content stringlengths 23 1.05M |
|---|
namespace Game_Memory.Levels
{
class Level08 : Level
{
protected override void setProperties()
{
amountColumns = 8;
amountLines = 8;
amountFlag = 64;
bonusMultiplier = 8;
timeStopwatch = 500;
}
public override Level nextLevel()
{
return new Level09();
}
public override string getLevel()
{
return "Level 08";
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web.Routing;
namespace MvcSiteMapProvider.Web
{
/// <summary>
/// XmlSiteMapController class
/// </summary>
public class XmlSiteMapController
: Controller
{
/// <summary>
/// GET: /XmlSiteMap/Index
/// </summary>
/// <param name="page">The page.</param>
/// <returns>XmlSiteMapResult instance</returns>
public ActionResult Index(int page)
{
return new XmlSiteMapResult() { Page = page };
}
/// <summary>
/// Registers the routes.
/// </summary>
/// <param name="routeCollection">The route collection.</param>
public static void RegisterRoutes(RouteCollection routeCollection)
{
List<RouteBase> routes = new List<RouteBase> {
new Route("sitemap.xml",
new RouteValueDictionary(
new { controller = "XmlSiteMap", action = "Index", page = 0 }),
new MvcRouteHandler()),
new Route("sitemap-{page}.xml",
new RouteValueDictionary(
new { controller = "XmlSiteMap", action = "Index", page = 0 }),
new MvcRouteHandler())
};
if (routeCollection.Count == 0)
{
foreach (var route in routes)
{
routeCollection.Add(route);
}
}
else
{
foreach (var route in routes)
{
routeCollection.Insert(routeCollection.Count - 1, route);
}
}
}
}
}
|
// This is an open source non-commercial project. Dear PVS-Studio, please check it. PVS-Studio Static
// Code Analyzer for C, C++ and C#: http://www.viva64.com
namespace Nds.Extensions
{
using System;
using System.Collections.Generic;
/// <summary>
/// Extensions for the <see cref="IEnumerable{T}"/>.
/// </summary>
internal static class SeqIComparableExtensions
{
/// <summary>
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="Seq"></param>
/// <param name="OtherSeq"></param>
/// <param name="Cmp"></param>
/// <returns>
/// <para>
/// true, if <paramref name="Seq"/> and <paramref name="OtherSeq"/> are empty or they have
/// equal size and their elements are equal, otherwise false.
/// </para>
/// </returns>
public static bool CmpSeqEqual<T>(this IEnumerable<T> Seq, IEnumerable<T> OtherSeq, Comparison<T> Cmp)
{
bool isEqual = true, isNotEnd1, isNotEnd2;
using (IEnumerator<T> enum1 = Seq.GetEnumerator(), enum2 = OtherSeq.GetEnumerator())
{
while ((isNotEnd1 = enum1.MoveNext()) & (isNotEnd2 = enum2.MoveNext()))
{
T elem1 = enum1.Current;
T elem2 = enum2.Current;
if (ConverterResCmp.ConvertToResCmp(Cmp(elem1, elem2)) != ResComp.EQ)
{
isEqual = false;
break;
}
}
if (!isNotEnd1 || !isNotEnd2)
{
isEqual = false;
}
}
return isEqual;
}
/// <summary>
/// Find a minimum and maximum value in the <see cref="IEnumerable{T}"/>.
/// </summary>
/// <param name="Seq"></param>
/// <param name="Cmp"> <see cref="Comparison{T}"/>. </param>
/// <param name="MinValue"> A minimum value of the <paramref name="Seq"/>. </param>
/// <param name="MaxValue"> A maximum value of the <paramref name="Seq"/>. </param>
/// <exception cref="ArgumentNullException">
/// If <paramref name="Seq"/> is null or empty.
/// </exception>
public static void MinMax<T>(this IEnumerable<T> Seq, out T MinValue, out T MaxValue, Comparison<T> Cmp)
{
if (Seq == null)
{
throw new ArgumentNullException(nameof(Seq));
}
using (IEnumerator<T> enumerator = Seq.GetEnumerator())
{
if (!enumerator.MoveNext())
{
throw new ArgumentException($"The {nameof(Seq)} is empty.", nameof(Seq));
}
MinValue = enumerator.Current;
MaxValue = enumerator.Current;
ResComp resComp;
while (enumerator.MoveNext())
{
resComp = ConverterResCmp.ConvertToResCmp(Cmp(enumerator.Current, MinValue));
if (resComp == ResComp.LE)
{
MinValue = enumerator.Current;
}
else
{
resComp = ConverterResCmp.ConvertToResCmp(Cmp(enumerator.Current, MaxValue));
if (resComp == ResComp.GR)
{
MaxValue = enumerator.Current;
}
}
}
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace NtrSharp.NtrObject
{
[DataContract(IsReference=true)]
public class Process
{
[DataMember]
public String Name { get; set; }
[DataMember]
public MemoryRegion[] Memory { get; set; }
public Process(String Name, params MemoryRegion[] Memory)
{
this.Name = Name;
this.Memory = Memory;
}
}
}
|
//-----------------------------------------------------------------------
// <copyright file="LocalNetworkProvider.cs">
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// 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.
// </copyright>
//-----------------------------------------------------------------------
using System;
namespace Microsoft.PSharp.Net
{
/// <summary>
/// The local P# network provider.
/// </summary>
internal class LocalNetworkProvider : INetworkProvider
{
#region fields
/// <summary>
/// Instance of the P# runtime.
/// </summary>
private PSharpRuntime Runtime;
/// <summary>
/// The local endpoint.
/// </summary>
private string LocalEndpoint;
#endregion
#region constructors
/// <summary>
/// Constructor.
/// </summary>
/// <param name="runtime">PSharpRuntime</param>
public LocalNetworkProvider(PSharpRuntime runtime)
{
this.Runtime = runtime;
this.LocalEndpoint = "";
}
#endregion
#region methods
/// <summary>
/// Creates a new remote machine of the specified type
/// and with the specified event. An optional friendly
/// name can be specified. If the friendly name is null
/// or the empty string, a default value will be given.
/// </summary>
/// <param name="type">Type of the machine</param>
/// <param name="friendlyName">Friendly machine name used for logging</param>
/// <param name="endpoint">Endpoint</param>
/// <param name="e">Event</param>
/// <returns>MachineId</returns>
MachineId INetworkProvider.RemoteCreateMachine(Type type, string friendlyName,
string endpoint, Event e)
{
return this.Runtime.CreateMachine(type, friendlyName, e);
}
/// <summary>
/// Sends an asynchronous event to a machine.
/// </summary>
/// <param name="target">Target machine id</param>
/// <param name="e">Event</param>
void INetworkProvider.RemoteSend(MachineId target, Event e)
{
this.Runtime.SendEvent(target, e);
}
/// <summary>
/// Returns the local endpoint.
/// </summary>
/// <returns>Endpoint</returns>
string INetworkProvider.GetLocalEndpoint()
{
return this.LocalEndpoint;
}
/// <summary>
/// Disposes the network provider.
/// </summary>
public void Dispose() { }
#endregion
}
}
|
using Plugin.Settings;
using Plugin.Settings.Abstractions;
using System;
namespace AICompanion.Services
{
/// <summary>
/// This is the Settings static class that can be used in your Core solution or in any
/// of your client applications. All settings are laid out the same exact way with getters
/// and setters.
/// </summary>
public class SettingsService : ISettingsService
{
private readonly ISettings settings;
public SettingsService()
{
settings = CrossSettings.Current;
}
public string VisionRegion
{
get => settings.GetValueOrDefault(nameof(VisionRegion), null);
set => settings.AddOrUpdateValue(nameof(VisionRegion), value);
}
public string VisionSubscriptionKey
{
get => settings.GetValueOrDefault(nameof(VisionSubscriptionKey), null);
set => settings.AddOrUpdateValue(nameof(VisionSubscriptionKey), value);
}
public string FaceRegion
{
get => settings.GetValueOrDefault(nameof(FaceRegion), null);
set => settings.AddOrUpdateValue(nameof(FaceRegion), value);
}
public string FaceSubscriptionKey
{
get => settings.GetValueOrDefault(nameof(FaceSubscriptionKey), null);
set => settings.AddOrUpdateValue(nameof(FaceSubscriptionKey), value);
}
public string CustomVisionRegion
{
get => settings.GetValueOrDefault(nameof(CustomVisionRegion), null);
set => settings.AddOrUpdateValue(nameof(CustomVisionRegion), value);
}
public string CustomVisionProjectName
{
get => settings.GetValueOrDefault(nameof(CustomVisionProjectName), null);
set => settings.AddOrUpdateValue(nameof(CustomVisionProjectName), value);
}
public string CustomVisionPredictionKey
{
get => settings.GetValueOrDefault(nameof(CustomVisionPredictionKey), null);
set => settings.AddOrUpdateValue(nameof(CustomVisionPredictionKey), value);
}
public string CustomVisionIterationId
{
get => settings.GetValueOrDefault(nameof(CustomVisionIterationId), Guid.Empty.ToString("D"));
set => settings.AddOrUpdateValue(nameof(CustomVisionIterationId), value);
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
using PFDAL.Models;
namespace PFDAL.ConnectModels
{
public class RandomWeatherRequest
{
public int ContinentId { get; set; }
public int SeasonId { get; set; }
}
public class RandomWeatherResult
{
public bool Success { get; set; }
public int ContinentId { get; set; }
public int SeasonId { get; set; }
public List<Weather> WeatherList { get; set; }
}
}
|
using System;
using System.ComponentModel;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace ME.Base
{
/// <summary>
/// 強型別集合成員基礎類別。
/// </summary>
public class GCollectionItem : ICollectionItem
{
#region ICollectionItem 介面
/// <summary>
/// 設定所屬集合。
/// </summary>
/// <param name="collection">集合。</param>
public void SetCollection(ICollectionBase collection)
{
Collection = collection;
}
/// <summary>
/// 移除成員
/// </summary>
public void Remove()
{
if (Collection != null)
Collection.Remove(this);
}
#endregion
/// <summary>
/// 所屬集合。
/// </summary>
[JsonIgnore]
public ICollectionBase Collection { get; protected set; } = null;
}
}
|
namespace Babylon.Investments.Domain.Abstractions.Requests.Base
{
public abstract class Request
{
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace PCL49Lib
{
public class PCL49
{
public static string GetMessage() => "Hello from PCL Profile 49!";
}
}
|
using System;
using TweetinviCore.Enum;
using TweetinviCore.Interfaces;
using TweetinviCore.Interfaces.Models;
namespace TweetinviControllers.Search
{
public interface ISearchQueryValidator
{
bool IsSearchParameterValid(ITweetSearchParameters searchParameters);
bool IsSearchQueryValid(string searchQuery);
bool IsGeoCodeValid(IGeoCode geoCode);
bool IsLocaleParameterValid(string locale);
bool IsLangDefined(Language lang);
bool IsSinceIdDefined(long sinceId);
bool IsMaxIdDefined(long maxId);
bool IsMaximumNumberOfResultsDefined(int maximumResult);
bool IsUntilDefined(DateTime untilDateTime);
}
public class SearchQueryValidator : ISearchQueryValidator
{
public bool IsSearchParameterValid(ITweetSearchParameters searchParameters)
{
return searchParameters != null && IsAtLeasOneRequiredCriteriaSet(searchParameters);
}
private bool IsAtLeasOneRequiredCriteriaSet(ITweetSearchParameters searchParameters)
{
bool isSearchQuerySet = !String.IsNullOrEmpty(searchParameters.SearchQuery);
bool isSearchQueryValid = IsSearchQueryValid(searchParameters.SearchQuery);
bool isGeoCodeSet = IsGeoCodeValid(searchParameters.GeoCode);
return (isSearchQuerySet && isSearchQueryValid) || isGeoCodeSet;
}
public bool IsSearchQueryValid(string searchQuery)
{
// We might want to restrict the size to 1000 characters as indicated in the documentation
return true;
}
public bool IsGeoCodeValid(IGeoCode geoCode)
{
return geoCode != null;
}
public bool IsLocaleParameterValid(string locale)
{
return !String.IsNullOrEmpty(locale);
}
public bool IsLangDefined(Language lang)
{
return lang != Language.Undefined;
}
public bool IsSinceIdDefined(long sinceId)
{
return sinceId != -1;
}
public bool IsMaxIdDefined(long maxId)
{
return maxId != -1;
}
public bool IsMaximumNumberOfResultsDefined(int maximumResult)
{
return maximumResult != -1;
}
public bool IsUntilDefined(DateTime untilDateTime)
{
return untilDateTime != default (DateTime);
}
}
} |
using Microting.eFormApi.BasePn.Infrastructure.Models.API;
using System.Threading.Tasks;
using WorkOrders.Pn.Infrastructure.Models.Settings;
namespace WorkOrders.Pn.Abstractions
{
public interface IWorkOrdersSettingsService
{
Task<OperationDataResult<WorkOrdersSettingsModel>> GetAllSettingsAsync();
Task<OperationResult> AddSiteToSettingsAsync(int siteId);
Task<OperationResult> RemoveSiteFromSettingsAsync(int siteId);
Task<OperationResult> UpdateFolder(int folderId);
Task<OperationResult> UpdateTaskFolder(int folderId);
}
}
|
using Newtonsoft.Json;
namespace Monzo.Messages
{
internal sealed class RegisterWebhookResponse
{
[JsonProperty("webhook")]
public Webhook Webhook { get; set; }
}
} |
using MyPersonelWebsite.Data.Models;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace MyPersonelWebsite.Data
{
public interface IProject
{
Project GetById(int id);
Project GetbyTitle(string title);
IEnumerable<Project> GetAll();
Task Create(Project project);
Task Edit(Project project);
Task Delete(int id);
}
}
|
using HelpMyStreet.Utils.Enums;
using HelpMyStreet.Utils.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace HelpMyStreet.Utils.Models
{
public class RequestSummary : IContainsLocation
{
public Shift Shift { get; set; }
public List<JobSummary> JobSummaries { get; set; }
public List<ShiftJob> ShiftJobs { get; set; }
public List<JobBasic> JobBasics
{
get
{
return JobSummaries.Cast<JobBasic>()
.Concat(ShiftJobs.Cast<JobBasic>()).ToList();
}
}
public int RequestID { get; set; }
public RequestType RequestType { get; set; }
public int ReferringGroupID { get; set; }
public DateTime DateRequested { get; set; }
public string PostCode { get; set; }
public double? DistanceInMiles { get; set; }
public bool? SuppressRecipientPersonalDetail { get; set; }
public bool MultiVolunteer { get; set; }
public bool Repeat { get; set; }
public string HMSReference { get => GetHMSReference(); }
private string GetHMSReference (){
if (JobSummaries.Count() > 0)
{
Groups thisGroup = (Groups)JobSummaries.First().ReferringGroupID;
return $"{thisGroup.GroupIdentifier()}-{DateRequested:yyMMdd}-{RequestID % 1000}";
} else if (ShiftJobs.Count() > 0)
{
Groups thisGroup = (Groups)ShiftJobs.First().ReferringGroupID;
return $"{thisGroup.GroupIdentifier()}-{DateRequested:yyMMdd}-{RequestID % 1000}";
}
else {
return "";
}
}
public LocationDetails GetLocationDetails()
{
if (JobSummaries.Count() > 0)
{
return JobSummaries.First().GetLocationDetails();
}
else if (ShiftJobs.Count > 0)
{
return ShiftJobs.First().GetLocationDetails();
}
else
{
return new LocationDetails();
}
}
}
}
|
using System;
using System.Runtime.InteropServices;
namespace FileCreationTriggeredController.Hardware.Audio
{
static class AudioHandler
{
public static void SetMute(bool isMuted)
{
var masterVolumeHandler = AudioDevice.GetMasterVolumeHandler();
if (masterVolumeHandler != null)
{
masterVolumeHandler.SetMute(isMuted, Guid.Empty);
Marshal.ReleaseComObject(masterVolumeHandler);
}
}
public static void SetMasterVolume(int percent)
{
if (percent < 0 || percent > 100)
{
throw new ArgumentException("Out of range", nameof(percent));
}
var masterVolumeHandler = AudioDevice.GetMasterVolumeHandler();
if (masterVolumeHandler != null)
{
masterVolumeHandler.SetMasterVolumeLevelScalar((float)percent / 100, Guid.Empty);
Marshal.ReleaseComObject(masterVolumeHandler);
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class MainMenuController : MonoBehaviour
{
[SerializeField] AudioClip _mainThemeAudio;
public EventSystem eventSystem;
public GameObject p2;
public GameObject p3;
public GameObject p4;
public GameObject c1;
public GameObject[] selectors;
public GameObject selectorHider;
public void Start(){
ShowCursor();
PlayMainTheme();
}
public void StartGame(){
}
public void QuitGame(){
Application.Quit();
}
public void ShowCursor(){
Cursor.lockState = CursorLockMode.None;
Cursor.visible = true;
}
public void SetSelectedButton(GameObject btn){
eventSystem.SetSelectedGameObject(btn, new BaseEventData(eventSystem));
}
public void SetPlayersButton(){
if(PlayerManagerSingleton.Instance.playerCount == 2){
eventSystem.SetSelectedGameObject(p2, new BaseEventData(eventSystem));
}
if(PlayerManagerSingleton.Instance.playerCount == 3){
eventSystem.SetSelectedGameObject(p3, new BaseEventData(eventSystem));
}
if(PlayerManagerSingleton.Instance.playerCount == 4){
eventSystem.SetSelectedGameObject(p4, new BaseEventData(eventSystem));
}
}
public void PlayMainTheme(){
if(_mainThemeAudio != null){
AudioManagerSingleton.Instance.PlaySong(_mainThemeAudio);
}
}
public void HideCharacterButtons(){
for(int i = 0; i < 4; i++){
selectors[i].transform.position = selectorHider.transform.position;
}
}
public void SetCharacterButton(){
if(PlayerManagerSingleton.Instance.playerSelecting < PlayerManagerSingleton.Instance.playerCount){
SetSelectedButton(c1);
}
}
public void OnSelect(BaseEventData eventData)
{
//MoveCharacterSelector()
Debug.Log(this.gameObject.name + " was selected");
}
}
|
using Microsoft.AspNetCore.Components;
using Microsoft.EntityFrameworkCore;
namespace PeterPedia.Pages.Photos;
public partial class Photos : ComponentBase
{
[Inject]
private PeterPediaContext DbContext { get; set; } = null!;
[Inject]
private IConfiguration Configuration { get; set; } = null!;
public List<string> Albums { get; set; } = new();
public string? Album { get; set; }
public List<Photo>? PhotoList { get; set; } = null;
protected override async Task OnInitializedAsync()
{
List<AlbumEF> items = await DbContext.Albums.OrderBy(a => a.Name).ToListAsync();
Albums.Clear();
foreach (AlbumEF item in items)
{
Albums.Add(item.Name);
}
}
public async Task OpenAlbumAsync(string album)
{
if (string.IsNullOrWhiteSpace(album))
{
PhotoList = null;
return;
}
List<PhotoEF> items = await DbContext.Photos.Where(p => p.Album.Name == album).ToListAsync();
PhotoList = new List<Photo>(items.Count);
foreach (PhotoEF item in items)
{
PhotoList.Add(ConvertToItem(item));
}
}
private Photo ConvertToItem(PhotoEF itemEF)
{
if (itemEF is null)
{
throw new ArgumentNullException(nameof(itemEF));
}
var photo = new Photo();
var basePath = Configuration["PhotoPath"] ?? "/photos";
var relativePath = Path.GetRelativePath(basePath, itemEF.AbsolutePath);
photo.Url = "/photo/" + relativePath.Replace('\\', '/');
return photo;
}
}
|
using Newtonsoft.Json;
namespace PoissonSoft.KrakenApi.Contracts.MarketData
{
/// <summary>
///
/// </summary>
public class OHLCData
{
[JsonProperty("error")]
public string[] Error { get; set; }
[JsonProperty("result")]
//public Dictionary<string, OHLCDataResult> Result { get; set; }
public OHLCDataResult Result { get; set; }
}
public class OHLCDataResult
{
public object[][] XXBTZUSD { get; set; }
//public object[][] Tick { get; set; }
//public Dictionary<string, string[]> XXBTZUSD { get; set; }
[JsonProperty("last")]
public int Last { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Options;
namespace OptionsDemo.Services
{
public interface IOrderService
{
int ShowMaxOrderCount();
}
public class OrderService : IOrderService
{
IOptionsMonitor<OrderServiceOptions> _options;
public OrderService(IOptionsMonitor<OrderServiceOptions> options)
{
this._options = options;
_options.OnChange(options =>
{
Console.WriteLine($"配置发生了变化,新值为:{options.MaxOrderCount }");
});
}
public int ShowMaxOrderCount()
{
return _options.CurrentValue.MaxOrderCount;
}
}
public class OrderServiceOptions
{
[Range(1, 200)]
public int MaxOrderCount { get; set; } = 100;
}
public class OrderServiceValidateOptions: IValidateOptions<OrderServiceOptions>
{
public ValidateOptionsResult Validate(string name, OrderServiceOptions options)
{
if (options.MaxOrderCount > 200)
{
return ValidateOptionsResult.Fail("不能大于200");
}
else
{
return ValidateOptionsResult.Success;
}
}
}
}
|
using System;
using FluentAssertions;
using NUnit.Framework;
using SFA.DAS.Payments.Model.Core.Audit;
using SFA.DAS.Payments.Model.Core.Entities;
using SFA.DAS.Payments.Model.Core.Incentives;
using SFA.DAS.Payments.RequiredPayments.Messages.Events;
namespace SFA.DAS.Payments.Audit.Application.UnitTests.RequiredPayment.Mapping
{
[TestFixture]
public class IncentiveRequiredPaymentMappingTests: RequiredPaymentsMappingTests<CalculatedRequiredIncentiveAmount>
{
protected override CalculatedRequiredIncentiveAmount CreatePaymentEvent()
{
return new CalculatedRequiredIncentiveAmount
{
ContractType = ContractType.Act2,
};
}
[TestCaseSource(nameof(GetIncentiveTypes))]
public void Maps_IncentiveTypes(IncentivePaymentType incentiveType)
{
PaymentEvent.Type = incentiveType;
var model = Mapper.Map<RequiredPaymentEventModel>(PaymentEvent);
model.TransactionType.Should().Be((TransactionType)PaymentEvent.Type);
}
public static Array GetIncentiveTypes()
{
return GetEnumValues<IncentivePaymentType>();
}
[TestCaseSource(nameof(GetContractTypes))]
public void Maps_ContractType(ContractType contractType)
{
PaymentEvent.ContractType = contractType;
Mapper.Map<RequiredPaymentEventModel>(PaymentEvent).ContractType.Should().Be(PaymentEvent.ContractType);
}
[Test]
public void Maps_SfaContributionPercentage()
{
Mapper.Map<RequiredPaymentEventModel>(PaymentEvent).SfaContributionPercentage.Should().Be(1);
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RotateAround : MonoBehaviour
{
public Transform transformCenter;
public float speed;
public float radius;
float deltaY;
float angle;
void Start()
{
if (radius == -1)
radius = Vector3.Distance(transformCenter.position, transform.position);
deltaY = transform.position.y;
}
void Update()
{
angle += Time.deltaTime * speed;
var pos = transformCenter.position + radius * new Vector3(Mathf.Sin(angle), 0, Mathf.Cos(angle));
pos.y += deltaY;
transform.position = pos;
transform.LookAt(transformCenter);
}
}
|
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Net;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Web.Filters;
using Web.Helpers;
namespace Web.Api
{
[ApiController]
[TokenAuthentication]
public class TokenController : ControllerBase
{
private readonly JwtHelper jwt;
public TokenController(JwtHelper jwt)
{
this.jwt = jwt;
}
public string UserName
{
get { return User.Identity.Name; }
}
[HttpPost("~/parent")]
public ActionResult parentAction()
{
return new JsonResult("i am pa");
}
[AllowAnonymous]
[HttpPost("~/signin")]
public ActionResult SignIn(UserModel user)
{
if (CheckUser(user.Uid))
{
return new JsonResult(jwt.GenerateToken(user.Uid));
}
return new JsonResult(HttpStatusCode.BadRequest);
}
public static bool CheckUser(string username)
{
return true;
}
public class UserModel
{
public string Uid { get; set; }
public string Password { get; set; }
}
}
}
|
using System.Collections.Generic;
namespace SrkToolkit.ServiceDefinition {
/// <summary>
/// Configuration for a code generation.
/// </summary>
public class Generation {
/// <summary>
/// Gets or sets the name of the contract.
/// It must match a contract name in the service definition file.
/// </summary>
public string ContractName { get; set; }
/// <summary>
/// Gets or sets the XML namespace URI.
/// </summary>
public string Namespace { get; set; }
/// <summary>
/// Gets or sets the name of the type to generate.
/// </summary>
public string TypeName { get; set; }
public TypeAccessibility Accessibility { get; set; }
////public GenerationKind Kind { get; set; } // old params from wild T4
////public GenerationAsyncMode AsyncMode { get; set; } // old params from wild T4
/// <summary>
/// Gets or sets the using directives.
/// </summary>
public IList<string> Usings { get; set; }
/// <summary>
/// Gets or sets the parent classes and interfaces.
/// </summary>
public IList<string> Parents { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to suppress persistent params from methods.
/// </summary>
public bool SuppressPersistentParams { get; set; }
/// <summary>
/// Gets or sets the generator class type name.
/// </summary>
public string GeneratorClass { get; set; }
/// <summary>
/// Gets or sets the generator class assembly name (for an external type).
/// </summary>
public string GeneratorAssembly { get; set; }
/// <summary>
/// Gets or sets the generator.
/// </summary>
internal GeneratorBase Generator { get; set; }
/// <summary>
/// Gets or sets the contract.
/// </summary>
internal Contract Contract { get; set; }
internal GenerationSet Set { get; set; }
}
public enum FieldAccessibility {
Private, Protected, ProtectedInternal, Internal, Public
}
public enum TypeAccessibility {
Private, Protected, ProtectedInternal, Internal, Public
}
public enum GenerationKind {
Interface,
Client,
SilverlightClient
}
public enum GenerationAsyncMode {
Sync,
AsyncWithEvents,
AsyncWithCallbacks,
WcfAsyncPattern,
AsyncPattern,
}
}
|
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
namespace GeoTime {
public class TZAmbiguityStore : IReadOnlyDictionary<string, HashSet<int>> {
public TZAmbiguityStore( IReadOnlyDictionary<string, HashSet<int>> store ) {
Store = store;
}
public HashSet<int> this[string key] => Store[key];
public IReadOnlyDictionary<string, HashSet<int>> Store { get; }
public IEnumerable<string> Keys => Store.Keys;
public IEnumerable<HashSet<int>> Values => Store.Values;
public int Count => Store.Count;
public bool ContainsKey( string key ) =>
Store.ContainsKey( key );
public IEnumerator<KeyValuePair<string, HashSet<int>>> GetEnumerator() =>
Store.GetEnumerator();
public bool TryGetValue( string key, [MaybeNullWhen( false )] out HashSet<int> value ) =>
Store.TryGetValue( key, out value );
IEnumerator IEnumerable.GetEnumerator() =>
( (IEnumerable)Store ).GetEnumerator();
}
}
|
namespace SpriteCompiler.AI
{
/// <summary>
/// Class that taken a search node and detemines whether or not to terminate the
/// search at the node. This is different than a goal test and is used in the
/// contect of depth-limited searches.
/// </summary>
public class CostNodeLimiter<T, C> : INodeLimiter<T, C>
where T : ISearchNode<C>
where C : ICost<C>, new()
{
private readonly C maxCost;
private C nextCost;
public CostNodeLimiter(C maxCost, C infinity)
{
this.maxCost = maxCost;
this.nextCost = infinity;
}
public C NextCost { get { return nextCost; } }
public bool Cutoff(T node)
{
// If we find a value that exceeds the current maximum, return false,
// but keep track of the smallest value that is larger than the maximum
// cost.
// Current bug -- three line sprite, never exceeds cost of 23
if (node.PathCost.CompareTo(maxCost) > 0)
{
nextCost = (node.PathCost.CompareTo(nextCost) < 0) ? node.PathCost : nextCost;
return true;
}
return false;
}
}
}
|
/*
* Trade secret of Alibaba Group R&D.
* Copyright (c) 2015 Alibaba Group R&D.
*
* All rights reserved. This notice is intended as a precaution against
* inadvertent publication and does not imply publication or any waiver
* of confidentiality. The year included in the foregoing notice is the
* year of creation of the work.
*
*/
using System;
using System.Collections.Generic;
using NUnit.Framework;
using Aliyun.OTS.DataModel;
namespace Aliyun.OTS.UnitTest.DataModel
{
[TestFixture]
class ColumnNameTest : OTSUnitTestBase
{
public void TestBadColumnName(string badColumnName)
{
var badPrimaryKeySchema = new PrimaryKeySchema
{
{ badColumnName, ColumnValueType.String }
};
var badPrimaryKey = new PrimaryKey
{
{ badColumnName, new ColumnValue(3.14) }
};
var badColumnsToGet = new HashSet<string>
{
badColumnName
};
var expectFailureInfo = "Invalid column name: '" + badColumnName + "'.";
var expectedFailure = new Dictionary<string, string>
{
{ "CreateTable", expectFailureInfo}
};
var errorMessage = String.Format("Bug: unsupported primary key type: Double");
var badAttribute = new AttributeColumns
{
{ badColumnName, new ColumnValue(3.14) }
};
SetTestConext(
pkSchema: badPrimaryKeySchema,
primaryKey: badPrimaryKey,
startPrimaryKey: badPrimaryKey,
expectedFailure: expectedFailure,
allFailedMessage: errorMessage);
TestAllDataAPI(deleteTable: false);
SetTestConext(
attribute: badAttribute,
allFailedMessage: expectFailureInfo);
TestAllDataAPIWithAttribute(false);
SetTestConext(
columnsToGet: badColumnsToGet,
expectedFailure: expectedFailure,
allFailedMessage: expectFailureInfo);
TestAllDataAPIWithColumnsToGet();
}
// <summary>
// 测试所有接口,列名长度为0的情况,期望返回错误消息:Invalid column name: '{ColumnName}'. 中包含的ColumnName与输入一致。
// </summary>
[Test]
public void TestColumnNameOfZeroLength()
{
TestBadColumnName("");
}
//// <summary>
//// 测试所有接口,列名包含Unicode,期望返回错误信息:Invalid column name: '{ColumnName}'. 中包含的ColumnName与输入一致。
//// </summary>
//[Test]
//public void TestColumnNameWithUnicode()
//{
// TestBadColumnName("中文");
//}
// <summary>
// 测试所有接口,列名长度为1KB,期望返回错误信息:Invalid column name: '{ColumnName}'. 中包含的ColumnName与输入一致。
// </summary>
[Test]
public void Test1KBColumnName()
{
TestBadColumnName(new string('X', 1024));
}
}
}
|
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.CommandLine;
using System.CommandLine.Parsing;
using System.IO;
using System.Linq;
using Microsoft.DotNet.Cli.CommandLineValidation;
namespace Microsoft.DotNet.Cli
{
internal sealed class CommandLineValidationMessages : Resources
{
public override string ExpectsOneArgument(SymbolResult symbolResult) =>
symbolResult is CommandResult
? string.Format(
LocalizableStrings.CommandAcceptsOnlyOneArgument,
symbolResult.Token().Value,
symbolResult.Tokens.Count
)
: string.Format(
LocalizableStrings.OptionAcceptsOnlyOneArgument,
symbolResult.Token().Value,
symbolResult.Tokens.Count
);
public override string NoArgumentProvided(SymbolResult symbolResult) =>
symbolResult is CommandResult
? string.Format(
LocalizableStrings.RequiredArgumentMissingForCommand,
symbolResult.Token().Value
)
: string.Format(
LocalizableStrings.RequiredArgumentMissingForOption,
symbolResult.Token().Value
);
public override string FileDoesNotExist(string filePath) =>
string.Format(LocalizableStrings.FileDoesNotExist, filePath);
public override string RequiredCommandWasNotProvided() =>
string.Format(LocalizableStrings.RequiredCommandWasNotProvided);
public override string UnrecognizedArgument(
string unrecognizedArg,
IReadOnlyCollection<string> allowedValues
) =>
string.Format(
LocalizableStrings.UnrecognizedArgument,
unrecognizedArg,
string.Join("\n\t", allowedValues.Select(v => $"'{v}'"))
);
public override string UnrecognizedCommandOrArgument(string arg) =>
string.Format(LocalizableStrings.UnrecognizedCommandOrArgument, arg);
public override string ExpectsFewerArguments(
Token token,
int providedNumberOfValues,
int maximumNumberOfValues
) =>
token.Type == TokenType.Command
? string.Format(
LocalizableStrings.CommandExpectsFewerArguments,
token,
maximumNumberOfValues,
providedNumberOfValues
)
: string.Format(
LocalizableStrings.OptionExpectsFewerArguments,
token,
maximumNumberOfValues,
providedNumberOfValues
);
public override string DirectoryDoesNotExist(string path) =>
string.Format(LocalizableStrings.DirectoryDoesNotExist, path);
public override string FileOrDirectoryDoesNotExist(string path) =>
string.Format(LocalizableStrings.FileOrDirectoryDoesNotExist, path);
public override string InvalidCharactersInPath(char invalidChar) =>
string.Format(LocalizableStrings.CharacterNotAllowedInPath, invalidChar);
public override string RequiredArgumentMissing(SymbolResult symbolResult) =>
symbolResult is CommandResult
? string.Format(
LocalizableStrings.RequiredCommandArgumentMissing,
symbolResult.Token().Value
)
: string.Format(
LocalizableStrings.RequiredOptionArgumentMissing,
symbolResult.Token().Value
);
public override string ResponseFileNotFound(string filePath) =>
string.Format(LocalizableStrings.ResponseFileNotFound, filePath);
public override string ErrorReadingResponseFile(string filePath, IOException e) =>
string.Format(LocalizableStrings.ErrorReadingResponseFile, filePath, e.Message);
public override string HelpOptionDescription() => LocalizableStrings.ShowHelpInfo;
}
internal static class SymbolResultExtensions
{
internal static Token Token(this SymbolResult symbolResult)
{
return symbolResult switch
{
CommandResult commandResult => commandResult.Token,
OptionResult optionResult
=> optionResult.Token
?? new Token($"--{optionResult.Option.Name}", TokenType.Option),
ArgumentResult argResult
=> new Token(argResult.GetValueOrDefault<string>(), TokenType.Argument),
_ => null
};
}
}
}
|
using System.Threading.Tasks;
using Conferences.Api.Models;
namespace Conferences.Api.Mapper
{
public interface IMapConferences
{
Task<ConferencesResponse> GetAllConferences(string topic);
Task<ConferenceGetResponse> GetConferenceById(int id);
Task<ConferenceGetResponse> Add(ConferenceCreate conferenceToAdd);
Task Remove(int id);
Task<bool> UpdateAttendanceFor(int id, bool attending);
}
} |
using System;
using System.Security.Cryptography;
namespace Stravaig.ShortCode
{
public class CryptographicallyRandomCodeGenerator : IShortCodeGenerator
{
private readonly RNGCryptoServiceProvider _rng;
public CryptographicallyRandomCodeGenerator()
{
_rng = new RNGCryptoServiceProvider();
}
public ulong GetNextCode()
{
byte[] bytes = new byte[8];
_rng.GetBytes(bytes);
return BitConverter.ToUInt64(bytes, 0);
}
}
} |
namespace Tracker.App.Api.Configurations
{
using Autofac;
using global::Infrastructure.Persistence;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
public class EfModule : Module
{
private readonly DbContextOptions<TrackerDbContext> options;
public EfModule(string sqlServerConnectionString)
{
var builder = new DbContextOptionsBuilder<TrackerDbContext>();
builder.UseSqlServer(sqlServerConnectionString, options => { options.EnableRetryOnFailure(); });
builder.ConfigureWarnings(w => w.Throw(RelationalEventId.QueryPossibleUnintendedUseOfEqualsWarning));
this.options = builder.Options;
}
protected override void Load(ContainerBuilder builder)
{
builder.RegisterType<TrackerDbContext>()
.AsSelf()
.WithParameter(new NamedParameter("options", this.options))
.InstancePerLifetimeScope();
base.Load(builder);
}
}
} |
using System;
using Logging.Benchmark.Enums;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace Logging.Benchmark.Scenarios.NetCore.Setups
{
public static class NetCoreSetup
{
public static void AddNetCoreLogging(this IServiceCollection services, LogLevel logLevel,
OutputMode outputMode)
{
switch (outputMode)
{
case OutputMode.Console:
services.AddLogging(opt =>
{
opt.AddConsole();
opt.SetMinimumLevel(logLevel);
});
break;
case OutputMode.File:
throw new NotSupportedException(outputMode.ToString());
default:
throw new ArgumentOutOfRangeException(nameof(outputMode), outputMode, null);
}
}
}
} |
namespace WpfTest.Views.FilterDesigners
{
public partial class ButterworthBandPassFilterDesigner
{
public ButterworthBandPassFilterDesigner() => InitializeComponent();
}
}
|
#region 命名空间
using System;
using System.Collections;
using System.Collections.Generic;
using Framework.Utility;
using LuaInterface;
using UnityEngine;
using UnityEngine.Networking;
using Object = UnityEngine.Object;
#endregion
namespace Framework
{
public class AssetBundleInfo
{
public AssetBundle mAssetBundle;
public int ReferencedCount;
public AssetBundleInfo(AssetBundle assetBundle)
{
mAssetBundle = assetBundle;
ReferencedCount = 0;
}
}
public class LoadAssetRequest
{
public Type assetType;
public string[] assetNames;
public LuaFunction luaFunc;
public Action<Object[]> sharpFunc;
}
public class ResourceManager : MonoBehaviour
{
private string[] m_AllManifest = null;
private AssetBundleManifest m_AssetBundleManifest = null;
private Dictionary<string, string[]> m_Dependencies = new Dictionary<string, string[]>();
private Dictionary<string, AssetBundleInfo> m_LoadedAssetBundles = new Dictionary<string, AssetBundleInfo>();
private Dictionary<string, List<LoadAssetRequest>> m_LoadRequests = new Dictionary<string, List<LoadAssetRequest>>();
public string BaseDownloadingURL { get; set; } = string.Empty; //加载基础路径
/// <summary>
/// Load AssetBundleManifest.
/// </summary>
/// <param name="manifestName"></param>
/// <param name="initOK"></param>
public void Initialize(string manifestName, Action initOK)
{
BaseDownloadingURL = Util.RelativePath + GameConst.AssetsDir + "/";
LoadAsset<AssetBundleManifest>(manifestName, new string[] { "AssetBundleManifest" }, delegate (Object[] objs)
{
if (objs.Length > 0)
{
m_AssetBundleManifest = objs[0] as AssetBundleManifest;
m_AllManifest = m_AssetBundleManifest.GetAllAssetBundles();
}
initOK?.Invoke();
});
}
public void LoadPrefab(string abName, string assetName, Action<Object[]> func)
{
LoadAsset<Object>(abName, new string[] { assetName }, func);
}
public void LoadPrefab(string abName, string[] assetNames, Action<Object[]> func)
{
LoadAsset<Object>(abName, assetNames, func);
}
public void LoadPrefab(string abName, string assetName, LuaFunction func)
{
LoadAsset<Object>(abName, new string[] { assetName }, null, func);
}
public void LoadPrefab(string abName, string[] assetNames, LuaFunction func)
{
LoadAsset<Object>(abName, assetNames, null, func);
}
/// <summary>
/// 获取绝对路径
/// </summary>
/// <param name="abName"></param>
/// <returns></returns>
private string GetRealAssetPath(string abName)
{
if (abName.Equals(GameConst.AssetsDir)) return abName;
abName = abName.ToLower();
if (!abName.EndsWith(GameConst.BundleSuffix))
{
abName += GameConst.BundleSuffix;
}
if (abName.Contains("/")) return abName;
for (int node = 0; node < m_AllManifest.Length; node++)
{
int index = m_AllManifest[node].LastIndexOf('/');
string path = m_AllManifest[node].Remove(0, index + 1); //字符串操作函数都会产生GC
if (path.Equals(abName))
{
return m_AllManifest[node];
}
}
Util.LogError("GetRealAssetPath Error:>>" + abName);
return null;
}
/// <summary>
/// 载入素材
/// </summary>
private void LoadAsset<T>(string abName, string[] assetNames, Action<Object[]> action = null, LuaFunction func = null) where T : Object
{
abName = GetRealAssetPath(abName);
LoadAssetRequest request = new LoadAssetRequest();
request.assetType = typeof(T);
request.assetNames = assetNames;
request.luaFunc = func;
request.sharpFunc = action;
List<LoadAssetRequest> requests = null;
if (!m_LoadRequests.TryGetValue(abName, out requests))
{
requests = new List<LoadAssetRequest>();
requests.Add(request);
m_LoadRequests.Add(abName, requests);
StartCoroutine(OnLoadAsset<T>(abName));
}
else
{
requests.Add(request);
//m_LoadRequests.Add(abName, requests);
}
}
/// <summary>
/// 加载AB协程
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="abName"></param>
/// <returns></returns>
private IEnumerator OnLoadAsset<T>(string abName) where T : Object
{
AssetBundleInfo bundleInfo = GetLoadedAssetBundle(abName);
if (bundleInfo == null)
{
yield return StartCoroutine(OnLoadAssetBundle(abName, typeof(T)));
bundleInfo = GetLoadedAssetBundle(abName);
if (bundleInfo == null)
{
m_LoadRequests.Remove(abName);
Debug.LogError("OnLoadAsset--->>>" + abName);
yield break;
}
}
List<LoadAssetRequest> list = null;
if (!m_LoadRequests.TryGetValue(abName, out list))
{
m_LoadRequests.Remove(abName);
yield break;
}
for (int node = 0, count = list.Count; node < count; node++)
{
string[] assetNames = list[node].assetNames;
List<Object> result = new List<Object>();
AssetBundle assetBundle = bundleInfo.mAssetBundle;
for (int repo = 0; repo < assetNames.Length; repo++)
{
string assetPath = assetNames[repo];
AssetBundleRequest request = assetBundle.LoadAssetAsync(assetPath, list[node].assetType);
yield return request;
result.Add(request.asset);
}
if (list[node].sharpFunc != null)
{
list[node].sharpFunc(result.ToArray());
list[node].sharpFunc = null;
}
if (list[node].luaFunc != null)
{
list[node].luaFunc.Call((object)result.ToArray());
list[node].luaFunc.Dispose();
list[node].luaFunc = null;
}
bundleInfo.ReferencedCount++;
}
m_LoadRequests.Remove(abName);
}
/// <summary>
/// 加载完成
/// </summary>
/// <param name="abName"></param>
/// <param name="type"></param>
/// <returns></returns>
private IEnumerator OnLoadAssetBundle(string abName, Type type)
{
string url = BaseDownloadingURL + abName;
Util.LogWarning(url);
UnityWebRequest download = null;
if (type == typeof(AssetBundleManifest))
{
download = UnityWebRequestAssetBundle.GetAssetBundle(url);
}
else
{
string[] dependencies = m_AssetBundleManifest.GetAllDependencies(abName);
if (dependencies.Length > 0)
{
m_Dependencies.Add(abName, dependencies);
for (int i = 0; i < dependencies.Length; i++)
{
string depName = dependencies[i];
AssetBundleInfo bundleInfo = null;
if (m_LoadedAssetBundles.TryGetValue(depName, out bundleInfo))
{
bundleInfo.ReferencedCount++;
}
else if (!m_LoadRequests.ContainsKey(depName))
{
yield return StartCoroutine(OnLoadAssetBundle(depName, type));
}
}
}
download = UnityWebRequestAssetBundle.GetAssetBundle(url, m_AssetBundleManifest.GetAssetBundleHash(abName), 0);
}
yield return download.SendWebRequest();
AssetBundle assetObj = DownloadHandlerAssetBundle.GetContent(download);
if (assetObj != null)
{
m_LoadedAssetBundles.Add(abName, new AssetBundleInfo(assetObj));
}
}
/// <summary>
/// 获取AB资源信息
/// </summary>
/// <param name="abName">AB名称</param>
/// <returns></returns>
private AssetBundleInfo GetLoadedAssetBundle(string abName)
{
AssetBundleInfo bundle = null;
m_LoadedAssetBundles.TryGetValue(abName, out bundle);
if (bundle == null) return null;
// No dependencies are recorded, only the bundle itself is required.
string[] dependencies = null;
if (!m_Dependencies.TryGetValue(abName, out dependencies)) return bundle;
// Make sure all dependencies are loaded
foreach (var dependency in dependencies)
{
AssetBundleInfo dependentBundle;
m_LoadedAssetBundles.TryGetValue(dependency, out dependentBundle);
if (dependentBundle == null) return null;
}
return bundle;
}
/// <summary>
/// 此函数交给外部卸载专用,自己调整是否需要彻底清除AB
/// </summary>
/// <param name="abName"></param>
/// <param name="isThorough"></param>
public void UnloadAssetBundle(string abName, bool isThorough = false)
{
abName = GetRealAssetPath(abName);
Debug.Log(m_LoadedAssetBundles.Count + " assetbundle(s) in memory before unloading " + abName);
UnloadAssetBundleInternal(abName, isThorough);
UnloadDependencies(abName, isThorough);
Debug.Log(m_LoadedAssetBundles.Count + " assetbundle(s) in memory after unloading " + abName);
}
/// <summary>
/// 卸载依赖AB
/// </summary>
/// <param name="abName"></param>
/// <param name="isThorough"></param>
private void UnloadDependencies(string abName, bool isThorough)
{
string[] dependencies = null;
if (!m_Dependencies.TryGetValue(abName, out dependencies)) return;
// Loop dependencies.
foreach (var dependency in dependencies)
{
UnloadAssetBundleInternal(dependency, isThorough);
}
m_Dependencies.Remove(abName);
}
private void UnloadAssetBundleInternal(string abName, bool isThorough)
{
AssetBundleInfo bundle = GetLoadedAssetBundle(abName);
if (bundle == null) return;
if (--bundle.ReferencedCount <= 0)
{
if (m_LoadRequests.ContainsKey(abName))
{
return; //如果当前AB处于Async Loading过程中,卸载会崩溃,只减去引用计数即可
}
bundle.mAssetBundle.Unload(isThorough);
m_LoadedAssetBundles.Remove(abName);
Debug.Log(abName + " has been unloaded successfully");
}
}
}
}
|
using System;
namespace Arrowgene.Services.Performance
{
public class MemoryMeasurement
{
public DateTime Time { get; set; }
public double Usage { get; set; }
}
} |
using UnityEngine;
using System.Collections;
public class Shapeways : MonoBehaviour {
#region OAuth configuration
const string kConsumerKey = "7a3a7af890731cf8d07463dd384645863519983e";
const string kConsumerSecret = "8ede871c3ddccabea8d6f32e3e9e93ec0fe7b83f";
const string kPrefix = "Shapeways";
#endregion
#region OAuth URLs
const string kRequestUrl = "http://api.shapeways.com/oauth1/request_token/v1";
const string kAuthorizationUrl = "http://api.shapeways.com/login?oauth_token={0}";
const string kAccessUrl = "http://api.shapeways.com/oauth1/access_token/v1";
#endregion
public string label {
get { return "Shapeways"; }
}
public MeshManager manager;
OAuth1 m_authority;
MeshPattern m_pattern;
System.IO.MemoryStream m_stlStream;
bool m_stlReady;
bool m_cancelling;
void Awake() {
m_authority = new OAuth1(kPrefix, kConsumerKey, kConsumerSecret);
Dispatcher<float>.AddListener(MeshPattern.kOnExportUpdate, StlExportUpdate);
}
void OnDestroy() {
Dispatcher<float>.RemoveListener(MeshPattern.kOnExportUpdate, StlExportUpdate);
}
#region Interaction with the menu
public void CheckAuthorization() {
// User just clicked the "Upload to Shapeways" button.
// If they're authorized, open up the upload panel.
// If they're not, try to authorize them.
// Start converting to STL right away.
m_pattern = new MeshPattern();
m_stlStream = new System.IO.MemoryStream();
m_stlReady = false;
m_pattern.SaveStlFromBlob(manager.m_blob, m_stlStream, false);
if (m_authority.IsAuthorized()) {
Dispatcher.Broadcast(ShapewaysPanel.kOpenShapeways);
}
else {
StartCoroutine(m_authority.RequestAuthorization(kRequestUrl, kAuthorizationUrl,
null, OpenPinMenu, DisplayError));
}
}
void OpenPinMenu(string message) {
// Prompt the user to enter their verification code.
Dispatcher<string, PanelController.StringHandler,PanelController.StringHandler>.Broadcast(
PanelController.kEventRequest,
"Enter your verification number below:", OnVerificationEntered,
OnVerificationCanceled);
}
void DisplayError(string reason) {
// Make the menu visible again.
Dispatcher<string, PanelController.Handler>.Broadcast(PanelController.kEventPrompt,
reason, OnErrorAcknowledged);
Text.Error(reason);
}
void OnVerificationEntered(string verification) {
Text.Log(@"Using verification number: {0}", verification);
StartCoroutine(m_authority.RequestAuthorization(kAccessUrl, null,
verification, OnCredentialsOk, DisplayError));
}
void OnVerificationCanceled(string verification) {
Dispatcher<Panel>.Broadcast(PanelController.kEventOpenPanel, Panel.Menu);
m_authority.ClearRequestCredentials();
}
void OnErrorAcknowledged() {
Dispatcher<Panel>.Broadcast(PanelController.kEventOpenPanel, Panel.Menu);
m_authority.ClearRequestCredentials();
}
void OnCredentialsOk(string message) {
Text.Log(message);
Dispatcher.Broadcast(ShapewaysPanel.kOpenShapeways);
}
#endregion
#region Shapeways panel functions
public IEnumerator UploadModel(string title, string tags, bool isPublic, bool canDownload) {
if (!m_stlReady) {
m_cancelling = false;
Dispatcher<string, string, PanelController.Handler, PanelController.Handler>.Broadcast(
PanelController.kEventShowProgress,
OAuth1.kOnUpdateProgress, "Processing ({0:0%} completed)...",
delegate() {},
delegate() { m_cancelling = true; Scheduler.StopCoroutines(m_pattern); }
);
while (!m_cancelling && !m_stlReady) {
Dispatcher<float>.Broadcast(OAuth1.kOnUpdateProgress, m_pattern.loadProgress);
yield return null;
}
if (m_cancelling) {
yield break;
}
Dispatcher<float>.Broadcast(OAuth1.kOnUpdateProgress, 1.0f);
}
Dispatcher<string, string, PanelController.Handler, PanelController.Handler>.Broadcast(
PanelController.kEventShowProgress,
OAuth1.kOnUpdateProgress, "Uploading ({0:0%} completed)...",
delegate() {},
delegate() { m_cancelling = true; Scheduler.StopCoroutines(this); }
);
byte[] fileData = m_stlStream.ToArray();
string fileBase64Data = System.Convert.ToBase64String(fileData);
title = title.Replace(" ", "").Trim();
string fileName = title;
if (string.IsNullOrEmpty(fileName)) {
fileName = "Untitled.stl";
title = "Untitled";
}
else if (!fileName.Contains(".")) fileName = fileName + ".stl";
Json payload = new Json();
payload.Add("file", OAuth1.UrlEncode(fileBase64Data));
payload.Add("fileName", fileName);
payload.Add("uploadScale", VoxelBlob.kVoxelSizeInMm * 0.001f);
payload.Add("hasRightsToModel", 1);
payload.Add("acceptTermsAndConditions", 1);
payload.Add("title", title);
payload.Add("isPublic", isPublic ? 1 : 0);
payload.Add("isDownloadable", canDownload ? 1 : 0);
payload.Add("tags", tags.Split(',', ';'));
yield return Scheduler.StartCoroutine(m_authority.PostData("http://api.shapeways.com/models/v1",
payload, OnSuccess, OnFailure), this);
m_stlStream.Close();
}
void OnSuccess(string results) {
bool wasSuccessful = results.IndexOf("success") >= 0;
if (wasSuccessful) {
Dispatcher<string, PanelController.Handler>.Broadcast(PanelController.kEventPrompt,
"Upload successful.", delegate () {
Dispatcher<Panel>.Broadcast(PanelController.kEventOpenPanel, Panel.Menu);
});
}
else OnFailure(string.Format("Unexpected result: {0}", results));
}
void OnFailure(string error) {
Dispatcher<string, PanelController.Handler>.Broadcast(PanelController.kEventPrompt,
"Received an invalid response. Try again later.",
OnResultAcknowledged);
Text.Error("{0}", error);
}
void OnResultAcknowledged() {
Dispatcher<Panel>.Broadcast(PanelController.kEventOpenPanel, Panel.Menu);
}
#endregion
void StlExportUpdate(float amount) {
if (Mathf.Approximately(amount, 1.0f)) {
m_stlReady = true;
}
}
}
|
//
// Copyright (c) 2017 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
using System;
using System.Diagnostics;
namespace nanoFramework.Tools.VisualStudio.Extension
{
public abstract class MessageCentreBase
{
protected static readonly Guid s_InternalErrorsPaneGuid = Guid.NewGuid();
protected static readonly Guid s_DeploymentMessagesPaneGuid = Guid.NewGuid();
//--//
public abstract void DebugMessage(string message);
public abstract void ClearDeploymentMessages();
public abstract void DeploymentMessage(string message);
public abstract void InternalErrorMessage(string message);
public abstract void InternalErrorMessage(bool assertion, string message);
public abstract void InternalErrorMessage(bool assertion, string message, int skipFrames);
public abstract void OutputMessageHandler(object sendingProcess, DataReceivedEventArgs outLine);
public abstract void ErrorMessageHandler(object sendingProcess, DataReceivedEventArgs outLine);
public abstract void StartProgressMessage(string message);
public abstract void StopProgressMessage(string message);
public void StopProgressMessage()
{
this.StopProgressMessage(null);
}
}
public class NullMessageCentre : MessageCentreBase
{
public override void DebugMessage(string message)
{
}
public override void ClearDeploymentMessages()
{
}
public override void DeploymentMessage(string message)
{
}
public override void InternalErrorMessage(string message)
{
}
public override void InternalErrorMessage(bool assertion, string message)
{
}
public override void InternalErrorMessage(bool assertion, string message, int skipFrames)
{
}
public override void OutputMessageHandler(object sendingProcess, DataReceivedEventArgs outLine)
{
}
public override void ErrorMessageHandler(object sendingProcess, DataReceivedEventArgs outLine)
{
}
public override void StartProgressMessage(string message)
{
}
public override void StopProgressMessage(string message)
{
}
}
}
|
using System.Collections.Generic;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
namespace SqlPad
{
public static class Snippets
{
public const string SnippetDirectoryName = "Snippets";
public const string CodeGenerationItemDirectoryName = "CodeGenerationItems";
private static readonly XmlSerializer XmlSerializer = new XmlSerializer(typeof(Snippet));
private static readonly List<Snippet> SnippetCollectionInternal = new List<Snippet>();
private static readonly List<Snippet> CodeGenerationItemCollectionInternal = new List<Snippet>();
public static void ReloadSnippets()
{
ReloadSnippetCollection(ConfigurationProvider.FolderNameSnippets, SnippetCollectionInternal);
ReloadSnippetCollection(ConfigurationProvider.FolderNameCodeGenerationItems, CodeGenerationItemCollectionInternal);
}
private static void ReloadSnippetCollection(string folderName, ICollection<Snippet> snippetCollection)
{
snippetCollection.Clear();
foreach (var snippetFile in Directory.GetFiles(folderName, "*.xml"))
{
using (var reader = XmlReader.Create(snippetFile))
{
snippetCollection.Add((Snippet)XmlSerializer.Deserialize(reader));
}
}
}
public static IReadOnlyCollection<Snippet> SnippetCollection
{
get
{
EnsureSnippetsLoaded();
return SnippetCollectionInternal.AsReadOnly();
}
}
private static void EnsureSnippetsLoaded()
{
lock (SnippetCollectionInternal)
{
if (SnippetCollectionInternal.Count == 0 || CodeGenerationItemCollectionInternal.Count == 0)
{
ReloadSnippets();
}
}
}
public static IReadOnlyCollection<Snippet> CodeGenerationItemCollection
{
get
{
EnsureSnippetsLoaded();
return CodeGenerationItemCollectionInternal.AsReadOnly();
}
}
}
} |
using Microsoft.VisualStudio.Services.Feed.WebApi;
namespace TfsCmdlets.Controllers.Artifact
{
[CmdletController(typeof(FeedView))]
partial class GetArtifactFeedViewController
{
protected override IEnumerable Run()
{
var client = GetClient<FeedHttpClient>();
foreach (var input in View)
{
var view = input switch
{
_ => input
};
var feed = GetItem<Feed>();
switch (view)
{
case FeedView fv:
{
yield return fv;
break;
}
case string s when !string.IsNullOrEmpty(s) && feed.Project == null:
{
yield return client.GetFeedViewsAsync(feed.Id.ToString())
.GetResult($"Error getting artifact feed view(s) '{s}'")
.Where(fv => fv.Name.IsLike(s));
break;
}
case string s when !string.IsNullOrEmpty(s):
{
yield return client.GetFeedViewsAsync(feed.Project.Id, feed.Id.ToString())
.GetResult($"Error getting artifact feed view(s) '{s}'")
.Where(fv => fv.Name.IsLike(s));
break;
}
default:
{
Logger.LogError(new ArgumentException($"Invalid or non-existent feed view '{view}'"));
break;
}
}
}
}
}
} |
#region File Description
//-----------------------------------------------------------------------------
// Dog.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
#endregion
namespace Audio3D
{
/// Entity class which sits in one place and plays dog sounds.
/// This uses a looping sound, which must be explicitly stopped
/// to prevent it going on forever. See the Cat class for an
/// example of using a single-shot sound.
class Dog : SpriteEntity
{
#region Fields
// How long until we should start or stop the sound.
TimeSpan timeDelay = TimeSpan.Zero;
// The sound which is currently playing, if any.
SoundEffectInstance activeSound = null;
#endregion
/// <summary>
/// Updates the position of the dog, and plays sounds.
/// </summary>
public override void Update(GameTime gameTime, AudioManager audioManager)
{
// Set the entity to a fixed position.
Position = new Vector3(0, 0, -4000);
Forward = Vector3.Forward;
Up = Vector3.Up;
Velocity = Vector3.Zero;
// If the time delay has run out, start or stop the looping sound.
// This would normally go on forever, but we stop it after a six
// second delay, then start it up again after four more seconds.
timeDelay -= gameTime.ElapsedGameTime;
if (timeDelay < TimeSpan.Zero)
{
if (activeSound == null)
{
// If no sound is currently playing, trigger one.
activeSound = audioManager.Play3DSound("DogSound", true, this);
timeDelay += TimeSpan.FromSeconds(6);
}
else
{
// Otherwise stop the current sound.
activeSound.Stop(false);
activeSound = null;
timeDelay += TimeSpan.FromSeconds(4);
}
}
}
}
}
|
using System.ComponentModel;
using Vip.DFe.Attributes;
namespace Vip.DFe.Shared.Enum
{
public enum TipoImpressao
{
[DFeEnum("0")] [Description("0 - Sem DANFE")]
SemDanfe = 0,
[DFeEnum("1")] [Description("1 - DANFE Normal Retrato")]
NormalRetrato = 1,
[DFeEnum("2")] [Description("2 - DANFE Normal Paisagem")]
NormalPaisagem = 2,
[DFeEnum("3")] [Description("3 - DANFE Simplificado")]
Simplificado = 3,
[DFeEnum("4")] [Description("4 - DANFE NFCe")]
NFCe = 4,
[DFeEnum("5")] [Description("5 - DANFE NFCe mensagem eletrônica")]
NFCeMensagemEletronica = 5,
}
} |
using System;
namespace RoadBook.CsharpBasic.Chapter02.Examples
{
public class Ex002
{
public void Run()
{
char ch = 'A';
string strMessage = "Hello World";
Console.WriteLine(ch);
Console.WriteLine(strMessage);
}
}
} |
namespace PlaylistSystem.Services.Contracts
{
using Models;
using System.Linq;
public interface IPlaylistService
{
IQueryable<Playlist> GetTop(int count);
IQueryable<Playlist> GetAll();
Playlist UpdateById(int id, Playlist updatedArticle);
void DeleteById(int id);
Playlist GetById(int id);
Playlist Create(Playlist newArticle);
}
}
|
namespace DSInternals.PowerShell
{
using System;
using DSInternals.DataStore;
using System.Security.Principal;
using DSInternals.Common.Data;
// Transport object
public class DomainController : IDomainController
{
public string Name
{
get;
set;
}
public string DNSHostName
{
get;
set;
}
public DistinguishedName ServerReference
{
get;
set;
}
public string DomainName
{
get;
set;
}
public string ForestName
{
get;
set;
}
public string NetBIOSDomainName
{
get;
set;
}
public SecurityIdentifier DomainSid
{
get;
set;
}
public Guid? DomainGuid
{
get;
set;
}
public Guid? Guid
{
get;
set;
}
public SecurityIdentifier Sid
{
get;
set;
}
public FunctionalLevel DomainMode
{
get;
set;
}
public FunctionalLevel ForestMode
{
get;
set;
}
public string SiteName
{
get;
set;
}
public System.Guid DsaGuid
{
get;
set;
}
public Guid InvocationId
{
get;
set;
}
public bool IsADAM
{
get;
set;
}
public bool IsGlobalCatalog
{
get;
set;
}
public DomainControllerOptions Options
{
get;
set;
}
public string OSName
{
get;
set;
}
public string OSVersion
{
get;
set;
}
public uint? OSVersionMajor
{
get;
set;
}
public uint? OSVersionMinor
{
get;
set;
}
public DistinguishedName DomainNamingContext
{
get;
set;
}
public DistinguishedName ConfigurationNamingContext
{
get;
set;
}
public DistinguishedName SchemaNamingContext
{
get;
set;
}
public string[] WritablePartitions
{
get;
set;
}
public DatabaseState State
{
get;
set;
}
public long HighestCommittedUsn
{
get;
set;
}
public long? UsnAtIfm
{
get;
set;
}
public long? BackupUsn
{
get;
set;
}
public DateTime? BackupExpiration
{
get;
set;
}
public int? Epoch
{
get;
set;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace LykkeWalletServices
{
public class WalletBackendHTTPClient : HttpClient
{
public async Task<HttpResponseMessage> GetAsync(string requestUri, int retryCount = 3)
{
// The benefit of retry over wait time is that in retries a new request is sent
// while the first request maybe stuck
// Manually tested with the help of Telerik Fiddler
int retries = 0;
while (true)
{
try
{
return await base.GetAsync(requestUri);
}
catch (TaskCanceledException exp)
{
retries++;
if (retries >= retryCount)
{
throw exp;
}
else
{
continue;
}
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using UnityEngine;
using Wowsome.Core;
using Wowsome.Generic;
namespace Wowsome.TwoDee {
public class WParticlePool : MonoBehaviour, ISceneController {
[Serializable]
public class PrefabConfig {
public ParticleSystem prefab;
public string id;
[Tooltip("the number of Gameobject to init")]
public int initCount;
[Tooltip("when it's true and there is no more object in the pool, it will instantiate a new gameobject")]
public bool cloneWhenEmpty;
}
public List<PrefabConfig> prefabs = new List<PrefabConfig>();
WObjectPool _pool = new WObjectPool();
HashSet<WParticleObject> _objects = new HashSet<WParticleObject>();
public WParticleObject Activate(string id, Vector3 worldPos) {
WParticleObject po = null;
var obj = _pool.Get(id);
if (null != obj) {
po = obj as WParticleObject;
Vector3 curPos = new Vector3(worldPos.x, worldPos.y, po.Position.z);
po.Position = curPos;
}
return po;
}
#region ISceneController
public void InitSceneController(ISceneStarter sceneStarter) {
for (int i = 0; i < prefabs.Count; ++i) {
Clone(prefabs[i]);
}
_pool.OnPoolEmpty += id => {
PrefabConfig config = prefabs.Find(x => x.id == id);
if (null != config && config.cloneWhenEmpty) {
Clone(config);
return true;
}
return false;
};
_pool.OnReleased += obj => {
// remove the obj from the cache of active objects
WParticleObject pObj = obj as WParticleObject;
};
}
public void UpdateSceneController(float dt) {
foreach (WParticleObject obj in _objects) {
obj.UpdateObject(dt);
}
}
#endregion
void Clone(PrefabConfig config) {
for (int i = 0; i < config.initCount; ++i) {
ParticleSystem p = config.prefab.Clone<ParticleSystem>(transform);
WParticleObject pObj = new WParticleObject(p, config);
_pool.Add(pObj);
_objects.Add(pObj);
}
}
}
}
|
/****************************** Module Header ******************************\
Module Name : Calculate Tax
File Name : CalculateTax.cs
Created by : Selvam Ramasamy
Project : Sales Tax
Copyright(c) : thoughtworks
<Description of the file>
\***************************************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace ConsoleApplication28
{
// CalculateTax class implements ICalculateTax interface
public class CalculateTax : ICalculateTax
{
// Array of SalesItems for each item
private SalesItems[] item = null;
// Create tax
private Tax tax = null;
// total tax and item amount
private double tot = 0;
// only total Tax
private double totaltax = 0.0;
// public cons for init the SalesItems values
public CalculateTax(SalesItems[] it)
{
tax = new Tax();
item = it;
}
// Calculate the Toal TaxItem Amount
public Hashtable CaluculateToalTaxItemAmount()
{
//create hashtable for store the total amount and item name
Hashtable h = new Hashtable(item.Length);
for (int i = 0; i < item.Length; i++)
{
tax = new Tax(); // create object for each item
tax.CalculateTax(item[i]); // calculate the tax
tot = tax.TotalItemAmount(item[i].Price,item[i].NoOfItems);// get the total amount
h.Add(item[i].Name, tot); // Add in Hashatable
}
return h; // return heash table
}
// method for calculate the total sales tax
public double TotalSalesTax()
{
// calculate the total sales tax amount
for (int i = 0; i < item.Length; i++)
{
tax = new Tax();
tax.CalculateTax(item[i]);
totaltax = totaltax + tax.TotalTaxAmount();
}
//return the rounded up to the nearest 0.05) amount of sales tax
return Math.Ceiling(totaltax * 20) / 20;
}
}
}
|
using System;
namespace ZptSharp.Expressions
{
/// <summary>
/// An implementation of <see cref="IConfiguresRootContext"/> which allows setting
/// of global variables into an expression context.
/// </summary>
public class RootContextConfigHelper : IConfiguresRootContext
{
readonly ExpressionContext context;
/// <summary>
/// Adds a named value to the root ZPT context.
/// </summary>
/// <param name="name">The name of the value to be added.</param>
/// <param name="value">The value to be added for the name.</param>
public void AddToRootContext(string name, object value)
{
context.GlobalDefinitions.Add(name, value);
}
/// <summary>
/// Initializes a new instance of the <see cref="RootContextConfigHelper"/> class.
/// </summary>
/// <param name="context">Context.</param>
public RootContextConfigHelper(ExpressionContext context)
{
this.context = context ?? throw new ArgumentNullException(nameof(context));
}
}
}
|
using System;
using UnityEngine;
using UnityEngine.UI;
public class ScoreManager : MonoBehaviour
{
public Text Score;
private string _time;
private bool _gameOver;
private float _score;
void Start ()
{
_time = "";
_gameOver = false;
_score = 9999999999;
}
void Update()
{
if (!_gameOver)
{
UpdateTime();
}
}
private void UpdateTime()
{
_score = Time.time;
_time = ScoreManager.GetScoreFormatting(Time.time);
Score.text = _time;
}
public void GameOver()
{
_gameOver = true;
}
public float GetScore()
{
return _score;
}
// we can call this function anywhere we want, we don't need to have an instance of this class
public static string GetScoreFormatting(float time)
{
int minutes = Mathf.FloorToInt(time / 60);
int seconds = Mathf.FloorToInt(time % 60);
float miliseconds = time * 100;
miliseconds = miliseconds % 100;
return string.Format("{0:0}:{1:00}:{2:00}", minutes, seconds, miliseconds);
}
}
|
using System;
namespace Obviously.SemanticTypes.Consumer.NetCoreConsole
{
[SemanticType(typeof(string))]
public partial class EmailAddressWithValidation
{
public static bool IsValid(string value)
{
return value.Contains('@', StringComparison.OrdinalIgnoreCase);
}
}
}
|
namespace Andromeda
{
/**
* Interface for events.
*/
public interface IEvent { }
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace UnityEngine
{
public enum RenderTextureFormat
{
//
// Summary:
// Color render texture format, 8 bits per channel.
ARGB32 = 0,
//
// Summary:
// A depth render texture format.
Depth = 1,
//
// Summary:
// Color render texture format, 16 bit floating point per channel.
ARGBHalf = 2,
//
// Summary:
// A native shadowmap render texture format.
Shadowmap = 3,
//
// Summary:
// Color render texture format.
RGB565 = 4,
//
// Summary:
// Color render texture format, 4 bit per channel.
ARGB4444 = 5,
//
// Summary:
// Color render texture format, 1 bit for Alpha channel, 5 bits for Red, Green and
// Blue channels.
ARGB1555 = 6,
//
// Summary:
// Default color render texture format: will be chosen accordingly to Frame Buffer
// format and Platform.
Default = 7,
//
// Summary:
// Color render texture format. 10 bits for colors, 2 bits for alpha.
ARGB2101010 = 8,
//
// Summary:
// Default HDR color render texture format: will be chosen accordingly to Frame
// Buffer format and Platform.
DefaultHDR = 9,
//
// Summary:
// Four color render texture format, 16 bits per channel, fixed point, unsigned
// normalized.
ARGB64 = 10,
//
// Summary:
// Color render texture format, 32 bit floating point per channel.
ARGBFloat = 11,
//
// Summary:
// Two color (RG) render texture format, 32 bit floating point per channel.
RGFloat = 12,
//
// Summary:
// Two color (RG) render texture format, 16 bit floating point per channel.
RGHalf = 13,
//
// Summary:
// Scalar (R) render texture format, 32 bit floating point.
RFloat = 14,
//
// Summary:
// Scalar (R) render texture format, 16 bit floating point.
RHalf = 15,
//
// Summary:
// Single channel (R) render texture format, 8 bit integer.
R8 = 16,
//
// Summary:
// Four channel (ARGB) render texture format, 32 bit signed integer per channel.
ARGBInt = 17,
//
// Summary:
// Two channel (RG) render texture format, 32 bit signed integer per channel.
RGInt = 18,
//
// Summary:
// Scalar (R) render texture format, 32 bit signed integer.
RInt = 19,
//
// Summary:
// Color render texture format, 8 bits per channel.
BGRA32 = 20,
//
// Summary:
// Color render texture format. R and G channels are 11 bit floating point, B channel
// is 10 bit floating point.
RGB111110Float = 22,
//
// Summary:
// Two color (RG) render texture format, 16 bits per channel, fixed point, unsigned
// normalized.
RG32 = 23,
//
// Summary:
// Four channel (RGBA) render texture format, 16 bit unsigned integer per channel.
RGBAUShort = 24,
//
// Summary:
// Two channel (RG) render texture format, 8 bits per channel.
RG16 = 25,
//
// Summary:
// Color render texture format, 10 bit per channel, extended range.
BGRA10101010_XR = 26,
//
// Summary:
// Color render texture format, 10 bit per channel, extended range.
BGR101010_XR = 27,
//
// Summary:
// Single channel (R) render texture format, 16 bit integer.
R16 = 28
}
}
|
#if !DISABLE_REACTIVE_COMPONENTS
using System;
using System.Collections.Generic;
using System.Linq;
using Improbable.Worker.CInterop;
using Unity.Entities;
namespace Improbable.Gdk.ReactiveComponents
{
public static class AuthorityChangesProvider
{
private static readonly Dictionary<uint, List<Authority>> Storage = new Dictionary<uint, List<Authority>>();
private static readonly Dictionary<uint, World> WorldMapping = new Dictionary<uint, World>();
private static uint nextHandle;
public static uint Allocate(World world)
{
var handle = GetNextHandle();
Storage.Add(handle, default(List<Authority>));
WorldMapping.Add(handle, world);
return handle;
}
public static List<Authority> Get(uint handle)
{
if (!Storage.TryGetValue(handle, out var value))
{
throw new ArgumentException($"AuthorityChangesProvider does not contain handle {handle}");
}
return value;
}
public static void Set(uint handle, List<Authority> value)
{
if (!Storage.ContainsKey(handle))
{
throw new ArgumentException($"AuthorityChangesProvider does not contain handle {handle}");
}
Storage[handle] = value;
}
public static void Free(uint handle)
{
Storage.Remove(handle);
WorldMapping.Remove(handle);
}
public static void CleanDataInWorld(World world)
{
var handles = WorldMapping.Where(pair => pair.Value == world).Select(pair => pair.Key).ToList();
foreach (var handle in handles)
{
Free(handle);
}
}
private static uint GetNextHandle()
{
nextHandle++;
while (Storage.ContainsKey(nextHandle))
{
nextHandle++;
}
return nextHandle;
}
}
}
#endif
|
namespace Auditable.AspNetCore.Tests.Infrastructure
{
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication;
public class TestAuthenticationOptions : AuthenticationSchemeOptions
{
public virtual ClaimsIdentity Identity { get; } = new ClaimsIdentity(new[]
{
new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", "abc-123"),
new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name", "dave")
}, "test");
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace NetworkStreamDemo
{
class Program
{
static void Main(string[] args)
{
TcpClient tcpClient = new TcpClient();
tcpClient.Connect("www.baidu.com", 80);
NetworkStream networkStream = tcpClient.GetStream();
//是否有数据可读
if (networkStream.CanRead)
{
//接收数据的缓冲区
byte[] dataBuff = new byte[1024];
StringBuilder stringBuilder = new StringBuilder();
int ReceiveNum = 0;
//准备接受的消息长度可能大于1024,用循环读取
do
{
ReceiveNum = networkStream.Read(dataBuff, 0, dataBuff.Length);
stringBuilder.AppendFormat("{0}", Encoding.UTF8.GetString(dataBuff, 0, ReceiveNum));
} while (networkStream.DataAvailable);
Console.WriteLine("接收到的消息为:" + stringBuilder);
}
else
{
Console.WriteLine("当前没有可供读取的数据!");
}
}
}
}
|
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using Microsoft.CloudMine.GitHub.Collectors.Model;
using System.Threading.Tasks;
namespace Microsoft.CloudMine.GitHub.Collectors.Cache
{
public interface IEventsBookkeeper
{
Task InitializeAsync();
Task SignalCountAsync(Repository eventStats);
Task<int> IncrementCountAsync(Repository repositoryDetails);
Task ResetCountAsync(Repository repositoryDetails);
}
}
|
using System;
using System.Collections.Generic;
namespace Skclusive.Dashboard.App.View
{
public class OrderData
{
public static IEnumerable<Order> GetOrders()
{
yield return new Order
{
Id = Guid.NewGuid().ToString(),
Ref = "CDD1049",
Customer = "Ekaterina Tankova",
Status = "pending",
Amount = 30.5M,
CreatedAt = DateTime.Now.AddDays(-12)
};
yield return new Order
{
Id = Guid.NewGuid().ToString(),
Ref = "CDD1048",
Customer = "Cao Yu",
Status = "delivered",
Amount = 25.1M,
CreatedAt = DateTime.Now.AddDays(-3)
};
yield return new Order
{
Id = Guid.NewGuid().ToString(),
Ref = "CDD1047",
Customer = "Alexa Richardson",
Status = "refunded",
Amount = 10.99M,
CreatedAt = DateTime.Now.AddDays(-1)
};
yield return new Order
{
Id = Guid.NewGuid().ToString(),
Ref = "CDD1046",
Customer = "Anje Keizer",
Status = "pending",
Amount = 96.43M,
CreatedAt = DateTime.Now.AddDays(-6)
};
yield return new Order
{
Id = Guid.NewGuid().ToString(),
Ref = "CDD1045",
Customer = "Clarke Gillebert",
Status = "delivered",
Amount = 32.54M,
CreatedAt = DateTime.Now.AddDays(-4)
};
yield return new Order
{
Id = Guid.NewGuid().ToString(),
Ref = "CDD1044",
Customer = "Adam Denisov",
Status = "delivered",
Amount = 16.76M,
CreatedAt = DateTime.Now.AddDays(-8)
};
}
}
}
|
namespace DemoWebApplication.Controllers
{
using CustomFramework.Http;
using CustomFramework.Mvc;
using CustomFramework.Mvc.Attributes;
using Services;
using Data.Models;
public class HomeController : Controller
{
private readonly IUsersService usersService;
public HomeController(IUsersService usersService)
{
this.usersService = usersService;
}
[HttpGet("/")]
public HttpResponse Index()
{
if (this.IsUserLoggedIn())
{
User user = this.usersService.GetUser(this.User);
return this.View(user.Username);
}
return this.View();
}
}
}
|
namespace Lab11
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.textPlain = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.textKey = new System.Windows.Forms.TextBox();
this.btnEncrypt = new System.Windows.Forms.Button();
this.btnDecrypt = new System.Windows.Forms.Button();
this.textEncrypt = new System.Windows.Forms.TextBox();
this.label3 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.textDecrypt = new System.Windows.Forms.TextBox();
this.SuspendLayout();
//
// textPlain
//
this.textPlain.Location = new System.Drawing.Point(24, 33);
this.textPlain.Multiline = true;
this.textPlain.Name = "textPlain";
this.textPlain.Size = new System.Drawing.Size(185, 53);
this.textPlain.TabIndex = 0;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(21, 17);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(50, 13);
this.label1.TabIndex = 1;
this.label1.Text = "Plain text";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(21, 92);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(25, 13);
this.label2.TabIndex = 2;
this.label2.Text = "Key";
//
// textKey
//
this.textKey.Location = new System.Drawing.Point(24, 111);
this.textKey.Name = "textKey";
this.textKey.Size = new System.Drawing.Size(185, 20);
this.textKey.TabIndex = 3;
//
// btnEncrypt
//
this.btnEncrypt.Location = new System.Drawing.Point(24, 145);
this.btnEncrypt.Name = "btnEncrypt";
this.btnEncrypt.Size = new System.Drawing.Size(86, 26);
this.btnEncrypt.TabIndex = 4;
this.btnEncrypt.Text = "Encrypt";
this.btnEncrypt.UseVisualStyleBackColor = true;
this.btnEncrypt.Click += new System.EventHandler(this.btnEncrypt_Click);
//
// btnDecrypt
//
this.btnDecrypt.Location = new System.Drawing.Point(123, 145);
this.btnDecrypt.Name = "btnDecrypt";
this.btnDecrypt.Size = new System.Drawing.Size(86, 26);
this.btnDecrypt.TabIndex = 5;
this.btnDecrypt.Text = "Decrypt";
this.btnDecrypt.UseVisualStyleBackColor = true;
this.btnDecrypt.Click += new System.EventHandler(this.btnDecrypt_Click);
//
// textEncrypt
//
this.textEncrypt.Location = new System.Drawing.Point(236, 33);
this.textEncrypt.Multiline = true;
this.textEncrypt.Name = "textEncrypt";
this.textEncrypt.Size = new System.Drawing.Size(185, 53);
this.textEncrypt.TabIndex = 0;
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(233, 17);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(75, 13);
this.label3.TabIndex = 1;
this.label3.Text = "Encrypted text";
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(233, 99);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(76, 13);
this.label4.TabIndex = 1;
this.label4.Text = "Decrypted text";
//
// textDecrypt
//
this.textDecrypt.Location = new System.Drawing.Point(236, 118);
this.textDecrypt.Multiline = true;
this.textDecrypt.Name = "textDecrypt";
this.textDecrypt.Size = new System.Drawing.Size(185, 53);
this.textDecrypt.TabIndex = 0;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(439, 193);
this.Controls.Add(this.btnDecrypt);
this.Controls.Add(this.btnEncrypt);
this.Controls.Add(this.textKey);
this.Controls.Add(this.label2);
this.Controls.Add(this.label4);
this.Controls.Add(this.label3);
this.Controls.Add(this.label1);
this.Controls.Add(this.textDecrypt);
this.Controls.Add(this.textEncrypt);
this.Controls.Add(this.textPlain);
this.Name = "Form1";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Lab11";
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.TextBox textPlain;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.TextBox textKey;
private System.Windows.Forms.Button btnEncrypt;
private System.Windows.Forms.Button btnDecrypt;
private System.Windows.Forms.TextBox textEncrypt;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.TextBox textDecrypt;
}
}
|
using System.Linq;
using System.Collections.Generic;
using HotChocolate.Language;
using HotChocolate.Language.Utilities;
using Xunit;
using Snapshooter.Xunit;
namespace HotChocolate.Stitching.Merge.Handlers
{
public class InputObjectTypeMergeHandlerTests
{
[Fact]
public void Merge_SimpleIdenticalInputs_TypeMerges()
{
// arrange
DocumentNode schema_a =
Utf8GraphQLParser.Parse("input A { b: String }");
DocumentNode schema_b =
Utf8GraphQLParser.Parse("input A { b: String }");
var types = new List<ITypeInfo>
{
TypeInfo.Create(
schema_a.Definitions.OfType<ITypeDefinitionNode>().First(),
new SchemaInfo("Schema_A", schema_a)),
TypeInfo.Create(
schema_b.Definitions.OfType<ITypeDefinitionNode>().First(),
new SchemaInfo("Schema_B", schema_b))
};
var context = new SchemaMergeContext();
// act
var typeMerger = new InputObjectTypeMergeHandler((c, t) => { });
typeMerger.Merge(context, types);
// assert
context
.CreateSchema()
.Print()
.MatchSnapshot();
}
[Fact]
public void Merge_ThreeInputsWhereTwoAreIdentical_TwoTypesAfterMerge()
{
// arrange
DocumentNode schema_a =
Utf8GraphQLParser.Parse("input A { b: String }");
DocumentNode schema_b =
Utf8GraphQLParser.Parse("input A { b: String c: String }");
DocumentNode schema_c =
Utf8GraphQLParser.Parse("input A { b: String }");
var types = new List<ITypeInfo>
{
TypeInfo.Create(
schema_a.Definitions.OfType<ITypeDefinitionNode>().First(),
new SchemaInfo("Schema_A", schema_a)),
TypeInfo.Create(
schema_b.Definitions.OfType<ITypeDefinitionNode>().First(),
new SchemaInfo("Schema_B", schema_b)),
TypeInfo.Create(
schema_c.Definitions.OfType<ITypeDefinitionNode>().First(),
new SchemaInfo("Schema_C", schema_c))
};
var context = new SchemaMergeContext();
// act
var typeMerger = new InputObjectTypeMergeHandler((c, t) => { });
typeMerger.Merge(context, types);
// assert
context
.CreateSchema()
.Print()
.MatchSnapshot();
}
[Fact]
public void Merge_DifferentTypes_InputMergesLeftoversArePassed()
{
// arrange
DocumentNode schema_a =
Utf8GraphQLParser.Parse("input A { b: String }");
DocumentNode schema_b =
Utf8GraphQLParser.Parse("enum A { B C }");
var types = new List<ITypeInfo>
{
TypeInfo.Create(
schema_a.Definitions.OfType<ITypeDefinitionNode>().First(),
new SchemaInfo("Schema_A", schema_a)),
TypeInfo.Create(
schema_b.Definitions.OfType<ITypeDefinitionNode>().First(),
new SchemaInfo("Schema_B", schema_b)),
};
var context = new SchemaMergeContext();
var leftovers = new List<ITypeInfo>();
// act
var typeMerger = new InputObjectTypeMergeHandler(
(c, t) => leftovers.AddRange(t));
typeMerger.Merge(context, types);
// assert
Assert.Collection(leftovers,
t => Assert.IsType<EnumTypeInfo>(t));
Snapshot.Match(new List<object>
{
context.CreateSchema().Print(),
leftovers
});
}
}
}
|
using NLog;
using System;
using System.Collections.Generic;
using System.Reflection;
namespace Geek.Server
{
public class MsgFactory
{
private static readonly Logger LOGGER = LogManager.GetCurrentClassLogger();
private static Dictionary<int, Type> MsgDic = new Dictionary<int, Type>();
public static void InitMsg(Type assemblyType)
{
foreach (var type in assemblyType.Assembly.GetTypes())
{
if (!type.IsSubclassOf(typeof(BaseMessage))) continue;
var msgIdField = type.GetField("SID", BindingFlags.Static | BindingFlags.Public);
if (msgIdField == null) continue;
int msgId = (int)msgIdField.GetValue(null);
if (MsgDic.ContainsKey(msgId))
LOGGER.Error($"重复的消息 msgId:{msgId}");
else
MsgDic.Add(msgId, type);
}
}
public static IMessage GetMsg(int msgId)
{
if (!MsgDic.ContainsKey(msgId))
{
LOGGER.Error($"未注册的消息ID:{msgId}");
return null;
}
Type msgType = MsgDic[msgId];
var msg = Activator.CreateInstance(msgType) as IMessage;
if (msg == null)
LOGGER.Error($"创建msg失败 msgId:{msgId} msgTy[e:{msgType}");
return msg;
}
}
}
|
using CustomerRecords.Models.ValueObjects;
using System;
using System.Collections.Generic;
using System.Text;
namespace CustomerRecords.Services.Interfaces
{
/// <summary>
/// Service provides geo utils
/// </summary>
public interface IGeoService
{
/// <summary>
/// get distance between points in km
/// </summary>
/// <param name="point1">Coordinates of point 1</param>
/// <param name="point2">Coordinates of point 2</param>
/// <returns>Distnace in km</returns>
double GetDistance(GeoCoordinate point1, GeoCoordinate point2);
}
}
|
namespace CompanyName.Notebook.NoteTaking.Core.Domain.Factories
{
using System;
using CompanyName.Notebook.NoteTaking.Core.Domain.Models;
public interface ICategoryFactory
{
ICategory Create(
string name,
INoteFactory noteFactory,
ISubscriberFactory subscriberFactory
);
ICategory Build(
ICategory category,
INoteFactory noteFactory,
ISubscriberFactory subscriberFactory
);
}
} |
using System;
using System.Globalization;
using System.Runtime.Serialization;
using System.Threading;
using System.Xml.Serialization;
namespace Gimela.Tasks.Triggers
{
/// <summary>
/// 触发器,这是一个抽象类。
/// </summary>
[Serializable]
[DataContract]
[XmlInclude(typeof(OnceTrigger)), XmlInclude(typeof(CronTrigger))]
[KnownType(typeof(OnceTrigger))]
[KnownType(typeof(CronTrigger))]
public abstract class Trigger : ITrigger
{
/// <summary>
/// 触发器构造函数
/// </summary>
protected Trigger()
{
}
/// <summary>
/// 触发器Id
/// </summary>
[XmlAttribute]
[DataMember]
public string Id { get; set; }
/// <summary>
/// 触发器名称
/// </summary>
[XmlAttribute]
[DataMember]
public string Name { get; set; }
/// <summary>
/// 被触发执行的作业
/// </summary>
[XmlIgnore]
[IgnoreDataMember]
public IJob TargetJob { get; set; }
/// <summary>
/// 触发器已终结事件
/// </summary>
public event EventHandler<TriggerTerminatedEventArgs> TriggerTerminatedEvent;
/// <summary>
/// 触发器是否已终结
/// </summary>
[XmlIgnore]
[IgnoreDataMember]
public bool IsTerminated { get; set; }
/// <summary>
/// 终结触发器
/// </summary>
public void Terminate()
{
IsTerminated = true;
if (TriggerTerminatedEvent != null)
{
TriggerTerminatedEvent(this, new TriggerTerminatedEventArgs(this.Id));
}
}
/// <summary>
/// 运行触发器之前的准备工作
/// </summary>
protected virtual void PrepareRun()
{
}
/// <summary>
/// 运行触发器
/// </summary>
/// <param name="job">被触发作业</param>
public void Run(IJob job)
{
this.TargetJob = job;
Run();
}
/// <summary>
/// 运行触发器
/// </summary>
public void Run()
{
PrepareRun();
while (!IsTerminated)
{
if (CheckFireTime())
{
try
{
ThreadPool.QueueUserWorkItem((state) =>
{
Fire();
},
null);
}
catch { }
}
if (CheckContinue())
{
Thread.Sleep(WaitingMilliseconds);
}
else
{
Terminate();
}
}
}
/// <summary>
/// 触发触发器
/// </summary>
protected void Fire()
{
if (TargetJob != null)
{
TargetJob.Run();
}
}
/// <summary>
/// 检测触发时间
/// </summary>
/// <returns></returns>
protected abstract bool CheckFireTime();
/// <summary>
/// 检测是否继续
/// </summary>
/// <returns></returns>
protected abstract bool CheckContinue();
/// <summary>
/// 获取等待时长 微秒
/// </summary>
/// <returns></returns>
protected abstract int WaitingMilliseconds { get; }
#region ToString
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="System.String"/> that represents this instance.
/// </returns>
public override string ToString()
{
return string.Format(CultureInfo.InvariantCulture, @"Id[{0}], Name[{1}]", Id, Name);
}
#endregion
}
}
|
namespace DesignPattern.Composite.VirtualDirectoryExample
{
public class FileItem : FileSystemItem
{
public FileItem(string name, long fileBytes) : base(name)
{
this.FileBytes = fileBytes;
}
public long FileBytes { get; }
public override decimal GetSizeInKb()
{
return decimal.Divide(FileBytes, 1000);
}
}
}
|
using System;
namespace GirLoader.Output
{
internal class AliasFactory
{
private readonly TypeReferenceFactory _typeReferenceFactory;
public AliasFactory(TypeReferenceFactory typeReferenceFactory)
{
_typeReferenceFactory = typeReferenceFactory;
}
public Alias Create(Input.Alias alias, Repository repository)
{
if (alias.Type is null)
throw new Exception("Alias is missing a type");
if (alias.Name is null)
throw new Exception("Alias is missing a name");
if (alias.For?.Name is null)
throw new Exception($"Alias {alias.Name} is missing target");
return new Alias(
cType: alias.Type,
name: alias.Name,
typeReference: _typeReferenceFactory.CreateResolveable(alias.For.Name, alias.For.CType),
repository: repository
);
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Text;
using ALinq.SqlClient;
namespace ALinq.SqlClient.Implementation
{
/// <summary>
/// Defines methods for dynamically materializing objects.
/// </summary>
/// <typeparam name="TDataReader">The type of the data reader.</typeparam>
public abstract class ObjectMaterializer<TDataReader> where TDataReader : DbDataReader
{
/// <summary>
/// Captures internal state for the fast materializer.
/// </summary>
public object[] Arguments;
/// <summary>
/// Represents a reader that reads data rows in a forward-only manner.
/// </summary>
public DbDataReader BufferReader;
/// <summary>
/// Represents a data reader.
/// </summary>
public TDataReader DataReader;
/// <summary>
/// Captures internal state for the fast materializer.
/// </summary>
public object[] Globals;
/// <summary>
/// Captures internal state for the fast materializer.
/// </summary>
public object[] Locals;
/// <summary>
/// Represents column ordinals of a data reader.
/// </summary>
public int[] Ordinals;
/// <summary>
/// Initializes a new instance of the ALinq.SqlClient.Implementation.ObjectMaterializer<TDataReader> class.
/// </summary>
protected ObjectMaterializer()
{
this.DataReader = default(TDataReader);
}
/// <summary>
/// Changes the type of each element in a specified sequence.
/// </summary>
/// <typeparam name="TOutput">The type to convert the elements to.</typeparam>
/// <param name="source">A sequence that contains elements to convert.</param>
/// <returns>A sequence that contains the type-converted elements.</returns>
public static IEnumerable<TOutput> Convert<TOutput>(IEnumerable source)
{
//<Convert>d__0<TDataReader, TOutput> d__ = new <Convert>d__0<TDataReader, TOutput>(-2);
//d__.<>3__source = source;
//return d__;
foreach (var item in source)
yield return DBConvert.ChangeType<TOutput>(item);
}
/// <summary>
/// Creates a group from a specified key and collection of values.
/// </summary>
/// <typeparam name="TKey">The type of the key of the group.</typeparam>
/// <typeparam name="TElement">The type of the values in the group.</typeparam>
/// <param name="key">The key for the group.</param>
/// <param name="items">The values for the group.</param>
/// <returns>A group that has the specified key and the specified collection of values.</returns>
public static IGrouping<TKey, TElement> CreateGroup<TKey, TElement>(TKey key, IEnumerable<TElement> items)
{
return new ObjectReaderCompiler.Group<TKey, TElement>(key, items);
}
/// <summary>
/// Creates an ordered sequence from a specified collection of values.
/// </summary>
/// <typeparam name="TElement">The type of the values in the ordered sequence.</typeparam>
/// <param name="items">The values to put in the ordered sequence.</param>
/// <returns>An ordered sequence that contains the specified values.</returns>
public static IOrderedEnumerable<TElement> CreateOrderedEnumerable<TElement>(IEnumerable<TElement> items)
{
return new ObjectReaderCompiler.OrderedResults<TElement>(items);
}
/// <summary>
/// Returns an exception that indicates that a null value was tried to be assigned to a non-nullable value type.
/// </summary>
/// <param name="type">The type to which a null value was attempted to be assigned.</param>
/// <returns>An exception that indicates that a null value was attempted to be assigned to a non-nullable value type.</returns>
public static Exception ErrorAssignmentToNull(Type type)
{
return SqlClient.Error.CannotAssignNull(type);
}
/// <summary>
/// When overridden in a derived class, executes a query.
/// </summary>
/// <param name="iSubQuery">The index of the query.</param>
/// <param name="args">The arguments to the query.</param>
/// <returns>The results from executing the query.</returns>
public abstract IEnumerable ExecuteSubQuery(int iSubQuery, object[] args);
/// <summary>
/// When overridden in a derived class, creates a new deferred source.
/// </summary>
/// <typeparam name="T">The type of the result elements.</typeparam>
/// <param name="globalLink">The index of the link.</param>
/// <param name="localFactory">The index of the factory.</param>
/// <param name="keyValues">The key values for the deferred source.</param>
/// <returns>An enumerable deferred source.</returns>
public abstract IEnumerable<T> GetLinkSource<T>(int globalLink, int localFactory, object[] keyValues);
/// <summary>
/// When overridden in a derived class, creates a new deferred source.
/// </summary>
/// <typeparam name="T">The type of the result elements.</typeparam>
/// <param name="globalLink">The index of the link.</param>
/// <param name="localFactory">The index of the factory.</param>
/// <param name="instance">The instance for the deferred source.</param>
/// <returns>An enumerable deferred source.</returns>
public abstract IEnumerable<T> GetNestedLinkSource<T>(int globalLink, int localFactory, object instance);
/// <summary>
/// When overridden in a derived class, inserts a value into a data structure.
/// </summary>
/// <param name="globalMetaType">The index of the ALinq.Mapping.MetaType.</param>
/// <param name="instance">The object to insert into the data structure.</param>
/// <returns>The value that was inserted into the data structure.</returns>
public abstract object InsertLookup(int globalMetaType, object instance);
/// <summary>
/// When overridden in a derived class, advances the reader to the next record.
/// </summary>
/// <returns>true if there are more rows; otherwise, false.</returns>
public abstract bool Read();
/// <summary>
/// When overridden in a derived class, invokes the method represented by ALinq.Mapping.MetaType.OnLoadedMethod.
/// </summary>
/// <param name="globalMetaType">The index of the ALinq.Mapping.MetaType.</param>
/// <param name="instance">The parameter to pass to the invoked method.</param>
public abstract void SendEntityMaterialized(int globalMetaType, object instance);
/// <summary>
/// When overridden in a derived class, gets a value that indicates whether deferred loading is enabled.
/// </summary>
/// <returns>
/// true if deferred loading is enabled; otherwise, false.
/// </returns>
public abstract bool CanDeferLoad { get; }
}
} |
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using OSnack.Web.Api.AppSettings;
using OSnack.Web.Api.Database.Context;
using OSnack.Web.Api.Database.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mime;
using System.Threading.Tasks;
using static OSnack.Web.Api.AppSettings.oAppFunc;
namespace OSnack.Web.Api.Controllers
{
[Route("[controller]")]
public class AddressController : ControllerBase
{
private AppDbContext DbContext { get; }
private List<oError> ErrorsList = new List<oError>();
/// <summary>
/// Class Constructor. Set the local properties
/// </summary>
/// <param name="db">Receive the AppDbContext instance from the ASP.Net Pipeline</param>
public AddressController(AppDbContext db) => DbContext = db;
/// <summary>
/// Used to get a list of Address
/// </summary>
#region *** 200 OK, 417 ExpectationFailed ***
[Consumes(MediaTypeNames.Application.Json)]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status417ExpectationFailed)]
#endregion
[HttpGet("[action]/{userId}")]
// [Authorize(oAppConst.AccessPolicies.LevelFour)] /// Ready For Test
public IActionResult Get(int userId)
{
try
{
/// return the list of User's Address
return Ok(DbContext.Addresses.Where(t => t.User.Id == userId));
}
catch (Exception) //ArgumentNullException
{
/// in the case any exceptions return the following error
oAppFunc.Error(ref ErrorsList, oAppConst.CommonErrors.ServerError);
return StatusCode(417, ErrorsList);
}
}
/// <summary>
/// Create a new Address
/// </summary>
#region *** 201 Created, 400 BadRequest, 422 UnprocessableEntity, 417 ExpectationFailed ***
[HttpPost("[action]")]
[Consumes(MediaTypeNames.Application.Json)]
[ProducesResponseType(StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status422UnprocessableEntity)]
[ProducesResponseType(StatusCodes.Status417ExpectationFailed)]
#endregion
// [Authorize(oAppConst.AccessPolicies.LevelTwo)] /// Ready For Test
public async Task<IActionResult> Post([FromBody] oAddress newAddress)
{
try
{
/// if model validation failed
if (!TryValidateModel(newAddress))
{
oAppFunc.ExtractErrors(ModelState, ref ErrorsList);
/// return Unprocessable Entity with all the errors
return UnprocessableEntity(ErrorsList);
}
/// Add the new Address to the EF context
await DbContext.Addresses.AddAsync(newAddress).ConfigureAwait(false);
/// save the changes to the data base
await DbContext.SaveChangesAsync().ConfigureAwait(false);
/// return 201 created status with the new object
/// and success message
return Created("Success", newAddress);
}
catch (Exception) // DbUpdateException, DbUpdateConcurrencyException
{
/// Add the error below to the error list and return bad request
oAppFunc.Error(ref ErrorsList, oAppConst.CommonErrors.ServerError);
return StatusCode(417, ErrorsList);
}
}
/// <summary>
/// Update a modified Address
/// </summary>
#region *** 200 OK, 304 NotModified,422 UnprocessableEntity, 417 ExpectationFailed***
[HttpPut("[action]")]
[Consumes(MediaTypeNames.Application.Json)]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status422UnprocessableEntity)]
[ProducesResponseType(StatusCodes.Status417ExpectationFailed)]
#endregion
// [Authorize(oAppConst.AccessPolicies.LevelTwo)] /// Ready For Test
public async Task<IActionResult> Put([FromBody] oAddress modifiedAddress)
{
try
{
/// if model validation failed
if (!TryValidateModel(modifiedAddress))
{
oAppFunc.ExtractErrors(ModelState, ref ErrorsList);
/// return Unprocessable Entity with all the errors
return UnprocessableEntity(ErrorsList);
}
/// Update the current Address to the EF context
DbContext.Addresses.Update(modifiedAddress);
/// save the changes to the data base
await DbContext.SaveChangesAsync().ConfigureAwait(false);
/// return 200 OK (Update) status with the modified object
/// and success message
return Ok(modifiedAddress);
}
catch (Exception) // DbUpdateException, DbUpdateConcurrencyException
{
/// Add the error below to the error list and return bad request
oAppFunc.Error(ref ErrorsList, oAppConst.CommonErrors.ServerError);
return StatusCode(417, ErrorsList);
}
}
/// <summary>
/// Delete Address
/// </summary>
#region *** 200 OK,417 ExpectationFailed, 400 BadRequest, 404 NotFound ***
[HttpDelete("[action]")]
[Consumes(MediaTypeNames.Application.Json)]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status417ExpectationFailed)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
#endregion
//[Authorize(oAppConst.AccessPolicies.LevelTwo)] /// Ready For Test
public async Task<IActionResult> Delete([FromBody] oAddress address)
{
try
{
/// if the Address record with the same id is not found
if (!await DbContext.Addresses.AnyAsync(d => d.Id == address.Id).ConfigureAwait(false))
{
oAppFunc.Error(ref ErrorsList, "Category not found");
return NotFound(ErrorsList);
}
/// now delete the Address record
DbContext.Addresses.Remove(address);
/// save the changes to the database
await DbContext.SaveChangesAsync().ConfigureAwait(false);
/// return 200 OK status
return Ok($"Address was deleted");
}
catch (Exception)
{
/// Add the error below to the error list
oAppFunc.Error(ref ErrorsList, oAppConst.CommonErrors.ServerError);
return StatusCode(417, ErrorsList);
}
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class InstanciadorDeZombies : MonoBehaviour {
public int[] tiempos;
public GameObject Zombie;
void Start()
{
for (int i = 0; i < tiempos.Length; i++)
{
Invoke("InstanciarZombie", tiempos[i]);
}
}
void InstanciarZombie()
{
Instantiate(Zombie, transform.position, Zombie.transform.rotation);
}
}
|
using System;
namespace IAttendanceWebAPI.Core.Entities
{
public class Message
{
public int Id { get; set; }
public string FromUserId { get; set; }
public User FromUser { get; set; }
public string ToUserId { get; set; }
public User ToUser { get; set; }
public string Topic { get; set; }
public string Description { get; set; }
public int StatusMessageId { get; set; }
public StatusMessage StatusMessage { get; set; }
public int TimeTableId { get; set; }
public TimeTable TimeTable { get; set; }
public DateTime Date { get; set; }
}
} |
@* Copyright © 2020 Dmitry Sikorsky. All rights reserved. *@
@* Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. *@
@model Platformus.ECommerce.Backend.ViewModels.ECommerce.ProductSelectorFormViewModel
@inject Microsoft.AspNetCore.Mvc.Localization.IViewLocalizer Localizer
<div class="pop-up-form__header">
@Localizer["Product Selector"]
</div>
<div class="pop-up-form__content">
<div class="item-selector-pop-up-form__items">
<table class="item-selector-pop-up-form__table table">
<columns>
@foreach (var tableColumn in this.Model.TableColumns)
{
<column label="@tableColumn.Label" />
}
</columns>
<rows>
@foreach (var product in this.Model.Products)
{
<row class="@(product.Id == this.Model.ProductId ? "table__row--selected" : null)" data-item-value="@product.Id">
<cell class="item-selector-pop-up-form__cell">@product.Category.Name</cell>
<cell class="item-selector-pop-up-form__cell">@product.Name</cell>
</row>
}
</rows>
</table>
</div>
<div class="pop-up-form__buttons buttons">
<positive-button onclick="return platformus.forms.productSelectorForm.select();">@Localizer["Select"]</positive-button>
<neutral-button onclick="return platformus.forms.productSelectorForm.hideAndRemove();">@Localizer["Cancel"]</neutral-button>
</div>
</div> |
using System;
using System.Collections.Generic;
using System.Text;
using Omnix.Cryptography;
namespace Xeus.Core.Contents.Internal
{
partial class SharedBlocksInfo
{
#region OmniHash to Index
private Dictionary<OmniHash, int> _hashMap = null;
public int GetIndex(OmniHash hash)
{
if (_hashMap == null)
{
_hashMap = new Dictionary<OmniHash, int>();
for (int i = 0; i < this.Hashes.Count; i++)
{
_hashMap[this.Hashes[i]] = i;
}
}
{
int result;
if (!_hashMap.TryGetValue(hash, out result)) return -1;
return result;
}
}
#endregion
}
}
|
using System;
namespace Services.Common.ObjUtils
{
public abstract class DisposableModel : IDisposable
{
private bool IsDisposed { get; set; }
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool isDisposing)
{
if (IsDisposed)
{
return;
}
if (isDisposing)
{
DisposeUnmanagedResources();
}
IsDisposed = true;
}
protected virtual void DisposeUnmanagedResources()
{
}
~DisposableModel()
{
Dispose(false);
}
}
} |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using O2NextGen.ESender.Business.Models;
using O2NextGen.ESender.Data.Entities;
namespace O2NextGen.ESender.Impl.Mappings
{
public class BaseMappings<TViewModel, TModel>
where TViewModel : class, IDbEntity
where TModel : class, IBaseModel
{
public TViewModel ToViewModel(TModel model)
{
if (model == null)
return null;
var returnViewModel = Activator.CreateInstance<TViewModel>();
returnViewModel.Id = model.Id;
returnViewModel.AddedDate = model.AddedDate;
returnViewModel.ModifiedDate = model.ModifiedDate;
returnViewModel.DeletedDate = model.DeletedDate;
returnViewModel.IsDeleted = model.IsDeleted;
return returnViewModel;
}
public TModel ToServiceModel(TViewModel viewModel)
{
//Todo: return not null
if (viewModel == null)
return null;
var model = Activator.CreateInstance<TModel>();
model.Id = viewModel.Id;
model.AddedDate = viewModel.AddedDate;
model.ModifiedDate = viewModel.ModifiedDate;
model.DeletedDate = viewModel.DeletedDate;
model.IsDeleted = viewModel.IsDeleted;
return model;
}
public IReadOnlyCollection<TViewModel> ToViewModel(IReadOnlyCollection<TModel> models)
{
if (models.Count == 0)
{
return Array.Empty<TViewModel>();
}
var subscription = new TViewModel[models.Count];
var i = 0;
foreach (var model in models)
{
subscription[i] = ToViewModel(model);
++i;
}
return new ReadOnlyCollection<TViewModel>(subscription);
}
}
} |
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Identity;
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Authorization;
using Final.Models;
using Final.Areas.Admin.ViewModels;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
// For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
namespace Final.Areas.Admin.Controllers
{
[Area("wp-admin")]
[Authorize(Roles = "Admins")]
public class RoleController : Controller
{
private RoleManager<IdentityRole> _roleManager;
private UserManager<BlogMember> _userManager;
public RoleController(RoleManager<IdentityRole> roleMgr,
UserManager<BlogMember> userMrg)
{
_roleManager = roleMgr;
_userManager = userMrg;
}
public ViewResult Index() => View(_roleManager.Roles);
public IActionResult Create() => View();
[HttpPost]
public async Task<IActionResult> Create([Required]string name)
{
if (ModelState.IsValid)
{
IdentityResult result
= await _roleManager.CreateAsync(new IdentityRole(name));
if (result.Succeeded)
{
return RedirectToAction("Index");
}
else
{
AddErrorsFromResult(result);
}
}
return View(name);
}
[HttpPost]
public async Task<IActionResult> Delete(string id)
{
IdentityRole role = await _roleManager.FindByIdAsync(id);
if (role != null)
{
IdentityResult result = await _roleManager.DeleteAsync(role);
if (result.Succeeded)
{
return RedirectToAction("Index");
}
else
{
AddErrorsFromResult(result);
}
}
else
{
ModelState.AddModelError("", "No role found");
}
return View("Index", _roleManager.Roles);
}
private void AddErrorsFromResult(IdentityResult result)
{
foreach (IdentityError error in result.Errors)
{
ModelState.AddModelError("", error.Description);
}
}
public async Task<IActionResult> Edit(string id)
{
IdentityRole role = await _roleManager.FindByIdAsync(id);
List<BlogMember> members = new List<BlogMember>();
List<BlogMember> nonMembers = new List<BlogMember>();
foreach (BlogMember user in _userManager.Users)
{
var list = await _userManager.IsInRoleAsync(user, role.Name)
? members : nonMembers;
list.Add(user);
}
return View(new RoleEditModel
{
Role = role,
Members = members,
NonMembers = nonMembers
});
}
[HttpPost]
public async Task<IActionResult> Edit(RoleModificationModel model)
{
IdentityResult result;
if (ModelState.IsValid)
{
foreach (string userId in model.IdsToAdd ?? new string[] { })
{
BlogMember user = await _userManager.FindByIdAsync(userId);
if (user != null)
{
result = await _userManager.AddToRoleAsync(user,
model.RoleName);
if (!result.Succeeded)
{
AddErrorsFromResult(result);
}
}
}
foreach (string userId in model.IdsToDelete ?? new string[] { })
{
BlogMember user = await _userManager.FindByIdAsync(userId);
if (user != null)
{
result = await _userManager.RemoveFromRoleAsync(user,
model.RoleName);
if (!result.Succeeded)
{
AddErrorsFromResult(result);
}
}
}
}
if (ModelState.IsValid)
{
return RedirectToAction(nameof(Index));
}
else
{
return await Edit(model.RoleId);
}
}
}
} |
namespace afVmPowerMonitor
{
public class VMResults
{
public string id;
public string location;
public string name;
public Properties properties = new Properties();
public string type;
public class HardwareProfile
{
public string vmSize;
}
public class Properties
{
public HardwareProfile hardwareProfile = new HardwareProfile();
public string provisioningState;
public string vmId;
}
}
} |
@using NavigationMenusMvc
@using NavigationMenusMvc.Models
@using KenticoCloud.Delivery
@using NavigationMenusMvc.Helpers.Extensions
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
|
namespace SpookyDistance.CommonLispReflection.TestLibrary
{
public struct Struct2
{
public Struct2(int i)
{
}
}
}
|
namespace ChainPay.Test
{
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
[TestClass]
public class DateTests
{
[TestMethod]
public void TestExpiryMillis()
{
var date = new DateTime(2019, 01, 01, 0, 0, 0, DateTimeKind.Utc);
var expiryMillis = ChainPay.MillisFromEpoch(date).ToString();
var resultDate = ChainPay.ExpiryMillisToDate(expiryMillis);
Assert.AreEqual(date, resultDate);
}
}
}
|
using SeguraChain_Lib.Blockchain.Block.Object.Structure;
namespace SeguraChain_Lib.Instance.Node.Network.Services.P2P.Sync.Packet.SubPacket.Response
{
public class ClassPeerPacketSendBlockData
{
public ClassBlockObject BlockData;
public long PacketTimestamp;
public string PacketNumericHash;
public string PacketNumericSignature;
}
} |
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Net;
using System.Text;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//Create a simple ASP.Net page with table inside
if (!Page.IsPostBack)
{
//Create a simple ASP.Net table
Table table = new Table();
table.Style.Add("border-collapse", "collapse");
TableRow row = null;
TableCell cell = null;
int rows = 5;
int cells = 5;
for (int x = 0; x < rows; x++)
{
row = new TableRow();
for (int y = 0; y < cells; y++)
{
cell = new TableCell();
cell.Width = Unit.Pixel(100);
cell.BorderColor = System.Drawing.ColorTranslator.FromHtml("darkgreen");
cell.BorderWidth = Unit.Pixel(2);
cell.Font.Name = "Helvetica";
cell.Font.Size = FontUnit.Point(10);
cell.HorizontalAlign = HorizontalAlign.Center;
cell.Text = "Row " + ((int)(x + 1)).ToString() + ", Cell " + ((int)(y + 1)).ToString();
row.Cells.Add(cell);
}
table.Rows.Add(row);
}
//Add table to page
Panel1.Controls.Add(table);
}
}
//Get HTML from ASPX
protected override void Render(HtmlTextWriter writer)
{
// setup a TextWriter to capture the markup
TextWriter tw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(tw);
// render the markup into our surrogate TextWriter
base.Render(htw);
// get the captured markup as a string
string currentPage = tw.ToString();
//Save HTML code to temporary file
if (!Page.IsPostBack)
File.WriteAllText(Path.Combine(Server.MapPath("Temp"), "temp.htm"), currentPage, Encoding.UTF8);
// render the markup into the output stream verbatim
writer.Write(currentPage);
}
protected void Button1_Click(object sender, EventArgs e)
{
//Get HTML from temporary file which we've created in the overridden method Render()
string html = File.ReadAllText(Path.Combine(Server.MapPath("Temp"), "temp.htm"), Encoding.UTF8);
string url = System.Web.HttpContext.Current.Request.Url.AbsoluteUri;
if (html.Length > 0)
{
SautinSoft.PdfMetamorphosis p = new SautinSoft.PdfMetamorphosis();
//After purchasing the license, please insert your serial number here to activate the component
//p.Serial = "XXXXXXXXXXX";
p.HtmlSettings.BaseUrl = url;
byte[] pdf = p.HtmlToPdfConvertStringToByte(html);
//show PDF
if (pdf != null)
{
Response.Buffer = true;
Response.Clear();
Response.ContentType = "application/PDF";
Response.AddHeader("content-disposition", "attachment; filename=Result.pdf");
Response.BinaryWrite(pdf);
Response.Flush();
Response.End();
}
}
}
}
|
using System;
namespace funcao_aula2
{
public class ProgV2
{
public static void Executar()
{
int max = 0;
Console.WriteLine("Qual o max dos numeros?");
max = int.Parse(Console.ReadLine());
var nuns = new int[max];
for (int cont = 0; cont < max; cont++)
{
Console.WriteLine("Digite o valor do " + (cont + 1) + "º numero");
nuns[cont] = int.Parse(Console.ReadLine());
}
EntradaSaida.ImprimeOResultado(ProgV2.Soma(max, nuns));
}
public static int Soma(int max, int[] numeros)
{
int soma = 0;
for (int cont = 0; cont < max; cont++)
{
soma = soma + numeros[cont];
}
return soma;
}
}
}
|
using System;
using Codemasters.F1_2020;
namespace ApexVisual.F1_2020.Analysis
{
public class Lap
{
public byte LapNumber {get; set;}
public TelemetrySnapshot[] Corners {get; set;}
public float Sector1Time {get; set;}
public float Sector2Time {get; set;}
public float Sector3Time {get; set;}
public bool LapInvalid {get; set;}
public float FuelConsumed {get; set;}
public float PercentOnThrottle {get; set;}
public float PercentOnBrake {get; set;}
public float PercentCoasting {get; set;}
public float PercentThrottleBrakeOverlap {get; set;}
public float PercentOnMaxThrottle {get; set;}
public float PercentOnMaxBrake {get; set;}
public float ErsDeployed {get; set;}
public float ErsHarvested {get; set;}
public int GearChanges {get; set;}
public ushort TopSpeedKph {get; set;}
public TyreCompound EquippedTyreCompound {get; set;}
//Incremental Tyre Wear
public WheelDataArray IncrementalTyreWear {get; set;}
//Beginning tyre wear (snapshot)
public WheelDataArray BeginningTyreWear {get; set;}
public float LapTime()
{
return Sector1Time + Sector2Time + Sector3Time;
}
}
} |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
namespace Tests.Expressions
{
partial class ExpressionCatalog
{
private static IEnumerable<Expression> MemberAccess()
{
var instance = Expression.Constant(new Members());
foreach (var member in typeof(Members).GetMembers().Where(m => m is FieldInfo || m is PropertyInfo))
{
var isStatic = false;
if (member is FieldInfo)
{
var field = (FieldInfo)member;
isStatic = field.IsStatic || field.IsLiteral;
}
else
{
var property = (PropertyInfo)member;
isStatic = property.GetGetMethod().IsStatic;
}
if (isStatic)
{
yield return Expression.MakeMemberAccess(null, member);
}
else
{
yield return Expression.MakeMemberAccess(instance, member);
yield return Expression.MakeMemberAccess(Expression.Default(typeof(Members)), member);
}
}
}
}
class Members
{
public static readonly int A = 42;
public const int B = 43;
public static int C
{
get { return 44; }
}
public static readonly string D = "bar";
public const string E = "foo";
public static string F
{
get { return "qux"; }
}
public int G = 45;
public int H
{
get { return 46; }
}
public string I = "baz";
public string J
{
get { return "foz"; }
}
}
} |
using System;
using System.Linq;
using System.Collections.Generic;
using UnityEngine;
namespace PubNubAPI
{
public class HistoryBuilder
{
private readonly HistoryRequestBuilder pubBuilder;
public HistoryBuilder(PubNubUnity pn){
pubBuilder = new HistoryRequestBuilder(pn);
}
public HistoryBuilder IncludeTimetoken(bool includeTimetokenForHistory){
pubBuilder.IncludeTimetoken(includeTimetokenForHistory);
return this;
}
public HistoryBuilder Reverse(bool reverseHistory){
pubBuilder.Reverse(reverseHistory);
return this;
}
public HistoryBuilder Start(long startTime){
pubBuilder.Start(startTime);
return this;
}
public HistoryBuilder End(long endTime){
pubBuilder.End(endTime);
return this;
}
public HistoryBuilder Channel(string channelName){
pubBuilder.Channel(channelName);
return this;
}
public HistoryBuilder Count(ushort historyCount){
pubBuilder.Count(historyCount);
return this;
}
public HistoryBuilder QueryParam(Dictionary<string, string> queryParam){
pubBuilder.QueryParam(queryParam);
return this;
}
public void Async(Action<PNHistoryResult, PNStatus> callback)
{
pubBuilder.Async(callback);
}
}
} |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//using UnityEngine.AI;
public class Enemy_NavePursue : MonoBehaviour {
private Enemy_Master enemyMaster;
private UnityEngine.AI.NavMeshAgent myNavMesh;
private float checkRate;
private float nextCheck;
private AudioSource audio;
void Start(){
// audio = GetComponent<AudioSource>();
}
// Use this for initialization
void SetIntiailReferance () {
enemyMaster = GetComponent<Enemy_Master>();
if (GetComponent<UnityEngine.AI.NavMeshAgent>() != null)
{
myNavMesh = GetComponent<UnityEngine.AI.NavMeshAgent>();
}
checkRate = UnityEngine.Random.Range(0.1f, 0.2f);
}
private void OnEnable()
{
SetIntiailReferance();
enemyMaster.EventEnemyDie += DisableThis;
}
private void OnDisable()
{
enemyMaster.EventEnemyDie -= DisableThis;
}
private void DisableThis()
{
if (myNavMesh != null)
{
myNavMesh.enabled = false;
}
this.enabled = false;
}
// Update is called once per frame
void Update () {
if (Time.time > nextCheck)
{
nextCheck = Time.time + checkRate;
}
TrytoCheckTarget();
}
private void TrytoCheckTarget()
{
if(enemyMaster.myTarget!=null&&
myNavMesh!=null
&&!enemyMaster.isNavPuse)
{
print("enamy walk");
myNavMesh.SetDestination(enemyMaster.myTarget.position);
}
if (myNavMesh.remainingDistance > myNavMesh.stoppingDistance)
{
enemyMaster.CallEventEnemyWalking();
print("Is On Route");
// audio.Play ();
enemyMaster.isOnRoute = true;
}
}
}
|
namespace Jade.Music
{
partial class JWave
{
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
/// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region 组件设计器生成的代码
/// <summary>
/// 设计器支持所需的方法 - 不要
/// 使用代码编辑器修改此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.waterTime = new System.Windows.Forms.Timer(this.components);
this.trAoto = new System.Windows.Forms.Timer(this.components);
this.SuspendLayout();
//
// waterTime
//
this.waterTime.Interval = 15;
this.waterTime.Tick += new System.EventHandler(this.waterTime_Tick);
//
// trAoto
//
this.trAoto.Enabled = true;
this.trAoto.Interval = 500;
this.trAoto.Tick += new System.EventHandler(this.trAoto_Tick);
//
// JWave
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.Transparent;
this.Name = "JWave";
this.Size = new System.Drawing.Size(130, 130);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Timer waterTime;
private System.Windows.Forms.Timer trAoto;
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class UI_CardLoader : MonoBehaviour {
public static GameObject [] slots = new GameObject[3];
GameObject[] cards = new GameObject[3];
public int loadTime = 3;
bool isLoading = false;
public bool blankFound;
GameObject drawnCard;
public Text reloadCounter;
RectTransform rectTransform;
public GameObject blankPrefab;
public List <GameObject> deck = new List<GameObject>();
public List <GameObject> hand = new List<GameObject>();
public List <GameObject> pile = new List<GameObject>();
public List <GameObject> equipped = new List<GameObject>();
public List <GameObject> searchableDeck = new List<GameObject> ();
public List <GameObject> searchables = new List<GameObject> ();
public List <GameObject> tempDeck = new List <GameObject> ();
void Start(){
for (int i = 0; i < slots.Length; i++) {
int n = i + 1;
string g = "Card Slot " + n.ToString ();
slots [i] = GameObject.Find (g);
}
InitializeDeck (deck, tempDeck);
InitializeDeck (searchableDeck, searchables);
}
void Update(){
if (tempDeck.Count <= 0) {
// LoadDeck ();
ReloadDeck();
}
reloadCounter.text = tempDeck.Count.ToString ();
}
public void DrawNewCards(){
if (!isLoading) {
StartCoroutine ("LoadCards");
} else {
Debug.Log ("Still Loading...");
//Insert else code
}
}
IEnumerator LoadCards(){
for (int i = 0; i < slots.Length; i++) {
Card card = slots [i].GetComponentInChildren<Card> ();
if (card != null) {
if (card.mySlotState == Card.SlotState.CARD_SLOT) {
DeactivateCard (card.gameObject, true);
}
}
}
Debug.Log ("Loading");
isLoading = true;
//Insert Loading code
yield return new WaitForSeconds (loadTime);
isLoading = false;
if (tempDeck.Count >= slots.Length) {
for (int i = 0; i < slots.Length; i++) {
int num = Random.Range (0, tempDeck.Count - 1);
drawnCard = tempDeck [num];
hand.Add (drawnCard);
tempDeck.Remove (drawnCard);
// cards [i] = Instantiate(drawnCard,slots [i].transform.position,Quaternion.identity) as GameObject;
cards [i] = drawnCard;
rectTransform = cards [i].GetComponent<RectTransform> ();
UtilScript.AlignRectTransformToParent (rectTransform);
cards [i].transform.SetParent (slots [i].transform, false);
cards [i].SetActive (true);
}
} else {
// print ("Not enough cards in Deck");
for (int i = 0; i < tempDeck.Count + 1; i++) {
int num = Random.Range (0, tempDeck.Count - 1);
drawnCard = tempDeck [num];
hand.Add (drawnCard);
tempDeck.Remove (drawnCard);
cards [i] = drawnCard;
RectTransform rectTransform = cards [i].GetComponent<RectTransform> ();
UtilScript.AlignRectTransformToParent (rectTransform);
cards [i].transform.SetParent (slots [i].transform, false);
cards [i].SetActive (true);
}
ReloadDeck ();
}
Debug.Log ("Loaded");
//Insert New cards code
}
void ReloadDeck(){
tempDeck.AddRange (pile);
pile.Clear ();
StatCounter.IncrementTotalDeckReload ();
AddBlankToDeck ();
//Fire Spread code - move to another script if necessary
GameObject[] fires = GameObject.FindGameObjectsWithTag ("Fire");
for (int i = 0; i < fires.Length; i++) {
fires [i].GetComponent<FireController> ().SpreadWarning ();
}
}
public void AddtoCarry(GameObject card){
equipped.Add(card);
hand.Remove (card);
}
public void DeactivateCard(GameObject card, bool discarded){
if (hand.Contains (card)) {
hand.Remove (card);
}
if (equipped.Contains (card)) {
equipped.Remove (card);
}
card.SetActive (false);
card.transform.position = transform.position;
card.transform.SetParent (transform);
if (discarded) {
pile.Add (card);
}
}
public void CheckBlankCard( ){
for (int i = 0; i < slots.Length; i++) {
Card card = slots [i].GetComponentInChildren<Card> ();
if (card != null) {
if (card.myCardType == Card.CardType.BLANK_CARD) {
blankFound = true;
break;
} else {
blankFound = false;
}
}
}
}
public void ReplaceBlankCard(){
for (int i = 0; i < slots.Length; i++) {
Card card = slots [i].GetComponentInChildren<Card> ();
if (card != null) {
if (card.myCardType == Card.CardType.BLANK_CARD) {
int rnd = Random.Range (0, searchables.Count);
GameObject newCard = searchables [rnd];
RectTransform rectTransform = newCard.GetComponent<RectTransform> ();
UtilScript.AlignRectTransformToParent (rectTransform);
newCard.transform.SetParent (slots [i].transform, false);
newCard.SetActive (true);
hand.Add (newCard);
searchables.Remove(searchables[rnd]);
DeactivateCard (card.gameObject, false);
break;
} else {
}
}
}
}
void InitializeDeck(List<GameObject> origin, List<GameObject> target ){
for (int i = 0; i < origin.Count; i++) {
GameObject deckCard = Instantiate (origin[i], transform.position, Quaternion.identity);
deckCard.transform.SetParent (transform);
deckCard.SetActive (false);
target.Add (deckCard);
}
}
void AddBlankToDeck(){
GameObject blank = Instantiate (blankPrefab, transform.position, Quaternion.identity);
blank.transform.SetParent (transform);
blank.SetActive (false);
tempDeck.Add (blank);
}
}
|
using System;
using System.Threading.Tasks;
using IdentityServer.Models;
using IdentityServerPlus.Plugin.Base.Interfaces;
using Microsoft.AspNetCore.Authentication;
namespace IdentityServerPlus.Plugin.Base.Structures
{
public abstract class AuthenticationProvider : IAuthenticationProvider
{
public string FriendlyName { get; set; }
public string Scheme { get; set; }
public string Name => FriendlyName + " login provider";
public abstract string Description { get; }
protected AuthenticationProvider(string friendlyName, string scheme)
{
this.FriendlyName = friendlyName;
this.Scheme = scheme;
}
public abstract AuthenticationBuilder Build(AuthenticationBuilder builder);
public abstract string GetProviderId(AuthenticateResult authResult);
public abstract ApplicationUser ProvisionUser(AuthenticateResult result);
public virtual Task UpdateUserAsync(ApplicationUser user, AuthenticateResult result)
{
return Task.CompletedTask;
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
/// <summary>
/// 作者:刘泽华
/// 时间:2018年5月29日11点29分
/// </summary>
namespace KilyCore.EntityFrameWork
{
public interface IKilyContext
{
}
}
|
/*
Logger.cs
Handles printing information to files.
***
04/03/2018
ISTE 330.02 - Group 16
Ian Effendi
Jacob Toporoff
*/
// Using statements.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace Services
{
/// <summary>
/// Static class that handles printing custom messages to a file.
/// </summary>
public class Logger
{
// General logger instance.
/// <summary>
/// Static, singleton instance of a Logger.
/// </summary>
private static Logger instance = null;
/// <summary>
/// Creates a new logger and assigns it as the singleton instance.
/// </summary>
/// <returns></returns>
private static Logger CreateInstance()
{
if(instance == null)
{
instance = new Logger();
}
return instance;
}
/// <summary>
/// Grants access to singleton instance of a general Logger for most printing needs.
/// </summary>
public static Logger Instance
{
get { return (instance == null) ? CreateInstance() : instance; }
}
// Field(s).
/// <summary>
/// Filename to print text information to.
/// </summary>
private string filename = "log";
/// <summary>
/// Filepath to print text file in.
/// </summary>
private string filepath = "";
/// <summary>
/// Extension to append.
/// </summary>
private string extension = "txt";
// Properties.
/// <summary>
/// (Read-only) Returns the formatted filepath of the logger.
/// </summary>
public string Filepath
{
get { return filepath + filename + "." + extension; }
}
// Constructor(s).
/// <summary>
/// Logger object writes log information to a set file.
/// </summary>
/// <param name="_filepath">Filepath to store file.</param>
/// <param name="_filename">Filename to assign to file.</param>
/// <param name="_ext">Extension to save file under.</param>
public Logger(string _filepath = "", string _filename = "log", string _ext = "txt")
{
this.filename = _filename;
this.filepath = _filepath;
this.extension = _ext;
}
/// <summary>
/// Clear the text file associated with this logger of all text.
/// </summary>
/// <returns>Returns reference to self.</returns>
public Logger Clear()
{
if (File.Exists(this.Filepath))
{
File.WriteAllText(this.Filepath, String.Empty);
}
return this;
}
/// <summary>
/// Write a line in the text file.
/// </summary>
/// <param name="message">Message to print.</param>
/// <returns>Returns reference to this logger.</returns>
public Logger Write(string message)
{
string content = message;
string[] lines = content.Split('\n');
using (StreamWriter write = File.AppendText(this.Filepath))
{
foreach (string text in lines)
{
if (text.Length > 0)
{
write.WriteLine(text);
}
}
}
return this;
}
/// <summary>
/// Write messages to this log's text file. If newline is true, each line is placed on its own line.
/// </summary>
/// <param name="messages">Messages to print.</param>
/// <param name="newline">Newline separation between lines.</param>
/// <returns>Returns reference to this logger.</returns>
public Logger Write(List<string> messages, bool newline = true)
{
if (messages.Count > 0)
{
string text = "";
foreach (string message in messages)
{
if (newline)
{
this.Write(message);
continue;
}
else
{
text += " " + message;
}
}
if(!newline) { return this.Write(text); }
}
return this;
}
}
}
|
using UnityEngine;
namespace ZMD
{
public class RaycastSource : MonoBehaviour
{
[SerializeField] Transform source;
[SerializeField] float range = 20f;
[SerializeField] RaycastHitEvent Hit;
[SerializeField] bool triggerOnUpdate = true;
void Update() { if (triggerOnUpdate) Trigger(); }
public void Trigger()
{
Ray ray = new Ray(source.position, source.forward);
Physics.Raycast(ray, out RaycastHit hit, range);
Hit.Invoke(hit);
}
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
public interface IGenX<T>
{
string m(T t);
}
public interface IGenY<T>
{
string m(T[] tArr);
}
struct Gen<T,U> : IGenX<T[]>, IGenY<U>
{
string IGenX<T[]>.m(T[] t)
{
return "IGenX.m";
}
string IGenY<U>.m(U[] tArr)
{
return "IGenY.m";
}
}
public class Test
{
public static int counter = 0;
public static bool result = true;
public static void Eval(bool exp)
{
counter++;
if (!exp)
{
result = exp;
Console.WriteLine("Test Failed at location: " + counter);
}
}
public static int Main()
{
Gen<int,int> GenIntInt = new Gen<int,int>();
Eval(((IGenX<int[]>)GenIntInt).m(null).Equals("IGenX.m"));
Eval(((IGenY<int>)GenIntInt).m(null).Equals("IGenY.m"));
Gen<int,string> GenIntString = new Gen<int,string>();
Eval(((IGenX<int[]>)GenIntString).m(null).Equals("IGenX.m"));
Eval(((IGenY<string>)GenIntString).m(null).Equals("IGenY.m"));
Gen<string,int> GenStringInt = new Gen<string,int>();
Eval(((IGenX<string[]>)GenStringInt).m(null).Equals("IGenX.m"));
Eval(((IGenY<int>)GenStringInt).m(null).Equals("IGenY.m"));
Gen<string,string> GenStringString = new Gen<string,string>();
Eval(((IGenX<string[]>)GenStringString).m(null).Equals("IGenX.m"));
Eval(((IGenY<string>)GenStringString).m(null).Equals("IGenY.m"));
if (result)
{
Console.WriteLine("Test Passed");
return 100;
}
else
{
Console.WriteLine("Test Failed");
return 1;
}
}
}
|
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Reductech.Sequence.Core.Abstractions;
namespace Reductech.Sequence.Connectors.Nuix.Tests;
public abstract partial class NuixStepTestBase<TStep, TOutput>
{
public record NuixDeserializeTest : DeserializeCase
{
/// <inheritdoc />
public NuixDeserializeTest(
string name,
string yaml,
TOutput expectedOutput,
IReadOnlyCollection<ExternalProcessAction> externalProcessActions,
params string[] expectedLoggedValues) : base(
name,
yaml,
expectedOutput,
expectedLoggedValues
)
{
ExternalProcessActions = externalProcessActions;
IgnoreFinalState = true;
}
/// <inheritdoc />
public NuixDeserializeTest(
string name,
string yaml,
Unit _,
IReadOnlyCollection<ExternalProcessAction> externalProcessActions,
params string[] expectedLoggedValues) : base(
name,
yaml,
_,
expectedLoggedValues
)
{
ExternalProcessActions = externalProcessActions;
IgnoreFinalState = true;
}
public IReadOnlyCollection<ExternalProcessAction> ExternalProcessActions { get; }
/// <inheritdoc />
public override async Task<StateMonad> GetStateMonad(
IExternalContext externalContext,
ILogger logger)
{
var externalProcessMock = new ExternalProcessMock(
1,
ExternalProcessActions.ToArray()
);
var newExternalContext = new ExternalContext(
externalProcessMock,
externalContext.RestClientFactory,
externalContext.Console,
externalContext.InjectedContexts
);
var baseMonad = await base.GetStateMonad(newExternalContext, logger);
return new StateMonad(
baseMonad.Logger,
baseMonad.StepFactoryStore,
newExternalContext,
baseMonad.SequenceMetadata
);
}
}
}
|
<li class="collection-item">
<div class="row">
<div class="col s6">
<a href="/Patient/Profile/DocumentDownload/@Model.Id" class="collections-title">@Model.File</a>
</div>
<div class="col s3">
<span class="task-cat red lighten-2">@Model.DoctorName</span>
</div>
<div class="col s3">
<span>@Model.CreatedOn</span>
</div>
</div>
</li>
|
using Avalonia.Controls;
using Newtonsoft.Json;
using OpenPersonalFinances.Models;
using OpenPersonalFinances.Services;
using System;
using System.Collections.Generic;
using System.Text;
namespace OpenPersonalFinances.ViewModels
{
public class NewAccountDialogViewModel : ViewModelBase
{
private Window _ParentWindow;
public string NewAccountName { get; set; } = "My Account";
public NewAccountDialogViewModel(Window parentWindow)
{
_ParentWindow = parentWindow;
}
public void NewAccountCommand()
{
var newAccount = new OPFAccount();
newAccount.Name = NewAccountName;
CurrentProjectService.ActiveProject.Accounts.Add(newAccount);
_ParentWindow.Close();
}
}
}
|
using java.lang;
using loon.action;
using loon.utils;
namespace loon.geom
{
public class RectBox : Shape , BoxSize, XYZW {
public static RectBox At(string v)
{
if (StringUtils.IsEmpty(v))
{
return new RectBox();
}
string[] result = StringUtils.Split(v, ',');
int len = result.Length;
if (len > 3)
{
try
{
float x = Float.ParseFloat(result[0].Trim());
float y = Float.ParseFloat(result[1].Trim());
float width = Float.ParseFloat(result[2].Trim());
float height = Float.ParseFloat(result[3].Trim());
return new RectBox(x, y, width, height);
}
catch (Exception)
{
}
}
return new RectBox();
}
public static RectBox At(int x, int y, int w, int h)
{
return new RectBox(x, y, w, h);
}
public static RectBox At(float x, float y, float w, float h)
{
return new RectBox(x, y, w, h);
}
public static RectBox FromActor(ActionBind bind)
{
return new RectBox(bind.GetX(), bind.GetY(), bind.GetWidth(), bind.GetHeight());
}
public static RectBox Inflate(RectBox src, int xScale, int yScale)
{
float destWidth = src.width + xScale;
float destHeight = src.height + yScale;
float destX = src.x - xScale / 2;
float destY = src.y - yScale / 2;
return new RectBox(destX, destY, destWidth, destHeight);
}
public static RectBox Intersect(RectBox src1, RectBox src2, RectBox dest)
{
if (dest == null)
{
dest = new RectBox();
}
float x1 = MathUtils.Max(src1.GetMinX(), src2.GetMinX());
float y1 = MathUtils.Max(src1.GetMinY(), src2.GetMinY());
float x2 = MathUtils.Min(src1.GetMaxX(), src2.GetMaxX());
float y2 = MathUtils.Min(src1.GetMaxY(), src2.GetMaxY());
dest.SetBounds(x1, y1, x2 - x1, y2 - y1);
return dest;
}
public static RectBox GetIntersection(RectBox a, RectBox b)
{
float a_x = a.GetX();
float a_r = a.GetRight();
float a_y = a.GetY();
float a_t = a.GetBottom();
float b_x = b.GetX();
float b_r = b.GetRight();
float b_y = b.GetY();
float b_t = b.GetBottom();
float i_x = MathUtils.Max(a_x, b_x);
float i_r = MathUtils.Min(a_r, b_r);
float i_y = MathUtils.Max(a_y, b_y);
float i_t = MathUtils.Min(a_t, b_t);
return i_x < i_r && i_y < i_t ? new RectBox(i_x, i_y, i_r - i_x, i_t - i_y) : null;
}
public static RectBox GetIntersection(RectBox a, RectBox b, RectBox result)
{
float a_x = a.GetX();
float a_r = a.GetRight();
float a_y = a.GetY();
float a_t = a.GetBottom();
float b_x = b.GetX();
float b_r = b.GetRight();
float b_y = b.GetY();
float b_t = b.GetBottom();
float i_x = MathUtils.Max(a_x, b_x);
float i_r = MathUtils.Min(a_r, b_r);
float i_y = MathUtils.Max(a_y, b_y);
float i_t = MathUtils.Min(a_t, b_t);
if (i_x < i_r && i_y < i_t)
{
result.SetBounds(i_x, i_y, i_r - i_x, i_t - i_y);
return result;
}
return null;
}
public int width;
public int height;
private Matrix4 _matrix;
public RectBox()
{
SetBounds(0, 0, 0, 0);
}
public RectBox(int width, int height)
{
SetBounds(0, 0, width, height);
}
public RectBox(int x, int y, int width, int height)
{
SetBounds(x, y, width, height);
}
public RectBox(float x, float y, float width, float height)
{
SetBounds(x, y, width, height);
}
public RectBox(double x, double y, double width, double height)
{
SetBounds(x, y, width, height);
}
public RectBox(RectBox rect)
{
SetBounds(rect.x, rect.y, rect.width, rect.height);
}
public RectBox OffSet(Vector2f offset)
{
this.x += offset.x;
this.y += offset.y;
return this;
}
public RectBox Offset(int offSetX, int offSetY)
{
this.x += offSetX;
this.y += offSetY;
return this;
}
public RectBox SetBoundsFromCenter(float centerX, float centerY, float cornerX, float cornerY)
{
float halfW = MathUtils.Abs(cornerX - centerX);
float halfH = MathUtils.Abs(cornerY - centerY);
SetBounds(centerX - halfW, centerY - halfH, halfW * 2.0, halfH * 2.0);
return this;
}
public RectBox SetBounds(RectBox rect)
{
SetBounds(rect.x, rect.y, rect.width, rect.height);
return this;
}
public RectBox SetBounds(double x, double y, double width, double height)
{
SetBounds((float)x, (float)y, (float)width, (float)height);
return this;
}
public RectBox SetBounds(float x, float y, float width, float height)
{
this.x = x;
this.y = y;
this.width = (int)width;
this.height = (int)height;
this.minX = x;
this.minY = y;
this.maxX = x + width;
this.maxY = y + height;
this.pointsDirty = true;
this.CheckPoints();
return this;
}
public RectBox Inflate(int horizontalValue, int verticalValue)
{
this.x -= horizontalValue;
this.y -= verticalValue;
this.width += horizontalValue * 2;
this.height += verticalValue * 2;
return this;
}
public RectBox SetLocation(RectBox r)
{
this.x = r.x;
this.y = r.y;
return this;
}
public RectBox SetLocation(Point r)
{
this.x = r.x;
this.y = r.y;
return this;
}
public RectBox SetLocation(int x, int y)
{
this.x = x;
this.y = y;
return this;
}
public RectBox Grow(float h, float v)
{
SetX(GetX() - h);
SetY(GetY() - v);
SetWidth(GetWidth() + (h * 2));
SetHeight(GetHeight() + (v * 2));
return this;
}
public RectBox ScaleGrow(float h, float v)
{
Grow(GetWidth() * (h - 1), GetHeight() * (v - 1));
return this;
}
public override void SetScale(float sx, float sy)
{
if (scaleX != sx || scaleY != sy)
{
SetSize(width * (scaleX = sx), height * (scaleY * sy));
}
}
public RectBox SetSize(float width, float height)
{
SetWidth(width);
SetHeight(height);
return this;
}
public bool Overlaps(RectBox rectangle)
{
return !(x > rectangle.x + rectangle.width || x + width < rectangle.x || y > rectangle.y + rectangle.height
|| y + height < rectangle.y);
}
public Matrix4 GetMatrix()
{
if (_matrix == null)
{
_matrix = new Matrix4();
}
return _matrix.SetToOrtho2D(this.x, this.y, this.width, this.height);
}
public int X()
{
return (int)x;
}
public int Y()
{
return (int)y;
}
public int Width()
{
return width;
}
public int Height()
{
return height;
}
public override float GetX()
{
return x;
}
public override void SetX(float x)
{
this.x = x;
}
public override float GetY()
{
return y;
}
public override void SetY(float y)
{
this.y = y;
}
public float GetZ()
{
return GetWidth();
}
public float GetW()
{
return GetHeight();
}
public RectBox Copy(RectBox other)
{
this.x = other.x;
this.y = other.y;
this.width = other.width;
this.height = other.height;
return this;
}
public override float GetMinX()
{
return GetX();
}
public override float GetMinY()
{
return GetY();
}
public override float GetMaxX()
{
return this.x + this.width;
}
public override float GetMaxY()
{
return this.y + this.height;
}
public float GetMiddleX()
{
return GetCenterX();
}
public float GetMiddleY()
{
return GetCenterY();
}
public override float GetCenterX()
{
return x + width / 2f;
}
public override float GetCenterY()
{
return y + height / 2f;
}
public float GetLeft()
{
return this.GetMinX();
}
public RectBox SetLeft(float value)
{
this.width += (int)(this.x - value);
this.x = value;
return this;
}
public float GetRight()
{
return GetMaxX();
}
public RectBox SetRight(float v)
{
this.width = (int)(v - this.x);
return this;
}
public float GetTop()
{
return GetMinY();
}
public RectBox SetTop(float value)
{
this.height += (int)(this.y - value);
this.y = value;
return this;
}
public float GetBottom()
{
return GetMaxY();
}
public RectBox SetBottom(float v)
{
this.height = (int)(v - this.y);
return this;
}
public int Left()
{
return this.X();
}
public int Right()
{
return (int)GetMaxX();
}
public int Top()
{
return this.Y();
}
public int Bottom()
{
return (int)GetMaxY();
}
public Vector2f TopLeft()
{
return new Vector2f(this.GetLeft(), this.GetTop());
}
public Vector2f BottomRight()
{
return new Vector2f(this.GetRight(), this.GetBottom());
}
public RectBox Normalize()
{
return Normalize(this);
}
public RectBox Normalize(RectBox r)
{
if (r.width < 0)
{
r.width = MathUtils.Abs(r.width);
r.x -= r.width;
}
if (r.height < 0)
{
r.height = MathUtils.Abs(r.height);
r.y -= r.height;
}
return this;
}
public float[] ToFloat()
{
return new float[] { x, y, width, height };
}
public RectBox GetRect()
{
return this;
}
public override float GetHeight()
{
return height;
}
public void SetHeight(float height)
{
this.height = (int)height;
}
public override float GetWidth()
{
return width;
}
public void SetWidth(float width)
{
this.width = (int)width;
}
public override bool Equals(object obj)
{
if (obj is RectBox rect)
{
return Equals(rect.x, rect.y, rect.width, rect.height);
}
else
{
return false;
}
}
public bool Equals(float x, float y, float width, float height)
{
return (this.x == x && this.y == y && this.width == width && this.height == height);
}
public int GetArea()
{
return width * height;
}
public override bool Contains(float x, float y)
{
return Contains(x, y, 0, 0);
}
public bool Contains(float x, float y, float width, float height)
{
return (x >= this.x && y >= this.y && ((x + width) <= (this.x + this.width))
&& ((y + height) <= (this.y + this.height)));
}
public bool Contains(RectBox rect)
{
return Contains(rect.x, rect.y, rect.width, rect.height);
}
public bool Contains(Circle circle)
{
float xmin = circle.x - circle.boundingCircleRadius;
float xmax = xmin + 2f * circle.boundingCircleRadius;
float ymin = circle.y - circle.boundingCircleRadius;
float ymax = ymin + 2f * circle.boundingCircleRadius;
return ((xmin > x && xmin < x + width) && (xmax > x && xmax < x + width))
&& ((ymin > y && ymin < y + height) && (ymax > y && ymax < y + height));
}
public bool Contains(Vector2f v)
{
return Contains(v.x, v.y);
}
public bool Contains(Point point)
{
if (this.x < point.x && this.x + this.width > point.x && this.y < point.y && this.y + this.height > point.y)
{
return true;
}
return false;
}
public bool Contains(PointF point)
{
if (this.x < point.x && this.x + this.width > point.x && this.y < point.y && this.y + this.height > point.y)
{
return true;
}
return false;
}
public bool Contains(PointI point)
{
if (this.x < point.x && this.x + this.width > point.x && this.y < point.y && this.y + this.height > point.y)
{
return true;
}
return false;
}
public bool Intersects(RectBox rect)
{
return Intersects(rect.x, rect.y, rect.width, rect.height);
}
public bool Intersects(float x, float y)
{
return Intersects(x, y, width, height);
}
public bool Intersects(float x, float y, float width, float height)
{
return x + width > this.x && x < this.x + this.width && y + height > this.y && y < this.y + this.height;
}
public RectBox Intersection(RectBox rect)
{
return Intersection(rect.x, rect.y, rect.width, rect.height);
}
public RectBox Intersection(float x, float y, float width, float height)
{
int x1 = (int)MathUtils.Max(this.x, x);
int y1 = (int)MathUtils.Max(this.y, y);
int x2 = (int)MathUtils.Min(this.x + this.width - 1, x + width - 1);
int y2 = (int)MathUtils.Min(this.y + this.height - 1, y + height - 1);
return SetBounds(x1, y1, MathUtils.Max(0, x2 - x1 + 1), MathUtils.Max(0, y2 - y1 + 1));
}
public bool Inside(int x, int y)
{
return (x >= this.x) && ((x - this.x) < this.width) && (y >= this.y) && ((y - this.y) < this.height);
}
public RectBox GetIntersection(RectBox rect)
{
int x1 = (int)MathUtils.Max(x, rect.x);
int x2 = (int)MathUtils.Min(x + width, rect.x + rect.width);
int y1 = (int)MathUtils.Max(y, rect.y);
int y2 = (int)MathUtils.Min(y + height, rect.y + rect.height);
return new RectBox(x1, y1, x2 - x1, y2 - y1);
}
public RectBox Union(RectBox rect)
{
return Union(rect.x, rect.y, rect.width, rect.height);
}
public RectBox Union(float x, float y, float width, float height)
{
int x1 = (int)MathUtils.Min(this.x, x);
int y1 = (int)MathUtils.Min(this.y, y);
int x2 = (int)MathUtils.Max(this.x + this.width - 1, x + width - 1);
int y2 = (int)MathUtils.Max(this.y + this.height - 1, y + height - 1);
SetBounds(x1, y1, x2 - x1 + 1, y2 - y1 + 1);
return this;
}
protected override void CreatePoints()
{
float useWidth = width;
float useHeight = height;
points = new float[8];
points[0] = x;
points[1] = y;
points[2] = x + useWidth;
points[3] = y;
points[4] = x + useWidth;
points[5] = y + useHeight;
points[6] = x;
points[7] = y + useHeight;
maxX = points[2];
maxY = points[5];
minX = points[0];
minY = points[1];
FindCenter();
CalculateRadius();
}
public override Shape Transform(Matrix3 transform)
{
CheckPoints();
Polygon resultPolygon = new Polygon();
float[] result = new float[points.Length];
transform.Transform(points, 0, result, 0, points.Length / 2);
resultPolygon.points = result;
resultPolygon.FindCenter();
resultPolygon.CheckPoints();
return resultPolygon;
}
public RectBox ModX(float xMod)
{
x += xMod;
return this;
}
public RectBox ModY(float yMod)
{
y += yMod;
return this;
}
public RectBox ModWidth(float w)
{
this.width += (int)w;
return this;
}
public RectBox ModHeight(float h)
{
this.height += (int)h;
return this;
}
public bool IntersectsLine( float x1, float y1, float x2, float y2)
{
return Contains(x1, y1) || Contains(x2, y2);
}
public bool Inside(float x, float y)
{
return (x >= this.x) && ((x - this.x) < this.width) && (y >= this.y) && ((y - this.y) < this.height);
}
public RectBox Cpy()
{
return new RectBox(this.x, this.y, this.width, this.height);
}
public RectBox CreateIntersection(RectBox rectBox)
{
RectBox dest = new RectBox();
dest.Intersection(rectBox);
Intersect(this, rectBox, dest);
return dest;
}
public float MaxX()
{
return X() + Width();
}
public float MaxY()
{
return Y() + Height();
}
public override bool IsEmpty()
{
return GetWidth() <= 0 || Height() <= 0;
}
public RectBox SetEmpty()
{
this.x = 0;
this.y = 0;
this.width = 0;
this.height = 0;
return this;
}
public RectBox Offset(Point point)
{
x += point.x;
y += point.y;
return this;
}
public RectBox Offset(PointF point)
{
x += point.x;
y += point.y;
return this;
}
public RectBox Offset(PointI point)
{
x += point.x;
y += point.y;
return this;
}
public RectBox Inc(RectBox view)
{
if (view == null)
{
return Cpy();
}
return new RectBox(x + view.x, y + view.y, width + view.width, height + view.height);
}
public RectBox Sub(RectBox view)
{
if (view == null)
{
return Cpy();
}
return new RectBox(x - view.x, y - view.y, width - view.width, height - view.height);
}
public RectBox Mul(RectBox view)
{
if (view == null)
{
return Cpy();
}
return new RectBox(x * view.x, y * view.y, width * view.width, height * view.height);
}
public RectBox Div(RectBox view)
{
if (view == null)
{
return Cpy();
}
return new RectBox(x / view.x, y / view.y, width / view.width, height / view.height);
}
public RectBox Inc(float v)
{
return new RectBox(x + v, y + v, width + v, height + v);
}
public RectBox Sub(float v)
{
return new RectBox(x - v, y - v, width - v, height - v);
}
public RectBox Mul(float v)
{
return new RectBox(x * v, y * v, width * v, height * v);
}
public RectBox Div(float v)
{
return new RectBox(x / v, y / v, width / v, height / v);
}
public RectBox Add(float px, float py)
{
float x1 = MathUtils.Min(x, px);
float x2 = MathUtils.Max(x + width, px);
float y1 = MathUtils.Min(y, py);
float y2 = MathUtils.Max(y + height, py);
SetBounds(x1, y1, x2 - x1, y2 - y1);
return this;
}
public RectBox Add(Vector2f v)
{
return Add(v.x, v.y);
}
public RectBox Add(RectBox r)
{
int tx2 = this.width;
int ty2 = this.height;
if ((tx2 | ty2) < 0)
{
SetBounds(r.x, r.y, r.width, r.height);
}
int rx2 = r.width;
int ry2 = r.height;
if ((rx2 | ry2) < 0)
{
return this;
}
float tx1 = this.x;
float ty1 = this.y;
tx2 += (int)tx1;
ty2 += (int)ty1;
float rx1 = r.x;
float ry1 = r.y;
rx2 += (int)rx1;
ry2 += (int)ry1;
if (tx1 > rx1)
{
tx1 = rx1;
}
if (ty1 > ry1)
{
ty1 = ry1;
}
if (tx2 < rx2)
{
tx2 = rx2;
}
if (ty2 < ry2)
{
ty2 = ry2;
}
tx2 -= (int)tx1;
ty2 -= (int)ty1;
if (tx2 > Integer.MAX_VALUE_JAVA)
{
tx2 = Integer.MAX_VALUE_JAVA;
}
if (ty2 > Integer.MAX_VALUE_JAVA)
{
ty2 = Integer.MAX_VALUE_JAVA;
}
SetBounds(tx1, ty1, tx2, ty2);
return this;
}
public float GetAspectRatio()
{
return (height == 0) ? MathUtils.NaN : (float)width / (float)height;
}
public float Area()
{
return this.width * this.height;
}
public float Perimeter()
{
return 2f * (this.width + this.height);
}
public RectBox Random()
{
this.x = MathUtils.Random(0f, LSystem.viewSize.GetWidth());
this.y = MathUtils.Random(0f, LSystem.viewSize.GetHeight());
this.width = MathUtils.Random(0, LSystem.viewSize.GetWidth());
this.height = MathUtils.Random(0, LSystem.viewSize.GetHeight());
return this;
}
public override int GetHashCode()
{
uint prime = 31;
uint result = 1;
result = prime * result + NumberUtils.FloatToIntBits(x);
result = prime * result + NumberUtils.FloatToIntBits(y);
result = prime * result + NumberUtils.FloatToIntBits(width);
result = prime * result + NumberUtils.FloatToIntBits(height);
return (int)result;
}
public override string ToString()
{
StringKeyValue builder = new StringKeyValue("RectBox");
builder.Kv("x", x).Comma().Kv("y", y).Comma().Kv("width", width).Comma().Kv("height", height).Comma()
.Kv("left", Left()).Comma().Kv("right", Right()).Comma().Kv("top", Top()).Comma()
.Kv("bottom", Bottom());
return builder.ToString();
}
}
}
|
/**
* Copyright 2015-2016 GetSocial B.V.
*
* 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 UnityEngine;
public abstract class DemoMenuSection : MonoBehaviour
{
protected GetSocialDemoController demoController;
protected DemoAppConsole _console;
private bool started = false;
protected abstract string GetTitle();
protected abstract void DrawSectionBody();
Vector2 _scrollPos;
protected virtual void Start()
{
started = true;
}
protected virtual void InitGuiElements()
{
}
protected virtual void GoBack()
{
demoController.PopMenuSection();
}
protected virtual bool IsBackButtonActive()
{
return true;
}
#region unity_methods
public virtual void Update()
{
HandleAndroidBackKey();
}
void HandleAndroidBackKey()
{
if(Application.platform == RuntimePlatform.Android && Input.GetKeyDown(KeyCode.Escape))
{
GoBack();
}
}
void OnGUI()
{
if (!started)
{
return;
}
_scrollPos = DemoGuiUtils.DrawScrollBodyWrapper(_scrollPos, DrawBody);
}
#endregion
public virtual void Initialize(GetSocialDemoController demoController, DemoAppConsole console)
{
this.demoController = demoController;
this._console = console;
InitGuiElements();
}
public ActionDialog Dialog()
{
return demoController.Dialog();
}
void DrawBody()
{
GUILayout.BeginVertical();
{
GUILayout.Space(30);
GUILayout.BeginHorizontal();
if(IsBackButtonActive())
{
DemoGuiUtils.DrawButton("< Back", GoBack, style: GSStyles.Button);
}
GUILayout.Label(GetTitle(), GSStyles.BigLabelText);
GUILayout.EndHorizontal();
GUILayout.Space(30);
DrawSectionBody();
}
GUILayout.EndVertical();
}
}
|
using UnityEngine;
using System.Collections;
public class GyroInput : MonoBehaviour
{
// Quaternion offset;
void OnEnable () {
// offset = transform.rotation * Quaternion.Inverse(GyroToUnity(Input.gyro.attitude));
}
void OnDisable () {
}
void Update () {
// this.transform.rotation = offset * GyroToUnity(Input.gyro.attitude);
this.transform.rotation *= Quaternion.Euler(-Input.gyro.rotationRate * 20f * Time.deltaTime);
}
private static Quaternion GyroToUnity(Quaternion q) {
return new Quaternion(q.x, q.y, -q.z, -q.w);
}
} |
using System;
using System.Diagnostics.Contracts;
using System.Windows;
using System.Windows.Markup;
namespace Nova.Bindings.Base
{
public abstract class NovaMarkUpExtension : MarkupExtension
{
private readonly PropertyPath _path;
protected NovaMarkUpExtension(PropertyPath path)
{
Contract.Requires<ArgumentNullException>(path != null, "The supplied path can't be null.");
Contract.Requires<ArgumentNullException>(path.Path != ".", "The supplied path can't '.'.");
_path = path;
}
protected PropertyPath Path
{
get { return _path; }
}
public override sealed object ProvideValue(IServiceProvider serviceProvider)
{
var target = (IProvideValueTarget) serviceProvider.GetService(typeof (IProvideValueTarget));
//The markup expression is evaluated when it is encountered by the XAML parser :
// in that case, when the template is parsed. But at this time,
// the control is not created yet, so the ProvideValue method can’t access it...
//When a markup extension is evaluated inside a template,
//the TargetObject is actually an instance of System.Windows.SharedDp, an internal WPF class.
//For the markup extension to be able to access its target,
//it has to be evaluated when the template is applied : we need to defer its evaluation until this time.
//It’s actually pretty simple, we just need to return the markup extension itself from ProvideValue:
//this way, it will be evaluated again when the actual target control is created.
// http://www.thomaslevesque.com/2009/08/23/wpf-markup-extensions-and-templates/
if (target == null || target.TargetObject.GetType().FullName == "System.Windows.SharedDp")
return this;
return ProvideValue(serviceProvider, target);
}
protected abstract object ProvideValue(IServiceProvider serviceProvider, IProvideValueTarget target);
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.