content stringlengths 23 1.05M |
|---|
namespace usingblazor.tips.Localization.Api;
public interface Localizer<T>
{
string this[string name] { get; }
string this[string name, params object[] arguments] { get; }
}
|
using System;
using System.Drawing;
namespace Screna
{
/// <summary>
/// Captures the Region specified by a Rectangle.
/// </summary>
public class RegionProvider : IImageProvider
{
Rectangle _region;
readonly ImagePool _imagePool;
readonly bool _includeCursor;
readonly Func<Point, Point> _transform;
/// <summary>
/// Creates a new instance of <see cref="RegionProvider"/>.
/// </summary>
public RegionProvider(Rectangle Region, bool IncludeCursor)
{
Region = Region.Even();
_region = Region;
_includeCursor = IncludeCursor;
_transform = P => new Point(P.X - _region.X, P.Y - _region.Y);
_imagePool = new ImagePool(Region.Width, Region.Height);
}
bool _outsideBounds;
public void UpdateLocation(Point P)
{
if (_region.Location == P)
return;
_region.Location = P;
_outsideBounds = !WindowProvider.DesktopRectangle.Contains(_region);
}
public IBitmapFrame Capture()
{
var bmp = _imagePool.Get();
try
{
using (var editor = bmp.GetEditor())
{
if (_outsideBounds)
editor.Graphics.Clear(Color.Transparent);
editor.Graphics.CopyFromScreen(_region.Location,
Point.Empty,
_region.Size,
CopyPixelOperation.SourceCopy);
if (_includeCursor)
MouseCursor.Draw(editor.Graphics, _transform);
}
return bmp;
}
catch
{
bmp.Dispose();
return RepeatFrame.Instance;
}
}
/// <summary>
/// Height of Captured image.
/// </summary>
public int Height => _region.Height;
/// <summary>
/// Width of Captured image.
/// </summary>
public int Width => _region.Width;
/// <summary>
/// Frees all resources used by this instance.
/// </summary>
public void Dispose()
{
_imagePool.Dispose();
}
}
}
|
using System.Threading.Tasks;
using Microsoft.ServiceBus.Messaging;
namespace DCT.ILR.ValidationServiceStateless.ServiceBus
{
public interface ITopicHelper
{
Task SendMessage(BrokeredMessage message);
}
} |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Collections;
namespace Rabbit_explosion_game
{
public class Program
{
static List<Rabbit> RabbitList;
static void Main(string[] args)
{
Console.WriteLine($"The number of rabbits is: {RabbitCounter(20)[20]}");
Process.Start("RABBIT EXPLOSION!!!!!!!!.csv");
}
/// <summary>
/// We created a rabbit counter
/// </summary>
/// <param name="seconds">How many seconds we want the counter to run</param>
/// <returns>The number of rabbits when we want the counter to end</returns>
public static ArrayList RabbitCounter(int maxTime)
{
int populationLimit = 100000;
ArrayList myRabbitArray = new ArrayList();
// Write header to CSV file
File.WriteAllText("RABBIT EXPLOSION!!!!!!!!.csv", "Time (seconds),Population");
RabbitList = new List<Rabbit>();
RabbitList.Add(new Rabbit());
RabbitList.Add(new Rabbit());
//Add the first population to the ArrayList
myRabbitArray.Add(RabbitList.Count);
int seconds = 0;
while (seconds <maxTime)
{
//Write time and population to CSV files
File.AppendAllText("RABBIT EXPLOSION!!!!!!!!.csv", $"\n{seconds},{RabbitList.Count}");
System.Threading.Thread.Sleep(10);
++seconds;
List<Rabbit> babyRabbits = new List<Rabbit>();
foreach (var item in RabbitList)
{
if(RabbitList.Count + babyRabbits.Count >= populationLimit)
{
break;
}
babyRabbits.Add(new Rabbit());
}
RabbitList.AddRange(babyRabbits);
Console.WriteLine("Breading rabbits");
myRabbitArray.Add(RabbitList.Count);
// Add new population size to arrayList
}
//Write final population to file
File.AppendAllText("RABBIT EXPLOSION!!!!!!!!.csv", $"\n{seconds},{RabbitList.Count}");
return myRabbitArray;
}
}
class Rabbit
{
}
}
|
using CmlLib.Core.Downloader;
using CmlLib.Core.Version;
using CmlLib.Utils;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
namespace CmlLib.Core.Files
{
public sealed class AssetChecker : IFileChecker
{
private string assetServer = MojangServer.ResourceDownload;
public string AssetServer
{
get => assetServer;
set
{
if (value.Last() == '/')
assetServer = value;
else
assetServer = value + "/";
}
}
public bool CheckHash { get; set; } = true;
public DownloadFile[]? CheckFiles(MinecraftPath path, MVersion version,
IProgress<DownloadFileChangedEventArgs>? progress)
{
return checkIndexAndAsset(path, version, progress);
}
public Task<DownloadFile[]?> CheckFilesTaskAsync(MinecraftPath path, MVersion version,
IProgress<DownloadFileChangedEventArgs>? progress)
{
return Task.Run(() => checkIndexAndAsset(path, version, progress));
}
private DownloadFile[]? checkIndexAndAsset(MinecraftPath path, MVersion version,
IProgress<DownloadFileChangedEventArgs>? progress)
{
checkIndex(path, version);
return CheckAssetFiles(path, version, progress);
}
private void checkIndex(MinecraftPath path, MVersion version)
{
if (string.IsNullOrEmpty(version.AssetId))
return;
string index = path.GetIndexFilePath(version.AssetId);
if (!string.IsNullOrEmpty(version.AssetUrl))
if (!IOUtil.CheckFileValidation(index, version.AssetHash, CheckHash))
{
var directoryName = Path.GetDirectoryName(index);
if (!string.IsNullOrEmpty(directoryName))
Directory.CreateDirectory(directoryName);
using (var wc = new WebClient())
{
wc.DownloadFile(version.AssetUrl, index);
}
}
}
[MethodTimer.Time]
public JObject? ReadIndex(MinecraftPath path, MVersion version)
{
if (string.IsNullOrEmpty(version.AssetId))
return null;
string indexPath = path.GetIndexFilePath(version.AssetId);
if (!File.Exists(indexPath)) return null;
string json = File.ReadAllText(indexPath);
var index = JObject.Parse(json); // 100ms
return index;
}
[MethodTimer.Time]
public DownloadFile[]? CheckAssetFiles(MinecraftPath path, MVersion version,
IProgress<DownloadFileChangedEventArgs>? progress)
{
JObject? index = ReadIndex(path, version);
if (index == null)
return null;
bool isVirtual = checkJsonTrue(index["virtual"]); // check virtual
bool mapResource = checkJsonTrue(index["map_to_resources"]); // check map_to_resources
var list = index["objects"] as JObject;
if (list == null)
return null;
var downloadRequiredFiles = new List<DownloadFile>(list.Count);
int total = list.Count;
int progressed = 0;
foreach (var item in list)
{
if (item.Value != null)
{
var f = checkAssetFile(item.Key, item.Value, path, version, isVirtual, mapResource);
if (f != null)
downloadRequiredFiles.Add(f);
}
progressed++;
if (progressed % 50 == 0) // prevent ui freezing
progress?.Report(
new DownloadFileChangedEventArgs(MFile.Resource, this, "", total, progressed));
}
return downloadRequiredFiles.Distinct().ToArray(); // 10ms
}
private DownloadFile? checkAssetFile(string key, JToken job, MinecraftPath path, MVersion version,
bool isVirtual, bool mapResource)
{
if (string.IsNullOrEmpty(version.AssetId))
return null;
// download hash resource
string? hash = job["hash"]?.ToString();
if (hash == null)
return null;
var hashName = hash.Substring(0, 2) + "/" + hash;
var hashPath = Path.Combine(path.GetAssetObjectPath(version.AssetId), hashName);
long size = 0;
string? sizeStr = job["size"]?.ToString();
if (!string.IsNullOrEmpty(sizeStr))
long.TryParse(sizeStr, out size);
var afterDownload = new List<Func<Task>>(1);
if (isVirtual)
{
var resPath = Path.Combine(path.GetAssetLegacyPath(version.AssetId), key);
afterDownload.Add(() => assetCopy(hashPath, resPath));
}
if (mapResource)
{
var desPath = Path.Combine(path.Resource, key);
afterDownload.Add(() => assetCopy(hashPath, desPath));
}
if (!IOUtil.CheckFileValidation(hashPath, hash, CheckHash))
{
string hashUrl = AssetServer + hashName;
return new DownloadFile(hashPath, hashUrl)
{
Type = MFile.Resource,
Name = key,
Size = size,
AfterDownload = afterDownload.ToArray()
};
}
else
{
foreach (var item in afterDownload)
{
item().GetAwaiter().GetResult();
}
return null;
}
}
private async Task assetCopy(string org, string des)
{
try
{
var orgFile = new FileInfo(org);
var desFile = new FileInfo(des);
if (!desFile.Exists || orgFile.Length != desFile.Length)
{
var directoryName = Path.GetDirectoryName(des);
if (!string.IsNullOrEmpty(directoryName))
Directory.CreateDirectory(directoryName);
await IOUtil.CopyFileAsync(org, des);
}
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
}
private bool checkJsonTrue(JToken? j)
{
string? str = j?.ToString().ToLowerInvariant();
return str is "true";
}
}
}
|
using System;
using System.Threading.Tasks;
using ConstellationMind.Infrastructure.Services.Commands.Constellations;
using ConstellationMind.Infrastructure.Services.Services.Domains.Interfaces;
using ConstellationMind.Shared.Handlers.Interfaces;
namespace ConstellationMind.Infrastructure.Services.Handlers.Constellations
{
public class CreateConstellationHandler : ICommandHandler<CreateConstellation>
{
private readonly IConstellationService _constellationService;
public CreateConstellationHandler(IConstellationService constellationService)
=> _constellationService = constellationService;
public async Task HandleAsync(CreateConstellation command)
=> await _constellationService.CreateAsync(command.Id = Guid.NewGuid(), command.Designation, command.Name);
}
}
|
using UnityEngine;
public class Obstacle : MonoBehaviour
{
public Vector3 startPos;
public Vector3 endPos;
public float cycleTime;
private float _currentTime;
private void Update()
{
Move();
}
private void Move()
{
_currentTime += Time.deltaTime / cycleTime;
transform.position = Vector3.Lerp(startPos, endPos, _currentTime);
if (transform.position != endPos) return;
var start = startPos;
startPos = endPos;
endPos = start;
_currentTime = 0;
}
[ContextMenu("SaveStartPos")]
private void SaveStartPos()
{
startPos = transform.position;
}
[ContextMenu("SaveEndPos")]
private void SaveEndPos()
{
endPos = transform.position;
}
}
|
using AutoMapper;
using Cafe.Core;
using Cafe.Core.TabContext.Commands;
using Cafe.Domain;
using Cafe.Domain.Entities;
using Cafe.Domain.Events;
using Cafe.Domain.Repositories;
using FluentValidation;
using MediatR;
using Optional;
using Optional.Async;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Cafe.Business.TabContext.CommandHandlers
{
public class RejectMenuItemsHandler : BaseTabHandler<RejectMenuItems>
{
public RejectMenuItemsHandler(
ITabRepository tabRepository,
IMenuItemsService menuItemsService,
IValidator<RejectMenuItems> validator,
IEventBus eventBus,
IMapper mapper)
: base(tabRepository, menuItemsService, validator, eventBus, mapper)
{
}
public override Task<Option<Unit, Error>> Handle(RejectMenuItems command) =>
TabShouldNotBeClosed(command.TabId).FlatMapAsync(tab =>
MenuItemsShouldExist(command.ItemNumbers).FlatMapAsync(items =>
TheItemsShouldHaveBeenOrdered(tab, command.ItemNumbers).MapAsync(__ =>
PublishEvents(tab.Id, tab.RejectMenuItems(items)))));
private Option<Unit, Error> TheItemsShouldHaveBeenOrdered(Tab tab, IList<int> itemNumbers)
{
var allTabItemNumbers = tab
.OutstandingMenuItems
.Concat(tab.ServedMenuItems)
.ToLookup(i => i.Number);
var unorderedItems = itemNumbers
.Where(n => !allTabItemNumbers.Contains(n))
.ToArray();
return unorderedItems
.SomeWhen(
items => items.Length == 0,
Error.Validation($"Attempted to reject menu items {string.Join(", ", unorderedItems)} which haven't been ordered."))
.Map(_ => Unit.Value);
}
}
}
|
using System.Reflection;
using System.Windows;
namespace goh_ui.Views
{
public partial class AboutWindow : ToolWindow
{
public AboutWindow()
{
DataContext = this;
Version = Assembly.GetExecutingAssembly().GetName().Version.ToString(2);
InitializeComponent();
}
/// <summary> Program version number. </summary>
public string Version { get; private set; }
/// <summary> Display a modal 'About' window. </summary>
/// <param name="owner">Window that will own this dialog.</param>
public static void Display(Window owner) => new AboutWindow() { Owner = owner }.ShowDialog();
}
}
|
using Milvaneth.Overlay;
using Milvaneth.Service;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows.Media.Imaging;
namespace Milvaneth.ViewModel
{
public class OverviewPresenterViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private ObservableCollection<OverviewPresenter> _bindingCollection;
public ObservableCollection<OverviewPresenter> BindingCollection
{
get => _bindingCollection;
set
{
_bindingCollection = value;
OnPropertyChanged(nameof(BindingCollection));
}
}
internal void LoadTestData()
{
var od = new List<OverviewData>
{
new OverviewData
{
Demand = 12,
ItemId = 1,
OpenListing = 22,
UpdateTime = DateTime.Now,
},
new OverviewData
{
Demand = 999,
ItemId = 2714,
OpenListing = 999,
UpdateTime = DateTime.Now.AddDays(-1),
},
new OverviewData
{
Demand = 12,
ItemId = 2210,
OpenListing = 22,
UpdateTime = DateTime.Now.AddDays(-998),
},
new OverviewData
{
Demand = 12,
ItemId = 26173,
OpenListing = 22,
UpdateTime = DateTime.Now.AddDays(-1000),
},
};
UpdateData(od);
}
public void UpdateData(List<OverviewData> od)
{
var t = new ObservableCollection<OverviewPresenter>();
if (od == null) return;
foreach (var i in od)
{
try
{
t.Add(new OverviewPresenter(i.ItemId, 0, i.OpenListing, 0, i.Demand, i.UpdateTime));
}
catch
{
// ignored
}
}
BindingCollection = t;
}
internal void OnPropertyChanged(string name)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
}
public class OverviewPresenter
{
public OverviewPresenter(int itemId, int price, int openListing, int sale, int demand, DateTime update)
{
ItemId = itemId;
ItemIcon = IconManagementService.GetIcon(itemId, false);
ItemName = DictionaryManagementService.GetName(itemId);
MinPrice = price;
OpenListing = openListing;
WeekSale = sale;
Demand = demand;
UpdateTime = $"{(int)Math.Min((DateTime.Now - update).TotalDays, 999)} 天前";
}
public int ItemId { get; set; }
public BitmapSource ItemIcon { get; set; }
public string ItemName { get; set; }
public int MinPrice { get; set; }
public int OpenListing { get; set; }
public int WeekSale { get; set; }
public int Demand { get; set; }
public string UpdateTime { get; set; }
}
}
|
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs.Script.Description;
using Xunit;
namespace Microsoft.Azure.WebJobs.Script.Tests.Description.Node.Compilation.Raw
{
public class RawJavascriptCompilationTests
{
[Fact]
public async Task Emit_ReturnsScriptPath()
{
string path = @"c:\root\test\index.js";
var compilation = new RawJavaScriptCompilation(path);
string result = await compilation.EmitAsync(CancellationToken.None);
Assert.Equal(path, result);
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using VirtualWork.Interfaces;
using VirtualWork.Interfaces.Attributes;
namespace VirtualWork.Persistence.Entities
{
public class Issue : Repeatable, IHaveIdentifier, IHaveTitle
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[ForeignKey(nameof(Parent))]
public int? ParentId { get; set; }
public virtual Issue Parent { get; set; }
[ForeignKey(nameof(Creator))]
[Required]
public int CreatorId { get; set; }
public virtual User Creator { get; set; }
[ForeignKey(nameof(Owner))]
public int? OwnerId { get; set; }
public virtual User Owner { get; set; }
public string Description { get; set; }
[StringLength(PersistenceConstants.MaxLengthOfStrings)]
[Required]
public string Title { get; set; }
[UtcDateTime]
public DateTime CreationDate { get; set; }
[UtcDateTime]
public DateTime DueDate { get; set; }
public TimeSpan Interval { get; set; }
public bool IsVerified { get; set; }
public bool IsBlocked { get; set; }
public int IssueType { get; set; }
public int IssueState { get; set; }
public int Priority { get; set; }
public virtual ICollection<User> Followers { get; set; }
public virtual ICollection<IssueConnection> IssueConnections { get; set; }
public virtual ICollection<IssueHistory> IssueHistoryEntries { get; set; }
public virtual ICollection<Comment> Comments { get; set; }
public override string ToString()
{
return $"{Id} - {Title}";
}
}
} |
#region Copyright
// Copyright 2014 Myrcon Pty. Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using System.Collections.Generic;
using System.Threading;
namespace Potato.Core.Shared {
/// <summary>
/// Handles throttling the stream of events to tick every 1 second, reducing
/// the requirement to cross the AppDomain several hundred times a second.
/// </summary>
/// <typeparam name="T">The type of item being streamed in</typeparam>
public class ThrottledStream<T> : IThrottledStream<T> {
public TimeSpan Interval { get; set; }
public bool Running { get; set; }
public Action<List<T>> FlushTo { get; set; }
/// <summary>
/// List of items waiting to be flushed
/// </summary>
public List<T> Items { get; set; }
/// <summary>
/// Lock used when accessing the items list.
/// </summary>
protected readonly Object ItemsLock = new Object();
/// <summary>
/// The timer controlling the interval ticking.
/// </summary>
public Timer IntervalTick { get; set; }
/// <summary>
/// Sets up the default values (1 second interval etc)
/// </summary>
public ThrottledStream() {
this.Interval = new TimeSpan(0, 0, 0, 1);
this.Items = new List<T>();
}
/// <summary>
/// Flushes any waitign items to the callback method
/// </summary>
public void Flush() {
lock (this.ItemsLock) {
if (this.Running == true && this.Items.Count > 0) {
if (this.FlushTo != null) {
this.FlushTo(new List<T>(this.Items));
}
}
this.Items.Clear();
}
}
public IThrottledStream<T> Call(T item) {
if (this.Running == true) {
lock (this.ItemsLock) {
this.Items.Add(item);
}
}
return this;
}
public IThrottledStream<T> Start() {
this.Running = true;
this.IntervalTick = new Timer(state => this.Flush(), null, this.Interval, this.Interval);
return this;
}
public IThrottledStream<T> Stop() {
this.Running = false;
this.FlushTo = null;
if (this.IntervalTick != null) {
this.IntervalTick.Dispose();
this.IntervalTick = null;
}
return this;
}
}
}
|
using Admin.Core.Service.Admin.Api;
using Xunit;
namespace Admin.Core.Tests.Service.Admin
{
public class ApiServiceTest : BaseTest
{
private readonly IApiService _apiService;
public ApiServiceTest()
{
_apiService = GetService<IApiService>();
}
[Fact]
public async void GetAsync()
{
var res = await _apiService.GetAsync(161227168079941);
Assert.True(res.Success);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace FirstViewerWebApp
{
/// <summary>
/// Model class required to deserialize the JSON response
/// </summary>
public class Models
{
public class AccessToken
{
public string token_type { get; set; }
public int expires_in { get; set; }
public string access_token { get; set; }
}
public class UploadBucket
{
public string bucket_key { get; set; }
public List<UploadItem> objects { get; set; }
}
public class UploadItem
{
public string id { get; set; }
public string key { get; set; }
public string sha_1 { get; set; }
public string size { get; set; }
public string contentType { get; set; }
public string location { get; set; }
}
}
} |
using Buffers;
using Base.Config;
using Newtonsoft.Json.Linq;
namespace Base.Data.Operations.Result
{
public sealed class SpaceTypeIdOperationResultData : OperationResultData
{
private SpaceTypeId value;
public override object Value => value;
public override ChainTypes.OperationResult Type => ChainTypes.OperationResult.SpaceTypeId;
public SpaceTypeIdOperationResultData()
{
value = SpaceTypeId.EMPTY;
}
public override ByteBuffer ToBufferRaw(ByteBuffer buffer = null)
{
return value.ToBuffer(buffer ?? new ByteBuffer(ByteBuffer.LITTLE_ENDING));
}
public override string Serialize() => value.Serialize();
public static SpaceTypeIdOperationResultData Create(JToken value)
{
return new SpaceTypeIdOperationResultData
{
value = value.ToObject<SpaceTypeId>()
};
}
}
} |
@model BalanceViewModel
@{
ViewData["Title"] = "Your balance";
}
<h2>Your current balance is: <strong>@Model.Balance.ToString("c")</strong></h2>
<form asp-action="Withdraw">
<div class="form-group">
<label >Amount to withdraw: </label>
<input type="number" min="1" step="1" class="form-control" name="amount" id="amount" required />
</div>
<button type="submit" class="btn btn-default">Withdraw funds</button>
</form> |
using System;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
namespace Models
{
public class Purchase
{
public int Id { get; set; }
public int Count { get; set; }
[InverseProperty("Purchases")]
public Product? FirstProduct { get; set; }
public int FirstProductId { get; set; }
public Product? SecondProduct { get; set; }
public int SecondProductId { get; set; }
public static void UpdatePurchases(Order order, ApplicationContext context)
{
var productLines = order.ProductLines;
var combinations = productLines
.SelectMany(productLine => productLines, Tuple.Create)
.Where(tuple => tuple.Item1.Id != tuple.Item2.Id);
foreach (var (productLine1, productLine2) in combinations)
{
var purchase = context
.Purchase
.FirstOrDefault(p => p.FirstProductId == productLine1.ProductId &&
p.SecondProductId == productLine2.ProductId);
if (purchase == null)
{
purchase = new Purchase
{
FirstProduct = productLine1.Product,
SecondProduct = productLine2.Product
};
context.Purchase.Add(purchase);
}
purchase.Count++;
context.SaveChanges();
}
}
}
} |
namespace Elders.Cronus.DomainModeling
{
public interface IProjection
{
}
} |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Ref<T>
{
private T[] m_ref;
public Ref(T _value)
{
m_ref = new T[] {_value};
}
// copy the value, so no modification on this value
public T asValue
{
get{return m_ref[0];}
set{m_ref[0] = value;}
}
public T[] asRef
{
get{return m_ref;}
}
}
public class Property
{
public enum Type
{
None,
Bool,
Float,
Key
}
public Type type = Type.None;
public object reference = null;
public string name = "";
public Property(string _name, Ref<bool> _ref)
{
reference = _ref;
type = Type.Bool;
name = _name;
}
public Property(string _name, Ref<float> _ref)
{
reference = _ref;
type = Type.Float;
name = _name;
}
public Property(string _name, Ref<KeyCode> _ref)
{
reference = _ref;
type = Type.Key;
name = _name;
}
public JSONProperty Serialize()
{
JSONProperty json = new JSONProperty { type = type };
switch (type)
{
case Type.Bool:
json.boolValue = (reference as Ref<bool>).asValue;
break;
case Type.Float:
json.floatValue = (reference as Ref<float>).asValue;
break;
case Type.Key:
json.keyValue = (int)(reference as Ref<KeyCode>).asValue;
break;
default:
break;
}
return json;
}
public void Deserialize(JSONProperty _json)
{
if(type == _json.type)
{
switch (type)
{
case Type.Bool:
(reference as Ref<bool>).asRef[0] = _json.boolValue;
break;
case Type.Float:
(reference as Ref<float>).asRef[0] = _json.floatValue;
break;
case Type.Key:
(reference as Ref<KeyCode>).asRef[0] = (KeyCode)_json.keyValue;
break;
default:
break;
}
}
}
}
[Serializable]
public struct JSONProperty
{
public Property.Type type;
public int keyValue;
public float floatValue;
public bool boolValue;
} |
// <auto-generated>
// DO NOT EDIT: generated by fsdgencsharp
// </auto-generated>
#nullable enable
using System;
using Facility.Core;
namespace EdgeCases
{
[System.CodeDom.Compiler.GeneratedCode("fsdgencsharp", "")]
internal static class EdgeCasesMethods
{
[Obsolete]
public static readonly IServiceMethodInfo OldMethod =
ServiceMethodInfo.Create<IEdgeCases, OldMethodRequestDto, OldMethodResponseDto>(
"oldMethod", "EdgeCases", x => x.OldMethodAsync);
}
}
|
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TransportSystem.Data.DbModels;
using TransportSystem.Data.Entities;
namespace TransportSystem.Data.Dbcontexts
{
public class ApplicationDbContext: IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{
}
public DbSet<Terminal> Terminals { get; set; }
public DbSet<DepartingTerminal> DepartingTerminal { get; set; }
public DbSet<Seat> Seats { get; set; }
public DbSet<Bus> Buses { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<Bus>().HasOne(b => b.Terminal)
.WithMany(b => b.Bus).OnDelete(DeleteBehavior.ClientCascade);
base.OnModelCreating(builder);
builder.Entity<Bus>().HasOne(b => b.DepartingTerminal)
.WithMany(b => b.Bus).OnDelete(DeleteBehavior.ClientCascade);
base.OnModelCreating(builder);
builder.Entity<Seat>().HasOne(b => b.Bus).WithMany(b => b.Seat).HasForeignKey("BusId");
}
}
}
|
using ProjectEye.Core.Enums;
using ProjectEye.Core.Models.Options;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Media;
using System.Windows;
using System.Windows.Resources;
namespace ProjectEye.Core.Service
{
/// <summary>
/// 音效Service
/// 处理休息结束提示音的加载和播放
/// </summary>
public class SoundService : IService
{
private readonly ConfigService config;
private Dictionary<SoundType, SoundPlayer> players;
public SoundService(ConfigService config)
{
players = new Dictionary<SoundType, SoundPlayer>();
//player.LoadCompleted += Player_LoadCompleted;
this.config = config;
}
private void Player_LoadCompleted(object sender, AsyncCompletedEventArgs e)
{
(sender as SoundPlayer).Dispose();
}
public void Init()
{
players.Add(SoundType.RestOverSound, new SoundPlayer());
players.Add(SoundType.TomatoWorkStartSound, new SoundPlayer());
players.Add(SoundType.TomatoWorkEndSound, new SoundPlayer());
players.Add(SoundType.Other, new SoundPlayer());
players[SoundType.RestOverSound].LoadCompleted += Player_LoadCompleted;
players[SoundType.TomatoWorkStartSound].LoadCompleted += Player_LoadCompleted;
players[SoundType.TomatoWorkEndSound].LoadCompleted += Player_LoadCompleted;
players[SoundType.Other].LoadCompleted += Player_LoadCompleted;
LoadConfigSound();
config.Changed += Config_Changed;
}
private void Config_Changed(object sender, EventArgs e)
{
var oldOptions = sender as OptionsModel;
if (oldOptions.General.SoundPath != config.options.General.SoundPath ||
oldOptions.Tomato.WorkStartSoundPath != config.options.Tomato.WorkStartSoundPath ||
oldOptions.Tomato.WorkEndSoundPath != config.options.Tomato.WorkEndSoundPath)
{
LoadConfigSound();
}
}
/// <summary>
/// 加载用户配置的音效
/// </summary>
private void LoadConfigSound()
{
string restOverPath = null, tomatoWorkStartPath = null, tomatoWorkEndPath = null;
if (!string.IsNullOrEmpty(config.options.General.SoundPath))
{
restOverPath = config.options.General.SoundPath;
}
if (!string.IsNullOrEmpty(config.options.Tomato.WorkStartSoundPath))
{
tomatoWorkStartPath = config.options.Tomato.WorkStartSoundPath;
}
if (!string.IsNullOrEmpty(config.options.Tomato.WorkEndSoundPath))
{
tomatoWorkEndPath = config.options.Tomato.WorkEndSoundPath;
}
//加载休息结束提示音
LoadSound(SoundType.RestOverSound, restOverPath);
//加载番茄时钟工作开始提示音
LoadSound(SoundType.TomatoWorkStartSound, tomatoWorkStartPath);
//加载番茄时钟工作结束提示音
LoadSound(SoundType.TomatoWorkEndSound, tomatoWorkEndPath);
}
#region 播放音效
/// <summary>
/// 播放音效,默认休息结束音效
/// </summary>
public bool Play(SoundType soundType = SoundType.RestOverSound)
{
var player = players[soundType];
if (player.IsLoadCompleted)
{
try
{
player.Play();
return true;
}
catch (Exception ec)
{
//播放声音失败,可能是加载了不支持或损坏的文件
LogHelper.Warning(ec.ToString());
//切换到默认音效
LoadSound();
}
}
return false;
}
#endregion
#region 加载指定音效文件
/// <summary>
/// 从路径加载音效
/// </summary>
/// <param name="file">路径</param>
/// <param name="resource">指示是否是系统资源</param>
/// <returns></returns>
public bool Load(SoundType soundType, string file, bool resource = true)
{
try
{
var player = players[soundType];
if (resource)
{
Uri soundUri = new Uri(file, UriKind.RelativeOrAbsolute);
StreamResourceInfo info = Application.GetResourceStream(soundUri);
player.Stream = info.Stream;
}
else
{
player.SoundLocation = file;
}
player.LoadAsync();
return true;
}
catch (Exception ec)
{
//Debug.WriteLine(ec);
LogHelper.Warning(ec.ToString());
return false;
}
}
/// <summary>
/// 加载指定音效文件
/// </summary>
/// <param name="path">音效文件路径,为空时加载默认音效</param>
public void LoadSound(SoundType soundType = SoundType.RestOverSound, string path = null)
{
bool isDefault = false;
if (string.IsNullOrEmpty(path))
{
isDefault = true;
path = "/ProjectEye;component/Resources/relentless.wav";
}
bool loadResult = Load(soundType, path, isDefault);
//加载音效失败
if (!loadResult && !isDefault)
{
//加载自定义音效失败
//尝试加载默认音效
LoadSound();
}
}
#endregion
#region 测试外部音效
/// <summary>
/// 测试外部音效
/// </summary>
/// <param name="file"></param>
/// <returns></returns>
public bool Test(string file)
{
if (Load(SoundType.Other, file, false))
{
if (Play(SoundType.Other))
{
return true;
}
}
return false;
}
#endregion
}
}
|
using UnityEngine;
using System.Collections;
public class PlayerControl : MonoBehaviour
{
[HideInInspector]
public bool jump = false;
public int maxJump;
private Animator mecanim;
private Uni2DAnimationPlayer ap;
private CharacterController2D controller;
public Vector2 initialVelocity = new Vector2(15f, 0);
public float gravity = -9.8f;
public float jumpForce = 1000f;
private int jumpLeft = 2;
private bool inJump;
private float jumpForceRemain;
private ScoreManager scoreManager;
private bool isSM;
private bool grounded;
private SceneManager sceneManager;
private DefaultDown defaultDown;
void Awake()
{
foreach (var render in GetComponentsInChildren<Renderer>())
{
render.sortingLayerName = "Character";
}
mecanim = GetComponentInChildren<Animator>();
controller = GetComponent<CharacterController2D>();
scoreManager = FindObjectOfType<ScoreManager>();
if (Application.isEditor && Camera.main == null)
{
Application.LoadLevel("title");
return;
}
var screenMin = Camera.main.ScreenToWorldPoint(new Vector3(0, 0));
transform.position = new Vector3(screenMin.x, transform.position.y);
defaultDown = FindObjectOfType<DefaultDown>();
defaultDown.playerControl = gameObject;
scoreManager.ActivateAchievements();
}
void Update()
{
var xSpeed = 0f;
if (initialVelocity.x > 0.2f)
{
var delta = initialVelocity * Time.deltaTime;
initialVelocity -= delta;
xSpeed = delta.x;
}
if (jumpLeft > 0)
{
jump = Input.GetButtonDown("Jump") || jump;
if (jump)
{
jumpLeft--;
scoreManager.jumpCountLabel.text = jumpLeft.ToString();
jumpForceRemain = jumpForce;
inJump = true;
}
}
mecanim.SetBool("jump", jump);
var vSpeed = 0f;
if (jumpForceRemain > 0f)
{
var jumpFrame = jumpForceRemain * Time.deltaTime;
jumpForceRemain -= jumpFrame;
vSpeed += jumpFrame;
inJump = true;
}
else
{
jumpForceRemain = 0f;
}
if (!controller.collisionState.below)
{
vSpeed += gravity * Time.deltaTime;
}
mecanim.SetFloat("vSpeed", vSpeed);
controller.move(new Vector3(xSpeed, vSpeed));
if (controller.collisionState.becameGroundedThisFrame)
{
mecanim.SetBool("thisframe", true);
jumpForceRemain = 0;
}
else
{
mecanim.SetBool("thisframe", false);
}
mecanim.SetBool("grounded", controller.collisionState.below);
jump = false;
}
public void OnDefaultDown()
{
Debug.Log("default down");
if (!(Time.timeScale > 0)) return;
if (jumpLeft > 0)
{
jump = true;
}
}
void OnTriggerEnter2D(Collider2D other)
{
Debug.Log("enter " + other.name);
if (other.CompareTag("platform"))
{
jumpLeft = maxJump;
scoreManager.jumpCountLabel.text = jumpLeft.ToString();
}
else if (other.CompareTag("Dead"))
{
defaultDown.SendMessage("GameOver");
scoreManager.SendMessage("GameOver");
}
}
}
|
namespace TeamBuilder.App.Commands
{
using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;
using TeamBuilder.App.Commands.Abstractions;
using TeamBuilder.App.Interfaces;
using TeamBuilder.Data;
using TeamBuilder.Models;
public class AcceptInviteCommand : Command
{
private const string Success = "User {0} joined team {1}!";
private const int ArgsExactLength = 1;
private const string TeamNotExistExceptionMessage = "Team {0} not found!";
private const string MissingInvitationExceptionMessage = "Invite from {0} is not found!";
private const string AlreadyMemberExceptionMessage = "You are already a member of team {0}! Invitation not found.";
public AcceptInviteCommand(string[] cmdArgs, IUserSession session)
: base(cmdArgs, session)
{
}
// <teamName>
public override string Execute(TeamBuilderContext context)
{
base.MustBeLoggedIn();
base.CmdArgsExactLengthValidation(ArgsExactLength);
var teamName = this.CmdArgs[0];
var team = this.GetTeam(context, teamName);
if (team.TeamUsers.Any(tu => tu.UserId == this.Session.User.Id))
{
throw new ArgumentException(string.Format(AlreadyMemberExceptionMessage, teamName));
}
var invitaition = context.Invitations
.SingleOrDefault(i => i.TeamId == team.Id && i.InvitedUserId == this.Session.User.Id);
// If user is not invited
if (invitaition == null || invitaition.IsActive == false)
{
throw new ArgumentException(string.Format(MissingInvitationExceptionMessage, teamName));
}
// Accept user in the team
invitaition.IsActive = false;
var mapping = new UserTeam();
mapping.User = this.Session.User;
mapping.Team = team;
context.UsersTeams.Add(mapping);
context.SaveChanges();
return string.Format(Success, this.Session.User.Username, teamName);
}
private Team GetTeam(TeamBuilderContext context, string teamName)
{
var team = context.Teams
.Include(t => t.TeamUsers)
.SingleOrDefault(t => t.Name.Equals(teamName, StringComparison.OrdinalIgnoreCase));
if (team == null)
{
throw new ArgumentException(string.Format(TeamNotExistExceptionMessage, teamName));
}
return team;
}
}
}
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using Serilog;
using System;
using System.Collections.Generic;
using System.IO;
namespace AttackSurfaceAnalyzer.Utils
{
public class DirectoryWalker
{
public static IEnumerable<FileSystemInfo> WalkDirectory(string root)
{
// Data structure to hold names of subfolders to be
// examined for files.
Stack<string> dirs = new Stack<string>();
if (!System.IO.Directory.Exists(root))
{
throw new ArgumentException("Unable to find [" + root + "]");
}
dirs.Push(root);
while (dirs.Count > 0)
{
string currentDir = dirs.Pop();
if (Filter.IsFiltered(Helpers.GetPlatformString(), "Scan", "File", "Path", currentDir))
{
continue;
}
string[] subDirs;
try
{
subDirs = System.IO.Directory.GetDirectories(currentDir);
}
// An UnauthorizedAccessException exception will be thrown if we do not have
// discovery permission on a folder or file. It may or may not be acceptable
// to ignore the exception and continue enumerating the remaining files and
// folders. It is also possible (but unlikely) that a DirectoryNotFound exception
// will be raised. This will happen if currentDir has been deleted by
// another application or thread after our call to Directory.Exists. The
// choice of which exceptions to catch depends entirely on the specific task
// you are intending to perform and also on how much you know with certainty
// about the systems on which this code will run.
catch (UnauthorizedAccessException)
{
Log.Debug("Unable to access: {0}", currentDir);
continue;
}
catch (System.IO.DirectoryNotFoundException)
{
Log.Debug("Directory not found: {0}", currentDir);
continue;
}
// @TODO: Improve this catch.
// This catches a case where we sometimes try to walk a file
// even though its not a directory on Mac OS.
// System.IO.Directory.GetDirectories is how we get the
// directories.
catch (Exception ex)
{
Log.Debug(ex.StackTrace);
Log.Debug(ex.GetType().ToString());
continue;
}
string[] files = null;
try
{
files = System.IO.Directory.GetFiles(currentDir);
}
catch (UnauthorizedAccessException e)
{
Log.Debug(e.Message);
continue;
}
catch (System.IO.DirectoryNotFoundException e)
{
Log.Debug(e.Message);
continue;
}
// Perform the required action on each file here.
// Modify this block to perform your required task.
foreach (string file in files)
{
FileInfo fileInfo = null;
try
{
fileInfo = new FileInfo(file);
}
catch (System.IO.FileNotFoundException e)
{
// If file was deleted by a separate application
// or thread since the call to TraverseTree()
// then just continue.
Log.Debug(e.Message);
continue;
}
if (Filter.IsFiltered(Helpers.GetPlatformString(), "Scan", "File", "Path", file))
{
continue;
}
yield return fileInfo;
}
// Push the subdirectories onto the stack for traversal.
// This could also be done before handing the files.
foreach (string str in subDirs)
{
DirectoryInfo fileInfo = null;
try
{
fileInfo = new DirectoryInfo(str);
// Skip symlinks to avoid loops
// Future improvement: log it as a symlink in the data
if (fileInfo.Attributes.HasFlag(FileAttributes.ReparsePoint))
{
continue;
}
}
catch (System.IO.DirectoryNotFoundException)
{
// If file was deleted by a separate application
// or thread since the call to TraverseTree()
// then just continue.
continue;
}
catch (Exception e)
{
Logger.DebugException(e);
Telemetry.TrackTrace(Microsoft.ApplicationInsights.DataContracts.SeverityLevel.Warning, e);
continue;
}
dirs.Push(str);
yield return fileInfo;
}
}
}
}
} |
// MailCellTemplate.cs
// (c) Copyright Christian Ruiz @_christian_ruiz
// MvvmCross - Controls Navigation Plugin is licensed using Microsoft Public License (Ms-PL)
//
using System;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using Cirrious.MvvmCross.Binding.BindingContext;
using Cirrious.MvvmCross.Binding.Touch.Views;
using MupApps.ControlsNavigation.Sample.Core.Model;
namespace MupApps.ControlsNavigation.Sample.IPhone
{
public partial class MailCellTemplate : MvxTableViewCell
{
public static readonly UINib Nib = UINib.FromName ("MailCellTemplate", NSBundle.MainBundle);
public static readonly NSString Key = new NSString ("MailCellTemplate");
public MailCellTemplate (IntPtr handle) : base (handle)
{
this.DelayBind(() => {
var set = this.CreateBindingSet<MailCellTemplate, Mail>();
set.Bind(FromLabel).To(mail => mail.From);
set.Bind(SubjectLabel).To(mail => mail.Subject);
set.Bind(DateLabel).To(mail => mail.Date);
set.Apply ();
});
}
public static MailCellTemplate Create ()
{
return (MailCellTemplate)Nib.Instantiate (null, null) [0];
}
}
}
|
using System;
using UnityEngine;
public class CreatureClass : MonoBehaviour {
public enum CreatureClassType {
Hellhound,
Imp
}
public enum CreatureSubClassType {
Melee
}
[SerializeField] private CreatureClassType _classType;
public CreatureClassType ClassType {
get { return _classType; }
set { _classType = value; }
}
[SerializeField] private CreatureSubClassType _subClassType;
public CreatureSubClassType SubClassType {
get { return _subClassType; }
set { _subClassType = value; }
}
public void UpdateClass(ClassTypeData classType) {
_classType = (CreatureClassType)classType.ClassType;
_subClassType = (CreatureSubClassType)classType.SubClassType;
}
}
|
namespace OliWorkshop.Deriv.ApiResponse
{
using System;
using System.Collections.Generic;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
/// <summary>
/// Server status alongside general settings like call limits, currencies information,
/// supported languages, etc.
/// </summary>
public partial class WebsiteStatusResponse
{
/// <summary>
/// Echo of the request made.
/// </summary>
[JsonProperty("echo_req")]
public Dictionary<string, object> EchoReq { get; set; }
/// <summary>
/// Action name of the request made.
/// </summary>
[JsonProperty("msg_type")]
public MsgType MsgType { get; set; }
/// <summary>
/// Optional field sent in request to map to response, present only when request contains
/// `req_id`.
/// </summary>
[JsonProperty("req_id", NullValueHandling = NullValueHandling.Ignore)]
public long? ReqId { get; set; }
/// <summary>
/// For subscription requests only.
/// </summary>
[JsonProperty("subscription", NullValueHandling = NullValueHandling.Ignore)]
public SubscriptionInformation Subscription { get; set; }
/// <summary>
/// Server status and other information regarding general settings
/// </summary>
[JsonProperty("website_status", NullValueHandling = NullValueHandling.Ignore)]
public WebsiteStatus WebsiteStatus { get; set; }
}
/// <summary>
/// Server status and other information regarding general settings
/// </summary>
public partial class WebsiteStatus
{
/// <summary>
/// Maximum number of API calls during specified period of time.
/// </summary>
[JsonProperty("api_call_limits")]
public ApiCallLimits ApiCallLimits { get; set; }
/// <summary>
/// Country code of connected IP
/// </summary>
[JsonProperty("clients_country", NullValueHandling = NullValueHandling.Ignore)]
public string ClientsCountry { get; set; }
/// <summary>
/// Provides minimum withdrawal for all crypto currency in USD
/// </summary>
[JsonProperty("crypto_config")]
public Dictionary<string, object> CryptoConfig { get; set; }
/// <summary>
/// Available currencies and their information
/// </summary>
[JsonProperty("currencies_config")]
public Dictionary<string, object> CurrenciesConfig { get; set; }
/// <summary>
/// Text for site status banner, contains problem description. shown only if set by the
/// system.
/// </summary>
[JsonProperty("message", NullValueHandling = NullValueHandling.Ignore)]
public string Message { get; set; }
/// <summary>
/// Peer-to-peer payment system settings.
/// </summary>
[JsonProperty("p2p_config")]
public P2PConfig P2PConfig { get; set; }
/// <summary>
/// The current status of the website.
/// </summary>
[JsonProperty("site_status", NullValueHandling = NullValueHandling.Ignore)]
public SiteStatus? SiteStatus { get; set; }
/// <summary>
/// Provides codes for languages supported.
/// </summary>
[JsonProperty("supported_languages", NullValueHandling = NullValueHandling.Ignore)]
public string[] SupportedLanguages { get; set; }
/// <summary>
/// Latest terms and conditions version.
/// </summary>
[JsonProperty("terms_conditions_version", NullValueHandling = NullValueHandling.Ignore)]
public string TermsConditionsVersion { get; set; }
}
/// <summary>
/// Maximum number of API calls during specified period of time.
/// </summary>
public partial class ApiCallLimits
{
/// <summary>
/// Maximum subscription to proposal calls.
/// </summary>
[JsonProperty("max_proposal_subscription")]
public MaxProposalSubscription MaxProposalSubscription { get; set; }
/// <summary>
/// Maximum number of general requests allowed during specified period of time.
/// </summary>
[JsonProperty("max_requestes_general")]
public MaxRequestesGeneral MaxRequestesGeneral { get; set; }
/// <summary>
/// Maximum number of outcome requests allowed during specified period of time.
/// </summary>
[JsonProperty("max_requests_outcome")]
public MaxRequestsOutcome MaxRequestsOutcome { get; set; }
/// <summary>
/// Maximum number of pricing requests allowed during specified period of time.
/// </summary>
[JsonProperty("max_requests_pricing")]
public MaxRequestsPricing MaxRequestsPricing { get; set; }
}
/// <summary>
/// Maximum subscription to proposal calls.
/// </summary>
public partial class MaxProposalSubscription
{
/// <summary>
/// Describes which calls this limit applies to.
/// </summary>
[JsonProperty("applies_to")]
public string AppliesTo { get; set; }
/// <summary>
/// Maximum number of allowed calls.
/// </summary>
[JsonProperty("max")]
public double Max { get; set; }
}
/// <summary>
/// Maximum number of general requests allowed during specified period of time.
/// </summary>
public partial class MaxRequestesGeneral
{
/// <summary>
/// Describes which calls this limit applies to.
/// </summary>
[JsonProperty("applies_to")]
public string AppliesTo { get; set; }
/// <summary>
/// The maximum of allowed calls per hour.
/// </summary>
[JsonProperty("hourly")]
public double Hourly { get; set; }
/// <summary>
/// The maximum of allowed calls per minute.
/// </summary>
[JsonProperty("minutely")]
public double Minutely { get; set; }
}
/// <summary>
/// Maximum number of outcome requests allowed during specified period of time.
/// </summary>
public partial class MaxRequestsOutcome
{
/// <summary>
/// Describes which calls this limit applies to.
/// </summary>
[JsonProperty("applies_to")]
public string AppliesTo { get; set; }
/// <summary>
/// The maximum of allowed calls per hour.
/// </summary>
[JsonProperty("hourly")]
public double Hourly { get; set; }
/// <summary>
/// The maximum of allowed calls per minute.
/// </summary>
[JsonProperty("minutely")]
public double Minutely { get; set; }
}
/// <summary>
/// Maximum number of pricing requests allowed during specified period of time.
/// </summary>
public partial class MaxRequestsPricing
{
/// <summary>
/// Describes which calls this limit applies to.
/// </summary>
[JsonProperty("applies_to")]
public string AppliesTo { get; set; }
/// <summary>
/// The maximum of allowed calls per hour.
/// </summary>
[JsonProperty("hourly")]
public double Hourly { get; set; }
/// <summary>
/// The maximum of allowed calls per minute.
/// </summary>
[JsonProperty("minutely")]
public double Minutely { get; set; }
}
/// <summary>
/// Peer-to-peer payment system settings.
/// </summary>
public partial class P2PConfig
{
/// <summary>
/// Maximum number of active ads allowed by an advertiser per currency pair and advert type
/// (buy or sell).
/// </summary>
[JsonProperty("adverts_active_limit")]
public double AdvertsActiveLimit { get; set; }
/// <summary>
/// Adverts will be deactivated if no activity occurs within this period, in days.
/// </summary>
[JsonProperty("adverts_archive_period", NullValueHandling = NullValueHandling.Ignore)]
public double? AdvertsArchivePeriod { get; set; }
/// <summary>
/// A buyer will be blocked for this duration after exceeding the cancellation limit, in
/// hours.
/// </summary>
[JsonProperty("cancellation_block_duration")]
public double CancellationBlockDuration { get; set; }
/// <summary>
/// The period within which to count buyer cancellations, in hours.
/// </summary>
[JsonProperty("cancellation_count_period")]
public double CancellationCountPeriod { get; set; }
/// <summary>
/// A buyer may cancel an order within this period without negative consequences, in minutes
/// after order creation.
/// </summary>
[JsonProperty("cancellation_grace_period")]
public double CancellationGracePeriod { get; set; }
/// <summary>
/// A buyer will be temporarily barred after marking this number of cancellations within
/// cancellation_period.
/// </summary>
[JsonProperty("cancellation_limit")]
public double CancellationLimit { get; set; }
/// <summary>
/// Maximum amount of an advert, in USD.
/// </summary>
[JsonProperty("maximum_advert_amount")]
public double MaximumAdvertAmount { get; set; }
/// <summary>
/// Maximum amount of an order, in USD.
/// </summary>
[JsonProperty("maximum_order_amount")]
public double MaximumOrderAmount { get; set; }
/// <summary>
/// Maximum number of orders a user may create per day.
/// </summary>
[JsonProperty("order_daily_limit")]
public double OrderDailyLimit { get; set; }
/// <summary>
/// Time allowed for order payment, in minutes after order creation.
/// </summary>
[JsonProperty("order_payment_period")]
public double OrderPaymentPeriod { get; set; }
}
/// <summary>
/// The current status of the website.
/// </summary>
public enum SiteStatus { Down, Up, Updating };
public static class B2Converter
{
public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
{
MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
DateParseHandling = DateParseHandling.None,
Converters =
{
SiteStatusConverter.Singleton,
new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
},
};
}
public class SiteStatusConverter : JsonConverter
{
public override bool CanConvert(Type t) => t == typeof(SiteStatus) || t == typeof(SiteStatus?);
public override object ReadJson(JsonReader reader, Type t, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null) return null;
var value = serializer.Deserialize<string>(reader);
switch (value)
{
case "down":
return SiteStatus.Down;
case "up":
return SiteStatus.Up;
case "updating":
return SiteStatus.Updating;
}
throw new Exception("Cannot unmarshal type SiteStatus");
}
public override void WriteJson(JsonWriter writer, object untypedValue, JsonSerializer serializer)
{
if (untypedValue == null)
{
serializer.Serialize(writer, null);
return;
}
var value = (SiteStatus)untypedValue;
switch (value)
{
case SiteStatus.Down:
serializer.Serialize(writer, "down");
return;
case SiteStatus.Up:
serializer.Serialize(writer, "up");
return;
case SiteStatus.Updating:
serializer.Serialize(writer, "updating");
return;
}
throw new Exception("Cannot marshal type SiteStatus");
}
public static readonly SiteStatusConverter Singleton = new SiteStatusConverter();
}
}
|
namespace Majiro.Script.Analysis.Source.Nodes.Expressions {
public class BinaryExpression : Expression {
public Expression Left;
public Expression Right;
public BinaryOperation Operation;
public BinaryExpression(Expression left, Expression right, BinaryOperation operation, MjoType type) {
Left = left;
Right = right;
Operation = operation;
Type = type;
}
public override TRes Accept<TArg, TRes>(ISyntaxVisitor<TArg, TRes> visitor, TArg arg) =>
visitor.Visit(this, arg);
}
public enum BinaryOperation {
None,
Addition,
Subtraction,
Multiplication,
Division,
Modulo,
ShiftLeft,
ShiftRight,
BitwiseAnd,
BitwiseOr,
BitwiseXor,
LogicalAnd,
LogicalOr,
CompareLessEqual,
CompareLessThan,
CompareGreaterEqual,
CompareGreaterThan,
CompareEqual,
CompareNotEqual,
}
}
|
using Bunit;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Bit.Client.Web.BlazorUI.Tests.Persona
{
[TestClass]
public class BitPersonaTests : BunitTestContext
{
[DataTestMethod,
DataRow(Visual.Fluent, true),
DataRow(Visual.Fluent, false),
DataRow(Visual.Cupertino, true),
DataRow(Visual.Cupertino, false),
DataRow(Visual.Material, true),
DataRow(Visual.Material, false)
]
public void BitPersonaShouldTakeCorrectVisual(Visual visual, bool isEnabled)
{
var component = RenderComponent<BitPersonaTest>(parameters =>
{
parameters.Add(p => p.Visual, visual);
parameters.Add(p => p.IsEnable, isEnabled);
});
var persona = component.Find(".bit-prs");
var enabledClass = isEnabled ? "enabled" : "disabled";
var visualClass = visual == Visual.Cupertino ? "cupertino" : visual == Visual.Material ? "material" : "fluent";
Assert.IsTrue(persona.ClassList.Contains($"bit-prs-{enabledClass}-{visualClass}"));
}
[DataTestMethod,
DataRow("Text", "SecondaryText", "TertiaryText", "OptionalText"),
DataRow(null, null, null, null)]
public void BitPersonaShouldCurrectWorkText(string text, string secondaryText, string tertiaryText, string optionalText)
{
var component = RenderComponent<BitPersonaTest>(
parameters =>
{
parameters.Add(p => p.Text, text);
parameters.Add(p => p.SecondaryText, secondaryText);
parameters.Add(p => p.TertiaryText, tertiaryText);
parameters.Add(p => p.OptionalText, optionalText);
});
var textClassName = component.Find(".bit-prs-primary-text");
var secendryTextClassName = component.Find(".bit-prs-secondary-text");
var tertiaryTextClassName = component.Find(".bit-prs-tertiary-text");
var optionalTextClassName = component.Find(".bit-prs-optional-text");
Assert.AreEqual(text, textClassName.TextContent.HasValue() ? textClassName.TextContent : null);
Assert.AreEqual(secondaryText, secendryTextClassName.TextContent.HasValue() ? secendryTextClassName.TextContent : null);
Assert.AreEqual(tertiaryText, tertiaryTextClassName.TextContent.HasValue() ? tertiaryTextClassName.TextContent : null);
Assert.AreEqual(optionalText, optionalTextClassName.TextContent.HasValue() ? optionalTextClassName.TextContent : null);
}
[DataTestMethod,
DataRow(BitPersonaPresenceStatus.Blocked, true),
DataRow(BitPersonaPresenceStatus.Blocked, false),
DataRow(BitPersonaPresenceStatus.Offline, true),
DataRow(BitPersonaPresenceStatus.Offline, false),
DataRow(BitPersonaPresenceStatus.Away, true),
DataRow(BitPersonaPresenceStatus.Away, false),
DataRow(BitPersonaPresenceStatus.Online, true),
DataRow(BitPersonaPresenceStatus.Online, false),
DataRow(BitPersonaPresenceStatus.Busy, true),
DataRow(BitPersonaPresenceStatus.Busy, false),
DataRow(BitPersonaPresenceStatus.DND, true),
DataRow(BitPersonaPresenceStatus.DND, false),]
public void BitPersonaPresenceStatusClassNameTest(BitPersonaPresenceStatus presenceStatus, bool isOutOfOffice)
{
var component = RenderComponent<BitPersonaTest>(
parameters =>
{
parameters.Add(p => p.Presence, presenceStatus);
parameters.Add(p => p.IsOutOfOffice, isOutOfOffice);
});
var presenceStatusClassName = DetermineIcon(presenceStatus, isOutOfOffice);
var personaStatus = component.Find(".bit-prs-presence > i");
Assert.AreEqual($"bit-prs-icon bit-icon--{presenceStatusClassName}", personaStatus.GetAttribute("class"));
}
[DataTestMethod,
DataRow(BitPersonaSize.Size8),
DataRow(BitPersonaSize.Size32),
DataRow(BitPersonaSize.Size40),
DataRow(BitPersonaSize.Size48),
DataRow(BitPersonaSize.Size56),
DataRow(BitPersonaSize.Size72),
DataRow(BitPersonaSize.Size100),
DataRow(BitPersonaSize.Size120)]
public void BitPersonaSizeClassNameTest(string size)
{
var component = RenderComponent<BitPersonaTest>(
parameters =>
{
parameters.Add(p => p.Size, size);
});
var persona = component.Find(".bit-prs");
var personaSizeClass = $"bit-prs-{size}";
Assert.IsTrue(persona.ClassList.Contains(personaSizeClass));
}
[DataTestMethod,
DataRow("Image url"),
DataRow(null)]
public void BitPersonaImageTest(string imageurl)
{
var component = RenderComponent<BitPersonaTest>(
parameters =>
{
parameters.Add(p => p.ImageUrl, imageurl);
});
if (imageurl.HasValue())
{
var personaImageContainerClassName = component.Find(".bit-prs-img-container");
var personaImage = personaImageContainerClassName.FirstElementChild;
var imageSrc = personaImage.GetAttribute("src");
Assert.AreEqual(imageurl, imageSrc);
}
}
[DataTestMethod,
DataRow("Presence Title", BitPersonaPresenceStatus.Blocked),
DataRow("Presence Title", BitPersonaPresenceStatus.Away),
DataRow("Presence Title", BitPersonaPresenceStatus.Offline),
DataRow("Presence Title", BitPersonaPresenceStatus.Online),
DataRow("Presence Title", BitPersonaPresenceStatus.DND),
DataRow("Presence Title", BitPersonaPresenceStatus.Busy),]
public void BitPersonaPresenceTitleTest(string presenceTitle, BitPersonaPresenceStatus presenceStatus)
{
var component = RenderComponent<BitPersonaTest>(
parameters =>
{
parameters.Add(p => p.PresenceTitle, presenceTitle);
parameters.Add(p => p.Presence, presenceStatus);
});
var precenseTitleClassName = component.Find(".bit-prs-presence");
var title = precenseTitleClassName.GetAttribute("title");
Assert.AreEqual(presenceTitle, title);
}
private string DetermineIcon(BitPersonaPresenceStatus presence, bool isOutofOffice)
{
string oofIcon = "presence_oof";
return presence switch
{
BitPersonaPresenceStatus.Online => "presence_available",
BitPersonaPresenceStatus.Busy => "presence_busy",
BitPersonaPresenceStatus.Away => isOutofOffice ? oofIcon : "presence_away",
BitPersonaPresenceStatus.DND => "presence_dnd",
BitPersonaPresenceStatus.Offline => isOutofOffice ? oofIcon : "presence_offline",
_ => "presence_unknown",
};
}
}
}
|
/* _BEGIN_TEMPLATE_
{
"id": "LOOT_101",
"name": [
"爆炸符文",
"Explosive Runes"
],
"text": [
"<b>奥秘:</b>在你的对手使用一张随从牌后,对该随从造成$6点伤害,超过其生命值的伤害将由对方英雄\n承受。",
"<b>Secret:</b> After your opponent plays a minion, deal $6 damage to it and any excess to their hero."
],
"cardClass": "MAGE",
"type": "SPELL",
"cost": 3,
"rarity": "RARE",
"set": "LOOTAPALOOZA",
"collectible": true,
"dbfId": 43407
}
_END_TEMPLATE_ */
namespace HREngine.Bots
{
class Sim_LOOT_101 : SimTemplate //* 爆炸符文 Explosive Runes
{
//<b>Secret:</b> After your opponent plays a minion, deal $6 damage to it and any excess to their hero.
//<b>奥秘:</b>在你的对手使用一张随从牌后,对该随从造成$6点伤害,超过其生命值上限的伤害将由对方英雄承受。
public override void onSecretPlay(Playfield p, bool ownplay, Minion target, int number)
{
var dmg = ownplay ? p.getSpellDamageDamage(6) : p.getEnemySpellDamageDamage(6);
p.minionGetDamageOrHeal(target, dmg);
}
}
} |
using System.Web;
using System.Web.Mvc;
using Cake.Web.Core;
using Cake.Web.Docs;
namespace Cake.Web.Helpers.Api
{
public static class FieldHelper
{
public static IHtmlString FieldName(this ApiServices context, DocumentedField field)
{
if (field != null)
{
return MvcHtmlString.Create(field.Definition.Name);
}
return MvcHtmlString.Create(string.Empty);
}
}
} |
using Microsoft.AspNetCore.Mvc;
using RRBL;
using RRModels;
using RRREST.DTO;
using System.Threading.Tasks;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace RRREST.Controllers
{
[Route("restaurants/{restaurantId}/reviews")]
[ApiController]
public class ReviewController : ControllerBase
{
private readonly IReviewBL _reviewBL;
private readonly IRestaurantBL _restaurantBL;
public ReviewController(IReviewBL reviewBL, IRestaurantBL restaurantBL)
{
_reviewBL = reviewBL;
_restaurantBL = restaurantBL;
}
// GET: api/<ReviewController>
[HttpGet]
public async Task<IActionResult> GetAllReviewsAsync(int restaurantId)
{
var result = await _reviewBL.GetReviewsAsync(await _restaurantBL.GetRestaurantByIdAsync(restaurantId));
return Ok(new Rating
{
reviews = result.Item1,
average = result.Item2
});
}
// POST api/<ReviewController>
[HttpPost]
public async Task<IActionResult> AddReviewAsync(int restaurantId, [FromBody] Review newReview)
{
return Created($"/api/Restaurants/{restaurantId}/Reviews",
await _reviewBL.AddReviewAsync(
await _restaurantBL.GetRestaurantByIdAsync(restaurantId),
new Review(newReview.Rating, newReview.Description
)));
}
}
} |
using Abp.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
namespace Lpb.Service1.EntityFrameworkCore
{
public class Service1DbContext : AbpDbContext
{
//Add DbSet properties for your entities...
public Service1DbContext(DbContextOptions<Service1DbContext> options)
: base(options)
{
}
}
}
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2013 Tasharen Entertainment
//----------------------------------------------
using UnityEditor;
using UnityEngine;
#pragma warning disable
/// <summary>
/// Editor component used to display a list of sprites.
/// </summary>
public class SpriteSelector : ScriptableWizard
{
public delegate void Callback (string sprite);
UIAtlas mAtlas;
UISprite mSprite;
string mName;
Vector2 mPos = Vector2.zero;
Callback mCallback;
float mClickTime = 0f;
/// <summary>
/// Name of the selected sprite.
/// </summary>
public string spriteName { get { return (mSprite != null) ? mSprite.spriteName : mName; } }
/// <summary>
/// Show the selection wizard.
/// </summary>
public static void Show (UIAtlas atlas, string selectedSprite, Callback callback)
{
SpriteSelector comp = ScriptableWizard.DisplayWizard<SpriteSelector>("Select a Sprite");
comp.mAtlas = atlas;
comp.mSprite = null;
comp.mName = selectedSprite;
comp.mCallback = callback;
}
/// <summary>
/// Show the selection wizard.
/// </summary>
public static void Show (UIAtlas atlas, UISprite selectedSprite)
{
SpriteSelector comp = ScriptableWizard.DisplayWizard<SpriteSelector>("Select a Sprite");
comp.mAtlas = atlas;
comp.mSprite = selectedSprite;
comp.mCallback = null;
}
/// <summary>
/// Draw the custom wizard.
/// </summary>
void OnGUI ()
{
EditorGUIUtility.LookLikeControls(80f);
if (mAtlas == null)
{
GUILayout.Label("No Atlas selected.", "LODLevelNotifyText");
}
else
{
bool close = false;
GUILayout.Label(mAtlas.name + " Sprites", "LODLevelNotifyText");
NGUIEditorTools.DrawSeparator();
GUILayout.BeginHorizontal();
GUILayout.Space(84f);
string before = NGUISettings.partialSprite;
string after = EditorGUILayout.TextField("", before, "SearchTextField");
NGUISettings.partialSprite = after;
if (GUILayout.Button("", "SearchCancelButton", GUILayout.Width(18f)))
{
NGUISettings.partialSprite = "";
GUIUtility.keyboardControl = 0;
}
GUILayout.Space(84f);
GUILayout.EndHorizontal();
Texture2D tex = mAtlas.texture as Texture2D;
if (tex == null)
{
GUILayout.Label("The atlas doesn't have a texture to work with");
return;
}
BetterList<string> sprites = mAtlas.GetListOfSprites(NGUISettings.partialSprite);
float size = 80f;
float padded = size + 10f;
int columns = Mathf.FloorToInt(Screen.width / padded);
if (columns < 1) columns = 1;
int offset = 0;
Rect rect = new Rect(10f, 0, size, size);
GUILayout.Space(10f);
mPos = GUILayout.BeginScrollView(mPos);
while (offset < sprites.size)
{
GUILayout.BeginHorizontal();
{
int col = 0;
rect.x = 10f;
for (; offset < sprites.size; ++offset)
{
UIAtlas.Sprite sprite = mAtlas.GetSprite(sprites[offset]);
if (sprite == null) continue;
// Button comes first
if (GUI.Button(rect, ""))
{
float delta = Time.realtimeSinceStartup - mClickTime;
mClickTime = Time.realtimeSinceStartup;
if (spriteName != sprite.name)
{
if (mSprite != null)
{
NGUIEditorTools.RegisterUndo("Atlas Selection", mSprite);
mSprite.spriteName = sprite.name;
mSprite.MakePixelPerfect();
EditorUtility.SetDirty(mSprite.gameObject);
}
if (mCallback != null)
{
mName = sprite.name;
mCallback(sprite.name);
}
}
else if (delta < 0.5f) close = true;
}
if (Event.current.type == EventType.Repaint)
{
// On top of the button we have a checkboard grid
NGUIEditorTools.DrawTiledTexture(rect, NGUIEditorTools.backdropTexture);
Rect uv = sprite.outer;
if (mAtlas.coordinates == UIAtlas.Coordinates.Pixels)
uv = NGUIMath.ConvertToTexCoords(uv, tex.width, tex.height);
// Calculate the texture's scale that's needed to display the sprite in the clipped area
float scaleX = rect.width / uv.width;
float scaleY = rect.height / uv.height;
// Stretch the sprite so that it will appear proper
float aspect = (scaleY / scaleX) / ((float)tex.height / tex.width);
Rect clipRect = rect;
if (aspect != 1f)
{
if (aspect < 1f)
{
// The sprite is taller than it is wider
float padding = size * (1f - aspect) * 0.5f;
clipRect.xMin += padding;
clipRect.xMax -= padding;
}
else
{
// The sprite is wider than it is taller
float padding = size * (1f - 1f / aspect) * 0.5f;
clipRect.yMin += padding;
clipRect.yMax -= padding;
}
}
GUI.DrawTextureWithTexCoords(clipRect, tex, uv);
// Draw the selection
if (spriteName == sprite.name)
{
NGUIEditorTools.DrawOutline(rect, new Color(0.4f, 1f, 0f, 1f));
}
}
if (++col >= columns)
{
++offset;
break;
}
rect.x += padded;
}
}
GUILayout.EndHorizontal();
GUILayout.Space(padded);
rect.y += padded;
}
GUILayout.EndScrollView();
if (close) Close();
}
}
}
|
using System.Collections.Generic;
using AutoMapper;
using AdventureWorks.Application.DataEngine.Purchasing.Vendor.Queries.GetVendors;
using AdventureWorks.Application.Interfaces.Mapping;
using AdventureWorks.BaseDomain.Entities.Purchasing;
using AdventureWorks.Common.Extensions;
using MediatR;
using Entities = AdventureWorks.Domain.Entities.Purchasing;
namespace AdventureWorks.Application.DataEngine.Purchasing.Vendor.Commands.UpdateVendor
{
public partial class UpdateVendorSetCommand : IRequest<List<VendorLookupModel>>,
IHaveCustomMapping
{
public List<UpdateVendorCommand> Commands { get; set; }
public void CreateMappings(Profile configuration)
{
configuration.CreateMap<List<BaseVendor>, List<UpdateVendorCommand>>(MemberList.Source)
.IgnoreMissingDestinationMembers();
configuration.CreateMap<List<UpdateVendorCommand>, List<Entities.Vendor>>(MemberList.None)
.IgnoreMissingDestinationMembers();
configuration.CreateMap<List<Entities.Vendor>, List<Entities.Vendor>>(MemberList.None);
}
}
} |
/////////////////////////////////////////////////////////////////////////////////
// Paint.NET //
// Copyright (C) dotPDN LLC, Rick Brewster, Tom Jackson, and contributors. //
// Portions Copyright (C) Microsoft Corporation. All Rights Reserved. //
// See src/Resources/Files/License.txt for full licensing and attribution //
// details. //
// . //
/////////////////////////////////////////////////////////////////////////////////
using System;
namespace PaintDotNet.SystemLayer
{
/// <summary>
/// Methods for keeping track of time in a high precision manner.
/// </summary>
/// <remarks>
/// This class provides precision and accuracy of 1 millisecond.
/// </remarks>
public sealed class Timing
{
private ulong countsPerMs;
private double countsPerMsDouble;
private ulong birthTick;
/// <summary>
/// The number of milliseconds that elapsed between system startup
/// and creation of this instance of Timing.
/// </summary>
public ulong BirthTick
{
get
{
return birthTick;
}
}
/// <summary>
/// Returns the number of milliseconds that have elapsed since
/// system startup.
/// </summary>
public ulong GetTickCount()
{
ulong tick;
SafeNativeMethods.QueryPerformanceCounter(out tick);
return tick / countsPerMs;
}
/// <summary>
/// Returns the number of milliseconds that have elapsed since
/// system startup.
/// </summary>
public double GetTickCountDouble()
{
ulong tick;
SafeNativeMethods.QueryPerformanceCounter(out tick);
return (double)tick / countsPerMsDouble;
}
/// <summary>
/// Constructs an instance of the Timing class.
/// </summary>
public Timing()
{
ulong frequency;
if (!SafeNativeMethods.QueryPerformanceFrequency(out frequency))
{
NativeMethods.ThrowOnWin32Error("QueryPerformanceFrequency returned false");
}
countsPerMs = frequency / 1000;
countsPerMsDouble = (double)frequency / 1000.0;
birthTick = GetTickCount();
}
}
}
|
using System;
using OpenCvSharp.Internal;
// ReSharper disable once CheckNamespace
namespace OpenCvSharp.XImgProc
{
/// <summary>
/// Interface for realizations of Domain Transform filter.
/// </summary>
// ReSharper disable once InconsistentNaming
public class DTFilter : Algorithm
{
private Ptr? detectorPtr;
/// <summary>
/// Creates instance by raw pointer
/// </summary>
protected DTFilter(IntPtr p)
{
detectorPtr = new Ptr(p);
ptr = detectorPtr.Get();
}
/// <summary>
/// Releases managed resources
/// </summary>
protected override void DisposeManaged()
{
detectorPtr?.Dispose();
detectorPtr = null;
base.DisposeManaged();
}
/// <summary>
/// Factory method, create instance of DTFilter and produce initialization routines.
/// </summary>
/// <param name="guide">guided image (used to build transformed distance, which describes edge structure of
/// guided image).</param>
/// <param name="sigmaSpatial">sigma_H parameter in the original article, it's similar to the sigma in the
/// coordinate space into bilateralFilter.</param>
/// <param name="sigmaColor">sigma_r parameter in the original article, it's similar to the sigma in the
/// color space into bilateralFilter.</param>
/// <param name="mode">one form three modes DTF_NC, DTF_RF and DTF_IC which corresponds to three modes for
/// filtering 2D signals in the article.</param>
/// <param name="numIters">optional number of iterations used for filtering, 3 is quite enough.</param>
/// <returns></returns>
public static DTFilter Create(
InputArray guide, double sigmaSpatial, double sigmaColor,
EdgeAwareFiltersList mode = EdgeAwareFiltersList.DTF_NC, int numIters = 3)
{
if (guide == null)
throw new ArgumentNullException(nameof(guide));
guide.ThrowIfDisposed();
NativeMethods.HandleException(
NativeMethods.ximgproc_createDTFilter(
guide.CvPtr, sigmaSpatial, sigmaColor, (int)mode, numIters, out var p));
GC.KeepAlive(guide);
return new DTFilter(p);
}
/// <summary>
/// Simple one-line Domain Transform filter call. If you have multiple images to filter with the same
/// guided image then use DTFilter interface to avoid extra computations on initialization stage.
/// </summary>
/// <param name="src"></param>
/// <param name="dst"></param>
/// <param name="dDepth"></param>
public virtual void Filter(InputArray src, OutputArray dst, int dDepth = -1)
{
ThrowIfDisposed();
if (src == null)
throw new ArgumentNullException(nameof(src));
if (dst == null)
throw new ArgumentNullException(nameof(dst));
src.ThrowIfDisposed();
dst.ThrowIfNotReady();
NativeMethods.HandleException(
NativeMethods.ximgproc_DTFilter_filter(
ptr, src.CvPtr, dst.CvPtr, dDepth));
GC.KeepAlive(this);
GC.KeepAlive(src);
dst.Fix();
}
internal class Ptr : OpenCvSharp.Ptr
{
public Ptr(IntPtr ptr) : base(ptr)
{
}
public override IntPtr Get()
{
NativeMethods.HandleException(
NativeMethods.ximgproc_Ptr_DTFilter_get(ptr, out var ret));
GC.KeepAlive(this);
return ret;
}
protected override void DisposeUnmanaged()
{
NativeMethods.HandleException(
NativeMethods.ximgproc_Ptr_DTFilter_delete(ptr));
base.DisposeUnmanaged();
}
}
}
}
|
using System;
using FubuCore;
using FubuMVC.Core.Registration.Conventions;
using FubuMVC.Core.Registration.DSL;
using FubuMVC.Core.Registration.Nodes;
using FubuMVC.Core.Runtime;
namespace FubuMVC.Core
{
public class OutputDeterminationExpression
{
private readonly FubuRegistry _registry;
public OutputDeterminationExpression(FubuRegistry registry)
{
_registry = registry;
}
public ActionCallFilterExpression ToJson
{
get
{
return output(call => call.AddToEnd(new RenderJsonNode(call.OutputType())),
"Adding json output node to render json");
}
}
public ActionCallFilterExpression ToHtml
{
get
{
return output(call => call.AddToEnd(new RenderTextNode<string>
{
MimeType = MimeType.Html
}), "Adding output node to render raw HTML text");
}
}
public ActionCallFilterExpression To(Func<ActionCall, OutputNode> func)
{
return output(action =>
{
OutputNode node = func(action);
action.AddToEnd(node);
}, "Adding output nodes from per-call function");
}
public ActionCallFilterExpression To<T>() where T : OutputNode, new()
{
return output(action => action.AddToEnd(new T()), "Adding output node '{0}'".ToFormat(typeof (T).Name));
}
private ActionCallFilterExpression output(Action<ActionCall> configure, string reason)
{
var modification = new ActionCallModification(configure, reason);
_registry.ApplyConvention(modification);
modification.Filters.Excludes += call => call.HasOutputBehavior();
return new ActionCallFilterExpression(modification.Filters);
}
}
} |
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Licensed under the MIT License. See LICENSE.txt in the project root for license information.
using ExampleGallery.Direct3DInterop.SpriteBatchPerformance;
using Microsoft.Graphics.Canvas;
using Microsoft.Graphics.Canvas.Text;
using Microsoft.Graphics.Canvas.UI.Xaml;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Numerics;
using System.Threading;
using System.Threading.Tasks;
using Windows.ApplicationModel;
using Windows.Foundation;
using Windows.UI;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;
namespace ExampleGallery
{
public sealed partial class SpriteBatchPerf : UserControl, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public enum GraphMode
{
DrawCount,
BitmapCount,
}
public List<GraphMode> GraphModes { get { return Utils.GetEnumAsList<GraphMode>(); } }
GraphMode currentGraphMode = GraphMode.DrawCount;
public GraphMode CurrentGraphMode
{
get
{
return currentGraphMode;
}
set
{
if (currentGraphMode != value)
{
ResetGraph();
}
currentGraphMode = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("IsDrawCountEnabled"));
PropertyChanged(this, new PropertyChangedEventArgs("IsBitmapCountEnabled"));
}
}
}
public bool IsDrawCountEnabled { get { return CurrentGraphMode == GraphMode.BitmapCount; } }
public bool IsBitmapCountEnabled { get { return CurrentGraphMode == GraphMode.DrawCount; } }
public int DrawCount { get; set; }
public int BitmapCount { get; set; }
public List<Scenario> Scenarios { get; private set; }
// This is used when the page unloads to stop any pending profiling work.
CancellationTokenSource currentProfilingTaskCancellation = new CancellationTokenSource();
public SpriteBatchPerf()
{
Scenarios = new List<Scenario>();
bool spriteBatchSupported = CanvasSpriteBatch.IsSupported(CanvasDevice.GetSharedDevice());
Scenarios.Add(new Scenario(Scenario.DrawMethod.DrawImage, CanvasSpriteSortMode.None));
if (spriteBatchSupported)
{
Scenarios.Add(new Scenario(Scenario.DrawMethod.Win2DSpriteBatch, CanvasSpriteSortMode.None));
Scenarios.Add(new Scenario(Scenario.DrawMethod.Win2DSpriteBatch, CanvasSpriteSortMode.Bitmap));
Scenarios.Add(new Scenario(Scenario.DrawMethod.CppWin2DSpriteBatch, CanvasSpriteSortMode.None));
Scenarios.Add(new Scenario(Scenario.DrawMethod.CppWin2DSpriteBatch, CanvasSpriteSortMode.Bitmap));
Scenarios.Add(new Scenario(Scenario.DrawMethod.D2DSpriteBatch, CanvasSpriteSortMode.None));
}
DrawCount = 0;
BitmapCount = 1;
if (!DesignMode.DesignModeEnabled)
DataContext = this;
if (ThumbnailGenerator.IsDrawingThumbnail)
{
foreach (var scenario in Scenarios)
{
scenario.PopulateWithThumbnailData();
}
}
this.InitializeComponent();
if (!spriteBatchSupported)
{
this.SpriteBatchNotSupportedText.Visibility = Visibility.Visible;
}
}
void control_Unloaded(object sender, RoutedEventArgs e)
{
currentProfilingTaskCancellation.Cancel();
// Explicitly remove references to allow the Win2D controls to get garbage collected.
CpuGraphCanvas.RemoveFromVisualTree();
GpuGraphCanvas.RemoveFromVisualTree();
CpuGraphCanvas = null;
GpuGraphCanvas = null;
}
async void OnGoButtonClicked(object sender, RoutedEventArgs e)
{
var button = (Button)sender;
button.IsEnabled = false;
try
{
await RunScenarios();
}
catch (TaskCanceledException)
{
// ignore
}
button.IsEnabled = true;
}
async Task RunScenarios()
{
var device = CanvasDevice.GetSharedDevice();
int maxValue;
switch (CurrentGraphMode)
{
case GraphMode.DrawCount:
maxValue = (int)DrawCountSlider.Maximum;
break;
case GraphMode.BitmapCount:
maxValue = (int)BitmapCountSlider.Maximum;
break;
default:
throw new Exception();
}
for (int value = 0; value <= maxValue; value += (maxValue / 100))
{
switch (CurrentGraphMode)
{
case GraphMode.DrawCount:
DrawCount = value;
break;
case GraphMode.BitmapCount:
value = Math.Max(1, value);
BitmapCount = value;
break;
}
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("DrawCount"));
PropertyChanged(this, new PropertyChangedEventArgs("BitmapCount"));
}
using (var scenarioData = new ScenarioData(device, DrawCount, BitmapCount, value))
{
foreach (var scenario in Scenarios)
{
await scenario.Go(currentProfilingTaskCancellation.Token, device, scenarioData);
}
}
InvalidateGraphs();
}
}
void OnDrawCpuGraph(CanvasControl sender, CanvasDrawEventArgs args)
{
var graphDrawer = new GraphDrawer((float)sender.ActualWidth, (float)sender.ActualHeight, Scenarios, e => e.CpuTimeInMs, "CPU");
graphDrawer.Draw(args.DrawingSession);
}
void OnDrawGpuGraph(CanvasControl sender, CanvasDrawEventArgs args)
{
var graphDrawer = new GraphDrawer((float)sender.ActualWidth, (float)sender.ActualHeight, Scenarios, e => e.GpuTimeInMs, "GPU");
graphDrawer.Draw(args.DrawingSession);
}
void OnResetGraphClicked(object sender, RoutedEventArgs e)
{
ResetGraph();
}
void ResetGraph()
{
foreach (var scenario in Scenarios)
{
scenario.Reset();
}
InvalidateGraphs();
}
void InvalidateGraphs()
{
CpuGraphCanvas.Invalidate();
GpuGraphCanvas.Invalidate();
}
public sealed class Scenario : INotifyPropertyChanged
{
public enum DrawMethod
{
Win2DSpriteBatch,
CppWin2DSpriteBatch,
D2DSpriteBatch,
DrawImage
}
public DrawMethod Method { get; private set; }
public CanvasSpriteSortMode SortMode { get; private set; }
public CanvasImageSource Image { get; private set; }
static Color[] colors =
{
Colors.Red,
Colors.Green,
Colors.Blue,
Colors.DarkGoldenrod,
Colors.Purple,
Colors.DarkOliveGreen
};
public SolidColorBrush Color
{
get
{
int index = (int)Method + (int)SortMode * Enum.GetValues(typeof(DrawMethod)).Length;
return new SolidColorBrush(colors[index % colors.Length]);
}
}
public string Name
{
get
{
string n;
switch (Method)
{
case DrawMethod.Win2DSpriteBatch: n = "C# Win2D"; break;
case DrawMethod.CppWin2DSpriteBatch: n = "C++ Win2D"; break;
case DrawMethod.D2DSpriteBatch: n = "C++ D2D"; break;
case DrawMethod.DrawImage: n = "C# DrawImage"; break;
default: throw new Exception();
}
if (SortMode == CanvasSpriteSortMode.Bitmap)
n = n + " (sorted)";
return n;
}
}
public string Summary
{
get
{
if (Data == null || Data.Count == 0)
return "no data";
return string.Format("CPU/GPU avg: {0:0.00}ms/{1:0.00}ms",
Data.Values.Select(e => e.CpuTimeInMs).Average(),
Data.Values.Where(e => e.GpuTimeInMs >= 0.0).Select(e => e.GpuTimeInMs).Average());
}
}
public Dictionary<int, CpuGpuTime> Data { get; private set; }
public event PropertyChangedEventHandler PropertyChanged;
public Scenario(DrawMethod method, CanvasSpriteSortMode sortMode)
{
Method = method;
SortMode = sortMode;
Reset();
}
IScenarioRunner MakeScenarioRunner()
{
switch (Method)
{
case DrawMethod.Win2DSpriteBatch:
case DrawMethod.DrawImage:
return new Win2DScenarioRunner(Method);
case DrawMethod.CppWin2DSpriteBatch:
return new CppWin2DScenarioRunner();
case DrawMethod.D2DSpriteBatch:
return new Direct2DScenarioRunner();
default:
throw new Exception();
}
}
public struct CpuGpuTime
{
public double CpuTimeInMs;
public double GpuTimeInMs;
}
internal async Task Go(CancellationToken cancellationToken, CanvasDevice device, ScenarioData scenarioData)
{
var runner = MakeScenarioRunner();
scenarioData.AddDataToScenarioRunner(runner);
// Create the image source and the render target. These sizes are hardcoded and independent of the
// display's DPI since we just want a small image to convince ourselves that the scenarios really are
// rendering the right thing.
Image = new CanvasImageSource(device, 128, 128, 96);
using (var rt = new CanvasRenderTarget(device, 128, 128, 96))
{
// We actually run the scenario on the thread pool - XAML really falls down if you overload the UI thread.
var time = await Task.Run(() =>
{
// Run the scenario multiple times to try and avoid too much noise
List<CpuGpuTime> times = new List<CpuGpuTime>();
for (int i = 0; i < 10; ++i)
{
// Hold the device lock while we run the scenario - this prevents other threads
// from interacting with the device and interfering with our recorded time.
using (var deviceLock = device.Lock())
{
times.Add(RunScenario(runner, rt));
}
if (cancellationToken.IsCancellationRequested)
return new CpuGpuTime();
}
var cpuTimes = from entry in times select entry.CpuTimeInMs;
var gpuTimes = from entry in times select entry.GpuTimeInMs;
return new CpuGpuTime
{
CpuTimeInMs = GetAverage(cpuTimes),
GpuTimeInMs = GetAverage(gpuTimes)
};
}, cancellationToken);
Data[scenarioData.Value] = time;
if (cancellationToken.IsCancellationRequested)
return;
using (var ds = Image.CreateDrawingSession(Colors.Transparent))
{
ds.DrawImage(rt);
var timing = string.Format("{0:0.00}ms\n{1:0.00}ms", time.CpuTimeInMs, time.GpuTimeInMs);
ds.DrawText(timing, 0, 0, Colors.White);
ds.DrawText(timing, 1, 1, Colors.Black);
}
}
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("Image"));
PropertyChanged(this, new PropertyChangedEventArgs("Summary"));
}
}
static double GetAverage(IEnumerable<double> times)
{
var list = times.ToList();
if (list.Count > 2)
{
// Return the median value
list.Sort();
if (list.Count % 2 == 0)
return list[list.Count / 2];
else
return list.GetRange(list.Count / 2, 2).Average();
}
else
{
return list.Average();
}
}
CpuGpuTime RunScenario(IScenarioRunner runner, CanvasRenderTarget rt)
{
while (true)
{
Stopwatch stopWatch = new Stopwatch();
using (GpuStopWatch gpuStopWatch = new GpuStopWatch(rt.Device))
{
gpuStopWatch.Start();
stopWatch.Start();
using (var ds = rt.CreateDrawingSession())
{
ds.Clear(Colors.Black);
runner.RunScenario(ds, SortMode);
}
stopWatch.Stop();
gpuStopWatch.Stop();
var gpuTime = gpuStopWatch.GetGpuTimeInMs();
if (gpuTime < 0)
{
// try again until we get a time that isn't disjoint
continue;
}
return new CpuGpuTime
{
CpuTimeInMs = stopWatch.Elapsed.TotalMilliseconds,
GpuTimeInMs = gpuTime
};
}
}
}
public void Reset()
{
Data = new Dictionary<int, CpuGpuTime>();
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs("Summary"));
}
public void PopulateWithThumbnailData()
{
Reset();
int seed = (int)Method + (int)SortMode * Enum.GetValues(typeof(DrawMethod)).Length;
var rnd = new Random(seed);
double scale = rnd.NextDouble() * 30;
double jitter = 10;
for (int i = 0; i < 100; ++i)
{
Data.Add(i * 100, new CpuGpuTime()
{
CpuTimeInMs = (i / 100.0) * scale + rnd.NextDouble() * jitter,
GpuTimeInMs = (i / 100.0) * scale + rnd.NextDouble() * jitter
});
}
}
}
class Win2DScenarioRunner : IScenarioRunner
{
private Scenario.DrawMethod method;
List<ScenarioData.DrawInfo> sprites = new List<ScenarioData.DrawInfo>();
public Win2DScenarioRunner(Scenario.DrawMethod method)
{
this.method = method;
}
public void AddSprite(CanvasBitmap bitmap, Vector4 tint, Vector2 position, float rotation)
{
sprites.Add(new ScenarioData.DrawInfo()
{
Bitmap = bitmap,
Tint = tint,
Position = position,
Rotation = rotation
});
}
public void RunScenario(CanvasDrawingSession drawingSession, CanvasSpriteSortMode sortMode)
{
switch (method)
{
case Scenario.DrawMethod.Win2DSpriteBatch:
using (var sb = drawingSession.CreateSpriteBatch(sortMode))
{
foreach (var sprite in sprites)
{
sb.Draw(sprite.Bitmap, sprite.Position, sprite.Tint, Vector2.Zero, sprite.Rotation, Vector2.One, CanvasSpriteFlip.None);
}
}
break;
case Scenario.DrawMethod.DrawImage:
var oldTransform = drawingSession.Transform;
foreach (var sprite in sprites)
{
drawingSession.Transform = Matrix3x2.CreateRotation(sprite.Rotation) * Matrix3x2.CreateTranslation(sprite.Position);
drawingSession.DrawImage(sprite.Bitmap, Vector2.Zero, sprite.Bitmap.Bounds, sprite.Tint.W);
}
drawingSession.Transform = oldTransform;
break;
}
}
}
class GraphDrawer
{
float actualHeight;
float actualWidth;
List<Scenario> scenarios;
Func<Scenario.CpuGpuTime, double> selector;
string title;
float maxXValue;
float maxYValue;
Vector2 origin;
Vector2 xAxisEnd;
Vector2 yAxisEnd;
public GraphDrawer(float actualWidth, float actualHeight, List<Scenario> scenarios, Func<Scenario.CpuGpuTime, double> selector, string title)
{
this.actualWidth = actualWidth;
this.actualHeight = actualHeight;
this.scenarios = scenarios;
this.selector = selector;
this.title = title;
maxXValue = (float)(Math.Ceiling(FindMaxCount() / 100) * 100); // round to next 100
maxYValue = (float)(Math.Ceiling(FindMaxTime() / 2) * 2); // round to next 2
}
CanvasTextFormat axisFormat = new CanvasTextFormat()
{
FontSize = 12,
HorizontalAlignment = CanvasHorizontalAlignment.Right,
VerticalAlignment = CanvasVerticalAlignment.Center
};
public void Draw(CanvasDrawingSession ds)
{
var widestLayoutRect = new CanvasTextLayout(ds, string.Format("{0}\t", maxYValue.ToString()), axisFormat, 500, 100).LayoutBounds;
origin = new Vector2((float)widestLayoutRect.Width, actualHeight - (float)widestLayoutRect.Height);
yAxisEnd = new Vector2(origin.X, (float)widestLayoutRect.Height);
xAxisEnd = new Vector2(actualWidth, origin.Y);
foreach (var scenario in scenarios)
{
DrawSeries(ds, scenario);
}
DrawAxes(ds);
ds.DrawText(title, new Vector2(origin.X + 10, 10), Colors.White);
}
private void DrawSeries(CanvasDrawingSession ds, Scenario scenario)
{
var data = scenario.Data;
var lastPoint = origin;
var color = scenario.Color.Color;
foreach (var key in data.Keys.OrderBy(k => k))
{
var point = new Vector2(GetX(key), GetY((float)selector(data[key])));
ds.DrawLine(lastPoint, point, color, 2);
lastPoint = point;
}
}
private void DrawAxes(CanvasDrawingSession ds)
{
ds.DrawLine(origin, xAxisEnd, Colors.White, 1);
ds.DrawLine(origin, yAxisEnd, Colors.White, 1);
for (int i = 0; i <= 9; ++i)
{
float y = (maxYValue / 9.0f) * (float)i;
ds.DrawText(string.Format("{0}", (int)y), new Vector2(origin.X - 5, GetY(y)), Colors.White, axisFormat);
}
axisFormat.VerticalAlignment = CanvasVerticalAlignment.Top;
for (int i = 0; i <= 9; ++i)
{
float x = (maxXValue / 9.0f) * (float)i;
ds.DrawText(string.Format("{0}", (int)x), new Vector2(GetX(x), origin.Y), Colors.White, axisFormat);
}
}
double FindMaxTime()
{
double maxTime = 0;
foreach (var scenario in scenarios)
{
if (scenario.Data.Count > 0)
maxTime = Math.Max(maxTime, scenario.Data.Values.Select(selector).Max());
}
return maxTime;
}
float FindMaxCount()
{
float maxCount = 0;
foreach (var scenario in scenarios)
{
if (scenario.Data.Count > 0)
maxCount = Math.Max(maxCount, scenario.Data.Keys.Max());
}
return maxCount;
}
float GetY(float value)
{
return Vector2.Lerp(origin, yAxisEnd, (value / maxYValue)).Y;
}
float GetX(float value)
{
return Vector2.Lerp(origin, xAxisEnd, (value / maxXValue)).X;
}
}
internal class ScenarioData : IDisposable
{
public int DrawCount { get; private set; }
public int BitmapCount { get; private set; }
public int Value { get; private set; }
public struct DrawInfo
{
public CanvasBitmap Bitmap;
public Vector4 Tint;
public Vector2 Position;
public float Rotation;
}
List<DrawInfo> drawInfo;
public ScenarioData(CanvasDevice device, int drawCount, int bitmapCount, int value)
{
DrawCount = drawCount;
BitmapCount = bitmapCount;
Value = value;
var bitmaps = new List<CanvasBitmap>();
for (int i = 0; i < bitmapCount; ++i)
{
var bitmap = new CanvasRenderTarget(device, 32, 32, 96);
using (var ds = bitmap.CreateDrawingSession())
{
ds.FillCircle(16, 16, 16, Colors.White);
ds.DrawText(i.ToString(), new Rect(0, 0, 32, 32), Colors.Black,
new CanvasTextFormat()
{
FontFamily = "Comic Sans MS",
HorizontalAlignment = CanvasHorizontalAlignment.Center,
VerticalAlignment = CanvasVerticalAlignment.Center
});
}
bitmaps.Add(bitmap);
}
var rng = new Random();
drawInfo = new List<DrawInfo>();
for (int i = 0; i < drawCount; ++i)
{
drawInfo.Add(new DrawInfo()
{
Bitmap = bitmaps[i % bitmaps.Count],
Position = new Vector2(64.0f + (float)Math.Sin(i * 0.1) * 16, 64.0f + (float)Math.Cos(i * 0.1) * 16),
Rotation = (float)(i * 0.3),
Tint = new Vector4((float)rng.NextDouble(), (float)rng.NextDouble(), (float)rng.NextDouble(), (float)rng.NextDouble())
});
}
}
public void Dispose()
{
foreach (var d in drawInfo)
{
d.Bitmap.Dispose();
}
}
public void AddDataToScenarioRunner(IScenarioRunner runner)
{
foreach (var d in drawInfo)
{
runner.AddSprite(d.Bitmap, d.Tint, d.Position, d.Rotation);
}
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ResourceManager : MonoBehaviour {
public static ResourceManager instance;
void Awake() {
if (instance == null) {
DontDestroyOnLoad (gameObject);
instance = this;
} else if (instance != this) {
Destroy(gameObject);
}
}
/** Main Resources Types **/
public int coins;
public int population;
public int wood;
public int stone;
public int ore;
public int hqLevel;
[Header("UI Elements")]
public Text coinText;
public Text populationText;
public Text woodText;
public Text stoneText;
public Text oreText;
/** Adds Coins **/
public void addCoins(int coins) {
this.coins += coins;
}
/** Checks if user has enough resources to purchase tower **/
public bool hasEnoughResourcesFor(TowerBlueprint towerBlueprint) {
return (
coins >= towerBlueprint.coinsCost &&
population >= towerBlueprint.populationCost &&
wood >= towerBlueprint.woodCost &&
stone >= towerBlueprint.stoneCost &&
ore >= towerBlueprint.oreCost
);
}
/** Checks if user has enough resources to purchase HQ upgrade **/
public bool hasEnoughResourcesFor(HQUpgrade hqUpgrade) {
return (
coins >= hqUpgrade.coinsCost &&
population >= hqUpgrade.populationCost &&
wood >= hqUpgrade.woodCost &&
stone >= hqUpgrade.stoneCost &&
ore >= hqUpgrade.oreCost
);
}
/** Deducts Resources Needed to build Tower **/
public void deductResorcesFor(TowerBlueprint towerBlueprint) {
coins -= towerBlueprint.coinsCost;
population -= towerBlueprint.populationCost;
wood -= towerBlueprint.woodCost;
stone -= towerBlueprint.stoneCost;
ore -= towerBlueprint.oreCost;
}
/** Deducts Resources Needed to upgrade HQ **/
public void deductResorcesFor(HQUpgrade hqUpgrade) {
coins -= hqUpgrade.coinsCost;
population -= hqUpgrade.populationCost;
wood -= hqUpgrade.woodCost;
stone -= hqUpgrade.stoneCost;
ore -= hqUpgrade.oreCost;
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
coinText.text = "" + coins;
populationText.text = "" + population;
woodText.text = "" + wood;
stoneText.text = "" + stone;
oreText.text = "" + ore;
}
#region Trade Functions
public void buyWoodFromVillage() {
float price = Village.instance.tradeTable[0, 1];
if (coins < price) {
UIHelper.instance.showError("Insufficient Funds");
return;
}
coins -= (int)price;
wood += 1;
UIHelper.instance.showNormalMessage("1 Wood Purchased");
}
public void sellWoodToVillage() {
if (wood <= 0) {
UIHelper.instance.showError("Not Enough Lumber");
return;
}
wood -= 1;
coins += (int)Village.instance.tradeTable[0, 0];
UIHelper.instance.showNormalMessage("1 Wood Sold");
}
public void buyStoneFromVillage() {
float price = Village.instance.tradeTable[1, 1];
if (coins < price) {
UIHelper.instance.showError("Insufficient Funds");
return;
}
coins -= (int)price;
stone += 1;
UIHelper.instance.showNormalMessage("1 Stone Purchased");
}
public void sellStoneToVillage() {
if (stone <= 0) {
UIHelper.instance.showError("Not Enough Stones");
return;
}
stone -= 1;
coins += (int)Village.instance.tradeTable[1, 0];
UIHelper.instance.showNormalMessage("1 Stone Sold");
}
public void buySteelFromVillage() {
float price = Village.instance.tradeTable[2, 1];
if (coins < price) {
UIHelper.instance.showError("Insufficient Funds");
return;
}
coins -= (int)price;
ore += 1;
UIHelper.instance.showNormalMessage("1 Steel Purchased");
}
public void sellSteelToVillage() {
if (ore <= 0) {
UIHelper.instance.showError("Not Enough Steel");
return;
}
ore -= 1;
coins += (int)Village.instance.tradeTable[2, 0];
UIHelper.instance.showNormalMessage("1 Steel Sold");
}
public void buyRecruitFromVillage() {
float price = Village.instance.tradeTable[3, 1];
if (coins < price) {
UIHelper.instance.showError("Insufficient Funds");
return;
}
coins -= (int)price;
population += 1;
UIHelper.instance.showNormalMessage("1 Recruit Hired");
}
public void sellRecruitToVillage() {
if (population <= 0) {
UIHelper.instance.showError("Not Enough Recruits");
return;
}
population -= 1;
coins += (int)Village.instance.tradeTable[3, 0];
UIHelper.instance.showNormalMessage("1 Recruit Fired");
}
#endregion
}
|
using log4net.Config;
using Owin;
namespace OwinSelfHostLogging.Logging
{
public static class AppBuilderLoggerExtensions
{
public static void CreateLog4NetLogger(this IAppBuilder app)
{
// This code will load log4net configure from App.config
XmlConfigurator.Configure();
}
}
}
|
using System;
namespace FluidDbClient.Sandbox.Models
{
public class Widget
{
public Widget(int widgetId, Guid globalId, string name, string description)
{
WidgetId = widgetId;
GlobalId = globalId;
Name = name;
Description = description;
}
public int WidgetId { get; }
public Guid GlobalId { get; }
public string Name { get; }
public string Description { get; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.CompilerServices;
using GGGG.Interface;
namespace GGGG.Algorithms
{
//public class MonteCache
//{
// LruCache<string, MonteCacheEntry> internalCache;
// public MonteCache()
// {
// internalCache = new LruCache<string, MonteCacheEntry>(new TimeSpan(0, 60, 0), 500000, 10000);
// }
// [MethodImpl(MethodImplOptions.Synchronized)]
// public void CacheBoard(Board board, double eval, int currentDepth)
// {
// int max = currentDepth + 14;
// max = Math.Min(max, board.MoveHistory.Count);
// for (int i = currentDepth; i < max; i++)
// {
// string hash = board.MoveHistory[i];
// AddOrUpdateEntry(hash, eval,currentDepth);
// }
// }
// [MethodImpl(MethodImplOptions.Synchronized)]
// public MonteCacheEntry GetCachedBoardEvals(string hash)
// {
// var result = internalCache.GetObject(hash);
// if(result == null)
// return new MonteCacheEntry();
// return result;
// }
// public void AddOrUpdateEntry(string hash, double eval, int currentDepth)
// {
// var item = internalCache.GetObject(hash);
// if (item == null)
// item = new MonteCacheEntry();
// //Item is higher in the tree than the curret depth, reset all stats (pass)
// if(item.Depth < currentDepth)
// {
// item = new MonteCacheEntry {Depth = currentDepth};
// }
// if (eval > 0)
// item.WhiteWon += 1;
// else
// item.BlackWon += 1;
// internalCache.AddObject(hash, item);
// }
//}
}
|
namespace FoxOffice.Domain
{
using Autofac;
using FluentAssertions;
using Khala.Messaging;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
[TestClass]
public class DomainModule_specs
{
[TestMethod]
public void sut_inherits_Module()
{
typeof(DomainModule).Should().BeDerivedFrom<Module>();
}
private static IContainer BuildContainer()
{
var builder = new ContainerBuilder();
builder.RegisterInstance(Mock.Of<IMessageSerializer>());
builder.RegisterInstance(Mock.Of<IMessageBus>());
var module = new DomainModule(
Storage.ConnectionString, Storage.EventStoreTableName);
builder.RegisterModule(module);
return builder.Build();
}
[TestMethod]
public void sut_registers_Theater_factory_service_correctly()
{
IContainer container = BuildContainer();
container.AssertFactoryRegistered(Theater.Factory);
}
[TestMethod]
public void sut_registers_Theater_repository_service()
{
IContainer container = BuildContainer();
container.AssertRepositoryRegistered<Theater>();
}
[TestMethod]
public void sut_registers_TheaterCommandHandler_service()
{
IContainer container = BuildContainer();
container.AssertServiceRegistered<TheaterCommandHandler>();
}
[TestMethod]
public void sut_registers_Movie_factory_service_correctly()
{
IContainer container = BuildContainer();
container.AssertFactoryRegistered(Movie.Factory);
}
[TestMethod]
public void sut_registers_Movie_repository_service()
{
IContainer container = BuildContainer();
container.AssertRepositoryRegistered<Movie>();
}
[TestMethod]
public void sut_registers_MovieCommandHandler_service()
{
IContainer container = BuildContainer();
container.AssertServiceRegistered<MovieCommandHandler>();
}
}
}
|
using UnityEngine.UI;
using System;
namespace FanLang
{
/// <summary>
/// <see cref="Toggle"/> binding that makes it easier to manage toggle value change subscriptions.
/// </summary>
public class ToggleBinding : IDisposable
{
private Toggle toggle;
private Func<bool> getData;
private Action<bool> setData;
public ToggleBinding(Toggle toggle, Func<bool> getData, Action<bool> setData)
{
this.toggle = toggle;
this.getData = getData;
this.setData = setData;
toggle.SetIsOnWithoutNotify(getData());
toggle.onValueChanged.AddListener(OnInputChanged);
}
public void Dispose()
{
if (toggle != null)
{
toggle.onValueChanged.RemoveListener(OnInputChanged);
}
}
private void OnInputChanged(bool value)
{
setData(value);
}
}
} |
using ServiceStack;
namespace Api.Interfaces.ServiceOperations.Doctors
{
[Route("/doctors", "POST")]
public class RegisterDoctorRequest : PostOperation<RegisterDoctorResponse>
{
public string ClinicId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
} |
using System;
using System.Runtime.CompilerServices;
namespace Base64
{
/// <summary>
///
/// </summary>
public class Base64DecoderConstant : Base64Constant, IDecoder
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static byte Base64CharToByte(byte c, bool urlSafe)
{
int c1 = urlSafe ? '-' : '+';
int c2 = urlSafe ? '_' : '/';
int x =
(ConstantGreaterThenOrEquals(c, 'A') & ConstantLessThenOrEquals(c, 'Z') & (c - 'A')) |
(ConstantGreaterThenOrEquals(c, 'a') & ConstantLessThenOrEquals(c, 'z') & (c - ('a' - 26))) |
(ConstantGreaterThenOrEquals(c, '0') & ConstantLessThenOrEquals(c, '9') & (c - ('0' - 52))) |
(ConstantEquals(c, c1) & 62) |
(ConstantEquals(c, c2) & 63);
return (byte) (x | (ConstantEquals(x, 0) & (ConstantEquals(c, 'A') ^ 0xFF)));
}
public void Decode(Span<byte> dst, ReadOnlySpan<byte> base64, Variant variant)
{
int accLen = 0, b64Pos = 0, binPos = 0;
ulong acc = 0;
bool isUrlSafe = ((int) variant & (int) Mask.UrlSafe) > 0;
while (b64Pos < base64.Length)
{
byte c = base64[b64Pos];
byte d = Base64CharToByte(c, isUrlSafe);
if (d == 0xFF)
{
break;
}
acc = (acc << 6) + d;
accLen += 6;
if (accLen >= 8)
{
accLen -= 8;
dst[binPos++] = (byte) ((acc >> accLen) & 0xFF);
}
b64Pos++;
}
// Check for padding
if (((int) variant & (int) Mask.NoPadding) == 0)
{
int paddingLen = accLen / 2;
byte c;
while (paddingLen > 0)
{
c = base64[b64Pos];
if (c == 61) // =
{
paddingLen--;
}
b64Pos++;
}
}
else if (b64Pos != base64.Length)
{
throw new Exception("Cannot decode base64");
}
}
/// <summary>
/// Decodes base64 string into buffer (byte array) with variants
/// 1. Standard with padding
/// 2. Standard with no padding
/// 3. UrlSafe with padding
/// 4. UrlSafe with no padding
/// </summary>
/// <param name="base64">Base64 Encoded string</param>
/// <param name="variant">Variant used in encoding</param>
/// <returns>Return Memory>byte< with underlying byte buffer or null on error</returns>
public Memory<byte> Decode(ReadOnlySpan<byte> base64, Variant variant)
{
byte[] data = new byte[EncodedLengthToBytes(base64)];
Decode(data, base64, variant);
return data;
}
}
} |
using System;
namespace Concept.Tuple.Lesson2 {
class Main {
// private delegate void ShowDelegate();
// private ShowDelegate ShowAction { get; set; }
private Action ShowAction { get; set; }
private Action<string> ShowMessageAction { get; set; }
public void Run() {
ShowAction = HelloShow;
ShowMessageAction = HelloShowMessage;
ShowAction();
ShowMessageAction("Lesson 2.");
}
private void HelloShow() => Console.WriteLine("Hello world !!");
private void HelloShowMessage(string message) => Console.WriteLine($"Hello world !! {message}");
}
}
|
using Piranha.AttributeBuilder;
using Piranha.Extend.Fields;
using Piranha.Models;
namespace NorthwindCms.Models.Regions
{
public class ProductRegion
{
[Field(Title = "Product ID")]
public NumberField ProductID { get; set; }
[Field(Title = "Product name")]
public TextField ProductName { get; set; }
[Field(Title = "Unit price",
Options = FieldOption.HalfWidth)]
public StringField UnitPrice { get; set; }
[Field(Title = "Units in stock",
Options = FieldOption.HalfWidth)]
public NumberField UnitsInStock { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using YourSpace.Areas.Identity;
using YourSpace.Modules.Moderation.Models;
namespace YourSpace.Services
{
public interface ISUsers
{
public Task<List<MIdentityUser>> GetUsers(int page, MUserFilter filter = null);
public int GetTotalPagesUsers();
}
}
|
@model OOM.Model.Expression
@{
ViewBag.Title = "Expression details";
}
<ul class="breadcrumb">
<li>@Html.ActionLink("Home", "Index", "Home")</li>
<li>@Html.ActionLink("Expressions", "List")</li>
<li class="active">Details</li>
</ul>
<h2>Expression details</h2>
<div>
<dl class="dl-horizontal">
<dt>
@Html.DisplayNameFor(model => model.Name)
</dt>
<dd>
@Html.DisplayFor(model => model.Name)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Formula)
</dt>
<dd>
@Html.DisplayFor(model => model.Formula)
</dd>
<dt>
@Html.DisplayNameFor(model => model.TargetType)
</dt>
<dd>
@Html.DisplayFor(model => model.TargetType)
</dd>
</dl>
</div> |
namespace SecurityConsultantCore.Thievery
{
public class PreferenceMostHidden : Preference
{
public PreferenceMostHidden()
: base((x, y) => -x.Publicity.CompareTo(y.Publicity))
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
using System.Xml;
using Sogeti.Provisioning.Business;
using Sogeti.Provisioning.Business.Interface;
using Sogeti.Provisioning.Domain;
using System.Xml.Linq;
namespace Sogeti.ProvisioningWeb.Models
{
public class SiteTemplateCreationModel : SiteTemplate
{
public IEnumerable<SelectListItem> SiteTemplateList
{
get
{
var result = new List<SelectListItem>
{
new SelectListItem {Value = "0", Text = "[Choose Site Creation Template]"}
};
result.AddRange(SiteCreationTemplates.Select(t => new SelectListItem
{
Value = t.Id.ToString(),
Text = t.Name
}));
return result;
}
}
public IEnumerable<SiteTemplate> SiteCreationTemplates { get; set; }
[Display(Name = "Site Creation Templates")]
public string SelectedSiteCreationTemplate { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using firstwebapp.Models;
using firstwebapp.Data;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
namespace firstwebapp.Pages.Questions
{
[Authorize(Roles = "User")]
public class Vote : PageModel
{
private readonly ApplicationDbContext _context;
public Vote(
ApplicationDbContext context,
UserManager<IdentityUser> userManager
)
{
_context = context;
UserManager = userManager;
}
public Question Question { get; set; }
public int? ID { get; set; }
public bool UpvoteExist = false;
public int VoteCounter = 0;
public UserManager<IdentityUser> UserManager { get; }
public async Task<IActionResult> OnGetAsync(int? id)
{
ID = id;
if (id == null)
{
return NotFound();
}
Question = await _context.Questions.FirstOrDefaultAsync(m => m.ID == id);
try
{
VoteCounter = Question.Vote.Count();
}
catch (Exception)
{
VoteCounter = 0;
}
if (Question == null)
{
return NotFound();
}
var user = await UserManager.GetUserAsync(HttpContext.User);
UpvoteExist = upvoteExist(user, id);
return Page();
}
private bool upvoteExist(IdentityUser user, int? id)
{
var UpvoteExist = false;
if (_context.Votes.Any(d => (d.User.Id == user.Id && d.QuestionId == id)))
{
UpvoteExist = true;
}
return UpvoteExist;
}
public async Task<IActionResult> OnPostAsync(int? id)
{
ID = id;
int Id;
if (id == null)
{
return NotFound();
}
else
{
Id = id.Value;
}
var user = await UserManager.GetUserAsync(HttpContext.User);
if (upvoteExist(user, id))
{
_context.Votes.Remove(_context.Votes.FirstOrDefault(d => d.UserId == user.Id && d.QuestionId == id));
UpvoteExist = false;
}
else
{
_context.Votes.Add(new Votes() { QuestionId = Id, UserId = user.Id });
UpvoteExist = true;
}
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException ex)
{
if (!QuestionExists(Question.ID))
{
return NotFound();
}
else
{
throw new Exception(ex.Message);
}
}
catch (DbUpdateException ex)
{
if(ex.InnerException.Message.Contains("duplicate key"))
{
Question = _context.Questions.FirstOrDefault(d => d.ID == Id);
try
{
VoteCounter = Question.Vote.Count();
}
catch (Exception)
{
VoteCounter = 0;
}
return Page();
}
else
{
throw new Exception(ex.Message);
}
}
return RedirectToPage("./Index");
}
private bool QuestionExists(int id)
{
return _context.Questions.Any(e => e.ID == id);
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class AllowedKey : MonoBehaviour
{
public KeyCode keyCode;
public Image sprite;
public Vector2 defaultPosition;
private void Awake()
{
sprite = GetComponentInChildren<Image>();
defaultPosition = transform.position;
}
public void SetLerp(float lerpDuration)
{
this.lerpDuration = lerpDuration;
}
public void Move()
{
Vector3 target = new Vector3(transform.position.x, valueToLerp, 0f);
if (timeElapsed < lerpDuration)
{
valueToLerp = Mathf.Lerp(startValue, endValue, timeElapsed / lerpDuration);
transform.position = target;
timeElapsed += Time.deltaTime;
}
}
public void DefaultPosition()
{
transform.position = defaultPosition;
lerpDuration = 0f;
}
private void FixedUpdate()
{
}
float timeElapsed;
public float startValue = -0.7f;
public float endValue = -1;
public float valueToLerp;
public float lerpDuration;
void Update()
{
}
}
|
using Castle.ActiveRecord;
using Castle.ActiveRecord.Framework;
using System.ComponentModel.DataAnnotations;
using System;
namespace Mictlanix.BE.Model
{
[ActiveRecord("payment_on_delivery")]
public class PaymentOnDelivery : ActiveRecordLinqBase<PaymentOnDelivery>
{
[PrimaryKey(PrimaryKeyType.Identity, "payment_on_delivery_id")]
public int Id { get; set; }
[BelongsTo ("cash_session")]
public virtual CashSession CashSession { get; set; }
[BelongsTo ("customer_payment", Lazy = FetchWhen.OnInvoke)]
public virtual CustomerPayment CustomerPayment { get; set; }
[Property("paid")]
[Display(Name = "Paid", ResourceType = typeof(Resources))]
public bool IsPaid { get; set; }
[Property]
[DataType (DataType.DateTime)]
[Display (Name = "Date", ResourceType = typeof (Resources))]
public virtual DateTime Date { get; set; }
}
}
|
using System.Threading.Tasks;
using GrainInterfaces;
namespace GrainCollection
{
class HelloGrain : Orleans.Grain, IHello
{
public Task<string> SayHello(string msg)
{
return Task.FromResult(string.Format("You said {0}, I say: Hello!", msg));
}
}
}
|
namespace MagiQL.Expressions.Model
{
public class UnaryExpression : Expression
{
public Expression Expression { get; set; }
public Operator Operator { get; set; }
public UnaryExpression()
{
Operator = Operator.None;
}
public UnaryExpression(Expression expression, Operator op)
{
Expression = expression;
Operator = op;
}
public override object Visit(Visitor visitor)
{
return visitor.Visit(this);
}
public override string ToString()
{
var expr = Expression != null ? Expression.ToString() : "[]";
return GetOperator(Operator) + expr;
}
private string GetOperator(Operator op)
{
switch (op)
{
case Operator.Minus: return "-";
case Operator.Negate: return "!";
}
return "?";
}
}
}
|
// (c) Copyright Microsoft Corporation.
// This source is subject to the Microsoft Public License (Ms-PL).
// Please see http://go.microsoft.com/fwlink/?LinkID=131993 for details.
// All other rights reserved.
using System.Windows;
using System.Windows.Controls;
namespace Microsoft.Silverlight.Testing.Client
{
/// <summary>
/// Represents a control that builds on top of the standard platform Button,
/// offering the ability to modify the corner radii or even use special
/// button modes.
/// </summary>
public class AdvancedButton : Button
{
#region public Visibility SecondaryVisibility
/// <summary>
/// Gets or sets the visibility of a secondary set of visuals in the
/// template.
/// </summary>
public Visibility SecondaryVisibility
{
get { return (Visibility)GetValue(SecondaryVisibilityProperty); }
set { SetValue(SecondaryVisibilityProperty, value); }
}
/// <summary>
/// Identifies the SecondaryVisibility dependency property.
/// </summary>
public static readonly DependencyProperty SecondaryVisibilityProperty =
DependencyProperty.Register(
"SecondaryVisibility",
typeof(Visibility),
typeof(AdvancedButton),
new PropertyMetadata(Visibility.Visible));
#endregion public Visibility SecondaryVisibility
#region public CornerRadius CornerRadius
/// <summary>
/// Gets or sets the corner radius to use.
/// </summary>
public CornerRadius CornerRadius
{
get { return (CornerRadius)GetValue(CornerRadiusProperty); }
set { SetValue(CornerRadiusProperty, value); }
}
/// <summary>
/// Identifies the CornerRadius dependency property.
/// </summary>
public static readonly DependencyProperty CornerRadiusProperty =
DependencyProperty.Register(
"CornerRadius",
typeof(CornerRadius),
typeof(AdvancedButton),
new PropertyMetadata(new CornerRadius(1)));
#endregion public CornerRadius CornerRadius
}
} |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows.Input;
using Xamarin.Forms;
using Xamvvm;
namespace FFImageLoading.Forms.Sample
{
public class ListPageModel : BasePageModel
{
public ListPageModel()
{
ItemSelectedCommand = new BaseCommand<SelectedItemChangedEventArgs>((arg) =>
{
SelectedItem = null;
});
}
public ListItem SelectedItem { get; set; }
public ICommand ItemSelectedCommand { get; set; }
public ObservableCollection<ListItem> Items { get; set; }
public void Reload()
{
var list = new List<ListItem>();
string[] images = {
"https://farm9.staticflickr.com/8625/15806486058_7005d77438.jpg",
"https://farm5.staticflickr.com/4011/4308181244_5ac3f8239b.jpg",
"https://farm8.staticflickr.com/7423/8729135907_79599de8d8.jpg",
"https://farm3.staticflickr.com/2475/4058009019_ecf305f546.jpg",
"https://farm6.staticflickr.com/5117/14045101350_113edbe20b.jpg",
"https://farm2.staticflickr.com/1227/1116750115_b66dc3830e.jpg",
"https://farm8.staticflickr.com/7351/16355627795_204bf423e9.jpg",
"https://farm1.staticflickr.com/44/117598011_250aa8ffb1.jpg",
"https://farm8.staticflickr.com/7524/15620725287_3357e9db03.jpg",
"https://farm9.staticflickr.com/8351/8299022203_de0cb894b0.jpg",
"https://farm4.staticflickr.com/3688/10684479284_211f2a8b0f.jpg",
"https://farm6.staticflickr.com/5755/20725502975_0dd9b4c5f2.jpg",
"https://farm4.staticflickr.com/3732/9308209014_ea8eac4387.jpg",
"https://farm4.staticflickr.com/3026/3096284216_8b2e8da102.jpg",
"https://farm3.staticflickr.com/2915/14139578975_42d87d2d00.jpg",
"https://farm4.staticflickr.com/3900/14949063062_a92fc5426f.jpg",
"https://farm9.staticflickr.com/8514/8349332314_e1ae376fd4.jpg",
"https://farm3.staticflickr.com/2241/2513217764_740fdd6afa.jpg",
"https://farm6.staticflickr.com/5083/5377978827_51d978d271.jpg",
"https://farm4.staticflickr.com/3626/3499605313_a9d43c1c83.jpg",
"https://farm1.staticflickr.com/16/19438696_f103861437.jpg",
"https://farm3.staticflickr.com/2221/2243980018_d2925f3d77.jpg",
"https://farm8.staticflickr.com/7338/8719134406_74a21b617c.jpg",
"https://farm6.staticflickr.com/5149/5626285743_ae6a75dde7.jpg",
"https://farm5.staticflickr.com/4105/4963731276_a10e1bd520.jpg",
"https://farm4.staticflickr.com/3270/2814060518_6305796eb1.jpg",
"https://farm7.staticflickr.com/6183/6123785115_2c17b85328.jpg",
"https://farm3.staticflickr.com/2900/14398989204_59f60a05c5.jpg",
"https://farm3.staticflickr.com/2136/1756449787_c93e6eb647.jpg",
"https://farm4.staticflickr.com/3201/3070391067_c80fb9e942.jpg"
};
for (int j = 0; j < 5; j++)
{
for (int i = 0; i < images.Length; i++)
{
var item1 = new ListItem()
{
ImageUrl = images[i],
FileName = string.Format("image{0}.jpeg", i + 1),
};
list.Add(item1);
var item2 = new ListItem()
{
ImageUrl = images[i],
FileName = string.Format("image{0}.jpeg", i + 1),
};
list.Add(item2);
var item3 = new ListItem()
{
ImageUrl = images[i],
FileName = string.Format("image{0}.jpeg", i + 1),
};
list.Add(item3);
}
}
Items = new ObservableCollection<ListItem>(list);
}
public class ListItem : BaseModel
{
public string ImageUrl { get; set; }
public string FileName { get; set; }
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace RarLib {
public class TRarElement {
public string Name { get; set; }
public string Pathname { get; set; }
public string Fullname {
get {
return ((Pathname ?? "") == "" ? "" : Pathname + "\\") + Name;
}
}
public double CompressionRatio { get; private set; }
public long UncompressedSize {get; private set;}
public long CompressedSize { get; private set; }
public string Attributes {get;private set;}
public bool IsFolder { get; private set; }
#region Constructor(s)
public TRarElement() {
Name = "";
Pathname = "";
CompressionRatio = 0d;
}
public TRarElement(string name, string codedInfo = "")
: this() {
if (name.Contains("\\")) {
Name = name.Substring(name.LastIndexOf("\\") + 1);
Pathname = name.Substring(0, name.LastIndexOf("\\"));
} else {
Name = name;
Pathname = "";
}
if (codedInfo != "") {
_Parse(codedInfo);
}
}
private void _Parse(string codedInfo) {
string[] SplittedInfo = codedInfo.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
UncompressedSize = long.Parse(SplittedInfo[0]);
CompressedSize = long.Parse(SplittedInfo[1]);
CompressionRatio = double.Parse(SplittedInfo[2].TrimEnd('%'));
Attributes = SplittedInfo[5];
IsFolder = Attributes.Contains('D');
}
#endregion Constructor(s)
public override string ToString() {
StringBuilder RetVal = new StringBuilder();
RetVal.AppendFormat("\"{0}\"", Fullname);
if (!IsFolder) {
RetVal.AppendFormat(", Compression Ratio={0}%", CompressionRatio);
RetVal.AppendFormat(", Size={0}", UncompressedSize);
RetVal.AppendFormat(", Compressed={0}", CompressedSize);
}
return RetVal.ToString();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace weixin.work.Response.msgaudit
{
public class Response_getpermituserlist:Response_base
{
public List<string> ids { get; set; }
}
}
|
using SFML.Audio;
using System;
using System.IO;
class Audio
{
// Lista dos sons
public enum Sounds
{
Click = 1,
Above,
Rain,
Thunder_1,
Thunder_2,
Thunder_3,
Thunder_4,
Amount
}
// Listas das músicas
public enum Musics
{
Menu = 1,
Amount
}
public class Sound
{
// Formato em o dispositivo irá ler os sons
public const string Format = ".wav";
// Dispositivo sonoro
private static SFML.Audio.Sound[] List;
public static void Load()
{
// Redimensiona a lista
Array.Resize(ref List, (byte)Sounds.Amount);
// Carrega todos os arquivos e os adiciona a lista
for (int i = 1; i < List.Length; i++)
List[i] = new SFML.Audio.Sound(new SoundBuffer(Directories.Sounds.FullName + i + Format));
}
public static void Play(Sounds Index, bool Loop = false)
{
// Apenas se necessário
if (!Lists.Options.Sounds) return;
// Reproduz o áudio
List[(byte)Index].Volume = 20;
List[(byte)Index].Loop = Loop;
List[(byte)Index].Play();
}
public static void Stop_All()
{
// Apenas se necessário
if (List == null) return;
// Para todos os sons
for (byte i = 1; i < (byte)Sounds.Amount; i++)
List[i].Stop();
}
}
public class Music
{
// Formato em o dispositivo irá ler as músicas
public const string Format = ".ogg";
// Lista das músicas
private static SFML.Audio.Music Device;
// Index da música reproduzida atualmente
private static byte Current;
public static void Play(Musics Index, bool Loop = false)
{
string Directory = Directories.Musics.FullName + (byte)Index + Format;
// Apenas se necessário
if (Device != null) return;
if (!Lists.Options.Musics) return;
if (!File.Exists(Directory)) return;
// Carrega o áudio
Device = new SFML.Audio.Music(Directory);
Device.Loop = true;
Device.Volume = 20;
Device.Loop = Loop;
// Reproduz
Device.Play();
Current = (byte)Index;
}
public static void Stop()
{
// Para a música que está tocando
if (Device != null && Current != 0)
{
Device.Stop();
Device.Dispose();
Device = null;
}
}
}
} |
using System.Collections.Generic;
using ESFA.DC.Data.DAS.Model;
namespace ESFA.DC.ILR.ReportService.Service.Comparer
{
public sealed class DasCommitmentsComparer : IEqualityComparer<DasCommitments>
{
public bool Equals(DasCommitments x, DasCommitments y)
{
if (x == null && y != null)
{
return false;
}
if (x != null && y == null)
{
return false;
}
if (x == null && y == null)
{
return true;
}
return x.CommitmentId == y.CommitmentId && x.VersionId == y.VersionId;
}
public int GetHashCode(DasCommitments obj)
{
unchecked
{
int hash = 17;
hash = (hash * 23) + obj.CommitmentId.GetHashCode();
hash = (hash * 23) + obj.VersionId.GetHashCode();
return hash;
}
}
}
}
|
using ASPNETCore2JwtAuthentication.DomainClasses;
namespace ASPNETCore2JwtAuthentication.Services;
public interface ITokenStoreService
{
Task AddUserTokenAsync(UserToken userToken);
Task AddUserTokenAsync(User user, string refreshTokenSerial, string accessToken, string refreshTokenSourceSerial);
Task<bool> IsValidTokenAsync(string accessToken, int userId);
Task DeleteExpiredTokensAsync();
Task<UserToken> FindTokenAsync(string refreshTokenValue);
Task DeleteTokenAsync(string refreshTokenValue);
Task DeleteTokensWithSameRefreshTokenSourceAsync(string refreshTokenIdHashSource);
Task InvalidateUserTokensAsync(int userId);
Task RevokeUserBearerTokensAsync(string userIdValue, string refreshTokenValue);
} |
using System;
using System.Threading.Tasks;
namespace Demos.SharedCode.ConfigHandling {
public interface IConfigService<T> where T : class, new() {
T Settings { get; }
T ReadSettingsFile();
void WriteSettings(T obj);
bool SettingsExist { get; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace BFNet.Execution
{
public static class Utils
{
public static char ToAsciiCode(this short input) => (char) input;
public static short ToChar(this char input) => (short) input;
public static void SafeIncrement(ref IList<short> cells, int index, short amount = 1)
{
SafeSet(ref cells, index, (short) (cells.ElementAtOrDefault(index) + amount));
}
public static void SafeSet(ref IList<short> cells, int index, short amount)
{
try
{
// Try to just set the value simply
cells[index] = amount;
}
catch (ArgumentOutOfRangeException) // Value does not already exist
{
// If required, populate previous cells with default of 0
for (var i = cells.Count; i < index; i++) cells.Insert(i, default);
// Set value
cells.Insert(index, amount);
}
}
}
} |
using System.Collections.Generic;
using System.ComponentModel;
using System.Threading.Tasks;
namespace OpenTracker.Models.AutoTracking
{
/// <summary>
/// This is the interface containing autotracking data and methods
/// </summary>
public interface IAutoTracker : INotifyPropertyChanged
{
List<string> Devices { get; }
bool RaceIllegalTracking { get; set; }
Dictionary<ulong, IMemoryAddress> MemoryAddresses { get; }
ConnectionStatus Status { get; }
Task InGameCheck();
Task MemoryCheck();
Task GetDevices();
Task Disconnect();
Task Connect(string uriString);
bool CanConnect();
bool CanDisconnect();
bool CanGetDevices();
bool CanStart();
Task Start(string device);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace SFog.Models.Queues
{
public class AllocatedServer
{
private string serverID;
public string ServerID
{
get { return serverID; }
set { serverID = value; }
}
private Tuple tuple;
public Tuple Tuple
{
get { return tuple; }
set { tuple = value; }
}
public AllocatedServer(string serverId, Tuple tuple)
{
ServerID = serverId;
Tuple = tuple;
}
}
public class ServerQueue
{
private string serverId;
public string ServerId
{
get { return serverId; }
set { serverId = value; }
}
private Queue<List<Tuple>> tupleQueue;
public Queue<List<Tuple>> TupleQueue
{
get { return tupleQueue; }
set { tupleQueue = value; }
}
public ServerQueue(string serverId, List<Tuple> Tuple)
{
ServerId = serverId;
TupleQueue.Enqueue(Tuple);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Library
{
public class Sudoku4 : Library.Matrix
{
public Sudoku4()
: base(4, new RangeSet4(), new RangeSet4())
{ }
public Sudoku4(int[,] data)
: base(4, new RangeSet4(), new RangeSet4(), data)
{}
public class RangeSet4 : HashSet<Matrix.Range>
{
public RangeSet4()
{
this.Add(new Matrix.Range(0, 2));
this.Add(new Matrix.Range(2, 2));
}
}
}
}
|
@using Telerik.Sitefinity.DynamicModules.Model
@using Telerik.Sitefinity.Model
@model IQueryable<DynamicContent>
<h1>
Projects
</h1>
<ul>
@foreach (var project in @Model)
{
<li>@Html.ActionLink(project.GetString("Title"), "Detail", new { urlName = project.UrlName })</li>
}
</ul> |
//<Snippet1>
using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
public class Group{
public string GroupName;
public GroupType Grouptype;
}
public enum GroupType{
// Use the SoapEnumAttribute to instruct the XmlSerializer
// to generate Small and Large instead of A and B.
[SoapEnum("Small")]
A,
[SoapEnum("Large")]
B
}
public class Run {
static void Main(){
Run test= new Run();
test.SerializeObject("SoapEnum.xml");
test.SerializeOverride("SoapOverride.xml");
Console.WriteLine("Fininished writing two files");
}
private void SerializeObject(string filename){
// Create an instance of the XmlSerializer Class.
XmlTypeMapping mapp =
(new SoapReflectionImporter()).ImportTypeMapping(typeof(Group));
XmlSerializer mySerializer = new XmlSerializer(mapp);
// Writing the file requires a TextWriter.
TextWriter writer = new StreamWriter(filename);
// Create an instance of the Class that will be serialized.
Group myGroup = new Group();
// Set the object properties.
myGroup.GroupName = ".NET";
myGroup.Grouptype= GroupType.A;
// Serialize the Class, and close the TextWriter.
mySerializer.Serialize(writer, myGroup);
writer.Close();
}
private void SerializeOverride(string fileName){
SoapAttributeOverrides soapOver = new SoapAttributeOverrides();
SoapAttributes SoapAtts = new SoapAttributes();
// Add a SoapEnumAttribute for the GroupType.A enumerator.
// Instead of 'A' it will be "West".
SoapEnumAttribute soapEnum = new SoapEnumAttribute("West");
// Override the "A" enumerator.
SoapAtts.SoapEnum = soapEnum;
soapOver.Add(typeof(GroupType), "A", SoapAtts);
// Add another SoapEnumAttribute for the GroupType.B enumerator.
// Instead of //B// it will be "East".
SoapAtts= new SoapAttributes();
soapEnum = new SoapEnumAttribute();
soapEnum.Name = "East";
SoapAtts.SoapEnum = soapEnum;
soapOver.Add(typeof(GroupType), "B", SoapAtts);
// Create an XmlSerializer used for overriding.
XmlTypeMapping map =
new SoapReflectionImporter(soapOver).
ImportTypeMapping(typeof(Group));
XmlSerializer ser = new XmlSerializer(map);
Group myGroup = new Group();
myGroup.GroupName = ".NET";
myGroup.Grouptype = GroupType.B;
// Writing the file requires a TextWriter.
TextWriter writer = new StreamWriter(fileName);
ser.Serialize(writer, myGroup);
writer.Close();
}
}
//</Snippet1>
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace KittenzRepositorySample.Data
{
public class JsonRepository : IRepository
{
private static readonly List<DadJoke> _DadJokes;
static JsonRepository()
{
LoadFromJson();
}
private static void LoadFromJson() {
if (_DadJokes != null && _DadJokes.Any()) return;
// do the thing to load the List<DadJoke>
}
public IQueryable<DadJoke> Get()
{
return _DadJokes.AsQueryable();
}
public DadJoke GetRandom() {
return _DadJokes.OrderBy(j => Guid.NewGuid()).First();
}
public DadJoke GetById(int id)
{
return _DadJokes.FirstOrDefault(j => j.Id == id);
}
}
}
|
using NUnit.Framework;
using UnityEngine;
using Random = System.Random;
namespace Archon.SwissArmyLib.Partitioning.Tests
{
[TestFixture]
public class QuadtreeTests
{
private static Vector2 GetPoint(Quadtree<object> tree, float x, float y)
{
var actualX = Mathf.LerpUnclamped(tree.Bounds.xMin, tree.Bounds.xMax, x);
var actualY = Mathf.LerpUnclamped(tree.Bounds.yMin, tree.Bounds.yMax, y);
return new Vector2(actualX, actualY);
}
private static Rect GetRectAtPoint(Quadtree<object> tree, float x, float y)
{
return new Rect(GetPoint(tree, x, y), Vector2.zero);
}
private static Rect GetMinMaxRect(Quadtree<object> tree, float minX, float minY, float maxX, float maxY)
{
var min = GetPoint(tree, minX, minY);
var max = GetPoint(tree, maxX, maxY);
return Rect.MinMaxRect(min.x, min.y, max.x, max.y);
}
private static ItemWithBounds[] FillWithItems(Quadtree<object> tree, int amount, int seed = 0)
{
var random = new Random(seed);
var items = new ItemWithBounds[amount];
for (var i = 0; i < items.Length; i++)
{
var item = new ItemWithBounds(GetRectAtPoint(tree, (float)random.NextDouble(), (float)random.NextDouble()));
items[i] = item;
tree.Insert(item, item.Bounds);
}
return items;
}
[Test]
public void Create_CorrectState()
{
var treeBounds = Rect.MinMaxRect(-500, -400, 300, 200);
var tree = Quadtree<object>.Create(treeBounds, 3, 5);
Assert.AreEqual(0, tree.Count);
Assert.AreEqual(0, tree.Depth);
Assert.AreEqual(5, tree.MaxDepth);
Assert.AreEqual(3, tree.MaxItems);
Assert.IsFalse(tree.IsSplit);
Assert.AreEqual(-500, tree.Bounds.min.x);
Assert.AreEqual(-400, tree.Bounds.min.y);
Assert.AreEqual(300, tree.Bounds.max.x);
Assert.AreEqual(200, tree.Bounds.max.y);
}
[Test]
public void Insert_Centered_AddedInAllSubtrees()
{
var treeBounds = Rect.MinMaxRect(-500, -400, 300, 200);
var tree = Quadtree<object>.Create(treeBounds, 3, 5);
FillWithItems(tree, 3);
var item = new object();
var itemBounds = GetMinMaxRect(tree, 0.4f, 0.4f, 0.6f, 0.6f);
tree.Insert(item, itemBounds);
var topLeftResults = tree.Retrieve(GetRectAtPoint(tree, 0.4f, 0.6f));
var topRightResults = tree.Retrieve(GetRectAtPoint(tree, 0.6f, 0.6f));
var bottomLeftResults = tree.Retrieve(GetRectAtPoint(tree, 0.4f, 0.4f));
var bottomRightResults = tree.Retrieve(GetRectAtPoint(tree, 0.6f, 0.4f));
Assert.IsTrue(tree.IsSplit);
Assert.IsTrue(topLeftResults.Contains(item));
Assert.IsTrue(topRightResults.Contains(item));
Assert.IsTrue(bottomLeftResults.Contains(item));
Assert.IsTrue(bottomRightResults.Contains(item));
}
[Test]
public void Insert_TooManyItems_TreeIsSplit()
{
var treeBounds = Rect.MinMaxRect(-500, -400, 300, 200);
var tree = Quadtree<object>.Create(treeBounds, 2, 5);
for (var i = 0; i < 5; i++)
tree.Insert(null, GetRectAtPoint(tree, 0, 0));
Assert.AreEqual(5, tree.Count);
Assert.IsTrue(tree.IsSplit);
}
[Test]
public void Insert_MaxDepth_NotSplit()
{
var treeBounds = Rect.MinMaxRect(-500, -400, 300, 200);
var tree = Quadtree<object>.Create(treeBounds, 2, 0);
for (var i = 0; i < 5; i++)
tree.Insert(null, GetRectAtPoint(tree, 0, 0));
Assert.AreEqual(5, tree.Count);
Assert.IsFalse(tree.IsSplit);
}
[Test]
public void Retrieve_Empty_NoResults()
{
var treeBounds = Rect.MinMaxRect(-500, -400, 300, 200);
var tree = Quadtree<object>.Create(treeBounds, 3, 5);
var results = tree.Retrieve(GetMinMaxRect(tree, -1, -1, 2, 2));
Assert.AreEqual(0, results.Count);
}
[Test]
public void Retrieve_CorrectResults()
{
var treeBounds = Rect.MinMaxRect(-500, -400, 300, 200);
var tree = Quadtree<object>.Create(treeBounds, 1, 5);
// Looks somewhat like this:
//
// +----------------+----------------+
// | | |
// | +------------------+ |
// | | | | |
// | | | | |
// | | | | |
// | | | +----------+ |
// | +------------------+ | |
// | | | | |
// +---------------------------------+
// | | | | |
// | | | | |
// | | | | |
// | | | | |
// | | | | |
// | | | | |
// | | +----------+ |
// | | |
// +----------------+----------------+
var topItem = new ItemWithBounds(GetMinMaxRect(tree, 0.1f, 0.6f, 0.7f, 0.9f));
var bottomItem = new ItemWithBounds(GetMinMaxRect(tree, 0.6f, 0.1f, 0.9f, 0.7f));
tree.Insert(topItem, topItem.Bounds);
tree.Insert(bottomItem, bottomItem.Bounds);
// sorry for anybody who is reading this shitty code..
var topLeft = tree.Retrieve(GetMinMaxRect(tree, 0, 0.51f, 0.49f, 1f));
var topRight = tree.Retrieve(GetMinMaxRect(tree, 0.51f, 0.51f, 1, 1));
var bottomLeft = tree.Retrieve(GetMinMaxRect(tree, 0, 0, 0.49f, 0.49f));
var bottomRight = tree.Retrieve(GetMinMaxRect(tree, 0.51f, 0, 1, 0.49f));
// better names anybody? please?
// ReSharper disable InconsistentNaming
var topRight_topLeft = tree.Retrieve(GetMinMaxRect(tree, 0.51f, 0.76f, 0.74f, 1));
var topRight_topRight = tree.Retrieve(GetMinMaxRect(tree, 0.76f, 0.76f, 1, 1));
var topRight_bottomLeft = tree.Retrieve(GetMinMaxRect(tree, 0.51f, 0.51f, 0.74f, 0.74f));
var topRight_bottomRight = tree.Retrieve(GetMinMaxRect(tree, 0.76f, 0.51f, 1, 0.74f));
// ReSharper restore InconsistentNaming
Assert.IsTrue(tree.IsSplit);
Assert.AreEqual(1, topLeft.Count);
Assert.AreEqual(2, topRight.Count);
Assert.AreEqual(0, bottomLeft.Count);
Assert.AreEqual(1, bottomRight.Count);
Assert.AreEqual(1, topRight_topLeft.Count);
Assert.AreEqual(0, topRight_topRight.Count);
Assert.AreEqual(2, topRight_bottomLeft.Count);
Assert.AreEqual(1, topRight_bottomRight.Count);
Assert.IsTrue(topLeft.Contains(topItem));
Assert.IsTrue(bottomRight.Contains(bottomItem));
}
[Test]
public void Remove_SubtreesMerged()
{
var treeBounds = Rect.MinMaxRect(-500, -400, 300, 200);
var tree = Quadtree<object>.Create(treeBounds, 4, 5);
var items = FillWithItems(tree, tree.MaxItems + 1);
tree.Remove(items[0], items[0].Bounds);
Assert.IsFalse(tree.IsSplit);
}
[Test]
public void Remove_RemovedFromNodes()
{
var treeBounds = Rect.MinMaxRect(-500, -400, 300, 200);
var tree = Quadtree<object>.Create(treeBounds, 4, 5);
var items = FillWithItems(tree, 20);
tree.Remove(items[0], items[0].Bounds);
var results = tree.Retrieve(GetMinMaxRect(tree, -1, -1, 2, 2));
Assert.IsFalse(results.Contains(items[0]));
}
[Test]
public void Clear_AllRemoved()
{
var treeBounds = Rect.MinMaxRect(-500, -400, 300, 200);
var tree = Quadtree<object>.Create(treeBounds, 3, 5);
var random = new Random(0);
for (var i = 0; i < 50; i++)
{
var x = (float) random.NextDouble();
var y = (float) random.NextDouble();
tree.Insert(null, GetRectAtPoint(tree, x, y));
}
tree.Clear();
Assert.AreEqual(0, tree.Count);
Assert.IsFalse(tree.IsSplit);
}
private class ItemWithBounds
{
public readonly Rect Bounds;
public ItemWithBounds(Rect bounds)
{
Bounds = bounds;
}
}
}
}
|
using System;
namespace cn.SMSSDK.Unity
{
public class UserInfo
{
public string uid;
public string phoneNumber;
public string avatar;
public string nickName;
public string zone;
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using BLL;
using Model;
using xxxxx.Interop;
namespace UI
{
/// <summary>
/// MyBook.xaml 的交互逻辑
/// </summary>
public partial class MyBook : Page
{
int uid;
List<MyBorrow> books = new List<MyBorrow>();
public MyBook(string x)
{
uid = int.Parse(x);
InitializeComponent();
initView();
}
public void initView()
{
bookListView.Items.Clear();
books = new userBook_BLL().GetMyBorrows(uid);
foreach (MyBorrow b in books)
{
string status = "";
if (b.borrowtime == -1)
{
status = "丢失";
}
else if (DateTime.Compare(DateTime.Now, Convert.ToDateTime(b.time)) > 0)
{
status = "已超出还书期限";
}
else
{
switch (b.borrowtime)
{
case 1:
status = "初次借阅";
break;
case 2:
status = "已经续借";
break;
}
}
bookListView.Items.Add(new
{
c1 = b.bname,
c2 = b.author,
c3 = b.publisher,
c4 = b.time,
c5=status,
c6= (status == "初次借阅" ? Visibility.Visible : Visibility.Collapsed),
c7 = (status == "丢失" ? Visibility.Collapsed : Visibility.Visible)
});
}
}
private void order(object sender, RoutedEventArgs e)
{
var a = this.bookListView.SelectedItem;
string b = (a.GetType().GetProperty("c1").GetValue(a, null)).ToString();
string c = (a.GetType().GetProperty("c4").GetValue(a, null)).ToString();
new bookitBLL().order(b, uid, c);
initView();
OBJ o = new OBJ();
o.push("续借成功!");
}
public void lose(object sender, RoutedEventArgs e)
{
var a = this.bookListView.SelectedItem;
string b = (a.GetType().GetProperty("c1").GetValue(a, null)).ToString();
new bookitBLL().lose(uid, b);
initView();
OBJ o = new OBJ();
o.push("挂失成功!");
}
private void BookListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
namespace CoralEngine
{
public enum BouncerMode : int { Additive, Subtractive, Absolute }
public class Bouncer : Entity
{
public List<Entity> TouchedEntities = new List<Entity>();
public Vector2 AddVelocity;
public BouncerMode Mode;
public override void Serialize(System.IO.BinaryWriter writer)
{
base.Serialize(writer);
writer.Write(AddVelocity.X);
writer.Write(AddVelocity.Y);
writer.Write((int)Mode);
}
public override void Deserialize(System.IO.BinaryReader reader)
{
base.Deserialize(reader);
AddVelocity = new Vector2(reader.ReadSingle(), reader.ReadSingle());
Mode = (BouncerMode)reader.ReadInt32();
}
public override void Update(GameTime gameTime)
{
foreach (Entity ent in Engine.World.Entities)
{
if (ent.GetCollision().Intersects(GetCollision()))
{
if (ent.Dynamic && !TouchedEntities.Contains(ent))
{
TouchedEntities.Add(ent);
switch (Mode)
{
case BouncerMode.Additive: ent.Velocity += AddVelocity; break;
case BouncerMode.Subtractive: ent.Velocity -= AddVelocity; break;
case BouncerMode.Absolute: ent.Velocity = new Vector2(AddVelocity.X, AddVelocity.Y); break;
}
}
}
else if (TouchedEntities.Contains(ent))
TouchedEntities.Remove(ent);
}
base.Update(gameTime);
}
public override void Render(SpriteBatch spriteBatch)
{
if (Engine.RenderDebug)
spriteBatch.Draw(EngineContent.Textures.Pixel, GetRenderRectangle(), new Color(255, 0, 128, 90));
base.Render(spriteBatch);
}
}
}
|
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("PashuaNetBindings.Tests")]
namespace Pashua
{
/// <summary>
/// Internal interface used to set results on the element.
/// </summary>
internal interface IHaveResults
{
/// <summary>
/// Intentionally shadows <see cref="IPashuaControl.Id"/>
/// </summary>
string Id { get; }
/// <summary>
/// Sets the raw result on the control.
/// </summary>
/// <param name="result">The raw result.</param>
void SetResult(string result);
}
}
|
using System;
public class Example
{
public static void Main()
{
ConvertInt16();
Console.WriteLine("-----");
ConvertInt64();
Console.WriteLine("-----");
ConvertObject();
Console.WriteLine("-----");
ConvertSByte();
Console.WriteLine("----");
ConvertUInt16();
Console.WriteLine("-----");
ConvertUInt32();
Console.WriteLine("------");
ConvertUInt64();
Console.WriteLine("-----");
ConvertString();
}
private static void ConvertInt16()
{
// <Snippet1>
short[] numbers = { Int16.MinValue, -1032, 0, 192, Int16.MaxValue };
double result;
foreach (short number in numbers)
{
result = Convert.ToDouble(number);
Console.WriteLine("Converted the UInt16 value {0} to {1}.",
number, result);
}
// Converted the UInt16 value -32768 to -32768.
// Converted the UInt16 value -1032 to -1032.
// Converted the UInt16 value 0 to 0.
// Converted the UInt16 value 192 to 192.
// Converted the UInt16 value 32767 to 32767.
// </Snippet1>
}
private static void ConvertInt64()
{
// <Snippet2>
long[] numbers = { Int64.MinValue, -903, 0, 172, Int64.MaxValue};
double result;
foreach (long number in numbers)
{
result = Convert.ToDouble(number);
Console.WriteLine("Converted the {0} value '{1}' to the {2} value {3}.",
number.GetType().Name, number,
result.GetType().Name, result);
}
// The example displays the following output:
// Converted the Int64 value '-9223372036854775808' to the Double value -9.22337203685478E+18.
// Converted the Int64 value '-903' to the Double value -903.
// Converted the Int64 value '0' to the Double value 0.
// Converted the Int64 value '172' to the Double value 172.
// Converted the Int64 value '9223372036854775807' to the Double value 9.22337203685478E+18.
// </Snippet2>
}
private static void ConvertObject()
{
// <Snippet3>
object[] values = { true, 'a', 123, 1.764e32f, "9.78", "1e-02",
1.67e03f, "A100", "1,033.67", DateTime.Now,
Decimal.MaxValue };
double result;
foreach (object value in values)
{
try {
result = Convert.ToDouble(value);
Console.WriteLine("Converted the {0} value {1} to {2}.",
value.GetType().Name, value, result);
}
catch (FormatException) {
Console.WriteLine("The {0} value {1} is not recognized as a valid Double value.",
value.GetType().Name, value);
}
catch (InvalidCastException) {
Console.WriteLine("Conversion of the {0} value {1} to a Double is not supported.",
value.GetType().Name, value);
}
}
// The example displays the following output:
// Converted the Boolean value True to 1.
// Conversion of the Char value a to a Double is not supported.
// Converted the Int32 value 123 to 123.
// Converted the Single value 1.764E+32 to 1.76399995098587E+32.
// Converted the String value 9.78 to 9.78.
// Converted the String value 1e-02 to 0.01.
// Converted the Single value 1670 to 1670.
// The String value A100 is not recognized as a valid Double value.
// Converted the String value 1,033.67 to 1033.67.
// Conversion of the DateTime value 10/21/2008 07:12:12 AM to a Double is not supported.
// Converted the Decimal value 79228162514264337593543950335 to 7.92281625142643E+28.
// </Snippet3>
}
private static void ConvertSByte()
{
// <Snippet4>
sbyte[] numbers = { SByte.MinValue, -23, 0, 17, SByte.MaxValue };
double result;
foreach (sbyte number in numbers)
{
result = Convert.ToDouble(number);
Console.WriteLine("Converted the SByte value {0} to {1}.", number, result);
}
// Converted the SByte value -128 to -128.
// Converted the SByte value -23 to -23.
// Converted the SByte value 0 to 0.
// Converted the SByte value 17 to 17.
// Converted the SByte value 127 to 127.
// </Snippet4>
}
private static void ConvertUInt16()
{
// <Snippet5>
ushort[] numbers = { UInt16.MinValue, 121, 12345, UInt16.MaxValue };
double result;
foreach (ushort number in numbers)
{
result = Convert.ToDouble(number);
Console.WriteLine("Converted the UInt16 value {0} to {1}.",
number, result);
}
// The example displays the following output:
// Converted the UInt16 value 0 to 0.
// Converted the UInt16 value 121 to 121.
// Converted the UInt16 value 12345 to 12345.
// Converted the UInt16 value 65535 to 65535.
// </Snippet5>
}
private static void ConvertUInt32()
{
// <Snippet6>
uint[] numbers = { UInt32.MinValue, 121, 12345, UInt32.MaxValue };
double result;
foreach (uint number in numbers)
{
result = Convert.ToDouble(number);
Console.WriteLine("Converted the UInt32 value {0} to {1}.",
number, result);
}
// The example displays the following output:
// Converted the UInt32 value 0 to 0.
// Converted the UInt32 value 121 to 121.
// Converted the UInt32 value 12345 to 12345.
// Converted the UInt32 value 4294967295 to 4294967295.
// </Snippet6>
}
private static void ConvertUInt64()
{
// <Snippet7>
ulong[] numbers = { UInt64.MinValue, 121, 12345, UInt64.MaxValue };
double result;
foreach (ulong number in numbers)
{
result = Convert.ToDouble(number);
Console.WriteLine("Converted the UInt64 value {0} to {1}.",
number, result);
}
// The example displays the following output:
// Converted the UInt64 value 0 to 0.
// Converted the UInt64 value 121 to 121.
// Converted the UInt64 value 12345 to 12345.
// Converted the UInt64 value 18446744073709551615 to 1.84467440737096E+19.
// </Snippet7>
}
// unused
private static void ConvertString()
{
string[] values= { "-1,035.77219", "1AFF", "1e-35",
"1,635,592,999,999,999,999,999,999", "-17.455",
"190.34001", "1.29e325"};
double result;
foreach (string value in values)
{
try {
result = Convert.ToDouble(value);
Console.WriteLine("Converted '{0}' to {1}.", value, result);
}
catch (FormatException) {
Console.WriteLine("Unable to convert '{0}' to a Double.", value);
}
catch (OverflowException) {
Console.WriteLine("'{0}' is outside the range of a Double.", value);
}
}
// The example displays the following output:
// Converted '-1,035.77219' to -1035.77219.
// Unable to convert '1AFF' to a Double.
// Converted '1e-35' to 1E-35.
// Converted '1,635,592,999,999,999,999,999,999' to 1.635593E+24.
// Converted '-17.455' to -17.455.
// Converted '190.34001' to 190.34001.
// '1.29e325' is outside the range of a Double.
}
}
|
using System.Collections.Generic;
using System.Web.Mvc;
using Abp.Localization;
namespace Localink.Platform.Web.Areas.Mpa.Models.Languages
{
public class LanguageTextsViewModel
{
public string LanguageName { get; set; }
public List<SelectListItem> Sources { get; set; }
public List<LanguageInfo> Languages { get; set; }
public string BaseLanguageName { get; set; }
public string TargetValueFilter { get; set; }
public string FilterText { get; set; }
}
} |
namespace Crucis.Protocol
{
public class MessageHandlerAttribute : BaseAttribute
{
public MessageHandlerAttribute()
{
}
}
} |
namespace FootballLeagues.Data.Models
{
public enum Target
{
News,
Player,
Team,
Game
}
}
|
using System;
namespace Cube.Properties
{
class CubeProperties
{
static void Main()
{
double sideOfCube = double.Parse(Console.ReadLine());
string parameter = Console.ReadLine();
double result = (double)CubeParameters(sideOfCube, parameter);
Console.WriteLine("{0:f2}", result);
}
private static double CubeParameters(double num, string parameter)
{
if (parameter == "face")
{
double result = Math.Sqrt(2 * Math.Pow(num, 2));
return result;
}
else if (parameter == "space")
{
double result = Math.Sqrt(3 * Math.Pow(num, 2));
return result;
}
else if (parameter == "volume")
{
double result = Math.Pow(num,3);
return result;
}
else
{
double result = 6 * Math.Pow(num, 2);
return result;
}
}
}
}
|
/* Copyright (c) 2016 Sysprogs OU. All Rights Reserved.
This software is licensed under the Sysprogs BSP Generator License.
https://github.com/sysprogs/BSPTools/blob/master/LICENSE
*/
using BSPEngine;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
namespace CC3200_bsp_generator
{
static class PeripheralRegisterGenerator
{
public class CBaseAdress
{
public string Name;
public ulong adress;
public bool used;
}
private static List<CBaseAdress> lstBaseAdress = null; //list base adress
private static Dictionary<string, ulong> adicAdrrOffsetDriv;
private static SortedList<string, string> adicBitsOffsetDriv;
private static string mNameCurrentAdr;
//---------------------------------
private static bool LoadBaseAdress(string pFileMap)
{
if (!File.Exists(pFileMap)) return false;
//--------Load Adress Base ------------------
lstBaseAdress = new List<CBaseAdress>();
foreach (var ln in File.ReadAllLines(pFileMap))
{
Match m = Regex.Match(ln, @"#define[ \t]+([\w]+)_BASE[ \t]+0x([0-9A-F]+)?.*");
if (m.Success)
lstBaseAdress.Add(new CBaseAdress { Name = m.Groups[1].Value, adress = ParseHex(m.Groups[2].Value) });
}
return true;
}
//---------------------------------
private static void CheckAllBaseAdress()
{
//-----Check base adress
foreach (var ba in lstBaseAdress)
if (ba.used == false)
Console.WriteLine("not used base adress " + ba.Name);
}
//---------------------------------
private static List<HardwareRegisterSet> ProcessParseSetsReg(string aDir)
{
if (!LoadBaseAdress(Path.Combine(aDir, "hw_memmap.h")))
throw new Exception("no map memory file");
//-------Load Registry-------------------------
List<HardwareRegisterSet> setOut = new List<HardwareRegisterSet>();
foreach (var fn in Directory.GetFiles(aDir, "hw_*.h"))
{
var aHR = ProcessRegisterSetNamesList(fn);
if (aHR != null)
setOut.AddRange(aHR);
}
//----------------------
CheckAllBaseAdress();
return setOut;
}
//---------------------------------
public static HardwareRegisterSet[] GeneratePeripheralRegisters(string familyDirectory)
{
// Create the hardware register sets
Console.WriteLine("Process Peripheral Registers");
return (ProcessParseSetsReg(familyDirectory).ToArray());
}
//---------------------------------
private static string ChangeNamePrefixAdress(string pNamePrefix)
{
switch (pNamePrefix ?? "")
{
case "MCSPI":
return "SPI";
case "APPS_RCM":
return "ARCM";
case "FLASH_CTRL":
return "FLASH_CONTROL";
case "MCASP":
return "I2S";
case "MMCHS":
return "SDHOST";
case "STACK_DIE_CTRL":
return "STACKDIE_CTRL";
}
return pNamePrefix;
}
//---------------------------------
public static List<CBaseAdress> GetBaseAdress(string NameReg)
{
var astrShortName = ChangeNamePrefixAdress(NameReg);
return lstBaseAdress.FindAll(p => (astrShortName != "" && p.Name.Contains(astrShortName)));
}
//---------------------------------
private static bool IsExcepMacrosRegisters(string pMacros)
{
string[] astrMacExc = new[] { "#define SHAMD5_HASH512_ODIGEST_O_DATA_M ", "#define SHAMD5_HASH512_IDIGEST_O_DATA_M " };
foreach (var st in astrMacExc)
if (pMacros.StartsWith(st))
return true;
return false;
}
//---------------------------------
private static bool IsParametrMacros(string pMacros, SortedList<string, string> alstOffset)
{
string astrNameSubReg = pMacros;
int idxRegisters = astrNameSubReg.LastIndexOf('_');
while (idxRegisters > 0)
{
astrNameSubReg = astrNameSubReg.Remove(idxRegisters);
string shotNameReg = astrNameSubReg + "_M";
if (alstOffset.ContainsKey(shotNameReg))
{
return true;
}
idxRegisters = astrNameSubReg.LastIndexOf('_');
}
return false;
}
//---------------------------------
private static bool LoadDictonaryRegisters(string pFileName)
{
adicAdrrOffsetDriv = new Dictionary<string, ulong>();
adicBitsOffsetDriv = new SortedList<string, string>();
string strLndef = "";
string astrUserFrendlyName = "";
if (!File.Exists(pFileName))
return false;
foreach (var ln in File.ReadAllLines(pFileName))
{
if (ln.EndsWith(@"\")) // check macros to next string
{
strLndef = ln.Replace(@"\", "");
continue;
}
strLndef = strLndef + ln;
//// The following are defines for the register offsets.
Match m1 = Regex.Match(strLndef, @"#define[ \t]+([\w\d]+)_O_([\w\d]+)[ \t]+0x([0-9A-F]+)");
bool ablExcept = IsExcepMacrosRegisters(strLndef);
if (m1.Success && !ablExcept)
{
adicAdrrOffsetDriv[m1.Groups[1].Value + "_" + m1.Groups[2].Value] = ParseHex(m1.Groups[3].Value);
if (astrUserFrendlyName != m1.Groups[1].Value && astrUserFrendlyName != "")
throw new Exception("different name prefix of registers");
astrUserFrendlyName = m1.Groups[1].Value;
}
else
{
// The following are defines for the bit fields in the register.
m1 = Regex.Match(strLndef, @"#define[ \t]+([\w\d]+)[ \t]+0x([0-9A-F]+)");
if (m1.Success)
if (!IsParametrMacros(m1.Groups[1].Value, adicBitsOffsetDriv) || ablExcept)
adicBitsOffsetDriv[m1.Groups[1].Value] = m1.Groups[2].Value;
}
strLndef = "";
}
mNameCurrentAdr = astrUserFrendlyName;
return true;
}
//---------------------------------
private static List<HardwareRegisterSet> ProcessLoadHardwareRegisterSet()
{
List<HardwareRegisterSet> oReg = new List<HardwareRegisterSet>();
List<HardwareSubRegister> alstSubReg = new List<HardwareSubRegister>();
var aLstPerep = GetBaseAdress(mNameCurrentAdr);
foreach (var perep in aLstPerep)
{
List<HardwareRegister> alstReg = new List<HardwareRegister>();
ulong aBaseAdress = perep.adress;
perep.used = true;
foreach (var reg in adicAdrrOffsetDriv)
{
HardwareRegister Reg = new HardwareRegister();
alstSubReg.Clear();
Reg.Name = reg.Key;
Reg.Address = FormatToHex(reg.Value + aBaseAdress);
Reg.SizeInBits = 32;
foreach (var subReg in adicBitsOffsetDriv)
{
if (subReg.Key.StartsWith(Reg.Name))
{
HardwareSubRegister hsr = new HardwareSubRegister
{
Name = subReg.Key.Remove(0, Reg.Name.Length + 1),
ParentRegister = Reg,
OriginalMacroBase = Reg.Name,
SizeInBits = GetSizeBit(subReg.Value),
FirstBit = GetFirstBit(subReg.Value),
};
if (hsr.SizeInBits == 0)
Console.WriteLine("size subreg 0 " + hsr.Name);
alstSubReg.Add(hsr);
}
}
Reg.SubRegisters = alstSubReg.ToArray();
alstReg.Add(Reg);
}
if (alstReg.Count > 0)
oReg.Add(new HardwareRegisterSet
{
ExpressionPrefix = mNameCurrentAdr,
UserFriendlyName = perep.Name,// astrUserFrendlyName,
Registers = alstReg.ToArray()
});
}
return oReg;
}
//---------------------------------
public static List<HardwareRegisterSet> ProcessRegisterSetNamesList(string pFileName)
{
if(LoadDictonaryRegisters(pFileName))
return (ProcessLoadHardwareRegisterSet());
return null;
}
//---------------------------------
private static int GetSizeBit(string pHex)
{
int aOut = 0;
ulong intHex = ParseHex(pHex);
while (intHex != 0)
{
if ((intHex & 0x01) == 1)
aOut++;
intHex = intHex >> 1;
}
return aOut;
}
//---------------------------------
private static int GetFirstBit(string pHex)
{
int aOut = 0;
ulong intHex = ParseHex(pHex);
if (intHex == 0)
Console.WriteLine(" new Exception(no set bit");
else
while ((intHex & 0x01) != 1)
{
aOut++;
intHex = intHex >> 1;
}
return aOut;
}
//------------------------------
private static ulong ParseHex(string hex)
{
if (hex.StartsWith("0x"))
hex = hex.Substring(2);
return ulong.Parse(hex, System.Globalization.NumberStyles.HexNumber);
}
//---------------------------------
private static string FormatToHex(ulong addr, int length = 32)
{
string format = "0x{0:x" + length / 4 + "}";
return string.Format(format, (uint)addr);
}
//---------------------------------
private static HardwareRegisterSet DeepCopy(HardwareRegisterSet set)
{
HardwareRegisterSet set_new = new HardwareRegisterSet
{
UserFriendlyName = set.UserFriendlyName,
ExpressionPrefix = set.ExpressionPrefix,
};
if (set.Registers != null)
{
set_new.Registers = new HardwareRegister[set.Registers.Length];
for (int i = 0; i < set.Registers.Length; i++)
{
set_new.Registers[i] = DeepCopy(set.Registers[i]);
}
}
return set_new;
}
//---------------------------------
private static HardwareRegister DeepCopy(HardwareRegister reg)
{
HardwareRegister reg_new = new HardwareRegister
{
Name = reg.Name,
Address = reg.Address,
GDBExpression = reg.GDBExpression,
ReadOnly = reg.ReadOnly,
SizeInBits = reg.SizeInBits
};
if (reg.SubRegisters != null)
{
reg_new.SubRegisters = new HardwareSubRegister[reg.SubRegisters.Length];
for (int i = 0; i < reg.SubRegisters.Length; i++)
{
reg_new.SubRegisters[i] = DeepCopy(reg.SubRegisters[i]);
}
}
return reg_new;
}
//---------------------------------
private static HardwareSubRegister DeepCopy(HardwareSubRegister subreg)
{
HardwareSubRegister subreg_new = new HardwareSubRegister
{
Name = subreg.Name,
FirstBit = subreg.FirstBit,
SizeInBits = subreg.SizeInBits,
KnownValues = (subreg.KnownValues != null) ? (KnownSubRegisterValue[])subreg.KnownValues.Clone() : null
};
return subreg_new;
}
}
}
|
namespace BuilderDesignPatternExample
{
public interface IBeverageBuilder
{
void SetBeverageType();
}
} |
// 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 class Base
{
public virtual int Foo(int x)
{
return x + 1;
}
}
// Override via a shared generic.
//
// Jit must be careful to set the right context
// for the shared methods when devirtualizing.
public class Derived<T> : Base
{
public override sealed int Foo(int x)
{
if (typeof(T) == typeof(string))
{
return x + 42;
}
else if (typeof(T) == typeof(int))
{
return x + 31;
}
else
{
return x + 22;
}
}
}
// All calls to Foo should devirtualize, however we can't
// get the b.Foo case yet because we don't recognize b
// as having an exact type.
public class Test_sharedoverride
{
public static int Main()
{
var ds = new Derived<string>();
var dx = new Derived<object>();
var di = new Derived<int>();
var b = new Base();
int resultD = ds.Foo(1) + dx.Foo(1) + di.Foo(1) + b.Foo(1);
return resultD;
}
}
|
using MailKit.Net.Smtp;
using Microsoft.Extensions.Configuration;
using MimeKit;
using System;
using UsuariosApi.Models;
namespace UsuariosApi.Services
{
public class EmailService
{
private IConfiguration _configuration;
public EmailService(IConfiguration configuration)
{
_configuration = configuration;
}
public void EnviarEmail(string[] destinatarios, string assunto, int usuarioId, string code)
{
//Compor uma mensagem
Mensagem mensagem = new Mensagem(destinatarios, assunto, usuarioId, code);
//Converter a mensagem em um e-mail em si
var mensagemDeEmail = CriaCorpoDoEmail(mensagem);
//Enviar e-mail propriamente dito
Enviar(mensagemDeEmail);
}
//Converter a mensagem para enviar ela por email
private MimeMessage CriaCorpoDoEmail(Mensagem mensagem)
{
var mensagemDeEmail = new MimeMessage();
mensagemDeEmail.From.Add(new MailboxAddress("",
_configuration.GetValue<string>("EmailSettings:From")));
mensagemDeEmail.To.AddRange(mensagem.Destinatarios);
mensagemDeEmail.Subject = mensagem.Assunto;
//Não podemos colocar diretamente a string
//TextPart é um texto do tipo Mime que nosso email vai aceitar
mensagemDeEmail.Body = new TextPart(MimeKit.Text.TextFormat.Text)
{
Text = mensagem.Conteudo
};
return mensagemDeEmail;
}
private void Enviar(MimeMessage mensagemDeEmail)
{
using (var client = new SmtpClient())
{
try
{
//conexao com algum provedor de e-mail
client.Connect(_configuration.GetValue<string>("EmailSettings:SmtpServer"),
_configuration.GetValue<int>("EmailSettings:Port"), true);
//Removendo autenticação mais complexa
client.AuthenticationMechanisms.Remove("XOUATH2");
client.Authenticate(_configuration.GetValue<string>("EmailSettings:From"),
_configuration.GetValue<string>("EmailSettings:Password"));
client.Send(mensagemDeEmail);
}
catch
{
throw;
}
finally
{
client.Disconnect(true);
client.Dispose();
}
}
}
}
}
|
using System;
using System.IO;
// https://www.spoj.com/problems/CODESPTB/ #bit #sorting
// Finds the number of swaps necessary when performing insertion sort.
public static class CODESPTB
{
private const int _elementLimit = 1000000;
// Insertion sort looks like this: [sorted part]k[unsorted part]. When adding the
// kth element to the sorted part, we swap it with however many larger elements
// there are to its left. The number of larger elements to its left doesn't change
// as those elements get sorted, so this problem is equivalent to INVCNT. The array
// size is limited to 100k elements, but that could be 100k * (100k - 1) / 2
// inversions, so we need to use long when counting. I tried using same code as
// INVCNT but got TLE. Hints pointed at BIT, and reviewing DQUERY led to the idea.
// Element values in the array are limited to <= 1 million. Say we're at the ith
// index in the array. We want to use the BIT to figure out how many values greater
// than a[i] have already been seen. All we need to do is make sure we've incremented
// the BIT for each a[j], j before i. Then we can do a range query from a[i]+1 to
// the limit of a million. For example, say the array is [9 6 9 4 5 1 2]. The BIT
// goes up to a million. By the time we get the value 5, 9 has been incremented twice,
// 6 has been incremented once, and 4 has been incremented once. We then sum from
// 6 (one more than 5) to a million (the limit), and see that 5 is inverted with
// 3 values to its left (9, 9 and 6, but not 4).
// ...But what would we do if the limit were much higher? Self-balancing BST?
public static long Solve(int[] array)
{
var elementBIT = new PURQBinaryIndexedTree(
// Max value (1 million) correponds to max index => array length is +1 of that.
arrayLength: _elementLimit + 1);
long inversionCount = 0;
for (int i = 1; i < array.Length; ++i)
{
elementBIT.PointUpdate(array[i - 1], 1);
inversionCount += elementBIT.SumQuery(array[i] + 1, _elementLimit);
}
return inversionCount;
}
}
// Point update, range query binary indexed tree. This is the original BIT described
// by Fenwick. There are lots of tutorials online but I'd start with these two videos:
// https://www.youtube.com/watch?v=v_wj_mOAlig, https://www.youtube.com/watch?v=CWDQJGaN1gY.
// Those make the querying part clear but don't really describe the update part very well.
// For that, I'd go and read Fenwick's paper. This is all a lot less intuitive than segment trees.
public sealed class PURQBinaryIndexedTree
{
private readonly int[] _tree;
public PURQBinaryIndexedTree(int arrayLength)
{
_tree = new int[arrayLength + 1];
}
// Updates to reflect an addition at an index of the original array (by traversing the update tree).
public void PointUpdate(int updateIndex, int delta)
{
for (++updateIndex;
updateIndex < _tree.Length;
updateIndex += updateIndex & -updateIndex)
{
_tree[updateIndex] += delta;
}
}
// Computes the sum from the zeroth index through the query index (by traversing the interrogation tree).
private int SumQuery(int queryEndIndex)
{
int sum = 0;
for (++queryEndIndex;
queryEndIndex > 0;
queryEndIndex -= queryEndIndex & -queryEndIndex)
{
sum += _tree[queryEndIndex];
}
return sum;
}
// Computes the sum from the start through the end query index, by removing the part we
// shouldn't have counted. Fenwick describes a more efficient way to do this, but it's complicated.
public int SumQuery(int queryStartIndex, int queryEndIndex)
=> SumQuery(queryEndIndex) - SumQuery(queryStartIndex - 1);
}
public static class Program
{
private static void Main()
{
int remainingTestCases = FastIO.ReadNonNegativeInt();
while (remainingTestCases-- > 0)
{
int[] array = new int[FastIO.ReadNonNegativeInt()];
for (int i = 0; i < array.Length; ++i)
{
array[i] = FastIO.ReadNonNegativeInt();
}
Console.WriteLine(
CODESPTB.Solve(array));
}
}
}
// This is based in part on submissions from https://www.codechef.com/status/INTEST.
// It's assumed the input is well-formed, so if you try to read an integer when no
// integers remain in the input, there's undefined behavior (infinite loop).
// NOTE: FastIO might not be necessary, but seems like large input.
public static class FastIO
{
private const byte _null = (byte)'\0';
private const byte _newLine = (byte)'\n';
private const byte _minusSign = (byte)'-';
private const byte _zero = (byte)'0';
private const int _inputBufferLimit = 8192;
private static readonly Stream _inputStream = Console.OpenStandardInput();
private static readonly byte[] _inputBuffer = new byte[_inputBufferLimit];
private static int _inputBufferSize = 0;
private static int _inputBufferIndex = 0;
private static byte ReadByte()
{
if (_inputBufferIndex == _inputBufferSize)
{
_inputBufferIndex = 0;
_inputBufferSize = _inputStream.Read(_inputBuffer, 0, _inputBufferLimit);
if (_inputBufferSize == 0)
return _null; // All input has been read.
}
return _inputBuffer[_inputBufferIndex++];
}
public static int ReadNonNegativeInt()
{
byte digit;
// Consume and discard whitespace characters (their ASCII codes are all < _minusSign).
do
{
digit = ReadByte();
}
while (digit < _minusSign);
// Build up the integer from its digits, until we run into whitespace or the null byte.
int result = digit - _zero;
while (true)
{
digit = ReadByte();
if (digit < _zero) break;
result = result * 10 + (digit - _zero);
}
return result;
}
}
|
namespace Abc.NCrafts.Quizz.Performance2018.Questions._003
{
[NonCodeAnswer]
[CorrectAnswer(Difficulty = Difficulty.Hard)]
public class Answer3
{
public void Run()
{
// begin
// end
}
}
}
|
using System;
namespace GDShrapt.Reader
{
public sealed class GDInvalidToken : GDCharSequence
{
readonly char[] _stopChars;
readonly Predicate<char> _stop;
internal GDInvalidToken(params char[] stopChars)
{
_stopChars = stopChars;
}
internal GDInvalidToken(Predicate<char> stop)
{
_stop = stop;
}
internal override bool CanAppendChar(char c, GDReadingState state)
{
if (_stop != null)
return !_stop(c);
return Array.IndexOf(_stopChars, c) == -1;
}
public override GDSyntaxToken Clone()
{
return new GDInvalidToken()
{
Sequence = Sequence
};
}
}
}
|
//======================================================================
//
// CopyRight 2019-2021 © MUXI Game Studio
// . All Rights Reserved
//
// FileName : PlotItemEditorWindow.cs
//
// Created by 半世癫(Roc) at 2021-01-26 13:56:22
//
//======================================================================
using System;
#if UNITY_EDITOR
using GalForUnity.System;
using UnityEngine;
using UnityEditor;
#endif
namespace GalForUnity.Graph.Windows{
[Serializable]
public class PlotItemEditorWindow
#if UNITY_EDITOR
: GfuEditorWindow
#endif
{
#if UNITY_EDITOR
public override void Init(string path){
base.Init(path);
GameSystem.GraphData.currentGfuPlotItemEditorWindow = this;
GraphView = new PlotItemGraph(this, path);
rootVisualElement.Add(GraphView);
AddButton(GraphView);
titleContent = new GUIContent(GfuLanguage.GfuLanguageInstance.PLOTITEMEDITORWINDOW.Value);
}
private void OnDidOpenScene(){
onSceneChanged = true;
GraphView?.Clear();
EditorApplication.playModeStateChanged -= OnPlayModeChanged;
}
private void OnDisable(){
// GraphView?.Clear();
// GraphView = null;
}
PlotItemEditorWindow(){
EditorApplication.playModeStateChanged += OnPlayModeChanged;
}
public void OnPlayModeChanged(PlayModeStateChange playModeStateChange){
if (onSceneChanged) return;
if (playModeStateChange == PlayModeStateChange.ExitingPlayMode){
EditorApplication.delayCall += () => {
GraphView?.Clear();
Init(GraphView?.path ?? path);
};
}
}
[MenuItem("GalForUnity/PlotItem")]
public static void Open(){
PlotItemEditorWindow window =
GameSystem.GraphData.currentGfuPlotItemEditorWindow =
GetWindow<PlotItemEditorWindow>(
ObjectNames.NicifyVariableName(nameof(PlotItemEditorWindow)));
window.Init(null);
}
private void OnEnable(){
EditorApplication.delayCall += (() => {
if (onSceneChanged) return;
GraphView?.Clear();
Init(GraphView?.path ?? path);
});
}
#endif
}
} |
namespace Zilon.Core.Persons
{
public interface IPersonPerkInitializator
{
IPerk[] Generate();
}
} |
using System;
using System.Xml.Serialization;
using NewLife.Serialization;
using System.IO;
namespace NewLife.Messaging
{
/// <summary>指定长度的字节数据消息</summary>
/// <remarks>
/// 一般用于对数据进行二次包装,理论上,这是一个万能消息。
/// 数据长度由<see cref="Data"/>决定,以编码整数来存储。
/// </remarks>
public class DataMessage : Message
{
/// <summary>消息类型</summary>
[XmlIgnore]
public override MessageKind Kind { get { return MessageKind.Data; } }
//private Int32 _Length;
///// <summary>长度</summary>
//public Int32 Length { get { return _Length; } set { _Length = value; } }
private Byte[] _Data;
/// <summary>数据</summary>
public Byte[] Data { get { return _Data; } set { _Data = value; } }
/// <summary>已重载。</summary>
/// <param name="stream">数据流</param>
/// <param name="rwkind">序列化类型</param>
protected override void OnWrite(Stream stream, RWKinds rwkind)
{
// 因为不写对象引用,所以不能为null
if (Data == null) Data = new Byte[0];
base.OnWrite(stream, rwkind);
}
/// <summary>读写前设置。不使用对象引用</summary>
/// <param name="rw"></param>
protected override void OnReadWriteSet(IReaderWriter rw)
{
base.OnReadWriteSet(rw);
rw.Settings.UseObjRef = false;
}
#region 辅助
/// <summary>已重载。</summary>
/// <returns></returns>
public override string ToString()
{
var data = Data;
return String.Format("{0} Length={1}", base.ToString(), data != null ? data.Length : 0);
}
#endregion
}
} |
using System;
using System.Threading.Tasks;
using AndrewLarsson.Common.Domain;
namespace AndrewLarsson.Common.AppService {
public interface IAggregateRootStore<T> where T : AggregateRoot {
Task<T> LoadAsync(Guid id);
Task SaveAsync(T t);
}
}
|
using System;
using System.IO;
namespace versioning
{
class AssemblyInfoRepo
{
private string repo;
private string[] files;
public AssemblyInfoRepo(string repo)
{
this.repo = repo;
this.files = Directory.GetFiles(repo, "AssemblyInfo.cs", SearchOption.AllDirectories);
}
public void UpdateVersion(Version version)
{
foreach (string file in files)
{
var cs = new AssemblyInfoFile(file);
cs.UpdateVersion(version);
cs.Save();
}
}
}
}
|
using WeakAuraAutomationTool.Warcraft;
using WeakAuraAutomationTool.Warcraft.Classes;
using WeakAuraAutomationTool.WeakAuras;
namespace WeakAuraAutomationTool.Barbeque.Auras
{
internal static class DeathKnightBlood
{
public static void Generate(WeakAura wa)
{
var blood = new Blood();
var builder = new SpecBuilder(ClassSpec.Blood);
// todo: Death Strike heal tracker?
builder.AddOverflow(
blood.DarkCommand,
blood.RaiseAlly,
blood.RaiseDead,
blood.SacrificialPact,
blood.Consumption,
blood.BloodTap,
// todo: does this change Core Rotation?
blood.MarkOfBlood.DeBuff(),
// todo: will this detect a debuff on player?
blood.DeathPact.Buff()
// havoc.Torment,
).AddRightBar(
// Cooldowns
blood.Anti_MagicShell.Buff(),
blood.Anti_MagicZone.Buff(),
blood.IceboundFortitude.Buff(),
blood.Lichborne
).AddCoreRotation(
// todo: probably needs a _missing_ warning \ a _low_ warning
// todo: associate with Ossuary Buff
blood.BoneShield.Passive().Buff().BigStacks(),
blood.RuneTap.Buff(),
blood.DeathAndDecay.Buff().AssociateAura(blood.CrimsonScourge),
blood.BloodBoil
).AddCoreCooldowns(
blood.DancingRuneWeapon.Buff(),
blood.VampiricBlood.Buff(),
blood.Blooddrinker.Buff(),
blood.Tombstone.Buff(),
blood.Bonestorm.Buff()
).AddBottomBar(
blood.DeathGrip,
blood.GorefiendsGrasp,
blood.DeathsAdvance.Buff(),
blood.WraithWalk.Buff(),
blood.MindFreeze.DeBuff(),
blood.Asphyxiate.DeBuff()
).AddTopBar(
blood.ControlUndead.Passive().Buff(),
blood.BloodPlague.Passive().DeBuff(),
blood.Bloodworms.Passive().Buff().BigStacks()
).AddAlerts(
blood.PathOfFrost.Passive().Buff(),
blood.Purgatory.Passive().Buff()
).Build(wa);
}
}
} |
using System;
using System.Collections.Generic;
namespace RestEaseClientGeneratorConsoleApp.Examples.Infura.Models
{
public class TickerFullResponse
{
public string Base { get; set; }
public string Quote { get; set; }
public object[] Tickers { get; set; }
}
}
|
namespace Cbn.Infrastructure.SQS
{
public static class SQSConstans
{
public const int MaxDelay = 900;
public const string TypeFullNameKey = "sqs-type";
public const string ReceiveCountKey = "sqs-count";
public const string ApproximateReceiveCountKey = "ApproximateReceiveCount";
public const string VisibilityTimeoutKey = "VisibilityTimeout";
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.