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 NBitcoin;
using WalletWasabi.Crypto;
using WalletWasabi.Crypto.Randomness;
using WalletWasabi.WabiSabi.Backend.Rounds;
using WalletWasabi.WabiSabi.Crypto;
using WalletWasabi.WabiSabi.Models.MultipartyTransaction;
namespace WalletWasabi.WabiSabi.Models;
public record RoundState(uint256 Id,
uint256 BlameOf,
CredentialIssuerParameters AmountCredentialIssuerParameters,
CredentialIssuerParameters VsizeCredentialIssuerParameters,
Phase Phase,
EndRoundState EndRoundState,
DateTimeOffset InputRegistrationStart,
TimeSpan InputRegistrationTimeout,
MultipartyTransactionState CoinjoinState)
{
public DateTimeOffset InputRegistrationEnd => InputRegistrationStart + InputRegistrationTimeout;
public static RoundState FromRound(Round round, int stateId = 0) =>
new(
round.Id,
round is BlameRound blameRound ? blameRound.BlameOf.Id : uint256.Zero,
round.AmountCredentialIssuerParameters,
round.VsizeCredentialIssuerParameters,
round.Phase,
round.EndRoundState,
round.InputRegistrationTimeFrame.StartTime,
round.InputRegistrationTimeFrame.Duration,
round.CoinjoinState.GetStateFrom(stateId)
);
public RoundState GetSubState(int skipFromBaseState) =>
new(
Id,
BlameOf,
AmountCredentialIssuerParameters,
VsizeCredentialIssuerParameters,
Phase,
EndRoundState,
InputRegistrationStart,
InputRegistrationTimeout,
CoinjoinState.GetStateFrom(skipFromBaseState)
);
public TState Assert<TState>() where TState : MultipartyTransactionState =>
CoinjoinState switch
{
TState s => s,
_ => throw new InvalidOperationException($"{typeof(TState).Name} state was expected but {CoinjoinState.GetType().Name} state was received.")
};
public WabiSabiClient CreateAmountCredentialClient(WasabiRandom random) =>
new(AmountCredentialIssuerParameters, random, CoinjoinState.Parameters.MaxAmountCredentialValue);
public WabiSabiClient CreateVsizeCredentialClient(WasabiRandom random) =>
new(VsizeCredentialIssuerParameters, random, CoinjoinState.Parameters.MaxVsizeCredentialValue);
}
| 33.704918 | 143 | 0.817121 | [
"MIT"
] | CAnorbo/WalletWasabi | WalletWasabi/WabiSabi/Models/RoundState.cs | 2,056 | C# |
using APIServer.Aplication.Commands.WebHooks;
using HotChocolate.Types;
namespace APIServer.Aplication.GraphQL.Types
{
public class UpdateWebHookActivStatePayloadType : ObjectType<UpdateWebHookActivStatePayload>
{
protected override void Configure(IObjectTypeDescriptor<UpdateWebHookActivStatePayload> descriptor)
{
descriptor.Field(e => e.hook).Type<WebHookType>();
}
}
public class UpdateWebHookActivStateErrorUnion : UnionType<IUpdateWebHookActivStateError>
{
protected override void Configure(IUnionTypeDescriptor descriptor)
{
descriptor.Type<ValidationErrorType>();
descriptor.Type<UnAuthorisedType>();
descriptor.Type<InternalServerErrorType>();
descriptor.Type<WebHookNotFoundType>();
}
}
} | 31.916667 | 103 | 0.76893 | [
"MIT"
] | shockzinfinity/trouble-training | Src/APIServer/Aplication/Graphql/Types/MutationTypes/WebHooks/UpdateProjectWebHookActivStateMuattionTypes.cs | 766 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using Excel = Microsoft.Office.Interop.Excel;
using Office = Microsoft.Office.Core;
using Microsoft.Office.Tools.Excel;
using System.Windows.Forms;
namespace ExcelCamAddIn
{
public partial class ThisAddIn
{
public WebCam webcam;
WinFormsCameraControl winformControl;
Microsoft.Office.Tools.CustomTaskPane pane;
System.Windows.Forms.Integration.ElementHost myHost;
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
try
{
webcam = new WebCam();
winformControl = new WinFormsCameraControl();
pane = CustomTaskPanes.Add(winformControl, "CameraControl");
//pane.Visible = false;
pane.Visible = true;
pane.DockPosition = Office.MsoCTPDockPosition.msoCTPDockPositionRight;
pane.VisibleChanged += pane_VisibleChanged;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
void pane_VisibleChanged(object sender, EventArgs e)
{
try
{
webcam.Stop();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
{
}
#region VSTO generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InternalStartup()
{
this.Startup += new System.EventHandler(ThisAddIn_Startup);
this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
}
#endregion
}
}
| 26.689189 | 86 | 0.574177 | [
"MIT"
] | nemanja-popovic/ExcelAddInWithCamera | ExcelCamAddIn/ThisAddIn.cs | 1,977 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlockchainCS
{
public enum BlockchainMode
{
MainNet = 0x77,
TestNet = 0x00
}
public class Blockchain
{
public static int Difficulty = 1;
public static string Problem = "effa0";
public static int BlockHeight = 0;
public static BlockchainMode BlockchainMode = BlockchainMode.TestNet;
public List<Block> chain = new List<Block>();
private Queue<Transaction> PendingTransactions = new Queue<Transaction>();
public static long TimeStarted = GetTimestamp();
public static long GetTimestamp()
{
DateTimeOffset now = DateTimeOffset.UtcNow;
return now.ToUnixTimeMilliseconds();
}
public static Block CreateHeadBlock()
{
Block block = new Block();
block.block = 0;
block.Timestamp = Block.GetTimestamp(DateTime.Parse("24/08/2021"));
block.PreviousHash = string.Empty;
block.Validator = "ATOMIC-chain-head";
block.Hash = block.ComputeHash();
return block;
}
public Block GetLatestBlock()
{
return chain.Last();
//return this.chain[this.chain.Count() - 1];
}
public void VerifyPendingTransactions(string validatorAddress)
{
Block block = new Block();
block.block = ++BlockHeight;
block.PreviousHash = this.GetLatestBlock().Hash;
if (block.block > 0)
{
block.Timestamp = Block.GetTimestamp();
}
else
{
block.Timestamp = this.GetLatestBlock().Timestamp;
}
block.Transactions = new List<Transaction>(this.PendingTransactions);
block.Validator = validatorAddress;
for (int i=0;i< block.Transactions.Count();i++)
{
var txn = block.Transactions[i];
txn.BlockID = block.block;
}
block.Hash = block.ComputeHash();
block.VerifyBlock(Difficulty, Problem);
if(block.VerifyProblem(Difficulty, Problem))
{
// Block sucessfully mined.
// TODO: verify that hash meets problem requirements before adding to blockchain.
PendingTransactions.Clear();
// Add to the blockchain:
this.chain.Add(block);
// Save block to file system.
block.SaveToFilesystem();
// TODO: Notify or broadcast new block to other connected clients
}
}
public void AddTransaction(Transaction transaction)
{
if (string.IsNullOrEmpty(transaction.FromAddress) || string.IsNullOrEmpty(transaction.ToAddress))
{
throw new Exception("Transaction must include from and to address");
}
// Verify the transactiion
if (!transaction.IsValid())
{
throw new Exception("Cannot add invalid transaction to chain");
}
if (string.IsNullOrEmpty(transaction.Key))
{
throw new Exception("Transaction key should be specified");
}
if (string.IsNullOrEmpty(transaction.Value))
{
throw new Exception("Transaction value should be specified");
}
// TODO: Check that size of value is not greater than the max storage size
this.PendingTransactions.Enqueue(transaction);
Console.WriteLine("Transaction added. " + transaction.ToString());
}
public string GetValue(string profileAddress, string key)
{
string value = string.Empty;
// TODO: Optimise using a database since chain can have a really large N*M.
for(int i=0; i< this.chain.Count();i++)
{
Block block = this.chain[i];
for(int j=0; j < block.Transactions.Count(); j++)
{
Transaction transaction = block.Transactions[j];
if (transaction.FromAddress == profileAddress && transaction.Key == key)
{
// Take data away from profile holder.
// Nullify key and value in profile.
value = string.Empty;
}
if (transaction.ToAddress == profileAddress && transaction.Key == key)
{
// Give data to profile holder:
value = transaction.Value;
}
}
}
return value;
}
public List<Block> GetLatestBlocks(string blockId)
{
List<Block> blocks;
int blocki = -1;
try
{
int.TryParse(blockId, out blocki);
}
catch(Exception ex)
{
}
if(string.IsNullOrEmpty(blockId))
{
blocks = this.chain.OrderByDescending(item => item.block).Take(100).ToList();
}
else
{
blocks = this.chain.Where(item=> item.block == blocki).OrderByDescending(item => item.block).Take(100).ToList();
}
return blocks;
}
public List<Transaction> GetAllTransactionsForProfile(string profileAddress)
{
List<Transaction> transactions = new List<Transaction>();
// TODO: Optimise using a database since chain can have a really large N*M.
for (int i = 0; i < this.chain.Count(); i++)
{
Block block = this.chain[i];
for (int j = 0; j < block.Transactions.Count(); j++)
{
Transaction transaction = block.Transactions[j];
if (transaction.FromAddress == profileAddress || transaction.ToAddress == profileAddress)
{
transactions.Add(transaction);
}
}
}
Console.WriteLine("Get transactions for profile count: " + transactions.Count());
return transactions;
}
public Block GetBlockById(string blockId)
{
Block block;
block = this.chain.Where(item => item.block.ToString() == blockId).Take(1).FirstOrDefault();
return block;
}
public Transaction GetTransactionById(string txId)
{
Transaction txn = null;
// TODO: Optimise using a database since chain can have a really large N*M.
bool found = false;
for (int i = 0; i < this.chain.Count() && !found; i++)
{
Block block = this.chain[i];
for (int j = 0; j < block.Transactions.Count() && !found; j++)
{
Transaction transaction = block.Transactions[j];
if(transaction.Signature == txId)
{
found = true;
txn = transaction;
}
}
}
return txn;
}
public bool IsChainValid()
{
// TODO: Optimise by replacing with hash code comparision
string realGenesis = CreateHeadBlock().ToHashableString();
string chainGenesis = this.chain.First().ToHashableString();
if (realGenesis != chainGenesis)
{
Console.WriteLine("Chain head does not match local head");
return false;
}
for (int i = 1; i < this.chain.Count(); i++)
{
Block currentBlock = this.chain[i];
Block previousBlock = this.chain[i - 1];
if (previousBlock.Hash != currentBlock.PreviousHash)
{
return false;
}
if (!currentBlock.ValidateTransactions())
{
return false;
}
if (currentBlock.Hash != currentBlock.ComputeHash())
{
return false;
}
}
return true;
}
public void LoadFromFilesystem()
{
string chainDir = "chain";
BlockchainInfo info = BlockchainInfo.GetInfo();
for(int blockId=0; blockId <= info.BlockHeight; blockId++)
{
string fileName = chainDir + "\\block_" + blockId.ToString() + ".dat";
if(File.Exists(fileName))
{
string blockJSON = File.ReadAllText(fileName);
Block block = JSON.FromJSON<Block>(blockJSON);
this.chain.Add(block);
}
else
{
// TODO: Sync block from p2p nodes
}
}
}
}
}
| 29.661392 | 128 | 0.495786 | [
"BSD-3-Clause"
] | JelloJellyton/V2AN | BlockchainCS/Blockchain.cs | 9,375 | C# |
using LogJoint.Postprocessing;
using System.Linq;
namespace LogJoint.Chromium.ChromeDriver
{
}
| 13.857143 | 40 | 0.814433 | [
"MIT"
] | rkapl123/logjoint | trunk/extensions/chromium/model/Formats/Chromedriver/Reader/Extensions.cs | 99 | C# |
/*
This file is part of pspsharp.
pspsharp is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
pspsharp is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with pspsharp. If not, see <http://www.gnu.org/licenses/>.
*/
namespace pspsharp.HLE.kernel.types
{
public interface IWaitStateChecker
{
/// <summary>
/// Checks if a thread has to return to its wait state after the execution
/// of a callback.
/// </summary>
/// <param name="thread"> the thread </param>
/// <param name="wait"> the wait state that has to be checked </param>
/// <returns> true if the thread has to return to the wait state
/// false if the thread has not to return to the wait state but
/// continue in the READY state. In that case, the return values have
/// to be set in the CpuState of the thread (at least $v0). </returns>
bool continueWaitState(SceKernelThreadInfo thread, ThreadWaitInfo wait);
}
} | 40.5 | 86 | 0.711692 | [
"MIT"
] | xXxTheDarkprogramerxXx/PSPSHARP | PSP_EMU/HLE/kernel/types/IWaitStateChecker.cs | 1,379 | C# |
// Copyright 2008-2011. This work is licensed under the BSD license, available at
// http://www.movesinstitute.org/licenses
//
// Orignal authors: DMcG, Jason Nelson
// Modified for use with C#:
// - Peter Smith (Naval Air Warfare Center - Training Systems Division)
// - Zvonko Bostjancic (Blubit d.o.o. - zvonko.bostjancic@blubit.si)
using System;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
namespace OpenDis.Enumerations.Entity.Information.Minefield
{
/// <summary>
/// Enumeration values for Fusing (entity.mine.fusing, Fusing,
/// section 10.3.3)
/// The enumeration values are generated from the SISO DIS XML EBV document (R35), which was
/// obtained from http://discussions.sisostds.org/default.asp?action=10&fd=31
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Serializable]
public struct Fusing
{
/// <summary>
/// Identifies the type of the primary fuse
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Identifies the type of the primary fuse")]
public enum PrimaryValue : uint
{
/// <summary>
/// No Fuse
/// </summary>
NoFuse = 0,
/// <summary>
/// Other
/// </summary>
Other = 1,
/// <summary>
/// Pressure
/// </summary>
Pressure = 2,
/// <summary>
/// Magnetic
/// </summary>
Magnetic = 3,
/// <summary>
/// Tilt Rod
/// </summary>
TiltRod = 4,
/// <summary>
/// Command
/// </summary>
Command = 5,
/// <summary>
/// Trip Wire
/// </summary>
TripWire = 6
}
/// <summary>
/// Identifies the type of the secondary fuse
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Identifies the type of the secondary fuse")]
public enum SecondaryValue : uint
{
/// <summary>
/// No Fuse
/// </summary>
NoFuse = 0,
/// <summary>
/// Other
/// </summary>
Other = 1,
/// <summary>
/// Pressure
/// </summary>
Pressure = 2,
/// <summary>
/// Magnetic
/// </summary>
Magnetic = 3,
/// <summary>
/// Tilt Rod
/// </summary>
TiltRod = 4,
/// <summary>
/// Command
/// </summary>
Command = 5,
/// <summary>
/// Trip Wire
/// </summary>
TripWire = 6
}
/// <summary>
/// Describes the anti-handling device status of the mine
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Describes the anti-handling device status of the mine")]
public enum AHDValue : uint
{
/// <summary>
/// No anti-handling device
/// </summary>
NoAntiHandlingDevice = 0,
/// <summary>
/// Anti-handling device
/// </summary>
AntiHandlingDevice = 1
}
private Fusing.PrimaryValue primary;
private Fusing.SecondaryValue secondary;
private Fusing.AHDValue aHD;
/// <summary>
/// Implements the operator !=.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if operands are not equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator !=(Fusing left, Fusing right)
{
return !(left == right);
}
/// <summary>
/// Implements the operator ==.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if operands are not equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator ==(Fusing left, Fusing right)
{
if (object.ReferenceEquals(left, right))
{
return true;
}
// If parameters are null return false (cast to object to prevent recursive loop!)
if (((object)left == null) || ((object)right == null))
{
return false;
}
return left.Equals(right);
}
/// <summary>
/// Performs an explicit conversion from <see cref="OpenDis.Enumerations.Entity.Information.Minefield.Fusing"/> to <see cref="System.UInt16"/>.
/// </summary>
/// <param name="obj">The <see cref="OpenDis.Enumerations.Entity.Information.Minefield.Fusing"/> scheme instance.</param>
/// <returns>The result of the conversion.</returns>
public static explicit operator ushort(Fusing obj)
{
return obj.ToUInt16();
}
/// <summary>
/// Performs an explicit conversion from <see cref="System.UInt16"/> to <see cref="OpenDis.Enumerations.Entity.Information.Minefield.Fusing"/>.
/// </summary>
/// <param name="value">The ushort value.</param>
/// <returns>The result of the conversion.</returns>
public static explicit operator Fusing(ushort value)
{
return Fusing.FromUInt16(value);
}
/// <summary>
/// Creates the <see cref="OpenDis.Enumerations.Entity.Information.Minefield.Fusing"/> instance from the byte array.
/// </summary>
/// <param name="array">The array which holds the values for the <see cref="OpenDis.Enumerations.Entity.Information.Minefield.Fusing"/>.</param>
/// <param name="index">The starting position within value.</param>
/// <returns>The <see cref="OpenDis.Enumerations.Entity.Information.Minefield.Fusing"/> instance, represented by a byte array.</returns>
/// <exception cref="ArgumentNullException">if the <c>array</c> is null.</exception>
/// <exception cref="IndexOutOfRangeException">if the <c>index</c> is lower than 0 or greater or equal than number of elements in array.</exception>
public static Fusing FromByteArray(byte[] array, int index)
{
if (array == null)
{
throw new ArgumentNullException("array");
}
if (index < 0 ||
index > array.Length - 1 ||
index + 2 > array.Length - 1)
{
throw new IndexOutOfRangeException();
}
return FromUInt16(BitConverter.ToUInt16(array, index));
}
/// <summary>
/// Creates the <see cref="OpenDis.Enumerations.Entity.Information.Minefield.Fusing"/> instance from the ushort value.
/// </summary>
/// <param name="value">The ushort value which represents the <see cref="OpenDis.Enumerations.Entity.Information.Minefield.Fusing"/> instance.</param>
/// <returns>The <see cref="OpenDis.Enumerations.Entity.Information.Minefield.Fusing"/> instance, represented by the ushort value.</returns>
public static Fusing FromUInt16(ushort value)
{
Fusing ps = new Fusing();
uint mask0 = 0x007f;
byte shift0 = 0;
uint newValue0 = value & mask0 >> shift0;
ps.Primary = (Fusing.PrimaryValue)newValue0;
uint mask1 = 0x3f80;
byte shift1 = 7;
uint newValue1 = value & mask1 >> shift1;
ps.Secondary = (Fusing.SecondaryValue)newValue1;
uint mask2 = 0x0010;
byte shift2 = 4;
uint newValue2 = value & mask2 >> shift2;
ps.AHD = (Fusing.AHDValue)newValue2;
return ps;
}
/// <summary>
/// Gets or sets the primary.
/// </summary>
/// <value>The primary.</value>
public Fusing.PrimaryValue Primary
{
get { return this.primary; }
set { this.primary = value; }
}
/// <summary>
/// Gets or sets the secondary.
/// </summary>
/// <value>The secondary.</value>
public Fusing.SecondaryValue Secondary
{
get { return this.secondary; }
set { this.secondary = value; }
}
/// <summary>
/// Gets or sets the ahd.
/// </summary>
/// <value>The ahd.</value>
public Fusing.AHDValue AHD
{
get { return this.aHD; }
set { this.aHD = value; }
}
/// <summary>
/// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object obj)
{
if (obj == null)
{
return false;
}
if (!(obj is Fusing))
{
return false;
}
return this.Equals((Fusing)obj);
}
/// <summary>
/// Determines whether the specified <see cref="OpenDis.Enumerations.Entity.Information.Minefield.Fusing"/> instance is equal to this instance.
/// </summary>
/// <param name="other">The <see cref="OpenDis.Enumerations.Entity.Information.Minefield.Fusing"/> instance to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="OpenDis.Enumerations.Entity.Information.Minefield.Fusing"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public bool Equals(Fusing other)
{
// If parameter is null return false (cast to object to prevent recursive loop!)
if ((object)other == null)
{
return false;
}
return
this.Primary == other.Primary &&
this.Secondary == other.Secondary &&
this.AHD == other.AHD;
}
/// <summary>
/// Converts the instance of <see cref="OpenDis.Enumerations.Entity.Information.Minefield.Fusing"/> to the byte array.
/// </summary>
/// <returns>The byte array representing the current <see cref="OpenDis.Enumerations.Entity.Information.Minefield.Fusing"/> instance.</returns>
public byte[] ToByteArray()
{
return BitConverter.GetBytes(this.ToUInt16());
}
/// <summary>
/// Converts the instance of <see cref="OpenDis.Enumerations.Entity.Information.Minefield.Fusing"/> to the ushort value.
/// </summary>
/// <returns>The ushort value representing the current <see cref="OpenDis.Enumerations.Entity.Information.Minefield.Fusing"/> instance.</returns>
public ushort ToUInt16()
{
ushort val = 0;
val |= (ushort)((uint)this.Primary << 0);
val |= (ushort)((uint)this.Secondary << 7);
val |= (ushort)((uint)this.AHD << 4);
return val;
}
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
/// <returns>
/// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
/// </returns>
public override int GetHashCode()
{
int hash = 17;
// Overflow is fine, just wrap
unchecked
{
hash = (hash * 29) + this.Primary.GetHashCode();
hash = (hash * 29) + this.Secondary.GetHashCode();
hash = (hash * 29) + this.AHD.GetHashCode();
}
return hash;
}
}
}
| 39.668449 | 165 | 0.551699 | [
"BSD-2-Clause"
] | mcgredonps/Unity_DIS | Assets/Plugins/DIS/Enumerations/Entity.Information.Minefield/Fusing.cs | 14,836 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace ML.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("ML.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized string similar to Your URL is invalid. Please check the formatting on it..
/// </summary>
internal static string Application_BearerAuthentication_InvalidURLException {
get {
return ResourceManager.GetString("Application_BearerAuthentication_InvalidURLException", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Server is unreachable. Please make sure it is up and running!.
/// </summary>
internal static string Application_BearerAuthentication_ServerUnreachableException {
get {
return ResourceManager.GetString("Application_BearerAuthentication_ServerUnreachableException", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Something went wrong while communicating with the server. Please try again..
/// </summary>
internal static string Application_BearerAuthentication_SomethingWrongException {
get {
return ResourceManager.GetString("Application_BearerAuthentication_SomethingWrongException", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid URL..
/// </summary>
internal static string Application_CreateClient_InvalidURLException {
get {
return ResourceManager.GetString("Application_CreateClient_InvalidURLException", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The server is unreachable..
/// </summary>
internal static string Application_CreateClient_ServerUnreachableException {
get {
return ResourceManager.GetString("Application_CreateClient_ServerUnreachableException", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The selected authentication scheme is unknown. Please choose one of the following: {0}.
/// </summary>
internal static string Application_InitializeAsync_UnknownAuthSchemeException {
get {
return ResourceManager.GetString("Application_InitializeAsync_UnknownAuthSchemeException", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to 400 Bad Request: The server didn't like that call. Please check your syntax..
/// </summary>
internal static string HTTPMagic_CheckStatus_400 {
get {
return ResourceManager.GetString("HTTPMagic_CheckStatus_400", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to 401 Unauthorized: The server doesn't recognize you. Please check your credentials..
/// </summary>
internal static string HTTPMagic_CheckStatus_401 {
get {
return ResourceManager.GetString("HTTPMagic_CheckStatus_401", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to 403 Forbidden: The server recognizes you, but is refusing access. Please ensure that you have permission to access this resource..
/// </summary>
internal static string HTTPMagic_CheckStatus_403 {
get {
return ResourceManager.GetString("HTTPMagic_CheckStatus_403", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to 404 Not Found: The server is there, but the page you're going for is not. Please ensure that all required setup is complete..
/// </summary>
internal static string HTTPMagic_CheckStatus_404 {
get {
return ResourceManager.GetString("HTTPMagic_CheckStatus_404", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to 405 Not Allowed: The server recognizes your request, but is refusing it. Please check that all prerequisites for this request have been completed..
/// </summary>
internal static string HTTPMagic_CheckStatus_405 {
get {
return ResourceManager.GetString("HTTPMagic_CheckStatus_405", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to 408 Timeout: The server gave it a shot, but took too long and timed out. Please try again..
/// </summary>
internal static string HTTPMagic_CheckStatus_408 {
get {
return ResourceManager.GetString("HTTPMagic_CheckStatus_408", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to 410 Gone: Whatever was once at this location is gone now. Please contact the activity creator to look into this..
/// </summary>
internal static string HTTPMagic_CheckStatus_410 {
get {
return ResourceManager.GetString("HTTPMagic_CheckStatus_410", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to 413 Too Large: Your payload is too large for the server to handle. Please reduce its size or send it in batches..
/// </summary>
internal static string HTTPMagic_CheckStatus_413 {
get {
return ResourceManager.GetString("HTTPMagic_CheckStatus_413", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to 414 Too Long: Your URL is too long. Please shorten it if possible..
/// </summary>
internal static string HTTPMagic_CheckStatus_414 {
get {
return ResourceManager.GetString("HTTPMagic_CheckStatus_414", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to 415 Bad Payload Type: Your payload is in a format the server doesn't like. Please check the desired format (e.g. JSON, XML, etc)..
/// </summary>
internal static string HTTPMagic_CheckStatus_415 {
get {
return ResourceManager.GetString("HTTPMagic_CheckStatus_415", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to 500 Server Error: Something went wrong on the server's side. Please try again..
/// </summary>
internal static string HTTPMagic_CheckStatus_500 {
get {
return ResourceManager.GetString("HTTPMagic_CheckStatus_500", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to 501 Not Implemented: This version of the server doesn't have the method you're trying to invoke. Please check for available updates..
/// </summary>
internal static string HTTPMagic_CheckStatus_501 {
get {
return ResourceManager.GetString("HTTPMagic_CheckStatus_501", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to 502 Bad Gateway: Something went wrong on the server's side. Please try again..
/// </summary>
internal static string HTTPMagic_CheckStatus_502 {
get {
return ResourceManager.GetString("HTTPMagic_CheckStatus_502", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to 503 Unavailable: The server is temporarily overloaded and can't process your request. Please try again in a bit..
/// </summary>
internal static string HTTPMagic_CheckStatus_503 {
get {
return ResourceManager.GetString("HTTPMagic_CheckStatus_503", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to 504 Timeout: The server gave it a shot, but took too long and timed out. Please try again..
/// </summary>
internal static string HTTPMagic_CheckStatus_504 {
get {
return ResourceManager.GetString("HTTPMagic_CheckStatus_504", resourceCulture);
}
}
}
}
| 45.221344 | 200 | 0.611572 | [
"MIT"
] | allenlooplee/RPABook | src/ML/ML/Properties/Resources.Designer.cs | 11,443 | C# |
using UnityEngine;
using UnityEngine.UI;
using TMPro;
using System.IO;
/*
*
*
* Think of ways to gate the other modes...
*
* Finish Tutorial for "quick play"
* Play quick play 4 times for challenge mode
* Get Elo rating of 120 to unlock Dungeon Run
*
*
*/
public class TutorialLevelSceneScript : Scene<TransitionData>
{
public bool[] humanPlayers { get; private set; }
public static string progressFileName
{
get
{
return Application.persistentDataPath + Path.DirectorySeparatorChar +
"progress.txt";
}
}
private Level levelSelected;
[SerializeField]
private GameObject tutorialLevelButtonParent;
[SerializeField]
private LevelButton[] tutorialLevelButtons;
[SerializeField]
private GameObject backButton;
[SerializeField]
private GameObject optionButton;
// Use this for initialization
void Start ()
{
}
private TaskManager _tm = new TaskManager();
internal override void OnEnter(TransitionData data)
{
//tutorialLevelButtons = tutorialLevelButtonParent.GetComponentsInChildren<LevelButton>();
tutorialLevelButtonParent.SetActive(false);
backButton.SetActive(false);
optionButton.SetActive(false);
humanPlayers = new bool[2];
humanPlayers[0] = true;
humanPlayers[1] = false;
int progress = 0;
if (File.Exists(progressFileName))
{
string fileText = File.ReadAllText(progressFileName);
int.TryParse(fileText, out progress);
}
SetLevelProgress(progress);
tutorialLevelButtonParent.transform.eulerAngles = new Vector3(0, 0, 0);
if (humanPlayers[0] && !humanPlayers[1])
{
tutorialLevelButtonParent.transform.eulerAngles = new Vector3(0, 0, 0);
}
else if (!humanPlayers[0] && humanPlayers[1])
{
tutorialLevelButtonParent.transform.eulerAngles = new Vector3(0, 0, 180);
}
tutorialLevelButtonParent.SetActive(true);
for (int i = 0; i < tutorialLevelButtons.Length; i++)
{
tutorialLevelButtons[i].gameObject.SetActive(false);
}
GameObject levelSelectText =
tutorialLevelButtonParent.GetComponentInChildren<TextMeshProUGUI>().gameObject;
levelSelectText.SetActive(false);
TaskTree tutorialEntrance = new TaskTree(new EmptyTask(),
new TaskTree(new LevelSelectTextEntrance(levelSelectText)),
new TaskTree(new LevelSelectButtonEntranceTask(tutorialLevelButtons)),
new TaskTree(new LevelSelectTextEntrance(backButton, true)),
new TaskTree(new LevelSelectTextEntrance(optionButton)));
_tm.Do(tutorialEntrance);
}
internal override void OnExit()
{
Services.GameManager.SetHandicapValues(HandicapSystem.handicapValues);
}
internal override void ExitTransition()
{
TaskTree tutorialExit = new TaskTree(new EmptyTask(),
new TaskTree(new LevelSelectTextEntrance(tutorialLevelButtonParent,false, true)),
new TaskTree(new LevelSelectButtonEntranceTask(tutorialLevelButtons,null, true)),
new TaskTree(new LevelSelectTextEntrance(backButton, true, true)),
new TaskTree(new LevelSelectTextEntrance(optionButton, false , true)));
_tm.Do(tutorialExit);
}
public void StartGame()
{
Services.GameManager.SetCurrentLevel(levelSelected);
Task changeScene = new WaitUnscaled(0.01f);
changeScene.Then(new ActionTask(ChangeScene));
_tm.Do(changeScene);
}
private void ChangeScene()
{
Services.GameManager.SetNumPlayers(humanPlayers);
Services.Scenes.Swap<GameSceneScript>();
}
public void SelectLevel(LevelButton levelButton)
{
if (levelButton.unlocked)
{
//levelSelectionIndicator.gameObject.SetActive(true);
levelSelected = levelButton.level;
//levelSelectionIndicator.transform.position = levelButton.transform.position;
StartGame();
}
else
{
return;
}
}
private void SetLevelProgress(int progress)
{
for (int i = 0; i < tutorialLevelButtons.Length; i++)
{
LevelButton button = tutorialLevelButtons[i].GetComponent<LevelButton>();
int lockIndex = button.GetComponentsInChildren<Image>().Length - 1;
int completionSymbolIndex = button.GetComponentsInChildren<Image>().Length - 2;
if (i > progress)
{
button.unlocked = false;
button.GetComponentsInChildren<Image>()[lockIndex].enabled = true;
button.GetComponentsInChildren<Image>()[completionSymbolIndex].enabled = false;
}
else if (i < progress)
{
button.unlocked = true;
button.GetComponentsInChildren<Image>()[completionSymbolIndex].enabled = true;
button.GetComponentsInChildren<Image>()[lockIndex].enabled = false;
}
else if(i == progress)
{
button.unlocked = true;
button.GetComponentsInChildren<Image>()[completionSymbolIndex].enabled = false;
button.GetComponentsInChildren<Image>()[lockIndex].enabled = false;
}
}
}
private void SlideInLevelButtons()
{
}
public void UnlockAllLevels()
{
SetLevelProgress(5);
Services.GameManager.UnlockAllModes();
TutorialManager.ViewedAllTutorial(true);
File.WriteAllText(GameOptionsSceneScript.progressFileName, "5");
}
public void LockAllLevels()
{
SetLevelProgress(0);
Services.GameManager.ModeUnlockReset();
TutorialManager.ViewedAllTutorial(false);
File.WriteAllText(GameOptionsSceneScript.progressFileName, "0");
}
public void UIClick()
{
Services.AudioManager.PlaySoundEffect(Services.Clips.UIClick, 0.55f);
}
public void UIButtonPressedSound()
{
Services.AudioManager.PlaySoundEffect(Services.Clips.UIButtonPressed, 0.55f);
}
// Update is called once per frame
void Update ()
{
_tm.Update();
}
}
| 30.9 | 98 | 0.623979 | [
"Unlicense"
] | chrsjwilliams/Omino | Assets/Scripts/_ChrsUtils/SceneManager/TutorialLevelSceneScript.cs | 6,491 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
namespace JIT.HardwareIntrinsics.General
{
public static partial class Program
{
private static void GreaterThanOrEqualByte()
{
var test = new VectorBinaryOpTest__GreaterThanOrEqualByte();
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class VectorBinaryOpTest__GreaterThanOrEqualByte
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Byte[] inArray1, Byte[] inArray2, Byte[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Byte>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Byte>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Byte>();
if ((alignment != 32 && alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Byte, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Byte, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Byte> _fld1;
public Vector128<Byte> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
return testStruct;
}
public void RunStructFldScenario(VectorBinaryOpTest__GreaterThanOrEqualByte testClass)
{
var result = Vector128.GreaterThanOrEqual(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte);
private static Byte[] _data1 = new Byte[Op1ElementCount];
private static Byte[] _data2 = new Byte[Op2ElementCount];
private static Vector128<Byte> _clsVar1;
private static Vector128<Byte> _clsVar2;
private Vector128<Byte> _fld1;
private Vector128<Byte> _fld2;
private DataTable _dataTable;
static VectorBinaryOpTest__GreaterThanOrEqualByte()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
}
public VectorBinaryOpTest__GreaterThanOrEqualByte()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
_dataTable = new DataTable(_data1, _data2, new Byte[RetElementCount], LargestVectorSize);
}
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Vector128.GreaterThanOrEqual(
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var method = typeof(Vector128).GetMethod(nameof(Vector128.GreaterThanOrEqual), new Type[] {
typeof(Vector128<Byte>),
typeof(Vector128<Byte>)
});
if (method is null)
{
method = typeof(Vector128).GetMethod(nameof(Vector128.GreaterThanOrEqual), 1, new Type[] {
typeof(Vector128<>).MakeGenericType(Type.MakeGenericMethodParameter(0)),
typeof(Vector128<>).MakeGenericType(Type.MakeGenericMethodParameter(0))
});
}
if (method.IsGenericMethodDefinition)
{
method = method.MakeGenericMethod(typeof(Byte));
}
var result = method.Invoke(null, new object[] {
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Vector128.GreaterThanOrEqual(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr);
var result = Vector128.GreaterThanOrEqual(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new VectorBinaryOpTest__GreaterThanOrEqualByte();
var result = Vector128.GreaterThanOrEqual(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Vector128.GreaterThanOrEqual(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Vector128.GreaterThanOrEqual(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
private void ValidateResult(Vector128<Byte> op1, Vector128<Byte> op2, void* result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[Op1ElementCount];
Byte[] inArray2 = new Byte[Op2ElementCount];
Byte[] outArray = new Byte[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[Op1ElementCount];
Byte[] inArray2 = new Byte[Op2ElementCount];
Byte[] outArray = new Byte[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Byte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Byte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Byte[] left, Byte[] right, Byte[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != ((left[0] >= right[0]) ? byte.MaxValue : 0))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != ((left[i] >= right[i]) ? byte.MaxValue : 0))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Vector128)}.{nameof(Vector128.GreaterThanOrEqual)}<Byte>(Vector128<Byte>, Vector128<Byte>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| 44.028986 | 184 | 0.60395 | [
"MIT"
] | 333fred/runtime | src/tests/JIT/HardwareIntrinsics/General/Vector128/GreaterThanOrEqual.Byte.cs | 15,190 | C# |
using Unity.Networking.Transport;
using Unity.NetCode;
using Unity.Mathematics;
using UnityEngine;
public struct Char_TerraformerSnapshotData : ISnapshotData<Char_TerraformerSnapshotData>
{
public uint tick;
private int CharacterInterpolatedDataPositionX;
private int CharacterInterpolatedDataPositionY;
private int CharacterInterpolatedDataPositionZ;
private int CharacterInterpolatedDatarotation;
private int CharacterInterpolatedDataaimYaw;
private int CharacterInterpolatedDataaimPitch;
private int CharacterInterpolatedDatamoveYaw;
private int CharacterInterpolatedDatacharAction;
private int CharacterInterpolatedDatacharActionTick;
private int CharacterInterpolatedDatadamageTick;
private int CharacterInterpolatedDatadamageDirection;
private uint CharacterInterpolatedDatasprinting;
private int CharacterInterpolatedDatasprintWeight;
private int CharacterInterpolatedDatacrouchWeight;
private int CharacterInterpolatedDataselectorTargetSource;
private int CharacterInterpolatedDatamoveAngleLocal;
private int CharacterInterpolatedDatashootPoseWeight;
private int CharacterInterpolatedDatalocomotionVectorX;
private int CharacterInterpolatedDatalocomotionVectorY;
private int CharacterInterpolatedDatalocomotionPhase;
private int CharacterInterpolatedDatabanking;
private int CharacterInterpolatedDatalandAnticWeight;
private int CharacterInterpolatedDataturnStartAngle;
private int CharacterInterpolatedDataturnDirection;
private int CharacterInterpolatedDatasquashTime;
private int CharacterInterpolatedDatasquashWeight;
private int CharacterInterpolatedDatainAirTime;
private int CharacterInterpolatedDatajumpTime;
private int CharacterInterpolatedDatasimpleTime;
private int CharacterInterpolatedDatafootIkOffsetX;
private int CharacterInterpolatedDatafootIkOffsetY;
private int CharacterInterpolatedDatafootIkNormalLeftX;
private int CharacterInterpolatedDatafootIkNormalLeftY;
private int CharacterInterpolatedDatafootIkNormalLeftZ;
private int CharacterInterpolatedDatafootIkNormalRightX;
private int CharacterInterpolatedDatafootIkNormalRightY;
private int CharacterInterpolatedDatafootIkNormalRightZ;
private int CharacterInterpolatedDatafootIkWeight;
private int CharacterInterpolatedDatablendOutAim;
private int CharacterPredictedDatatick;
private float CharacterPredictedDatapositionX;
private float CharacterPredictedDatapositionY;
private float CharacterPredictedDatapositionZ;
private float CharacterPredictedDatavelocityX;
private float CharacterPredictedDatavelocityY;
private float CharacterPredictedDatavelocityZ;
private uint CharacterPredictedDatasprinting;
private int CharacterPredictedDatacameraProfile;
private int CharacterPredictedDatadamageTick;
private int CharacterPredictedDatadamageDirectionX;
private int CharacterPredictedDatadamageDirectionY;
private int CharacterPredictedDatadamageDirectionZ;
private int CharacterReplicatedDataheroTypeIndex;
private float CharacterControllerGroundSupportDataSurfaceNormalX;
private float CharacterControllerGroundSupportDataSurfaceNormalY;
private float CharacterControllerGroundSupportDataSurfaceNormalZ;
private float CharacterControllerGroundSupportDataSurfaceVelocityX;
private float CharacterControllerGroundSupportDataSurfaceVelocityY;
private float CharacterControllerGroundSupportDataSurfaceVelocityZ;
private int CharacterControllerGroundSupportDataSupportedState;
private float CharacterControllerMoveResultMoveResultX;
private float CharacterControllerMoveResultMoveResultY;
private float CharacterControllerMoveResultMoveResultZ;
private float CharacterControllerVelocityVelocityX;
private float CharacterControllerVelocityVelocityY;
private float CharacterControllerVelocityVelocityZ;
private int HealthStateDatahealth;
private int InventoryStateactiveSlot;
private int PlayerOwnerPlayerIdValue;
private int PlayerControlledStateresetCommandTick;
private int PlayerControlledStateresetCommandLookYaw;
private int PlayerControlledStateresetCommandLookPitch;
private int Child0AbilityAbilityControlbehaviorState;
private uint Child0AbilityAbilityControlrequestDeactivate;
private int Child0AbilityMovementInterpolatedStatecharLocoState;
private int Child0AbilityMovementInterpolatedStatecharLocoTick;
private uint Child0AbilityMovementInterpolatedStatecrouching;
private int Child0AbilityMovementPredictedStatelocoState;
private int Child0AbilityMovementPredictedStatelocoStartTick;
private int Child0AbilityMovementPredictedStatejumpCount;
private uint Child0AbilityMovementPredictedStatecrouching;
private int Child1AbilityAbilityControlbehaviorState;
private uint Child1AbilityAbilityControlrequestDeactivate;
private int Child1AbilitySprintPredictedStateactive;
private int Child1AbilitySprintPredictedStateterminating;
private int Child1AbilitySprintPredictedStateterminateStartTick;
private int Child2AbilityAbilityControlbehaviorState;
private uint Child2AbilityAbilityControlrequestDeactivate;
private int Child3AbilityAbilityControlbehaviorState;
private uint Child3AbilityAbilityControlrequestDeactivate;
uint changeMask0;
uint changeMask1;
uint changeMask2;
public uint Tick => tick;
public float3 GetCharacterInterpolatedDataPosition(GhostDeserializerState deserializerState)
{
return GetCharacterInterpolatedDataPosition();
}
public float3 GetCharacterInterpolatedDataPosition()
{
return new float3(CharacterInterpolatedDataPositionX * 0.01f, CharacterInterpolatedDataPositionY * 0.01f, CharacterInterpolatedDataPositionZ * 0.01f);
}
public void SetCharacterInterpolatedDataPosition(float3 val, GhostSerializerState serializerState)
{
SetCharacterInterpolatedDataPosition(val);
}
public void SetCharacterInterpolatedDataPosition(float3 val)
{
CharacterInterpolatedDataPositionX = (int)(val.x * 100);
CharacterInterpolatedDataPositionY = (int)(val.y * 100);
CharacterInterpolatedDataPositionZ = (int)(val.z * 100);
}
public float GetCharacterInterpolatedDatarotation(GhostDeserializerState deserializerState)
{
return CharacterInterpolatedDatarotation * 1f;
}
public float GetCharacterInterpolatedDatarotation()
{
return CharacterInterpolatedDatarotation * 1f;
}
public void SetCharacterInterpolatedDatarotation(float val, GhostSerializerState serializerState)
{
CharacterInterpolatedDatarotation = (int)(val * 1);
}
public void SetCharacterInterpolatedDatarotation(float val)
{
CharacterInterpolatedDatarotation = (int)(val * 1);
}
public float GetCharacterInterpolatedDataaimYaw(GhostDeserializerState deserializerState)
{
return CharacterInterpolatedDataaimYaw * 1f;
}
public float GetCharacterInterpolatedDataaimYaw()
{
return CharacterInterpolatedDataaimYaw * 1f;
}
public void SetCharacterInterpolatedDataaimYaw(float val, GhostSerializerState serializerState)
{
CharacterInterpolatedDataaimYaw = (int)(val * 1);
}
public void SetCharacterInterpolatedDataaimYaw(float val)
{
CharacterInterpolatedDataaimYaw = (int)(val * 1);
}
public float GetCharacterInterpolatedDataaimPitch(GhostDeserializerState deserializerState)
{
return CharacterInterpolatedDataaimPitch * 1f;
}
public float GetCharacterInterpolatedDataaimPitch()
{
return CharacterInterpolatedDataaimPitch * 1f;
}
public void SetCharacterInterpolatedDataaimPitch(float val, GhostSerializerState serializerState)
{
CharacterInterpolatedDataaimPitch = (int)(val * 1);
}
public void SetCharacterInterpolatedDataaimPitch(float val)
{
CharacterInterpolatedDataaimPitch = (int)(val * 1);
}
public float GetCharacterInterpolatedDatamoveYaw(GhostDeserializerState deserializerState)
{
return CharacterInterpolatedDatamoveYaw * 1f;
}
public float GetCharacterInterpolatedDatamoveYaw()
{
return CharacterInterpolatedDatamoveYaw * 1f;
}
public void SetCharacterInterpolatedDatamoveYaw(float val, GhostSerializerState serializerState)
{
CharacterInterpolatedDatamoveYaw = (int)(val * 1);
}
public void SetCharacterInterpolatedDatamoveYaw(float val)
{
CharacterInterpolatedDatamoveYaw = (int)(val * 1);
}
public Ability.AbilityAction.Action GetCharacterInterpolatedDatacharAction(GhostDeserializerState deserializerState)
{
return (Ability.AbilityAction.Action)CharacterInterpolatedDatacharAction;
}
public Ability.AbilityAction.Action GetCharacterInterpolatedDatacharAction()
{
return (Ability.AbilityAction.Action)CharacterInterpolatedDatacharAction;
}
public void SetCharacterInterpolatedDatacharAction(Ability.AbilityAction.Action val, GhostSerializerState serializerState)
{
CharacterInterpolatedDatacharAction = (int)val;
}
public void SetCharacterInterpolatedDatacharAction(Ability.AbilityAction.Action val)
{
CharacterInterpolatedDatacharAction = (int)val;
}
public int GetCharacterInterpolatedDatacharActionTick(GhostDeserializerState deserializerState)
{
return (int)CharacterInterpolatedDatacharActionTick;
}
public int GetCharacterInterpolatedDatacharActionTick()
{
return (int)CharacterInterpolatedDatacharActionTick;
}
public void SetCharacterInterpolatedDatacharActionTick(int val, GhostSerializerState serializerState)
{
CharacterInterpolatedDatacharActionTick = (int)val;
}
public void SetCharacterInterpolatedDatacharActionTick(int val)
{
CharacterInterpolatedDatacharActionTick = (int)val;
}
public int GetCharacterInterpolatedDatadamageTick(GhostDeserializerState deserializerState)
{
return (int)CharacterInterpolatedDatadamageTick;
}
public int GetCharacterInterpolatedDatadamageTick()
{
return (int)CharacterInterpolatedDatadamageTick;
}
public void SetCharacterInterpolatedDatadamageTick(int val, GhostSerializerState serializerState)
{
CharacterInterpolatedDatadamageTick = (int)val;
}
public void SetCharacterInterpolatedDatadamageTick(int val)
{
CharacterInterpolatedDatadamageTick = (int)val;
}
public float GetCharacterInterpolatedDatadamageDirection(GhostDeserializerState deserializerState)
{
return CharacterInterpolatedDatadamageDirection * 0.1f;
}
public float GetCharacterInterpolatedDatadamageDirection()
{
return CharacterInterpolatedDatadamageDirection * 0.1f;
}
public void SetCharacterInterpolatedDatadamageDirection(float val, GhostSerializerState serializerState)
{
CharacterInterpolatedDatadamageDirection = (int)(val * 10);
}
public void SetCharacterInterpolatedDatadamageDirection(float val)
{
CharacterInterpolatedDatadamageDirection = (int)(val * 10);
}
public bool GetCharacterInterpolatedDatasprinting(GhostDeserializerState deserializerState)
{
return CharacterInterpolatedDatasprinting!=0;
}
public bool GetCharacterInterpolatedDatasprinting()
{
return CharacterInterpolatedDatasprinting!=0;
}
public void SetCharacterInterpolatedDatasprinting(bool val, GhostSerializerState serializerState)
{
CharacterInterpolatedDatasprinting = val?1u:0;
}
public void SetCharacterInterpolatedDatasprinting(bool val)
{
CharacterInterpolatedDatasprinting = val?1u:0;
}
public float GetCharacterInterpolatedDatasprintWeight(GhostDeserializerState deserializerState)
{
return CharacterInterpolatedDatasprintWeight * 0.01f;
}
public float GetCharacterInterpolatedDatasprintWeight()
{
return CharacterInterpolatedDatasprintWeight * 0.01f;
}
public void SetCharacterInterpolatedDatasprintWeight(float val, GhostSerializerState serializerState)
{
CharacterInterpolatedDatasprintWeight = (int)(val * 100);
}
public void SetCharacterInterpolatedDatasprintWeight(float val)
{
CharacterInterpolatedDatasprintWeight = (int)(val * 100);
}
public float GetCharacterInterpolatedDatacrouchWeight(GhostDeserializerState deserializerState)
{
return CharacterInterpolatedDatacrouchWeight * 0.01f;
}
public float GetCharacterInterpolatedDatacrouchWeight()
{
return CharacterInterpolatedDatacrouchWeight * 0.01f;
}
public void SetCharacterInterpolatedDatacrouchWeight(float val, GhostSerializerState serializerState)
{
CharacterInterpolatedDatacrouchWeight = (int)(val * 100);
}
public void SetCharacterInterpolatedDatacrouchWeight(float val)
{
CharacterInterpolatedDatacrouchWeight = (int)(val * 100);
}
public int GetCharacterInterpolatedDataselectorTargetSource(GhostDeserializerState deserializerState)
{
return (int)CharacterInterpolatedDataselectorTargetSource;
}
public int GetCharacterInterpolatedDataselectorTargetSource()
{
return (int)CharacterInterpolatedDataselectorTargetSource;
}
public void SetCharacterInterpolatedDataselectorTargetSource(int val, GhostSerializerState serializerState)
{
CharacterInterpolatedDataselectorTargetSource = (int)val;
}
public void SetCharacterInterpolatedDataselectorTargetSource(int val)
{
CharacterInterpolatedDataselectorTargetSource = (int)val;
}
public float GetCharacterInterpolatedDatamoveAngleLocal(GhostDeserializerState deserializerState)
{
return CharacterInterpolatedDatamoveAngleLocal * 1f;
}
public float GetCharacterInterpolatedDatamoveAngleLocal()
{
return CharacterInterpolatedDatamoveAngleLocal * 1f;
}
public void SetCharacterInterpolatedDatamoveAngleLocal(float val, GhostSerializerState serializerState)
{
CharacterInterpolatedDatamoveAngleLocal = (int)(val * 1);
}
public void SetCharacterInterpolatedDatamoveAngleLocal(float val)
{
CharacterInterpolatedDatamoveAngleLocal = (int)(val * 1);
}
public float GetCharacterInterpolatedDatashootPoseWeight(GhostDeserializerState deserializerState)
{
return CharacterInterpolatedDatashootPoseWeight * 0.001f;
}
public float GetCharacterInterpolatedDatashootPoseWeight()
{
return CharacterInterpolatedDatashootPoseWeight * 0.001f;
}
public void SetCharacterInterpolatedDatashootPoseWeight(float val, GhostSerializerState serializerState)
{
CharacterInterpolatedDatashootPoseWeight = (int)(val * 1000);
}
public void SetCharacterInterpolatedDatashootPoseWeight(float val)
{
CharacterInterpolatedDatashootPoseWeight = (int)(val * 1000);
}
public float2 GetCharacterInterpolatedDatalocomotionVector(GhostDeserializerState deserializerState)
{
return GetCharacterInterpolatedDatalocomotionVector();
}
public float2 GetCharacterInterpolatedDatalocomotionVector()
{
return new float2(CharacterInterpolatedDatalocomotionVectorX * 0.001f, CharacterInterpolatedDatalocomotionVectorY * 0.001f);
}
public void SetCharacterInterpolatedDatalocomotionVector(float2 val, GhostSerializerState serializerState)
{
SetCharacterInterpolatedDatalocomotionVector(val);
}
public void SetCharacterInterpolatedDatalocomotionVector(float2 val)
{
CharacterInterpolatedDatalocomotionVectorX = (int)(val.x * 1000);
CharacterInterpolatedDatalocomotionVectorY = (int)(val.y * 1000);
}
public float GetCharacterInterpolatedDatalocomotionPhase(GhostDeserializerState deserializerState)
{
return CharacterInterpolatedDatalocomotionPhase * 0.001f;
}
public float GetCharacterInterpolatedDatalocomotionPhase()
{
return CharacterInterpolatedDatalocomotionPhase * 0.001f;
}
public void SetCharacterInterpolatedDatalocomotionPhase(float val, GhostSerializerState serializerState)
{
CharacterInterpolatedDatalocomotionPhase = (int)(val * 1000);
}
public void SetCharacterInterpolatedDatalocomotionPhase(float val)
{
CharacterInterpolatedDatalocomotionPhase = (int)(val * 1000);
}
public float GetCharacterInterpolatedDatabanking(GhostDeserializerState deserializerState)
{
return CharacterInterpolatedDatabanking * 0.001f;
}
public float GetCharacterInterpolatedDatabanking()
{
return CharacterInterpolatedDatabanking * 0.001f;
}
public void SetCharacterInterpolatedDatabanking(float val, GhostSerializerState serializerState)
{
CharacterInterpolatedDatabanking = (int)(val * 1000);
}
public void SetCharacterInterpolatedDatabanking(float val)
{
CharacterInterpolatedDatabanking = (int)(val * 1000);
}
public float GetCharacterInterpolatedDatalandAnticWeight(GhostDeserializerState deserializerState)
{
return CharacterInterpolatedDatalandAnticWeight * 0.01f;
}
public float GetCharacterInterpolatedDatalandAnticWeight()
{
return CharacterInterpolatedDatalandAnticWeight * 0.01f;
}
public void SetCharacterInterpolatedDatalandAnticWeight(float val, GhostSerializerState serializerState)
{
CharacterInterpolatedDatalandAnticWeight = (int)(val * 100);
}
public void SetCharacterInterpolatedDatalandAnticWeight(float val)
{
CharacterInterpolatedDatalandAnticWeight = (int)(val * 100);
}
public float GetCharacterInterpolatedDataturnStartAngle(GhostDeserializerState deserializerState)
{
return CharacterInterpolatedDataturnStartAngle * 1f;
}
public float GetCharacterInterpolatedDataturnStartAngle()
{
return CharacterInterpolatedDataturnStartAngle * 1f;
}
public void SetCharacterInterpolatedDataturnStartAngle(float val, GhostSerializerState serializerState)
{
CharacterInterpolatedDataturnStartAngle = (int)(val * 1);
}
public void SetCharacterInterpolatedDataturnStartAngle(float val)
{
CharacterInterpolatedDataturnStartAngle = (int)(val * 1);
}
public short GetCharacterInterpolatedDataturnDirection(GhostDeserializerState deserializerState)
{
return (short)CharacterInterpolatedDataturnDirection;
}
public short GetCharacterInterpolatedDataturnDirection()
{
return (short)CharacterInterpolatedDataturnDirection;
}
public void SetCharacterInterpolatedDataturnDirection(short val, GhostSerializerState serializerState)
{
CharacterInterpolatedDataturnDirection = (int)val;
}
public void SetCharacterInterpolatedDataturnDirection(short val)
{
CharacterInterpolatedDataturnDirection = (int)val;
}
public float GetCharacterInterpolatedDatasquashTime(GhostDeserializerState deserializerState)
{
return CharacterInterpolatedDatasquashTime * 0.01f;
}
public float GetCharacterInterpolatedDatasquashTime()
{
return CharacterInterpolatedDatasquashTime * 0.01f;
}
public void SetCharacterInterpolatedDatasquashTime(float val, GhostSerializerState serializerState)
{
CharacterInterpolatedDatasquashTime = (int)(val * 100);
}
public void SetCharacterInterpolatedDatasquashTime(float val)
{
CharacterInterpolatedDatasquashTime = (int)(val * 100);
}
public float GetCharacterInterpolatedDatasquashWeight(GhostDeserializerState deserializerState)
{
return CharacterInterpolatedDatasquashWeight * 0.01f;
}
public float GetCharacterInterpolatedDatasquashWeight()
{
return CharacterInterpolatedDatasquashWeight * 0.01f;
}
public void SetCharacterInterpolatedDatasquashWeight(float val, GhostSerializerState serializerState)
{
CharacterInterpolatedDatasquashWeight = (int)(val * 100);
}
public void SetCharacterInterpolatedDatasquashWeight(float val)
{
CharacterInterpolatedDatasquashWeight = (int)(val * 100);
}
public float GetCharacterInterpolatedDatainAirTime(GhostDeserializerState deserializerState)
{
return CharacterInterpolatedDatainAirTime * 0.01f;
}
public float GetCharacterInterpolatedDatainAirTime()
{
return CharacterInterpolatedDatainAirTime * 0.01f;
}
public void SetCharacterInterpolatedDatainAirTime(float val, GhostSerializerState serializerState)
{
CharacterInterpolatedDatainAirTime = (int)(val * 100);
}
public void SetCharacterInterpolatedDatainAirTime(float val)
{
CharacterInterpolatedDatainAirTime = (int)(val * 100);
}
public float GetCharacterInterpolatedDatajumpTime(GhostDeserializerState deserializerState)
{
return CharacterInterpolatedDatajumpTime * 0.01f;
}
public float GetCharacterInterpolatedDatajumpTime()
{
return CharacterInterpolatedDatajumpTime * 0.01f;
}
public void SetCharacterInterpolatedDatajumpTime(float val, GhostSerializerState serializerState)
{
CharacterInterpolatedDatajumpTime = (int)(val * 100);
}
public void SetCharacterInterpolatedDatajumpTime(float val)
{
CharacterInterpolatedDatajumpTime = (int)(val * 100);
}
public float GetCharacterInterpolatedDatasimpleTime(GhostDeserializerState deserializerState)
{
return CharacterInterpolatedDatasimpleTime * 0.01f;
}
public float GetCharacterInterpolatedDatasimpleTime()
{
return CharacterInterpolatedDatasimpleTime * 0.01f;
}
public void SetCharacterInterpolatedDatasimpleTime(float val, GhostSerializerState serializerState)
{
CharacterInterpolatedDatasimpleTime = (int)(val * 100);
}
public void SetCharacterInterpolatedDatasimpleTime(float val)
{
CharacterInterpolatedDatasimpleTime = (int)(val * 100);
}
public float2 GetCharacterInterpolatedDatafootIkOffset(GhostDeserializerState deserializerState)
{
return GetCharacterInterpolatedDatafootIkOffset();
}
public float2 GetCharacterInterpolatedDatafootIkOffset()
{
return new float2(CharacterInterpolatedDatafootIkOffsetX * 0.01f, CharacterInterpolatedDatafootIkOffsetY * 0.01f);
}
public void SetCharacterInterpolatedDatafootIkOffset(float2 val, GhostSerializerState serializerState)
{
SetCharacterInterpolatedDatafootIkOffset(val);
}
public void SetCharacterInterpolatedDatafootIkOffset(float2 val)
{
CharacterInterpolatedDatafootIkOffsetX = (int)(val.x * 100);
CharacterInterpolatedDatafootIkOffsetY = (int)(val.y * 100);
}
public float3 GetCharacterInterpolatedDatafootIkNormalLeft(GhostDeserializerState deserializerState)
{
return GetCharacterInterpolatedDatafootIkNormalLeft();
}
public float3 GetCharacterInterpolatedDatafootIkNormalLeft()
{
return new float3(CharacterInterpolatedDatafootIkNormalLeftX * 0.01f, CharacterInterpolatedDatafootIkNormalLeftY * 0.01f, CharacterInterpolatedDatafootIkNormalLeftZ * 0.01f);
}
public void SetCharacterInterpolatedDatafootIkNormalLeft(float3 val, GhostSerializerState serializerState)
{
SetCharacterInterpolatedDatafootIkNormalLeft(val);
}
public void SetCharacterInterpolatedDatafootIkNormalLeft(float3 val)
{
CharacterInterpolatedDatafootIkNormalLeftX = (int)(val.x * 100);
CharacterInterpolatedDatafootIkNormalLeftY = (int)(val.y * 100);
CharacterInterpolatedDatafootIkNormalLeftZ = (int)(val.z * 100);
}
public float3 GetCharacterInterpolatedDatafootIkNormalRight(GhostDeserializerState deserializerState)
{
return GetCharacterInterpolatedDatafootIkNormalRight();
}
public float3 GetCharacterInterpolatedDatafootIkNormalRight()
{
return new float3(CharacterInterpolatedDatafootIkNormalRightX * 0.01f, CharacterInterpolatedDatafootIkNormalRightY * 0.01f, CharacterInterpolatedDatafootIkNormalRightZ * 0.01f);
}
public void SetCharacterInterpolatedDatafootIkNormalRight(float3 val, GhostSerializerState serializerState)
{
SetCharacterInterpolatedDatafootIkNormalRight(val);
}
public void SetCharacterInterpolatedDatafootIkNormalRight(float3 val)
{
CharacterInterpolatedDatafootIkNormalRightX = (int)(val.x * 100);
CharacterInterpolatedDatafootIkNormalRightY = (int)(val.y * 100);
CharacterInterpolatedDatafootIkNormalRightZ = (int)(val.z * 100);
}
public float GetCharacterInterpolatedDatafootIkWeight(GhostDeserializerState deserializerState)
{
return CharacterInterpolatedDatafootIkWeight * 0.01f;
}
public float GetCharacterInterpolatedDatafootIkWeight()
{
return CharacterInterpolatedDatafootIkWeight * 0.01f;
}
public void SetCharacterInterpolatedDatafootIkWeight(float val, GhostSerializerState serializerState)
{
CharacterInterpolatedDatafootIkWeight = (int)(val * 100);
}
public void SetCharacterInterpolatedDatafootIkWeight(float val)
{
CharacterInterpolatedDatafootIkWeight = (int)(val * 100);
}
public float GetCharacterInterpolatedDatablendOutAim(GhostDeserializerState deserializerState)
{
return CharacterInterpolatedDatablendOutAim * 0.01f;
}
public float GetCharacterInterpolatedDatablendOutAim()
{
return CharacterInterpolatedDatablendOutAim * 0.01f;
}
public void SetCharacterInterpolatedDatablendOutAim(float val, GhostSerializerState serializerState)
{
CharacterInterpolatedDatablendOutAim = (int)(val * 100);
}
public void SetCharacterInterpolatedDatablendOutAim(float val)
{
CharacterInterpolatedDatablendOutAim = (int)(val * 100);
}
public int GetCharacterPredictedDatatick(GhostDeserializerState deserializerState)
{
return (int)CharacterPredictedDatatick;
}
public int GetCharacterPredictedDatatick()
{
return (int)CharacterPredictedDatatick;
}
public void SetCharacterPredictedDatatick(int val, GhostSerializerState serializerState)
{
CharacterPredictedDatatick = (int)val;
}
public void SetCharacterPredictedDatatick(int val)
{
CharacterPredictedDatatick = (int)val;
}
public float3 GetCharacterPredictedDataposition(GhostDeserializerState deserializerState)
{
return GetCharacterPredictedDataposition();
}
public float3 GetCharacterPredictedDataposition()
{
return new float3(CharacterPredictedDatapositionX, CharacterPredictedDatapositionY, CharacterPredictedDatapositionZ);
}
public void SetCharacterPredictedDataposition(float3 val, GhostSerializerState serializerState)
{
SetCharacterPredictedDataposition(val);
}
public void SetCharacterPredictedDataposition(float3 val)
{
CharacterPredictedDatapositionX = val.x;
CharacterPredictedDatapositionY = val.y;
CharacterPredictedDatapositionZ = val.z;
}
public float3 GetCharacterPredictedDatavelocity(GhostDeserializerState deserializerState)
{
return GetCharacterPredictedDatavelocity();
}
public float3 GetCharacterPredictedDatavelocity()
{
return new float3(CharacterPredictedDatavelocityX, CharacterPredictedDatavelocityY, CharacterPredictedDatavelocityZ);
}
public void SetCharacterPredictedDatavelocity(float3 val, GhostSerializerState serializerState)
{
SetCharacterPredictedDatavelocity(val);
}
public void SetCharacterPredictedDatavelocity(float3 val)
{
CharacterPredictedDatavelocityX = val.x;
CharacterPredictedDatavelocityY = val.y;
CharacterPredictedDatavelocityZ = val.z;
}
public bool GetCharacterPredictedDatasprinting(GhostDeserializerState deserializerState)
{
return CharacterPredictedDatasprinting!=0;
}
public bool GetCharacterPredictedDatasprinting()
{
return CharacterPredictedDatasprinting!=0;
}
public void SetCharacterPredictedDatasprinting(bool val, GhostSerializerState serializerState)
{
CharacterPredictedDatasprinting = val?1u:0;
}
public void SetCharacterPredictedDatasprinting(bool val)
{
CharacterPredictedDatasprinting = val?1u:0;
}
public CameraProfile GetCharacterPredictedDatacameraProfile(GhostDeserializerState deserializerState)
{
return (CameraProfile)CharacterPredictedDatacameraProfile;
}
public CameraProfile GetCharacterPredictedDatacameraProfile()
{
return (CameraProfile)CharacterPredictedDatacameraProfile;
}
public void SetCharacterPredictedDatacameraProfile(CameraProfile val, GhostSerializerState serializerState)
{
CharacterPredictedDatacameraProfile = (int)val;
}
public void SetCharacterPredictedDatacameraProfile(CameraProfile val)
{
CharacterPredictedDatacameraProfile = (int)val;
}
public int GetCharacterPredictedDatadamageTick(GhostDeserializerState deserializerState)
{
return (int)CharacterPredictedDatadamageTick;
}
public int GetCharacterPredictedDatadamageTick()
{
return (int)CharacterPredictedDatadamageTick;
}
public void SetCharacterPredictedDatadamageTick(int val, GhostSerializerState serializerState)
{
CharacterPredictedDatadamageTick = (int)val;
}
public void SetCharacterPredictedDatadamageTick(int val)
{
CharacterPredictedDatadamageTick = (int)val;
}
public float3 GetCharacterPredictedDatadamageDirection(GhostDeserializerState deserializerState)
{
return GetCharacterPredictedDatadamageDirection();
}
public float3 GetCharacterPredictedDatadamageDirection()
{
return new float3(CharacterPredictedDatadamageDirectionX * 0.001f, CharacterPredictedDatadamageDirectionY * 0.001f, CharacterPredictedDatadamageDirectionZ * 0.001f);
}
public void SetCharacterPredictedDatadamageDirection(float3 val, GhostSerializerState serializerState)
{
SetCharacterPredictedDatadamageDirection(val);
}
public void SetCharacterPredictedDatadamageDirection(float3 val)
{
CharacterPredictedDatadamageDirectionX = (int)(val.x * 1000);
CharacterPredictedDatadamageDirectionY = (int)(val.y * 1000);
CharacterPredictedDatadamageDirectionZ = (int)(val.z * 1000);
}
public int GetCharacterReplicatedDataheroTypeIndex(GhostDeserializerState deserializerState)
{
return (int)CharacterReplicatedDataheroTypeIndex;
}
public int GetCharacterReplicatedDataheroTypeIndex()
{
return (int)CharacterReplicatedDataheroTypeIndex;
}
public void SetCharacterReplicatedDataheroTypeIndex(int val, GhostSerializerState serializerState)
{
CharacterReplicatedDataheroTypeIndex = (int)val;
}
public void SetCharacterReplicatedDataheroTypeIndex(int val)
{
CharacterReplicatedDataheroTypeIndex = (int)val;
}
public float3 GetCharacterControllerGroundSupportDataSurfaceNormal(GhostDeserializerState deserializerState)
{
return GetCharacterControllerGroundSupportDataSurfaceNormal();
}
public float3 GetCharacterControllerGroundSupportDataSurfaceNormal()
{
return new float3(CharacterControllerGroundSupportDataSurfaceNormalX, CharacterControllerGroundSupportDataSurfaceNormalY, CharacterControllerGroundSupportDataSurfaceNormalZ);
}
public void SetCharacterControllerGroundSupportDataSurfaceNormal(float3 val, GhostSerializerState serializerState)
{
SetCharacterControllerGroundSupportDataSurfaceNormal(val);
}
public void SetCharacterControllerGroundSupportDataSurfaceNormal(float3 val)
{
CharacterControllerGroundSupportDataSurfaceNormalX = val.x;
CharacterControllerGroundSupportDataSurfaceNormalY = val.y;
CharacterControllerGroundSupportDataSurfaceNormalZ = val.z;
}
public float3 GetCharacterControllerGroundSupportDataSurfaceVelocity(GhostDeserializerState deserializerState)
{
return GetCharacterControllerGroundSupportDataSurfaceVelocity();
}
public float3 GetCharacterControllerGroundSupportDataSurfaceVelocity()
{
return new float3(CharacterControllerGroundSupportDataSurfaceVelocityX, CharacterControllerGroundSupportDataSurfaceVelocityY, CharacterControllerGroundSupportDataSurfaceVelocityZ);
}
public void SetCharacterControllerGroundSupportDataSurfaceVelocity(float3 val, GhostSerializerState serializerState)
{
SetCharacterControllerGroundSupportDataSurfaceVelocity(val);
}
public void SetCharacterControllerGroundSupportDataSurfaceVelocity(float3 val)
{
CharacterControllerGroundSupportDataSurfaceVelocityX = val.x;
CharacterControllerGroundSupportDataSurfaceVelocityY = val.y;
CharacterControllerGroundSupportDataSurfaceVelocityZ = val.z;
}
public CharacterControllerUtilities.CharacterSupportState GetCharacterControllerGroundSupportDataSupportedState(GhostDeserializerState deserializerState)
{
return (CharacterControllerUtilities.CharacterSupportState)CharacterControllerGroundSupportDataSupportedState;
}
public CharacterControllerUtilities.CharacterSupportState GetCharacterControllerGroundSupportDataSupportedState()
{
return (CharacterControllerUtilities.CharacterSupportState)CharacterControllerGroundSupportDataSupportedState;
}
public void SetCharacterControllerGroundSupportDataSupportedState(CharacterControllerUtilities.CharacterSupportState val, GhostSerializerState serializerState)
{
CharacterControllerGroundSupportDataSupportedState = (int)val;
}
public void SetCharacterControllerGroundSupportDataSupportedState(CharacterControllerUtilities.CharacterSupportState val)
{
CharacterControllerGroundSupportDataSupportedState = (int)val;
}
public float3 GetCharacterControllerMoveResultMoveResult(GhostDeserializerState deserializerState)
{
return GetCharacterControllerMoveResultMoveResult();
}
public float3 GetCharacterControllerMoveResultMoveResult()
{
return new float3(CharacterControllerMoveResultMoveResultX, CharacterControllerMoveResultMoveResultY, CharacterControllerMoveResultMoveResultZ);
}
public void SetCharacterControllerMoveResultMoveResult(float3 val, GhostSerializerState serializerState)
{
SetCharacterControllerMoveResultMoveResult(val);
}
public void SetCharacterControllerMoveResultMoveResult(float3 val)
{
CharacterControllerMoveResultMoveResultX = val.x;
CharacterControllerMoveResultMoveResultY = val.y;
CharacterControllerMoveResultMoveResultZ = val.z;
}
public float3 GetCharacterControllerVelocityVelocity(GhostDeserializerState deserializerState)
{
return GetCharacterControllerVelocityVelocity();
}
public float3 GetCharacterControllerVelocityVelocity()
{
return new float3(CharacterControllerVelocityVelocityX, CharacterControllerVelocityVelocityY, CharacterControllerVelocityVelocityZ);
}
public void SetCharacterControllerVelocityVelocity(float3 val, GhostSerializerState serializerState)
{
SetCharacterControllerVelocityVelocity(val);
}
public void SetCharacterControllerVelocityVelocity(float3 val)
{
CharacterControllerVelocityVelocityX = val.x;
CharacterControllerVelocityVelocityY = val.y;
CharacterControllerVelocityVelocityZ = val.z;
}
public float GetHealthStateDatahealth(GhostDeserializerState deserializerState)
{
return HealthStateDatahealth * 1f;
}
public float GetHealthStateDatahealth()
{
return HealthStateDatahealth * 1f;
}
public void SetHealthStateDatahealth(float val, GhostSerializerState serializerState)
{
HealthStateDatahealth = (int)(val * 1);
}
public void SetHealthStateDatahealth(float val)
{
HealthStateDatahealth = (int)(val * 1);
}
public sbyte GetInventoryStateactiveSlot(GhostDeserializerState deserializerState)
{
return (sbyte)InventoryStateactiveSlot;
}
public sbyte GetInventoryStateactiveSlot()
{
return (sbyte)InventoryStateactiveSlot;
}
public void SetInventoryStateactiveSlot(sbyte val, GhostSerializerState serializerState)
{
InventoryStateactiveSlot = (int)val;
}
public void SetInventoryStateactiveSlot(sbyte val)
{
InventoryStateactiveSlot = (int)val;
}
public int GetPlayerOwnerPlayerIdValue(GhostDeserializerState deserializerState)
{
return (int)PlayerOwnerPlayerIdValue;
}
public int GetPlayerOwnerPlayerIdValue()
{
return (int)PlayerOwnerPlayerIdValue;
}
public void SetPlayerOwnerPlayerIdValue(int val, GhostSerializerState serializerState)
{
PlayerOwnerPlayerIdValue = (int)val;
}
public void SetPlayerOwnerPlayerIdValue(int val)
{
PlayerOwnerPlayerIdValue = (int)val;
}
public int GetPlayerControlledStateresetCommandTick(GhostDeserializerState deserializerState)
{
return (int)PlayerControlledStateresetCommandTick;
}
public int GetPlayerControlledStateresetCommandTick()
{
return (int)PlayerControlledStateresetCommandTick;
}
public void SetPlayerControlledStateresetCommandTick(int val, GhostSerializerState serializerState)
{
PlayerControlledStateresetCommandTick = (int)val;
}
public void SetPlayerControlledStateresetCommandTick(int val)
{
PlayerControlledStateresetCommandTick = (int)val;
}
public float GetPlayerControlledStateresetCommandLookYaw(GhostDeserializerState deserializerState)
{
return PlayerControlledStateresetCommandLookYaw * 0.1f;
}
public float GetPlayerControlledStateresetCommandLookYaw()
{
return PlayerControlledStateresetCommandLookYaw * 0.1f;
}
public void SetPlayerControlledStateresetCommandLookYaw(float val, GhostSerializerState serializerState)
{
PlayerControlledStateresetCommandLookYaw = (int)(val * 10);
}
public void SetPlayerControlledStateresetCommandLookYaw(float val)
{
PlayerControlledStateresetCommandLookYaw = (int)(val * 10);
}
public float GetPlayerControlledStateresetCommandLookPitch(GhostDeserializerState deserializerState)
{
return PlayerControlledStateresetCommandLookPitch * 0.1f;
}
public float GetPlayerControlledStateresetCommandLookPitch()
{
return PlayerControlledStateresetCommandLookPitch * 0.1f;
}
public void SetPlayerControlledStateresetCommandLookPitch(float val, GhostSerializerState serializerState)
{
PlayerControlledStateresetCommandLookPitch = (int)(val * 10);
}
public void SetPlayerControlledStateresetCommandLookPitch(float val)
{
PlayerControlledStateresetCommandLookPitch = (int)(val * 10);
}
public Ability.AbilityControl.State GetChild0AbilityAbilityControlbehaviorState(GhostDeserializerState deserializerState)
{
return (Ability.AbilityControl.State)Child0AbilityAbilityControlbehaviorState;
}
public Ability.AbilityControl.State GetChild0AbilityAbilityControlbehaviorState()
{
return (Ability.AbilityControl.State)Child0AbilityAbilityControlbehaviorState;
}
public void SetChild0AbilityAbilityControlbehaviorState(Ability.AbilityControl.State val, GhostSerializerState serializerState)
{
Child0AbilityAbilityControlbehaviorState = (int)val;
}
public void SetChild0AbilityAbilityControlbehaviorState(Ability.AbilityControl.State val)
{
Child0AbilityAbilityControlbehaviorState = (int)val;
}
public bool GetChild0AbilityAbilityControlrequestDeactivate(GhostDeserializerState deserializerState)
{
return Child0AbilityAbilityControlrequestDeactivate!=0;
}
public bool GetChild0AbilityAbilityControlrequestDeactivate()
{
return Child0AbilityAbilityControlrequestDeactivate!=0;
}
public void SetChild0AbilityAbilityControlrequestDeactivate(bool val, GhostSerializerState serializerState)
{
Child0AbilityAbilityControlrequestDeactivate = val?1u:0;
}
public void SetChild0AbilityAbilityControlrequestDeactivate(bool val)
{
Child0AbilityAbilityControlrequestDeactivate = val?1u:0;
}
public AbilityMovement.LocoState GetChild0AbilityMovementInterpolatedStatecharLocoState(GhostDeserializerState deserializerState)
{
return (AbilityMovement.LocoState)Child0AbilityMovementInterpolatedStatecharLocoState;
}
public AbilityMovement.LocoState GetChild0AbilityMovementInterpolatedStatecharLocoState()
{
return (AbilityMovement.LocoState)Child0AbilityMovementInterpolatedStatecharLocoState;
}
public void SetChild0AbilityMovementInterpolatedStatecharLocoState(AbilityMovement.LocoState val, GhostSerializerState serializerState)
{
Child0AbilityMovementInterpolatedStatecharLocoState = (int)val;
}
public void SetChild0AbilityMovementInterpolatedStatecharLocoState(AbilityMovement.LocoState val)
{
Child0AbilityMovementInterpolatedStatecharLocoState = (int)val;
}
public int GetChild0AbilityMovementInterpolatedStatecharLocoTick(GhostDeserializerState deserializerState)
{
return (int)Child0AbilityMovementInterpolatedStatecharLocoTick;
}
public int GetChild0AbilityMovementInterpolatedStatecharLocoTick()
{
return (int)Child0AbilityMovementInterpolatedStatecharLocoTick;
}
public void SetChild0AbilityMovementInterpolatedStatecharLocoTick(int val, GhostSerializerState serializerState)
{
Child0AbilityMovementInterpolatedStatecharLocoTick = (int)val;
}
public void SetChild0AbilityMovementInterpolatedStatecharLocoTick(int val)
{
Child0AbilityMovementInterpolatedStatecharLocoTick = (int)val;
}
public bool GetChild0AbilityMovementInterpolatedStatecrouching(GhostDeserializerState deserializerState)
{
return Child0AbilityMovementInterpolatedStatecrouching!=0;
}
public bool GetChild0AbilityMovementInterpolatedStatecrouching()
{
return Child0AbilityMovementInterpolatedStatecrouching!=0;
}
public void SetChild0AbilityMovementInterpolatedStatecrouching(bool val, GhostSerializerState serializerState)
{
Child0AbilityMovementInterpolatedStatecrouching = val?1u:0;
}
public void SetChild0AbilityMovementInterpolatedStatecrouching(bool val)
{
Child0AbilityMovementInterpolatedStatecrouching = val?1u:0;
}
public AbilityMovement.LocoState GetChild0AbilityMovementPredictedStatelocoState(GhostDeserializerState deserializerState)
{
return (AbilityMovement.LocoState)Child0AbilityMovementPredictedStatelocoState;
}
public AbilityMovement.LocoState GetChild0AbilityMovementPredictedStatelocoState()
{
return (AbilityMovement.LocoState)Child0AbilityMovementPredictedStatelocoState;
}
public void SetChild0AbilityMovementPredictedStatelocoState(AbilityMovement.LocoState val, GhostSerializerState serializerState)
{
Child0AbilityMovementPredictedStatelocoState = (int)val;
}
public void SetChild0AbilityMovementPredictedStatelocoState(AbilityMovement.LocoState val)
{
Child0AbilityMovementPredictedStatelocoState = (int)val;
}
public int GetChild0AbilityMovementPredictedStatelocoStartTick(GhostDeserializerState deserializerState)
{
return (int)Child0AbilityMovementPredictedStatelocoStartTick;
}
public int GetChild0AbilityMovementPredictedStatelocoStartTick()
{
return (int)Child0AbilityMovementPredictedStatelocoStartTick;
}
public void SetChild0AbilityMovementPredictedStatelocoStartTick(int val, GhostSerializerState serializerState)
{
Child0AbilityMovementPredictedStatelocoStartTick = (int)val;
}
public void SetChild0AbilityMovementPredictedStatelocoStartTick(int val)
{
Child0AbilityMovementPredictedStatelocoStartTick = (int)val;
}
public int GetChild0AbilityMovementPredictedStatejumpCount(GhostDeserializerState deserializerState)
{
return (int)Child0AbilityMovementPredictedStatejumpCount;
}
public int GetChild0AbilityMovementPredictedStatejumpCount()
{
return (int)Child0AbilityMovementPredictedStatejumpCount;
}
public void SetChild0AbilityMovementPredictedStatejumpCount(int val, GhostSerializerState serializerState)
{
Child0AbilityMovementPredictedStatejumpCount = (int)val;
}
public void SetChild0AbilityMovementPredictedStatejumpCount(int val)
{
Child0AbilityMovementPredictedStatejumpCount = (int)val;
}
public bool GetChild0AbilityMovementPredictedStatecrouching(GhostDeserializerState deserializerState)
{
return Child0AbilityMovementPredictedStatecrouching!=0;
}
public bool GetChild0AbilityMovementPredictedStatecrouching()
{
return Child0AbilityMovementPredictedStatecrouching!=0;
}
public void SetChild0AbilityMovementPredictedStatecrouching(bool val, GhostSerializerState serializerState)
{
Child0AbilityMovementPredictedStatecrouching = val?1u:0;
}
public void SetChild0AbilityMovementPredictedStatecrouching(bool val)
{
Child0AbilityMovementPredictedStatecrouching = val?1u:0;
}
public Ability.AbilityControl.State GetChild1AbilityAbilityControlbehaviorState(GhostDeserializerState deserializerState)
{
return (Ability.AbilityControl.State)Child1AbilityAbilityControlbehaviorState;
}
public Ability.AbilityControl.State GetChild1AbilityAbilityControlbehaviorState()
{
return (Ability.AbilityControl.State)Child1AbilityAbilityControlbehaviorState;
}
public void SetChild1AbilityAbilityControlbehaviorState(Ability.AbilityControl.State val, GhostSerializerState serializerState)
{
Child1AbilityAbilityControlbehaviorState = (int)val;
}
public void SetChild1AbilityAbilityControlbehaviorState(Ability.AbilityControl.State val)
{
Child1AbilityAbilityControlbehaviorState = (int)val;
}
public bool GetChild1AbilityAbilityControlrequestDeactivate(GhostDeserializerState deserializerState)
{
return Child1AbilityAbilityControlrequestDeactivate!=0;
}
public bool GetChild1AbilityAbilityControlrequestDeactivate()
{
return Child1AbilityAbilityControlrequestDeactivate!=0;
}
public void SetChild1AbilityAbilityControlrequestDeactivate(bool val, GhostSerializerState serializerState)
{
Child1AbilityAbilityControlrequestDeactivate = val?1u:0;
}
public void SetChild1AbilityAbilityControlrequestDeactivate(bool val)
{
Child1AbilityAbilityControlrequestDeactivate = val?1u:0;
}
public int GetChild1AbilitySprintPredictedStateactive(GhostDeserializerState deserializerState)
{
return (int)Child1AbilitySprintPredictedStateactive;
}
public int GetChild1AbilitySprintPredictedStateactive()
{
return (int)Child1AbilitySprintPredictedStateactive;
}
public void SetChild1AbilitySprintPredictedStateactive(int val, GhostSerializerState serializerState)
{
Child1AbilitySprintPredictedStateactive = (int)val;
}
public void SetChild1AbilitySprintPredictedStateactive(int val)
{
Child1AbilitySprintPredictedStateactive = (int)val;
}
public int GetChild1AbilitySprintPredictedStateterminating(GhostDeserializerState deserializerState)
{
return (int)Child1AbilitySprintPredictedStateterminating;
}
public int GetChild1AbilitySprintPredictedStateterminating()
{
return (int)Child1AbilitySprintPredictedStateterminating;
}
public void SetChild1AbilitySprintPredictedStateterminating(int val, GhostSerializerState serializerState)
{
Child1AbilitySprintPredictedStateterminating = (int)val;
}
public void SetChild1AbilitySprintPredictedStateterminating(int val)
{
Child1AbilitySprintPredictedStateterminating = (int)val;
}
public int GetChild1AbilitySprintPredictedStateterminateStartTick(GhostDeserializerState deserializerState)
{
return (int)Child1AbilitySprintPredictedStateterminateStartTick;
}
public int GetChild1AbilitySprintPredictedStateterminateStartTick()
{
return (int)Child1AbilitySprintPredictedStateterminateStartTick;
}
public void SetChild1AbilitySprintPredictedStateterminateStartTick(int val, GhostSerializerState serializerState)
{
Child1AbilitySprintPredictedStateterminateStartTick = (int)val;
}
public void SetChild1AbilitySprintPredictedStateterminateStartTick(int val)
{
Child1AbilitySprintPredictedStateterminateStartTick = (int)val;
}
public Ability.AbilityControl.State GetChild2AbilityAbilityControlbehaviorState(GhostDeserializerState deserializerState)
{
return (Ability.AbilityControl.State)Child2AbilityAbilityControlbehaviorState;
}
public Ability.AbilityControl.State GetChild2AbilityAbilityControlbehaviorState()
{
return (Ability.AbilityControl.State)Child2AbilityAbilityControlbehaviorState;
}
public void SetChild2AbilityAbilityControlbehaviorState(Ability.AbilityControl.State val, GhostSerializerState serializerState)
{
Child2AbilityAbilityControlbehaviorState = (int)val;
}
public void SetChild2AbilityAbilityControlbehaviorState(Ability.AbilityControl.State val)
{
Child2AbilityAbilityControlbehaviorState = (int)val;
}
public bool GetChild2AbilityAbilityControlrequestDeactivate(GhostDeserializerState deserializerState)
{
return Child2AbilityAbilityControlrequestDeactivate!=0;
}
public bool GetChild2AbilityAbilityControlrequestDeactivate()
{
return Child2AbilityAbilityControlrequestDeactivate!=0;
}
public void SetChild2AbilityAbilityControlrequestDeactivate(bool val, GhostSerializerState serializerState)
{
Child2AbilityAbilityControlrequestDeactivate = val?1u:0;
}
public void SetChild2AbilityAbilityControlrequestDeactivate(bool val)
{
Child2AbilityAbilityControlrequestDeactivate = val?1u:0;
}
public Ability.AbilityControl.State GetChild3AbilityAbilityControlbehaviorState(GhostDeserializerState deserializerState)
{
return (Ability.AbilityControl.State)Child3AbilityAbilityControlbehaviorState;
}
public Ability.AbilityControl.State GetChild3AbilityAbilityControlbehaviorState()
{
return (Ability.AbilityControl.State)Child3AbilityAbilityControlbehaviorState;
}
public void SetChild3AbilityAbilityControlbehaviorState(Ability.AbilityControl.State val, GhostSerializerState serializerState)
{
Child3AbilityAbilityControlbehaviorState = (int)val;
}
public void SetChild3AbilityAbilityControlbehaviorState(Ability.AbilityControl.State val)
{
Child3AbilityAbilityControlbehaviorState = (int)val;
}
public bool GetChild3AbilityAbilityControlrequestDeactivate(GhostDeserializerState deserializerState)
{
return Child3AbilityAbilityControlrequestDeactivate!=0;
}
public bool GetChild3AbilityAbilityControlrequestDeactivate()
{
return Child3AbilityAbilityControlrequestDeactivate!=0;
}
public void SetChild3AbilityAbilityControlrequestDeactivate(bool val, GhostSerializerState serializerState)
{
Child3AbilityAbilityControlrequestDeactivate = val?1u:0;
}
public void SetChild3AbilityAbilityControlrequestDeactivate(bool val)
{
Child3AbilityAbilityControlrequestDeactivate = val?1u:0;
}
public void PredictDelta(uint tick, ref Char_TerraformerSnapshotData baseline1, ref Char_TerraformerSnapshotData baseline2)
{
var predictor = new GhostDeltaPredictor(tick, this.tick, baseline1.tick, baseline2.tick);
CharacterInterpolatedDataPositionX = predictor.PredictInt(CharacterInterpolatedDataPositionX, baseline1.CharacterInterpolatedDataPositionX, baseline2.CharacterInterpolatedDataPositionX);
CharacterInterpolatedDataPositionY = predictor.PredictInt(CharacterInterpolatedDataPositionY, baseline1.CharacterInterpolatedDataPositionY, baseline2.CharacterInterpolatedDataPositionY);
CharacterInterpolatedDataPositionZ = predictor.PredictInt(CharacterInterpolatedDataPositionZ, baseline1.CharacterInterpolatedDataPositionZ, baseline2.CharacterInterpolatedDataPositionZ);
CharacterInterpolatedDatarotation = predictor.PredictInt(CharacterInterpolatedDatarotation, baseline1.CharacterInterpolatedDatarotation, baseline2.CharacterInterpolatedDatarotation);
CharacterInterpolatedDataaimYaw = predictor.PredictInt(CharacterInterpolatedDataaimYaw, baseline1.CharacterInterpolatedDataaimYaw, baseline2.CharacterInterpolatedDataaimYaw);
CharacterInterpolatedDataaimPitch = predictor.PredictInt(CharacterInterpolatedDataaimPitch, baseline1.CharacterInterpolatedDataaimPitch, baseline2.CharacterInterpolatedDataaimPitch);
CharacterInterpolatedDatamoveYaw = predictor.PredictInt(CharacterInterpolatedDatamoveYaw, baseline1.CharacterInterpolatedDatamoveYaw, baseline2.CharacterInterpolatedDatamoveYaw);
CharacterInterpolatedDatacharAction = predictor.PredictInt(CharacterInterpolatedDatacharAction, baseline1.CharacterInterpolatedDatacharAction, baseline2.CharacterInterpolatedDatacharAction);
CharacterInterpolatedDatacharActionTick = predictor.PredictInt(CharacterInterpolatedDatacharActionTick, baseline1.CharacterInterpolatedDatacharActionTick, baseline2.CharacterInterpolatedDatacharActionTick);
CharacterInterpolatedDatadamageTick = predictor.PredictInt(CharacterInterpolatedDatadamageTick, baseline1.CharacterInterpolatedDatadamageTick, baseline2.CharacterInterpolatedDatadamageTick);
CharacterInterpolatedDatadamageDirection = predictor.PredictInt(CharacterInterpolatedDatadamageDirection, baseline1.CharacterInterpolatedDatadamageDirection, baseline2.CharacterInterpolatedDatadamageDirection);
CharacterInterpolatedDatasprinting = (uint)predictor.PredictInt((int)CharacterInterpolatedDatasprinting, (int)baseline1.CharacterInterpolatedDatasprinting, (int)baseline2.CharacterInterpolatedDatasprinting);
CharacterInterpolatedDatasprintWeight = predictor.PredictInt(CharacterInterpolatedDatasprintWeight, baseline1.CharacterInterpolatedDatasprintWeight, baseline2.CharacterInterpolatedDatasprintWeight);
CharacterInterpolatedDatacrouchWeight = predictor.PredictInt(CharacterInterpolatedDatacrouchWeight, baseline1.CharacterInterpolatedDatacrouchWeight, baseline2.CharacterInterpolatedDatacrouchWeight);
CharacterInterpolatedDataselectorTargetSource = predictor.PredictInt(CharacterInterpolatedDataselectorTargetSource, baseline1.CharacterInterpolatedDataselectorTargetSource, baseline2.CharacterInterpolatedDataselectorTargetSource);
CharacterInterpolatedDatamoveAngleLocal = predictor.PredictInt(CharacterInterpolatedDatamoveAngleLocal, baseline1.CharacterInterpolatedDatamoveAngleLocal, baseline2.CharacterInterpolatedDatamoveAngleLocal);
CharacterInterpolatedDatashootPoseWeight = predictor.PredictInt(CharacterInterpolatedDatashootPoseWeight, baseline1.CharacterInterpolatedDatashootPoseWeight, baseline2.CharacterInterpolatedDatashootPoseWeight);
CharacterInterpolatedDatalocomotionVectorX = predictor.PredictInt(CharacterInterpolatedDatalocomotionVectorX, baseline1.CharacterInterpolatedDatalocomotionVectorX, baseline2.CharacterInterpolatedDatalocomotionVectorX);
CharacterInterpolatedDatalocomotionVectorY = predictor.PredictInt(CharacterInterpolatedDatalocomotionVectorY, baseline1.CharacterInterpolatedDatalocomotionVectorY, baseline2.CharacterInterpolatedDatalocomotionVectorY);
CharacterInterpolatedDatalocomotionPhase = predictor.PredictInt(CharacterInterpolatedDatalocomotionPhase, baseline1.CharacterInterpolatedDatalocomotionPhase, baseline2.CharacterInterpolatedDatalocomotionPhase);
CharacterInterpolatedDatabanking = predictor.PredictInt(CharacterInterpolatedDatabanking, baseline1.CharacterInterpolatedDatabanking, baseline2.CharacterInterpolatedDatabanking);
CharacterInterpolatedDatalandAnticWeight = predictor.PredictInt(CharacterInterpolatedDatalandAnticWeight, baseline1.CharacterInterpolatedDatalandAnticWeight, baseline2.CharacterInterpolatedDatalandAnticWeight);
CharacterInterpolatedDataturnStartAngle = predictor.PredictInt(CharacterInterpolatedDataturnStartAngle, baseline1.CharacterInterpolatedDataturnStartAngle, baseline2.CharacterInterpolatedDataturnStartAngle);
CharacterInterpolatedDataturnDirection = predictor.PredictInt(CharacterInterpolatedDataturnDirection, baseline1.CharacterInterpolatedDataturnDirection, baseline2.CharacterInterpolatedDataturnDirection);
CharacterInterpolatedDatasquashTime = predictor.PredictInt(CharacterInterpolatedDatasquashTime, baseline1.CharacterInterpolatedDatasquashTime, baseline2.CharacterInterpolatedDatasquashTime);
CharacterInterpolatedDatasquashWeight = predictor.PredictInt(CharacterInterpolatedDatasquashWeight, baseline1.CharacterInterpolatedDatasquashWeight, baseline2.CharacterInterpolatedDatasquashWeight);
CharacterInterpolatedDatainAirTime = predictor.PredictInt(CharacterInterpolatedDatainAirTime, baseline1.CharacterInterpolatedDatainAirTime, baseline2.CharacterInterpolatedDatainAirTime);
CharacterInterpolatedDatajumpTime = predictor.PredictInt(CharacterInterpolatedDatajumpTime, baseline1.CharacterInterpolatedDatajumpTime, baseline2.CharacterInterpolatedDatajumpTime);
CharacterInterpolatedDatasimpleTime = predictor.PredictInt(CharacterInterpolatedDatasimpleTime, baseline1.CharacterInterpolatedDatasimpleTime, baseline2.CharacterInterpolatedDatasimpleTime);
CharacterInterpolatedDatafootIkOffsetX = predictor.PredictInt(CharacterInterpolatedDatafootIkOffsetX, baseline1.CharacterInterpolatedDatafootIkOffsetX, baseline2.CharacterInterpolatedDatafootIkOffsetX);
CharacterInterpolatedDatafootIkOffsetY = predictor.PredictInt(CharacterInterpolatedDatafootIkOffsetY, baseline1.CharacterInterpolatedDatafootIkOffsetY, baseline2.CharacterInterpolatedDatafootIkOffsetY);
CharacterInterpolatedDatafootIkNormalLeftX = predictor.PredictInt(CharacterInterpolatedDatafootIkNormalLeftX, baseline1.CharacterInterpolatedDatafootIkNormalLeftX, baseline2.CharacterInterpolatedDatafootIkNormalLeftX);
CharacterInterpolatedDatafootIkNormalLeftY = predictor.PredictInt(CharacterInterpolatedDatafootIkNormalLeftY, baseline1.CharacterInterpolatedDatafootIkNormalLeftY, baseline2.CharacterInterpolatedDatafootIkNormalLeftY);
CharacterInterpolatedDatafootIkNormalLeftZ = predictor.PredictInt(CharacterInterpolatedDatafootIkNormalLeftZ, baseline1.CharacterInterpolatedDatafootIkNormalLeftZ, baseline2.CharacterInterpolatedDatafootIkNormalLeftZ);
CharacterInterpolatedDatafootIkNormalRightX = predictor.PredictInt(CharacterInterpolatedDatafootIkNormalRightX, baseline1.CharacterInterpolatedDatafootIkNormalRightX, baseline2.CharacterInterpolatedDatafootIkNormalRightX);
CharacterInterpolatedDatafootIkNormalRightY = predictor.PredictInt(CharacterInterpolatedDatafootIkNormalRightY, baseline1.CharacterInterpolatedDatafootIkNormalRightY, baseline2.CharacterInterpolatedDatafootIkNormalRightY);
CharacterInterpolatedDatafootIkNormalRightZ = predictor.PredictInt(CharacterInterpolatedDatafootIkNormalRightZ, baseline1.CharacterInterpolatedDatafootIkNormalRightZ, baseline2.CharacterInterpolatedDatafootIkNormalRightZ);
CharacterInterpolatedDatafootIkWeight = predictor.PredictInt(CharacterInterpolatedDatafootIkWeight, baseline1.CharacterInterpolatedDatafootIkWeight, baseline2.CharacterInterpolatedDatafootIkWeight);
CharacterInterpolatedDatablendOutAim = predictor.PredictInt(CharacterInterpolatedDatablendOutAim, baseline1.CharacterInterpolatedDatablendOutAim, baseline2.CharacterInterpolatedDatablendOutAim);
CharacterPredictedDatatick = predictor.PredictInt(CharacterPredictedDatatick, baseline1.CharacterPredictedDatatick, baseline2.CharacterPredictedDatatick);
CharacterPredictedDatasprinting = (uint)predictor.PredictInt((int)CharacterPredictedDatasprinting, (int)baseline1.CharacterPredictedDatasprinting, (int)baseline2.CharacterPredictedDatasprinting);
CharacterPredictedDatacameraProfile = predictor.PredictInt(CharacterPredictedDatacameraProfile, baseline1.CharacterPredictedDatacameraProfile, baseline2.CharacterPredictedDatacameraProfile);
CharacterPredictedDatadamageTick = predictor.PredictInt(CharacterPredictedDatadamageTick, baseline1.CharacterPredictedDatadamageTick, baseline2.CharacterPredictedDatadamageTick);
CharacterPredictedDatadamageDirectionX = predictor.PredictInt(CharacterPredictedDatadamageDirectionX, baseline1.CharacterPredictedDatadamageDirectionX, baseline2.CharacterPredictedDatadamageDirectionX);
CharacterPredictedDatadamageDirectionY = predictor.PredictInt(CharacterPredictedDatadamageDirectionY, baseline1.CharacterPredictedDatadamageDirectionY, baseline2.CharacterPredictedDatadamageDirectionY);
CharacterPredictedDatadamageDirectionZ = predictor.PredictInt(CharacterPredictedDatadamageDirectionZ, baseline1.CharacterPredictedDatadamageDirectionZ, baseline2.CharacterPredictedDatadamageDirectionZ);
CharacterReplicatedDataheroTypeIndex = predictor.PredictInt(CharacterReplicatedDataheroTypeIndex, baseline1.CharacterReplicatedDataheroTypeIndex, baseline2.CharacterReplicatedDataheroTypeIndex);
CharacterControllerGroundSupportDataSupportedState = predictor.PredictInt(CharacterControllerGroundSupportDataSupportedState, baseline1.CharacterControllerGroundSupportDataSupportedState, baseline2.CharacterControllerGroundSupportDataSupportedState);
HealthStateDatahealth = predictor.PredictInt(HealthStateDatahealth, baseline1.HealthStateDatahealth, baseline2.HealthStateDatahealth);
InventoryStateactiveSlot = predictor.PredictInt(InventoryStateactiveSlot, baseline1.InventoryStateactiveSlot, baseline2.InventoryStateactiveSlot);
PlayerOwnerPlayerIdValue = predictor.PredictInt(PlayerOwnerPlayerIdValue, baseline1.PlayerOwnerPlayerIdValue, baseline2.PlayerOwnerPlayerIdValue);
PlayerControlledStateresetCommandTick = predictor.PredictInt(PlayerControlledStateresetCommandTick, baseline1.PlayerControlledStateresetCommandTick, baseline2.PlayerControlledStateresetCommandTick);
PlayerControlledStateresetCommandLookYaw = predictor.PredictInt(PlayerControlledStateresetCommandLookYaw, baseline1.PlayerControlledStateresetCommandLookYaw, baseline2.PlayerControlledStateresetCommandLookYaw);
PlayerControlledStateresetCommandLookPitch = predictor.PredictInt(PlayerControlledStateresetCommandLookPitch, baseline1.PlayerControlledStateresetCommandLookPitch, baseline2.PlayerControlledStateresetCommandLookPitch);
Child0AbilityAbilityControlbehaviorState = predictor.PredictInt(Child0AbilityAbilityControlbehaviorState, baseline1.Child0AbilityAbilityControlbehaviorState, baseline2.Child0AbilityAbilityControlbehaviorState);
Child0AbilityAbilityControlrequestDeactivate = (uint)predictor.PredictInt((int)Child0AbilityAbilityControlrequestDeactivate, (int)baseline1.Child0AbilityAbilityControlrequestDeactivate, (int)baseline2.Child0AbilityAbilityControlrequestDeactivate);
Child0AbilityMovementInterpolatedStatecharLocoState = predictor.PredictInt(Child0AbilityMovementInterpolatedStatecharLocoState, baseline1.Child0AbilityMovementInterpolatedStatecharLocoState, baseline2.Child0AbilityMovementInterpolatedStatecharLocoState);
Child0AbilityMovementInterpolatedStatecharLocoTick = predictor.PredictInt(Child0AbilityMovementInterpolatedStatecharLocoTick, baseline1.Child0AbilityMovementInterpolatedStatecharLocoTick, baseline2.Child0AbilityMovementInterpolatedStatecharLocoTick);
Child0AbilityMovementInterpolatedStatecrouching = (uint)predictor.PredictInt((int)Child0AbilityMovementInterpolatedStatecrouching, (int)baseline1.Child0AbilityMovementInterpolatedStatecrouching, (int)baseline2.Child0AbilityMovementInterpolatedStatecrouching);
Child0AbilityMovementPredictedStatelocoState = predictor.PredictInt(Child0AbilityMovementPredictedStatelocoState, baseline1.Child0AbilityMovementPredictedStatelocoState, baseline2.Child0AbilityMovementPredictedStatelocoState);
Child0AbilityMovementPredictedStatelocoStartTick = predictor.PredictInt(Child0AbilityMovementPredictedStatelocoStartTick, baseline1.Child0AbilityMovementPredictedStatelocoStartTick, baseline2.Child0AbilityMovementPredictedStatelocoStartTick);
Child0AbilityMovementPredictedStatejumpCount = predictor.PredictInt(Child0AbilityMovementPredictedStatejumpCount, baseline1.Child0AbilityMovementPredictedStatejumpCount, baseline2.Child0AbilityMovementPredictedStatejumpCount);
Child0AbilityMovementPredictedStatecrouching = (uint)predictor.PredictInt((int)Child0AbilityMovementPredictedStatecrouching, (int)baseline1.Child0AbilityMovementPredictedStatecrouching, (int)baseline2.Child0AbilityMovementPredictedStatecrouching);
Child1AbilityAbilityControlbehaviorState = predictor.PredictInt(Child1AbilityAbilityControlbehaviorState, baseline1.Child1AbilityAbilityControlbehaviorState, baseline2.Child1AbilityAbilityControlbehaviorState);
Child1AbilityAbilityControlrequestDeactivate = (uint)predictor.PredictInt((int)Child1AbilityAbilityControlrequestDeactivate, (int)baseline1.Child1AbilityAbilityControlrequestDeactivate, (int)baseline2.Child1AbilityAbilityControlrequestDeactivate);
Child1AbilitySprintPredictedStateactive = predictor.PredictInt(Child1AbilitySprintPredictedStateactive, baseline1.Child1AbilitySprintPredictedStateactive, baseline2.Child1AbilitySprintPredictedStateactive);
Child1AbilitySprintPredictedStateterminating = predictor.PredictInt(Child1AbilitySprintPredictedStateterminating, baseline1.Child1AbilitySprintPredictedStateterminating, baseline2.Child1AbilitySprintPredictedStateterminating);
Child1AbilitySprintPredictedStateterminateStartTick = predictor.PredictInt(Child1AbilitySprintPredictedStateterminateStartTick, baseline1.Child1AbilitySprintPredictedStateterminateStartTick, baseline2.Child1AbilitySprintPredictedStateterminateStartTick);
Child2AbilityAbilityControlbehaviorState = predictor.PredictInt(Child2AbilityAbilityControlbehaviorState, baseline1.Child2AbilityAbilityControlbehaviorState, baseline2.Child2AbilityAbilityControlbehaviorState);
Child2AbilityAbilityControlrequestDeactivate = (uint)predictor.PredictInt((int)Child2AbilityAbilityControlrequestDeactivate, (int)baseline1.Child2AbilityAbilityControlrequestDeactivate, (int)baseline2.Child2AbilityAbilityControlrequestDeactivate);
Child3AbilityAbilityControlbehaviorState = predictor.PredictInt(Child3AbilityAbilityControlbehaviorState, baseline1.Child3AbilityAbilityControlbehaviorState, baseline2.Child3AbilityAbilityControlbehaviorState);
Child3AbilityAbilityControlrequestDeactivate = (uint)predictor.PredictInt((int)Child3AbilityAbilityControlrequestDeactivate, (int)baseline1.Child3AbilityAbilityControlrequestDeactivate, (int)baseline2.Child3AbilityAbilityControlrequestDeactivate);
}
public void Serialize(int networkId, ref Char_TerraformerSnapshotData baseline, DataStreamWriter writer, NetworkCompressionModel compressionModel)
{
changeMask0 = (CharacterInterpolatedDataPositionX != baseline.CharacterInterpolatedDataPositionX ||
CharacterInterpolatedDataPositionY != baseline.CharacterInterpolatedDataPositionY ||
CharacterInterpolatedDataPositionZ != baseline.CharacterInterpolatedDataPositionZ) ? 1u : 0;
changeMask0 |= (CharacterInterpolatedDatarotation != baseline.CharacterInterpolatedDatarotation) ? (1u<<1) : 0;
changeMask0 |= (CharacterInterpolatedDataaimYaw != baseline.CharacterInterpolatedDataaimYaw) ? (1u<<2) : 0;
changeMask0 |= (CharacterInterpolatedDataaimPitch != baseline.CharacterInterpolatedDataaimPitch) ? (1u<<3) : 0;
changeMask0 |= (CharacterInterpolatedDatamoveYaw != baseline.CharacterInterpolatedDatamoveYaw) ? (1u<<4) : 0;
changeMask0 |= (CharacterInterpolatedDatacharAction != baseline.CharacterInterpolatedDatacharAction) ? (1u<<5) : 0;
changeMask0 |= (CharacterInterpolatedDatacharActionTick != baseline.CharacterInterpolatedDatacharActionTick) ? (1u<<6) : 0;
changeMask0 |= (CharacterInterpolatedDatadamageTick != baseline.CharacterInterpolatedDatadamageTick) ? (1u<<7) : 0;
changeMask0 |= (CharacterInterpolatedDatadamageDirection != baseline.CharacterInterpolatedDatadamageDirection) ? (1u<<8) : 0;
changeMask0 |= (CharacterInterpolatedDatasprinting != baseline.CharacterInterpolatedDatasprinting) ? (1u<<9) : 0;
changeMask0 |= (CharacterInterpolatedDatasprintWeight != baseline.CharacterInterpolatedDatasprintWeight) ? (1u<<10) : 0;
changeMask0 |= (CharacterInterpolatedDatacrouchWeight != baseline.CharacterInterpolatedDatacrouchWeight) ? (1u<<11) : 0;
changeMask0 |= (CharacterInterpolatedDataselectorTargetSource != baseline.CharacterInterpolatedDataselectorTargetSource) ? (1u<<12) : 0;
changeMask0 |= (CharacterInterpolatedDatamoveAngleLocal != baseline.CharacterInterpolatedDatamoveAngleLocal) ? (1u<<13) : 0;
changeMask0 |= (CharacterInterpolatedDatashootPoseWeight != baseline.CharacterInterpolatedDatashootPoseWeight) ? (1u<<14) : 0;
changeMask0 |= (CharacterInterpolatedDatalocomotionVectorX != baseline.CharacterInterpolatedDatalocomotionVectorX ||
CharacterInterpolatedDatalocomotionVectorY != baseline.CharacterInterpolatedDatalocomotionVectorY) ? (1u<<15) : 0;
changeMask0 |= (CharacterInterpolatedDatalocomotionPhase != baseline.CharacterInterpolatedDatalocomotionPhase) ? (1u<<16) : 0;
changeMask0 |= (CharacterInterpolatedDatabanking != baseline.CharacterInterpolatedDatabanking) ? (1u<<17) : 0;
changeMask0 |= (CharacterInterpolatedDatalandAnticWeight != baseline.CharacterInterpolatedDatalandAnticWeight) ? (1u<<18) : 0;
changeMask0 |= (CharacterInterpolatedDataturnStartAngle != baseline.CharacterInterpolatedDataturnStartAngle) ? (1u<<19) : 0;
changeMask0 |= (CharacterInterpolatedDataturnDirection != baseline.CharacterInterpolatedDataturnDirection) ? (1u<<20) : 0;
changeMask0 |= (CharacterInterpolatedDatasquashTime != baseline.CharacterInterpolatedDatasquashTime) ? (1u<<21) : 0;
changeMask0 |= (CharacterInterpolatedDatasquashWeight != baseline.CharacterInterpolatedDatasquashWeight) ? (1u<<22) : 0;
changeMask0 |= (CharacterInterpolatedDatainAirTime != baseline.CharacterInterpolatedDatainAirTime) ? (1u<<23) : 0;
changeMask0 |= (CharacterInterpolatedDatajumpTime != baseline.CharacterInterpolatedDatajumpTime) ? (1u<<24) : 0;
changeMask0 |= (CharacterInterpolatedDatasimpleTime != baseline.CharacterInterpolatedDatasimpleTime) ? (1u<<25) : 0;
changeMask0 |= (CharacterInterpolatedDatafootIkOffsetX != baseline.CharacterInterpolatedDatafootIkOffsetX ||
CharacterInterpolatedDatafootIkOffsetY != baseline.CharacterInterpolatedDatafootIkOffsetY) ? (1u<<26) : 0;
changeMask0 |= (CharacterInterpolatedDatafootIkNormalLeftX != baseline.CharacterInterpolatedDatafootIkNormalLeftX ||
CharacterInterpolatedDatafootIkNormalLeftY != baseline.CharacterInterpolatedDatafootIkNormalLeftY ||
CharacterInterpolatedDatafootIkNormalLeftZ != baseline.CharacterInterpolatedDatafootIkNormalLeftZ) ? (1u<<27) : 0;
changeMask0 |= (CharacterInterpolatedDatafootIkNormalRightX != baseline.CharacterInterpolatedDatafootIkNormalRightX ||
CharacterInterpolatedDatafootIkNormalRightY != baseline.CharacterInterpolatedDatafootIkNormalRightY ||
CharacterInterpolatedDatafootIkNormalRightZ != baseline.CharacterInterpolatedDatafootIkNormalRightZ) ? (1u<<28) : 0;
changeMask0 |= (CharacterInterpolatedDatafootIkWeight != baseline.CharacterInterpolatedDatafootIkWeight) ? (1u<<29) : 0;
changeMask0 |= (CharacterInterpolatedDatablendOutAim != baseline.CharacterInterpolatedDatablendOutAim) ? (1u<<30) : 0;
changeMask0 |= (CharacterPredictedDatatick != baseline.CharacterPredictedDatatick) ? (1u<<31) : 0;
changeMask1 = (CharacterPredictedDatapositionX != baseline.CharacterPredictedDatapositionX ||
CharacterPredictedDatapositionY != baseline.CharacterPredictedDatapositionY ||
CharacterPredictedDatapositionZ != baseline.CharacterPredictedDatapositionZ) ? 1u : 0;
changeMask1 |= (CharacterPredictedDatavelocityX != baseline.CharacterPredictedDatavelocityX ||
CharacterPredictedDatavelocityY != baseline.CharacterPredictedDatavelocityY ||
CharacterPredictedDatavelocityZ != baseline.CharacterPredictedDatavelocityZ) ? (1u<<1) : 0;
changeMask1 |= (CharacterPredictedDatasprinting != baseline.CharacterPredictedDatasprinting) ? (1u<<2) : 0;
changeMask1 |= (CharacterPredictedDatacameraProfile != baseline.CharacterPredictedDatacameraProfile) ? (1u<<3) : 0;
changeMask1 |= (CharacterPredictedDatadamageTick != baseline.CharacterPredictedDatadamageTick) ? (1u<<4) : 0;
changeMask1 |= (CharacterPredictedDatadamageDirectionX != baseline.CharacterPredictedDatadamageDirectionX ||
CharacterPredictedDatadamageDirectionY != baseline.CharacterPredictedDatadamageDirectionY ||
CharacterPredictedDatadamageDirectionZ != baseline.CharacterPredictedDatadamageDirectionZ) ? (1u<<5) : 0;
changeMask1 |= (CharacterReplicatedDataheroTypeIndex != baseline.CharacterReplicatedDataheroTypeIndex) ? (1u<<6) : 0;
changeMask1 |= (CharacterControllerGroundSupportDataSurfaceNormalX != baseline.CharacterControllerGroundSupportDataSurfaceNormalX ||
CharacterControllerGroundSupportDataSurfaceNormalY != baseline.CharacterControllerGroundSupportDataSurfaceNormalY ||
CharacterControllerGroundSupportDataSurfaceNormalZ != baseline.CharacterControllerGroundSupportDataSurfaceNormalZ) ? (1u<<7) : 0;
changeMask1 |= (CharacterControllerGroundSupportDataSurfaceVelocityX != baseline.CharacterControllerGroundSupportDataSurfaceVelocityX ||
CharacterControllerGroundSupportDataSurfaceVelocityY != baseline.CharacterControllerGroundSupportDataSurfaceVelocityY ||
CharacterControllerGroundSupportDataSurfaceVelocityZ != baseline.CharacterControllerGroundSupportDataSurfaceVelocityZ) ? (1u<<8) : 0;
changeMask1 |= (CharacterControllerGroundSupportDataSupportedState != baseline.CharacterControllerGroundSupportDataSupportedState) ? (1u<<9) : 0;
changeMask1 |= (CharacterControllerMoveResultMoveResultX != baseline.CharacterControllerMoveResultMoveResultX ||
CharacterControllerMoveResultMoveResultY != baseline.CharacterControllerMoveResultMoveResultY ||
CharacterControllerMoveResultMoveResultZ != baseline.CharacterControllerMoveResultMoveResultZ) ? (1u<<10) : 0;
changeMask1 |= (CharacterControllerVelocityVelocityX != baseline.CharacterControllerVelocityVelocityX ||
CharacterControllerVelocityVelocityY != baseline.CharacterControllerVelocityVelocityY ||
CharacterControllerVelocityVelocityZ != baseline.CharacterControllerVelocityVelocityZ) ? (1u<<11) : 0;
changeMask1 |= (HealthStateDatahealth != baseline.HealthStateDatahealth) ? (1u<<12) : 0;
changeMask1 |= (InventoryStateactiveSlot != baseline.InventoryStateactiveSlot) ? (1u<<13) : 0;
changeMask1 |= (PlayerOwnerPlayerIdValue != baseline.PlayerOwnerPlayerIdValue) ? (1u<<14) : 0;
changeMask1 |= (PlayerControlledStateresetCommandTick != baseline.PlayerControlledStateresetCommandTick) ? (1u<<15) : 0;
changeMask1 |= (PlayerControlledStateresetCommandLookYaw != baseline.PlayerControlledStateresetCommandLookYaw) ? (1u<<16) : 0;
changeMask1 |= (PlayerControlledStateresetCommandLookPitch != baseline.PlayerControlledStateresetCommandLookPitch) ? (1u<<17) : 0;
changeMask1 |= (Child0AbilityAbilityControlbehaviorState != baseline.Child0AbilityAbilityControlbehaviorState) ? (1u<<18) : 0;
changeMask1 |= (Child0AbilityAbilityControlrequestDeactivate != baseline.Child0AbilityAbilityControlrequestDeactivate) ? (1u<<19) : 0;
changeMask1 |= (Child0AbilityMovementInterpolatedStatecharLocoState != baseline.Child0AbilityMovementInterpolatedStatecharLocoState) ? (1u<<20) : 0;
changeMask1 |= (Child0AbilityMovementInterpolatedStatecharLocoTick != baseline.Child0AbilityMovementInterpolatedStatecharLocoTick) ? (1u<<21) : 0;
changeMask1 |= (Child0AbilityMovementInterpolatedStatecrouching != baseline.Child0AbilityMovementInterpolatedStatecrouching) ? (1u<<22) : 0;
changeMask1 |= (Child0AbilityMovementPredictedStatelocoState != baseline.Child0AbilityMovementPredictedStatelocoState) ? (1u<<23) : 0;
changeMask1 |= (Child0AbilityMovementPredictedStatelocoStartTick != baseline.Child0AbilityMovementPredictedStatelocoStartTick) ? (1u<<24) : 0;
changeMask1 |= (Child0AbilityMovementPredictedStatejumpCount != baseline.Child0AbilityMovementPredictedStatejumpCount) ? (1u<<25) : 0;
changeMask1 |= (Child0AbilityMovementPredictedStatecrouching != baseline.Child0AbilityMovementPredictedStatecrouching) ? (1u<<26) : 0;
changeMask1 |= (Child1AbilityAbilityControlbehaviorState != baseline.Child1AbilityAbilityControlbehaviorState) ? (1u<<27) : 0;
changeMask1 |= (Child1AbilityAbilityControlrequestDeactivate != baseline.Child1AbilityAbilityControlrequestDeactivate) ? (1u<<28) : 0;
changeMask1 |= (Child1AbilitySprintPredictedStateactive != baseline.Child1AbilitySprintPredictedStateactive) ? (1u<<29) : 0;
changeMask1 |= (Child1AbilitySprintPredictedStateterminating != baseline.Child1AbilitySprintPredictedStateterminating) ? (1u<<30) : 0;
changeMask1 |= (Child1AbilitySprintPredictedStateterminateStartTick != baseline.Child1AbilitySprintPredictedStateterminateStartTick) ? (1u<<31) : 0;
changeMask2 = (Child2AbilityAbilityControlbehaviorState != baseline.Child2AbilityAbilityControlbehaviorState) ? 1u : 0;
changeMask2 |= (Child2AbilityAbilityControlrequestDeactivate != baseline.Child2AbilityAbilityControlrequestDeactivate) ? (1u<<1) : 0;
changeMask2 |= (Child3AbilityAbilityControlbehaviorState != baseline.Child3AbilityAbilityControlbehaviorState) ? (1u<<2) : 0;
changeMask2 |= (Child3AbilityAbilityControlrequestDeactivate != baseline.Child3AbilityAbilityControlrequestDeactivate) ? (1u<<3) : 0;
writer.WritePackedUIntDelta(changeMask0, baseline.changeMask0, compressionModel);
writer.WritePackedUIntDelta(changeMask1, baseline.changeMask1, compressionModel);
writer.WritePackedUIntDelta(changeMask2, baseline.changeMask2, compressionModel);
bool isPredicted = GetPlayerOwnerPlayerIdValue() == networkId;
writer.WritePackedUInt(isPredicted?1u:0, compressionModel);
if ((changeMask1 & (1 << 6)) != 0)
writer.WritePackedIntDelta(CharacterReplicatedDataheroTypeIndex, baseline.CharacterReplicatedDataheroTypeIndex, compressionModel);
if ((changeMask1 & (1 << 7)) != 0)
{
writer.WritePackedFloatDelta(CharacterControllerGroundSupportDataSurfaceNormalX, baseline.CharacterControllerGroundSupportDataSurfaceNormalX, compressionModel);
writer.WritePackedFloatDelta(CharacterControllerGroundSupportDataSurfaceNormalY, baseline.CharacterControllerGroundSupportDataSurfaceNormalY, compressionModel);
writer.WritePackedFloatDelta(CharacterControllerGroundSupportDataSurfaceNormalZ, baseline.CharacterControllerGroundSupportDataSurfaceNormalZ, compressionModel);
}
if ((changeMask1 & (1 << 8)) != 0)
{
writer.WritePackedFloatDelta(CharacterControllerGroundSupportDataSurfaceVelocityX, baseline.CharacterControllerGroundSupportDataSurfaceVelocityX, compressionModel);
writer.WritePackedFloatDelta(CharacterControllerGroundSupportDataSurfaceVelocityY, baseline.CharacterControllerGroundSupportDataSurfaceVelocityY, compressionModel);
writer.WritePackedFloatDelta(CharacterControllerGroundSupportDataSurfaceVelocityZ, baseline.CharacterControllerGroundSupportDataSurfaceVelocityZ, compressionModel);
}
if ((changeMask1 & (1 << 9)) != 0)
writer.WritePackedIntDelta(CharacterControllerGroundSupportDataSupportedState, baseline.CharacterControllerGroundSupportDataSupportedState, compressionModel);
if ((changeMask1 & (1 << 10)) != 0)
{
writer.WritePackedFloatDelta(CharacterControllerMoveResultMoveResultX, baseline.CharacterControllerMoveResultMoveResultX, compressionModel);
writer.WritePackedFloatDelta(CharacterControllerMoveResultMoveResultY, baseline.CharacterControllerMoveResultMoveResultY, compressionModel);
writer.WritePackedFloatDelta(CharacterControllerMoveResultMoveResultZ, baseline.CharacterControllerMoveResultMoveResultZ, compressionModel);
}
if ((changeMask1 & (1 << 11)) != 0)
{
writer.WritePackedFloatDelta(CharacterControllerVelocityVelocityX, baseline.CharacterControllerVelocityVelocityX, compressionModel);
writer.WritePackedFloatDelta(CharacterControllerVelocityVelocityY, baseline.CharacterControllerVelocityVelocityY, compressionModel);
writer.WritePackedFloatDelta(CharacterControllerVelocityVelocityZ, baseline.CharacterControllerVelocityVelocityZ, compressionModel);
}
if ((changeMask1 & (1 << 12)) != 0)
writer.WritePackedIntDelta(HealthStateDatahealth, baseline.HealthStateDatahealth, compressionModel);
if ((changeMask1 & (1 << 13)) != 0)
writer.WritePackedIntDelta(InventoryStateactiveSlot, baseline.InventoryStateactiveSlot, compressionModel);
if ((changeMask1 & (1 << 14)) != 0)
writer.WritePackedIntDelta(PlayerOwnerPlayerIdValue, baseline.PlayerOwnerPlayerIdValue, compressionModel);
if ((changeMask1 & (1 << 15)) != 0)
writer.WritePackedIntDelta(PlayerControlledStateresetCommandTick, baseline.PlayerControlledStateresetCommandTick, compressionModel);
if ((changeMask1 & (1 << 16)) != 0)
writer.WritePackedIntDelta(PlayerControlledStateresetCommandLookYaw, baseline.PlayerControlledStateresetCommandLookYaw, compressionModel);
if ((changeMask1 & (1 << 17)) != 0)
writer.WritePackedIntDelta(PlayerControlledStateresetCommandLookPitch, baseline.PlayerControlledStateresetCommandLookPitch, compressionModel);
if ((changeMask1 & (1 << 18)) != 0)
writer.WritePackedIntDelta(Child0AbilityAbilityControlbehaviorState, baseline.Child0AbilityAbilityControlbehaviorState, compressionModel);
if ((changeMask1 & (1 << 19)) != 0)
writer.WritePackedUIntDelta(Child0AbilityAbilityControlrequestDeactivate, baseline.Child0AbilityAbilityControlrequestDeactivate, compressionModel);
if ((changeMask1 & (1 << 20)) != 0)
writer.WritePackedIntDelta(Child0AbilityMovementInterpolatedStatecharLocoState, baseline.Child0AbilityMovementInterpolatedStatecharLocoState, compressionModel);
if ((changeMask1 & (1 << 21)) != 0)
writer.WritePackedIntDelta(Child0AbilityMovementInterpolatedStatecharLocoTick, baseline.Child0AbilityMovementInterpolatedStatecharLocoTick, compressionModel);
if ((changeMask1 & (1 << 22)) != 0)
writer.WritePackedUIntDelta(Child0AbilityMovementInterpolatedStatecrouching, baseline.Child0AbilityMovementInterpolatedStatecrouching, compressionModel);
if ((changeMask1 & (1 << 23)) != 0)
writer.WritePackedIntDelta(Child0AbilityMovementPredictedStatelocoState, baseline.Child0AbilityMovementPredictedStatelocoState, compressionModel);
if ((changeMask1 & (1 << 24)) != 0)
writer.WritePackedIntDelta(Child0AbilityMovementPredictedStatelocoStartTick, baseline.Child0AbilityMovementPredictedStatelocoStartTick, compressionModel);
if ((changeMask1 & (1 << 25)) != 0)
writer.WritePackedIntDelta(Child0AbilityMovementPredictedStatejumpCount, baseline.Child0AbilityMovementPredictedStatejumpCount, compressionModel);
if ((changeMask1 & (1 << 26)) != 0)
writer.WritePackedUIntDelta(Child0AbilityMovementPredictedStatecrouching, baseline.Child0AbilityMovementPredictedStatecrouching, compressionModel);
if ((changeMask1 & (1 << 27)) != 0)
writer.WritePackedIntDelta(Child1AbilityAbilityControlbehaviorState, baseline.Child1AbilityAbilityControlbehaviorState, compressionModel);
if ((changeMask1 & (1 << 28)) != 0)
writer.WritePackedUIntDelta(Child1AbilityAbilityControlrequestDeactivate, baseline.Child1AbilityAbilityControlrequestDeactivate, compressionModel);
if ((changeMask1 & (1 << 29)) != 0)
writer.WritePackedIntDelta(Child1AbilitySprintPredictedStateactive, baseline.Child1AbilitySprintPredictedStateactive, compressionModel);
if ((changeMask1 & (1 << 30)) != 0)
writer.WritePackedIntDelta(Child1AbilitySprintPredictedStateterminating, baseline.Child1AbilitySprintPredictedStateterminating, compressionModel);
if ((changeMask1 & (1 << 31)) != 0)
writer.WritePackedIntDelta(Child1AbilitySprintPredictedStateterminateStartTick, baseline.Child1AbilitySprintPredictedStateterminateStartTick, compressionModel);
if ((changeMask2 & (1 << 0)) != 0)
writer.WritePackedIntDelta(Child2AbilityAbilityControlbehaviorState, baseline.Child2AbilityAbilityControlbehaviorState, compressionModel);
if ((changeMask2 & (1 << 1)) != 0)
writer.WritePackedUIntDelta(Child2AbilityAbilityControlrequestDeactivate, baseline.Child2AbilityAbilityControlrequestDeactivate, compressionModel);
if ((changeMask2 & (1 << 2)) != 0)
writer.WritePackedIntDelta(Child3AbilityAbilityControlbehaviorState, baseline.Child3AbilityAbilityControlbehaviorState, compressionModel);
if ((changeMask2 & (1 << 3)) != 0)
writer.WritePackedUIntDelta(Child3AbilityAbilityControlrequestDeactivate, baseline.Child3AbilityAbilityControlrequestDeactivate, compressionModel);
if (isPredicted)
{
if ((changeMask0 & (1 << 31)) != 0)
writer.WritePackedIntDelta(CharacterPredictedDatatick, baseline.CharacterPredictedDatatick, compressionModel);
if ((changeMask1 & (1 << 0)) != 0)
{
writer.WritePackedFloatDelta(CharacterPredictedDatapositionX, baseline.CharacterPredictedDatapositionX, compressionModel);
writer.WritePackedFloatDelta(CharacterPredictedDatapositionY, baseline.CharacterPredictedDatapositionY, compressionModel);
writer.WritePackedFloatDelta(CharacterPredictedDatapositionZ, baseline.CharacterPredictedDatapositionZ, compressionModel);
}
if ((changeMask1 & (1 << 1)) != 0)
{
writer.WritePackedFloatDelta(CharacterPredictedDatavelocityX, baseline.CharacterPredictedDatavelocityX, compressionModel);
writer.WritePackedFloatDelta(CharacterPredictedDatavelocityY, baseline.CharacterPredictedDatavelocityY, compressionModel);
writer.WritePackedFloatDelta(CharacterPredictedDatavelocityZ, baseline.CharacterPredictedDatavelocityZ, compressionModel);
}
if ((changeMask1 & (1 << 2)) != 0)
writer.WritePackedUIntDelta(CharacterPredictedDatasprinting, baseline.CharacterPredictedDatasprinting, compressionModel);
if ((changeMask1 & (1 << 3)) != 0)
writer.WritePackedIntDelta(CharacterPredictedDatacameraProfile, baseline.CharacterPredictedDatacameraProfile, compressionModel);
if ((changeMask1 & (1 << 4)) != 0)
writer.WritePackedIntDelta(CharacterPredictedDatadamageTick, baseline.CharacterPredictedDatadamageTick, compressionModel);
if ((changeMask1 & (1 << 5)) != 0)
{
writer.WritePackedIntDelta(CharacterPredictedDatadamageDirectionX, baseline.CharacterPredictedDatadamageDirectionX, compressionModel);
writer.WritePackedIntDelta(CharacterPredictedDatadamageDirectionY, baseline.CharacterPredictedDatadamageDirectionY, compressionModel);
writer.WritePackedIntDelta(CharacterPredictedDatadamageDirectionZ, baseline.CharacterPredictedDatadamageDirectionZ, compressionModel);
}
}
if (!isPredicted)
{
if ((changeMask0 & (1 << 0)) != 0)
{
writer.WritePackedIntDelta(CharacterInterpolatedDataPositionX, baseline.CharacterInterpolatedDataPositionX, compressionModel);
writer.WritePackedIntDelta(CharacterInterpolatedDataPositionY, baseline.CharacterInterpolatedDataPositionY, compressionModel);
writer.WritePackedIntDelta(CharacterInterpolatedDataPositionZ, baseline.CharacterInterpolatedDataPositionZ, compressionModel);
}
if ((changeMask0 & (1 << 1)) != 0)
writer.WritePackedIntDelta(CharacterInterpolatedDatarotation, baseline.CharacterInterpolatedDatarotation, compressionModel);
if ((changeMask0 & (1 << 2)) != 0)
writer.WritePackedIntDelta(CharacterInterpolatedDataaimYaw, baseline.CharacterInterpolatedDataaimYaw, compressionModel);
if ((changeMask0 & (1 << 3)) != 0)
writer.WritePackedIntDelta(CharacterInterpolatedDataaimPitch, baseline.CharacterInterpolatedDataaimPitch, compressionModel);
if ((changeMask0 & (1 << 4)) != 0)
writer.WritePackedIntDelta(CharacterInterpolatedDatamoveYaw, baseline.CharacterInterpolatedDatamoveYaw, compressionModel);
if ((changeMask0 & (1 << 5)) != 0)
writer.WritePackedIntDelta(CharacterInterpolatedDatacharAction, baseline.CharacterInterpolatedDatacharAction, compressionModel);
if ((changeMask0 & (1 << 6)) != 0)
writer.WritePackedIntDelta(CharacterInterpolatedDatacharActionTick, baseline.CharacterInterpolatedDatacharActionTick, compressionModel);
if ((changeMask0 & (1 << 7)) != 0)
writer.WritePackedIntDelta(CharacterInterpolatedDatadamageTick, baseline.CharacterInterpolatedDatadamageTick, compressionModel);
if ((changeMask0 & (1 << 8)) != 0)
writer.WritePackedIntDelta(CharacterInterpolatedDatadamageDirection, baseline.CharacterInterpolatedDatadamageDirection, compressionModel);
if ((changeMask0 & (1 << 9)) != 0)
writer.WritePackedUIntDelta(CharacterInterpolatedDatasprinting, baseline.CharacterInterpolatedDatasprinting, compressionModel);
if ((changeMask0 & (1 << 10)) != 0)
writer.WritePackedIntDelta(CharacterInterpolatedDatasprintWeight, baseline.CharacterInterpolatedDatasprintWeight, compressionModel);
if ((changeMask0 & (1 << 11)) != 0)
writer.WritePackedIntDelta(CharacterInterpolatedDatacrouchWeight, baseline.CharacterInterpolatedDatacrouchWeight, compressionModel);
if ((changeMask0 & (1 << 12)) != 0)
writer.WritePackedIntDelta(CharacterInterpolatedDataselectorTargetSource, baseline.CharacterInterpolatedDataselectorTargetSource, compressionModel);
if ((changeMask0 & (1 << 13)) != 0)
writer.WritePackedIntDelta(CharacterInterpolatedDatamoveAngleLocal, baseline.CharacterInterpolatedDatamoveAngleLocal, compressionModel);
if ((changeMask0 & (1 << 14)) != 0)
writer.WritePackedIntDelta(CharacterInterpolatedDatashootPoseWeight, baseline.CharacterInterpolatedDatashootPoseWeight, compressionModel);
if ((changeMask0 & (1 << 15)) != 0)
{
writer.WritePackedIntDelta(CharacterInterpolatedDatalocomotionVectorX, baseline.CharacterInterpolatedDatalocomotionVectorX, compressionModel);
writer.WritePackedIntDelta(CharacterInterpolatedDatalocomotionVectorY, baseline.CharacterInterpolatedDatalocomotionVectorY, compressionModel);
}
if ((changeMask0 & (1 << 16)) != 0)
writer.WritePackedIntDelta(CharacterInterpolatedDatalocomotionPhase, baseline.CharacterInterpolatedDatalocomotionPhase, compressionModel);
if ((changeMask0 & (1 << 17)) != 0)
writer.WritePackedIntDelta(CharacterInterpolatedDatabanking, baseline.CharacterInterpolatedDatabanking, compressionModel);
if ((changeMask0 & (1 << 18)) != 0)
writer.WritePackedIntDelta(CharacterInterpolatedDatalandAnticWeight, baseline.CharacterInterpolatedDatalandAnticWeight, compressionModel);
if ((changeMask0 & (1 << 19)) != 0)
writer.WritePackedIntDelta(CharacterInterpolatedDataturnStartAngle, baseline.CharacterInterpolatedDataturnStartAngle, compressionModel);
if ((changeMask0 & (1 << 20)) != 0)
writer.WritePackedIntDelta(CharacterInterpolatedDataturnDirection, baseline.CharacterInterpolatedDataturnDirection, compressionModel);
if ((changeMask0 & (1 << 21)) != 0)
writer.WritePackedIntDelta(CharacterInterpolatedDatasquashTime, baseline.CharacterInterpolatedDatasquashTime, compressionModel);
if ((changeMask0 & (1 << 22)) != 0)
writer.WritePackedIntDelta(CharacterInterpolatedDatasquashWeight, baseline.CharacterInterpolatedDatasquashWeight, compressionModel);
if ((changeMask0 & (1 << 23)) != 0)
writer.WritePackedIntDelta(CharacterInterpolatedDatainAirTime, baseline.CharacterInterpolatedDatainAirTime, compressionModel);
if ((changeMask0 & (1 << 24)) != 0)
writer.WritePackedIntDelta(CharacterInterpolatedDatajumpTime, baseline.CharacterInterpolatedDatajumpTime, compressionModel);
if ((changeMask0 & (1 << 25)) != 0)
writer.WritePackedIntDelta(CharacterInterpolatedDatasimpleTime, baseline.CharacterInterpolatedDatasimpleTime, compressionModel);
if ((changeMask0 & (1 << 26)) != 0)
{
writer.WritePackedIntDelta(CharacterInterpolatedDatafootIkOffsetX, baseline.CharacterInterpolatedDatafootIkOffsetX, compressionModel);
writer.WritePackedIntDelta(CharacterInterpolatedDatafootIkOffsetY, baseline.CharacterInterpolatedDatafootIkOffsetY, compressionModel);
}
if ((changeMask0 & (1 << 27)) != 0)
{
writer.WritePackedIntDelta(CharacterInterpolatedDatafootIkNormalLeftX, baseline.CharacterInterpolatedDatafootIkNormalLeftX, compressionModel);
writer.WritePackedIntDelta(CharacterInterpolatedDatafootIkNormalLeftY, baseline.CharacterInterpolatedDatafootIkNormalLeftY, compressionModel);
writer.WritePackedIntDelta(CharacterInterpolatedDatafootIkNormalLeftZ, baseline.CharacterInterpolatedDatafootIkNormalLeftZ, compressionModel);
}
if ((changeMask0 & (1 << 28)) != 0)
{
writer.WritePackedIntDelta(CharacterInterpolatedDatafootIkNormalRightX, baseline.CharacterInterpolatedDatafootIkNormalRightX, compressionModel);
writer.WritePackedIntDelta(CharacterInterpolatedDatafootIkNormalRightY, baseline.CharacterInterpolatedDatafootIkNormalRightY, compressionModel);
writer.WritePackedIntDelta(CharacterInterpolatedDatafootIkNormalRightZ, baseline.CharacterInterpolatedDatafootIkNormalRightZ, compressionModel);
}
if ((changeMask0 & (1 << 29)) != 0)
writer.WritePackedIntDelta(CharacterInterpolatedDatafootIkWeight, baseline.CharacterInterpolatedDatafootIkWeight, compressionModel);
if ((changeMask0 & (1 << 30)) != 0)
writer.WritePackedIntDelta(CharacterInterpolatedDatablendOutAim, baseline.CharacterInterpolatedDatablendOutAim, compressionModel);
}
}
public void Deserialize(uint tick, ref Char_TerraformerSnapshotData baseline, DataStreamReader reader, ref DataStreamReader.Context ctx,
NetworkCompressionModel compressionModel)
{
this.tick = tick;
changeMask0 = reader.ReadPackedUIntDelta(ref ctx, baseline.changeMask0, compressionModel);
changeMask1 = reader.ReadPackedUIntDelta(ref ctx, baseline.changeMask1, compressionModel);
changeMask2 = reader.ReadPackedUIntDelta(ref ctx, baseline.changeMask2, compressionModel);
bool isPredicted = reader.ReadPackedUInt(ref ctx, compressionModel)!=0;
if ((changeMask1 & (1 << 6)) != 0)
CharacterReplicatedDataheroTypeIndex = reader.ReadPackedIntDelta(ref ctx, baseline.CharacterReplicatedDataheroTypeIndex, compressionModel);
else
CharacterReplicatedDataheroTypeIndex = baseline.CharacterReplicatedDataheroTypeIndex;
if ((changeMask1 & (1 << 7)) != 0)
{
CharacterControllerGroundSupportDataSurfaceNormalX = reader.ReadPackedFloatDelta(ref ctx, baseline.CharacterControllerGroundSupportDataSurfaceNormalX, compressionModel);
CharacterControllerGroundSupportDataSurfaceNormalY = reader.ReadPackedFloatDelta(ref ctx, baseline.CharacterControllerGroundSupportDataSurfaceNormalY, compressionModel);
CharacterControllerGroundSupportDataSurfaceNormalZ = reader.ReadPackedFloatDelta(ref ctx, baseline.CharacterControllerGroundSupportDataSurfaceNormalZ, compressionModel);
}
else
{
CharacterControllerGroundSupportDataSurfaceNormalX = baseline.CharacterControllerGroundSupportDataSurfaceNormalX;
CharacterControllerGroundSupportDataSurfaceNormalY = baseline.CharacterControllerGroundSupportDataSurfaceNormalY;
CharacterControllerGroundSupportDataSurfaceNormalZ = baseline.CharacterControllerGroundSupportDataSurfaceNormalZ;
}
if ((changeMask1 & (1 << 8)) != 0)
{
CharacterControllerGroundSupportDataSurfaceVelocityX = reader.ReadPackedFloatDelta(ref ctx, baseline.CharacterControllerGroundSupportDataSurfaceVelocityX, compressionModel);
CharacterControllerGroundSupportDataSurfaceVelocityY = reader.ReadPackedFloatDelta(ref ctx, baseline.CharacterControllerGroundSupportDataSurfaceVelocityY, compressionModel);
CharacterControllerGroundSupportDataSurfaceVelocityZ = reader.ReadPackedFloatDelta(ref ctx, baseline.CharacterControllerGroundSupportDataSurfaceVelocityZ, compressionModel);
}
else
{
CharacterControllerGroundSupportDataSurfaceVelocityX = baseline.CharacterControllerGroundSupportDataSurfaceVelocityX;
CharacterControllerGroundSupportDataSurfaceVelocityY = baseline.CharacterControllerGroundSupportDataSurfaceVelocityY;
CharacterControllerGroundSupportDataSurfaceVelocityZ = baseline.CharacterControllerGroundSupportDataSurfaceVelocityZ;
}
if ((changeMask1 & (1 << 9)) != 0)
CharacterControllerGroundSupportDataSupportedState = reader.ReadPackedIntDelta(ref ctx, baseline.CharacterControllerGroundSupportDataSupportedState, compressionModel);
else
CharacterControllerGroundSupportDataSupportedState = baseline.CharacterControllerGroundSupportDataSupportedState;
if ((changeMask1 & (1 << 10)) != 0)
{
CharacterControllerMoveResultMoveResultX = reader.ReadPackedFloatDelta(ref ctx, baseline.CharacterControllerMoveResultMoveResultX, compressionModel);
CharacterControllerMoveResultMoveResultY = reader.ReadPackedFloatDelta(ref ctx, baseline.CharacterControllerMoveResultMoveResultY, compressionModel);
CharacterControllerMoveResultMoveResultZ = reader.ReadPackedFloatDelta(ref ctx, baseline.CharacterControllerMoveResultMoveResultZ, compressionModel);
}
else
{
CharacterControllerMoveResultMoveResultX = baseline.CharacterControllerMoveResultMoveResultX;
CharacterControllerMoveResultMoveResultY = baseline.CharacterControllerMoveResultMoveResultY;
CharacterControllerMoveResultMoveResultZ = baseline.CharacterControllerMoveResultMoveResultZ;
}
if ((changeMask1 & (1 << 11)) != 0)
{
CharacterControllerVelocityVelocityX = reader.ReadPackedFloatDelta(ref ctx, baseline.CharacterControllerVelocityVelocityX, compressionModel);
CharacterControllerVelocityVelocityY = reader.ReadPackedFloatDelta(ref ctx, baseline.CharacterControllerVelocityVelocityY, compressionModel);
CharacterControllerVelocityVelocityZ = reader.ReadPackedFloatDelta(ref ctx, baseline.CharacterControllerVelocityVelocityZ, compressionModel);
}
else
{
CharacterControllerVelocityVelocityX = baseline.CharacterControllerVelocityVelocityX;
CharacterControllerVelocityVelocityY = baseline.CharacterControllerVelocityVelocityY;
CharacterControllerVelocityVelocityZ = baseline.CharacterControllerVelocityVelocityZ;
}
if ((changeMask1 & (1 << 12)) != 0)
HealthStateDatahealth = reader.ReadPackedIntDelta(ref ctx, baseline.HealthStateDatahealth, compressionModel);
else
HealthStateDatahealth = baseline.HealthStateDatahealth;
if ((changeMask1 & (1 << 13)) != 0)
InventoryStateactiveSlot = reader.ReadPackedIntDelta(ref ctx, baseline.InventoryStateactiveSlot, compressionModel);
else
InventoryStateactiveSlot = baseline.InventoryStateactiveSlot;
if ((changeMask1 & (1 << 14)) != 0)
PlayerOwnerPlayerIdValue = reader.ReadPackedIntDelta(ref ctx, baseline.PlayerOwnerPlayerIdValue, compressionModel);
else
PlayerOwnerPlayerIdValue = baseline.PlayerOwnerPlayerIdValue;
if ((changeMask1 & (1 << 15)) != 0)
PlayerControlledStateresetCommandTick = reader.ReadPackedIntDelta(ref ctx, baseline.PlayerControlledStateresetCommandTick, compressionModel);
else
PlayerControlledStateresetCommandTick = baseline.PlayerControlledStateresetCommandTick;
if ((changeMask1 & (1 << 16)) != 0)
PlayerControlledStateresetCommandLookYaw = reader.ReadPackedIntDelta(ref ctx, baseline.PlayerControlledStateresetCommandLookYaw, compressionModel);
else
PlayerControlledStateresetCommandLookYaw = baseline.PlayerControlledStateresetCommandLookYaw;
if ((changeMask1 & (1 << 17)) != 0)
PlayerControlledStateresetCommandLookPitch = reader.ReadPackedIntDelta(ref ctx, baseline.PlayerControlledStateresetCommandLookPitch, compressionModel);
else
PlayerControlledStateresetCommandLookPitch = baseline.PlayerControlledStateresetCommandLookPitch;
if ((changeMask1 & (1 << 18)) != 0)
Child0AbilityAbilityControlbehaviorState = reader.ReadPackedIntDelta(ref ctx, baseline.Child0AbilityAbilityControlbehaviorState, compressionModel);
else
Child0AbilityAbilityControlbehaviorState = baseline.Child0AbilityAbilityControlbehaviorState;
if ((changeMask1 & (1 << 19)) != 0)
Child0AbilityAbilityControlrequestDeactivate = reader.ReadPackedUIntDelta(ref ctx, baseline.Child0AbilityAbilityControlrequestDeactivate, compressionModel);
else
Child0AbilityAbilityControlrequestDeactivate = baseline.Child0AbilityAbilityControlrequestDeactivate;
if ((changeMask1 & (1 << 20)) != 0)
Child0AbilityMovementInterpolatedStatecharLocoState = reader.ReadPackedIntDelta(ref ctx, baseline.Child0AbilityMovementInterpolatedStatecharLocoState, compressionModel);
else
Child0AbilityMovementInterpolatedStatecharLocoState = baseline.Child0AbilityMovementInterpolatedStatecharLocoState;
if ((changeMask1 & (1 << 21)) != 0)
Child0AbilityMovementInterpolatedStatecharLocoTick = reader.ReadPackedIntDelta(ref ctx, baseline.Child0AbilityMovementInterpolatedStatecharLocoTick, compressionModel);
else
Child0AbilityMovementInterpolatedStatecharLocoTick = baseline.Child0AbilityMovementInterpolatedStatecharLocoTick;
if ((changeMask1 & (1 << 22)) != 0)
Child0AbilityMovementInterpolatedStatecrouching = reader.ReadPackedUIntDelta(ref ctx, baseline.Child0AbilityMovementInterpolatedStatecrouching, compressionModel);
else
Child0AbilityMovementInterpolatedStatecrouching = baseline.Child0AbilityMovementInterpolatedStatecrouching;
if ((changeMask1 & (1 << 23)) != 0)
Child0AbilityMovementPredictedStatelocoState = reader.ReadPackedIntDelta(ref ctx, baseline.Child0AbilityMovementPredictedStatelocoState, compressionModel);
else
Child0AbilityMovementPredictedStatelocoState = baseline.Child0AbilityMovementPredictedStatelocoState;
if ((changeMask1 & (1 << 24)) != 0)
Child0AbilityMovementPredictedStatelocoStartTick = reader.ReadPackedIntDelta(ref ctx, baseline.Child0AbilityMovementPredictedStatelocoStartTick, compressionModel);
else
Child0AbilityMovementPredictedStatelocoStartTick = baseline.Child0AbilityMovementPredictedStatelocoStartTick;
if ((changeMask1 & (1 << 25)) != 0)
Child0AbilityMovementPredictedStatejumpCount = reader.ReadPackedIntDelta(ref ctx, baseline.Child0AbilityMovementPredictedStatejumpCount, compressionModel);
else
Child0AbilityMovementPredictedStatejumpCount = baseline.Child0AbilityMovementPredictedStatejumpCount;
if ((changeMask1 & (1 << 26)) != 0)
Child0AbilityMovementPredictedStatecrouching = reader.ReadPackedUIntDelta(ref ctx, baseline.Child0AbilityMovementPredictedStatecrouching, compressionModel);
else
Child0AbilityMovementPredictedStatecrouching = baseline.Child0AbilityMovementPredictedStatecrouching;
if ((changeMask1 & (1 << 27)) != 0)
Child1AbilityAbilityControlbehaviorState = reader.ReadPackedIntDelta(ref ctx, baseline.Child1AbilityAbilityControlbehaviorState, compressionModel);
else
Child1AbilityAbilityControlbehaviorState = baseline.Child1AbilityAbilityControlbehaviorState;
if ((changeMask1 & (1 << 28)) != 0)
Child1AbilityAbilityControlrequestDeactivate = reader.ReadPackedUIntDelta(ref ctx, baseline.Child1AbilityAbilityControlrequestDeactivate, compressionModel);
else
Child1AbilityAbilityControlrequestDeactivate = baseline.Child1AbilityAbilityControlrequestDeactivate;
if ((changeMask1 & (1 << 29)) != 0)
Child1AbilitySprintPredictedStateactive = reader.ReadPackedIntDelta(ref ctx, baseline.Child1AbilitySprintPredictedStateactive, compressionModel);
else
Child1AbilitySprintPredictedStateactive = baseline.Child1AbilitySprintPredictedStateactive;
if ((changeMask1 & (1 << 30)) != 0)
Child1AbilitySprintPredictedStateterminating = reader.ReadPackedIntDelta(ref ctx, baseline.Child1AbilitySprintPredictedStateterminating, compressionModel);
else
Child1AbilitySprintPredictedStateterminating = baseline.Child1AbilitySprintPredictedStateterminating;
if ((changeMask1 & (1 << 31)) != 0)
Child1AbilitySprintPredictedStateterminateStartTick = reader.ReadPackedIntDelta(ref ctx, baseline.Child1AbilitySprintPredictedStateterminateStartTick, compressionModel);
else
Child1AbilitySprintPredictedStateterminateStartTick = baseline.Child1AbilitySprintPredictedStateterminateStartTick;
if ((changeMask2 & (1 << 0)) != 0)
Child2AbilityAbilityControlbehaviorState = reader.ReadPackedIntDelta(ref ctx, baseline.Child2AbilityAbilityControlbehaviorState, compressionModel);
else
Child2AbilityAbilityControlbehaviorState = baseline.Child2AbilityAbilityControlbehaviorState;
if ((changeMask2 & (1 << 1)) != 0)
Child2AbilityAbilityControlrequestDeactivate = reader.ReadPackedUIntDelta(ref ctx, baseline.Child2AbilityAbilityControlrequestDeactivate, compressionModel);
else
Child2AbilityAbilityControlrequestDeactivate = baseline.Child2AbilityAbilityControlrequestDeactivate;
if ((changeMask2 & (1 << 2)) != 0)
Child3AbilityAbilityControlbehaviorState = reader.ReadPackedIntDelta(ref ctx, baseline.Child3AbilityAbilityControlbehaviorState, compressionModel);
else
Child3AbilityAbilityControlbehaviorState = baseline.Child3AbilityAbilityControlbehaviorState;
if ((changeMask2 & (1 << 3)) != 0)
Child3AbilityAbilityControlrequestDeactivate = reader.ReadPackedUIntDelta(ref ctx, baseline.Child3AbilityAbilityControlrequestDeactivate, compressionModel);
else
Child3AbilityAbilityControlrequestDeactivate = baseline.Child3AbilityAbilityControlrequestDeactivate;
if (isPredicted)
{
if ((changeMask0 & (1 << 31)) != 0)
CharacterPredictedDatatick = reader.ReadPackedIntDelta(ref ctx, baseline.CharacterPredictedDatatick, compressionModel);
else
CharacterPredictedDatatick = baseline.CharacterPredictedDatatick;
if ((changeMask1 & (1 << 0)) != 0)
{
CharacterPredictedDatapositionX = reader.ReadPackedFloatDelta(ref ctx, baseline.CharacterPredictedDatapositionX, compressionModel);
CharacterPredictedDatapositionY = reader.ReadPackedFloatDelta(ref ctx, baseline.CharacterPredictedDatapositionY, compressionModel);
CharacterPredictedDatapositionZ = reader.ReadPackedFloatDelta(ref ctx, baseline.CharacterPredictedDatapositionZ, compressionModel);
}
else
{
CharacterPredictedDatapositionX = baseline.CharacterPredictedDatapositionX;
CharacterPredictedDatapositionY = baseline.CharacterPredictedDatapositionY;
CharacterPredictedDatapositionZ = baseline.CharacterPredictedDatapositionZ;
}
if ((changeMask1 & (1 << 1)) != 0)
{
CharacterPredictedDatavelocityX = reader.ReadPackedFloatDelta(ref ctx, baseline.CharacterPredictedDatavelocityX, compressionModel);
CharacterPredictedDatavelocityY = reader.ReadPackedFloatDelta(ref ctx, baseline.CharacterPredictedDatavelocityY, compressionModel);
CharacterPredictedDatavelocityZ = reader.ReadPackedFloatDelta(ref ctx, baseline.CharacterPredictedDatavelocityZ, compressionModel);
}
else
{
CharacterPredictedDatavelocityX = baseline.CharacterPredictedDatavelocityX;
CharacterPredictedDatavelocityY = baseline.CharacterPredictedDatavelocityY;
CharacterPredictedDatavelocityZ = baseline.CharacterPredictedDatavelocityZ;
}
if ((changeMask1 & (1 << 2)) != 0)
CharacterPredictedDatasprinting = reader.ReadPackedUIntDelta(ref ctx, baseline.CharacterPredictedDatasprinting, compressionModel);
else
CharacterPredictedDatasprinting = baseline.CharacterPredictedDatasprinting;
if ((changeMask1 & (1 << 3)) != 0)
CharacterPredictedDatacameraProfile = reader.ReadPackedIntDelta(ref ctx, baseline.CharacterPredictedDatacameraProfile, compressionModel);
else
CharacterPredictedDatacameraProfile = baseline.CharacterPredictedDatacameraProfile;
if ((changeMask1 & (1 << 4)) != 0)
CharacterPredictedDatadamageTick = reader.ReadPackedIntDelta(ref ctx, baseline.CharacterPredictedDatadamageTick, compressionModel);
else
CharacterPredictedDatadamageTick = baseline.CharacterPredictedDatadamageTick;
if ((changeMask1 & (1 << 5)) != 0)
{
CharacterPredictedDatadamageDirectionX = reader.ReadPackedIntDelta(ref ctx, baseline.CharacterPredictedDatadamageDirectionX, compressionModel);
CharacterPredictedDatadamageDirectionY = reader.ReadPackedIntDelta(ref ctx, baseline.CharacterPredictedDatadamageDirectionY, compressionModel);
CharacterPredictedDatadamageDirectionZ = reader.ReadPackedIntDelta(ref ctx, baseline.CharacterPredictedDatadamageDirectionZ, compressionModel);
}
else
{
CharacterPredictedDatadamageDirectionX = baseline.CharacterPredictedDatadamageDirectionX;
CharacterPredictedDatadamageDirectionY = baseline.CharacterPredictedDatadamageDirectionY;
CharacterPredictedDatadamageDirectionZ = baseline.CharacterPredictedDatadamageDirectionZ;
}
}
if (!isPredicted)
{
if ((changeMask0 & (1 << 0)) != 0)
{
CharacterInterpolatedDataPositionX = reader.ReadPackedIntDelta(ref ctx, baseline.CharacterInterpolatedDataPositionX, compressionModel);
CharacterInterpolatedDataPositionY = reader.ReadPackedIntDelta(ref ctx, baseline.CharacterInterpolatedDataPositionY, compressionModel);
CharacterInterpolatedDataPositionZ = reader.ReadPackedIntDelta(ref ctx, baseline.CharacterInterpolatedDataPositionZ, compressionModel);
}
else
{
CharacterInterpolatedDataPositionX = baseline.CharacterInterpolatedDataPositionX;
CharacterInterpolatedDataPositionY = baseline.CharacterInterpolatedDataPositionY;
CharacterInterpolatedDataPositionZ = baseline.CharacterInterpolatedDataPositionZ;
}
if ((changeMask0 & (1 << 1)) != 0)
CharacterInterpolatedDatarotation = reader.ReadPackedIntDelta(ref ctx, baseline.CharacterInterpolatedDatarotation, compressionModel);
else
CharacterInterpolatedDatarotation = baseline.CharacterInterpolatedDatarotation;
if ((changeMask0 & (1 << 2)) != 0)
CharacterInterpolatedDataaimYaw = reader.ReadPackedIntDelta(ref ctx, baseline.CharacterInterpolatedDataaimYaw, compressionModel);
else
CharacterInterpolatedDataaimYaw = baseline.CharacterInterpolatedDataaimYaw;
if ((changeMask0 & (1 << 3)) != 0)
CharacterInterpolatedDataaimPitch = reader.ReadPackedIntDelta(ref ctx, baseline.CharacterInterpolatedDataaimPitch, compressionModel);
else
CharacterInterpolatedDataaimPitch = baseline.CharacterInterpolatedDataaimPitch;
if ((changeMask0 & (1 << 4)) != 0)
CharacterInterpolatedDatamoveYaw = reader.ReadPackedIntDelta(ref ctx, baseline.CharacterInterpolatedDatamoveYaw, compressionModel);
else
CharacterInterpolatedDatamoveYaw = baseline.CharacterInterpolatedDatamoveYaw;
if ((changeMask0 & (1 << 5)) != 0)
CharacterInterpolatedDatacharAction = reader.ReadPackedIntDelta(ref ctx, baseline.CharacterInterpolatedDatacharAction, compressionModel);
else
CharacterInterpolatedDatacharAction = baseline.CharacterInterpolatedDatacharAction;
if ((changeMask0 & (1 << 6)) != 0)
CharacterInterpolatedDatacharActionTick = reader.ReadPackedIntDelta(ref ctx, baseline.CharacterInterpolatedDatacharActionTick, compressionModel);
else
CharacterInterpolatedDatacharActionTick = baseline.CharacterInterpolatedDatacharActionTick;
if ((changeMask0 & (1 << 7)) != 0)
CharacterInterpolatedDatadamageTick = reader.ReadPackedIntDelta(ref ctx, baseline.CharacterInterpolatedDatadamageTick, compressionModel);
else
CharacterInterpolatedDatadamageTick = baseline.CharacterInterpolatedDatadamageTick;
if ((changeMask0 & (1 << 8)) != 0)
CharacterInterpolatedDatadamageDirection = reader.ReadPackedIntDelta(ref ctx, baseline.CharacterInterpolatedDatadamageDirection, compressionModel);
else
CharacterInterpolatedDatadamageDirection = baseline.CharacterInterpolatedDatadamageDirection;
if ((changeMask0 & (1 << 9)) != 0)
CharacterInterpolatedDatasprinting = reader.ReadPackedUIntDelta(ref ctx, baseline.CharacterInterpolatedDatasprinting, compressionModel);
else
CharacterInterpolatedDatasprinting = baseline.CharacterInterpolatedDatasprinting;
if ((changeMask0 & (1 << 10)) != 0)
CharacterInterpolatedDatasprintWeight = reader.ReadPackedIntDelta(ref ctx, baseline.CharacterInterpolatedDatasprintWeight, compressionModel);
else
CharacterInterpolatedDatasprintWeight = baseline.CharacterInterpolatedDatasprintWeight;
if ((changeMask0 & (1 << 11)) != 0)
CharacterInterpolatedDatacrouchWeight = reader.ReadPackedIntDelta(ref ctx, baseline.CharacterInterpolatedDatacrouchWeight, compressionModel);
else
CharacterInterpolatedDatacrouchWeight = baseline.CharacterInterpolatedDatacrouchWeight;
if ((changeMask0 & (1 << 12)) != 0)
CharacterInterpolatedDataselectorTargetSource = reader.ReadPackedIntDelta(ref ctx, baseline.CharacterInterpolatedDataselectorTargetSource, compressionModel);
else
CharacterInterpolatedDataselectorTargetSource = baseline.CharacterInterpolatedDataselectorTargetSource;
if ((changeMask0 & (1 << 13)) != 0)
CharacterInterpolatedDatamoveAngleLocal = reader.ReadPackedIntDelta(ref ctx, baseline.CharacterInterpolatedDatamoveAngleLocal, compressionModel);
else
CharacterInterpolatedDatamoveAngleLocal = baseline.CharacterInterpolatedDatamoveAngleLocal;
if ((changeMask0 & (1 << 14)) != 0)
CharacterInterpolatedDatashootPoseWeight = reader.ReadPackedIntDelta(ref ctx, baseline.CharacterInterpolatedDatashootPoseWeight, compressionModel);
else
CharacterInterpolatedDatashootPoseWeight = baseline.CharacterInterpolatedDatashootPoseWeight;
if ((changeMask0 & (1 << 15)) != 0)
{
CharacterInterpolatedDatalocomotionVectorX = reader.ReadPackedIntDelta(ref ctx, baseline.CharacterInterpolatedDatalocomotionVectorX, compressionModel);
CharacterInterpolatedDatalocomotionVectorY = reader.ReadPackedIntDelta(ref ctx, baseline.CharacterInterpolatedDatalocomotionVectorY, compressionModel);
}
else
{
CharacterInterpolatedDatalocomotionVectorX = baseline.CharacterInterpolatedDatalocomotionVectorX;
CharacterInterpolatedDatalocomotionVectorY = baseline.CharacterInterpolatedDatalocomotionVectorY;
}
if ((changeMask0 & (1 << 16)) != 0)
CharacterInterpolatedDatalocomotionPhase = reader.ReadPackedIntDelta(ref ctx, baseline.CharacterInterpolatedDatalocomotionPhase, compressionModel);
else
CharacterInterpolatedDatalocomotionPhase = baseline.CharacterInterpolatedDatalocomotionPhase;
if ((changeMask0 & (1 << 17)) != 0)
CharacterInterpolatedDatabanking = reader.ReadPackedIntDelta(ref ctx, baseline.CharacterInterpolatedDatabanking, compressionModel);
else
CharacterInterpolatedDatabanking = baseline.CharacterInterpolatedDatabanking;
if ((changeMask0 & (1 << 18)) != 0)
CharacterInterpolatedDatalandAnticWeight = reader.ReadPackedIntDelta(ref ctx, baseline.CharacterInterpolatedDatalandAnticWeight, compressionModel);
else
CharacterInterpolatedDatalandAnticWeight = baseline.CharacterInterpolatedDatalandAnticWeight;
if ((changeMask0 & (1 << 19)) != 0)
CharacterInterpolatedDataturnStartAngle = reader.ReadPackedIntDelta(ref ctx, baseline.CharacterInterpolatedDataturnStartAngle, compressionModel);
else
CharacterInterpolatedDataturnStartAngle = baseline.CharacterInterpolatedDataturnStartAngle;
if ((changeMask0 & (1 << 20)) != 0)
CharacterInterpolatedDataturnDirection = reader.ReadPackedIntDelta(ref ctx, baseline.CharacterInterpolatedDataturnDirection, compressionModel);
else
CharacterInterpolatedDataturnDirection = baseline.CharacterInterpolatedDataturnDirection;
if ((changeMask0 & (1 << 21)) != 0)
CharacterInterpolatedDatasquashTime = reader.ReadPackedIntDelta(ref ctx, baseline.CharacterInterpolatedDatasquashTime, compressionModel);
else
CharacterInterpolatedDatasquashTime = baseline.CharacterInterpolatedDatasquashTime;
if ((changeMask0 & (1 << 22)) != 0)
CharacterInterpolatedDatasquashWeight = reader.ReadPackedIntDelta(ref ctx, baseline.CharacterInterpolatedDatasquashWeight, compressionModel);
else
CharacterInterpolatedDatasquashWeight = baseline.CharacterInterpolatedDatasquashWeight;
if ((changeMask0 & (1 << 23)) != 0)
CharacterInterpolatedDatainAirTime = reader.ReadPackedIntDelta(ref ctx, baseline.CharacterInterpolatedDatainAirTime, compressionModel);
else
CharacterInterpolatedDatainAirTime = baseline.CharacterInterpolatedDatainAirTime;
if ((changeMask0 & (1 << 24)) != 0)
CharacterInterpolatedDatajumpTime = reader.ReadPackedIntDelta(ref ctx, baseline.CharacterInterpolatedDatajumpTime, compressionModel);
else
CharacterInterpolatedDatajumpTime = baseline.CharacterInterpolatedDatajumpTime;
if ((changeMask0 & (1 << 25)) != 0)
CharacterInterpolatedDatasimpleTime = reader.ReadPackedIntDelta(ref ctx, baseline.CharacterInterpolatedDatasimpleTime, compressionModel);
else
CharacterInterpolatedDatasimpleTime = baseline.CharacterInterpolatedDatasimpleTime;
if ((changeMask0 & (1 << 26)) != 0)
{
CharacterInterpolatedDatafootIkOffsetX = reader.ReadPackedIntDelta(ref ctx, baseline.CharacterInterpolatedDatafootIkOffsetX, compressionModel);
CharacterInterpolatedDatafootIkOffsetY = reader.ReadPackedIntDelta(ref ctx, baseline.CharacterInterpolatedDatafootIkOffsetY, compressionModel);
}
else
{
CharacterInterpolatedDatafootIkOffsetX = baseline.CharacterInterpolatedDatafootIkOffsetX;
CharacterInterpolatedDatafootIkOffsetY = baseline.CharacterInterpolatedDatafootIkOffsetY;
}
if ((changeMask0 & (1 << 27)) != 0)
{
CharacterInterpolatedDatafootIkNormalLeftX = reader.ReadPackedIntDelta(ref ctx, baseline.CharacterInterpolatedDatafootIkNormalLeftX, compressionModel);
CharacterInterpolatedDatafootIkNormalLeftY = reader.ReadPackedIntDelta(ref ctx, baseline.CharacterInterpolatedDatafootIkNormalLeftY, compressionModel);
CharacterInterpolatedDatafootIkNormalLeftZ = reader.ReadPackedIntDelta(ref ctx, baseline.CharacterInterpolatedDatafootIkNormalLeftZ, compressionModel);
}
else
{
CharacterInterpolatedDatafootIkNormalLeftX = baseline.CharacterInterpolatedDatafootIkNormalLeftX;
CharacterInterpolatedDatafootIkNormalLeftY = baseline.CharacterInterpolatedDatafootIkNormalLeftY;
CharacterInterpolatedDatafootIkNormalLeftZ = baseline.CharacterInterpolatedDatafootIkNormalLeftZ;
}
if ((changeMask0 & (1 << 28)) != 0)
{
CharacterInterpolatedDatafootIkNormalRightX = reader.ReadPackedIntDelta(ref ctx, baseline.CharacterInterpolatedDatafootIkNormalRightX, compressionModel);
CharacterInterpolatedDatafootIkNormalRightY = reader.ReadPackedIntDelta(ref ctx, baseline.CharacterInterpolatedDatafootIkNormalRightY, compressionModel);
CharacterInterpolatedDatafootIkNormalRightZ = reader.ReadPackedIntDelta(ref ctx, baseline.CharacterInterpolatedDatafootIkNormalRightZ, compressionModel);
}
else
{
CharacterInterpolatedDatafootIkNormalRightX = baseline.CharacterInterpolatedDatafootIkNormalRightX;
CharacterInterpolatedDatafootIkNormalRightY = baseline.CharacterInterpolatedDatafootIkNormalRightY;
CharacterInterpolatedDatafootIkNormalRightZ = baseline.CharacterInterpolatedDatafootIkNormalRightZ;
}
if ((changeMask0 & (1 << 29)) != 0)
CharacterInterpolatedDatafootIkWeight = reader.ReadPackedIntDelta(ref ctx, baseline.CharacterInterpolatedDatafootIkWeight, compressionModel);
else
CharacterInterpolatedDatafootIkWeight = baseline.CharacterInterpolatedDatafootIkWeight;
if ((changeMask0 & (1 << 30)) != 0)
CharacterInterpolatedDatablendOutAim = reader.ReadPackedIntDelta(ref ctx, baseline.CharacterInterpolatedDatablendOutAim, compressionModel);
else
CharacterInterpolatedDatablendOutAim = baseline.CharacterInterpolatedDatablendOutAim;
}
}
public void Interpolate(ref Char_TerraformerSnapshotData target, float factor)
{
SetCharacterInterpolatedDataPosition(math.lerp(GetCharacterInterpolatedDataPosition(), target.GetCharacterInterpolatedDataPosition(), factor));
SetCharacterInterpolatedDatarotation(Mathf.LerpAngle(GetCharacterInterpolatedDatarotation(), target.GetCharacterInterpolatedDatarotation(), factor));
SetCharacterInterpolatedDataaimYaw(Mathf.LerpAngle(GetCharacterInterpolatedDataaimYaw(), target.GetCharacterInterpolatedDataaimYaw(), factor));
SetCharacterInterpolatedDataaimPitch(Mathf.LerpAngle(GetCharacterInterpolatedDataaimPitch(), target.GetCharacterInterpolatedDataaimPitch(), factor));
SetCharacterInterpolatedDatamoveYaw(Mathf.LerpAngle(GetCharacterInterpolatedDatamoveYaw(), target.GetCharacterInterpolatedDatamoveYaw(), factor));
SetCharacterInterpolatedDatasprintWeight(math.lerp(GetCharacterInterpolatedDatasprintWeight(), target.GetCharacterInterpolatedDatasprintWeight(), factor));
SetCharacterInterpolatedDatacrouchWeight(math.lerp(GetCharacterInterpolatedDatacrouchWeight(), target.GetCharacterInterpolatedDatacrouchWeight(), factor));
SetCharacterInterpolatedDatamoveAngleLocal(Mathf.LerpAngle(GetCharacterInterpolatedDatamoveAngleLocal(), target.GetCharacterInterpolatedDatamoveAngleLocal(), factor));
SetCharacterInterpolatedDatashootPoseWeight(math.lerp(GetCharacterInterpolatedDatashootPoseWeight(), target.GetCharacterInterpolatedDatashootPoseWeight(), factor));
SetCharacterInterpolatedDatalocomotionVector(math.lerp(GetCharacterInterpolatedDatalocomotionVector(), target.GetCharacterInterpolatedDatalocomotionVector(), factor));
SetCharacterInterpolatedDatalocomotionPhase(math.lerp(GetCharacterInterpolatedDatalocomotionPhase(), target.GetCharacterInterpolatedDatalocomotionPhase(), factor));
SetCharacterInterpolatedDatabanking(math.lerp(GetCharacterInterpolatedDatabanking(), target.GetCharacterInterpolatedDatabanking(), factor));
SetCharacterInterpolatedDatalandAnticWeight(math.lerp(GetCharacterInterpolatedDatalandAnticWeight(), target.GetCharacterInterpolatedDatalandAnticWeight(), factor));
SetCharacterInterpolatedDatasquashTime(math.lerp(GetCharacterInterpolatedDatasquashTime(), target.GetCharacterInterpolatedDatasquashTime(), factor));
SetCharacterInterpolatedDatasquashWeight(math.lerp(GetCharacterInterpolatedDatasquashWeight(), target.GetCharacterInterpolatedDatasquashWeight(), factor));
SetCharacterInterpolatedDatainAirTime(math.lerp(GetCharacterInterpolatedDatainAirTime(), target.GetCharacterInterpolatedDatainAirTime(), factor));
SetCharacterInterpolatedDatajumpTime(math.lerp(GetCharacterInterpolatedDatajumpTime(), target.GetCharacterInterpolatedDatajumpTime(), factor));
SetCharacterInterpolatedDatasimpleTime(math.lerp(GetCharacterInterpolatedDatasimpleTime(), target.GetCharacterInterpolatedDatasimpleTime(), factor));
SetCharacterInterpolatedDatafootIkOffset(math.lerp(GetCharacterInterpolatedDatafootIkOffset(), target.GetCharacterInterpolatedDatafootIkOffset(), factor));
SetCharacterInterpolatedDatafootIkNormalLeft(math.lerp(GetCharacterInterpolatedDatafootIkNormalLeft(), target.GetCharacterInterpolatedDatafootIkNormalLeft(), factor));
SetCharacterInterpolatedDatafootIkNormalRight(math.lerp(GetCharacterInterpolatedDatafootIkNormalRight(), target.GetCharacterInterpolatedDatafootIkNormalRight(), factor));
SetCharacterInterpolatedDatafootIkWeight(math.lerp(GetCharacterInterpolatedDatafootIkWeight(), target.GetCharacterInterpolatedDatafootIkWeight(), factor));
SetCharacterInterpolatedDatablendOutAim(math.lerp(GetCharacterInterpolatedDatablendOutAim(), target.GetCharacterInterpolatedDatablendOutAim(), factor));
}
}
| 65.995466 | 267 | 0.773048 | [
"MIT"
] | The-ULTIMATE-MULTIPLAYER-EXPERIENCE/Ultimate-Archery-Multiplayer-Unity-Game | DOTSSample-master/Assets/Scripts/Networking/Generated/Char_TerraformerSnapshotData.cs | 131,001 | 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("Collector_Livestream")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Collector_Livestream")]
[assembly: AssemblyCopyright("Copyright © 2020")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("43c6ff78-dcad-4588-9ad3-33da97aca3b5")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.054054 | 84 | 0.75071 | [
"Unlicense"
] | slogslog/Coding-Kurzgeschichten | Livestreams/Collector_Livestream/Collector_Livestream/Properties/AssemblyInfo.cs | 1,411 | C# |
// Copyright 2017 Quintonn Rothmann
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.ComponentModel.DataAnnotations;
namespace BasicAuthentication.Core.Security
{
public class RefreshToken
{
public string Id { get; set; }
[Required]
[MaxLength(50)]
public string Subject { get; set; }
[Required]
[MaxLength(50)]
public string ClientId { get; set; }
public DateTime IssuedUtc { get; set; }
public DateTime ExpiresUtc { get; set; }
[Required]
public string ProtectedTicket { get; set; }
}
}
| 52.870968 | 465 | 0.718731 | [
"MIT"
] | quintonn/QBic | BasicAuthentication.Core/Security/RefreshToken.cs | 1,641 | C# |
using Vortice.Direct3D12;
namespace RayTracingTutorial13.Structs
{
public struct PipelineConfig
{
public RaytracingPipelineConfig config;
public StateSubObject suboject;
public PipelineConfig(int maxTraceRecursionDepth)
{
config = new RaytracingPipelineConfig(maxTraceRecursionDepth);
suboject = new StateSubObject(config);
}
}
}
| 22.777778 | 74 | 0.680488 | [
"MIT"
] | Jorgemagic/CSharpDirectXRaytracing | 13-SecondRayType/RTX/Structs/PipelineConfig.cs | 412 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace Azure.Messaging.ServiceBus
{
/// <summary>
/// The <see cref="ProcessSessionMessageEventArgs"/> contain event args that
/// are specific to the <see cref="ServiceBusReceivedMessage"/> and session that
/// is being processed.
/// </summary>
public class ProcessSessionMessageEventArgs : EventArgs
{
/// <summary>
/// Gets the <see cref="ServiceBusReceivedMessage"/> to be processed.
/// </summary>
public ServiceBusReceivedMessage Message { get; }
/// <summary>
/// Gets the <see cref="System.Threading.CancellationToken"/> instance which
/// will be cancelled when <see cref="ServiceBusSessionProcessor.StopProcessingAsync"/>
/// is called, or when the session lock has been lost, or if <see cref="ReleaseSession"/> is called.
/// </summary>
public CancellationToken CancellationToken { get; }
internal ConcurrentDictionary<ServiceBusReceivedMessage, byte> Messages => _receiveActions.Messages;
/// <summary>
/// The <see cref="ServiceBusSessionReceiver"/> that will be used for all settlement methods for the args.
/// </summary>
private readonly ServiceBusSessionReceiver _sessionReceiver;
private readonly SessionReceiverManager _manager;
private readonly ProcessorReceiveActions _receiveActions;
/// <summary>
/// Gets the Session Id associated with the <see cref="ServiceBusReceivedMessage"/>.
/// </summary>
public string SessionId => _sessionReceiver.SessionId;
/// <summary>
/// Gets the DateTime that the session corresponding to
/// the <see cref="ServiceBusReceivedMessage"/> is locked until.
/// </summary>
public DateTimeOffset SessionLockedUntil => _sessionReceiver.SessionLockedUntil;
/// <summary>
/// Initializes a new instance of the <see cref="ProcessSessionMessageEventArgs"/> class.
/// </summary>
///
/// <param name="message">The current <see cref="ServiceBusReceivedMessage"/>.</param>
/// <param name="receiver">The <see cref="ServiceBusSessionReceiver"/> that will be used for all settlement methods
/// for the args.</param>
/// <param name="cancellationToken">The processor's <see cref="System.Threading.CancellationToken"/> instance which will be cancelled in the event that <see cref="ServiceBusProcessor.StopProcessingAsync"/> is called.</param>
public ProcessSessionMessageEventArgs(
ServiceBusReceivedMessage message,
ServiceBusSessionReceiver receiver,
CancellationToken cancellationToken) : this(message, manager: null, cancellationToken)
{
_sessionReceiver = receiver;
}
internal ProcessSessionMessageEventArgs(
ServiceBusReceivedMessage message,
SessionReceiverManager manager,
CancellationToken cancellationToken)
{
Message = message;
_manager = manager;
// manager would be null in scenarios where customers are using the public constructor for testing purposes.
_sessionReceiver = (ServiceBusSessionReceiver) _manager?.Receiver;
_receiveActions = new ProcessorReceiveActions(message, manager, false);
CancellationToken = cancellationToken;
}
/// <inheritdoc cref="ServiceBusSessionReceiver.GetSessionStateAsync(CancellationToken)"/>
public virtual async Task<BinaryData> GetSessionStateAsync(
CancellationToken cancellationToken = default) =>
await _sessionReceiver.GetSessionStateAsync(cancellationToken).ConfigureAwait(false);
/// <inheritdoc cref="ServiceBusSessionReceiver.SetSessionStateAsync(BinaryData, CancellationToken)"/>
public virtual async Task SetSessionStateAsync(
BinaryData sessionState,
CancellationToken cancellationToken = default) =>
await _sessionReceiver.SetSessionStateAsync(sessionState, cancellationToken).ConfigureAwait(false);
/// <inheritdoc cref="ServiceBusReceiver.AbandonMessageAsync(ServiceBusReceivedMessage, IDictionary{string, object}, CancellationToken)"/>
public virtual async Task AbandonMessageAsync(
ServiceBusReceivedMessage message,
IDictionary<string, object> propertiesToModify = default,
CancellationToken cancellationToken = default)
{
await _sessionReceiver.AbandonMessageAsync(message, propertiesToModify, cancellationToken)
.ConfigureAwait(false);
message.IsSettled = true;
}
/// <inheritdoc cref="ServiceBusReceiver.CompleteMessageAsync(ServiceBusReceivedMessage, CancellationToken)"/>
public virtual async Task CompleteMessageAsync(
ServiceBusReceivedMessage message,
CancellationToken cancellationToken = default)
{
await _sessionReceiver.CompleteMessageAsync(
message,
cancellationToken)
.ConfigureAwait(false);
message.IsSettled = true;
}
/// <inheritdoc cref="ServiceBusReceiver.DeadLetterMessageAsync(ServiceBusReceivedMessage, string, string, CancellationToken)"/>
public virtual async Task DeadLetterMessageAsync(
ServiceBusReceivedMessage message,
string deadLetterReason,
string deadLetterErrorDescription = default,
CancellationToken cancellationToken = default)
{
await _sessionReceiver.DeadLetterMessageAsync(
message,
deadLetterReason,
deadLetterErrorDescription,
cancellationToken)
.ConfigureAwait(false);
message.IsSettled = true;
}
/// <inheritdoc cref="ServiceBusReceiver.DeadLetterMessageAsync(ServiceBusReceivedMessage, IDictionary{string, object}, CancellationToken)"/>
public virtual async Task DeadLetterMessageAsync(
ServiceBusReceivedMessage message,
IDictionary<string, object> propertiesToModify = default,
CancellationToken cancellationToken = default)
{
await _sessionReceiver.DeadLetterMessageAsync(
message,
propertiesToModify,
cancellationToken)
.ConfigureAwait(false);
message.IsSettled = true;
}
/// <inheritdoc cref="ServiceBusReceiver.DeferMessageAsync(ServiceBusReceivedMessage, IDictionary{string, object}, CancellationToken)"/>
public virtual async Task DeferMessageAsync(
ServiceBusReceivedMessage message,
IDictionary<string, object> propertiesToModify = default,
CancellationToken cancellationToken = default)
{
await _sessionReceiver.DeferMessageAsync(
message,
propertiesToModify,
cancellationToken)
.ConfigureAwait(false);
message.IsSettled = true;
}
/// <summary>
/// Releases the session that is being processed. No new receives will be initiated for the session before the
/// session is closed. Any already received messages will still be delivered to the user message handler, and in-flight message handlers
/// will be allowed to complete. Messages will still be completed automatically if <see cref="ServiceBusSessionProcessorOptions.AutoCompleteMessages"/>
/// is <c>true</c>.
/// The session may end up being reopened for processing immediately after closing if there are messages remaining in the session (
/// This depends on what other session messages may be in the queue or subscription).
/// </summary>
public virtual void ReleaseSession() =>
// manager will be null if instance created using the public constructor which is exposed for testing purposes
_manager?.CancelSession();
///<inheritdoc cref="ServiceBusSessionReceiver.RenewSessionLockAsync(CancellationToken)"/>
public virtual async Task RenewSessionLockAsync(CancellationToken cancellationToken = default)
{
await _sessionReceiver.RenewSessionLockAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets a <see cref="ProcessorReceiveActions"/> instance which enables receiving additional messages within the scope of the current event.
/// </summary>
public virtual ProcessorReceiveActions GetReceiveActions() => _receiveActions;
internal void EndExecutionScope() => _receiveActions.EndExecutionScope();
}
} | 48.643243 | 232 | 0.676742 | [
"MIT"
] | ChenTanyi/azure-sdk-for-net | sdk/servicebus/Azure.Messaging.ServiceBus/src/Processor/ProcessSessionMessageEventArgs.cs | 9,001 | C# |
using Microsoft.EntityFrameworkCore.Migrations;
namespace Infra.Migrations
{
public partial class GenericBattlev3 : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_InputBattleData_KoffieBattle_CurrentBattleId",
table: "InputBattleData");
migrationBuilder.DropIndex(
name: "IX_InputBattleData_CurrentBattleId",
table: "InputBattleData");
migrationBuilder.DropColumn(
name: "CurrentBattleId",
table: "InputBattleData");
migrationBuilder.AddColumn<int>(
name: "GegevensId",
table: "InputBattleData",
nullable: true);
migrationBuilder.CreateIndex(
name: "IX_InputBattleData_GegevensId",
table: "InputBattleData",
column: "GegevensId");
migrationBuilder.AddForeignKey(
name: "FK_InputBattleData_KoffieBattle_GegevensId",
table: "InputBattleData",
column: "GegevensId",
principalTable: "KoffieBattle",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_InputBattleData_KoffieBattle_GegevensId",
table: "InputBattleData");
migrationBuilder.DropIndex(
name: "IX_InputBattleData_GegevensId",
table: "InputBattleData");
migrationBuilder.DropColumn(
name: "GegevensId",
table: "InputBattleData");
migrationBuilder.AddColumn<int>(
name: "CurrentBattleId",
table: "InputBattleData",
type: "int",
nullable: true);
migrationBuilder.CreateIndex(
name: "IX_InputBattleData_CurrentBattleId",
table: "InputBattleData",
column: "CurrentBattleId");
migrationBuilder.AddForeignKey(
name: "FK_InputBattleData_KoffieBattle_CurrentBattleId",
table: "InputBattleData",
column: "CurrentBattleId",
principalTable: "KoffieBattle",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
}
}
}
| 34.293333 | 72 | 0.563764 | [
"MIT"
] | Kimo-sudo/CitrixDomain | Infra/Migrations/20200208184846_GenericBattlev3.cs | 2,574 | C# |
using UnityEngine;
using System.Collections;
public class OnJoinInstantiate : MonoBehaviour
{
public Transform ObjectToInstantiate;
public bool InstantiateSceneObjects = false;
public GameObject newObj; // not used but to show that you get the GO as return
public void OnJoinedRoom()
{
Vector3 pos = Vector3.zero;
pos.x += PhotonNetwork.player.ID;
if (!InstantiateSceneObjects)
{
newObj = PhotonNetwork.Instantiate(ObjectToInstantiate.name, pos, Quaternion.identity, 0, null);
// anything you do with newObj locally is not reflected on the other clients.
// you can add a script to the Prefab to do some instantiation in Awake() and you can call RPCs on newObj now.
}
else
{
newObj = PhotonNetwork.InstantiateSceneObject(ObjectToInstantiate.name, pos, Quaternion.identity, 0, null);
//PhotonView pv = newObj.GetComponent<PhotonView>() as PhotonView;
//Debug.Log(pv.ownerId + " " + pv.viewID);
}
}
}
| 31.571429 | 123 | 0.632579 | [
"Apache-2.0"
] | alejandrade/GlobalGameJam-Hackaton | Orbital/Assets/Photon Unity Networking/Demos/DemoChangeOwner/OnJoinInstantiate.cs | 1,105 | C# |
/*
* Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
* See https://github.com/openiddict/openiddict-core for more information concerning
* the license and the contributors participating to this project.
*/
using System.Collections.Immutable;
using System.ComponentModel;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Text.Json;
#if SUPPORTS_JSON_NODES
using System.Text.Json.Nodes;
#endif
namespace OpenIddict.Abstractions;
/// <summary>
/// Represents an OpenIddict parameter value, that can be either a primitive value,
/// an array of strings or a complex JSON representation containing child nodes.
/// </summary>
public readonly struct OpenIddictParameter : IEquatable<OpenIddictParameter>
{
/// <summary>
/// Initializes a new parameter using the specified value.
/// </summary>
/// <param name="value">The parameter value.</param>
public OpenIddictParameter(bool value) => Value = value;
/// <summary>
/// Initializes a new parameter using the specified value.
/// </summary>
/// <param name="value">The parameter value.</param>
public OpenIddictParameter(bool? value) => Value = value;
/// <summary>
/// Initializes a new parameter using the specified value.
/// </summary>
/// <param name="value">The parameter value.</param>
public OpenIddictParameter(JsonElement value) => Value = value;
#if SUPPORTS_JSON_NODES
/// <summary>
/// Initializes a new parameter using the specified value.
/// </summary>
/// <param name="value">The parameter value.</param>
public OpenIddictParameter(JsonNode? value) => Value = value;
#endif
/// <summary>
/// Initializes a new parameter using the specified value.
/// </summary>
/// <param name="value">The parameter value.</param>
public OpenIddictParameter(long value) => Value = value;
/// <summary>
/// Initializes a new parameter using the specified value.
/// </summary>
/// <param name="value">The parameter value.</param>
public OpenIddictParameter(long? value) => Value = value;
/// <summary>
/// Initializes a new parameter using the specified value.
/// </summary>
/// <param name="value">The parameter value.</param>
public OpenIddictParameter(string? value) => Value = value;
/// <summary>
/// Initializes a new parameter using the specified value.
/// </summary>
/// <param name="value">The parameter value.</param>
public OpenIddictParameter(string?[]? value) => Value = value;
/// <summary>
/// Gets the child item corresponding to the specified index.
/// </summary>
/// <param name="index">The index of the child item.</param>
/// <returns>An <see cref="OpenIddictParameter"/> instance containing the item value.</returns>
public OpenIddictParameter? this[int index] => GetUnnamedParameter(index);
/// <summary>
/// Gets the child item corresponding to the specified name.
/// </summary>
/// <param name="name">The name of the child item.</param>
/// <returns>An <see cref="OpenIddictParameter"/> instance containing the item value.</returns>
public OpenIddictParameter? this[string name] => GetNamedParameter(name);
/// <summary>
/// Gets the number of named or unnamed child items contained in the current parameter or 0
/// if the parameter doesn't represent an array of strings, a JSON array or a JSON object.
/// </summary>
public int Count
{
get
{
return Value switch
{
// If the parameter is a primitive array of strings, return its length.
string?[] value => value.Length,
// If the parameter is a JSON array or a JSON object, return its length.
JsonElement { ValueKind: JsonValueKind.Array or JsonValueKind.Object } element
=> Count(element),
#if SUPPORTS_JSON_NODES
// If the parameter is a JsonArray, return its length.
JsonArray value => value.Count,
// If the parameter is a JsonObject, return its length.
JsonObject value => value.Count,
// If the parameter is a JsonValue wrapping a JsonElement,
// apply the same logic as with direct JsonElement instances.
JsonValue value when value.TryGetValue(out JsonElement element)
=> element.ValueKind is JsonValueKind.Array or JsonValueKind.Object ? Count(element) : 0,
// If the parameter is a JsonValue wrapping a well-known primitive type
// (e.g int or string), always return 0 as these types can't have a length.
JsonValue value when value.TryGetValue(out bool _) ||
value.TryGetValue(out int _) ||
value.TryGetValue(out long _) ||
value.TryGetValue(out string _) => 0,
// If the parameter is any other JsonNode (e.g a JsonValue), serialize it
// to a JsonElement first to determine its actual JSON representation
// and extract the number of items if the element is a JSON array or object.
JsonNode value when JsonSerializer.SerializeToElement(value)
is JsonElement { ValueKind: JsonValueKind.Array or JsonValueKind.Object } element
=> Count(element),
#endif
// Otherwise, return 0.
_ => 0
};
static int Count(JsonElement element)
{
switch (element.ValueKind)
{
case JsonValueKind.Array:
return element.GetArrayLength();
case JsonValueKind.Object:
var count = 0;
using (var enumerator = element.EnumerateObject())
{
checked
{
while (enumerator.MoveNext())
{
count++;
}
}
}
return count;
default: return 0;
}
}
}
}
/// <summary>
/// Gets the associated value, that can be either a primitive CLR type
/// (e.g bool, string, long), an array of strings or a complex JSON object.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
public object? Value { get; }
/// <summary>
/// Determines whether the current <see cref="OpenIddictParameter"/>
/// instance is equal to the specified <see cref="OpenIddictParameter"/>.
/// </summary>
/// <param name="other">The other object to which to compare this instance.</param>
/// <returns>
/// <see langword="true"/> if the two instances have both the same representation
/// (e.g <see cref="string"/>) and value, <see langword="false"/> otherwise.
/// </returns>
public bool Equals(OpenIddictParameter other)
{
return (left: Value, right: other.Value) switch
{
// If the two parameters reference the same instance, return true.
//
// Note: true will also be returned if the two parameters are null.
var (left, right) when ReferenceEquals(left, right) => true,
// If one of the two parameters is null, return false.
(null, _) or (_, null) => false,
// If the two parameters are booleans, compare them directly.
(bool left, bool right) => left == right,
// If the two parameters are integers, compare them directly.
(long left, long right) => left == right,
// If the two parameters are strings, use string.Equals().
(string left, string right) => string.Equals(left, right, StringComparison.Ordinal),
// If the two parameters are string arrays, use SequenceEqual().
(string?[] left, string?[] right) => left.SequenceEqual(right),
// If one of the two parameters is an undefined JsonElement, treat it
// as a null value and return true if the other parameter is null too.
(JsonElement { ValueKind: JsonValueKind.Null or JsonValueKind.Undefined }, var right)
=> right is null,
(var left, JsonElement { ValueKind: JsonValueKind.Null or JsonValueKind.Undefined })
=> left is null,
// If the two parameters are JsonElement instances, use the custom comparer.
(JsonElement left, JsonElement right) => DeepEquals(left, right),
// When one of the parameters is a JsonElement, compare their underlying values.
(JsonElement { ValueKind: JsonValueKind.True }, bool right) => right,
(bool left, JsonElement { ValueKind: JsonValueKind.True }) => left,
(JsonElement { ValueKind: JsonValueKind.False }, bool right) => !right,
(bool left, JsonElement { ValueKind: JsonValueKind.False }) => !left,
(JsonElement { ValueKind: JsonValueKind.Number } left, long right)
when left.TryGetInt64(out var result) => result == right,
(long left, JsonElement { ValueKind: JsonValueKind.Number } right)
when right.TryGetInt64(out var result) => left == result,
(JsonElement { ValueKind: JsonValueKind.String } left, string right)
=> string.Equals(left.GetString(), right, StringComparison.Ordinal),
(string left, JsonElement { ValueKind: JsonValueKind.String } right)
=> string.Equals(left, right.GetString(), StringComparison.Ordinal),
#if SUPPORTS_JSON_NODES
// When one of the parameters is a JsonValue, try to compare their underlying values
// if the wrapped type is a common CLR primitive type to avoid the less efficient
// JsonElement-based comparison, that requires doing a full JSON serialization.
(JsonValue left, bool right) when left.TryGetValue(out bool result) => result == right,
(bool left, JsonValue right) when right.TryGetValue(out bool result) => result == left,
(JsonValue left, long right) when left.TryGetValue(out int result) => result == right,
(long left, JsonValue right) when right.TryGetValue(out int result) => result == left,
(JsonValue left, long right) when left.TryGetValue(out long result) => result == right,
(long left, JsonValue right) when right.TryGetValue(out long result) => result == left,
(JsonValue left, string right) when left.TryGetValue(out string? result)
=> string.Equals(result, right, StringComparison.Ordinal),
(string left, JsonValue right) when right.TryGetValue(out string? result)
=> string.Equals(left, result, StringComparison.Ordinal),
#endif
// Otherwise, serialize both values to JsonElement and compare them.
#if SUPPORTS_DIRECT_JSON_ELEMENT_SERIALIZATION
var (left, right) => DeepEquals(
JsonSerializer.SerializeToElement(left, left.GetType()),
JsonSerializer.SerializeToElement(right, right.GetType()))
#else
var (left, right) => DeepEquals(
JsonSerializer.Deserialize<JsonElement>(JsonSerializer.Serialize(left, left.GetType())),
JsonSerializer.Deserialize<JsonElement>(JsonSerializer.Serialize(right, right.GetType())))
#endif
};
static bool DeepEquals(JsonElement left, JsonElement right)
{
RuntimeHelpers.EnsureSufficientExecutionStack();
switch ((left.ValueKind, right.ValueKind))
{
case (JsonValueKind.Undefined, JsonValueKind.Undefined):
case (JsonValueKind.Null, JsonValueKind.Null):
case (JsonValueKind.False, JsonValueKind.False):
case (JsonValueKind.True, JsonValueKind.True):
return true;
// Treat undefined JsonElement instances as null values.
case (JsonValueKind.Undefined, JsonValueKind.Null):
case (JsonValueKind.Null, JsonValueKind.Undefined):
return true;
case (JsonValueKind.Number, JsonValueKind.Number):
return string.Equals(left.GetRawText(), right.GetRawText(), StringComparison.Ordinal);
case (JsonValueKind.String, JsonValueKind.String):
return string.Equals(left.GetString(), right.GetString(), StringComparison.Ordinal);
case (JsonValueKind.Array, JsonValueKind.Array):
{
var length = left.GetArrayLength();
if (length != right.GetArrayLength())
{
return false;
}
for (var index = 0; index < length; index++)
{
if (!DeepEquals(left[index], right[index]))
{
return false;
}
}
return true;
}
case (JsonValueKind.Object, JsonValueKind.Object):
{
foreach (var property in left.EnumerateObject())
{
if (!right.TryGetProperty(property.Name, out JsonElement element) ||
property.Value.ValueKind != element.ValueKind)
{
return false;
}
if (!DeepEquals(property.Value, element))
{
return false;
}
}
return true;
}
default: return false;
}
}
}
/// <summary>
/// Determines whether the current <see cref="OpenIddictParameter"/>
/// instance is equal to the specified <see cref="object"/>.
/// </summary>
/// <param name="obj">The other object to which to compare this instance.</param>
/// <returns>
/// <see langword="true"/> if the two instances have both the same representation
/// (e.g <see cref="string"/>) and value, <see langword="false"/> otherwise.
/// </returns>
public override bool Equals(object? obj) => obj is OpenIddictParameter parameter && Equals(parameter);
/// <summary>
/// Returns the hash code of the current <see cref="OpenIddictParameter"/> instance.
/// </summary>
/// <returns>The hash code for the current instance.</returns>
public override int GetHashCode()
{
return Value switch
{
// When the parameter value is null, return 0.
null => 0,
// When the parameter is an array of strings, compute the hash code of its items to
// match the logic used when treating a JsonElement instance representing an array.
string?[] value => GetHashCodeFromArray(value),
// When the parameter is a JsonElement, compute its hash code.
JsonElement value => GetHashCodeFromJsonElement(value),
#if SUPPORTS_JSON_NODES
// When the parameter is a JsonValue wrapping a JsonElement,
// apply the same logic as with direct JsonElement instances.
JsonValue value when value.TryGetValue(out JsonElement element)
=> GetHashCodeFromJsonElement(element),
// When the parameter is a JsonValue, compute the hash code of its underlying value
// if the wrapped type is a common CLR primitive type to avoid the less efficient
// JsonElement-based computation, that requires doing a full JSON serialization.
JsonValue value when value.TryGetValue(out bool result) => result.GetHashCode(),
JsonValue value when value.TryGetValue(out int result) => result.GetHashCode(),
JsonValue value when value.TryGetValue(out long result) => result.GetHashCode(),
JsonValue value when value.TryGetValue(out string? result) => result.GetHashCode(),
// When the parameter is a JsonNode (e.g a JsonValue wrapping a non-primitive type),
// serialize it to a JsonElement first to determine its actual JSON representation
// and apply the same logic as with non-wrapped JsonElement instances.
JsonNode value when JsonSerializer.SerializeToElement(value) is JsonElement element
=> GetHashCodeFromJsonElement(element),
#endif
// Otherwise, use the default hash code method.
var value => value.GetHashCode()
};
static int GetHashCodeFromArray(string?[] array)
{
var hash = new HashCode();
for (var index = 0; index < array.Length; index++)
{
hash.Add(array[index]);
}
return hash.ToHashCode();
}
static int GetHashCodeFromJsonElement(JsonElement element)
{
RuntimeHelpers.EnsureSufficientExecutionStack();
switch (element.ValueKind)
{
case JsonValueKind.Undefined:
case JsonValueKind.Null:
return 0;
case JsonValueKind.True:
return true.GetHashCode();
case JsonValueKind.False:
return false.GetHashCode();
case JsonValueKind.Number when element.TryGetInt64(out var result):
return result.GetHashCode();
case JsonValueKind.Number:
return element.GetRawText().GetHashCode();
case JsonValueKind.String:
return element.GetString()!.GetHashCode();
case JsonValueKind.Array:
{
var hash = new HashCode();
foreach (var item in element.EnumerateArray())
{
hash.Add(GetHashCodeFromJsonElement(item));
}
return hash.ToHashCode();
}
case JsonValueKind.Object:
{
var hash = new HashCode();
foreach (var property in element.EnumerateObject())
{
hash.Add(property.Name);
hash.Add(GetHashCodeFromJsonElement(property.Value));
}
return hash.ToHashCode();
}
default: return 0;
}
}
}
/// <summary>
/// Gets the child item corresponding to the specified name.
/// </summary>
/// <param name="name">The name of the child item.</param>
/// <returns>An <see cref="OpenIddictParameter"/> instance containing the item value.</returns>
public OpenIddictParameter? GetNamedParameter(string name)
=> TryGetNamedParameter(name, out var value) ? value : (OpenIddictParameter?) null;
/// <summary>
/// Gets the child item corresponding to the specified index.
/// </summary>
/// <param name="index">The index of the child item.</param>
/// <returns>An <see cref="OpenIddictParameter"/> instance containing the item value.</returns>
public OpenIddictParameter? GetUnnamedParameter(int index)
=> TryGetUnnamedParameter(index, out var value) ? value : (OpenIddictParameter?) null;
/// <summary>
/// Gets the named child items associated with the current parameter, if it represents a JSON object.
/// Note: if the JSON object contains multiple parameters with the same name, only the last occurrence is returned.
/// </summary>
/// <returns>A dictionary of all the parameters associated with the current instance.</returns>
public IReadOnlyDictionary<string, OpenIddictParameter> GetNamedParameters()
{
return Value switch
{
// When the parameter is a JsonElement representing an object, return the requested item.
JsonElement { ValueKind: JsonValueKind.Object } value => GetParametersFromJsonElement(value),
#if SUPPORTS_JSON_NODES
// When the parameter is a JsonObject, return the requested item.
JsonObject value => GetParametersFromJsonNode(value),
// When the parameter is a JsonNode (e.g a JsonValue wrapping a non-primitive type),
// serialize it to a JsonElement first to determine its actual JSON representation
// and apply the same logic as with non-wrapped JsonElement instances.
JsonNode value when JsonSerializer.SerializeToElement(value)
is JsonElement { ValueKind: JsonValueKind.Object } element
=> GetParametersFromJsonElement(element),
#endif
_ => ImmutableDictionary.Create<string, OpenIddictParameter>(StringComparer.Ordinal)
};
static IReadOnlyDictionary<string, OpenIddictParameter> GetParametersFromJsonElement(JsonElement element)
{
var parameters = new Dictionary<string, OpenIddictParameter>(StringComparer.Ordinal);
foreach (var property in element.EnumerateObject())
{
parameters[property.Name] = new(property.Value);
}
return parameters;
}
#if SUPPORTS_JSON_NODES
static IReadOnlyDictionary<string, OpenIddictParameter> GetParametersFromJsonNode(JsonObject node)
{
var parameters = new Dictionary<string, OpenIddictParameter>(node.Count, StringComparer.Ordinal);
foreach (var property in node)
{
parameters[property.Key] = new(property.Value);
}
return parameters;
}
#endif
}
/// <summary>
/// Gets the unnamed child items associated with the current parameter,
/// if it represents an array of strings or a JSON array.
/// </summary>
/// <returns>An enumeration of all the unnamed parameters associated with the current instance.</returns>
public IReadOnlyList<OpenIddictParameter> GetUnnamedParameters()
{
return Value switch
{
// When the parameter is an array of strings, return its items.
string?[] value => GetParametersFromArray(value),
// When the parameter is a JsonElement representing an array, return its children.
JsonElement { ValueKind: JsonValueKind.Array } value => GetParametersFromJsonElement(value),
#if SUPPORTS_JSON_NODES
// When the parameter is a JsonArray, return its children.
JsonArray value => GetParametersFromJsonNode(value),
// When the parameter is a JsonNode (e.g a JsonValue wrapping a non-primitive type),
// serialize it to a JsonElement first to determine its actual JSON representation
// and apply the same logic as with non-wrapped JsonElement instances.
JsonNode value when JsonSerializer.SerializeToElement(value)
is JsonElement { ValueKind: JsonValueKind.Array } element
=> GetParametersFromJsonElement(element),
#endif
_ => ImmutableList.Create<OpenIddictParameter>()
};
static IReadOnlyList<OpenIddictParameter> GetParametersFromArray(string?[] array)
{
var parameters = new OpenIddictParameter[array.Length];
for (var index = 0; index < array.Length; index++)
{
parameters[index] = new(array[index]);
}
return parameters;
}
static IReadOnlyList<OpenIddictParameter> GetParametersFromJsonElement(JsonElement element)
{
var length = element.GetArrayLength();
var parameters = new OpenIddictParameter[length];
for (var index = 0; index < length; index++)
{
parameters[index] = new(element[index]);
}
return parameters;
}
#if SUPPORTS_JSON_NODES
static IReadOnlyList<OpenIddictParameter> GetParametersFromJsonNode(JsonArray node)
{
var parameters = new OpenIddictParameter[node.Count];
for (var index = 0; index < node.Count; index++)
{
parameters[index] = new(node[index]);
}
return parameters;
}
#endif
}
/// <summary>
/// Returns the <see cref="string"/> representation of the current instance.
/// </summary>
/// <returns>The <see cref="string"/> representation associated with the parameter value.</returns>
public override string? ToString() => Value switch
{
null => string.Empty,
bool value => value ? bool.TrueString : bool.FalseString,
long value => value.ToString(CultureInfo.InvariantCulture),
string value => value,
string?[] value => string.Join(", ", value),
JsonElement value => value.ToString(),
#if SUPPORTS_JSON_NODES
JsonValue value when value.TryGetValue(out JsonElement element)
=> element.ToString(),
JsonValue value when value.TryGetValue(out bool result)
=> result ? bool.TrueString : bool.FalseString,
JsonValue value when value.TryGetValue(out int result)
=> result.ToString(CultureInfo.InvariantCulture),
JsonValue value when value.TryGetValue(out long result)
=> result.ToString(CultureInfo.InvariantCulture),
JsonValue value when value.TryGetValue(out string? result) => result,
JsonNode value => value.ToJsonString(),
#endif
_ => string.Empty
};
/// <summary>
/// Tries to get the child item corresponding to the specified name.
/// </summary>
/// <param name="name">The name of the child item.</param>
/// <param name="value">An <see cref="OpenIddictParameter"/> instance containing the item value.</param>
/// <returns><see langword="true"/> if the parameter could be found, <see langword="false"/> otherwise.</returns>
public bool TryGetNamedParameter(string name, out OpenIddictParameter value)
{
if (string.IsNullOrEmpty(name))
{
throw new ArgumentException(SR.GetResourceString(SR.ID0192), nameof(name));
}
var result = Value switch
{
// When the parameter is a JsonElement representing an array, return the requested item.
JsonElement { ValueKind: JsonValueKind.Object } element =>
element.TryGetProperty(name, out JsonElement property) ? new(property) : null,
#if SUPPORTS_JSON_NODES
// When the parameter is a JsonObject, return the requested item.
JsonObject node => node.TryGetPropertyValue(name, out JsonNode? property) ? new(property) : null,
// When the parameter is a JsonNode (e.g a JsonValue wrapping a non-primitive type),
// serialize it to a JsonElement first to determine its actual JSON representation
// and apply the same logic as with non-wrapped JsonElement instances.
JsonNode node when JsonSerializer.SerializeToElement(node)
is JsonElement { ValueKind: JsonValueKind.Object } element
=> element.TryGetProperty(name, out JsonElement property) ? new(property) : null,
#endif
_ => (OpenIddictParameter?) null
};
value = result.GetValueOrDefault();
return result.HasValue;
}
/// <summary>
/// Tries to get the child item corresponding to the specified index.
/// </summary>
/// <param name="index">The index of the child item.</param>
/// <param name="value">An <see cref="OpenIddictParameter"/> instance containing the item value.</param>
/// <returns><see langword="true"/> if the parameter could be found, <see langword="false"/> otherwise.</returns>
public bool TryGetUnnamedParameter(int index, out OpenIddictParameter value)
{
if (index < 0)
{
throw new ArgumentOutOfRangeException(nameof(index), SR.GetResourceString(SR.ID0193));
}
var result = Value switch
{
// When the parameter is an array of strings, return the requested item.
string?[] array => index < array.Length ? new(array[index]) : null,
// When the parameter is a JsonElement representing an array, return the requested item.
JsonElement { ValueKind: JsonValueKind.Array } element =>
index < element.GetArrayLength() ? new(element[index]) : null,
#if SUPPORTS_JSON_NODES
// When the parameter is a JsonArray, return the requested item.
JsonArray node => index < node.Count ? new(node[index]) : null,
// When the parameter is a JsonNode (e.g a JsonValue wrapping a non-primitive type),
// serialize it to a JsonElement first to determine its actual JSON representation
// and apply the same logic as with non-wrapped JsonElement instances.
JsonNode node when JsonSerializer.SerializeToElement(node)
is JsonElement { ValueKind: JsonValueKind.Array } element
=> index < element.GetArrayLength() ? new(element) : null,
#endif
_ => (OpenIddictParameter?) null
};
value = result.GetValueOrDefault();
return result.HasValue;
}
/// <summary>
/// Writes the parameter value to the specified JSON writer.
/// </summary>
/// <param name="writer">The UTF-8 JSON writer.</param>
public void WriteTo(Utf8JsonWriter writer)
{
if (writer is null)
{
throw new ArgumentNullException(nameof(writer));
}
switch (Value)
{
// Note: undefined JsonElement values are assimilated to null values.
case null:
case JsonElement { ValueKind: JsonValueKind.Null or JsonValueKind.Undefined }:
writer.WriteNullValue();
break;
case bool value:
writer.WriteBooleanValue(value);
break;
case long value:
writer.WriteNumberValue(value);
break;
case string value:
writer.WriteStringValue(value);
break;
case string?[] value:
writer.WriteStartArray();
for (var index = 0; index < value.Length; index++)
{
writer.WriteStringValue(value[index]);
}
writer.WriteEndArray();
break;
case JsonElement value:
value.WriteTo(writer);
break;
#if SUPPORTS_JSON_NODES
case JsonNode value:
value.WriteTo(writer);
break;
#endif
}
}
/// <summary>
/// Determines whether two <see cref="OpenIddictParameter"/> instances are equal.
/// </summary>
/// <param name="left">The first instance.</param>
/// <param name="right">The second instance.</param>
/// <returns><see langword="true"/> if the two instances are equal, <see langword="false"/> otherwise.</returns>
public static bool operator ==(OpenIddictParameter left, OpenIddictParameter right) => left.Equals(right);
/// <summary>
/// Determines whether two <see cref="OpenIddictParameter"/> instances are not equal.
/// </summary>
/// <param name="left">The first instance.</param>
/// <param name="right">The second instance.</param>
/// <returns><see langword="true"/> if the two instances are not equal, <see langword="false"/> otherwise.</returns>
public static bool operator !=(OpenIddictParameter left, OpenIddictParameter right) => !left.Equals(right);
/// <summary>
/// Converts an <see cref="OpenIddictParameter"/> instance to a boolean.
/// </summary>
/// <param name="parameter">The parameter to convert.</param>
/// <returns>The converted value.</returns>
public static explicit operator bool(OpenIddictParameter? parameter)
=> ((bool?) parameter).GetValueOrDefault();
/// <summary>
/// Converts an <see cref="OpenIddictParameter"/> instance to a nullable boolean.
/// </summary>
/// <param name="parameter">The parameter to convert.</param>
/// <returns>The converted value.</returns>
public static explicit operator bool?(OpenIddictParameter? parameter)
{
return parameter?.Value switch
{
// When the parameter is a null value or a JsonElement representing null, return null.
null or JsonElement { ValueKind: JsonValueKind.Null or JsonValueKind.Undefined } => null,
// When the parameter is a boolean value, return it as-is.
bool value => value,
// When the parameter is a string value, try to parse it.
string value => bool.TryParse(value, out var result) ? result : null,
// When the parameter is a JsonElement, try to convert it if it's of a supported type.
JsonElement value => ConvertFromJsonElement(value),
#if SUPPORTS_JSON_NODES
// When the parameter is a JsonValue wrapping a JsonElement,
// apply the same logic as with direct JsonElement instances.
JsonValue value when value.TryGetValue(out JsonElement element) => ConvertFromJsonElement(element),
// When the parameter is a JsonValue wrapping a boolean, return it as-is.
JsonValue value when value.TryGetValue(out bool result) => result,
// When the parameter is a JsonValue wrapping a string, try to parse it.
JsonValue value when value.TryGetValue(out string? text) =>
bool.TryParse(text, out var result) ? result : null,
// When the parameter is a JsonNode (e.g a JsonValue wrapping a non-primitive type),
// serialize it to a JsonElement first to determine its actual JSON representation
// and apply the same logic as with non-wrapped JsonElement instances.
JsonNode value when JsonSerializer.SerializeToElement(value) is JsonElement element
=> ConvertFromJsonElement(element),
#endif
// If the parameter is of a different type, return null to indicate the conversion failed.
_ => null
};
static bool? ConvertFromJsonElement(JsonElement element) => element.ValueKind switch
{
// When the parameter is a JsonElement representing a boolean, return it as-is.
JsonValueKind.True => true,
JsonValueKind.False => false,
// When the parameter is a JsonElement representing a string, try to parse it.
JsonValueKind.String => bool.TryParse(element.GetString(), out var result) ? result : null,
_ => null
};
}
/// <summary>
/// Converts an <see cref="OpenIddictParameter"/> instance to a <see cref="JsonElement"/>.
/// </summary>
/// <param name="parameter">The parameter to convert.</param>
/// <returns>The converted value.</returns>
public static explicit operator JsonElement(OpenIddictParameter? parameter)
{
return parameter?.Value switch
{
// When the parameter is a null value, return an undefined JsonElement.
null => default,
// When the parameter is already a JsonElement, return it as-is.
JsonElement value => value,
#if SUPPORTS_JSON_NODES
// When the parameter is JsonNode, serialize it as a JsonElement.
JsonNode value => JsonSerializer.SerializeToElement(value),
#endif
// When the parameter is a string starting with '{' or '[' (which would correspond
// to a JSON object or array), try to deserialize it to get a JsonElement instance.
string { Length: > 0 } value when value[0] is '{' or '[' =>
DeserializeElement(value) ??
DeserializeElement(JsonSerializer.Serialize(value)) ?? default,
// Otherwise, serialize it to get a JsonElement instance.
#if SUPPORTS_DIRECT_JSON_ELEMENT_SERIALIZATION
object value => JsonSerializer.SerializeToElement(value, value.GetType())
#else
object value => DeserializeElement(JsonSerializer.Serialize(value)) ?? default
#endif
};
static JsonElement? DeserializeElement(string value)
{
try
{
using var document = JsonDocument.Parse(value);
return document.RootElement.Clone();
}
catch (JsonException)
{
return null;
}
}
}
#if SUPPORTS_JSON_NODES
/// <summary>
/// Converts an <see cref="OpenIddictParameter"/> instance to a <see cref="JsonNode"/>.
/// </summary>
/// <param name="parameter">The parameter to convert.</param>
/// <returns>The converted value.</returns>
public static explicit operator JsonNode?(OpenIddictParameter? parameter)
{
return parameter?.Value switch
{
// When the parameter is a null value or a JsonElement representing null, return null.
null or JsonElement { ValueKind: JsonValueKind.Null or JsonValueKind.Undefined } => null,
// When the parameter is already a JsonNode, return it as-is.
JsonNode value => value,
// When the parameter is a boolean, return a JsonValue.
bool value => JsonValue.Create(value),
// When the parameter is an integer, return a JsonValue.
long value => JsonValue.Create(value),
// When the parameter is a string starting with '{' or '[' (which would correspond
// to a JSON object or array), try to deserialize it to get a JsonNode instance.
string { Length: > 0 } value when value[0] is '{' or '[' => DeserializeNode(value),
// When the parameter is a string, return a JsonValue.
string value => JsonValue.Create(value),
// When the parameter is an array of strings, return a JsonArray.
string?[] value => CreateArray(value),
// When the parameter is JsonElement, deserialize it as a JsonNode.
JsonElement value => JsonSerializer.Deserialize<JsonNode>(value),
// If the parameter is of a different type, return null to indicate the conversion failed.
_ => null
};
static JsonNode? DeserializeNode(string value)
{
try
{
return JsonNode.Parse(value);
}
catch (JsonException)
{
return null;
}
}
static JsonArray? CreateArray(string?[] values)
{
var array = new JsonArray();
for (var index = 0; index < values.Length; index++)
{
array.Add(values[index]);
}
return array;
}
}
/// <summary>
/// Converts an <see cref="OpenIddictParameter"/> instance to a <see cref="JsonArray"/>.
/// </summary>
/// <param name="parameter">The parameter to convert.</param>
/// <returns>The converted value.</returns>
public static explicit operator JsonArray?(OpenIddictParameter? parameter)
=> ((JsonNode?) parameter) as JsonArray;
/// <summary>
/// Converts an <see cref="OpenIddictParameter"/> instance to a <see cref="JsonObject"/>.
/// </summary>
/// <param name="parameter">The parameter to convert.</param>
/// <returns>The converted value.</returns>
public static explicit operator JsonObject?(OpenIddictParameter? parameter)
=> ((JsonNode?) parameter) as JsonObject;
/// <summary>
/// Converts an <see cref="OpenIddictParameter"/> instance to a <see cref="JsonValue"/>.
/// </summary>
/// <param name="parameter">The parameter to convert.</param>
/// <returns>The converted value.</returns>
public static explicit operator JsonValue?(OpenIddictParameter? parameter)
=> ((JsonNode?) parameter) as JsonValue;
#endif
/// <summary>
/// Converts an <see cref="OpenIddictParameter"/> instance to a long integer.
/// </summary>
/// <param name="parameter">The parameter to convert.</param>
/// <returns>The converted value.</returns>
public static explicit operator long(OpenIddictParameter? parameter)
=> ((long?) parameter).GetValueOrDefault();
/// <summary>
/// Converts an <see cref="OpenIddictParameter"/> instance to a nullable long integer.
/// </summary>
/// <param name="parameter">The parameter to convert.</param>
/// <returns>The converted value.</returns>
public static explicit operator long?(OpenIddictParameter? parameter)
{
return parameter?.Value switch
{
// When the parameter is a null value or a JsonElement representing null, return null.
null or JsonElement { ValueKind: JsonValueKind.Null or JsonValueKind.Undefined } => null,
// When the parameter is an integer, return it as-is.
long value => value,
// When the parameter is a string value, try to parse it.
string value => long.TryParse(value, NumberStyles.Integer,
CultureInfo.InvariantCulture, out var result) ? result : null,
// When the parameter is a JsonElement, try to convert it if it's of a supported type.
JsonElement value => ConvertFromJsonElement(value),
#if SUPPORTS_JSON_NODES
// When the parameter is a JsonValue wrapping a JsonElement,
// apply the same logic as with direct JsonElement instances.
JsonValue value when value.TryGetValue(out JsonElement element) => ConvertFromJsonElement(element),
// When the parameter is a JsonValue wrapping an integer, return it as-is.
JsonValue value when value.TryGetValue(out int result) => result,
JsonValue value when value.TryGetValue(out long result) => result,
// When the parameter is a JsonValue wrapping a string, return it as-is.
JsonValue value when value.TryGetValue(out string? text) =>
long.TryParse(text, NumberStyles.Integer,
CultureInfo.InvariantCulture, out var result) ? result : null,
// When the parameter is a JsonNode (e.g a JsonValue wrapping a non-primitive type),
// serialize it to a JsonElement first to determine its actual JSON representation
// and apply the same logic as with non-wrapped JsonElement instances.
JsonNode value when JsonSerializer.SerializeToElement(value) is JsonElement element
=> ConvertFromJsonElement(element),
#endif
// If the parameter is of a different type, return null to indicate the conversion failed.
_ => null
};
static long? ConvertFromJsonElement(JsonElement element) => element.ValueKind switch
{
// When the parameter is a JsonElement representing a number, return it as-is.
JsonValueKind.Number => element.TryGetInt64(out var result) ? result : null,
// When the parameter is a JsonElement representing a string, try to parse it.
JsonValueKind.String => long.TryParse(element.GetString(), NumberStyles.Integer,
CultureInfo.InvariantCulture, out var result) ? result : null,
_ => null
};
}
/// <summary>
/// Converts an <see cref="OpenIddictParameter"/> instance to a string.
/// </summary>
/// <param name="parameter">The parameter to convert.</param>
/// <returns>The converted value.</returns>
public static explicit operator string?(OpenIddictParameter? parameter)
{
return parameter?.Value switch
{
// When the parameter is a null value or a JsonElement representing null, return null.
null or JsonElement { ValueKind: JsonValueKind.Null or JsonValueKind.Undefined } => null,
// When the parameter is a string value, return it as-is.
string value => value,
// When the parameter is a boolean value, use its string representation.
bool value => value ? bool.TrueString : bool.FalseString,
// When the parameter is an integer, use its string representation.
long value => value.ToString(CultureInfo.InvariantCulture),
// When the parameter is a JsonElement, try to convert it if it's of a supported type.
JsonElement value => ConvertFromJsonElement(value),
#if SUPPORTS_JSON_NODES
// When the parameter is a JsonValue wrapping a JsonElement,
// apply the same logic as with direct JsonElement instances.
JsonValue value when value.TryGetValue(out JsonElement element) => ConvertFromJsonElement(element),
// When the parameter is a JsonValue wrapping a string, return it as-is.
JsonValue value when value.TryGetValue(out string? result) => result,
// When the parameter is a JsonValue wrapping a boolean, return its representation.
JsonValue value when value.TryGetValue(out bool result) => result ? bool.TrueString : bool.FalseString,
// When the parameter is a JsonValue wrapping a boolean, return its representation.
JsonValue value when value.TryGetValue(out int result) => result.ToString(CultureInfo.InvariantCulture),
JsonValue value when value.TryGetValue(out long result) => result.ToString(CultureInfo.InvariantCulture),
// When the parameter is a JsonNode (e.g a JsonValue wrapping a non-primitive type),
// serialize it to a JsonElement first to determine its actual JSON representation
// and apply the same logic as with non-wrapped JsonElement instances.
JsonNode value when JsonSerializer.SerializeToElement(value) is JsonElement element
=> ConvertFromJsonElement(element),
#endif
// If the parameter is of a different type, return null to indicate the conversion failed.
_ => null
};
static string? ConvertFromJsonElement(JsonElement element) => element.ValueKind switch
{
// When the parameter is a JsonElement representing a string,
// a number or a boolean, return its string representation.
JsonValueKind.String or JsonValueKind.Number or
JsonValueKind.True or JsonValueKind.False
=> element.ToString(),
_ => null
};
}
/// <summary>
/// Converts an <see cref="OpenIddictParameter"/> instance to an array of strings.
/// </summary>
/// <param name="parameter">The parameter to convert.</param>
/// <returns>The converted value.</returns>
public static explicit operator string?[]?(OpenIddictParameter? parameter)
{
return parameter?.Value switch
{
// When the parameter is a null value or a JsonElement representing null, return null.
null or JsonElement { ValueKind: JsonValueKind.Null or JsonValueKind.Undefined } => null,
// When the parameter is already an array of strings, return it as-is.
string?[] value => value,
// When the parameter is a string value, return an array with a single entry.
string value => new string?[] { value },
// When the parameter is a boolean value, return an array with its string representation.
bool value => new string?[] { value ? bool.TrueString : bool.FalseString },
// When the parameter is an integer, return an array with its string representation.
long value => new string?[] { value.ToString(CultureInfo.InvariantCulture) },
// When the parameter is a JsonElement, try to convert it if it's of a supported type.
JsonElement value => ConvertFromJsonElement(value),
#if SUPPORTS_JSON_NODES
// When the parameter is a JsonValue wrapping a JsonElement,
// apply the same logic as with direct JsonElement instances.
JsonValue value when value.TryGetValue(out JsonElement element) => ConvertFromJsonElement(element),
// When the parameter is a JsonValue wrapping a string, return an array with a single entry.
JsonValue value when value.TryGetValue(out string? result) => new string?[] { result },
// When the parameter is a JsonValue wrapping a boolean, return an array with its string representation.
JsonValue value when value.TryGetValue(out bool result)
=> new string?[] { result ? bool.TrueString : bool.FalseString },
// When the parameter is a JsonValue wrapping an integer, return an array with its string representation.
JsonValue value when value.TryGetValue(out int result)
=> new string?[] { result.ToString(CultureInfo.InvariantCulture) },
JsonValue value when value.TryGetValue(out long result)
=> new string?[] { result.ToString(CultureInfo.InvariantCulture) },
// When the parameter is a JsonNode (e.g a JsonValue wrapping a non-primitive type),
// serialize it to a JsonElement first to determine its actual JSON representation
// and apply the same logic as with non-wrapped JsonElement instances.
JsonNode value when JsonSerializer.SerializeToElement(value) is JsonElement element
=> ConvertFromJsonElement(element),
#endif
// If the parameter is of a different type, return null to indicate the conversion failed.
_ => null
};
static string?[]? ConvertFromJsonElement(JsonElement element) => element.ValueKind switch
{
// When the parameter is a JsonElement representing a string, a number
// or a boolean, return an 1-item array with its string representation.
JsonValueKind.String or JsonValueKind.Number or
JsonValueKind.True or JsonValueKind.False
=> new string?[] { element.ToString() },
// When the parameter is a JsonElement representing an array, return the elements as strings.
JsonValueKind.Array => CreateArrayFromJsonElement(element),
_ => null
};
static string?[]? CreateArrayFromJsonElement(JsonElement element)
{
var length = element.GetArrayLength();
var array = new string?[length];
for (var index = 0; index < length; index++)
{
// Always return a null array if one of the items is a not string, a number or a boolean.
if (element[index] is not { ValueKind: JsonValueKind.String or JsonValueKind.Number or
JsonValueKind.True or JsonValueKind.False } item)
{
return null;
}
array[index] = item.ToString();
}
return array;
}
}
/// <summary>
/// Converts a boolean to an <see cref="OpenIddictParameter"/> instance.
/// </summary>
/// <param name="value">The value to convert</param>
/// <returns>An <see cref="OpenIddictParameter"/> instance.</returns>
public static implicit operator OpenIddictParameter(bool value) => new(value);
/// <summary>
/// Converts a nullable boolean to an <see cref="OpenIddictParameter"/> instance.
/// </summary>
/// <param name="value">The value to convert</param>
/// <returns>An <see cref="OpenIddictParameter"/> instance.</returns>
public static implicit operator OpenIddictParameter(bool? value) => new(value);
/// <summary>
/// Converts a <see cref="JsonElement"/> to an <see cref="OpenIddictParameter"/> instance.
/// </summary>
/// <param name="value">The value to convert</param>
/// <returns>An <see cref="OpenIddictParameter"/> instance.</returns>
public static implicit operator OpenIddictParameter(JsonElement value) => new(value);
#if SUPPORTS_JSON_NODES
/// <summary>
/// Converts a <see cref="JsonNode"/> to an <see cref="OpenIddictParameter"/> instance.
/// </summary>
/// <param name="value">The value to convert</param>
/// <returns>An <see cref="OpenIddictParameter"/> instance.</returns>
public static implicit operator OpenIddictParameter(JsonNode? value) => new(value);
#endif
/// <summary>
/// Converts a long integer to an <see cref="OpenIddictParameter"/> instance.
/// </summary>
/// <param name="value">The value to convert</param>
/// <returns>An <see cref="OpenIddictParameter"/> instance.</returns>
public static implicit operator OpenIddictParameter(long value) => new(value);
/// <summary>
/// Converts a nullable long integer to an <see cref="OpenIddictParameter"/> instance.
/// </summary>
/// <param name="value">The value to convert</param>
/// <returns>An <see cref="OpenIddictParameter"/> instance.</returns>
public static implicit operator OpenIddictParameter(long? value) => new(value);
/// <summary>
/// Converts a string to an <see cref="OpenIddictParameter"/> instance.
/// </summary>
/// <param name="value">The value to convert</param>
/// <returns>An <see cref="OpenIddictParameter"/> instance.</returns>
public static implicit operator OpenIddictParameter(string? value) => new(value);
/// <summary>
/// Converts an array of strings to an <see cref="OpenIddictParameter"/> instance.
/// </summary>
/// <param name="value">The value to convert</param>
/// <returns>An <see cref="OpenIddictParameter"/> instance.</returns>
public static implicit operator OpenIddictParameter(string?[]? value) => new(value);
/// <summary>
/// Determines whether a parameter is null or empty.
/// </summary>
/// <param name="parameter">The parameter.</param>
/// <returns><see langword="true"/> if the parameter is null or empty, <see langword="false"/> otherwise.</returns>
public static bool IsNullOrEmpty(OpenIddictParameter parameter)
{
return parameter.Value switch
{
null or JsonElement { ValueKind: JsonValueKind.Null or JsonValueKind.Undefined } => true,
string value => value.Length is 0,
string?[] value => value.Length is 0,
JsonElement value => IsEmptyJsonElement(value),
#if SUPPORTS_JSON_NODES
JsonArray value => value.Count is 0,
JsonObject value => value.Count is 0,
JsonValue value when value.TryGetValue(out JsonElement element)
=> IsEmptyJsonElement(element),
JsonValue value when value.TryGetValue(out string? result)
=> string.IsNullOrEmpty(result),
JsonNode value when JsonSerializer.SerializeToElement(value) is JsonElement element
=> IsEmptyJsonElement(element),
#endif
_ => false
};
static bool IsEmptyJsonElement(JsonElement element)
{
switch (element.ValueKind)
{
case JsonValueKind.String:
return string.IsNullOrEmpty(element.GetString());
case JsonValueKind.Array:
return element.GetArrayLength() is 0;
case JsonValueKind.Object:
using (var enumerator = element.EnumerateObject())
{
return !enumerator.MoveNext();
}
default: return false;
}
}
}
}
| 43.097859 | 120 | 0.61284 | [
"Apache-2.0"
] | OrgAE/OrgAE-Openiddict | src/OpenIddict.Abstractions/Primitives/OpenIddictParameter.cs | 56,374 | C# |
using SharpDX.Direct3D9;
using System;
using System.Threading;
using System.Windows.Interop;
namespace LottieSharp.WpfSurface
{
class Dx11ImageSource : D3DImage, IDisposable
{
// - field -----------------------------------------------------------------------
private static int ActiveClients;
private static Direct3DEx D3DContext;
private static DeviceEx D3DDevice;
private Texture renderTarget;
private bool _disposed;
// - property --------------------------------------------------------------------
public int RenderWait { get; set; } = 10; // default: 2ms
// - public methods --------------------------------------------------------------
public Dx11ImageSource()
{
StartD3D();
Dx11ImageSource.ActiveClients++;
IsFrontBufferAvailableChanged += Dx11ImageSource_IsFrontBufferAvailableChanged;
}
private void Dx11ImageSource_IsFrontBufferAvailableChanged(object sender, System.Windows.DependencyPropertyChangedEventArgs e)
{
//UpdateBackBuffer();
}
public void Dispose()
{
if (_disposed) return;
_disposed = true;
SetRenderTarget(null);
Disposer.SafeDispose(ref renderTarget);
Dx11ImageSource.ActiveClients--;
EndD3D();
}
public void InvalidateD3DImage()
{
if (!this.IsFrontBufferAvailable) return;
if (renderTarget != null)
{
using (var surface = renderTarget.GetSurfaceLevel(0))
{
base.Lock();
base.SetBackBuffer(D3DResourceType.IDirect3DSurface9, surface.NativePointer, true);
if (RenderWait != 0)
{
Thread.Sleep(RenderWait);
}
base.AddDirtyRect(new System.Windows.Int32Rect(0, 0, base.PixelWidth, base.PixelHeight));
base.Unlock();
}
}
}
private void UpdateBackBuffer()
{
using (var surface = renderTarget.GetSurfaceLevel(0))
{
base.Lock();
base.SetBackBuffer(D3DResourceType.IDirect3DSurface9, surface.NativePointer, true);
base.Unlock();
}
}
public void SetRenderTarget(SharpDX.Direct3D11.Texture2D target)
{
if (renderTarget != null)
{
renderTarget = null;
base.Lock();
base.SetBackBuffer(D3DResourceType.IDirect3DSurface9, IntPtr.Zero, true);
base.Unlock();
}
if (target == null)
{
return;
}
var format = Dx11ImageSource.TranslateFormat(target);
var handle = GetSharedHandle(target);
if (!IsShareable(target))
{
throw new ArgumentException("Texture must be created with ResouceOptionFlags.Shared");
}
if (format == Format.Unknown)
{
throw new ArgumentException("Texture format is not compatible with OpenSharedResouce");
}
if (handle == IntPtr.Zero)
{
throw new ArgumentException("Invalid handle");
}
renderTarget = new Texture(Dx11ImageSource.D3DDevice, target.Description.Width, target.Description.Height, 1, Usage.RenderTarget, format, Pool.Default, ref handle);
using (var surface = renderTarget.GetSurfaceLevel(0))
{
base.Lock();
base.SetBackBuffer(D3DResourceType.IDirect3DSurface9, surface.NativePointer, true);
base.Unlock();
}
}
// - private methods -------------------------------------------------------------
private void StartD3D()
{
if (Dx11ImageSource.ActiveClients != 0)
{
return;
}
var presentParams = GetPresentParameters();
var createFlags = CreateFlags.HardwareVertexProcessing | CreateFlags.Multithreaded | CreateFlags.FpuPreserve;
Dx11ImageSource.D3DContext = new Direct3DEx();
Dx11ImageSource.D3DDevice = new DeviceEx(D3DContext, 0, DeviceType.Hardware, IntPtr.Zero, createFlags, presentParams);
}
private void EndD3D()
{
if (Dx11ImageSource.ActiveClients != 0)
{
return;
}
Disposer.SafeDispose(ref renderTarget);
Disposer.SafeDispose(ref Dx11ImageSource.D3DDevice);
Disposer.SafeDispose(ref Dx11ImageSource.D3DContext);
}
private static void ResetD3D()
{
if (Dx11ImageSource.ActiveClients == 0)
{
return;
}
var presentParams = GetPresentParameters();
Dx11ImageSource.D3DDevice.ResetEx(ref presentParams);
}
private static PresentParameters GetPresentParameters()
{
var presentParams = new PresentParameters();
presentParams.Windowed = true;
presentParams.SwapEffect = SwapEffect.Discard;
presentParams.DeviceWindowHandle = NativeMethods.GetDesktopWindow();
presentParams.PresentationInterval = PresentInterval.Default;
return presentParams;
}
private IntPtr GetSharedHandle(SharpDX.Direct3D11.Texture2D texture)
{
using (var resource = texture.QueryInterface<SharpDX.DXGI.Resource>())
{
return resource.SharedHandle;
}
}
private static Format TranslateFormat(SharpDX.Direct3D11.Texture2D texture)
{
switch (texture.Description.Format)
{
case SharpDX.DXGI.Format.R10G10B10A2_UNorm: return SharpDX.Direct3D9.Format.A2B10G10R10;
case SharpDX.DXGI.Format.R16G16B16A16_Float: return SharpDX.Direct3D9.Format.A16B16G16R16F;
case SharpDX.DXGI.Format.B8G8R8A8_UNorm: return SharpDX.Direct3D9.Format.A8R8G8B8;
default: return SharpDX.Direct3D9.Format.Unknown;
}
}
private static bool IsShareable(SharpDX.Direct3D11.Texture2D texture)
{
return (texture.Description.OptionFlags & SharpDX.Direct3D11.ResourceOptionFlags.Shared) != 0;
}
}
}
| 32.512315 | 176 | 0.545303 | [
"Apache-2.0"
] | ascora/LottieSharp | LottieSharp/WpfSurface/Dx11ImageSource.cs | 6,602 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace CoinMarketCapNet.Endpoints
{
internal enum EndpointSecurityType
{
None,
ApiKey
}
}
| 14.615385 | 38 | 0.689474 | [
"MIT"
] | M-Boukhlouf/CoinMarketCapNet | CoinMarketCapNet/Endpoints/EndpointSecurityType.cs | 192 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MsExcel = Microsoft.Office.Interop.Excel;
namespace ComWrapper.Excel
{
public class Names : WrapperBase<MsExcel.Names>, IEnumerable<Name>
{
public int Count
{
get { return ComObject.Count; }
}
public Name this[int idx]
{
get { return new Name(this, ComObject.Item(idx)); }
}
/// <summary>
///
/// </summary>
/// <param name="parent"></param>
/// <param name="comObject"></param>
public Names(WrapperBase parent, MsExcel.Names comObject) : base(parent, comObject)
{ }
public IEnumerator<Name> GetEnumerator()
{
IEnumerator e = ComObject.GetEnumerator();
while (e.MoveNext())
yield return new Name(this, (MsExcel.Name)e.Current);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
}
| 25.113636 | 91 | 0.569231 | [
"MIT"
] | sumakineko/ComWrapper | ExcelWrapper/Excel/Names.cs | 1,107 | C# |
// Copyright (c) 2015 - 2019 Doozy Entertainment. All Rights Reserved.
// This code can only be used under the standard Unity Asset Store End User License Agreement
// A Copy of the EULA APPENDIX 1 is available at http://unity3d.com/company/legal/as_terms
using System;
using Doozy.Editor.Nody;
using Doozy.Engine.Extensions;
using Doozy.Editor.Nody.NodeGUI;
using Doozy.Engine.Nody.Connections;
using Doozy.Engine.Nody.Models;
using Doozy.Engine.UI.Nodes;
using UnityEditor;
using UnityEngine;
namespace Doozy.Editor.UI.Nodes
{
// ReSharper disable once UnusedMember.Global
[CustomNodeGUI(typeof(PortalNode))]
public class PortalNodeGUI : BaseNodeGUI
{
private static GUIStyle s_iconStyle;
private static GUIStyle IconStyle { get { return s_iconStyle ?? (s_iconStyle = Styles.GetStyle(Styles.StyleName.NodeIconPortalNode)); } }
protected override GUIStyle GetIconStyle() { return IconStyle; }
private PortalNode TargetNode { get { return (PortalNode) Node; } }
protected override void OnNodeGUI()
{
DrawNodeBody();
if (TargetNode.SwitchBackMode)
{
if (TargetNode.InputSockets == null ||
TargetNode.InputSockets.Count == 0)
{
TargetNode.AddInputSocket(ConnectionMode.Multiple, typeof(PassthroughConnection), false, false);
GraphEvent.ConstructGraph();
GraphEvent.RecalculateAllPoints();
}
DrawSocketsList(Node.InputSockets);
}
else
{
if (TargetNode.InputSockets != null
&& TargetNode.InputSockets.Count > 0)
{
if (TargetNode.FirstInputSocket != null &&
TargetNode.FirstInputSocket.IsConnected)
GraphEvent.DisconnectSocket(TargetNode.FirstInputSocket);
TargetNode.InputSockets.Clear();
GraphEvent.ConstructGraph();
GraphEvent.RecalculateAllPoints();
}
}
DrawSocketsList(Node.OutputSockets);
DrawActionDescription();
}
private GUIStyle m_actionIcon;
private string m_title;
private string m_description;
private GUIStyle m_sourceIcon;
private string m_sourceNodeName;
private Styles.StyleName WaitForActionIconStyleName
{
get
{
switch (TargetNode.ListenFor)
{
case PortalNode.ListenerType.GameEvent: return Styles.StyleName.IconGameEventListener;
case PortalNode.ListenerType.UIView: return Styles.StyleName.IconUIViewListener;
case PortalNode.ListenerType.UIButton: return Styles.StyleName.IconUIButtonListener;
case PortalNode.ListenerType.UIDrawer: return Styles.StyleName.IconUIDrawerListener;
default: throw new ArgumentOutOfRangeException();
}
}
}
private void DrawActionDescription()
{
DynamicHeight += DGUI.Properties.Space(4);
float x = DrawRect.x + 16;
float lineHeight = DGUI.Properties.SingleLineHeight;
float iconLineHeight = lineHeight * 2;
float iconSize = iconLineHeight * 0.6f;
var iconRect = new Rect(x, DynamicHeight + (iconLineHeight - iconSize) / 2, iconSize, iconSize);
float textX = iconRect.xMax + DGUI.Properties.Space(4);
float textWidth = DrawRect.width - iconSize - DGUI.Properties.Space(4) - 32;
var titleRect = new Rect(textX, DynamicHeight, textWidth, lineHeight);
DynamicHeight += titleRect.height;
var descriptionRect = new Rect(textX, DynamicHeight, textWidth, lineHeight);
DynamicHeight += descriptionRect.height;
DynamicHeight += DGUI.Properties.Space(4);
var sourceIconRect = new Rect();
var sourceTextRect = new Rect();
bool switchBackModeEnabled = TargetNode.SwitchBackMode && TargetNode.HasSource;
if (switchBackModeEnabled)
{
DynamicHeight -= DGUI.Properties.Space(2);
sourceIconRect = new Rect(iconRect.x, DynamicHeight + (iconLineHeight - iconSize) / 2, iconSize, iconSize);
DynamicHeight += (iconLineHeight - iconSize) / 2 + 2;
sourceTextRect = new Rect(textX, DynamicHeight, textWidth, lineHeight);
DynamicHeight += sourceTextRect.height;
DynamicHeight += DGUI.Properties.Space(4);
}
if (ZoomedBeyondSocketDrawThreshold) return;
m_actionIcon = Styles.GetStyle(WaitForActionIconStyleName);
m_title = UILabels.ListenFor + ": ";
switch (TargetNode.ListenFor)
{
case PortalNode.ListenerType.GameEvent:
m_title += TargetNode.WaitForInfoTitle;
break;
case PortalNode.ListenerType.UIButton:
case PortalNode.ListenerType.UIView:
case PortalNode.ListenerType.UIDrawer:
m_title = TargetNode.WaitForInfoTitle;
break;
}
m_description = TargetNode.WaitForInfoDescription;
Color iconAndTextColor = (DGUI.Utility.IsProSkin ? Color.white.Darker() : Color.black.Lighter()).WithAlpha(0.6f);
DGUI.Icon.Draw(iconRect, m_actionIcon, iconAndTextColor);
GUI.Label(titleRect, m_title, DGUI.Colors.ColorTextOfGUIStyle(DGUI.Label.Style(Editor.Size.S, TextAlign.Left), iconAndTextColor));
GUI.Label(descriptionRect, m_description, DGUI.Colors.ColorTextOfGUIStyle(DGUI.Label.Style(Doozy.Editor.Size.M, TextAlign.Left), iconAndTextColor));
if (!switchBackModeEnabled) return;
m_sourceIcon = Styles.GetStyle(Styles.StyleName.IconFaAngleDoubleLeft);
DGUI.Icon.Draw(sourceIconRect, m_sourceIcon, iconAndTextColor);
GUI.Label(sourceTextRect, TargetNode.Source.Name, DGUI.Colors.ColorTextOfGUIStyle(DGUI.Label.Style(Doozy.Editor.Size.M, TextAlign.Left), iconAndTextColor));
}
}
} | 44.842466 | 169 | 0.601497 | [
"MIT"
] | MikaelStenstrand/drivingo | Assets/Doozy/Editor/UI/Nodes/GUIs/PortalNodeGUI.cs | 6,547 | C# |
using System;
namespace WebMagicSharp.Utils
{
public static class LangUtils
{
public static int HASH_SEED = 17;
public static int HASH_OFFSET = 37;
/** Disabled default constructor. */
public static int HashCode(int seed, int hashcode)
{
return seed * HASH_OFFSET + hashcode;
}
public static int HashCode(int seed, bool b)
{
return HashCode(seed, b ? 1 : 0);
}
public static int HashCode(int seed, object obj)
{
return HashCode(seed, obj != null ? obj.GetHashCode() : 0);
}
/**
* Check if two objects are equal.
*
* @param obj1 first object to compare, may be {@code null}
* @param obj2 second object to compare, may be {@code null}
* @return {@code true} if the objects are equal or both null
*/
public new static bool Equals(object obj1, object obj2)
{
return obj1 == null ? obj2 == null : obj1.Equals(obj2);
}
/**
* Check if two object arrays are equal.
* <ul>
* <li>If both parameters are null, return {@code true}</li>
* <li>If one parameter is null, return {@code false}</li>
* <li>If the array lengths are different, return {@code false}</li>
* <li>Compare array elements using .equals(); return {@code false} if any comparisons fail.</li>
* <li>Return {@code true}</li>
* </ul>
*
* @param a1 first array to compare, may be {@code null}
* @param a2 second array to compare, may be {@code null}
* @return {@code true} if the arrays are equal or both null
*/
public static bool Equals(object[] a1, object[] a2)
{
if (a1 == null)
{
return a2 == null;
}
else
{
if (a2 != null && a1.Length == a2.Length)
{
for (int i = 0; i < a1.Length; i++)
{
if (!Equals(a1[i], a2[i]))
{
return false;
}
}
return true;
}
else
{
return false;
}
}
}
}
}
| 30.64557 | 105 | 0.458488 | [
"Apache-2.0"
] | Peefy/DuGu.WebMagicSharp | WebMagicSharp/Utils/LangUtils.cs | 2,423 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Linq;
namespace PVInfo
{
class Program
{
static void Main(string[] args)
{
/*
string folderOfScans = @"X:\Data\C57\GRABNE\2021-10-04-ne-washon";
if (args.Length == 1) {
folderOfScans = args[0];
}
MakeIndex(folderOfScans);
*/
// ffmpeg.exe -y -i video.avi -c:v libx264 -pix_fmt yuv420p video.mp4
string[] folders = {
"X:/Data/OT-Cre/OT-GCaMP-nonspecific/04-03-19 evoke OT/19421000",
"X:/Data/OT-Cre/OT-GCaMP-nonspecific/04-03-19 evoke OT/19528000",
"X:/Data/OT-Cre/OT-GCaMP-nonspecific/04-03-19 evoke OT/04-30-2020 K-GLU analyze/19528021",
"X:/Data/OT-Cre/OT-GCaMP-nonspecific/04-03-19 evoke OT/19610000",
"X:/Data/OT-Cre/OT-GCaMP-nonspecific/04-03-19 evoke OT/04-30-2020 K-GLU analyze/19610009",
"X:/Data/OT-Cre/OT-GCaMP-nonspecific/04-03-19 evoke OT/19523000",
"X:/Data/OT-Cre/OT-GCaMP-nonspecific/04-03-19 evoke OT/04-30-2020 K-GLU analyze/19523009",
"X:/Data/OT-Cre/OT-GCaMP-nonspecific/04-03-19 evoke OT/19523019",
"X:/Data/OT-Cre/OT-GCaMP-nonspecific/04-03-19 evoke OT/04-30-2020 K-GLU analyze/19d09000",
"X:/Data/OT-Cre/OT-GCaMP-nonspecific/04-03-19 evoke OT/04-30-2020 K-GLU analyze/20207000",
"X:/Data/OT-Cre/OT-GCaMP-nonspecific/04-03-19 evoke OT/04-30-2020 K-GLU analyze/20207019",
"X:/Data/OT-Cre/OT-GCaMP-nonspecific/04-03-19 evoke OT/04-30-2020 K-GLU analyze/20214011",
"X:/Data/OT-Cre/OT-GCaMP-nonspecific/04-03-19 evoke OT/04-30-2020 K-GLU analyze/20214022",
};
foreach (string folder in folders)
{
MakeIndex(folder);
}
}
static string GetImageHtml(string folderPath)
{
StringBuilder sb = new();
string[] extensions = { ".png", ".gif", ".jpg", ".jpeg" };
string[] filenames = Directory.GetFiles(folderPath)
.Select(x => Path.GetFileName(x))
.Where(x => extensions.Contains(Path.GetExtension(x)))
.ToArray();
foreach (var filename in filenames)
sb.AppendLine($"<a href='{filename}'><img src='{filename}' height='300' class='shadow border m-3' /></a>");
return sb.ToString();
}
static string GetVideoHtml(string folderPath)
{
StringBuilder sb = new();
string[] extensions = { /*".avi",*/ ".mp4" };
string[] filenames = Directory.GetFiles(folderPath)
.Select(x => Path.GetFileName(x))
.Where(x => extensions.Contains(Path.GetExtension(x)))
.ToArray();
foreach (var filename in filenames)
sb.AppendLine($"<video class='m-3' height='300' controls><source src='{filename}' type='video/mp4'></video>");
return sb.ToString();
}
static void MakeIndex(string folderPath)
{
StringBuilder sb = new();
sb.AppendLine($"<h3><code>{folderPath}</code></h3>");
string[] imageExtensions = { ".png", ".gif", ".jpg", ".jpeg" };
string[] imageFilenames = Directory.GetFiles(folderPath)
.Select(x => Path.GetFileName(x))
.Where(x => imageExtensions.Contains(Path.GetExtension(x)))
.ToArray();
sb.AppendLine("<div class='bg-light my-3 d-flex'>");
sb.AppendLine(GetImageHtml(folderPath));
sb.AppendLine(GetVideoHtml(folderPath));
sb.AppendLine("</div>");
foreach (var pvFolderPath in Directory.GetDirectories(folderPath))
{
PVScan.IScan scan = PVScan.ScanFactory.FromPVFolder(pvFolderPath);
if (scan is not null)
{
Console.WriteLine($"Analyzing: {pvFolderPath}");
sb.AppendLine("<div class='my-5 p-3 bg-light shadow border rounded bg-white'>");
sb.AppendLine($"<h1>{scan.ScanType}: {Path.GetFileName(pvFolderPath)}</h1>");
AddHeading(sb, $"Scan Information");
Code(sb, scan.GetSummary());
ShowImages(pvFolderPath, sb);
sb.AppendLine("</div>");
}
else
{
Console.WriteLine($"Skipping: {pvFolderPath}");
}
}
string template = File.ReadAllText("template.html");
string html = template.Replace("{{CONTENT}}", sb.ToString());
string reportFilePath = Path.Combine(folderPath, "index.html");
File.WriteAllText(reportFilePath, html);
Console.WriteLine(reportFilePath);
}
static void AddHeading(StringBuilder sb, string heading)
{
sb.AppendLine($"<h3>{heading}</h3>");
}
static void CodeStart(StringBuilder sb) => sb.Append($"\n<pre class='p-2'>");
static void CodeEnd(StringBuilder sb) => sb.Append($"</pre>\n");
static void Code(StringBuilder sb, string code)
{
CodeStart(sb);
sb.Append(code);
CodeEnd(sb);
}
static void ShowImages(string pvFolderPath, StringBuilder sb)
{
string pvFolderName = Path.GetFileName(pvFolderPath);
List<string> tifFiles = new();
List<string> imageFiles = new();
List<string> notesFiles = new();
List<string> videoFiles = new();
string[] supportedExtensions = { ".jpg", ".gif", ".png" };
foreach (string subFolderPath in Directory.GetDirectories(pvFolderPath))
{
foreach (string filePath in Directory.GetFiles(subFolderPath, "*.*"))
{
string ext = Path.GetExtension(filePath);
if (ext == ".tif")
tifFiles.Add(filePath);
if (ext == ".txt")
notesFiles.Add(filePath);
if (ext == ".mp4")
videoFiles.Add(filePath);
if (ext == ".jpg" || ext == ".gif" || ext == ".png")
imageFiles.Add(filePath);
}
}
AddHeading(sb, $"Experiment Notes ({notesFiles.Count})");
CodeStart(sb);
foreach (string notesFile in notesFiles)
sb.AppendLine(File.ReadAllText(notesFile));
CodeEnd(sb);
AddHeading(sb, $"Processed TIFs ({tifFiles.Count}):");
CodeStart(sb);
foreach (string tif in tifFiles)
sb.AppendLine(tif);
CodeEnd(sb);
AddHeading(sb, $"Processed Images ({imageFiles.Count}):");
CodeStart(sb);
foreach (string imageFile in imageFiles)
sb.AppendLine(imageFile);
CodeEnd(sb);
foreach (string imageFile in imageFiles)
{
string imageFolderName = Path.GetFileName(Path.GetDirectoryName(imageFile));
string imageFileName = Path.GetFileName(imageFile);
string imageUrl = $"{pvFolderName}/{imageFolderName}/{imageFileName}";
sb.AppendLine($"<a href='{imageUrl}'><img src='{imageUrl}'></a>");
}
AddHeading(sb, $"Processed Videos ({videoFiles.Count}):");
CodeStart(sb);
foreach (string videoFile in videoFiles)
sb.AppendLine(Path.GetDirectoryName(pvFolderPath) + "/" + videoFile);
CodeEnd(sb);
foreach (string videoFile in videoFiles)
{
string videoFolderName = Path.GetFileName(Path.GetDirectoryName(videoFile));
string videoFileName = Path.GetFileName(videoFile);
string videoUrl = $"{pvFolderName}/{videoFolderName}/{videoFileName}";
sb.AppendLine($"<video class='m-3' controls><source src='{videoUrl}' type='video/mp4'></video>");
}
}
}
} | 40.592233 | 126 | 0.532289 | [
"MIT"
] | swharden/ephys-projects | tools/PVInfo/Program.cs | 8,364 | C# |
#region License
// Copyright (c) Jeremy Skinner (http://www.jeremyskinner.co.uk)
//
// 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.
//
// The latest version of this file can be found at https://github.com/JeremySkinner/FluentValidation
#endregion
namespace FluentValidation.Resources {
using Validators;
internal class DutchLanguage : Language {
public override string Name => "nl";
public DutchLanguage() {
Translate<EmailValidator>("'{PropertyName}' is geen geldig email adres.");
Translate<EqualValidator>("'{PropertyName}' moet gelijk zijn aan '{ComparisonValue}'.");
Translate<GreaterThanOrEqualValidator>("'{PropertyName}' moet meer dan of gelijk zijn aan '{ComparisonValue}'.");
Translate<GreaterThanValidator>("'{PropertyName}' moet groter zijn dan '{ComparisonValue}'.");
Translate<LengthValidator>("De lengte van '{PropertyName}' moet tussen {MinLength} en {MaxLength} karakters zijn. Er zijn {TotalLength} karakters ingevoerd.");
Translate<MinimumLengthValidator>("De lengte van '{PropertyName}' moet groter zijn dan of gelijk aan {MinLength} tekens. U hebt {TotalLength} -tekens ingevoerd.");
Translate<MaximumLengthValidator>("De lengte van '{PropertyName}' moet kleiner zijn dan of gelijk aan {MaxLength} tekens. U hebt {TotalLength} -tekens ingevoerd.");
Translate<LessThanOrEqualValidator>("'{PropertyName}' moet minder dan of gelijk zijn aan '{ComparisonValue}'.");
Translate<LessThanValidator>("'{PropertyName}' moet minder zijn dan '{ComparisonValue}'.");
Translate<NotEmptyValidator>("'{PropertyName}' mag niet leeg zijn.");
Translate<NotEqualValidator>("'{PropertyName}' moet anders zijn dan '{ComparisonValue}'.");
Translate<NotNullValidator>("'{PropertyName}' mag niet leeg zijn.");
Translate<PredicateValidator>("'{PropertyName}' voldoet niet aan de vereisten.");
Translate<AsyncPredicateValidator>("'{PropertyName}' voldoet niet aan de vereisten.");
Translate<RegularExpressionValidator>("'{PropertyName}' voldoet niet aan het verwachte formaat.");
Translate<ExactLengthValidator>("De lengte van '{PropertyName}' moet {MaxLength} karakters zijn. Er zijn {TotalLength} karakters ingevoerd.");
Translate<EnumValidator>("'{PropertyValue}' komt niet voor in het bereik van '{PropertyName}'.");
Translate<CreditCardValidator>("'{PropertyName}' is geen geldig credit card nummer.");
Translate<EmptyValidator>("'{PropertyName}' hoort leeg te zijn.");
Translate<ExclusiveBetweenValidator>("'{PropertyName}' moet na {From} komen en voor {To} liggen. Je hebt ingevuld {Value}.");
Translate<InclusiveBetweenValidator>("'{PropertyName}' moet tussen {From} en {To} liggen. Je hebt ingevuld {Value}.");
Translate<ScalePrecisionValidator>("'{PropertyName}' mag in totaal niet meer dan {ExpectedPrecision} decimalen nauwkeurig zijn, met een grote van {ExpectedScale} gehele getallen. Er zijn {Digits} decimalen en een grote van {ActualScale} gehele getallen gevonden.");
Translate<NullValidator>("'{PropertyName}' moet leeg zijn.");
}
}
} | 70.45098 | 269 | 0.738937 | [
"Apache-2.0"
] | MDormann/FluentValidation | src/FluentValidation/Resources/Languages/DutchLanguage.cs | 3,593 | C# |
using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Interop;
using System.Windows.Media;
using OpenTK.Graphics.OpenGL;
using OpenTK.Graphics.Wgl;
using OpenTK.Wpf.Interop;
namespace OpenTK.Wpf
{
/// Renderer that uses DX_Interop for a fast-path.
internal sealed class GLWpfControlRenderer {
private readonly Stopwatch _stopwatch = Stopwatch.StartNew();
private readonly DxGlContext _context;
public event Action<TimeSpan> GLRender;
public event Action GLAsyncRender;
private DxGLFramebuffer _framebuffer;
/// The OpenGL framebuffer handle.
public int FrameBufferHandle => _framebuffer?.GLFramebufferHandle ?? 0;
/// The OpenGL Framebuffer width
public int Width => _framebuffer?.FramebufferWidth ?? 0;
/// The OpenGL Framebuffer height
public int Height => _framebuffer?.FramebufferHeight ?? 0;
private TimeSpan _lastFrameStamp;
public GLWpfControlRenderer(GLWpfControlSettings settings)
{
_context = new DxGlContext(settings);
}
public void SetSize(int width, int height, double dpiScaleX, double dpiScaleY) {
if (_framebuffer == null || _framebuffer.Width != width || _framebuffer.Height != height) {
_framebuffer?.Dispose();
_framebuffer = null;
if (width > 0 && height > 0) {
_framebuffer = new DxGLFramebuffer(_context, width, height, dpiScaleX, dpiScaleY);
}
}
}
public void Render(DrawingContext drawingContext) {
if (_framebuffer == null) {
return;
}
var curFrameStamp = _stopwatch.Elapsed;
var deltaT = curFrameStamp - _lastFrameStamp;
_lastFrameStamp = curFrameStamp;
PreRender();
GLRender?.Invoke(deltaT);
GL.BindFramebuffer(FramebufferTarget.Framebuffer, 0);
GL.Flush();
GLAsyncRender?.Invoke();
PostRender();
// Transforms are applied in reverse order
drawingContext.PushTransform(_framebuffer.TranslateTransform); // Apply translation to the image on the Y axis by the height. This assures that in the next step, where we apply a negative scale the image is still inside of the window
drawingContext.PushTransform(_framebuffer.FlipYTransform); // Apply a scale where the Y axis is -1. This will rotate the image by 180 deg
// dpi scaled rectangle from the image
var rect = new Rect(0, 0, _framebuffer.D3dImage.Width, _framebuffer.D3dImage.Height);
drawingContext.DrawImage(_framebuffer.D3dImage, rect); // Draw the image source
drawingContext.Pop(); // Remove the scale transform
drawingContext.Pop(); // Remove the translation transform
}
/// Sets up the framebuffer, directx stuff for rendering.
private void PreRender()
{
_framebuffer.D3dImage.Lock();
Wgl.DXLockObjectsNV(_context.GlDeviceHandle, 1, new [] {_framebuffer.DxInteropRegisteredHandle});
GL.BindFramebuffer(FramebufferTarget.Framebuffer, _framebuffer.GLFramebufferHandle);
GL.Viewport(0, 0, _framebuffer.FramebufferWidth, _framebuffer.FramebufferHeight);
}
/// Sets up the framebuffer and prepares stuff for usage in directx.
private void PostRender()
{
Wgl.DXUnlockObjectsNV(_context.GlDeviceHandle, 1, new [] {_framebuffer.DxInteropRegisteredHandle});
_framebuffer.D3dImage.SetBackBuffer(D3DResourceType.IDirect3DSurface9, _framebuffer.DxRenderTargetHandle);
_framebuffer.D3dImage.AddDirtyRect(new Int32Rect(0, 0, _framebuffer.FramebufferWidth, _framebuffer.FramebufferHeight));
_framebuffer.D3dImage.Unlock();
}
}
}
| 42.670103 | 258 | 0.623822 | [
"MIT"
] | BBoldenow/GLWpfControl | src/GLWpfControl/GLWpfControlRenderer.cs | 4,139 | C# |
/*
* Copyright (c) 2018, Firely (info@fire.ly) and contributors
* See the file CONTRIBUTORS for details.
*
* This file is licensed under the BSD 3-Clause license
* available at https://github.com/ewoutkramer/fhir-net-api/blob/master/LICENSE
*/
using Hl7.Fhir.Introspection;
using Hl7.Fhir.Model;
using Hl7.Fhir.Serialization;
using Hl7.Fhir.Utility;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
namespace Hl7.Fhir.Specification
{
public class PocoStructureDefinitionSummaryProvider : IStructureDefinitionSummaryProvider
{
public IStructureDefinitionSummary Provide(Type type)
{
var classMapping = GetMappingForType(type);
if (classMapping == null) return null;
return new PocoComplexTypeSerializationInfo(classMapping);
}
public IStructureDefinitionSummary Provide(string canonical)
{
var isLocalType = !canonical.Contains("/");
var typeName = canonical;
if(!isLocalType)
{
// So, we have received a canonical url, not being a relative path
// (know resource/datatype), we -for now- only know how to get a ClassMapping
// for this, if it's a built-in T4 generated POCO, so there's no way
// to find a mapping for this.
return null;
}
Type csType = ModelInfo.GetTypeForFhirType(typeName);
if (csType == null) return null;
return Provide(csType);
}
internal static ClassMapping GetMappingForType(Type elementType)
{
var inspector = Serialization.BaseFhirParser.Inspector;
return inspector.ImportType(elementType);
}
}
internal struct PocoComplexTypeSerializationInfo : IStructureDefinitionSummary
{
private readonly ClassMapping _classMapping;
public PocoComplexTypeSerializationInfo(ClassMapping classMapping)
{
_classMapping = classMapping;
}
public string TypeName => !_classMapping.IsBackbone ? _classMapping.Name :
(_classMapping.NativeType.CanBeTreatedAsType(typeof(BackboneElement)) ?
"BackboneElement" : "Element");
public bool IsAbstract => _classMapping.IsAbstract;
public bool IsResource => _classMapping.IsResource;
public IEnumerable<IElementDefinitionSummary> GetElements() =>
_classMapping.PropertyMappings.Where(pm => !pm.RepresentsValueElement).Select(pm =>
(IElementDefinitionSummary)new PocoElementSerializationInfo(pm));
}
internal struct PocoTypeReferenceInfo : IStructureDefinitionReference
{
public PocoTypeReferenceInfo(string canonical)
{
ReferredType = canonical;
}
public string ReferredType { get; private set; }
}
internal struct PocoElementSerializationInfo : IElementDefinitionSummary
{
private readonly PropertyMapping _pm;
// [WMR 20180822] OPTIMIZE: use LazyInitializer.EnsureInitialized instead of Lazy<T>
// Lazy<T> introduces considerable performance degradation when running in debugger (F5) ?
//private readonly Lazy<ITypeSerializationInfo[]> _types;
private ITypeSerializationInfo[] _types;
internal PocoElementSerializationInfo(PropertyMapping pm)
{
_pm = pm;
// [WMR 20180822] OPTIMIZE
// _types = new Lazy<ITypeSerializationInfo[]>(() => buildTypes(pm));
_types = null;
}
// [WMR 20180822] OPTIMIZE
// private static ITypeSerializationInfo[] buildTypes(PropertyMapping pm)
private ITypeSerializationInfo[] buildTypes()
{
var pm = _pm;
if (pm.IsBackboneElement)
{
var mapping = PocoStructureDefinitionSummaryProvider.GetMappingForType(pm.ImplementingType);
return new ITypeSerializationInfo[] { new PocoComplexTypeSerializationInfo(mapping) };
}
else
{
var names = pm.FhirType.Select(ft => getFhirTypeName(ft));
return names.Select(n => (ITypeSerializationInfo)new PocoTypeReferenceInfo(n)).ToArray();
}
string getFhirTypeName(Type ft)
{
var map = PocoStructureDefinitionSummaryProvider.GetMappingForType(ft);
return map.IsCodeOfT ? "code" : map.Name;
}
}
public string ElementName => _pm.Name;
public bool IsCollection => _pm.IsCollection;
public bool InSummary => _pm.InSummary;
public XmlRepresentation Representation => _pm.SerializationHint != XmlRepresentation.None ?
_pm.SerializationHint : XmlRepresentation.XmlElement;
public bool IsChoiceElement => _pm.Choice == ChoiceType.DatatypeChoice;
public bool IsResource => _pm.Choice == ChoiceType.ResourceChoice;
public bool IsRequired => _pm.IsMandatoryElement;
public int Order => _pm.Order;
// [WMR 20180822] OPTIMIZE
public ITypeSerializationInfo[] Type //=> _types.Value;
{
get
{
// [WMR 20180822] Optimize lazy initialization
// Multiple threads may execute buildTypes, first result is used & assigned
// Safe, because buildTypes is idempotent
LazyInitializer.EnsureInitialized(ref _types, buildTypes);
return _types;
}
}
public string NonDefaultNamespace => null;
}
}
| 34.521212 | 108 | 0.635007 | [
"BSD-3-Clause"
] | amitpuri/fhir-net-api | src/Hl7.Fhir.Core/Specification/PocoStructureDefinitionSummaryProvider.cs | 5,698 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Gcp.Organizations
{
public static partial class Invokes
{
/// <summary>
/// Generates an IAM policy document that may be referenced by and applied to
/// other Google Cloud Platform resources, such as the `gcp.organizations.Project` resource.
///
/// **Note:** Several restrictions apply when setting IAM policies through this API.
/// See the [setIamPolicy docs](https://cloud.google.com/resource-manager/reference/rest/v1/projects/setIamPolicy)
/// for a list of these restrictions.
///
///
/// This data source is used to define IAM policies to apply to other resources.
/// Currently, defining a policy through a datasource and referencing that policy
/// from another resource is the only way to apply an IAM policy to a resource.
///
/// > This content is derived from https://github.com/terraform-providers/terraform-provider-google/blob/master/website/docs/d/iam_policy.html.markdown.
/// </summary>
public static Task<GetIAMPolicyResult> GetIAMPolicy(GetIAMPolicyArgs? args = null, InvokeOptions? options = null)
=> Pulumi.Deployment.Instance.InvokeAsync<GetIAMPolicyResult>("gcp:organizations/getIAMPolicy:getIAMPolicy", args ?? InvokeArgs.Empty, options.WithVersion());
}
public sealed class GetIAMPolicyArgs : Pulumi.InvokeArgs
{
[Input("auditConfigs")]
private List<Inputs.GetIAMPolicyAuditConfigsArgs>? _auditConfigs;
/// <summary>
/// A nested configuration block that defines logging additional configuration for your project.
/// </summary>
public List<Inputs.GetIAMPolicyAuditConfigsArgs> AuditConfigs
{
get => _auditConfigs ?? (_auditConfigs = new List<Inputs.GetIAMPolicyAuditConfigsArgs>());
set => _auditConfigs = value;
}
[Input("bindings")]
private List<Inputs.GetIAMPolicyBindingsArgs>? _bindings;
/// <summary>
/// A nested configuration block (described below)
/// defining a binding to be included in the policy document. Multiple
/// `binding` arguments are supported.
/// </summary>
public List<Inputs.GetIAMPolicyBindingsArgs> Bindings
{
get => _bindings ?? (_bindings = new List<Inputs.GetIAMPolicyBindingsArgs>());
set => _bindings = value;
}
public GetIAMPolicyArgs()
{
}
}
[OutputType]
public sealed class GetIAMPolicyResult
{
public readonly ImmutableArray<Outputs.GetIAMPolicyAuditConfigsResult> AuditConfigs;
public readonly ImmutableArray<Outputs.GetIAMPolicyBindingsResult> Bindings;
/// <summary>
/// The above bindings serialized in a format suitable for
/// referencing from a resource that supports IAM.
/// </summary>
public readonly string PolicyData;
/// <summary>
/// id is the provider-assigned unique ID for this managed resource.
/// </summary>
public readonly string Id;
[OutputConstructor]
private GetIAMPolicyResult(
ImmutableArray<Outputs.GetIAMPolicyAuditConfigsResult> auditConfigs,
ImmutableArray<Outputs.GetIAMPolicyBindingsResult> bindings,
string policyData,
string id)
{
AuditConfigs = auditConfigs;
Bindings = bindings;
PolicyData = policyData;
Id = id;
}
}
namespace Inputs
{
public sealed class GetIAMPolicyAuditConfigsArgs : Pulumi.InvokeArgs
{
[Input("auditLogConfigs", required: true)]
private List<GetIAMPolicyAuditConfigsAuditLogConfigsArgs>? _auditLogConfigs;
/// <summary>
/// A nested block that defines the operations you'd like to log.
/// </summary>
public List<GetIAMPolicyAuditConfigsAuditLogConfigsArgs> AuditLogConfigs
{
get => _auditLogConfigs ?? (_auditLogConfigs = new List<GetIAMPolicyAuditConfigsAuditLogConfigsArgs>());
set => _auditLogConfigs = value;
}
/// <summary>
/// Defines a service that will be enabled for audit logging. For example, `storage.googleapis.com`, `cloudsql.googleapis.com`. `allServices` is a special value that covers all services.
/// </summary>
[Input("service", required: true)]
public string Service { get; set; } = null!;
public GetIAMPolicyAuditConfigsArgs()
{
}
}
public sealed class GetIAMPolicyAuditConfigsAuditLogConfigsArgs : Pulumi.InvokeArgs
{
[Input("exemptedMembers")]
private List<string>? _exemptedMembers;
/// <summary>
/// Specifies the identities that are exempt from these types of logging operations. Follows the same format of the `members` array for `binding`.
/// </summary>
public List<string> ExemptedMembers
{
get => _exemptedMembers ?? (_exemptedMembers = new List<string>());
set => _exemptedMembers = value;
}
/// <summary>
/// Defines the logging level. `DATA_READ`, `DATA_WRITE` and `ADMIN_READ` capture different types of events. See [the audit configuration documentation](https://cloud.google.com/resource-manager/reference/rest/Shared.Types/AuditConfig) for more details.
/// </summary>
[Input("logType", required: true)]
public string LogType { get; set; } = null!;
public GetIAMPolicyAuditConfigsAuditLogConfigsArgs()
{
}
}
public sealed class GetIAMPolicyBindingsArgs : Pulumi.InvokeArgs
{
[Input("condition")]
public GetIAMPolicyBindingsConditionArgs? Condition { get; set; }
[Input("members", required: true)]
private List<string>? _members;
/// <summary>
/// An array of identities that will be granted the privilege in the `role`. For more details on format and restrictions see https://cloud.google.com/billing/reference/rest/v1/Policy#Binding
/// Each entry can have one of the following values:
/// * **allUsers**: A special identifier that represents anyone who is on the internet; with or without a Google account. It **can't** be used with the `gcp.organizations.Project` resource.
/// * **allAuthenticatedUsers**: A special identifier that represents anyone who is authenticated with a Google account or a service account. It **can't** be used with the `gcp.organizations.Project` resource.
/// * **user:{emailid}**: An email address that represents a specific Google account. For example, alice@gmail.com.
/// * **serviceAccount:{emailid}**: An email address that represents a service account. For example, my-other-app@appspot.gserviceaccount.com.
/// * **group:{emailid}**: An email address that represents a Google group. For example, admins@example.com.
/// * **domain:{domain}**: A G Suite domain (primary, instead of alias) name that represents all the users of that domain. For example, google.com or example.com.
/// </summary>
public List<string> Members
{
get => _members ?? (_members = new List<string>());
set => _members = value;
}
/// <summary>
/// The role/permission that will be granted to the members.
/// See the [IAM Roles](https://cloud.google.com/compute/docs/access/iam) documentation for a complete list of roles.
/// Note that custom roles must be of the format `[projects|organizations]/{parent-name}/roles/{role-name}`.
/// </summary>
[Input("role", required: true)]
public string Role { get; set; } = null!;
public GetIAMPolicyBindingsArgs()
{
}
}
public sealed class GetIAMPolicyBindingsConditionArgs : Pulumi.InvokeArgs
{
[Input("description")]
public string? Description { get; set; }
[Input("expression", required: true)]
public string Expression { get; set; } = null!;
[Input("title", required: true)]
public string Title { get; set; } = null!;
public GetIAMPolicyBindingsConditionArgs()
{
}
}
}
namespace Outputs
{
[OutputType]
public sealed class GetIAMPolicyAuditConfigsAuditLogConfigsResult
{
/// <summary>
/// Specifies the identities that are exempt from these types of logging operations. Follows the same format of the `members` array for `binding`.
/// </summary>
public readonly ImmutableArray<string> ExemptedMembers;
/// <summary>
/// Defines the logging level. `DATA_READ`, `DATA_WRITE` and `ADMIN_READ` capture different types of events. See [the audit configuration documentation](https://cloud.google.com/resource-manager/reference/rest/Shared.Types/AuditConfig) for more details.
/// </summary>
public readonly string LogType;
[OutputConstructor]
private GetIAMPolicyAuditConfigsAuditLogConfigsResult(
ImmutableArray<string> exemptedMembers,
string logType)
{
ExemptedMembers = exemptedMembers;
LogType = logType;
}
}
[OutputType]
public sealed class GetIAMPolicyAuditConfigsResult
{
/// <summary>
/// A nested block that defines the operations you'd like to log.
/// </summary>
public readonly ImmutableArray<GetIAMPolicyAuditConfigsAuditLogConfigsResult> AuditLogConfigs;
/// <summary>
/// Defines a service that will be enabled for audit logging. For example, `storage.googleapis.com`, `cloudsql.googleapis.com`. `allServices` is a special value that covers all services.
/// </summary>
public readonly string Service;
[OutputConstructor]
private GetIAMPolicyAuditConfigsResult(
ImmutableArray<GetIAMPolicyAuditConfigsAuditLogConfigsResult> auditLogConfigs,
string service)
{
AuditLogConfigs = auditLogConfigs;
Service = service;
}
}
[OutputType]
public sealed class GetIAMPolicyBindingsConditionResult
{
public readonly string? Description;
public readonly string Expression;
public readonly string Title;
[OutputConstructor]
private GetIAMPolicyBindingsConditionResult(
string? description,
string expression,
string title)
{
Description = description;
Expression = expression;
Title = title;
}
}
[OutputType]
public sealed class GetIAMPolicyBindingsResult
{
public readonly GetIAMPolicyBindingsConditionResult? Condition;
/// <summary>
/// An array of identities that will be granted the privilege in the `role`. For more details on format and restrictions see https://cloud.google.com/billing/reference/rest/v1/Policy#Binding
/// Each entry can have one of the following values:
/// * **allUsers**: A special identifier that represents anyone who is on the internet; with or without a Google account. It **can't** be used with the `gcp.organizations.Project` resource.
/// * **allAuthenticatedUsers**: A special identifier that represents anyone who is authenticated with a Google account or a service account. It **can't** be used with the `gcp.organizations.Project` resource.
/// * **user:{emailid}**: An email address that represents a specific Google account. For example, alice@gmail.com.
/// * **serviceAccount:{emailid}**: An email address that represents a service account. For example, my-other-app@appspot.gserviceaccount.com.
/// * **group:{emailid}**: An email address that represents a Google group. For example, admins@example.com.
/// * **domain:{domain}**: A G Suite domain (primary, instead of alias) name that represents all the users of that domain. For example, google.com or example.com.
/// </summary>
public readonly ImmutableArray<string> Members;
/// <summary>
/// The role/permission that will be granted to the members.
/// See the [IAM Roles](https://cloud.google.com/compute/docs/access/iam) documentation for a complete list of roles.
/// Note that custom roles must be of the format `[projects|organizations]/{parent-name}/roles/{role-name}`.
/// </summary>
public readonly string Role;
[OutputConstructor]
private GetIAMPolicyBindingsResult(
GetIAMPolicyBindingsConditionResult? condition,
ImmutableArray<string> members,
string role)
{
Condition = condition;
Members = members;
Role = role;
}
}
}
}
| 43.837748 | 261 | 0.649218 | [
"ECL-2.0",
"Apache-2.0"
] | 23doors/pulumi-gcp | sdk/dotnet/Organizations/GetIAMPolicy.cs | 13,239 | C# |
using static System.Console;
namespace Casm.Emulator
{
public static class Program
{
public static void Main(string[] args)
{
var context = new EmulatorContext();
context.ExecuteNextInstruction();
context.ExecuteNextInstruction();
PrintRegisters(context.GetRegisterValues());
}
private static void PrintRegisters(uint[] registers)
{
for (var i = 0; i < 16; ++i)
{
WriteLine($"r{i} = 0x{registers[i]:x}");
}
}
}
} | 23.08 | 60 | 0.52513 | [
"MIT"
] | jorgy343/condor | ncasm/Casm.Emulator/Program.cs | 579 | C# |
using System;
namespace PnP.Core.Admin.Model.SharePoint
{
/// <summary>
/// Contains the available options for creating a classic site collection (e.g. classic team site)
/// </summary>
public class ClassicSiteOptions : CommonSiteOptions
{
/// <summary>
/// Default constuctor for creating a <see cref="ClassicSiteOptions"/> object used to define a classic site collection creation
/// </summary>
/// <param name="url">Url of the classic site collection to create</param>
/// <param name="title">Title of the classic site collection to create</param>
/// <param name="webTemplate">Web template of the classic site collection to create</param>
/// <param name="siteOwnerLogin">Owner of the classic site collection to create</param>
/// <param name="language">Language to use for the site</param>
/// <param name="timeZone">Time zone of the classic site collection to create</param>
public ClassicSiteOptions(Uri url, string title, string webTemplate, string siteOwnerLogin, Language language, TimeZone timeZone)
{
if (url == null)
{
throw new ArgumentNullException(nameof(url));
}
if (string.IsNullOrEmpty(title))
{
throw new ArgumentNullException(nameof(title));
}
if (string.IsNullOrEmpty(webTemplate))
{
throw new ArgumentNullException(nameof(webTemplate));
}
if (string.IsNullOrEmpty(siteOwnerLogin))
{
throw new ArgumentNullException(nameof(siteOwnerLogin));
}
if (timeZone == TimeZone.None)
{
throw new ArgumentException("Provide a timeZone value");
}
Url = url;
Title = title;
WebTemplate = webTemplate;
Owner = siteOwnerLogin;
TimeZone = timeZone;
Language = language;
}
/// <summary>
/// Title of the classic site
/// </summary>
public string Title { get; set; }
/// <summary>
/// Url of the classic site
/// </summary>
public Uri Url { get; set; }
/// <summary>
/// Owner of the classic site
/// </summary>
public string Owner { get; set; }
/// <summary>
/// Time zone id for the classic site
/// </summary>
public TimeZone TimeZone { get; set; }
}
}
| 34.013333 | 137 | 0.562917 | [
"MIT"
] | JackStrap/pnpcore | src/sdk/PnP.Core.Admin/Model/SharePoint/Core/Public/Options/ClassicSiteOptions.cs | 2,553 | C# |
//-----------------------------------------------------------------------
// <copyright file="Variable.cs" company="None">
// Copyright (c) Brandon Wallace and Jesse Calhoun. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace TQVaultData
{
using System;
using System.Globalization;
using System.Text;
/// <summary>
/// The different data-types a variable can be.
/// </summary>
public enum VariableDataType
{
/// <summary>
/// int
/// values will be Int32
/// </summary>
Integer = 0,
/// <summary>
/// float
/// values will be Single
/// </summary>
Float = 1,
/// <summary>
/// string
/// Values will be string
/// </summary>
StringVar = 2,
/// <summary>
/// bool
/// Values will be Int32
/// </summary>
Boolean = 3,
/// <summary>
/// unknown type
/// values will be Int32
/// </summary>
Unknown = 4
}
/// <summary>
/// A variable within a DB Record
/// </summary>
public class Variable
{
/// <summary>
/// the variable values.
/// </summary>
private object[] values;
/// <summary>
/// Initializes a new instance of the Variable class.
/// </summary>
/// <param name="variableName">string name of the variable.</param>
/// <param name="dataType">string type of data for variable.</param>
/// <param name="numberOfValues">int number for values that the variable contains.</param>
public Variable(string variableName, VariableDataType dataType, int numberOfValues)
{
this.Name = variableName;
this.DataType = dataType;
this.values = new object[numberOfValues];
}
/// <summary>
/// Gets the name of the variable.
/// </summary>
public string Name { get; private set; }
/// <summary>
/// Gets the Datatype of the variable.
/// </summary>
public VariableDataType DataType { get; private set; }
/// <summary>
/// Gets the number of values that the variable contains.
/// </summary>
public int NumberOfValues
{
get
{
return this.values.Length;
}
}
/// <summary>
/// Gets or sets the generic object for a particular value.
/// </summary>
/// <param name="index">Index of the value.</param>
/// <returns>object containing the value.</returns>
public object this[int index]
{
get
{
return this.values[index];
}
set
{
this.values[index] = value;
}
}
/// <summary>
/// Gets the integer for a value.
/// Throws exception if value is not the correct type
/// </summary>
/// <param name="index">Index of the value.</param>
/// <returns>Returns the integer for the value.</returns>
public int GetInt32(int index)
{
return Convert.ToInt32(this.values[index], CultureInfo.InvariantCulture);
}
/// <summary>
/// Gets the float for a value.
/// </summary>
/// <param name="index">Index of the value.</param>
/// <returns>Single of the value.</returns>
public float GetSingle(int index)
{
return Convert.ToSingle(this.values[index], CultureInfo.InvariantCulture);
}
/// <summary>
/// Gets a string for a particular value.
/// </summary>
/// <param name="index">Index of the value.</param>
/// <returns>
/// string of value.
/// </returns>
public string GetString(int index)
{
return Convert.ToString(this.values[index], CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the variable to a string.
/// Format is name,val1;val2;val3;val4;...;valn,
/// </summary>
/// <returns>Returns converted string for the values including the variable name.</returns>
public override string ToString()
{
// First set our val format string based on the data type
string formatSpec = "{0}";
if (this.DataType == VariableDataType.Float)
{
formatSpec = "{0:f6}";
}
StringBuilder ans = new StringBuilder(64);
ans.Append(this.Name);
ans.Append(",");
for (int i = 0; i < this.NumberOfValues; ++i)
{
if (i > 0)
{
ans.Append(";");
}
ans.AppendFormat(CultureInfo.InvariantCulture, formatSpec, this.values[i]);
}
ans.Append(",");
return ans.ToString();
}
/// <summary>
/// Converts the values to a string.
/// Format is name,val1;val2;val3;val4;...;valn,
/// </summary>
/// <returns>Returns converted string for the values.</returns>
public string ToStringValue()
{
// First set our val format string based on the data type
string formatSpec = "{0}";
if (this.DataType == VariableDataType.Float)
{
formatSpec = "{0:f6}";
}
StringBuilder ans = new StringBuilder(64);
for (int i = 0; i < this.NumberOfValues; ++i)
{
if (i > 0)
{
ans.Append(", ");
}
ans.AppendFormat(CultureInfo.InvariantCulture, formatSpec, this.values[i]);
}
return ans.ToString();
}
}
} | 23.699507 | 93 | 0.605903 | [
"MIT"
] | marq/TQVaultAE | src/TQVaultAE.DAL/Variable.cs | 4,813 | C# |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using UnityEngine;
using System;
using System.Linq;
using UnityEditor.EditorTools;
using UnityEditor.IMGUI.Controls;
namespace UnityEditor
{
[CustomEditor(typeof(PolygonCollider2D))]
[CanEditMultipleObjects]
internal class PolygonCollider2DEditor : Collider2DEditorBase
{
SerializedProperty m_Points;
public override void OnEnable()
{
base.OnEnable();
m_Points = serializedObject.FindProperty("m_Points");
m_AutoTiling = serializedObject.FindProperty("m_AutoTiling");
m_Points.isExpanded = false;
}
public override void OnInspectorGUI()
{
bool disableEditCollider = !CanEditCollider();
if (disableEditCollider)
{
EditorGUILayout.HelpBox(Styles.s_ColliderEditDisableHelp.text, MessageType.Info);
if (EditorTools.EditorTools.activeToolType == typeof(PolygonCollider2DTool))
EditorTools.EditorTools.RestorePreviousPersistentTool();
}
else
{
BeginColliderInspector();
}
// Grab this as the offset to the top of the drag target.
base.OnInspectorGUI();
if (targets.Length == 1)
{
EditorGUI.BeginDisabledGroup(editingCollider);
EditorGUILayout.PropertyField(m_Points, true);
EditorGUI.EndDisabledGroup();
}
EndColliderInspector();
FinalizeInspectorGUI();
HandleDragAndDrop(GUILayoutUtility.GetLastRect());
}
// Copy collider from sprite if it is drag&dropped to the inspector
private void HandleDragAndDrop(Rect targetRect)
{
if (Event.current.type != EventType.DragPerform && Event.current.type != EventType.DragUpdated)
return;
// Check we're dropping onto the polygon collider editor.
if (!targetRect.Contains(Event.current.mousePosition))
return;
foreach (var obj in DragAndDrop.objectReferences.Where(obj => obj is Sprite || obj is Texture2D))
{
DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
if (Event.current.type == EventType.DragPerform)
{
var sprite = obj is Sprite ? obj as Sprite : SpriteUtility.TextureToSprite(obj as Texture2D);
// Copy collider to all selected components
foreach (var collider in targets.Select(target => target as PolygonCollider2D))
{
Vector2[][] paths;
UnityEditor.Sprites.SpriteUtility.GenerateOutlineFromSprite(sprite, 0.25f, 200, true, out paths);
collider.pathCount = paths.Length;
for (int i = 0; i < paths.Length; ++i)
collider.SetPath(i, paths[i]);
DragAndDrop.AcceptDrag();
}
if (EditorTools.EditorTools.activeToolType == typeof(PolygonCollider2DTool))
EditorTools.EditorTools.RestorePreviousPersistentTool();
}
return;
}
DragAndDrop.visualMode = DragAndDropVisualMode.Rejected;
}
}
[EditorTool("Edit Polygon Collider 2D", typeof(PolygonCollider2D))]
class PolygonCollider2DTool : EditorTool
{
public override GUIContent toolbarIcon
{
get { return PrimitiveBoundsHandle.editModeButton; }
}
internal readonly PolygonEditorUtility polyUtility = new PolygonEditorUtility();
public void OnEnable()
{
EditorTools.EditorTools.activeToolChanged += OnActiveToolChanged;
EditorTools.EditorTools.activeToolChanging += OnActiveToolChanging;
Selection.selectionChanged += OnSelectionChanged;
}
public void OnDisable()
{
EditorTools.EditorTools.activeToolChanged -= OnActiveToolChanged;
EditorTools.EditorTools.activeToolChanging -= OnActiveToolChanging;
Selection.selectionChanged -= OnSelectionChanged;
}
public override void OnToolGUI(EditorWindow window)
{
polyUtility.OnSceneGUI();
}
void OnActiveToolChanged()
{
var collider = target as Collider2D;
if (EditorTools.EditorTools.IsActiveTool(this) && IsAvailable() && collider)
polyUtility.StartEditing(collider);
}
void OnSelectionChanged()
{
if (EditorTools.EditorTools.IsActiveTool(this))
polyUtility.StopEditing();
var collider = target as Collider2D;
if (EditorTools.EditorTools.IsActiveTool(this) && IsAvailable() && collider != null)
polyUtility.StartEditing(collider);
}
void OnActiveToolChanging()
{
if (EditorTools.EditorTools.IsActiveTool(this))
polyUtility.StopEditing();
}
public override bool IsAvailable()
{
// We don't support multi-selection editing
return targets.Count() == 1 && !targets.FirstOrDefault((x) =>
{
var sr = (x as Component).GetComponent<SpriteRenderer>();
var cd = (x as Component).GetComponent<PolygonCollider2D>();
return (sr != null && sr.drawMode != SpriteDrawMode.Simple && cd.autoTiling);
}
);
}
}
}
| 35.163636 | 121 | 0.587901 | [
"Unlicense"
] | HelloWindows/AccountBook | client/framework/UnityCsReference-master/Editor/Mono/Inspector/PolygonCollider2DEditor.cs | 5,802 | C# |
// 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.
namespace Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20210601
{
using Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.PowerShell;
/// <summary>Represents server restart parameters.</summary>
[System.ComponentModel.TypeConverter(typeof(RestartParameterTypeConverter))]
public partial class RestartParameter
{
/// <summary>
/// <c>AfterDeserializeDictionary</c> will be called after the deserialization has finished, allowing customization of the
/// object before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content);
/// <summary>
/// <c>AfterDeserializePSObject</c> will be called after the deserialization has finished, allowing customization of the object
/// before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content);
/// <summary>
/// <c>BeforeDeserializeDictionary</c> will be called before the deserialization has commenced, allowing complete customization
/// of the object before it is deserialized.
/// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
/// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow);
/// <summary>
/// <c>BeforeDeserializePSObject</c> will be called before the deserialization has commenced, allowing complete customization
/// of the object before it is deserialized.
/// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
/// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow);
/// <summary>
/// Deserializes a <see cref="global::System.Collections.IDictionary" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20210601.RestartParameter"
/// />.
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
/// <returns>
/// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20210601.IRestartParameter" />.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20210601.IRestartParameter DeserializeFromDictionary(global::System.Collections.IDictionary content)
{
return new RestartParameter(content);
}
/// <summary>
/// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20210601.RestartParameter"
/// />.
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
/// <returns>
/// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20210601.IRestartParameter" />.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20210601.IRestartParameter DeserializeFromPSObject(global::System.Management.Automation.PSObject content)
{
return new RestartParameter(content);
}
/// <summary>
/// Creates a new instance of <see cref="RestartParameter" />, deserializing the content from a json string.
/// </summary>
/// <param name="jsonText">a string containing a JSON serialized instance of this model.</param>
/// <returns>an instance of the <see cref="className" /> model class.</returns>
public static Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20210601.IRestartParameter FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Json.JsonNode.Parse(jsonText));
/// <summary>
/// Deserializes a <see cref="global::System.Collections.IDictionary" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20210601.RestartParameter"
/// />.
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
internal RestartParameter(global::System.Collections.IDictionary content)
{
bool returnNow = false;
BeforeDeserializeDictionary(content, ref returnNow);
if (returnNow)
{
return;
}
// actually deserialize
if (content.Contains("RestartWithFailover"))
{
((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20210601.IRestartParameterInternal)this).RestartWithFailover = (bool?) content.GetValueForProperty("RestartWithFailover",((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20210601.IRestartParameterInternal)this).RestartWithFailover, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool)));
}
if (content.Contains("FailoverMode"))
{
((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20210601.IRestartParameterInternal)this).FailoverMode = (string) content.GetValueForProperty("FailoverMode",((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20210601.IRestartParameterInternal)this).FailoverMode, global::System.Convert.ToString);
}
AfterDeserializeDictionary(content);
}
/// <summary>
/// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20210601.RestartParameter"
/// />.
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
internal RestartParameter(global::System.Management.Automation.PSObject content)
{
bool returnNow = false;
BeforeDeserializePSObject(content, ref returnNow);
if (returnNow)
{
return;
}
// actually deserialize
if (content.Contains("RestartWithFailover"))
{
((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20210601.IRestartParameterInternal)this).RestartWithFailover = (bool?) content.GetValueForProperty("RestartWithFailover",((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20210601.IRestartParameterInternal)this).RestartWithFailover, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool)));
}
if (content.Contains("FailoverMode"))
{
((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20210601.IRestartParameterInternal)this).FailoverMode = (string) content.GetValueForProperty("FailoverMode",((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20210601.IRestartParameterInternal)this).FailoverMode, global::System.Convert.ToString);
}
AfterDeserializePSObject(content);
}
/// <summary>Serializes this instance to a json string.</summary>
/// <returns>a <see cref="System.String" /> containing this model serialized to JSON text.</returns>
public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.SerializationMode.IncludeAll)?.ToString();
}
/// Represents server restart parameters.
[System.ComponentModel.TypeConverter(typeof(RestartParameterTypeConverter))]
public partial interface IRestartParameter
{
}
} | 63.193333 | 385 | 0.685515 | [
"MIT"
] | Agazoth/azure-powershell | src/PostgreSql/generated/api/Models/Api20210601/RestartParameter.PowerShell.cs | 9,330 | C# |
namespace RD_AAOW
{
/// <summary>
/// Перечисление результатов инициализации класса-описателя диаграммы
/// </summary>
public enum DiagramDataInitResults
{
/// <summary>
/// Файл данных успешно загружен
/// </summary>
Ok = 0,
/// <summary>
/// Файл данных не найден или недоступен
/// </summary>
FileNotAvailable = -1,
/// <summary>
/// Файл данных имеет некорректную структуру
/// </summary>
BrokenFile = -2,
/// <summary>
/// Файл данных содержит недостаточное число строк и/или столбцов
/// </summary>
NotEnoughData = -3,
/// <summary>
/// Некоторые значения в таблице некорректны
/// </summary>
BrokenTable = -11,
/// <summary>
/// Использование библиотеки поддержки файлов Excel не разрешено
/// </summary>
ExcelNotAvailable = -21,
/// <summary>
/// Класс-описатель диаграммы не инициализирован
/// </summary>
NotInited = 1
}
/// <summary>
/// Класс предоставляет метод, формирующий сообщения об ошибках
/// </summary>
public static class DiagramDataInitResultsMessage
{
/// <summary>
/// Метод формирует сообщение об ошибке
/// </summary>
/// <param name="Result">Результат инициализации класса</param>
/// <param name="Language">Язык локализации</param>
/// <returns>Сообщение об ошибке</returns>
public static string ErrorMessage (DiagramDataInitResults Result, SupportedLanguages Language)
{
switch (Result)
{
case DiagramDataInitResults.NotInited:
return Localization.GetText ("NotInitedError", Language);
case DiagramDataInitResults.FileNotAvailable:
return Localization.GetText ("FileNotAvailableError", Language);
case DiagramDataInitResults.BrokenFile:
return Localization.GetText ("BrokenFileError", Language);
case DiagramDataInitResults.NotEnoughData:
return Localization.GetText ("NotEnoughDataError", Language);
case DiagramDataInitResults.BrokenTable:
return Localization.GetText ("BrokenTableError", Language);
case DiagramDataInitResults.ExcelNotAvailable:
return Localization.GetText ("ExcelNotAvailableError", Language);
default: // В том числе - OK
return "";
}
}
}
}
| 26.204819 | 96 | 0.694713 | [
"MIT"
] | adslbarxatov/GeomagDataDrawer | src/DiagramDataInitResults.cs | 2,659 | C# |
namespace Klaims.Scim.Endpoints
{
using System;
using Klaims.Scim.Resources;
using Klaims.Scim.Services;
using Microsoft.AspNet.Mvc;
[Route(ScimConstants.Routes.Templates.Self)]
public class SelfEndpoint : ScimEndpoint
{
private readonly IScimUserManager resourceManager;
public SelfEndpoint(IScimUserManager resourceManager)
{
this.resourceManager = resourceManager;
}
// Just a stub for now. Assume this claim is required.
private string UserId => this.User.FindFirst("urn:claims.userId").Value;
public ScimUser Get()
{
var result = this.resourceManager.FindById(this.UserId);
if (result == null)
{
// this will be mappped later in filter
throw new Exception("User not found");
}
return result;
}
[HttpPost]
public void Create([FromBody] ScimUser item)
{
if (!this.ModelState.IsValid)
{
this.Context.Response.StatusCode = 400;
}
else
{
this.resourceManager.Create(item);
var url = this.Url.RouteUrl("GetByIdRoute", new { id = item.Id }, this.Request.Scheme, this.Request.Host.ToUriComponent());
this.Context.Response.StatusCode = 201;
this.Context.Response.Headers["Location"] = url;
}
}
[HttpDelete]
public ScimUser DeleteItem()
{
var removed = this.resourceManager.Remove(this.UserId, -1);
if (removed == null)
{
throw new Exception("User not found");
}
return removed; // 201 No Content
}
}
} | 22.746032 | 127 | 0.690858 | [
"Apache-2.0"
] | aanufriyev/Klaims.DirectoryServices | src/Klaims.Scim/Endpoints/SelfEndpoint.cs | 1,435 | C# |
/* =======================================================================
Copyright 2017 Technische Universitaet Darmstadt, Fachgebiet fuer Stroemungsdynamik (chair of fluid dynamics)
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 BoSSS.Foundation;
using BoSSS.Platform.LinAlg;
using BoSSS.Solution.CompressibleFlowCommon;
using BoSSS.Solution.CompressibleFlowCommon.MaterialProperty;
using BoSSS.Solution.Utils;
using BoSSS.Solution.CompressibleFlowCommon.Boundary;
using CNS.Convection;
using CNS.Diffusion;
using CNS.MaterialProperty;
using ilPSP;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace CNS.IBM {
/// <summary>
/// Abstract base class for source terms that represent boundary conditions
/// at immersed interfaces.
/// </summary>
public abstract class BoundaryConditionSource : IEquationComponent {
/// <summary>
/// Configuration options
/// </summary>
protected CNSControl config;
/// <summary>
/// Information about the location of the immersed boundary
/// </summary>
protected ISpeciesMap speciesMap;
/// <summary>
/// The boundary condition to be enforced
/// </summary>
protected BoundaryCondition boundaryCondition;
/// <summary>
/// Constructor
/// </summary>
/// <param name="config"></param>
/// <param name="speciesMap"></param>
/// <param name="boundaryCondition"></param>
public BoundaryConditionSource(CNSControl config, ISpeciesMap speciesMap, BoundaryCondition boundaryCondition) {
this.config = config;
this.speciesMap = speciesMap;
this.boundaryCondition = boundaryCondition;
}
#region IEquationComponent Members
/// <summary>
/// <see cref="CNSEnvironment.PrimalArgumentOrdering"/>
/// </summary>
public IList<string> ArgumentOrdering {
get {
return CNSEnvironment.PrimalArgumentOrdering;
}
}
/// <summary>
/// The level set gradient
/// </summary>
public IList<string> ParameterOrdering {
get {
return Enumerable.
Range(0, CNSEnvironment.NumberOfDimensions).
Select(i => "levelSetGradient" + i).
ToList();
}
}
#endregion
}
/// <summary>
/// Helper methods for <see cref="BoundaryConditionSource"/>
/// </summary>
public static class IEquationComponentExtensions {
/// <summary>
/// Dispatcher to determine the correct sub-class of
/// <see cref="BoundaryConditionSource"/> when creating a source term
/// for a specific equation component.
/// </summary>
public static BoundaryConditionSource CreateBoundaryConditionSource(
this IEquationComponent equationComponent, CNSControl control, ISpeciesMap speciesMap, BoundaryCondition boundaryCondition) {
BoundaryConditionSource result;
if (equationComponent is INonlinearFlux) {
result = new BoundaryConditionSourceFromINonlinearFlux(
control, speciesMap, boundaryCondition, (INonlinearFlux)equationComponent);
} else if (equationComponent is SIPGFlux) {
result = new BoundaryConditionSourceFromSIPGFlux(
control, speciesMap, boundaryCondition, (SIPGFlux)equationComponent);
} else if (equationComponent is INonlinear2ndOrderForm) {
result = new BoundaryConditionSourceFromINonlinear2ndOrderForm(
control, speciesMap, boundaryCondition, (INonlinear2ndOrderForm)equationComponent);
} else {
throw new NotImplementedException("To do");
}
return result;
}
}
/// <summary>
/// Implements a source term that enforces a boundary condition at the zero
/// iso-contour of a level set. Note that this source term does not include
/// the multiplication with the delta distribution (i.e., this has to be
/// accounted for during quadrature)
/// </summary>
public class BoundaryConditionSourceFromINonlinearFlux : BoundaryConditionSource, INonlinearSource {
/// <summary>
/// The flux function to be used to evaluate the flux across the zero
/// level set (by making use of
/// <see cref="EulerFlux.InnerEdgeFlux(double[], double, StateVector, StateVector, ref Vector, int)"/>)
/// </summary>
private INonlinearFlux fluxFunction;
/// <summary>
/// Constructs a new source term for a given
/// <paramref name="boundaryCondition"/>
/// </summary>
/// <param name="config">
/// Configuration options
/// </param>
/// <param name="speciesMap">
/// Information about the location of the immersed boundary
/// </param>
/// <param name="boundaryCondition">
/// The boundary condition to be enforced
/// </param>
/// <param name="fluxFunction">
/// The flux function to be used to evaluate the flux across the zero
/// level set (by making use of
/// <see cref="NonlinearFlux.InnerEdgeFlux(double, int, MultidimensionalArray, MultidimensionalArray, MultidimensionalArray[], MultidimensionalArray[], int, int, MultidimensionalArray)"/>)
/// </param>
public BoundaryConditionSourceFromINonlinearFlux(
CNSControl config, ISpeciesMap speciesMap, BoundaryCondition boundaryCondition, INonlinearFlux fluxFunction)
: base(config, speciesMap, boundaryCondition) {
this.fluxFunction = fluxFunction;
}
#region INonlinearSource Members
/// <summary>
/// Evaluates the configured flux function (see
/// <see cref="BoundaryConditionSourceFromINonlinearFlux.BoundaryConditionSourceFromINonlinearFlux(CNSControl, ISpeciesMap, BoundaryCondition, INonlinearFlux)"/>
/// using the present flow state <paramref name="U"/> and the boundary
/// value provided by the configured boundary condition.
/// </summary>
/// <param name="time"></param>
/// <param name="x"></param>
/// <param name="U"></param>
/// <param name="IndexOffset"></param>
/// <param name="FirstCellInd"></param>
/// <param name="Lenght"></param>
/// <param name="Output"></param>
public void Source(double time, MultidimensionalArray x, MultidimensionalArray[] U, int IndexOffset, int FirstCellInd, int Lenght, MultidimensionalArray Output) {
int D = CNSEnvironment.NumberOfDimensions;
int noOfNodes = x.GetLength(1);
int noOfVariables = D + 2;
MultidimensionalArray normal = MultidimensionalArray.Create(Lenght, noOfNodes, D);
MultidimensionalArray[] Uout = new MultidimensionalArray[noOfVariables];
for (int i = 0; i < noOfVariables; i++) {
Uout[i] = MultidimensionalArray.Create(Lenght, noOfNodes);
}
double[] xLocal = new double[D];
Material material = speciesMap.GetMaterial(double.NaN);
for (int i = 0; i < Lenght; i++) {
for (int j = 0; j < noOfNodes; j++) {
StateVector stateIn = new StateVector(material, U, i, j, CNSEnvironment.NumberOfDimensions);
Vector levelSetNormal = new Vector(CNSEnvironment.NumberOfDimensions);
int offset = CNSEnvironment.NumberOfDimensions + 2;
for (int d = 0; d < CNSEnvironment.NumberOfDimensions; d++) {
levelSetNormal[d] = U[offset + d][i + IndexOffset, j];
}
levelSetNormal.Normalize();
Debug.Assert(Math.Abs(levelSetNormal.Abs() - 1.0) < 1e-13, "Abnormal normal vector");
for (int d = 0; d < D; d++) {
xLocal[d] = x[i + IndexOffset, j, d];
normal[i, j, d] = levelSetNormal[d];
}
StateVector stateOut = boundaryCondition.GetBoundaryState(time, xLocal, levelSetNormal, stateIn);
Debug.Assert(stateOut.IsValid, "Invalid boundary state");
Uout[0][i, j] = stateOut.Density;
for (int d = 0; d < D; d++) {
Uout[d + 1][i, j] = stateOut.Momentum[d];
}
Uout[D + 1][i, j] = stateOut.Energy;
}
}
fluxFunction.InnerEdgeFlux(time, -1, x, normal, U, Uout, IndexOffset, Lenght, Output);
}
#endregion
}
/// <summary>
/// Variant of <see cref="BoundaryConditionSourceFromINonlinearFlux"/> for
/// sub-classes of <see cref="SIPGFlux"/>
/// </summary>
public class BoundaryConditionSourceFromSIPGFlux : BoundaryConditionSource, IVolumeForm {
private SIPGFlux fluxFunction;
/// <summary>
/// Constructor
/// </summary>
/// <param name="config"></param>
/// <param name="speciesMap"></param>
/// <param name="boundaryCondition"></param>
/// <param name="fluxFunction"></param>
public BoundaryConditionSourceFromSIPGFlux(
CNSControl config, ISpeciesMap speciesMap, BoundaryCondition boundaryCondition, SIPGFlux fluxFunction)
: base(config, speciesMap, boundaryCondition) {
this.fluxFunction = fluxFunction;
}
/// <summary>
/// See <see cref="SIPGFlux.BoundaryEdgeTerms"/>
/// </summary>
public TermActivationFlags VolTerms {
get {
return fluxFunction.BoundaryEdgeTerms;
}
}
/// <summary>
/// Evaluates the configured flux function (see
/// <see cref="BoundaryConditionSourceFromSIPGFlux.BoundaryConditionSourceFromSIPGFlux(CNSControl, ISpeciesMap, BoundaryCondition, SIPGFlux)"/>
/// using the present flow state <paramref name="U"/> and the boundary
/// value provided by the configured boundary condition.
/// </summary>
/// <param name="cpv"></param>
/// <param name="U"></param>
/// <param name="GradU"></param>
/// <param name="V"></param>
/// <param name="GradV"></param>
/// <returns></returns>
public double VolumeForm(ref CommonParamsVol cpv, double[] U, double[,] GradU, double V, double[] GradV) {
int D = CNSEnvironment.NumberOfDimensions;
double[] normal = new double[D];
double abs = 0.0;
for (int d = 0; d < D; d++) {
normal[d] = cpv.Parameters[d];
abs += normal[d] * normal[d];
}
abs = Math.Sqrt(abs);
Debug.Assert(abs > 1e-10, "Extremely flat level set gradient");
for (int d = 0; d < D; d++) {
normal[d] /= abs;
}
Material material = speciesMap.GetMaterial(double.NaN);
StateVector stateIn = new StateVector(U, material);
StateVector stateOut = boundaryCondition.GetBoundaryState(cpv.time, cpv.Xglobal, normal, stateIn);
Debug.Assert(stateOut.IsValid, "Invalid boundary state");
CommonParams InParams = new CommonParams() {
GridDat = cpv.GridDat,
iEdge = Math.Abs(cpv.GridDat.iLogicalCells.Cells2Edges[cpv.jCell][0]) - 1, // TO BE CHANGED
Normale = normal,
Parameters_IN = cpv.Parameters,
Parameters_OUT = cpv.Parameters,
time = cpv.time,
X = cpv.Xglobal
};
// cf. SIPGFlux, line 206
double[,] GradUBoundary = GradU;
// cf. SIPGFlux, line 207 & 210
double VBoundary = 0.0;
// cf. SIPGFlux, line 203
// BEWARE: _Not_ zero since we want {gradV} = gradVIn
double[] GradVBoundary = GradV;
//return fluxFunction.InnerEdgeForm(
// ref InParams, U, stateOut.ToArray(), GradU, GradUBoundary, V, VBoundary, GradV, GradVBoundary);
SIPGFlux.EVIL_HACK_CELL_INDEX = cpv.jCell;
double flux = fluxFunction.InnerEdgeForm(
ref InParams, U, stateOut.ToArray(), GradU, GradUBoundary, V, VBoundary, GradV, GradVBoundary);
SIPGFlux.EVIL_HACK_CELL_INDEX = -1;
return flux;
}
}
/// <summary>
/// Variant of <see cref="BoundaryConditionSourceFromINonlinearFlux"/> for
/// sub-classes of <see cref="INonlinear2ndOrderForm"/>
/// </summary>
public class BoundaryConditionSourceFromINonlinear2ndOrderForm : BoundaryConditionSource, INonlinVolumeForm_GradV, INonlinVolumeForm_V {
private INonlinear2ndOrderForm fluxFunction;
private bool adiaWall;
/// <summary>
/// Constructor
/// </summary>
/// <param name="config"></param>
/// <param name="speciesMap"></param>
/// <param name="boundaryCondition"></param>
/// <param name="fluxFunction"></param>
public BoundaryConditionSourceFromINonlinear2ndOrderForm(
CNSControl config, ISpeciesMap speciesMap, BoundaryCondition boundaryCondition, INonlinear2ndOrderForm fluxFunction)
: base(config, speciesMap, boundaryCondition) {
this.fluxFunction = fluxFunction;
if (boundaryCondition is AdiabaticWall) {
adiaWall = true;
}
}
/// <summary>
/// See <see cref="IVolumeForm.VolTerms"/>
/// </summary>
TermActivationFlags IVolumeForm.VolTerms {
get {
return fluxFunction.InnerEdgeTerms;
}
}
/// <summary>
/// Not used
/// </summary>
/// <param name="cpv"></param>
/// <param name="U"></param>
/// <param name="GradU"></param>
/// <param name="V"></param>
/// <param name="GradV"></param>
/// <returns></returns>
double IVolumeForm.VolumeForm(ref CommonParamsVol cpv, double[] U, double[,] GradU, double V, double[] GradV) {
// Not used
throw new NotImplementedException();
}
/// <summary>
/// Passes the given parameters to <see cref="INonlinEdgeForm_V.InternalEdge"/>
/// </summary>
/// <param name="prm"></param>
/// <param name="U"></param>
/// <param name="GradU"></param>
/// <param name="f"></param>
void INonlinVolumeForm_V.Form(ref VolumFormParams prm, MultidimensionalArray[] U, MultidimensionalArray[] GradU, MultidimensionalArray f) {
INonlinEdgeForm_V flux = fluxFunction;
MultidimensionalArray[] UBoundary;
MultidimensionalArray normals;
EdgeFormParams efp;
AdaptParameters(ref prm, U, GradU, out efp, out UBoundary, out normals);
MultidimensionalArray[] GradUBoundary = GradU; // cf. SIPGFlux, line 206
// Set fBoundary to zero
MultidimensionalArray fBoundary = MultidimensionalArray.Create(
U[0].GetLength(0), prm.Xglobal.GetLength(1));
OptimizedSIPGEnergyFlux.EVIL_HACK_CELL_INDEX = prm.j0;
OptimizedSIPGMomentumFlux.EVIL_HACK_CELL_INDEX = prm.j0;
fluxFunction.AdiabaticWall = this.adiaWall;
flux.InternalEdge(ref efp, U, UBoundary, GradU, GradUBoundary, f, fBoundary);
OptimizedSIPGEnergyFlux.EVIL_HACK_CELL_INDEX = -1;
OptimizedSIPGMomentumFlux.EVIL_HACK_CELL_INDEX = -1;
}
/// <summary>
/// Passes the given parameters to <see cref="INonlinEdgeForm_GradV.InternalEdge"/>
/// </summary>
/// <param name="prm"></param>
/// <param name="U"></param>
/// <param name="GradU"></param>
/// <param name="f"></param>
void INonlinVolumeForm_GradV.Form(ref VolumFormParams prm, MultidimensionalArray[] U, MultidimensionalArray[] GradU, MultidimensionalArray f) {
INonlinEdgeForm_GradV flux = fluxFunction;
MultidimensionalArray[] UBoundary;
MultidimensionalArray normals;
EdgeFormParams efp;
AdaptParameters(ref prm, U, GradU, out efp, out UBoundary, out normals);
MultidimensionalArray[] GradUBoundary = GradU; // cf. SIPGFlux, line 206
// Set fBoundary to zero
MultidimensionalArray fBoundary = MultidimensionalArray.Create(
U[0].GetLength(0), prm.Xglobal.GetLength(1), CNSEnvironment.NumberOfDimensions);
fluxFunction.AdiabaticWall = this.adiaWall;
flux.InternalEdge(ref efp, U, UBoundary, GradU, GradUBoundary, f, fBoundary);
}
/// <summary>
/// Reformulates the given parameters into <paramref name="efp"/>,
/// <paramref name="UBoundary"/> and <paramref name="normals"/>, which
/// are in the form required by
/// <see cref="INonlinEdgeForm_GradV.InternalEdge"/>
/// and <see cref="INonlinEdgeForm_V.InternalEdge"/>
/// </summary>
/// <param name="prm"></param>
/// <param name="U"></param>
/// <param name="GradU"></param>
/// <param name="efp"></param>
/// <param name="UBoundary"></param>
/// <param name="normals"></param>
private void AdaptParameters(ref VolumFormParams prm, MultidimensionalArray[] U, MultidimensionalArray[] GradU, out EdgeFormParams efp, out MultidimensionalArray[] UBoundary, out MultidimensionalArray normals) {
Debug.Assert(U[0].GetLength(0) == 1, "Number of cells must be 1");
Debug.Assert(prm.Len == 1, "Number of cells must be 1");
INonlinEdgeForm_GradV flux = fluxFunction;
int noOfCells = 1;
int noOfNodesPerCell = prm.Xglobal.GetLength(1);
UBoundary = new MultidimensionalArray[U.Length];
for (int k = 0; k < U.Length; k++) {
UBoundary[k] = MultidimensionalArray.Create(noOfCells, noOfNodesPerCell);
}
normals = MultidimensionalArray.Create(
noOfCells, noOfNodesPerCell, CNSEnvironment.NumberOfDimensions);
Material material = speciesMap.GetMaterial(double.NaN);
for (int j = 0; j < noOfNodesPerCell; j++) {
double[] x = new double[CNSEnvironment.NumberOfDimensions];
double[] normal = new double[CNSEnvironment.NumberOfDimensions];
double abs = 0.0;
for (int d = 0; d < CNSEnvironment.NumberOfDimensions; d++) {
x[d] = prm.Xglobal[0, j, d];
normal[d] = prm.ParameterVars[d][0, j];
abs += normal[d] * normal[d];
}
abs = Math.Sqrt(abs);
Debug.Assert(abs > 1e-10, "Extremely flat level set gradient");
for (int d = 0; d < CNSEnvironment.NumberOfDimensions; d++) {
normal[d] /= abs;
}
StateVector stateIn = new StateVector(material, U, 0, j, CNSEnvironment.NumberOfDimensions);
StateVector stateBoundary = boundaryCondition.GetBoundaryState(
prm.time, x, normal, stateIn);
Debug.Assert(stateBoundary.IsValid, "Invalid boundary state");
double[] UBoundaryLocal = stateBoundary.ToArray();
for (int k = 0; k < U.Length; k++) {
UBoundary[k][0, j] = UBoundaryLocal[k];
}
for (int d = 0; d < CNSEnvironment.NumberOfDimensions; d++) {
normals[0, j, d] = normal[d];
}
}
efp = new EdgeFormParams() {
e0 = Math.Abs(prm.GridDat.iLogicalCells.Cells2Edges[prm.j0][0]) - 1, // THIS IS AN EVIL HACK; NEEDS TO BE CHANGED
GridDat = prm.GridDat,
Len = prm.Len,
NodesGlobal = prm.Xglobal,
Normals = normals,
ParameterVars_IN = prm.ParameterVars,
ParameterVars_OUT = prm.ParameterVars,
time = prm.time
};
}
}
}
| 42.7833 | 220 | 0.576115 | [
"Apache-2.0"
] | leyel/BoSSS | src/L4-application/CNS/IBM/BoundaryConditionSource.cs | 21,020 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// <auto-generated/>
// Template Source: EntityCollectionPage.cs.tt
namespace Microsoft.Graph
{
using System;
/// <summary>
/// The type EntitlementManagementAccessPackageCatalogsCollectionPage.
/// </summary>
public partial class EntitlementManagementAccessPackageCatalogsCollectionPage : CollectionPage<AccessPackageCatalog>, IEntitlementManagementAccessPackageCatalogsCollectionPage
{
/// <summary>
/// Gets the next page <see cref="IEntitlementManagementAccessPackageCatalogsCollectionRequest"/> instance.
/// </summary>
public IEntitlementManagementAccessPackageCatalogsCollectionRequest NextPageRequest { get; private set; }
/// <summary>
/// Initializes the NextPageRequest property.
/// </summary>
public void InitializeNextPageRequest(IBaseClient client, string nextPageLinkString)
{
if (!string.IsNullOrEmpty(nextPageLinkString))
{
this.NextPageRequest = new EntitlementManagementAccessPackageCatalogsCollectionRequest(
nextPageLinkString,
client,
null);
}
}
}
}
| 41 | 179 | 0.613508 | [
"MIT"
] | GeertVL/msgraph-beta-sdk-dotnet | src/Microsoft.Graph/Generated/requests/EntitlementManagementAccessPackageCatalogsCollectionPage.cs | 1,599 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Car.Data;
using Car.Data.Interfaces;
using Car.Data.Repository;
using Car.Services;
using Car.Services.AutoMapper;
using Car.Services.Interfaces;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Swashbuckle.AspNetCore.Swagger;
namespace Car.Api
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseNpgsql(Configuration.GetConnectionString("DefaultConnection")));
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
#region repository
services.AddScoped<ICustomerRepository, CustomerRepository>();
services.AddScoped<ICustomerGroupRepository, CustomerGroupRepository>();
services.AddScoped<IProspectRepository, ProspectRepository>();
services.AddScoped<ISourceRepository, SourceRepository>();
services.AddScoped<ITitleRepository, TitleRepository>();
services.AddScoped<IVehicleRepository, VehicleRepository>();
services.AddScoped<IPersonalRepository, PersonalRepository>();
#endregion
#region services
services.AddScoped<ICustomerAppService, CustomerAppService>();
#endregion
// Register the Swagger generator, defining 1 or more Swagger documents
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info { Title = "Car API", Version = "v1" });
});
services.AddAutoMapperSetup();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseSwagger();
// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
// specifying the Swagger JSON endpoint.
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "Car API V1");
});
app.UseCors(c =>
{
c.AllowAnyHeader();
c.AllowAnyMethod();
c.AllowAnyOrigin();
});
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseMvc();
}
}
}
| 33.457447 | 106 | 0.638474 | [
"MIT"
] | buibup/Car | Car.Api/Startup.cs | 3,147 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Data;
using System.Windows;
using System.Windows.Input;
using PropertyChanged;
namespace Abnaki.Windows.Software.Wpf.PreferredControls.Grid
{
/// <summary>
/// ViewModel for Grid
/// </summary>
[ImplementPropertyChanged]
public class GridVm
{
public GridVm(IEnumerable data)
{
this.Data = new Xceed.Wpf.DataGrid.DataGridCollectionView(data);
this.AddRecords = new Command.CmdAddRecords(this.Data);
//this.DeleteRecords = new Command.CmdDeleteRecords(this.Data);
}
public void Refresh()
{
this.Data.Refresh();
}
/// <summary>
/// Expect Grid to bind to it.
/// Inherits System.Windows.Data.CollectionView.
/// </summary>
public Xceed.Wpf.DataGrid.DataGridCollectionView Data { get; set; }
public ICommand AddRecords { get; set; }
//public ICommand DeleteRecords { get; set; }
}
}
| 27.317073 | 77 | 0.609821 | [
"MIT"
] | abnaki/windows | Library/Software/WpfPreferredControls/Grid/GridVm.cs | 1,122 | C# |
using eliteKit.eliteCore;
using SkiaSharp;
using SkiaSharp.Views.Forms;
using Xamarin.Forms;
#pragma warning disable ALL
namespace eliteKit.eliteElements
{
public class eliteProgressSteps : SKCanvasView
{
private int canvasWidth = 0;
private int canvasHeight = 0;
private int stepSweepAngle = 0;
public static readonly BindableProperty StepCurrentProperty = BindableProperty.Create(nameof(StepCurrent), typeof(int), typeof(eliteProgressSteps), 2, BindingMode.TwoWay, propertyChanged: (bindableObject, oldValue, value) =>
{
if (value != null)
{
((eliteProgressSteps)bindableObject).InvalidateSurface();
}
});
/// <summary>
///
/// </summary>
public int StepCurrent
{
get
{
return (int)GetValue(StepCurrentProperty);
}
set
{
SetValue(StepCurrentProperty, value);
}
}
public static readonly BindableProperty StepMaxProperty = BindableProperty.Create(nameof(StepMax), typeof(int), typeof(eliteProgressSteps), 4, BindingMode.TwoWay, propertyChanged: (bindableObject, oldValue, value) =>
{
if (value != null)
{
((eliteProgressSteps)bindableObject).InvalidateSurface();
}
});
/// <summary>
///
/// </summary>
public int StepMax
{
get
{
return (int)GetValue(StepMaxProperty);
}
set
{
SetValue(StepMaxProperty, value);
}
}
public static readonly BindableProperty ColorPrimaryProperty = BindableProperty.Create(nameof(ColorPrimary), typeof(Color), typeof(eliteProgressSteps), coreSettings.ColorPrimary, BindingMode.TwoWay, propertyChanged: (bindableObject, oldValue, value) =>
{
if (value != null)
{
((eliteProgressSteps)bindableObject).InvalidateSurface();
}
});
/// <summary>
///
/// </summary>
public Color ColorPrimary
{
get
{
return (Color)GetValue(ColorPrimaryProperty);
}
set
{
SetValue(ColorPrimaryProperty, value);
}
}
public static readonly BindableProperty ColorSecondaryProperty = BindableProperty.Create(nameof(ColorSecondary), typeof(Color), typeof(eliteProgressSteps), coreSettings.ColorSecondary, BindingMode.TwoWay, propertyChanged: (bindableObject, oldValue, value) =>
{
if (value != null)
{
((eliteProgressSteps)bindableObject).InvalidateSurface();
}
});
/// <summary>
///
/// </summary>
public Color ColorSecondary
{
get
{
return (Color)GetValue(ColorSecondaryProperty);
}
set
{
SetValue(ColorSecondaryProperty, value);
}
}
public static readonly BindableProperty ColorInactiveStepsProperty = BindableProperty.Create(nameof(ColorInactiveSteps), typeof(Color), typeof(eliteProgressSteps), Color.LightGray, BindingMode.TwoWay, propertyChanged: (bindableObject, oldValue, value) =>
{
if (value != null)
{
((eliteProgressSteps)bindableObject).InvalidateSurface();
}
});
/// <summary>
///
/// </summary>
public Color ColorInactiveSteps
{
get
{
return (Color)GetValue(ColorInactiveStepsProperty);
}
set
{
SetValue(ColorInactiveStepsProperty, value);
}
}
public static readonly BindableProperty ColorActiveStepsProperty = BindableProperty.Create(nameof(ColorActiveSteps), typeof(Color), typeof(eliteProgressSteps), coreSettings.ColorPrimary, BindingMode.TwoWay, propertyChanged: (bindableObject, oldValue, value) =>
{
if (value != null)
{
((eliteProgressSteps)bindableObject).InvalidateSurface();
}
});
/// <summary>
///
/// </summary>
public Color ColorActiveSteps
{
get
{
return (Color)GetValue(ColorActiveStepsProperty);
}
set
{
SetValue(ColorActiveStepsProperty, value);
}
}
public static readonly BindableProperty IsGradientProperty = BindableProperty.Create(nameof(IsGradient), typeof(bool), typeof(eliteProgressSteps), true, BindingMode.TwoWay, propertyChanged: (bindableObject, oldValue, value) =>
{
if (value != null)
{
((eliteProgressSteps)bindableObject).InvalidateSurface();
}
});
/// <summary>
///
/// </summary>
public bool IsGradient
{
get
{
return (bool)GetValue(IsGradientProperty);
}
set
{
SetValue(IsGradientProperty, value);
}
}
public eliteProgressSteps()
{
this.stepSweepAngle = 360 / this.StepMax;
}
public void updateStep(int stepCurrent)
{
this.StepCurrent = stepCurrent;
this.InvalidateSurface();
}
public void increaseStep()
{
this.StepCurrent++;
this.InvalidateSurface();
}
public void decreaseStep()
{
this.StepCurrent--;
this.InvalidateSurface();
}
protected override void OnPaintSurface(SKPaintSurfaceEventArgs eventArgs)
{
var givenCanvas = eventArgs.Surface.Canvas;
givenCanvas.Clear();
this.canvasWidth = eventArgs.Info.Width;
this.canvasHeight = eventArgs.Info.Height;
// Draw background steps
SKPaint paintBackgroundSteps = new SKPaint()
{
Color = this.ColorInactiveSteps.ToSKColor(),
Style = SKPaintStyle.Stroke,
StrokeWidth = 30,
StrokeCap = SKStrokeCap.Round,
IsAntialias = true
};
SKRect progressRect = new SKRect();
progressRect.Size = new SKSize(this.canvasWidth - 35, this.canvasHeight - 35);
progressRect.Location = new SKPoint(15, 15);
int startAngle = -90;
int requiredOffset = 15;
int requiredAngle = (360 - (this.StepMax * requiredOffset)) / this.StepMax;
for (int i = 0; i < this.StepMax; i++)
{
SKPath progressPath = new SKPath();
progressPath.AddArc(progressRect, startAngle, requiredAngle);
givenCanvas.DrawPath(progressPath, paintBackgroundSteps);
startAngle += (requiredAngle + requiredOffset);
}
// Draw active steps
SKPaint paintActiveSteps = new SKPaint()
{
Color = this.ColorPrimary.ToSKColor(),
Style = SKPaintStyle.Stroke,
StrokeCap = SKStrokeCap.Round,
StrokeWidth = 30,
IsAntialias = true
};
if (this.IsGradient)
paintActiveSteps.Shader = SKShader.CreateLinearGradient(
new SKPoint(0, this.canvasWidth),
new SKPoint(this.canvasHeight, 0),
new SKColor[] {
this.ColorPrimary.ToSKColor(),
this.ColorSecondary.ToSKColor()
},
new float[] {
0,
1
},
SKShaderTileMode.Repeat
);
for (int i = 0; i < this.StepCurrent; i++)
{
SKPath progressPath = new SKPath();
progressPath.AddArc(progressRect, startAngle, requiredAngle);
givenCanvas.DrawPath(progressPath, paintActiveSteps);
startAngle += (requiredAngle + requiredOffset);
}
// Current progress text
SKPaint progressCurrentTextPaint = new SKPaint()
{
Color = this.ColorActiveSteps.ToSKColor(),
TextAlign = SKTextAlign.Center,
TextSize = 70f,
IsAntialias = true
};
string currentText = string.Format("{0}/{1}", this.StepCurrent, this.StepMax);
SKRect rectCurrentText = new SKRect();
progressCurrentTextPaint.MeasureText(currentText, ref rectCurrentText);
givenCanvas.DrawText(currentText, canvasWidth / 2, canvasHeight / 2 - rectCurrentText.MidY, progressCurrentTextPaint);
}
}
} | 32.258503 | 268 | 0.511704 | [
"MIT"
] | arqueror/eliteK | src/Forms/eliteKit_Src/eliteElements/eliteProgressSteps.cs | 9,486 | 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("ctsMapper")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("ctsMapper")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2010")]
[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("a9579698-86b1-47e3-a45d-6e84dd02c36f")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 39.054054 | 85 | 0.72872 | [
"MIT"
] | saintsrowmods/SaintsRow2Tools | ctsMapper/Properties/AssemblyInfo.cs | 1,448 | C# |
using CuttingEdge.Conditions;
using Newtonsoft.Json;
using SquareAccess.Configuration;
using SquareAccess.Exceptions;
using SquareAccess.Shared;
using SquareAccess.Throttling;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using SquareAccess.Services.Authentication;
namespace SquareAccess.Services
{
public class AuthorizedBaseService : BaseService
{
public SquareMerchantCredentials Credentials { get; }
protected Square.Connect.Client.Configuration ApiConfiguration { get; }
public AuthorizedBaseService( SquareConfig config, SquareMerchantCredentials credentials ) : base( config )
{
Condition.Requires( credentials, "credentials" ).IsNotNull();
this.Credentials = credentials;
this.ApiConfiguration = new Square.Connect.Client.Configuration()
{
AccessToken = this.Credentials.AccessToken
};
}
protected override async Task RefreshAccessToken( CancellationToken cancellationToken )
{
var mark = Mark.CreateNew();
var response = await this.ThrottleRequest( SquareEndPoint.ObtainOAuth2TokenUrl, this.Credentials.AccessToken, mark, ( token ) =>
{
var service = new SquareAuthenticationService( base.Config );
return service.RefreshAccessToken( this.Credentials.RefreshToken, token );
}, cancellationToken ).ConfigureAwait( false );
this.Credentials.AccessToken = response.AccessToken;
this.ApiConfiguration.AccessToken = response.AccessToken;
}
}
public abstract class BaseService : IDisposable
{
protected SquareConfig Config { get; private set; }
protected readonly Throttler Throttler;
protected readonly HttpClient HttpClient;
private Func< string > _additionalLogInfo;
private const int _tooManyRequestsHttpCode = 429;
private const string _invalidRefreshTokenMessage = "Invalid refresh token";
/// <summary>
/// Extra logging information
/// </summary>
public Func< string > AdditionalLogInfo
{
get { return this._additionalLogInfo ?? ( () => string.Empty ); }
set => _additionalLogInfo = value;
}
public BaseService( SquareConfig config )
{
Condition.Requires( config, "config" ).IsNotNull();
this.Config = config;
this.Throttler = new Throttler( config.ThrottlingOptions.MaxRequestsPerTimeInterval, config.ThrottlingOptions.TimeIntervalInSec, config.ThrottlingOptions.MaxRetryAttempts );
HttpClient = new HttpClient()
{
BaseAddress = new Uri( Config.ApiBaseUrl )
};
}
protected async Task< T > PostAsync< T >( string url, Dictionary< string, string > body, CancellationToken cancellationToken, Mark mark = null )
{
if ( cancellationToken.IsCancellationRequested )
{
var exceptionDetails = CreateMethodCallInfo( url, mark, additionalInfo: this.AdditionalLogInfo() );
throw new SquareException( string.Format( "{0}. Task was cancelled", exceptionDetails ) );
}
var responseContent = await this.ThrottleRequest( url, body.ToJson(), mark, async ( token ) =>
{
var payload = new FormUrlEncodedContent( body );
var httpResponse = await HttpClient.PostAsync( url, payload, token ).ConfigureAwait( false );
var content = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait( false );
ThrowIfError( httpResponse, content );
return content;
}, cancellationToken ).ConfigureAwait( false );
var response = JsonConvert.DeserializeObject< T >( responseContent );
return response;
}
protected void ThrowIfError( HttpResponseMessage response, string message )
{
HttpStatusCode responseStatusCode = response.StatusCode;
if ( response.IsSuccessStatusCode )
return;
if ( responseStatusCode == HttpStatusCode.Unauthorized )
{
throw new SquareUnauthorizedException( message );
}
else if ( (int)responseStatusCode == _tooManyRequestsHttpCode )
{
throw new SquareRateLimitsExceeded( message );
}
throw new SquareNetworkException( message );
}
protected Task< T > ThrottleRequest< T >( string url, string payload, Mark mark, Func< CancellationToken, Task< T > > processor, CancellationToken token )
{
return Throttler.ExecuteAsync( () =>
{
return new ActionPolicy( Config.NetworkOptions.RetryAttempts, Config.NetworkOptions.DelayBetweenFailedRequestsInSec, Config.NetworkOptions.DelayFailRequestRate )
.ExecuteAsync( async () =>
{
using( var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource( token ) )
{
SquareLogger.LogStarted( this.CreateMethodCallInfo( url, mark, payload: payload, additionalInfo: this.AdditionalLogInfo() ) );
linkedTokenSource.CancelAfter( Config.NetworkOptions.RequestTimeoutMs );
var result = await processor( linkedTokenSource.Token ).ConfigureAwait( false );
SquareLogger.LogEnd( this.CreateMethodCallInfo( url, mark, methodResult: result.ToJson(), additionalInfo: this.AdditionalLogInfo() ) );
return result;
}
},
( exception, timeSpan, retryCount ) =>
{
if ( exception.IsUnauthorizedException()
&& !( exception.InnerException != null
&& exception.InnerException.Message != null
&& exception.InnerException.Message.Contains( _invalidRefreshTokenMessage ) ) )
{
this.RefreshAccessToken( CancellationToken.None ).GetAwaiter().GetResult();
}
string retryDetails = CreateMethodCallInfo( SquareEndPoint.SearchCatalogUrl, mark, additionalInfo: this.AdditionalLogInfo() );
SquareLogger.LogTraceRetryStarted( timeSpan.Seconds, retryCount, retryDetails );
},
() => CreateMethodCallInfo( SquareEndPoint.SearchCatalogUrl, mark, additionalInfo: this.AdditionalLogInfo() ),
SquareLogger.LogTraceException );
} );
}
protected abstract Task RefreshAccessToken( CancellationToken cancellationToken );
/// <summary>
/// Creates method calling detailed information
/// </summary>
/// <param name="url">Absolute path to service endpoint</param>
/// <param name="mark">Unique stamp to track concrete method</param>
/// <param name="errors">Errors</param>
/// <param name="methodResult">Service endpoint raw result</param>
/// <param name="payload">Method payload (POST)</param>
/// <param name="additionalInfo">Extra logging information</param>
/// <param name="memberName">Method name</param>
/// <returns></returns>
protected string CreateMethodCallInfo( string url = "", Mark mark = null, string errors = "", string methodResult = "", string additionalInfo = "", string payload = "", [ CallerMemberName ] string memberName = "" )
{
string serviceEndPoint = null;
string requestParameters = null;
if ( !string.IsNullOrEmpty( url ) )
{
Uri uri = new Uri( url.Contains( Config.ApiBaseUrl ) ? url : Config.ApiBaseUrl + url );
serviceEndPoint = uri.LocalPath;
requestParameters = uri.Query;
}
var str = string.Format(
"{{MethodName: {0}, Mark: '{1}', ServiceEndPoint: '{2}', {3} {4}{5}{6}{7}}}",
memberName,
mark ?? Mark.Blank(),
string.IsNullOrWhiteSpace( serviceEndPoint ) ? string.Empty : serviceEndPoint,
string.IsNullOrWhiteSpace( requestParameters ) ? string.Empty : ", RequestParameters: " + requestParameters,
string.IsNullOrWhiteSpace( errors ) ? string.Empty : ", Errors:" + errors,
string.IsNullOrWhiteSpace( methodResult ) ? string.Empty : ", Result:" + methodResult,
string.IsNullOrWhiteSpace( payload ) ? string.Empty : ", Payload:" + payload,
string.IsNullOrWhiteSpace( additionalInfo ) ? string.Empty : ", " + additionalInfo
);
return str;
}
#region IDisposable Support
private bool disposedValue = false;
void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
this.Throttler.Dispose();
}
disposedValue = true;
}
}
public void Dispose()
{
Dispose(true);
}
#endregion
}
}
| 36.392857 | 217 | 0.701546 | [
"MIT"
] | skuvault-integrations/squareAccess | src/SquareAccess/Services/BaseService.cs | 8,154 | C# |
// <copyright file="Ability.cs" company="Worldshifters">
// Copyright (c) Worldshifters. All rights reserved.
// </copyright>
#pragma warning disable CA1034 // Nested types should not be visible
namespace Worldshifters.Data.Hero
{
using System;
using System.Collections.Generic;
using Google.Protobuf.Collections;
using Worldshifters.Data.Raid;
public enum AbilityTargettingType
{
TargetNone,
TargetSingleAliveFrontLineMember,
TargetSingleDeadPartyMember,
TargetSingleAliveFrontLineMemberExcludingSelf,
}
public class Ability
{
public AbilityTargettingType AbilityTargetting { get; set; }
public string AnimationName { get; set; }
public int Cooldown { get; set; }
public string Description { get; set; }
public RepeatedField<AbilityEffect> Effects { get; }
public int InitialCooldown { get; set; }
public ModelMetadata ModelMetadata { get; set; }
public string Name { get; set; }
public bool RenderOnAllPartyMembers { get; set; }
public bool RepositionOnTarget { get; set; }
public bool ShouldRepositionSpriteAnimation { get; set; }
public bool DoNotRenderAbilityCastEffect { get; set; }
public Types.AbilityType Type { get; set; }
/// <summary>
/// Input parameters: caster, target position in frontline (0-indexed).
/// </summary>
public Action<EntitySnapshot, int, IList<RaidAction>> ProcessEffects { get; set; }
/// <summary>
/// A delegate method which returns a pair where the first element is true if the ability can be used,
/// and false otherwise. The second element of the pair is an optional (nullable) error message which will
/// be displayed to the player when the ability can't be used.
/// Inputs: the caster, the target position in frontline (0-indexed).
/// </summary>
/// <remarks>
/// Regardless whether <see cref="CanCast"/> is provided or not, the ability cooldown and selected target
/// are evaluated first and will have the precedence to determine whether the ability can be used or not.
/// </remarks>
public Func<EntitySnapshot, int, (bool canUse, string errorMessage)> CanCast { get; set; }
/// <summary>
/// Cast an ability targetting the caster or with no target.
/// </summary>
/// <param name="caster">The ability caster.</param>
/// <param name="raidActions"></param>
/// <param name="doNotRenderCastAbilityEffect">Optional boolean to toggle on or off the "cast ability" animation when this <see cref="Ability"/> is used.</param>
public void Cast(EntitySnapshot caster, IList<RaidAction> raidActions, bool? doNotRenderCastAbilityEffect = null)
{
throw new NotImplementedException();
}
public void Cast(EntitySnapshot caster, int targetPositionInFrontline, IList<RaidAction> raidActions, bool? doNotRenderCastAbilityEffect = null)
{
throw new NotImplementedException();
}
public static class Types
{
public enum AbilityType
{
Offensive,
Healing,
Defensive,
Support,
}
}
}
}
| 35.473684 | 169 | 0.637389 | [
"MIT"
] | Seiryuha96/Worldshifters.Open | Worldshifters.Abstractions/Hero/Ability.cs | 3,372 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the signer-2017-08-25.normal.json service model.
*/
using System;
using System.Net;
using Amazon.Runtime;
namespace Amazon.Signer.Model
{
///<summary>
/// Signer exception
/// </summary>
#if !PCL && !NETSTANDARD
[Serializable]
#endif
public class BadRequestException : AmazonSignerException
{
/// <summary>
/// Constructs a new BadRequestException with the specified error
/// message.
/// </summary>
/// <param name="message">
/// Describes the error encountered.
/// </param>
public BadRequestException(string message)
: base(message) {}
/// <summary>
/// Construct instance of BadRequestException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
public BadRequestException(string message, Exception innerException)
: base(message, innerException) {}
/// <summary>
/// Construct instance of BadRequestException
/// </summary>
/// <param name="innerException"></param>
public BadRequestException(Exception innerException)
: base(innerException) {}
/// <summary>
/// Construct instance of BadRequestException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public BadRequestException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, innerException, errorType, errorCode, requestId, statusCode) {}
/// <summary>
/// Construct instance of BadRequestException
/// </summary>
/// <param name="message"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public BadRequestException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, errorType, errorCode, requestId, statusCode) {}
#if !PCL && !NETSTANDARD
/// <summary>
/// Constructs a new instance of the BadRequestException class with serialized data.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception>
/// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception>
protected BadRequestException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
: base(info, context)
{
}
#endif
}
} | 42.226804 | 178 | 0.642578 | [
"Apache-2.0"
] | NGL321/aws-sdk-net | sdk/src/Services/Signer/Generated/Model/BadRequestException.cs | 4,096 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
// <copyright file="" company="">
// <author>Pierre-François Léon</author>
// </copyright>
/// <summary>
/// Affichage graphique des statistiques :
/// - Ouvrir le site http://gnuplot.respawned.com
/// - Copier / coller des données dans le champ data
/// - Modification du "Plot script" comme suit :
/// # Scale font and line width (dpi) by changing the size! It will always display stretched.
//set terminal svg size 800,600 enhanced fname 'arial' fsize 10 butt solid
//set output 'out.svg'
//# Key means label...
//set key inside bottom right
//set xlabel 'Volume données (nb éléments)'
//set ylabel 'Temps (ms)'
//set title 'Comparaison algorithmes'
//plot "data.txt" using 1:2 title 'TVInsererFinCasIdeal' with lines, "data.txt" using 1:3 title 'TVInsererFinPireCas' with lines, "data.txt" using 1:4 title 'TVInsererDebut' with lines, "data.txt" using 1:5 title 'LCC#InsererFinCasIdeal' with lines, "data.txt" using 1:6 title 'LCC#InsererFinPireCas' with lines, "data.txt" using 1:7 title 'LCC#InsererDebut' with lines
/// </summary>
namespace ComparaisonAlgorithmesEtStD
{
class Program
{
static void Main(string[] args)
{
// Préparation du tableau de stats
Dictionary<int, List<long>> lstTemps = new Dictionary<int, List<long>>();
int[] colNbValeurs = new int[] { 10, 100, 1000, 10000, 20000, 30000, 40000, 50000, 60000, 70000, 80000, 90000, 100000 };
foreach (var nbValeur in colNbValeurs)
{
lstTemps.Add(nbValeur, new List<long>());
}
// Choisir le test à effectuer
//TestsStdTableauVariable_ListInserer(colNbValeurs, 100, lstTemps);
TestsFusionnerDeuxListesTriees(colNbValeurs, 100, lstTemps);
// Affichage des stats pour gnuplot
foreach (var nbValeur in colNbValeurs)
{
Console.WriteLine($"{nbValeur.ToString().PadRight(8)} {string.Join(" ", lstTemps[nbValeur].Select(v => v.ToString().PadRight(10)))}");
}
Console.ReadKey();
}
private static void TestsFusionnerDeuxListesTriees(int[] p_nbValeurs, int p_nbTests, Dictionary<int, List<long>> p_lstTemps)
{
TestFusionnerDeuxListesTrieesV1(p_nbValeurs, p_nbTests, p_lstTemps);
TestFusionnerDeuxListesTrieesV2(p_nbValeurs, p_nbTests, p_lstTemps);
}
private static void TestFusionnerDeuxListesTrieesV1(int[] p_nbValeurs, int p_nbTests, Dictionary<int, List<long>> p_lstTemps)
{
MesureMedianAppel(p_nbValeurs, p_nbTests, p_lstTemps,
nbValeurs =>
{
List<int> lst1 = CreerListeAleatoire(nbValeurs, false); lst1.Sort();
List<int> lst2 = CreerListeAleatoire(nbValeurs, false); lst2.Sort();
return Tuple.Create(lst1, lst2);
},
(lst) =>
{
FusionListeUtilitaire<int>.FusionnerDeuxListesTrieesV1(lst.Item1, lst.Item2);
});
}
private static void TestFusionnerDeuxListesTrieesV2(int[] p_nbValeurs, int p_nbTests, Dictionary<int, List<long>> p_lstTemps)
{
MesureMedianAppel(p_nbValeurs, p_nbTests, p_lstTemps,
nbValeurs =>
{
List<int> lst1 = CreerListeAleatoire(nbValeurs, false); lst1.Sort();
List<int> lst2 = CreerListeAleatoire(nbValeurs, false); lst2.Sort();
return Tuple.Create(lst1, lst2);
},
(lst) =>
{
FusionListeUtilitaire<int>.FusionnerDeuxListesTrieesV2(lst.Item1, lst.Item2);
});
}
private static void TestsStdTableauVariable_ListInserer(int[] p_nbValeurs, int p_nbTests, Dictionary<int, List<long>> p_lstTemps)
{
TestTableauVariableInsererFinCasIdeal(p_nbValeurs, p_nbTests, p_lstTemps);
TestTableauVariableInsererFinPireCas(p_nbValeurs, p_nbTests, p_lstTemps);
TestTableauVariableInsererDebut(p_nbValeurs, p_nbTests, p_lstTemps);
TestListeChaineeCSharpInsererFinCasIdeal(p_nbValeurs, p_nbTests, p_lstTemps);
TestListeChaineeCSharpInsererFinPireCas(p_nbValeurs, p_nbTests, p_lstTemps);
TestListeChaineeCSharpInsererDebut(p_nbValeurs, p_nbTests, p_lstTemps);
}
private static void TestTableauVariableInsererFinCasIdeal(int[] p_nbValeurs, int p_nbTests, Dictionary<int, List<long>> p_lstTemps)
{
MesureMedianAppel(p_nbValeurs, p_nbTests, p_lstTemps,
nbValeurs => CreerTableauVariableAleatoire(nbValeurs, true),
(tv) =>
{
tv.AjouterFin(42);
});
}
private static void TestTableauVariableInsererFinPireCas(int[] p_nbValeurs, int p_nbTests, Dictionary<int, List<long>> p_lstTemps)
{
MesureMedianAppel(p_nbValeurs, p_nbTests, p_lstTemps,
nbValeurs => CreerTableauVariableAleatoire(nbValeurs, false),
(tv) =>
{
tv.AjouterFin(42);
});
}
private static void TestTableauVariableInsererDebut(int[] p_nbValeurs, int p_nbTests, Dictionary<int, List<long>> p_lstTemps)
{
MesureMedianAppel(p_nbValeurs, p_nbTests, p_lstTemps,
nbValeurs => CreerTableauVariableAleatoire(nbValeurs, true),
(tv) =>
{
tv.AjouterDebut(42);
});
}
private static void TestListeChaineeCSharpInsererFinCasIdeal(int[] p_nbValeurs, int p_nbTests, Dictionary<int, List<long>> p_lstTemps)
{
MesureMedianAppel(p_nbValeurs, p_nbTests, p_lstTemps,
nbValeurs => CreerListeAleatoire(nbValeurs, true),
(tv) =>
{
tv.Add(42);
});
}
private static void TestListeChaineeCSharpInsererFinPireCas(int[] p_nbValeurs, int p_nbTests, Dictionary<int, List<long>> p_lstTemps)
{
MesureMedianAppel(p_nbValeurs, p_nbTests, p_lstTemps,
nbValeurs => CreerListeAleatoire(nbValeurs, false),
(tv) =>
{
tv.Add(42);
});
}
private static void TestListeChaineeCSharpInsererDebut(int[] p_nbValeurs, int p_nbTests, Dictionary<int, List<long>> p_lstTemps)
{
MesureMedianAppel(p_nbValeurs, p_nbTests, p_lstTemps,
nbValeurs => CreerListeAleatoire(nbValeurs, true),
(tv) =>
{
tv.Insert(0, 42);
});
}
/// <summary>
/// Prépare et effectue une suite de tests.
/// </summary>
/// <typeparam name="TypeStructure"></typeparam>
/// <param name="p_nbValeurs">Collection des différents volumes de données à tester</param>
/// <param name="p_nbTests">Nombre de tests par volume de données à effecter > 0</param>
/// <param name="p_lstTemps">Dictionnaire de résultats associant un volume à un temps (ici médian)</param>
/// <param name="fctCreationCas">Fonction qui permet de créer un cas de test</param>
/// <param name="fctAMesurer">Action à mesurer</param>
private static void MesureMedianAppel<TypeStructure>(int[] p_nbValeurs, int p_nbTests, Dictionary<int, List<long>> p_lstTemps,
Func<int, TypeStructure> fctCreationCas, Action<TypeStructure> fctAMesurer)
{
foreach (var nbValeurs in p_nbValeurs)
{
TypeStructure[] tableauxVariables = new TypeStructure[p_nbTests];
for (int i = 0; i < p_nbTests; i++)
{
tableauxVariables[i] = fctCreationCas(nbValeurs);
}
List<long> valeursTemps = new List<long>();
Stopwatch sw = null;
for (int i = 0; i < p_nbTests; i++)
{
sw = Stopwatch.StartNew();
fctAMesurer(tableauxVariables[i]);
sw.Stop();
valeursTemps.Add(sw.ElapsedTicks);
}
valeursTemps.Sort();
long mediane = valeursTemps[valeursTemps.Count / 2];
p_lstTemps[nbValeurs].Add(mediane);
}
}
/// <summary>
/// Crée un objet de type TableauVariable d'une capacité passée en paramètres rempli avec des valeurs aléatoires
/// </summary>
/// <param name="p_nbValeurs">Nombre de valeurs à générer</param>
/// <param name="p_capaciteEnPlus">ajouter au moins un espace à la capacité initiale afin de ne pas être dans le cas
/// où le tableau est recopié afin de ne pas fausser le meilleur des cas</param>
/// <returns></returns>
private static TableauVariable<int> CreerTableauVariableAleatoire(int p_nbValeurs, bool p_capaciteEnPlus)
{
Random rnd = new Random();
int capacite = p_nbValeurs;
if (p_capaciteEnPlus)
{
capacite += 1;
}
TableauVariable<int> res = new TableauVariable<int>(capacite);
for (int i = 0; i < p_nbValeurs; i++)
{
res.AjouterFin(rnd.Next());
}
return res;
}
/// <summary>
/// Crée une liste C# d'une capacité passée en paramètres remplie avec des valeurs aléatoires
/// </summary>
/// <param name="p_nbValeurs">Nombre de valeurs à générer</param>
/// <param name="p_capaciteEnPlus">ajouter au moins un espace à la capacité initiale afin de ne pas être dans le cas
/// où le tableau est recopié afin de ne pas fausser le meilleur des cas</param>
/// <returns></returns>
private static List<int> CreerListeAleatoire(int p_nbValeurs, bool p_capaciteEnPlus)
{
Random rnd = new Random();
int capacite = p_nbValeurs;
if (p_capaciteEnPlus)
{
capacite += 1;
}
List<int> res = new List<int>(capacite);
for (int i = 0; i < p_nbValeurs; i++)
{
res.Add(rnd.Next());
}
return res;
}
}
}
| 42.733871 | 370 | 0.586243 | [
"MIT"
] | PiFou86/420-229-SF_Algo_Prog_II | ComparaisonAlgorithmesEtStD/Program.cs | 10,645 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System;
using System.Net;
using Amazon.Runtime;
namespace Amazon.SimpleWorkflow.Model
{
///<summary>
/// AmazonSimpleWorkflow exception
/// </summary>
public class WorkflowExecutionAlreadyStartedException : AmazonSimpleWorkflowException
{
/// <summary>
/// Constructs a new WorkflowExecutionAlreadyStartedException with the specified error
/// message.
/// </summary>
/// <param name="message">
/// Describes the error encountered.
/// </param>
public WorkflowExecutionAlreadyStartedException(string message)
: base(message) {}
public WorkflowExecutionAlreadyStartedException(string message, Exception innerException)
: base(message, innerException) {}
public WorkflowExecutionAlreadyStartedException(Exception innerException)
: base(innerException) {}
public WorkflowExecutionAlreadyStartedException(string message, Exception innerException, ErrorType errorType, string errorCode, string RequestId, HttpStatusCode statusCode)
: base(message, innerException, errorType, errorCode, RequestId, statusCode) {}
public WorkflowExecutionAlreadyStartedException(string message, ErrorType errorType, string errorCode, string RequestId, HttpStatusCode statusCode)
: base(message, errorType, errorCode, RequestId, statusCode) {}
}
}
| 40.235294 | 182 | 0.698343 | [
"Apache-2.0"
] | virajs/aws-sdk-net | AWSSDK_DotNet35/Amazon.SimpleWorkflow/Model/WorkflowExecutionAlreadyStartedException.cs | 2,052 | C# |
using System;
using System.Linq;
using UML=TSF.UmlToolingFramework.UML;
namespace TSF.UmlToolingFramework.Wrappers.EA
{
/// <summary>
/// Multiplicity is an interval with a lower limit of type Unsigned Integer (Natural), and a upper limit of type UnlimitedNatural
/// it is usually represented as [lower limit]..[upper limit] e.g. 0..1, 1..1, 0..*
/// </summary>
public class Multiplicity
{
public uint lower {get;set;}
public UML.Classes.Kernel.UnlimitedNatural upper {get;set;}
private const string delimiter = "..";
public override string ToString()
{
return this.EACardinality;
}
public string EACardinality
{
get
{
return this.lower.ToString() + delimiter + this.upper.ToString();
}
set
{
string[] parts = value.Split(new string[]{delimiter},StringSplitOptions.None);
if (value.Length > 0 && parts.Length >= 2)
{
this.lower = uint.Parse(parts[0]);
this.upper = new UnlimitedNatural(parts[1]);
}
else if (value.Length > 0 && parts.Length == 1)
{
if (parts[0] == UnlimitedNatural.unlimited)
{ //[*] means [0..*]
this.lower = 0;
this.upper = new UnlimitedNatural(parts[0]);
}
else
{
// [1] means [1..1]
this.lower = uint.Parse(parts[0]);
this.upper = new UnlimitedNatural(parts[0]);
}
}
else
{
throw new Exception(string.Format("Cardinality specification {0} is invalid!" ,value));
}
}
}
public Multiplicity(string cardinality)
{
this.EACardinality = cardinality;
}
public Multiplicity(string lowerString, string upperString)
{
if (lowerString.Length > 0 && upperString.Length > 0)
{
this.EACardinality = lowerString + ".." + upperString;
}
else
{
this.EACardinality = lowerString+upperString;
}
}
#region Equals and GetHashCode implementation
public override bool Equals(object obj)
{
Multiplicity other = obj as Multiplicity;
if (other == null)
return false;
return this.EACardinality == other.EACardinality;
}
public override int GetHashCode()
{
int hashCode = 0;
unchecked {
hashCode += 1000000007 * lower.GetHashCode();
if (upper != null)
hashCode += 1000000009 * upper.GetHashCode();
}
return hashCode;
}
public static bool operator ==(Multiplicity lhs, Multiplicity rhs) {
if (ReferenceEquals(lhs, rhs))
return true;
if (ReferenceEquals(lhs, null) || ReferenceEquals(rhs, null))
return false;
return lhs.Equals(rhs);
}
public static bool operator !=(Multiplicity lhs, Multiplicity rhs) {
return !(lhs == rhs);
}
#endregion
}
}
| 24.592593 | 130 | 0.64119 | [
"BSD-2-Clause"
] | Helmut-Ortmann/Enterprise-Architect-Add-in-Framework | EAAddinFramework/EAWrappers/Multiplicity.cs | 2,658 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Eco.DataContext
{
public partial class AspNetUserClaims
{
public int Id { get; set; }
public string ClaimType { get; set; }
public string ClaimValue { get; set; }
[Required]
public string UserId { get; set; }
[ForeignKey("UserId")]
[InverseProperty("AspNetUserClaims")]
public AspNetUsers User { get; set; }
}
}
| 26 | 51 | 0.661172 | [
"Apache-2.0"
] | arsalan0312/Eco | Eco/DataContext/AspNetUserClaims.cs | 548 | C# |
namespace KafkaFlow.Producers
{
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Confluent.Kafka;
/// <summary>
/// </summary>
public static class BatchProduceExtension
{
/// <summary>
/// Calls the Produce() method in loop for high throughput scenarios
/// </summary>
/// <param name="producer"></param>
/// <param name="items">All messages to produce</param>
/// <param name="throwIfAnyProduceFail">indicates if the method should throw a <see cref="BatchProduceException"/> if any message fail</param>
/// <returns>A Task that will be marked as completed when all produce operations end</returns>
public static Task<IReadOnlyCollection<BatchProduceItem>> BatchProduceAsync(
this IMessageProducer producer,
IReadOnlyCollection<BatchProduceItem> items,
bool throwIfAnyProduceFail = true)
{
var completionSource = new TaskCompletionSource<IReadOnlyCollection<BatchProduceItem>>();
var pendingProduceCount = items.Count;
var hasErrors = false;
if (pendingProduceCount == 0)
{
completionSource.SetResult(items);
}
foreach (var item in items)
{
producer.Produce(
item.Topic,
item.PartitionKey,
item.Message,
item.Headers,
report =>
{
item.DeliveryReport = report;
if (report.Error.IsError)
{
hasErrors = true;
}
if (Interlocked.Decrement(ref pendingProduceCount) != 0)
{
return;
}
if (throwIfAnyProduceFail && hasErrors)
{
completionSource.SetException(new BatchProduceException(items));
}
else
{
completionSource.SetResult(items);
}
});
}
return completionSource.Task;
}
}
/// <summary>
/// Represents a message to be produced in batch
/// </summary>
public class BatchProduceItem
{
/// <summary>
/// The message topic name
/// </summary>
public string Topic { get; }
/// <summary>
/// The message partition key
/// </summary>
public string PartitionKey { get; }
/// <summary>
/// The message object
/// </summary>
public object Message { get; }
/// <summary>
/// The message headers
/// </summary>
public IMessageHeaders Headers { get; }
/// <summary>
/// The delivery report after the production
/// </summary>
public DeliveryReport<byte[], byte[]> DeliveryReport { get; internal set; }
/// <summary>
/// Creates a batch produce item
/// </summary>
/// <param name="topic"></param>
/// <param name="partitionKey"></param>
/// <param name="message"></param>
/// <param name="headers"></param>
public BatchProduceItem(
string topic,
string partitionKey,
object message,
IMessageHeaders headers)
{
this.Topic = topic;
this.PartitionKey = partitionKey;
this.Message = message;
this.Headers = headers;
}
}
/// <summary>
/// Exception thrown by <see cref="BatchProduceExtension.BatchProduceAsync"/>
/// </summary>
public class BatchProduceException : Exception
{
/// <summary>
/// The requested items to produce with <see cref="BatchProduceItem.DeliveryReport"/> filled
/// </summary>
public IReadOnlyCollection<BatchProduceItem> Items { get; }
/// <summary>
/// Creates a <see cref="BatchProduceException"/>
/// </summary>
/// <param name="items"></param>
public BatchProduceException(IReadOnlyCollection<BatchProduceItem> items)
{
this.Items = items;
}
}
}
| 31.794326 | 150 | 0.510596 | [
"MIT"
] | fab60/kafka-flow | src/KafkaFlow/Producers/BatchProduceExtension.cs | 4,483 | C# |
using MediatR;
using Pets.Platform.Permissions.Core.Domain;
using Pets.Platform.Permissions.Core.Interfaces;
namespace Pets.Platform.Permissions.Core.Queries;
public class GetUserUiModules : IRequest<UserUiModules>
{
public long UserId { get; init; }
public long ProjectId { get; init; }
}
public class UserUiModules
{
public IEnumerable<UIModule> Modules { get; init; }
public IEnumerable<UIMenu> Menus { get; init; }
public IEnumerable<UIElement> Elements { get; init; }
}
internal class GetUserUiModulesHandler : IRequestHandler<GetUserUiModules, UserUiModules>
{
private readonly IPermissionProvider _provider;
public GetUserUiModulesHandler(IPermissionProvider provider)
{
_provider = provider;
}
public async Task<UserUiModules> Handle(GetUserUiModules request, CancellationToken cancellationToken)
{
var uiPermissions = await _provider.GetUiPermissions(request.UserId, request.ProjectId);
return new UserUiModules()
{
Modules = uiPermissions.UiModules,
Elements = uiPermissions.UiElements,
Menus = uiPermissions.UiMenus
};
}
} | 29.225 | 106 | 0.718563 | [
"MIT"
] | 11pets/Pets.Platform.Permissions | Pets.Platform.Permissions.Core/Queries/GetUserUiModulesQuery.cs | 1,171 | C# |
using System;
using System.Threading.Tasks;
using ResourceProvisioning.Abstractions.Repositories;
using ResourceProvisioning.Broker.Domain.Aggregates.ResourceAggregate;
namespace ResourceProvisioning.Broker.Domain.Repository
{
public interface IResourceRepository : IRepository<ResourceRoot>
{
Task<ResourceRoot> GetByIdAsync(Guid resourceId);
}
}
| 27.307692 | 70 | 0.842254 | [
"MIT"
] | dfds/resource-provisioning-poc | src/ResourceProvisioning.Broker.Domain/Repositories/IResourceRepository.cs | 357 | C# |
using Dapper.Contrib.Extensions;
namespace Blog.Models
{
[Table("[Category]")]
public class Category
{
public Category()
=> Posts = new List<Post>();
public int Id { get; set; }
public string Name { get; set; }
public string Slug { get; set; }
public List<Post> Posts { get; set; }
}
} | 22.1875 | 45 | 0.549296 | [
"MIT"
] | DouglasMoraiis/dotnet-cli-projects | Blog/Models/Category.cs | 355 | C# |
#region License
// /*
// * ######
// * ######
// * ############ ####( ###### #####. ###### ############ ############
// * ############# #####( ###### #####. ###### ############# #############
// * ###### #####( ###### #####. ###### ##### ###### ##### ######
// * ###### ###### #####( ###### #####. ###### ##### ##### ##### ######
// * ###### ###### #####( ###### #####. ###### ##### ##### ######
// * ############# ############# ############# ############# ##### ######
// * ############ ############ ############# ############ ##### ######
// * ######
// * #############
// * ############
// *
// * Adyen Dotnet API Library
// *
// * Copyright (c) 2020 Adyen B.V.
// * This file is open source and available under the MIT license.
// * See the LICENSE file for more info.
// */
#endregion
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace Adyen.Model.MarketPay
{
/// <summary>
/// GetAccountHolderResponse
/// </summary>
[DataContract]
public partial class GetAccountHolderResponse : IEquatable<GetAccountHolderResponse>, IValidatableObject
{
/// <summary>
/// The legal entity of the account holder.
/// </summary>
/// <value>The legal entity of the account holder.</value>
[JsonConverter(typeof(StringEnumConverter))]
public enum LegalEntityEnum
{
/// <summary>
/// Enum Business for value: Business
/// </summary>
[EnumMember(Value = "Business")]
Business = 1,
/// <summary>
/// Enum Individual for value: Individual
/// </summary>
[EnumMember(Value = "Individual")]
Individual = 2,
/// <summary>
/// Enum NonProfit for value: NonProfit
/// </summary>
[EnumMember(Value = "NonProfit")]
NonProfit = 3,
/// <summary>
/// Enum PublicCompany for value: PublicCompany
/// </summary>
[EnumMember(Value = "PublicCompany")]
PublicCompany = 4 }
/// <summary>
/// The legal entity of the account holder.
/// </summary>
/// <value>The legal entity of the account holder.</value>
[DataMember(Name="legalEntity", EmitDefaultValue=false)]
public LegalEntityEnum LegalEntity { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="GetAccountHolderResponse" /> class.
/// </summary>
/// <param name="accountHolderCode">The code of the account holder. (required).</param>
/// <param name="accountHolderDetails">accountHolderDetails (required).</param>
/// <param name="accountHolderStatus">accountHolderStatus (required).</param>
/// <param name="accounts">A list of the accounts under the account holder..</param>
/// <param name="description">The description of the account holder..</param>
/// <param name="invalidFields">Contains field validation errors that would prevent requests from being processed..</param>
/// <param name="legalEntity">The legal entity of the account holder. (required).</param>
/// <param name="primaryCurrency">The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes), with which the prospective account holder primarily deals..</param>
/// <param name="pspReference">The reference of a request. Can be used to uniquely identify the request. (required).</param>
/// <param name="resultCode">The result code..</param>
/// <param name="systemUpToDateTime">The time that shows how up to date is the information in the response..</param>
/// <param name="verification">verification (required).</param>
public GetAccountHolderResponse(string accountHolderCode = default(string), AccountHolderDetails accountHolderDetails = default(AccountHolderDetails), AccountHolderStatus accountHolderStatus = default(AccountHolderStatus), List<Account> accounts = default(List<Account>), string description = default(string), List<ErrorFieldType> invalidFields = default(List<ErrorFieldType>), LegalEntityEnum legalEntity = default(LegalEntityEnum), string primaryCurrency = default(string), string pspReference = default(string), string resultCode = default(string), DateTime? systemUpToDateTime = default(DateTime?), KYCVerificationResult verification = default(KYCVerificationResult))
{
// to ensure "accountHolderCode" is required (not null)
if (accountHolderCode == null)
{
throw new InvalidDataException("accountHolderCode is a required property for GetAccountHolderResponse and cannot be null");
}
else
{
this.AccountHolderCode = accountHolderCode;
}
// to ensure "accountHolderDetails" is required (not null)
if (accountHolderDetails == null)
{
throw new InvalidDataException("accountHolderDetails is a required property for GetAccountHolderResponse and cannot be null");
}
else
{
this.AccountHolderDetails = accountHolderDetails;
}
// to ensure "accountHolderStatus" is required (not null)
if (accountHolderStatus == null)
{
throw new InvalidDataException("accountHolderStatus is a required property for GetAccountHolderResponse and cannot be null");
}
else
{
this.AccountHolderStatus = accountHolderStatus;
}
// to ensure "pspReference" is required (not null)
if (pspReference == null)
{
throw new InvalidDataException("pspReference is a required property for GetAccountHolderResponse and cannot be null");
}
else
{
this.PspReference = pspReference;
}
// to ensure "verification" is required (not null)
if (verification == null)
{
throw new InvalidDataException("verification is a required property for GetAccountHolderResponse and cannot be null");
}
else
{
this.Verification = verification;
}
this.LegalEntity = legalEntity;
this.Accounts = accounts;
this.Description = description;
this.InvalidFields = invalidFields;
this.PrimaryCurrency = primaryCurrency;
this.ResultCode = resultCode;
this.SystemUpToDateTime = systemUpToDateTime;
}
/// <summary>
/// The code of the account holder.
/// </summary>
/// <value>The code of the account holder.</value>
[DataMember(Name="accountHolderCode", EmitDefaultValue=false)]
public string AccountHolderCode { get; set; }
/// <summary>
/// Gets or Sets AccountHolderDetails
/// </summary>
[DataMember(Name="accountHolderDetails", EmitDefaultValue=false)]
public AccountHolderDetails AccountHolderDetails { get; set; }
/// <summary>
/// Gets or Sets AccountHolderStatus
/// </summary>
[DataMember(Name="accountHolderStatus", EmitDefaultValue=false)]
public AccountHolderStatus AccountHolderStatus { get; set; }
/// <summary>
/// A list of the accounts under the account holder.
/// </summary>
/// <value>A list of the accounts under the account holder.</value>
[DataMember(Name="accounts", EmitDefaultValue=false)]
public List<Account> Accounts { get; set; }
/// <summary>
/// The description of the account holder.
/// </summary>
/// <value>The description of the account holder.</value>
[DataMember(Name="description", EmitDefaultValue=false)]
public string Description { get; set; }
/// <summary>
/// Contains field validation errors that would prevent requests from being processed.
/// </summary>
/// <value>Contains field validation errors that would prevent requests from being processed.</value>
[DataMember(Name="invalidFields", EmitDefaultValue=false)]
public List<ErrorFieldType> InvalidFields { get; set; }
/// <summary>
/// The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes), with which the prospective account holder primarily deals.
/// </summary>
/// <value>The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes), with which the prospective account holder primarily deals.</value>
[DataMember(Name="primaryCurrency", EmitDefaultValue=false)]
public string PrimaryCurrency { get; set; }
/// <summary>
/// The reference of a request. Can be used to uniquely identify the request.
/// </summary>
/// <value>The reference of a request. Can be used to uniquely identify the request.</value>
[DataMember(Name="pspReference", EmitDefaultValue=false)]
public string PspReference { get; set; }
/// <summary>
/// The result code.
/// </summary>
/// <value>The result code.</value>
[DataMember(Name="resultCode", EmitDefaultValue=false)]
public string ResultCode { get; set; }
/// <summary>
/// The time that shows how up to date is the information in the response.
/// </summary>
/// <value>The time that shows how up to date is the information in the response.</value>
[DataMember(Name="systemUpToDateTime", EmitDefaultValue=false)]
public DateTime? SystemUpToDateTime { get; set; }
/// <summary>
/// Gets or Sets Verification
/// </summary>
[DataMember(Name="verification", EmitDefaultValue=false)]
public KYCVerificationResult Verification { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class GetAccountHolderResponse {\n");
sb.Append(" AccountHolderCode: ").Append(AccountHolderCode).Append("\n");
sb.Append(" AccountHolderDetails: ").Append(AccountHolderDetails).Append("\n");
sb.Append(" AccountHolderStatus: ").Append(AccountHolderStatus).Append("\n");
sb.Append(" Accounts: ").Append(Accounts).Append("\n");
sb.Append(" Description: ").Append(Description).Append("\n");
sb.Append(" InvalidFields: ").Append(InvalidFields).Append("\n");
sb.Append(" LegalEntity: ").Append(LegalEntity).Append("\n");
sb.Append(" PrimaryCurrency: ").Append(PrimaryCurrency).Append("\n");
sb.Append(" PspReference: ").Append(PspReference).Append("\n");
sb.Append(" ResultCode: ").Append(ResultCode).Append("\n");
sb.Append(" SystemUpToDateTime: ").Append(SystemUpToDateTime).Append("\n");
sb.Append(" Verification: ").Append(Verification).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as GetAccountHolderResponse);
}
/// <summary>
/// Returns true if GetAccountHolderResponse instances are equal
/// </summary>
/// <param name="input">Instance of GetAccountHolderResponse to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(GetAccountHolderResponse input)
{
if (input == null)
return false;
return
(
this.AccountHolderCode == input.AccountHolderCode ||
(this.AccountHolderCode != null &&
this.AccountHolderCode.Equals(input.AccountHolderCode))
) &&
(
this.AccountHolderDetails == input.AccountHolderDetails ||
(this.AccountHolderDetails != null &&
this.AccountHolderDetails.Equals(input.AccountHolderDetails))
) &&
(
this.AccountHolderStatus == input.AccountHolderStatus ||
(this.AccountHolderStatus != null &&
this.AccountHolderStatus.Equals(input.AccountHolderStatus))
) &&
(
this.Accounts == input.Accounts ||
this.Accounts != null &&
input.Accounts != null &&
this.Accounts.SequenceEqual(input.Accounts)
) &&
(
this.Description == input.Description ||
(this.Description != null &&
this.Description.Equals(input.Description))
) &&
(
this.InvalidFields == input.InvalidFields ||
this.InvalidFields != null &&
input.InvalidFields != null &&
this.InvalidFields.SequenceEqual(input.InvalidFields)
) &&
(
this.LegalEntity == input.LegalEntity ||
this.LegalEntity.Equals(input.LegalEntity)
) &&
(
this.PrimaryCurrency == input.PrimaryCurrency ||
(this.PrimaryCurrency != null &&
this.PrimaryCurrency.Equals(input.PrimaryCurrency))
) &&
(
this.PspReference == input.PspReference ||
(this.PspReference != null &&
this.PspReference.Equals(input.PspReference))
) &&
(
this.ResultCode == input.ResultCode ||
(this.ResultCode != null &&
this.ResultCode.Equals(input.ResultCode))
) &&
(
this.SystemUpToDateTime == input.SystemUpToDateTime ||
(this.SystemUpToDateTime != null &&
this.SystemUpToDateTime.Equals(input.SystemUpToDateTime))
) &&
(
this.Verification == input.Verification ||
(this.Verification != null &&
this.Verification.Equals(input.Verification))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.AccountHolderCode != null)
hashCode = hashCode * 59 + this.AccountHolderCode.GetHashCode();
if (this.AccountHolderDetails != null)
hashCode = hashCode * 59 + this.AccountHolderDetails.GetHashCode();
if (this.AccountHolderStatus != null)
hashCode = hashCode * 59 + this.AccountHolderStatus.GetHashCode();
if (this.Accounts != null)
hashCode = hashCode * 59 + this.Accounts.GetHashCode();
if (this.Description != null)
hashCode = hashCode * 59 + this.Description.GetHashCode();
if (this.InvalidFields != null)
hashCode = hashCode * 59 + this.InvalidFields.GetHashCode();
hashCode = hashCode * 59 + this.LegalEntity.GetHashCode();
if (this.PrimaryCurrency != null)
hashCode = hashCode * 59 + this.PrimaryCurrency.GetHashCode();
if (this.PspReference != null)
hashCode = hashCode * 59 + this.PspReference.GetHashCode();
if (this.ResultCode != null)
hashCode = hashCode * 59 + this.ResultCode.GetHashCode();
if (this.SystemUpToDateTime != null)
hashCode = hashCode * 59 + this.SystemUpToDateTime.GetHashCode();
if (this.Verification != null)
hashCode = hashCode * 59 + this.Verification.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| 46.735065 | 679 | 0.551326 | [
"MIT"
] | Adyen/adyen-dotnet-api-library | Adyen/Model/MarketPay/GetAccountHolderResponse.cs | 17,993 | C# |
#if ENABLE_PLAYFABSERVER_API
using System;
using System.Collections.Generic;
using PlayFab.SharedModels;
namespace PlayFab.MatchmakerModels
{
[Serializable]
public class AuthUserRequest : PlayFabRequestCommon
{
/// <summary>
/// Session Ticket provided by the client.
/// </summary>
public string AuthorizationTicket;
}
[Serializable]
public class AuthUserResponse : PlayFabResultCommon
{
/// <summary>
/// Boolean indicating if the user has been authorized to use the external match-making service.
/// </summary>
public bool Authorized;
/// <summary>
/// PlayFab unique identifier of the account that has been authorized.
/// </summary>
public string PlayFabId;
}
/// <summary>
/// A unique instance of an item in a user's inventory. Note, to retrieve additional information for an item instance (such
/// as Tags, Description, or Custom Data that are set on the root catalog item), a call to GetCatalogItems is required. The
/// Item ID of the instance can then be matched to a catalog entry, which contains the additional information. Also note
/// that Custom Data is only set here from a call to UpdateUserInventoryItemCustomData.
/// </summary>
[Serializable]
public class ItemInstance
{
/// <summary>
/// Game specific comment associated with this instance when it was added to the user inventory.
/// </summary>
public string Annotation;
/// <summary>
/// Array of unique items that were awarded when this catalog item was purchased.
/// </summary>
public List<string> BundleContents;
/// <summary>
/// Unique identifier for the parent inventory item, as defined in the catalog, for object which were added from a bundle or
/// container.
/// </summary>
public string BundleParent;
/// <summary>
/// Catalog version for the inventory item, when this instance was created.
/// </summary>
public string CatalogVersion;
/// <summary>
/// A set of custom key-value pairs on the inventory item.
/// </summary>
public Dictionary<string,string> CustomData;
/// <summary>
/// CatalogItem.DisplayName at the time this item was purchased.
/// </summary>
public string DisplayName;
/// <summary>
/// Timestamp for when this instance will expire.
/// </summary>
public DateTime? Expiration;
/// <summary>
/// Class name for the inventory item, as defined in the catalog.
/// </summary>
public string ItemClass;
/// <summary>
/// Unique identifier for the inventory item, as defined in the catalog.
/// </summary>
public string ItemId;
/// <summary>
/// Unique item identifier for this specific instance of the item.
/// </summary>
public string ItemInstanceId;
/// <summary>
/// Timestamp for when this instance was purchased.
/// </summary>
public DateTime? PurchaseDate;
/// <summary>
/// Total number of remaining uses, if this is a consumable item.
/// </summary>
public int? RemainingUses;
/// <summary>
/// Currency type for the cost of the catalog item.
/// </summary>
public string UnitCurrency;
/// <summary>
/// Cost of the catalog item in the given currency.
/// </summary>
public uint UnitPrice;
/// <summary>
/// The number of uses that were added or removed to this item in this call.
/// </summary>
public int? UsesIncrementedBy;
}
[Serializable]
public class PlayerJoinedRequest : PlayFabRequestCommon
{
/// <summary>
/// Unique identifier of the Game Server Instance the user is joining. This must be a Game Server Instance started with the
/// Matchmaker/StartGame API.
/// </summary>
public string LobbyId;
/// <summary>
/// PlayFab unique identifier for the player joining.
/// </summary>
public string PlayFabId;
}
[Serializable]
public class PlayerJoinedResponse : PlayFabResultCommon
{
}
[Serializable]
public class PlayerLeftRequest : PlayFabRequestCommon
{
/// <summary>
/// Unique identifier of the Game Server Instance the user is leaving. This must be a Game Server Instance started with the
/// Matchmaker/StartGame API.
/// </summary>
public string LobbyId;
/// <summary>
/// PlayFab unique identifier for the player leaving.
/// </summary>
public string PlayFabId;
}
[Serializable]
public class PlayerLeftResponse : PlayFabResultCommon
{
}
public enum Region
{
USCentral,
USEast,
EUWest,
Singapore,
Japan,
Brazil,
Australia
}
[Serializable]
public class StartGameRequest : PlayFabRequestCommon
{
/// <summary>
/// Unique identifier of the previously uploaded build executable which is to be started.
/// </summary>
public string Build;
/// <summary>
/// Custom command line argument when starting game server process.
/// </summary>
public string CustomCommandLineData;
/// <summary>
/// HTTP endpoint URL for receiving game status events, if using an external matchmaker. When the game ends, PlayFab will
/// make a POST request to this URL with the X-SecretKey header set to the value of the game's secret and an
/// application/json body of { "EventName": "game_ended", "GameID": "<gameid>" }.
/// </summary>
public string ExternalMatchmakerEventEndpoint;
/// <summary>
/// Game mode for this Game Server Instance.
/// </summary>
public string GameMode;
/// <summary>
/// Region with which to associate the server, for filtering.
/// </summary>
public Region Region;
}
[Serializable]
public class StartGameResponse : PlayFabResultCommon
{
/// <summary>
/// Unique identifier for the game/lobby in the new Game Server Instance.
/// </summary>
public string GameID;
/// <summary>
/// IPV4 address of the new Game Server Instance.
/// </summary>
[Obsolete("Use 'ServerIPV4Address' instead", false)]
public string ServerHostname;
/// <summary>
/// IPV4 address of the server
/// </summary>
public string ServerIPV4Address;
/// <summary>
/// IPV6 address of the new Game Server Instance.
/// </summary>
public string ServerIPV6Address;
/// <summary>
/// Port number for communication with the Game Server Instance.
/// </summary>
public uint ServerPort;
/// <summary>
/// Public DNS name (if any) of the server
/// </summary>
public string ServerPublicDNSName;
}
[Serializable]
public class UserInfoRequest : PlayFabRequestCommon
{
/// <summary>
/// Minimum catalog version for which data is requested (filters the results to only contain inventory items which have a
/// catalog version of this or higher).
/// </summary>
public int MinCatalogVersion;
/// <summary>
/// PlayFab unique identifier of the user whose information is being requested.
/// </summary>
public string PlayFabId;
}
[Serializable]
public class UserInfoResponse : PlayFabResultCommon
{
/// <summary>
/// Array of inventory items in the user's current inventory.
/// </summary>
public List<ItemInstance> Inventory;
/// <summary>
/// Boolean indicating whether the user is a developer.
/// </summary>
public bool IsDeveloper;
/// <summary>
/// PlayFab unique identifier of the user whose information was requested.
/// </summary>
public string PlayFabId;
/// <summary>
/// Steam unique identifier, if the user has an associated Steam account.
/// </summary>
public string SteamId;
/// <summary>
/// Title specific display name, if set.
/// </summary>
public string TitleDisplayName;
/// <summary>
/// PlayFab unique user name.
/// </summary>
public string Username;
/// <summary>
/// Array of virtual currency balance(s) belonging to the user.
/// </summary>
public Dictionary<string,int> VirtualCurrency;
/// <summary>
/// Array of remaining times and timestamps for virtual currencies.
/// </summary>
public Dictionary<string,VirtualCurrencyRechargeTime> VirtualCurrencyRechargeTimes;
}
[Serializable]
public class VirtualCurrencyRechargeTime
{
/// <summary>
/// Maximum value to which the regenerating currency will automatically increment. Note that it can exceed this value
/// through use of the AddUserVirtualCurrency API call. However, it will not regenerate automatically until it has fallen
/// below this value.
/// </summary>
public int RechargeMax;
/// <summary>
/// Server timestamp in UTC indicating the next time the virtual currency will be incremented.
/// </summary>
public DateTime RechargeTime;
/// <summary>
/// Time remaining (in seconds) before the next recharge increment of the virtual currency.
/// </summary>
public int SecondsToRecharge;
}
}
#endif
| 35.537634 | 132 | 0.604034 | [
"Apache-2.0"
] | deltaDNA/tutorial-playfab | Assets/PlayFabSdk/Matchmaker/PlayFabMatchmakerModels.cs | 9,915 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.Loader;
using System.Threading;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Azure.WebJobs.Script.Config;
using Microsoft.Extensions.DependencyModel;
using ResolutionPolicyEvaluator = System.Func<System.Reflection.AssemblyName, System.Reflection.Assembly, bool>;
namespace Microsoft.Azure.WebJobs.Script.Description
{
/// <summary>
/// Establishes an assembly load context for a extensions, functions and their dependencies.
/// </summary>
public partial class FunctionAssemblyLoadContext : AssemblyLoadContext
{
private const string PrivateDependencyResolutionPolicy = "private";
private static readonly Lazy<Dictionary<string, ResolutionPolicyEvaluator>> _resolutionPolicyEvaluators = new Lazy<Dictionary<string, ResolutionPolicyEvaluator>>(InitializeLoadPolicyEvaluators);
private static readonly ConcurrentDictionary<string, object> _sharedContextAssembliesInFallbackLoad = new ConcurrentDictionary<string, object>();
private static readonly RuntimeAssembliesInfo _runtimeAssembliesInfo = new RuntimeAssembliesInfo();
private static Lazy<FunctionAssemblyLoadContext> _defaultContext = new Lazy<FunctionAssemblyLoadContext>(CreateSharedContext, true);
private readonly List<string> _probingPaths = new List<string>();
private readonly IDictionary<string, RuntimeAsset[]> _depsAssemblies;
private readonly IDictionary<string, RuntimeAsset[]> _nativeLibraries;
private readonly List<string> _currentRidFallback;
public FunctionAssemblyLoadContext(string basePath)
{
if (basePath == null)
{
throw new ArgumentNullException(nameof(basePath));
}
_currentRidFallback = DependencyHelper.GetRuntimeFallbacks();
(_depsAssemblies, _nativeLibraries) = InitializeDeps(basePath, _currentRidFallback);
_probingPaths.Add(basePath);
}
public static FunctionAssemblyLoadContext Shared => _defaultContext.Value;
internal static void ResetSharedContext()
{
_defaultContext = new Lazy<FunctionAssemblyLoadContext>(CreateSharedContext, true);
_runtimeAssembliesInfo.ResetIfStale();
}
internal static (IDictionary<string, RuntimeAsset[]> depsAssemblies, IDictionary<string, RuntimeAsset[]> nativeLibraries) InitializeDeps(string basePath, List<string> ridFallbacks)
{
string depsFilePath = Path.Combine(basePath, DotNetConstants.FunctionsDepsFileName);
if (File.Exists(depsFilePath))
{
try
{
var reader = new DependencyContextJsonReader();
using (Stream file = File.OpenRead(depsFilePath))
{
var depsContext = reader.Read(file);
var depsAssemblies = depsContext.RuntimeLibraries.SelectMany(l => SelectRuntimeAssemblyGroup(ridFallbacks, l.RuntimeAssemblyGroups))
.GroupBy(a => Path.GetFileNameWithoutExtension(a.Path))
.ToDictionary(g => g.Key, g => g.ToArray(), StringComparer.OrdinalIgnoreCase);
// Note the difference here that nativeLibraries has the whole file name, including extension.
var nativeLibraries = depsContext.RuntimeLibraries.SelectMany(l => SelectRuntimeAssemblyGroup(ridFallbacks, l.NativeLibraryGroups))
.GroupBy(path => Path.GetFileName(path.Path))
.ToDictionary(g => g.Key, g => g.ToArray(), StringComparer.OrdinalIgnoreCase);
return (depsAssemblies, nativeLibraries);
}
}
catch
{
}
}
return (null, null);
}
private static IEnumerable<RuntimeAsset> SelectRuntimeAssemblyGroup(List<string> rids, IReadOnlyList<RuntimeAssetGroup> runtimeAssemblyGroups)
{
// Attempt to load group for the current RID graph
foreach (var rid in rids)
{
var assemblyGroup = runtimeAssemblyGroups.FirstOrDefault(g => string.Equals(g.Runtime, rid, StringComparison.OrdinalIgnoreCase));
if (assemblyGroup != null)
{
return assemblyGroup.AssetPaths.Select(path => new RuntimeAsset(rid, path));
}
}
// If unsuccessful, load default assets, making sure the path is flattened to reflect deployed files
return runtimeAssemblyGroups.GetDefaultAssets().Select(a => new RuntimeAsset(null, Path.GetFileName(a)));
}
private static FunctionAssemblyLoadContext CreateSharedContext()
{
var sharedContext = new FunctionAssemblyLoadContext(ResolveFunctionBaseProbingPath());
Default.Resolving += HandleDefaultContextFallback;
return sharedContext;
}
private static Assembly HandleDefaultContextFallback(AssemblyLoadContext loadContext, AssemblyName assemblyName)
{
// If we're not currently loading this from the shared context, an attempt to load
// a user assembly from the default context might have been made (e.g. Assembly.Load or AppDomain.Load called in a
// runtime/default context loaded assembly against a function assembly)
if (!_sharedContextAssembliesInFallbackLoad.ContainsKey(assemblyName.Name))
{
return Shared.LoadCore(assemblyName);
}
return null;
}
private static Dictionary<string, ResolutionPolicyEvaluator> InitializeLoadPolicyEvaluators()
{
return new Dictionary<string, ResolutionPolicyEvaluator>
{
{ "minorMatchOrLower", IsMinorMatchOrLowerPolicyEvaluator },
{ "runtimeVersion", RuntimeVersionPolicyEvaluator },
{ PrivateDependencyResolutionPolicy, (a, b) => false }
};
}
/// <summary>
/// A load policy evaluator that accepts the runtime assembly, regardless of version.
/// </summary>
/// <param name="requestedAssembly">The name of the requested assembly.</param>
/// <param name="runtimeAssembly">The runtime assembly.</param>
/// <returns>True if the evaluation succeeds.</returns>
private static bool RuntimeVersionPolicyEvaluator(AssemblyName requestedAssembly, Assembly runtimeAssembly) => true;
/// <summary>
/// A load policy evaluator that verifies if the runtime package is the same major and
/// newer minor version.
/// </summary>
/// <param name="requestedAssembly">The name of the requested assembly.</param>
/// <param name="runtimeAssembly">The runtime assembly.</param>
/// <returns>True if the evaluation succeeds.</returns>
private static bool IsMinorMatchOrLowerPolicyEvaluator(AssemblyName requestedAssembly, Assembly runtimeAssembly)
{
AssemblyName runtimeAssemblyName = AssemblyNameCache.GetName(runtimeAssembly);
return requestedAssembly.Version == null || (requestedAssembly.Version.Major == runtimeAssemblyName.Version.Major &&
requestedAssembly.Version.Minor <= runtimeAssemblyName.Version.Minor);
}
private bool IsRuntimeAssembly(AssemblyName assemblyName)
=> _runtimeAssembliesInfo.Assemblies.ContainsKey(assemblyName.Name);
private bool TryGetRuntimeAssembly(AssemblyName assemblyName, out ScriptRuntimeAssembly assembly)
=> _runtimeAssembliesInfo.Assemblies.TryGetValue(assemblyName.Name, out assembly);
private ResolutionPolicyEvaluator GetResolutionPolicyEvaluator(string policyName)
{
if (_resolutionPolicyEvaluators.Value.TryGetValue(policyName, out ResolutionPolicyEvaluator policy))
{
return policy;
}
throw new InvalidOperationException($"'{policyName}' is not a valid assembly resolution policy");
}
private Assembly LoadCore(AssemblyName assemblyName)
{
foreach (var probingPath in _probingPaths)
{
string path = Path.Combine(probingPath, assemblyName.Name + ".dll");
if (File.Exists(path))
{
return LoadFromAssemblyPath(path);
}
}
return null;
}
protected override Assembly Load(AssemblyName assemblyName)
{
// Try to load from deps references, if available
if (TryLoadDepsDependency(assemblyName, out Assembly assembly))
{
return assembly;
}
// If this is a runtime restricted assembly, load it based on unification rules
if (TryGetRuntimeAssembly(assemblyName, out ScriptRuntimeAssembly scriptRuntimeAssembly))
{
return LoadRuntimeAssembly(assemblyName, scriptRuntimeAssembly);
}
// If the assembly being requested matches a host assembly, we'll use
// the host assembly instead of loading it in this context:
if (TryLoadHostEnvironmentAssembly(assemblyName, out assembly))
{
return assembly;
}
return LoadCore(assemblyName);
}
private Assembly LoadRuntimeAssembly(AssemblyName assemblyName, ScriptRuntimeAssembly scriptRuntimeAssembly)
{
// If this is a private runtime assembly, return function dependency
if (string.Equals(scriptRuntimeAssembly.ResolutionPolicy, PrivateDependencyResolutionPolicy))
{
return LoadCore(assemblyName);
}
// Attempt to load the runtime version of the assembly based on the unification policy evaluation result.
if (TryLoadHostEnvironmentAssembly(assemblyName, allowPartialNameMatch: true, out Assembly assembly))
{
var policyEvaluator = GetResolutionPolicyEvaluator(scriptRuntimeAssembly.ResolutionPolicy);
if (policyEvaluator.Invoke(assemblyName, assembly))
{
return assembly;
}
}
return null;
}
private bool TryLoadDepsDependency(AssemblyName assemblyName, out Assembly assembly)
{
assembly = null;
if (_depsAssemblies != null &&
!IsRuntimeAssembly(assemblyName) &&
TryGetDepsAsset(_depsAssemblies, assemblyName.Name, _currentRidFallback, out string assemblyPath))
{
foreach (var probingPath in _probingPaths)
{
string filePath = Path.Combine(probingPath, assemblyPath);
if (File.Exists(filePath))
{
assembly = LoadFromAssemblyPath(filePath);
break;
}
}
}
return assembly != null;
}
internal static bool TryGetDepsAsset(IDictionary<string, RuntimeAsset[]> depsAssets, string assetName, List<string> ridFallbacks, out string assemblyPath)
{
assemblyPath = null;
if (depsAssets.TryGetValue(assetName, out RuntimeAsset[] assets))
{
// If we have a single asset match, return it:
if (assets.Length == 1)
{
assemblyPath = assets[0].Path;
}
else
{
foreach (var rid in ridFallbacks)
{
RuntimeAsset match = assets.FirstOrDefault(a => string.Equals(rid, a.Rid, StringComparison.OrdinalIgnoreCase));
if (match != null)
{
assemblyPath = match.Path;
break;
}
}
// If we're unable to locate a matching asset based on the RID fallback probing,
// attempt to use a default/RID-agnostic asset instead
if (assemblyPath == null)
{
assemblyPath = assets.FirstOrDefault(a => a.Rid == null)?.Path;
}
}
}
return assemblyPath != null;
}
private bool TryLoadHostEnvironmentAssembly(AssemblyName assemblyName, bool allowPartialNameMatch, out Assembly assembly)
{
return TryLoadHostEnvironmentAssembly(assemblyName, out assembly)
|| (allowPartialNameMatch && TryLoadHostEnvironmentAssembly(new AssemblyName(assemblyName.Name), out assembly));
}
private bool TryLoadHostEnvironmentAssembly(AssemblyName assemblyName, out Assembly assembly)
{
assembly = null;
try
{
_sharedContextAssembliesInFallbackLoad.TryAdd(assemblyName.Name, null);
assembly = AssemblyLoadContext.Default.LoadFromAssemblyName(assemblyName);
}
catch (FileNotFoundException)
{
}
finally
{
_sharedContextAssembliesInFallbackLoad.TryRemove(assemblyName.Name, out object _);
}
return assembly != null;
}
public Assembly LoadFromAssemblyPath(string assemblyPath, bool addProbingPath)
{
if (addProbingPath)
{
string directory = Path.GetDirectoryName(assemblyPath);
if (Directory.Exists(directory))
{
_probingPaths.Add(directory);
}
}
return LoadFromAssemblyPath(assemblyPath);
}
internal (bool succeeded, Assembly assembly, bool isRuntimeAssembly) TryLoadAssembly(AssemblyName assemblyName)
{
bool isRuntimeAssembly = IsRuntimeAssembly(assemblyName);
Assembly assembly = null;
if (!isRuntimeAssembly)
{
assembly = Load(assemblyName);
}
return (assembly != null, assembly, isRuntimeAssembly);
}
protected virtual Assembly OnResolvingAssembly(AssemblyLoadContext arg1, AssemblyName assemblyName)
{
// Log/handle failure
return null;
}
protected override IntPtr LoadUnmanagedDll(string unmanagedDllName)
{
string fileName = GetUnmanagedLibraryFileName(unmanagedDllName);
string filePath = GetRuntimeNativeAssetPath(fileName);
if (filePath != null)
{
return LoadUnmanagedDllFromPath(filePath);
}
return base.LoadUnmanagedDll(unmanagedDllName);
}
private string GetRuntimeNativeAssetPath(string assetFileName)
{
string basePath = _probingPaths[0];
const string ridSubFolder = "native";
string runtimesPath = Path.Combine(basePath, "runtimes");
List<string> rids = DependencyHelper.GetRuntimeFallbacks();
string result = rids.Select(r => Path.Combine(runtimesPath, r, ridSubFolder, assetFileName))
.Union(_probingPaths)
.FirstOrDefault(p => File.Exists(p));
if (result == null && _nativeLibraries != null)
{
if (TryGetDepsAsset(_nativeLibraries, assetFileName, _currentRidFallback, out string relativePath))
{
string nativeLibraryFullPath = Path.Combine(basePath, relativePath);
if (File.Exists(nativeLibraryFullPath))
{
result = nativeLibraryFullPath;
}
}
}
return result;
}
internal string GetUnmanagedLibraryFileName(string unmanagedLibraryName)
{
// We need to properly resolve the native library in different platforms:
// - Windows will append the '.DLL' extension to the name
// - Linux uses the 'lib' prefix and '.so' suffix. The version may also be appended to the suffix
// - macOS uses the 'lib' prefix '.dylib'
// To handle the different scenarios described above, we'll just have a pattern that gives us the ability
// to match the variations across different platforms. If needed, we can expand this in the future to have
// logic specific to the platform we're running under.
string fileName = null;
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
if (unmanagedLibraryName.EndsWith(".dll", StringComparison.OrdinalIgnoreCase))
{
fileName = unmanagedLibraryName;
}
else
{
fileName = unmanagedLibraryName + ".dll";
}
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
fileName = "lib" + unmanagedLibraryName + ".dylib";
}
else
{
fileName = "lib" + unmanagedLibraryName + ".so";
}
return fileName;
}
protected static string ResolveFunctionBaseProbingPath()
{
string basePath = null;
if (ScriptSettingsManager.Instance.IsAppServiceEnvironment)
{
string home = Environment.GetEnvironmentVariable(EnvironmentSettingNames.AzureWebsiteHomePath);
basePath = Path.Combine(home, "site", "wwwroot");
}
else
{
basePath = Environment.GetEnvironmentVariable(EnvironmentSettingNames.AzureWebJobsScriptRoot) ?? AppContext.BaseDirectory;
}
return Path.Combine(basePath, "bin");
}
}
}
| 41.558036 | 202 | 0.605973 | [
"Apache-2.0",
"MIT"
] | amamounelsayed/azure-functions-host | src/WebJobs.Script/Description/DotNet/FunctionAssemblyLoadContext.cs | 18,620 | C# |
using System.Threading.Tasks;
using AElf.Types;
namespace AElf.Kernel.SmartContractExecution.Application
{
public interface ITransactionValidationProvider
{
Task<bool> ValidateTransactionAsync(Transaction transaction);
}
} | 24.3 | 69 | 0.781893 | [
"MIT"
] | clairernovotny/AElf | src/AElf.Kernel.SmartContractExecution/Application/ITransactionValidationProvider.cs | 243 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace PlatformFileServer.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "15.7.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
}
}
| 39.740741 | 151 | 0.584343 | [
"MIT"
] | Silex/mipsdk-samples-plugin | PlatformFileServer/Properties/Settings.Designer.cs | 1,075 | C# |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using ZigBeeNet;
using ZigBeeNet.App;
using ZigBeeNet.App.Discovery;
using ZigBeeNet.ZDO.Command;
using ZigBeeNet.Util;
using Microsoft.Extensions.Logging;
using ZigBeeNet.ZCL.Clusters;
using ZigBeeNet.ZCL;
using ZigBeeNet.ZCL.Clusters.IasZone;
namespace ZigBeeNet.App.IasClient
{
/// <summary>
/// Implements the a minimal IAS client side functionality.The IAS(Intruder Alarm Systems) server clusters require
/// support on the client side when enrolling.Once an IAS device joins the network, it looks for a CIE (Control and
/// Indicating Equipment) which is implemented here.
/// <p>
/// There are three methods for enrolling IAS Zone server to an IAS CIE (i.e., IAS Zone client):
/// <ul>
/// <li>Trip-to-pair
/// <li>Auto-Enroll-Response
/// <li>Auto-Enroll-Request
/// </ul>
/// <p>
/// IAS Zone clients SHALL support either:
/// <ul>
/// <li>Trip-to-pair AND Auto-Enroll-Response, OR
/// <li>Auto-Enroll-Request
/// </ul>
/// <p>
/// An IAS Zone client MAY support all enrollment methods.The Trip-to-Pair enrollment method is primarily intended to be
/// used when there is a desire for an explicit enrollment method (e.g., when a GUI wizard or other commissioning tool is
/// used by a user or installer to add multiple IAS Zone servers in an orderly fashion, assign names to them, configure
/// them in the system).
/// <p>
/// The detailed requirements for each commissioning method follow:
/// <p>
/// <b>Trip-to-Pair</b>
/// <ol>
/// <li>After an IAS Zone server is commissioned to a network, the IAS CIE MAY perform service discovery.
/// <li>If the IAS CIE determines it wants to enroll the IAS Zone server, it SHALL send a Write Attribute command on the
/// IAS Zone server’s IAS_CIE_Address attribute with its IEEE address
/// <li>The IAS Zone server MAY configure a binding table entry for the IAS CIE’s address because all of its
/// communication will be directed to the IAS CIE.
/// <li>Upon a user input determined by the manufacturer (e.g., a button, change to device’s ZoneStatus attribute that
/// would result in a Zone Status Change Notification command) and the IAS Zone server’s ZoneState attribute equal to
/// 0x00 (unenrolled), the IAS Zone server SHALL send a Zone Enroll Request command.
/// <li>The IAS CIE SHALL send a Zone Enroll Response command, which assigns the IAS Zone server’s ZoneID attribute.
/// <li>The IAS Zone server SHALL change its ZoneState attribute to 0x01 (enrolled).
/// </ol>
/// <p>
/// <b>Auto-Enroll-Response</b>
/// <ol>
/// <li>After an IAS Zone server is commissioned to a network, the IAS CIE MAY perform service discovery.
/// <li>If the IAS CIE determines it wants to enroll the IAS Zone server, it SHALL send a Write Attribute command
/// on the IAS Zone server’s CIE_IAS_Address attribute with its IEEE address.
/// <li>The IAS Zone server MAY configure a binding table entry for the IAS CIE’s address because all of its
/// communication will be directed to the IAS CIE.
/// <li>The IAS CIE SHALL send a Zone Enroll Response, which assigns the IAS Zone server’s ZoneID attribute.
/// <li>The IAS Zone server SHALL change its ZoneState attribute to 0x01 (enrolled).
/// </ol>
/// <p>
/// <b>Auto-Enroll-Request</b>
/// <ol>
/// <li>After an IAS Zone server is commissioned to a network, the IAS CIE MAY perform service discovery.
/// <li>If the IAS CIE determines it wants to enroll the IAS Zone server, it SHALL send a Write Attribute command on the
/// IAS Zone server’s IAS_CIE_Address attribute with its IEEE address.
/// <li>The IAS Zone server MAY configure a binding table entry for the IAS CIE’s address because all of its
/// communication will be directed to the IAS CIE.
/// <li>The IAS Zone server SHALL send a Zone Enroll Request command.
/// <li>The IAS CIE SHALL send a Zone Enroll Response command, which assigns the IAS Zone server’s ZoneID attribute.
/// <li>The IAS Zone server SHALL change its ZoneState attribute to 0x01 (enrolled).
/// </ol>
/// <p> /// </summary>
public class ZclIasZoneClient : IZigBeeApplication
{
/// <summary>
/// ILogger for logging events for this class
/// </summary>
private static ILogger _logger = LogManager.GetLog<ZclIasZoneClient>();
/// <summary>
/// The default number of milliseconds to wait for a <see cref="ZoneEnrollRequestCommand"/>
/// before sending the <see cref="ZoneEnrollResponse"/>
/// </summary>
private const int DEFAULT_AUTO_ENROLL_DELAY = 2000;
/// <summary>
/// The <see cref="ZigBeeNetworkManager">
/// </summary>
private ZigBeeNetworkManager _networkManager;
/// <summary>
/// The IAS cluster to which we're bound
/// </summary>
private ZclIasZoneCluster _iasZoneCluster;
/// <summary>
/// The <see cref="IeeeAddress"/> of the CIE server. Normally this should be the local address of the coordinator.
/// </summary>
private IeeeAddress _ieeeAddress;
/// <summary>
/// The time to wait for a <see cref="ZoneEnrollRequestCommand"/> before sending the <see cref="ZoneEnrollResponse"/>
/// </summary>
public int AutoEnrollDelay { get; set; } = DEFAULT_AUTO_ENROLL_DELAY;
/// <summary>
/// The cancellation token for the auto enrollment task being run
/// </summary>
private CancellationTokenSource _autoEnrollmentCancellationToken;
/// <summary>
/// The IAS zone ID for this device
/// </summary>
public byte ZoneId { get; private set; }
/// <summary>
/// The zone type reported by the remote device during enrollment
/// </summary>
public ushort? ZoneType { get; private set; }
/// <summary>
/// Constructor
/// </summary>
/// <param name="networkManager">the <see cref="ZigBeeNetworkManager"/> this belongs to</param>
/// <param name="ieeeAddress"> <see cref="IeeeAddress"/> of the CIE</param>
/// <param name="zoneId">the zone ID to use for this device</param>
public ZclIasZoneClient(ZigBeeNetworkManager networkManager, IeeeAddress ieeeAddress, byte zoneId)
{
_networkManager = networkManager;
_ieeeAddress = ieeeAddress;
ZoneId = zoneId;
}
/**
* Gets the IAS zone type for this device. This is provided by the remote device during enrollment.
*
* @return the IAS zone type as {@link ZoneTypeEnum} or null if the zone type is unknown
*/
//public ZoneTypeEnum getZoneType() {
// if (zoneType == null) {
// return null;
// }
// return ZoneTypeEnum.getByValue(zoneType);
//}
public ZigBeeStatus AppStartup(ZclCluster cluster)
{
_iasZoneCluster = (ZclIasZoneCluster) cluster;
Task.Run(Initialise).GetAwaiter().GetResult();
return ZigBeeStatus.SUCCESS;
}
private async Task Initialise()
{
byte? currentState = (byte?) await _iasZoneCluster.GetAttribute(ZclIasZoneCluster.ATTR_ZONESTATE).ReadValue(long.MaxValue);
if (currentState.HasValue)
{
ZoneStateEnum currentStateEnum = (ZoneStateEnum)currentState;
_logger.LogDebug("{Address}: IAS CIE state is currently {StateEnum}[{State}]", _iasZoneCluster.GetZigBeeAddress(), currentStateEnum, currentState);
if (currentStateEnum == ZoneStateEnum.ENROLLED)
{
_logger.LogDebug("{Address}: IAS CIE is already enrolled", _iasZoneCluster.GetZigBeeAddress());
return;
}
}
else
{
_logger.LogDebug("{Address}: IAS CIE failed to get state", _iasZoneCluster.GetZigBeeAddress());
}
ZclAttribute cieAddressAttribute = _iasZoneCluster.GetAttribute(ZclIasZoneCluster.ATTR_IASCIEADDRESS);
IeeeAddress currentIeeeAddress = (IeeeAddress) await cieAddressAttribute.ReadValue(0);
_logger.LogDebug("{Address}: IAS CIE address is currently {Address2}", _iasZoneCluster.GetZigBeeAddress(), currentIeeeAddress);
if (!_ieeeAddress.Equals(currentIeeeAddress))
{
// Set the CIE address in the remote device. This is where the device will send its reports.
await cieAddressAttribute.WriteValue(_ieeeAddress);
currentIeeeAddress = (IeeeAddress) await cieAddressAttribute.ReadValue(0);
if (_ieeeAddress.Equals(currentIeeeAddress))
{
_logger.LogDebug("{Address}: IAS CIE address is confirmed {Address2}", _iasZoneCluster.GetZigBeeAddress(), currentIeeeAddress);
}
else
{
_logger.LogWarning("{Address}: IAS CIE address is NOT confirmed {Address2}", _iasZoneCluster.GetZigBeeAddress(), currentIeeeAddress);
}
}
byte? currentZone = (byte?) await _iasZoneCluster.GetAttribute(ZclIasZoneCluster.ATTR_ZONEID).ReadValue(0);
if (currentZone == null)
{
_logger.LogDebug("{Address}: IAS CIE zone ID request failed", _iasZoneCluster.GetZigBeeAddress());
}
else
{
_logger.LogDebug("{Address}: IAS CIE zone ID is currently {ZoneId}", _iasZoneCluster.GetZigBeeAddress(), currentZone);
}
ZoneType = (ushort?) await _iasZoneCluster.GetAttribute(ZclIasZoneCluster.ATTR_ZONETYPE).ReadValue(long.MaxValue);
if (ZoneType == null)
{
_logger.LogDebug("{Address}: IAS CIE zone type request failed", _iasZoneCluster.GetZigBeeAddress());
}
else
{
_logger.LogDebug("{Address}: IAS CIE zone type is {ZoneTypeEnum} ({ZoneTypeValue})", _iasZoneCluster.GetZigBeeAddress(), ((ZoneTypeEnum)ZoneType), ZoneType.Value.ToString("X2"));
}
// Start the auto-enroll timer
_autoEnrollmentCancellationToken = new CancellationTokenSource();
_ = Task.Run(RunAutoEnrollmentTask, _autoEnrollmentCancellationToken.Token);
}
private async Task RunAutoEnrollmentTask()
{
try
{
await Task.Delay(AutoEnrollDelay, _autoEnrollmentCancellationToken.Token);
await _iasZoneCluster.ZoneEnrollResponse((byte)IasEnrollResponseCodeEnum.SUCCESS, ZoneId);
}
catch(OperationCanceledException)
{
//task has been cancelled
}
catch(Exception ex)
{
_logger.LogWarning("{Address}: IAS CIE Exception in RunAutoEnrollmentTask {Exception}", _iasZoneCluster.GetZigBeeAddress(), ex.Message);
}
}
public void AppShutdown()
{
if (_autoEnrollmentCancellationToken != null)
{
_autoEnrollmentCancellationToken.Cancel();
}
}
public int GetClusterId()
{
return ZclIasZoneCluster.CLUSTER_ID;
}
/// <summary>
/// Handle the received <see cref="ZoneEnrollRequestCommand"/> and send the <see cref="ZoneEnrollResponse"/>.
/// This will register the zone number specified in the constructor <see cref="ZigBeeIasCieExtension"/>.
/// </summary>
/// <param name="command">the received <see cref="ZoneEnrollRequestCommand"/></param>
/// <returns></returns>
private bool HandleZoneEnrollRequestCommand(ZoneEnrollRequestCommand command)
{
if (_autoEnrollmentCancellationToken != null)
{
_autoEnrollmentCancellationToken.Cancel();
}
ZoneType = command.ZoneType;
_iasZoneCluster.ZoneEnrollResponse((byte)IasEnrollResponseCodeEnum.SUCCESS, ZoneId);
return true;
}
public void CommandReceived(ZigBeeCommand command)
{
if (command is ZoneEnrollRequestCommand)
{
HandleZoneEnrollRequestCommand((ZoneEnrollRequestCommand) command);
}
}
}
}
| 44.068966 | 194 | 0.630125 | [
"EPL-1.0"
] | JanneMattila/ZigbeeNet | libraries/ZigBeeNet/App/IasClient/ZclIasZoneClient.cs | 12,802 | C# |
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Service.Exchange.Balances.Postgres.Migrations
{
public partial class UpdateBalancePrecision : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<decimal>(
name: "ReserveBalance",
schema: "exchange_balances",
table: "balances",
type: "numeric(40,20)",
precision: 40,
scale: 20,
nullable: false,
oldClrType: typeof(decimal),
oldType: "numeric(20,0)",
oldPrecision: 20);
migrationBuilder.AlterColumn<decimal>(
name: "Balance",
schema: "exchange_balances",
table: "balances",
type: "numeric(40,20)",
precision: 40,
scale: 20,
nullable: false,
oldClrType: typeof(decimal),
oldType: "numeric(20,0)",
oldPrecision: 20);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<decimal>(
name: "ReserveBalance",
schema: "exchange_balances",
table: "balances",
type: "numeric(20,0)",
precision: 20,
nullable: false,
oldClrType: typeof(decimal),
oldType: "numeric(40,20)",
oldPrecision: 40,
oldScale: 20);
migrationBuilder.AlterColumn<decimal>(
name: "Balance",
schema: "exchange_balances",
table: "balances",
type: "numeric(20,0)",
precision: 20,
nullable: false,
oldClrType: typeof(decimal),
oldType: "numeric(40,20)",
oldPrecision: 40,
oldScale: 20);
}
}
}
| 32.40625 | 71 | 0.488428 | [
"MIT"
] | MyJetWallet/Service.Exchange.Balances | src/Service.Exchange.Balances.Postgres/Migrations/20211118110605_UpdateBalancePrecision.cs | 2,076 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the monitoring-2010-08-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.CloudWatch.Model
{
/// <summary>
/// Container for the parameters to the PutAnomalyDetector operation.
/// Creates an anomaly detection model for a CloudWatch metric. You can use the model
/// to display a band of expected normal values when the metric is graphed.
///
///
/// <para>
/// For more information, see <a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Anomaly_Detection.html">CloudWatch
/// Anomaly Detection</a>.
/// </para>
/// </summary>
public partial class PutAnomalyDetectorRequest : AmazonCloudWatchRequest
{
private AnomalyDetectorConfiguration _configuration;
private List<Dimension> _dimensions = new List<Dimension>();
private string _metricName;
private string _awsNamespace;
private string _stat;
/// <summary>
/// Gets and sets the property Configuration.
/// <para>
/// The configuration specifies details about how the anomaly detection model is to be
/// trained, including time ranges to exclude when training and updating the model. You
/// can specify as many as 10 time ranges.
/// </para>
///
/// <para>
/// The configuration can also include the time zone to use for the metric.
/// </para>
/// </summary>
public AnomalyDetectorConfiguration Configuration
{
get { return this._configuration; }
set { this._configuration = value; }
}
// Check to see if Configuration property is set
internal bool IsSetConfiguration()
{
return this._configuration != null;
}
/// <summary>
/// Gets and sets the property Dimensions.
/// <para>
/// The metric dimensions to create the anomaly detection model for.
/// </para>
/// </summary>
[AWSProperty(Max=10)]
public List<Dimension> Dimensions
{
get { return this._dimensions; }
set { this._dimensions = value; }
}
// Check to see if Dimensions property is set
internal bool IsSetDimensions()
{
return this._dimensions != null && this._dimensions.Count > 0;
}
/// <summary>
/// Gets and sets the property MetricName.
/// <para>
/// The name of the metric to create the anomaly detection model for.
/// </para>
/// </summary>
[AWSProperty(Required=true, Min=1, Max=255)]
public string MetricName
{
get { return this._metricName; }
set { this._metricName = value; }
}
// Check to see if MetricName property is set
internal bool IsSetMetricName()
{
return this._metricName != null;
}
/// <summary>
/// Gets and sets the property Namespace.
/// <para>
/// The namespace of the metric to create the anomaly detection model for.
/// </para>
/// </summary>
[AWSProperty(Required=true, Min=1, Max=255)]
public string Namespace
{
get { return this._awsNamespace; }
set { this._awsNamespace = value; }
}
// Check to see if Namespace property is set
internal bool IsSetNamespace()
{
return this._awsNamespace != null;
}
/// <summary>
/// Gets and sets the property Stat.
/// <para>
/// The statistic to use for the metric and the anomaly detection model.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public string Stat
{
get { return this._stat; }
set { this._stat = value; }
}
// Check to see if Stat property is set
internal bool IsSetStat()
{
return this._stat != null;
}
}
} | 33.298013 | 152 | 0.577367 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/CloudWatch/Generated/Model/PutAnomalyDetectorRequest.cs | 5,028 | C# |
using MediatR;
namespace ChatterBot.Core.Auth
{
public class AccessTokenReceived : IRequest<bool>
{
public string AccessToken { get; set; } = string.Empty;
public string Scope { get; set; } = string.Empty;
public string State { get; set; } = string.Empty;
public string TokenType { get; set; } = string.Empty;
public AccessTokenReceived()
{
}
public AccessTokenReceived(string accessToken,
string scope, string state, string tokenType)
{
AccessToken = accessToken;
Scope = scope;
State = state;
TokenType = tokenType;
}
}
}
| 26.153846 | 63 | 0.575 | [
"MIT"
] | SimonGeering/ChatterBot | src/Core/ChatterBot/Core/Auth/AccessTokenReceived.cs | 682 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的常规信息通过以下
// 特性集控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("MSCodeTools")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MSCodeTools")]
[assembly: AssemblyCopyright("Copyright © 2019")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 使此程序集中的类型
// 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型,
// 则将该类型上的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("c4b54bfd-0917-4f28-88e9-6ee70e11ae80")]
// 程序集的版本信息由下面四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
// 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
// 方法是按如下所示使用“*”:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 25.594595 | 56 | 0.714889 | [
"Apache-2.0"
] | andyshao/CodeTools | MSCodeTools/Properties/AssemblyInfo.cs | 1,306 | C# |
#if true
public class BuildinSceneIndex
{
public const int AppStage_lv_003_001_00 = 0;
public const int AppSystem_PermanentCollection = 1;
public const int CameraModule_CameraModule = 2;
public static readonly int[] Category_AppStage = new int[]{AppStage_lv_003_001_00, };
public static readonly int[] Category_AppSystem = new int[]{AppSystem_PermanentCollection, };
public static readonly int[] Category_CameraModule = new int[]{CameraModule_CameraModule, };
public static readonly string[] Paths = new string[]{
"Assets/Application/Level/lv_003_001_00.unity",
"Assets/Application/Scenes/PermanentCollection.unity",
"Assets/Until/Modules/Camera/Scenes/CameraModule.unity",
};
}
#endif
| 34.45 | 93 | 0.802612 | [
"MIT"
] | fullmoonhalf/until | Assets/Generated/UpdateScenesInBuild/BuildinSceneIndex.cs | 689 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace TogglDesktop.Tests
{
public class LibraryIntegrationTests : IClassFixture<LibraryFixture>
{
private readonly LibraryFixture _state;
private readonly string _firstTimeEntryGuid;
public LibraryIntegrationTests(LibraryFixture libraryFixture)
{
_state = libraryFixture;
Assert.True(Toggl.SetLoggedInUser(_state.MeJson));
_firstTimeEntryGuid = _state.TimeEntries[0].GUID;
}
[Fact]
public void ShowAppShouldNotCrash()
{
Toggl.ShowApp();
}
[Fact]
public void LoginWithFakeUserShouldFail()
{
Assert.False(Toggl.Login("john@doe.com", "foobar", 1));
}
[Fact]
public void LoginWithFakeGoogleTokenShouldFail()
{
Assert.False(Toggl.GoogleLogin("faketoken"));
}
[Fact]
public void ForgotPasswordShouldNotCrash()
{
Toggl.PasswordForgot();
}
[Fact]
public void OpenInBrowserShouldNotCrash()
{
Toggl.OpenInBrowser();
}
[Fact]
public void SendFeedbackShouldNotFail()
{
Assert.True(Toggl.SendFeedback("topic", "details", "filename"));
}
[Fact]
public void ViewTimeEntryListShouldContainKnownTimeEntry()
{
Toggl.ViewTimeEntryList();
Assert.Contains(_state.TimeEntries, te => te.ID == (ulong) 89818605);
}
[Fact]
public void EditShouldTriggerOnTimeEntryEditor()
{
var assertionExecuted = false;
Toggl.OnTimeEntryEditor += Assertion;
Toggl.Edit(_firstTimeEntryGuid, false, "description");
Toggl.OnTimeEntryEditor -= Assertion;
void Assertion(bool open, Toggl.TogglTimeEntryView timeEntry, string focusedFieldName)
{
Assert.True(open);
Assert.Equal(timeEntry.GUID, _firstTimeEntryGuid);
Assert.Equal("description", focusedFieldName);
assertionExecuted = true;
}
Assert.True(assertionExecuted);
}
[Fact]
public void EditPreferencesShouldOpenSettings()
{
var assertionExecuted = false;
Toggl.OnSettings += Assertion;
Toggl.EditPreferences();
Toggl.OnSettings -= Assertion;
void Assertion(bool open, Toggl.TogglSettingsView settings)
{
Assert.True(open);
assertionExecuted = true;
}
Assert.True(assertionExecuted);
}
[Fact]
public void StartShouldStartTimeEntry()
{
var guid = Toggl.Start("doing stuff", "", 0, 0, "", "");
Assert.NotNull(guid);
Assert.NotEqual(string.Empty, guid);
Assert.True(_state.IsRunning);
Assert.Equal(_state.RunningEntry.GUID, guid);
}
[Fact]
public void StopShouldStopTimeEntry()
{
var guid = Toggl.Start("doing stuff", "", 0, 0, "", "");
Assert.NotNull(guid);
Assert.NotEqual(string.Empty, guid);
Assert.True(_state.IsRunning);
Assert.Equal(_state.RunningEntry.GUID, guid);
Assert.True(Toggl.Stop());
Assert.False(_state.IsRunning);
Assert.NotEqual(_state.RunningEntry.GUID, guid);
}
[Fact]
public void ContinueShouldStartTimeEntry()
{
var guid = _state.TimeEntries[0].GUID;
var description = _state.TimeEntries[0].Description;
Toggl.Stop();
Assert.False(_state.IsRunning);
Toggl.Continue(guid);
Assert.True(_state.IsRunning);
Assert.Equal(description, _state.RunningEntry.Description);
}
[Fact]
public void ContinueLatestShouldStartTimeEntry()
{
Assert.True(Toggl.Stop());
Assert.False(_state.IsRunning);
Toggl.ContinueLatest();
Assert.True(_state.IsRunning);
}
[Fact]
public void DeleteTimeEntryShouldDeleteTimeEntry()
{
Toggl.DeleteTimeEntry(_firstTimeEntryGuid);
Assert.DoesNotContain(_state.TimeEntries, te => te.GUID == _firstTimeEntryGuid);
}
[Fact]
public void SetTimeEntryDurationShouldChangeDuration()
{
Assert.True(Toggl.SetTimeEntryDuration(_firstTimeEntryGuid, "1 hour"));
Assert.Equal(3600, GetTimeEntry(_firstTimeEntryGuid).DurationInSeconds);
}
[Fact]
public void SetTimeEntryProjectShouldChangeProject()
{
const ulong projectId = 2567324ul;
Assert.True(Toggl.SetTimeEntryProject(_firstTimeEntryGuid, 0, projectId, ""));
Assert.Equal(GetTimeEntry(_firstTimeEntryGuid).PID, projectId);
}
[Fact]
public void SetTimeEntryStartShouldChangeStartTime()
{
Assert.True(Toggl.SetTimeEntryStart(_firstTimeEntryGuid, "12:34"));
Assert.Equal("12:34", GetTimeEntry(_firstTimeEntryGuid).StartTimeString);
}
[Fact]
public void SetTimeEntryDateShouldChangeStartDate()
{
var now = DateTime.Now;
Assert.True(Toggl.SetTimeEntryDate(_firstTimeEntryGuid, now));
var started = Toggl.DateTimeFromUnix(GetTimeEntry(_firstTimeEntryGuid).Started);
Assert.Equal(started.Date, now.Date);
}
[Fact]
public void SetTimeEntryEndShouldChangeEndTime()
{
Assert.True(Toggl.SetTimeEntryEnd(_firstTimeEntryGuid, "23:45"));
Assert.Equal("23:45", GetTimeEntry(_firstTimeEntryGuid).EndTimeString);
}
[Fact]
public void SetTimeEntryTagsShouldChangeTags()
{
var tagsList = new List<string> {"John", "Anna", "Monica"};
Assert.True(Toggl.SetTimeEntryTags(_firstTimeEntryGuid, tagsList));
Assert.Equal(GetTimeEntry(_firstTimeEntryGuid).Tags, string.Join(Toggl.TagSeparator, tagsList));
}
[Fact]
public void SetTimeEntryBillableShouldChangeBillable()
{
Assert.True(Toggl.SetTimeEntryBillable(_firstTimeEntryGuid, true));
Assert.True(GetTimeEntry(_firstTimeEntryGuid).Billable);
Assert.True(Toggl.SetTimeEntryBillable(_firstTimeEntryGuid, false));
Assert.False(GetTimeEntry(_firstTimeEntryGuid).Billable);
}
[Fact]
public void SetTimeEntryDescriptionShouldChangeDescription()
{
Assert.True(Toggl.SetTimeEntryDescription(_firstTimeEntryGuid, "new description"));
Assert.Equal("new description", GetTimeEntry(_firstTimeEntryGuid).Description);
}
[Theory]
[InlineData(true)] // add as new entry
[InlineData(false)] // discard
public void DiscardAtShouldWorkCorrectly(bool split)
{
var guid = Toggl.Start("description", "", 0, 0, "", "");
Assert.True(Toggl.SetTimeEntryDuration(guid, "01:00"));
var entry = _state.RunningEntry;
var at = entry.Started;
var count = _state.TimeEntries.Count;
Assert.True(Toggl.DiscardTimeAt(guid, (long) (at + 20), split));
Assert.Equal(count + 1, _state.TimeEntries.Count);
Assert.Equal(split, _state.IsRunning);
}
[Theory]
[InlineData(1, 2, 3, 4)]
[InlineData(0, 0, 768, 1024)]
[InlineData(0, 0, 1200, 1900)]
[InlineData(-1900, -1200, 1200, 1900)]
public void SetWindowSettingsShouldSaveWindowSettings(long x, long y, long h, long w)
{
Toggl.SetWindowSettings(x, y, h, w);
long x1 = 0, y1 = 0, h1 = 0, w1 = 0;
Toggl.WindowSettings(ref x1, ref y1, ref h1, ref w1);
Assert.Equal(new[]{x, y, h, w}, new[]{x1, y1, h1, w1});
}
[Theory]
[InlineData(false, false)]
[InlineData(false, true)]
[InlineData(true, false)]
[InlineData(true, true)]
public void SetSettingsShouldSaveSettings(bool autotrack, bool pomodoro)
{
Toggl.TogglSettingsView currentSettings = default;
Toggl.OnSettings += ReadCurrentSettings;
Toggl.EditPreferences();
Toggl.OnSettings -= ReadCurrentSettings;
void ReadCurrentSettings(bool open, Toggl.TogglSettingsView settings) => currentSettings = settings;
var savedAutotrack = false;
var savedPomodoro = false;
Toggl.OnSettings += ReadSavedSettings;
currentSettings.Autotrack = autotrack;
currentSettings.Pomodoro = pomodoro;
Toggl.SetSettings(currentSettings);
void ReadSavedSettings(bool open, Toggl.TogglSettingsView settings)
{
savedAutotrack = settings.Autotrack;
savedPomodoro = settings.Pomodoro;
}
Assert.Equal(autotrack, savedAutotrack);
Assert.Equal(pomodoro, savedPomodoro);
Toggl.OnSettings -= ReadSavedSettings;
}
[Fact]
public void LogoutShouldLogTheUserOut()
{
var assertionExecuted = false;
Toggl.OnLogin += Assertion;
Assert.True(Toggl.Logout());
void Assertion(bool open, ulong userId)
{
Assert.True(open);
Assert.Equal(0ul, userId);
assertionExecuted = true;
}
Assert.True(assertionExecuted);
Toggl.OnLogin -= Assertion;
}
[Fact]
public void ClearCacheShouldLogTheUserOut()
{
var assertionExecuted = false;
Toggl.OnLogin += Assertion;
Assert.True(Toggl.Logout());
void Assertion(bool open, ulong userId)
{
Assert.True(open);
Assert.Equal(0ul, userId);
assertionExecuted = true;
}
Assert.True(assertionExecuted);
Toggl.OnLogin -= Assertion;
}
[Fact]
public void AddProjectShouldCreateNewProjectAndAssignItToTimeEntry()
{
var projectId = Toggl.AddProject(_firstTimeEntryGuid, 123456789, 0, null,
"testing project adding", false, null);
Assert.NotNull(projectId);
Assert.NotEqual(string.Empty, projectId);
Assert.Equal("testing project adding", GetTimeEntry(_firstTimeEntryGuid).ProjectLabel);
}
[Fact]
public void CreateClientShouldCreateNewClientInTheCorrectWorkspace()
{
var assertionExecuted = false;
Toggl.OnClientSelect += Assertion;
var clientId = Toggl.CreateClient(123456789, "test creating client");
Assert.NotNull(clientId);
Assert.NotEqual(string.Empty, clientId);
void Assertion(List<Toggl.TogglGenericView> clients)
{
Assert.Contains(clients, c => c.Name == "test creating client" && c.WID == 123456789);
assertionExecuted = true;
}
Assert.True(assertionExecuted);
Toggl.OnClientSelect -= Assertion;
}
[Theory]
[InlineData("fake channel", false)]
[InlineData("stable", true)]
[InlineData("beta", true)]
[InlineData("dev", true)]
public void SetChannelShouldSetChannelIfItIsValid(string channelName, bool isValid)
{
Assert.Equal(isValid, Toggl.SetUpdateChannel(channelName));
if (isValid)
{
Assert.Equal(channelName, Toggl.UpdateChannel());
}
}
[Fact]
public void UserEmailReturnsCorrectData()
{
Assert.Equal("johnsmith@toggl.com", Toggl.UserEmail());
}
[Fact]
public void SyncDoesNotCrash()
{
Toggl.Sync();
}
[Fact]
public void SetSleepDoesNotCrash()
{
Toggl.SetSleep();
}
[Fact]
public void SetWakeDoesNotCrash()
{
Toggl.SetWake();
}
[Fact]
public void SetIdleSecondsDoesNotCrash()
{
Toggl.SetIdleSeconds(123);
}
private Toggl.TogglTimeEntryView GetTimeEntry(string guid) => _state.TimeEntries.First(te => te.GUID == guid);
}
} | 32.432099 | 119 | 0.559117 | [
"BSD-3-Clause"
] | AndrewVebster/toggldesktop | src/ui/windows/TogglDesktop/TogglDesktop.Tests/LibraryIntegrationTests.cs | 13,137 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
namespace Example.Web.Legacy
{
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseUrls("http://localhost:5003")
;
}
}
| 26.037037 | 77 | 0.640114 | [
"MIT"
] | TartanLeGrand/Prise | samples/Example.Web.Legacy/Program.cs | 705 | C# |
using Elight.Entity.Sys;
using Elight.Logic.Base;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Elight.Utility.Web;
using Elight.Utility.Operator;
using Elight.Utility.Extension;
namespace Elight.Logic.Sys
{
public class SysPermissionLogic : BaseLogic
{
public bool ActionValidate(string userId, string action)
{
var authorizeModules = GetList(userId);
foreach (var item in authorizeModules)
{
if (!string.IsNullOrEmpty(item.Url))
{
string[] url = item.Url.Split('?');
if (url[0].ToLower() == action.ToLower())
{
return true;
}
}
}
return false;
}
public List<SysPermission> GetList(string userId)
{
using (var db = GetInstance())
{
return
db.Queryable<SysUserRoleRelation, SysRoleAuthorize, SysPermission>((A, B, C) => new object[] {
JoinType.Left,A.RoleId == B.RoleId,
JoinType.Left,C.Id == B.ModuleId,
})
.Where((A, B, C) => A.UserId == userId && C.IsEnable == "1" && C.DeleteMark == "0")
.OrderBy((A, B, C) => C.SortCode)
.Select((A, B, C) => new SysPermission
{
Id = C.Id,
ParentId = C.ParentId,
Layer = C.Layer,
EnCode = C.EnCode,
Name = C.Name,
JsEvent = C.JsEvent,
Icon = C.Icon,
Url = C.Url,
Remark = C.Remark,
Type = C.Type,
SortCode = C.SortCode,
IsEnable = C.IsEnable,
DeleteMark = C.DeleteMark,
CreateUser = C.CreateUser,
CreateTime = C.CreateTime,
ModifyUser = C.ModifyUser,
ModifyTime = C.ModifyTime
}).WithCache(60).ToList();
}
}
public List<SysPermission> GetList(int pageIndex, int pageSize, string keyWord, ref int totalCount)
{
using (var db = GetInstance())
{
if (keyWord.IsNullOrEmpty())
{
totalCount = db.Queryable<SysPermission>().Where(it => it.DeleteMark == "0").Count();
return db.Queryable<SysPermission>().Where(it => it.DeleteMark == "0").OrderBy(it => it.SortCode).ToPageList(pageIndex, pageSize);
}
totalCount = db.Queryable<SysPermission>().Where(it => it.DeleteMark == "0" && (it.Name.Contains(keyWord) || it.EnCode.Contains(keyWord))).Count();
return db.Queryable<SysPermission>().Where(it => it.DeleteMark == "0" && (it.Name.Contains(keyWord) || it.EnCode.Contains(keyWord))).OrderBy(it => it.SortCode).ToPageList(pageIndex, pageSize);
}
}
public int Delete(params string[] primaryKeys)
{
using (var db = GetInstance())
{
try
{
db.Ado.BeginTran();
//删除权限与角色的对应关系。
List<string> list = db.Queryable<SysPermission>().In(primaryKeys).Select(it => it.Id).ToList();
db.Deleteable<SysPermission>().In(primaryKeys).ExecuteCommand();
db.Deleteable<SysRoleAuthorize>().Where(it => list.Contains(it.ModuleId)).ExecuteCommand();
db.Ado.CommitTran();
return 1;
}
catch (Exception ex)
{
db.Ado.RollbackTran();
return 0;
}
}
}
public int GetChildCount(string parentId)
{
using (var db = GetInstance())
{
return db.Queryable<SysPermission>().Where(it => it.ParentId == parentId).ToList().Count();
}
}
public List<SysPermission> GetList()
{
using (var db = GetInstance())
{
return db.Queryable<SysPermission>().Where(it => it.DeleteMark == "0" && it.ShopID == OperatorProvider.Instance.Current.ShopID).OrderBy(it => it.SortCode).ToList();
}
}
public SysPermission Get(string primaryKey)
{
using (var db = GetInstance())
{
return db.Queryable<SysPermission>().InSingle(primaryKey);
}
}
public int Insert(SysPermission model)
{
using (var db = GetInstance())
{
model.Id = Guid.NewGuid().ToString().Replace("-", "");
//最高级菜单id为1
model.Layer = model.ParentId == "1" ? 0 : Get(model.ParentId).Layer += 1;
model.IsEnable = model.IsEnable == null ? "0" : "1";
model.IsEdit = "1";
model.IsPublic = "1";
model.DeleteMark = "0";
model.CreateUser = OperatorProvider.Instance.Current.Account;
model.CreateTime = DateTime.Now;
model.ModifyUser = model.CreateUser;
model.ModifyTime = model.CreateTime;
return db.Insertable<SysPermission>(model).ExecuteCommand();
}
}
public int Update(SysPermission model)
{
using (var db = GetInstance())
{
model.Layer = model.ParentId == "1" ? 0 : Get(model.ParentId).Layer += 1;
model.IsEnable = model.IsEnable == null ? "0" : "1";
//model.IsEdit = model.IsEdit == null ? "0" : "1";
//model.IsPublic = model.IsPublic == null ? "0" : "1";
model.ModifyUser = OperatorProvider.Instance.Current.Account;
model.ModifyTime = DateTime.Now;
return db.Updateable<SysPermission>(model).UpdateColumns(it => new
{
it.ParentId,
it.Layer,
it.EnCode,
it.Name,
it.JsEvent,
it.Icon,
it.Url,
it.Remark,
it.Type,
it.SortCode,
it.IsEnable,
it.ModifyUser,
it.ModifyTime,
}).ExecuteCommand();
}
}
}
}
| 37.379121 | 208 | 0.463472 | [
"MIT"
] | luhongguo/adentAnchor | Elight.Logic/Sys/SysPermissionLogic.cs | 6,843 | C# |
namespace App08TagHelpers.ViewModels
{
public class IndexViewModel
{
public string SearchTerm { get; set; }
}
}
| 16.625 | 46 | 0.654135 | [
"MIT"
] | bigfont/asp-net-5-beginner | App06TagHelpers/ViewModels/IndexModel.cs | 135 | C# |
using System;
using System.Collections.Generic;
namespace Company1.Department1.Project1.Services.Helper.DataAccess
{
/// <summary>
/// Singleton Implementation for TokenCollection
/// </summary>
public class SingletonData
{
private static volatile SingletonData instance;
private static object syncRoot = new Object();
public Dictionary<Tuple<String, String, String>, String> TokenCollection { get; set; }
public static SingletonData Instance
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
{
instance = new SingletonData();
}
}
}
return instance;
}
}
private SingletonData()
{
TokenCollection = new Dictionary<Tuple<String, String, String>, String>();
}
}
}
| 27.051282 | 94 | 0.487204 | [
"MIT"
] | manihew/urban-barnacle | Source/Company1.Department1.Project1.Services/Helper/DataAccess/SingletonData.cs | 1,057 | C# |
using System;
using System.Collections.Generic;
namespace Tulet.Models.Entities
{
public partial class Category
{
public Category()
{
Post = new HashSet<Post>();
}
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Post> Post { get; set; }
}
}
| 18.368421 | 51 | 0.561605 | [
"MIT"
] | chukwuemekachm/Tulet | Models/Entities/Category.cs | 351 | C# |
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json.Linq;
namespace ScriptPlayer.Shared.Scripts
{
public class FeelMeLikeBruteForceJsonLoader : FeelMeJsonLoaderBase
{
public override List<ScriptFileFormat> GetSupportedFormats()
{
return new List<ScriptFileFormat>
{
new ScriptFileFormat("FeelMe Meta File (Unknown Json)", "meta", "json")
};
}
protected override JToken GetScriptNode(JToken file)
{
var tokens = file.SelectTokens("$..*");
var possibleTokens = tokens.Where(t => !t.HasValues).ToList();
int longestToken = possibleTokens.Max(t => t.ToString().Length);
return possibleTokens.First(t => t.ToString().Length == longestToken);
}
}
} | 30.703704 | 87 | 0.618818 | [
"BSD-3-Clause"
] | atkdg/ScriptPlayer | ScriptPlayer/ScriptPlayer.Shared/Scripts/FeelMe/FeelMeLikeBruteForceJsonLoader.cs | 829 | C# |
//
// Copyright (C) DataStax 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.Net;
using System.Text;
using System.Threading.Tasks;
using Cassandra.Connections.Control;
namespace Cassandra.Connections
{
/// <inheritdoc />
internal class SniConnectionEndPoint : IConnectionEndPoint
{
private readonly string _serverName;
private readonly IPEndPoint _hostIpEndPoint;
public SniConnectionEndPoint(IPEndPoint socketIpEndPoint, string serverName, IContactPoint contactPoint) :
this(socketIpEndPoint, null, serverName, contactPoint)
{
}
public SniConnectionEndPoint(IPEndPoint socketIpEndPoint, IPEndPoint hostIpEndPoint, string serverName, IContactPoint contactPoint)
{
SocketIpEndPoint = socketIpEndPoint ?? throw new ArgumentNullException(nameof(socketIpEndPoint));
_hostIpEndPoint = hostIpEndPoint;
_serverName = serverName;
ContactPoint = contactPoint;
var stringBuilder = new StringBuilder(hostIpEndPoint?.ToString() ?? socketIpEndPoint.ToString());
if (hostIpEndPoint == null && serverName != null)
{
stringBuilder.Append($" ({serverName})");
}
EndpointFriendlyName = stringBuilder.ToString();
}
/// <inheritdoc />
public IContactPoint ContactPoint { get; }
/// <inheritdoc />
public IPEndPoint SocketIpEndPoint { get; }
/// <inheritdoc />
public string EndpointFriendlyName { get; }
/// <inheritdoc />
public override string ToString()
{
return EndpointFriendlyName;
}
/// <inheritdoc />
public Task<string> GetServerNameAsync()
{
return Task.FromResult(_serverName);
}
/// <inheritdoc />
public IPEndPoint GetHostIpEndPointWithFallback()
{
return _hostIpEndPoint ?? SocketIpEndPoint;
}
/// <inheritdoc />
public IPEndPoint GetOrParseHostIpEndPoint(IRow row, IAddressTranslator translator, int port)
{
if (_hostIpEndPoint != null)
{
return _hostIpEndPoint;
}
var ipEndPoint = TopologyRefresher.GetAddressForLocalOrPeerHost(row, translator, port);
if (ipEndPoint == null)
{
throw new DriverInternalError("Could not parse the node's ip address from system tables.");
}
return ipEndPoint;
}
public bool Equals(IConnectionEndPoint other)
{
return Equals((object)other);
}
public override bool Equals(object obj)
{
if (!(obj is SniConnectionEndPoint point))
{
return false;
}
if (!object.Equals(_hostIpEndPoint, point._hostIpEndPoint))
{
return false;
}
if (!object.Equals(SocketIpEndPoint, point.SocketIpEndPoint))
{
return false;
}
return _serverName == point._serverName;
}
public override int GetHashCode()
{
return Utils.CombineHashCodeWithNulls(new object[]
{
_hostIpEndPoint, _serverName, SocketIpEndPoint
});
}
}
} | 30.515385 | 139 | 0.600706 | [
"Apache-2.0"
] | halex2005/csharp-driver | src/Cassandra/Connections/SniConnectionEndPoint.cs | 3,967 | C# |
using System;
using Xamarin.Forms;
namespace FormsGallery
{
class MyotonicDystrophy : ContentPage
{
public MyotonicDystrophy()
{
Command<Type> navigateCommand =
new Command<Type>(async (Type pageType) =>
{
Page page = (Page)Activator.CreateInstance(pageType);
await this.Navigation.PushAsync(page);
});
BackgroundColor = Color.White;
Label header = new Label
{
Text = "Myotonic Dystrophy",
TextColor = Color.Black,
FontSize = 30,
FontAttributes = FontAttributes.Bold,
HorizontalOptions = LayoutOptions.Center,
HorizontalTextAlignment = TextAlignment.Center,
};
ScrollView scrollView = new ScrollView
{
Margin = 0,
Padding = 0,
Content = new StackLayout
{
Spacing = 0,
Padding = 0,
//Orientation = StackOrientation.Vertical,
Children =
{
new StackLayout
{
Padding = 0,
Children =
{
new Label
{
FontSize = 20,
Text = "Background",
TextColor = Color.Black,
FontAttributes = FontAttributes.Bold,
},
new Label
{
Text = " ",
FontSize = 5,
},
}
},
new StackLayout
{
Padding = 0,
Orientation = StackOrientation.Horizontal,
Children =
{
new Label
{
Text = "• ",
TextColor = Color.Black,
},
new Label
{
FontSize = 16,
Text = "Clinically & genetically heterogeneous disorder with two major forms: type 1 (DM1) & type 2 (DM2)",
TextColor = Color.Black,
HorizontalOptions = LayoutOptions.Start
},
}
},
new StackLayout
{
Padding = 0,
Orientation = StackOrientation.Horizontal,
Children =
{
new Label
{
Text = "• ",
TextColor = Color.Black,
},
new Label
{
FontSize = 16,
Text = "Multisystem disorder characterized by skeletal muscle weakness & myotonia, cardiac conduction abnormalities, cataracts, testicular failure, hypogammaglobulinemia, & insulin resistance\n\n",
TextColor = Color.Black,
HorizontalOptions = LayoutOptions.Start
},
}
},
new StackLayout
{
Padding = 0,
Children =
{
new Label
{
FontSize = 20,
Text = "Considerations ",
TextColor = Color.Black,
FontAttributes = FontAttributes.Bold,
},
new Label
{
Text = " ",
FontSize = 5,
},
}
},
new StackLayout
{
Padding = 0,
Orientation = StackOrientation.Horizontal,
Children =
{
new Label
{
Text = "• ",
TextColor = Color.Black,
},
new Label
{
FontSize = 16,
Text = "Multisystem disease:",
TextColor = Color.Black,
HorizontalOptions = LayoutOptions.Start
},
}
},
new StackLayout
{
Padding = new Thickness(20, 0, 0, 0),
Orientation = StackOrientation.Horizontal,
Children =
{
new Label
{
Text = "• ",
TextColor = Color.Black,
},
new Label
{
FontSize = 16,
Text = "Airway ",
TextColor = Color.Black,
HorizontalOptions = LayoutOptions.Start
},
}
},
new StackLayout
{
Padding = new Thickness(40, 0, 0, 0),
Orientation = StackOrientation.Horizontal,
Children =
{
new Label
{
Text = "• ",
TextColor = Color.Black,
},
new Label
{
FontSize = 16,
Text = "Bulbar dysfunction & risk of aspiration",
TextColor = Color.Black,
HorizontalOptions = LayoutOptions.Start
},
}
},
new StackLayout
{
Padding = new Thickness(40, 0, 0, 0),
Orientation = StackOrientation.Horizontal,
Children =
{
new Label
{
Text = "• ",
TextColor = Color.Black,
},
new Label
{
FontSize = 16,
Text = "Central sleep apnea",
TextColor = Color.Black,
HorizontalOptions = LayoutOptions.Start
},
}
},
new StackLayout
{
Padding = new Thickness(20, 0, 0, 0),
Orientation = StackOrientation.Horizontal,
Children =
{
new Label
{
Text = "• ",
TextColor = Color.Black,
},
new Label
{
FontSize = 16,
Text = "Respiratory: ",
TextColor = Color.Black,
HorizontalOptions = LayoutOptions.Start
},
}
},
new StackLayout
{
Padding = new Thickness(20, 0, 0, 0),
Orientation = StackOrientation.Horizontal,
Children =
{
new Label
{
Text = "• ",
TextColor = Color.Black,
},
new Label
{
FontSize = 16,
Text = "Respiratory: ",
TextColor = Color.Black,
HorizontalOptions = LayoutOptions.Start
},
}
},
new StackLayout
{
Padding = new Thickness(40, 0, 0, 0),
Orientation = StackOrientation.Horizontal,
Children =
{
new Label
{
Text = "• ",
TextColor = Color.Black,
},
new Label
{
FontSize = 16,
Text = "Restrictive lung disease (weak respiratory muscles)",
TextColor = Color.Black,
HorizontalOptions = LayoutOptions.Start
},
}
},
new StackLayout
{
Padding = new Thickness(40, 0, 0, 0),
Orientation = StackOrientation.Horizontal,
Children =
{
new Label
{
Text = "• ",
TextColor = Color.Black,
},
new Label
{
FontSize = 16,
Text = "Possible pulmonary hypertension",
TextColor = Color.Black,
HorizontalOptions = LayoutOptions.Start
},
}
},
new StackLayout
{
Padding = new Thickness(40, 0, 0, 0),
Orientation = StackOrientation.Horizontal,
Children =
{
new Label
{
Text = "• ",
TextColor = Color.Black,
},
new Label
{
FontSize = 16,
Text = "↓ ventilatory response to hypoxia/hypercarbia",
TextColor = Color.Black,
HorizontalOptions = LayoutOptions.Start
},
}
},
new StackLayout
{
Padding = new Thickness(20, 0, 0, 0),
Orientation = StackOrientation.Horizontal,
Children =
{
new Label
{
Text = "• ",
TextColor = Color.Black,
},
new Label
{
FontSize = 16,
Text = "Cardiac:",
TextColor = Color.Black,
HorizontalOptions = LayoutOptions.Start
},
}
},
new StackLayout
{
Padding = new Thickness(40, 0, 0, 0),
Orientation = StackOrientation.Horizontal,
Children =
{
new Label
{
Text = "• ",
TextColor = Color.Black,
},
new Label
{
FontSize = 16,
Text = "Cardiomyopathy",
TextColor = Color.Black,
HorizontalOptions = LayoutOptions.Start
},
}
},
new StackLayout
{
Padding = new Thickness(40, 0, 0, 0),
Orientation = StackOrientation.Horizontal,
Children =
{
new Label
{
Text = "• ",
TextColor = Color.Black,
},
new Label
{
FontSize = 16,
Text = "Dysrhythmias & heart blocks",
TextColor = Color.Black,
HorizontalOptions = LayoutOptions.Start
},
}
},
new StackLayout
{
Padding = new Thickness(20, 0, 0, 0),
Orientation = StackOrientation.Horizontal,
Children =
{
new Label
{
Text = "• ",
TextColor = Color.Black,
},
new Label
{
FontSize = 16,
Text = "GI:",
TextColor = Color.Black,
HorizontalOptions = LayoutOptions.Start
},
}
},
new StackLayout
{
Padding = new Thickness(40, 0, 0, 0),
Orientation = StackOrientation.Horizontal,
Children =
{
new Label
{
Text = "• ",
TextColor = Color.Black,
},
new Label
{
FontSize = 16,
Text = "Delayed gastric motility",
TextColor = Color.Black,
HorizontalOptions = LayoutOptions.Start
},
}
},
new StackLayout
{
Padding = new Thickness(20, 0, 0, 0),
Orientation = StackOrientation.Horizontal,
Children =
{
new Label
{
Text = "• ",
TextColor = Color.Black,
},
new Label
{
FontSize = 16,
Text = "Endocrine:",
TextColor = Color.Black,
HorizontalOptions = LayoutOptions.Start
},
}
},
new StackLayout
{
Padding = new Thickness(40, 0, 0, 0),
Orientation = StackOrientation.Horizontal,
Children =
{
new Label
{
Text = "• ",
TextColor = Color.Black,
},
new Label
{
FontSize = 16,
Text = "Hypothyroid, diabetes mellitus, adrenal insufficiency",
TextColor = Color.Black,
HorizontalOptions = LayoutOptions.Start
},
}
},
new StackLayout
{
Padding = 0,
Orientation = StackOrientation.Horizontal,
Children =
{
new Label
{
Text = "• ",
TextColor = Color.Black,
},
new Label
{
FontSize = 16,
Text = "Altered sensitivity to anesthetic agents:",
TextColor = Color.Black,
HorizontalOptions = LayoutOptions.Start
},
}
},
new StackLayout
{
Padding = new Thickness(20, 0, 0, 0),
Orientation = StackOrientation.Horizontal,
Children =
{
new Label
{
Text = "• ",
TextColor = Color.Black,
},
new Label
{
FontSize = 16,
Text = "Succinylcholine contraindicated due to risks of hyperkalemia & myotonic contractures",
TextColor = Color.Black,
HorizontalOptions = LayoutOptions.Start
},
}
},
new StackLayout
{
Padding = new Thickness(20, 0, 0, 0),
Orientation = StackOrientation.Horizontal,
Children =
{
new Label
{
Text = "• ",
TextColor = Color.Black,
},
new Label
{
FontSize = 16,
Text = "Sensitivity to CNS depessants (propofol, opioids, benzodiazepines, barbiturates)",
TextColor = Color.Black,
HorizontalOptions = LayoutOptions.Start
},
}
},
new StackLayout
{
Padding = new Thickness(20, 0, 0, 0),
Orientation = StackOrientation.Horizontal,
Children =
{
new Label
{
Text = "• ",
TextColor = Color.Black,
},
new Label
{
FontSize = 16,
Text = "Anticholingerics may trigger myotonic contracture, don't use neostigmine!",
TextColor = Color.Black,
HorizontalOptions = LayoutOptions.Start
},
}
},
new StackLayout
{
Padding = 0,
Orientation = StackOrientation.Horizontal,
Children =
{
new Label
{
Text = "• ",
TextColor = Color.Black,
},
new Label
{
FontSize = 16,
Text = "Risk of perioperative myotonic crisis:",
TextColor = Color.Black,
HorizontalOptions = LayoutOptions.Start
},
}
},
new StackLayout
{
Padding = new Thickness(20, 0, 0, 0),
Orientation = StackOrientation.Horizontal,
Children =
{
new Label
{
Text = "• ",
TextColor = Color.Black,
},
new Label
{
FontSize = 16,
Text = "Triggers:",
TextColor = Color.Black,
HorizontalOptions = LayoutOptions.Start
},
}
},
new StackLayout
{
Padding = new Thickness(40, 0, 0, 0),
Orientation = StackOrientation.Horizontal,
Children =
{
new Label
{
Text = "• ",
TextColor = Color.Black,
},
new Label
{
FontSize = 16,
Text = "Drugs (e.g., succinylcholine, neostigmine)",
TextColor = Color.Black,
HorizontalOptions = LayoutOptions.Start
},
}
},
new StackLayout
{
Padding = new Thickness(40, 0, 0, 0),
Orientation = StackOrientation.Horizontal,
Children =
{
new Label
{
Text = "• ",
TextColor = Color.Black,
},
new Label
{
FontSize = 16,
Text = "Surgical manipulation, electrocautery, nerve stimulator",
TextColor = Color.Black,
HorizontalOptions = LayoutOptions.Start
},
}
},
new StackLayout
{
Padding = new Thickness(40, 0, 0, 0),
Orientation = StackOrientation.Horizontal,
Children =
{
new Label
{
Text = "• ",
TextColor = Color.Black,
},
new Label
{
FontSize = 16,
Text = "Hypothermia/shivering",
TextColor = Color.Black,
HorizontalOptions = LayoutOptions.Start
},
}
},
new StackLayout
{
Padding = new Thickness(20, 0, 0, 0),
Orientation = StackOrientation.Horizontal,
Children =
{
new Label
{
Text = "• ",
TextColor = Color.Black,
},
new Label
{
FontSize = 16,
Text = "Treatment:",
TextColor = Color.Black,
HorizontalOptions = LayoutOptions.Start
},
}
},
new StackLayout
{
Padding = new Thickness(20, 0, 0, 0),
Orientation = StackOrientation.Horizontal,
Children =
{
new Label
{
Text = "• ",
TextColor = Color.Black,
},
new Label
{
FontSize = 16,
Text = "Phenytoin, procainamide, quinine, IM lidocaine, ↑ volatile",
TextColor = Color.Black,
HorizontalOptions = LayoutOptions.Start
},
}
},
new StackLayout
{
Padding = new Thickness(40, 0, 0, 0),
Orientation = StackOrientation.Horizontal,
Children =
{
new Label
{
Text = "• ",
TextColor = Color.Black,
},
new Label
{
FontSize = 16,
Text = "Phenytoin/procainamide: 18mg/kg over 20 min",
TextColor = Color.Black,
HorizontalOptions = LayoutOptions.Start
},
}
},
new StackLayout
{
Padding = new Thickness(40, 0, 0, 0),
Orientation = StackOrientation.Horizontal,
Children =
{
new Label
{
Text = "• ",
TextColor = Color.Black,
},
new Label
{
FontSize = 16,
Text = "Quinine 300-600mg IV",
TextColor = Color.Black,
HorizontalOptions = LayoutOptions.Start
},
}
},
new StackLayout
{
Padding = new Thickness(20, 0, 0, 0),
Orientation = StackOrientation.Horizontal,
Children =
{
new Label
{
Text = "• ",
TextColor = Color.Black,
},
new Label
{
FontSize = 16,
Text = "Muscle relaxants & IV anesthetics do NOT work\n\n",
TextColor = Color.Black,
HorizontalOptions = LayoutOptions.Start
},
}
},
new StackLayout
{
Padding = 0,
Children =
{
new Label
{
FontSize = 20,
Text = "Goals/Optimization",
TextColor = Color.Black,
FontAttributes = FontAttributes.Bold,
},
new Label
{
Text = " ",
FontSize = 5,
},
}
},
new StackLayout
{
Padding = 0,
Orientation = StackOrientation.Horizontal,
Children =
{
new Label
{
Text = "• ",
TextColor = Color.Black,
},
new Label
{
FontSize = 16,
Text = "If elective, multidisciplinary discussion regarding plans for surgery ",
TextColor = Color.Black,
HorizontalOptions = LayoutOptions.Start
},
}
},
new StackLayout
{
Padding = 0,
Orientation = StackOrientation.Horizontal,
Children =
{
new Label
{
Text = "• ",
TextColor = Color.Black,
},
new Label
{
FontSize = 16,
Text = "Prevent aspiration, administer aspiration prophylaxis ",
TextColor = Color.Black,
HorizontalOptions = LayoutOptions.Start
},
}
},
new StackLayout
{
Padding = 0,
Orientation = StackOrientation.Horizontal,
Children =
{
new Label
{
Text = "• ",
TextColor = Color.Black,
},
new Label
{
FontSize = 16,
Text = "Avoid hemodynamic instability",
TextColor = Color.Black,
HorizontalOptions = LayoutOptions.Start
},
}
},
new StackLayout
{
Padding = 0,
Orientation = StackOrientation.Horizontal,
Children =
{
new Label
{
Text = "• ",
TextColor = Color.Black,
},
new Label
{
FontSize = 16,
Text = "Avoid precipitants of myotonic crisis & treat if required",
TextColor = Color.Black,
HorizontalOptions = LayoutOptions.Start
},
}
},
new StackLayout
{
Padding = 0,
Orientation = StackOrientation.Horizontal,
Children =
{
new Label
{
Text = "• ",
TextColor = Color.Black,
},
new Label
{
FontSize = 16,
Text = "Arrange appropriate disposition (need for post-operative monitoring, ventilation)\n\n",
TextColor = Color.Black,
HorizontalOptions = LayoutOptions.Start
},
}
},
new StackLayout
{
Padding = 0,
Children =
{
new Label
{
FontSize = 20,
Text = "Conflicts ",
TextColor = Color.Black,
FontAttributes = FontAttributes.Bold,
},
new Label
{
Text = " ",
FontSize = 5,
},
}
},
new StackLayout
{
Padding = 0,
Orientation = StackOrientation.Horizontal,
Children =
{
new Label
{
Text = "• ",
TextColor = Color.Black,
},
new Label
{
FontSize = 16,
Text = "Need to prevent aspiration (RSI) vs contraindication to succinylcholine & high dose rocuronium (as reversal with neostigmine contraindicated)\n\n ",
TextColor = Color.Black,
HorizontalOptions = LayoutOptions.Start
},
}
},
new StackLayout
{
Padding = 0,
Children =
{
new Label
{
FontSize = 20,
Text = "Pregnancy ",
TextColor = Color.Black,
FontAttributes = FontAttributes.Bold,
},
new Label
{
Text = " ",
FontSize = 5,
},
}
},
new StackLayout
{
Padding = 0,
Orientation = StackOrientation.Horizontal,
Children =
{
new Label
{
Text = "• ",
TextColor = Color.Black,
},
new Label
{
FontSize = 16,
Text = "High risk pregnant patient: ↑ muscle weakness/myotonia, heart failure, uterine atony, postpartum hemorrhage",
TextColor = Color.Black,
HorizontalOptions = LayoutOptions.Start
},
}
},
new StackLayout
{
Padding = 0,
Orientation = StackOrientation.Horizontal,
Children =
{
new Label
{
Text = "• ",
TextColor = Color.Black,
},
new Label
{
FontSize = 16,
Text = "Neuraxial anesthesia is preferred for labor & vaginal or cesarean delivery",
TextColor = Color.Black,
HorizontalOptions = LayoutOptions.Start
},
}
},
}
}
};
Button homeButton = new Button
{
Text = "Home Page",
Command = navigateCommand,
CommandParameter = typeof(HomePage),
Font = Font.SystemFontOfSize(NamedSize.Large),
BorderWidth = 1,
HorizontalOptions = LayoutOptions.Center,
VerticalOptions = LayoutOptions.CenterAndExpand
};
// Build the page.
this.Content = new StackLayout
{
Children =
{
header,
scrollView,
homeButton,
}
};
}
}
} | 42.615309 | 233 | 0.243109 | [
"Apache-2.0"
] | EricGrahamMacEachern/anesthesiaconsiderations-Android | anesthesiaconsiderations-Android/MyotonicDystrophy.cs | 43,513 | C# |
#region Copyright(c) Alexey Sadomov, Vladimir Timashkov. All Rights Reserved.
// -----------------------------------------------------------------------------
// Copyright(c) 2010 Alexey Sadomov, Vladimir Timashkov. All Rights Reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. No Trademark License - Microsoft Public License (Ms-PL) does not grant you rights to use
// authors names, logos, or trademarks.
// 2. If you distribute any portion of the software, you must retain all copyright,
// patent, trademark, and attribution notices that are present in the software.
// 3. If you distribute any portion of the software in source code form, you may do
// so only under this license by including a complete copy of Microsoft Public License (Ms-PL)
// with your distribution. If you distribute any portion of the software in compiled
// or object code form, you may only do so under a license that complies with
// Microsoft Public License (Ms-PL).
// 4. The names of the authors may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// The software is licensed "as-is." You bear the risk of using it. The authors
// give no express warranties, guarantees or conditions. You may have additional consumer
// rights under your local laws which this license cannot change. To the extent permitted
// under your local laws, the authors exclude the implied warranties of merchantability,
// fitness for a particular purpose and non-infringement.
// -----------------------------------------------------------------------------
#endregion
using System;
using System.Xml.Linq;
using CamlexNET.Impl;
using CamlexNET.Impl.Operands;
using CamlexNET.Impl.ReverseEngeneering;
using CamlexNET.Impl.ReverseEngeneering.Caml.Factories;
using CamlexNET.Interfaces.ReverseEngeneering;
using NUnit.Framework;
using Rhino.Mocks;
namespace CamlexNET.UnitTests.ReverseEngeneering.Analyzers.TestBase
{
internal class ReUnaryExpressionTestBase<TAnalyzer, TOperation>
where TAnalyzer : ReNullabilityBaseAnalyzer
where TOperation : UnaryOperationBase
{
internal void BASE_test_WHEN_xml_is_null_THEN_expression_is_not_valid
(Func<XElement, IReOperandBuilder, TAnalyzer> constructor)
{
var analyzer = constructor(null, null);
Assert.IsFalse(analyzer.IsValid());
}
internal void BASE_test_WHEN_neither_field_ref_nor_value_specified_THEN_expression_is_not_valid
(Func<XElement, IReOperandBuilder, TAnalyzer> constructor, string operationName)
{
var xml = string.Format(
" <{0}>" +
" </{0}>",
operationName);
var analyzer = constructor(XmlHelper.Get(xml), null);
Assert.IsFalse(analyzer.IsValid());
}
internal void BASE_test_WHEN_field_ref_without_name_attribute_specified_THEN_expression_is_not_valid
(Func<XElement, IReOperandBuilder, TAnalyzer> constructor, string operationName)
{
var xml = string.Format(
"<{0}>" +
" <FieldRef />" +
"</{0}>",
operationName);
var analyzer = constructor(XmlHelper.Get(xml), new ReOperandBuilderFromCaml());
Assert.IsFalse(analyzer.IsValid());
}
internal void BASE_test_WHEN_field_ref_specified_and_value_not_specified_THEN_expression_is_not_valid
(Func<XElement, IReOperandBuilder, TAnalyzer> constructor, string operationName)
{
var xml = string.Format(
"<{0}>" +
" <FieldRef Name=\"Title\" />" +
"</{0}>",
operationName);
var analyzer = constructor(XmlHelper.Get(xml), null);
Assert.IsTrue(analyzer.IsValid());
}
internal void BASE_test_WHEN_expression_is_not_valid_THEN_exception_is_thrown
(Func<XElement, IReOperandBuilder, TAnalyzer> constructor)
{
var analyzer = constructor(null, null);
analyzer.GetOperation();
}
internal void BASE_test_WHEN_expression_is_valid_THEN_operation_is_returned
(Func<XElement, IReOperandBuilder, TAnalyzer> constructor, string operationName, string operationSymbol)
{
var xml = string.Format(
"<{0}>" +
" <FieldRef Name=\"Title\" />" +
"</{0}>",
operationName);
var b = MockRepository.GenerateStub<IReOperandBuilder>();
b.Stub(c => c.CreateFieldRefOperand(null)).Return(new FieldRefOperand("Title")).IgnoreArguments();
var analyzer = constructor(XmlHelper.Get(xml), b);
var operation = analyzer.GetOperation();
Assert.IsInstanceOf<TOperation>(operation);
var operationT = (TOperation)operation;
Assert.That(operationT.ToExpression().ToString(), Is.EqualTo(
string.Format("(x.get_Item(\"Title\") {0})", operationSymbol)));
}
}
} | 46.904348 | 117 | 0.629218 | [
"MIT"
] | sadomovalex/camlex | Camlex.NET.UnitTests/ReverseEngeneering/Analyzers/TestBase/ReUnaryExpressionTestBase.cs | 5,396 | C# |
using System.Diagnostics;
using System.IO.Compression;
using System.Net;
namespace WO_Updater {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e) {
using WebClient wc = new();
wc.DownloadProgressChanged += wc_DownloadProgressChanged;
wc.DownloadFileCompleted += wc_DownloadFileCompleted; ;
wc.DownloadFileAsync(
new System.Uri("https://www.dropbox.com/s/m47ixlm4ohsephc/Windows%20Optimizer.zip?dl=1"),
Path.Combine(Environment.CurrentDirectory, "Latest.zip")
);
}
void wc_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e) {
progressBar1.Value = e.ProgressPercentage;
label1.Text = $"Download ({progressBar1.Value}%)";
}
void wc_DownloadFileCompleted(object? sender, System.ComponentModel.AsyncCompletedEventArgs e) {
ZipFile.ExtractToDirectory(Path.Combine(Environment.CurrentDirectory, "Latest.zip"), Environment.CurrentDirectory, true);
File.Delete(Path.Combine(Environment.CurrentDirectory, "Latest.zip"));
Process p = new();
p.StartInfo.FileName = Path.Combine(Environment.CurrentDirectory, "Windows Optimizer.exe");
p.Start();
Application.Exit();
}
}
} | 41.085714 | 133 | 0.646036 | [
"MIT"
] | DeanReynolds/Windows-Optimizer | WO Updater/Form1.cs | 1,438 | C# |
//
// MessageHandlers.cs
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using System.Net;
using System.Net.Http;
using System.Linq;
using System.IO;
using NUnit.Framework;
#if MONOMAC
using Foundation;
#endif
namespace MonoTests.System.Net.Http
{
[TestFixture]
public class MessageHandlerTest
{
HttpMessageHandler GetHandler (Type handler_type)
{
return (HttpMessageHandler) Activator.CreateInstance (handler_type);
}
[Test]
#if !__WATCHOS__
[TestCase (typeof (HttpClientHandler))]
[TestCase (typeof (CFNetworkHandler))]
#endif
[TestCase (typeof (NSUrlSessionHandler))]
public void DnsFailure (Type handlerType)
{
bool done = false;
Exception ex = null;
TestRuntime.RunAsync (DateTime.Now.AddSeconds (30), async () =>
{
try {
HttpClient client = new HttpClient (GetHandler (handlerType));
var s = await client.GetStringAsync ("http://doesnotexist.xamarin.com");
} catch (Exception e) {
ex = e;
} finally {
done = true;
}
}, () => done);
Assert.IsNotNull (ex, "Exception");
// The handlers throw different types of exceptions, so we can't assert much more than that something went wrong.
}
}}
| 22.22807 | 116 | 0.704815 | [
"BSD-3-Clause"
] | alexanderkyte/xamarin-macios | tests/monotouch-test/System.Net.Http/MessageHandlers.cs | 1,269 | C# |
using System;
using LogParserApi.Core.Contracts;
using LogParserApi.Parsers;
using LogParserApi.Parsers.FileSystem;
using LogParserApi.Parsers.Log4Net;
using LogParserApi.ParserTests.UserSecrets;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace LogParserApi.ParserTests
{
public class DependencyRegistration
{
private readonly ServiceCollection _services;
public DependencyRegistration()
{
_services = new ServiceCollection();
_services.AddTransient<IFileReader, FileReader>();
}
public DependencyRegistration AddLog4NetParser()
{
_services.AddTransient<ILogReader, Log4NetParser>();
_services.AddSingleton<ILineParser, Log4NetLineParser>();
return this;
}
public DependencyRegistration AddConfigurations(IConfiguration config)
{
_services.Configure<Locations>(config.GetSection(nameof(Locations)));
return this;
}
public IServiceProvider Build()
{
return _services.BuildServiceProvider();
}
}
}
| 28.414634 | 81 | 0.683262 | [
"MIT"
] | penCsharpener/LogParserApi | tests/LogParserApi.ParserTests/DependencyRegistration.cs | 1,167 | C# |
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace Mundipagg.Models.Request
{
[JsonObject(NamingStrategyType = typeof(SnakeCaseNamingStrategy))]
public class UpdateGeneralSettingsRequest
{
public string DisplayName { get; set; }
public string Logo { get; set; }
public string Email { get; set; }
public string Website { get; set; }
public string Theme { get; set; }
public string PrimaryColor { get; set; }
public string SecondaryColor { get; set; }
}
}
| 22.16 | 70 | 0.65343 | [
"MIT"
] | AmandaMaiaPessanha/mundipagg-dotnet | Mundipagg/Models/Request/UpdateGeneralSettingsRequest.cs | 556 | C# |
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
namespace GloboTicket.Web
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
| 24.857143 | 70 | 0.578544 | [
"Apache-2.0"
] | CraigRichards/deploying-asp-dot-net-core-microservices-kubernetes-aks | GloboTicket/GloboTicket.Web.Bff/Program.cs | 522 | C# |
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Hornbill;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using NUnit.Framework;
using Shouldly;
using Stackage.Core.Abstractions.Metrics;
using Stackage.Http.Extensions;
using Stackage.Http.Tests.Services;
namespace Stackage.Http.Tests.MetricsScenarios
{
public class get_request_from_service_with_no_base_address : handler_scenario
{
private HttpStatusCode _statusCode;
private string _content;
[OneTimeSetUp]
public async Task setup_scenario()
{
setup_handler_scenario(
stubHttpService =>
{
stubHttpService.AddResponse("/passthrough", Method.GET, Response.WithBody(200, "bar"));
},
(stubBaseAddress, services) =>
{
var configuration = new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary<string, string>
{
{"TESTHTTPSERVICE:TIMEOUTMS", "500"}
}).Build();
services.AddHttpService<ITestHttpService, TestHttpService, TestHttpServiceConfiguration>(configuration);
});
var api = ServiceProvider.GetRequiredService<ITestHttpService>();
(_statusCode, _content) = await api.Passthrough(StubBaseAddress);
}
[OneTimeTearDown]
public void teardown_scenario()
{
teardown_handler_scenario();
}
[Test]
public void should_return_status_code_200()
{
_statusCode.ShouldBe(HttpStatusCode.OK);
}
[Test]
public void should_return_content()
{
_content.ShouldBe("bar");
}
[Test]
public void should_write_two_metrics()
{
Assert.That(MetricSink.Metrics.Count, Is.EqualTo(2));
}
[Test]
public void should_write_start_metric()
{
var metric = (Counter) MetricSink.Metrics.First();
Assert.That(metric.Name, Is.EqualTo("http_client_start"));
Assert.That(metric.Dimensions["name"], Is.EqualTo("TestHttpService"));
Assert.That(metric.Dimensions["method"], Is.EqualTo("GET"));
Assert.That(metric.Dimensions["path"], Is.EqualTo("/passthrough"));
}
[Test]
public void should_write_end_metric()
{
var metric = (Gauge) MetricSink.Metrics.Last();
Assert.That(metric.Name, Is.EqualTo("http_client_end"));
Assert.That(metric.Dimensions["name"], Is.EqualTo("TestHttpService"));
Assert.That(metric.Dimensions["method"], Is.EqualTo("GET"));
Assert.That(metric.Dimensions["path"], Is.EqualTo("/passthrough"));
Assert.That(metric.Dimensions["statusCode"], Is.EqualTo(200));
}
}
}
| 30.709677 | 119 | 0.636555 | [
"MIT"
] | concilify/stackage-http-nuget | package/Stackage.Http.Tests/MetricsScenarios/get_request_from_service_with_no_base_address.cs | 2,856 | C# |
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.ResponseCompression;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System.Linq;
namespace blazor_intro.Server
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddRazorPages();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseWebAssemblyDebugging();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseBlazorFrameworkFiles();
app.UseStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapControllers();
endpoints.MapFallbackToFile("index.html");
});
}
}
}
| 32.55 | 143 | 0.62212 | [
"MIT"
] | theilgaz/blazor-sandbox | src/blazor-intro/blazor-intro/Server/Startup.cs | 1,953 | C# |
using RegularAPINET6.Models;
using System;
using System.Collections.Generic;
namespace RegularAPINET6.Repositories.Interfaces;
public interface IPersonRepository
{
void Create(Person person);
#nullable enable
Person? GetPersonById(Guid id);
#nullable disable
List<Person> GetAllPersons();
void Update(Person person);
void Delete(Guid id);
}
| 22.6875 | 49 | 0.768595 | [
"Apache-2.0"
] | pmortari/MinimalAPIsSandbox | RegularAPINET6/Repositories/Interfaces/IPersonRepository.cs | 365 | C# |
namespace VoiceSystem.Web.Controllers
{
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security;
using VoiceSystem.Web.ViewModels.Manage;
[Authorize]
public class ManageController : BaseController
{
// Used for XSRF protection when adding external logins
private const string XsrfKey = "XsrfId";
private ApplicationSignInManager signInManager;
private ApplicationUserManager userManager;
public ManageController()
{
}
public ManageController(ApplicationUserManager userManager, ApplicationSignInManager signInManager)
{
this.UserManager = userManager;
this.SignInManager = signInManager;
}
public enum ManageMessageId
{
AddPhoneSuccess,
ChangePasswordSuccess,
SetTwoFactorSuccess,
SetPasswordSuccess,
RemoveLoginSuccess,
RemovePhoneSuccess,
Error
}
public ApplicationSignInManager SignInManager
{
get
{
return this.signInManager ?? this.HttpContext.GetOwinContext().Get<ApplicationSignInManager>();
}
private set
{
this.signInManager = value;
}
}
public ApplicationUserManager UserManager
{
get
{
return this.userManager ?? this.HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
}
private set
{
this.userManager = value;
}
}
private IAuthenticationManager AuthenticationManager => this.HttpContext.GetOwinContext().Authentication;
// GET: /Manage/Index
public async Task<ActionResult> Index(ManageMessageId? message)
{
this.ViewBag.StatusMessage = message == ManageMessageId.ChangePasswordSuccess
? "Your password has been changed."
: message == ManageMessageId.SetPasswordSuccess
? "Your password has been set."
: message == ManageMessageId.SetTwoFactorSuccess
? "Your two-factor authentication provider has been set."
: message == ManageMessageId.Error
? "An error has occurred."
: message == ManageMessageId.AddPhoneSuccess
? "Your phone number was added."
: message == ManageMessageId.RemovePhoneSuccess
? "Your phone number was removed."
: string.Empty;
var userId = this.User.Identity.GetUserId();
var model = new IndexViewModel
{
HasPassword = this.HasPassword(),
PhoneNumber = await this.UserManager.GetPhoneNumberAsync(userId),
TwoFactor = await this.UserManager.GetTwoFactorEnabledAsync(userId),
Logins = await this.UserManager.GetLoginsAsync(userId),
BrowserRemembered =
await
this.AuthenticationManager.TwoFactorBrowserRememberedAsync(userId)
};
return this.View(model);
}
// POST: /Manage/RemoveLogin
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> RemoveLogin(string loginProvider, string providerKey)
{
ManageMessageId? message;
var result =
await
this.UserManager.RemoveLoginAsync(
this.User.Identity.GetUserId(),
new UserLoginInfo(loginProvider, providerKey));
if (result.Succeeded)
{
var user = await this.UserManager.FindByIdAsync(this.User.Identity.GetUserId());
if (user != null)
{
await this.SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
}
message = ManageMessageId.RemoveLoginSuccess;
}
else
{
message = ManageMessageId.Error;
}
return this.RedirectToAction("ManageLogins", new { Message = message });
}
// GET: /Manage/AddPhoneNumber
public ActionResult AddPhoneNumber()
{
return this.View();
}
// POST: /Manage/AddPhoneNumber
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> AddPhoneNumber(AddPhoneNumberViewModel model)
{
if (!this.ModelState.IsValid)
{
return this.View(model);
}
// Generate the token and send it
var code =
await this.UserManager.GenerateChangePhoneNumberTokenAsync(this.User.Identity.GetUserId(), model.Number);
if (this.UserManager.SmsService != null)
{
var message = new IdentityMessage
{
Destination = model.Number,
Body = "Your security code is: " + code
};
await this.UserManager.SmsService.SendAsync(message);
}
return this.RedirectToAction("VerifyPhoneNumber", new { PhoneNumber = model.Number });
}
// POST: /Manage/EnableTwoFactorAuthentication
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> EnableTwoFactorAuthentication()
{
await this.UserManager.SetTwoFactorEnabledAsync(this.User.Identity.GetUserId(), true);
var user = await this.UserManager.FindByIdAsync(this.User.Identity.GetUserId());
if (user != null)
{
await this.SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
}
return this.RedirectToAction("Index", "Manage");
}
// POST: /Manage/DisableTwoFactorAuthentication
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> DisableTwoFactorAuthentication()
{
await this.UserManager.SetTwoFactorEnabledAsync(this.User.Identity.GetUserId(), false);
var user = await this.UserManager.FindByIdAsync(this.User.Identity.GetUserId());
if (user != null)
{
await this.SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
}
return this.RedirectToAction("Index", "Manage");
}
// GET: /Manage/VerifyPhoneNumber
public async Task<ActionResult> VerifyPhoneNumber(string phoneNumber)
{
var code =
await this.UserManager.GenerateChangePhoneNumberTokenAsync(this.User.Identity.GetUserId(), phoneNumber);
// Send an SMS through the SMS provider to verify the phone number
return phoneNumber == null
? this.View("Error")
: this.View(new VerifyPhoneNumberViewModel { PhoneNumber = phoneNumber });
}
// POST: /Manage/VerifyPhoneNumber
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> VerifyPhoneNumber(VerifyPhoneNumberViewModel model)
{
if (!this.ModelState.IsValid)
{
return this.View(model);
}
var result =
await
this.UserManager.ChangePhoneNumberAsync(this.User.Identity.GetUserId(), model.PhoneNumber, model.Code);
if (result.Succeeded)
{
var user = await this.UserManager.FindByIdAsync(this.User.Identity.GetUserId());
if (user != null)
{
await this.SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
}
return this.RedirectToAction("Index", new { Message = ManageMessageId.AddPhoneSuccess });
}
// If we got this far, something failed, redisplay form
this.ModelState.AddModelError(string.Empty, "Failed to verify phone");
return this.View(model);
}
// GET: /Manage/RemovePhoneNumber
public async Task<ActionResult> RemovePhoneNumber()
{
var result = await this.UserManager.SetPhoneNumberAsync(this.User.Identity.GetUserId(), null);
if (!result.Succeeded)
{
return this.RedirectToAction("Index", new { Message = ManageMessageId.Error });
}
var user = await this.UserManager.FindByIdAsync(this.User.Identity.GetUserId());
if (user != null)
{
await this.SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
}
return this.RedirectToAction("Index", new { Message = ManageMessageId.RemovePhoneSuccess });
}
// GET: /Manage/ChangePassword
public ActionResult ChangePassword()
{
return this.View();
}
// POST: /Manage/ChangePassword
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ChangePassword(ChangePasswordViewModel model)
{
if (!this.ModelState.IsValid)
{
return this.View(model);
}
var result =
await
this.UserManager.ChangePasswordAsync(
this.User.Identity.GetUserId(),
model.OldPassword,
model.NewPassword);
if (result.Succeeded)
{
var user = await this.UserManager.FindByIdAsync(this.User.Identity.GetUserId());
if (user != null)
{
await this.SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
}
return this.RedirectToAction("Index", new { Message = ManageMessageId.ChangePasswordSuccess });
}
this.AddErrors(result);
return this.View(model);
}
// GET: /Manage/SetPassword
public ActionResult SetPassword()
{
return this.View();
}
// POST: /Manage/SetPassword
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> SetPassword(SetPasswordViewModel model)
{
if (this.ModelState.IsValid)
{
var result = await this.UserManager.AddPasswordAsync(this.User.Identity.GetUserId(), model.NewPassword);
if (result.Succeeded)
{
var user = await this.UserManager.FindByIdAsync(this.User.Identity.GetUserId());
if (user != null)
{
await this.SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
}
return this.RedirectToAction("Index", new { Message = ManageMessageId.SetPasswordSuccess });
}
this.AddErrors(result);
}
// If we got this far, something failed, redisplay form
return this.View(model);
}
// GET: /Manage/ManageLogins
public async Task<ActionResult> ManageLogins(ManageMessageId? message)
{
this.ViewBag.StatusMessage = message == ManageMessageId.RemoveLoginSuccess
? "The external login was removed."
: message == ManageMessageId.Error
? "An error has occurred."
: string.Empty;
var user = await this.UserManager.FindByIdAsync(this.User.Identity.GetUserId());
if (user == null)
{
return this.View("Error");
}
var userLogins = await this.UserManager.GetLoginsAsync(this.User.Identity.GetUserId());
var otherLogins =
this.AuthenticationManager.GetExternalAuthenticationTypes()
.Where(auth => userLogins.All(ul => auth.AuthenticationType != ul.LoginProvider))
.ToList();
this.ViewBag.ShowRemoveButton = user.PasswordHash != null || userLogins.Count > 1;
return this.View(new ManageLoginsViewModel { CurrentLogins = userLogins, OtherLogins = otherLogins });
}
// POST: /Manage/LinkLogin
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult LinkLogin(string provider)
{
// Request a redirect to the external login provider to link a login for the current user
return new AccountController.ChallengeResult(
provider,
this.Url.Action("LinkLoginCallback", "Manage"),
this.User.Identity.GetUserId());
}
// GET: /Manage/LinkLoginCallback
public async Task<ActionResult> LinkLoginCallback()
{
var loginInfo =
await this.AuthenticationManager.GetExternalLoginInfoAsync(XsrfKey, this.User.Identity.GetUserId());
if (loginInfo == null)
{
return this.RedirectToAction("ManageLogins", new { Message = ManageMessageId.Error });
}
var result = await this.UserManager.AddLoginAsync(this.User.Identity.GetUserId(), loginInfo.Login);
return result.Succeeded
? this.RedirectToAction("ManageLogins")
: this.RedirectToAction("ManageLogins", new { Message = ManageMessageId.Error });
}
protected override void Dispose(bool disposing)
{
if (disposing && this.userManager != null)
{
this.userManager.Dispose();
this.userManager = null;
}
base.Dispose(disposing);
}
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
this.ModelState.AddModelError(string.Empty, error);
}
}
private bool HasPassword()
{
var user = this.UserManager.FindById(this.User.Identity.GetUserId());
return user?.PasswordHash != null;
}
private bool HasPhoneNumber()
{
var user = this.UserManager.FindById(this.User.Identity.GetUserId());
return user?.PhoneNumber != null;
}
}
}
| 38.002427 | 121 | 0.535671 | [
"MIT"
] | todorm85/TelerikAcademy | Courses/Software Technologies/AspNet MVC/Exam/Web/HikingPlanAndRescue.Web/Controllers/ManageController.cs | 15,659 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
namespace Azure.Messaging.ServiceBus
{
/// <summary>
/// The set of well-known reasons for an Service Bus operation failure that was the cause of an exception.
/// </summary>
public enum ServiceBusFailureReason
{
/// <summary>
/// The exception was the result of a general error within the client library.
/// </summary>
GeneralError,
/// <summary>
/// A Service Bus resource cannot be found by the Service Bus service.
/// </summary>
MessagingEntityNotFound,
/// <summary>
/// The lock on the message is lost. Callers should call attempt to receive and process the message again.
/// </summary>
MessageLockLost,
/// <summary>
/// The requested message was not found.
/// </summary>
MessageNotFound,
/// <summary>
/// A message is larger than the maximum size allowed for its transport.
/// </summary>
MessageSizeExceeded,
/// <summary>
/// The Messaging Entity is disabled. Enable the entity again using Portal.
/// </summary>
MessagingEntityDisabled,
/// <summary>
/// The quota applied to an Service Bus resource has been exceeded while interacting with the Azure Service Bus service.
/// </summary>
QuotaExceeded,
/// <summary>
/// The Azure Service Bus service reports that it is busy in response to a client request to perform an operation.
/// </summary>
ServiceBusy,
/// <summary>
/// An operation or other request timed out while interacting with the Azure Service Bus service.
/// </summary>
ServiceTimeout,
/// <summary>
/// There was a general communications error encountered when interacting with the Azure Service Bus service.
/// </summary>
ServiceCommunicationProblem,
/// <summary>
/// The requested session cannot be locked.
/// </summary>
SessionCannotBeLocked,
/// <summary>
/// The lock on the session has expired. Callers should request the session again.
/// </summary>
SessionLockLost,
/// <summary>
/// An entity with the same name exists under the same namespace.
/// </summary>
MessagingEntityAlreadyExists
}
}
| 32.324675 | 128 | 0.60225 | [
"MIT"
] | 0rland0Wats0n/azure-sdk-for-net | sdk/servicebus/Azure.Messaging.ServiceBus/src/Primitives/ServiceBusFailureReason.cs | 2,491 | C# |
using NBi.Xml.Items.Calculation.Grouping;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
namespace NBi.Xml.Items.Alteration.Summarization
{
public class SummarizeXml : AlterationXml
{
[XmlElement(Type = typeof(SumXml), ElementName = "sum"),
XmlElement(Type = typeof(MinXml), ElementName = "min"),
XmlElement(Type = typeof(MaxXml), ElementName = "max"),
XmlElement(Type = typeof(AverageXml), ElementName = "average"),
XmlElement(Type = typeof(CountRowsXml), ElementName = "count"),
XmlElement(Type = typeof(ConcatenationXml), ElementName = "concatenation"),
]
public AggregationXml Aggregation { get; set; }
[XmlElement(ElementName = "group-by")]
public GroupByXml GroupBy { get; set; }
}
}
| 33.592593 | 87 | 0.668137 | [
"Apache-2.0"
] | TheAutomatingMrLynch/NBi | NBi.Xml/Items/Alteration/Summarization/SummarizeXml.cs | 909 | C# |
// This file is subject to the MIT License as seen in the root of this folder structure (LICENSE)
using UnityEngine;
using UnityEngine.Rendering;
namespace Crest
{
/// <summary>
/// Captures waves/shape that is drawn kinematically - there is no frame-to-frame state. The gerstner
/// waves are drawn in this way. There are two special features of this particular LodData.
///
/// * A combine pass is done which combines downwards from low detail lods down into the high detail lods (see OceanScheduler).
/// * The textures from this LodData are passed to the ocean material when the surface is drawn (by OceanChunkRenderer).
/// * LodDataDynamicWaves adds its results into this LodData. The dynamic waves piggy back off the combine
/// pass and subsequent assignment to the ocean material (see OceanScheduler).
/// * The LodDataSeaFloorDepth sits on this same GameObject and borrows the camera. This could be a model for the other sim types..
/// </summary>
public class LodDataAnimatedWaves : LodData
{
public override SimType LodDataType { get { return SimType.AnimatedWaves; } }
public override SimSettingsBase CreateDefaultSettings() { return null; }
public override void UseSettings(SimSettingsBase settings) {}
// shape format. i tried RGB111110Float but error becomes visible. one option would be to use a UNORM setup.
public override RenderTextureFormat TextureFormat { get { return RenderTextureFormat.ARGBHalf; } }
public override CameraClearFlags CamClearFlags { get { return CameraClearFlags.Color; } }
public override RenderTexture DataTexture { get { return Cam.targetTexture; } }
[Tooltip("Read shape textures back to the CPU for collision purposes.")]
public bool _readbackShapeForCollision = true;
/// <summary>
/// Turn shape combine pass on/off. Debug only - idef'd out in standalone
/// </summary>
public static bool _shapeCombinePass = true;
CommandBuffer _bufCombineShapes = null;
CameraEvent _combineEvent = 0;
Camera _combineCamera = null;
Material _combineMaterial;
Material CombineMaterial { get { return _combineMaterial ?? (_combineMaterial = new Material(Shader.Find("Ocean/Shape/Combine"))); } }
protected override void Start()
{
base.Start();
_dataReadback = GetComponent<ReadbackLodData>();
}
public void HookCombinePass(Camera camera, CameraEvent onEvent)
{
_combineCamera = camera;
_combineEvent = onEvent;
if (_bufCombineShapes == null)
{
_bufCombineShapes = new CommandBuffer();
_bufCombineShapes.name = "Combine Displacements";
var cams = OceanRenderer.Instance.Builder._camsAnimWaves;
for (int L = cams.Length - 2; L >= 0; L--)
{
// accumulate shape data down the LOD chain - combine L+1 into L
var mat = OceanRenderer.Instance.Builder._lodDataAnimWaves[L].CombineMaterial;
_bufCombineShapes.Blit(cams[L + 1].targetTexture, cams[L].targetTexture, mat);
}
}
_combineCamera.AddCommandBuffer(_combineEvent, _bufCombineShapes);
}
public void UnhookCombinePass()
{
if (_bufCombineShapes != null)
{
_combineCamera.RemoveCommandBuffer(_combineEvent, _bufCombineShapes);
_bufCombineShapes = null;
}
}
#if UNITY_EDITOR
private void Update()
{
if (_dataReadback != null)
{
_dataReadback._active = _readbackShapeForCollision;
}
// shape combine pass done by last shape camera - lod 0
if (LodTransform.LodIndex == 0)
{
if (_bufCombineShapes != null && !_shapeCombinePass)
{
UnhookCombinePass();
}
else if (_bufCombineShapes == null && _shapeCombinePass)
{
HookCombinePass(_combineCamera, _combineEvent);
}
}
}
#endif
public float MaxWavelength()
{
float oceanBaseScale = OceanRenderer.Instance.transform.lossyScale.x;
float maxDiameter = 4f * oceanBaseScale * Mathf.Pow(2f, LodTransform.LodIndex);
float maxTexelSize = maxDiameter / (4f * OceanRenderer.Instance._baseVertDensity);
return 2f * maxTexelSize * OceanRenderer.Instance._minTexelsPerWave;
}
// script execution order ensures this runs after ocean has been placed
protected override void LateUpdate()
{
base.LateUpdate();
LateUpdateShapeCombinePassSettings();
}
// apply this camera's properties to the shape combine materials
void LateUpdateShapeCombinePassSettings()
{
BindResultData(0, CombineMaterial);
if (LodTransform.LodIndex > 0)
{
var ldaws = OceanRenderer.Instance.Builder._lodDataAnimWaves;
BindResultData(1, ldaws[LodTransform.LodIndex - 1].CombineMaterial);
}
}
void OnDisable()
{
UnhookCombinePass();
// free native array when component removed or destroyed
if (_dataReadback._dataNative.IsCreated)
{
_dataReadback._dataNative.Dispose();
}
}
protected override void BindData(int shapeSlot, IPropertyWrapper properties, Texture applyData, bool blendOut, ref LodTransform.RenderData renderData)
{
base.BindData(shapeSlot, properties, applyData, blendOut, ref renderData);
// need to blend out shape if this is the largest lod, and the ocean might get scaled down later (so the largest lod will disappear)
bool needToBlendOutShape = LodTransform.LodIndex == LodTransform.LodCount - 1 && OceanRenderer.Instance.ScaleCouldDecrease && blendOut;
float shapeWeight = needToBlendOutShape ? OceanRenderer.Instance.ViewerAltitudeLevelAlpha : 1f;
properties.SetVector(_paramsOceanParams[shapeSlot],
new Vector4(LodTransform._renderData._texelWidth, LodTransform._renderData._textureRes, shapeWeight, 1f / LodTransform._renderData._textureRes));
}
public bool SampleDisplacement(ref Vector3 worldPos, ref Vector3 displacement)
{
float xOffset = worldPos.x - _dataReadback._dataRenderData._posSnapped.x;
float zOffset = worldPos.z - _dataReadback._dataRenderData._posSnapped.z;
float r = _dataReadback._dataRenderData._texelWidth * _dataReadback._dataRenderData._textureRes / 2f;
if (Mathf.Abs(xOffset) >= r || Mathf.Abs(zOffset) >= r)
{
// outside of this collision data
return false;
}
var u = 0.5f + 0.5f * xOffset / r;
var v = 0.5f + 0.5f * zOffset / r;
var x = Mathf.FloorToInt(u * _dataReadback._dataRenderData._textureRes);
var y = Mathf.FloorToInt(v * _dataReadback._dataRenderData._textureRes);
var idx = 4 * (y * (int)_dataReadback._dataRenderData._textureRes + x);
displacement.x = Mathf.HalfToFloat(_dataReadback._dataNative[idx + 0]);
displacement.y = Mathf.HalfToFloat(_dataReadback._dataNative[idx + 1]);
displacement.z = Mathf.HalfToFloat(_dataReadback._dataNative[idx + 2]);
return true;
}
/// <summary>
/// Get position on ocean plane that displaces horizontally to the given position.
/// </summary>
public Vector3 GetPositionDisplacedToPosition(ref Vector3 displacedWorldPos)
{
// fixed point iteration - guess should converge to location that displaces to the target position
var guess = displacedWorldPos;
// 2 iterations was enough to get very close when chop = 1, added 2 more which should be
// sufficient for most applications. for high chop values or really stormy conditions there may
// be some error here. one could also terminate iteration based on the size of the error, this is
// worth trying but is left as future work for now.
for (int i = 0; i < 4; i++)
{
var disp = Vector3.zero;
SampleDisplacement(ref guess, ref disp);
var error = guess + disp - displacedWorldPos;
guess.x -= error.x;
guess.z -= error.z;
}
guess.y = OceanRenderer.Instance.SeaLevel;
return guess;
}
public float GetHeight(ref Vector3 worldPos)
{
var posFlatland = worldPos;
posFlatland.y = OceanRenderer.Instance.transform.position.y;
var undisplacedPos = GetPositionDisplacedToPosition(ref posFlatland);
var disp = Vector3.zero;
SampleDisplacement(ref undisplacedPos, ref disp);
return posFlatland.y + disp.y;
}
/// <summary>
/// Returns index of lod that completely covers the sample area, and contains wavelengths that repeat no more than twice across the smaller
/// spatial length. If no such lod available, returns -1. This means high frequency wavelengths are filtered out, and the lod index can
/// be used for each sample in the sample area.
/// </summary>
public static int SuggestDataLOD(Rect sampleAreaXZ)
{
return SuggestDataLOD(sampleAreaXZ, Mathf.Min(sampleAreaXZ.width, sampleAreaXZ.height));
}
public static int SuggestDataLOD(Rect sampleAreaXZ, float minSpatialLength)
{
var ldaws = OceanRenderer.Instance.Builder._lodDataAnimWaves;
for (int lod = 0; lod < ldaws.Length; lod++)
{
// shape texture needs to completely contain sample area
var ldaw = ldaws[lod];
if (ldaw.DataReadback == null) return -1;
var wdcRect = ldaw.DataReadback.DataRectXZ;
// shrink rect by 1 texel border - this is to make finite differences fit as well
wdcRect.x += ldaw.LodTransform._renderData._texelWidth; wdcRect.y += ldaw.LodTransform._renderData._texelWidth;
wdcRect.width -= 2f * ldaw.LodTransform._renderData._texelWidth; wdcRect.height -= 2f * ldaw.LodTransform._renderData._texelWidth;
if (!wdcRect.Contains(sampleAreaXZ.min) || !wdcRect.Contains(sampleAreaXZ.max))
continue;
// the smallest wavelengths should repeat no more than twice across the smaller spatial length
var minWL = ldaw.MaxWavelength() / 2f;
if (minWL < minSpatialLength / 2f)
continue;
return lod;
}
return -1;
}
ReadbackLodData _dataReadback; public ReadbackLodData DataReadback { get { return _dataReadback; } }
}
}
| 44.884921 | 161 | 0.620988 | [
"MIT"
] | TalhaCagatay/crest-oceanrender | src/unity/Assets/Crest/Scripts/LodData/LodDataAnimatedWaves.cs | 11,313 | C# |
#region License
// https://github.com/TheBerkin/Rant
//
// Copyright (c) 2017 Nicholas Fleck
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in the
// Software without restriction, including without limitation the rights to use, copy,
// modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
// OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System.Collections.Generic;
namespace Rant.Core.Utilities
{
internal static class Extensions
{
public static ulong RotL(this ulong data, int times)
{
return (data << (times % 64)) | (data >> (64 - times % 64));
}
public static ulong RotR(this ulong data, int times)
{
return (data >> (times % 64)) | (data << (64 - times % 64));
}
public static long Hash(this string input)
{
unchecked
{
long seed = 13;
foreach (char c in input)
{
seed += c * 19;
seed *= 6364136223846793005;
}
return seed;
}
}
public static void AddRange<T>(this HashSet<T> hashset, params T[] items)
{
foreach (var item in items) hashset.Add(item);
}
public static void AddRange<T>(this HashSet<T> hashset, IEnumerable<T> items)
{
foreach (var item in items) hashset.Add(item);
}
}
} | 34.606061 | 87 | 0.626095 | [
"MIT"
] | MozaicWorks/rant | Rant/Core/Utilities/Extensions.cs | 2,286 | C# |
// This file is part of Tmds.Ssh which is released under MIT.
// See file LICENSE for full license details.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using static Tmds.Ssh.Interop;
namespace Tmds.Ssh
{
public sealed partial class SshClient : IDisposable
{
enum CredentialAuthResult
{
Success,
Error,
Again,
NextCredential
}
enum AuthStep
{
Initial,
// Steps for PrivateKeyFileCredential.
IdentityFileKeyImported,
IdentityFilePubKeyAccepted
}
class AuthState
{
// Index in settings Credentials.
public int CredentialIndex;
public AuthStep Step;
public SshKeyHandle? PublicKey;
public SshKeyHandle? PrivateKey;
public void Reset()
{
PublicKey?.Dispose();
PrivateKey?.Dispose();
Step = AuthStep.Initial;
PublicKey = null;
PrivateKey = null;
}
}
static volatile List<Credential>? s_defaultCredentials;
private static List<Credential> GetDefaultCredentials()
{
if (s_defaultCredentials == null)
{
List<Credential> credentials = new();
string home = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments, Environment.SpecialFolderOption.DoNotVerify);
credentials.Add(new PrivateKeyFileCredential(Path.Combine(home, ".ssh", "id_ed25519")));
credentials.Add(new PrivateKeyFileCredential(Path.Combine(home, ".ssh", "id_ecdsa")));
credentials.Add(new PrivateKeyFileCredential(Path.Combine(home, ".ssh", "id_rsa")));
credentials.Add(new PrivateKeyFileCredential(Path.Combine(home, ".ssh", "id_dsa")));
s_defaultCredentials = credentials;
}
return s_defaultCredentials;
}
private void Authenticate()
{
Debug.Assert(Monitor.IsEntered(Gate));
var credentials = _clientSettings.Credentials;
if (credentials == null || credentials.Count == 0)
{
credentials = GetDefaultCredentials();
}
bool ignoreErrors = credentials.Count > 1;
while (true)
{
int credentialIndex = _authState.CredentialIndex;
if (credentialIndex >= credentials.Count)
{
CompleteConnectStep(new SshSessionException("Client authentication failed."));
return;
}
Credential credential = credentials[credentialIndex];
string? errorMessage = null;
CredentialAuthResult result = credential switch
{
PrivateKeyFileCredential ifc => Authenticate(ifc, ignoreErrors, out errorMessage),
_ => throw new IndexOutOfRangeException($"Unexpected credential type: {credential.GetType().FullName}")
};
if (result != CredentialAuthResult.Again)
{
_authState.Reset();
}
if (result == CredentialAuthResult.Success)
{
_state = SessionState.Connected;
CompleteConnectStep(null);
return;
}
else if (result == CredentialAuthResult.Error)
{
CompleteConnectStep(new SshSessionException(errorMessage ?? ssh_get_error(_ssh)));
return;
}
else if (result == CredentialAuthResult.NextCredential)
{
_authState.CredentialIndex = credentialIndex + 1;
}
else
{
Debug.Assert(result == CredentialAuthResult.Again);
return;
}
}
}
private CredentialAuthResult Authenticate(PrivateKeyFileCredential credential, bool ignoreErrors, out string? errorMessage)
{
errorMessage = null;
string privateKeyFile = credential.FileName;
if (_authState.Step == AuthStep.Initial)
{
Debug.Assert(_authState.PublicKey == null);
Debug.Assert(_authState.PrivateKey == null);
string publicKeyFile = $"{privateKeyFile}.pub";
int rv = ssh_pki_import_pubkey_file(publicKeyFile, out _authState.PublicKey);
if (rv == SSH_ERROR)
{
return CredentialAuthResult.NextCredential;
}
else if (rv == SSH_EOF) // File not found.
{
// TODO: Read the private key and save the public key to file
if (!ignoreErrors)
{
errorMessage = $"Failed to read public key file: {publicKeyFile}.";
return CredentialAuthResult.Error;
}
return CredentialAuthResult.NextCredential;
}
Debug.Assert(rv == SSH_OK);
_authState.Step = AuthStep.IdentityFileKeyImported;
}
if (_authState.Step == AuthStep.IdentityFileKeyImported)
{
AuthResult rv = ssh_userauth_try_publickey(_ssh, null, _authState.PublicKey!);
if (rv == AuthResult.Error)
{
return CredentialAuthResult.Error;
}
else if (rv == AuthResult.Again)
{
return CredentialAuthResult.Again;
}
else if (rv != AuthResult.Success)
{
return CredentialAuthResult.NextCredential;
}
_authState.Step = AuthStep.IdentityFilePubKeyAccepted;
}
Debug.Assert(_authState.Step == AuthStep.IdentityFilePubKeyAccepted);
if (_authState.PrivateKey == null)
{
int rv = ssh_pki_import_privkey_file(privateKeyFile, null, out _authState.PrivateKey);
if (rv == SSH_ERROR)
{
if (!ignoreErrors)
{
errorMessage = $"Failed to read private key file: {privateKeyFile}.";
return CredentialAuthResult.Error;
}
return CredentialAuthResult.NextCredential;
}
else if (rv == SSH_EOF)
{
if (!ignoreErrors)
{
errorMessage = $"Private key file is missing: {privateKeyFile}.";
return CredentialAuthResult.Error;
}
return CredentialAuthResult.NextCredential;
}
Debug.Assert(rv == SSH_OK);
}
{
AuthResult rv = ssh_userauth_publickey(_ssh, null, _authState.PrivateKey!);
if (rv == AuthResult.Success)
{
return CredentialAuthResult.Success;
}
else if (rv == AuthResult.Again)
{
return CredentialAuthResult.Again;
}
else if (rv == AuthResult.Error)
{
return CredentialAuthResult.Error;
}
return CredentialAuthResult.NextCredential;
}
}
}
} | 35.63964 | 140 | 0.51049 | [
"MIT"
] | tmds/Tmds.Ssh | src/Tmds.Ssh/SshClient.Authenticate.cs | 7,912 | C# |
////////////////////////////////////////////////////////////////////////////////
//NUnit tests for "EF Core Provider for LCPI OLE DB"
// IBProvider and Contributors. 02.12.2021.
using System;
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.Equal.Complete.NewArray1_Object.NewArray1_Object{
////////////////////////////////////////////////////////////////////////////////
using T_ARR1_E =System.Object;
using T_ARR2_E =System.Object;
using T_DATA1 =System.Int16;
using T_DATA2 =System.Int32;
using T_DATA1_U=System.Int16;
using T_DATA2_U=System.Int32;
////////////////////////////////////////////////////////////////////////////////
//class TestSet_001__fields__02__VC
public static class TestSet_001__fields__02__VC
{
private const string c_NameOf__TABLE ="TEST_MODIFY_ROW2";
private const string c_NameOf__COL_DATA1 ="COL_SMALLINT";
private const string c_NameOf__COL_DATA2 ="COL2_INTEGER";
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))
{
const T_DATA1_U c_value1=4;
const T_DATA2_U c_value2=4;
System.Int64? testID=Helper__InsertRow(db,c_value1,c_value2);
var recs=db.testTable.Where(r => (new T_ARR1_E[]{r.COL_DATA1,r.COL_DATA2} /*OP{*/ == /*}OP*/ new T_ARR2_E[]{c_value2,c_value1}) && 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
db.CheckTextOfLastExecutedCommand
(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 (").N("t",c_NameOf__COL_DATA1).T(" = 4) AND (").N("t",c_NameOf__COL_DATA2).T(" = 4) AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")"));
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))
{
const T_DATA1_U c_value1=22;
const T_DATA2_U c_value2=44;
System.Int64? testID=Helper__InsertRow(db,c_value1,c_value2);
var recs=db.testTable.Where(r => (new T_ARR1_E[]{r.COL_DATA1,r.COL_DATA2} /*OP{*/ == /*}OP*/ new T_ARR2_E[]{c_value1,c_value2}) && 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
db.CheckTextOfLastExecutedCommand
(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 (").N("t",c_NameOf__COL_DATA1).T(" = 22) AND (").N("t",c_NameOf__COL_DATA2).T(" = 44) AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")"));
Assert.AreEqual
(1,
nRecs);
}//using db
tr.Rollback();
}//using tr
}//using cn
}//Test_002
//Helper methods --------------------------------------------------------
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__02__VC
////////////////////////////////////////////////////////////////////////////////
}//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Operators.SET_001.Equal.Complete.NewArray1_Object.NewArray1_Object
| 28.467593 | 165 | 0.563669 | [
"MIT"
] | ibprovider/Lcpi.EFCore.LcpiOleDb | Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D3/Query/Operators/SET_001/Equal/Complete/NewArray1_Object/NewArray1_Object/TestSet_001__fields__02__VC.cs | 6,151 | C# |
// Copyright 2016 MaterialUI for Unity http://materialunity.com
// Please see license file for terms and conditions of use, and more information.
using UnityEngine;
using UnityEngine.UI;
namespace MaterialUI
{
/// <summary>
/// Changes the state of a ScrollRect, depending on whether its content RectTransform is over a specified height.
/// </summary>
/// <seealso cref="UnityEngine.MonoBehaviour" />
/// <seealso cref="UnityEngine.UI.ILayoutElement" />
[AddComponentMenu("MaterialUI/Vertical Scroll Layout Element", 50)]
public class VerticalScrollLayoutElement : MonoBehaviour, ILayoutElement
{
/// <summary>
/// The maximun height the content can be before the ScrollRect is activated.
/// </summary>
[SerializeField]
private float m_MaxHeight;
/// <summary>
/// The maximun height the content can be before the ScrollRect is activated.
/// Calls <see cref="RefreshLayout"/> if set.
/// </summary>
public float maxHeight
{
get { return m_MaxHeight; }
set
{
m_MaxHeight = value;
RefreshLayout();
}
}
/// <summary>
/// The content RectTransform.
/// </summary>
[SerializeField]
private RectTransform m_ContentRectTransform;
/// <summary>
/// The content RectTransform.
/// Calls <see cref="RefreshLayout"/> if set.
/// </summary>
public RectTransform contentRectTransform
{
get { return m_ContentRectTransform; }
set
{
m_ContentRectTransform = value;
RefreshLayout();
}
}
/// <summary>
/// The target ScrollRect.
/// </summary>
[SerializeField]
private ScrollRect m_ScrollRect;
/// <summary>
/// The target ScrollRect.
/// Calls <see cref="RefreshLayout"/> if set.
/// </summary>
public ScrollRect scrollRect
{
get { return m_ScrollRect; }
set
{
m_ScrollRect = value;
RefreshLayout();
}
}
/// <summary>
/// The target ScrollRect's transform.
/// </summary>
private RectTransform m_ScrollRectTransform;
/// <summary>
/// The target ScrollRect's transform.
/// Calls <see cref="RefreshLayout"/> if set.
/// </summary>
public RectTransform scrollRectTransform
{
get { return m_ScrollRectTransform; }
set
{
m_ScrollRectTransform = value;
RefreshLayout();
}
}
/// <summary>
/// The scrollbar handle image.
/// </summary>
[SerializeField]
private Image m_ScrollHandleImage;
/// <summary>
/// The scrollbar handle image.
/// Calls <see cref="RefreshLayout"/> if set.
/// </summary>
public Image scrollHandleImage
{
get { return m_ScrollHandleImage; }
set
{
m_ScrollHandleImage = value;
RefreshLayout();
}
}
/// <summary>
/// The ScrollRect movement type when scrollable.
/// </summary>
[SerializeField]
private ScrollRect.MovementType m_MovementTypeWhenScrollable;
/// <summary>
/// The ScrollRect movement type when scrollable.
/// Calls <see cref="RefreshLayout"/> if set.
/// </summary>
public ScrollRect.MovementType movementTypeWhenScrollable
{
get { return m_MovementTypeWhenScrollable; }
set
{
m_MovementTypeWhenScrollable = value;
RefreshLayout();
}
}
/// <summary>
/// Optional other Images to show if ScrollRect is scrollable.
/// </summary>
[SerializeField]
private Image[] m_ShowWhenScrollable;
/// <summary>
/// Is the ScrollRect scrollable?
/// </summary>
private bool m_ScrollEnabled;
/// <summary>
/// Is the ScrollRect scrollable?
/// </summary>
public bool scrollEnabled
{
get { return m_ScrollEnabled; }
}
/// <summary>
/// The layout height of the ScrollRect.
/// </summary>
private float m_Height;
/// <summary>
/// Calculates if the ScrollRect should be scrollable based on the content height and sets the ScrollRect height.
/// </summary>
private void RefreshLayout()
{
if (!m_ScrollRect)
{
m_ScrollRect = GetComponent<ScrollRect>();
}
if (!m_ScrollRectTransform)
{
m_ScrollRectTransform = m_ScrollRect.GetComponent<RectTransform>();
}
LayoutRebuilder.ForceRebuildLayoutImmediate(contentRectTransform);
float tempHeight = LayoutUtility.GetPreferredHeight(contentRectTransform);
if (tempHeight > m_MaxHeight)
{
m_Height = maxHeight;
m_ScrollRect.movementType = movementTypeWhenScrollable;
m_ScrollHandleImage.enabled = true;
m_ScrollEnabled = true;
for (int i = 0; i < m_ShowWhenScrollable.Length; i++)
{
m_ShowWhenScrollable[i].enabled = true;
}
}
else
{
m_Height = tempHeight;
m_ScrollRect.movementType = ScrollRect.MovementType.Clamped;
m_ScrollHandleImage.enabled = false;
m_ScrollEnabled = false;
for (int i = 0; i < m_ShowWhenScrollable.Length; i++)
{
m_ShowWhenScrollable[i].enabled = false;
}
}
m_ScrollRectTransform.sizeDelta = new Vector2(m_ScrollRectTransform.sizeDelta.x, m_Height);
}
/// <summary>
/// The minWidth, preferredWidth, and flexibleWidth values may be calculated in this callback.
/// </summary>
public void CalculateLayoutInputHorizontal() { }
/// <summary>
/// The minHeight, preferredHeight, and flexibleHeight values may be calculated in this callback.
/// </summary>
public void CalculateLayoutInputVertical()
{
RefreshLayout();
}
/// <summary>
/// The minimum width this layout element may be allocated.
/// </summary>
public float minWidth { get { return -1; } }
/// <summary>
/// The preferred width this layout element should be allocated if there is sufficient space.
/// </summary>
public float preferredWidth { get { return -1; } }
/// <summary>
/// The extra relative width this layout element should be allocated if there is additional available space.
/// </summary>
public float flexibleWidth { get { return -1; } }
/// <summary>
/// The minimum height this layout element may be allocated.
/// </summary>
public float minHeight { get { return m_Height; } }
/// <summary>
/// The preferred height this layout element should be allocated if there is sufficient space.
/// </summary>
public float preferredHeight { get { return m_Height; } }
/// <summary>
/// The extra relative height this layout element should be allocated if there is additional available space.
/// </summary>
public float flexibleHeight { get { return m_Height; } }
/// <summary>
/// The layout priority of this component.
/// </summary>
public int layoutPriority { get { return 0; } }
}
}
| 33.909836 | 122 | 0.528886 | [
"Apache-2.0"
] | Ianmaster231/tabekana | Tabekana/Assets/MaterialUI/Scripts/Common/VerticalScrollLayoutElement.cs | 8,276 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq.Expressions;
using System.Threading;
namespace Kooboo.Json.Deserialize
{
internal class DeserializeObjectJump
{
private static SpinLock _spinLock = new SpinLock();
private static readonly Dictionary<Type, Func<string, JsonDeserializeHandler, object>> JumpStringConvertDics =
new Dictionary<Type, Func<string, JsonDeserializeHandler, object>>();
private static readonly Dictionary<Type, Func<StreamReader, JsonDeserializeHandler, object>> JumpStreamConvertDics =
new Dictionary<Type, Func<StreamReader, JsonDeserializeHandler, object>>();
internal static object GetThreadSafetyJumpFunc(string json, Type t, JsonDeserializeHandler handler)
{
if (JumpStringConvertDics.TryGetValue(t, out var fc))
return fc(json, handler);
else
{
try
{
bool i = false;
_spinLock.Enter(ref i);
if (!JumpStringConvertDics.TryGetValue(t, out fc))
{
fc = GenerateJumpStringConvertFunc(t);
JumpStringConvertDics.Add(t, fc);
}
return fc(json, handler);
}
catch (Exception e)
{
throw e;
}
finally
{
_spinLock.Exit();
}
}
}
internal static object GetThreadSafetyJumpFunc(StreamReader stream, Type t, JsonDeserializeHandler handler)
{
if (JumpStreamConvertDics.TryGetValue(t, out var fc))
return fc(stream, handler);
else
{
try
{
bool i = false;
_spinLock.Enter(ref i);
if (!JumpStreamConvertDics.TryGetValue(t, out fc))
{
fc = GenerateJumpStreamConvertFunc(t);
JumpStreamConvertDics.Add(t, fc);
}
return fc(stream, handler);
}
catch (Exception e)
{
throw e;
}
finally
{
_spinLock.Exit();
}
}
}
internal static Func<string, JsonDeserializeHandler, object> GenerateJumpStringConvertFunc(Type t)
{
var genericType = typeof(ResolveProvider<>).MakeGenericType(t);
var jsonEx = Expression.Parameter(typeof(string), "json");
var handlerEx = Expression.Parameter(typeof(JsonDeserializeHandler), "handler");
var body = Expression.Convert(Expression.Call(genericType.GetMethod("Convert",System.Reflection.BindingFlags.NonPublic|System.Reflection.BindingFlags.Static,null, new Type[] { typeof(string), typeof(JsonDeserializeHandler) },null), jsonEx, handlerEx), typeof(object));
return Expression.Lambda<Func<string, JsonDeserializeHandler, object>>(body, jsonEx, handlerEx).Compile();
}
internal static Func<StreamReader, JsonDeserializeHandler, object> GenerateJumpStreamConvertFunc(Type t)
{
var genericType = typeof(ResolveProvider<>).MakeGenericType(t);
var jsonEx = Expression.Parameter(typeof(StreamReader), "reader");
var handlerEx = Expression.Parameter(typeof(JsonDeserializeHandler), "handler");
var body = Expression.Convert(Expression.Call(genericType.GetMethod("Convert", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static ,null,new Type[] { typeof(StreamReader), typeof(JsonDeserializeHandler) },null), jsonEx, handlerEx), typeof(object));
return Expression.Lambda<Func<StreamReader, JsonDeserializeHandler, object>>(body, jsonEx, handlerEx).Compile();
}
}
}
| 43.677419 | 289 | 0.576071 | [
"MIT"
] | Kooboo/Json | Kooboo.Json/Formatter/Deserializer/DeserializeObjectJump.cs | 4,064 | 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.AwsNative.KMS.Outputs
{
/// <summary>
/// A key-value pair to associate with a resource.
/// </summary>
[OutputType]
public sealed class KeyTag
{
/// <summary>
/// The key name of the tag. You can specify a value that is 1 to 128 Unicode characters in length and cannot be prefixed with aws:. You can use any of the following characters: the set of Unicode letters, digits, whitespace, _, ., /, =, +, and -.
/// </summary>
public readonly string Key;
/// <summary>
/// The value for the tag. You can specify a value that is 0 to 256 Unicode characters in length and cannot be prefixed with aws:. You can use any of the following characters: the set of Unicode letters, digits, whitespace, _, ., /, =, +, and -.
/// </summary>
public readonly string Value;
[OutputConstructor]
private KeyTag(
string key,
string value)
{
Key = key;
Value = value;
}
}
}
| 34.435897 | 255 | 0.625465 | [
"Apache-2.0"
] | AaronFriel/pulumi-aws-native | sdk/dotnet/KMS/Outputs/KeyTag.cs | 1,343 | C# |
using LuaInterface;
using System;
using UnityEngine;
public class UISpriteAnimationWrap
{
public static void Register(LuaState L)
{
L.BeginClass(typeof(UISpriteAnimation), typeof(MonoBehaviour), null);
L.RegFunction("RebuildSpriteList", new LuaCSFunction(UISpriteAnimationWrap.RebuildSpriteList));
L.RegFunction("Play", new LuaCSFunction(UISpriteAnimationWrap.Play));
L.RegFunction("Pause", new LuaCSFunction(UISpriteAnimationWrap.Pause));
L.RegFunction("ResetToBeginning", new LuaCSFunction(UISpriteAnimationWrap.ResetToBeginning));
L.RegFunction("__eq", new LuaCSFunction(UISpriteAnimationWrap.op_Equality));
L.RegFunction("__tostring", new LuaCSFunction(ToLua.op_ToString));
L.RegVar("frameIndex", new LuaCSFunction(UISpriteAnimationWrap.get_frameIndex), new LuaCSFunction(UISpriteAnimationWrap.set_frameIndex));
L.RegVar("frames", new LuaCSFunction(UISpriteAnimationWrap.get_frames), null);
L.RegVar("framesPerSecond", new LuaCSFunction(UISpriteAnimationWrap.get_framesPerSecond), new LuaCSFunction(UISpriteAnimationWrap.set_framesPerSecond));
L.RegVar("namePrefix", new LuaCSFunction(UISpriteAnimationWrap.get_namePrefix), new LuaCSFunction(UISpriteAnimationWrap.set_namePrefix));
L.RegVar("loop", new LuaCSFunction(UISpriteAnimationWrap.get_loop), new LuaCSFunction(UISpriteAnimationWrap.set_loop));
L.RegVar("isPlaying", new LuaCSFunction(UISpriteAnimationWrap.get_isPlaying), null);
L.EndClass();
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
private static int RebuildSpriteList(IntPtr L)
{
int result;
try
{
ToLua.CheckArgsCount(L, 1);
UISpriteAnimation uISpriteAnimation = (UISpriteAnimation)ToLua.CheckObject(L, 1, typeof(UISpriteAnimation));
uISpriteAnimation.RebuildSpriteList();
result = 0;
}
catch (Exception e)
{
result = LuaDLL.toluaL_exception(L, e, null);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
private static int Play(IntPtr L)
{
int result;
try
{
ToLua.CheckArgsCount(L, 1);
UISpriteAnimation uISpriteAnimation = (UISpriteAnimation)ToLua.CheckObject(L, 1, typeof(UISpriteAnimation));
uISpriteAnimation.Play();
result = 0;
}
catch (Exception e)
{
result = LuaDLL.toluaL_exception(L, e, null);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
private static int Pause(IntPtr L)
{
int result;
try
{
ToLua.CheckArgsCount(L, 1);
UISpriteAnimation uISpriteAnimation = (UISpriteAnimation)ToLua.CheckObject(L, 1, typeof(UISpriteAnimation));
uISpriteAnimation.Pause();
result = 0;
}
catch (Exception e)
{
result = LuaDLL.toluaL_exception(L, e, null);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
private static int ResetToBeginning(IntPtr L)
{
int result;
try
{
ToLua.CheckArgsCount(L, 1);
UISpriteAnimation uISpriteAnimation = (UISpriteAnimation)ToLua.CheckObject(L, 1, typeof(UISpriteAnimation));
uISpriteAnimation.ResetToBeginning();
result = 0;
}
catch (Exception e)
{
result = LuaDLL.toluaL_exception(L, e, null);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
private static int op_Equality(IntPtr L)
{
int result;
try
{
ToLua.CheckArgsCount(L, 2);
UnityEngine.Object x = (UnityEngine.Object)ToLua.ToObject(L, 1);
UnityEngine.Object y = (UnityEngine.Object)ToLua.ToObject(L, 2);
bool value = x == y;
LuaDLL.lua_pushboolean(L, value);
result = 1;
}
catch (Exception e)
{
result = LuaDLL.toluaL_exception(L, e, null);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
private static int get_frameIndex(IntPtr L)
{
object obj = null;
int result;
try
{
obj = ToLua.ToObject(L, 1);
UISpriteAnimation uISpriteAnimation = (UISpriteAnimation)obj;
int frameIndex = uISpriteAnimation.frameIndex;
LuaDLL.lua_pushinteger(L, frameIndex);
result = 1;
}
catch (Exception ex)
{
result = LuaDLL.toluaL_exception(L, ex, (obj != null) ? ex.Message : "attempt to index frameIndex on a nil value");
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
private static int get_frames(IntPtr L)
{
object obj = null;
int result;
try
{
obj = ToLua.ToObject(L, 1);
UISpriteAnimation uISpriteAnimation = (UISpriteAnimation)obj;
int frames = uISpriteAnimation.frames;
LuaDLL.lua_pushinteger(L, frames);
result = 1;
}
catch (Exception ex)
{
result = LuaDLL.toluaL_exception(L, ex, (obj != null) ? ex.Message : "attempt to index frames on a nil value");
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
private static int get_framesPerSecond(IntPtr L)
{
object obj = null;
int result;
try
{
obj = ToLua.ToObject(L, 1);
UISpriteAnimation uISpriteAnimation = (UISpriteAnimation)obj;
int framesPerSecond = uISpriteAnimation.framesPerSecond;
LuaDLL.lua_pushinteger(L, framesPerSecond);
result = 1;
}
catch (Exception ex)
{
result = LuaDLL.toluaL_exception(L, ex, (obj != null) ? ex.Message : "attempt to index framesPerSecond on a nil value");
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
private static int get_namePrefix(IntPtr L)
{
object obj = null;
int result;
try
{
obj = ToLua.ToObject(L, 1);
UISpriteAnimation uISpriteAnimation = (UISpriteAnimation)obj;
string namePrefix = uISpriteAnimation.namePrefix;
LuaDLL.lua_pushstring(L, namePrefix);
result = 1;
}
catch (Exception ex)
{
result = LuaDLL.toluaL_exception(L, ex, (obj != null) ? ex.Message : "attempt to index namePrefix on a nil value");
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
private static int get_loop(IntPtr L)
{
object obj = null;
int result;
try
{
obj = ToLua.ToObject(L, 1);
UISpriteAnimation uISpriteAnimation = (UISpriteAnimation)obj;
bool loop = uISpriteAnimation.loop;
LuaDLL.lua_pushboolean(L, loop);
result = 1;
}
catch (Exception ex)
{
result = LuaDLL.toluaL_exception(L, ex, (obj != null) ? ex.Message : "attempt to index loop on a nil value");
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
private static int get_isPlaying(IntPtr L)
{
object obj = null;
int result;
try
{
obj = ToLua.ToObject(L, 1);
UISpriteAnimation uISpriteAnimation = (UISpriteAnimation)obj;
bool isPlaying = uISpriteAnimation.isPlaying;
LuaDLL.lua_pushboolean(L, isPlaying);
result = 1;
}
catch (Exception ex)
{
result = LuaDLL.toluaL_exception(L, ex, (obj != null) ? ex.Message : "attempt to index isPlaying on a nil value");
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
private static int set_frameIndex(IntPtr L)
{
object obj = null;
int result;
try
{
obj = ToLua.ToObject(L, 1);
UISpriteAnimation uISpriteAnimation = (UISpriteAnimation)obj;
int frameIndex = (int)LuaDLL.luaL_checknumber(L, 2);
uISpriteAnimation.frameIndex = frameIndex;
result = 0;
}
catch (Exception ex)
{
result = LuaDLL.toluaL_exception(L, ex, (obj != null) ? ex.Message : "attempt to index frameIndex on a nil value");
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
private static int set_framesPerSecond(IntPtr L)
{
object obj = null;
int result;
try
{
obj = ToLua.ToObject(L, 1);
UISpriteAnimation uISpriteAnimation = (UISpriteAnimation)obj;
int framesPerSecond = (int)LuaDLL.luaL_checknumber(L, 2);
uISpriteAnimation.framesPerSecond = framesPerSecond;
result = 0;
}
catch (Exception ex)
{
result = LuaDLL.toluaL_exception(L, ex, (obj != null) ? ex.Message : "attempt to index framesPerSecond on a nil value");
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
private static int set_namePrefix(IntPtr L)
{
object obj = null;
int result;
try
{
obj = ToLua.ToObject(L, 1);
UISpriteAnimation uISpriteAnimation = (UISpriteAnimation)obj;
string namePrefix = ToLua.CheckString(L, 2);
uISpriteAnimation.namePrefix = namePrefix;
result = 0;
}
catch (Exception ex)
{
result = LuaDLL.toluaL_exception(L, ex, (obj != null) ? ex.Message : "attempt to index namePrefix on a nil value");
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
private static int set_loop(IntPtr L)
{
object obj = null;
int result;
try
{
obj = ToLua.ToObject(L, 1);
UISpriteAnimation uISpriteAnimation = (UISpriteAnimation)obj;
bool loop = LuaDLL.luaL_checkboolean(L, 2);
uISpriteAnimation.loop = loop;
result = 0;
}
catch (Exception ex)
{
result = LuaDLL.toluaL_exception(L, ex, (obj != null) ? ex.Message : "attempt to index loop on a nil value");
}
return result;
}
}
| 27.504732 | 154 | 0.71694 | [
"MIT"
] | moto2002/kaituo_src | src/UISpriteAnimationWrap.cs | 8,719 | C# |
using System;
using System.Collections.Generic;
using DataBuddy;
namespace Graffiti.Core
{
public class TagWeightCloud
{
public static TagWeightCollection FetchTags(int minWeight, int maxItems)
{
TagWeightCollection twc = ZCache.Get<TagWeightCollection>("TagCloud:" + minWeight + "|" + maxItems);
if (twc == null)
{
Query q = TagWeight.CreateQuery();
if (minWeight > 0)
q.AndWhere(TagWeight.Columns.Weight, minWeight, Comparison.GreaterOrEquals);
if (maxItems > 0)
q.Top = maxItems.ToString();
//q.OrderByAsc(TagWeight.Columns.Weight);
q.Orders.Add(DataService.Provider.QuoteName(TagWeight.Columns.Weight.Alias) + " DESC");
twc = TagWeightCollection.FetchByQuery(q);
double mean = 0;
double std = StdDev(twc, out mean);
foreach (TagWeight tag in twc)
{
tag.FontFactor = NormalizeWeight(tag.Count, mean, std);
tag.FontSize = _fontSizes[tag.FontFactor - 1];
}
twc.Sort(delegate(TagWeight t1, TagWeight t2) {return Comparer<string>.Default.Compare(t1.Name, t2.Name); });
ZCache.InsertCache("TagCloud:" + minWeight + "|" + maxItems,twc,120);
}
return twc;
}
static string[] _fontSizes = new string[] { "xx-small", "x-small", "small", "medium", "large", "x-large", "xx-large" };
private static int NormalizeWeight(double weight, double mean, double stdDev)
{
double factor = (weight - mean);
if (factor != 0 && stdDev != 0) factor /= stdDev;
return (factor > 2) ? 7 :
(factor > 1) ? 6 :
(factor > 0.5) ? 5 :
(factor > -0.5) ? 4 :
(factor > -1) ? 3 :
(factor > -2) ? 2 :
1;
}
private static double Mean(TagWeightCollection twc)
{
double sum = 0;
int count = 0;
foreach (TagWeight item in twc)
{
sum += item.Weight;
count++;
}
return sum / count;
}
private static double StdDev(TagWeightCollection twc, out double mean)
{
mean = Mean(twc);
double sumOfDiffSquares = 0;
int count = 0;
foreach (TagWeight item in twc)
{
double diff = (item.Weight - mean);
sumOfDiffSquares += diff * diff;
count++;
}
return Math.Sqrt(sumOfDiffSquares / count);
}
}
} | 30.107527 | 127 | 0.492143 | [
"MIT"
] | harder/GraffitiCMS | src/Graffiti.Core/Data/TagWeightCloud.cs | 2,800 | C# |
//-----------------------------------------------------------------------
// <copyright file="Dial180.cs" company="David Black">
// Copyright 2008 David Black
//
// 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>
//-----------------------------------------------------------------------
namespace Codeplex.Dashboarding
{
using System;
using System.Diagnostics.CodeAnalysis;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
/// <summary>
/// Base class for the Dial180North, South, East and West classes
/// </summary>
public abstract class Dial180 : BidirectionalDial
{
/// <summary>
/// Canvas to rotate to move the grab handle
/// </summary>
private Canvas grabHandleCanvas;
/// <summary>
/// Shape used to highlight that the mouse is in the grab area
/// </summary>
private Shape grabHighlightShape;
/// <summary>
/// The percentage value text black
/// </summary>
private TextBlock textBlock;
/// <summary>
/// Blend start for the face of the dial
/// </summary>
private GradientStop faceHighColorGradientStop;
/// <summary>
/// Blend end for the face of the dial
/// </summary>
private GradientStop faceLowColorGradientStop;
/// <summary>
/// Blend start for the face of the dial
/// </summary>
private GradientStop needleHighColorGradientStop;
/// <summary>
/// Blend end for the face of the dial
/// </summary>
private GradientStop needleLowColorGradientStop;
/// <summary>
/// Gets the shape used to highlight the grab control
/// </summary>
protected override Shape GrabHighlight => grabHighlightShape;
/// <summary>
/// Move the needle and set the needle and face colors to suite the value
/// </summary>
protected override void Animate()
{
UpdateFaceColor();
UpdateNeedleColor();
ShowHandleIfBidirectional();
if (!IsBidirectional || (IsBidirectional && !IsGrabbed))
{
SetPointerByAnimationOverSetTime(CalculatePointFromNormalisedValue(), CurrentValue, AnimationDuration);
}
else
{
SetPointerByAnimationOverSetTime(CalculatePointFromCurrentNormalisedValue(), CurrentValue, TimeSpan.Zero);
}
}
/// <summary>
/// Calculate the rotation angle from the normalized actual value
/// </summary>
/// <returns>angle in degrees to position the transform</returns>
protected abstract double CalculatePointFromNormalisedValue();
/// <summary>
/// Calculate the rotation angle from the normalized current value
/// </summary>
/// <returns>angle in degrees to position the transform</returns>
protected abstract double CalculatePointFromCurrentNormalisedValue();
/// <summary>
/// Set the defaults for our dependency properties and register the
/// grab handle
/// </summary>
protected void InitializeDial180()
{
InitialiseRefs();
SetValue(FaceTextColorProperty, Colors.White);
SetValue(ValueTextColorProperty, Colors.Black);
SetValue(FontSizeProperty, 10.0);
RegisterGrabHandle(grabHandleCanvas);
}
/// <summary>
/// Based on the rotation angle, set the normalized current value
/// </summary>
/// <param name="cv">rotation angle</param>
protected override void SetCurrentNormalizedValue(double cv)
{
cv = (cv < 0) ? 0 : cv;
cv = (cv > 180) ? 180 : cv;
CurrentNormalizedValue = cv / 180;
}
/// <summary>
/// Set our text color to that of the TextColorProperty
/// </summary>
protected override void UpdateTextColor()
{
for (var i = 0; i <= 4; i++)
{
if (ResourceRoot.FindName("_txt" + i) is TextBlock tb)
{
tb.Foreground = new SolidColorBrush(FaceTextColor);
}
}
textBlock.Foreground = new SolidColorBrush(ValueTextColor);
}
/// <summary>
/// Sets the text visibility to that of the TextVisibility property
/// </summary>
protected override void UpdateTextVisibility()
{
for (var i = 0; i <= 4; i++)
{
if (ResourceRoot.FindName("_txt" + i) is TextBlock tb)
{
tb.Visibility = FaceTextVisibility;
}
}
textBlock.Visibility = ValueTextVisibility;
}
/// <summary>
/// Updates the font style for both face and value text.
/// </summary>
protected override void UpdateFontStyle()
{
for (var i = 0; i <= 4; i++)
{
var tb = ResourceRoot.FindName("_txt" + i) as TextBlock;
CopyFontDetails(tb);
}
CopyFontDetails(textBlock);
}
/// <summary>
/// The format string for the value has changed
/// </summary>
protected override void UpdateTextFormat()
{
for (var i = 0; i <= 4; i++)
{
if (ResourceRoot.FindName("_txt" + i) is TextBlock tb && FaceTextFormat != null)
{
tb.Text = string.Format(FaceTextFormat, RealMinimum + (i * ((RealMaximum - RealMinimum) / 4)));
}
}
if (textBlock != null)
{
textBlock.Text = IsGrabbed ? FormattedCurrentValue : FormattedValue;
}
}
/// <summary>
/// Requires that the control honors all appearance setting as specified in the
/// dependency properties (at least the supported ones). No dependency property handling
/// is performed until all dependency properties are set and the control is loaded.
/// </summary>
protected override void ManifestChanges()
{
UpdateFaceColor();
UpdateNeedleColor();
UpdateTextColor();
UpdateTextFormat();
UpdateTextVisibility();
UpdateFontStyle();
}
/// <summary>
/// Sets the face color from the color range
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Color", Justification = "We support U.S. naming in a British project")]
protected override void UpdateFaceColor()
{
var c = FaceColorRange.GetColor(Value);
if (c != null)
{
faceLowColorGradientStop.Color = c.LowColor;
faceHighColorGradientStop.Color = c.HiColor;
}
}
/// <summary>
/// Sets the needle color from the color range
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Color", Justification = "We support U.S. naming in a British project")]
protected override void UpdateNeedleColor()
{
var c = NeedleColorRange.GetColor(Value);
if (c != null)
{
needleHighColorGradientStop.Color = c.HiColor;
needleLowColorGradientStop.Color = c.LowColor;
}
}
/// <summary>
/// Sets the pointer animation to execute and sets the time to animate. This allow the same
/// code to handle normal operation using the Dashboard.AnimationDuration or for dragging the
/// needle during bidirectional operation (TimeSpan.Zero)
/// </summary>
/// <param name="point">The Value normalised or current.</param>
/// <param name="value">The value.</param>
/// <param name="duration">The duration.</param>
private void SetPointerByAnimationOverSetTime(double point, double value, TimeSpan duration)
{
UpdateTextFormat();
var needle = SetFirstChildSplineDoubleKeyFrameTime(AnimateIndicatorStoryboard, point);
needle.KeyTime = KeyTime.FromTimeSpan(duration);
Start(AnimateIndicatorStoryboard);
var handle = SetFirstChildSplineDoubleKeyFrameTime(AnimateGrabHandleStoryboard, point);
handle.KeyTime = KeyTime.FromTimeSpan(duration);
Start(AnimateGrabHandleStoryboard);
}
/// <summary>
/// Shows the grab handle if this control is bidirectional
/// </summary>
private void ShowHandleIfBidirectional()
{
var val = IsBidirectional ? Visibility.Visible : Visibility.Collapsed;
grabHandleCanvas.Visibility = val;
grabHandleCanvas.Visibility = val;
}
/// <summary>
/// Initialize references to controls we expect to find in the child
/// </summary>
private void InitialiseRefs()
{
grabHandleCanvas = ResourceRoot.FindName("_grabHandle") as Canvas;
grabHighlightShape = ResourceRoot.FindName("_grabHighlight") as Shape;
textBlock = ResourceRoot.FindName("_text") as TextBlock;
faceHighColorGradientStop = ResourceRoot.FindName("_colourRangeStart") as GradientStop;
faceLowColorGradientStop = ResourceRoot.FindName("_colourRangeEnd") as GradientStop;
needleHighColorGradientStop = ResourceRoot.FindName("_needleHighColour") as GradientStop;
needleLowColorGradientStop = ResourceRoot.FindName("_needleLowColour") as GradientStop;
}
}
} | 38.510638 | 176 | 0.563444 | [
"Apache-2.0"
] | LGM-AdrianHum/Dashboarding | Codeplex.Dashboarding/Dial180.cs | 10,862 | C# |
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Abp.Auditing;
using Abp.Authorization.Users;
using Abp.Extensions;
using NoteApp.Validation;
namespace NoteApp.Authorization.Accounts.Dto
{
public class RegisterInput : IValidatableObject
{
[Required]
[StringLength(AbpUserBase.MaxNameLength)]
public string Name { get; set; }
[Required]
[StringLength(AbpUserBase.MaxSurnameLength)]
public string Surname { get; set; }
[Required]
[StringLength(AbpUserBase.MaxUserNameLength)]
public string UserName { get; set; }
[Required]
[EmailAddress]
[StringLength(AbpUserBase.MaxEmailAddressLength)]
public string EmailAddress { get; set; }
[Required]
[StringLength(AbpUserBase.MaxPlainPasswordLength)]
[DisableAuditing]
public string Password { get; set; }
[DisableAuditing]
public string CaptchaResponse { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (!UserName.IsNullOrEmpty())
{
if (!UserName.Equals(EmailAddress) && ValidationHelper.IsEmail(UserName))
{
yield return new ValidationResult("Username cannot be an email address unless it's the same as your email address!");
}
}
}
}
}
| 29.897959 | 137 | 0.636177 | [
"MIT"
] | nitinreddy3/NoteApp | aspnet-core/src/NoteApp.Application/Authorization/Accounts/Dto/RegisterInput.cs | 1,467 | C# |
/*******************************************************************\
* Copyright (c) 2016 Shinobytes, Gothenburg, Sweden. *
* Any usage of the content of this file, in part or whole, without *
* a written agreement from Shinobytes, will be considered a *
* violation against international copyright law. *
\*******************************************************************/
using System.Collections.Generic;
namespace Shinobytes.Core.Net
{
public interface INetworkConnectionManager : IList<INetworkConnection>
{
}
} | 38.4 | 74 | 0.515625 | [
"MIT"
] | Shinobytes/core | Shinobytes.Core/Net/INetworkConnectionManager.cs | 576 | C# |
namespace ShakaDB.Client.Protocol
{
using System.IO;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
public static class Transmitter
{
private const uint Magic = 0x4B414D41;
private const int HeaderSize = 8;
public static async Task<byte[]> Receive(Stream input)
{
var header = await ReadBuffer(input, HeaderSize);
using (var r = new BinaryReader(new MemoryStream(header), Encoding.ASCII, true))
{
var magic = r.ReadUInt32();
var totalSize = r.ReadInt32();
if (magic != Magic)
{
throw new ShakaDbException("Received malformed packet");
}
return await ReadBuffer(input, totalSize - HeaderSize);
}
}
public static async Task Send(byte[] payload, Stream output)
{
var header = new MemoryStream();
using (var w = new BinaryWriter(header))
{
w.Write(Magic);
w.Write(payload.Length + HeaderSize);
await output.WriteAsync(header.ToArray(), 0, HeaderSize);
await output.WriteAsync(payload, 0, payload.Length);
}
}
private static async Task<byte[]> ReadBuffer(Stream stream, int count)
{
var result = new byte[count];
var read = 0;
var totalRead = 0;
while (count != totalRead && (read = await stream.ReadAsync(result, totalRead, count - totalRead)) > 0)
{
totalRead += read;
}
if (totalRead != count)
{
throw new ShakaDbException("Failed to read all bytes");
}
return result;
}
}
} | 29.015625 | 115 | 0.518578 | [
"MIT"
] | burzyk/Apollo.Data | clients/dotnet/ShakaDB.Client/Protocol/Transmitter.cs | 1,859 | C# |
using API.Foundation;
using API.Foundation.Contexts;
using API.Todo.Middleware;
using Autofac;
using Autofac.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Newtonsoft.Json.Serialization;
namespace API.Todo
{
public class Startup
{
public Startup(IWebHostEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
this.Configuration = builder.Build();
}
public IConfiguration Configuration { get; }
public static ILifetimeScope AutofacContainer { get; private set; }
public (string connectionString, string migrationAssemblyName) ConnectionAndMigration()
{
var connectionStringName = "SQLSERVERCONNECTIONS";
var connectionString = Configuration.GetConnectionString(connectionStringName);
var migrationAssemblyName = typeof(Startup).Assembly.FullName;
return (connectionString, migrationAssemblyName);
}
public void ConfigureContainer(ContainerBuilder builder)
{
var (connectionString, migrationAssemblyName) = ConnectionAndMigration();
builder.RegisterModule(new ApiModule(connectionString, migrationAssemblyName));
builder.RegisterModule(new FoundationModule(connectionString, migrationAssemblyName));
}
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
var (connectionString, migrationAssemblyName) = ConnectionAndMigration();
services.AddDbContext<TodoContext>(options =>
options.UseSqlServer(connectionString, m
=> m.MigrationsAssembly(migrationAssemblyName)));
services.Configure<DataAccessLayer.Cassandra>(Configuration.GetSection("Cassandra"));
services.AddControllers().AddNewtonsoftJson(opt => {
opt.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
AutofacContainer = app.ApplicationServices.GetAutofacRoot();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseMiddleware<RequestMiddleware>();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
| 38.785714 | 106 | 0.662063 | [
"MIT"
] | ismail5g/TodoApps | Todo/Startup.cs | 3,258 | C# |
namespace MicroSistema
{
partial class frmMdiPrincipal
{
/// <summary>
/// Variável de designer necessária.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Limpar os recursos que estão sendo usados.
/// </summary>
/// <param name="disposing">true se for necessário descartar os recursos gerenciados; caso contrário, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Código gerado pelo Windows Form Designer
/// <summary>
/// Método necessário para suporte ao Designer - não modifique
/// o conteúdo deste método com o editor de código.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmMdiPrincipal));
this.menuStrip = new System.Windows.Forms.MenuStrip();
this.fileMenu = new System.Windows.Forms.ToolStripMenuItem();
this.newToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.openToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator();
this.saveToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.saveAsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator4 = new System.Windows.Forms.ToolStripSeparator();
this.printToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.printPreviewToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.printSetupToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator5 = new System.Windows.Forms.ToolStripSeparator();
this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.editMenu = new System.Windows.Forms.ToolStripMenuItem();
this.undoToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.redoToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator6 = new System.Windows.Forms.ToolStripSeparator();
this.cutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.copyToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.pasteToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator7 = new System.Windows.Forms.ToolStripSeparator();
this.selectAllToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.viewMenu = new System.Windows.Forms.ToolStripMenuItem();
this.toolBarToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.statusBarToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolsMenu = new System.Windows.Forms.ToolStripMenuItem();
this.optionsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.windowsMenu = new System.Windows.Forms.ToolStripMenuItem();
this.newWindowToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.cascadeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.tileVerticalToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.tileHorizontalToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.closeAllToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.arrangeIconsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.helpMenu = new System.Windows.Forms.ToolStripMenuItem();
this.contentsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.indexToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.searchToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator8 = new System.Windows.Forms.ToolStripSeparator();
this.aboutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.logisticaToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.fornecedoresToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.gerenciamentoToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.usuariosToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStrip = new System.Windows.Forms.ToolStrip();
this.newToolStripButton = new System.Windows.Forms.ToolStripButton();
this.openToolStripButton = new System.Windows.Forms.ToolStripButton();
this.saveToolStripButton = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.printToolStripButton = new System.Windows.Forms.ToolStripButton();
this.printPreviewToolStripButton = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator();
this.helpToolStripButton = new System.Windows.Forms.ToolStripButton();
this.statusStrip = new System.Windows.Forms.StatusStrip();
this.toolStripStatusLabel = new System.Windows.Forms.ToolStripStatusLabel();
this.toolTip = new System.Windows.Forms.ToolTip(this.components);
this.sairToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.menuStrip.SuspendLayout();
this.toolStrip.SuspendLayout();
this.statusStrip.SuspendLayout();
this.SuspendLayout();
//
// menuStrip
//
this.menuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.fileMenu,
this.editMenu,
this.viewMenu,
this.toolsMenu,
this.windowsMenu,
this.helpMenu,
this.logisticaToolStripMenuItem,
this.gerenciamentoToolStripMenuItem,
this.sairToolStripMenuItem});
this.menuStrip.Location = new System.Drawing.Point(0, 0);
this.menuStrip.MdiWindowListItem = this.windowsMenu;
this.menuStrip.Name = "menuStrip";
this.menuStrip.Padding = new System.Windows.Forms.Padding(7, 3, 0, 3);
this.menuStrip.Size = new System.Drawing.Size(902, 25);
this.menuStrip.TabIndex = 0;
this.menuStrip.Text = "MenuStrip";
//
// fileMenu
//
this.fileMenu.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.newToolStripMenuItem,
this.openToolStripMenuItem,
this.toolStripSeparator3,
this.saveToolStripMenuItem,
this.saveAsToolStripMenuItem,
this.toolStripSeparator4,
this.printToolStripMenuItem,
this.printPreviewToolStripMenuItem,
this.printSetupToolStripMenuItem,
this.toolStripSeparator5,
this.exitToolStripMenuItem});
this.fileMenu.ImageTransparentColor = System.Drawing.SystemColors.ActiveBorder;
this.fileMenu.Name = "fileMenu";
this.fileMenu.Size = new System.Drawing.Size(61, 19);
this.fileMenu.Text = "&Arquivo";
this.fileMenu.Visible = false;
//
// newToolStripMenuItem
//
this.newToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("newToolStripMenuItem.Image")));
this.newToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Black;
this.newToolStripMenuItem.Name = "newToolStripMenuItem";
this.newToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.N)));
this.newToolStripMenuItem.Size = new System.Drawing.Size(188, 22);
this.newToolStripMenuItem.Text = "&Nova";
this.newToolStripMenuItem.Click += new System.EventHandler(this.ShowNewForm);
//
// openToolStripMenuItem
//
this.openToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("openToolStripMenuItem.Image")));
this.openToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Black;
this.openToolStripMenuItem.Name = "openToolStripMenuItem";
this.openToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.O)));
this.openToolStripMenuItem.Size = new System.Drawing.Size(188, 22);
this.openToolStripMenuItem.Text = "&Abrir";
this.openToolStripMenuItem.Click += new System.EventHandler(this.OpenFile);
//
// toolStripSeparator3
//
this.toolStripSeparator3.Name = "toolStripSeparator3";
this.toolStripSeparator3.Size = new System.Drawing.Size(185, 6);
//
// saveToolStripMenuItem
//
this.saveToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("saveToolStripMenuItem.Image")));
this.saveToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Black;
this.saveToolStripMenuItem.Name = "saveToolStripMenuItem";
this.saveToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.S)));
this.saveToolStripMenuItem.Size = new System.Drawing.Size(188, 22);
this.saveToolStripMenuItem.Text = "&Salvar";
//
// saveAsToolStripMenuItem
//
this.saveAsToolStripMenuItem.Name = "saveAsToolStripMenuItem";
this.saveAsToolStripMenuItem.Size = new System.Drawing.Size(188, 22);
this.saveAsToolStripMenuItem.Text = "Salvar &como";
this.saveAsToolStripMenuItem.Click += new System.EventHandler(this.SaveAsToolStripMenuItem_Click);
//
// toolStripSeparator4
//
this.toolStripSeparator4.Name = "toolStripSeparator4";
this.toolStripSeparator4.Size = new System.Drawing.Size(185, 6);
//
// printToolStripMenuItem
//
this.printToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("printToolStripMenuItem.Image")));
this.printToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Black;
this.printToolStripMenuItem.Name = "printToolStripMenuItem";
this.printToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.P)));
this.printToolStripMenuItem.Size = new System.Drawing.Size(188, 22);
this.printToolStripMenuItem.Text = "Im&primir";
//
// printPreviewToolStripMenuItem
//
this.printPreviewToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("printPreviewToolStripMenuItem.Image")));
this.printPreviewToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Black;
this.printPreviewToolStripMenuItem.Name = "printPreviewToolStripMenuItem";
this.printPreviewToolStripMenuItem.Size = new System.Drawing.Size(188, 22);
this.printPreviewToolStripMenuItem.Text = "&Vizualizar impressão";
//
// printSetupToolStripMenuItem
//
this.printSetupToolStripMenuItem.Name = "printSetupToolStripMenuItem";
this.printSetupToolStripMenuItem.Size = new System.Drawing.Size(188, 22);
this.printSetupToolStripMenuItem.Text = "Configurar Impressão";
//
// toolStripSeparator5
//
this.toolStripSeparator5.Name = "toolStripSeparator5";
this.toolStripSeparator5.Size = new System.Drawing.Size(185, 6);
//
// exitToolStripMenuItem
//
this.exitToolStripMenuItem.Name = "exitToolStripMenuItem";
this.exitToolStripMenuItem.Size = new System.Drawing.Size(188, 22);
this.exitToolStripMenuItem.Text = "Sai&r";
this.exitToolStripMenuItem.Click += new System.EventHandler(this.ExitToolsStripMenuItem_Click);
//
// editMenu
//
this.editMenu.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.undoToolStripMenuItem,
this.redoToolStripMenuItem,
this.toolStripSeparator6,
this.cutToolStripMenuItem,
this.copyToolStripMenuItem,
this.pasteToolStripMenuItem,
this.toolStripSeparator7,
this.selectAllToolStripMenuItem});
this.editMenu.Name = "editMenu";
this.editMenu.Size = new System.Drawing.Size(49, 19);
this.editMenu.Text = "&Editar";
this.editMenu.Visible = false;
//
// undoToolStripMenuItem
//
this.undoToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("undoToolStripMenuItem.Image")));
this.undoToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Black;
this.undoToolStripMenuItem.Name = "undoToolStripMenuItem";
this.undoToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Z)));
this.undoToolStripMenuItem.Size = new System.Drawing.Size(201, 22);
this.undoToolStripMenuItem.Text = "&Desfazer";
//
// redoToolStripMenuItem
//
this.redoToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("redoToolStripMenuItem.Image")));
this.redoToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Black;
this.redoToolStripMenuItem.Name = "redoToolStripMenuItem";
this.redoToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Y)));
this.redoToolStripMenuItem.Size = new System.Drawing.Size(201, 22);
this.redoToolStripMenuItem.Text = "&Refazer";
//
// toolStripSeparator6
//
this.toolStripSeparator6.Name = "toolStripSeparator6";
this.toolStripSeparator6.Size = new System.Drawing.Size(198, 6);
//
// cutToolStripMenuItem
//
this.cutToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("cutToolStripMenuItem.Image")));
this.cutToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Black;
this.cutToolStripMenuItem.Name = "cutToolStripMenuItem";
this.cutToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.X)));
this.cutToolStripMenuItem.Size = new System.Drawing.Size(201, 22);
this.cutToolStripMenuItem.Text = "&Recortar";
this.cutToolStripMenuItem.Click += new System.EventHandler(this.CutToolStripMenuItem_Click);
//
// copyToolStripMenuItem
//
this.copyToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("copyToolStripMenuItem.Image")));
this.copyToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Black;
this.copyToolStripMenuItem.Name = "copyToolStripMenuItem";
this.copyToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.C)));
this.copyToolStripMenuItem.Size = new System.Drawing.Size(201, 22);
this.copyToolStripMenuItem.Text = "&Copiar";
this.copyToolStripMenuItem.Click += new System.EventHandler(this.CopyToolStripMenuItem_Click);
//
// pasteToolStripMenuItem
//
this.pasteToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("pasteToolStripMenuItem.Image")));
this.pasteToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Black;
this.pasteToolStripMenuItem.Name = "pasteToolStripMenuItem";
this.pasteToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.V)));
this.pasteToolStripMenuItem.Size = new System.Drawing.Size(201, 22);
this.pasteToolStripMenuItem.Text = "&Colar";
this.pasteToolStripMenuItem.Click += new System.EventHandler(this.PasteToolStripMenuItem_Click);
//
// toolStripSeparator7
//
this.toolStripSeparator7.Name = "toolStripSeparator7";
this.toolStripSeparator7.Size = new System.Drawing.Size(198, 6);
//
// selectAllToolStripMenuItem
//
this.selectAllToolStripMenuItem.Name = "selectAllToolStripMenuItem";
this.selectAllToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.A)));
this.selectAllToolStripMenuItem.Size = new System.Drawing.Size(201, 22);
this.selectAllToolStripMenuItem.Text = "Selecion&ar Tudo";
//
// viewMenu
//
this.viewMenu.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolBarToolStripMenuItem,
this.statusBarToolStripMenuItem});
this.viewMenu.Name = "viewMenu";
this.viewMenu.Size = new System.Drawing.Size(47, 19);
this.viewMenu.Text = "&Exibir";
this.viewMenu.Visible = false;
//
// toolBarToolStripMenuItem
//
this.toolBarToolStripMenuItem.Checked = true;
this.toolBarToolStripMenuItem.CheckOnClick = true;
this.toolBarToolStripMenuItem.CheckState = System.Windows.Forms.CheckState.Checked;
this.toolBarToolStripMenuItem.Name = "toolBarToolStripMenuItem";
this.toolBarToolStripMenuItem.Size = new System.Drawing.Size(185, 22);
this.toolBarToolStripMenuItem.Text = "&Barra de Ferramentas";
this.toolBarToolStripMenuItem.Click += new System.EventHandler(this.ToolBarToolStripMenuItem_Click);
//
// statusBarToolStripMenuItem
//
this.statusBarToolStripMenuItem.Checked = true;
this.statusBarToolStripMenuItem.CheckOnClick = true;
this.statusBarToolStripMenuItem.CheckState = System.Windows.Forms.CheckState.Checked;
this.statusBarToolStripMenuItem.Name = "statusBarToolStripMenuItem";
this.statusBarToolStripMenuItem.Size = new System.Drawing.Size(185, 22);
this.statusBarToolStripMenuItem.Text = "&Barra de Status";
this.statusBarToolStripMenuItem.Click += new System.EventHandler(this.StatusBarToolStripMenuItem_Click);
//
// toolsMenu
//
this.toolsMenu.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.optionsToolStripMenuItem});
this.toolsMenu.Name = "toolsMenu";
this.toolsMenu.Size = new System.Drawing.Size(84, 19);
this.toolsMenu.Text = "&Ferramentas";
this.toolsMenu.Visible = false;
//
// optionsToolStripMenuItem
//
this.optionsToolStripMenuItem.Name = "optionsToolStripMenuItem";
this.optionsToolStripMenuItem.Size = new System.Drawing.Size(114, 22);
this.optionsToolStripMenuItem.Text = "&Opções";
//
// windowsMenu
//
this.windowsMenu.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.newWindowToolStripMenuItem,
this.cascadeToolStripMenuItem,
this.tileVerticalToolStripMenuItem,
this.tileHorizontalToolStripMenuItem,
this.closeAllToolStripMenuItem,
this.arrangeIconsToolStripMenuItem});
this.windowsMenu.Name = "windowsMenu";
this.windowsMenu.Size = new System.Drawing.Size(56, 19);
this.windowsMenu.Text = "&Janelas";
this.windowsMenu.Visible = false;
//
// newWindowToolStripMenuItem
//
this.newWindowToolStripMenuItem.Name = "newWindowToolStripMenuItem";
this.newWindowToolStripMenuItem.Size = new System.Drawing.Size(179, 22);
this.newWindowToolStripMenuItem.Text = "&Nova Janela";
this.newWindowToolStripMenuItem.Click += new System.EventHandler(this.ShowNewForm);
//
// cascadeToolStripMenuItem
//
this.cascadeToolStripMenuItem.Name = "cascadeToolStripMenuItem";
this.cascadeToolStripMenuItem.Size = new System.Drawing.Size(179, 22);
this.cascadeToolStripMenuItem.Text = "&Cascata";
this.cascadeToolStripMenuItem.Click += new System.EventHandler(this.CascadeToolStripMenuItem_Click);
//
// tileVerticalToolStripMenuItem
//
this.tileVerticalToolStripMenuItem.Name = "tileVerticalToolStripMenuItem";
this.tileVerticalToolStripMenuItem.Size = new System.Drawing.Size(179, 22);
this.tileVerticalToolStripMenuItem.Text = "Empilhar &Vertical";
this.tileVerticalToolStripMenuItem.Click += new System.EventHandler(this.TileVerticalToolStripMenuItem_Click);
//
// tileHorizontalToolStripMenuItem
//
this.tileHorizontalToolStripMenuItem.Name = "tileHorizontalToolStripMenuItem";
this.tileHorizontalToolStripMenuItem.Size = new System.Drawing.Size(179, 22);
this.tileHorizontalToolStripMenuItem.Text = "Empilhar &Horizontal";
this.tileHorizontalToolStripMenuItem.Click += new System.EventHandler(this.TileHorizontalToolStripMenuItem_Click);
//
// closeAllToolStripMenuItem
//
this.closeAllToolStripMenuItem.Name = "closeAllToolStripMenuItem";
this.closeAllToolStripMenuItem.Size = new System.Drawing.Size(179, 22);
this.closeAllToolStripMenuItem.Text = "Fec&har todos";
this.closeAllToolStripMenuItem.Click += new System.EventHandler(this.CloseAllToolStripMenuItem_Click);
//
// arrangeIconsToolStripMenuItem
//
this.arrangeIconsToolStripMenuItem.Name = "arrangeIconsToolStripMenuItem";
this.arrangeIconsToolStripMenuItem.Size = new System.Drawing.Size(179, 22);
this.arrangeIconsToolStripMenuItem.Text = "&Organizar Ícones";
this.arrangeIconsToolStripMenuItem.Click += new System.EventHandler(this.ArrangeIconsToolStripMenuItem_Click);
//
// helpMenu
//
this.helpMenu.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.contentsToolStripMenuItem,
this.indexToolStripMenuItem,
this.searchToolStripMenuItem,
this.toolStripSeparator8,
this.aboutToolStripMenuItem});
this.helpMenu.Name = "helpMenu";
this.helpMenu.Size = new System.Drawing.Size(50, 19);
this.helpMenu.Text = "&Ajuda";
this.helpMenu.Visible = false;
//
// contentsToolStripMenuItem
//
this.contentsToolStripMenuItem.Name = "contentsToolStripMenuItem";
this.contentsToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.F1)));
this.contentsToolStripMenuItem.Size = new System.Drawing.Size(173, 22);
this.contentsToolStripMenuItem.Text = "&Conteúdo";
//
// indexToolStripMenuItem
//
this.indexToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("indexToolStripMenuItem.Image")));
this.indexToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Black;
this.indexToolStripMenuItem.Name = "indexToolStripMenuItem";
this.indexToolStripMenuItem.Size = new System.Drawing.Size(173, 22);
this.indexToolStripMenuItem.Text = "&Índice";
//
// searchToolStripMenuItem
//
this.searchToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("searchToolStripMenuItem.Image")));
this.searchToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Black;
this.searchToolStripMenuItem.Name = "searchToolStripMenuItem";
this.searchToolStripMenuItem.Size = new System.Drawing.Size(173, 22);
this.searchToolStripMenuItem.Text = "&Procurar";
//
// toolStripSeparator8
//
this.toolStripSeparator8.Name = "toolStripSeparator8";
this.toolStripSeparator8.Size = new System.Drawing.Size(170, 6);
//
// aboutToolStripMenuItem
//
this.aboutToolStripMenuItem.Name = "aboutToolStripMenuItem";
this.aboutToolStripMenuItem.Size = new System.Drawing.Size(173, 22);
this.aboutToolStripMenuItem.Text = "&Sobre ... ...";
//
// logisticaToolStripMenuItem
//
this.logisticaToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.fornecedoresToolStripMenuItem});
this.logisticaToolStripMenuItem.Name = "logisticaToolStripMenuItem";
this.logisticaToolStripMenuItem.Size = new System.Drawing.Size(66, 19);
this.logisticaToolStripMenuItem.Text = "Logística";
//
// fornecedoresToolStripMenuItem
//
this.fornecedoresToolStripMenuItem.Name = "fornecedoresToolStripMenuItem";
this.fornecedoresToolStripMenuItem.Size = new System.Drawing.Size(145, 22);
this.fornecedoresToolStripMenuItem.Text = "Fornecedores";
//
// gerenciamentoToolStripMenuItem
//
this.gerenciamentoToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.usuariosToolStripMenuItem});
this.gerenciamentoToolStripMenuItem.Name = "gerenciamentoToolStripMenuItem";
this.gerenciamentoToolStripMenuItem.Size = new System.Drawing.Size(100, 19);
this.gerenciamentoToolStripMenuItem.Text = "Gerenciamento";
//
// usuariosToolStripMenuItem
//
this.usuariosToolStripMenuItem.Name = "usuariosToolStripMenuItem";
this.usuariosToolStripMenuItem.Size = new System.Drawing.Size(119, 22);
this.usuariosToolStripMenuItem.Text = "Usuários";
this.usuariosToolStripMenuItem.Click += new System.EventHandler(this.usuariosToolStripMenuItem_Click);
//
// toolStrip
//
this.toolStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.newToolStripButton,
this.openToolStripButton,
this.saveToolStripButton,
this.toolStripSeparator1,
this.printToolStripButton,
this.printPreviewToolStripButton,
this.toolStripSeparator2,
this.helpToolStripButton});
this.toolStrip.Location = new System.Drawing.Point(0, 25);
this.toolStrip.Name = "toolStrip";
this.toolStrip.Size = new System.Drawing.Size(902, 25);
this.toolStrip.TabIndex = 1;
this.toolStrip.Text = "ToolStrip";
this.toolStrip.Visible = false;
//
// newToolStripButton
//
this.newToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.newToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("newToolStripButton.Image")));
this.newToolStripButton.ImageTransparentColor = System.Drawing.Color.Black;
this.newToolStripButton.Name = "newToolStripButton";
this.newToolStripButton.Size = new System.Drawing.Size(23, 22);
this.newToolStripButton.Text = "Novo";
this.newToolStripButton.Click += new System.EventHandler(this.ShowNewForm);
//
// openToolStripButton
//
this.openToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.openToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("openToolStripButton.Image")));
this.openToolStripButton.ImageTransparentColor = System.Drawing.Color.Black;
this.openToolStripButton.Name = "openToolStripButton";
this.openToolStripButton.Size = new System.Drawing.Size(23, 22);
this.openToolStripButton.Text = "Abrir";
this.openToolStripButton.Click += new System.EventHandler(this.OpenFile);
//
// saveToolStripButton
//
this.saveToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.saveToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("saveToolStripButton.Image")));
this.saveToolStripButton.ImageTransparentColor = System.Drawing.Color.Black;
this.saveToolStripButton.Name = "saveToolStripButton";
this.saveToolStripButton.Size = new System.Drawing.Size(23, 22);
this.saveToolStripButton.Text = "Salvar";
//
// toolStripSeparator1
//
this.toolStripSeparator1.Name = "toolStripSeparator1";
this.toolStripSeparator1.Size = new System.Drawing.Size(6, 25);
//
// printToolStripButton
//
this.printToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.printToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("printToolStripButton.Image")));
this.printToolStripButton.ImageTransparentColor = System.Drawing.Color.Black;
this.printToolStripButton.Name = "printToolStripButton";
this.printToolStripButton.Size = new System.Drawing.Size(23, 22);
this.printToolStripButton.Text = "Imprimir";
//
// printPreviewToolStripButton
//
this.printPreviewToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.printPreviewToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("printPreviewToolStripButton.Image")));
this.printPreviewToolStripButton.ImageTransparentColor = System.Drawing.Color.Black;
this.printPreviewToolStripButton.Name = "printPreviewToolStripButton";
this.printPreviewToolStripButton.Size = new System.Drawing.Size(23, 22);
this.printPreviewToolStripButton.Text = "Vizualizer Impressão";
//
// toolStripSeparator2
//
this.toolStripSeparator2.Name = "toolStripSeparator2";
this.toolStripSeparator2.Size = new System.Drawing.Size(6, 25);
//
// helpToolStripButton
//
this.helpToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.helpToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("helpToolStripButton.Image")));
this.helpToolStripButton.ImageTransparentColor = System.Drawing.Color.Black;
this.helpToolStripButton.Name = "helpToolStripButton";
this.helpToolStripButton.Size = new System.Drawing.Size(23, 22);
this.helpToolStripButton.Text = "Ajuda";
//
// statusStrip
//
this.statusStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolStripStatusLabel});
this.statusStrip.Location = new System.Drawing.Point(0, 497);
this.statusStrip.Name = "statusStrip";
this.statusStrip.Padding = new System.Windows.Forms.Padding(1, 0, 16, 0);
this.statusStrip.Size = new System.Drawing.Size(902, 22);
this.statusStrip.TabIndex = 2;
this.statusStrip.Text = "StatusStrip";
//
// toolStripStatusLabel
//
this.toolStripStatusLabel.Name = "toolStripStatusLabel";
this.toolStripStatusLabel.Size = new System.Drawing.Size(39, 17);
this.toolStripStatusLabel.Text = "Status";
//
// sairToolStripMenuItem
//
this.sairToolStripMenuItem.Name = "sairToolStripMenuItem";
this.sairToolStripMenuItem.Size = new System.Drawing.Size(38, 19);
this.sairToolStripMenuItem.Text = "Sair";
this.sairToolStripMenuItem.Click += new System.EventHandler(this.sairToolStripMenuItem_Click);
//
// frmMdiPrincipal
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 17F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(902, 519);
this.Controls.Add(this.statusStrip);
this.Controls.Add(this.toolStrip);
this.Controls.Add(this.menuStrip);
this.Font = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.IsMdiContainer = true;
this.MainMenuStrip = this.menuStrip;
this.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.Name = "frmMdiPrincipal";
this.Text = "Micro Sistema";
this.Load += new System.EventHandler(this.frmMdiPrincipal_Load);
this.menuStrip.ResumeLayout(false);
this.menuStrip.PerformLayout();
this.toolStrip.ResumeLayout(false);
this.toolStrip.PerformLayout();
this.statusStrip.ResumeLayout(false);
this.statusStrip.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.MenuStrip menuStrip;
private System.Windows.Forms.ToolStrip toolStrip;
private System.Windows.Forms.StatusStrip statusStrip;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator1;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator2;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator3;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator4;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator5;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator6;
private System.Windows.Forms.ToolStripMenuItem printSetupToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator7;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator8;
private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel;
private System.Windows.Forms.ToolStripMenuItem aboutToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem tileHorizontalToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem fileMenu;
private System.Windows.Forms.ToolStripMenuItem newToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem openToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem saveToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem saveAsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem printToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem printPreviewToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem editMenu;
private System.Windows.Forms.ToolStripMenuItem undoToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem redoToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem cutToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem copyToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem pasteToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem selectAllToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem viewMenu;
private System.Windows.Forms.ToolStripMenuItem toolBarToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem statusBarToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem toolsMenu;
private System.Windows.Forms.ToolStripMenuItem optionsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem windowsMenu;
private System.Windows.Forms.ToolStripMenuItem newWindowToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem cascadeToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem tileVerticalToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem closeAllToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem arrangeIconsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem helpMenu;
private System.Windows.Forms.ToolStripMenuItem contentsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem indexToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem searchToolStripMenuItem;
private System.Windows.Forms.ToolStripButton newToolStripButton;
private System.Windows.Forms.ToolStripButton openToolStripButton;
private System.Windows.Forms.ToolStripButton saveToolStripButton;
private System.Windows.Forms.ToolStripButton printToolStripButton;
private System.Windows.Forms.ToolStripButton printPreviewToolStripButton;
private System.Windows.Forms.ToolStripButton helpToolStripButton;
private System.Windows.Forms.ToolTip toolTip;
private System.Windows.Forms.ToolStripMenuItem logisticaToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem fornecedoresToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem gerenciamentoToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem usuariosToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem sairToolStripMenuItem;
}
}
| 59.324405 | 156 | 0.666056 | [
"MIT"
] | AntonioZanini/MicroSistema | MicroSistema/frmMdiPrincipal.Designer.cs | 39,890 | C# |
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Forms;
using System;
using System.Linq.Expressions;
namespace Plk.Blazor.DragDrop.Demo.Data
{
public class TextField : Field
{
public string Value { get; set; }
public override RenderFragment RenderFieldEdit()
{
return builder =>
{
builder.OpenComponent<InputText>(0);
builder.AddAttribute(1, "Value", Value);
builder.AddAttribute(2, "ValueChanged", EventCallback.Factory.Create(this.ParentComponent, (string val) => Value = val));
Expression<Func<string>> valExpr = () => Value;
builder.AddAttribute(3, "ValueExpression", valExpr);
builder.CloseComponent();
};
}
}
}
| 25.9375 | 137 | 0.598795 | [
"MIT"
] | rdm1234/blazor-dragdrop | Plk.Blazor.DragDrop.Demo/Data/TextField.cs | 832 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.