content stringlengths 23 1.05M |
|---|
using System;
using System.Linq;
using UnityEngine;
using UnityEngine.UI;
/// <summary>
///
/// </summary>
public class RecipeManager : MonoBehaviour
{
/// <summary>
/// Instantiate class object
/// </summary>
public static RecipeManager Instance
{
get
{
if (instance == null)
{
instance = GameObject.FindObjectOfType<RecipeManager>();
}
return RecipeManager.instance;
}
}
private static RecipeManager instance;
/// <summary>
/// GUI
/// </summary>
public Button GUI_Button_SwitchBuyAmount;
/// <summary>
/// GUI
/// </summary>
public Text GUI_Text_SwitchButtonText;
/// <summary>
///
/// </summary>
[HideInInspector]
public BuyAmountMode BuyAmountMode = BuyAmountMode.Single;
/// <summary>
///
/// </summary>
private int amount = 1;
/// <summary>
/// Use this for initialization
/// </summary>
private void Start()
{
SwitchBuyMode();
}
/// <summary>
///
/// </summary>
public void SwitchBuyMode()
{
GUI_Text_SwitchButtonText.text = BuyAmountMode.ToString();
GUI_Button_SwitchBuyAmount.onClick.AddListener(() =>
{
BuyAmountMode current = BuyAmountMode;
if (current == Enum.GetValues(typeof(BuyAmountMode)).Cast<BuyAmountMode>().Max())
{
BuyAmountMode = BuyAmountMode.Single;
}
else
{
BuyAmountMode = current + 1;
}
switch (BuyAmountMode)
{
case BuyAmountMode.Single:
amount = 1;
break;
case BuyAmountMode.Fifty:
amount = 50;
break;
case BuyAmountMode.OneHundred:
amount = 100;
break;
}
for (int i = 0; i < SaveLoad.Instance.Recipe_Item.Count; i++)
{
RecipeData r = SaveLoad.Instance.Recipe_Item[i].GetComponent<RecipeData>();
r.AmountSellMuiltplyer = amount;
r.UpdateText();
}
GUI_Text_SwitchButtonText.text = BuyAmountMode.ToString();
});
}
}
|
using PressCenter.Data.Models;
namespace PressCenter.Services.Data
{
public interface IDataValidationService
{
bool ValidateNews(INews news);
bool ValidateTopNews(ITopNews news);
}
} |
// Copyright (c) Zolution Software Ltd. All rights reserved.
// Licensed under the MIT License, see LICENSE.txt in the solution root for license information
using System;
namespace Rezolver.Events
{
/// <summary>
/// Contains the arguments for the <see cref="IRootTargetContainer.TargetRegistered"/> event exposed
/// by the <see cref="IRootTargetContainer"/>
/// </summary>
public class TargetRegisteredEventArgs : EventArgs
{
/// <summary>
/// The target that was registered
/// </summary>
public ITarget Target { get; }
/// <summary>
/// The type against which the target was registered.
/// </summary>
public Type Type { get; }
/// <summary>
/// Constructs a new instance of the <see cref="TargetRegisteredEventArgs"/>
/// </summary>
/// <param name="target"></param>
/// <param name="type"></param>
public TargetRegisteredEventArgs(ITarget target, Type type)
{
Target = target;
Type = type;
}
}
} |
namespace FoodShortage
{
using System;
using System.Collections.Generic;
using System.Linq;
using Interface;
using Model;
public class StartUp
{
static void Main()
{
var buyers = new HashSet<IBuyer>();
int countOfPeople = int.Parse(Console.ReadLine());
for (int i = 0; i < countOfPeople; i++)
{
var currentLine = Console.ReadLine().Split();
if (currentLine.Length == 4)
{
buyers.Add(new Citizen(currentLine[0], int.Parse(currentLine[1]), currentLine[2], currentLine[3]));
}
else if (currentLine.Length == 3)
{
buyers.Add(new Rebel(currentLine[0], int.Parse(currentLine[1]), currentLine[2]));
}
}
string command = null;
while ((command = Console.ReadLine()) != "End")
{
var buyer = buyers.SingleOrDefault(x => x.Name == command);
if (buyer != null)
{
buyer.BuyFood();
}
}
Console.WriteLine(buyers.Sum(x => x.Food));
}
}
}
|
using System.Data.Entity;
using Microsoft.AspNet.Identity.EntityFramework;
using UCRS.Data.Contracts;
using UCRS.Data.Models;
namespace UCRS.Data
{
public class UniversitySystemDbContext : DbContext, IUniversitySystemDbContext
{
public UniversitySystemDbContext()
: base("UniversitySystemDBConnectionString")
{
}
public IDbSet<Student> Students { get; set; }
public IDbSet<Course> Courses { get; set; }
}
}
|
//---------------------------------------------------------------------
// <copyright file="IProviderType.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
// </copyright>
//---------------------------------------------------------------------
namespace Microsoft.OData.Service.Providers
{
#region Namespaces
using System.Collections.Generic;
#endregion
/// <summary>
/// Implemented by a class that encapsulates a data service provider's metadata representation of a type.
/// </summary>
internal interface IProviderType
{
/// <summary>
/// Returns the members declared on this type only, not including any inherited members.
/// </summary>
IEnumerable<IProviderMember> Members { get; }
/// <summary>
/// Name of the type without its namespace
/// </summary>
string Name { get; }
}
}
|
using ESC.Infrastructure;
using ESC.Infrastructure.DomainObjects;
using ESC.Service;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using Microsoft.AspNetCore.Mvc;
namespace ESC.Web.Controllers
{
public class WStockController : BaseController
{
WStockService sService = new WStockService();
//
// GET: /WStock/
public ActionResult Index()
{
return View();
}
#region 弹层选择
/// <summary>
/// 查询库存
/// </summary>
/// <returns></returns>
[HttpGet]
public ActionResult SearchStockView()
{
return View();
}
/// <summary>
/// 获取特定仓库的库存
/// </summary>
/// <returns></returns>
public ActionResult SearchWhStockView()
{
ViewBag.WarehouseID = GetParam("WarehouseID");
return View();
}
/// <summary>
/// 查询库存根据销售通知单
/// </summary>
/// <returns></returns>
[HttpGet]
public ActionResult SearchStockSellNoticeView()
{
ViewBag.WarehouseID = GetParam("WarehouseID");
ViewBag.ParentID = GetParam("ParentID");
return View();
}
/// <summary>
/// 查询库存根据采购单
/// </summary>
/// <returns></returns>
[HttpGet]
public ActionResult SearchStockPurchaseView()
{
ViewBag.WarehouseID = GetParam("WarehouseID");
ViewBag.ParentID = GetParam("ParentID");
return View();
}
#endregion
#region 初始化
/// <summary>
/// 初始化
/// </summary>
/// <returns></returns>
[HttpGet]
public ActionResult Init()
{
InitData idata = BaseInit(typeof(WStock), true);
return ReturnResult(idata);
}
#endregion
#region 增删改查
/// <summary>
/// 查询
/// </summary>
/// <returns></returns>
[HttpGet]
public ContentResult Search()
{
List<WhereItem> whereItems = GetWhereItems();
long pageIndex = GetPageIndex();
long pageSize = GetPageSize();
var page = sService.PageSearch(pageIndex, pageSize, whereItems);
return ReturnResult(page);
}
/// <summary>
/// 销售通知单查询
/// </summary>
/// <returns></returns>
[HttpGet]
public ContentResult SellNoticeSearch()
{
List<WhereItem> whereItems = GetWhereItems();
long pageIndex = GetPageIndex();
long pageSize = GetPageSize();
var page = sService.PageSellNoticeSearch(pageIndex, pageSize, whereItems);
return ReturnResult(page);
}
/// <summary>
/// 根据采购入库单条件查询
/// </summary>
/// <param name="whereItems"></param>
/// <returns></returns>
public ContentResult PageSearchPurchase()
{
List<WhereItem> whereItems = GetWhereItems();
long pageIndex = GetPageIndex();
long pageSize = GetPageSize();
var page = sService.PageSearchPurchase(pageIndex, pageSize, whereItems);
return ReturnResult(page);
}
/// <summary>
/// 文件下载
/// </summary>
/// <returns></returns>
[HttpGet]
public FileResult DownLoad()
{
List<WhereItem> whereItems = GetWhereItems();
DataTable dt = sService.GetStocks(whereItems);
ResetColumnName(dt);
return BaseDownloadFile(string.Format("库存{0}.xlsx", DateTime.Now.ToString("yyyyMMddhhmmss")), dt);
}
/// <summary>
/// 重置data名称
/// </summary>
/// <param name="dt"></param>
protected void ResetColumnName(DataTable dt)
{
SColumnService sService = new SColumnService();
List<SColumn> cols = sService.GetVisibleColumnsByTable("WStock");
for (int i = 0; i < dt.Columns.Count; i++)
{
dt.Columns[i].Caption = string.Empty;
foreach (SColumn col in cols)
{
if (string.IsNullOrEmpty(col.DisplayColumn))
{
if (col.ColumnName == dt.Columns[i].ColumnName)
{
dt.Columns[i].Caption = col.Title;
break;
}
}
else
{
if (col.DisplayColumn == dt.Columns[i].ColumnName)
{
dt.Columns[i].Caption = col.Title;
break;
}
}
}
}
}
#endregion
}
} |
using System;
using StoryTeller.Commands;
using StoryTeller.Messages;
namespace ST.Client.Persistence
{
public class RequestSpecDataCommand : Command<SpecDataRequested>
{
private readonly Lazy<IPersistenceController> _persistence;
private readonly Lazy<IClientConnector> _client;
public RequestSpecDataCommand(Lazy<IPersistenceController> persistence, Lazy<IClientConnector> client)
{
_persistence = persistence;
_client = client;
}
public override void HandleMessage(SpecDataRequested message)
{
var data = _persistence.Value.LoadSpecification(message.id);
_client.Value.SendMessageToClient(data);
}
}
} |
using System.Runtime.InteropServices;
using Clarity.Common.Numericals.Algebra;
namespace Clarity.Common.Numericals.Geometry
{
[StructLayout(LayoutKind.Sequential)]
public struct LineSegment3 // todo: IEquatable<>
{
public Vector3 Point1;
public Vector3 Point2;
public LineSegment3(Vector3 point1, Vector3 point2)
{
Point1 = point1;
Point2 = point2;
}
public float Length => Difference.Length();
public float LengthSq => Difference.LengthSquared();
public Vector3 Difference => Point2 - Point1;
public override string ToString() => $"{{{Point1}, {Point2}}}";
}
} |
namespace SnakeGame.IO.Contracts
{
public interface IWriter
{
void WriteLine(string value);
void Write(string value);
}
}
|
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Assertions;
using System.Collections;
using GhostGen;
using DG.Tweening;
public class PlayerHandView : UIView
{
public Transform[] cardSlotList;
public CanvasGroup canvasGroup;
public Transform dragCardLayer;
public Image dragBlocker;
private IngredientCardView[] _cardViewList;
void Awake()
{
_cardViewList = new IngredientCardView[PlayerState.kHandSize];
blockCardDrag = false;
}
void Start()
{
OnIntroTransitionFinished();
}
public bool blockCardDrag
{
set
{
dragBlocker.gameObject.SetActive(value);
}
}
public void SetCardAtIndex(int index, IngredientCardView card)
{
_boundsCheck(index);
if(card != _cardViewList[index])
{
_cardViewList[index] = _processCardView(index, card);
invalidateFlag |= InvalidationFlag.STATIC_DATA;
}
}
public IngredientCardView GetCardAtIndex(int index)
{
_boundsCheck(index);
return _cardViewList[index];
}
public void RemoveCardByIndex(int index)
{
_boundsCheck(index);
if(_cardViewList[index])
{
//_cardViewList[index].gameObject.SetActive(false);
Singleton.instance.gui.viewFactory.RemoveView(_cardViewList[index]);
_cardViewList[index] = null;
invalidateFlag = InvalidationFlag.ALL;
}
}
protected override void OnViewUpdate()
{
if(IsInvalid(InvalidationFlag.STATIC_DATA))
{
for(int i = 0; i < _cardViewList.Length; ++i)
{
IngredientCardView cardView = _cardViewList[i];
if (cardView)
{
cardView.invalidateFlag = InvalidationFlag.STATIC_DATA;
}
}
}
}
private IngredientCardView _processCardView(
int handIndex,
IngredientCardView cardView)
{
if (cardView == null) { return null; }
_boundsCheck(handIndex);
cardView.transform.SetParent(cardSlotList[handIndex]);
cardView.transform.localPosition = Vector3.zero;
cardView.handView = this;
cardView.handSlot = cardSlotList[handIndex];
cardView.dragLayer = dragCardLayer;
cardView.handIndex = handIndex;
return cardView;
}
private void _boundsCheck(int index)
{
Debug.Assert(index >= 0, "Index is less than 0!");
Debug.Assert(index < PlayerHand.kDefaultHandSize, "Index is greater than slot container size");
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Formats.Jpeg;
using SixLabors.ImageSharp.PixelFormats;
public class BitmapDiff
{
private readonly int _tolerance = ushort.MaxValue / 4;
public BitmapDiff(ushort tolerance = ushort.MaxValue / 4)
{
_tolerance = tolerance;
}
public Task<Image<L16>> GetDiffImageAsync(Stream imageStream1, Stream imageStream2)
{
return Task.Run(() =>
{
using Image<L16> image1 = Image.Load<L16>(imageStream1, new JpegDecoder());
using Image<L16> image2 = Image.Load<L16>(imageStream2, new JpegDecoder());
if (image1.Width != image2.Width || image1.Height != image2.Height)
{
throw new InvalidOperationException("Height and width of the two bitmaps to compare should match.");
}
if (image1.PixelType.BitsPerPixel != image2.PixelType.BitsPerPixel)
{
throw new InvalidOperationException("PixelType has to match.");
}
var pixels1 = image1.GetPixels();
var pixels2 = image2.GetPixels();
var resultPixels = new L16[pixels1.Length];
for (int i = 0; i < pixels1.Length; i++)
{
unchecked
{
resultPixels[i] = new L16((ushort)Math.Abs(pixels1[i].PackedValue - pixels2[i].PackedValue));
}
}
Image<L16> result = new Image<L16>(image1.Width, image1.Height);
result.SetPixels(resultPixels);
return result;
});
}
public Task<double> GetDiffNumberFromImageAsync(Image<L16> image)
{
return Task.Run(() =>
{
var pixels = image.GetPixels();
var deviations = new List<L16>();
for (int i = 0; i < pixels.Length; i++)
{
if (pixels[i].PackedValue >= _tolerance)
{
deviations.Add(pixels[i]);
//System.Console.Write($"{bytes[i]} ");
}
}
if (deviations.Count == 0)
{
//System.Console.WriteLine("No deviations!");
return 0;
}
// System.Console.WriteLine($"Count: {deviations.Count}");
// System.Console.WriteLine($"Average: {deviations.Average(d => d.PackedValue - _treshold)}");
// System.Console.WriteLine($"Maximum: {deviations.Max(d => d.PackedValue - _treshold)}");
return deviations.Average(d => d.PackedValue - _tolerance);
});
}
} |
using System;
using System.Collections.Generic;
using UnityEngine;
using Object = UnityEngine.Object;
/// <summary>
/// 资源预读,一个游戏只能有一个该对象
/// </summary>
public class SuperResource : SingleObject<SuperResource>
{
private readonly Dictionary<string, Object> resDic = new Dictionary<string, Object>();//构建的对象池
private readonly List<ResourceRequest> resDatas = new List<ResourceRequest>();
private int resProgress;
public int ResProgress
{
get
{
return resProgress;
}
}
private bool isDone;
/// <summary>
/// 检查这个来判断读取是否完成
/// </summary>
public bool IsDone
{
get
{
return isDone;
}
}
protected override void Init() { }
/// <summary>
/// 读取传入路径的prefab,如果不传递参数,自动读取Resources/LoadPath/prefabPath.asset
/// 异步读取,IsDone与resProgress分别表示读取是否完成与读取进度
/// </summary>
public void LoadAsync(string[] names = null)
{
isDone = false;
string[] check;
if (names == null)
{
EasyConfig ec = EasyConfig.GetConfig("DefaultPath");
check = ec.GetDataArray("Prefab");
}
else
{
check = names;
}
foreach (string t in check)
{
ResourceRequest data = Resources.LoadAsync<Object>(t);
resDatas.Add(data);
}
SuperTimer.Instance.RegisterFrameFunction(CheckRes);
}
private bool CheckRes(object obj)
{
isDone = true;
resProgress = 0;
foreach (ResourceRequest t in resDatas)
{
if (t.isDone)
{
if (!resDic.ContainsKey(t.asset.name)) resDic.Add(t.asset.name, t.asset);
}
else
{
isDone = false;
}
resProgress += (int)(t.progress * 100);
}
resProgress = resProgress / resDatas.Count;
if (isDone)
{
return true;
}
return false;
}
/// <summary>
/// 获取并创建一个GameObject舞台对象(已经实例化)
/// </summary>
public GameObject GetInstance(string name)
{
try
{
return Object.Instantiate(resDic[name] as GameObject);
}
catch (Exception)
{
Debug.LogError("资源获取出错,是不是路径有错? @ " + name);
throw;
}
}
/// <summary>
/// 获取一个GameObject对象(未实例化)
/// </summary>
public GameObject GetObject(string name)
{
try
{
GameObject gb = resDic[name] as GameObject;
return gb;
}
catch (Exception)
{
Debug.LogError("资源获取出错,是不是路径有错? @ " + name);
throw;
}
}
/// <summary>
/// 移除所有资源
/// </summary>
public void Clear()
{
isDone = false;
resDic.Clear();
}
}
|
using System;
using System.Text.Json.Serialization;
namespace Conceptoire.Twitch.API
{
public class IGDBGame
{
[JsonPropertyName("id")]
public int Id { get; set; }
[JsonPropertyName("age_ratings")]
public int[] AgeRatings { get; set; }
[JsonPropertyName("aggregated_rating")]
public double AggregatedRating { get; set; }
[JsonPropertyName("aggregated_rating_count")]
public int AggregatedRatingCount { get; set; }
[JsonPropertyName("alternative_names")]
public int[] AlternativeNames { get; set; }
[JsonPropertyName("artworks")]
public int[] Artworks { get; set; }
[JsonPropertyName("category")]
public int Category { get; set; }
[JsonPropertyName("collection")]
public int Collection { get; set; }
[JsonPropertyName("cover")]
public int Cover { get; set; }
[JsonPropertyName("created_at")]
public int CreatedAt { get; set; }
[JsonPropertyName("external_games")]
public int[] ExternalGames { get; set; }
[JsonPropertyName("first_release_date")]
public int FirstReleaseDate { get; set; }
[JsonPropertyName("follows")]
public int Follows { get; set; }
[JsonPropertyName("game_engines")]
public int[] GameEngines { get; set; }
[JsonPropertyName("game_modes")]
public int[] GameModes { get; set; }
[JsonPropertyName("genres")]
public int[] Genres { get; set; }
[JsonPropertyName("hypes")]
public int Hypes { get; set; }
[JsonPropertyName("involved_companies")]
public int[] InvolvedCompanies { get; set; }
[JsonPropertyName("keywords")]
public int[] Keywords { get; set; }
[JsonPropertyName("multiplayer_modes")]
public int[] MultiplayerModes { get; set; }
[JsonPropertyName("name")]
public string Name { get; set; }
[JsonPropertyName("platforms")]
public int[] Platforms { get; set; }
[JsonPropertyName("player_perspectives")]
public int[] PlayerPerspectives { get; set; }
[JsonPropertyName("rating")]
public double Rating { get; set; }
[JsonPropertyName("rating_count")]
public int RatingCount { get; set; }
[JsonPropertyName("release_dates")]
public int[] ReleaseDates { get; set; }
[JsonPropertyName("screenshots")]
public int[] Screenshots { get; set; }
[JsonPropertyName("similar_games")]
public int[] SimilarGames { get; set; }
[JsonPropertyName("slug")]
public string Slug { get; set; }
[JsonPropertyName("storyline")]
public string Storyline { get; set; }
[JsonPropertyName("summary")]
public string Summary { get; set; }
[JsonPropertyName("tags")]
public int[] Tags { get; set; }
[JsonPropertyName("themes")]
public int[] Themes { get; set; }
[JsonPropertyName("total_rating")]
public double TotalRating { get; set; }
[JsonPropertyName("total_rating_count")]
public int TotalRatingCount { get; set; }
[JsonPropertyName("updated_at")]
public int UpdatedAt { get; set; }
[JsonPropertyName("url")]
public Uri Url { get; set; }
[JsonPropertyName("videos")]
public int[] Videos { get; set; }
[JsonPropertyName("websites")]
public int[] Websites { get; set; }
[JsonPropertyName("checksum")]
public Guid Checksum { get; set; }
}
}
|
using System.Collections.Generic;
using System.Drawing;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media.Imaging;
using LevelEditor.Models;
namespace LevelEditor.Services {
public class TileMapService {
private static TileMapService _instance;
public static TileMapService Instance => _instance ?? (_instance = new TileMapService());
public Dictionary<string, TileMap> Factory { get; set; }
private TileMapService()
{
Factory = new Dictionary<string, TileMap>();
}
public TileMap LoadMap(string path)
{
if (Factory.TryGetValue(path, out var map))
return map;
var tileMap = JsonService.LoadGet<TileMap>(path);
Factory.Add(path, tileMap);
return tileMap;
}
}
}
|
using System;
using RimWorld;
using Verse;
namespace RaceWeapons
{
// Token: 0x02000037 RID: 55
[DefOf]
public static class ThingDefOf
{
// Token: 0x060000AE RID: 174 RVA: 0x00006159 File Offset: 0x00004359
static ThingDefOf()
{
DefOfHelper.EnsureInitializedInCtor(typeof(ThingDefOf));
}
// Token: 0x0400005B RID: 91
public static ThingDef LaserMoteWorker;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Lycus.Satori
{
/// <summary>
/// Represents an Epiphany platform.
/// </summary>
public sealed class Machine : IDisposable
{
public const int MinRows = 2;
public const int MaxRows = 64;
public const int MinColumns = 2;
public const int MaxColumns = 64;
/// <summary>
/// The architecture version of this machine.
/// </summary>
public Architecture Architecture { get; private set; }
/// <summary>
/// The logger in use by this machine.
/// </summary>
public Logger Logger { get; private set; }
/// <summary>
/// The kernel in use by this machine.
/// </summary>
public Kernel Kernel { get; private set; }
/// <summary>
/// The memory system of this machine.
/// </summary>
public Memory Memory { get; private set; }
/// <summary>
/// The instruction fetcher used by this machine.
/// </summary>
public Fetcher Fetcher { get; private set; }
public int Rows { get; private set; }
public int Columns { get; private set; }
public IReadOnlyList<Core> Cores { get; private set; }
public IReadOnlyList<IReadOnlyList<Core>> Grid { get; private set; }
public TimeSpan SleepDuration { get; set; }
public TimeSpan IdleDuration { get; set; }
internal bool Halting { get; private set; }
bool _disposed;
public Machine(Architecture architecture, Logger logger, Kernel kernel,
int rows, int columns, int memory)
{
if (architecture != Architecture.EpiphanyIII &&
architecture != Architecture.EpiphanyIV)
throw new ArgumentException(
"Invalid Architecture value ({0}).".Interpolate(architecture),
"architecture");
if (logger == null)
throw new ArgumentNullException("logger");
if (kernel == null)
throw new ArgumentNullException("kernel");
if (rows < MinRows || rows > MaxRows)
throw new ArgumentOutOfRangeException("rows", rows,
"Row count is out of range.");
if (columns < MinColumns || columns > MaxColumns)
throw new ArgumentOutOfRangeException("columns", columns,
"Column count is out of range.");
if (new CoreId(rows - 1, columns - 1).ToAddress() >= Memory.ExternalBaseAddress)
throw new ArgumentException("The given row and column counts would result " +
"in a grid that overlaps external memory.");
if (memory < Memory.MinMemorySize || memory > Memory.MaxMemorySize)
throw new ArgumentOutOfRangeException("memory", memory,
"External memory size is out of range.");
Architecture = architecture;
Logger = logger;
Kernel = kernel;
Memory = new Memory(this, memory);
Fetcher = new Fetcher(this);
Rows = rows;
Columns = columns;
var cores = new List<Core>(rows * columns);
var grid = new List<List<Core>>(rows);
for (var i = 0; i < rows; i++)
{
var row = new List<Core>(columns);
for (var j = 0; j < columns; j++)
{
// A core can't have row 0 and column 0 since routing
// anything to it would be impossible; addresses with
// the upper 12 bits all zero are mapped to the local
// core memory.
if (i == 0 && j == 0)
break;
row.Add(new Core(this, new CoreId(i, j)));
}
cores.AddRange(row);
// See comment above. We don't want a `null` entry in the
// `Cores` list, so insert it here.
if (i == 0)
row.Insert(0, null);
grid.Add(row);
}
Cores = cores;
Grid = grid;
SleepDuration = TimeSpan.FromMilliseconds(50);
IdleDuration = TimeSpan.FromMilliseconds(10);
}
public Core GetCore(CoreId id)
{
if (id.Row >= Grid.Count)
return null;
var list = Grid[id.Row];
return id.Column >= list.Count ? null : list[id.Column];
}
public void Join()
{
Task.WaitAll(Cores.Select(x => x.MainTask).ToArray());
}
void RealDispose()
{
if (_disposed)
return;
_disposed = true;
// Flag all cores for shutdown.
Halting = true;
// Wait for all cores to shut down.
Join();
// Clean up the rest now that nothing will call it.
Kernel.Dispose();
Logger.Dispose();
Fetcher.Dispose();
}
~Machine()
{
RealDispose();
}
public void Dispose()
{
RealDispose();
GC.SuppressFinalize(this);
}
}
}
|
using Equilaterus.Vortex.Saturn.Commands;
using Equilaterus.Vortex.Saturn.Services;
using Moq;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace Equilaterus.Vortex.Saturn.Tests.Commands
{
public class DeleteAdjuntableTests : BaseActionTest<AdjuntableTestModel>
{
public DeleteAdjuntableTests()
{
ThrowsOnNullDataStorage = false;
}
protected override GenericAction<AdjuntableTestModel> GetCommand(VortexContext<AdjuntableTestModel> context)
{
return new DeleteAttacheableFile<AdjuntableTestModel>(context);
}
protected override VortexData GetData()
{
return new VortexData(new AdjuntableTestModel("fileurl/dir/name.ext"));
}
[Fact]
public async Task ExecuteCommand()
{
// Prepare data
var data = GetData();
// Prepare objects
var mock = new Mock<IFileStorage>();
var context = new VortexContext<AdjuntableTestModel>(null, mock.Object);
var command = GetCommand(context);
command.Params = data;
command.Initialize();
// Execute
await command.Execute();
mock.Verify(m => m.DeleteFileAsync("fileurl/dir/name.ext"), Times.Once);
Assert.Null(data.GetMainEntityAs<AdjuntableTestModel>().FileUrl);
}
}
}
|
// ForStatement.cs
// Script#/Core/ScriptSharp
// This source code is subject to terms and conditions of the Apache License, Version 2.0.
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
namespace ScriptSharp.ScriptModel {
internal sealed class ForStatement : Statement {
private Expression _condition;
private List<Expression> _initializers;
private List<Expression> _increments;
private VariableDeclarationStatement _variables;
private Statement _body;
public ForStatement()
: base(StatementType.For) {
}
public Statement Body {
get {
return _body;
}
}
public Expression Condition {
get {
return _condition;
}
}
public bool HasScopeVariables {
get {
return (_variables != null);
}
}
public ICollection<Expression> Increments {
get {
return _increments;
}
}
public ICollection<Expression> Initializers {
get {
return _initializers;
}
}
public override bool RequiresThisContext {
get {
if ((_body != null) && _body.RequiresThisContext) {
return true;
}
if ((_condition != null) && _condition.RequiresThisContext) {
return true;
}
if (_increments != null) {
foreach (Expression expression in _increments) {
if (expression.RequiresThisContext) {
return true;
}
}
}
if (_initializers != null) {
foreach (Expression expression in _initializers) {
if (expression.RequiresThisContext) {
return true;
}
}
}
return false;
}
}
public VariableDeclarationStatement Variables {
get {
return _variables;
}
}
public void AddBody(Statement statement) {
Debug.Assert(_body == null);
_body = statement;
}
public void AddCondition(Expression expression) {
Debug.Assert(_condition == null);
_condition = expression;
}
public void AddIncrement(Expression expression) {
if (_increments == null) {
_increments = new List<Expression>();
}
_increments.Add(expression);
}
public void AddInitializer(Expression expression) {
Debug.Assert(_variables == null);
if (_initializers == null) {
_initializers = new List<Expression>();
}
_initializers.Add(expression);
}
public void AddInitializer(VariableDeclarationStatement variables) {
Debug.Assert(_initializers == null);
Debug.Assert(_variables == null);
_variables = variables;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Gallio.Model;
using Gallio.ConcordionAdapter.Properties;
namespace Gallio.ConcordionAdapter.Model
{
/// <summary>
/// Builds a test object model, based on Concordion attributes using reflection
/// </summary>
public class ConcordionTestFramework : BaseTestFramework
{
/// <inheritdoc />
public override void RegisterTestExplorers(IList<ITestExplorer> explorers)
{
explorers.Add(new ConcordionTestExplorer());
}
}
}
|
//--------------------------------------------------------------------------------------
// FixedScroll.cs
//
// Advanced Technology Group (ATG)
// Copyright (C) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
//--------------------------------------------------------------------------------------
using UnityEngine;
public class FixedScroll : MonoBehaviour
{
public float YScrollSpeed = 0.025f;
public float XScrollSpeed = 0.025f;
public Vector2 CameraXBounds = new Vector2(-30f, 30f);
public Vector2 CameraYBounds = new Vector2(-30f, 30f);
Transform theCamera;
void Start()
{
theCamera = Camera.main.transform;
}
void Update()
{
float newX = theCamera.position.x + XScrollSpeed;
float newY = theCamera.position.y + YScrollSpeed;
if (newX < CameraXBounds.x || newX > CameraXBounds.y)
{
XScrollSpeed *= -1;
}
if (newY < CameraYBounds.x || newY > CameraYBounds.y)
{
YScrollSpeed *= -1;
}
theCamera.position = new Vector3(newX, newY, theCamera.position.z);
}
}
|
using System;
using System.Collections.Generic;
using Monaco.Bus.MessageManagement.Serialization;
using Monaco.Configuration;
using Xunit;
namespace Monaco.Tests.Bus.Internals.Serializer
{
public class DataContractSerializerTests : IDisposable
{
private IConfiguration configuration;
public DataContractSerializerTests()
{
configuration = Monaco.Configuration.Configuration.Create();
configuration
.WithContainer(c => c.UsingWindsor());
((Monaco.Configuration.Configuration)this.configuration).Configure();
}
public void Dispose()
{
if(this.configuration != null)
{
if(this.configuration.Container != null)
{
this.configuration.Container.Dispose();
}
}
this.configuration = null;
}
[Fact(Skip = "Using SharpSerializer over DataContractSerializer")]
public void can_serialize_proxy_from_interface()
{
var contracts = new List<Type>();
contracts.Add(typeof (ILoanApplication));
var serializer = this.configuration.Container.Resolve<ISerializationProvider>();
serializer.AddTypes(contracts);
serializer.Initialize();
var application = configuration.Container.Resolve<ILoanApplication>();
application.ApplicationNumber = Guid.NewGuid().ToString();
application.ReceivedOn = DateTime.Now;
var results = serializer.Serialize(application);
Assert.NotEqual(results, string.Empty);
Assert.True(results.Contains("LoanApplication"));
System.Console.WriteLine(results);
// turn the serialized results into an object:
var loanApplication = serializer.Deserialize(results);
Assert.IsAssignableFrom<ILoanApplication>(loanApplication);
}
#region Nested type: IApplication
public interface IApplication : IMessage
{
string ApplicationNumber { get; set; }
DateTime ReceivedOn { get; set; }
}
#endregion
#region Nested type: ILoanApplication
public interface ILoanApplication : IApplication
{
}
#endregion
}
} |
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace streamdeck_client_csharp.Events
{
public class TitleParametersPayload
{
[JsonProperty("settings")]
public JObject Settings { get; private set; }
[JsonProperty("coordinates")]
public Coordinates Coordinates { get; private set; }
[JsonProperty("state")]
public uint State { get; private set; }
[JsonProperty("title")]
public string Title { get; private set; }
[JsonProperty("titleParameters")]
public TitleParameters TitleParameters { get; private set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using SnealUltra.Assets._Project.Scripts.Mixins;
public class FloatData : MixinBase
{
[SerializeField]
float data;
public CurrentWeaponData weaponDefination;
public List<MixinBase> updateMixins;
public override void Awake()
{
data = weaponDefination.GetShots();
}
public float GetData()
{
return data;
}
public void SetData(float newData)
{
data = newData;
Action();
}
public void IncrementData(float num)
{
data += num;
Action();
}
public override void Action()
{
if(updateMixins.Count>0)
{
for (int i = 0; i < updateMixins.Count; i++)
{
updateMixins[i].Action();
}
}
}
}
|
using System;
using MassTransit;
using MassTransit.Context;
using MassTransit.RabbitMqTransport;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace Notiflow.Messaging.Shared.Bus
{
public static class MassTransitExtensions
{
public static void AddMassTransitBus(this IServiceCollection services, RabbitMqSettings rabbitMqSettings,
Action<IRabbitMqBusFactoryConfigurator, IRabbitMqHost> registrationAction = null)
{
var serviceProvider = services.BuildServiceProvider();
// Handle Logging
var loggerFactory = serviceProvider.GetRequiredService<ILoggerFactory>();
LogContext.ConfigureCurrentLogContext(loggerFactory);
// Configure Bus
var bus = ConfigureBus(rabbitMqSettings, registrationAction);
// Register Interfaces
services.AddSingleton<IPublishEndpoint>(bus);
services.AddSingleton<ISendEndpointProvider>(bus);
services.AddSingleton<IBus>(bus);
services.AddSingleton<IBusControl>(bus);
try
{
bus.Start();
}
catch (Exception ex)
{
var logger = loggerFactory.CreateLogger(nameof(AddMassTransitBus));
logger?.LogError($"Bus could not started. Error: {ex.Message}, StackTrace: {ex.StackTrace}");
}
}
private static IBusControl ConfigureBus(
RabbitMqSettings settings,
Action<IRabbitMqBusFactoryConfigurator, IRabbitMqHost> registrationAction = null)
{
if (settings.UseInMemoryQueue)
{
return MassTransit.Bus.Factory.CreateUsingInMemory(cfg => { });
}
else
{
return MassTransit.Bus.Factory.CreateUsingRabbitMq(cfg =>
{
var host = cfg.Host(new Uri(settings.RabbitMqUri), hst =>
{
hst.Username(settings.UserName);
hst.Password(settings.Password);
});
registrationAction?.Invoke(cfg, host);
});
}
}
}
} |
using System;
namespace LeetCode.Naive.Problems
{
/// <summary>
/// Problem: https://leetcode.com/problems/queries-on-number-of-points-inside-a-circle/
/// Submission: https://leetcode.com/submissions/detail/490782502/
/// </summary>
internal class P1828
{
public class Solution
{
public int[] CountPoints(int[][] points, int[][] queries)
{
var ans = new int[queries.Length];
for (var i = 0; i < queries.Length; ++i)
{
foreach (var point in points)
{
var distance = Math.Sqrt(
(queries[i][0] - point[0]) * (queries[i][0] - point[0]) +
(queries[i][1] - point[1]) * (queries[i][1] - point[01]));
if (distance <= queries[i][2])
ans[i]++;
}
}
return ans;
}
}
}
}
|
using Hathor.Models.Responses;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Hathor.Client.Sample.WebApp.Models
{
public class IndexViewModel
{
public bool? IsNodeRunning { get; set; }
public AddressResponse? Address { get; set; }
public BalanceResponse? Balance { get; set; }
public TxHistoryResponse? TxHistory { get; set; }
public AddressesResponse Addresses { get; set; } = default!;
public TransactionModel TransactionModel { get; set; } = new TransactionModel();
}
}
|
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Identity;
using Nano.Models.Attributes;
namespace Nano.Models
{
/// <summary>
/// Default Entity User.
/// </summary>
public class DefaultEntityUser : DefaultEntity
{
/// <summary>
/// Identity User Id.
/// </summary>
[MaxLength(128)]
public virtual string IdentityUserId { get; set; }
/// <summary>
/// Identity User.
/// Always included using <see cref="IncludeAttribute"/>.
/// </summary>
[Include]
public virtual IdentityUser IdentityUser { get; set; }
}
} |
using Newtonsoft.Json;
namespace LichessApi.Web.Api.Puzzles.Response{
public class Themes
{
[JsonProperty("advancedPawn")]
public AdvancedPawn AdvancedPawn { get; set; }
[JsonProperty("anastasiaMate")]
public AnastasiaMate AnastasiaMate { get; set; }
}
} |
using System;
using BenchmarkSuite.Framework.Interfaces;
namespace BenchmarkSuite.Logging
{
public class EmptyLogger : ILog
{
#region ILog implementation
public void Trace(object message)
{
}
public void Trace(object message, Exception exception)
{
}
public void TraceFormat(string format, params object[] args)
{
}
public void Debug(object message)
{
}
public void Debug(object message, Exception exception)
{
}
public void DebugFormat(string format, params object[] args)
{
}
public void Info(object message)
{
}
public void Info(object message, Exception exception)
{
}
public void InfoFormat(string format, params object[] args)
{
}
public void Warn(object message)
{
}
public void Warn(object message, Exception exception)
{
}
public void WarnFormat(string format, params object[] args)
{
}
public void Error(object message)
{
}
public void Error(object message, Exception exception)
{
}
public void ErrorFormat(string format, params object[] args)
{
}
public void Fatal(object message)
{
}
public void Fatal(object message, Exception exception)
{
}
public void FatalFormat(string format, params object[] args)
{
}
public bool IsDebugEnabled
{
get
{
return false;
}
}
public bool IsTraceEnabled
{
get
{
return false;
}
}
public bool IsInfoEnabled
{
get
{
return false;
}
}
public bool IsWarnEnabled
{
get
{
return false;
}
}
public bool IsErrorEnabled
{
get
{
return false;
}
}
public bool IsFatalEnabled
{
get
{
return false;
}
}
#endregion
public EmptyLogger()
{
}
}
}
|
using System.Collections.Generic;
using E_Commerce_Shop.Entity;
namespace E_Commerce_Shop.DataAccess.Abstract
{
public interface ICategoryRepository : IRepository<Category>
{
Category GetByIdWithProducts(int id);
void DeleteProductFromCategory(int productId, int categoryId);
}
} |
using System.Collections.Generic;
namespace FortiGateMigration
{
public abstract class FgCommand
{
public string Name { get; set; }
public FgCommand(string name)
{
Name = name;
}
}
public abstract class FgCommandExt : FgCommand
{
public List<FgCommand> SubCommandsList { get; set; }
public FgCommandExt(string name) : base(name)
{
SubCommandsList = new List<FgCommand>();
}
public void addSubCommandToList(FgCommand fgCommand)
{
SubCommandsList.Add(fgCommand);
}
}
public class FgCommand_Config : FgCommandExt
{
public string ObjectName { get; set; }
public FgCommand_Config(string objectName) : base("config")
{
ObjectName = objectName;
}
}
public class FgCommand_Edit : FgCommandExt
{
public string Table { get; set; }
public FgCommand_Edit(string tableName) : base("edit")
{
Table = tableName.Trim('"');
}
}
public class FgCommand_Set : FgCommand
{
public string Field { get; set; }
public string Value { get; set; }
public FgCommand_Set(string args) : base("set")
{
if (args.IndexOf(" ") != -1)
{
Field = args.Substring(0, args.IndexOf(" "));
Value = args.Substring(args.IndexOf(" ")).Trim();
Value = Value.Trim('"');
}
else
{
Field = args;
Value = "";
}
}
}
public class FgCommand_UnSet : FgCommand
{
public string Field { get; set; }
public string Value { get; set; }
public FgCommand_UnSet(string args) : base("unset")
{
if (args.IndexOf(" ") != -1)
{
Field = args.Substring(0, args.IndexOf(" "));
Value = args.Substring(args.IndexOf(" ")).Trim();
Value = Value.Trim('"');
}
else
{
Field = args;
Value = "";
}
}
}
}
|
using System.Text.Json.Serialization;
namespace Essensoft.Paylink.Alipay.Domain
{
/// <summary>
/// PrizePriceStrategy Data Structure.
/// </summary>
public class PrizePriceStrategy : AlipayObject
{
/// <summary>
/// 根据不同的奖品类型填写不同的值,具体用法联系营销技术获取
/// </summary>
[JsonPropertyName("max_price")]
public string MaxPrice { get; set; }
/// <summary>
/// 根据不同的奖品类型填写不同的值,具体用法联系营销技术获取
/// </summary>
[JsonPropertyName("min_price")]
public string MinPrice { get; set; }
/// <summary>
/// 废弃-不再使用
/// </summary>
[JsonPropertyName("stragety_value")]
public string StragetyValue { get; set; }
/// <summary>
/// RANDOM_PRICE随机,FIX_PRICE定额奖品,不同的定价策略填写不同值,具体根据业务评估
/// </summary>
[JsonPropertyName("strategy_type")]
public string StrategyType { get; set; }
/// <summary>
/// 定价策略值,根据不同的奖品类型填写不同的值,具体用法联系营销技术获取
/// </summary>
[JsonPropertyName("strategy_value")]
public string StrategyValue { get; set; }
}
}
|
namespace x42.Controllers.Results
{
/// <summary>
/// Class representing the ping result of the currently running node.
/// </summary>
public class PingResult
{
/// <summary>
/// Initializes a new instance of the <see cref="PingResult" /> class.
/// </summary>
public PingResult() { }
/// <summary>The node's version.</summary>
public string Version { get; set; }
/// <summary>The nodes best block height.</summary>
public uint? BestBlockHeight { get; set; }
/// <summary>The node's tier level.</summary>
public int Tier { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lake.AmazonConnect.Model
{
/// <summary>
/// Response metadata.
/// </summary>
public class ResponseMetadata
{
/// <summary>
/// Gets or sets the ID that uniquely identifies a request.
/// Amazon keeps track of request IDs. If you have a question about a request, include
/// the request ID in your correspondence.
/// </summary>
public string RequestId { get; set; }
/// <summary>
/// Gets or sets the metadata.
/// </summary>
public IDictionary<string, string> Metadata { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
namespace Duality.Editor.Plugins.ProjectView.Properties
{
/// <summary>
/// Since directly accessing code generated from .resx files will result in a deserialization on
/// each Resource access, this class allows cached Resource access.
/// </summary>
public static class ProjectViewResCache
{
public static readonly Icon IconProjectView = ProjectViewRes.IconProjectView;
}
}
|
using System;
using System.Collections.Generic;
using FOS.Website.Feature.ContentBlocks.Data;
using FOS.Website.Feature.ContentBlocks.Helpers;
using Sitecore.Data.Fields;
using Sitecore.Mvc.Presentation;
using Sitecore.StringExtensions;
using Synthesis;
using Synthesis.FieldTypes.Interfaces;
namespace FOS.Website.Feature.ContentBlocks.Models
{
public class TickersModel : ContentBlockModelBase
{
public int NrTickers { get; set; } = 0;
public IEnumerable<ITextField> TickerList { get; set; }
public TickersModel(I_TickersItem tickerItem)
{
var tickerList = new List<ITextField>();
if (tickerItem != null)
{
AddTextField(ref tickerList, tickerItem.Statement1);
AddTextField(ref tickerList, tickerItem.Statement2);
AddTextField(ref tickerList, tickerItem.Statement3);
AddTextField(ref tickerList, tickerItem.Statement4);
AddTextField(ref tickerList, tickerItem.Statement5);
}
TickerList = tickerList;
}
private void AddTextField(ref List<ITextField> list, ITextField field)
{
if (field.HasTextValue)
NrTickers++;
list.Add(field);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Zaggoware.BugTracker.Common.Helpers
{
public static class UrlHelper
{
public static string CreateUrlFromName(string name, bool convertToLower)
{
var url = name;
if (convertToLower)
{
url = url.ToLower();
}
return url.Replace(" ", "-");
}
}
}
|
namespace StevenVolckaert.InventorPowerTools.Buttons
{
using System;
using System.Drawing;
using System.Windows;
using Inventor;
/// <summary>
/// Base class for Inventor buttons.
/// </summary>
internal abstract class ButtonBase : IDisposable
{
protected readonly ButtonDefinition _buttonDefinition;
/// <summary>
/// Gets the button's name.
/// </summary>
public string Name { get; }
/// <summary>
/// Gets the button's command type.
/// </summary>
public virtual CommandTypesEnum CommandType { get; } = CommandTypesEnum.kShapeEditCmdType;
/// <summary>
/// Gets the button's display name.
/// </summary>
public abstract string DisplayName { get; }
/// <summary>
/// Gets the button's display type.
/// </summary>
public virtual ButtonDisplayEnum DisplayType { get; } = ButtonDisplayEnum.kDisplayTextInLearningMode;
/// <summary>
/// Gets the button's description
/// </summary>
public virtual string Description
{
get { return DisplayName; }
}
/// <summary>
/// Gets the button's tool tip.
/// </summary>
public virtual string ToolTip
{
get { return Description; }
}
/// <summary>
/// Gets or sets the panel to which the button belongs.
/// </summary>
public RibbonPanel Panel { get; set; }
protected static DrawingDocument DrawingDocument
{
get { return (DrawingDocument)AddIn.ActiveDocument; }
}
/// <summary>
/// Gets or sets a value that indicates whether the button is enabled.
/// </summary>
public bool IsEnabled
{
get { return _buttonDefinition.Enabled; }
set { _buttonDefinition.Enabled = value; }
}
protected ButtonBase()
{
var typeName = GetType().Name;
Name = "Autodesk:PowerTools:" + typeName;
try
{
var standardIcon = ImageConvert.FromIconToIPictureDisp(
icon: new Icon(typeof(ButtonBase), typeName + ".ico")
);
_buttonDefinition =
AddIn.Inventor.CommandManager.ControlDefinitions.AddButtonDefinition(
DisplayName: DisplayName,
InternalName: Name,
Classification: CommandType,
ClientId: AddIn.ClientId,
DescriptionText: Description,
ToolTipText: ToolTip,
StandardIcon: standardIcon,
LargeIcon: standardIcon,
ButtonDisplay: DisplayType
);
_buttonDefinition.OnExecute += OnExecute;
IsEnabled = false;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
public void Dispose()
{
if (_buttonDefinition != null)
_buttonDefinition.OnExecute -= OnExecute;
}
protected abstract void OnExecute(NameValueMap context);
/// <summary>
/// Adds the button to a specified command bar.
/// </summary>
/// <param name="commandBar">The command bar to add the button to.</param>
/// <exception cref="ArgumentNullException"><paramref name="commandBar"/> is <c>null</c>.</exception>
public void AddTo(CommandBar commandBar)
{
if (commandBar == null)
throw new ArgumentNullException(nameof(commandBar));
commandBar.Controls.AddButton(_buttonDefinition, Before: 0);
}
/// <summary>
/// Adds the button to a specified ribbon panel.
/// </summary>
/// <param name="ribbonPanel">The ribbon panel.</param>
public void AddTo(RibbonPanel ribbonPanel)
{
AddTo(ribbonPanel, targetControlName: string.Empty, insertBeforeTargetControl: false);
}
/// <summary>
/// Adds the button to a specified ribbon panel.
/// </summary>
/// <param name="ribbonPanel">The ribbon panel.</param>
/// <param name="targetControlName">The name of an existing control to position the button next to.</param>
/// <param name="insertBeforeTargetControl">A value that indicates whether to position the button before or
/// after the target control.</param>
/// <exception cref="ArgumentNullException"><paramref name="ribbonPanel"/> or
/// <paramref name="targetControlName"/> is <c>null</c>.</exception>
public void AddTo(RibbonPanel ribbonPanel, string targetControlName, bool insertBeforeTargetControl)
{
if (ribbonPanel == null)
throw new ArgumentNullException(nameof(ribbonPanel));
if (targetControlName == null)
throw new ArgumentNullException(nameof(targetControlName));
ribbonPanel.CommandControls.AddButton(
ButtonDefinition: _buttonDefinition,
UseLargeIcon: true,
ShowText: true,
TargetControlInternalName: targetControlName,
InsertBeforeTargetControl: insertBeforeTargetControl
);
}
/// <summary>
/// Adds the button to its panel.
/// </summary>
public virtual void AddToPanel()
{
if (Panel == null)
return;
try
{
AddTo(Panel);
}
catch
{
// The button already exists.
// TODO Update it's buttondefinition.
}
}
/// <summary>
/// Adds the button to a specified command category. If the specified category doesn't exist, it is created.
/// </summary>
/// <param name="categoryName">The name of the category.</param>
/// <param name="displayName">The display name of the category, if it should be created.</param>
public void AddToCommandCategory(string categoryName, string displayName)
{
try
{
var commandCategories = AddIn.Inventor.CommandManager.CommandCategories;
var commandCategory =
commandCategories.TryGetValue(categoryName) ??
commandCategories.Add(displayName, categoryName, AddIn.ClientId);
commandCategory.Add(_buttonDefinition);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
protected void ShowMessageBox(string message)
{
ShowMessageBox("{0}", message);
}
protected void ShowMessageBox(string messageFormat, params object[] messageArgs)
{
AddIn.ShowMessageBox(DisplayName, messageFormat, messageArgs);
}
protected void ShowWarningMessageBox(Exception exception)
{
ShowWarningMessageBox("{0}", exception.ToString());
}
protected void ShowWarningMessageBox(string messageFormat, params object[] messageArgs)
{
AddIn.ShowWarningMessageBox(DisplayName, messageFormat, messageArgs);
}
}
}
|
using System.Reflection;
namespace Telerik.Sitefinity.Frontend.TestUtilities
{
/// <summary>
/// Helper for common operations related to Assemblies loading and reflection.
/// </summary>
public static class AssemblyLoaderHelper
{
/// <summary>
/// Gets the Test Utilities Assembly
/// </summary>
/// <returns>Assembly context</returns>
public static Assembly GetTestUtilitiesAssembly()
{
return Assembly.GetExecutingAssembly();
}
}
} |
/*
* Copyright (c) 2018, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Runtime.InteropServices;
namespace XGBoostBindings
{
/**
* xgboost c api bindings
*/
public class Bindings
{
public const string LibName = "libxgboost";
/*!
* get string message of the last error
*
* all function in this file will return 0 when success
* and -1 when an error occurred,
* XGBGetLastError can be called to retrieve the error
*
* this function is thread safe and can be called by different thread
* \return const char* error information
*/
[DllImport(LibName)]
public static extern string XGBGetLastError();
/*!
* create matrix content from dense matrix
* \param data pointer to the data space
* \param nrow number of rows
* \param ncol number columns
* \param missing which value to represent missing value
* \param out created dmatrix
* \return 0 when success, -1 when failure happens
*/
[DllImport(LibName)]
public static extern int XGDMatrixCreateFromMat(float[] data, ulong nRow, ulong nCol,
float missing, out IntPtr handle);
/*!
* \brief free space in data matrix
* \return 0 when success, -1 when failure happens
*/
[DllImport(LibName)]
public static extern int XGDMatrixFree(IntPtr handle);
/*!
* \brief set float vector to a content in info
* \param handle a instance of data matrix
* \param field field name, can be label, weight
* \param array pointer to float vector
* \param len length of array
* \return 0 when success, -1 when failure happens
*/
[DllImport(LibName)]
public static extern int XGDMatrixSetFloatInfo(IntPtr handle, string field,
float[] array, ulong len);
/*!
* \brief get float info vector from matrix
* \param handle a instance of data matrix
* \param field field name
* \param out_len used to set result length
* \param out_dptr pointer to the result
* \return 0 when success, -1 when failure happens
*/
[DllImport(LibName)]
public static extern int XGDMatrixGetFloatInfo(IntPtr handle, string field,
out ulong len, out IntPtr result);
/*!
* \brief create xgboost learner
* \param dmats matrices that are set to be cached
* \param len length of dmats
* \param out handle to the result booster
* \return 0 when success, -1 when failure happens
*/
[DllImport(LibName)]
public static extern int XGBoosterCreate(IntPtr[] matrices,
ulong len, out IntPtr handle);
/*!
* \brief set parameters
* \param handle handle
* \param name parameter name
* \param value value of parameter
* \return 0 when success, -1 when failure happens
*/
[DllImport(LibName)]
public static extern int XGBoosterSetParam(IntPtr handle, string name, string val);
/*!
* \brief update the model in one round using dtrain
* \param handle handle
* \param iter current iteration rounds
* \param dtrain training data
* \return 0 when success, -1 when failure happens
*/
[DllImport(LibName)]
public static extern int XGBoosterUpdateOneIter(IntPtr bHandle, int iteration,
IntPtr dHandle);
/*!
* \brief make prediction based on dmat
* \param handle handle
* \param dmat data matrix
* \param option_mask bit-mask of options taken in prediction, possible values
* 0:normal prediction
* 1:output margin instead of transformed value
* 2:output leaf index of trees instead of leaf value, note leaf index is unique per tree
* 4:output feature contributions to individual predictions
* \param ntree_limit limit number of trees used for prediction, this is only valid for boosted trees
* when the parameter is set to 0, we will use all the trees
* \param out_len used to store length of returning result
* \param out_result used to set a pointer to array
* \return 0 when success, -1 when failure happens
*/
[DllImport(LibName)]
public static extern int XGBoosterPredict(IntPtr bHandle, IntPtr dHandle,
int optionMask, int ntreeLimit,
out ulong pLen, out IntPtr pPtr);
}
}
|
@using iTechArt.ManagementDemo.Web
@using iTechArt.ManagementDemo.Web.Models
@using iTechArt.ManagementDemo.Web.Models.Table
@using iTechArt.ManagementDemo.Querying.Models
@using Newtonsoft.Json;
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
|
namespace Qsi.Cql.Schema
{
public abstract class CqlType
{
internal CqlType()
{
}
public abstract string ToSql();
public override string ToString()
{
return ToSql();
}
}
}
|
#region License
// Distributed under the MIT License
// ============================================================
// Copyright (c) 2019 Hotcakes Commerce, LLC
// Copyright (c) 2020 Upendo Ventures, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software
// and associated documentation files (the "Software"), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge, publish, distribute,
// sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#endregion
using System.Collections.Generic;
using Hotcakes.Commerce.Content;
using Hotcakes.Commerce.Marketing;
using Hotcakes.Commerce.Membership;
using Hotcakes.Commerce.Utilities;
namespace Hotcakes.Commerce.Contacts
{
public abstract class ContactService : HccServiceBase
{
public ContactService(HccRequestContext context)
: base(context)
{
Affiliates = Factory.CreateRepo<AffiliateRepository>(Context);
Addresses = Factory.CreateRepo<AddressRepository>(Context);
PriceGroups = Factory.CreateRepo<PriceGroupRepository>(Context);
MailingLists = Factory.CreateRepo<MailingListRepository>(Context);
Vendors = Factory.CreateRepo<VendorRepository>(Context);
Manufacturers = Factory.CreateRepo<ManufacturerRepository>(Context);
AffiliateReferrals = Factory.CreateRepo<AffiliateReferralRepository>(Context);
AffiliatePayments = Factory.CreateRepo<AffiliatePaymentRepository>(Context);
}
public AffiliateRepository Affiliates { get; protected set; }
public AffiliateReferralRepository AffiliateReferrals { get; protected set; }
public AffiliatePaymentRepository AffiliatePayments { get; protected set; }
public AddressRepository Addresses { get; protected set; }
public PriceGroupRepository PriceGroups { get; protected set; }
public MailingListRepository MailingLists { get; protected set; }
public VendorRepository Vendors { get; protected set; }
public ManufacturerRepository Manufacturers { get; protected set; }
public abstract void UpdateProfileAffiliateId(long affiliateId);
public abstract void SetAffiliateReferral(string affiliateId, string referralUrl);
public abstract long? GetCurrentAffiliateId();
public void AffiliateWasApproved(Affiliate aff, string culture = "")
{
var membershipServices = Factory.CreateService<MembershipServices>(Context);
var marketingService = Factory.CreateService<MarketingService>(Context);
var acc = membershipServices.Customers.Find(aff.UserId.ToString());
marketingService.ApplyAffiliatePromotions(acc);
SendAffiliateApprovementEmail(aff, culture);
}
public void SendNewRolesAssignment(CustomerAccount acc, string[] roles)
{
var roleTags = new Replaceable("[[User.NewRoles]]", string.Join(", ", roles));
var storeSettingsProvider = Factory.CreateStoreSettingsProvider();
var defaultCulture = storeSettingsProvider.GetDefaultLocale();
var hccRequestContext = HccRequestContextUtils.GetContextWithCulture(Context, defaultCulture);
var contentService = Factory.CreateService<ContentService>(hccRequestContext);
var template = contentService.GetHtmlTemplateOrDefault(HtmlTemplateType.NewRoleAssignment);
template = template.ReplaceTagsInTemplate(hccRequestContext, new List<IReplaceable> {acc, roleTags});
var message = template.ConvertToMailMessage(acc.Email);
MailServices.SendMail(message, hccRequestContext.CurrentStore);
}
public void SendAffiliateConfirmationEmail(Affiliate aff, string defaultCulture = "")
{
var storeSettingsProvider = Factory.CreateStoreSettingsProvider();
if (string.IsNullOrEmpty(defaultCulture))
{
defaultCulture = storeSettingsProvider.GetDefaultLocale();
}
var hccRequestContext = HccRequestContextUtils.GetContextWithCulture(Context, defaultCulture);
var contentService = Factory.CreateService<ContentService>(hccRequestContext);
var template = contentService.GetHtmlTemplateOrDefault(HtmlTemplateType.AffiliateRegistration);
template = template.ReplaceTagsInTemplate(hccRequestContext, aff);
var message = template.ConvertToMailMessage(aff.Email);
MailServices.SendMail(message, hccRequestContext.CurrentStore);
}
public void SendAffiliateReviewEmail(Affiliate aff)
{
var storeSettingsProvider = Factory.CreateStoreSettingsProvider();
var defaultCulture = storeSettingsProvider.GetDefaultLocale();
var hccRequestContext = HccRequestContextUtils.GetContextWithCulture(Context, defaultCulture);
var contentService = Factory.CreateService<ContentService>(hccRequestContext);
var template = contentService.GetHtmlTemplateOrDefault(HtmlTemplateType.AffiliateReview);
template = template.ReplaceTagsInTemplate(hccRequestContext, aff);
var storeAdmin = hccRequestContext.CurrentStore.Settings.MailServer.EmailForNewOrder;
var message = template.ConvertToMailMessage(storeAdmin);
MailServices.SendMail(message, hccRequestContext.CurrentStore);
}
public void SendAffiliateApprovementEmail(Affiliate aff, string culture = "")
{
var storeSettingsProvider = Factory.CreateStoreSettingsProvider();
if (string.IsNullOrEmpty(culture))
{
culture = storeSettingsProvider.GetDefaultLocale();
}
var hccRequestContext = HccRequestContextUtils.GetContextWithCulture(Context, culture);
var contentService = Factory.CreateService<ContentService>(hccRequestContext);
var template = contentService.GetHtmlTemplateOrDefault(HtmlTemplateType.AffiliateApprovement);
template = template.ReplaceTagsInTemplate(hccRequestContext, aff);
var message = template.ConvertToMailMessage(aff.Email);
MailServices.SendMail(message, hccRequestContext.CurrentStore);
}
#region Implementation
protected bool LogReferral(long affiliateId, string referrerUrl)
{
var aff = Affiliates.Find(affiliateId);
if (aff != null && aff.Enabled && aff.Approved)
{
var r = new AffiliateReferral();
r.AffiliateId = aff.Id;
r.ReferrerUrl = referrerUrl;
return AffiliateReferrals.Create(r);
}
return false;
}
#endregion
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Client.ServiceReference1;
namespace Client
{
public partial class AddTestForm : Form
{
private TestServiceClient client;
private int testCount = 0;
public AddTestForm(TestServiceClient client)
{
InitializeComponent();
this.client = client;
}
private void addTestButton_Click(object sender, EventArgs e)
{
if (testNameTB.Text == string.Empty)
{
MessageBox.Show("Введите название теста!");
return;
}
TestDTO t = new TestDTO();
t.Name = testNameTB.Text;
if (this.client.AddTest(t))
testCount++;
else
{
MessageBox.Show("Тест с таким названием уже существует!");
return;
}
testCountLabel.Text = "Добавлено тестов: " + testCount.ToString();
testNameTB.ResetText();
}
}
}
|
using UnityEngine;
namespace Sample.Service {
public sealed class EditorAnalytics : IAnalyticsService {
public void SendEvent(string name) =>
Debug.Log($"EditorAnalytics.SendEvent: '{name}'");
}
} |
// Copyright (c) 2007-2018 Thong Nguyen (tumtumtum@gmail.com)
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
namespace Shaolinq.Persistence.Linq
{
public class ProjectionBuilderScope
{
public Dictionary<string, int> ColumnIndexes { get; }
public readonly List<Expression> rootPrimaryKeys = new List<Expression>();
public ProjectionBuilderScope(string[] columnNames)
: this(columnNames.Select((c, i) => new { c, i }).ToDictionary(c => c.c, c => c.i))
{
}
public ProjectionBuilderScope(Dictionary<string, int> columnIndexes)
{
this.ColumnIndexes = columnIndexes;
}
}
} |
using System.Collections.Generic;
using System.Diagnostics;
using Machine.Specifications.Runner.Impl.Listener;
namespace Machine.Specifications.Runner
{
public class TimingRunListener : ISpecificationRunListener
{
readonly Stopwatch _assemblyTimer = new Stopwatch();
readonly Dictionary<AssemblyInfo, long> _assemblyTimes = new Dictionary<AssemblyInfo, long>();
readonly Stopwatch _contextTimer = new Stopwatch();
readonly Dictionary<ContextInfo, long> _contextTimes = new Dictionary<ContextInfo, long>();
readonly Stopwatch _runTimer = new Stopwatch();
readonly Stopwatch _specificationTimer = new Stopwatch();
readonly Dictionary<SpecificationInfo, long> _specificationTimes = new Dictionary<SpecificationInfo, long>();
public void OnRunStart()
{
_runTimer.Restart();
}
public void OnRunEnd()
{
_runTimer.Stop();
}
public void OnAssemblyStart(AssemblyInfo assembly)
{
_assemblyTimer.Restart();
}
public void OnAssemblyEnd(AssemblyInfo assembly)
{
_assemblyTimer.Stop();
_assemblyTimes[assembly] = _assemblyTimer.ElapsedMilliseconds;
}
public void OnContextStart(ContextInfo context)
{
_contextTimer.Restart();
_specificationTimer.Restart();
}
public void OnContextEnd(ContextInfo context)
{
_contextTimer.Stop();
_contextTimes[context] = _contextTimer.ElapsedMilliseconds;
}
public void OnSpecificationStart(SpecificationInfo specification)
{
if (!_specificationTimer.IsRunning)
{
_specificationTimer.Restart();
}
}
public void OnSpecificationEnd(SpecificationInfo specification, Result result)
{
_specificationTimer.Stop();
_specificationTimes[specification] = _specificationTimer.ElapsedMilliseconds;
}
public void OnFatalError(ExceptionResult exception)
{
}
public long GetSpecificationTime(SpecificationInfo specificationInfo)
{
if (_specificationTimes.ContainsKey(specificationInfo))
{
return _specificationTimes[specificationInfo];
}
return -1;
}
public long GetContextTime(ContextInfo contextInfo)
{
if (_contextTimes.ContainsKey(contextInfo))
{
return _contextTimes[contextInfo];
}
return -1;
}
public long GetAssemblyTime(AssemblyInfo assemblyInfo)
{
if (_assemblyTimes.ContainsKey(assemblyInfo))
{
return _assemblyTimes[assemblyInfo];
}
return -1;
}
public long GetRunTime()
{
return _runTimer.ElapsedMilliseconds;
}
}
static class TimerExtensions
{
public static void Restart(this Stopwatch timer)
{
timer.Reset();
timer.Start();
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Expression;
namespace PreviewApp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Database db = new Database();
private void button1_Click(object sender, EventArgs e)
{
//Dictionary<string, int> countSad = new Dictionary<string, int>();
//Dictionary<string, int> countHappy = new Dictionary<string, int>();
//db.getCountExpresiLogUser(ref countSad, ref countHappy, "purwanto@outlook.com");
//Console.WriteLine(" Jumlah Sedih");
//int i = 1;
//foreach (var item in countSad)
//{
// Console.WriteLine("{0}: {1}->{2}",i,item.Key,item.Value);
// i++;
//}
//Console.WriteLine("Jumlah Senang");
//int j = 1;
//foreach (var item in countHappy)
//{
// Console.WriteLine("{0}: {1}->{2}", j, item.Key, item.Value);
// j++;
//}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NetCheatX.Core.Interfaces
{
/// <summary>
/// Search result plugin interface
/// </summary>
public interface ISearchResult
{
/// <summary>
/// Memory address of result
/// </summary>
ulong Address { get; set; }
/// <summary>
/// Value of result
/// </summary>
byte[] Value { get; set; }
/// <summary>
/// Converts the ISearchResult into an array of bytes to be stored into a scan file
/// </summary>
/// <param name="bytes">Resulting byte array after conversion</param>
void ToByteArray(out byte[] bytes);
/// <summary>
/// Loads byte array information into ISearchResult instance
/// </summary>
/// <param name="bytes">ISearchResult in a byte array</param>
void FromByteArray(byte[] bytes);
}
}
|
using System.Collections.Immutable;
namespace Funcky.Test.Monads
{
public sealed partial class OptionTest
{
[Fact]
public void NoneIsLessThanSome()
{
Assert.True(Option<int>.None() < Option.Some(10));
Assert.True(Option<int>.None() <= Option.Some(10));
}
[Fact]
public void SomeIsGreaterThanNone()
{
Assert.True(Option.Some(10) > Option<int>.None());
Assert.True(Option.Some(10) >= Option<int>.None());
}
[Fact]
public void GreaterSomeValueIsGreaterThanSomeValue()
{
Assert.True(Option.Some(20) > Option.Some(10));
Assert.True(Option.Some(20) >= Option.Some(10));
}
[Fact]
public void LessSomeValueIsLessThanSomeValue()
{
Assert.True(Option.Some(10) < Option.Some(20));
Assert.True(Option.Some(10) <= Option.Some(20));
}
[Fact]
public void CompareToReturnsZeroWhenValuesAreEqual()
{
Assert.Equal(0, Option.Some(10).CompareTo(Option.Some(10)));
}
[Fact]
public void CompareToReturnsZeroWhenBothAreNone()
{
Assert.Equal(0, Option<string>.None().CompareTo(Option<string>.None()));
}
[Fact]
public void OptionIsGreaterThanNull()
{
Assert.True(Option.Some(10).CompareTo(null) > 0);
}
[Fact]
public void CompareToThrowsWhenRhsIsNotAnOption()
{
var option = Option.Some(10);
Assert.Throws<ArgumentException>(() => _ = option.CompareTo("hello"));
}
[Fact]
public void CompareToThrowsWhenRhsIsOptionWithDifferentItemType()
{
var optionOfInt = Option.Some(10);
var optionOfString = Option.Some("hello");
Assert.Throws<ArgumentException>(() => _ = optionOfInt.CompareTo(optionOfString));
}
[Fact]
public void EnumerableOfOptionsCanBeSorted()
{
var unsorted = ImmutableList.Create(
Option.Some(5),
Option<int>.None(),
Option.Some(0),
Option.Some(10),
Option<int>.None());
var expected = ImmutableList.Create(
Option<int>.None(),
Option<int>.None(),
Option.Some(0),
Option.Some(5),
Option.Some(10));
var sorted = unsorted.Sort();
Assert.Equal(expected, sorted);
}
[Fact]
public void CompareToThrowsWhenTwoSomeValuesWhereItemTypeIsNotComparableAreCompared()
{
var optionOne = Option.Some(new Person());
var optionTwo = Option.Some(new Person());
Assert.Throws<ArgumentException>(() => _ = optionOne.CompareTo(optionTwo));
}
[Fact]
public void CompareToDoesNotThrowWhenTwoNoneValuesWhereItemTypeIsNotComparableAreCompared()
{
var optionOne = Option<Person>.None();
var optionTwo = Option<Person>.None();
_ = optionOne.CompareTo(optionTwo);
}
[Fact]
public void CompareToDoesNotThrowWhenNoneValueAndSomeValueWhereItemTypeIsNotComparableAreCompared()
{
var optionOne = Option.Some(new Person());
var optionTwo = Option<Person>.None();
_ = optionOne.CompareTo(optionTwo);
_ = optionTwo.CompareTo(optionOne);
}
private sealed class Person
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Serialization;
namespace BNSharp.BattleNet
{
/// <summary>
/// Contains information about a change in advertisements.
/// </summary>
[Serializable]
[DataContract]
public class AdChangedEventArgs : BaseEventArgs
{
[DataMember(Name = "AdID")]
private int m_adID;
[DataMember(Name = "FileTime")]
private DateTime m_fileTime;
[DataMember(Name = "Filename")]
private string m_filename;
[DataMember(Name = "LinkUrl")]
private string m_linkUrl;
/// <summary>
/// Creates a new <see>AdChangedEventArgs</see>.
/// </summary>
/// <param name="adID">The unique ID of the ad.</param>
/// <param name="fileTime">The local time of the file's most recent change.</param>
/// <param name="fileName">The name of the file that contains the ad image.</param>
/// <param name="linkUrl">The URL to which the ad links.</param>
public AdChangedEventArgs(int adID, DateTime fileTime, string fileName, string linkUrl)
: base()
{
if (string.IsNullOrEmpty(fileName))
throw new ArgumentNullException("fileName");
if (string.IsNullOrEmpty(linkUrl))
throw new ArgumentNullException("linkUrl");
m_adID = adID;
m_fileTime = fileTime;
m_filename = fileName;
m_linkUrl = linkUrl;
}
/// <summary>
/// Gets the unique ID of the ad.
/// </summary>
public int AdID
{
get { return m_adID; }
}
/// <summary>
/// Gets the local time of the file's most recent change.
/// </summary>
public DateTime FileTime
{
get { return m_fileTime; }
}
/// <summary>
/// Gets the name of the file that has the ad image.
/// </summary>
public string Filename
{
get { return m_filename; }
}
/// <summary>
/// Gets the URL to the link to which the ad links.
/// </summary>
public string LinkUrl
{
get { return m_linkUrl; }
}
}
/// <summary>
/// Specifies the contract for handlers wishing to listen for AdChanged events.
/// </summary>
/// <param name="sender">The object that originated the event.</param>
/// <param name="e">The event arguments.</param>
public delegate void AdChangedEventHandler(object sender, AdChangedEventArgs e);
}
|
using LINGYUN.Abp.Serilog.Enrichers.UniqueId;
using Serilog.Configuration;
using System;
namespace Serilog
{
public static class UniqueIdLoggerConfigurationExtensions
{
public static LoggerConfiguration WithUniqueId(
this LoggerEnrichmentConfiguration enrichmentConfiguration)
{
if (enrichmentConfiguration == null) throw new ArgumentNullException(nameof(enrichmentConfiguration));
return enrichmentConfiguration.With<UniqueIdEnricher>();
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using SqlBuildManager.Enterprise.Policy;
namespace SqlSync.SqlBuild.Policy
{
public partial class PolicyViolationForm : Form
{
Package lstViolations;
bool multiScriptViolations = false;
bool showSaveButtons = true;
private PolicyViolationForm(bool showSaveButtons)
{
this.showSaveButtons = showSaveButtons;
InitializeComponent();
}
public PolicyViolationForm(Package lstViolations, bool showSaveButtons)
: this(showSaveButtons)
{
this.lstViolations = lstViolations;
this.multiScriptViolations = true;
}
public PolicyViolationForm(Script violation, bool showSaveButtons)
: this(new Package(new Script[] { violation }), showSaveButtons)
{
this.multiScriptViolations = false;
}
private void PolicyViolationForm_Load(object sender, EventArgs e)
{
flowMain.Controls.Clear();
List<PolicyViolationControl> ctrls = new List<PolicyViolationControl>();
int height = 0;
for(int i=0;i<lstViolations.Count;i++)
{
PolicyViolationControl ctrl = new PolicyViolationControl();
ctrl.AutoSize = false;
//ctrl.Size = new System.Drawing.Size(784, 52);
ctrl.DataBind(lstViolations[i]);
ctrls.Add(ctrl);
height += ctrl.Height;
}
//int start = 0;
for (int i = 0; i < ctrls.Count; i++)
{
//ctrls[i].Location = new Point(0, start);
flowMain.Controls.Add(ctrls[i]);
// ctrls[i].Size = new Size(908, ctrls[i].Height);
//start += ctrls[i].Height;
}
if (height > 375)
this.Height = 400;
else
this.Height = this.Height + (height + 10 - this.flowMain.Height);
if (this.multiScriptViolations)
{
lblYesButtonMessage.Text = "(Add files and fix later)";
lblNoButtonMessage.Text = "(Cancel Add)";
lblContinueMessage.Text = "Do you want to continue to add these files?";
}
if (this.showSaveButtons)
{
this.saveButtonsTablePanel.Visible = true;
this.btnClose.Visible = false;
}
else
{
this.saveButtonsTablePanel.Visible = false;
this.btnClose.Visible = true;
}
}
private void btnYes_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.Yes;
this.Close();
}
private void btnNo_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.No;
this.Close();
}
private void pictureBox1_Click(object sender, EventArgs e)
{
SqlSync.SqlBuild.UtilityHelper.OpenManual("ScriptPolicyChecking");
}
private void btnClose_Click(object sender, EventArgs e)
{
this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.Close();
}
}
}
|
@{
ViewBag.Title = "UnAuthorize";
}
<h1 class="text-danger">Не сте оторизиран за тази страница!</h1>
|
using System;
using System.ComponentModel.DataAnnotations.Schema;
using Microsoft.EntityFrameworkCore;
namespace Content.Server.Database
{
public sealed class SqliteServerDbContext : ServerDbContext
{
public DbSet<SqliteServerBan> Ban { get; set; } = default!;
public DbSet<SqliteServerUnban> Unban { get; set; } = default!;
public DbSet<SqlitePlayer> Player { get; set; } = default!;
public DbSet<SqliteConnectionLog> ConnectionLog { get; set; } = default!;
public SqliteServerDbContext()
{
}
protected override void OnConfiguring(DbContextOptionsBuilder options)
{
if (!InitializedWithOptions)
options.UseSqlite("dummy connection string");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<SqlitePlayer>()
.HasIndex(p => p.LastSeenUserName);
}
public SqliteServerDbContext(DbContextOptions<ServerDbContext> options) : base(options)
{
}
}
[Table("ban")]
public class SqliteServerBan
{
[Column("ban_id")] public int Id { get; set; }
[Column("user_id")] public Guid? UserId { get; set; }
[Column("address")] public string? Address { get; set; }
[Column("hwid")] public byte[]? HWId { get; set; }
[Column("ban_time")] public DateTime BanTime { get; set; }
[Column("expiration_time")] public DateTime? ExpirationTime { get; set; }
[Column("reason")] public string Reason { get; set; } = null!;
[Column("banning_admin")] public Guid? BanningAdmin { get; set; }
public SqliteServerUnban? Unban { get; set; }
}
[Table("unban")]
public class SqliteServerUnban
{
[Column("unban_id")] public int Id { get; set; }
[Column("ban_id")] public int BanId { get; set; }
public SqliteServerBan Ban { get; set; } = null!;
[Column("unbanning_admin")] public Guid? UnbanningAdmin { get; set; }
[Column("unban_time")] public DateTime UnbanTime { get; set; }
}
[Table("player")]
public class SqlitePlayer
{
[Column("player_id")] public int Id { get; set; }
// Permanent data
[Column("user_id")] public Guid UserId { get; set; }
[Column("first_seen_time")] public DateTime FirstSeenTime { get; set; }
// Data that gets updated on each join.
[Column("last_seen_user_name")] public string LastSeenUserName { get; set; } = null!;
[Column("last_seen_time")] public DateTime LastSeenTime { get; set; }
[Column("last_seen_address")] public string LastSeenAddress { get; set; } = null!;
[Column("last_seen_hwid")] public byte[]? LastSeenHWId { get; set; }
}
[Table("connection_log")]
public class SqliteConnectionLog
{
[Column("connection_log_id")] public int Id { get; set; }
[Column("user_id")] public Guid UserId { get; set; }
[Column("user_name")] public string UserName { get; set; } = null!;
[Column("time")] public DateTime Time { get; set; }
[Column("address")] public string Address { get; set; } = null!;
[Column("hwid")] public byte[]? HWId { get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
public enum EffectName { Typing, RightShot, Approach, LeftShot, Step1, Step2, Step3, Step4, Step5, Performance }
[System.Serializable]
public class EffectTrigger
{
public EffectName name;
}
[System.Serializable]
public class EffectEvent : UnityEvent<EffectTrigger> { } //effect list
public class EffectMgr : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}
|
using Common.Api.Validators;
using FluentValidation;
using ToDo.Api.Models;
namespace ToDo.Api.Validators
{
public class ToDoTaskPostValidator : ValidatorBase<ToDoTaskPost>
{
public ToDoTaskPostValidator()
{
// On a POST description is required
RuleFor(t => t.Description)
.NotEmpty()
.WithMessage(ValidationLibrary.RequiredError)
.Must(d => !string.IsNullOrWhiteSpace(d))
.WithMessage(ValidationLibrary.RequiredError);
// On a POST due date is required
RuleFor(t => t.DueDate)
.NotEmpty()
.WithMessage(ValidationLibrary.RequiredError)
.Must(d => d.IsValidDate())
.WithMessage(ValidationLibrary.ValidDateError)
.Must(d => d.IsFutureDate())
.WithMessage(ValidationLibrary.FutureDateError);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Drw.Combat
{
public class GroundAttack : MonoBehaviour
{
private void OnEnable()
{
Destroy(gameObject, 8f); // TODO - temp
}
}
} |
using System;
using System.Collections.Generic;
using System.Data.SQLite;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
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.Navigation;
using System.Windows.Shapes;
namespace Appaec2
{
/// <summary>
/// ALibrary.xaml 的交互逻辑
/// </summary>
public partial class ALib : Page
{
public ALib()
{
InitializeComponent();
listBox.AddHandler(UIElement.MouseDownEvent, new MouseButtonEventHandler(listBoxItem_Click), true);
}
private void listBoxItem_Click(object sender, MouseButtonEventArgs e)
{
//MessageBox.Show(listBox.SelectedItem, "see");
if (listBox.Items.Count > 0 && listBox.SelectedIndex > -1)
{
ALibModel lm = listBox.SelectedItem as ALibModel;
string searchStr = lm.Tag;
AResult result = new AResult(searchStr);
Window m = Application.Current.Properties["mainwindow"] as Window;
Frame main_frame = m.FindName("main_frame") as Frame;
main_frame.Navigate(result);
}
}
private void char_button_Click(object sender, RoutedEventArgs e)
{
// pinyin c
string let = (e.Source as Button).Content as string;
ALibViewModel vm = listBox.DataContext as ALibViewModel;
if (vm.Pydic.ContainsKey(let.ToLower()))
{
int idc = vm.Pydic[let.ToLower()];
listBox.ScrollIntoView(listBox.Items[idc]);
}
}
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
// ReSharper disable once CheckNamespace
namespace Cake.Core
{
/// <summary>
/// Contains extension methods for <see cref="Type"/>.
/// </summary>
public static class TypeExtensions
{
/// <summary>
/// Determines whether the specified <see cref="Type"/> is static.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>Whether or not the specified type is static.</returns>
public static bool IsStatic(this Type type)
{
if (type == null)
{
throw new ArgumentNullException(nameof(type));
}
var typeInfo = type.GetTypeInfo();
return typeInfo.IsAbstract && typeInfo.IsSealed;
}
/// <summary>
/// Gets the full name of a <see cref="Type"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <param name="includeNamespace">if set to <c>true</c> then namespace is included.</param>
/// <returns>The full name of a type.</returns>
public static string GetFullName(this Type type, bool includeNamespace = true)
{
if (type == null)
{
throw new ArgumentNullException(nameof(type));
}
if (type.IsGenericParameter)
{
return type.Name;
}
if (type.IsArray)
{
return type.GetElementType().GetFullName(includeNamespace) + "[]";
}
// fix any nested types by a simple replacement + will become .
Type genericType;
return (type.IsGenericType(out genericType)
? GetGenericTypeName(genericType, includeNamespace)
: includeNamespace ? type.FullName : type.Name).Replace('+', '.');
}
/// <summary>
/// Gets whether or not a given <see cref="System.Type"/> is a subclass of an raw/open generic.
/// </summary>
/// <param name="toCheck">The type to check.</param>
/// <param name="generic">The open generic to test.</param>
/// <code>typeof(Nullable<int>).IsSubclassOfRawGeneric(typeof(Nullable<>));.</code>
/// <returns>Returns <c>true</c> if the type is a subtype of a raw generic, else <c>false</c>.</returns>
public static bool IsSubclassOfRawGeneric(this Type toCheck, Type generic)
{
while (toCheck != null && toCheck != typeof(object))
{
var cur = toCheck.GetTypeInfo().IsGenericType ? toCheck.GetGenericTypeDefinition() : toCheck;
if (generic == cur)
{
return true;
}
toCheck = toCheck.GetTypeInfo().BaseType;
}
return false;
}
private static string GetGenericTypeName(this Type type, bool includeNamespace)
{
var builder = new StringBuilder();
if (includeNamespace)
{
builder.Append(type.Namespace);
builder.Append(".");
}
builder.Append(type.Name.Substring(0, type.Name.IndexOf('`')));
builder.Append("<");
builder.Append(GetGenericTypeArguments(type, includeNamespace));
builder.Append(">");
return builder.ToString();
}
private static bool IsGenericType(this Type type, out Type genericType)
{
genericType = type.IsByRef
? (type.GetElementType() ?? type)
: type;
return genericType.GetTypeInfo().IsGenericType;
}
private static string GetGenericTypeArguments(this Type type, bool includeNamespace)
{
var genericArguments = new List<string>();
foreach (var argument in type.GenericTypeArguments)
{
genericArguments.Add(GetFullName(argument, includeNamespace));
}
return string.Join(", ", genericArguments);
}
}
} |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using CommandLine;
namespace Localization.Options
{
public class ExtractOptions
{
[Option(
's',
"source",
HelpText = "path to the folder that contains source files for data extraction (it's root project folder).",
Required = true)]
public string SourceDirectory { get; set; }
[Option(
'd',
"dest",
HelpText = "path to the folder in which will be saved all extracted items.",
Required = true)]
public string DestinationDirectory { get; set; }
[Option(
't',
"tag",
MutuallyExclusiveSet = "extractMode",
HelpText = "indicate the tag name which marks the commit from where to look for modified files.")]
public string TagName { get; set; }
[Option(
'c',
"commit",
MutuallyExclusiveSet = "extractMode",
HelpText = "commit from where to look for modified files")]
public string CommitSha { get; set; }
public ExtractorMode ExtractorMode
{
get
{
if (!string.IsNullOrEmpty(TagName))
{
return ExtractorMode.TagName;
}
if (!string.IsNullOrEmpty(CommitSha))
{
return ExtractorMode.Commit;
}
return ExtractorMode.All;
}
}
}
}
|
// TODO: LOGGING: remove dead code.
namespace SFA.Apprenticeships.Infrastructure.LogEventIndexer.Domain
{
/*
using System;
public class LogEvent
{
public string Application { get; set; }
public string CurrentCulture { get; set; }
// ReSharper disable once InconsistentNaming
public string CurrentUICulture { get; set; }
public string ErrorCode { get; set; }
public string Exception { get; set; }
public string Headers { get; set; }
public DateTime Date { get; set; }
public string Environment { get; set; }
public string Level { get; set; }
public string Logger { get; set; }
public string MachineName { get; set; }
public string Message { get; set; }
public int ProcessId { get; set; }
public string ProcessName { get; set; }
public string Referrer { get; set; }
public string Session { get; set; }
public long Ticks { get; set; }
public string Type { get; set; }
public string User { get; set; }
public string UserAgent { get; set; }
public string UserLanguages { get; set; }
public string Version { get; set; }
}
*/
}
|
// Copyright 2020 New Relic, Inc. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
using NewRelic.Agent.Core.Aggregators;
using NewRelic.Agent.Core.Samplers;
using NewRelic.Agent.Core.WireModels;
using NewRelic.Core.Logging;
using System;
using System.Collections.Generic;
namespace NewRelic.Agent.Core.Transformers
{
public interface IGcSampleTransformer
{
void Transform(Dictionary<GCSampleType, float> sampleValues);
}
public class GcSampleTransformer : IGcSampleTransformer
{
private readonly IMetricBuilder _metricBuilder;
private readonly IMetricAggregator _metricAggregator;
public GcSampleTransformer(IMetricBuilder metricBuilder, IMetricAggregator metricAggregator)
{
_metricBuilder = metricBuilder;
_metricAggregator = metricAggregator;
_metricBuilderHandlers = new Dictionary<GCSampleType, Func<GCSampleType, float, MetricWireModel>>()
{
{ GCSampleType.HandlesCount, CreateMetric_Gauge},
{ GCSampleType.InducedCount, CreateMetric_Count},
{ GCSampleType.PercentTimeInGc, CreateMetric_Percent},
{ GCSampleType.Gen0Size, CreateMetric_ByteData},
{ GCSampleType.Gen0Promoted, CreateMetric_ByteData},
{ GCSampleType.Gen0CollectionCount, CreateMetric_Count},
{ GCSampleType.Gen1Size, CreateMetric_ByteData},
{ GCSampleType.Gen1Promoted, CreateMetric_ByteData},
{ GCSampleType.Gen1CollectionCount, CreateMetric_Count},
{ GCSampleType.Gen2Size, CreateMetric_ByteData},
{ GCSampleType.Gen2Survived, CreateMetric_ByteData},
{ GCSampleType.Gen2CollectionCount, CreateMetric_Count},
{ GCSampleType.LOHSize, CreateMetric_ByteData},
{ GCSampleType.LOHSurvived, CreateMetric_ByteData},
};
}
private readonly Dictionary<GCSampleType, Func<GCSampleType, float, MetricWireModel>> _metricBuilderHandlers;
public void Transform(Dictionary<GCSampleType, float> sampleValues)
{
var metrics = new List<MetricWireModel>();
foreach (var sampleValue in sampleValues)
{
var metricWireModel = _metricBuilderHandlers[sampleValue.Key](sampleValue.Key, sampleValue.Value);
if (metricWireModel != null)
{
metrics.Add(metricWireModel);
}
}
RecordMetrics(metrics);
}
private MetricWireModel CreateMetric_Gauge(GCSampleType sampleType, float sampleValue)
{
return _metricBuilder.TryBuildGCGaugeMetric(sampleType, sampleValue);
}
private MetricWireModel CreateMetric_Count(GCSampleType sampleType, float sampleValue)
{
if (sampleValue < 0)
{
Log.Finest($"The GC Sampler encountered a negative value: {sampleValue}, for sample: {Enum.GetName(typeof(GCSampleType), sampleType)}");
sampleValue = 0;
}
return _metricBuilder.TryBuildGCCountMetric(sampleType, (int)sampleValue);
}
private MetricWireModel CreateMetric_ByteData(GCSampleType sampleType, float sampleValue)
{
return _metricBuilder.TryBuildGCBytesMetric(sampleType, (long)sampleValue);
}
private MetricWireModel CreateMetric_Percent(GCSampleType sampleType, float sampleValue)
{
return _metricBuilder.TryBuildGCPercentMetric(sampleType, sampleValue);
}
private void RecordMetrics(IEnumerable<MetricWireModel> metrics)
{
foreach (var metric in metrics)
{
_metricAggregator.Collect(metric);
}
}
}
}
|
using static BuckarooSdk.Constants.Services;
namespace BuckarooSdk.Services.Ideal.Push
{
/// <summary>
///
/// </summary>
public class IdealPayRemainderPush : ActionPush
{
public override ServiceNames ServiceNames => ServiceNames.Ideal;
/// <summary>
///
/// </summary>
public string ConsumerIban { get; set; }
public string ConsumerBic { get; set; }
public string ConsumerName { get; set; }
public string ConsumerIssuer { get; set; }
}
}
|
namespace Razor.UI.Pages
{
[Authorize(AuthenticationSchemes = OpenIdConnectDefaults.AuthenticationScheme)]
public class UserProfileModel : PageModel
{
private readonly IUserService _userService;
public UserProfileModel(IUserService userService)
{
_userService = userService ?? throw new ArgumentNullException(nameof(userService));
}
public ApplicationUserModel UserDetail { get; set; } = new ApplicationUserModel();
public async Task<IActionResult> OnGetAsync(string categoryName)
{
var userDetail = await _userService.GetUserDetail();
UserDetail = userDetail;
return Page();
}
}
}
|
using System.IO;
using iDi.Blockchain.Framework.Execution;
using iDi.Blockchain.Framework.Extensions;
using iDi.Plus.Domain.Extensions;
using iDi.Plus.Domain.Pipeline;
using iDi.Plus.Infrastructure.Extensions;
using iDi.Plus.Node.Context;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace iDi.Plus.Node
{
class Program
{
static void Main(string[] args)
{
// create service collection
var services = new ServiceCollection();
ConfigureServices(services);
// create service provider
var serviceProvider = services.BuildServiceProvider();
// entry to run app
using var scope = serviceProvider.CreateScope();
scope.ServiceProvider.GetService<Process>()?.Run();
}
private static void ConfigureStages(IPipelineFactory pipelineFactory)
{
//CreateNewBlock pipeline stage types here
//The order is important
pipelineFactory?.AddStage<LogicControllerStage>();
}
private static void ConfigureServices(IServiceCollection services)
{
// build config
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", false)
.AddEnvironmentVariables()
.Build();
services.AddOptions();
services.AddDbContext<IdPlusDbContext>();
var config = configuration.GetSection("Settings").Get<Settings>();
services.AddSingleton(config);
services.AddIdiBlockchainCommunicationServices()
.AddPipeline(ConfigureStages)
.AddIdiPlusCoreServices()
.AddIdiInfrastructureServices(config.ConnectionString)
.AddDomainService()
.AddDomainServices();
//CreateNewBlock pipeline stage classes to the IoC container here
//services.AddTransient<SampleStage>()
// add app
services.AddSingleton<Process>();
}
}
}
|
namespace TwitterCards.Core.Interfaces
{
public interface ITweet
{
long Id { get; }
ITwitterUser Author { get; }
string Text { get; }
string MediaUrl { get; }
}
}
|
namespace GameModel
{
public enum StartOptions
{
Blank,
Random
}
}
|
namespace Mono.Cecil.AssemblyResolver
{
public enum TargetPlatform
{
None = 0,
CLR_1,
CLR_2,
CLR_2_3,
CLR_3_5,
CLR_4,
WPF,
Silverlight,
WindowsPhone,
WindowsCE,
WinRT
}
}
|
// -----------------------------------------------------------------------
// <copyright file="SuccessEventArgs.cs" company="John Lynch">
// This file is licensed under the MIT license.
// Copyright (c) 2018 John Lynch
// </copyright>
// -----------------------------------------------------------------------
namespace Harmony.Events {
using System;
using Harmony.Responses;
/// <summary>
/// Event arguments that indicates whether a command was successful or not
/// </summary>
public class SuccessEventArgs : HarmonyEventArgs<string> {
/// <summary>
/// Initializes a new instance of the <see cref="SuccessEventArgs" /> class.
/// </summary>
/// <param name="response">The response data from the command</param>
public SuccessEventArgs(StringResponse response)
: base(response) =>
this.Success = Math.Abs(response.Code - 200) < 1;
/// <summary>
/// Gets a value indicating whether or not the command was successful
/// </summary>
public bool Success { get; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using CommandLine;
using NLog;
using Kifa.Api.Files;
using Kifa.IO;
namespace Kifa.Tools {
public abstract partial class KifaFileCommand : KifaCommand {
static readonly Logger logger = LogManager.GetCurrentClassLogger();
[Value(0, Required = true, HelpText = "Target file(s) to take action on.")]
public IEnumerable<string> FileNames { get; set; }
[Option('i', "id", HelpText = "Treat input files as logical ids.")]
public virtual bool ById { get; set; } = false;
[Option('r', "recursive", HelpText = "Take action on files in recursive folders.")]
public virtual bool Recursive { get; set; } = false;
/// <summary>
/// Iterate over files with this prefix. If it's not, prefix the path with this member.
/// </summary>
protected virtual string Prefix => null;
/// <summary>
/// By default, it will only iterate over existing files. When it's set to true, it will iterate over
/// logical ones and produce ExecuteOneInstance calls with the two combined.
/// </summary>
protected virtual bool IterateOverLogicalFiles => false;
protected virtual bool NaturalSorting => false;
public override int Execute() {
var multi = FileNames.Count() > 1;
if (ById || IterateOverLogicalFiles) {
var fileInfos = new List<(string sortKey, string value)>();
foreach (var fileName in FileNames) {
var host = "";
var path = fileName;
if (IterateOverLogicalFiles) {
var f = new KifaFile(path);
if (!ById) {
host = f.Host;
}
path = f.Id;
}
path = Prefix == null ? path : $"{Prefix}{path}";
var thisFolder = FileInformation.Client.ListFolder(path, Recursive);
if (thisFolder.Count > 0) {
multi = true;
fileInfos.AddRange(thisFolder.Select(f => (f.GetNaturalSortKey(), host + f)));
} else {
fileInfos.Add((path.GetNaturalSortKey(), host + path));
}
}
fileInfos.Sort();
var files = fileInfos.Select(f => f.value).ToList();
return ById
? ExecuteAllFileInformation(files, multi)
: ExecuteAllKifaFiles(files.Select(f => new KifaFile(f)).ToList(), multi);
} else {
var files = new List<(string sortKey, KifaFile value)>();
foreach (var fileName in FileNames) {
var fileInfo = new KifaFile(fileName);
if (Prefix != null && !fileInfo.Path.StartsWith(Prefix)) {
fileInfo = fileInfo.GetFilePrefixed(Prefix);
}
var thisFolder = fileInfo.List(Recursive).ToList();
if (thisFolder.Count > 0) {
multi = true;
files.AddRange(thisFolder.Select(f => (f.ToString().GetNaturalSortKey(), f)));
} else {
files.Add((fileInfo.ToString().GetNaturalSortKey(), fileInfo));
}
}
files.Sort();
return ExecuteAllKifaFiles(files.Select(f => f.value).ToList(), multi);
}
}
}
public abstract partial class KifaFileCommand {
protected virtual Func<List<string>, string> FileInformationConfirmText => null;
protected virtual int ExecuteOneFileInformation(string file) => -1;
int ExecuteAllFileInformation(List<string> files, bool multi) {
if (multi && FileInformationConfirmText != null) {
files.ForEach(Console.WriteLine);
Console.Write(FileInformationConfirmText(files));
Console.ReadLine();
}
var errors = new Dictionary<string, Exception>();
var result = files.Select(s => {
try {
return ExecuteOneFileInformation(s);
} catch (Exception ex) {
logger.Error($"{s}: {ex}");
errors[s] = ex;
return 255;
}
}).Max();
foreach (var (key, value) in errors) {
logger.Error($"{key}: {value}");
}
if (errors.Count > 0) {
logger.Error($"{errors.Count} files failed to be taken action on.");
}
return result;
}
}
public abstract partial class KifaFileCommand {
protected virtual Func<List<KifaFile>, string> KifaFileConfirmText => null;
protected virtual int ExecuteOneKifaFile(KifaFile file) => -1;
int ExecuteAllKifaFiles(List<KifaFile> files, bool multi) {
if (multi && KifaFileConfirmText != null) {
files.ForEach(Console.WriteLine);
Console.Write(KifaFileConfirmText(files));
Console.ReadLine();
}
var errors = new Dictionary<string, Exception>();
var result = files.Select(s => {
try {
return ExecuteOneKifaFile(s);
} catch (Exception ex) {
logger.Error($"{s}: {ex}");
errors[s.ToString()] = ex;
return 255;
}
}).Max();
foreach (var (key, value) in errors) {
logger.Error($"{key}: {value}");
}
if (errors.Count > 0) {
logger.Error($"{errors.Count} files failed to be taken action on.");
}
return result;
}
}
}
|
// ReSharper disable once CheckNamespace
using MFiles.VAF.Configuration;
using System;
namespace MFiles.VAF.Extensions
{
/// <summary>
/// Defines that the following property or field controls how a task processor should recur.
/// The property or field that follows should be a <see cref="TimeSpan"/>.
/// </summary>
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = true, Inherited = true)]
public class RecurringOperationConfigurationAttribute
: JsonConfEditorAttribute, IRecurringOperationConfigurationAttribute
{
/// <inheritdoc />
public string QueueID { get; set; }
/// <inheritdoc />
public string TaskType { get; set; }
/// <inheritdoc />
public Type[] ExpectedPropertyOrFieldTypes { get; private set; }
public RecurringOperationConfigurationAttribute
(
string queueId,
string taskType
)
{
this.QueueID = queueId;
this.TaskType = taskType;
this.ExpectedPropertyOrFieldTypes = new[]
{
typeof(TimeSpan),
typeof(IRecurrenceConfiguration)
};
}
}
}
|
using System.Runtime.Serialization;
namespace CakeMail.RestClient.Models
{
/// <summary>
/// Enumeration to indicate how to sort clients.
/// </summary>
public enum ClientsSortBy
{
/// <summary>
/// Sort by company name
/// </summary>
[EnumMember(Value = "company_name")]
CompanyName,
/// <summary>
/// Sort by 'Registered On'
/// </summary>
[EnumMember(Value = "registered_date")]
RegisteredOn,
/// <summary>
/// Sort by mailing limit
/// </summary>
[EnumMember(Value = "mailing_limit")]
MailingLimit,
/// <summary>
/// Sort by monthly limit
/// </summary>
[EnumMember(Value = "month_limit")]
MonthlyLimit,
/// <summary>
/// Sort by contact limit
/// </summary>
[EnumMember(Value = "contact_limit")]
ContactLimit,
/// <summary>
/// Sort by 'Last Activity On'
/// </summary>
[EnumMember(Value = "last_activity")]
LastActivityOn
}
}
|
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
namespace Cheeze.Inventory
{
[Route("api/inventory")]
public class Controller : Microsoft.AspNetCore.Mvc.Controller
{
private static readonly Random Random = new Random();
[HttpGet("{id}")]
[ProducesResponseType(typeof(uint), (int)HttpStatusCode.OK)]
public Task<ActionResult<uint>> Get(Guid id)
{
return Task.FromResult<ActionResult<uint>>(Ok((uint)Random.Next(10)));
}
[HttpPost]
[ProducesResponseType(typeof(IEnumerable<Available>), (int)HttpStatusCode.OK)]
public Task<ActionResult<IEnumerable<Available>>> Post([FromBody] Request request)
{
var available = request.Ids
.Select(id => new Available { Id = id, Quantity = (uint)Random.Next(10) })
.ToArray();
return Task.FromResult<ActionResult<IEnumerable<Available>>>(Ok(available));
}
}
} |
using System;
namespace F29API.Data
{
public class Association
{
public Entity Subject { get; set; }
public Entity Object { get; set; }
public Relation Relation { get; set; }
}
}
|
using BchainSimServices;
namespace BSimClient.Entities.Extensions
{
public static class BlockProgressExtensions
{
public static bool IsSameBlockAs(this BlockProgress blockProgress, BlockProgress anotherBlockProgress)
{
return blockProgress?.BlockIndex == anotherBlockProgress?.BlockIndex &&
blockProgress?.BlockOrdinal == anotherBlockProgress?.BlockOrdinal;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace CoreBlogApp.Entity.ResultModel
{
public class MessageResult<T> where T : class
{
public T Result { get; set; }
//errorMessages eklenecek
}
}
|
using System;
using System.Net;
using LianZhao.Patterns.Func;
using Void = LianZhao.Void;
namespace WikiaWP
{
public class WikiAsyncAction : WikiAsyncFunc<Void>
{
public WikiAsyncAction(
IAsyncFunc<ApiClient, Void> func,
Action<UnhandledErrorEventArgs<Exception>> onError = null,
Action<bool> onFinally = null)
: base(func, onError, onFinally)
{
}
}
} |
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NUnit.Framework;
namespace Cake.Jira.Tests
{
[TestFixture]
public class JiraClientTests
{
[SetUp]
public void SetUp()
{
}
[Test]
public void CreateJiraVersion_Should_CreateVersion_When_SpecifiedVersionDoesntExist()
{
}
}
}
|
using System;
using System.Linq;
using UnityEngine;
using Unity.VisualScripting;
namespace DNode {
public class DLiteral : Unit, IDCustomInspectorDataProvider {
[DoNotSerialize][PortLabelHidden][ShortEditor] public ValueInput X;
[DoNotSerialize][PortLabelHidden][ShortEditor] public ValueInput Y;
[DoNotSerialize][PortLabelHidden][ShortEditor] public ValueInput Z;
[DoNotSerialize][PortLabelHidden][ShortEditor] public ValueInput W;
[DoNotSerialize][PortLabelHidden] public ValueOutput result;
private int _vectorLength = 1;
[Serialize][Inspectable][InspectorRange(1, 4)] public int VectorLength {
get => _vectorLength;
set {
_vectorLength = value;
PortsChanged();
}
}
private Vector4 _valueDefault = Vector4.zero;
private Vector4 _valueMin = Vector4.zero;
private Vector4 _valueMax = Vector4.one;
private bool _isLogScale = false;
private double _logScalingFactor = 1.0;
private ClampMode _clampMode = ClampMode.Clamp;
[Serialize][Inspectable] public Vector4 DefaultValue {
get => _valueDefault;
set {
_valueDefault = value;
PortsChanged();
}
}
[Serialize][Inspectable] public Vector4 MinValue {
get => _valueMin;
set {
_valueMin = value;
PortsChanged();
}
}
[Serialize][Inspectable] public Vector4 MaxValue {
get => _valueMax;
set {
_valueMax = value;
PortsChanged();
}
}
[Serialize][Inspectable] public bool IsLogScale {
get => _isLogScale;
set {
_isLogScale = value;
PortsChanged();
}
}
[Serialize][Inspectable] public double LogScalingFactor {
get => _logScalingFactor;
set {
_logScalingFactor = value;
PortsChanged();
}
}
[Serialize][Inspectable] public ClampMode ClampMode {
get => _clampMode;
set {
_clampMode = value;
PortsChanged();
}
}
private int _resultLength;
private DCustomInspectorValue MakeValue(int axis) {
return new DCustomInspectorValue {
Value = _valueDefault[axis],
Key = $"{axis}",
};
}
public DCustomInspectorData? ProvideCustomInspectorData(string key) {
int axis;
switch (key) {
case "0": axis = 0; break;
case "1": axis = 1; break;
case "2": axis = 2; break;
case "3": axis = 3; break;
default:
return null;
}
return new DCustomInspectorData {
MinValue = _valueMin[axis],
MaxValue = _valueMax[axis],
DefaultValue = _valueDefault[axis],
IsLogScale = _isLogScale,
LogScalingFactor = _logScalingFactor,
ClampMode = _clampMode,
};
}
protected override void Definition() {
X = ValueInput<DCustomInspectorValue>(nameof(X), MakeValue(0));
_resultLength = 1;
if (_vectorLength >= 2) {
Y = ValueInput<DCustomInspectorValue>(nameof(Y), MakeValue(1));
_resultLength = 2;
}
if (_vectorLength >= 3) {
Z = ValueInput<DCustomInspectorValue>(nameof(Z), MakeValue(2));
_resultLength = 3;
}
if (_vectorLength >= 4) {
W = ValueInput<DCustomInspectorValue>(nameof(W), MakeValue(3));
_resultLength = 4;
}
DValue ComputeFromFlow(Flow flow) {
DMutableValue result = new DMutableValue(1, _resultLength);
result[0, 0] = (double)flow.GetValue<DValue>(X);
if (_vectorLength >= 2) {
result[0, 1] = (double)flow.GetValue<DValue>(Y);
}
if (_vectorLength >= 3) {
result[0, 2] = (double)flow.GetValue<DValue>(Z);
}
if (_vectorLength >= 4) {
result[0, 3] = (double)flow.GetValue<DValue>(W);
}
return result.ToValue();
}
result = ValueOutput<DValue>(nameof(result), DNodeUtils.CachePerFrame(ComputeFromFlow));
}
}
}
|
using System.Collections.Generic;
using UnityObject = UnityEngine.Object;
namespace Unity.VisualScripting
{
[Analyser(typeof(INesterUnit))]
public class NesterUnitAnalyser<TNesterUnit> : UnitAnalyser<TNesterUnit> where TNesterUnit : class, INesterUnit
{
public NesterUnitAnalyser(GraphReference reference, TNesterUnit unit) : base(reference, unit) { }
protected override IEnumerable<Warning> Warnings()
{
foreach (var baseWarning in base.Warnings())
{
yield return baseWarning;
}
if (unit.childGraph == null)
{
yield return Warning.Caution("Missing nested graph.");
}
if (unit.nest.hasBackgroundEmbed)
{
yield return Warning.Caution("Background embed graph detected.");
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using ZeroZeroOne.Holidays.Interface;
namespace ZeroZeroOne.Holidays
{
public static class HolidayManager
{
public static Boolean IsDateAHoliday(ICountryHolidayProvider countryHolidayProvider, DateTime date)
{
return countryHolidayProvider.DateIsHoliday(date);
}
public static List<DateTime> GetHolidaysForYear(ICountryHolidayProvider countryHolidayProvider, Int32 year)
{
return countryHolidayProvider.GetHolidaysForYear(year);
}
}
}
|
using System;
namespace Lawn
{
public enum GardenType //Prefix: GARDEN
{
Main,
Mushroom,
Wheelbarrow,
Aquarium
}
}
|
using PatternDemos.CompoundPatternDemo.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PatternDemos.CompoundPatternDemo.Adapter
{
/// <summary>
/// 使用适配器模式创建一个会鹅叫的鸭子。
/// </summary>
public class GooseAdapter : IQuackable
{
Goose goose;
public GooseAdapter(Goose goose)
{
this.goose = goose;
}
public void Quack()
{
goose.Honk();
}
}
}
|
using Akka.Actor;
using Autofac;
using Lykke.Service.EthereumClassicApi.Actors.Factories.Interfaces;
using Lykke.Service.EthereumClassicApi.Actors.Roles.Interfaces;
namespace Lykke.Service.EthereumClassicApi.Actors
{
public sealed class ActorsModule : Module
{
protected override void Load(ContainerBuilder builder)
{
builder
.RegisterAssemblyTypes(ThisAssembly)
.AssignableTo<IActorRole>()
.AsImplementedInterfaces()
.SingleInstance();
builder
.RegisterAssemblyTypes(ThisAssembly)
.AssignableTo<IChildActorFactory>()
.AsImplementedInterfaces()
.SingleInstance();
builder
.RegisterAssemblyTypes(ThisAssembly)
.Where(x => !x.IsAbstract && x.IsSubclassOf(typeof(ActorBase)));
}
}
}
|
using System.Threading.Tasks;
using WebApi.Model.QueueRequests;
namespace WebApi.Services.Interop
{
public interface IMaskedEmailCommandService
{
Task QueueCommandAsync(MaskedEmailCommand command);
}
} |
/*********************************************
作者:曹旭升
QQ:279060597
访问博客了解详细介绍及更多内容:
http://blog.shengxunwei.com
**********************************************/
using System;
namespace Microsoft.Practices.EnterpriseLibrary.Logging
{
public interface ILogWriterStructureUpdater : IDisposable
{
}
}
|
namespace EventMaster.Course
{
public class CourseParticipantListViewModel
{
public string Vorname { get; set; }
public string Nachname { get; internal set; }
public string Email { get; internal set; }
public string Telefon { get; internal set; }
public string Anwesenheit { get; set; }
public int Laufnummer { get; set; }
public string Ersatz { get; set; }
public string AnmeldungsId { get; set; }
}
} |
using System;
namespace Claw.Documents
{
/// <summary>
/// Container for constants used in the *.pr0 file format.
/// </summary>
internal static class PR0Constants
{
/// <summary>
/// Opening character for nodes.
/// </summary>
internal const char OPEN_NODE_CHARCTER = '[';
/// <summary>
/// Closing character for nodes.
/// </summary>
internal const char CLOSE_NODE_CHARCTER = ']';
/// <summary>
/// Character for attribute value assignments.
/// </summary>
internal const char ASSIGN_CHARACTER = '=';
/// <summary>
/// Character for the opening of an enclosing statement for objects that contain whitespace characters.
/// </summary>
internal const char ENCLOSING_OPEN_CHARACTER = '\'';
/// <summary>
/// Character for the closing of an enclosing statement for objects that contain whitespace characters.
/// </summary>
internal const char ENCLOSING_CLOSE_CHARACTER = '\'';
/// <summary>
/// Character for the beginning of a data section.
/// </summary>
internal const char BEGIN_DATA_SECTION_CHARACTER = '<';
/// <summary>
/// Character for the closing of a data section.
/// </summary>
internal const char TERMINATE_DATA_SECTION_CHARACTER = '>';
/// <summary>
/// Illegal characters that are not allowed to be contained in any node name or value.
/// </summary>
internal static readonly char[] ILLEGAL_CHARACTERS = {
ENCLOSING_OPEN_CHARACTER,
ENCLOSING_CLOSE_CHARACTER,
};
}
}
|
using System.Collections.Generic;
using Microsoft.AspNetCore.Components;
using Microsoft.JSInterop;
using System.Threading.Tasks;
using WebVella.Pulsar.Models;
using WebVella.Pulsar.Utils;
using System;
using WebVella.Pulsar.Services;
using Microsoft.AspNetCore.Components.Web;
using Newtonsoft.Json;
namespace WebVella.Pulsar.Components
{
public partial class WvpDisplayNumber : WvpDisplayBase
{
#region << Parameters >>
/// <summary>
/// Pattern of accepted string values. Goes with title attribute as description of the pattern
/// </summary>
[Parameter] public decimal? Value { get; set; } = null;
[Parameter] public int DecimalPlaces { get; set; } = 0;
#endregion
#region << Callbacks >>
#endregion
#region << Private properties >>
private List<string> _cssList = new List<string>();
private decimal? _value = null;
#endregion
#region << Lifecycle methods >>
protected override async Task OnParametersSetAsync()
{
_cssList = new List<string>();
if (!String.IsNullOrWhiteSpace(Class))
{
_cssList.Add(Class);
if (!Class.Contains("form-control"))
{//Handle input-group case
_cssList.Add("form-control-plaintext");
if (Value == null)
_cssList.Add("form-control-plaintext--empty");
}
}
else
{
_cssList.Add("form-control-plaintext");
if (Value == null)
_cssList.Add("form-control-plaintext--empty");
}
var sizeSuffix = Size.ToDescriptionString();
if (!String.IsNullOrWhiteSpace(sizeSuffix))
_cssList.Add($"form-control-{sizeSuffix}");
_value = null;
if (Value != null)
{
_value = FieldValueService.InitAsDecimal(Value);
_value = Math.Round(_value.Value, DecimalPlaces, MidpointRounding.AwayFromZero);
}
await base.OnParametersSetAsync();
}
#endregion
#region << Private methods >>
#endregion
#region << Ui handlers >>
#endregion
#region << JS Callbacks methods >>
#endregion
}
} |
namespace DesignPatterns
{
public interface IPagamento
{
Pagamento RealizarPagamento(Pedido pedido, Pagamento pagamento);
}
} |
namespace System.Runtime.CompilerServices
{
[System.AttributeUsage(
AttributeTargets.Class |
AttributeTargets.Delegate |
AttributeTargets.Interface |
AttributeTargets.Method |
AttributeTargets.Struct,
AllowMultiple = false,
Inherited = false)]
public sealed class NullableContextAttribute : Attribute
{
public readonly byte Flag;
public NullableContextAttribute(byte flag)
{
Flag = flag;
}
}
}
|
using NpgsqlTypes;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.NetworkInformation;
using System.Reflection;
namespace DynamicLinqPadPostgreSqlDriver
{
using NpgsqlInet = ValueTuple<IPAddress, int>;
public static class SqlHelper
{
private static readonly IDictionary<string, string> SqlCache = new Dictionary<string, string>();
public static string LoadSql(string name)
{
var resourceName = $"DynamicLinqPadPostgreSqlDriver.SQL.{name}";
string sql;
if (SqlCache.TryGetValue(resourceName, out sql))
return sql;
using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))
{
if (stream == null)
throw new Exception($"There is no resource with name '{resourceName}'.");
using (var streamReader = new StreamReader(stream))
{
sql = streamReader.ReadToEnd();
SqlCache[resourceName] = sql;
return sql;
}
}
}
public static Type MapDbTypeToType(string dbType, string udtName, bool nullable, bool useExperimentalTypes)
{
if (dbType == null)
throw new ArgumentNullException(nameof(dbType));
dbType = dbType.ToLower();
// See the PostgreSQL datatypes as reference:
//
// http://www.npgsql.org/doc/types.html
//
// http://www.postgresql.org/docs/9.4/static/datatype-numeric.html
// http://www.postgresql.org/docs/9.4/static/datatype-datetime.html
// http://www.postgresql.org/docs/9.4/static/datatype-binary.html
// http://www.postgresql.org/docs/9.4/static/datatype-character.html
// handle the basic types first
switch (dbType)
{
case "int2":
case "smallint":
return nullable ? typeof(short?) : typeof(short);
case "int4":
case "integer":
case "serial":
return nullable ? typeof(int?) : typeof(int);
case "int8":
case "bigint":
case "bigserial":
return nullable ? typeof(long?) : typeof(long);
case "decimal":
case "numeric":
return nullable ? typeof(decimal?) : typeof(decimal);
case "real":
return nullable ? typeof(float?) : typeof(float);
case "double precision":
return nullable ? typeof(double?) : typeof(double);
case "bit":
return null; // not supported ?
case "bool":
case "boolean":
return nullable ? typeof(bool?) : typeof(bool);
case "date":
case "timestamp":
case "timestamptz":
case "timestamp with time zone":
case "timestamp without time zone":
return nullable ? typeof(DateTime?) : typeof(DateTime);
case "time":
case "time without time zone":
case "interval":
return nullable ? typeof(TimeSpan?) : typeof(TimeSpan);
case "timetz":
case "time with time zone":
return nullable ? typeof(DateTimeOffset?) : typeof(DateTimeOffset);
case "char":
case "text":
case "character":
case "character varying":
case "name":
case "varchar":
return typeof(string);
case "bytea":
return typeof(byte[]);
}
if (!useExperimentalTypes)
return null;
// handle advanced type mappings
switch (dbType)
{
case "json":
case "jsonb":
case "xml":
return typeof(string);
case "point":
return nullable ? typeof(NpgsqlPoint?) : typeof(NpgsqlPoint); // untested
case "lseg":
return nullable ? typeof(NpgsqlLSeg?) : typeof(NpgsqlLSeg); // untested
case "path":
return nullable ? typeof(NpgsqlPath?) : typeof(NpgsqlPath); // untested
case "polygon":
return nullable ? typeof(NpgsqlPolygon?) : typeof(NpgsqlPolygon); // untested
case "line":
return nullable ? typeof(NpgsqlLine?) : typeof(NpgsqlLine); // untested
case "circle":
return nullable ? typeof(NpgsqlCircle?) : typeof(NpgsqlCircle); // untested
case "box":
return nullable ? typeof(NpgsqlBox?) : typeof(NpgsqlBox); // untested
case "varbit":
case "bit varying":
return typeof(BitArray); // untested
case "hstore":
return typeof(IDictionary<string, string>); // untested
case "uuid":
return nullable ? typeof(Guid?) : typeof(Guid);
case "cidr":
return nullable ? typeof(NpgsqlInet?) : typeof(NpgsqlInet); // untested
case "inet":
return typeof(IPAddress); // untested
case "macaddr":
return typeof(PhysicalAddress); // untested
case "tsquery":
return typeof(NpgsqlTsQuery); // untested
case "tsvector":
return typeof(NpgsqlTsVector); // untested
case "oid":
case "xid":
case "cid":
return nullable ? typeof(uint?) : typeof(uint); // untested
case "oidvector":
return typeof(uint[]); // untested
case "geometry":
return null; // unsupported
case "record":
return typeof(object[]); // untested
case "range":
return null; // unsupported
case "array":
if (string.IsNullOrWhiteSpace(udtName))
return null;
if (udtName.StartsWith("_"))
{
udtName = udtName.Substring(1);
}
if ("array".Equals(udtName, StringComparison.InvariantCultureIgnoreCase))
return null;
var type = MapDbTypeToType(udtName, null, false, useExperimentalTypes);
if (type == null)
return null;
return type.MakeArrayType(); // untested
}
return null; // unsupported type
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.SceneManagement;
namespace Assets.Scripts.Pipeline
{
class SceneLoadManager
{
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
private static void OnBeforeSceneLoadRuntimeMethod()
{
SceneManager.sceneLoaded += SceneManager_sceneLoaded;
SceneManager.sceneUnloaded += SceneManager_sceneUnloaded;
}
private static void SceneManager_sceneLoaded(Scene scene, LoadSceneMode mode)
{
var gameObjects = scene.GetRootGameObjects();
foreach (var gameObject in gameObjects)
{
var lifecycles = gameObject.GetComponents<ILifecycleObject>();
foreach (var lifecycle in lifecycles)
{
lifecycle.OnSceneLoaded();
}
}
}
private static void SceneManager_sceneUnloaded(Scene scene)
{
var gameObjects = scene.GetRootGameObjects();
foreach (var gameObject in gameObjects)
{
var lifecycles = gameObject.GetComponents<ILifecycleObject>();
foreach (var lifecycle in lifecycles)
{
lifecycle.OnSceneUnloaded();
}
}
}
}
}
|
//-----------------------------------------------------------------------------
// <copyright file="CommandCreator.cs" company="WheelMUD Development Team">
// Copyright (c) WheelMUD Development Team. See LICENSE.txt. This file is
// subject to the Microsoft Public License. All other rights reserved.
// </copyright>
//-----------------------------------------------------------------------------
using WheelMUD.Server;
namespace WheelMUD.Core
{
using System.Linq;
/// <summary>A delegate used for calling CommandScripts Execute methods.</summary>
/// <param name="actionInput">The full input specified for executing the command.</param>
public delegate void CommandScriptExecuteDelegate(ActionInput actionInput);
/// <summary>A delegate used for calling CommandScripts Execute methods.</summary>
/// <param name="actionInput">The full input specified for executing the command.</param>
/// <returns>Returns a string describing the error for the user if any of the guards failed, else null.</returns>
public delegate string CommandScriptGuardsDelegate(ActionInput actionInput);
/// <summary>Creates ScriptingCommands based on the provided Actions.</summary>
public class CommandCreator
{
/// <summary>The response given for a player's attempted but unrecognized command.</summary>
private static readonly string unknownCommandResponse = "Huh?";
/// <summary>Prevents a default instance of the CommandCreator class from being created.</summary>
private CommandCreator()
{
}
/// <summary>Gets the singleton instance of the CommandCreator class.</summary>
public static CommandCreator Instance { get; } = new CommandCreator();
/// <summary>Creates a scripting command from action input.</summary>
/// <param name="actionInput">The action input to transform into a ScriptingCommand instance.</param>
/// <returns>A new ScriptingCommand instance for the specified input, if found, else null.</returns>
public ScriptingCommand Create(ActionInput actionInput)
{
// TODO: Build targeting into command selection when there are multiple valid targets; IE if multiple
// openable things registered an "open" context command, then if the user said "open door" then we
// want to select the context command attached to the closest match for "door" as our command; if
// there are still multiple targets, we can start a conflict resolution prompt, etc. Individual non-
// context commands may also wish to use such targeting code, so it should be built to be reusable.
ScriptingCommand command = TryCreateMasterCommand(actionInput, 0) ??
TryCreateMasterCommand(actionInput, 1) ??
TryCreateContextCommand(actionInput, 0) ??
TryCreateContextCommand(actionInput, 1);
if (command == null)
{
actionInput.Session?.WriteLine(unknownCommandResponse);
}
return command;
}
private ScriptingCommand TryCreateMasterCommand(ActionInput actionInput, int lastKeywordIndex)
{
string commandAlias = GetCommandAlias(actionInput, lastKeywordIndex);
// If this isn't actually a command, bail now.
////if (string.IsNullOrEmpty(commandAlias) || !this.masterCommandList.ContainsKey(commandAlias))
if (string.IsNullOrEmpty(commandAlias) || !CommandManager.Instance.MasterCommandList.ContainsKey(commandAlias))
{
return null;
}
// Create a new instance of the specified GameAction.
Command command = CommandManager.Instance.MasterCommandList[commandAlias];
var commandScript = (GameAction)command.Constructor.Invoke(null);
// Track the execute and guards delegates of this instance for calling soon, with the user's input.
var executeDelegate = new CommandScriptExecuteDelegate(commandScript.Execute);
var guardsDelegate = new CommandScriptGuardsDelegate(commandScript.Guards);
return new ScriptingCommand(command.Name, executeDelegate, guardsDelegate, command.SecurityRole, actionInput);
}
private ScriptingCommand TryCreateContextCommand(ActionInput actionInput, int lastKeywordIndex)
{
string commandAlias = GetCommandAlias(actionInput, lastKeywordIndex);
if (string.IsNullOrEmpty(commandAlias))
{
return null;
}
// Find the first valid command of this name and of applicable context, if any.
Thing sender = actionInput.Actor;
var contextCommand = CommandManager.Instance.GetContextCommands(sender, commandAlias).FirstOrDefault();
if (contextCommand == null)
{
return null;
}
var executeDelegate = new CommandScriptExecuteDelegate(contextCommand.CommandScript.Execute);
var guardsDelegate = new CommandScriptGuardsDelegate(contextCommand.CommandScript.Guards);
return new ScriptingCommand(contextCommand.CommandKey, executeDelegate, guardsDelegate, SecurityRole.all, actionInput);
}
/// <summary>Get a potential command alias from the actionInput and up to lastKeywordIndex additional keywords.</summary>
/// <param name="actionInput">The action input provided by a user issuing a command.</param>
/// <param name="lastKeywordIndex">The last keyword to append as a potential part of a command alias.</param>
/// <returns>The potential command alias, if there were enough keywords provided to test an alias this size.</returns>
private string GetCommandAlias(ActionInput actionInput, int lastKeywordIndex)
{
string commandAlias = actionInput.Noun;
if (lastKeywordIndex > 0)
{
if (actionInput.Params.Length < lastKeywordIndex)
{
// Since we test all shorter aliases first, don't wast time with longer aliases
// than the user actually provided.
return null;
}
// Otherwise prepare to scan action input for a potential command that's longer than
// just one word; IE one could implement "turn off" and "turn on" commands as two
// separate commands, provided there is no "turn" command present. If the user then
// passes "turn off flashlight" then we'll find "turn off" as the command.
for (int i = 1; i <= lastKeywordIndex; i++)
{
if (actionInput.Params.Length > lastKeywordIndex)
{
commandAlias += " " + actionInput.Params[0].ToLower();
}
}
}
return commandAlias;
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class SoundManagerScript : MonoBehaviour {
public enum Sound
{
buttonClick, damage, gamePlay, gameWinner, menu, portal, powerUp, rollDice, death,
};
public static List<AudioClip> sounds = new List<AudioClip>();
private static AudioSource audioSrcSfx;
private static AudioSource audioSrcMusic;
public Slider sfxVolume;
public Slider musicVolume;
private static int limiter = 0;
private void Start()
{
sounds.Add(Resources.Load<AudioClip>("buttonClick"));
sounds.Add(Resources.Load<AudioClip>("damage"));
sounds.Add(Resources.Load<AudioClip>("gamePlay"));
sounds.Add(Resources.Load<AudioClip>("gameWinner"));
sounds.Add(Resources.Load<AudioClip>("menu"));
sounds.Add(Resources.Load<AudioClip>("portal"));
sounds.Add(Resources.Load<AudioClip>("powerUp"));
sounds.Add(Resources.Load<AudioClip>("rollDice"));
sounds.Add(Resources.Load<AudioClip>("death"));
AudioSource[] sources = GetComponents<AudioSource>();
audioSrcSfx = sources[0];
audioSrcMusic = sources[1];
audioSrcSfx.volume = PlayerPrefs.GetFloat("sfxVolume",0.95f);
sfxVolume.value = audioSrcSfx.volume;
audioSrcMusic.volume = PlayerPrefs.GetFloat("musicVolume",0.10f);
musicVolume.value = audioSrcMusic.volume;
if (SceneManager.GetActiveScene().buildIndex == 0)
PlaySound(Sound.menu);
else
PlaySound(Sound.gamePlay);
}
public void Update()
{
if(!audioSrcMusic.isPlaying)
{
if (SceneManager.GetActiveScene().buildIndex == 0)
PlaySound(Sound.menu);
else
PlaySound(Sound.gamePlay);
}
}
public void SetMusicLevel()
{
audioSrcMusic.volume = musicVolume.value;
PlayerPrefs.SetFloat("musicVolume", musicVolume.value);
}
public void SetSfxLevel()
{
audioSrcSfx.volume = sfxVolume.value;
PlayerPrefs.SetFloat("sfxVolume", sfxVolume.value);
}
public static void PlaySound(Sound clip)
{
limiter++;
foreach(AudioClip a in sounds)
{
if(clip.ToString().Equals(a.name))
{
if (a.name == "gamePlay" || a.name == "menu")
audioSrcMusic.PlayOneShot(a);
else
if(limiter<2)
audioSrcSfx.PlayOneShot(a);
limiter--;
return;
}
}
limiter--;
}
}
|
using Unity.Jobs;
using Unity.Collections;
using Unity.Mathematics;
using Unity.Burst;
[BurstCompile]
public struct SelfComplementWithSkipJob : IJobParallelFor
{
public NativeSlice<byte> data;
public byte threshold;
public int height;
public int widthOverLineSkip;
public void Execute(int i)
{
bool operateOnThisPixel = (i % height) < widthOverLineSkip;
bool overThreshold = data[i] > threshold;
data[i] = (byte)math.select(data[i], ~data[i], overThreshold && operateOnThisPixel);
}
}
[BurstCompile]
public struct SelfComplementNoSkipJob : IJobParallelFor
{
public NativeSlice<byte> data;
public byte threshold;
public void Execute(int i)
{
data[i] = (byte)math.select(data[i], ~data[i], data[i] > threshold);
}
}
[BurstCompile]
public struct SelfLeftShiftBurstJob : IJobParallelFor
{
public NativeSlice<byte> data;
public byte threshold;
public int height;
public int widthOverLineSkip;
public void Execute(int i)
{
bool operateOnThisPixel = (i % height) < widthOverLineSkip;
bool overThreshold = data[i] > threshold;
data[i] = (byte)math.select(data[i], data[i] << data[i], overThreshold && operateOnThisPixel);
}
}
[BurstCompile]
public struct LeftShiftNoSkipJob : IJobParallelFor
{
public NativeSlice<byte> data;
public byte threshold;
public void Execute(int i)
{
data[i] = (byte)math.select(data[i], data[i] << data[i], data[i] > threshold);
}
}
[BurstCompile]
public struct ThresholdRightShiftBurstJob : IJobParallelFor
{
public NativeSlice<byte> data;
public byte threshold;
public int height;
public int widthOverLineSkip;
public void Execute(int i)
{
bool operateOnThisPixel = (i % height) < widthOverLineSkip;
bool overThreshold = data[i] > threshold;
data[i] = (byte)math.select(data[i], data[i] >> data[i], overThreshold && operateOnThisPixel);
}
}
[BurstCompile]
public struct RightShiftNoSkipJob : IJobParallelFor
{
public NativeSlice<byte> data;
public byte threshold;
public void Execute(int i)
{
data[i] = (byte)math.select(data[i], data[i] >> data[i], data[i] > threshold);
}
}
[BurstCompile]
public struct SelfExclusiveOrBurstJob : IJobParallelFor
{
public NativeSlice<byte> data;
public byte threshold;
public int height;
public int widthOverLineSkip;
public void Execute(int i)
{
bool operateOnThisPixel = (i % height) < widthOverLineSkip;
bool overThreshold = data[i] > threshold;
data[i] = (byte)math.select(data[i], data[i] ^ threshold, overThreshold && operateOnThisPixel);
}
}
[BurstCompile]
public struct SelfExclusiveOrNoSkipJob : IJobParallelFor
{
public NativeSlice<byte> data;
public byte threshold;
public void Execute(int i)
{
data[i] = (byte)math.select(data[i], data[i] ^ data[i], data[i] > threshold);
}
}
[BurstCompile]
public struct ThresholdExclusiveOrBurstJob : IJobParallelFor
{
public NativeSlice<byte> data;
public byte threshold;
public int height;
public int widthOverLineSkip;
public void Execute(int i)
{
bool operateOnThisPixel = (i % height) < widthOverLineSkip;
bool overThreshold = data[i] > threshold;
data[i] = (byte)math.select(data[i], data[i] ^ threshold, overThreshold && operateOnThisPixel);
}
}
[BurstCompile]
public struct ThresholdExclusiveOrNoSkipJob : IJobParallelFor
{
public NativeSlice<byte> data;
public byte threshold;
public void Execute(int i)
{
data[i] = (byte)math.select(data[i], data[i] ^ threshold, data[i] > threshold);
}
}
|
using System;
using System.Linq;
class C
{
static int[] Read() => Array.ConvertAll(Console.ReadLine().Split(), int.Parse);
static (int, int) Read2() { var a = Read(); return (a[0], a[1]); }
static long[] ReadL() => Array.ConvertAll(Console.ReadLine().Split(), long.Parse);
static void Main() => Console.WriteLine(Solve());
static object Solve()
{
var n = int.Parse(Console.ReadLine());
var a = Read();
var sum = a.Sum();
if (sum % 2 != 0) return 0;
var u = Comb(n, a, sum);
if (!u[sum / 2]) return 0;
while (true)
{
var odds = Enumerable.Range(0, n).Where(i => a[i] % 2 == 1).ToArray();
if (odds.Any()) return $"1\n{odds[0] + 1}";
a = a.Select(x => x / 2).ToArray();
}
}
static bool[] Comb(int n, int[] a, int max)
{
var u = new bool[max + 1];
u[0] = true;
for (int i = 0; i < n; i++)
{
for (int j = max; j >= 0; j--)
{
if (u[j])
{
u[j + a[i]] = true;
}
}
}
return u;
}
}
|
// ===================================================================
// 实体(DawnXZ.Dawnauth.Entity)项目
//====================================================================
//【宋杰军 @Copy Right 2008+】--【联系QQ:6808240】--【请保留此注释】
//====================================================================
// 文件名称:DawnAuthDepartmentMDL.cs
// 项目名称:晨曦小竹权限云管理系统
// 创建时间:2013年11月22日 19:32:59
// 创建人员:宋杰军
// 负 责 人:宋杰军
// ===================================================================
// 修改日期:
// 修改人员:
// 修改内容:
// ===================================================================
using System;
using System.Collections.Generic;
namespace DawnXZ.Dawnauth.Entity
{
/// <summary>
///单位部门管理
/// </summary>
[Serializable]
public class DawnAuthDepartmentMDL
{
#region 构造函数
///<summary>
/// 单位部门管理
///</summary>
public DawnAuthDepartmentMDL()
{ }
#endregion
#region 公共属性
///<summary>
/// 系统编号
///</summary>
public int DptId{get;set;}
///<summary>
/// 部门名称
///</summary>
public string DptName{get;set;}
///<summary>
/// 部门标识
///</summary>
public int DptFather{get;set;}
///<summary>
/// 部门路径
///</summary>
public string DptPath{get;set;}
///<summary>
/// 部门编码
///</summary>
public string DptCode{get;set;}
///<summary>
/// 部门识别码
///</summary>
public int DptIdent{get;set;}
///<summary>
/// 部门序列
///</summary>
public int DptRank{get;set;}
///<summary>
/// 部门点击
///</summary>
public int DptClick{get;set;}
///<summary>
/// 部门统计
///</summary>
public int DptCounts{get;set;}
///<summary>
/// 部门描述
///</summary>
public string DptDesc{get;set;}
///<summary>
/// 添加时间
///</summary>
public DateTime DptTime{get;set;}
#endregion
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.