content
stringlengths 5
1.04M
| avg_line_length
float64 1.75
12.9k
| max_line_length
int64 2
244k
| alphanum_fraction
float64 0
0.98
| licenses
list | repository_name
stringlengths 7
92
| path
stringlengths 3
249
| size
int64 5
1.04M
| lang
stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
using Assets.Scripts.Model;
using Com.Game.Data;
using Com.Game.Manager;
using Com.Game.Module;
using MobaProtocol;
using MobaProtocol.Data;
using System;
using System.Collections.Generic;
using UnityEngine;
namespace Assets.Scripts.GUILogic.View.Runes
{
public class RunesCoalesceMiddle : MonoBehaviour
{
private Transform transMiddle;
private Transform btnMinus;
private Transform btnPlus;
private UISprite btnCoalesceMiddle;
private UISprite runeMiddle;
private UILabel labelCurrMiddleCount;
private UILabel labelMiddleDesc;
private UILabel labelMoneyCost;
private UILabel labelExpectCount;
private Color alphaBtn = new Color(255f, 255f, 255f, 0.4862745f);
private Color nonAlphaBtn = new Color(255f, 255f, 255f, 1f);
private RuneSend runesend = default(RuneSend);
private object[] mgs;
private int modelID_1;
private int modelID_2;
private int modelID_3;
private int countRunesOwn;
private int countMoney;
private int countRunesExp;
private int cost1to2;
private int cost2to3;
private int moneyRequire;
private bool isCanCoalesce;
public int ModelID_2
{
get
{
return this.modelID_2;
}
}
private int CountRunesOwn
{
get
{
return this.countRunesOwn;
}
set
{
this.countRunesOwn = value;
this.labelCurrMiddleCount.text = "x" + this.countRunesOwn.ToString();
}
}
private int CountMoney
{
get
{
return this.countMoney;
}
set
{
this.countMoney = value;
this.labelMoneyCost.text = this.countMoney.ToString();
UserData userData = ModelManager.Instance.Get_userData_X();
this.labelMoneyCost.color = (((long)this.countMoney >= userData.Money) ? Color.red : Color.yellow);
}
}
private int CountRunesExp
{
get
{
return this.countRunesExp;
}
set
{
this.countRunesExp = value;
this.labelExpectCount.text = this.countRunesExp.ToString();
if (this.countRunesExp == 0)
{
this.labelExpectCount.color = Color.yellow;
}
this.InitBtnState();
}
}
private void Awake()
{
this.mgs = new object[]
{
ClientV2C.coalesceviewOpenView,
ClientV2C.coalesceviewAdjustHigh,
ClientV2C.coalesceviewAfterPurchase,
ClientV2C.coalesceviewAfterCoalesce,
ClientV2C.coalesceviewChangeExpColor,
ClientV2C.coalesceviewChangeBtnState
};
this.Initialize();
}
private void OnEnable()
{
this.Register();
}
private void OnDisable()
{
this.Unregister();
}
private void Register()
{
MobaMessageManagerTools.RegistMsg(this, this.mgs, true, "OnMsg_");
}
private void Unregister()
{
MobaMessageManagerTools.RegistMsg(this, this.mgs, false, "OnMsg_");
}
private void Start()
{
}
private void Update()
{
}
private void Initialize()
{
this.transMiddle = base.transform.Find("Middle");
this.btnCoalesceMiddle = this.transMiddle.Find("CoalesceBtn").GetComponent<UISprite>();
this.runeMiddle = this.transMiddle.Find("Rune").GetComponent<UISprite>();
this.labelCurrMiddleCount = this.transMiddle.Find("Count").GetComponent<UILabel>();
this.labelMiddleDesc = this.transMiddle.Find("Description").GetComponent<UILabel>();
this.labelMoneyCost = this.transMiddle.Find("CostHint/MoneyCost").GetComponent<UILabel>();
this.btnMinus = this.transMiddle.Find("CountAdjust/Minus");
this.btnPlus = this.transMiddle.Find("CountAdjust/Plus");
this.labelExpectCount = this.transMiddle.Find("CountAdjust/Label").GetComponent<UILabel>();
UIEventListener.Get(this.btnCoalesceMiddle.gameObject).onClick = new UIEventListener.VoidDelegate(this.ClickCoalesce);
UIEventListener.Get(this.btnMinus.gameObject).onClick = new UIEventListener.VoidDelegate(this.ClickAdjust);
UIEventListener.Get(this.btnPlus.gameObject).onClick = new UIEventListener.VoidDelegate(this.ClickAdjust);
}
private void OnMsg_coalesceviewOpenView(MobaMessage msg)
{
if (msg.Param != null)
{
ModelIDs modelsData = default(ModelIDs);
modelsData = (ModelIDs)msg.Param;
this.SetModelsData(modelsData);
this.SetPerCost();
this.ResetSectionState();
this.SetSprite();
this.SetDescription();
this.ReFreshOwned();
}
}
private void OnMsg_coalesceviewAdjustHigh(MobaMessage msg)
{
if (msg.Param != null)
{
int num = (int)msg.Param;
int num2 = num * 3 - this.countRunesOwn;
this.CountRunesExp = ((num2 > 0) ? (num * 3 - this.countRunesOwn) : 0);
if (this.countRunesExp >= 0)
{
MobaMessageManagerTools.SendClientMsg(ClientV2C.coalesceviewAdjustMiddle, this.countRunesExp, false);
}
}
}
private void OnMsg_coalesceviewAfterPurchase(MobaMessage msg)
{
if (msg != null)
{
this.ReFreshOwned();
this.CountRunesExp = this.countRunesExp;
RunesCtrl.GetInstance().runestate = RunesInlayState.Nothing;
}
}
private void OnMsg_coalesceviewAfterCoalesce(MobaMessage msg)
{
if (msg != null)
{
this.ReFreshOwned();
this.ResetSectionState();
RunesCtrl.GetInstance().runestate = RunesInlayState.Nothing;
}
}
private void OnMsg_coalesceviewChangeBtnState(MobaMessage msg)
{
this.btnCoalesceMiddle.alpha = 0.4862745f;
this.btnCoalesceMiddle.GetComponent<UIButton>().defaultColor = this.alphaBtn;
this.btnCoalesceMiddle.GetComponent<UIButton>().hover = this.alphaBtn;
this.btnCoalesceMiddle.GetComponent<UIButton>().pressed = this.alphaBtn;
this.isCanCoalesce = false;
}
private void OnMsg_coalesceviewChangeExpColor(MobaMessage msg)
{
if (msg.Param != null)
{
bool flag = (bool)msg.Param;
this.labelExpectCount.color = ((!flag) ? Color.yellow : Color.red);
}
}
private void SetModelsData(ModelIDs mds)
{
this.modelID_1 = mds.modelID_1;
this.modelID_2 = mds.modelID_2;
this.modelID_3 = mds.modelID_3;
}
private void SetDescription()
{
SysGameItemsVo dataById = BaseDataMgr.instance.GetDataById<SysGameItemsVo>(this.modelID_2.ToString());
string[] array = dataById.attribute.Split(new char[]
{
'|'
});
this.labelMiddleDesc.text = ((!(array[1].Substring(array[1].Length - 1, 1) == "%")) ? ("+" + float.Parse(array[1]).ToString(array[2]) + LanguageManager.Instance.GetStringById(BaseDataMgr.instance.GetAttrNumberData(array[0]).attrName)) : ("+" + array[1] + LanguageManager.Instance.GetStringById(BaseDataMgr.instance.GetAttrNumberData(array[0]).attrName)));
}
private void SetSprite()
{
SysGameItemsVo dataById = BaseDataMgr.instance.GetDataById<SysGameItemsVo>(this.modelID_2.ToString());
this.runeMiddle.spriteName = dataById.icon;
}
private void ResetSectionState()
{
this.CountRunesExp = 0;
this.CountMoney = 0;
}
private void ReFreshOwned()
{
List<EquipmentInfoData> list = ModelManager.Instance.Get_equipmentList_X();
if (list != null)
{
EquipmentInfoData equipmentInfoData = list.Find((EquipmentInfoData obj) => obj.ModelId == this.modelID_2);
this.CountRunesOwn = ((equipmentInfoData != null) ? equipmentInfoData.Count : 0);
}
}
private void InitBtnState()
{
UserData userData = ModelManager.Instance.Get_userData_X();
long money = userData.Money;
bool flag = this.CheckCount();
this.CountMoney = this.moneyRequire;
if (flag && (long)this.moneyRequire <= money)
{
this.btnCoalesceMiddle.alpha = 1f;
this.btnCoalesceMiddle.GetComponent<UIButton>().defaultColor = this.nonAlphaBtn;
this.btnCoalesceMiddle.GetComponent<UIButton>().hover = this.nonAlphaBtn;
this.btnCoalesceMiddle.GetComponent<UIButton>().pressed = this.nonAlphaBtn;
this.isCanCoalesce = true;
}
else
{
this.btnCoalesceMiddle.alpha = 0.4862745f;
this.btnCoalesceMiddle.GetComponent<UIButton>().defaultColor = this.alphaBtn;
this.btnCoalesceMiddle.GetComponent<UIButton>().hover = this.alphaBtn;
this.btnCoalesceMiddle.GetComponent<UIButton>().pressed = this.alphaBtn;
this.isCanCoalesce = false;
}
}
private bool CheckCount()
{
this.moneyRequire = 0;
if (this.countRunesExp <= 0)
{
return false;
}
List<EquipmentInfoData> list = ModelManager.Instance.Get_equipmentList_X();
EquipmentInfoData equipmentInfoData = list.Find((EquipmentInfoData obj) => obj.ModelId == this.modelID_1);
int num = (equipmentInfoData != null) ? equipmentInfoData.Count : 0;
int num2 = this.countRunesExp * 3;
this.moneyRequire = this.countRunesExp * this.cost1to2;
if (num2 <= num)
{
this.runesend.ModelID = this.modelID_2;
this.runesend.Count1 = num2;
this.runesend.Count2 = 0;
return true;
}
return false;
}
private void SetPerCost()
{
if (this.modelID_1 != 0)
{
SysGameItemsVo dataById = BaseDataMgr.instance.GetDataById<SysGameItemsVo>(this.modelID_1.ToString());
if (dataById != null)
{
this.cost1to2 = dataById.consumption_money;
}
}
if (this.modelID_2 != 0)
{
SysGameItemsVo dataById2 = BaseDataMgr.instance.GetDataById<SysGameItemsVo>(this.modelID_2.ToString());
if (dataById2 != null)
{
this.cost2to3 = dataById2.consumption_money;
}
}
}
private int ReturnInitCount(int modelid)
{
if (modelid == 0)
{
return 0;
}
int num = 0;
List<EquipmentInfoData> list = ModelManager.Instance.Get_equipmentList_X();
if (list != null)
{
EquipmentInfoData equipmentInfoData = list.Find((EquipmentInfoData obj) => obj.ModelId == modelid);
int arg_58_0 = (equipmentInfoData != null) ? equipmentInfoData.Count : 0;
}
SysGameItemsVo dataById = BaseDataMgr.instance.GetDataById<SysGameItemsVo>(modelid.ToString());
bool flag = true;
if (dataById != null)
{
flag = int.TryParse(dataById.consumption, out num);
}
num = ((flag && num != 0) ? num : 3);
return 0;
}
private int MoneyRequire()
{
return this.countRunesExp * this.cost1to2;
}
private void ClickCoalesce(GameObject obj)
{
if (null != obj)
{
if (!this.isCanCoalesce)
{
Singleton<TipView>.Instance.ShowViewSetText("缺少一级符文或金钱条件不满足!!!", 1f);
return;
}
if (RunesCtrl.GetInstance().runestate == RunesInlayState.Doing)
{
return;
}
RunesCtrl.GetInstance().runestate = RunesInlayState.Doing;
SendMsgManager.SendMsgParam param = new SendMsgManager.SendMsgParam(true, "正在合成", false, 15f);
SendMsgManager.Instance.SendMsg(MobaGameCode.Coalesce, param, new object[]
{
this.runesend.ModelID,
this.runesend.Count1,
this.runesend.Count2
});
RunesCtrl.GetInstance().modelID = this.modelID_2;
}
}
private void ClickAdjust(GameObject obj)
{
if (null != obj)
{
string name = obj.name;
if (name != null)
{
if (RunesCoalesceMiddle.<>f__switch$map29 == null)
{
RunesCoalesceMiddle.<>f__switch$map29 = new Dictionary<string, int>(2)
{
{
"Minus",
0
},
{
"Plus",
1
}
};
}
int num;
if (RunesCoalesceMiddle.<>f__switch$map29.TryGetValue(name, out num))
{
if (num != 0)
{
if (num == 1)
{
this.CountRunesExp++;
if (this.countRunesExp > 99)
{
this.CountRunesExp = 0;
}
}
}
else
{
this.CountRunesExp--;
if (this.countRunesExp < 0)
{
this.CountRunesExp = 99;
}
}
}
}
MobaMessageManagerTools.SendClientMsg(ClientV2C.coalesceviewAdjustMiddle, null, false);
if (this.countRunesExp >= 0)
{
MobaMessageManagerTools.SendClientMsg(ClientV2C.coalesceviewAdjustMiddle, this.countRunesExp, false);
}
}
}
}
}
| 26.794248
| 359
| 0.657501
|
[
"MIT"
] |
corefan/mobahero_src
|
Assets.Scripts.GUILogic.View.Runes/RunesCoalesceMiddle.cs
| 12,153
|
C#
|
using System;
using System.Collections.Generic;
using Xunit;
namespace DesignPatterns.Creational
{
public class Builder : DesignPattern
{
public override void Execute()
{
var chef = new PizzaChef();
chef.SetPizzaRecipe(new PepperoniPizzaRecipe());
chef.ConstructPizza();
Pizza pepperoniPizza = chef.ServePizza();
Assert.Equal(Sauce.Tomato, pepperoniPizza.Sauce);
Assert.Equal(Topping.Pepperoni | Topping.Cheese, pepperoniPizza.Toppings);
chef.SetPizzaRecipe(new SpecialPizzaRecipe());
chef.ConstructPizza();
Pizza specialPizza = chef.ServePizza();
Assert.Equal(Sauce.Spicy, specialPizza.Sauce);
Assert.Equal(Topping.Bacon | Topping.Cheese | Topping.Onion | Topping.Sausage, specialPizza.Toppings);
}
#region Definition
public enum Sauce
{
Tomato,
Spicy
}
[Flags]
public enum Topping
{
Sausage = 1,
Pepperoni = 2,
Onion = 4,
Cheese = 8,
Bacon = 16
}
/// <summary>
/// Product
/// </summary>
/// <remarks>
/// - Represents the complex object under construction.
/// - Concrete Builder builds the product's internal representation and defines the process by which it's assembled.
/// - Includes classes that define the constituent parts, including interfaces for assembling the parts into the final result
/// </remarks>
public class Pizza
{
public Sauce Sauce { get; private set; }
public Topping Toppings { get; private set; }
public void SetSauce(Sauce sauce)
{
this.Sauce = sauce;
}
public void SetToppings(Topping toppings)
{
this.Toppings = toppings;
}
}
/// <summary>
/// Director
/// </summary>
/// <remarks>
/// Constructs an object using the Builder interface.
/// </remarks>
public class PizzaChef
{
private IPizzaRecipe _recipe;
private readonly Queue<Pizza> _createdPizzas;
public PizzaChef()
{
this._createdPizzas = new Queue<Pizza>();
}
public void SetPizzaRecipe(IPizzaRecipe recipe)
{
this._recipe = recipe;
}
public void ConstructPizza()
{
this._recipe.PrepareNewPizza();
this._recipe.AddSauce();
this._recipe.AddToppings();
this._createdPizzas.Enqueue(this._recipe.ServePizza());
}
public Pizza ServePizza()
{
return this._createdPizzas.Dequeue();
}
}
/// <summary>
/// Builder
/// </summary>
/// <remarks>
/// Specifies an abstract interface for creating parts of a Product object.
/// </remarks>
public interface IPizzaRecipe
{
void PrepareNewPizza();
void AddSauce();
void AddToppings();
Pizza ServePizza();
}
#endregion
#region Concrete Implementations
/// <summary>
/// Concrete Builder
/// </summary>
/// <remarks>
/// - Constructs and assembles parts of the product by implementing the Builder interface.
/// - Defines and keeps track of the representation it creates.
/// - Provides an interface for retrieving the product.
/// </remarks>
public abstract class BasePizzaRecipe : IPizzaRecipe
{
protected Pizza Pizza { get; private set; }
public void PrepareNewPizza()
{
this.Pizza = new Pizza();
}
public abstract void AddSauce();
public abstract void AddToppings();
public Pizza ServePizza()
{
return this.Pizza;
}
}
/// <summary>
/// Concrete Builder
/// </summary>
/// <remarks>
/// - Constructs and assembles parts of the product by implementing the Builder interface.
/// - Defines and keeps track of the representation it creates.
/// - Provides an interface for retrieving the product.
/// </remarks>
public class PepperoniPizzaRecipe : BasePizzaRecipe
{
public override void AddSauce()
{
this.Pizza?.SetSauce(Sauce.Tomato);
}
public override void AddToppings()
{
this.Pizza?.SetToppings(Topping.Pepperoni | Topping.Cheese);
}
}
/// <summary>
/// Concrete Builder
/// </summary>
/// <remarks>
/// - Constructs and assembles parts of the product by implementing the Builder interface.
/// - Defines and keeps track of the representation it creates.
/// - Provides an interface for retrieving the product.
/// </remarks>
public class SpecialPizzaRecipe : BasePizzaRecipe
{
public override void AddSauce()
{
this.Pizza?.SetSauce(Sauce.Spicy);
}
public override void AddToppings()
{
this.Pizza?.SetToppings(Topping.Bacon | Topping.Cheese | Topping.Onion | Topping.Sausage);
}
}
#endregion
}
}
| 28.893401
| 133
| 0.527231
|
[
"MIT"
] |
Arcxk/DesignPatterns
|
DesignPatterns/Creational/Builder.cs
| 5,694
|
C#
|
using System;
using System.Collections.Generic;
using System.Text;
namespace BookManager.Domain.Commands.CategoryCommands
{
public class UpdateCategoryCommand
{
}
}
| 16.272727
| 54
| 0.765363
|
[
"MIT"
] |
thiagocruzrj/BookManager
|
src/BookManager.Domain/Commands/CategoryCommands/UpdateCategoryCommand.cs
| 181
|
C#
|
using System;
using System.Collections.Generic;
using System.Web;
using Bloom.Api;
using Bloom.Book;
using Bloom.Edit;
using Microsoft.CSharp.RuntimeBinder;
namespace Bloom.web.controllers
{
/// <summary>
/// This API handles requests to add new pages and change existing pages to match some other layout.
/// </summary>
public class AddOrChangePageApi
{
private Dictionary<string, IPage> _templatePagesDict;
private readonly TemplateInsertionCommand _templateInsertionCommand;
private readonly PageRefreshEvent _pageRefreshEvent;
private readonly PageSelection _pageSelection;
private readonly SourceCollectionsList _sourceCollectionsList;
public AddOrChangePageApi( TemplateInsertionCommand templateInsertionCommand,
PageRefreshEvent pageRefreshEvent,
PageSelection pageSelection,
SourceCollectionsList sourceCollectionsList)
{
_templateInsertionCommand = templateInsertionCommand;
_pageRefreshEvent = pageRefreshEvent;
_pageSelection = pageSelection;
_sourceCollectionsList = sourceCollectionsList;
}
public void RegisterWithApiHandler(BloomApiHandler apiHandler)
{
// Both of these display UI, expect to require UI thread.
apiHandler.RegisterEndpointHandler("addPage", HandleAddPage, true).Measureable("Add Page");
apiHandler.RegisterEndpointHandler("changeLayout", HandleChangeLayout, true).Measureable("Change Layout"); ;
}
private void HandleAddPage(ApiRequest request)
{
(IPage templatePage, bool dummy, int numberOfPagesToAdd) = GetPageTemplateAndUserStyles(request);
if (templatePage == null || numberOfPagesToAdd < 1) // just in case
return;
CopyVideoPlaceHolderIfNeeded(templatePage);
_templateInsertionCommand.Insert(templatePage as Page, numberOfPagesToAdd);
_pageRefreshEvent.Raise(PageRefreshEvent.SaveBehavior.JustRedisplay); // needed to get the styles updated
request.PostSucceeded();
}
/// <summary>
/// Ensure the book folder has the video-placeholder.svg file if it is needed by the template
/// page.
/// </summary>
/// <remarks>
/// See https://issues.bloomlibrary.org/youtrack/issue/BL-6920.
/// </remarks>
private void CopyVideoPlaceHolderIfNeeded(IPage templatePage)
{
// The need for video-placeholder.svg is given by an element in the page that looks
// something like this:
// <div class="bloom-videoContainer bloom-noVideoSelected bloom-leadingElement" />
// Note that the page's HTML doesn't directly reference the image file. That's done
// by the CSS which interprets bloom-noVideoSelected.
var div = templatePage.GetDivNodeForThisPage();
if (div.SelectSingleNode(".//div[contains(@class, 'bloom-noVideoSelected')]") != null)
_pageSelection.CurrentSelection.Book.Storage.Update("video-placeholder.svg");
}
private void HandleChangeLayout(ApiRequest request)
{
(IPage templatePage, bool changeWholeBook, int dummy) = GetPageTemplateAndUserStyles(request);
if (templatePage == null)
return;
CopyVideoPlaceHolderIfNeeded(templatePage);
var pageToChange = _pageSelection.CurrentSelection;
if (templatePage.Book != null) // may be null in unit tests that are unconcerned with stylesheets
HtmlDom.AddStylesheetFromAnotherBook(templatePage.Book.OurHtmlDom, pageToChange.Book.OurHtmlDom);
if (changeWholeBook)
ChangeSimilarPagesInEntireBook(pageToChange, templatePage);
else
pageToChange.Book.UpdatePageToTemplateAndUpdateLineage(pageToChange, templatePage);
_pageRefreshEvent.Raise(PageRefreshEvent.SaveBehavior.JustRedisplay);
request.PostSucceeded();
}
private static void ChangeSimilarPagesInEntireBook(IPage currentSelectedPage, IPage newTemplatePage)
{
var book = currentSelectedPage.Book;
var ancestorPageId = currentSelectedPage.IdOfFirstAncestor;
foreach (var page in book.GetPages())
{
if (page.IsXMatter || page.IdOfFirstAncestor != ancestorPageId)
continue;
// The user has explicitly allowed possible data loss.
// See https://issues.bloomlibrary.org/youtrack/issue/BL-6921.
book.UpdatePageToTemplateAndUpdateLineage(page, newTemplatePage, true);
}
}
private (IPage templatePage, bool convertWholeBook, int numberToAdd) GetPageTemplateAndUserStyles(ApiRequest request)
{
var convertWholeBook = false;
var requestData = DynamicJson.Parse(request.RequiredPostJson());
var templateBookPath = HttpUtility.HtmlDecode(requestData.templateBookPath);
var templateBook = _sourceCollectionsList.FindAndCreateTemplateBookByFullPath(templateBookPath);
if(templateBook == null)
{
request.Failed("Could not find template book " + templateBookPath);
return (null, false, -1);
}
var pageDictionary = templateBook.GetTemplatePagesIdDictionary();
if(!pageDictionary.TryGetValue(requestData.pageId, out IPage page))
{
request.Failed("Could not find the page " + requestData.pageId + " in the template book " + requestData.templateBookUrl);
return (null, false, -1);
}
if (requestData.convertWholeBook)
convertWholeBook = true;
int addNum;
// Unfortunately, a try-catch is the only reliable way to know if 'numberToAdd' is defined or not.
try
{
addNum = (int)requestData.numberToAdd;
}
catch (RuntimeBinderException)
{
addNum = 1;
}
return (page, convertWholeBook, addNum);
}
}
}
| 38.278571
| 125
| 0.759097
|
[
"MIT"
] |
nabalone/BloomDesktop
|
src/BloomExe/web/controllers/AddOrChangePageApi.cs
| 5,359
|
C#
|
using GroupDocs.Annotation.Models;
using GroupDocs.Total.WebForms.Products.Annotation.Entity.Web;
using System.Collections.Generic;
namespace GroupDocs.Total.WebForms.Products.Annotation.Annotator
{
public abstract class AbstractTextAnnotator : BaseAnnotator
{
protected AbstractTextAnnotator(AnnotationDataEntity annotationData, PageInfo pageInfo)
: base(annotationData, pageInfo)
{
}
protected static List<Point> GetPoints(AnnotationDataEntity annotationData, PageInfo pageInfo)
{
return new List<Point>
{
new Point(annotationData.left, pageInfo.Height - annotationData.top),
new Point(annotationData.left + annotationData.width, pageInfo.Height - annotationData.top),
new Point(annotationData.left, pageInfo.Height - annotationData.top - annotationData.height),
new Point(annotationData.left + annotationData.width, pageInfo.Height - annotationData.top - annotationData.height)
};
}
protected static List<Point> GetPointsForImages(AnnotationDataEntity annotationData, PageInfo pageInfo)
{
return new List<Point>
{
new Point(annotationData.left, annotationData.top + annotationData.height),
new Point(annotationData.left + annotationData.width, annotationData.top + annotationData.height),
new Point(annotationData.left, annotationData.top),
new Point(annotationData.left + annotationData.width, annotationData.top)
};
}
}
}
| 46.5
| 135
| 0.655317
|
[
"MIT"
] |
faizin87/GroupDocs.Total-for-.NET
|
Demos/WebForms/src/Products/Annotation/Annotator/AbstractTextAnnotator.cs
| 1,676
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
namespace DotNetNinja.Wpf.Commands
{
public class CommandParametrized<TParameter> : ICommand
{
public event EventHandler CanExecuteChanged;
protected Action<TParameter> What { get; set; }
protected Func<TParameter, bool> When { get; set; }
public CommandParametrized(Action<TParameter> what)
: this(what, x => true)
{
}
public CommandParametrized(Action<TParameter> what, Func<TParameter, bool> when)
{
if (what == null)
{
throw new ArgumentNullException(nameof(what));
}
if (when == null)
{
throw new ArgumentNullException(nameof(when));
}
What = what;
When = when;
}
public bool CanExecute(object parameter)
{
return When((TParameter) parameter);
}
public void Execute(object parameter)
{
What((TParameter) parameter);
}
}
}
| 24
| 88
| 0.567177
|
[
"MIT"
] |
ninjah187/DotNetNinja
|
DotNetNinja.Wpf.Commands/DotNetNinja.Wpf.Commands/CommandParametrized.cs
| 1,178
|
C#
|
//
// RtfCompressedToRtfTests.cs
//
// Author: Jeffrey Stedfast <jestedfa@microsoft.com>
//
// Copyright (c) 2013-2020 Xamarin Inc. (www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
using System;
using System.IO;
using System.Text;
using MimeKit.IO;
using MimeKit.Tnef;
using NUnit.Framework;
namespace UnitTests.Text {
[TestFixture]
public class RtfCompressedToRtfTests
{
[Test]
public void TestSimpleCompressedRtfExample ()
{
// http://msdn.microsoft.com/en-us/library/ee217938(v=exchg.80).aspx
var compressedRtfData = new byte[] {
// header
0x2d, 0x00, 0x00, 0x00, 0x2b, 0x00, 0x00, 0x00, 0x4c, 0x5a, 0x46, 0x75, 0xf1, 0xc5, 0xc7, 0xa7,
// data
0x03, 0x00, 0x0a, 0x00, 0x72, 0x63, 0x70, 0x67, 0x31, 0x32, 0x35, 0x42, 0x32, 0x0a, 0xf3, 0x20,
0x68, 0x65, 0x6c, 0x09, 0x00, 0x20, 0x62, 0x77, 0x05, 0xb0, 0x6c, 0x64, 0x7d, 0x0a, 0x80, 0x0f,
0xa0
};
var expected = "{\\rtf1\\ansi\\ansicpg1252\\pard hello world}\r\n";
var converter = new RtfCompressedToRtf ();
int outputLength, outputIndex;
var decompressed = converter.Flush (compressedRtfData, 0, compressedRtfData.Length, out outputIndex, out outputLength);
var text = Encoding.UTF8.GetString (decompressed, outputIndex, outputLength);
Assert.AreEqual (expected, text, "Decompressed RTF data does not match.");
Assert.IsTrue (converter.IsValidCrc32, "Invalid CRC32 checksum.");
}
[Test]
public void TestCrossingWritePositionExample ()
{
// http://msdn.microsoft.com/en-us/library/ee158471(v=exchg.80).aspx
var compressedRtfData = new byte[] {
// header
0x1a, 0x00, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x00, 0x4c, 0x5a, 0x46, 0x75, 0xe2, 0xd4, 0x4b, 0x51,
// data
0x41, 0x00, 0x04, 0x20, 0x57, 0x58, 0x59, 0x5a, 0x0d, 0x6e, 0x7d, 0x01, 0x0e, 0xb0
};
var expected = "{\\rtf1 WXYZWXYZWXYZWXYZWXYZ}";
var converter = new RtfCompressedToRtf ();
int outputLength, outputIndex;
var decompressed = converter.Flush (compressedRtfData, 0, compressedRtfData.Length, out outputIndex, out outputLength);
var text = Encoding.UTF8.GetString (decompressed, outputIndex, outputLength);
Assert.AreEqual (expected, text, "Decompressed RTF data does not match.");
Assert.IsTrue (converter.IsValidCrc32, "Invalid CRC32 checksum.");
}
}
}
| 37.561798
| 122
| 0.721807
|
[
"MIT"
] |
EssentialNRG/MimeKit
|
UnitTests/Text/RtfCompressedToRtfTests.cs
| 3,345
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
namespace TalkNotesBack
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
// NOTE: In order to launch WCF Test Client for testing this service, please select Service1.svc or Service1.svc.cs at the Solution Explorer and start debugging.
public class TalkNoteService : ITalkNoteService
{
public List<TalkNote> GetAll()
{
return new List<TalkNote>()
{
new TalkNote()
{
Title = "Talk Note " + new Random().Next(100)
}
};
}
public TalkNote GetTalkNoteByID(int talkNoteID)
{
return null;
}
}
}
| 29.59375
| 165
| 0.616684
|
[
"MIT"
] |
sebug/TalkNotesBack
|
TalkNotesBack/TalkNoteService.svc.cs
| 949
|
C#
|
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Immutable;
using System.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.CodeGeneration;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Operations;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.UseIndexOrRangeOperator
{
using static CSharpUseRangeOperatorDiagnosticAnalyzer;
using static Helpers;
using static SyntaxFactory;
[ExportCodeFixProvider(LanguageNames.CSharp), Shared]
internal class CSharpUseRangeOperatorCodeFixProvider : SyntaxEditorBasedCodeFixProvider
{
[ImportingConstructor]
public CSharpUseRangeOperatorCodeFixProvider()
{
}
public override ImmutableArray<string> FixableDiagnosticIds { get; } =
ImmutableArray.Create(IDEDiagnosticIds.UseRangeOperatorDiagnosticId);
public override Task RegisterCodeFixesAsync(CodeFixContext context)
{
context.RegisterCodeFix(new MyCodeAction(
c => FixAsync(context.Document, context.Diagnostics[0], c)),
context.Diagnostics);
return Task.CompletedTask;
}
protected override async Task FixAllAsync(
Document document, ImmutableArray<Diagnostic> diagnostics,
SyntaxEditor editor, CancellationToken cancellationToken)
{
var invocationNodes = diagnostics.Select(d => GetInvocationExpression(d, cancellationToken))
.OrderByDescending(i => i.SpanStart)
.ToImmutableArray();
await editor.ApplyExpressionLevelSemanticEditsAsync(
document, invocationNodes,
canReplace: (_1, _2) => true,
(semanticModel, currentRoot, currentInvocation) =>
UpdateInvocation(semanticModel, currentRoot, currentInvocation, cancellationToken),
cancellationToken).ConfigureAwait(false);
}
private SyntaxNode UpdateInvocation(
SemanticModel semanticModel, SyntaxNode currentRoot,
InvocationExpressionSyntax currentInvocation,
CancellationToken cancellationToken)
{
var invocation = semanticModel.GetOperation(currentInvocation, cancellationToken) as IInvocationOperation;
if (invocation != null)
{
var infoCache = new InfoCache(semanticModel.Compilation);
var resultOpt = AnalyzeInvocation(
invocation, infoCache, analyzerOptionsOpt: null, cancellationToken);
if (resultOpt != null)
{
var result = resultOpt.Value;
var updatedNode = FixOne(semanticModel, result, cancellationToken);
if (updatedNode != null)
{
return currentRoot.ReplaceNode(result.Invocation, updatedNode);
}
}
}
return currentRoot;
}
private static InvocationExpressionSyntax GetInvocationExpression(Diagnostic d, CancellationToken cancellationToken)
=> (InvocationExpressionSyntax)d.AdditionalLocations[0].FindNode(getInnermostNodeForTie: true, cancellationToken);
private ExpressionSyntax FixOne(
SemanticModel semanticModel, Result result, CancellationToken cancellationToken)
{
var invocation = result.Invocation;
var expression = invocation.Expression is MemberAccessExpressionSyntax memberAccess
? memberAccess.Expression
: invocation.Expression;
var rangeExpression = CreateRangeExpression(semanticModel, result, cancellationToken);
var argument = Argument(rangeExpression).WithAdditionalAnnotations(Formatter.Annotation);
var arguments = SingletonSeparatedList(argument);
if (result.MemberInfo.OverloadedMethodOpt == null)
{
var argList = invocation.ArgumentList;
return ElementAccessExpression(
expression,
BracketedArgumentList(
Token(SyntaxKind.OpenBracketToken).WithTriviaFrom(argList.OpenParenToken),
arguments,
Token(SyntaxKind.CloseBracketToken).WithTriviaFrom(argList.CloseParenToken)));
}
else
{
return invocation.ReplaceNode(
invocation.ArgumentList,
invocation.ArgumentList.WithArguments(arguments));
}
}
private RangeExpressionSyntax CreateRangeExpression(
SemanticModel semanticModel, Result result, CancellationToken cancellationToken)
{
switch (result.Kind)
{
case ResultKind.Computed:
return CreateComputedRange(semanticModel, result, cancellationToken);
case ResultKind.Constant:
return CreateConstantRange(semanticModel, result, cancellationToken);
default:
throw ExceptionUtilities.Unreachable;
}
}
private RangeExpressionSyntax CreateComputedRange(
SemanticModel semanticModel, Result result, CancellationToken cancellationToken)
{
// We have enough information now to generate `start..end`. However, this will often
// not be what the user wants. For example, generating `start..expr.Length` is not as
// desirable as `start..`. Similarly, `start..(expr.Length - 1)` is not as desirable as
// `start..^1`.
var startOperation = result.Op1;
var endOperation = result.Op2;
var startExpr = (ExpressionSyntax)startOperation.Syntax;
var endExpr = (ExpressionSyntax)endOperation.Syntax;
var startFromEnd = false;
var endFromEnd = false;
var lengthLikeProperty = result.MemberInfo.LengthLikeProperty;
var instance = result.InvocationOperation.Instance;
// If our start-op is actually equivalent to `expr.Length - val`, then just change our
// start-op to be `val` and record that we should emit it as `^val`.
startFromEnd = IsFromEnd(lengthLikeProperty, instance, ref startOperation);
startExpr = (ExpressionSyntax)startOperation.Syntax;
// Similarly, if our end-op is actually equivalent to `expr.Length - val`, then just
// change our end-op to be `val` and record that we should emit it as `^val`.
endFromEnd = IsFromEnd(lengthLikeProperty, instance, ref endOperation);
endExpr = (ExpressionSyntax)endOperation.Syntax;
// If the range operation goes to 'expr.Length' then we can just leave off the end part
// of the range. i.e. `start..`
if (IsInstanceLengthCheck(lengthLikeProperty, instance, endOperation))
{
endExpr = null;
}
// If we're starting the range operation from 0, then we can just leave off the start of
// the range. i.e. `..end`
if (startOperation.ConstantValue.HasValue &&
startOperation.ConstantValue.Value is 0)
{
startExpr = null;
}
return RangeExpression(
startExpr != null && startFromEnd ? IndexExpression(startExpr) : startExpr,
endExpr != null && endFromEnd ? IndexExpression(endExpr) : endExpr);
}
private static ExpressionSyntax GetExpression(ImmutableDictionary<string, string> props, ExpressionSyntax expr, string omitKey, string fromEndKey)
=> props.ContainsKey(omitKey)
? null
: props.ContainsKey(fromEndKey) ? IndexExpression(expr) : expr;
private static RangeExpressionSyntax CreateConstantRange(
SemanticModel semanticModel, Result result, CancellationToken cancellationToken)
{
var constant1Syntax = (ExpressionSyntax)result.Op1.Syntax;
var constant2Syntax = (ExpressionSyntax)result.Op2.Syntax;
// the form is s.Slice(constant1, s.Length - constant2). Want to generate
// s[constant1..(constant2-constant1)]
var constant1 = GetInt32Value(result.Op1);
var constant2 = GetInt32Value(result.Op2);
var endExpr = (ExpressionSyntax)CSharpSyntaxGenerator.Instance.LiteralExpression(constant2 - constant1);
return RangeExpression(
constant1Syntax,
IndexExpression(endExpr));
}
private static int GetInt32Value(IOperation operation)
=> (int)operation.ConstantValue.Value;
/// <summary>
/// check if its the form: `expr.Length - value`. If so, update rangeOperation to then
/// point to 'value' so that we can generate '^value'.
/// </summary>
private static bool IsFromEnd(
IPropertySymbol lengthLikeProperty, IOperation instance, ref IOperation rangeOperation)
{
if (IsSubtraction(rangeOperation, out var subtraction) &&
IsInstanceLengthCheck(lengthLikeProperty, instance, subtraction.LeftOperand))
{
rangeOperation = subtraction.RightOperand;
return true;
}
return false;
}
private class MyCodeAction : CodeAction.DocumentChangeAction
{
public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument)
: base(FeaturesResources.Use_range_operator, createChangedDocument, FeaturesResources.Use_range_operator)
{
}
}
}
}
| 44.080508
| 161
| 0.633663
|
[
"Apache-2.0"
] |
GovernessS/roslyn
|
src/Features/CSharp/Portable/UseIndexOrRangeOperator/CSharpUseRangeOperatorCodeFixProvider.cs
| 10,405
|
C#
|
namespace Witter.Services.Data
{
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Witter.Data.Common.Repositories;
using Witter.Data.Models;
using Witter.Data.Models.Enums;
using Witter.Services.Data.Contracts;
public class FollowerService : IFollowerService
{
private readonly IDeletableEntityRepository<UserFollowers> followerRepository;
private readonly IUserService userService;
private readonly INotificationsService notificationsService;
public FollowerService(IDeletableEntityRepository<UserFollowers> repository, IUserService userService, INotificationsService notificationsService)
{
this.followerRepository = repository;
this.userService = userService;
this.notificationsService = notificationsService;
}
// TODO: Properties are mapping in reverse
// Data models for userFollowers table should change.
public async Task Follow(string senderId, string reciverId)
{
var entity = this.followerRepository
.AllWithDeleted()
.FirstOrDefault(x => x.RevicerId == reciverId && x.SenderId == senderId);
var sender = this.userService.GetUserId(senderId);
var revicer = this.userService.GetUserId(reciverId);
if (entity == null || !entity.IsDeleted)
{
var insertEntity = new UserFollowers()
{
Sender = sender,
Revicer = revicer,
IsFollowing = true,
};
await this.followerRepository.AddAsync(insertEntity);
}
else
{
entity.IsFollowing = true;
this.followerRepository.Undelete(entity);
}
await this.notificationsService.AddNotificationAsync(sender, revicer, NotificationType.Follow);
await this.followerRepository.SaveChangesAsync();
}
public async Task UnFollow(string senderId, string reciverId)
{
var entity = this.followerRepository
.All()
.FirstOrDefaultAsync(x => x.RevicerId == reciverId && x.SenderId == senderId)
.GetAwaiter()
.GetResult();
if (entity.IsFollowing)
{
entity.IsFollowing = false;
this.followerRepository.Delete(entity);
await this.followerRepository.SaveChangesAsync();
}
}
public bool IsFollowing(string senderId, string reciverId)
{
var entity = this.followerRepository
.All()
.FirstOrDefaultAsync(x => x.RevicerId == reciverId && x.SenderId == senderId)
.GetAwaiter()
.GetResult();
return entity != null && entity.IsFollowing;
}
}
}
| 34.802326
| 154
| 0.590378
|
[
"MIT"
] |
Dreed657/Witter
|
src/Services/Witter.Services.Data/FollowerService.cs
| 2,995
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using EcsRx.Examples.ExampleApps.Performance.Components.Specific;
using EcsRx.Groups;
namespace EcsRx.Examples.ExampleApps.Performance.Helper
{
public class RandomGroupFactory
{
public IEnumerable<Type> GetComponentTypes => _componentTypes;
private List<Type> _componentTypes;
public RandomGroupFactory()
{
PopulateComponentList();
}
private void PopulateComponentList()
{
var componentNamespace = typeof(Component1).Namespace;
var componentTypes = typeof(Component1).Assembly.GetTypes().Where(x => x.Namespace == componentNamespace);
_componentTypes = componentTypes.ToList();
}
public IEnumerable<IGroup> CreateTestGroups(int cycles = 5)
{
for (var i = 1; i < cycles; i++)
{
for (var j = 0; j < _componentTypes.Count; j++)
{
yield return new Group(_componentTypes.Skip(i).Take(j).ToArray());
}
}
}
}
}
| 30.675676
| 118
| 0.597357
|
[
"MIT"
] |
EcsRx/ecsrx
|
src/EcsRx.Examples/ExampleApps/Performance/Helper/RandomGroupFactory.cs
| 1,137
|
C#
|
using Microsoft.CodeAnalysis;
namespace NSubstitute.Analyzers.Shared.DiagnosticAnalyzers
{
internal readonly struct NonSubstitutableMemberAnalysisResult
{
public bool CanBeSubstituted { get; }
public bool NonVirtualMemberSubstitution { get; }
public bool InternalMemberSubstitution { get; }
public ISymbol Symbol { get; }
public string MemberName { get; }
public SyntaxNode Member { get; }
public NonSubstitutableMemberAnalysisResult(
bool nonVirtualMemberSubstitution,
bool internalMemberSubstitution,
ISymbol symbol,
SyntaxNode member,
string memberName)
{
NonVirtualMemberSubstitution = nonVirtualMemberSubstitution;
InternalMemberSubstitution = internalMemberSubstitution;
Member = member;
MemberName = memberName;
Symbol = symbol;
CanBeSubstituted = !NonVirtualMemberSubstitution && !InternalMemberSubstitution;
}
}
}
| 31.705882
| 93
| 0.640074
|
[
"MIT"
] |
nsubstitute/NSubstitute.Analyzers
|
src/NSubstitute.Analyzers.Shared/DiagnosticAnalyzers/NonSubstitutableMemberAnalysisResult.cs
| 1,078
|
C#
|
///*
// link: https://practice.geeksforgeeks.org/problems/largest-bst/1
// set2: https://www.geeksforgeeks.org/largest-bst-binary-tree-set-2/
// set1 (just refer it): https://www.geeksforgeeks.org/find-the-largest-subtree-in-a-tree-that-is-also-a-bst/
//*/
//// ----------------------------------------------------------------------------------------------------------------------- //
//// C++ program to find largest BST in a
//// Binary Tree.
//#include <bits/stdc++.h>
//using namespace std;
///* A binary tree node has data,
//pointer to left child and a
//pointer to right child */
//struct Node
//{
// int data;
// struct Node* left;
// struct Node* right;
//};
///* Helper function that allocates a new
//node with the given data and NULL left
//and right pointers. */
//struct Node* newNode(int data)
//{
// struct Node* node = new Node;
// node->data = data;
// node->left = node->right = NULL;
// return(node);
//}
//// Information to be returned by every
//// node in bottom up traversal.
//struct Info
//{
// int sz; // Size of subtree
// int max; // Min value in subtree
// int min; // Max value in subtree
// int ans; // Size of largest BST which
// // is subtree of current node
// bool isBST; // If subtree is BST
//};
//// Returns Information about subtree. The
//// Information also includes size of largest
//// subtree which is a BST.
//Info largestBSTBT(Node* root)
//{
// // Base cases : When tree is empty or it has
// // one child.
// if (root == NULL)
// return { 0, INT_MIN, INT_MAX, 0, true };
// if (root->left == NULL && root->right == NULL)
// return { 1, root->data, root->data, 1, true };
// // Recur for left subtree and right subtrees
// Info l = largestBSTBT(root->left);
// Info r = largestBSTBT(root->right);
// // Create a return variable and initialize its
// // size.
// Info ret;
// ret.sz = (1 + l.sz + r.sz);
// // If whole tree rooted under current root is
// // BST.
// if (l.isBST && r.isBST && l.max < root->data &&
// r.min > root->data)
// {
// ret.min = min(l.min, min(r.min, root->data));
// ret.max = max(r.max, max(l.max, root->data));
// // Update answer for tree rooted under
// // current 'root'
// ret.ans = ret.sz;
// ret.isBST = true;
// return ret;
// }
// // If whole tree is not BST, return maximum
// // of left and right subtrees
// ret.ans = max(l.ans, r.ans);
// ret.isBST = false;
// return ret;
//}
///* Driver program to test above functions*/
//int main()
//{
// /* Let us construct the following Tree
// 60
// / \
// 65 70
// /
// 50 */
// struct Node* root = newNode(60);
// root->left = newNode(65);
// root->right = newNode(70);
// root->left->left = newNode(50);
// printf(" Size of the largest BST is %d\n",
// largestBSTBT(root).ans);
// return 0;
//}
| 26.553571
| 127
| 0.546738
|
[
"MIT"
] |
harshanu11/Love-Babbar-450-In-CSharp
|
Love-Babbar-450-In-CSharp/07_binary_search_trees/21_largest_BST_in_binary_tree.cs
| 2,974
|
C#
|
using AutoFixture;
using MediatR;
using Moq;
using NUnit.Framework;
using SFA.DAS.CommitmentsV2.Application.Commands.ValidateApprenticeshipForEdit;
using SFA.DAS.CommitmentsV2.Domain.Entities.EditApprenticeshipValidation;
using SFA.DAS.CommitmentsV2.Domain.Interfaces;
using SFA.DAS.CommitmentsV2.Shared.Interfaces;
using SFA.DAS.Testing.AutoFixture;
using System.Threading;
using System.Threading.Tasks;
namespace SFA.DAS.CommitmentsV2.UnitTests.Application.Commands
{
public class ValidateApprenticeshipForEditCommandHandlerTests
{
[Test, MoqAutoData]
public async Task EditValidationServiceIsCalled()
{
//Act
var fixture = new ValidateApprenticeshipForEditCommandHandlerTestsFixture();
await fixture.Handle();
fixture.Verify_EditApprenticeshipValidationService_IsCalled_Once();
}
public class ValidateApprenticeshipForEditCommandHandlerTestsFixture
{
Mock<IEditApprenticeshipValidationService> _editValidationService;
Mock<IModelMapper> _modelMapper;
ValidateApprenticeshipForEditCommand _command;
public IRequestHandler<ValidateApprenticeshipForEditCommand, EditApprenticeshipValidationResult> Handler { get; set; }
public ValidateApprenticeshipForEditCommandHandlerTestsFixture()
{
var fixture = new Fixture();
_editValidationService = new Mock<IEditApprenticeshipValidationService>();
_modelMapper = new Mock<IModelMapper>();
_command = fixture.Create<ValidateApprenticeshipForEditCommand>();
_editValidationService.Setup(x => x.Validate(It.IsAny<EditApprenticeshipValidationRequest>(), CancellationToken.None)).Returns(Task.FromResult(new EditApprenticeshipValidationResult()));
Handler = new ValidateApprenticeshipForEditCommandHandler(_editValidationService.Object);
}
public async Task<ValidateApprenticeshipForEditCommandHandlerTestsFixture> Handle()
{
await Handler.Handle(_command, CancellationToken.None);
return this;
}
public void Verify_EditApprenticeshipValidationService_IsCalled_Once()
{
_editValidationService.Verify(x => x.Validate(It.IsAny<EditApprenticeshipValidationRequest>(), CancellationToken.None), Times.Once);
}
}
}
}
| 41.316667
| 202
| 0.70956
|
[
"MIT"
] |
SkillsFundingAgency/das-commitments
|
src/CommitmentsV2/SFA.DAS.CommitmentsV2.UnitTests/Application/Commands/ValidateApprenticeshipForEditCommandHandlerTests.cs
| 2,481
|
C#
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.Arm;
namespace JIT.HardwareIntrinsics.Arm
{
public static partial class Program
{
private static void MultiplyDoublingWideningLowerAndAddSaturate_Vector64_Int32()
{
var test =
new SimpleTernaryOpTest__MultiplyDoublingWideningLowerAndAddSaturate_Vector64_Int32();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (AdvSimd.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleTernaryOpTest__MultiplyDoublingWideningLowerAndAddSaturate_Vector64_Int32
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] inArray3;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle inHandle3;
private GCHandle outHandle;
private ulong alignment;
public DataTable(
Int64[] inArray1,
Int32[] inArray2,
Int32[] inArray3,
Int64[] outArray,
int alignment
)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int64>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int32>();
int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<Int32>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int64>();
if (
(alignment != 16 && alignment != 8)
|| (alignment * 2) < sizeOfinArray1
|| (alignment * 2) < sizeOfinArray2
|| (alignment * 2) < sizeOfinArray3
|| (alignment * 2) < sizeOfoutArray
)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.inArray3 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.inHandle3 = GCHandle.Alloc(this.inArray3, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(
ref Unsafe.AsRef<byte>(inArray1Ptr),
ref Unsafe.As<Int64, byte>(ref inArray1[0]),
(uint)sizeOfinArray1
);
Unsafe.CopyBlockUnaligned(
ref Unsafe.AsRef<byte>(inArray2Ptr),
ref Unsafe.As<Int32, byte>(ref inArray2[0]),
(uint)sizeOfinArray2
);
Unsafe.CopyBlockUnaligned(
ref Unsafe.AsRef<byte>(inArray3Ptr),
ref Unsafe.As<Int32, byte>(ref inArray3[0]),
(uint)sizeOfinArray3
);
}
public void* inArray1Ptr =>
Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr =>
Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray3Ptr =>
Align((byte*)(inHandle3.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr =>
Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
inHandle3.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Int64> _fld1;
public Vector64<Int32> _fld2;
public Vector64<Int32> _fld3;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++)
{
_data1[i] = TestLibrary.Generator.GetInt64();
}
Unsafe.CopyBlockUnaligned(
ref Unsafe.As<Vector128<Int64>, byte>(ref testStruct._fld1),
ref Unsafe.As<Int64, byte>(ref _data1[0]),
(uint)Unsafe.SizeOf<Vector128<Int64>>()
);
for (var i = 0; i < Op2ElementCount; i++)
{
_data2[i] = TestLibrary.Generator.GetInt32();
}
Unsafe.CopyBlockUnaligned(
ref Unsafe.As<Vector64<Int32>, byte>(ref testStruct._fld2),
ref Unsafe.As<Int32, byte>(ref _data2[0]),
(uint)Unsafe.SizeOf<Vector64<Int32>>()
);
for (var i = 0; i < Op3ElementCount; i++)
{
_data3[i] = TestLibrary.Generator.GetInt32();
}
Unsafe.CopyBlockUnaligned(
ref Unsafe.As<Vector64<Int32>, byte>(ref testStruct._fld3),
ref Unsafe.As<Int32, byte>(ref _data3[0]),
(uint)Unsafe.SizeOf<Vector64<Int32>>()
);
return testStruct;
}
public void RunStructFldScenario(
SimpleTernaryOpTest__MultiplyDoublingWideningLowerAndAddSaturate_Vector64_Int32 testClass
)
{
var result = AdvSimd.MultiplyDoublingWideningLowerAndAddSaturate(
_fld1,
_fld2,
_fld3
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(
SimpleTernaryOpTest__MultiplyDoublingWideningLowerAndAddSaturate_Vector64_Int32 testClass
)
{
fixed (Vector128<Int64>* pFld1 = &_fld1)
fixed (Vector64<Int32>* pFld2 = &_fld2)
fixed (Vector64<Int32>* pFld3 = &_fld3)
{
var result = AdvSimd.MultiplyDoublingWideningLowerAndAddSaturate(
AdvSimd.LoadVector128((Int64*)(pFld1)),
AdvSimd.LoadVector64((Int32*)(pFld2)),
AdvSimd.LoadVector64((Int32*)(pFld3))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount =
Unsafe.SizeOf<Vector128<Int64>>() / sizeof(Int64);
private static readonly int Op2ElementCount =
Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32);
private static readonly int Op3ElementCount =
Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32);
private static readonly int RetElementCount =
Unsafe.SizeOf<Vector128<Int64>>() / sizeof(Int64);
private static Int64[] _data1 = new Int64[Op1ElementCount];
private static Int32[] _data2 = new Int32[Op2ElementCount];
private static Int32[] _data3 = new Int32[Op3ElementCount];
private static Vector128<Int64> _clsVar1;
private static Vector64<Int32> _clsVar2;
private static Vector64<Int32> _clsVar3;
private Vector128<Int64> _fld1;
private Vector64<Int32> _fld2;
private Vector64<Int32> _fld3;
private DataTable _dataTable;
static SimpleTernaryOpTest__MultiplyDoublingWideningLowerAndAddSaturate_Vector64_Int32()
{
for (var i = 0; i < Op1ElementCount; i++)
{
_data1[i] = TestLibrary.Generator.GetInt64();
}
Unsafe.CopyBlockUnaligned(
ref Unsafe.As<Vector128<Int64>, byte>(ref _clsVar1),
ref Unsafe.As<Int64, byte>(ref _data1[0]),
(uint)Unsafe.SizeOf<Vector128<Int64>>()
);
for (var i = 0; i < Op2ElementCount; i++)
{
_data2[i] = TestLibrary.Generator.GetInt32();
}
Unsafe.CopyBlockUnaligned(
ref Unsafe.As<Vector64<Int32>, byte>(ref _clsVar2),
ref Unsafe.As<Int32, byte>(ref _data2[0]),
(uint)Unsafe.SizeOf<Vector64<Int32>>()
);
for (var i = 0; i < Op3ElementCount; i++)
{
_data3[i] = TestLibrary.Generator.GetInt32();
}
Unsafe.CopyBlockUnaligned(
ref Unsafe.As<Vector64<Int32>, byte>(ref _clsVar3),
ref Unsafe.As<Int32, byte>(ref _data3[0]),
(uint)Unsafe.SizeOf<Vector64<Int32>>()
);
}
public SimpleTernaryOpTest__MultiplyDoublingWideningLowerAndAddSaturate_Vector64_Int32()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++)
{
_data1[i] = TestLibrary.Generator.GetInt64();
}
Unsafe.CopyBlockUnaligned(
ref Unsafe.As<Vector128<Int64>, byte>(ref _fld1),
ref Unsafe.As<Int64, byte>(ref _data1[0]),
(uint)Unsafe.SizeOf<Vector128<Int64>>()
);
for (var i = 0; i < Op2ElementCount; i++)
{
_data2[i] = TestLibrary.Generator.GetInt32();
}
Unsafe.CopyBlockUnaligned(
ref Unsafe.As<Vector64<Int32>, byte>(ref _fld2),
ref Unsafe.As<Int32, byte>(ref _data2[0]),
(uint)Unsafe.SizeOf<Vector64<Int32>>()
);
for (var i = 0; i < Op3ElementCount; i++)
{
_data3[i] = TestLibrary.Generator.GetInt32();
}
Unsafe.CopyBlockUnaligned(
ref Unsafe.As<Vector64<Int32>, byte>(ref _fld3),
ref Unsafe.As<Int32, byte>(ref _data3[0]),
(uint)Unsafe.SizeOf<Vector64<Int32>>()
);
for (var i = 0; i < Op1ElementCount; i++)
{
_data1[i] = TestLibrary.Generator.GetInt64();
}
for (var i = 0; i < Op2ElementCount; i++)
{
_data2[i] = TestLibrary.Generator.GetInt32();
}
for (var i = 0; i < Op3ElementCount; i++)
{
_data3[i] = TestLibrary.Generator.GetInt32();
}
_dataTable = new DataTable(
_data1,
_data2,
_data3,
new Int64[RetElementCount],
LargestVectorSize
);
}
public bool IsSupported => AdvSimd.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = AdvSimd.MultiplyDoublingWideningLowerAndAddSaturate(
Unsafe.Read<Vector128<Int64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector64<Int32>>(_dataTable.inArray2Ptr),
Unsafe.Read<Vector64<Int32>>(_dataTable.inArray3Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(
_dataTable.inArray1Ptr,
_dataTable.inArray2Ptr,
_dataTable.inArray3Ptr,
_dataTable.outArrayPtr
);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.MultiplyDoublingWideningLowerAndAddSaturate(
AdvSimd.LoadVector128((Int64*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector64((Int32*)(_dataTable.inArray2Ptr)),
AdvSimd.LoadVector64((Int32*)(_dataTable.inArray3Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(
_dataTable.inArray1Ptr,
_dataTable.inArray2Ptr,
_dataTable.inArray3Ptr,
_dataTable.outArrayPtr
);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(AdvSimd)
.GetMethod(
nameof(AdvSimd.MultiplyDoublingWideningLowerAndAddSaturate),
new Type[]
{
typeof(Vector128<Int64>),
typeof(Vector64<Int32>),
typeof(Vector64<Int32>)
}
)
.Invoke(
null,
new object[]
{
Unsafe.Read<Vector128<Int64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector64<Int32>>(_dataTable.inArray2Ptr),
Unsafe.Read<Vector64<Int32>>(_dataTable.inArray3Ptr)
}
);
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result));
ValidateResult(
_dataTable.inArray1Ptr,
_dataTable.inArray2Ptr,
_dataTable.inArray3Ptr,
_dataTable.outArrayPtr
);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd)
.GetMethod(
nameof(AdvSimd.MultiplyDoublingWideningLowerAndAddSaturate),
new Type[]
{
typeof(Vector128<Int64>),
typeof(Vector64<Int32>),
typeof(Vector64<Int32>)
}
)
.Invoke(
null,
new object[]
{
AdvSimd.LoadVector128((Int64*)(_dataTable.inArray1Ptr)),
AdvSimd.LoadVector64((Int32*)(_dataTable.inArray2Ptr)),
AdvSimd.LoadVector64((Int32*)(_dataTable.inArray3Ptr))
}
);
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result));
ValidateResult(
_dataTable.inArray1Ptr,
_dataTable.inArray2Ptr,
_dataTable.inArray3Ptr,
_dataTable.outArrayPtr
);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.MultiplyDoublingWideningLowerAndAddSaturate(
_clsVar1,
_clsVar2,
_clsVar3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Int64>* pClsVar1 = &_clsVar1)
fixed (Vector64<Int32>* pClsVar2 = &_clsVar2)
fixed (Vector64<Int32>* pClsVar3 = &_clsVar3)
{
var result = AdvSimd.MultiplyDoublingWideningLowerAndAddSaturate(
AdvSimd.LoadVector128((Int64*)(pClsVar1)),
AdvSimd.LoadVector64((Int32*)(pClsVar2)),
AdvSimd.LoadVector64((Int32*)(pClsVar3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Int64>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector64<Int32>>(_dataTable.inArray2Ptr);
var op3 = Unsafe.Read<Vector64<Int32>>(_dataTable.inArray3Ptr);
var result = AdvSimd.MultiplyDoublingWideningLowerAndAddSaturate(op1, op2, op3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector128((Int64*)(_dataTable.inArray1Ptr));
var op2 = AdvSimd.LoadVector64((Int32*)(_dataTable.inArray2Ptr));
var op3 = AdvSimd.LoadVector64((Int32*)(_dataTable.inArray3Ptr));
var result = AdvSimd.MultiplyDoublingWideningLowerAndAddSaturate(op1, op2, op3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test =
new SimpleTernaryOpTest__MultiplyDoublingWideningLowerAndAddSaturate_Vector64_Int32();
var result = AdvSimd.MultiplyDoublingWideningLowerAndAddSaturate(
test._fld1,
test._fld2,
test._fld3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test =
new SimpleTernaryOpTest__MultiplyDoublingWideningLowerAndAddSaturate_Vector64_Int32();
fixed (Vector128<Int64>* pFld1 = &test._fld1)
fixed (Vector64<Int32>* pFld2 = &test._fld2)
fixed (Vector64<Int32>* pFld3 = &test._fld3)
{
var result = AdvSimd.MultiplyDoublingWideningLowerAndAddSaturate(
AdvSimd.LoadVector128((Int64*)(pFld1)),
AdvSimd.LoadVector64((Int32*)(pFld2)),
AdvSimd.LoadVector64((Int32*)(pFld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.MultiplyDoublingWideningLowerAndAddSaturate(_fld1, _fld2, _fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Int64>* pFld1 = &_fld1)
fixed (Vector64<Int32>* pFld2 = &_fld2)
fixed (Vector64<Int32>* pFld3 = &_fld3)
{
var result = AdvSimd.MultiplyDoublingWideningLowerAndAddSaturate(
AdvSimd.LoadVector128((Int64*)(pFld1)),
AdvSimd.LoadVector64((Int32*)(pFld2)),
AdvSimd.LoadVector64((Int32*)(pFld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.MultiplyDoublingWideningLowerAndAddSaturate(
test._fld1,
test._fld2,
test._fld3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = AdvSimd.MultiplyDoublingWideningLowerAndAddSaturate(
AdvSimd.LoadVector128((Int64*)(&test._fld1)),
AdvSimd.LoadVector64((Int32*)(&test._fld2)),
AdvSimd.LoadVector64((Int32*)(&test._fld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(
Vector128<Int64> op1,
Vector64<Int32> op2,
Vector64<Int32> op3,
void* result,
[CallerMemberName] string method = ""
)
{
Int64[] inArray1 = new Int64[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Int32[] inArray3 = new Int32[Op3ElementCount];
Int64[] outArray = new Int64[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), op2);
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray3[0]), op3);
Unsafe.CopyBlockUnaligned(
ref Unsafe.As<Int64, byte>(ref outArray[0]),
ref Unsafe.AsRef<byte>(result),
(uint)Unsafe.SizeOf<Vector128<Int64>>()
);
ValidateResult(inArray1, inArray2, inArray3, outArray, method);
}
private void ValidateResult(
void* op1,
void* op2,
void* op3,
void* result,
[CallerMemberName] string method = ""
)
{
Int64[] inArray1 = new Int64[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Int32[] inArray3 = new Int32[Op3ElementCount];
Int64[] outArray = new Int64[RetElementCount];
Unsafe.CopyBlockUnaligned(
ref Unsafe.As<Int64, byte>(ref inArray1[0]),
ref Unsafe.AsRef<byte>(op1),
(uint)Unsafe.SizeOf<Vector128<Int64>>()
);
Unsafe.CopyBlockUnaligned(
ref Unsafe.As<Int32, byte>(ref inArray2[0]),
ref Unsafe.AsRef<byte>(op2),
(uint)Unsafe.SizeOf<Vector64<Int32>>()
);
Unsafe.CopyBlockUnaligned(
ref Unsafe.As<Int32, byte>(ref inArray3[0]),
ref Unsafe.AsRef<byte>(op3),
(uint)Unsafe.SizeOf<Vector64<Int32>>()
);
Unsafe.CopyBlockUnaligned(
ref Unsafe.As<Int64, byte>(ref outArray[0]),
ref Unsafe.AsRef<byte>(result),
(uint)Unsafe.SizeOf<Vector128<Int64>>()
);
ValidateResult(inArray1, inArray2, inArray3, outArray, method);
}
private void ValidateResult(
Int64[] firstOp,
Int32[] secondOp,
Int32[] thirdOp,
Int64[] result,
[CallerMemberName] string method = ""
)
{
bool succeeded = true;
for (var i = 0; i < RetElementCount; i++)
{
if (
Helpers.MultiplyDoublingWideningAndAddSaturate(
firstOp[i],
secondOp[i],
thirdOp[i]
) != result[i]
)
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation(
$"{nameof(AdvSimd)}.{nameof(AdvSimd.MultiplyDoublingWideningLowerAndAddSaturate)}<Int64>(Vector128<Int64>, Vector64<Int32>, Vector64<Int32>): {method} failed:"
);
TestLibrary.TestFramework.LogInformation(
$" firstOp: ({string.Join(", ", firstOp)})"
);
TestLibrary.TestFramework.LogInformation(
$"secondOp: ({string.Join(", ", secondOp)})"
);
TestLibrary.TestFramework.LogInformation(
$" thirdOp: ({string.Join(", ", thirdOp)})"
);
TestLibrary.TestFramework.LogInformation(
$" result: ({string.Join(", ", result)})"
);
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| 38.17875
| 179
| 0.532986
|
[
"MIT"
] |
belav/runtime
|
src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/MultiplyDoublingWideningLowerAndAddSaturate.Vector64.Int32.cs
| 30,543
|
C#
|
/*
Copyright 2017 Microsoft
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 SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH
THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using Microsoft.Devices.Management;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Windows.Foundation.Diagnostics;
using Mock.Microsoft.Azure.Devices.Client;
namespace Mock.App
{
class AppDeviceManagementRequestHandler : IDeviceManagementRequestHandler
{
DeviceClientApp appHandler;
public AppDeviceManagementRequestHandler(DeviceClientApp appHandler)
{
this.appHandler = appHandler;
}
// Answer the question "is it OK to reboot the device"
async Task<bool> IDeviceManagementRequestHandler.IsSystemRebootAllowed()
{
return await Task.FromResult<bool>(true);
}
}
class DeviceClientApp
{
private const string JsonVersion = "$version";
public DeviceManagementClient DMClient
{
get
{
return _deviceManagementClient;
}
}
private async Task<string> GetConnectionStringAsync()
{
var tpmDevice = new TpmDevice();
string connectionString = "";
do
{
try
{
// connectionString = await tpmDevice.GetConnectionStringAsync();
connectionString = "HostName=remote-monitoring-pcs.azure-devices.net;DeviceId=gmileka06;SharedAccessKey=7iKTI2S9w0tY65kx8Ble7fk649guK6oCNZ27FpWD8co=";
break;
}
catch (Exception)
{
// We'll just keep trying.
}
await Task.Delay(1000);
} while (true);
return connectionString;
}
private async Task ResetConnectionAsync(DeviceClient existingConnection, Twin twin)
{
Logger.Log("ResetConnectionAsync start", LoggingLevel.Verbose);
// Attempt to close any existing connections before
// creating a new one
if (existingConnection != null)
{
await existingConnection.CloseAsync().ContinueWith((t) =>
{
var e = t.Exception;
if (e != null)
{
var msg = "existingClient.CloseAsync exception: " + e.Message + "\n" + e.StackTrace;
System.Diagnostics.Debug.WriteLine(msg);
Logger.Log(msg, LoggingLevel.Verbose);
}
});
}
// Get new SAS Token
var deviceConnectionString = await GetConnectionStringAsync();
// Create DeviceClient. Application uses DeviceClient for telemetry messages, device twin
// as well as device management
_deviceClient = DeviceClient.CreateFromConnectionString(twin, deviceConnectionString, TransportType.Mqtt);
// IDeviceTwin abstracts away communication with the back-end.
// AzureIoTHubDeviceTwinProxy is an implementation of Azure IoT Hub
IDeviceTwin deviceTwin = new Mock.Lib.AzureIoTHubDeviceTwinProxy(_deviceClient, twin, ResetConnectionAsync, Logger.Log);
// IDeviceManagementRequestHandler handles device management-specific requests to the app,
// such as whether it is OK to perform a reboot at any givem moment, according the app business logic
// AppDeviceManagementRequestHandler is the Toaster app implementation of the interface
IDeviceManagementRequestHandler appRequestHandler = new AppDeviceManagementRequestHandler(this);
// Create the DeviceManagementClient, the main entry point into device management
this._deviceManagementClient = await DeviceManagementClient.CreateAsync(deviceTwin, appRequestHandler);
// Set the callback for desired properties update. The callback will be invoked
// for all desired properties -- including those specific to device management
await _deviceClient.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertyUpdated, null);
// Tell the _deviceManagementClient to sync the device with the current desired state.
await this._deviceManagementClient.ApplyDesiredStateAsync();
Logger.Log("ResetConnectionAsync end", LoggingLevel.Verbose);
}
public async Task InitializeDeviceClientAsync(Twin twin)
{
while (true)
{
try
{
await ResetConnectionAsync(null, twin);
break;
}
catch (Exception e)
{
var msg = "InitializeDeviceClientAsync exception: " + e.Message + "\n" + e.StackTrace;
System.Diagnostics.Debug.WriteLine(msg);
Logger.Log(msg, LoggingLevel.Error);
}
await Task.Delay(5 * 60 * 1000);
}
}
private async Task OnDesiredPropertyUpdated(TwinCollection twinProperties, object userContext)
{
Dictionary<string, object> desiredProperties = new Dictionary<string, object>();
foreach (KeyValuePair<string, object> p in twinProperties)
{
desiredProperties[p.Key] = p.Value;
}
desiredProperties[JsonVersion] = twinProperties.Version;
// Let the device management client process properties specific to device management
await this._deviceManagementClient.ApplyDesiredStateAsync(desiredProperties);
// Application developer can process all the top-level nodes here
// return Task.CompletedTask;
}
DeviceClient _deviceClient;
DeviceManagementClient _deviceManagementClient;
}
}
| 40.676647
| 170
| 0.632563
|
[
"MIT"
] |
mehrdad-shokri/iot-core-azure-dm-client
|
tests/E2ETestApp/MockObjects/MockDeviceClientApp.cs
| 6,795
|
C#
|
using Maincotech.ExamAssistant;
using Maincotech.ExamAssistant.ViewModels;
using ReactiveUI;
using System;
using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reactive;
using System.Threading.Tasks;
namespace Maincotech.ExamAssistant.Pages.Exam
{
public class EditViewModel : SettingBasedViewModel
{
private static Maincotech.Logging.ILogger _Logger = AppRuntimeContext.Current.GetLogger<EditViewModel>();
private string _Name;
[Required]
public string Name
{
get => _Name;
set => this.RaiseAndSetIfChanged(ref _Name, value);
}
private string _Provider;
public string Provider
{
get => _Provider;
set => this.RaiseAndSetIfChanged(ref _Provider, value);
}
private string _Id;
public string Id
{
get => _Id;
set => this.RaiseAndSetIfChanged(ref _Id, value);
}
private int _Duration;
public int Duration
{
get => _Duration;
set => this.RaiseAndSetIfChanged(ref _Duration, value);
}
public string SearchText { get; set; }
public int PageNumber { get; set; } = 1;
public int PageSize { get; set; } = 10;
public int Total { get; set; }
public int NextOffset { get; set; }
public bool HasMoreData { get; set; }
private readonly ObservableAsPropertyHelper<bool> _isLoading;
public bool IsLoading => _isLoading.Value;
public ObservableCollection<QuestionViewModel> Items { get; set; } = new ObservableCollection<QuestionViewModel>();
public EditViewModel(string userId):base(userId)
{
Search = ReactiveCommand.CreateFromTask(SearchAsync);
Load = ReactiveCommand.CreateFromTask(LoadAsync);
LoadMore = ReactiveCommand.CreateFromTask(LoadMoreAsync);
Search.ThrownExceptions.Subscribe(exception =>
{
_Logger.Error("Unexpected error occurred.", exception);
});
this.WhenAnyObservable(x => x.Search.IsExecuting).ToProperty(this, x => x.IsLoading, out _isLoading);
UpdateSection = ReactiveCommand.CreateFromTask<SectionViewModel>(CreateOrUpdateSectionAsync);
DeleteSection = ReactiveCommand.CreateFromTask<SectionViewModel>(DeleteSectionAsync);
UpdateQuestion = ReactiveCommand.CreateFromTask<QuestionViewModel>(CreateOrUpdateQuestionAsync);
DeleteQuestion = ReactiveCommand.CreateFromTask<QuestionViewModel>(DeleteQuestionAsync);
LoadSection = ReactiveCommand.CreateFromTask<SectionViewModel>(LoadSectioinAsync);
}
private async Task SearchAsync()
{
Items.Clear();
var query = new LoadMoreQuery
{
Limit = 10,
Offset = 0,
SearchText = SearchText
};
var queryResult = await client.GetQuestionsAsync(Id, query);
NextOffset = queryResult.NextOffset;
HasMoreData = queryResult.HasMoreData;
foreach (var dto in queryResult.Items)
{
Items.Add(dto.To<QuestionViewModel>());
}
}
private async Task LoadMoreAsync()
{
var query = new LoadMoreQuery
{
Limit = 10,
Offset = NextOffset,
SearchText = SearchText
};
var queryResult = await client.GetQuestionsAsync(Id, query);
HasMoreData = queryResult.HasMoreData;
NextOffset = queryResult.NextOffset;
foreach (var dto in queryResult.Items)
{
Items.Add(dto.To<QuestionViewModel>());
}
}
// public ReactiveCommand<Unit, Unit> Load { get; }
public ReactiveCommand<Unit, Unit> Search { get; }
public ReactiveCommand<Unit, Unit> Load { get; }
public ReactiveCommand<Unit, Unit> LoadMore { get; }
public ReactiveCommand<SectionViewModel, Unit> UpdateSection { get; }
public ReactiveCommand<SectionViewModel, Unit> DeleteSection { get; }
public ReactiveCommand<QuestionViewModel, Unit> UpdateQuestion { get; }
public ReactiveCommand<QuestionViewModel, Unit> DeleteQuestion { get; }
public ReactiveCommand<SectionViewModel, Unit> LoadSection { get; }
public ObservableCollection<SectionViewModel> Sections { get; set; } = new ObservableCollection<SectionViewModel>();
private async Task LoadSectioinAsync(SectionViewModel vm)
{
var dtos = await client.GetQuestionsInSectionAsync(Id, vm.Id);
foreach (var dto in dtos)
{
var questionVM = dto.To<QuestionViewModel>();
vm.Questions.Add(questionVM);
}
vm.IsLoaded = true;
// var section = Sections.First(x => x.Id == vm.SectionId);
// section.Questions.Remove(vm);
}
private async Task DeleteQuestionAsync(QuestionViewModel vm)
{
await client.DeleteQuestionAsync(vm.ExamId, vm.SectionId, vm.Id);
var section = Sections.First(x => x.Id == vm.SectionId);
section.Questions.Remove(vm);
}
private async Task DeleteSectionAsync(SectionViewModel vm)
{
await client.DeleteSectionAsync(Id, vm.Id);
Sections.Remove(vm);
}
private async Task CreateOrUpdateSectionAsync(SectionViewModel vm)
{
var dto = new SectionDto
{
ExamId = Id,
Id = vm.Id,
Name = vm.Name,
Description = vm.MarkdownContent
};
dto = await client.CreateOrUpdateSectionAsync(Id,dto);
vm.Id = dto.Id;
if (Sections.Contains(vm) == false)
{
Sections.Add(vm);
}
}
private async Task CreateOrUpdateQuestionAsync(QuestionViewModel vm)
{
var dto = vm.To<QuestionDto>();
dto = await client.CreateOrUpdateQuestionAsync(Id,vm.SectionId,dto);
vm.Id = dto.Id;
var sectionVM = Sections.First(x => x.Id == vm.SectionId);
if (sectionVM.Questions.Contains(vm) == false)
{
sectionVM.Questions.Add(vm);
}
}
private async Task LoadAsync()
{
ExamDto examDto;
if (Id.IsNotNullOrEmpty())
{
examDto = await client.GetExamAsync(Id);
await LoadSections();
}
else
{
examDto = new ExamDto
{
Name = "New exam",
Duration = 0,
};
examDto = await client.CreateOrUpdateExamAsync(examDto);
}
Id = examDto.Id;
Name = examDto.Name;
Provider = examDto.Provider;
Duration = examDto.Duration;
//Sections = new ObservableCollection<SectionViewModel>();
//Questions = new ObservableCollection<QuestionViewModel>();
}
public async Task LoadSections()
{
var sections = await client.GetSectionsAsync(Id);
foreach (var section in sections)
{
Sections.Add(new SectionViewModel
{
Id = section.Id,
Name = section.Name,
MarkdownContent = section.Description,
NumberOfQuestions = section.NumberOfQuestions
});
}
}
public int GetIndex(QuestionViewModel viewModel)
{
var index = 1;
SectionViewModel sectionViewModel = null;
foreach (var section in Sections)
{
if (section.Id == viewModel.SectionId)
{
sectionViewModel = section;
break;
}
index += section.NumberOfQuestions;
}
foreach (var question in sectionViewModel.Questions)
{
if (question.Id == viewModel.Id)
{
break;
}
index++;
}
return index;
}
}
}
| 33.988095
| 124
| 0.557501
|
[
"MIT"
] |
maincotech/quizmaker
|
src/Maincotech.ExamAssistant.Maker/Pages/Exam/Edit.razor.ViewModel.cs
| 8,567
|
C#
|
// Copyright 2021-present Etherna Sagl
//
// 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 Etherna.CreditSystem.Areas.Api.DtoModels;
using System.Collections.Generic;
using System.Security.Claims;
using System.Threading.Tasks;
namespace Etherna.CreditSystem.Areas.Api.Services
{
public interface IUserControllerService
{
string GetAddress(ClaimsPrincipal user);
Task<CreditDto> GetCreditAsync(ClaimsPrincipal user);
Task<IEnumerable<OperationLogDto>> GetLogsAsync(ClaimsPrincipal user, int page, int take);
}
}
| 38.607143
| 98
| 0.743756
|
[
"Apache-2.0"
] |
Etherna/etherna-credit
|
src/EthernaCredit/Areas/Api/Services/IUserControllerService.cs
| 1,083
|
C#
|
using Miru.Fabrication;
using Miru.Fabrication.FixtureConventions;
namespace Corpo.Skeleton.Tests;
public class SkeletonFabricator : Fabricator
{
public SkeletonFabricator(FabSupport context) : base(context)
{
Fixture.AddConvention(cfg =>
{
cfg.IfPropertyNameIs("Name").Use(f => f.Name.FullName());
});
}
}
| 23.733333
| 69
| 0.671348
|
[
"MIT"
] |
MiruFx/Miru
|
samples/Corpo.Skeleton/tests/Corpo.Skeleton.Tests/SkeletonFabricator.cs
| 356
|
C#
|
//------------------------------------------------------------
// Game Framework
// Copyright © 2013-2020 Jiang Yin. All rights reserved.
// Homepage: https://gameframework.cn/
// Feedback: mailto:ellan@gameframework.cn
//------------------------------------------------------------
using GameFramework.Download;
using GameFramework.FileSystem;
using System;
using System.Collections.Generic;
using System.IO;
namespace GameFramework.Resource
{
internal sealed partial class ResourceManager : GameFrameworkModule, IResourceManager
{
/// <summary>
/// 资源更新器。
/// </summary>
private sealed partial class ResourceUpdater
{
private const int CachedHashBytesLength = 4;
private const int CachedBytesLength = 0x1000;
private readonly ResourceManager m_ResourceManager;
private readonly List<ApplyInfo> m_ApplyWaitingInfo;
private readonly List<UpdateInfo> m_UpdateWaitingInfo;
private readonly Dictionary<ResourceName, UpdateInfo> m_UpdateCandidateInfo;
private readonly SortedDictionary<string, List<int>> m_CachedFileSystemsForGenerateReadWriteVersionList;
private readonly byte[] m_CachedHashBytes;
private readonly byte[] m_CachedBytes;
private IDownloadManager m_DownloadManager;
private bool m_CheckResourcesComplete;
private string m_ApplyingResourcePackPath;
private FileStream m_ApplyingResourcePackStream;
private ResourceGroup m_UpdatingResourceGroup;
private int m_GenerateReadWriteVersionListLength;
private int m_CurrentGenerateReadWriteVersionListLength;
private int m_UpdateRetryCount;
private int m_UpdatingCount;
private bool m_FailureFlag;
private string m_ReadWriteVersionListFileName;
private string m_ReadWriteVersionListBackupFileName;
public GameFrameworkAction<ResourceName, string, string, int, int> ResourceApplySuccess;
public GameFrameworkAction<ResourceName, string, string> ResourceApplyFailure;
public GameFrameworkAction<string, bool, bool> ResourceApplyComplete;
public GameFrameworkAction<ResourceName, string, string, int, int, int> ResourceUpdateStart;
public GameFrameworkAction<ResourceName, string, string, int, int> ResourceUpdateChanged;
public GameFrameworkAction<ResourceName, string, string, int, int> ResourceUpdateSuccess;
public GameFrameworkAction<ResourceName, string, int, int, string> ResourceUpdateFailure;
public GameFrameworkAction<ResourceGroup, bool, bool> ResourceUpdateComplete;
/// <summary>
/// 初始化资源更新器的新实例。
/// </summary>
/// <param name="resourceManager">资源管理器。</param>
public ResourceUpdater(ResourceManager resourceManager)
{
m_ResourceManager = resourceManager;
m_ApplyWaitingInfo = new List<ApplyInfo>();
m_UpdateWaitingInfo = new List<UpdateInfo>();
m_UpdateCandidateInfo = new Dictionary<ResourceName, UpdateInfo>();
m_CachedFileSystemsForGenerateReadWriteVersionList = new SortedDictionary<string, List<int>>(StringComparer.Ordinal);
m_CachedHashBytes = new byte[CachedHashBytesLength];
m_CachedBytes = new byte[CachedBytesLength];
m_DownloadManager = null;
m_CheckResourcesComplete = false;
m_ApplyingResourcePackPath = null;
m_ApplyingResourcePackStream = null;
m_UpdatingResourceGroup = null;
m_GenerateReadWriteVersionListLength = 0;
m_CurrentGenerateReadWriteVersionListLength = 0;
m_UpdateRetryCount = 3;
m_UpdatingCount = 0;
m_FailureFlag = false;
m_ReadWriteVersionListFileName = Utility.Path.GetRegularPath(Path.Combine(m_ResourceManager.m_ReadWritePath, LocalVersionListFileName));
m_ReadWriteVersionListBackupFileName = Utility.Text.Format("{0}.{1}", m_ReadWriteVersionListFileName, BackupExtension);
ResourceApplySuccess = null;
ResourceApplyFailure = null;
ResourceApplyComplete = null;
ResourceUpdateStart = null;
ResourceUpdateChanged = null;
ResourceUpdateSuccess = null;
ResourceUpdateFailure = null;
ResourceUpdateComplete = null;
}
/// <summary>
/// 获取或设置每更新多少字节的资源,重新生成一次版本资源列表。
/// </summary>
public int GenerateReadWriteVersionListLength
{
get
{
return m_GenerateReadWriteVersionListLength;
}
set
{
m_GenerateReadWriteVersionListLength = value;
}
}
/// <summary>
/// 获取正在应用的资源包路径。
/// </summary>
public string ApplyingResourcePackPath
{
get
{
return m_ApplyingResourcePackPath;
}
}
/// <summary>
/// 获取等待应用资源数量。
/// </summary>
public int ApplyWaitingCount
{
get
{
return m_ApplyWaitingInfo.Count;
}
}
/// <summary>
/// 获取或设置资源更新重试次数。
/// </summary>
public int UpdateRetryCount
{
get
{
return m_UpdateRetryCount;
}
set
{
m_UpdateRetryCount = value;
}
}
/// <summary>
/// 获取正在更新的资源组。
/// </summary>
public IResourceGroup UpdatingResourceGroup
{
get
{
return m_UpdatingResourceGroup;
}
}
/// <summary>
/// 获取等待更新资源数量。
/// </summary>
public int UpdateWaitingCount
{
get
{
return m_UpdateWaitingInfo.Count;
}
}
/// <summary>
/// 获取候选更新资源数量。
/// </summary>
public int UpdateCandidateCount
{
get
{
return m_UpdateCandidateInfo.Count;
}
}
/// <summary>
/// 获取正在更新资源数量。
/// </summary>
public int UpdatingCount
{
get
{
return m_UpdatingCount;
}
}
/// <summary>
/// 资源更新器轮询。
/// </summary>
/// <param name="elapseSeconds">逻辑流逝时间,以秒为单位。</param>
/// <param name="realElapseSeconds">真实流逝时间,以秒为单位。</param>
public void Update(float elapseSeconds, float realElapseSeconds)
{
if (m_ApplyingResourcePackStream != null)
{
while (m_ApplyWaitingInfo.Count > 0)
{
ApplyInfo applyInfo = m_ApplyWaitingInfo[0];
m_ApplyWaitingInfo.RemoveAt(0);
if (ApplyResource(applyInfo))
{
return;
}
}
Array.Clear(m_CachedBytes, 0, CachedBytesLength);
string resourcePackPath = m_ApplyingResourcePackPath;
m_ApplyingResourcePackPath = null;
m_ApplyingResourcePackStream.Dispose();
m_ApplyingResourcePackStream = null;
if (ResourceApplyComplete != null)
{
ResourceApplyComplete(resourcePackPath, !m_FailureFlag, m_UpdateCandidateInfo.Count <= 0);
}
}
if (m_UpdateWaitingInfo.Count > 0)
{
if (m_DownloadManager.FreeAgentCount > 0)
{
UpdateInfo updateInfo = m_UpdateWaitingInfo[0];
m_UpdateWaitingInfo.RemoveAt(0);
string resourceFullNameWithCrc32 = updateInfo.ResourceName.Variant != null ? Utility.Text.Format("{0}.{1}.{2:x8}.{3}", updateInfo.ResourceName.Name, updateInfo.ResourceName.Variant, updateInfo.HashCode, DefaultExtension) : Utility.Text.Format("{0}.{1:x8}.{2}", updateInfo.ResourceName.Name, updateInfo.HashCode, DefaultExtension);
m_DownloadManager.AddDownload(updateInfo.ResourcePath, Utility.Path.GetRemotePath(Path.Combine(m_ResourceManager.m_UpdatePrefixUri, resourceFullNameWithCrc32)), updateInfo);
m_UpdatingCount++;
}
return;
}
if (m_UpdatingResourceGroup != null && m_UpdatingCount <= 0)
{
ResourceGroup updatingResourceGroup = m_UpdatingResourceGroup;
m_UpdatingResourceGroup = null;
if (ResourceUpdateComplete != null)
{
ResourceUpdateComplete(updatingResourceGroup, !m_FailureFlag, m_UpdateCandidateInfo.Count <= 0);
}
return;
}
}
/// <summary>
/// 关闭并清理资源更新器。
/// </summary>
public void Shutdown()
{
if (m_DownloadManager != null)
{
m_DownloadManager.DownloadStart -= OnDownloadStart;
m_DownloadManager.DownloadUpdate -= OnDownloadUpdate;
m_DownloadManager.DownloadSuccess -= OnDownloadSuccess;
m_DownloadManager.DownloadFailure -= OnDownloadFailure;
}
m_UpdateWaitingInfo.Clear();
m_UpdateCandidateInfo.Clear();
m_CachedFileSystemsForGenerateReadWriteVersionList.Clear();
}
/// <summary>
/// 设置下载管理器。
/// </summary>
/// <param name="downloadManager">下载管理器。</param>
public void SetDownloadManager(IDownloadManager downloadManager)
{
if (downloadManager == null)
{
throw new GameFrameworkException("Download manager is invalid.");
}
m_DownloadManager = downloadManager;
m_DownloadManager.DownloadStart += OnDownloadStart;
m_DownloadManager.DownloadUpdate += OnDownloadUpdate;
m_DownloadManager.DownloadSuccess += OnDownloadSuccess;
m_DownloadManager.DownloadFailure += OnDownloadFailure;
}
/// <summary>
/// 增加资源更新。
/// </summary>
/// <param name="resourceName">资源名称。</param>
/// <param name="fileSystemName">资源所在的文件系统名称。</param>
/// <param name="loadType">资源加载方式。</param>
/// <param name="length">资源大小。</param>
/// <param name="hashCode">资源哈希值。</param>
/// <param name="zipLength">压缩后大小。</param>
/// <param name="zipHashCode">压缩后哈希值。</param>
/// <param name="resourcePath">资源路径。</param>
public void AddResourceUpdate(ResourceName resourceName, string fileSystemName, LoadType loadType, int length, int hashCode, int zipLength, int zipHashCode, string resourcePath)
{
m_UpdateCandidateInfo.Add(resourceName, new UpdateInfo(resourceName, fileSystemName, loadType, length, hashCode, zipLength, zipHashCode, resourcePath));
}
/// <summary>
/// 检查资源完成。
/// </summary>
/// <param name="needGenerateReadWriteVersionList">是否需要生成读写区版本资源列表。</param>
public void CheckResourceComplete(bool needGenerateReadWriteVersionList)
{
m_CheckResourcesComplete = true;
if (needGenerateReadWriteVersionList)
{
GenerateReadWriteVersionList();
}
}
/// <summary>
/// 应用指定资源包的资源。
/// </summary>
/// <param name="resourcePackPath">要应用的资源包路径。</param>
public void ApplyResources(string resourcePackPath)
{
if (!m_CheckResourcesComplete)
{
throw new GameFrameworkException("You must check resources complete first.");
}
if (m_ApplyingResourcePackStream != null)
{
throw new GameFrameworkException(Utility.Text.Format("There is already a resource pack '{0}' being applied.", m_ApplyingResourcePackPath));
}
if (m_UpdatingResourceGroup != null)
{
throw new GameFrameworkException(Utility.Text.Format("There is already a resource group '{0}' being updated.", m_UpdatingResourceGroup.Name));
}
try
{
long length = 0L;
ResourcePackVersionList versionList = default(ResourcePackVersionList);
using (FileStream fileStream = new FileStream(resourcePackPath, FileMode.Open, FileAccess.Read))
{
length = fileStream.Length;
versionList = m_ResourceManager.m_ResourcePackVersionListSerializer.Deserialize(fileStream);
}
if (!versionList.IsValid)
{
throw new GameFrameworkException("Deserialize resource pack version list failure.");
}
if (versionList.Offset + versionList.Length != length)
{
throw new GameFrameworkException("Resource pack length is invalid.");
}
m_ApplyingResourcePackPath = resourcePackPath;
m_ApplyingResourcePackStream = new FileStream(resourcePackPath, FileMode.Open, FileAccess.Read);
m_ApplyingResourcePackStream.Position = versionList.Offset;
m_FailureFlag = false;
ResourcePackVersionList.Resource[] resources = versionList.GetResources();
foreach (ResourcePackVersionList.Resource resource in resources)
{
ResourceName resourceName = new ResourceName(resource.Name, resource.Variant, resource.Extension);
UpdateInfo updateInfo = null;
if (!m_UpdateCandidateInfo.TryGetValue(resourceName, out updateInfo))
{
continue;
}
if (updateInfo.LoadType == (LoadType)resource.LoadType && updateInfo.Length == resource.Length && updateInfo.HashCode == resource.HashCode)
{
m_ApplyWaitingInfo.Add(new ApplyInfo(resourceName, updateInfo.FileSystemName, (LoadType)resource.LoadType, resource.Offset, resource.Length, resource.HashCode, resource.ZipLength, resource.ZipHashCode, updateInfo.ResourcePath));
}
}
}
catch (Exception exception)
{
if (m_ApplyingResourcePackStream != null)
{
m_ApplyingResourcePackStream.Dispose();
m_ApplyingResourcePackStream = null;
}
throw new GameFrameworkException(Utility.Text.Format("Apply resources '{0}' with exception '{1}'.", resourcePackPath, exception.ToString()), exception);
}
}
/// <summary>
/// 更新指定资源组的资源。
/// </summary>
/// <param name="resourceGroup">要更新的资源组。</param>
public void UpdateResources(ResourceGroup resourceGroup)
{
if (m_DownloadManager == null)
{
throw new GameFrameworkException("You must set download manager first.");
}
if (!m_CheckResourcesComplete)
{
throw new GameFrameworkException("You must check resources complete first.");
}
if (m_ApplyingResourcePackStream != null)
{
throw new GameFrameworkException(Utility.Text.Format("There is already a resource pack '{0}' being applied.", m_ApplyingResourcePackPath));
}
if (m_UpdatingResourceGroup != null)
{
throw new GameFrameworkException(Utility.Text.Format("There is already a resource group '{0}' being updated.", m_UpdatingResourceGroup.Name));
}
if (string.IsNullOrEmpty(resourceGroup.Name))
{
foreach (KeyValuePair<ResourceName, UpdateInfo> updateInfo in m_UpdateCandidateInfo)
{
m_UpdateWaitingInfo.Add(updateInfo.Value);
}
m_UpdateCandidateInfo.Clear();
}
else
{
ResourceName[] resourceNames = resourceGroup.InternalGetResourceNames();
foreach (ResourceName resourceName in resourceNames)
{
UpdateInfo updateInfo = null;
if (!m_UpdateCandidateInfo.TryGetValue(resourceName, out updateInfo))
{
continue;
}
m_UpdateWaitingInfo.Add(updateInfo);
m_UpdateCandidateInfo.Remove(resourceName);
}
}
m_UpdatingResourceGroup = resourceGroup;
m_FailureFlag = false;
}
public void UpdateResource(ResourceName resourceName)
{
if (m_DownloadManager == null)
{
throw new GameFrameworkException("You must set download manager first.");
}
if (!m_CheckResourcesComplete)
{
throw new GameFrameworkException("You must check resources complete first.");
}
if (m_ApplyingResourcePackStream != null)
{
throw new GameFrameworkException(Utility.Text.Format("There is already a resource pack '{0}' being applied.", m_ApplyingResourcePackPath));
}
UpdateInfo updateInfo = null;
if (m_UpdateCandidateInfo.TryGetValue(resourceName, out updateInfo))
{
m_UpdateWaitingInfo.Add(updateInfo);
m_UpdateCandidateInfo.Remove(resourceName);
}
}
private bool ApplyResource(ApplyInfo applyInfo)
{
long position = m_ApplyingResourcePackStream.Position;
try
{
bool zip = applyInfo.Length != applyInfo.ZipLength || applyInfo.HashCode != applyInfo.ZipHashCode;
int bytesRead = 0;
int bytesLeft = applyInfo.ZipLength;
string directory = Path.GetDirectoryName(applyInfo.ResourcePath);
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
m_ApplyingResourcePackStream.Position += applyInfo.Offset;
using (FileStream fileStream = new FileStream(applyInfo.ResourcePath, FileMode.Create, FileAccess.ReadWrite))
{
while ((bytesRead = m_ApplyingResourcePackStream.Read(m_CachedBytes, 0, bytesLeft < CachedBytesLength ? bytesLeft : CachedBytesLength)) > 0)
{
bytesLeft -= bytesRead;
fileStream.Write(m_CachedBytes, 0, bytesRead);
}
if (zip)
{
fileStream.Position = 0L;
int hashCode = Utility.Verifier.GetCrc32(fileStream);
if (hashCode != applyInfo.ZipHashCode)
{
if (ResourceApplyFailure != null)
{
string errorMessage = Utility.Text.Format("Resource zip hash code error, need '{0}', applied '{1}'.", applyInfo.ZipHashCode.ToString(), hashCode.ToString());
ResourceApplyFailure(applyInfo.ResourceName, m_ApplyingResourcePackPath, errorMessage);
}
return false;
}
if (m_ResourceManager.m_DecompressCachedStream == null)
{
m_ResourceManager.m_DecompressCachedStream = new MemoryStream();
}
fileStream.Position = 0L;
m_ResourceManager.m_DecompressCachedStream.Position = 0L;
m_ResourceManager.m_DecompressCachedStream.SetLength(0L);
if (!Utility.Zip.Decompress(fileStream, m_ResourceManager.m_DecompressCachedStream))
{
if (ResourceApplyFailure != null)
{
string errorMessage = Utility.Text.Format("Unable to decompress resource '{0}'.", applyInfo.ResourcePath);
ResourceApplyFailure(applyInfo.ResourceName, m_ApplyingResourcePackPath, errorMessage);
}
return false;
}
fileStream.Position = 0L;
fileStream.SetLength(0L);
fileStream.Write(m_ResourceManager.m_DecompressCachedStream.GetBuffer(), 0, (int)m_ResourceManager.m_DecompressCachedStream.Length);
}
else
{
int hashCode = 0;
fileStream.Position = 0L;
if (applyInfo.LoadType == LoadType.LoadFromMemoryAndQuickDecrypt || applyInfo.LoadType == LoadType.LoadFromMemoryAndDecrypt
|| applyInfo.LoadType == LoadType.LoadFromBinaryAndQuickDecrypt || applyInfo.LoadType == LoadType.LoadFromBinaryAndDecrypt)
{
applyInfo.HashCode = Utility.Converter.GetInt32(m_CachedHashBytes);
if (applyInfo.LoadType == LoadType.LoadFromMemoryAndQuickDecrypt || applyInfo.LoadType == LoadType.LoadFromBinaryAndQuickDecrypt)
{
hashCode = Utility.Verifier.GetCrc32(fileStream, m_CachedHashBytes, Utility.Encryption.QuickEncryptLength);
}
else if (applyInfo.LoadType == LoadType.LoadFromMemoryAndDecrypt || applyInfo.LoadType == LoadType.LoadFromBinaryAndDecrypt)
{
hashCode = Utility.Verifier.GetCrc32(fileStream, m_CachedHashBytes, applyInfo.Length);
}
Array.Clear(m_CachedHashBytes, 0, CachedHashBytesLength);
}
else
{
hashCode = Utility.Verifier.GetCrc32(fileStream);
}
if (hashCode != applyInfo.HashCode)
{
if (ResourceApplyFailure != null)
{
string errorMessage = Utility.Text.Format("Resource hash code error, need '{0}', applied '{1}'.", applyInfo.HashCode.ToString(), hashCode.ToString());
ResourceApplyFailure(applyInfo.ResourceName, m_ApplyingResourcePackPath, errorMessage);
}
return false;
}
}
}
if (applyInfo.UseFileSystem)
{
IFileSystem fileSystem = m_ResourceManager.GetFileSystem(applyInfo.FileSystemName, false);
bool retVal = fileSystem.WriteFile(applyInfo.ResourceName.FullName, applyInfo.ResourcePath);
if (File.Exists(applyInfo.ResourcePath))
{
File.Delete(applyInfo.ResourcePath);
}
return retVal;
}
m_UpdateCandidateInfo.Remove(applyInfo.ResourceName);
m_ResourceManager.m_ResourceInfos[applyInfo.ResourceName].MarkReady();
m_ResourceManager.m_ReadWriteResourceInfos.Add(applyInfo.ResourceName, new ReadWriteResourceInfo(applyInfo.FileSystemName, applyInfo.LoadType, applyInfo.Length, applyInfo.HashCode));
if (ResourceApplySuccess != null)
{
ResourceApplySuccess(applyInfo.ResourceName, applyInfo.ResourcePath, m_ApplyingResourcePackPath, applyInfo.Length, applyInfo.ZipLength);
}
string downloadingResource = Utility.Text.Format("{0}.download", applyInfo.ResourcePath);
if (File.Exists(downloadingResource))
{
File.Delete(downloadingResource);
}
m_CurrentGenerateReadWriteVersionListLength += applyInfo.ZipLength;
if (m_ApplyWaitingInfo.Count <= 0 || m_CurrentGenerateReadWriteVersionListLength >= m_GenerateReadWriteVersionListLength)
{
m_CurrentGenerateReadWriteVersionListLength = 0;
GenerateReadWriteVersionList();
return true;
}
return false;
}
catch (Exception exception)
{
if (ResourceApplyFailure != null)
{
ResourceApplyFailure(applyInfo.ResourceName, m_ApplyingResourcePackPath, exception.ToString());
}
return false;
}
finally
{
m_ApplyingResourcePackStream.Position = position;
}
}
private void GenerateReadWriteVersionList()
{
if (File.Exists(m_ReadWriteVersionListFileName))
{
if (File.Exists(m_ReadWriteVersionListBackupFileName))
{
File.Delete(m_ReadWriteVersionListBackupFileName);
}
File.Move(m_ReadWriteVersionListFileName, m_ReadWriteVersionListBackupFileName);
}
FileStream fileStream = null;
try
{
fileStream = new FileStream(m_ReadWriteVersionListFileName, FileMode.Create, FileAccess.Write);
LocalVersionList.Resource[] resources = m_ResourceManager.m_ReadWriteResourceInfos.Count > 0 ? new LocalVersionList.Resource[m_ResourceManager.m_ReadWriteResourceInfos.Count] : null;
if (resources != null)
{
int index = 0;
foreach (KeyValuePair<ResourceName, ReadWriteResourceInfo> i in m_ResourceManager.m_ReadWriteResourceInfos)
{
resources[index] = new LocalVersionList.Resource(i.Key.Name, i.Key.Variant, i.Key.Extension, (byte)i.Value.LoadType, i.Value.Length, i.Value.HashCode);
if (i.Value.UseFileSystem)
{
List<int> resourceIndexes = null;
if (!m_CachedFileSystemsForGenerateReadWriteVersionList.TryGetValue(i.Value.FileSystemName, out resourceIndexes))
{
resourceIndexes = new List<int>();
m_CachedFileSystemsForGenerateReadWriteVersionList.Add(i.Value.FileSystemName, resourceIndexes);
}
resourceIndexes.Add(index);
}
index++;
}
}
LocalVersionList.FileSystem[] fileSystems = m_CachedFileSystemsForGenerateReadWriteVersionList.Count > 0 ? new LocalVersionList.FileSystem[m_CachedFileSystemsForGenerateReadWriteVersionList.Count] : null;
if (fileSystems != null)
{
int index = 0;
foreach (KeyValuePair<string, List<int>> i in m_CachedFileSystemsForGenerateReadWriteVersionList)
{
fileSystems[index++] = new LocalVersionList.FileSystem(i.Key, i.Value.ToArray());
i.Value.Clear();
}
}
LocalVersionList versionList = new LocalVersionList(resources, fileSystems);
if (!m_ResourceManager.m_ReadWriteVersionListSerializer.Serialize(fileStream, versionList))
{
throw new GameFrameworkException("Serialize read write version list failure.");
}
if (fileStream != null)
{
fileStream.Dispose();
fileStream = null;
}
if (File.Exists(m_ReadWriteVersionListBackupFileName))
{
File.Delete(m_ReadWriteVersionListBackupFileName);
}
}
catch (Exception exception)
{
if (fileStream != null)
{
fileStream.Dispose();
fileStream = null;
}
if (File.Exists(m_ReadWriteVersionListFileName))
{
File.Delete(m_ReadWriteVersionListFileName);
}
if (File.Exists(m_ReadWriteVersionListBackupFileName))
{
File.Move(m_ReadWriteVersionListBackupFileName, m_ReadWriteVersionListFileName);
}
throw new GameFrameworkException(Utility.Text.Format("Generate read write version list exception '{0}'.", exception.ToString()), exception);
}
}
private void OnDownloadStart(object sender, DownloadStartEventArgs e)
{
UpdateInfo updateInfo = e.UserData as UpdateInfo;
if (updateInfo == null)
{
return;
}
if (m_DownloadManager == null)
{
throw new GameFrameworkException("You must set download manager first.");
}
if (ResourceUpdateStart != null)
{
ResourceUpdateStart(updateInfo.ResourceName, e.DownloadPath, e.DownloadUri, e.CurrentLength, updateInfo.ZipLength, updateInfo.RetryCount);
}
}
private void OnDownloadUpdate(object sender, DownloadUpdateEventArgs e)
{
UpdateInfo updateInfo = e.UserData as UpdateInfo;
if (updateInfo == null)
{
return;
}
if (m_DownloadManager == null)
{
throw new GameFrameworkException("You must set download manager first.");
}
if (e.CurrentLength > updateInfo.ZipLength)
{
m_DownloadManager.RemoveDownload(e.SerialId);
string downloadFile = Utility.Text.Format("{0}.download", e.DownloadPath);
if (File.Exists(downloadFile))
{
File.Delete(downloadFile);
}
string errorMessage = Utility.Text.Format("When download update, downloaded length is larger than zip length, need '{0}', downloaded '{1}'.", updateInfo.ZipLength.ToString(), e.CurrentLength.ToString());
DownloadFailureEventArgs downloadFailureEventArgs = DownloadFailureEventArgs.Create(e.SerialId, e.DownloadPath, e.DownloadUri, errorMessage, e.UserData);
OnDownloadFailure(this, downloadFailureEventArgs);
ReferencePool.Release(downloadFailureEventArgs);
return;
}
if (ResourceUpdateChanged != null)
{
ResourceUpdateChanged(updateInfo.ResourceName, e.DownloadPath, e.DownloadUri, e.CurrentLength, updateInfo.ZipLength);
}
}
private void OnDownloadSuccess(object sender, DownloadSuccessEventArgs e)
{
UpdateInfo updateInfo = e.UserData as UpdateInfo;
if (updateInfo == null)
{
return;
}
using (FileStream fileStream = new FileStream(e.DownloadPath, FileMode.Open, FileAccess.ReadWrite))
{
bool zip = updateInfo.Length != updateInfo.ZipLength || updateInfo.HashCode != updateInfo.ZipHashCode;
int length = (int)fileStream.Length;
if (length != updateInfo.ZipLength)
{
fileStream.Close();
string errorMessage = Utility.Text.Format("Resource zip length error, need '{0}', downloaded '{1}'.", updateInfo.ZipLength.ToString(), length.ToString());
DownloadFailureEventArgs downloadFailureEventArgs = DownloadFailureEventArgs.Create(e.SerialId, e.DownloadPath, e.DownloadUri, errorMessage, e.UserData);
OnDownloadFailure(this, downloadFailureEventArgs);
ReferencePool.Release(downloadFailureEventArgs);
return;
}
if (zip)
{
fileStream.Position = 0L;
int hashCode = Utility.Verifier.GetCrc32(fileStream);
if (hashCode != updateInfo.ZipHashCode)
{
fileStream.Close();
string errorMessage = Utility.Text.Format("Resource zip hash code error, need '{0}', downloaded '{1}'.", updateInfo.ZipHashCode.ToString(), hashCode.ToString());
DownloadFailureEventArgs downloadFailureEventArgs = DownloadFailureEventArgs.Create(e.SerialId, e.DownloadPath, e.DownloadUri, errorMessage, e.UserData);
OnDownloadFailure(this, downloadFailureEventArgs);
ReferencePool.Release(downloadFailureEventArgs);
return;
}
if (m_ResourceManager.m_DecompressCachedStream == null)
{
m_ResourceManager.m_DecompressCachedStream = new MemoryStream();
}
try
{
fileStream.Position = 0L;
m_ResourceManager.m_DecompressCachedStream.Position = 0L;
m_ResourceManager.m_DecompressCachedStream.SetLength(0L);
if (!Utility.Zip.Decompress(fileStream, m_ResourceManager.m_DecompressCachedStream))
{
fileStream.Close();
string errorMessage = Utility.Text.Format("Unable to decompress resource '{0}'.", e.DownloadPath);
DownloadFailureEventArgs downloadFailureEventArgs = DownloadFailureEventArgs.Create(e.SerialId, e.DownloadPath, e.DownloadUri, errorMessage, e.UserData);
OnDownloadFailure(this, downloadFailureEventArgs);
ReferencePool.Release(downloadFailureEventArgs);
return;
}
if (m_ResourceManager.m_DecompressCachedStream.Length != updateInfo.Length)
{
fileStream.Close();
string errorMessage = Utility.Text.Format("Resource length error, need '{0}', downloaded '{1}'.", updateInfo.Length.ToString(), m_ResourceManager.m_DecompressCachedStream.Length.ToString());
DownloadFailureEventArgs downloadFailureEventArgs = DownloadFailureEventArgs.Create(e.SerialId, e.DownloadPath, e.DownloadUri, errorMessage, e.UserData);
OnDownloadFailure(this, downloadFailureEventArgs);
ReferencePool.Release(downloadFailureEventArgs);
return;
}
fileStream.Position = 0L;
fileStream.SetLength(0L);
fileStream.Write(m_ResourceManager.m_DecompressCachedStream.GetBuffer(), 0, (int)m_ResourceManager.m_DecompressCachedStream.Length);
}
catch (Exception exception)
{
fileStream.Close();
string errorMessage = Utility.Text.Format("Unable to decompress resource '{0}' with error message '{1}'.", e.DownloadPath, exception.ToString());
DownloadFailureEventArgs downloadFailureEventArgs = DownloadFailureEventArgs.Create(e.SerialId, e.DownloadPath, e.DownloadUri, errorMessage, e.UserData);
OnDownloadFailure(this, downloadFailureEventArgs);
ReferencePool.Release(downloadFailureEventArgs);
return;
}
finally
{
m_ResourceManager.m_DecompressCachedStream.Position = 0L;
m_ResourceManager.m_DecompressCachedStream.SetLength(0L);
}
}
else
{
int hashCode = 0;
fileStream.Position = 0L;
if (updateInfo.LoadType == LoadType.LoadFromMemoryAndQuickDecrypt || updateInfo.LoadType == LoadType.LoadFromMemoryAndDecrypt
|| updateInfo.LoadType == LoadType.LoadFromBinaryAndQuickDecrypt || updateInfo.LoadType == LoadType.LoadFromBinaryAndDecrypt)
{
updateInfo.HashCode = Utility.Converter.GetInt32( m_CachedHashBytes);
if (updateInfo.LoadType == LoadType.LoadFromMemoryAndQuickDecrypt || updateInfo.LoadType == LoadType.LoadFromBinaryAndQuickDecrypt)
{
hashCode = Utility.Verifier.GetCrc32(fileStream, m_CachedHashBytes, Utility.Encryption.QuickEncryptLength);
}
else if (updateInfo.LoadType == LoadType.LoadFromMemoryAndDecrypt || updateInfo.LoadType == LoadType.LoadFromBinaryAndDecrypt)
{
hashCode = Utility.Verifier.GetCrc32(fileStream, m_CachedHashBytes, length);
}
Array.Clear(m_CachedHashBytes, 0, CachedHashBytesLength);
}
else
{
hashCode = Utility.Verifier.GetCrc32(fileStream);
}
if (hashCode != updateInfo.HashCode)
{
fileStream.Close();
string errorMessage = Utility.Text.Format("Resource hash code error, need '{0}', downloaded '{1}'.", updateInfo.HashCode.ToString(), hashCode.ToString());
DownloadFailureEventArgs downloadFailureEventArgs = DownloadFailureEventArgs.Create(e.SerialId, e.DownloadPath, e.DownloadUri, errorMessage, e.UserData);
OnDownloadFailure(this, downloadFailureEventArgs);
ReferencePool.Release(downloadFailureEventArgs);
return;
}
}
}
if (updateInfo.UseFileSystem)
{
IFileSystem fileSystem = m_ResourceManager.GetFileSystem(updateInfo.FileSystemName, false);
bool retVal = fileSystem.WriteFile(updateInfo.ResourceName.FullName, updateInfo.ResourcePath);
if (File.Exists(updateInfo.ResourcePath))
{
File.Delete(updateInfo.ResourcePath);
}
if (!retVal)
{
string errorMessage = Utility.Text.Format("Write resource to file system '{0}' error.", fileSystem.FullPath);
DownloadFailureEventArgs downloadFailureEventArgs = DownloadFailureEventArgs.Create(e.SerialId, e.DownloadPath, e.DownloadUri, errorMessage, e.UserData);
OnDownloadFailure(this, downloadFailureEventArgs);
return;
}
}
m_UpdatingCount--;
m_ResourceManager.m_ResourceInfos[updateInfo.ResourceName].MarkReady();
m_ResourceManager.m_ReadWriteResourceInfos.Add(updateInfo.ResourceName, new ReadWriteResourceInfo(updateInfo.FileSystemName, updateInfo.LoadType, updateInfo.Length, updateInfo.HashCode));
m_CurrentGenerateReadWriteVersionListLength += updateInfo.ZipLength;
if (m_UpdatingCount <= 0 || m_CurrentGenerateReadWriteVersionListLength >= m_GenerateReadWriteVersionListLength)
{
m_CurrentGenerateReadWriteVersionListLength = 0;
GenerateReadWriteVersionList();
}
if (ResourceUpdateSuccess != null)
{
ResourceUpdateSuccess(updateInfo.ResourceName, e.DownloadPath, e.DownloadUri, updateInfo.Length, updateInfo.ZipLength);
}
}
private void OnDownloadFailure(object sender, DownloadFailureEventArgs e)
{
UpdateInfo updateInfo = e.UserData as UpdateInfo;
if (updateInfo == null)
{
return;
}
if (File.Exists(e.DownloadPath))
{
File.Delete(e.DownloadPath);
}
m_UpdatingCount--;
if (ResourceUpdateFailure != null)
{
ResourceUpdateFailure(updateInfo.ResourceName, e.DownloadUri, updateInfo.RetryCount, m_UpdateRetryCount, e.ErrorMessage);
}
if (updateInfo.RetryCount < m_UpdateRetryCount)
{
updateInfo.RetryCount++;
m_UpdateWaitingInfo.Add(updateInfo);
}
else
{
m_FailureFlag = true;
updateInfo.RetryCount = 0;
m_UpdateCandidateInfo.Add(updateInfo.ResourceName, updateInfo);
}
}
}
}
}
| 47.682489
| 354
| 0.516868
|
[
"MIT"
] |
jaysunxiao/zsharp
|
GameFramework/Resource/ResourceManager.ResourceUpdater.cs
| 45,842
|
C#
|
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
namespace Microsoft.eShopWeb.Web.API
{
public class CustomSchemaFilters : ISchemaFilter
{
public void Apply(OpenApiSchema schema, SchemaFilterContext context)
{
var excludeProperties = new[] { "CorrelationId" };
foreach (var prop in excludeProperties)
if (schema.Properties.ContainsKey(prop))
schema.Properties.Remove(prop);
}
}
}
| 27.944444
| 76
| 0.648111
|
[
"MIT"
] |
AccedeLtd/eShopOnWeb
|
src/Web/API/CustomSchemaFilters.cs
| 505
|
C#
|
namespace Macabresoft.Macabre2D.Framework;
using System;
using Microsoft.Xna.Framework;
/// <summary>
/// Wraps a <see cref="GameTime" /> to provide seconds passed in regards to a predefined game speed.
/// </summary>
public struct FrameTime {
/// <summary>
/// A <see cref="FrameTime" /> without any time passed.
/// </summary>
public static readonly FrameTime Zero = new();
/// <summary>
/// The frame time span. This represents the time that has passed since the last frame.
/// </summary>
public readonly TimeSpan FrameTimeSpan;
/// <summary>
/// A value indicating whether or not this is running slowly.
/// </summary>
public readonly bool IsRunningSlowly;
/// <summary>
/// The milliseconds passed with game speed accounted for.
/// </summary>
public readonly double MillisecondsPassed;
/// <summary>
/// The seconds passed with game speed accounted for.
/// </summary>
public readonly double SecondsPassed;
/// <summary>
/// The total time span. This represents the total time that has passed since running.
/// </summary>
public readonly TimeSpan TotalTimeSpan;
/// <summary>
/// Initializes a new instance of the <see cref="FrameTime" /> struct.
/// </summary>
/// <param name="gameTime">The game time.</param>
/// <param name="gameSpeed">The game speed.</param>
public FrameTime(GameTime gameTime, double gameSpeed) {
this.IsRunningSlowly = gameTime.IsRunningSlowly;
this.FrameTimeSpan = gameTime.ElapsedGameTime;
this.TotalTimeSpan = gameTime.TotalGameTime;
this.SecondsPassed = this.FrameTimeSpan.TotalSeconds * gameSpeed;
this.MillisecondsPassed = this.FrameTimeSpan.TotalMilliseconds * gameSpeed;
}
/// <summary>
/// Initializes a new instance of the <see cref="FrameTime" /> struct.
/// </summary>
public FrameTime() {
this.IsRunningSlowly = false;
this.FrameTimeSpan = TimeSpan.Zero;
this.TotalTimeSpan = TimeSpan.Zero;
this.SecondsPassed = 0;
this.MillisecondsPassed = 0;
}
}
| 33.730159
| 100
| 0.660235
|
[
"MIT"
] |
BrettStory/Macabre2D
|
Framework/Time/FrameTime.cs
| 2,125
|
C#
|
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.Management.ContainerService.Models
{
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// Agent Pool.
/// </summary>
[Rest.Serialization.JsonTransformation]
public partial class AgentPool : SubResource
{
/// <summary>
/// Initializes a new instance of the AgentPool class.
/// </summary>
public AgentPool()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the AgentPool class.
/// </summary>
/// <param name="id">Resource ID.</param>
/// <param name="name">The name of the resource that is unique within a
/// resource group. This name can be used to access the
/// resource.</param>
/// <param name="type">Resource type</param>
/// <param name="count">Number of agents (VMs) to host docker
/// containers. Allowed values must be in the range of 0 to 1000
/// (inclusive) for user pools and in the range of 1 to 1000
/// (inclusive) for system pools. The default value is 1.</param>
/// <param name="vmSize">The size of the agent pool VMs.</param>
/// <param name="osDiskType">Possible values include: 'Managed',
/// 'Ephemeral'</param>
/// <param name="kubeletDiskType">Possible values include: 'OS',
/// 'Temporary'</param>
/// <param name="vnetSubnetID">The ID of the subnet which agent pool
/// nodes and optionally pods will join on startup.</param>
/// <param name="podSubnetID">The ID of the subnet which pods will join
/// when launched.</param>
/// <param name="maxPods">The maximum number of pods that can run on a
/// node.</param>
/// <param name="osType">Possible values include: 'Linux',
/// 'Windows'</param>
/// <param name="osSKU">Possible values include: 'Ubuntu',
/// 'CBLMariner'</param>
/// <param name="maxCount">The maximum number of nodes for
/// auto-scaling</param>
/// <param name="minCount">The minimum number of nodes for
/// auto-scaling</param>
/// <param name="enableAutoScaling">Whether to enable
/// auto-scaler</param>
/// <param name="scaleDownMode">The scale down mode to use when scaling
/// the Agent Pool.</param>
/// <param name="agentPoolType">Possible values include:
/// 'VirtualMachineScaleSets', 'AvailabilitySet'</param>
/// <param name="mode">Possible values include: 'System',
/// 'User'</param>
/// <param name="orchestratorVersion">The version of Kubernetes running
/// on the Agent Pool.</param>
/// <param name="nodeImageVersion">The version of node image</param>
/// <param name="upgradeSettings">Settings for upgrading the
/// agentpool</param>
/// <param name="provisioningState">The current deployment or
/// provisioning state.</param>
/// <param name="powerState">Describes whether the Agent Pool is
/// Running or Stopped</param>
/// <param name="availabilityZones">The list of Availability zones to
/// use for nodes. This can only be specified if the AgentPoolType
/// property is 'VirtualMachineScaleSets'.</param>
/// <param name="enableNodePublicIP">Whether each node is allocated its
/// own public IP.</param>
/// <param name="nodePublicIPPrefixID">The public IP prefix ID which VM
/// nodes should use IPs from.</param>
/// <param name="scaleSetPriority">The Virtual Machine Scale Set
/// priority. If not specified, the default is 'Regular'. Possible
/// values include: 'Spot', 'Regular'</param>
/// <param name="scaleSetEvictionPolicy">The Virtual Machine Scale Set
/// eviction policy to use.</param>
/// <param name="spotMaxPrice">The max price (in US Dollars) you are
/// willing to pay for spot instances. Possible values are any decimal
/// value greater than zero or -1 which indicates default price to be
/// up-to on-demand.</param>
/// <param name="tags">The tags to be persisted on the agent pool
/// virtual machine scale set.</param>
/// <param name="nodeLabels">The node labels to be persisted across all
/// nodes in agent pool.</param>
/// <param name="nodeTaints">The taints added to new nodes during node
/// pool create and scale. For example, key=value:NoSchedule.</param>
/// <param name="proximityPlacementGroupID">The ID for Proximity
/// Placement Group.</param>
/// <param name="kubeletConfig">The Kubelet configuration on the agent
/// pool nodes.</param>
/// <param name="linuxOSConfig">The OS configuration of Linux agent
/// nodes.</param>
/// <param name="enableEncryptionAtHost">Whether to enable host based
/// OS and data drive encryption.</param>
/// <param name="enableUltraSSD">Whether to enable UltraSSD</param>
/// <param name="enableFIPS">Whether to use a FIPS-enabled OS.</param>
/// <param name="gpuInstanceProfile">GPUInstanceProfile to be used to
/// specify GPU MIG instance profile for supported GPU VM SKU. Possible
/// values include: 'MIG1g', 'MIG2g', 'MIG3g', 'MIG4g', 'MIG7g'</param>
public AgentPool(string id = default(string), string name = default(string), string type = default(string), int? count = default(int?), string vmSize = default(string), int? osDiskSizeGB = default(int?), string osDiskType = default(string), string kubeletDiskType = default(string), string vnetSubnetID = default(string), string podSubnetID = default(string), int? maxPods = default(int?), string osType = default(string), string osSKU = default(string), int? maxCount = default(int?), int? minCount = default(int?), bool? enableAutoScaling = default(bool?), string scaleDownMode = default(string), string agentPoolType = default(string), string mode = default(string), string orchestratorVersion = default(string), string nodeImageVersion = default(string), AgentPoolUpgradeSettings upgradeSettings = default(AgentPoolUpgradeSettings), string provisioningState = default(string), PowerState powerState = default(PowerState), IList<string> availabilityZones = default(IList<string>), bool? enableNodePublicIP = default(bool?), string nodePublicIPPrefixID = default(string), string scaleSetPriority = default(string), string scaleSetEvictionPolicy = default(string), double? spotMaxPrice = default(double?), IDictionary<string, string> tags = default(IDictionary<string, string>), IDictionary<string, string> nodeLabels = default(IDictionary<string, string>), IList<string> nodeTaints = default(IList<string>), string proximityPlacementGroupID = default(string), KubeletConfig kubeletConfig = default(KubeletConfig), LinuxOSConfig linuxOSConfig = default(LinuxOSConfig), bool? enableEncryptionAtHost = default(bool?), bool? enableUltraSSD = default(bool?), bool? enableFIPS = default(bool?), string gpuInstanceProfile = default(string))
: base(id, name, type)
{
Count = count;
VmSize = vmSize;
OsDiskSizeGB = osDiskSizeGB;
OsDiskType = osDiskType;
KubeletDiskType = kubeletDiskType;
VnetSubnetID = vnetSubnetID;
PodSubnetID = podSubnetID;
MaxPods = maxPods;
OsType = osType;
OsSKU = osSKU;
MaxCount = maxCount;
MinCount = minCount;
EnableAutoScaling = enableAutoScaling;
ScaleDownMode = scaleDownMode;
AgentPoolType = agentPoolType;
Mode = mode;
OrchestratorVersion = orchestratorVersion;
NodeImageVersion = nodeImageVersion;
UpgradeSettings = upgradeSettings;
ProvisioningState = provisioningState;
PowerState = powerState;
AvailabilityZones = availabilityZones;
EnableNodePublicIP = enableNodePublicIP;
NodePublicIPPrefixID = nodePublicIPPrefixID;
ScaleSetPriority = scaleSetPriority;
ScaleSetEvictionPolicy = scaleSetEvictionPolicy;
SpotMaxPrice = spotMaxPrice;
Tags = tags;
NodeLabels = nodeLabels;
NodeTaints = nodeTaints;
ProximityPlacementGroupID = proximityPlacementGroupID;
KubeletConfig = kubeletConfig;
LinuxOSConfig = linuxOSConfig;
EnableEncryptionAtHost = enableEncryptionAtHost;
EnableUltraSSD = enableUltraSSD;
EnableFIPS = enableFIPS;
GpuInstanceProfile = gpuInstanceProfile;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets number of agents (VMs) to host docker containers.
/// Allowed values must be in the range of 0 to 1000 (inclusive) for
/// user pools and in the range of 1 to 1000 (inclusive) for system
/// pools. The default value is 1.
/// </summary>
[JsonProperty(PropertyName = "properties.count")]
public int? Count { get; set; }
/// <summary>
/// Gets or sets the size of the agent pool VMs.
/// </summary>
/// <remarks>
/// VM size availability varies by region. If a node contains
/// insufficient compute resources (memory, cpu, etc) pods might fail
/// to run correctly. For more details on restricted VM sizes, see:
/// https://docs.microsoft.com/azure/aks/quotas-skus-regions
/// </remarks>
[JsonProperty(PropertyName = "properties.vmSize")]
public string VmSize { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "properties.osDiskSizeGB")]
public int? OsDiskSizeGB { get; set; }
/// <summary>
/// Gets or sets possible values include: 'Managed', 'Ephemeral'
/// </summary>
[JsonProperty(PropertyName = "properties.osDiskType")]
public string OsDiskType { get; set; }
/// <summary>
/// Gets or sets possible values include: 'OS', 'Temporary'
/// </summary>
[JsonProperty(PropertyName = "properties.kubeletDiskType")]
public string KubeletDiskType { get; set; }
/// <summary>
/// Gets or sets the ID of the subnet which agent pool nodes and
/// optionally pods will join on startup.
/// </summary>
/// <remarks>
/// If this is not specified, a VNET and subnet will be generated and
/// used. If no podSubnetID is specified, this applies to nodes and
/// pods, otherwise it applies to just nodes. This is of the form:
/// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/subnets/{subnetName}
/// </remarks>
[JsonProperty(PropertyName = "properties.vnetSubnetID")]
public string VnetSubnetID { get; set; }
/// <summary>
/// Gets or sets the ID of the subnet which pods will join when
/// launched.
/// </summary>
/// <remarks>
/// If omitted, pod IPs are statically assigned on the node subnet (see
/// vnetSubnetID for more details). This is of the form:
/// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/subnets/{subnetName}
/// </remarks>
[JsonProperty(PropertyName = "properties.podSubnetID")]
public string PodSubnetID { get; set; }
/// <summary>
/// Gets or sets the maximum number of pods that can run on a node.
/// </summary>
[JsonProperty(PropertyName = "properties.maxPods")]
public int? MaxPods { get; set; }
/// <summary>
/// Gets or sets possible values include: 'Linux', 'Windows'
/// </summary>
[JsonProperty(PropertyName = "properties.osType")]
public string OsType { get; set; }
/// <summary>
/// Gets or sets possible values include: 'Ubuntu', 'CBLMariner'
/// </summary>
[JsonProperty(PropertyName = "properties.osSKU")]
public string OsSKU { get; set; }
/// <summary>
/// Gets or sets the maximum number of nodes for auto-scaling
/// </summary>
[JsonProperty(PropertyName = "properties.maxCount")]
public int? MaxCount { get; set; }
/// <summary>
/// Gets or sets the minimum number of nodes for auto-scaling
/// </summary>
[JsonProperty(PropertyName = "properties.minCount")]
public int? MinCount { get; set; }
/// <summary>
/// Gets or sets whether to enable auto-scaler
/// </summary>
[JsonProperty(PropertyName = "properties.enableAutoScaling")]
public bool? EnableAutoScaling { get; set; }
/// <summary>
/// Gets or sets the scale down mode to use when scaling the Agent
/// Pool.
/// </summary>
/// <remarks>
/// This also effects the cluster autoscaler behavior. If not
/// specified, it defaults to Delete. Possible values include:
/// 'Delete', 'Deallocate'
/// </remarks>
[JsonProperty(PropertyName = "properties.scaleDownMode")]
public string ScaleDownMode { get; set; }
/// <summary>
/// Gets or sets possible values include: 'VirtualMachineScaleSets',
/// 'AvailabilitySet'
/// </summary>
[JsonProperty(PropertyName = "properties.type")]
public string AgentPoolType { get; set; }
/// <summary>
/// Gets or sets possible values include: 'System', 'User'
/// </summary>
[JsonProperty(PropertyName = "properties.mode")]
public string Mode { get; set; }
/// <summary>
/// Gets or sets the version of Kubernetes running on the Agent Pool.
/// </summary>
/// <remarks>
/// As a best practice, you should upgrade all node pools in an AKS
/// cluster to the same Kubernetes version. The node pool version must
/// have the same major version as the control plane. The node pool
/// minor version must be within two minor versions of the control
/// plane version. The node pool version cannot be greater than the
/// control plane version. For more information see [upgrading a node
/// pool](https://docs.microsoft.com/azure/aks/use-multiple-node-pools#upgrade-a-node-pool).
/// </remarks>
[JsonProperty(PropertyName = "properties.orchestratorVersion")]
public string OrchestratorVersion { get; set; }
/// <summary>
/// Gets the version of node image
/// </summary>
[JsonProperty(PropertyName = "properties.nodeImageVersion")]
public string NodeImageVersion { get; private set; }
/// <summary>
/// Gets or sets settings for upgrading the agentpool
/// </summary>
[JsonProperty(PropertyName = "properties.upgradeSettings")]
public AgentPoolUpgradeSettings UpgradeSettings { get; set; }
/// <summary>
/// Gets the current deployment or provisioning state.
/// </summary>
[JsonProperty(PropertyName = "properties.provisioningState")]
public string ProvisioningState { get; private set; }
/// <summary>
/// Gets describes whether the Agent Pool is Running or Stopped
/// </summary>
[JsonProperty(PropertyName = "properties.powerState")]
public PowerState PowerState { get; private set; }
/// <summary>
/// Gets or sets the list of Availability zones to use for nodes. This
/// can only be specified if the AgentPoolType property is
/// 'VirtualMachineScaleSets'.
/// </summary>
[JsonProperty(PropertyName = "properties.availabilityZones")]
public IList<string> AvailabilityZones { get; set; }
/// <summary>
/// Gets or sets whether each node is allocated its own public IP.
/// </summary>
/// <remarks>
/// Some scenarios may require nodes in a node pool to receive their
/// own dedicated public IP addresses. A common scenario is for gaming
/// workloads, where a console needs to make a direct connection to a
/// cloud virtual machine to minimize hops. For more information see
/// [assigning a public IP per
/// node](https://docs.microsoft.com/azure/aks/use-multiple-node-pools#assign-a-public-ip-per-node-for-your-node-pools).
/// The default is false.
/// </remarks>
[JsonProperty(PropertyName = "properties.enableNodePublicIP")]
public bool? EnableNodePublicIP { get; set; }
/// <summary>
/// Gets or sets the public IP prefix ID which VM nodes should use IPs
/// from.
/// </summary>
/// <remarks>
/// This is of the form:
/// /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPPrefixes/{publicIPPrefixName}
/// </remarks>
[JsonProperty(PropertyName = "properties.nodePublicIPPrefixID")]
public string NodePublicIPPrefixID { get; set; }
/// <summary>
/// Gets or sets the Virtual Machine Scale Set priority. If not
/// specified, the default is 'Regular'. Possible values include:
/// 'Spot', 'Regular'
/// </summary>
[JsonProperty(PropertyName = "properties.scaleSetPriority")]
public string ScaleSetPriority { get; set; }
/// <summary>
/// Gets or sets the Virtual Machine Scale Set eviction policy to use.
/// </summary>
/// <remarks>
/// This cannot be specified unless the scaleSetPriority is 'Spot'. If
/// not specified, the default is 'Delete'. Possible values include:
/// 'Delete', 'Deallocate'
/// </remarks>
[JsonProperty(PropertyName = "properties.scaleSetEvictionPolicy")]
public string ScaleSetEvictionPolicy { get; set; }
/// <summary>
/// Gets or sets the max price (in US Dollars) you are willing to pay
/// for spot instances. Possible values are any decimal value greater
/// than zero or -1 which indicates default price to be up-to
/// on-demand.
/// </summary>
/// <remarks>
/// Possible values are any decimal value greater than zero or -1 which
/// indicates the willingness to pay any on-demand price. For more
/// details on spot pricing, see [spot VMs
/// pricing](https://docs.microsoft.com/azure/virtual-machines/spot-vms#pricing)
/// </remarks>
[JsonProperty(PropertyName = "properties.spotMaxPrice")]
public double? SpotMaxPrice { get; set; }
/// <summary>
/// Gets or sets the tags to be persisted on the agent pool virtual
/// machine scale set.
/// </summary>
[JsonProperty(PropertyName = "properties.tags")]
public IDictionary<string, string> Tags { get; set; }
/// <summary>
/// Gets or sets the node labels to be persisted across all nodes in
/// agent pool.
/// </summary>
[JsonProperty(PropertyName = "properties.nodeLabels")]
public IDictionary<string, string> NodeLabels { get; set; }
/// <summary>
/// Gets or sets the taints added to new nodes during node pool create
/// and scale. For example, key=value:NoSchedule.
/// </summary>
[JsonProperty(PropertyName = "properties.nodeTaints")]
public IList<string> NodeTaints { get; set; }
/// <summary>
/// Gets or sets the ID for Proximity Placement Group.
/// </summary>
[JsonProperty(PropertyName = "properties.proximityPlacementGroupID")]
public string ProximityPlacementGroupID { get; set; }
/// <summary>
/// Gets or sets the Kubelet configuration on the agent pool nodes.
/// </summary>
[JsonProperty(PropertyName = "properties.kubeletConfig")]
public KubeletConfig KubeletConfig { get; set; }
/// <summary>
/// Gets or sets the OS configuration of Linux agent nodes.
/// </summary>
[JsonProperty(PropertyName = "properties.linuxOSConfig")]
public LinuxOSConfig LinuxOSConfig { get; set; }
/// <summary>
/// Gets or sets whether to enable host based OS and data drive
/// encryption.
/// </summary>
/// <remarks>
/// This is only supported on certain VM sizes and in certain Azure
/// regions. For more information, see:
/// https://docs.microsoft.com/azure/aks/enable-host-encryption
/// </remarks>
[JsonProperty(PropertyName = "properties.enableEncryptionAtHost")]
public bool? EnableEncryptionAtHost { get; set; }
/// <summary>
/// Gets or sets whether to enable UltraSSD
/// </summary>
[JsonProperty(PropertyName = "properties.enableUltraSSD")]
public bool? EnableUltraSSD { get; set; }
/// <summary>
/// Gets or sets whether to use a FIPS-enabled OS.
/// </summary>
/// <remarks>
/// See [Add a FIPS-enabled node
/// pool](https://docs.microsoft.com/azure/aks/use-multiple-node-pools#add-a-fips-enabled-node-pool-preview)
/// for more details.
/// </remarks>
[JsonProperty(PropertyName = "properties.enableFIPS")]
public bool? EnableFIPS { get; set; }
/// <summary>
/// Gets or sets gPUInstanceProfile to be used to specify GPU MIG
/// instance profile for supported GPU VM SKU. Possible values include:
/// 'MIG1g', 'MIG2g', 'MIG3g', 'MIG4g', 'MIG7g'
/// </summary>
[JsonProperty(PropertyName = "properties.gpuInstanceProfile")]
public string GpuInstanceProfile { get; set; }
/// <summary>
/// Validate the object.
/// </summary>
/// <exception cref="ValidationException">
/// Thrown if validation fails
/// </exception>
public virtual void Validate()
{
if (KubeletConfig != null)
{
KubeletConfig.Validate();
}
}
}
}
| 47.671458
| 1,743
| 0.620176
|
[
"MIT"
] |
93mishra/azure-sdk-for-net
|
sdk/containerservice/Microsoft.Azure.Management.ContainerService/src/Generated/Models/AgentPool.cs
| 23,216
|
C#
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.Collections.Generic;
using Aliyun.Acs.Core.Transform;
using Aliyun.Acs.ddoscoo.Model.V20200101;
namespace Aliyun.Acs.ddoscoo.Transform.V20200101
{
public class DescribeDomainOverviewResponseUnmarshaller
{
public static DescribeDomainOverviewResponse Unmarshall(UnmarshallerContext _ctx)
{
DescribeDomainOverviewResponse describeDomainOverviewResponse = new DescribeDomainOverviewResponse();
describeDomainOverviewResponse.HttpResponse = _ctx.HttpResponse;
describeDomainOverviewResponse.RequestId = _ctx.StringValue("DescribeDomainOverview.RequestId");
describeDomainOverviewResponse.MaxHttps = _ctx.LongValue("DescribeDomainOverview.MaxHttps");
describeDomainOverviewResponse.MaxHttp = _ctx.LongValue("DescribeDomainOverview.MaxHttp");
return describeDomainOverviewResponse;
}
}
}
| 40.261905
| 105
| 0.775872
|
[
"Apache-2.0"
] |
AxiosCros/aliyun-openapi-net-sdk
|
aliyun-net-sdk-ddoscoo/Ddoscoo/Transform/V20200101/DescribeDomainOverviewResponseUnmarshaller.cs
| 1,691
|
C#
|
//
// Copyright (c) 2019-2020 Ryujinx
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
//
using Ryujinx.Audio.Renderer.Dsp.State;
using Ryujinx.Common.Memory;
using Ryujinx.Common.Utilities;
using System;
using System.Runtime.InteropServices;
namespace Ryujinx.Audio.Renderer.Common
{
/// <summary>
/// Represent the update state of a voice.
/// </summary>
/// <remarks>This is shared between the server and audio processor.</remarks>
[StructLayout(LayoutKind.Sequential, Pack = Align)]
public struct VoiceUpdateState
{
public const int Align = 0x10;
public const int BiquadStateOffset = 0x0;
public const int BiquadStateSize = 0x10;
/// <summary>
/// The state of the biquad filters of this voice.
/// </summary>
public Array2<BiquadFilterState> BiquadFilterState;
/// <summary>
/// The total amount of samples that was played.
/// </summary>
/// <remarks>This is reset to 0 when a <see cref="WaveBuffer"/> finishes playing and <see cref="WaveBuffer.IsEndOfStream"/> is set.</remarks>
/// <remarks>This is reset to 0 when looping while <see cref="Parameter.VoiceInParameter.DecodingBehaviour.PlayedSampleCountResetWhenLooping"/> is set.</remarks>
public ulong PlayedSampleCount;
/// <summary>
/// The current sample offset in the <see cref="WaveBuffer"/> pointed by <see cref="WaveBufferIndex"/>.
/// </summary>
public int Offset;
/// <summary>
/// The current index of the <see cref="WaveBuffer"/> in use.
/// </summary>
public uint WaveBufferIndex;
private WaveBufferValidArray _isWaveBufferValid;
/// <summary>
/// The total amount of <see cref="WaveBuffer"/> consumed.
/// </summary>
public uint WaveBufferConsumed;
/// <summary>
/// Pitch used for Sample Rate Conversion.
/// </summary>
public Array8<short> Pitch;
public float Fraction;
/// <summary>
/// The ADPCM loop context when <see cref="SampleFormat.Adpcm"/> is in use.
/// </summary>
public AdpcmLoopContext LoopContext;
/// <summary>
/// The last samples after a mix ramp.
/// </summary>
/// <remarks>This is used for depop (to perform voice drop).</remarks>
public Array24<float> LastSamples;
/// <summary>
/// The current count of loop performed.
/// </summary>
public int LoopCount;
[StructLayout(LayoutKind.Sequential, Size = 1 * RendererConstants.VoiceWaveBufferCount, Pack = 1)]
private struct WaveBufferValidArray { }
/// <summary>
/// Contains information of <see cref="WaveBuffer"/> validity.
/// </summary>
public Span<bool> IsWaveBufferValid => SpanHelpers.AsSpan<WaveBufferValidArray, bool>(ref _isWaveBufferValid);
/// <summary>
/// Mark the current <see cref="WaveBuffer"/> as played and switch to the next one.
/// </summary>
/// <param name="waveBuffer">The current <see cref="WaveBuffer"/></param>
/// <param name="waveBufferIndex">The wavebuffer index.</param>
/// <param name="waveBufferConsumed">The amount of wavebuffers consumed.</param>
/// <param name="playedSampleCount">The total count of sample played.</param>
public void MarkEndOfBufferWaveBufferProcessing(ref WaveBuffer waveBuffer, ref int waveBufferIndex, ref uint waveBufferConsumed, ref ulong playedSampleCount)
{
IsWaveBufferValid[waveBufferIndex++] = false;
LoopCount = 0;
waveBufferConsumed++;
if (waveBufferIndex >= RendererConstants.VoiceWaveBufferCount)
{
waveBufferIndex = 0;
}
if (waveBuffer.IsEndOfStream)
{
playedSampleCount = 0;
}
}
}
}
| 37.622951
| 169
| 0.636601
|
[
"MIT"
] |
AkechiShiro/Ryujinx
|
Ryujinx.Audio.Renderer/Common/VoiceUpdateState.cs
| 4,590
|
C#
|
using Accounting.Application.Common.Interfaces;
using FluentValidation;
using Microsoft.EntityFrameworkCore;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Accounting.Application.DetailAccounts.Commands.CreateCommand
{
public class CreateDetailAccountCommandValidator : AbstractValidator<CreateDetailAccountCommand>
{
private readonly IApplicationDbContext _context;
public CreateDetailAccountCommandValidator(IApplicationDbContext context)
{
this._context = context;
RuleFor(v => v.DetailAccountIdByCustomer)
.NotEmpty().WithMessage("Detail Account Id can't be empty")
.GreaterThan(0).WithMessage("Detail Account Id can't Zero or negative");
RuleFor(v => v.DetailAccountNameAr)
.NotEmpty().WithMessage("Detail Account Name (Ar) can't be empty")
.MaximumLength(250).WithMessage("Detail Account Name (Ar) can't exceed 250 characters");
RuleFor(v => v.DetailAccountNameEn)
.MaximumLength(250).WithMessage("Detail Account Name (En) can't exceed 250 characters");
RuleFor(v => v.CustomerId)
.NotEmpty().WithMessage("Customer Id can't be null")
.MustAsync(BeExistCustomer).WithMessage("Invalid Customer");
RuleFor(v => v.TotalAccountId)
.NotEmpty().WithMessage("Detail Account must belong to Total Account")
.MustAsync(BeExistGLForThisCustomer).WithMessage("The Main account not defined for this customer");
}
private async Task<bool> BeExistGLForThisCustomer(CreateDetailAccountCommand command, Guid mainAccountId, CancellationToken cancellationToken)
{
var result = await _context.TotalAccounts.AnyAsync(m => m.CustomerId == command.CustomerId && m.Id == mainAccountId && m.IsActive);
return result;
}
private async Task<bool> BeExistCustomer(Guid customerId, CancellationToken cancellationToken)
{
var result = await _context.Customers.AnyAsync(c => c.Id == customerId);
return result;
}
}
}
| 42.803922
| 150
| 0.673843
|
[
"MIT"
] |
shadi-alhaj/Accounting
|
src/Application/DetailAccounts/Commands/CreateCommand/CreateDetailAccountCommandValidator.cs
| 2,185
|
C#
|
//File automatically generated using robotdotnet-tools. Please do not modify.
using System;
using System.Runtime.InteropServices;
// ReSharper disable CheckNamespace
namespace HAL.Base
{
public partial class HALCanTalonSRX
{
static HALCanTalonSRX()
{
HAL.Initialize();
}
public delegate IntPtr C_TalonSRX_Create3Delegate(int deviceNumber, int controlPeriodMs, int enablePeriodMs);
public static C_TalonSRX_Create3Delegate C_TalonSRX_Create3;
public delegate void C_TalonSRX_DestroyDelegate(IntPtr handle);
public static C_TalonSRX_DestroyDelegate C_TalonSRX_Destroy;
public delegate void C_TalonSRX_SetDelegate(IntPtr handle, double value);
public static C_TalonSRX_SetDelegate C_TalonSRX_Set;
public delegate CTR_Code C_TalonSRX_SetParamDelegate(IntPtr handle, int paramEnum, double value);
public static C_TalonSRX_SetParamDelegate C_TalonSRX_SetParam;
public delegate CTR_Code C_TalonSRX_RequestParamDelegate(IntPtr handle, int paramEnum);
public static C_TalonSRX_RequestParamDelegate C_TalonSRX_RequestParam;
public delegate CTR_Code C_TalonSRX_GetParamResponseDelegate(IntPtr handle, int paramEnum, ref double value);
public static C_TalonSRX_GetParamResponseDelegate C_TalonSRX_GetParamResponse;
public delegate CTR_Code C_TalonSRX_GetParamResponseInt32Delegate(IntPtr handle, int paramEnum, ref int value);
public static C_TalonSRX_GetParamResponseInt32Delegate C_TalonSRX_GetParamResponseInt32;
public delegate CTR_Code C_TalonSRX_SetPgainDelegate(IntPtr handle, int slotIdx, double gain);
public static C_TalonSRX_SetPgainDelegate C_TalonSRX_SetPgain;
public delegate CTR_Code C_TalonSRX_SetIgainDelegate(IntPtr handle, int slotIdx, double gain);
public static C_TalonSRX_SetIgainDelegate C_TalonSRX_SetIgain;
public delegate CTR_Code C_TalonSRX_SetDgainDelegate(IntPtr handle, int slotIdx, double gain);
public static C_TalonSRX_SetDgainDelegate C_TalonSRX_SetDgain;
public delegate CTR_Code C_TalonSRX_SetFgainDelegate(IntPtr handle, int slotIdx, double gain);
public static C_TalonSRX_SetFgainDelegate C_TalonSRX_SetFgain;
public delegate CTR_Code C_TalonSRX_SetIzoneDelegate(IntPtr handle, int slotIdx, int zone);
public static C_TalonSRX_SetIzoneDelegate C_TalonSRX_SetIzone;
public delegate CTR_Code C_TalonSRX_SetCloseLoopRampRateDelegate(IntPtr handle, int slotIdx, int closeLoopRampRate);
public static C_TalonSRX_SetCloseLoopRampRateDelegate C_TalonSRX_SetCloseLoopRampRate;
public delegate CTR_Code C_TalonSRX_SetVoltageCompensationRateDelegate(IntPtr handle, double voltagePerMs);
public static C_TalonSRX_SetVoltageCompensationRateDelegate C_TalonSRX_SetVoltageCompensationRate;
public delegate CTR_Code C_TalonSRX_SetSensorPositionDelegate(IntPtr handle, int pos);
public static C_TalonSRX_SetSensorPositionDelegate C_TalonSRX_SetSensorPosition;
public delegate CTR_Code C_TalonSRX_SetForwardSoftLimitDelegate(IntPtr handle, int forwardLimit);
public static C_TalonSRX_SetForwardSoftLimitDelegate C_TalonSRX_SetForwardSoftLimit;
public delegate CTR_Code C_TalonSRX_SetReverseSoftLimitDelegate(IntPtr handle, int reverseLimit);
public static C_TalonSRX_SetReverseSoftLimitDelegate C_TalonSRX_SetReverseSoftLimit;
public delegate CTR_Code C_TalonSRX_SetForwardSoftEnableDelegate(IntPtr handle, int enable);
public static C_TalonSRX_SetForwardSoftEnableDelegate C_TalonSRX_SetForwardSoftEnable;
public delegate CTR_Code C_TalonSRX_SetReverseSoftEnableDelegate(IntPtr handle, int enable);
public static C_TalonSRX_SetReverseSoftEnableDelegate C_TalonSRX_SetReverseSoftEnable;
public delegate CTR_Code C_TalonSRX_GetPgainDelegate(IntPtr handle, int slotIdx, ref double gain);
public static C_TalonSRX_GetPgainDelegate C_TalonSRX_GetPgain;
public delegate CTR_Code C_TalonSRX_GetIgainDelegate(IntPtr handle, int slotIdx, ref double gain);
public static C_TalonSRX_GetIgainDelegate C_TalonSRX_GetIgain;
public delegate CTR_Code C_TalonSRX_GetDgainDelegate(IntPtr handle, int slotIdx, ref double gain);
public static C_TalonSRX_GetDgainDelegate C_TalonSRX_GetDgain;
public delegate CTR_Code C_TalonSRX_GetFgainDelegate(IntPtr handle, int slotIdx, ref double gain);
public static C_TalonSRX_GetFgainDelegate C_TalonSRX_GetFgain;
public delegate CTR_Code C_TalonSRX_GetIzoneDelegate(IntPtr handle, int slotIdx, ref int zone);
public static C_TalonSRX_GetIzoneDelegate C_TalonSRX_GetIzone;
public delegate CTR_Code C_TalonSRX_GetCloseLoopRampRateDelegate(IntPtr handle, int slotIdx, ref int closeLoopRampRate);
public static C_TalonSRX_GetCloseLoopRampRateDelegate C_TalonSRX_GetCloseLoopRampRate;
public delegate CTR_Code C_TalonSRX_GetVoltageCompensationRateDelegate(IntPtr handle, ref double voltagePerMs);
public static C_TalonSRX_GetVoltageCompensationRateDelegate C_TalonSRX_GetVoltageCompensationRate;
public delegate CTR_Code C_TalonSRX_GetForwardSoftLimitDelegate(IntPtr handle, ref int forwardLimit);
public static C_TalonSRX_GetForwardSoftLimitDelegate C_TalonSRX_GetForwardSoftLimit;
public delegate CTR_Code C_TalonSRX_GetReverseSoftLimitDelegate(IntPtr handle, ref int reverseLimit);
public static C_TalonSRX_GetReverseSoftLimitDelegate C_TalonSRX_GetReverseSoftLimit;
public delegate CTR_Code C_TalonSRX_GetForwardSoftEnableDelegate(IntPtr handle, ref int enable);
public static C_TalonSRX_GetForwardSoftEnableDelegate C_TalonSRX_GetForwardSoftEnable;
public delegate CTR_Code C_TalonSRX_GetReverseSoftEnableDelegate(IntPtr handle, ref int enable);
public static C_TalonSRX_GetReverseSoftEnableDelegate C_TalonSRX_GetReverseSoftEnable;
public delegate CTR_Code C_TalonSRX_GetPulseWidthRiseToFallUsDelegate(IntPtr handle, ref int param);
public static C_TalonSRX_GetPulseWidthRiseToFallUsDelegate C_TalonSRX_GetPulseWidthRiseToFallUs;
public delegate CTR_Code C_TalonSRX_IsPulseWidthSensorPresentDelegate(IntPtr handle, ref int param);
public static C_TalonSRX_IsPulseWidthSensorPresentDelegate C_TalonSRX_IsPulseWidthSensorPresent;
public delegate CTR_Code C_TalonSRX_SetModeSelect2Delegate(IntPtr handle, int modeSelect, int demand);
public static C_TalonSRX_SetModeSelect2Delegate C_TalonSRX_SetModeSelect2;
public delegate CTR_Code C_TalonSRX_SetStatusFrameRateDelegate(IntPtr handle, int frameEnum, int periodMs);
public static C_TalonSRX_SetStatusFrameRateDelegate C_TalonSRX_SetStatusFrameRate;
public delegate CTR_Code C_TalonSRX_ClearStickyFaultsDelegate(IntPtr handle);
public static C_TalonSRX_ClearStickyFaultsDelegate C_TalonSRX_ClearStickyFaults;
public delegate void C_TalonSRX_ChangeMotionControlFramePeriodDelegate(IntPtr handle, int periodMs);
public static C_TalonSRX_ChangeMotionControlFramePeriodDelegate C_TalonSRX_ChangeMotionControlFramePeriod;
public delegate void C_TalonSRX_ClearMotionProfileTrajectoriesDelegate(IntPtr handle);
public static C_TalonSRX_ClearMotionProfileTrajectoriesDelegate C_TalonSRX_ClearMotionProfileTrajectories;
public delegate int C_TalonSRX_GetMotionProfileTopLevelBufferCountDelegate(IntPtr handle);
public static C_TalonSRX_GetMotionProfileTopLevelBufferCountDelegate C_TalonSRX_GetMotionProfileTopLevelBufferCount;
public delegate int C_TalonSRX_IsMotionProfileTopLevelBufferFullDelegate(IntPtr handle);
public static C_TalonSRX_IsMotionProfileTopLevelBufferFullDelegate C_TalonSRX_IsMotionProfileTopLevelBufferFull;
public delegate CTR_Code C_TalonSRX_PushMotionProfileTrajectoryDelegate(IntPtr handle, int targPos, int targVel, int profileSlotSelect, int timeDurMs, int velOnly, int isLastPoint, int zeroPos);
public static C_TalonSRX_PushMotionProfileTrajectoryDelegate C_TalonSRX_PushMotionProfileTrajectory;
public delegate void C_TalonSRX_ProcessMotionProfileBufferDelegate(IntPtr handle);
public static C_TalonSRX_ProcessMotionProfileBufferDelegate C_TalonSRX_ProcessMotionProfileBuffer;
public delegate CTR_Code C_TalonSRX_GetMotionProfileStatusDelegate(IntPtr handle, ref int flags, ref int profileSlotSelect, ref int targPos, ref int targVel, ref int topBufferRemaining, ref int topBufferCnt, ref int btmBufferCnt, ref int outputEnable);
public static C_TalonSRX_GetMotionProfileStatusDelegate C_TalonSRX_GetMotionProfileStatus;
public delegate CTR_Code C_TalonSRX_GetFault_OverTempDelegate(IntPtr handle, ref int param);
public static C_TalonSRX_GetFault_OverTempDelegate C_TalonSRX_GetFault_OverTemp;
public delegate CTR_Code C_TalonSRX_GetFault_UnderVoltageDelegate(IntPtr handle, ref int param);
public static C_TalonSRX_GetFault_UnderVoltageDelegate C_TalonSRX_GetFault_UnderVoltage;
public delegate CTR_Code C_TalonSRX_GetFault_ForLimDelegate(IntPtr handle, ref int param);
public static C_TalonSRX_GetFault_ForLimDelegate C_TalonSRX_GetFault_ForLim;
public delegate CTR_Code C_TalonSRX_GetFault_RevLimDelegate(IntPtr handle, ref int param);
public static C_TalonSRX_GetFault_RevLimDelegate C_TalonSRX_GetFault_RevLim;
public delegate CTR_Code C_TalonSRX_GetFault_HardwareFailureDelegate(IntPtr handle, ref int param);
public static C_TalonSRX_GetFault_HardwareFailureDelegate C_TalonSRX_GetFault_HardwareFailure;
public delegate CTR_Code C_TalonSRX_GetFault_ForSoftLimDelegate(IntPtr handle, ref int param);
public static C_TalonSRX_GetFault_ForSoftLimDelegate C_TalonSRX_GetFault_ForSoftLim;
public delegate CTR_Code C_TalonSRX_GetFault_RevSoftLimDelegate(IntPtr handle, ref int param);
public static C_TalonSRX_GetFault_RevSoftLimDelegate C_TalonSRX_GetFault_RevSoftLim;
public delegate CTR_Code C_TalonSRX_GetStckyFault_OverTempDelegate(IntPtr handle, ref int param);
public static C_TalonSRX_GetStckyFault_OverTempDelegate C_TalonSRX_GetStckyFault_OverTemp;
public delegate CTR_Code C_TalonSRX_GetStckyFault_UnderVoltageDelegate(IntPtr handle, ref int param);
public static C_TalonSRX_GetStckyFault_UnderVoltageDelegate C_TalonSRX_GetStckyFault_UnderVoltage;
public delegate CTR_Code C_TalonSRX_GetStckyFault_ForLimDelegate(IntPtr handle, ref int param);
public static C_TalonSRX_GetStckyFault_ForLimDelegate C_TalonSRX_GetStckyFault_ForLim;
public delegate CTR_Code C_TalonSRX_GetStckyFault_RevLimDelegate(IntPtr handle, ref int param);
public static C_TalonSRX_GetStckyFault_RevLimDelegate C_TalonSRX_GetStckyFault_RevLim;
public delegate CTR_Code C_TalonSRX_GetStckyFault_ForSoftLimDelegate(IntPtr handle, ref int param);
public static C_TalonSRX_GetStckyFault_ForSoftLimDelegate C_TalonSRX_GetStckyFault_ForSoftLim;
public delegate CTR_Code C_TalonSRX_GetStckyFault_RevSoftLimDelegate(IntPtr handle, ref int param);
public static C_TalonSRX_GetStckyFault_RevSoftLimDelegate C_TalonSRX_GetStckyFault_RevSoftLim;
public delegate CTR_Code C_TalonSRX_GetAppliedThrottleDelegate(IntPtr handle, ref int param);
public static C_TalonSRX_GetAppliedThrottleDelegate C_TalonSRX_GetAppliedThrottle;
public delegate CTR_Code C_TalonSRX_GetCloseLoopErrDelegate(IntPtr handle, ref int param);
public static C_TalonSRX_GetCloseLoopErrDelegate C_TalonSRX_GetCloseLoopErr;
public delegate CTR_Code C_TalonSRX_GetFeedbackDeviceSelectDelegate(IntPtr handle, ref int param);
public static C_TalonSRX_GetFeedbackDeviceSelectDelegate C_TalonSRX_GetFeedbackDeviceSelect;
public delegate CTR_Code C_TalonSRX_GetModeSelectDelegate(IntPtr handle, ref int param);
public static C_TalonSRX_GetModeSelectDelegate C_TalonSRX_GetModeSelect;
public delegate CTR_Code C_TalonSRX_GetLimitSwitchEnDelegate(IntPtr handle, ref int param);
public static C_TalonSRX_GetLimitSwitchEnDelegate C_TalonSRX_GetLimitSwitchEn;
public delegate CTR_Code C_TalonSRX_GetLimitSwitchClosedForDelegate(IntPtr handle, ref int param);
public static C_TalonSRX_GetLimitSwitchClosedForDelegate C_TalonSRX_GetLimitSwitchClosedFor;
public delegate CTR_Code C_TalonSRX_GetLimitSwitchClosedRevDelegate(IntPtr handle, ref int param);
public static C_TalonSRX_GetLimitSwitchClosedRevDelegate C_TalonSRX_GetLimitSwitchClosedRev;
public delegate CTR_Code C_TalonSRX_GetSensorPositionDelegate(IntPtr handle, ref int param);
public static C_TalonSRX_GetSensorPositionDelegate C_TalonSRX_GetSensorPosition;
public delegate CTR_Code C_TalonSRX_GetSensorVelocityDelegate(IntPtr handle, ref int param);
public static C_TalonSRX_GetSensorVelocityDelegate C_TalonSRX_GetSensorVelocity;
public delegate CTR_Code C_TalonSRX_GetCurrentDelegate(IntPtr handle, ref double param);
public static C_TalonSRX_GetCurrentDelegate C_TalonSRX_GetCurrent;
public delegate CTR_Code C_TalonSRX_GetBrakeIsEnabledDelegate(IntPtr handle, ref int param);
public static C_TalonSRX_GetBrakeIsEnabledDelegate C_TalonSRX_GetBrakeIsEnabled;
public delegate CTR_Code C_TalonSRX_GetEncPositionDelegate(IntPtr handle, ref int param);
public static C_TalonSRX_GetEncPositionDelegate C_TalonSRX_GetEncPosition;
public delegate CTR_Code C_TalonSRX_GetEncVelDelegate(IntPtr handle, ref int param);
public static C_TalonSRX_GetEncVelDelegate C_TalonSRX_GetEncVel;
public delegate CTR_Code C_TalonSRX_GetEncIndexRiseEventsDelegate(IntPtr handle, ref int param);
public static C_TalonSRX_GetEncIndexRiseEventsDelegate C_TalonSRX_GetEncIndexRiseEvents;
public delegate CTR_Code C_TalonSRX_GetQuadApinDelegate(IntPtr handle, ref int param);
public static C_TalonSRX_GetQuadApinDelegate C_TalonSRX_GetQuadApin;
public delegate CTR_Code C_TalonSRX_GetQuadBpinDelegate(IntPtr handle, ref int param);
public static C_TalonSRX_GetQuadBpinDelegate C_TalonSRX_GetQuadBpin;
public delegate CTR_Code C_TalonSRX_GetQuadIdxpinDelegate(IntPtr handle, ref int param);
public static C_TalonSRX_GetQuadIdxpinDelegate C_TalonSRX_GetQuadIdxpin;
public delegate CTR_Code C_TalonSRX_GetAnalogInWithOvDelegate(IntPtr handle, ref int param);
public static C_TalonSRX_GetAnalogInWithOvDelegate C_TalonSRX_GetAnalogInWithOv;
public delegate CTR_Code C_TalonSRX_GetAnalogInVelDelegate(IntPtr handle, ref int param);
public static C_TalonSRX_GetAnalogInVelDelegate C_TalonSRX_GetAnalogInVel;
public delegate CTR_Code C_TalonSRX_GetTempDelegate(IntPtr handle, ref double param);
public static C_TalonSRX_GetTempDelegate C_TalonSRX_GetTemp;
public delegate CTR_Code C_TalonSRX_GetBatteryVDelegate(IntPtr handle, ref double param);
public static C_TalonSRX_GetBatteryVDelegate C_TalonSRX_GetBatteryV;
public delegate CTR_Code C_TalonSRX_GetResetCountDelegate(IntPtr handle, ref int param);
public static C_TalonSRX_GetResetCountDelegate C_TalonSRX_GetResetCount;
public delegate CTR_Code C_TalonSRX_GetResetFlagsDelegate(IntPtr handle, ref int param);
public static C_TalonSRX_GetResetFlagsDelegate C_TalonSRX_GetResetFlags;
public delegate CTR_Code C_TalonSRX_GetFirmVersDelegate(IntPtr handle, ref int param);
public static C_TalonSRX_GetFirmVersDelegate C_TalonSRX_GetFirmVers;
public delegate CTR_Code C_TalonSRX_GetPulseWidthPositionDelegate(IntPtr handle, ref int param);
public static C_TalonSRX_GetPulseWidthPositionDelegate C_TalonSRX_GetPulseWidthPosition;
public delegate CTR_Code C_TalonSRX_GetPulseWidthVelocityDelegate(IntPtr handle, ref int param);
public static C_TalonSRX_GetPulseWidthVelocityDelegate C_TalonSRX_GetPulseWidthVelocity;
public delegate CTR_Code C_TalonSRX_GetPulseWidthRiseToRiseUsDelegate(IntPtr handle, ref int param);
public static C_TalonSRX_GetPulseWidthRiseToRiseUsDelegate C_TalonSRX_GetPulseWidthRiseToRiseUs;
public delegate CTR_Code C_TalonSRX_GetActTraj_IsValidDelegate(IntPtr handle, ref int param);
public static C_TalonSRX_GetActTraj_IsValidDelegate C_TalonSRX_GetActTraj_IsValid;
public delegate CTR_Code C_TalonSRX_GetActTraj_ProfileSlotSelectDelegate(IntPtr handle, ref int param);
public static C_TalonSRX_GetActTraj_ProfileSlotSelectDelegate C_TalonSRX_GetActTraj_ProfileSlotSelect;
public delegate CTR_Code C_TalonSRX_GetActTraj_VelOnlyDelegate(IntPtr handle, ref int param);
public static C_TalonSRX_GetActTraj_VelOnlyDelegate C_TalonSRX_GetActTraj_VelOnly;
public delegate CTR_Code C_TalonSRX_GetActTraj_IsLastDelegate(IntPtr handle, ref int param);
public static C_TalonSRX_GetActTraj_IsLastDelegate C_TalonSRX_GetActTraj_IsLast;
public delegate CTR_Code C_TalonSRX_GetOutputTypeDelegate(IntPtr handle, ref int param);
public static C_TalonSRX_GetOutputTypeDelegate C_TalonSRX_GetOutputType;
public delegate CTR_Code C_TalonSRX_GetHasUnderrunDelegate(IntPtr handle, ref int param);
public static C_TalonSRX_GetHasUnderrunDelegate C_TalonSRX_GetHasUnderrun;
public delegate CTR_Code C_TalonSRX_GetIsUnderrunDelegate(IntPtr handle, ref int param);
public static C_TalonSRX_GetIsUnderrunDelegate C_TalonSRX_GetIsUnderrun;
public delegate CTR_Code C_TalonSRX_GetNextIDDelegate(IntPtr handle, ref int param);
public static C_TalonSRX_GetNextIDDelegate C_TalonSRX_GetNextID;
public delegate CTR_Code C_TalonSRX_GetBufferIsFullDelegate(IntPtr handle, ref int param);
public static C_TalonSRX_GetBufferIsFullDelegate C_TalonSRX_GetBufferIsFull;
public delegate CTR_Code C_TalonSRX_GetCountDelegate(IntPtr handle, ref int param);
public static C_TalonSRX_GetCountDelegate C_TalonSRX_GetCount;
public delegate CTR_Code C_TalonSRX_GetActTraj_VelocityDelegate(IntPtr handle, ref int param);
public static C_TalonSRX_GetActTraj_VelocityDelegate C_TalonSRX_GetActTraj_Velocity;
public delegate CTR_Code C_TalonSRX_GetActTraj_PositionDelegate(IntPtr handle, ref int param);
public static C_TalonSRX_GetActTraj_PositionDelegate C_TalonSRX_GetActTraj_Position;
public delegate CTR_Code C_TalonSRX_SetDemandDelegate(IntPtr handle, int param);
public static C_TalonSRX_SetDemandDelegate C_TalonSRX_SetDemand;
public delegate CTR_Code C_TalonSRX_SetOverrideLimitSwitchEnDelegate(IntPtr handle, int param);
public static C_TalonSRX_SetOverrideLimitSwitchEnDelegate C_TalonSRX_SetOverrideLimitSwitchEn;
public delegate CTR_Code C_TalonSRX_SetFeedbackDeviceSelectDelegate(IntPtr handle, int param);
public static C_TalonSRX_SetFeedbackDeviceSelectDelegate C_TalonSRX_SetFeedbackDeviceSelect;
public delegate CTR_Code C_TalonSRX_SetRevMotDuringCloseLoopEnDelegate(IntPtr handle, int param);
public static C_TalonSRX_SetRevMotDuringCloseLoopEnDelegate C_TalonSRX_SetRevMotDuringCloseLoopEn;
public delegate CTR_Code C_TalonSRX_SetOverrideBrakeTypeDelegate(IntPtr handle, int param);
public static C_TalonSRX_SetOverrideBrakeTypeDelegate C_TalonSRX_SetOverrideBrakeType;
public delegate CTR_Code C_TalonSRX_SetModeSelectDelegate(IntPtr handle, int param);
public static C_TalonSRX_SetModeSelectDelegate C_TalonSRX_SetModeSelect;
public delegate CTR_Code C_TalonSRX_SetProfileSlotSelectDelegate(IntPtr handle, int param);
public static C_TalonSRX_SetProfileSlotSelectDelegate C_TalonSRX_SetProfileSlotSelect;
public delegate CTR_Code C_TalonSRX_SetRampThrottleDelegate(IntPtr handle, int param);
public static C_TalonSRX_SetRampThrottleDelegate C_TalonSRX_SetRampThrottle;
public delegate CTR_Code C_TalonSRX_SetRevFeedbackSensorDelegate(IntPtr handle, int param);
public static C_TalonSRX_SetRevFeedbackSensorDelegate C_TalonSRX_SetRevFeedbackSensor;
}
}
| 62.371951
| 260
| 0.821244
|
[
"MIT"
] |
Team-1922/OzWPILib.NET
|
HAL/Delegates/HALCanTalonSRXGenerated.cs
| 20,458
|
C#
|
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
/*
* Do not modify this file. This file is generated from the glue-2017-03-31.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.Glue.Model
{
/// <summary>
/// A classifier for custom <code>CSV</code> content.
/// </summary>
public partial class CsvClassifier
{
private bool? _allowSingleColumn;
private CsvHeaderOption _containsHeader;
private DateTime? _creationTime;
private string _delimiter;
private bool? _disableValueTrimming;
private List<string> _header = new List<string>();
private DateTime? _lastUpdated;
private string _name;
private string _quoteSymbol;
private long? _version;
/// <summary>
/// Gets and sets the property AllowSingleColumn.
/// <para>
/// Enables the processing of files that contain only one column.
/// </para>
/// </summary>
public bool AllowSingleColumn
{
get { return this._allowSingleColumn.GetValueOrDefault(); }
set { this._allowSingleColumn = value; }
}
// Check to see if AllowSingleColumn property is set
internal bool IsSetAllowSingleColumn()
{
return this._allowSingleColumn.HasValue;
}
/// <summary>
/// Gets and sets the property ContainsHeader.
/// <para>
/// Indicates whether the CSV file contains a header.
/// </para>
/// </summary>
public CsvHeaderOption ContainsHeader
{
get { return this._containsHeader; }
set { this._containsHeader = value; }
}
// Check to see if ContainsHeader property is set
internal bool IsSetContainsHeader()
{
return this._containsHeader != null;
}
/// <summary>
/// Gets and sets the property CreationTime.
/// <para>
/// The time that this classifier was registered.
/// </para>
/// </summary>
public DateTime CreationTime
{
get { return this._creationTime.GetValueOrDefault(); }
set { this._creationTime = value; }
}
// Check to see if CreationTime property is set
internal bool IsSetCreationTime()
{
return this._creationTime.HasValue;
}
/// <summary>
/// Gets and sets the property Delimiter.
/// <para>
/// A custom symbol to denote what separates each column entry in the row.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=1)]
public string Delimiter
{
get { return this._delimiter; }
set { this._delimiter = value; }
}
// Check to see if Delimiter property is set
internal bool IsSetDelimiter()
{
return this._delimiter != null;
}
/// <summary>
/// Gets and sets the property DisableValueTrimming.
/// <para>
/// Specifies not to trim values before identifying the type of column values. The default
/// value is <code>true</code>.
/// </para>
/// </summary>
public bool DisableValueTrimming
{
get { return this._disableValueTrimming.GetValueOrDefault(); }
set { this._disableValueTrimming = value; }
}
// Check to see if DisableValueTrimming property is set
internal bool IsSetDisableValueTrimming()
{
return this._disableValueTrimming.HasValue;
}
/// <summary>
/// Gets and sets the property Header.
/// <para>
/// A list of strings representing column names.
/// </para>
/// </summary>
public List<string> Header
{
get { return this._header; }
set { this._header = value; }
}
// Check to see if Header property is set
internal bool IsSetHeader()
{
return this._header != null && this._header.Count > 0;
}
/// <summary>
/// Gets and sets the property LastUpdated.
/// <para>
/// The time that this classifier was last updated.
/// </para>
/// </summary>
public DateTime LastUpdated
{
get { return this._lastUpdated.GetValueOrDefault(); }
set { this._lastUpdated = value; }
}
// Check to see if LastUpdated property is set
internal bool IsSetLastUpdated()
{
return this._lastUpdated.HasValue;
}
/// <summary>
/// Gets and sets the property Name.
/// <para>
/// The name of the classifier.
/// </para>
/// </summary>
[AWSProperty(Required=true, Min=1, Max=255)]
public string Name
{
get { return this._name; }
set { this._name = value; }
}
// Check to see if Name property is set
internal bool IsSetName()
{
return this._name != null;
}
/// <summary>
/// Gets and sets the property QuoteSymbol.
/// <para>
/// A custom symbol to denote what combines content into a single column value. It must
/// be different from the column delimiter.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=1)]
public string QuoteSymbol
{
get { return this._quoteSymbol; }
set { this._quoteSymbol = value; }
}
// Check to see if QuoteSymbol property is set
internal bool IsSetQuoteSymbol()
{
return this._quoteSymbol != null;
}
/// <summary>
/// Gets and sets the property Version.
/// <para>
/// The version of this classifier.
/// </para>
/// </summary>
public long Version
{
get { return this._version.GetValueOrDefault(); }
set { this._version = value; }
}
// Check to see if Version property is set
internal bool IsSetVersion()
{
return this._version.HasValue;
}
}
}
| 30.055794
| 102
| 0.56076
|
[
"Apache-2.0"
] |
DetlefGolze/aws-sdk-net
|
sdk/src/Services/Glue/Generated/Model/CsvClassifier.cs
| 7,003
|
C#
|
// Developed by Softeq Development Corporation
// http://www.softeq.com
using System;
using System.Diagnostics.CodeAnalysis;
using NSubstitute;
using Softeq.XToolkit.Common.Tests.WeakTests.Utils;
using Xunit;
namespace Softeq.XToolkit.Common.Tests.WeakTests.WeakFuncTests
{
[SuppressMessage("ReSharper", "xUnit1026", Justification = "Generic parameters used just for test case generation")]
public class WeakAnonymousFuncWithLocalReferenceTests
{
[Theory]
[MemberData(nameof(WeakDelegatesTestsDataProvider.WeakFuncOutputParameters), MemberType = typeof(WeakDelegatesTestsDataProvider))]
public void IsStatic_ReturnsFalse<TOut>(TOut outputParameter)
{
var callCounter = Substitute.For<ICallCounter>();
var weakFunc = WeakDelegatesCallCounter.GetWeakAnonymousFuncWithLocalReference<TOut>(callCounter);
Assert.False(weakFunc.IsStatic);
}
// This test shows why WeakDelegate for lambdas with local variable references doesn't work:
// compiler creates instance of inner class, that could be garbage collected as soon as method ends
[Theory]
[MemberData(nameof(WeakDelegatesTestsDataProvider.WeakFuncOutputParameters), MemberType = typeof(WeakDelegatesTestsDataProvider))]
public void IsAlive_AfterGarbageCollection_ReturnsFalse<TOut>(TOut outputParameter)
{
var callCounter = Substitute.For<ICallCounter>();
var weakFunc = WeakDelegatesCallCounter.GetWeakAnonymousFuncWithLocalReference<TOut>(callCounter);
GC.Collect();
Assert.False(weakFunc.IsAlive);
}
[Theory]
[MemberData(nameof(WeakDelegatesTestsDataProvider.WeakFuncOutputParameters), MemberType = typeof(WeakDelegatesTestsDataProvider))]
public void Execute_AfterGarbageCollection_DoesNotInvokeFunc<TOut>(TOut outputParameter)
{
var callCounter = Substitute.For<ICallCounter>();
var weakFunc = WeakDelegatesCallCounter.GetWeakAnonymousFuncWithLocalReference<TOut>(callCounter);
GC.Collect();
weakFunc.Execute();
callCounter.DidNotReceive().OnFuncCalled<TOut>();
}
}
}
| 41.240741
| 138
| 0.722048
|
[
"MIT"
] |
Softeq/XToolkit.WhiteLabel
|
Softeq.XToolkit.Common.Tests/WeakTests/WeakFuncTests/WeakAnonymousFuncWithLocalReferenceTests.cs
| 2,227
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Activities;
using System.Activities.Presentation.Metadata;
using System.ComponentModel;
using System.Data;
using System.Xml.Linq;
using Newtonsoft.Json.Linq;
using System.IO;
using Newtonsoft.Json;
namespace readConfigXml
{
[DisplayName("Read Xml or Json")]
public class readXmlClass : CodeActivity
{
public enum fileType
{
Xml, Json
}
[Category("Input")]
[RequiredArgument]
[DisplayName("File Type")]
public fileType TypeOfFile { get; set; }
[Category("Input")]
[RequiredArgument]
[DisplayName("File Path")]
public InArgument<string> FilePath { get; set; }
[Category("Output")]
[DisplayName("Result Dictionary")]
public OutArgument<Dictionary<String,String>> ResultDictionary { get; set; }
protected override void Execute(CodeActivityContext context)
{
string File_Path = FilePath.Get(context);
//DataTable dt = new DataTable();
//dt.Columns.Add(new DataColumn("Name", typeof(String)));
//dt.Columns.Add(new DataColumn("Value", typeof(String)));
Dictionary<String, String> dt = new Dictionary<String, String>();
fileType file_Type = TypeOfFile;
if (file_Type == fileType.Xml)
{
XDocument xDoc = XDocument.Load(File_Path);
XContainer xContainer = xDoc;
String fullNodeName = String.Empty;
readXMLNodes(xContainer, ref dt, fullNodeName);
ResultDictionary.Set(context, dt);
}
else
{
JToken objJToken;
using (StreamReader file = File.OpenText(File_Path))
using (JsonTextReader reader = new JsonTextReader(file))
{
objJToken = JToken.ReadFrom(reader);
}
readJsonNodes(objJToken, ref dt, String.Empty);
ResultDictionary.Set(context, dt);
}
}
protected void readXMLNodes(XContainer inXmlElement, ref Dictionary<String,String> dt, string fullNodeName)
{
if (inXmlElement.Elements().Count() > 0)
{
if (inXmlElement.Parent != null)
{
if (string.IsNullOrEmpty(fullNodeName))
fullNodeName = ((XElement)inXmlElement).Name.ToString();
else
fullNodeName = fullNodeName + "_" + ((XElement)inXmlElement).Name;
}
foreach (XElement x in inXmlElement.Elements())
{
readXMLNodes(x, ref dt, fullNodeName);
}
}
else
{
XElement xElem = (XElement)inXmlElement;
if (xElem != null)
{
//DataRow dr = dt.NewRow();
//dr["Name"] = fullNodeName + "_" + xElem.Name;
//dr["Value"] = xElem.Value;
//dt.Rows.Add(dr);
if(dt.ContainsKey(fullNodeName + "_" + xElem.Name))
{
int i = 1;
while(dt.ContainsKey(fullNodeName + "_" + xElem.Name+"_"+i.ToString()))
{
i += 1;
}
dt[fullNodeName + "_" + xElem.Name+"_"+i.ToString()] = xElem.Value;
}
else
{
dt[fullNodeName + "_" + xElem.Name] = xElem.Value;
}
}
}
}
protected void readJsonNodes(JToken objJtoken, ref Dictionary<String, String> dt, string fullNodeName)
{
JToken newJToken;
if (objJtoken is JProperty)
{
newJToken = ((JProperty)objJtoken).Value;
if (string.IsNullOrEmpty(fullNodeName))
fullNodeName = ((JProperty)objJtoken).Name.ToString();
else
fullNodeName = fullNodeName + "_" + ((JProperty)objJtoken).Name.ToString();
}
else
{
newJToken = objJtoken;
}
if (newJToken is JArray)
{
JArray objJArray = (JArray)newJToken;
foreach (JObject j in objJArray)
{
readJsonNodes(j, ref dt, fullNodeName);
}
}
else if (newJToken is JObject)
{
JObject objJson = (JObject)newJToken;
foreach (JProperty j in objJson.Properties())
{
readJsonNodes(j, ref dt, fullNodeName);
}
}
else
{
JProperty jP = (JProperty)objJtoken;
if (jP != null)
{
//DataRow dr = dt.NewRow();
//dr["Name"] = fullNodeName;
//dr["Value"] = jP.Value;
//dt.Rows.Add(dr);
if (dt.ContainsKey(fullNodeName))
{
int i = 1;
while (dt.ContainsKey(fullNodeName + "_" + i.ToString()))
{
i += 1;
}
dt[fullNodeName + "_" + i.ToString()] = jP.Value.ToString();
}
else
{
dt[fullNodeName] = jP.Value.ToString();
}
}
}
}
}
}
| 33.091892
| 116
| 0.438909
|
[
"MIT"
] |
vikasrawat911/ReadXmlOrJson
|
readXmlClass.cs
| 6,124
|
C#
|
using Abp.MultiTenancy;
using demoFirstApp.Authorization.Users;
namespace demoFirstApp.MultiTenancy
{
public class Tenant : AbpTenant<User>
{
public Tenant()
{
}
public Tenant(string tenancyName, string name)
: base(tenancyName, name)
{
}
}
}
| 18.333333
| 54
| 0.569697
|
[
"MIT"
] |
MatiasDevop/abp-netcore
|
aspnet-core/src/demoFirstApp.Core/MultiTenancy/Tenant.cs
| 332
|
C#
|
//Write a program that reads from the console a sequence of n integer numbers and returns the minimal, the maximal number, the sum and the average of all numbers (displayed with 2 digits after the decimal point).
//The input starts by the number n (alone in a line) followed by n lines, each holding an integer number.
using System;
using System.Threading;
using System.Globalization;
class MinMaxSumAverageOfNnumbers
{
static void Main()
{
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
int n = int.Parse(Console.ReadLine());
int min=0, max=0;
double sum=0, avg=0;
for (int i = 1; i <= n; i++)
{
int number = int.Parse(Console.ReadLine());
if (number<min)
{
min = number;
}
if (number>max)
{
max=number;
}
sum += number;
}
avg = sum / n;
Console.WriteLine("min = {0}", 1);
Console.WriteLine("max = {0}", max);
Console.WriteLine("sum = {0}", sum);
Console.WriteLine("avg = {0:F2}", avg);
}
}
| 31.162162
| 213
| 0.565481
|
[
"MIT"
] |
ztodorova/Telerik-Academy
|
C#-part1/Loops/3. MinMaxSumAverageOfNnumbers/MinMaxSumAverageOfNnumbers.cs
| 1,155
|
C#
|
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace OpenItems.Data
{
using System;
using System.Collections.Generic;
public partial class tblMainForExcelImport0325
{
public string DocType { get; set; }
public string DocNumber { get; set; }
public string Title { get; set; }
public string EarliestDate { get; set; }
public string LatestDate { get; set; }
public string AcctPeriod { get; set; }
public Nullable<decimal> TotalLine { get; set; }
public Nullable<decimal> COM { get; set; }
public Nullable<decimal> UDO { get; set; }
public Nullable<decimal> UDOShouldBe { get; set; }
public Nullable<decimal> DO { get; set; }
public Nullable<decimal> DOShouldBe { get; set; }
public Nullable<decimal> ACCR { get; set; }
public Nullable<decimal> UDO_DO { get; set; }
public Nullable<decimal> PENDPYMT { get; set; }
public Nullable<decimal> TotalOrder { get; set; }
public Nullable<decimal> TotalOrderPercent { get; set; }
public Nullable<decimal> PYMTS_TRAN { get; set; }
public Nullable<decimal> PYMTS_CONF { get; set; }
public Nullable<decimal> HOLDBACKS { get; set; }
public string ExpectedCompDate { get; set; }
public Nullable<int> Region { get; set; }
public string OrgCodeBySource { get; set; }
public string LastPaid { get; set; }
public string ContractingOfficer { get; set; }
public Nullable<System.DateTime> ExpirationDate { get; set; }
public string AwardNumber { get; set; }
public string StatusField { get; set; }
public Nullable<decimal> PREPAY { get; set; }
public string Category { get; set; }
public string ItemInfo { get; set; }
}
}
| 44.02
| 85
| 0.587006
|
[
"CC0-1.0"
] |
gaybro8777/FM-ULO
|
Archive/OpenItems/Data/tblMainForExcelImport0325.cs
| 2,201
|
C#
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.Dynamics365.UIAutomation.Api.UCI;
using Microsoft.Dynamics365.UIAutomation.Browser;
using System;
using System.Security;
namespace Microsoft.Dynamics365.UIAutomation.Sample.UCI
{
[TestClass]
public class SetValueUci
{
private readonly SecureString _username = System.Configuration.ConfigurationManager.AppSettings["OnlineUsername"].ToSecureString();
private readonly SecureString _password = System.Configuration.ConfigurationManager.AppSettings["OnlinePassword"].ToSecureString();
private readonly SecureString _mfaSecretKey = System.Configuration.ConfigurationManager.AppSettings["MfaSecretKey"].ToSecureString();
private readonly Uri _xrmUri = new Uri(System.Configuration.ConfigurationManager.AppSettings["OnlineCrmUrl"].ToString());
[TestMethod]
public void UCITestSetValue()
{
var client = new WebClient(TestSettings.Options);
using (var xrmApp = new XrmApp(client))
{
xrmApp.OnlineLogin.Login(_xrmUri, _username, _password, _mfaSecretKey);
xrmApp.Navigation.OpenApp(UCIAppName.Sales);
xrmApp.Navigation.OpenSubArea("Sales", "Accounts");
xrmApp.Grid.SwitchView("My Active Accounts");
xrmApp.Grid.OpenRecord(0);
//xrmApp.Entity.SetValue("name", "Margaret");
}
}
[TestMethod]
public void UCITestSelectOptionSetValue()
{
var client = new WebClient(TestSettings.Options);
using (var xrmApp = new XrmApp(client))
{
xrmApp.OnlineLogin.Login(_xrmUri, _username, _password, _mfaSecretKey);
xrmApp.Navigation.OpenApp(UCIAppName.Sales);
xrmApp.Navigation.OpenSubArea("Sales", "Contacts");
xrmApp.Grid.SwitchView("Active Contacts");
xrmApp.Grid.OpenRecord(0);
xrmApp.ThinkTime(3000);
xrmApp.Entity.SetValue(new OptionSet { Name = "preferredcontactmethodcode", Value = "Email" });
}
}
[TestCategory("Fail - Bug")]
[TestMethod]
public void UCITestOpenLookupSetValue()
{
var client = new WebClient(TestSettings.Options);
using (var xrmApp = new XrmApp(client))
{
xrmApp.OnlineLogin.Login(_xrmUri, _username, _password, _mfaSecretKey);
xrmApp.Navigation.OpenApp(UCIAppName.Sales);
xrmApp.Navigation.OpenSubArea("Sales", "Accounts");
xrmApp.Grid.SwitchView("Active Accounts");
xrmApp.Grid.OpenRecord(0);
xrmApp.ThinkTime(500);
// Need to handle the Lookup Records window and select a record
// Feature Request #854
// To work around the bug below, clearvalue first to initalize the field and then set it
xrmApp.Entity.ClearValue(new LookupItem { Name = "primarycontactid" });
// Bug - System.InvalidOperationException: No Results Matching Jim Were Found. #769
xrmApp.Entity.SetValue(new LookupItem { Name = "primarycontactid", Value = "Jim" });
xrmApp.ThinkTime(500);
}
}
}
}
| 39.241758
| 142
| 0.608513
|
[
"MIT"
] |
operep/Easy-Repro-Example
|
Microsoft.Dynamics365.UIAutomation.Sample/UCI/SetValue.cs
| 3,573
|
C#
|
public class InterpolatingModule : IDigiModule
{
public IDigiFilter Filter { get; private set; }
public Form Form { get; private set; }
public InterpolatingModule()
{
CreateFilterForProperty("Price");
FillForm();
}
public void ApplyForm()
{
var field = Form.GetEntry("PropertySelect").Value;
CreateFilterForProperty(field);
}
private void CreateFilterForProperty(string field)
{
var range = Product.Ranges[field];
Filter = new InterpolatingFilter(Product.GetPropertySelector(field), range.Min, range.Max);
}
private void FillForm()
{
Form = new Form();
var select = new Select();
select.Add("Price", "Price");
select.Add("Calories", "Calories");
select.Add("Fat", "Fat");
select.Add("Sugar", "Sugar");
select.Add("Salt", "Salt");
Form.Add(select, "PropertySelect");
}
}
| 23.675
| 99
| 0.598733
|
[
"MIT"
] |
r0ehre/digimart
|
Assets/UnityARKitPlugin/Examples/ARKit1.5/UnityARImageAnchor/Model/Modules/InterpolatingModule.cs
| 949
|
C#
|
using NUnit.Framework;
using RefactoringEssentials.CSharp.Diagnostics;
namespace RefactoringEssentials.Tests.CSharp.Diagnostics
{
[TestFixture]
[Ignore("TODO: Issue not ported yet")]
public class ForCanBeConvertedToForeachTests : CSharpDiagnosticTestBase
{
[Test]
public void TestArrayCase()
{
Test<ForCanBeConvertedToForeachAnalyzer>(@"
class Test
{
void Foo (object[] o)
{
for (int i = 0; i < o.Length; i++) {
var p = o [i];
System.Console.WriteLine (p);
}
}
}", @"
class Test
{
void Foo (object[] o)
{
foreach (var p in o) {
System.Console.WriteLine (p);
}
}
}");
}
[Test]
public void TestIListCase()
{
Test<ForCanBeConvertedToForeachAnalyzer>(@"
using System.Collections.Generic;
class Test
{
void Foo(IList<int> o)
{
for (int i = 0; i < o.Count; i++) {
var p = o [i];
System.Console.WriteLine (p);
}
}
}", @"
using System.Collections.Generic;
class Test
{
void Foo(IList<int> o)
{
foreach (var p in o) {
System.Console.WriteLine (p);
}
}
}");
}
[Test]
public void TestInvalid()
{
Analyze<ForCanBeConvertedToForeachAnalyzer>(@"
class Test
{
void Foo (object[] o)
{
for (int i = 0; i < o.Length; i++) {
var p = o [i];
System.Console.WriteLine (p);
System.Console.WriteLine (i++);
}
}
}");
}
[Test]
public void TestInvalidCase2()
{
Analyze<ForCanBeConvertedToForeachAnalyzer>(@"
class Test
{
void Foo (object[] o)
{
for (int i = 0; i < o.Length; i++) {
var p = o [i];
System.Console.WriteLine (p);
System.Console.WriteLine (i);
}
}
}");
}
[Test]
public void TestInvalidCase3()
{
Analyze<ForCanBeConvertedToForeachAnalyzer>(@"
class Test
{
void Foo (object[] o)
{
for (int i = 0; i < o.Length; i++) {
var p = o [i];
p = o[0];
System.Console.WriteLine (p);
}
}
}");
}
[Test]
public void TestComplexExpression()
{
Test<ForCanBeConvertedToForeachAnalyzer>(@"
using System.Collections.Generic;
class Test
{
IList<int> Bar { get { return null; } }
void Foo(object o)
{
for (int i = 0; i < ((Test)o).Bar.Count; i++) {
var p = ((Test)o).Bar [i];
System.Console.WriteLine (p);
}
}
}", @"
using System.Collections.Generic;
class Test
{
IList<int> Bar { get { return null; } }
void Foo(object o)
{
foreach (var p in ((Test)o).Bar) {
System.Console.WriteLine (p);
}
}
}");
}
[Test]
public void TestOptimizedFor()
{
Test<ForCanBeConvertedToForeachAnalyzer>(@"
using System.Collections.Generic;
class Test
{
IList<int> Bar { get { return null; } }
void Foo(object o)
{
for (var i = 0, maxBarCount = ((Test)o).Bar.Count; i < maxBarCount; ++i) {
var p = ((Test)o).Bar[i];
System.Console.WriteLine(p);
}
}
}", @"
using System.Collections.Generic;
class Test
{
IList<int> Bar { get { return null; } }
void Foo(object o)
{
foreach (var p in ((Test)o).Bar) {
System.Console.WriteLine (p);
}
}
}");
}
[Test]
public void TestDisable()
{
Analyze<ForCanBeConvertedToForeachAnalyzer>(@"
class Test
{
void Foo (object[] o)
{
// ReSharper disable once ForCanBeConvertedToForeach
for (int i = 0; i < o.Length; i++) {
var p = o [i];
System.Console.WriteLine (p);
}
}
}");
}
}
}
| 17.181373
| 76
| 0.566334
|
[
"MIT"
] |
Wagnerp/RefactoringEssentials
|
Tests/CSharp/Diagnostics/ForCanBeConvertedToForeachTests.cs
| 3,505
|
C#
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Question_16_08_EnglishIntTests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Question_16_08_EnglishIntTests")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("3cdea258-91e8-4611-afa3-071ea7ec3ed2")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.72973
| 84
| 0.75157
|
[
"Apache-2.0"
] |
qulia/CrackingTheCodingInterview
|
Question_16_08_EnglishIntTests/Properties/AssemblyInfo.cs
| 1,436
|
C#
|
// 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.
#nullable disable
using System.ComponentModel;
namespace System.Drawing.Design
{
/// <summary>
/// Provides an interface to manage the images, ToolTips, and event handlers for the properties of a component displayed in a property browser.
/// </summary>
public interface IPropertyValueUIService
{
/// <summary>
/// Adds or removes an <see cref='EventHandler'/> that will be invoked when the global list of <see cref="PropertyValueUIItem"/> is modified.
/// </summary>
event EventHandler PropertyUIValueItemsChanged;
/// <summary>
/// Adds the specified <see cref="PropertyValueUIHandler" /> to this service.
/// </summary>
/// <param name="newHandler">The UI handler to add. </param>
void AddPropertyValueUIHandler(PropertyValueUIHandler newHandler);
/// <summary>
/// Gets the <see cref="PropertyValueUIItem" /> objects that match the specified context and property descriptor characteristics.
/// </summary>
/// <returns>An array of <see cref="PropertyValueUIItem" /> objects that match the specified parameters.</returns>
/// <param name="context">An <see cref="ITypeDescriptorContext" /> that can be used to gain additional context information. </param>
/// <param name="propDesc">A <see cref="PropertyDescriptor" /> that indicates the property to match with the properties to return. </param>
PropertyValueUIItem[] GetPropertyUIValueItems(ITypeDescriptorContext context, PropertyDescriptor propDesc);
/// <summary>
/// Notifies the <see cref="IPropertyValueUIService"/> implementation that the global list of <see cref="PropertyValueUIItem"/> has been modified.
/// </summary>
void NotifyPropertyValueUIItemsChanged();
/// <summary>
/// Removes a <see cref='PropertyValueUIHandler'/> from this service.
/// </summary>
/// <param name="newHandler">The handler to remove.</param>
void RemovePropertyValueUIHandler(PropertyValueUIHandler newHandler);
}
}
| 48.978723
| 155
| 0.682884
|
[
"MIT"
] |
Amy-Li03/winforms
|
src/System.Windows.Forms/src/System/Drawing/Design/IPropertyValueUIService.cs
| 2,304
|
C#
|
using SimpleTools.App.ViewModels;
using System.Linq;
using Windows.UI.Xaml.Controls;
namespace SimpleTools.App.Views
{
public sealed partial class YouTubeTimestampLinkerPage : Page
{
public YouTubeTimestampLinkerPage()
{
InitializeComponent();
DataContext = ViewModelLocator.Current.YouTubeTimestampLinkerViewModel;
}
private void TextBox_OnBeforeTextChanging(TextBox sender, TextBoxBeforeTextChangingEventArgs args)
{
if (string.IsNullOrEmpty(args.NewText))
{
args.Cancel = false;
}
else
{
bool shouldCancelForNonNums = args.NewText.Any(c => !char.IsDigit(c));
args.Cancel = shouldCancelForNonNums;
}
}
}
}
| 27.2
| 106
| 0.605392
|
[
"MIT"
] |
aaron-salisbury/SimpleTools
|
SimpleTools/SimpleTools.App/Views/Tools/Web/YouTubeTimestampLinkerPage.xaml.cs
| 818
|
C#
|
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using SimpleIdServer.OpenBankingApi.Exceptions;
using System.Net;
namespace SimpleIdServer.OpenBankingApi.Infrastructure.Filters
{
public class HttpGlobalExceptionFilter : IExceptionFilter
{
private readonly ILogger<HttpGlobalExceptionFilter> logger;
public HttpGlobalExceptionFilter(ILogger<HttpGlobalExceptionFilter> logger)
{
this.logger = logger;
}
public void OnException(ExceptionContext context)
{
logger.LogError(new EventId(context.Exception.HResult), context.Exception, context.Exception.Message);
var problemDetails = new ValidationProblemDetails()
{
Instance = context.HttpContext.Request.Path,
Status = typeof(NotFoundException).IsAssignableFrom(context.Exception.GetType()) ? StatusCodes.Status404NotFound : StatusCodes.Status401Unauthorized,
Detail = "Please refer to the errors property for additional details."
};
if (typeof(NotFoundException).IsAssignableFrom(context.Exception.GetType()))
{
problemDetails.Status = StatusCodes.Status404NotFound;
}
if (typeof(UnauthorizedException).IsAssignableFrom(context.Exception.GetType()))
{
problemDetails.Status = StatusCodes.Status401Unauthorized;
}
else
{
problemDetails.Status = StatusCodes.Status400BadRequest;
}
problemDetails.Errors.Add("ValidationErrors", new string[] { context.Exception.Message.ToString() });
context.Result = new BadRequestObjectResult(problemDetails);
context.HttpContext.Response.StatusCode = (int)HttpStatusCode.NotFound;
context.ExceptionHandled = true;
}
}
}
| 41.1875
| 165
| 0.670207
|
[
"Apache-2.0"
] |
LaTranche31/SimpleIdServer
|
src/OpenBankingApi/SimpleIdServer.OpenBankingApi/Infrastructure/Filters/HttpGlobalExceptionFilter.cs
| 1,979
|
C#
|
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace Microsoft.Azure.Cosmos.Tests.Pagination
{
using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.Azure.Cosmos.CosmosElements;
using Microsoft.Azure.Cosmos.Pagination;
using Microsoft.Azure.Cosmos.ReadFeed.Pagination;
using Microsoft.Azure.Documents;
internal static class ReadFeedPageExtensions
{
public static IReadOnlyList<Record> GetRecords(this ReadFeedPage page)
{
using (MemoryStream memoryStream = new MemoryStream())
{
page.Content.CopyTo(memoryStream);
CosmosObject responseEnvolope = CosmosObject.CreateFromBuffer(memoryStream.ToArray());
if (!responseEnvolope.TryGetValue("Documents", out CosmosArray documents))
{
throw new InvalidOperationException();
}
List<Record> records = new List<Record>();
foreach (CosmosElement document in documents)
{
CosmosObject documentObject = (CosmosObject)document;
ResourceId rid = ResourceId.Parse(((CosmosString)documentObject["_rid"]).Value);
long ticks = Number64.ToLong(((CosmosNumber)documentObject["_ts"]).Value);
string id = ((CosmosString)documentObject["id"]).Value;
CosmosObject payload = documentObject;
Record record = new Record(rid, new DateTime(ticks: ticks, DateTimeKind.Utc), id, payload);
records.Add(record);
}
return records;
}
}
}
}
| 40.26087
| 111
| 0.561555
|
[
"MIT"
] |
Arithmomaniac/azure-cosmos-dotnet-v3
|
Microsoft.Azure.Cosmos/tests/Microsoft.Azure.Cosmos.Tests/Pagination/ReadFeedPageExtensions.cs
| 1,854
|
C#
|
using TheMovieDbNet.Models.Common;
namespace TheMovieDbNet.Models.TVs
{
/// <summary>
/// Represents movie settings used in search.
/// </summary>
public class TVSearchSettings : SearchSettings
{
/// <summary>
/// Gets or Sets language of search query
/// </summary>
public string Language { get; set; }
/// <summary>
/// Gets or Sets primary release year of the seached movie
/// </summary>
public int FirstAirDateYear { get; set; }
/// <summary>
/// Converts to string to use in search queries.
/// </summary>
/// <returns>String form of query.</returns>
public override string ToString()
{
var result = base.ToString();
if (!string.IsNullOrWhiteSpace(Language))
result += $"&language={Language}";
if (FirstAirDateYear > 1900)
result += $"&first_air_date_year={FirstAirDateYear}";
return result;
}
}
}
| 24.194444
| 60
| 0.657865
|
[
"MIT"
] |
Kerego/TheMovieDbNet
|
src/TheMovieDBNet/Models/TVs/TVSearchSettings.cs
| 871
|
C#
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle( "ScheduleDesign" )]
[assembly: AssemblyDescription( "" )]
[assembly: AssemblyConfiguration( "" )]
[assembly: AssemblyCompany( "Microsoft" )]
[assembly: AssemblyProduct( "ScheduleDesign" )]
[assembly: AssemblyCopyright( "Copyright © Microsoft 2009" )]
[assembly: AssemblyTrademark( "" )]
[assembly: AssemblyCulture( "" )]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible( false )]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid( "e149e91b-e656-4003-9898-659bf773640a" )]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion( "1.0.0.1" )]
[assembly: AssemblyFileVersion( "1.0.0.1" )]
| 39.972973
| 85
| 0.718729
|
[
"MIT"
] |
d3x0r/xperdex
|
OpenSkiePOS/OpenSkieScheduler/ScheduleDesigner2/Properties/AssemblyInfo.cs
| 1,482
|
C#
|
using Microsoft.AspNetCore.Components.WebAssembly.Authentication;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BlazingPizza.Client
{
public class PizzaAuthenticationState : RemoteAuthenticationState
{
public Order Order { get; set; }
}
}
| 23
| 69
| 0.770186
|
[
"MIT"
] |
alberto-bp/blazor-workshop
|
save-points/00-get-started/BlazingPizza.Client/PizzaAuthenticationState.cs
| 324
|
C#
|
using System;
using BenchmarkDotNet.Portability;
namespace BenchmarkDotNet.Horology
{
public static class Chronometer
{
public static readonly IClock Stopwatch = new StopwatchClock();
public static readonly IClock DateTime = new DateTimeClock();
public static readonly IClock WindowsClock = new WindowsClock();
public static readonly IClock BestClock;
public static Frequency Frequency => BestClock.Frequency;
public static long GetTimestamp() => BestClock.GetTimestamp();
public static StartedClock Start() => BestClock.Start();
public static TimeInterval GetResolution() => BestClock.GetResolution();
static Chronometer()
{
if (RuntimeInformation.IsWindows() && WindowsClock.IsAvailable)
BestClock = WindowsClock;
else
BestClock = Stopwatch;
}
public static HardwareTimerKind HardwareTimerKind => GetHardwareTimerKind(BestClock.Frequency);
public static HardwareTimerKind GetHardwareTimerKind(Frequency frequency)
{
long freqKHz = (long)Math.Round(frequency / Frequency.KHz);
if (14300 <= freqKHz && freqKHz <= 14400)
return HardwareTimerKind.Hpet;
if (3579500 <= frequency && frequency <= 3579600)
return HardwareTimerKind.Acpi;
if (freqKHz == 10000)
return HardwareTimerKind.Unknown;
if (5 <= freqKHz && freqKHz < 4000)
return HardwareTimerKind.Tsc;
if (freqKHz <= 4)
return HardwareTimerKind.System;
return HardwareTimerKind.Unknown;
}
}
}
| 37.844444
| 103
| 0.630065
|
[
"MIT"
] |
agocke/BenchmarkDotNet
|
src/BenchmarkDotNet.Core/Horology/Chronometer.cs
| 1,705
|
C#
|
//-----------------------------------------------------------------------------
// Filename: STUNv2AddressAttribute.cs
//
// Description: Implements STUN address attribute as defined in RFC5389.
//
// Author(s):
// Aaron Clauson
//
// History:
// 26 Nov 2010 Aaron Clauson Created (aaron@sipsorcery.com), SIP Sorcery PTY LTD, Hobart, Australia (www.sipsorcery.com).
//
// License:
// BSD 3-Clause "New" or "Revised" License, see included LICENSE.md file.
//-----------------------------------------------------------------------------
using System;
using System.Net;
namespace SIPSorcery.Net
{
public class STUNv2AddressAttribute : STUNv2Attribute
{
public const UInt16 ADDRESS_ATTRIBUTE_LENGTH = 8;
//protected readonly STUNv2AttributeTypesEnum Family = STUNv2AttributeTypesEnum.MappedAddress;
public int Family = 1; // Ipv4 = 1, IPv6 = 2.
public int Port;
public IPAddress Address;
public override UInt16 PaddedLength
{
get { return ADDRESS_ATTRIBUTE_LENGTH; }
}
public STUNv2AddressAttribute(byte[] attributeValue)
: base(STUNv2AttributeTypesEnum.MappedAddress, attributeValue)
{
if (BitConverter.IsLittleEndian)
{
Port = Utility.ReverseEndian(BitConverter.ToUInt16(attributeValue, 2));
}
else
{
Port = BitConverter.ToUInt16(attributeValue, 2);
}
Address = new IPAddress(new byte[] { attributeValue[4], attributeValue[5], attributeValue[6], attributeValue[7] });
}
public STUNv2AddressAttribute(STUNv2AttributeTypesEnum attributeType, int port, IPAddress address)
: base(attributeType, null)
{
Port = port;
Address = address;
base.AttributeType = attributeType;
//base.Length = ADDRESS_ATTRIBUTE_LENGTH;
}
public override int ToByteBuffer(byte[] buffer, int startIndex)
{
if (BitConverter.IsLittleEndian)
{
Buffer.BlockCopy(BitConverter.GetBytes(Utility.ReverseEndian((UInt16)base.AttributeType)), 0, buffer, startIndex, 2);
Buffer.BlockCopy(BitConverter.GetBytes(Utility.ReverseEndian(ADDRESS_ATTRIBUTE_LENGTH)), 0, buffer, startIndex + 2, 2);
}
else
{
Buffer.BlockCopy(BitConverter.GetBytes((UInt16)base.AttributeType), 0, buffer, startIndex, 2);
Buffer.BlockCopy(BitConverter.GetBytes(ADDRESS_ATTRIBUTE_LENGTH), 0, buffer, startIndex + 2, 2);
}
buffer[startIndex + 5] = (byte)Family;
if (BitConverter.IsLittleEndian)
{
Buffer.BlockCopy(BitConverter.GetBytes(Utility.ReverseEndian(Convert.ToUInt16(Port))), 0, buffer, startIndex + 6, 2);
}
else
{
Buffer.BlockCopy(BitConverter.GetBytes(Convert.ToUInt16(Port)), 0, buffer, startIndex + 6, 2);
}
Buffer.BlockCopy(Address.GetAddressBytes(), 0, buffer, startIndex + 8, 4);
return STUNv2Attribute.STUNATTRIBUTE_HEADER_LENGTH + ADDRESS_ATTRIBUTE_LENGTH;
}
public override string ToString()
{
string attrDescrStr = "STUNv2 Attribute: " + base.AttributeType + ", address=" + Address.ToString() + ", port=" + Port + ".";
return attrDescrStr;
}
}
}
| 36.333333
| 137
| 0.584862
|
[
"BSD-3-Clause"
] |
apdevelop/sipsorcery
|
src/net/STUNv2/STUNAttributes/STUNv2AddressAttribute.cs
| 3,488
|
C#
|
using System;
using System.Text.RegularExpressions;
namespace ConsoleApp.Validator {
public class SimpleEmailValidator : IInputValidator {
public SimpleEmailValidator(String invalidMessage) {
InvalidMessage = invalidMessage;
}
const String ValidatePattern = "^[a-zA-Z0-9_-]+(?:\\.[a-zA-Z0-9_-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$";
public String InvalidMessage { get; }
public Boolean Validate(String value) =>
!String.IsNullOrEmpty(value.Trim(' ')) &&
Regex.IsMatch(value.Trim(' '), ValidatePattern, RegexOptions.Singleline | RegexOptions.Compiled);
}
}
| 38.833333
| 169
| 0.622318
|
[
"Unlicense"
] |
asakura89/AspNetMembershipPasswordReset
|
AspNetMembershipPasswordReset/Vendor/ConsoleApp/Validator/SimpleEmailValidator.cs
| 699
|
C#
|
// 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.Reflection.Emit;
/// <summary>
/// OpCodes.Mul [v-minch]
/// </summary>
public class OpCodesMul
{
public static int Main()
{
OpCodesMul test = new OpCodesMul();
TestLibrary.TestFramework.BeginTestCase("Test for the field of OpCodes.Mul");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
return retVal;
}
#region PositiveTest
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1: Verify OpCodes Mul field value");
try
{
retVal = VerificationHelper(OpCodes.Mul,
"mul",
StackBehaviour.Pop1_pop1,
StackBehaviour.Push1,
OperandType.InlineNone,
OpCodeType.Primitive,
1,
(byte)0xff,
(byte)0x5a,
FlowControl.Next,
"001.",
"Mul") && retVal;
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
#region Private Methods
private bool VerificationHelper(OpCode code,
string name,
StackBehaviour pop,
StackBehaviour push,
OperandType oprandType,
OpCodeType type,
int size,
byte s1,
byte s2,
FlowControl ctrl,
string errorno,
string errordesp)
{
bool retVal = true;
string actualName = code.Name;
if (actualName != name)
{
TestLibrary.TestFramework.LogError(errorno + ".0", "Name returns wrong value for OpCode " + errordesp);
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actualName = " + actualName + ", name = " + name);
retVal = false;
}
StackBehaviour actualPop = code.StackBehaviourPop;
if (actualPop != pop)
{
TestLibrary.TestFramework.LogError(errorno + ".1", "StackBehaviourPop returns wrong value for OpCode " + errordesp);
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actualPop = " + actualPop + ", pop = " + pop);
retVal = false;
}
StackBehaviour actualPush = code.StackBehaviourPush;
if (actualPush != push)
{
TestLibrary.TestFramework.LogError(errorno + ".2", "StackBehaviourPush returns wrong value for OpCode " + errordesp);
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actualPush = " + actualPush + ", push = " + push);
retVal = false;
}
OperandType actualOperandType = code.OperandType;
if (actualOperandType != oprandType)
{
TestLibrary.TestFramework.LogError(errorno + ".3", "OperandType returns wrong value for OpCode " + errordesp);
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actualOperandType = " + actualOperandType + ", oprandType = " + oprandType);
retVal = false;
}
OpCodeType actualOpCodeType = code.OpCodeType;
if (actualOpCodeType != type)
{
TestLibrary.TestFramework.LogError(errorno + ".4", "OpCodeType returns wrong value for OpCode " + errordesp);
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actualOpCodeType = " + actualOpCodeType + ", type = " + type);
retVal = false;
}
int actualSize = code.Size;
if (actualSize != size)
{
TestLibrary.TestFramework.LogError(errorno + ".5", "Size returns wrong value for OpCode " + errordesp);
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actualSize = " + actualSize + ", size = " + size);
retVal = false;
}
short expectedValue = 0;
if (size == 2)
expectedValue = (short)(s1 << 8 | s2);
else
expectedValue = (short)s2;
short actualValue = code.Value;
if (actualValue != expectedValue)
{
TestLibrary.TestFramework.LogError(errorno + ".6", "Value returns wrong value for OpCode " + errordesp);
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actualValue = " + actualValue + ", s1 = " + s1 + ", s2 = " + s2 + ", expectedValue = " + expectedValue);
retVal = false;
}
FlowControl actualCtrl = code.FlowControl;
if (actualCtrl != ctrl)
{
TestLibrary.TestFramework.LogError(errorno + ".7", "FlowControl returns wrong value for OpCode " + errordesp);
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actualCtrl = " + actualCtrl + ", ctrl = " + ctrl);
retVal = false;
}
return retVal;
}
#endregion
}
| 36.974026
| 183
| 0.588339
|
[
"MIT"
] |
AaronRobinsonMSFT/coreclr
|
tests/src/CoreMangLib/cti/system/reflection/emit/opcodes/opcodesmul.cs
| 5,694
|
C#
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Desharp.ExampleWinForms")]
[assembly: AssemblyDescription("Desharp - Basic Windows Forms application demo.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Tom Flidr")]
[assembly: AssemblyProduct("Desharp.ExampleWinForms")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("Tom Flidr")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("2633ef41-3d49-45ed-8c59-fa5d8cfdc8b6")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.3.0.1")]
[assembly: AssemblyFileVersion("1.3.0.1")]
| 40.081081
| 84
| 0.752529
|
[
"BSD-3-Clause"
] |
debug-sharp/example-win-forms
|
Properties/AssemblyInfo.cs
| 1,486
|
C#
|
using UnityEngine;
using System.Collections;
using OpenMined.Syft.Tensor;
using OpenMined.Network.Controllers;
/**
* Like CrossEntropyLoss, but follows the spec of Keras implementation
* of Categorical cross entropy
*/
namespace OpenMined.Syft.Layer.Loss
{
public class CategoricalCrossEntropyLoss : Loss
{
public CategoricalCrossEntropyLoss(SyftController controller)
{
init("categorical_crossentropy");
#pragma warning disable 420
id = System.Threading.Interlocked.Increment(ref nCreated);
controller.addModel(this);
}
public override FloatTensor Forward(FloatTensor prediction, FloatTensor target)
{
// Note: prediction should be logits, basically pre-softmax. This method applies softmax first.
// TODO check shapes
FloatTensor output = ((target.Mul(prediction.Log())).Sum()).Neg();
return output;
}
public override int getParameterCount() { return 0; }
}
}
| 26.097561
| 109
| 0.642056
|
[
"Apache-2.0"
] |
justin1121/OpenMined
|
UnityProject/Assets/OpenMined/Syft/NN/Loss/CategoricalCrossEntropyLoss.cs
| 1,070
|
C#
|
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.Activities
{
using System.Activities.Validation;
using System.Collections.Generic;
using System.Runtime;
[Fx.Tag.XamlVisible(false)]
sealed class ActivityLocationReferenceEnvironment : LocationReferenceEnvironment
{
Dictionary<string, LocationReference> declarations;
List<LocationReference> unnamedDeclarations;
public ActivityLocationReferenceEnvironment()
{
}
public ActivityLocationReferenceEnvironment(LocationReferenceEnvironment parent)
{
this.Parent = parent;
if (this.Parent != null)
{
this.InternalRoot = parent.Root;
}
}
public override Activity Root
{
get
{
return this.InternalRoot;
}
}
public Activity InternalRoot
{
get;
set;
}
Dictionary<string, LocationReference> Declarations
{
get
{
if (this.declarations == null)
{
this.declarations = new Dictionary<string, LocationReference>();
}
return this.declarations;
}
}
public override bool IsVisible(LocationReference locationReference)
{
if (locationReference == null)
{
throw FxTrace.Exception.ArgumentNull("locationReference");
}
LocationReferenceEnvironment currentScope = this;
while (currentScope != null)
{
ActivityLocationReferenceEnvironment activityEnvironment = currentScope as ActivityLocationReferenceEnvironment;
if (activityEnvironment != null)
{
if (activityEnvironment.declarations != null)
{
foreach (LocationReference declaration in activityEnvironment.declarations.Values)
{
if (locationReference == declaration)
{
return true;
}
}
}
if (activityEnvironment.unnamedDeclarations != null)
{
for (int i = 0; i < activityEnvironment.unnamedDeclarations.Count; i++)
{
if (locationReference == activityEnvironment.unnamedDeclarations[i])
{
return true;
}
}
}
}
else
{
return currentScope.IsVisible(locationReference);
}
currentScope = currentScope.Parent;
}
return false;
}
public void Declare(LocationReference locationReference, Activity owner, ref IList<ValidationError> validationErrors)
{
Fx.Assert(locationReference != null, "Must not be null");
if (locationReference.Name == null)
{
if (this.unnamedDeclarations == null)
{
this.unnamedDeclarations = new List<LocationReference>();
}
this.unnamedDeclarations.Add(locationReference);
}
else
{
if (this.Declarations.ContainsKey(locationReference.Name))
{
string id = null;
if (owner != null)
{
id = owner.Id;
}
ValidationError validationError = new ValidationError(SR.SymbolNamesMustBeUnique(locationReference.Name))
{
Source = owner,
Id = id
};
ActivityUtilities.Add(ref validationErrors, validationError);
}
else
{
this.Declarations.Add(locationReference.Name, locationReference);
}
}
}
public override bool TryGetLocationReference(string name, out LocationReference result)
{
if (name == null)
{
// We don't allow null names in our LocationReferenceEnvironment but
// a custom declared environment might. We need to walk up
// to the root and see if it chains to a
// non-ActivityLocationReferenceEnvironment implementation
LocationReferenceEnvironment currentEnvironment = this.Parent;
while (currentEnvironment is ActivityLocationReferenceEnvironment)
{
currentEnvironment = currentEnvironment.Parent;
}
if (currentEnvironment != null)
{
Fx.Assert(!(currentEnvironment is ActivityLocationReferenceEnvironment), "We must be at a non-ActivityLocationReferenceEnvironment implementation.");
return currentEnvironment.TryGetLocationReference(name, out result);
}
}
else
{
if (this.declarations != null && this.declarations.TryGetValue(name, out result))
{
return true;
}
bool found = false;
LocationReferenceEnvironment currentEnvironment = this.Parent;
LocationReferenceEnvironment rootEnvironment = this;
// Loop through all of the ActivityLocationReferenceEnvironments we have chained together
while (currentEnvironment != null && currentEnvironment is ActivityLocationReferenceEnvironment)
{
ActivityLocationReferenceEnvironment activityEnvironment = (ActivityLocationReferenceEnvironment)currentEnvironment;
if (activityEnvironment.declarations != null && activityEnvironment.declarations.TryGetValue(name, out result))
{
return true;
}
rootEnvironment = currentEnvironment;
currentEnvironment = currentEnvironment.Parent;
}
if (!found)
{
if (currentEnvironment != null)
{
// Looks like we have a non-ActivityLocationReferenceEnvironment at the root
Fx.Assert(!(currentEnvironment is ActivityLocationReferenceEnvironment), "We should have some other host environment at this point.");
if (currentEnvironment.TryGetLocationReference(name, out result))
{
return true;
}
}
}
}
result = null;
return false;
}
public override IEnumerable<LocationReference> GetLocationReferences()
{
return this.Declarations.Values;
}
}
}
| 35.167442
| 169
| 0.493586
|
[
"Apache-2.0"
] |
295007712/295007712.github.io
|
sourceCode/dotNet4.6/ndp/cdf/src/NetFx40/System.Activities/System/Activities/ActivityLocationReferenceEnvironment.cs
| 7,561
|
C#
|
using OA.Core;
using OA.Core.Input;
using OA.Core.UI;
using OA.Ultima.World;
using OA.Ultima.World.Entities;
using OA.Ultima.World.Entities.Mobiles;
using UnityEngine;
namespace OA.Ultima.UI.Controls
{
class PaperdollInteractable : Gump
{
bool _isFemale;
bool _isElf;
GumpPicBackpack _backpack;
WorldModel _world;
public PaperdollInteractable(AControl parent, int x, int y, Mobile sourceEntity)
: base(0, 0)
{
Parent = parent;
Position = new Vector2Int(x, y);
_isFemale = sourceEntity.Flags.IsFemale;
SourceEntity = sourceEntity;
_world = Service.Get<WorldModel>();
}
public override void Dispose()
{
_sourceEntity.ClearCallBacks(OnEntityUpdated, OnEntityDisposed);
if (_backpack != null)
_backpack.MouseDoubleClickEvent -= On_Dblclick_Backpack;
base.Dispose();
}
public override void Update(double totalMS, double frameMS)
{
if (_sourceEntity != null)
{
_isFemale = ((Mobile)_sourceEntity).Flags.IsFemale;
_isElf = false;
}
base.Update(totalMS, frameMS);
}
void OnEntityUpdated(AEntity entity)
{
ClearControls();
// Add the base gump - the semi-naked paper doll.
if (true)
{
var bodyID = 12 + (_isElf ? 2 : 0) + (_isFemale ? 1 : 0); // ((Mobile)m_sourceEntity).BodyID;
GumpPic paperdoll = (GumpPic)AddControl(new GumpPic(this, 0, 0, bodyID, ((Mobile)_sourceEntity).Hue));
paperdoll.HandlesMouseInput = true;
paperdoll.IsPaperdoll = true;
}
// Loop through the items on the mobile and create the gump pics.
for (var i = 0; i < _drawOrder.Length; i++)
{
var item = ((Mobile)_sourceEntity).GetItem((int)_drawOrder[i]);
if (item == null)
continue;
var canPickUp = true;
switch (_drawOrder[i])
{
case PaperDollEquipSlots.FacialHair:
case PaperDollEquipSlots.Hair:
canPickUp = false;
break;
default:
break;
}
AddControl(new ItemGumplingPaperdoll(this, 0, 0, item));
((ItemGumplingPaperdoll)LastControl).SlotIndex = (int)i;
((ItemGumplingPaperdoll)LastControl).IsFemale = _isFemale;
((ItemGumplingPaperdoll)LastControl).CanPickUp = canPickUp;
}
// If this object has a backpack, add it last.
if (((Mobile)_sourceEntity).GetItem((int)PaperDollEquipSlots.Backpack) != null)
{
var backpack = ((Mobile)_sourceEntity).GetItem((int)PaperDollEquipSlots.Backpack);
AddControl(_backpack = new GumpPicBackpack(this, -7, 0, backpack));
_backpack.HandlesMouseInput = true;
_backpack.MouseDoubleClickEvent += On_Dblclick_Backpack;
}
}
void OnEntityDisposed(AEntity entity)
{
Dispose();
}
void On_Dblclick_Backpack(AControl control, int x, int y, MouseButton button)
{
var backpack = ((Mobile)_sourceEntity).Backpack;
_world.Interaction.DoubleClick(backpack);
}
AEntity _sourceEntity;
public AEntity SourceEntity
{
set
{
if (value != _sourceEntity)
{
if (_sourceEntity != null)
{
_sourceEntity.ClearCallBacks(OnEntityUpdated, OnEntityDisposed);
_sourceEntity = null;
}
if (value is Mobile)
{
_sourceEntity = value;
// update the gump
OnEntityUpdated(_sourceEntity);
// if the entity changes in the future, update the gump again
_sourceEntity.SetCallbacks(OnEntityUpdated, OnEntityDisposed);
}
}
}
get { return _sourceEntity; }
}
enum PaperDollEquipSlots
{
Body = 0,
RightHand = 1,
LeftHand = 2,
Footwear = 3,
Legging = 4,
Shirt = 5,
Head = 6,
Gloves = 7,
Ring = 8,
Talisman = 9,
Neck = 10,
Hair = 11,
Belt = 12,
Chest = 13,
Bracelet = 14,
Unused = 15,
FacialHair = 16,
Sash = 17,
Earring = 18,
Sleeves = 19,
Back = 20,
Backpack = 21,
Robe = 22,
Skirt = 23,
// skip 24, inner legs (!!! do we really skip this?)
}
static PaperDollEquipSlots[] _drawOrder = {
PaperDollEquipSlots.Footwear,
PaperDollEquipSlots.Legging,
PaperDollEquipSlots.Shirt,
PaperDollEquipSlots.Sleeves,
PaperDollEquipSlots.Gloves,
PaperDollEquipSlots.Ring,
PaperDollEquipSlots.Talisman,
PaperDollEquipSlots.Neck,
PaperDollEquipSlots.Belt,
PaperDollEquipSlots.Chest,
PaperDollEquipSlots.Bracelet,
PaperDollEquipSlots.Hair,
PaperDollEquipSlots.FacialHair,
PaperDollEquipSlots.Head,
PaperDollEquipSlots.Sash,
PaperDollEquipSlots.Earring,
PaperDollEquipSlots.Back,
PaperDollEquipSlots.Skirt,
PaperDollEquipSlots.Robe,
PaperDollEquipSlots.LeftHand,
PaperDollEquipSlots.RightHand
};
}
}
| 35.106742
| 119
| 0.496559
|
[
"MIT"
] |
BclEx/object-assets
|
src/ObjectManager/Object.Ultima.Game/UI/Controls/PaperdollInteractable.cs
| 6,251
|
C#
|
using System;
using NUnit.Framework;
namespace WebGL.UnitTests
{
[TestFixture]
public class FramebufferTest : BaseTest
{
[Test(Description = "")]
public void ShouldDoMagic()
{
throw new NotImplementedException();
}
}
}
| 18.666667
| 48
| 0.596429
|
[
"Apache-2.0"
] |
jdarc/webgl.net
|
WebGL.UnitTests/conformance/v100/FramebufferTest.cs
| 282
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using Akka.Actor;
using Akka.Configuration;
namespace Akka.Dispatch
{
/// <summary>
/// Class Mailboxes.
/// </summary>
public class Mailboxes
{
/// <summary>
/// The system
/// </summary>
private readonly ActorSystem _system;
private readonly DeadLetterMailbox _deadLetterMailbox;
public static readonly string DefaultMailboxId = "akka.actor.default-mailbox";
private readonly Dictionary<Type, Config> _requirementsMapping;
/// <summary>
/// Initializes a new instance of the <see cref="Mailboxes" /> class.
/// </summary>
/// <param name="system">The system.</param>
public Mailboxes(ActorSystem system)
{
_system = system;
_deadLetterMailbox = new DeadLetterMailbox(system.DeadLetters);
var mailboxConfig = system.Settings.Config.GetConfig("akka.actor.mailbox");
var requirements = mailboxConfig.GetConfig("requirements").AsEnumerable().ToList();
_requirementsMapping = new Dictionary<Type, Config>();
foreach (var kvp in requirements)
{
var type = Type.GetType(kvp.Key);
if (type == null)
{
//TODO: can't log here, logger not created yet
// system.Log.Warn("Mailbox Requirement mapping '{0}' is not an actual type",kvp.Key);
continue;
}
var config = system.Settings.Config.GetConfig(kvp.Value.GetString());
_requirementsMapping.Add(type, config);
}
}
public Type LookupByQueueType(Type queueType)
{
var config = _requirementsMapping[queueType];
var mailbox = config.GetString("mailbox-type");
var mailboxType = Type.GetType(mailbox);
return mailboxType;
}
public DeadLetterMailbox DeadLetterMailbox { get { return _deadLetterMailbox; } }
public Mailbox CreateMailbox(Props props, Config dispatcherConfig)
{
var type = GetMailboxType(props, dispatcherConfig);
var instance = (Mailbox)Activator.CreateInstance(type);
return instance;
}
public Type GetMailboxType(Props props, Config dispatcherConfig)
{
if (!string.IsNullOrEmpty(props.Mailbox))
{
return FromConfig(props.Mailbox);
}
var actortype = props.Type;
var interfaces = actortype.GetInterfaces()
.Where(i => i.IsGenericType)
.Where(i => i.GetGenericTypeDefinition() == typeof (RequiresMessageQueue<>))
.Select(i => i.GetGenericArguments().First())
.ToList();
if (interfaces.Count > 0)
{
var config = _requirementsMapping[interfaces.First()];
var mailbox = config.GetString("mailbox-type");
var mailboxType = Type.GetType(mailbox);
return mailboxType;
}
return FromConfig(DefaultMailboxId);
}
/// <summary>
/// Creates a mailbox from a configuration path.
/// </summary>
/// <param name="path">The path.</param>
/// <returns>Mailbox.</returns>
public Type FromConfig(string path)
{
//TODO: this should not exist, its a temp hack because we are not serializing mailbox info when doing remote deply..
if (string.IsNullOrEmpty(path))
{
return typeof (UnboundedMailbox);
}
var config = _system.Settings.Config.GetConfig(path);
var type = config.GetString("mailbox-type");
var mailboxType = Type.GetType(type);
return mailboxType;
/*
mailbox-capacity = 1000
mailbox-push-timeout-time = 10s
stash-capacity = -1
*/
}
}
}
| 35.077586
| 128
| 0.567461
|
[
"Apache-2.0"
] |
HCanber/akka.net
|
src/core/Akka/Dispatch/Mailboxes.cs
| 4,071
|
C#
|
// *** WARNING: this file was generated by crd2pulumi. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Kubernetes.Types.Inputs.Packages.V1Alpha1
{
public class PackageSpecControllerDeploymentSpecTemplateSpecVolumesFlexVolumeArgs : Pulumi.ResourceArgs
{
[Input("driver", required: true)]
public Input<string> Driver { get; set; } = null!;
[Input("fsType")]
public Input<string>? FsType { get; set; }
[Input("options")]
private InputMap<string>? _options;
public InputMap<string> Options
{
get => _options ?? (_options = new InputMap<string>());
set => _options = value;
}
[Input("readOnly")]
public Input<bool>? ReadOnly { get; set; }
[Input("secretRef")]
public Input<Pulumi.Kubernetes.Types.Inputs.Packages.V1Alpha1.PackageSpecControllerDeploymentSpecTemplateSpecVolumesFlexVolumeSecretRefArgs>? SecretRef { get; set; }
public PackageSpecControllerDeploymentSpecTemplateSpecVolumesFlexVolumeArgs()
{
}
}
}
| 31.9
| 173
| 0.670063
|
[
"Apache-2.0"
] |
pulumi/pulumi-kubernetes-crds
|
operators/crossplane/dotnet/Kubernetes/Crds/Operators/Crossplane/Packages/V1Alpha1/Inputs/PackageSpecControllerDeploymentSpecTemplateSpecVolumesFlexVolumeArgs.cs
| 1,276
|
C#
|
using Microsoft.AspNetCore.Mvc;
using Senparc.Areas.Admin.Filters;
using Senparc.Core.Models.VD;
using Senparc.Scf.Core.Models.VD;
namespace Senparc.Areas.Admin
{
public interface IBaseAdminPageModel : IBasePageModel
{
}
//暂时取消权限验证
//[ServiceFilter(typeof(AuthenticationAsyncPageFilterAttribute))]
[AdminAuthorize("AdminOnly")]
public class BaseAdminPageModel : PageModelBase, IBaseAdminPageModel
{
/// <summary>
/// 存储相关用户信息
/// </summary>
public Core.AdminWorkContext AdminWorkContext { get; set; }
public virtual IActionResult RenderError(string message)
{
//保留原有的controller和action信息
//ViewData["FakeControllerName"] = RouteData.Values["controller"] as string;
//ViewData["FakeActionName"] = RouteData.Values["action"] as string;
return Page();//TODO:设定一个特定的错误页面
//return View("Error", new Error_ExceptionVD
//{
// //HandleErrorInfo = new HandleErrorInfo(new Exception(message), Url.RequestContext.RouteData.GetRequiredString("controller"), Url.RequestContext.RouteData.GetRequiredString("action"))
//});
}
}
}
| 30.35
| 201
| 0.657331
|
[
"Apache-2.0"
] |
502931221/SCF
|
src/Senparc.Areas.Admin/BaseAdminPageModel.cs
| 1,288
|
C#
|
#region Apache License Version 2.0
/*----------------------------------------------------------------
Copyright 2022 Jeffrey Su & Suzhou Senparc Network Technology Co.,Ltd.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the
License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
either express or implied. See the License for the specific language governing permissions
and limitations under the License.
Detail: https://github.com/JeffreySu/WeiXinMPSDK/blob/master/license.md
----------------------------------------------------------------*/
#endregion Apache License Version 2.0
/*----------------------------------------------------------------
Copyright (C) 2022 Senparc
文件名:InterfaceAnalysisItemJson.cs
文件功能描述:获取接口分析数据返回结果 单条数据类
创建标识:Senparc - 20150211
修改标识:Senparc - 20150303
修改描述:整理接口
修改标识:Senparc - 20150310
修改描述:修改类
----------------------------------------------------------------*/
namespace Senparc.Weixin.MP.AdvancedAPIs.Analysis
{
public class BaseInterfaceAnalysisResult : BaseAnalysisObject
{
/// <summary>
/// 数据的日期,需在begin_date和end_date之间
/// </summary>
public string ref_date { get; set; }
/// <summary>
/// 通过服务器配置地址获得消息后,被动回复用户消息的次数
/// </summary>
public int callback_count { get; set; }
/// <summary>
/// 上述动作的失败次数
/// </summary>
public int fail_count { get; set; }
/// <summary>
/// 总耗时,除以callback_count即为平均耗时
/// </summary>
public int total_time_cost { get; set; }
/// <summary>
/// 最大耗时
/// </summary>
public int max_time_cost { get; set; }
}
/// <summary>
/// 接口分析数据 单条数据
/// </summary>
public class InterfaceSummaryItem : BaseInterfaceAnalysisResult
{
}
/// <summary>
/// 接口分析分时数据 单条数据
/// </summary>
public class InterfaceSummaryHourItem : BaseInterfaceAnalysisResult
{
/// <summary>
/// 数据的小时
/// </summary>
public int ref_hour { get; set; }
}
}
| 28.416667
| 90
| 0.564726
|
[
"Apache-2.0"
] |
AaronWu666/WeiXinMPSDK
|
src/Senparc.Weixin.MP/Senparc.Weixin.MP/AdvancedAPIs/Analysis/AnalysisResultJson/InterfaceAnalysisItemJson.cs
| 2,687
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BE;
using System.Data;
using System.Data.SqlClient;
using Dapper;
namespace DAO
{
public class Det_Evento_ServicioDAO
{
public static List<Servicio> BuscarDetEvento_Servicio(int idevento)
{
List<Servicio> lis = new List<Servicio>();
SqlConnection cn = new SqlConnection(Conexion.cn);
try
{
DynamicParameters dypa = new DynamicParameters();
dypa.Add("@IdEvento", idevento);
lis = cn.Query<Servicio>("itData.SP_S_ID_Servicios", dypa, commandType: CommandType.StoredProcedure).ToList();
}
catch (Exception e)
{
lis = null;
var rpt = "Excepción ocurrida: " + e.Message;
}
finally
{
cn.Close();
cn.Dispose();
}
return lis;
}
public static string Ingresar(Det_Evento_Servicio value)
{
string rpt = "ok";
SqlConnection cn = new SqlConnection(Conexion.cn);
try
{
DynamicParameters dp1 = new DynamicParameters();
dp1.Add("@IdEvento", value.IdEvento);
dp1.Add("@IdServicio", value.IdServicio);
dp1.Add("@Descripcion", value.Descripcion);
cn.Execute("itData.SP_I_DETEVENTO_SERVICIOS", dp1, commandType: CommandType.StoredProcedure);
}
catch (Exception e)
{
rpt = "Excepción ocurrida: " + e.Message;
}
finally
{
cn.Close();
cn.Dispose();
}
return rpt;
}
public static string Eliminar(int IdEvento, int idservicio)
{
string rpt = "ok";
SqlConnection cn = new SqlConnection(Conexion.cn);
cn.Open();
try
{
DynamicParameters dp1 = new DynamicParameters();
dp1.Add("@IdEvento", IdEvento);
dp1.Add("@IdServicio", idservicio);
cn.Execute("itData.SP_D_DetEvento_Servicio", dp1, commandType: CommandType.StoredProcedure);
}
catch (Exception e)
{
rpt = "Excepción ocurrida: " + e.Message;
}
finally
{
cn.Close();
cn.Dispose();
}
return rpt;
}
}
}
| 29.909091
| 126
| 0.49734
|
[
"MIT"
] |
carloseip/ApiEventos
|
DAO/Det_Evento_ServicioDAO.cs
| 2,637
|
C#
|
using System;
using System.Collections.Generic;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
using Content.Server.GameObjects.Components.Access;
using Content.Server.GameObjects.Components.Movement;
using Content.Server.GameObjects.EntitySystems.AI.Pathfinding;
using Content.Server.GameObjects.EntitySystems.AI.Pathfinding.Pathfinders;
using Content.Server.GameObjects.EntitySystems.JobQueues;
using Content.Shared.GameObjects.EntitySystems.ActionBlocker;
using Content.Shared.Utility;
using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Map;
using Robust.Shared.Maths;
using Robust.Shared.Physics;
using Robust.Shared.Timing;
using Robust.Shared.Utility;
using Robust.Shared.ViewVariables;
namespace Content.Server.GameObjects.EntitySystems.AI.Steering
{
public sealed class AiSteeringSystem : EntitySystem
{
// http://www.red3d.com/cwr/papers/1999/gdc99steer.html for a steering overview
[Dependency] private readonly IMapManager _mapManager = default!;
[Dependency] private readonly IPauseManager _pauseManager = default!;
private PathfindingSystem _pathfindingSystem = default!;
/// <summary>
/// Whether we try to avoid non-blocking physics objects
/// </summary>
[ViewVariables(VVAccess.ReadWrite)]
public bool CollisionAvoidanceEnabled { get; set; } = true;
/// <summary>
/// How close we need to get to the center of each tile
/// </summary>
private const float TileTolerance = 0.8f;
/// <summary>
/// How long to wait between checks (if necessary).
/// </summary>
private const float InRangeUnobstructedCooldown = 0.25f;
private Dictionary<IEntity, IAiSteeringRequest> RunningAgents => _agentLists[_listIndex];
// We'll cycle the running list every tick as all we're doing is getting a vector2 for the
// agent's steering. Should help a lot given this is the most expensive operator by far.
// The AI will keep moving, it's just it'll keep moving in its existing direction.
// If we change to 20/30 TPS you might want to change this but for now it's fine
private readonly List<Dictionary<IEntity, IAiSteeringRequest>> _agentLists = new(AgentListCount);
private const int AgentListCount = 2;
private int _listIndex;
// Cache nextGrid
private readonly Dictionary<IEntity, EntityCoordinates> _nextGrid = new();
/// <summary>
/// Current live paths for AI
/// </summary>
private readonly Dictionary<IEntity, Queue<TileRef>> _paths = new();
/// <summary>
/// Pathfinding request jobs we're waiting on
/// </summary>
private readonly Dictionary<IEntity, (CancellationTokenSource CancelToken, Job<Queue<TileRef>> Job)> _pathfindingRequests =
new();
/// <summary>
/// Keep track of how long we've been in 1 position and re-path if it's been too long
/// </summary>
private readonly Dictionary<IEntity, int> _stuckCounter = new();
/// <summary>
/// Get a fixed position for the target entity; if they move then re-path
/// </summary>
private readonly Dictionary<IEntity, EntityCoordinates> _entityTargetPosition = new();
// Anti-Stuck
// Given the collision avoidance can lead to twitching need to store a reference position and check if we've been near this too long
private readonly Dictionary<IEntity, EntityCoordinates> _stuckPositions = new();
public override void Initialize()
{
base.Initialize();
_pathfindingSystem = Get<PathfindingSystem>();
for (var i = 0; i < AgentListCount; i++)
{
_agentLists.Add(new Dictionary<IEntity, IAiSteeringRequest>());
}
}
/// <summary>
/// Adds the AI to the steering system to move towards a specific target
/// </summary>
/// We'll add it to the movement list that has the least number of agents
/// <param name="entity"></param>
/// <param name="steeringRequest"></param>
public void Register(IEntity entity, IAiSteeringRequest steeringRequest)
{
var lowestListCount = 1000;
var lowestListIndex = 0;
for (var i = 0; i < _agentLists.Count; i++)
{
var agentList = _agentLists[i];
// Register shouldn't be called twice; if it is then someone dun fucked up
DebugTools.Assert(!agentList.ContainsKey(entity));
if (agentList.Count < lowestListCount)
{
lowestListCount = agentList.Count;
lowestListIndex = i;
}
}
_agentLists[lowestListIndex].Add(entity, steeringRequest);
}
/// <summary>
/// Stops the steering behavior for the AI and cleans up
/// </summary>
/// <param name="entity"></param>
/// <exception cref="InvalidOperationException"></exception>
public void Unregister(IEntity entity)
{
if (entity.TryGetComponent(out AiControllerComponent? controller))
{
controller.VelocityDir = Vector2.Zero;
}
if (_pathfindingRequests.TryGetValue(entity, out var request))
{
switch (request.Job.Status)
{
case JobStatus.Pending:
case JobStatus.Finished:
break;
case JobStatus.Running:
case JobStatus.Paused:
case JobStatus.Waiting:
request.CancelToken.Cancel();
break;
}
switch (request.Job.Exception)
{
case null:
break;
default:
ExceptionDispatchInfo.Capture(request.Job.Exception).Throw();
throw request.Job.Exception;
}
_pathfindingRequests.Remove(entity);
}
if (_paths.ContainsKey(entity))
{
_paths.Remove(entity);
}
if (_nextGrid.ContainsKey(entity))
{
_nextGrid.Remove(entity);
}
if (_stuckCounter.ContainsKey(entity))
{
_stuckCounter.Remove(entity);
}
if (_entityTargetPosition.ContainsKey(entity))
{
_entityTargetPosition.Remove(entity);
}
foreach (var agentList in _agentLists)
{
if (agentList.ContainsKey(entity))
{
agentList.Remove(entity);
return;
}
}
}
/// <summary>
/// Is the entity currently registered for steering?
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
public bool IsRegistered(IEntity entity)
{
foreach (var agentList in _agentLists)
{
if (agentList.ContainsKey(entity))
{
return true;
}
}
return false;
}
public override void Update(float frameTime)
{
base.Update(frameTime);
foreach (var (agent, steering) in RunningAgents)
{
// Yeah look it's not true frametime but good enough.
var result = Steer(agent, steering, frameTime * RunningAgents.Count);
steering.Status = result;
switch (result)
{
case SteeringStatus.Pending:
break;
case SteeringStatus.NoPath:
Unregister(agent);
break;
case SteeringStatus.Arrived:
Unregister(agent);
break;
case SteeringStatus.Moving:
break;
default:
throw new ArgumentOutOfRangeException();
}
}
_listIndex = (_listIndex + 1) % _agentLists.Count;
}
/// <summary>
/// Go through each steerer and combine their vectors
/// </summary>
/// <param name="entity"></param>
/// <param name="steeringRequest"></param>
/// <param name="frameTime"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
private SteeringStatus Steer(IEntity entity, IAiSteeringRequest steeringRequest, float frameTime)
{
// Main optimisation to be done below is the redundant calls and adding more variables
if (entity.Deleted ||
!entity.TryGetComponent(out AiControllerComponent? controller) ||
!ActionBlockerSystem.CanMove(entity) ||
!entity.Transform.GridID.IsValid())
{
return SteeringStatus.NoPath;
}
var entitySteering = steeringRequest as EntityTargetSteeringRequest;
if (entitySteering != null && entitySteering.Target.Deleted)
{
controller.VelocityDir = Vector2.Zero;
return SteeringStatus.NoPath;
}
if (_pauseManager.IsGridPaused(entity.Transform.GridID))
{
controller.VelocityDir = Vector2.Zero;
return SteeringStatus.Pending;
}
// Validation
// Check if we can even arrive -> Currently only samegrid movement supported
if (entity.Transform.GridID != steeringRequest.TargetGrid.GetGridId(EntityManager))
{
controller.VelocityDir = Vector2.Zero;
return SteeringStatus.NoPath;
}
// Check if we have arrived
var targetDistance = (entity.Transform.MapPosition.Position - steeringRequest.TargetMap.Position).Length;
steeringRequest.TimeUntilInteractionCheck -= frameTime;
if (targetDistance <= steeringRequest.ArrivalDistance && steeringRequest.TimeUntilInteractionCheck <= 0.0f)
{
if (!steeringRequest.RequiresInRangeUnobstructed ||
entity.InRangeUnobstructed(steeringRequest.TargetMap, steeringRequest.ArrivalDistance, popup: true))
{
// TODO: Need cruder LOS checks for ranged weaps
controller.VelocityDir = Vector2.Zero;
return SteeringStatus.Arrived;
}
steeringRequest.TimeUntilInteractionCheck = InRangeUnobstructedCooldown;
// Welp, we'll keep on moving.
}
// If we're really close don't swiggity swoogity back and forth and just wait for the interaction check maybe?
if (steeringRequest.TimeUntilInteractionCheck > 0.0f && targetDistance <= 0.1f)
{
controller.VelocityDir = Vector2.Zero;
return SteeringStatus.Moving;
}
// Handle pathfinding job
// If we still have an existing path then keep following that until the new path arrives
if (_pathfindingRequests.TryGetValue(entity, out var pathRequest) && pathRequest.Job.Status == JobStatus.Finished)
{
switch (pathRequest.Job.Exception)
{
case null:
break;
// Currently nothing should be cancelling these except external factors
case TaskCanceledException _:
controller.VelocityDir = Vector2.Zero;
return SteeringStatus.NoPath;
default:
throw pathRequest.Job.Exception;
}
// No actual path
var path = _pathfindingRequests[entity].Job.Result;
if (path == null || path.Count == 0)
{
controller.VelocityDir = Vector2.Zero;
return SteeringStatus.NoPath;
}
// If we're closer to next tile then we don't want to walk backwards to our tile's center
UpdatePath(entity, path);
// If we're targeting entity get a fixed tile; if they move from it then re-path (at least til we get a better solution)
if (entitySteering != null)
{
_entityTargetPosition[entity] = entitySteering.TargetGrid;
}
// Move next tick
return SteeringStatus.Pending;
}
// Check if we even have a path to follow
// If the route's empty we could be close and may not need a re-path so we won't check if it is
if (!_paths.ContainsKey(entity) && !_pathfindingRequests.ContainsKey(entity) && targetDistance > 1.5f)
{
controller.VelocityDir = Vector2.Zero;
RequestPath(entity, steeringRequest);
return SteeringStatus.Pending;
}
var ignoredCollision = new List<IEntity>();
// Check if the target entity has moved - If so then re-path
// TODO: Patch the path from the target's position back towards us, stopping if it ever intersects the current path
// Probably need a separate "PatchPath" job
if (entitySteering != null)
{
// Check if target's moved too far
if (_entityTargetPosition.TryGetValue(entity, out var targetGrid) &&
(entitySteering.TargetGrid.Position - targetGrid.Position).Length >= entitySteering.TargetMaxMove)
{
// We'll just repath and keep following the existing one until we get a new one
RequestPath(entity, steeringRequest);
}
ignoredCollision.Add(entitySteering.Target);
}
HandleStuck(entity);
// TODO: Probably need a dedicated queuing solver (doorway congestion FML)
// Get the target grid (either next tile or target itself) and pass it in to the steering behaviors
// If there's nowhere to go then just stop and wait
var nextGrid = NextGrid(entity, steeringRequest);
if (!nextGrid.HasValue)
{
controller.VelocityDir = Vector2.Zero;
return SteeringStatus.NoPath;
}
// Validate that we can even get to the next grid (could probably just check if we can use nextTile if we're not near the target grid)
if (!_pathfindingSystem.CanTraverse(entity, nextGrid.Value))
{
controller.VelocityDir = Vector2.Zero;
return SteeringStatus.NoPath;
}
// Now we can /finally/ move
var movementVector = Vector2.Zero;
// Originally I tried using interface steerers but ehhh each one kind of needs to do its own thing
// Plus there's not much point putting these in a separate class
// Each one just adds onto the final vector
movementVector += Seek(entity, nextGrid.Value);
if (CollisionAvoidanceEnabled)
{
movementVector += CollisionAvoidance(entity, movementVector, ignoredCollision);
}
// Group behaviors would also go here e.g. separation, cohesion, alignment
// Move towards it
DebugTools.Assert(movementVector != new Vector2(float.NaN, float.NaN));
controller.VelocityDir = movementVector.Normalized;
return SteeringStatus.Moving;
}
/// <summary>
/// Get a new job from the pathfindingsystem
/// </summary>
/// <param name="entity"></param>
/// <param name="steeringRequest"></param>
private void RequestPath(IEntity entity, IAiSteeringRequest steeringRequest)
{
if (_pathfindingRequests.ContainsKey(entity))
{
return;
}
var cancelToken = new CancellationTokenSource();
var gridManager = _mapManager.GetGrid(entity.Transform.GridID);
var startTile = gridManager.GetTileRef(entity.Transform.Coordinates);
var endTile = gridManager.GetTileRef(steeringRequest.TargetGrid);
var collisionMask = 0;
if (entity.TryGetComponent(out IPhysBody? physics))
{
collisionMask = physics.CollisionMask;
}
var access = AccessReader.FindAccessTags(entity);
var job = _pathfindingSystem.RequestPath(new PathfindingArgs(
entity.Uid,
access,
collisionMask,
startTile,
endTile,
steeringRequest.PathfindingProximity
), cancelToken.Token);
_pathfindingRequests.Add(entity, (cancelToken, job));
}
/// <summary>
/// Given the pathfinding is timesliced we need to trim the first few(?) tiles so we don't walk backwards
/// </summary>
/// <param name="entity"></param>
/// <param name="path"></param>
private void UpdatePath(IEntity entity, Queue<TileRef> path)
{
_pathfindingRequests.Remove(entity);
var entityTile = _mapManager.GetGrid(entity.Transform.GridID).GetTileRef(entity.Transform.Coordinates);
var tile = path.Dequeue();
var closestDistance = PathfindingHelpers.OctileDistance(entityTile, tile);
for (var i = 0; i < path.Count; i++)
{
tile = path.Peek();
var distance = PathfindingHelpers.OctileDistance(entityTile, tile);
if (distance < closestDistance)
{
path.Dequeue();
}
else
{
break;
}
}
_paths[entity] = path;
}
/// <summary>
/// Get the next tile as EntityCoordinates
/// </summary>
/// <param name="entity"></param>
/// <param name="steeringRequest"></param>
/// <returns></returns>
private EntityCoordinates? NextGrid(IEntity entity, IAiSteeringRequest steeringRequest)
{
// Remove the cached grid
if (!_paths.ContainsKey(entity) && _nextGrid.ContainsKey(entity))
{
_nextGrid.Remove(entity);
}
// If no tiles left just move towards the target (if we're close)
if (!_paths.ContainsKey(entity) || _paths[entity].Count == 0)
{
if ((steeringRequest.TargetGrid.Position - entity.Transform.Coordinates.Position).Length <= 2.0f)
{
return steeringRequest.TargetGrid;
}
// Too far so we need a re-path
return null;
}
if (!_nextGrid.TryGetValue(entity, out var nextGrid) ||
(nextGrid.Position - entity.Transform.Coordinates.Position).Length <= TileTolerance)
{
UpdateGridCache(entity);
nextGrid = _nextGrid[entity];
}
DebugTools.Assert(nextGrid != default);
return nextGrid;
}
/// <summary>
/// Rather than converting TileRef to EntityCoordinates over and over we'll just cache it
/// </summary>
/// <param name="entity"></param>
/// <param name="dequeue"></param>
private void UpdateGridCache(IEntity entity, bool dequeue = true)
{
if (_paths[entity].Count == 0) return;
var nextTile = dequeue ? _paths[entity].Dequeue() : _paths[entity].Peek();
var nextGrid = _mapManager.GetGrid(entity.Transform.GridID).GridTileToLocal(nextTile.GridIndices);
_nextGrid[entity] = nextGrid;
}
/// <summary>
/// Check if we've been near our last EntityCoordinates too long and try to fix it
/// </summary>
/// <param name="entity"></param>
private void HandleStuck(IEntity entity)
{
if (!_stuckPositions.TryGetValue(entity, out var stuckPosition))
{
_stuckPositions[entity] = entity.Transform.Coordinates;
_stuckCounter[entity] = 0;
return;
}
if ((entity.Transform.Coordinates.Position - stuckPosition.Position).Length <= 1.0f)
{
_stuckCounter.TryGetValue(entity, out var stuckCount);
_stuckCounter[entity] = stuckCount + 1;
}
else
{
// No longer stuck
_stuckPositions[entity] = entity.Transform.Coordinates;
_stuckCounter[entity] = 0;
return;
}
// Should probably be time-based
if (_stuckCounter[entity] < 30)
{
return;
}
// Okay now we're stuck
_paths.Remove(entity);
_stuckCounter[entity] = 0;
}
#region Steering
/// <summary>
/// Move straight to target position
/// </summary>
/// <param name="entity"></param>
/// <param name="grid"></param>
/// <returns></returns>
private Vector2 Seek(IEntity entity, EntityCoordinates grid)
{
// is-even much
var entityPos = entity.Transform.Coordinates;
return entityPos == grid
? Vector2.Zero
: (grid.Position - entityPos.Position).Normalized;
}
/// <summary>
/// Like Seek but slows down when within distance
/// </summary>
/// <param name="entity"></param>
/// <param name="grid"></param>
/// <param name="slowingDistance"></param>
/// <returns></returns>
private Vector2 Arrival(IEntity entity, EntityCoordinates grid, float slowingDistance = 1.0f)
{
var entityPos = entity.Transform.Coordinates;
DebugTools.Assert(slowingDistance > 0.0f);
if (entityPos == grid)
{
return Vector2.Zero;
}
var targetDiff = grid.Position - entityPos.Position;
var rampedSpeed = targetDiff.Length / slowingDistance;
return targetDiff.Normalized * MathF.Min(1.0f, rampedSpeed);
}
/// <summary>
/// Like Seek but predicts target's future position
/// </summary>
/// <param name="entity"></param>
/// <param name="target"></param>
/// <returns></returns>
private Vector2 Pursuit(IEntity entity, IEntity target)
{
var entityPos = entity.Transform.Coordinates;
var targetPos = target.Transform.Coordinates;
if (entityPos == targetPos)
{
return Vector2.Zero;
}
if (target.TryGetComponent(out IPhysBody? physics))
{
var targetDistance = (targetPos.Position - entityPos.Position);
targetPos = targetPos.Offset(physics.LinearVelocity * targetDistance);
}
return (targetPos.Position - entityPos.Position).Normalized;
}
/// <summary>
/// Checks for non-anchored physics objects that can block us
/// </summary>
/// <param name="entity"></param>
/// <param name="direction">entity's travel direction</param>
/// <param name="ignoredTargets"></param>
/// <returns></returns>
private Vector2 CollisionAvoidance(IEntity entity, Vector2 direction, ICollection<IEntity> ignoredTargets)
{
if (direction == Vector2.Zero || !entity.TryGetComponent(out IPhysBody? physics))
{
return Vector2.Zero;
}
// We'll check tile-by-tile
// Rewriting this frequently so not many comments as they'll go stale
// I realise this is bad so please rewrite it ;-;
var entityCollisionMask = physics.CollisionMask;
var avoidanceVector = Vector2.Zero;
var checkTiles = new HashSet<TileRef>();
var avoidTiles = new HashSet<TileRef>();
var entityGridCoords = entity.Transform.Coordinates;
var grid = _mapManager.GetGrid(entity.Transform.GridID);
var currentTile = grid.GetTileRef(entityGridCoords);
var halfwayTile = grid.GetTileRef(entityGridCoords.Offset(direction / 2));
var nextTile = grid.GetTileRef(entityGridCoords.Offset(direction));
checkTiles.Add(currentTile);
checkTiles.Add(halfwayTile);
checkTiles.Add(nextTile);
// Handling corners with collision avoidance is a real bitch
// TBH collision avoidance in general that doesn't run like arse is a real bitch
foreach (var tile in checkTiles)
{
var node = _pathfindingSystem.GetNode(tile);
// Assume the immovables have already been checked
foreach (var (physicsEntity, layer) in node.PhysicsLayers)
{
// Ignore myself / my target if applicable / if my mask doesn't collide
if (physicsEntity == entity || ignoredTargets.Contains(physicsEntity) || (entityCollisionMask & layer) == 0) continue;
// God there's so many ways to do this
// err for now we'll just assume the first entity is the center and just add a vector for it
//Pathfinding updates are deferred so this may not be done yet.
if (physicsEntity.Deleted) continue;
// if we're moving in the same direction then ignore
// So if 2 entities are moving towards each other and both detect a collision they'll both move in the same direction
// i.e. towards the right
if (physicsEntity.TryGetComponent(out IPhysBody? otherPhysics) &&
Vector2.Dot(otherPhysics.LinearVelocity, direction) > 0)
{
continue;
}
var centerGrid = physicsEntity.Transform.Coordinates;
// Check how close we are to center of tile and get the inverse; if we're closer this is stronger
var additionalVector = (centerGrid.Position - entityGridCoords.Position);
var distance = additionalVector.Length;
// If we're too far no point, if we're close then cap it at the normalized vector
distance = MathHelper.Clamp(2.5f - distance, 0.0f, 1.0f);
additionalVector = new Angle(90 * distance).RotateVec(additionalVector);
avoidanceVector += additionalVector;
// if we do need to avoid that means we'll have to lookahead for the next tile
avoidTiles.Add(tile);
break;
}
}
// Dis ugly
if (_paths.TryGetValue(entity, out var path))
{
if (path.Count > 0)
{
var checkTile = path.Peek();
for (var i = 0; i < Math.Min(path.Count, avoidTiles.Count); i++)
{
if (avoidTiles.Contains(checkTile))
{
checkTile = path.Dequeue();
}
}
UpdateGridCache(entity, false);
}
}
return avoidanceVector == Vector2.Zero ? avoidanceVector : avoidanceVector.Normalized;
}
#endregion
}
public enum SteeringStatus
{
Pending,
NoPath,
Arrived,
Moving,
}
}
| 39.949861
| 146
| 0.554595
|
[
"MIT"
] |
FoundVivo/space-station-14
|
Content.Server/GameObjects/EntitySystems/AI/Steering/AiSteeringSystem.cs
| 28,684
|
C#
|
// Generated by gencs from visualization_msgs/InteractiveMarkerPose.msg
// DO NOT EDIT THIS FILE BY HAND!
using System;
using System.Collections;
using System.Collections.Generic;
using SIGVerse.RosBridge;
using UnityEngine;
using SIGVerse.RosBridge.std_msgs;
using SIGVerse.RosBridge.geometry_msgs;
namespace SIGVerse.RosBridge
{
namespace visualization_msgs
{
[System.Serializable]
public class InteractiveMarkerPose : RosMessage
{
public std_msgs.Header header;
public geometry_msgs.Pose pose;
public string name;
public InteractiveMarkerPose()
{
this.header = new std_msgs.Header();
this.pose = new geometry_msgs.Pose();
this.name = "";
}
public InteractiveMarkerPose(std_msgs.Header header, geometry_msgs.Pose pose, string name)
{
this.header = header;
this.pose = pose;
this.name = name;
}
new public static string GetMessageType()
{
return "visualization_msgs/InteractiveMarkerPose";
}
new public static string GetMD5Hash()
{
return "a6e6833209a196a38d798dadb02c81f8";
}
} // class InteractiveMarkerPose
} // namespace visualization_msgs
} // namespace SIGVerse.ROSBridge
| 22.653846
| 93
| 0.736842
|
[
"MIT"
] |
Ohara124c41/TUB-MSc_Thesis
|
SEK_01_MkI/Assets/SIGVerse/Common/ROSBridge/messaging/visualization_msgs/InteractiveMarkerPose.cs
| 1,178
|
C#
|
//
// MusicBrainzQueryJob.cs
//
// Author:
// Aaron Bockover <abockover@novell.com>
// Aurélien Mino <aurelien.mino@gmail.com>
//
// Copyright (C) 2006-2008 Novell, Inc.
// Copyright (C) 2010 Aurélien Mino
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
using System.IO;
using System.Net;
using System.Xml;
using System.Text;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Web;
using System.Text.RegularExpressions;
using MusicBrainz;
using Hyena;
using Banshee.Base;
using Banshee.Metadata;
using Banshee.Kernel;
using Banshee.Collection;
using Banshee.Streaming;
using Banshee.Networking;
using Banshee.Collection.Database;
namespace Banshee.Metadata.MusicBrainz
{
public class MusicBrainzQueryJob : MetadataServiceJob
{
private static string AmazonUriFormat = "http://images.amazon.com/images/P/{0}.01._SCLZZZZZZZ_.jpg";
class CoverArtSite
{
public Regex Regex;
public string ImgURI;
public CoverArtSite (Regex regex, string img_URI) {
this.Regex = regex;
this.ImgURI = img_URI;
}
}
private static CoverArtSite [] CoverArtSites = new CoverArtSite [] {
// CDBaby
new CoverArtSite (
new Regex (@"http://(?:www\.)?cdbaby.com/cd/(\w)(\w)(\w*)"),
"http://cdbaby.name/{0}/{1}/{0}{1}{2}.jpg"
),
// Jamendo
new CoverArtSite (
new Regex (@"http:\/\/(?:www\.)?jamendo.com\/(?:[a-z]+\/)?album\/([0-9]+)"),
"http://www.jamendo.com/get/album/id/album/artworkurl/redirect/{0}/?artwork_size=0"
)
};
public MusicBrainzQueryJob (IBasicTrackInfo track)
{
Track = track;
MusicBrainzService.UserAgent = Banshee.Web.Browser.UserAgent;
}
public override void Run ()
{
Lookup ();
}
public bool Lookup ()
{
if (Track == null || (Track.MediaAttributes & TrackMediaAttributes.Podcast) != 0) {
return false;
}
string artwork_id = Track.ArtworkId;
if (artwork_id == null) {
return false;
} else if (CoverArtSpec.CoverExists (artwork_id)) {
return false;
} else if (!InternetConnected) {
return false;
}
DatabaseTrackInfo dbtrack;
dbtrack = Track as DatabaseTrackInfo;
Release release;
// If we have the MBID of the album, we can do a direct MusicBrainz lookup
if (dbtrack != null && dbtrack.AlbumMusicBrainzId != null) {
release = Release.Get (dbtrack.AlbumMusicBrainzId);
if (!String.IsNullOrEmpty (release.GetAsin ()) && SaveCover (String.Format (AmazonUriFormat, release.GetAsin ()))) {
return true;
}
// Otherwise we do a MusicBrainz search
} else {
ReleaseQueryParameters parameters = new ReleaseQueryParameters ();
parameters.Title = Track.AlbumTitle;
parameters.Artist = Track.AlbumArtist;
if (dbtrack != null) {
parameters.TrackCount = dbtrack.TrackCount;
}
Query<Release> query = Release.Query (parameters);
release = query.PerfectMatch ();
foreach (Release r in query.Best ()) {
if (!String.IsNullOrEmpty (r.GetAsin ()) && SaveCover (String.Format (AmazonUriFormat, r.GetAsin ()))) {
return true;
}
}
}
if (release == null) {
return false;
}
// No success with ASIN, let's try with other linked URLs
ReadOnlyCollection<UrlRelation> relations = release.GetUrlRelations ();
foreach (UrlRelation relation in relations) {
foreach (CoverArtSite site in CoverArtSites) {
Match m = site.Regex.Match (relation.Target.AbsoluteUri);
if (m.Success) {
string [] parameters = new string [m.Groups.Count];
for (int i = 1; i < m.Groups.Count; i++) {
parameters[i-1] = m.Groups[i].Value;
}
String uri = String.Format (site.ImgURI, parameters);
if (SaveCover (uri)) {
return true;
}
}
}
if (relation.Type == "CoverArtLink" && SaveCover (relation.Target.AbsoluteUri)) {
return true;
}
}
return false;
}
private bool SaveCover (string uri) {
string artwork_id = Track.ArtworkId;
if (SaveHttpStreamCover (new Uri (uri), artwork_id, null)) {
Log.Debug ("Downloaded cover art", artwork_id);
StreamTag tag = new StreamTag ();
tag.Name = CommonTags.AlbumCoverId;
tag.Value = artwork_id;
AddTag (tag);
return true;
}
return false;
}
}
}
| 33.544041
| 132
| 0.562249
|
[
"MIT"
] |
Dynalon/banshee-osx
|
src/Core/Banshee.Services/Banshee.Metadata.MusicBrainz/MusicBrainzQueryJob.cs
| 6,476
|
C#
|
namespace Gripper.ChromeDevTools.Audits
{
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.Runtime.Serialization;
/// <summary>
/// HeavyAdReason
/// </summary>
[JsonConverter(typeof(StringEnumConverter))]
public enum HeavyAdReason
{
[EnumMember(Value = "NetworkTotalLimit")]
NetworkTotalLimit,
[EnumMember(Value = "CpuTotalLimit")]
CpuTotalLimit,
[EnumMember(Value = "CpuPeakLimit")]
CpuPeakLimit,
}
}
| 25.6
| 49
| 0.648438
|
[
"MIT"
] |
tomaskrupka/Gripper
|
src/Gripper.ChromeDevTools/Audits/HeavyAdReason.cs
| 512
|
C#
|
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace MedicalStore
{
public partial class Medicine
{
/// <summary>
/// Button1 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button Button1;
/// <summary>
/// Button2 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button Button2;
/// <summary>
/// Button3 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button Button3;
/// <summary>
/// Textbox1 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox Textbox1;
/// <summary>
/// Button4 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button Button4;
/// <summary>
/// Textbox2 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox Textbox2;
/// <summary>
/// Button5 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button Button5;
/// <summary>
/// Textbox3 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox Textbox3;
/// <summary>
/// Button6 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button Button6;
/// <summary>
/// Textbox4 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox Textbox4;
/// <summary>
/// Button7 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button Button7;
/// <summary>
/// Textbox5 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox Textbox5;
/// <summary>
/// Button8 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button Button8;
/// <summary>
/// Textbox6 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox Textbox6;
/// <summary>
/// Button9 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button Button9;
/// <summary>
/// Textbox7 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox Textbox7;
/// <summary>
/// Button10 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button Button10;
/// <summary>
/// Textbox8 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox Textbox8;
/// <summary>
/// Textbox9 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox Textbox9;
/// <summary>
/// Button11 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button Button11;
/// <summary>
/// Textbox10 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox Textbox10;
/// <summary>
/// Textbox11 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox Textbox11;
/// <summary>
/// Button12 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button Button12;
}
}
| 34.502222
| 85
| 0.532011
|
[
"MIT"
] |
UmairHabib/Web-Based-Pharmacy-using-C-Sharp-and-SQL
|
Pharmacy/MedicalStore/Medicine.aspx.designer.cs
| 7,765
|
C#
|
using Unity.UIWidgets.foundation;
using Unity.UIWidgets.ui;
using UnityEngine;
using Rect = Unity.UIWidgets.ui.Rect;
namespace Unity.UIWidgets.flow {
public class TextureLayer : Layer {
Offset _offset = Offset.zero;
public Offset offset {
set { this._offset = value ?? Offset.zero; }
}
Size _size;
public Size size {
set { this._size = value; }
}
Texture _texture;
public Texture texture {
set { this._texture = value; }
}
bool _freeze = false;
public bool freeze {
set { this._freeze = value; }
}
public override void preroll(PrerollContext context, Matrix3 matrix) {
this.paintBounds = Rect.fromLTWH(
this._offset.dx, this._offset.dy, this._size.width, this._size.height);
}
public override void paint(PaintContext context) {
D.assert(this.needsPainting);
if (this._texture == null) {
return;
}
var image = new Image(this._texture, noDispose: true);
var canvas = context.canvas;
canvas.drawImageRect(image, this.paintBounds, new Paint());
}
}
}
| 24.615385
| 87
| 0.552344
|
[
"BSD-3-Clause"
] |
ServiceStack/script-unity
|
MyFirstGame/Library/PackageCache/com.unity.uiwidgets@1.0.6-preview/Runtime/flow/texture_layer.cs
| 1,280
|
C#
|
namespace Vyn;
/// <summary>
/// This class describes the base of every game. This is the main class and entry point for every game.
/// It holds specific information and the main entry point to the underlying game's API.
/// Every game needs exact one class inheriting this class.
/// </summary>
public abstract class VynGame
{
/// <summary>
/// Gets called when the engine has been initialized and started. At this point the renderer should
/// be up and running and a window should be visible.
/// </summary>
public abstract void OnStart();
/// <summary>
/// Gets called when the game is getting stopped.
/// </summary>
/// <returns>If the method is returning true, the stopping gets cancelled.</returns>
public virtual bool OnStop() => false;
/// <summary>
/// Gets called when the game main class was being loaded but the game hasn't started yet.
/// </summary>
public virtual void OnLoad() {}
}
| 37.076923
| 103
| 0.676349
|
[
"MIT"
] |
VynEngine/Vyn
|
Vyn/VynGame.cs
| 966
|
C#
|
using System;
namespace GovernCMS.ViewModels
{
public class LoginViewModel
{
public String EmailAddr { get; set; }
public String Passwd { get; set; }
public String RedirectUrl { get; set; }
}
}
| 21
| 47
| 0.623377
|
[
"MIT"
] |
ptenn/govern-cms
|
GovernCMSWeb/ViewModels/LoginViewModel.cs
| 233
|
C#
|
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/prsht.h in the Windows SDK for Windows 10.0.19041.0
// Original source is Copyright © Microsoft. All rights reserved.
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace TerraFX.Interop
{
public unsafe partial struct PROPSHEETPAGEA_V2
{
[NativeTypeName("DWORD")]
public uint dwSize;
[NativeTypeName("DWORD")]
public uint dwFlags;
[NativeTypeName("HINSTANCE")]
public IntPtr hInstance;
[NativeTypeName("_PROPSHEETPAGEA_V2::(anonymous union at C:/Program Files (x86)/Windows Kits/10/Include/10.0.19041.0/um/prsht.h:204:5)")]
public _Anonymous1_e__Union Anonymous1;
public ref sbyte* pszTemplate
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
fixed (_Anonymous1_e__Union* pField = &Anonymous1)
{
return ref pField->pszTemplate;
}
}
}
public ref DLGTEMPLATE* pResource
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
fixed (_Anonymous1_e__Union* pField = &Anonymous1)
{
return ref pField->pResource;
}
}
}
[NativeTypeName("_PROPSHEETPAGEA_V2::(anonymous union at C:/Program Files (x86)/Windows Kits/10/Include/10.0.19041.0/um/prsht.h:204:5)")]
public _Anonymous2_e__Union Anonymous2;
public ref IntPtr hIcon
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
return ref MemoryMarshal.GetReference(MemoryMarshal.CreateSpan(ref Anonymous2.hIcon, 1));
}
}
public ref sbyte* pszIcon
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
fixed (_Anonymous2_e__Union* pField = &Anonymous2)
{
return ref pField->pszIcon;
}
}
}
[NativeTypeName("LPCSTR")]
public sbyte* pszTitle;
[NativeTypeName("DLGPROC")]
public delegate* unmanaged<IntPtr, uint, nuint, nint, nint> pfnDlgProc;
[NativeTypeName("LPARAM")]
public nint lParam;
[NativeTypeName("LPFNPSPCALLBACKA")]
public delegate* unmanaged<IntPtr, uint, PROPSHEETPAGEA*, uint> pfnCallback;
[NativeTypeName("UINT *")]
public uint* pcRefParent;
[NativeTypeName("LPCSTR")]
public sbyte* pszHeaderTitle;
[NativeTypeName("LPCSTR")]
public sbyte* pszHeaderSubTitle;
[StructLayout(LayoutKind.Explicit)]
public unsafe partial struct _Anonymous1_e__Union
{
[FieldOffset(0)]
[NativeTypeName("LPCSTR")]
public sbyte* pszTemplate;
[FieldOffset(0)]
[NativeTypeName("PROPSHEETPAGE_RESOURCE")]
public DLGTEMPLATE* pResource;
}
[StructLayout(LayoutKind.Explicit)]
public unsafe partial struct _Anonymous2_e__Union
{
[FieldOffset(0)]
[NativeTypeName("HICON")]
public IntPtr hIcon;
[FieldOffset(0)]
[NativeTypeName("LPCSTR")]
public sbyte* pszIcon;
}
}
}
| 29.716667
| 145
| 0.579921
|
[
"MIT"
] |
Perksey/terrafx.interop.windows
|
sources/Interop/Windows/um/prsht/PROPSHEETPAGEA_V2.cs
| 3,568
|
C#
|
using Microsoft.CodeAnalysis;
using Semmle.Extraction.Kinds;
namespace Semmle.Extraction.CSharp.Entities.Expressions
{
class This : Expression
{
This(IExpressionInfo info) : base(info) { }
public static This CreateImplicit(Context cx, Type @class, Extraction.Entities.Location loc, IExpressionParentEntity parent, int child) =>
new This(new ExpressionInfo(cx, new AnnotatedType(@class, NullableAnnotation.None), loc, Kinds.ExprKind.THIS_ACCESS, parent, child, true, null));
public static This CreateExplicit(ExpressionNodeInfo info) => new This(info.SetKind(ExprKind.THIS_ACCESS));
}
}
| 39.8125
| 157
| 0.737834
|
[
"MIT"
] |
Abdullahki/codeql
|
csharp/extractor/Semmle.Extraction.CSharp/Entities/Expressions/This.cs
| 637
|
C#
|
/*
* Copyright (c) 2022 ETH Zürich, Educational Development and Technology (LET)
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
namespace SafeExamBrowser.Browser.Contracts.Events
{
/// <summary>
/// Event handler used to control (e.g. allow or prohibit) download requests.
/// </summary>
public delegate void DownloadRequestedEventHandler(string fileName, DownloadEventArgs args);
}
| 34.5625
| 93
| 0.734177
|
[
"MPL-2.0"
] |
RickAllMighty8195/seb-win-refactoring
|
SafeExamBrowser.Browser.Contracts/Events/DownloadRequestedEventHandler.cs
| 556
|
C#
|
using MCTuristic_Centro_Historico.localhost;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace MCTuristic_Centro_Historico.GUI
{
public partial class Suscripciones : System.Web.UI.Page
{
int idUser;
localhost.WsMCTuristic owebService = new WsMCTuristic();
protected void Page_Load(object sender, EventArgs e)
{
idUser = Convert.ToInt32(Session["idUsuario"]);
}
protected void btnGratis_Click(object sender, EventArgs e)
{
if (idUser == 0)
{
Response.Redirect("Registro.aspx");
}
else
{
int idGratis = 1;
GenerarNuevaSuscripcion(idGratis);
}
}
public void GenerarNuevaSuscripcion(int idSus)
{
try
{
localhost.SuscripcionBO oSuscripcion = new SuscripcionBO();
//Obtener id Usuario Recien registrado
oSuscripcion.FechaPago = DateTime.Now.Date;
oSuscripcion.IdSuscripcion = idSus;
oSuscripcion.IdUsuario = Convert.ToString(idUser);
int i = owebService.InsertarSuscripcion(oSuscripcion);
if (i > 0)
{
Response.Redirect("InicioSesion.aspx");
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
protected void Button2_Click(object sender, EventArgs e)
{
Response.Redirect("https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=YAHTQP78APJES");
//if (idUser == 0)
//{
// Response.Redirect("Registro.aspx");
//}
//else
//{
// int mes = 2;
// GenerarNuevaSuscripcion(mes);
//}
}
protected void Button3_Click(object sender, EventArgs e)
{
Response.Redirect("https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=PMWY57KLG7YP8");
//if (idUser == 0)
//{
// Response.Redirect("Registro.aspx");
//}
//else
//{
// int seism = 3;
// GenerarNuevaSuscripcion(seism);
//}
}
protected void Button4_Click(object sender, EventArgs e)
{
Response.Redirect("https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=Q4W8ELA9JRG9W");
//if (idUser == 0)
//{
// Response.Redirect("Registro.aspx");
//}
//else
//{
// int Año = 4;
// GenerarNuevaSuscripcion(Año);
//}
}
}
}
| 30.010204
| 116
| 0.50561
|
[
"MIT"
] |
JLPuc/TU
|
Proyecto0.1/MCTuristic_Centro_Historico/MCTuristic_Centro_Historico/GUI/Suscripciones.aspx.cs
| 2,945
|
C#
|
namespace ContosoUniversity.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class SoftDelete : DbMigration
{
public override void Up()
{
AddColumn("dbo.Person", "IsDeleted", c => c.Boolean());
}
public override void Down()
{
DropColumn("dbo.Person", "IsDeleted");
}
}
}
| 21.421053
| 67
| 0.547912
|
[
"MIT"
] |
j-kelly/ContosoUniversity
|
src/ContosoUniversity.Domain.Core/Repository/Migrations/201509040833136_SoftDelete.cs
| 407
|
C#
|
// Generated class v2.50.0.0, don't modify
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
namespace NHtmlUnit.Svg
{
public partial class SvgFeTile : NHtmlUnit.Svg.SvgElement, NHtmlUnit.W3C.Dom.INode, NHtmlUnit.W3C.Dom.IElement
{
static SvgFeTile()
{
ObjectWrapper.RegisterWrapperCreator((com.gargoylesoftware.htmlunit.svg.SvgFeTile o) =>
new SvgFeTile(o));
}
public SvgFeTile(com.gargoylesoftware.htmlunit.svg.SvgFeTile wrappedObject) : base(wrappedObject) {}
public new com.gargoylesoftware.htmlunit.svg.SvgFeTile WObj
{
get { return (com.gargoylesoftware.htmlunit.svg.SvgFeTile)WrappedObject; }
}
}
}
| 26.566667
| 114
| 0.685069
|
[
"Apache-2.0"
] |
HtmlUnit/NHtmlUnit
|
app/NHtmlUnit/Generated/Svg/SvgFeTile.cs
| 797
|
C#
|
using Codeplex.Data;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ALVR
{
class ClientSocket
{
TcpClient client;
Action StartServerCallback;
Action ConnectionClosedCallback;
int RequestId = 1;
public ClientSocket(Action startServerCallback, Action connectionClosedCallback)
{
StartServerCallback = startServerCallback;
ConnectionClosedCallback = connectionClosedCallback;
}
async public Task<bool> Connect(string host, int port)
{
try
{
client = new TcpClient();
await client.ConnectAsync(host, port);
}
catch (Exception) {
return false;
}
Task t = ReadLoop();
Task k = KeepAliveLoop();
return true;
}
async public Task Disconnect()
{
if (client != null)
{
await SendCommand("Close");
client.Close();
}
client = null;
}
async private Task ReadLoop()
{
try
{
while (true)
{
dynamic message = await ReadNextMessage();
switch (message.command)
{
case "StartServer":
StartServerCallback();
await ReplyMessage((int)message.requestId, "OK");
break;
case "Ping":
await ReplyMessage((int)message.requestId, "Pong");
break;
case "Pong":
break;
case "Close":
return;
}
}
}
catch (Exception e)
{
System.Console.WriteLine(e);
}
finally
{
ConnectionClosedCallback();
if (client != null)
{
client.Close();
}
client = null;
}
}
async private Task KeepAliveLoop()
{
try
{
while (client != null)
{
var t = SendCommand("Ping");
await Task.Delay(1000);
await t;
}
}
catch (Exception)
{
}
}
async private Task<dynamic> ReadNextMessage()
{
byte[] buffer = new byte[4];
int ret = -1;
ret = await client.GetStream().ReadAsync(buffer, 0, 4);
if (ret == 0 || ret < 0)
{
// Disconnected
throw new IOException();
}
int length = buffer[0]
| (buffer[1] << 8) | (buffer[2] << 16) | (buffer[3] << 24);
if (length == 0 || length > 1000 * 1000 * 10)
{
throw new IOException();
}
buffer = new byte[length];
ret = await client.GetStream().ReadAsync(buffer, 0, length);
if (ret == 0 || ret < 0)
{
// Disconnected
throw new IOException();
}
else
{
return DynamicJson.Parse(Encoding.UTF8.GetString(buffer));
}
}
async private Task SendMessage(byte[] buffer)
{
if (client == null)
{
return;
}
int length = buffer.Length;
byte[] packet = new byte[4 + buffer.Length];
packet[0] = (byte)length;
packet[1] = (byte)(length >> 8);
packet[2] = (byte)(length >> 16);
packet[3] = (byte)(length >> 24);
Array.Copy(buffer, 0, packet, 4, buffer.Length);
await client.GetStream().WriteAsync(packet, 0, packet.Length);
}
async private Task ReplyMessage(int requestId, string s)
{
string str = DynamicJson.Serialize(new
{
requestId = requestId,
result = s
});
await SendMessage(Encoding.UTF8.GetBytes(str));
}
async private Task SendCommand(string s)
{
string str = DynamicJson.Serialize(new
{
requestId = RequestId++,
command = s
});
await SendMessage(Encoding.UTF8.GetBytes(str));
}
}
}
| 27.954023
| 88
| 0.422903
|
[
"MIT",
"BSD-3-Clause"
] |
CHOI-HOGI/ALVR
|
ALVR/ClientSocket.cs
| 4,866
|
C#
|
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Windows;
using System.Windows.Controls;
using andrefmello91.Extensions;
using andrefmello91.Material.Reinforcement;
using andrefmello91.SPMElements.StringerProperties;
using SPMTool.Annotations;
using SPMTool.Core;
using SPMTool.Core.Elements;
using SPMTool.Enums;
using UnitsNet;
using UnitsNet.Units;
using static SPMTool.Core.SPMModel;
namespace SPMTool.Application.UserInterface
{
/// <summary>
/// Lógica interna para StringerGeometryWindow.xaml
/// </summary>
public partial class StringerWindow : INotifyPropertyChanged
{
#region Fields
private readonly SPMModel _database;
private readonly LengthUnit _geometryUnit;
private readonly LengthUnit _reinforcementUnit;
private readonly PressureUnit _stressUnit;
private readonly List<StringerObject> _stringers;
private bool _reinforcementChecked, _setGeometry, _setReinforcement;
#endregion
#region Properties
public string DiameterUnit => _reinforcementUnit.Abbrev();
// Properties
public string GeometryUnit => _geometryUnit.Abbrev();
/// <summary>
/// Get header text.
/// </summary>
public string HeaderText => _stringers.Count == 1
? $"Stringer {_stringers[0].Number}"
: $"{_stringers.Count} stringers selected";
/// <summary>
/// Gets and sets reinforcement checkbox state.
/// </summary>
public bool ReinforcementChecked
{
get => _reinforcementChecked;
set
{
// if (value)
// {
// ReinforcementBoxes.Enable();
//
// if (_database.Steels.Any())
// SavedSteel.Enable();
//
// if (_database.StringerReinforcements.Any())
// SavedReinforcement.Enable();
// }
// else
// {
// ReinforcementBoxes.Disable();
//
// if (_database.Steels.Any())
// SavedSteel.Disable();
//
// if (_database.StringerReinforcements.Any())
// SavedReinforcement.Disable();
// }
_reinforcementChecked = value;
OnPropertyChanged();
}
}
/// <summary>
/// Get and set option to save geometry to all stringers.
/// </summary>
public bool SetGeometry
{
get => _setGeometry;
set
{
_setGeometry = value;
OnPropertyChanged();
}
}
/// <summary>
/// Get and set option to save reinforcement to all stringers.
/// </summary>
public bool SetReinforcement
{
get => _setReinforcement;
set
{
_setReinforcement = value;
OnPropertyChanged();
}
}
public string StressUnit => _stressUnit.Abbrev();
/// <summary>
/// Get/set bar diameter.
/// </summary>
private Length BarDiameter
{
get => Length.From(double.Parse(PhiBox.Text), _reinforcementUnit);
set => PhiBox.Text = $"{value.As(_reinforcementUnit):F3}";
}
/// <summary>
/// Get/set bar elastic module, in MPa.
/// </summary>
private Pressure ElasticModule
{
get => Pressure.From(double.Parse(EBox.Text), _stressUnit);
set => EBox.Text = $"{value.As(_stressUnit):F3}";
}
/// <summary>
/// Get geometry <see cref="TextBox" />'s.
/// </summary>
private IEnumerable<TextBox> GeometryBoxes => new[] { WBox, HBox };
/// <summary>
/// Verify if geometry text boxes are filled.
/// </summary>
private bool GeometryFilled => CheckBoxes(GeometryBoxes);
/// <summary>
/// Get/set number of bars.
/// </summary>
private int NumOfBars
{
get => int.Parse(NumBox.Text);
set => NumBox.Text = $"{value:0}";
}
/// <summary>
/// Get cross section for output.
/// </summary>
private CrossSection OutputCrossSection
{
get => new(StrWidth, StrHeight);
set
{
StrWidth = value.Width;
StrHeight = value.Height;
}
}
/// <summary>
/// Get reinforcement for output.
/// </summary>
private UniaxialReinforcement? OutputReinforcement
{
get => ReinforcementChecked ? new UniaxialReinforcement(NumOfBars, BarDiameter, OutputSteel!, Area.Zero) : null;
set
{
NumOfBars = value?.NumberOfBars ?? 2;
BarDiameter = value?.BarDiameter ?? Length.FromMillimeters(10);
}
}
/// <summary>
/// Get steel for output.
/// </summary>
private SteelParameters? OutputSteel
{
get => new(YieldStress, ElasticModule);
set
{
YieldStress = value?.YieldStress ?? Pressure.FromMegapascals(500);
ElasticModule = value?.ElasticModule ?? Pressure.FromMegapascals(210000);
}
}
/// <summary>
/// Get reinforcement <see cref="TextBox" />'s.
/// </summary>
private IEnumerable<TextBox> ReinforcementBoxes => new[] { NumBox, PhiBox, FBox, EBox };
/// <summary>
/// Verify if reinforcement text boxes are filled.
/// </summary>
private bool ReinforcementFilled => CheckBoxes(ReinforcementBoxes);
/// <summary>
/// Get/set height.
/// </summary>
private Length StrHeight
{
get => Length.From(double.Parse(HBox.Text), _geometryUnit);
set => HBox.Text = $"{value.As(_geometryUnit):F3}";
}
/// <summary>
/// Get/set width.
/// </summary>
private Length StrWidth
{
get => Length.From(double.Parse(WBox.Text), _geometryUnit);
set => WBox.Text = $"{value.As(_geometryUnit):F3}";
}
/// <summary>
/// Get/set bar yield stress.
/// </summary>
private Pressure YieldStress
{
get => Pressure.From(double.Parse(FBox.Text), _stressUnit);
set => FBox.Text = $"{value.As(_stressUnit):F3}";
}
#endregion
#region Events
public event PropertyChangedEventHandler? PropertyChanged;
#endregion
#region Constructors
public StringerWindow(IEnumerable<StringerObject> stringers)
{
_stringers = stringers.ToList();
_database = ActiveModel;
_stressUnit = _database.Settings.Units.MaterialStrength;
_geometryUnit = _database.Settings.Units.Geometry;
_reinforcementUnit = _database.Settings.Units.Reinforcement;
DataContext = this;
InitializeComponent();
// Get stringer image
CrossSection.Source = Icons.GetBitmap(Properties.Resources.stringer_cross_section);
GetInitialGeometry();
GetInitialReinforcement();
}
#endregion
#region Methods
/// <summary>
/// Get saved steel options as string collection.
/// </summary>
/// <returns></returns>
public static IEnumerable<string> SavedSteelOptions(SPMModel database) => database.Steels.Distinct()
.Select(s => $"{s.YieldStress.As(database.Settings.Units.MaterialStrength):F3} | {s.ElasticModule.As(database.Settings.Units.MaterialStrength):F3}");
/// <summary>
/// Get saved geometry options as string collection.
/// </summary>
/// <returns></returns>
private static IEnumerable<string> SavedGeoOptions(SPMModel database) => database.StringerCrossSections.Distinct()
.Select(geo => $"{geo.Width.As(database.Settings.Units.Geometry):F3} {(char) Character.Times} {geo.Height.As(database.Settings.Units.Geometry):F3}");
/// <summary>
/// Get saved reinforcement options as string collection.
/// </summary>
/// <returns></returns>
private static IEnumerable<string> SavedRefOptions(SPMModel database) => database.StringerReinforcements.Distinct()
.Select(r => $"{r.NumberOfBars:0} {(char) Character.Phi} {r.BarDiameter.As(database.Settings.Units.Reinforcement):F3}");
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
/// <summary>
/// Get the initial geometry data of stringers.
/// </summary>
private void GetInitialGeometry()
{
SetGeometry = true;
if (!_database.StringerCrossSections.IsNullOrEmpty())
{
SavedGeometries.ItemsSource = SavedGeoOptions(_database);
SavedGeometries.SelectedIndex = _stringers.Count == 1
? _database.StringerCrossSections.IndexOf(_stringers[0].CrossSection)
: 0;
OutputCrossSection = _stringers.Count == 1
? _stringers[0].CrossSection
: _database.StringerCrossSections[0];
return;
}
SavedGeometries.Disable();
StrWidth = Length.FromMillimeters(100);
StrHeight = Length.FromMillimeters(100);
}
/// <summary>
/// Get the initial reinforcement data stringers.
/// </summary>
private void GetInitialReinforcement()
{
SetReinforcement = true;
if (!_database.Steels.IsNullOrEmpty())
{
SavedSteel.ItemsSource = SavedSteelOptions(_database);
SavedSteel.SelectedIndex = 0;
if (_stringers.Count > 1)
OutputSteel = _database.Steels[0];
}
else
{
SavedSteel.Disable();
OutputSteel = null;
}
if (!_database.StringerReinforcements.IsNullOrEmpty())
{
SavedReinforcement.ItemsSource = SavedRefOptions(_database);
SavedReinforcement.SelectedIndex = 0;
if (_stringers.Count > 1)
OutputReinforcement = _database.StringerReinforcements[0];
}
else
{
SavedReinforcement.Disable();
OutputReinforcement = null;
}
if (_stringers.Count == 1)
{
var reinforcement = _stringers[0].Reinforcement;
ReinforcementChecked = reinforcement is not null;
OutputReinforcement = reinforcement;
OutputSteel = reinforcement?.Steel;
}
else
{
ReinforcementChecked = false;
}
}
/// <summary>
/// Save data in the stringer object.
/// </summary>
private void SaveGeometry()
{
var crossSection = OutputCrossSection;
_database.StringerCrossSections.Add(crossSection);
// Set to stringers
foreach (var str in _stringers)
str.CrossSection = crossSection;
}
/// <summary>
/// Save data in the stringer object.
/// </summary>
private void SaveReinforcement()
{
var reinforcement = OutputReinforcement;
_database.StringerReinforcements.Add(reinforcement);
// Set to stringers
foreach (var str in _stringers)
str.Reinforcement = reinforcement;
}
private void ButtonOK_OnClick(object sender, RoutedEventArgs e)
{
// Check geometry
if (SetGeometry)
{
if (!GeometryFilled)
{
MessageBox.Show("Please set positive and non zero values for stringer geometry.", "Alert");
return;
}
SaveGeometry();
}
// Check if reinforcement is set
if (SetReinforcement)
{
if (ReinforcementChecked && !ReinforcementFilled)
{
MessageBox.Show("Please set positive and non zero values for reinforcement properties or uncheck reinforcement checkbox.", "Alert");
return;
}
SaveReinforcement();
}
Close();
}
private void SavedGeometries_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
var box = (ComboBox) sender;
// Get index
var i = box.SelectedIndex;
if (i >= _database.StringerCrossSections.Count || i < 0)
return;
// Update textboxes
OutputCrossSection = _database.StringerCrossSections[i];
}
private void SavedReinforcement_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
var box = (ComboBox) sender;
// Get index
var i = box.SelectedIndex;
if (i >= _database.StringerReinforcements.Count || i < 0)
return;
// Update textboxes
OutputReinforcement = _database.StringerReinforcements[i];
}
private void SavedSteel_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
var box = (ComboBox) sender;
// Get index
var i = box.SelectedIndex;
if (i >= _database.Steels.Count || i < 0)
return;
// Update textboxes
OutputSteel = _database.Steels[i];
}
#endregion
}
}
| 24.619958
| 152
| 0.673508
|
[
"MIT"
] |
andrefmello91/SPMTool
|
SPMTool/UserInterface/Windows/StringerWindow.xaml.cs
| 11,599
|
C#
|
using System;
using System.Collections.Generic;
using System.Text;
namespace KDTreeDLL
{
/// <summary>
/// Bjoern Heckel's solution to the KD-Tree n-nearest-neighbor problem
/// </summary>
class NearestNeighborList
{
public static int REMOVE_HIGHEST = 1;
public static int REMOVE_LOWEST = 2;
PriorityQueue m_Queue = null;
int m_Capacity = 0;
// constructor
public NearestNeighborList(int capacity)
{
m_Capacity = capacity;
m_Queue = new PriorityQueue(m_Capacity, Double.PositiveInfinity);
}
public double getMaxPriority()
{
if (m_Queue.length() == 0)
{
return Double.PositiveInfinity;
}
return m_Queue.getMaxPriority();
}
public bool insert(Object _object, double priority)
{
if (m_Queue.length() < m_Capacity)
{
// capacity not reached
m_Queue.add(_object, priority);
return true;
}
if (priority > m_Queue.getMaxPriority())
{
// do not insert - all elements in queue have lower priority
return false;
}
// remove object with highest priority
m_Queue.remove();
// add new object
m_Queue.add(_object, priority);
return true;
}
public bool isCapacityReached()
{
return m_Queue.length() >= m_Capacity;
}
public Object getHighest()
{
return m_Queue.front();
}
public bool isEmpty()
{
return m_Queue.length() == 0;
}
public int getSize()
{
return m_Queue.length();
}
public Object removeHighest()
{
// remove object with highest priority
return m_Queue.remove();
}
}
}
| 24.426829
| 77
| 0.510734
|
[
"MIT"
] |
ctyeong/unitytool
|
Assets/Scripts/KD Tree/NearestNeighborList.cs
| 2,003
|
C#
|
//------------------------------------------------------------------------------
// <auto-generated>
// Il codice è stato generato da uno strumento.
// Versione runtime:4.0.30319.42000
//
// Le modifiche apportate a questo file possono provocare un comportamento non corretto e andranno perse se
// il codice viene rigenerato.
// </auto-generated>
//------------------------------------------------------------------------------
namespace SDS1_s_Sidekick.Properties {
using System;
/// <summary>
/// Classe di risorse fortemente tipizzata per la ricerca di stringhe localizzate e così via.
/// </summary>
// Questa classe è stata generata automaticamente dalla classe StronglyTypedResourceBuilder.
// tramite uno strumento quale ResGen o Visual Studio.
// Per aggiungere o rimuovere un membro, modificare il file con estensione ResX ed eseguire nuovamente ResGen
// con l'opzione /str oppure ricompilare il progetto VS.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Restituisce l'istanza di ResourceManager nella cache utilizzata da questa classe.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("SDS1_s_Sidekick.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Esegue l'override della proprietà CurrentUICulture del thread corrente per tutte le
/// ricerche di risorse eseguite utilizzando questa classe di risorse fortemente tipizzata.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Cerca una risorsa localizzata di tipo System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap Logo {
get {
object obj = ResourceManager.GetObject("Logo", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
}
}
| 45.405405
| 181
| 0.622917
|
[
"MIT"
] |
Liquid-S/SDSE1-s-Sidekick
|
Properties/Resources.Designer.cs
| 3,366
|
C#
|
using System;
using System.Collections.Generic;
namespace Ystervark.Database.Models
{
public partial class Journey
{
public Journey()
{
JourneyRoute = new HashSet<JourneyRoute>();
}
public int Id { get; set; }
public DateTime TravelDate { get; set; }
public double TotalDistance { get; set; }
public double OriginLatitude { get; set; }
public double OriginLongitude { get; set; }
public double DestinationLatitude { get; set; }
public double DestinationLongitude { get; set; }
public int ResourceId { get; set; }
public double OriginToTenantDistance { get; set; }
public double DestinationToTenantDistance { get; set; }
public Resource Resource { get; set; }
public ICollection<JourneyRoute> JourneyRoute { get; set; }
}
}
| 31.107143
| 67
| 0.628014
|
[
"Unlicense",
"MIT"
] |
Programm3r/Ystervark
|
Ystervark.Database/Models/Journey.cs
| 873
|
C#
|
// Copyright 2020 Google LLC
//
// 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 NSubstitute;
using NUnit.Framework;
using YetiVSI.DebugEngine.Variables;
namespace YetiVSI.Test.DebugEngine.Variables
{
[TestFixture]
class FormatSpecifierUtilTests
{
[Test]
public void HasRawFormatSpecifier()
{
Assert.That(FormatSpecifierUtil.HasRawFormatSpecifier(null), Is.False);
Assert.That(FormatSpecifierUtil.HasRawFormatSpecifier(string.Empty), Is.False);
Assert.That(FormatSpecifierUtil.HasRawFormatSpecifier("!"), Is.True);
Assert.That(FormatSpecifierUtil.HasRawFormatSpecifier(" ! "), Is.True);
Assert.That(FormatSpecifierUtil.HasRawFormatSpecifier("!!"), Is.True);
Assert.That(FormatSpecifierUtil.HasRawFormatSpecifier(" !! "), Is.True);
Assert.That(FormatSpecifierUtil.HasRawFormatSpecifier("!x"), Is.True);
Assert.That(FormatSpecifierUtil.HasRawFormatSpecifier(" !x "), Is.True);
Assert.That(FormatSpecifierUtil.HasRawFormatSpecifier("!!x"), Is.True);
Assert.That(FormatSpecifierUtil.HasRawFormatSpecifier(" !!x "), Is.True);
Assert.That(FormatSpecifierUtil.HasRawFormatSpecifier(" 3!!x "), Is.True);
Assert.That(FormatSpecifierUtil.HasRawFormatSpecifier("!!view(a) "), Is.True);
Assert.That(FormatSpecifierUtil.HasRawFormatSpecifier(" !expand(a) "), Is.True);
Assert.That(FormatSpecifierUtil.HasRawFormatSpecifier(" [n]!x "), Is.True);
Assert.That(FormatSpecifierUtil.HasRawFormatSpecifier(" [!n]x "), Is.False);
Assert.That(FormatSpecifierUtil.HasRawFormatSpecifier("x"), Is.False);
Assert.That(FormatSpecifierUtil.HasRawFormatSpecifier("x!"), Is.False);
Assert.That(FormatSpecifierUtil.HasRawFormatSpecifier("x!!"), Is.False);
}
[Test]
public void RemoveRawFormatSpecifier()
{
Assert.That(FormatSpecifierUtil.RemoveRawFormatSpecifierPrefix(null),
Is.EqualTo(string.Empty));
Assert.That(FormatSpecifierUtil.RemoveRawFormatSpecifierPrefix(string.Empty),
Is.EqualTo(string.Empty));
Assert.That(FormatSpecifierUtil.RemoveRawFormatSpecifierPrefix("!"),
Is.EqualTo(string.Empty));
Assert.That(FormatSpecifierUtil.RemoveRawFormatSpecifierPrefix(" ! "),
Is.EqualTo(string.Empty));
Assert.That(FormatSpecifierUtil.RemoveRawFormatSpecifierPrefix("!!"),
Is.EqualTo(string.Empty));
Assert.That(FormatSpecifierUtil.RemoveRawFormatSpecifierPrefix(" !! "),
Is.EqualTo(string.Empty));
Assert.That(FormatSpecifierUtil.RemoveRawFormatSpecifierPrefix("!x"), Is.EqualTo("x"));
Assert.That(FormatSpecifierUtil.RemoveRawFormatSpecifierPrefix(" !expand(3) "),
Is.EqualTo("expand(3)"));
Assert.That(FormatSpecifierUtil.RemoveRawFormatSpecifierPrefix("!!x"), Is.EqualTo("x"));
Assert.That(FormatSpecifierUtil.RemoveRawFormatSpecifierPrefix(" !!view(simple) "),
Is.EqualTo("view(simple)"));
Assert.That(FormatSpecifierUtil.RemoveRawFormatSpecifierPrefix("x"), Is.EqualTo("x"));
Assert.That(FormatSpecifierUtil.RemoveRawFormatSpecifierPrefix("x!"), Is.EqualTo("x!"));
}
[Test]
public void SuppressMemoryAddress()
{
Assert.That(FormatSpecifierUtil.SuppressMemoryAddress(null), Is.False);
Assert.That(FormatSpecifierUtil.SuppressMemoryAddress(string.Empty), Is.False);
Assert.That(FormatSpecifierUtil.SuppressMemoryAddress("!"), Is.False);
Assert.That(FormatSpecifierUtil.SuppressMemoryAddress("!!"), Is.False);
Assert.That(FormatSpecifierUtil.SuppressMemoryAddress("na"), Is.True);
Assert.That(FormatSpecifierUtil.SuppressMemoryAddress("!na"), Is.True);
Assert.That(FormatSpecifierUtil.SuppressMemoryAddress(" !na "), Is.True);
Assert.That(FormatSpecifierUtil.SuppressMemoryAddress("!!na"), Is.True);
Assert.That(FormatSpecifierUtil.SuppressMemoryAddress(" !!na "), Is.True);
Assert.That(FormatSpecifierUtil.SuppressMemoryAddress(" 3!na "), Is.True);
Assert.That(FormatSpecifierUtil.SuppressMemoryAddress(" [3]s "), Is.True);
Assert.That(FormatSpecifierUtil.SuppressMemoryAddress("!x"), Is.False);
Assert.That(FormatSpecifierUtil.SuppressMemoryAddress(" !x "), Is.False);
Assert.That(FormatSpecifierUtil.SuppressMemoryAddress("! x "), Is.False);
Assert.That(FormatSpecifierUtil.SuppressMemoryAddress("!!x"), Is.False);
Assert.That(FormatSpecifierUtil.SuppressMemoryAddress(" !!x "), Is.False);
Assert.That(FormatSpecifierUtil.SuppressMemoryAddress("!! x "), Is.False);
}
[Test]
public void GetChildFormatSpecifier_NotInherited()
{
var formatMock = Substitute.For<IRemoteValueFormat>();
formatMock.ShouldInheritFormatSpecifier().Returns(false);
Assert.That(FormatSpecifierUtil.GetChildFormatSpecifier("spec", formatMock),
Is.EqualTo(string.Empty));
Assert.That(FormatSpecifierUtil.GetChildFormatSpecifier("!spec", formatMock),
Is.EqualTo(string.Empty));
Assert.That(FormatSpecifierUtil.GetChildFormatSpecifier("!!spec", formatMock),
Is.EqualTo("!!"));
Assert.That(FormatSpecifierUtil.GetChildFormatSpecifier(" !!spec ", formatMock),
Is.EqualTo("!!"));
}
[Test]
public void TrySplitSpecifier_Empty()
{
bool result = FormatSpecifierUtil.TrySplitSpecifier("", out string size, out string raw,
out string baseSpecifier);
Assert.That(result, Is.True);
Assert.That(size, Is.EqualTo(""));
Assert.That(raw, Is.EqualTo(""));
Assert.That(baseSpecifier, Is.EqualTo(""));
}
[Test]
public void TrySplitSpecifier_BaseOnly()
{
bool result = FormatSpecifierUtil.TrySplitSpecifier(
"x", out string size, out string raw, out string baseSpecifier);
Assert.That(result, Is.True);
Assert.That(size, Is.EqualTo(""));
Assert.That(raw, Is.EqualTo(""));
Assert.That(baseSpecifier, Is.EqualTo("x"));
}
[Test]
public void TrySplitSpecifier_RawBase()
{
bool result = FormatSpecifierUtil.TrySplitSpecifier(
"!Hb", out string size, out string raw, out string baseSpecifier);
Assert.That(result, Is.True);
Assert.That(size, Is.EqualTo(""));
Assert.That(raw, Is.EqualTo("!"));
Assert.That(baseSpecifier, Is.EqualTo("Hb"));
}
[Test]
public void TrySplitSpecifier_RawOnly()
{
bool result = FormatSpecifierUtil.TrySplitSpecifier(
"!", out string size, out string raw, out string baseSpecifier);
Assert.That(result, Is.True);
Assert.That(size, Is.EqualTo(""));
Assert.That(raw, Is.EqualTo("!"));
Assert.That(baseSpecifier, Is.EqualTo(""));
}
[Test]
public void TrySplitSpecifier_Size()
{
bool result = FormatSpecifierUtil.TrySplitSpecifier(
"10", out string size, out string raw, out string baseSpecifier);
Assert.That(result, Is.True);
Assert.That(size, Is.EqualTo("10"));
Assert.That(raw, Is.EqualTo(""));
Assert.That(baseSpecifier, Is.EqualTo(""));
}
[Test]
public void TrySplitSpecifier_SizeBase()
{
bool result = FormatSpecifierUtil.TrySplitSpecifier(
"10o", out string size, out string raw, out string baseSpecifier);
Assert.That(result, Is.True);
Assert.That(size, Is.EqualTo("10"));
Assert.That(raw, Is.EqualTo(""));
Assert.That(baseSpecifier, Is.EqualTo("o"));
}
[Test]
public void TrySplitSpecifier_SizeHexBase()
{
bool result = FormatSpecifierUtil.TrySplitSpecifier(
"0xabx", out string size, out string raw, out string baseSpecifier);
Assert.That(result, Is.True);
Assert.That(size, Is.EqualTo("0xab"));
Assert.That(raw, Is.EqualTo(""));
Assert.That(baseSpecifier, Is.EqualTo("x"));
}
[Test]
public void TrySplitSpecifier_SizeExpression()
{
bool result = FormatSpecifierUtil.TrySplitSpecifier(
"[expr]", out string size, out string raw, out string baseSpecifier);
Assert.That(result, Is.True);
Assert.That(size, Is.EqualTo("[expr]"));
Assert.That(raw, Is.EqualTo(""));
Assert.That(baseSpecifier, Is.EqualTo(""));
}
[Test]
public void TrySplitSpecifier_SizeExpressionBracket()
{
bool result = FormatSpecifierUtil.TrySplitSpecifier(
"[a[i]]", out string size, out string raw, out string baseSpecifier);
Assert.That(result, Is.True);
Assert.That(size, Is.EqualTo("[a[i]]"));
Assert.That(raw, Is.EqualTo(""));
Assert.That(baseSpecifier, Is.EqualTo(""));
}
[Test]
public void TrySplitSpecifier_SizeExpressionBase()
{
bool result = FormatSpecifierUtil.TrySplitSpecifier(
"[a[i]]x", out string size, out string raw, out string baseSpecifier);
Assert.That(result, Is.True);
Assert.That(size, Is.EqualTo("[a[i]]"));
Assert.That(raw, Is.EqualTo(""));
Assert.That(baseSpecifier, Is.EqualTo("x"));
}
[Test]
public void TrySplitSpecifier_SizeExpressionWithDoubleQuotesBase()
{
bool result = FormatSpecifierUtil.TrySplitSpecifier(
"[f(a, \"]c\")]Xb", out string size, out string raw, out string baseSpecifier);
Assert.That(result, Is.True);
Assert.That(size, Is.EqualTo("[f(a, \"]c\")]"));
Assert.That(raw, Is.EqualTo(""));
Assert.That(baseSpecifier, Is.EqualTo("Xb"));
}
[Test]
public void TrySplitSpecifier_SizeExpressionRawBase()
{
bool result = FormatSpecifierUtil.TrySplitSpecifier(
"[a[i]]!!x", out string size, out string raw, out string baseSpecifier);
Assert.That(result, Is.True);
Assert.That(size, Is.EqualTo("[a[i]]"));
Assert.That(raw, Is.EqualTo("!!"));
Assert.That(baseSpecifier, Is.EqualTo("x"));
}
[Test]
public void TrySplitSpecifier_InvalidRaw()
{
bool result = FormatSpecifierUtil.TrySplitSpecifier(
"!!!", out string size, out string raw, out string baseSpecifier);
Assert.That(result, Is.False);
}
[Test]
public void GetChildFormatSpecifier_Inherited()
{
var formatMock = Substitute.For<IRemoteValueFormat>();
formatMock.ShouldInheritFormatSpecifier().Returns(true);
Assert.That(FormatSpecifierUtil.GetChildFormatSpecifier("spec", formatMock),
Is.EqualTo("spec"));
Assert.That(FormatSpecifierUtil.GetChildFormatSpecifier("!spec", formatMock),
Is.EqualTo("spec"));
Assert.That(FormatSpecifierUtil.GetChildFormatSpecifier("!!spec", formatMock),
Is.EqualTo("!!spec"));
Assert.That(FormatSpecifierUtil.GetChildFormatSpecifier(" !!spec ", formatMock),
Is.EqualTo("!!spec"));
}
[Test]
public void GetChildFormatSpecifier_Expand_NotInherited()
{
Assert.That(FormatSpecifierUtil.GetChildFormatSpecifier("expand(1)", null),
Is.EqualTo(""));
Assert.That(FormatSpecifierUtil.GetChildFormatSpecifier("!expand(1)", null),
Is.EqualTo(""));
Assert.That(FormatSpecifierUtil.GetChildFormatSpecifier("!!expand(1)", null),
Is.EqualTo("!!"));
}
[Test]
public void GetChildFormatSpecifier_View_Inherited()
{
Assert.That(FormatSpecifierUtil.GetChildFormatSpecifier("view(simple)", null),
Is.EqualTo("view(simple)"));
Assert.That(FormatSpecifierUtil.GetChildFormatSpecifier("!view(simple)", null),
Is.EqualTo("view(simple)"));
Assert.That(FormatSpecifierUtil.GetChildFormatSpecifier("!!view(simple)", null),
Is.EqualTo("!!view(simple)"));
}
}
}
| 47.346021
| 100
| 0.602938
|
[
"Apache-2.0"
] |
googlestadia/vsi-lldb
|
YetiVSI.Tests/DebugEngine/Variables/FormatSpecifierUtilTests.cs
| 13,683
|
C#
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//
using System;
using System.Collections.Generic;
using System.Text;
namespace XUnitWrapperLibrary;
public class TestFilter
{
public interface ISearchClause
{
bool IsMatch(string fullyQualifiedName, string displayName, string[] traits);
}
public enum TermKind
{
FullyQualifiedName,
DisplayName
}
public sealed class NameClause : ISearchClause
{
public NameClause(TermKind kind, string filter, bool substring)
{
Kind = kind;
Filter = filter;
Substring = substring;
}
public TermKind Kind { get; }
public string Filter { get; }
public bool Substring { get; }
public bool IsMatch(string fullyQualifiedName, string displayName, string[] traits)
{
string stringToSearch = Kind switch
{
TermKind.FullyQualifiedName => fullyQualifiedName,
TermKind.DisplayName => displayName,
_ => throw new InvalidOperationException()
};
if (Substring)
{
return stringToSearch.Contains(Filter);
}
return stringToSearch == Filter;
}
}
public sealed class AndClause : ISearchClause
{
private ISearchClause _left;
private ISearchClause _right;
public AndClause(ISearchClause left, ISearchClause right)
{
_left = left;
_right = right;
}
public bool IsMatch(string fullyQualifiedName, string displayName, string[] traits) => _left.IsMatch(fullyQualifiedName, displayName, traits) && _right.IsMatch(fullyQualifiedName, displayName, traits);
}
public sealed class OrClause : ISearchClause
{
private ISearchClause _left;
private ISearchClause _right;
public OrClause(ISearchClause left, ISearchClause right)
{
_left = left;
_right = right;
}
public bool IsMatch(string fullyQualifiedName, string displayName, string[] traits) => _left.IsMatch(fullyQualifiedName, displayName, traits) || _right.IsMatch(fullyQualifiedName, displayName, traits);
}
public sealed class NotClause : ISearchClause
{
private ISearchClause _inner;
public NotClause(ISearchClause inner)
{
_inner = inner;
}
public bool IsMatch(string fullyQualifiedName, string displayName, string[] traits) => !_inner.IsMatch(fullyQualifiedName, displayName, traits);
}
private ISearchClause? _filter;
public TestFilter(string filterString)
{
if (filterString.IndexOfAny(new[] { '!', '(', ')', '~', '=' }) != -1)
{
throw new ArgumentException("Complex test filter expressions are not supported today. The only filters supported today are the simple form supported in 'dotnet test --filter' (substrings of the test's fully qualified name). If further filtering options are desired, file an issue on dotnet/runtime for support.", nameof(filterString));
}
_filter = new NameClause(TermKind.FullyQualifiedName, filterString, substring: true);
}
public TestFilter(ISearchClause filter)
{
_filter = filter;
}
public bool ShouldRunTest(string fullyQualifiedName, string displayName, string[]? traits = null) => _filter is null ? true : _filter.IsMatch(fullyQualifiedName, displayName, traits ?? Array.Empty<string>());
}
| 33.302752
| 347
| 0.644077
|
[
"MIT"
] |
333fred/runtime
|
src/tests/Common/XUnitWrapperLibrary/TestFilter.cs
| 3,630
|
C#
|
/*
Write a program that converts a string to a sequence of C# Unicode character literals.
Examples:
INPUT OUTPUT
Hi! \0057\0068\0061\0074\003f\0021\003f
What?!? \0057\0068\0061\0074\003f\0021\003f
SoftUni \0053\006f\0066\0074\0055\006e\0069
*/
namespace UnicodeCharacters
{
using System;
class UnicodeCharacters
{
static void Main()
{
string input = Console.ReadLine();
if (input != null)
{
Console.Clear();
foreach (var symbol in input)
{
Console.Write("\\u{0:x4}", (int)symbol);
}
Console.WriteLine("\r\n");
}
}
}
}
| 25.264706
| 91
| 0.43539
|
[
"MIT"
] |
idmitrov/CSharp-Part2
|
Strings and Text Processing/UnicodeCharacters.cs
| 861
|
C#
|
using System;
using System.Collections.Generic;
using Department.Base.Model.Common;
namespace Department.Base.Model.Order
{
/// <summary>
/// Represents operation
/// </summary>
public partial class Operation
{
public Operation()
{
ChildrenOperations = new List<Operation>();
DynamicProperties = new List<DynamicProperty>();
}
/// <summary>
/// Operation type string representation (CustomerOrder, Shipment etc)
/// </summary>
/// <value>Operation type string representation (CustomerOrder, Shipment etc)</value>
public string OperationType { get; set; }
/// <summary>
/// Unique user friendly document number (generate automatically based on special algorithm realization)
/// </summary>
/// <value>Unique user friendly document number (generate automatically based on special algorithm realization)</value>
public string Number { get; set; }
/// <summary>
/// Flag can be used to refer to a specific order status in a variety of user scenarios with combination of Status
/// (Order completion, Shipment send etc)
/// </summary>
/// <value>
/// Flag can be used to refer to a specific order status in a variety of user scenarios with combination of Status
/// (Order completion, Shipment send etc)
/// </value>
public bool? IsApproved { get; set; }
/// <summary>
/// Current operation status may have any values defined by concrete business process
/// </summary>
/// <value>Current operation status may have any values defined by concrete business process</value>
public string Status { get; set; }
/// <summary>
/// Gets or Sets Comment
/// </summary>
public string Comment { get; set; }
/// <summary>
/// Currecy code
/// </summary>
/// <value>Currecy code</value>
public Currency Currency { get; set; }
/// <summary>
/// Gets or Sets TaxIncluded
/// </summary>
public bool? TaxIncluded { get; set; }
/// <summary>
/// Money amount without tax
/// </summary>
/// <value>Money amount without tax</value>
public Money Sum { get; set; }
/// <summary>
/// Tax total
/// </summary>
/// <value>Tax total</value>
public Money Tax { get; set; }
/// <summary>
/// Gets or Sets IsCancelled
/// </summary>
public bool? IsCancelled { get; set; }
/// <summary>
/// Gets or Sets CancelledDate
/// </summary>
public DateTime? CancelledDate { get; set; }
/// <summary>
/// Gets or Sets CancelReason
/// </summary>
public string CancelReason { get; set; }
/// <summary>
/// Used for construct hierarchy of operation and represent parent operation id
/// </summary>
/// <value>Used for construct hierarchy of operation and represent parent operation id</value>
public string ParentOperationId { get; set; }
/// <summary>
/// Gets or Sets ChildrenOperations
/// </summary>
public IList<Operation> ChildrenOperations { get; set; }
/// <summary>
/// Used for dynamic properties management, contains object type string
/// </summary>
/// <value>Used for dynamic properties management, contains object type string</value>
public string ObjectType { get; set; }
/// <summary>
/// Dynamic properties collections
/// </summary>
/// <value>Dynamic properties collections</value>
public IList<DynamicProperty> DynamicProperties { get; set; }
/// <summary>
/// Gets or Sets CreatedDate
/// </summary>
public DateTime? CreatedDate { get; set; }
/// <summary>
/// Gets or Sets ModifiedDate
/// </summary>
public DateTime? ModifiedDate { get; set; }
/// <summary>
/// Gets or Sets CreatedBy
/// </summary>
public string CreatedBy { get; set; }
/// <summary>
/// Gets or Sets ModifiedBy
/// </summary>
public string ModifiedBy { get; set; }
/// <summary>
/// Gets or Sets Id
/// </summary>
public string Id { get; set; }
}
}
| 32.649635
| 127
| 0.565616
|
[
"Apache-2.0"
] |
takemurakimio/department-store
|
DepartmentStoreOne.Base.Model/Order/Operation.cs
| 4,473
|
C#
|
namespace Command.SwitchExample
{
using System.Collections.Generic;
/// <summary>
/// The Invoker class
/// </summary>
public class Switch
{
private readonly List<ICommand> history = new List<ICommand>();
public List<ICommand> History
{
get
{
return this.history;
}
}
public void StoreAndExecute(ICommand command)
{
this.history.Add(command); // optional
command.Execute();
}
}
}
| 20.185185
| 71
| 0.515596
|
[
"MIT"
] |
ElenaStaykova/High-Quality-Code
|
17. Design Patterns/Demo/Behavioral/Command/SwitchExample/Switch.cs
| 547
|
C#
|
namespace ProjectDover
{
public enum GameType
{
UNKNOWN = -1,
NEW_GAME,
LOADED_GAME
}
}
| 12.4
| 24
| 0.532258
|
[
"MIT"
] |
1kevgriff/ProjectDover
|
GameType.cs
| 124
|
C#
|
using fourthAplicattion.Models;
using fourthAplicattion.Services;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using Xamarin.Forms;
using Xamarin.Essentials;
using fourthAplicattion.Views;
namespace fourthAplicattion.ViewModels
{
public class MainViewModel
{
public ObservableCollection<Contact> Contacts { get; }
public ICommand AddContact { get; }
public ICommand DeleteCommand { get; }
public ICommand MoreCommand { get; }
AddUserToContactPage ToContactPage;
private IAlertServices AlertServices;
public MainViewModel(IAlertServices alertServices)
{
Contacts = new ObservableCollection<Contact>();
ToContactPage = new AddUserToContactPage(Contacts);
AddContact = new Command(AddContactToList);
DeleteCommand = new Command<Contact>(DeleteContact);
MoreCommand = new Command<Contact>(OnMoreCommandClick);
AlertServices = alertServices;
}
public async void AddContactToList()
{
await App.Current.MainPage.Navigation.PushAsync(new AddUserToContactPage(Contacts));
}
public void DeleteContact(Contact contact)
{
if(Contacts != null)
{
Contacts.Remove(contact);
}
}
public async void OnMoreCommandClick(Contact contact)
{
var category = await App.Current.MainPage.DisplayActionSheet("Select the option","Cancel",null,new string[] { $"Call +{contact.Number}","Edit"});
if(category != "Edit")
{
try
{
PhoneDialer.Open(contact.Number);
}
catch (ArgumentNullException anEx)
{
string mensaje = anEx.Message;
await AlertServices.DisplayAlert(mensaje);
}
}
else
{
Contacts.Remove(contact);
contact.Name = await App.Current.MainPage.DisplayPromptAsync("Editar el nombre","Digite el nombre","Ok","Cancel");
contact.Number = await App.Current.MainPage.DisplayPromptAsync("Editar el Telefono", "Digite el numero Telefonico", "Ok", "Cancel");
Contacts.Add(new Contact(contact.Name,contact.Number));
}
}
}
}
| 31.82716
| 157
| 0.595811
|
[
"MIT"
] |
walase01/MyFouthAplication
|
fourthAplicattion/fourthAplicattion/ViewModels/MainViewModel.cs
| 2,580
|
C#
|
using System;
using UnityEngine;
using Variables.Floats;
namespace Variables.Vector3s
{
/// <summary>
/// Vector3 reference allowing to switch between constant and variable.
/// </summary>
[Serializable]
public class Vector3Reference : AbstractReference<Vector3, Vector3Variable, Vector3Event>
{
public Vector3Reference(Vector3 defaultConstantValue = new Vector3()) : base(defaultConstantValue)
{
}
}
}
| 26.764706
| 106
| 0.698901
|
[
"MIT"
] |
yanicksenn/unity-variables
|
Runtime/Vector3s/Vector3Reference.cs
| 455
|
C#
|
namespace ShopManage.Web.Views.Shared.Components.TenantChange
{
public class ChangeModalViewModel
{
public string TenancyName { get; set; }
}
}
| 20.625
| 62
| 0.69697
|
[
"MIT"
] |
DSOY/ShopManage
|
aspnet-core/src/ShopManage.Web.Mvc/Views/Shared/Components/TenantChange/ChangeModalViewModel.cs
| 167
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Human
{
internal class Program
{
static void Main(string[] args)
{
int[] array = { 1, 2, 3, };
}
}
}
| 15.444444
| 39
| 0.589928
|
[
"CC0-1.0"
] |
rahmanashraf/Csharp
|
Scrawl-test/Namespace_yoxlamag/Human/Program.cs
| 280
|
C#
|
using PixiEditor.Helpers;
using PixiEditor.Helpers.Extensions;
using PixiEditor.Models.Controllers;
using PixiEditor.Models.DataHolders;
using PixiEditor.Models.Enums;
using PixiEditor.Models.ImageManipulation;
using PixiEditor.Models.Position;
using PixiEditor.Models.Tools.ToolSettings.Toolbars;
using PixiEditor.ViewModels;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using SkiaSharp;
namespace PixiEditor.Models.Tools.Tools
{
internal class SelectTool : ReadonlyTool
{
private readonly RectangleTool rectangleTool;
private readonly CircleTool circleTool;
private IEnumerable<Coordinates> oldSelectedPoints;
private static Selection ActiveSelection { get => ViewModelMain.Current.BitmapManager.ActiveDocument.ActiveSelection; }
private BitmapManager BitmapManager { get; }
public SelectTool(BitmapManager bitmapManager)
{
ActionDisplay = "Click and move to select an area.";
Toolbar = new SelectToolToolbar();
BitmapManager = bitmapManager;
rectangleTool = new RectangleTool();
circleTool = new CircleTool();
}
public SelectionType SelectionType { get; set; } = SelectionType.Add;
public override string Tooltip => "Selects area. (M)";
public override void BeforeUse()
{
base.BeforeUse();
SelectionType = Toolbar.GetEnumSetting<SelectionType>("SelectMode").Value;
oldSelectedPoints = new ReadOnlyCollection<Coordinates>(ActiveSelection.SelectedPoints);
}
public override void AfterUse(SKRectI sessionRect)
{
base.AfterUse(sessionRect);
if (ActiveSelection.SelectedPoints.Count <= 1)
{
// If we have not selected multiple points, clear the selection
ActiveSelection.Clear();
}
SelectionHelpers.AddSelectionUndoStep(ViewModelMain.Current.BitmapManager.ActiveDocument, oldSelectedPoints, SelectionType);
}
public override void Use(IReadOnlyList<Coordinates> pixels)
{
Select(pixels, Toolbar.GetEnumSetting<SelectionShape>("SelectShape").Value);
}
public IEnumerable<Coordinates> GetRectangleSelectionForPoints(Coordinates start, Coordinates end)
{
List<Coordinates> result = new List<Coordinates>();
ToolCalculator.GenerateRectangleNonAlloc(
start, end, true, 1, result);
return result;
}
public IEnumerable<Coordinates> GetCircleSelectionForPoints(Coordinates start, Coordinates end)
{
List<Coordinates> result = new List<Coordinates>();
ToolCalculator.GenerateEllipseNonAlloc(
start, end, true, result);
return result;
}
/// <summary>
/// Gets coordinates of every pixel in root layer.
/// </summary>
/// <returns>Coordinates array of pixels.</returns>
public IEnumerable<Coordinates> GetAllSelection()
{
return GetAllSelection(ViewModelMain.Current.BitmapManager.ActiveDocument);
}
/// <summary>
/// Gets coordinates of every pixel in chosen document.
/// </summary>
/// <returns>Coordinates array of pixels.</returns>
public IEnumerable<Coordinates> GetAllSelection(Document document)
{
return GetRectangleSelectionForPoints(new Coordinates(0, 0), new Coordinates(document.Width - 1, document.Height - 1));
}
private void Select(IReadOnlyList<Coordinates> pixels, SelectionShape shape)
{
IEnumerable<Coordinates> selection;
BitmapManager.ActiveDocument.ActiveSelection.SetSelection(oldSelectedPoints, SelectionType.New);
if (pixels.Count < 2)
{
selection = new List<Coordinates>();
}
else if (shape == SelectionShape.Circle)
{
selection = GetCircleSelectionForPoints(pixels[^1], pixels[0]);
}
else if (shape == SelectionShape.Rectangle)
{
selection = GetRectangleSelectionForPoints(pixels[^1], pixels[0]);
}
else
{
throw new NotImplementedException($"Selection shape '{shape}' has not been implemented");
}
BitmapManager.ActiveDocument.ActiveSelection.SetSelection(selection, SelectionType);
}
}
}
| 36.165354
| 136
| 0.640322
|
[
"MIT"
] |
rebizu/PixiEditor
|
PixiEditor/Models/Tools/Tools/SelectTool.cs
| 4,595
|
C#
|
namespace Heroes.Icons.ModelExtensions;
/// <summary>
/// Contains extensions for <see cref="VoiceLine"/>.
/// </summary>
public static class VoiceLineExtensions
{
/// <summary>
/// Updates the localized gamestrings to the selected <see cref="Localization"/>.
/// </summary>
/// <param name="voiceLine">The data to be updated.</param>
/// <param name="gameStringDocument">Instance of a <see cref="GameStringDocument"/>.</param>
/// <exception cref="ArgumentNullException"><paramref name="gameStringDocument"/> is null.</exception>
public static void UpdateGameStrings(this VoiceLine voiceLine, GameStringDocument gameStringDocument)
{
ArgumentNullException.ThrowIfNull(gameStringDocument, nameof(gameStringDocument));
gameStringDocument.UpdateGameStrings(voiceLine);
}
}
| 39.333333
| 106
| 0.720339
|
[
"MIT"
] |
koliva8245/Heroes.Icons
|
Heroes.Icons/ModelExtensions/VoiceLineExtensions.cs
| 828
|
C#
|
namespace DeepNestLib
{
public interface IHiddenNfp
{
void Push(SvgPoint svgPoint);
}
}
| 14
| 33
| 0.704082
|
[
"MIT"
] |
9swampy/DeepNestSharp
|
DeepNestLib.Core/IHiddenNfp.cs
| 100
|
C#
|
using ParksApi.Contracts;
using ParksApi.Helpers;
namespace ParksApi.Repository
{
public class RepositoryWrapper : IRepositoryWrapper
{
private ParksApiContext _parksApiContext;
private IParkRepository _park;
private IStateRepository _state;
private IUserRepository _user;
public IParkRepository Park
{
get
{
if (_park == null)
{
_park = new ParkRepository(_parksApiContext);
}
return _park;
}
}
public IStateRepository State
{
get
{
if (_state == null)
{
_state = new StateRepository(_parksApiContext);
}
return _state;
}
}
public IUserRepository User
{
get
{
if (_user == null)
{
_user = new UserRepository(_parksApiContext);
}
return _user;
}
}
public RepositoryWrapper(ParksApiContext parksApiContext)
{
_parksApiContext = parksApiContext;
}
public void Save()
{
_parksApiContext.SaveChanges();
}
}
}
| 17.803279
| 61
| 0.581031
|
[
"MIT"
] |
Andrew-Philpott/ParkFinder
|
ParksApi/Repository/Wrapper.cs
| 1,086
|
C#
|
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
/*
* Do not modify this file. This file is generated from the ec2-2015-04-15.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.EC2.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
namespace Amazon.EC2.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for NetworkAclEntry Object
/// </summary>
public class NetworkAclEntryUnmarshaller : IUnmarshaller<NetworkAclEntry, XmlUnmarshallerContext>, IUnmarshaller<NetworkAclEntry, JsonUnmarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public NetworkAclEntry Unmarshall(XmlUnmarshallerContext context)
{
NetworkAclEntry unmarshalledObject = new NetworkAclEntry();
int originalDepth = context.CurrentDepth;
int targetDepth = originalDepth + 1;
if (context.IsStartOfDocument)
targetDepth += 2;
while (context.ReadAtDepth(originalDepth))
{
if (context.IsStartElement || context.IsAttribute)
{
if (context.TestExpression("cidrBlock", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.CidrBlock = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("egress", targetDepth))
{
var unmarshaller = BoolUnmarshaller.Instance;
unmarshalledObject.Egress = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("icmpTypeCode", targetDepth))
{
var unmarshaller = IcmpTypeCodeUnmarshaller.Instance;
unmarshalledObject.IcmpTypeCode = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("portRange", targetDepth))
{
var unmarshaller = PortRangeUnmarshaller.Instance;
unmarshalledObject.PortRange = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("protocol", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.Protocol = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("ruleAction", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.RuleAction = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("ruleNumber", targetDepth))
{
var unmarshaller = IntUnmarshaller.Instance;
unmarshalledObject.RuleNumber = unmarshaller.Unmarshall(context);
continue;
}
}
else if (context.IsEndElement && context.CurrentDepth < originalDepth)
{
return unmarshalledObject;
}
}
return unmarshalledObject;
}
/// <summary>
/// Unmarshaller error response to exception.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public NetworkAclEntry Unmarshall(JsonUnmarshallerContext context)
{
return null;
}
private static NetworkAclEntryUnmarshaller _instance = new NetworkAclEntryUnmarshaller();
/// <summary>
/// Gets the singleton.
/// </summary>
public static NetworkAclEntryUnmarshaller Instance
{
get
{
return _instance;
}
}
}
}
| 38.736842
| 158
| 0.560753
|
[
"Apache-2.0"
] |
jasoncwik/aws-sdk-net
|
sdk/src/Services/EC2/Generated/Model/Internal/MarshallTransformations/NetworkAclEntryUnmarshaller.cs
| 5,152
|
C#
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System.Text.Json;
using Azure.Core;
namespace Azure.ResourceManager.CosmosDB.Models
{
public partial class CassandraTableResource : IUtf8JsonSerializable
{
void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
{
writer.WriteStartObject();
writer.WritePropertyName("id");
writer.WriteStringValue(Id);
if (Optional.IsDefined(DefaultTtl))
{
writer.WritePropertyName("defaultTtl");
writer.WriteNumberValue(DefaultTtl.Value);
}
if (Optional.IsDefined(Schema))
{
writer.WritePropertyName("schema");
writer.WriteObjectValue(Schema);
}
if (Optional.IsDefined(AnalyticalStorageTtl))
{
writer.WritePropertyName("analyticalStorageTtl");
writer.WriteNumberValue(AnalyticalStorageTtl.Value);
}
writer.WriteEndObject();
}
internal static CassandraTableResource DeserializeCassandraTableResource(JsonElement element)
{
string id = default;
Optional<int> defaultTtl = default;
Optional<CassandraSchema> schema = default;
Optional<int> analyticalStorageTtl = default;
foreach (var property in element.EnumerateObject())
{
if (property.NameEquals("id"))
{
id = property.Value.GetString();
continue;
}
if (property.NameEquals("defaultTtl"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
property.ThrowNonNullablePropertyIsNull();
continue;
}
defaultTtl = property.Value.GetInt32();
continue;
}
if (property.NameEquals("schema"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
property.ThrowNonNullablePropertyIsNull();
continue;
}
schema = CassandraSchema.DeserializeCassandraSchema(property.Value);
continue;
}
if (property.NameEquals("analyticalStorageTtl"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
property.ThrowNonNullablePropertyIsNull();
continue;
}
analyticalStorageTtl = property.Value.GetInt32();
continue;
}
}
return new CassandraTableResource(id, Optional.ToNullable(defaultTtl), schema.Value, Optional.ToNullable(analyticalStorageTtl));
}
}
}
| 36.081395
| 140
| 0.519497
|
[
"MIT"
] |
0rland0Wats0n/azure-sdk-for-net
|
sdk/cosmosdb/Azure.ResourceManager.CosmosDB/src/Generated/Models/CassandraTableResource.Serialization.cs
| 3,103
|
C#
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System.Collections.Generic;
using DateObject = System.DateTime;
namespace Microsoft.Recognizers.Text.DateTime.Utilities
{
public class ModAndDateResult
{
public ModAndDateResult(DateObject beginDate, DateObject endDate, string mod, List<DateObject> dateList)
{
this.BeginDate = beginDate;
this.EndDate = endDate;
this.Mod = mod;
this.DateList = dateList;
}
public ModAndDateResult(DateObject beginDate, DateObject endDate)
{
this.BeginDate = beginDate;
this.EndDate = endDate;
this.Mod = string.Empty;
this.DateList = null;
}
public DateObject BeginDate { get; set; }
public DateObject EndDate { get; set; }
public string Mod { get; set; }
public List<DateObject> DateList { get; set; }
}
}
| 28.444444
| 113
| 0.599609
|
[
"MIT"
] |
17000cyh/Recognizers-Text
|
.NET/Microsoft.Recognizers.Text.DateTime/Utilities/ModAndDateResult.cs
| 1,026
|
C#
|
namespace CoherentNoise
{
internal class Constants
{
public const int MultiplierX = 1619;
public const int MultiplierY = 31337;
public const int MultiplierZ = 6971;
public const int MultiplierSeed = 1013;
public const int ValueShift = 8;
}
}
| 23.090909
| 41
| 0.744094
|
[
"MIT"
] |
djspider117/jacked
|
Jacked/Assets/__Jacked/Code/CoherentNoise/Constants.cs
| 254
|
C#
|
using System;
using System.ComponentModel.DataAnnotations;
namespace Construct.Core.Database.Model
{
public class Permission
{
/// <summary>
/// Primary key used by Entity Framework. Not intended to be used for anything else.
/// </summary>
[Key]
public long Key { get; set; }
/// <summary>
/// User with the permission.
/// </summary>
[Required]
public User User { get; set; }
/// <summary>
/// Name of the permission.
/// </summary>
[Required]
public string Name { get; set; }
/// <summary>
/// Start time of the permission.
/// </summary>
public DateTime? StartTime { get; set; }
/// <summary>
/// End time of the permission.
/// </summary>
public DateTime? EndTime { get; set; }
/// <summary>
/// Returns if the permission is active.
/// </summary>
/// <returns>Whether the permission is active.</returns>
public bool IsActive()
{
// Return if the permission hasn't started or the permission has expired.
if ((this.StartTime.HasValue && this.StartTime > DateTime.Now) || (this.EndTime.HasValue && this.EndTime < DateTime.Now))
{
return false;
}
// Return true (permission active).
return true;
}
}
}
| 28.75
| 133
| 0.50903
|
[
"MIT"
] |
ChrisFigura/Makerspace-Database-Server
|
Construct.Core/Database/Model/Permission.cs
| 1,497
|
C#
|
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using Avalonia.Input;
namespace Avalonia.Controls.Primitives
{
/// <summary>
/// Interface implemented by controls that handle their own scrolling when placed inside a
/// <see cref="ScrollViewer"/>.
/// </summary>
/// <remarks>
/// Controls that implement this interface, when placed inside a <see cref="ScrollViewer"/>
/// can override the physical scrolling behavior of the scroll viewer with logical scrolling.
/// Physical scrolling means that the scroll viewer is a simple viewport onto a larger canvas
/// whereas logical scrolling means that the scrolling is handled by the child control itself
/// and it can choose to do handle the scroll information as it sees fit.
/// </remarks>
public interface ILogicalScrollable : IScrollable
{
/// <summary>
/// Gets or sets a value indicating whether the content can be scrolled horizontally.
/// </summary>
bool CanHorizontallyScroll { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the content can be scrolled horizontally.
/// </summary>
bool CanVerticallyScroll { get; set; }
/// <summary>
/// Gets a value indicating whether logical scrolling is enabled on the control.
/// </summary>
bool IsLogicalScrollEnabled { get; }
/// <summary>
/// Gets or sets the scroll invalidation method.
/// </summary>
/// <remarks>
/// <para>
/// This method notifies the attached <see cref="ScrollViewer"/> of a change in
/// the <see cref="IScrollable.Extent"/>, <see cref="IScrollable.Offset"/> or
/// <see cref="IScrollable.Viewport"/> properties.
/// </para>
/// <para>
/// This property is set by the parent <see cref="ScrollViewer"/> when the
/// <see cref="ILogicalScrollable"/> is placed inside it.
/// </para>
/// </remarks>
Action InvalidateScroll { get; set; }
/// <summary>
/// Gets the size to scroll by, in logical units.
/// </summary>
Size ScrollSize { get; }
/// <summary>
/// Gets the size to page by, in logical units.
/// </summary>
Size PageScrollSize { get; }
/// <summary>
/// Attempts to bring a portion of the target visual into view by scrolling the content.
/// </summary>
/// <param name="target">The target visual.</param>
/// <param name="targetRect">The portion of the target visual to bring into view.</param>
/// <returns>True if the scroll offset was changed; otherwise false.</returns>
bool BringIntoView(IControl target, Rect targetRect);
/// <summary>
/// Gets the next control in the specified direction.
/// </summary>
/// <param name="direction">The movement direction.</param>
/// <param name="from">The control from which movement begins.</param>
/// <returns>The control.</returns>
IControl GetControlInDirection(NavigationDirection direction, IControl from);
}
}
| 41.3625
| 104
| 0.621336
|
[
"MIT"
] |
Artentus/Avalonia
|
src/Avalonia.Controls/Primitives/ILogicalScrollable.cs
| 3,309
|
C#
|
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace MSDTC.Properties
{
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources
{
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources()
{
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager
{
get
{
if ((resourceMan == null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("MSDTC.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture
{
get
{
return resourceCulture;
}
set
{
resourceCulture = value;
}
}
}
}
| 38.430556
| 171
| 0.601373
|
[
"MIT"
] |
pointearth/dotnet-best-practices
|
src/DataBase/MSDTC/Properties/Resources.Designer.cs
| 2,769
|
C#
|
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Tester_ZYH.NET_V.T
{
public partial class css_test
{
/// <summary>
/// form1 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlForm form1;
}
}
| 28.592593
| 85
| 0.453368
|
[
"MIT"
] |
yuhengzhou/ZYH.NET
|
Tester_ZYH.NET_V/T/css_test.aspx.designer.cs
| 774
|
C#
|
using System;
namespace AdventureWorksCosmos.Core.Models.Orders
{
public class OrderRejected : IDocumentMessage
{
public Guid Id { get; set; }
public Guid OrderId { get; set; }
}
}
| 21
| 49
| 0.652381
|
[
"MIT"
] |
jbogard/AdventureWorksCosmos
|
AdventureWorksCosmos.Core/Models/Orders/OrderRejected.cs
| 212
|
C#
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.