content stringlengths 23 1.05M |
|---|
using System;
using Jint.Runtime;
namespace Jint.Native
{
public sealed class JsBoolean : JsValue, IEquatable<JsBoolean>
{
public static readonly JsBoolean False = new JsBoolean(false);
public static readonly JsBoolean True = new JsBoolean(true);
internal static readonly object BoxedTrue = true;
internal static readonly object BoxedFalse = false;
internal readonly bool _value;
public JsBoolean(bool value) : base(Types.Boolean)
{
_value = value;
}
public override object ToObject()
{
return _value ? BoxedTrue : BoxedFalse;
}
public override string ToString()
{
return _value ? bool.TrueString : bool.FalseString;
}
public override bool Equals(JsValue obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
if (!(obj is JsBoolean))
{
return false;
}
return Equals(obj as JsBoolean);
}
public bool Equals(JsBoolean other)
{
if (ReferenceEquals(null, other))
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
return _value == other._value;
}
public override int GetHashCode()
{
return _value.GetHashCode();
}
}
} |
using System;
using OpenQA.Selenium;
using Xunit.Gherkin.Quick;
namespace bdd_tests
{
public abstract partial class TestBase : Feature, IDisposable
{
[And(@"I complete the change hours application for (.*)")]
public void RequestChangeHours(string hoursType)
{
/*
Page Title: Licences & Authorizations
*/
if (hoursType == "a lounge area within service hours")
{
var uiLoungeAreaWithinHours =
ngDriver.FindElement(
By.LinkText("Change to Hours of Liquor Service (Lounge Area, within Service Hours)"));
var executor = (IJavaScriptExecutor) ngDriver.WrappedDriver;
executor.ExecuteScript("arguments[0].scrollIntoView(true);", uiLoungeAreaWithinHours);
uiLoungeAreaWithinHours.Click();
}
if (hoursType == "a lounge area outside of service hours")
{
var uiLoungeAreaOutsideHours =
ngDriver.FindElement(
By.LinkText("Change to Hours of Liquor Service (Lounge Area, outside Service Hours)"));
var executor = (IJavaScriptExecutor) ngDriver.WrappedDriver;
executor.ExecuteScript("arguments[0].scrollIntoView(true);", uiLoungeAreaOutsideHours);
uiLoungeAreaOutsideHours.Click();
}
if (hoursType == "a special event area within service hours")
{
var uiSpecialEventAreaWithinHours =
ngDriver.FindElement(By.CssSelector(".ng-star-inserted:nth-child(15) span"));
uiSpecialEventAreaWithinHours.Click();
}
if (hoursType == "a special event area outside of service hours")
{
var uiSpecialEventAreaOutsideHours =
ngDriver.FindElement(By.CssSelector(".ng-star-inserted:nth-child(14) span"));
uiSpecialEventAreaOutsideHours.Click();
}
ContinueToApplicationButton();
// select the proposed new hours
var uiServiceHoursSundayOpen =
ngDriver.FindElement(
By.CssSelector("[formcontrolname='serviceHoursSundayOpen'] option[value='09:00']"));
uiServiceHoursSundayOpen.Click();
var uiServiceHoursSundayClose =
ngDriver.FindElement(
By.CssSelector("[formcontrolname='serviceHoursSundayClose'] option[value='21:00']"));
uiServiceHoursSundayClose.Click();
var uiServiceHoursMondayOpen =
ngDriver.FindElement(
By.CssSelector("[formcontrolname='serviceHoursMondayOpen'] option[value='11:00']"));
uiServiceHoursMondayOpen.Click();
var uiServiceHoursMondayClose =
ngDriver.FindElement(
By.CssSelector("[formcontrolname='serviceHoursMondayClose'] option[value='23:00']"));
uiServiceHoursMondayClose.Click();
var uiServiceHoursTuesdayOpen =
ngDriver.FindElement(
By.CssSelector("[formcontrolname='serviceHoursTuesdayOpen'] option[value='09:15']"));
uiServiceHoursTuesdayOpen.Click();
var uiServiceHoursTuesdayClose =
ngDriver.FindElement(
By.CssSelector("[formcontrolname='serviceHoursTuesdayClose'] option[value='10:30']"));
uiServiceHoursTuesdayClose.Click();
var uiServiceHoursWednesdayOpen =
ngDriver.FindElement(
By.CssSelector("[formcontrolname='serviceHoursWednesdayOpen'] option[value='12:30']"));
uiServiceHoursWednesdayOpen.Click();
var uiServiceHoursWednesdayClose =
ngDriver.FindElement(
By.CssSelector("[formcontrolname='serviceHoursWednesdayClose'] option[value='21:30']"));
uiServiceHoursWednesdayClose.Click();
var uiServiceHoursThursdayOpen =
ngDriver.FindElement(
By.CssSelector("[formcontrolname='serviceHoursThursdayOpen'] option[value='14:30']"));
uiServiceHoursThursdayOpen.Click();
var uiServiceHoursThursdayClose =
ngDriver.FindElement(
By.CssSelector("[formcontrolname='serviceHoursThursdayClose'] option[value='19:00']"));
uiServiceHoursThursdayClose.Click();
var uiServiceHoursFridayOpen =
ngDriver.FindElement(
By.CssSelector("[formcontrolname='serviceHoursFridayOpen'] option[value='17:00']"));
uiServiceHoursFridayOpen.Click();
var uiServiceHoursFridayClose =
ngDriver.FindElement(
By.CssSelector("[formcontrolname='serviceHoursFridayClose'] option[value='19:45']"));
uiServiceHoursFridayClose.Click();
var uiServiceHoursSaturdayOpen =
ngDriver.FindElement(
By.CssSelector("[formcontrolname='serviceHoursSaturdayOpen'] option[value='09:45']"));
uiServiceHoursSaturdayOpen.Click();
var uiServiceHoursSaturdayClose =
ngDriver.FindElement(
By.CssSelector("[formcontrolname='serviceHoursSaturdayClose'] option[value='20:00']"));
uiServiceHoursSaturdayClose.Click();
// select the authorized to submit checkbox
var uiAuthorizedToSubmit =
ngDriver.FindElement(By.CssSelector("mat-checkbox[formcontrolname='authorizedToSubmit']"));
uiAuthorizedToSubmit.Click();
// select the signature agreement checkbox
var uiSignatureAgreement =
ngDriver.FindElement(By.CssSelector("mat-checkbox[formcontrolname='signatureAgreement']"));
uiSignatureAgreement.Click();
}
[And(@"I complete the change hours application for liquor service within service hours")]
public void RequestLiquorChangeHours(string hoursType)
{
// select the proposed new hours
var uiServiceHoursSundayOpen =
ngDriver.FindElement(
By.CssSelector("[formcontrolname='serviceHoursSundayOpen'] option[value='09:00']"));
uiServiceHoursSundayOpen.Click();
var uiServiceHoursSundayClose =
ngDriver.FindElement(
By.CssSelector("[formcontrolname='serviceHoursSundayClose'] option[value='21:00']"));
uiServiceHoursSundayClose.Click();
var uiServiceHoursMondayOpen =
ngDriver.FindElement(
By.CssSelector("[formcontrolname='serviceHoursMondayOpen'] option[value='11:00']"));
uiServiceHoursMondayOpen.Click();
var uiServiceHoursMondayClose =
ngDriver.FindElement(
By.CssSelector("[formcontrolname='serviceHoursMondayClose'] option[value='23:00']"));
uiServiceHoursMondayClose.Click();
var uiServiceHoursTuesdayOpen =
ngDriver.FindElement(
By.CssSelector("[formcontrolname='serviceHoursTuesdayOpen'] option[value='09:15']"));
uiServiceHoursTuesdayOpen.Click();
var uiServiceHoursTuesdayClose =
ngDriver.FindElement(
By.CssSelector("[formcontrolname='serviceHoursTuesdayClose'] option[value='10:30']"));
uiServiceHoursTuesdayClose.Click();
var uiServiceHoursWednesdayOpen =
ngDriver.FindElement(
By.CssSelector("[formcontrolname='serviceHoursWednesdayOpen'] option[value='12:30']"));
uiServiceHoursWednesdayOpen.Click();
var uiServiceHoursWednesdayClose =
ngDriver.FindElement(
By.CssSelector("[formcontrolname='serviceHoursWednesdayClose'] option[value='21:30']"));
uiServiceHoursWednesdayClose.Click();
var uiServiceHoursThursdayOpen =
ngDriver.FindElement(
By.CssSelector("[formcontrolname='serviceHoursThursdayOpen'] option[value='14:30']"));
uiServiceHoursThursdayOpen.Click();
var uiServiceHoursThursdayClose =
ngDriver.FindElement(
By.CssSelector("[formcontrolname='serviceHoursThursdayClose'] option[value='19:00']"));
uiServiceHoursThursdayClose.Click();
var uiServiceHoursFridayOpen =
ngDriver.FindElement(
By.CssSelector("[formcontrolname='serviceHoursFridayOpen'] option[value='17:00']"));
uiServiceHoursFridayOpen.Click();
var uiServiceHoursFridayClose =
ngDriver.FindElement(
By.CssSelector("[formcontrolname='serviceHoursFridayClose'] option[value='19:45']"));
uiServiceHoursFridayClose.Click();
var uiServiceHoursSaturdayOpen =
ngDriver.FindElement(
By.CssSelector("[formcontrolname='serviceHoursSaturdayOpen'] option[value='09:45']"));
uiServiceHoursSaturdayOpen.Click();
var uiServiceHoursSaturdayClose =
ngDriver.FindElement(
By.CssSelector("[formcontrolname='serviceHoursSaturdayClose'] option[value='20:00']"));
uiServiceHoursSaturdayClose.Click();
// select the authorized to submit checkbox
var uiAuthorizedToSubmit =
ngDriver.FindElement(By.CssSelector("mat-checkbox[formcontrolname='authorizedToSubmit']"));
uiAuthorizedToSubmit.Click();
// select the signature agreement checkbox
var uiSignatureAgreement =
ngDriver.FindElement(By.CssSelector("mat-checkbox[formcontrolname='signatureAgreement']"));
uiSignatureAgreement.Click();
}
[And(@"I complete the change hours application for liquor service outside service hours")]
public void RequestLiquorChangeHoursOutside(string hoursType)
{
// select the proposed new hours
var uiServiceHoursSundayOpen =
ngDriver.FindElement(
By.CssSelector("[formcontrolname='serviceHoursSundayOpen'] option[value='09:00']"));
uiServiceHoursSundayOpen.Click();
var uiServiceHoursSundayClose =
ngDriver.FindElement(
By.CssSelector("[formcontrolname='serviceHoursSundayClose'] option[value='21:00']"));
uiServiceHoursSundayClose.Click();
var uiServiceHoursMondayOpen =
ngDriver.FindElement(
By.CssSelector("[formcontrolname='serviceHoursMondayOpen'] option[value='11:00']"));
uiServiceHoursMondayOpen.Click();
var uiServiceHoursMondayClose =
ngDriver.FindElement(
By.CssSelector("[formcontrolname='serviceHoursMondayClose'] option[value='23:00']"));
uiServiceHoursMondayClose.Click();
var uiServiceHoursTuesdayOpen =
ngDriver.FindElement(
By.CssSelector("[formcontrolname='serviceHoursTuesdayOpen'] option[value='09:15']"));
uiServiceHoursTuesdayOpen.Click();
var uiServiceHoursTuesdayClose =
ngDriver.FindElement(
By.CssSelector("[formcontrolname='serviceHoursTuesdayClose'] option[value='10:30']"));
uiServiceHoursTuesdayClose.Click();
var uiServiceHoursWednesdayOpen =
ngDriver.FindElement(
By.CssSelector("[formcontrolname='serviceHoursWednesdayOpen'] option[value='12:30']"));
uiServiceHoursWednesdayOpen.Click();
var uiServiceHoursWednesdayClose =
ngDriver.FindElement(
By.CssSelector("[formcontrolname='serviceHoursWednesdayClose'] option[value='21:30']"));
uiServiceHoursWednesdayClose.Click();
var uiServiceHoursThursdayOpen =
ngDriver.FindElement(
By.CssSelector("[formcontrolname='serviceHoursThursdayOpen'] option[value='14:30']"));
uiServiceHoursThursdayOpen.Click();
var uiServiceHoursThursdayClose =
ngDriver.FindElement(
By.CssSelector("[formcontrolname='serviceHoursThursdayClose'] option[value='19:00']"));
uiServiceHoursThursdayClose.Click();
var uiServiceHoursFridayOpen =
ngDriver.FindElement(
By.CssSelector("[formcontrolname='serviceHoursFridayOpen'] option[value='17:00']"));
uiServiceHoursFridayOpen.Click();
var uiServiceHoursFridayClose =
ngDriver.FindElement(
By.CssSelector("[formcontrolname='serviceHoursFridayClose'] option[value='19:45']"));
uiServiceHoursFridayClose.Click();
var uiServiceHoursSaturdayOpen =
ngDriver.FindElement(
By.CssSelector("[formcontrolname='serviceHoursSaturdayOpen'] option[value='09:45']"));
uiServiceHoursSaturdayOpen.Click();
var uiServiceHoursSaturdayClose =
ngDriver.FindElement(
By.CssSelector("[formcontrolname='serviceHoursSaturdayClose'] option[value='20:00']"));
uiServiceHoursSaturdayClose.Click();
// select the authorized to submit checkbox
var uiAuthorizedToSubmit =
ngDriver.FindElement(By.CssSelector("mat-checkbox[formcontrolname='authorizedToSubmit']"));
uiAuthorizedToSubmit.Click();
// select the signature agreement checkbox
var uiSignatureAgreement =
ngDriver.FindElement(By.CssSelector("mat-checkbox[formcontrolname='signatureAgreement']"));
uiSignatureAgreement.Click();
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Tool
{
/*
* Description: user defined exception
*/
class FTBAutoTestException : ApplicationException
{
public FTBAutoTestException(string message) : base(message) { }
public override string Message
{
get
{
return base.Message;
}
}
}
}
|
namespace Fonet.Fo.Flow
{
using Fonet.DataTypes;
using Fonet.Fo.Properties;
using Fonet.Layout;
internal class TableColumn : FObj
{
private Length columnWidthPropVal;
private int columnWidth;
private int columnOffset;
private int numColumnsRepeated;
private int iColumnNumber;
private bool setup = false;
private AreaContainer areaContainer;
new internal class Maker : FObj.Maker
{
public override FObj Make(FObj parent, PropertyList propertyList)
{
return new TableColumn(parent, propertyList);
}
}
new public static FObj.Maker GetMaker()
{
return new Maker();
}
public TableColumn(FObj parent, PropertyList propertyList)
: base(parent, propertyList)
{
this.name = "fo:table-column";
}
public Length GetColumnWidthAsLength()
{
return columnWidthPropVal;
}
public int GetColumnWidth()
{
return columnWidth;
}
public void SetColumnWidth(int columnWidth)
{
this.columnWidth = columnWidth;
}
public int GetColumnNumber()
{
return iColumnNumber;
}
public int GetNumColumnsRepeated()
{
return numColumnsRepeated;
}
public void DoSetup(Area area)
{
BorderAndPadding bap = propMgr.GetBorderAndPadding();
BackgroundProps bProps = propMgr.GetBackgroundProps();
this.iColumnNumber =
this.properties.GetProperty("column-number").GetNumber().IntValue();
this.numColumnsRepeated =
this.properties.GetProperty("number-columns-repeated").GetNumber().IntValue();
this.columnWidthPropVal =
this.properties.GetProperty("column-width").GetLength();
this.columnWidth = columnWidthPropVal.MValue();
string id = this.properties.GetProperty("id").GetString();
area.getIDReferences().InitializeID(id, area);
setup = true;
}
public override Status Layout(Area area)
{
if (this.marker == MarkerBreakAfter)
{
return new Status(Status.OK);
}
if (this.marker == MarkerStart)
{
if (!setup)
{
DoSetup(area);
}
}
if (columnWidth > 0)
{
this.areaContainer =
new AreaContainer(propMgr.GetFontState(area.getFontInfo()),
columnOffset, 0, columnWidth,
area.getContentHeight(), Position.RELATIVE);
areaContainer.foCreator = this;
areaContainer.setPage(area.getPage());
areaContainer.setBorderAndPadding(propMgr.GetBorderAndPadding());
areaContainer.setBackground(propMgr.GetBackgroundProps());
areaContainer.SetHeight(area.GetHeight());
area.addChild(areaContainer);
}
return new Status(Status.OK);
}
public void SetColumnOffset(int columnOffset)
{
this.columnOffset = columnOffset;
}
public void SetHeight(int height)
{
if (areaContainer != null)
{
areaContainer.setMaxHeight(height);
areaContainer.SetHeight(height);
}
}
}
} |
using System.Collections.Generic;
using Core.Model;
using Core.Database.Tables;
namespace Core.Managers
{
public class ClansManager : SingletonBase<ClansManager>
{
public Clan getClanById(ulong id)
{
foreach (Clan im in ClansTable.clans.Values)
{
if (im.Id == id)
return im;
}
return null;
}
public Dictionary<ulong, Player> getPlayersForClan(int ClanID)
{
Dictionary<ulong, Player> players;
players = new Dictionary<ulong, Player>();
foreach (var player in PlayersTable.players.Values)
{
if(player.getClanID() == ClanID)
{
players.Add(player.PlayerID, player);
}
}
return players;
}
public Clan getClanForName(string name)
{
foreach (Clan clan in ClansTable.clans.Values)
{
if (clan.Name == name)
return clan;
}
return null;
}
public Dictionary<ulong, Clan> getClans()
{
return ClansTable.clans;
}
}
}
|
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc.Filters;
using ServerCore.DataModel;
namespace ServerCore.Areas.Identity.UserAuthorizationPolicy
{
/// <summary>
/// Require that the current user is an author for the event in the route.
/// </summary>
public class IsAuthorInEventRequirement : IAuthorizationRequirement
{
public IsAuthorInEventRequirement()
{
}
}
public class IsAuthorInEventHandler : AuthorizationHandler<IsAuthorInEventRequirement>
{
private readonly PuzzleServerContext dbContext;
private readonly UserManager<IdentityUser> userManager;
public IsAuthorInEventHandler(PuzzleServerContext pContext, UserManager<IdentityUser> manager)
{
dbContext = pContext;
userManager = manager;
}
protected override async Task HandleRequirementAsync(AuthorizationHandlerContext authContext,
IsAuthorInEventRequirement requirement)
{
await AuthorizationHelper.IsEventAuthorCheck(authContext, dbContext, userManager, requirement);
}
}
}
|
using System.Collections.Generic;
using System.Text.Json.Serialization;
#nullable disable
namespace RiotPls.DataDragon.Entities
{
internal class ChampionDataDto : BaseDataDto
{
[JsonPropertyName("data")]
public IReadOnlyDictionary<string, ChampionDto> Champion { get; set; }
}
} |
namespace OSS.DataFlow.Event
{
/// <summary>
/// 事件的输入参数
/// </summary>
/// <typeparam name="TIn"></typeparam>
public class FlowEventInput<TIn>
{
/// <summary>
/// 循环执行次数
/// </summary>
public int circulate_times { get; set; }
/// <summary>
/// 输入参数
/// </summary>
public TIn input { get; set; }
}
internal readonly struct EventProcessResp<TOut>
{
public bool is_success { get; }
public EventProcessResp(bool isSuccess, TOut res)
{
is_success = isSuccess;
result = res;
}
/// <summary>
/// 返回结果
/// </summary>
public TOut result { get; }
}
} |
using Corund.Engine;
using Corund.Tools;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace Corund.Sprites
{
/// <summary>
/// Sprite that can cover a given rectangle with tiled texture.
/// </summary>
public class TiledSprite: Sprite, ITiledSprite
{
#region Constructor
public TiledSprite(Texture2D texture, Vector2? effectiveSize = null)
: base(texture)
{
EffectiveSize = effectiveSize ?? Size;
}
#endregion
#region Fields
private Vector2 _effectiveSize;
private Vector2 _textureOffset;
private Rectangle _tileRectangle;
#endregion
#region Properties
/// <summary>
/// Gets or sets the actual size of the rectangle to cover with tiled texture.
/// </summary>
public Vector2 EffectiveSize
{
get => _effectiveSize;
set
{
if (_effectiveSize != value)
return;
_effectiveSize = value;
UpdateTileRectangle();
}
}
/// <summary>
/// Gets or sets the point in the texture that will be placed into left top corner of the rendered rectangle.
/// </summary>
public Vector2 TextureOffset
{
get => _textureOffset;
set
{
if (_textureOffset != value)
return;
_textureOffset = value;
UpdateTileRectangle();
}
}
#endregion
#region Methods
/// <summary>
/// Renders the tiled rectangle to the screen.
/// </summary>
public override void Draw(TransformInfo transform, Color tint, float zOrder)
{
GameEngine.Render.TryBeginBatch(BlendState, true);
GameEngine.Render.SpriteBatch.Draw(
Texture,
transform.Position,
_tileRectangle,
tint,
transform.Angle,
HotSpot,
transform.ScaleVector,
SpriteEffects.None,
zOrder
);
}
/// <summary>
/// Refreshes the tile rectangle when size or texture offset change.
/// </summary>
private void UpdateTileRectangle()
{
_tileRectangle = new Rectangle(
(int)_textureOffset.X,
(int)_textureOffset.Y,
(int)(_effectiveSize.X + _textureOffset.X),
(int)(_effectiveSize.Y + _textureOffset.Y)
);
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using P1FinalDbContext;
using P1Models;
namespace P1FinalBusiness
{
public class CartCheckout
{
//carts need to have a context because they need to access the db & arraylist of orders
private readonly P1TestDbContext _context;
//private List<P1Models.Order> _ord;
// private List<Product> _prod;
public List<P1Models.Product> Products { get; set; }
public Customer Customer;
//static list
//constructor
public CartCheckout(P1TestDbContext context)
{
this._context = context;
Products = new List<P1Models.Product>();
}
// AddProductAsync
/* public async Task<bool> AddProductAsync(Product p)
{
Products.Add(p);
var n = new CartProduct(1, p.ProductId);
await _context.AddAsync(n);
await _context.SaveChangesAsync();
return true;
}
*/
//Display an order
//public async Task<List<CartProduct>> ListOfCartProductsAsync()
//{
// // ps = _context.Users.ToList();
// ps = _context.CartProducts.ToList();
// return ps;
//}
}
}
|
using System.Collections.Generic;
using Amazon.CloudFormation.Model;
namespace ProjectBaseName.DeployTool
{
public class Config
{
public string Env { get; set; }
public string Region { get; set; }
public string Profile { get; set; }
public string Stack { get; set; }
public string Team { get; set; }
public string Email { get; set; }
public string BuildPath { get; set; }
public string BuildConfig { get; set; }
public List<Tag> Tags { get; set; }
}
} |
using System;
class MyClass
{
internal void MyMethod() => Console.WriteLine("MyMethod called!");
}
class Program
{
static void Main()
{
var x = new MyClass();
x.MyMethod();
}
}
|
using System.Collections.Generic;
using System.Linq;
using TrackMe.Core.Models;
using TrackMe.Core.Services.Interfaces;
namespace TrackMe.Core.Services
{
public class PossibleTimeProvider : IPossibleTimeProvider
{
public IEnumerable<PossibleTime> GetPossibleTimes()
{
#if DEBUG
int[] times = {1, 5, 10, 30, 60, 120};
#else
int[] times = {5, 10, 30, 60, 120};
#endif
return times.Select(time => new PossibleTime(time)).ToList();
}
}
} |
using System;
using Equinox.Domain.Models;
using Nest;
public static class SearchHelper
{
public const string PRODUCT_INDEX = "product";
public const string PRODUCT_ALIAS = "alias-product";
public static void Initialize(ElasticClient elasticClient)
{
var settings = new IndexSettings { NumberOfReplicas = 0, NumberOfShards = 1 };
var indexConfig = new IndexState
{
Settings = settings
};
if (!elasticClient.IndexExists(PRODUCT_INDEX).Exists)
{
elasticClient.CreateIndex(PRODUCT_INDEX, i => i
.InitializeUsing(indexConfig)
.Mappings(m => m.Map<Product>(ms => ms
.Properties(p => p.Text(t => t.Name(n => n.Name)
.SearchAnalyzer("standard")
.Analyzer("whitespace")))
.AutoMap()))
.Aliases(x => x.Alias(PRODUCT_ALIAS)));
}
}
} |
using System;
namespace Umbraco.Cms.Core.Macros
{
// represents the content of a macro
public class MacroContent
{
// gets or sets the text content
public string Text { get; set; }
// gets or sets the date the content was generated
public DateTime Date { get; set; } = DateTime.Now;
// a value indicating whether the content is empty
public bool IsEmpty => Text is null;
// gets an empty macro content
public static MacroContent Empty { get; } = new MacroContent();
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace UsingConstraints
{
class Node<T> : IComparable<Node<T>> where T : IComparable<T>
{
//clanovi polja
private T data;
private Node<T> next = null;
private Node<T> prev = null;
//konstruktor
public Node(T data)
{
this.data = data;
}
//svojstva
public T Data { get { return this.data; } }
public Node<T> Next
{
get { return this.next; }
}
public int CompareTo(Node<T> rhs)
{
//funkcionira zbog ogranicenja
return data.CompareTo(rhs.data);
}
public bool Equals(Node<T> rhs)
{
return this.data.Equals(rhs.Data);
}
//metode
public Node<T> Add(Node<T> newNode)
{
if(this.CompareTo(newNode) > 0) //ide prije mene
{
newNode.next = this; //novi cvor pokazuje na mene
//ako imam predhodno postavi ih da pokazuju na novi cvor kao svoj sljedeci
if(this.prev != null)
{
this.prev.next = newNode;
newNode.prev = this.prev;
}
//postavlja prev u tekucem cvoru da pokazuje na novi cvor
this.prev = newNode;
//vraca newNode u slucaju da je to novo zaglavlje
return newNode;
}
else //ide nakon mene
{
//ako imam sljedeci, prosljedjuje novi cvor na usporedjivanje
if(this.next != null)
{
this.next.Add(newNode);
}
//nemam sljedeci pa postavim novi cvor
//da bude moj sljedeci i postavi njegov prev da pokazuje na mene
else
{
this.next = newNode;
newNode.prev = this;
}
return this;
}
}
public override string ToString()
{
string output = data.ToString();
if(next != null)
{
output += ", " + next.ToString();
}
return output;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using ZKWeb.Localize;
using ZKWebStandard.Extensions;
using ZKWebStandard.Ioc;
using ZKWeb.Web.ActionResults;
using ZKWeb.Web;
using ZKWebStandard.Web;
using ZKWeb.Plugins.Shopping.Order.src.Domain.Services;
using ZKWeb.Plugins.Shopping.Order.src.Domain.Enums;
using ZKWeb.Plugins.Common.Base.src.Controllers.Extensions;
using ZKWeb.Plugins.Shopping.Product.src.Domain.Structs;
using ZKWeb.Plugins.Common.Currency.src.Domain.Service;
using ZKWeb.Plugins.Common.Currency.src.Components.Interfaces;
using ZKWeb.Plugins.Shopping.Order.src.Domain.Structs;
using ZKWeb.Plugins.Common.Base.src.Controllers.Bases;
using ZKWeb.Plugins.Shopping.Order.src.Domain.Extensions;
namespace ZKWeb.Plugins.Shopping.Order.src.Controllers {
/// <summary>
/// 购物车Api控制器
/// </summary>
[ExportMany]
public class CartApiController : ControllerBase {
/// <summary>
/// 获取购物车商品的总数量
/// </summary>
/// <returns></returns>
[Action("api/cart/product_total_count", HttpMethods.POST)]
public IActionResult CartProductTotalCount() {
var cartProductManager = Application.Ioc.Resolve<CartProductManager>();
var totalCount = cartProductManager.GetCartProductTotalCount(CartProductType.Default);
return new JsonResult(new { totalCount });
}
/// <summary>
/// 获取迷你购物车的信息
/// </summary>
/// <returns></returns>
[Action("api/cart/minicart_info")]
public IActionResult MiniCartInfo() {
var cartProductManager = Application.Ioc.Resolve<CartProductManager>();
var info = cartProductManager.GetMiniCartApiInfo();
return new JsonResult(info);
}
/// <summary>
/// 获取购物车信息
/// </summary>
/// <returns></returns>
[Action("api/cart/info", HttpMethods.POST)]
public IActionResult CartInfo() {
var type = Request.Get<string>("type");
var cartProductType = (type == "buynow") ? CartProductType.Buynow : CartProductType.Default;
var cartProductManager = Application.Ioc.Resolve<CartProductManager>();
var info = cartProductManager.GetCartApiInfo(cartProductType);
return new JsonResult(info);
}
/// <summary>
/// 添加商品到购物车
/// </summary>
/// <returns></returns>
[Action("api/cart/add", HttpMethods.POST)]
public IActionResult Add() {
this.RequireAjaxRequest();
var request = Request;
var productId = request.Get<Guid>("productId");
var matchParameters = request.Get<ProductMatchParameters>("matchParameters");
var isBuyNow = request.Get<bool>("isBuyNow");
var cartProductType = isBuyNow ? CartProductType.Buynow : CartProductType.Default;
// 添加购物车商品,抛出无权限错误时跳转到登陆页面
var cartProductManager = Application.Ioc.Resolve<CartProductManager>();
try {
cartProductManager.AddCartProduct(productId, cartProductType, matchParameters);
} catch (HttpException ex) {
if (ex.StatusCode == 403) {
return new JsonResult(new { redirectTo = "/user/login" });
}
throw;
}
// 立刻购买时跳转到购物车页面
if (isBuyNow) {
return new JsonResult(new { redirectTo = "/cart?type=buynow" });
}
// 加入购物车时显示弹出框,包含商品总数和价格
var currencyManager = Application.Ioc.Resolve<CurrencyManager>();
var totalCount = cartProductManager.GetCartProductTotalCount(cartProductType);
var totalPrices = cartProductManager.GetCartProductTotalPrice(
cartProductManager.GetCartProducts(cartProductType));
var totalPriceString = string.Join(", ", totalPrices.Select(
pair => currencyManager.GetCurrency(pair.Key).Format(pair.Value)));
return new JsonResult(new { showDialog = new { totalCount, totalPriceString } });
}
/// <summary>
/// 删除购物车中的商品
/// </summary>
/// <returns></returns>
[Action("api/cart/delete", HttpMethods.POST)]
public IActionResult Delete() {
this.RequireAjaxRequest();
var id = Request.Get<Guid>("id");
var cartProductManager = Application.Ioc.Resolve<CartProductManager>();
cartProductManager.DeleteCartProduct(id);
return new JsonResult(new { message = new T("Delete Successfully") });
}
/// <summary>
/// 更新购物车中的商品数量
/// </summary>
/// <returns></returns>
[Action("api/cart/update_counts", HttpMethods.POST)]
public IActionResult UpdateCounts() {
this.RequireAjaxRequest();
var counts = Request.Get<IDictionary<Guid, long>>("counts");
var cartProductManager = Application.Ioc.Resolve<CartProductManager>();
cartProductManager.UpdateCartProductCounts(counts);
return new JsonResult(new { });
}
/// <summary>
/// 计算购物车中的商品价格
/// </summary>
/// <returns></returns>
[Action("api/cart/calculate_price", HttpMethods.POST)]
public IActionResult CalculatePrice() {
this.RequireAjaxRequest();
var createOrderParameters = Request
.Get<CreateOrderParameters>("CreateOrderParameters") ?? new CreateOrderParameters();
createOrderParameters.SetLoginInfo();
var cartProductManager = Application.Ioc.Resolve<CartProductManager>();
try {
var info = cartProductManager.GetCartCalculatePriceApiInfo(createOrderParameters);
return new JsonResult(new { priceInfo = info });
} catch (Exception ex) {
return new JsonResult(new { error = ex.Message });
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using FieldScribeAPI.Models;
using FieldScribeAPI.Infrastructure;
using Microsoft.EntityFrameworkCore;
using AutoMapper;
using AutoMapper.QueryableExtensions;
using Microsoft.EntityFrameworkCore.Extensions.Internal;
namespace FieldScribeAPI.Services
{
public class DefaultEntryService : IEntryService
{
private readonly FieldScribeAPIContext _context;
public DefaultEntryService(FieldScribeAPIContext context)
{
_context = context;
}
public async Task<EventEntry> GetEntryByIdAsync(int entryId, CancellationToken ct)
{
var entity = await _context.EventEntries.SingleOrDefaultAsync
(r => r.entryId == entryId, ct);
if (entity == null) return null;
var entry = Mapper.Map<EventEntry>(entity);
EventMarks em = await new AttemptsProcessor(_context, entry.eventId)
.GetAttempts(entryId, ct);
entry.Marks = em.Attempts;
entry.MarkType = em.MarkType;
return entry;
}
public async Task<Collection<EventEntry>> GetEntriesByEventAsync(
int eventId,
SortOptions<EventEntry, EventEntryEntity> sortOptions,
SearchOptions<EventEntry, EventEntryEntity> searchOptions,
CancellationToken ct)
{
IQueryable<EventEntryEntity> query =
_context.EventEntries.Where(r => r.eventId == eventId);
query = searchOptions.Apply(query);
query = sortOptions.Apply(query);
var items = await query
.ProjectTo<EventEntry>()
.ToArrayAsync(ct);
AttemptsProcessor ap = new AttemptsProcessor(_context, eventId);
foreach (var ent in items)
{
EventMarks em = await ap.GetAttempts(ent.entryId, ct);
ent.Marks = em.Attempts;
ent.MarkType = em.MarkType;
}
return new Collection<EventEntry>
{
Value = items
};
}
}
}
|
//Copyright © 2014 Sony Computer Entertainment America LLC. See License.txt.
using System;
using SharpDX.DirectWrite;
namespace Sce.Atf.Direct2D
{
/// <summary>
/// The D2dTextFormat describes the font and paragraph properties used to format text,
/// and it describes locale information</summary>
public class D2dTextFormat : D2dResource
{
/// <summary>
/// Gets the font family name</summary>
public string FontFamilyName
{
get { return m_nativeTextFormat.FontFamilyName; }
}
/// <summary>
/// Gets the font size in DIP (Device Independent Pixels) units</summary>
public float FontSize
{
get { return m_nativeTextFormat.FontSize; }
}
/// <summary>
/// Gets the height of the font</summary>
public float FontHeight
{
get { return m_fontHeight; }
}
/// <summary>
/// Gets or sets the alignment option of a paragraph that is relative to the top and
/// bottom edges of a layout box</summary>
public D2dParagraphAlignment ParagraphAlignment
{
get { return (D2dParagraphAlignment)m_nativeTextFormat.ParagraphAlignment; }
set
{
m_nativeTextFormat.ParagraphAlignment = (ParagraphAlignment)value;
}
}
/// <summary>
/// Gets or sets the current reading direction for text in a paragraph</summary>
public D2dReadingDirection ReadingDirection
{
get { return (D2dReadingDirection)m_nativeTextFormat.ReadingDirection; }
set
{
m_nativeTextFormat.ReadingDirection = (ReadingDirection)value;
}
}
/// <summary>
/// Gets or sets the alignment option of text relative to the layout box's leading and
/// trailing edge</summary>
public D2dTextAlignment TextAlignment
{
get { return (D2dTextAlignment)m_nativeTextFormat.TextAlignment; }
set
{
m_nativeTextFormat.TextAlignment = (TextAlignment)value;
}
}
/// <summary>
/// Gets or sets the word wrapping option</summary>
public D2dWordWrapping WordWrapping
{
get { return (D2dWordWrapping)m_nativeTextFormat.WordWrapping; }
set
{
m_nativeTextFormat.WordWrapping = (WordWrapping)value;
}
}
/// <summary>
/// Gets or sets the trimming options for text that overflows the layout box</summary>
public D2dTrimming Trimming
{
get
{
D2dTrimming trimmingOptions;
InlineObject trimmingSign;
Trimming tmpTrimming;
m_nativeTextFormat.GetTrimming(out tmpTrimming, out trimmingSign);
trimmingOptions.Delimiter = tmpTrimming.Delimiter;
trimmingOptions.DelimiterCount = tmpTrimming.DelimiterCount;
trimmingOptions.Granularity =(D2dTrimmingGranularity) tmpTrimming.Granularity;
return trimmingOptions;
}
set
{
Trimming trimming = new Trimming();
trimming.Delimiter = value.Delimiter;
trimming.DelimiterCount = value.DelimiterCount;
trimming.Granularity = (TrimmingGranularity)value.Granularity;
IntPtr inlineObj = (value.Granularity != D2dTrimmingGranularity.None) ?
m_ellipsisTrimming.NativePointer : IntPtr.Zero;
object[] args = { trimming, inlineObj };
SetTrimmingInfo.Invoke(m_nativeTextFormat, args);
}
}
/// <summary>
/// Gets and sets text snapping and clipping options.
/// Default value:
/// Text is vertically snapped to pixel boundaries
/// and it is clipped to the layout rectangle.</summary>
public D2dDrawTextOptions DrawTextOptions
{
get {return m_drawTextOptions; }
set { m_drawTextOptions = value; }
}
/// <summary>
/// Gets and sets whether the text is underlined</summary>
public bool Underlined
{
get;
set;
}
/// <summary>
/// Gets and sets whether the text has the strike-out effect</summary>
public bool Strikeout
{
get;
set;
}
/// <summary>
/// Returns the line spacing adjustment set for a multiline text paragraph</summary>
/// <param name="lineSpacingMethod">A value that indicates how line height is determined</param>
/// <param name="lineSpacing">When this method returns, contains the line height,
/// or distance between one baseline to another</param>
/// <param name="baseline">When this method returns, contains the distance from top of line to baseline.
/// A reasonable ratio to lineSpacing is 80 percent.</param>
/// <returns>If the method succeeds, it returns D2dResult.Ok.
/// Otherwise, it throws an exception.</returns>
public D2dResult GetLineSpacing(
out D2dLineSpacingMethod lineSpacingMethod,
out float lineSpacing,
out float baseline)
{
LineSpacingMethod tmpLineSpacingMethod;
m_nativeTextFormat.GetLineSpacing(
out tmpLineSpacingMethod,
out lineSpacing,
out baseline);
lineSpacingMethod = (D2dLineSpacingMethod)tmpLineSpacingMethod;
return D2dResult.Ok;
}
/// <summary>
/// Sets the line spacing</summary>
/// <param name="lineSpacingMethod">Specifies how line height is being determined; see D2dLineSpacingMethod
/// for more information</param>
/// <param name="lineSpacing">The line height, or distance between one baseline to another</param>
/// <param name="baseline">The distance from top of line to baseline. A reasonable ratio to lineSpacing
/// is 80 percent.</param>
/// <returns>If the method succeeds, it returns D2dResult.OK. Otherwise, it throws an exception.</returns>
/// <remarks>
/// For the default method, spacing depends solely on the content. For uniform
/// spacing, the specified line height overrides the content.</remarks>
public D2dResult SetLineSpacing(D2dLineSpacingMethod lineSpacingMethod, float lineSpacing, float baseline)
{
m_nativeTextFormat.SetLineSpacing((LineSpacingMethod)lineSpacingMethod, lineSpacing, baseline);
return D2dResult.Ok;
}
protected override void Dispose(bool disposing)
{
if (IsDisposed) return;
m_ellipsisTrimming.Dispose();
m_nativeTextFormat.Dispose();
base.Dispose(disposing);
}
internal TextFormat NativeTextFormat
{
get { return m_nativeTextFormat; }
}
internal D2dTextFormat(TextFormat textFormat)
{
if (textFormat == null)
throw new ArgumentNullException("textFormat");
m_nativeTextFormat = textFormat;
m_ellipsisTrimming = new EllipsisTrimming(D2dFactory.NativeDwFactory
, m_nativeTextFormat);
// it seems SharpDX guys forgot to expose SetTrimming(..) method.
// for now use reflection to access it.
if(SetTrimmingInfo == null)
{
SetTrimmingInfo = textFormat.GetType().GetMethod("SetTrimming_"
, System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
}
m_fontHeight =(float)Math.Ceiling(m_nativeTextFormat.FontSize * 1.2);
}
private static System.Reflection.MethodInfo SetTrimmingInfo;
private TextFormat m_nativeTextFormat;
private EllipsisTrimming m_ellipsisTrimming;
private D2dDrawTextOptions m_drawTextOptions = D2dDrawTextOptions.None;
private float m_fontHeight;
}
/// <summary>
/// Enum that specifies the alignment of paragraph text along the flow direction axis,
/// relative to the top and bottom of the flow's layout box</summary>
public enum D2dParagraphAlignment
{
/// <summary>
/// The top of the text flow is aligned to the top edge of the layout box</summary>
Near = 0,
/// <summary>
/// The bottom of the text flow is aligned to the bottom edge of the layout box</summary>
Far = 1,
/// <summary>
/// The center of the flow is aligned to the center of the layout box</summary>
Center = 2,
}
/// <summary>
/// Enum that specifies the direction in which reading progresses</summary>
public enum D2dReadingDirection
{
/// <summary>
/// Indicates that reading progresses from left to right</summary>
LeftToRight = 0,
/// <summary>
/// Indicates that reading progresses from right to left</summary>
RightToLeft = 1,
}
/// <summary>
/// Enum that specifies the alignment of paragraph text along the reading direction axis,
/// relative to the leading and trailing edge of the layout box</summary>
public enum D2dTextAlignment
{
/// <summary>
/// The leading edge of the paragraph text is aligned to the leading edge of
/// the layout box</summary>
Leading = 0,
/// <summary>
/// The trailing edge of the paragraph text is aligned to the trailing edge of
/// the layout box</summary>
Trailing = 1,
/// <summary>
/// The center of the paragraph text is aligned to the center of the layout box</summary>
Center = 2,
}
/// <summary>
/// Enum that specifies the word wrapping to be used in a particular multiline paragraph</summary>
public enum D2dWordWrapping
{
/// <summary>
/// Indicates that words are broken across lines to avoid text
/// overflowing the layout box</summary>
Wrap = 0,
/// <summary>
/// Indicates that words are kept within the same line even when it overflows
/// the layout box. This option is often used with scrolling to reveal overflow text.</summary>
NoWrap = 1,
}
/// <summary>
/// Enum that specifies the method used for line spacing in a text layout</summary>
/// <remarks>
/// The line spacing method is set by using the SetLineSpacing method of
/// the D2dTextFormat or D2dTextLayout.
/// To get the current line spacing method of a text format or textlayout, use
/// the GetLineSpacing method.</remarks>
public enum D2dLineSpacingMethod
{
/// <summary>
/// Line spacing depends solely on the content, adjusting to accommodate the
/// size of fonts and inline objects</summary>
Default = 0,
/// <summary>
/// Lines are explicitly set to uniform spacing, regardless of the size of fonts
/// and inline objects. This can be useful to avoid the uneven appearance that
/// can occur from font fallback.</summary>
Uniform = 1,
}
/// <summary>
/// Enum that specifies the text granularity used to trim text overflowing the layout box</summary>
public enum D2dTrimmingGranularity
{
/// <summary>
/// No trimming occurs. Text flows beyond the layout width.</summary>
None = 0,
/// <summary>
/// Trimming occurs at a character cluster boundary</summary>
Character = 1,
/// <summary>
/// Trimming occurs at a word boundary</summary>
Word = 2,
}
/// <summary>
/// Struct that specifies the trimming option for text overflowing the layout box</summary>
public struct D2dTrimming
{
/// <summary>
/// A character code used as the delimiter that signals the beginning of the
/// portion of text to be preserved. Most useful for path ellipsis, where the
/// delimiter would be a slash.</summary>
public int Delimiter;
/// <summary>
/// A value that indicates how many occurrences of the delimiter to step back</summary>
public int DelimiterCount;
/// <summary>
/// A value that specifies the text granularity used to trim text overflowing
/// the layout box</summary>
public D2dTrimmingGranularity Granularity;
}
/// <summary>
/// Enum that specifies whether text snapping is suppressed-or-clipping to the layout rectangle
/// is enabled. This enumeration allows a bitwise combination of its member values.</summary>
[Flags]
public enum D2dDrawTextOptions
{
/// <summary>
/// Text is vertically snapped to pixel boundaries and is not clipped to the
/// layout rectangle</summary>
None = 0,
/// <summary>
/// Text is not vertically snapped to pixel boundaries. This setting is recommended
/// for text that is being animated.</summary>
NoSnap = 1,
/// <summary>
/// Text is clipped to the layout rectangle</summary>
Clip = 2,
}
/// <summary>
/// Enum that represents the density of a typeface, in terms of the lightness or heaviness
/// of the strokes. The enumerated values correspond to the usWeightClass definition
/// in the OpenType specification. The usWeightClass represents an integer value
/// between 1 and 999. Lower values indicate lighter weights; higher values indicate
/// heavier weights.</summary>
/// <remarks>
/// Weight differences are generally differentiated by an increased stroke or
/// thickness that is associated with a given character in a typeface, as compared
/// to a "normal" character from that same typeface.</remarks>
public enum D2dFontWeight
{
/// <summary>
/// Predefined font weight : Thin (100)</summary>
Thin = 100,
/// <summary>
/// Predefined font weight : Extra-light (200)</summary>
ExtraLight = 200,
/// <summary>
/// Predefined font weight : Ultra-light (200)</summary>
UltraLight = 200,
/// <summary>
/// Predefined font weight : Light (300)</summary>
Light = 300,
/// <summary>
/// Predefined font weight : Normal (400)</summary>
Normal = 400,
/// <summary>
/// Predefined font weight : Regular (400)</summary>
Regular = 400,
/// <summary>
/// Predefined font weight : Medium (500)</summary>
Medium = 500,
/// <summary>
/// Predefined font weight : Demi-bold (600)</summary>
DemiBold = 600,
/// <summary>
/// Predefined font weight : Semi-bold (600)</summary>
SemiBold = 600,
/// <summary>
/// Predefined font weight : Bold (700)</summary>
Bold = 700,
/// <summary>
/// Predefined font weight : Ultra-bold (800)</summary>
UltraBold = 800,
/// <summary>
/// Predefined font weight : Extra-bold (800)</summary>
ExtraBold = 800,
/// <summary>
/// Predefined font weight : Heavy (900)</summary>
Heavy = 900,
/// <summary>
/// Predefined font weight : Black (900)</summary>
Black = 900,
/// <summary>
/// Predefined font weight : Extra-black (950)</summary>
ExtraBlack = 950,
/// <summary>
/// Predefined font weight : Ultra-black (950)</summary>
UltraBlack = 950,
}
/// <summary>
/// Enum that represents the style of a font face as normal, italic, or oblique</summary>
/// <remarks>
/// Three terms categorize the slant of a font:
/// Normal: The characters in a normal, or roman, font are upright.
/// Italic: The characters in an italic font are truly slanted and appear as they were designed.
/// Oblique: The characters in an oblique font are artificially slanted.
/// For Oblique, the slant is achieved by performing a shear transformation on the characters
/// from a normal font. When a true italic font is not available on a computer or printer,
/// an oblique style can be generated from the normal font and used to simulate an italic font.
/// The following illustration shows the normal, italic, and oblique font styles for the Palatino
/// Linotype font. Notice how the italic font style has a more flowing and visually appealing
/// appearance than the oblique font style, which is simply created by skewing the normal font
/// style version of the text.</remarks>
public enum D2dFontStyle
{
/// <summary>
/// Font style : Normal</summary>
Normal = 0,
/// <summary>
/// Font style : Oblique</summary>
Oblique = 1,
/// <summary>
/// Font style : Italic</summary>
Italic = 2,
}
/// <summary>
/// Enum that represents the degree to which a font has been stretched compared to a font's
/// normal aspect ratio. The enumerated values correspond to the usWidthClass
/// definition in the OpenType specification. The usWidthClass represents an
/// integer value between 1 and 9. Lower values indicate narrower widths; higher
/// values indicate wider widths.</summary>
/// <remarks>
/// A font stretch describes the degree to which a font form is stretched from
/// its normal aspect ratio, which is the original width to height ratio specified
/// for the glyphs in the font.</remarks>
public enum D2dFontStretch
{
/// <summary>
/// Predefined font stretch : Not known (0)</summary>
Undefined = 0,
/// <summary>
/// Predefined font stretch : Ultra-condensed (1)</summary>
UltraCondensed = 1,
/// <summary>
/// Predefined font stretch : Extra-condensed (2)</summary>
ExtraCondensed = 2,
/// <summary>
/// Predefined font stretch : Condensed (3)</summary>
Condensed = 3,
/// <summary>
/// Predefined font stretch : Semi-condensed (4)</summary>
SemiCondensed = 4,
/// <summary>
/// Predefined font stretch : Normal (5)</summary>
Normal = 5,
/// <summary>
/// Predefined font stretch : Medium (5)</summary>
Medium = 5,
/// <summary>
/// Predefined font stretch : Semi-expanded (6)</summary>
SemiExpanded = 6,
/// <summary>
/// Predefined font stretch : Expanded (7)</summary>
Expanded = 7,
/// <summary>
/// Predefined font stretch : Extra-expanded (8)</summary>
ExtraExpanded = 8,
/// <summary>
/// Predefined font stretch : Ultra-expanded (9)</summary>
UltraExpanded = 9,
}
}
|
using System;
using System.Runtime.InteropServices;
namespace UsbNotify
{
public static partial class UsbNotification
{
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
internal struct DEV_BROADCAST_OEM
{
internal UInt32 dbch_size;
internal UInt32 dbch_devicetype;
internal UInt32 dbch_reserved;
internal uint dbco_identifier;
internal uint dbco_suppfunc;
};
}
} |
using System;
using System.Linq;
using System.Text.RegularExpressions;
namespace Westwind.AspNetCore.Markdown.Utilities
{
#region License
/*
**************************************************************
* Author: Rick Strahl
* (c) West Wind Technologies, 2008 - 2018
* http://www.west-wind.com/
*
* Created: 09/08/2018
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
**************************************************************
*/
#endregion
/// <summary>
/// String utility class that provides several string related operations.
///
/// Extracted from: westwind.utilities and internalized to avoid dependency
/// For more info see relevant methods in that library
/// </summary>
internal static class StringUtils
{
/// <summary>
/// Extracts a string from between a pair of delimiters. Only the first
/// instance is found.
/// </summary>
/// <param name="source">Input String to work on</param>
/// <param name="StartDelim">Beginning delimiter</param>
/// <param name="endDelim">ending delimiter</param>
/// <param name="CaseInsensitive">Determines whether the search for delimiters is case sensitive</param>
/// <returns>Extracted string or ""</returns>
public static string ExtractString(string source,
string beginDelim,
string endDelim,
bool caseSensitive = false,
bool allowMissingEndDelimiter = false,
bool returnDelimiters = false)
{
int at1, at2;
if (string.IsNullOrEmpty(source))
return string.Empty;
if (caseSensitive)
{
at1 = source.IndexOf(beginDelim);
if (at1 == -1)
return string.Empty;
at2 = source.IndexOf(endDelim, at1 + beginDelim.Length);
}
else
{
//string Lower = source.ToLower();
at1 = source.IndexOf(beginDelim, 0, source.Length, StringComparison.OrdinalIgnoreCase);
if (at1 == -1)
return string.Empty;
at2 = source.IndexOf(endDelim, at1 + beginDelim.Length, StringComparison.OrdinalIgnoreCase);
}
if (allowMissingEndDelimiter && at2 < 0)
{
if (!returnDelimiters)
return source.Substring(at1 + beginDelim.Length);
return source.Substring(at1);
}
if (at1 > -1 && at2 > 1)
{
if (!returnDelimiters)
return source.Substring(at1 + beginDelim.Length, at2 - at1 - beginDelim.Length);
return source.Substring(at1, at2 - at1 + endDelim.Length);
}
return string.Empty;
}
/// <summary>
/// Parses a string into an array of lines broken
/// by \r\n or \n
/// </summary>
/// <param name="s">String to check for lines</param>
/// <param name="maxLines">Optional - max number of lines to return</param>
/// <returns>array of strings, or empty array if the string passed was a null</returns>
public static string[] GetLines(string s, int maxLines = 0)
{
if (s == null)
return new string[] {};
s = s.Replace("\r\n", "\n");
if (maxLines < 1)
return s.Split('\n');
return s.Split('\n').Take(maxLines).ToArray();
}
/// <summary>
/// Note: this is an internal implementation which should duplicate what
/// Westwind.Utilities.HtmlUtils.SanitizeHtml() does. Avoids dependency
///
/// https://github.com/RickStrahl/Westwind.Utilities/blob/master/Westwind.Utilities/Utilities/HtmlUtils.cs#L255
/// </summary>
static string DefaultHtmlSanitizeTagBlackList { get; } = "script|iframe|object|embed|form";
static Regex _RegExScript = new Regex($@"(<({DefaultHtmlSanitizeTagBlackList})\b[^<]*(?:(?!<\/({DefaultHtmlSanitizeTagBlackList}))<[^<]*)*<\/({DefaultHtmlSanitizeTagBlackList})>)",
RegexOptions.IgnoreCase | RegexOptions.Multiline);
// strip javascript: and unicode representation of javascript:
// href='javascript:alert(\"gotcha\")'
// href='javascript:alert(\"gotcha\");'
static Regex _RegExJavaScriptHref = new Regex(
@"<[^>]*?\s(href|src|dynsrc|lowsrc)=.{0,20}((javascript:)|(&#)).*?>",
RegexOptions.IgnoreCase | RegexOptions.Singleline);
static Regex _RegExOnEventAttributes = new Regex(
@"<[^>]*?\s(on[^\s\\]{0,20}=([""].*?[""]|['].*?['])).*?(>|\/>)",
RegexOptions.IgnoreCase | RegexOptions.Singleline);
/// <summary>
/// Sanitizes HTML to some of the most of
/// </summary>
/// <remarks>
/// This provides rudimentary HTML sanitation catching the most obvious
/// XSS script attack vectors. For mroe complete HTML Sanitation please look into
/// a dedicated HTML Sanitizer.
/// </remarks>
/// <param name="html">input html</param>
/// <param name="htmlTagBlacklist">A list of HTML tags that are stripped.</param>
/// <returns>Sanitized HTML</returns>
public static string SanitizeHtml(string html, string htmlTagBlacklist = "script|iframe|object|embed|form")
{
if (string.IsNullOrEmpty(html))
return html;
if (string.IsNullOrEmpty(htmlTagBlacklist) || htmlTagBlacklist == DefaultHtmlSanitizeTagBlackList)
{
// Replace Script tags - reused expr is more efficient
html = _RegExScript.Replace(html, string.Empty);
}
else
{
html = Regex.Replace(html,
$@"(<({htmlTagBlacklist})\b[^<]*(?:(?!<\/({DefaultHtmlSanitizeTagBlackList}))<[^<]*)*<\/({htmlTagBlacklist})>)",
"", RegexOptions.IgnoreCase | RegexOptions.Multiline);
}
// Remove javascript: directives
var matches = _RegExJavaScriptHref.Matches(html);
foreach (Match match in matches)
{
if (match.Groups.Count > 2)
{
var txt = match.Value.Replace(match.Groups[2].Value, "unsupported:");
html = html.Replace(match.Value, txt);
}
}
// Remove onEvent handlers from elements
matches = _RegExOnEventAttributes.Matches(html);
foreach (Match match in matches)
{
var txt = match.Value;
if (match.Groups.Count > 1)
{
var onEvent = match.Groups[1].Value;
txt = txt.Replace(onEvent, string.Empty);
if (!string.IsNullOrEmpty(txt))
html = html.Replace(match.Value, txt);
}
}
return html;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace VideoLibrary
{
internal interface IService<T> where T : Video
{
T GetVideo(string uri);
IEnumerable<T> GetAllVideos(string uri);
}
}
|
namespace Drawmasters.Levels
{
public class ProjectileColoredEnemyApplyRagdollComponent : ProjectileEnemyApplyRagdollComponent
{
#region Ctor
public ProjectileColoredEnemyApplyRagdollComponent(CollisionNotifier _collisionNotifier)
: base(_collisionNotifier)
{
}
#endregion
#region Abstract implementation
protected override bool CanHitTarget(LevelTarget levelTarget, CollidableObjectType collidableObjectType)
{
bool result = base.CanHitTarget(levelTarget, collidableObjectType);
result &= ColorTypesSolutions.CanHitEnemy(mainProjectile, levelTarget);
return result;
}
#endregion
}
}
|
using System;
using System.Numerics;
using Veldrid;
using Veldrid.Graphics;
using Veldrid.Graphics.Pipeline;
namespace Engine.Graphics
{
public class ShadowMapStage : PipelineStage
{
private const int DepthMapWidth = 4096;
private const int DepthMapHeight = 4096;
private readonly RenderQueue _queue = new RenderQueue();
private readonly string _contextBindingName = "ShadowMap";
private readonly DynamicDataProvider<Matrix4x4> _lightViewProvider = new DynamicDataProvider<Matrix4x4>();
private readonly DynamicDataProvider<Matrix4x4> _lightProjectionProvider = new DynamicDataProvider<Matrix4x4>();
private Framebuffer _shadowMapFramebuffer;
private DeviceTexture2D _depthTexture;
public bool Enabled { get; set; } = true;
public string Name => "ShadowMap";
public RenderContext RenderContext { get; private set; }
public DirectionalLight Light { get; set; }
public Camera MainCamera { get; set; }
public ShadowMapStage(RenderContext rc, string contextBindingName = "ShadowMap")
{
RenderContext = rc;
_contextBindingName = contextBindingName;
rc.RegisterGlobalDataProvider("LightViewMatrix", _lightViewProvider);
rc.RegisterGlobalDataProvider("LightProjMatrix", _lightProjectionProvider);
}
public void ChangeRenderContext(RenderContext rc)
{
RenderContext = rc;
InitializeContextObjects(rc);
}
private void InitializeContextObjects(RenderContext rc)
{
_depthTexture = rc.ResourceFactory.CreateDepthTexture(DepthMapWidth, DepthMapHeight, sizeof(ushort), PixelFormat.Alpha_UInt16);
_shadowMapFramebuffer = rc.ResourceFactory.CreateFramebuffer();
_shadowMapFramebuffer.DepthTexture = _depthTexture;
rc.GetTextureContextBinding(_contextBindingName).Value = _depthTexture;
}
public void ExecuteStage(VisibiltyManager visibilityManager, Vector3 cameraPosition)
{
UpdateLightProjection();
RenderContext.ClearScissorRectangle();
RenderContext.SetFramebuffer(_shadowMapFramebuffer);
RenderContext.ClearBuffer();
RenderContext.SetViewport(0, 0, DepthMapWidth, DepthMapHeight);
_queue.Clear();
visibilityManager.CollectVisibleObjects(_queue, "ShadowMap", Vector3.Zero);
_queue.Sort();
foreach (RenderItem item in _queue)
{
item.Render(RenderContext, "ShadowMap");
}
}
private void UpdateLightProjection()
{
if (MainCamera == null)
{
return;
}
if (Light == null)
{
_lightProjectionProvider.Data = Matrix4x4.Identity;
_lightViewProvider.Data = Matrix4x4.Identity;
return;
}
Vector3 cameraDir = MainCamera.Transform.Forward;
Vector3 unitY = Vector3.UnitY;
Vector3 cameraPosition = MainCamera.Transform.Position;
FrustumCorners corners;
FrustumHelpers.ComputePerspectiveFrustumCorners(
ref cameraPosition,
ref cameraDir,
ref unitY,
MainCamera.FieldOfViewRadians,
MainCamera.NearPlaneDistance,
MainCamera.FarPlaneDistance,
(float)RenderContext.Window.Width / (float)RenderContext.Window.Height,
out corners);
// Approach used: http://alextardif.com/ShadowMapping.html
Vector3 frustumCenter = Vector3.Zero;
frustumCenter += corners.NearTopLeft;
frustumCenter += corners.NearTopRight;
frustumCenter += corners.NearBottomLeft;
frustumCenter += corners.NearBottomRight;
frustumCenter += corners.FarTopLeft;
frustumCenter += corners.FarTopRight;
frustumCenter += corners.FarBottomLeft;
frustumCenter += corners.FarBottomRight;
frustumCenter /= 8f;
float radius = (corners.NearTopLeft - corners.FarBottomRight).Length() / 2.0f;
float texelsPerUnit = (float)DepthMapWidth / (radius * 2.0f);
Matrix4x4 scalar = Matrix4x4.CreateScale(texelsPerUnit, texelsPerUnit, texelsPerUnit);
var _lightDirection = Light.Direction;
Vector3 baseLookAt = -_lightDirection;
Matrix4x4 lookat = Matrix4x4.CreateLookAt(Vector3.Zero, baseLookAt, Vector3.UnitY);
lookat = scalar * lookat;
Matrix4x4 lookatInv;
Matrix4x4.Invert(lookat, out lookatInv);
frustumCenter = Vector3.Transform(frustumCenter, lookat);
frustumCenter.X = (int)frustumCenter.X;
frustumCenter.Y = (int)frustumCenter.Y;
frustumCenter = Vector3.Transform(frustumCenter, lookatInv);
Vector3 lightPos = frustumCenter - (_lightDirection * radius * 2f);
Matrix4x4 lightView = Matrix4x4.CreateLookAt(lightPos, frustumCenter, Vector3.UnitY);
_lightProjectionProvider.Data = Matrix4x4.CreateOrthographicOffCenter(
-radius, radius, -radius, radius, -radius * 4f, radius * 4f);
_lightViewProvider.Data = lightView;
}
private void Dispose()
{
_shadowMapFramebuffer.Dispose();
}
}
}
|
using System;
using System.IO;
using MessageBird.Net;
using MessageBird.Net.ProxyConfigurationInjector;
using MessageBird.Resources;
using Moq;
using Newtonsoft.Json.Linq;
namespace MessageBirdUnitTests
{
/// <summary>
/// Helper that offers a convenient way to create and configure a RestClient mock with a fluent API.
///
/// <example>
/// The example below fails the test if the MessageBird Client does not
/// generate the expected request. Assertions can be made on the response
/// to assert it is deserialized correctly.
/// <code>
/// var restClient = MockRestClient.ThatExpects(requestBody).AndReturns(responseBody).FromEndpoint("POST", "messages").Get();
/// var client = new Client(restClient);
///
/// client.SendMessage(...)
/// </code>
/// </example>
/// </summary>
public class MockRestClient
{
private const string AccessKey = "";
private const IProxyConfigurationInjector ProxyConfigurationInjector = null;
private MockRepository mockRepository;
private string RequestBody { get; set; }
private string ResponseBody { get; set; }
private Stream ResponseStream { get; set; }
private string Method { get; set; }
private string Uri { get; set; }
private string BaseUrl { get; set; }
private MockRestClient()
{
// MockBehavior.Strict configures the mocks to throw exceptions
// when invoked without a corresponding setup, rather than
// returning "default" values (empty arrays, null et al).
mockRepository = new MockRepository(MockBehavior.Strict)
{
// Never invoke the base class implementation.
CallBase = false,
};
}
/// <summary>
/// Actually creates the mock and configures it as specified.
/// </summary>
public Mock<RestClient> Get()
{
var restClient = mockRepository.Create<RestClient>(AccessKey, ProxyConfigurationInjector);
if (ResponseBody == null && ResponseStream == null)
{
throw new Exception("Mock must be configured to return a response body or stream.");
}
if (Method == null || Uri == null)
{
throw new Exception("Mock must be configured to expect a HTTP method and URI.");
}
// Handle the overload...
if (ResponseStream != null)
{
restClient.Setup(c => c.PerformHttpRequest(Uri, It.IsAny<HttpStatusCode>(), BaseUrl)).Returns(ResponseStream).Verifiable();
}
else if (RequestBody == null)
{
restClient.Setup(c => c.PerformHttpRequest(Method, Uri, It.IsAny<HttpStatusCode>(), BaseUrl)).Returns(ResponseBody).Verifiable();
}
else
{
restClient.Setup(c => c.PerformHttpRequest(Method, Uri,
It.Is<string>(arg => JToken.DeepEquals(JToken.Parse(RequestBody), JToken.Parse(arg))),
It.IsAny<HttpStatusCode>(), BaseUrl)).Returns(ResponseBody).Verifiable();
}
return restClient;
}
/// <summary>
/// Creates a mock client and sets the expected request body.
/// </summary>
public static MockRestClient ThatExpects(string requestBody)
{
return new MockRestClient { RequestBody = requestBody };
}
/// <summary>
/// Creates a mock client and sets the expected response body.
/// </summary>
public static MockRestClient ThatReturns(string responseBody = null, string filename = null, Stream stream = null)
{
string mockResponseBody = string.Empty;
if (!string.IsNullOrEmpty(responseBody))
{
mockResponseBody = responseBody;
}
else if (!string.IsNullOrEmpty(filename))
{
mockResponseBody = File.ReadAllText(Path.Combine(Environment.CurrentDirectory, @"Responses", filename));
}
return new MockRestClient
{
ResponseBody = mockResponseBody,
ResponseStream = stream
};
}
/// <summary>
/// Sets the expected response body from string or json file name.
/// </summary>
public MockRestClient AndReturns(string responseBody = null, string filename = null)
{
ResponseBody = responseBody ?? File.ReadAllText(Path.Combine(Environment.CurrentDirectory, @"Responses", filename));
return this;
}
/// <summary>
/// Sets the expected (HTTP) method.
/// </summary>
public MockRestClient FromEndpoint(string method, string uri, string baseUrl = null)
{
Method = method;
Uri = uri;
BaseUrl = baseUrl ?? Resource.DefaultBaseUrl;
return this;
}
}
}
|
// CommandLineArgsUtils
using System;
using System.Collections;
using System.Text;
public static class CommandLineArgsUtils
{
public static Hashtable GetCommandLineArgs()
{
return GetCommandLineArgs(Environment.GetCommandLineArgs());
}
public static Hashtable GetCommandLineArgs(string[] argsArray)
{
Hashtable hashtable = new Hashtable();
for (int i = 0; i < argsArray.Length; i++)
{
if (argsArray[i].StartsWith("-"))
{
if (argsArray[i].Contains("="))
{
string[] array = argsArray[i].Split('=');
hashtable[array[0].Substring(1)] = array[1];
}
else if (i + 1 < argsArray.Length && !argsArray[i + 1].StartsWith("-"))
{
hashtable[argsArray[i].Substring(1)] = argsArray[i + 1];
}
else
{
hashtable[argsArray[i].Substring(1)] = true;
}
}
}
return hashtable;
}
public static StringBuilder AppendArg(StringBuilder stringBuilder, string key, object value)
{
if (stringBuilder == null)
{
throw new ArgumentNullException("stringBuilder");
}
if (value == null)
{
throw new ArgumentNullException("value");
}
stringBuilder.AppendFormat(" -{0} {1}", EscapeSpaces(key), EscapeSpaces(value.ToString()));
return stringBuilder;
}
public static StringBuilder AppendArg(StringBuilder stringBuilder, string key)
{
if (stringBuilder == null)
{
throw new ArgumentNullException("stringBuilder");
}
stringBuilder.AppendFormat(" -{0}", EscapeSpaces(key));
return stringBuilder;
}
public static string EscapeSpaces(string arg)
{
if (arg.Contains(" "))
{
return $"\"{arg}\"";
}
return arg;
}
}
|
namespace Polycular.Clustar
{
public interface IGraphComponent
{
string Id { get; }
string Type { get; }
int OrderId { get; }
}
} |
/*===========================================================================*/
/*
* * FileName : AutoFireShot.cs
*
* * Author : Hiroki_Kitahara.
*/
/*===========================================================================*/
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
/// <summary>
/// .
/// </summary>
public class AutoFireShot : MonoBehaviour
{
[SerializeField]
private int delay;
[SerializeField]
private List<PlayerShotFire> refShotFireList;
void Update()
{
if( delay > 0 )
{
delay--;
return;
}
refShotFireList.ForEach( s =>
{
s.Fire();
});
}
void OnPlayerSelectMode()
{
enabled = true;
}
}
|
using SCPVisualization.MVVM;
using UnityEngine.UIElements;
namespace SCPVisualization.Screens
{
public class SCPLibraryViewModel : ViewModel<SCPLibraryModel>
{
private Button ReturnToMenuButton { get; set; }
private void Awake ()
{
Model.OnGetRootVisualElement += GetRootVisualElement;
ReturnToMenuButton = View.rootVisualElement.Q<Button>("ReturnToMenu");
}
private void OnEnable ()
{
ReturnToMenuButton.clicked += Model.ReturnToMenu;
}
private void OnDisable ()
{
ReturnToMenuButton.clicked -= Model.ReturnToMenu;
}
private void OnDestroy ()
{
if (Model != null)
{
Model.OnGetRootVisualElement -= GetRootVisualElement;
}
}
private VisualElement GetRootVisualElement ()
{
return View.rootVisualElement;
}
}
} |
using System.Net.Sockets;
namespace Titanium.Web.Proxy.Extensions
{
internal static class TcpExtensions
{
/// <summary>
/// verifies if the underlying socket is connected before using a TcpClient connection
/// </summary>
/// <param name="client"></param>
/// <returns></returns>
internal static bool IsConnected(this Socket client)
{
// This is how you can determine whether a socket is still connected.
bool blockingState = client.Blocking;
try
{
byte[] tmp = new byte[1];
client.Blocking = false;
client.Send(tmp, 0, 0);
return true;
}
catch (SocketException e)
{
// 10035 == WSAEWOULDBLOCK
if (e.NativeErrorCode.Equals(10035))
{
return true;
}
else
{
return false;
}
}
finally
{
client.Blocking = blockingState;
}
}
}
}
|
using System;
namespace PolyglotHeaven.Infrastructure
{
public class IdGenerator
{
private static Func<Guid> _generator;
public static Func<Guid> GenerateGuid
{
get
{
_generator = _generator ?? Guid.NewGuid;
return _generator;
}
set { _generator = value; }
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace FX.Core.IO.Files.Enums
{
public enum FileTypes { Excel, CSV };
}
|
using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using WizBot.Services.Database.Models;
namespace WizBot.Db
{
public static class CurrencyTransactionExtensions
{
public static List<CurrencyTransaction> GetPageFor(this DbSet<CurrencyTransaction> set, ulong userId, int page)
{
return set.AsQueryable()
.AsNoTracking()
.Where(x => x.UserId == userId)
.OrderByDescending(x => x.DateAdded)
.Skip(15 * page)
.Take(15)
.ToList();
}
}
} |
using EPiServer.Core;
using EPiServer.DataAbstraction;
using EPiServer.DataAnnotations;
using EPiServer.Framework.DataAnnotations;
using System.ComponentModel.DataAnnotations;
namespace Lorem.Models.Media
{
public abstract class SiteImageFile
: ImageData
{
[Display(GroupName = SystemTabNames.Content, Order = 10)]
public virtual string Heading { get; set; }
}
} |
using System.Reflection;
using UnityEngine;
namespace UnityEditor.ShaderGraph
{
[Title("Procedural", "Shape", "Rounded Rectangle")]
class RoundedRectangleNode : CodeFunctionNode
{
public RoundedRectangleNode()
{
name = "Rounded Rectangle";
}
protected override MethodInfo GetFunctionToConvert()
{
return GetType().GetMethod("Unity_RoundedRectangle", BindingFlags.Static | BindingFlags.NonPublic);
}
static string Unity_RoundedRectangle(
[Slot(0, Binding.MeshUV0)] Vector2 UV,
[Slot(1, Binding.None, 0.5f, 0, 0, 0)] Vector1 Width,
[Slot(2, Binding.None, 0.5f, 0, 0, 0)] Vector1 Height,
[Slot(3, Binding.None, 0.1f, 0, 0, 0)] Vector1 Radius,
[Slot(4, Binding.None, ShaderStageCapability.Fragment)] out Vector1 Out)
{
return
@"
{
Radius = max(min(min(abs(Radius * 2), abs(Width)), abs(Height)), 1e-5);
$precision2 uv = abs(UV * 2 - 1) - $precision2(Width, Height) + Radius;
$precision d = length(max(0, uv)) / Radius;
Out = saturate((1 - d) / fwidth(d));
}";
}
}
}
|
namespace Simple.Data
{
using System.Collections.Generic;
using Extensions;
public class AdoCompatibleComparer : IEqualityComparer<string>
{
public static readonly HomogenizedEqualityComparer DefaultInstance = new HomogenizedEqualityComparer();
public bool Equals(string x, string y)
{
return ReferenceEquals(x, y.Homogenize())
|| x.Homogenize() == y.Homogenize()
|| x.Homogenize().Singularize() == y.Homogenize().Singularize();
}
public int GetHashCode(string obj)
{
return obj.Homogenize().Singularize().GetHashCode();
}
}
} |
using System;
namespace StoreUI
{
public interface IValidationService
{
string ValidateEmptyInput(string prompt);
decimal ValidatePrice(string prompt);
int ValidateQuantity(string prompt);
string ValidateBarcode(string prompt);
DateTime ValidateDate(string prompt);
public string ValidateValidCommand(string prompt);
}
} |
using AElf.Types;
using Google.Protobuf;
namespace AElf.Kernel.TransactionPool
{
public static class FakeTransaction
{
public static Transaction Generate()
{
var transaction = new Transaction()
{
From = SampleAddress.AddressList[0],
To = SampleAddress.AddressList[1],
MethodName = "test",
Params = ByteString.CopyFromUtf8("test")
};
return transaction;
}
}
} |
using System;
using System.Collections.Generic;
namespace Mohmd.AspNetCore.Proxify.Attributes
{
[AttributeUsage(AttributeTargets.Interface | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class IgnoreInterceptorsAttribute : Attribute
{
public IgnoreInterceptorsAttribute(params Type[] interceptorTypes)
{
Interceptors = interceptorTypes;
}
public IReadOnlyList<Type> Interceptors { get; private set; }
}
}
|
namespace Codefire.ExpressionEvaluator.Expressions
{
public class DivideExpression : BinaryExpression
{
public DivideExpression(Expression left, Expression right)
: base(left, right)
{
}
public override decimal? Invoke(EvaluatorContext context)
{
var leftValue = Left.Invoke(context);
var rightValue = Right.Invoke(context);
// Don't throw a divide by zero exception, return 0
// Buuuutttt, if the left value is null then let's return null rather.
if (rightValue == 0) return leftValue == null ? (decimal?)null : 0M;
return leftValue / rightValue;
}
}
} |
namespace Cloudlucky.GuardClauses;
internal static class GuardMessages
{
public static string Default(string? message = default)
=> message ?? "Value must not be default (null or default).";
public static string NotDefault(string? message = default)
=> message ?? "Value must be default (null or default).";
public static string Empty(string? message = default)
=> message ?? "Value must not be empty.";
public static string NotEmpty(string? message = default)
=> message ?? "Value must be empty.";
public static string Null(string? message = default)
=> message ?? "Value must not be null.";
public static string NotNull(string? message = default)
=> message ?? "Value must be null.";
public static string OutOfRange(string? message = default)
=> message ?? "Value must be in range.";
public static string InRange(string? message = default)
=> message ?? "Value must be out of range.";
public static string Found(string? message = default)
=> message ?? "Value must not be null or default";
public static string NotFound(string? message = default)
=> message ?? "Value must be null or default";
public static string NotNullOrEmpty(string? message = default)
=> message ?? "Value must be null or empty";
public static string GreaterThan(string? message = default)
=> message ?? "Value must not be greater than.";
public static string NotGreaterThan(string? message = default)
=> message ?? "Value must be greater than.";
public static string GreaterThanOrEqualTo(string? message = default)
=> message ?? "Value must not be greater than or equal to.";
public static string NotGreaterThanOrEqualTo(string? message = default)
=> message ?? "Value must be greater than or equal to.";
public static string LessThan(string? message = default)
=> message ?? "Value must not be less than.";
public static string NotLessThan(string? message = default)
=> message ?? "Value must be less than.";
public static string LessThanOrEqualTo(string? message = default)
=> message ?? "Value must not be less than or equal to.";
public static string NotLessThanOrEqualTo(string? message = default)
=> message ?? "Value must be less than or equal to.";
public static string Zero(string? message = default)
=> message ?? "Value must not be zero.";
public static string NotZero(string? message = default)
=> message ?? "Value must be zero.";
}
|
using AutoMapper;
namespace DlnaController.Domain
{
internal class DtoMapperProfile: Profile
{
public DtoMapperProfile()
{
// TODO: call CreateMap here
}
}
} |
using LHGames.Helper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace LHGames.Interfaces
{
public interface IAStar
{
List<Tile> Run(int startX, int startY, int endX, int endY);
List<Tile> Run(Point start, Point end);
List<Tile> Run(Tile start, Tile end);
Point DirectionToward(Point start, Point end);
}
}
|
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Diagnostics.CodeAnalysis;
using NuGet.VisualStudio;
namespace NuGetConsole.Host.PowerShell.Implementation
{
public static class PowerShellHostService
{
private static readonly IRunspaceManager _runspaceManager = new RunspaceManager();
[SuppressMessage(
"Microsoft.Reliability",
"CA2000:Dispose objects before losing scope",
Justification = "Can't dispose an object if we want to return it.")]
public static IHost CreateHost(string name, IRestoreEvents restoreEvents, bool isAsync)
{
IHost host;
if (isAsync)
{
host = new AsyncPowerShellHost(name, restoreEvents, _runspaceManager);
}
else
{
host = new SyncPowerShellHost(name, restoreEvents, _runspaceManager);
}
return host;
}
}
}
|
using System.Collections;
using UnityEngine;
public class Player : MonoBehaviour {
public float Speed = 3f;
// public Sprite IconLeft;
// public Sprite IconUp;
// public Sprite IconRight;
// public Sprite IconDown;
public Transform ShootPosition; //子弹发射位置
public GameObject Bullect;
//方向
private Dir _dir = Dir.Up;
private SpriteRenderer _sp;
private bool _canShoot = true;
private Animator moveAnim;
private void Awake() {
_sp = GetComponent<SpriteRenderer>();
moveAnim = GetComponent<Animator>();
}
// Use this for initialization
void Start() {
}
// Update is called once per frame
void Update() {
}
private void FixedUpdate() {
var h = Input.GetAxisRaw("Horizontal");
var v = Input.GetAxisRaw("Vertical");
Move(h, v);
Shoot();
}
private void Move(float h, float v) {
if (h != 0f || v != 0f) {
moveAnim.SetBool("isMoving",true);
}
else {
moveAnim.SetBool("isMoving",false);
}
//切换图片
if (h > 0) //right
{
transform.eulerAngles = new Vector3(0, 0, -90); //由欧拉角直接指定
//改变方向
_dir = Dir.Right;
//设置图片
}
else if (h < 0) {
_dir = Dir.Left;
transform.eulerAngles = new Vector3(0, 0, 90); //由欧拉角直接指定
}
if (v > 0) {
_dir = Dir.Up;
transform.eulerAngles = new Vector3(0, 0, 0); //由欧拉角直接指定
}
else if (v < 0) {
_dir = Dir.Down;
transform.eulerAngles = new Vector3(0, 0, 180); //由欧拉角直接指定
}
transform.Translate(Vector2.right * h * Speed * Time.deltaTime, Space.World);
transform.Translate(Vector2.up * v * Speed * Time.deltaTime, Space.World);
}
private void Shoot() {
if (Input.GetKeyDown(KeyCode.Space)) {
if (_canShoot) {
Instantiate(Bullect, ShootPosition.position, ShootPosition.rotation);
_canShoot = false;
StartCoroutine(WaitShoot());
}
}
}
private enum Dir {
Left,
Up,
Right,
Down
}
private IEnumerator WaitShoot() {
yield return new WaitForSeconds(.45f);
_canShoot = true;
}
} |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SleepToCsv.Events;
using SleepToCsv.Movements;
using SleepToCsv.Summary;
namespace SleepToCsv
{
class Program
{
static void Main(string[] args)
{
try
{
if (!args.Any())
DisplayHelp();
var sourceFile = args[0];
var targetFolder = args[1];
new CreateSummaryFileCommand()
.Execute(sourceFile, targetFolder);
new CreateMovementsFileCommand()
.Execute(sourceFile, targetFolder);
new CreateEventsFileCommand()
.Execute(sourceFile, targetFolder);
Exit();
}
catch (Exception ex)
{
Console.WriteLine("FATAL: {0}", ex.Message);
Exit();
}
}
private static void DisplayHelp()
{
var help = new StringBuilder()
.AppendLine("Converts Sleep as Android .csv files to summary, movements, and events .csv files")
.AppendLine("Usage: SleepToCsv.exe source-file target-folder")
.AppendLine()
.AppendLine("The parameters are:")
.AppendLine(" source-file - the file containing the Sleep as Android .csv file")
.AppendLine(" target-folder - the folder to write the real .csv files to")
.AppendLine()
.AppendLine("Example: SleepAsAndroid.exe \"C:\\Source\\sleep-export.csv\" \"C:\\Target\"");
Console.WriteLine(help.ToString());
Exit();
}
private static void Exit()
{
Console.WriteLine();
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
Environment.Exit(0);
}
}
}
|
using SummerBoot.Repository;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using SummerBoot.Repository.Attributes;
using SummerBoot.WebApi.Models;
namespace SummerBoot.Test.Repository
{
[AutoRepository]
public interface ICustomerRepository :IBaseRepository<Customer>
{
//一部
[Select("select od.productName from customer c join orderHeader oh on c.id=oh.customerid" +
" join orderDetail od on oh.id=od.OrderHeaderId where c.name=@name")]
Task<List<CustomerBuyProduct>> QueryAllBuyProductByNameAsync(string name);
[Select("select * from customer where age>@age order by id")]
Task<Page<Customer>> GetCustomerByPageAsync(IPageable pageable, int age);
[Update("update customer set name=@name where age>@age")]
Task<int> UpdateCustomerAsync(string name,int age);
[Update("update customer set name=@name where age>@age")]
Task UpdateCustomerTask(string name, int age);
[Delete("delete from customer where age>@age")]
Task<int> DeleteCustomerAsync( int age);
[Delete("delete from customer where age>@age")]
Task DeleteCustomerTask(int age);
[Select("select CreateTime from orderHeader where OrderNo='fffdsfdsf'")]
Task<DateTime> GetDatetime();
//同步
[Select("select od.productName from customer c join orderHeader oh on c.id=oh.customerid" +
" join orderDetail od on oh.id=od.OrderHeaderId where c.name=@name")]
List<CustomerBuyProduct> QueryAllBuyProductByName(string name);
[Select("select * from customer where age>@age order by id")]
Page<Customer> GetCustomerByPage(IPageable pageable, int age);
[Update("update customer set name=@name where age>@age")]
int UpdateCustomer(string name, int age);
[Update("update customer set name=@name where age>@age")]
void UpdateCustomerVoid(string name, int age);
[Delete("delete from customer where age>@age")]
int DeleteCustomer(int age);
[Delete("delete from customer where age>@age")]
void DeleteCustomerNoReturn(int age);
}
} |
namespace Xtaieer.Regular
{
/// <summary>
/// 正则表达式的抽象语法树的一个叶子节点,代表一个字符
/// </summary>
public class SingleCharLeafExpression : IRegularExpression
{
private char c;
/// <summary>
/// 使用一个字符构造抽象语法树的叶子节点
/// </summary>
/// <param name="c"></param>
public SingleCharLeafExpression(char c)
{
this.c = c;
}
/// <summary>
/// 访问者模式的实现。以所代表的字符为参数调用<c>IRegularExpressionVisitor.SingleCharLeaf</c>方法
/// </summary>
/// <param name="visitor">访问者</param>
void IRegularExpression.Accept(IRegularExpressionVisitor visitor)
{
visitor.SingleCharLeaf(c);
}
}
}
|
using Abp.AutoMapper;
using Abp.Modules;
using Abp.Reflection.Extensions;
using PMTool16Bit.Authorization;
using PMTool16Bit.Services;
using PMTool16Bit.Models;
namespace PMTool16Bit
{
[DependsOn(
typeof(PMTool16BitCoreModule),
typeof(AbpAutoMapperModule))]
public class PMTool16BitApplicationModule : AbpModule
{
public override void PreInitialize()
{
Configuration.Authorization.Providers.Add<PMTool16BitAuthorizationProvider>();
}
public override void Initialize()
{
var thisAssembly = typeof(PMTool16BitApplicationModule).GetAssembly();
IocManager.RegisterAssemblyByConvention(thisAssembly);
Configuration.Modules.AbpAutoMapper().Configurators.Add(
// Scan the assembly for classes which inherit from AutoMapper.Profile
cfg => {
cfg.AddProfiles(thisAssembly);
//cfg.CreateMap<Foo, FooCopy>()
// .ForMember(x =>x.Text, opt => opt.Ignore())
// .ForMember(x => x.Age , opt => opt.Ignore() );
cfg.CreateMap<ProjectCreateDto, Project>()
.ForMember(x => x.GroupTasks, opt => opt.Ignore());
cfg.CreateMap<ProjectMemberDto, ProjectMember>()
.ForMember(x => x.Id, opt => opt.Ignore())
.ForMember(x => x.Project, opt => opt.Ignore())
.ForMember(x => x.Member, opt => opt.Ignore())
;
}
);
}
}
}
|
namespace CyberCAT.Core.DumpedEnums
{
public enum CraftingMode
{
craft = 0,
upgrade = 1
}
}
|
namespace MemoScope.Modules.TypeDetails
{
partial class TypeDetailsModule
{
/// <summary>
/// Variable nécessaire au concepteur.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Nettoyage des ressources utilisées.
/// </summary>
/// <param name="disposing">true si les ressources managées doivent être supprimées ; sinon, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Code généré par le Concepteur de composants
/// <summary>
/// Méthode requise pour la prise en charge du concepteur - ne modifiez pas
/// le contenu de cette méthode avec l'éditeur de code.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.splitContainer1 = new System.Windows.Forms.SplitContainer();
this.splitContainer3 = new System.Windows.Forms.SplitContainer();
this.gbTypeInformation = new System.Windows.Forms.GroupBox();
this.pgTypeInfo = new System.Windows.Forms.PropertyGrid();
this.gbFiledProperties = new System.Windows.Forms.GroupBox();
this.dlvFields = new WinFwk.UITools.DefaultListView();
this.gbMethods = new System.Windows.Forms.GroupBox();
this.dlvMethods = new WinFwk.UITools.DefaultListView();
this.splitContainer2 = new System.Windows.Forms.SplitContainer();
this.gbInterfaces = new System.Windows.Forms.GroupBox();
this.dtlvParentClasses = new WinFwk.UITools.DefaultTreeListView();
((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).BeginInit();
this.splitContainer1.Panel1.SuspendLayout();
this.splitContainer1.Panel2.SuspendLayout();
this.splitContainer1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.splitContainer3)).BeginInit();
this.splitContainer3.Panel1.SuspendLayout();
this.splitContainer3.Panel2.SuspendLayout();
this.splitContainer3.SuspendLayout();
this.gbTypeInformation.SuspendLayout();
this.gbFiledProperties.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.dlvFields)).BeginInit();
this.gbMethods.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.dlvMethods)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.splitContainer2)).BeginInit();
this.splitContainer2.Panel1.SuspendLayout();
this.splitContainer2.Panel2.SuspendLayout();
this.splitContainer2.SuspendLayout();
this.gbInterfaces.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.dtlvParentClasses)).BeginInit();
this.SuspendLayout();
//
// splitContainer1
//
this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill;
this.splitContainer1.Location = new System.Drawing.Point(0, 0);
this.splitContainer1.Name = "splitContainer1";
this.splitContainer1.Orientation = System.Windows.Forms.Orientation.Horizontal;
//
// splitContainer1.Panel1
//
this.splitContainer1.Panel1.Controls.Add(this.splitContainer3);
//
// splitContainer1.Panel2
//
this.splitContainer1.Panel2.Controls.Add(this.gbMethods);
this.splitContainer1.Size = new System.Drawing.Size(460, 531);
this.splitContainer1.SplitterDistance = 350;
this.splitContainer1.TabIndex = 0;
//
// splitContainer3
//
this.splitContainer3.Dock = System.Windows.Forms.DockStyle.Fill;
this.splitContainer3.Location = new System.Drawing.Point(0, 0);
this.splitContainer3.Name = "splitContainer3";
//
// splitContainer3.Panel1
//
this.splitContainer3.Panel1.Controls.Add(this.gbTypeInformation);
//
// splitContainer3.Panel2
//
this.splitContainer3.Panel2.Controls.Add(this.splitContainer2);
this.splitContainer3.Size = new System.Drawing.Size(460, 350);
this.splitContainer3.SplitterDistance = 224;
this.splitContainer3.TabIndex = 1;
//
// gbTypeInformation
//
this.gbTypeInformation.Controls.Add(this.pgTypeInfo);
this.gbTypeInformation.Dock = System.Windows.Forms.DockStyle.Fill;
this.gbTypeInformation.Location = new System.Drawing.Point(0, 0);
this.gbTypeInformation.Name = "gbTypeInformation";
this.gbTypeInformation.Size = new System.Drawing.Size(224, 350);
this.gbTypeInformation.TabIndex = 0;
this.gbTypeInformation.TabStop = false;
this.gbTypeInformation.Text = "Informations";
//
// pgTypeInfo
//
this.pgTypeInfo.CategoryForeColor = System.Drawing.SystemColors.InactiveCaptionText;
this.pgTypeInfo.Dock = System.Windows.Forms.DockStyle.Fill;
this.pgTypeInfo.HelpVisible = false;
this.pgTypeInfo.Location = new System.Drawing.Point(3, 18);
this.pgTypeInfo.Name = "pgTypeInfo";
this.pgTypeInfo.Size = new System.Drawing.Size(218, 329);
this.pgTypeInfo.TabIndex = 0;
this.pgTypeInfo.ToolbarVisible = false;
//
// gbFiledProperties
//
this.gbFiledProperties.Controls.Add(this.dlvFields);
this.gbFiledProperties.Dock = System.Windows.Forms.DockStyle.Fill;
this.gbFiledProperties.Location = new System.Drawing.Point(0, 0);
this.gbFiledProperties.Name = "gbFiledProperties";
this.gbFiledProperties.Size = new System.Drawing.Size(232, 175);
this.gbFiledProperties.TabIndex = 0;
this.gbFiledProperties.TabStop = false;
this.gbFiledProperties.Text = "Fields / Properties";
//
// dlvFields
//
this.dlvFields.Dock = System.Windows.Forms.DockStyle.Fill;
this.dlvFields.FullRowSelect = true;
this.dlvFields.HideSelection = false;
this.dlvFields.Location = new System.Drawing.Point(3, 18);
this.dlvFields.Name = "dlvFields";
this.dlvFields.OwnerDraw = true;
this.dlvFields.ShowGroups = false;
this.dlvFields.ShowImagesOnSubItems = true;
this.dlvFields.Size = new System.Drawing.Size(226, 154);
this.dlvFields.TabIndex = 0;
this.dlvFields.UseCompatibleStateImageBehavior = false;
this.dlvFields.View = System.Windows.Forms.View.Details;
this.dlvFields.VirtualMode = true;
//
// gbMethods
//
this.gbMethods.Controls.Add(this.dlvMethods);
this.gbMethods.Dock = System.Windows.Forms.DockStyle.Fill;
this.gbMethods.Location = new System.Drawing.Point(0, 0);
this.gbMethods.Name = "gbMethods";
this.gbMethods.Size = new System.Drawing.Size(460, 177);
this.gbMethods.TabIndex = 1;
this.gbMethods.TabStop = false;
this.gbMethods.Text = "Methods";
//
// dlvMethods
//
this.dlvMethods.Dock = System.Windows.Forms.DockStyle.Fill;
this.dlvMethods.FullRowSelect = true;
this.dlvMethods.HideSelection = false;
this.dlvMethods.Location = new System.Drawing.Point(3, 18);
this.dlvMethods.Name = "dlvMethods";
this.dlvMethods.OwnerDraw = true;
this.dlvMethods.ShowGroups = false;
this.dlvMethods.ShowImagesOnSubItems = true;
this.dlvMethods.Size = new System.Drawing.Size(454, 156);
this.dlvMethods.TabIndex = 0;
this.dlvMethods.UseCompatibleStateImageBehavior = false;
this.dlvMethods.View = System.Windows.Forms.View.Details;
this.dlvMethods.VirtualMode = true;
//
// splitContainer2
//
this.splitContainer2.Dock = System.Windows.Forms.DockStyle.Fill;
this.splitContainer2.Location = new System.Drawing.Point(0, 0);
this.splitContainer2.Name = "splitContainer2";
this.splitContainer2.Orientation = System.Windows.Forms.Orientation.Horizontal;
//
// splitContainer2.Panel1
//
this.splitContainer2.Panel1.Controls.Add(this.gbFiledProperties);
//
// splitContainer2.Panel2
//
this.splitContainer2.Panel2.Controls.Add(this.gbInterfaces);
this.splitContainer2.Size = new System.Drawing.Size(232, 350);
this.splitContainer2.SplitterDistance = 175;
this.splitContainer2.TabIndex = 1;
//
// gbInterfaces
//
this.gbInterfaces.Controls.Add(this.dtlvParentClasses);
this.gbInterfaces.Dock = System.Windows.Forms.DockStyle.Fill;
this.gbInterfaces.Location = new System.Drawing.Point(0, 0);
this.gbInterfaces.Name = "gbInterfaces";
this.gbInterfaces.Size = new System.Drawing.Size(232, 171);
this.gbInterfaces.TabIndex = 0;
this.gbInterfaces.TabStop = false;
this.gbInterfaces.Text = "Base Class / Interfaces";
//
// defaultTreeListView1
//
this.dtlvParentClasses.DataSource = null;
this.dtlvParentClasses.Dock = System.Windows.Forms.DockStyle.Fill;
this.dtlvParentClasses.FullRowSelect = true;
this.dtlvParentClasses.HideSelection = false;
this.dtlvParentClasses.Location = new System.Drawing.Point(3, 18);
this.dtlvParentClasses.Name = "defaultTreeListView1";
this.dtlvParentClasses.OwnerDraw = true;
this.dtlvParentClasses.RootKeyValueString = "";
this.dtlvParentClasses.ShowGroups = false;
this.dtlvParentClasses.ShowImagesOnSubItems = true;
this.dtlvParentClasses.Size = new System.Drawing.Size(226, 150);
this.dtlvParentClasses.TabIndex = 1;
this.dtlvParentClasses.UseCompatibleStateImageBehavior = false;
this.dtlvParentClasses.View = System.Windows.Forms.View.Details;
this.dtlvParentClasses.VirtualMode = true;
//
// TypeDetailsModule
//
this.Controls.Add(this.splitContainer1);
this.Name = "TypeDetailsModule";
this.Size = new System.Drawing.Size(460, 531);
this.splitContainer1.Panel1.ResumeLayout(false);
this.splitContainer1.Panel2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).EndInit();
this.splitContainer1.ResumeLayout(false);
this.splitContainer3.Panel1.ResumeLayout(false);
this.splitContainer3.Panel2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.splitContainer3)).EndInit();
this.splitContainer3.ResumeLayout(false);
this.gbTypeInformation.ResumeLayout(false);
this.gbFiledProperties.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.dlvFields)).EndInit();
this.gbMethods.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.dlvMethods)).EndInit();
this.splitContainer2.Panel1.ResumeLayout(false);
this.splitContainer2.Panel2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.splitContainer2)).EndInit();
this.splitContainer2.ResumeLayout(false);
this.gbInterfaces.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.dtlvParentClasses)).EndInit();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.SplitContainer splitContainer1;
private System.Windows.Forms.GroupBox gbTypeInformation;
private System.Windows.Forms.PropertyGrid pgTypeInfo;
private System.Windows.Forms.GroupBox gbFiledProperties;
private System.Windows.Forms.GroupBox gbMethods;
private WinFwk.UITools.DefaultListView dlvFields;
private WinFwk.UITools.DefaultListView dlvMethods;
private System.Windows.Forms.SplitContainer splitContainer3;
private System.Windows.Forms.SplitContainer splitContainer2;
private System.Windows.Forms.GroupBox gbInterfaces;
private WinFwk.UITools.DefaultTreeListView dtlvParentClasses;
}
}
|
//
// Tests for System.Web.UI.WebControls.DataControlFieldTest.cs
//
// Author:
// Yoni Klein (yonik@mainsoft.com)
//
//
// Copyright (C) 2005 Novell, Inc (http://www.novell.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.
#if NET_2_0
using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Drawing;
using System.Collections;
using System.Collections.Specialized;
using NUnit.Framework;
namespace MonoTests.System.Web.UI.WebControls
{
[TestFixture]
public class DataControlFieldTest
{
class DerivedDataControlField : DataControlField
{
private bool _fieldChanged;
public bool FieldChanged
{
get { return _fieldChanged; }
}
protected override DataControlField CreateField ()
{
throw new NotImplementedException();
}
public Control DoControl ()
{
return base.Control;
}
public bool DoDesignMode ()
{
return base.DesignMode;
}
public bool DoIsTrackingViewState ()
{
return base.IsTrackingViewState;
}
public StateBag StateBag
{
get { return base.ViewState; }
}
public void DoTrackViewState ()
{
base.TrackViewState ();
}
public void DoCopyProperties (DataControlField newField)
{
base.CopyProperties (newField);
}
public DataControlField DoCloneField ()
{
return base.CloneField ();
}
protected override void OnFieldChanged ()
{
base.OnFieldChanged ();
_fieldChanged = true;
}
public object DoSaveViewState ()
{
return base.SaveViewState ();
}
public void DoLoadViewState (object savedState)
{
base.LoadViewState (savedState);
}
}
[Test]
public void DataControlField_DefaultProperty ()
{
DerivedDataControlField field = new DerivedDataControlField ();
Assert.AreEqual ("", field.AccessibleHeaderText, "AccessibleHeaderText");
Assert.AreEqual ("System.Web.UI.WebControls.Style", field.ControlStyle.ToString (), "ControlStyle");
Assert.AreEqual ("System.Web.UI.WebControls.TableItemStyle", field.FooterStyle.ToString (), "FooterStyle");
Assert.AreEqual ("", field.FooterText, "FooterText");
Assert.AreEqual ("", field.HeaderImageUrl, "HeaderImageUrl");
Assert.AreEqual ("System.Web.UI.WebControls.TableItemStyle", field.HeaderStyle.ToString (), "HeaderStyle");
Assert.AreEqual ("", field.HeaderText, "HeaderText");
Assert.AreEqual (true, field.InsertVisible, "InsertVisible");
Assert.AreEqual ("System.Web.UI.WebControls.TableItemStyle", field.ItemStyle.ToString (), "ItemStyle");
Assert.AreEqual (true, field.ShowHeader, "ShowHeader");
Assert.AreEqual ("", field.SortExpression, "SortExpression");
Assert.AreEqual (true, field.Visible, "Visible");
//protected properties
Assert.AreEqual (null, field.DoControl (), "Control");
Assert.AreEqual (false, field.DoDesignMode (), "DesignMode");
Assert.AreEqual (false, field.DoIsTrackingViewState (), "IsTrackingViewState");
Assert.AreEqual ("System.Web.UI.StateBag", field.StateBag.ToString (), "StateBag");
}
[Test]
public void DataControlField_AssignProperty ()
{
DerivedDataControlField field = new DerivedDataControlField ();
field.AccessibleHeaderText = "test";
Assert.AreEqual ("test", field.AccessibleHeaderText, "AccessibleHeaderText");
field.ControlStyle.BackColor = Color.Red;
Assert.AreEqual (Color.Red, field.ControlStyle.BackColor, "ControlStyle");
field.FooterStyle.BackColor = Color.Red;
Assert.AreEqual (Color.Red, field.FooterStyle.BackColor, "FooterStyle");
field.FooterText = "test";
Assert.AreEqual ("test", field.FooterText, "FooterText");
field.HeaderImageUrl = "test";
Assert.AreEqual ("test", field.HeaderImageUrl, "HeaderImageUrl");
field.HeaderStyle.BackColor = Color.Red;
Assert.AreEqual (Color.Red, field.HeaderStyle.BackColor, "HeaderStyle");
field.HeaderText = "test";
Assert.AreEqual ("test", field.HeaderText, "HeaderText");
field.ItemStyle.BackColor = Color.Red;
Assert.AreEqual (Color.Red, field.ItemStyle.BackColor, "ItemStyle");
field.ShowHeader = false;
Assert.AreEqual (false, field.ShowHeader, "ShowHeader");
field.SortExpression = "test";
Assert.AreEqual ("test", field.SortExpression, "SortExpression");
field.Visible = false;
Assert.AreEqual (false, field.Visible, "Visible");
}
[Test]
public void DataControlField_Initilize ()
{
DerivedDataControlField field = new DerivedDataControlField ();
bool res = field.Initialize (false, new Control ());
Assert.AreEqual (false, res, "Initilize");
}
[Test]
public void DataControlField_InitilizeCell ()
{
DerivedDataControlField field = new DerivedDataControlField ();
field.HeaderText = "test";
field.HeaderStyle.BackColor = Color.Red;
field.HeaderImageUrl = "test";
DataControlFieldCell cell = new DataControlFieldCell (field);
field.InitializeCell (cell, DataControlCellType.Header, DataControlRowState.Normal, 1);
Assert.AreEqual ("test", cell.ContainingField.HeaderText, "HeaderText");
Assert.AreEqual ("test", cell.ContainingField.HeaderImageUrl, "HeaderImageUrl");
Assert.AreEqual (Color.Red, cell.ContainingField.HeaderStyle.BackColor, "BackColor");
}
[Test]
public void DataControlField_CopyProperties ()
{
DerivedDataControlField field = new DerivedDataControlField ();
DerivedDataControlField newField = new DerivedDataControlField ();
field.AccessibleHeaderText = "test";
field.ControlStyle.BackColor = Color.Red;
field.FooterStyle.BackColor = Color.Red;
field.HeaderStyle.BackColor = Color.Red;
field.ItemStyle.BackColor = Color.Red;
field.FooterText = "test";
field.HeaderImageUrl = "test";
field.HeaderText = "test";
field.InsertVisible = false;
field.ShowHeader = false;
field.SortExpression = "test";
field.Visible = false;
field.DoCopyProperties (newField);
Assert.AreEqual ("test", newField.AccessibleHeaderText, "AccessibleHeaderText");
Assert.AreEqual (Color.Red, newField.ControlStyle.BackColor, "ControlStyle");
Assert.AreEqual (Color.Red, newField.FooterStyle.BackColor, "FooterStyle");
Assert.AreEqual (Color.Red, newField.HeaderStyle.BackColor, "HeaderStyle");
Assert.AreEqual (Color.Red, newField.ItemStyle.BackColor, "ItemStyle");
Assert.AreEqual ("test", newField.FooterText, "FooterText");
Assert.AreEqual ("test", newField.HeaderImageUrl,"HeaderImageUrl");
Assert.AreEqual ("test", newField.HeaderText, "HeaderText ");
Assert.AreEqual (false, newField.InsertVisible, "InsertVisible");
Assert.AreEqual (false, newField.ShowHeader, "ShowHeader");
Assert.AreEqual ("test", newField.SortExpression, "SortExpression");
Assert.AreEqual (false, newField.Visible, "Visible");
}
[Test]
public void DataControlField_Events ()
{
DerivedDataControlField field = new DerivedDataControlField ();
Assert.AreEqual (false, field.FieldChanged, "BeforeChangingProperty");
field.FooterText = "test";
Assert.AreEqual (true, field.FieldChanged, "AfterChangingProperty");
}
[Test]
public void DataControlField_ViewState ()
{
DerivedDataControlField field = new DerivedDataControlField ();
DerivedDataControlField newField = new DerivedDataControlField ();
field.DoTrackViewState ();
field.FooterStyle.BackColor = Color.Red;
field.ItemStyle.BackColor = Color.Red;
field.HeaderStyle.BackColor = Color.Red;
object state = field.DoSaveViewState();
newField.DoLoadViewState (state);
Assert.AreEqual (Color.Red, newField.HeaderStyle.BackColor, "HeaderStyle");
Assert.AreEqual (Color.Red, newField.ItemStyle.BackColor, "ItemStyle");
Assert.AreEqual (Color.Red, newField.FooterStyle.BackColor, "FooterStyle");
}
[Test]
[ExpectedException (typeof(NotImplementedException))]
public void DataControlField_CloneField ()
{
DerivedDataControlField field = new DerivedDataControlField ();
DerivedDataControlField newField = new DerivedDataControlField ();
newField = (DerivedDataControlField)field.DoCloneField ();
}
}
}
#endif
|
using System;
using Xunit;
using Util;
using System.Linq;
using System.Collections.Generic;
using System.Text;
namespace SymmetricTree
{
public class Solution
{
public bool IsSymmetric(TreeNode root)
{
if (root == null)
{
return true;
}
return CompareBT(root.left, root.right);
}
bool CompareBT(TreeNode left, TreeNode right)
{
if (left == null)
{
return right == null;
}
if (right == null) return false;
if (left.val != right.val) return false;
if (!CompareBT(left.left, right.right)) return false;
if (!CompareBT(left.right, right.left)) return false;
return true;
}
}
public class Test
{
void GetBTPath(TreeNode root, string path, Dictionary<string, int> vals)
{
vals[path] = root.val;
if (root.left != null)
{
GetBTPath(root.left, $"{path}L", vals);
}
if (root.right != null)
{
GetBTPath(root.right, $"{path}R", vals);
}
}
static public void Run()
{
var input = @"
#start line, to avoid removed by CleanInput
[1,2,2,3,4,4,3]
true
[1,2,2,null,3,null,3]
false
[1,2,2,2,null,2]
false
";
var lines = input.CleanInput();
Verify.Method(new Solution(), lines);
}
}
} |
using AM;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace UnitTests.AM
{
[TestClass]
public class UnsafeUtilityTest
{
[TestMethod]
public void UnsafeUtility_AsSpan_1()
{
var value = 0;
var span = UnsafeUtility.AsSpan(ref value);
//Assert.AreEqual(Marshal.SizeOf(typeof(int)), span.Length);
Assert.AreEqual((byte)0, span[0]);
}
}
}
|
using System;
namespace lastmilegames.DialogueSystem.NodeData
{
[Serializable]
public class ExposedProperty
{
public string propertyName = "@@NAME@@";
public string propertyValue = "Value";
}
} |
namespace Strategy.Behavior.Flying
{
public interface IFlyingBehavior
{
void Fly();
}
} |
public class IdleState:StateBase
{
public IdleState(BevBase bev) : base(bev)
{
}
#region override methods
public override void Execute()
{
if (base.frameCounter >= base.intervalFrame)
{
base.frameCounter = 0;
if (base.bev.HasPosTarget())
{
this.bev.StateMachine.ChangeState(BevStateType.Move);
}
else
{
this.bev.Idle();
}
}
else
{
base.frameCounter++;
}
}
#endregion
}
|
namespace DragonSouvenirs.Services.Data
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DragonSouvenirs.Data.Common.Repositories;
using DragonSouvenirs.Data.Models;
using DragonSouvenirs.Services.Mapping;
using Microsoft.EntityFrameworkCore;
public class CartService : ICartService
{
private readonly IDeletableEntityRepository<Cart> cartRepository;
private readonly IDeletableEntityRepository<CartProduct> cartProductRepository;
private readonly IDeletableEntityRepository<ApplicationUser> userRepository;
private readonly IDeletableEntityRepository<Product> productRepository;
public CartService(
IDeletableEntityRepository<Cart> cartRepository,
IDeletableEntityRepository<CartProduct> cartProductRepository,
IDeletableEntityRepository<ApplicationUser> userRepository,
IDeletableEntityRepository<Product> productRepository)
{
this.cartRepository = cartRepository;
this.cartProductRepository = cartProductRepository;
this.userRepository = userRepository;
this.productRepository = productRepository;
}
// Get the products in the user's shopping cart
public async Task<IEnumerable<T>> GetCartProductsAsync<T>(string userId)
{
var cart = await this.cartProductRepository
.All()
.Where(c => c.Cart.UserId == userId)
.To<T>()
.ToListAsync();
return cart;
}
// Get the products cart price with the discount
public async Task<decimal> GetCartTotalPriceAsync(string userId, decimal personalDiscountPercentage)
{
var totalPrice = await this.cartProductRepository
.All()
.Include(cp => cp.Cart)
.Where(cp => cp.Cart.UserId == userId)
.SumAsync(cp => cp.Quantity * (cp.Product.DiscountPrice ?? cp.Product.Price));
totalPrice *= personalDiscountPercentage == 0
? 1
: 1 - (personalDiscountPercentage / 100);
return totalPrice;
}
// Add a product to the user's shopping cart
public async Task<bool> AddProductToCartAsync(string userId, int productId, int quantity)
{
var user = await this.userRepository
.AllWithDeleted()
.Include(u => u.Cart)
.FirstOrDefaultAsync(u => u.Id == userId);
if (user.Cart == null)
{
var cart = new Cart()
{
CreatedOn = DateTime.UtcNow,
UserId = user.Id,
};
await this.cartRepository.AddAsync(cart);
await this.cartRepository.SaveChangesAsync();
}
var cartProduct = new CartProduct();
var product = await this.productRepository.All().FirstOrDefaultAsync(p => p.Id == productId);
if (product == null)
{
return false;
}
if (product.Quantity < quantity)
{
return false;
}
// Check if a deleted CardProduct with the same product exists.
if (await this.cartProductRepository
.AllWithDeleted()
.Where(cp => cp.Cart.UserId == userId)
.AnyAsync(cp => cp.ProductId == productId))
{
cartProduct = await this.cartProductRepository
.AllWithDeleted()
.FirstOrDefaultAsync(cp => cp.ProductId == productId);
if (cartProduct.IsDeleted)
{
cartProduct.Quantity = quantity;
cartProduct.IsDeleted = false;
}
else
{
cartProduct.Quantity += quantity;
}
}
else
{
cartProduct.Cart = user.Cart;
cartProduct.Quantity = quantity;
cartProduct.CreatedOn = DateTime.UtcNow;
cartProduct.ProductId = productId;
await this.cartProductRepository.AddAsync(cartProduct);
}
// Check if the quantity exceeds total product quantity
if (cartProduct.Quantity > product.Quantity)
{
cartProduct.Quantity = product.Quantity;
}
await this.cartProductRepository.SaveChangesAsync();
return true;
}
// Delete a product from the user's shopping cart
public async Task<bool> DeleteProductFromCartAsync(string userId, int productId)
{
var cartProduct = await this.GetProductFromCart(userId, productId);
if (cartProduct == null)
{
return false;
}
this.cartProductRepository
.Delete(cartProduct);
await this.cartProductRepository.SaveChangesAsync();
return true;
}
// Edit a product in the user's shopping cart
public async Task<bool> EditProductInCartAsync(string userId, int productId, int quantity)
{
var cartProduct = await this.GetProductFromCart(userId, productId);
if (cartProduct == null)
{
return false;
}
var product = await this.productRepository
.All()
.FirstOrDefaultAsync(p => p.Id == productId);
if (product == null)
{
return false;
}
if (product.Quantity < quantity)
{
return false;
}
// Set the quantity to the max available product quantity in stock
cartProduct.Quantity = product.Quantity < quantity
? product.Quantity
: quantity;
await this.cartProductRepository.SaveChangesAsync();
return true;
}
// Get the shopping cart by Id
public async Task<T> GetCartByIdAsync<T>(string id)
{
var cart = await this.cartRepository
.All()
.Where(c => c.User.Id == id)
.To<T>()
.FirstOrDefaultAsync();
return cart;
}
// Check if user's shopping cart has any products(NOT DELETED)
public async Task<bool> UserHasProductsInCart(string userId)
{
var hasValidCart = await this.cartRepository
.All()
.AnyAsync(c => c.UserId == userId);
if (hasValidCart)
{
hasValidCart = await this.cartProductRepository
.All()
.Where(cp => cp.Cart.UserId == userId && !cp.Product.IsDeleted)
.AnyAsync();
}
return hasValidCart;
}
// Get the product from the user's shopping cart
private async Task<CartProduct> GetProductFromCart(string userId, int productId)
{
return await this.cartProductRepository
.AllWithDeleted()
.FirstOrDefaultAsync(
cp => cp.Cart.UserId == userId
&& cp.ProductId == productId);
}
}
}
|
using Fleck;
using InterflowFramework.Core.Channel.InputPoint.Const;
using InterflowFramework.Core.Channel.InputPoint.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace InternalFramework.Fleck.InputPoint
{
public class FleckInputPoint : SimpleInputPoint
{
public string ConnectionString;
private WebSocketServer _server;
public WebSocketServer Server {
get {
if(_server == null) {
_server = new WebSocketServer(ConnectionString);
}
return _server;
}
}
public FleckInputPoint(string connectionString): base() {
ConnectionString = connectionString;
}
public override void Enable()
{
base.Enable();
Server.Start(WebSocketServerConfigurate);
}
public override void Dispose()
{
base.Dispose();
Server.Dispose();
}
private void WebSocketServerConfigurate(IWebSocketConnection obj)
{
obj.OnOpen = () => Subscriber.Execute(InputPointEvent.onConnect);
obj.OnClose = () => Subscriber.Execute(InputPointEvent.onDisconnect);
obj.OnMessage = msg => Push(msg);
}
}
}
|
using System;
using System.Collections;
namespace FastReport
{
/// <summary>
/// This class represents a data band footer.
/// </summary>
public class DataFooterBand : HeaderFooterBandBase
{
}
} |
namespace __RootNamespace__.Features.__FeatureName__s
{
using MediatR;
using System;
using __RootNamespace__.Features.Bases;
public class GetById__FeatureName__Request : BaseApiRequest, IRequest<GetById__FeatureName__Response>
{
public const string RouteTemplate = "api/__FeatureName__s/Get";
/// <summary>
/// Guid ID for individual item.
/// </summary>
/// <example>82b85a2c-c5e4-4306-a803-08d8de1257c1</example>
public Guid Id { get; set; }
internal override string GetRoute() => $"{RouteTemplate}?{nameof(Id)}={Id}";
}
} |
using System;
using System.IO;
using System.Security.Claims;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using LeanCode.Components;
using LeanCode.CQRS.Execution;
using NSubstitute;
namespace LeanCode.CQRS.RemoteHttp.Server.Tests
{
public abstract class BaseMiddlewareTests
{
protected const int PipelineContinued = 100;
private readonly TypesCatalog catalog = new TypesCatalog(typeof(BaseMiddlewareTests));
private readonly IServiceProvider serviceProvider;
protected StubQueryExecutor Query { get; } = new StubQueryExecutor();
protected StubCommandExecutor Command { get; } = new StubCommandExecutor();
protected RemoteCQRSMiddleware<AppContext> Middleware { get; }
private readonly string endpoint;
private readonly string defaultObject;
public BaseMiddlewareTests(string endpoint, Type defaultObject, ISerializer? serializer = null)
{
this.endpoint = endpoint;
this.defaultObject = defaultObject.FullName!;
serviceProvider = Substitute.For<IServiceProvider>();
serviceProvider.GetService(typeof(IQueryExecutor<AppContext>)).Returns(Query);
serviceProvider.GetService(typeof(ICommandExecutor<AppContext>)).Returns(Command);
Middleware = new RemoteCQRSMiddleware<AppContext>(
catalog,
h => new AppContext(h.User),
serializer ?? new Utf8JsonSerializer(),
ctx =>
{
ctx.Response.StatusCode = PipelineContinued;
return Task.CompletedTask;
});
}
protected async Task<(int statusCode, string response)> Invoke(
string? type = null,
string content = "{}",
string method = "POST",
ClaimsPrincipal? user = null)
{
type = type ?? defaultObject;
var ctx = new StubContext(method, $"/{endpoint}/{type}", content)
{
RequestServices = serviceProvider,
User = user ?? new ClaimsPrincipal(),
};
await Middleware.InvokeAsync(ctx);
var statusCode = ctx.Response.StatusCode;
var body = (MemoryStream)ctx.Response.Body;
return (statusCode, Encoding.UTF8.GetString(body.ToArray()));
}
}
}
|
using System;
using System.Windows.Forms;
using Avtec.DevMorningFix.FormatOutput;
using Avtec.DevMorningFix.XmlStoreModule.DataManager;
namespace DesktopApp
{
public partial class Form1 : Form
{
private readonly IDataManager _dataManager;
private readonly IFundamentalFormat _format;
private readonly IFundamentalModel _model;
/*
Note:
This in no way suggests an implementation, solution or any other final construct.
This is simply code put in to allow further refactoring towards improvement.
I.e., it allows stuff to work for now.
*/
public Form1(IDataManager dataManager, IFundamentalFormat format, IFundamentalModel model)
{
_dataManager = dataManager;
_format = format;
_model = model;
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
var fundamentals = _dataManager.GetFundamentalsList();
var format = _format.GetFormat();
foreach (var fundamental in fundamentals)
{
var data = _model.GetData(fundamental);
label1.Text += string.Format(format + "\n", data);
}
}
}
} |
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using SFA.DAS.CommitmentsV2.Shared.Interfaces;
using SFA.DAS.ProviderCommitments.Web.Models.Apprentice;
namespace SFA.DAS.ProviderCommitments.Web.Mappers.Apprentice
{
public class StartDateViewModelToConfirmRequestMapper : IMapper<StartDateViewModel, ConfirmRequest>
{
private readonly ILogger<StartDateViewModelToConfirmRequestMapper> _logger;
public StartDateViewModelToConfirmRequestMapper(ILogger<StartDateViewModelToConfirmRequestMapper> logger)
{
_logger = logger;
}
public async Task<ConfirmRequest> Map(StartDateViewModel source)
{
try
{
return await Task.FromResult(new ConfirmRequest
{
ProviderId = source.ProviderId,
ApprenticeshipHashedId = source.ApprenticeshipHashedId,
EmployerAccountLegalEntityPublicHashedId = source.EmployerAccountLegalEntityPublicHashedId,
EndDate = source.EndDate,
StartDate = source.StartDate.MonthYear,
Price = source.Price.Value
});
}
catch (Exception e)
{
_logger.LogError($"Error Mapping {nameof(StartDateViewModel)} to {nameof(ConfirmRequest)}", e);
throw;
}
}
}
}
|
using SFA.DAS.Payments.Calc.CoInvestedPayments.Infrastructure.Data.Entities;
namespace SFA.DAS.Payments.Calc.CoInvestedPayments.Infrastructure.Data
{
public interface IPaymentRepository
{
void AddPayment(PaymentEntity payment);
void AddPayments(PaymentEntity[] payments);
}
}
|
@{
ViewBag.Title = "ChildAction";
}
<h2>ChildAction</h2>
@{
TempData["SkipLayout"] = true;
}
@Html.Action("Inline") |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using Microsoft.Azure.Commands.OperationalInsights.Properties;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Microsoft.Azure.Commands.OperationalInsights.Models
{
public class PSCustomLogDataSourceProperties: PSDataSourcePropertiesBase
{
[JsonIgnore]
public override string Kind { get { return PSDataSourceKinds.CustomLog; } }
/// <summary>
/// Gets or sets the custom log name.
/// </summary>
[JsonProperty(PropertyName= "customLogName")]
public string CustomLogName { get; set; }
/// <summary>
/// Gets or sets the description.
/// </summary>
[JsonProperty(PropertyName = "description")]
public string Description { get; set; }
/// <summary>
/// Gets or sets the extractions.
/// </summary>
[JsonProperty(PropertyName = "extractions")]
public List<CustomLogExtraction> Extractions { get; set; }
/// <summary>
/// Gets or sets the inputs.
/// </summary>
[JsonProperty(PropertyName = "inputs")]
public List<CustomLogInput> Inputs { get; set; }
}
/// <summary>
/// The location.
/// </summary>
public class Location
{
#region Public Properties
/// <summary>
/// Gets or sets the file system locations.
/// </summary>
public FileSystemLocations fileSystemLocations { get; set; }
#endregion
}
/// <summary>
/// The file system locations.
/// </summary>
public class FileSystemLocations
{
#region Public Properties
/// <summary>
/// Gets or sets the linux file type log paths.
/// </summary>
public string[] linuxFileTypeLogPaths { get; set; }
/// <summary>
/// Gets or sets the windows file type log paths.
/// </summary>
public string[] windowsFileTypeLogPaths { get; set; }
#endregion
}
/// <summary>
/// The record delimiter.
/// </summary>
public class RecordDelimiter
{
#region Public Properties
/// <summary>
/// Gets or sets the regex delimiter.
/// </summary>
public RegexDelimiter regexDelimiter { get; set; }
#endregion
}
/// <summary>
/// The regex delimiter.
/// </summary>
public class RegexDelimiter
{
#region Public Properties
/// <summary>
/// Gets or sets the match index.
/// </summary>
public int matchIndex { get; set; }
/// <summary>
/// Gets or sets the numberd group.
/// </summary>
public string numberdGroup { get; set; }
/// <summary>
/// Gets or sets the pattern.
/// </summary>
public string pattern { get; set; }
#endregion
}
/// <summary>
/// The custom log input.
/// </summary>
public class CustomLogInput
{
#region Public Properties
/// <summary>
/// Gets or sets the location.
/// </summary>
public Location location { get; set; }
/// <summary>
/// Gets or sets the record delimiter.
/// </summary>
public RecordDelimiter recordDelimiter { get; set; }
#endregion
}
/// <summary>
/// The date time extraction.
/// </summary>
public class DateTimeExtraction
{
#region Public Properties
/// <summary>
/// Gets or sets the join string regex.
/// </summary>
public string joinStringRegex { get; set; }
/// <summary>
/// Gets or sets the regex.
/// </summary>
public string regex { get; set; }
#endregion
}
/// <summary>
/// The extraction properties.
/// </summary>
public class ExtractionProperties
{
#region Public Properties
/// <summary>
/// Gets or sets the date time extraction.
/// </summary>
public DateTimeExtraction dateTimeExtraction { get; set; }
#endregion
}
/// <summary>
/// The custom log extraction.
/// </summary>
public class CustomLogExtraction
{
#region Public Properties
/// <summary>
/// Gets or sets the extraction name.
/// </summary>
public string extractionName { get; set; }
/// <summary>
/// Gets or sets the extraction properties.
/// </summary>
public ExtractionProperties extractionProperties { get; set; }
/// <summary>
/// Gets or sets the extraction type.
/// </summary>
public string extractionType { get; set; }
#endregion
}
}
|
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Numerics;
using Pcg;
using System.Threading;
namespace PrimeGen
{
public class BigIntegerGenerator
{
Random random;
ThreadLocal<byte[]> threadLocalByteArray;
public BigIntegerGenerator(int byteSize)
{
random = new ThreadSafeRandom(() => new PcgRandom());
threadLocalByteArray = new ThreadLocal<byte[]>(() => new byte[byteSize]);
}
public BigInteger Next()
{
var ret = BigInteger.Zero;
while (ret.IsZero)
{
var bytes = threadLocalByteArray.Value;
random.NextBytes(bytes);
ret = BigInteger.Abs(new BigInteger(bytes));
}
return ret;
}
}
}
|
using System.Collections.Generic;
namespace HeroesOfTheStats.Shared.Entities
{
public class Hero
{
public double wins { get; set; }
public double loses { get; set; }
public double win_rate { get; set; }
public string name { get; set; }
public string short_name { get; set; }
public string attribute_id { get; set; }
public string c_hero_id { get; set; }
public string c_unit_id { get; set; }
public IEnumerable<string> translations { get; set; }
public object icon_url { get; set; }
public string role { get; set; }
public string type { get; set; }
public string release_date { get; set; }
public string release_patch { get; set; }
public IEnumerable<Ability> abilities { get; set; }
public IEnumerable<Talent> talents { get; set; }
}
}
|
namespace SFA.Apprenticeships.Web.Candidate.Validators
{
using Constants.ViewModels;
using FluentValidation;
using ViewModels.Register;
public class ForgottenPasswordViewModelClientValidator : AbstractValidator<ForgottenPasswordViewModel>
{
public ForgottenPasswordViewModelClientValidator()
{
this.AddCommonRules();
}
}
public class ForgottenPasswordViewModelServerValidator : AbstractValidator<ForgottenPasswordViewModel>
{
public ForgottenPasswordViewModelServerValidator()
{
this.AddCommonRules();
}
}
public static class ForgottenPasswordViewModelValidationRules
{
public static void AddCommonRules(this AbstractValidator<ForgottenPasswordViewModel> validator)
{
validator.RuleFor(x => x.EmailAddress)
.Length(0, 100)
.WithMessage(ForgottenPasswordViewModelMessages.EmailAddressMessages.TooLongErrorText)
.NotEmpty()
.WithMessage(ForgottenPasswordViewModelMessages.EmailAddressMessages.RequiredErrorText)
.Matches(ForgottenPasswordViewModelMessages.EmailAddressMessages.WhiteListRegularExpression)
.WithMessage(ForgottenPasswordViewModelMessages.EmailAddressMessages.WhiteListErrorText);
}
}
} |
using System;
using System.Collections.Generic;
using System.Numerics;
using System.Text;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Media.Animation;
using CoreAnimation;
using CoreGraphics;
using Uno.Disposables;
using Uno.UI.Extensions;
namespace Uno.UI.Media
{
partial class NativeRenderTransformAdapter
{
private CATransform3D _transform = CATransform3D.Identity;
private bool _wasAnimating = false;
#if __MACOS__
private bool _isDisposed;
private bool _isDeferring;
private IDisposable _deferredInitialization;
#endif
partial void Initialized()
{
#if __MACOS__
Owner.WantsLayer = true;
// On MAC OS, if we set the Transform before the NSView has been rendered at least once,
// it will be definitively ignored (even if updated).
// So here we hide the control (using Layer.Opacity to avoid not alter the Element itself),
// and wait for the control to be loaded to set the transform and restore the visibility.
if (Owner is FrameworkElement element && !element.IsLoaded)
{
_isDeferring = true;
element.Layer.Opacity = 0;
element.Loaded += DeferredInitialize;
_deferredInitialization = Disposable.Create(CompleteInitialization);
return;
void DeferredInitialize(object sender, RoutedEventArgs e)
{
element.Loaded -= DeferredInitialize;
// Note: Deferring to the loaded is not enough ... we must wait for the next dispatcher loop to set the Transform!
element.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, CompleteInitialization);
}
void CompleteInitialization()
{
// Note: we unsubscribe from the event a second time in case of this adapter is being disposed before the load (cf. _deferredInitialization)
element.Loaded -= DeferredInitialize;
_isDeferring = false;
element.Layer.Opacity = 1;
if (!_isDisposed)
{
InitializeOrigin();
Update();
}
}
}
#else
// On íOS and MacOS Transform are applied by default on the center on the view
// so make sure to reset it when the transform is attached to the view
InitializeOrigin();
// Apply the transform as soon as its been declared
Update();
#endif
}
private void InitializeOrigin()
{
var oldFrame = Owner.Layer.Frame;
Owner.Layer.AnchorPoint = CurrentOrigin;
// Restore the old frame to correct the offset potentially introduced by changing AnchorPoint. This is safe to do since we know
// that the transform is currently identity.
Owner.Layer.Frame = oldFrame;
}
partial void Apply(bool isSizeChanged, bool isOriginChanged)
{
#if __MACOS__
if (_isDeferring)
{
return;
}
#endif
if (Transform.IsAnimating)
{
// While animating the transform, we let the Animator apply the transform by itself, so do not update the Transform
if (!_wasAnimating)
{
// At the beginning of the animation make sure we disable all properties of the transform
Owner.Layer.AnchorPoint = GPUFloatValueAnimator.GetAnchorForAnimation(Transform, CurrentOrigin, CurrentSize);
Owner.Layer.Transform = CoreAnimation.CATransform3D.Identity;
_wasAnimating = true;
}
return;
}
else if (_wasAnimating)
{
// Make sure to fully restore the transform at the end of an animation
Owner.Layer.AnchorPoint = CurrentOrigin;
Owner.Layer.Transform = _transform = Transform.MatrixCore.ToTransform3D();
_wasAnimating = false;
return;
}
if (isSizeChanged)
{
// As we use the 'AnchorPoint', the transform matrix is independent of the size of the control
// But the layouter expects from us that we restore the transform on each measuring phase
Owner.Layer.Transform = _transform;
}
else if (isOriginChanged)
{
Owner.Layer.AnchorPoint = CurrentOrigin;
}
else
{
Owner.Layer.Transform = _transform = Transform.MatrixCore.ToTransform3D();
}
}
partial void Cleanup()
{
#if __MACOS__
_isDisposed = true;
_deferredInitialization?.Dispose();
#endif
Owner.Layer.Transform = CATransform3D.Identity;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace XP.SDK.XPLM
{
[Flags]
public enum MouseHandlers : byte
{
None = 0,
LeftClick = 1,
RightClick = 2,
All = 0xFF
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Fourier_Transformatie.Fourier {
public class ComplexGetal {
private float reëel, imaginair;
public ComplexGetal(float reëel, float imaginair) {
this.reëel = reëel;
this.imaginair = imaginair;
}
public float Reëel {
get { return reëel; }
set { reëel = value; }
}
public float Imaginair {
get { return imaginair; }
set { imaginair = value; }
}
public float Modulus {
get {
// http://nl.wikipedia.org/wiki/Complex_getal#Gerelateerde_waarden
return (float)(Math.Sqrt(reëel * reëel + imaginair * imaginair));
}
}
public float Argument {
get {
// http://nl.wikipedia.org/wiki/Argument_(complex_getal)
// return ((float)Math.Atan(imaginair / reëel));
return (float)Math.Atan2(imaginair, reëel);
}
}
}
}
|
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
using System.ComponentModel.Composition;
namespace VsChromium.Package {
[Export(typeof(IPackagePreInitializer))]
public class VisualStudioPackageInitializer : IPackagePreInitializer {
private readonly IVisualStudioPackageProvider _visualStudioPackageProvider;
[ImportingConstructor]
public VisualStudioPackageInitializer(IVisualStudioPackageProvider visualStudioPackageProvider) {
_visualStudioPackageProvider = visualStudioPackageProvider;
}
public int Priority { get { return int.MaxValue; } }
public void Run(IVisualStudioPackage package) {
_visualStudioPackageProvider.SetPackage(package);
}
}
} |
namespace MyWebtoonWebProject.Services.Data
{
using System.Threading.Tasks;
public interface IWebtoonsRatingsService
{
Task RateWebtoonAsync(string webtoonTitleNumber, string userId, byte ratingValue);
double GetWebtoonAverageRating(string webtoonTitleNumber);
bool DoesWebtoonHaveARating(string webtoonTitleNumber);
}
}
|
// Copyright © 2018 – Property of Tobii AB (publ) - All Rights Reserved
namespace Tobii.XR
{
using UnityEditor;
public interface IEditorSettings
{
void SetScriptingDefineSymbolsForGroup(BuildTargetGroup targetGroup, string defines);
string GetScriptingDefineSymbolsForGroup(BuildTargetGroup targetGroup);
}
} |
using SoulsFormats;
using System.Collections.Generic;
using System.Numerics;
namespace HKX2
{
public enum SolverStabilizationType
{
SOLVER_STABILIZATION_OFF = 0,
SOLVER_STABILIZATION_LOW = 1,
SOLVER_STABILIZATION_MEDIUM = 2,
SOLVER_STABILIZATION_HIGH = 3,
SOLVER_STABILIZATION_AGGRESSIVE = 4,
}
public enum DeactivationStrategy
{
DEACTIVATION_STRATEGY_AGGRESSIVE = 3,
DEACTIVATION_STRATEGY_BALANCED = 4,
DEACTIVATION_STRATEGY_ACCURATE = 5,
}
public partial class hknpMotionProperties : IHavokObject
{
public virtual uint Signature { get => 1575913025; }
public enum FlagsEnum
{
NEVER_REBUILD_MASS_PROPERTIES = 2,
ENABLE_GRAVITY_MODIFICATION = 536870912,
ENABLE_TIME_FACTOR = 1073741824,
FLAGS_MASK = -536870912,
AUTO_FLAGS_MASK = 66060288,
}
public uint m_isExclusive;
public uint m_flags;
public float m_gravityFactor;
public float m_timeFactor;
public float m_maxLinearSpeed;
public float m_maxAngularSpeed;
public float m_linearDamping;
public float m_angularDamping;
public float m_solverStabilizationSpeedThreshold;
public float m_solverStabilizationSpeedReduction;
public float m_maxDistSqrd;
public float m_maxRotSqrd;
public float m_invBlockSize;
public short m_pathingUpperThreshold;
public short m_pathingLowerThreshold;
public byte m_numDeactivationFrequencyPasses;
public byte m_deactivationVelocityScaleSquare;
public byte m_minimumPathingVelocityScaleSquare;
public byte m_spikingVelocityScaleThresholdSquared;
public byte m_minimumSpikingVelocityScaleSquared;
public virtual void Read(PackFileDeserializer des, BinaryReaderEx br)
{
m_isExclusive = br.ReadUInt32();
m_flags = br.ReadUInt32();
m_gravityFactor = br.ReadSingle();
m_timeFactor = br.ReadSingle();
m_maxLinearSpeed = br.ReadSingle();
m_maxAngularSpeed = br.ReadSingle();
m_linearDamping = br.ReadSingle();
m_angularDamping = br.ReadSingle();
m_solverStabilizationSpeedThreshold = br.ReadSingle();
m_solverStabilizationSpeedReduction = br.ReadSingle();
m_maxDistSqrd = br.ReadSingle();
m_maxRotSqrd = br.ReadSingle();
m_invBlockSize = br.ReadSingle();
m_pathingUpperThreshold = br.ReadInt16();
m_pathingLowerThreshold = br.ReadInt16();
m_numDeactivationFrequencyPasses = br.ReadByte();
m_deactivationVelocityScaleSquare = br.ReadByte();
m_minimumPathingVelocityScaleSquare = br.ReadByte();
m_spikingVelocityScaleThresholdSquared = br.ReadByte();
m_minimumSpikingVelocityScaleSquared = br.ReadByte();
br.ReadUInt16();
br.ReadByte();
}
public virtual void Write(PackFileSerializer s, BinaryWriterEx bw)
{
bw.WriteUInt32(m_isExclusive);
bw.WriteUInt32(m_flags);
bw.WriteSingle(m_gravityFactor);
bw.WriteSingle(m_timeFactor);
bw.WriteSingle(m_maxLinearSpeed);
bw.WriteSingle(m_maxAngularSpeed);
bw.WriteSingle(m_linearDamping);
bw.WriteSingle(m_angularDamping);
bw.WriteSingle(m_solverStabilizationSpeedThreshold);
bw.WriteSingle(m_solverStabilizationSpeedReduction);
bw.WriteSingle(m_maxDistSqrd);
bw.WriteSingle(m_maxRotSqrd);
bw.WriteSingle(m_invBlockSize);
bw.WriteInt16(m_pathingUpperThreshold);
bw.WriteInt16(m_pathingLowerThreshold);
bw.WriteByte(m_numDeactivationFrequencyPasses);
bw.WriteByte(m_deactivationVelocityScaleSquare);
bw.WriteByte(m_minimumPathingVelocityScaleSquare);
bw.WriteByte(m_spikingVelocityScaleThresholdSquared);
bw.WriteByte(m_minimumSpikingVelocityScaleSquared);
bw.WriteUInt16(0);
bw.WriteByte(0);
}
}
}
|
using Assets.Scripts.Atmospherics;
namespace WebAPI.Payloads
{
public class AtmospherePayload : IAtmosphericContentPayload
{
public string roomId { get; set; }
public float? pipeNetworkId { get; set; }
public bool isGlobal { get; set; }
public float oxygen { get; set; }
public float volatiles { get; set; }
public float water { get; set; }
public float carbonDioxide { get; set; }
public float nitrogen { get; set; }
public float nitrousOxide { get; set; }
public float pollutant { get; set; }
public float volume { get; set; }
public float energy { get; set; }
public float temperature { get; set; }
public float pressure { get; set; }
public static AtmospherePayload FromAtmosphere(Atmosphere atmosphere)
{
var payload = new AtmospherePayload()
{
roomId = atmosphere.Room?.RoomId.ToString(),
pipeNetworkId = atmosphere.PipeNetwork?.NetworkId,
isGlobal = atmosphere.IsGlobalAtmosphere,
};
payload.CopyFromAtmosphere(atmosphere);
return payload;
}
}
} |
using System;
using System.Collections.Generic;
[System.Serializable]
public class ZenSceneData
{
public string imagePath;
public DateTime dateTime;
public List<RailSaveData> railsData = new List<RailSaveData>();
public List<EnvSaveData> envsData = new List<EnvSaveData>();
public List<TrainSaveData> trainsData = new List<TrainSaveData>();
public List<CollectableSaveData> collectableData = new List<CollectableSaveData>();
public PlaygroundSaveData playgroundData = new PlaygroundSaveData();
}
|
using FluentCore.Model;
namespace FluentCore.Interface
{
/// <summary>
/// 游戏依赖接口
/// </summary>
public interface IDependence
{
/// <summary>
/// 获取对应游戏依赖的下载请求
/// </summary>
/// <param name="root">.minecraft游戏目录</param>
/// <returns></returns>
HttpDownloadRequest GetDownloadRequest(string root);
/// <summary>
/// 获取游戏依赖相对于.minecraft的路径
/// </summary>
/// <returns></returns>
string GetRelativePath();
}
}
|
namespace ApprovalTests.Reporters
{
public struct LaunchArgs
{
private string arguments;
private string program;
public LaunchArgs(string program, string arguments)
{
this.program = program;
this.arguments = arguments;
}
public string Program => program;
public string Arguments => arguments;
public override string ToString()
{
return $"\"{program}\" {arguments}";
}
}
} |
using System;
using System.Collections.Generic;
using ENet;
using Entitas;
using Sources.Networking.Client;
using Sources.Networking.Server;
using UnityEngine;
public class GameController : MonoBehaviour
{
public static GameController I;
[NonSerialized] public Mode Mode = Mode.Inactive;
[Header("Server")] public int TargetTickPerSecond = 20;
[Header("Client")] public int PanicStateCount = 10;
public int PanicCleanupTarget = 6;
private IGroup<GameEntity> _connectionsGroup;
private readonly List<GameEntity> _connectionsBuffer = new List<GameEntity>(ServerNetworkSystem.MaxPlayers);
private Contexts _contexts;
private ClientNetworkSystem _client;
private ClientFeature _clientFeature;
private ServerNetworkSystem _server;
private ServerFeature _serverFeature;
private int _tickCount;
private ushort _tickrate = 10;
private float _timer = 1f;
private int _totalTicksThisSecond;
private string _ip = "192.168.1.1";
private float _lastUpdate;
private string _message = "";
private ushort _port = 9500;
private int _lastId;
private void Awake()
{
I = this;
Library.Initialize();
_contexts = Contexts.sharedInstance;
_connectionsGroup = _contexts.game.GetGroup(GameMatcher.Connection);
_lastUpdate = Time.realtimeSinceStartup;
}
public void StartServer()
{
if (Mode != Mode.Inactive)
throw new ApplicationException("Can't start server if already active.");
SetupHooks(_contexts);
_server = new ServerNetworkSystem(_contexts);
_server.TickRate = (ushort) TargetTickPerSecond;
var services = new Services
{
ServerSystem = _server
};
_serverFeature = new ServerFeature(_contexts, services);
Mode = Mode.Server;
}
public void StartClient()
{
if (Mode != Mode.Inactive)
throw new ApplicationException("Can't start client if already active.");
_client = new ClientNetworkSystem(_contexts);
_client.TickRate = (ushort) TargetTickPerSecond;
_client.PanicStateCount = PanicStateCount;
_client.PanicCleanupTarget = PanicCleanupTarget;
var services = new Services
{
ClientSystem = _client
};
_clientFeature = new ClientFeature(_contexts, services);
Mode = Mode.Client;
}
private void Update()
{
switch (Mode)
{
case Mode.Server:
TargetTickPerSecond = _server.TickRate;
break;
case Mode.Client:
TargetTickPerSecond = _client.TickRate;
break;
}
while (_lastUpdate < Time.realtimeSinceStartup)
{
_lastUpdate += 1f / TargetTickPerSecond;
_tickCount++;
switch (Mode)
{
case Mode.Server:
_server.Execute();
_serverFeature.Execute();
_serverFeature.Cleanup();
break;
case Mode.Client:
_client.UpdateNetwork();
_client.Execute();
_clientFeature.Execute();
_clientFeature.Cleanup();
break;
}
}
_timer -= Time.deltaTime;
if (_timer < 0f)
{
_totalTicksThisSecond = _tickCount;
_tickCount = 0;
_timer += 1;
}
}
private void OnGUI()
{
GUILayout.Label($"TPS {_totalTicksThisSecond}");
switch (Mode)
{
case Mode.Inactive:
if (GUILayout.Button("Setup Server")) StartServer();
if (GUILayout.Button("Setup Client")) StartClient();
break;
case Mode.Server:
switch (_server.State)
{
case ServerState.Stopped:
GUILayout.Label("Server stopped");
GUILayout.BeginHorizontal();
_ip = GUILayout.TextField(_ip, GUILayout.Width(120));
var tmp =
GUILayout.TextField(_port.ToString(), GUILayout.Width(60));
if (ushort.TryParse(tmp, out var result)) _port = result;
if (GUILayout.Button("Start!"))
{
var address = new Address();
address.Port = _port;
address.SetHost(_ip);
_server.StartServer(address);
}
GUILayout.EndHorizontal();
if (GUILayout.Button("localhost")) _ip = "localhost";
break;
case ServerState.Starting:
GUILayout.Label("Server starting");
break;
case ServerState.Working:
GUILayout.Label("Server working");
if (GUILayout.Button("Stop!")) _server.StopServer();
break;
case ServerState.Stopping:
GUILayout.Label("Server stopping");
break;
}
break;
case Mode.Client:
switch (_client.State)
{
case ClientState.Disconnected:
GUILayout.Label("Disconnected");
GUILayout.BeginHorizontal();
_ip = GUILayout.TextField(_ip, GUILayout.Width(120));
var tmp =
GUILayout.TextField(_port.ToString(), GUILayout.Width(60));
if (ushort.TryParse(tmp, out var result)) _port = result;
if (GUILayout.Button("Connect!"))
{
var address = new Address();
address.Port = _port;
address.SetHost(_ip);
_client.Connect(address);
}
GUILayout.EndHorizontal();
if (GUILayout.Button("localhost")) _ip = "localhost";
break;
case ClientState.Connecting:
GUILayout.Label("Connecting");
if (GUILayout.Button("Cancel")) _client.EnqueueRequest(NetworkThreadRequest.CancelConnect);
break;
case ClientState.WaitingForId:
GUILayout.Label("WaitingForId");
break;
case ClientState.Connected:
GUILayout.BeginHorizontal();
GUILayout.Label("Connected");
tmp = GUILayout.TextField(_tickrate.ToString(), GUILayout.Width(60));
if (ushort.TryParse(tmp, out result))
if (result > 0)
_tickrate = result;
if (GUILayout.Button("Set tickRate"))
_client.EnqueueCommand(new ClientSetTickrateCommand {Tickrate = _tickrate});
var str = "States :";
for (var i = 0; i < _client.StatesCount; i++) str += "#";
GUILayout.Label(str);
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
_message = GUILayout.TextField(_message, GUILayout.Width(120));
if (GUILayout.Button("Send message"))
_client.EnqueueCommand(new ClientChatMessageCommand {Message = _message});
if (GUILayout.Button("Request character"))
_client.EnqueueCommand(new ClientRequestCharacterCommand());
GUILayout.EndHorizontal();
if (GUILayout.Button("Disconnect")) _client.Disconnect();
break;
case ClientState.Disconnecting:
GUILayout.Label("Disconnecting");
break;
}
break;
}
}
private void OnDestroy()
{
switch (Mode)
{
case Mode.Server:
_server.TearDown();
_serverFeature.TearDown();
break;
case Mode.Client:
_client.TearDown();
_clientFeature.TearDown();
break;
}
Library.Deinitialize();
}
private void SetupHooks(Contexts contexts)
{
contexts.Reset();
contexts.game.OnEntityCreated += (context, entity) =>
{
((GameEntity) entity).AddId((ushort) _lastId);
_lastId++;
};
}
}
public enum Mode
{
Inactive,
Server,
Client
} |
using System.Collections.Generic;
using System.IO;
namespace CoffeeMachine
{
public class FileService
{
public static List<string> ReadLines(string path)
{
if (!File.Exists(path))
throw new FileNotFoundException($"The file \"{path}\" does not exist.");
var lines = (new List<string>(File.ReadAllLines(path)));
// Remove excess white space
lines.ForEach(line => line.Trim());
return lines;
}
}
}
|
using FlatRedBall.Glue.Managers;
using FlatRedBall.Glue.Plugins.ExportedImplementations;
using FlatRedBall.Glue.SaveClasses;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TileGraphicsPlugin.ViewModels;
namespace TileGraphicsPlugin.Controllers
{
public class TileShapeCollectionsPropertiesController :
Singleton<TileShapeCollectionsPropertiesController>
{
Views.TileShapeCollectionProperties view;
ViewModels.TileShapeCollectionPropertiesViewModel viewModel;
bool shouldApplyViewModelChanges = true;
public Views.TileShapeCollectionProperties GetView()
{
if(view == null)
{
view = new Views.TileShapeCollectionProperties();
viewModel = new ViewModels.TileShapeCollectionPropertiesViewModel();
view.DataContext = viewModel;
}
return view;
}
public bool IsTileShapeCollection(NamedObjectSave namedObject)
{
var isTileShapeCollection = false;
if (namedObject != null)
{
var ati = namedObject.GetAssetTypeInfo();
isTileShapeCollection =
ati == AssetTypeInfoAdder.Self.TileShapeCollectionAssetTypeInfo;
}
return isTileShapeCollection;
}
public void RefreshViewModelTo(NamedObjectSave namedObject, IElement element)
{
// Disconnect the view from the view model so that
// changes that happen here dont' have side effects
// through the view. For example, if we don't disconnect
// the two, then clearing the available TMX objects will set
// the selection to null, and even persist it to the Glue object
view.DataContext = null;
shouldApplyViewModelChanges = false;
viewModel.GlueObject = namedObject;
RefreshAvailableTiledObjects(element);
viewModel.UpdateFromGlueObject();
viewModel.IsEntireViewEnabled = namedObject.DefinedByBase == false;
shouldApplyViewModelChanges = true;
view.DataContext = viewModel;
}
private void RefreshAvailableTiledObjects(IElement element)
{
// refresh availble TMXs
var referencedFileSaves = element.ReferencedFiles
.Where(item =>
item.LoadedAtRuntime &&
item.GetAssetTypeInfo() == AssetTypeInfoAdder.Self.TmxAssetTypeInfo);
var namedObjects = element.AllNamedObjects
.Where(item =>
item.IsDisabled == false &&
item.GetAssetTypeInfo() == AssetTypeInfoAdder.Self.TmxAssetTypeInfo);
if (viewModel.TmxObjectNames == null)
{
viewModel.TmxObjectNames = new System.Collections.ObjectModel.ObservableCollection<string>();
}
viewModel.TmxObjectNames.Clear();
foreach (var rfs in referencedFileSaves)
{
viewModel.TmxObjectNames.Add(rfs.GetInstanceName());
}
foreach (var nos in namedObjects)
{
viewModel.TmxObjectNames.Add(nos.InstanceName);
}
}
}
}
|
using System.Text;
using Diadoc.Api.Proto.Events;
namespace Diadoc.Api
{
public partial class DiadocHttpApi
{
public void RecycleDraft(string authToken, string boxId, string draftId)
{
var sb = new StringBuilder(string.Format("/RecycleDraft?boxId={0}", boxId));
if (!string.IsNullOrEmpty(draftId)) sb.AppendFormat("&draftId={0}", draftId);
PerformHttpRequest(authToken, "POST", sb.ToString());
}
public Message SendDraft(string authToken, DraftToSend draft, string operationId = null)
{
var queryString = string.Format("/SendDraft?operationId={0}", operationId);
return PerformHttpRequest<DraftToSend, Message>(authToken, queryString, draft);
}
}
}
|
// Copyright (c) Microsoft. All rights reserved.
namespace Microsoft.Azure.Devices.Edge.Test
{
using System;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Devices.Edge.Test.Common;
using Microsoft.Azure.Devices.Edge.Test.Common.Config;
using Microsoft.Azure.Devices.Edge.Test.Helpers;
using Microsoft.Azure.Devices.Edge.Util;
using Microsoft.Azure.Devices.Edge.Util.Test.Common.NUnit;
using NUnit.Framework;
using Serilog;
[EndToEnd]
class Device : SasManualProvisioningFixture
{
[Test]
[Category("CentOsSafe")]
public async Task QuickstartCerts()
{
CancellationToken token = this.TestToken;
await this.runtime.DeployConfigurationAsync(token, this.device.NestedEdge.IsNestedEdge);
string leafDeviceId = DeviceId.Current.Generate();
var leaf = await LeafDevice.CreateAsync(
leafDeviceId,
Protocol.Amqp,
AuthenticationType.Sas,
Option.Some(this.runtime.DeviceId),
false,
this.ca,
this.IotHub,
this.device.NestedEdge.DeviceHostname,
token,
Option.None<string>(),
this.device.NestedEdge.IsNestedEdge);
await TryFinally.DoAsync(
async () =>
{
DateTime seekTime = DateTime.Now;
await leaf.SendEventAsync(token);
await leaf.WaitForEventsReceivedAsync(seekTime, token);
await leaf.InvokeDirectMethodAsync(token);
},
async () =>
{
await leaf.DeleteIdentityAsync(token);
});
}
[Test]
[Category("CentOsSafe")]
[Category("NestedEdgeOnly")]
[Category("FlakyOnNested")]
public async Task QuickstartChangeSasKey()
{
CancellationToken token = this.TestToken;
await this.runtime.DeployConfigurationAsync(token, this.device.NestedEdge.IsNestedEdge);
string leafDeviceId = DeviceId.Current.Generate();
// Create leaf and send message
var leaf = await LeafDevice.CreateAsync(
leafDeviceId,
Protocol.Amqp,
AuthenticationType.Sas,
Option.Some(this.runtime.DeviceId),
false,
this.ca,
this.IotHub,
this.device.NestedEdge.DeviceHostname,
token,
Option.None<string>(),
this.device.NestedEdge.IsNestedEdge);
await TryFinally.DoAsync(
async () =>
{
DateTime seekTime = DateTime.Now;
await leaf.SendEventAsync(token);
await leaf.WaitForEventsReceivedAsync(seekTime, token);
await leaf.InvokeDirectMethodAsync(token);
},
async () =>
{
await leaf.Close();
await leaf.DeleteIdentityAsync(token);
});
// Re-create the leaf with the same device ID, for our purposes this is
// the equivalent of updating the SAS keys
var leafUpdated = await LeafDevice.CreateAsync(
leafDeviceId,
Protocol.Amqp,
AuthenticationType.Sas,
Option.Some(this.runtime.DeviceId),
false,
this.ca,
this.IotHub,
this.device.NestedEdge.DeviceHostname,
token,
Option.None<string>(),
this.device.NestedEdge.IsNestedEdge);
await TryFinally.DoAsync(
async () =>
{
DateTime seekTime = DateTime.Now;
await leafUpdated.SendEventAsync(token);
await leafUpdated.WaitForEventsReceivedAsync(seekTime, token);
await leafUpdated.InvokeDirectMethodAsync(token);
},
async () =>
{
await leafUpdated.Close();
await leafUpdated.DeleteIdentityAsync(token);
});
}
[Test]
[Category("CentOsSafe")]
[Category("NestedEdgeOnly")]
[Category("NestedEdgeAmqpOnly")]
public async Task RouteMessageL3LeafToL4Module()
{
CancellationToken token = this.TestToken;
await this.runtime.DeployConfigurationAsync(token, Context.Current.NestedEdge);
// These must match the IDs in nestededge_middleLayerBaseDeployment_amqp.json,
// which defines a route that filters by deviceId to forwards the message
// to the relayer module
string parentDeviceId = Context.Current.ParentDeviceId.Expect(() => new InvalidOperationException("No parent device ID set!"));
string leafDeviceId = "L3LeafToRelayer1";
string relayerModuleId = "relayer1";
// Create leaf and send message
var leaf = await LeafDevice.CreateAsync(
leafDeviceId,
Protocol.Amqp,
AuthenticationType.Sas,
Option.Some(this.runtime.DeviceId),
false,
this.ca,
this.IotHub,
Context.Current.Hostname.GetOrElse(Dns.GetHostName().ToLower()),
token,
Option.None<string>(),
Context.Current.NestedEdge);
await TryFinally.DoAsync(
async () =>
{
// Send a message from the leaf device
DateTime seekTime = DateTime.Now;
await leaf.SendEventAsync(token);
Log.Verbose($"Sent message from {leafDeviceId}");
// Verify that the message was received/resent by the relayer module on L4
await Profiler.Run(
() => this.IotHub.ReceiveEventsAsync(
parentDeviceId,
seekTime,
data =>
{
data.SystemProperties.TryGetValue("iothub-connection-device-id", out object devId);
data.SystemProperties.TryGetValue("iothub-connection-module-id", out object modId);
data.Properties.TryGetValue("leaf-message-id", out object msgId);
Log.Verbose($"Received event for '{devId + "/" + modId}' with message ID '{msgId}'");
return devId != null && devId.ToString().Equals(parentDeviceId)
&& modId.ToString().Equals(relayerModuleId);
},
token),
"Received events from module '{Device}' on Event Hub '{EventHub}'",
parentDeviceId + "/" + relayerModuleId,
this.IotHub.EntityPath);
},
async () =>
{
await leaf.Close();
await leaf.DeleteIdentityAsync(token);
});
}
[Test]
[Category("CentOsSafe")]
[Category("Flaky")]
public async Task DisableReenableParentEdge()
{
CancellationToken token = this.TestToken;
Log.Verbose("Deploying L3 Edge");
await this.runtime.DeployConfigurationAsync(token, this.device.NestedEdge.IsNestedEdge);
// Disable the parent Edge device
Log.Verbose("Disabling Edge device");
await this.IotHub.UpdateEdgeEnableStatus(this.runtime.DeviceId, false);
await Task.Delay(TimeSpan.FromSeconds(10));
// Re-enable parent Edge
Log.Verbose("Re-enabling Edge device");
await this.IotHub.UpdateEdgeEnableStatus(this.runtime.DeviceId, true);
await Task.Delay(TimeSpan.FromSeconds(10));
// Try connecting
string leafDeviceId = DeviceId.Current.Generate();
var leaf = await LeafDevice.CreateAsync(
leafDeviceId,
Protocol.Amqp,
AuthenticationType.Sas,
Option.Some(this.runtime.DeviceId),
false,
this.ca,
this.IotHub,
this.device.NestedEdge.DeviceHostname,
token,
Option.None<string>(),
this.device.NestedEdge.IsNestedEdge);
await TryFinally.DoAsync(
async () =>
{
DateTime seekTime = DateTime.Now;
await leaf.SendEventAsync(token);
await leaf.WaitForEventsReceivedAsync(seekTime, token);
await leaf.InvokeDirectMethodAsync(token);
},
async () =>
{
await leaf.DeleteIdentityAsync(token);
});
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Runtime.CompilerServices;
using System.Drawing;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Media;
using Uno.Collections;
using Uno.Disposables;
using Uno.Extensions;
using Uno.UI.DataBinding;
using ObjCRuntime;
#if XAMARIN_IOS_UNIFIED
using Foundation;
using UIKit;
#elif XAMARIN_IOS
using MonoTouch.Foundation;
using MonoTouch.UIKit;
#endif
#if !NET6_0_OR_GREATER
using NativeHandle = System.IntPtr;
#endif
namespace Uno.UI.Controls
{
public partial class BindableUIView : UIView, DependencyObject, IShadowChildrenProvider
{
private MaterializableList<UIView> _shadowChildren = new MaterializableList<UIView>();
List<UIView> IShadowChildrenProvider.ChildrenShadow => _shadowChildren.Materialized;
internal IReadOnlyList<UIView> ChildrenShadow => _shadowChildren;
public override void SubviewAdded(UIView uiview)
{
base.SubviewAdded(uiview);
// Reference the list as we don't know where
// the items has been added other than by getting the complete list.
// Subviews materializes a new array at every call, which makes it safe to
// reference.
_shadowChildren = new MaterializableList<UIView>(Subviews);
}
internal List<UIView>.Enumerator GetChildrenEnumerator() => _shadowChildren.Materialized.GetEnumerator();
public override void AddSubview(UIView view)
{
// As iOS will invoke the MovedToWindow on the 'view' (which will invoke the Loaded event)
// ** before ** invoking the SubviewAdded on its parent (i.e. this element),
// we cannot rely only on the cloned collection made in that SubviewAdded callback.
// Instead we have to pre-update the _shadowChildren so handlers of the Loaded event will be able
// to properly walk the tree up and down (cf. EffectiveViewport).
_shadowChildren.Add(view);
base.AddSubview(view);
}
public override void InsertSubview(UIView view, nint atIndex)
{
// cf. AddSubview comment!
_shadowChildren.Insert((int)atIndex, view);
base.InsertSubview(view, atIndex);
}
public override void WillRemoveSubview(UIView uiview)
{
// cf. AddSubview comment!
var index = _shadowChildren.IndexOf(uiview, ReferenceEqualityComparer<UIView>.Default);
if (index != -1)
{
_shadowChildren.RemoveAt(index);
}
base.WillRemoveSubview(uiview);
}
public BindableUIView()
{
Initialize();
ClipsToBounds = false;
}
public BindableUIView(NativeHandle handle)
: base(handle)
{
Initialize();
}
public BindableUIView(RectangleF frame)
: base(frame)
{
Initialize();
}
public BindableUIView(NSCoder coder)
: base(coder)
{
Initialize();
}
public BindableUIView(NSObjectFlag t)
: base(t)
{
Initialize();
}
private void Initialize()
{
InitializeBinder();
}
/// <summary>
/// Moves a view from one position to another position, without unloading it.
/// </summary>
/// <param name="oldIndex">The old index of the item</param>
/// <param name="newIndex">The new index of the item</param>
/// <remarks>
/// The trick for this method is to move the child from one position to the other
/// without calling RemoveView and AddView. In this context, the only way to do this is
/// to call BringSubviewToFront, which is the only available method on UIView that manipulates
/// the index of a view, even if it does not allow for specifying an index.
/// </remarks>
internal void MoveViewTo(int oldIndex, int newIndex)
{
var view = _shadowChildren[oldIndex];
_shadowChildren.RemoveAt(oldIndex);
_shadowChildren.Insert(newIndex, view);
var reorderIndex = Math.Min(oldIndex, newIndex);
for (int i = reorderIndex; i < _shadowChildren.Count; i++)
{
BringSubviewToFront(_shadowChildren[i]);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using SmartHomeApi.Core.Interfaces;
using SmartHomeApi.Core.Interfaces.Configuration;
using SmartHomeApi.Core.Services;
using SmartHomeApi.WebApi.CLI;
namespace SmartHomeApi.WebApi
{
public class Program
{
public static async Task<int> Main(string[] args)
{
//System.Diagnostics.Debugger.Launch();
var builder = new ConfigurationBuilder();
try
{
var config = builder.AddJsonFile("appsettings.json", optional: false).Build();
if (args is { Length: > 0 })
{
if (args.Length == 1 && args[0] == "cli")
{
Console.WriteLine("Welcome to SmartHomeApi command line interface!");
var code = await new CLIMainMenu().Execute(new CLIContext());
if (code == 2)
{
await StartApp(args, config);
return 0;
}
return code;
}
Console.WriteLine("Invalid argument. Run SmartHomeApi with 'cli' argument to enter CLI mode.");
return 1;
}
await StartApp(args, config);
return 0;
}
catch (FileNotFoundException)
{
Console.WriteLine("appsettings.json not found so run installer.");
var code = await new CLIMainMenu().Execute(new CLIContext
{ Options = new Dictionary<string, object> { { "MenuItem", "Create appsettings.json" } } });
if (code == 2)
{
var config = builder.AddJsonFile("appsettings.json", optional: false).Build();
await StartApp(args, config);
return 0;
}
return code;
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
private static async Task StartApp(string[] args, IConfigurationRoot config)
{
Console.WriteLine("Press Ctrl+C or Ctrl+Break to shut down");
AppSettings settings = new AppSettings();
config.GetSection("AppSettings").Bind(settings);
if (!string.IsNullOrWhiteSpace(settings.ApiCulture))
{
var culture = new CultureInfo(settings.ApiCulture);
CultureInfo.DefaultThreadCurrentCulture = culture;
CultureInfo.DefaultThreadCurrentUICulture = culture;
}
var host = CreateHostBuilder(args).Build();
var logger = host.Services.GetService<IApiLogger>();
var migrationResult = await AppMigrator.Migrate(logger, settings);
if (migrationResult == 1) return;
if (migrationResult == 2)
{
//Version has been updated so need to actualize AppSettings
config.Reload();
config.GetSection("AppSettings").Bind(settings);
}
await host.RunAsync();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); })
.ConfigureServices(services => { services.AddHostedService<ApiManagerService>(); })
.UseWindowsService();
}
} |
// MIT License - Copyright (c) Malte Rupprecht
// This file is subject to the terms and conditions defined in
// LICENSE, which is part of this source code package
using System;
using LibreLancer.Ini;
namespace LibreLancer.Data.Equipment
{
public abstract class AbstractEquipment
{
[Entry("nickname")]
public string Nickname;
[Entry("da_archetype")]
public string DaArchetype;
[Entry("material_library")]
public string MaterialLibrary;
[Entry("lodranges")]
public float[] LODRanges;
[Entry("hp_child")]
public string HPChild { get; private set; }
[Entry("ids_name")]
public int IdsName = -1;
[Entry("ids_info")]
public int IdsInfo = -1;
[Entry("lootable")]
public bool Lootable;
[Entry("hit_pts")]
public int Hitpoints;
}
}
|
// Copyright (c) Converter Systems LLC. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Urho;
using Xamarin.Forms;
namespace Workstation.MobileHmi
{
public partial class RobotView : ContentView
{
private RobotGame robotGame;
private bool initialized;
public RobotView()
{
this.InitializeComponent();
}
protected async override void OnSizeAllocated(double width, double height)
{
base.OnSizeAllocated(width, height);
if (!this.initialized)
{
if (height > 0 && width > 0)
{
this.initialized = true;
this.robotGame = await this.UrhoSurface.Show<RobotGame>(new ApplicationOptions(assetsFolder: "Data") { Orientation = ApplicationOptions.OrientationType.LandscapeAndPortrait });
this.robotGame.Axis1 = this.Axis1;
this.robotGame.Axis2 = this.Axis2;
this.robotGame.Axis3 = this.Axis3;
this.robotGame.Axis4 = this.Axis4;
}
}
}
public float Axis1
{
get { return (float)this.GetValue(Axis1Property); }
set { this.SetValue(Axis1Property, value); }
}
public static readonly BindableProperty Axis1Property =
BindableProperty.Create(nameof(Axis1), typeof(float), typeof(RobotView), 0f, propertyChanged: new BindableProperty.BindingPropertyChangedDelegate(OnAxis1Changed));
private static void OnAxis1Changed(BindableObject d, object oldValue, object newValue)
{
var control = (RobotView)d;
var game = control.robotGame;
if (game != null)
{
game.Axis1 = (float)newValue;
}
}
public float Axis2
{
get { return (float)this.GetValue(Axis2Property); }
set { this.SetValue(Axis2Property, value); }
}
public static readonly BindableProperty Axis2Property =
BindableProperty.Create(nameof(Axis2), typeof(float), typeof(RobotView), 0f, propertyChanged: new BindableProperty.BindingPropertyChangedDelegate(OnAxis2Changed));
private static void OnAxis2Changed(BindableObject d, object oldValue, object newValue)
{
var control = (RobotView)d;
var game = control.robotGame;
if (game != null)
{
control.robotGame.Axis2 = (float)newValue;
}
}
public float Axis3
{
get { return (float)this.GetValue(Axis3Property); }
set { this.SetValue(Axis3Property, value); }
}
public static readonly BindableProperty Axis3Property =
BindableProperty.Create(nameof(Axis3), typeof(float), typeof(RobotView), 0f, propertyChanged: new BindableProperty.BindingPropertyChangedDelegate(OnAxis3Changed));
private static void OnAxis3Changed(BindableObject d, object oldValue, object newValue)
{
var control = (RobotView)d;
var game = control.robotGame;
if (game != null)
{
control.robotGame.Axis3 = (float)newValue;
}
}
public float Axis4
{
get { return (float)this.GetValue(Axis4Property); }
set { this.SetValue(Axis4Property, value); }
}
public static readonly BindableProperty Axis4Property =
BindableProperty.Create(nameof(Axis4), typeof(float), typeof(RobotView), 0f, propertyChanged: new BindableProperty.BindingPropertyChangedDelegate(OnAxis4Changed));
private static void OnAxis4Changed(BindableObject d, object oldValue, object newValue)
{
var control = (RobotView)d;
var game = control.robotGame;
if (game != null)
{
control.robotGame.Axis4 = (float)newValue;
}
}
}
}
|
// Instance generated by TankLibHelper.InstanceBuilder
// ReSharper disable All
namespace TankLib.STU.Types {
[STUAttribute(0xBD2D717B)]
public class STU_BD2D717B : STU_1361E674 {
[STUFieldAttribute(0xB257A3A4)]
public byte m_B257A3A4;
}
}
|
namespace MudBlazor.Interfaces
{
public interface IForm
{
public bool IsValid { get; }
public string[] Errors { get; }
internal void Add(IFormComponent formControl);
internal void Remove(IFormComponent formControl);
internal void Update(IFormComponent formControl);
}
}
|
namespace WarriorsSnuggery.Graphics
{
public class TextRenderable : IRenderable
{
BatchObject charRenderable;
static readonly Vector shadowOffset = new Vector(0.02f * WindowInfo.Ratio, -0.02f, 0);
Vector position;
readonly Font font;
Color color;
public TextRenderable(Font font, char c, Color color)
{
this.font = font;
SetCharacter(c);
SetColor(color);
}
public void SetPosition(CPos pos, int offset = 0)
{
position = pos.ToVector() + new Vector(offset / 1024f, 0, 0);
charRenderable.SetPosition(position);
}
public void SetScale(float scale)
{
charRenderable.SetScale(scale);
}
public void SetScale(Vector scale)
{
charRenderable.SetScale(scale);
}
public void SetRotation(VAngle rotation)
{
charRenderable.SetRotation(rotation);
}
public void SetColor(Color color)
{
this.color = color;
charRenderable.SetColor(color);
}
public void SetCharacter(char c)
{
charRenderable = new BatchObject(Mesh.Character(font, c));
charRenderable.SetColor(color);
}
public void Render()
{
if (Settings.EnableTextShadowing)
{
charRenderable.SetColor(Color.Black);
charRenderable.SetPosition(position + shadowOffset);
charRenderable.Render();
charRenderable.SetPosition(position - shadowOffset);
charRenderable.SetColor(color);
}
charRenderable.Render();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SignalRuleLeft : MonoBehaviour {
public BoxCollider boxColliderComponent;
public BoxCollider boxColliderComponent2;
public BoxCollider boxColliderComponent3;
public BoxCollider boxColliderComponent4;
public BoxCollider boxColliderComponent5;
public BoxCollider boxColliderComponent6;
void Update()
{
if (Input.GetKeyDown(KeyCode.Z))
{
boxColliderComponent.enabled = false;
boxColliderComponent2.enabled = false;
boxColliderComponent3.enabled = false;
boxColliderComponent4.enabled = false;
boxColliderComponent5.enabled = false;
boxColliderComponent6.enabled = false;
}
else if (Input.GetKeyUp(KeyCode.Z))
{
boxColliderComponent.enabled = true;
boxColliderComponent2.enabled = true;
boxColliderComponent3.enabled = true;
boxColliderComponent4.enabled = true;
boxColliderComponent5.enabled = true;
boxColliderComponent6.enabled = true;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace PnP.PowerShell.Commands.Utilities
{
internal static class BrowserHelper
{
public static void LaunchBrowser(string url)
{
if (OperatingSystem.IsWindows())
{
Process.Start(new ProcessStartInfo(url) { UseShellExecute = true }); // Works ok on windows
}
else if (OperatingSystem.IsLinux())
{
Process.Start("xdg-open", url); // Works ok on linux
}
else if (OperatingSystem.IsMacOS())
{
Process.Start("open", url); // Not tested
}
}
}
}
|
using CSCore.CoreAudioAPI;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
namespace CSCore.Test.CoreAudioAPI
{
[TestClass]
public class EndpointTests
{
[TestMethod]
[TestCategory("CoreAudioAPI.Endpoint")]
public void CanCreateAudioEndpointVolume()
{
using (var device = Utils.GetDefaultRenderDevice())
using (var endpointVolume = AudioEndpointVolume.FromDevice(device))
{
}
}
[TestMethod]
[TestCategory("CoreAudioAPI.Endpoint")]
public void CanGetAudioEndpointVolume()
{
using (var device = Utils.GetDefaultRenderDevice())
using (var endpointVolume = AudioEndpointVolume.FromDevice(device))
{
var volume = endpointVolume.GetMasterVolumeLevelScalar();
Debug.WriteLine("Volume: {0}", volume);
endpointVolume.SetMasterVolumeLevelScalar(0.5f, Guid.Empty);
}
}
[TestMethod]
[TestCategory("CoreAudioAPI.Endpoint")]
public void CanGetAudioEndpointVolumeChannelCount()
{
using (var device = Utils.GetDefaultRenderDevice())
using (var endpointVolume = AudioEndpointVolume.FromDevice(device))
{
Debug.WriteLine(endpointVolume.GetChannelCount());
}
}
[TestMethod]
[TestCategory("CoreAudioAPI.Endpoint")]
public void CanCreateAudioEndpointVolumeNotification()
{
using (var device = Utils.GetDefaultRenderDevice())
using (var endpointVolume = AudioEndpointVolume.FromDevice(device))
{
AudioEndpointVolumeCallback callback = new AudioEndpointVolumeCallback();
callback.NotifyRecived += (s, e) =>
{
Debug.WriteLine("Notification1");
//Debug.Assert(e.Channels == endpointVolume.ChannelCount);
};
endpointVolume.RegisterControlChangeNotify(callback);
var vol = endpointVolume.GetChannelVolumeLevelScalar(0);
endpointVolume.SetChannelVolumeLevelScalar(0, 1f, Guid.Empty);
endpointVolume.SetChannelVolumeLevelScalar(0, vol, Guid.Empty);
endpointVolume.UnregisterControlChangeNotify(callback);
System.Threading.Thread.Sleep(1000);
}
}
[TestMethod]
[TestCategory("CoreAudioAPI.Endpoint")]
public void CanCreateAudioMeterInformation()
{
using (var device = Utils.GetDefaultRenderDevice())
using (var meter = AudioMeterInformation.FromDevice(device))
{
}
}
[TestMethod]
[TestCategory("CoreAudioAPI.Endpoint")]
public void CanGetAudioMeterInformationPeakValue()
{
using (var device = Utils.GetDefaultRenderDevice())
using (var meter = AudioMeterInformation.FromDevice(device))
{
Console.WriteLine(meter.PeakValue);
}
}
[TestMethod]
[TestCategory("CoreAudioAPI.Endpoint")]
public void CanGetAudioMeterInformationChannelsPeaks()
{
using (var device = Utils.GetDefaultRenderDevice())
using (var meter = AudioMeterInformation.FromDevice(device))
{
for (int i = 0; i < meter.MeteringChannelCount; i++)
{
Console.WriteLine(meter[i]);
}
}
}
}
} |
using System;
using DemoParser.Parser.Components.Abstract;
using DemoParser.Utils;
using DemoParser.Utils.BitStreams;
namespace DemoParser.Parser.Components.Packets.StringTableEntryTypes {
public class QueryPort : StringTableEntryData {
internal override bool InlineToString => true;
public uint Port;
public QueryPort(SourceDemo? demoRef) : base(demoRef) {}
internal override StringTableEntryData CreateCopy() {
return new QueryPort(DemoRef) {Port = Port};
}
protected override void Parse(ref BitStreamReader bsr) {
Port = bsr.ReadUInt();
}
internal override void WriteToStreamWriter(BitStreamWriter bsw) {
throw new NotImplementedException();
}
public override void PrettyWrite(IPrettyWriter iw) {
iw.Append(Port.ToString());
}
}
} |
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using Wintellect.PowerCollections;
using nJocLogic.data;
using nJocLogic.gameContainer;
namespace nJocLogic.util.gdl.model
{
public class SentenceDomainModels
{
public enum VarDomainOpts
{
IncludeHead,
BodyOnly
}
public static IDictionary<TermVariable, ISet<TermObject>> GetVarDomains(
Implication rule,
ISentenceDomain domainModel,
VarDomainOpts includeHead)
{
// For each positive definition of sentences in the rule, intersect their
// domains everywhere the variables show up
var varDomainsByVar = new MultiDictionary<TermVariable, ISet<TermObject>>(true);
foreach (Expression literal in GetSentences(rule, includeHead))
{
var sentence = literal as Fact;
if (sentence != null && sentence.RelationName != GameContainer.Parser.TokDistinct)
{
var form = new SimpleSentenceForm(sentence);
ISentenceFormDomain formWithDomain = domainModel.GetDomain(form);
List<Term> tuple = sentence.NestedTerms.ToList();
for (int i = 0; i < tuple.Count; i++)
{
var variable = tuple[i] as TermVariable;
if (variable != null)
varDomainsByVar.Add(variable, formWithDomain.GetDomainForSlot(i));
}
}
}
return CombineDomains(varDomainsByVar);
}
/// <summary>
/// Return all the sentences in a rule (the antecedents) and include the head fact if specified
/// </summary>
/// <param name="rule">The rule to return the sentences from</param>
/// <param name="includeHead">Include the consequent as well as the antecedents</param>
/// <returns>An enumerable of all sentences in the rule</returns>
public static IEnumerable<Expression> GetSentences(Implication rule, VarDomainOpts includeHead)
{
return includeHead == VarDomainOpts.IncludeHead
? ImmutableList.Create(rule.Consequent).Concat(rule.Antecedents.Conjuncts)
: rule.Antecedents.Conjuncts;
}
private static IDictionary<TermVariable, ISet<TermObject>> CombineDomains(
IEnumerable<KeyValuePair<TermVariable, ICollection<ISet<TermObject>>>> varDomainsByVar)
{
var result = new Dictionary<TermVariable, ISet<TermObject>>();
foreach (var kv in varDomainsByVar)
result[kv.Key] = IntersectSets(kv.Value);
return result.ToImmutableDictionary();
}
private static ISet<T> IntersectSets<T>(ICollection<ISet<T>> input)
{
if (!input.Any())
throw new Exception("Can't take an intersection of no sets");
ISet<T> result = null;
foreach (ISet<T> set in input)
{
if (result == null)
result = new HashSet<T>(set);
else
result.IntersectWith(set);
}
Debug.Assert(result != null);
return result;
}
}
}
|
using System.Collections.Generic;
namespace Z80.Kernel.Z80Assembler.ExpressionHandling
{
internal abstract class Operator
{
public int Priority { get; }
public int OperandCount { get; }
public bool IsUnary { get; }
public string Token { get; }
public void AddOperand(ushort operand)
{
Operands.Push(operand);
}
public static Operator Create(string token, bool unary = false)
{
switch (token)
{
case ExpressionConstans.Operators.LeftParent: return new LeftParent();
case ExpressionConstans.Operators.RightParent: return new RightParent();
case ExpressionConstans.Operators.Plus: return new Plus(unary);
case ExpressionConstans.Operators.Minus: return new Minus(unary);
case ExpressionConstans.Operators.Multiply: return new Multiply();
case ExpressionConstans.Operators.Divide: return new Divide();
case ExpressionConstans.Operators.And: return new And();
case ExpressionConstans.Operators.Or: return new Or();
case ExpressionConstans.Operators.Xor: return new Xor();
case ExpressionConstans.Operators.LeftShift: return new LeftShift();
case ExpressionConstans.Operators.RightShift: return new RightShift();
case ExpressionConstans.Operators.OnesComplement: return new OnesComplement();
case ExpressionConstans.Operators.Sqrt: return new Sqrt();
case ExpressionConstans.Operators.Abs: return new Abs();
case ExpressionConstans.Operators.High: return new High();
case ExpressionConstans.Operators.Low: return new Low();
default: throw new Z80AssemblerException($"Nem támogatott operátor:{token}");
}
}
public static bool operator <=(Operator op1, Operator op2)
{
return op1.Priority <= op2.Priority;
}
public static bool operator >=(Operator op1, Operator op2)
{
return op1.Priority >= op2.Priority;
}
public abstract ushort Calculate();
protected Operator(string token, bool isUnary, int operandCount, int priority)
{
Operands = new Stack<ushort>();
IsUnary = isUnary;
OperandCount = operandCount;
Priority = priority;
Token = token;
}
protected readonly Stack<ushort> Operands;
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ArDrone2.Client.NavData
{
public class NavDataRetriever
{
private readonly UdpClient client;
private IPEndPoint endpoint;
private const int keepAliveSignalInterval = 200;
private Stopwatch keepAliveStopwatch = new Stopwatch();
private const int initialSequenceNumber = 0;
private uint checksum;
private NavigationDataHeaderStruct currentNavigationDataHeaderStruct;
private NavigationDataStruct currentNavigationDataStruct;
private DroneData currentNavigationData;
private uint currentSequenceNumber;
private bool initialized = false;
private bool commandModeEnabled = false;
public NavDataRetriever(string remoteIpAddress, int port, int timeoutValue, UdpClient client = null)
{
ResetVariables();
keepAliveStopwatch = new Stopwatch();
endpoint = new IPEndPoint(IPAddress.Parse(remoteIpAddress), port);
this.client = client ?? new UdpClient(5554);
}
protected void ResetVariables()
{
keepAliveStopwatch.Reset();
currentNavigationDataStruct = new NavigationDataStruct();
currentNavigationDataHeaderStruct = new NavigationDataHeaderStruct();
currentNavigationData = new DroneData();
currentSequenceNumber = initialSequenceNumber;
}
public void WaitForFirstMessageToArrive()
{
int currentRetries = 0;
int maxRetries = 20;
while (currentRetries < maxRetries &&
currentNavigationDataHeaderStruct.Status == 0)
{
currentRetries++;
Thread.Sleep(50);
}
}
protected virtual void StartKeepAliveSignal()
{
keepAliveStopwatch.Restart();
}
protected bool IsKeepAliveSignalNeeded()
{
if (keepAliveStopwatch.ElapsedMilliseconds > keepAliveSignalInterval)
{
keepAliveStopwatch.Restart();
return true;
}
else
{
return false;
}
}
public Action<int> SendMessage;
public void Start() => Task.Factory.StartNew(ProcessWorkerThread);
protected void ProcessWorkerThread()
{
SendMessage(1);
StartKeepAliveSignal();
do
{
if (IsKeepAliveSignalNeeded())
SendMessage(1);
byte[] buffer = ReceiveData();
if (buffer != null)
{
DetermineNavigationDataHeader(buffer);
if (IsNavigationDataHeaderValid())
{
UpdateNavigationData(buffer);
if (!IsChecksumValid(buffer))
ProcessInvalidChecksum();
}
currentSequenceNumber = currentNavigationDataHeaderStruct.SequenceNumber;
}
}
while (!false);
}
private byte[] ReceiveData()
{
byte[] buffer = null;
try
{
if (client != null)
buffer = client.Receive(ref endpoint);
}
catch (SocketException e)
{
if (e.ErrorCode == 10060) //Timeout
SendMessage(1);
if (client != null)
buffer = client.Receive(ref endpoint);
}
return buffer;
}
protected void AfterDisconnect()
{
ResetVariables();
}
public void ResetSequenceNumber()
{
currentSequenceNumber = initialSequenceNumber;
}
private bool IsNavigationDataHeaderValid()
{
return currentNavigationDataHeaderStruct.Header == 0x55667788;
}
private void UpdateNavigationData(byte[] buffer)
{
MemoryStream memoryStream;
BinaryReader reader;
InitializeBinaryReader(buffer, out memoryStream, out reader);
while (memoryStream.Position < memoryStream.Length)
{
ushort tag = reader.ReadUInt16();
ushort size = reader.ReadUInt16();
if (IsNavigationData(tag))
{
DetermineNavigationData(buffer, (int)(memoryStream.Position - 4));
memoryStream.Position += size - 4;
}
else if (IsNavigationDataCheckSum(tag))
{
checksum = reader.ReadUInt32();
}
else
{
memoryStream.Position += size - 4;
}
}
}
private void InitializeBinaryReader(byte[] buffer, out MemoryStream memoryStream, out BinaryReader reader)
{
memoryStream = new MemoryStream(buffer);
reader = new BinaryReader(memoryStream);
memoryStream.Position = Marshal.SizeOf(typeof(NavigationDataHeaderStruct));
}
private bool IsNavigationData(ushort tag)
{
return tag == 0;
}
private bool IsNavigationDataCheckSum(ushort tag)
{
return tag == 0xFFFF;
}
private bool IsChecksumValid(byte[] buffer)
{
return CalculateChecksum(buffer) == checksum;
}
private uint CalculateChecksum(byte[] buffer)
{
uint checksum = 0;
for (uint index = 0; index < buffer.Length - 8; index++)
{
checksum += buffer[index];
}
return checksum;
}
private void ProcessInvalidChecksum()
{
// TODO implement
}
private void DetermineNavigationDataHeader(byte[] buffer)
{
unsafe
{
fixed (byte* entry = &buffer[0])
{
currentNavigationDataHeaderStruct = *(NavigationDataHeaderStruct*)entry;
}
}
SetStatusFlags(currentNavigationDataHeaderStruct.Status);
//Console.WriteLine(currentNavigationDataHeaderStruct.Status);
}
private void DetermineNavigationData(byte[] buffer, int position)
{
unsafe
{
fixed (byte* entry = &buffer[position])
{
currentNavigationDataStruct = *(NavigationDataStruct*)entry;
}
}
currentNavigationData = new DroneData(currentNavigationDataStruct);
}
private void SetStatusFlags(uint state)
{
uint initializedState = state & 2048; // 11th bit of the status entry
uint commandModeState = state & 64; // 8th bit of the status entry
initialized = initializedState == 0;
commandModeEnabled = commandModeState != 0;
}
public DroneData CurrentNavigationData
{
get
{
return currentNavigationData;
}
}
public bool IsInitialized
{
get
{
return initialized;
}
}
public bool IsCommandModeEnabled
{
get
{
return commandModeEnabled;
}
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.