content stringlengths 23 1.05M |
|---|
using GraphQL.Data.UserRepository;
using GraphQL.Models;
using GraphQL.Types;
namespace GraphQL.Graph.Types
{
public class TodoItemType : ObjectGraphType<TodoItem>
{
public TodoItemType(IUserRepository userRepo)
{
Name = nameof(TodoItemType);
Field(c => c.Id, type: typeof(IdGraphType));
Field(c => c.Title);
Field(c => c.Description);
Field(c => c.AssignedUserId);
Field(c => c.Created);
Field(c => c.LastModified);
Field<UserType>("assignedUser", resolve: context => userRepo.Fetch(context.Source.AssignedUserId));
}
}
public class TodoItemInputType : InputObjectGraphType<TodoItem>
{
public TodoItemInputType()
{
Name = nameof(TodoItemInputType);
Field(c => c.Id, type: typeof(IdGraphType));
Field(c => c.Title, nullable: true);
Field(c => c.Description, nullable: true);
Field(c => c.AssignedUserId, nullable: true);
}
}
}
|
namespace SecondDesktopDll
{
public class MsgArgs
{
public object Sender { get; private set; }
public MsgArgs(object sender = null)
{
Sender = sender;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace CloudTools_Assaigment
{
public static class Extension
{
public static int Sum(this List<int> arrayOfNumbers)
{
int result = 0;
foreach (var number in arrayOfNumbers)
{
result += number;
}
return result;
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
namespace Ultraviolet.Core.Collections
{
/// <summary>
/// Represents a linked list that draws its nodes from a pre-allocated pool.
/// </summary>
/// <remarks>The Base Class Library's built-in <see cref="LinkedList{T}"/> class will allocate a new instance of
/// <see cref="LinkedListNode{T}"/> whenever it needs one, making it difficult to use in performance scenarios
/// which are sensitive to garbage collection, like games. Ultraviolet <see cref="PooledLinkedList{T}"/> maintains
/// an internal pool of nodes which it uses instead of allocating.</remarks>
/// <typeparam name="T">The type of item contained by the list.</typeparam>
public class PooledLinkedList<T> : IEnumerable<T>
{
/// <summary>
/// Initializes a new instance of the PooledLinkedList class.
/// </summary>
public PooledLinkedList()
: this(10)
{
}
/// <summary>
/// Initializes a new instance of the PooledLinkedList class.
/// </summary>
/// <param name="capacity">The linked list's initial capacity.</param>
public PooledLinkedList(Int32 capacity)
{
Contract.EnsureRange(capacity >= 1, nameof(capacity));
NodePool = new List<LinkedListNode<T>>(capacity);
for (int i = 0; i < capacity; i++)
NodePool.Add(new LinkedListNode<T>(default(T)));
}
/// <summary>
/// Finds the first node that contains the specified value.
/// </summary>
/// <param name="value">The value to locate in the list.</param>
/// <returns>The first node that contains the specified value, if one exists; otherwise, null.</returns>
public LinkedListNode<T> Find(T value)
{
return List.Find(value);
}
/// <summary>
/// Finds the last node that contains the specified value.
/// </summary>
/// <param name="value">The value to locate in the list.</param>
/// <returns>The last node that contains the specified value, if one exists; otherwise, null.</returns>
public LinkedListNode<T> FindLast(T value)
{
return List.FindLast(value);
}
/// <summary>
/// Clears the linked list's contents.
/// </summary>
public void Clear()
{
var node = List.First;
var next = List.First;
while (node != null)
{
next = node.Next;
ReleaseNode(node);
node = next;
}
List.Clear();
}
/// <summary>
/// Adds the specified item to the beginning of the linked list.
/// </summary>
/// <param name="item">The item to add to the list.</param>
public void AddFirst(T item)
{
var node = RetrieveNode();
node.Value = item;
List.AddFirst(node);
}
/// <summary>
/// Adds the specified item to the end of the linked list.
/// </summary>
/// <param name="item">The item to add to the list.</param>
public void AddLast(T item)
{
var node = RetrieveNode();
node.Value = item;
List.AddLast(node);
}
/// <summary>
/// Adds the specified new node after the specified existing node.
/// </summary>
/// <param name="node">The node after which to insert a new value.</param>
/// <param name="item">The value to insert.</param>
public void AddAfter(LinkedListNode<T> node, T item)
{
Contract.Require(node, nameof(node));
Contract.Ensure(node.List == List, CoreStrings.ListNodeDoesNotBelongToList);
var value = RetrieveNode();
value.Value = item;
List.AddAfter(node, value);
}
/// <summary>
/// Adds the specified new node before the specified existing node.
/// </summary>
/// <param name="node">The node before which to insert a new value.</param>
/// <param name="item">The value to insert.</param>
public void AddBefore(LinkedListNode<T> node, T item)
{
Contract.Require(node, nameof(node));
Contract.Ensure(node.List == List, CoreStrings.ListNodeDoesNotBelongToList);
var value = RetrieveNode();
value.Value = item;
List.AddBefore(node, value);
}
/// <summary>
/// Removes the first occurrence of the specified item from the list.
/// </summary>
/// <param name="item">The item to remove from the list.</param>
/// <returns><see langword="true"/> if the specified item was removed from the list; otherwise, <see langword="false"/>.</returns>
public bool Remove(T item)
{
var node = List.Find(item);
if (node != null)
{
List.Remove(node);
ReleaseNode(node);
return true;
}
return false;
}
/// <summary>
/// Removes the specified node from the list.
/// </summary>
/// <param name="node">The node to remove from the list.</param>
/// <returns><see langword="true"/> if the specified item was removed from the list; otherwise, <see langword="false"/>.</returns>
public bool Remove(LinkedListNode<T> node)
{
Contract.Require(node, nameof(node));
Contract.Ensure(node.List == List, CoreStrings.ListNodeDoesNotBelongToList);
List.Remove(node);
ReleaseNode(node);
return true;
}
/// <summary>
/// Removes the node at the beginning of the list.
/// </summary>
public void RemoveFirst()
{
var node = List.First;
List.RemoveFirst();
ReleaseNode(node);
}
/// <summary>
/// Removes the node at the end of the list.
/// </summary>
public void RemoveLast()
{
var node = List.Last;
List.RemoveLast();
ReleaseNode(node);
}
/// <summary>
/// Gets a value indicating whether the linked list contains the specified value.
/// </summary>
/// <param name="value">The value to locate in the linked list.</param>
/// <returns><see langword="true"/> if the linked list contains the specified value; otherwise, <see langword="false"/>.</returns>
public bool Contains(T value)
{
return List.Contains(value);
}
/// <summary>
/// Gets an enumerator for the list.
/// </summary>
/// <returns>An enumerator for the list.</returns>
public LinkedList<T>.Enumerator GetEnumerator()
{
return List.GetEnumerator();
}
/// <summary>
/// Gets an enumerator for the list.
/// </summary>
/// <returns>An enumerator for the list.</returns>
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return List.GetEnumerator();
}
/// <summary>
/// Gets an enumerator for the list.
/// </summary>
/// <returns>An enumerator for the list.</returns>
IEnumerator IEnumerable.GetEnumerator()
{
return List.GetEnumerator();
}
/// <summary>
/// Gets the number of items in the list.
/// </summary>
public Int32 Count
{
get { return List.Count; }
}
/// <summary>
/// Gets the first node of the linked list.
/// </summary>
public LinkedListNode<T> First
{
get { return List.First; }
}
/// <summary>
/// Gets the last node of the linked list.
/// </summary>
public LinkedListNode<T> Last
{
get { return List.Last; }
}
/// <summary>
/// Retrieves a node from the list's pool of nodes.
/// </summary>
/// <returns>The node that was retrieved.</returns>
private LinkedListNode<T> RetrieveNode()
{
LinkedListNode<T> node;
if (NodePool.Count == 0)
{
node = new LinkedListNode<T>(default(T));
NodePool.Capacity++;
}
else
{
node = NodePool[NodePool.Count - 1];
NodePool.RemoveAt(NodePool.Count - 1);
}
return node;
}
/// <summary>
/// Releases a node back into the list's pool of nodes.
/// </summary>
/// <param name="node">The node to release.</param>
private void ReleaseNode(LinkedListNode<T> node)
{
node.Value = default(T);
NodePool.Add(node);
}
// The underlying linked list and its pool of nodes.
private readonly LinkedList<T> List = new LinkedList<T>();
private readonly List<LinkedListNode<T>> NodePool;
}
}
|
using System;
using System.Collections.Generic;
namespace I9OpenWebApi.Models
{
public partial class Usuario
{
public Usuario()
{
Comercio = new HashSet<Comercio>();
Plano = new HashSet<Plano>();
}
public int IdUsuario { get; set; }
public string Nome { get; set; }
public string Rg { get; set; }
public string Cpf { get; set; }
public string Telefone { get; set; }
public string Email { get; set; }
public string Senha { get; set; }
public int FkTipoUsuario { get; set; }
public TipoUsuario FkTipoUsuarioNavigation { get; set; }
public ICollection<Comercio> Comercio { get; set; }
public ICollection<Plano> Plano { get; set; }
}
}
|
namespace AdjustNamespace.Xaml
{
public interface IXmlnsProvider
{
XamlXmlns GetByAlias(string alias);
XamlXmlns? TryGetByNamespace(string @namespace);
XamlX GetXPrefix();
}
}
|
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
[CreateAssetMenu(fileName = "Processor", menuName = "Interactable/Processor")]
public class Processor : ScriptableObject
{
public List<Recipe> Recipes;
public Recipe FindProcessableRecipe(IEnumerable<Item> items)
{
foreach (var recipe in Recipes)
{
return FindMatchingRecipeWithInventoryContent(items, recipe);
}
return null;
}
public void Process(Inventory inventory, Recipe recipeToCraft)
{
RemoveRecipeFromInventory(inventory, recipeToCraft);
AddNewItemToInventory(inventory, recipeToCraft);
}
private static Recipe FindMatchingRecipeWithInventoryContent(IEnumerable<Item> items, Recipe recipe)
{
var invItemsCopy = new LinkedList<Item>(items);
foreach (var requiredItem in recipe.RequiredItems)
{
if (ItemNotFoundInCollection(invItemsCopy, requiredItem)) return null;
}
return recipe;
}
private static bool ItemNotFoundInCollection(ICollection<Item> invItemsCopy, Item requiredItem)
{
var foundItem = invItemsCopy.FirstOrDefault(invItem =>
requiredItem.Name.Equals(invItem.Name));
if (foundItem == null) return true;
invItemsCopy.Remove(foundItem);
return false;
}
private static void RemoveRecipeFromInventory(Inventory inventory, Recipe recipeToCraft)
{
var invItemsCopy = new List<Item>(inventory.Contents);
RemoveRecipeItemsFromCollection(invItemsCopy, recipeToCraft);
inventory.CreateMatchingListWith(invItemsCopy);
}
private static void RemoveRecipeItemsFromCollection(ICollection<Item> invItemsCopy, Recipe recipeToCraft)
{
foreach (var requiredItem in recipeToCraft.RequiredItems)
{
var foundItem = invItemsCopy.FirstOrDefault(invItem =>
requiredItem.Name.Equals(invItem.Name));
invItemsCopy.Remove(foundItem);
}
}
private static void AddNewItemToInventory(Inventory inventory, Recipe recipeToCraft)
{
inventory.Push(recipeToCraft.Output.Copy());
}
} |
using System;
public class WhereFieldIsDisposableClassArray :
IDisposable
{
public Disposable[] Field = new Disposable[0];
public void Dispose()
{
}
public class Disposable : IDisposable
{
public void Dispose()
{
}
}
} |
using Hudl.FFmpeg.Settings.Attributes;
using Hudl.FFmpeg.Settings.Interfaces;
namespace Hudl.FFprobe.Settings
{
[Setting(Name = "show_frames", IsParameterless = true)]
public class ShowFrames : ISetting
{
}
}
|
using System.ComponentModel;
namespace Xamarin.Forms.Platform.WinPhone
{
public class ActivityIndicatorRenderer : ViewRenderer<ActivityIndicator, System.Windows.Controls.ProgressBar>
{
protected override void OnElementChanged(ElementChangedEventArgs<ActivityIndicator> e)
{
base.OnElementChanged(e);
SetNativeControl(new System.Windows.Controls.ProgressBar());
Control.IsIndeterminate = Element.IsRunning;
UpdateColor();
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (e.PropertyName == ActivityIndicator.IsRunningProperty.PropertyName)
Control.IsIndeterminate = Element.IsRunning;
else if (e.PropertyName == ActivityIndicator.ColorProperty.PropertyName)
UpdateColor();
}
void UpdateColor()
{
Color color = Element.Color;
if (color == Color.Default)
Control.ClearValue(System.Windows.Controls.Control.ForegroundProperty);
else
Control.Foreground = color.ToBrush();
}
}
} |
using System;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
using Nexinho.Models;
namespace Nexinho.Gateways;
public class ChuckGateway : IChuckGateway
{
private readonly HttpClient httpClient;
public ChuckGateway(HttpClient httpClient)
{
this.httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient));
}
public async Task<ChuckJoke> Get()
{
try
{
var responseString = await httpClient.GetStringAsync(httpClient.BaseAddress);
var joke = JsonSerializer.Deserialize<ChuckJoke>(responseString);
return joke;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return null;
}
}
public Task<ChuckJoke> GetByCategory(string category)
{
throw new NotImplementedException();
}
}
|
namespace _2PAC.WebApp.WebAPIModel
{
public class W_Score
{
public int ScoreId {get; set;}
public int UserId {get; set;}
public string Username {get; set;}
public int GameId {get; set;}
public string GameName {get; set;}
public double Score {get; set;}
}
} |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using Microsoft.Azure.Management.Internal.Resources.Utilities.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System.Collections.Generic;
namespace Microsoft.Azure.Commands.Aks.Models
{
public class PSKubernetesCluster : PSResource
{
/// <summary>
/// Initializes a new instance of the ManagedCluster class.
/// </summary>
/// <param name="location">Resource location</param>
/// <param name="id">Resource Id</param>
/// <param name="name">Resource name</param>
/// <param name="type">Resource type</param>
/// <param name="tags">Resource tags</param>
/// <param name="provisioningState">The current deployment or
/// provisioning state, which only appears in the response.</param>
/// <param name="dnsPrefix">DNS prefix specified when creating the
/// managed cluster.</param>
/// <param name="fqdn">FDQN for the master pool.</param>
/// <param name="kubernetesVersion">Version of Kubernetes specified
/// when creating the managed cluster.</param>
/// <param name="agentPoolProfiles">Properties of the agent
/// pool.</param>
/// <param name="linuxProfile">Profile for Linux VMs in the container
/// service cluster.</param>
/// <param name="servicePrincipalProfile">Information about a service
/// principal identity for the cluster to use for manipulating Azure
/// APIs. Either secret or keyVaultSecretRef must be specified.</param>
public PSKubernetesCluster(string location, string id = default(string), string name = default(string),
string type = default(string), IDictionary<string, string> tags = default(IDictionary<string, string>),
string provisioningState = default(string), string dnsPrefix = default(string),
string fqdn = default(string), string kubernetesVersion = default(string),
IList<PSContainerServiceAgentPoolProfile> agentPoolProfiles =
default(IList<PSContainerServiceAgentPoolProfile>),
PSContainerServiceLinuxProfile linuxProfile = default(PSContainerServiceLinuxProfile),
PSContainerServiceServicePrincipalProfile servicePrincipalProfile =
default(PSContainerServiceServicePrincipalProfile))
: base(location, id, name, type, tags)
{
ProvisioningState = provisioningState;
DnsPrefix = dnsPrefix;
Fqdn = fqdn;
KubernetesVersion = kubernetesVersion;
AgentPoolProfiles = agentPoolProfiles;
LinuxProfile = linuxProfile;
ServicePrincipalProfile = servicePrincipalProfile;
}
/// <summary>
/// Gets the current deployment or provisioning state, which only
/// appears in the response.
/// </summary>
public string ProvisioningState { get; private set; }
/// <summary>
/// Gets the max number of agent pools for the managed cluster.
/// </summary>
public int? MaxAgentPools { get; private set; }
/// <summary>
/// Gets or sets version of Kubernetes specified when creating the
/// managed cluster.
/// </summary>
public string KubernetesVersion { get; set; }
/// <summary>
/// Gets or sets DNS prefix specified when creating the managed
/// cluster.
/// </summary>
public string DnsPrefix { get; set; }
/// <summary>
/// Gets FQDN for the master pool.
/// </summary>
public string Fqdn { get; private set; }
/// <summary>
/// Gets FQDN of private cluster.
/// </summary>
public string PrivateFQDN { get; private set; }
/// <summary>
/// Gets or sets properties of the agent pool.
/// </summary>
public IList<PSContainerServiceAgentPoolProfile> AgentPoolProfiles { get; set; }
/// <summary>
/// Gets or sets profile for Windows VMs in the container service
/// cluster.
/// </summary>
public PSManagedClusterWindowsProfile WindowsProfile { get; set; }
/// <summary>
/// Gets or sets profile of managed cluster add-on.
/// </summary>
public IDictionary<string, PSManagedClusterAddonProfile> AddonProfiles { get; set; }
/// <summary>
/// Gets or sets name of the resource group containing agent pool
/// nodes.
/// </summary>
public string NodeResourceGroup { get; set; }
/// <summary>
/// Gets or sets whether to enable Kubernetes Role-Based Access
/// Control.
/// </summary>
public bool? EnableRBAC { get; set; }
/// <summary>
/// Gets or sets (PREVIEW) Whether to enable Kubernetes Pod security
/// policy.
/// </summary>
public bool? EnablePodSecurityPolicy { get; set; }
/// <summary>
/// Gets or sets profile of network configuration.
/// </summary>
public PSContainerServiceNetworkProfile NetworkProfile { get; set; }
/// <summary>
/// Gets or sets profile of Azure Active Directory configuration.
/// </summary>
public PSManagedClusterAadProfile AadProfile { get; set; }
/// <summary>
/// Gets or sets access profile for managed cluster API server.
/// </summary>
public PSManagedClusterAPIServerAccessProfile ApiServerAccessProfile { get; set; }
//
// Summary:
// Gets or sets identities associated with the cluster.
public IDictionary<string, PSManagedClusterPropertiesIdentityProfile> IdentityProfile { get; set; }
/// <summary>
/// Gets or sets the identity of the managed cluster, if configured.
/// </summary>
public PSManagedClusterIdentity Identity { get; set; }
/// <summary>
/// Gets or sets profile for Linux VMs in the container service
/// cluster.
/// </summary>
public PSContainerServiceLinuxProfile LinuxProfile { get; set; }
/// <summary>
/// Gets or sets information about a service principal identity for the
/// cluster to use for manipulating Azure APIs. Either secret or
/// keyVaultSecretRef must be specified.
/// </summary>
public PSContainerServiceServicePrincipalProfile ServicePrincipalProfile { get; set; }
/// <summary>
/// Gets the ResourceGroupName from ResourceId.
/// </summary>
public string ResourceGroupName
{
get
{
var resource = new ResourceIdentifier(Id);
return resource.ResourceGroupName;
}
}
/// <summary>
/// This is used by pipeline to autorest based cmdlets.
/// </summary>
/// <returns></returns>
public string ToJsonString()
{
DefaultContractResolver contractResolver = new DefaultContractResolver
{
NamingStrategy = new CamelCaseNamingStrategy()
};
return JsonConvert.SerializeObject(this, new JsonSerializerSettings
{
ContractResolver = contractResolver,
Formatting = Formatting.Indented
});
}
}
} |
using System;
using NUnit.Framework;
using SaG.GuidReferences;
using SaG.SaveSystem.GameStateManagement;
using UnityEngine;
namespace SaG.SaveSystem.Tests
{
public class SaveableTests
{
// A Test behaves as an ordinary method
[Test]
public void Id_ReturnsGuidId()
{
var go = new GameObject("test saveable game object");
go.SetActive(false);
var saveable = go.AddComponent<Saveable>();
var guidProvider = go.GetComponent<GuidComponent>();
var guid = Guid.NewGuid();
guidProvider.SetGuid(guid);
Assert.AreEqual(guid.ToString(), saveable.Id);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Moki11so.Shared.Reporting
{
public enum ReportType
{
AmeiseError = 1000,
AmeiseImportError = 1001,
WorkerError = 1010,
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Leap.Unity;
using LeapInternal;
public class GetLeapImage : MonoBehaviour{
private LeapServiceProvider _provider;
// private Controller _controller;
private void Awake()
{
// _provider = GetComponent<LeapServiceProvider>();
// _controller = _provider.GetLeapController();
// _controller.ImageReady += OnImageReady;
// _provider.Image.Undistort();
}
} |
using LagoVista.Core.IOC;
using LagoVista.Core.PlatformSupport;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LagoVista.PickAndPlace.Models
{
public partial class HeightMap
{
public async Task SaveAsync()
{
if (!String.IsNullOrEmpty(_fileName))
{
var popupService = SLWIOC.Get<IPopupServices>();
_fileName = await popupService.ShowSaveFileAsync(Constants.FileFilterHeightMap);
}
if (!String.IsNullOrEmpty(_fileName))
{
await Core.PlatformSupport.Services.Storage.StoreAsync(this, _fileName);
}
}
public async Task SaveAsAsync()
{
var popupService = SLWIOC.Get<IPopupServices>();
_fileName = await popupService.ShowSaveFileAsync(Constants.FileFilterHeightMap);
if (!String.IsNullOrEmpty(_fileName))
{
await Core.PlatformSupport.Services.Storage.StoreAsync(this, _fileName);
}
}
public static async Task<HeightMap> OpenAsync(MachineSettings settings)
{
var popupService = SLWIOC.Get<IPopupServices>();
var fileName = await popupService.ShowSaveFileAsync(Constants.FileFilterHeightMap);
if (fileName != null)
{
var heightMap = await Core.PlatformSupport.Services.Storage.GetAsync<HeightMap>(fileName);
heightMap.Refresh();
return heightMap;
}
else
{
return null;
}
}
}
}
|
#region Copyright
// Copyright Hitachi Consulting
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
#region using
using System;
using System.Security.Principal;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Xigadee
{
/// <summary>
/// This class allows you to connect to a persistence server command using the default actions with remote server capability and timeout support.
/// </summary>
/// <typeparam name="K">The key type.</typeparam>
/// <typeparam name="E">The entity type.</typeparam>
public class PersistenceClient<K, E> : PersistenceClientBase<K, E, PersistenceClientPolicy>
, IPersistenceMessageInitiator
where K : IEquatable<K>
{
#region Constructor
/// <summary>
/// This is the default constructor. This set the default routing to external only.
/// </summary>
public PersistenceClient(ICacheManager<K, E> cacheManager = null, TimeSpan? defaultRequestTimespan = null)
: base(cacheManager, defaultRequestTimespan)
{
RoutingDefault = ProcessOptions.RouteExternal;
}
#endregion
#region EntityType
/// <summary>
/// This is the entity type for the commands
/// </summary>
public virtual string EntityType
{
get
{
return typeof(E).Name;
}
}
#endregion
#region ResponseId
/// <summary>
/// This is the MessageFilterWrapper for the payloadRs message channel. This will pick up all reponse messages of the specific type
/// for this instance and pipe them to be processed.
/// </summary>
protected override MessageFilterWrapper ResponseId
{
get { return new MessageFilterWrapper(new ServiceMessageHeader(ResponseChannelId, EntityType),OriginatorId.ExternalServiceId ); }
}
#endregion
#region RoutingDefault
/// <summary>
/// This is the default routing for outgoing messages.
/// By default messages will try external providers.
/// </summary>
public ProcessOptions? RoutingDefault { get; set; }
#endregion
#region TransmitInternal<KT, ET>(string actionType, RepositoryHolder<KT, ET> rq)
/// <summary>
/// This method marshals the RepositoryHolder and transmits it to the remote Microservice.
/// </summary>
/// <typeparam Name="KT">The key type.</typeparam>
/// <typeparam Name="ET">The entity type.</typeparam>
/// <param Name="actionType">The action type.</param>
/// <param Name="rq">The repository holder request.</param>
/// <returns>Returns an async task that will be signalled when the request completes or times out.</returns>
protected override async Task<RepositoryHolder<KT, ET>> TransmitInternal<KT, ET>(
string actionType, RepositoryHolder<KT, ET> rq, ProcessOptions? routing = null, IPrincipal principal = null)
{
try
{
StatisticsInternal.ActiveIncrement();
var payload = TransmissionPayload.Create(Policy.TransmissionPayloadTraceEnabled);
payload.SecurityPrincipal = TransmissionPayload.ConvertToClaimsPrincipal(principal ?? Thread.CurrentPrincipal);
// Set the process correlation key to the correlation id if passed through the rq settings
if (!string.IsNullOrEmpty(rq.Settings?.CorrelationId))
payload.Message.ProcessCorrelationKey = rq.Settings.CorrelationId;
bool processAsync = rq.Settings?.ProcessAsync ?? false;
payload.Message.ChannelPriority = processAsync ? 0 : 1;
payload.Options = routing ?? RoutingDefault ?? ProcessOptions.RouteExternal;
payload.Message.Holder = ServiceHandlerContext.CreateWithObject(rq);
payload.Message.ResponseChannelId = ResponseChannelId;
payload.Message.ResponseChannelId = ResponseId.Header.ChannelId;
payload.Message.ResponseMessageType = ResponseId.Header.MessageType;
payload.Message.ResponseActionType = ResponseId.Header.ActionType;
payload.Message.ResponseChannelPriority = payload.Message.ChannelPriority;
payload.Message.ChannelId = ChannelId;
payload.Message.MessageType = EntityType;
payload.Message.ActionType = actionType;
payload.MaxProcessingTime = rq.Settings?.WaitTime ?? mDefaultRequestTimespan;
return await OutgoingRequestOut(payload, ProcessResponse<KT, ET>, processAsync);
}
catch (Exception ex)
{
string key = rq != null && rq.Key != null ? rq.Key.ToString() : string.Empty;
Collector?.LogException($"Error transmitting {actionType}-{key} internally", ex);
throw;
}
}
#endregion
}
}
|
using UnityEngine;
public class ShootingScript : MonoBehaviour
{
// Bullet object for instantiating on shooting.
public BulletScript BulletPrefab;
// A bullet is spawned for each shooting point defined here. No shooting points mean no shooting.
public Transform[] Barrels;
// Time between shots (in seconds).
public float ShootInterval = 0.2f;
// If true, shooting immediately from all shooting points, if false - from next unfired.
public bool AlternateFire = false;
// Current alternate shooting barrel;
int CurrentShooterIndex = 0;
// Counts time from last shot.
float LastShotTime;
void Awake()
{
Debug.Assert(Barrels.Length > 0);
}
void Update()
{
LastShotTime += Time.deltaTime;
ProcessInput();
}
void ProcessInput()
{
InputData input = InputManager.Instance.GetInput();
if (input.Shooting == true && LastShotTime >= ShootInterval)
{
LastShotTime = 0.0f;
Shoot(Barrels, BulletPrefab);
}
}
// Shoots from barrels.
void Shoot(Transform[] points, BulletScript prefab)
{
if (AlternateFire == false)
{
foreach (Transform point in points)
{
ShootFromPoint(point, prefab);
}
}
else
{
ShootFromPoint(points[CurrentShooterIndex], prefab);
CurrentShooterIndex++;
if (CurrentShooterIndex >= Barrels.Length)
{
CurrentShooterIndex = 0;
}
}
}
// Spawns and launches a bullet.
void ShootFromPoint(Transform point, BulletScript prefab)
{
Debug.Assert(point);
Debug.Assert(prefab != null);
BulletScript bullet = Instantiate(prefab);
bullet.transform.position = point.position;
bullet.transform.rotation = transform.rotation;
bullet.Shoot();
}
}
|
using System;
using UnityEngine;
public static class TransformExtensions
{
// Useful for cleaning up scroll group contents
public static void DetachAndDestroyChildren(this Transform transform)
{
int total = transform.childCount;
for (int i = total-1; i >= 0; i--)
{
GameObject.Destroy(transform.GetChild(i).gameObject);
}
}
// This is used to fit scrollview transforms to the length of their children.
public static void FitToChildLength(this RectTransform rt, float buffer = 0.0f )
{
if (rt.childCount > 0)
{
var lastChild = rt.GetChild(rt.childCount - 1) as RectTransform;
if (lastChild != null)
{
float lastY = lastChild.position.y + lastChild.sizeDelta.y + buffer;
rt.sizeDelta = new Vector2(rt.sizeDelta.x, lastY);
}
}
}
}
|
namespace DotNetCore.CAP.Plus
{
public class PlusOptions
{
public const int DEFAULT_RESUME_FETCH_COUNT = 1000;
public const int DEFAULT_RETRY_FETCH_COUNT = 1000;
public const int DEFAULT_RETRY_IMMEDIATELY_TIMES = 3;
public const int DEFAULT_IDLE_INTERVAL = 10;
public int IdleInterval { get; set; } = DEFAULT_IDLE_INTERVAL;
public int ResumePreFetchCount { get; set; } = DEFAULT_RESUME_FETCH_COUNT;
public int RetryPreFetchCount { get; set; } = DEFAULT_RETRY_FETCH_COUNT;
public int RetryImmediatelyTimes { get; set; } = DEFAULT_RETRY_IMMEDIATELY_TIMES;
private int[] _failRetryIntervals;
public int[] FailRetryIntervals
{
get
{
if (_failRetryIntervals == null || _failRetryIntervals.Length == 0)
{
int[] defaultIntervals = new int[] { 10, 20, 30, 40, 50 };
_failRetryIntervals = defaultIntervals;
}
return _failRetryIntervals;
}
set { _failRetryIntervals = value; }
}
}
} |
using System.Collections.Generic;
using System.Threading.Tasks;
using Apollo.Core.Dto;
using Apollo.Core.Validation;
namespace Apollo.Core.Interfaces
{
public interface IReservationService
{
void AddRule(ISeatValidation validationRule);
void UseDefaultRules();
void ClearRules();
Task<ReservationDto> AddReservationAsync(IEnumerable<SeatDto> seatDtos, long scheduleId, long userId);
Task<IEnumerable<ReservationDto>> GetReservationsAsync();
Task<IEnumerable<ReservationDto>> GetReservationsByUserIdAsync(long userId);
Task<IEnumerable<ReservationDto>> GetReservationsByScheduleIdAsync(long scheduleId);
Task<int> GetCountReservationsByCinemaHallAsync(long cinemaHallId);
Task<bool> DeleteReservationsAsync(IEnumerable<ReservationDto> reservations);
Task<bool> DeleteReservationsAsync(IEnumerable<long> reservationIds);
Task<bool> DeleteReservationAsync(ReservationDto reservation);
Task<bool> DeleteReservationAsync(long reservationId);
void ApplyValidation(IEnumerable<SeatDto> seatDtos, IEnumerable<SeatDto> seatLayout);
Task<IEnumerable<TicketDto>> GetTicketsAsync();
Task<IEnumerable<TicketDto>> GetTicketsByUserIdAsync(long userId);
Task<IEnumerable<SeatReservationDto>> GetSeatReservationsAsync();
Task<ReservationDto> GetReservationByIdAsync(long reservationId);
Task<IEnumerable<SeatReservationDto>> GetSeatReservationsByUserIdAsync(long userId);
Task UpdateReservation(ReservationDto reservationDto, IList<SeatDto> selectedSeats);
}
}
|
namespace PMF.RecurrenceDay.Enums
{
/// <summary>
/// Day type
/// </summary>
public enum DayType
{
/// <summary>
/// The sunday
/// </summary>
Sunday,
/// <summary>
/// The monday
/// </summary>
Monday,
/// <summary>
/// The tuesday
/// </summary>
Tuesday,
/// <summary>
/// The wednesday
/// </summary>
Wednesday,
/// <summary>
/// The thursday
/// </summary>
Thursday,
/// <summary>
/// The friday
/// </summary>
Friday,
/// <summary>
/// The saturday
/// </summary>
Saturday,
/// <summary>
/// The day
/// </summary>
Day,
/// <summary>
/// The week day
/// </summary>
WeekDay,
/// <summary>
/// The weekend day
/// </summary>
WeekendDay,
}
} |
using System;
using System.Collections.Generic;
using System.Net;
#if !CompactFramework
using System.Net.NetworkInformation;
#else
using OpenNETCF.Net.NetworkInformation;
#endif
namespace PipBenchmark.Hardware
{
public class NetworkBenchmarkSuite : BenchmarkSuite
{
private Parameter _destinationAddress;
private Parameter _pingPacketSize;
private Parameter _pingTimeout;
private object _syncRoot = new object();
private Ping _ping;
private byte[] _pingBuffer;
private int _pingTimeoutValue;
private IPAddress _destinationIP;
public NetworkBenchmarkSuite()
: base("Network", "Benchmark for network")
{
InitializeConfigurationParameters();
InitializeTests();
}
private void InitializeConfigurationParameters()
{
_destinationAddress = CreateParameter("DestinationAddress", "Address of the remote host", "localhost");
_pingPacketSize = CreateParameter("PingPacketSize", "Size of ping packets in bytes", "32");
_pingTimeout = CreateParameter("PingTimeout", "Ping timeout in msecs", "3000");
}
private void InitializeTests()
{
CreateBenchmark("Ping", "Measures network pings", ExecutePing);
}
public string DestinationAddress
{
get { return _destinationAddress.AsString; }
}
public int PingPacketSize
{
get { return _pingPacketSize.AsInteger; }
}
public int PingTimeout
{
get { return _pingTimeout.AsInteger; }
}
public override void SetUp()
{
_ping = new Ping();
_pingBuffer = new byte[PingPacketSize];
_destinationIP = Dns.GetHostEntry(DestinationAddress).AddressList[0];
_pingTimeoutValue = PingTimeout;
}
public override void TearDown()
{
}
public void ExecutePing()
{
lock (_syncRoot)
{
try
{
#if !CompactFramework
_ping.Send(_destinationIP, _pingTimeoutValue, _pingBuffer, new PingOptions());
#else
_ping.Send(_destinationIP, _pingBuffer, _pingTimeoutValue, new PingOptions());
#endif
}
catch (PingException)
{
// Ignore exception;
}
}
}
}
}
|
// CS0106: The modifier `async' is not valid for this item
// Line: 6
// Compiler options: -langversion:future
interface I
{
async void M ();
}
|
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Sharpenchat.Core.Serialization;
namespace Sharpenchat.Payment
{
public class UnifiedOrderRequest
{
[FieldName("appid"), Required, MaxLength(32)]
internal string AppId { get; set; }
[FieldName("mch_id"), Required, MaxLength(32)]
internal string MchId { get; set; }
[FieldName("nonce_str"), Required, MaxLength(32)]
internal string NonceStr { get; set; }
[FieldName("sign"), Required, MaxLength(32)]
internal string Sign { get; set; }
[FieldName("sign_type")]
internal string SignType { get; set; }
[Ignore]
internal SignType EmbedSignType { get; set; }
[FieldName("attach"), MaxLength(127)]
public string Attach { get; set; }
[FieldName("body"), Required, MaxLength(128)]
public string Body { get; set; }
[FieldName("device_info")]
public string DeviceInfo { get; set; }
[FieldName("fee_type"), MaxLength(16)]
public string FeeType { get; set; }
[Ignore]
public FeeType EmbedFeeType { get; set; }
[FieldName("goods_tag"), MaxLength(32)]
public string GoodsTag { get; set; }
[FieldName("limit_pay"), MaxLength(32)]
internal string LimitPay { get; set; }
[Ignore]
public LimitPay EmbedLimitPay { get; set; }
[FieldName("notify_url"), Required, MaxLength(256)]
public string NotifyUrl { get; set; }
[FieldName("out_trade_no"), Required, MaxLength(32)]
public string OutTradeNo { get; set; }
[FieldName("spbill_create_ip"), Required, MaxLength(16)]
public string SpbillCreateIp { get; set; }
[FieldName("time_expire"), Required, MaxLength(14)]
public string TimeExpire { get; set; }
[FieldName("time_start"), Required, MaxLength(14)]
public string TimeStart { get; set; }
[FieldName("total_fee")]
public int TotalFee { get; set; }
[FieldName("trade_type"), Required, MaxLength(16)]
internal string TradeType { get; set; }
[Ignore]
public TradeType EmbedTradeType { get; set; }
[FieldName("detail")]
internal string Detail { get; set; }
[Ignore]
public UnifiedOrderDetail EmbedDetail { get; set; }
[FieldName("product_id"), MaxLength(32)]
public string ProductId { get; set; }
[FieldName("openid"), MaxLength(128)]
public string OpenId { get; set; }
internal void Preparing(PaymentContext paymentContext) {
if (EmbedTradeType == null) {
throw new ValidationException("trade_type is required");
}
if (EmbedDetail != null) {
Detail = paymentContext.JsonSerializer.SerializeSync(EmbedDetail);
}
SignType = EmbedSignType?.ToString();
FeeType = EmbedFeeType?.ToString();
LimitPay = EmbedLimitPay?.ToString();
TradeType = EmbedTradeType?.ToString();
AppId = paymentContext.AppId;
MchId = paymentContext.MchId;
}
}
public class UnifiedOrderDetail
{
public UnifiedOrderDetail() {
GoodsDetail = new List<GoodsDetail>();
}
[Required, FieldName("goods_detail")]
public IList<GoodsDetail> GoodsDetail { get; set; }
#region jsapi & native
public int? cost_price { get; set; }
[MaxLength(32)]
public string receipt_id { get; set; }
#endregion
}
public class GoodsDetail
{
[FieldName("goods_id"), Required, MaxLength(32)]
public string GoodsId { get; set; }
[FieldName("goods_name"), Required, MaxLength(256)]
public string GoodsName { get; set; }
[FieldName("price")]
public int Price { get; set; }
[FieldName("quantity")]
public int Quantity { get; set; }
[FieldName("wxpay_goods_id"), Required, MaxLength(32)]
public string WxpayGoodsId { get; set; }
#region app
[FieldName("goods_category"), MaxLength(32)]
public string GoodsCategory { get; set; }
[FieldName("body"), MaxLength(1000)]
public string Body { get; set; }
#endregion
}
public class SignType
{
private readonly string _typeValue;
private SignType(string typeValue) {
_typeValue = typeValue;
}
public static SignType Md5 => new SignType("MD5");
public static SignType HmacSha256 => new SignType("HMAC-SHA256");
public override string ToString() {
return _typeValue;
}
}
public class TradeType
{
private readonly string _typeValue;
private TradeType(string typeValue) {
_typeValue = typeValue;
}
public static TradeType App => new TradeType("APP");
public static TradeType Jsapi => new TradeType("JSAPI");
public static TradeType Native => new TradeType("NATIVE");
public override string ToString() {
return _typeValue;
}
}
public class FeeType
{
private readonly string _typeValue;
private FeeType(string typeValue) {
_typeValue = typeValue;
}
public static FeeType Cny => new FeeType("CNY");
public override string ToString() {
return _typeValue;
}
}
public class LimitPay
{
private readonly string _typeValue;
private LimitPay(string typeValue) {
_typeValue = typeValue;
}
public static LimitPay NoCredit => new LimitPay("no_credit");
public override string ToString() {
return _typeValue;
}
}
} |
using System;
using Microsoft.EntityFrameworkCore.Migrations;
namespace Hangfire.EntityFrameworkCore.AspNetCoreExternalDbContext.Migrations
{
public partial class Initial : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "HangfireCounter",
columns: table => new
{
Id = table.Column<long>(type: "INTEGER", nullable: false)
.Annotation("Sqlite:Autoincrement", true),
Key = table.Column<string>(type: "TEXT", maxLength: 100, nullable: false),
Value = table.Column<long>(type: "INTEGER", nullable: false),
ExpireAt = table.Column<DateTime>(type: "TEXT", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_HangfireCounter", x => x.Id);
});
migrationBuilder.CreateTable(
name: "HangfireHash",
columns: table => new
{
Key = table.Column<string>(type: "TEXT", maxLength: 100, nullable: false),
Field = table.Column<string>(type: "TEXT", maxLength: 100, nullable: false),
Value = table.Column<string>(type: "TEXT", nullable: true),
ExpireAt = table.Column<DateTime>(type: "TEXT", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_HangfireHash", x => new { x.Key, x.Field });
});
migrationBuilder.CreateTable(
name: "HangfireList",
columns: table => new
{
Key = table.Column<string>(type: "TEXT", maxLength: 100, nullable: false),
Position = table.Column<int>(type: "INTEGER", nullable: false),
Value = table.Column<string>(type: "TEXT", nullable: true),
ExpireAt = table.Column<DateTime>(type: "TEXT", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_HangfireList", x => new { x.Key, x.Position });
});
migrationBuilder.CreateTable(
name: "HangfireLock",
columns: table => new
{
Id = table.Column<string>(type: "TEXT", maxLength: 100, nullable: false),
AcquiredAt = table.Column<DateTime>(type: "TEXT", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_HangfireLock", x => x.Id);
});
migrationBuilder.CreateTable(
name: "HangfireServer",
columns: table => new
{
Id = table.Column<string>(type: "TEXT", maxLength: 100, nullable: false),
StartedAt = table.Column<DateTime>(type: "TEXT", nullable: false),
Heartbeat = table.Column<DateTime>(type: "TEXT", nullable: false),
WorkerCount = table.Column<int>(type: "INTEGER", nullable: false),
Queues = table.Column<string>(type: "TEXT", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_HangfireServer", x => x.Id);
});
migrationBuilder.CreateTable(
name: "HangfireSet",
columns: table => new
{
Key = table.Column<string>(type: "TEXT", maxLength: 100, nullable: false),
Value = table.Column<string>(type: "TEXT", maxLength: 100, nullable: false),
Score = table.Column<double>(type: "REAL", nullable: false),
ExpireAt = table.Column<DateTime>(type: "TEXT", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_HangfireSet", x => new { x.Key, x.Value });
});
migrationBuilder.CreateTable(
name: "SampleTables",
columns: table => new
{
Id = table.Column<Guid>(type: "TEXT", nullable: false),
Name = table.Column<string>(type: "TEXT", nullable: true),
Value = table.Column<int>(type: "INTEGER", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_SampleTables", x => x.Id);
});
migrationBuilder.CreateTable(
name: "HangfireJobParameter",
columns: table => new
{
JobId = table.Column<long>(type: "INTEGER", nullable: false),
Name = table.Column<string>(type: "TEXT", maxLength: 40, nullable: false),
Value = table.Column<string>(type: "TEXT", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_HangfireJobParameter", x => new { x.JobId, x.Name });
});
migrationBuilder.CreateTable(
name: "HangfireQueuedJob",
columns: table => new
{
Id = table.Column<long>(type: "INTEGER", nullable: false)
.Annotation("Sqlite:Autoincrement", true),
JobId = table.Column<long>(type: "INTEGER", nullable: false),
Queue = table.Column<string>(type: "TEXT", maxLength: 50, nullable: false),
FetchedAt = table.Column<DateTime>(type: "TEXT", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_HangfireQueuedJob", x => x.Id);
});
migrationBuilder.CreateTable(
name: "HangfireState",
columns: table => new
{
Id = table.Column<long>(type: "INTEGER", nullable: false)
.Annotation("Sqlite:Autoincrement", true),
JobId = table.Column<long>(type: "INTEGER", nullable: false),
Name = table.Column<string>(type: "TEXT", maxLength: 20, nullable: false),
Reason = table.Column<string>(type: "TEXT", maxLength: 100, nullable: true),
CreatedAt = table.Column<DateTime>(type: "TEXT", nullable: false),
Data = table.Column<string>(type: "TEXT", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_HangfireState", x => x.Id);
});
migrationBuilder.CreateTable(
name: "HangfireJob",
columns: table => new
{
Id = table.Column<long>(type: "INTEGER", nullable: false)
.Annotation("Sqlite:Autoincrement", true),
CreatedAt = table.Column<DateTime>(type: "TEXT", nullable: false),
StateId = table.Column<long>(type: "INTEGER", nullable: true),
StateName = table.Column<string>(type: "TEXT", maxLength: 20, nullable: true),
ExpireAt = table.Column<DateTime>(type: "TEXT", nullable: true),
InvocationData = table.Column<string>(type: "TEXT", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_HangfireJob", x => x.Id);
table.ForeignKey(
name: "FK_HangfireJob_HangfireState_StateId",
column: x => x.StateId,
principalTable: "HangfireState",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateIndex(
name: "IX_HangfireCounter_ExpireAt",
table: "HangfireCounter",
column: "ExpireAt");
migrationBuilder.CreateIndex(
name: "IX_HangfireCounter_Key_Value",
table: "HangfireCounter",
columns: new[] { "Key", "Value" });
migrationBuilder.CreateIndex(
name: "IX_HangfireHash_ExpireAt",
table: "HangfireHash",
column: "ExpireAt");
migrationBuilder.CreateIndex(
name: "IX_HangfireJob_ExpireAt",
table: "HangfireJob",
column: "ExpireAt");
migrationBuilder.CreateIndex(
name: "IX_HangfireJob_StateId",
table: "HangfireJob",
column: "StateId");
migrationBuilder.CreateIndex(
name: "IX_HangfireJob_StateName",
table: "HangfireJob",
column: "StateName");
migrationBuilder.CreateIndex(
name: "IX_HangfireList_ExpireAt",
table: "HangfireList",
column: "ExpireAt");
migrationBuilder.CreateIndex(
name: "IX_HangfireQueuedJob_JobId",
table: "HangfireQueuedJob",
column: "JobId");
migrationBuilder.CreateIndex(
name: "IX_HangfireQueuedJob_Queue_FetchedAt",
table: "HangfireQueuedJob",
columns: new[] { "Queue", "FetchedAt" });
migrationBuilder.CreateIndex(
name: "IX_HangfireServer_Heartbeat",
table: "HangfireServer",
column: "Heartbeat");
migrationBuilder.CreateIndex(
name: "IX_HangfireSet_ExpireAt",
table: "HangfireSet",
column: "ExpireAt");
migrationBuilder.CreateIndex(
name: "IX_HangfireSet_Key_Score",
table: "HangfireSet",
columns: new[] { "Key", "Score" });
migrationBuilder.CreateIndex(
name: "IX_HangfireState_JobId",
table: "HangfireState",
column: "JobId");
migrationBuilder.AddForeignKey(
name: "FK_HangfireJobParameter_HangfireJob_JobId",
table: "HangfireJobParameter",
column: "JobId",
principalTable: "HangfireJob",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_HangfireQueuedJob_HangfireJob_JobId",
table: "HangfireQueuedJob",
column: "JobId",
principalTable: "HangfireJob",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_HangfireState_HangfireJob_JobId",
table: "HangfireState",
column: "JobId",
principalTable: "HangfireJob",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_HangfireJob_HangfireState_StateId",
table: "HangfireJob");
migrationBuilder.DropTable(
name: "HangfireCounter");
migrationBuilder.DropTable(
name: "HangfireHash");
migrationBuilder.DropTable(
name: "HangfireJobParameter");
migrationBuilder.DropTable(
name: "HangfireList");
migrationBuilder.DropTable(
name: "HangfireLock");
migrationBuilder.DropTable(
name: "HangfireQueuedJob");
migrationBuilder.DropTable(
name: "HangfireServer");
migrationBuilder.DropTable(
name: "HangfireSet");
migrationBuilder.DropTable(
name: "SampleTables");
migrationBuilder.DropTable(
name: "HangfireState");
migrationBuilder.DropTable(
name: "HangfireJob");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TrainEngine.Trains
{
public class Train : ITrain, ITrainPosition
{
public int Id { get; set; }
public string Name { get; set; }
public int MaxSpeed { get; set; }
public bool Operated { get; set; }
public List<Passanger> CurrentPassangers { get; set; }
public int MaxPassengersCount { get; set; }
public bool IsMoving { get; set; }
public string CurrentDestination { get; set; }
public bool IsAtStation { get; set; }
public Train() { }
public Train(int id)
{
Id = id;
}
public Train(int id, string name, int maxSpeed, bool operated)
{
Id = id;
Name = name;
MaxSpeed = maxSpeed;
Operated = operated;
CurrentPassangers = new List<Passanger>();
}
public void UpdatePassengers(List<Passanger> GettingOnPassengers, List<Passanger> GettingOffPassengers)
{
foreach (Passanger passenger in GettingOnPassengers)
{
if (CurrentPassangers.Count < MaxPassengersCount)
CurrentPassangers.Add(passenger);
else throw new Exception();
}
foreach (Passanger passenger in GettingOffPassengers)
{
//if (CurrentPassangers.Any(p => p.Id == passenger.Id))
if (CurrentPassangers.Contains(passenger))
CurrentPassangers.Remove(passenger);
}
}
public void UpdateTrainPosition(ITrainPosition trainPosition)
{
IsMoving = trainPosition.IsMoving;
CurrentDestination = trainPosition.CurrentDestination;
IsAtStation = trainPosition.IsAtStation;
}
}
} |
namespace Cryptography.Obfuscation
{
/// <summary>
/// The obfuscation strategy to use.
/// </summary>
public enum ObfuscationStrategy
{
/// <summary>
/// With the same Seed value,
/// Constant mode will always generate the same obfuscated string for a particular number.
/// </summary>
Constant,
/// <summary>
/// Regardless of Seed value,
/// Randomized mode will generate randomized obfuscated string for a particular number,
/// All of which will still map the same number.
/// </summary>
Randomize
}
} |
using BrawlLib.Internal;
using BrawlLib.SSBB.Types;
using System.ComponentModel;
namespace BrawlLib.SSBB.ResourceNodes
{
public unsafe class MVPMNode : ARCEntryNode
{
internal Parameter* Header => (Parameter*) WorkingUncompressed.Address;
//public override ResourceType ResourceFileType => ResourceType.ADPM;
public override bool OnInitialize()
{
base.OnInitialize();
return Header->_count > 0;
}
protected override string GetName()
{
return base.GetName("Movie Parameters");
}
private const int _entrySize = 88;
public override void OnPopulate()
{
for (int i = 0; i < Header->_count; i++)
{
new MVPMEntryNode().Initialize(this, new DataSource((*Header)[i], _entrySize));
}
}
public override int OnCalculateSize(bool force)
{
return 0x10 + Children.Count * 4 + Children.Count * _entrySize;
}
public override void OnRebuild(VoidPtr address, int length, bool force)
{
Parameter* header = (Parameter*) address;
*header = new Parameter(Parameter.TagMVPM, Children.Count);
uint offset = (uint) (0x10 + Children.Count * 4);
for (int i = 0; i < Children.Count; i++)
{
ResourceNode r = Children[i];
*(buint*) (address + 0x10 + i * 4) = offset;
r.Rebuild(address + offset, _entrySize, true);
offset += _entrySize;
}
}
internal static ResourceNode TryParse(DataSource source, ResourceNode parent)
{
return ((Parameter*) source.Address)->_tag == Parameter.TagMVPM ? new MVPMNode() : null;
}
}
public unsafe class MVPMEntryNode : ResourceNode
{
internal MovParameterEntry* Header => (MovParameterEntry*) WorkingUncompressed.Address;
public override ResourceType ResourceFileType => ResourceType.Unknown;
private ParameterValueManager _values = new ParameterValueManager(null);
[Category("MVPM Values")]
public short ID
{
get => _values.GetShort(0, 0);
set
{
_values.SetShort(0, 0, value);
SignalPropertyChange();
}
}
[Category("MVPM Values")]
public short Value1b
{
get => _values.GetShort(0, 1);
set
{
_values.SetShort(0, 1, value);
SignalPropertyChange();
}
}
[Category("MVPM Values")]
[Description("The frame at which the first character name card (first texture in Model Data [1]) is displayed")]
public int CharacterNameCardDisplay1
{
get => _values.GetInt(1);
set
{
_values.SetInt(1, value);
SignalPropertyChange();
}
}
[Category("MVPM Values")]
public int Value3
{
get => _values.GetInt(2);
set
{
_values.SetInt(2, value);
SignalPropertyChange();
}
}
[Category("MVPM Values")]
[Description("The amount of frames that the first character name card stays out for after being displayed")]
public int CharacterNameCardDisplayLength1
{
get => _values.GetInt(3);
set
{
_values.SetInt(3, value);
SignalPropertyChange();
}
}
[Category("MVPM Values")]
public int Value5
{
get => _values.GetInt(4);
set
{
_values.SetInt(4, value);
SignalPropertyChange();
}
}
[Category("MVPM Values")]
[Description("The frame at which the second character name card (second texture in Model Data [1]) is displayed")]
public int CharacterNameCardDisplay2
{
get => _values.GetInt(5);
set
{
_values.SetInt(5, value);
SignalPropertyChange();
}
}
[Category("MVPM Values")]
public int Value7
{
get => _values.GetInt(6);
set
{
_values.SetInt(6, value);
SignalPropertyChange();
}
}
[Category("MVPM Values")]
[Description("The amount of frames that the second character name card stays out for after being displayed")]
public int CharacterNameCardDisplayLength2
{
get => _values.GetInt(7);
set
{
_values.SetInt(7, value);
SignalPropertyChange();
}
}
[Category("MVPM Values")]
public int Value9
{
get => _values.GetInt(8);
set
{
_values.SetInt(8, value);
SignalPropertyChange();
}
}
[Category("MVPM Values")]
[Description("The frame at which the third character name card (third texture in Model Data [1]) is displayed")]
public int CharacterNameCardDisplay3
{
get => _values.GetInt(9);
set
{
_values.SetInt(9, value);
SignalPropertyChange();
}
}
[Category("MVPM Values")]
public int Value11
{
get => _values.GetInt(10);
set
{
_values.SetInt(10, value);
SignalPropertyChange();
}
}
[Category("MVPM Values")]
[Description("The amount of frames that the third character name card stays out for after being displayed")]
public int CharacterNameCardDisplayLength3
{
get => _values.GetInt(11);
set
{
_values.SetInt(11, value);
SignalPropertyChange();
}
}
[Category("MVPM Values")]
public int Value13
{
get => _values.GetInt(12);
set
{
_values.SetInt(12, value);
SignalPropertyChange();
}
}
[Category("MVPM Values")]
[Description("The frame at which the fourth character name card (fourth texture in Model Data [1]) is displayed")]
public int CharacterNameCardDisplay4
{
get => _values.GetInt(13);
set
{
_values.SetInt(13, value);
SignalPropertyChange();
}
}
[Category("MVPM Values")]
public int Value15
{
get => _values.GetInt(14);
set
{
_values.SetInt(14, value);
SignalPropertyChange();
}
}
[Category("MVPM Values")]
[Description("The amount of frames that the fourth character name card stays out for after being displayed")]
public int CharacterNameCardDisplayLength4
{
get => _values.GetInt(15);
set
{
_values.SetInt(15, value);
SignalPropertyChange();
}
}
[Category("MVPM Values")]
public int Value17
{
get => _values.GetInt(16);
set
{
_values.SetInt(16, value);
SignalPropertyChange();
}
}
[Category("MVPM Values")]
public int Value18
{
get => _values.GetInt(17);
set
{
_values.SetInt(17, value);
SignalPropertyChange();
}
}
[Category("MVPM Values")]
public int Value19
{
get => _values.GetInt(18);
set
{
_values.SetInt(18, value);
SignalPropertyChange();
}
}
[Category("MVPM Values")]
public int Value20
{
get => _values.GetInt(19);
set
{
_values.SetInt(19, value);
SignalPropertyChange();
}
}
[Category("MVPM Values")]
public int Value21
{
get => _values.GetInt(20);
set
{
_values.SetInt(20, value);
SignalPropertyChange();
}
}
[Category("MVPM Values")]
public byte Value22a
{
get => _values.GetByte(21, 0);
set
{
_values.SetByte(21, 0, value);
SignalPropertyChange();
}
}
[Category("MVPM Values")]
public byte Value22b
{
get => _values.GetByte(21, 1);
set
{
_values.SetByte(21, 1, value);
SignalPropertyChange();
}
}
[Category("MVPM Values")]
public short Value22c
{
get => _values.GetShort(21, 1);
set
{
_values.SetShort(21, 1, value);
SignalPropertyChange();
}
}
public override bool OnInitialize()
{
if (_name == null)
{
_name = "MVPMEntry " + Index;
}
_values = new ParameterValueManager((VoidPtr) Header);
return false;
}
public override void OnRebuild(VoidPtr address, int length, bool force)
{
MovParameterEntry* header = (MovParameterEntry*) address;
*header = new MovParameterEntry();
byte* pOut = (byte*) header;
byte* pIn = (byte*) _values._values.Address;
for (int i = 0; i < 22 * 4; i++)
{
*pOut++ = *pIn++;
}
}
}
} |
using DotNetty.Buffers;
using DotNetty.Transport.Channels;
using OpenClassic.Server.Domain;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;
namespace OpenClassic.Server.Networking
{
public class GameConnectionHandler : ChannelHandlerAdapter, ISession
{
private static IGameEngine gameEngine;
private static IPacketHandler[] PacketHandlerMap;
private readonly IChannel gameChannel;
public override bool IsSharable => false;
public IChannel ClientChannel => gameChannel;
// This needs to be volatile because this field can be set by either
// a worker thread OR the game thread.
private volatile IByteBuffer _buffer;
public bool AllowedToDisconnect => false;
public IByteBuffer Buffer => _buffer;
public IPlayer Player { get; set; }
public bool ShouldUpdate => Player != null && gameChannel.IsWritable;
public int CurrentPacketStartIndex { get; set; }
public int? CurrentPacketId { get; set; }
public int CurrentPacketBitfieldPosition { get; set; }
public int MaxPacketLength => _buffer?.Capacity ?? 0;
#region Packet queue fields and properties
private readonly List<IByteBuffer> packetQueueOne = new List<IByteBuffer>(128);
private readonly List<IByteBuffer> packetQueueTwo = new List<IByteBuffer>(128);
private readonly object packetQueueLock = new object();
private List<IByteBuffer> CurrentPacketQueue { get; set; }
#endregion
public static void Init(IGameEngine engine, IPacketHandler[] packetHandlers)
{
Debug.Assert(engine != null);
Debug.Assert(packetHandlers != null);
// This needs to be executed on the game thread. Otherwise the
// game thread won't necessarily see the loaded IPacketHandler map
// when it invokes the Pulse() method each game tick.
Debug.Assert(engine.IsOnGameThread);
var handlerMap = new IPacketHandler[255];
foreach (var handler in packetHandlers)
{
handlerMap[handler.Opcode] = handler;
}
for (var i = 0; i < handlerMap.Length; i++)
{
if (handlerMap[i] == null)
{
handlerMap[i] = new NoOpPacketHandler();
}
}
gameEngine = engine;
PacketHandlerMap = handlerMap;
}
public GameConnectionHandler(IChannel channel)
{
Debug.Assert(channel != null);
this.gameChannel = channel;
AllocateBuffer();
Debug.Assert(_buffer != null);
Debug.Assert(_buffer.ReferenceCount == 1);
CurrentPacketQueue = packetQueueOne;
}
public override void ChannelInactive(IChannelHandlerContext context)
{
base.ChannelInactive(context);
}
public override void ChannelActive(IChannelHandlerContext context)
{
Debug.Assert(context != null);
var channel = context.Channel;
base.ChannelActive(context);
}
public override void ChannelRead(IChannelHandlerContext context, object message)
{
Debug.Assert(context != null);
Debug.Assert(message != null);
Debug.Assert(message is IByteBuffer);
var buffer = message as IByteBuffer;
// Add the message to the queue. Use AddMessage(IByteBuffer) so that
// the message is added while the packetQueueLock is held.
AddMessageThreadSafe(buffer);
}
public int Pulse()
{
// Pulse must only ever be invoked on the game thread.
Debug.Assert(gameEngine.IsOnGameThread);
// Get the list of messages requiring processing. Make use of the
// GetAndSwapPacketQueueThreadSafe() method to ensure that the
// correct lock is held while retrieving queued packets.
var messages = GetAndSwapPacketQueueThreadSafe();
try
{
var packetsHandled = 0;
foreach (var buffer in messages)
{
try
{
var opcode = buffer.GetOpcode();
var handler = PacketHandlerMap[opcode];
handler.Handle(this, buffer);
packetsHandled++;
}
#pragma warning disable RECS0022 // A catch clause that catches System.Exception and has an empty body
catch (Exception ex)
#pragma warning restore RECS0022 // A catch clause that catches System.Exception and has an empty body
{
var inner = ex.InnerException;
// TODO: Determine what we want to do on packet handler failure.
}
finally
{
buffer.Release();
}
}
return packetsHandled;
}
finally
{
// We need to lock again to ensure that other threads accessing the packet queue
// in the future see the correctly-cleared queue.
lock (packetQueueLock)
{
messages.Clear();
Debug.Assert(messages.Count == 0);
Debug.Assert(messages != CurrentPacketQueue);
}
}
}
#region Message queueing
private void AddMessageThreadSafe(IByteBuffer message)
{
// This method should only ever be called by DotNetty worker threads.
// Debug.Assert(!gameEngine.IsOnGameThread); // Commented as this breaks unit tests
Debug.Assert(message != null);
// We need to lock here to guarantee memory visibility of the queue contents.
lock (packetQueueLock)
{
var currentQueue = CurrentPacketQueue;
Debug.Assert(currentQueue != null);
currentQueue.Add(message);
}
}
private List<IByteBuffer> GetAndSwapPacketQueueThreadSafe()
{
List<IByteBuffer> messages = null;
// We need to lock here to guarantee memory visibility.
lock (packetQueueLock)
{
var currentQueue = CurrentPacketQueue;
Debug.Assert(currentQueue != null);
var otherQueue = ReferenceEquals(currentQueue, packetQueueTwo) ? packetQueueOne : packetQueueTwo;
Debug.Assert(otherQueue != null);
Debug.Assert(otherQueue.Count == 0); // The other queue should currently be empty.
// Assign the current queue to our messages variable so that we can iterate
// over it in a moment once we're outside of this mutex.
messages = currentQueue;
// Finally, also swap the queues over while inside the mutex.
CurrentPacketQueue = otherQueue;
Debug.Assert(messages != null);
Debug.Assert(messages != CurrentPacketQueue);
}
return messages;
}
#endregion
public Task WriteAndFlushSessionBuffer()
{
// Invocation of this method should be on the game thread.
Debug.Assert(gameEngine.IsOnGameThread);
var bufferBeforeFlush = _buffer;
Debug.Assert(bufferBeforeFlush != null);
Debug.Assert(bufferBeforeFlush.ReferenceCount == 1);
var writeAndFlushResult = gameChannel.WriteAndFlushAsync(bufferBeforeFlush);
AllocateBuffer();
var bufferAfterFlush = _buffer;
Debug.Assert(bufferAfterFlush != null);
Debug.Assert(bufferAfterFlush.ReferenceCount == 1);
return writeAndFlushResult;
}
public Task WriteFlushClose()
{
// Invocation of this method should be on the game thread.
Debug.Assert(gameEngine.IsOnGameThread);
Debug.Assert(_buffer != null);
Debug.Assert(_buffer.ReferenceCount == 1);
var writeFinishedFuture = gameChannel.WriteAndFlushAsync(_buffer);
var unregisterAndCloseOnGameEngineThread = writeFinishedFuture.ContinueWith(async (t) =>
{
// This callback is running on a worker thread.
Debug.Assert(!gameEngine.IsOnGameThread);
// Worker thread awaits channel closure.
await gameChannel.CloseAsync();
// And now that the channel is closed, unregister the session
// in the GameEngine.
gameEngine.UnregisterSession(this);
});
return unregisterAndCloseOnGameEngineThread;
}
private void AllocateBuffer()
{
// This method could be called by either thread, which is why
// the _buffer field is volatile.
// TODO: Consider using a single-threaded allocator here that belongs exclusively to the game thread.
_buffer = gameChannel.Allocator.Buffer(8192);
}
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using Cake.Core.IO;
using Xunit;
namespace Cake.Core.Tests.Unit.IO
{
public sealed class DirectoryPathCollectionTests
{
public sealed class TheConstructor
{
[Fact]
public void Should_Use_PathComparer_Default_If_Comparer_Is_Null()
{
// Given
var collection = new DirectoryPathCollection();
// Then
Assert.Equal(PathComparer.Default, collection.Comparer);
}
}
public sealed class TheCountProperty
{
[Fact]
public void Should_Return_The_Number_Of_Paths_In_The_Collection()
{
// Given
var collection = new DirectoryPathCollection(new DirectoryPath[] { "A", "B" }, new PathComparer(false));
// When, Then
Assert.Equal(2, collection.Count);
}
}
public sealed class TheAddMethod
{
public sealed class WithSinglePath
{
[Fact]
public void Should_Add_Path_If_Not_Already_Present()
{
// Given
var collection = new DirectoryPathCollection(new DirectoryPath[] { "A" }, new PathComparer(false));
// When
collection.Add(new DirectoryPath("B"));
// Then
Assert.Equal(2, collection.Count);
}
[Theory]
[InlineData(true, 2)]
[InlineData(false, 1)]
public void Should_Respect_File_System_Case_Sensitivity_When_Adding_Path(bool caseSensitive, int expectedCount)
{
// Given
var collection = new DirectoryPathCollection(new DirectoryPath[] { "A" }, new PathComparer(caseSensitive));
// When
collection.Add(new DirectoryPath("a"));
// Then
Assert.Equal(expectedCount, collection.Count);
}
}
public sealed class WithMultiplePaths
{
[Fact]
public void Should_Throw_If_Paths_Is_Null()
{
// Given
var collection = new DirectoryPathCollection(new DirectoryPath[] { "A" }, new PathComparer(false));
// When
var result = Record.Exception(() => collection.Add((IEnumerable<DirectoryPath>)null));
// Then
AssertEx.IsArgumentNullException(result, "paths");
}
[Fact]
public void Should_Add_Paths_That_Are_Not_Present()
{
// Given
var collection = new DirectoryPathCollection(new DirectoryPath[] { "A", "B" }, new PathComparer(false));
// When
collection.Add(new DirectoryPath[] { "A", "B", "C" });
// Then
Assert.Equal(3, collection.Count);
}
[Theory]
[InlineData(true, 5)]
[InlineData(false, 3)]
public void Should_Respect_File_System_Case_Sensitivity_When_Adding_Paths(bool caseSensitive, int expectedCount)
{
// Given
var collection = new DirectoryPathCollection(new DirectoryPath[] { "A", "B" }, new PathComparer(caseSensitive));
// When
collection.Add(new DirectoryPath[] { "a", "b", "c" });
// Then
Assert.Equal(expectedCount, collection.Count);
}
}
}
public sealed class TheRemoveMethod
{
public sealed class WithSinglePath
{
[Theory]
[InlineData(true, 1)]
[InlineData(false, 0)]
public void Should_Respect_File_System_Case_Sensitivity_When_Removing_Path(bool caseSensitive, int expectedCount)
{
// Given
var collection = new DirectoryPathCollection(new DirectoryPath[] { "A" }, new PathComparer(caseSensitive));
// When
collection.Remove(new DirectoryPath("a"));
// Then
Assert.Equal(expectedCount, collection.Count);
}
}
public sealed class WithMultiplePaths
{
[Fact]
public void Should_Throw_If_Paths_Is_Null()
{
// Given
var collection = new DirectoryPathCollection(new DirectoryPath[] { "A" }, new PathComparer(false));
// When
var result = Record.Exception(() => collection.Remove((IEnumerable<DirectoryPath>)null));
// Then
AssertEx.IsArgumentNullException(result, "paths");
}
[Theory]
[InlineData(true, 2)]
[InlineData(false, 0)]
public void Should_Respect_File_System_Case_Sensitivity_When_Removing_Paths(bool caseSensitive, int expectedCount)
{
// Given
var collection = new DirectoryPathCollection(new DirectoryPath[] { "A", "B" }, new PathComparer(caseSensitive));
// When
collection.Remove(new DirectoryPath[] { "a", "b", "c" });
// Then
Assert.Equal(expectedCount, collection.Count);
}
}
}
public sealed class ThePlusOperator
{
public sealed class WithSinglePath
{
[Fact]
public void Should_Throw_If_Collection_Is_Null()
{
// Given, When
var result = Record.Exception(() => (DirectoryPathCollection)null + new DirectoryPath("a"));
// Then
AssertEx.IsArgumentNullException(result, "collection");
}
[Theory]
[InlineData(true, 2)]
[InlineData(false, 1)]
public void Should_Respect_File_System_Case_Sensitivity_When_Adding_Path(bool caseSensitive, int expectedCount)
{
// Given
var collection = new DirectoryPathCollection(new DirectoryPath[] { "A" }, new PathComparer(caseSensitive));
// When
var result = collection + new DirectoryPath("a");
// Then
Assert.Equal(expectedCount, result.Count);
}
[Fact]
public void Should_Return_New_Collection_When_Adding_Path()
{
// Given
var collection = new DirectoryPathCollection(new DirectoryPath[] { "A" }, new PathComparer(false));
// When
var result = collection + new DirectoryPath("B");
// Then
Assert.False(ReferenceEquals(result, collection));
}
}
public sealed class WithMultiplePaths
{
[Fact]
public void Should_Throw_If_Collection_Is_Null()
{
// Given, When
var result = Record.Exception(() => (DirectoryPathCollection)null + new DirectoryPath[] { "a" });
// Then
AssertEx.IsArgumentNullException(result, "collection");
}
[Theory]
[InlineData(true, 5)]
[InlineData(false, 3)]
public void Should_Respect_File_System_Case_Sensitivity_When_Adding_Paths(bool caseSensitive, int expectedCount)
{
// Given
var collection = new DirectoryPathCollection(new DirectoryPath[] { "A", "B" }, new PathComparer(caseSensitive));
// When
var result = collection + new DirectoryPath[] { "a", "b", "c" };
// Then
Assert.Equal(expectedCount, result.Count);
}
[Fact]
public void Should_Return_New_Collection_When_Adding_Paths()
{
// Given
var collection = new DirectoryPathCollection(new DirectoryPath[] { "A", "B" }, new PathComparer(false));
// When
var result = collection + new DirectoryPath[] { "C", "D" };
// Then
Assert.False(ReferenceEquals(result, collection));
}
}
}
public sealed class TheMinusOperator
{
public sealed class WithSinglePath
{
[Fact]
public void Should_Throw_If_Collection_Is_Null()
{
// Given, When
var result = Record.Exception(() => (DirectoryPathCollection)null - new DirectoryPath("a"));
// Then
AssertEx.IsArgumentNullException(result, "collection");
}
[Theory]
[InlineData(true, 2)]
[InlineData(false, 1)]
public void Should_Respect_File_System_Case_Sensitivity_When_Removing_Path(bool caseSensitive, int expectedCount)
{
// Given
var collection = new DirectoryPathCollection(new DirectoryPath[] { "A", "B" }, new PathComparer(caseSensitive));
// When
var result = collection - new DirectoryPath("a");
// Then
Assert.Equal(expectedCount, result.Count);
}
[Fact]
public void Should_Return_New_Collection_When_Removing_Path()
{
// Given
var collection = new DirectoryPathCollection(new DirectoryPath[] { "A", "B" }, new PathComparer(false));
// When
var result = collection - new DirectoryPath("A");
// Then
Assert.False(ReferenceEquals(result, collection));
}
}
public sealed class WithMultiplePaths
{
[Fact]
public void Should_Throw_If_Collection_Is_Null()
{
// Given, When
var result = Record.Exception(() => (DirectoryPathCollection)null - new DirectoryPath[] { "a" });
// Then
AssertEx.IsArgumentNullException(result, "collection");
}
[Theory]
[InlineData(true, 3)]
[InlineData(false, 1)]
public void Should_Respect_File_System_Case_Sensitivity_When_Removing_Paths(bool caseSensitive, int expectedCount)
{
// Given
var collection = new DirectoryPathCollection(new DirectoryPath[] { "A", "B", "C" }, new PathComparer(caseSensitive));
// When
var result = collection - new DirectoryPath[] { "b", "c" };
// Then
Assert.Equal(expectedCount, result.Count);
}
[Fact]
public void Should_Return_New_Collection_When_Removing_Paths()
{
// Given
var collection = new DirectoryPathCollection(new DirectoryPath[] { "A", "B", "C" }, new PathComparer(false));
// When
var result = collection - new DirectoryPath[] { "B", "C" };
// Then
Assert.False(ReferenceEquals(result, collection));
}
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
namespace EasyGameServer
{
class WorldManager
{
private int m_WorldTick = Environment.TickCount;
private int m_GCTick = Environment.TickCount;
private Dictionary<int, ClientSession> m_ClientList = new Dictionary<int, ClientSession>();
private List<ClientSession> m_GuillotineList = new List<ClientSession>();
private System.Object lockThis = new System.Object();
public WorldManager()
{
Timer myTimer = new System.Timers.Timer();
myTimer.Elapsed += new ElapsedEventHandler(OnPeriodWork);
myTimer.Interval = 10;
myTimer.Start();
}
public int RegistClientSession(int credential, ClientConnection connection)
{
lock (lockThis)
{
if (!m_ClientList.ContainsKey(credential))
{
if (credential == -1)
{
credential = EasyGameServer.g_credentialManager.GetCredential();
ClientSession client = new ClientSession();
client.m_Credential = credential;
m_ClientList.Add(credential, client);
}
else
{
// 정리되어버림
// 그냥 세션만들어 주던지 에러 페킷을 주던지...
}
}
m_ClientList[credential].SetConnection(connection);
}
return credential;
}
public void DeleteClient(int credential)
{
lock (lockThis)
{
if (m_ClientList.ContainsKey(credential))
{
m_ClientList[credential].DisconnectConnection();
m_ClientList.Remove(credential);
EasyGameServer.g_credentialManager.ReturnCredential(credential);
}
}
}
public ClientSession GetClient(int credential)
{
return m_ClientList[credential];
}
// need now?
public Dictionary<int, ClientSession> GetClientList()
{
return m_ClientList;
}
public bool IsSessionContain(int credential)
{
if (m_ClientList.ContainsKey(credential))
{
return true;
}
return false;
}
public void ResetTickTime(int credential)
{
try
{
m_ClientList[credential].ResetTickTime();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
public void SendMessage(int credential, string message)
{
try
{
if (null != m_ClientList[credential].GetConnection())
{
m_ClientList[credential].GetConnection().Send(message);
}
}
catch(Exception e)
{
Console.WriteLine(e.ToString());
}
}
public void SendBroadCast(string message)
{
foreach (ClientSession client in m_ClientList.Values)
{
if ( null != client.GetConnection() )
{
if (null != client.GetConnection().workSocket)
{
client.GetConnection().Send(message);
}
}
}
}
public string WrapPacket(PacketTypes packetType, string payload)
{
payload = Utils.Base64Encoding(payload);
Packet packet = new Packet();
packet.m_Type = (int)packetType;
packet.m_Payload = payload;
string resultPacket = JsonFx.Json.JsonWriter.Serialize(packet);
return resultPacket;
}
public void OnPeriodWork(Object myObject, EventArgs myEventArgs)
{
m_WorldTick = Environment.TickCount;
if (m_WorldTick - m_GCTick > Defines.GC_INTERVAL)
{
CollectGarbageSessions();
m_GCTick = m_WorldTick;
}
}
public void CollectGarbageSessions()
{
Console.WriteLine("CollectGarbageSessions");
m_GuillotineList.Clear();
foreach (ClientSession client in m_ClientList.Values)
{
if ( client.IsTimeOut() )
{
m_GuillotineList.Add(client);
}
}
for(int i=0; i<m_GuillotineList.Count; ++i)
{
try
{
ClientSession client = m_GuillotineList[i];
Console.WriteLine("Delete!!");
DeleteClient(client.m_Credential);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
}
}
|
using System.Collections.Generic;
using WampSharp.Core.Serialization;
using WampSharp.V2.Core.Contracts;
namespace WampSharp.V2.PubSub
{
/// <summary>
/// Represents a topic subscriber that lives outside a router process.
/// </summary>
public interface IWampRawTopicClientSubscriber
{
/// <summary>
/// Occurs when an incoming event is avilable.
/// </summary>
/// <param name="formatter">A formatter that can be used to deserialize event arguments.</param>
/// <param name="publicationId">The publication id of the incoming publication.</param>
/// <param name="details">The details about this publication.</param>
/// <typeparam name="TMessage"></typeparam>
void Event<TMessage>(IWampFormatter<TMessage> formatter, long publicationId, EventDetails details);
/// <summary>
/// Occurs when an incoming event is avilable.
/// </summary>
/// <param name="formatter">A formatter that can be used to deserialize event arguments.</param>
/// <param name="publicationId">The publication id of the incoming publication.</param>
/// <param name="details">The details about this publication.</param>
/// <param name="arguments">The arguments of this publication.</param>
/// <typeparam name="TMessage"></typeparam>
void Event<TMessage>(IWampFormatter<TMessage> formatter, long publicationId, EventDetails details, TMessage[] arguments);
/// <summary>
/// Occurs when an incoming event is avilable.
/// </summary>
/// <param name="formatter">A formatter that can be used to deserialize event arguments.</param>
/// <param name="publicationId">The publication id of the incoming publication.</param>
/// <param name="details">The details about this publication.</param>
/// <param name="arguments">The arguments of this publication.</param>
/// <param name="argumentsKeywords">The arguments keywords of this publication.</param>
/// <typeparam name="TMessage"></typeparam>
void Event<TMessage>(IWampFormatter<TMessage> formatter, long publicationId, EventDetails details, TMessage[] arguments, IDictionary<string, TMessage> argumentsKeywords);
}
} |
using System.Threading.Tasks;
using Esfa.Recruit.Vacancies.Jobs.TrainingTypes.Models;
namespace Esfa.Recruit.Vacancies.Jobs.Infrastructure
{
public interface IUpdateQueryStore
{
Task UpdateStandardsAndFrameworksAsync(ApprenticeshipProgrammeView updatedList);
}
} |
using System;
using System.Text.RegularExpressions;
namespace Shouldly.MessageGenerators
{
internal class ShouldSatisfyAllConditionsMessageGenerator : ShouldlyMessageGenerator
{
private static readonly Regex Validator = new Regex("ShouldSatisfyAllConditions", RegexOptions.Compiled);
public override bool CanProcess(ShouldlyAssertionContext context)
{
return Validator.IsMatch(context.ShouldMethod) && !context.HasActual;
}
public override string GenerateErrorMessage(ShouldlyAssertionContext context)
{
const string format = @"
{0} should satisfy all the conditions specified, but does not.
The following errors were found ...
{1}";
var codePart = context.CodePart;
var expectedValue = context.Expected.ToString();
return String.Format(format, codePart, expectedValue);
}
}
} |
using System;
namespace BigInteger
{
public partial struct BigInteger
{
// 1种逆向序数对齐的Array.Copy()
// 长度_输入是对齐的的值,不是增|减的值
private static UInt64[] 等长化_核心(UInt64[] 数_输入, Int64 长度_输入, Boolean Is右向_输入 = default)
{
Int32 长度 = 数_输入.Length;
Int64 长度差 = 长度_输入 - 长度; // !理论上∈ [0, +∞)
UInt64[] 数容器 = new UInt64[长度_输入];
Int64 容器索引 = default; // !称之为新·除数索引更合适
UInt64[] 数_输出 = default;
if(Is右向_输入 == default) // 左向的情况
{
for(Int32 索引 = default; 索引 <= ToInt32(〇索引化(长度)); 索引++) // 空出前长度差个位置
{
// 预处理
容器索引 = 索引 + 长度差;
数容器[容器索引 >= 0 ? 容器索引 : default] = 数_输入[索引];
}
}
else // 右向的情况
{
数_输入.CopyTo(数容器, default);
}
数_输出 = 数容器;
return 数_输出;
}
// 对齐到当前Cell最高位
private static UInt64[] 左对齐_核心(UInt64[] 源_输入)
{
UInt64 高位〇数 = 高位始空白〇值计数(源_输入[^ToInt32(一索引化(default))]);
Int32 左移位 = ToInt32(高位〇数);
return 左移位_核心(源_输入, 左移位);
}
private static UInt64[] 左移位_核心(UInt64[] 源_输入, Int32 左移位_输入)
{
Boolean Is左移位 = default;
if(左移位_输入 >= 0)
{
Is左移位 = true;
}
else
{
// 占位
左移位_输入 = ToInt32(求绝对值(左移位_输入));
}
return 移位_核心(源_输入, 左移位_输入, Is左移位);
}
// 左对齐_核心的Wrap
private static UInt64[] 右移位_核心(UInt64[] 源_输入, Int32 右移位_输入) => 左移位_核心(源_输入, -右移位_输入);
private static UInt64[] 移位_核心(UInt64[] 源_输入, Int32 移位_输入, Boolean Is左移位_输入 = default)
{
// 预处理
// 定义
Int32 长度 = 源_输入.Length;
UInt64 高位〇数 = 高位始空白〇值计数(源_输入[^ToInt32(一索引化(default))]);
UInt64 最高位始点 = 四字位数 - 高位〇数; // 一索引化的值
UInt64 最高位终点 = default; // 一索引化的值
Int32 移位容器 = default;
Int32 左移位 = default;
Int32 右移位 = default;
Boolean? Is右向 = default;
Boolean Is进退位 = default;
Int32 容器 = default;
// 处理
// 处理Is进退位
if(Is左移位_输入)
{
Is进退位 = ToUInt64(移位_输入) > 高位〇数 ? true : false; // >、≤
}
else // Is左移位_输入 == false的情况
{
Is进退位 = ToUInt64(移位_输入) >= 最高位始点 ? true : false; // ≥、<
}
// 处理移位容器
容器 = 移位容器 = 移位_输入;
//
if(Is进退位)
{
容器 = 移位容器 -= ToInt32(Is左移位_输入 ? 高位〇数 : 最高位始点);
容器 = 求模(容器, 四字位数);
}
else // 不进|退位
{
// 占位
//移位容器 = 移位_输入;
}
// 赋值最高位终点
if(Is进退位)
{
if(Is左移位_输入)
{
最高位终点 = ToUInt64(容器);
}
else // Is左移位_输入 == false的情况
{
最高位终点 = ToUInt64(四字位数 - 容器);
}
}
else // 不进|退位
{
if(Is左移位_输入)
{
最高位终点 = 最高位始点 + ToUInt64(容器);
}
else // Is左移位_输入 == false的情况
{
最高位终点 = 最高位始点 - ToUInt64(容器);
}
}
// 处理Is右向
if(最高位终点 > 最高位始点)
{
Is右向 = false;
}
else if(最高位终点 < 最高位始点)
{
Is右向 = true;
}
else // 无移位、左|右移位终位置同始位置
{
// 占位
//Is右向 = default;
}
// 移位数
if(Is进退位) // “进|退位”的情况:左移位_输入 > 高位〇数
{
if(Is右向 == true)
{
右移位 = ToInt32(最高位始点 - 最高位终点);
左移位 = 四字位数 - 右移位;
}
else if(Is右向 == false)
{
左移位 = ToInt32(最高位终点 - 最高位始点);
右移位 = 四字位数 - 左移位;
}
else // 无移位、左|右移位终位置同始位置
{
// 占位
}
}
else // 不足“进位”的情况:左移位_输入 ≤ 高位〇数
{
if(Is右向 == true)
{
右移位 = ToInt32(最高位始点 - 最高位终点);
左移位 = 四字位数 - 右移位;
}
else if(Is右向 == false)
{
左移位 = ToInt32(最高位终点 - 最高位始点);
右移位 = 四字位数 - 左移位;
}
else // 无移位、左|右移位终位置同始位置
{
// 占位
}
}
// 长度
if(Is进退位)
{
// 真·右对齐借用左对齐内部的右对齐
容器 = ToInt32(Ceiling倍数化除以(ToUInt64(移位容器), 四字位数));
//
if(Is左移位_输入)
{
长度 += 容器;
}
else
{
if(容器 >= 长度)
{
return new UInt64[]{ default };
}
else
{
长度 -= 容器;
}
}
}
else // 无进|退位
{
// 占位
}
// 定义
UInt64[] 的_输出 = new UInt64[长度];
if // 补充右移位的左向情况下的末端位的值,正常赋值时超出了范围,无法获得
(
Is左移位_输入 == default
&& Is右向 == false
&& 向后(长度) <= 源_输入.Length
)
{
的_输出[default] = 源_输入[^ToInt32(向后(长度))] >> 右移位;
}
else
{
// 占位
}
UInt64[] 处理容器 = 等长化_核心(源_输入, 长度);
// 处理
if(Is右向 != default) // 仅针对需要对齐的进行处理
// 2019.06.23,≠ default比:> default道理上说得过去
{
for(Int32 索引 = ToInt32(〇索引化(长度)); 索引 >= 0; 索引--)
{
if(Is右向 == true)
{
的_输出[索引] |= 处理容器[索引] >> 右移位;
}
else if(Is右向 == false)
{
的_输出[索引] |= 处理容器[索引] << 左移位;
}
else // 无移位、左|右移位终位置同始位置
{
// 占位
}
if(索引 >= 向后(default))
{
if(Is右向 == true)
{
的_输出[向前(索引)] = 处理容器[索引] << 左移位; // 理论上一定足够,故不需要位于:索引 >= 向后(default)判定中
}
else if(Is右向 == false)
{
的_输出[索引] |= 处理容器[向前(索引)] >> 右移位;
}
else // 无移位、左|右移位终位置同始位置
{
// 占位
}
}
else // 2019.06.23,视为做补〇
{
// 占位
}
}
}
else // 无移位、左|右移位终位置同始位置
{
Array.Copy(处理容器, 的_输出, 长度);
}
return 的_输出;
}
}
} |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
namespace StructurizrObjects
{
public static class NamedIdentity
{
private static Type[] ReferencedAssembliesTypesCache;
public static string GetNameFromType(Type type)
{
var input = type.Name;
return SpacesFromCamel(input);
}
public static string GetName<T>()
{
var input = typeof(T).Name;
return SpacesFromCamel(input);
}
public static bool TryGetTypeFromExternalAssemblyByElementName(string name, out Type type)
{
if (ReferencedAssembliesTypesCache == null)
{
var path = AppContext.BaseDirectory; // returns bin/debug path
var directory = new DirectoryInfo(path);
var dllFiles = directory.GetFiles("*.dll");
ReferencedAssembliesTypesCache = dllFiles
.SelectMany(x => Assembly.LoadFile(x.FullName).GetTypes())
.ToArray();
}
var camelCase = CamelFromSpaces(name);
type = ReferencedAssembliesTypesCache.FirstOrDefault(x => x.Name == camelCase);
return type != null;
}
public static string SpacesFromCamel(string value)
{
if (value.Length > 0)
{
var result = new List<char>();
char[] array = value.ToCharArray();
foreach (var item in array)
{
if (char.IsUpper(item) && result.Count > 0)
{
result.Add(' ');
}
result.Add(item);
}
return new string(result.ToArray());
}
return value;
}
public static string CamelFromSpaces(string value)
{
if (value.Length > 0)
{
bool makeUpper = true;
var result = new List<char>();
char[] array = value.ToCharArray();
foreach (var item in array)
{
if (makeUpper)
{
result.Add(char.ToUpper(item));
makeUpper = false;
continue;
}
if (item == ' ')
{
makeUpper = true;
}
else
{
result.Add(item);
}
}
return new string(result.ToArray());
}
return value;
}
}
}
|
using System;
using Unity.Build;
using Unity.Builder;
namespace Unity.Policy.Mapping
{
/// <summary>
/// Represents a builder policy for mapping build keys.
/// </summary>
public class BuildKeyMappingPolicy : NamedTypeBase, IBuildKeyMappingPolicy
{
#region Constructors
/// <summary>
/// Initialize a new instance of the <see cref="BuildKeyMappingPolicy"/> with the new build key.
/// </summary>
/// <param name="newBuildKey">The new build key.</param>
public BuildKeyMappingPolicy(INamedType newBuildKey)
: base(newBuildKey.Type, newBuildKey.Name)
{
}
public BuildKeyMappingPolicy(Type type, string name, bool build)
: base(type, name)
{
RequireBuild = build;
}
#endregion
#region IBuildKeyMappingPolicy
/// <summary>
/// Maps the build key.
/// </summary>
/// <param name="buildKey">The build key to map.</param>
/// <param name="context">Current build context. Used for contextual information
/// if writing a more sophisticated mapping, unused in this implementation.</param>
/// <returns>The new build key.</returns>
public INamedType Map<TContext>(INamedType buildKey, ref TContext context)
where TContext : IBuildContext
{
return this;
}
/// <summary>
/// Instructs engine to resolve type rather than build it
/// </summary>
public bool RequireBuild { get; } = true;
#endregion
}
}
|
namespace Defence;
/// <summary>
/// main class for keeping info from each field on validation
/// </summary>
/// <typeparam name="T"></typeparam>
public class DefenceProperty<T>
{
public DefenceProperty(string fieldName, T input)
{
FieldName = fieldName;
Input = input;
}
public string FieldName { get; set; }
public T Input { get; set; }
} |
using System.Data;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using LambdicSql;
using LambdicSql.feat.Dapper;
using static LambdicSql.Oracle.Symbol;
using static Test.Helper.DBProviderInfo;
using Test.Helper;
namespace Test
{
[TestClass]
public class TestSymbolClausesLimit
{
public TestContext TestContext { get; set; }
public IDbConnection _connection;
[TestInitialize]
public void TestInitialize()
{
_connection = TestEnvironment.CreateConnection(TestContext);
_connection.Open();
}
[TestCleanup]
public void TestCleanup() => _connection.Dispose();
[TestMethod]
public void Test_RowNum()
{
var sql = Db<DB>.Sql(db =>
Select(Asterisk(db.tbl_remuneration)).
From(db.tbl_remuneration).
Where(Between(RowNum(), 1, 3)).
OrderBy(Asc(db.tbl_remuneration.id))
);
var datas = _connection.Query(sql).ToList();
Assert.AreEqual(3, datas.Count);
AssertEx.AreEqual(sql, _connection,
@"SELECT *
FROM tbl_remuneration
WHERE ROWNUM BETWEEN :p_0 AND :p_1
ORDER BY
tbl_remuneration.id ASC",
1, 3);
}
}
}
|
namespace AdoptMe.Services.Adopters
{
public interface IAdopterService
{
int Create(string firstName, string lastName, int Age, string userId);
bool IsAdopter(string userId);
}
} |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;
using RestRunner.Models;
using RestRunner.Properties;
using RestRunner.Services;
using RestSharp;
namespace RestRunner.Design
{
public class DesignCommandService : ICommandService
{
private readonly string _commandsFilePath = Settings.Default.SaveFolder + @"\commands.dat";
private List<RestCommand> _commands;
public async Task<List<RestCommand>> GetCommandsAsync()
{
if (_commands != null)
return _commands;
var result = new List<RestCommand>();
var adhocCategory = new RestCommandCategory("Adhoc", @"");
//Adhoc
var bodyText = @"";
var captureValues = new ObservableCollection<CaptionedKeyValuePair>();
var command = new RestCommand("%service-host%/", bodyText, Method.POST)
{
CaptureValues = captureValues,
Category = adhocCategory,
Label = "Adhoc"
};
result.Add(command);
_commands = result;
return _commands;
}
public bool HasChanged(IList<RestCommand> commands)
{
return false;
}
/// <summary>
/// This is helpful for resetting the save file if something gets screwed up.
/// </summary>
/// <param name="commands"></param>
/// <returns></returns>
public async Task SaveCommandsAsync(IEnumerable<RestCommand> commands)
{
await Task.Run(() =>
{
IFormatter formatter = new BinaryFormatter();
using (var s = new FileStream(_commandsFilePath, FileMode.Create))
{
formatter.Serialize(s, commands.ToList());
}
});
}
}
}
|
/*
This code is derived from jgit (http://eclipse.org/jgit).
Copyright owners are documented in jgit's IP log.
This program and the accompanying materials are made available
under the terms of the Eclipse Distribution License v1.0 which
accompanies this distribution, is reproduced below, and is
available at http://www.eclipse.org/org/documents/edl-v10.php
All rights reserved.
Redistribution and use in source and binary forms, with or
without modification, are permitted provided that the following
conditions are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
- Neither the name of the Eclipse Foundation, Inc. nor the
names of its contributors may be used to endorse or promote
products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using NGit;
using NGit.Errors;
using NGit.Junit;
using NUnit.Framework;
using Sharpen;
namespace NGit
{
[NUnit.Framework.TestFixture]
public class ObjectLoaderTest
{
private TestRng rng;
private TestRng GetRng()
{
if (rng == null)
{
rng = new TestRng(Sharpen.Extensions.GetTestName());
}
return rng;
}
/// <exception cref="NGit.Errors.MissingObjectException"></exception>
/// <exception cref="System.IO.IOException"></exception>
[NUnit.Framework.Test]
public virtual void TestSmallObjectLoader()
{
byte[] act = GetRng().NextBytes(512);
ObjectLoader ldr = new ObjectLoader.SmallObject(Constants.OBJ_BLOB, act);
NUnit.Framework.Assert.AreEqual(Constants.OBJ_BLOB, ldr.GetType());
NUnit.Framework.Assert.AreEqual(act.Length, ldr.GetSize());
NUnit.Framework.Assert.IsFalse(ldr.IsLarge(), "not is large");
NUnit.Framework.Assert.AreSame(act, ldr.GetCachedBytes());
NUnit.Framework.Assert.AreSame(act, ldr.GetCachedBytes(1));
NUnit.Framework.Assert.AreSame(act, ldr.GetCachedBytes(int.MaxValue));
byte[] copy = ldr.GetBytes();
NUnit.Framework.Assert.AreNotSame(act, copy);
NUnit.Framework.Assert.IsTrue(Arrays.Equals(act, copy), "same content");
copy = ldr.GetBytes(1);
NUnit.Framework.Assert.AreNotSame(act, copy);
NUnit.Framework.Assert.IsTrue(Arrays.Equals(act, copy), "same content");
copy = ldr.GetBytes(int.MaxValue);
NUnit.Framework.Assert.AreNotSame(act, copy);
NUnit.Framework.Assert.IsTrue(Arrays.Equals(act, copy), "same content");
ObjectStream @in = ldr.OpenStream();
NUnit.Framework.Assert.IsNotNull(@in, "has stream");
NUnit.Framework.Assert.IsTrue(@in is ObjectStream.SmallStream, "is small stream");
NUnit.Framework.Assert.AreEqual(Constants.OBJ_BLOB, @in.GetType());
NUnit.Framework.Assert.AreEqual(act.Length, @in.GetSize());
NUnit.Framework.Assert.AreEqual(act.Length, @in.Available());
NUnit.Framework.Assert.IsTrue(@in.MarkSupported(), "mark supported");
copy = new byte[act.Length];
NUnit.Framework.Assert.AreEqual(act.Length, @in.Read(copy));
NUnit.Framework.Assert.AreEqual(0, @in.Available());
NUnit.Framework.Assert.AreEqual(-1, @in.Read());
NUnit.Framework.Assert.IsTrue(Arrays.Equals(act, copy), "same content");
ByteArrayOutputStream tmp = new ByteArrayOutputStream();
ldr.CopyTo(tmp);
NUnit.Framework.Assert.IsTrue(Arrays.Equals(act, tmp.ToByteArray()), "same content"
);
}
/// <exception cref="NGit.Errors.MissingObjectException"></exception>
/// <exception cref="System.IO.IOException"></exception>
[NUnit.Framework.Test]
public virtual void TestLargeObjectLoader()
{
byte[] act = GetRng().NextBytes(512);
ObjectLoader ldr = new _ObjectLoader_122(act);
NUnit.Framework.Assert.AreEqual(Constants.OBJ_BLOB, ldr.GetType());
NUnit.Framework.Assert.AreEqual(act.Length, ldr.GetSize());
NUnit.Framework.Assert.IsTrue(ldr.IsLarge(), "is large");
try
{
ldr.GetCachedBytes();
NUnit.Framework.Assert.Fail("did not throw on getCachedBytes()");
}
catch (LargeObjectException)
{
}
// expected
try
{
ldr.GetBytes();
NUnit.Framework.Assert.Fail("did not throw on getBytes()");
}
catch (LargeObjectException)
{
}
// expected
try
{
ldr.GetCachedBytes(64);
NUnit.Framework.Assert.Fail("did not throw on getCachedBytes(64)");
}
catch (LargeObjectException)
{
}
// expected
byte[] copy = ldr.GetCachedBytes(1024);
NUnit.Framework.Assert.AreNotSame(act, copy);
NUnit.Framework.Assert.IsTrue(Arrays.Equals(act, copy), "same content");
ObjectStream @in = ldr.OpenStream();
NUnit.Framework.Assert.IsNotNull(@in, "has stream");
NUnit.Framework.Assert.AreEqual(Constants.OBJ_BLOB, @in.GetType());
NUnit.Framework.Assert.AreEqual(act.Length, @in.GetSize());
NUnit.Framework.Assert.AreEqual(act.Length, @in.Available());
NUnit.Framework.Assert.IsTrue(@in.MarkSupported(), "mark supported");
copy = new byte[act.Length];
NUnit.Framework.Assert.AreEqual(act.Length, @in.Read(copy));
NUnit.Framework.Assert.AreEqual(0, @in.Available());
NUnit.Framework.Assert.AreEqual(-1, @in.Read());
NUnit.Framework.Assert.IsTrue(Arrays.Equals(act, copy), "same content");
ByteArrayOutputStream tmp = new ByteArrayOutputStream();
ldr.CopyTo(tmp);
NUnit.Framework.Assert.IsTrue(Arrays.Equals(act, tmp.ToByteArray()), "same content"
);
}
private sealed class _ObjectLoader_122 : ObjectLoader
{
public _ObjectLoader_122(byte[] act)
{
this.act = act;
}
/// <exception cref="NGit.Errors.LargeObjectException"></exception>
public override byte[] GetCachedBytes()
{
throw new LargeObjectException();
}
public override long GetSize()
{
return act.Length;
}
public override int GetType()
{
return Constants.OBJ_BLOB;
}
/// <exception cref="NGit.Errors.MissingObjectException"></exception>
/// <exception cref="System.IO.IOException"></exception>
public override ObjectStream OpenStream()
{
return new ObjectStream.Filter(this.GetType(), act.Length, new ByteArrayInputStream
(act));
}
private readonly byte[] act;
}
/// <exception cref="NGit.Errors.LargeObjectException"></exception>
/// <exception cref="NGit.Errors.MissingObjectException"></exception>
/// <exception cref="System.IO.IOException"></exception>
[NUnit.Framework.Test]
public virtual void TestLimitedGetCachedBytes()
{
byte[] act = GetRng().NextBytes(512);
ObjectLoader ldr = new _SmallObject_196(Constants.OBJ_BLOB, act);
NUnit.Framework.Assert.IsTrue(ldr.IsLarge(), "is large");
try
{
ldr.GetCachedBytes(10);
NUnit.Framework.Assert.Fail("Did not throw LargeObjectException");
}
catch (LargeObjectException)
{
}
// Expected result.
byte[] copy = ldr.GetCachedBytes(512);
NUnit.Framework.Assert.AreNotSame(act, copy);
NUnit.Framework.Assert.IsTrue(Arrays.Equals(act, copy), "same content");
copy = ldr.GetCachedBytes(1024);
NUnit.Framework.Assert.AreNotSame(act, copy);
NUnit.Framework.Assert.IsTrue(Arrays.Equals(act, copy), "same content");
}
private sealed class _SmallObject_196 : ObjectLoader.SmallObject
{
public _SmallObject_196(int baseArg1, byte[] baseArg2) : base(baseArg1, baseArg2)
{
}
public override bool IsLarge()
{
return true;
}
}
/// <exception cref="NGit.Errors.LargeObjectException"></exception>
/// <exception cref="NGit.Errors.MissingObjectException"></exception>
/// <exception cref="System.IO.IOException"></exception>
[NUnit.Framework.Test]
public virtual void TestLimitedGetCachedBytesExceedsJavaLimits()
{
ObjectLoader ldr = new _ObjectLoader_223();
NUnit.Framework.Assert.IsTrue(ldr.IsLarge(), "is large");
try
{
ldr.GetCachedBytes(10);
NUnit.Framework.Assert.Fail("Did not throw LargeObjectException");
}
catch (LargeObjectException)
{
}
// Expected result.
try
{
ldr.GetCachedBytes(int.MaxValue);
NUnit.Framework.Assert.Fail("Did not throw LargeObjectException");
}
catch (LargeObjectException)
{
}
}
private sealed class _ObjectLoader_223 : ObjectLoader
{
public _ObjectLoader_223()
{
}
public override bool IsLarge()
{
return true;
}
/// <exception cref="NGit.Errors.LargeObjectException"></exception>
public override byte[] GetCachedBytes()
{
throw new LargeObjectException();
}
public override long GetSize()
{
return long.MaxValue;
}
public override int GetType()
{
return Constants.OBJ_BLOB;
}
/// <exception cref="NGit.Errors.MissingObjectException"></exception>
/// <exception cref="System.IO.IOException"></exception>
public override ObjectStream OpenStream()
{
return new _ObjectStream_247();
}
private sealed class _ObjectStream_247 : ObjectStream
{
public _ObjectStream_247()
{
}
public override long GetSize()
{
return long.MaxValue;
}
public override int GetType()
{
return Constants.OBJ_BLOB;
}
/// <exception cref="System.IO.IOException"></exception>
public override int Read()
{
NUnit.Framework.Assert.Fail("never should have reached read");
return -1;
}
}
}
// Expected result.
}
}
|
using System.Collections.Generic;
namespace IOC
{
public interface IDataProvider
{
IEnumerable<int> GetNumbers();
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace BagOfHolding
{
public partial class PartyWindow : UserControl
{
bool initialized;
List<Character> party;
public PartyWindow() {
party = new List<Character>();
}
public PartyWindow(ref List<Character> p) {
party = p;
}
public void open() {
if(!initialized)
startup();
setColors();
updateUIData();
Show();
Visible = true;
BringToFront();
IsAccessible = true;
}
private void startup() {
initialized = true;
InitializeComponent();
Properties.Settings.Default.PropertyChanged += new PropertyChangedEventHandler(settingsChanged);
Dock = DockStyle.Fill;
}
#region Utility methods
private void saveParty() {
foreach(Character c in party) {
c.saveChar();
}
}
public void updateUIData() {
party_panel.Controls.Clear();
foreach(Character c in party) {
CharacterBox charBox = new CharacterBox(c);
party_panel.Controls.Add(charBox);
charBox.createWindows();
}
}
private void updatePartyData() {
party.Clear();
foreach(CharacterBox c in party_panel.Controls) {
party.Add(c.getChar());
}
}
private void setColors() {
menu_strip.BackColor = Properties.Settings.Default.windowToolColor;
}
#endregion
#region Get & Set methods
public List<Character> getParty() {
return party;
}
public void setParty(ref List<Character> p) {
party = p;
}
#endregion
#region Event Handlers
private void settingsChanged(object sender, PropertyChangedEventArgs e) {
setColors();
}
private void newCharacterToolStripMenuItem_Click(object sender, EventArgs e) {
updatePartyData();
party.Add(new Character());
updateUIData();
}
private void loadCharacterToolStripMenuItem_Click(object sender, EventArgs e) {
updatePartyData();
OpenFileDialog loadWindow = new OpenFileDialog();
loadWindow.Multiselect = true;
loadWindow.Filter = "Character Files ('*.char') | *.char";
loadWindow.DefaultExt = "char";
if(loadWindow.ShowDialog() == DialogResult.OK) {
foreach(string f in loadWindow.FileNames) {
Character c = new Character();
c.loadChar(f);
party.Add(c);
}
updateUIData();
}
}
private void savePartyAsToolStripMenuItem_Click(object sender, EventArgs e) {
}
private void savePartyToolStripMenuItem_Click(object sender, EventArgs e) {
saveParty();
}
private void refreshToolStripMenuItem_Click(object sender, EventArgs e) {
updatePartyData();
}
private void clearWithoutSavingToolStripMenuItem_Click(object sender, EventArgs e) {
party.Clear();
updateUIData();
}
private void clearAndSaveToolStripMenuItem_Click(object sender, EventArgs e) {
saveParty();
party.Clear();
updateUIData();
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace Autojector.TestAssemblyGenerator;
public static class AssemblyExtensions
{
public static Type GetTypeFromAssemblyByName(this Assembly assembly, string typeName)
{
return assembly.GetTypes().Where(t => t.Name == typeName).First();
}
}
|
namespace Nivaes.App.Cross.Mobile.Sample
{
using System.Threading.Tasks;
using Nivaes.App.Cross.Navigation;
using Nivaes.App.Cross.Sample;
using Nivaes.App.Cross.ViewModels;
public sealed class AppMobileSampleAppStart
: AppSampleAppStart, IMvxAppStart
{
public AppMobileSampleAppStart(ICrossApplication application, IMvxNavigationService navigationService)
: base(application, navigationService)
{
}
protected override ValueTask<bool> NavigateToFirstViewModel(object? hint = null)
{
return base.NavigationService.Navigate<RootViewModel>();
}
}
}
|
// SPDX-License-Identifier: BSD-3-Clause
//
// Copyright 2020 Raritan Inc. All rights reserved.
//
// This file was generated by IdlC from Net.idl.
using System;
using System.Linq;
using LightJson;
using Com.Raritan.Idl;
using Com.Raritan.JsonRpc;
using Com.Raritan.Util;
#pragma warning disable 0108, 0219, 0414, 1591
namespace Com.Raritan.Idl.net {
public class EthLinkMode : ICloneable {
public object Clone() {
EthLinkMode copy = new EthLinkMode();
copy.speed = this.speed;
copy.duplexMode = this.duplexMode;
return copy;
}
public LightJson.JsonObject Encode() {
LightJson.JsonObject json = new LightJson.JsonObject();
json["speed"] = (int)this.speed;
json["duplexMode"] = (int)this.duplexMode;
return json;
}
public static EthLinkMode Decode(LightJson.JsonObject json, Agent agent) {
EthLinkMode inst = new EthLinkMode();
inst.speed = (Com.Raritan.Idl.net.EthSpeed)(int)json["speed"];
inst.duplexMode = (Com.Raritan.Idl.net.EthDuplexMode)(int)json["duplexMode"];
return inst;
}
public Com.Raritan.Idl.net.EthSpeed speed = Com.Raritan.Idl.net.EthSpeed.SPEED_AUTO;
public Com.Raritan.Idl.net.EthDuplexMode duplexMode = Com.Raritan.Idl.net.EthDuplexMode.DUPLEX_MODE_AUTO;
}
}
|
namespace Valerie.Enums
{
public enum LogSource
{
/// <summary>Ready</summary>
RDY,
/// <summary>Connected</summary>
CNN,
/// <summary>Disconnected</summary>
DSN,
/// <summary>Discord</summary>
DSD,
/// <summary>Database</summary>
DTB,
/// <summary>Left Guild</summary>
LGD,
/// <summary>Joined Guild</summary>
JGD,
/// <summary>Guild Available</summary>
GAB,
/// <summary>User Joined</summary>
UJN,
/// <summary>User Left</summary>
ULT,
/// <summary>Document</summary>
DOC,
/// <summary>Config</summary>
CNF,
/// <summary>Event</summary>
EVT,
/// <summary>Update</summary>
UPT,
/// <summary>Exception</summary>
EXC
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace XSMP.MediaDatabase.Models
{
public partial class Artist
{
public Artist()
{
Album = new HashSet<Album>();
ArtistSong = new HashSet<ArtistSong>();
}
[Key]
public string Name { get; set; }
[Required]
public string NiceName { get; set; }
[InverseProperty("ArtistNameNavigation")]
public virtual ICollection<Album> Album { get; set; }
[InverseProperty("ArtistNameNavigation")]
public virtual ICollection<ArtistSong> ArtistSong { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
using System.Xml.Serialization;
namespace GDICanvas
{
public class GDILine : GDIObject
{
public float X1 { get; set; }
public float X2 { get; set; }
public float Y1 { get; set; }
public float Y2 { get; set; }
public GDILine(GDIObjectContainer parent = null) : base(parent)
{
}
public override void Draw(Graphics g)
{
if (X2 == X1 || Y2 == Y1)
return;
g.DrawLine(new Pen(Color.FromArgb(LineAlpha, LineColor.ToColor()), LineThickness),
new PointF(X1, Y1), new PointF(X2, Y2));
}
}
}
|
using App.Core.UseCases.SearchBlogPosts;
using Castle.Windsor;
using Castle.Windsor.Installer;
using FD.CleanArchitecture.Core.Interactor;
using System;
using System.Reflection;
namespace App.ConsoleInterface
{
class Program
{
static void Main(string[] args)
{
var container = new WindsorContainer();
container.Install(FromAssembly.InThisApplication(Assembly.GetEntryAssembly()));
var factory = container.Resolve<IInteractorsFactory>();
var outputboundary = new ConsolePresenter();
var request = new SearchBlogPostsRequest(string.Empty, null, null);
var usecase = factory.Create<SearchBlogPostsRequest, SearchBlogPostsResponse>(outputboundary);
usecase.Execute(request);
Console.ReadKey();
}
}
}
|
using System.Threading.Tasks;
using WorkflowDatabase.EF.Interfaces;
namespace Portal.Helpers
{
public interface ITaskDataHelper
{
Task<ITaskData> GetTaskData(string activityName, int processId);
Task<IProductActionData> GetProductActionData(string activityName, int processId);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SmashLabs.Tools
{
public class ErrorHandling
{
public static void ThrowError(object error)
{
throw new Exception(error.ToString());
}
}
}
|
using AutoFixture;
using AutoFixture.Dsl;
using AutoFixture.Kernel;
using NHSD.GPIT.BuyingCatalogue.EntityFramework.Users.Models;
namespace NHSD.GPIT.BuyingCatalogue.Test.Framework.AutoFixtureCustomisations
{
internal sealed class AspNetUserCustomization : ICustomization
{
public void Customize(IFixture fixture)
{
static ISpecimenBuilder ComposerTransformation(ICustomizationComposer<AspNetUser> composer) => composer
.Without(u => u.AspNetUserClaims)
.Without(u => u.AspNetUserLogins)
.Without(u => u.AspNetUserRoles)
.Without(u => u.AspNetUserTokens)
.Without(u => u.PrimaryOrganisation)
.Without(u => u.LastUpdatedByUser);
fixture.Customize<AspNetUser>(ComposerTransformation);
}
}
}
|
using System;
using ChartDirector;
namespace CSharpChartExplorer
{
public class overlapbar : DemoModule
{
//Name of demo module
public string getName() { return "Overlapping Bar Chart"; }
//Number of charts produced in this demo module
public int getNoOfCharts() { return 1; }
//Main code for creating chart.
//Note: the argument chartIndex is unused because this demo only has 1 chart.
public void createChart(WinChartViewer viewer, int chartIndex)
{
// The data for the bar chart
double[] data0 = {100, 125, 156, 147, 87, 124, 178, 109, 140, 106, 192, 122};
double[] data1 = {122, 156, 179, 211, 198, 177, 160, 220, 190, 188, 220, 270};
double[] data2 = {167, 190, 213, 267, 250, 320, 212, 199, 245, 267, 240, 310};
string[] labels = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept",
"Oct", "Nov", "Dec"};
// Create a XYChart object of size 580 x 280 pixels
XYChart c = new XYChart(580, 280);
// Add a title to the chart using 14pt Arial Bold Italic font
c.addTitle("Product Revenue For Last 3 Years", "Arial Bold Italic", 14);
// Set the plot area at (50, 50) and of size 500 x 200. Use two alternative background
// colors (f8f8f8 and ffffff)
c.setPlotArea(50, 50, 500, 200, 0xf8f8f8, 0xffffff);
// Add a legend box at (50, 25) using horizontal layout. Use 8pt Arial as font, with
// transparent background.
c.addLegend(50, 25, false, "Arial", 8).setBackground(Chart.Transparent);
// Set the x axis labels
c.xAxis().setLabels(labels);
// Draw the ticks between label positions (instead of at label positions)
c.xAxis().setTickOffset(0.5);
// Add a multi-bar layer with 3 data sets
BarLayer layer = c.addBarLayer2(Chart.Side);
layer.addDataSet(data0, 0xff8080, "Year 2003");
layer.addDataSet(data1, 0x80ff80, "Year 2004");
layer.addDataSet(data2, 0x8080ff, "Year 2005");
// Set 50% overlap between bars
layer.setOverlapRatio(0.5);
// Add a title to the y-axis
c.yAxis().setTitle("Revenue (USD in millions)");
// Output the chart
viewer.Chart = c;
//include tool tip for the chart
viewer.ImageMap = c.getHTMLImageMap("clickable", "",
"title='{xLabel} Revenue on {dataSetName}: {value} millions'");
}
}
}
|
@model OrchardCore.Users.ViewModels.ForgotPasswordViewModel
@{
ViewLayout = "Layout__Login";
}
<div class="govuk-width-container">
<h2 class="govuk-heading-s">@T["Forgot password?"]</h2>
<h2 class="govuk-heading-s">@T["Please check your email to reset your password."]</h2>
<hr />
<div class="govuk-grid-row">
<div class="col-md-8">
<form asp-controller="ResetPassword" asp-action="ForgotPassword" method="post" class="form-horizontal">
<div asp-validation-summary="All" class="govuk-error-message"></div>
<div class="govuk-form-group">
<label asp-for="Email" class="col-md-4 govuk-label">@T["Email"]</label>
<div class="col-md-9">
<input asp-for="Email" class="govuk-input" />
</div>
</div>
@await RenderSectionAsync("AfterForgotPassword", required: false)
<div class="govuk-form-group">
<div class="col-md-offset-4 col-md-8">
<button type="submit" class="govuk-button">@T["Submit"]</button>
</div>
</div>
</form>
</div>
</div>
</div> |
using Cysharp.Threading.Tasks;
using UnityEngine;
using UnityEngine.AddressableAssets;
public static class GameInitializer
{
[RuntimeInitializeOnLoadMethod]
private static async void Init()
{
Application.targetFrameRate = 60;
GameObject gameSysObj = await Addressables.InstantiateAsync("GameSystem");
Object.DontDestroyOnLoad(gameSysObj);
}
}
|
using SIS.MvcFramework;
using System.Collections.Generic;
namespace BattleCards.Models
{
public class User : IdentityUser<string>
{
public User()
{
this.userCards = new HashSet<UserCard>();
}
public ICollection<UserCard> userCards { get; set; }
}
}
|
namespace SuperServiceJob {
public enum Result {
Success,
ParsingError,
SyncError
}
} |
using System.Reflection;
using TechTalk.SpecFlow.MsBuildNetSdk.IntegrationTests.Features;
using Xunit;
namespace TechTalk.SpecFlow.MsBuildNetSdk.IntegrationTests
{
public class CodeBehindFileGenerationTests
{
[Fact]
public void TestIfCodeBehindFilesWasGeneratedAndCompiled()
{
var assemblyHoldingThisClass = Assembly.GetExecutingAssembly();
var typeOfGeneratedFeatureFile = assemblyHoldingThisClass.GetType(typeof(DummyFeatureFileToTestMSBuildNetsdkCodebehindFileGenerationFeature).FullName);
Assert.NotNull(typeOfGeneratedFeatureFile);
}
}
}
|
using System;
using System.Threading;
using System.Threading.Tasks;
using StackExchange.Redis;
namespace HotChocolate.Subscriptions.Redis
{
public class RedisEventStream
: IEventStream
{
private readonly IEventDescription _eventDescription;
private readonly ChannelMessageQueue _channel;
private readonly IPayloadSerializer _serializer;
private bool _isCompleted;
public RedisEventStream(
IEventDescription eventDescription,
ChannelMessageQueue channel,
IPayloadSerializer serializer)
{
_eventDescription = eventDescription;
_channel = channel;
_serializer = serializer;
}
public bool IsCompleted => _isCompleted;
public Task<IEventMessage> ReadAsync() =>
ReadAsync(CancellationToken.None);
public async Task<IEventMessage> ReadAsync(
CancellationToken cancellationToken)
{
ChannelMessage message = await _channel
.ReadAsync(cancellationToken);
var payload = _serializer.Deserialize(message.Message);
return new EventMessage(message.Channel, payload);
}
public async Task CompleteAsync()
{
if (!_isCompleted)
{
await _channel.UnsubscribeAsync()
.ConfigureAwait(false);
_isCompleted = true;
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public void Dispose(bool disposing)
{
if (!_isCompleted)
{
if (disposing)
{
_channel.Unsubscribe();
}
_isCompleted = true;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
namespace bilong.Data.Repository.Memory
{
public class MemoryStorableRepository<T> : IStorableRepository<T> where T : IStorable
{
private readonly Dictionary<object, T> _memoryStore = new Dictionary<object, T>();
public Task<T> Add(T entity, string userId)
{
lock (_memoryStore)
{
if (string.IsNullOrEmpty(entity.Id)) entity.Id = Guid.NewGuid().ToString();
var time = DateTime.UtcNow;
entity.CreatedTime = time;
entity.CreatorId = userId;
entity.ModifiedTime = time;
entity.ModifierId = userId;
_memoryStore.Add(entity.Id, entity);
return Task.FromResult(entity);
}
}
public Task<IEnumerable<T>> FindAll()
{
lock (_memoryStore)
{
IEnumerable<T> result = _memoryStore.Values.ToList();
return Task.FromResult(result);
}
}
public Task<IEnumerable<T>> Find(Expression<Func<T, bool>> filter)
{
lock (_memoryStore)
{
IEnumerable<T> result = _memoryStore.Values.Where(filter.Compile()).ToList();
return Task.FromResult(result);
}
}
public Task<T> FindOne(Expression<Func<T, bool>> filter)
{
lock (_memoryStore)
{
return Task.FromResult(_memoryStore.Values.FirstOrDefault(filter.Compile()));
}
}
public Task<T> Replace(T entity, string userId)
{
lock (_memoryStore)
{
if (string.IsNullOrEmpty(entity.Id))
throw new ArgumentNullException(nameof(entity.Id), "Id must contain a value");
var existingEntity = _memoryStore[entity.Id];
entity.CreatedTime = existingEntity.CreatedTime;
entity.CreatorId = existingEntity.CreatorId;
entity.ModifiedTime = DateTime.UtcNow;
entity.ModifierId = userId;
_memoryStore[entity.Id] = entity;
return Task.FromResult(entity);
}
}
public Task Delete(T entity, string userId)
{
lock (_memoryStore)
{
_memoryStore.Remove(entity.Id);
return Task.CompletedTask;
}
}
}
} |
using SOArchitecture;
using UnityEngine;
[CreateAssetMenu(menuName = "Variable/Transform")]
public class TransformVariable : GameVariable<Transform>
{
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Visitor
{
public abstract class Action
{
public abstract void GetManConclusion();
public abstract void GetWomanConclusion();
}
public class Success : Action
{
public override void GetManConclusion()
{
Console.WriteLine($"When Man {this.GetType().Name}. man backward has a great woman");
}
public override void GetWomanConclusion()
{
Console.WriteLine($"When Woman {this.GetType().Name}. woman backward has a bad man");
}
}
public class Failed : Action
{
public override void GetManConclusion()
{
Console.WriteLine($"When Man {this.GetType().Name},He wants to drink.");
}
public override void GetWomanConclusion()
{
Console.WriteLine($"When Woman {this.GetType().Name}. woman wants to buy buy buy");
}
}
public class FallInLove : Action
{
public override void GetManConclusion()
{
Console.WriteLine($"When Man {this.GetType().Name},He Know Everything.");
}
public override void GetWomanConclusion()
{
Console.WriteLine($"When Woman {this.GetType().Name},She Know nothing.");
}
}
public class Marriage : Action
{
public override void GetManConclusion()
{
Console.WriteLine($"When Man {this.GetType().Name},He Has No Money.");
}
public override void GetWomanConclusion()
{
Console.WriteLine($"When Woman {this.GetType().Name},She Has Much Money.");
}
}
public abstract class PersonAdvance
{
public abstract void Accept(Action visitor);
}
public class ManAdvance : PersonAdvance
{
public override void Accept(Action visitor)
{
visitor.GetManConclusion();
}
}
public class WomanAdvance : PersonAdvance
{
public override void Accept(Action visitor)
{
visitor.GetWomanConclusion();
}
}
public class ObjectStructure
{
private IList<PersonAdvance> elements = new List<PersonAdvance>();
public void Attach(PersonAdvance personAdvance)
{
elements.Add(personAdvance);
}
public void Detach(PersonAdvance personAdvance)
{
elements.Remove(personAdvance);
}
public void Display(Action visitor)
{
foreach (var item in elements)
{
item.Accept(visitor);
}
}
}
}
|
using FeatureLoom.Diagnostics;
using System;
using Xunit;
namespace FeatureLoom.MessageFlow
{
public class ForwarderTests
{
[Theory]
[InlineData(42)]
[InlineData("test string")]
public void CanForwardObjectsAndValues<T>(T message)
{
TestHelper.PrepareTestContext();
var sender = new Sender<T>();
var forwarder = new Forwarder();
var sink = new SingleMessageTestSink<T>();
sender.ConnectTo(forwarder).ConnectTo(sink);
sender.Send(message);
Assert.True(sink.received);
Assert.Equal(message, sink.receivedMessage);
}
[Fact]
public void TypedForwarderFailsWhenConnectedToWrongType()
{
TestHelper.PrepareTestContext();
Forwarder<int> intForwarder = new Forwarder<int>();
Forwarder<int> intForwarder2 = new Forwarder<int>();
Forwarder<string> stringForwarder = new Forwarder<string>();
Forwarder<object> objectForwarder = new Forwarder<object>();
Assert.ThrowsAny<Exception>(() => intForwarder.ConnectTo(stringForwarder));
Assert.ThrowsAny<Exception>(() => objectForwarder.ConnectTo(stringForwarder));
intForwarder.ConnectTo(intForwarder2);
Assert.True(intForwarder.CountConnectedSinks == 1);
stringForwarder.ConnectTo(objectForwarder);
Assert.True(stringForwarder.CountConnectedSinks == 1);
intForwarder2.ConnectTo(objectForwarder);
Assert.True(intForwarder2.CountConnectedSinks == 1);
}
}
} |
using BuilderDesignPattern.Lab_1.Abstraction;
using BuilderDesignPattern.Lab_1.Delegate;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BuilderDesignPattern.Lab_1.Concrete
{
public class Builder_2 : IBuilder
{
private Product product = new Product();
public void BuilderPartA()
{
product.Add("Part X");
}
public void BuilderPartB()
{
product.Add("Part Y");
}
public Product GetResult()
{
return product;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TicTacToe.Engine.Players;
namespace TicTacToe.Engine.Games
{
public class MultiPlayerGame : Game
{
public MultiPlayerGame(HumanPlayer player1, HumanPlayer player2)
:base(player1, player2)
{
}
}
}
|
#define NET35
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
#if NET35
namespace Peach.AeronetInversion
{
public class Path
{
public static string Combine(string path, params string[] paths)
{
if (paths == null || paths.Length == 0) return path;
else
{
string result = path;
foreach (string p in paths)
{
result = System.IO.Path.Combine(result, p);
}
return result;
}
}
}
}
#endif
|
using UnityEngine;
namespace Fumohouse.ScriptableObjects
{
public abstract class PartData : ScriptableObject
{
public string PartName;
public Scope Scope;
}
}
|
using System;
using Ditto.Internal;
namespace Ditto.Criteria
{
public class TypePropertyCriterion:IPropertyCriterion
{
private readonly Type targetType;
public TypePropertyCriterion(Type targetType)
{
this.targetType = targetType;
}
public bool IsSatisfiedBy(IDescribeMappableProperty property)
{
return property.PropertyType.IsOneOf(targetType);
}
}
} |
using System.Collections.Generic;
using System.Threading.Tasks;
using IoTHs.Api.Shared;
namespace IoTHs.Devices.Interfaces
{
public interface IPluginRegistry
{
void RegisterPluginType<T>() where T : class, IPlugin;
IEnumerable<T> GetPlugins<T>() where T : class, IPlugin;
T GetPlugin<T>() where T : class, IPlugin;
T GetPlugin<T>(string name) where T : class, IPlugin;
Task TeardownPluginsAsync();
object GetPlugin(string name);
IEnumerable<IPlugin> GetPlugins();
Task InitializePluginsAsync(AppConfigurationModel configurationObject);
}
}
|
namespace BeyondNet.App.Ums.Domain.User.Key
{
public static class EKeyStatus
{
public static int Active = 1;
public static int Inactive = 1;
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace IDEIMusic.Models
{
public interface ISaleRepository
{
IEnumerable<SaleSummary> GetSaleSummaries();
IEnumerable<SaleSummary> GetSaleSummariesBySales();
IEnumerable<SaleSummary> GetSaleSummariesByIncome();
}
} |
using System;
using System.Collections.Generic;
using System.Net.Http.Headers;
using KeyPayV2.Au.Models.Common;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json;
using KeyPayV2.Au.Enums;
namespace KeyPayV2.Au.Models.PayRun
{
public class AuApiPaySlipModel
{
public IList<ApiPaySlipPaygAdjustmentModel> PaygAdjustments { get; set; }
public IList<ApiPaySlipSuperAdjustmentModel> SuperAdjustments { get; set; }
public IList<ApiPaySlipSuperPaymentModel> SuperPayments { get; set; }
public IList<AuApiPaySlipBankPaymentModel> BankPayments { get; set; }
public IList<AuApiPaySlipEarningsLineModel> EarningsLines { get; set; }
public decimal PaygWithholdingAmount { get; set; }
public decimal SfssAmount { get; set; }
public decimal HelpAmount { get; set; }
public decimal SuperContribution { get; set; }
public string EmployeePostalSuburbName { get; set; }
public string EmployeePostalSuburbPostcode { get; set; }
public string EmployeePostalSuburbState { get; set; }
public decimal SuperYTD { get; set; }
public decimal SfssYTD { get; set; }
public decimal HelpYTD { get; set; }
public decimal PaygYTD { get; set; }
public string Abn { get; set; }
public IList<ApiPaySlipLeaveModel> TotalAccruedLeave { get; set; }
public IList<ApiPaySlipLeaveModel> AccruedLeave { get; set; }
public IList<ApiPaySlipLeaveModel> LeaveTaken { get; set; }
public IList<ApiPaySlipDeductionModel> Deductions { get; set; }
public IList<ApiYearToDateEarningsBreakdownModel> GrossYTDDetails { get; set; }
public IList<ApiEmployeeExpenseGridModel> EmployeeExpenses { get; set; }
public decimal TotalHours { get; set; }
public decimal GrossEarnings { get; set; }
public decimal NetEarnings { get; set; }
public decimal TaxableEarnings { get; set; }
public decimal PostTaxDeductionAmount { get; set; }
public decimal PreTaxDeductionAmount { get; set; }
public int Id { get; set; }
public string BusinessName { get; set; }
public string BusinessAddress { get; set; }
public string ContactName { get; set; }
public string PayPeriodStarting { get; set; }
public string PayPeriodEnding { get; set; }
public string Message { get; set; }
public int EmployeeId { get; set; }
public string EmployeeExternalId { get; set; }
public string EmployeeName { get; set; }
public string EmployeeFirstName { get; set; }
public string EmployeeSurname { get; set; }
public string EmployeePostalStreetAddress { get; set; }
public string EmployeePostalAddressLine2 { get; set; }
public string EmployeePostalAddressCountry { get; set; }
public string Notation { get; set; }
public bool IsPublished { get; set; }
public decimal GrossYTD { get; set; }
public decimal NetYTD { get; set; }
public decimal WithholdingYTD { get; set; }
public string BasePayRate { get; set; }
public string BaseRate { get; set; }
public decimal HourlyRate { get; set; }
public decimal PreTaxDeductionsYTD { get; set; }
public decimal PostTaxDeductionsYTD { get; set; }
public decimal EmployeeBaseRate { get; set; }
[JsonConverter(typeof(StringEnumConverter))]
public RateUnitEnum EmployeeBaseRateUnit { get; set; }
}
}
|
using QHomeGroup.Data.Entities.Content;
using QHomeGroup.Infrastructure.Interfaces;
namespace QHomeGroup.Application.Common
{
public class CommonService : ICommonService
{
private IRepository<Slide, int> _slideRepository;
private IUnitOfWork _unitOfWork;
public CommonService(IUnitOfWork unitOfWork, IRepository<Slide, int> slideRepository)
{
_unitOfWork = unitOfWork;
_slideRepository = slideRepository;
}
}
} |
// MIT License
// Copyright (c) 2011-2016 Elisée Maurer, Sparklin Labs, Creative Patterns
// Copyright (c) 2016 Thomas Morgner, Rabbit-StewDio Ltd.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using Steropes.UI.Components;
using Steropes.UI.Styles.Io.Parser;
using Steropes.UI.Styles.Io.Values;
using Steropes.UI.Styles.Selector;
using Steropes.UI.Util;
using Steropes.UI.Widgets;
using Steropes.UI.Widgets.TextWidgets;
namespace Steropes.UI.Styles.Io.Writer
{
public interface IStyleWriter : IStyleSerializerConfiguration
{
IStyleSystem StyleSystem { get; }
XDocument Write(IEnumerable<IStyleRule> rules);
XElement WriteRule(IStyleRule r);
}
public class StyleWriter : IStyleWriter
{
readonly ConditionWriter conditionWriter;
readonly Dictionary<Type, IStylePropertySerializer> propertyParsers;
readonly Dictionary<string, IStyleKey> registeredKeys;
public StyleWriter(IStyleSystem styleSystem)
{
StyleSystem = styleSystem;
registeredKeys = new Dictionary<string, IStyleKey>();
propertyParsers = new Dictionary<Type, IStylePropertySerializer>();
conditionWriter = new ConditionWriter();
RegisterPropertyParsers(new BoolValueStylePropertySerializer());
RegisterPropertyParsers(new ColorValueStylePropertySerializer());
RegisterPropertyParsers(new FloatValueStylePropertySerializer());
RegisterPropertyParsers(new IntValueStylePropertySerializer());
RegisterPropertyParsers(new StringValueStylePropertySerializer());
RegisterPropertyParsers(new InsetsStylePropertySerializer());
}
public IStyleSystem StyleSystem { get; }
public void RegisterPropertyParsers(IStylePropertySerializer p)
{
conditionWriter.Register(p);
propertyParsers.Add(p.TargetType, p);
}
public void RegisterStyles(IStyleDefinition styleDefinitions)
{
var properties = styleDefinitions.GetType().GetProperties();
for (var i = 0; i < properties.Length; i++)
{
var property = properties[i];
if (!property.CanRead)
{
continue;
}
if (property.GetIndexParameters().Length > 0)
{
continue;
}
if (!typeof(IStyleKey).IsAssignableFrom(property.PropertyType))
{
continue;
}
var getter = property.GetGetMethod();
var key = (IStyleKey)getter?.Invoke(styleDefinitions, new object[0]);
if (key != null && StyleSystem.IsRegisteredKey(key))
{
registeredKeys[key.Name] = key;
}
}
}
public XDocument Write(IEnumerable<IStyleRule> rules)
{
var root = new XElement(StyleParser.StyleNamespace + "styles");
root.Add(new XAttribute("xmlns", StyleParser.StyleNamespace));
rules.Select(WriteRule).Merge().ForEach(root.Add);
var doc = new XDocument(new XDeclaration("1.0", "UTF-8", "yes"));
doc.Add(root);
return doc;
}
public XElement WriteRule(IStyleRule r)
{
var element = new XElement("style");
var innerStyle = ProcessSelector(element, r.Selector);
foreach (var pair in registeredKeys)
{
object raw;
if (r.Style.GetValue(pair.Value, out raw))
{
var propertyElement = new XElement("property");
propertyElement.Add(new XAttribute("name", pair.Key));
if (InheritMarker.IsInheritMarker(raw))
{
propertyElement.Add(new XAttribute("inherit", "true"));
}
else
{
IStylePropertySerializer p;
if (propertyParsers.TryGetValue(pair.Value.ValueType, out p))
{
p.Write(StyleSystem, propertyElement, raw);
}
else
{
throw new StyleWriterException("Key " + pair.Key + " was not registered.");
}
}
innerStyle.Add(propertyElement);
}
}
return element;
}
List<Tuple<bool, ISimpleSelector>> ExtractSelectors(DescendantSelector s)
{
var retval = new List<Tuple<bool, ISimpleSelector>>();
while (true)
{
retval.Add(Tuple.Create(s.DirectChild, s.Selector));
if (s.AnchestorSelector is DescendantSelector)
{
s = (DescendantSelector)s.AnchestorSelector;
}
else if (s.AnchestorSelector is ISimpleSelector)
{
retval.Add(Tuple.Create(true, (ISimpleSelector)s.AnchestorSelector));
return retval;
}
else
{
throw new StyleWriterException();
}
}
}
XElement ProcessSelector(XElement style, IStyleSelector selector)
{
if (selector is DescendantSelector)
{
var ds = (DescendantSelector)selector;
var extractSelectors = ExtractSelectors(ds);
extractSelectors.Reverse();
var first = true;
foreach (var tuple in extractSelectors)
{
if (!first)
{
var inner = new XElement("style");
style.Add(inner);
style = inner;
style.Add(new XAttribute("direct-child", tuple.Item1));
}
else
{
first = false;
}
ProcessSimpleSelector(style, tuple.Item2);
}
return style;
}
if (selector is ISimpleSelector)
{
ProcessSimpleSelector(style, (ISimpleSelector)selector);
return style;
}
throw new StyleWriterException();
}
void ProcessSimpleSelector(XElement style, ISimpleSelector selector)
{
if (selector is ConditionalSelector)
{
var cs = (ConditionalSelector)selector;
var conditions = new XElement("conditions");
conditionWriter.Write(StyleSystem, conditions, cs.Condition, conditionWriter);
style.Add(conditions);
selector = cs.Selector;
}
if (selector is ElementSelector)
{
var es = (ElementSelector)selector;
style.Add(new XAttribute("element", es.TypeName));
}
}
}
} |
using System;
using Shouldly;
using Vertical.ConsoleApplications.Utilities;
using Xunit;
namespace Vertical.ConsoleApplications.Test.Utilities
{
public class TokenHelperTests
{
[Theory]
[InlineData("arg1", "arg1")]
[InlineData("arg1+arg2", "arg1")]
[InlineData("arg1+arg2+arg3", "arg1")]
[InlineData("arg1+arg2+arg3", "arg1 arg2")]
[InlineData("arg1+arg2+arg3", "arg1 arg2 arg3")]
public void IsCommandMatchPositives(string args, string command)
{
var split = args.Split('+');
TokenHelpers.IsCommandMatch(split, command).ShouldBeTrue();
}
[Fact]
public void ReplaceEnvironmentVariablesReplacesSymbols()
{
var result = TokenHelpers.ReplaceEnvironmentVariables("Path is $PATH");
result.ShouldBe($"Path is {Environment.GetEnvironmentVariable("PATH")}");
}
[Fact]
public void ReplaceSpecialFolderTokensReplacesSymbols()
{
var result = TokenHelpers.ReplaceSpecialFolderPaths("Path is $ApplicationData");
result.ShouldBe($"Path is {Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)}");
}
}
} |
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file, You can obtain one at https://opensource.org/licenses/MIT.
// Copyright (C) Leszek Pomianowski and WPF UI Contributors.
// All Rights Reserved.
#nullable enable
using System.Collections.Generic;
using System.Windows;
using System.Windows.Media;
using Wpf.Ui.Appearance;
using Wpf.Ui.Common.Interfaces;
using Wpf.Ui.Demo.Models.Colors;
namespace Wpf.Ui.Demo.ViewModels;
public class ColorsViewModel : Wpf.Ui.Mvvm.ViewModelBase, INavigationAware
{
private bool _dataInitialized = false;
private readonly string[] _paletteResources =
{
"PalettePrimaryBrush",
"PaletteRedBrush",
"PalettePinkBrush",
"PalettePurpleBrush",
"PaletteDeepPurpleBrush",
"PaletteIndigoBrush",
"PaletteBlueBrush",
"PaletteLightBlueBrush",
"PaletteCyanBrush",
"PaletteTealBrush",
"PaletteGreenBrush",
"PaletteLightGreenBrush",
"PaletteLimeBrush",
"PaletteYellowBrush",
"PaletteAmberBrush",
"PaletteOrangeBrush",
"PaletteDeepOrangeBrush",
"PaletteBrownBrush",
"PaletteGreyBrush",
"PaletteBlueGreyBrush"
};
private readonly string[] _themeResources =
{
"SystemAccentColorLight1Brush",
"SystemAccentColorLight2Brush",
"SystemAccentColorLight3Brush",
"ControlElevationBorderBrush",
"CircleElevationBorderBrush",
"AccentControlElevationBorderBrush",
"TextFillColorPrimaryBrush",
"TextFillColorSecondaryBrush",
"TextFillColorTertiaryBrush",
"TextFillColorDisabledBrush",
"TextFillColorInverseBrush",
"AccentTextFillColorDisabledBrush",
"TextOnAccentFillColorSelectedTextBrush",
"ControlFillColorDefaultBrush",
"ControlFillColorSecondaryBrush",
"ControlFillColorTertiaryBrush",
"ControlFillColorDisabledBrush",
"ControlSolidFillColorDefaultBrush",
"AccentFillColorDisabledBrush",
"MenuBorderColorDefaultBrush",
"SystemFillColorSuccessBrush",
"SystemFillColorCautionBrush",
"SystemFillColorCriticalBrush",
"SystemFillColorNeutralBrush",
"SystemFillColorSolidNeutralBrush",
"SystemFillColorAttentionBackgroundBrush",
"SystemFillColorSuccessBackgroundBrush",
"SystemFillColorCautionBackgroundBrush",
"SystemFillColorCriticalBackgroundBrush",
"SystemFillColorNeutralBackgroundBrush",
"SystemFillColorSolidAttentionBackgroundBrush",
"SystemFillColorSolidNeutralBackgroundBrush"
};
public IEnumerable<Pa__one> PaletteBrushes
{
get => GetValue<IEnumerable<Pa__one>>() ?? new Pa__one[] { };
set => SetValue(value);
}
public IEnumerable<Pa__one> ThemeBrushes
{
get => GetValue<IEnumerable<Pa__one>>() ?? new Pa__one[] { };
set => SetValue(value);
}
public int Columns
{
get => GetStructOrDefault(8);
set => SetValue(value);
}
public ColorsViewModel()
{
Wpf.Ui.Appearance.Theme.Changed += ThemeOnChanged;
}
/// <inheritdoc />
protected override void OnViewCommand(object? parameter = null)
{
}
public void OnNavigatedTo()
{
if (!_dataInitialized)
InitializeData();
}
public void OnNavigatedFrom()
{
}
private void ThemeOnChanged(ThemeType currentTheme, Color systemAccent)
{
FillTheme();
}
private void InitializeData()
{
_dataInitialized = true;
FillPalette();
FillTheme();
}
private void FillPalette()
{
var pallete = new List<Pa__one> { };
foreach (var singleBrushKey in _paletteResources)
{
var singleBrush = Application.Current.Resources[singleBrushKey] as Brush;
if (singleBrush == null)
continue;
string description;
if (singleBrush is SolidColorBrush solidColorBrush)
description =
$"R: {solidColorBrush.Color.R}, G: {solidColorBrush.Color.G}, B: {solidColorBrush.Color.B}";
else
description = "Gradient";
pallete.Add(new Pa__one
{
Title = "PALETTE",
Subtitle = description + "\n" + singleBrushKey,
Brush = singleBrush,
BrushKey = singleBrushKey
});
}
PaletteBrushes = pallete;
}
private void FillTheme()
{
var theme = new List<Pa__one> { };
foreach (var singleBrushKey in _themeResources)
{
var singleBrush = Application.Current.Resources[singleBrushKey] as Brush;
if (singleBrush == null)
continue;
string description;
if (singleBrush is SolidColorBrush solidColorBrush)
description =
$"R: {solidColorBrush.Color.R}, G: {solidColorBrush.Color.G}, B: {solidColorBrush.Color.B}";
else
description = "Gradient";
theme.Add(new Pa__one
{
Title = "THEME",
Subtitle = description + "\n" + singleBrushKey,
Brush = singleBrush,
BrushKey = singleBrushKey
});
}
ThemeBrushes = theme;
}
}
|
// <Snippet5>
/*
The following example demonstrates using asynchronous methods to
get Domain Name System information for the specified host computer.
*/
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Collections;
namespace Examples.AdvancedProgramming.AsynchronousOperations
{
// Create a state object that holds each requested host name,
// an associated IPHostEntry object or a SocketException.
public class HostRequest
{
// Stores the requested host name.
private string hostName;
// Stores any SocketException returned by the Dns EndGetHostByName method.
private SocketException e;
// Stores an IPHostEntry returned by the Dns EndGetHostByName method.
private IPHostEntry entry;
public HostRequest(string name)
{
hostName = name;
}
public string HostName
{
get
{
return hostName;
}
}
public SocketException ExceptionObject
{
get
{
return e;
}
set
{
e = value;
}
}
public IPHostEntry HostEntry
{
get
{
return entry;
}
set
{
entry = value;
}
}
}
public class UseDelegateAndStateForAsyncCallback
{
// The number of pending requests.
static int requestCounter;
static ArrayList hostData = new ArrayList();
static void UpdateUserInterface()
{
// Print a message to indicate that the application
// is still working on the remaining requests.
Console.WriteLine("{0} requests remaining.", requestCounter);
}
public static void Main()
{
// Create the delegate that will process the results of the
// asynchronous request.
AsyncCallback callBack = new AsyncCallback(ProcessDnsInformation);
string host;
do
{
Console.Write(" Enter the name of a host computer or <enter> to finish: ");
host = Console.ReadLine();
if (host.Length > 0)
{
// Increment the request counter in a thread safe manner.
Interlocked.Increment(ref requestCounter);
// Create and store the state object for this request.
HostRequest request = new HostRequest(host);
hostData.Add(request);
// Start the asynchronous request for DNS information.
Dns.BeginGetHostEntry(host, callBack, request);
}
} while (host.Length > 0);
// The user has entered all of the host names for lookup.
// Now wait until the threads complete.
while (requestCounter > 0)
{
UpdateUserInterface();
}
// Display the results.
foreach(HostRequest r in hostData)
{
if (r.ExceptionObject != null)
{
Console.WriteLine("Request for host {0} returned the following error: {1}.",
r.HostName, r.ExceptionObject.Message);
}
else
{
// Get the results.
IPHostEntry h = r.HostEntry;
string[] aliases = h.Aliases;
IPAddress[] addresses = h.AddressList;
if (aliases.Length > 0)
{
Console.WriteLine("Aliases for {0}", r.HostName);
for (int j = 0; j < aliases.Length; j++)
{
Console.WriteLine("{0}", aliases[j]);
}
}
if (addresses.Length > 0)
{
Console.WriteLine("Addresses for {0}", r.HostName);
for (int k = 0; k < addresses.Length; k++)
{
Console.WriteLine("{0}",addresses[k].ToString());
}
}
}
}
}
// The following method is invoked when each asynchronous operation completes.
static void ProcessDnsInformation(IAsyncResult result)
{
// Get the state object associated with this request.
HostRequest request = (HostRequest) result.AsyncState;
try
{
// Get the results and store them in the state object.
IPHostEntry host = Dns.EndGetHostEntry(result);
request.HostEntry = host;
}
catch (SocketException e)
{
// Store any SocketExceptions.
request.ExceptionObject = e;
}
finally
{
// Decrement the request counter in a thread-safe manner.
Interlocked.Decrement(ref requestCounter);
}
}
}
}
// </Snippet5>
|
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Umbraco.Cms.Core;
using Umbraco.Cms.Core.Models;
using Umbraco.Cms.Web.Common.Models;
namespace Umbraco.Cms.Web.Website.Models
{
public class RegisterModel : PostRedirectModel
{
public RegisterModel()
{
MemberTypeAlias = Constants.Conventions.MemberTypes.DefaultAlias;
UsernameIsEmail = true;
MemberProperties = new List<MemberPropertyModel>();
}
[Required]
[EmailAddress]
[Display(Name = "Email")]
public string Email { get; set; }
/// <summary>
/// Returns the member properties
/// </summary>
public List<MemberPropertyModel> MemberProperties { get; set; }
/// <summary>
/// The member type alias to use to register the member
/// </summary>
[Editable(false)]
public string MemberTypeAlias { get; set; }
/// <summary>
/// The members real name
/// </summary>
public string Name { get; set; }
/// <summary>
/// The members password
/// </summary>
[Required]
[StringLength(256)]
[DataType(System.ComponentModel.DataAnnotations.DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(System.ComponentModel.DataAnnotations.DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
/// <summary>
/// The username of the model, if UsernameIsEmail is true then this is ignored.
/// </summary>
public string Username { get; set; }
/// <summary>
/// Flag to determine if the username should be the email address, if true then the Username property is ignored
/// </summary>
public bool UsernameIsEmail { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace EnWebSockets
{
public enum WebSocketVersion
{
None = -1,
DraftHybi00 = 0,
DraftHybi10 = 8,
Rfc6455 = 13,
}
}
|
using System;
using System.Collections.Generic;
namespace Telefon_Rehberi_Uygulamas_
{
public static class AnaEkran
{
public static List<Kisiler> KisiList;
static AnaEkran()
{
KisiList = new List<Kisiler>()
{
new Kisiler("Recep","Şahin","3055651620"),
new Kisiler("Recep","Karapınar","3065412345"),
new Kisiler("İsmail","Sönmez","3512152014"),
new Kisiler("Onur","Alper","3012411932"),
new Kisiler("Ömer","Reis","5078484953")
};
KisiList.Sort((x,y)=> x.Isim.CompareTo(y.Isim));
}
public static void AnaEkranGoster()
{
Console.WriteLine("Lütfen yapmak istediğiniz işlemi seçiniz :) ");
Console.WriteLine("*******************************************");
Console.WriteLine("(1) Yeni Numara Kaydetmek");
Console.WriteLine("(2) Varolan Numarayı Silmek");
Console.WriteLine("(3) Varolan Numarayı Güncelleme");
Console.WriteLine("(4) Rehberi Listelemek");
Console.WriteLine("(5) Rehberde Arama Yapmak");
int number = int.Parse(Console.ReadLine());
TuslamaFonk(number);
}
public static void TuslamaFonk(int number)
{
switch (number)
{
case 1:
NumaraKaydetmeEkran.NumaraKaydetmeEkranGoster();
break;
case 2:
NumaraSilmeEkran.NumaraSilmeEkranGoster();
break;
case 3:
NumaraGuncellemeEkran.NumaraGuncellemeEkranGoster();
break;
case 4:
RehberListelemeEkran.RehberListelemeEkranGoster();
break;
case 5:
AramaYapmaEkran.AramaYapmaEkranGoster();
break;
default:
Console.WriteLine("Yanlış Karakter Tuşladınız");
AnaEkranGoster();
break;
}
}
}
} |
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using KeLi.HelloMvvmLight.Sample2.Models;
namespace KeLi.HelloMvvmLight.Sample2.ViewModels
{
public partial class BindingAdvancedViewModel
{
private List<CheckBottonModel> _checkButtonsData;
private string _checkInfo;
private ComboBoxItemModel _comboBoxItem;
private List<ComboBoxItemModel> _comboBoxData;
private ObservableCollection<FruitInfoViewModel> _userControlData;
private bool _isSingleRadioCheck;
private IEnumerable _listBoxData;
private CheckBottonModel _radioButton;
private List<CheckBottonModel> _radioButtons;
private string _singleRadioContent;
private List<TreeNodeModel> _treeData;
private ObservableCollection<UserInfoModel> _dataGridData;
public ComboBoxItemModel ComboBoxItem
{
get => _comboBoxItem;
set
{
_comboBoxItem = value;
RaisePropertyChanged(() => ComboBoxItem);
}
}
public List<ComboBoxItemModel> ComboBoxData
{
get => _comboBoxData;
set
{
_comboBoxData = value;
RaisePropertyChanged(() => ComboBoxData);
}
}
public string SingleRadioContent
{
get => _singleRadioContent;
set
{
_singleRadioContent = value;
RaisePropertyChanged(() => SingleRadioContent);
}
}
public bool IsSingleRadioCheck
{
get => _isSingleRadioCheck;
set
{
_isSingleRadioCheck = value;
RaisePropertyChanged(() => IsSingleRadioCheck);
}
}
public List<CheckBottonModel> RadioButtons
{
get => _radioButtons;
set
{
_radioButtons = value;
RaisePropertyChanged(() => RadioButtons);
}
}
public CheckBottonModel RadioButton
{
get => _radioButton;
set
{
_radioButton = value;
RaisePropertyChanged(() => RadioButton);
}
}
public List<CheckBottonModel> CheckButtons
{
get => _checkButtonsData;
set
{
_checkButtonsData = value;
RaisePropertyChanged(() => CheckButtons);
}
}
public string CheckInfo
{
get => _checkInfo;
set
{
_checkInfo = value;
RaisePropertyChanged(() => CheckInfo);
}
}
public List<TreeNodeModel> TreeData
{
get => _treeData;
set
{
_treeData = value;
RaisePropertyChanged(() => TreeData);
}
}
public ObservableCollection<UserInfoModel> DataGridData
{
get => _dataGridData;
set
{
_dataGridData = value;
RaisePropertyChanged(() => DataGridData);
}
}
public IEnumerable ListBoxData
{
get => _listBoxData;
set
{
_listBoxData = value;
RaisePropertyChanged(() => ListBoxData);
}
}
public ObservableCollection<FruitInfoViewModel> UserControlData
{
get => _userControlData;
set
{
_userControlData = value;
RaisePropertyChanged(() => UserControlData);
}
}
}
} |
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using System.Threading.Tasks;
namespace AkrDataSource
{
public abstract class PagingColletcionDataSourceBase<T, TParam> : ObservableCollection<T>,
IPagingColletcionDataSource<TParam>
{
protected int CurrentPageImpt;
protected TParam CurrentParam { get; set; }
public bool IsNoMoreData { get; set; }
public async Task Reload(TParam param)
{
IsNoMoreData = false;
OnPropertyChanged(new PropertyChangedEventArgs(nameof(IsNoMoreData)));
CurrentPageImpt = 0;
CurrentParam = param;
await SetPage(0, true);
}
public int CurrentPage => CurrentPageImpt;
public abstract int CountInPage(int page);
public abstract PagingType PagingType { get; }
public async Task Next()
{
CurrentPageImpt += 1;
await SetPage(CurrentPageImpt, false);
}
public async Task SetPage(int page, bool needClear)
{
IEnumerable<T> data;
try
{
data = await LoadDataImpt(page, CurrentParam);
}
catch (System.Exception ex)
{
throw;
}
finally
{
if (needClear || PagingType == PagingType.Paging && Count > 0)
{
Clear();
}
}
if (data == null || !data.Any())
{
IsNoMoreData = true;
OnPropertyChanged(new PropertyChangedEventArgs(nameof(IsNoMoreData)));
}
else
{
AddRange(data);
}
}
public void AddRange(IEnumerable<T> collection)
{
foreach (var i in collection)
{
Items.Add(i);
}
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add,
collection.ToList()));
}
protected abstract Task<IEnumerable<T>> LoadDataImpt(int page, TParam param);
}
} |
using FrannHammer.WebScraping.Domain.Contracts;
namespace FrannHammer.WebScraping.Domain
{
public class MiiSwordfighter : WebCharacter
{
public MiiSwordfighter()
: base("MiiSwordfighter", "Mii%20Swordfighter", null, "MiiSwordspider", "Mii Fighters")
{
DisplayName = "Mii Swordfighter";
CssKey = "mii";
}
}
} |
namespace NetRx.Store
{
public abstract class Reducer<TState>
{
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FrogControl : MonoBehaviour
{
private int MAX_JUMPS = 1;
private int FROG_JMP_Y = 400;
private int FROG_JMP_X = 100;
private float PROB_JMP=0.015f;
private bool movingToTheRigth;
private bool isTouchingFloor;
private bool isJumping;
private int jumps;
private Animator animator;
private Rigidbody2D rbd;
// Start is called before the first frame update
void Start()
{
movingToTheRigth = true;
isTouchingFloor = true;
isJumping = false;
jumps = 0;
animator = GetComponent<Animator>();
rbd = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void FixedUpdate()
{
if (Random.value < PROB_JMP) Jump();
}
void Jump()
{
if (isTouchingFloor && !isJumping && jumps < MAX_JUMPS)
{
float jmpDirection = (Random.value - 0.5f) < 0f ? -1f : 1f;
Vector2 jmp = new Vector2(-jmpDirection * FROG_JMP_X, FROG_JMP_Y);
animator.SetTrigger("Jump");
rbd.AddForce(jmp);
jumps++;
isJumping = true;
isTouchingFloor = false;
if (movingToTheRigth && jmpDirection < -0.1f)
{
movingToTheRigth = false;
Flip();
}
else if (!movingToTheRigth && jmpDirection > 0.1f)
{
movingToTheRigth = true;
Flip();
}
} else
{
isJumping = false;
}
}
void Flip()
{
var scale = transform.localScale;
scale.x *= -1;
transform.localScale = scale;
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.name == "Floor")
{
isTouchingFloor = true;
jumps = 0;
isJumping = false;
float angle = rbd.rotation;
while (angle > 0)
{
angle--;
rbd.rotation = angle;
}
while (angle < 0)
{
angle++;
rbd.rotation = angle;
}
}
}
private void OnTriggerExit2D(Collider2D collision)
{
if (collision.gameObject.name == "Floor")
{
isTouchingFloor = false;
isJumping = true;
}
}
} |
using System.Data;
namespace OpenBots.Core.Interfaces
{
public interface ISeleniumElementActionCommand
{
string v_InstanceName { get; set; }
DataTable v_SeleniumSearchParameters { get; set; }
string v_SeleniumSearchOption { get; set; }
string v_SeleniumElementAction { get; set; }
DataTable v_WebActionParameterTable { get; set; }
string v_Timeout { get; set; }
}
}
|
namespace Nager.Country.Translation
{
/// <summary>
/// ILanguageTranslation
/// </summary>
public interface ILanguageTranslation
{
/// <summary>
/// CommonName
/// </summary>
string CommonName { get; }
/// <summary>
/// OfficialName
/// </summary>
string OfficialName { get; }
TranslationInfo[] Translations { get; }
/// <summary>
/// ISO 639-1 language code
/// </summary>
LanguageCode LanguageCode { get; }
}
}
|
namespace Vendr.PaymentProviders.PayPal.Api.Models
{
public class PayPalRefundPayment : PayPalPayment
{
public static class Statuses
{
public const string CANCELLED = "CANCELLED";
public const string PENDING = "PENDING";
public const string COMPLETED = "COMPLETED";
}
}
}
|
using System.Collections.Generic;
using System.IO;
using System.Linq;
using ILRepacking;
namespace OxidePack.Client.Core.ILMerger
{
public class MergeSession
{
public string Directory;
public string[] Files;
public MergeSession(string directory, List<string> files)
: this(directory)
{
this.Files = files.ToArray();
}
public MergeSession(string directory)
{
this.Directory = directory;
}
public void LoadAllFiles()
{
this.Files = new DirectoryInfo(Directory).GetFiles("*.dll").Select(p=>p.FullName).ToArray();
}
public void Merge(string outputFile)
{
var repOptions = new RepackOptions()
{
InputAssemblies = Files,
SearchDirectories = new []{ Directory },
TargetPlatformVersion = "v4",
TargetKind = ILRepack.Kind.Dll,
OutputFile = outputFile
};
var r = new ILRepack(repOptions);
r.Repack();
}
}
} |
using System.Threading.Tasks;
using LimeFlight.OpenAPI.Diff.BusinessObjects;
namespace LimeFlight.OpenAPI.Diff.Output
{
public interface IRender
{
Task<string> Render(ChangedOpenApiBO diff);
}
} |
using AutoMapper;
using BriefShop.Core;
using BriefShop.UserDetails.Dto;
namespace BriefShop.UserDetails.Mappers
{
/// <summary>
/// UserDetail映射配置
/// </summary>
public class UserDetailDtoMapper : IDtoMapping
{
public void CreateMapping(IMapperConfigurationExpression mapper)
{
mapper.CreateMap<UserDetail, UserDetailDto>();
var map = mapper.CreateMap<UpdateUserLastVisitInput, UserDetail>();
map.ForMember(m => m.Id, o => o.Ignore());
}
}
}
|
using Jil;
using System;
namespace Aju.Carefree.NetCore.Helpers
{
/// <summary>
/// json serialization and deserialization, using Jil.
/// </summary>
public class JsonConvertor
{
public static string Serialize(object source, Jil.Options options = null)
{
return JSON.Serialize(source, options);
}
public static string Serialize<T>(T source, Jil.Options options = null)
{
return JSON.Serialize(source, options);
}
public static T Deserialize<T>(string source, Jil.Options options = null)
{
return JSON.Deserialize<T>(source, options);
}
public static object Deserialize(string source, Type destinationType, Jil.Options options = null)
{
return JSON.Deserialize(source, destinationType, options);
}
public static dynamic Deserialize(string source, Jil.Options options = null)
{
return JSON.DeserializeDynamic(source, options);
}
}
}
|
using System;
using JetBrains.Annotations;
using StereoKit;
namespace StereoKitApp.Utils
{
public static class BoundsExtensions
{
/// <summary>
/// Copy the bounds, and return a new Bounds with position and extents scaled.
/// </summary>
[Pure]
public static Bounds Scaled(this Bounds bounds, float scaleUniform)
{
return Scaled(bounds, Vec3.One * scaleUniform);
}
/// <summary>
/// Copy the bounds, and return a new Bounds with position and extents scaled.
/// </summary>
[Pure]
public static Bounds Scaled(this Bounds bounds, Vec3 scale)
{
var outBounds = bounds;
outBounds.center *= scale;
outBounds.dimensions *= scale;
return outBounds;
}
/// <summary>
/// Copy the bounds, and Convert the result to the Local Hierarchy.
/// </summary>
[Obsolete("Not actually obsolete, but I have not tested that this works yet...")]
[Pure]
public static Bounds ToLocal(this Bounds bounds)
{
var scale = Hierarchy.ToLocal(Vec3.One);
var outBounds = bounds;
outBounds.center = Hierarchy.ToLocal(outBounds.center) * scale;
outBounds.dimensions = Hierarchy.ToLocal(outBounds.dimensions) * scale;
return outBounds;
}
}
}
|
namespace MealPlan.Repo.Dto.Models
{
public class RecipeInfo
{
public string Name { get; set; }
public RecipeIngredientInfo[] Ingredients { get; set; }
public string[] Steps { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using UnityEngine.UI;
interface ChairState
{
void Occupied();
void Vacant();
}
[System.Serializable]
public class Chair : MonoBehaviour, ChairState
{
private bool empty = true;
public bool Empty
{
get { return empty; }
}
public void Occupied()
{
empty = false;
}
public void Vacant()
{
empty = true;
}
}
|
namespace StoryTeller.UserInterface.Screens
{
public abstract class ScreenSubject<T, SCREEN> : IScreenLocator<T> where SCREEN : class, IScreen
{
#region IScreenSubject<T> Members
public bool Matches(IScreen screen)
{
var theSpecificScreen = screen as SCREEN;
if (theSpecificScreen == null) return false;
return matches(theSpecificScreen);
}
public abstract IScreen CreateScreen(IScreenFactory factory);
#endregion
protected abstract bool matches(SCREEN screen);
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.