content stringlengths 23 1.05M |
|---|
//-----------------------------------------------------------------------
// <copyright file="UserService.cs" company="QJJS">
// Copyright QJJS. All rights reserved.
// </copyright>
// <author>liyuhang</author>
// <date>2021/9/1 16:09:43</date>
//-----------------------------------------------------------------------
using LiMeowApi.Entity.User;
using LiMeowApi.Repository;
using LiMeowApi.Schema.User;
using LiMeowApi.Service.Contract;
using LiMeowApi.Utility;
using System.Threading.Tasks;
namespace LiMeowApi.Service.Implement
{
public class UserService : IUserService
{
private readonly IRepository<UserEntity> _userRepository;
public UserService(IRepository<UserEntity> userRepository)
{
_userRepository = userRepository;
}
public async Task<UserModel> GetUserById(string id)
{
return await _userRepository.Get<UserModel>(x => x.Id == id);
}
public async Task<UserModel> GetUserByUserName(string userName)
{
return await _userRepository.Get<UserModel>(x => x.UserName == userName);
}
public async Task<UserModel> AddUser(UserModel user)
{
if (await _userRepository.Count(x => x.UserName == user.UserName) == 0)
{
user.Password = SecurityUtil.Md5Password(user.UserName, user.Password);
return await _userRepository.Save(user);
}
return null;
}
public async Task<bool> ModifyPassword(string userId, string oldPassword, string newPassword)
{
if (!newPassword.Equals(oldPassword))
{
var user = await _userRepository.Get<UserModel>(x => x.Id == userId);
if (user != null)
{
if (SecurityUtil.Md5Password(user.UserName, oldPassword) == user.Password)
{
user.Password = SecurityUtil.Md5Password(user.UserName, newPassword);
await _userRepository.Update(user);
return true;
}
}
}
return false;
}
}
} |
using Backlog.Domain.Models;
using FluentValidation;
using System;
namespace Backlog.Domain.Dtos
{
public class ArticleSnapShotDtoValidator: AbstractValidator<ArticleSnapShotDto>
{
public ArticleSnapShotDtoValidator()
{
RuleFor(x => x.ArticleSnapShotId).NotNull();
RuleFor(x => x.Name).NotNull();
}
}
public class ArticleSnapShotDto
{
public Guid ArticleSnapShotId { get; set; }
public string Name { get; set; }
}
public static class ArticleSnapShotExtensions
{
public static ArticleSnapShotDto ToDto(this ArticleSnapShot articleSnapShot)
=> new ArticleSnapShotDto
{
ArticleSnapShotId = articleSnapShot.ArticleSnapShotId
};
}
}
|
// <copyright file="UserGroupSearchResult.cs" company="Microsoft">
// Copyright (c) Microsoft. All rights reserved.
// </copyright>
namespace Microsoft.Teams.Apps.EmployeeTraining.Models
{
/// <summary>
/// Represents model for search result consisting users and groups.
/// </summary>
public class UserGroupSearchResult
{
/// <summary>
/// Gets or sets display name for user or group.
/// </summary>
public string DisplayName { get; set; }
/// <summary>
/// Gets or sets unique object identifier for user or group.
/// </summary>
public string Id { get; set; }
/// <summary>
/// Gets or sets a value indicating whether boolean indicating whether entity is group.
/// </summary>
public bool IsGroup { get; set; }
/// <summary>
/// Gets or sets email address for user or group.
/// </summary>
public string Email { get; set; }
/// <summary>
/// Gets or sets a value indicating whether user or group is set to mandatory.
/// </summary>
public bool IsMandatory { get; set; }
}
}
|
using System.Threading.Tasks;
using Orleans;
namespace SimpleIoT.Grains.Interfaces
{
public interface IIntegrationGrain : IGrainWithGuidKey
{
Task InitiazeAsync();
Task AddDeviceAsync(IDeviceGrain device);
Task<string[]> GetDevicesAsync();
}
}
|
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using Windows.UI.Xaml;
using Audiotica.Core.Windows.Helpers;
namespace Audiotica.Windows.CustomTriggers
{
public class DeviceFamilyTrigger : StateTriggerBase
{
//private variables
private DeviceFamily _queriedDeviceFamily;
//Public property
public DeviceFamily DeviceFamily
{
get { return _queriedDeviceFamily; }
set
{
_queriedDeviceFamily = value;
SetActive(DeviceHelper.IsType(_queriedDeviceFamily));
}
}
}
} |
using vts.Shared.Entities.Master;
using vts.Shared.Services;
namespace vts.Shared.Repository
{
public interface IConstituencyRepository : IMasterRepository<Constituency>
{
QueryResult<Constituency> Query(QueryStandard query);
}
} |
using Sitecore.Data;
using Sitecore.Data.Fields;
using Sitecore.Xml;
using System;
using System.Collections.Generic;
using System.Xml;
namespace Sitecron.Core.Jobs.Loader
{
public class ConfigJobLoader
{
public List<SitecronJob> SiteCronConfigJobs { get; private set; }
public ConfigJobLoader()
{
this.SiteCronConfigJobs = new List<SitecronJob>();
}
public void LoadConfigJobs(XmlNode node)
{
this.SiteCronConfigJobs.Add(CreateSitecronJob(node));
}
private SitecronJob CreateSitecronJob(XmlNode node)
{
DateTime executeExactlyAtDateTime;
if (!DateTime.TryParse(XmlUtil.GetChildValue("executeExactlyAtDateTime", node), out executeExactlyAtDateTime))
executeExactlyAtDateTime = DateTime.MinValue;
//Archive after execution set to false since this is not an item.
return new SitecronJob
{
ItemId = "SiteCron Config Job " + Guid.NewGuid().ToString(),
TemplateId = ID.Null,
Name = Sitecore.Xml.XmlUtil.GetAttribute("name", node),
JobSource = "CONFIG",
JobTypeSignature = Sitecore.Xml.XmlUtil.GetChildValue("type", node),
CronExpression = Sitecore.Xml.XmlUtil.GetChildValue("cronExpression", node),
Parameters = Sitecore.Xml.XmlUtil.GetChildValue("parameters", node),
Items = Sitecore.Xml.XmlUtil.GetChildValue("items", node),
Disable = Sitecore.Xml.XmlUtil.GetChildValue("disable", node) == "1",
ArchiveAfterExecution = false,
ExecuteExactlyAtDateTime = executeExactlyAtDateTime,
LastRunUTC = string.Empty,
NextRunUTC = string.Empty,
ExecutionTime = string.Empty,
LastRunLog = string.Empty,
SitecoreJobType = Sitecore.Xml.XmlUtil.GetChildValue("sitecoreJobType", node),
SitecoreJobMethod = Sitecore.Xml.XmlUtil.GetChildValue("sitecoreJobMethod", node),
SitecoreJobName = Sitecore.Xml.XmlUtil.GetChildValue("sitecoreJobName", node),
SitecoreJobCategory = Sitecore.Xml.XmlUtil.GetChildValue("sitecoreJobCategory", node),
SitecoreJobSiteName = Sitecore.Xml.XmlUtil.GetChildValue("sitecoreJobSiteName", node),
SitecoreJobPriority = Sitecore.Xml.XmlUtil.GetChildValue("sitecoreJobPriority", node),
SitecoreScheduleJob = Sitecore.Xml.XmlUtil.GetChildValue("sitecoreScheduleJob", node),
MinionFullName = Sitecore.Xml.XmlUtil.GetChildValue("minionFullName", node),
EnvironmentName = Sitecore.Xml.XmlUtil.GetChildValue("environmentName", node)
};
}
}
} |
using System;
using System.Collections.Generic;
namespace mcc.Util
{
public static class Timer
{
private static Dictionary<string, DateTime> _timers = new Dictionary<string, DateTime>();
public static void Start(string name)
{
_timers.Remove(name);
_timers.Add(name, DateTime.UtcNow);
}
public static TimeSpan End(string name)
{
return DateTime.UtcNow - _timers[name];
}
}
}
|
using System;
using XzySocketBase;
namespace XzySocketServer
{
/// <summary>
/// socket service interface.
/// </summary>
/// <typeparam name="TMessage"></typeparam>
public interface ISocketService<TMessage> where TMessage : class, Messaging.IMessage
{
/// <summary>
/// 当建立socket连接时,会调用此方法
/// </summary>
/// <param name="connection"></param>
void OnConnected(IConnection connection);
/// <summary>
/// 发送回调
/// </summary>
/// <param name="connection"></param>
/// <param name="packet"></param>
/// <param name="isSuccess"></param>
void OnSendCallback(IConnection connection, Packet packet, bool isSuccess);
/// <summary>
/// 当接收到客户端新消息时,会调用此方法.
/// </summary>
/// <param name="connection"></param>
/// <param name="message"></param>
void OnReceived(IConnection connection, TMessage message);
/// <summary>
/// 当socket连接断开时,会调用此方法
/// </summary>
/// <param name="connection"></param>
/// <param name="ex"></param>
void OnDisconnected(IConnection connection, Exception ex);
/// <summary>
/// 当发生异常时,会调用此方法
/// </summary>
/// <param name="connection"></param>
/// <param name="ex"></param>
void OnException(IConnection connection, Exception ex);
}
} |
using Grpc.Net.Client;
using IdentityClient.Protos;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace TestGrpcClient
{
class Program
{
static async Task Main(string[] args)
{
var grpcChannel = GrpcChannel.ForAddress("http://localhost:7101/");
var client = new User.UserClient(grpcChannel);
//Get all users
Console.WriteLine("All users: ");
var users = await GetUsers(client);
foreach (var user in users)
Console.WriteLine(user);
Console.WriteLine();
//Get user info by ID
Console.WriteLine("User info: ");
var userInfo = await GetUserById(client, users.FirstOrDefault()?.Id);
Console.WriteLine(userInfo);
}
static async Task<List<UserReply>> GetUsers(User.UserClient client)
{
List<UserReply> users = new();
using var clientData = client.GetUsers(new UsersRequest());
while (await clientData.ResponseStream.MoveNext(new System.Threading.CancellationToken()))
{
var user = clientData.ResponseStream.Current;
users.Add(user);
}
return users;
}
static async Task<UserReply> GetUserById(User.UserClient client, string userId)
{
return await client.GetUserByIdAsync(new UserRequest { Id = userId });
}
}
}
|
// *** WARNING: this file was generated by test. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Example
{
public static class DoFoo
{
public static Task InvokeAsync(DoFooArgs args, InvokeOptions? options = null)
=> Pulumi.Deployment.Instance.InvokeAsync("example::doFoo", args ?? new DoFooArgs(), options.WithVersion());
}
public sealed class DoFooArgs : Pulumi.InvokeArgs
{
[Input("foo", required: true)]
public Inputs.Foo Foo { get; set; } = null!;
public DoFooArgs()
{
}
}
}
|
namespace CoreLibrary.Ports.Out;
using CoreLibrary.Entity;
public interface IRepository
{
Task<int> Count();
Task Truncate();
Task<Friend> AddFriend(string lastName, string firstName, string? knownAs);
Task<Friend?> GetFriend(string id);
Task<List<Friend>> FindFriendOnLastName(string lastName);
}
|
using System.IO;
using System.Linq;
using Parsec.Helpers;
namespace Parsec.Shaiya.Data
{
public static class DataBuilder
{
/// <summary>
/// The path to the data directory (both data.sah and data.saf)
/// </summary>
private static string _path;
/// <summary>
/// The binary write instance for the saf file
/// </summary>
private static BinaryWriter _safWriter;
/// <summary>
/// The total file count
/// </summary>
private static int _fileCount;
/// <summary>
/// Creates both sah and saf files based on the data inside a directory
/// </summary>
/// <param name="inputFolderPath">Path to the base directory that holds the data to be read</param>
/// <param name="outputFolderPath">Path of the file to be created</param>
public static Data CreateFromDirectory(string inputFolderPath, string outputFolderPath)
{
try
{
_path = inputFolderPath;
if (!FileHelper.DirectoryExists(inputFolderPath))
throw new DirectoryNotFoundException();
// Create output folder
FileHelper.CreateDirectory(outputFolderPath);
var outputDirectoryInfo = new DirectoryInfo(outputFolderPath);
var safPath = Path.Combine(outputFolderPath, $"{outputDirectoryInfo.Name}.saf");
var sahPath = Path.Combine(outputFolderPath, $"{outputDirectoryInfo.Name}.sah");
// Create binary writer instance to write saf file
_safWriter = new BinaryWriter(File.OpenWrite(safPath));
// Create root folder
var rootFolder = new SFolder(null);
// Read data folder
ReadFolderFromDirectory(rootFolder, inputFolderPath);
// Create sah instance
var sah = new Sah(inputFolderPath, rootFolder, _fileCount);
// Write sah
sah.Write(sahPath);
var saf = new Saf(safPath);
var data = new Data(sah, saf);
return data;
}
finally
{
// Cleanup
_safWriter?.Dispose();
_safWriter = null;
_path = "";
_fileCount = 0;
}
}
/// <summary>
/// Reads a folder's content and assigns it to a <see cref="SFolder"/> instance
/// </summary>
/// <param name="folder">The <see cref="SFolder"/> instance</param>
/// <param name="directoryPath">Directory path</param>
private static void ReadFolderFromDirectory(SFolder folder, string directoryPath)
{
ReadFilesFromDirectory(folder, directoryPath);
var subfolders = Directory.GetDirectories(directoryPath).Select(sf => new DirectoryInfo(sf).Name);
foreach (var subfolder in subfolders)
{
var shaiyaFolder = new SFolder(folder)
{
Name = subfolder,
ParentFolder = folder
};
folder.AddSubfolder(shaiyaFolder);
// Recursively read subfolders
ReadFolderFromDirectory(shaiyaFolder, Path.Combine(directoryPath, subfolder));
}
}
/// <summary>
/// Reads the files inside a directory and adds them to a ShaiyaFolder instance
/// </summary>
/// <param name="folder">The shaiya folder instance</param>
/// <param name="directoryPath">Directory path</param>
private static void ReadFilesFromDirectory(SFolder folder, string directoryPath)
{
// Read all files in directory
var files = Directory.GetFiles(directoryPath).Select(Path.GetFileName);
foreach (var file in files)
{
var filePath = Path.Combine(directoryPath, file);
var fileStream = File.OpenRead(filePath);
var shaiyaFile = new SFile(folder)
{
Name = file,
Length = (int)fileStream.Length,
//RelativePath = Path.Combine(folder.RelativePath, file)
};
// Write file in saf file
WriteFile(shaiyaFile);
folder.AddFile(shaiyaFile);
// Increase file count
_fileCount++;
}
}
/// <summary>
/// Appends a file at the end of the saf file
/// </summary>
/// <param name="file"><see cref="SFile"/> instance to add</param>
private static void WriteFile(SFile file)
{
// Write file offset
file.Offset = _safWriter.BaseStream.Position;
// Read file bytes
var fileBytes = File.ReadAllBytes(Path.Combine(_path, file.RelativePath));
// Store file bytes in saf
_safWriter.Write(fileBytes);
}
}
}
|
// $Id: MACAddress.cs,v 1.1.1.1 2007/07/03 10:15:18 tamirgal Exp $
/// <summary>************************************************************************
/// Copyright (C) 2001, Patrick Charles and Jonas Lehmann *
/// Distributed under the Mozilla Public License *
/// http://www.mozilla.org/NPL/MPL-1.1.txt *
/// *************************************************************************
/// </summary>
using System;
//UPGRADE_TODO: The type 'Tamir.IPLib.Packets.Util.ArrayHelper' could not be found. If it was not included in the conversion, there may be compiler issues. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1262'"
using ArrayHelper = Tamir.IPLib.Packets.Util.ArrayHelper;
//UPGRADE_TODO: The type 'Tamir.IPLib.Packets.Util.HexHelper' could not be found. If it was not included in the conversion, there may be compiler issues. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1262'"
using HexHelper = Tamir.IPLib.Packets.Util.HexHelper;
namespace Tamir.IPLib.Packets
{
/// <summary> MAC address.
/// <p>
/// This class doesn't yet store MAC addresses. Only a utility method
/// to extract a MAC address from a big-endian byte array is implemented.
///
/// </summary>
/// <author> Patrick Charles and Jonas Lehmann
/// </author>
/// <version> $Revision: 1.1.1.1 $
/// </version>
/// <lastModifiedBy> $Author: tamirgal $ </lastModifiedBy>
/// <lastModifiedAt> $Date: 2007/07/03 10:15:18 $ </lastModifiedAt>
public class MACAddress
{
/// <summary> Extract a MAC address from an array of bytes.</summary>
/// <param name="offset">the offset of the address data from the start of the
/// packet.
/// </param>
/// <param name="bytes">an array of bytes containing at least one MAC address.
/// </param>
public static System.String extract(int offset, byte[] bytes)
{
System.Text.StringBuilder sa = new System.Text.StringBuilder();
for (int i = offset; i < offset + WIDTH; i++)
{
sa.Append(HexHelper.toString(bytes[i]));
if (i != offset + WIDTH - 1)
sa.Append(':');
}
return sa.ToString();
}
public static System.String extract(long mac)
{
byte[] bytes = new byte[6];
ArrayHelper.insertLong(bytes, mac, 0, 6);
return extract(0, bytes);
}
public static void insert(System.String mac, byte[] bytes, int offset)
{
mac = mac.Replace(":", "").Replace("-","");
long l = System.Convert.ToInt64(mac, 16);
ArrayHelper.insertLong(bytes, l, offset, 6);
}
public static void insert(System.String mac, int offset, byte[] bytes)
{
mac = mac.Replace(":", "").Replace("-","");
long l = System.Convert.ToInt64(mac, 16);
ArrayHelper.insertLong(bytes, l, offset, 6);
}
/// <summary> Generate a random MAC address.</summary>
public static long random()
{
//UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
return (long)(0xffffffffffffL * SupportClass.Random.NextDouble());
}
/// <summary> The width in bytes of a MAC address.</summary>
public const int WIDTH = 6;
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace Alexa.NET.SkillFlow.CoreExtensions
{
public class Buy:SceneInstruction
{
public override string Type => nameof(Buy);
public string Item { get; set; }
public string SuccessScene { get; set; }
public string FailureScene { get; set; }
public string DeclinedScene { get; set; }
public string AlreadyPurchasedScene { get; set; }
public string ErrorScene { get; set; }
}
}
|
using System;
namespace Kros.Data
{
/// <summary>
/// Interface for generating IDs for records in database. In general, IDs are just sequential numbers.
/// </summary>
/// <remarks>Usually one generator generates IDs for just one table.</remarks>
/// <seealso cref="SqlServer.SqlServerIdGenerator"/>
/// <example>
/// <code language="cs" source="..\Examples\Kros.Utils\IdGeneratorExamples.cs" region="IdGeneratorFactory"/>
/// </example>
public interface IIdGenerator
: IDisposable
{
/// <summary>
/// Returns next ID.
/// </summary>
/// <returns>
/// Unique ID for record in data table.
/// </returns>
int GetNext();
}
}
|
using System.Collections.Generic;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Confluent.Kafka;
using Next.Abstractions.Bus.Transport;
using Next.Abstractions.Serialization.Json;
using Next.Bus.Kafka.Configuration;
namespace Next.Bus.Kafka.Transport
{
public class KafkaProducerTransport: IOutboundTransport
{
private readonly ITopicNamingStrategy _topicNamingStrategy;
private readonly IJsonSerializer _jsonSerializer;
private readonly string _bootstrapServers;
private readonly string _clientId;
private readonly IProducer<string, string> _producer;
public KafkaProducerTransport(
ITopicNamingStrategy topicNamingStrategy,
IJsonSerializer jsonSerializer,
string bootstrapServers,
string clientId)
{
_topicNamingStrategy = topicNamingStrategy;
_jsonSerializer = jsonSerializer;
_bootstrapServers = bootstrapServers;
_clientId = clientId;
_producer = InitializeProducer();
}
public async Task Send(TransportMessage message)
{
var topic = _topicNamingStrategy.GetProducerTopic(message);
var kafkaMessage = CreateKafkaMessage(message);
await _producer.ProduceAsync(
topic,
kafkaMessage);
}
public async Task SendMultiple(IEnumerable<TransportMessage> messages)
{
foreach (var message in messages)
{
await Send(message);
}
}
private IProducer<string, string> InitializeProducer()
{
var config = new ProducerConfig()
{
BootstrapServers = _bootstrapServers,
ClientId = GetClientId(),
};
var builder = new ProducerBuilder<string, string>(config);
return builder.Build();
}
private string GetClientId()
{
return _clientId ?? $"{KafkaConfiguration.NameSpace}-{Dns.GetHostName().ToLower()}-producer";
}
private Message<string, string> CreateKafkaMessage(TransportMessage message)
{
var headers = new Headers();
foreach (var (key, value) in message.Headers)
{
headers.Add(key, Encoding.UTF8.GetBytes(value));
}
return new Message<string, string>
{
Key = message.Id,
Headers = headers,
Value = _jsonSerializer.Serialize(message)
};
}
}
} |
using System;
using System.Runtime.InteropServices;
namespace UHP.Lib
{
public static class RawDataSerialization
{
public static T RawDeserialize<T>(byte[] rawData) where T : struct
{
int rawsize = Marshal.SizeOf(typeof(T));
IntPtr buffer = Marshal.AllocHGlobal(rawsize);
Marshal.Copy(rawData, 0, buffer, rawsize);
T obj = (T)Marshal.PtrToStructure(buffer, typeof(T));
Marshal.FreeHGlobal(buffer);
return obj;
}
public static byte[] RawSerialize<T>(T value) where T : struct
{
int rawSize = Marshal.SizeOf(value);
IntPtr buffer = Marshal.AllocHGlobal(rawSize);
Marshal.StructureToPtr(value, buffer, false);
byte[] rawDatas = new byte[rawSize];
Marshal.Copy(buffer, rawDatas, 0, rawSize);
Marshal.FreeHGlobal(buffer);
return rawDatas;
}
public static void Send<T>(this Protocol protocol, T value) where T : struct
{
var data = RawSerialize(value);
protocol.Send(data);
}
public static T ReceiveAs<T>(this Protocol protocol) where T : struct
{
var data = protocol.Receive();
return RawDeserialize<T>(data.Buffer);
}
}
}
|
namespace JB.Collections.Reactive
{
public interface IObservableCollectionChange<out T>
{
/// <summary>
/// Gets the type of the change.
/// </summary>
/// <value>
/// The type of the change.
/// </value>
ObservableCollectionChangeType ChangeType { get; }
/// <summary>
/// Gets the item that was added, changed or removed.
/// </summary>
/// <value>
/// The affected item, if any.
/// </value>
T Item { get; }
}
} |
namespace NewsSystem.Data.UnitOfWork
{
using System;
using System.Collections.Generic;
using NewsSystem.Data.Common.Models;
using NewsSystem.Data.Common.Repository;
using NewsSystem.Data.Models;
using NewsSystem.Data.Repositories;
public class NewsSystemData : INewsSystemData
{
private IDictionary<Type, object> repositories;
public NewsSystemData(INewsSystemDbContext context)
{
this.Context = context;
this.repositories = new Dictionary<Type, object>();
}
public INewsSystemDbContext Context { get; set; }
public IRepository<User> Users
{
get
{
return this.GetRepository<User>();
}
}
public IRepository<Article> Articles
{
get
{
return this.GetDeletableEntityRepository<Article>();
}
}
public IRepository<VisitorIp> VisitorsIps
{
get
{
return GetRepository<VisitorIp>();
}
}
public IRepository<Theme> Themes
{
get
{
return this.GetDeletableEntityRepository<Theme>();
}
}
public IRepository<Album> Albums
{
get
{
return this.GetDeletableEntityRepository<Album>();
}
}
public IRepository<Category> Categories
{
get
{
return this.GetDeletableEntityRepository<Category>();
}
}
public IRepository<Tag> Tags
{
get
{
return this.GetDeletableEntityRepository<Tag>();
}
}
public IRepository<NSImage> NSImages
{
get
{
return this.GetDeletableEntityRepository<NSImage>();
}
}
public IRepository<Question> Questions
{
get
{
return this.GetDeletableEntityRepository<Question>();
}
}
public IRepository<Answer> Answers
{
get
{
return this.GetDeletableEntityRepository<Answer>();
}
}
public IRepository<Comment> Comments
{
get
{
return this.GetDeletableEntityRepository<Comment>();
}
}
public IRepository<Vote> Votes
{
get
{
return GetRepository<Vote>();
}
}
public int SaveChanges()
{
return this.Context.SaveChanges();
}
private IRepository<T> GetRepository<T>() where T : class
{
if (!this.repositories.ContainsKey(typeof(T)))
{
var type = typeof(GenericRepository<T>);
this.repositories.Add(typeof(T), Activator.CreateInstance(type, this.Context));
}
return (IRepository<T>)this.repositories[typeof(T)];
}
private IDeletableEntityRepository<T> GetDeletableEntityRepository<T>() where T : class, IDeletableEntity
{
var typeOfRepository = typeof(T);
if (!this.repositories.ContainsKey(typeOfRepository))
{
var newRepository = Activator.CreateInstance(typeof(DeletableEntityRepository<T>), this.Context);
this.repositories.Add(typeOfRepository, newRepository);
}
return (IDeletableEntityRepository<T>)this.repositories[typeOfRepository];
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (this.Context != null)
{
this.Context.Dispose();
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace Nanook.NKit
{
internal class IsoReader : IReader
{
public bool EncryptWiiPartitions { get; set; }
private ILog _log;
public void Construct(ILog log)
{
_log = log;
}
public bool VerifyIsWrite { get; set; }
public bool RequireVerifyCrc { get; set; }
public bool RequireValidationCrc { get; set; }
public void Read(Context ctx, NStream inStream, Stream outStream, Coordinator pc)
{
NCrc crc = new NCrc();
try
{
CryptoStream target = new CryptoStream(outStream, crc, CryptoStreamMode.Write);
uint outputCrc = 0;
if (inStream.IsNkit || inStream.IsGameCube || !EncryptWiiPartitions)
{
pc.ReaderCheckPoint1PreWrite(null, 0); //size that we will output from this read
if (inStream.HeaderRead)
{
target.Write(inStream.DiscHeader.Data, 0, (int)inStream.DiscHeader.Size); //write the header
inStream.Copy(target, inStream.Length - inStream.DiscHeader.Size);
}
else
inStream.Copy(target, inStream.Length);
}
else
{
WiiDiscHeaderSection hdr = null;
using (NDisc disc = new NDisc(_log, inStream))
{
foreach (IWiiDiscSection s in disc.EnumerateSections(inStream.Length)) //ctx.ImageLength
{
if (s is WiiDiscHeaderSection)
{
hdr = (WiiDiscHeaderSection)s;
target.Write(hdr.Data, 0, hdr.Data.Length); //write the header
pc.ReaderCheckPoint1PreWrite(null, 0); //size that we will output from this read //ctx.ImageLength
}
else if (s is WiiPartitionSection)
{
WiiPartitionSection ps = (WiiPartitionSection)s;
//bool lengthChanged = inStream.CheckLength(ps.DiscOffset, ps.Header.PartitionSize);
target.Write(ps.Header.Data, 0, (int)ps.Header.Size);
foreach (WiiPartitionGroupSection pg in ps.Sections)
target.Write(pg.Encrypted, 0, (int)pg.Size);
}
else if (s is WiiFillerSection)
{
WiiFillerSection fs = (WiiFillerSection)s;
if (fs.Size != 0)
{
foreach (WiiFillerSectionItem item in ((WiiFillerSection)s).Sections)
target.Write(item.Data, 0, (int)item.Size);
}
}
}
}
}
crc.Snapshot("iso");
if (inStream.IsNkit)
outputCrc = inStream.DiscHeader.ReadUInt32B(0x208); //assume source nkit crc is correct
else
outputCrc = crc.FullCrc(true);
pc.ReaderCheckPoint2Complete(crc, false, outputCrc, outputCrc, this.VerifyIsWrite, null, null);
pc.ReaderCheckPoint3Complete();
}
catch (Exception ex)
{
throw pc.SetReaderException(ex, "IsoReader.Read - Read Image"); //don't let the writer lock
}
}
private string friendly(string text)
{
string f = text.Trim('\0') ?? "<NULL>";
//if (Regex.IsMatch(f, "[^<>A-Z0-9-_+=]", RegexOptions.IgnoreCase))
// f = "Hex-" + BitConverter.ToString(Encoding.ASCII.GetBytes(f)).Replace("-", "");
return f;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Caliburn.Micro;
using ShvTasker.Models;
namespace ShvTasker.ViewModels
{
public class MouseItemViewModel : Screen, IAddItemPage
{
public bool LeftBtn
{
get => leftBtn;
set
{
leftBtn = value;
NotifyOfPropertyChange(() => LeftBtn);
}
}
public Entry FetchEntry()
{
if (entry == null)
{
entry = new Entry();
}
entry.MouseBtn = LeftBtn ? MouseBtns.Left : MouseBtns.Right;
return entry;
}
private Entry entry;
private bool leftBtn = true;
public void Init(Entry e)
{
this.entry = e;
LeftBtn = e.MouseBtn == MouseBtns.Left;
}
}
} |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using HaveIBeenPwned.PwnedPasswords.Models;
namespace HaveIBeenPwned.PwnedPasswords.Abstractions
{
public interface ITableStorage
{
Task<PwnedPasswordsTransaction> InsertAppendDataAsync(string subscriptionId, CancellationToken cancellationToken = default);
Task<bool> IsTransactionConfirmedAsync(string subscriptionId, string transactionId, CancellationToken cancellationToken = default);
Task<List<PwnedPasswordsIngestionValue>> GetTransactionValuesAsync(string subscriptionId, string transactionId, CancellationToken cancellationToken = default);
Task<bool> ConfirmAppendDataAsync(string subscriptionId, PwnedPasswordsTransaction transaction, CancellationToken cancellationToken = default);
Task<bool> AddOrIncrementHashEntry(string subscriptionId, string transactionId, PwnedPasswordsIngestionValue value, CancellationToken cancellationToken = default);
Task<List<string>> GetModifiedHashPrefixes(CancellationToken cancellationToken = default);
Task MarkHashPrefixAsModified(string prefix, CancellationToken cancellationToken = default);
}
}
|
using GifImageView.FormsPlugin.Abstractions;
using System;
using Xamarin.Forms;
using GifImageView.FormsPlugin.Android;
using Xamarin.Forms.Platform.Android;
using System.Net.Http;
using System.Threading;
using System.IO;
using System.Threading.Tasks;
[assembly: ExportRenderer(typeof(GifImageViewControl), typeof(GifImageViewRenderer))]
namespace GifImageView.FormsPlugin.Android
{
/// <summary>
/// GifImageView Renderer
/// </summary>
public class GifImageViewRenderer : ViewRenderer<Image, Felipecsl.GifImageViewLibrary.GifImageView>
{
/// <summary>
/// Used for registration with dependency service
/// </summary>
public static void Init() { }
Felipecsl.GifImageViewLibrary.GifImageView gif;
protected override void OnElementChanged(ElementChangedEventArgs<Image> e)
{
base.OnElementChanged(e);
if (e.OldElement != null || Element == null)
return;
gif = new Felipecsl.GifImageViewLibrary.GifImageView(Forms.Context);
SetNativeControl(gif);
}
static async Task<byte[]> GetBytesFromStreamAsync(Stream stream)
{
using (stream)
{
if (stream == null || stream.Length == 0)
return null;
var bytes = new byte[stream.Length];
if (await stream.ReadAsync(bytes, 0, (int)stream.Length) > 0)
return bytes;
}
return null;
}
bool loaded;
protected override async void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (e.PropertyName == Image.SourceProperty.PropertyName)
{
byte[] bytes = null;
var s = Element.Source;
if (s is UriImageSource)
{
using (var client = new HttpClient())
bytes = await client.GetByteArrayAsync(((UriImageSource)s).Uri);
}
else if (s is StreamImageSource)
{
bytes = await GetBytesFromStreamAsync(await ((StreamImageSource)s).Stream(default(CancellationToken)));
}
else if (s is FileImageSource)
{
bytes = await GetBytesFromStreamAsync(File.OpenRead(((FileImageSource)s).File));
}
if (bytes == null)
return;
try
{
gif.StopAnimation();
gif.SetBytes(bytes);
gif.StartAnimation();
}
catch(Exception ex)
{
System.Diagnostics.Debug.WriteLine("Unable to load gif: " + ex.Message);
}
}
}
}
} |
namespace KenneyAsteroids.Engine.Rules
{
public interface IGameRuleSystem : IUpdatable
{
}
}
|
namespace Contract
{
public class AudioDemuxJob : FFmpegJob
{
public override JobType Type => JobType.AudioDemux;
}
}
|
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using ProApiLibrary.Api.Queries;
namespace ProApiLibraryTests.TestCases.ApiTests.QueryTests
{
/// <summary>
/// Copyright @2015 Whitepages, Inc.
/// </summary>
[TestClass]
public class QueryTest
{
[TestMethod]
public void ItShouldPrintAHumanReadablePersonQuery()
{
var q = new PersonQuery("Amelia", "Jessica", "Pond", "Seattle", "WA", "98101");
var s = q.ToString();
Console.Out.WriteLine(s);
Assert.IsTrue(s.StartsWith("PersonQuery"));
Assert.IsTrue(s.Contains("Amelia"));
Assert.IsTrue(s.Contains("Jessica"));
Assert.IsTrue(s.Contains("Pond"));
Assert.IsTrue(s.Contains("Seattle"));
Assert.IsTrue(s.Contains("WA"));
Assert.IsTrue(s.Contains("98101"));
}
[TestMethod]
public void ItShouldPrintAHumanReadableBusinessQuery()
{
var q = new BusinessQuery("Whitepages") {City = "Seattle", StateCode = "WA"};
var s = q.ToString();
Console.Out.WriteLine(s);
Assert.IsTrue(s.StartsWith("BusinessQuery"));
Assert.IsTrue(s.Contains("Whitepages"));
Assert.IsTrue(s.Contains("Seattle"));
Assert.IsTrue(s.Contains("WA"));
}
[TestMethod]
public void ItShouldPrintAHumanReadablePhoneQuery()
{
var q = new PhoneQuery("2065551234");
var s = q.ToString();
Console.Out.WriteLine(s);
Assert.IsTrue(s.StartsWith("PhoneQuery"));
Assert.IsTrue(s.Contains("2065551234"));
}
[TestMethod]
public void ItShouldPrintAHumanReadableLocationQuery()
{
var q = new LocationQuery("1301 5th Ave", "Ste 1600", "Seattle", "WA", "98101");
var s = q.ToString();
Console.Out.WriteLine(s);
Assert.IsTrue(s.StartsWith("LocationQuery"));
Assert.IsTrue(s.Contains("1301 5th Ave"));Assert.IsTrue(s.Contains("Ste 1600"));
Assert.IsTrue(s.Contains("Seattle"));
Assert.IsTrue(s.Contains("WA"));
Assert.IsTrue(s.Contains("98101"));
}
}
}
|
using UnityEngine;
namespace FPController
{
/// <summary>
/// Preset for First Person Controller.
/// </summary>
[CreateAssetMenu(fileName = "FirsPersonPreset", menuName = "FP Preset", order = 1500)]
public class FirstPersonPreset : ScriptableObject
{
/// <summary>
/// Name, set to game object on reset.
/// </summary>
public string Name = "Player";
/// <summary>
/// Tag, set to game object on reset.
/// TODO: Check if Tag is found in unity Tags.
/// </summary>
public string Tag = "Player";
/// <summary>
/// Charachters target walk speed.
/// </summary>
public float WalkSpeed = 5;
/// <summary>
/// Charachters target run speed (walk * run multiplier).
/// </summary>
public float RunMultiplier = 1.3f;
/// <summary>
/// Charachters target crouching speed (walk * crouch multiplier).
/// </summary>
public float CrouchMultiplier = 0.6f;
/// <summary>
/// Force added to make rigidbody jump.
/// </summary>
public float JumpForce = 5f;
/// <summary>
/// Charachters (Capsule Colliders) radius.
/// </summary>
public float Radius = 0.35f;
/// <summary>
/// Charachters (Capsule Colliders) height.
/// Used for standing after crouching.
/// </summary>
public float Height = 1.75f;
/// <summary>
/// Maximum angle for slope.
/// <see cref="FirstPersonController.UpdateFriction(Vector3)"/>
/// </summary>
public float MaxSlopeAngle = 45f;
/// <summary>
/// Physics Material Max Friction.
/// Used when on slopes under max angle.
/// </summary>
public float MaxFriction = 20f;
}
} |
#nullable enable
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Utils;
using Utils.Storage;
using Wellcome.Dds.Common;
namespace Wellcome.Dds.Server.Controllers
{
public class Helpers
{
private readonly IStorage storage;
private readonly DdsOptions ddsOptions;
public Helpers(
IStorage storage,
IOptions<DdsOptions> options)
{
this.storage = storage;
ddsOptions = options.Value;
}
/// <summary>
/// We don't have separate S3 buckets with IIIF content that uses localhost paths.
/// And we don't want to do that, you'd need a lot of test content.
/// This optionally allows the locally run Dds.Server to rewrite the LinedDataDomain in the response.
/// This is obviously slower and inefficient, but it only does it if an overriding domain is provided.
/// It allows localhost to create content in the test S3 bucket, but serve it with correct paths.
///
/// Add an extra local appSetting to the Dds section:
///
/// "RewriteDomainLinksTo": "http://localhost:8084",
/// </summary>
/// <param name="container"></param>
/// <param name="path"></param>
/// <param name="contentType"></param>
/// <param name="controller"></param>
/// <returns></returns>
public async Task<IActionResult> ServeIIIFContent(string container, string path, string contentType,
ControllerBase controller)
{
var stream = await storage.GetStream(container, path);
if (stream == null)
{
return controller.NotFound($"No IIIF resource found for {path}");
}
if (string.IsNullOrWhiteSpace(ddsOptions.RewriteDomainLinksTo))
{
// This is the efficient way to return the response
return controller.File(stream, contentType);
}
// This is an inefficient method but allows us to manipulate the response.
using var reader = new StreamReader(stream, Encoding.UTF8);
string raw = await reader.ReadToEndAsync();
// This is OK but we want to leave the DLCS links intact!
// string rewritten = raw.Replace(ddsOptions.LinkedDataDomain, ddsOptions.RewriteDomainLinksTo);
// https://iiif-test\.wellcomecollection\.org/(?<!image|thumbs|pdf|av|auth)/(.*)
var pattern = GetRegexPattern(ddsOptions.LinkedDataDomain);
var placeholder = "__PLACEHOLDER__";
var pass1 = Regex.Replace(raw, pattern, $"\"{placeholder}/$1/$2\"");
var pass2 = pass1.Replace(ddsOptions.LinkedDataDomain, ddsOptions.RewriteDomainLinksTo);
var rewritten = pass2.Replace(placeholder, ddsOptions.LinkedDataDomain);
return controller.Content(rewritten, contentType);
}
private string GetRegexPattern(string domainPart)
{
var pattern = "\\\"" + domainPart.Replace(".", "\\.");
pattern += "/(image|thumbs|pdf|av|auth)/([^\"]*)\\\"";
return pattern;
}
public async Task<JObject?> LoadAsJson(string container, string path)
{
var stream = await storage.GetStream(container, path);
if(stream == null)
{
return null;
}
using StreamReader reader = new(stream);
using JsonTextReader jsonReader = new(reader);
// In the IIIF context, this should ALWAYS come out as JObject.
return new JsonSerializer().Deserialize(jsonReader) as JObject;
}
}
} |
namespace KnightBus.Messages
{
/// <summary>
/// Enables <see cref="ICommand"/> to have large attachments.
/// Both sender and receiver must register an implementation for transporting attachments.
/// </summary>
public interface ICommandWithAttachment
{
IMessageAttachment Attachment { get; set; }
}
} |
using System;
namespace ProtoBuf.Meta
{
/// <summary>
/// Indiate the variant of the protobuf .proto DSL syntax to use
/// </summary>
public enum ProtoSyntax
{
/// <summary>
/// Use the global default
/// </summary>
Default = -1,
/// <summary>
/// https://developers.google.com/protocol-buffers/docs/proto
/// </summary>
Proto2 = 0,
/// <summary>
/// https://developers.google.com/protocol-buffers/docs/proto3
/// </summary>
Proto3 = 1,
}
} |
using Microsoft.EntityFrameworkCore.Migrations;
namespace TaskTronic.Statistics.Data.Migrations
{
public partial class InitialDatabase : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "FolderViews",
columns: table => new
{
FolderViewId = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
FolderId = table.Column<int>(nullable: false),
UserId = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_FolderViews", x => x.FolderViewId);
});
migrationBuilder.CreateTable(
name: "Statistics",
columns: table => new
{
StatisticsId = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
TotalFolders = table.Column<int>(nullable: false),
TotalFiles = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Statistics", x => x.StatisticsId);
});
migrationBuilder.CreateIndex(
name: "IX_FolderViews_FolderId",
table: "FolderViews",
column: "FolderId");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "FolderViews");
migrationBuilder.DropTable(
name: "Statistics");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace KapheinSharp
{
public class FunctionToComparaerAdapter<T>
: IComparer<T>
{
public FunctionToComparaerAdapter(
Func<T, T, int> func
)
{
if(func == null) {
throw new ArgumentNullException("null");
}
func_ = func;
}
public FunctionToComparaerAdapter(
FunctionToComparaerAdapter<T> src
)
: this(src.func_)
{
}
public int Compare(
T x
, T y
)
{
return func_.Invoke(x, y);
}
private Func<T, T, int> func_;
}
}
|
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using FuelSDKIntegration.Structures;
//-----------------------------------------------------------------
/*
PUBLIC INTERFACE
*/
//-----------------------------------------------------------------
public partial class FuelIgnite : MonoBehaviour
{
//--------------------------------------------------------------------
/*
Returns a sorted list of events
The top element is the most relevant event
*/
//--------------------------------------------------------------------
public List<IgniteEvent> GetActiveEventList {
get {
#if NOT_TESTBED
mIgniteEventList = TestFuelSDK.GetTestEventList();
#endif
if( mIgniteEventList == null || mIgniteEventList.Count == 0 ) {
return null;
}
return mIgniteEventList;
}
}
public IgniteEvent GetActiveEvent(){
#if NOT_TESTBED
mIgniteEventList = TestFuelSDK.GetTestEventList();
#endif
if (mIgniteEventList.Count > 0) {
return mIgniteEventList [0];
}
return null;
}
public int GetNumberOfActiveEvents()
{
if (mIgniteEventList == null) {
return 0;
}
return mIgniteEventList.Count;
}
public void GetEventsWithTags()
{
ResetEventsRecieved ();
List<object> eventFiltertags = GetEventFilterTags();
FuelSDK.GetEvents (eventFiltertags);
List<object> sampleEventFiltertags = GetSampleEventFilterTags();
FuelSDK.GetSampleEvents (sampleEventFiltertags);
StartCreateEventListCoroutine ();
}
//Get Events Coroutine
private IEnumerator getEventsCoroutine;
public void StartGetEventsCorroutine()
{
getEventsCoroutine = WaitAndGetEvents (1.0f);
StartCoroutine (getEventsCoroutine);
}
public IEnumerator WaitAndGetEvents(float waitTime)
{
yield return new WaitForSeconds(waitTime);
GetEventsWithTags ();
}
//Create Event List Coroutine
private IEnumerator createEventListCoroutine;
public void StartCreateEventListCoroutine()
{
createEventListCoroutine = createEventList ();
StartCoroutine (createEventListCoroutine);
}
public IEnumerator createEventList()
{
while( mIgniteEventsRecieved == false ){
yield return null;
}
while( mIgniteSampleEventsRecieved == false ){
yield return null;
}
FactorInSampleEvents();
CreateSortedEventList ();
ResetEventsRecieved ();
}
//--------------------------------------------------------------------
/*
Request Server (or cache) ignite data
*/
//--------------------------------------------------------------------
public void RequestEventData()
{
WaitAndGetEvents (0f);
}
public void RequestMissionEventData(string MissionId)
{
FuelSDK.GetMission(MissionId);
}
public bool RequestAllMissionEventData()
{
if( mIgniteEventsDictionary != null ) {
foreach( IgniteEvent igniteEvent in mIgniteEventsDictionary.Values ) {
RequestMissionEventData (igniteEvent.Id);
}
return true;
}
return false;
}
} |
using System.Collections.Generic;
namespace Mondop.CodeDom
{
public class CodeTypeDeclaration: CodeExpression
{
public ScopeIdentifier Scope { get; set; } = ScopeIdentifier.Public;
public string Name { get; set; }
public List<AttributeReference> Attributes { get; set; } = new List<AttributeReference>();
}
}
|
// nRed Unity Mobile Utilities
// Copyright (c) nRed-kelta. For terms of use, see
// https://github.com/nRed-kelta/UnityMobileUtilities
using System.Collections;
using System.Collections.Generic;
namespace nRed.CollectionUtil
{
public static class ICollectionUtility
{
public static void SafeClear(this IList self)
{
if(self!=null)
self.Clear();
}
public static void SafeClear(this IDictionary self)
{
if(self!=null)
self.Clear();
}
// Caution: Shallow copy.
public static Dictionary<K,V> Clone<K,V>(this Dictionary<K,V> self)
{
if(self==null)
return null;
Dictionary<K,V> ret = new Dictionary<K,V>( self.Count );
var enm = self.GetEnumerator();
while( enm.MoveNext() )
{
ret[enm.Current.Key] = enm.Current.Value;
}
return ret;
}
public static bool SafeGetValue<K,V>(this Dictionary<K,V> self, K key, out V val, V defaultVal=default(V))
{
if(self==null || key==null || !self.ContainsKey(key))
{
val = defaultVal;
return false;
}
val = self[key];
return true;
}
public static bool IsAvailable<T>(this ICollection<T> self)
{
return (self!=null) && (self.Count>0);
}
public static bool InRange(this byte self, byte inclusive_min, byte exclusive_max)
{
return self>=inclusive_min && self<exclusive_max;
}
public static bool InRange(this int self, int inclusive_min, int exclusive_max)
{
return self>=inclusive_min && self<exclusive_max;
}
public static bool InRange(this float self, float inclusive_min, float exclusive_max)
{
return self>=inclusive_min && self<exclusive_max;
}
public static bool InRange(this double self, double inclusive_min, double exclusive_max)
{
return self>=inclusive_min && self<exclusive_max;
}
public static bool InRange(this long self, long inclusive_min, long exclusive_max)
{
return self>=inclusive_min && self<exclusive_max;
}
public static bool InRange(this ICollection self, int index )
{
return self!=null && index>=0 && index<self.Count;
}
}
} |
using Breeze.Sharp.Core;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
namespace Breeze.Sharp {
/// <summary>
/// Interface for the backing information for any IEntity or IComplexObject.
/// Implemented via an explicit interface.
/// </summary>
public interface IHasBackingStore {
IDictionary<String, Object> BackingStore { get; set; }
}
/// <summary>
/// Base class for both <see cref="EntityAspect"/> and <see cref="ComplexAspect"/>.
/// </summary>
public abstract class StructuralAspect {
public StructuralAspect(IStructuralObject stObj) {
_backingStore = (stObj is IHasBackingStore) ? null : new Dictionary<String, Object>();
}
#region Public/protected properties
public abstract EntityState EntityState { get; set; }
public abstract EntityVersion EntityVersion { get; internal set; }
public abstract IEnumerable<ValidationError> GetValidationErrors(String propertyPath);
public abstract StructuralType StructuralType { get; }
public bool Initialized { get; private set; }
protected abstract IStructuralObject StructuralObject { get; }
protected internal IDictionary<String, Object> BackingStore {
get {
return _backingStore ?? ((IHasBackingStore)StructuralObject).BackingStore;
}
set {
if (_backingStore != null) {
_backingStore = value;
} else {
((IHasBackingStore)StructuralObject).BackingStore = value;
}
}
}
#endregion
#region Get/Set value
protected internal Object GetRawValue(String propertyName) {
Object val = null;
BackingStore.TryGetValue(propertyName, out val);
return val;
}
protected internal void SetRawValue(string propertyName, Object value) {
BackingStore[propertyName] = value;
}
public Object GetValue(String propertyName) {
// TODO: will be different when we add property interception.
return GetRawValue(propertyName);
}
public Object GetValue(StructuralProperty prop) {
return GetValue(prop.Name);
}
public T GetValue<T>(StructuralProperty prop) {
return (T) GetRawValue(prop.Name);
}
public T GetValue<T>(String propertyName) {
return (T) GetRawValue(propertyName);
}
public Object GetValue(DataProperty property, EntityVersion version) {
if (version == EntityVersion.Default) {
version = EntityVersion;
}
Object result;
if (version == EntityVersion.Current) {
if (this.EntityVersion == EntityVersion.Proposed) {
result = GetPreproposedValue(property);
} else {
result = GetValue(property);
}
} else if (version == EntityVersion.Original) {
result = GetOriginalValue(property);
} else if (version == EntityVersion.Proposed) {
result = GetValue(property);
} else {
throw new ArgumentException("Invalid entity version");
}
if (property.IsComplexProperty) {
var co = (IComplexObject)result;
if (co.ComplexAspect.Parent == null || co.ComplexAspect.Parent != this.StructuralObject) {
co.ComplexAspect.Parent = this.StructuralObject;
co.ComplexAspect.ParentProperty = property;
}
return co;
} else {
return result;
}
}
public abstract void SetValue(String propertyName, object newValue);
protected internal abstract void SetDpValue(DataProperty dp, object newValue);
protected internal Object[] GetValues(IEnumerable<DataProperty> properties = null) {
if (properties == null) {
properties = this.StructuralType.DataProperties;
}
return properties.Select(p => this.GetValue(p)).ToArray();
}
#endregion
#region event handling
#endregion
#region Validation
public IEnumerable<ValidationError> Validate() {
ValidateInternal();
return this.GetValidationErrors(null);
}
public IEnumerable<ValidationError> ValidateProperty(StructuralProperty prop) {
var value = this.GetValue(prop);
return ValidateProperty(prop, value);
}
protected internal void ValidateInternal() {
var vc = new ValidationContext(this.StructuralObject);
vc.IsMutable = true;
// PERF:
// Not using LINQ here because we want to reuse the same
// vc property for perf reasons and this
// would cause closure issues with a linq expression unless
// we kept resolving with toList. This is actually simpler code.
var properties = this.StructuralType.Properties;
foreach (var prop in properties) {
vc.Property = prop;
vc.PropertyValue = this.GetValue(prop);
var co = vc.PropertyValue as IComplexObject;
if (co != null) {
co.ComplexAspect.ValidateInternal();
}
foreach (var vr in prop.Validators) {
var ve = ValidateCore(vr, vc);
}
}
vc.Property = null;
vc.PropertyValue = null;
foreach (var vr in this.StructuralType.Validators) {
var ve = ValidateCore(vr, vc);
}
}
// called internally by property set logic
internal IEnumerable<ValidationError> ValidateProperty(StructuralProperty prop, Object value) {
IEnumerable<ValidationError> errors = null;
var co = value as IComplexObject;
if (co != null) {
errors = co.ComplexAspect.Validate();
}
var vc = new ValidationContext(this.StructuralObject, prop, value);
var itemErrors = prop.Validators.Select(vr => ValidateCore(vr, vc)).Where(ve => ve != null);
return errors == null ? itemErrors.ToList() : errors.Concat(itemErrors).ToList();
}
// insures that validation events get fired and _validators collection is updated.
protected abstract ValidationError ValidateCore(Validator vr, ValidationContext vc);
internal virtual String GetPropertyPath(String propName) {
return propName;
}
#endregion
#region other misc
internal void Initialize() {
if (this.Initialized) return;
// will initialize base types as long as Initialize impls call base.Initialize();
this.StructuralObject.Initialize();
//// TODO: Only needed if we want to support Initializer fns in addition to
//var et = st as EntityType;
//if (et != null && et.BaseEntityType != null) {
// InitializeSo(so, et.BaseEntityType);
//}
//var initAction = st.InitializerAction;
//if (initAction != null) {
// initAction(so);
//}
this.StructuralType.ComplexProperties.ForEach(cp => {
var co = (IComplexObject) this.GetValue(cp);
co.ComplexAspect.Initialize();
});
this.Initialized = true;
}
protected void RejectChangesCore() {
if (_originalValuesMap != null) {
_originalValuesMap.ForEach(kvp => {
SetValue(kvp.Key, kvp.Value);
});
}
this.ProcessComplexProperties(co => co.ComplexAspect.RejectChangesCore());
}
protected void ProcessComplexProperties(Action<IComplexObject> action) {
this.StructuralType.ComplexProperties.ForEach(cp => {
var cos = this.GetValue(cp.Name);
if (cp.IsScalar) {
var co = (IComplexObject)cos;
action(co);
} else {
((IEnumerable)cos).Cast<IComplexObject>().ForEach(co => action(co));
}
});
}
#endregion
#region Backup version members
protected void UpdateBackupVersion(DataProperty property, Object oldValue) {
// We actually do want to track Proposed changes when Detached ( or Added) but we do not track an Original for either
if (this.EntityState.IsAdded() || this.EntityState.IsDetached()) {
if (this.EntityVersion == EntityVersion.Proposed) {
BackupProposedValueIfNeeded(property, oldValue);
}
} else {
if (this.EntityVersion == EntityVersion.Current) {
BackupOriginalValueIfNeeded(property, oldValue);
} else if (this.EntityVersion == EntityVersion.Proposed) {
// need to do both
BackupOriginalValueIfNeeded(property, oldValue);
BackupProposedValueIfNeeded(property, oldValue);
}
}
}
protected Object GetOriginalValue(DataProperty property) {
object result;
if (property.IsComplexProperty) {
var co = (IComplexObject)GetValue(property, EntityVersion.Current);
return co.ComplexAspect.GetOriginalVersion();
} else {
if (_originalValuesMap != null && _originalValuesMap.TryGetValue(property.Name, out result)) {
return result;
} else {
return GetValue(property);
}
}
}
protected Object GetPreproposedValue(DataProperty property) {
object result;
if (_preproposedValuesMap != null && _preproposedValuesMap.TryGetValue(property.Name, out result)) {
return result;
} else {
return GetValue(property);
}
}
protected internal virtual void ClearBackupVersion(EntityVersion version) {
// don't need return value;
GetBackupMap(version, true);
ProcessComplexProperties((co) => co.ComplexAspect.ClearBackupVersion(version));
}
protected internal virtual void RestoreBackupVersion( EntityVersion version) {
var backupMap = GetBackupMap(version, true);
if (backupMap != null) {
backupMap.ForEach(kvp => {
var value = kvp.Value;
var dp = this.StructuralType.GetDataProperty(kvp.Key);
if (GetValue(dp) != value) {
SetDpValue(dp, value);
OnDataPropertyRestore(dp);
}
});
}
ProcessComplexProperties((co) => co.ComplexAspect.RestoreBackupVersion(version));
}
private BackupValuesMap GetBackupMap(EntityVersion version, bool shouldClear) {
BackupValuesMap result;
if (version == EntityVersion.Original) {
result = _originalValuesMap;
if (shouldClear) _originalValuesMap = null;
} else if (version == EntityVersion.Proposed) {
result = _preproposedValuesMap;
if (shouldClear) _preproposedValuesMap = null;
} else {
throw new Exception("GetBackupMap is not implemented for " + version.ToString());
}
return result;
}
internal virtual void OnDataPropertyRestore(DataProperty dp) {
// deliberate noop here;
}
private void BackupOriginalValueIfNeeded(DataProperty property, Object oldValue) {
if (_originalValuesMap == null) {
_originalValuesMap = new BackupValuesMap();
} else {
if (_originalValuesMap.ContainsKey(property.Name)) return;
}
// reference copy of complex object is deliberate - actual original values will be stored in the co itself.
_originalValuesMap.Add(property.Name, oldValue);
}
private void BackupProposedValueIfNeeded(DataProperty property, Object oldValue) {
if (_preproposedValuesMap == null) {
_preproposedValuesMap = new BackupValuesMap();
} else {
if (_preproposedValuesMap.ContainsKey(property.Name)) return;
}
_preproposedValuesMap.Add(property.Name, oldValue);
}
public ReadOnlyDictionary<String, Object> OriginalValuesMap {
get { return HandleNull(_originalValuesMap); }
}
public ReadOnlyDictionary<String, Object> PreproposedValuesMap {
get { return HandleNull(_preproposedValuesMap); }
}
private ReadOnlyDictionary<String, Object> HandleNull(BackupValuesMap map) {
return (map ?? BackupValuesMap.Empty).ReadOnlyDictionary;
}
internal BackupValuesMap _originalValuesMap;
internal BackupValuesMap _preproposedValuesMap;
#endregion
#region Private
private IDictionary<String, Object> _backingStore;
#endregion
}
}
|
using Xunit.Abstractions;
#if XUNIT_CORE_DLL
namespace Xunit.Sdk
#else
namespace Xunit
#endif
{
/// <summary>
/// Default implementation of <see cref="ITestOutput"/>.
/// </summary>
public class TestOutput : TestMessage, ITestOutput
{
/// <summary>
/// Initializes a new instance of the <see cref="TestOutput"/> class.
/// </summary>
public TestOutput(ITest test, string output)
: base(test)
{
Output = output;
}
/// <inheritdoc/>
public string Output { get; private set; }
}
} |
using AudioToolbox;
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
namespace Plugin.AudioRecorder
{
internal class AudioStream : IAudioStream
{
const int CountAudioBuffers = 3;
const int MaxBufferSize = 0x50000; // 320 KB
const float TargetMeasurementTime = 100F; // milliseconds
InputAudioQueue audioQueue;
/// <summary>
/// Occurs when new audio has been streamed.
/// </summary>
public event EventHandler<byte []> OnBroadcast;
/// <summary>
/// Occurs when the audio stream active status changes.
/// </summary>
public event EventHandler<bool> OnActiveChanged;
/// <summary>
/// Occurs when there's an error while capturing audio.
/// </summary>
public event EventHandler<Exception> OnException;
/// <summary>
/// Gets the sample rate.
/// </summary>
/// <value>
/// The sample rate.
/// </value>
public int SampleRate
{
get;
private set;
}
/// <summary>
/// Gets the channel count. Currently always 1 (Mono).
/// </summary>
/// <value>
/// The channel count.
/// </value>
public int ChannelCount => 1;
/// <summary>
/// Gets bits per sample. Currently always 16 (bits).
/// </summary>
public int BitsPerSample => 16;
/// <summary>
/// Gets a value indicating if the audio stream is active.
/// </summary>
public bool Active => audioQueue?.IsRunning ?? false;
/// <summary>
/// Wrapper function to run success/failure callbacks from an operation that returns an AudioQueueStatus.
/// </summary>
/// <param name="bufferFn">The function that returns AudioQueueStatus.</param>
/// <param name="successAction">The Action to run if the result is AudioQueueStatus.Ok.</param>
/// <param name="failAction">The Action to run if the result is anything other than AudioQueueStatus.Ok.</param>
void BufferOperation (Func<AudioQueueStatus> bufferFn, Action successAction = null, Action<AudioQueueStatus> failAction = null)
{
var status = bufferFn ();
if (status == AudioQueueStatus.Ok)
{
successAction?.Invoke ();
}
else
{
if (failAction != null)
{
failAction (status);
}
else
{
throw new Exception ($"AudioStream buffer error :: buffer operation returned non - Ok status:: {status}");
}
}
}
/// <summary>
/// Starts the audio stream.
/// </summary>
public Task Start ()
{
try
{
if (!Active)
{
InitAudioQueue ();
BufferOperation (() => audioQueue.Start (),
() => OnActiveChanged?.Invoke (this, true),
status => throw new Exception ($"audioQueue.Start() returned non-OK status: {status}"));
}
return Task.FromResult (true);
}
catch (Exception ex)
{
Debug.WriteLine ("Error in AudioStream.Start(): {0}", ex.Message);
Stop ();
throw;
}
}
/// <summary>
/// Stops the audio stream.
/// </summary>
public Task Stop ()
{
if (audioQueue != null)
{
audioQueue.InputCompleted -= QueueInputCompleted;
if (audioQueue.IsRunning)
{
BufferOperation (() => audioQueue.Stop (true),
() => OnActiveChanged?.Invoke (this, false),
status => Debug.WriteLine ("AudioStream.Stop() :: audioQueue.Stop returned non OK result: {0}", status));
}
audioQueue.Dispose ();
audioQueue = null;
}
return Task.FromResult (true);
}
/// <summary>
/// Initializes a new instance of the <see cref="AudioStream"/> class.
/// </summary>
/// <param name="sampleRate">Sample rate.</param>
public AudioStream (int sampleRate)
{
SampleRate = sampleRate;
}
void InitAudioQueue ()
{
// create our audio queue & configure buffers
var audioFormat = AudioStreamBasicDescription.CreateLinearPCM (SampleRate, (uint) ChannelCount, (uint) BitsPerSample);
audioQueue = new InputAudioQueue (audioFormat);
audioQueue.InputCompleted += QueueInputCompleted;
// calculate our buffer size and make sure it's not too big
var bufferByteSize = (int) (TargetMeasurementTime / 1000F/*ms to sec*/ * SampleRate * audioFormat.BytesPerPacket);
bufferByteSize = bufferByteSize < MaxBufferSize ? bufferByteSize : MaxBufferSize;
for (var index = 0; index < CountAudioBuffers; index++)
{
var bufferPtr = IntPtr.Zero;
BufferOperation (() => audioQueue.AllocateBuffer (bufferByteSize, out bufferPtr), () =>
{
BufferOperation (() => audioQueue.EnqueueBuffer (bufferPtr, bufferByteSize, null), () => Debug.WriteLine ("AudioQueue buffer enqueued :: {0} of {1}", index + 1, CountAudioBuffers));
});
}
}
/// <summary>
/// Handles iOS audio buffer queue completed message.
/// </summary>
/// <param name='sender'>Sender object</param>
/// <param name='e'> Input completed parameters.</param>
void QueueInputCompleted (object sender, InputCompletedEventArgs e)
{
try
{
// we'll only broadcast if we're actively monitoring audio packets
if (!Active)
{
return;
}
if (e.Buffer.AudioDataByteSize > 0)
{
var audioBytes = new byte [e.Buffer.AudioDataByteSize];
Marshal.Copy (e.Buffer.AudioData, audioBytes, 0, (int) e.Buffer.AudioDataByteSize);
// broadcast the audio data to any listeners
OnBroadcast?.Invoke (this, audioBytes);
// check if active again, because the auto stop logic may stop the audio queue from within this handler!
if (Active)
{
BufferOperation (() => audioQueue.EnqueueBuffer (e.IntPtrBuffer, null), null, status =>
{
Debug.WriteLine ("AudioStream.QueueInputCompleted() :: audioQueue.EnqueueBuffer returned non-Ok status :: {0}", status);
OnException?.Invoke (this, new Exception ($"audioQueue.EnqueueBuffer returned non-Ok status :: {status}"));
});
}
}
}
catch (Exception ex)
{
Debug.WriteLine ("AudioStream.QueueInputCompleted() :: Error: {0}", ex.Message);
OnException?.Invoke (this, new Exception ($"AudioStream.QueueInputCompleted() :: Error: {ex.Message}"));
}
}
/// <summary>
/// Flushes any audio bytes in memory but not yet broadcast out to any listeners.
/// </summary>
public void Flush ()
{
// not needed for this implementation
}
}
}
|
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
namespace Steganography
{
/// <summary>
/// Converter between boolean value and Visibility.
/// Used to convert between value IsProcessing flag of binding context and value on UI.
/// </summary>
public class VisibilityToBooleanConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return value?.Equals(true) == true ? Visibility.Visible : Visibility.Hidden;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return value != null && (Visibility)value != Visibility.Visible;
}
}
}
|
using Silent.Practices.CQRS.Queries;
namespace Silent.Practices.CQRS.Tests.Fakes
{
internal sealed class FakeUnregisteredQuery : IQuery<FakeResult>
{
}
}
|
namespace Shapeshifter.WindowsDesktop.Services.Images.Interfaces
{
using System.Windows.Media.Imaging;
using Infrastructure.Dependencies.Interfaces;
public interface IImagePersistenceService: ISingleInstance
{
byte[] ConvertBitmapSourceToByteArray(BitmapSource input);
byte[] DecorateSourceWithMetaInformation(byte[] source, ImageMetaInformation information);
BitmapSource ConvertByteArrayToBitmapSource(byte[] input);
}
} |
/*
* GazeEventSource Unity Component
* (c) Copyright 2017, 2018, Warwick Molloy
* GitHub repo WazzaMo/UnityComponents
* Provided under the terms of the MIT License.
*/
using System;
using System.Collections.Generic;
namespace Actor.GazeInput {
public interface IGazeEventBroadcaster {
void RegisterGlobalHandlers(List<IGlobalGazeEventHandler> handlers);
void BroadcastGazeEvents(List<GazeData> events);
}
}
|
//
// System.Security.Cryptography.X509Certificates.X500DistinguishedName
//
// Author:
// Sebastien Pouliot <sebastien@ximian.com>
//
// Copyright (C) 2004-2006 Novell Inc. (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
#if SECURITY_DEP
#if MONOTOUCH || MONODROID
using Mono.Security;
using MX = Mono.Security.X509;
#else
extern alias MonoSecurity;
using MonoSecurity::Mono.Security;
using MX = MonoSecurity::Mono.Security.X509;
#endif
using System.Collections;
using System.Text;
namespace System.Security.Cryptography.X509Certificates {
[MonoTODO ("Some X500DistinguishedNameFlags options aren't supported, like DoNotUsePlusSign, DoNotUseQuotes and ForceUTF8Encoding")]
public sealed class X500DistinguishedName : AsnEncodedData {
private const X500DistinguishedNameFlags AllFlags = X500DistinguishedNameFlags.Reversed |
X500DistinguishedNameFlags.UseSemicolons | X500DistinguishedNameFlags.DoNotUsePlusSign |
X500DistinguishedNameFlags.DoNotUseQuotes | X500DistinguishedNameFlags.UseCommas |
X500DistinguishedNameFlags.UseNewLines | X500DistinguishedNameFlags.UseUTF8Encoding |
X500DistinguishedNameFlags.UseT61Encoding | X500DistinguishedNameFlags.ForceUTF8Encoding;
private string name;
public X500DistinguishedName (AsnEncodedData encodedDistinguishedName)
{
if (encodedDistinguishedName == null)
throw new ArgumentNullException ("encodedDistinguishedName");
RawData = encodedDistinguishedName.RawData;
if (RawData.Length > 0)
DecodeRawData ();
else
name = String.Empty;
}
public X500DistinguishedName (byte[] encodedDistinguishedName)
{
if (encodedDistinguishedName == null)
throw new ArgumentNullException ("encodedDistinguishedName");
Oid = new Oid ();
RawData = encodedDistinguishedName;
if (encodedDistinguishedName.Length > 0)
DecodeRawData ();
else
name = String.Empty;
}
public X500DistinguishedName (string distinguishedName)
: this (distinguishedName, X500DistinguishedNameFlags.Reversed)
{
}
public X500DistinguishedName (string distinguishedName, X500DistinguishedNameFlags flag)
{
if (distinguishedName == null)
throw new ArgumentNullException ("distinguishedName");
if ((flag != 0) && ((flag & AllFlags) == 0))
throw new ArgumentException ("flag");
Oid = new Oid ();
if (distinguishedName.Length == 0) {
// empty (0x00) ASN.1 sequence (0x30)
RawData = new byte [2] { 0x30, 0x00 };
DecodeRawData ();
} else {
var dn = MX.X501.FromString (distinguishedName);
if ((flag & X500DistinguishedNameFlags.Reversed) != 0) {
ASN1 rdn = new ASN1 (0x30);
for (int i = dn.Count - 1; i >= 0; i--)
rdn.Add (dn [i]);
dn = rdn;
}
RawData = dn.GetBytes ();
if (flag == X500DistinguishedNameFlags.None)
name = distinguishedName;
else
name = Decode (flag);
}
}
public X500DistinguishedName (X500DistinguishedName distinguishedName)
{
if (distinguishedName == null)
throw new ArgumentNullException ("distinguishedName");
Oid = new Oid ();
RawData = distinguishedName.RawData;
name = distinguishedName.name;
}
public string Name {
get { return name; }
}
public string Decode (X500DistinguishedNameFlags flag)
{
if ((flag != 0) && ((flag & AllFlags) == 0))
throw new ArgumentException ("flag");
if (RawData.Length == 0)
return String.Empty;
// Mono.Security reversed isn't the same as fx 2.0 (which is the reverse of 1.x)
bool reversed = ((flag & X500DistinguishedNameFlags.Reversed) != 0);
bool quotes = ((flag & X500DistinguishedNameFlags.DoNotUseQuotes) == 0);
string separator = GetSeparator (flag);
ASN1 rdn = new ASN1 (RawData);
return MX.X501.ToString (rdn, reversed, separator, quotes);
}
public override string Format (bool multiLine)
{
if (multiLine) {
string s = Decode (X500DistinguishedNameFlags.UseNewLines);
if (s.Length > 0)
return s + Environment.NewLine;
else
return s;
} else {
return Decode (X500DistinguishedNameFlags.UseCommas);
}
}
// private stuff
private static string GetSeparator (X500DistinguishedNameFlags flag)
{
if ((flag & X500DistinguishedNameFlags.UseSemicolons) != 0)
return "; ";
if ((flag & X500DistinguishedNameFlags.UseCommas) != 0)
return ", ";
if ((flag & X500DistinguishedNameFlags.UseNewLines) != 0)
return Environment.NewLine;
return ", "; //default
}
// decode the DN using the (byte[]) RawData
private void DecodeRawData ()
{
if ((RawData == null) || (RawData.Length < 3)) {
name = String.Empty;
return;
}
ASN1 sequence = new ASN1 (RawData);
name = MX.X501.ToString (sequence, true, ", ", true);
}
private static string Canonize (string s)
{
int i = s.IndexOf ('=') + 1;
StringBuilder r = new StringBuilder (s.Substring (0, i));
// skip any white space starting the value
while (i < s.Length && Char.IsWhiteSpace (s, i))
i++;
// ensure we skip white spaces at the end of the value
s = s.TrimEnd ();
// keep track of internal multiple spaces
bool space = false;
for (; i < s.Length; i++) {
if (space) {
space = Char.IsWhiteSpace (s, i);
if (space)
continue;
}
if (Char.IsWhiteSpace (s, i))
space = true;
r.Append (Char.ToUpperInvariant (s[i]));
}
return r.ToString ();
}
// of all X500DistinguishedNameFlags flags nothing can do a "correct" comparison :|
internal static bool AreEqual (X500DistinguishedName name1, X500DistinguishedName name2)
{
if (name1 == null)
return (name2 == null);
if (name2 == null)
return false;
X500DistinguishedNameFlags flags = X500DistinguishedNameFlags.UseNewLines | X500DistinguishedNameFlags.DoNotUseQuotes;
string[] split = new string[] { Environment.NewLine };
string[] parts1 = name1.Decode (flags).Split (split, StringSplitOptions.RemoveEmptyEntries);
string[] parts2 = name2.Decode (flags).Split (split, StringSplitOptions.RemoveEmptyEntries);
if (parts1.Length != parts2.Length)
return false;
for (int i = 0; i < parts1.Length; i++) {
if (Canonize (parts1[i]) != Canonize (parts2[i]))
return false;
}
return true;
}
}
}
#endif
|
using System;
using System.Linq;
namespace Vendstor.Backend.Objects
{
[Serializable()]
public class Tax
{
public virtual string Id { get; set; }
public virtual string Name { get; set; }
public virtual string ShortName { get; set; }
public virtual decimal Rate { get; set; }
public virtual string StoreShortName { get; set; }
public virtual string Description { get; set; }
public virtual string Code
{
get
{
return StoreShortName.First().ToString();
}
}
public virtual Store Store { get; set; }
public virtual DateTime UpdatedAt { get; set; }
public virtual DateTime CreatedAt { get; set; }
}
}
|
//<snippet1>
using System;
using System.Globalization;
class Sample
{
public static void Main()
{
PersianCalendar jc = new PersianCalendar();
DateTime thisDate = DateTime.Now;
//--------------------------------------------------------------------------------
// Properties
//--------------------------------------------------------------------------------
Console.WriteLine("\n........... Selected Properties .....................\n");
Console.Write("Eras:");
foreach (int era in jc.Eras)
{
Console.WriteLine(" era = {0}", era);
}
//--------------------------------------------------------------------------------
Console.WriteLine("\nTwoDigitYearMax = {0}", jc.TwoDigitYearMax);
//--------------------------------------------------------------------------------
// Methods
//--------------------------------------------------------------------------------
Console.WriteLine("\n............ Selected Methods .......................\n");
//--------------------------------------------------------------------------------
Console.WriteLine("GetDayOfYear: day = {0}", jc.GetDayOfYear(thisDate));
//--------------------------------------------------------------------------------
Console.WriteLine("GetDaysInMonth: days = {0}",
jc.GetDaysInMonth( thisDate.Year, thisDate.Month,
PersianCalendar.PersianEra));
//--------------------------------------------------------------------------------
Console.WriteLine("GetDaysInYear: days = {0}",
jc.GetDaysInYear(thisDate.Year, PersianCalendar.PersianEra));
//--------------------------------------------------------------------------------
Console.WriteLine("GetLeapMonth: leap month (if any) = {0}",
jc.GetLeapMonth(thisDate.Year, PersianCalendar.PersianEra));
//-------------------------------------------------------------
Console.WriteLine("GetMonthsInYear: months in a year = {0}",
jc.GetMonthsInYear(thisDate.Year, PersianCalendar.PersianEra));
//--------------------------------------------------------------------------------
Console.WriteLine("IsLeapDay: This is a leap day = {0}",
jc.IsLeapDay(thisDate.Year, thisDate.Month, thisDate.Day,
PersianCalendar.PersianEra));
//--------------------------------------------------------------------------------
Console.WriteLine("IsLeapMonth: This is a leap month = {0}",
jc.IsLeapMonth(thisDate.Year, thisDate.Month,
PersianCalendar.PersianEra));
//--------------------------------------------------------------------------------
Console.WriteLine("IsLeapYear: 1370 is a leap year = {0}",
jc.IsLeapYear(1370, PersianCalendar.PersianEra));
//--------------------------------------------------------------------------------
// Get the 4-digit year for a year whose last two digits are 99. The 4-digit year
// depends on the current value of the TwoDigitYearMax property.
Console.WriteLine("ToFourDigitYear:");
Console.WriteLine(" If TwoDigitYearMax = {0}, ToFourDigitYear(99) = {1}",
jc.TwoDigitYearMax, jc.ToFourDigitYear(99));
jc.TwoDigitYearMax = thisDate.Year;
Console.WriteLine(" If TwoDigitYearMax = {0}, ToFourDigitYear(99) = {1}",
jc.TwoDigitYearMax, jc.ToFourDigitYear(99));
}
}
// The example displays the following output:
// ........... Selected Properties .....................
//
// Eras: era = 1
//
// TwoDigitYearMax = 99
//
// ............ Selected Methods .......................
//
// GetDayOfYear: day = 1
// GetDaysInMonth: days = 31
// GetDaysInYear: days = 365
// GetLeapMonth: leap month (if any) = 0
// GetMonthsInYear: months in a year = 12
// IsLeapDay: This is a leap day = False
// IsLeapMonth: This is a leap month = False
// IsLeapYear: 1370 is a leap year = True
// ToFourDigitYear:
// If TwoDigitYearMax = 99, ToFourDigitYear(99) = 99
// If TwoDigitYearMax = 2012, ToFourDigitYear(99) = 1999
// </Snippet1>
public class CalendarConversion
{
public void ConvertToday()
{
// <Snippet2>
// Instantiate a PersianCalendar object
PersianCalendar pc = new PersianCalendar();
// Define a Gregorian date of 3/21/2007 12:47:15
DateTime gregorianDate = new DateTime(2007, 3, 21, 00, 47, 15);
Console.WriteLine("The Gregorian calendar date is {0:G}", gregorianDate);
// Convert the Gregorian date to its equivalent date in the Persian calendar
Console.WriteLine("The Persian calendar date is {0}/{1}/{2} {3}:{4}:{5}.",
pc.GetMonth(gregorianDate),
pc.GetDayOfMonth(gregorianDate),
pc.GetYear(gregorianDate),
pc.GetHour(gregorianDate),
pc.GetMinute(gregorianDate),
pc.GetSecond(gregorianDate));
// Convert the Persian calendar date back to the Gregorian calendar date
DateTime fromPersianDate = pc.ToDateTime(
pc.GetYear(gregorianDate),
pc.GetMonth(gregorianDate),
pc.GetDayOfMonth(gregorianDate),
pc.GetHour(gregorianDate),
pc.GetMinute(gregorianDate),
pc.GetSecond(gregorianDate),
(int) pc.GetMilliseconds(gregorianDate),
PersianCalendar.PersianEra);
Console.WriteLine("The converted Gregorian calendar date is {0:G}", fromPersianDate);
// The code displays the following output to the console:
//
// The Gregorian calendar date is 3/21/2007 12:47:15 AM
// The Persian calendar date is 1/1/1386 0:47:15.
// The converted Gregorian calendar date is 3/21/2007 12:47:15 AM
// </Snippet2>
}
}
|
using MpcCore.Commands.Base;
namespace MpcCore.Commands.Queue
{
public class AddToQueue : SimpleCommandBase
{
/// <summary>
/// <inheritdoc/>
/// </summary>
/// <param name="path">path of file or directory</param>
public AddToQueue(string path)
{
Command = $"add \"{path}\"";
}
}
}
|
using Hypermint.Base;
using Prism.Commands;
using Prism.Events;
using Prism.Regions;
using Hypermint.Base.Constants;
using Hypermint.Base.Events;
using Hypermint.Base.Services;
using Hypermint.Base.Interfaces;
using System.IO;
using System.Windows.Input;
using System;
using Hypermint.Base.Extensions;
namespace Hs.Hypermint.NavBar.ViewModels
{
public class NavBarViewModel : ViewModelBase
{
#region Constructors
public NavBarViewModel(IRegionManager manager, IEventAggregator eventAggregator,
ISelectedService selectedService, ISettingsHypermint settings)
{
_regionManager = manager;
_eventAggregator = eventAggregator;
_selectedService = selectedService;
_settings = settings;
_eventAggregator.GetEvent<SystemSelectedEvent>().Subscribe(ShowDatabaseOrSearchView);
_eventAggregator.GetEvent<NavigateRequestEvent>().Subscribe(Navigate);
_eventAggregator.GetEvent<NavigateMediaPaneRequestEvent>().Subscribe(NavigateMediaPane);
_eventAggregator.GetEvent<RequestOpenFolderEvent>().Subscribe(OnOpenFolder);
NavigateCommand = new DelegateCommand<string>(Navigate);
Navigate("DatabaseDetailsView");
}
#endregion
#region Fields
private IRegionManager _regionManager;
private IEventAggregator _eventAggregator;
private ISelectedService _selectedService;
private ISettingsHypermint _settings;
private string _systemName = "";
#endregion
#region Properties
private string currentView = "Views: Database editor";
/// <summary>
/// Gets or sets the current view name.
/// </summary>
public string CurrentView
{
get { return currentView; }
set { SetProperty(ref currentView, value); }
}
private bool isRlEnabled = false;
/// <summary>
/// Used to disable rocketlaunch if main menu selected.
/// </summary>
public bool IsRlEnabled
{
get { return isRlEnabled; }
set { SetProperty(ref isRlEnabled, value); }
}
private bool isMainMenu = true;
/// <summary>
/// Show the search icon
/// </summary>
public bool IsMainMenu
{
get { return isMainMenu; }
set { SetProperty(ref isMainMenu, value); }
}
private bool isNotMainMenu;
/// <summary>
/// Show the datbase Icon
/// </summary>
public bool IsNotMainMenu
{
get { return isNotMainMenu; }
set { SetProperty(ref isNotMainMenu, value); }
}
#endregion
#region Commands
/// <summary>
/// Navigate command for the navbar
/// </summary>
public ICommand NavigateCommand { get; set; }
#endregion
#region Support Methods
/// <summary>
/// Uses the RegionManager.RequestNavigate to show either the search view or database view.<para/>
/// The Main menu shows the search view and any other system shows the database view.
/// </summary>
/// <param name="systemName"></param>
private void ShowDatabaseOrSearchView(string systemName)
{
_systemName = systemName;
NavigateMediaPane("MediaPaneView");
//Check if a multi system file exists
if (File.Exists(_settings.HypermintSettings.HsPath + @"\Databases\" + systemName + "\\_multiSystem"))
_selectedService.IsMultiSystem = true;
else
_selectedService.IsMultiSystem = false;
if (systemName.ToLower().Contains("main menu") || _selectedService.IsMultiSystem)
{
// Disable RL audit, main menu & multisystem
IsRlEnabled = false;
if (!_selectedService.IsMultiSystem)
{
IsNotMainMenu = false;
IsMainMenu = true;
_regionManager.RequestNavigate(RegionNames.ContentRegion, "SearchView");
RemoveAllFilesRegionViews();
}
else
{
IsNotMainMenu = true;
IsMainMenu = false;
_regionManager.RequestNavigate(RegionNames.ContentRegion, "DatabaseDetailsView");
}
}
else
{
IsRlEnabled = true;
IsMainMenu = false;
IsNotMainMenu = true;
_regionManager.RequestNavigate(RegionNames.FilesRegion, "DatabaseOptionsView");
if (!_regionManager.Regions.ContainsRegionWithName(RegionNames.FilesRegion))
{
_regionManager.Regions.Add(RegionNames.FilesRegion, _regionManager.Regions["FilesRegion"]);
}
_regionManager.RequestNavigate(RegionNames.ContentRegion, "DatabaseDetailsView");
}
}
/// <summary>
/// Sets the current view and uses region manager requestNavigate.
/// </summary>
/// <param name="uri"></param>
private void Navigate(string uri = "")
{
//TODO: Move these view names to constants.
CurrentView = "Views: ";
_eventAggregator.GetEvent<NavigateMediaPaneRequestEvent>().Publish(ViewNames.MediaPaneView);
switch (uri)
{
case "DatabaseDetailsView":
if (_selectedService.CurrentSystem.ToLower().Contains("main menu"))
{
CurrentView += "Search view";
_regionManager.RequestNavigate(RegionNames.ContentRegion, "SearchView");
RemoveAllFilesRegionViews();
}
else
{
CurrentView += "Database editor";
_regionManager.RequestNavigate(RegionNames.FilesRegion, "DatabaseOptionsView");
_regionManager.RequestNavigate("ContentRegion", "DatabaseDetailsView");
}
break;
case "HsMediaAuditView":
CurrentView += "Hyperspin media audit";
_regionManager.RequestNavigate(RegionNames.FilesRegion, "HyperspinFilesView");
break;
case "RlMediaAuditView":
if (!_selectedService.CurrentSystem.ToLower().Contains("main menu"))
{
CurrentView += "RocketLaunch media audit";
_regionManager.RequestNavigate(RegionNames.FilesRegion, "RlFilesView");
}
break;
case "IntroVideosView":
if (!_selectedService.CurrentSystem.ToLower().Contains("main menu"))
{
CurrentView += "Hyperspin video intros";
_regionManager.RequestNavigate(RegionNames.FilesRegion, "ExportVideoOptionsView");
}
break;
case "MultiSystemView":
if (!_selectedService.CurrentSystem.ToLower().Contains("main menu"))
{
CurrentView += "Hyperspin multiple system generator";
_regionManager.RequestNavigate(RegionNames.FilesRegion, "MultiSystemOptionsView");
}
break;
case "SimpleWheelView":
if (!_selectedService.CurrentSystem.ToLower().Contains("main menu"))
{
CurrentView += "Simple wheel creator";
_regionManager.RequestNavigate(RegionNames.FilesRegion, "WheelProcessView");
}
break;
case "StatsView":
CurrentView += "Rocketlaunch stats";
RemoveAllFilesRegionViews();
break;
case "YoutubeView":
CurrentView += "Youtube search";
RemoveAllFilesRegionViews();
break;
case "CreateImageView":
CurrentView += "Image edit";
_regionManager.RequestNavigate(RegionNames.FilesRegion, "ImagePresetView");
break;
case "VideoEditView":
CurrentView += "Video edit";
_regionManager.RequestNavigate(RegionNames.FilesRegion, "VideoProcessView");
break;
default:
break;
}
if (CurrentView != "Views: " && uri != "WebBrowseView" && uri != "DatabaseDetailsView")
_regionManager.RequestNavigate(RegionNames.ContentRegion, uri);
}
/// <summary>
/// Changes the media pane view.
/// </summary>
/// <param name="uri"></param>
private void NavigateMediaPane(string view)
{
try
{
_regionManager.RequestNavigate(RegionNames.MediaPaneRegion, view);
}
catch { }
}
private void OnOpenFolder(string directory)
{
var result = new DirectoryInfo(directory).Open();
}
/// <summary>
/// Use to clear out the File Region of any views
/// </summary>
private void RemoveAllFilesRegionViews()
{
foreach (var view in _regionManager.Regions[RegionNames.FilesRegion].Views)
{
_regionManager.Regions[RegionNames.FilesRegion].Deactivate(view);
}
}
#endregion
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AudioVisualizer : MonoBehaviour
{
public GameObject SampleCubePrefab;
GameObject[] SampleCubes = new GameObject[512];
public float maxScale;
// Start is called before the first frame update
void Start()
{
for (int i = 0; i < 512; i++) {
GameObject Cube = (GameObject) Instantiate(SampleCubePrefab);
Cube.transform.position = this.transform.position;
Cube.transform.parent = this.transform;
Cube.name = "Cube" + i;
this.transform.eulerAngles = new Vector3 (0, -0.703125f * i, 0);
Cube.transform.position = Vector3.forward * 100;
SampleCubes[i] = Cube;
}
}
// Update is called once per frame
void Update()
{
for (int i = 0; i < 512; i++) {
if (SampleCubes != null) {
SampleCubes[i].transform.localScale = new Vector3(10, (AudioPeer.samples[i] * maxScale) + 2 ,10);
}
}
}
}
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace Hang {
namespace AiryAudio {
[CreateAssetMenu(fileName = "AiryAudioBank", menuName = "Hang/AiryAudio/AiryAudioBank", order = 1)]
public class AiryAudioBank : ScriptableObject {
[SerializeField] List<AiryAudioSnapshot> mySnapshots;
[SerializeField] List<AiryAudioData> myBank;
public List<AiryAudioSnapshot> GetMySnapshots () {
return mySnapshots;
}
public List<AiryAudioData> GetMyBank () {
return myBank;
}
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class InventoryDrop : MonoBehaviour, IDropHandler
{
public void OnDrop(PointerEventData eventData)
{
if (eventData.pointerDrag != null)
{
InventoryItem newItem = eventData.pointerDrag.GetComponent<InventoryItem>();
InventorySlot OriginalSlot = newItem.originalSlot.GetComponent<InventorySlot>();
// Revert OnDrag Changes
newItem.canvasGroup.blocksRaycasts = true;
if (newItem.inWeaponSlot)
{
OriginalSlot.currentItem = null;
OriginalSlot.isFull = false;
GameManager.Instance.weaponID = -1;
GameManager.Instance.DestroyWeapon();
GameManager.Instance.DropItem(newItem);
}
else if (newItem.inArmourSlot)
{
OriginalSlot.currentItem = null;
OriginalSlot.isFull = false;
GameManager.Instance.armourID = -1;
GameManager.Instance.DestroyArmour();
GameManager.Instance.DropItem(newItem);
}
else
{
OriginalSlot.currentItem = null;
OriginalSlot.isFull = false;
GameManager.Instance.DropItem(newItem);
}
}
}
}
|
namespace Unosquare.FFplayDotNet.Core
{
using FFmpeg.AutoGen;
/// <summary>
/// An AVDictionaryEntry wrapper
/// </summary>
internal unsafe class FFDictionaryEntry
{
// This ointer is generated in unmanaged code.
internal readonly AVDictionaryEntry* Pointer;
/// <summary>
/// Initializes a new instance of the <see cref="FFDictionaryEntry"/> class.
/// </summary>
/// <param name="entryPointer">The entry pointer.</param>
public FFDictionaryEntry(AVDictionaryEntry* entryPointer)
{
Pointer = entryPointer;
}
/// <summary>
/// Gets the key.
/// </summary>
public string Key => Pointer != null ?
Utils.PtrToString(Pointer->key) : null;
/// <summary>
/// Gets the value.
/// </summary>
public string Value => Pointer != null ?
Utils.PtrToString(Pointer->value) : null;
}
}
|
using System;
using System.Collections.Generic;
namespace Persona2
{
class Persona:IComparable
{
int id;
string nombre;
public Int32 CompareTo(Object o)
{
return this.id.CompareTo(((Persona)o).id);
}
/*public String CompareTo(Object o)
{
return this.nombre.CompareTo(((Persona)o).id);
}*/
public Persona(int id, string n)
{
this.id=id;
nombre=n;
}
public override string ToString()
{
return String.Format("{0},{1}", id, nombre);
}
}
class Program
{
static void Main(string[] args)
{
List<Persona> pers = new List<Persona>();
pers.Add(new Persona(2,"Pablo"));
pers.Add(new Persona(1,"Cesar"));
pers.Add(new Persona(3,"Felix"));
Console.WriteLine("Lista");
foreach(Persona p in pers)
{
Console.WriteLine(p);
}
Console.WriteLine("Lista ordenada.");
pers.Sort();
foreach(Persona p in pers)
{
Console.WriteLine(p);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Net.Security;
using System.ServiceModel;
using CarRental.Domain;
namespace CarRental.Service
{
[ServiceContract]
public interface ICarService
{
[OperationContract(Name = "Add", ProtectionLevel = ProtectionLevel.EncryptAndSign)]
CarInfo AddCar(CarInfo carInfo);
[OperationContract(Name = "GetAt")]
Car GetCarAt(int id);
[OperationContract(Name = "GetAll")]
List<Car> GetAllCars();
[OperationContract(Name = "ListAvailable")]
List<Car> ListAvailableCars(DateTime startTime, DateTime endTime);
[OperationContract(Name = "Delete", ProtectionLevel = ProtectionLevel.EncryptAndSign)]
StatusResponse DeleteCar(CarRequest request);
[OperationContract(Name = "PickUp", ProtectionLevel = ProtectionLevel.EncryptAndSign)]
CarInfo PickUpCar(CarRequest request);
[OperationContract(Name = "DropOff", ProtectionLevel = ProtectionLevel.EncryptAndSign)]
CarInfo DropOffCar(CarRequest request);
}
}
|
using UnityEngine;
/// <summary>
/// Simple script to set the playback speed of a particle system on application start
/// Allows you to also lock that speed so it can't be changed by another script.
/// </summary>
[RequireComponent(typeof(ParticleSystem))]
public class ParticleSystemSpeed : MonoBehaviour
{
public float speed = 1f;
public bool lockSpeed = false;
ParticleSystem psys;
void Start()
{
psys = gameObject.GetComponent<ParticleSystem>();
ParticleSystem.MainModule main = psys.main;
main.simulationSpeed= speed;
}
void LateUpdate()
{
if (!lockSpeed)
return;
if (!Mathf.Approximately(psys.main.simulationSpeed, speed))
{
ParticleSystem.MainModule main = psys.main;
main.simulationSpeed = speed;
}
}
} |
using UnityEngine;
using Unity.Entities;
using Unity.Transforms;
using Unity.Mathematics;
using Unity.Collections;
using UnityEngine.UI;
public class GridSpawner : MonoBehaviour
{
//[SerializeField, Tooltip("number of entities to spawn (default 10)")] private int m_spawnCount = 10;
[SerializeField, Tooltip("spacing between entities (default 1.5)")] private float m_spacing = 1.5f;
[SerializeField, Tooltip("a text object that will get updated with the current spawn count (optional)")] private Text m_statusText = null;
[SerializeField, Tooltip("an input field object that lets the player enter the spawn count")] private InputField m_inputField = null;
//bool m_run = false;
int m_currentCount = 0;
//int m_prefabIndex = 0;
EntityManager m_em;
float3 m_pos;
float m_width = 0f;
int m_spawnCount = 0;
NativeArray<Entity> m_prefabs;
//public void StartSpawning()
//{
// m_run = true;
//}
//public void StopSpawning()
//{
// m_run = false;
//}
// Start is called before the first frame update
void Start()
{
//m_pos = transform.position;
m_em = World.DefaultGameObjectInjectionWorld.EntityManager;
EntityQuery query = m_em.CreateEntityQuery(ComponentType.ReadOnly<SpawnTag>());
m_prefabs = query.ToEntityArray(Allocator.Persistent);
UpdateCountText();
}
public void ClearSpawns()
{
EntityQuery query = m_em.CreateEntityQuery(ComponentType.ReadOnly<SpawnedTag>());
m_em.DestroyEntity(query);
UpdateCountText();
}
public void BatchSpawn()
{
ClearSpawns();
if (m_prefabs.Length <= 0) {
m_statusText.text = "No entities found with SpawnTag.";
return;
}
m_pos = transform.position;
m_spawnCount = int.Parse(m_inputField.text);
m_width = math.sqrt(m_spawnCount) * m_spacing;
int wholePart = m_spawnCount / m_prefabs.Length;
int remainder = m_spawnCount - (wholePart * m_prefabs.Length);
// for every prefab, spawn wholePart instances
for (int i = 0; i < m_prefabs.Length; i++) {
// if we're on the last index, include the remainder
if (i == m_prefabs.Length - 1) { wholePart += remainder; }
// do a batch instantiation
NativeArray<Entity> entities = m_em.Instantiate(m_prefabs[i], wholePart, Allocator.Temp);
// set the position for each of the new entities
for (int j = 0; j < entities.Length; j++) {
m_em.AddComponentData<Translation>(entities[j], new Translation { Value = m_pos });
m_em.AddComponent<SpawnedTag>(entities[j]);
IncrementPosition();
}
m_currentCount += entities.Length;
entities.Dispose();
}
UpdateCountText();
}
void UpdateCountText()
{
if (m_statusText != null) { m_statusText.text = m_currentCount + " of " + m_spawnCount + " entities"; }
}
void IncrementPosition()
{
// increment position
m_pos.x += m_spacing;
if (m_pos.x > (m_width + transform.position.x)) {
m_pos.x = transform.position.x;
m_pos.z += m_spacing;
}
}
// Update is called once per frame
//void Update()
//{
// if (!m_run) { return; }
// if (m_currentCount >= m_spawnCount) { return; }
// Entity entity = m_em.Instantiate(m_prefabs[m_prefabIndex]);
// if (entity == Entity.Null) { return; }
// // increment prefab index
// m_prefabIndex++;
// if (m_prefabIndex >= m_prefabs.Length) { m_prefabIndex = 0; }
// m_em.AddComponentData<Translation>(entity, new Translation { Value = new float3(m_pos) });
// IncrementPosition();
// m_currentCount++;
// UpdateCountText();
//}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SimpleEffects2D : MonoBehaviour
{
EffectCurves curve;
private void Start()
{
if (curve == null)
curve = new GameObject().AddComponent<EffectCurves>();
ScaleEffect(transform, curve.bell, .2f, 1f);
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
Start();
}
Coroutine scaleCor;
public void ScaleEffect(Transform affected, AnimationCurve curve, float time, float apex)
{
if (scaleCor != null)
StopCoroutine(scaleCor);
scaleCor = StartCoroutine(StartScaleEffect(affected, curve, time, apex));
}
Vector3 orgScale;
IEnumerator StartScaleEffect(Transform affected, AnimationCurve curve, float time, float apex)
{
Vector3 orgScale = affected.localScale;
float t = 0;
while (t < time)
{
Evaluate();
t += Time.deltaTime;
yield return null;
}
t = time;
Evaluate();
void Evaluate()
{
affected.localScale = orgScale * (1 + curve.Evaluate(t / time) * apex);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace kernel
{
/*
An offset element object represents one file offset item in a structure.
*/
public class OffsetElement
{
string _additionalOffset = "";
/*
Set expression which result to be added to parsed offset value
Parameters:
additionalOffset String with expression
*/
public void setAdditionalOffset(String additionalOffset)
{
_additionalOffset = additionalOffset;
}
}
}
|
using APIServices.DTOs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace APIServices.Models
{
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public string Address { get; set; }
public DateTime DateOfBirth { get; set; }
public string PhoneNumer { get; set; }
public string State { get; set; }
public string ZipCode { get; set; }
public int Id { get; set; }
public static Person FromDto(PersonDto dto)
{
if (dto == null)
return null;
return new Person
{
FirstName = dto.FirstName,
LastName = dto.LastName,
Age = dto.Age,
Address = dto.Address,
DateOfBirth = dto.DateOfBirth,
PhoneNumer = dto.PhoneNumer,
State = dto.State,
ZipCode = dto.ZipCode,
Id = dto.Id
};
}
public static List<Person> FromDto(GetPersonResponseDto dto)
{
if (dto == null)
return null;
return dto.People.Select(Person.FromDto).ToList();
}
}
}
|
using Bogus;
using FluentAssertions;
using Moq;
using NUnit.Framework;
using SocialCareCaseViewerApi.V1.Boundary.Requests;
using SocialCareCaseViewerApi.V1.Gateways;
using SocialCareCaseViewerApi.V1.Helpers;
using System;
using System.Collections.Generic;
using System.Linq;
#nullable enable
namespace SocialCareCaseViewerApi.Tests.V1.Gateways.Database
{
[TestFixture]
public class SaveRequestAudit : DatabaseTests
{
private DatabaseGateway _databaseGateway = null!;
private Mock<IProcessDataGateway> _mockProcessDataGateway = null!;
private Mock<ISystemTime> _mockSystemTime = null!;
private readonly Faker _faker = new Faker();
[SetUp]
public void SetUp()
{
_mockProcessDataGateway = new Mock<IProcessDataGateway>();
_mockSystemTime = new Mock<ISystemTime>();
_databaseGateway = new DatabaseGateway(DatabaseContext, _mockProcessDataGateway.Object,
_mockSystemTime.Object);
}
[Test]
public void CreatesRequestAudit()
{
var metadata = new Dictionary<string, object>() { { "residentId", 333 }, { "caseNoteId", 555 } };
CreateRequestAuditRequest requestAuditRequest = new CreateRequestAuditRequest()
{
ActionName = "view_resident",
UserName = _faker.Person.Email,
Metadata = metadata
};
_databaseGateway.CreateRequestAudit(requestAuditRequest);
var requestAudit = DatabaseContext.RequestAudits.FirstOrDefault();
requestAudit?.ActionName.Should().Be(requestAuditRequest.ActionName);
requestAudit?.UserName.Should().Be(requestAuditRequest.UserName);
requestAudit?.Timestamp.Should().BeCloseTo(DateTime.Now, precision: 1000);
requestAudit?.Metadata.Should().BeEquivalentTo(requestAuditRequest.Metadata);
}
}
}
|
using System;
using System.Configuration;
using Forte.EpiCommonUtils.Infrastructure;
using JavaScriptEngineSwitcher.ChakraCore;
using JavaScriptEngineSwitcher.Core;
using EpiDemo.Web.Features.ReactComponents;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using React;
using WebActivatorEx;
[assembly: PreApplicationStartMethod(typeof(ReactConfig), "Configure")]
namespace EpiDemo.Web.Features.ReactComponents
{
public static class ReactConfig
{
private static bool ReuseJavaScriptEngines =>
"false".Equals(ConfigurationManager.AppSettings["React:ReuseJavaScriptEngines"],
StringComparison.OrdinalIgnoreCase) == false;
public static void Configure()
{
JsEngineSwitcher.Current.EngineFactories.AddChakraCore();
JsEngineSwitcher.Current.DefaultEngineName = ChakraCoreJsEngine.EngineName;
ReactSiteConfiguration.Configuration
.SetJsonSerializerSettings(new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),
StringEscapeHandling = StringEscapeHandling.EscapeHtml
})
.SetReuseJavaScriptEngines(ReuseJavaScriptEngines)
#if DEBUG
.DisableServerSideRendering()
#endif
.SetLoadBabel(false)
.SetLoadReact(false)
.AddScriptWithoutTransform("~" + WebpackManifest.GetEntry("server-side")
.Js); // bundled React components
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
namespace FlatRedBall.Graphics
{
#region XML Docs
/// <summary>
/// Caches effects and effect parameters
/// </summary>
#endregion
public class EffectCache
{
#region Static Members
#region Enums and defaults
static int EffectParameterNamesCount = 40;
public static string[] EffectParameterNames;
public enum EffectParameterNamesEnum
{
World,
View,
Projection,
ViewProj,
// Lighting
LightingEnable,
AmbLight0Enable,
AmbLight0DiffuseColor,
DirLight0Enable,
DirLight0Direction,
DirLight0DiffuseColor,
DirLight0SpecularColor,
DirLight1Enable,
DirLight1Direction,
DirLight1DiffuseColor,
DirLight1SpecularColor,
DirLight2Enable,
DirLight2Direction,
DirLight2DiffuseColor,
DirLight2SpecularColor,
PointLight0Enable,
PointLight0Position,
PointLight0DiffuseColor,
PointLight0SpecularColor,
PointLight0Range,
// Fog
FogEnabled,
FogColor,
FogStart,
FogEnd,
// Shared parameters
PixelSize,
InvViewProj,
NearClipPlane,
FarClipPlane,
CameraPosition,
ViewportSize,
// Shadow
ShadowMapTexture,
ShadowCameraMatrix,
ShadowLightDirection,
ShadowLightDist,
ShadowCameraAt,
// Animation
MatrixPalette
}
#endregion
#region Static Constructor
#region XML Docs
/// <summary>
/// Initializes parameter name strings
/// </summary>
#endregion
static EffectCache()
{
EffectParameterNames = new string[EffectParameterNamesCount];
for (int i = 0; i < EffectParameterNamesCount; i++)
{
EffectParameterNames[i] = ((EffectParameterNamesEnum)i).ToString();
}
}
#endregion
#endregion
#region Fields
#region XML Docs
/// <summary>
/// Whether or not shared parameters should be cached
/// </summary>
#endregion
bool mCacheShared;
#region XML Docs
/// <summary>
/// The effect cached, if any
/// </summary>
#endregion
Effect mEffect = null;
#region XML Docs
/// <summary>
/// Caches all effect parameters for faster lookup, by effect
/// </summary>
#endregion
Dictionary<Effect, Dictionary<string, EffectParameter>> mFullEffectParameterCache =
new Dictionary<Effect, Dictionary<string, EffectParameter>>();
#region XML Docs
/// <summary>
/// Caches all effect parameters for faster lookup, by parameter name
/// </summary>
#endregion
Dictionary<string, List<EffectParameter>> mFullParameterCache =
new Dictionary<string, List<EffectParameter>>();
#region XML Docs
/// <summary>
/// Caches all effects
/// </summary>
#endregion
List<Effect> mEffectCache = new List<Effect>();
#region XML Docs
/// <summary>
/// Caches all enumerated effect parameters
/// </summary>
#endregion
List<List<EffectParameter>> mEffectParameterCache = new List<List<EffectParameter>>();
Dictionary<Effect, Dictionary<string, EffectTechnique>> mEffectTechniqueCache =
new Dictionary<Effect, Dictionary<string, EffectTechnique>>();
#endregion
#region Properties
#region XML Docs
/// <summary>
/// Whether or not shared parameters should be cached
/// </summary>
#endregion
public bool CacheShared
{
get { return mCacheShared; }
}
#region XML Docs
/// <summary>
/// Gets a list of cached effects
/// </summary>
#endregion
public List<Effect> Effects
{
get { return mEffectCache; }
}
#region XML Docs
/// <summary>
/// Gets a list of parameters of the specified name
/// </summary>
/// <param name="name">The name of the parameters to retrieve</param>
/// <returns>A list of parameters (or null if name not found)</returns>
#endregion
public List<EffectParameter> this[string name]
{
get
{
if (mFullParameterCache.ContainsKey(name))
return mFullParameterCache[name];
else
return null;
}
}
#region XML Docs
/// <summary>
/// Retrieves all parameters of one of the standard types
/// </summary>
/// <param name="name">The name of the parameter</param>
/// <returns>A list of parameters (or null if shared params aren't cached)</returns>
#endregion
public List<EffectParameter> this[EffectParameterNamesEnum name]
{
get
{
// If we don't cache shared parameters, there is no list
if (!mCacheShared)
return null;
else
return mEffectParameterCache[(int)name];
}
}
#region XML Docs
/// <summary>
/// Gets a parameter in a specified effect
/// </summary>
/// <param name="effect">The effect</param>
/// <param name="parameterName">The parameter name</param>
/// <returns>The parameter, or null if either effect or parameter not found</returns>
#endregion
public EffectParameter this[Effect effect, string parameterName]
{
get
{
EffectParameter param = null;
// Check if the effect and parameter are found
if (mFullEffectParameterCache.ContainsKey(effect) &&
mFullEffectParameterCache[effect].ContainsKey(parameterName))
{
param =
mFullEffectParameterCache[effect][parameterName];
}
return param;
}
}
#region XML Docs
/// <summary>
/// Gets the specified technique from the specified effect, or null if no technique by that name exists
/// </summary>
/// <param name="effect">The effect</param>
/// <param name="techniqueName">The name of the technique</param>
/// <returns>The technique requested, or null if not found</returns>
#endregion
public EffectTechnique GetTechnique(Effect effect, string techniqueName)
{
EffectTechnique technique = null;
if (mEffectTechniqueCache.ContainsKey(effect) &&
mEffectTechniqueCache[effect].ContainsKey(techniqueName))
{
technique = mEffectTechniqueCache[effect][techniqueName];
}
return technique;
}
#endregion
#region Constructor
#region XML Docs
/// <summary>
/// Caches an effect's parameters
/// </summary>
/// <param name="effect">The effect to cache</param>
/// <param name="cacheShared">Whether or not shared parameters should be cached</param>
#endregion
public EffectCache(Effect effect, bool cacheShared)
{
mCacheShared = cacheShared;
mEffect = effect;
UpdateCache();
}
#endregion
#region Methods
#region XML Docs
/// <summary>
/// Adds an effect to the cache
/// </summary>
/// <param name="effect">The effect to cache</param>
#endregion
private void CacheEffect(Effect effect)
{
// Cache the effect
if (!mEffectCache.Contains(effect))
mEffectCache.Add(effect);
// Cache the effect and its parameters
if (!mFullEffectParameterCache.ContainsKey(effect))
mFullEffectParameterCache.Add(effect, new Dictionary<string, EffectParameter>());
// Create the full parameter dictionary
Dictionary<string, EffectParameter> parameters = new Dictionary<string,EffectParameter>();
foreach (EffectParameter param in effect.Parameters)
{
// Cache all parameters in the global cache
parameters.Add(param.Name, param);
// Cache parameter
if (!mFullParameterCache.ContainsKey(param.Name))
{
mFullParameterCache.Add(param.Name, new List<EffectParameter>(1));
}
mFullParameterCache[param.Name].Add(param);
// Cache parameter by effect
if (!mFullEffectParameterCache[effect].ContainsKey(param.Name))
mFullEffectParameterCache[effect].Add(param.Name, param);
else
mFullEffectParameterCache[effect][param.Name] = param;
}
// Cache shared parameters if it is allowed
if (mCacheShared)
{
for (int i = 0; i < EffectParameterNamesCount; i++)
{
EffectParameter param = effect.Parameters[
((EffectParameterNamesEnum)i).ToString()];
// Cache if found
if (param != null)
{
mEffectParameterCache[i].Add(param);
}
}
}
// Cache techniques
if (mEffectTechniqueCache.ContainsKey(effect))
{
mEffectTechniqueCache[effect].Clear();
}
else
{
mEffectTechniqueCache.Add(effect, new Dictionary<string, EffectTechnique>());
}
foreach (EffectTechnique technique in effect.Techniques)
{
mEffectTechniqueCache[effect].Add(technique.Name, technique);
}
}
#region XML Docs
/// <summary>
/// Recreates the cache
/// </summary>
#endregion
public void UpdateCache()
{
// Clear the caches
mFullEffectParameterCache.Clear();
mFullParameterCache.Clear();
mEffectCache.Clear();
mEffectParameterCache.Clear();
#if !SILVERLIGHT
// Recreate the parameter cache if allowed
if (mCacheShared)
{
for (int i = 0; i < EffectParameterNamesCount; i++)
{
mEffectParameterCache.Add(new List<EffectParameter>());
}
}
// Update the cached effect
if (mEffect != null)
{
CacheEffect(mEffect);
}
#endif
}
#region XML Docs
/// <summary>
/// Validates the cached model/effect to make sure it hasn't changed
/// </summary>
/// <param name="updateNow">Whether or not the cache should be updated if found invalid</param>
/// <returns>Whether or not the cache was valid</returns>
#endregion
public bool ValidateCache(bool updateNow)
{
bool isValid = true;
// We just need to check to make sure all the required effects are cached
if (mEffect != null)
{
if (!mEffectCache.Contains(mEffect))
isValid = false;
}
// Return validity
return isValid;
}
#endregion
}
}
|
namespace Cuemon.Data
{
/// <summary>
/// Identifies the type of data operation performed by a query against a data source.
/// </summary>
public enum QueryType
{
/// <summary>
/// Indicates that a query is used for a data operation that retrieves data.
/// </summary>
Select = 0,
/// <summary>
/// Indicates that a query is used for a data operation that updates data.
/// </summary>
Update = 1,
/// <summary>
/// Indicates that a query is used for a data operation that inserts data.
/// </summary>
Insert = 2,
/// <summary>
/// Indicates that a query is used for a data operation that deletes data.
/// </summary>
Delete = 3,
/// <summary>
/// Indicates that a query is specifically used for a lookup on whether a data record exists.
/// </summary>
Exists = 4
}
} |
using System;
using System.Configuration;
using System.Globalization;
using ReMi.BusinessLogic.BusinessRules;
using ReMi.Common.Constants.BusinessRules;
using ReMi.Common.Utils;
namespace ReMi.Api.Insfrastructure
{
public class ApplicationSettings : IApplicationSettings
{
private const int SettingsSessionDuration = 15;
private static DateTime _lastSettingsRefresh = DateTime.MinValue;
private static object _sync = new object();
private int _sessionDuration = -1;
public IBusinessRuleEngine BusinessRuleEngine { get; set; }
public int DefaultReleaseWindowDurationTime
{
get
{
var config = ConfigurationManager.AppSettings["DefaultReleaseWindowDurationTime"];
return GetInt(config, 120);
}
}
public bool LogJsonFormatted
{
get { return GetBool(ConfigurationManager.AppSettings["LogJsonFormatted"], true); }
}
public bool LogQueryResponses
{
get { return GetBool(ConfigurationManager.AppSettings["LogQueryResponses"]); }
}
public string FrontEndUrl
{
get { return ConfigurationManager.AppSettings["frontendUrl"]; }
}
public int SessionDuration
{
get
{
RefreshSettings();
return _sessionDuration;
}
}
#region Helpers
private static int GetInt(string config, int defaultValue = 0)
{
if (!string.IsNullOrWhiteSpace(config))
{
int value;
if (int.TryParse(config, NumberStyles.Integer, CultureInfo.InvariantCulture, out value))
return value;
}
return defaultValue;
}
private static bool GetBool(string config, bool defaultValue = false)
{
if (!string.IsNullOrWhiteSpace(config))
{
bool value;
if (bool.TryParse(config, out value))
return value;
}
return defaultValue;
}
private void RefreshSettings()
{
lock (_sync)
{
if (!((SystemTime.Now - _lastSettingsRefresh).TotalMinutes > SettingsSessionDuration))
return;
_lastSettingsRefresh = SystemTime.Now;
_sessionDuration = BusinessRuleEngine.Execute<int>(Guid.Empty,
BusinessRuleConstants.Config.SessionDurationRule.ExternalId,
null);
}
}
#endregion
}
}
|
namespace MiddleMan.Exceptions
{
public class MultipleHandlersException : MiddleManExceptionBase
{
public MultipleHandlersException(string message) : base(message)
{
}
}
} |
using System.Collections.Generic;
namespace kanimal
{
using AnimHashTable = Dictionary<int, string>;
// Spriter's object names are numbered sequentially from 0.
// This is arguably useful if multiple of the same sprite is included in a single animation frame
// Therefore, keep track of the objects included in a frame.
public class ObjectNameMap : Dictionary<SpriteName, int>
{
public void Update(KAnim.Element element, AnimHashTable animHashes)
{
var name = element.FindName(animHashes);
if (!ContainsKey(name))
this[name] = 0;
else
this[name] += 1;
}
public SpriterObjectName FindObjectName(KAnim.Element element, AnimHashTable animHashes)
{
var name = element.FindName(animHashes);
return name.ToSpriterObjectName(this[name]);
}
}
} |
using System;
/*
* Да се напише програма, която чете 2*n-на брой цели числа, подадени от потребителя,
* и проверява дали сумата на първите n числа (лява сума) е равна на сумата на вторите n числа (дясна сума).
*
* При равенство печата "Yes" + сумата; иначе печата "No" + разликата.
* Разликата се изчислява като положително число (по абсолютна стойност).
*/
namespace forSimple7LeftSumRight
{
class forSimple7LeftSumRight
{
static void Main(string[] args)
{
long n = long.Parse(Console.ReadLine());
long sum1 = 0, sum2 = 0;
for (int i = 0; i < n; i++)
{
long num = long.Parse(Console.ReadLine());
sum1 += num;
};
for (int i = 0; i < n; i++)
{
long num = long.Parse(Console.ReadLine());
sum2 += num;
};
if (sum1==sum2)
Console.WriteLine("Yes, sum = {0}", sum1);
else
Console.WriteLine("No, diff = {0}", Math.Abs(sum1-sum2));
}
}
} |
using Atlas.Roleplay.Library.Models;
namespace Atlas.Roleplay.Client.Environment.Jobs.Police
{
public class MalePoliceUniform : Style
{
public MalePoliceUniform()
{
Shirt.Current = 38;
Torso.Current = 149;
TorsoType.Current = 0; // Badge
Decals.Current = 1;
Body.Current = 19;
Pants.Current = 45;
Shoes.Current = 25;
Bag.Current = 3;
Mask.Current = 121;
}
}
public class FemalePoliceUniform : Style
{
public FemalePoliceUniform()
{
Shirt.Current = 35;
Torso.Current = 2;
TorsoType.Current = 0; // Badge
Decals.Current = 1;
Body.Current = 31;
Pants.Current = 51;
Shoes.Current = 25;
Bag.Current = 3;
Mask.Current = 121;
}
}
} |
// Copyright (c) MOSA Project. Licensed under the New BSD License.
namespace System.Runtime.InteropServices
{
[ComVisible(true)]
public enum UnmanagedType
{
Bool = 2,
I1 = 3,
U1 = 4,
I2 = 5,
U2 = 6,
I4 = 7,
U4 = 8,
I8 = 9,
U8 = 10,
R4 = 11,
R8 = 12,
Currency = 15,
BStr = 19,
LPStr = 20,
LPWStr = 21,
LPTStr = 22,
ByValTStr = 23,
IUnknown = 25,
IDispatch = 26,
Struct = 27,
Interface = 28,
SafeArray = 29,
ByValArray = 30,
SysInt = 31,
SysUInt = 32,
VBByRefStr = 34,
AnsiBStr = 35,
TBStr = 36,
VariantBool = 37,
FunctionPtr = 38,
AsAny = 40,
LPArray = 42,
LPStruct = 43,
CustomMarshaler = 44,
Error = 45
}
}
|
using Chocolatey.Explorer.Commands;
using Chocolatey.Explorer.Services;
using Chocolatey.Explorer.Services.PackagesService;
using NUnit.Framework;
using Rhino.Mocks;
namespace Chocolatey.Explorer.Test.Commands
{
public class TestClearCacheInstalledPackagesCommand
{
[Test]
public void IfIPackageVersionIsICacheableThenShouldInvalidateCache()
{
var sut = new ClearCacheInstalledPackagesCommand();
sut.InstalledPackagesService = MockRepository.GenerateMock<IFakeCacheableInstalledPackagesService>();
sut.Execute();
sut.InstalledPackagesService.AssertWasCalled(x => ((ICacheable)x).InvalidateCache());
}
public interface IFakeCacheableInstalledPackagesService : IInstalledPackagesService, ICacheable { }
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerInventory : Singleton<PlayerInventory>
{
WeaponSlotManager weaponSlotManager;
public WeaponItem rightWeapon;
public WeaponItem leftWeapon;
public WeaponItem unarmedWeapon;
public WeaponItem[] weaponsInRightHandSlots = new WeaponItem[2];
public WeaponItem[] weaponsInLeftHandSlots = new WeaponItem[2];
public List<WeaponItem> weaponInventory;
public int currentRightWeaponIndex = -1;
public int currentLeftWeaponIndex = -1;
void Awake()
{
weaponSlotManager = GetComponentInChildren<WeaponSlotManager>();
}
void Start()
{
rightWeapon = weaponsInRightHandSlots[0];
leftWeapon = weaponsInLeftHandSlots[0];
weaponSlotManager.LoadWeaponOnSlot(rightWeapon, false);
weaponSlotManager.LoadWeaponOnSlot(leftWeapon, true);
}
public void ChangeLeftHandWeapon()
{
currentLeftWeaponIndex = currentLeftWeaponIndex + 1;
if (currentLeftWeaponIndex == 0 && weaponsInLeftHandSlots[0] != null)
{
leftWeapon = weaponsInLeftHandSlots[currentLeftWeaponIndex];
weaponSlotManager.LoadWeaponOnSlot(leftWeapon, Flags.IS_LEFT);
}
else if (currentLeftWeaponIndex == 0 && weaponsInLeftHandSlots[0] == null)
{
// Not weapon in this slot, go to next slot
currentLeftWeaponIndex = currentLeftWeaponIndex + 1;
}
else if (currentLeftWeaponIndex == 1 && weaponsInLeftHandSlots[1] != null)
{
leftWeapon = weaponsInLeftHandSlots[currentLeftWeaponIndex];
weaponSlotManager.LoadWeaponOnSlot(leftWeapon, Flags.IS_LEFT);
}
else
{
currentLeftWeaponIndex = currentLeftWeaponIndex + 1;
}
if (currentLeftWeaponIndex > weaponsInLeftHandSlots.Length - 1)
{
currentLeftWeaponIndex = -1;
leftWeapon = unarmedWeapon;
weaponSlotManager.LoadWeaponOnSlot(unarmedWeapon, Flags.IS_LEFT);
}
}
public void ChangeRightHandWeapon()
{
currentRightWeaponIndex = currentRightWeaponIndex + 1;
if (currentRightWeaponIndex == 0 && weaponsInRightHandSlots[0] != null)
{
rightWeapon = weaponsInRightHandSlots[currentRightWeaponIndex];
weaponSlotManager.LoadWeaponOnSlot(rightWeapon, Flags.IS_RIGHT);
}
else if (currentRightWeaponIndex == 0 && weaponsInRightHandSlots[0] == null)
{
// Not weapon in this slot, go to next slot
currentRightWeaponIndex = currentRightWeaponIndex + 1;
}
else if (currentRightWeaponIndex == 1 && weaponsInRightHandSlots[1] != null)
{
rightWeapon = weaponsInRightHandSlots[currentRightWeaponIndex];
weaponSlotManager.LoadWeaponOnSlot(rightWeapon, Flags.IS_RIGHT);
}
else
{
currentRightWeaponIndex = currentRightWeaponIndex + 1;
}
if (currentRightWeaponIndex > weaponsInRightHandSlots.Length - 1)
{
currentRightWeaponIndex = -1;
rightWeapon = unarmedWeapon;
weaponSlotManager.LoadWeaponOnSlot(unarmedWeapon, Flags.IS_RIGHT);
}
}
}
|
using Blue.Menu;
using UnityEngine;
public class TestingPrefab : MonoBehaviour
{
public MenuController menu;
// Use this for initialization
void Start()
{
Instantiate(menu.gameObject);
}
} |
using System;
namespace Kekstoaster.Syntax
{
/// <summary>
/// Empty syntax element, meaning it contains no nested Elements or the nested elements are not important.
/// </summary>
public sealed class EmptyElement:SyntaxElement
{
private CompileAction _compile = null;
/// <summary>
/// Initializes a new instance of the <see cref="Kekstoaster.Syntax.EmptyElement"/> class.
/// </summary>
/// <param name="compiler">The compiler compiling the element.</param>
internal EmptyElement (ParseAction parse, EbnfCompiler compiler) : base (parse, compiler)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Kekstoaster.Syntax.EmptyElement"/> class.
/// </summary>
/// <param name="compiler">The compiler compiling the element.</param>
/// <param name="compile">The compile action used to compile the element.</param>
public EmptyElement (ParseAction parse, EbnfCompiler compiler, CompileAction compile) : base (parse, compiler)
{
this._compile = compile;
}
/// <summary>
/// Gets the text representation of the element.
/// </summary>
/// <value>The text.</value>
public override string Text {
get {
return "";
}
}
/// <summary>
/// Compile this element in the specified ScopeContext.
/// </summary>
/// <param name="parentContext">Parent context.</param>
internal override object Compile (ScopeContext parentContext)
{
if (this._compile != null) {
return this._compile.Compile (parentContext, null);
} else {
return null;
}
}
}
}
|
//<Snippet1>
using System;
namespace DesignLibrary
{
public class NoInstancesNeeded
{
// Violates rule: StaticHolderTypesShouldNotHaveConstructors.
// Uncomment the following line to correct the violation.
// private NoInstancesNeeded() {}
public static void Method1() {}
public static void Method2() {}
}
}
//</Snippet1>
|
@inherits RazorRenderer.BasePage<ChameleonForms.Templates.ChameleonFormsDefaultTemplate.Params.FieldConfigurationParams>
@foreach (var html in Model.FieldConfiguration.AppendedHtml)
{@html
} |
/*
* Copyright 2014 Splunk, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"): you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
namespace Splunk.ModularInputs
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Xml.Serialization;
/// <summary>
/// The <see cref="MultiValueParameter"/> class represents a this that
/// contains multiple values.
/// </summary>
/// <remarks>
/// <example>Sample XML</example>
/// <code>
/// <param_list name="multiValue">
/// <value>value1</value>
/// <value>value2</value>
/// </param_list>
/// </code>
/// </remarks>
[XmlRoot("param_list")]
public class MultiValueParameter : Parameter
{
#region Constructors
public MultiValueParameter(string name, params string[] values)
: this(name, values.AsEnumerable())
{ }
public MultiValueParameter(string name, IEnumerable<string> values)
{
Contract.Requires<ArgumentNullException>(name != null);
Contract.Requires<ArgumentNullException>(values != null);
this.Values = new Collection<string>();
foreach (var value in values)
{
this.Values.Add(value);
}
}
#endregion
#region Properties
/// <summary>
/// The values in the current <see cref="MultiValueParameter"/>.
/// </summary>
/// <value>
/// The values.
/// </value>
[XmlElement("value")]
public Collection<string> Values
{ get; set; }
#endregion
#region Methods
/// <summary>
/// Converts this object to a boolean collection.
/// </summary>
/// <returns>
/// This object as a Collection<Boolean>
/// </returns>
public Collection<Boolean> ToBooleanCollection()
{
var collection = new Collection<bool>();
foreach (var value in this.Values)
{
collection.Add( Util.ParseSplunkBoolean(value));
}
return collection;
}
/// <summary>
/// Converts this object to a double collection.
/// </summary>
/// <returns>
/// This object as a Collection<Double>
/// </returns>
public Collection<Double> ToDoubleCollection()
{
var collection = new Collection<double>();
foreach (var value in this.Values)
{
collection.Add(double.Parse(value));
}
return collection;
}
/// <summary>
/// Converts this object to an int 32 collection.
/// </summary>
/// <returns>
/// This object as a Collection<Int32>
/// </returns>
public Collection<Int32> ToInt32Collection()
{
var collection = new Collection<int>();
foreach (var value in this.Values)
{
collection.Add(int.Parse(value));
}
return collection;
}
/// <summary>
/// Converts this object to an int 64 collection.
/// </summary>
/// <returns>
/// This object as a Collection<Int64>
/// </returns>
public Collection<Int64> ToInt64Collection()
{
var collection = new Collection<long>();
foreach (var value in this.Values)
{
collection.Add(long.Parse(value));
}
return collection;
}
/// <summary>
/// Converts this object to a single collection.
/// </summary>
/// <returns>
/// This object as a Collection<Single>
/// </returns>
public Collection<Single> ToSingleCollection()
{
var collection = new Collection<float>();
foreach (var value in this.Values)
{
collection.Add(float.Parse(value));
}
return collection;
}
/// <summary>
/// Converts this object to a string collection.
/// </summary>
/// <returns>
/// This object as a Collection<String>
/// </returns>
public Collection<String> ToStringCollection()
{
return new Collection<string>(this.Values);
}
#endregion
#region Privates/internals
MultiValueParameter()
{ }
#endregion
}
}
|
using System;
using Volo.Abp.Application.Dtos;
namespace EasyAbp.EShop.Products.Categories.Dtos
{
public class CategoryDto : FullAuditedEntityDto<Guid>
{
public Guid? ParentCategoryId { get; set; }
public string DisplayName { get; set; }
public string Description { get; set; }
public string MediaResources { get; set; }
}
} |
#define DO_AUTO_PAUSE //comment out this line to disable this script
#if UNITY_EDITOR_WIN && DO_AUTO_PAUSE
using System;
using System.Runtime.InteropServices;
using UnityEditor;
namespace AutoPauseMusic
{
[InitializeOnLoadAttribute]
public class PauseSystemMusicInPlayMode
{
public const int KEYEVENTF_EXTENTEDKEY = 1;
public const int KEYEVENTF_KEYUP = 0;
public const int VK_MEDIA_PLAY_PAUSE = 0xB3;
//key press lib
[DllImport("user32.dll")]
public static extern void keybd_event(byte virtualKey, byte scanCode, uint flags, IntPtr extraInfo);
// listen for playModeStateChanged when the class is initialized
static PauseSystemMusicInPlayMode()
{
EditorApplication.playModeStateChanged += PlayModeStateChanged;
}
private static void PlayModeStateChanged(PlayModeStateChange state)
{
//keep those bangin' tunes if playmode is muted
if (EditorUtility.audioMasterMute)
return;
//play/pause as we change state
if (state == PlayModeStateChange.EnteredPlayMode || state == PlayModeStateChange.ExitingPlayMode)
{
SimulateSystemPlayPauseButton();
}
}
private static void SimulateSystemPlayPauseButton()
{
keybd_event(VK_MEDIA_PLAY_PAUSE, 0, KEYEVENTF_EXTENTEDKEY, IntPtr.Zero);
}
}
}
#endif |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class hw2 : MonoBehaviour
{
bool noRedUnderLine = true;
void Start()
{
if (noRedUnderLine)
{
Debug.Log("There is no error in your script.");
}
int count = 10;
for (int i = 0; i < count; i++)
{
Debug.Log(i);
}
}
}
public class Pet : MonoBehaviour
{
string breed;
string petName;
int age;
string color;
public void cat()
{
Pet cat = new Pet();
cat.breed = "siamese and scottish fold";
cat.name = "brulee";
cat.age = 4;
cat.color = "brown";
}
}
|
using System.Diagnostics;
namespace EDTradeAdvisor.DomainObjects
{
[DebuggerDisplay("{Description,nq}")]
public class Location
{
public Location(StarSystem system, Station station)
{
System = system;
Station = station;
}
/// <summary></summary>
public StarSystem System { get; set; }
/// <summary></summary>
public Station Station { get; set; }
/// <summary></summary>
public static implicit operator LocationID(Location loc) => new LocationID(loc.System?.ID, loc.Station?.ID);
/// <summary></summary>
public string Description => $"{System.Name}/{Station.Name}";
#region Equals
public bool Equals(Location rhs)
{
return System.Equals(rhs.System) && Station.Equals(rhs.Station);
}
public override bool Equals(object obj)
{
return base.Equals(obj);
}
public override int GetHashCode()
{
return new { System, Station }.GetHashCode();
}
#endregion
}
}
|
// Copyright © 2020 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
namespace CefSharp.DevTools.Profiler
{
/// <summary>
/// Coverage data for a source range.
/// </summary>
[System.Runtime.Serialization.DataContractAttribute]
public class CoverageRange : CefSharp.DevTools.DevToolsDomainEntityBase
{
/// <summary>
/// JavaScript script source offset for the range start.
/// </summary>
[System.Runtime.Serialization.DataMemberAttribute(Name = ("startOffset"), IsRequired = (true))]
public int StartOffset
{
get;
set;
}
/// <summary>
/// JavaScript script source offset for the range end.
/// </summary>
[System.Runtime.Serialization.DataMemberAttribute(Name = ("endOffset"), IsRequired = (true))]
public int EndOffset
{
get;
set;
}
/// <summary>
/// Collected execution count of the source range.
/// </summary>
[System.Runtime.Serialization.DataMemberAttribute(Name = ("count"), IsRequired = (true))]
public int Count
{
get;
set;
}
}
} |
using System.Collections.Generic;
using demos.Models.ViewModels.Courses;
namespace demos.Services.Contracts
{
public interface IHomeService
{
IEnumerable<CourseViewModel> GetAllCourses();
}
} |
using System.Threading.Tasks;
using DasBlog.Web.Models.BlogViewModels;
using Microsoft.AspNetCore.Razor.TagHelpers;
namespace DasBlog.Web.TagHelpers.Comments
{
public class CommentMailtoLinkTagHelper : TagHelper
{
public CommentAdminViewModel Comment { get; set; }
private const string MAILTOLINK = "mailto:{0}?subject={1}";
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
var maillink = string.Format(MAILTOLINK, Comment.Email, Comment.Title);
output.TagName = "a";
output.TagMode = TagMode.StartTagAndEndTag;
output.Attributes.SetAttribute("href", maillink);
output.Attributes.SetAttribute("class", "dbc-comment-mailto-link");
var content = await output.GetChildContentAsync();
output.Content.SetHtmlContent(content.GetContent());
}
}
}
|
<div id="messageContainer">
<h4 class="text-center"><strong id="message" class="text-success"></strong></h4>
</div>
|
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.ModelBinding;
namespace GovUk.Frontend.AspNetCore.ModelBinding
{
public class DateInputModelBinderProvider : IModelBinderProvider
{
public IModelBinder GetBinder(ModelBinderProviderContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
var modelType = context.Metadata.ModelType;
if (modelType == typeof(Date) || modelType == typeof(Date?))
{
return new DateInputModelBinder();
}
return null;
}
}
public class DateInputModelBinder : IModelBinder
{
internal const string DayComponentName = "Day";
internal const string MonthComponentName = "Month";
internal const string YearComponentName = "Year";
public Task BindModelAsync(ModelBindingContext bindingContext)
{
if (bindingContext == null)
{
throw new ArgumentNullException(nameof(bindingContext));
}
var modelType = bindingContext.ModelType;
if (modelType != typeof(Date) && modelType != typeof(Date?))
{
throw new InvalidOperationException($"Cannot bind {modelType.Name}.");
}
var dayModelName = $"{bindingContext.ModelName}.{DayComponentName}";
var monthModelName = $"{bindingContext.ModelName}.{MonthComponentName}";
var yearModelName = $"{bindingContext.ModelName}.{YearComponentName}";
var dayValueProviderResult = bindingContext.ValueProvider.GetValue(dayModelName);
var monthValueProviderResult = bindingContext.ValueProvider.GetValue(monthModelName);
var yearValueProviderResult = bindingContext.ValueProvider.GetValue(yearModelName);
// If all components are empty and ModelType is nullable then bind null to result
if (dayValueProviderResult == ValueProviderResult.None &&
monthValueProviderResult == ValueProviderResult.None &&
yearValueProviderResult == ValueProviderResult.None)
{
if (modelType == typeof(Date?))
{
bindingContext.Result = ModelBindingResult.Success(null);
}
else
{
bindingContext.Result = ModelBindingResult.Failed();
}
return Task.CompletedTask;
}
int day = -1;
int month = -1;
int year = -1;
if (TryParseYear() && TryParseMonth() && TryParseDay())
{
var date = new Date(year, month, day);
bindingContext.Result = ModelBindingResult.Success(date);
}
else
{
bindingContext.ModelState.SetModelValue(dayModelName, dayValueProviderResult);
bindingContext.ModelState.SetModelValue(monthModelName, monthValueProviderResult);
bindingContext.ModelState.SetModelValue(yearModelName, yearValueProviderResult);
bindingContext.ModelState.TryAddModelError(
bindingContext.ModelName,
new DateParseException("Invalid date specified."),
bindingContext.ModelMetadata);
bindingContext.Result = ModelBindingResult.Failed();
}
return Task.CompletedTask;
bool TryParseDay()
{
if (dayValueProviderResult != ValueProviderResult.None &&
dayValueProviderResult.FirstValue != string.Empty)
{
if (!int.TryParse(dayValueProviderResult.FirstValue, out day) ||
day < 1 ||
(month != -1 && year != -1 && day > DateTime.DaysInMonth(year, month)))
{
bindingContext.ModelState.TryAddModelError(
dayModelName,
new DateParseException("Day is not valid."),
bindingContext.ModelMetadata);
bindingContext.ModelState.TryGetValue(bindingContext.ModelName, out var x);
return false;
}
else
{
return true;
}
}
else
{
bindingContext.ModelState.TryAddModelError(
dayModelName,
new DateParseException("Day is missing."),
bindingContext.ModelMetadata);
return false;
}
}
bool TryParseMonth()
{
if (monthValueProviderResult != ValueProviderResult.None &&
monthValueProviderResult.FirstValue != string.Empty)
{
if (!int.TryParse(monthValueProviderResult.FirstValue, out month) ||
month < 1 ||
month > 12)
{
bindingContext.ModelState.TryAddModelError(
monthModelName,
new DateParseException("Month is not valid."),
bindingContext.ModelMetadata);
return false;
}
else
{
return true;
}
}
else
{
bindingContext.ModelState.TryAddModelError(
monthModelName,
new DateParseException("Month is missing."),
bindingContext.ModelMetadata);
return false;
}
}
bool TryParseYear()
{
if (yearValueProviderResult != ValueProviderResult.None &&
yearValueProviderResult.FirstValue != string.Empty)
{
if (!int.TryParse(yearValueProviderResult.FirstValue, out year) ||
year < 1 ||
year > 9999)
{
bindingContext.ModelState.TryAddModelError(
yearModelName,
new DateParseException("Year is not valid."),
bindingContext.ModelMetadata);
return false;
}
else
{
return true;
}
}
else
{
bindingContext.ModelState.TryAddModelError(
yearModelName,
new DateParseException("Year is missing."),
bindingContext.ModelMetadata);
return false;
}
}
}
}
}
|
using Newtonsoft.Json;
namespace PrimePenguin.CentraSharp.Entities
{
public class ShippingTerms
{
/// <summary>
/// Id of the specific shipping terms object.
/// </summary>
[JsonProperty("id")]
public int Id { get; set; }
/// <summary>
/// Name of the specific shipping terms object.
/// </summary>
[JsonProperty("name")]
public string Name { get; set; }
/// <summary>
/// Description of the specific shipping terms object.
/// </summary>
[JsonProperty("description")]
public string Description { get; set; }
}
} |
using System.Threading.Tasks;
namespace Aptacode.CSharp.Common.Persistence.UnitOfWork
{
public abstract class GenericUnitOfWork : IUnitOfWork
{
#region Repositories
public abstract TRepo Get<TRepo>();
#endregion
#region Unit Of Work
public abstract void Dispose();
public abstract Task Commit();
public abstract void RejectChanges();
#endregion
}
} |
namespace EuroHelp.Services.Damages
{
public enum DamageSorting
{
EventDate = 0,
RegisterDate = 1,
InsuranceCompany = 2
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace UnsupervisedLearning.KMeans
{
/// <summary>
/// Representa uma associção entre instância e cluster que significa que
/// a instância está classificada naquele cluster.
/// </summary>
public class InstanceClustered
{
public Instance instance { get; private set; }
public Cluster cluster { get; private set; }
public InstanceClustered(Instance instance, Cluster cluster)
{
if (instance == null)
throw new ArgumentException("instance");
if (cluster == null)
throw new ArgumentException("cluster");
this.instance = instance;
this.cluster = cluster;
}
}
}
|
using Newtonsoft.Json;
namespace Tfl.Api.Presentation.Entities.JourneyPlanner
{
public class JourneyPlannerCycleHireDockingStationData
{
[JsonProperty(PropertyName = "originNumberOfBikes")]
public int? OriginNumberOfBikes { get; set; }
[JsonProperty(PropertyName = "destinationNumberOfBikes")]
public int? DestinationNumberOfBikes { get; set; }
[JsonProperty(PropertyName = "originNumberOfEmptySlots")]
public int? OriginNumberOfEmptySlots { get; set; }
[JsonProperty(PropertyName = "destinationNumberOfEmptySlots")]
public int? DestinationNumberOfEmptySlots { get; set; }
[JsonProperty(PropertyName = "originId")]
public string OriginId { get; set; }
[JsonProperty(PropertyName = "destinationId")]
public string DestinationId { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace OSIResearch.Qillion.Functions
{
static class BindingRedirector
{
//Lifted from npiasecki's workaround for the lack of native binding redirects
//https://github.com/Azure/azure-webjobs-sdk-script/issues/992
public static void RedirectAssembly(
string shortName,
Version targetVersion,
string publicKeyToken)
{
ResolveEventHandler handler = null;
handler = (sender, args) =>
{
var requestedAssembly = new AssemblyName(args.Name);
if (requestedAssembly.Name != shortName)
{
return null;
}
var targetPublicKeyToken = new AssemblyName("x, PublicKeyToken=" + publicKeyToken)
.GetPublicKeyToken();
requestedAssembly.Version = targetVersion;
requestedAssembly.SetPublicKeyToken(targetPublicKeyToken);
requestedAssembly.CultureInfo = CultureInfo.InvariantCulture;
AppDomain.CurrentDomain.AssemblyResolve -= handler;
return Assembly.Load(requestedAssembly);
};
AppDomain.CurrentDomain.AssemblyResolve += handler;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ReactiveApp.Xaml.Controls;
using Windows.UI;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;
namespace ReactiveApp.Xaml.Services
{
public class SystemTrayManager : ISystemTrayManager
{
private SystemTray systemTray;
private static Lazy<SystemTrayManager> instance = new Lazy<SystemTrayManager>(() => new SystemTrayManager());
public static ISystemTrayManager Instance
{
get { return instance.Value; }
}
/// <summary>
/// Initializes the <see cref="OrientationManager"/> class.
/// </summary>
private SystemTrayManager()
{
this.systemTray = new SystemTray();
Canvas.SetZIndex(systemTray, 20000);
this.ProgressIndicator = new ProgressIndicator(systemTray);
var color = ((SolidColorBrush)Application.Current.Resources["ApplicationForegroundThemeBrush"]).Color;
this.Foreground = color;
this.ProgressIndicator.Foreground = color;
this.Opacity = 1.0;
this.Background = Colors.Red;
this.IsVisible = true;
}
public Color Foreground
{
get
{
SolidColorBrush brush = this.systemTray.Foreground as SolidColorBrush;
if (brush != null)
{
return brush.Color;
}
else
{
throw new InvalidOperationException();
}
}
set
{
this.systemTray.Foreground = new SolidColorBrush(value);
}
}
public Color Background
{
get
{
SolidColorBrush brush = this.systemTray.Background as SolidColorBrush;
if (brush != null)
{
return brush.Color;
}
else
{
throw new InvalidOperationException();
}
}
set
{
this.systemTray.Background = new SolidColorBrush(value);
}
}
public double Opacity
{
get { return this.systemTray.TrayOpacity; }
set { this.systemTray.TrayOpacity = value; }
}
public bool IsVisible
{
get { return this.systemTray.Visibility == Visibility.Visible; }
set { this.systemTray.Visibility = value ? Visibility.Visible : Visibility.Collapsed; }
}
public IProgressIndicator ProgressIndicator
{
get;
private set;
}
}
}
|
// Licensed to Laurent Ellerbach under one or more agreements.
// Laurent Ellerbach licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Newtonsoft.Json;
namespace Nabaztag.Net.Models
{
/// <summary>
/// {"audio":audio_list,"choreography":choreography}
/// </summary>
public class Sequence
{
/// <summary>
/// An audio list can be:
/// * a path of sound separated by ; example: "nabmastodon/communion.wav;otherpath/othersound.mp3".
/// if the sound resource end with "*" or "*.suffixe", a random sound is played in this resource
/// * a text to speech: "tts:language,text" => not anymore into the doc!
/// </summary>
[JsonProperty(PropertyName = "audio", NullValueHandling = NullValueHandling.Ignore)]
public string[] AudioList { get; set; }
/// <summary>
/// A choreography list can be:
/// * like for sound, a list of choreography from the choreographies directory of the various apps
/// * "urn:x-chor:streaming" to stream a choreography with a random color
/// * "urn:x-chor:streaming:N" to stream a choreography with a specific color N
/// </summary>
[JsonProperty(PropertyName = "choreography", NullValueHandling = NullValueHandling.Ignore)]
public string ChoreographyList { get; set; }
}
}
|
// <auto-generated> This file has been auto generated by EF Core Power Tools. </auto-generated>
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
namespace CurrencyApi.Models
{
public partial class DtbankdbContext : DbContext
{
public virtual DbSet<RATE> RATE { get; set; }
public DtbankdbContext(DbContextOptions<DtbankdbContext> options) : base(options)
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasAnnotation("ProductVersion", "2.2.0-rtm-35687");
modelBuilder.Entity<RATE>(entity =>
{
entity.Property(e => e.Id)
.HasMaxLength(36)
.HasDefaultValueSql("(newid())");
entity.Property(e => e.Country).HasMaxLength(3);
entity.Property(e => e.Name).HasMaxLength(50);
entity.Property(e => e.Rate1)
.HasColumnName("Rate")
.HasColumnType("money");
entity.Property(e => e.TimeStamp)
.HasColumnType("datetime")
.HasDefaultValueSql("(getdate())");
});
OnModelCreatingExt(modelBuilder);
}
partial void OnModelCreatingExt(ModelBuilder modelBuilder);
}
} |
namespace OPCAIC.Messaging.Messages
{
/// <summary>
/// Result status of the job sent from broker to worker for execution.
/// </summary>
public enum JobStatus
{
/// <summary>
/// Unknown status.
/// </summary>
Unknown,
/// <summary>
/// Job completed successfully.
/// </summary>
Ok,
/// <summary>
/// Job was cancelled.
/// </summary>
Canceled,
/// <summary>
/// Job was forcibly terminated by worker after timeout period expired.
/// </summary>
Timeout,
/// <summary>
/// Job completed with errors.
/// </summary>
Error
}
} |
using System;
using System.Collections.Generic;
using OpenSource.Data.HashFunction.Core;
using OpenSource.Data.HashFunction.Core.Utilities;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace OpenSource.Data.HashFunction.Jenkins
{
internal class JenkinsLookup2_Implementation
: StreamableHashFunctionBase,
IJenkinsLookup2
{
public IJenkinsLookup2Config Config => _config.Clone();
public override int HashSizeInBits { get; } = 32;
private IJenkinsLookup2Config _config;
public JenkinsLookup2_Implementation(IJenkinsLookup2Config config)
{
if (config == null)
throw new ArgumentNullException(nameof(config));
_config = config.Clone();
}
public override IBlockTransformer CreateBlockTransformer() =>
new BlockTransformer(_config);
private class BlockTransformer
: BlockTransformerBase<BlockTransformer>
{
private UInt32 _a;
private UInt32 _b;
private UInt32 _c;
private UInt32 _bytesProcessed;
public BlockTransformer()
: base(inputBlockSize: 12)
{
}
public BlockTransformer(IJenkinsLookup2Config config)
: this()
{
_a = 0x9e3779b9;
_b = 0x9e3779b9;
_c = config.Seed;
_bytesProcessed = 0;
}
protected override void CopyStateTo(BlockTransformer other)
{
other._a = _a;
other._b = _b;
other._c = _c;
other._bytesProcessed = _bytesProcessed;
}
protected override void TransformByteGroupsInternal(ArraySegment<byte> data)
{
Debug.Assert(data.Count % 12 == 0);
var dataArray = data.Array;
var dataCount = data.Count;
var endOffset = data.Offset + dataCount;
var tempA = _a;
var tempB = _b;
var tempC = _c;
for (var currentOffset = data.Offset; currentOffset < endOffset; currentOffset += 12)
{
tempA += BitConverter.ToUInt32(dataArray, currentOffset);
tempB += BitConverter.ToUInt32(dataArray, currentOffset + 4);
tempC += BitConverter.ToUInt32(dataArray, currentOffset + 8);
Mix(ref tempA, ref tempB, ref tempC);
}
_a = tempA;
_b = tempB;
_c = tempC;
_bytesProcessed += (UInt32) dataCount;
}
protected override IHashValue FinalizeHashValueInternal(CancellationToken cancellationToken)
{
var remainder = FinalizeInputBuffer;
var remainderLength = (remainder?.Length).GetValueOrDefault();
Debug.Assert(remainderLength >= 0);
Debug.Assert(remainderLength < 12);
var finalA = _a;
var finalB = _b;
var finalC = _c;
// All the case statements fall through on purpose
switch (remainderLength)
{
case 11: finalC += (UInt32) remainder[10] << 24; goto case 10;
case 10: finalC += (UInt32) remainder[9] << 16; goto case 9;
case 9: finalC += (UInt32) remainder[8] << 8; goto case 8;
// the first byte of c is reserved for the length
case 8:
finalB += BitConverter.ToUInt32(remainder, 4);
goto case 4;
case 7: finalB += (UInt32) remainder[6] << 16; goto case 6;
case 6: finalB += (UInt32) remainder[5] << 8; goto case 5;
case 5: finalB += (UInt32) remainder[4]; goto case 4;
case 4:
finalA += BitConverter.ToUInt32(remainder, 0);
break;
case 3: finalA += (UInt32)remainder[2] << 16; goto case 2;
case 2: finalA += (UInt32)remainder[1] << 8; goto case 1;
case 1:
finalA += (UInt32)remainder[0];
break;
}
finalC += _bytesProcessed + (UInt32) remainderLength;
Mix(ref finalA, ref finalB, ref finalC);
return new HashValue(
BitConverter.GetBytes(finalC),
32);
}
private static void Mix(ref UInt32 a, ref UInt32 b, ref UInt32 c)
{
a -= b; a -= c; a ^= (c >> 13);
b -= c; b -= a; b ^= (a << 8);
c -= a; c -= b; c ^= (b >> 13);
a -= b; a -= c; a ^= (c >> 12);
b -= c; b -= a; b ^= (a << 16);
c -= a; c -= b; c ^= (b >> 5);
a -= b; a -= c; a ^= (c >> 3);
b -= c; b -= a; b ^= (a << 10);
c -= a; c -= b; c ^= (b >> 15);
}
}
}
}
|
// Structure of heap
using System;
using System.Collections;
using System.Collections.Generic;
namespace Algolib.Structures
{
public class Heap<T> : IEnumerable<T>
{
private readonly List<T> heap;
/// <summary>The comparer.</summary>
public IComparer<T> Comparer
{
get;
}
/// <summary>Number of elements.</summary>
public int Count => heap.Count;
public Heap() : this(Comparer<T>.Default)
{
}
public Heap(IEnumerable<T> enumerable) : this()
{
foreach(T element in enumerable)
Push(element);
}
public Heap(Comparison<T> comparison) : this(Comparer<T>.Create(comparison))
{
}
public Heap(IComparer<T> comparer)
{
heap = new List<T>();
Comparer = comparer;
}
public IEnumerator<T> GetEnumerator() => heap.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => heap.GetEnumerator();
/// <summary>Adds a new element to this heap.</summary>
/// <param name="item">Element to add</param>
public void Push(T item)
{
heap.Add(item);
int index = heap.Count - 1;
while(index > 0)
{
int nextIndex = (index - 1) / 2;
if(Comparer.Compare(heap[index], heap[nextIndex]) >= 0)
break;
swap(index, nextIndex);
index = nextIndex;
}
}
/// <summary>Retrieves minimal element from this heap.</summary>
/// <returns>Minimal element</returns>
/// <exception cref="InvalidOperationException">If the heap is empty</exception>
public T Get() => Count == 0 ? throw new InvalidOperationException("The heap is empty")
: heap[0];
/// <summary>
/// Retrieves minimal element from this heap and copies it to the <c>result</c> parameter.
/// </summary>
/// <param name="result">Minimal element if it's present, otherwise the default value</param>
/// <returns><c>true</c> if the element exists, otherwise <c>false</c></returns>
public bool TryGet(out T result)
{
if(Count == 0)
{
result = default;
return false;
}
result = heap[0];
return true;
}
/// <summary>Retrieves and removes minimal element from this heap.</summary>
/// <returns>Removed minimal element</returns>
/// <exception cref="InvalidOperationException">If the heap is empty</exception>
public T Pop()
{
T element = Get();
doPop();
return element;
}
/// <summary>
/// Removes minimal element from this heap and copies it to the <c>result</c> parameter.
/// </summary>
/// <param name="result">
/// Removed minimal element if it's present, otherwise the default value
/// </param>
/// <returns><c>true</c> if the element exists, otherwise <c>false</c></returns>
public bool TryPop(out T result)
{
bool wasPresent = TryGet(out result);
if(wasPresent)
doPop();
return wasPresent;
}
// Removes minimal element
private void doPop()
{
heap[0] = heap[^1];
heap.RemoveAt(heap.Count - 1);
int index = 0;
while(index + index + 1 < heap.Count)
{
int childIndex = index + index + 2 == heap.Count
? index + index + 1
: Comparer.Compare(heap[index + index + 1], heap[index + index + 2]) < 0
? index + index + 1
: index + index + 2;
if(Comparer.Compare(heap[childIndex], heap[index]) >= 0)
break;
swap(index, childIndex);
index = childIndex;
}
}
// Swaps two elements in the heap.
private void swap(int indexFirst, int indexSecond)
{
T temp = heap[indexFirst];
heap[indexFirst] = heap[indexSecond];
heap[indexSecond] = temp;
}
}
}
|
using SchoolLocker.Core.Contracts;
using SchoolLocker.Core.Entities;
using System;
using System.Linq;
using SchoolLocker.Core.DataTransferObjects;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
namespace SchoolLocker.Persistence
{
public class BookingRepository : IBookingRepository
{
private readonly ApplicationDbContext _dbContext;
public BookingRepository(ApplicationDbContext dbContext)
{
_dbContext = dbContext;
}
public async Task AddRangeAsync(Booking[] bookings)
=> await _dbContext.Bookings.AddRangeAsync(bookings);
public async Task AddAsync(Booking booking)
=> await _dbContext.Bookings.AddAsync(booking);
public async Task<Booking> GetOverlappingBookingAsync(Booking booking)
{
DateTime end = booking.To ?? DateTime.MaxValue;
return await _dbContext.Bookings.FirstOrDefaultAsync(b =>
b.Id != booking.Id && booking.LockerId == b.LockerId && (
(b.From >= booking.From && b.From <= end) //True if b.From is in range of booking
|| (b.To >= booking.From && b.To <= end) //True if b.To is in range of booking
|| (b.From < booking.From && b.To > end) //True if booking is completely inside b
));
}
public async Task<BookingDto[]> GetOverlappingBookingsAsync(int lockerNumber, DateTime @from, DateTime? to)
{
var bookings = (await _dbContext
.Bookings
.Include(b => b.Pupil)
.Where(b => b.Locker.Number == lockerNumber &&
(b.From >= @from && (to == null || b.From <= to) ||
b.To >= @from && (to == null || b.To <= to))
)
.OrderBy(b => b.From)
.ToArrayAsync())
.Select(b => new BookingDto
{
Lastname = b.Pupil.Lastname,
Firstname = b.Pupil.Firstname,
LockerNumber = b.Locker.Number,
From = b.From,
To = b.To
})
.ToArray();
return bookings;
}
// 2020-07-01 2020-07-20 ==> 0
// 2020-07-01 2020-07-21 ==> 1
// 2020-06-29 2020-07-20 ==> 1
// 2020-07-20 2020-08-08 ==> 1
// 2019-10-21 2020-09-03 ==> 3
// 2020-06-29 2020-08-16 ==> 3
}
} |
using System;
using System.Collections.Generic;
using Caasiope.Explorer.Managers.NotificationManagers;
using Caasiope.Explorer.Types;
using Caasiope.Protocol.Types;
using Helios.Common.Logs;
using Helios.JSON;
namespace Caasiope.Explorer.Managers
{
// subscription manager ?
public class SubscriptionManager
{
public OrderBookNotificationManager OrderBookNotificationManager { get; }
private readonly List<INotificationManager> managers = new List<INotificationManager>();
private readonly FundsNotificationManager fundsNotificationManager;
private readonly AddressNotificationManager addressNotificationManager;
private Action<ISession, NotificationMessage> send;
private readonly ILogger logger;
public SubscriptionManager(ILogger logger)
{
this.logger = logger;
AddManager(new TransactionNotificationManager());
AddManager(new LedgerNotificationManager());
addressNotificationManager = AddManager(new AddressNotificationManager());
OrderBookNotificationManager = AddManager(new OrderBookNotificationManager());
fundsNotificationManager = AddManager(new FundsNotificationManager());
}
public void ListenTo(ISession session, Topic topic)
{
// TODO may be use switch?
// TODO move lock here?
managers.ForEach(_ => _.ListenTo(session, topic));
}
public void Notify(SignedLedger ledger)
{
foreach (var manager in managers)
{
try
{
manager.Notify(ledger);
}
catch (Exception e)
{
logger.Log("SubscriptionManager", e);
}
}
}
private T AddManager<T>(T manager) where T : INotificationManager
{
managers.Add(manager);
return manager;
}
public void Initialize()
{
managers.ForEach(_ => _.Send += send);
fundsNotificationManager.Initialize();
addressNotificationManager.Initialize();
}
public void OnSend(Action<ISession, NotificationMessage> callback)
{
send += callback;
}
public void OnClose(ISession session)
{
managers.ForEach(_ => _.OnClose(session));
}
}
public interface INotificationManager
{
void ListenTo(ISession session, Topic topic);
void Notify(SignedLedger ledger);
Action<ISession, NotificationMessage> Send { get; set; }
void OnClose(ISession session);
}
}
|
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace Meiswinkel.NightScoutReporter.NightScoutContracts
{
[JsonObject]
public class Entry
{
/// <summary>
/// Internally assigned id.
/// </summary>
[JsonProperty(PropertyName = "_id", NullValueHandling = NullValueHandling.Ignore)]
public string Id
{
get; set;
}
/// <summary>
/// sgv, mbg, cal, etc
/// </summary>
[JsonProperty(PropertyName = "type")]
public string Type { get; set; }
/// <summary>
/// dateString, prefer ISO `8601`
/// </summary>
[JsonProperty(PropertyName = "dateString", NullValueHandling = NullValueHandling.Ignore)]
public string DateString { get; set; }
/// <summary>
/// dateString, prefer ISO `8601`
/// </summary>
[JsonProperty(PropertyName = "device", NullValueHandling = NullValueHandling.Ignore)]
public string Device
{
get; set;
}
/// <summary>
/// Epoch
/// </summary>
[JsonProperty(PropertyName = "date")]
public long? Date { get; set; }
/// <summary>
/// The glucose reading. (only available for sgv types)
/// </summary>
[JsonProperty(PropertyName = "sgv", NullValueHandling = NullValueHandling.Ignore)]
public uint? Sgv { get; set; }
/// <summary>
/// The glucose reading. (only available for mbg types)
/// </summary>
[JsonProperty(PropertyName = "mbg", NullValueHandling = NullValueHandling.Ignore)]
public uint? Mbg
{
get; set;
}
/// <summary>
/// Direction of glucose trend reported by CGM. (only available for sgv types)
/// </summary>
[JsonProperty(PropertyName = "direction", NullValueHandling = NullValueHandling.Ignore)]
public string Direction { get; set; }
/// <summary>
/// Noise level at time of reading. (only available for sgv types)
/// </summary>
[JsonProperty(PropertyName = "noise", NullValueHandling = NullValueHandling.Ignore)]
public decimal? Noise { get; set; }
/// <summary>
/// The raw filtered value directly from CGM transmitter. (only available for sgv types)
/// </summary>
[JsonProperty(PropertyName = "filtered", NullValueHandling = NullValueHandling.Ignore)]
public decimal? Filtered { get; set; }
/// <summary>
/// dateString, prefer ISO `8601`
/// </summary>
[JsonProperty(PropertyName = "sysTime", NullValueHandling = NullValueHandling.Ignore)]
public string SysTime
{
get; set;
}
/// <summary>
/// The raw unfiltered value directly from CGM transmitter. (only available for sgv types)
/// </summary>
[JsonProperty(PropertyName = "unfiltered", NullValueHandling = NullValueHandling.Ignore)]
public decimal? Unfiltered { get; set; }
/// <summary>
/// The signal strength from CGM transmitter. (only available for sgv types)
/// </summary>
[JsonProperty(PropertyName = "rssi", NullValueHandling = NullValueHandling.Ignore)]
public decimal? Rssi { get; set; }
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.