content stringlengths 23 1.05M |
|---|
//
// SQLiteStatus.cs
//
// Copyright (c) 2016 Couchbase, Inc All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
namespace LiteCore.Interop
{
public enum SQLiteStatus
{
Ok, /* Successful result */
Error, /* SQL error or missing database */
Internal, /* Internal logic error in SQLite */
Perm, /* Access permission denied */
Abort, /* Callback routine requested an abort */
Busy, /* The database file is locked */
Locked, /* A table in the database is locked */
NoMem, /* A malloc() failed */
ReadOnly, /* Attempt to write a readonly database */
Interrupt, /* Operation terminated by sqlite3_interrupt()*/
IoErr, /* Some kind of disk I/O error occurred */
Corrupt, /* The database disk image is malformed */
NotFound, /* Unknown opcode in sqlite3_file_control() */
Full, /* Insertion failed because database is full */
CantOpen, /* Unable to open the database file */
Protocol, /* Database lock protocol error */
Empty, /* Database is empty */
Schema, /* The database schema changed */
TooBig, /* String or BLOB exceeds size limit */
Constraint, /* Abort due to constraint violation */
Mismatch, /* Data type mismatch */
Misuse, /* Library used incorrectly */
NoLfs, /* Uses OS features not supported on host */
Auth, /* Authorization denied */
Format, /* Auxiliary database format error */
Range, /* 2nd parameter to sqlite3_bind out of range */
NotADb, /* File opened that is not a database file */
Notice, /* Notifications from sqlite3_log() */
Warning, /* Warnings from sqlite3_log() */
Row, /* sqlite3_step() has another row ready */
Done, /* sqlite3_step() has finished executing */
}
}
|
namespace TRuDI.Models.BasicData
{
using System.Collections.Generic;
/// <summary>
/// Die Klasse IntervalBlock enthält die einzelnen Intervallwerte. Eine Nachricht
/// muss mindestens eine Instanz der Klasse IntervalBlock enthalten.
///
/// Jede Instanz der Klasse IntervalBlock:
/// muss auf mindestens eine Instanz der Klasse IntervalReading verweisen.
/// </summary>
public class IntervalBlock
{
/// <summary>
/// Im Konstruktor wird sichergestellt, dass alle vorhandenen Listen
/// vor dem ersten Zugriff initialisert werden.
/// </summary>
public IntervalBlock()
{
this.IntervalReadings = new List<IntervalReading>();
}
/// <summary>
/// Der Verweis auf die Instanz der Klasse MeterReading, zu der
/// die Instanz der Klasse IntervalBlock zugehörig ist.
/// </summary>
public MeterReading MeterReading
{
get; set;
}
/// <summary>
/// Jede Instanz Der Klasse IntervalReading beinhaltet die Daten
/// zu einem konkreten Messwert.
/// </summary>
public List<IntervalReading> IntervalReadings
{
get; set;
}
/// <summary>
/// Das Datenelement interval beschreibt die gesamte Zeitperiode, für
/// die die nachfolgenden Messwerte in der Messwertliste enthalten sind.
///
/// Die Zeitperiode wird durch einen Startzeitpunkt und eine Dauer definiert.
///
/// Der Startzeitpunkt wird als xs:dateTime beschrieben. Die Dauer wird als ganzzahliger
/// Sekundenwert beschrieben.
///
/// Jede Instanz der Klasse IntervalBlock muss ein Datenelement vom Typ interval enthalten.
/// </summary>
public Interval Interval
{
get; set;
}
}
}
|
using UnityEngine;
using System.Collections;
public class GoalController : MonoBehaviour
{
// publisher
public delegate void GoalScored(GameObject ball);
public static event GoalScored OnGoalScored;
public void FitTo(float halfWidth, float height, SideLR side)
{
float destX = side == SideLR.Left ? -(halfWidth + 1f) : halfWidth + 1f;
transform.position = new Vector3(destX, 0f, 0f);
transform.localScale = new Vector3(1f, 2f * height, 1f);
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.CompareTag("Ball"))
{
if (OnGoalScored != null)
{
OnGoalScored(collision.gameObject); // broadcast information
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using Rhino.Mocks;
using Rhino.Mocks.Constraints;
namespace RhinoMocksConstraints
{
/// <summary>
/// Constraints are a way to verify that a method's arguments match a certain criteria.
/// </summary>
/// <see cref="http://www.ayende.com/wiki/Rhino+Mocks+Constraints.ashx"/>
public class RhinoMocksConstraintsTest
{
[Test]
public void ConstraintsGroupingTest()
{
MockRepository mocks = new MockRepository();
IValidationMessagesLogger loggerMock = mocks.DynamicMock<IValidationMessagesLogger>(null);
IValidator Validator = new Validator();
using (mocks.Record())
{
loggerMock.LogMessage(null);
LastCall.Constraints(/*LastCall notation is used because LogMessage(...) does not return anything (is void).*/
new PropertyConstraint("Text", Rhino.Mocks.Constraints.Text.Contains("Whoa!")) &&
Property.Value("MessageKind", ValidationMessageKind.Error))
.Repeat.Once();
}//implicitly calls mocks.ReplayAll()
Validator.Validate("input", loggerMock);//a validator that uses logger internally to log validation messages.
mocks.VerifyAll();
}
[Test]
public void ConstraintsGroupingTest_AAA()
{
//Arrange
IValidationMessagesLogger loggerMock = MockRepository.GenerateMock<IValidationMessagesLogger>(null);
loggerMock.Expect(l => l.LogMessage(null)).IgnoreArguments().Constraints(
new PropertyConstraint("Text", Rhino.Mocks.Constraints.Text.Contains("Whoa!")) &&
Property.Value("MessageKind", ValidationMessageKind.Error))
.Repeat.Once();
//Act
IValidator Validator = new Validator();
Validator.Validate("input", loggerMock);//a validator that uses logger internally to log validation messages.
//Assert
loggerMock.VerifyAllExpectations();
}
}
}
|
// -----------------------------------------------------------------------
// <copyright file="DictionaryUtilities.cs" company="Ris Adams">
// Copyright © 2014 Ris Adams. All rights reserved.
// </copyright>
// <author></author>
// <project>CAS.Common</project>
// -----------------------------------------------------------------------
#region
using System.Collections.Generic;
using System.Linq;
#endregion
namespace CAS.Common
{
/// <summary>
/// Class DictionaryUtilities.
/// </summary>
public static class DictionaryUtilities
{
/// <summary>
/// Merges the specified target.
/// </summary>
/// <typeparam name="TDict">The type of the t dictionary.</typeparam>
/// <typeparam name="TKey">The type of the t key.</typeparam>
/// <typeparam name="TValue">The type of the t value.</typeparam>
/// <param name="target">The target.</param>
/// <param name="sources">The sources.</param>
/// <returns>TDict.</returns>
public static TDict Merge<TDict, TKey, TValue>(this TDict target, params IDictionary<TKey, TValue>[] sources)
where TDict : IDictionary<TKey, TValue>, new()
{
var map = new TDict();
foreach (var p in (new List<IDictionary<TKey, TValue>> {target}).Concat(sources).SelectMany(src => src))
{
map[p.Key] = p.Value;
}
return map;
}
/// <summary>
/// Appends the specified target.
/// </summary>
/// <typeparam name="TDict">The type of the t dictionary.</typeparam>
/// <typeparam name="TKey">The type of the t key.</typeparam>
/// <typeparam name="TValue">The type of the t value.</typeparam>
/// <param name="target">The target.</param>
/// <param name="sources">The sources.</param>
public static void Append<TDict, TKey, TValue>(this TDict target, params IDictionary<TKey, TValue>[] sources)
where TDict : IDictionary<TKey, TValue>, new()
{
if (target == null)
return;
foreach (var source in sources)
{
foreach (var key in source.Keys)
{
if (!target.ContainsKey(key))
target.Add(key, source[key]);
else
{
target[key] = source[key];
}
}
}
}
}
}
|
using SkinSelfie.ServiceData.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SkinSelfie.ServiceData.Models;
using System.Linq.Expressions;
namespace SkinSelfie.Repository
{
public class PhotoRepository : IReadWriteRepository<ServiceData.Models.Photo>
{
private readonly SkinSelfieDB context;
public PhotoRepository()
{
context = new SkinSelfieDB();
}
public async Task Delete(int id)
{
context.Photos.Remove(context.Photos.Single(p => p.Id == id));
await context.SaveChangesAsync();
}
public IQueryable<ServiceData.Models.Photo> GetAll()
{
return context.Photos.Select(p => new ServiceData.Models.Photo
{
Id = p.Id,
CreatedAt = p.CreatedAt,
Url = p.Url,
ThumbUrl = p.ThumbUrl,
Notes = p.Notes,
PhotoDescription = p.PhotoDescription,
Rating = p.Rating,
Treatment = p.Treatment,
UserCondition = new ServiceData.Models.UserCondition
{
Id = p.UserCondition.Id,
Condition = p.UserCondition.Condition,
Passcode = p.UserCondition.Passcode,
SkinRegion = new ServiceData.Models.SkinRegion
{
Id = p.UserCondition.SkinRegion.Id,
Name = p.UserCondition.SkinRegion.Name,
BodyPart = new ServiceData.Models.BodyPart
{
Id = p.UserCondition.SkinRegion.BodyPart.Id,
Name = p.UserCondition.SkinRegion.BodyPart.Name
}
},
StartDate = p.UserCondition.StartDate,
Treatment = p.UserCondition.Treatment
}
});
}
public ServiceData.Models.Photo GetById(int id)
{
try
{
return GetAll().Single(photo => photo.Id == id);
}
catch
{
return null;
}
}
public ServiceData.Models.Photo Insert(ServiceData.Models.Photo model)
{
try
{
Photo result = context.Photos.Add(new Photo
{
Notes = model.Notes,
CreatedAt = model.CreatedAt,
PhotoDescription = model.PhotoDescription,
Rating = model.Rating,
Treatment = model.Treatment,
Url = model.Url,
ThumbUrl = model.ThumbUrl,
UserConditionId = model.UserCondition.Id,
});
context.SaveChanges();
result.UserCondition = new UserCondition
{
Id = model.UserCondition.Id,
Condition = model.UserCondition.Condition,
Owner = new User
{
Id = model.UserCondition.Owner.Id,
Name = model.UserCondition.Owner.Name,
Email = model.UserCondition.Owner.Email,
BirthDate = model.UserCondition.Owner.BirthDate
},
OwnerId = model.UserCondition.Owner.Id,
Passcode = model.UserCondition.Passcode,
SkinRegion = new SkinRegion
{
Id = model.UserCondition.SkinRegion.Id,
Name = model.UserCondition.SkinRegion.Name
}
};
return ToServiceModel(result);
}
catch (Exception e)
{
return null;
}
}
public IQueryable<ServiceData.Models.Photo> Search(Expression<Func<ServiceData.Models.Photo, bool>> predicate)
{
throw new NotImplementedException();
}
public ServiceData.Models.Photo Update(ServiceData.Models.Photo model)
{
var entity = context.Photos.Single(photo => photo.Id == model.Id);
entity.Notes = model.Notes;
entity.PhotoDescription = model.PhotoDescription;
entity.Rating = model.Rating;
entity.Treatment = model.Treatment;
entity.ThumbUrl = model.ThumbUrl;
entity.Url = model.Url;
context.SaveChangesAsync();
return model;
}
private ServiceData.Models.Photo ToServiceModel(Photo photo)
{
return new ServiceData.Models.Photo
{
Id = photo.Id,
CreatedAt = photo.CreatedAt,
Notes = photo.Notes,
PhotoDescription = photo.PhotoDescription,
Rating = photo.Rating,
Treatment = photo.Treatment,
Url = photo.Url,
ThumbUrl = photo.ThumbUrl,
UserCondition = new ServiceData.Models.UserCondition
{
Id = photo.UserCondition.Id,
Condition = photo.UserCondition.Condition,
Passcode = photo.UserCondition.Passcode,
StartDate = photo.UserCondition.StartDate,
Treatment = photo.UserCondition.Treatment,
Owner = new ServiceData.Models.User
{
Id = photo.UserCondition.Owner.Id,
Name = photo.UserCondition.Owner.Name,
Email = photo.UserCondition.Owner.Email,
BirthDate = photo.UserCondition.Owner.BirthDate
}
}
};
}
}
}
|
using GraphicsComposerLib.POVRay.SDL.Textures;
namespace GraphicsComposerLib.POVRay.SDL.Directives
{
public sealed class SdlDefaultTextureDirective : SdlDirective
{
public ISdlTexture Texture { get; set; }
}
}
|
using pt;
public class entrada{
public static void Main(string[] args){
double numero;
pt.pts.escrever("escreva a sua idade?");
numero=pt.pts.entradan();
pt.pts.escrever("");
pt.pts.escrever("a sua idade é!");
pt.pts.escrever(pt.pts.texton(numero));
}
}
|
using System.Runtime.InteropServices;
namespace RecklessBoon.MacroDeck.GPUZ
{
[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Unicode)]
public struct GPUZ_RECORD
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
public string key;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
public string value;
}
}
|
namespace CvSystem.Web.ViewModels.Add
{
using CvSystem.Data.Models;
using CvSystem.Web.Infrastructure.Mapping;
public class EducationIdViewModel : IMapFrom<Education>
{
public int Id { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using ScaffoldView.Models;
namespace ScaffoldView.Data
{
public class ScaffoldViewContext : DbContext
{
public ScaffoldViewContext(DbContextOptions<ScaffoldViewContext> options)
: base(options)
{
}
public DbSet<Account> Account { get; set; }
}
} |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore.Utilities;
namespace Microsoft.EntityFrameworkCore.Storage.Internal
{
/// <summary>
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public class FallbackTypeMappingSource : TypeMappingSource
{
/// <summary>
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
#pragma warning disable 618
private readonly ITypeMapper _typeMapper;
#pragma warning restore 618
/// <summary>
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public FallbackTypeMappingSource(
[NotNull] TypeMappingSourceDependencies dependencies,
#pragma warning disable 618
[NotNull] ITypeMapper typeMapper)
#pragma warning restore 618
: base(dependencies)
{
Check.NotNull(typeMapper, nameof(typeMapper));
_typeMapper = typeMapper;
}
/// <summary>
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
protected override CoreTypeMapping FindMapping(TypeMappingInfo mappingInfo)
{
Check.NotNull(mappingInfo, nameof(mappingInfo));
return _typeMapper.IsTypeMapped(mappingInfo.ProviderClrType)
? new CoreTypeMapping(mappingInfo.ProviderClrType)
: null;
}
}
}
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Rabbit.Kernel.Extensions.Folders;
using System.Linq;
namespace Rabbit.Kernel.Tests.Extensions
{
[TestClass]
public sealed class ExtensionHarvesterTests : TestBase
{
public IExtensionHarvester ExtensionHarvester { get; set; }
// public ILifetimeScope LifetimeScope { get; set; }
[TestMethod]
public void HarvestExtensionsTest()
{
var extensions = ExtensionHarvester.HarvestExtensions(new[] { "~/Modules" }, "Module", "Module.txt", false);
Assert.IsTrue(extensions.Any());
}
}
} |
namespace SystemModule;
public class TAddAbility
{
public ushort wHP;
public ushort wMP;
public ushort wHitPoint;
public ushort wSpeedPoint;
public int wAC;
public int wMAC;
public int wDC;
public int wMC;
public int wSC;
public ushort wAntiPoison;
public ushort wPoisonRecover;
public ushort wHealthRecover;
public ushort wSpellRecover;
public ushort wAntiMagic;
public byte btLuck;
public byte btUnLuck;
public byte btWeaponStrong;
public ushort nHitSpeed;
public byte btUndead;
public ushort Weight;
public ushort WearWeight;
public ushort HandWeight;
} |
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Game.Maths;
namespace Game.WorldGen
{
/// <summary>
/// A class linearly mapping intervals of values to new intervals.
/// </summary>
/// <remarks>
/// This class is used in the world generation progress, where thresholds for different terrain intervals
/// are determined at runtime.
///
/// If a mapper contains the entries (0.35, 0.5) and (0.5, 0.85), then this describes the following intervals:
/// - [0, 0.35] which gets mapped to [0, 0.5]
/// - [0.35, 0.5] which gets mapped to [0.5, 0.85]
/// - [0.5, 1.0] which gets mapped to [0.85, 1]
///
/// The first number in each entry is the upper bound in the source range, and the second number is
/// the upper bound in the destination range.
/// </remarks>
public class ValueMapper : IEnumerable<(float, float)>
{
/// <summary>
/// All entries in this value mapper
/// </summary>
protected List<(float SourceEnd, float DestinationEnd)> Entries { get; set; }
/// <summary>
/// Create a new value mapper instance with given entries.
/// </summary>
public ValueMapper(params (float SourceEnd, float DestinationEnd)[] entries)
{
this.Entries = new List<(float SourceEnd, float DestinationEnd)>(entries);
}
public ValueMapper()
{
this.Entries = new List<(float SourceEnd, float DestinationEnd)>();
}
public void Add(float sourceEnd, float destinationEnd)
{
this.Entries.Add((sourceEnd, destinationEnd));
}
/// <summary>
/// Map given value according to the intervals defined by the stored entries.
/// </summary>
public float Map(float value)
{
if (this.Entries.Count <= 0)
return 0.0f;
var sourceEnd = 0.0f;
var sourceLength = 0.0f;
var destinationEnd = 0.0f;
var destinationLength = 0.0f;
for (var i = 0; i < this.Entries.Count; ++i)
{
var entry = this.Entries[i];
var sourceBegin = sourceEnd;
sourceEnd = entry.SourceEnd;
var destinationBegin = destinationEnd;
destinationEnd = entry.DestinationEnd;
if (value <= sourceEnd)
{
// Map it into the range
var sourceRange = new Range(sourceBegin, sourceEnd);
var destinationRange = new Range(destinationBegin, destinationEnd);
return MathUtil.Map(value, sourceRange, destinationRange);
}
}
// Value is in last range
var lastSourceRange = new Range(sourceEnd, 1.0f);
var lastDestinationRange = new Range(destinationEnd, 1.0f);
return MathUtil.Map(value, lastSourceRange, lastDestinationRange);
}
public IEnumerator<(float, float)> GetEnumerator()
{
return this.Entries.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
} |
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DiscordBotPlayground.DiceRolling
{
public class DiceRollFormatter : IDiceRollFormatter
{
public string Format(SummaryRollResult rollResult)
{
var stringBuilder = new StringBuilder();
var diceGroupIndex = 1;
foreach (var groupResult in rollResult.DiceGroupRollResults)
{
var formattedGroupResult = FormatDiceGroupRoll(groupResult, diceGroupIndex++);
stringBuilder.AppendLine(formattedGroupResult);
}
return stringBuilder.ToString();
}
private string FormatDiceGroupRoll(DiceGroupRollResult rollResult, int groupIndex)
{
string result;
if (rollResult.DiceResults.Count > 1)
{
result = FormatMultiDiceGroupRoll(rollResult, groupIndex);
}
else
{
result = FormatSingleDiceGroupRoll(rollResult, groupIndex);
}
return result;
}
private string FormatMultiDiceGroupRoll(DiceGroupRollResult result, int groupIndex)
{
var stringBuilder = new StringBuilder();
var groupContents = FormatDiceGroupContents(result);
stringBuilder.AppendLine($"Группа #{groupIndex} ({groupContents}):");
var diceIndex = 1;
foreach (var diceResult in result.DiceResults)
{
var linePrefix = $"Кость #{diceIndex++}";
var formattedDiceRoll = FormatSingleDiceRoll(diceResult, linePrefix);
stringBuilder.AppendLine(formattedDiceRoll);
}
stringBuilder.AppendLine($"Сумма: {result.Sum} / {result.MaxSum}");
return stringBuilder.ToString();
}
private string FormatSingleDiceGroupRoll(DiceGroupRollResult result, int groupIndex)
{
var firstDiceRollResult = result.DiceResults.First();
var linePrefix = $"Одиночная кость #{groupIndex}";
return FormatSingleDiceRoll(firstDiceRollResult, linePrefix);
}
private string FormatDiceGroupContents(DiceGroupRollResult groupRollResult)
{
var diceCountBySideCount = new Dictionary<int, int>();
foreach (var rollResult in groupRollResult.DiceResults)
{
var currentSideCount = rollResult.MaxResult;
if (diceCountBySideCount.TryGetValue(currentSideCount, out var diceCount))
{
diceCountBySideCount[currentSideCount] = diceCount + 1;
}
else
{
diceCountBySideCount.Add(currentSideCount, 1);
}
}
var formattedDice = diceCountBySideCount.Select(x => x.Value == 1 ? $"d{x.Key}" : $"{x.Value}d{x.Key}");
return string.Join("+", formattedDice);
}
private string FormatSingleDiceRoll(DiceRollResult result, string linePrefix)
{
return $"{linePrefix}: {result.Result} / {result.MaxResult}";
}
}
} |
namespace OStimAnimationTool.Core.Models.Navigation
{
public enum Actors
{
Dom = 0,
Sub = 1
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpacePlayer : MonoBehaviour, IDestructable
{
//Range sets the range that speed can be set to in the inspector.
//Tooltip creates a tooltip in the inspector.
[Range(0, 200)] [Tooltip("speed of the player")] public float speed = 100;
// Update is called once per frame
void Update()
{
// Movement
Vector3 direction = Vector3.zero;
direction.x = Input.GetAxis("Horizontal");
direction.z = Input.GetAxis("Vertical");
transform.Translate(direction * speed * Time.deltaTime);
float x, z;
x = transform.position.x < -190 ? -190 : transform.position.x;
x = transform.position.x > 190 ? 190 : x;
z = transform.position.z < -105 ? -105 : transform.position.z;
z = transform.position.z > 105 ? 105 : z;
transform.position = new Vector3(x, transform.position.y, z);
// Shooting
if ((Input.GetButton("Fire1")))
{
GetComponent<SpaceWeapon>().Fire();
}
// Health Bar
GameManager.Instance.playerHealth = GetComponent<Health>().health;
}
public void Destroyed()
{
GameManager.Instance.playerHealth = 0;
GameManager.Instance.OnPlayerDead();
}
}
|
namespace _02.Photo
{
public static class TagTransformer
{
private const string Pound = "#";
private const int RequiredLeght = 20;
public static string Transform(string tag)
{
string formattedTag = tag;
formattedTag = formattedTag.Replace(" ", string.Empty);
if (!formattedTag.StartsWith(Pound))
{
formattedTag = Pound + formattedTag;
}
if (formattedTag.Length > RequiredLeght)
{
formattedTag = formattedTag.Substring(0, RequiredLeght);
}
return formattedTag;
}
}
} |
namespace SharpVectors.Dom.Css
{
/// <summary>
/// The <c>ICssCharsetRule</c> interface represents a <c>@charset</c> rule in a CSS style sheet. The value of the
/// encoding attribute does not affect the encoding of text data in the DOM objects; this encoding is
/// always UTF-16. After a stylesheet is loaded, the value of the encoding attribute is the value found in the
/// <c>@charset</c> rule. If there was no <c>@charset</c> in the original document, then no <c>ICssCharsetRule</c> is created.
/// The value of the encoding attribute may also be used as a hint for the
/// encoding used on serialization of the style sheet.
/// </summary>
public interface ICssCharsetRule : ICssRule
{
/// <summary>
/// The encoding information used in this <c>@charset</c> rule.
/// </summary>
/// <exception cref="DomException">
/// <c>SYNTAX_ERR</c>: Raised if the specified encoding value has a syntax error and is unparsable.
/// </exception>
/// <exception cref="DomException">
/// <c>NO_MODIFICATION_ALLOWED_ERR</c>: Raised if this encoding rule is readonly.
/// </exception>
string Encoding
{
get;
set;
}
}
}
|
namespace Nancy
{
using System;
/// <summary>
/// Predicate used to decide if a <see cref="Type"/> should be included when resolving types.
/// </summary>
/// <param name="type">The <see cref="Type"/> that is being inspected.</param>
/// <value><see langword="true"/> if the type should be included in the result, otherwise <see langword="false"/>.</value>
public delegate bool TypeResolveStrategy(Type type);
}
|
using Newtonsoft.Json;
using ZendeskApi.Client.Models;
namespace ZendeskApi.Client.Responses
{
public class OrganizationMembershipResponse
{
[JsonProperty("organization_membership")]
public OrganizationMembership OrganizationMembership { get; set; }
}
} |
using UnityEngine;
using System.Collections.Generic;
[CreateAssetMenu(fileName = "ParticleRegistry", menuName = "Particles/ParticleRegistry", order = 2)]
public class ParticleRegistry : ScriptableObject
{
public List<Particle> Particles = new List<Particle>();
}
|
using System;
using System.Collections.Generic;
namespace PVOutput.Net.Objects
{
/// <summary>
/// Describes a list of dates without any recorded data.
/// </summary>
public interface IMissing
{
/// <summary>
/// Dates where no data has been recorded for.
/// </summary>
IEnumerable<DateTime> Dates { get; set; }
}
}
|
using System.Xml;
namespace Perrich.SepaWriter.Utils
{
/// <summary>
/// Some Utilities to manage XML
/// </summary>
public static class XmlUtils
{
/// <summary>
/// Find First element in the Xml document with provided name
/// </summary>
/// <param name="document">The Xml Document</param>
/// <param name="nodeName">The name of the node</param>
/// <returns></returns>
public static XmlElement GetFirstElement(XmlNode document, string nodeName)
{
return document.SelectSingleNode("//" + nodeName) as XmlElement;
}
/// <summary>
/// Create a BIC
/// </summary>
/// <param name="element">The Xml element</param>
/// <param name="iban">The iban</param>
/// <returns></returns>
public static void CreateBic(XmlElement element, SepaIbanData iban)
{
if (iban.UnknownBic)
{
element.NewElement("FinInstnId").NewElement("Othr").NewElement("Id", "NOTPROVIDED");
}
else
{
if (!string.IsNullOrWhiteSpace(iban.Bic))
{
element.NewElement("FinInstnId").NewElement("BIC", iban.Bic);
}
}
}
}
}
|
using System;
using System.Drawing;
namespace DumbBotsNET.Api
{
public interface IDirectorApi
{
#region Extensibility
IUserEntity CreateCustomEntity(string modelFile, string textureFile, Point position);
bool RemoveCustomEntity(IUserEntity userEntity);
#endregion Extensibility
#region Messaging
void SendMessageToPlayers(string message, TimeSpan time);
void SendMessageToSelf(string message, TimeSpan time);
void SendMessageToPlayer(int player, string message, TimeSpan time);
string FetchMessage();
#endregion Messaging
#region Rules
void SetBazookaRespawnTime(TimeSpan value);
void SetBulletDamage(int value);
void SetBulletReloadTime(TimeSpan value);
void SetBulletSpeedModifier(int value);
void SetDefaultAmmo(int value);
void SetMaxAmmo(int value);
void SetMaxHealth(int value);
void SetMedkitHealthBoost(int value);
void SetMedkitRespawnTime(TimeSpan value);
void SetRocketDamage(int value);
void SetRocketReloadTime(TimeSpan value);
void SetRocketSpeedModifier(int value);
void SetPlayerSpeed(int player, double value);
void SetPlayerDamageModifier(int player, double modifier);
void SetGameSpeed(float value);
#endregion Rules
#region Player Interaction
Point GetPlayerPosition(int player);
void SetPlayerPosition(int player, Point position);
void HealPlayer(int player, int health);
void GivePlayerAmmo(int player, int ammo);
int GetPlayerScore(int player);
void SetPlayerScore(int player, int score);
int GetPlayerHealth(int player);
int GetPlayerAmmo(int player);
int GetPlayerCustomEntitiesDestroyed(int player);
#endregion Player Interaction
#region Game Information
TimeSpan GetGameTime();
Point GetPositionFromMapPoint(int x, int y);
#endregion Game Information
#region Sound
void PlaySound(string filename);
#endregion Sound
#region Text
void SayText(string message, System.Drawing.Color color, Point position);
#endregion Text
#region Keyboard
bool IsKeyDown(params System.Windows.Forms.Keys[] keys);
#endregion Keyboard
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
namespace PeNet.Analyzer
{
internal static class ReflectiveEnumerator
{
public static IEnumerable<T> GetEnumerableOfType<T>(params object[] constructorArgs) where T : class
{
var types = typeof(T)
.Assembly.GetTypes()
.Where(t => t.IsSubclassOf(typeof(T)) && !t.IsAbstract)
.Select(t => (T)Activator.CreateInstance(t, constructorArgs));
return types;
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataFaker.Models.Prograd3
{
[Table( "alunograd" )]
public class AlunoGrad : Model
{
[Key]
public int codalu_alug { get; set; }
public string nomealu_alug { get; set; }
public string cpf_alug { get; set; }
}
}
|
using System.Runtime.InteropServices;
using System.Collections.Generic;
namespace ViconDataStreamSDK.CSharp
{
public enum Result:int
{
Unknown = 0,
NotImplemented = 1,
Success = 2,
InvalidHostName = 3,
InvalidMulticastIP = 4,
ClientAlreadyConnected = 5,
ClientConnectionFailed = 6,
ServerAlreadyTransmittingMulticast = 7,
ServerNotTransmittingMulticast = 8,
NotConnected = 9,
NoFrame = 10,
InvalidIndex = 11,
InvalidCameraName = 12,
InvalidSubjectName = 13,
InvalidSegmentName = 14,
InvalidMarkerName = 15,
InvalidDeviceName = 16,
InvalidDeviceOutputName = 17,
InvalidLatencySampleName = 18,
CoLinearAxes = 19,
LeftHandedAxes = 20,
HapticAlreadySet = 21,
EarlyDataRequested = 22,
LateDataRequested = 23,
InvalidOperation = 24,
NotSupported = 25,
ConfigurationFailed = 26,
NotPresent = 27
}
public enum StreamMode:int
{
ClientPull = 0,
ClientPullPreFetch = 1,
ServerPush = 2,
}
public enum Direction
{
Up = 0,
Down = 1,
Left = 2,
Right = 3,
Forward = 4,
Backward = 5,
}
public enum DeviceType
{
Unknown = 0,
ForcePlate = 1,
EyeTracker = 2,
}
public enum Unit
{
Unknown = 0,
Volt = 1,
Newton = 2,
NewtonMeter = 3,
Meter = 4,
Kilogram = 5,
Second = 6,
Ampere = 7,
Kelvin = 8,
Mole = 9,
Candela = 10,
Radian = 11,
Steradian = 12,
MeterSquared = 13,
MeterCubed = 14,
MeterPerSecond = 15,
MeterPerSecondSquared = 16,
RadianPerSecond = 17,
RadianPerSecondSquared = 18,
Hertz = 19,
Joule = 20,
Watt = 21,
Pascal = 22,
Lumen = 23,
Lux = 24,
Coulomb = 25,
Ohm = 26,
Farad = 27,
Weber = 28,
Tesla = 29,
Henry = 30,
Siemens = 31,
Becquerel = 32,
Gray = 33,
Sievert = 34,
Katal = 35,
}
public enum TimecodeStandard
{
None = 0,
PAL = 1,
NTSC = 2,
NTSCDrop = 3,
Film = 4,
NTSCFilm = 5,
ATSC = 6
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_Connect
{
public Result Result;
//public Output_Connect() { }
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetVersion
{
public uint Major;
public uint Minor;
public uint Point;
public uint Revision;
//public Output_GetVersion() { }
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_IsConnected
{
public bool Connected;
//public Output_IsConnected() { }
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetSubjectName
{
public Result Result;
[MarshalAs(UnmanagedType.LPStr)]
public string SubjectName;
//public Output_GetSubjectName();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetSegmentGlobalRotationQuaternion
{
public Result Result;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
public double[] Rotation;
public bool Occluded;
/*public Output_GetSegmentGlobalRotationQuaternion()
{
Result = Result.Unknown;
//Rotation = new double[] { 0, 0, 0, 1.0f };
Occluded = false;
}*/
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_ConnectToMulticast
{
public Result Result;
//public Output_ConnectToMulticast();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_DisableDeviceData
{
public Result Result;
//public Output_DisableDeviceData();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_DisableMarkerData
{
public Result Result;
//public Output_DisableMarkerData();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_DisableSegmentData
{
public Result Result;
//public Output_DisableSegmentData();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_DisableUnlabeledMarkerData
{
public Result Result;
// public Output_DisableUnlabeledMarkerData();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_DisableMarkerRayData
{
public Result Result;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_DisableCentroidData
{
public Result Result;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_DisableDebugData
{
public Result Result;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_DisableGreyscaleData
{
public Result Result;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_Disconnect
{
public Result Result;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_UpdateFrame
{
public Result Result;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_WaitForFrame
{
public Result Result;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_EnableDeviceData
{
public Result Result;
//public Output_EnableDeviceData();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_EnableMarkerData
{
public Result Result;
//public Output_EnableMarkerData();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_EnableSegmentData
{
public Result Result;
// public Output_EnableSegmentData();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_EnableLightweightSegmentData
{
public Result Result;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_DisableLightweightSegmentData
{
public Result Result;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_EnableUnlabeledMarkerData
{
public Result Result;
// public Output_EnableUnlabeledMarkerData();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_EnableMarkerRayData
{
public Result Result;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_EnableDebugData
{
public Result Result;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_EnableCentroidData
{
public Result Result;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_EnableGreyscaleData
{
public Result Result;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetAxisMapping
{
public Direction XAxis;
public Direction YAxis;
public Direction ZAxis;
//public Output_GetAxisMapping();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetDeviceCount
{
public Result Result;
public uint DeviceCount;
// public Output_GetDeviceCount();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetDeviceName
{
public Result Result;
[MarshalAs(UnmanagedType.LPStr)]
public string DeviceName;
public DeviceType DeviceType;
//public Output_GetDeviceName();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetDeviceOutputCount
{
public Result Result;
public uint DeviceOutputCount;
//public Output_GetDeviceOutputCount();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetDeviceOutputName
{
public Result Result;
[MarshalAs(UnmanagedType.LPStr)]
public string DeviceOutputName;
public Unit DeviceOutputUnit;
// public Output_GetDeviceOutputName();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetDeviceOutputComponentName
{
public Result Result;
[MarshalAs(UnmanagedType.LPStr)]
public string DeviceOutputName;
public string DeviceOutputComponentName;
public Unit DeviceOutputUnit;
// public Output_GetDeviceOutputName();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetDeviceOutputSubsamples
{
public Result Result;
public uint DeviceOutputSubsamples;
public bool Occluded;
//public Output_GetDeviceOutputSubsamples();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetDeviceOutputValue
{
public Result Result;
public double Value;
public bool Occluded;
//public Output_GetDeviceOutputValue();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetEyeTrackerCount
{
public Result Result;
public uint EyeTrackerCount;
//public Output_GetEyeTrackerCount();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetEyeTrackerGlobalGazeVector
{
public Result Result;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)]
public double[] GazeVector;
public bool Occluded;
// public Output_GetEyeTrackerGlobalGazeVector();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetEyeTrackerGlobalPosition
{
public Result Result;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)]
public double[] Position;
public bool Occluded;
//public Output_GetEyeTrackerGlobalPosition();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetForcePlateCount
{
public Result Result;
public uint ForcePlateCount;
//public Output_GetForcePlateCount();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetForcePlateSubsamples
{
public Result Result;
public uint ForcePlateSubsamples;
//public Output_GetForcePlateSubsamples();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetFrame
{
public Result Result;
//public Output_GetFrame();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetFrameNumber
{
public Result Result;
public uint FrameNumber;
//public Output_GetFrameNumber();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetFrameRate
{
public Result Result;
public double FrameRateHz;
//public Output_GetFrameRate();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetGlobalCentreOfPressure
{
public Result Result;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)]
public double[] CentreOfPressure;
//public Output_GetGlobalCentreOfPressure();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetGlobalForceVector
{
public Result Result;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)]
public double[] ForceVector;
//public Output_GetGlobalForceVector();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetGlobalMomentVector
{
public Result Result;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)]
public double[] MomentVector;
//public Output_GetGlobalMomentVector();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetLatencySampleCount
{
public Result Result;
public uint Count;
//public Output_GetLatencySampleCount();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetLatencySampleName
{
public Result Result;
[MarshalAs(UnmanagedType.LPStr)]
public string Name;
//public Output_GetLatencySampleName();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetLatencySampleValue
{
public Result Result;
public double Value;
// public Output_GetLatencySampleValue();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetLatencyTotal
{
public Result Result;
public double Total;
//public Output_GetLatencyTotal();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetMarkerCount
{
public Result Result;
public uint MarkerCount;
//public Output_GetMarkerCount();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetMarkerGlobalTranslation
{
public Result Result;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)]
public double[] Translation;
public bool Occluded;
//public Output_GetMarkerGlobalTranslation();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetMarkerName
{
public Result Result;
[MarshalAs(UnmanagedType.LPStr)]
public string MarkerName;
//public Output_GetMarkerName();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetMarkerParentName
{
public Result Result;
[MarshalAs(UnmanagedType.LPStr)]
public string SegmentName;
//public Output_GetMarkerParentName();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetSegmentChildCount
{
public Result Result;
public uint SegmentCount;
//public Output_GetSegmentChildCount();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetSegmentChildName
{
public Result Result;
[MarshalAs(UnmanagedType.LPStr)]
public string SegmentName;
//public Output_GetSegmentChildName();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetSegmentCount
{
public Result Result;
public uint SegmentCount;
//public Output_GetSegmentCount();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetSegmentGlobalRotationEulerXYZ
{
public Result Result;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)]
public double[] Rotation;
public bool Occluded;
//public Output_GetSegmentGlobalRotationEulerXYZ();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetSegmentGlobalRotationHelical
{
public Result Result;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)]
public double[] Rotation;
public bool Occluded;
//public Output_GetSegmentGlobalRotationHelical();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetSegmentGlobalRotationMatrix
{
public Result Result;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 9)]
public double[] Rotation;
public bool Occluded;
//public Output_GetSegmentGlobalRotationMatrix();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetSegmentGlobalTranslation
{
public Result Result;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)]
public double[] Translation;
public bool Occluded;
//public Output_GetSegmentGlobalTranslation();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetSegmentLocalRotationEulerXYZ
{
public Result Result;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)]
public double[] Rotation;
public bool Occluded;
//public Output_GetSegmentLocalRotationEulerXYZ();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetSegmentLocalRotationHelical
{
public Result Result;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)]
public double[] Rotation;
public bool Occluded;
//public Output_GetSegmentLocalRotationHelical();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetSegmentLocalRotationMatrix
{
public Result Result;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 9)]
public double[] Rotation;
public bool Occluded;
//public Output_GetSegmentLocalRotationMatrix();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetSegmentLocalRotationQuaternion
{
public Result Result;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
public double[] Rotation;
public bool Occluded;
//public Output_GetSegmentLocalRotationQuaternion();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetSegmentLocalTranslation
{
public Result Result;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)]
public double[] Translation;
public bool Occluded;
//public Output_GetSegmentLocalTranslation();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetSegmentName
{
public Result Result;
[MarshalAs(UnmanagedType.LPStr)]
public string SegmentName;
//public Output_GetSegmentName();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetSegmentParentName
{
public Result Result;
[MarshalAs(UnmanagedType.LPStr)]
public string SegmentName;
//public Output_GetSegmentParentName();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetSegmentStaticRotationEulerXYZ
{
public Result Result;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)]
public double[] Rotation;
//public Output_GetSegmentStaticRotationEulerXYZ();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetSegmentStaticRotationHelical
{
public Result Result;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)]
public double[] Rotation;
//public Output_GetSegmentStaticRotationHelical();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetSegmentStaticRotationMatrix
{
public Result Result;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 9)]
public double[] Rotation;
//public Output_GetSegmentStaticRotationMatrix();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetSegmentStaticRotationQuaternion
{
public Result Result;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
public double[] Rotation;
//public Output_GetSegmentStaticRotationQuaternion();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetSegmentStaticTranslation
{
public Result Result;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)]
public double[] Translation;
//public Output_GetSegmentStaticTranslation();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetSegmentStaticScale
{
public Result Result;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)]
public double[] Scale;
//public Output_GetSegmentStaticScale();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetSubjectCount
{
public Result Result;
public uint SubjectCount;
//public Output_GetSubjectCount();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetSubjectRootSegmentName
{
public Result Result;
[MarshalAs(UnmanagedType.LPStr)]
public string SegmentName;
//public Output_GetSubjectRootSegmentName();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetTimecode
{
public Result Result;
public uint Hours;
public uint Minutes;
public uint Seconds;
public uint Frames;
public uint SubFrame;
public bool FieldFlag;
public TimecodeStandard Standard;
public uint SubFramesPerFrame;
public uint UserBits;
//public Output_GetTimecode();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetUnlabeledMarkerCount
{
public Result Result;
public uint MarkerCount;
//public Output_GetUnlabeledMarkerCount();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetUnlabeledMarkerGlobalTranslation
{
public Result Result;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)]
public double[] Translation;
public uint MarkerID;
//public Output_GetUnlabeledMarkerGlobalTranslation();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_IsDeviceDataEnabled
{
public bool Enabled;
//public Output_IsDeviceDataEnabled();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_IsMarkerDataEnabled
{
public bool Enabled;
//public Output_IsMarkerDataEnabled();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_IsSegmentDataEnabled
{
public bool Enabled;
//public Output_IsSegmentDataEnabled();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_IsMarkerRayDataEnabled
{
public bool Enabled;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_IsCentroidDataEnabled
{
public bool Enabled;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_IsDebugDataEnabled
{
public bool Enabled;
//public Output_IsUnlabeledMarkerDataEnabled();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_IsGreyscaleDataEnabled
{
public bool Enabled;
//public Output_IsUnlabeledMarkerDataEnabled();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_IsVideoDataEnabled
{
public bool Enabled;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_IsUnlabeledMarkerDataEnabled
{
public bool Enabled;
//public Output_IsUnlabeledMarkerDataEnabled();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_SetApexDeviceFeedback
{
public Result Result;
//public Output_SetApexDeviceFeedback();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_SetAxisMapping
{
public Result Result;
//public Output_SetAxisMapping();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_SetStreamMode
{
public Result Result;
//public Output_SetStreamMode();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_StartTransmittingMulticast
{
public Result Result;
// public Output_StartTransmittingMulticast();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_StopTransmittingMulticast
{
public Result Result;
//public Output_StopTransmittingMulticast();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetCentroidCount
{
public Result Result;
public uint CentroidCount;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetMarkerRayContributionCount
{
public Result Result;
public uint RayContributionsCount;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetObjectQuality
{
public Result Result;
public double Quality;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetCameraUserId
{
public Result Result;
public uint CameraUserId;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetCentroidPosition
{
public Result Result;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)]
public double[] CentroidPosition;
public double Radius;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetCameraCount
{
public Result Result;
public uint CameraCount;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetCameraName
{
public Result Result;
[MarshalAs(UnmanagedType.LPStr)]
public string CameraName;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetServerOrientation
{
public Result Result;
public Result Orientation;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetMarkerRayContribution
{
public Result Result;
public uint CameraID;
public uint CentroidIndex;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetFrameRateCount
{
public Result Result;
public uint Count;
}
//[StructLayout(LayoutKind.Sequential, Pack = 1)]
//public class Output_GetGreyscaleBlob
//{
// public Result Result;
// public uint * BlobLinePositionsX;
// public uint BlobLinePositionsXSize;
// public uint * BlobLinePositionsY;
// public uint BlobLinePositionsYSize;
// unsigned char * BlobLinePixelValues;
//}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetCameraType
{
public Result Result;
[MarshalAs(UnmanagedType.LPStr)]
public string CameraType;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetCameraDisplayName
{
public Result Result;
[MarshalAs(UnmanagedType.LPStr)]
public string CameraDisplayName;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetCameraResolution
{
public Result Result;
public uint ResolutionX;
public uint ResolutionY;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetFrameRateName
{
public Result Result;
[MarshalAs(UnmanagedType.LPStr)]
public string Name;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetFrameRateValue
{
public Result Result;
public double Value;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetLabeledMarkerCount
{
public Result Result;
public uint MarkerCount;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetIsVideoCamera
{
public Result Result;
public bool IsVideoCamera;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetCameraId
{
public Result Result;
public uint CameraId;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetHardwareFrameNumber
{
public Result Result;
public uint HardwareFrameNumber;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetLabeledMarkerGlobalTranslation
{
public Result Result;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)]
public double[] Translation;
public uint MarkerID;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetCentroidWeight
{
public Result Result;
public double Weight;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetGreyscaleBlobCount
{
public Result Result;
public uint BlobCount;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_ClearSubjectFilter
{
public Result Result;
//public Output_ClearSubjectFilter();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_AddToSubjectFilter
{
public Result Result;
//public Output_AddToSubjectFilter();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_SetTimingLogFile
{
public Result Result;
//public Output_SetTimingLogFile();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_ConfigureWireless
{
public Result Result;
[MarshalAs(UnmanagedType.LPStr)]
public string Error;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetRetimedSubjectCount
{
public Result Result;
public uint SubjectCount;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_GetRetimedSubjectName
{
public Result Result;
[MarshalAs(UnmanagedType.LPStr)]
public string Name;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_RetimedSegment
{
public bool Occluded;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)]
public double[] Global_Position;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 9)]
public double[] Global_Rotation;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)]
public double[] Local_Position;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 9)]
public double[] Local_Rotation;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_RetimedSubject
{
public Result Result;
[MarshalAs(UnmanagedType.LPStr)]
public string Name;
[MarshalAs(UnmanagedType.LPStr)]
public string RootSegmentName;
public uint Parent1_FrameNumber;
public uint Parent2_FrameNumber;
public void AddSegment(Output_RetimedSegment Segment)
{
m_Segments.Add(Segment);
}
public int GetSegmentCount()
{
return m_Segments.Count;
}
public bool GetSegment(int Index, out Output_RetimedSegment Segment)
{
if (Index < m_Segments.Count)
{
Segment = m_Segments[Index];
return true;
}
Segment = new Output_RetimedSegment();
return false;
}
private List<Output_RetimedSegment> m_Segments = new List<Output_RetimedSegment>();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class Output_RetimedSubjects
{
public Result Result;
public Output_RetimedSubjects()
{
}
public void AddSubject(Output_RetimedSubject Subject)
{
m_Subjects.Add(Subject);
}
public int GetSubjectCount()
{
return m_Subjects.Count;
}
public bool GetSubject(int Index, out Output_RetimedSubject Subject)
{
if (Index < m_Subjects.Count)
{
Subject = m_Subjects[Index];
return true;
}
Subject = new Output_RetimedSubject();
return false;
}
private List<Output_RetimedSubject> m_Subjects = new List<Output_RetimedSubject>();
};
} |
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;
public class CreateJsonClass : MonoBehaviour
{
public Foo MyFoo;
static string path = "Assets/Resources/test.txt";
[ContextMenu("Load")]
void LoadJSON() {
//TextAsset asset = Resources.Load<TextAsset>(path);
MyFoo = JsonUtility.FromJson<Foo>(File.ReadAllText(path));
}
[ContextMenu("Save")]
void SaveJSON() {
/*var f = new Foo();
f.floatList = new List<float>();
f.myInt = -99;*/
string json = JsonUtility.ToJson(MyFoo, true);
File.WriteAllText(path, json);
}
}
[System.Serializable]
public class Foo
{
public int myInt;
public List<float> floatList;
} |
#if MULTIPLAYER_TOOLS
using UnityEngine;
namespace Unity.Netcode.RuntimeTests.Metrics.Utility
{
public class NetworkVariableComponent : NetworkBehaviour
{
public NetworkVariable<int> MyNetworkVariable { get; } = new NetworkVariable<int>();
private void Update()
{
if (IsServer)
{
MyNetworkVariable.Value = Random.Range(100, 999);
}
}
}
}
#endif
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Input.Events;
using osuTK;
using osuTK.Graphics;
namespace osu.Game.Graphics.Containers
{
public abstract class OsuRearrangeableListItem<TModel> : RearrangeableListItem<TModel>
{
public const float FADE_DURATION = 100;
/// <summary>
/// Whether any item is currently being dragged. Used to hide other items' drag handles.
/// </summary>
public readonly BindableBool DragActive = new BindableBool();
private Color4 handleColour = Color4.White;
/// <summary>
/// The colour of the drag handle.
/// </summary>
protected Color4 HandleColour
{
get => handleColour;
set
{
if (handleColour == value)
return;
handleColour = value;
if (handle != null)
handle.Colour = value;
}
}
/// <summary>
/// Whether the drag handle should be shown.
/// </summary>
protected readonly Bindable<bool> ShowDragHandle = new Bindable<bool>(true);
private Container handleContainer;
private PlaylistItemHandle handle;
protected OsuRearrangeableListItem(TModel item)
: base(item)
{
RelativeSizeAxes = Axes.X;
AutoSizeAxes = Axes.Y;
}
[BackgroundDependencyLoader]
private void load()
{
InternalChild = new GridContainer
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Content = new[]
{
new[]
{
handleContainer = new Container
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
AutoSizeAxes = Axes.Both,
Padding = new MarginPadding { Horizontal = 5 },
Child = handle = new PlaylistItemHandle
{
Size = new Vector2(12),
Colour = HandleColour,
AlwaysPresent = true,
Alpha = 0
}
},
CreateContent()
}
},
ColumnDimensions = new[] { new Dimension(GridSizeMode.AutoSize) },
RowDimensions = new[] { new Dimension(GridSizeMode.AutoSize) }
};
}
protected override void LoadComplete()
{
base.LoadComplete();
ShowDragHandle.BindValueChanged(show => handleContainer.Alpha = show.NewValue ? 1 : 0, true);
}
protected override bool OnDragStart(DragStartEvent e)
{
if (!base.OnDragStart(e))
return false;
DragActive.Value = true;
return true;
}
protected override void OnDragEnd(DragEndEvent e)
{
DragActive.Value = false;
base.OnDragEnd(e);
}
protected override bool IsDraggableAt(Vector2 screenSpacePos) => handle.HandlingDrag;
protected override bool OnHover(HoverEvent e)
{
handle.UpdateHoverState(IsDragged || !DragActive.Value);
return base.OnHover(e);
}
protected override void OnHoverLost(HoverLostEvent e) => handle.UpdateHoverState(false);
protected abstract Drawable CreateContent();
public class PlaylistItemHandle : SpriteIcon
{
public bool HandlingDrag { get; private set; }
private bool isHovering;
public PlaylistItemHandle()
{
Icon = FontAwesome.Solid.Bars;
}
protected override bool OnMouseDown(MouseDownEvent e)
{
base.OnMouseDown(e);
HandlingDrag = true;
UpdateHoverState(isHovering);
return false;
}
protected override void OnMouseUp(MouseUpEvent e)
{
base.OnMouseUp(e);
HandlingDrag = false;
UpdateHoverState(isHovering);
}
public void UpdateHoverState(bool hovering)
{
isHovering = hovering;
if (isHovering || HandlingDrag)
this.FadeIn(FADE_DURATION);
else
this.FadeOut(FADE_DURATION);
}
}
}
}
|
using ComputerStore.Data.Models;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace ComputerStore.Services
{
public interface IService<TEntity>
where TEntity : class
{
Task<TEntity> Create(TEntity entity);
Task Delete(TEntity entity);
Task Update(TEntity entity);
IEnumerable<TEntity> All();
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace Bugfree.Spo.Cqrs.Console
{
class Program
{
static IEnumerable<ICommand> GetCommands()
{
var iCommand = typeof(ICommand);
return System.Reflection.Assembly.GetExecutingAssembly().GetTypes().ToList()
.Where(t => iCommand.IsAssignableFrom(t) && t != iCommand)
.Select(t => Activator.CreateInstance(t) as ICommand);
}
static void DisplayHelp()
{
System.Console.WriteLine("Console [Command] [Arg1] [Arg2] [ArgN]\n\n");
GetCommands().ToList().ForEach(command =>
System.Console.WriteLine(command.Usage + "\n" + command.Description + "\n\n"));
}
static int Main(string[] args)
{
if (args.Length == 0)
{
DisplayHelp();
return (int)ExitCode.Failure;
}
var commandName = args[0];
var command = GetCommands().SingleOrDefault(t => t.GetType().Name == commandName);
if (command == null)
{
throw new ArgumentException(string.Format("Command '{0}' not found", commandName));
}
var executeArguments = new List<string>(args);
executeArguments.RemoveAt(0);
var exitCode = command.Execute(executeArguments.ToArray());
return (int)exitCode;
}
}
}
|
using System;
using System.Diagnostics;
namespace OneSmallStep.Utility.Time
{
[DebuggerDisplay("{TickOffset}")]
public struct TimeOffset : IEquatable<TimeOffset>, IComparable<TimeOffset>
{
public static readonly TimeOffset OneTick = new TimeOffset(1);
public TimeOffset(long offset)
{
TickOffset = offset;
}
public long TickOffset { get; }
public override bool Equals(object that)
{
return !ReferenceEquals(that, null) && (that is TimeOffset thatTimeOffset) && Equals(thatTimeOffset);
}
public bool Equals(TimeOffset that)
{
return TickOffset == that.TickOffset;
}
public static bool operator ==(TimeOffset left, TimeOffset right)
{
return left.Equals(right);
}
public static bool operator !=(TimeOffset left, TimeOffset right)
{
return !left.Equals(right);
}
public override int GetHashCode()
{
return TickOffset.GetHashCode();
}
public int CompareTo(TimeOffset that)
{
return TickOffset.CompareTo(that.TickOffset);
}
public static TimeOffset operator -(TimeOffset left, TimeOffset right)
{
return new TimeOffset(left.TickOffset - right.TickOffset);
}
public static TimeOffset operator +(TimeOffset left, TimeOffset right)
{
return new TimeOffset(left.TickOffset + right.TickOffset);
}
}
} |
using System;
using StoryTeller.Grammars;
namespace StoryTeller.RDBMS
{
public class NoRowsGrammar : FactGrammar
{
public static Func<ISpecContext, bool> Test(string dbObject)
{
return c =>
{
var runner = c.State.Retrieve<CommandRunner>();
var rowCount = runner.RowCount(dbObject);
StoryTellerAssert.Fail(rowCount > 0, $"Found {rowCount} rows, but expected 0");
return rowCount == 0;
};
}
public NoRowsGrammar(string title, string dbObject) : base(title, Test(dbObject))
{
}
}
}
|
using System;
namespace Intersect.Client.Framework.Graphics
{
public struct Resolution
{
public static readonly Resolution Empty = default;
private static readonly char[] Separators = { 'x', ',', ' ', '/', '-', '_', '.', '~' };
public readonly ushort X;
public readonly ushort Y;
public Resolution(long x = 800, long y = 600)
{
X = (ushort)(x & 0xFFFF);
Y = (ushort)(y & 0xFFFF);
}
public Resolution(ulong x = 800, ulong y = 600)
{
X = (ushort)(x & 0xFFFF);
Y = (ushort)(y & 0xFFFF);
}
public Resolution(Resolution resolution, long overrideX = 0, long overrideY = 0)
: this(
overrideX > 0 ? overrideX : resolution.X, overrideY > 0 ? overrideY : resolution.Y
)
{ }
public Resolution(Resolution resolution, Resolution? overrideResolution = null)
{
var x = overrideResolution?.X ?? resolution.X;
X = x > 0 ? x : resolution.X;
var y = overrideResolution?.Y ?? resolution.Y;
Y = y > 0 ? y : resolution.Y;
}
public override bool Equals(object obj) => obj is Resolution resolution && Equals(resolution);
public bool Equals(Resolution other) => X == other.X && Y == other.Y;
public override int GetHashCode() => (X << 16) & Y;
public override string ToString() => $"{X},{Y}";
public static Resolution Parse(string resolution)
{
var split = resolution?.Split(Separators);
string xString = split?[0], yString = split?[1];
if (string.IsNullOrWhiteSpace(xString))
{
throw new ArgumentNullException(nameof(xString));
}
if (string.IsNullOrWhiteSpace(yString))
{
throw new ArgumentNullException(nameof(xString));
}
var x = ushort.Parse(xString);
var y = ushort.Parse(yString);
return new Resolution(x, y);
}
public static bool TryParse(string resolutionString, out Resolution resolution)
{
try
{
resolution = Parse(resolutionString);
return true;
}
catch
{
// Ignore
resolution = default;
return false;
}
}
public static bool operator ==(Resolution left, Resolution right) =>
left.X == right.X && left.Y == right.Y;
public static bool operator !=(Resolution left, Resolution right) =>
left.X != right.X && left.Y != right.Y;
}
}
|
using Azure.Sdk.Tools.GitHubIssues.Services.Configuration;
using Azure.Security.KeyVault.Secrets;
using GitHubIssues.Helpers;
using Microsoft.Extensions.Logging;
using Microsoft.Identity.Client;
using Octokit;
using Polly;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace Azure.Sdk.Tools.GitHubIssues.Reports
{
public abstract class BaseReport
{
protected IConfigurationService ConfigurationService { get; private set; }
protected ILogger<BaseReport> Logger { get; private set; }
public BaseReport(IConfigurationService configurationService, ILogger<BaseReport> logger)
{
ConfigurationService = configurationService;
Logger = logger;
}
protected async Task ExecuteWithRetryAsync(int retryCount, Func<Task> action)
{
await Policy
.Handle<AbuseException>()
.Or<RateLimitExceededException>()
.RetryAsync(10, async (ex, retryCount) =>
{
TimeSpan retryDelay = TimeSpan.FromSeconds(10); // Default.
switch (ex)
{
case AbuseException abuseException:
retryDelay = TimeSpan.FromSeconds((double)abuseException.RetryAfterSeconds);
Logger.LogWarning("Abuse exception detected. Retry after seconds is: {retrySeconds}",
abuseException.RetryAfterSeconds
);
break;
case RateLimitExceededException rateLimitExceededException:
retryDelay = rateLimitExceededException.GetRetryAfterTimeSpan();
Logger.LogWarning(
"Rate limit exception detected. Limit is: {limit}, reset is: {reset}, retry seconds is: {retrySeconds}",
rateLimitExceededException.Limit,
rateLimitExceededException.Reset,
retryDelay.TotalSeconds
);
break;
default:
Logger.LogError(
"Fall through case invoked, this should never happen!"
);
break;
}
await Task.Delay(retryDelay);
})
.ExecuteAsync(async () =>
{
try
{
await action();
}
catch (AggregateException ex) when (ex.InnerException! is AbuseException || ex.InnerException! is RateLimitExceededException)
{
throw ex.InnerException;
}
});
}
public async Task ExecuteAsync()
{
Task<string> pendingGitHubPersonalAccessToken = ConfigurationService.GetGitHubPersonalAccessTokenAsync();
var gitHubClient = new GitHubClient(new ProductHeaderValue("github-issues"))
{
Credentials = new Credentials(await pendingGitHubPersonalAccessToken)
};
Logger.LogInformation("Preparing report execution context for: {reportType}", this.GetType());
var context = new ReportExecutionContext(
await ConfigurationService.GetFromAddressAsync(),
await ConfigurationService.GetSendGridTokenAsync(),
await pendingGitHubPersonalAccessToken,
await ConfigurationService.GetRepositoryConfigurationsAsync(),
gitHubClient
);
Logger.LogInformation("Executing report: {reportType}", this.GetType());
await ExecuteCoreAsync(context);
Logger.LogInformation("Executed report: {reportType}", this.GetType());
}
protected abstract Task ExecuteCoreAsync(ReportExecutionContext context);
}
}
|
using System;
using System.Threading.Tasks;
using Elasticsearch.Net;
using Microsoft.Extensions.DependencyInjection;
using Nest;
using ShowScraper.TvMazeClient;
using ShowScraper.TvMazeClient.Models;
using Xunit;
using Xunit.Abstractions;
namespace ShowScraper.Tests
{
public class ElasticClientIntegrationTests
{
readonly ITestOutputHelper _logger;
readonly IServiceProvider _provider;
public ElasticClientIntegrationTests(ITestOutputHelper logger)
{
_logger = logger;
var services = new ServiceCollection();
services.AddScoped<IElasticClient>(_ =>
{
var node = new Uri("http://localhost:9200");
var connectionPool = new SniffingConnectionPool(new[] {node}) {SniffedOnStartup = true };
var connectionSettingsValues = new ConnectionSettings(connectionPool)
.DefaultMappingFor<ShowWithCast>(s => s.IndexName(nameof(ShowWithCast).ToLowerInvariant()));
return new ElasticClient(connectionSettingsValues);
});
services.AddTransient<ElasticShowsProvider>();
_provider = services.BuildServiceProvider();
}
[Fact]
public async Task Can_get_shows_with_cast()
{
var service = _provider.GetService<ElasticShowsProvider>();
var shows = await service.GetShows(10,3);
foreach (var show in shows)
{
_logger.WriteLine(show.name);
foreach (var cast in show._embedded.cast)
{
_logger.WriteLine("Person: {0}, Birthday: {1}", cast.person.name, cast.person.birthday);
}
}
}
}
} |
// *
// * Copyright (C) 2005 Roger Alsing : http://www.puzzleframework.com
// *
// * This library is free software; you can redistribute it and/or modify it
// * under the terms of the GNU Lesser General Public License 2.1 or later, as
// * published by the Free Software Foundation. See the included license.txt
// * or http://www.gnu.org/copyleft/lesser.html for details.
// *
// *
using System;
using System.Collections;
using Puzzle.NCore.Framework.Collections;
using Puzzle.NPath.Framework.CodeDom;
namespace Puzzle.NPath.Framework
{
public class SortOrderComparer : IComparer
{
private IObjectQueryEngine engine = null;
private NPathOrderByClause orderBy = null;
public SortOrderComparer(NPathOrderByClause orderBy, IObjectQueryEngine engine)
{
this.orderBy = orderBy;
this.engine = engine;
}
#region IComparer Members
private MultiHashtable lookup = new MultiHashtable();
private object GetObjectValue(object item, IValue expression)
{
object value = lookup[item, expression];
if (value == null)
{
value = engine.EvalValue(item, expression);
lookup[item, expression] = value;
}
return value;
}
public int Compare(object x, object y)
{
if (x == y)
return 0;
if (x == null || y == null)
throw new Exception("Values may not be null"); // do not localize
foreach (SortProperty property in orderBy.SortProperties)
{
object xv = GetObjectValue(x, property.Expression);
if (xv == null)
return -1;
object yv = GetObjectValue(y, property.Expression);
if (yv == null)
return 1;
int res = Comparer.Default.Compare(xv, yv);
//values are equal , compare the next property in the order by clause
if (res == 0)
continue;
if (property.Direction == SortDirection.Desc)
res = -res;
return res;
}
return 0;
}
#endregion
}
} |
using Ditto.CommandLine;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
namespace Amdl.Maml.Converter.Console
{
[DefaultProperty("Help")]
internal sealed class Parameters
{
[Required]
[Option]
[Option("s")]
[DisplayName("sourcePath")]
[Description("Source folder path")]
public string SourcePath
{
get;
set;
}
[Required]
[Option]
[Option("d")]
[DisplayName("destinationPath")]
[Description("Destination folder path")]
public string DestinationPath
{
get;
set;
}
[Option]
[Option("l")]
[DisplayName("contentLayoutPath")]
[Description("Content layout file path")]
public string ContentLayoutPath
{
get;
set;
}
[Option]
[Option("v")]
[DefaultValue(Verbosity.Normal)]
[Description("Verbosity")]
[Category("Output")]
public Verbosity Verbosity
{
get;
set;
}
[Option]
[Option("tf")]
[DefaultValue("yyyy-MM-dd HH:mm:ss.fff")]
[Description("Time format")]
[Category("Output")]
public string TimeFormat
{
get;
set;
}
[Option]
[Option("df")]
[DefaultValue("hh:mm:ss.fff")]
[Description("Duration format")]
[Category("Output")]
public string DurationFormat
{
get;
set;
}
[Option]
[Option("?")]
[Description("Display this help")]
[Category("Miscellaneous")]
public bool Help
{
get;
set;
}
}
}
|
using FluentAssertions;
using NUnit.Framework;
using Pegatron.Core;
using Pegatron.UnitTests.Mocks;
using System;
using System.Linq;
namespace Pegatron.UnitTests
{
/// <summary>
/// These tests are almost the same as in <see cref="TokenStreamTest"/>, they just use the index API instead
/// of directly accessing the token stream.
/// </summary>
[TestFixture]
public class TokenStreamIndexTest
{
[Test]
[TestCase(-1)]
[TestCase(-12)]
[TestCase(-42)]
public void Index_WithNegativeNumber_Throws(int number)
{
var stream = new TokenStream(StaticLexer.FromWords());
Action action = () => new TokenStreamIndex(stream, number);
action.Should().Throw<ArgumentOutOfRangeException>();
}
[Test]
public void Index_FromEmptyLexer_ContainsEosToken()
{
var index = new TokenStream(StaticLexer.FromWords()).Start();
var eos = index.Get();
eos.Should().NotBeNull();
eos.IsEndOfStream.Should().BeTrue();
index.Invoking(i => i.Next()).Should().Throw<IndexOutOfRangeException>();
}
[Test]
[TestCase(0)]
[TestCase(1)]
[TestCase(10)]
public void Stream_WithInvalidLexer_ThrowsMissingEosTokenException(int tokenCount)
{
var tokens = Enumerable.Repeat(_dummy, tokenCount);
var index = new TokenStream(new StaticLexer(tokens)).Start();
for (var i = 0; i < tokenCount; i++)
{
index.Index.Should().Be(i);
index.Get().Value.Should().Be(_dummy.Value);
index = index.Next();
}
index.Invoking(i => i.Get()).Should().Throw<LexerException>().Where(e => e.Id == LexerExceptionId.MissingEosToken);
}
[Test]
public void Stream_FromSingleToken_ContainsTokenAndEos()
{
var token = "test";
var index = new TokenStream(StaticLexer.FromWords(token)).Start();
index.Get().Value.Should().Be(token);
index.Get().IsEndOfStream.Should().BeFalse();
index = index.Next();
index.Get().IsEndOfStream.Should().BeTrue();
}
private readonly Token _dummy = new Token("dummy")
{
Value = "dummy",
Line = 0,
Start = 0,
};
}
}
|
//bibaoke.com
using Less.Text;
namespace Less.Html
{
/// <summary>
/// 注释
/// </summary>
public class Comment : Node
{
/// <summary>
/// 节点名称
/// </summary>
internal static string NodeName
{
get { return "#comment"; }
}
/// <summary>
/// 节点名称
/// </summary>
public override string nodeName
{
get
{
return Comment.NodeName.ToUpper();
}
}
/// <summary>
/// 节点值
/// </summary>
public override string nodeValue
{
get
{
int length = this.End - this.Begin + 1;
return this.ownerDocument.Content.SubstringUnsafe(this.Begin, length);
}
}
internal Comment(int begin, int end) : base(begin, end)
{
//
}
/// <summary>
/// 克隆节点
/// </summary>
/// <param name="deep"></param>
/// <returns></returns>
public override Node cloneNode(bool deep)
{
return this.ownerDocument.Parse(this.Content).firstChild;
}
internal override Node Clone(Node parent)
{
Comment clone = new Comment(this.Begin, this.End);
clone.parentNode = parent;
clone.ChildIndex = this.ChildIndex;
parent.ChildNodeList.Add(clone);
clone.Index = this.Index;
parent.ownerDocument.AllNodes.Add(clone);
clone.ownerDocument = parent.ownerDocument;
return clone;
}
}
}
|
using NUnit.Framework;
using NServiceKit.Common;
using NServiceKit.Plugins.ProtoBuf;
using NServiceKit.ServiceClient.Web;
using NServiceKit.Text;
using NServiceKit.WebHost.IntegrationTests.Services;
namespace NServiceKit.WebHost.IntegrationTests.Tests
{
/// <summary>A cached service tests.</summary>
[TestFixture]
public class CachedServiceTests
{
/// <summary>Executes the before each test action.</summary>
[TestFixtureSetUp]
public void OnBeforeEachTest()
{
var jsonClient = new JsonServiceClient(Config.NServiceKitBaseUri);
jsonClient.Post<ResetMoviesResponse>("reset-movies", new ResetMovies());
}
/// <summary>Can call cached web service with JSON.</summary>
[Test]
public void Can_call_Cached_WebService_with_JSON()
{
var client = new JsonServiceClient(Config.NServiceKitBaseUri);
var response = client.Get<MoviesResponse>("/cached/movies");
Assert.That(response.Movies.Count, Is.EqualTo(ResetMoviesService.Top5Movies.Count));
}
/// <summary>Can call cached web service with prototype buffer.</summary>
[Test]
public void Can_call_Cached_WebService_with_ProtoBuf()
{
var client = new ProtoBufServiceClient(Config.NServiceKitBaseUri);
var response = client.Get<MoviesResponse>("/cached/movies");
Assert.That(response.Movies.Count, Is.EqualTo(ResetMoviesService.Top5Movies.Count));
}
/// <summary>Can call cached web service with prototype buffer without compression.</summary>
[Test]
public void Can_call_Cached_WebService_with_ProtoBuf_without_compression()
{
var client = new ProtoBufServiceClient(Config.NServiceKitBaseUri);
client.DisableAutoCompression = true;
client.Get<MoviesResponse>("/cached/movies");
var response2 = client.Get<MoviesResponse>("/cached/movies");
Assert.That(response2.Movies.Count, Is.EqualTo(ResetMoviesService.Top5Movies.Count));
}
/// <summary>Can call cached web service with jsonp.</summary>
[Test]
public void Can_call_Cached_WebService_with_JSONP()
{
var url = Config.NServiceKitBaseUri.CombineWith("/cached/movies?callback=cb");
var jsonp = url.GetJsonFromUrl();
Assert.That(jsonp.StartsWith("cb("));
}
}
} |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Tscrump_App
{
public static class Extentions
{
/// <summary>
/// Transforms a DateTime into a string, readable by MySQL
/// </summary>
/// <param name="Value">The datetime value to convert</param>
/// <returns>A MySQL suitable formatted string.</returns>
public static string ToSQLString(this DateTime Value)
{
return $"\"{Value.ToString("yyyy-MM-dd HH:mm:ss")}\"";
}
/// <summary>
/// Removes any character that is not a number
/// </summary>
public static string ToNumberString(this string value)
{
string RealNewText = "";
for (int i = 0; i < value.Length; i++)
{
if (char.IsDigit(value, i) || value[i] == App.DeviceCulture.NumberFormat.NumberDecimalSeparator[0])
{
RealNewText += value[i];
}
}
return RealNewText;
}
/// <summary>
/// Gives a 'NumberString' proper punctuation.
/// </summary>
public static string ToFormattedNumberString(this string value)
{
return double.Parse(value).ToString(App.DeviceCulture);
}
}
}
|
namespace System.Command.Commands
{
/// <inheritdoc />
public abstract class MigrationCommand : Command, IMigrationCommand
{
protected MigrationCommand(string commandName) : base(commandName)
{
}
/// <inheritdoc />
public abstract void Down();
/// <inheritdoc />
public abstract void Up();
}
} |
using System.Collections.Generic;
using Avalonia.Media;
namespace WDE.Common.Avalonia.Controls
{
public class FormattedTextCache
{
private Dictionary<(string, int), FormattedText> cache = new();
private Dictionary<int, (Typeface family, double size)> styles = new();
public void AddStyle(int index, Typeface fontFamily, int fontSize)
{
styles[index] = (fontFamily, fontSize);
}
public FormattedText GetFormattedText(string text, int styleId)
{
if (cache.TryGetValue((text, styleId), out var formattedText))
return formattedText;
formattedText = new FormattedText();
formattedText.Text = text;
if (!styles.TryGetValue(styleId, out var style))
return formattedText;
formattedText.FontSize = style.size;
formattedText.Typeface = style.family;
cache[(text, styleId)] = formattedText;
return formattedText;
}
public void InvalidateCache()
{
cache.Clear();
}
}
} |
// <copyright file="ConsoleTraceListener.cs" company="Soup">
// Copyright (c) Soup. All rights reserved.
// </copyright>
namespace Opal
{
using global::System;
/// <summary>
/// Console logger that wraps the base <see cref="TraceListener"/>.
/// </summary>
public class ConsoleTraceListener : TraceListener
{
/// <summary>
/// Initializes a new instance of the <see cref='ConsoleTraceListener'/> class.
/// </summary>
public ConsoleTraceListener()
: base()
{
}
/// <summary>
/// Initializes a new instance of the <see cref='ConsoleTraceListener'/> class.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="filter">The filter.</param>
/// <param name="showEventType">A value indicating whether to show the event type.</param>
/// <param name="showEventId">A value indicating whether to show the event id.</param>
public ConsoleTraceListener(
string name,
IEventFilter filter,
bool showEventType,
bool showEventId)
: base(name, filter, showEventType, showEventId)
{
}
public void SetConsoleColor()
{
//// TODO
//// switch (_currentEvent)
//// {
//// case TraceEventType.Error:
//// Console.ForegroundColor = ConsoleColor.Red;
//// break;
//// case TraceEventType.Warning:
//// Console.ForegroundColor = ConsoleColor.Yellow;
//// break;
//// }
}
/// <summary>
/// Writes a message and newline terminator.
/// </summary>
/// <param name="message">The message.</param>
protected override void WriteLine(string message)
{
//// if (NeedIndent)
//// {
//// WriteIndent();
//// }
this.SetConsoleColor();
Console.WriteLine(message);
// TODO: restore color
// NeedIndent = true;
}
}
}
|
using Newtonsoft.Json;
namespace Citizerve.SyncWorker.Models
{
public class Citizen
{
[JsonProperty(PropertyName = "citizenId")]
public string CitizenId { get; set; }
[JsonProperty(PropertyName = "tenantId")]
public string TenantId { get; set; }
[JsonProperty(PropertyName = "givenName")]
public string GivenName { get; set; }
[JsonProperty(PropertyName = "surname")]
public string Surname { get; set; }
[JsonProperty(PropertyName = "phoneNumber")]
public string PhoneNumber { get; set; }
[JsonProperty(PropertyName = "address")]
public CitizenAddress Address { get; set; }
public override string ToString()
{
return string.Format(
"Citizen: CitizenId: {1}, TenantId: {2}, GivenName: {3}, Surname: {4}, PhoneNumber: {5}, Address: {6}",
CitizenId, TenantId, GivenName, Surname, PhoneNumber, Address.ToString()
);
}
}
} |
namespace Plivo.Exception
{
public class PlivoNotFoundException : PlivoRestException
{
public PlivoNotFoundException(string message, uint statusCode = 404) : base(message, statusCode)
{
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using static PEReader.Native.NativeConstants;
namespace PEReader.Native
{
[StructLayout(LayoutKind.Sequential, Pack = 4)]
internal struct IMAGE_OPTIONAL_HEADER32
{
//
// Standard fields.
// Fields that are defined for all implementations of COFF, including UNIX.
//
/// <summary>
/// The unsigned integer that identifies the state of the image file.
/// </summary>
public ushort Magic;
/// <summary>
/// The linker major version number.
/// </summary>
public byte MajorLinkerVersion;
/// <summary>
/// The linker minor version number.
/// </summary>
public byte MinorLinkerVersion;
/// <summary>
/// The size of the code (".text") section, or the sum of all code
/// sections if there are multiple sections.
/// </summary>
public uint SizeOfCode;
/// <summary>
/// The size of the initialized data section, or the sum of all
/// such sections if there are multiple data sections.
/// </summary>
public uint SizeOfInitializedData;
/// <summary>
/// The size of the uninitialized data section (".bss"), or the sum
/// of all such sections if there are multiple BSS sections.
/// </summary>
public uint SizeOfUninitializedData;
/// <summary>
/// The address of the entry point relative to the image base when the
/// executable file is loaded into memory. For program images, this is
/// the starting address. For device drivers, this is the address of the
/// initialization function. An entry point is optional for DLLs. When
/// no entry point is present, this field must be zero.
/// </summary>
public uint AddressOfEntryPoint;
/// <summary>
/// The address that is relative to the image base of the
/// beginning-of-code section when it is loaded into memory.
/// </summary>
public uint BaseOfCode;
/// <summary>
/// The address that is relative to the image base of the
/// beginning-of-data section when it is loaded into memory.
/// </summary>
public uint BaseOfData;
//
// NT additional fields.
// Windows-specific fields
//
/// <summary>
/// The preferred address of the first byte of image when loaded into
/// memory; must be a multiple of 64 K. The default for DLLs is
/// 0x10000000. The default for Windows CE EXEs is 0x00010000. The
/// default for Windows NT, Windows 2000, Windows XP, Windows 95,
/// Windows 98, and Windows Me is 0x00400000.
/// </summary>
public uint ImageBase;
/// <summary>
/// The alignment (in bytes) of sections when they are loaded into
/// memory. It must be greater than or equal to FileAlignment. The
/// default is the page size for the architecture.
/// </summary>
public uint SectionAlignment;
/// <summary>
/// The alignment factor (in bytes) that is used to align the raw data
/// of sections in the image file. The value should be a power of 2
/// between 512 and 64 K, inclusive. The default is 512. If the
/// SectionAlignment is less than the architecture’s page size, then
/// FileAlignment must match SectionAlignment.
/// </summary>
public uint FileAlignment;
/// <summary>
/// The major version number of the required operating system.
/// </summary>
public ushort MajorOperatingSystemVersion;
/// <summary>
/// The minor version number of the required operating system.
/// </summary>
public ushort MinorOperatingSystemVersion;
/// <summary>
/// The major version number of the image.
/// </summary>
public ushort MajorImageVersion;
/// <summary>
/// The minor version number of the image.
/// </summary>
public ushort MinorImageVersion;
/// <summary>
/// The major version number of the subsystem.
/// </summary>
public ushort MajorSubsystemVersion;
/// <summary>
/// The minor version number of the subsystem.
/// </summary>
public ushort MinorSubsystemVersion;
/// <summary>
/// Reserved, must be zero.
/// </summary>
public uint Win32VersionValue;
/// <summary>
/// The size (in bytes) of the image, including all headers, as the
/// image is loaded in memory. It must be a multiple of SectionAlignment.
/// </summary>
public uint SizeOfImage;
/// <summary>
/// The combined size of an MS‑DOS stub, PE header, and section headers
/// rounded up to a multiple of FileAlignment.
/// </summary>
public uint SizeOfHeaders;
/// <summary>
/// The image file checksum. The algorithm for computing the checksum
/// is incorporated into IMAGHELP.DLL. The following are checked for
/// validation at load time: all drivers, any DLL loaded at boot time,
/// and any DLL that is loaded into a critical Windows process.
/// </summary>
public uint CheckSum;
/// <summary>
/// The subsystem that is required to run this image.
/// </summary>
public ImageSubsystem Subsystem;
/// <see cref="PEReader.DllCharacteristics"/>
public DllCharacteristics DllCharacteristics;
/// <summary>
/// The size of the stack to reserve. Only SizeOfStackCommit is
/// committed; the rest is made available one page at a time until
/// the reserve size is reached.
/// </summary>
public uint SizeOfStackReserve;
/// <summary>
/// The size of the stack to commit.
/// </summary>
public uint SizeOfStackCommit;
/// <summary>
/// The size of the local heap space to reserve. Only SizeOfHeapCommit
/// is committed; the rest is made available one page at a time until
/// the reserve size is reached.
/// </summary>
public uint SizeOfHeapReserve;
/// <summary>
/// The size of the local heap space to commit.
/// </summary>
public uint SizeOfHeapCommit;
/// <summary>
/// Reserved, must be zero.
/// </summary>
public uint LoaderFlags;
/// <summary>
/// The number of data-directory entries in the remainder of the
/// optional header. Each describes a location and size.
/// </summary>
public uint NumberOfRvaAndSizes;
}
}
|
using System;
using System.IO;
public class CompareTwoTextFiles
{
internal static void Main()
{
string firstFileName = "inputOne.txt";
string secondFileName = "inputTwo.txt";
if (!File.Exists(firstFileName))
{
string createFirstText = "Hello and Welcome!" + Environment.NewLine + "How are you?";
File.WriteAllText(firstFileName, createFirstText);
}
if (!File.Exists(secondFileName))
{
string createSecondText = "Hello and Welcome!" + Environment.NewLine + "What do you do?";
File.WriteAllText(secondFileName, createSecondText);
}
try
{
TextReader myFirstReader = new StreamReader(firstFileName);
TextReader mySecondReader = new StreamReader(secondFileName);
int sameLineCount = 0;
int diffLineCount = 0;
using (myFirstReader)
{
using (mySecondReader)
{
string firstLine = myFirstReader.ReadLine();
string secondLine = mySecondReader.ReadLine();
while (firstLine != null || secondLine != null)
{
if (firstLine == secondLine)
{
sameLineCount++;
}
else
{
diffLineCount++;
}
firstLine = myFirstReader.ReadLine();
secondLine = mySecondReader.ReadLine();
}
}
}
Console.WriteLine("The number of lines that are the same is: {0}", sameLineCount);
Console.WriteLine("The number of lines that are different is: {0}", diffLineCount);
}
catch
{
Console.Error.WriteLine("Error!");
}
}
}
|
using System.Collections.Generic;
namespace FluentEvents.Plugins
{
/// <summary>
/// Provides a way to add or list plugins.
/// </summary>
public interface IFluentEventsPluginOptions
{
/// <summary>
/// Adds a plugin.
/// </summary>
/// <remarks>
/// This method should be called with custom extension methods
/// to provide a better configuration experience.
/// </remarks>
/// <param name="plugin">The instance of the plugin.</param>
void AddPlugin(IFluentEventsPlugin plugin);
/// <summary>
/// Returns the list of the added plugins.
/// </summary>
IEnumerable<IFluentEventsPlugin> Plugins { get; }
}
} |
using System;
using System.Collections.Concurrent;
using static System.Runtime.Loader.AssemblyLoadContext;
namespace Natasha
{
public class DomainManagment
{
public readonly static AssemblyDomain Default;
public static ConcurrentDictionary<string, WeakReference> Cache;
static DomainManagment()
{
Cache = new ConcurrentDictionary<string, WeakReference>();
Default = new AssemblyDomain("Default");
}
public static AssemblyDomain Random
{
get { return DomainManagment.Create("N" + Guid.NewGuid().ToString("N")); }
}
public static AssemblyDomain Create(string key)
{
if (Cache.ContainsKey(key))
{
return (AssemblyDomain)(Cache[key].Target);
}
else
{
foreach (var item in Cache)
{
var domain = (AssemblyDomain)(item.Value.Target);
if (!item.Value.IsAlive)
{
Cache.TryRemove(item.Key, out _);
}
}
return new AssemblyDomain(key);
}
}
#if !NETSTANDARD2_0
public static ContextualReflectionScope Lock(string key)
{
if (Cache.ContainsKey(key))
{
return ((AssemblyDomain)(Cache[key].Target)).EnterContextualReflection();
}
return Default.EnterContextualReflection();
}
public static ContextualReflectionScope Lock(AssemblyDomain domain)
{
return domain.EnterContextualReflection();
}
public static ContextualReflectionScope CreateAndLock(string key)
{
return Lock(Create(key));
}
public static AssemblyDomain CurrentDomain
{
get
{
return CurrentContextualReflectionContext==default?
Default:
(AssemblyDomain)CurrentContextualReflectionContext;
}
}
#endif
public static void Add(string key, AssemblyDomain domain)
{
if (Cache.ContainsKey(key))
{
if (!Cache[key].IsAlive)
{
Cache[key] = new WeakReference(domain);
}
}
else
{
Cache[key] = new WeakReference(domain, trackResurrection: true);
}
}
public static WeakReference Remove(string key)
{
if (Cache.ContainsKey(key))
{
Cache.TryRemove(key, out var result);
if (result != default)
{
((AssemblyDomain)(result.Target)).Dispose();
}
return result;
}
throw new Exception($"Can't find key : {key}!");
}
public static bool IsDeleted(string key)
{
if (Cache.ContainsKey(key))
{
return !Cache[key].IsAlive;
}
return true;
}
public static AssemblyDomain Get(string key)
{
if (Cache.ContainsKey(key))
{
return (AssemblyDomain)Cache[key].Target;
}
return null;
}
public static int Count(string key)
{
return ((AssemblyDomain)(Cache[key].Target)).Count;
}
}
}
|
using System.Drawing;
namespace ConsoleApp;
public class ColorSettings
{
public Color TextColor { get; set; } = Color.LightGray;
public Color ScoreColor { get; set; } = Color.Red;
public Color Tile0 { get; set; } = Color.DarkGray;
public Color Tile2 { get; set; } = Color.Cyan;
public Color Tile4 { get; set; } = Color.AliceBlue;
public Color Tile8 { get; set; } = Color.DarkOrange;
public Color Tile16 { get; set; } = Color.LimeGreen;
public Color Tile32 { get; set; } = Color.LightGreen;
public Color Tile64 { get; set; } = Color.Yellow;
public Color Tile128 { get; set; } = Color.DodgerBlue;
public Color Tile256 { get; set; } = Color.DarkRed;
public Color Tile512 { get; set; } = Color.Firebrick;
public Color Tile1024 { get; set; } = Color.IndianRed;
public Color Tile2048 { get; set; } = Color.Coral;
public Color Tile4096 { get; set; } = Color.Gold;
public Color DefaultTile { get; set; } = Color.Goldenrod;
}
|
using GloboTicket.TicketManagement.App.Contracts;
using GloboTicket.TicketManagement.App.ViewModels;
using Microsoft.AspNetCore.Components;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace GloboTicket.TicketManagement.App.Pages
{
public partial class CategoryOverview
{
[Inject]
public ICategoryDataService CategoryDataService{ get; set; }
[Inject]
public NavigationManager NavigationManager { get; set; }
public ICollection<CategoryEventsViewModel> Categories { get; set; }
protected async override Task OnInitializedAsync()
{
Categories = await CategoryDataService.GetAllCategoriesWithEvents(false);
}
protected async void OnIncludeHistoryChanged(ChangeEventArgs args)
{
if((bool)args.Value)
{
Categories = await CategoryDataService.GetAllCategoriesWithEvents(true);
}
else
{
Categories = await CategoryDataService.GetAllCategoriesWithEvents(false);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace LiteDB
{
internal class QueryLess : Query
{
private BsonValue _value;
private bool _equals;
public QueryLess(string field, BsonValue value, bool equals)
: base(field)
{
_value = value;
_equals = equals;
}
internal override IEnumerable<IndexNode> ExecuteIndex(IndexService indexer, CollectionIndex index)
{
var value = _value.Normalize(index.Options);
foreach (var node in indexer.FindAll(index, Query.Ascending))
{
var diff = node.Key.CompareTo(value);
if (diff == 1 || (!_equals && diff == 0)) break;
if (node.IsHeadTail(index)) yield break;
yield return node;
}
}
}
}
|
namespace DataFactory.Performance
{
public interface IPerformanceExampleRestApi
{
}
} |
using System;
namespace Weborb.Reader
{
public interface INamedType
{
string getTypeName();
}
}
|
namespace Computers.UI.Console.Interfaces
{
public interface IRechargable
{
int CurrentCharge { get; }
void Charge(int powerInput);
}
}
|
namespace Bike.Interpreter
{
using System.Collections.Generic;
using System.IO;
using Builtin;
internal abstract class ImportContext
{
protected readonly string CoreLibFolder;
protected readonly string AddonLibFolders;
protected readonly List<string> SearchPaths = new List<string>();
protected ImportContext(string coreLibFolder, string addonLibFolders)
{
CoreLibFolder = coreLibFolder;
AddonLibFolders = addonLibFolders;
SearchPaths.Add(coreLibFolder);
if (string.IsNullOrWhiteSpace(addonLibFolders))
return;
string[] paths = addonLibFolders.Split(Path.PathSeparator);
foreach (var path in paths)
if (Directory.Exists(path))
SearchPaths.Add(path);
SearchPaths.Reverse();
}
protected string ResolvePath(string currentFolder, string filePath)
{
if (Path.IsPathRooted(filePath))
{
if (File.Exists(filePath))
return filePath;
throw ErrorFactory.CreateLoadError(filePath);
}
if (currentFolder != null)
{
var path = SearchInFolder(currentFolder, filePath);
if (path != null)
return path;
}
foreach (string libFolder in SearchPaths)
{
var path = SearchInFolder(libFolder, filePath);
if (path != null)
return path;
}
throw ErrorFactory.CreateLoadError(filePath);
}
private static string SearchInFolder(string folder, string filePath)
{
var path = Path.Combine(folder, filePath);
if (File.Exists(path))
return path;
foreach (var dir in new DirectoryInfo(folder).GetDirectories())
{
path = SearchInFolder(dir.FullName, filePath);
if (path != null)
return path;
}
return null;
}
}
}
|
namespace vdt.jquerydropdownlist.MVC.test {
public class TestViewModel {
public JQueryDropdownlist TestProperty { get; set; }
}
}
|
using Microsoft.Azure.Documents;
namespace SFA.DAS.CosmosDb.UnitTests.Fakes
{
public class ReadOnlyDummyRepository : ReadOnlyDocumentRepository<ReadOnlyDummy>
{
public ReadOnlyDummyRepository(IDocumentClient documentClient, string databaseName, string collectionName)
: base(documentClient, databaseName, collectionName)
{
}
}
} |
using System.IO;
using Base.Lang;
namespace Base.IO.Impl
{
public class ReadableFile : ILengthAwareReadable, INamed
{
public readonly FileInfo File;
public long Length => File.Length;
public string Name => File.FullName;
public ReadableFile(string file)
{
File = new FileInfo(file);
}
public ReadableFile(FileInfo file)
{
File = file;
}
public Stream OpenReader()
{
return File.OpenRead();
}
public override string ToString()
{
return Name;
}
}
} |
namespace BookLibrary.Web.Pages.Books
{
using System.Linq;
using Data;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Models;
public class DetailsModel : PageModel
{
private BookLibraryDbContext db;
public DetailsModel(BookLibraryDbContext db)
{
this.db = db;
}
public BookDetailsViewModel BookDetails { get; set; }
public IActionResult OnGet(int id)
{
this.BookDetails = this.db.Books
.Where(b => b.Id == id)
.Select(b => new BookDetailsViewModel()
{
Author = b.Author.Name,
CoverImg = b.CoverImg,
Title = b.Title,
ShortDescription = b.ShortDescription,
Status = b.Status
})
.FirstOrDefault();
if (this.BookDetails == null)
{
return this.NotFound();
}
return this.Page();
}
}
} |
using System;
using System.Collections.Generic;
namespace HBSQLite
{
/// <summary>
/// provide methods and properties to create order by object
/// </summary>
public class OrderBy : IOrderBy
{
/// <summary>
/// convert this class to string
/// </summary>
/// <param name="orderBy">the object to convert</param>
public static implicit operator string(OrderBy orderBy) => orderBy.ToString();
/// <summary>
/// the columns that will be used for sorting
/// </summary>
public List<SQLiteTableColumn> Columns { get; } = new List<SQLiteTableColumn>();
/// <summary>
/// the way to oder
/// </summary>
public OrderByWay OrderByWay { get; set; }
/// <summary>
/// initialize new instance of <see cref="SQLiteTableColumn"/> with full data
/// </summary>
/// <param name="columns">the columns that will be used for sorting</param>
/// <param name="orderByWay">the way to oder</param>
public OrderBy(IEnumerable<SQLiteTableColumn> columns, OrderByWay orderByWay)
{
Columns = new List<SQLiteTableColumn>(columns);
OrderByWay = orderByWay;
}
/// <summary>
/// initialize new instance of <see cref="SQLiteTableColumn"/> with one column
/// </summary>
/// <param name="column">the column that will be used for sorting</param>
/// <param name="orderByWay">the way to oder</param>
public OrderBy(SQLiteTableColumn column, OrderByWay orderByWay)
{
if (column == null) throw new ArgumentNullException(nameof(column));
Add(column);
OrderByWay = orderByWay;
}
/// <summary>
/// initialize new instance of <see cref="SQLiteTableColumn"/> with order state
/// </summary>
/// <param name="orderByWay">the way to oder</param>
public OrderBy(OrderByWay orderByWay) => OrderByWay = orderByWay;
/// <summary>
/// add new column to the list
/// </summary>
/// <param name="columns">the column that will be used for sorting</param>
public void Add(SQLiteTableColumn columns)
{
if (columns == null)
throw new ArgumentNullException(nameof(columns));
Columns.Add(columns);
}
/// <summary>
/// convert this object to string that can used in query
/// </summary>
/// <returns>string can used in query</returns>
public override string ToString()
{
switch (OrderByWay)
{
case OrderByWay.ASC:
return $" order by {string.Join(",", Columns)} {OrderByWay.ASC} ";
case OrderByWay.DESC:
return $" order by {string.Join(",", Columns)} {OrderByWay.DESC} ";
default:
throw new ArgumentNullException(nameof(OrderByWay));
}
}
}
}
|
namespace Stories.Services
{
public interface IVoteQueueService
{
void QueueStoryVote(int storyId);
void QueueCommentVote(int commentId);
}
}
|
using Models;
namespace Interfaces
{
public interface IDumpable
{
/// <summary>
/// Wykonaj zrzut ofert ze strony
/// </summary>
/// <returns></returns>
Dump GenerateDump();
}
}
|
using AbiokaRdn.Infrastructure.Common.Domain;
using AbiokaRdn.Infrastructure.Common.Exceptions;
namespace AbiokaRdn.Domain.Repositories
{
public interface IExceptionLogRepository : IReadOnlyRepository<ExceptionLog>
{
/// <summary>
/// Adds the specified exception log.
/// </summary>
/// <param name="exceptionLog">The exception log.</param>
void Add(ExceptionLog exceptionLog);
}
}
|
using System;
using System.Globalization;
using System.Reflection;
using Xamarin.Forms;
namespace IconButtonSample.Converters
{
public class ImageSourceConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (!(value is string))
{
return default(ImageSource);
}
var path = value.ToString();
if (Device.OS == TargetPlatform.iOS || Device.OS == TargetPlatform.Android)
{
return ImageSource.FromResource(path);
}
else
{
var assembly = typeof(App).GetTypeInfo().Assembly;
return ImageSource.FromResource(path, assembly);
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
|
using System.Text;
using FeatureToggle.NET.Core.Settings;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
namespace FeatureToggle.NET.Web
{
public partial class Startup
{
public void SetupAuth(IServiceCollection services)
{
var authSettings = new AuthSettings();
services.Configure<AuthSettings>(Configuration.GetSection("Auth"));
Configuration.GetSection("Auth").Bind(authSettings);
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = authSettings.Issuer,
ValidAudience = authSettings.Audience,
IssuerSigningKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(authSettings.EncryptionKey))
};
});
}
}
} |
using System.Windows.Input;
namespace GongSolutions.Wpf.DragDrop
{
/// <summary>
/// Interface implemented by Drag Info Builders.
/// It enables custom construction of DragInfo objects to support 3rd party controls like DevExpress, Telerik, etc.
/// </summary>
public interface IDragInfoBuilder
{
/// <summary>
/// Creates a drag info object from <see cref="MouseButtonEventArgs"/>.
/// </summary>
///
/// <param name="sender">
/// The sender of the mouse event that initiated the drag.
/// </param>
///
/// <param name="e">
/// The mouse event that initiated the drag.
/// </param>
DragInfo CreateDragInfo(object sender, MouseButtonEventArgs e);
/// <summary>
/// Creates a drag info object from <see cref="TouchEventArgs"/>.
/// </summary>
///
/// <param name="sender">
/// The sender of the touch event that initiated the drag.
/// </param>
///
/// <param name="e">
/// The touch event that initiated the drag.
/// </param>
DragInfo CreateDragInfo(object sender, TouchEventArgs e);
}
} |
using System.ComponentModel.DataAnnotations;
using UrlShortener.Validation;
namespace UrlShortener.Models;
/// <summary>
/// Create shortened url request
/// </summary>
public class CreateShortenedUrlRequest
{
/// <summary>
/// Url to shorten
/// </summary>
[Required]
[Url]
public string Url { get; set; } = string.Empty;
/// <summary>
/// Desired short name (optional). Case sensitive.
/// </summary>
[MaxLength(64)]
[ShortName]
public string? ShortName { get; set; }
}
|
using System;
// ReSharper disable once CheckNamespace
namespace Palla.Labs.Vdt.App.Dominio.Dtos
{
public class ManutencaoDto : DtoBase<Guid>
{
public long Data { get; set; }
public string Parte { get; set; }
}
} |
using System.Runtime.InteropServices;
using Sharpen;
namespace android.graphics
{
[Sharpen.Sharpened]
public partial class Region : android.os.Parcelable, System.IDisposable
{
/// <hide></hide>
internal readonly android.graphics.Region.NativeRegion mNativeRegion;
public enum Op : int
{
DIFFERENCE = 0,
INTERSECT = 1,
UNION = 2,
XOR = 3,
REVERSE_DIFFERENCE = 4,
REPLACE = 5
}
/// <summary>Create an empty region</summary>
public Region() : this(nativeConstructor())
{
}
/// <summary>Return a copy of the specified region</summary>
public Region(android.graphics.Region region) : this(nativeConstructor())
{
// the native values for these must match up with the enum in SkRegion.h
nativeSetRegion(mNativeRegion, region.mNativeRegion);
}
/// <summary>Return a region set to the specified rectangle</summary>
public Region(android.graphics.Rect r)
{
mNativeRegion = nativeConstructor();
nativeSetRect(mNativeRegion, r.left, r.top, r.right, r.bottom);
}
/// <summary>Return a region set to the specified rectangle</summary>
public Region(int left, int top, int right, int bottom)
{
mNativeRegion = nativeConstructor();
nativeSetRect(mNativeRegion, left, top, right, bottom);
}
/// <summary>Set the region to the empty region</summary>
public virtual void setEmpty()
{
nativeSetRect(mNativeRegion, 0, 0, 0, 0);
}
/// <summary>Set the region to the specified region.</summary>
/// <remarks>Set the region to the specified region.</remarks>
public virtual bool set(android.graphics.Region region)
{
return nativeSetRegion(mNativeRegion, region.mNativeRegion);
}
/// <summary>Set the region to the specified rectangle</summary>
public virtual bool set(android.graphics.Rect r)
{
return nativeSetRect(mNativeRegion, r.left, r.top, r.right, r.bottom);
}
/// <summary>Set the region to the specified rectangle</summary>
public virtual bool set(int left, int top, int right, int bottom)
{
return nativeSetRect(mNativeRegion, left, top, right, bottom);
}
/// <summary>Set the region to the area described by the path and clip.</summary>
/// <remarks>
/// Set the region to the area described by the path and clip.
/// Return true if the resulting region is non-empty. This produces a region
/// that is identical to the pixels that would be drawn by the path
/// (with no antialiasing).
/// </remarks>
public virtual bool setPath(android.graphics.Path path, android.graphics.Region clip
)
{
return nativeSetPath(mNativeRegion, path.nativeInstance, clip.mNativeRegion);
}
[DllImport("libxobotos.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.
Unicode)]
private static extern bool libxobotos_Region_isEmpty(android.graphics.Region.NativeRegion
_instance);
/// <summary>Return true if this region is empty</summary>
public virtual bool isEmpty()
{
return libxobotos_Region_isEmpty(mNativeRegion);
}
[DllImport("libxobotos.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.
Unicode)]
private static extern bool libxobotos_Region_isRect(android.graphics.Region.NativeRegion
_instance);
/// <summary>Return true if the region contains a single rectangle</summary>
public virtual bool isRect()
{
return libxobotos_Region_isRect(mNativeRegion);
}
[DllImport("libxobotos.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.
Unicode)]
private static extern bool libxobotos_Region_isComplex(android.graphics.Region.NativeRegion
_instance);
/// <summary>Return true if the region contains more than one rectangle</summary>
public virtual bool isComplex()
{
return libxobotos_Region_isComplex(mNativeRegion);
}
/// <summary>Return a new Rect set to the bounds of the region.</summary>
/// <remarks>
/// Return a new Rect set to the bounds of the region. If the region is
/// empty, the Rect will be set to [0, 0, 0, 0]
/// </remarks>
public virtual android.graphics.Rect getBounds()
{
android.graphics.Rect r = new android.graphics.Rect();
nativeGetBounds(mNativeRegion, r);
return r;
}
/// <summary>Set the Rect to the bounds of the region.</summary>
/// <remarks>
/// Set the Rect to the bounds of the region. If the region is empty, the
/// Rect will be set to [0, 0, 0, 0]
/// </remarks>
public virtual bool getBounds(android.graphics.Rect r)
{
if (r == null)
{
throw new System.ArgumentNullException();
}
return nativeGetBounds(mNativeRegion, r);
}
/// <summary>Return the boundary of the region as a new Path.</summary>
/// <remarks>
/// Return the boundary of the region as a new Path. If the region is empty,
/// the path will also be empty.
/// </remarks>
public virtual android.graphics.Path getBoundaryPath()
{
android.graphics.Path path = new android.graphics.Path();
nativeGetBoundaryPath(mNativeRegion, path.nativeInstance);
return path;
}
/// <summary>Set the path to the boundary of the region.</summary>
/// <remarks>
/// Set the path to the boundary of the region. If the region is empty, the
/// path will also be empty.
/// </remarks>
public virtual bool getBoundaryPath(android.graphics.Path path)
{
return nativeGetBoundaryPath(mNativeRegion, path.nativeInstance);
}
[DllImport("libxobotos.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.
Unicode)]
private static extern bool libxobotos_Region_contains(android.graphics.Region.NativeRegion
_instance, int x, int y);
/// <summary>Return true if the region contains the specified point</summary>
public virtual bool contains(int x, int y)
{
return libxobotos_Region_contains(mNativeRegion, x, y);
}
/// <summary>
/// Return true if the region is a single rectangle (not complex) and it
/// contains the specified rectangle.
/// </summary>
/// <remarks>
/// Return true if the region is a single rectangle (not complex) and it
/// contains the specified rectangle. Returning false is not a guarantee
/// that the rectangle is not contained by this region, but return true is a
/// guarantee that the rectangle is contained by this region.
/// </remarks>
public virtual bool quickContains(android.graphics.Rect r)
{
return quickContains(r.left, r.top, r.right, r.bottom);
}
[DllImport("libxobotos.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.
Unicode)]
private static extern bool libxobotos_Region_quickContains(android.graphics.Region.NativeRegion
_instance, int left, int top, int right, int bottom);
/// <summary>
/// Return true if the region is a single rectangle (not complex) and it
/// contains the specified rectangle.
/// </summary>
/// <remarks>
/// Return true if the region is a single rectangle (not complex) and it
/// contains the specified rectangle. Returning false is not a guarantee
/// that the rectangle is not contained by this region, but return true is a
/// guarantee that the rectangle is contained by this region.
/// </remarks>
public virtual bool quickContains(int left, int top, int right, int bottom)
{
return libxobotos_Region_quickContains(mNativeRegion, left, top, right, bottom);
}
/// <summary>
/// Return true if the region is empty, or if the specified rectangle does
/// not intersect the region.
/// </summary>
/// <remarks>
/// Return true if the region is empty, or if the specified rectangle does
/// not intersect the region. Returning false is not a guarantee that they
/// intersect, but returning true is a guarantee that they do not.
/// </remarks>
public virtual bool quickReject(android.graphics.Rect r)
{
return quickReject(r.left, r.top, r.right, r.bottom);
}
[DllImport("libxobotos.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.
Unicode)]
private static extern bool libxobotos_Region_quickRejectRect(android.graphics.Region.NativeRegion
_instance, int left, int top, int right, int bottom);
/// <summary>
/// Return true if the region is empty, or if the specified rectangle does
/// not intersect the region.
/// </summary>
/// <remarks>
/// Return true if the region is empty, or if the specified rectangle does
/// not intersect the region. Returning false is not a guarantee that they
/// intersect, but returning true is a guarantee that they do not.
/// </remarks>
public virtual bool quickReject(int left, int top, int right, int bottom)
{
return libxobotos_Region_quickRejectRect(mNativeRegion, left, top, right, bottom);
}
[DllImport("libxobotos.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.
Unicode)]
private static extern bool libxobotos_Region_quickReject(android.graphics.Region.NativeRegion
_instance, android.graphics.Region.NativeRegion rgn);
/// <summary>
/// Return true if the region is empty, or if the specified region does not
/// intersect the region.
/// </summary>
/// <remarks>
/// Return true if the region is empty, or if the specified region does not
/// intersect the region. Returning false is not a guarantee that they
/// intersect, but returning true is a guarantee that they do not.
/// </remarks>
public virtual bool quickReject(android.graphics.Region rgn)
{
return libxobotos_Region_quickReject(mNativeRegion, rgn != null ? rgn.mNativeRegion
: android.graphics.Region.NativeRegion.Zero);
}
/// <summary>Translate the region by [dx, dy].</summary>
/// <remarks>Translate the region by [dx, dy]. If the region is empty, do nothing.</remarks>
public virtual void translate(int dx, int dy)
{
translate(dx, dy, null);
}
[DllImport("libxobotos.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.
Unicode)]
private static extern void libxobotos_Region_translate(android.graphics.Region.NativeRegion
_instance, int dx, int dy, android.graphics.Region.NativeRegion dst);
/// <summary>Set the dst region to the result of translating this region by [dx, dy].
/// </summary>
/// <remarks>
/// Set the dst region to the result of translating this region by [dx, dy].
/// If this region is empty, then dst will be set to empty.
/// </remarks>
public virtual void translate(int dx, int dy, android.graphics.Region dst)
{
libxobotos_Region_translate(mNativeRegion, dx, dy, dst != null ? dst.mNativeRegion
: android.graphics.Region.NativeRegion.Zero);
}
/// <summary>Scale the region by the given scale amount.</summary>
/// <remarks>
/// Scale the region by the given scale amount. This re-constructs new region by
/// scaling the rects that this region consists of. New rectis are computed by scaling
/// coordinates by float, then rounded by roundf() function to integers. This may results
/// in less internal rects if 0 < scale < 1. Zero and Negative scale result in
/// an empty region. If this region is empty, do nothing.
/// </remarks>
/// <hide></hide>
public virtual void scale(float scale_1)
{
scale(scale_1, null);
}
[DllImport("libxobotos.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.
Unicode)]
private static extern void libxobotos_Region_scale(android.graphics.Region.NativeRegion
_instance, float scale_1, android.graphics.Region.NativeRegion dst);
/// <summary>Set the dst region to the result of scaling this region by the given scale amount.
/// </summary>
/// <remarks>
/// Set the dst region to the result of scaling this region by the given scale amount.
/// If this region is empty, then dst will be set to empty.
/// </remarks>
/// <hide></hide>
public virtual void scale(float scale_1, android.graphics.Region dst)
{
libxobotos_Region_scale(mNativeRegion, scale_1, dst != null ? dst.mNativeRegion :
android.graphics.Region.NativeRegion.Zero);
}
public bool union(android.graphics.Rect r)
{
return op(r, android.graphics.Region.Op.UNION);
}
/// <summary>Perform the specified Op on this region and the specified rect.</summary>
/// <remarks>
/// Perform the specified Op on this region and the specified rect. Return
/// true if the result of the op is not empty.
/// </remarks>
public virtual bool op(android.graphics.Rect r, android.graphics.Region.Op op_1)
{
return nativeOp(mNativeRegion, r.left, r.top, r.right, r.bottom, (int)op_1);
}
/// <summary>Perform the specified Op on this region and the specified rect.</summary>
/// <remarks>
/// Perform the specified Op on this region and the specified rect. Return
/// true if the result of the op is not empty.
/// </remarks>
public virtual bool op(int left, int top, int right, int bottom, android.graphics.Region
.Op op_1)
{
return nativeOp(mNativeRegion, left, top, right, bottom, (int)op_1);
}
/// <summary>Perform the specified Op on this region and the specified region.</summary>
/// <remarks>
/// Perform the specified Op on this region and the specified region. Return
/// true if the result of the op is not empty.
/// </remarks>
public virtual bool op(android.graphics.Region region, android.graphics.Region.Op
op_1)
{
return op(this, region, op_1);
}
/// <summary>
/// Set this region to the result of performing the Op on the specified rect
/// and region.
/// </summary>
/// <remarks>
/// Set this region to the result of performing the Op on the specified rect
/// and region. Return true if the result is not empty.
/// </remarks>
public virtual bool op(android.graphics.Rect rect, android.graphics.Region region
, android.graphics.Region.Op op_1)
{
return nativeOp(mNativeRegion, rect, region.mNativeRegion, (int)op_1);
}
/// <summary>
/// Set this region to the result of performing the Op on the specified
/// regions.
/// </summary>
/// <remarks>
/// Set this region to the result of performing the Op on the specified
/// regions. Return true if the result is not empty.
/// </remarks>
public virtual bool op(android.graphics.Region region1, android.graphics.Region region2
, android.graphics.Region.Op op_1)
{
return nativeOp(mNativeRegion, region1.mNativeRegion, region2.mNativeRegion, (int
)op_1);
}
public static readonly android.os.ParcelableClass.Creator<android.graphics.Region
> CREATOR = null;
//////////////////////////////////////////////////////////////////////////
[Sharpen.ImplementsInterface(@"android.os.Parcelable")]
public virtual int describeContents()
{
return 0;
}
[Sharpen.Stub]
[Sharpen.ImplementsInterface(@"android.os.Parcelable")]
public virtual void writeToParcel(android.os.Parcel p, int flags)
{
throw new System.NotImplementedException();
}
[Sharpen.OverridesMethod(@"java.lang.Object")]
public override bool Equals(object obj)
{
if (obj == null || !(obj is android.graphics.Region))
{
return false;
}
android.graphics.Region peer = (android.graphics.Region)obj;
return nativeEquals(mNativeRegion, peer.mNativeRegion);
}
~Region()
{
try
{
nativeDestructor(mNativeRegion);
}
finally
{
;
}
}
internal Region(android.graphics.Region.NativeRegion ni_1)
{
if (ni_1 == null)
{
throw new java.lang.RuntimeException();
}
mNativeRegion = ni_1;
}
private Region(android.graphics.Region.NativeRegion ni_1, android.graphics.Region.NativeRegion
dummy) : this(ni_1)
{
}
[DllImport("libxobotos.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.
Unicode)]
private static extern bool libxobotos_Region_equals(android.graphics.Region.NativeRegion
native_r1, android.graphics.Region.NativeRegion native_r2);
private static bool nativeEquals(android.graphics.Region.NativeRegion native_r1,
android.graphics.Region.NativeRegion native_r2)
{
return libxobotos_Region_equals(native_r1, native_r2);
}
[DllImport("libxobotos.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.
Unicode)]
private static extern android.graphics.Region.NativeRegion libxobotos_Region_constructor
();
private static android.graphics.Region.NativeRegion nativeConstructor()
{
return libxobotos_Region_constructor();
}
private static void nativeDestructor(android.graphics.Region.NativeRegion native_region
)
{
native_region.Dispose();
}
[DllImport("libxobotos.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.
Unicode)]
private static extern bool libxobotos_Region_setRegion(android.graphics.Region.NativeRegion
native_dst, android.graphics.Region.NativeRegion native_src);
private static bool nativeSetRegion(android.graphics.Region.NativeRegion native_dst
, android.graphics.Region.NativeRegion native_src)
{
return libxobotos_Region_setRegion(native_dst, native_src);
}
[DllImport("libxobotos.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.
Unicode)]
private static extern bool libxobotos_Region_setRect(android.graphics.Region.NativeRegion
native_dst, int left, int top, int right, int bottom);
private static bool nativeSetRect(android.graphics.Region.NativeRegion native_dst
, int left, int top, int right, int bottom)
{
return libxobotos_Region_setRect(native_dst, left, top, right, bottom);
}
[DllImport("libxobotos.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.
Unicode)]
private static extern bool libxobotos_Region_setPath(android.graphics.Region.NativeRegion
native_dst, android.graphics.Path.NativePath native_path, android.graphics.Region.NativeRegion
native_clip);
private static bool nativeSetPath(android.graphics.Region.NativeRegion native_dst
, android.graphics.Path.NativePath native_path, android.graphics.Region.NativeRegion
native_clip)
{
return libxobotos_Region_setPath(native_dst, native_path, native_clip);
}
[DllImport("libxobotos.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.
Unicode)]
private static extern bool libxobotos_Region_getBounds(android.graphics.Region.NativeRegion
native_region, System.IntPtr rect);
private static bool nativeGetBounds(android.graphics.Region.NativeRegion native_region
, android.graphics.Rect rect)
{
System.IntPtr rect_ptr = System.IntPtr.Zero;
try
{
rect_ptr = android.graphics.Rect.Rect_Helper.ManagedToNative(rect);
bool _retval = libxobotos_Region_getBounds(native_region, rect_ptr);
android.graphics.Rect.Rect_Helper.MarshalOut(rect_ptr, rect);
return _retval;
}
finally
{
android.graphics.Rect.Rect_Helper.FreeManagedPtr(rect_ptr);
}
}
[DllImport("libxobotos.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.
Unicode)]
private static extern bool libxobotos_Region_getBoundaryPath(android.graphics.Region.NativeRegion
native_region, android.graphics.Path.NativePath native_path);
private static bool nativeGetBoundaryPath(android.graphics.Region.NativeRegion native_region
, android.graphics.Path.NativePath native_path)
{
return libxobotos_Region_getBoundaryPath(native_region, native_path);
}
[DllImport("libxobotos.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.
Unicode)]
private static extern bool libxobotos_Region_recOp(android.graphics.Region.NativeRegion
native_dst, int left, int top, int right, int bottom, int op_1);
private static bool nativeOp(android.graphics.Region.NativeRegion native_dst, int
left, int top, int right, int bottom, int op_1)
{
return libxobotos_Region_recOp(native_dst, left, top, right, bottom, op_1);
}
[DllImport("libxobotos.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.
Unicode)]
private static extern bool libxobotos_Region_rectOp(android.graphics.Region.NativeRegion
native_dst, System.IntPtr rect, android.graphics.Region.NativeRegion native_region
, int op_1);
private static bool nativeOp(android.graphics.Region.NativeRegion native_dst, android.graphics.Rect
rect, android.graphics.Region.NativeRegion native_region, int op_1)
{
System.IntPtr rect_ptr = System.IntPtr.Zero;
try
{
rect_ptr = android.graphics.Rect.Rect_Helper.ManagedToNative(rect);
return libxobotos_Region_rectOp(native_dst, rect_ptr, native_region, op_1);
}
finally
{
android.graphics.Rect.Rect_Helper.FreeManagedPtr(rect_ptr);
}
}
[DllImport("libxobotos.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.
Unicode)]
private static extern bool libxobotos_Region_op(android.graphics.Region.NativeRegion
native_dst, android.graphics.Region.NativeRegion native_region1, android.graphics.Region.NativeRegion
native_region2, int op_1);
private static bool nativeOp(android.graphics.Region.NativeRegion native_dst, android.graphics.Region.NativeRegion
native_region1, android.graphics.Region.NativeRegion native_region2, int op_1)
{
return libxobotos_Region_op(native_dst, native_region1, native_region2, op_1);
}
internal NativeRegion nativeInstance
{
get
{
return mNativeRegion;
}
}
public void Dispose()
{
mNativeRegion.Dispose();
}
internal class NativeRegion : System.Runtime.InteropServices.SafeHandle
{
internal NativeRegion() : base(System.IntPtr.Zero, true)
{
}
internal NativeRegion(System.IntPtr handle) : base(System.IntPtr.Zero, true)
{
this.handle = handle;
}
[DllImport("libxobotos.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.
Unicode)]
private static extern void libxobotos_android_graphics_Region_destructor(System.IntPtr
handle);
internal System.IntPtr Handle
{
get
{
return handle;
}
}
public static readonly NativeRegion Zero = new NativeRegion();
protected override bool ReleaseHandle()
{
if (handle != System.IntPtr.Zero)
{
libxobotos_android_graphics_Region_destructor(handle);
}
handle = System.IntPtr.Zero;
return true;
}
public override bool IsInvalid
{
get
{
return handle == System.IntPtr.Zero;
}
}
}
}
}
|
using System;
namespace Robzilla888.ApiReviewHelper.ObjectModel
{
[Flags]
internal enum MemberAttributes
{
None = 0x0,
New = 0x1,
//Private = 0x2,
Protected = 0x4,
Protected_Internal = 0x8,
Public = 0x10,
Static = 0x20,
Virtual = 0x40,
Abstract = 0x80,
Sealed = 0x100,
Override = 0x200,
Async = 0x400,
Readonly = 0x800,
Const = 0x1000,
Event = 0x2000,
}
}
|
using Masiv.Roulette.Model;
using System.Threading.Tasks;
namespace Masiv.Roulette.Data
{
public interface IBetRepository
{
Task<int> CreateBet(Bet bet);
}
} |
using FluentAssertions;
using LogoFX.Client.Mvvm.Model.Specs.Helpers;
using LogoFX.Client.Mvvm.Model.Specs.Objects;
using TechTalk.SpecFlow;
namespace LogoFX.Client.Mvvm.Model.Specs.Steps
{
[Binding]
internal sealed class DeepHierarchyEditableModelSteps
{
private readonly CompositeDirtyScenarioDataStore _dirtyScenarioDataStore;
private readonly ModelSteps _modelSteps;
public DeepHierarchyEditableModelSteps(
ScenarioContext scenarioContext,
ModelSteps modelSteps)
{
_dirtyScenarioDataStore = new CompositeDirtyScenarioDataStore(scenarioContext);
_modelSteps = modelSteps;
}
[When(@"The deep hierarchy model is created")]
public void WhenTheDeepHierarchyModelIsCreated()
{
_modelSteps.CreateModel(() => new DeepHierarchyEditableModel());
}
[When(@"The deep hierarchy model with all generations is created")]
public void WhenTheDeepHierarchyModelWithAllGenerationsIsCreated()
{
var grandchild = new SimpleEditableModel(DataGenerator.ValidName, 10);
var child = new CompositeEditableModel("location", new[] {grandchild});
_dirtyScenarioDataStore.Child = child;
_dirtyScenarioDataStore.GrandChild = grandchild;
_modelSteps.CreateModel(() => { return new DeepHierarchyEditableModel(new[] {child}); });
}
[When(@"The child model is created")]
public void WhenTheChildModelIsCreated()
{
var child = new CompositeEditableModel("location");
_dirtyScenarioDataStore.Child = child;
}
[When(@"The first child model is created")]
public void WhenTheFirstChildModelIsCreated()
{
var child = new CompositeEditableModel("location");
_dirtyScenarioDataStore.FirstChild = child;
}
[When(@"The second child model is created")]
public void WhenTheSecondChildModelIsCreated()
{
var child = new CompositeEditableModel("location");
_dirtyScenarioDataStore.SecondChild = child;
}
[When(@"The grandchild model is created")]
public void WhenTheGrandchildModelIsCreated()
{
var grandchild = new SimpleEditableModel(DataGenerator.ValidName, 10);
_dirtyScenarioDataStore.GrandChild = grandchild;
}
[When(@"The first grandchild model is created")]
public void WhenTheFirstGrandchildModelIsCreated()
{
var grandChild = new SimpleEditableModel();
_dirtyScenarioDataStore.FirstGrandChild = grandChild;
}
[When(@"The second grandchild model is created")]
public void WhenTheSecondGrandchildModelIsCreated()
{
var grandChild = new SimpleEditableModel();
_dirtyScenarioDataStore.SecondGrandChild = grandChild;
}
[When(@"The grandchild name is updated to '(.*)'")]
public void WhenTheGrandchildNameIsUpdatedTo(string name)
{
var grandchild = _dirtyScenarioDataStore.GrandChild;
grandchild.Name = name;
}
[When(@"The child is added to the deep hierarchy model")]
public void WhenTheChildIsAddedToTheDeepHierarchyModel()
{
var model = _modelSteps.GetModel<DeepHierarchyEditableModel>();
var child = _dirtyScenarioDataStore.Child;
model.AddCompositeItemImpl(child);
}
[When(@"The first child is added to the deep hierarchy model")]
public void WhenTheFirstChildIsAddedToTheDeepHierarchyModel()
{
var model = _modelSteps.GetModel<DeepHierarchyEditableModel>();
var child = _dirtyScenarioDataStore.FirstChild;
model.AddCompositeItemImpl(child);
}
[When(@"The second child is added to the deep hierarchy model")]
public void WhenTheSecondChildIsAddedToTheDeepHierarchyModel()
{
var model = _modelSteps.GetModel<DeepHierarchyEditableModel>();
var child = _dirtyScenarioDataStore.SecondChild;
model.AddCompositeItemImpl(child);
}
[When(@"The grandchild is added to the child")]
public void WhenTheGrandchildIsAddedToTheChild()
{
var child = _dirtyScenarioDataStore.Child;
var grandchild = _dirtyScenarioDataStore.GrandChild;
child.AddSimpleModelImpl(grandchild);
}
[When(@"The first grandchild is added to the first child")]
public void WhenTheFirstGrandchildIsAddedToTheFirstChild()
{
var child = _dirtyScenarioDataStore.FirstChild;
var grandchild = _dirtyScenarioDataStore.FirstGrandChild;
child.AddSimpleModelImpl(grandchild);
}
[When(@"The second grandchild is added to the first child")]
public void WhenTheSecondGrandchildIsAddedToTheFirstChild()
{
var child = _dirtyScenarioDataStore.FirstChild;
var grandchild = _dirtyScenarioDataStore.SecondGrandChild;
child.AddSimpleModelImpl(grandchild);
}
[When(@"The first child is removed from the deep hierarchy model")]
public void WhenTheFirstChildIsRemovedFromTheDeepHierarchyModel()
{
var model = _modelSteps.GetModel<DeepHierarchyEditableModel>();
var child = _dirtyScenarioDataStore.FirstChild;
model.RemoveCompositeModel(child);
}
[When(@"The child is updated with removing the grandchild")]
public void WhenTheChildIsUpdatedWithRemovingTheGrandchild()
{
var child = _dirtyScenarioDataStore.Child;
var grandchild = _dirtyScenarioDataStore.GrandChild;
child.RemoveSimpleItem(grandchild);
}
[When(@"The first child is updated with removing the first grandchild")]
public void WhenTheFirstChildIsUpdatedWithRemovingTheFirstGrandchild()
{
var child = _dirtyScenarioDataStore.FirstChild;
var grandchild = _dirtyScenarioDataStore.FirstGrandChild;
child.RemoveSimpleItem(grandchild);
}
[When(@"The deep hierarchy model changes are committed")]
public void WhenTheDeepHierarchyModelChangesAreCommitted()
{
var model = _modelSteps.GetModel<DeepHierarchyEditableModel>();
model.CommitChanges();
}
[When(@"The deep hierarchy model changes are cancelled")]
public void WhenTheDeepHierarchyModelChangesAreCancelled()
{
var model = _modelSteps.GetModel<DeepHierarchyEditableModel>();
model.CancelChanges();
}
[Then(@"The deep hierarchy model is not marked as dirty")]
public void ThenTheDeepHierarchyModelIsNotMarkedAsDirty()
{
var model = _modelSteps.GetModel<DeepHierarchyEditableModel>();
model.IsDirty.Should().BeFalse();
}
[Then(@"The grandchild name should be identical to the valid name")]
public void ThenTheGrandchildNameShouldBeIdenticalToTheValidName()
{
var grandchild = _dirtyScenarioDataStore.GrandChild;
grandchild.Name.Should().Be(DataGenerator.ValidName);
}
[Then(@"The deep hierarchy model changes can be cancelled")]
public void ThenTheDeepHierarchyModelChangesCanBeCancelled()
{
var model = _modelSteps.GetModel<DeepHierarchyEditableModel>();
model.CanCancelChanges.Should().BeTrue();
}
[Then(@"The deep hierarchy model changes can not be cancelled")]
public void ThenTheDeepHierarchyModelChangesCanNotBeCancelled()
{
var model = _modelSteps.GetModel<DeepHierarchyEditableModel>();
model.CanCancelChanges.Should().BeFalse();
}
[Then(@"The deep hierarchy model contains the child")]
public void ThenTheDeepHierarchyModelContainsTheChild()
{
var model = _modelSteps.GetModel<DeepHierarchyEditableModel>();
var child = _dirtyScenarioDataStore.Child;
model.CompositeModels.Should().BeEquivalentTo(new[] {child});
}
[Then(@"The deep hierarchy model contains all children")]
public void ThenTheDeepHierarchyModelContainsAllChildren()
{
var model = _modelSteps.GetModel<DeepHierarchyEditableModel>();
var children = new[]
{
_dirtyScenarioDataStore.FirstChild,
_dirtyScenarioDataStore.SecondChild
};
model.CompositeModels.Should().BeEquivalentTo(children);
}
[Then(@"The child contains the grandchild")]
public void ThenTheChildContainsTheGrandchild()
{
var grandchild = _dirtyScenarioDataStore.GrandChild;
var child = _dirtyScenarioDataStore.Child;
child.SimpleCollection.Should().BeEquivalentTo(new[] {grandchild});
}
[Then(@"The child does not contain the grandchild")]
public void ThenTheChildDoesNotContainTheGrandchild()
{
var grandchild = _dirtyScenarioDataStore.GrandChild;
var child = _dirtyScenarioDataStore.Child;
child.SimpleCollection.Should().NotContain(grandchild);
}
[Then(@"The first child contains all grandchildren")]
public void ThenTheFirstChildContainsAllGrandchildren()
{
var grandchildren = new[]
{
_dirtyScenarioDataStore.FirstGrandChild,
_dirtyScenarioDataStore.SecondGrandChild
};
var child = _dirtyScenarioDataStore.FirstChild;
child.SimpleCollection.Should().BeEquivalentTo(grandchildren);
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;
using ProjectManager.Controls;
using ProjectManager.Projects;
using PluginCore;
using PluginCore.Localization;
using PluginCore.Controls;
using ASClassWizard.Controls.TreeView;
namespace ASClassWizard.Wizards
{
public partial class PackageBrowser : SmartForm
{
List<string> classpathList;
public PackageBrowser()
{
Initialize();
InitializeComponent();
LocalizeTexts();
CenterToParent();
this.FormGuid = "b5a7f1b4-959b-485b-a7d7-9b683191c0cf";
this.Font = PluginBase.Settings.DefaultFont;
this.browserView.ImageList = Icons.ImageList;
this.browserView.BeforeExpand += onBeforeExpandNode;
}
private void LocalizeTexts()
{
this.inviteLabel.Text = TextHelper.GetString("Wizard.Label.ChosePackage");
this.okButton.Text = TextHelper.GetString("Wizard.Button.Ok");
this.cancelButton.Text = TextHelper.GetString("Wizard.Button.Cancel");
this.Text = TextHelper.GetString("Wizard.Label.PackageSelection");
}
public Project Project { get; set; }
public string Package => ((SimpleDirectoryNode) browserView.SelectedNode)?.directoryPath;
private void Initialize() => classpathList = new List<string>();
public void AddClassPath(string value) => classpathList.Add(value);
private void RefreshTree()
{
this.browserView.BeginUpdate();
this.browserView.Nodes.Clear();
if (classpathList.Count > 0)
{
foreach(string cp in classpathList)
{
if (Directory.Exists(cp))
try
{
foreach (string item in Directory.GetDirectories(cp))
{
if (!IsDirectoryExcluded(item))
{
var node = new SimpleDirectoryNode(item, Path.Combine(cp, item));
node.ImageIndex = Icons.Folder.Index;
node.SelectedImageIndex = Icons.Folder.Index;
this.browserView.Nodes.Add(node);
}
}
}
catch { }
}
}
this.browserView.EndUpdate();
}
private void PackageBrowser_Load(object sender, EventArgs e)
{
RefreshTree();
}
private void onBeforeExpandNode(object sender, TreeViewCancelEventArgs e)
{
if (e.Node is SimpleDirectoryNode node && node.dirty)
{
node.dirty = false;
node.Nodes.Clear();
foreach (string item in Directory.GetDirectories(node.directoryPath))
{
if (!IsDirectoryExcluded(item))
{
var newNode = new SimpleDirectoryNode(item, Path.Combine(node.directoryPath, item));
newNode.ImageIndex = Icons.Folder.Index;
newNode.SelectedImageIndex = Icons.Folder.Index;
node.Nodes.Add(newNode);
}
}
}
}
/// <summary>
/// Verify if a given directory is hidden
/// </summary>
protected bool IsDirectoryExcluded(string path)
{
string dirName = Path.GetFileName(path);
foreach (string excludedDir in ProjectManager.PluginMain.Settings.ExcludedDirectories)
{
if (dirName.ToLower() == excludedDir)
{
return true;
}
}
return Project.IsPathHidden(path) && !Project.ShowHiddenPaths;
}
private void okButton_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.OK;
this.Close();
}
private void cancelButton_Click(object sender, EventArgs e)
{
this.browserView.SelectedNode = null;
this.DialogResult = DialogResult.Cancel;
this.Close();
}
}
}
|
using Util.Biz.Payments.Core;
namespace Util.Biz.Payments.Wechatpay.Parameters.Requests {
/// <summary>
/// 微信App支付参数
/// </summary>
public class WechatpayAppPayRequest : PayParamBase {
}
}
|
using System;
using System.IO;
using MO.Common.Lang;
namespace MO.Common.IO
{
//============================================================
// <T>字符读取器。</T>
//============================================================
public class FCharReader : IDisposable
{
protected StreamReader _reader;
protected int _position = 0;
protected int _count = 0;
protected string _skips = "\r";
protected char[] _buffer;
public const int DEFAULT_SIZE = 16;
public FCharReader(StreamReader reader)
: this(reader, DEFAULT_SIZE) {
}
public FCharReader(StreamReader reader, int length) {
_reader = reader;
_buffer = new char[length];
ReadBuffer();
}
public StreamReader Reader {
get { return _reader; }
}
protected void ReadBuffer() {
_count -= _position;
if (_count > 0) {
Array.Copy(_buffer, _position, _buffer, 0, _count);
}
_count += _reader.Read(_buffer, _count, _buffer.Length - _count);
int offset = 0;
for (int n = 0; n < _count; n++) {
if (_skips.IndexOf(_buffer[n]) != -1) {
continue;
}
_buffer[offset++] = _buffer[n];
}
_count = offset;
_position = 0;
}
public bool HasNext() {
if (_position >= _count) {
ReadBuffer();
}
return _position < _count;
}
public char Read() {
if (_position >= _count) {
ReadBuffer();
}
return (_position < _count) ? _buffer[_position++] : default(char);
}
public string ReadLine() {
FString line = new FString();
while (HasNext()) {
char ch = Read();
if (ch == '\r') {
continue;
} else if (ch == '\r') {
break;
}
line.Append(ch);
}
return line.ToString();
}
public char Get(int index) {
if (_position + index >= _count) {
ReadBuffer();
}
if (_position < _count) {
return _buffer[_position + index - 1];
}
return default(char);
}
public void Skip(int index) {
if (_position + index >= _count) {
ReadBuffer();
}
if (_position < _count) {
_position++;
}
}
public void Close() {
if (_reader != null) {
_reader.Close();
}
}
public void Dispose() {
Close();
}
}
}
|
using System.Transactions;
namespace BookLovers.Base.Infrastructure.Persistence
{
public static class TransactionScopeFactory
{
public static TransactionScope CreateTransactionScope(
IsolationLevel isolationLevel)
{
return new TransactionScope(
TransactionScopeOption.Required,
new TransactionOptions
{
IsolationLevel = isolationLevel,
Timeout = TransactionManager.MaximumTimeout
}, TransactionScopeAsyncFlowOption.Enabled);
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
using DatAdmin;
using System.Globalization;
using System.Text.RegularExpressions;
using System.Data.OracleClient;
using System.Data;
namespace Plugin.oracle
{
public class OracleDDA : DialectDataAdapterBase
{
public OracleDDA(ISqlDialect dialect)
: base(dialect)
{
}
public override SqlLiteralFormatter CreateLiteralFormatter()
{
return new OracleLiteralFormatter(m_dialect);
}
public override IBedReader AdaptReader(System.Data.IDataReader reader)
{
return new OracleDataReaderAdapter(reader, m_dialect);
}
}
public class OracleLiteralFormatter : SqlLiteralFormatter
{
static Regex m_dayRegex = new Regex(@"^(\d*\.)?(\d\d?\:\d\d?\:\d\d?)(\.\d*)?$");
public OracleLiteralFormatter(ISqlDialect dialect)
: base(dialect)
{
}
public override void SetString(string value)
{
if (TargetType != null)
{
var spec = m_dialect.GenericTypeToSpecific(TargetType);
if (spec is OracleTypeIntervalDayToSecond)
{
var m1 = m_dayRegex.Match(value);
if (m1.Success)
{
if (m1.Groups[1].Success)
{
m_text = "INTERVAL '";
m_text += m1.Groups[1].Value.Slice(0, -1);
m_text += " ";
m_text += m1.Groups[2].Value;
if (m1.Groups[3].Success) m_text += m1.Groups[3].Value;
m_text += "' DAY TO SECOND";
}
else
{
m_text = "INTERVAL '";
m_text += m1.Groups[2].Value;
if (m1.Groups[3].Success) m_text += m1.Groups[3].Value;
m_text += "' HOUR TO SECOND";
}
return;
}
int days;
if (Int32.TryParse(value, out days))
{
m_text = "INTERVAL '" + days.ToString() + "' DAY";
return;
}
}
if (spec is OracleTypeIntervalYearToMonth)
{
int months;
if (Int32.TryParse(value, out months))
{
m_text = "INTERVAL '" + months.ToString() + "' MONTH";
return;
}
}
}
base.SetString(value);
}
public override void SetInt32(int value)
{
if (TargetType != null)
{
var spec = m_dialect.GenericTypeToSpecific(TargetType);
if (spec is OracleTypeIntervalYearToMonth)
{
m_text = "INTERVAL '" + value.ToString() + "' MONTH";
return;
}
}
base.SetInt32(value);
}
public override void SetDateTime(DateTime value)
{
m_text = "timestamp'" + value.ToString("yyyy-MM-dd HH:mm:ss.fff", DateTimeFormatInfo.InvariantInfo) + "'";
}
public override void SetDateTimeEx(DateTimeEx value)
{
m_text = "timestamp'" + value.ToString("yyyy-MM-dd HH:mm:ss.fff", DateTimeFormatInfo.InvariantInfo) + "'";
}
public override void SetDateEx(DateEx value)
{
m_text = "date'" + value.ToString("yyyy-MM-dd", DateTimeFormatInfo.InvariantInfo) + "'";
}
public override void SetTimeEx(TimeEx value)
{
m_text = "timestamp'" + value.ToString("0001-01-01 HH:mm:ss.fff", DateTimeFormatInfo.InvariantInfo) + "'";
}
}
public class OracleDataReaderAdapter : DataReaderAdapter
{
OracleDataReader m_myReader;
public OracleDataReaderAdapter(IDataReader reader, ISqlDialect dialect)
: base(reader, dialect)
{
m_myReader = reader as OracleDataReader;
}
}
}
|
using System.Collections.Generic;
using BattleLogic.Player.Stats;
namespace BattleLogic.Stats
{
public interface IStats
{
IEnumerable<IStat> All { get; }
void Set(StatType type, float value);
void Reset(StatType type);
void Increase(StatType type, float value);
void Decrease(StatType type, float value);
IStat By(StatType type);
}
} |
namespace PcapDotNet.Packets.IpV6
{
/// <summary>
/// RFC-ietf-netext-pmip-lr-10.
/// </summary>
public enum IpV6MobilityLocalizedRoutingAcknowledgementStatus : byte
{
/// <summary>
/// Success.
/// </summary>
Success = 0,
/// <summary>
/// Localized Routing Not Allowed.
/// </summary>
LocalizedRoutingNotAllowed = 128,
/// <summary>
/// MN not attached.
/// </summary>
MobileNodeNotAttached = 129,
}
} |
using PokemonManager.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PokemonManager.Game.FileStructure.Gen3.GBA {
public class BlockData : IBlockData {
protected byte[] raw;
protected BlockDataCollection parent;
protected IGameSave gameSave;
public BlockData(IGameSave gameSave, byte[] data, BlockDataCollection parent) {
if (data.Length != 4096)
throw new Exception("Block size not equal to 4096 bytes");
this.raw = data;
this.parent = parent;
this.gameSave = gameSave;
}
public byte[] Raw {
get { return raw; }
}
public uint this[int index, uint val] {
get { return LittleEndian.ToUInt32(raw, index); }
set { LittleEndian.WriteUInt32(value, raw, index); }
}
public ushort this[int index, ushort val] {
get { return LittleEndian.ToUInt16(raw, index); }
set { LittleEndian.WriteUInt16(value, raw, index); }
}
public byte this[int index, byte val] {
get { return raw[index]; }
set { raw[index] = value; }
}
public BlockDataCollection Parent {
get { return parent; }
set { parent = value; }
}
public uint SaveIndex {
get { return LittleEndian.ToUInt32(raw, 4092); }
set { LittleEndian.WriteUInt32(value, raw, 4092); }
}
public SectionTypes SectionID {
get { return (SectionTypes)LittleEndian.ToUInt16(raw, 4084); }
set { LittleEndian.WriteUInt16((ushort)value, raw, 4084); }
}
public ushort Checksum {
get { return LittleEndian.ToUInt16(raw, 4086); }
set { LittleEndian.WriteUInt16(value, raw, 4086); }
}
public virtual ushort CalculateChecksum() {
uint checksum = 0;
int contents = SectionIDTable.GetContents(SectionID);
int startIndex = 0;
while (startIndex < contents) {
checksum += BitConverter.ToUInt32(raw, startIndex);
startIndex += 4;
}
byte[] bytes = BitConverter.GetBytes(checksum);
return (ushort)((uint)BitConverter.ToUInt16(bytes, 0) + (uint)BitConverter.ToUInt16(bytes, 2));
}
public virtual byte[] GetFinalData() {
Checksum = CalculateChecksum();
return raw;
}
}
}
|
namespace ay.Controls
{
public class TreeViewItemData : AyPropertyChanged
{
private string _Header;
/// <summary>
/// 树的内容
/// </summary>
public string Header
{
get { return _Header; }
set { Set(ref _Header, value); }
}
private int _OrderID;
/// <summary>
/// 排序ID,
/// </summary>
public int OrderID
{
get { return _OrderID; }
set { Set(ref _OrderID, value); }
}
}
}
|
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
namespace SpanJson.Formatters.Dynamic
{
public sealed class SpanJsonDynamicObject : DynamicObject
{
private readonly Dictionary<string, object> _dictionary;
internal SpanJsonDynamicObject(Dictionary<string, object> dictionary)
{
_dictionary = dictionary;
}
public override string ToString()
{
return $"{{{string.Join(",", _dictionary.Select(a => $"\"{a.Key}\":{a.Value.ToJsonValue()}"))}}}";
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
return _dictionary.TryGetValue(binder.Name, out result);
}
public override bool TryConvert(ConvertBinder binder, out object result)
{
if (typeof(IDictionary<string, object>).IsAssignableFrom(binder.ReturnType))
{
result = _dictionary;
return true;
}
return base.TryConvert(binder, out result);
}
public override IEnumerable<string> GetDynamicMemberNames()
{
return _dictionary.Keys;
}
}
} |
namespace Book.ViewModels.Samples.Chapter25.Sample01
{
using System;
using System.Reactive;
using System.Reactive.Concurrency;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using Microsoft.Reactive.Testing;
using PCLMock;
using ReactiveUI;
using ReactiveUI.Testing;
using Xunit;
[Sample(
"Re-structuring for improved readability",
@"This sample is a refactoring of [Sample 24.02](24.02) to improve the readability and maintainability of the code.")]
public sealed class Tests : TestSampleViewModel
{
[Fact]
public void data_is_not_retrieved_upon_construction()
{
var api = new ApiMock();
var sut = new DinosaurDetailsViewModel(
42,
new BitmapLoaderMock(),
api,
CurrentThreadScheduler.Instance);
api
.Verify(x => x.GetDinosaur(It.IsAny<int>()))
.WasNotCalled();
}
[Fact]
public void data_is_retrieved_upon_activation()
{
var api = new ApiMock();
var sut = new DinosaurDetailsViewModel(
42,
new BitmapLoaderMock(),
api,
CurrentThreadScheduler.Instance);
sut
.Activator
.Activate();
api
.Verify(x => x.GetDinosaur(42))
.WasCalledExactlyOnce();
}
[Fact]
public void retrieved_data_is_used_to_populate_the_initial_values()
{
var scheduler = new TestScheduler();
var dinosaur = new Dinosaur("Barney", 13, new byte[] { 1, 2, 3 });
var api = new ApiMock();
api
.When(x => x.GetDinosaur(42))
.Return(Observable.Return(dinosaur));
var sut = new DinosaurDetailsViewModel(
42,
new BitmapLoaderMock(),
api,
scheduler);
sut
.Activator
.Activate();
scheduler.AdvanceByMs(1);
Assert.Equal("Barney", sut.Name);
Assert.Equal("13", sut.Weight);
Assert.Equal(13, sut.ValidatedWeight.Value);
Assert.NotNull(sut.Image);
}
[Fact]
public void valid_weights_are_accepted()
{
var scheduler = new TestScheduler();
var sut = new DinosaurDetailsViewModel(
42,
new BitmapLoaderMock(),
new ApiMock(),
scheduler);
sut
.Activator
.Activate();
scheduler.AdvanceByMs(1);
sut.Weight = "42";
scheduler.AdvanceByMs(1);
Assert.True(sut.ValidatedWeight.IsValid);
Assert.Equal(42, sut.ValidatedWeight.Value);
}
[Fact]
public void invalid_weights_are_rejected()
{
var sut = new DinosaurDetailsViewModel(
42,
new BitmapLoaderMock(),
new ApiMock(),
CurrentThreadScheduler.Instance);
sut
.Activator
.Activate();
sut.Weight = "42a";
Assert.False(sut.ValidatedWeight.IsValid);
Assert.Equal("'42a' is not a valid weight. Please enter whole numbers only.", sut.ValidatedWeight.Error);
}
[Fact]
public void changing_the_image_data_updates_the_image()
{
var sut = new DinosaurDetailsViewModel(
42,
new BitmapLoaderMock(),
new ApiMock(),
CurrentThreadScheduler.Instance);
sut
.Activator
.Activate();
var images = sut
.WhenAnyValue(x => x.Image)
.CreateCollection(ImmediateScheduler.Instance);
sut.ImageData = new byte[] { 1, 2, 3 };
sut.ImageData = new byte[] { 4, 5, 6 };
Assert.Equal(3, images.Count);
}
[Fact]
public void data_is_saved_two_seconds_after_name_is_modified()
{
var scheduler = new TestScheduler();
var api = new ApiMock();
var sut = new DinosaurDetailsViewModel(
42,
new BitmapLoaderMock(),
api,
scheduler);
sut
.Activator
.Activate();
scheduler.AdvanceByMs(2000);
sut.Name = "Barney";
sut.Weight = "42";
scheduler.AdvanceByMs(1999);
api
.Verify(x => x.SaveDinosaur(It.IsAny<Dinosaur>()))
.WasNotCalled();
scheduler.AdvanceByMs(1);
api
.Verify(x => x.SaveDinosaur(It.IsAny<Dinosaur>()))
.WasCalledExactlyOnce();
}
[Fact]
public void data_is_saved_two_seconds_after_weight_is_modified()
{
var scheduler = new TestScheduler();
var api = new ApiMock();
var sut = new DinosaurDetailsViewModel(
42,
new BitmapLoaderMock(),
api,
scheduler);
sut
.Activator
.Activate();
scheduler.AdvanceByMs(2000);
sut.Weight = "42";
scheduler.AdvanceByMs(1999);
api
.Verify(x => x.SaveDinosaur(It.IsAny<Dinosaur>()))
.WasNotCalled();
scheduler.AdvanceByMs(1);
api
.Verify(x => x.SaveDinosaur(It.IsAny<Dinosaur>()))
.WasCalledExactlyOnce();
}
[Fact]
public void data_is_saved_two_seconds_after_image_data_is_modified()
{
var scheduler = new TestScheduler();
var api = new ApiMock();
var sut = new DinosaurDetailsViewModel(
42,
new BitmapLoaderMock(),
api,
scheduler);
sut
.Activator
.Activate();
scheduler.AdvanceByMs(2000);
sut.Weight = "42";
sut.ImageData = new byte[] { 1, 2, 3 };
scheduler.AdvanceByMs(1999);
api
.Verify(x => x.SaveDinosaur(It.IsAny<Dinosaur>()))
.WasNotCalled();
scheduler.AdvanceByMs(1);
api
.Verify(x => x.SaveDinosaur(It.IsAny<Dinosaur>()))
.WasCalledExactlyOnce();
}
[Fact]
public void data_is_saved_immediately_upon_deactivation_even_if_two_seconds_has_not_elapsed_since_last_change()
{
var scheduler = new TestScheduler();
var api = new ApiMock();
var sut = new DinosaurDetailsViewModel(
42,
new BitmapLoaderMock(),
api,
scheduler);
sut
.Activator
.Activate();
sut.Name = "Barney";
scheduler.AdvanceByMs(1);
api
.Verify(x => x.SaveDinosaur(It.IsAny<Dinosaur>()))
.WasNotCalled();
sut
.Activator
.Deactivate();
scheduler.AdvanceByMs(1);
api
.Verify(x => x.SaveDinosaur(It.IsAny<Dinosaur>()))
.WasCalledExactlyOnce();
}
[Fact]
public void saves_are_throttled_to_two_seconds()
{
var scheduler = new TestScheduler();
var api = new ApiMock();
var sut = new DinosaurDetailsViewModel(
42,
new BitmapLoaderMock(),
api,
scheduler);
sut
.Activator
.Activate();
scheduler.AdvanceByMs(2000);
sut.Name = "Barney";
scheduler.AdvanceByMs(500);
sut.Name = "Barney the Dinosaur";
scheduler.AdvanceByMs(500);
sut.Weight = "42";
scheduler.AdvanceByMs(1999);
api
.Verify(x => x.SaveDinosaur(It.IsAny<Dinosaur>()))
.WasNotCalled();
scheduler.AdvanceByMs(1);
api
.Verify(x => x.SaveDinosaur(It.IsAny<Dinosaur>()))
.WasCalledExactlyOnce();
}
[Fact]
public void data_is_not_saved_if_it_is_invalid()
{
var api = new ApiMock();
var sut = new DinosaurDetailsViewModel(
42,
new BitmapLoaderMock(),
api,
CurrentThreadScheduler.Instance);
sut
.Activator
.Activate();
sut.Weight = "42a";
api
.Verify(x => x.SaveDinosaur(It.IsAny<Dinosaur>()))
.WasNotCalled();
}
[Fact]
public void data_cannot_be_deleted_if_the_auditing_system_is_unavailable()
{
var api = new ApiMock();
var isAuditingAvailable = new BehaviorSubject<bool>(true);
api
.When(x => x.IsAuditingAvailable)
.Return(isAuditingAvailable);
var sut = new DinosaurDetailsViewModel(
42,
new BitmapLoaderMock(),
api,
CurrentThreadScheduler.Instance);
sut
.Activator
.Activate();
Assert.True(sut.DeleteCommand.CanExecute.FirstAsync().Wait());
isAuditingAvailable.OnNext(false);
Assert.False(sut.DeleteCommand.CanExecute.FirstAsync().Wait());
isAuditingAvailable.OnNext(true);
Assert.True(sut.DeleteCommand.CanExecute.FirstAsync().Wait());
}
[Fact]
public void data_is_not_deleted_if_user_cancels()
{
var api = new ApiMock();
var sut = new DinosaurDetailsViewModel(
42,
new BitmapLoaderMock(),
api,
CurrentThreadScheduler.Instance);
using (sut.ConfirmDeleteInteraction.RegisterHandler(context => context.SetOutput(false)))
{
sut
.DeleteCommand
.Execute()
.Subscribe();
}
api
.Verify(x => x.DeleteDinosaur(It.IsAny<int>()))
.WasNotCalled();
}
[Fact]
public void data_is_deleted_if_user_confirms()
{
var api = new ApiMock();
var sut = new DinosaurDetailsViewModel(
42,
new BitmapLoaderMock(),
api,
CurrentThreadScheduler.Instance);
using (sut.ConfirmDeleteInteraction.RegisterHandler(context => context.SetOutput(true)))
{
sut
.DeleteCommand
.Execute()
.Subscribe();
}
api
.Verify(x => x.DeleteDinosaur(It.IsAny<int>()))
.WasCalledExactlyOnce();
}
[Fact]
public void busy_flag_remains_true_whilst_retrieving_data()
{
var api = new ApiMock();
var getDinosaur = new Subject<Dinosaur>();
api
.When(x => x.GetDinosaur(It.IsAny<int>()))
.Return(getDinosaur);
var sut = new DinosaurDetailsViewModel(
42,
new BitmapLoaderMock(),
api,
CurrentThreadScheduler.Instance);
sut
.Activator
.Activate();
Assert.True(sut.IsBusy);
getDinosaur.OnCompleted();
Assert.False(sut.IsBusy);
}
[Fact]
public void busy_flag_remains_true_whilst_saving_data()
{
var scheduler = new TestScheduler();
var api = new ApiMock();
var saveDinosaur = new Subject<Unit>();
api
.When(x => x.SaveDinosaur(It.IsAny<Dinosaur>()))
.Return(saveDinosaur);
var sut = new DinosaurDetailsViewModel(
42,
new BitmapLoaderMock(),
api,
scheduler);
sut
.Activator
.Activate();
sut.Name = "Barney";
sut.Weight = "42";
scheduler.AdvanceByMs(2001);
Assert.True(sut.IsBusy);
saveDinosaur.OnCompleted();
scheduler.AdvanceByMs(1);
Assert.False(sut.IsBusy);
}
[Fact]
public void busy_flag_remains_true_whilst_deleting_data()
{
var api = new ApiMock();
var deleteDinosaur = new Subject<Unit>();
api
.When(x => x.DeleteDinosaur(It.IsAny<int>()))
.Return(deleteDinosaur);
var sut = new DinosaurDetailsViewModel(
42,
new BitmapLoaderMock(),
api,
CurrentThreadScheduler.Instance);
sut
.Activator
.Activate();
using (sut.ConfirmDeleteInteraction.RegisterHandler(context => context.SetOutput(true)))
{
sut
.DeleteCommand
.Execute()
.Subscribe();
Assert.True(sut.IsBusy);
}
deleteDinosaur.OnCompleted();
Assert.False(sut.IsBusy);
}
[Fact]
public void errors_retrieving_data_are_surfaced()
{
var api = new ApiMock();
api
.When(x => x.GetDinosaur(It.IsAny<int>()))
.Return(Observable.Throw<Dinosaur>(new InvalidOperationException("foo")));
var sut = new DinosaurDetailsViewModel(
42,
new BitmapLoaderMock(),
api,
CurrentThreadScheduler.Instance);
sut
.Activator
.Activate();
Assert.NotNull(sut.Error);
Assert.Equal("foo", sut.Error.Exception.Message);
api
.When(x => x.GetDinosaur(It.IsAny<int>()))
.Return(Observable.Return(default(Dinosaur)));
sut
.Error
.RetryCommand
.Execute(null);
Assert.Null(sut.Error);
}
[Fact]
public void errors_saving_data_are_surfaced()
{
var scheduler = new TestScheduler();
var api = new ApiMock();
api
.When(x => x.SaveDinosaur(It.IsAny<Dinosaur>()))
.Return(Observable.Throw<Unit>(new InvalidOperationException("foo")));
var sut = new DinosaurDetailsViewModel(
42,
new BitmapLoaderMock(),
api,
scheduler);
sut
.Activator
.Activate();
sut.Name = "Barney";
sut.Weight = "42";
scheduler.AdvanceByMs(2001);
Assert.NotNull(sut.Error);
Assert.Equal("foo", sut.Error.Exception.Message);
api
.When(x => x.SaveDinosaur(It.IsAny<Dinosaur>()))
.Return(Observable.Return(Unit.Default));
sut
.Error
.RetryCommand
.Execute(null);
scheduler.AdvanceByMs(1);
Assert.Null(sut.Error);
}
[Fact]
public void errors_deleting_data_are_surfaced()
{
var api = new ApiMock();
api
.When(x => x.DeleteDinosaur(It.IsAny<int>()))
.Return(Observable.Throw<Unit>(new InvalidOperationException("foo")));
var sut = new DinosaurDetailsViewModel(
42,
new BitmapLoaderMock(),
api,
CurrentThreadScheduler.Instance);
sut
.Activator
.Activate();
using (sut.ConfirmDeleteInteraction.RegisterHandler(context => context.SetOutput(true)))
{
sut
.DeleteCommand
.Execute()
.Subscribe(
_ => { },
_ => { });
Assert.NotNull(sut.Error);
Assert.Equal("foo", sut.Error.Exception.Message);
api
.When(x => x.DeleteDinosaur(It.IsAny<int>()))
.Return(Observable.Return(Unit.Default));
sut
.Error
.RetryCommand
.Execute(null);
Assert.Null(sut.Error);
}
}
[Fact]
public void memory_is_reclaimed_after_deactivation()
{
//
// IMPORTANT: if you're observing failures in this test, try running it in release mode without a debugger attached.
//
// The SUT will subscribe to this subject, so we hold a reference to it so that it can't be GC'd.
var isAuditingAvailable = new Subject<bool>();
var api = new ApiMock();
api
.When(x => x.IsAuditingAvailable)
.Return(isAuditingAvailable);
var sut = new DinosaurDetailsViewModel(
42,
new BitmapLoaderMock(),
api,
CurrentThreadScheduler.Instance);
sut
.Activator
.Activate();
var weakSut = new WeakReference(sut);
sut = null;
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
Assert.True(weakSut.IsAlive);
// Deactivation is when the SUT should detach subscriptions and therefore become eligible for collection.
((DinosaurDetailsViewModel)weakSut.Target)
.Activator
.Deactivate();
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
Assert.False(weakSut.IsAlive);
}
}
} |
using SOLID_._5.DIP.GoodExample.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SOLID_._5.DIP.GoodExample.Concrete
{
public class ChickenMeat : IRecipes
{
public string GetCooking()
{
return "Tavuk ızagara tafileri..!";
}
}
}
|
namespace ET.Client
{
[ComponentOf(typeof(Session))]
public class RouterCheckComponent: Entity, IAwake
{
}
} |
using System.Collections.Immutable;
using Zio;
namespace Arbor.CodeAutomate;
public class RepositoryAnalysis
{
public RepositoryAnalysis(ImmutableArray<FileEntry> workflowFiles,
IReadOnlyCollection<ICodeFixSuggestion> codeFixSuggestions)
{
CodeFixSuggestions = codeFixSuggestions;
WorkflowFiles = workflowFiles;
GitHubActionsEnabled = !WorkflowFiles.IsDefaultOrEmpty;
}
public ImmutableArray<FileEntry> WorkflowFiles { get; }
public bool GitHubActionsEnabled { get; }
public IReadOnlyCollection<ICodeFixSuggestion> CodeFixSuggestions { get; }
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RA.Models.Input.profiles.QData
{
/// <summary>
/// DataSet Time Frame
/// Time frame including earnings and employment start and end dates of the data set.
/// https://credreg.net/qdata/terms/DataSetTimeFrame
/// </summary>
public class DataSetTimeFrame
{
/// <summary>
/// Attributes of the data set.
/// qdata:DataProfile
/// </summary>
public List<DataProfile> DataAttributes { get; set; } = new List<DataProfile>();
/// <summary>
/// Data Source Coverage Type
/// Type of geographic coverage of the subjects.
/// <see cref="https://credreg.net/qdata/terms/dataSourceCoverageType"/>
/// skos:Concept
/// <see cref="https://credreg.net/qdata/terms/DataSourceCoverage"/>
/// sourceCoverage:Country
/// sourceCoverage:Global
/// sourceCoverage:Region
/// sourceCoverage:StateOrProvince
/// sourceCoverage:UrbanArea
/// </summary>
public List<string> DataSourceCoverageType { get; set; } = new List<string>();
//NOT required
public string Description { get; set; }
public LanguageMap Description_Map { get; set; } = new LanguageMap();
public string Name { get; set; }
public LanguageMap Name_Map { get; set; } = new LanguageMap();
public string StartDate { get; set; }
public string EndDate { get; set; }
}
}
|
using FluentValidation;
using MediatR;
using StarterProject.Api.Common.Responses;
using System.Threading.Tasks;
namespace StarterProject.Api.Services
{
public interface IMediatorService
{
Task<Response<TResponse>> Send<TResponse>(IRequest<TResponse> request)
where TResponse : class, new();
}
public class MediatorService : IMediatorService
{
private readonly IMediator _mediator;
public MediatorService(IMediator mediator)
{
_mediator = mediator;
}
public async Task<Response<TResponse>> Send<TResponse>(IRequest<TResponse> request)
where TResponse : class, new()
{
var response = new Response<TResponse>();
try
{
var result = await _mediator.Send(request);
response.Data = result;
}
catch (ValidationException validationException)
{
response = ConvertValidationErrorsToErrorMessages<TResponse>(validationException);
}
return response;
}
private Response<TResponse> ConvertValidationErrorsToErrorMessages<TResponse>(ValidationException result)
where TResponse : class, new()
{
var response = new Response<TResponse> { Data = new TResponse() };
foreach (var error in result.Errors)
{
var errorMessage = new ErrorMessage
{
Message = error.ErrorMessage,
Property = error.PropertyName
};
response.ErrorMessages.Add(errorMessage);
}
return response;
}
}
} |
using System;
using System.Collections.Generic;
namespace DesignPatterns.GoF.Behavioural.Memento
{
// Intent
// Without violating encapsulation, capture and externalize an object'sinternal
//state so that the object can be restored to this state later.
// Use the Memento pattern when
//· a snapshot of(some portion of) an object's state must be saved sothat it
//can be restored to that state later, and
//· a direct interface to obtaining the state would expose implementation
//details and break the object's encapsulation.
// Consequences
//The Memento pattern has several consequences:
//1. Preserving encapsulation boundaries.Memento avoids exposing information
//that only an originator shouldmanage but that must be stored nevertheless
//outside the originator.The pattern shields other objects from potentially
//complex Originatorinternals, thereby preserving encapsulation boundaries.
//2. It simplifies Originator.In other encapsulation-preserving designs,
//Originator keeps theversions of internal state that clients have requested.
//That puts allthe storage management burden on Originator.Having
//clientsmanage the state they ask for simplifies Originator and keepsclients
//from having to notify originators when they're done.
//3. Using mementos might be expensive.Mementos might incur considerable
//overhead if Originator must copylarge amounts of information to store in
//the memento or if clientscreate and return mementos to the originator often
//enough. Unless encapsulating and restoring Originator state is cheap, the
//patternmight not be appropriate.See the discussion of incrementality in
//theImplementation section.
//4. Defining narrow and wide interfaces.It may be difficult in some languages
//to ensure that only theoriginator can access the memento's state.
//5. Hidden costs in caring for mementos.A caretaker is responsible for deleting
//the mementos it cares for.However, the caretaker has no idea how much state
//is in the memento.Hence an otherwise lightweight caretaker might incur large
//storagecosts when it stores mementos.
//Participants
//· Memento(SolverState)
//o stores internal state of the Originator object. The memento may store
//as much or as little of the originator's internal state as necessary
//at its originator's discretion.
//o protects against access by objects other than the originator.
//Mementos have effectively two interfaces. Caretaker sees a narrow
//interface to the Memento—it can only pass the memento to other objects.
//Originator, in contrast, sees a wide interface, one that lets it
//access all the data necessary to restore itself to its previous state.
//Ideally, only the originator that produced the memento would be
//permitted to access the memento's internal state.
//· Originator (ConstraintSolver)
//o creates a memento containing a snapshot of its current internal
//state.
//o uses the memento to restore its internal state.
//· Caretaker(undo mechanism)
//o is responsible for the memento's safekeeping.
//o never operates on or examines the contents of a memento.
public class MementoExample
{
public static void Main(String[] args)
{
Caretaker caretaker = new Caretaker();
Originator originator = new Originator();
originator.Set("State1");
originator.Set("State2");
caretaker.AddMemento(originator.SaveToMemento());
originator.Set("State3");
caretaker.AddMemento(originator.SaveToMemento());
originator.Set("State4");
originator.RestoreFromMemento(caretaker.GetMemento(1));
Console.ReadLine();
}
public class Originator
{
private String state;
public void Set(String state)
{
Console.WriteLine("Originator: Setting state to " + state);
this.state = state;
}
public Object SaveToMemento()
{
Console.WriteLine("Originator: Saving to Memento.");
return new Memento(state);
}
public void RestoreFromMemento(Object m)
{
if (m is Memento) {
Memento memento = (Memento)m;
state = memento.GetSavedState();
Console.WriteLine("Originator: State after restoring from Memento: " + state);
}
}
}
public class Memento
{
private String state;
public Memento(String stateToSave)
{
state = stateToSave;
}
public String GetSavedState()
{
return state;
}
}
public class Caretaker
{
private List<Object> savedStates = new List<Object>();
public void AddMemento(Object m)
{
savedStates.Add(m);
}
public Object GetMemento(int index)
{
return savedStates[index];
}
}
}
} |
using System;
namespace MemgrindDifferencingEngine.Util
{
static class Strings
{
/// <summary>
/// Return the first line of a string.
/// </summary>
/// <param name="multiline"></param>
/// <returns></returns>
public static string FirstLine(this string multiline)
{
return multiline.Substring(0, multiline.IndexOf(Environment.NewLine));
}
public static string AfterFirstLine(this string multiline)
{
return multiline.Substring(multiline.IndexOf(Environment.NewLine) + 1);
}
}
}
|
using System;
namespace ASD.Graphs
{
/// <summary>
/// Lista incydencji implementowana jako drzewo AVL
/// </summary>
/// <remarks>
/// Cała funkcjonalność pochodzi z typu bazowego <see cref="AVL{TKey,TValue}"/>.
/// </remarks>
/// <seealso cref="ASD.Graphs"/>
[Serializable]
public class AVLAdjacencyList : AVL<int, double>, IAdjacencyList
{
}
}
|
using WashableSoftware.Crosscutting.Notifications.Core.Channels;
using WashableSoftware.Crosscutting.Notifications.Core.Notifications;
using System.Threading.Tasks;
namespace WashableSoftware.Crosscutting.Notifications.Core.Manager
{
public interface INotificationManager
{
INotificationChannel GetChannel(string channelName, bool suppressErrors = false);
Task SendNotificationAsync(INotificationChannel channel, INotification notification);
Task SendNotificationAsync(string channelName, INotification notification);
Task SendNotificationAsync(INotificationChannel channel, object data);
Task SendNotificationAsync(string channelName, object data);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ES5.Script.EcmaScript.Internal
{
public class CommaSeparatedExpression : ExpressionElement
{
List<ExpressionElement> fParameters;
public CommaSeparatedExpression(PositionPair aPositionPair, params ExpressionElement[] aParameters)
: base(aPositionPair)
{
fParameters = new List<ExpressionElement>(aParameters);
}
public CommaSeparatedExpression(PositionPair aPositionPair, IEnumerable<ExpressionElement> aParameters)
: base(aPositionPair)
{
fParameters = new List<ExpressionElement>(aParameters);
}
public CommaSeparatedExpression(PositionPair aPositionPair, List<ExpressionElement> aParameters)
: base(aPositionPair)
{
fParameters = aParameters;
}
public List<ExpressionElement> Parameters { get { return fParameters; } }
public override ElementType Type { get { return ElementType.CommaSeparatedExpression; } }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Fruits : MonoBehaviour {
string[] cars = { "banana", "apple", "mango", "blueberry"};
void Start(){
for (int i = 0; i <= cars.Length; i = i + 1)
{
Debug.Log("cars at position" + i + "is " + cars[i]);
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.