content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
using System.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("WCF_DuplexClient")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("WCF_DuplexClient")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[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("ccfd2767-5fef-4f42-b4fd-0d42db2cd279")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.972973 | 84 | 0.746619 | [
"MIT"
] | Team-on/works | 0_homeworks/C#/9 wcf/0 primer/WCF_DuplexSvc1/WCF_DuplexClient/Properties/AssemblyInfo.cs | 1,408 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace TxtUploader.Account {
public partial class TwoFactorAuthenticationSignIn {
/// <summary>
/// sendcode control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.PlaceHolder sendcode;
/// <summary>
/// Providers control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.DropDownList Providers;
/// <summary>
/// ProviderSubmit control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button ProviderSubmit;
/// <summary>
/// verifycode control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.PlaceHolder verifycode;
/// <summary>
/// SelectedProvider control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.HiddenField SelectedProvider;
/// <summary>
/// ErrorMessage control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.PlaceHolder ErrorMessage;
/// <summary>
/// FailureText control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal FailureText;
/// <summary>
/// Code control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox Code;
/// <summary>
/// RememberBrowser control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox RememberBrowser;
/// <summary>
/// CodeSubmit control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button CodeSubmit;
}
}
| 35.141509 | 84 | 0.540134 | [
"MIT"
] | atanas-georgiev/TelerikAcademy | 16.ASP.NET-Web-Forms/Homeworks/07. ASP.NET-File-Upload/TxtUploader/Account/TwoFactorAuthenticationSignIn.aspx.designer.cs | 3,727 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace NJsonApi.Test.TestModel
{
public class ModelWithoutAnId
{
public DateTime SomeOtherProperty { get; set; }
}
} | 18.909091 | 55 | 0.716346 | [
"MIT"
] | AdamLJohnson/NJsonApiCore | test/NJsonApiCore.Test/TestModel/ModelWithoutAnId.cs | 210 | C# |
using RootSystem = System;
using System.Linq;
using System.Collections.Generic;
namespace Windows.Kinect
{
//
// Windows.Kinect.CameraSpacePoint
//
[RootSystem.Runtime.InteropServices.StructLayout(RootSystem.Runtime.InteropServices.LayoutKind.Sequential), System.Serializable]
public struct CameraSpacePoint
{
public float X { get; set; }
public float Y { get; set; }
public float Z { get; set; }
public override int GetHashCode()
{
return X.GetHashCode() ^ Y.GetHashCode() ^ Z.GetHashCode();
}
public override bool Equals(object obj)
{
if (!(obj is CameraSpacePoint))
{
return false;
}
return this.Equals((CameraSpacePoint)obj);
}
public bool Equals(CameraSpacePoint obj)
{
return X.Equals(obj.X) && Y.Equals(obj.Y) && Z.Equals(obj.Z);
}
public static bool operator ==(CameraSpacePoint a, CameraSpacePoint b)
{
return a.Equals(b);
}
public static bool operator !=(CameraSpacePoint a, CameraSpacePoint b)
{
return !(a.Equals(b));
}
}
}
| 25.5625 | 132 | 0.572127 | [
"MIT"
] | sugi-cho/KinectStudy-Unity | Assets/Standard Assets/Windows/Kinect/CameraSpacePoint.cs | 1,227 | C# |
// <copyright file="GameInfo.cs" company="Google Inc.">
// Copyright (C) 2015 Google Inc. 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.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
#if (UNITY_ANDROID || (UNITY_IPHONE && !NO_GPGS))
namespace GooglePlayGames {
///
/// This file is automatically generated DO NOT EDIT!
///
/// These are the constants defined in the Play Games Console for Game Services
/// Resources.
///
/// <summary>
/// File containing information about the game. This is automatically updated by running the
/// platform-appropriate setup commands in the Unity editor (which does a simple search / replace
/// on the IDs in the form "__ID__"). We can check whether any particular field has been updated
/// by checking whether it still retains its initial value - we prevent the constants from being
/// replaced in the aforementioned search/replace by stripping off the leading and trailing "__".
/// </summary>
public static class GameInfo {
private const string UnescapedApplicationId = "APP_ID";
private const string UnescapedIosClientId = "IOS_CLIENTID";
private const string UnescapedWebClientId = "WEB_CLIENTID";
private const string UnescapedNearbyServiceId = "NEARBY_SERVICE_ID";
private const string UnescapedRequireGooglePlus = "REQUIRE_GOOGLE_PLUS";
public const string ApplicationId = "149512578246"; // Filled in automatically
public const string IosClientId = ""; // Filled in automatically
public const string WebClientId = ""; // Filled in automatically
public const string NearbyConnectionServiceId = "";
public static bool RequireGooglePlus()
{
return "false" == "true";
}
public static bool ApplicationIdInitialized() {
return !string.IsNullOrEmpty(ApplicationId) && !ApplicationId.Equals(ToEscapedToken(UnescapedApplicationId));
}
public static bool IosClientIdInitialized() {
return !string.IsNullOrEmpty(IosClientId) && !IosClientId.Equals(ToEscapedToken(UnescapedIosClientId));
}
public static bool WebClientIdInitialized() {
return !string.IsNullOrEmpty(WebClientId) && !WebClientId.Equals(ToEscapedToken(UnescapedWebClientId));
}
public static bool NearbyConnectionsInitialized() {
return !string.IsNullOrEmpty(NearbyConnectionServiceId) &&
!NearbyConnectionServiceId.Equals(ToEscapedToken(UnescapedNearbyServiceId));
}
/// <summary>
/// Returns an escaped token (i.e. one flanked with "__") for the passed token
/// </summary>
/// <returns>The escaped token.</returns>
/// <param name="token">The Token</param>
private static string ToEscapedToken(string token) {
return string.Format("__{0}__", token);
}
}
}
#endif
| 44.153846 | 121 | 0.684959 | [
"Apache-2.0"
] | stemichael/BlocksDodger | Block-Dodge-Game/Assets/GooglePlayGames/GameInfo.cs | 3,444 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Rabbitual.Agents.WebServer")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Rabbitual.Agents.WebServer")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("5cc5de2a-1416-40c3-9789-92cd7bb2a2bd")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.513514 | 84 | 0.747368 | [
"MIT"
] | BjartN/Rabbitual | src/Rabbitual.Agents.WebServer/Properties/AssemblyInfo.cs | 1,428 | C# |
// Copyright (c) 2020 Sergio Aquilini
// This code is licensed under MIT license (see LICENSE file for details)
using System;
using Silverback.Diagnostics;
using Silverback.Messaging.Broker.Behaviors;
namespace Silverback.Messaging.Broker
{
/// <inheritdoc cref="Producer" />
public abstract class Producer<TBroker, TEndpoint> : Producer
where TBroker : IBroker
where TEndpoint : IProducerEndpoint
{
/// <summary>
/// Initializes a new instance of the <see cref="Producer{TBroker,TEndpoint}" /> class.
/// </summary>
/// <param name="broker">
/// The <see cref="IBroker" /> that instantiated this producer.
/// </param>
/// <param name="endpoint">
/// The endpoint to produce to.
/// </param>
/// <param name="behaviorsProvider">
/// The <see cref="IBrokerBehaviorsProvider{TBehavior}" />.
/// </param>
/// <param name="serviceProvider">
/// The <see cref="IServiceProvider" /> to be used to resolve the needed services.
/// </param>
/// <param name="logger">
/// The <see cref="ISilverbackIntegrationLogger" />.
/// </param>
protected Producer(
TBroker broker,
TEndpoint endpoint,
IBrokerBehaviorsProvider<IProducerBehavior> behaviorsProvider,
IServiceProvider serviceProvider,
ISilverbackIntegrationLogger<Producer> logger)
: base(broker, endpoint, behaviorsProvider, serviceProvider, logger)
{
}
/// <summary>
/// Gets the <typeparamref name="TBroker" /> that owns this producer.
/// </summary>
public new TBroker Broker => (TBroker)base.Broker;
/// <summary>
/// Gets the <typeparamref name="TEndpoint" /> representing the endpoint that is being produced to.
/// </summary>
public new TEndpoint Endpoint => (TEndpoint)base.Endpoint;
}
}
| 37.296296 | 111 | 0.595829 | [
"MIT"
] | mjeanrichard/silverback | src/Silverback.Integration/Messaging/Broker/Producer`2.cs | 2,016 | C# |
using System.Collections.Generic;
using System.Linq;
using Esprima.Ast;
using Jint.Native;
using Jint.Runtime.Environments;
namespace Jint.Runtime.Debugger
{
internal class DebugHandler
{
private readonly Stack<string> _debugCallStack;
private StepMode _stepMode;
private int _callBackStepOverDepth;
private readonly Engine _engine;
public DebugHandler(Engine engine)
{
_engine = engine;
_debugCallStack = new Stack<string>();
_stepMode = StepMode.Into;
}
internal void PopDebugCallStack()
{
if (_debugCallStack.Count > 0)
{
_debugCallStack.Pop();
}
if (_stepMode == StepMode.Out && _debugCallStack.Count < _callBackStepOverDepth)
{
_callBackStepOverDepth = _debugCallStack.Count;
_stepMode = StepMode.Into;
}
else if (_stepMode == StepMode.Over && _debugCallStack.Count == _callBackStepOverDepth)
{
_callBackStepOverDepth = _debugCallStack.Count;
_stepMode = StepMode.Into;
}
}
internal void AddToDebugCallStack(CallExpression callExpression)
{
var identifier = callExpression.Callee as Esprima.Ast.Identifier;
if (identifier != null)
{
var stack = identifier.Name + "(";
var paramStrings = new System.Collections.Generic.List<string>();
foreach (var argument in callExpression.Arguments)
{
if (argument != null)
{
var argIdentifier = argument as Esprima.Ast.Identifier;
paramStrings.Add(argIdentifier != null ? argIdentifier.Name : "null");
}
else
{
paramStrings.Add("null");
}
}
stack += string.Join(", ", paramStrings);
stack += ")";
_debugCallStack.Push(stack);
}
}
internal void OnStep(Statement statement)
{
var old = _stepMode;
if (statement == null)
{
return;
}
BreakPoint breakpoint = _engine.BreakPoints.FirstOrDefault(breakPoint => BpTest(statement, breakPoint));
bool breakpointFound = false;
if (breakpoint != null)
{
DebugInformation info = CreateDebugInformation(statement);
var result = _engine.InvokeBreakEvent(info);
if (result.HasValue)
{
_stepMode = result.Value;
breakpointFound = true;
}
}
if (breakpointFound == false && _stepMode == StepMode.Into)
{
DebugInformation info = CreateDebugInformation(statement);
var result = _engine.InvokeStepEvent(info);
if (result.HasValue)
{
_stepMode = result.Value;
}
}
if (old == StepMode.Into && _stepMode == StepMode.Out)
{
_callBackStepOverDepth = _debugCallStack.Count;
}
else if (old == StepMode.Into && _stepMode == StepMode.Over)
{
var expressionStatement = statement as ExpressionStatement;
if (expressionStatement != null && expressionStatement.Expression is CallExpression)
{
_callBackStepOverDepth = _debugCallStack.Count;
}
else
{
_stepMode = StepMode.Into;
}
}
}
private bool BpTest(Statement statement, BreakPoint breakpoint)
{
bool afterStart, beforeEnd;
afterStart = (breakpoint.Line == statement.Location.Start.Line &&
breakpoint.Char >= statement.Location.Start.Column);
if (!afterStart)
{
return false;
}
beforeEnd = breakpoint.Line < statement.Location.End.Line
|| (breakpoint.Line == statement.Location.End.Line &&
breakpoint.Char <= statement.Location.End.Column);
if (!beforeEnd)
{
return false;
}
if (!string.IsNullOrEmpty(breakpoint.Condition))
{
var completionValue = _engine.Execute(breakpoint.Condition).GetCompletionValue();
return ((JsBoolean) completionValue)._value;
}
return true;
}
private DebugInformation CreateDebugInformation(Statement statement)
{
var info = new DebugInformation { CurrentStatement = statement, CallStack = _debugCallStack };
if (_engine.ExecutionContext.LexicalEnvironment != null)
{
var lexicalEnvironment = _engine.ExecutionContext.LexicalEnvironment;
info.Locals = GetLocalVariables(lexicalEnvironment);
info.Globals = GetGlobalVariables(lexicalEnvironment);
}
return info;
}
private static Dictionary<string, JsValue> GetLocalVariables(LexicalEnvironment lex)
{
Dictionary<string, JsValue> locals = new Dictionary<string, JsValue>();
if (!ReferenceEquals(lex?._record, null))
{
AddRecordsFromEnvironment(lex, locals);
}
return locals;
}
private static Dictionary<string, JsValue> GetGlobalVariables(LexicalEnvironment lex)
{
Dictionary<string, JsValue> globals = new Dictionary<string, JsValue>();
LexicalEnvironment tempLex = lex;
while (!ReferenceEquals(tempLex?._record, null))
{
AddRecordsFromEnvironment(tempLex, globals);
tempLex = tempLex._outer;
}
return globals;
}
private static void AddRecordsFromEnvironment(LexicalEnvironment lex, Dictionary<string, JsValue> locals)
{
var bindings = lex._record.GetAllBindingNames();
foreach (var binding in bindings)
{
if (locals.ContainsKey(binding) == false)
{
var jsValue = lex._record.GetBindingValue(binding, false);
if (jsValue.TryCast<ICallable>() == null)
{
locals.Add(binding, jsValue);
}
}
}
}
}
}
| 33.990099 | 116 | 0.51908 | [
"BSD-2-Clause"
] | ahmetkakici/jint | Jint/Runtime/Debugger/DebugHandler.cs | 6,868 | C# |
#Thu Mar 18 16:30:47 CET 2021
lib/com.ibm.ws.javaee.version_1.0.49.jar=aa20b567971d71b754b3f066e361d4d7
lib/com.ibm.ws.javaee.platform.v7_1.0.49.jar=fb81c6638ff004e1ada5832de4ea4a64
lib/features/com.ibm.websphere.appserver.javaeePlatform-7.0.mf=416dd5eb7c3e159006b7206a7ab0b7fc
lib/com.ibm.ws.javaee.platform.defaultresource_1.0.49.jar=6ea65347bed417cf89cc946a2c007413
| 61.5 | 95 | 0.859079 | [
"EPL-1.0"
] | angeloemme80/open-liberty | target/liberty/wlp/lib/features/checksums/com.ibm.websphere.appserver.javaeePlatform-7.0.cs | 369 | C# |
// Generated class v2.14.0.0, can be modified
namespace NHtmlUnit.Svg
{
public partial class SvgFontFace
{
}
}
| 12.090909 | 46 | 0.62406 | [
"Apache-2.0"
] | HtmlUnit/NHtmlUnit | app/NHtmlUnit/NonGenerated/Svg/SvgFontFace.cs | 133 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("02.WormIpsum")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("02.WormIpsum")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("33dcbd5d-30b4-406e-bc64-2bae1a18adaf")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.621622 | 84 | 0.746408 | [
"MIT"
] | DimchoLakov/ProgrammingFundamentalsMay2017 | Exams/30April2017/30April2017/02.WormIpsum/Properties/AssemblyInfo.cs | 1,395 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using essentialMix.Extensions;
using JetBrains.Annotations;
namespace essentialMix.Collections;
[Serializable]
public class WordList : List<ushort>
{
public WordList()
{
}
public WordList(int capacity)
: base(capacity)
{
}
public WordList([NotNull] IEnumerable<ushort> collection)
: base(collection)
{
}
public WordList([NotNull] IEnumerable<byte> enumerable)
{
AddRange(enumerable);
}
public WordList([NotNull] IEnumerable<char> enumerable)
{
AddRange(enumerable);
}
[NotNull]
public static explicit operator WordList([NotNull] byte[] value) { return new WordList(value); }
[NotNull]
public static explicit operator byte[] ([NotNull] WordList value) { return value.ToByteArray(); }
[NotNull]
public byte[] ToByteArray()
{
if (Count == 0) return Array.Empty<byte>();
byte[] bytes = new byte[Count * Constants.USHORT_SIZE];
CopyTo(bytes);
return bytes;
}
public void AddRange([NotNull] IEnumerable<byte> enumerable)
{
int c = 0;
byte[] bytes = new byte[Constants.USHORT_SIZE];
foreach (byte b in enumerable)
{
bytes[c % Constants.USHORT_SIZE] = b;
c++;
if (c % Constants.USHORT_SIZE == 0) Add(BitConverter.ToUInt16(bytes, 0));
}
if (c == 0 || c % Constants.USHORT_SIZE == 0) return;
for (int i = c % Constants.USHORT_SIZE; i < Constants.USHORT_SIZE; i++)
bytes[i] = 0;
Add(BitConverter.ToUInt16(bytes, 0));
}
public void AddRange([NotNull] IEnumerable<char> enumerable)
{
foreach (char c in enumerable)
Add(Convert.ToUInt16(c));
}
public void CopyTo([NotNull] byte[] array) { CopyTo(0, array, 0, Count); }
public void CopyTo([NotNull] byte[] array, int arrayIndex) { CopyTo(0, array, arrayIndex, Count); }
public void CopyTo(int index, [NotNull] byte[] array, int arrayIndex, int count)
{
if (array == null) throw new ArgumentNullException(nameof(array));
if (count < 0) count = Count;
int total = count * Constants.USHORT_SIZE;
total.ValidateRange(index, ref count);
total.ValidateRange(arrayIndex, ref count);
if (count == 0 || total == 0) return;
int lastIndex = index + count - 1;
for (int i = index, j = 0; i <= lastIndex; i++, j += Constants.USHORT_SIZE)
Buffer.BlockCopy(BitConverter.GetBytes(this[i]), 0, array, j, Constants.USHORT_SIZE);
}
[NotNull]
public static WordList From<T>([NotNull] IEnumerable<T> enumerable)
where T : struct, IComparable, IComparable<T>, IEquatable<T>, IConvertible
{
WordList list = new WordList();
list.AddRange(enumerable.Select(value => Convert.ToUInt16(value)));
return list;
}
}
public static class WordListExtension
{
[NotNull]
[MethodImpl(MethodImplOptions.ForwardRef | MethodImplOptions.AggressiveInlining)]
public static byte[] AsBytes([NotNull] this WordList thisValue) { return (byte[])thisValue; }
[NotNull]
[MethodImpl(MethodImplOptions.ForwardRef | MethodImplOptions.AggressiveInlining)]
public static WordList AsWordList([NotNull] this byte[] thisValue) { return (WordList)thisValue; }
} | 26.655172 | 100 | 0.709897 | [
"MIT"
] | asm2025/essentialMix | Standard/essentialMix.Collections/WordList.cs | 3,092 | C# |
using System;
using FluentValidation;
using Moq;
using OpenRasta.DI;
namespace JE.ApiValidation.Tests.RequestValidity.OpenRasta
{
public abstract class WhenValidatorsAreFound : WhenFluentValidationOperationInterceptorRuns
{
protected override void GivenResolverStubs()
{
var dr = GetMockFor<IDependencyResolver>();
dr.Setup(x => x.HasDependency(It.Is<Type>(y => y.IsAssignableFrom(typeof(IValidator<Request>)))))
.Returns(true);
dr.Setup(x => x.Resolve(It.Is<Type>(y => y.IsAssignableFrom(typeof(IValidator<Request>)))))
.Returns(new RulesForRequest());
}
}
}
| 33.3 | 109 | 0.659159 | [
"Apache-2.0"
] | justeat/JE.ApiValidation | src/JE.ApiValidation.Tests/RequestValidity/OpenRasta/WhenValidatorsAreFound.cs | 668 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Facturacion.Modelo
{
class Producto
{
private string id_pro;
private string id_cat;
private string nom_pro;
private double pre_com;
private int can_pro;
private double por_gan;
private double pre_gan;
private string iva_sn;
private double pre_ven;
private string fec_ing;
private List<Producto> listaProductos = new List<Producto>();
public string idpro
{
get { return id_pro; }
set { id_pro = value; }
}
public string idcat
{
get { return id_cat; }
set { id_cat = value; }
}
public string nompro
{
get { return nom_pro; }
set { nom_pro = value; }
}
public double precom
{
get { return pre_com; }
set { pre_com = value; }
}
public int canpro
{
get { return can_pro; }
set { can_pro = value; }
}
public double porgan
{
get { return por_gan; }
set { por_gan = value; }
}
public double pregan
{
get { return pre_gan; }
set { pre_gan = value; }
}
public string ivasn
{
get { return iva_sn; }
set { iva_sn = value; }
}
public double preven
{
get { return pre_ven; }
set { pre_ven = value; }
}
public string fecing
{
get { return fec_ing; }
set { fec_ing = value; }
}
public List<Producto> ListaProductos
{
get { return listaProductos; }
set { listaProductos = value; }
}
private string est_pro;
public string estpro
{
get { return est_pro; }
set { est_pro = value; }
}
}
}
| 24.678161 | 70 | 0.454122 | [
"Apache-2.0"
] | darkangel100/sanchez | Facturacion/Modelo/Producto.cs | 2,149 | C# |
using UnityEngine;
public class ReadOnlyAttribute : PropertyAttribute { } | 24.666667 | 54 | 0.824324 | [
"Apache-2.0"
] | 10xcr4zy01/open-project-1 | UOP1_Project/Assets/Scripts/EditorTools/Attributes/ReadOnlyAttribute/ReadOnlyAttribute.cs | 74 | C# |
namespace Morph.Input.Controllers.Features.Gestures
{
/// <summary>
/// Morph controller gesture type
/// </summary>
public enum MorphControllerGestureType
{
/// <summary>
/// Swipe
/// </summary>
Swipe
}
}
| 18.857143 | 52 | 0.55303 | [
"MIT"
] | RLefrancoise/Morph | Assets/Morph/Input/Controllers/Features/Gestures/MorphControllerGestureType.cs | 266 | C# |
// <copyright file="EnumerableExtensions.cs" company="Erratic Motion Ltd">
// Copyright (c) Erratic Motion Ltd. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// </copyright>
namespace ErraticMotion
{
using System;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// Contains extension methods for the <see cref="IEnumerable{T}"/> interface.
/// </summary>
public static class EnumerableExtensions
{
/// <summary>
/// Performs an action for each element in a sequence.
/// </summary>
/// <typeparam name="T">The type of each element in the sequence.</typeparam>
/// <param name="source">An IEnumerable to walk.</param>
/// <param name="action">The action to perform.</param>
/// <exception cref="ArgumentNullException"><c>source</c> is null.</exception>
public static void ForAll<T>(this IEnumerable<T> source, Action<T> action)
{
if (source == null)
{
throw new ArgumentNullException("source", "source is null.");
}
if (action == null)
{
throw new ArgumentNullException("action", "action is null.");
}
foreach (var item in source)
{
action(item);
}
}
/// <summary>
/// Reverses the collection.
/// </summary>
/// <typeparam name="T">The type of each element in the sequence.</typeparam>
/// <param name="source">An IEnumerable to walk.</param>
/// <returns>An enumerable collection.</returns>
/// <exception cref="ArgumentNullException"><c>source</c> is null.</exception>
public static IEnumerable<T> Reverse<T>(this IEnumerable<T> source)
{
if (source == null)
{
throw new ArgumentNullException("source", "source is null.");
}
var enumerable = source as T[] ?? source.ToArray();
for (var i = enumerable.Count() - 1; i >= 0; i--)
{
yield return enumerable.ElementAt(i);
}
}
/// <summary>
/// Converts the collection.
/// </summary>
/// <typeparam name="T1">The type of each input element in the sequence.</typeparam>
/// <typeparam name="T2">The type of each output element in the sequence.</typeparam>
/// <param name="source">An IEnumerable to walk.</param>
/// <param name="action">The conversion action.</param>
/// <returns>An enumerable collection.</returns>
/// <exception cref="ArgumentNullException"><c>source</c> is null.</exception>
public static IEnumerable<T2> Convert<T1, T2>(this IEnumerable<T1> source, Func<T1, T2> action)
{
if (source == null)
{
throw new ArgumentNullException("source", "source is null.");
}
if (action == null)
{
throw new ArgumentNullException("action", "action is null.");
}
return source.Select(action);
}
/// <summary>
/// Performs an action on each element in a sequence using the element's index.
/// </summary>
/// <typeparam name="T">The type of each element in the sequence.</typeparam>
/// <param name="items">An IEnumerable to walk.</param>
/// <param name="action">The action to perform.</param>
/// <exception cref="ArgumentNullException"><c>source</c> is null.</exception>
public static void ForIndex<T>(this IEnumerable<T> items, Action<int, T> action)
{
if (items == null)
{
throw new ArgumentNullException("items");
}
if (action == null)
{
throw new ArgumentNullException("action");
}
var index = 0;
foreach (var item in items)
{
action(index, item);
index++;
}
}
/// <summary>
/// Takes from the end of the collection.
/// </summary>
/// <typeparam name="T">The type of each element in the sequence.</typeparam>
/// <param name="items">An IEnumerable to walk.</param>
/// <param name="count">The number of elements to take.</param>
/// <returns>An enumerable collection.</returns>
/// <exception cref="ArgumentNullException"><c>source</c> is null.</exception>
public static IEnumerable<T> TakeFromEnd<T>(this IEnumerable<T> items, int count)
{
if (items == null)
{
throw new ArgumentNullException("items");
}
var enumerable = items as T[] ?? items.ToArray();
if (enumerable.Count() <= count)
{
foreach (var t in enumerable)
{
yield return t;
}
}
else
{
var c = enumerable.Count() - count;
for (var i = 0; i < count; i++)
{
yield return enumerable.ElementAt(c);
c++;
}
}
}
/// <summary>
/// <para>
/// Breaks apart an input sequence into chunks of the given size.
/// </para>
/// <para>
/// If the sequence does not contain enough elements to break evenly,
/// the last chunk will be less than the given size.
/// </para>
/// </summary>
/// <typeparam name="TSource">The type of the source sequence.</typeparam>
/// <param name="source">The source sequence.</param>
/// <param name="chunkSize">The size of each chunk.</param>
/// <returns>Chunks of data as sequences of lists.</returns>
/// <exception cref="ArgumentNullException"><c>source</c> is null.</exception>
/// <exception cref="ArgumentException"><c>chunkSize</c> must be greater than zero.</exception>
public static IEnumerable<IList<TSource>> Chunk<TSource>(this IEnumerable<TSource> source, int chunkSize)
{
if (source == null)
{
throw new ArgumentNullException("source", @"source is null.");
}
if (chunkSize < 1)
{
throw new ArgumentException(@"chunk size must be greater than 0.", "chunkSize");
}
return ChunkHelper(source, enumerator => BreakOffChunk(enumerator, chunkSize));
}
private static IEnumerable<IList<TSource>> ChunkHelper<TSource>(IEnumerable<TSource> source, Func<IEnumerator<TSource>, IEnumerable<TSource>> chunker)
{
using (var enumerator = source.GetEnumerator())
{
var currentChunk = chunker(enumerator).ToList();
while (currentChunk.Any())
{
yield return currentChunk;
currentChunk = chunker(enumerator).ToList();
}
}
}
private static IEnumerable<T> BreakOffChunk<T>(IEnumerator<T> enumerator, int chunkSize)
{
for (var i = 0; i < chunkSize && enumerator.MoveNext(); i++)
{
yield return enumerator.Current;
}
}
}
} | 37.535 | 158 | 0.532703 | [
"MIT"
] | erraticmotion/gherkin-net | Gherkin.Net/Gherkin.Tests/EnumerableExtensions.cs | 7,509 | C# |
using System;
namespace TrainTheTrainers
{
internal class Program
{
static void Main(string[] args)
{
int jurysCount = int.Parse(Console.ReadLine());
double finalAverageGrade = 0;
int counter = 0;
string presentationsName = Console.ReadLine();
while (presentationsName != "Finish")
{
double averageGrade = 0;
for (int jury = 1; jury <= jurysCount; jury++)
{
double grade = double.Parse(Console.ReadLine());
counter++;
averageGrade += grade;
finalAverageGrade += grade;
}
Console.WriteLine($"{presentationsName} - {(averageGrade / jurysCount):F2}.");
presentationsName = Console.ReadLine();
}
Console.WriteLine($"Student's final assessment is {(finalAverageGrade / counter):F2}.");
}
}
}
| 28.628571 | 100 | 0.502994 | [
"MIT"
] | Ivanazzz/SoftUni-Software-Engineering | CSharp-Programming-Basics/NestedLoops/lab/TrainTheTrainers/Program.cs | 1,004 | C# |
namespace StudentSystemServices.Models
{
using StudentSystem.Models;
using System;
using System.ComponentModel.DataAnnotations;
using System.Linq.Expressions;
public class StudentTemplate
{
public static Expression<Func<Student, StudentTemplate>> FromStudent
{
get
{
return a => new StudentTemplate
{
FirstName = a.FirstName,
LastName = a.LastName,
Level = a.Level
};
}
}
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
public int Level { get; set; }
}
} | 24 | 76 | 0.518817 | [
"Apache-2.0"
] | iliantrifonov/TelerikAcademy | Web services and Cloud/02.AspNetWebApi/01.StudentSystemServices/StudentSystemServices/Models/StudentTemplate.cs | 746 | C# |
using System;
namespace Quizzer
{
class Card
{
public string Question { get; set; }
public string Answer;
public string Type;
public string[] Options { get; private set; }
public int ID;
public Card()
{
Options = new string[4];
Question = "";
Answer = "";
Type = "flashcard";
ID = 0;
}
public Card(string ques, string ans)
{
Options = new string[4];
Question = ques;
Answer = ans;
Type = "flashcard";
ID = 0;
}
public void AddOption(int index, string option)
{
if (index > Options.Length)
{
throw new IndexOutOfRangeException();
}
Options[index] = option;
}
public bool IsCorrect(string ans)
{
return ans == this.Answer;
}
}
}
| 20.787234 | 55 | 0.445241 | [
"BSD-3-Clause"
] | lfkeitel/cs358-A5-Quizzer | Quizzer/Card.cs | 977 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using Advanced_Combat_Tracker;
namespace ACT.SpecialSpellTimer
{
public class AssemblyResolver
{
#region Singleton
private static AssemblyResolver instance;
public static AssemblyResolver Instance =>
instance ?? (instance = new AssemblyResolver());
public static void Free()
{
instance?.Dispose();
instance = null;
}
#endregion Singleton
private IActPluginV1 plugin;
public List<string> Directories { get; private set; } = new List<string>();
public void Initialize(
IActPluginV1 plugin)
{
this.plugin = plugin;
this.Directories.Add(Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
@"Advanced Combat Tracker\Plugins"));
AppDomain.CurrentDomain.AssemblyResolve -= this.CustomAssemblyResolve;
AppDomain.CurrentDomain.AssemblyResolve += this.CustomAssemblyResolve;
}
public void Dispose()
{
AppDomain.CurrentDomain.AssemblyResolve -= this.CustomAssemblyResolve;
this.plugin = null;
}
private Assembly CustomAssemblyResolve(object sender, ResolveEventArgs e)
{
Assembly tryLoadAssembly(
string directory,
string extension)
{
var asm = new AssemblyName(e.Name);
var asmPath = Path.Combine(directory, asm.Name + extension);
if (File.Exists(asmPath))
{
return Assembly.LoadFrom(asmPath);
}
return null;
}
var pluginDirectory = ActGlobals.oFormActMain?.PluginGetSelfData(this.plugin)?.pluginFile.DirectoryName;
if (!string.IsNullOrEmpty(pluginDirectory))
{
if (!this.Directories.Any(x => x == pluginDirectory))
{
this.Directories.Add(pluginDirectory);
this.Directories.Add(Path.Combine(pluginDirectory, "references"));
}
}
// Directories プロパティで指定されたディレクトリを基準にアセンブリを検索する
foreach (var directory in this.Directories)
{
var asm = tryLoadAssembly(directory, ".dll");
if (asm != null)
{
return asm;
}
}
return null;
}
}
}
| 29.355556 | 116 | 0.555261 | [
"BSD-3-Clause"
] | MasteRyuuuu/ACT.Hojoring | source/ACT.SpecialSpellTimer/ACT.SpecialSpellTimer/AssemblyResolver.cs | 2,704 | C# |
namespace OpenWeatherMap.Standard
{
public class Clouds
{
public int all { get; set; }
}
}
| 12.555556 | 36 | 0.584071 | [
"MIT"
] | jeuxjeux20/OpenWeatherMap.Standard | OpenWeatherMap.Standard/Clouds.cs | 115 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System.Collections.Generic;
using Aliyun.Acs.Core;
namespace Aliyun.Acs.Smartag.Model.V20180313
{
public class CreateSagStaticRouteResponse : AcsResponse
{
private string requestId;
public string RequestId
{
get
{
return requestId;
}
set
{
requestId = value;
}
}
}
}
| 26.534884 | 63 | 0.719544 | [
"Apache-2.0"
] | AxiosCros/aliyun-openapi-net-sdk | aliyun-net-sdk-smartag/Smartag/Model/V20180313/CreateSagStaticRouteResponse.cs | 1,141 | C# |
using System;
using System.Collections;
using System.IO;
using My2C2P.Org.BouncyCastle.Asn1;
using My2C2P.Org.BouncyCastle.Asn1.Ocsp;
using My2C2P.Org.BouncyCastle.Asn1.X509;
using My2C2P.Org.BouncyCastle.Crypto;
using My2C2P.Org.BouncyCastle.Security;
using My2C2P.Org.BouncyCastle.Security.Certificates;
using My2C2P.Org.BouncyCastle.Utilities;
using My2C2P.Org.BouncyCastle.X509;
using My2C2P.Org.BouncyCastle.X509.Store;
namespace My2C2P.Org.BouncyCastle.Ocsp
{
/// <remarks>
/// <code>
/// BasicOcspResponse ::= SEQUENCE {
/// tbsResponseData ResponseData,
/// signatureAlgorithm AlgorithmIdentifier,
/// signature BIT STRING,
/// certs [0] EXPLICIT SEQUENCE OF Certificate OPTIONAL
/// }
/// </code>
/// </remarks>
public class BasicOcspResp
: X509ExtensionBase
{
private readonly BasicOcspResponse resp;
private readonly ResponseData data;
// private readonly X509Certificate[] chain;
public BasicOcspResp(
BasicOcspResponse resp)
{
this.resp = resp;
this.data = resp.TbsResponseData;
}
/// <returns>The DER encoding of the tbsResponseData field.</returns>
/// <exception cref="OcspException">In the event of an encoding error.</exception>
public byte[] GetTbsResponseData()
{
try
{
return data.GetDerEncoded();
}
catch (IOException e)
{
throw new OcspException("problem encoding tbsResponseData", e);
}
}
public int Version
{
get { return data.Version.Value.IntValue + 1; }
}
public RespID ResponderId
{
get { return new RespID(data.ResponderID); }
}
public DateTime ProducedAt
{
get { return data.ProducedAt.ToDateTime(); }
}
public SingleResp[] Responses
{
get
{
Asn1Sequence s = data.Responses;
SingleResp[] rs = new SingleResp[s.Count];
for (int i = 0; i != rs.Length; i++)
{
rs[i] = new SingleResp(SingleResponse.GetInstance(s[i]));
}
return rs;
}
}
public X509Extensions ResponseExtensions
{
get { return data.ResponseExtensions; }
}
protected override X509Extensions GetX509Extensions()
{
return ResponseExtensions;
}
public string SignatureAlgName
{
get { return OcspUtilities.GetAlgorithmName(resp.SignatureAlgorithm.Algorithm); }
}
public string SignatureAlgOid
{
get { return resp.SignatureAlgorithm.Algorithm.Id; }
}
[Obsolete("RespData class is no longer required as all functionality is available on this class")]
public RespData GetResponseData()
{
return new RespData(data);
}
public byte[] GetSignature()
{
return resp.GetSignatureOctets();
}
private IList GetCertList()
{
// load the certificates and revocation lists if we have any
IList certs = Platform.CreateArrayList();
Asn1Sequence s = resp.Certs;
if (s != null)
{
foreach (Asn1Encodable ae in s)
{
try
{
certs.Add(new X509CertificateParser().ReadCertificate(ae.GetEncoded()));
}
catch (IOException ex)
{
throw new OcspException("can't re-encode certificate!", ex);
}
catch (CertificateException ex)
{
throw new OcspException("can't re-encode certificate!", ex);
}
}
}
return certs;
}
public X509Certificate[] GetCerts()
{
IList certs = GetCertList();
X509Certificate[] result = new X509Certificate[certs.Count];
for (int i = 0; i < certs.Count; ++i)
{
result[i] = (X509Certificate)certs[i];
}
return result;
}
/// <returns>The certificates, if any, associated with the response.</returns>
/// <exception cref="OcspException">In the event of an encoding error.</exception>
public IX509Store GetCertificates(
string type)
{
try
{
return X509StoreFactory.Create(
"Certificate/" + type,
new X509CollectionStoreParameters(this.GetCertList()));
}
catch (Exception e)
{
throw new OcspException("can't setup the CertStore", e);
}
}
/// <summary>
/// Verify the signature against the tbsResponseData object we contain.
/// </summary>
public bool Verify(
AsymmetricKeyParameter publicKey)
{
try
{
ISigner signature = SignerUtilities.GetSigner(this.SignatureAlgName);
signature.Init(false, publicKey);
byte[] bs = data.GetDerEncoded();
signature.BlockUpdate(bs, 0, bs.Length);
return signature.VerifySignature(this.GetSignature());
}
catch (Exception e)
{
throw new OcspException("exception processing sig: " + e, e);
}
}
/// <returns>The ASN.1 encoded representation of this object.</returns>
public byte[] GetEncoded()
{
return resp.GetEncoded();
}
public override bool Equals(
object obj)
{
if (obj == this)
return true;
BasicOcspResp other = obj as BasicOcspResp;
if (other == null)
return false;
return resp.Equals(other.resp);
}
public override int GetHashCode()
{
return resp.GetHashCode();
}
}
}
| 22.511312 | 100 | 0.665729 | [
"MIT"
] | 2C2P/My2C2PPKCS7 | My2C2PPKCS7/ocsp/BasicOCSPResp.cs | 4,975 | C# |
using Business.Interfaces;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authorization.Infrastructure;
namespace AppWeb.AuthorizationHandler;
public class CustomAuthorizationHandler : IAuthorizationHandler
{
private readonly IClaimsService _claimsService;
private readonly IAccountService _accountService;
public CustomAuthorizationHandler(
IClaimsService claimsService,
IAccountService accountService
)
{
_claimsService = claimsService;
_accountService = accountService;
}
public Task HandleAsync(AuthorizationHandlerContext context)
{
var roles = new List<string>()
{
"User",
"Admin"
};
var userClaims = _claimsService.GetClaims(context);
var user = _accountService.GetAuthorizedUser(context, out var error, CancellationToken.None);
if (user != null)
{
if (user.Role.Name == userClaims.Role && roles.Contains(user.Role.Name))
{
context.Succeed(new AssertionRequirement(handlerContext => handlerContext.HasSucceeded));
return Task.CompletedTask;
}
}
context.Fail();
return Task.CompletedTask;
}
} | 28.711111 | 105 | 0.649381 | [
"MIT"
] | KnJbMfLAgdkwZL/iLearningSolution | AppWeb/AuthorizationHandler/CustomAuthorizationHandler.cs | 1,292 | C# |
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Calabonga.Catalog.Core.Exceptions;
namespace Calabonga.Catalog.Web.Infrastructure.Helpers
{
/// <summary>
/// System utilities
/// </summary>
public static class Utilities
{
/// <summary>
/// Compute Hash
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
public static byte[] ComputeHash(string filePath)
{
var runCount = 1;
while (runCount < 4)
{
try
{
if (!File.Exists(filePath))
{
throw new FileNotFoundException();
}
using (var fs = File.OpenRead(filePath))
{
return SHA1.Create().ComputeHash(fs);
}
}
catch (IOException ex)
{
if (runCount == 3 || ex.HResult != -2147024864)
{
throw;
}
else
{
Thread.Sleep(TimeSpan.FromSeconds(Math.Pow(2, runCount)));
runCount++;
}
}
}
return new byte[20];
}
/// <summary>
/// Return file content
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
public static async Task<string> GetFileContent(string filePath)
{
try
{
if (!File.Exists(filePath))
{
throw new FileNotFoundException();
}
return await File.ReadAllTextAsync(filePath);
}
catch
{
return null;
}
}
/// <summary>
/// Remove file from directory (physical deleting)
/// </summary>
/// <param name="filePath"></param>
public static void DeleteFile(string filePath)
{
try
{
if (!File.Exists(filePath))
{
throw new FileNotFoundException();
}
File.Delete(filePath);
}
catch
{
// ignored
}
}
/// <summary>
/// Save content to the text file
/// </summary>
/// <param name="filePath"></param>
/// <param name="content"></param>
/// <returns></returns>
public static async Task SetFileContent(string filePath, string content)
{
try
{
var folder = Path.GetDirectoryName(filePath);
if (!Directory.Exists(folder))
{
Directory.CreateDirectory(folder);
}
if (File.Exists(filePath))
{
throw new MicroserviceFileAlreadyExistsException();
}
using (var fs = File.Create(filePath))
{
var info = new UTF8Encoding(true).GetBytes(content);
await fs.WriteAsync(info, 0, info.Length);
}
}
catch
{
// ignored
}
}
/// <summary>
/// Generate ETag for content bytes
/// </summary>
/// <param name="key"></param>
/// <param name="contentBytes"></param>
/// <returns></returns>
public static string GetETag(string key, byte[] contentBytes)
{
var keyBytes = Encoding.UTF8.GetBytes(key);
var combinedBytes = Combine(keyBytes, contentBytes);
return GenerateETag(combinedBytes);
}
/// <summary>
/// Returns Working folder path
/// </summary>
/// <returns></returns>
public static string GetWorkingFolder()
{
var location = System.Reflection.Assembly.GetEntryAssembly().Location;
return Path.GetDirectoryName(location);
}
private static string GenerateETag(byte[] data)
{
using (var md5 = MD5.Create())
{
var hash = md5.ComputeHash(data);
var hex = BitConverter.ToString(hash);
return hex.Replace("-", "");
}
}
private static byte[] Combine(byte[] a, byte[] b)
{
var c = new byte[a.Length + b.Length];
Buffer.BlockCopy(a, 0, c, 0, a.Length);
Buffer.BlockCopy(b, 0, c, a.Length, b.Length);
return c;
}
}
}
| 28.252874 | 82 | 0.439788 | [
"MIT"
] | Calabonga/Calabonga.Catalog | Source/Calabonga.Catalog/Calabonga.Catalog.Web/Infrastructure/Helpers/Utilites.cs | 4,918 | 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.
/*============================================================
**
**
**
** Purpose: Managed ACL wrapper for files & directories.
**
**
===========================================================*/
using System.IO;
namespace System.Security.AccessControl
{
public sealed class DirectorySecurity : FileSystemSecurity
{
#region Constructors
public DirectorySecurity()
: base(true)
{
}
public DirectorySecurity(string name, AccessControlSections includeSections)
: base(true, name, includeSections, true)
{
string fullPath = Path.GetFullPath(name);
}
#endregion
}
}
| 24.527778 | 84 | 0.556059 | [
"MIT"
] | CryptoPro/corefx | src/System.IO.FileSystem.AccessControl/src/System/Security/AccessControl/DirectorySecurity.cs | 883 | C# |
using System;
using System.Collections.Generic;
using System.IO;
namespace LibCompressionEstimator
{
interface IEstimatorRunner
{
IEnumerable<EstimationResult> Estimate(IEnumerable<DirectoryInfo> directories, Func<DirectoryInfo, EstimationResult> estimateFunc);
}
}
| 24.916667 | 140 | 0.752508 | [
"MIT"
] | jborza/compression-estimator | LibCompressionEstimator/IEstimatorRunner.cs | 301 | C# |
using System.Management.Automation;
using Microsoft.SharePoint.Client;
using OfficeDevPnP.PowerShell.CmdletHelpAttributes;
namespace OfficeDevPnP.PowerShell.Commands.PageLayout
{
[Cmdlet(VerbsCommon.Add, "SPOPublishingPageLayout")]
[CmdletHelp("Adds a publishing page layout",
Category = CmdletHelpCategory.Publishing)]
public class AddPublishingPageLayout : SPOWebCmdlet
{
[Parameter(Mandatory = true, HelpMessage = "Path to the file which will be uploaded")]
public string SourceFilePath = string.Empty;
[Parameter(Mandatory = true, HelpMessage = "Title for the page layout")]
public string Title = string.Empty;
[Parameter(Mandatory = true, HelpMessage = "Description for the page layout")]
public string Description = string.Empty;
[Parameter(Mandatory = true, HelpMessage = "Associated content type ID")]
public string AssociatedContentTypeID;
[Parameter(Mandatory = false, HelpMessage = "Folder hierarchy where the html page layouts will be deployed")]
public string DestinationFolderHierarchy;
protected override void ExecuteCmdlet()
{
if (!System.IO.Path.IsPathRooted(SourceFilePath))
{
SourceFilePath = System.IO.Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, SourceFilePath);
}
SelectedWeb.DeployPageLayout(SourceFilePath, Title, Description, AssociatedContentTypeID, DestinationFolderHierarchy);
}
}
}
| 41.351351 | 130 | 0.70719 | [
"MIT"
] | Dean144/PnP-PowerShell | Commands/Publishing/AddPublishingPageLayout.cs | 1,532 | C# |
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Hosting;
using Stl.RegisterAttributes.Internal;
namespace Stl.RegisterAttributes;
public class RegisterHostedServiceAttribute : RegisterServiceAttribute
{
public override void Register(IServiceCollection services, Type implementationType)
{
if (Lifetime != ServiceLifetime.Singleton)
throw Errors.HostedServiceHasToBeSingleton(implementationType);
var serviceType = ServiceType ?? implementationType;
// The code is tricky because TryAddEnumerable requires that
// passed factory delegate (Func<...>) indicates correct implementation
// type in its last type argument.
var factory = (Func<IServiceProvider, object>) CreateServiceFactoryMethod
.MakeGenericMethod(serviceType)
.Invoke(null, Array.Empty<object>())!;
services.TryAddEnumerable(
ServiceDescriptor.Singleton(
typeof(IHostedService), factory));
}
private static MethodInfo CreateServiceFactoryMethod = typeof(RegisterHostedServiceAttribute)
.GetMethod(nameof(CreateServiceFactory), BindingFlags.Static | BindingFlags.NonPublic)!;
private static Func<IServiceProvider, TImpl> CreateServiceFactory<TImpl>()
where TImpl : class
=> c => c.GetRequiredService<TImpl>();
}
| 41.911765 | 97 | 0.736842 | [
"MIT"
] | ScriptBox21/Stl.Fusion | src/Stl.RegisterAttributes/Attributes/RegisterHostedServiceAttribute.cs | 1,425 | 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.VirtualMachineImages.V20190501Preview.Inputs
{
/// <summary>
/// Reboots a VM and waits for it to come back online (Windows). Corresponds to Packer windows-restart provisioner
/// </summary>
public sealed class ImageTemplateRestartCustomizerArgs : Pulumi.ResourceArgs
{
/// <summary>
/// Friendly Name to provide context on what this customization step does
/// </summary>
[Input("name")]
public Input<string>? Name { get; set; }
/// <summary>
/// Command to check if restart succeeded [Default: '']
/// </summary>
[Input("restartCheckCommand")]
public Input<string>? RestartCheckCommand { get; set; }
/// <summary>
/// Command to execute the restart [Default: 'shutdown /r /f /t 0 /c "packer restart"']
/// </summary>
[Input("restartCommand")]
public Input<string>? RestartCommand { get; set; }
/// <summary>
/// Restart timeout specified as a string of magnitude and unit, e.g. '5m' (5 minutes) or '2h' (2 hours) [Default: '5m']
/// </summary>
[Input("restartTimeout")]
public Input<string>? RestartTimeout { get; set; }
/// <summary>
/// The type of customization tool you want to use on the Image. For example, "Shell" can be shell customizer
/// Expected value is 'WindowsRestart'.
/// </summary>
[Input("type", required: true)]
public Input<string> Type { get; set; } = null!;
public ImageTemplateRestartCustomizerArgs()
{
}
}
}
| 35.666667 | 128 | 0.619418 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/VirtualMachineImages/V20190501Preview/Inputs/ImageTemplateRestartCustomizerArgs.cs | 1,926 | C# |
// ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschränkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Net.Http.Headers;
using NSwag.Annotations;
using Squidex.Areas.Api.Controllers.Apps.Models;
using Squidex.Domain.Apps.Entities;
using Squidex.Domain.Apps.Entities.Apps;
using Squidex.Domain.Apps.Entities.Apps.Commands;
using Squidex.Domain.Apps.Entities.Apps.Services;
using Squidex.Infrastructure.Assets;
using Squidex.Infrastructure.Commands;
using Squidex.Infrastructure.Log;
using Squidex.Infrastructure.Security;
using Squidex.Infrastructure.Validation;
using Squidex.Shared;
using Squidex.Web;
namespace Squidex.Areas.Api.Controllers.Apps
{
/// <summary>
/// Manages and configures apps.
/// </summary>
[ApiExplorerSettings(GroupName = nameof(Apps))]
public sealed class AppsController : ApiController
{
private readonly IAppImageStore appImageStore;
private readonly IAssetStore assetStore;
private readonly IAssetThumbnailGenerator assetThumbnailGenerator;
private readonly IAppProvider appProvider;
private readonly IAppPlansProvider appPlansProvider;
public AppsController(ICommandBus commandBus,
IAppImageStore appImageStore,
IAssetStore assetStore,
IAssetThumbnailGenerator assetThumbnailGenerator,
IAppProvider appProvider,
IAppPlansProvider appPlansProvider)
: base(commandBus)
{
this.appImageStore = appImageStore;
this.assetStore = assetStore;
this.assetThumbnailGenerator = assetThumbnailGenerator;
this.appProvider = appProvider;
this.appPlansProvider = appPlansProvider;
}
/// <summary>
/// Get your apps.
/// </summary>
/// <returns>
/// 200 => Apps returned.
/// </returns>
/// <remarks>
/// You can only retrieve the list of apps when you are authenticated as a user (OpenID implicit flow).
/// You will retrieve all apps, where you are assigned as a contributor.
/// </remarks>
[HttpGet]
[Route("apps/")]
[ProducesResponseType(typeof(AppDto[]), 200)]
[ApiPermission]
[ApiCosts(0)]
public async Task<IActionResult> GetApps()
{
var userOrClientId = HttpContext.User.UserOrClientId()!;
var userPermissions = HttpContext.Permissions();
var apps = await appProvider.GetUserAppsAsync(userOrClientId, userPermissions);
var response = Deferred.Response(() =>
{
return apps.OrderBy(x => x.Name).Select(a => AppDto.FromApp(a, userOrClientId, userPermissions, appPlansProvider, this)).ToArray();
});
Response.Headers[HeaderNames.ETag] = apps.ToEtag();
return Ok(response);
}
/// <summary>
/// Create a new app.
/// </summary>
/// <param name="request">The app object that needs to be added to Squidex.</param>
/// <returns>
/// 201 => App created.
/// 400 => App request not valid.
/// 409 => App name is already in use.
/// </returns>
/// <remarks>
/// You can only create an app when you are authenticated as a user (OpenID implicit flow).
/// You will be assigned as owner of the new app automatically.
/// </remarks>
[HttpPost]
[Route("apps/")]
[ProducesResponseType(typeof(AppDto), 201)]
[ApiPermission]
[ApiCosts(0)]
public async Task<IActionResult> PostApp([FromBody] CreateAppDto request)
{
var response = await InvokeCommandAsync(request.ToCommand());
return CreatedAtAction(nameof(GetApps), response);
}
/// <summary>
/// Update the app.
/// </summary>
/// <param name="app">The name of the app to update.</param>
/// <param name="request">The values to update.</param>
/// <returns>
/// 200 => App updated.
/// 404 => App not found.
/// </returns>
[HttpPut]
[Route("apps/{app}/")]
[ProducesResponseType(typeof(AppDto), 200)]
[ApiPermission(Permissions.AppUpdateGeneral)]
[ApiCosts(0)]
public async Task<IActionResult> UpdateApp(string app, [FromBody] UpdateAppDto request)
{
var response = await InvokeCommandAsync(request.ToCommand());
return Ok(response);
}
/// <summary>
/// Get the app image.
/// </summary>
/// <param name="app">The name of the app to update.</param>
/// <param name="file">The file to upload.</param>
/// <returns>
/// 200 => App image uploaded.
/// 404 => App not found.
/// </returns>
[HttpPost]
[Route("apps/{app}/image")]
[ProducesResponseType(typeof(AppDto), 201)]
[ApiPermission(Permissions.AppUpdateImage)]
[ApiCosts(0)]
public async Task<IActionResult> UploadImage(string app, [OpenApiIgnore] List<IFormFile> file)
{
var response = await InvokeCommandAsync(CreateCommand(file));
return Ok(response);
}
/// <summary>
/// Get the app image.
/// </summary>
/// <param name="app">The name of the app.</param>
/// <returns>
/// 200 => App image found and content or (resized) image returned.
/// 404 => App not found.
/// </returns>
[HttpGet]
[Route("apps/{app}/image")]
[ProducesResponseType(typeof(FileResult), 200)]
[AllowAnonymous]
[ApiCosts(0)]
public IActionResult GetImage(string app)
{
if (App.Image == null)
{
return NotFound();
}
var etag = App.Image.Etag;
Response.Headers[HeaderNames.ETag] = etag;
var handler = new Func<Stream, Task>(async bodyStream =>
{
var resizedAsset = $"{App.Id}_{etag}_Resized";
try
{
await assetStore.DownloadAsync(resizedAsset, bodyStream);
}
catch (AssetNotFoundException)
{
using (Profiler.Trace("Resize"))
{
using (var sourceStream = GetTempStream())
{
using (var destinationStream = GetTempStream())
{
using (Profiler.Trace("ResizeDownload"))
{
await appImageStore.DownloadAsync(App.Id, sourceStream);
sourceStream.Position = 0;
}
using (Profiler.Trace("ResizeImage"))
{
await assetThumbnailGenerator.CreateThumbnailAsync(sourceStream, destinationStream, 150, 150, "Crop");
destinationStream.Position = 0;
}
using (Profiler.Trace("ResizeUpload"))
{
await assetStore.UploadAsync(resizedAsset, destinationStream);
destinationStream.Position = 0;
}
await destinationStream.CopyToAsync(bodyStream);
}
}
}
}
});
return new FileCallbackResult(App.Image.MimeType, null, true, handler);
}
/// <summary>
/// Remove the app image.
/// </summary>
/// <param name="app">The name of the app to update.</param>
/// <returns>
/// 200 => App image removed.
/// 404 => App not found.
/// </returns>
[HttpDelete]
[Route("apps/{app}/image")]
[ProducesResponseType(typeof(AppDto), 201)]
[ApiPermission(Permissions.AppUpdate)]
[ApiCosts(0)]
public async Task<IActionResult> DeleteImage(string app)
{
var response = await InvokeCommandAsync(new RemoveAppImage());
return Ok(response);
}
/// <summary>
/// Archive the app.
/// </summary>
/// <param name="app">The name of the app to archive.</param>
/// <returns>
/// 204 => App archived.
/// 404 => App not found.
/// </returns>
[HttpDelete]
[Route("apps/{app}/")]
[ApiPermission(Permissions.AppDelete)]
[ApiCosts(0)]
public async Task<IActionResult> DeleteApp(string app)
{
await CommandBus.PublishAsync(new ArchiveApp());
return NoContent();
}
private async Task<AppDto> InvokeCommandAsync(ICommand command)
{
var context = await CommandBus.PublishAsync(command);
var userOrClientId = HttpContext.User.UserOrClientId()!;
var userPermissions = HttpContext.Permissions();
var result = context.Result<IAppEntity>();
var response = AppDto.FromApp(result, userOrClientId, userPermissions, appPlansProvider, this);
return response;
}
private static UploadAppImage CreateCommand(IReadOnlyList<IFormFile> file)
{
if (file.Count != 1)
{
var error = new ValidationError($"Can only upload one file, found {file.Count} files.");
throw new ValidationException("Cannot create asset.", error);
}
return new UploadAppImage { File = file[0].ToAssetFile() };
}
private static FileStream GetTempStream()
{
var tempFileName = Path.GetTempFileName();
return new FileStream(tempFileName,
FileMode.Create,
FileAccess.ReadWrite,
FileShare.Delete, 1024 * 16,
FileOptions.Asynchronous |
FileOptions.DeleteOnClose |
FileOptions.SequentialScan);
}
}
}
| 35.586885 | 147 | 0.539432 | [
"MIT"
] | mhilgersom/squidex | backend/src/Squidex/Areas/Api/Controllers/Apps/AppsController.cs | 10,857 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("L2_T12")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("L2_T12")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("8c80f041-9b44-4948-82c8-63b3cab2c8f0")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.297297 | 84 | 0.745652 | [
"MIT"
] | doXi70/Homework_SoftUni | L2_T12/Properties/AssemblyInfo.cs | 1,383 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的常规信息通过以下
// 特性集控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("DNSManager")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DNSManager")]
[assembly: AssemblyCopyright("Copyright © dnslocal 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 使此程序集中的类型
// 对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型,
// 则将该类型上的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("5a92a961-75af-446e-8f1c-7d1fb2752bcb")]
// 程序集的版本信息由下面四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
// 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
// 方法是按如下所示使用“*”:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.2.0")]
[assembly: AssemblyFileVersion("1.0.2.0")]
| 26.837838 | 59 | 0.687815 | [
"MIT"
] | dnslocal/dnslocal-windows | DNSManager/DNSManager/Properties/AssemblyInfo.cs | 1,352 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace YiSha.Entity.SystemManage
{
public class IdEntity
{
public long? Id { get; set; }
public string Token { get; set; }
}
}
| 18.4 | 41 | 0.677536 | [
"MIT"
] | guoer1228/YiShaAdmin | YiSha.Entity/YiSha.Entity/SystemManage/IdEntity.cs | 278 | C# |
using SPICA.PICA.Commands;
using System;
namespace SPICA.Formats.CtrGfx.Model.Mesh
{
public enum GfxGLDataType : uint
{
GL_BYTE = 0x1400,
GL_UNSIGNED_BYTE = 0x1401,
GL_SHORT = 0x1402,
GL_UNSIGNED_SHORT = 0x1403,
GL_FLOAT = 0x1406,
GL_FIXED = 0x140C
}
static class GfxGLDataTypeExtensions
{
public static PICAAttributeFormat ToPICAAttributeFormat(this GfxGLDataType Format)
{
switch (Format)
{
case GfxGLDataType.GL_BYTE: return PICAAttributeFormat.Byte;
case GfxGLDataType.GL_UNSIGNED_BYTE: return PICAAttributeFormat.Ubyte;
case GfxGLDataType.GL_SHORT: return PICAAttributeFormat.Short;
case GfxGLDataType.GL_FLOAT: return PICAAttributeFormat.Float;
default: throw new ArgumentException($"Invalid format {Format}!");
}
}
}
}
| 30.484848 | 90 | 0.590457 | [
"Unlicense"
] | AkelaSnow/SPICA | SPICA/Formats/CtrGfx/Model/Mesh/GfxGLDataType.cs | 1,008 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using HullMaker.Models;
namespace HullMaker.Account
{
public partial class TwoFactorAuthenticationSignIn : System.Web.UI.Page
{
private ApplicationSignInManager signinManager;
private ApplicationUserManager manager;
public TwoFactorAuthenticationSignIn()
{
manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
signinManager = Context.GetOwinContext().GetUserManager<ApplicationSignInManager>();
}
protected void Page_Load(object sender, EventArgs e)
{
var userId = signinManager.GetVerifiedUserId<ApplicationUser, string>();
if (userId == null)
{
Response.Redirect("/Account/Error", true);
}
var userFactors = manager.GetValidTwoFactorProviders(userId);
Providers.DataSource = userFactors.Select(x => x).ToList();
Providers.DataBind();
}
protected void CodeSubmit_Click(object sender, EventArgs e)
{
bool rememberMe = false;
bool.TryParse(Request.QueryString["RememberMe"], out rememberMe);
var result = signinManager.TwoFactorSignIn<ApplicationUser, string>(SelectedProvider.Value, Code.Text, isPersistent: rememberMe, rememberBrowser: RememberBrowser.Checked);
switch (result)
{
case SignInStatus.Success:
IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
break;
case SignInStatus.LockedOut:
Response.Redirect("/Account/Lockout");
break;
case SignInStatus.Failure:
default:
FailureText.Text = "Invalid code";
ErrorMessage.Visible = true;
break;
}
}
protected void ProviderSubmit_Click(object sender, EventArgs e)
{
if (!signinManager.SendTwoFactorCode(Providers.SelectedValue))
{
Response.Redirect("/Account/Error");
}
var user = manager.FindById(signinManager.GetVerifiedUserId<ApplicationUser, string>());
if (user != null)
{
var code = manager.GenerateTwoFactorToken(user.Id, Providers.SelectedValue);
}
SelectedProvider.Value = Providers.SelectedValue;
sendcode.Visible = false;
verifycode.Visible = true;
}
}
} | 36.623377 | 183 | 0.604965 | [
"MIT"
] | ArenaDave/CodeFighter | CodeFighter/HullMaker/Account/TwoFactorAuthenticationSignIn.aspx.cs | 2,822 | C# |
using System;
using CAFU.Core.Domain.Model;
using CAFU.Core.Presentation.Presenter;
using JetBrains.Annotations;
using UnityEngine;
using Object = UnityEngine.Object;
namespace CAFU.Core.Presentation.View
{
// 本当は IMonoBehaviour 的なモノを継承したいところだが、そんな inteface ないので規約ベースで頑張る
[PublicAPI]
public interface IView
{
}
[PublicAPI]
public interface IInjectableView<in TModel> : IView where TModel : IModel
{
void Inject(TModel model);
}
[PublicAPI]
public static class ViewExtension
{
public static string GetSceneName(this IView view)
{
var component = view as Component;
if (component == null)
{
throw new InvalidCastException($"View '{view.GetType().FullName}' does not extends UnityEngine.Component.");
}
return component.gameObject.scene.name;
}
public static TPresenter GetPresenter<TPresenter>(this IView view) where TPresenter : IPresenter
{
return PresenterContainer.Instance.GetPresenter<TPresenter>(view.GetSceneName());
}
public static IView AddChildView(this Transform transform, Component prefab)
{
return transform.AddChildView(prefab.gameObject);
}
public static IView AddChildView(this Transform transform, GameObject prefab)
{
return transform.AddChildView<IView>(prefab);
}
public static IView AddChildView<TModel>(this Transform transform, Component prefab, TModel model)
where TModel : IModel
{
return transform.AddChildView(prefab.gameObject, model);
}
public static IView AddChildView<TModel>(this Transform transform, GameObject prefab, TModel model)
where TModel : IModel
{
return transform.AddChildView<IView, TModel>(prefab, model);
}
public static TView AddChildView<TView>(this Transform transform, TView prefab)
where TView : Component, IView
{
return transform.AddChildView<TView>(prefab.gameObject);
}
public static TView AddChildView<TView>(this Transform transform, GameObject prefab)
where TView : IView
{
var child = Object.Instantiate(prefab, transform);
var childView = child.gameObject.GetComponent<TView>();
if (childView == null)
{
throw new InvalidOperationException($"GameObject '{child.name}' has not attached component '{typeof(TView).FullName}'.");
}
return childView;
}
public static TView AddChildView<TView, TModel>(this Transform transform, TView prefab, TModel model)
where TView : Component, IView
where TModel : IModel
{
return transform.AddChildView<TView, TModel>(prefab.gameObject, model);
}
public static TView AddChildView<TView, TModel>(this Transform transform, GameObject prefab, TModel model)
where TView : IView
where TModel : IModel
{
var childView = transform.AddChildView<TView>(prefab);
var childMonoBehaviour = childView as MonoBehaviour;
if (childMonoBehaviour == default(MonoBehaviour))
{
throw new InvalidOperationException($"'{typeof(TView).FullName}' is not inheritance MonoBehaviour.");
}
(childView as IInjectableView<TModel>)?.Inject(model);
return childView;
}
}
} | 34.219048 | 137 | 0.629001 | [
"MIT"
] | c-c-c-c/cafu_core | Assets/Scripts/Presentation/View/View.cs | 3,665 | C# |
// <copyright file="RequestSerialiserTests.cs" company="Glenn Watson">
// Copyright (c) 2018 Glenn Watson. All rights reserved.
// See LICENSE file in the project root for full license information.
// </copyright>
namespace GitLfs.Core.Tests
{
using GitLfs.Core.BatchRequest;
using Xunit;
public class RequestSerialiserTests
{
[Fact]
public void RequestDeserialiseTest()
{
const string jsonText =
"{\r\n \"operation\": \"download\",\r\n \"transfers\": [ \"basic\" ],\r\n \"objects\": [\r\n {\r\n \"oid\": \"12345678\",\r\n \"size\": 123,\r\n }\r\n ]\r\n}";
var serialiser = new JsonBatchRequestSerialiser();
BatchRequest request = serialiser.FromString(jsonText);
Assert.Equal(1, request.Objects.Count);
Assert.Equal(1, request.Transfers.Count);
Assert.Equal(BatchRequestMode.Download, request.Operation);
Assert.Equal("12345678", request.Objects[0].Hash);
Assert.Equal(123, request.Objects[0].Size);
Assert.Equal(TransferMode.Basic, request.Transfers[0]);
}
[Fact]
public void RequestSerialiseTest()
{
const string jsonText =
"{\r\n \"objects\": [\r\n {\r\n \"oid\": \"12345678\",\r\n \"size\": 123\r\n }\r\n ],\r\n \"operation\": \"download\",\r\n \"transfers\": [\r\n \"basic\"\r\n ]\r\n}";
var serialiser = new JsonBatchRequestSerialiser();
BatchRequest objectValue = serialiser.FromString(jsonText);
string objectText = serialiser.ToString(objectValue);
Assert.Equal(jsonText, objectText);
}
}
} | 36.530612 | 207 | 0.559777 | [
"MIT"
] | glennawatson/GitLfsCachingServer | GitLfs.Core.Tests/RequestSerialiserTests.cs | 1,792 | C# |
namespace Rabbiter.Core.Events.Listeners
{
using Microsoft.Extensions.Logging;
using Rabbiter.Core.Abstractions;
using Rabbiter.Core.Abstractions.Events;
using Rabbiter.Core.Abstractions.Publishers;
using System;
using System.Threading.Tasks;
public class EventProcessingFaultResolver
: IEventProcessingFaultResolvingStrategy
{
private readonly ILogger<EventProcessingFaultResolver> _logger;
private readonly IEventPublisher _eventPublisher;
public EventProcessingFaultResolver(
ILogger<EventProcessingFaultResolver> logger,
IEventPublisher eventPublisher)
{
_logger = logger;
_eventPublisher = eventPublisher;
}
public async Task ResolveFaultAsync<TEvent>(IEventContainer<TEvent> @event, Exception exception)
where TEvent: IEvent
{
_logger.LogError($"{@event} error occurs while processing an event {@event.Id}");
_logger.LogError($"{@event} about to send fault message...");
_eventPublisher.PublishFault(@event.Event, exception.Message);
}
public async Task ResolveFaultAsync<TEvent>(IEventContainer<TEvent> @event, string exception)
where TEvent : IEvent
{
_logger.LogError($"{@event} error occurs while processing an event {@event.Id}");
_logger.LogError($"{@event} about to send fault message...");
_eventPublisher.PublishFault(@event.Event, exception);
}
}
}
| 37.119048 | 104 | 0.661321 | [
"Apache-2.0"
] | goOrn/RabbiteR | src/Rabbiter.Core/Events/Listeners/EventProcessingFaultResolver.cs | 1,561 | C# |
using System.Collections.Generic;
namespace EndIf.Yust
{
[Description(token: "(", precedence: 0)]
internal class ParenthesesStart : Instruction
{
public override bool Execute(Stack<object> stack, IDictionary<string, object> context)
{
return true;
}
}
[Description(token: ")", precedence: 99)]
internal class ParenthesesEnd : Instruction
{
public override bool Execute(Stack<object> stack, IDictionary<string, object> context)
{
return true;
}
}
}
| 24.130435 | 94 | 0.616216 | [
"MIT"
] | GugeNet/Yust | Yust/Parentheses.cs | 557 | C# |
namespace AlgoExpertTest
{
using AlgoExpert;
using FluentAssertions;
using NUnit.Framework;
[TestFixture]
[Parallelizable(ParallelScope.All)]
public class ValidIPAddressesTest
{
[Test]
public void TestCase1()
{
var str = "1921680";
var expected = new[]
{
"1.9.216.80",
"1.92.16.80",
"1.92.168.0",
"19.2.16.80",
"19.2.168.0",
"19.21.6.80",
"19.21.68.0",
"19.216.8.0",
"192.1.6.80",
"192.1.68.0",
"192.16.8.0"
};
var sut = new ValidIPAddresses();
var actual = sut.Solve(str);
actual.Should().BeEquivalentTo(expected);
}
[Test]
public void TestCase2()
{
var str = "3700100";
var expected = new[]
{
"3.70.0.100",
"37.0.0.100"
};
var sut = new ValidIPAddresses();
var actual = sut.Solve(str);
actual.Should().BeEquivalentTo(expected);
}
[Test]
public void TestCase3()
{
var str = "255255255255";
var expected = new[]
{
"255.255.255.255"
};
var sut = new ValidIPAddresses();
var actual = sut.Solve(str);
actual.Should().BeEquivalentTo(expected);
}
[Test]
public void TestCase4()
{
var str = "255255255256";
var expected = new string[] { };
var sut = new ValidIPAddresses();
var actual = sut.Solve(str);
actual.Should().BeEquivalentTo(expected);
}
}
}
| 25.791667 | 53 | 0.422725 | [
"MIT"
] | KucherenkoSerhiy/AlgoPractice | SandBoxTest/ValidIPAddressesTest.cs | 1,859 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by \generate-code.bat.
//
// Changes to this file will be lost when the code is regenerated.
// The build server regenerates the code before each build and a pre-build
// step will regenerate the code on each local build.
//
// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units.
//
// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities.
// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities.
//
// </auto-generated>
//------------------------------------------------------------------------------
// Licensed under MIT No Attribution, see LICENSE file at the root.
// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet.
using System;
using UnitsNet.Units;
namespace UnitsNet
{
/// <inheritdoc />
/// <summary>
/// Enthalpy is a measure.
/// </summary>
public struct EnthalpyMolar
{
/// <summary>
/// The numeric value this quantity was constructed with.
/// </summary>
private readonly double _value;
/// <summary>
/// The unit this quantity was constructed with.
/// </summary>
private readonly EnthalpyMolarUnit _unit;
/// <summary>
/// The numeric value this quantity was constructed with.
/// </summary>
public double Value => _value;
/// <inheritdoc />
public EnthalpyMolarUnit Unit => _unit;
/// <summary>
/// Creates the quantity with the given numeric value and unit.
/// </summary>
/// <param name="value">The numeric value to construct this quantity with.</param>
/// <param name="unit">The unit representation to construct this quantity with.</param>
/// <exception cref="ArgumentException">If value is NaN or Infinity.</exception>
public EnthalpyMolar(double value, EnthalpyMolarUnit unit)
{
_value = value;
_unit = unit;
}
/// <summary>
/// The base unit of Duration, which is Second. All conversions go via this value.
/// </summary>
public static EnthalpyMolarUnit BaseUnit { get; } = EnthalpyMolarUnit.JoulePerMole;
/// <summary>
/// Represents the largest possible value of Duration
/// </summary>
public static EnthalpyMolar MaxValue { get; } = new EnthalpyMolar(double.MaxValue, BaseUnit);
/// <summary>
/// Represents the smallest possible value of Duration
/// </summary>
public static EnthalpyMolar MinValue { get; } = new EnthalpyMolar(double.MinValue, BaseUnit);
/// <summary>
/// Gets an instance of this quantity with a value of 0 in the base unit Second.
/// </summary>
public static EnthalpyMolar Zero { get; } = new EnthalpyMolar(0, BaseUnit);
#region Conversion Properties
/// <summary>
/// Get EnthalpyMolar in BTUsPerPoundMole.
/// </summary>
public double BTUsPerPoundMole => As(EnthalpyMolarUnit.BTUPerPoundMole);
/// <summary>
/// Get EnthalpyMolar in CaloriesPerMole.
/// </summary>
public double CaloriesPerMole => As(EnthalpyMolarUnit.CaloriesPerMole);
/// <summary>
/// Get EnthalpyMolar in JoulesPerKilomole.
/// </summary>
public double JoulesPerKilomole => As(EnthalpyMolarUnit.JoulePerKilomole);
/// <summary>
/// Get EnthalpyMolar in JoulesPerMole.
/// </summary>
public double JoulesPerMole => As(EnthalpyMolarUnit.JoulePerMole);
/// <summary>
/// Get EnthalpyMolar in KilojoulesPerKilomole.
/// </summary>
public double KilojoulesPerKilomole => As(EnthalpyMolarUnit.KilojoulePerKilomole);
/// <summary>
/// Get EnthalpyMolar in KilojoulesPerMole.
/// </summary>
public double KilojoulesPerMole => As(EnthalpyMolarUnit.KilojoulePerMole);
/// <summary>
/// Get EnthalpyMolar in MegajoulesPerMole.
/// </summary>
public double MegajoulesPerMole => As(EnthalpyMolarUnit.MegajoulePerMole);
#endregion
#region Static Factory Methods
/// <summary>
/// Get EnthalpyMolar from BTUsPerPoundMole.
/// </summary>
/// <exception cref="ArgumentException">If value is NaN or Infinity.</exception>
public static EnthalpyMolar FromBTUsPerPoundMole(double btusperpoundmole) => new EnthalpyMolar(btusperpoundmole, EnthalpyMolarUnit.BTUPerPoundMole);
/// <summary>
/// Get EnthalpyMolar from CaloriesPerMole.
/// </summary>
/// <exception cref="ArgumentException">If value is NaN or Infinity.</exception>
public static EnthalpyMolar FromCaloriesPerMole(double caloriespermole) => new EnthalpyMolar(caloriespermole, EnthalpyMolarUnit.CaloriesPerMole);
/// <summary>
/// Get EnthalpyMolar from JoulesPerKilomole.
/// </summary>
/// <exception cref="ArgumentException">If value is NaN or Infinity.</exception>
public static EnthalpyMolar FromJoulesPerKilomole(double joulesperkilomole) => new EnthalpyMolar(joulesperkilomole, EnthalpyMolarUnit.JoulePerKilomole);
/// <summary>
/// Get EnthalpyMolar from JoulesPerMole.
/// </summary>
/// <exception cref="ArgumentException">If value is NaN or Infinity.</exception>
public static EnthalpyMolar FromJoulesPerMole(double joulespermole) => new EnthalpyMolar(joulespermole, EnthalpyMolarUnit.JoulePerMole);
/// <summary>
/// Get EnthalpyMolar from KilojoulesPerKilomole.
/// </summary>
/// <exception cref="ArgumentException">If value is NaN or Infinity.</exception>
public static EnthalpyMolar FromKilojoulesPerKilomole(double kilojoulesperkilomole) => new EnthalpyMolar(kilojoulesperkilomole, EnthalpyMolarUnit.KilojoulePerKilomole);
/// <summary>
/// Get EnthalpyMolar from KilojoulesPerMole.
/// </summary>
/// <exception cref="ArgumentException">If value is NaN or Infinity.</exception>
public static EnthalpyMolar FromKilojoulesPerMole(double kilojoulespermole) => new EnthalpyMolar(kilojoulespermole, EnthalpyMolarUnit.KilojoulePerMole);
/// <summary>
/// Get EnthalpyMolar from MegajoulesPerMole.
/// </summary>
/// <exception cref="ArgumentException">If value is NaN or Infinity.</exception>
public static EnthalpyMolar FromMegajoulesPerMole(double megajoulespermole) => new EnthalpyMolar(megajoulespermole, EnthalpyMolarUnit.MegajoulePerMole);
/// <summary>
/// Dynamically convert from value and unit enum <see cref="EnthalpyMolarUnit" /> to <see cref="EnthalpyMolar" />.
/// </summary>
/// <param name="value">Value to convert from.</param>
/// <param name="fromUnit">Unit to convert from.</param>
/// <returns>EnthalpyMolar unit value.</returns>
public static EnthalpyMolar From(double value, EnthalpyMolarUnit fromUnit)
{
return new EnthalpyMolar(value, fromUnit);
}
#endregion
#region Conversion Methods
/// <summary>
/// Convert to the unit representation <paramref name="unit" />.
/// </summary>
/// <returns>Value converted to the specified unit.</returns>
public double As(EnthalpyMolarUnit unit) => GetValueAs(unit);
/// <summary>
/// Converts this Duration to another Duration with the unit representation <paramref name="unit" />.
/// </summary>
/// <returns>A Duration with the specified unit.</returns>
public EnthalpyMolar ToUnit(EnthalpyMolarUnit unit)
{
var convertedValue = GetValueAs(unit);
return new EnthalpyMolar(convertedValue, unit);
}
/// <summary>
/// Converts the current value + unit to the base unit.
/// This is typically the first step in converting from one unit to another.
/// </summary>
/// <returns>The value in the base unit representation.</returns>
private double GetValueInBaseUnit()
{
switch(Unit)
{
case EnthalpyMolarUnit.BTUPerPoundMole: return _value*(1055.05585262/453.59237);
case EnthalpyMolarUnit.CaloriesPerMole: return _value*4184;
case EnthalpyMolarUnit.JoulePerKilomole: return _value*(1.0/1000);
case EnthalpyMolarUnit.JoulePerMole: return _value;
case EnthalpyMolarUnit.KilojoulePerKilomole: return (_value*(1.0/1000)) * 1e3d;
case EnthalpyMolarUnit.KilojoulePerMole: return (_value) * 1e3d;
case EnthalpyMolarUnit.MegajoulePerMole: return (_value) * 1e6d;
default:
throw new NotImplementedException($"Can not convert {Unit} to base units.");
}
}
private double GetValueAs(EnthalpyMolarUnit unit)
{
if(Unit == unit)
return _value;
var baseUnitValue = GetValueInBaseUnit();
switch(unit)
{
case EnthalpyMolarUnit.BTUPerPoundMole: return baseUnitValue/(1055.05585262/453.59237);
case EnthalpyMolarUnit.CaloriesPerMole: return baseUnitValue/4184;
case EnthalpyMolarUnit.JoulePerKilomole: return baseUnitValue/(1.0/1000);
case EnthalpyMolarUnit.JoulePerMole: return baseUnitValue;
case EnthalpyMolarUnit.KilojoulePerKilomole: return (baseUnitValue/(1.0/1000)) / 1e3d;
case EnthalpyMolarUnit.KilojoulePerMole: return (baseUnitValue) / 1e3d;
case EnthalpyMolarUnit.MegajoulePerMole: return (baseUnitValue) / 1e6d;
default:
throw new NotImplementedException($"Can not convert {Unit} to {unit}.");
}
}
#endregion
}
}
| 42.896694 | 176 | 0.621905 | [
"MIT-feh"
] | Gas-Liquids-Engineering/UnitsNet | UnitsNet.NanoFramework/GeneratedCode/Quantities/EnthalpyMolar.g.cs | 10,381 | C# |
using CMS;
using CMS.DataEngine;
using DoctorAppointments;
[assembly: RegisterModule(typeof(DoctorAppointmentsModule))]
public class DoctorAppointmentsModule : Module
{
// Module class constructor, inherits from the base constructor with the code name of the module as the parameter
public DoctorAppointmentsModule() : base("DoctorAppointments")
{
}
/// <summary>
/// Initializes the module. Called when the application starts.
/// </summary>
protected override void OnInit()
{
base.OnInit();
// Custom event handler executed after the appointment is created
AppointmentInfo.TYPEINFO.Events.Insert.After += AppointmentEvents.Insert_After;
}
} | 29.625 | 117 | 0.7173 | [
"MIT"
] | Kentico/DEV02-K12 | DoctorAppointments/DoctorAppointments.cs | 713 | C# |
using Micky5991.Quests.Entities;
using Micky5991.Quests.Interfaces.Nodes;
namespace Micky5991.Quests.Tests.Entities
{
public class DummyParallelNode : QuestParallelNode
{
public DummyParallelNode(IQuestRootNode rootNode)
: base(rootNode)
{
}
}
}
| 21.071429 | 57 | 0.684746 | [
"MIT"
] | Micky5991/Quests | Quests.Tests/Entities/DummyParallelNode.cs | 295 | C# |
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.Management.Security
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for ExternalSecuritySolutionsOperations.
/// </summary>
public static partial class ExternalSecuritySolutionsOperationsExtensions
{
/// <summary>
/// Gets a list of external security solutions for the subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static IPage<ExternalSecuritySolution> List(this IExternalSecuritySolutionsOperations operations)
{
return operations.ListAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Gets a list of external security solutions for the subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<ExternalSecuritySolution>> ListAsync(this IExternalSecuritySolutionsOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets a list of external Security Solutions for the subscription and
/// location.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static IPage<ExternalSecuritySolution> ListByHomeRegion(this IExternalSecuritySolutionsOperations operations)
{
return operations.ListByHomeRegionAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Gets a list of external Security Solutions for the subscription and
/// location.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<ExternalSecuritySolution>> ListByHomeRegionAsync(this IExternalSecuritySolutionsOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByHomeRegionWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets a specific external Security Solution.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group within the user's subscription. The name is
/// case insensitive.
/// </param>
/// <param name='externalSecuritySolutionsName'>
/// Name of an external security solution.
/// </param>
public static ExternalSecuritySolution Get(this IExternalSecuritySolutionsOperations operations, string resourceGroupName, string externalSecuritySolutionsName)
{
return operations.GetAsync(resourceGroupName, externalSecuritySolutionsName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets a specific external Security Solution.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group within the user's subscription. The name is
/// case insensitive.
/// </param>
/// <param name='externalSecuritySolutionsName'>
/// Name of an external security solution.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ExternalSecuritySolution> GetAsync(this IExternalSecuritySolutionsOperations operations, string resourceGroupName, string externalSecuritySolutionsName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, externalSecuritySolutionsName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets a list of external security solutions for the subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<ExternalSecuritySolution> ListNext(this IExternalSecuritySolutionsOperations operations, string nextPageLink)
{
return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Gets a list of external security solutions for the subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<ExternalSecuritySolution>> ListNextAsync(this IExternalSecuritySolutionsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets a list of external Security Solutions for the subscription and
/// location.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<ExternalSecuritySolution> ListByHomeRegionNext(this IExternalSecuritySolutionsOperations operations, string nextPageLink)
{
return operations.ListByHomeRegionNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Gets a list of external Security Solutions for the subscription and
/// location.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<ExternalSecuritySolution>> ListByHomeRegionNextAsync(this IExternalSecuritySolutionsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByHomeRegionNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| 46.153061 | 255 | 0.590316 | [
"MIT"
] | 0rland0Wats0n/azure-sdk-for-net | sdk/securitycenter/Microsoft.Azure.Management.SecurityCenter/src/Generated/ExternalSecuritySolutionsOperationsExtensions.cs | 9,046 | C# |
#nullable enable
using System.Threading.Tasks;
using Content.Server.GameObjects.Components.Chemistry;
using Content.Server.GameObjects.EntitySystems.DoAfter;
using Content.Shared.Chemistry;
using Content.Shared.Interfaces;
using Content.Shared.Interfaces.GameObjects.Components;
using Content.Shared.Utility;
using Robust.Shared.Audio;
using Robust.Shared.GameObjects;
using Robust.Shared.Localization;
using Robust.Shared.Player;
using Robust.Shared.Serialization.Manager.Attributes;
using Robust.Shared.ViewVariables;
namespace Content.Server.GameObjects.Components.Fluids
{
/// <summary>
/// For cleaning up puddles
/// </summary>
[RegisterComponent]
public class MopComponent : Component, IAfterInteract
{
public override string Name => "Mop";
/// <summary>
/// Used to prevent do_after spam if we're currently mopping.
/// </summary>
public bool Mopping { get; private set; }
public SolutionContainerComponent? Contents => Owner.GetComponentOrNull<SolutionContainerComponent>();
public ReagentUnit MaxVolume
{
get => Owner.GetComponentOrNull<SolutionContainerComponent>()?.MaxVolume ?? ReagentUnit.Zero;
set
{
if (Owner.TryGetComponent(out SolutionContainerComponent? solution))
{
solution.MaxVolume = value;
}
}
}
public ReagentUnit CurrentVolume =>
Owner.GetComponentOrNull<SolutionContainerComponent>()?.CurrentVolume ?? ReagentUnit.Zero;
// Currently there's a separate amount for pickup and dropoff so
// Picking up a puddle requires multiple clicks
// Dumping in a bucket requires 1 click
// Long-term you'd probably use a cooldown and start the pickup once we have some form of global cooldown
[DataField("pickup_amount")]
public ReagentUnit PickupAmount { get; } = ReagentUnit.New(5);
[DataField("pickup_sound")]
private string? _pickupSound = "/Audio/Effects/Fluids/slosh.ogg";
/// <summary>
/// Multiplier for the do_after delay for how fast the mop works.
/// </summary>
[ViewVariables]
[DataField("speed")]
private float _mopSpeed = 1;
public override void Initialize()
{
base.Initialize();
Owner.EnsureComponentWarn(out SolutionContainerComponent _);
}
async Task<bool> IAfterInteract.AfterInteract(AfterInteractEventArgs eventArgs)
{
/*
* Functionality:
* Essentially if we click on an empty tile spill our contents there
* Otherwise, try to mop up the puddle (if it is a puddle).
* It will try to destroy solution on the mop to do so, and if it is successful
* will spill some of the mop's solution onto the puddle which will evaporate eventually.
*/
if (!Owner.TryGetComponent(out SolutionContainerComponent? contents) ||
Mopping ||
!eventArgs.InRangeUnobstructed(ignoreInsideBlocker: true, popup: true))
{
return false;
}
var currentVolume = CurrentVolume;
if (eventArgs.Target == null)
{
if (currentVolume > 0)
{
// Drop the liquid on the mop on to the ground
contents.SplitSolution(CurrentVolume).SpillAt(eventArgs.ClickLocation, "PuddleSmear");
return true;
}
return false;
}
if (!eventArgs.Target.TryGetComponent(out PuddleComponent? puddleComponent))
{
return false;
}
var puddleVolume = puddleComponent.CurrentVolume;
if (currentVolume <= 0)
{
Owner.PopupMessage(eventArgs.User, Loc.GetString("Mop needs to be wet!"));
return false;
}
Mopping = true;
// So if the puddle has 20 units we mop in 2 seconds. Don't just store CurrentVolume given it can change so need to re-calc it anyway.
var doAfterArgs = new DoAfterEventArgs(eventArgs.User, _mopSpeed * puddleVolume.Float() / 10.0f, target: eventArgs.Target)
{
BreakOnUserMove = true,
BreakOnStun = true,
BreakOnDamage = true,
};
var result = await EntitySystem.Get<DoAfterSystem>().DoAfter(doAfterArgs);
Mopping = false;
if (result == DoAfterStatus.Cancelled ||
Owner.Deleted ||
puddleComponent.Deleted)
return false;
// Annihilate the puddle
var transferAmount = ReagentUnit.Min(ReagentUnit.New(5), puddleComponent.CurrentVolume, CurrentVolume);
var puddleCleaned = puddleComponent.CurrentVolume - transferAmount <= 0;
if (transferAmount == 0)
{
if (puddleComponent.EmptyHolder) //The puddle doesn't actually *have* reagents, for example vomit because there's no "vomit" reagent.
{
puddleComponent.Owner.Delete();
transferAmount = ReagentUnit.Min(ReagentUnit.New(5), CurrentVolume);
puddleCleaned = true;
}
else
{
return true;
}
}
else
{
puddleComponent.SplitSolution(transferAmount);
}
if (puddleCleaned) //After cleaning the puddle, make a new puddle with solution from the mop as a "wet floor". Then evaporate it slowly.
{
contents.SplitSolution(transferAmount).SpillAt(eventArgs.ClickLocation, "PuddleSmear");
}
else
{
contents.SplitSolution(transferAmount);
}
if (!string.IsNullOrWhiteSpace(_pickupSound))
{
SoundSystem.Play(Filter.Pvs(Owner), _pickupSound, Owner);
}
return true;
}
}
}
| 36.005747 | 149 | 0.583081 | [
"MIT"
] | FoundVivo/space-station-14 | Content.Server/GameObjects/Components/Fluids/MopComponent.cs | 6,265 | C# |
#pragma checksum "C:\Users\bablu\Desktop\code-fun-do\project\dot2\MainPage.xaml" "{406ea660-64cf-4c82-b6f0-42d48172a799}" "F8809B4186E2A18B251D68782A3A5642"
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace dot2
{
partial class MainPage : global::Windows.UI.Xaml.Controls.Page, global::Windows.UI.Xaml.Markup.IComponentConnector
{
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public void Connect(int connectionId, object target)
{
switch(connectionId)
{
case 1:
#line 46 "..\..\MainPage.xaml"
((global::Windows.UI.Xaml.UIElement)(target)).Tapped += this.can_Tapped;
#line default
#line hidden
break;
}
this._contentLoaded = true;
}
}
}
| 34.567568 | 156 | 0.538702 | [
"MIT"
] | babbhoi/Gravity_Point | project/dot2/obj/Debug/MainPage.g.cs | 1,281 | C# |
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using BitCoinSharp.IO;
namespace BitCoinSharp
{
/// <summary>
/// A transaction represents the movement of coins from some addresses to some other addresses. It can also represent
/// the minting of new coins. A Transaction object corresponds to the equivalent in the BitCoin C++ implementation.
/// </summary>
/// <remarks>
/// It implements TWO serialization protocols - the BitCoin proprietary format which is identical to the C++
/// implementation and is used for reading/writing transactions to the wire and for hashing. It also implements Java
/// serialization which is used for the wallet. This allows us to easily add extra fields used for our own accounting
/// or UI purposes.
/// </remarks>
[Serializable]
public class Transaction : Message
{
// These are serialized in both BitCoin and java serialization.
private uint _version;
private List<TransactionInput> _inputs;
private List<TransactionOutput> _outputs;
private uint _lockTime;
// This is an in memory helper only.
[NonSerialized] private Sha256Hash _hash;
internal Transaction(NetworkParameters @params)
: base(@params)
{
_version = 1;
_inputs = new List<TransactionInput>();
_outputs = new List<TransactionOutput>();
// We don't initialize appearsIn deliberately as it's only useful for transactions stored in the wallet.
}
/// <summary>
/// Creates a transaction from the given serialized bytes, eg, from a block or a tx network message.
/// </summary>
/// <exception cref="BitCoinSharp.ProtocolException" />
public Transaction(NetworkParameters @params, byte[] payloadBytes)
: base(@params, payloadBytes, 0)
{
}
/// <summary>
/// Creates a transaction by reading payload starting from offset bytes in. Length of a transaction is fixed.
/// </summary>
/// <exception cref="BitCoinSharp.ProtocolException" />
public Transaction(NetworkParameters @params, byte[] payload, int offset)
: base(@params, payload, offset)
{
// inputs/outputs will be created in parse()
}
/// <summary>
/// Returns a read-only list of the inputs of this transaction.
/// </summary>
public IList<TransactionInput> Inputs
{
get { return _inputs.AsReadOnly(); }
}
/// <summary>
/// Returns a read-only list of the outputs of this transaction.
/// </summary>
public IList<TransactionOutput> Outputs
{
get { return _outputs.AsReadOnly(); }
}
/// <summary>
/// Returns the transaction hash as you see them in the block explorer.
/// </summary>
public Sha256Hash Hash
{
get { return _hash ?? (_hash = new Sha256Hash(Utils.ReverseBytes(Utils.DoubleDigest(BitcoinSerialize())))); }
}
public string HashAsString
{
get { return Hash.ToString(); }
}
/// <summary>
/// Calculates the sum of the outputs that are sending coins to a key in the wallet. The flag controls whether to
/// include spent outputs or not.
/// </summary>
internal ulong GetValueSentToMe(Wallet wallet, bool includeSpent)
{
// This is tested in WalletTest.
var v = 0UL;
foreach (var o in _outputs)
{
if (!o.IsMine(wallet)) continue;
if (!includeSpent && !o.IsAvailableForSpending) continue;
v += o.Value;
}
return v;
}
/// <summary>
/// Calculates the sum of the outputs that are sending coins to a key in the wallet.
/// </summary>
public ulong GetValueSentToMe(Wallet wallet)
{
return GetValueSentToMe(wallet, true);
}
/// <summary>
/// Returns a set of blocks which contain the transaction, or null if this transaction doesn't have that data
/// because it's not stored in the wallet or because it has never appeared in a block.
/// </summary>
internal ICollection<StoredBlock> AppearsIn { get; private set; }
/// <summary>
/// Adds the given block to the internal serializable set of blocks in which this transaction appears. This is
/// used by the wallet to ensure transactions that appear on side chains are recorded properly even though the
/// block stores do not save the transaction data at all.
/// </summary>
internal void AddBlockAppearance(StoredBlock block)
{
if (AppearsIn == null)
{
AppearsIn = new HashSet<StoredBlock>();
}
AppearsIn.Add(block);
}
/// <summary>
/// Calculates the sum of the inputs that are spending coins with keys in the wallet. This requires the
/// transactions sending coins to those keys to be in the wallet. This method will not attempt to download the
/// blocks containing the input transactions if the key is in the wallet but the transactions are not.
/// </summary>
/// <returns>Sum in nanocoins.</returns>
/// <exception cref="BitCoinSharp.ScriptException" />
public ulong GetValueSentFromMe(Wallet wallet)
{
// This is tested in WalletTest.
var v = 0UL;
foreach (var input in _inputs)
{
// This input is taking value from an transaction in our wallet. To discover the value,
// we must find the connected transaction.
var connected = input.GetConnectedOutput(wallet.Unspent);
if (connected == null)
connected = input.GetConnectedOutput(wallet.Spent);
if (connected == null)
connected = input.GetConnectedOutput(wallet.Pending);
if (connected == null)
continue;
v += connected.Value;
}
return v;
}
internal bool DisconnectInputs()
{
var disconnected = false;
foreach (var input in _inputs)
{
disconnected |= input.Disconnect();
}
return disconnected;
}
/// <summary>
/// Connects all inputs using the provided transactions. If any input cannot be connected returns that input or
/// null on success.
/// </summary>
internal TransactionInput ConnectInputs(IDictionary<Sha256Hash, Transaction> transactions, bool disconnect)
{
foreach (var input in _inputs)
{
// Coinbase transactions, by definition, do not have connectable inputs.
if (input.IsCoinBase) continue;
if (input.Connect(transactions, disconnect) != TransactionInput.ConnectionResult.Success)
{
// Could not connect this input, so return it and abort.
return input;
}
}
return null;
}
/// <summary>
/// These constants are a part of a scriptSig signature on the inputs. They define the details of how a
/// transaction can be redeemed, specifically, they control how the hash of the transaction is calculated.
/// </summary>
/// <remarks>
/// In the official client, this enum also has another flag, SIGHASH_ANYONECANPAY. In this implementation,
/// that's kept separate. Only SIGHASH_ALL is actually used in the official client today. The other flags
/// exist to allow for distributed contracts.
/// </remarks>
public enum SigHash
{
All, // 1
None, // 2
Single, // 3
}
/// <exception cref="BitCoinSharp.ProtocolException" />
protected override void Parse()
{
_version = ReadUint32();
// First come the inputs.
var numInputs = ReadVarInt();
_inputs = new List<TransactionInput>((int) numInputs);
for (var i = 0UL; i < numInputs; i++)
{
var input = new TransactionInput(Params, this, Bytes, Cursor);
_inputs.Add(input);
Cursor += input.MessageSize;
}
// Now the outputs
var numOutputs = ReadVarInt();
_outputs = new List<TransactionOutput>((int) numOutputs);
for (var i = 0UL; i < numOutputs; i++)
{
var output = new TransactionOutput(Params, this, Bytes, Cursor);
_outputs.Add(output);
Cursor += output.MessageSize;
}
_lockTime = ReadUint32();
// Store a hash, it may come in useful later (want to avoid re-serialization costs).
_hash = new Sha256Hash(Utils.ReverseBytes(Utils.DoubleDigest(Bytes, Offset, Cursor - Offset)));
}
/// <summary>
/// A coinbase transaction is one that creates a new coin. They are the first transaction in each block and their
/// value is determined by a formula that all implementations of BitCoin share. In 2011 the value of a coinbase
/// transaction is 50 coins, but in future it will be less. A coinbase transaction is defined not only by its
/// position in a block but by the data in the inputs.
/// </summary>
public bool IsCoinBase
{
get { return _inputs[0].IsCoinBase; }
}
/// <returns>A human readable version of the transaction useful for debugging.</returns>
public override string ToString()
{
var s = new StringBuilder();
s.Append(" ");
s.Append(HashAsString);
s.AppendLine();
if (IsCoinBase)
{
var script = "???";
var script2 = "???";
try
{
script = _inputs[0].ScriptSig.ToString();
script2 = _outputs[0].ScriptPubKey.ToString();
}
catch (ScriptException)
{
}
return " == COINBASE TXN (scriptSig " + script + ") (scriptPubKey " + script2 + ")";
}
foreach (var @in in _inputs)
{
s.Append(" ");
s.Append("from ");
try
{
s.Append(@in.ScriptSig.FromAddress.ToString());
}
catch (Exception e)
{
s.Append("[exception: ").Append(e.Message).Append("]");
throw;
}
s.AppendLine();
}
foreach (var @out in _outputs)
{
s.Append(" ");
s.Append("to ");
try
{
var toAddr = new Address(Params, @out.ScriptPubKey.PubKeyHash);
s.Append(toAddr.ToString());
s.Append(" ");
s.Append(Utils.BitcoinValueToFriendlyString(@out.Value));
s.Append(" BTC");
}
catch (Exception e)
{
s.Append("[exception: ").Append(e.Message).Append("]");
}
s.AppendLine();
}
return s.ToString();
}
/// <summary>
/// Adds an input to this transaction that imports value from the given output. Note that this input is NOT
/// complete and after every input is added with addInput() and every output is added with addOutput(),
/// signInputs() must be called to finalize the transaction and finish the inputs off. Otherwise it won't be
/// accepted by the network.
/// </summary>
public void AddInput(TransactionOutput from)
{
_inputs.Add(new TransactionInput(Params, this, from));
}
internal void AddInput(TransactionInput input)
{
_inputs.Add(input);
}
/// <summary>
/// Adds the given output to this transaction. The output must be completely initialized.
/// </summary>
public void AddOutput(TransactionOutput to)
{
to.ParentTransaction = this;
_outputs.Add(to);
}
/// <summary>
/// Once a transaction has some inputs and outputs added, the signatures in the inputs can be calculated. The
/// signature is over the transaction itself, to prove the redeemer actually created that transaction,
/// so we have to do this step last.
/// </summary>
/// <remarks>
/// This method is similar to SignatureHash in script.cpp
/// </remarks>
/// <param name="hashType">This should always be set to SigHash.ALL currently. Other types are unused. </param>
/// <param name="wallet">A wallet is required to fetch the keys needed for signing.</param>
/// <exception cref="BitCoinSharp.ScriptException" />
public void SignInputs(SigHash hashType, Wallet wallet)
{
Debug.Assert(_inputs.Count > 0);
Debug.Assert(_outputs.Count > 0);
// I don't currently have an easy way to test other modes work, as the official client does not use them.
Debug.Assert(hashType == SigHash.All);
// The transaction is signed with the input scripts empty except for the input we are signing. In the case
// where addInput has been used to set up a new transaction, they are already all empty. The input being signed
// has to have the connected OUTPUT program in it when the hash is calculated!
//
// Note that each input may be claiming an output sent to a different key. So we have to look at the outputs
// to figure out which key to sign with.
var signatures = new byte[_inputs.Count][];
var signingKeys = new EcKey[_inputs.Count];
for (var i = 0; i < _inputs.Count; i++)
{
var input = _inputs[i];
Debug.Assert(input.ScriptBytes.Length == 0, "Attempting to sign a non-fresh transaction");
// Set the input to the script of its output.
input.ScriptBytes = input.Outpoint.ConnectedPubKeyScript;
// Find the signing key we'll need to use.
var connectedPubKeyHash = input.Outpoint.ConnectedPubKeyHash;
var key = wallet.FindKeyFromPubHash(connectedPubKeyHash);
// This assert should never fire. If it does, it means the wallet is inconsistent.
Debug.Assert(key != null, "Transaction exists in wallet that we cannot redeem: " + Utils.BytesToHexString(connectedPubKeyHash));
// Keep the key around for the script creation step below.
signingKeys[i] = key;
// The anyoneCanPay feature isn't used at the moment.
const bool anyoneCanPay = false;
var hash = HashTransactionForSignature(hashType, anyoneCanPay);
// Set the script to empty again for the next input.
input.ScriptBytes = TransactionInput.EmptyArray;
// Now sign for the output so we can redeem it. We use the keypair to sign the hash,
// and then put the resulting signature in the script along with the public key (below).
using (var bos = new MemoryStream())
{
bos.Write(key.Sign(hash));
bos.Write((byte) (((int) hashType + 1) | (anyoneCanPay ? 0x80 : 0)));
signatures[i] = bos.ToArray();
}
}
// Now we have calculated each signature, go through and create the scripts. Reminder: the script consists of
// a signature (over a hash of the transaction) and the complete public key needed to sign for the connected
// output.
for (var i = 0; i < _inputs.Count; i++)
{
var input = _inputs[i];
Debug.Assert(input.ScriptBytes.Length == 0);
var key = signingKeys[i];
input.ScriptBytes = Script.CreateInputScript(signatures[i], key.PubKey);
}
// Every input is now complete.
}
private byte[] HashTransactionForSignature(SigHash type, bool anyoneCanPay)
{
using (var bos = new MemoryStream())
{
BitcoinSerializeToStream(bos);
// We also have to write a hash type.
var hashType = (uint) type + 1;
if (anyoneCanPay)
hashType |= 0x80;
Utils.Uint32ToByteStreamLe(hashType, bos);
// Note that this is NOT reversed to ensure it will be signed correctly. If it were to be printed out
// however then we would expect that it is IS reversed.
return Utils.DoubleDigest(bos.ToArray());
}
}
/// <summary>
/// Given a named input and the transaction output it connects to, runs the script formed from the
/// concatenation of the input and output scripts, returning true if the link is valid. In
/// this way, we prove that the creator of this transaction is allowed to redeem the output
/// of the connectedTx and thus spend the money.
/// </summary>
/// <remarks>
/// <b>WARNING: NOT FINISHED</b><p />
/// </remarks>
/// <param name="inputIndex">Which input to verify.</param>
/// <param name="connectedTx">The Transaction that the input is connected to.</param>
/// <exception cref="BitCoinSharp.ScriptException" />
public bool VerifyInput(int inputIndex, Transaction connectedTx)
{
var input = _inputs[inputIndex];
var inScript = input.ScriptSig;
var pubkey = inScript.PubKey;
return false;
}
/// <exception cref="System.IO.IOException" />
public override void BitcoinSerializeToStream(Stream stream)
{
Utils.Uint32ToByteStreamLe(_version, stream);
stream.Write(new VarInt((ulong) _inputs.Count).Encode());
foreach (var @in in _inputs)
@in.BitcoinSerializeToStream(stream);
stream.Write(new VarInt((ulong) _outputs.Count).Encode());
foreach (var @out in _outputs)
@out.BitcoinSerializeToStream(stream);
Utils.Uint32ToByteStreamLe(_lockTime, stream);
}
public override bool Equals(object other)
{
if (!(other is Transaction)) return false;
var t = (Transaction) other;
return t.Hash.Equals(Hash);
}
public override int GetHashCode()
{
var hash = Hash.Hash;
return hash != null ? hash.Aggregate(1, (current, element) => 31*current + element) : 0;
}
}
} | 42.075 | 144 | 0.568776 | [
"Apache-2.0"
] | CoiniumServ/BitcoinSharp | tags/0.2/Core/Transaction.cs | 20,196 | C# |
// c:\program files (x86)\windows kits\10\include\10.0.18362.0\um\d3d10.h(3235,5)
using System;
using System.Runtime.InteropServices;
namespace DirectN
{
[Guid("9b7e4c09-342c-4106-a19f-4f2704f689f0"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public partial interface ID3D10DepthStencilView : ID3D10View
{
// ID3D10DeviceChild
[PreserveSig]
new void GetDevice(/* [annotation] _Out_ */ out ID3D10Device ppDevice);
[PreserveSig]
new HRESULT GetPrivateData(/* [annotation] _In_ */ [MarshalAs(UnmanagedType.LPStruct)] Guid guid, /* [annotation] _Inout_ */ ref uint pDataSize, /* optional(void) */ IntPtr pData);
[PreserveSig]
new HRESULT SetPrivateData(/* [annotation] _In_ */ [MarshalAs(UnmanagedType.LPStruct)] Guid guid, /* [annotation] _In_ */ uint DataSize, /* optional(void) */ IntPtr pData);
[PreserveSig]
new HRESULT SetPrivateDataInterface(/* [annotation] _In_ */ [MarshalAs(UnmanagedType.LPStruct)] Guid guid, /* optional(IUnknown) */ IntPtr pData);
// ID3D10View
[PreserveSig]
new void GetResource(/* [annotation] _Out_ */ out ID3D10Resource ppResource);
// ID3D10DepthStencilView
[PreserveSig]
void GetDesc(/* [annotation] _Out_ */ out D3D10_DEPTH_STENCIL_VIEW_DESC pDesc);
}
}
| 43.125 | 188 | 0.664493 | [
"MIT"
] | bbday/DirectN | DirectN/DirectN/Generated/ID3D10DepthStencilView.cs | 1,382 | C# |
using UnityEngine;
using UnityEditor;
using UnityEditor.ProBuilder.UI;
using System.Linq;
using UnityEngine.ProBuilder.Stl;
using UnityEngine.ProBuilder;
using UnityEditor.ProBuilder;
namespace UnityEditor.ProBuilder.Actions
{
sealed class ExportStlBinary : MenuAction
{
public override ToolbarGroup group { get { return ToolbarGroup.Export; } }
public override Texture2D icon { get { return null; } }
public override TooltipContent tooltip { get { return _tooltip; } }
static readonly TooltipContent _tooltip = new TooltipContent
(
"Export Stl",
@"Export an Stl model file."
);
public override bool hidden
{
get { return true; }
}
public override bool enabled
{
get { return Selection.gameObjects != null && Selection.gameObjects.Length > 0; }
}
public override ActionResult DoAction()
{
var res = ExportStlAscii.ExportWithFileDialog(Selection.gameObjects, FileType.Binary);
if (string.IsNullOrEmpty(res))
return new ActionResult(ActionResult.Status.Canceled, "User Canceled");
Export.PingExportedModel(res);
return new ActionResult(ActionResult.Status.Success, "Export STL");
}
}
}
| 29.391304 | 98 | 0.632396 | [
"MIT"
] | ASE-Blast/unity3dgames | Space Game/Library/PackageCache/com.unity.probuilder@4.1.2/Editor/MenuActions/Export/ExportStlBinary.cs | 1,352 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
namespace Microsoft.Protocols.TestManager.Kernel
{
public delegate void ContentModifiedEventHandler();
/// <summary>
/// PTFConfig file.
/// </summary>
public class PtfConfig
{
// ConfigNode Tree root according to ptfconfig files
public PtfProperty PtfPropertyRoot { get; set; }
/// <summary>
/// The name of Configfile.
/// </summary>
public List<string> ConfigFileNames { get; set; }
public Dictionary<string, List<string>> FileProperties;
//xml document name list
public List<XmlDocument> XmlDocList { get; set; }
/// <summary>
/// Constructor of PtfConfig
/// </summary>
/// <param name="activeConfigFile">A list of active configfile</param>
/// <param name="defaultConfigFile">A list of default configfile</param>
public PtfConfig(List<string> activeConfigFile, List<string> defaultConfigFile)
{
ConfigFileNames = activeConfigFile;
List<string> DefaultConfigFileNames = defaultConfigFile;
XmlDocList = new List<XmlDocument>();
//Deal with config file in Env file
PtfProperty DefaultPtfPropertyRoot = new PtfProperty();
Merge(DefaultConfigFileNames, DefaultPtfPropertyRoot);
AdjustDefaultGroup(DefaultPtfPropertyRoot);
XmlDocList = new List<XmlDocument>();
//Deal with config file in Bin file
PtfPropertyRoot = new PtfProperty();
FileProperties = Merge(ConfigFileNames, PtfPropertyRoot);
AdjustDefaultGroup(PtfPropertyRoot);
//Set Env value as default value
SetDefaultValues(DefaultPtfPropertyRoot);
}
/// <summary>
/// Save changes back to ptfconfig file in bin folder.
/// </summary>
/// <returns></returns>
public void Save(string path)
{
for (int k = 0; k < ConfigFileNames.Count; k++)
{
string fileName = Path.GetFileName(ConfigFileNames[k]);
fileName = Path.Combine(path, fileName);
Utility.RemoveReadonly(fileName);
XmlDocList[k].Save(fileName);
}
}
/// <summary>
/// Merges PTFConfig files
/// </summary>
/// <param name="configFileNames">PTFConfig file names</param>
/// <param name="RootNode">PTF property tree</param>
/// <returns>Filename-property list dictionary</returns>
public Dictionary<string, List<string>> Merge(List<string> configFileNames, PtfProperty RootNode)
{
Dictionary<string, List<string>> propertyMap = new Dictionary<string, List<string>>();
try
{
if (configFileNames == null)
{
throw new ArgumentException(StringResource.ConfigFileNameNotSpecified);
}
//Create an XmlNamespaceManager for resolving namespaces.
XmlNamespaceManager nsmgr = new XmlNamespaceManager(new NameTable());
nsmgr.AddNamespace("tc", StringResource.DefaultNamespace);
foreach (string configFileName in configFileNames)
{
if (configFileName == null)
continue;
XmlDocument doc = new XmlDocument();
doc.XmlResolver = null;
XmlReaderSettings settings = new XmlReaderSettings();
settings.XmlResolver = null;
settings.DtdProcessing = DtdProcessing.Prohibit;
using (var xmlReader = XmlReader.Create(configFileName, settings))
{
doc.Load(xmlReader);
//record each xmldoc for Config node to refer to
XmlDocList.Add(doc);
//Properties
XmlNode node = doc.DocumentElement.SelectSingleNode("tc:Properties", nsmgr);
string filename = System.IO.Path.GetFileName(configFileName);
propertyMap[filename] = new List<string>();
Stack<string> parent = new Stack<string>();
Stack<XmlNode> nodes = new Stack<XmlNode>();
foreach (XmlNode child in node.ChildNodes)
{
string propertyName = "";
if (child.NodeType == XmlNodeType.Element)
{
propertyName = child.Attributes["name"].Value;
if (child.Name == "Property")
{
propertyMap[filename].Add(propertyName);
}
else if (child.Name == "Group")
{
foreach (XmlNode subChild in child.ChildNodes)
{
if (subChild.NodeType == XmlNodeType.Element)
{
parent.Push(child.Attributes["name"].Value);
nodes.Push(subChild);
}
}
}
}
}
while (nodes.Count > 0)
{
var n = nodes.Pop();
var p = parent.Pop();
if (n.Name == "Property")
{
propertyMap[filename].Add(string.Format("{0}.{1}", p, n.Attributes["name"].Value));
}
else if (n.Name == "Group")
{
foreach (XmlNode child in n.ChildNodes)
{
if (child.NodeType == XmlNodeType.Element)
{
parent.Push(string.Format("{0}.{1}", p, n.Attributes["name"].Value));
nodes.Push(child);
}
}
}
}
MergePropertyAndGroup(RootNode, node);
}
}
LoadAdapters();
}
catch (XmlException e)
{
throw new XmlException("Merge Exception" + e);
}
return propertyMap;
}
public Dictionary<string, XmlNode> adapterTable;
public Dictionary<string, XmlDocument> adapterDocTable;
private void LoadAdapters()
{
XmlNamespaceManager nsmgr = new XmlNamespaceManager(new NameTable());
nsmgr.AddNamespace("tc", StringResource.DefaultNamespace);
adapterTable = new Dictionary<string, XmlNode>();
adapterDocTable = new Dictionary<string, XmlDocument>();
foreach (XmlDocument doc in XmlDocList)
{
XmlNode adapterNode = doc.SelectSingleNode("tc:TestSite/tc:Adapters", nsmgr);
if (adapterNode == null) continue;
foreach (XmlNode adapter in adapterNode.SelectNodes("tc:Adapter", nsmgr))
{
adapterTable[adapter.Attributes["name"].Value] = adapter;
adapterDocTable[adapter.Attributes["name"].Value] = doc;
}
}
}
/// <summary>
/// recurrsively create Config Node tree from ptfconfig file
/// </summary>
/// <param name="baseConfigNode"></param>
/// <param name="root"></param>
private void MergePropertyAndGroup(PtfProperty baseConfigNode, XmlNode root)
{
Dictionary<string, XmlNode> propertyDict = new Dictionary<string, XmlNode>();
Dictionary<string, XmlNode> groupDict = new Dictionary<string, XmlNode>();
string value = "";
//to sort Group node before Property node
//record the pos of first Property node. If no Propert, default value is -1
int propertyPos = -1;
foreach (XmlNode child in root.ChildNodes)
{
if (child.NodeType == XmlNodeType.Element)
{
value = child.Attributes["name"].Value;
if (child.Name == "Property")
{
if (propertyDict.ContainsKey(value))
throw new InvalidOperationException(
string.Format(StringResource.DuplicatePTFConfigNode, child.Name, value));
propertyDict.Add(value, child);
}
else
{
if (groupDict.ContainsKey(value))
throw new InvalidOperationException(
string.Format(StringResource.DuplicatePTFConfigNode, child.Name, value));
groupDict.Add(value, child);
}
}
}
//Merge Group First
foreach (XmlNode child in groupDict.Values)
{
bool duplicate = false;
PtfProperty config = null;
for (int i = 0; i < baseConfigNode.Count; i++)
{
if (baseConfigNode[i].ValueType != PtfPropertyType.Group && propertyPos == -1)
{
propertyPos = i;
}
if (baseConfigNode[i].ValueType == PtfPropertyType.Group && baseConfigNode[i].Name == child.Attributes["name"].Value)
{
duplicate = true;
config = baseConfigNode[i];
break;
}
}
if (duplicate)
{
//duplicate, first merge Group Node's Attribute
//Recurrsively Merge Property and Group to create data structure
if (child.Attributes["description"] != null)
{
config.Description = child.Attributes["description"].Value;
config.RefXmlNode = child;
}
MergePropertyAndGroup(config, child);
}
else
{
//create new Group Node
//Insert Group before Property
//Recurrsively Merge Property and Group to create data structure
PtfProperty newGroup = new PtfProperty(child, true);
if (propertyPos >= 0)
{
baseConfigNode.Insert(propertyPos, newGroup);
propertyPos++;
}
else
{
baseConfigNode.Add(newGroup);
}
MergePropertyAndGroup(newGroup, child);
}
}
//Merge Property
foreach (XmlNode child in propertyDict.Values)
{
bool duplicate = false;
PtfProperty config = null;
foreach (PtfProperty childConfig in baseConfigNode)
{
if (childConfig.ValueType != PtfPropertyType.Group && childConfig.Name == child.Attributes["name"].Value)
{
duplicate = true;
config = childConfig;
break;
}
}
//First remove old node
if (duplicate)
{
baseConfigNode.Remove(config);
}
//Insert new node
PtfProperty newProperty = new PtfProperty(child, false);
baseConfigNode.Add(newProperty);
}
groupDict.Clear();
propertyDict.Clear();
}
/// <summary>
/// Set Propert under Properties node into DefaultGroup
/// </summary>
public void AdjustDefaultGroup(PtfProperty RootNode)
{
PtfProperty defaultGroup = new PtfProperty()
{
Name = StringResource.DefaultGroupName,
Description = "",
ValueType = PtfPropertyType.Group
};
for (int i = 0; i < RootNode.Count; i++)
{
if (RootNode[i].ValueType != PtfPropertyType.Group)
{
defaultGroup.Add(RootNode[i]);
RootNode.RemoveAt(i);
i--;
}
}
//Set DefaultGroup node to be the first one
RootNode.Insert(0, defaultGroup);
}
/// <summary>
/// Set Environment config as default value
/// </summary>
private void SetDefaultValues(PtfProperty DefaultPropertyRoot)
{
Stack<PtfProperty> ConfigStack = new Stack<PtfProperty>();
ConfigStack.Push(PtfPropertyRoot);
while (ConfigStack.Count > 0)
{
PtfProperty topNode = ConfigStack.Pop();
string defaultValue = GetDefaultValueByName(DefaultPropertyRoot, topNode.Name);
topNode.DefaultValue = defaultValue;
foreach (PtfProperty cn in topNode)
{
ConfigStack.Push(cn);
}
}
}
private string GetDefaultValueByName(PtfProperty root, string NodeName)
{
Stack<PtfProperty> ConfigStack = new Stack<PtfProperty>();
ConfigStack.Push(root);
while (ConfigStack.Count > 0)
{
PtfProperty topNode = ConfigStack.Pop();
if (topNode.Name == NodeName)
{
return topNode.Value;
}
foreach (PtfProperty cn in topNode)
{
ConfigStack.Push(cn);
}
}
return "";
}
/// <summary>
/// Sets the property value.
/// </summary>
/// <param name="propertyName">The property name</param>
/// <param name="propertyValue">A list of property values</param>
/// <returns></returns>
public bool SetPropertyValue(string propertyName, List<string> propertyValue)
{
if (propertyValue.Count == 0) return false;
PtfProperty propertyNode = GetPropertyNodeByName(propertyName);
if (propertyNode == null) return false;
return true;
}
/// <summary>
/// Gets the PtfProperty instance from a property name.
/// </summary>
/// <param name="propertyName">property name</param>
/// <returns>The PtfProperty</returns>
public PtfProperty GetPropertyNodeByName(string propertyName)
{
string searchName = "." + propertyName;
string[] groups = propertyName.Split('.');
//Property
Stack<PtfProperty> s = new Stack<PtfProperty>();
//Base
Stack<string> b = new Stack<string>();
foreach (PtfProperty p in PtfPropertyRoot)
{
// Move all the properties under Default Group to the root.
if (p.Name == StringResource.DefaultGroupName)
{
foreach (PtfProperty child in p)
{
s.Push(child);
b.Push("");
}
}
else
{
s.Push(p);
b.Push("");
}
}
while(s.Count> 0)
{
PtfProperty p = s.Pop();
string n = b.Pop();
if (p.ValueType == PtfPropertyType.Group)
{
foreach (PtfProperty child in p)
{
s.Push(child);
b.Push(n + "." + p.Name);
}
}
else
{
if (n + "." + p.Name == searchName) return p;
}
}
return null;
}
/// <summary>
/// Creates PtfPropertyView
/// </summary>
/// <param name="hideProperties">Hide properties.</param>
/// <returns>An instance of PtfPropertyView</returns>
public PtfPropertyView CreatePtfPropertyView(List<string> hideProperties)
{
List<PtfProperty> hide = new List<PtfProperty>();
foreach (string name in hideProperties)
{
PtfProperty p = GetPropertyNodeByName(name);
if (p != null) hide.Add(p);
}
// Root Group
PtfPropertyRoot.ValueType = PtfPropertyType.Group;
PtfPropertyView propertyView = new PtfPropertyView(PtfPropertyRoot);
Stack<TreeStackItem> propertyStack = new Stack<TreeStackItem>();
propertyStack.Push(new TreeStackItem(PtfPropertyRoot, propertyView));
while (propertyStack.Count > 0)
{
TreeStackItem p = propertyStack.Pop();
if (p.PropertyNode.ValueType != PtfPropertyType.Group)
{
if (hide.Contains(p.PropertyNode)) continue;
var view = new PtfPropertyView(p.PropertyNode, p.PathFrom(3));
p.PropertyView.Add(view);
}
else
{
PtfPropertyView view;
if (p.Path.Count <= 2)
{
view = new PtfPropertyView(p.PropertyNode);
p.PropertyView.Add(view);
}
else view = p.PropertyView;
for (int i = p.PropertyNode.Count - 1; i >= 0; i--)
{
var child = p.PropertyNode[i];
TreeStackItem c = new TreeStackItem(
child,
view);
c.Path.InsertRange(0, p.Path);
c.Path.Add(p.PropertyNode.Name);
propertyStack.Push(c);
}
}
}
var v = propertyView[0];
// Remove empty view
for (int i = 0; i < v.Count; i++)
{
if (v[i].IsEmptyGroup)
{
v.RemoveAt(i);
i--;
continue;
}
var childv = v[i];
for (int ii = 0; ii < childv.Count; ii++)
{
if (childv[ii].IsEmptyGroup)
{
childv.RemoveAt(ii);
ii--;
}
}
}
return v;
}
/// <summary>
/// Applies the adapter config.
/// </summary>
/// <param name="adapter">the adapter config</param>
public void ApplyAdapterConfig(IAdapterConfig adapter)
{
XmlDocument doc = adapterDocTable[adapter.Name];
XmlNamespaceManager nsmgr = new XmlNamespaceManager(new NameTable());
nsmgr.AddNamespace("tc", StringResource.DefaultNamespace);
XmlNode adapterNode = doc.SelectSingleNode("tc:TestSite/tc:Adapters", nsmgr);
XmlNode node = adapter.CreateXmlNode(doc);
adapterNode.RemoveChild(adapterTable[adapter.Name]);
adapterNode.AppendChild(node);
adapterTable[adapter.Name] = node;
}
}
class TreeStackItem
{
public PtfProperty PropertyNode;
public PtfPropertyView PropertyView;
public List<string> Path;
public TreeStackItem(PtfProperty node, PtfPropertyView view)
{
PropertyNode = node;
PropertyView = view;
Path = new List<string>();
}
public string PathFrom(int index)
{
StringBuilder sb = new StringBuilder();
for (int i = index; i < Path.Count; i++)
{
sb.AppendFormat(".{0}", Path[i]);
}
return sb.ToString().Trim(new char[] { '.' });
}
}
}
| 38.894353 | 137 | 0.46799 | [
"MIT"
] | 0neb1n/WindowsProtocolTestSuites | ProtocolTestManager/Kernel/PtfConfig/PtfConfig.cs | 21,355 | C# |
#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
using System;
using Org.BouncyCastle.Math.Raw;
namespace Org.BouncyCastle.Math.EC.Custom.Sec
{
internal class SecP192R1Point
: AbstractFpPoint
{
/**
* Create a point which encodes with point compression.
*
* @param curve
* the curve to use
* @param x
* affine x co-ordinate
* @param y
* affine y co-ordinate
*
* @deprecated Use ECCurve.createPoint to construct points
*/
public SecP192R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y)
: this(curve, x, y, false)
{
}
/**
* Create a point that encodes with or without point compresion.
*
* @param curve
* the curve to use
* @param x
* affine x co-ordinate
* @param y
* affine y co-ordinate
* @param withCompression
* if true encode with point compression
*
* @deprecated per-point compression property will be removed, refer
* {@link #getEncoded(bool)}
*/
public SecP192R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, bool withCompression)
: base(curve, x, y, withCompression)
{
if ((x == null) != (y == null))
throw new ArgumentException("Exactly one of the field elements is null");
}
internal SecP192R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression)
: base(curve, x, y, zs, withCompression)
{
}
protected override ECPoint Detach()
{
return new SecP192R1Point(null, AffineXCoord, AffineYCoord);
}
public override ECPoint Add(ECPoint b)
{
if (this.IsInfinity)
return b;
if (b.IsInfinity)
return this;
if (this == b)
return Twice();
ECCurve curve = this.Curve;
SecP192R1FieldElement X1 = (SecP192R1FieldElement)this.RawXCoord, Y1 = (SecP192R1FieldElement)this.RawYCoord;
SecP192R1FieldElement X2 = (SecP192R1FieldElement)b.RawXCoord, Y2 = (SecP192R1FieldElement)b.RawYCoord;
SecP192R1FieldElement Z1 = (SecP192R1FieldElement)this.RawZCoords[0];
SecP192R1FieldElement Z2 = (SecP192R1FieldElement)b.RawZCoords[0];
uint c;
uint[] tt1 = Nat192.CreateExt();
uint[] t2 = Nat192.Create();
uint[] t3 = Nat192.Create();
uint[] t4 = Nat192.Create();
bool Z1IsOne = Z1.IsOne;
uint[] U2, S2;
if (Z1IsOne)
{
U2 = X2.x;
S2 = Y2.x;
}
else
{
S2 = t3;
SecP192R1Field.Square(Z1.x, S2);
U2 = t2;
SecP192R1Field.Multiply(S2, X2.x, U2);
SecP192R1Field.Multiply(S2, Z1.x, S2);
SecP192R1Field.Multiply(S2, Y2.x, S2);
}
bool Z2IsOne = Z2.IsOne;
uint[] U1, S1;
if (Z2IsOne)
{
U1 = X1.x;
S1 = Y1.x;
}
else
{
S1 = t4;
SecP192R1Field.Square(Z2.x, S1);
U1 = tt1;
SecP192R1Field.Multiply(S1, X1.x, U1);
SecP192R1Field.Multiply(S1, Z2.x, S1);
SecP192R1Field.Multiply(S1, Y1.x, S1);
}
uint[] H = Nat192.Create();
SecP192R1Field.Subtract(U1, U2, H);
uint[] R = t2;
SecP192R1Field.Subtract(S1, S2, R);
// Check if b == this or b == -this
if (Nat192.IsZero(H))
{
if (Nat192.IsZero(R))
{
// this == b, i.e. this must be doubled
return this.Twice();
}
// this == -b, i.e. the result is the point at infinity
return curve.Infinity;
}
uint[] HSquared = t3;
SecP192R1Field.Square(H, HSquared);
uint[] G = Nat192.Create();
SecP192R1Field.Multiply(HSquared, H, G);
uint[] V = t3;
SecP192R1Field.Multiply(HSquared, U1, V);
SecP192R1Field.Negate(G, G);
Nat192.Mul(S1, G, tt1);
c = Nat192.AddBothTo(V, V, G);
SecP192R1Field.Reduce32(c, G);
SecP192R1FieldElement X3 = new SecP192R1FieldElement(t4);
SecP192R1Field.Square(R, X3.x);
SecP192R1Field.Subtract(X3.x, G, X3.x);
SecP192R1FieldElement Y3 = new SecP192R1FieldElement(G);
SecP192R1Field.Subtract(V, X3.x, Y3.x);
SecP192R1Field.MultiplyAddToExt(Y3.x, R, tt1);
SecP192R1Field.Reduce(tt1, Y3.x);
SecP192R1FieldElement Z3 = new SecP192R1FieldElement(H);
if (!Z1IsOne)
{
SecP192R1Field.Multiply(Z3.x, Z1.x, Z3.x);
}
if (!Z2IsOne)
{
SecP192R1Field.Multiply(Z3.x, Z2.x, Z3.x);
}
ECFieldElement[] zs = new ECFieldElement[] { Z3 };
return new SecP192R1Point(curve, X3, Y3, zs, IsCompressed);
}
public override ECPoint Twice()
{
if (this.IsInfinity)
return this;
ECCurve curve = this.Curve;
SecP192R1FieldElement Y1 = (SecP192R1FieldElement)this.RawYCoord;
if (Y1.IsZero)
return curve.Infinity;
SecP192R1FieldElement X1 = (SecP192R1FieldElement)this.RawXCoord, Z1 = (SecP192R1FieldElement)this.RawZCoords[0];
uint c;
uint[] t1 = Nat192.Create();
uint[] t2 = Nat192.Create();
uint[] Y1Squared = Nat192.Create();
SecP192R1Field.Square(Y1.x, Y1Squared);
uint[] T = Nat192.Create();
SecP192R1Field.Square(Y1Squared, T);
bool Z1IsOne = Z1.IsOne;
uint[] Z1Squared = Z1.x;
if (!Z1IsOne)
{
Z1Squared = t2;
SecP192R1Field.Square(Z1.x, Z1Squared);
}
SecP192R1Field.Subtract(X1.x, Z1Squared, t1);
uint[] M = t2;
SecP192R1Field.Add(X1.x, Z1Squared, M);
SecP192R1Field.Multiply(M, t1, M);
c = Nat192.AddBothTo(M, M, M);
SecP192R1Field.Reduce32(c, M);
uint[] S = Y1Squared;
SecP192R1Field.Multiply(Y1Squared, X1.x, S);
c = Nat.ShiftUpBits(6, S, 2, 0);
SecP192R1Field.Reduce32(c, S);
c = Nat.ShiftUpBits(6, T, 3, 0, t1);
SecP192R1Field.Reduce32(c, t1);
SecP192R1FieldElement X3 = new SecP192R1FieldElement(T);
SecP192R1Field.Square(M, X3.x);
SecP192R1Field.Subtract(X3.x, S, X3.x);
SecP192R1Field.Subtract(X3.x, S, X3.x);
SecP192R1FieldElement Y3 = new SecP192R1FieldElement(S);
SecP192R1Field.Subtract(S, X3.x, Y3.x);
SecP192R1Field.Multiply(Y3.x, M, Y3.x);
SecP192R1Field.Subtract(Y3.x, t1, Y3.x);
SecP192R1FieldElement Z3 = new SecP192R1FieldElement(M);
SecP192R1Field.Twice(Y1.x, Z3.x);
if (!Z1IsOne)
{
SecP192R1Field.Multiply(Z3.x, Z1.x, Z3.x);
}
return new SecP192R1Point(curve, X3, Y3, new ECFieldElement[] { Z3 }, IsCompressed);
}
public override ECPoint TwicePlus(ECPoint b)
{
if (this == b)
return ThreeTimes();
if (this.IsInfinity)
return b;
if (b.IsInfinity)
return Twice();
ECFieldElement Y1 = this.RawYCoord;
if (Y1.IsZero)
return b;
return Twice().Add(b);
}
public override ECPoint ThreeTimes()
{
if (this.IsInfinity || this.RawYCoord.IsZero)
return this;
// NOTE: Be careful about recursions between TwicePlus and ThreeTimes
return Twice().Add(this);
}
public override ECPoint Negate()
{
if (IsInfinity)
return this;
return new SecP192R1Point(Curve, RawXCoord, RawYCoord.Negate(), RawZCoords, IsCompressed);
}
}
}
#endif
| 31.806338 | 126 | 0.488763 | [
"MIT"
] | czlsy009/UnityAppMVCFramework | Framework/Assets/SilenceFramework/Libs/Best HTTP (Pro)/BestHTTP/SecureProtocol/math/ec/custom/sec/SecP192R1Point.cs | 9,033 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Script.Serialization;
namespace WindowsFormsApplication1
{
public class ValueChecker
{
public int Value(int input)
{
int betrag = 0;
if (input == 0)
{
betrag = 150;
}
else if (input < 1000)
{
betrag = 50;
}
else if (input < 10000)
{
betrag = 100;
}
else if (input < 50000)
{
betrag = 250;
}
else if (input < 100000)
{
betrag = 500;
}
else if (input >= 100000)
{
betrag = 1000;
}
return betrag;
}
public double AveragePrice(string search, string resId)
{
var check = true;
List<int> buyNowPrice = new List<int>();
List<int> avg = new List<int>();
Player_AuctionInfo.RootObject returnedAuctions = new JavaScriptSerializer().Deserialize<Player_AuctionInfo.RootObject>(search);
foreach (var item in returnedAuctions.auctionInfo)
{
if (resId == item.itemData.resourceId)
{
buyNowPrice.Add(item.buyNowPrice);
}
}
double average = 0;
if (buyNowPrice.Count != 0)
{
for (int v = 0; v < 3; v++)
{
//System.Windows.Forms.MessageBox.Show(buyNowPrice.Count().ToString());
var lowestPrice = 15000000;
var hilf = 0;
for (int i = 0; i < buyNowPrice.Count; i++)
{
if (buyNowPrice[i] <= lowestPrice && buyNowPrice[i] != 0)
{
lowestPrice = buyNowPrice[i];
hilf = i;
}
}
//System.Windows.Forms.MessageBox.Show(lowestPrice.ToString() + "; " + hilf);
avg.Add(lowestPrice);
if (hilf != 0)
{
buyNowPrice.RemoveAt(hilf);
}
else
{
check = false;
}
}
average = check ? avg.Average() : 0;
}
return average;
}
public int RoundPrice(double input)
{
int temp;
if (input <= 1000)
{
temp = (int)Math.Round(input / 50.0) * 50;
}
else if (input <= 10000)
{
temp = (int)Math.Round(input / 100.0) * 100;
}
else if (input <= 50000)
{
temp = (int)Math.Round(input / 250.0) * 250;
}
else if (input <= 50000)
{
temp = (int)Math.Round(input / 500.0) * 500;
}
else
{
temp = (int)Math.Round(input / 1000.0) * 1000;
}
return temp;
}
public int ValueSell(int input)
{
int betrag = 0;
if (input <= 1000)
{
betrag = 50;
}
else if (input <= 10000)
{
betrag = 100;
}
else if (input <= 50000)
{
betrag = 250;
}
else if (input <= 100000)
{
betrag = 500;
}
else if (input >= 100000)
{
betrag = 1000;
}
return betrag;
}
}
}
| 27.892857 | 139 | 0.370038 | [
"MIT"
] | igeligel/Fifa13UltimateTeamAutobuyer | FUT 13 Autobuyer/ValueChecker.cs | 3,907 | C# |
using System.Drawing;
namespace DJMaxEditor.Controls.Editor.Renderers.Zones.Trilogy
{
internal class Trilogy7kZoneRenderer : ZoneRenderer
{
public override void DrawZones(GraphicsWrapper g, int trackIndex, int trackX, int trackY, int width, int height, Rectangle bounds)
{
DrawZone(g, trackIndex, trackX, trackY, width, height, bounds, CustomBrushes.Player1Visible, "7 Keys", 3, 7);
DrawZone(g, trackIndex, trackX, trackY, width, height, bounds, CustomBrushes.Player1Visible, "7 Keys", 10, 11);
}
public override string GetName()
{
return "Trilogy 7 keys";
}
}
}
| 34.842105 | 138 | 0.65861 | [
"Apache-2.0"
] | hsreina/DJMax-Editor | DJMaxEditor/Controls/Editor/Renderers/Zones/Trilogy/Trilogy7kZoneRenderer.cs | 664 | C# |
using PnP.Framework.Extensions;
using System;
using System.Collections.Generic;
namespace PnP.Framework.Provisioning.Providers.Xml.Resolvers.V201705
{
/// <summary>
/// Resolves the IRM Settings of a List from Schema to Domain Model
/// </summary>
internal class IRMSettingsFromSchemaToModelTypeResolver : ITypeResolver
{
public string Name => this.GetType().Name;
public bool CustomCollectionResolver => true;
public IRMSettingsFromSchemaToModelTypeResolver()
{
}
public object Resolve(object source, Dictionary<String, IResolver> resolvers = null, Boolean recursive = false)
{
Object result = null;
var irmSettings = source.GetPublicInstancePropertyValue("IRMSettings");
if (null != irmSettings)
{
result = new Model.IRMSettings();
PnPObjectsMapper.MapProperties(irmSettings, result, resolvers, recursive);
}
return (result);
}
}
}
| 29.514286 | 119 | 0.638916 | [
"MIT"
] | Arturiby/pnpframework | src/lib/PnP.Framework/Provisioning/Providers/Xml/Resolvers/V201705/IRMSettingsFromSchemaToModelTypeResolver.cs | 1,035 | C# |
// SF API version v50.0
// Custom fields included: False
// Relationship objects included: True
using System;
using NetCoreForce.Client.Models;
using NetCoreForce.Client.Attributes;
using Newtonsoft.Json;
namespace NetCoreForce.Models
{
///<summary>
/// Field Security Classification
///<para>SObject Name: FieldSecurityClassification</para>
///<para>Custom Object: False</para>
///</summary>
public class SfFieldSecurityClassification : SObject
{
[JsonIgnore]
public static string SObjectTypeName
{
get { return "FieldSecurityClassification"; }
}
///<summary>
/// Field Security Classification ID
/// <para>Name: Id</para>
/// <para>SF Type: id</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "id")]
[Updateable(false), Createable(false)]
public string Id { get; set; }
///<summary>
/// Master Label
/// <para>Name: MasterLabel</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "masterLabel")]
[Updateable(false), Createable(false)]
public string MasterLabel { get; set; }
///<summary>
/// Api Name
/// <para>Name: ApiName</para>
/// <para>SF Type: string</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "apiName")]
[Updateable(false), Createable(false)]
public string ApiName { get; set; }
///<summary>
/// Sort Order
/// <para>Name: SortOrder</para>
/// <para>SF Type: int</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "sortOrder")]
[Updateable(false), Createable(false)]
public int? SortOrder { get; set; }
///<summary>
/// Description
/// <para>Name: Description</para>
/// <para>SF Type: textarea</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "description")]
[Updateable(false), Createable(false)]
public string Description { get; set; }
///<summary>
/// High-Risk Level
/// <para>Name: IsHighRiskLevel</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isHighRiskLevel")]
[Updateable(false), Createable(false)]
public bool? IsHighRiskLevel { get; set; }
///<summary>
/// Created By ID
/// <para>Name: CreatedById</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "createdById")]
[Updateable(false), Createable(false)]
public string CreatedById { get; set; }
///<summary>
/// ReferenceTo: User
/// <para>RelationshipName: CreatedBy</para>
///</summary>
[JsonProperty(PropertyName = "createdBy")]
[Updateable(false), Createable(false)]
public SfUser CreatedBy { get; set; }
///<summary>
/// Created Date
/// <para>Name: CreatedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "createdDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? CreatedDate { get; set; }
///<summary>
/// Last Modified By ID
/// <para>Name: LastModifiedById</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "lastModifiedById")]
[Updateable(false), Createable(false)]
public string LastModifiedById { get; set; }
///<summary>
/// ReferenceTo: User
/// <para>RelationshipName: LastModifiedBy</para>
///</summary>
[JsonProperty(PropertyName = "lastModifiedBy")]
[Updateable(false), Createable(false)]
public SfUser LastModifiedBy { get; set; }
///<summary>
/// Last Modified Date
/// <para>Name: LastModifiedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "lastModifiedDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? LastModifiedDate { get; set; }
///<summary>
/// System Modstamp
/// <para>Name: SystemModstamp</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "systemModstamp")]
[Updateable(false), Createable(false)]
public DateTimeOffset? SystemModstamp { get; set; }
}
}
| 27.993464 | 58 | 0.65795 | [
"MIT"
] | Mintish/NetCoreForce | src/NetCoreForce.Models/SfFieldSecurityClassification.cs | 4,283 | C# |
#region License
/*
Copyright © 2014-2021 European Support Limited
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.
*/
#endregion
using System;
using System.Windows;
namespace Ginger.UserControlsLib.PieChart
{
public static class Utils
{
/// <summary>
/// Converts a coordinate from the polar coordinate system to the cartesian coordinate system.
/// </summary>
/// <param name="angle"></param>
/// <param name="radius"></param>
/// <returns></returns>
public static Point ComputeCartesianCoordinate(double angle, double radius)
{
// convert to radians
double angleRad = (Math.PI / 180.0) * (angle - 90);
double x = radius * Math.Cos(angleRad);
double y = radius * Math.Sin(angleRad);
return new Point(x, y);
}
}
}
| 30.431818 | 102 | 0.668409 | [
"Apache-2.0"
] | Ginger-Automation/Ginger | Ginger/Ginger/UserControlsLib/PieChart/Utils.cs | 1,340 | C# |
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Institute.Portal.Application")]
[assembly: AssemblyTrademark("")]
// 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("3870c648-4aea-4b85-ba3f-f2f63b96136a")]
| 42.052632 | 84 | 0.779725 | [
"MIT"
] | sweetguo/PortalMicroService | aspnet-core/src/Institute.Portal.Application/Properties/AssemblyInfo.cs | 801 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ParticleManager : MonoBehaviour
{
[SerializeField] float decayTime = 3f;
private void Awake()
{
Destroy(gameObject, decayTime);
}
}
| 16.0625 | 44 | 0.692607 | [
"MIT"
] | TheGeekSKM/BossBattle_Project01 | Assets/Scripts/ParticleManager.cs | 259 | C# |
using System.Collections;
using System.Collections.Generic;
using System;
using NetRuntimeSystem = System;
using System.ComponentModel;
using NetOffice.Attributes;
using NetOffice.CollectionsGeneric;
namespace NetOffice.ExcelApi
{
/// <summary>
/// DispatchInterface SlicerCaches
/// SupportByVersion Excel, 14,15,16
/// </summary>
/// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Excel.SlicerCaches"/> </remarks>
[SupportByVersion("Excel", 14,15,16)]
[EntityType(EntityType.IsDispatchInterface), Enumerator(Enumerator.Reference, EnumeratorInvoke.Property), HasIndexProperty(IndexInvoke.Property, "_Default")]
public class SlicerCaches : COMObject, IEnumerableProvider<NetOffice.ExcelApi.SlicerCache>
{
#pragma warning disable
#region Type Information
/// <summary>
/// Instance Type
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced), Browsable(false), Category("NetOffice"), CoreOverridden]
public override Type InstanceType
{
get
{
return LateBindingApiWrapperType;
}
}
private static Type _type;
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public static Type LateBindingApiWrapperType
{
get
{
if (null == _type)
_type = typeof(SlicerCaches);
return _type;
}
}
#endregion
#region Ctor
/// <param name="factory">current used factory core</param>
/// <param name="parentObject">object there has created the proxy</param>
/// <param name="proxyShare">proxy share instead if com proxy</param>
public SlicerCaches(Core factory, ICOMObject parentObject, COMProxyShare proxyShare) : base(factory, parentObject, proxyShare)
{
}
///<param name="factory">current used factory core</param>
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
public SlicerCaches(Core factory, ICOMObject parentObject, object comProxy) : base(factory, parentObject, comProxy)
{
}
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public SlicerCaches(ICOMObject parentObject, object comProxy) : base(parentObject, comProxy)
{
}
///<param name="factory">current used factory core</param>
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
///<param name="comProxyType">Type of inner wrapped COM proxy"</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public SlicerCaches(Core factory, ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(factory, parentObject, comProxy, comProxyType)
{
}
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
///<param name="comProxyType">Type of inner wrapped COM proxy"</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public SlicerCaches(ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(parentObject, comProxy, comProxyType)
{
}
///<param name="replacedObject">object to replaced. replacedObject are not usable after this action</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public SlicerCaches(ICOMObject replacedObject) : base(replacedObject)
{
}
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public SlicerCaches() : base()
{
}
/// <param name="progId">registered progID</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public SlicerCaches(string progId) : base(progId)
{
}
#endregion
#region Properties
/// <summary>
/// SupportByVersion Excel 14, 15, 16
/// Get
/// </summary>
/// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Excel.SlicerCaches.Application"/> </remarks>
[SupportByVersion("Excel", 14,15,16)]
public NetOffice.ExcelApi.Application Application
{
get
{
return Factory.ExecuteKnownReferencePropertyGet<NetOffice.ExcelApi.Application>(this, "Application", NetOffice.ExcelApi.Application.LateBindingApiWrapperType);
}
}
/// <summary>
/// SupportByVersion Excel 14, 15, 16
/// Get
/// </summary>
/// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Excel.SlicerCaches.Creator"/> </remarks>
[SupportByVersion("Excel", 14,15,16)]
public NetOffice.ExcelApi.Enums.XlCreator Creator
{
get
{
return Factory.ExecuteEnumPropertyGet<NetOffice.ExcelApi.Enums.XlCreator>(this, "Creator");
}
}
/// <summary>
/// SupportByVersion Excel 14, 15, 16
/// Get
/// Unknown COM Proxy
/// </summary>
/// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Excel.SlicerCaches.Parent"/> </remarks>
[SupportByVersion("Excel", 14,15,16), ProxyResult]
public object Parent
{
get
{
return Factory.ExecuteReferencePropertyGet(this, "Parent");
}
}
/// <summary>
/// SupportByVersion Excel 14, 15, 16
/// Get
/// </summary>
/// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Excel.SlicerCaches.Count"/> </remarks>
[SupportByVersion("Excel", 14,15,16)]
public Int32 Count
{
get
{
return Factory.ExecuteInt32PropertyGet(this, "Count");
}
}
/// <summary>
/// SupportByVersion Excel 14, 15, 16
/// Get
/// </summary>
/// <param name="index">object index</param>
[SupportByVersion("Excel", 14,15,16)]
[NetRuntimeSystem.Runtime.CompilerServices.IndexerName("Item"), IndexProperty]
public NetOffice.ExcelApi.SlicerCache this[object index]
{
get
{
return Factory.ExecuteKnownReferencePropertyGet<NetOffice.ExcelApi.SlicerCache>(this, "_Default", NetOffice.ExcelApi.SlicerCache.LateBindingApiWrapperType, index);
}
}
#endregion
#region Methods
/// <summary>
/// SupportByVersion Excel 14, 15, 16
/// </summary>
/// <param name="source">object source</param>
/// <param name="sourceField">object sourceField</param>
/// <param name="name">optional object name</param>
[SupportByVersion("Excel", 14,15,16)]
public NetOffice.ExcelApi.SlicerCache Add(object source, object sourceField, object name)
{
return Factory.ExecuteKnownReferenceMethodGet<NetOffice.ExcelApi.SlicerCache>(this, "Add", NetOffice.ExcelApi.SlicerCache.LateBindingApiWrapperType, source, sourceField, name);
}
/// <summary>
/// SupportByVersion Excel 15,16
/// </summary>
/// <param name="source">object source</param>
/// <param name="sourceField">object sourceField</param>
/// <param name="name">optional object name</param>
/// <param name="slicerCacheType">optional object slicerCacheType</param>
[SupportByVersion("Excel", 15, 16)]
public NetOffice.ExcelApi.SlicerCache Add(object source, object sourceField, object name, object slicerCacheType)
{
return Factory.ExecuteKnownReferenceMethodGet<NetOffice.ExcelApi.SlicerCache>(this, "Add", NetOffice.ExcelApi.SlicerCache.LateBindingApiWrapperType, source, sourceField, name, slicerCacheType);
}
/// <summary>
/// SupportByVersion Excel 14, 15, 16
/// </summary>
/// <param name="source">object source</param>
/// <param name="sourceField">object sourceField</param>
[CustomMethod]
[SupportByVersion("Excel", 14,15,16)]
public NetOffice.ExcelApi.SlicerCache Add(object source, object sourceField)
{
return Factory.ExecuteKnownReferenceMethodGet<NetOffice.ExcelApi.SlicerCache>(this, "Add", NetOffice.ExcelApi.SlicerCache.LateBindingApiWrapperType, source, sourceField);
}
/// <summary>
/// SupportByVersion Excel 15,16
/// </summary>
/// <param name="source">object source</param>
/// <param name="sourceField">object sourceField</param>
/// <param name="name">optional object name</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
[SupportByVersion("Excel", 15, 16)]
public NetOffice.ExcelApi.SlicerCache _Add(object source, object sourceField, object name)
{
return Factory.ExecuteKnownReferenceMethodGet<NetOffice.ExcelApi.SlicerCache>(this, "_Add", NetOffice.ExcelApi.SlicerCache.LateBindingApiWrapperType, source, sourceField, name);
}
/// <summary>
/// SupportByVersion Excel 15,16
/// </summary>
/// <param name="source">object source</param>
/// <param name="sourceField">object sourceField</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
[CustomMethod]
[SupportByVersion("Excel", 15, 16)]
public NetOffice.ExcelApi.SlicerCache _Add(object source, object sourceField)
{
return Factory.ExecuteKnownReferenceMethodGet<NetOffice.ExcelApi.SlicerCache>(this, "_Add", NetOffice.ExcelApi.SlicerCache.LateBindingApiWrapperType, source, sourceField);
}
#endregion
#region IEnumerableProvider<NetOffice.ExcelApi.SlicerCache>
ICOMObject IEnumerableProvider<NetOffice.ExcelApi.SlicerCache>.GetComObjectEnumerator(ICOMObject parent)
{
return NetOffice.Utils.GetComObjectEnumeratorAsProperty(parent, this, false);
}
IEnumerable IEnumerableProvider<NetOffice.ExcelApi.SlicerCache>.FetchVariantComObjectEnumerator(ICOMObject parent, ICOMObject enumerator)
{
return NetOffice.Utils.FetchVariantComObjectEnumerator(parent, enumerator, false);
}
#endregion
#region IEnumerable<NetOffice.ExcelApi.SlicerCache>
/// <summary>
/// SupportByVersion Excel, 14,15,16
/// </summary>
[SupportByVersion("Excel", 14, 15, 16)]
public IEnumerator<NetOffice.ExcelApi.SlicerCache> GetEnumerator()
{
NetRuntimeSystem.Collections.IEnumerable innerEnumerator = (this as NetRuntimeSystem.Collections.IEnumerable);
foreach (NetOffice.ExcelApi.SlicerCache item in innerEnumerator)
yield return item;
}
#endregion
#region IEnumerable
/// <summary>
/// SupportByVersion Excel, 14,15,16
/// </summary>
[SupportByVersion("Excel", 14,15,16)]
IEnumerator NetRuntimeSystem.Collections.IEnumerable.GetEnumerator()
{
return NetOffice.Utils.GetProxyEnumeratorAsProperty(this, false);
}
#endregion
#pragma warning restore
}
} | 35.732441 | 196 | 0.701797 | [
"MIT"
] | NetOfficeFw/NetOffice | Source/Excel/DispatchInterfaces/SlicerCaches.cs | 10,686 | C# |
#region Using Statements
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
#endregion
namespace Artemis.Engine.Utilities.UriTree
{
/// <summary>
/// A recursive container structure where items and subgroups are
/// accessed using a "URI" (a name with parts separated by the
/// URI_SEPARATOR character).
/// </summary>
/// <typeparam name="T">This must be the class itself, otherwise recursion won't work.</typeparam>
/// <typeparam name="U">The type of object stored in each group.</typeparam>
public class UriTreeGroup<T, U> : UriTreeNode<T> where T : UriTreeGroup<T, U>
{
/// <summary>
/// Check if this group is empty (i.e. it has no items and it has no
/// subgroups).
/// </summary>
public bool IsEmpty
{
get
{
return (Items.Count == 0 && IsLeaf);
}
}
/// <summary>
/// The dictionary of all items in this group.
/// </summary>
public Dictionary<string, U> Items { get; protected set; }
/// <summary>
/// The list of all unnamed items in this group.
/// </summary>
public ICollection<U> AnonymousItems { get; protected set; }
protected UriTreeGroup(string name, ICollection<U> anonymousItemsCollection = null)
: base(name)
{
Items = new Dictionary<string, U>();
AnonymousItems = anonymousItemsCollection == null ? anonymousItemsCollection : new HashSet<U>();
}
/// <summary>
/// Return the item with the given full name. If not found, return the given
/// default value.
/// </summary>
/// <param name="fullName"></param>
/// <param name="defaultVal"></param>
/// <returns></returns>
public U GetItem(string fullName, U defaultVal, bool useDefault = true)
{
return GetItem(new Queue<string>(UriUtilities.GetParts(fullName)), useDefault, defaultVal);
}
/// <summary>
/// Return the item with the given full name.
/// </summary>
/// <param name="fullName"></param>
/// <returns></returns>
public U GetItem(string fullName, bool useDefault = false)
{
return GetItem(new Queue<string>(UriUtilities.GetParts(fullName)), useDefault, default(U));
}
internal U GetItem(Queue<string> nameParts, bool useDefault, U defaultVal)
{
var first = nameParts.Dequeue();
if (nameParts.Count > 0 && !Subnodes.ContainsKey(first))
{
if (useDefault)
{
return defaultVal;
}
throw CouldNotRetrieveItem(first);
}
else if (nameParts.Count == 0)
{
if (!Items.ContainsKey(first))
{
if (useDefault)
{
return defaultVal;
}
throw CouldNotRetrieveItem(first);
}
return Items[first];
}
return Subnodes[first].GetItem(nameParts, useDefault, defaultVal);
}
/// <summary>
/// Common exception thrown when an item could not be retrieved.
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
private UriTreeException CouldNotRetrieveItem(string name)
{
return new UriTreeException(
String.Format(
"Could not retrieve item with name '{0}' " +
"from group with full name '{1}'", name, FullName
)
);
}
public bool ContainsItem(string name)
{
return ContainsItem(new Queue<string>(UriUtilities.GetParts(name)));
}
internal bool ContainsItem(Queue<string> nameParts)
{
var first = nameParts.Dequeue();
if (nameParts.Count == 0)
{
return Items.ContainsKey(first);
}
return Subnodes[first].ContainsItem(nameParts);
}
/// <summary>
/// Check if this group contains the given item.
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
public bool ContainsItem(U item, bool searchRecursive = true)
{
return Items.ContainsValue(item) || (
searchRecursive ? Subnodes.Any(kvp => kvp.Value.ContainsItem(item)) : false
);
}
/// <summary>
/// Iterate through all the items in this group.
///
/// Note: This will not iterate through all items in subgroups as well.
/// </summary>
/// <returns></returns>
public IEnumerator<U> IterateItems()
{
foreach (var kvp in Items)
{
yield return kvp.Value;
}
foreach (var item in AnonymousItems)
{
yield return item;
}
}
/// <summary>
/// Iterate through all the named items in this group.
/// </summary>
/// <returns></returns>
public IEnumerator<U> IterateNamedItems()
{
foreach (var kvp in Items)
{
yield return kvp.Value;
}
}
/// <summary>
/// Iterate through all the anonymous items in this group.
/// </summary>
/// <returns></returns>
public IEnumerator<U> IterateAnonymousItems()
{
foreach (var item in AnonymousItems)
{
yield return item;
}
}
/// <summary>
/// Iterate through all the items in this group whose name matches a
/// given regex.
///
/// Note: This will not iterate through all items in subgroups as well.
/// </summary>
/// <param name="regex"></param>
/// <returns></returns>
public IEnumerator<U> IterateItems(string regex)
{
foreach (var kvp in Items)
{
if (Regex.IsMatch(kvp.Key, regex))
{
yield return kvp.Value;
}
}
}
/// <summary>
/// Iterate through the names of items.
/// </summary>
/// <returns></returns>
public IEnumerator<string> IterateItemNames()
{
foreach (var kvp in Items)
{
yield return kvp.Key;
}
}
}
}
| 31.632558 | 108 | 0.504632 | [
"MIT"
] | ArtemisEngine/Artemis-Engine | Artemis.Engine/Utilities/UriTree/UriTreeGroup.cs | 6,803 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using Renci.SshNet.Common;
namespace Renci.SshNet
{
/// <summary>
/// Provides client connection to SSH server.
/// </summary>
public class SshClient : BaseClient
{
/// <summary>
/// Holds the list of forwarded ports
/// </summary>
private readonly List<ForwardedPort> _forwardedPorts;
/// <summary>
/// Holds a value indicating whether the current instance is disposed.
/// </summary>
/// <value>
/// <c>true</c> if the current instance is disposed; otherwise, <c>false</c>.
/// </value>
private bool _isDisposed;
private Stream _inputStream;
/// <summary>
/// Gets the list of forwarded ports.
/// </summary>
public IEnumerable<ForwardedPort> ForwardedPorts
{
get
{
return _forwardedPorts.AsReadOnly();
}
}
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="SshClient" /> class.
/// </summary>
/// <param name="connectionInfo">The connection info.</param>
/// <example>
/// <code source="..\..\src\Renci.SshNet.Tests\Classes\PasswordConnectionInfoTest.cs" region="Example PasswordConnectionInfo" language="C#" title="Connect using PasswordConnectionInfo object" />
/// <code source="..\..\src\Renci.SshNet.Tests\Classes\PasswordConnectionInfoTest.cs" region="Example PasswordConnectionInfo PasswordExpired" language="C#" title="Connect using PasswordConnectionInfo object with passwod change option" />
/// <code source="..\..\src\Renci.SshNet.Tests\Classes\PrivateKeyConnectionInfoTest.cs" region="Example PrivateKeyConnectionInfo PrivateKeyFile" language="C#" title="Connect using PrivateKeyConnectionInfo" />
/// <code source="..\..\src\Renci.SshNet.Tests\Classes\SshClientTest.cs" region="Example SshClient Connect Timeout" language="C#" title="Specify connection timeout when connecting" />
/// </example>
/// <exception cref="ArgumentNullException"><paramref name="connectionInfo"/> is <c>null</c>.</exception>
public SshClient(ConnectionInfo connectionInfo)
: this(connectionInfo, false)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="SshClient"/> class.
/// </summary>
/// <param name="host">Connection host.</param>
/// <param name="port">Connection port.</param>
/// <param name="username">Authentication username.</param>
/// <param name="password">Authentication password.</param>
/// <exception cref="ArgumentNullException"><paramref name="password"/> is <c>null</c>.</exception>
/// <exception cref="ArgumentException"><paramref name="host"/> is invalid, or <paramref name="username"/> is <c>null</c> or contains only whitespace characters.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="port"/> is not within <see cref="IPEndPoint.MinPort"/> and <see cref="IPEndPoint.MaxPort"/>.</exception>
[SuppressMessage("Microsoft.Reliability", "C2A000:DisposeObjectsBeforeLosingScope", Justification = "Disposed in Dispose(bool) method.")]
public SshClient(string host, int port, string username, string password)
: this(new PasswordConnectionInfo(host, port, username, password), true)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="SshClient"/> class.
/// </summary>
/// <param name="host">Connection host.</param>
/// <param name="username">Authentication username.</param>
/// <param name="password">Authentication password.</param>
/// <example>
/// <code source="..\..\src\Renci.SshNet.Tests\Classes\SshClientTest.cs" region="Example SshClient(host, username) Connect" language="C#" title="Connect using username and password" />
/// </example>
/// <exception cref="ArgumentNullException"><paramref name="password"/> is <c>null</c>.</exception>
/// <exception cref="ArgumentException"><paramref name="host"/> is invalid, or <paramref name="username"/> is <c>null</c> or contains only whitespace characters.</exception>
public SshClient(string host, string username, string password)
: this(host, ConnectionInfo.DefaultPort, username, password)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="SshClient"/> class.
/// </summary>
/// <param name="host">Connection host.</param>
/// <param name="port">Connection port.</param>
/// <param name="username">Authentication username.</param>
/// <param name="keyFiles">Authentication private key file(s) .</param>
/// <example>
/// <code source="..\..\src\Renci.SshNet.Tests\Classes\SshClientTest.cs" region="Example SshClient(host, username) Connect PrivateKeyFile" language="C#" title="Connect using username and private key" />
/// <code source="..\..\src\Renci.SshNet.Tests\Classes\SshClientTest.cs" region="Example SshClient(host, username) Connect PrivateKeyFile PassPhrase" language="C#" title="Connect using username and private key and pass phrase" />
/// </example>
/// <exception cref="ArgumentNullException"><paramref name="keyFiles"/> is <c>null</c>.</exception>
/// <exception cref="ArgumentException"><paramref name="host"/> is invalid, -or- <paramref name="username"/> is <c>null</c> or contains only whitespace characters.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="port"/> is not within <see cref="IPEndPoint.MinPort"/> and <see cref="IPEndPoint.MaxPort"/>.</exception>
[SuppressMessage("Microsoft.Reliability", "CA2000:DisposeObjectsBeforeLosingScope", Justification = "Disposed in Dispose(bool) method.")]
public SshClient(string host, int port, string username, params PrivateKeyFile[] keyFiles)
: this(new PrivateKeyConnectionInfo(host, port, username, keyFiles), true)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="SshClient"/> class.
/// </summary>
/// <param name="host">Connection host.</param>
/// <param name="username">Authentication username.</param>
/// <param name="keyFiles">Authentication private key file(s) .</param>
/// <example>
/// <code source="..\..\src\Renci.SshNet.Tests\Classes\SshClientTest.cs" region="Example SshClient(host, username) Connect PrivateKeyFile" language="C#" title="Connect using private key" />
/// <code source="..\..\src\Renci.SshNet.Tests\Classes\SshClientTest.cs" region="Example SshClient(host, username) Connect PrivateKeyFile PassPhrase" language="C#" title="Connect using private key and pass phrase" />
/// </example>
/// <exception cref="ArgumentNullException"><paramref name="keyFiles"/> is <c>null</c>.</exception>
/// <exception cref="ArgumentException"><paramref name="host"/> is invalid, -or- <paramref name="username"/> is <c>null</c> or contains only whitespace characters.</exception>
public SshClient(string host, string username, params PrivateKeyFile[] keyFiles)
: this(host, ConnectionInfo.DefaultPort, username, keyFiles)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="SshClient"/> class.
/// </summary>
/// <param name="connectionInfo">The connection info.</param>
/// <param name="ownsConnectionInfo">Specified whether this instance owns the connection info.</param>
/// <exception cref="ArgumentNullException"><paramref name="connectionInfo"/> is <c>null</c>.</exception>
/// <remarks>
/// If <paramref name="ownsConnectionInfo"/> is <c>true</c>, then the
/// connection info will be disposed when this instance is disposed.
/// </remarks>
private SshClient(ConnectionInfo connectionInfo, bool ownsConnectionInfo)
: this(connectionInfo, ownsConnectionInfo, new ServiceFactory())
{
}
/// <summary>
/// Initializes a new instance of the <see cref="SshClient"/> class.
/// </summary>
/// <param name="connectionInfo">The connection info.</param>
/// <param name="ownsConnectionInfo">Specified whether this instance owns the connection info.</param>
/// <param name="serviceFactory">The factory to use for creating new services.</param>
/// <exception cref="ArgumentNullException"><paramref name="connectionInfo"/> is <c>null</c>.</exception>
/// <exception cref="ArgumentNullException"><paramref name="serviceFactory"/> is <c>null</c>.</exception>
/// <remarks>
/// If <paramref name="ownsConnectionInfo"/> is <c>true</c>, then the
/// connection info will be disposed when this instance is disposed.
/// </remarks>
internal SshClient(ConnectionInfo connectionInfo, bool ownsConnectionInfo, IServiceFactory serviceFactory)
: base(connectionInfo, ownsConnectionInfo, serviceFactory)
{
_forwardedPorts = new List<ForwardedPort>();
}
#endregion
/// <summary>
/// Called when client is disconnecting from the server.
/// </summary>
protected override void OnDisconnecting()
{
base.OnDisconnecting();
foreach (var port in _forwardedPorts)
{
port.Stop();
}
}
/// <summary>
/// Adds the forwarded port.
/// </summary>
/// <param name="port">The port.</param>
/// <example>
/// <code source="..\..\src\Renci.SshNet.Tests\Classes\ForwardedPortRemoteTest.cs" region="Example SshClient AddForwardedPort Start Stop ForwardedPortRemote" language="C#" title="Remote port forwarding" />
/// <code source="..\..\src\Renci.SshNet.Tests\Classes\ForwardedPortLocalTest.cs" region="Example SshClient AddForwardedPort Start Stop ForwardedPortLocal" language="C#" title="Local port forwarding" />
/// </example>
/// <exception cref="InvalidOperationException">Forwarded port is already added to a different client.</exception>
/// <exception cref="ArgumentNullException"><paramref name="port"/> is <c>null</c>.</exception>
/// <exception cref="SshConnectionException">Client is not connected.</exception>
public void AddForwardedPort(ForwardedPort port)
{
if (port == null)
throw new ArgumentNullException("port");
EnsureSessionIsOpen();
AttachForwardedPort(port);
_forwardedPorts.Add(port);
}
/// <summary>
/// Stops and removes the forwarded port from the list.
/// </summary>
/// <param name="port">Forwarded port.</param>
/// <exception cref="ArgumentNullException"><paramref name="port"/> is <c>null</c>.</exception>
public void RemoveForwardedPort(ForwardedPort port)
{
if (port == null)
throw new ArgumentNullException("port");
// Stop port forwarding before removing it
port.Stop();
DetachForwardedPort(port);
_forwardedPorts.Remove(port);
}
private void AttachForwardedPort(ForwardedPort port)
{
if (port.Session != null && port.Session != Session)
throw new InvalidOperationException("Forwarded port is already added to a different client.");
port.Session = Session;
}
private static void DetachForwardedPort(ForwardedPort port)
{
port.Session = null;
}
/// <summary>
/// Creates the command to be executed.
/// </summary>
/// <param name="commandText">The command text.</param>
/// <returns><see cref="SshCommand"/> object.</returns>
/// <exception cref="SshConnectionException">Client is not connected.</exception>
public SshCommand CreateCommand(string commandText)
{
return CreateCommand(commandText, ConnectionInfo.Encoding);
}
/// <summary>
/// Creates the command to be executed with specified encoding.
/// </summary>
/// <param name="commandText">The command text.</param>
/// <param name="encoding">The encoding to use for results.</param>
/// <returns><see cref="SshCommand"/> object which uses specified encoding.</returns>
/// <remarks>This method will change current default encoding.</remarks>
/// <exception cref="SshConnectionException">Client is not connected.</exception>
/// <exception cref="ArgumentNullException"><paramref name="commandText"/> or <paramref name="encoding"/> is <c>null</c>.</exception>
public SshCommand CreateCommand(string commandText, Encoding encoding)
{
EnsureSessionIsOpen();
ConnectionInfo.Encoding = encoding;
return new SshCommand(Session, commandText, encoding);
}
/// <summary>
/// Creates and executes the command.
/// </summary>
/// <param name="commandText">The command text.</param>
/// <returns>Returns an instance of <see cref="SshCommand"/> with execution results.</returns>
/// <remarks>This method internally uses asynchronous calls.</remarks>
/// <example>
/// <code source="..\..\src\Renci.SshNet.Tests\Classes\SshCommandTest.cs" region="Example SshCommand RunCommand Result" language="C#" title="Running simple command" />
/// <code source="..\..\src\Renci.SshNet.Tests\Classes\SshCommandTest.cs" region="Example SshCommand RunCommand Parallel" language="C#" title="Run many commands in parallel" />
/// </example>
/// <exception cref="ArgumentException">CommandText property is empty.</exception>
/// <exception cref="T:Renci.SshNet.Common.SshException">Invalid Operation - An existing channel was used to execute this command.</exception>
/// <exception cref="InvalidOperationException">Asynchronous operation is already in progress.</exception>
/// <exception cref="SshConnectionException">Client is not connected.</exception>
/// <exception cref="ArgumentNullException"><paramref name="commandText"/> is <c>null</c>.</exception>
public SshCommand RunCommand(string commandText)
{
var cmd = CreateCommand(commandText);
cmd.Execute();
return cmd;
}
/// <summary>
/// Creates the shell.
/// </summary>
/// <param name="input">The input.</param>
/// <param name="output">The output.</param>
/// <param name="extendedOutput">The extended output.</param>
/// <param name="terminalName">Name of the terminal.</param>
/// <param name="columns">The columns.</param>
/// <param name="rows">The rows.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <param name="terminalModes">The terminal mode.</param>
/// <param name="bufferSize">Size of the internal read buffer.</param>
/// <returns>
/// Returns a representation of a <see cref="Shell" /> object.
/// </returns>
/// <exception cref="SshConnectionException">Client is not connected.</exception>
public Shell CreateShell(Stream input, Stream output, Stream extendedOutput, string terminalName, uint columns, uint rows, uint width, uint height, IDictionary<TerminalModes, uint> terminalModes, int bufferSize)
{
EnsureSessionIsOpen();
return new Shell(Session, input, output, extendedOutput, terminalName, columns, rows, width, height, terminalModes, bufferSize);
}
/// <summary>
/// Creates the shell.
/// </summary>
/// <param name="input">The input.</param>
/// <param name="output">The output.</param>
/// <param name="extendedOutput">The extended output.</param>
/// <param name="terminalName">Name of the terminal.</param>
/// <param name="columns">The columns.</param>
/// <param name="rows">The rows.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <param name="terminalModes">The terminal mode.</param>
/// <returns>
/// Returns a representation of a <see cref="Shell" /> object.
/// </returns>
/// <exception cref="SshConnectionException">Client is not connected.</exception>
public Shell CreateShell(Stream input, Stream output, Stream extendedOutput, string terminalName, uint columns, uint rows, uint width, uint height, IDictionary<TerminalModes, uint> terminalModes)
{
return CreateShell(input, output, extendedOutput, terminalName, columns, rows, width, height, terminalModes, 1024);
}
/// <summary>
/// Creates the shell.
/// </summary>
/// <param name="input">The input.</param>
/// <param name="output">The output.</param>
/// <param name="extendedOutput">The extended output.</param>
/// <returns>
/// Returns a representation of a <see cref="Shell" /> object.
/// </returns>
/// <exception cref="SshConnectionException">Client is not connected.</exception>
public Shell CreateShell(Stream input, Stream output, Stream extendedOutput)
{
return CreateShell(input, output, extendedOutput, string.Empty, 0, 0, 0, 0, null, 1024);
}
/// <summary>
/// Creates the shell.
/// </summary>
/// <param name="encoding">The encoding to use to send the input.</param>
/// <param name="input">The input.</param>
/// <param name="output">The output.</param>
/// <param name="extendedOutput">The extended output.</param>
/// <param name="terminalName">Name of the terminal.</param>
/// <param name="columns">The columns.</param>
/// <param name="rows">The rows.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <param name="terminalModes">The terminal mode.</param>
/// <param name="bufferSize">Size of the internal read buffer.</param>
/// <returns>
/// Returns a representation of a <see cref="Shell" /> object.
/// </returns>
/// <exception cref="SshConnectionException">Client is not connected.</exception>
public Shell CreateShell(Encoding encoding, string input, Stream output, Stream extendedOutput, string terminalName, uint columns, uint rows, uint width, uint height, IDictionary<TerminalModes, uint> terminalModes, int bufferSize)
{
// TODO let shell dispose of input stream when we own the stream!
_inputStream = new MemoryStream();
var writer = new StreamWriter(_inputStream, encoding);
writer.Write(input);
writer.Flush();
_inputStream.Seek(0, SeekOrigin.Begin);
return CreateShell(_inputStream, output, extendedOutput, terminalName, columns, rows, width, height, terminalModes, bufferSize);
}
/// <summary>
/// Creates the shell.
/// </summary>
/// <param name="encoding">The encoding.</param>
/// <param name="input">The input.</param>
/// <param name="output">The output.</param>
/// <param name="extendedOutput">The extended output.</param>
/// <param name="terminalName">Name of the terminal.</param>
/// <param name="columns">The columns.</param>
/// <param name="rows">The rows.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <param name="terminalModes">The terminal modes.</param>
/// <returns>
/// Returns a representation of a <see cref="Shell" /> object.
/// </returns>
/// <exception cref="SshConnectionException">Client is not connected.</exception>
public Shell CreateShell(Encoding encoding, string input, Stream output, Stream extendedOutput, string terminalName, uint columns, uint rows, uint width, uint height, IDictionary<TerminalModes, uint> terminalModes)
{
return CreateShell(encoding, input, output, extendedOutput, terminalName, columns, rows, width, height, terminalModes, 1024);
}
/// <summary>
/// Creates the shell.
/// </summary>
/// <param name="encoding">The encoding.</param>
/// <param name="input">The input.</param>
/// <param name="output">The output.</param>
/// <param name="extendedOutput">The extended output.</param>
/// <returns>
/// Returns a representation of a <see cref="Shell" /> object.
/// </returns>
/// <exception cref="SshConnectionException">Client is not connected.</exception>
public Shell CreateShell(Encoding encoding, string input, Stream output, Stream extendedOutput)
{
return CreateShell(encoding, input, output, extendedOutput, string.Empty, 0, 0, 0, 0, null, 1024);
}
/// <summary>
/// Creates the shell stream.
/// </summary>
/// <param name="terminalName">The <c>TERM</c> environment variable.</param>
/// <param name="columns">The terminal width in columns.</param>
/// <param name="rows">The terminal width in rows.</param>
/// <param name="width">The terminal height in pixels.</param>
/// <param name="height">The terminal height in pixels.</param>
/// <param name="bufferSize">The size of the buffer.</param>
/// <returns>
/// The created <see cref="ShellStream"/> instance.
/// </returns>
/// <exception cref="SshConnectionException">Client is not connected.</exception>
/// <remarks>
/// <para>
/// The <c>TERM</c> environment variable contains an identifier for the text window's capabilities.
/// You can get a detailed list of these cababilities by using the ‘infocmp’ command.
/// </para>
/// <para>
/// The column/row dimensions override the pixel dimensions(when nonzero). Pixel dimensions refer
/// to the drawable area of the window.
/// </para>
/// </remarks>
public ShellStream CreateShellStream(string terminalName, uint columns, uint rows, uint width, uint height, int bufferSize)
{
return CreateShellStream(terminalName, columns, rows, width, height, bufferSize, null);
}
/// <summary>
/// Creates the shell stream.
/// </summary>
/// <param name="terminalName">The <c>TERM</c> environment variable.</param>
/// <param name="columns">The terminal width in columns.</param>
/// <param name="rows">The terminal width in rows.</param>
/// <param name="width">The terminal height in pixels.</param>
/// <param name="height">The terminal height in pixels.</param>
/// <param name="bufferSize">The size of the buffer.</param>
/// <param name="terminalModeValues">The terminal mode values.</param>
/// <returns>
/// The created <see cref="ShellStream"/> instance.
/// </returns>
/// <exception cref="SshConnectionException">Client is not connected.</exception>
/// <remarks>
/// <para>
/// The <c>TERM</c> environment variable contains an identifier for the text window's capabilities.
/// You can get a detailed list of these cababilities by using the ‘infocmp’ command.
/// </para>
/// <para>
/// The column/row dimensions override the pixel dimensions(when non-zero). Pixel dimensions refer
/// to the drawable area of the window.
/// </para>
/// </remarks>
public ShellStream CreateShellStream(string terminalName, uint columns, uint rows, uint width, uint height, int bufferSize, IDictionary<TerminalModes, uint> terminalModeValues)
{
EnsureSessionIsOpen();
return ServiceFactory.CreateShellStream(Session, terminalName, columns, rows, width, height, terminalModeValues, bufferSize);
}
/// <summary>
/// Stops forwarded ports.
/// </summary>
protected override void OnDisconnected()
{
base.OnDisconnected();
for (var i = _forwardedPorts.Count - 1; i >= 0; i--)
{
var port = _forwardedPorts[i];
DetachForwardedPort(port);
_forwardedPorts.RemoveAt(i);
}
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources
/// </summary>
/// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (_isDisposed)
return;
if (disposing)
{
if (_inputStream != null)
{
_inputStream.Dispose();
_inputStream = null;
}
_isDisposed = true;
}
}
private void EnsureSessionIsOpen()
{
if (Session == null)
throw new SshConnectionException("Client not connected.");
}
}
}
| 51.066536 | 249 | 0.616287 | [
"BSD-2-Clause",
"BSD-3-Clause"
] | 0x727/metasploit-framework | external/source/Scanner/share/Renci.SshNet/SshClient.cs | 26,105 | C# |
using Aop.Api.Response;
using Com.Alipay.Business;
using Com.Alipay.Domain;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Com.Alipay
{
/// <summary>
/// IAlipayMonitor 的摘要说明
/// </summary>
public interface IAlipayMonitor
{
//云监控接口
AlipayF2FMonitorResult mcloudMonitor(AlipayMonitorContentBuilder builder);
}
} | 18.318182 | 82 | 0.704715 | [
"Apache-2.0"
] | WangJunZzz/AlipayDemo | AspNet/Module/F2FPayDll/Business/IAlipayMonitor.cs | 425 | C# |
namespace Core.TileBodies
{
struct Computer
{
// Tag component
}
}
| 11 | 26 | 0.556818 | [
"MIT"
] | SpencasaurusRex/ARA2D | Core/TileBodies/Computer.cs | 90 | C# |
using PopupWindowActionSample.Views;
using Prism.Ioc;
using Prism.Modularity;
using Prism.Regions;
using System.Windows;
namespace PopupWindowActionSample
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App
{
protected override Window CreateShell()
{
return Container.Resolve<MainWindow>();
}
protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
containerRegistry.RegisterForNavigation<ContentView>();
containerRegistry.RegisterForNavigation<PopupView>();
containerRegistry.RegisterForNavigation<SubaView>();
containerRegistry.RegisterForNavigation<SubbView>();
}
protected override void OnInitialized()
{
base.OnInitialized();
Container.Resolve<IRegionManager>().RequestNavigate("ContentRegion", nameof(ContentView));
}
}
}
| 28.617647 | 102 | 0.660843 | [
"MIT"
] | kwhrkzk/Prism7Sample | PopupWindowActionSample/App.xaml.cs | 975 | C# |
using Newtonsoft.Json;
namespace Vendr.Contrib.OrderLabels.Web.Models.Response
{
internal class LabelGeneratorResponse
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("alias")]
public string Alias { get; set; }
}
} | 21.923077 | 55 | 0.635088 | [
"MIT"
] | callumbwhyte/vendr-order-labels | src/Vendr.Contrib.OrderLabels/Web/Models/Response/LabelGeneratorResponse.cs | 287 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BoundariesController : MonoBehaviour
{
public void CheckBoundaries(in Vector2 pos, out Vector2 newPos, in Vector2 objTransformPos, in float boundariesRadius)
{
newPos = objTransformPos;
// Do vertical bounds
if (pos.y - boundariesRadius > Camera.main.orthographicSize)
{
newPos.y = -Camera.main.orthographicSize;
}
if (pos.y + boundariesRadius < -Camera.main.orthographicSize)
{
newPos.y = Camera.main.orthographicSize;
}
// Calculate the orthographic width based on the screen ration
float screenRation = (float)Screen.width / (float)Screen.height;
float widthOrtho = Camera.main.orthographicSize * screenRation;
// Do horizontal bounds
if (pos.x - boundariesRadius > widthOrtho)
{
newPos.x = -widthOrtho;
}
if (pos.x + boundariesRadius < -widthOrtho)
{
newPos.x = widthOrtho;
}
}
public bool IsOnScreen(in Vector2 pos)
{
bool isOnScreen = false;
if (pos.y < Camera.main.orthographicSize && pos.y > -Camera.main.orthographicSize)
{
isOnScreen = true;
}
// Calculate the orthographic width based on the screen ration
float screenRation = (float)Screen.width / (float)Screen.height;
float widthOrtho = Camera.main.orthographicSize * screenRation;
// Do horizontal bounds
if (pos.x > widthOrtho || pos.x < -widthOrtho)
{
isOnScreen = false;
}
return isOnScreen;
}
}
| 29.344828 | 122 | 0.611046 | [
"Apache-2.0"
] | KryvytskyiDenis/Asteroids | Asteroids/Assets/Scripts/BoundariesController.cs | 1,704 | C# |
// Developed by Softeq Development Corporation
// http://www.softeq.com
using System;
using NSubstitute;
using Softeq.XToolkit.Common.Tests.WeakTests.Utils;
using Xunit;
namespace Softeq.XToolkit.Common.Tests.WeakTests.WeakActionTests
{
public class WeakAnonymousActionWithInstanceReferenceTests
{
[Fact]
public void IsStatic_ReturnsFalse()
{
var (_, weakAction) = WeakDelegateCreator.CreateWeakDelegate(
() => new WeakDelegatesCallCounter(),
x => x.GetWeakAnonymousActionWithInstanceReference());
Assert.False(weakAction.IsStatic);
}
[Fact]
public void IsAlive_WithTargetReference_AfterGarbageCollection_ReturnsTrue()
{
var (_, weakAction) = WeakDelegateCreator.CreateWeakDelegate(
() => new WeakDelegatesCallCounter(),
x => x.GetWeakAnonymousActionWithInstanceReference());
GC.Collect();
Assert.True(weakAction.IsAlive);
}
[Fact]
public void Execute_WithTargetReference_AfterGarbageCollection_InvokesAction()
{
var callCounter = Substitute.For<ICallCounter>();
var (_, weakAction) = WeakDelegateCreator.CreateWeakDelegate(
() => new WeakDelegatesCallCounter(callCounter),
x => x.GetWeakAnonymousActionWithInstanceReference());
weakAction.Execute();
callCounter.Received(1).OnActionCalled();
}
[Fact]
public void IsAlive_WithoutTargetReference_AfterGarbageCollection_ReturnsFalse()
{
var (reference, weakAction) = WeakDelegateCreator.CreateWeakDelegate(
() => new WeakDelegatesCallCounter(),
x => x.GetWeakAnonymousActionWithInstanceReference());
reference.Dispose();
GC.Collect();
Assert.False(weakAction.IsAlive);
}
[Fact]
public void Execute_WithoutTargetReference_AfterGarbageCollection_DoesNotInvokeAction()
{
var callCounter = Substitute.For<ICallCounter>();
var (reference, weakAction) = WeakDelegateCreator.CreateWeakDelegate(
() => new WeakDelegatesCallCounter(callCounter),
x => x.GetWeakAnonymousActionWithInstanceReference());
reference.Dispose();
GC.Collect();
weakAction.Execute();
callCounter.DidNotReceive().OnActionCalled();
}
}
}
| 32.371795 | 95 | 0.628119 | [
"MIT"
] | Softeq/XToolkit.WhiteLabel | Softeq.XToolkit.Common.Tests/WeakTests/WeakActionTests/WeakAnonymousActionWithInstanceReferenceTests.cs | 2,525 | C# |
#pragma warning disable 108 // new keyword hiding
#pragma warning disable 114 // new keyword hiding
namespace Windows.Media.MediaProperties
{
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
#endif
public partial class TimedMetadataEncodingProperties : global::Windows.Media.MediaProperties.IMediaEncodingProperties
{
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public string Subtype
{
get
{
throw new global::System.NotImplementedException("The member string TimedMetadataEncodingProperties.Subtype is not implemented in Uno.");
}
set
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Media.MediaProperties.TimedMetadataEncodingProperties", "string TimedMetadataEncodingProperties.Subtype");
}
}
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public global::Windows.Media.MediaProperties.MediaPropertySet Properties
{
get
{
throw new global::System.NotImplementedException("The member MediaPropertySet TimedMetadataEncodingProperties.Properties is not implemented in Uno.");
}
}
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public string Type
{
get
{
throw new global::System.NotImplementedException("The member string TimedMetadataEncodingProperties.Type is not implemented in Uno.");
}
}
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public TimedMetadataEncodingProperties()
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Media.MediaProperties.TimedMetadataEncodingProperties", "TimedMetadataEncodingProperties.TimedMetadataEncodingProperties()");
}
#endif
// Forced skipping of method Windows.Media.MediaProperties.TimedMetadataEncodingProperties.TimedMetadataEncodingProperties()
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public void SetFormatUserData( byte[] value)
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Media.MediaProperties.TimedMetadataEncodingProperties", "void TimedMetadataEncodingProperties.SetFormatUserData(byte[] value)");
}
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public void GetFormatUserData(out byte[] value)
{
throw new global::System.NotImplementedException("The member void TimedMetadataEncodingProperties.GetFormatUserData(out byte[] value) is not implemented in Uno.");
}
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public global::Windows.Media.MediaProperties.TimedMetadataEncodingProperties Copy()
{
throw new global::System.NotImplementedException("The member TimedMetadataEncodingProperties TimedMetadataEncodingProperties.Copy() is not implemented in Uno.");
}
#endif
// Forced skipping of method Windows.Media.MediaProperties.TimedMetadataEncodingProperties.Properties.get
// Forced skipping of method Windows.Media.MediaProperties.TimedMetadataEncodingProperties.Type.get
// Forced skipping of method Windows.Media.MediaProperties.TimedMetadataEncodingProperties.Subtype.set
// Forced skipping of method Windows.Media.MediaProperties.TimedMetadataEncodingProperties.Subtype.get
// Processing: Windows.Media.MediaProperties.IMediaEncodingProperties
}
}
| 44.7 | 214 | 0.779922 | [
"Apache-2.0"
] | AlexTrepanier/Uno | src/Uno.UWP/Generated/3.0.0.0/Windows.Media.MediaProperties/TimedMetadataEncodingProperties.cs | 3,576 | C# |
//******************************************************************************************************************************************************************************************//
// Copyright (c) 2021 @redhook62 (adfsmfa@gmail.com) //
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), //
// to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, //
// and to permit persons to whom the Software is furnished to do so, subject to the following conditions: //
// //
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. //
// //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, //
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. //
// //
// //
// https://github.com/neos-sdi/adfsmfa //
// //
//******************************************************************************************************************************************************************************************//
using Neos.IdentityServer.MultiFactor.Common;
using Neos.IdentityServer.MultiFactor.Data;
using Neos.IdentityServer.MultiFactor.WebAuthN.Metadata;
using Neos.IdentityServer.MultiFactor.WebAuthN.Objects;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace Neos.IdentityServer.MultiFactor.WebAuthN
{
public class NeosWebAuthNProvider : BaseExternalProvider, IWebAuthNProvider
{
private bool _isrequired = false;
private bool _isinitialized = false;
private ForceWizardMode _forceenrollment = ForceWizardMode.Disabled;
private IWebAuthN _webathn;
private MFAMetadataService _metadataservice;
public MFAConfig Config { get; set; }
public bool DirectLogin { get; private set; }
public int ChallengeSize { get; private set; }
public string ForbiddenBrowsers { get; private set; }
public string ForbiddenOperatingSystems { get; private set; }
public string InitiatedBrowsers { get; private set; }
public string InitiatedOperatingSystems { get; private set; }
public string NoCounterBrowsers { get; private set; }
public string ConveyancePreference { get; private set; }
public string Attachement { get; private set; }
public bool Extentions { get; private set; }
public bool UserVerificationMethod { get; private set; }
public UserVerificationRequirement UserVerificationRequirement { get; private set; }
public bool RequireResidentKey { get; private set; }
public WebAuthNPinRequirements PinRequirements { get; set; } = WebAuthNPinRequirements.Null;
/// <summary>
/// Constructor
/// </summary>
public NeosWebAuthNProvider(bool constrained):base()
{
Trace.WriteLine("IMetadataService initialization");
if (constrained)
{
_metadataservice = new MFAMetadataService(new List<IMetadataRepository>
{
new MDSConstrainedMetadataRepository()
});
}
else
{
_metadataservice = new MFAMetadataService(new List<IMetadataRepository>
{
new MDSMetadataRepository()
});
}
var result = Task.Factory.StartNew(_metadataservice.Initialize);
result.Wait(15000);
}
/// <summary>
/// Kind property implementation
/// </summary>
public override PreferredMethod Kind
{
get { return PreferredMethod.Biometrics; }
}
/// <summary>
/// IsBuiltIn property implementation
/// </summary>
public override bool IsBuiltIn
{
get { return true; }
}
/// <summary>
/// IsRequired property implementation
/// </summary>
public override bool IsRequired
{
get { return _isrequired; }
set { _isrequired = value; }
}
/// <summary>
/// CanBeDisabled property implementation
/// </summary>
public override bool AllowDisable
{
get { return true; }
}
/// <summary>
/// IsInitialized property implmentation
/// </summary>
public override bool IsInitialized
{
get { return _isinitialized; }
}
/// <summary>
/// AllowOverride property implmentation
/// </summary>
public override bool AllowOverride
{
get { return true; }
}
/// <summary>
/// AllowEnrollment property implementation
/// </summary>
public override bool AllowEnrollment
{
get { return true; }
}
/// <summary>
/// ForceEnrollment property implementation
/// </summary>
public override ForceWizardMode ForceEnrollment
{
get { return _forceenrollment; }
set { _forceenrollment = value; }
}
/// <summary>
/// Name property implementation
/// </summary>
public override string Name
{
get { return "Neos.Provider.Biometrics"; }
}
/// <summary>
/// Description property implementation
/// </summary>
public override string Description
{
get
{
string independent = "Biometrics Multi-Factor Provider";
ResourcesLocale Resources = null;
if (CultureInfo.DefaultThreadCurrentUICulture != null)
Resources = new ResourcesLocale(CultureInfo.DefaultThreadCurrentUICulture.LCID);
else
Resources = new ResourcesLocale(CultureInfo.CurrentUICulture.LCID);
string res = Resources.GetString(ResourcesLocaleKind.FIDOHtml, "PROVIDERBIODESCRIPTION");
if (!string.IsNullOrEmpty(res))
return res;
else
return independent;
}
}
/// <summary>
/// GetUILabel method implementation
/// </summary>
public override string GetUILabel(AuthenticationContext ctx)
{
ResourcesLocale Resources = new ResourcesLocale(ctx.Lcid);
return Resources.GetString(ResourcesLocaleKind.FIDOHtml, "BIOUIOTPLabel");
}
/// <summary>
/// GetWizardUILabel method implementation
/// </summary>
public override string GetWizardUILabel(AuthenticationContext ctx)
{
ResourcesLocale Resources = new ResourcesLocale(ctx.Lcid);
return Resources.GetString(ResourcesLocaleKind.FIDOHtml, "BIOUIWIZLabel");
}
/// <summary>
/// GetWizardUIComment method implementation
/// </summary>
public override string GetWizardUIComment(AuthenticationContext ctx)
{
ResourcesLocale Resources = new ResourcesLocale(ctx.Lcid);
return Resources.GetString(ResourcesLocaleKind.FIDOHtml, "BIOUIWIZComment");
}
/// <summary>
/// GetWizardLinkLabel method implementation
/// </summary>
public override string GetWizardLinkLabel(AuthenticationContext ctx)
{
ResourcesLocale Resources = new ResourcesLocale(ctx.Lcid);
return Resources.GetString(ResourcesLocaleKind.FIDOHtml, "BIOWIZEnroll");
}
/// <summary>
/// GetUICFGLabel method implementation
/// </summary>
public override string GetUICFGLabel(AuthenticationContext ctx)
{
ResourcesLocale Resources = new ResourcesLocale(ctx.Lcid);
return Resources.GetString(ResourcesLocaleKind.FIDOHtml, "BIOUICFGLabel");
}
/// <summary>
/// GetUIMessage method implementation
/// </summary>
public override string GetUIMessage(AuthenticationContext ctx)
{
ResourcesLocale Resources = new ResourcesLocale(ctx.Lcid);
return Resources.GetString(ResourcesLocaleKind.FIDOHtml, "BIOUIMessage");
}
/// <summary>
/// GetUIListOptionLabel method implementation
/// </summary>
public override string GetUIListOptionLabel(AuthenticationContext ctx)
{
ResourcesLocale Resources = new ResourcesLocale(ctx.Lcid);
return Resources.GetString(ResourcesLocaleKind.FIDOHtml, "BIOUIListOptionLabel");
}
/// <summary>
/// GetUIListChoiceLabel method implementation
/// </summary>
public override string GetUIListChoiceLabel(AuthenticationContext ctx)
{
ResourcesLocale Resources = new ResourcesLocale(ctx.Lcid);
return Resources.GetString(ResourcesLocaleKind.FIDOHtml, "BIOUIListChoiceLabel");
}
/// <summary>
/// GetUIConfigLabel method implementation
/// </summary>
public override string GetUIConfigLabel(AuthenticationContext ctx)
{
ResourcesLocale Resources = new ResourcesLocale(ctx.Lcid);
return Resources.GetString(ResourcesLocaleKind.FIDOHtml, "BIOUIConfigLabel");
}
/// <summary>
/// GetUIChoiceLabel method implementation
/// </summary>
public override string GetUIChoiceLabel(AuthenticationContext ctx, AvailableAuthenticationMethod method = null)
{
ResourcesLocale Resources = new ResourcesLocale(ctx.Lcid);
return Resources.GetString(ResourcesLocaleKind.FIDOHtml, "BIOUIChoiceLabel");
}
/// <summary>
/// GetUIWarningInternetLabel method implmentation
/// </summary>
public override string GetUIWarningInternetLabel(AuthenticationContext ctx)
{
ResourcesLocale Resources = new ResourcesLocale(ctx.Lcid);
return Resources.GetString(ResourcesLocaleKind.FIDOHtml, "GLOBALWarnOverNetwork");
}
/// <summary>
/// GetUIWarningThirdPartyLabel method implementation
/// </summary>
public override string GetUIWarningThirdPartyLabel(AuthenticationContext ctx)
{
ResourcesLocale Resources = new ResourcesLocale(ctx.Lcid);
return Resources.GetString(ResourcesLocaleKind.FIDOHtml, "GLOBALWarnThirdParty");
}
/// <summary>
/// GetUIDefaultChoiceLabel method implementation
/// </summary>
public override string GetUIDefaultChoiceLabel(AuthenticationContext ctx)
{
ResourcesLocale Resources = new ResourcesLocale(ctx.Lcid);
return Resources.GetString(ResourcesLocaleKind.FIDOHtml, "GLOBALListChoiceDefaultLabel");
}
/// <summary>
/// GetUIEnrollmentTaskLabel method implementation
/// </summary>
public override string GetUIEnrollmentTaskLabel(AuthenticationContext ctx)
{
ResourcesLocale Resources = new ResourcesLocale(ctx.Lcid);
return Resources.GetString(ResourcesLocaleKind.FIDOHtml, "BIOUIEnrollTaskLabel");
}
/// <summary>
/// GetUIEnrollValidatedLabel method implementation
/// </summary>
public override string GetUIEnrollValidatedLabel(AuthenticationContext ctx)
{
ResourcesLocale Resources = new ResourcesLocale(ctx.Lcid);
return Resources.GetString(ResourcesLocaleKind.FIDOHtml, "BIOUIEnrollValidatedLabel");
}
/// <summary>
/// GetUIAccountManagementLabel method implementation
/// </summary>
public override string GetUIAccountManagementLabel(AuthenticationContext ctx)
{
return string.Empty;
}
/// <summary>
/// GetAccountManagementUrl method implmentation
/// </summary>
public override string GetAccountManagementUrl(AuthenticationContext ctx)
{
return null;
}
/// <summary>
/// IsAvailable method implmentation
/// </summary>
public override bool IsAvailable(AuthenticationContext ctx)
{
return true;
}
/// <summary>
/// IsAvailableForUser method implmentation
/// </summary>
public override bool IsAvailableForUser(AuthenticationContext ctx)
{
try
{
List<WebAuthNCredentialInformation> wcreds = GetUserStoredCredentials(ctx);
return (wcreds.Count > 0);
}
catch
{
return false;
}
}
/// <summary>
/// IsMethodElementRequired implementation
/// </summary>
public override bool IsUIElementRequired(AuthenticationContext ctx, RequiredMethodElements element)
{
switch (element)
{
case RequiredMethodElements.BiometricInputRequired:
return true;
case RequiredMethodElements.BiometricParameterRequired:
return true;
case RequiredMethodElements.BiometricLinkRequired:
return true;
case RequiredMethodElements.PinLinkRequired:
return this.PinRequired;
case RequiredMethodElements.PinParameterRequired:
return this.PinRequired;
case RequiredMethodElements.PinInputRequired:
return this.PinRequired;
}
return false;
}
/// <summary>
/// Initialize method implementation
/// </summary>
public override void Initialize(BaseProviderParams externalsystem)
{
try
{
if (!_isinitialized)
{
Trace.WriteLine("WebAuthNProvider Initialize");
if (externalsystem is WebAuthNProviderParams)
{
WebAuthNProviderParams param = externalsystem as WebAuthNProviderParams;
Config = param.Config;
Enabled = param.Enabled;
IsRequired = param.IsRequired;
WizardEnabled = param.EnrollWizard;
ForceEnrollment = param.ForceWizard;
PinRequired = param.PinRequired;
PinRequirements = param.PinRequirements;
DirectLogin = param.DirectLogin;
ConveyancePreference = param.Options.AttestationConveyancePreference;
Attachement = param.Options.AuthenticatorAttachment;
Extentions = param.Options.Extensions;
UserVerificationMethod = param.Options.UserVerificationMethod;
UserVerificationRequirement = param.Options.UserVerificationRequirement.ToEnum<UserVerificationRequirement>();
RequireResidentKey = param.Options.RequireResidentKey;
ChallengeSize = param.Configuration.ChallengeSize;
ForbiddenBrowsers = param.Configuration.ForbiddenBrowsers;
InitiatedBrowsers = param.Configuration.InitiatedBrowsers;
NoCounterBrowsers = param.Configuration.NoCounterBrowsers;
Fido2Configuration fido = new Fido2Configuration()
{
ServerDomain = param.Configuration.ServerDomain,
ServerName = param.Configuration.ServerName,
Origin = param.Configuration.Origin,
Timeout = param.Configuration.Timeout,
TimestampDriftTolerance = param.Configuration.TimestampDriftTolerance,
ChallengeSize = param.Configuration.ChallengeSize
};
Trace.WriteLine("WebAuthNAdapter Create");
_webathn = new WebAuthNAdapter(fido, _metadataservice);
Trace.WriteLine("WebAuthNAdapter Created");
_isinitialized = true;
Trace.WriteLine("WebAuthNProvider Initialized");
return;
}
else
throw new InvalidCastException("Invalid WebAuthN Provider !");
}
}
catch (Exception ex)
{
this.Enabled = false;
throw ex;
}
}
/// <summary>
/// GetAuthenticationMethods method implementation
/// </summary>
public override List<AvailableAuthenticationMethod> GetAuthenticationMethods(AuthenticationContext ctx)
{
if (!IsInitialized)
throw new Exception("Provider not initialized !");
List<AvailableAuthenticationMethod> result = GetSessionData(this.Kind, ctx);
if (result != null)
return result;
else
{
result = new List<AvailableAuthenticationMethod>();
AvailableAuthenticationMethod item = new AvailableAuthenticationMethod
{
IsDefault = true,
IsRemote = true,
IsTwoWay = true,
IsSendBack = false,
RequiredEmail = false,
RequiredPhone = false,
RequiredCode = false,
Method = AuthenticationResponseKind.Biometrics,
RequiredPin = false,
RequiredBiometrics = true
};
result.Add(item);
SaveSessionData(this.Kind, ctx, result);
}
return result;
}
/// <summary>
/// GetAuthenticationContext method implementation
/// </summary>
public override void GetAuthenticationContext(AuthenticationContext ctx)
{
if (!IsInitialized)
throw new Exception("Provider not initialized !");
ResourcesLocale Resources = new ResourcesLocale(ctx.Lcid);
AvailableAuthenticationMethod result = GetSelectedAuthenticationMethod(ctx);
ctx.PinRequired = result.RequiredPin;
ctx.IsRemote = result.IsRemote;
ctx.IsTwoWay = result.IsTwoWay;
ctx.IsSendBack = result.IsSendBack;
ctx.PreferredMethod = ctx.PreferredMethod;
ctx.SelectedMethod = result.Method;
ctx.ExtraInfos = result.ExtraInfos;
// ctx.DirectLogin = this.DirectLogin;
}
/// <summary>
/// GetAuthenticationData method implementation
/// </summary>
public override string GetAuthenticationData(AuthenticationContext ctx)
{
if (ctx.UIMode == ProviderPageMode.EnrollBiometrics)
return GetRegisterCredentialOptions(ctx);
else
return GetLoginAssertionsOptions(ctx);
}
/// <summary>
/// ReleaseAuthenticationData method implementation
/// </summary>
public override void ReleaseAuthenticationData(AuthenticationContext ctx)
{
if (ctx.UIMode == ProviderPageMode.EnrollBiometrics)
ctx.CredentialOptions = string.Empty;
else
ctx.AssertionOptions = string.Empty;
}
/// <summary>
/// PostAuthenticationRequest method implementation
/// </summary>
public override int PostAuthenticationRequest(AuthenticationContext ctx)
{
if (!IsInitialized)
throw new Exception("Provider not initialized !");
if (ctx.SelectedMethod == AuthenticationResponseKind.Error)
GetAuthenticationContext(ctx);
ctx.Notification = (int)ctx.SelectedMethod;
ctx.SessionId = Guid.NewGuid().ToString();
ctx.SessionDate = DateTime.Now;
return (int)ctx.SelectedMethod;
}
/// <summary>
/// SetAuthenticationResult method implementation
/// </summary>
public override int SetAuthenticationResult(AuthenticationContext ctx, string result)
{
string error = string.Empty;
return (int)SetAuthenticationResult(ctx, result, out error);
}
/// <summary>
/// SetAuthenticationResult method implementation
/// </summary>
public override int SetAuthenticationResult(AuthenticationContext ctx, string result, out string error)
{
if (!IsInitialized)
throw new Exception("Provider not initialized !");
if (ctx.UIMode == ProviderPageMode.EnrollBiometrics)
return (int)SetRegisterCredentialResult(ctx, result, out error);
else
return (int)SetLoginAssertionResult(ctx, result, out error);
}
#region IWebAuthNProvider
/// <summary>
/// GetManageLinkLabel method implementation
/// </summary>
public string GetManageLinkLabel(AuthenticationContext ctx)
{
ResourcesLocale Resources = new ResourcesLocale(ctx.Lcid);
return Resources.GetString(ResourcesLocaleKind.FIDOHtml, "BIOUIEnrollManageLinkLabel");
}
/// <summary>
/// GetDeleteLinkLabel method implementation
/// </summary>
public string GetDeleteLinkLabel(AuthenticationContext ctx)
{
ResourcesLocale Resources = new ResourcesLocale(ctx.Lcid);
return Resources.GetString(ResourcesLocaleKind.FIDOHtml, "BIOUIEnrollDeleteLinkLabel");
}
/// <summary>
/// GetUserStoredCredentials method implementation
/// </summary>
public List<WebAuthNCredentialInformation> GetUserStoredCredentials(AuthenticationContext ctx)
{
return GetUserStoredCredentials(ctx.UPN);
}
/// <summary>
/// GetUserStoredCredentials method implementation
/// </summary>
public List<WebAuthNCredentialInformation> GetUserStoredCredentials(string upn)
{
List<WebAuthNCredentialInformation> wcreds = new List<WebAuthNCredentialInformation>();
try
{
MFAWebAuthNUser user = RuntimeRepository.GetUser(Config, upn);
if (user != null)
{
List<MFAUserCredential> creds = RuntimeRepository.GetCredentialsByUser(Config, user);
if (creds.Count == 0)
return null;
// return wcreds;
foreach (MFAUserCredential st in creds)
{
WebAuthNCredentialInformation itm = new WebAuthNCredentialInformation()
{
CredentialID = HexaEncoding.GetHexStringFromByteArray(st.Descriptor.Id),
AaGuid = st.AaGuid,
CredType = st.CredType,
RegDate = st.RegDate,
SignatureCounter = st.SignatureCounter,
NickName = st.NickName
};
if (st.Descriptor.Type != null)
itm.Type = EnumExtensions.ToEnumMemberValue(st.Descriptor.Type.Value);
wcreds.Add(itm);
}
return wcreds.OrderByDescending(c => c.RegDate).ToList();
}
else
{
Log.WriteEntry(string.Format("{0}\r\n{1}", upn, "User does not exists !"), EventLogEntryType.Error, 5000);
throw new ArgumentNullException(string.Format("{0}\r\n{1}", upn, "User does not exists !")); ;
}
}
catch (Exception e)
{
Log.WriteEntry(string.Format("{0}\r\n{1}", upn, e.Message), EventLogEntryType.Error, 5000);
throw e;
}
}
/// <summary>
/// RemoveUserStoredCredentials method implementation
/// </summary>
public void RemoveUserStoredCredentials(AuthenticationContext ctx, string credentialid)
{
RemoveUserStoredCredentials(ctx.UPN, credentialid);
}
/// <summary>
/// RemoveUserStoredCredentials method implementation
/// </summary>
public void RemoveUserStoredCredentials(string upn, string credentialid)
{
try
{
MFAWebAuthNUser user = RuntimeRepository.GetUser(Config, upn);
if (user != null)
RuntimeRepository.RemoveUserCredential(Config, user, credentialid);
else
{
Log.WriteEntry(string.Format("{0}\r\n{1}", upn, "User does not exists !"), EventLogEntryType.Error, 5000);
throw new ArgumentNullException(string.Format("{0}\r\n{1}", upn, "User does not exists !")); ;
}
}
catch (Exception e)
{
Log.WriteEntry(string.Format("{0}\r\n{1}", upn, e.Message), EventLogEntryType.Error, 5000);
throw e;
}
}
/// <summary>
/// GetRegisterCredentialOptions method implementation
/// </summary>
private string GetRegisterCredentialOptions(AuthenticationContext ctx)
{
try
{
if (string.IsNullOrEmpty(ctx.UPN))
throw new ArgumentNullException(ctx.UPN);
string attType = this.ConveyancePreference; // none, direct, indirect
string authType = this.Attachement; // <empty>, platform, cross-platform
UserVerificationRequirement userVerification = this.UserVerificationRequirement; // preferred, required, discouraged
bool requireResidentKey = this.RequireResidentKey; // true,false
MFAWebAuthNUser user = RuntimeRepository.GetUser(Config, ctx.UPN);
if (user != null)
{
List<MFAPublicKeyCredentialDescriptor> existingKeys = RuntimeRepository.GetCredentialsByUser(Config, user).Select(c => c.Descriptor).ToList();
// 3. Create options
AuthenticatorSelection authenticatorSelection = new AuthenticatorSelection
{
RequireResidentKey = requireResidentKey,
UserVerification = userVerification
};
if (!string.IsNullOrEmpty(authType))
authenticatorSelection.AuthenticatorAttachment = authType.ToEnum<AuthenticatorAttachment>();
AuthenticationExtensionsClientInputs exts = new AuthenticationExtensionsClientInputs()
{
Extensions = this.Extentions,
UserVerificationMethod = this.UserVerificationMethod
};
CredentialCreateOptions options = null;
if (existingKeys.Count > 0)
options = _webathn.GetRegisterCredentialOptions(user.ToCore(), existingKeys.ToCore(), authenticatorSelection, attType.ToEnum<AttestationConveyancePreference>(), exts);
else
options = _webathn.GetRegisterCredentialOptions(user.ToCore(), null, authenticatorSelection, attType.ToEnum<AttestationConveyancePreference>(), exts);
string result = options.ToJson();
ctx.CredentialOptions = result;
return result;
}
else
{
Log.WriteEntry(string.Format("{0}\r\n{1}", ctx.UPN, "User does not exists !"), EventLogEntryType.Error, 5000);
string result = (new CredentialMakeResult { Status = "error", ErrorMessage = string.Format("{0}", "User does not exists !") }).ToJson();
ctx.CredentialOptions = result;
return result;
}
}
catch (Exception e)
{
Log.WriteEntry(string.Format("{0}\r\n{1}", ctx.UPN, e.Message), System.Diagnostics.EventLogEntryType.Error, 5000);
string result = (new CredentialMakeResult { Status = "error", ErrorMessage = string.Format("{0}{1}", e.Message, e.InnerException != null ? " (" + e.InnerException.Message + ")" : "") }).ToJson();
ctx.CredentialOptions = result;
return result;
}
}
/// <summary>
/// SetRegisterCredentialResult method implementation
/// </summary>
private int SetRegisterCredentialResult(AuthenticationContext ctx, string jsonResponse, out string error)
{
bool isDeserialized = false;
try
{
string jsonOptions = ctx.CredentialOptions;
if (string.IsNullOrEmpty(jsonOptions))
throw new ArgumentNullException(jsonOptions);
if (string.IsNullOrEmpty(jsonResponse))
throw new ArgumentNullException(jsonResponse);
MFAWebAuthNUser user = RuntimeRepository.GetUser(Config, ctx.UPN);
if (user != null)
{
CredentialCreateOptions options = CredentialCreateOptions.FromJson(jsonOptions);
#pragma warning disable CS1998 // Cette méthode async n'a pas d'opérateur 'await' et elle s'exécutera de façon synchrone
IsCredentialIdUniqueToUserAsyncDelegate callback = async (args) =>
#pragma warning restore CS1998 // Cette méthode async n'a pas d'opérateur 'await' et elle s'exécutera de façon synchrone
{
var users = RuntimeRepository.GetUsersByCredentialId(Config, user, args.CredentialId);
if (users.Count > 0)
return false;
return true;
};
AuthenticatorAttestationRawResponse attestationResponse = JsonConvert.DeserializeObject<AuthenticatorAttestationRawResponse>(jsonResponse);
isDeserialized = true;
CredentialMakeResult success = _webathn.SetRegisterCredentialResult(attestationResponse, options, callback).Result;
RuntimeRepository.AddUserCredential(Config, user, new MFAUserCredential
{
Descriptor = new MFAPublicKeyCredentialDescriptor(success.Result.CredentialId),
PublicKey = success.Result.PublicKey,
UserHandle = success.Result.User.Id,
SignatureCounter = success.Result.Counter,
CredType = success.Result.CredType,
RegDate = DateTime.Now,
AaGuid = success.Result.Aaguid,
NickName = ctx.NickName
});
error = string.Empty;
return (int)AuthenticationResponseKind.Biometrics;
}
else
{
Log.WriteEntry(string.Format("{0}\r\n{1}", ctx.UPN, "User does not exists !"), System.Diagnostics.EventLogEntryType.Error, 5000);
error = string.Format("{0}\r\n{1}", ctx.UPN, "User does not exists !");
return (int)AuthenticationResponseKind.Error;
}
}
catch (Exception e)
{
if (isDeserialized)
Log.WriteEntry(string.Format("{0}\r\n{1}", ctx.UPN, e.Message), EventLogEntryType.Error, 5000);
else
Log.WriteEntry(string.Format("{0}\r\n{1}", ctx.UPN, jsonResponse), EventLogEntryType.Error, 5000);
error = e.Message;
return (int)AuthenticationResponseKind.Error;
}
}
/// <summary>
/// GetLoginAssertionsOptions method implementation
/// </summary>
private string GetLoginAssertionsOptions(AuthenticationContext ctx)
{
try
{
List<MFAPublicKeyCredentialDescriptor> existingCredentials = new List<MFAPublicKeyCredentialDescriptor>();
if (!string.IsNullOrEmpty(ctx.UPN))
{
var user = RuntimeRepository.GetUser(Config, ctx.UPN);
if (user == null)
throw new ArgumentException("Username was not registered");
existingCredentials = RuntimeRepository.GetCredentialsByUser(Config, user).Select(c => c.Descriptor).ToList();
}
AuthenticationExtensionsClientInputs exts = new AuthenticationExtensionsClientInputs()
{
Extensions = this.Extentions,
UserVerificationMethod = this.UserVerificationMethod,
};
UserVerificationRequirement uv = this.UserVerificationRequirement;
AssertionOptions options = null;
if (existingCredentials.Count > 0)
options = _webathn.GetAssertionOptions(existingCredentials.ToCore(), uv, exts);
else
options = _webathn.GetAssertionOptions(null, uv, exts);
string result = options.ToJson();
ctx.AssertionOptions = result;
return result;
}
catch (Exception e)
{
Log.WriteEntry(string.Format("{0}\r\n{1}", ctx.UPN, e.Message), EventLogEntryType.Error, 5000);
string result = (new AssertionOptions { Status = "error", ErrorMessage = string.Format("{0} / {1}", e.Message, e.InnerException != null ? " (" + e.InnerException.Message + ")" : "") }).ToJson();
ctx.AssertionOptions = result;
return result;
}
}
/// <summary>
/// SetLoginAssertionResult method implementation
/// </summary>
private int SetLoginAssertionResult(AuthenticationContext ctx, string jsonResponse, out string error)
{
bool isDeserialized = false;
try
{
string jsonOptions = ctx.AssertionOptions;
if (string.IsNullOrEmpty(jsonOptions))
throw new ArgumentNullException(jsonOptions);
if (string.IsNullOrEmpty(jsonResponse))
throw new ArgumentNullException(jsonResponse);
MFAWebAuthNUser user = RuntimeRepository.GetUser(Config, ctx.UPN);
if (user != null)
{
AssertionOptions options = AssertionOptions.FromJson(jsonOptions);
try
{
AuthenticatorAssertionRawResponse clientResponse = JsonConvert.DeserializeObject<AuthenticatorAssertionRawResponse>(jsonResponse);
isDeserialized = true;
MFAUserCredential creds = RuntimeRepository.GetCredentialById(Config, user, clientResponse.Id);
if (creds == null)
{
throw new Exception("Unknown credentials");
}
AuthenticatorData authData = new AuthenticatorData(clientResponse.Response.AuthenticatorData);
bool isnocount = Utilities.IsNoCounterDevice(this.Config.WebAuthNProvider.Configuration, ctx);
uint authCounter = 0;
uint storedCounter = 0;
if (!isnocount)
{
authCounter = authData.SignCount;
storedCounter = creds.SignatureCounter;
}
else
if ((authCounter > 0) && (authCounter <= storedCounter))
{
ResourcesLocale Resources = new ResourcesLocale(ctx.Lcid);
throw new Exception(Resources.GetString(ResourcesLocaleKind.FIDOHtml, "BIOERRORAUTHREPLAY"));
}
#pragma warning disable CS1998 // Cette méthode async n'a pas d'opérateur 'await' et elle s'exécutera de façon synchrone
IsUserHandleOwnerOfCredentialIdAsync callback = async (args) =>
#pragma warning restore CS1998 // Cette méthode async n'a pas d'opérateur 'await' et elle s'exécutera de façon synchrone
{
var storedCreds = RuntimeRepository.GetCredentialsByUserHandle(Config, user, args.UserHandle);
return storedCreds.Exists(c => c.Descriptor.Id.SequenceEqual(args.CredentialId));
};
// Apple counter always 0
AssertionVerificationResult res = _webathn.SetAssertionResult(clientResponse, options, creds.PublicKey, storedCounter, callback).Result;
if (!isnocount)
{
RuntimeRepository.UpdateCounter(Config, user, res.CredentialId, res.Counter);
}
else
{
RuntimeRepository.UpdateCounter(Config, user, res.CredentialId, 0);
}
if (!authData.UserPresent || !authData.UserVerified)
{
switch (creds.CredType)
{
case "none":
ctx.PinRequirements = (this.PinRequirements.HasFlag(WebAuthNPinRequirements.None));
break;
case "android-key":
ctx.PinRequirements = (this.PinRequirements.HasFlag(WebAuthNPinRequirements.AndroidKey));
break;
case "android-safetynet":
ctx.PinRequirements = (this.PinRequirements.HasFlag(WebAuthNPinRequirements.AndroidSafetyNet));
break;
case "fido-u2f":
ctx.PinRequirements = (this.PinRequirements.HasFlag(WebAuthNPinRequirements.Fido2U2f));
break;
case "packed":
ctx.PinRequirements = (this.PinRequirements.HasFlag(WebAuthNPinRequirements.Packed));
break;
case "tpm":
ctx.PinRequirements = (this.PinRequirements.HasFlag(WebAuthNPinRequirements.TPM));
break;
case "apple":
ctx.PinRequirements = (this.PinRequirements.HasFlag(WebAuthNPinRequirements.Apple));
break;
default:
ctx.PinRequirements = false;
break;
}
}
else
ctx.PinRequirements = false;
error = string.Empty;
return (int)AuthenticationResponseKind.Biometrics;
}
catch (Exception ex)
{
if (isDeserialized)
Log.WriteEntry(string.Format("{0}\r\n{1}", ctx.UPN, ex.Message), EventLogEntryType.Error, 5000);
else
Log.WriteEntry(string.Format("{0}\r\n{1}", ctx.UPN, jsonResponse), EventLogEntryType.Error, 5000);
error = ex.Message;
return (int)AuthenticationResponseKind.Error;
}
}
else
{
Log.WriteEntry(string.Format("{0}\r\n{1}", ctx.UPN, "User does not exists !"), EventLogEntryType.Error, 5000);
error = string.Format("{0}\r\n{1}", ctx.UPN, "User does not exists !");
return (int)AuthenticationResponseKind.Error;
}
}
catch (Exception e)
{
Log.WriteEntry(string.Format("{0}\r\n{1}", ctx.UPN, e.Message), EventLogEntryType.Error, 5000);
error = e.Message;
return (int)AuthenticationResponseKind.Error;
}
}
#endregion
}
/// <summary>
/// WebAuthNTypesExtensions class
/// Maps differents classes MFA/FIDO Components
/// </summary>
internal static class WebAuthNTypesExtensions
{
internal static MFAWebAuthNUser FromCore(this Fido2User user)
{
var usr = new MFAWebAuthNUser()
{
DisplayName = user.DisplayName,
Id = user.Id,
Name = user.Name
};
return usr;
}
internal static Fido2User ToCore(this MFAWebAuthNUser user)
{
var usr = new Fido2User()
{
DisplayName = user.DisplayName,
Id = user.Id,
Name = user.Name
};
return usr;
}
internal static MFAPublicKeyCredentialDescriptor FromCore(this PublicKeyCredentialDescriptor data)
{
var creds = new MFAPublicKeyCredentialDescriptor()
{
Id = data.Id,
Type = (MFAPublicKeyCredentialType)data.Type
};
if (data.Transports != null)
{
creds.Transports = new MFAAuthenticatorTransport[data.Transports.Length];
for (int i = 0; i < data.Transports.Length; i++)
{
creds.Transports[i] = (MFAAuthenticatorTransport)data.Transports[i];
}
}
return creds;
}
internal static PublicKeyCredentialDescriptor ToCore(this MFAPublicKeyCredentialDescriptor data)
{
var creds = new PublicKeyCredentialDescriptor()
{
Id = data.Id,
Type = (PublicKeyCredentialType)data.Type
};
if (data.Transports != null)
{
creds.Transports = new AuthenticatorTransport[data.Transports.Length];
for (int i = 0; i < data.Transports.Length; i++)
{
creds.Transports[i] = (AuthenticatorTransport)data.Transports[i];
}
}
return creds;
}
internal static List<MFAPublicKeyCredentialDescriptor> FromCore(this List<PublicKeyCredentialDescriptor> data)
{
var creds = new List<MFAPublicKeyCredentialDescriptor>();
foreach (PublicKeyCredentialDescriptor Desc in data)
{
MFAPublicKeyCredentialDescriptor res = Desc.FromCore();
creds.Add(res);
}
return creds;
}
internal static List<PublicKeyCredentialDescriptor> ToCore(this List<MFAPublicKeyCredentialDescriptor> data)
{
var creds = new List<PublicKeyCredentialDescriptor>();
foreach(MFAPublicKeyCredentialDescriptor MFADesc in data)
{
PublicKeyCredentialDescriptor res = MFADesc.ToCore();
creds.Add(res);
}
return creds;
}
}
}
| 45.538387 | 211 | 0.531744 | [
"MIT"
] | neos-sdi/adfsmfa | Neos.IdentityServer 3.1/Neos.IdentityServer.MultiFactor.WebAuthN.Provider/Neos.IdentityServer.MultiFactor.Providers.WebAuthN.cs | 46,877 | C# |
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using GodLesZ.Library.Win7.Shell;
using MS.WindowsAPICodePack.Internal;
namespace GodLesZ.Library.Win7.Controls {
internal enum ShellViewGetItemObject {
Background = 0x00000000,
Selection = 0x00000001,
AllView = 0x00000002,
Checked = 0x00000003,
TypeMask = 0x0000000F,
ViewOrderFlag = unchecked((int)0x80000000)
}
[Flags]
internal enum FolderOptions {
AutoArrange = 0x00000001,
AbbreviatedNames = 0x00000002,
SnapToGrid = 0x00000004,
OwnerData = 0x00000008,
BestFitWindow = 0x00000010,
Desktop = 0x00000020,
SingleSelection = 0x00000040,
NoSubfolders = 0x00000080,
Transparent = 0x00000100,
NoClientEdge = 0x00000200,
NoScroll = 0x00000400,
AlignLeft = 0x00000800,
NoIcons = 0x00001000,
ShowSelectionAlways = 0x00002000,
NoVisible = 0x00004000,
SingleClickActivate = 0x00008000,
NoWebView = 0x00010000,
HideFilenames = 0x00020000,
CheckSelect = 0x00040000,
NoEnumRefresh = 0x00080000,
NoGrouping = 0x00100000,
FullRowSelect = 0x00200000,
NoFilters = 0x00400000,
NoColumnHeaders = 0x00800000,
NoHeaderInAllViews = 0x01000000,
ExtendedTiles = 0x02000000,
TriCheckSelect = 0x04000000,
AutoCheckSelect = 0x08000000,
NoBrowserViewState = 0x10000000,
SubsetGroups = 0x20000000,
UseSearchFolders = 0x40000000,
AllowRightToLeftReading = unchecked((int)0x80000000)
}
internal enum FolderViewMode {
Auto = -1,
First = 1,
Icon = 1,
SmallIcon = 2,
List = 3,
Details = 4,
Thumbnail = 5,
Tile = 6,
Thumbstrip = 7,
Content = 8,
Last = 8
}
internal enum ExplorerPaneState {
DoNotCare = 0x00000000,
DefaultOn = 0x00000001,
DefaultOff = 0x00000002,
StateMask = 0x0000ffff,
InitialState = 0x00010000,
Force = 0x00020000
}
[StructLayout(LayoutKind.Sequential, Pack = 4)]
internal class FolderSettings {
public FolderViewMode ViewMode;
public FolderOptions Options;
}
[Flags]
internal enum ExplorerBrowserOptions {
NavigateOnce = 0x00000001,
ShowFrames = 0x00000002,
AlwaysNavigate = 0x00000004,
NoTravelLog = 0x00000008,
NoWrapperWindow = 0x00000010,
HtmlSharepointView = 0x00000020
}
internal enum CommDlgBrowserStateChange {
SetFocus = 0,
KillFocus = 1,
SelectionChange = 2,
Rename = 3,
StateChange = 4
}
internal enum CommDlgBrowserNotifyType {
Done = 1,
Start = 2
}
internal enum CommDlgBrowser2ViewFlags {
ShowAllFiles = 0x00000001,
IsFileSave = 0x00000002,
AllowPreviewPane = 0x00000004,
NoSelectVerb = 0x00000008,
NoIncludeItem = 0x00000010,
IsFolderPicker = 0x00000020
}
// Disable warning if a method declaration hides another inherited from a parent COM interface
// To successfully import a COM interface, all inherited methods need to be declared again with
// the exception of those already declared in "IUnknown"
#pragma warning disable 108
[ComImport,
TypeLibType(TypeLibTypeFlags.FCanCreate),
ClassInterface(ClassInterfaceType.None),
Guid(ExplorerBrowserCLSIDGuid.ExplorerBrowser)]
internal class ExplorerBrowserClass : IExplorerBrowser {
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
public virtual extern void Initialize(IntPtr hwndParent, [In]ref NativeRect prc, [In] FolderSettings pfs);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
public virtual extern void Destroy();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
public virtual extern void SetRect([In, Out] ref IntPtr phdwp, NativeRect rcBrowser);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
public virtual extern void SetPropertyBag([MarshalAs(UnmanagedType.LPWStr)] string pszPropertyBag);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
public virtual extern void SetEmptyText([MarshalAs(UnmanagedType.LPWStr)] string pszEmptyText);
[PreserveSig]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
public virtual extern HResult SetFolderSettings(FolderSettings pfs);
[PreserveSig]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
public virtual extern HResult Advise(IntPtr psbe, out uint pdwCookie);
[PreserveSig]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
public virtual extern HResult Unadvise(uint dwCookie);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
public virtual extern void SetOptions([In]ExplorerBrowserOptions dwFlag);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
public virtual extern void GetOptions(out ExplorerBrowserOptions pdwFlag);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
public virtual extern void BrowseToIDList(IntPtr pidl, uint uFlags);
[PreserveSig]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
public virtual extern HResult BrowseToObject([MarshalAs(UnmanagedType.IUnknown)] object punk, uint uFlags);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
public virtual extern void FillFromObject([MarshalAs(UnmanagedType.IUnknown)] object punk, int dwFlags);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
public virtual extern void RemoveAll();
[PreserveSig]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
public virtual extern HResult GetCurrentView(ref Guid riid, out IntPtr ppv);
}
[ComImport,
InterfaceType(ComInterfaceType.InterfaceIsIUnknown),
Guid(ExplorerBrowserIIDGuid.IExplorerBrowser)]
internal interface IExplorerBrowser {
/// <summary>
/// Prepares the browser to be navigated.
/// </summary>
/// <param name="hwndParent">A handle to the owner window or control.</param>
/// <param name="prc">A pointer to a RECT containing the coordinates of the bounding rectangle
/// the browser will occupy. The coordinates are relative to hwndParent. If this parameter is NULL,
/// then method IExplorerBrowser::SetRect should subsequently be called.</param>
/// <param name="pfs">A pointer to a FOLDERSETTINGS structure that determines how the folder will be
/// displayed in the view. If this parameter is NULL, then method IExplorerBrowser::SetFolderSettings
/// should be called, otherwise, the default view settings for the folder are used.</param>
/// <returns></returns>
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void Initialize(IntPtr hwndParent, [In] ref NativeRect prc, [In] FolderSettings pfs);
/// <summary>
/// Destroys the browser.
/// </summary>
/// <returns></returns>
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void Destroy();
/// <summary>
/// Sets the size and position of the view windows created by the browser.
/// </summary>
/// <param name="phdwp">A pointer to a DeferWindowPos handle. This paramater can be NULL.</param>
/// <param name="rcBrowser">The coordinates that the browser will occupy.</param>
/// <returns></returns>
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void SetRect([In, Out] ref IntPtr phdwp, NativeRect rcBrowser);
/// <summary>
/// Sets the name of the property bag.
/// </summary>
/// <param name="pszPropertyBag">A pointer to a constant, null-terminated, Unicode string that contains
/// the name of the property bag. View state information that is specific to the application of the
/// client is stored (persisted) using this name.</param>
/// <returns></returns>
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void SetPropertyBag([MarshalAs(UnmanagedType.LPWStr)] string pszPropertyBag);
/// <summary>
/// Sets the default empty text.
/// </summary>
/// <param name="pszEmptyText">A pointer to a constant, null-terminated, Unicode string that contains
/// the empty text.</param>
/// <returns></returns>
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void SetEmptyText([MarshalAs(UnmanagedType.LPWStr)] string pszEmptyText);
/// <summary>
/// Sets the folder settings for the current view.
/// </summary>
/// <param name="pfs">A pointer to a FOLDERSETTINGS structure that contains the folder settings
/// to be applied.</param>
/// <returns></returns>
[PreserveSig]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
HResult SetFolderSettings(FolderSettings pfs);
/// <summary>
/// Initiates a connection with IExplorerBrowser for event callbacks.
/// </summary>
/// <param name="psbe">A pointer to the IExplorerBrowserEvents interface of the object to be
/// advised of IExplorerBrowser events</param>
/// <param name="pdwCookie">When this method returns, contains a token that uniquely identifies
/// the event listener. This allows several event listeners to be subscribed at a time.</param>
/// <returns></returns>
[PreserveSig]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
HResult Advise(IntPtr psbe, out uint pdwCookie);
/// <summary>
/// Terminates an advisory connection.
/// </summary>
/// <param name="dwCookie">A connection token previously returned from IExplorerBrowser::Advise.
/// Identifies the connection to be terminated.</param>
/// <returns></returns>
[PreserveSig]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
HResult Unadvise([In] uint dwCookie);
/// <summary>
/// Sets the current browser options.
/// </summary>
/// <param name="dwFlag">One or more EXPLORER_BROWSER_OPTIONS flags to be set.</param>
/// <returns></returns>
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void SetOptions([In]ExplorerBrowserOptions dwFlag);
/// <summary>
/// Gets the current browser options.
/// </summary>
/// <param name="pdwFlag">When this method returns, contains the current EXPLORER_BROWSER_OPTIONS
/// for the browser.</param>
/// <returns></returns>
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetOptions(out ExplorerBrowserOptions pdwFlag);
/// <summary>
/// Browses to a pointer to an item identifier list (PIDL)
/// </summary>
/// <param name="pidl">A pointer to a const ITEMIDLIST (item identifier list) that specifies an object's
/// location as the destination to navigate to. This parameter can be NULL.</param>
/// <param name="uFlags">A flag that specifies the category of the pidl. This affects how
/// navigation is accomplished</param>
/// <returns></returns>
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void BrowseToIDList(IntPtr pidl, uint uFlags);
/// <summary>
/// Browse to an object
/// </summary>
/// <param name="punk">A pointer to an object to browse to. If the object cannot be browsed,
/// an error value is returned.</param>
/// <param name="uFlags">A flag that specifies the category of the pidl. This affects how
/// navigation is accomplished. </param>
/// <returns></returns>
[PreserveSig]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
HResult BrowseToObject([MarshalAs(UnmanagedType.IUnknown)] object punk, uint uFlags);
/// <summary>
/// Creates a results folder and fills it with items.
/// </summary>
/// <param name="punk">An interface pointer on the source object that will fill the IResultsFolder</param>
/// <param name="dwFlags">One of the EXPLORER_BROWSER_FILL_FLAGS</param>
/// <returns></returns>
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void FillFromObject([MarshalAs(UnmanagedType.IUnknown)] object punk, int dwFlags);
/// <summary>
/// Removes all items from the results folder.
/// </summary>
/// <returns></returns>
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void RemoveAll();
/// <summary>
/// Gets an interface for the current view of the browser.
/// </summary>
/// <param name="riid">A reference to the desired interface ID.</param>
/// <param name="ppv">When this method returns, contains the interface pointer requested in riid.
/// This will typically be IShellView or IShellView2. </param>
/// <returns></returns>
[PreserveSig]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
HResult GetCurrentView(ref Guid riid, out IntPtr ppv);
}
[ComImport,
Guid(ExplorerBrowserIIDGuid.IServiceProvider),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IServiceProvider {
[PreserveSig]
[MethodImpl(MethodImplOptions.InternalCall)]
HResult QueryService(ref Guid guidService, ref Guid riid, out IntPtr ppvObject);
};
[ComImport,
Guid(ExplorerBrowserIIDGuid.IFolderView),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IFolderView {
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetCurrentViewMode([Out] out uint pViewMode);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void SetCurrentViewMode(uint ViewMode);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetFolder(ref Guid riid, [MarshalAs(UnmanagedType.IUnknown)] out object ppv);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void Item(int iItemIndex, out IntPtr ppidl);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void ItemCount(uint uFlags, out int pcItems);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void Items(uint uFlags, ref Guid riid, [Out, MarshalAs(UnmanagedType.IUnknown)] out object ppv);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetSelectionMarkedItem(out int piItem);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetFocusedItem(out int piItem);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetItemPosition(IntPtr pidl, out NativePoint ppt);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetSpacing([Out] out NativePoint ppt);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetDefaultSpacing(out NativePoint ppt);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetAutoArrange();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void SelectItem(int iItem, uint dwFlags);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void SelectAndPositionItems(uint cidl, IntPtr apidl, ref NativePoint apt, uint dwFlags);
}
[ComImport,
Guid(ExplorerBrowserIIDGuid.IFolderView2),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IFolderView2 : IFolderView {
// IFolderView
[PreserveSig]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
HResult GetCurrentViewMode(out uint pViewMode);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void SetCurrentViewMode(uint ViewMode);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetFolder(ref Guid riid, [MarshalAs(UnmanagedType.IUnknown)] out object ppv);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void Item(int iItemIndex, out IntPtr ppidl);
[PreserveSig]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
HResult ItemCount(uint uFlags, out int pcItems);
[PreserveSig]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
HResult Items(uint uFlags, ref Guid riid, [Out, MarshalAs(UnmanagedType.IUnknown)] out object ppv);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetSelectionMarkedItem(out int piItem);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetFocusedItem(out int piItem);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetItemPosition(IntPtr pidl, out NativePoint ppt);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetSpacing([Out] out NativePoint ppt);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetDefaultSpacing(out NativePoint ppt);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetAutoArrange();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void SelectItem(int iItem, uint dwFlags);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void SelectAndPositionItems(uint cidl, IntPtr apidl, ref NativePoint apt, uint dwFlags);
// IFolderView2
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void SetGroupBy(IntPtr key, bool fAscending);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetGroupBy(ref IntPtr pkey, ref bool pfAscending);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void SetViewProperty(IntPtr pidl, IntPtr propkey, object propvar);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetViewProperty(IntPtr pidl, IntPtr propkey, out object ppropvar);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void SetTileViewProperties(IntPtr pidl, [MarshalAs(UnmanagedType.LPWStr)] string pszPropList);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void SetExtendedTileViewProperties(IntPtr pidl, [MarshalAs(UnmanagedType.LPWStr)] string pszPropList);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void SetText(int iType, [MarshalAs(UnmanagedType.LPWStr)] string pwszText);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void SetCurrentFolderFlags(uint dwMask, uint dwFlags);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetCurrentFolderFlags(out uint pdwFlags);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetSortColumnCount(out int pcColumns);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void SetSortColumns(IntPtr rgSortColumns, int cColumns);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetSortColumns(out IntPtr rgSortColumns, int cColumns);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetItem(int iItem, ref Guid riid, [MarshalAs(UnmanagedType.IUnknown)] out object ppv);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetVisibleItem(int iStart, bool fPrevious, out int piItem);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetSelectedItem(int iStart, out int piItem);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetSelection(bool fNoneImpliesFolder, out IShellItemArray ppsia);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetSelectionState(IntPtr pidl, out uint pdwFlags);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void InvokeVerbOnSelection([In, MarshalAs(UnmanagedType.LPWStr)] string pszVerb);
[PreserveSig]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
HResult SetViewModeAndIconSize(int uViewMode, int iImageSize);
[PreserveSig]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
HResult GetViewModeAndIconSize(out int puViewMode, out int piImageSize);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void SetGroupSubsetCount(uint cVisibleRows);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetGroupSubsetCount(out uint pcVisibleRows);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void SetRedraw(bool fRedrawOn);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void IsMoveInSameFolder();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void DoRename();
}
[ComImport,
Guid(ExplorerBrowserIIDGuid.IExplorerPaneVisibility),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IExplorerPaneVisibility {
[PreserveSig]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
HResult GetPaneState(ref Guid explorerPane, out ExplorerPaneState peps);
};
[ComImport,
Guid(ExplorerBrowserIIDGuid.IExplorerBrowserEvents),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IExplorerBrowserEvents {
[PreserveSig]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
HResult OnNavigationPending(IntPtr pidlFolder);
[PreserveSig]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
HResult OnViewCreated([MarshalAs(UnmanagedType.IUnknown)] object psv);
[PreserveSig]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
HResult OnNavigationComplete(IntPtr pidlFolder);
[PreserveSig]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
HResult OnNavigationFailed(IntPtr pidlFolder);
}
#region Unused - Keeping for debugging bug #885228
//[ComImport,
// Guid(ExplorerBrowserIIDGuid.ICommDlgBrowser),
// InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
//internal interface ICommDlgBrowser
//{
// [PreserveSig]
// [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
// HResult OnDefaultCommand(IntPtr ppshv);
// [PreserveSig]
// [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
// HResult OnStateChange(
// IntPtr ppshv,
// CommDlgBrowserStateChange uChange);
// [PreserveSig]
// [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
// HResult IncludeObject(
// IntPtr ppshv,
// IntPtr pidl);
//}
//[ComImport,
// Guid(ExplorerBrowserIIDGuid.ICommDlgBrowser2),
// InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
//internal interface ICommDlgBrowser2
//{
// // dlg
// [PreserveSig]
// [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
// HResult OnDefaultCommand(IntPtr ppshv);
// [PreserveSig]
// [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
// HResult OnStateChange(
// IntPtr ppshv,
// CommDlgBrowserStateChange uChange);
// [PreserveSig]
// [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
// HResult IncludeObject(
// IntPtr ppshv,
// IntPtr pidl);
// // dlg2
// [PreserveSig]
// [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
// HResult GetDefaultMenuText(
// [In] IShellView shellView,
// StringBuilder buffer, //A pointer to a buffer that is used by the Shell browser to return the default shortcut menu text.
// [In] int bufferMaxLength); //should be max size = 260?
// [PreserveSig]
// [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
// HResult GetViewFlags(CommDlgBrowser2ViewFlags pdwFlags);
// [PreserveSig]
// [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
// HResult Notify(
// IntPtr pshv,
// CommDlgBrowserNotifyType notifyType);
//}
#endregion
[ComImport,
Guid(ExplorerBrowserIIDGuid.ICommDlgBrowser3),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface ICommDlgBrowser3 {
// dlg1
[PreserveSig]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
HResult OnDefaultCommand(IntPtr ppshv);
[PreserveSig]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
HResult OnStateChange(
IntPtr ppshv,
CommDlgBrowserStateChange uChange);
[PreserveSig]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
HResult IncludeObject(
IntPtr ppshv,
IntPtr pidl);
// dlg2
[PreserveSig]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
HResult GetDefaultMenuText(
IShellView shellView,
IntPtr buffer, //A pointer to a buffer that is used by the Shell browser to return the default shortcut menu text.
int bufferMaxLength); //should be max size = 260?
[PreserveSig]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
HResult GetViewFlags(
[Out] out uint pdwFlags); // CommDlgBrowser2ViewFlags
[PreserveSig]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
HResult Notify(
IntPtr pshv, CommDlgBrowserNotifyType notifyType);
// dlg3
[PreserveSig]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
HResult GetCurrentFilter(
StringBuilder pszFileSpec,
int cchFileSpec);
[PreserveSig]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
HResult OnColumnClicked(
IShellView ppshv,
int iColumn);
[PreserveSig]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
HResult OnPreViewCreated(IShellView ppshv);
}
[ComImport,
Guid(ExplorerBrowserIIDGuid.IInputObject),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IInputObject {
[PreserveSig]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
HResult UIActivateIO(bool fActivate, ref System.Windows.Forms.Message pMsg);
[PreserveSig]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
HResult HasFocusIO();
[PreserveSig]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
HResult TranslateAcceleratorIO(ref System.Windows.Forms.Message pMsg);
};
[ComImport,
Guid(ExplorerBrowserIIDGuid.IShellView),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IShellView {
// IOleWindow
[PreserveSig]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
HResult GetWindow(
out IntPtr phwnd);
[PreserveSig]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
HResult ContextSensitiveHelp(
bool fEnterMode);
// IShellView
[PreserveSig]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
HResult TranslateAccelerator(
IntPtr pmsg);
[PreserveSig]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
HResult EnableModeless(
bool fEnable);
[PreserveSig]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
HResult UIActivate(
uint uState);
[PreserveSig]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
HResult Refresh();
[PreserveSig]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
HResult CreateViewWindow(
[MarshalAs(UnmanagedType.IUnknown)] object psvPrevious,
IntPtr pfs,
[MarshalAs(UnmanagedType.IUnknown)] object psb,
IntPtr prcView,
out IntPtr phWnd);
[PreserveSig]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
HResult DestroyViewWindow();
[PreserveSig]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
HResult GetCurrentInfo(
out IntPtr pfs);
[PreserveSig]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
HResult AddPropertySheetPages(
uint dwReserved,
IntPtr pfn,
uint lparam);
[PreserveSig]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
HResult SaveViewState();
[PreserveSig]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
HResult SelectItem(
IntPtr pidlItem,
uint uFlags);
[PreserveSig]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
HResult GetItemObject(
ShellViewGetItemObject uItem,
ref Guid riid,
[MarshalAs(UnmanagedType.IUnknown)] out object ppv);
}
#pragma warning restore 108
}
| 38.614691 | 132 | 0.772802 | [
"MIT"
] | GodLesZ/godlesz.library | Win7/Shell/Interop/ExplorerBrowser/ExplorerBrowserCOMInterfaces.cs | 29,967 | C# |
using System;
using System.Xml.Serialization;
using System.ComponentModel.DataAnnotations;
using BroadWorksConnector.Ocip.Validation;
using System.Collections.Generic;
namespace BroadWorksConnector.Ocip.Models
{
/// <summary>
///
/// </summary>
[Serializable]
[XmlRoot(Namespace = "")]
[Groups(@"[{""__type"":""Sequence:#BroadWorksConnector.Ocip.Validation"",""id"":""ab0042aa512abc10edb3c55e4b416b0b:38498""}]")]
public class SystemVoiceMessagingGroupGetVoicePortalMenusResponse20AdditionalMessageOptionsMenuKeys
{
private string _saveMessage;
[XmlElement(ElementName = "saveMessage", IsNullable = false, Namespace = "")]
[Optional]
[Group(@"ab0042aa512abc10edb3c55e4b416b0b:38498")]
[Length(1)]
[RegularExpression(@"[0-9]|\*|#")]
public string SaveMessage
{
get => _saveMessage;
set
{
SaveMessageSpecified = true;
_saveMessage = value;
}
}
[XmlIgnore]
protected bool SaveMessageSpecified { get; set; }
private string _deleteMessage;
[XmlElement(ElementName = "deleteMessage", IsNullable = false, Namespace = "")]
[Optional]
[Group(@"ab0042aa512abc10edb3c55e4b416b0b:38498")]
[Length(1)]
[RegularExpression(@"[0-9]|\*|#")]
public string DeleteMessage
{
get => _deleteMessage;
set
{
DeleteMessageSpecified = true;
_deleteMessage = value;
}
}
[XmlIgnore]
protected bool DeleteMessageSpecified { get; set; }
private string _playEnvelope;
[XmlElement(ElementName = "playEnvelope", IsNullable = false, Namespace = "")]
[Optional]
[Group(@"ab0042aa512abc10edb3c55e4b416b0b:38498")]
[Length(1)]
[RegularExpression(@"[0-9]|\*|#")]
public string PlayEnvelope
{
get => _playEnvelope;
set
{
PlayEnvelopeSpecified = true;
_playEnvelope = value;
}
}
[XmlIgnore]
protected bool PlayEnvelopeSpecified { get; set; }
private string _callbackCaller;
[XmlElement(ElementName = "callbackCaller", IsNullable = false, Namespace = "")]
[Optional]
[Group(@"ab0042aa512abc10edb3c55e4b416b0b:38498")]
[Length(1)]
[RegularExpression(@"[0-9]|\*|#")]
public string CallbackCaller
{
get => _callbackCaller;
set
{
CallbackCallerSpecified = true;
_callbackCaller = value;
}
}
[XmlIgnore]
protected bool CallbackCallerSpecified { get; set; }
private string _composeMessage;
[XmlElement(ElementName = "composeMessage", IsNullable = false, Namespace = "")]
[Optional]
[Group(@"ab0042aa512abc10edb3c55e4b416b0b:38498")]
[Length(1)]
[RegularExpression(@"[0-9]|\*|#")]
public string ComposeMessage
{
get => _composeMessage;
set
{
ComposeMessageSpecified = true;
_composeMessage = value;
}
}
[XmlIgnore]
protected bool ComposeMessageSpecified { get; set; }
private string _replyMessage;
[XmlElement(ElementName = "replyMessage", IsNullable = false, Namespace = "")]
[Optional]
[Group(@"ab0042aa512abc10edb3c55e4b416b0b:38498")]
[Length(1)]
[RegularExpression(@"[0-9]|\*|#")]
public string ReplyMessage
{
get => _replyMessage;
set
{
ReplyMessageSpecified = true;
_replyMessage = value;
}
}
[XmlIgnore]
protected bool ReplyMessageSpecified { get; set; }
private string _forwardMessage;
[XmlElement(ElementName = "forwardMessage", IsNullable = false, Namespace = "")]
[Optional]
[Group(@"ab0042aa512abc10edb3c55e4b416b0b:38498")]
[Length(1)]
[RegularExpression(@"[0-9]|\*|#")]
public string ForwardMessage
{
get => _forwardMessage;
set
{
ForwardMessageSpecified = true;
_forwardMessage = value;
}
}
[XmlIgnore]
protected bool ForwardMessageSpecified { get; set; }
private string _personalizedName;
[XmlElement(ElementName = "personalizedName", IsNullable = false, Namespace = "")]
[Optional]
[Group(@"ab0042aa512abc10edb3c55e4b416b0b:38498")]
[Length(1)]
[RegularExpression(@"[0-9]|\*|#")]
public string PersonalizedName
{
get => _personalizedName;
set
{
PersonalizedNameSpecified = true;
_personalizedName = value;
}
}
[XmlIgnore]
protected bool PersonalizedNameSpecified { get; set; }
private string _passcode;
[XmlElement(ElementName = "passcode", IsNullable = false, Namespace = "")]
[Optional]
[Group(@"ab0042aa512abc10edb3c55e4b416b0b:38498")]
[Length(1)]
[RegularExpression(@"[0-9]|\*|#")]
public string Passcode
{
get => _passcode;
set
{
PasscodeSpecified = true;
_passcode = value;
}
}
[XmlIgnore]
protected bool PasscodeSpecified { get; set; }
private string _returnToPreviousMenu;
[XmlElement(ElementName = "returnToPreviousMenu", IsNullable = false, Namespace = "")]
[Group(@"ab0042aa512abc10edb3c55e4b416b0b:38498")]
[Length(1)]
[RegularExpression(@"[0-9]|\*|#")]
public string ReturnToPreviousMenu
{
get => _returnToPreviousMenu;
set
{
ReturnToPreviousMenuSpecified = true;
_returnToPreviousMenu = value;
}
}
[XmlIgnore]
protected bool ReturnToPreviousMenuSpecified { get; set; }
private string _repeatMenu;
[XmlElement(ElementName = "repeatMenu", IsNullable = false, Namespace = "")]
[Optional]
[Group(@"ab0042aa512abc10edb3c55e4b416b0b:38498")]
[Length(1)]
[RegularExpression(@"[0-9]|\*|#")]
public string RepeatMenu
{
get => _repeatMenu;
set
{
RepeatMenuSpecified = true;
_repeatMenu = value;
}
}
[XmlIgnore]
protected bool RepeatMenuSpecified { get; set; }
}
}
| 28.545833 | 131 | 0.54357 | [
"MIT"
] | Rogn/broadworks-connector-net | BroadworksConnector/Ocip/Models/SystemVoiceMessagingGroupGetVoicePortalMenusResponse20AdditionalMessageOptionsMenuKeys.cs | 6,851 | C# |
using System;
using System.Collections.Generic;
static List<uint> Collatz(uint seed) {
List<uint> _history = new();
_history.Add(seed);
while (seed > 1)
if (seed % 2 == 0)
seed /= 2;
else
{
seed *= 3;
seed++;
}
_history.Add(seed);
return _history;
}
Console.Write("Starting number: ");
if (!uint.TryParse(Console.ReadLine(), out uint Seed)) {
Console.Error.WriteLine("The input entered was invalid.");
Environment.Exit(1);
}
var History = Collatz(Seed);
Console.WriteLine(Seed);
Console.WriteLine("Done!");
Console.WriteLine($"Took {History.Count} passes.");
Console.WriteLine($"History: {string.Join(' ', History)}"); | 22.484848 | 62 | 0.586253 | [
"MIT"
] | Innf107/collatz | C#/GermanBread/Program.cs | 744 | C# |
using Microsoft.EntityFrameworkCore.Migrations;
namespace ABP.TPLMS.Migrations
{
public partial class Upgrade_ABP_380 : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<string>(
name: "UserName",
table: "AbpUsers",
maxLength: 256,
nullable: false,
oldClrType: typeof(string),
oldMaxLength: 32);
migrationBuilder.AlterColumn<string>(
name: "NormalizedUserName",
table: "AbpUsers",
maxLength: 256,
nullable: false,
oldClrType: typeof(string),
oldMaxLength: 32);
migrationBuilder.AlterColumn<string>(
name: "UserName",
table: "AbpUserAccounts",
maxLength: 256,
nullable: true,
oldClrType: typeof(string),
oldMaxLength: 32,
oldNullable: true);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<string>(
name: "UserName",
table: "AbpUsers",
maxLength: 32,
nullable: false,
oldClrType: typeof(string),
oldMaxLength: 256);
migrationBuilder.AlterColumn<string>(
name: "NormalizedUserName",
table: "AbpUsers",
maxLength: 32,
nullable: false,
oldClrType: typeof(string),
oldMaxLength: 256);
migrationBuilder.AlterColumn<string>(
name: "UserName",
table: "AbpUserAccounts",
maxLength: 32,
nullable: true,
oldClrType: typeof(string),
oldMaxLength: 256,
oldNullable: true);
}
}
}
| 31.515625 | 71 | 0.495786 | [
"MIT"
] | ChenQian1984/ABP.TPLMS | aspnet-core/src/ABP.TPLMS.EntityFrameworkCore/Migrations/20180726102703_Upgrade_ABP_3.8.0.cs | 2,019 | C# |
using System;
namespace SampleGithubActionApp
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
| 14.538462 | 46 | 0.544974 | [
"Apache-2.0"
] | Jalalx/SampleGithubActionApp | Program.cs | 191 | C# |
using Client.Core.UI.HitMenu;
using Newtonsoft.Json;
using System;
using static Client.Core.Internal.CAPI;
namespace Client.Core.UI
{
public class HitMenuItem
{
public string Id { get; private set; } = RandomString();
public string Text { get; set; }
public string Emoji { get; set; }
public bool CloseMenuOnAction { get; set; }
public HitMenuContainer Parent { get; set; }
[JsonIgnore]
public Action<RaycastHit> Action { get; private set; }
public HitMenuItem() { }
public HitMenuItem(string text, string emoji, bool closeMenuOnAction, Action<RaycastHit> action)
{
Text = text;
Emoji = emoji;
CloseMenuOnAction = closeMenuOnAction;
Action = action;
}
}
}
| 26.966667 | 104 | 0.61063 | [
"CC0-1.0"
] | average-framework/average-framework | Average.Client/Core/UI/HitMenu/HitMenuItem.cs | 811 | C# |
using UnityEngine;
using System.Collections;
public class Rotator : MonoBehaviour {
public Vector3 delta;
public Space relativeTo;
void Update () {
if (relativeTo == Space.Self)
transform.localEulerAngles += delta * Time.deltaTime;
else
transform.eulerAngles += delta * Time.deltaTime;
}
}
| 19.3125 | 56 | 0.724919 | [
"Apache-2.0"
] | Slamakans/Game-Bois | Assets/Scripts/Utility/Rotator.cs | 311 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Media Player Aplication")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Media Player Aplication")]
[assembly: AssemblyCopyright("Copyright © 2021")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("a16876a8-70e4-48cf-b4fc-eb6e76aa5e91")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.351351 | 84 | 0.7463 | [
"MIT"
] | mariovarela99/C-Projects | Projects/Media Player Aplication/Media Player Aplication/Properties/AssemblyInfo.cs | 1,422 | C# |
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations;
using Newtonsoft.Json;
namespace BizzebeeSharp.Entities
{
public class ProductCategoryModelUpdatable
{
/// <summary>The product category Id</summary>
[JsonProperty("categoryId")]
public int? CategoryId { get; set; }
/// <summary>The category`s parent`s Id</summary>
[JsonProperty("parentId")]
public int? ParentId { get; set; }
/// <summary>
/// The category`s visibility settings. Possible values are: visible, hidden and pricelists. Pricelists means that
/// the category is only visible for customers with access to specific pricelists
/// </summary>
[JsonProperty("visibility")]
public string Visibility { get; set; }
/// <summary>Sort index. A category with a lower value is displayed higher up in lists</summary>
[JsonProperty("sortIndex")]
public int? SortIndex { get; set; }
/// <summary>
/// Whether or not links to the category should open a category page listing its products and sub categories on
/// click.
/// </summary>
[JsonProperty("openPage")]
public bool OpenPage { get; set; }
/// <summary>The Id to the category`s image file. Has to be an existing mediaFile</summary>
[JsonProperty("imageFileId")]
public int? ImageFileId { get; set; }
/// <summary>The system name the externalId belongs to.</summary>
[JsonProperty("externalType")]
[StringLength(20)]
public string ExternalType { get; set; }
/// <summary>The external Id for this category for the system named in externalType</summary>
[JsonProperty("externalId")]
[StringLength(40)]
public string ExternalId { get; set; }
/// <summary>Whether or not the category has any children categories</summary>
[JsonProperty("hasChildren")]
public bool HasChildren { get; set; }
[JsonProperty("languages")]
public ICollection<ProductCategoryLanguagesModel> Languages { get; set; } =
new Collection<ProductCategoryLanguagesModel>();
}
} | 38.982759 | 126 | 0.640425 | [
"MIT"
] | PrimePenguin/BizzebeeSharp | BizzebeeSharp/Entities/ProductCategoryModelUpdatable.cs | 2,261 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Connections;
using Microsoft.Extensions.Options;
namespace Microsoft.Azure.SignalR.Management
{
internal class ManagementConnectionFactory : IConnectionFactory
{
private readonly string _productInfo;
private readonly ConnectionFactory _connectionFactory;
public ManagementConnectionFactory(IOptions<ServiceManagerOptions> context, ConnectionFactory connectionFactory)
{
_productInfo = context.Value.ProductInfo;
_connectionFactory = connectionFactory;
}
public Task<ConnectionContext> ConnectAsync(HubServiceEndpoint endpoint, TransferFormat transferFormat, string connectionId, string target, CancellationToken cancellationToken = default, IDictionary<string, string> headers = null)
{
if (headers == null)
{
headers = new Dictionary<string, string> { { Constants.AsrsUserAgent, _productInfo } };
}
else
{
headers[Constants.AsrsUserAgent] = _productInfo;
}
return _connectionFactory.ConnectAsync(endpoint, transferFormat, connectionId, target, cancellationToken, headers);
}
public Task DisposeAsync(ConnectionContext connection)
{
return _connectionFactory.DisposeAsync(connection);
}
}
}
| 37.581395 | 238 | 0.69802 | [
"MIT"
] | Andy9FromSpace/azure-signalr | src/Microsoft.Azure.SignalR.Management/ManagementConnectionFactory.cs | 1,618 | C# |
using MelonManager.Utils;
using System;
using System.IO;
using System.Linq;
namespace MelonManager.Managers
{
public static class Logger
{
private const int MaxLogFiles = 10;
public static string logsDir = Path.Combine(Program.localFilesPath, "Logs");
public static string currentLogPath;
public static string latestLogPath;
public static StreamWriter latestLog;
public static StreamWriter currentLog;
private static object logLock = new object();
private static bool initialized;
public static void Initialize()
{
if (initialized)
return;
latestLogPath = Path.Combine(Program.localFilesPath, "MelonManager_Latest.log");
currentLogPath = Path.Combine(logsDir, "MelonManager_" + DateTime.Now.ToString("yy-MM-dd_HH-mm-ss.fff") + ".log");
Directory.CreateDirectory(logsDir);
var dir = new DirectoryInfo(logsDir);
var files = dir.GetFileSystemInfos();
if (files.Length >= MaxLogFiles)
{
var oldLog = files.OrderBy(x => x.CreationTime).First();
oldLog.Delete();
}
latestLog = new StreamWriter(File.Open(latestLogPath, FileMode.Create, FileAccess.Write, FileShare.Read));
currentLog = new StreamWriter(File.Open(currentLogPath, FileMode.Create, FileAccess.Write, FileShare.Read));
latestLog.AutoFlush = true;
currentLog.AutoFlush = true;
initialized = true;
Log("============================================");
Log("OS: " + Environment.OSVersion.ToString());
Log("App version: v" + BuildInfo.Version);
Log("Timezone: " + TimeZone.CurrentTimeZone.StandardName);
Log("Current date: " + DateTime.Now.ToString("yy-MM-dd"));
Log("============================================");
}
public static void Deinitialize()
{
if (!initialized)
return;
initialized = false;
if (latestLog != null)
latestLog.Dispose();
if (currentLog != null)
currentLog.Dispose();
}
public static string GetWholeLog()
{
if (!initialized)
return string.Empty;
lock (logLock)
{
latestLog.Dispose();
string str = File.ReadAllText(latestLogPath);
latestLog = new StreamWriter(File.Open(latestLogPath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read));
latestLog.AutoFlush = true;
return str;
}
}
public static void Log(string message, Level level = Level.Message)
{
if (!initialized)
return;
try
{
lock (logLock)
{
var log = $"[{DateTime.Now.ToString("HH:mm:ss.fff")}] [{level}] " + message;
latestLog.WriteLine(log);
currentLog.WriteLine(log);
}
}
catch { }
}
public enum Level
{
Message,
Warning,
Error
}
}
}
| 32.378641 | 128 | 0.51994 | [
"MIT"
] | RinLovesYou/MelonManager | MelonManager/Managers/Logger.cs | 3,337 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Text;
using Silk.NET.Core;
using Silk.NET.Core.Native;
using Silk.NET.Core.Attributes;
using Silk.NET.Core.Contexts;
using Silk.NET.Core.Loader;
using Silk.NET.OpenGL.Legacy;
using Extension = Silk.NET.Core.Attributes.ExtensionAttribute;
#pragma warning disable 1591
namespace Silk.NET.OpenGL.Legacy.Extensions.SGIS
{
[Extension("SGIS_texture_filter4")]
public unsafe partial class SgisTextureFilter4 : NativeExtension<GL>
{
public const string ExtensionName = "SGIS_texture_filter4";
[NativeApi(EntryPoint = "glGetTexFilterFuncSGIS", Convention = CallingConvention.Winapi)]
public unsafe partial void GetTexFilterFunc([Flow(FlowDirection.In)] SGIS target, [Flow(FlowDirection.In)] SGIS filter, [Count(Computed = "target, filter"), Flow(FlowDirection.Out)] float* weights);
[NativeApi(EntryPoint = "glGetTexFilterFuncSGIS", Convention = CallingConvention.Winapi)]
public partial void GetTexFilterFunc([Flow(FlowDirection.In)] SGIS target, [Flow(FlowDirection.In)] SGIS filter, [Count(Computed = "target, filter"), Flow(FlowDirection.Out)] out float weights);
[NativeApi(EntryPoint = "glGetTexFilterFuncSGIS", Convention = CallingConvention.Winapi)]
public unsafe partial void GetTexFilterFunc([Flow(FlowDirection.In)] SGIS target, [Flow(FlowDirection.In)] TextureFilterSGIS filter, [Count(Computed = "target, filter"), Flow(FlowDirection.Out)] float* weights);
[NativeApi(EntryPoint = "glGetTexFilterFuncSGIS", Convention = CallingConvention.Winapi)]
public partial void GetTexFilterFunc([Flow(FlowDirection.In)] SGIS target, [Flow(FlowDirection.In)] TextureFilterSGIS filter, [Count(Computed = "target, filter"), Flow(FlowDirection.Out)] out float weights);
[NativeApi(EntryPoint = "glGetTexFilterFuncSGIS", Convention = CallingConvention.Winapi)]
public unsafe partial void GetTexFilterFunc([Flow(FlowDirection.In)] TextureTarget target, [Flow(FlowDirection.In)] SGIS filter, [Count(Computed = "target, filter"), Flow(FlowDirection.Out)] float* weights);
[NativeApi(EntryPoint = "glGetTexFilterFuncSGIS", Convention = CallingConvention.Winapi)]
public partial void GetTexFilterFunc([Flow(FlowDirection.In)] TextureTarget target, [Flow(FlowDirection.In)] SGIS filter, [Count(Computed = "target, filter"), Flow(FlowDirection.Out)] out float weights);
[NativeApi(EntryPoint = "glGetTexFilterFuncSGIS", Convention = CallingConvention.Winapi)]
public unsafe partial void GetTexFilterFunc([Flow(FlowDirection.In)] TextureTarget target, [Flow(FlowDirection.In)] TextureFilterSGIS filter, [Count(Computed = "target, filter"), Flow(FlowDirection.Out)] float* weights);
[NativeApi(EntryPoint = "glGetTexFilterFuncSGIS", Convention = CallingConvention.Winapi)]
public partial void GetTexFilterFunc([Flow(FlowDirection.In)] TextureTarget target, [Flow(FlowDirection.In)] TextureFilterSGIS filter, [Count(Computed = "target, filter"), Flow(FlowDirection.Out)] out float weights);
[NativeApi(EntryPoint = "glTexFilterFuncSGIS", Convention = CallingConvention.Winapi)]
public unsafe partial void TexFilterFunc([Flow(FlowDirection.In)] SGIS target, [Flow(FlowDirection.In)] SGIS filter, [Flow(FlowDirection.In)] uint n, [Count(Parameter = "n"), Flow(FlowDirection.In)] float* weights);
[NativeApi(EntryPoint = "glTexFilterFuncSGIS", Convention = CallingConvention.Winapi)]
public partial void TexFilterFunc([Flow(FlowDirection.In)] SGIS target, [Flow(FlowDirection.In)] SGIS filter, [Flow(FlowDirection.In)] uint n, [Count(Parameter = "n"), Flow(FlowDirection.In)] in float weights);
[NativeApi(EntryPoint = "glTexFilterFuncSGIS", Convention = CallingConvention.Winapi)]
public unsafe partial void TexFilterFunc([Flow(FlowDirection.In)] SGIS target, [Flow(FlowDirection.In)] TextureFilterSGIS filter, [Flow(FlowDirection.In)] uint n, [Count(Parameter = "n"), Flow(FlowDirection.In)] float* weights);
[NativeApi(EntryPoint = "glTexFilterFuncSGIS", Convention = CallingConvention.Winapi)]
public partial void TexFilterFunc([Flow(FlowDirection.In)] SGIS target, [Flow(FlowDirection.In)] TextureFilterSGIS filter, [Flow(FlowDirection.In)] uint n, [Count(Parameter = "n"), Flow(FlowDirection.In)] in float weights);
[NativeApi(EntryPoint = "glTexFilterFuncSGIS", Convention = CallingConvention.Winapi)]
public unsafe partial void TexFilterFunc([Flow(FlowDirection.In)] TextureTarget target, [Flow(FlowDirection.In)] SGIS filter, [Flow(FlowDirection.In)] uint n, [Count(Parameter = "n"), Flow(FlowDirection.In)] float* weights);
[NativeApi(EntryPoint = "glTexFilterFuncSGIS", Convention = CallingConvention.Winapi)]
public partial void TexFilterFunc([Flow(FlowDirection.In)] TextureTarget target, [Flow(FlowDirection.In)] SGIS filter, [Flow(FlowDirection.In)] uint n, [Count(Parameter = "n"), Flow(FlowDirection.In)] in float weights);
[NativeApi(EntryPoint = "glTexFilterFuncSGIS", Convention = CallingConvention.Winapi)]
public unsafe partial void TexFilterFunc([Flow(FlowDirection.In)] TextureTarget target, [Flow(FlowDirection.In)] TextureFilterSGIS filter, [Flow(FlowDirection.In)] uint n, [Count(Parameter = "n"), Flow(FlowDirection.In)] float* weights);
[NativeApi(EntryPoint = "glTexFilterFuncSGIS", Convention = CallingConvention.Winapi)]
public partial void TexFilterFunc([Flow(FlowDirection.In)] TextureTarget target, [Flow(FlowDirection.In)] TextureFilterSGIS filter, [Flow(FlowDirection.In)] uint n, [Count(Parameter = "n"), Flow(FlowDirection.In)] in float weights);
public unsafe void TexFilterFunc([Flow(FlowDirection.In)] SGIS target, [Flow(FlowDirection.In)] SGIS filter, [Count(Parameter = "n"), Flow(FlowDirection.In)] ReadOnlySpan<float> weights)
{
// ImplicitCountSpanOverloader
TexFilterFunc(target, filter, (uint) weights.Length, in weights.GetPinnableReference());
}
public unsafe void TexFilterFunc([Flow(FlowDirection.In)] SGIS target, [Flow(FlowDirection.In)] TextureFilterSGIS filter, [Count(Parameter = "n"), Flow(FlowDirection.In)] ReadOnlySpan<float> weights)
{
// ImplicitCountSpanOverloader
TexFilterFunc(target, filter, (uint) weights.Length, in weights.GetPinnableReference());
}
public unsafe void TexFilterFunc([Flow(FlowDirection.In)] TextureTarget target, [Flow(FlowDirection.In)] SGIS filter, [Count(Parameter = "n"), Flow(FlowDirection.In)] ReadOnlySpan<float> weights)
{
// ImplicitCountSpanOverloader
TexFilterFunc(target, filter, (uint) weights.Length, in weights.GetPinnableReference());
}
public unsafe void TexFilterFunc([Flow(FlowDirection.In)] TextureTarget target, [Flow(FlowDirection.In)] TextureFilterSGIS filter, [Count(Parameter = "n"), Flow(FlowDirection.In)] ReadOnlySpan<float> weights)
{
// ImplicitCountSpanOverloader
TexFilterFunc(target, filter, (uint) weights.Length, in weights.GetPinnableReference());
}
public SgisTextureFilter4(INativeContext ctx)
: base(ctx)
{
}
}
}
| 73.401961 | 245 | 0.735274 | [
"MIT"
] | Ar37-rs/Silk.NET | src/OpenGL/Extensions/Silk.NET.OpenGL.Legacy.Extensions.SGIS/SgisTextureFilter4.gen.cs | 7,487 | C# |
using System;
using System.Threading;
namespace MultiThreading.Threads
{
public class SharedResource
{
private static bool isCompleted;
static readonly object lockCompleted = new object();
public static void Run()
{
//Worked Thread
Thread thread = new Thread(HelloWorld);
thread.Name = "bv Worker";
thread.Start();
//Main Thread
Thread.CurrentThread.Name = "bv main";
HelloWorld();
}
private static void HelloWorld()
{
lock (lockCompleted)
{
if (!isCompleted)
{
isCompleted = true;
Console.WriteLine("Hello World should print only once");
}
}
}
}
}
| 21.564103 | 76 | 0.491082 | [
"MIT"
] | SaeidSabzalizadeh/CSharp-Practices | Source/CSharpPractices/MultiThreading/Threads/SharedResource.cs | 843 | C# |
using CCXT.NET.Shared.Configuration;
using CCXT.NET.Shared.Serialize;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RestSharp;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Numerics;
using System.Text;
using System.Threading.Tasks;
using System.Web;
namespace CCXT.NET.Shared.Coin
{
/// <summary>
///
/// </summary>
public interface IXApiClient
{
/// <summary>
///
/// </summary>
string DealerName
{
get;
set;
}
/// <summary>
///
/// </summary>
ExchangeInfo ExchangeInfo
{
get;
}
/// <summary>
///
/// </summary>
bool IsAuthentication
{
get; set;
}
/// <summary>
///
/// </summary>
string ApiUrl
{
get; set;
}
/// <summary>
///
/// </summary>
string ConnectKey
{
get; set;
}
/// <summary>
///
/// </summary>
string SecretKey
{
get; set;
}
/// <summary>
///
/// </summary>
string UserName
{
get; set;
}
/// <summary>
///
/// </summary>
string UserPassword
{
get; set;
}
/// <summary>
///
/// </summary>
Dictionary<object, object> ErrorMessages
{
get;
set;
}
#region method common lib
/// <summary>
///
/// </summary>
/// <param name="error_code"></param>
/// <returns></returns>
string GetErrorMessage(int error_code);
/// <summary>
///
/// </summary>
/// <param name="response">response value arrive from exchange's server</param>
/// <returns></returns>
BoolResult GetResponseMessage(RestResponse response = null);
/// <summary>
///
/// </summary>
/// <param name="request"></param>
/// <param name="max_retry"></param>
/// <param name="delay_milliseconds"></param>
/// <returns></returns>
ValueTask<RestResponse> RestExecuteAsync(RestRequest request, int max_retry, int delay_milliseconds);
#endregion method common lib
#region method post
/// <summary>
///
/// </summary>
/// <param name="endpoint">api link address of a function</param>
/// <param name="args">Add additional attributes for each exchange</param>
/// <returns></returns>
ValueTask<RestRequest> CreatePostRequestAsync(string endpoint, Dictionary<string, object> args = null);
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="endpoint">api link address of a function</param>
/// <param name="args">Add additional attributes for each exchange</param>
/// <returns></returns>
ValueTask<T> CallApiPostAsync<T>(string endpoint, Dictionary<string, object> args = null) where T : new();
/// <summary>
///
/// </summary>
/// <param name="endpoint">api link address of a function</param>
/// <param name="args">Add additional attributes for each exchange</param>
/// <returns></returns>
ValueTask<string> CallApiPostAsync(string endpoint, Dictionary<string, object> args = null);
/// <summary>
///
/// </summary>
/// <param name="endpoint">api link address of a function</param>
/// <param name="args">Add additional attributes for each exchange</param>
/// <returns></returns>
ValueTask<(string Content, RestResponse Response)> CallApiPost1Async(string endpoint, Dictionary<string, object> args = null);
/// <summary>
///
/// </summary>
/// <param name="endpoint">api link address of a function</param>
/// <param name="args">Add additional attributes for each exchange</param>
/// <returns></returns>
ValueTask<RestResponse> CallApiPost2Async(string endpoint, Dictionary<string, object> args = null);
#endregion method post
#region method get
/// <summary>
///
/// </summary>
/// <param name="endpoint">api link address of a function</param>
/// <param name="args">Add additional attributes for each exchange</param>
/// <returns></returns>
ValueTask<RestRequest> CreateGetRequestAsync(string endpoint, Dictionary<string, object> args = null);
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="endpoint">api link address of a function</param>
/// <param name="args">Add additional attributes for each exchange</param>
/// <returns></returns>
ValueTask<T> CallApiGetAsync<T>(string endpoint, Dictionary<string, object> args = null) where T : new();
/// <summary>
///
/// </summary>
/// <param name="endpoint">api link address of a function</param>
/// <param name="args">Add additional attributes for each exchange</param>
/// <returns></returns>
ValueTask<string> CallApiGetAsync(string endpoint, Dictionary<string, object> args = null);
/// <summary>
///
/// </summary>
/// <param name="endpoint">api link address of a function</param>
/// <param name="args">Add additional attributes for each exchange</param>
/// <returns></returns>
ValueTask<(string Content, RestResponse Response)> CallApiGet1Async(string endpoint, Dictionary<string, object> args = null);
/// <summary>
///
/// </summary>
/// <param name="endpoint">api link address of a function</param>
/// <param name="args">Add additional attributes for each exchange</param>
/// <returns></returns>
ValueTask<RestResponse> CallApiGet2Async(string endpoint, Dictionary<string, object> args = null);
#endregion method get
#region method delete
/// <summary>
///
/// </summary>
/// <param name="endpoint">api link address of a function</param>
/// <param name="args">Add additional attributes for each exchange</param>
/// <returns></returns>
ValueTask<RestRequest> CreateDeleteRequestAsync(string endpoint, Dictionary<string, object> args = null);
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="endpoint">api link address of a function</param>
/// <param name="args">Add additional attributes for each exchange</param>
/// <returns></returns>
ValueTask<T> CallApiDeleteAsync<T>(string endpoint, Dictionary<string, object> args = null) where T : new();
/// <summary>
///
/// </summary>
/// <param name="endpoint">api link address of a function</param>
/// <param name="args">Add additional attributes for each exchange</param>
/// <returns></returns>
ValueTask<string> CallApiDeleteAsync(string endpoint, Dictionary<string, object> args = null);
/// <summary>
///
/// </summary>
/// <param name="endpoint">api link address of a function</param>
/// <param name="args">Add additional attributes for each exchange</param>
/// <returns></returns>
ValueTask<(string Content, RestResponse Response)> CallApiDelete1Async(string endpoint, Dictionary<string, object> args = null);
/// <summary>
///
/// </summary>
/// <param name="endpoint">api link address of a function</param>
/// <param name="args">Add additional attributes for each exchange</param>
/// <returns></returns>
ValueTask<RestResponse> CallApiDelete2Async(string endpoint, Dictionary<string, object> args = null);
#endregion method delete
}
/// <summary>
///
/// </summary>
public class XApiClient : IXApiClient, IDisposable
{
/// <summary>
///
/// </summary>
public static XUnitMode TestXUnitMode = XUnitMode.UseExchangeServer;
/// <summary>
///
/// </summary>
public static ConcurrentDictionary<string, long> marketLastNonce = new ConcurrentDictionary<string, long>();
/// <summary>
///
/// </summary>
public const string ContentType = "application/json";
/// <summary>
///
/// </summary>
public const string UserAgent = "odinsoft-ccxt/1.0.2019.10";
/// <summary>
///
/// </summary>
public virtual string DealerName
{
get;
set;
}
/// <summary>
/// information of exchange for trading
/// </summary>
public virtual ExchangeInfo ExchangeInfo
{
get;
set;
}
/// <summary>
///
/// </summary>
public bool IsAuthentication { get; set; } = false;
/// <summary>
///
/// </summary>
public string ApiUrl { get; set; } = "";
/// <summary>
///
/// </summary>
public string ConnectKey { get; set; } = "";
/// <summary>
///
/// </summary>
public string SecretKey { get; set; } = "";
/// <summary>
///
/// </summary>
public string UserName { get; set; } = "";
/// <summary>
///
/// </summary>
public string UserPassword { get; set; } = "";
/// <summary>
///
/// </summary>
/// <param name="division">exchange's api url for communication</param>
/// <param name="connect_key">exchange's api key for connect</param>
/// <param name="secret_key">exchange's secret key for signature</param>
/// <param name="user_name">exchange's id or uuid for login</param>
/// <param name="user_password">exchange's password for login</param>
/// <param name="authentication"></param>
public XApiClient(string division, string connect_key = "", string secret_key = "", string user_name = "", string user_password = "", bool authentication = false)
{
if (this.ExchangeInfo != null)
ApiUrl = this.ExchangeInfo.GetApiUrl(division ?? "");
ConnectKey = connect_key ?? "";
SecretKey = secret_key ?? "";
UserName = user_name ?? "";
UserPassword = user_password ?? "";
IsAuthentication = authentication;
}
#region method common
/// <summary>
///
/// </summary>
/// <param name="digit_count"></param>
/// <returns></returns>
public BigInteger GenerateNonceValue(int digit_count)
{
var _milli_seconds = CUnixTime.UtcNow.Subtract(CUnixTime.UnixEpoch).TotalMilliseconds;
var _nonce = new BigInteger(Math.Round(_milli_seconds * 10000.0, MidpointRounding.AwayFromZero));
{
var _nonce_size = _nonce.ToString().Length;
digit_count = digit_count <= 0 ? 16 : digit_count;
if (_nonce_size > digit_count)
_nonce = BigInteger.Divide(_nonce, BigInteger.Pow(10, _nonce_size - digit_count));
else if (_nonce_size < digit_count)
_nonce = _nonce * BigInteger.Pow(10, digit_count - _nonce_size);
}
return _nonce;
}
/// <summary>
///
/// </summary>
/// <param name="digit_count"></param>
/// <param name="right_length"></param>
/// <returns></returns>
public string GenerateNonceString(int digit_count, int right_length = 0)
{
var _nonce_string = GenerateNonceValue(digit_count).ToString(CultureInfo.InvariantCulture);
var _start_index = right_length > 0 ? _nonce_string.Length - right_length : 0;
return _nonce_string.Substring(_start_index);
}
/// <summary>
///
/// </summary>
/// <param name="digit_count"></param>
/// <returns></returns>
public long GenerateOnlyNonce(int digit_count)
{
var _nonce = (long)GenerateNonceValue(digit_count);
if (marketLastNonce.ContainsKey(this.DealerName))
{
var _last_nonce = marketLastNonce[this.DealerName];
#if DEBUG
if (_last_nonce.ToString().Length != _nonce.ToString().Length)
throw new Exception("nonce length mismatch error");
#endif
if (_last_nonce >= _nonce)
_nonce = _last_nonce++;
}
marketLastNonce[this.DealerName] = _nonce;
return _nonce;
}
/// <summary>
///
/// </summary>
/// <param name="args">Add additional attributes for each exchange</param>
/// <param name="json"></param>
/// <returns></returns>
public string ToQueryString(Dictionary<string, object> args, bool json = false)
{
var _result = "";
if (args != null)
{
if (json)
{
var _params = new List<string>();
foreach (var _entry in args)
_params.Add(String.Format("'{0}':'{1}'", _entry.Key, _entry.Value));
_result = "{" + String.Join(",", _params) + "}";
}
else
{
_result = String.Join("&", args.Select(a => $"{a.Key}={HttpUtility.UrlEncode((a.Value ?? "").ToString())}"));
}
}
return _result;
}
/// <summary>
///
/// </summary>
/// <param name="args">Add additional attributes for each exchange</param>
/// <returns></returns>
public string ToQueryString2(Dictionary<string, object> args)
{
return String.Join("&", args.Select(a => $"{a.Key}={Uri.EscapeDataString((a.Value ?? "").ToString())}"));
}
/// <summary>
///
/// </summary>
/// <param name="buffer"></param>
/// <returns></returns>
public string ConvertHexString(byte[] buffer)
{
return BitConverter.ToString(buffer).Replace("-", "");
}
/// <summary>
///
/// </summary>
/// <param name="args">Add additional attributes for each exchange</param>
/// <returns></returns>
public Dictionary<string, object> MergeParamsAndArgs(Dictionary<string, object> args)
{
return MergeParamsAndArgs(new Dictionary<string, object>(), args);
}
/// <summary>
///
/// </summary>
/// <param name="params"></param>
/// <param name="args">Add additional attributes for each exchange</param>
/// <returns></returns>
public Dictionary<string, object> MergeParamsAndArgs(Dictionary<string, object> @params, Dictionary<string, object> args)
{
if (args != null)
{
foreach (var _arg in args)
{
if (@params.ContainsKey(_arg.Key))
@params.Remove(_arg.Key);
@params.Add(_arg.Key, _arg.Value);
}
}
return @params;
}
/// <summary>
///
/// </summary>
/// <param name="baseurl"></param>
/// <returns></returns>
public virtual RestClient CreateJsonClient(string baseurl)
{
return new RestClient(new RestClientOptions
{
BaseUrl = new Uri(baseurl),
Timeout = 5 * 1000,
UserAgent = UserAgent,
Encoding = Encoding.GetEncoding(65001)
});
}
/// <summary>
///
/// </summary>
/// <param name="resource"></param>
/// <param name="args">Add additional attributes for each exchange</param>
/// <param name="method"></param>
/// <returns></returns>
public RestRequest CreateJsonRequest(string resource, Dictionary<string, object> args = null, Method method = Method.Get)
{
var _request = new RestRequest(resource, method)
{
RequestFormat = DataFormat.Json
};
if (args != null)
{
foreach (var _arg in args)
{
#if DEBUG
if (TestXUnitMode == XUnitMode.UseExchangeServer && _arg.Key == "jsonContent")
continue;
#endif
if (_arg.Value.GetType() == typeof(CArgument))
{
var _margs = _arg.Value as CArgument;
if (_margs != null)
{
if (_margs.isArray)
{
foreach (var _marg in (_margs.value as Array) ?? new Array[0])
_request.AddParameter(_arg.Key, _marg, ParameterType.GetOrPost);
}
else if (_margs.isJson)
{
_request.AddParameter(_arg.Key, JsonConvert.SerializeObject(_margs.value));
}
else
{
_request.AddParameter(_arg.Key, _margs.value, ParameterType.GetOrPost);
}
}
}
else
{
_request.AddParameter(_arg.Key, _arg.Value, ParameterType.GetOrPost);
}
}
}
return _request;
}
/// <summary>
///
/// </summary>
public virtual Dictionary<object, object> ErrorMessages
{
get;
set;
}
/// <summary>
///
/// </summary>
/// <param name="error_code"></param>
/// <returns></returns>
public virtual string GetErrorMessage(int error_code)
{
return ErrorMessages.ContainsKey(error_code)
? ErrorMessages[error_code].ToString()
: "failure";
}
/// <summary>
///
/// </summary>
/// <param name="response">response value arrive from exchange's server</param>
/// <returns></returns>
public virtual BoolResult GetResponseMessage(RestResponse response = null)
{
var _result = new BoolResult();
if (response != null)
{
if (response.IsSuccessful)
{
var _json_result = this.DeserializeObject<JToken>(response.Content);
if (_json_result.SelectToken("message") != null)
{
_result.SetFailure(
_json_result["message"]?.Value<string>(),
ErrorCode.ExchangeError
);
}
}
if (_result.success && response.IsSuccessful == false)
{
_result.SetFailure(
response.ErrorMessage ?? response.StatusDescription,
ErrorCode.ResponseRestError,
(int)response.StatusCode,
false
);
}
}
return _result;
}
/// <summary>
///
/// </summary>
/// <param name="request"></param>
/// <param name="max_retry"></param>
/// <param name="delay_milliseconds"></param>
/// <returns></returns>
public virtual async ValueTask<RestResponse> RestExecuteAsync(RestRequest request, int max_retry = 3, int delay_milliseconds = 1000)
{
var _result = (RestResponse)null;
var _client = CreateJsonClient(ApiUrl);
for (var _retry_count = 0; _retry_count < max_retry; _retry_count++)
{
var _tcs = new TaskCompletionSource<RestResponse>();
{
//var _handle = _client.ExecuteAsync(request, response =>
//{
// _tcs.SetResult(response);
//});
//_result = await _tcs.Task;
_result = await _client.ExecuteAsync(request);
}
if (_result.ResponseStatus != ResponseStatus.TimedOut && _result.StatusCode != HttpStatusCode.RequestTimeout)
break;
#if DEBUG
Debug.WriteLine($"request timeout: {_retry_count}/{max_retry}, {request.Resource}");
#endif
await Task.Delay(delay_milliseconds);
}
return _result;
}
#endregion method common
#region method post
private static RestSerializerSettings __rest_settings = null;
private RestSerializerSettings RestSerializerSettings
{
get
{
if (__rest_settings == null)
__rest_settings = new RestSerializerSettings("");
return __rest_settings;
}
}
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="json_string"></param>
/// <returns></returns>
public T DeserializeObject<T>(string json_string) //where T : new()
{
return JsonConvert.DeserializeObject<T>(json_string, this.RestSerializerSettings);
}
/// <summary>
///
/// </summary>
/// <param name="json_object"></param>
/// <param name="formatting"></param>
/// <returns></returns>
public string SerializeObject(object json_object, Formatting formatting = Formatting.Indented)
{
return JsonConvert.SerializeObject(json_object, formatting, this.RestSerializerSettings);
}
/// <summary>
///
/// </summary>
/// <param name="endpoint">api link address of a function</param>
/// <param name="args">Add additional attributes for each exchange</param>
/// <returns></returns>
public virtual async ValueTask<RestRequest> CreatePostRequestAsync(string endpoint, Dictionary<string, object> args = null)
{
var _request = CreateJsonRequest(endpoint, args, Method.Post);
return await Task.FromResult(_request);
}
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="endpoint">api link address of a function</param>
/// <param name="args">Add additional attributes for each exchange</param>
/// <returns></returns>
public virtual async ValueTask<T> CallApiPostAsync<T>(string endpoint, Dictionary<string, object> args = null) where T : new()
{
var _response = await CallApiPostAsync(endpoint, args);
return this.DeserializeObject<T>(_response);
}
/// <summary>
///
/// </summary>
/// <param name="endpoint">api link address of a function</param>
/// <param name="args">Add additional attributes for each exchange</param>
/// <returns></returns>
public virtual async ValueTask<string> CallApiPostAsync(string endpoint, Dictionary<string, object> args = null)
{
var _response = await CallApiPost2Async(endpoint, args);
return _response != null ? _response.Content : "";
}
/// <summary>
///
/// </summary>
/// <param name="endpoint">api link address of a function</param>
/// <param name="args">Add additional attributes for each exchange</param>
/// <returns></returns>
public virtual async ValueTask<(string Content, RestResponse Response)> CallApiPost1Async(string endpoint, Dictionary<string, object> args = null)
{
var _response = await CallApiPost2Async(endpoint, args);
return (_response.Content, _response);
}
/// <summary>
///
/// </summary>
/// <param name="endpoint">api link address of a function</param>
/// <param name="args">Add additional attributes for each exchange</param>
/// <returns></returns>
public virtual async ValueTask<RestResponse> CallApiPost2Async(string endpoint, Dictionary<string, object> args = null)
{
var _request = await CreatePostRequestAsync(endpoint, args);
#if DEBUG
if (TestXUnitMode == XUnitMode.ModeUnknown)
throw new Exception("POST: xUnitMode is unknown error when debug mode");
if (TestXUnitMode != XUnitMode.UseExchangeServer)
{
var _content = "";
if (args != null)
_content = args.ContainsKey("jsonContent") ? args["jsonContent"].ToString() : "";
var _result = new RestResponse
{
Request = _request,
Content = _content,
ResponseStatus = ResponseStatus.Completed,
StatusCode = HttpStatusCode.OK
};
return await Task.FromResult(_result);
}
#endif
return await RestExecuteAsync(_request);
}
#endregion method post
#region method get
/// <summary>
///
/// </summary>
/// <param name="endpoint">api link address of a function</param>
/// <param name="args">Add additional attributes for each exchange</param>
/// <returns></returns>
public virtual async ValueTask<RestRequest> CreateGetRequestAsync(string endpoint, Dictionary<string, object> args = null)
{
var _request = CreateJsonRequest(endpoint, args, Method.Get);
return await Task.FromResult(_request);
}
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="endpoint">api link address of a function</param>
/// <param name="args">Add additional attributes for each exchange</param>
/// <returns></returns>
public virtual async ValueTask<T> CallApiGetAsync<T>(string endpoint, Dictionary<string, object> args = null) where T : new()
{
var _response = await CallApiGet2Async(endpoint, args);
return _response != null
? this.DeserializeObject<T>(_response.Content)
: new T();
}
/// <summary>
///
/// </summary>
/// <param name="endpoint">api link address of a function</param>
/// <param name="args">Add additional attributes for each exchange</param>
/// <returns></returns>
public virtual async ValueTask<string> CallApiGetAsync(string endpoint, Dictionary<string, object> args = null)
{
var _response = await CallApiGet2Async(endpoint, args);
return _response != null ? _response.Content : "";
}
/// <summary>
///
/// </summary>
/// <param name="endpoint">api link address of a function</param>
/// <param name="args">Add additional attributes for each exchange</param>
/// <returns></returns>
public virtual async ValueTask<(string Content, RestResponse Response)> CallApiGet1Async(string endpoint, Dictionary<string, object> args = null)
{
var _response = await CallApiGet2Async(endpoint, args);
return (_response.Content, _response);
}
/// <summary>
///
/// </summary>
/// <param name="endpoint">api link address of a function</param>
/// <param name="args">Add additional attributes for each exchange</param>
/// <returns></returns>
public virtual async ValueTask<RestResponse> CallApiGet2Async(string endpoint, Dictionary<string, object> args = null)
{
var _request = await CreateGetRequestAsync(endpoint, args);
#if DEBUG
if (TestXUnitMode == XUnitMode.ModeUnknown)
throw new Exception("GET: xUnitMode is unknown error when debug mode");
if (TestXUnitMode != XUnitMode.UseExchangeServer)
{
var _result = new RestResponse
{
Request = _request,
Content = args != null ? (args.ContainsKey("jsonContent") ? args["jsonContent"].ToString() : "") : "",
ResponseStatus = ResponseStatus.Completed,
StatusCode = HttpStatusCode.OK
};
return await Task.FromResult(_result);
}
#endif
return await RestExecuteAsync(_request);
}
#endregion method get
#region method delete
/// <summary>
///
/// </summary>
/// <param name="endpoint">api link address of a function</param>
/// <param name="args">Add additional attributes for each exchange</param>
/// <returns></returns>
public virtual async ValueTask<RestRequest> CreateDeleteRequestAsync(string endpoint, Dictionary<string, object> args = null)
{
var _request = CreateJsonRequest(endpoint, args, Method.Delete);
return await Task.FromResult(_request);
}
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="endpoint">api link address of a function</param>
/// <param name="args">Add additional attributes for each exchange</param>
/// <returns></returns>
public virtual async ValueTask<T> CallApiDeleteAsync<T>(string endpoint, Dictionary<string, object> args = null) where T : new()
{
var _response = await CallApiDelete2Async(endpoint, args);
return _response != null
? this.DeserializeObject<T>(_response.Content)
: new T();
}
/// <summary>
///
/// </summary>
/// <param name="endpoint">api link address of a function</param>
/// <param name="args">Add additional attributes for each exchange</param>
/// <returns></returns>
public virtual async ValueTask<string> CallApiDeleteAsync(string endpoint, Dictionary<string, object> args = null)
{
var _response = await CallApiDelete2Async(endpoint, args);
return _response != null ? _response.Content : "";
}
/// <summary>
///
/// </summary>
/// <param name="endpoint">api link address of a function</param>
/// <param name="args">Add additional attributes for each exchange</param>
/// <returns></returns>
public virtual async ValueTask<(string Content, RestResponse Response)> CallApiDelete1Async(string endpoint, Dictionary<string, object> args = null)
{
var _response = await CallApiDelete2Async(endpoint, args);
return (_response.Content, _response);
}
/// <summary>
///
/// </summary>
/// <param name="endpoint">api link address of a function</param>
/// <param name="args">Add additional attributes for each exchange</param>
/// <returns></returns>
public virtual async ValueTask<RestResponse> CallApiDelete2Async(string endpoint, Dictionary<string, object> args = null)
{
var _request = await CreateDeleteRequestAsync(endpoint, args);
#if DEBUG
if (TestXUnitMode == XUnitMode.ModeUnknown)
throw new Exception("DELETE: xUnitMode is unknown error when debug mode");
if (TestXUnitMode != XUnitMode.UseExchangeServer)
{
var _result = new RestResponse
{
Request = _request,
Content = args != null ? (args.ContainsKey("jsonContent") ? args["jsonContent"].ToString() : "") : "",
ResponseStatus = ResponseStatus.Completed,
StatusCode = HttpStatusCode.OK
};
return await Task.FromResult(_result);
}
#endif
return await RestExecuteAsync(_request);
}
#endregion method delete
#region method put
/// <summary>
///
/// </summary>
/// <param name="endpoint">api link address of a function</param>
/// <param name="args">Add additional attributes for each exchange</param>
/// <returns></returns>
public virtual async ValueTask<RestRequest> CreatePutRequestAsync(string endpoint, Dictionary<string, object> args = null)
{
var _request = CreateJsonRequest(endpoint, args, Method.Put);
return await Task.FromResult(_request);
}
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="endpoint">api link address of a function</param>
/// <param name="args">Add additional attributes for each exchange</param>
/// <returns></returns>
public virtual async ValueTask<T> CallApiPutAsync<T>(string endpoint, Dictionary<string, object> args = null) where T : new()
{
var _response = await CallApiPut2Async(endpoint, args);
return _response != null
? this.DeserializeObject<T>(_response.Content)
: new T();
}
/// <summary>
///
/// </summary>
/// <param name="endpoint">api link address of a function</param>
/// <param name="args">Add additional attributes for each exchange</param>
/// <returns></returns>
public virtual async ValueTask<string> CallApiPutAsync(string endpoint, Dictionary<string, object> args = null)
{
var _response = await CallApiPut2Async(endpoint, args);
return _response != null ? _response.Content : "";
}
/// <summary>
///
/// </summary>
/// <param name="endpoint">api link address of a function</param>
/// <param name="args">Add additional attributes for each exchange</param>
/// <returns></returns>
public virtual async ValueTask<(string Content, RestResponse Response)> CallApiPut1Async(string endpoint, Dictionary<string, object> args = null)
{
var _response = await CallApiPut2Async(endpoint, args);
return (_response.Content, _response);
}
/// <summary>
///
/// </summary>
/// <param name="endpoint">api link address of a function</param>
/// <param name="args">Add additional attributes for each exchange</param>
/// <returns></returns>
public virtual async ValueTask<RestResponse> CallApiPut2Async(string endpoint, Dictionary<string, object> args = null)
{
var _request = await CreatePutRequestAsync(endpoint, args);
#if DEBUG
if (TestXUnitMode == XUnitMode.ModeUnknown)
throw new Exception("PUT: xUnitMode is unknown error when debug mode");
if (TestXUnitMode != XUnitMode.UseExchangeServer)
{
var _result = new RestResponse
{
Request = _request,
Content = args != null ? (args.ContainsKey("jsonContent") ? args["jsonContent"].ToString() : "") : "",
ResponseStatus = ResponseStatus.Completed,
StatusCode = HttpStatusCode.OK
};
return await Task.FromResult(_result);
}
#endif
return await RestExecuteAsync(_request);
}
#endregion method put
/// <summary>
///
/// </summary>
public void Dispose()
{
}
}
} | 35.178095 | 170 | 0.532934 | [
"MIT"
] | lisa3907/ccxt.net | src/shared/standard/XApiClient.cs | 36,939 | C# |
using System;
namespace _07.StringExplosion
{
class Program
{
static void Main(string[] args)
{
string text = Console.ReadLine();
int strength = 0;
for (int i = 0; i < text.Length; i++)
{
if (text[i] == '>')
{
strength += int.Parse(text[i + 1].ToString());
continue;
}
if (strength > 0)
{
text = text.Remove(i, 1);
i--;
strength--;
}
}
Console.WriteLine(text);
}
}
} | 21.125 | 66 | 0.343195 | [
"MIT"
] | grekssi/Softuni-Courses | SoftUni/01. .NET Courses/02. Technology Fundamentals - C#/15. Strings and Text Processing/Exercises/07.StringExplosion/07.cs | 678 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
[Serializable]
public class GameState
{
public Board board;
public GameState() {
this.board = new Board();
}
}
[Serializable]
public class Board
{
public List<BoardSquare> boardSquares;
public Board() {
this.boardSquares = new List<BoardSquare>();
}
}
[Serializable]
public class BoardSquare
{
public string id;
public int positionX;
public int positionY;
public bool active;
public BoardSquare(string id, int positionX, int positionY)
{
this.id = id;
this.positionX = positionX;
this.positionY = positionY;
this.active = false;
}
}
| 14.877551 | 63 | 0.636488 | [
"MIT"
] | hsadler/simple-unity-multiplayer | GameClient/Assets/Scripts/GameState.cs | 729 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Diagnostics
{
internal partial class AnalyzerDriver<TLanguageKindEnum> : AnalyzerDriver
where TLanguageKindEnum : struct
{
/// <summary>
/// <see cref="AnalyzerActions"/> grouped by <see cref="DiagnosticAnalyzer"/>, and possibly other entities, such as <see cref="OperationKind"/>, <see cref="SymbolKind"/>, etc.
/// </summary>
private sealed class GroupedAnalyzerActions : IGroupedAnalyzerActions
{
public static readonly GroupedAnalyzerActions Empty = new GroupedAnalyzerActions(
ImmutableArray<(DiagnosticAnalyzer, GroupedAnalyzerActionsForAnalyzer)>.Empty,
AnalyzerActions.Empty
);
private GroupedAnalyzerActions(
ImmutableArray<(DiagnosticAnalyzer, GroupedAnalyzerActionsForAnalyzer)> groupedActionsAndAnalyzers,
in AnalyzerActions analyzerActions
)
{
GroupedActionsByAnalyzer = groupedActionsAndAnalyzers;
AnalyzerActions = analyzerActions;
}
public ImmutableArray<(DiagnosticAnalyzer analyzer, GroupedAnalyzerActionsForAnalyzer groupedActions)> GroupedActionsByAnalyzer { get; }
public AnalyzerActions AnalyzerActions { get; }
public bool IsEmpty
{
get
{
var isEmpty = ReferenceEquals(this, Empty);
Debug.Assert(isEmpty || !GroupedActionsByAnalyzer.IsEmpty);
return isEmpty;
}
}
public static GroupedAnalyzerActions Create(
DiagnosticAnalyzer analyzer,
in AnalyzerActions analyzerActions
)
{
if (analyzerActions.IsEmpty)
{
return Empty;
}
var groupedActions = new GroupedAnalyzerActionsForAnalyzer(
analyzer,
analyzerActions,
analyzerActionsNeedFiltering: false
);
var groupedActionsAndAnalyzers =
ImmutableArray<(DiagnosticAnalyzer, GroupedAnalyzerActionsForAnalyzer)>.Empty.Add(
(analyzer, groupedActions)
);
return new GroupedAnalyzerActions(groupedActionsAndAnalyzers, in analyzerActions);
}
public static GroupedAnalyzerActions Create(
ImmutableArray<DiagnosticAnalyzer> analyzers,
in AnalyzerActions analyzerActions
)
{
Debug.Assert(!analyzers.IsDefaultOrEmpty);
var groups = analyzers.SelectAsArray(
(analyzer, analyzerActions) =>
(
analyzer,
new GroupedAnalyzerActionsForAnalyzer(
analyzer,
analyzerActions,
analyzerActionsNeedFiltering: true
)
),
analyzerActions
);
return new GroupedAnalyzerActions(groups, in analyzerActions);
}
IGroupedAnalyzerActions IGroupedAnalyzerActions.Append(
IGroupedAnalyzerActions igroupedAnalyzerActions
)
{
var groupedAnalyzerActions = (GroupedAnalyzerActions)igroupedAnalyzerActions;
#if DEBUG
var inputAnalyzers = groupedAnalyzerActions.GroupedActionsByAnalyzer.Select(
a => a.analyzer
);
var myAnalyzers = GroupedActionsByAnalyzer.Select(a => a.analyzer);
var intersected = inputAnalyzers.Intersect(myAnalyzers);
Debug.Assert(intersected.IsEmpty());
#endif
var newGroupedActions = GroupedActionsByAnalyzer.AddRange(
groupedAnalyzerActions.GroupedActionsByAnalyzer
);
var newAnalyzerActions = AnalyzerActions.Append(
groupedAnalyzerActions.AnalyzerActions
);
return new GroupedAnalyzerActions(newGroupedActions, newAnalyzerActions);
}
}
}
}
| 39.848739 | 183 | 0.576339 | [
"MIT"
] | belav/roslyn | src/Compilers/Core/Portable/DiagnosticAnalyzer/AnalyzerDriver.GroupedAnalyzerActions.cs | 4,744 | C# |
using System;
using System.Threading.Tasks;
using Dragino.Gps.Messages;
namespace Dragino.Gps
{
public interface IGpsManager : IPositionProvider
{
/// <summary>
/// Event fired when a standard GPS message arrives.
/// </summary>
event EventHandler<StandardGpsMessageEventArgs> OnStandardMessage;
/// <summary>
/// Event fired when a custom GPS message arrives.
/// </summary>
event EventHandler<GpsMessageEventArgs> OnCustomMessage;
/// <summary>
/// Event fired when the <see cref="GpsManager.LatestPosition"/> changes.
/// </summary>
event EventHandler<PositionDataEventArgs> OnPositionData;
/// <summary>
/// Event fired when the <see cref="GpsManager.LatestMovement"/> changes.
/// </summary>
event EventHandler<MovementDataEventArgs> OnMovementData;
/// <summary>
/// The difference between the system clock and the GPS timestamp.
/// A positive value means that the system clock > GPS clock.
/// </summary>
TimeSpan? UtcDateTimeDifference { get; }
/// <summary>
/// Current UTC date time, adjusted to the latest GPS timestamp.
/// </summary>
DateTime AdjustedUtcNow { get; }
/// <summary>
/// Last known position information.
/// </summary>
PositionData LatestPosition { get; }
/// <summary>
/// Last known movement information.
/// </summary>
MovementData LatestMovement { get; }
/// <summary>
/// Send a message to the GPS chip.
/// </summary>
/// <param name="message">The message to be sent.</param>
/// <returns></returns>
Task SendMessage(GpsMessage message);
/// <summary>
/// Put the GPS in stand-by mode.
/// </summary>
Task Standby();
/// <summary>
/// Wake up the GPS from stand-by mode.
/// </summary>
Task WakeUp();
}
} | 30.41791 | 81 | 0.576546 | [
"MIT"
] | eberkund/Dragino.Lora | Dragino.Lora/Gps/IGpsManager.cs | 2,040 | C# |
//Do not edit! This file was generated by Unity-ROS MessageGeneration.
using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using Unity.Robotics.ROSTCPConnector.MessageGeneration;
namespace RosMessageTypes.Moveit
{
[Serializable]
public class ExecuteTrajectoryFeedback : Message
{
public const string k_RosMessageName = "moveit_msgs/ExecuteTrajectory";
public override string RosMessageName => k_RosMessageName;
// The internal state that the move group action currently is in
public string state;
public ExecuteTrajectoryFeedback()
{
this.state = "";
}
public ExecuteTrajectoryFeedback(string state)
{
this.state = state;
}
public static ExecuteTrajectoryFeedback Deserialize(MessageDeserializer deserializer) => new ExecuteTrajectoryFeedback(deserializer);
private ExecuteTrajectoryFeedback(MessageDeserializer deserializer)
{
deserializer.Read(out this.state);
}
public override void SerializeTo(MessageSerializer serializer)
{
serializer.Write(this.state);
}
public override string ToString()
{
return "ExecuteTrajectoryFeedback: " +
"\nstate: " + state.ToString();
}
#if UNITY_EDITOR
[UnityEditor.InitializeOnLoadMethod]
#else
[UnityEngine.RuntimeInitializeOnLoadMethod]
#endif
public static void Register()
{
MessageRegistry.Register(k_RosMessageName, Deserialize, MessageSubtopic.Feedback);
}
}
}
| 28.396552 | 141 | 0.66606 | [
"MIT"
] | scottwillmoore/fetch_vr | unity/Assets/Fetch VR/Messages/Moveit/action/ExecuteTrajectoryFeedback.cs | 1,647 | C# |
// *** WARNING: this file was generated by pulumigen. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Kubernetes.Types.Inputs.Apps.V1Beta2
{
/// <summary>
/// DaemonSetStatus represents the current status of a daemon set.
/// </summary>
public class DaemonSetStatusArgs : Pulumi.ResourceArgs
{
/// <summary>
/// Count of hash collisions for the DaemonSet. The DaemonSet controller uses this field as a collision avoidance mechanism when it needs to create the name for the newest ControllerRevision.
/// </summary>
[Input("collisionCount")]
public Input<int>? CollisionCount { get; set; }
[Input("conditions")]
private InputList<Pulumi.Kubernetes.Types.Inputs.Apps.V1Beta2.DaemonSetConditionArgs>? _conditions;
/// <summary>
/// Represents the latest available observations of a DaemonSet's current state.
/// </summary>
public InputList<Pulumi.Kubernetes.Types.Inputs.Apps.V1Beta2.DaemonSetConditionArgs> Conditions
{
get => _conditions ?? (_conditions = new InputList<Pulumi.Kubernetes.Types.Inputs.Apps.V1Beta2.DaemonSetConditionArgs>());
set => _conditions = value;
}
/// <summary>
/// The number of nodes that are running at least 1 daemon pod and are supposed to run the daemon pod. More info: https://kubernetes.io/docs/concepts/workloads/controllers/daemonset/
/// </summary>
[Input("currentNumberScheduled", required: true)]
public Input<int> CurrentNumberScheduled { get; set; } = null!;
/// <summary>
/// The total number of nodes that should be running the daemon pod (including nodes correctly running the daemon pod). More info: https://kubernetes.io/docs/concepts/workloads/controllers/daemonset/
/// </summary>
[Input("desiredNumberScheduled", required: true)]
public Input<int> DesiredNumberScheduled { get; set; } = null!;
/// <summary>
/// The number of nodes that should be running the daemon pod and have one or more of the daemon pod running and available (ready for at least spec.minReadySeconds)
/// </summary>
[Input("numberAvailable")]
public Input<int>? NumberAvailable { get; set; }
/// <summary>
/// The number of nodes that are running the daemon pod, but are not supposed to run the daemon pod. More info: https://kubernetes.io/docs/concepts/workloads/controllers/daemonset/
/// </summary>
[Input("numberMisscheduled", required: true)]
public Input<int> NumberMisscheduled { get; set; } = null!;
/// <summary>
/// The number of nodes that should be running the daemon pod and have one or more of the daemon pod running and ready.
/// </summary>
[Input("numberReady", required: true)]
public Input<int> NumberReady { get; set; } = null!;
/// <summary>
/// The number of nodes that should be running the daemon pod and have none of the daemon pod running and available (ready for at least spec.minReadySeconds)
/// </summary>
[Input("numberUnavailable")]
public Input<int>? NumberUnavailable { get; set; }
/// <summary>
/// The most recent generation observed by the daemon set controller.
/// </summary>
[Input("observedGeneration")]
public Input<int>? ObservedGeneration { get; set; }
/// <summary>
/// The total number of nodes that are running updated daemon pod
/// </summary>
[Input("updatedNumberScheduled")]
public Input<int>? UpdatedNumberScheduled { get; set; }
public DaemonSetStatusArgs()
{
}
}
}
| 44.325843 | 207 | 0.651711 | [
"Apache-2.0"
] | AaronFriel/pulumi-kubernetes | sdk/dotnet/Apps/V1Beta2/Inputs/DaemonSetStatusArgs.cs | 3,945 | C# |
/*
* 金庸群侠传3D重制版
* https://github.com/jynew/jynew
*
* 这是本开源项目文件头,所有代码均使用MIT协议。
* 但游戏内资源和第三方插件、dll等请仔细阅读LICENSE相关授权协议文档。
*
* 金庸老先生千古!
*/
using Jyx2;
using Jyx2.Middleware;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Jyx2RoleSelector : MonoBehaviour
{
public static Jyx2RoleSelector Create(IEnumerable<RoleInstance> roles, Func<RoleInstance, bool> mustRoles, Action<List<RoleInstance>> callback)
{
var prefab = Jyx2ResourceHelper.GetCachedPrefab("Assets/Prefabs/Jyx2RoleSelector.prefab");
var obj = Instantiate(prefab);
var parent = GameObject.Find("MainUI").transform;
obj.transform.SetParent(parent);
var rt = obj.GetComponent<RectTransform>();
rt.localPosition = Vector3.zero;
rt.localScale = Vector3.one;
var panel = obj.GetComponent<Jyx2RoleSelector>();
panel.Show(roles, mustRoles, callback);
return panel;
}
public Text info;
public Button confirmButton;
public Button cancelButton;
public Transform m_Container;
Action<List<RoleInstance>> _callback;
Func<RoleInstance, bool> _mustRolesFunc;
public void Show(IEnumerable<RoleInstance> roles, Func<RoleInstance, bool> mustRoles, Action<List<RoleInstance>> callback)
{
HSUnityTools.DestroyChildren(m_Container);
_mustRolesFunc = mustRoles;
_callback = callback;
foreach (var role in roles)
{
AddRole(role);
}
}
void AddRole(RoleInstance role)
{
bool isMust = (_mustRolesFunc != null && _mustRolesFunc(role));
var roleItemUI = Jyx2RoleHeadUI.Create(role, isMust, ()=> { info.text = role.Name; });
roleItemUI.transform.SetParent(m_Container);
}
void Start()
{
confirmButton.onClick.RemoveAllListeners();
confirmButton.onClick.AddListener(OnConfirm);
cancelButton.onClick.RemoveAllListeners();
cancelButton.onClick.AddListener(OnCancel);
}
void OnConfirm()
{
List<RoleInstance> rst = new List<RoleInstance>();
for(int i = 0; i < m_Container.childCount; ++i)
{
var child = m_Container.GetChild(i);
Jyx2RoleHeadUI roleHeadUI = child.GetComponent<Jyx2RoleHeadUI>();
if (roleHeadUI == null) continue;
if (roleHeadUI.IsChecked)
{
var role = roleHeadUI.GetRole();
rst.Add(role);
Debug.Log(role.Key);
}
}
_callback(rst);
Destroy(this.gameObject);
}
void OnCancel()
{
GameUtil.DisplayPopinfo("不能取消");
}
}
| 27.34 | 147 | 0.636064 | [
"MIT"
] | Alinccc/jynew | jyx2/Assets/Scripts/Jyx2RoleSelector.cs | 2,872 | C# |
// LeetCode #448
// https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/
//
// Given an array nums of n integers where nums[i] is in the range [1, n], return an array of all the integers in the range [1, n] that do not appear in nums.
// This solution uses the value of the number for the actual index in the new array so we can iterate through the new array and just check for any
// values that are still set to the default value of 0.
// This problem can also be solved using O(1) space by following a similar pattern but flipping each number to a negative as you iterate through the array,
// and then when you check the numbers on a second pass you look for any that are still positive.
// Time: O(n)
// Space: O(n)
public class Solution {
public IList<int> FindDisappearedNumbers(int[] nums) {
int[] foundNums = new int[nums.Length + 1];
List<int> missingNumList = new List<int>();
for (int i = 0; i < nums.Length; i++) {
foundNums[nums[i]] = nums[i];
}
for (int i = 1; i < foundNums.Length; i++) {
if (foundNums[i] == 0) {
missingNumList.Add(i);
}
}
return missingNumList;
}
} | 41.633333 | 158 | 0.629303 | [
"MIT"
] | eander01/InterviewPrep | Solutions/LeetCode/0448/FindDisappearedNumbers.cs | 1,249 | C# |
////////////////////////////////////////////////////////////////////////////////
//NUnit tests for "EF Core Provider for LCPI OLE DB"
// IBProvider and Contributors. 05.12.2020.
using System;
using System.Data;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using NUnit.Framework;
using xdb=lcpi.data.oledb;
namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Operators.SET_001.Multiply.Complete.NullableInt32.NullableDouble{
////////////////////////////////////////////////////////////////////////////////
using T_DATA1 =System.Nullable<System.Int32>;
using T_DATA2 =System.Nullable<System.Double>;
////////////////////////////////////////////////////////////////////////////////
//class TestSet_001__fields
public static class TestSet_001__fields
{
private const string c_NameOf__TABLE ="TEST_MODIFY_ROW2";
private const string c_NameOf__COL_DATA1 ="COL_INTEGER";
private const string c_NameOf__COL_DATA2 ="COL2_DOUBLE";
private sealed class MyContext:TestBaseDbContext
{
[Table(c_NameOf__TABLE)]
public sealed class TEST_RECORD
{
[Key]
[Column("TEST_ID")]
public System.Int64? TEST_ID { get; set; }
[Column(c_NameOf__COL_DATA1)]
public T_DATA1 COL_DATA1 { get; set; }
[Column(c_NameOf__COL_DATA2)]
public T_DATA2 COL_DATA2 { get; set; }
};//class TEST_RECORD
//----------------------------------------------------------------------
public DbSet<TEST_RECORD> testTable { get; set; }
//----------------------------------------------------------------------
public MyContext(xdb.OleDbTransaction tr)
:base(tr)
{
}//MyContext
};//class MyContext
//-----------------------------------------------------------------------
[Test]
public static void Test_001()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
T_DATA1 c_value1=7;
T_DATA2 c_value2=4;
System.Int64? testID=Helper__InsertRow(db,c_value1,c_value2);
Assert.AreEqual
(28,
c_value1*c_value2);
var recs=db.testTable.Where(r => (r.COL_DATA1*r.COL_DATA2)==28 && r.TEST_ID==testID);
int nRecs=0;
foreach(var r in recs)
{
Assert.AreEqual
(0,
nRecs);
++nRecs;
Assert.IsTrue
(r.TEST_ID.HasValue);
Assert.AreEqual
(testID,
r.TEST_ID.Value);
Assert.AreEqual
(c_value1,
r.COL_DATA1);
Assert.AreEqual
(c_value2,
r.COL_DATA2);
}//foreach r
var sqlt
=new TestSqlTemplate()
.T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_DATA1).T(", ").N("t",c_NameOf__COL_DATA2).EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL()
.T("WHERE ((CAST(").N("t",c_NameOf__COL_DATA1).T(" AS DOUBLE PRECISION) * ").N("t",c_NameOf__COL_DATA2).T(") = 28.0) AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")");
db.CheckTextOfLastExecutedCommand
(sqlt);
Assert.AreEqual
(1,
nRecs);
}//using db
tr.Rollback();
}//using tr
}//using cn
}//Test_001
//-----------------------------------------------------------------------
[Test]
public static void Test_002()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
T_DATA1 c_value1=7;
T_DATA2 c_value2=4.5;
System.Int64? testID=Helper__InsertRow(db,c_value1,c_value2);
Assert.AreEqual
(31.5,
c_value1*c_value2);
var recs=db.testTable.Where(r => (r.COL_DATA1*r.COL_DATA2)==31.5 && r.TEST_ID==testID);
int nRecs=0;
foreach(var r in recs)
{
Assert.AreEqual
(0,
nRecs);
++nRecs;
Assert.IsTrue
(r.TEST_ID.HasValue);
Assert.AreEqual
(testID,
r.TEST_ID.Value);
Assert.AreEqual
(c_value1,
r.COL_DATA1);
Assert.AreEqual
(c_value2,
r.COL_DATA2);
}//foreach r
var sqlt
=new TestSqlTemplate()
.T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_DATA1).T(", ").N("t",c_NameOf__COL_DATA2).EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL()
.T("WHERE ((CAST(").N("t",c_NameOf__COL_DATA1).T(" AS DOUBLE PRECISION) * ").N("t",c_NameOf__COL_DATA2).T(") = 31.5) AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")");
db.CheckTextOfLastExecutedCommand
(sqlt);
Assert.AreEqual
(1,
nRecs);
}//using db
tr.Rollback();
}//using tr
}//using cn
}//Test_002
//-----------------------------------------------------------------------
private static System.Int64 Helper__InsertRow(MyContext db,
T_DATA1 valueForColData1,
T_DATA2 valueForColData2)
{
var newRecord=new MyContext.TEST_RECORD();
newRecord.COL_DATA1 =valueForColData1;
newRecord.COL_DATA2 =valueForColData2;
db.testTable.Add(newRecord);
db.SaveChanges();
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("INSERT INTO ").N(c_NameOf__TABLE).T(" (").N(c_NameOf__COL_DATA1).T(", ").N(c_NameOf__COL_DATA2).T(")").EOL()
.T("VALUES (").P("p0").T(", ").P("p1").T(")").EOL()
.T("RETURNING ").N("TEST_ID").EOL()
.T("INTO ").P("p2").T(";"));
Assert.IsTrue
(newRecord.TEST_ID.HasValue);
Console.WriteLine("TEST_ID: {0}",newRecord.TEST_ID.Value);
return newRecord.TEST_ID.Value;
}//Helper__InsertRow
};//class TestSet_001__fields
////////////////////////////////////////////////////////////////////////////////
}//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Operators.SET_001.Multiply.Complete.NullableInt32.NullableDouble
| 27.248889 | 184 | 0.551623 | [
"MIT"
] | ibprovider/Lcpi.EFCore.LcpiOleDb | Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D3/Query/Operators/SET_001/Multiply/Complete/NullableInt32/NullableDouble/TestSet_001__fields.cs | 6,133 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace NingyoRi
{
public enum ManagerType
{
TextMap,
Input,
Resource,
UI,
Entity,
None
}
public partial class TextMapManager
{
public override ManagerType managerType { get { return ManagerType.TextMap; } }
}
public partial class ResourceManager
{
public override ManagerType managerType { get { return ManagerType.Resource; } }
}
public partial class InputManager
{
public override ManagerType managerType { get { return ManagerType.Input; } }
}
public partial class UIManager
{
public override ManagerType managerType { get { return ManagerType.UI; } }
}
public partial class EntityManager
{
public override ManagerType managerType { get { return ManagerType.Entity; } }
}
} | 18.767442 | 82 | 0.741016 | [
"MIT"
] | IdlessChaye/NoMono | Assets/TouhouNingyoMatsuri/Scripts/Src/Managers/ManagerType.cs | 809 | C# |
using AIS.Parser.Contracts;
using AIS.Parser.Models;
using Microsoft.Extensions.DependencyInjection;
namespace AIS.Parser.Bootstrapping
{
public class DefaultBootstrappingConfiguration
{
public void Bootstrap(IServiceCollection serviceCollection)
{
serviceCollection.AddSingleton<IPacketFactory, PacketFactory>();
serviceCollection.AddSingleton<ISentenceListener, NMEASentenceListener>();
serviceCollection.AddSingleton<ISentenceProcessor, NMEASentenceProcessor>();
var vesselCollection = new VesselCollection();
serviceCollection.AddSingleton<VesselCollection>(vesselCollection);
serviceCollection.AddTransient<IReadOnlyVesselCollection, VesselCollection>((serviceProvider) => vesselCollection);
}
}
}
| 38.761905 | 127 | 0.743243 | [
"MIT"
] | StephenDemanuele/Marine_AIS | AIS.Parser/Bootstrapping/DefaultBootstrappingConfiguration.cs | 816 | C# |
// (c) Copyright Microsoft Corporation.
// This source is subject to the Microsoft Public License (Ms-PL).
// Please see http://go.microsoft.com/fwlink/?LinkID=131993 for details.
// All other rights reserved.
using Avalonia.Controls.Metadata;
using Avalonia.Controls.Mixins;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Media;
using System;
using System.Diagnostics;
using System.Reactive.Linq;
namespace Avalonia.Controls
{
[PseudoClasses(":pressed", ":current", ":expanded")]
public class DataGridRowGroupHeader : TemplatedControl
{
private const string DATAGRIDROWGROUPHEADER_expanderButton = "ExpanderButton";
private const string DATAGRIDROWGROUPHEADER_indentSpacer = "IndentSpacer";
private const string DATAGRIDROWGROUPHEADER_itemCountElement = "ItemCountElement";
private const string DATAGRIDROWGROUPHEADER_propertyNameElement = "PropertyNameElement";
private bool _areIsCheckedHandlersSuspended;
private ToggleButton _expanderButton;
private DataGridRowHeader _headerElement;
private Control _indentSpacer;
private TextBlock _itemCountElement;
private TextBlock _propertyNameElement;
private Panel _rootElement;
private double _totalIndent;
public static readonly StyledProperty<bool> IsItemCountVisibleProperty =
AvaloniaProperty.Register<DataGridRowGroupHeader, bool>(nameof(IsItemCountVisible));
/// <summary>
/// Gets or sets a value that indicates whether the item count is visible.
/// </summary>
public bool IsItemCountVisible
{
get { return GetValue(IsItemCountVisibleProperty); }
set { SetValue(IsItemCountVisibleProperty, value); }
}
public static readonly StyledProperty<string> PropertyNameProperty =
AvaloniaProperty.Register<DataGridRowGroupHeader, string>(nameof(PropertyName));
/// <summary>
/// Gets or sets the name of the property that this <see cref="T:Avalonia.Controls.DataGrid" /> row is bound to.
/// </summary>
public string PropertyName
{
get { return GetValue(PropertyNameProperty); }
set { SetValue(PropertyNameProperty, value); }
}
public static readonly StyledProperty<bool> IsPropertyNameVisibleProperty =
AvaloniaProperty.Register<DataGridRowGroupHeader, bool>(nameof(IsPropertyNameVisible));
/// <summary>
/// Gets or sets a value that indicates whether the property name is visible.
/// </summary>
public bool IsPropertyNameVisible
{
get { return GetValue(IsPropertyNameVisibleProperty); }
set { SetValue(IsPropertyNameVisibleProperty, value); }
}
public static readonly StyledProperty<double> SublevelIndentProperty =
AvaloniaProperty.Register<DataGridRowGroupHeader, double>(
nameof(SublevelIndent),
defaultValue: DataGrid.DATAGRID_defaultRowGroupSublevelIndent,
validate: IsValidSublevelIndent);
private static bool IsValidSublevelIndent(double value)
{
return !double.IsNaN(value) && !double.IsInfinity(value) && value >= 0;
}
/// <summary>
/// Gets or sets a value that indicates the amount that the
/// children of the <see cref="T:Avalonia.Controls.RowGroupHeader" /> are indented.
/// </summary>
public double SublevelIndent
{
get { return GetValue(SublevelIndentProperty); }
set { SetValue(SublevelIndentProperty, value); }
}
private void OnSublevelIndentChanged(AvaloniaPropertyChangedEventArgs e)
{
if (OwningGrid != null)
{
OwningGrid.OnSublevelIndentUpdated(this, (double)e.NewValue);
}
}
static DataGridRowGroupHeader()
{
SublevelIndentProperty.Changed.AddClassHandler<DataGridRowGroupHeader>((x,e) => x.OnSublevelIndentChanged(e));
PressedMixin.Attach<DataGridRowGroupHeader>();
}
/// <summary>
/// Constructs a DataGridRowGroupHeader
/// </summary>
public DataGridRowGroupHeader()
{
//DefaultStyleKey = typeof(DataGridRowGroupHeader);
AddHandler(InputElement.PointerPressedEvent, (s, e) => DataGridRowGroupHeader_PointerPressed(e), handledEventsToo: true);
}
internal DataGridRowHeader HeaderCell
{
get
{
return _headerElement;
}
}
private bool IsCurrent
{
get
{
Debug.Assert(OwningGrid != null);
return (RowGroupInfo.Slot == OwningGrid.CurrentSlot);
}
}
private bool IsMouseOver
{
get;
set;
}
internal bool IsRecycled
{
get;
set;
}
internal int Level
{
get;
set;
}
internal DataGrid OwningGrid
{
get;
set;
}
internal DataGridRowGroupInfo RowGroupInfo
{
get;
set;
}
internal double TotalIndent
{
set
{
_totalIndent = value;
if (_indentSpacer != null)
{
_indentSpacer.Width = _totalIndent;
}
}
}
private IDisposable _expanderButtonSubscription;
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
_rootElement = e.NameScope.Find<Panel>(DataGridRow.DATAGRIDROW_elementRoot);
_expanderButtonSubscription?.Dispose();
_expanderButton = e.NameScope.Find<ToggleButton>(DATAGRIDROWGROUPHEADER_expanderButton);
if(_expanderButton != null)
{
EnsureExpanderButtonIsChecked();
_expanderButtonSubscription =
_expanderButton.GetObservable(ToggleButton.IsCheckedProperty)
.Skip(1)
.Subscribe(v => OnExpanderButtonIsCheckedChanged(v));
}
_headerElement = e.NameScope.Find<DataGridRowHeader>(DataGridRow.DATAGRIDROW_elementRowHeader);
if(_headerElement != null)
{
_headerElement.Owner = this;
EnsureHeaderVisibility();
}
_indentSpacer = e.NameScope.Find<Control>(DATAGRIDROWGROUPHEADER_indentSpacer);
if(_indentSpacer != null)
{
_indentSpacer.Width = _totalIndent;
}
_itemCountElement = e.NameScope.Find<TextBlock>(DATAGRIDROWGROUPHEADER_itemCountElement);
_propertyNameElement = e.NameScope.Find<TextBlock>(DATAGRIDROWGROUPHEADER_propertyNameElement);
UpdateTitleElements();
}
internal void ApplyHeaderStatus()
{
if (_headerElement != null && OwningGrid.AreRowHeadersVisible)
{
_headerElement.UpdatePseudoClasses();
}
}
internal void UpdatePseudoClasses()
{
PseudoClasses.Set(":current", IsCurrent);
if (RowGroupInfo?.CollectionViewGroup != null)
{
PseudoClasses.Set(":expanded", RowGroupInfo.IsVisible && RowGroupInfo.CollectionViewGroup.ItemCount > 0);
}
}
protected override Size ArrangeOverride(Size finalSize)
{
if (OwningGrid == null)
{
return base.ArrangeOverride(finalSize);
}
Size size = base.ArrangeOverride(finalSize);
if (_rootElement != null)
{
if (OwningGrid.AreRowGroupHeadersFrozen)
{
foreach (Control child in _rootElement.Children)
{
child.Clip = null;
}
}
else
{
double frozenLeftEdge = 0;
foreach (Control child in _rootElement.Children)
{
if (DataGridFrozenGrid.GetIsFrozen(child) && child.IsVisible)
{
TranslateTransform transform = new TranslateTransform();
// Automatic layout rounding doesn't apply to transforms so we need to Round this
transform.X = Math.Round(OwningGrid.HorizontalOffset);
child.RenderTransform = transform;
double childLeftEdge = child.Translate(this, new Point(child.Bounds.Width, 0)).X - transform.X;
frozenLeftEdge = Math.Max(frozenLeftEdge, childLeftEdge + OwningGrid.HorizontalOffset);
}
}
// Clip the non-frozen elements so they don't overlap the frozen ones
foreach (Control child in _rootElement.Children)
{
if (!DataGridFrozenGrid.GetIsFrozen(child))
{
EnsureChildClip(child, frozenLeftEdge);
}
}
}
}
return size;
}
internal void ClearFrozenStates()
{
if (_rootElement != null)
{
foreach (Control child in _rootElement.Children)
{
child.RenderTransform = null;
}
}
}
//TODO TabStop
private void DataGridRowGroupHeader_PointerPressed(PointerPressedEventArgs e)
{
if (OwningGrid == null)
{
return;
}
if (e.GetCurrentPoint(this).Properties.IsLeftButtonPressed)
{
if (OwningGrid.IsDoubleClickRecordsClickOnCall(this) && !e.Handled)
{
ToggleExpandCollapse(!RowGroupInfo.IsVisible, true);
e.Handled = true;
}
else
{
//if (!e.Handled && OwningGrid.IsTabStop)
if (!e.Handled)
{
OwningGrid.Focus();
}
e.Handled = OwningGrid.UpdateStateOnMouseLeftButtonDown(e, OwningGrid.CurrentColumnIndex, RowGroupInfo.Slot, allowEdit: false);
}
}
else if (e.GetCurrentPoint(this).Properties.IsRightButtonPressed)
{
if (!e.Handled)
{
OwningGrid.Focus();
}
e.Handled = OwningGrid.UpdateStateOnMouseRightButtonDown(e, OwningGrid.CurrentColumnIndex, RowGroupInfo.Slot, allowEdit: false);
}
}
private void EnsureChildClip(Visual child, double frozenLeftEdge)
{
double childLeftEdge = child.Translate(this, new Point(0, 0)).X;
if (frozenLeftEdge > childLeftEdge)
{
double xClip = Math.Round(frozenLeftEdge - childLeftEdge);
var rg = new RectangleGeometry();
rg.Rect =
new Rect(xClip, 0,
Math.Max(0, child.Bounds.Width - xClip),
child.Bounds.Height);
child.Clip = rg;
}
else
{
child.Clip = null;
}
}
internal void EnsureExpanderButtonIsChecked()
{
if (_expanderButton != null && RowGroupInfo != null && RowGroupInfo.CollectionViewGroup != null &&
RowGroupInfo.CollectionViewGroup.ItemCount != 0)
{
SetIsCheckedNoCallBack(RowGroupInfo.IsVisible);
}
}
//TODO Styles
//internal void EnsureHeaderStyleAndVisibility(Style previousStyle)
internal void EnsureHeaderVisibility()
{
if (_headerElement != null && OwningGrid != null)
{
_headerElement.IsVisible = OwningGrid.AreRowHeadersVisible;
}
}
private void OnExpanderButtonIsCheckedChanged(bool? value)
{
if(!_areIsCheckedHandlersSuspended)
{
ToggleExpandCollapse(value ?? false, true);
}
}
internal void LoadVisualsForDisplay()
{
EnsureExpanderButtonIsChecked();
EnsureHeaderVisibility();
UpdatePseudoClasses();
ApplyHeaderStatus();
}
protected override void OnPointerEnter(PointerEventArgs e)
{
if (IsEnabled)
{
IsMouseOver = true;
UpdatePseudoClasses();
}
base.OnPointerEnter(e);
}
protected override void OnPointerLeave(PointerEventArgs e)
{
if (IsEnabled)
{
IsMouseOver = false;
UpdatePseudoClasses();
}
base.OnPointerLeave(e);
}
private void SetIsCheckedNoCallBack(bool value)
{
if (_expanderButton != null && _expanderButton.IsChecked != value)
{
_areIsCheckedHandlersSuspended = true;
try
{
_expanderButton.IsChecked = value;
}
finally
{
_areIsCheckedHandlersSuspended = false;
}
}
}
internal void ToggleExpandCollapse(bool isVisible, bool setCurrent)
{
if (RowGroupInfo.CollectionViewGroup.ItemCount != 0)
{
if (OwningGrid == null)
{
// Do these even if the OwningGrid is null in case it could improve the Designer experience for a standalone DataGridRowGroupHeader
RowGroupInfo.IsVisible = isVisible;
}
else if(RowGroupInfo.IsVisible != isVisible)
{
OwningGrid.OnRowGroupHeaderToggled(this, isVisible, setCurrent);
}
EnsureExpanderButtonIsChecked();
UpdatePseudoClasses();
}
}
internal void UpdateTitleElements()
{
if (_propertyNameElement != null)
{
string txt;
if (string.IsNullOrWhiteSpace(PropertyName))
txt = String.Empty;
else
txt = String.Format("{0}:", PropertyName);
_propertyNameElement.Text = txt;
}
if (_itemCountElement != null && RowGroupInfo != null && RowGroupInfo.CollectionViewGroup != null)
{
string formatString;
if(RowGroupInfo.CollectionViewGroup.ItemCount == 1)
formatString = "({0} Item)";
else
formatString = "({0} Items)";
_itemCountElement.Text = String.Format(formatString, RowGroupInfo.CollectionViewGroup.ItemCount);
}
}
}
}
| 34.243956 | 151 | 0.54175 | [
"MIT"
] | 0x90d/Avalonia | src/Avalonia.Controls.DataGrid/DataGridRowGroupHeader.cs | 15,583 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using ISAAR.MSolve.FEM.Stochastic;
using ISAAR.MSolve.Solvers.Interfaces;
using ISAAR.MSolve.Solvers.PCGSkyline;
using ISAAR.MSolve.Numerical.LinearAlgebra;
using ISAAR.MSolve.Numerical.LinearAlgebra.Interfaces;
namespace ISAAR.MSolve.Analyzers
{
public enum PolynomialChaosSolverPCGPreconditioner
{
BlockDiagonal,
BlockSSOR,
ILU,
SSOR,
Diagonal
}
public class PolynomialChaosSolverPCGMatrixCalculator : ISolverPCGMatrixCalculator
{
private SolverPCG<SkylineMatrix2D> solver;
private readonly int mOrder, pOrder;
private readonly PolynomialChaosSolverPCGPreconditioner preconditionerKind;
//private readonly int psiSize;
//private int[][] psiBasis;
//private int[] psiSquareNorm;
//private List<Tuple<int, int, double>>[] gaussianCoefficients;
//private Dictionary<Tuple<int, int>, double>[] lognormalCoefficients;
private readonly bool isGaussian;
private readonly PolynomialChaosCoefficientsCalculator calculator;
private double[] meanDiagonalCoefficients, ssorDiagonals;
private PolynomialChaosAnalyzer analyzer;
private int meanSize;
private Vector tempVectorIn, tempVectorOut;
private List<List<Tuple<int, int, int, double>>> coeffLower, coeffUpper;
public SolverPCG<SkylineMatrix2D> Solver
{
get { return solver; }
set { solver = value; }
}
public PolynomialChaosAnalyzer Analyzer
{
get { return analyzer; }
set { analyzer = value; }
}
public PolynomialChaosSolverPCGMatrixCalculator(int m, int p, bool isGaussian, PolynomialChaosSolverPCGPreconditioner preconditionerKind)
{
this.preconditionerKind = preconditionerKind;
this.isGaussian = isGaussian;
this.calculator = new PolynomialChaosCoefficientsCalculator(m, p, isGaussian);
this.mOrder = m;
this.pOrder = p;
//if (mOrder < 1) throw new ArgumentException("m cannot be less than 1");
//if (pOrder < 1) throw new ArgumentException("p cannot be less than 1");
//psiSize = 0;
//for (int k = 0; k <= pOrder; k++)
// psiSize += Factorial(mOrder + k - 1) / (Factorial(k) * Factorial(mOrder - 1));
//CalculatePCCoefficients();
CalculateMeanDiagonalCoefficients();
if (isGaussian)
MakeGaussianCache();
else
MakeLognormalCache();
}
private void MakeSSORDiagonals()
{
if (ssorDiagonals != null) return;
ssorDiagonals = new double[this.VectorSize];
//foreach (ILinearSystem subdomain in solver.SubdomainsDictionary.Values)
//foreach (ILinearSystem subdomain in solver.SubdomainsDictionary.Values)
//{
for (int i = 0; i < coeffLower.Count; i++)
{
int blockStart = i * meanSize;
foreach (var c in coeffLower[i].Where(x => x.Item2 == x.Item3))
{
SkylineMatrix2D K = (SkylineMatrix2D)analyzer.Matrices[c.Item1][solver.LinearSystem.ID];
double[] d = K.Data as double[];
for (int n = 0; n < K.Rows; n++)
ssorDiagonals[blockStart + n] += d[K.RowIndex[n]] * c.Item4;
}
//}
}
//for (int n = 0; n < ssorDiagonals.Length; n++)
// ssorDiagonals[n] = 1.0 / ssorDiagonals[n];
}
public int VectorSize
{
get
{
//meanSize = solver.SubdomainsDictionary.Values.First().RHS.Length;
meanSize = solver.LinearSystem.RHS.Length;
return meanSize * calculator.PsiSize;
}
}
private void MakeGaussianCache()
{
var cLower = calculator.GaussianCoefficients.SelectMany((x, index) =>
{
var a = new List<Tuple<int, int, int, double>>();
foreach (var item in x)
if (item.Item1 >= item.Item2)
a.Add(new Tuple<int, int, int, double>(index, item.Item1, item.Item2, item.Item3));
return a;
})
.OrderBy(x => x.Item1).OrderBy(x => x.Item3).OrderBy(x => x.Item2)
.GroupBy(x => x.Item2);
coeffLower = new List<List<Tuple<int, int, int, double>>>();
foreach (var elements in cLower)
{
var currentList = new List<Tuple<int, int, int, double>>();
foreach (var element in elements)
currentList.Add(element);
coeffLower.Add(currentList);
}
var cUpper = calculator.GaussianCoefficients.SelectMany((x, index) =>
{
var a = new List<Tuple<int, int, int, double>>();
foreach (var item in x)
if (item.Item1 <= item.Item2)
a.Add(new Tuple<int, int, int, double>(index, item.Item1, item.Item2, item.Item3));
return a;
})
.OrderBy(x => x.Item1).OrderBy(x => x.Item3).OrderBy(x => x.Item2)
.GroupBy(x => x.Item2);
coeffUpper = new List<List<Tuple<int, int, int, double>>>();
foreach (var elements in cUpper)
{
var currentList = new List<Tuple<int, int, int, double>>();
foreach (var element in elements)
currentList.Add(element);
coeffUpper.Add(currentList);
}
}
private void MakeLognormalCache()
{
var cLower = calculator.LognormalCoefficients.SelectMany((x, index) =>
{
var a = new List<Tuple<int, int, int, double>>();
foreach (var item in x)
if (item.Key.Item1 >= item.Key.Item2)
a.Add(new Tuple<int, int, int, double>(index, item.Key.Item1, item.Key.Item2, item.Value));
return a;
})
.OrderBy(x => x.Item1).OrderBy(x => x.Item3).OrderBy(x => x.Item2)
.GroupBy(x => x.Item2);
coeffLower = new List<List<Tuple<int, int, int, double>>>();
foreach (var elements in cLower)
{
var currentList = new List<Tuple<int, int, int, double>>();
foreach (var element in elements)
currentList.Add(element);
coeffLower.Add(currentList);
}
var cUpper = calculator.LognormalCoefficients.SelectMany((x, index) =>
{
var a = new List<Tuple<int, int, int, double>>();
foreach (var item in x)
if (item.Key.Item1 <= item.Key.Item2)
a.Add(new Tuple<int, int, int, double>(index, item.Key.Item1, item.Key.Item2, item.Value));
return a;
})
.OrderBy(x => x.Item1).OrderBy(x => x.Item3).OrderBy(x => x.Item2)
.GroupBy(x => x.Item2);
coeffUpper = new List<List<Tuple<int, int, int, double>>>();
foreach (var elements in cUpper)
{
var currentList = new List<Tuple<int, int, int, double>>();
foreach (var element in elements)
currentList.Add(element);
coeffUpper.Add(currentList);
}
}
//private int Factorial(int f)
//{
// int result = 1;
// for (int i = 2; i <= f; i++)
// result *= i;
// return result;
//}
//private int DoubleFactorial(int f)
//{
// if (f % 2 == 1) return 0;
// int f2 = f / 2;
// int result = 1;
// for (int i = 2; i <= f2; i++)
// result *= 2 * i - 1;
// return result;
//}
//private double[][] HermitePolynomials(int order)
//{
// double[][] p = new double[order][];
// p[0] = new double[2] { 1, 0 };
// for (int i = 1; i < order; i++)
// {
// int i1 = i + 1;
// p[i] = new double[i + 2];
// for (int j = 0; j <= i; j++)
// p[i][j] = p[i - 1][j] * i1 / (i1 - j);
// p[i][i1] = i1 % 2 == 1 ? 0 : Math.Pow(-1, i1 / 2) * DoubleFactorial(i1);
// }
// return p;
//}
//private double[] Convolute(double[] v1, double[] v2)
//{
// int vecSize1 = v1.Length;
// int vecSize2 = v2.Length;
// int size = vecSize1 + vecSize2 - 1;
// var result = new double[size];
// var v1Ext = new double[size];
// var v2Ext = new double[size];
// var v2Reverse = v2.Reverse().ToArray();
// Array.Clear(v2Ext, 0, size);
// Array.Copy(v2Reverse, 0, v2Ext, size - vecSize2, vecSize2);
// int index = size - 1;
// for (int i = 0; i < size - vecSize1 + 1; i++)
// {
// Array.Clear(v1Ext, 0, size);
// Array.Copy(v1, 0, v1Ext, i, vecSize1);
// for (int j = 0; j < size; j++)
// result[index] += v1Ext[j] * v2Ext[j];
// index--;
// }
// for (int i = size - vecSize2 - 1; i >= 0; i--)
// {
// Array.Clear(v2Ext, 0, size);
// Array.Copy(v2Reverse, 0, v2Ext, i, vecSize2);
// for (int j = 0; j < size; j++)
// result[index] += v1Ext[j] * v2Ext[j];
// index--;
// }
// return result;
//}
//private void CalculatePCCoefficients()
//{
// psiBasis = new int[psiSize][];
// for (int i = 0; i < psiSize; i++)
// psiBasis[i] = new int[mOrder];
// int mm = mOrder - 1;
// int n = 0;
// if (mOrder == 1)
// for (int i = 0; i < pOrder; i++)
// psiBasis[i + 1][0] = i;
// else
// {
// int[] t = new int[mm];
// for (int currentOrder = 1; currentOrder <= pOrder; currentOrder++)
// {
// bool endOfGeneration = false;
// bool firstThisOrder = false;
// while (!endOfGeneration)
// {
// n++;
// if (!firstThisOrder)
// {
// for (int i = 0; i < mm; i++)
// t[i] = i + 1;
// firstThisOrder = true;
// }
// else
// {
// if (t[mm - 1] < mm + currentOrder)
// t[mm - 1] += 1;
// else
// {
// int j = mm;
// while (t[j - 1] == j + currentOrder)
// j--;
// t[j - 1]++;
// for (int k = j; k < mm; k++)
// t[k] = t[j - 1] + k - j + 1;
// }
// }
// psiBasis[n][0] = t[0] - 1;
// for (int i = 1; i < mm; i++)
// psiBasis[n][i] = t[i] - t[i - 1] - 1;
// psiBasis[n][mm] = mOrder + currentOrder - t[mm - 1] - 1;
// if (t[0] == currentOrder + 1)
// endOfGeneration = true;
// }
// }
// }
// psiSquareNorm = new int[psiSize];
// int norme = 1;
// for (int k = 0; k < psiSize; k++)
// {
// norme = 1;
// for (int j = 0; j < mOrder; j++)
// norme *= Factorial(psiBasis[k][j]);
// psiSquareNorm[k] = norme;
// }
// gaussianCoefficients = new List<Tuple<int, int, double>>[mOrder];
// for (int i = 0; i < mOrder; i++)
// {
// gaussianCoefficients[i] = new List<Tuple<int, int, double>>();
// for (int j = 0; j < psiSize; j++)
// for (int k = 0; k < psiSize; k++)
// {
// bool almostEqual = false;
// for (int l = 0; l < mOrder; l++)
// if (l != i && psiBasis[j][l] != psiBasis[k][l])
// {
// almostEqual = true;
// break;
// }
// if (!almostEqual)
// if (psiBasis[k][i] == psiBasis[j][i] - 1)
// gaussianCoefficients[i].Add(new Tuple<int, int, double>(j, k, psiSquareNorm[j]));
// else if (psiBasis[k][i] == psiBasis[j][i] + 1)
// gaussianCoefficients[i].Add(new Tuple<int, int, double>(j, k, psiSquareNorm[j] * (psiBasis[j][i] + 1)));
// }
// }
// var hp = HermitePolynomials(pOrder);
// lognormalCoefficients = new Dictionary<Tuple<int, int>, double>[psiSize];
// for (int i = 0; i < psiSize; i++)
// lognormalCoefficients[i] = new Dictionary<Tuple<int, int>, double>();
// for (int i = 0; i < psiSize; i++)
// {
// for (int j = 0; j < psiSize; j++)
// for (int k = 0; k < psiSize; k++)
// {
// double esp = 1;
// double[] productPol;
// for (int l = 0; l < mOrder; l++)
// {
// if (psiBasis[i][l] == 0)
// if (psiBasis[j][l] == 0)
// if (psiBasis[k][l] == 0)
// productPol = new double[] { 1 };
// else
// productPol = hp[psiBasis[k][l] - 1];
// else
// if (psiBasis[k][l] == 0)
// productPol = hp[psiBasis[j][l] - 1];
// else
// productPol = Convolute(hp[psiBasis[j][l] - 1], hp[psiBasis[k][l] - 1]);
// else
// if (psiBasis[j][l] == 0)
// if (psiBasis[k][l] == 0)
// productPol = hp[psiBasis[i][l] - 1];
// else
// productPol = Convolute(hp[psiBasis[i][l] - 1], hp[psiBasis[k][l] - 1]);
// else
// if (psiBasis[k][l] == 0)
// productPol = Convolute(hp[psiBasis[i][l] - 1], hp[psiBasis[j][l] - 1]);
// else
// productPol = Convolute(Convolute(hp[psiBasis[i][l] - 1], hp[psiBasis[j][l] - 1]), hp[psiBasis[k][l] - 1]);
// int degPol = productPol.Length - 1;
// double esperanceProd = productPol[degPol];
// for (int q = 0; q < degPol - 1; q++)
// esperanceProd += DoubleFactorial(degPol - q) * productPol[q];
// esp *= esperanceProd;
// if (esp == 0)
// break;
// }
// if (esp != 0)
// {
// var jk = new Tuple<int, int>(j, k);
// var kj = new Tuple<int, int>(k, j);
// var ik = new Tuple<int, int>(i, k);
// var ki = new Tuple<int, int>(k, i);
// var ij = new Tuple<int, int>(i, j);
// var ji = new Tuple<int, int>(j, i);
// if (lognormalCoefficients[i].ContainsKey(jk))
// lognormalCoefficients[i][jk] = esp;
// else
// lognormalCoefficients[i].Add(jk, esp);
// if (lognormalCoefficients[i].ContainsKey(kj))
// lognormalCoefficients[i][kj] = esp;
// else
// lognormalCoefficients[i].Add(kj, esp);
// if (lognormalCoefficients[j].ContainsKey(ik))
// lognormalCoefficients[j][ik] = esp;
// else
// lognormalCoefficients[j].Add(ik, esp);
// if (lognormalCoefficients[j].ContainsKey(ki))
// lognormalCoefficients[j][ki] = esp;
// else
// lognormalCoefficients[j].Add(ki, esp);
// if (lognormalCoefficients[k].ContainsKey(ij))
// lognormalCoefficients[k][ij] = esp;
// else
// lognormalCoefficients[k].Add(ij, esp);
// if (lognormalCoefficients[k].ContainsKey(ji))
// lognormalCoefficients[k][ji] = esp;
// else
// lognormalCoefficients[k].Add(ji, esp);
// }
// }
// }
//}
private void CalculateMeanDiagonalCoefficients()
{
meanDiagonalCoefficients = new double[calculator.PsiSize];
if (isGaussian)
foreach (var c in calculator.GaussianCoefficients[0].Where(x => x.Item1 == x.Item2))
meanDiagonalCoefficients[c.Item1] = c.Item3;
else
foreach (var c in calculator.LognormalCoefficients[0].Where(x => x.Key.Item1 == x.Key.Item2))
meanDiagonalCoefficients[c.Key.Item1] = c.Value;
}
public void Precondition(IVector vIn, IVector vOut)
{
switch (preconditionerKind)
{
case PolynomialChaosSolverPCGPreconditioner.BlockDiagonal:
PreconditionBlock(vIn, vOut);
break;
case PolynomialChaosSolverPCGPreconditioner.BlockSSOR:
PreconditionBlockSSOR(vIn, vOut);
break;
case PolynomialChaosSolverPCGPreconditioner.ILU:
PreconditionILU(vIn, vOut);
break;
case PolynomialChaosSolverPCGPreconditioner.SSOR:
PreconditionSSOR(vIn, vOut);
break;
case PolynomialChaosSolverPCGPreconditioner.Diagonal:
PreconditionDiagonal(vIn, vOut);
break;
}
}
private void PreconditionDiagonal(IVector vIn, IVector vOut)
{
if (analyzer.FactorizedMatrices.Count < 1)
throw new InvalidOperationException("Cannot precondition with no factorized matrices");
if (analyzer.FactorizedMatrices[0].Count != 1)
throw new InvalidOperationException("Cannot precondition with more than one subdomains");
if (tempVectorIn == null)
tempVectorIn = new Vector(meanSize);
if (tempVectorOut == null)
tempVectorOut = new Vector(meanSize);
var v = (Vector)vIn;
var o = (Vector)vOut;
//Array.Copy(v.Data, 0, o.Data, 0, v.Data.Length);
//foreach (ILinearSystem subdomain in solver.SubdomainsDictionary.Values)
//{
SkylineMatrix2D k = (SkylineMatrix2D)analyzer.Matrices[0][solver.LinearSystem.ID];
for (int i = 0; i < calculator.PsiSize; i++)
{
Array.Copy(v.Data, i * meanSize, tempVectorIn.Data, 0, meanSize);
tempVectorIn.Multiply(1.0 / meanDiagonalCoefficients[i]);
for (int j = 0; j < k.Rows; j++)
tempVectorOut[j] = tempVectorIn[j] / k.Data[k.RowIndex[j]];
Array.Copy(tempVectorOut.Data, 0, o.Data, i * meanSize, meanSize);
}
//}
}
private void PreconditionBlock(IVector vIn, IVector vOut)
{
if (analyzer.FactorizedMatrices.Count < 1)
throw new InvalidOperationException("Cannot precondition with no factorized matrices");
if (analyzer.FactorizedMatrices[0].Count != 1)
throw new InvalidOperationException("Cannot precondition with more than one subdomains");
if (tempVectorIn == null)
tempVectorIn = new Vector(meanSize);
if (tempVectorOut == null)
tempVectorOut = new Vector(meanSize);
var v = vIn;
var o = vOut;
//var v = (Vector<double>)vIn;
//var o = (Vector<double>)vOut;
//Array.Copy(v.Data, 0, o.Data, 0, v.Data.Length);
foreach (var m in analyzer.FactorizedMatrices[0].Values)
for (int i = 0; i < calculator.PsiSize; i++)
{
tempVectorIn.CopyFrom(0, meanSize, v, i * meanSize);
//Array.Copy(v.Data, i * meanSize, tempVectorIn.Data, 0, meanSize);
tempVectorIn.Multiply(1.0 / meanDiagonalCoefficients[i]);
m.Solve(tempVectorIn, tempVectorOut);
o.CopyFrom(i * meanSize, meanSize, tempVectorOut, 0);
//Array.Copy(tempVectorOut.Data, 0, o.Data, i * meanSize, meanSize);
}
}
private void PreconditionBlockSSOR(IVector vIn, IVector vOut)
{
if (analyzer.FactorizedMatrices.Count < 1)
throw new InvalidOperationException("Cannot precondition with no factorized matrices");
if (analyzer.FactorizedMatrices[0].Count != 1)
throw new InvalidOperationException("Cannot precondition with more than one subdomains");
//MakeSSORDiagonals();
//for (int i = 0; i < this.VectorSize; i++)
//{
// vOut[i] = vIn[i] * ssorDiagonals[i];
//}
//return;
if (tempVectorIn == null)
tempVectorIn = new Vector(meanSize);
if (tempVectorOut == null)
tempVectorOut = new Vector(meanSize);
//var v = (Vector<double>)vIn;
//var o = (Vector<double>)vOut;
var v = vIn;
var o = vOut;
var oTemp = new Vector(this.VectorSize);
//foreach (ILinearSystem subdomain in solver.SubdomainsDictionary.Values)
//{
// Forward sub
o.CopyFrom(0, v.Length, v, 0);
//Array.Copy(v.Data, 0, o.Data, 0, v.Data.Length);
for (int i = 0; i < coeffLower.Count; i++)
{
int blockStart = i * meanSize;
tempVectorOut.CopyFrom(0, tempVectorOut.Length, v, blockStart);
//Array.Copy(v.Data, blockStart, tempVectorOut.Data, 0, meanSize);
//Array.Clear(tempVectorIn.Data, 0, meanSize);
//Array.Clear(tempVectorOut.Data, 0, meanSize);
foreach (var c in coeffLower[i].Where(x => x.Item2 != x.Item3))
{
SkylineMatrix2D k = (SkylineMatrix2D)analyzer.Matrices[c.Item1][solver.LinearSystem.ID];
int row = c.Item2 * k.Rows;
int col = c.Item3 * k.Rows;
k.Multiply(o, tempVectorOut.Data, -c.Item4, col, 0, false);
}
Array.Clear(tempVectorIn.Data, 0, meanSize);
foreach (var c in coeffLower[i].Where(x => x.Item2 == x.Item3 && x.Item1 == 0))
{
//Array.Copy(v.Data, i * meanSize, tempVectorIn.Data, 0, meanSize);
Array.Copy(tempVectorOut.Data, 0, tempVectorIn.Data, 0, meanSize);
tempVectorIn.Multiply(1.0 / c.Item4);
analyzer.FactorizedMatrices[0][1].Solve(tempVectorIn, tempVectorOut);
o.CopyFrom(0, meanSize, tempVectorOut, i * meanSize);
//Array.Copy(tempVectorOut.Data, 0, o.Data, i * meanSize, meanSize);
// SkylineMatrix2D<double> K = (SkylineMatrix2D<double>)analyzer.Matrices[c.Item1][subdomain.ID];
// double[] d = K.Data as double[];
// for (int n = 0; n < K.Rows; n++)
// {
// int KL = K.RowIndex[n] + 1;
// int KU = K.RowIndex[n + 1] - 1;
// if (KU >= KL)
// {
// int k = n;
// for (int KK = KL; KK <= KU; KK++)
// {
// k--;
// tempVectorIn[n] += c.Item4 * d[KK] * tempVectorOut[k];
// }
// }
// }
}
////for (int n = 0; n < meanSize; n++)
//// o[blockStart + n] -= tempVectorIn[n];
//for (int n = 0; n < meanSize; n++)
// o[blockStart + n] = (o[blockStart + n] - tempVectorIn[n]) * ssorDiagonals[blockStart + n];
}
// Multiply with diagonal
Array.Clear(oTemp.Data, 0, this.VectorSize);
for (int i = 0; i < coeffLower.Count; i++)
{
foreach (var c in coeffLower[i].Where(x => x.Item2 == x.Item3 && x.Item1 == 0))
{
SkylineMatrix2D k = (SkylineMatrix2D)analyzer.Matrices[c.Item1][solver.LinearSystem.ID];
int row = c.Item2 * k.Rows;
int col = c.Item3 * k.Rows;
k.Multiply(o, oTemp.Data, c.Item4, col, row, false);
}
}
// Backward sub
o.CopyFrom(0, v.Length, oTemp, 0);
//Array.Copy(oTemp.Data, 0, o.Data, 0, v.Data.Length);
for (int i = coeffUpper.Count - 1; i >= 0; i--)
{
int blockStart = i * meanSize;
Array.Copy(oTemp.Data, blockStart, tempVectorOut.Data, 0, meanSize);
//Array.Clear(tempVectorOut.Data, 0, meanSize);
foreach (var c in coeffUpper[i].Where(x => x.Item2 != x.Item3))
{
SkylineMatrix2D k = (SkylineMatrix2D)analyzer.Matrices[c.Item1][solver.LinearSystem.ID];
int row = c.Item2 * k.Rows;
int col = c.Item3 * k.Rows;
k.Multiply(o, tempVectorOut.Data, -c.Item4, col, 0, false);
}
foreach (var c in coeffUpper[i].Where(x => x.Item2 == x.Item3 && x.Item1 == 0))
{
//Array.Copy(oTemp.Data, i * meanSize, tempVectorIn.Data, 0, meanSize);
Array.Copy(tempVectorOut.Data, 0, tempVectorIn.Data, 0, meanSize);
tempVectorIn.Multiply(1.0 / c.Item4);
analyzer.FactorizedMatrices[0][1].Solve(tempVectorIn, tempVectorOut);
o.CopyFrom(0, meanSize, tempVectorOut, i * meanSize);
//Array.Copy(tempVectorOut.Data, 0, o.Data, i * meanSize, meanSize);
//SkylineMatrix2D<double> K = (SkylineMatrix2D<double>)analyzer.Matrices[c.Item1][subdomain.ID];
//double[] d = K.Data as double[];
//int n = K.Rows - 1;
//for (int l = 0; l < K.Rows; l++)
//{
// int KL = K.RowIndex[n] + 1;
// int KU = K.RowIndex[n + 1] - 1;
// if (KU >= KL)
// {
// int k = n;
// for (int KK = KL; KK <= KU; KK++)
// {
// k--;
// tempVectorOut[k] += c.Item4 * d[KK] * tempVectorOut[n];
// //result[k] -= d[KK] * result[n];
// }
// }
// n--;
//}
}
//for (int n = 0; n < meanSize; n++)
// o[blockStart + n] -= tempVectorOut[n];
}
//// Division
//for (int i = 0; i < this.VectorSize; i++)
// o.Data[i] *= ssorDiagonals[i];
//}
}
private void PreconditionSSOR(IVector vIn, IVector vOut)
{
if (analyzer.FactorizedMatrices.Count < 1)
throw new InvalidOperationException("Cannot precondition with no factorized matrices");
if (analyzer.FactorizedMatrices[0].Count != 1)
throw new InvalidOperationException("Cannot precondition with more than one subdomains");
MakeSSORDiagonals();
//for (int i = 0; i < this.VectorSize; i++)
//{
// vOut[i] = vIn[i] * ssorDiagonals[i];
//}
//return;
if (tempVectorIn == null)
tempVectorIn = new Vector(meanSize);
if (tempVectorOut == null)
tempVectorOut = new Vector(meanSize);
var v = (Vector)vIn;
var o = (Vector)vOut;
var oTemp = new Vector(this.VectorSize);
//foreach (ILinearSystem subdomain in solver.SubdomainsDictionary.Values)
//{
// Forward sub
Array.Copy(v.Data, 0, o.Data, 0, v.Data.Length);
for (int i = 0; i < coeffLower.Count; i++)
{
int blockStart = i * meanSize;
Array.Copy(v.Data, blockStart, tempVectorOut.Data, 0, meanSize);
//Array.Clear(tempVectorIn.Data, 0, meanSize);
//Array.Clear(tempVectorOut.Data, 0, meanSize);
foreach (var c in coeffLower[i].Where(x => x.Item2 != x.Item3))
{
SkylineMatrix2D k = (SkylineMatrix2D)analyzer.Matrices[c.Item1][solver.LinearSystem.ID];
int row = c.Item2 * k.Rows;
int col = c.Item3 * k.Rows;
k.Multiply(o, tempVectorOut.Data, -c.Item4, col, 0, false);
}
Array.Clear(tempVectorIn.Data, 0, meanSize);
foreach (var c in coeffLower[i].Where(x => x.Item2 == x.Item3 && x.Item1 == 0))
{
////Array.Copy(v.Data, i * meanSize, tempVectorIn.Data, 0, meanSize);
//Array.Copy(tempVectorOut.Data, 0, tempVectorIn.Data, 0, meanSize);
//tempVectorIn.Multiply(1.0 / c.Item4);
//analyzer.FactorizedMatrices[0][1].Solve(tempVectorIn, tempVectorOut.Data);
//Array.Copy(tempVectorOut.Data, 0, o.Data, i * meanSize, meanSize);
//double coefficientInverse = 1.0 / c.Item4;
//Array.Copy(tempVectorOut.Data, 0, tempVectorIn.Data, 0, meanSize);
//tempVectorIn.Multiply(1.0 / c.Item4);
tempVectorOut.Multiply(1.0 / c.Item4);
SkylineMatrix2D K = (SkylineMatrix2D)analyzer.Matrices[c.Item1][solver.LinearSystem.ID];
double[] d = K.Data as double[];
for (int n = 0; n < K.Rows; n++)
{
int KL = K.RowIndex[n] + 1;
int KU = K.RowIndex[n + 1] - 1;
if (KU >= KL)
{
int k = n;
double C = 0;
for (int KK = KL; KK <= KU; KK++)
{
k--;
C += d[KK] * tempVectorOut[k]; // c.Item4
//tempVectorIn[n] += c.Item4 * d[KK] * tempVectorOut[k];
}
tempVectorOut[n] -= C;
}
tempVectorOut[n] /= d[KL - 1];
}
Array.Copy(tempVectorOut.Data, 0, o.Data, i * meanSize, meanSize);
}
////for (int n = 0; n < meanSize; n++)
//// o[blockStart + n] -= tempVectorIn[n];
//for (int n = 0; n < meanSize; n++)
// o[blockStart + n] = (o[blockStart + n] - tempVectorIn[n]) * ssorDiagonals[blockStart + n];
}
// Multiply with diagonal
for (int i = 0; i < v.Data.Length; i++)
oTemp.Data[i] = o.Data[i] * ssorDiagonals[i];
//Array.Copy(o.Data, 0, oTemp.Data, 0, v.Data.Length);
//Array.Clear(oTemp.Data, 0, this.VectorSize);
//for (int i = 0; i < coeffLower.Count; i++)
//{
// //foreach (var c in coeffLower[i].Where(x => x.Item2 == x.Item3 && x.Item1 == 0))
// //{
// // SkylineMatrix2D<double> k = (SkylineMatrix2D<double>)analyzer.Matrices[c.Item1][subdomain.ID];
// // int row = c.Item2 * k.Rows;
// // int col = c.Item3 * k.Rows;
// // k.Multiply(o, oTemp.Data, c.Item4, col, row, false);
// //}
// foreach (var c in coeffLower[i].Where(x => x.Item2 == x.Item3 && x.Item1 == 0))
// {
// SkylineMatrix2D<double> k = (SkylineMatrix2D<double>)analyzer.Matrices[c.Item1][subdomain.ID];
// int row = c.Item2 * k.Rows;
// int col = c.Item3 * k.Rows;
// for (int cnt = 0; cnt < k.RowIndex.Length - 1; cnt++)
// {
// oTemp.Data[row + cnt] = c.Item4 * o.Data[col + cnt] * k.Data[k.RowIndex[cnt]];
// //k.Multiply(o, oTemp.Data, c.Item4, col, row, false);
// }
// }
//}
// Backward sub
Array.Copy(oTemp.Data, 0, o.Data, 0, v.Data.Length);
for (int i = coeffUpper.Count - 1; i >= 0; i--)
{
int blockStart = i * meanSize;
Array.Copy(oTemp.Data, blockStart, tempVectorOut.Data, 0, meanSize);
//Array.Clear(tempVectorOut.Data, 0, meanSize);
foreach (var c in coeffUpper[i].Where(x => x.Item2 != x.Item3))
{
SkylineMatrix2D k = (SkylineMatrix2D)analyzer.Matrices[c.Item1][solver.LinearSystem.ID];
int row = c.Item2 * k.Rows;
int col = c.Item3 * k.Rows;
k.Multiply(o, tempVectorOut.Data, -c.Item4, col, 0, false);
}
foreach (var c in coeffUpper[i].Where(x => x.Item2 == x.Item3 && x.Item1 == 0))
{
////Array.Copy(oTemp.Data, i * meanSize, tempVectorIn.Data, 0, meanSize);
//Array.Copy(tempVectorOut.Data, 0, tempVectorIn.Data, 0, meanSize);
//tempVectorIn.Multiply(1.0 / c.Item4);
//analyzer.FactorizedMatrices[0][1].Solve(tempVectorIn, tempVectorOut.Data);
//Array.Copy(tempVectorOut.Data, 0, o.Data, i * meanSize, meanSize);
//Array.Copy(tempVectorOut.Data, 0, tempVectorIn.Data, 0, meanSize);
//tempVectorIn.Multiply(1.0 / c.Item4);
tempVectorOut.Multiply(1.0 / c.Item4);
SkylineMatrix2D K = (SkylineMatrix2D)analyzer.Matrices[c.Item1][solver.LinearSystem.ID];
//double[] d = K.Data as double[];
//for (int n = K.Rows - 1; n >= 0; n--)
//{
// int KL = K.RowIndex[n] + 1;
// int KU = K.RowIndex[n + 1] - 1;
// if (KU >= KL)
// {
// int k = n;
// double C = 0;
// for (int KK = KL; KK <= KU; KK++)
// {
// k--;
// C += d[KK] * tempVectorOut[k]; // c.Item4
// //tempVectorIn[n] += c.Item4 * d[KK] * tempVectorOut[k];
// }
// tempVectorOut[n] -= C;
// }
// tempVectorOut[n] /= d[KL - 1];
//}
double[] d = K.Data as double[];
int n = K.Rows - 1;
for (int l = 0; l < K.Rows; l++)
{
int KL = K.RowIndex[n] + 1;
int KU = K.RowIndex[n + 1] - 1;
tempVectorOut[n] /= d[KL - 1];
if (KU >= KL)
{
int k = n;
for (int KK = KL; KK <= KU; KK++)
{
k--;
tempVectorOut[k] -= d[KK] * tempVectorOut[n];
//result[k] -= d[KK] * result[n];
}
}
n--;
}
Array.Copy(tempVectorOut.Data, 0, o.Data, i * meanSize, meanSize);
}
//for (int n = 0; n < meanSize; n++)
// o[blockStart + n] -= tempVectorOut[n];
}
//// Division
//for (int i = 0; i < this.VectorSize; i++)
// o.Data[i] *= ssorDiagonals[i];
//}
}
private void PreconditionILU(IVector vIn, IVector vOut)
{
if (analyzer.FactorizedMatrices.Count < 1)
throw new InvalidOperationException("Cannot precondition with no factorized matrices");
if (analyzer.FactorizedMatrices[0].Count != 1)
throw new InvalidOperationException("Cannot precondition with more than one subdomains");
//MakeSSORDiagonals();
//for (int i = 0; i < this.VectorSize; i++)
//{
// vOut[i] = vIn[i] * ssorDiagonals[i];
//}
//return;
if (tempVectorIn == null)
tempVectorIn = new Vector(meanSize);
if (tempVectorOut == null)
tempVectorOut = new Vector(meanSize);
var v = (Vector)vIn;
var o = (Vector)vOut;
var oTemp = new Vector(this.VectorSize);
var tOut = new Vector(meanSize);
//foreach (ILinearSystem subdomain in solver.SubdomainsDictionary.Values)
//{
// Forward sub
Array.Copy(v.Data, 0, o.Data, 0, v.Data.Length);
for (int i = 0; i < coeffLower.Count; i++)
{
int blockStart = i * meanSize;
Array.Copy(v.Data, blockStart, tempVectorOut.Data, 0, meanSize);
//Array.Clear(tempVectorIn.Data, 0, meanSize);
//Array.Clear(tempVectorOut.Data, 0, meanSize);
foreach (var c in coeffLower[i].Where(x => x.Item2 != x.Item3))
{
SkylineMatrix2D k = analyzer.FactorizedMatrices[c.Item1][solver.LinearSystem.ID];
int row = c.Item2 * k.Rows;
int col = c.Item3 * k.Rows;
//Array.Copy(o.Data, col, tempVectorIn.Data, 0, meanSize);
//tempVectorIn.Multiply(1.0 / -c.Item4);
//k.Solve(tempVectorIn, tOut.Data);
//for (int p = 0; p < meanSize; p++)
// tempVectorOut[p] += tOut[p];
//int row = c.Item2 * k.Rows;
//int col = c.Item3 * k.Rows;
k.Multiply(o, tempVectorOut.Data, -c.Item4, col, 0, false);
}
Array.Clear(tempVectorIn.Data, 0, meanSize);
foreach (var c in coeffLower[i].Where(x => x.Item2 == x.Item3 && x.Item1 == 0))
{
//Array.Copy(v.Data, i * meanSize, tempVectorIn.Data, 0, meanSize);
Array.Copy(tempVectorOut.Data, 0, tempVectorIn.Data, 0, meanSize);
tempVectorIn.Multiply(1.0 / c.Item4);
analyzer.FactorizedMatrices[0][1].Solve(tempVectorIn, tempVectorOut);
Array.Copy(tempVectorOut.Data, 0, o.Data, i * meanSize, meanSize);
// SkylineMatrix2D<double> K = (SkylineMatrix2D<double>)analyzer.Matrices[c.Item1][subdomain.ID];
// double[] d = K.Data as double[];
// for (int n = 0; n < K.Rows; n++)
// {
// int KL = K.RowIndex[n] + 1;
// int KU = K.RowIndex[n + 1] - 1;
// if (KU >= KL)
// {
// int k = n;
// for (int KK = KL; KK <= KU; KK++)
// {
// k--;
// tempVectorIn[n] += c.Item4 * d[KK] * tempVectorOut[k];
// }
// }
// }
}
////for (int n = 0; n < meanSize; n++)
//// o[blockStart + n] -= tempVectorIn[n];
//for (int n = 0; n < meanSize; n++)
// o[blockStart + n] = (o[blockStart + n] - tempVectorIn[n]) * ssorDiagonals[blockStart + n];
}
// Multiply with diagonal
Array.Clear(oTemp.Data, 0, this.VectorSize);
for (int i = 0; i < coeffLower.Count; i++)
{
foreach (var c in coeffLower[i].Where(x => x.Item2 == x.Item3 && x.Item1 == 0))
{
SkylineMatrix2D k = (SkylineMatrix2D)analyzer.Matrices[c.Item1][solver.LinearSystem.ID];
int row = c.Item2 * k.Rows;
int col = c.Item3 * k.Rows;
k.Multiply(o, oTemp.Data, c.Item4, col, row, false);
}
}
// Backward sub
Array.Copy(oTemp.Data, 0, o.Data, 0, v.Data.Length);
for (int i = coeffUpper.Count - 1; i >= 0; i--)
{
int blockStart = i * meanSize;
Array.Copy(oTemp.Data, blockStart, tempVectorOut.Data, 0, meanSize);
//Array.Clear(tempVectorOut.Data, 0, meanSize);
foreach (var c in coeffUpper[i].Where(x => x.Item2 != x.Item3))
{
SkylineMatrix2D k = (SkylineMatrix2D)analyzer.FactorizedMatrices[c.Item1][solver.LinearSystem.ID];
int row = c.Item2 * k.Rows;
int col = c.Item3 * k.Rows;
k.Multiply(o, tempVectorOut.Data, -c.Item4, col, 0, false);
//SkylineMatrix2D<double> k = analyzer.FactorizedMatrices[c.Item1][subdomain.ID];
//int row = c.Item2 * k.Rows;
//int col = c.Item3 * k.Rows;
//Array.Copy(o.Data, col, tempVectorIn.Data, 0, meanSize);
//tempVectorIn.Multiply(1.0 / -c.Item4);
//k.Solve(tempVectorIn, tOut.Data);
//for (int p = 0; p < meanSize; p++)
// tempVectorOut[p] += tOut[p];
}
foreach (var c in coeffUpper[i].Where(x => x.Item2 == x.Item3 && x.Item1 == 0))
{
//Array.Copy(oTemp.Data, i * meanSize, tempVectorIn.Data, 0, meanSize);
Array.Copy(tempVectorOut.Data, 0, tempVectorIn.Data, 0, meanSize);
tempVectorIn.Multiply(1.0 / c.Item4);
analyzer.FactorizedMatrices[0][1].Solve(tempVectorIn, tempVectorOut);
Array.Copy(tempVectorOut.Data, 0, o.Data, i * meanSize, meanSize);
//SkylineMatrix2D<double> K = (SkylineMatrix2D<double>)analyzer.Matrices[c.Item1][subdomain.ID];
//double[] d = K.Data as double[];
//int n = K.Rows - 1;
//for (int l = 0; l < K.Rows; l++)
//{
// int KL = K.RowIndex[n] + 1;
// int KU = K.RowIndex[n + 1] - 1;
// if (KU >= KL)
// {
// int k = n;
// for (int KK = KL; KK <= KU; KK++)
// {
// k--;
// tempVectorOut[k] += c.Item4 * d[KK] * tempVectorOut[n];
// //result[k] -= d[KK] * result[n];
// }
// }
// n--;
//}
}
//for (int n = 0; n < meanSize; n++)
// o[blockStart + n] -= tempVectorOut[n];
}
//// Division
//for (int i = 0; i < this.VectorSize; i++)
// o.Data[i] *= ssorDiagonals[i];
//}
}
//private void PreconditionILU(IVector<double> vIn, IVector<double> vOut)
//{
// if (analyzer.FactorizedMatrices.Count < 1)
// throw new InvalidOperationException("Cannot precondition with no factorized matrices");
// if (analyzer.FactorizedMatrices[0].Count != 1)
// throw new InvalidOperationException("Cannot precondition with more than one subdomains");
// if (tempVectorIn == null)
// tempVectorIn = new Vector<double>(meanSize);
// if (tempVectorOut == null)
// tempVectorOut = new Vector<double>(meanSize);
// var v = (Vector<double>)vIn;
// var o = (Vector<double>)vOut;
// Array.Clear(o.Data, 0, o.Length);
// for (int pos = 0; pos < (isGaussian ? mOrder + 1 : calculator.PsiSize); pos++)
// {
// var m = analyzer.FactorizedMatrices[pos][1];
// if (isGaussian)
// foreach (var x in calculator.GaussianCoefficients[pos])
// {
// int i = x.Item1;
// int j = x.Item2;
// Array.Copy(v.Data, j * meanSize, tempVectorIn.Data, 0, meanSize);
// tempVectorIn.Multiply(1.0 / x.Item3);
// m.Solve(tempVectorIn, tempVectorOut.Data);
// for (int p = 0; p < meanSize; p++)
// o.Data[i * meanSize + p] += tempVectorOut.Data[p];
// }
// else
// foreach (var x in calculator.LognormalCoefficients[pos])
// {
// int i = x.Key.Item1;
// int j = x.Key.Item2;
// Array.Copy(v.Data, j * meanSize, tempVectorIn.Data, 0, meanSize);
// tempVectorIn.Multiply(1.0 / x.Value);
// m.Solve(tempVectorIn, tempVectorOut.Data);
// for (int p = 0; p < meanSize; p++)
// o.Data[i * meanSize + p] += tempVectorOut.Data[p];
// }
// }
//}
public void MultiplyWithMatrix(IVector vIn, IVector vOut)
{
var data = ((Vector)vOut).Data;
Array.Clear(data, 0, data.Length);
//foreach (ILinearSystem subdomain in solver.SubdomainsDictionary.Values)
//{
for (int pos = 0; pos < (isGaussian ? mOrder + 1 : calculator.PsiSize); pos++)
{
//SkylineMatrix2D<double> k = ((SkylineMatrix2D<double>)subdomain.Matrix);
SkylineMatrix2D k = (SkylineMatrix2D)analyzer.Matrices[pos][solver.LinearSystem.ID];
if (isGaussian)
foreach (var x in calculator.GaussianCoefficients[pos])
{
int i = x.Item1 * k.Rows;
int j = x.Item2 * k.Rows;
k.Multiply(vIn, data, x.Item3, j, i, false);
}
else
foreach (var x in calculator.LognormalCoefficients[pos])
{
int i = x.Key.Item1 * k.Rows;
int j = x.Key.Item2 * k.Rows;
k.Multiply(vIn, data, x.Value, j, i, false);
}
}
//}
}
}
}
| 46.699819 | 148 | 0.4212 | [
"Apache-2.0"
] | SerafeimBakalakos/MSolve | ISAAR.MSolve.Analyzers/PolynomialChaosSolverPCGMatrixCalculator.cs | 51,652 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class baozha : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
//GameObject.Find("baozha").GetComponent<ParticleSystem>().Stop();
GameObject.FindGameObjectWithTag("baozha").GetComponent<ParticleSystem>().Stop();
}
// Update is called once per frame
void Update()
{
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.CompareTag("birdboss"))
{
//GameObject.Find("baozha").GetComponent<ParticleSystem>().Play();
GameObject.FindGameObjectWithTag("baozha").GetComponent<ParticleSystem>().Play();
}
}
}
| 25.032258 | 93 | 0.643041 | [
"MIT"
] | SSTeeo/Development-of-game07 | BlackCat/Assets/Scripts/taoyucheng/baozha.cs | 778 | C# |
using MasterServerToolkit.Networking;
using System;
using System.Collections.Generic;
namespace MasterServerToolkit.MasterServer
{
public interface ILobby
{
int Id { get; }
string Type { get; set; }
string GameIp { get; }
int GamePort { get; }
int MaxPlayers { get; }
int PlayerCount { get; }
string Name { get; set; }
List<LobbyMember> Members { get; }
event Action<ILobby> OnDestroyedEvent;
MstProperties GetPublicProperties(IPeer peer);
bool AddPlayer(LobbyUserPeerExtension playerExt, out string error);
void RemovePlayer(LobbyUserPeerExtension playerExt);
bool SetProperty(LobbyUserPeerExtension setter, string key, string value);
bool SetProperty(string key, string value);
LobbyMember GetMemberByExtension(LobbyUserPeerExtension playerExt);
LobbyMember GetMemberByUsername(string username);
LobbyMember GetMemberByPeerId(int peerId);
void SetReadyState(LobbyMember member, bool state);
bool SetPlayerProperty(LobbyMember player, string key, string value);
bool TryJoinTeam(string teamName, LobbyMember player);
LobbyDataPacket GenerateLobbyData(LobbyUserPeerExtension user);
LobbyDataPacket GenerateLobbyData();
bool StartGameManually(LobbyUserPeerExtension user);
void ChatMessageHandler(LobbyMember member, IIncomingMessage message);
void GameAccessRequestHandler(IIncomingMessage message);
}
} | 34.681818 | 82 | 0.707077 | [
"MIT"
] | rafaeldolfe/MasterServerChess | Assets/MasterServerToolkit/MasterServer/Scripts/Modules/Lobbies/ILobby.cs | 1,528 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.