content stringlengths 23 1.05M |
|---|
using System;
namespace RadLine
{
public sealed class AutoCompleteCommand : LineEditorCommand
{
private const string Position = nameof(Position);
private const string Index = nameof(Index);
private readonly AutoComplete _kind;
public AutoCompleteCommand(AutoComplete kind)
{
_kind = kind;
}
public override void Execute(LineEditorContext context)
{
var completion = context.GetService<ITextCompletion>();
if (completion == null)
{
return;
}
var originalPosition = context.Buffer.Position;
// Get the start position of the word
var start = context.Buffer.Position;
if (context.Buffer.IsAtCharacter)
{
context.Buffer.MoveToBeginningOfWord();
start = context.Buffer.Position;
}
else if (context.Buffer.IsAtEndOfWord)
{
context.Buffer.MoveToPreviousWord();
start = context.Buffer.Position;
}
// Get the end position of the word.
var end = context.Buffer.Position;
if (context.Buffer.IsAtCharacter)
{
context.Buffer.MoveToEndOfWord();
end = context.Buffer.Position;
}
// Not the same start position as last time?
if (context.GetState(Position, () => 0) != start)
{
// Reset
var startIndex = _kind == AutoComplete.Next ? 0 : -1;
context.SetState(Index, startIndex);
}
// Get the prefix and word
var prefix = context.Buffer.Content.Substring(0, start);
var word = context.Buffer.Content.Substring(start, end - start);
var suffix = context.Buffer.Content.Substring(end, context.Buffer.Content.Length - end);
// Get the completions
if (!completion.TryGetCompletions(prefix, word, suffix, out var completions))
{
context.Buffer.Move(originalPosition);
return;
}
// Get the index to insert
var index = GetSuggestionIndex(context, word, completions);
if (index == -1)
{
context.Buffer.Move(originalPosition);
return;
}
// Remove the current word
if (start != end)
{
context.Buffer.Clear(start, end - start);
context.Buffer.Move(start);
}
// Insert the completion
context.Buffer.Insert(completions[index]);
// Move to the end of the word
context.Buffer.MoveToEndOfWord();
// Increase the completion index
context.SetState(Position, start);
context.SetState(Index, _kind == AutoComplete.Next ? ++index : --index);
}
private int GetSuggestionIndex(LineEditorContext context, string word, string[] completions)
{
if (completions is null)
{
throw new ArgumentNullException(nameof(completions));
}
if (!string.IsNullOrWhiteSpace(word))
{
// Try find an exact match
var index = 0;
foreach (var completion in completions)
{
if (completion.Equals(word, StringComparison.Ordinal))
{
var newIndex = _kind == AutoComplete.Next ? index + 1 : index - 1;
return newIndex.WrapAround(0, completions.Length - 1);
}
index++;
}
// Try find a partial match
index = 0;
foreach (var completion in completions)
{
if (completion.StartsWith(word, StringComparison.Ordinal))
{
return index;
}
index++;
}
return -1;
}
return context.GetState(Index, () => 0).WrapAround(0, completions.Length - 1);
}
}
}
|
using System;
namespace Zw.EliteExx.Core.Config
{
public class Env
{
public string AppFolder { get; }
public Env(string appFolder)
{
this.AppFolder = appFolder;
}
}
}
|
namespace ReactiveXComponent.Serializer
{
public enum SerializationType
{
Binary = 0,
Json = 1,
Bson = 2,
Custom = 3
}
} |
using System.Collections.Generic;
namespace slack_bot_hive.Services.Filters
{
public class EventFilterBuilder : IEventFilterBuilder
{
List<IFilter> _filters = new List<IFilter>();
public EventFilterBuilder AddGroupDmFilter()
{
_filters.Add(new GroupDmFilter());
return this;
}
public EventFilterBuilder AddBotFilter()
{
_filters.Add(new BotFilter());
return this;
}
public EventFilterBuilder AddChangedFilter()
{
_filters.Add(new ChangedFilter());
return this;
}
public IEventFilter GetFilter()
{
return new EventFilter(_filters);
}
}
}
|
using Microsoft.Xna.Framework.Graphics;
namespace HxEngine.Graphics
{
public class Sprite : GameObject
{
public Texture2D Texture;
}
} |
using System.Linq;
using Quidjibo.Models;
namespace Quidjibo.Extensions
{
public static class ScheduleItemExtensions
{
public static bool EquivalentTo(this ScheduleItem item, ScheduleItem existingItem)
{
return existingItem != null && item.Name == existingItem.Name
&& item.CronExpression == existingItem.CronExpression
&& item.Queue == existingItem.Queue;
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CollectibleItem : MonoBehaviour
{
public int healthRestoration = 1;
public GameObject lightingParticles;
public GameObject burstParticles;
private SpriteRenderer _rederer;
private Collider2D _collider;
private void Awake()
{
_rederer = GetComponent<SpriteRenderer>();
_collider = GetComponent<Collider2D>();
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.CompareTag("Player")) {
// Cure Player
collision.SendMessageUpwards("AddHealth", healthRestoration);
// Disable Collider
_collider.enabled = false;
// Visual stuff
_rederer.enabled = false;
lightingParticles.SetActive(false);
burstParticles.SetActive(true);
// Destroy after some time
Destroy(gameObject, 2f);
}
}
}
|
namespace SimpleShop.App.Commands.Contracts
{
public interface ICommandParser
{
ICommand Parse(string commandName);
}
}
|
using System;
using System.CommandLine;
using System.CommandLine.Invocation;
using System.IO;
using com.tammymakesthings.circtool.lib;
namespace com.tammymakesthings.circtool.lib
{
public class Version
{
public static System.Version APP_VERSION
{
get { return (new System.Version(1, 0, 0)); }
}
public static System.DateTime APP_DATE
{
get { return new System.DateTime(2021, 05, 31); }
}
}
}
|
// Encog(tm) Artificial Intelligence Framework v2.5
// .Net Version
// http://www.heatonresearch.com/encog/
// http://code.google.com/p/encog-java/
//
// Copyright 2008-2010 by Heaton Research Inc.
//
// Released under the LGPL.
//
// This is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation; either version 2.1 of
// the License, or (at your option) any later version.
//
// This software 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this software; if not, write to the Free
// Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
// 02110-1301 USA, or see the FSF site: http://www.fsf.org.
//
// Encog and Heaton Research are Trademarks of Heaton Research, Inc.
// For information on Heaton Research trademarks, visit:
//
// http://www.heatonresearch.com/copyright.html
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Encog.Normalize.Input;
namespace Encog.Normalize.Output.Mapped
{
/// <summary>
/// An encoded output field. This allows ranges of output values to be
/// mapped to specific values.
/// </summary>
public class OutputFieldEncode : BasicOutputField
{
/// <summary>
/// The source field.
/// </summary>
private IInputField sourceField;
/// <summary>
/// The catch all value, if nothing matches, then use this value.
/// </summary>
private double catchAll;
/// <summary>
/// The ranges.
/// </summary>
private IList<MappedRange> ranges = new List<MappedRange>();
/// <summary>
/// Construct an encoded field.
/// </summary>
/// <param name="sourceField">The field that this is based on.</param>
public OutputFieldEncode(IInputField sourceField)
{
this.sourceField = sourceField;
}
/// <summary>
/// Add a ranged mapped to a value.
/// </summary>
/// <param name="low">The low value for the range.</param>
/// <param name="high">The high value for the range.</param>
/// <param name="value">The value that the field should produce for this range.</param>
public void addRange(double low, double high, double value)
{
MappedRange range = new MappedRange(low, high, value);
this.ranges.Add(range);
}
/// <summary>
/// Calculate the value for this field.
/// </summary>
/// <param name="subfield">Not used.</param>
/// <returns>Return the value for the range the input falls within, or return
/// the catchall if nothing matches.</returns>
public override double Calculate(int subfield)
{
foreach (MappedRange range in this.ranges)
{
if (range.InRange(this.sourceField.CurrentValue))
{
return range.Value;
}
}
return this.catchAll;
}
/// <summary>
/// The source field.
/// </summary>
public IInputField SourceField
{
get
{
return this.sourceField;
}
}
/// <summary>
/// Return 1, no subfield supported.
/// </summary>
public override int SubfieldCount
{
get
{
return 1;
}
}
/// <summary>
/// Not needed for this sort of output field.
/// </summary>
public override void RowInit()
{
}
/// <summary>
/// The catch all value that is to be returned if none
/// of the ranges match.
/// </summary>
public double CatchAll
{
get
{
return this.catchAll;
}
set
{
this.catchAll = value;
}
}
}
}
|
namespace MediatorUploader.Domain
{
public interface IAppContext
{
string MapDataPath(string path);
};
}
|
using System;
using System.Collections;
using Server;
namespace Server.Engines.PartySystem
{
public class DeclineTimer : Timer
{
private Mobile m_Mobile, m_Leader;
private static Hashtable m_Table = new Hashtable();
public static void Start( Mobile m, Mobile leader )
{
DeclineTimer t = (DeclineTimer)m_Table[m];
if ( t != null )
t.Stop();
m_Table[m] = t = new DeclineTimer( m, leader );
t.Start();
}
private DeclineTimer( Mobile m, Mobile leader ) : base( TimeSpan.FromSeconds( 30.0 ) )
{
m_Mobile = m;
m_Leader = leader;
}
protected override void OnTick()
{
m_Table.Remove( m_Mobile );
if ( m_Mobile.Party == m_Leader && PartyCommands.Handler != null )
PartyCommands.Handler.OnDecline( m_Mobile, m_Leader );
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TeachingPlatformApp.Validations
{
public class AngleValidationRule : IValidationRule<float>
{
public string ValidationMessage { get; set; } = "角度不在范围内";
public bool Check(float value)
{
if (value <= Up && value >= Down)
return true;
return false;
}
public float Up { get; set; }
public float Down { get; set; }
public AngleValidationRule(float up, float down)
{
Up = up;
Down = down;
}
}
}
|
using FluentAssertions;
using Xunit;
namespace Dgt.Minesweeper.Engine
{
public class InvalidLocationExceptionTests
{
[Fact]
public void Ctor_Should_InitialiseLocationWhenLocationIsPassed()
{
// Arrange
var location = Location.Parse("C3");
// Act
var sut = new InvalidLocationException(location, 5);
// Assert
sut.Location.Should().Be(location);
}
[Fact]
public void Ctor_Should_InitialiseMaximumColumnNameWhenNumberOfColumnsIsPassed()
{
// Arrange, Act
var sut = new InvalidLocationException(Location.Parse("E5"), 3, 7);
// Assert
sut.MaximumColumnName.Should().Be(new ColumnName("C"));
}
[Fact]
public void Ctor_Should_InitialiseMaximumRowIndexWhenNumberOfRowsIsPassed()
{
// Arrange, Act
var sut = new InvalidLocationException(Location.Parse("E5"), 7, 3);
// Assert
sut.MaximumRowIndex.Should().Be(3);
}
[Fact]
public void Ctor_Should_InitialiseMaximumColumnNameAndMaximumRowIndexWhenNumberOfColumnsAndRowsIsPassed()
{
// Arrange, Act
var sut = new InvalidLocationException(Location.Parse("H8"), 5);
// Assert
sut.MaximumColumnName.Should().Be(new ColumnName("E"));
sut.MaximumRowIndex.Should().Be(5);
}
[Fact]
public void Ctor_Should_IncludeColumnInformationInMessageWhenColumnIsOutOfBounds()
{
// Arrange, Act
var sut = new InvalidLocationException(Location.Parse("H8"), 5, 10);
// Assert
sut.Message.Should().Contain("The column is out of bounds.");
sut.Message.Should().Contain("The column must be between \"A\" and \"E\", but found \"H\".");
}
[Fact]
public void Ctor_Should_IncludeRowInformationInMessageWhenRowIsOutOfBounds()
{
// Arrange, Act
var sut = new InvalidLocationException(Location.Parse("H8"), 10, 5);
// Assert
sut.Message.Should().Contain("The row is out of bounds.");
sut.Message.Should().Contain("The row must be between 1 and 5, but found 8.");
}
[Fact]
public void Ctor_Should_IncludeColumnAndRowInformationInMessageWhenColumnAndRowAreOutOfBounds()
{
// Arrange, Act
var sut = new InvalidLocationException(Location.Parse("H8"), 5);
// Assert
sut.Message.Should().Contain("The column is out of bounds.");
sut.Message.Should().Contain("The row is out of bounds.");
}
[Fact]
public void Ctor_Should_IncludeDefaultMessage()
{
// Arrange
var sut = new InvalidLocationException(Location.Parse("H8"), 5);
// Assert
sut.Message.Should().StartWith("The Location does not exist in the Minefield.");
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text;
using Newtonsoft.Json;
namespace Modix.WebServer.Models
{
public enum UserRole
{
Member,
Staff
}
public class DiscordUser
{
public string Name { get; set; }
public ulong UserId { get; set; }
public string AvatarHash { get; set; }
public UserRole UserRole { get; set; } = UserRole.Member;
public static DiscordUser FromClaimsPrincipal(ClaimsPrincipal user)
{
if (user?.Identity?.Name == null) { return null; }
return new DiscordUser
{
Name = user.Identity.Name,
UserId = ulong.Parse(user.Claims.FirstOrDefault(d => d.Type == ClaimTypes.NameIdentifier).Value),
AvatarHash = user.Claims.FirstOrDefault(d=>d.Type == "avatarHash")?.Value ?? ""
};
}
}
}
|
using FSight.Core.Entities;
namespace FSight.Core.Specifications
{
public class ProjectsWithMembersSpecification : BaseSpecification<Project>
{
public ProjectsWithMembersSpecification(ProjectSpecParams projectParams)
: base (x =>
(string.IsNullOrEmpty(projectParams.Search) || x.Name.ToLower().Contains(projectParams.Search)))
{
AddInclude(x => x.Members);
AddOrderBy(x => x.Name);
ApplyPaging(projectParams.PageSize * (projectParams.PageIndex - 1), projectParams.PageSize);
if (!string.IsNullOrEmpty(projectParams.Search))
{
switch (projectParams.Sort)
{
case "idAsc":
AddOrderBy(x => x.Id);
break;
case "idDesc":
AddOrderByDescending(x => x.Id);
break;
default:
AddOrderBy(x => x.CreateDate);
break;
}
}
}
public ProjectsWithMembersSpecification(int id) : base (x => x.Id == id)
{
AddInclude(x => x.Members);
}
}
} |
using System;
using System.Linq;
using ZzukBot.Constants;
using ZzukBot.ExtensionMethods;
using ZzukBot.Game.Statics;
using ZzukBot.Helpers;
using ZzukBot.Mem;
namespace ZzukBot.Objects
{
/// <summary>
/// Class for the local player
/// </summary>
public class LocalPlayer : WoWUnit
{
/// <summary>
/// facing with coordinates instead of a passed unit
/// </summary>
private const float facingComparer = 0.2f;
/// <summary>
/// Let the toon jump
/// </summary>
public void Jump()
{
Lua.Instance.Execute("Jump()");
}
/// <summary>
/// Retrieves the transport we are currently on (ship, ceppelin, elevator etc.)
/// </summary>
//public WoWGameObject CurrentTransport
//{
// get
// {
// if (!ObjectManager.Instance.IsIngame) return null;
// var transportGuid = 0x00C7B608.ReadAs<UInt64>();
// if (transportGuid == 0) return null;
// var transport = ObjectManager.Instance.GameObjects.FirstOrDefault(x => x.Guid == transportGuid);
// return transport;
// }
//}
/// <summary>
/// Constructor
/// </summary>
internal LocalPlayer(ulong parGuid, IntPtr parPointer, Enums.WoWObjectTypes parType)
: base(parGuid, parPointer, parType)
{
}
/// <summary>
/// Position of the characters corpse
/// </summary>
public Location CorpsePosition => new Location(
Memory.Reader.Read<float>(Offsets.Player.CorpsePositionX),
Memory.Reader.Read<float>(Offsets.Player.CorpsePositionY),
Memory.Reader.Read<float>(Offsets.Player.CorpsePositionZ));
internal float CtmX => Memory.Reader.Read<float>(Offsets.Player.CtmX);
/// <summary>
/// Always friendly for local player
/// </summary>
public override Enums.UnitReaction Reaction => Enums.UnitReaction.Friendly;
internal float CtmY => Memory.Reader.Read<float>(Offsets.Player.CtmY);
internal float CtmZ => Memory.Reader.Read<float>(Offsets.Player.CtmZ);
/// <summary>
/// The current spell by ID we are casting (0 or spell ID)
/// </summary>
/// <value>
/// The casting.
/// </value>
public override int Casting
{
get
{
var tmpId = base.Casting;
var tmpName = Spell.Instance.GetName(tmpId);
if (tmpName == "Heroic Strike" || tmpName == "Maul")
return 0;
return tmpId;
}
}
/// <summary>
/// Current spell casted by name
/// </summary>
/// <value>
/// The name of the casting as.
/// </value>
public string CastingAsName => Spell.Instance.GetName(Casting);
/// <summary>
/// true if no click to move action is taking place
/// </summary>
/// <value>
/// </value>
public bool IsCtmIdle => CtmState == (int) PrivateEnums.CtmType.None ||
CtmState == 12;
/// <summary>
/// Characters money in copper
/// </summary>
/// <value>
/// The money.
/// </value>
public int Money => ReadRelative<int>(0x2FD0);
/// <summary>
/// Get or set the current ctm state
/// </summary>
private int CtmState
{
get
{
return
Memory.Reader.Read<int>(Offsets.Player.CtmState);
}
set { Memory.Reader.Write(Offsets.Player.CtmState, value); }
}
/// <summary>
/// Characters movement state
/// </summary>
/// <value>
/// The state of the movement.
/// </value>
public new Enums.MovementFlags MovementState => ReadRelative<Enums.MovementFlags>(Offsets.Descriptors.MovementFlags);
/// <summary>
/// Determine if the character is inside a campfire
/// </summary>
/// <value>
/// <c>true</c> if this instance is in campfire; otherwise, <c>false</c>.
/// </value>
public bool IsInCampfire
{
get
{
var playerPos = ObjectManager.Instance.Player.Position;
var tmp = ObjectManager.Instance.GameObjects
.FirstOrDefault(i => i.Name == "Campfire" && i.Position.GetDistanceTo(playerPos) <= 2.9f);
return tmp != null;
}
}
/// <summary>
/// the ID of the map we are on
/// </summary>
public uint MapId => Memory.Reader.Read<uint>(
IntPtr.Add(
Memory.Reader.Read<IntPtr>(Offsets.ObjectManager.ManagerBase), 0xCC));
///// <summary>
///// Are we in LoS with object?
///// </summary>
//internal bool InLoSWith(WoWObject parObject)
//{
// // return 1 if something is inbetween the two coordinates
// return Functions.Intersect(Position, parObject.Position) == 0;
//}
/// <summary>
/// Is our character in CC?
/// </summary>
/// <value>
/// </value>
public bool IsInCC => 0 == Memory.Reader.Read<int>(Offsets.Player.IsInCC);
private ulong ComboPointGuid { get; set; }
/// <summary>
/// Get combopoints for current mob
/// </summary>
public byte ComboPoints
{
get
{
var ptr1 = ReadRelative<IntPtr>(Offsets.Player.ComboPoints1);
var ptr2 = IntPtr.Add(ptr1, Offsets.Player.ComboPoints2);
if (ComboPointGuid == 0)
Memory.Reader.Write(ptr2, 0);
var points = Memory.Reader.Read<byte>(ptr2);
if (points == 0)
{
ComboPointGuid = TargetGuid;
return points;
}
if (ComboPointGuid != TargetGuid)
{
Memory.Reader.Write<byte>(ptr2, 0);
return 0;
}
return Memory.Reader.Read<byte>(ptr2);
}
}
/// <summary>
/// Will retrieve the corpse of the player when in range
/// </summary>
public void RetrieveCorpse()
{
Functions.RetrieveCorpse();
}
/// <summary>
/// Will release the spirit if the player is dead
/// </summary>
public void RepopMe()
{
Functions.RepopMe();
}
/// <summary>
/// Tells if our character can overpower
/// </summary>
public bool CanOverpower => ComboPoints > 0;
/// <summary>
/// Tells if the character got a pet
/// </summary>
public bool HasPet => ObjectManager.Instance.Pet != null;
/// <summary>
/// Tells if the character is eating
/// </summary>
public bool IsEating => GotAura("Food");
/// <summary>
/// Tells if the character is drinking
/// </summary>
public bool IsDrinking => GotAura("Drink");
/// <summary>
/// The characters class
/// </summary>
public Enums.ClassId Class => (Enums.ClassId) Memory.Reader.Read<byte>(Offsets.Player.Class);
/// <summary>
/// Tells if the character is stealthed
/// </summary>
public bool IsStealth
{
get
{
switch (Class)
{
case Enums.ClassId.Rogue:
case Enums.ClassId.Druid:
return (PlayerBytes & 0x02000000) == 0x02000000;
}
return false;
}
}
/// <summary>
/// The player bytes
/// </summary>
public uint PlayerBytes => GetDescriptor<uint>(0x228);
/// <summary>
/// Characters race
/// </summary>
public string Race
{
get
{
const string getUnitRace = "{0} = UnitRace('player')";
var result = Lua.Instance.ExecuteWithResult(getUnitRace);
return result[0];
}
}
/// <summary>
/// Are we in ghost form
/// </summary>
public bool InGhostForm => Memory.Reader.Read<byte>(Offsets.Player.IsGhost) == 1;
internal float ZAxis
{
set { Memory.Reader.Write(IntPtr.Add(Pointer, Offsets.Unit.PosZ), value); }
get { return ReadRelative<float>((int) IntPtr.Add(Pointer, Offsets.Unit.PosZ)); }
}
/// <summary>
/// Time until we can accept a resurrect
/// </summary>
public int TimeUntilResurrect
{
get
{
var result = Lua.Instance.ExecuteWithResult("{0} = GetCorpseRecoveryDelay()");
return Convert.ToInt32(result[0]);
}
}
/// <summary>
/// XP gained into current level
/// </summary>
public int CurrentXp => GetDescriptor<int>(Offsets.Descriptors.CurrentXp);
/// <summary>
/// XP needed for the whole level
/// </summary>
public int NextLevelXp => GetDescriptor<int>(Offsets.Descriptors.NextLevelXp);
/// <summary>
/// Zone text
/// </summary>
public string RealZoneText => 0xB4B404.PointsTo().ReadString();
/// <summary>
/// Continent text
/// </summary>
public string ContinentText => Offsets.Player.ContinentText.ReadString();
/// <summary>
/// Minimap text
/// </summary>
public string MinimapZoneText
=> Offsets.Player.MinimapZoneText.ReadString();
/// <summary>
/// Guid of the unit the Merchant Frame belongs to (can be 0)
/// </summary>
public ulong VendorGuid => 0x00BDDFA0.ReadAs<ulong>();
/// <summary>
/// Guid of the unit the Quest Frame belongs to (can be 0)
/// </summary>
public ulong QuestNpcGuid => 0x00BE0810.ReadAs<ulong>();
/// <summary>
/// Guid of the unit the Gossip Frame belongs to (can be 0)
/// </summary>
public ulong GossipNpcGuid => 0x00BC3F58.ReadAs<ulong>();
/// <summary>
/// Guid of the unit our character is looting right now
/// </summary>
public ulong CurrentLootGuid => (Pointer + 0x1D28).ReadAs<ulong>();
internal void TurnOnSelfCast()
{
const string turnOnSelfCast = "SetCVar('autoSelfCast',1)";
Lua.Instance.Execute(turnOnSelfCast);
}
/// <summary>
/// Starts a movement
/// </summary>
/// <param name="parBits">The movement bits</param>
public void StartMovement(Enums.ControlBits parBits)
{
MainThread.Instance.Invoke(() =>
{
if (parBits != Enums.ControlBits.Nothing)
{
var movementState = MovementState;
if (parBits.HasFlag(Enums.ControlBits.Front) && movementState.HasFlag(Enums.MovementFlags.Back))
StopMovement(Enums.ControlBits.Back);
if (parBits.HasFlag(Enums.ControlBits.Back) && movementState.HasFlag(Enums.MovementFlags.Front))
StopMovement(Enums.ControlBits.Front);
if (parBits.HasFlag(Enums.ControlBits.Left) && movementState.HasFlag(Enums.MovementFlags.Right))
StopMovement(Enums.ControlBits.Right);
if (parBits.HasFlag(Enums.ControlBits.Right) && movementState.HasFlag(Enums.MovementFlags.Left))
StopMovement(Enums.ControlBits.Left);
if (parBits.HasFlag(Enums.ControlBits.StrafeLeft) && movementState.HasFlag(Enums.MovementFlags.StrafeRight))
StopMovement(Enums.ControlBits.StrafeRight);
if (parBits.HasFlag(Enums.ControlBits.StrafeRight) && movementState.HasFlag(Enums.MovementFlags.StrafeLeft))
StopMovement(Enums.ControlBits.StrafeLeft);
}
Console.WriteLine("Starting movement");
Functions.SetControlBit((int)parBits, 1, Environment.TickCount);
});
}
/// <summary>
/// Stops movement
/// </summary>
/// <param name="parBits">The movement bits</param>
public void StopMovement(Enums.ControlBits parBits)
{
Functions.SetControlBit((int) parBits, 0, Environment.TickCount);
}
/// <summary>
/// Start a ctm movement
/// </summary>
/// <param name="parPosition">The position.</param>
public void CtmTo(Location parPosition)
{
//float disX = Math.Abs(this.CtmX - parPosition.X);
//float disY = Math.Abs(this.CtmY - parPosition.Y);
//if (disX < 0.2f && disY < 0.2f) return;
Functions.Ctm(Pointer, PrivateEnums.CtmType.Move, parPosition, 0);
//SendMovementUpdate((int)Enums.MovementOpCodes.setFacing);
WoWEventHandler.Instance.TriggerCtmEvent(new WoWEventHandler.OnCtmArgs(parPosition,
(int) PrivateEnums.CtmType.Move));
}
/// <summary>
/// Stop the current ctm movement
/// </summary>
public void CtmStopMovement()
{
if (CtmState != (int) PrivateEnums.CtmType.None &&
CtmState != 12) //&& CtmState != (int)Enums.CtmType.Face)
{
var pos = ObjectManager.Instance.Player.Position;
Functions.Ctm(Pointer, PrivateEnums.CtmType.None, pos, 0);
WoWEventHandler.Instance.TriggerCtmEvent(new WoWEventHandler.OnCtmArgs(pos,
(int) PrivateEnums.CtmType.None));
}
else if ((CtmState == 12 || CtmState == (int) PrivateEnums.CtmType.None) &&
ObjectManager.Instance.Player.MovementState != 0)
{
var tmp =
Enum.GetValues(typeof(Enums.ControlBits))
.Cast<Enums.ControlBits>()
.Aggregate(Enums.ControlBits.Nothing, (current, bits) => current | bits);
ObjectManager.Instance.Player.StopMovement(tmp);
}
}
/// <summary>
/// Set CTM to idle (wont stop movement however)
/// </summary>
public void CtmSetToIdle()
{
if (CtmState != 12)
CtmState = 12;
}
/// <summary>
/// Enables CTM.
/// </summary>
public void EnableCtm()
{
const string ctmOn = "ConsoleExec('Autointeract 1')";
Lua.Instance.Execute(ctmOn);
}
/// <summary>
/// Disables CTM.
/// </summary>
public void DisableCtm()
{
const string ctmOff = "ConsoleExec('Autointeract 0')";
Lua.Instance.Execute(ctmOff);
}
/// <summary>
/// Gets the latency.
/// </summary>
/// <returns></returns>
public int GetLatency()
{
const string getLatency = "_, _, {0} = GetNetStats()";
var result = Lua.Instance.ExecuteWithResult(getLatency);
return Convert.ToInt32(result[0]);
}
/// <summary>
/// Simulate rightclick on a unit
/// </summary>
/// <param name="parUnit">The unit.</param>
public void RightClick(WoWUnit parUnit)
{
Functions.OnRightClickUnit(parUnit.Pointer, 1);
}
/// <summary>
/// Simulate rightclick on a unit
/// </summary>
/// <param name="parUnit">The unit.</param>
/// <param name="parAuto">Send shift</param>
internal void RightClick(WoWUnit parUnit, bool parAuto)
{
var type = 0;
if (parAuto) type = 1;
Functions.OnRightClickUnit(parUnit.Pointer, type);
}
/// <summary>
/// CTM face an WoWObject
/// </summary>
/// <param name="parObject">The Object.</param>
public void CtmFace(WoWObject parObject)
{
var tmp = parObject.Position;
Functions.Ctm(Pointer, PrivateEnums.CtmType.FaceTarget,
tmp, parObject.Guid);
}
/// <summary>
/// Check if we are in line of sight with an object
/// </summary>
/// <param name="parObject">The object.</param>
/// <returns></returns>
public bool InLosWith(WoWObject parObject)
{
return InLosWith(parObject.Position);
}
/// <summary>
/// Check if we are in line of sight with an object
/// </summary>
/// <param name="parPosition">The position.</param>
/// <returns></returns>
public bool InLosWith(Location parPosition)
{
var i = Functions.Intersect(Position, parPosition);
return i.R == 0 && i.X == 0 && i.Y == 0 && i.Z == 0;
}
/// <summary>
/// Set Facing towards passed object
/// </summary>
/// <param name="parObject">The object.</param>
public void Face(WoWObject parObject)
{
//Location xyz = new Location(parObject.Position.X, parObject.Position.Y, parObject.Position.Z);
//Functions.Ctm(this.Pointer, Enums.CtmType.FaceTarget, xyz, parObject.Guid);
Face(parObject.Position);
}
/// <summary>
/// Set facing towards a position
/// </summary>
/// <param name="parPosition">The position.</param>
public void Face(Location parPosition)
{
if (IsFacing(parPosition)) return;
Functions.SetFacing(IntPtr.Add(Pointer, Offsets.Player.MovementStruct), RequiredFacing(parPosition));
SendMovementUpdate((int) PrivateEnums.MovementOpCodes.setFacing);
}
/// <summary>
/// Set facing to value
/// </summary>
/// <param name="facing"></param>
public void Face(float facing)
{
Functions.SetFacing(IntPtr.Add(Pointer, Offsets.Player.MovementStruct), facing);
SendMovementUpdate((int)PrivateEnums.MovementOpCodes.setFacing);
}
/// <summary>
/// Determines if we are facing a position
/// </summary>
/// <param name="parCoordinates">The coordinates.</param>
/// <returns></returns>
public bool IsFacing(Location parCoordinates)
{
return FacingRelativeTo(parCoordinates) < facingComparer;
}
internal void SendMovementUpdate(int parOpCode)
{
Functions.SendMovementUpdate(Pointer, Environment.TickCount, parOpCode);
}
/// <summary>
/// Sets the last hardware action to the current tickcount
/// </summary>
public void AntiAfk()
{
Memory.Reader.Write(Offsets.Functions.LastHardwareAction, Environment.TickCount);
}
/// <summary>
/// Sets the target
/// </summary>
/// <param name="parObject">The object.</param>
public void SetTarget(WoWObject parObject)
{
if (parObject == null)
{
SetTarget(0);
return;
}
SetTarget(parObject.Guid);
}
/// <summary>
/// Sets the target.
/// </summary>
/// <param name="parGuid">The targets guid</param>
public void SetTarget(ulong parGuid)
{
Functions.SetTarget(parGuid);
TargetGuid = parGuid;
}
internal void RefreshSpells()
{
Spell.UpdateSpellbook();
}
#region Added Custom Class Functions
/// <summary>
/// Tells if we are to close to utilise ranged physical attacks (Auto Shot etc).
/// </summary>
/// <value>
/// <c>true</c> if we are too close.
/// </value>
public bool ToCloseForRanged => ObjectManager.Instance.Target.DistanceToPlayer < 5;
internal IntPtr SkillField => Pointer.Add(8).ReadAs<IntPtr>().Add(0xB38);
/// <summary>
/// Determines whether the mainhand weapon is temp. chanted (poisons etc)
/// </summary>
/// <returns>
/// Returns <c>true</c> if the mainhand is enchanted
/// </returns>
public bool IsMainhandEnchanted()
{
try
{
const string isMainhandEnchanted = "{0} = GetWeaponEnchantInfo()";
var result = Lua.Instance.ExecuteWithResult(isMainhandEnchanted);
return result[0] == "1";
}
catch
{
return false;
}
}
/// <summary>
/// Determines whether the offhand weapon is temp. chanted (poisons etc)
/// </summary>
/// <returns>
/// Returns <c>true</c> if the offhand is enchanted
/// </returns>
public bool IsOffhandEnchanted()
{
try
{
const string isOffhandEnchanted = "_, _, _, {0} = GetWeaponEnchantInfo()";
var result = Lua.Instance.ExecuteWithResult(isOffhandEnchanted);
return result[0] == "1";
}
catch
{
return false;
}
}
/// <summary>
/// Enchants the mainhand
/// </summary>
/// <param name="parItemName">Name of the item to use on the mainhand weapon</param>
public void EnchantMainhandItem(string parItemName)
{
const string enchantMainhand = "PickupInventoryItem(16)";
Inventory.Instance.GetItem(parItemName).Use();
Lua.Instance.Execute(enchantMainhand);
}
/// <summary>
/// Enchants the offhand
/// </summary>
/// <param name="parItemName">Name of the item to apply</param>
public void EnchantOffhandItem(string parItemName)
{
const string enchantOffhand = "PickupInventoryItem(17)";
Inventory.Instance.GetItem(parItemName).Use();
Lua.Instance.Execute(enchantOffhand);
}
/// <summary>
/// Determines whether a wand is equipped
/// </summary>
/// <returns>
/// Return <c>true</c> if a wand is equipped
/// </returns>
public bool IsWandEquipped()
{
const string checkWand = "{0} = HasWandEquipped()";
var result = Lua.Instance.ExecuteWithResult(checkWand);
return result[0].Contains("1");
}
/// <summary>
/// Tells if using aoe will engage the character with other units that arent fighting right now
/// </summary>
/// <param name="parRange">The radius around the character</param>
/// <returns>
/// Returns <c>true</c> if we can use AoE without engaging other unpulled units
/// </returns>
public bool IsAoeSafe(int parRange)
{
var mobs = ObjectManager.Instance.Npcs.
FindAll(i => (i.Reaction == Enums.UnitReaction.Hostile || i.Reaction == Enums.UnitReaction.Neutral) &&
i.DistanceToPlayer < parRange).ToList();
foreach (var mob in mobs)
if (mob.TargetGuid != Guid)
return false;
return true;
}
/// <summary>
/// Tells if a totem is spawned
/// </summary>
/// <param name="parName">Name of the totem</param>
/// <returns>
/// Returns the distance from the player to the totem or -1 if the totem isnt summoned
/// </returns>
public float IsTotemSpawned(string parName)
{
var totem = ObjectManager.Instance.Npcs.FirstOrDefault(i => i.IsTotem && i.Name.ToLower().Contains(parName.ToLower())
&&
i.SummonedBy ==
ObjectManager.Instance.Player.Guid);
if (totem != null)
return totem.DistanceToPlayer;
return -1;
}
/// <summary>
/// Eat food specified in settings if we arent already eating
/// <param name="parFoodName">Name of the food</param>
/// </summary>
public void Eat(string parFoodName)
{
if (IsEating) return;
if (Inventory.Instance.GetItemCount(parFoodName) == 0) return;
if (Wait.For("EatTimeout", 100))
Inventory.Instance.GetItem(parFoodName);
}
/// <summary>
/// Drinks drink specified in settings if we arent already drinking
/// <param name="parDrinkName">Name of the food</param>
/// </summary>
public void Drink(string parDrinkName)
{
if (IsDrinking) return;
if (Inventory.Instance.GetItemCount(parDrinkName) == 0) return;
if (Wait.For("DrinkTimeout", 100))
Inventory.Instance.GetItem(parDrinkName);
}
#endregion
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Doublelives.Api.Models.Menu
{
public class RouterViewModel
{
public List<RouterViewModel> Children { get; set; }
public string Component { get; set; }
public bool Hidden { get; set; }
public string Id { get; set; }
public MetaViewModel Meta { get; set; }
public string Name { get; set; }
public long Num { get; set; }
public string ParentId { get; set; }
public string Path { get; set; }
}
public class MetaViewModel
{
public string Icon { get; set; }
public string Title { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace StoreProcedures.PostgreModels
{
[Table("reservation")]
public partial class Reservation
{
public Reservation()
{
ReservationProcedures = new HashSet<ReservationProcedures>();
}
[Key]
[Column("id")]
public int Id { get; set; }
[Column("startdate", TypeName = "date")]
public DateTime Startdate { get; set; }
[Key]
[Column("hospital_id")]
public int HospitalId { get; set; }
[Key]
[Column("patient_id")]
[StringLength(15)]
public string PatientId { get; set; }
[ForeignKey(nameof(HospitalId))]
[InverseProperty("Reservation")]
public virtual Hospital Hospital { get; set; }
[ForeignKey(nameof(PatientId))]
[InverseProperty("Reservation")]
public virtual Patient Patient { get; set; }
public virtual ICollection<ReservationProcedures> ReservationProcedures { get; set; }
}
}
|
using Autofac.Builder;
using Autofac.Pooling.Tests.Shared;
using System;
using Xunit;
namespace Autofac.Pooling.Tests
{
public class RegistrationExtensionsTests
{
[Fact]
public void RequiresCallbackContainer()
{
// Manually create a registration builder, then call AsPooled
var regBuilder = RegistrationBuilder.ForType<PooledComponent>();
Assert.Throws<NotSupportedException>(() => regBuilder.PooledInstancePerLifetimeScope());
}
[Fact]
public void NoProvidedInstances()
{
var builder = new ContainerBuilder();
var regBuilder = builder.RegisterInstance(new PooledComponent());
Assert.Throws<NotSupportedException>(() => regBuilder.PooledInstancePerLifetimeScope());
}
[Fact]
public void OnReleaseNotCompatible()
{
var builder = new ContainerBuilder();
builder.RegisterType<PooledComponent>()
.PooledInstancePerLifetimeScope()
.OnRelease(args => { });
Assert.Throws<NotSupportedException>(() => builder.Build());
}
}
}
|
namespace MSyics.Traceyi;
internal sealed class AsyncLocalStackNode<T>
{
public AsyncLocalStackNode(T element, AsyncLocalStackNode<T> prev = null)
{
Element = element;
Prev = prev;
Count = prev is null ? 1 : prev.Count + 1;
}
public int Count { get; }
public T Element { get; }
public AsyncLocalStackNode<T> Prev { get; }
}
|
using System.Collections.Generic;
using Newtonsoft.Json;
namespace Zyborg.Vault.Ext.Token
{
public class TokenLookupResponse
{
[JsonProperty("id")]
public string Id
{ get; set; }
[JsonProperty("policies")]
public string[] Policies
{ get; set; }
[JsonProperty("path")]
public string Path
{ get; set; }
[JsonProperty("meta")]
public Dictionary<string, string> Meta
{ get; set; }
[JsonProperty("display_name")]
public string DisplayName
{ get; set; }
[JsonProperty("num_uses")]
public int NumUses
{ get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Microsoft.ServiceBus.Messaging;
using StatsdNet.Middleware;
namespace StatsdNet.Azure.EventHub.Frontend
{
public class StatsdFrontendEventProcessor : IEventProcessor
{
private readonly IMiddleware _hostedMiddeMiddleware;
private readonly Stopwatch _checkpointStopwatch = new Stopwatch();
public StatsdFrontendEventProcessor(IMiddleware hostedMiddeMiddleware)
{
_hostedMiddeMiddleware = hostedMiddeMiddleware;
}
public Task OpenAsync(PartitionContext context)
{
return Task.FromResult(false);
}
/// <summary>
/// Make a
/// </summary>
/// <param name="eventData"></param>
/// <returns></returns>
private Uri MakeUri(EventData eventData)
{
var uriString = string.Format("{0}/{1}/{2}",
eventData.SystemProperties[EventDataSystemPropertyNames.PartitionKey],
eventData.SystemProperties[EventDataSystemPropertyNames.Offset],
eventData.SystemProperties[EventDataSystemPropertyNames.Publisher]);
var builder = new UriBuilder("eventhub", uriString);
return builder.Uri;
}
public async Task ProcessEventsAsync(PartitionContext context, IEnumerable<EventData> messages)
{
foreach (var eventData in messages)
{
var packetData = Encoding.UTF8.GetString(eventData.GetBytes());
var packetContext = new PacketData(MakeUri(eventData), packetData);
await _hostedMiddeMiddleware.Invoke(packetContext);
}
await context.CheckpointAsync();
}
public Task CloseAsync(PartitionContext context, CloseReason reason)
{
if (reason == CloseReason.Shutdown)
{
return context.CheckpointAsync();
}
return Task.FromResult(false);
}
}
} |
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
namespace StrawberryShake
{
public interface IOperationSerializer
{
Task SerializeAsync(
IOperation operation,
IReadOnlyDictionary<string, object?>? extensions,
bool includeDocument,
Stream requestStream);
}
}
|
// Copyright (c) 2019 Lykke Corp.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using MarginTrading.TradingHistory.Client;
using MarginTrading.TradingHistory.Client.Common;
using MarginTrading.TradingHistory.Client.Models;
using MarginTrading.TradingHistory.Core;
using MarginTrading.TradingHistory.Core.Domain;
using MarginTrading.TradingHistory.Core.Repositories;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace MarginTrading.TradingHistory.Controllers
{
[Authorize]
[Route("api/order-blotter")]
public class OrderBlotterController : Controller, IOrderBlotterApi
{
private readonly IOrdersHistoryRepository _ordersHistoryRepository;
public OrderBlotterController(
IOrdersHistoryRepository ordersHistoryRepository)
{
_ordersHistoryRepository = ordersHistoryRepository;
}
[HttpGet]
public async Task<PaginatedResponseContract<OrderForOrderBlotterContract>> Get(
[FromQuery, Required] DateTime? relevanceTimestamp,
[FromQuery] string accountIdOrName,
[FromQuery] string assetName,
[FromQuery] string createdBy,
[FromQuery] List<OrderStatusContract> statuses,
[FromQuery] List<OrderTypeContract> orderTypes,
[FromQuery] List<OriginatorTypeContract> originatorTypes,
[FromQuery] DateTime? createdOnFrom,
[FromQuery] DateTime? createdOnTo,
[FromQuery] DateTime? modifiedOnFrom,
[FromQuery] DateTime? modifiedOnTo,
[FromQuery] int skip,
[FromQuery] int take,
[FromQuery] OrderBlotterSortingColumnContract sortingColumn,
[FromQuery] SortingOrderContract sortingOrder)
{
ApiValidationHelper.ValidatePagingParams(skip, take);
var result = await _ordersHistoryRepository.GetOrderBlotterAsync(
relevanceTimestamp.Value,
accountIdOrName,
assetName,
createdBy,
statuses?.Select(x => x.ToType<OrderStatus>()).ToList(),
orderTypes?.Select(x => x.ToType<OrderType>()).ToList(),
originatorTypes?.Select(x => x.ToType<OriginatorType>()).ToList(),
createdOnFrom,
createdOnTo,
modifiedOnFrom,
modifiedOnTo,
skip,
take,
sortingColumn.ToType<OrderBlotterSortingColumn>(),
sortingOrder.ToType<SortingOrder>());
return new PaginatedResponseContract<OrderForOrderBlotterContract>(
contents: result.Contents.Select(Convert).ToList(),
start: result.Start,
size: result.Size,
totalSize: result.TotalSize);
}
private static OrderForOrderBlotterContract Convert(IOrderHistoryForOrderBlotterWithAdditionalData history)
{
var exchangeRate = history.FxRate == 0 ? 1 : 1 / history.FxRate;
decimal? notional = null;
decimal? notionalEUR = null;
if (history.Status == OrderStatus.Executed && history.ExecutionPrice.HasValue)
{
notional = Math.Abs(history.Volume * history.ExecutionPrice.Value);
notionalEUR = notional / exchangeRate;
}
return new OrderForOrderBlotterContract
{
AccountId = history.AccountId,
AccountName = history.AccountName,
CreatedBy = history.CreatedBy,
Instrument = history.AssetName,
Quantity = history.Volume,
OrderType = history.Type.ToType<OrderTypeContract>(),
OrderStatus = history.Status.ToType<OrderStatusContract>(),
LimitStopPrice = history.ExpectedOpenPrice,
TakeProfitPrice = history.TakeProfitPrice,
StopLossPrice = history.StopLossPrice,
Price = history.ExecutionPrice,
Notional = notional,
NotionalEur = notionalEUR,
ExchangeRate = exchangeRate,
Direction = history.Direction.ToType<OrderDirectionContract>(),
Originator = history.Originator.ToType<OriginatorTypeContract>(),
OrderId = history.Id,
CreatedOn = history.CreatedTimestamp,
ModifiedOn = history.ModifiedTimestamp,
Validity = history.ValidityTime,
OrderComment = history.Comment,
Commission = history.Commission,
OnBehalfFee = history.OnBehalfFee,
Spread = history.Spread,
ForcedOpen = history.ForceOpen
};
}
}
}
|
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
//--------自制ScrollBar,用于垂直方向的ScrollRect
public class SkillScrollBar : MonoBehaviour {
//要修改的目标
public RectTransform rectTrans;
//面板上能够显示的Grid数量
public int gridNum = 4;
//单个Grid的长度
public int gridHeight = 64;
private Scrollbar scrollBar;
void Awake()
{
scrollBar = GetComponent<Scrollbar>();
}
//优化----1.当Scroll.value数值改变时调用
public void OnScrollValueChangedEvent()
{
if (rectTrans != null)
{
int maxY = (rectTrans.childCount - gridNum) * gridHeight;
rectTrans.anchoredPosition = new Vector2(0, scrollBar.value * maxY);
}
}
//当被改变职业技能面板时
public void SetScrollRect(RectTransform rectTrans)
{
this.rectTrans = rectTrans;
scrollBar.value = 0;
}
}
|
using System.Collections.Generic;
using UniRx;
using UnityEngine;
using UnityEngine.XR.MagicLeap;
using Utils;
using Utils.MagicLeaps;
namespace Prisms
{
// Move prism according to camera location until disposed
public class PrismTransformer : MonoBehaviour
{
[SerializeField]
Transform _prism;
[SerializeField]
Transform _scalePrism;
[SerializeField]
Vector2 _scaleRange;
[SerializeField]
float _scaleMagnitude;
[SerializeField]
float _distanceMagnitude;
[SerializeField]
float _prismDistance;
[SerializeField]
float _prismScale;
[SerializeField]
float _minPrismDistance;
int _spatialMeshLayerMask;
float? _spatialMeshDistance;
Transform _camera;
BehaviorSubject<bool> _acceptXAngle;
Queue<Vector3> _posBuffer; // smooth motion
MLTouchpadListener _touchpadListener;
void Awake()
{
_spatialMeshLayerMask = 1 << LayerMask.NameToLayer("Spatial Mesh");
_posBuffer = new Queue<Vector3>();
_acceptXAngle = new BehaviorSubject<bool>(false).AddTo(this);
_camera = Camera.main.transform;
}
void Start()
{
// Observe bumper and accept X-axis rotation while pressed
var bumperDowns = MLUtils.OnButtonDownAsObservable(MLInputControllerButton.Bumper).Select(_ => true);
var bumperUps = MLUtils.OnButtonUpAsObservable(MLInputControllerButton.Bumper).Select(_ => false);
bumperDowns.Merge(bumperUps).Subscribe(_acceptXAngle).AddTo(this);
MLUtils.LatestTouchpadListenerAsObservable()
.Subscribe(c => _touchpadListener = c)
.AddTo(this);
_prismScale = Mathf.Clamp(_prismScale, _scaleRange.x, _scaleRange.y);
_scalePrism.localScale = Vector3.one * _prismScale;
}
void Update()
{
// Handle scaling input
Vector2 swipeDelta = _touchpadListener?.Update() ?? Vector2.zero;
if (Mathf.Abs(swipeDelta.x) > Mathf.Abs(swipeDelta.y)) // scale
{
_prismScale += swipeDelta.x * _scaleMagnitude;
_prismScale = Mathf.Clamp(_prismScale, _scaleRange.x, _scaleRange.y);
_scalePrism.localScale = Vector3.one * _prismScale;
}
else // distance
{
// Handle touchpad swipe for prism position
_prismDistance += swipeDelta.y * _distanceMagnitude;
}
// Let spatial mesh "push" prism back to camera
var ray = new Ray(_camera.position, _camera.forward);
if (Physics.Raycast(ray, out var hit, float.MaxValue, _spatialMeshLayerMask))
{
var spatialMeshDistance = hit.distance - 0.1f;
_prismDistance = Mathf.Min(_prismDistance, spatialMeshDistance);
}
// Prevent coming up to camera too closely
_prismDistance = Mathf.Max(_prismDistance, _minPrismDistance);
// Set position via distance and append smoothing
Vector3 worldPosition = _camera.position + _camera.forward * _prismDistance;
_prism.position = EnqueuePositionBuffer(worldPosition);
// Apply rotation
_prism.LookAt(_camera);
if (!_acceptXAngle.Value)
{
_prism.SetLocalEulerAngles(x: 0);
}
}
Vector3 EnqueuePositionBuffer(Vector3 pos)
{
const int MaxBufferSize = 10;
_posBuffer.Enqueue(pos);
while (_posBuffer.Count > MaxBufferSize)
{
_posBuffer.Dequeue();
}
Vector3 sumPos = Vector3.zero;
foreach (Vector3 p in _posBuffer)
{
sumPos += p;
}
return sumPos / _posBuffer.Count;
}
public void SetActive(bool active)
{
enabled = active;
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Corwords.Core.Blog.EntityFrameworkCore
{
public class Tag : ITag<Blog, BlogPost, PostTag>
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public virtual int Id { get; set; }
[StringLength(255), Required]
public virtual string Title { get; set; }
public virtual string Description { get; set; }
[Required]
public virtual DateTime DateCreated { get; set; }
//public string htmlUrl;
//public string rssUrl;
public virtual IList<PostTag> PostTags { get; set; }
}
} |
namespace Metime.Test.Utils
{
public class FixedGetOffset : ICanGetOffset
{
public int GetOffset()
{
return 180;
}
}
}
|
using System;
namespace TinyGet.Requests
{
internal class RequestSenderCreator : IRequestSenderCreator
{
public IRequestSender Create(Context context)
{
return new RequestSender(context);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MvcEasyOrderSystem.Models;
using MvcEasyOrderSystem.Models.Repositry;
using System.Web.Mvc;
using System.Configuration;
using WebMatrix.WebData;
using MvcEasyOrderSystem.Controllers;
namespace MvcEasyOrderSystem.BussinessLogic
{
/// <summary>
/// 提供一些購物車相關動作。
/// 此class使用GetShoppingCart()來實例(create instance)自己。
/// </summary>
public class ShoppingCartLogic
{
public string UserIdSessionKey = ConfigurationManager.AppSettings["UserIdSession"];
public string UserId { get; set; }
private IGenericRepository<ShoppingCart> shoppingCartRepo;
private IGenericRepository<Meal> mealRepo;
private IGenericRepository<OrderDetial> orderDetailRepo;
private ShoppingCartLogic(IGenericRepository<ShoppingCart> inShoppingCartRepo,
IGenericRepository<Meal> inMealRepo,
IGenericRepository<OrderDetial> inOrderDetailRepo)
{
shoppingCartRepo = inShoppingCartRepo;
mealRepo = inMealRepo;
orderDetailRepo = inOrderDetailRepo;
}
private ShoppingCartLogic()
: this(new GenericRepository<ShoppingCart>(), new GenericRepository<Meal>(),
new GenericRepository<OrderDetial>())
{
}
/// <summary>
/// 如果使用者已經登陸,則得到使用者的登錄名稱(Name 同時在我的DB裏面作為Customer Table
/// 的PK),要不然使用Guid來給與一個暫時使用者Id。
/// </summary>
/// <param name="context">得到目前Request</param>
/// <returns>使用者Id,對應Customer Table PK</returns>
public string GetUserId(HttpContextBase context)
{
if (context.Session[UserIdSessionKey] == null)
{
if (string.IsNullOrEmpty(context.User.Identity.Name))
{
context.Session[UserIdSessionKey] = Guid.NewGuid().ToString();
}
else
{
context.Session[UserIdSessionKey] =context.User.Identity.Name.ToString();
}
}
return context.Session[UserIdSessionKey].ToString();
}
/// <summary>
/// 靜態方法,用來實例ShoppingCartLogic
/// </summary>
/// <param name="inContext">目前Context</param>
/// <returns></returns>
public static ShoppingCartLogic GetShoppingCart(HttpContextBase inContext)
{
ShoppingCartLogic cart = new ShoppingCartLogic();
cart.UserId = cart.GetUserId(inContext);
return cart;
}
/// <summary>
/// 得到目前所有這使用者所放入購物車的物品
/// </summary>
/// <returns></returns>
public IEnumerable<ShoppingCart> GetShoppingCartItems()
{
var result = shoppingCartRepo.GetWithFilterAndOrder(x => x.UserId == UserId);
foreach (var item in result)
{
item.Image = (from a in mealRepo.GetWithFilterAndOrder()
where a.MealId == item.MealId
select a).First().Image;
}
return result;
}
/// <summary>
/// 得到購物車所有物品的加總
/// </summary>
/// <param name="items"></param>
/// <returns></returns>
public decimal GetShoppingCartTotalPrice(IEnumerable<ShoppingCart> items)
{
decimal totalPrice = 0;
foreach (var item in items)
{
totalPrice = totalPrice + item.FullPrice;
}
return totalPrice;
}
/// <summary>
/// 把一個餐加入到購物車,如果已經存在,則是把數量加1
/// </summary>
/// <param name="mealId">Meal Table 的PK</param>
public void AddToCart(int mealId)
{
ShoppingCart result = shoppingCartRepo.GetSingleEntity(
x => x.UserId == UserId && x.MealId == mealId);
if (result == null)
{
var mealDetail = mealRepo.GetSingleEntity(x => x.MealId == mealId);
shoppingCartRepo.Insert(new ShoppingCart
{
MealId = mealDetail.MealId,
MealName = mealDetail.MealName,
Quantity = 1,
UnitPrice = mealDetail.Price,
UserId = UserId,
});
}
else
{
result.Quantity = result.Quantity + 1;
shoppingCartRepo.Update(result);
}
}
public void SaveChanges()
{
shoppingCartRepo.SaveChanges();
}
/// <summary>
/// 刪除購物車裏面其中一筆資料
/// </summary>
/// <param name="shoppingCartId"></param>
public void RemoveFromCart(int shoppingCartId)
{
ShoppingCart result = GetShoppingCartUsingShoppingCartId(shoppingCartId);
shoppingCartRepo.Delete(result);
}
/// <summary>
/// 清空整個購物車
/// </summary>
public void EmptyCart()
{
var cartItems = shoppingCartRepo.GetWithFilterAndOrder(x => x.UserId == UserId);
foreach (var item in cartItems)
{
shoppingCartRepo.Delete(item);
}
shoppingCartRepo.SaveChanges();
}
/// <summary>
/// 得到某一個指定的購物車
/// </summary>
/// <param name="shoppingCartId"></param>
/// <returns></returns>
public ShoppingCart GetShoppingCartUsingShoppingCartId(int shoppingCartId)
{
return (shoppingCartRepo.GetSingleEntity
(x => x.ShoppingCartId == shoppingCartId));
}
/// <summary>
/// 把購物車裏面每一筆資料轉換成對應的OrderDetail,用來做購買完成下定單的動作。
/// </summary>
/// <param name="order">主要爲了Order的Id,這樣OrderDetail才知道對應那個</param>
/// <returns>傳回這一筆Order的總金額</returns>
public decimal ShoppingCartToOrderDetails(Order order)
{
var cartItems = GetShoppingCartItems();
decimal totalPrice = 0;
foreach(var item in cartItems)
{
var orderDetail = new OrderDetial()
{
MealId = item.MealId,
OrderId = order.OrderId,
Quantity = item.Quantity,
UnitPrice = item.UnitPrice
};
totalPrice += (orderDetail.UnitPrice * orderDetail.Quantity);
orderDetailRepo.Insert(orderDetail);
}
orderDetailRepo.SaveChanges();
EmptyCart();
return totalPrice;
}
/// <summary>
/// 當使用著登陸以後,需要把本來臨時給予的假UserId(使用Guid達到)轉換成為真實的
/// UserId。
/// </summary>
/// <param name="inUserId">傳入真實UserId</param>
public void MigrateShoppingCartUserIdToUserId(string inUserId)
{
var cart = shoppingCartRepo.GetWithFilterAndOrder
(x => x.UserId == UserId) ;
foreach (var item in cart)
{
item.UserId = inUserId;
}
shoppingCartRepo.SaveChanges();
}
/// <summary>
/// 得到目前購物車總數
/// </summary>
/// <returns></returns>
public int GetShoppingCartCount()
{
return shoppingCartRepo.GetWithFilterAndOrder(x => x.UserId == UserId).Count();
}
}
}
|
// Licensed to Finnovation Labs Limited under one or more agreements.
// Finnovation Labs Limited licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using FinnovationLabs.OpenBanking.Library.Connector.Fluent;
using FinnovationLabs.OpenBanking.Library.Connector.Models.Persistent;
using FinnovationLabs.OpenBanking.Library.Connector.Models.Repository;
using FinnovationLabs.OpenBanking.Library.Connector.Persistence;
using FinnovationLabs.OpenBanking.Library.Connector.Repositories;
using FinnovationLabs.OpenBanking.Library.Connector.Services;
using Microsoft.EntityFrameworkCore;
namespace FinnovationLabs.OpenBanking.Library.Connector.Operations
{
internal class LocalEntityDelete<TEntity> :
IObjectDelete
where TEntity : class, ISupportsFluentDeleteLocal<TEntity>
{
private readonly IDbSaveChangesMethod _dbSaveChangesMethod;
protected readonly IDbReadWriteEntityMethods<TEntity> _entityMethods;
protected readonly IReadOnlyRepository<ProcessedSoftwareStatementProfile> _softwareStatementProfileRepo;
private readonly ITimeProvider _timeProvider;
public LocalEntityDelete(
IDbReadWriteEntityMethods<TEntity> entityMethods,
IDbSaveChangesMethod dbSaveChangesMethod,
ITimeProvider timeProvider,
IReadOnlyRepository<ProcessedSoftwareStatementProfile> softwareStatementProfileRepo)
{
_entityMethods = entityMethods;
_dbSaveChangesMethod = dbSaveChangesMethod;
_timeProvider = timeProvider;
_softwareStatementProfileRepo = softwareStatementProfileRepo;
}
public async
Task<IList<IFluentResponseInfoOrWarningMessage>> DeleteAsync(
Guid id,
string? modifiedBy,
bool useRegistrationAccessToken)
{
var requestInfo = new DeleteRequestInfo(id, modifiedBy, useRegistrationAccessToken);
// Create non-error list
var nonErrorMessages =
new List<IFluentResponseInfoOrWarningMessage>();
// DELETE at bank API
(TEntity persistedObject, IList<IFluentResponseInfoOrWarningMessage> newNonErrorMessages) =
await ApiDelete(requestInfo);
nonErrorMessages.AddRange(newNonErrorMessages);
// Local soft delete
persistedObject.IsDeleted = new ReadWriteProperty<bool>(
true,
_timeProvider,
requestInfo.ModifiedBy);
await _dbSaveChangesMethod.SaveChangesAsync();
// Return success response (thrown exceptions produce error response)
return nonErrorMessages;
}
protected virtual async
Task<(TEntity persistedObject, IList<IFluentResponseInfoOrWarningMessage> nonErrorMessages)>
ApiDelete(DeleteRequestInfo requestInfo)
{
// Create non-error list
var nonErrorMessages =
new List<IFluentResponseInfoOrWarningMessage>();
// Get persisted entity
TEntity persistedObject =
await _entityMethods
.DbSet
.SingleOrDefaultAsync(x => x.Id == requestInfo.Id) ??
throw new KeyNotFoundException($"No record found for entity with ID {requestInfo.Id}.");
return (persistedObject, nonErrorMessages);
}
public class DeleteRequestInfo
{
public DeleteRequestInfo(Guid id, string? modifiedBy, bool useRegistrationAccessToken)
{
Id = id;
ModifiedBy = modifiedBy;
UseRegistrationAccessToken = useRegistrationAccessToken;
}
public Guid Id { get; }
public string? ModifiedBy { get; }
public bool UseRegistrationAccessToken { get; }
}
}
}
|
using System;
namespace SolarSystem.Backend.Classes
{
public class OrderBoxProgress : IComparable
{
public OrderBox OrderBox { get; }
public DateTime TimeOfArrival { get; }
public int SecondsToSpend { get; private set; }
public OrderBoxProgress( OrderBox order, int secondsToSpend)
{
OrderBox = order ?? throw new ArgumentNullException(nameof(order));
TimeOfArrival = TimeKeeper.CurrentDateTime;
SecondsToSpend = secondsToSpend;
TimeKeeper.Tick += OneSecondSpent;
}
private void OneSecondSpent()
{
SecondsToSpend -= 1;
}
public int CompareTo(object obj)
{
if (obj is OrderBoxProgress orderBoxProgressObj)
{
return SecondsToSpend < orderBoxProgressObj.SecondsToSpend ? -1 :
SecondsToSpend > orderBoxProgressObj.SecondsToSpend ? 1 : 0;
}
return 0;
}
}
} |
using System;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Net.Sh_Lab.PlayingCards;
using Net.Sh_Lab.PlayingCards.Pyramid;
namespace PyramidTest
{
[TestClass]
public class PyramidTest
{
/// <summary>
/// 一段目 K
/// 二段目 Q A
/// QとA ⇒ Kの順に除去。
/// </summary>
[TestMethod]
public void TestMethod1()
{
var dictionary = new Dictionary<Card, IPosition>
{
{ Card.KingOfSpades, new Field(1, 1) },
{ Card.AceOfClubs, new Field(2, 1) },
{ Card.QueenOfClubs, new Field(2, 2) }
};
var pyramid = new Pyramid(dictionary);
Assert.IsTrue(pyramid.CanRemove(Card.AceOfClubs, Card.QueenOfClubs));
Assert.IsTrue(pyramid.CanRemove(Card.QueenOfClubs, Card.AceOfClubs));
Assert.IsFalse(pyramid.CanRemove(Card.AceOfClubs, Card.KingOfSpades));
Assert.IsFalse(pyramid.CanRemove(Card.KingOfSpades, Card.QueenOfClubs));
Assert.IsFalse(pyramid.CanRemove(Card.KingOfSpades));
Assert.IsFalse(pyramid.CanRemove(Card.QueenOfClubs));
Assert.IsFalse(pyramid.CanRemove(Card.AceOfClubs));
// AとQを除去
pyramid.Remove(Card.AceOfClubs, Card.QueenOfClubs);
Assert.IsTrue(pyramid[Card.AceOfClubs] is Outside);
Assert.IsTrue(pyramid[Card.QueenOfClubs] is Outside);
Assert.IsFalse(pyramid.CanRemove(Card.AceOfClubs, Card.QueenOfClubs));
Assert.IsFalse(pyramid.CanRemove(Card.QueenOfClubs, Card.AceOfClubs));
Assert.IsFalse(pyramid.CanRemove(Card.AceOfClubs, Card.KingOfSpades));
Assert.IsFalse(pyramid.CanRemove(Card.KingOfSpades, Card.QueenOfClubs));
Assert.IsTrue(pyramid.CanRemove(Card.KingOfSpades));
Assert.IsFalse(pyramid.CanRemove(Card.QueenOfClubs));
Assert.IsFalse(pyramid.CanRemove(Card.AceOfClubs));
/// Kを除去
pyramid.Remove(Card.KingOfSpades);
Assert.IsTrue(pyramid[Card.KingOfSpades] is Outside);
Assert.IsFalse(pyramid.CanRemove(Card.AceOfClubs, Card.QueenOfClubs));
Assert.IsFalse(pyramid.CanRemove(Card.QueenOfClubs, Card.AceOfClubs));
Assert.IsFalse(pyramid.CanRemove(Card.AceOfClubs, Card.KingOfSpades));
Assert.IsFalse(pyramid.CanRemove(Card.KingOfSpades, Card.QueenOfClubs));
Assert.IsFalse(pyramid.CanRemove(Card.KingOfSpades));
Assert.IsFalse(pyramid.CanRemove(Card.QueenOfClubs));
Assert.IsFalse(pyramid.CanRemove(Card.AceOfClubs));
}
/// <summary>
/// 一段目 A
/// 二段目 A
/// 山札 J Q Q
/// 山札をすべて引いてリディール
/// QとA ⇒ 山札からJを引く ⇒ 山札からQを引く ⇒ QとAの順に除去。
/// </summary>
[TestMethod]
public void TestMethod2()
{
var dictionary = new Dictionary<Card, IPosition>
{
{ Card.AceOfSpades, new Field(1, 1) },
{ Card.AceOfClubs, new Field(2, 1) },
{ Card.AceOfDiamonds, new Field(2, 2) },
{ Card.JackOfClubs, new Deck(2)},
{ Card.QueenOfSpades, new Deck(1)},
{ Card.QueenOfHearts, new Deck(0)},
};
var pyramid = new Pyramid(dictionary);
pyramid.Draw(Card.JackOfClubs);
pyramid.Draw(Card.QueenOfSpades);
pyramid.Draw(Card.QueenOfHearts);
Assert.IsTrue(pyramid.CanRedeal());
pyramid.Redeal();
}
}
}
|
using System.Xml.Serialization;
namespace openTRANS
{
public partial class AllowOrCharge
{
[XmlAttribute("type")]
public string Type;
[XmlElement("ALLOW_OR_CHARGE_SEQUENCE")]
public int AllowOrChageSequence;
[XmlElement("ALLOW_OR_CHARGE_NAME")]
public string AllowOrChargeName;
[XmlElement("ALLOW_OR_CHARGE_TYPE")]
public string AllowOrChargeType;
[XmlElement("ALLOW_OR_CHARGE_DESCR")]
public string AllowOrChargeDescr;
[XmlElement("ALLOW_OR_CHARGE_VALUE")]
public AllowOrChargeValue AllowOrChargeValue = new AllowOrChargeValue();
[XmlElement("ALLOW_OR_CHARGE_BASE")]
public float AllowOrChargeBase;
}
}
|
using System;
using System.Linq;
using System.Threading.Tasks;
using OrchardCore.DisplayManagement.Shapes;
namespace OrchardCore.DisplayManagement.Zones
{
public interface IZoneHolding : IShape
{
Zones Zones { get; }
}
/// <summary>
/// Provides the behavior of shapes that have a Zones property.
/// Examples include Layout and Item
///
/// * Returns a fake parent object for zones
/// Foo.Zones
///
/// *
/// Foo.Zones.Alpha :
/// Foo.Zones["Alpha"]
/// Foo.Alpha :same
///
/// </summary>
public class ZoneHolding : Shape, IZoneHolding
{
private readonly Func<ValueTask<IShape>> _zoneFactory;
public ZoneHolding(Func<ValueTask<IShape>> zoneFactory)
{
_zoneFactory = zoneFactory;
}
private Zones _zones;
public Zones Zones => _zones ??= new Zones(_zoneFactory, this);
public override bool TryGetMember(System.Dynamic.GetMemberBinder binder, out object result)
{
var name = binder.Name;
if (!base.TryGetMember(binder, out result) || (null == result))
{
// substitute nil results with a robot that turns adds a zone on
// the parent when .Add is invoked
result = new ZoneOnDemand(_zoneFactory, this, name);
TrySetMemberImpl(name, result);
}
return true;
}
}
/// <remarks>
/// Returns a ZoneOnDemand object the first time the indexer is invoked.
/// If an item is added to the ZoneOnDemand then the zoneFactory is invoked to create a zone shape and this item is added to the zone.
/// Then the zone shape is assigned in palce of the ZoneOnDemand. A ZoneOnDemand returns true when compared to null such that we can
/// do Zones["Foo"] == null to see if anything has been added to a zone, without instantiating a zone when accessing the indexer.
/// </remarks>
public class Zones : Composite
{
private readonly Func<ValueTask<IShape>> _zoneFactory;
private readonly ZoneHolding _parent;
public bool IsNotEmpty(string name) => !(this[name] is ZoneOnDemand);
public Zones(Func<ValueTask<IShape>> zoneFactory, ZoneHolding parent)
{
_zoneFactory = zoneFactory;
_parent = parent;
}
public IShape this[string name]
{
get
{
TryGetMemberImpl(name, out var result);
return result as IShape;
}
set
{
TrySetMemberImpl(name, value);
}
}
public override bool TryGetMember(System.Dynamic.GetMemberBinder binder, out object result)
{
return TryGetMemberImpl(binder.Name, out result);
}
protected override bool TryGetMemberImpl(string name, out object result)
{
if (!_parent.Properties.TryGetValue(name, out result))
{
result = new ZoneOnDemand(_zoneFactory, _parent, name);
}
return true;
}
protected override bool TrySetMemberImpl(string name, object value)
{
_parent.Properties[name] = value;
return true;
}
}
/// <remarks>
/// InterfaceProxyBehavior()
/// NilBehavior() => return Nil on GetMember and GetIndex in all cases
/// ZoneOnDemandBehavior(_zoneFactory, _parent, name) => when a zone (Shape) is
/// created, replace itself with the zone so that Layout.ZoneName is no more equal to Nil
/// </remarks>
public class ZoneOnDemand : Shape
{
private readonly Func<ValueTask<IShape>> _zoneFactory;
private readonly ZoneHolding _parent;
private readonly string _potentialZoneName;
private IShape _zone;
public ZoneOnDemand(Func<ValueTask<IShape>> zoneFactory, ZoneHolding parent, string potentialZoneName)
{
_zoneFactory = zoneFactory;
_parent = parent;
_potentialZoneName = potentialZoneName;
}
public override bool TryGetMember(System.Dynamic.GetMemberBinder binder, out object result)
{
// NilBehavior
result = Nil.Instance;
return true;
}
public override bool TryGetIndex(System.Dynamic.GetIndexBinder binder, object[] indexes, out object result)
{
// NilBehavior
result = Nil.Instance;
return true;
}
public override bool TryInvokeMember(System.Dynamic.InvokeMemberBinder binder, object[] args, out object result)
{
var name = binder.Name;
// NilBehavior
if (!args.Any() && name != "ToString")
{
result = Nil.Instance;
return true;
}
return base.TryInvokeMember(binder, args, out result);
}
public override string ToString()
{
return String.Empty;
}
public override bool TryConvert(System.Dynamic.ConvertBinder binder, out object result)
{
if (binder.ReturnType == typeof(string))
{
result = null;
}
else if (binder.ReturnType.IsValueType)
{
result = Activator.CreateInstance(binder.ReturnType);
}
else
{
result = null;
}
return true;
}
public static bool operator ==(ZoneOnDemand a, object b)
{
// if ZoneOnDemand is compared to null it must return true
return b == null || ReferenceEquals(b, Nil.Instance);
}
public static bool operator !=(ZoneOnDemand a, object b)
{
// if ZoneOnDemand is compared to null it must return true
return !(a == b);
}
public override bool Equals(object obj)
{
if (obj is null)
{
return true;
}
if (ReferenceEquals(this, obj))
{
return true;
}
return false;
}
public override int GetHashCode()
{
return HashCode.Combine(_parent, _potentialZoneName);
}
public override async ValueTask<IShape> AddAsync(object item, string position)
{
if (item == null)
{
if (_zone != null)
{
return _zone;
}
return this;
}
if (_zone == null)
{
_zone = await _zoneFactory();
_zone.Properties["Parent"] = _parent;
_zone.Properties["ZoneName"] = _potentialZoneName;
_parent.Properties[_potentialZoneName] = _zone;
}
return _zone = await _zone.AddAsync(item, position);
}
}
}
|
using SolidPrinciples.LiskovSubstitutionPrinciple.WithPrinciple.Abstract;
namespace SolidPrinciples.LiskovSubstitutionPrinciple.WithPrinciple.Implementation;
public class PermanentEmployee : Employee
{
public PermanentEmployee(int id, string name): base(id, name) { }
public override decimal CalculateBonus(decimal salary)
{
return salary * .1M;
}
public override decimal GetMinimumSalary()
{
return 15000;
}
} |
using System;
using Android.Content;
using Android.Support.V7.App;
namespace Lion.XDroid.Libs
{
public class AppDialog
{
private static AppDialog sigleton = null;
public static AppDialog SNG
{
get
{
if (sigleton == null)
sigleton = new AppDialog();
return sigleton;
}
}
public void Alert(Context context, string text)
{
var builder = new AlertDialog.Builder(context, Android.Resource.Style.ThemeHoloLightDialogNoActionBar);
builder.SetTitle("알림")
.SetMessage(text)
.SetCancelable(false)
.SetPositiveButton("확인",
(s, e) =>
{
((AlertDialog)s).Cancel();
});
var _dialog = builder.Create();
_dialog.Show();
}
public void Alert(Context context, string text, EventHandler<DialogEventArgs> listener)
{
var builder = new AlertDialog.Builder(context, Android.Resource.Style.ThemeHoloLightDialogNoActionBar);
builder.SetTitle("알림")
.SetMessage(text)
.SetCancelable(false)
.SetPositiveButton("확인",
(s, e) =>
{
listener?.Invoke(this, new DialogEventArgs(false));
((AlertDialog)s).Cancel();
});
var _dialog = builder.Create();
_dialog.Show();
}
public void CancelAlert(Context context, string text, EventHandler<DialogEventArgs> listener)
{
var builder = new AlertDialog.Builder(context, Android.Resource.Style.ThemeHoloLightDialogNoActionBar);
builder.SetTitle("알림")
.SetMessage(text)
.SetCancelable(false)
.SetPositiveButton("확인", (s, e) =>
{
listener?.Invoke(this, new DialogEventArgs(true));
((AlertDialog)s).Cancel();
})
.SetNegativeButton("취소", (s, e) =>
{
});
var _dialog = builder.Create();
_dialog.Show();
}
}
} |
namespace CoreDocker.Shared
{
public static class SignalRHubUrls
{
public const string ChatUrl = "/chat";
public const string ChatUrlSendCommand = "send";
public const string ChatUrlReceiveCommand = "receive";
}
} |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
using Microsoft.Owin.Hosting;
using Newtonsoft.Json;
using Owin;
namespace DeserializationPOC
{
class Program
{
static void Main(string[] args)
{
WebApp.Start<StartUp>("http://localhost:8085");
Console.WriteLine("Server is up");
Console.ReadKey();
}
public class StartUp
{
public void Configuration(IAppBuilder builder)
{
var config = new HttpConfiguration();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.MapHttpAttributeRoutes();
config.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
config.Formatters.JsonFormatter.SerializerSettings = new
JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.All
};
builder.UseWebApi(config);
}
}
}
}
|
using UnityEngine;
using Random = UnityEngine.Random;
namespace Utility
{
public class ScreenShake : MonoBehaviour
{
[SerializeField] private float _duration;
[SerializeField] private float _intensity;
[SerializeField] private AnimationCurve _dropoff;
[SerializeField] private Transform _camera;
private Vector2 _offset;
private void Update()
{
// Stop if below 0.
if (_duration <= 0)
{
_offset = Vector2.zero;
_duration = 0;
return;
}
_duration -= Time.deltaTime;
var intensity = _dropoff.Evaluate(_duration) * _intensity;
var xPos = Random.Range(-intensity, intensity);
var yPos = Random.Range(-intensity, intensity);
_offset = new Vector2(xPos, yPos);
_camera.localPosition = _offset;
}
public void SetDuration(float duration)
{
_duration = duration;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AtomicArcade.DataModels.Content;
using AtomicArcade.ViewModels.Content;
namespace AtomicArcade.ViewLogic.Content
{
public interface IGameVMConverter
{
IEnumerable<GameViewModel> GetViewModelList(IEnumerable<Game> gameList);
IEnumerable<GameFeaturesViewModel> GetFeaturesViewModelList(IEnumerable<Game> gameList);
IEnumerable<GameThumbnailViewModel> GetThumbnailViewModelList(IEnumerable<Game> gameList);
IEnumerable<GameDetailsViewModel> GetDetailsViewModelList(IEnumerable<Game> gameList);
GameDetailsViewModel GetDetailsViewModel(Game game);
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
using x360ce.Engine;
using System.IO;
namespace x360ce.App.Controls
{
public partial class GameSettingDetailsUserControl : UserControl
{
public GameSettingDetailsUserControl()
{
InitializeComponent();
if (IsDesignMode) return;
var paItems = (ProcessorArchitecture[])Enum.GetValues(typeof(ProcessorArchitecture));
DInputCheckBoxes = Controls.OfType<CheckBox>().Where(x => x.Name.StartsWith("DInput")).ToArray();
XInputCheckBoxes = Controls.OfType<CheckBox>().Where(x => x.Name.StartsWith("XInput")).ToArray();
HookCheckBoxes = Controls.OfType<CheckBox>().Where(x => x.Name.StartsWith("Hook")).ToArray();
foreach (var item in paItems) ProcessorArchitectureComboBox.Items.Add(item);
lock (CurrentGameLock)
{
EnableEvents();
}
}
internal bool IsDesignMode
{
get
{
if (DesignMode) return true;
if (LicenseManager.UsageMode == LicenseUsageMode.Designtime) return true;
var pa = this.ParentForm;
if (pa != null && pa.GetType().FullName.Contains("VisualStudio")) return true;
return false;
}
}
object CurrentGameLock = new object();
bool EnabledEvents = false;
bool ApplySettingsToFolderInstantly = false;
CheckBox[] XInputCheckBoxes;
CheckBox[] DInputCheckBoxes;
CheckBox[] HookCheckBoxes;
x360ce.Engine.Data.Game _CurrentGame;
x360ce.Engine.Data.Program _DefaultSettings;
[DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Hidden)]
public x360ce.Engine.Data.Game CurrentGame
{
get { return _CurrentGame; }
set
{
_CurrentGame = value;
UpdateInterface();
UpdateFakeVidPidControls();
UpdateDinputControls();
UpdateHelpButtons();
}
}
void UpdateInterface()
{
var en = (CurrentGame != null);
var item = CurrentGame ?? new x360ce.Engine.Data.Game();
var dInputMask = (DInputMask)item.DInputMask;
var xInputMask = (XInputMask)item.XInputMask;
var hookMask = (HookMask)item.HookMask;
SetMask(en, hookMask, dInputMask, xInputMask, item.FullPath, item.ProcessorArchitecture);
HookModeFakeVidNumericUpDown_ValueChanged2(null, null);
HookModeFakeVidNumericUpDown.Value = item.FakeVID;
HookModeFakePidNumericUpDown.Value = item.FakePID;
HookModeFakePidNumericUpDown_ValueChanged2(null, null);
TimeoutNumericUpDown.Value = item.Timeout;
if (en)
{
var status = GetGameStatus(CurrentGame, false);
ApplySettingsToFolderInstantly = (status == GameRefreshStatus.OK);
SynchronizeSettingsButton.Visible = (status != GameRefreshStatus.OK);
_DefaultSettings = SettingManager.Programs.Items.FirstOrDefault(x => x.FileName == CurrentGame.FileName);
ResetToDefaultButton.Enabled = _DefaultSettings != null;
if (ApplySettingsToFolderInstantly)
{
}
}
}
// Check game settings against folder.
public GameRefreshStatus GetGameStatus(x360ce.Engine.Data.Game game, bool fix = false)
{
var fi = new FileInfo(game.FullPath);
// Check if game file exists.
if (!fi.Exists)
{
return GameRefreshStatus.ExeNotExist;
}
// Check if game is not enabled.
else if (!game.IsEnabled)
{
return GameRefreshStatus.OK;
}
else
{
var gameVersion = System.Diagnostics.FileVersionInfo.GetVersionInfo(fi.FullName);
var xiValues = ((XInputMask[])Enum.GetValues(typeof(XInputMask))).Where(x => x != XInputMask.None).ToArray();
// Create dictionary from XInput type and XInput file name.
var dic = new Dictionary<XInputMask, string>();
foreach (var value in xiValues)
{
dic.Add(value, JocysCom.ClassLibrary.ClassTools.EnumTools.GetDescription(value));
}
var xiFileNames = dic.Values.Distinct();
// Loop through all files.
foreach (var xiFileName in xiFileNames)
{
var x64Value = dic.First(x => x.Value == xiFileName && x.ToString().Contains("x64")).Key;
var x86Value = dic.First(x => x.Value == xiFileName && x.ToString().Contains("x86")).Key;
var xiFullPath = System.IO.Path.Combine(fi.Directory.FullName, xiFileName);
var xiFileInfo = new System.IO.FileInfo(xiFullPath);
var xiArchitecture = ProcessorArchitecture.None;
var x64Enabled = ((uint)game.XInputMask & (uint)x64Value) != 0; ;
var x86Enabled = ((uint)game.XInputMask & (uint)x86Value) != 0; ;
if (x86Enabled && x64Enabled) xiArchitecture = ProcessorArchitecture.MSIL;
else if (x86Enabled) xiArchitecture = ProcessorArchitecture.X86;
else if (x64Enabled) xiArchitecture = ProcessorArchitecture.Amd64;
// If x360ce emulator for this game is disabled or both CheckBoxes are disabled or then...
if (xiArchitecture == ProcessorArchitecture.None) // !game.IsEnabled ||
{
// If XInput file exists then...
if (xiFileInfo.Exists)
{
if (fix)
{
// Delete unnecessary XInput file.
xiFileInfo.Delete();
continue;
}
else
{
return GameRefreshStatus.XInputFilesUnnecessary;
}
}
}
else
{
// If XInput file doesn't exists then...
if (!xiFileInfo.Exists)
{
// Create XInput file.
if (fix)
{
AppHelper.WriteFile(EngineHelper.GetXInputResoureceName(xiArchitecture), xiFileInfo.FullName);
continue;
}
else return GameRefreshStatus.XInputFilesNotExist;
}
// Get current architecture.
var xiCurrentArchitecture = Engine.Win32.PEReader.GetProcessorArchitecture(xiFullPath);
// If processor architectures doesn't match then...
if (xiArchitecture != xiCurrentArchitecture)
{
// Create XInput file.
if (fix)
{
AppHelper.WriteFile(EngineHelper.GetXInputResoureceName(xiArchitecture), xiFileInfo.FullName);
continue;
}
else return GameRefreshStatus.XInputFilesWrongPlatform;
}
bool byMicrosoft;
var dllVersion = EngineHelper.GetDllVersion(xiFullPath, out byMicrosoft);
var embededVersion = EngineHelper.GetEmbeddedDllVersion(xiCurrentArchitecture);
// If file on disk is older then...
if (dllVersion < embededVersion)
{
// Overwrite XInput file.
if (fix)
{
AppHelper.WriteFile(EngineHelper.GetXInputResoureceName(xiArchitecture), xiFileInfo.FullName);
continue;
}
return GameRefreshStatus.XInputFilesOlderVersion;
}
else if (dllVersion > embededVersion)
{
// Allow new version.
// return GameRefreshStatus.XInputFileNewerVersion;
}
}
}
}
return GameRefreshStatus.OK;
}
public void SetMask(bool en, HookMask hookMask, DInputMask dInputMask, XInputMask xInputMask, string path, int proc)
{
lock (CurrentGameLock)
{
if (EnabledEvents) DisableEvents();
SetMask<DInputMask>(DInputCheckBoxes, dInputMask);
SetMask<XInputMask>(XInputCheckBoxes, xInputMask);
SetMask<HookMask>(HookCheckBoxes, hookMask);
// Processor architecture.
ProcessorArchitectureComboBox.SelectedItem = Enum.IsDefined(typeof(ProcessorArchitecture), proc)
? (ProcessorArchitecture)proc
: ProcessorArchitecture.None;
SynchronizeSettingsButton.Visible = en;
ResetToDefaultButton.Visible = en;
// Enable events.
EnableEvents();
}
}
T GetMask<T>(CheckBox[] boxes)
{
uint mask = 0;
// Check/Uncheck CheckBox.
var xs = (T[])Enum.GetValues(typeof(T));
foreach (var value in xs)
{
// Get CheckBox linked to enum value.
var cb = boxes.FirstOrDefault(x => x.Name.StartsWith(value.ToString()));
if (cb != null && cb.Checked) mask |= (uint)(object)value;
}
return (T)(object)mask;
}
void SetMask<T>(CheckBox[] boxes, T mask)
{
// Check/Uncheck CheckBox.
var xs = (T[])Enum.GetValues(typeof(T));
foreach (var value in xs)
{
// Get CheckBox linked to enum value.
var cb = boxes.FirstOrDefault(x => x.Name.StartsWith(value.ToString()));
if (cb != null) cb.Checked = (((uint)(object)mask & (uint)(object)value) != 0);
}
}
void EnableEvents()
{
foreach (var cb in DInputCheckBoxes) cb.CheckedChanged += CheckBox_Changed;
foreach (var cb in XInputCheckBoxes) cb.CheckedChanged += CheckBox_Changed;
foreach (var cb in HookCheckBoxes) cb.CheckedChanged += CheckBox_Changed;
HookModeFakeVidNumericUpDown.ValueChanged += HookModeFakeVidNumericUpDown_ValueChanged;
HookModeFakePidNumericUpDown.ValueChanged += HookModeFakePidNumericUpDown_ValueChanged;
TimeoutNumericUpDown.ValueChanged += this.TimeoutNumericUpDown_ValueChanged;
EnabledEvents = true;
}
void DisableEvents()
{
foreach (var cb in DInputCheckBoxes) cb.CheckedChanged -= CheckBox_Changed;
foreach (var cb in XInputCheckBoxes) cb.CheckedChanged -= CheckBox_Changed;
foreach (var cb in HookCheckBoxes) cb.CheckedChanged -= CheckBox_Changed;
HookModeFakeVidNumericUpDown.ValueChanged -= HookModeFakeVidNumericUpDown_ValueChanged;
HookModeFakePidNumericUpDown.ValueChanged -= HookModeFakePidNumericUpDown_ValueChanged;
TimeoutNumericUpDown.ValueChanged -= this.TimeoutNumericUpDown_ValueChanged;
EnabledEvents = false;
}
/// <summary>
/// CheckBox events could fire at the same time.
/// Use lock to make sure that only one file is processed during synchronization.
/// </summary>
object CheckBoxLock = new object();
void CheckBox_Changed(object sender, EventArgs e)
{
if (CurrentGame == null) return;
lock (CheckBoxLock)
{
var cbx = (CheckBox)sender;
var is64bit = cbx.Name.Contains("x64");
var is32bit = cbx.Name.Contains("x86");
bool applySettings = true;
CheckBox[] cbxList = null;
if (XInputCheckBoxes.Contains(cbx)) cbxList = XInputCheckBoxes;
if (DInputCheckBoxes.Contains(cbx)) cbxList = DInputCheckBoxes;
if (cbxList != null)
{
// If 64-bit CheckBox an checked then...
if (is64bit && cbx.Checked)
{
// Make sure that 32-bit is unchecked
var cbx32 = cbxList.First(x => x.Name == cbx.Name.Replace("x64", "x86"));
if (cbx32.Checked)
{
cbx32.Checked = false;
applySettings = false;
}
}
// If 32-bit CheckBox an checked then...
if (is32bit && cbx.Checked)
{
// Make sure that 64-bit is unchecked
var cbx64 = cbxList.First(x => x.Name == cbx.Name.Replace("x86", "x64"));
if (cbx64.Checked)
{
cbx64.Checked = false;
applySettings = false;
}
}
}
// Set DInput mask.
var dm = (int)GetMask<DInputMask>(DInputCheckBoxes);
CurrentGame.DInputMask = dm;
DInputMaskTextBox.Text = dm.ToString("X8");
// Set XInput mask.
var xm = (int)GetMask<XInputMask>(XInputCheckBoxes);
CurrentGame.XInputMask = xm;
XInputMaskTextBox.Text = xm.ToString("X8");
// Set hook mask.
var hm = (int)GetMask<HookMask>(HookCheckBoxes);
CurrentGame.HookMask = hm;
HookMaskTextBox.Text = hm.ToString("X8");
SettingManager.Save();
if (applySettings && ApplySettingsToFolderInstantly) ApplySettings();
}
}
void SetCheckXinput(XInputMask mask)
{
//if (CurrentGame == null) return;
var name = JocysCom.ClassLibrary.ClassTools.EnumTools.GetDescription(mask);
var path = System.IO.Path.GetDirectoryName(CurrentGame.FullPath);
var fullPath = System.IO.Path.Combine(path, name);
///var box = (CheckBox)sender;
//var exists = AppHelper.CreateDllFile(, fullPath);
//if (exists != box.Checked) box.Checked = exists;
}
private void SynchronizeSettingsButton_Click(object sender, EventArgs e)
{
MessageBoxForm form = new MessageBoxForm();
form.StartPosition = FormStartPosition.CenterParent;
var status = GetGameStatus(CurrentGame, false);
var values = Enum.GetValues(typeof(GameRefreshStatus));
List<string> errors = new List<string>();
foreach (GameRefreshStatus value in values)
{
if (status.HasFlag(value))
{
var description = JocysCom.ClassLibrary.ClassTools.EnumTools.GetDescription(value);
errors.Add(description);
}
}
var message = "Synchronize current settings to game folder?";
message += "\r\n\r\n\tIssues:\r\n\r\n\t - " + string.Join("\r\n\t - ", errors);
var result = form.ShowForm(message, "Synchronize", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
if (result == DialogResult.OK) ApplySettings();
}
void ApplySettings()
{
var status = GetGameStatus(CurrentGame, true);
ApplySettingsToFolderInstantly = (status == GameRefreshStatus.OK);
SynchronizeSettingsButton.Visible = (status != GameRefreshStatus.OK) && (status != GameRefreshStatus.OK);
}
private void ResetToDefaultButton_Click(object sender, EventArgs e)
{
MessageBoxForm form = new MessageBoxForm();
form.StartPosition = FormStartPosition.CenterParent;
var result = form.ShowForm("Reset current settings to default?", "Reset", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
if (result == DialogResult.OK)
{
// Reset to default all properties which affects checksum.
_CurrentGame.XInputMask = _DefaultSettings.XInputMask;
_CurrentGame.HookMask = _DefaultSettings.HookMask;
_CurrentGame.DInputMask = _DefaultSettings.DInputMask;
_CurrentGame.DInputFile = _DefaultSettings.DInputFile ?? "";
_CurrentGame.FakeVID = _DefaultSettings.FakeVID;
_CurrentGame.FakePID = _DefaultSettings.FakePID;
_CurrentGame.Timeout = _DefaultSettings.Timeout;
UpdateInterface();
}
}
private void DInputFileTextBox_TextChanged(object sender, EventArgs e)
{
var item = CurrentGame;
if (item == null) return;
item.DInputFile = DInputFileTextBox.Text;
}
private void HookModeFakeVidNumericUpDown_ValueChanged(object sender, EventArgs e)
{
var item = CurrentGame;
if (item == null) return;
item.FakeVID = (int)HookModeFakeVidNumericUpDown.Value;
}
private void HookModeFakeVidNumericUpDown_ValueChanged2(object sender, EventArgs e)
{
HookModeFakeVidTextBox.Text = "0x" + ((int)HookModeFakeVidNumericUpDown.Value).ToString("X4");
}
private void HookModeFakePidNumericUpDown_ValueChanged(object sender, EventArgs e)
{
var item = CurrentGame;
if (item == null) return;
item.FakePID = (int)HookModeFakePidNumericUpDown.Value;
}
private void HookModeFakePidNumericUpDown_ValueChanged2(object sender, EventArgs e)
{
HookModeFakePidTextBox.Text = "0x" + ((int)HookModeFakePidNumericUpDown.Value).ToString("X4");
}
private void TimeoutNumericUpDown_ValueChanged(object sender, EventArgs e)
{
var item = CurrentGame;
if (item == null) return;
item.Timeout = (int)TimeoutNumericUpDown.Value;
}
private void HookPIDVIDCheckBox_CheckedChanged(object sender, EventArgs e)
{
UpdateFakeVidPidControls();
}
int msVid = 0x45E;
int msPid = 0x28E;
string dinputFile = "asiloader.dll";
void UpdateFakeVidPidControls()
{
var en = HookPIDVIDCheckBox.Checked;
HookModeFakeVidNumericUpDown.Enabled = en;
HookModeFakePidNumericUpDown.Enabled = en;
if (en)
{
if (HookModeFakeVidNumericUpDown.Value == 0)
{
HookModeFakeVidNumericUpDown.Value = msVid;
}
if (HookModeFakePidNumericUpDown.Value == 0)
{
HookModeFakePidNumericUpDown.Value = msPid;
}
}
else
{
if (HookModeFakeVidNumericUpDown.Value == msVid)
{
HookModeFakeVidNumericUpDown.Value = 0;
}
if (HookModeFakePidNumericUpDown.Value == msPid)
{
HookModeFakePidNumericUpDown.Value = 0;
}
}
}
private void DInput8_x86CheckBox_CheckedChanged(object sender, EventArgs e)
{
UpdateDinputControls();
}
private void DInput8_x64CheckBox_CheckedChanged(object sender, EventArgs e)
{
UpdateDinputControls();
}
void UpdateDinputControls()
{
var en = DInput8_x86CheckBox.Checked || DInput8_x64CheckBox.Checked;
DInputFileTextBox.Enabled = en;
if (en)
{
if (DInputFileTextBox.Text == "")
{
DInputFileTextBox.Text = dinputFile;
}
}
else
{
if (DInputFileTextBox.Text == dinputFile)
{
DInputFileTextBox.Text = "";
}
}
}
string GetGoogleSearchUrl()
{
var c = CurrentGame;
if (c == null) return "";
var url = "https://www.google.co.uk/?#q=";
var q = "x360ce " + c.FileProductName;
var keyName = EngineHelper.GetKey(q, false, " ");
url += System.Web.HttpUtility.UrlEncode(keyName);
return url;
}
string GetNGemuSearchUrl()
{
var c = CurrentGame;
if (c == null) return "";
var url = "http://ngemu.com/search/5815705?q=";
var q = "x360ce " + c.FileProductName;
var keyName = EngineHelper.GetKey(q, false, " ");
url += System.Web.HttpUtility.UrlEncode(keyName);
return url;
}
string GetNGemuThreadUrl()
{
var c = CurrentGame;
if (c == null) return "";
var q = "x360ce " + c.FileProductName;
var keyName = EngineHelper.GetKey(q, false);
var url = "http://ngemu.com/threads/";
url += System.Web.HttpUtility.UrlEncode(keyName) + "/";
return url;
}
void UpdateHelpButtons()
{
HelpButton.Enabled = CurrentGame != null;
GoogleSearchButton.Text = GetGoogleSearchUrl();
NGEmuSearchButton.Text = GetNGemuSearchUrl();
NGEmuThreadButton.Text = GetNGemuThreadUrl();
}
private void GoogleSearchButton_Click(object sender, EventArgs e)
{
EngineHelper.OpenUrl(GetGoogleSearchUrl());
}
private void NGEmuSearchLinkButton_Click(object sender, EventArgs e)
{
EngineHelper.OpenUrl(GetNGemuSearchUrl());
}
private void NGEmuThreadLinkButton_Click(object sender, EventArgs e)
{
EngineHelper.OpenUrl(GetNGemuThreadUrl());
}
}
}
|
using UnityEngine;
using UnityEngine.SceneManagement;
using System.Collections;
public class UIMenuManager : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
// removed for optimization, not called
// code not used
/*void Update () {
if (a != null) {
Debug.Log ("LOADING : " + a.progress);
Debug.Log ("is done : " + a.isDone + "(" + a.progress*100f +"%)" );
}
if (Time.time - timeStartLoading >= 10f) {
a.allowSceneActivation = true;
}
}*/
AsyncOperation a;
float timeStartLoading;
public void GoToLevelScene(){
GameStateManager.setGameState (GameState.Playing);
LevelManager.m_instance.LoadNextScene();
}
}
|
namespace RepositoryAndUnitOfWork.DomainModels
{
public class SiteOrder
{
public int SiteOrderId { get; set; }
//preliminary info - step1
public string SiteOrderWebSiteType { get; set; }
public string SiteOrderNumberOfMockUp { get; set; }
public string SiteOrderDevelopmentComplexity { get; set; }
public int? SiteOrderStaticPageNumber { get; set; }
public bool SiteOrderDoesHaveDatabase { get; set; }
public bool SiteOrderDoesHaveShoppingCart { get; set; }
public bool SiteOrderDoesHaveShoppingCartWithoutRegister { get; set; }
public bool SiteOrderDoesHaveBlog { get; set; }
public bool SiteOrderDoesContentOnUs { get; set; }
public string SiteOrderSupportType { get; set; }
//site design info - step2
public bool SiteOrderDoesUseTemplates { get; set; }
public bool SiteOrderDoesUseCustomDesign { get; set; }
public bool SiteOrderIsResponsive { get; set; }
public bool SiteOrderIsOptimizedForMobile { get; set; }
public bool SiteOrderIsOptimizedForAccessibility { get; set; }
public bool SiteOrderIsOptimizedForLightness { get; set; }
public bool SiteOrderDoesWithOkWithJavascriptDisabled { get; set; }
public bool SiteOrderDoesHaveSeo { get; set; }
public string SiteOrderSeoType { get; set; }
public bool SiteOrderDoesHaveSiteMap { get; set; }
//structural info - step3
public bool SiteOrderIsCrossPlatform { get; set; }
public bool SiteOrderDoesIncludeUnitTest { get; set; }
public bool SiteOrderIsAsync { get; set; }
public bool SiteOrderDoesConformToSolidDesign { get; set; }
public bool SiteOrderIsSinglePage { get; set; }
public bool SiteOrderDoesUseAjax { get; set; }
public string SiteOrderDoesUseAjaxType { get; set; }
public bool SiteOrderDoesHaveSsl { get; set; }
public bool SiteOrderDoesSourceCodeIncluded { get; set; }
public bool SiteOrderDoesHaveDocumentation { get; set; }
//site part info - step4
public bool SiteOrderDoesHaveRegistration { get; set; }
public bool SiteOrderDoesHaveExternalAuth { get; set; }
public bool SiteOrderDoesIncludeUserArea { get; set; }
public bool SiteOrderDoesHaveUserProfile { get; set; }
public bool SiteOrderDoesHaveAdminSection { get; set; }
public bool SiteOrderDoesAdminManageUsers { get; set; }
public bool SiteOrderDoesHaveFileManager { get; set; }
public bool SiteOrderDoesHaveImageGallery { get; set; }
public bool SiteOrderDoesHaveAdvancedHtmlEditor { get; set; }
public bool SiteOrderDoesHaveSlideShow { get; set; }
//auxiliary feature info - step5
public bool SiteOrderDoesSupportTagging { get; set; }
public bool SiteOrderDoesSupportCategory { get; set; }
public bool SiteOrderDoesHaveCommenting { get; set; }
public bool SiteOrderDoesHaveRatinging { get; set; }
public bool SiteOrderDoesHaveNewsLetter { get; set; }
public bool SiteOrderDoesHaveFeed { get; set; }
public bool SiteOrderDoesVideoPlaying { get; set; }
public bool SiteOrderDoesHaveForum { get; set; }
public bool SiteOrderDoesHaveSearch { get; set; }
public string SiteOrderSearchType { get; set; }
//misc feature info - step6
public bool SiteOrderDoesUseGoogleMap { get; set; }
public bool SiteOrderDoesUseGoogleAnalytics { get; set; }
public bool SiteOrderDoesUseSocialMedia { get; set; }
public bool SiteOrderDoesIncludeChart { get; set; }
public bool SiteOrderDoesIncludeDynamicChart { get; set; }
public bool SiteOrderDoesIncludeAdvancedReport { get; set; }
public bool SiteOrderDoesIncludeDomainAndHosting { get; set; }
public bool SiteOrderDoesSupportIncluded { get; set; }
public bool SiteOrderDoesHaveFaq { get; set; }
public bool SiteOrderDoesHaveComplexFooter { get; set; }
//check out info - step7
public string SiteOrderFullName { get; set; }
public string SiteOrderEmail { get; set; }
public string SiteOrderPhone { get; set; }
public string SiteOrderDesc { get; set; }
public string SiteOrderTimeToDeliverMonth { get; set; }
public string SiteOrderExample { get; set; }
public string SiteOrderHowFindUs { get; set; }
//final price info
public decimal? SiteOrderFinalPrice { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Graph
{
class GreedyColAlgorithm
{
public static Grapher<VertexBase> ColorVertices(Grapher<VertexBase> graphToColor)
{
var graph = graphToColor.Clone();
graph.Vertices.ForEach(v => v.Color = int.MaxValue);
foreach (var v in graph.Vertices)
{
var adjacentColors = from i in graph.Neighbours(v)
where i.Color != int.MaxValue
select i.Color;
v.Color = Enumerable.Range(0, adjacentColors.MaxOrDefault() + 2)
.Except(adjacentColors)
.Min();
}
return graph;
}
public static Grapher<VertexBase> ColorVerticesPrefilled(Grapher<VertexBase> graphToColor)
{
var graph = graphToColor.Clone();
foreach(var v in graph.Vertices)
{
if(v.Color == -1)
{
v.Color = int.MaxValue;
}
}
foreach (var v in graph.Vertices)
{
var adjacentColors = from i in graph.Neighbours(v)
where i.Color != int.MaxValue
select i.Color;
v.Color = Enumerable.Range(0, adjacentColors.MaxOrDefault() + 2)
.Except(adjacentColors)
.Min();
}
return graph;
}
public static Grapher<VertexBase> ColorVerticesVar(Grapher<VertexBase> graphToColor)
{
var graph = graphToColor.Clone();
graph.Vertices.ForEach(v => v.Color = int.MaxValue);
VertexBase vertex;
while ((vertex = graph.Vertices.FirstOrDefault(v => v.Color == int.MaxValue)) != null)
{
var adjacentColors = from i in graph.Neighbours(vertex)
where i.Color != int.MaxValue
select i.Color;
vertex.Color = Enumerable.Range(0, adjacentColors.MaxOrDefault() + 2)
.Except(adjacentColors)
.Min();
}
return graph;
}
public static Grapher<VertexBase> ColorVerticesVarRandom(Grapher<VertexBase> graphToColor)
{
var graph = graphToColor.Clone();
graph.Vertices.ForEach(v => v.Color = int.MaxValue);
VertexBase vertex;
while ((vertex = graph.Vertices.Where(v => v.Color == int.MaxValue).RandomElementOrDefault()) != null)
{
var adjacentColors = from i in graph.Neighbours(vertex)
where i.Color != int.MaxValue
select i.Color;
vertex.Color = Enumerable.Range(0, adjacentColors.MaxOrDefault() + 2)
.Except(adjacentColors)
.Min();
}
return graph;
}
public static Grapher<VertexBase> ColorVerticesVarPrefilledRandom(Grapher<VertexBase> graphToColor)
{
int maxColorCount = -1;
var graph = graphToColor.Clone();
foreach (var v in graph.Vertices)
{
if (v.Color == -1)
{
v.Color = int.MaxValue;
}
}
VertexBase vertex;
while ((vertex = graph.Vertices.Where(v => v.Color == int.MaxValue).RandomElementOrDefault()) != null)
{
var adjacentColors = from i in graph.Neighbours(vertex)
where i.Color != int.MaxValue
select i.Color;
vertex.Color = Enumerable.Range(0, adjacentColors.MaxOrDefault() + 2)
.Except(adjacentColors)
.Min();
if(vertex.Color >= maxColorCount)
{
maxColorCount = vertex.Color;
}
}
Console.WriteLine("Max Color Count: " + (maxColorCount + 1));
return graph;
}
}
}
|
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Channels
{
using System;
static class RedirectionConstants
{
public const string AddressElementName = "Address";
public const string LocationElementName = "Location";
public const string Namespace = "http://schemas.microsoft.com/ws/2008/06/redirect";
public const string Prefix = "r";
public const string RedirectionElementName = "Redirection";
internal static class Duration
{
public const string Permanent = "Permanent";
public const string Temporary = "Temporary";
public const string XmlName = "duration";
}
internal static class Scope
{
public const string Endpoint = "Endpoint";
public const string Message = "Message";
public const string Session = "Session";
public const string XmlName = "scope";
}
internal static class Type
{
public const string Cache = "Cache";
public const string Resource = "Resource";
public const string UseIntermediary = "UseIntermediary";
public const string XmlName = "type";
}
}
}
|
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
/// <summary>
/// Represents a highscores list.
/// </summary>
[Serializable]
public class Highscores
{
private const string HIGHSCORES_FILE = "Alphabet.SpaceShooter.Unity.3D.Highscores.dat";
public List<HighscoreEntry> Entries { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="Highscores"/> class.
/// </summary>
public Highscores ()
{
Entries = new List<HighscoreEntry> ();
}
/// <summary>
/// Deserializes the highscores.
/// </summary>
/// <returns>The highscores.</returns>
public static Highscores DeserializeHighscores ()
{
string filename = Path.Combine (Application.persistentDataPath, HIGHSCORES_FILE);
Highscores result = null;
if (File.Exists (filename)) {
try {
BinaryFormatter formatter = new BinaryFormatter ();
using (FileStream fs = File.Open(filename, FileMode.Open)) {
result = (Highscores)formatter.Deserialize (fs);
fs.Close ();
}
} catch (Exception ex) {
Debug.LogError (ex.Message);
}
}
if (result == null) {
result = new Highscores ();
}
return(result);
}
/// <summary>
/// Serializes the highscores.
/// </summary>
/// <param name="target">Target.</param>
public static void SerializeHighscores (Highscores target)
{
string filename = Path.Combine (Application.persistentDataPath, HIGHSCORES_FILE);
try {
BinaryFormatter formatter = new BinaryFormatter ();
using (FileStream fs = File.Open(filename, FileMode.OpenOrCreate)) {
if (fs.Length > 0) {
fs.SetLength (0);
}
formatter.Serialize (fs, target);
fs.Close ();
}
} catch (Exception ex) {
Debug.LogError (ex.Message);
}
}
}
/// <summary>
/// Represents a highscore entry.
/// </summary>
[Serializable]
public class HighscoreEntry
{
/// <summary>
/// Gets or sets the score.
/// </summary>
/// <value>The score.</value>
public int Score { get; set; }
/// <summary>
/// Gets or sets the shots fired.
/// </summary>
/// <value>The shots fired.</value>
public int ShotsFired { get; set; }
/// <summary>
/// Gets or sets the enemy ships destroyed.
/// </summary>
/// <value>The enemy ships destroyed.</value>
public int EnemyShipsDestroyed { get; set; }
/// <summary>
/// Gets or sets the enemy asteroids destroyed.
/// </summary>
/// <value>The enemy asteroids destroyed.</value>
public int EnemyAsteroidsDestroyed { get; set; }
/// <summary>
/// Gets or sets the text enemies destroyed.
/// </summary>
/// <value>The text enemies destroyed.</value>
public int TextEnemiesDestroyed { get; set; }
/// <summary>
/// Gets or sets the name of the player.
/// </summary>
/// <value>The name of the player.</value>
public string PlayerName { get; set; }
/// <summary>
/// Gets or sets the highscore date.
/// </summary>
/// <value>The highscore date.</value>
public DateTime HighscoreDate { get; set; }
}
|
using Moq;
using NUnit.Framework;
[TestFixture]
public class WeaversConfiguredInstanceLinkerTests
{
[Test]
public void CustomWeaverInWeaversProject()
{
var mock = new Mock<Processor>();
mock.Setup(x => x.WeaverProjectContainsType("CustomWeaver"))
.Returns(true);
mock.CallBase = true;
var processor = mock.Object;
processor.WeaverAssemblyPath = "Path";
var weaverConfig = new WeaverEntry
{
AssemblyName = "CustomWeaver"
};
processor.ProcessConfig(weaverConfig);
Assert.AreEqual("CustomWeaver", weaverConfig.TypeName);
Assert.AreEqual("Path",weaverConfig.AssemblyPath);
}
[Test]
public void WeaverInAddin()
{
var mock = new Mock<Processor>();
mock.Setup(x => x.WeaverProjectContainsType("AddinName"))
.Returns(false);
mock.Setup(x => x.FindAssemblyPath("AddinName")).Returns("Path");
mock.CallBase = true;
var processor = mock.Object;
var weaverConfig = new WeaverEntry
{
AssemblyName = "AddinName"
};
processor.ProcessConfig(weaverConfig);
Assert.AreEqual("ModuleWeaver", weaverConfig.TypeName);
Assert.AreEqual("Path",weaverConfig.AssemblyPath);
mock.Verify();
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using Behemoth.Util;
namespace Behemoth.Apps
{
/// <summary>
/// Component-based App class.
/// </summary>
public class App
{
public App()
{
if (App.instance != null)
{
throw new ApplicationException("Trying to instantiate multiple Apps.");
}
App.instance = this;
}
/// <summary>
/// Get the singleton App instance.
/// </summary>
public static App Instance { get { return instance; } }
/// <summary>
/// Shortcut for App.Instance.GetService<T>().
/// </summary>
public static T Service<T>() where T : IAppService
{
return Instance.GetService<T>();
}
public T GetService<T>() where T : IAppService
{
return (T)services[typeof(T)];
}
public bool TryGetService<T>(out T service) where T : IAppService
{
IAppService s;
if (services.TryGetValue(typeof(T), out s))
{
service = (T)s;
return true;
}
else
{
service = default(T);
return false;
}
}
public bool ContainsService(Type serviceType)
{
return services.ContainsKey(serviceType);
}
public void RegisterService(Type service, IAppService provider)
{
if (service.GetInterface("Behemoth.Apps.IAppService") == null)
{
throw new ArgumentException(
"Service type doesn't implement service base interface.",
"service");
}
if (!service.IsInstanceOfType(provider))
{
throw new ArgumentException(
"Provider does not implement the specified interface.",
"provider");
}
IAppService oldService;
if (services.TryGetValue(service, out oldService))
{
oldService.Uninit();
}
services[service] = provider;
provider.Init();
}
protected void UninitServices()
{
foreach (var serv in services.Values)
{
serv.Uninit();
}
}
public void Run()
{
try
{
InitApp();
AppMain();
}
finally
{
UninitApp();
UninitServices();
}
}
protected virtual void InitApp() {}
/// <summary>
/// The main function of the app, called from Run.
/// </summary>
protected virtual void AppMain() {}
protected virtual void UninitApp() {}
private IDictionary<Type, IAppService> services =
new Dictionary<Type, IAppService>();
private static App instance = null;
}
}
|
using System;
using XElement.CloudSyncHelper.InstalledPrograms;
namespace XElement.CloudSyncHelper.UI.Win32.DataTypes
{
#region not unit-tested
public class InstalledProgramViewModel
{
public InstalledProgramViewModel( IInstalledProgram installedProgram )
{
this._installedProgram = installedProgram;
}
public string DisplayName
{
get { return this._installedProgram.DisplayName ?? String.Empty; }
}
public string InstallLocation
{
get { return this._installedProgram.InstallLocation ?? String.Empty; }
}
private IInstalledProgram _installedProgram;
}
#endregion
}
|
using FossLock.Model.Base;
namespace FossLock.Model
{
/// <summary>
/// An individual version of a product.
/// In FossLock, <see cref="Customers"/> actually license a particular
/// ProductVersion, instead of the Product itself.
/// </summary>
public class Version : EntityBase
{
/// <summary>
/// String representation of the versioning data.
/// This string must be parsable to either a <see cref="System.Version"/> instance
/// or a <see cref="Summerset.SemanticVersion"/> instance, depending on which type
/// is being used for the product.
/// </summary>
public string Version { get; set; }
/// <summary>
/// A reference to the <see cref="Product"/> this
/// version is associated with.
/// </summary>
public virtual Product Product { get; set; }
}
} |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace UnityStandardAssets.Utility
{
public class ObjectResetter : MonoBehaviour
{
private Vector3 originalPosition;
private Quaternion originalRotation;
private List<Transform> originalStructure;
private Rigidbody Rigidbody;
// Use this for initialization
private void Start()
{
originalStructure = new List<Transform>(GetComponentsInChildren<Transform>());
originalPosition = transform.position;
originalRotation = transform.rotation;
Rigidbody = GetComponent<Rigidbody>();
}
public void DelayedReset(float delay)
{
StartCoroutine(ResetCoroutine(delay));
}
public IEnumerator ResetCoroutine(float delay)
{
yield return new WaitForSeconds(delay);
// remove any gameobjects added (fire, skid trails, etc)
foreach (var t in GetComponentsInChildren<Transform>())
{
if (!originalStructure.Contains(t))
{
t.parent = null;
}
}
transform.position = originalPosition;
transform.rotation = originalRotation;
if (Rigidbody)
{
Rigidbody.velocity = Vector3.zero;
Rigidbody.angularVelocity = Vector3.zero;
}
SendMessage("Reset");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using Tedd.ModuleLoader.Test.Common;
namespace Tedd.ModuleLoader.Test.Module1
{
public class ArgsModule : ICtorArgsModule
{
public string Arg1 { get; private set; }
public int Arg2 { get; private set; }
public ArgsModule(string arg1, int arg2)
{
Arg1 = arg1;
Arg2 = arg2;
}
}
}
|
using System;
namespace Biglab.Remote.Client
{
[Serializable]
public enum ElementType
{
Button,
InputField,
Dropdown,
Slider,
Toggle,
Label
};
} |
using Mindstorms.Core.Enums;
namespace Mindstorms.Core.Commands.Mathematics.Arithmetic
{
public class Or : TwoOperatorOperand
{
public Or(byte value1, byte value2)
: base (value1, value2, OpCode.Or8)
{ }
public Or(short value1, short value2)
: base(value1, value2, OpCode.Or16)
{ }
public Or(int value1, int value2)
: base(value1, value2, OpCode.Or32)
{ }
}
}
|
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
namespace KF.GoogleUrlShortenerApi
{
public class UrlShortener
{
private readonly string _apiKey;
private readonly string _uri;
private const string DefaultUri = "https://www.googleapis.com/urlshortener/v1/url";
public UrlShortener(string apiKey, string uri = DefaultUri)
{
_apiKey = apiKey;
_uri = uri;
}
public async Task<ShortenResult> Shorten(string longUrl)
{
var httpClient = new HttpClient();
var uri = $"{_uri}?key={_apiKey}";
var content = new { longUrl };
var typeFormatter = new JsonMediaTypeFormatter();
var response = await httpClient.PostAsync(uri, content, typeFormatter);
var json = await response.Content.ReadAsStringAsync();
var jObject = JObject.Parse(json);
if (response.IsSuccessStatusCode)
{
return new ShortenResult
{
Ok = true,
Kind = jObject.Value<string>("kind"),
Id = jObject.Value<string>("id"),
LongUrl = jObject.Value<string>("longUrl"),
Status = jObject.Value<string>("status")
};
}
var error = jObject.Value<JObject>("error");
var errors = error.Value<JArray>("errors");
return new ShortenResult
{
Error = new Error
{
Errors = errors.Select(x => new ErrorDescription
{
Domain = x.Value<string>("domain"),
Reason = x.Value<string>("reason"),
Message = x.Value<string>("message"),
Location = x.Value<string>("location"),
LocationType = x.Value<string>("locationType")
}).ToArray(),
Code = error.Value<int>("code"),
Message = error.Value<string>("message"),
}
};
}
}
public class ShortenResult
{
public bool Ok { get; set; } = false;
public string Kind { get; set; }
public string Id { get; set; }
public string LongUrl { get; set; }
public string Status { get; set; }
public Error Error { get; set; }
}
public class Error
{
public ErrorDescription[] Errors { get; set; }
public int Code { get; set; }
public string Message { get; set; }
}
public class ErrorDescription
{
public string Domain { get; set; }
public string Reason { get; set; }
public string Message { get; set; }
public string LocationType { get; set; }
public string Location { get; set; }
}
}
|
@model cloudscribe.Core.IdentityServerIntegration.Models.ClientEditViewModel
@using cloudscribe.Core.IdentityServerIntegration
@using Microsoft.Extensions.Localization
@inject IStringLocalizer<CloudscribeIds4Resources> sr
<div class="row">
<div class="col-md-10 col-md-push-2">
@if (Model.CurrentClient == null)
{
<h2>@ViewData["Title"]</h2>
await Html.RenderPartialAsync("NewClientPartial", Model.NewClient);
}
else
{
<h2>@ViewData["Title"]</h2>
await Html.RenderPartialAsync("EditClientPartial", Model.CurrentClient);
await Html.RenderPartialAsync("ClientRedirectsPartial", Model.CurrentClient);
await Html.RenderPartialAsync("ClientLogoutRedirectsPartial", Model.CurrentClient);
await Html.RenderPartialAsync("ClientAllowedCorsOriginsPartial", Model.CurrentClient);
await Html.RenderPartialAsync("ClientSecretsPartial", Model.CurrentClient);
await Html.RenderPartialAsync("ClientClaimsPartial", Model.CurrentClient);
await Html.RenderPartialAsync("ClientAllowedGrantTypesPartial", Model.CurrentClient);
await Html.RenderPartialAsync("ClientAllowedScopesPartial", Model.CurrentClient);
await Html.RenderPartialAsync("ClientProviderRestrictionsPartial", Model.CurrentClient);
await Html.RenderPartialAsync("ClientPropertiesPartial", Model.CurrentClient);
}
</div>
<div class="col-md-2 col-md-pull-10">
@await Component.InvokeAsync("Navigation", new { viewName = "SideNavAlt1", filterName = NamedNavigationFilters.ParentTree, startingNodeKey = "SiteAdmin" })
</div>
</div>
@section Scripts {
@{ await Html.RenderPartialAsync("_SideMenuScriptsPartial"); }
@{await Html.RenderPartialAsync("_UnobtrusiveValidationScriptsPartial"); }
}
|
using UnityEngine;
using System.Collections;
public class MainMenuDropdownHandler : MonoBehaviour {
private DropdownMenu Menu = null;
private MenuScroller Scroller = null;
void Start ()
{
Menu = FindObjectOfType<DropdownMenu>();
Scroller = FindObjectOfType<MenuScroller>();
Menu.Hide();
Menu.StatsMenu.CreateStats();
}
public void OptionsPressed()
{
StartCoroutine("ShowOptions");
}
private IEnumerator ShowOptions()
{
float WaitTime = Scroller.StatsScreen();
yield return new WaitForSeconds(WaitTime);
Menu.ShowOptions();
}
public void OptionsBackPressed()
{
StartCoroutine("HideDropdown", false);
}
private IEnumerator HideDropdown(bool bStatsMenu)
{
float WaitTime = Menu.RaiseMenu();
yield return new WaitForSeconds(WaitTime);
Scroller.MainMenu();
if (bStatsMenu)
{
Menu.StatsMenu.Hide();
}
}
public void StatsPressed()
{
StartCoroutine("ShowStats");
}
private IEnumerator ShowStats()
{
float WaitTime = Scroller.StatsScreen();
yield return new WaitForSeconds(WaitTime);
Menu.ShowStats();
}
public void StatsBackPressed()
{
StartCoroutine("HideDropdown", true);
}
}
|
using System;
using System.Collections.Generic;
namespace Inventor.Semantics.WPF.ViewModels
{
internal class ConceptDecorator : IConcept
{
#region Properties
public ILocalizedString Name
{ get { return Concept.Name; } }
public String ID
{ get { return Concept.ID; } }
public ILocalizedString Hint
{ get { return Concept.Hint; } }
public ICollection<IAttribute> Attributes
{ get { return Concept.Attributes; } }
public IConcept Concept
{ get; }
private readonly ILanguage _language;
#endregion
public ConceptDecorator(IConcept concept, ILanguage language)
{
Concept = concept;
_language = language;
}
public override string ToString()
{
return Concept.Name.GetValue(_language);
}
}
}
|
using IMDBProject.DAL.RepositoryConcrete;
using IMDBProject.Entities.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using IMDBProject.Entities.DTO;
namespace IMDBProject.BLL.IMDBService
{
public class DirectorService
{
DirectorRepository _directorRepository;
public DirectorService()
{
_directorRepository = new DirectorRepository();
}
public int AddDirectorService(Director director)
{
try
{
return _directorRepository.AddItem(director);
}
catch (Exception e)
{
MessageBox.Show("Hata:{0}", e.Message);
return 0;
}
}
public int DeleteDirectorService(Director director)
{
try
{
return _directorRepository.DeleteItem(director);
}
catch (Exception e)
{
MessageBox.Show("Hata:{0}", e.Message);
return 0; ;
}
}
public List<Director> GetAllDirectorService()
{
return _directorRepository.GetAll().ToList();
}
public int UpdateDirectorService(Director director)
{
return _directorRepository.UpdateItem(director);
}
public Director GetByIdDirectorService(int id)
{
return _directorRepository.GetById(id);
}
public List<DirectorRatingDTO> GetDirectorTopFive(Director director)
{
return _directorRepository.DirectorTopFiveFilm(director).ToList();
}
}
}
|
using System;
using it.unifi.dsi.stlab.networkreasoner.gas.system.exactly_dimensioned_instance.listeners;
namespace it.unifi.dsi.stlab.networkreasoner.model.textualinterface
{
public class RunnableSystemComputeGivenEventListener : RunnableSystemCompute
{
public NetwonRaphsonSystemEventsListener EventListener { get; set; }
protected override NetwonRaphsonSystemEventsListener buildEventListener ()
{
return EventListener;
}
}
}
|
using System;
namespace Rafty
{
public class RemoteServerLocation
{
public RemoteServerLocation(string url, Guid id)
{
this.Url = url;
}
public string Url { get; private set; }
public Guid Id { get; private set; }
}
} |
using System.ComponentModel.DataAnnotations;
using System.Xml.Serialization;
namespace MusicHub.DataProcessor.ImportDtos
{
[XmlType("Song")]
public class PerformerSongsDto
{
[XmlAttribute("id")]
public int SongId { get; set; }
}
}
|
using TrickingRoyal.Database;
using Battles.Application.ViewModels;
using MediatR;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Battles.Application.Services.Users.Queries;
using Battles.Enums;
using Transmogrify;
namespace Battles.Application.Services.Users.Commands
{
public class UpdateUserCommand : IRequest<BaseResponse>
{
[Required] [StringLength(15)] public string DisplayName { get; set; }
[Required] public int Skill { get; set; }
[StringLength(255)] public string Information { get; set; }
[StringLength(30)] public string City { get; set; }
[StringLength(30)] public string Country { get; set; }
[StringLength(40)] public string Gym { get; set; }
[StringLength(100)] public string Instagram { get; set; }
[StringLength(100)] public string Facebook { get; set; }
[StringLength(100)] public string Youtube { get; set; }
public string UserId { get; set; }
public UpdateUserCommand AttachUserId(string id)
{
UserId = id;
return this;
}
}
public class UpdateUserCommandHandler : IRequestHandler<UpdateUserCommand, BaseResponse>
{
private readonly AppDbContext _ctx;
private readonly IMediator _mediator;
private readonly ITranslator _translation;
public UpdateUserCommandHandler(
AppDbContext ctx,
IMediator mediator,
ITranslator translation)
{
_ctx = ctx;
_mediator = mediator;
_translation = translation;
}
public async Task<BaseResponse> Handle(UpdateUserCommand request, CancellationToken cancellationToken)
{
var user = _ctx.UserInformation
.FirstOrDefault(x => x.Id == request.UserId);
if (user == null)
return BaseResponse.Fail(await _translation.GetTranslation("User", "NotFound"));
var newDisplayName = request.DisplayName.Replace(" ", "_");
var nameAvailable = await _mediator.Send(new UserNameAvailableQuery
{
DisplayName = newDisplayName,
UserId = request.UserId
}, cancellationToken);
if (!nameAvailable)
return BaseResponse.Fail(await _translation.GetTranslation("User", "UsernameTaken"));
user.DisplayName = newDisplayName;
user.Skill = (Skill) request.Skill;
user.City = request.City;
user.Country = request.Country;
user.Gym = request.Gym;
user.Information = request.Information;
user.Instagram = request.Instagram;
user.Facebook = request.Facebook;
user.Youtube = request.Youtube;
if (_ctx.ChangeTracker.HasChanges())
await _ctx.SaveChangesAsync(cancellationToken);
return BaseResponse.Ok(await _translation.GetTranslation("User", "ProfileSaved"));
}
}
} |
//------------------------------------------------------------------------------
// <auto-generated>
// 此代码由工具生成。
// 运行时版本:4.0.30319.42000
//
// 对此文件的更改可能会导致不正确的行为,并且如果
// 重新生成代码,这些更改将会丢失。
// </auto-generated>
//------------------------------------------------------------------------------
namespace App.Properties {
using System;
/// <summary>
/// 一个强类型的资源类,用于查找本地化的字符串等。
/// </summary>
// 此类是由 StronglyTypedResourceBuilder
// 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。
// 若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen
// (以 /str 作为命令选项),或重新生成 VS 项目。
[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>
/// 返回此类使用的缓存的 ResourceManager 实例。
/// </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("App.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// 重写当前线程的 CurrentUICulture 属性
/// 重写当前线程的 CurrentUICulture 属性。
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// 查找类似 {
/// // Version
/// "version": "20181118.1",
///
/// // Duty
/// "instances": {
/// //单人使命 PVP 金碟游乐场
/// "2334": {
/// "name": "Recondition the Anima",
/// "tank": "0",
/// "healer": "0",
/// "dps": "0"
/// },
/// "3088": {
/// "name": "Recall of Duty",
/// "tank": "0",
/// "healer": "0",
/// "dps": "0"
/// },
/// "167": {
/// "name": "a Spectacle for the Ages",
/// "tank": "0",
/// "healer": "0",
/// "dps": "0"
/// },
/// "173": {
/// "name": "a Bloody Reunion",
/// "tank": "0",
/// "healer": "0",
/// "dps": "0"
/// },
/// "179": {
/// "name": "the Aqua [字符串的其余部分被截断]"; 的本地化字符串。
/// </summary>
internal static string Data_EN_US {
get {
return ResourceManager.GetString("Data_EN_US", resourceCulture);
}
}
/// <summary>
/// 查找类似 {
/// // Version
/// "version": "20181118.1",
///
/// // Duty
/// "instances": {
/// //单人使命 PVP 金碟游乐场
/// "2334": {
/// "name": "Un nouvel épanouissement",
/// "tank": "0",
/// "healer": "0",
/// "dps": "0"
/// },
/// "3088": {
/// "name": "La ballade des réminiscences",
/// "tank": "0",
/// "healer": "0",
/// "dps": "0"
/// },
/// "167": {
/// "name": "La grande manœuvre éorzéenne",
/// "tank": "0",
/// "healer": "0",
/// "dps": "0"
/// },
/// "173": {
/// "name": "Course-poursuite dans le laboratoire",
/// "tank": "0",
/// "healer": "0",
/// "dps [字符串的其余部分被截断]"; 的本地化字符串。
/// </summary>
internal static string Data_FR_FR {
get {
return ResourceManager.GetString("Data_FR_FR", resourceCulture);
}
}
/// <summary>
/// 查找类似 {
/// // Version
/// "version": "20181118.1",
///
/// // Duty
/// "instances": {
/// //单人使命 PVP 金碟游乐场
/// "2334": {
/// "name": "人造精霊の再調整",
/// "tank": "0",
/// "healer": "0",
/// "dps": "0"
/// },
/// "3088": {
/// "name": "再演の叙事詩",
/// "tank": "0",
/// "healer": "0",
/// "dps": "0"
/// },
/// "167": {
/// "name": "四国合同演習",
/// "tank": "0",
/// "healer": "0",
/// "dps": "0"
/// },
/// "173": {
/// "name": "レグラ・ヴァン・ヒュドルス追撃戦",
/// "tank": "0",
/// "healer": "0",
/// "dps": "0"
/// },
/// "179": {
/// "name": "宝物庫 アクアポリス",
/// "tank": "0",
/// "healer": "0", [字符串的其余部分被截断]"; 的本地化字符串。
/// </summary>
internal static string Data_JA_JP {
get {
return ResourceManager.GetString("Data_JA_JP", resourceCulture);
}
}
/// <summary>
/// 查找类似 {
/// // 버전
/// "version": "20181118.1",
///
/// // 임무
/// "instances": {
/// // 2.0 신생 에오르제아
/// // 2.0 던전
/// "4": {
/// "name": "사스타샤 침식 동굴",
/// "tank": "1",
/// "healer": "1",
/// "dps": "2"
/// },
/// "8": {
/// "name": "브레이플록스의 야영지",
/// "tank": "1",
/// "healer": "1",
/// "dps": "2"
/// },
/// "10": {
/// "name": "방랑자의 궁전",
/// "tank": "1",
/// "healer": "1",
/// "dps": "2"
/// },
/// "3": {
/// "name": "구리종 광산",
/// "tank": "1",
/// "healer": "1",
/// [字符串的其余部分被截断]"; 的本地化字符串。
/// </summary>
internal static string Data_KO_KR {
get {
return ResourceManager.GetString("Data_KO_KR", resourceCulture);
}
}
/// <summary>
/// 查找类似 {
/// // Version
/// "version": "20181204.1",
///
/// // Duty
/// "instances": {
/// //单人使命 PVP 金碟游乐场
/// "2334": {
/// "name": "重新调整人造元灵",
/// "tank": "0",
/// "healer": "0",
/// "dps": "0"
/// },
/// "3088": {
/// "name": "回顾英雄诗篇",
/// "tank": "0",
/// "healer": "0",
/// "dps": "0"
/// },
/// "167": {
/// "name": "四国联合军演",
/// "tank": "0",
/// "healer": "0",
/// "dps": "0"
/// },
/// "173": {
/// "name": "雷古拉·范·休著斯追击战",
/// "tank": "0",
/// "healer": "0",
/// "dps": "0"
/// },
/// "179": {
/// "name": "水城宝物库",
/// "tank": "0",
/// "healer": "0",
/// "dps": "0"
/// },
/// "181": {
/// "name": [字符串的其余部... 的本地化字符串。
/// </summary>
internal static string Data_ZH_CN {
get {
return ResourceManager.GetString("Data_ZH_CN", resourceCulture);
}
}
/// <summary>
/// 查找类似于 (图标) 的 System.Drawing.Icon 类型的本地化资源。
/// </summary>
internal static System.Drawing.Icon icon {
get {
object obj = ResourceManager.GetObject("icon", resourceCulture);
return ((System.Drawing.Icon)(obj));
}
}
/// <summary>
/// 查找类似 {
/// "app-name": "Duty/FATE Notificator",
///
/// "tts-langset": "en",
///
/// "unknown-instance": "Unknown Duty ({0})",
/// "unknown-roulette": "Unknown Roulette ({0})",
/// "unknown-area": "Unknown Area ({0})",
/// "unknown-fate": "Unknown FATE ({0})",
///
///
/// "notification-app-updated": "Version {0} Updated",
/// "notification-queue-matched": "< {0} > Matched!",
/// "notification-update-enabled": "Updateable to {0}",
/// "notification-uptodate": "Updating to {0}",
/// "notification-update-latest": "Already the latest version",
/// " [字符串的其余部分被截断]"; 的本地化字符串。
/// </summary>
internal static string Localization_EN_US {
get {
return ResourceManager.GetString("Localization_EN_US", resourceCulture);
}
}
/// <summary>
/// 查找类似 {
/// "app-name": "Notificateur Mission/ALEA",
///
/// "tts-langset": "fra",
///
/// "unknown-instance": "Mission inconnue ({0})",
/// "unknown-roulette": "Mission aléatoire inconnue ({0})",
/// "unknown-area": "Zone inconnue ({0})",
/// "unknown-fate": "ALEA inconnu ({0})",
///
///
/// "notification-app-updated": "Mise à jour version {0}",
/// "notification-queue-matched": "< {0} > disponible!",
/// "notification-update-enabled": "mises à la {0}",
/// "notification-uptodate": "la mise à jour de la {0}",
/// "notification-update-latest": [字符串的其余部分被截断]"; 的本地化字符串。
/// </summary>
internal static string Localization_FR_FR {
get {
return ResourceManager.GetString("Localization_FR_FR", resourceCulture);
}
}
/// <summary>
/// 查找类似 {
/// "app-name": "Duty/FATE Notificator",
///
/// "tts-langset": "jp",
///
/// "unknown-instance": "不明なコンテンツ ({0})",
/// "unknown-roulette": "不明なルーレット ({0})",
/// "unknown-area": "不明なエリア ({0})",
/// "unknown-fate": "不明なFATE ({0})",
///
///
/// "notification-app-updated": "バージョン {0} に更新されました",
/// "notification-queue-matched": "< {0} > 突入準備完了!",
/// "notification-update-enabled": "Updateable to {0}",
/// "notification-uptodate": "Updating to {0}",
/// "notification-update-latest": "Already the latest version",
/// "notification-dll-missing" [字符串的其余部分被截断]"; 的本地化字符串。
/// </summary>
internal static string Localization_JA_JP {
get {
return ResourceManager.GetString("Localization_JA_JP", resourceCulture);
}
}
/// <summary>
/// 查找类似 {
/// "app-name": "임무/돌발 찾기 도우미",
///
/// "tts-langset": "kor",
///
/// "unknown-instance": "알 수 없는 임무 ({0})",
/// "unknown-roulette": "알 수 없는 무작위 임무 ({0})",
/// "unknown-area": "알 수 없는 지역 ({0})",
/// "unknown-fate": "알 수 없는 돌발 ({0})",
///
///
/// "notification-app-updated": "버전 {0} 업데이트됨",
/// "notification-queue-matched": "< {0} > 매칭!",
/// "notification-update-enabled": "{0} 까지 업데이트할 수 있어요",
/// "notification-uptodate": "{0} 를 업데이트하고 있습니다",
/// "notification-update-latest": "최신 버전을 이용중입니다",
/// "notification-dll-missing": "Missing compon [字符串的其余部分被截断]"; 的本地化字符串。
/// </summary>
internal static string Localization_KO_KR {
get {
return ResourceManager.GetString("Localization_KO_KR", resourceCulture);
}
}
/// <summary>
/// 查找类似 {
/// "app-name": "任务/FATE 助手 - DFA",
///
/// "tts-langset": "zh",
///
/// "unknown-instance": "未知任务 ({0})",
/// "unknown-roulette": "未知随机任务 ({0})",
/// "unknown-area": "未知地区 ({0})",
/// "unknown-fate": "未知FATE ({0})",
///
///
/// "notification-app-updated": "已更新至版本 {0} ",
/// "notification-queue-matched": "< {0} > 匹配完成!",
/// "notification-update-enabled": "可更新至新版本 {0}",
/// "notification-uptodate": "正在更新至版本 {0}",
/// "notification-update-latest": "更新检查完成,暂无更新",
/// "notification-dll-missing": "缺失组件[{0}],正在联网获取",
/// "notification-dll-invalid" [字符串的其余部分被截断]"; 的本地化字符串。
/// </summary>
internal static string Localization_ZH_CN {
get {
return ResourceManager.GetString("Localization_ZH_CN", resourceCulture);
}
}
}
}
|
namespace Primordially.LstToLua
{
internal class EquipmentBonus : Bonus
{
public EquipmentBonus(TextSpan value) : base(value)
{
}
public override bool IsEquipment => true;
}
} |
using System;
using System.Linq;
using System.Collections.Generic;
using System.IO;
using numl.Serialization;
using numl.Supervised.NeuralNetwork;
using numl.Supervised.NeuralNetwork.Recurrent;
using numl.Utils;
using numl.Math.Functions;
namespace numl.Supervised.NeuralNetwork.Serializer.Recurrent
{
/// <summary>
/// Recurrent Node serializer.
/// </summary>
public class RecurrentNeuronSerializer : JsonSerializer<RecurrentNeuron>
{
/// <summary>
/// Deserializes the object from the stream.
/// </summary>
/// <param name="reader">Stream to read from.</param>
/// <returns>Node object.</returns>
public override object Read(JsonReader reader)
{
if (reader.IsNull()) return null;
else
{
var node = (RecurrentNeuron)this.Create();
node.Label = reader.ReadProperty().Value.ToString();
node.Id = (int)reader.ReadProperty().Value;
node.NodeId = (int)reader.ReadProperty().Value;
node.LayerId = (int)reader.ReadProperty().Value;
node.IsBias = (bool)reader.ReadProperty().Value;
var activation = reader.ReadProperty().Value;
if (activation != null)
node.ActivationFunction = Ject.FindType(activation.ToString()).CreateDefault<IFunction>();
node.Constrained = (bool) reader.ReadProperty().Value;
node.delta = (double)reader.ReadProperty().Value;
node.Delta = (double)reader.ReadProperty().Value;
node.Input = (double)reader.ReadProperty().Value;
node.Output = (double)reader.ReadProperty().Value;
node.H = (double) reader.ReadProperty().Value;
node.Hh = (double) reader.ReadProperty().Value;
node.R = (double) reader.ReadProperty().Value;
node.Rb = (double) reader.ReadProperty().Value;
node.Rh = (double) reader.ReadProperty().Value;
node.Rx = (double) reader.ReadProperty().Value;
var reset = reader.ReadProperty().Value;
if (reset != null)
node.ResetGate = Ject.FindType(reset.ToString()).CreateDefault<IFunction>();
node.Z = (double) reader.ReadProperty().Value;
node.Zb = (double) reader.ReadProperty().Value;
node.Zh = (double) reader.ReadProperty().Value;
node.Zx = (double) reader.ReadProperty().Value;
var update = reader.ReadProperty().Value;
if (update != null)
node.UpdateGate = Ject.FindType(update.ToString()).CreateDefault<IFunction>();
return node;
}
}
/// <summary>
/// Writes the Node object to the stream.
/// </summary>
/// <param name="writer">Stream to write to.</param>
/// <param name="value">Node object to write.</param>
public override void Write(JsonWriter writer, object value)
{
if (value == null)
writer.WriteNull();
else
{
var node = (RecurrentNeuron)value;
writer.WriteProperty(nameof(Neuron.Label), node.Label);
writer.WriteProperty(nameof(Neuron.Id), node.Id);
writer.WriteProperty(nameof(Neuron.NodeId), node.NodeId);
writer.WriteProperty(nameof(Neuron.LayerId), node.LayerId);
writer.WriteProperty(nameof(Neuron.IsBias), node.IsBias);
writer.WriteProperty(nameof(Neuron.ActivationFunction), node.ActivationFunction.GetType().FullName);
writer.WriteProperty(nameof(Neuron.Constrained), node.Constrained);
writer.WriteProperty(nameof(Neuron.delta), node.delta);
writer.WriteProperty(nameof(Neuron.Delta), node.Delta);
writer.WriteProperty(nameof(Neuron.Input), node.Input);
writer.WriteProperty(nameof(Neuron.Output), node.Output);
writer.WriteProperty(nameof(RecurrentNeuron.H), node.H);
writer.WriteProperty(nameof(RecurrentNeuron.Hh), node.Hh);
writer.WriteProperty(nameof(RecurrentNeuron.R), node.R);
writer.WriteProperty(nameof(RecurrentNeuron.Rb), node.Rb);
writer.WriteProperty(nameof(RecurrentNeuron.Rh), node.Rh);
writer.WriteProperty(nameof(RecurrentNeuron.Rx), node.Rx);
writer.WriteProperty(nameof(RecurrentNeuron.ResetGate), node.ResetGate.GetType().FullName);
writer.WriteProperty(nameof(RecurrentNeuron.Z), node.Z);
writer.WriteProperty(nameof(RecurrentNeuron.Zb), node.Zb);
writer.WriteProperty(nameof(RecurrentNeuron.Zh), node.Zh);
writer.WriteProperty(nameof(RecurrentNeuron.Zx), node.Zx);
writer.WriteProperty(nameof(RecurrentNeuron.UpdateGate), node.UpdateGate.GetType().FullName);
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
public class EditorCoroutine : IEnumerator
{
private Stack<IEnumerator> executionStack;
public EditorCoroutine(IEnumerator iterator)
{
this.executionStack = new Stack<IEnumerator>();
this.executionStack.Push(iterator);
}
public bool MoveNext()
{
IEnumerator i = this.executionStack.Peek();
if (i.MoveNext())
{
object result = i.Current;
if (result != null && result is IEnumerator)
{
this.executionStack.Push((IEnumerator)result);
}
return true;
}
else
{
if (this.executionStack.Count > 1)
{
this.executionStack.Pop();
return true;
}
}
return false;
}
public void Reset()
{
throw new System.NotSupportedException("This Operation Is Not Supported.");
}
public object Current
{
get { return this.executionStack.Peek().Current; }
}
public bool Find(IEnumerator iterator)
{
return this.executionStack.Contains(iterator);
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
namespace System.Linq.Expressions.Tests
{
internal class LocalsSignatureParser : SigParser
{
private readonly Stack<Type> _types = new Stack<Type>();
private readonly Stack<TypeCreator> _creators = new Stack<TypeCreator>();
private readonly ITokenResolver _tokenResolver;
private readonly ITypeFactory _typeFactory;
public LocalsSignatureParser(ITokenResolver tokenResolver, ITypeFactory typeFactory)
{
_tokenResolver = tokenResolver;
_typeFactory = typeFactory;
}
public bool Parse(byte[] sig, out Type[] types)
{
if (Parse(sig))
{
types = _types.Reverse().ToArray();
return true;
}
types = null;
return false;
}
private static Type ToType(byte corType)
{
switch (corType)
{
case ELEMENT_TYPE_VOID:
return typeof(void);
case ELEMENT_TYPE_BOOLEAN:
return typeof(bool);
case ELEMENT_TYPE_CHAR:
return typeof(char);
case ELEMENT_TYPE_I1:
return typeof(sbyte);
case ELEMENT_TYPE_U1:
return typeof(byte);
case ELEMENT_TYPE_I2:
return typeof(short);
case ELEMENT_TYPE_U2:
return typeof(ushort);
case ELEMENT_TYPE_I4:
return typeof(int);
case ELEMENT_TYPE_U4:
return typeof(uint);
case ELEMENT_TYPE_I8:
return typeof(long);
case ELEMENT_TYPE_U8:
return typeof(ulong);
case ELEMENT_TYPE_R4:
return typeof(float);
case ELEMENT_TYPE_R8:
return typeof(double);
case ELEMENT_TYPE_STRING:
return typeof(string);
case ELEMENT_TYPE_I:
return typeof(IntPtr);
case ELEMENT_TYPE_U:
return typeof(UIntPtr);
case ELEMENT_TYPE_OBJECT:
return typeof(object);
}
throw new NotSupportedException();
}
class TypeCreator
{
private readonly LocalsSignatureParser _parent;
private Inner _inner;
private bool _byRef;
public TypeCreator(LocalsSignatureParser parent)
{
_parent = parent;
}
public void Done()
{
_inner.Done(_parent._typeFactory, _parent._types);
if (_byRef)
{
new ByRefInner().Done(_parent._typeFactory, _parent._types);
}
}
public void TypeSimple(byte elemType)
{
_inner = new SimpleInner(ToType(elemType));
}
public void TypeSzArray()
{
_inner = new SzArrayInner();
}
public void ArrayShape()
{
_inner = new ArrayInner();
}
public void Rank(int rank)
{
((ArrayInner)_inner).Rank = rank;
}
public void GenericInst(int count)
{
_inner = new GenericInner(count);
}
public void ByRef()
{
_byRef = true;
}
public void TypePointer()
{
_inner = new PointerInner();
}
public void TypeValueType()
{
_inner = new TypeInner();
}
public void TypeClass()
{
_inner = new TypeInner();
}
public void TypeInternal(IntPtr ptr)
{
_inner = new SimpleInner(_parent._typeFactory.FromHandle(ptr));
}
internal void TypeDefOrRef(int token, byte indexType, int index)
{
Type type = _parent._tokenResolver.AsType(token);
((TypeInner)_inner).Resolve(type);
}
abstract class Inner
{
public abstract void Done(ITypeFactory factory, Stack<Type> stack);
}
class SimpleInner : Inner
{
private readonly Type _type;
public SimpleInner(Type type)
{
_type = type;
}
public override void Done(ITypeFactory factory, Stack<Type> stack)
{
stack.Push(_type);
}
}
class SzArrayInner : Inner
{
public override void Done(ITypeFactory factory, Stack<Type> stack)
{
stack.Push(factory.MakeArrayType(stack.Pop()));
}
}
class ArrayInner : Inner
{
public int Rank { get; set; }
public override void Done(ITypeFactory factory, Stack<Type> stack)
{
stack.Push(factory.MakeArrayType(stack.Pop(), Rank));
}
}
class ByRefInner : Inner
{
public override void Done(ITypeFactory factory, Stack<Type> stack)
{
stack.Push(factory.MakeByRefType(stack.Pop()));
}
}
class PointerInner : Inner
{
public override void Done(ITypeFactory factory, Stack<Type> stack)
{
stack.Push(factory.MakePointerType(stack.Pop()));
}
}
class TypeInner : Inner
{
private Type _type;
public override void Done(ITypeFactory factory, Stack<Type> stack)
{
stack.Push(_type);
}
public void Resolve(Type type)
{
_type = type;
}
}
class GenericInner : Inner
{
private readonly int _count;
public GenericInner(int count)
{
_count = count;
}
public override void Done(ITypeFactory factory, Stack<Type> stack)
{
var args = new Type[_count];
for (var i = args.Length - 1; i >= 0; i--)
{
args[i] = stack.Pop();
}
stack.Push(factory.MakeGenericType(stack.Pop(), args));
}
}
}
protected override void NotifyBeginType()
{
var creator = new TypeCreator(this);
if (_pendingByRef > 0)
{
_pendingByRef--;
creator.ByRef();
}
_creators.Push(creator);
}
protected override void NotifyEndType()
{
_creators.Pop().Done();
}
protected override void NotifyTypeSzArray()
{
_creators.Peek().TypeSzArray();
}
protected override void NotifyTypeSimple(byte elem_type)
{
_creators.Peek().TypeSimple(elem_type);
}
private int _pendingByRef;
protected override void NotifyByref()
{
_pendingByRef++;
}
protected override void NotifyTypePointer()
{
_creators.Peek().TypePointer();
}
protected override void NotifyVoid()
{
_types.Push(typeof(void));
}
protected override void NotifyTypeValueType()
{
_creators.Peek().TypeValueType();
}
protected override void NotifyTypeClass()
{
_creators.Peek().TypeClass();
}
protected override void NotifyTypeInternal(IntPtr ptr)
{
_creators.Peek().TypeInternal(ptr);
}
protected override void NotifyTypeDefOrRef(int token, byte indexType, int index)
{
_creators.Peek().TypeDefOrRef(token, indexType, index);
}
protected override void NotifyBeginArrayShape()
{
_creators.Peek().ArrayShape();
}
protected override void NotifyRank(int count)
{
_creators.Peek().Rank(count);
}
protected override void NotifyTypeGenericInst(int number)
{
_creators.Peek().GenericInst(number);
}
// NB: We can't stuff these in a System.Type, so won't forward them
protected override void NotifyNumSizes(int count) { }
protected override void NotifySize(int count) { }
protected override void NotifyNumLoBounds(int count) { }
protected override void NotifyLoBound(int count) { }
protected override void NotifyEndArrayShape() { }
protected override void NotifyTypedByref()
{
throw new NotImplementedException();
}
// NB: These are not needed for local signatures
protected override void NotifyBeginProperty(byte elem_type)
{
throw new NotImplementedException();
}
protected override void NotifyEndProperty()
{
throw new NotImplementedException();
}
protected override void NotifyBeginMethod(byte elem_type)
{
throw new NotImplementedException();
}
protected override void NotifyEndMethod()
{
throw new NotImplementedException();
}
protected override void NotifyBeginField(byte elem_type)
{
throw new NotImplementedException();
}
protected override void NotifyEndField()
{
throw new NotImplementedException();
}
protected override void NotifyBeginRetType()
{
throw new NotImplementedException();
}
protected override void NotifyEndRetType()
{
throw new NotImplementedException();
}
protected override void NotifyBeginParam()
{
throw new NotImplementedException();
}
protected override void NotifyParamCount(int count)
{
throw new NotImplementedException();
}
protected override void NotifyEndParam()
{
throw new NotImplementedException();
}
protected override void NotifyGenericParamCount(int count)
{
throw new NotImplementedException();
}
}
}
|
using TokenAuthentication.Requests;
namespace TokenAuthentication.Services
{
public interface IRegistrationService
{
void Register(RegisterUserRequest register);
}
} |
using System.Linq;
namespace SensorThings.OData
{
public class QuerySelect : AbstractQuery<string[]>
{
public QuerySelect(string[] values) : base("select", values) { }
public override string GetQueryValueString()
{
return Value.Aggregate((x, y) => $"{x},{y}");
}
}
}
|
namespace LoudPizza
{
public unsafe abstract class AudioStream : AudioSource
{
//public int mFiletype;
//public string? mFilename;
//public File* mMemFile;
//public File* mStreamFile;
public uint mSampleCount;
public AudioStream()
{
//mFilename = null;
//mSampleCount = 0;
//mFiletype = WAVSTREAM_WAV;
//mMemFile = 0;
//mStreamFile = 0;
}
~AudioStream()
{
stop();
//delete[] mFilename;
//delete mMemFile;
}
/*
public SOLOUD_ERRORS loadwav(File* fp)
{
fp->seek(0);
drwav decoder;
if (!drwav_init(&decoder, drwav_read_func, drwav_seek_func, (void*)fp, null))
return FILE_LOAD_FAILED;
mChannels = decoder.channels;
if (mChannels > MAX_CHANNELS)
{
mChannels = MAX_CHANNELS;
}
mBaseSamplerate = (float)decoder.sampleRate;
mSampleCount = (uint)decoder.totalPCMFrameCount;
mFiletype = WAVSTREAM_WAV;
drwav_uninit(&decoder);
return SOLOUD_ERRORS.SO_NO_ERROR;
}
public SOLOUD_ERRORS loadogg(File* fp)
{
fp->seek(0);
int e;
stb_vorbis* v;
v = stb_vorbis_open_file((Soloud_Filehack*)fp, 0, &e, 0);
if (v == null)
return FILE_LOAD_FAILED;
stb_vorbis_info info = stb_vorbis_get_info(v);
mChannels = info.channels;
if (info.channels > MAX_CHANNELS)
{
mChannels = MAX_CHANNELS;
}
mBaseSamplerate = (float)info.sample_rate;
int samples = stb_vorbis_stream_length_in_samples(v);
stb_vorbis_close(v);
mFiletype = WAVSTREAM_OGG;
mSampleCount = samples;
return 0;
}
public SOLOUD_ERRORS loadflac(File* fp)
{
fp->seek(0);
drflac* decoder = drflac_open(drflac_read_func, drflac_seek_func, (void*)fp, null);
if (decoder == null)
return FILE_LOAD_FAILED;
mChannels = decoder->channels;
if (mChannels > MAX_CHANNELS)
{
mChannels = MAX_CHANNELS;
}
mBaseSamplerate = (float)decoder->sampleRate;
mSampleCount = (uint)decoder->totalPCMFrameCount;
mFiletype = WAVSTREAM_FLAC;
drflac_close(decoder);
return SOLOUD_ERRORS.SO_NO_ERROR;
}
public SOLOUD_ERRORS loadmp3(File* fp)
{
fp->seek(0);
drmp3 decoder;
if (!drmp3_init(&decoder, drmp3_read_func, drmp3_seek_func, (void*)fp, null, null))
return FILE_LOAD_FAILED;
mChannels = decoder.channels;
if (mChannels > MAX_CHANNELS)
{
mChannels = MAX_CHANNELS;
}
drmp3_uint64 samples = drmp3_get_pcm_frame_count(&decoder);
mBaseSamplerate = (float)decoder.sampleRate;
mSampleCount = (uint)samples;
mFiletype = WAVSTREAM_MP3;
drmp3_uninit(&decoder);
return SOLOUD_ERRORS.SO_NO_ERROR;
}
public SOLOUD_ERRORS load(string aFilename)
{
//delete[] mFilename;
delete mMemFile;
mMemFile = 0;
mFilename = aFilename;
mSampleCount = 0;
DiskFile fp;
SOLOUD_ERRORS res = fp.open(aFilename);
if (res != SOLOUD_ERRORS.SO_NO_ERROR)
return res;
//int len = (int)strlen(aFilename);
//mFilename = new char[len + 1];
//memcpy(mFilename, aFilename, len);
//mFilename[len] = 0;
res = parse(&fp);
if (res != SOLOUD_ERRORS.SO_NO_ERROR)
{
//delete[] mFilename;
//mFilename = 0;
return res;
}
return 0;
}
public SOLOUD_ERRORS loadMem(byte* aData, uint aDataLen, bool aCopy, bool aTakeOwnership)
{
//delete[] mFilename;
//delete mMemFile;
mStreamFile = 0;
mMemFile = 0;
mFilename = null;
mSampleCount = 0;
if (aData == null || aDataLen == 0)
return SOLOUD_ERRORS.INVALID_PARAMETER;
MemoryFile* mf = new MemoryFile();
SOLOUD_ERRORS res = mf->openMem(aData, aDataLen, aCopy, aTakeOwnership);
if (res != SOLOUD_ERRORS.SO_NO_ERROR)
{
//delete mf;
return res;
}
res = parse(mf);
if (res != SOLOUD_ERRORS.SO_NO_ERROR)
{
//delete mf;
return res;
}
mMemFile = mf;
return SOLOUD_ERRORS.SO_NO_ERROR;
}
public SOLOUD_ERRORS loadToMem(string aFilename)
{
DiskFile df;
int res = df.open(aFilename);
if (res == SOLOUD_ERRORS.SO_NO_ERROR)
{
res = loadFileToMem(&df);
}
return res;
}
public SOLOUD_ERRORS loadFile(File* aFile)
{
//delete[] mFilename;
delete mMemFile;
mStreamFile = 0;
mMemFile = 0;
mFilename = null;
mSampleCount = 0;
int res = parse(aFile);
if (res != SOLOUD_ERRORS.SO_NO_ERROR)
{
return res;
}
mStreamFile = aFile;
return 0;
}
public SOLOUD_ERRORS loadFileToMem(File* aFile)
{
//delete[] mFilename;
delete mMemFile;
mStreamFile = 0;
mMemFile = 0;
mFilename = null;
mSampleCount = 0;
MemoryFile* mf = new MemoryFile();
SOLOUD_ERRORS res = mf->openFileToMem(aFile);
if (res != SOLOUD_ERRORS.SO_NO_ERROR)
{
//delete mf;
return res;
}
res = parse(mf);
if (res != SOLOUD_ERRORS.SO_NO_ERROR)
{
//delete mf;
return res;
}
mMemFile = mf;
return res;
}
public SOLOUD_ERRORS parse(File* aFile)
{
int tag = aFile->read32();
SOLOUD_ERRORS res = SOLOUD_ERRORS.SO_NO_ERROR;
if (tag == MAKEDWORD('O', 'g', 'g', 'S'))
{
res = loadogg(aFile);
}
else
if (tag == MAKEDWORD('R', 'I', 'F', 'F'))
{
res = loadwav(aFile);
}
else
if (tag == MAKEDWORD('f', 'L', 'a', 'C'))
{
res = loadflac(aFile);
}
else
if (loadmp3(aFile) == SO_NO_ERROR)
{
res = SOLOUD_ERRORS.SO_NO_ERROR;
}
else
{
res = SOLOUD_ERRORS.FILE_LOAD_FAILED;
}
return res;
}
*/
public Time getLength()
{
if (mBaseSamplerate == 0)
return 0;
return mSampleCount / mBaseSamplerate;
}
}
}
|
using AutoMapper;
using FizzWare.NBuilder;
using Moq;
using NUnit.Framework;
using ReMi.BusinessEntities.Api;
using ReMi.DataAccess.BusinessEntityGateways.Auth;
using System;
using System.Collections.Generic;
using System.Linq;
using ReMi.Common.Utils.Repository;
using ReMi.Contracts.Plugins.Data;
using ReMi.TestUtils.UnitTests;
using ReMi.DataAccess.Exceptions;
using ReMi.DataEntities.Auth;
using ReMi.DataEntities.Plugins;
using DataQuery = ReMi.DataEntities.Api.Query;
using DataQueryPermission = ReMi.DataEntities.Auth.QueryPermission;
using DataRole = ReMi.DataEntities.Auth.Role;
namespace ReMi.DataAccess.Tests.Auth
{
[TestFixture]
public class QueryPermissionsGatewayTests : TestClassFor<QueryPermissionsGateway>
{
private Mock<IRepository<DataQuery>> _queryRepositoryMock;
private Mock<IRepository<DataQueryPermission>> _queryPermissionRepositoryMock;
private Mock<IRepository<DataRole>> _roleRepositoryMock;
private Mock<IRepository<Account>> _accountRepositoryMock;
private Mock<IRepository<PluginConfiguration>> _pluginConfigurationRepositoryMock;
private Mock<IMappingEngine> _mapperMock;
protected override QueryPermissionsGateway ConstructSystemUnderTest()
{
return new QueryPermissionsGateway
{
QueryRepository = _queryRepositoryMock.Object,
QueryPermissionRepository = _queryPermissionRepositoryMock.Object,
RoleRepository = _roleRepositoryMock.Object,
AccountRepository = _accountRepositoryMock.Object,
PluginConfigurationRepository = _pluginConfigurationRepositoryMock.Object,
Mapper = _mapperMock.Object
};
}
protected override void TestInitialize()
{
_queryRepositoryMock = new Mock<IRepository<DataQuery>>(MockBehavior.Strict);
_queryPermissionRepositoryMock = new Mock<IRepository<DataQueryPermission>>(MockBehavior.Strict);
_roleRepositoryMock = new Mock<IRepository<DataRole>>(MockBehavior.Strict);
_accountRepositoryMock = new Mock<IRepository<Account>>(MockBehavior.Strict);
_pluginConfigurationRepositoryMock = new Mock<IRepository<PluginConfiguration>>(MockBehavior.Strict);
_mapperMock = new Mock<IMappingEngine>(MockBehavior.Strict);
base.TestInitialize();
}
[Test]
public void Dispose_ShouldDisposeAllRepositories_WhenInvoked()
{
_queryRepositoryMock.Setup(x => x.Dispose());
_queryPermissionRepositoryMock.Setup(x => x.Dispose());
_roleRepositoryMock.Setup(x => x.Dispose());
_accountRepositoryMock.Setup(x => x.Dispose());
_pluginConfigurationRepositoryMock.Setup(x => x.Dispose());
Sut.Dispose();
_queryRepositoryMock.Verify(x => x.Dispose(), Times.Once);
_queryPermissionRepositoryMock.Verify(x => x.Dispose(), Times.Once);
_roleRepositoryMock.Verify(x => x.Dispose(), Times.Once);
_accountRepositoryMock.Verify(x => x.Dispose(), Times.Once);
_pluginConfigurationRepositoryMock.Verify(x => x.Dispose(), Times.Once);
}
[Test]
public void GetQueries_ShouldReturnAllNotBackgroundQueries_WhenCalledWithoutParameter()
{
var queries = BuildQueryEntities();
var notStaticCount = queries.Count(x => !x.IsStatic);
_queryRepositoryMock.SetupEntities(queries);
_mapperMock.Setup(x => x.Map<DataQuery, Query>(It.IsAny<DataQuery>()))
.Returns(new Query());
var result = Sut.GetQueries();
Assert.AreEqual(notStaticCount, result.Count());
_mapperMock.Verify(x => x.Map<DataQuery, Query>(It.IsAny<DataQuery>()), Times.Exactly(notStaticCount));
}
[Test]
public void GetQueries_ShouldReturnAllQueries_WhenCalledWithoutTrueParameter()
{
var queries = BuildQueryEntities();
var count = queries.Count();
_queryRepositoryMock.SetupEntities(queries);
_mapperMock.Setup(x => x.Map<DataQuery, Query>(It.IsAny<DataQuery>()))
.Returns(new Query());
var result = Sut.GetQueries(true);
Assert.AreEqual(count, result.Count());
_mapperMock.Verify(x => x.Map<DataQuery, Query>(It.IsAny<DataQuery>()), Times.Exactly(count));
}
[Test]
public void AddQueryPermission_ShouldAddNewQueryToRoleRelation_WhenQueryAndRoleExist()
{
var roles = BuildRoleEntities();
var queries = BuildQueryEntities();
var startPermissionCount = queries.First().QueryPermissions.Count;
_queryRepositoryMock.SetupEntities(queries);
_roleRepositoryMock.SetupEntities(roles);
_queryRepositoryMock.Setup(x => x.Update(queries.First()))
.Returns((ChangedFields<DataQuery>)null);
Sut.AddQueryPermission(queries.First().QueryId, roles.First().ExternalId);
Assert.IsTrue(queries.First().QueryPermissions.Any(x => x.RoleId == roles.First().Id));
Assert.AreEqual(startPermissionCount + 1, queries.First().QueryPermissions.Count);
_queryRepositoryMock.Verify(x => x.Update(queries.First()), Times.Once());
}
[Test]
[ExpectedException(typeof(QueryNotFoundException))]
public void AddQueryPermission_ShouldThrowException_WhenQueryNotExists()
{
var roles = BuildRoleEntities();
var queries = BuildQueryEntities();
_queryRepositoryMock.SetupEntities(queries);
Sut.AddQueryPermission(-1, roles.First().ExternalId);
}
[Test]
[ExpectedException(typeof(RoleNotFoundException))]
public void AddQueryPermission_ShouldThrowException_WhenRoleNotExists()
{
var roles = BuildRoleEntities();
var queries = BuildQueryEntities();
_queryRepositoryMock.SetupEntities(queries);
_roleRepositoryMock.SetupEntities(roles);
Sut.AddQueryPermission(queries.First().QueryId, Guid.Empty);
}
[Test]
public void AddQueryPermission_ShouldDoNothing_WhenPermissionExists()
{
var roles = BuildRoleEntities();
var queries = BuildQueryEntities();
queries.First().QueryPermissions.Add(new DataQueryPermission
{
QueryId = queries.First().QueryId,
RoleId = roles.First().Id,
Role = roles.First()
});
var startPermissionCount = queries.First().QueryPermissions.Count;
_queryRepositoryMock.SetupEntities(queries);
_roleRepositoryMock.SetupEntities(roles);
Sut.AddQueryPermission(queries.First().QueryId, roles.First().ExternalId);
Assert.AreEqual(startPermissionCount, queries.First().QueryPermissions.Count);
_queryRepositoryMock.Verify(x => x.Update(It.IsAny<DataQuery>()), Times.Never);
}
[Test]
public void RemoveQueryPermission_ShouldRemoveQueryToRoleRelation_WhenQueryAndRoleExist()
{
var roles = BuildRoleEntities();
var queries = BuildQueryEntities();
queries.First().QueryPermissions.Add(new DataQueryPermission
{
QueryId = queries.First().QueryId,
RoleId = roles.First().Id,
Role = roles.First()
});
_queryRepositoryMock.SetupEntities(queries);
_roleRepositoryMock.SetupEntities(roles);
_queryPermissionRepositoryMock.SetupEntities(queries.First().QueryPermissions);
_queryPermissionRepositoryMock.Setup(x =>x.Delete(It.Is<DataQueryPermission>(
r => r.QueryId == queries.First().QueryId && r.RoleId == roles.First().Id)));
Sut.RemoveQueryPermission(queries.First().QueryId, roles.First().ExternalId);
Assert.IsTrue(queries.First().QueryPermissions.Any(x => x.RoleId == roles.First().Id));
_queryPermissionRepositoryMock.Verify(x => x.Delete(It.Is<DataQueryPermission>(
r => r.QueryId == queries.First().QueryId && r.RoleId == roles.First().Id)), Times.Once());
}
[Test]
[ExpectedException(typeof(QueryNotFoundException))]
public void RemoveQueryPermission_ShouldThrowException_WhenQueryNotExists()
{
var roles = BuildRoleEntities();
var queries = BuildQueryEntities();
_queryRepositoryMock.SetupEntities(queries);
Sut.RemoveQueryPermission(-1, roles.First().ExternalId);
}
[Test]
[ExpectedException(typeof(RoleNotFoundException))]
public void RemoveQueryPermission_ShouldThrowException_WhenRoleNotExists()
{
var roles = BuildRoleEntities();
var queries = BuildQueryEntities();
_queryRepositoryMock.SetupEntities(queries);
_roleRepositoryMock.SetupEntities(roles);
Sut.RemoveQueryPermission(queries.First().QueryId, Guid.Empty);
}
[Test]
public void RemoveQueryPermission_ShouldDoNothing_WhenPermissionExists()
{
var roles = BuildRoleEntities();
var queries = BuildQueryEntities();
_queryRepositoryMock.SetupEntities(queries);
_roleRepositoryMock.SetupEntities(roles);
Sut.RemoveQueryPermission(queries.First().QueryId, roles.First().ExternalId);
_queryPermissionRepositoryMock.Verify(x => x.Delete(It.IsAny<DataQueryPermission>()), Times.Never);
}
[Test]
public void GetAllowedQueries_ShouldReturnCorrectValue()
{
var queryPermissions = new List<DataQueryPermission>
{
new DataQueryPermission
{
Query = new DataQuery{Name = RandomData.RandomString(15,20)},
Role = new DataRole
{
ExternalId = Guid.NewGuid()
}
}
};
_roleRepositoryMock.SetupEntities(queryPermissions.Select(x => x.Role).ToArray());
_queryPermissionRepositoryMock.SetupEntities(queryPermissions);
var result = Sut.GetAllowedQueries(queryPermissions[0].Role.ExternalId);
Assert.AreEqual(queryPermissions[0].Query.Name, result.First());
}
[Test]
public void GetAllowedCommands_ShouldReturnEmptyCollection_WhenRoleIsEmptyAndAuthenticationMethodDefined()
{
var queries = Builder<DataQuery>.CreateListOfSize(5).Build();
var accounts = Builder<Account>.CreateListOfSize(5).Build();
var pluginsConfig = Builder<PluginConfiguration>.CreateListOfSize(5)
.Random(1)
.With(x => x.PluginType, PluginType.Authentication)
.With(x => x.PluginId, RandomData.RandomInt(int.MaxValue))
.Build();
_accountRepositoryMock.SetupEntities(accounts);
_pluginConfigurationRepositoryMock.SetupEntities(pluginsConfig);
_queryRepositoryMock.SetupEntities(queries);
var result = Sut.GetAllowedQueries(null);
CollectionAssert.IsEmpty(result);
}
[Test]
public void GetAllowedCommands_ShouldReturnAllCommands_WhenRoleIsEmptyAndNoAuthenticationMethodDefined()
{
var queries = Builder<DataQuery>.CreateListOfSize(5).Build();
_accountRepositoryMock.SetupEntities(Enumerable.Empty<Account>());
_pluginConfigurationRepositoryMock.SetupEntities(Enumerable.Empty<PluginConfiguration>());
_queryRepositoryMock.SetupEntities(queries);
var result = Sut.GetAllowedQueries(null);
CollectionAssert.AreEquivalent(queries.Select(x => x.Name), result);
}
[Test]
public void GetAllowedQueries_ShouldReturnAllQueriesWhenRoleIsAdmin()
{
var role = new DataRole
{
ExternalId = Guid.NewGuid(),
Name = "Admin"
};
var queries = Builder<DataQuery>.CreateListOfSize(5).Build();
_roleRepositoryMock.SetupEntities(new[] { role });
_queryRepositoryMock.SetupEntities(queries);
var result = Sut.GetAllowedQueries(role.ExternalId);
CollectionAssert.AreEquivalent(queries.Select(x => x.Name), result);
}
private static IList<DataQuery> BuildQueryEntities()
{
return Builder<DataQuery>.CreateListOfSize(5)
.All()
.Do(x => x.QueryId = RandomData.RandomInt(10000))
.Do(x => x.Description = RandomData.RandomString(10))
.Do(x => x.Group = RandomData.RandomString(10))
.Do(x => x.Name = RandomData.RandomString(10))
.Do(x => x.IsStatic = RandomData.RandomBool())
.Do(x => x.QueryPermissions = RandomData.RandomBool()
? new List<DataQueryPermission>()
: Builder<DataQueryPermission>.CreateListOfSize(RandomData.RandomInt(1, 5))
.All()
.Do(cp => cp.Role = new DataRole
{
ExternalId = Guid.NewGuid(),
Description = RandomData.RandomString(10),
Name = RandomData.RandomString(10),
Id = RandomData.RandomInt(10000)
})
.Build())
.Build();
}
private static IList<DataRole> BuildRoleEntities()
{
return Builder<DataRole>.CreateListOfSize(5)
.All()
.Do(x => x.Id = RandomData.RandomInt(10000))
.Do(x => x.Description = RandomData.RandomString(10))
.Do(x => x.Name = RandomData.RandomString(10))
.Do(x => x.ExternalId = Guid.NewGuid())
.Build();
}
}
}
|
using System.Reflection;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Jobs;
using MediatR;
using Microsoft.Extensions.DependencyInjection;
namespace Marble.Benchmarks
{
[SimpleJob(RuntimeMoniker.NetCoreApp31)]
[MarkdownExporterAttribute.GitHub]
[MeanColumn, MemoryDiagnoser]
public class Installation
{
[Benchmark(Baseline = true)]
public object MediatR()
{
return new ServiceCollection()
.AddMediatR(Assembly.GetExecutingAssembly())
.BuildServiceProvider()
.GetRequiredService<IMediator>();
}
[Benchmark]
public object Marble()
{
return new ServiceCollection()
.AddMediator(mediator => mediator.RegisterPartsFromExecutingAssembly())
.BuildServiceProvider()
.GetRequiredService<IMediator>();
}
}
} |
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace NYTimes.NET.Tests.Mocks
{
public class GeneralUseMocks
{
public static JObject GetEmptyJArray()
{
var mockArray = new
{
results = System.Array.Empty<object>()
};
return JObject.Parse(JsonConvert.SerializeObject(mockArray, Formatting.Indented));
}
public static JObject GetEmptyJObject<T>() where T : new()
{
var mockObject = new
{
results = new T()
};
return JObject.Parse(JsonConvert.SerializeObject(mockObject, Formatting.Indented));
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Weapon : MonoBehaviour
{
Animator animator;
void Start ()
{
animator = GetComponentInParent<Animator> ();
}
public float damage = 2;
void OnTriggerEnter (Collider other)
{
MeleeUnit hit = other.gameObject.GetComponent<MeleeUnit> ();
if (other.tag != this.gameObject.tag && hit && other.isTrigger == false)
{
Debug.DrawLine (transform.position, other.transform.position, Color.red, 1f);
Debug.DrawRay (transform.position, Vector3.up, Color.green);
hit.TakeDamage ((int)(damage * ((tag == "ennemy") ? GameManager.instance.pourcentqgeDegatEnemy : 1f)));
gameObject.SetActive (false);
return;
}
CastleUnit hitu = other.gameObject.GetComponent<CastleUnit> ();
if (other.tag != this.gameObject.tag && hitu && other.isTrigger == false)
{
Debug.Log("found a target");
Debug.DrawLine (transform.position, other.transform.position, Color.red, 1f);
Debug.DrawRay (transform.position, Vector3.up, Color.green);
hitu.TakeDamage ((int)damage);
animator.gameObject.GetComponent<MeleeUnit>().TakeDamage((int)damage/2);
gameObject.SetActive (false);
return;
}
}
} |
using GetcuReone.MvvmFrame.Wpf.TestAdapter.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace GetcuReone.MvvmFrame.Wpf.TestAdapter.Helpers
{
/// <summary>
/// thread helper
/// </summary>
public static class ThreadHelper
{
/// <summary>
/// Run an action in a STA thread
/// </summary>
/// <param name="threadStart"></param>
/// <param name="maxWaitTime"></param>
public static void RunActinInSTAThread(Action threadStart, int maxWaitTime)
{
if (Thread.CurrentThread.GetApartmentState() == ApartmentState.STA)
{
threadStart();
return;
}
Exception exception = null;
var thread = new Thread(() =>
{
try
{
threadStart();
}
catch (Exception ex)
{
exception = ex;
}
});
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
thread.Join(maxWaitTime);
switch (thread.ThreadState)
{
case ThreadState.Running:
thread.Abort();
break;
}
if (exception != null)
throw new ThreadAnotherException(exception);
}
}
}
|
namespace DataTanker.AccessMethods.RadixTree
{
using System.Collections.Generic;
using MemoryManagement;
internal interface IRadixTreeNode
{
/// <summary>
/// Gets or sets common prefix bytes stored in this node.
/// </summary>
byte[] Prefix { get; set; }
/// <summary>
/// Gets a collection of entries of this node
/// </summary>
IList<KeyValuePair<byte, DbItemReference>> Entries { get; }
/// <summary>
/// Gets a reference to this node.
/// </summary>
DbItemReference Reference { get; set; }
/// <summary>
/// Gets or sets an index of parent node. Returns -1 for the root node.
/// </summary>
DbItemReference ParentNodeReference { get; set; }
/// <summary>
/// Gets or sets a reference to storing value.
/// </summary>
DbItemReference ValueReference { get; set; }
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TrampaPuas : MonoBehaviour
{
public SpriteRenderer spriteRenderer;
public Sprite conEspinas;
public Sprite sinEspinas;
bool danino;
private int damage = 1;
void Start()
{
spriteRenderer = gameObject.GetComponent<SpriteRenderer>();
}
// Update is called once per frame
void Update()
{
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.transform.CompareTag("Player"))
{
SoundManager.PlaySound(SoundManager.Sound.alerta);
Invoke("Puas", 1);
}
}
private void OnTriggerExit2D(Collider2D collision)
{
if (collision.transform.CompareTag("Player"))
{
spriteRenderer.sprite = sinEspinas;
danino = false;
CancelInvoke("Puas");
}
}
private void OnTriggerStay2D(Collider2D collision)
{
if(collision.transform.CompareTag("Player"))
{
if(danino)
{
collision.SendMessageUpwards("AddDamage", damage);
}
}
}
void Puas()
{
spriteRenderer.sprite = conEspinas;
danino = true;
SoundManager.PlaySound(SoundManager.Sound.puas);
}
}
|
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
namespace FG5eParserModels.Player_Models
{
public class Classes : INotifyPropertyChanged
{
private string ClassName { get; set; }
private string ClassDescription { get; set; }
private string HitDice { get; set; }
private string HitPointsAtFirstLevel { get; set; }
private string HitPointsAfterFirstLevel { get; set; }
private string Armor { get; set; }
private string Weapons { get; set; }
private string Tools { get; set; }
private string SavingThrows { get; set; }
private string Skills { get; set; }
private string Equipment { get; set; }
public ObservableCollection<ClassFeatures> _featureList { get; set; }
private string FeatureArchtypeName { get; set; } // What the archtype section is called
public ObservableCollection<ClassAbilities> _abilityList { get; set; }
//NOTE: Output was moved to the viewmodel to make gathering all the details easier
#region PROPERTY CHANGES
// Declare the interface event
public event PropertyChangedEventHandler PropertyChanged;
// Create the OnPropertyChanged method to raise the event
public void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
#endregion
#region EXPOSED PROPERTIES
public string _ClassName
{
get{
return ClassName;
}
set {
ClassName = value;
OnPropertyChanged("_ClassName");
}
}
public string _ClassDescription
{
get
{
return ClassDescription;
}
set
{
ClassDescription = value;
OnPropertyChanged("_ClassDescription");
}
}
public string _HitDice
{
get
{
return HitDice;
}
set
{
HitDice = value;
OnPropertyChanged("_HitDice");
}
}
public string _HitPointsAtFirstLevel
{
get
{
return HitPointsAtFirstLevel;
}
set
{
HitPointsAtFirstLevel = value;
OnPropertyChanged("_HitPointsAtFirstLevel");
}
}
public string _HitPointsAfterFirstLevel
{
get
{
return HitPointsAfterFirstLevel;
}
set
{
HitPointsAfterFirstLevel = value;
OnPropertyChanged("_HitPointsAfterFirstLevel");
}
}
public string _Armor
{
get
{
return Armor;
}
set
{
Armor = value;
OnPropertyChanged("_Armor");
}
}
public string _Weapons
{
get
{
return Weapons;
}
set
{
Weapons = value;
OnPropertyChanged("_Weapons");
}
}
public string _Tools
{
get
{
return Tools;
}
set
{
Tools = value;
OnPropertyChanged("_Tools");
}
}
public string _SavingThrows
{
get
{
return SavingThrows;
}
set
{
SavingThrows = value;
OnPropertyChanged("_SavingThrows");
}
}
public string _Skills
{
get
{
return Skills;
}
set
{
Skills = value;
OnPropertyChanged("_Skills");
}
}
public string _Equipment
{
get
{
return Equipment;
}
set
{
Equipment = value;
OnPropertyChanged("_Equipment");
}
}
public string _FeatureArchtypeName
{
get
{
return FeatureArchtypeName;
}
set
{
FeatureArchtypeName = value;
OnPropertyChanged("_FeatureArchtypeName");
}
}
#endregion
// Constructors
public Classes()
{
_featureList = new ObservableCollection<ClassFeatures>();
_abilityList = new ObservableCollection<ClassAbilities>();
}
}
public class ClassFeatures : INotifyPropertyChanged
{
private string FeatureName { get; set; }
private string FeatureLevels { get; set; }
private string FeatureDescription { get; set; }
private bool isArchtypeHeader { get; set; } // True : If feature is defined as the archtype, False : If not
private string UnderArchtype { get; set; } // What archtype does this feature belong too
#region PROPERTY CHANGES
// Declare the nterface event
public event PropertyChangedEventHandler PropertyChanged;
// Create the OnPropertyChanged method to raise the event
public void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
#endregion
#region EXPOSED PROPERTIES
public string _FeatureLevels
{
get
{
return FeatureLevels;
}
set
{
FeatureLevels = value;
OnPropertyChanged("_FeatureLevels");
}
}
public string _FeatureDescription
{
get
{
return FeatureDescription;
}
set
{
FeatureDescription = value;
OnPropertyChanged("_FeatureDescription");
}
}
public string _FeatureName
{
get
{
return FeatureName;
}
set
{
FeatureName = value;
OnPropertyChanged("_FeatureName");
}
}
public string _isArchtypeHeader
{
get
{
return isArchtypeHeader.ToString();
}
set
{
isArchtypeHeader = Convert.ToBoolean(value);
OnPropertyChanged("_isArchtypeHeader");
}
}
public string _UnderArchtype
{
get
{
return UnderArchtype;
}
set
{
UnderArchtype = value;
OnPropertyChanged("_UnderArchtype");
}
}
#endregion
}
public class ClassAbilities : INotifyPropertyChanged
{
private string AbilityName { get; set; }
private string AbilityDescription { get; set; }
private ObservableCollection<string> _list { get; set; }
public ClassAbilities()
{
_list = new ObservableCollection<string>();
}
#region PROPERTY CHANGES
// Declare the nterface event
public event PropertyChangedEventHandler PropertyChanged;
// Create the OnPropertyChanged method to raise the event
public void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
#endregion
#region EXPOSED PROPERTIES
public string _AbilityName
{
get
{
return AbilityName;
}
set
{
AbilityName = value;
OnPropertyChanged("_AbilityName");
}
}
public string _AbilityDescription
{
get
{
return AbilityDescription;
}
set
{
AbilityDescription = value;
OnPropertyChanged("_AbilityDescription");
}
}
#endregion
}
}
|
using UnityEngine;
public class ThroableOrb : MonoBehaviour
{
public AudioClip hitSound;
public AudioClip throwSound;
public AudioClip bridgeApearSound;
public GameObject target;
public Vector3 defaultPos;
AudioSource source;
bool isBeingThrown = false;
GameObject[] bridgePieces;
private void Start()
{
bridgePieces = GameObject.FindGameObjectsWithTag("BridgePiece");
foreach (GameObject piece in bridgePieces)
{
piece.SetActive(false);
}
defaultPos = gameObject.transform.position;
source = GetComponent<AudioSource>();
}
public void PlayThrowSound()
{
isBeingThrown = true;
source.clip = throwSound;
source.Play();
}
private void OnCollisionEnter(Collision collision)
{
source.clip = hitSound;
source.Play();
if (collision.gameObject == target)
{
print("collide with target");
source.clip = bridgeApearSound;
source.Play(1000);
foreach (GameObject piece in bridgePieces)
{
piece.SetActive(true);
}
}
if(collision.gameObject.tag == "Water")
{
isBeingThrown = false;
gameObject.transform.position = defaultPos;
gameObject.GetComponent<Rigidbody>().velocity = Vector3.zero;
}
//resets ball back to it's initail position so it can be thrown again
else if (isBeingThrown)
{
isBeingThrown = false;
gameObject.transform.position = defaultPos;
gameObject.GetComponent<Rigidbody>().velocity = Vector3.zero;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerInput : MonoBehaviour
{
Board board;
Collider clickEnter;
public Transform t1, t2;
private Vector3 position;
private float width, height;
private float lastDistance = 0f;
void Start()
{
board = GameObject.Find("/Board").GetComponent<Board>();
width = Screen.width / 2.0f;
height = Screen.height / 2.0f;
}
void Update()
{
// EXPAND (pinch)
/*if (Input.GetAxis("Mouse ScrollWheel") > 0)
{
board.expanded = true;
board.selectedLevel = board.levels[Mathf.FloorToInt(board.halfBoardSize)];
}
else if (Input.GetAxis("Mouse ScrollWheel") < 0)
{
board.expanded = false;
transform.parent.position = new Vector3(0, 0, 0);
}*/
// EXPAND (pinch)
if (Input.touchCount == 2)
{
Touch touch1 = Input.GetTouch(0);
Touch touch2 = Input.GetTouch(1);
Vector2 pos = touch1.position;
pos.x = (pos.x - width) / width;
pos.y = (pos.y - height) / height;
position = new Vector3(-pos.x, pos.y, 0.0f);
t1.position = position;
pos = touch2.position;
pos.x = (pos.x - width) / width;
pos.y = (pos.y - height) / height;
position = new Vector3(-pos.x, pos.y, 0.0f);
t2.position = position;
float d = Vector3.Distance(t1.position, t2.position);
if(d>lastDistance)
{
board.expanded = true;
board.selectedLevel = board.levels[Mathf.FloorToInt(board.halfBoardSize)];
}
else if (d < lastDistance)
{
board.expanded = false;
transform.parent.position = new Vector3(0, 0, 0);
}
lastDistance = d;
}
// CLICK (tap)
if (Input.GetMouseButtonDown(0))
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit, 100.0f))
{
clickEnter = hit.collider;
}
else
{
clickEnter = null;
}
}
else if(Input.GetMouseButtonUp(0))
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit, 100.0f))
{
if (clickEnter == hit.collider) board.Click(clickEnter);
}
else
{
if (clickEnter == hit.collider) board.Click(clickEnter);
}
clickEnter = null;
}
}
}
|
using EC.Libraries.Framework;
namespace EC.Libraries.MongoDB
{
/// <summary>
/// 存放NoSqlDB的连接配置信息
/// </summary>
public class MongoDBConfig : BaseConfig
{
/// <summary>
/// NoSqlDB服务器的连接参数
/// 格式为:mongodb://[user:password@]<host>:<port>
/// </summary>
public string Host{ set; get; }
/// <summary>
/// 使用的数据库名
/// </summary>
public string DBName{ set; get; }
/// <summary>
/// 超时
/// </summary>
public int TimeOut { set; get; }
/// <summary>
/// 端口
/// </summary>
public int Port { set; get; }
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
//
using System;
using System.Diagnostics.Contracts;
using System.Diagnostics.Tracing;
using System.Runtime.CompilerServices;
using System.Text;
using System.Windows;
using System.Windows.Input;
using MS.Internal;
using MS.Internal.Telemetry;
using MS.Internal.Telemetry.PresentationCore;
namespace System.Windows.Input.Tracing
{
/// <summary>
/// Trace logger for the Stylus/Touch stack
/// </summary>
internal static class StylusTraceLogger
{
#region Enumerations
/// <summary>
/// Flags to determine used features in the touch stack.
/// </summary>
[Flags]
internal enum FeatureFlags
{
/// <summary>
/// Default value of no features used
/// </summary>
None = 0x00000000,
/// <summary>
/// Determines if a class derived from TouchDevice is used by the developer
/// </summary>
CustomTouchDeviceUsed = 0x00000001,
/// <summary>
/// Determines if any stylus plugin has been used.
/// </summary>
StylusPluginsUsed = 0x00000002,
/// <summary>
/// Determines if a pen flick is processed and used as a scroll up command
/// </summary>
FlickScrollingUsed = 0x00000004,
/// <summary>
/// Determines if the WM_POINTER stack is enabled
/// </summary>
PointerStackEnabled = 0x10000000,
/// <summary>
/// Determines if the WISP based stack is enabled
/// </summary>
WispStackEnabled = 0x20000000,
}
#endregion
#region Data Collection Classes
/// <summary>
/// A collection of relevant stylus usage statistics and flags
/// </summary>
[EventData]
internal class StylusStatistics
{
public FeatureFlags FeaturesUsed { get; set; } = FeatureFlags.None;
}
/// <summary>
/// Tracks known re-entrancy hits in the stylus stack.
/// </summary>
[EventData]
internal class ReentrancyEvent
{
public string FunctionName { get; set; } = string.Empty;
}
/// <summary>
/// Class to log Size instances from tablet
/// </summary>
[EventData]
internal class StylusSize
{
public StylusSize(Size size)
{
Width = size.Width;
Height = size.Height;
}
public double Width { get; set; } = double.NaN;
public double Height { get; set; } = double.NaN;
}
/// <summary>
/// The information for a particular tablet to log on connect/disconnect
/// </summary>
[EventData]
internal class StylusDeviceInfo
{
public StylusDeviceInfo(int id, string name, string pnpId, TabletHardwareCapabilities capabilities,
Size tabletSize, Size screenSize, TabletDeviceType deviceType, int maxContacts)
{
Id = id;
Name = name;
PlugAndPlayId = pnpId;
Capabilities = capabilities.ToString("F");
TabletSize = new StylusTraceLogger.StylusSize(tabletSize);
ScreenSize = new StylusTraceLogger.StylusSize(screenSize);
DeviceType = deviceType.ToString("F");
MaxContacts = maxContacts;
}
public int Id { get; set; }
public string Name { get; set; }
public string PlugAndPlayId { get; set; }
public string Capabilities { get; set; }
public StylusSize TabletSize { get; set; }
public StylusSize ScreenSize { get; set; }
public string DeviceType { get; set; }
public int MaxContacts { get; set; }
}
/// <summary>
/// The WISP device id of the disconnected device for matching against the
/// connect.
/// </summary>
[EventData]
internal class StylusDisconnectInfo
{
public int Id { get; set; } = -1;
}
/// <summary>
/// For reporting errors in the WISP stack
/// </summary>
[EventData]
internal class StylusErrorEventData
{
public string Error { get; set; } = null;
}
#endregion
#region Constants
/// <summary>
/// Event name for logging datagrid usage details
/// </summary>
private static readonly string StartupEventTag = "StylusStartup";
/// <summary>
/// Event name for logging datagrid usage details
/// </summary>
private static readonly string ShutdownEventTag = "StylusShutdown";
/// <summary>
/// Event name for logging datagrid usage details
/// </summary>
private static readonly string StatisticsTag = "StylusStatistics";
/// <summary>
/// Event name for a stylus error
/// </summary>
private static readonly string ErrorTag = "StylusError";
/// <summary>
/// Event name for a stylus connection
/// </summary>
private static readonly string DeviceConnectTag = "StylusConnect";
/// <summary>
/// Event name for a stylus disconnection
/// </summary>
private static readonly string DeviceDisconnectTag = "StylusDisconnect";
/// <summary>
/// Event name for a stylus disconnection
/// </summary>
private static readonly string ReentrancyTag = "StylusReentrancy";
/// <summary>
/// Event name for the retry limits on re-entrancy into the touch stack being reached
/// </summary>
private static readonly string ReentrancyRetryLimitTag = "StylusReentrancyRetryLimitReached";
#endregion
#region Data Collection Functions
/// <summary>
/// Logs Stylus/Touch stack startup
/// </summary>
internal static void LogStartup()
{
Log(StartupEventTag);
}
/// <summary>
/// Log various statistics about the stack
/// </summary>
/// <param name="stylusData">The statistics to log</param>
internal static void LogStatistics(StylusStatistics stylusData)
{
Requires<ArgumentNullException>(stylusData != null);
Log(StatisticsTag, stylusData);
}
/// <summary>
/// Log that the retry limit for touch stack re-entrancy has been reached.
/// </summary>
internal static void LogReentrancyRetryLimitReached()
{
Log(ReentrancyRetryLimitTag);
}
/// <summary>
/// Logs an error in the stack
/// </summary>
/// <param name="error"></param>
internal static void LogError(string error)
{
Requires<ArgumentNullException>(error != null);
Log(ErrorTag, new StylusErrorEventData() { Error = error });
}
/// <summary>
/// Logs device information on connect
/// </summary>
/// <param name="deviceInfo"></param>
internal static void LogDeviceConnect(StylusDeviceInfo deviceInfo)
{
Requires<ArgumentNullException>(deviceInfo != null);
Log(DeviceConnectTag, deviceInfo);
}
/// <summary>
/// Logs device id on disconnect
/// </summary>
/// <param name="deviceId"></param>
internal static void LogDeviceDisconnect(int deviceId)
{
Log(DeviceDisconnectTag, new StylusDisconnectInfo() { Id = deviceId });
}
/// <summary>
/// Logs detected re-entrancy in the stack
/// </summary>
/// <param name="message"></param>
/// <param name="functionName"></param>
internal static void LogReentrancy([CallerMemberName] string functionName = "")
{
Log(ReentrancyTag, new ReentrancyEvent() { FunctionName = functionName });
}
/// <summary>
/// Logs Stylus/Touch stack shutdown
/// </summary>
internal static void LogShutdown()
{
Log(ShutdownEventTag);
}
#endregion
#region Utility
/// <summary>
/// Throws exception when condition is not met. We can't use the contracts version of this
/// since ccrewrite does not work on C++\CLI or netmodules and PresentationCore is a hybrid
/// assembly.
/// </summary>
/// <typeparam name="T">The type of exception to throw</typeparam>
/// <param name="condition">The condition to check</param>
private static void Requires<T>(bool condition)
where T : Exception, new()
{
if (!condition) throw new T();
}
/// <summary>
/// Logs a tag with no associated data
/// </summary>
/// <param name="tag">The event tag to log</param>
private static void Log(string tag)
{
EventSource logger = TraceLoggingProvider.GetProvider();
logger?.Write(tag, TelemetryEventSource.MeasuresOptions());
}
/// <summary>
/// Logs a tag with associated event data
/// </summary>
/// <typeparam name="T">The type of the event data</typeparam>
/// <param name="tag">The event tag to log</param>
/// <param name="data">The event data to log (default null)</param>
private static void Log<T>(string tag, T data = null)
where T : class
{
EventSource logger = TraceLoggingProvider.GetProvider();
logger?.Write(tag, TelemetryEventSource.MeasuresOptions(), data);
}
#endregion
}
}
|
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
using System.Threading.Tasks.Dataflow;
using ProjBobcat.Class.Model;
namespace ProjBobcat.Class.Helper;
/// <summary>
/// 下载帮助器。
/// </summary>
public static class DownloadHelper
{
const int BufferSize = 1024;
/// <summary>
/// 下载线程
/// </summary>
public static int DownloadThread { get; set; }
/// <summary>
/// 最大重试计数
/// </summary>
public static int RetryCount { get; set; } = 10;
static HttpClient DataClient => HttpClientHelper.GetNewClient(HttpClientHelper.DataClientName);
#region 下载一个列表中的文件(自动确定是否使用分片下载)
/// <summary>
/// 下载文件方法(自动确定是否使用分片下载)
/// </summary>
/// <param name="fileEnumerable">文件列表</param>
/// <param name="downloadParts"></param>
public static async Task AdvancedDownloadListFile(IEnumerable<DownloadFile> fileEnumerable,
int downloadParts = 16)
{
ProcessorHelper.SetMaxThreads();
var filesBlock =
new TransformManyBlock<IEnumerable<DownloadFile>, DownloadFile>(d =>
{
foreach (var df in d.Where(df => !Directory.Exists(df.DownloadPath)))
Directory.CreateDirectory(df.DownloadPath);
return d;
});
var actionBlock = new ActionBlock<DownloadFile>(async d =>
{
if (d.FileSize is >= 1048576 or 0)
{
await MultiPartDownloadTaskAsync(d, downloadParts);
}
else
{
using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(d.TimeOut * 2));
await DownloadData(d, cts.Token);
}
}, new ExecutionDataflowBlockOptions
{
BoundedCapacity = DownloadThread,
MaxDegreeOfParallelism = DownloadThread
});
var linkOptions = new DataflowLinkOptions {PropagateCompletion = true};
filesBlock.LinkTo(actionBlock, linkOptions);
filesBlock.Post(fileEnumerable);
filesBlock.Complete();
await actionBlock.Completion;
actionBlock.Complete();
}
#endregion
#region 下载数据
/// <summary>
/// 下载文件(通过线程池)
/// </summary>
/// <param name="downloadProperty"></param>
public static async Task DownloadData(DownloadFile downloadProperty, CancellationToken? cto = null)
{
var ct = cto ?? CancellationToken.None;
var filePath = Path.Combine(downloadProperty.DownloadPath, downloadProperty.FileName);
try
{
using var request = new HttpRequestMessage {RequestUri = new Uri(downloadProperty.DownloadUri)};
if (!string.IsNullOrEmpty(downloadProperty.Host))
request.Headers.Host = downloadProperty.Host;
using var res = await DataClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, ct);
await using var stream = await res.Content.ReadAsStreamAsync(ct);
await using var fileToWriteTo = File.Open(filePath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
var responseLength = res.Content.Headers.ContentLength ?? 0;
var downloadedBytesCount = 0L;
var buffer = new byte[BufferSize];
var sw = new Stopwatch();
var tSpeed = 0D;
var cSpeed = 0;
while (true)
{
sw.Restart();
var bytesRead = await stream.ReadAsync(buffer.AsMemory(0, BufferSize), ct);
sw.Stop();
if (bytesRead == 0)
break;
await fileToWriteTo.WriteAsync(buffer.AsMemory(0, bytesRead), ct);
Interlocked.Add(ref downloadedBytesCount, bytesRead);
var elapsedTime = Math.Ceiling(sw.Elapsed.TotalSeconds);
var speed = CalculateDownloadSpeed(bytesRead, elapsedTime, SizeUnit.Kb);
tSpeed += speed;
cSpeed++;
downloadProperty.OnChanged(
speed,
(double) downloadedBytesCount / responseLength,
downloadedBytesCount,
responseLength);
}
await fileToWriteTo.FlushAsync();
sw.Stop();
var aSpeed = tSpeed / cSpeed;
downloadProperty.OnCompleted(true, null, aSpeed);
}
catch (Exception e)
{
downloadProperty.OnCompleted(false, e, 0);
}
}
#endregion
public static double CalculateDownloadSpeed(int bytesReceived, double passedSeconds,
SizeUnit unit = SizeUnit.Mb)
{
const double baseNum = 1024;
return unit switch
{
SizeUnit.B => bytesReceived / passedSeconds,
SizeUnit.Kb => bytesReceived / baseNum / passedSeconds,
SizeUnit.Mb => bytesReceived / Math.Pow(baseNum, 2) / passedSeconds,
SizeUnit.Gb => bytesReceived / Math.Pow(baseNum, 3) / passedSeconds,
SizeUnit.Tb => bytesReceived / Math.Pow(baseNum, 4) / passedSeconds,
_ => bytesReceived / passedSeconds
};
}
#region 分片下载
/// <summary>
/// 分片下载方法
/// </summary>
/// <param name="downloadFile">下载文件信息</param>
/// <param name="numberOfParts">分段数量</param>
public static void MultiPartDownload(DownloadFile downloadFile, int numberOfParts = 16)
{
MultiPartDownloadTaskAsync(downloadFile, numberOfParts).Wait();
}
static HttpClient HeadClient => HttpClientHelper.GetNewClient(HttpClientHelper.HeadClientName);
static HttpClient MultiPartClient =>
HttpClientHelper.GetNewClient(HttpClientHelper.MultiPartClientName);
/// <summary>
/// 分片下载方法(异步)
/// </summary>
/// <param name="downloadFile">下载文件信息</param>
/// <param name="numberOfParts">分段数量</param>
public static async Task MultiPartDownloadTaskAsync(DownloadFile downloadFile, int numberOfParts = 16)
{
if (downloadFile == null) return;
if (numberOfParts <= 0) numberOfParts = Environment.ProcessorCount;
var filePath = Path.Combine(downloadFile.DownloadPath, downloadFile.FileName);
using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(downloadFile.TimeOut * 2));
#region Get file size
using var message = new HttpRequestMessage(HttpMethod.Head, new Uri(downloadFile.DownloadUri));
message.Headers.Range = new RangeHeaderValue(0, 1);
if (!string.IsNullOrEmpty(downloadFile.Host))
message.Headers.Host = downloadFile.Host;
using var headRes = await HeadClient.SendAsync(message, cts.Token);
var hasAcceptRanges = headRes.Headers.AcceptRanges.Any();
var hasRightStatusCode = headRes.StatusCode == HttpStatusCode.PartialContent;
var responseLength = headRes.Content.Headers.ContentRange?.Length ?? 0;
var contentLength = headRes.Content.Headers.ContentLength ?? 0;
var parallelDownloadSupported =
hasAcceptRanges &&
hasRightStatusCode &&
contentLength == 2 &&
responseLength != 0;
if (!parallelDownloadSupported)
{
await DownloadData(downloadFile, cts.Token);
return;
}
#endregion
if (!Directory.Exists(downloadFile.DownloadPath))
Directory.CreateDirectory(downloadFile.DownloadPath);
#region Calculate ranges
var readRanges = new List<DownloadRange>();
var partSize = (long) Math.Round((double) responseLength / numberOfParts);
var previous = 0L;
if (responseLength > numberOfParts)
for (var i = partSize; i <= responseLength; i += partSize)
if (i + partSize < responseLength)
{
var start = previous;
readRanges.Add(new DownloadRange
{
Start = start,
End = i,
TempFileName = Path.GetTempFileName()
});
previous = i;
}
else
{
var start = previous;
readRanges.Add(new DownloadRange
{
Start = start,
End = responseLength,
TempFileName = Path.GetTempFileName()
});
previous = i;
}
else
readRanges.Add(new DownloadRange
{
End = responseLength,
Start = 0,
TempFileName = Path.GetTempFileName()
});
#endregion
try
{
#region Parallel download
var downloadedBytesCount = 0L;
var tasksDone = 0;
var doneRanges = new ConcurrentBag<DownloadRange>();
var streamBlock =
new TransformBlock<DownloadRange, ValueTuple<Task<HttpResponseMessage>, DownloadRange>>(
p =>
{
using var request = new HttpRequestMessage {RequestUri = new Uri(downloadFile.DownloadUri)};
if (!string.IsNullOrEmpty(downloadFile.Host))
request.Headers.Host = downloadFile.Host;
request.Headers.Range = new RangeHeaderValue(p.Start, p.End);
var downloadTask = MultiPartClient.SendAsync(request,
HttpCompletionOption.ResponseHeadersRead,
CancellationToken.None);
doneRanges.Add(p);
return (downloadTask, p);
}, new ExecutionDataflowBlockOptions
{
BoundedCapacity = numberOfParts,
MaxDegreeOfParallelism = numberOfParts
});
var tSpeed = 0D;
var cSpeed = 0;
var writeActionBlock = new ActionBlock<(Task<HttpResponseMessage>, DownloadRange)>(async t =>
{
using var res = await t.Item1;
await using (var stream = await res.Content.ReadAsStreamAsync(cts.Token))
{
await using var fileToWriteTo = File.Open(t.Item2.TempFileName, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
var buffer = new byte[BufferSize];
var sw = new Stopwatch();
while (true)
{
sw.Restart();
var bytesRead = await stream.ReadAsync(buffer.AsMemory(0, BufferSize), cts.Token);
sw.Stop();
if (bytesRead == 0)
break;
await fileToWriteTo.WriteAsync(buffer.AsMemory(0, bytesRead), cts.Token);
Interlocked.Add(ref downloadedBytesCount, bytesRead);
var elapsedTime = Math.Ceiling(sw.Elapsed.TotalSeconds);
var speed = CalculateDownloadSpeed(bytesRead, elapsedTime, SizeUnit.Kb);
tSpeed += speed;
cSpeed++;
downloadFile.OnChanged(
speed,
(double) downloadedBytesCount / responseLength,
downloadedBytesCount,
responseLength);
}
sw.Stop();
await fileToWriteTo.FlushAsync();
}
Interlocked.Add(ref tasksDone, 1);
doneRanges.TryTake(out _);
}, new ExecutionDataflowBlockOptions
{
BoundedCapacity = numberOfParts,
MaxDegreeOfParallelism = numberOfParts,
CancellationToken = cts.Token
});
var linkOptions = new DataflowLinkOptions {PropagateCompletion = true};
var filesBlock =
new TransformManyBlock<IEnumerable<DownloadRange>, DownloadRange>(chunk => chunk,
new ExecutionDataflowBlockOptions());
filesBlock.LinkTo(streamBlock, linkOptions);
streamBlock.LinkTo(writeActionBlock, linkOptions);
filesBlock.Post(readRanges);
filesBlock.Complete();
await writeActionBlock.Completion;
var aSpeed = tSpeed / cSpeed;
if (!doneRanges.IsEmpty)
{
var ex = new AggregateException(new Exception("没有完全下载所有的分片"));
downloadFile.OnCompleted(false, ex, aSpeed);
if (File.Exists(filePath))
File.Delete(filePath);
return;
}
await using (var outputStream = File.Open(filePath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
{
foreach (var inputFilePath in readRanges)
{
await using var inputStream = File.Open(inputFilePath.TempFileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
outputStream.Seek(inputFilePath.Start, SeekOrigin.Begin);
await inputStream.CopyToAsync(outputStream, cts.Token);
File.Delete(inputFilePath.TempFileName);
}
await outputStream.FlushAsync();
}
downloadFile.OnCompleted(true, null, aSpeed);
streamBlock.Complete();
writeActionBlock.Complete();
#endregion
}
catch (Exception ex)
{
foreach (var piece in readRanges.Where(piece => File.Exists(piece.TempFileName)))
try
{
File.Delete(piece.TempFileName);
}
catch (Exception e)
{
Debug.WriteLine(e);
}
downloadFile.OnCompleted(false, ex, 0);
}
}
#endregion
} |
using System.Threading.Tasks;
using Twitch.Net.Interfaces;
namespace Twitch.Net.Strategies
{
internal class RateLimitIgnoreStrategy : IRateLimitStrategy
{
public Task Wait()
{
return Task.CompletedTask;
}
}
}
|
using System;
using System.Collections.Generic;
namespace AwsCredentialHelper.Core
{
public record GitParameters
{
public readonly string Protocol;
public readonly string Host;
public readonly string Path;
public static GitParameters FromDictionary(Dictionary<string, string> parameters)
{
string GetOrThrow(string key) => parameters.GetValueOrDefault(key)
?? throw new ArgumentException($"Input parameters require a value for '{key}'", nameof(parameters));
return new GitParameters(GetOrThrow("protocol"), GetOrThrow("host"), GetOrThrow("path"));
}
public GitParameters(string protocol, string host, string path)
{
this.Protocol = protocol;
this.Host = host;
this.Path = path;
}
}
}
|
namespace Effort.Extra.Tests
{
using System;
using System.Collections.Generic;
using Effort.DataLoaders;
using Machine.Fakes;
using Machine.Specifications;
internal class ObjectTableDataLoader
{
public class Ctor
{
[Subject("ObjectTableDataLoader.Ctor")]
public abstract class ctor_context : WithFakes
{
protected static Exception thrown_exception;
protected static TableDescription table;
protected static ObjectDataTable<Person> entities;
protected static ObjectTableDataLoader<Person> subject;
Because of = () => thrown_exception = Catch.Exception(
() => subject = new ObjectTableDataLoader<Person>(table, entities));
}
public class when_table_is_null : ctor_context
{
Establish context = () =>
{
table = null;
entities = new ObjectDataTable<Person>();
};
It throws_an_argument_null_exception =
() => thrown_exception.ShouldBeOfExactType<ArgumentNullException>();
}
public class when_entities_is_null : ctor_context
{
Establish context = () =>
{
table = Builder.CreateTableDescription(typeof(Person).Name, typeof(Person));
entities = null;
};
It throws_an_argument_null_exception =
() => thrown_exception.ShouldBeOfExactType<ArgumentNullException>();
}
public class when_arguments_are_valid : ctor_context
{
Establish context = () =>
{
table = Builder.CreateTableDescription(typeof(Person).Name, typeof(Person));
entities = new ObjectDataTable<Person>();
};
It does_not_throw_an_exception = () => thrown_exception.ShouldBeNull();
}
}
public class CreateFormatter
{
[Subject("ObjectTableDataLoader.CreateFormatter")]
public abstract class create_formatter_context<TModel> : WithSubject<StubObjectTableDataLoader<TModel>>
{
protected static Exception thrown_exception;
protected static Func<TModel, object[]> formatter;
Because of = () => thrown_exception = Catch.Exception(
() => formatter = Subject.CreateFormatter());
}
public class when_formatter_is_created : create_formatter_context<Person>
{
It does_not_throw_an_exception = () => thrown_exception.ShouldBeNull();
It the_formatter_is_not_null = () => formatter.ShouldNotBeNull();
It the_formatter_behaves_correctly = () =>
{
var formatted = formatter(new Person { Name = "Fred" });
formatted.Length.ShouldEqual(1);
formatted[0].ShouldEqual("Fred");
};
}
public class when_type_has_column_attribtues : create_formatter_context<PersonWithAttribute>
{
It does_not_throw_an_exception = () => thrown_exception.ShouldBeNull();
It the_formatter_is_not_null = () => formatter.ShouldNotBeNull();
It the_formatter_behaves_correctly = () =>
{
var formatted = formatter(new PersonWithAttribute { Name = "Fred" });
formatted.Length.ShouldEqual(1);
formatted[0].ShouldEqual("Fred");
};
}
}
public class StubObjectTableDataLoader<TModel> : ObjectTableDataLoader<TModel>
{
public StubObjectTableDataLoader()
: base(Builder.CreateTableDescription(typeof(TModel).Name, typeof(TModel)), new ObjectDataTable<TModel>())
{ }
public new Func<TModel, object[]> CreateFormatter()
{
return base.CreateFormatter();
}
}
}
}
|
using RoyalCode.PipelineFlow.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
namespace RoyalCode.PipelineFlow
{
/// <summary>
/// <para>
/// Dispatcher are delegated to get a pipeline of an input type and send them out for processing.
/// </para>
/// <para>
/// This is a generic component for performing this operation.
/// </para>
/// </summary>
/// <typeparam name="TFor">The pipeline type.</typeparam>
public class PipelineDispatchers<TFor>
{
private static readonly Dictionary<Type, object> dispatchers = new();
private static readonly Dictionary<Type, object> asyncDispatchers = new();
internal static readonly MethodInfo requestDispatcherMethod = typeof(PipelineDispatchers<TFor>)
.GetTypeInfo()
.GetMethods(BindingFlags.Static | BindingFlags.NonPublic)
.Where(m => m.Name == nameof(PipelineDispatchers<object>.GetDispatcher))
.Where(m => m.GetGenericArguments().Length == 1)
.First();
internal static readonly MethodInfo requestResultDispatcherMethod = typeof(PipelineDispatchers<TFor>)
.GetTypeInfo()
.GetMethods(BindingFlags.Static | BindingFlags.NonPublic)
.Where(m => m.Name == nameof(PipelineDispatchers<object>.GetDispatcher))
.Where(m => m.GetGenericArguments().Length == 2)
.First();
internal static readonly MethodInfo requestAsyncDispatcherMethod = typeof(PipelineDispatchers<TFor>)
.GetTypeInfo()
.GetMethods(BindingFlags.Static | BindingFlags.NonPublic)
.Where(m => m.Name == nameof(PipelineDispatchers<object>.GetAsyncDispatcher))
.Where(m => m.GetGenericArguments().Length == 1)
.First();
internal static readonly MethodInfo requestResultAsyncDispatcherMethod = typeof(PipelineDispatchers<TFor>)
.GetTypeInfo()
.GetMethods(BindingFlags.Static | BindingFlags.NonPublic)
.Where(m => m.Name == nameof(PipelineDispatchers<object>.GetAsyncDispatcher))
.Where(m => m.GetGenericArguments().Length == 2)
.First();
protected static void ResetDispatchers()
{
dispatchers.Clear();
asyncDispatchers.Clear();
}
/// <summary>
/// It gets a synchronous dispatch delegate without producing a result.
/// </summary>
/// <param name="requestType">The type of the request, is the input type.</param>
/// <returns>The delegate.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Action<object, IPipelineFactory<TFor>> GetDispatcher(Type requestType)
{
return (Action<object, IPipelineFactory<TFor>>)
dispatchers.GetOrCreate(requestType, requestDispatcherMethod);
}
/// <summary>
/// Get a synchronous dispatch delegate that produces a result.
/// </summary>
/// <typeparam name="TOut">Type of result to be produced.</typeparam>
/// <param name="requestType">The type of the request, is the input type.</param>
/// <returns>The delegate.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Func<object, IPipelineFactory<TFor>, TOut> GetDispatcher<TOut>(Type requestType)
{
return (Func<object, IPipelineFactory<TFor>, TOut>)
dispatchers.GetOrCreate(requestType, typeof(TOut), requestResultDispatcherMethod);
}
/// <summary>
/// Gets an asynchronous dispatch delegate without producing a result.
/// </summary>
/// <param name="requestType">The type of the request, is the input type.</param>
/// <returns>The delegate.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Func<object, IPipelineFactory<TFor>, Task> GetAsyncDispatcher(Type requestType)
{
return (Func<object, IPipelineFactory<TFor>, Task>)
dispatchers.GetOrCreate(requestType, requestAsyncDispatcherMethod);
}
/// <summary>
/// Get an asynchronous dispatch delegate that produces a result.
/// </summary>
/// <typeparam name="TOut">Type of result to be produced.</typeparam>
/// <param name="requestType">The type of the request, is the input type.</param>
/// <returns>The delegate.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Func<object, IPipelineFactory<TFor>, Task<TOut>> GetAsyncDispatcher<TOut>(Type requestType)
{
return (Func<object, IPipelineFactory<TFor>, Task<TOut>>)
dispatchers.GetOrCreate(requestType, typeof(TOut), requestResultAsyncDispatcherMethod);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static Action<object, IPipelineFactory<TFor>> GetDispatcher<TIn>()
{
return (request, factory) =>
{
var pipeline = factory.Create<TIn>();
pipeline.Send((TIn)request);
};
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static Func<object, IPipelineFactory<TFor>, TOut> GetDispatcher<TIn, TOut>()
{
return (request, factory) =>
{
var pipeline = factory.Create<TIn, TOut>();
return pipeline.Send((TIn)request);
};
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static Func<object, IPipelineFactory<TFor>, Task> GetAsyncDispatcher<TIn>()
{
return (request, factory) =>
{
var pipeline = factory.Create<TIn>();
return pipeline.SendAsync((TIn)request);
};
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static Func<object, IPipelineFactory<TFor>, Task<TOut>> GetAsyncDispatcher<TIn, TOut>()
{
return (request, factory) =>
{
var pipeline = factory.Create<TIn, TOut>();
return pipeline.SendAsync((TIn)request);
};
}
}
}
|
using System;
using System.IO;
using System.Threading.Tasks;
using Android.Content.Res;
using Newtonsoft.Json.Linq;
using XamarinImgur.Interfaces;
namespace MonocleGiraffe.Android
{
public class SecretsProvider : ISecretsProvider
{
AssetManager assets;
public SecretsProvider(AssetManager assets)
{
this.assets = assets;
}
public async Task<JObject> GetSecrets()
{
return JObject.Parse(await GetSecretsString());
}
private string secretsJson;
private async Task<string> GetSecretsString()
{
if (secretsJson == null)
{
using (StreamReader sr = new StreamReader(assets.Open("Secrets.json")))
{
secretsJson = sr.ReadToEnd();
}
}
return secretsJson;
}
}
}
|
namespace CrawlerMv.Models
{
public class CrawledItem
{
public MapInfosItem MapInfo { get; set; }
public MapItem Map { get; set; }
}
}
|
using System.ComponentModel.DataAnnotations;
namespace Application.Models.Forms
{
public class RecaptchaForm
{
#region Properties
[Display(Name = "Test-value")]
[Required]
public virtual string Value { get; set; }
#endregion
}
} |
using System;
namespace ServiciosProfesionales.Entities
{
public class Concepto
{
public int Id { get; set; }
public DateTime Fecha { get; set; }
public int FacturaId { get; set; }
public int ServicioId { get; set; }
public decimal Importe { get; set; }
public decimal Iva16 { get; set; }
public decimal Iva10 { get; set; }
public decimal Isr10 { get; set; }
public decimal Total { get; set; }
public Servicio Servicio { get; set; }
public Factura Factura { get; set; }
}
} |
using System.Collections.Generic;
using System.Threading.Tasks;
using Oddity.Cache;
using Oddity.Models;
namespace Oddity.Builders
{
/// <summary>
/// Represents a list builder used to retrieve data (collection of objects) without any filters.
/// </summary>
/// <typeparam name="TReturn">Type which will be returned after successful API request.</typeparam>
public class ListBuilder<TReturn> : BuilderBase<List<TReturn>> where TReturn : ModelBase, IIdentifiable, new()
{
private readonly CacheService<TReturn> _cache;
private readonly string _endpoint;
/// <summary>
/// Initializes a new instance of the <see cref="ListBuilder{TReturn}"/> class.
/// </summary>
/// <param name="context">The Oddity context used to interact with API.</param>
/// <param name="cache">Cache service used to speed up requests.</param>
/// <param name="endpoint">The endpoint used in this instance to retrieve data from API.</param>
public ListBuilder(OddityCore context, CacheService<TReturn> cache, string endpoint) : base(context)
{
_cache = cache;
_endpoint = endpoint;
}
/// <inheritdoc />
public override List<TReturn> Execute()
{
return ExecuteAsync().GetAwaiter().GetResult();
}
/// <inheritdoc />
public override bool Execute(List<TReturn> model)
{
return ExecuteAsync(model).GetAwaiter().GetResult();
}
/// <inheritdoc />
public override async Task<List<TReturn>> ExecuteAsync()
{
var model = new List<TReturn>();
await ExecuteAsync(model);
return model;
}
/// <inheritdoc />
public override async Task<bool> ExecuteAsync(List<TReturn> models)
{
if (Context.CacheEnabled && _cache.GetListIfAvailable(out var list, _endpoint))
{
models.AddRange(list);
if (Context.StatisticsEnabled)
{
Context.Statistics.CacheHits += (uint)list.Count;
}
return true;
}
var content = await GetResponseFromEndpoint($"{_endpoint}");
if (content == null)
{
return false;
}
DeserializeJson(content, models);
foreach (var deserializedObject in models)
{
deserializedObject.SetContext(Context);
}
if (Context.CacheEnabled)
{
_cache.UpdateList(models, _endpoint);
if (Context.StatisticsEnabled)
{
Context.Statistics.CacheUpdates += (uint)models.Count;
}
}
return true;
}
}
}
|
using System;
using System.Linq.Expressions;
using Nirvana.Mediation;
namespace Nirvana.TestFramework
{
public abstract class TestBase<TSutType, TInputType>
where TInputType : new()
{
protected IMediator Mediator;
protected TSutType Sut;
protected TInputType Task;
public abstract Func<TSutType> Build { get; }
protected TestBase()
{
Task = new TInputType();
}
public virtual void SetUpData()
{
}
public void SetupBuildAndRun()
{
SetUpData();
Sut = Build();
RunTest();
}
public abstract void RunTest();
public T Any<T>()
{
return Arg<T>.Is.Anything;
}
public T Matches<T>(Expression<Predicate<T>> match)
{
return Arg<T>.Matches(match);
}
public T Matches<T>(T value)
{
return Arg<T>.Matches(x => x.Equals(value));
}
}
} |
using VRage.Profiler;
namespace VRageRender.Profiler
{
public class MyNullRenderProfiler : MyRenderProfiler
{
protected override void Draw(VRage.Profiler.MyProfiler drawProfiler, int lastFrameIndex, int frameToDraw)
{
}
}
}
|
using System.Collections;
using System.Collections.Generic;
namespace IPHelper
{
public class TcpTable : IEnumerable<TcpRow>
{
#region Private Fields
private readonly IEnumerable<TcpRow> tcpRows;
#endregion
#region Constructors
public TcpTable(IEnumerable<TcpRow> tcpRows)
{
this.tcpRows = tcpRows;
}
#endregion
#region Public Properties
public IEnumerable<TcpRow> Rows
{
get { return tcpRows; }
}
#endregion
#region IEnumerable<TcpRow> Members
public IEnumerator<TcpRow> GetEnumerator()
{
return tcpRows.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return tcpRows.GetEnumerator();
}
#endregion
}
} |
using System.Collections.Generic;
using UnityEngine;
namespace Unity.UIWidgets.ui {
class TabStops {
int _tabWidth = int.MaxValue;
Font _font;
int _fontSize;
int _spaceAdvance;
const int kTabSpaceCount = 4;
public void setFont(Font font, int size) {
if (this._font != font || this._fontSize != size) {
this._tabWidth = int.MaxValue;
}
this._font = font;
// Recompute the advance of space (' ') if font size changes
if (this._fontSize != size) {
this._fontSize = size;
this._font.RequestCharactersInTextureSafe(" ", this._fontSize);
this._font.getGlyphInfo(' ', out var glyphInfo, this._fontSize, UnityEngine.FontStyle.Normal);
this._spaceAdvance = glyphInfo.advance;
}
}
public float nextTab(float widthSoFar) {
if (this._tabWidth == int.MaxValue) {
if (this._fontSize > 0) {
this._tabWidth = this._spaceAdvance * kTabSpaceCount;
}
}
if (this._tabWidth == 0) {
return widthSoFar;
}
return (Mathf.Floor(widthSoFar / this._tabWidth + 1) * this._tabWidth);
}
}
struct Candidate {
public int offset;
public int pre;
public float preBreak;
public float penalty;
public float postBreak;
public int preSpaceCount;
public int postSpaceCount;
}
class LineBreaker {
const float ScoreInfty = float.MaxValue;
const float ScoreDesperate = 1e10f;
int _lineLimit = 0;
// Limit number of lines, 0 means no limit
public int lineLimit {
get { return this._lineLimit; }
set { this._lineLimit = value; }
}
public static LineBreaker instance {
get {
if (_instance == null) {
_instance = new LineBreaker();
}
return _instance;
}
}
static LineBreaker _instance;
public static int[] newLinePositions(string text, out int count) {
count = 0;
for (var i = 0; i < text.Length; i++) {
if (text[i] == '\n') {
count++;
}
}
count++;
if (_newLinePositions == null || _newLinePositions.Length < count) {
_newLinePositions = new int[count];
}
count = 0;
for (var i = 0; i < text.Length; i++) {
if (text[i] == '\n') {
_newLinePositions[count++] = i;
}
}
_newLinePositions[count++] = text.Length;
return _newLinePositions;
}
static int[] _newLinePositions;
TextBuff _textBuf;
float[] _charWidths;
List<int> _breaks = new List<int>();
int _breaksCount = 0;
List<float> _widths = new List<float>();
int _widthsCount = 0;
WordBreaker _wordBreaker = new WordBreaker();
float _width = 0.0f;
float _preBreak;
float _lineWidth;
int _lastBreak;
int _bestBreak;
float _bestScore;
int _spaceCount;
TabStops _tabStops;
int mFirstTabIndex;
List<Candidate> _candidates = new List<Candidate>();
int _candidatesCount = 0;
public int computeBreaks() {
int nCand = this._candidatesCount;
if (nCand > 0 && (nCand == 1 || this._lastBreak != nCand - 1)) {
var cand = this._candidates[this._candidatesCount - 1];
this._pushBreak(cand.offset, (cand.postBreak - this._preBreak));
}
return this._breaksCount;
}
public int getBreaksCount() {
return this._breaksCount;
}
public int getBreak(int i) {
return this._breaks[i];
}
public float getWidth(int i) {
return this._widths[i];
}
public void resize(int size) {
if (this._charWidths == null || this._charWidths.Length < size) {
this._charWidths = new float[LayoutUtils.minPowerOfTwo(size)];
}
}
public void setText(string text, int textOffset, int textLength) {
this._textBuf = new TextBuff(text, textOffset, textLength);
this._wordBreaker.setText(this._textBuf);
this._wordBreaker.next();
this._candidatesCount = 0;
Candidate can = new Candidate {
offset = 0, postBreak = 0, preBreak = 0, postSpaceCount = 0, preSpaceCount = 0, pre = 0
};
this._addCandidateToList(can);
this._lastBreak = 0;
this._bestBreak = 0;
this._bestScore = ScoreInfty;
this._preBreak = 0;
this.mFirstTabIndex = int.MaxValue;
this._spaceCount = 0;
}
public void setLineWidth(float lineWidth) {
this._lineWidth = lineWidth;
}
public float addStyleRun(TextStyle style, int start, int end) {
float width = 0;
if (style != null) {
// Layout.measureText(this._width - this._preBreak, this._textBuf,
// start, end - start, style,
// this._charWidths, start, this._tabStops);
width = Layout.computeCharWidths(this._width - this._preBreak, this._textBuf.text,
this._textBuf.offset + start, end - start, style,
this._charWidths, start, this._tabStops);
}
int current = this._wordBreaker.current();
float postBreak = this._width;
int postSpaceCount = this._spaceCount;
for (int i = start; i < end; i++) {
char c = this._textBuf.charAt(i);
if (c == '\t') {
this._width = this._preBreak + this._tabStops.nextTab(this._width - this._preBreak);
if (this.mFirstTabIndex == int.MaxValue) {
this.mFirstTabIndex = i;
}
}
else {
if (LayoutUtils.isWordSpace(c)) {
this._spaceCount += 1;
}
this._width += this._charWidths[i];
if (!LayoutUtils.isLineEndSpace(c)) {
postBreak = this._width;
postSpaceCount = this._spaceCount;
}
}
if (i + 1 == current) {
if (style != null || current == end || this._charWidths[current] > 0) {
this._addWordBreak(current, this._width, postBreak, this._spaceCount, postSpaceCount, 0);
}
current = this._wordBreaker.next();
}
}
return width;
}
public void finish() {
this._wordBreaker.finish();
this._width = 0;
this._candidatesCount = 0;
this._breaksCount = 0;
this._widthsCount = 0;
this._textBuf = default;
}
public int getWidthsCount() {
return this._widthsCount;
}
public void setTabStops(TabStops tabStops) {
this._tabStops = tabStops;
}
void _addWordBreak(int offset, float preBreak, float postBreak, int preSpaceCount, int postSpaceCount,
float penalty) {
float width = this._candidates[this._candidatesCount - 1].preBreak;
if (postBreak - width > this._lineWidth) {
this._addCandidatesInsideWord(width, offset, postSpaceCount);
}
this._addCandidate(new Candidate {
offset = offset,
preBreak = preBreak,
postBreak = postBreak,
preSpaceCount = preSpaceCount,
postSpaceCount = postSpaceCount,
penalty = penalty
});
}
void _addCandidatesInsideWord(float width, int offset, int postSpaceCount) {
int i = this._candidates[this._candidatesCount - 1].offset;
width += this._charWidths[i++];
for (; i < offset; i++) {
float w = this._charWidths[i];
if (w > 0) {
this._addCandidate(new Candidate {
offset = i,
preBreak = width,
postBreak = width,
preSpaceCount = postSpaceCount,
postSpaceCount = postSpaceCount,
penalty = ScoreDesperate,
});
width += w;
}
}
}
void _addCandidateToList(Candidate cand) {
if (this._candidates.Count == this._candidatesCount) {
this._candidates.Add(cand);
this._candidatesCount++;
}
else {
this._candidates[this._candidatesCount++] = cand;
}
}
void _addCandidate(Candidate cand) {
int candIndex = this._candidatesCount;
this._addCandidateToList(cand);
if (cand.postBreak - this._preBreak > this._lineWidth) {
if (this._bestBreak == this._lastBreak) {
this._bestBreak = candIndex;
}
this._pushGreedyBreak();
}
while (this._lastBreak != candIndex && cand.postBreak - this._preBreak > this._lineWidth) {
for (int i = this._lastBreak + 1; i < candIndex; i++) {
float penalty = this._candidates[i].penalty;
if (penalty <= this._bestScore) {
this._bestBreak = i;
this._bestScore = penalty;
}
}
if (this._bestBreak == this._lastBreak) {
this._bestBreak = candIndex;
}
this._pushGreedyBreak();
}
if (cand.penalty <= this._bestScore) {
this._bestBreak = candIndex;
this._bestScore = cand.penalty;
}
}
void _pushGreedyBreak() {
var bestCandidate = this._candidates[this._bestBreak];
this._pushBreak(bestCandidate.offset, bestCandidate.postBreak - this._preBreak);
this._bestScore = ScoreInfty;
this._lastBreak = this._bestBreak;
this._preBreak = bestCandidate.preBreak;
}
void _pushBreak(int offset, float width) {
if (this.lineLimit == 0 || this._breaksCount < this.lineLimit) {
if (this._breaks.Count == this._breaksCount) {
this._breaks.Add(offset);
this._breaksCount++;
}
else {
this._breaks[this._breaksCount++] = offset;
}
if (this._widths.Count == this._widthsCount) {
this._widths.Add(width);
this._widthsCount++;
}
else {
this._widths[this._widthsCount++] = width;
}
}
}
}
} |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Internal.IL;
using Internal.TypeSystem;
using Internal.TypeSystem.Ecma;
using Microsoft.Diagnostics.Tracing.Parsers.Kernel;
namespace Microsoft.Diagnostics.Tools.Pgo
{
/// <summary>
/// A class that handles correlating IP samples/LBR samples back to managed methods.
/// </summary>
internal class SampleCorrelator
{
private readonly Dictionary<MethodDesc, PerMethodInfo> _methodInf = new Dictionary<MethodDesc, PerMethodInfo>();
private readonly MethodMemoryMap _memMap;
public SampleCorrelator(MethodMemoryMap memMap)
{
_memMap = memMap;
}
public long SamplesOutsideManagedCode { get; private set; }
public long SamplesInManagedCodeWithoutAnyMappings { get; private set; }
public long SamplesInManagedCodeOutsideMappings { get; private set; }
public long SamplesInUnknownInlinees { get; private set; }
public long SamplesInManagedCodeWithoutIL { get; private set; }
public long SamplesInManagedCodeOutsideFlowGraph { get; private set; }
public long TotalAttributedSamples { get; private set; }
private PerMethodInfo GetOrCreateInfo(MethodDesc md)
{
if (!_methodInf.TryGetValue(md, out PerMethodInfo pmi))
{
MethodIL il =
md switch
{
EcmaMethod em => EcmaMethodIL.Create(em),
_ => new InstantiatedMethodIL(md, EcmaMethodIL.Create((EcmaMethod)md.GetTypicalMethodDefinition())),
};
if (il == null)
{
return null;
}
_methodInf.Add(md, pmi = new PerMethodInfo());
pmi.IL = il;
pmi.FlowGraph = FlowGraph.Create(il);
pmi.Profile = new SampleProfile(pmi.IL, pmi.FlowGraph);
}
return pmi;
}
public SampleProfile GetProfile(MethodDesc md)
=> _methodInf.GetValueOrDefault(md)?.Profile;
public void SmoothAllProfiles()
{
foreach (PerMethodInfo pmi in _methodInf.Values)
pmi.Profile.SmoothFlow();
}
public void AttributeSamplesToIP(ulong ip, long numSamples)
{
MemoryRegionInfo region = _memMap.GetInfo(ip);
if (region == null)
{
SamplesOutsideManagedCode += numSamples;
return;
}
if (region.NativeToILMap == null)
{
SamplesInManagedCodeWithoutAnyMappings += numSamples;
return;
}
if (!region.NativeToILMap.TryLookup(checked((uint)(ip - region.StartAddress)), out IPMapping mapping))
{
SamplesInManagedCodeOutsideMappings += numSamples;
return;
}
if (mapping.InlineeMethod == null)
{
SamplesInUnknownInlinees += numSamples;
return;
}
PerMethodInfo pmi = GetOrCreateInfo(mapping.InlineeMethod);
if (pmi == null)
{
SamplesInManagedCodeWithoutIL += numSamples;
return;
}
if (pmi.Profile.TryAttributeSamples(mapping.ILOffset, 1))
{
TotalAttributedSamples += numSamples;
}
else
{
SamplesInManagedCodeOutsideFlowGraph += numSamples;
}
}
private LbrEntry64[] _convertedEntries;
public void AttributeSampleToLbrRuns(Span<LbrEntry32> lbr)
{
if (_convertedEntries == null || _convertedEntries.Length < lbr.Length)
{
Array.Resize(ref _convertedEntries, lbr.Length);
}
Span<LbrEntry64> convertedEntries = _convertedEntries[..lbr.Length];
for (int i = 0; i < lbr.Length; i++)
{
ref LbrEntry64 entry = ref convertedEntries[i];
entry.FromAddress = lbr[i].FromAddress;
entry.ToAddress = lbr[i].ToAddress;
entry.Reserved = lbr[i].Reserved;
}
AttributeSampleToLbrRuns(convertedEntries);
}
private readonly List<(BasicBlock, int)> _callStack = new();
private readonly HashSet<(InlineContext, BasicBlock)> _seenOnRun = new();
public void AttributeSampleToLbrRuns(Span<LbrEntry64> lbr)
{
// LBR record represents branches taken by the CPU, in
// chronological order with most recent branches first. Using this
// data we can construct the 'runs' of instructions executed by the
// CPU. We attribute a sample to all basic blocks in each run.
//
// As an example, if we see a branch A -> B followed by a branch C -> D,
// we conclude that the CPU executed the instructions from B to C.
//
// Note that we need some special logic to handle calls. If we see
// a call A -> B followed by a return B -> A, a straightforward
// attribution process would attribute multiple samples to the
// block containing A. To deal with this we track in a list the
// basic blocks + offsets that we left, and if we see a return to
// the same basic block at a later offset, we skip that basic
// block.
// Note that this is an approximation of the call stack as we
// cannot differentiate between tailcalls and calls, so there
// may be BBs we left in here that we never return to.
// Therefore we cannot just use a straightforward stack.
List<(BasicBlock, int)> callStack = _callStack;
callStack.Clear();
// On each run we translate the endpoint RVAs to all IL offset
// mappings we have for that range. It is possible (and happens
// often) that we see multiple IL offsets corresponding to the same
// basic block.
//
// Therefore, we keep track of the basic blocks we have seen in each
// run to make sure we only attribute once. However, due to inlinees
// we sometimes may want to attribute twice, for example if A is inlined in
// A(); A();
// Therefore, we also key by the inline context.
HashSet<(InlineContext, BasicBlock)> seenOnRun = _seenOnRun;
MethodMemoryMap memMap = _memMap;
for (int i = lbr.Length - 2; i >= 0; i--)
{
ref LbrEntry64 prev = ref lbr[i + 1];
ref LbrEntry64 cur = ref lbr[i];
MemoryRegionInfo prevToInf = memMap.GetInfo(prev.ToAddress);
MemoryRegionInfo curFromInf = memMap.GetInfo(cur.FromAddress);
// If this run is not in the same function then ignore it.
// This probably means IP was changed out from beneath us while
// recording.
if (prevToInf == null || prevToInf != curFromInf)
continue;
if (curFromInf.NativeToILMap == null)
continue;
// Attribute samples to run.
seenOnRun.Clear();
uint rvaMin = checked((uint)(prev.ToAddress - prevToInf.StartAddress));
uint rvaMax = checked((uint)(cur.FromAddress - curFromInf.StartAddress));
int lastILOffs = -1;
BasicBlock lastBB = null;
bool isFirst = true;
foreach (IPMapping mapping in curFromInf.NativeToILMap.LookupRange(rvaMin, rvaMax))
{
bool isFirstMapping = isFirst;
isFirst = false;
if (mapping.InlineeMethod == null)
continue;
PerMethodInfo pmi = GetOrCreateInfo(mapping.InlineeMethod);
if (pmi == null)
continue;
BasicBlock bb = pmi.FlowGraph.Lookup(mapping.ILOffset);
if (bb == null)
continue;
lastBB = bb;
lastILOffs = mapping.ILOffset;
if (seenOnRun.Add((mapping.InlineContext, bb)))
{
if (isFirstMapping)
{
// This is the first mapping in the run. Check to
// see if we returned to this BB in the callstack,
// and if so, skip attributing anything to the
// first BB.
bool skip = false;
for (int j = callStack.Count - 1; j >= 0; j++)
{
(BasicBlock callFromBB, int callFromILOffs) = callStack[j];
if (callFromBB == bb && mapping.ILOffset >= callFromILOffs)
{
// Yep, we previously left 'bb' at
// 'callFromILOffs', and now we are jumping
// back to the same BB at a later offset.
skip = true;
callStack.RemoveRange(j, callStack.Count - j);
break;
}
}
if (skip)
continue;
}
pmi.Profile.AttributeSamples(bb, 1);
}
}
// Now see if this is a cross-function jump.
MemoryRegionInfo curToInf = memMap.GetInfo(cur.ToAddress);
// TODO: This check and above skipping logic does not handle recursion.
if (curFromInf != curToInf)
{
// Yes, either different managed function or not managed function (e.g. prestub).
// Record this.
if (lastBB != null)
{
callStack.Add((lastBB, lastILOffs));
}
}
}
}
public override string ToString() => $"{TotalAttributedSamples} samples in {_methodInf.Count} methods";
private class PerMethodInfo
{
public MethodIL IL { get; set; }
public FlowGraph FlowGraph { get; set; }
public SampleProfile Profile { get; set; }
public override string ToString() => IL.OwningMethod.ToString();
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.