content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System; [Serializable] public class GuildstatueDataVo { public int Rank; public string Modle; public float Offset; public string Tile; public string Pos1; public string Pos2; }
10.833333
30
0.748718
[ "MIT" ]
moto2002/tianzi_src2
src/GuildstatueDataVo.cs
195
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; using Xtoad.App.Budget.Models; using Xtoad.App.Budget.ViewModels; using Xtoad.App.Budget.Views; namespace Xtoad.App.Budget.Views { public partial class ItemsPage : ContentPage { ItemsViewModel _viewModel; public ItemsPage() { InitializeComponent(); BindingContext = _viewModel = new ItemsViewModel(); } protected override void OnAppearing() { base.OnAppearing(); _viewModel.OnAppearing(); } } }
22.09375
63
0.663366
[ "MIT" ]
442803117/Xtoad.App.Budget
Xtoad.App.Budget/Views/ItemsPage.xaml.cs
709
C#
using Dapper; using Xunit; namespace DotNetCore.CAP.MySql.Test { [Collection("MySql")] public class MySqlStorageTest : DatabaseTestHost { private readonly string _dbName; private readonly string _masterDbConnectionString; public MySqlStorageTest() { _dbName = ConnectionUtil.GetDatabaseName(); _masterDbConnectionString = ConnectionUtil.GetMasterConnectionString(); } [Fact] public void Database_IsExists() { using (var connection = ConnectionUtil.CreateConnection(_masterDbConnectionString)) { var databaseName = ConnectionUtil.GetDatabaseName(); var sql = $@"SELECT SCHEMA_NAME FROM SCHEMATA WHERE SCHEMA_NAME = '{databaseName}'"; var result = connection.QueryFirstOrDefault<string>(sql); Assert.NotNull(result); Assert.True(databaseName.Equals(result, System.StringComparison.CurrentCultureIgnoreCase)); } } [Theory] [InlineData("cap.published")] [InlineData("cap.received")] public void DatabaseTable_IsExists(string tableName) { using (var connection = ConnectionUtil.CreateConnection(_masterDbConnectionString)) { var sql = $"SELECT TABLE_NAME FROM `TABLES` WHERE TABLE_SCHEMA='{_dbName}' AND TABLE_NAME = '{tableName}'"; var result = connection.QueryFirstOrDefault<string>(sql); Assert.NotNull(result); Assert.Equal(tableName, result); } } } }
36.244444
123
0.614347
[ "MIT" ]
123longteng/CAP
test/DotNetCore.CAP.MySql.Test/MySqlStorageTest.cs
1,633
C#
using System; using System.IO; namespace UsingBloco { class Program { static void Main(string[] args) { string caminho = @"C:\Users\YANICK\Desktop\Rumo a PROGRAMADOR\C#\ApredendoArquivos\file1.txt"; try { // using (FileStream fs = new FileStream(caminho, FileMode.Open)) /*jeito mais longo*/ // { using (StreamReader sr = File.OpenText(caminho)) /*Apos a execucao do bloco using, o arquivo instanciado é fechado*/ { while (!sr.EndOfStream) { string line = sr.ReadLine(); Console.WriteLine(line); } } //} } catch (IOException e) { Console.WriteLine("Erro!!"); Console.WriteLine(e.Message); } } } }
30.088235
106
0.418377
[ "MIT" ]
Yanicksantos/.NET
ApredendoArquivos/UsingBlock/UsingBlock/Program.cs
1,026
C#
using System; using System.Linq; using Umbraco.Core; using Umbraco.Core.Cache; using Umbraco.Core.Models; using Umbraco.Core.Models.PublishedContent; using Umbraco.Core.Services; using Umbraco.Core.Services.Changes; using Umbraco.Web.PublishedCache; namespace Umbraco.Web.Cache { public sealed class ContentTypeCacheRefresher : PayloadCacheRefresherBase<ContentTypeCacheRefresher, ContentTypeCacheRefresher.JsonPayload> { private readonly IPublishedSnapshotService _publishedSnapshotService; private readonly IPublishedModelFactory _publishedModelFactory; private readonly IdkMap _idkMap; public ContentTypeCacheRefresher(AppCaches appCaches, IPublishedSnapshotService publishedSnapshotService, IPublishedModelFactory publishedModelFactory, IdkMap idkMap) : base(appCaches) { _publishedSnapshotService = publishedSnapshotService; _publishedModelFactory = publishedModelFactory; _idkMap = idkMap; } #region Define protected override ContentTypeCacheRefresher This => this; public static readonly Guid UniqueId = Guid.Parse("6902E22C-9C10-483C-91F3-66B7CAE9E2F5"); public override Guid RefresherUniqueId => UniqueId; public override string Name => "Content Type Cache Refresher"; #endregion #region Refresher public override void Refresh(JsonPayload[] payloads) { // TODO: refactor // we should NOT directly clear caches here, but instead ask whatever class // is managing the cache to please clear that cache properly if (payloads.Any(x => x.ItemType == typeof(IContentType).Name)) { ClearAllIsolatedCacheByEntityType<IContent>(); ClearAllIsolatedCacheByEntityType<IContentType>(); } if (payloads.Any(x => x.ItemType == typeof(IMediaType).Name)) { ClearAllIsolatedCacheByEntityType<IMedia>(); ClearAllIsolatedCacheByEntityType<IMediaType>(); } if (payloads.Any(x => x.ItemType == typeof(IMemberType).Name)) { ClearAllIsolatedCacheByEntityType<IMember>(); ClearAllIsolatedCacheByEntityType<IMemberType>(); } foreach (var id in payloads.Select(x => x.Id)) { _idkMap.ClearCache(id); } if (payloads.Any(x => x.ItemType == typeof(IContentType).Name)) // don't try to be clever - refresh all ContentCacheRefresher.RefreshContentTypes(AppCaches); if (payloads.Any(x => x.ItemType == typeof(IMediaType).Name)) // don't try to be clever - refresh all MediaCacheRefresher.RefreshMediaTypes(AppCaches); if (payloads.Any(x => x.ItemType == typeof(IMemberType).Name)) // don't try to be clever - refresh all MemberCacheRefresher.RefreshMemberTypes(AppCaches); // we have to refresh models before we notify the published snapshot // service of changes, else factories may try to rebuild models while // we are using the database to load content into caches _publishedModelFactory.WithSafeLiveFactory(() => _publishedSnapshotService.Notify(payloads)); // now we can trigger the event base.Refresh(payloads); } public override void RefreshAll() { throw new NotSupportedException(); } public override void Refresh(int id) { throw new NotSupportedException(); } public override void Refresh(Guid id) { throw new NotSupportedException(); } public override void Remove(int id) { throw new NotSupportedException(); } #endregion #region Json public class JsonPayload { public JsonPayload(string itemType, int id, ContentTypeChangeTypes changeTypes) { ItemType = itemType; Id = id; ChangeTypes = changeTypes; } public string ItemType { get; } public int Id { get; } public ContentTypeChangeTypes ChangeTypes { get; } } #endregion } }
32.75
174
0.614279
[ "MIT" ]
AndersBrohus/Umbraco-CMS
src/Umbraco.Web/Cache/ContentTypeCacheRefresher.cs
4,456
C#
using System.Text.RegularExpressions; namespace WebApiContrib.Formatting.Jsonp { public static class CallbackValidator { private static readonly Regex JsonpCallbackFormat = new Regex(@"[^0-9a-zA-Z\$_\.]|^(abstract|boolean|break|byte|case|catch|char|class|const|continue|debugger|default|delete|do|double|else|enum|export|extends|false|final|finally|float|for|function|goto|if|implements|import|in|instanceof|int|interface|long|native|new|null|package|private|protected|public|return|short|static|super|switch|synchronized|this|throw|throws|transient|true|try|typeof|var|volatile|void|while|with|NaN|Infinity|undefined)$"); public static bool IsValid(string callback) { return !JsonpCallbackFormat.IsMatch(callback); } } }
52.066667
509
0.758003
[ "MIT" ]
WebApiContrib/WebApiContrib.Formatting.Jsonp
src/WebApiContrib.Formatting.Jsonp/CallbackValidator.cs
783
C#
using System.Text.Json.Serialization; namespace Essensoft.AspNetCore.Payment.Alipay.Domain { /// <summary> /// AssetDeliveryItem Data Structure. /// </summary> public class AssetDeliveryItem : AlipayObject { /// <summary> /// SEND - 发货指令(执行向目的地进行发货动作) , RECEIVE - 收货指令(执行从来源地进行收货动作) /// </summary> [JsonPropertyName("action_type")] public string ActionType { get; set; } /// <summary> /// 配送数量 /// </summary> [JsonPropertyName("amount")] public long Amount { get; set; } /// <summary> /// 订单申请日期, 格式: yyyy-MM-dd HH:mm:ss /// </summary> [JsonPropertyName("apply_order_date")] public string ApplyOrderDate { get; set; } /// <summary> /// 申请单id /// </summary> [JsonPropertyName("apply_order_id")] public string ApplyOrderId { get; set; } /// <summary> /// 配送订单唯一Id /// </summary> [JsonPropertyName("assign_item_id")] public string AssignItemId { get; set; } /// <summary> /// 支付宝内部的配送流水号, 可供物料商和物流商用于对账. /// </summary> [JsonPropertyName("assign_out_order_id")] public string AssignOutOrderId { get; set; } /// <summary> /// 物料渠道标识 /// </summary> [JsonPropertyName("biz_tag")] public string BizTag { get; set; } /// <summary> /// 用于线下供应商区分业务流程,目前采用双方约定方 /// </summary> [JsonPropertyName("biz_type")] public string BizType { get; set; } /// <summary> /// 提供给物流商清关所用信息 /// </summary> [JsonPropertyName("custom_clearance")] public CCInfo CustomClearance { get; set; } /// <summary> /// 配送指令单据明细ID /// </summary> [JsonPropertyName("delivery_assign_order_item_id")] public string DeliveryAssignOrderItemId { get; set; } /// <summary> /// 送货单号 /// </summary> [JsonPropertyName("delivery_process_no")] public string DeliveryProcessNo { get; set; } /// <summary> /// 调拨指令承运方pid /// </summary> [JsonPropertyName("delivery_process_supplier_id")] public string DeliveryProcessSupplierId { get; set; } /// <summary> /// 调拨承运方供应商名称 /// </summary> [JsonPropertyName("delivery_process_supplier_name")] public string DeliveryProcessSupplierName { get; set; } /// <summary> /// 发送地址 /// </summary> [JsonPropertyName("from_address")] public AssetDeliveryAddress FromAddress { get; set; } /// <summary> /// 配送指令生成日期, 格式:yyyy-MM-dd HH:mm:ss /// </summary> [JsonPropertyName("gmt_assign")] public string GmtAssign { get; set; } /// <summary> /// 物料id /// </summary> [JsonPropertyName("item_id")] public string ItemId { get; set; } /// <summary> /// 物料名称 /// </summary> [JsonPropertyName("item_name")] public string ItemName { get; set; } /// <summary> /// 物流单信息 /// </summary> [JsonPropertyName("logistics_info")] public LogisticsInfo LogisticsInfo { get; set; } /// <summary> /// 备注 /// </summary> [JsonPropertyName("memo")] public string Memo { get; set; } /// <summary> /// 公司主体代码 /// </summary> [JsonPropertyName("ou_code")] public string OuCode { get; set; } /// <summary> /// 公司主体名 /// </summary> [JsonPropertyName("ou_name")] public string OuName { get; set; } /// <summary> /// 外部业务单号,例如淘宝订单号 /// </summary> [JsonPropertyName("out_biz_no")] public string OutBizNo { get; set; } /// <summary> /// 1. 如果该物料是套组的子物料, 那么该值为套组物料id; 2, 其他情况和物料id(即, item_id)一致或者为空. /// </summary> [JsonPropertyName("parent_item_id")] public string ParentItemId { get; set; } /// <summary> /// 面单信息 /// </summary> [JsonPropertyName("print_data")] public string PrintData { get; set; } /// <summary> /// 生产调拨对应的生产指令. /// </summary> [JsonPropertyName("produce_order_item_id")] public string ProduceOrderItemId { get; set; } /// <summary> /// TO_CUSTOMER : 到客户的配送指令; INTERIM : 中转配送指令. 可选值详见openApi文档. /// </summary> [JsonPropertyName("record_type")] public string RecordType { get; set; } /// <summary> /// 对应供应商pid /// </summary> [JsonPropertyName("supplier_id")] public string SupplierId { get; set; } /// <summary> /// 对应供应商名称 /// </summary> [JsonPropertyName("supplier_name")] public string SupplierName { get; set; } /// <summary> /// 接收地址(目的地址) /// </summary> [JsonPropertyName("to_address")] public AssetDeliveryAddress ToAddress { get; set; } } }
27.708108
74
0.526141
[ "MIT" ]
Msy1989/payment
src/Essensoft.AspNetCore.Payment.Alipay/Domain/AssetDeliveryItem.cs
5,712
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the chime-2018-05-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.Chime.Model { /// <summary> /// Container for the parameters to the GetVoiceConnectorProxy operation. /// Gets the proxy configuration details for the specified Amazon Chime Voice Connector. /// </summary> public partial class GetVoiceConnectorProxyRequest : AmazonChimeRequest { private string _voiceConnectorId; /// <summary> /// Gets and sets the property VoiceConnectorId. /// <para> /// The Amazon Chime voice connector ID. /// </para> /// </summary> [AWSProperty(Required=true, Min=1, Max=128)] public string VoiceConnectorId { get { return this._voiceConnectorId; } set { this._voiceConnectorId = value; } } // Check to see if VoiceConnectorId property is set internal bool IsSetVoiceConnectorId() { return this._voiceConnectorId != null; } } }
31.101695
103
0.673569
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/Chime/Generated/Model/GetVoiceConnectorProxyRequest.cs
1,835
C#
namespace SharpMusicPlayerDemo.Models { public class TimeStretchProfile { public string Id { get; set; } public string Description { get; set; } public bool UseAAFilter { get; set; } public int AAFilterLength { get; set; } public int Overlap { get; set; } public int Sequence { get; set; } public int SeekWindow { get; set; } public override string ToString() { return Description; } } }
24.75
47
0.573737
[ "MIT" ]
Milkitic/SharpMusicPlayerDemo
Models/TimeStretchProfile.cs
497
C#
using HN.Services; namespace HN.Controls.ImageEx.Core.Tests.Services { public class TestDesignModeService : IDesignModeService { public bool IsInDesignMode => false; } }
19.2
59
0.713542
[ "MIT" ]
h82258652/HN.Controls.ImageEx
test/HN.Controls.ImageEx.Core.Tests/Services/TestDesignModeService.cs
194
C#
using System; using System.Xml.Serialization; using Newtonsoft.Json; namespace Essensoft.AspNetCore.Payment.Alipay.Domain { /// <summary> /// DeliverInfo Data Structure. /// </summary> [Serializable] public class DeliverInfo : AlipayObject { /// <summary> /// 保单寄送地址的住址 /// </summary> [JsonProperty("recipients_address")] [XmlElement("recipients_address")] public string RecipientsAddress { get; set; } /// <summary> /// 配送地址行政区划代码 /// </summary> [JsonProperty("recipients_address_code")] [XmlElement("recipients_address_code")] public string RecipientsAddressCode { get; set; } /// <summary> /// 收件人姓名 /// </summary> [JsonProperty("recipients_name")] [XmlElement("recipients_name")] public string RecipientsName { get; set; } /// <summary> /// 收件人电话 /// </summary> [JsonProperty("recipients_phone")] [XmlElement("recipients_phone")] public string RecipientsPhone { get; set; } } }
26.333333
57
0.582278
[ "MIT" ]
AkonCoder/Payment
src/Essensoft.AspNetCore.Payment.Alipay/Domain/DeliverInfo.cs
1,164
C#
using AppDynamics.Dexter.ReportObjects; using CsvHelper.Configuration; namespace AppDynamics.Dexter.ReportObjectMaps { public class WEBPageToBusinessTransactionReportMap : ClassMap<WEBPageToBusinessTransaction> { public WEBPageToBusinessTransactionReportMap() { int i = 0; Map(m => m.Controller).Index(i); i++; Map(m => m.ApplicationName).Index(i); i++; Map(m => m.PageType).Index(i); i++; Map(m => m.PageName).Index(i); i++; Map(m => m.TierName).Index(i); i++; Map(m => m.BTName).Index(i); i++; Map(m => m.BTType).Index(i); i++; Map(m => m.ART).Index(i); i++; Map(m => m.ARTRange).Index(i); i++; Map(m => m.Calls).Index(i); i++; Map(m => m.CPM).Index(i); i++; Map(m => m.HasActivity).Index(i); i++; EPPlusCSVHelper.setISO8601DateFormat(Map(m => m.From), i); i++; EPPlusCSVHelper.setISO8601DateFormat(Map(m => m.To), i); i++; EPPlusCSVHelper.setISO8601DateFormat(Map(m => m.FromUtc), i); i++; EPPlusCSVHelper.setISO8601DateFormat(Map(m => m.ToUtc), i); i++; Map(m => m.Duration).Index(i); i++; Map(m => m.ApplicationID).Index(i); i++; Map(m => m.PageID).Index(i); i++; Map(m => m.TierID).Index(i); i++; Map(m => m.BTID).Index(i); i++; Map(m => m.ControllerLink).Index(i); i++; Map(m => m.ApplicationLink).Index(i); i++; } } }
36.232558
95
0.517972
[ "Apache-2.0" ]
Appdynamics/AppDynamics.DEXTER
ReportObjects/EntityWEB/Maps/WEBPageToBusinessTransactionReportMap.cs
1,560
C#
using Microsoft.Extensions.DependencyInjection; using System; namespace ConfigMgmt { public static class TheStartup { public static void ConfigureServices(IServiceCollection services) { services.AddHttpClient<IBadgeApiClient, BadgeApiClient>(); services.AddSingleton(RemotingClient.CreateClientAppService()); services.AddSingleton(RemotingClient.CreateBizSystemAppService()); services.AddSingleton(RemotingClient.CreateWorkbenchAppService()); services.AddScoped<Func<Guid, IUserSettingAppService>>(u => RemotingClient.CreateUserSettingAppService); services.AddScoped<Func<Guid, IUserFavoriteAppService>>(u => RemotingClient.CreateUserFavoriteAppService); } } }
35.181818
118
0.72739
[ "MIT" ]
appsonsf/FabricEAP
src/ConfigMgmtApi/TheStartup.cs
776
C#
using System.Net.Sockets; using System.Text; namespace core.BusinessEntityCollection { public class ClientState { public Socket Socket { get; set; } public ClientBuffer ClientBuffer { get; set; } public StringBuilder Data { get; set; } } }
17.625
54
0.652482
[ "Unlicense" ]
kartalm/chatService
chatService/core/BusinessEntityCollection/ClientState.cs
284
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Zadatak1 { class Program { static void Main(string[] args) { Orkestar orkestar = new Orkestar(); try { orkestar.DodajInstrument(1, new Violina("Violinista Jedan")); // nestane orkestar.DodajInstrument(2, new Violina("Violinista Dva")); orkestar.DodajInstrument(11, new Kontrabas("Kontrabas-ista Jedan")); orkestar.DodajInstrument(12, new Kontrabas("Kontrabas-ista Dva")); orkestar.DodajInstrument(21, new Frula("Frulas Jedan")); orkestar.DodajInstrument(22, new Frula("Frulas Dva")); // nestane orkestar.DodajInstrument(31, new Saksofon("Saksofon-ista Jedan")); orkestar.DodajInstrument(32, new Saksofon("Saksofon-ista Dva")); orkestar.DodajInstrument(33, new Saksofon("Frulas Jedan")); Console.WriteLine(orkestar.Simfonija()); orkestar.ObrisiInstrument(22); orkestar.ObrisiInstrument("Violinista Jedan"); Console.WriteLine(orkestar.Simfonija()); Instrument i = orkestar.PronadjiInstrument(31); Console.WriteLine(i); Console.WriteLine("Tip > " + i.Tip.ToString()); Console.WriteLine("Muzicar > " + i.Muzicar + "\n"); List<Instrument> ii = orkestar.PronadjiInstrumente("Frulas Jedan").ToList(); foreach (var item in ii) { Console.WriteLine(item); Console.WriteLine("Tip > " + item.Tip.ToString()); Console.WriteLine("Muzicar > " + item.Muzicar + "\n"); } foreach (var item in typeof(InstrumentTip).GetEnumValues()) { Console.WriteLine("Instrumenata tipa {0} ima {1}", item.ToString(), orkestar.BrojInstrumenataPoTipu((InstrumentTip)item)); } Console.WriteLine(); foreach (var item in typeof(InstrumentTip).GetEnumValues()) { List<Instrument> list = orkestar.PronadjiInstrumentePoTipu((InstrumentTip)item).ToList(); if (list.Count > 0) { Console.WriteLine("Tip {0} sviraju : ", item.ToString()); foreach (var inst in list) { Console.WriteLine("Muzicar > " + inst.Muzicar); } } else { Console.WriteLine("Niko ne svira {0}", item.ToString()); } } Console.WriteLine(); Type[] types = { typeof(Violina), typeof(Kontrabas), typeof(Frula), typeof(Saksofon) }; foreach (Type x in types) { Console.WriteLine("Broj {0} : {1}", x.Name, typeof(Orkestar).GetMethod("BrojInstrumenata").MakeGenericMethod(x).Invoke(orkestar, new object[] { })); } } catch (Exception e) { Console.WriteLine("Desila se greska."); Console.WriteLine("Poruka >> " + e.Message); Console.WriteLine("Pracenje >> " + e.StackTrace); } Console.ReadKey(true); } } }
41.83908
169
0.498077
[ "MIT" ]
astrihale/NTP4
prvi-blok/Zadatak1/Zadatak1/Program.cs
3,642
C#
using System.Collections.ObjectModel; namespace ApiRest.Areas.HelpPage.ModelDescriptions { public class ComplexTypeModelDescription : ModelDescription { public ComplexTypeModelDescription() { Properties = new Collection<ParameterDescription>(); } public Collection<ParameterDescription> Properties { get; private set; } } }
28.142857
81
0.680203
[ "Unlicense" ]
manutres/oesia
ApiRest/Areas/HelpPage/ModelDescriptions/ComplexTypeModelDescription.cs
394
C#
using System.Reflection; namespace Amazon.JSII.Runtime.Services { internal sealed class JsiiRuntimeProvider : IJsiiRuntimeProvider { private const string ENTRYPOINT = "jsii-runtime.js"; public JsiiRuntimeProvider(IResourceExtractor resourceExtractor) { string[] files = { ENTRYPOINT, ENTRYPOINT + ".map", "mappings.wasm" }; // deploy embedded resources to the temp directory var assembly = Assembly.GetExecutingAssembly(); foreach (var name in files) { var resourceName = "Amazon.JSII.Runtime.jsii_runtime." + name; var path = resourceExtractor.ExtractResource(assembly, resourceName, "jsii-runtime", name); if (name == ENTRYPOINT) { JsiiRuntimePath = path; } } } public string? JsiiRuntimePath { get; } } }
31.266667
107
0.584222
[ "Apache-2.0" ]
NGL321/jsii
packages/@jsii/dotnet-runtime/src/Amazon.JSII.Runtime/Services/JsiiRuntimeProvider.cs
940
C#
using UnityEngine; using System.Collections; using Invector.CharacterController.TopDownShooter; public class vShooterTopDownCursor : MonoBehaviour { private vTopDownShooterInput shooter; public GameObject sprite; public LineRenderer lineRender; void Start() { shooter = FindObjectOfType<vTopDownShooterInput>(); } void FixedUpdate() { if (shooter) { if (sprite) { if (shooter.isAiming && !sprite.gameObject.activeSelf) sprite.gameObject.SetActive(true); else if (!shooter.isAiming && sprite.gameObject.activeSelf) sprite.gameObject.SetActive(false); } transform.position = shooter.aimPosition; var dir = shooter.transform.position - shooter.aimPosition; dir.y = 0; if (dir != Vector3.zero) { transform.rotation = Quaternion.LookRotation(dir); if (lineRender) { lineRender.SetPosition(0, shooter.topDownController.lookPos); lineRender.SetPosition(1, shooter.aimPosition); if (shooter.isAiming && !lineRender.enabled) lineRender.enabled = true; else if (!shooter.isAiming && lineRender.enabled) lineRender.enabled = false; } } } } }
31.265306
82
0.530026
[ "MIT" ]
FR98/ProyectoJuegosUVG
Assets/Invector-3rdPersonController/Shooter/Scripts/Examples/TopDownShooter/TopDownCursor/vShooterTopDownCursor.cs
1,534
C#
using System; using System.IO; using System.Text; namespace TextTableFormatter.ConsoleApp { class Program { static void Main() { // 1. BASIC TABLE EXAMPLE var basicTable = new TextTable(3); basicTable.AddCell("Artist"); basicTable.AddCell("Album"); basicTable.AddCell("Year"); basicTable.AddCell("Jamiroquai"); basicTable.AddCell("Emergency on Planet Earth"); basicTable.AddCell("1993"); basicTable.AddCell("Jamiroquai"); basicTable.AddCell("The Return of the Space Cowboy"); basicTable.AddCell("1994"); Console.WriteLine(basicTable.Render()); // +----------+-------------------------------+-----+ // |Artist |Album |Year| // +----------+-------------------------------+-----+ // |Jamiroquai|Emergency on Planet Earth |1993| // |Jamiroquai|The Return of the Space Cowboy|1994| // +----------+-------------------------------+-----+ // 2. ADVANCED TABLE EXAMPLE var numberStyleAdvancedTable = new CellStyle(CellHorizontalAlignment.Right); var advancedTable = new TextTable(3, TableBordersStyle.DESIGN_FORMAL, TableVisibleBorders.SURROUND_HEADER_FOOTER_AND_COLUMNS); advancedTable.SetColumnWidthRange(0, 6, 14); advancedTable.SetColumnWidthRange(1, 4, 12); advancedTable.SetColumnWidthRange(2, 4, 12); advancedTable.AddCell("Region"); advancedTable.AddCell("Orders", numberStyleAdvancedTable); advancedTable.AddCell("Sales", numberStyleAdvancedTable); advancedTable.AddCell("North"); advancedTable.AddCell("6,345", numberStyleAdvancedTable); advancedTable.AddCell("$87.230", numberStyleAdvancedTable); advancedTable.AddCell("Center"); advancedTable.AddCell("837", numberStyleAdvancedTable); advancedTable.AddCell("$12.855", numberStyleAdvancedTable); advancedTable.AddCell("South"); advancedTable.AddCell("5,344", numberStyleAdvancedTable); advancedTable.AddCell("$72.561", numberStyleAdvancedTable); advancedTable.AddCell("Total", numberStyleAdvancedTable, 2); advancedTable.AddCell("$172.646", numberStyleAdvancedTable); Console.WriteLine(advancedTable.Render()); // ====================== // Region Orders Sales // ------ ------ -------- // North 6,345 $87.230 // Center 837 $12.855 // South 5,344 $72.561 // ------ ------ -------- // Total $172.646 // ====================== // 3. FANCY TABLE EXAMPLE var numberStyleFancyTable = new CellStyle(CellHorizontalAlignment.Right); var fancyTable = new TextTable(3, TableBordersStyle.DESIGN_PAPYRUS, TableVisibleBorders.SURROUND_HEADER_FOOTER_AND_COLUMNS); fancyTable.AddCell("Region"); fancyTable.AddCell("Orders", numberStyleFancyTable); fancyTable.AddCell("Sales", numberStyleFancyTable); fancyTable.AddCell("North"); fancyTable.AddCell("6,345", numberStyleFancyTable); fancyTable.AddCell("$87.230", numberStyleFancyTable); fancyTable.AddCell("Center"); fancyTable.AddCell("837", numberStyleFancyTable); fancyTable.AddCell("$12.855", numberStyleFancyTable); fancyTable.AddCell("South"); fancyTable.AddCell("5,344", numberStyleFancyTable); fancyTable.AddCell("$72.561", numberStyleFancyTable); fancyTable.AddCell("Total", numberStyleFancyTable, 2); fancyTable.AddCell("$172.646", numberStyleFancyTable); Console.WriteLine(fancyTable.Render()); // o~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~o // ) Region Orders Sales ( // ) ~~~~~~ ~~~~~~ ~~~~~~~~ ( // ) North 6,345 $87.230 ( // ) Center 837 $12.855 ( // ) South 5,344 $72.561 ( // ) ~~~~~~ ~~~~~~ ~~~~~~~~ ( // ) Total $172.646 ( // o~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~o // 4. UNICODE TABLE EXAMPLE var numberStyleUnicodeTable = new CellStyle(CellHorizontalAlignment.Right); var unicodeTable = new TextTable(3, TableBordersStyle.UNICODE_BOX_DOUBLE_BORDER_WIDE, TableVisibleBorders.SURROUND_HEADER_FOOTER_AND_COLUMNS, true); unicodeTable.AddCell("Region"); unicodeTable.AddCell("Orders", numberStyleUnicodeTable); unicodeTable.AddCell("Sales", numberStyleUnicodeTable); unicodeTable.AddCell("North"); unicodeTable.AddCell("6,345", numberStyleUnicodeTable); unicodeTable.AddCell("$87.230", numberStyleUnicodeTable); unicodeTable.AddCell("Center"); unicodeTable.AddCell("837", numberStyleUnicodeTable); unicodeTable.AddCell("$12.855", numberStyleUnicodeTable); unicodeTable.AddCell("South"); unicodeTable.AddCell("5,344", numberStyleUnicodeTable); unicodeTable.AddCell("$72.561", numberStyleUnicodeTable); unicodeTable.AddCell("Total", numberStyleUnicodeTable, 2); unicodeTable.AddCell("$172.646", numberStyleUnicodeTable); var unicodeTableStringArray = unicodeTable.RenderAsStringArray(); var sb = new StringBuilder("<html><body><pre>"); foreach (string line in unicodeTableStringArray) { sb.Append(line); sb.Append("<br>"); } sb.Append("</pre></html>"); File.WriteAllText("unicode.html", sb.ToString(), Encoding.UTF8); // unicode.html // ╔════════╤════════╤══════════╗ // ║ Region │ Orders │ Sales ║ // ╟────────┼────────┼──────────╢ // ║ North │ 6,345 │ $87.230 ║ // ║ Center │ 837 │ $12.855 ║ // ║ South │ 5,344 │ $72.561 ║ // ╟────────┴────────┼──────────╢ // ║ Total │ $172.646 ║ // ╚═════════════════╧══════════╝ } } }
37.357143
154
0.593603
[ "Apache-2.0" ]
dsantarelli/TextTableFormatter.NET
TextTableFormatter.ConsoleApp/Program.cs
6,033
C#
// This file was automatically generated and may be regenerated at any // time. To ensure any changes are retained, modify the tool with any segment/component/group/field name // or type changes. namespace Machete.HL7Schema.V26.Maps { using V26; /// <summary> /// OPL_O37_PATIENT (GroupMap) - /// </summary> public class OPL_O37_PATIENTMap : HL7V26LayoutMap<OPL_O37_PATIENT> { public OPL_O37_PATIENTMap() { Segment(x => x.PID, 0, x => x.Required = true); Segment(x => x.PD1, 1); Segment(x => x.OBX, 2); Layout(x => x.Insurance, 3); Segment(x => x.AL1, 4); } } }
29.695652
104
0.581259
[ "Apache-2.0" ]
ahives/Machete
src/Machete.HL7Schema/V26/Groups/Maps/OPL_O37_PATIENTMap.cs
683
C#
namespace TraktNet.Objects.Get.Tests.History.Json.Writer { using FluentAssertions; using Newtonsoft.Json; using System; using System.IO; using System.Threading.Tasks; using Trakt.NET.Tests.Utility.Traits; using TraktNet.Enums; using TraktNet.Extensions; using TraktNet.Objects.Get.Episodes; using TraktNet.Objects.Get.History; using TraktNet.Objects.Get.History.Json.Writer; using TraktNet.Objects.Get.Shows; using Xunit; [Category("Objects.Get.History.JsonWriter")] public partial class HistoryItemObjectJsonWriter_Tests { private static readonly DateTime WATCHED_AT = DateTime.UtcNow; [Fact] public async Task Test_HistoryItemObjectJsonWriter_Episode_WriteObject_JsonWriter_Exceptions() { var traktJsonWriter = new HistoryItemObjectJsonWriter(); ITraktHistoryItem traktHistoryItem = new TraktHistoryItem(); Func<Task> action = () => traktJsonWriter.WriteObjectAsync(default(JsonTextWriter), traktHistoryItem); await action.Should().ThrowAsync<ArgumentNullException>(); } [Fact] public async Task Test_HistoryItemObjectJsonWriter_Episode_WriteObject_JsonWriter_Only_ID_Property() { ITraktHistoryItem traktHistoryItem = new TraktHistoryItem { Id = 1982347UL }; using (var stringWriter = new StringWriter()) using (var jsonWriter = new JsonTextWriter(stringWriter)) { var traktJsonWriter = new HistoryItemObjectJsonWriter(); await traktJsonWriter.WriteObjectAsync(jsonWriter, traktHistoryItem); stringWriter.ToString().Should().Be(@"{""id"":1982347}"); } } [Fact] public async Task Test_HistoryItemObjectJsonWriter_Episode_WriteObject_JsonWriter_Only_WatchedAt_Property() { ITraktHistoryItem traktHistoryItem = new TraktHistoryItem { WatchedAt = WATCHED_AT }; using (var stringWriter = new StringWriter()) using (var jsonWriter = new JsonTextWriter(stringWriter)) { var traktJsonWriter = new HistoryItemObjectJsonWriter(); await traktJsonWriter.WriteObjectAsync(jsonWriter, traktHistoryItem); stringWriter.ToString().Should().Be($"{{\"id\":0,\"watched_at\":\"{WATCHED_AT.ToTraktLongDateTimeString()}\"}}"); } } [Fact] public async Task Test_HistoryItemObjectJsonWriter_Episode_WriteObject_JsonWriter_Only_Action_Property() { ITraktHistoryItem traktHistoryItem = new TraktHistoryItem { Action = TraktHistoryActionType.Checkin }; using (var stringWriter = new StringWriter()) using (var jsonWriter = new JsonTextWriter(stringWriter)) { var traktJsonWriter = new HistoryItemObjectJsonWriter(); await traktJsonWriter.WriteObjectAsync(jsonWriter, traktHistoryItem); stringWriter.ToString().Should().Be(@"{""id"":0,""action"":""checkin""}"); } } [Fact] public async Task Test_HistoryItemObjectJsonWriter_Episode_WriteObject_JsonWriter_Only_Type_Property() { ITraktHistoryItem traktHistoryItem = new TraktHistoryItem { Type = TraktSyncItemType.Episode }; using (var stringWriter = new StringWriter()) using (var jsonWriter = new JsonTextWriter(stringWriter)) { var traktJsonWriter = new HistoryItemObjectJsonWriter(); await traktJsonWriter.WriteObjectAsync(jsonWriter, traktHistoryItem); stringWriter.ToString().Should().Be(@"{""id"":0,""type"":""episode""}"); } } [Fact] public async Task Test_HistoryItemObjectJsonWriter_Episode_WriteObject_JsonWriter_Only_Episode_Property() { ITraktHistoryItem traktHistoryItem = new TraktHistoryItem { Episode = new TraktEpisode { SeasonNumber = 1, Number = 1, Title = "Winter Is Coming", Ids = new TraktEpisodeIds { Trakt = 73640U, Tvdb = 3254641U, Imdb = "tt1480055", Tmdb = 63056U, TvRage = 1065008299U } } }; using (var stringWriter = new StringWriter()) using (var jsonWriter = new JsonTextWriter(stringWriter)) { var traktJsonWriter = new HistoryItemObjectJsonWriter(); await traktJsonWriter.WriteObjectAsync(jsonWriter, traktHistoryItem); stringWriter.ToString().Should().Be(@"{""id"":0,""episode"":{""season"":1,""number"":1,""title"":""Winter Is Coming""," + @"""ids"":{""trakt"":73640,""tvdb"":3254641,""imdb"":""tt1480055"",""tmdb"":63056,""tvrage"":1065008299}}}"); } } [Fact] public async Task Test_HistoryItemObjectJsonWriter_Episode_WriteObject_JsonWriter_Only_Show_Property() { ITraktHistoryItem traktHistoryItem = new TraktHistoryItem { Show = new TraktShow { Title = "Game of Thrones", Year = 2011, Ids = new TraktShowIds { Trakt = 1390U, Slug = "game-of-thrones", Tvdb = 121361U, Imdb = "tt0944947", Tmdb = 1399U, TvRage = 24493U } } }; using (var stringWriter = new StringWriter()) using (var jsonWriter = new JsonTextWriter(stringWriter)) { var traktJsonWriter = new HistoryItemObjectJsonWriter(); await traktJsonWriter.WriteObjectAsync(jsonWriter, traktHistoryItem); stringWriter.ToString().Should().Be(@"{""id"":0,""show"":{""title"":""Game of Thrones"",""year"":2011," + @"""ids"":{""trakt"":1390,""slug"":""game-of-thrones"",""tvdb"":121361," + @"""imdb"":""tt0944947"",""tmdb"":1399,""tvrage"":24493}}}"); } } [Fact] public async Task Test_HistoryItemObjectJsonWriter_Episode_WriteObject_JsonWriter_Complete() { ITraktHistoryItem traktHistoryItem = new TraktHistoryItem { Id = 1982347UL, WatchedAt = WATCHED_AT, Action = TraktHistoryActionType.Checkin, Type = TraktSyncItemType.Episode, Episode = new TraktEpisode { SeasonNumber = 1, Number = 1, Title = "Winter Is Coming", Ids = new TraktEpisodeIds { Trakt = 73640U, Tvdb = 3254641U, Imdb = "tt1480055", Tmdb = 63056U, TvRage = 1065008299U } }, Show = new TraktShow { Title = "Game of Thrones", Year = 2011, Ids = new TraktShowIds { Trakt = 1390U, Slug = "game-of-thrones", Tvdb = 121361U, Imdb = "tt0944947", Tmdb = 1399U, TvRage = 24493U } } }; using (var stringWriter = new StringWriter()) using (var jsonWriter = new JsonTextWriter(stringWriter)) { var traktJsonWriter = new HistoryItemObjectJsonWriter(); await traktJsonWriter.WriteObjectAsync(jsonWriter, traktHistoryItem); stringWriter.ToString().Should().Be(@"{""id"":1982347," + $"\"watched_at\":\"{WATCHED_AT.ToTraktLongDateTimeString()}\"," + @"""action"":""checkin"",""type"":""episode""," + @"""show"":{""title"":""Game of Thrones"",""year"":2011," + @"""ids"":{""trakt"":1390,""slug"":""game-of-thrones"",""tvdb"":121361," + @"""imdb"":""tt0944947"",""tmdb"":1399,""tvrage"":24493}}," + @"""episode"":{""season"":1,""number"":1,""title"":""Winter Is Coming""," + @"""ids"":{""trakt"":73640,""tvdb"":3254641,""imdb"":""tt1480055"",""tmdb"":63056,""tvrage"":1065008299}}}"); } } } }
43.03211
161
0.504957
[ "MIT" ]
henrikfroehling/Trakt.NET
Source/Tests/Trakt.NET.Objects.Get.Tests/History/Json/Writer/HistoryItemObjectJsonWriter/HistoryItemObjectJsonWriter_Episode_JsonWriter_Tests.cs
9,383
C#
using My9GAG.Logic.Client; using My9GAG.Logic.DownloadManager; using My9GAG.Logic.PageNavigator; using My9GAG.Models.Comment; using My9GAG.Models.Post; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using System.Windows.Input; using Xamarin.Essentials; using Xamarin.Forms; namespace My9GAG.ViewModels { public class PostsPageViewModel : ViewModelBase { #region Constructors public PostsPageViewModel(IClientService clientService, IPageNavigator pageNavigator) { _clientService = clientService; _pageNavigator = pageNavigator; _currentCategory = PostCategory.Hot; Posts = new ObservableCollection<Post>(); InitCommands(); GetPostsAsync(_currentCategory); } #endregion #region Properties public ObservableCollection<Post> Posts { get { return _posts; } private set { SetProperty(ref _posts, value); } } public bool IsNotLoggedIn { get { return _isNotLoggedIn; } set { if (SetProperty(ref _isNotLoggedIn, value)) { Device.BeginInvokeOnMainThread(() => UpdateCommands()); } } } public bool ArePostsLoading { get; set; } public Post LastPost { get { return _lastPost; } set { SetProperty(ref _lastPost, value); } } public Post CurrentPost { get { return _currentPost; } set { LastPost?.PostMedia?.Pause(); LastPost = CurrentPost; if (SetProperty(ref _currentPost, value)) { int currentPosition = Posts.IndexOf(value); int postsLeft = Posts.Count - currentPosition - 1; bool needToLoadMore = postsLeft <= NUMBER_OF_POSTS_BEFORE_LOADING_MORE; Debug.WriteLine($"Position:{currentPosition} Left:{postsLeft}/{Posts.Count} Id:{CurrentPost?.Id} Last:{LastPost?.Id} Name:{CurrentPost.Title}"); if (Posts.Count > 0 && needToLoadMore && !ArePostsLoading) { GetMorePostsAsync(); } } } } #endregion #region Methods public async void GetPostsAsync(PostCategory postCategory) { switch (postCategory) { case PostCategory.Hot: StartWorkIndication(ViewModelConstants.LOADING_HOT_MESSAGE); break; case PostCategory.Trending: StartWorkIndication(ViewModelConstants.LOADING_TRENDING_MESSAGE); break; case PostCategory.Vote: StartWorkIndication(ViewModelConstants.LOADING_FRESH_MESSAGE); break; } ArePostsLoading = true; await Task.Run(async () => { var requestStatus = await _clientService.GetPostsAsync(postCategory, NUMBER_OF_POSTS); if (requestStatus != null && requestStatus.IsSuccessful) { _currentCategory = postCategory; Device.BeginInvokeOnMainThread(() => { Posts.Clear(); Posts = new ObservableCollection<Post>(_clientService.Posts); CurrentPost = Posts.FirstOrDefault(); }); await Task.Delay(ViewModelConstants.GET_POSTS_DELAY); } else { StopWorkIndication(); string message = requestStatus == null ? ViewModelConstants.REQUEST_FAILED_MESSAGE : requestStatus.Message; await ShowMessage(message); } }); ArePostsLoading = false; StopWorkIndication(); } public async void GetMorePostsAsync() { Debug.WriteLine("Getting more posts"); if (Posts.Count < 1) { await ShowMessage(ViewModelConstants.EMPTY_POST_LIST_MESSAGE); return; } ArePostsLoading = true; await Task.Run(async () => { var requestStatus = await _clientService.GetPostsAsync(_currentCategory, NUMBER_OF_POSTS, Posts.Last().Id); if (requestStatus != null && requestStatus.IsSuccessful) { Device.BeginInvokeOnMainThread(() => _clientService.Posts.ForEach(post => Posts.Add(post))); } else { string message = requestStatus == null ? ViewModelConstants.REQUEST_FAILED_MESSAGE : requestStatus.Message; await ShowMessage(message); } }); ArePostsLoading = false; } public async void GetCommentsAsync() { StartWorkIndication(ViewModelConstants.LOADING_COMMENTS); await Task.Run(async () => { var requestStatus = await _clientService.GetCommentsAsync(CurrentPost.Url, CurrentPost.CommentsCount); if (requestStatus != null && requestStatus.IsSuccessful) { var viewModel = new CommentsPageViewModel() { Title = CurrentPost.Title, Comments = new ObservableCollection<Comment>(_clientService.Comments) }; _pageNavigator.GoToCommentsPage(viewModel); } else { await ShowMessage(requestStatus.Message); } }); StopWorkIndication(); } public async void DownloadCurrentPostAsync() { await Task.Run(async () => { string url = CurrentPost.PostMedia.Url; string fileName = GenerateFileName(CurrentPost); var downloadManager = DependencyService.Get<IDownloadManager>(); try { downloadManager.DownloadFile(url, fileName); } catch { await ShowMessage(ViewModelConstants.DOWNLOAD_FAILED_MESSAGE); } }); } public async void OpenInBrowserAsync() { var uri = new Uri(CurrentPost.Url); await Launcher.OpenAsync(uri); } public async void Logout() { IsNotLoggedIn = true; await _clientService.Logout(); _pageNavigator.GoToLoginPage(null, true); } public void SaveState(IDictionary<string, object> dictionary) { dictionary["isNotLoggedIn"] = IsNotLoggedIn; } public void RestoreState(IDictionary<string, object> dictionary) { IsNotLoggedIn = GetDictionaryEntry(dictionary, "isNotLoggedIn", true); } #endregion #region Commands public ICommand LogInCommand { get; protected set; } public ICommand GetHotPostsCommand { get; protected set; } public ICommand GetTrendingPostsCommand { get; protected set; } public ICommand GetFreshPostsCommand { get; protected set; } public ICommand OpenInBrowserCommand { get; protected set; } public ICommand DownloadCommand { get; protected set; } public ICommand CommentsCommand { get; protected set; } public ICommand LogoutCommand { get; protected set; } public ICommand PositionChangedCommand { get; protected set; } #endregion #region Implementation protected void InitCommands() { LogInCommand = new Command( () => { }); GetHotPostsCommand = new Command( () => GetPostsAsync(PostCategory.Hot), () => !IsNotLoggedIn && !IsWorkIndicationVisible); GetTrendingPostsCommand = new Command( () => GetPostsAsync(PostCategory.Trending), () => !IsNotLoggedIn && !IsWorkIndicationVisible); GetFreshPostsCommand = new Command( () => GetPostsAsync(PostCategory.Vote), () => !IsNotLoggedIn && !IsWorkIndicationVisible); OpenInBrowserCommand = new Command( () => OpenInBrowserAsync(), () => !IsNotLoggedIn && !IsWorkIndicationVisible && CurrentPost != null); DownloadCommand = new Command( () => DownloadCurrentPostAsync(), () => !IsNotLoggedIn && !IsWorkIndicationVisible && CurrentPost != null); CommentsCommand = new Command( () => GetCommentsAsync(), () => !IsNotLoggedIn && !IsWorkIndicationVisible && CurrentPost != null); LogoutCommand = new Command( () => Logout(), () => !IsWorkIndicationVisible); _commands = new List<ICommand>() { LogInCommand, GetHotPostsCommand, GetTrendingPostsCommand, GetFreshPostsCommand, OpenInBrowserCommand, DownloadCommand, CommentsCommand, LogoutCommand }; } protected override void UpdateCommands() { foreach (var c in _commands) { if (c is Command command) { command.ChangeCanExecute(); } } } protected T GetDictionaryEntry<T>(IDictionary<string, object> dictionary, string key, T defaultValue) { if (dictionary.ContainsKey(key)) return (T)dictionary[key]; return defaultValue; } private string GenerateFileName(Post post) { string title = post.Title.Trim().Replace(' ', '-').ToLower(); string name = title.Length > MAX_FILE_NAME_LENGTH ? title.Substring(0, MAX_FILE_NAME_LENGTH) : title; string extention = post.PostMedia.Url.Split('.').Last(); return $"{name}.{extention}"; } #endregion #region Fields private readonly IClientService _clientService; private readonly IPageNavigator _pageNavigator; private PostCategory _currentCategory; private ObservableCollection<Post> _posts; private List<ICommand> _commands; private bool _isNotLoggedIn; private Post _lastPost; private Post _currentPost; #endregion #region Constants private const int NUMBER_OF_POSTS = 20; private const int NUMBER_OF_POSTS_BEFORE_LOADING_MORE = 15; private const int MAX_FILE_NAME_LENGTH = 30; #endregion } }
30.81201
164
0.517244
[ "MIT" ]
Rora/My9GAG
My9GAG/My9GAG/ViewModels/PostsPageViewModel.cs
11,803
C#
using FluentAssertions; using foodtruacker.AcceptanceTests.Framework; using foodtruacker.Application.BoundedContexts.UserAccountManagement.Commands; using foodtruacker.Application.Results; using foodtruacker.Domain.BoundedContexts.UserAccountManagement.Aggregates; using foodtruacker.Domain.BoundedContexts.UserAccountManagement.Events; using foodtruacker.Domain.BoundedContexts.UserAccountManagement.ValueObjects; using foodtruacker.SharedKernel; using MediatR; using System; using System.Collections.Generic; using System.Linq; namespace foodtruacker.AcceptanceTests.BoundedContexts.UserAccountManagement { public class When_verifying_a_customer : Specification<Customer, CustomerAccountVerifyCommand, CommandResult> { private readonly Guid _UserId = Guid.NewGuid(); private readonly string _Email = "test@user.com"; private readonly string _PlainPassword = "123456"; private readonly string _Firstname = "Test"; private readonly string _Lastname = "User"; protected override IRequestHandler<CustomerAccountVerifyCommand, CommandResult> CommandHandler() => new CustomerAccountVerifyCommandHandler(MockEventSourcingRepository.Object); protected override ICollection<IDomainEvent> GivenEvents() => new List<IDomainEvent>() { new CustomerAccountCreatedEvent ( userId: _UserId, email: (EmailAddress)EmailAddress.Create(_Email).ValueObject, password: (HashedPassword)HashedPassword.Create(_PlainPassword).ValueObject, name: (UserFullName)UserFullName.Create(_Firstname, _Lastname).ValueObject ) }; protected override CustomerAccountVerifyCommand When() => new CustomerAccountVerifyCommand { UserId = _UserId }; [Then] public void Then_a_CustomerAccountVerifiedEvent_will_be_published() { PublishedEvents.Last().As<CustomerAccountVerifiedEvent>().AggregateId.Should().Be(_UserId); PublishedEvents.Last().As<CustomerAccountVerifiedEvent>().Name.ToString().Should().Be($"{_Firstname} {_Lastname}"); PublishedEvents.Last().As<CustomerAccountVerifiedEvent>().Email.ToString().Should().Be(_Email); PublishedEvents.Last().As<CustomerAccountVerifiedEvent>().Verified.Should().BeTrue(); } } }
44.927273
127
0.707001
[ "MIT" ]
hiiammalte/foodtruacker
foodtruacker.AcceptanceTests/BoundedContexts/UserAccountManagement/When_verifying_a_customer.cs
2,473
C#
using System.Collections.Generic; using NodeCanvas.Framework; using ParadoxNotion.Design; namespace NodeCanvas.Tasks.Actions { [Category("✫ Blackboard/Lists")] public class GetIndexOfElement<T> : ActionTask { [RequiredField] [BlackboardOnly] public BBParameter<List<T>> targetList; public BBParameter<T> targetElement; [BlackboardOnly] public BBParameter<int> saveIndexAs; protected override void OnExecute() { saveIndexAs.value = targetList.value.IndexOf(targetElement.value); EndAction(true); } } }
25.375
78
0.663383
[ "MIT" ]
BlestxVentures/oculus-experiments
Assets/External/ParadoxNotion/NodeCanvas/Tasks/Actions/Blackboard/List Specific/GetIndexOfElement.cs
613
C#
namespace DigitalLearningSolutions.Data.Tests.Services { using DigitalLearningSolutions.Data.Services; using DigitalLearningSolutions.Data.Models; using DigitalLearningSolutions.Data.Tests.Helpers; using NUnit.Framework; using FluentAssertions; public class UnlockDataServiceTests { private UnlockDataService unlockDataService; [SetUp] public void Setup() { var connection = ServiceTestHelper.GetDatabaseConnection(); unlockDataService = new UnlockDataService(connection); } [Test] public void Get_unlock_data_returns_correct_results() { // When const int progressId = 173218; var result = unlockDataService.GetUnlockData(progressId); // Then var expectedUnlockData = new UnlockData { DelegateEmail = "hcta@egviomklw.", DelegateName = "xxxxx xxxxxxxxx", ContactForename = "xxxxx", ContactEmail = "e@1htrnkisv.wa", CourseName = "Office 2013 Essentials for the Workplace - Erin Test 01", CustomisationId = 15853 }; result.Should().BeEquivalentTo(expectedUnlockData); } } }
32.585366
88
0.591317
[ "MIT" ]
FridaTveit/DLSV2
DigitalLearningSolutions.Data.Tests/Services/UnlockDataServiceTests.cs
1,338
C#
namespace Caliburn.Micro { using System; using System.Collections.Generic; using System.Windows; ///<summary> /// A base implementation of <see cref = "IViewAware" /> which is capable of caching views by context. ///</summary> public class ViewAware : PropertyChangedBase, IViewAware { bool cacheViews; static readonly DependencyProperty PreviouslyAttachedProperty = DependencyProperty.RegisterAttached( "PreviouslyAttached", typeof(bool), typeof(ViewAware), null ); /// <summary> /// Indicates whether or not implementors of <see cref="IViewAware"/> should cache their views by default. /// </summary> public static bool CacheViewsByDefault = true; /// <summary> /// The view chache for this instance. /// </summary> protected readonly Dictionary<object, object> Views = new Dictionary<object, object>(); ///<summary> /// Creates an instance of <see cref="ViewAware"/>. ///</summary> public ViewAware() : this(CacheViewsByDefault) {} ///<summary> /// Creates an instance of <see cref="ViewAware"/>. ///</summary> ///<param name="cacheViews">Indicates whether or not this instance maintains a view cache.</param> public ViewAware(bool cacheViews) { CacheViews = cacheViews; } /// <summary> /// Raised when a view is attached. /// </summary> public event EventHandler<ViewAttachedEventArgs> ViewAttached = delegate { }; ///<summary> /// Indicates whether or not this instance maintains a view cache. ///</summary> protected bool CacheViews { get { return cacheViews; } set { cacheViews = value; if(!cacheViews) Views.Clear(); } } void IViewAware.AttachView(object view, object context) { if (CacheViews) { Views[context ?? View.DefaultContext] = view; } var nonGeneratedView = View.GetFirstNonGeneratedView(view); var element = nonGeneratedView as FrameworkElement; if (element != null && !(bool)element.GetValue(PreviouslyAttachedProperty)) { element.SetValue(PreviouslyAttachedProperty, true); View.ExecuteOnLoad(element, (s, e) => OnViewLoaded(s)); } OnViewAttached(nonGeneratedView, context); ViewAttached(this, new ViewAttachedEventArgs { View = nonGeneratedView, Context = context }); } /// <summary> /// Called when a view is attached. /// </summary> /// <param name="view">The view.</param> /// <param name="context">The context in which the view appears.</param> protected internal virtual void OnViewAttached(object view, object context) {} /// <summary> /// Called when an attached view's Loaded event fires. /// </summary> /// <param name = "view"></param> protected internal virtual void OnViewLoaded(object view) {} #if WP71 /// <summary> /// Called the first time the page's LayoutUpdated event fires after it is navigated to. /// </summary> /// <param name = "view"></param> protected internal virtual void OnViewReady(object view) { } #endif /// <summary> /// Gets a view previously attached to this instance. /// </summary> /// <param name = "context">The context denoting which view to retrieve.</param> /// <returns>The view.</returns> public virtual object GetView(object context = null) { object view; Views.TryGetValue(context ?? View.DefaultContext, out view); return view; } } }
36.211009
114
0.577654
[ "MIT" ]
victorarias/Caliburn.Micro
src/Caliburn.Micro.Silverlight/ViewAware.cs
3,949
C#
namespace DrawerConsole { partial class Form1 { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.UI_TIM_Render = new System.Windows.Forms.Timer(this.components); this.SuspendLayout(); // // UI_TIM_Render // this.UI_TIM_Render.Enabled = true; this.UI_TIM_Render.Interval = 1; this.UI_TIM_Render.Tick += new System.EventHandler(this.UI_TIM_Render_Tick); // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(284, 262); this.Name = "Form1"; this.Text = "Form1"; this.Load += new System.EventHandler(this.Form1_Load); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Timer UI_TIM_Render; } }
31.932203
107
0.558386
[ "BSD-3-Clause" ]
ISTNAIT/GDIDrawer
DrawerConsole/Form1.Designer.cs
1,886
C#
using Newtonsoft.Json; namespace NadekoBot.Modules.Searches.Common { public class MangaResult { public int Id { get; set; } [JsonProperty("publishing_status")] public string PublishingStatus { get; set; } [JsonProperty("image_url_lge")] public string ImageUrlLge { get; set; } [JsonProperty("title_english")] public string TitleEnglish { get; set; } [JsonProperty("total_chapters")] public int TotalChapters { get; set; } [JsonProperty("total_volumes")] public int TotalVolumes { get; set; } public string Description { get; set; } public string[] Genres { get; set; } [JsonProperty("average_score")] public string AverageScore { get; set; } public string Link => "http://anilist.co/manga/" + Id; public string Synopsis => Description?.Substring(0, Description.Length > 500 ? 500 : Description.Length) + "..."; } }
38.52
121
0.623053
[ "MIT" ]
A-N-NA/NadekoBot
NadekoBot.Core/Modules/Searches/Common/MangaResult.cs
963
C#
#region License and Copyright Notice // Copyright (c) 2010 Ananth B. // All rights reserved. // // The contents of this file are made available under the terms of the // Eclipse Public License v1.0 (the "License") which accompanies this // distribution, and is available at the following URL: // http://www.opensource.org/licenses/eclipse-1.0.php // // Software distributed under the License is distributed on an "AS IS" basis, // WITHOUT WARRANTY OF ANY KIND, either expressed or implied. See the License for // the specific language governing rights and limitations under the License. // // By using this software in any fashion, you are agreeing to be bound by the // terms of the License. #endregion using System; using Brahma.Types; namespace Brahma { public abstract class Buffer<T>: Mem<T>, IDisposable where T: struct, IMem { public abstract void Dispose(); [KernelCallable] public abstract T this[int32 index] { get; set; } public abstract int Length { get; } } }
28.974359
82
0.646903
[ "EPL-1.0" ]
aquavit/Brahma
Source/Brahma/Buffer.cs
1,132
C#
// 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; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using Microsoft.EntityFrameworkCore.Internal; using Microsoft.EntityFrameworkCore.Query.Expressions.Internal; // ReSharper disable SwitchStatementMissingSomeCases // ReSharper disable ForCanBeConvertedToForeach // ReSharper disable LoopCanBeConvertedToQuery namespace Microsoft.EntityFrameworkCore.Query.Internal { /// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public class ExpressionEqualityComparer : IEqualityComparer<Expression> { /// <summary> /// Creates a new <see cref="ExpressionEqualityComparer" />. /// </summary> private ExpressionEqualityComparer() { } /// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public static ExpressionEqualityComparer Instance => InnerExpressionEqualityComparer.Instance; /// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public virtual int GetHashCode(Expression obj) { if (obj == null) { return 0; } unchecked { var hashCode = (int)obj.NodeType; hashCode += (hashCode * 397) ^ obj.Type.GetHashCode(); switch (obj.NodeType) { case ExpressionType.Negate: case ExpressionType.NegateChecked: case ExpressionType.Not: case ExpressionType.Convert: case ExpressionType.ConvertChecked: case ExpressionType.ArrayLength: case ExpressionType.Quote: case ExpressionType.TypeAs: case ExpressionType.UnaryPlus: { var unaryExpression = (UnaryExpression)obj; if (unaryExpression.Method != null) { hashCode += hashCode * 397 ^ unaryExpression.Method.GetHashCode(); } hashCode += (hashCode * 397) ^ GetHashCode(unaryExpression.Operand); break; } case ExpressionType.Add: case ExpressionType.AddChecked: case ExpressionType.Subtract: case ExpressionType.SubtractChecked: case ExpressionType.Multiply: case ExpressionType.MultiplyChecked: case ExpressionType.Divide: case ExpressionType.Modulo: case ExpressionType.And: case ExpressionType.AndAlso: case ExpressionType.Or: case ExpressionType.OrElse: case ExpressionType.LessThan: case ExpressionType.LessThanOrEqual: case ExpressionType.GreaterThan: case ExpressionType.GreaterThanOrEqual: case ExpressionType.Equal: case ExpressionType.NotEqual: case ExpressionType.Coalesce: case ExpressionType.ArrayIndex: case ExpressionType.RightShift: case ExpressionType.LeftShift: case ExpressionType.ExclusiveOr: case ExpressionType.Power: { var binaryExpression = (BinaryExpression)obj; hashCode += (hashCode * 397) ^ GetHashCode(binaryExpression.Left); hashCode += (hashCode * 397) ^ GetHashCode(binaryExpression.Right); break; } case ExpressionType.TypeIs: { var typeBinaryExpression = (TypeBinaryExpression)obj; hashCode += (hashCode * 397) ^ GetHashCode(typeBinaryExpression.Expression); hashCode += (hashCode * 397) ^ typeBinaryExpression.TypeOperand.GetHashCode(); break; } case ExpressionType.Constant: { var constantExpression = (ConstantExpression)obj; if (constantExpression.Value != null && !(constantExpression.Value is IQueryable)) { hashCode += (hashCode * 397) ^ constantExpression.Value.GetHashCode(); } break; } case ExpressionType.Parameter: { var parameterExpression = (ParameterExpression)obj; hashCode += hashCode * 397; // ReSharper disable once ConditionIsAlwaysTrueOrFalse if (parameterExpression.Name != null) { hashCode ^= parameterExpression.Name.GetHashCode(); } break; } case ExpressionType.MemberAccess: { var memberExpression = (MemberExpression)obj; hashCode += (hashCode * 397) ^ memberExpression.Member.GetHashCode(); hashCode += (hashCode * 397) ^ GetHashCode(memberExpression.Expression); break; } case ExpressionType.Call: { var methodCallExpression = (MethodCallExpression)obj; hashCode += (hashCode * 397) ^ methodCallExpression.Method.GetHashCode(); hashCode += (hashCode * 397) ^ GetHashCode(methodCallExpression.Object); hashCode += (hashCode * 397) ^ GetHashCode(methodCallExpression.Arguments); break; } case ExpressionType.Lambda: { var lambdaExpression = (LambdaExpression)obj; hashCode += (hashCode * 397) ^ lambdaExpression.ReturnType.GetHashCode(); hashCode += (hashCode * 397) ^ GetHashCode(lambdaExpression.Body); hashCode += (hashCode * 397) ^ GetHashCode(lambdaExpression.Parameters); break; } case ExpressionType.New: { var newExpression = (NewExpression)obj; hashCode += (hashCode * 397) ^ (newExpression.Constructor?.GetHashCode() ?? 0); if (newExpression.Members != null) { for (var i = 0; i < newExpression.Members.Count; i++) { hashCode += (hashCode * 397) ^ newExpression.Members[i].GetHashCode(); } } hashCode += (hashCode * 397) ^ GetHashCode(newExpression.Arguments); break; } case ExpressionType.NewArrayInit: case ExpressionType.NewArrayBounds: { var newArrayExpression = (NewArrayExpression)obj; hashCode += (hashCode * 397) ^ GetHashCode(newArrayExpression.Expressions); break; } case ExpressionType.Invoke: { var invocationExpression = (InvocationExpression)obj; hashCode += (hashCode * 397) ^ GetHashCode(invocationExpression.Expression); hashCode += (hashCode * 397) ^ GetHashCode(invocationExpression.Arguments); break; } case ExpressionType.MemberInit: { var memberInitExpression = (MemberInitExpression)obj; hashCode += (hashCode * 397) ^ GetHashCode(memberInitExpression.NewExpression); for (var i = 0; i < memberInitExpression.Bindings.Count; i++) { var memberBinding = memberInitExpression.Bindings[i]; hashCode += (hashCode * 397) ^ memberBinding.Member.GetHashCode(); hashCode += (hashCode * 397) ^ (int)memberBinding.BindingType; switch (memberBinding.BindingType) { case MemberBindingType.Assignment: var memberAssignment = (MemberAssignment)memberBinding; hashCode += (hashCode * 397) ^ GetHashCode(memberAssignment.Expression); break; case MemberBindingType.ListBinding: var memberListBinding = (MemberListBinding)memberBinding; for (var j = 0; j < memberListBinding.Initializers.Count; j++) { hashCode += (hashCode * 397) ^ GetHashCode(memberListBinding.Initializers[j].Arguments); } break; default: throw new NotImplementedException(); } } break; } case ExpressionType.ListInit: { var listInitExpression = (ListInitExpression)obj; hashCode += (hashCode * 397) ^ GetHashCode(listInitExpression.NewExpression); for (var i = 0; i < listInitExpression.Initializers.Count; i++) { hashCode += (hashCode * 397) ^ GetHashCode(listInitExpression.Initializers[i].Arguments); } break; } case ExpressionType.Conditional: { var conditionalExpression = (ConditionalExpression)obj; hashCode += (hashCode * 397) ^ GetHashCode(conditionalExpression.Test); hashCode += (hashCode * 397) ^ GetHashCode(conditionalExpression.IfTrue); hashCode += (hashCode * 397) ^ GetHashCode(conditionalExpression.IfFalse); break; } case ExpressionType.Default: { hashCode += (hashCode * 397) ^ obj.Type.GetHashCode(); break; } case ExpressionType.Extension: { if (obj is NullConditionalExpression nullConditionalExpression) { hashCode += (hashCode * 397) ^ GetHashCode(nullConditionalExpression.AccessOperation); } else if (obj is NullSafeEqualExpression nullConditionalEqualExpression) { hashCode += (hashCode * 397) ^ GetHashCode(nullConditionalEqualExpression.OuterKeyNullCheck); hashCode += (hashCode * 397) ^ GetHashCode(nullConditionalEqualExpression.EqualExpression); } else { hashCode += (hashCode * 397) ^ obj.GetHashCode(); } break; } default: throw new NotImplementedException(); } return hashCode; } } private int GetHashCode<T>(IList<T> expressions) where T : Expression { var hashCode = 0; for (var i = 0; i < expressions.Count; i++) { hashCode += (hashCode * 397) ^ GetHashCode(expressions[i]); } return hashCode; } /// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public virtual bool Equals(Expression x, Expression y) => new ExpressionComparer().Compare(x, y); private sealed class ExpressionComparer { private ScopedDictionary<ParameterExpression, ParameterExpression> _parameterScope; public bool Compare(Expression a, Expression b) { if (a == b) { return true; } if (a == null || b == null) { return false; } if (a.NodeType != b.NodeType) { return false; } if (a.Type != b.Type) { return false; } switch (a.NodeType) { case ExpressionType.Negate: case ExpressionType.NegateChecked: case ExpressionType.Not: case ExpressionType.Convert: case ExpressionType.ConvertChecked: case ExpressionType.ArrayLength: case ExpressionType.Quote: case ExpressionType.TypeAs: case ExpressionType.UnaryPlus: return CompareUnary((UnaryExpression)a, (UnaryExpression)b); case ExpressionType.Add: case ExpressionType.AddChecked: case ExpressionType.Subtract: case ExpressionType.SubtractChecked: case ExpressionType.Multiply: case ExpressionType.MultiplyChecked: case ExpressionType.Divide: case ExpressionType.Modulo: case ExpressionType.And: case ExpressionType.AndAlso: case ExpressionType.Or: case ExpressionType.OrElse: case ExpressionType.LessThan: case ExpressionType.LessThanOrEqual: case ExpressionType.GreaterThan: case ExpressionType.GreaterThanOrEqual: case ExpressionType.Equal: case ExpressionType.NotEqual: case ExpressionType.Coalesce: case ExpressionType.ArrayIndex: case ExpressionType.RightShift: case ExpressionType.LeftShift: case ExpressionType.ExclusiveOr: case ExpressionType.Power: return CompareBinary((BinaryExpression)a, (BinaryExpression)b); case ExpressionType.TypeIs: return CompareTypeIs((TypeBinaryExpression)a, (TypeBinaryExpression)b); case ExpressionType.Conditional: return CompareConditional((ConditionalExpression)a, (ConditionalExpression)b); case ExpressionType.Constant: return CompareConstant((ConstantExpression)a, (ConstantExpression)b); case ExpressionType.Parameter: return CompareParameter((ParameterExpression)a, (ParameterExpression)b); case ExpressionType.MemberAccess: return CompareMemberAccess((MemberExpression)a, (MemberExpression)b); case ExpressionType.Call: return CompareMethodCall((MethodCallExpression)a, (MethodCallExpression)b); case ExpressionType.Lambda: return CompareLambda((LambdaExpression)a, (LambdaExpression)b); case ExpressionType.New: return CompareNew((NewExpression)a, (NewExpression)b); case ExpressionType.NewArrayInit: case ExpressionType.NewArrayBounds: return CompareNewArray((NewArrayExpression)a, (NewArrayExpression)b); case ExpressionType.Invoke: return CompareInvocation((InvocationExpression)a, (InvocationExpression)b); case ExpressionType.MemberInit: return CompareMemberInit((MemberInitExpression)a, (MemberInitExpression)b); case ExpressionType.ListInit: return CompareListInit((ListInitExpression)a, (ListInitExpression)b); case ExpressionType.Extension: return CompareExtension(a, b); default: throw new NotImplementedException(); } } private bool CompareUnary(UnaryExpression a, UnaryExpression b) => Equals(a.Method, b.Method) && a.IsLifted == b.IsLifted && a.IsLiftedToNull == b.IsLiftedToNull && Compare(a.Operand, b.Operand); private bool CompareBinary(BinaryExpression a, BinaryExpression b) => Equals(a.Method, b.Method) && a.IsLifted == b.IsLifted && a.IsLiftedToNull == b.IsLiftedToNull && Compare(a.Left, b.Left) && Compare(a.Right, b.Right); private bool CompareTypeIs(TypeBinaryExpression a, TypeBinaryExpression b) => a.TypeOperand == b.TypeOperand && Compare(a.Expression, b.Expression); private bool CompareConditional(ConditionalExpression a, ConditionalExpression b) => Compare(a.Test, b.Test) && Compare(a.IfTrue, b.IfTrue) && Compare(a.IfFalse, b.IfFalse); private static bool CompareConstant(ConstantExpression a, ConstantExpression b) { if (a.Value == b.Value) { return true; } if (a.Value == null || b.Value == null) { return false; } if (a.IsEntityQueryable() && b.IsEntityQueryable() && a.Value.GetType() == b.Value.GetType()) { return true; } return Equals(a.Value, b.Value); } private bool CompareParameter(ParameterExpression a, ParameterExpression b) { if (_parameterScope != null) { if (_parameterScope.TryGetValue(a, out var mapped)) { return mapped.Name == b.Name && mapped.Type == b.Type; } } return a.Name == b.Name && a.Type == b.Type; } private bool CompareMemberAccess(MemberExpression a, MemberExpression b) => Equals(a.Member, b.Member) && Compare(a.Expression, b.Expression); private bool CompareMethodCall(MethodCallExpression a, MethodCallExpression b) => Equals(a.Method, b.Method) && Compare(a.Object, b.Object) && CompareExpressionList(a.Arguments, b.Arguments); private bool CompareLambda(LambdaExpression a, LambdaExpression b) { var n = a.Parameters.Count; if (b.Parameters.Count != n) { return false; } // all must have same type for (var i = 0; i < n; i++) { if (a.Parameters[i].Type != b.Parameters[i].Type) { return false; } } var save = _parameterScope; _parameterScope = new ScopedDictionary<ParameterExpression, ParameterExpression>(_parameterScope); try { for (var i = 0; i < n; i++) { _parameterScope.Add(a.Parameters[i], b.Parameters[i]); } return Compare(a.Body, b.Body); } finally { _parameterScope = save; } } private bool CompareNew(NewExpression a, NewExpression b) => Equals(a.Constructor, b.Constructor) && CompareExpressionList(a.Arguments, b.Arguments) && CompareMemberList(a.Members, b.Members); private bool CompareExpressionList(IReadOnlyList<Expression> a, IReadOnlyList<Expression> b) { if (Equals(a, b)) { return true; } if (a == null || b == null) { return false; } if (a.Count != b.Count) { return false; } for (int i = 0, n = a.Count; i < n; i++) { if (!Compare(a[i], b[i])) { return false; } } return true; } private static bool CompareMemberList(IReadOnlyList<MemberInfo> a, IReadOnlyList<MemberInfo> b) { if (ReferenceEquals(a, b)) { return true; } if (a == null || b == null) { return false; } if (a.Count != b.Count) { return false; } for (int i = 0, n = a.Count; i < n; i++) { if (!Equals(a[i], b[i])) { return false; } } return true; } private bool CompareNewArray(NewArrayExpression a, NewArrayExpression b) => CompareExpressionList(a.Expressions, b.Expressions); private bool CompareExtension(Expression a, Expression b) { if (a is NullConditionalExpression nullConditionalExpressionA && b is NullConditionalExpression nullConditionalExpressionB) { return Compare( nullConditionalExpressionA.AccessOperation, nullConditionalExpressionB.AccessOperation); } if (a is NullSafeEqualExpression nullConditionalEqualExpressionA && b is NullSafeEqualExpression nullConditionalEqualExpressionB) { return Compare( nullConditionalEqualExpressionA.OuterKeyNullCheck, nullConditionalEqualExpressionB.OuterKeyNullCheck) && Compare( nullConditionalEqualExpressionA.EqualExpression, nullConditionalEqualExpressionB.EqualExpression); } return a.Equals(b); } private bool CompareInvocation(InvocationExpression a, InvocationExpression b) => Compare(a.Expression, b.Expression) && CompareExpressionList(a.Arguments, b.Arguments); private bool CompareMemberInit(MemberInitExpression a, MemberInitExpression b) => Compare(a.NewExpression, b.NewExpression) && CompareBindingList(a.Bindings, b.Bindings); private bool CompareBindingList(IReadOnlyList<MemberBinding> a, IReadOnlyList<MemberBinding> b) { if (ReferenceEquals(a, b)) { return true; } if (a == null || b == null) { return false; } if (a.Count != b.Count) { return false; } for (int i = 0, n = a.Count; i < n; i++) { if (!CompareBinding(a[i], b[i])) { return false; } } return true; } private bool CompareBinding(MemberBinding a, MemberBinding b) { if (a == b) { return true; } if (a == null || b == null) { return false; } if (a.BindingType != b.BindingType) { return false; } if (!Equals(a.Member, b.Member)) { return false; } switch (a.BindingType) { case MemberBindingType.Assignment: return CompareMemberAssignment((MemberAssignment)a, (MemberAssignment)b); case MemberBindingType.ListBinding: return CompareMemberListBinding((MemberListBinding)a, (MemberListBinding)b); case MemberBindingType.MemberBinding: return CompareMemberMemberBinding((MemberMemberBinding)a, (MemberMemberBinding)b); default: throw new NotImplementedException(); } } private bool CompareMemberAssignment(MemberAssignment a, MemberAssignment b) => Equals(a.Member, b.Member) && Compare(a.Expression, b.Expression); private bool CompareMemberListBinding(MemberListBinding a, MemberListBinding b) => Equals(a.Member, b.Member) && CompareElementInitList(a.Initializers, b.Initializers); private bool CompareMemberMemberBinding(MemberMemberBinding a, MemberMemberBinding b) => Equals(a.Member, b.Member) && CompareBindingList(a.Bindings, b.Bindings); private bool CompareListInit(ListInitExpression a, ListInitExpression b) => Compare(a.NewExpression, b.NewExpression) && CompareElementInitList(a.Initializers, b.Initializers); private bool CompareElementInitList(IReadOnlyList<ElementInit> a, IReadOnlyList<ElementInit> b) { if (ReferenceEquals(a, b)) { return true; } if (a == null || b == null) { return false; } if (a.Count != b.Count) { return false; } for (int i = 0, n = a.Count; i < n; i++) { if (!CompareElementInit(a[i], b[i])) { return false; } } return true; } private bool CompareElementInit(ElementInit a, ElementInit b) => Equals(a.AddMethod, b.AddMethod) && CompareExpressionList(a.Arguments, b.Arguments); private class ScopedDictionary<TKey, TValue> { private readonly ScopedDictionary<TKey, TValue> _previous; private readonly Dictionary<TKey, TValue> _map; public ScopedDictionary(ScopedDictionary<TKey, TValue> previous) { _previous = previous; _map = new Dictionary<TKey, TValue>(); } public void Add(TKey key, TValue value) => _map.Add(key, value); public bool TryGetValue(TKey key, out TValue value) { for (var scope = this; scope != null; scope = scope._previous) { if (scope._map.TryGetValue(key, out value)) { return true; } } value = default; return false; } } } private sealed class InnerExpressionEqualityComparer { static InnerExpressionEqualityComparer() { } internal static readonly ExpressionEqualityComparer Instance = new ExpressionEqualityComparer(); } } }
39.743155
128
0.470721
[ "Apache-2.0" ]
chrisblock/EntityFramework
src/EFCore/Query/Internal/ExpressionEqualityComparer.cs
30,483
C#
/* * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Net; using Amazon.IdentityManagement.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; namespace Amazon.IdentityManagement.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for ChangePassword operation /// </summary> internal class ChangePasswordResponseUnmarshaller : XmlResponseUnmarshaller { public override AmazonWebServiceResponse Unmarshall(XmlUnmarshallerContext context) { ChangePasswordResponse response = new ChangePasswordResponse(); while (context.Read()) { if (context.IsStartElement) { if (context.TestExpression("ResponseMetadata", 2)) { response.ResponseMetadata = ResponseMetadataUnmarshaller.GetInstance().Unmarshall(context); } } } return response; } public override AmazonServiceException UnmarshallException(XmlUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode) { ErrorResponse errorResponse = ErrorResponseUnmarshaller.GetInstance().Unmarshall(context); if (errorResponse.Code != null && errorResponse.Code.Equals("EntityTemporarilyUnmodifiable")) { return new EntityTemporarilyUnmodifiableException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("NoSuchEntity")) { return new NoSuchEntityException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("LimitExceeded")) { return new LimitExceededException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidUserType")) { return new InvalidUserTypeException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } return new AmazonIdentityManagementServiceException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } private static ChangePasswordResponseUnmarshaller instance; public static ChangePasswordResponseUnmarshaller GetInstance() { if (instance == null) { instance = new ChangePasswordResponseUnmarshaller(); } return instance; } } }
39.677419
182
0.652846
[ "Apache-2.0" ]
jdluzen/aws-sdk-net-android
AWSSDK/Amazon.IdentityManagement/Model/Internal/MarshallTransformations/ChangePasswordResponseUnmarshaller.cs
3,690
C#
using DCL.Models; using System.Collections; using System.Collections.Generic; using DCL.Helpers; using UnityEngine; using DCL.Controllers; namespace DCL.Components { public class DCLAnimator : BaseComponent { [System.Serializable] public class Model : BaseModel { [System.Serializable] public class DCLAnimationState { public string name; public string clip; public AnimationClip clipReference; public bool playing; [Range(0, 1)] public float weight = 1f; public float speed = 1f; public bool looping = true; public bool shouldReset = false; public DCLAnimationState Clone() { return (DCLAnimationState) this.MemberwiseClone(); } } public DCLAnimationState[] states; public override BaseModel GetDataFromJSON(string json) { return Utils.SafeFromJson<Model>(json); } } [System.NonSerialized] public Animation animComponent = null; Dictionary<string, AnimationClip> clipNameToClip = new Dictionary<string, AnimationClip>(); Dictionary<AnimationClip, AnimationState> clipToState = new Dictionary<AnimationClip, AnimationState>(); private void Awake() { model = new Model(); } private void OnDestroy() { entity.OnShapeUpdated -= OnComponentUpdated; } public override IEnumerator ApplyChanges(BaseModel model) { entity.OnShapeUpdated -= OnComponentUpdated; entity.OnShapeUpdated += OnComponentUpdated; UpdateAnimationState(); return null; } new public Model GetModel() { return (Model) model; } private void OnComponentUpdated(IDCLEntity e) { UpdateAnimationState(); } private void Initialize() { if (entity == null || animComponent != null) return; //NOTE(Brian): fetch all the AnimationClips in Animation component. animComponent = transform.parent.GetComponentInChildren<Animation>(true); if (animComponent == null) return; clipNameToClip.Clear(); clipToState.Clear(); int layerIndex = 0; animComponent.playAutomatically = true; animComponent.enabled = true; animComponent.Stop(); //NOTE(Brian): When the GLTF is created by GLTFSceneImporter a frame may be elapsed, //putting the component in play state if playAutomatically was true at that point. animComponent.clip?.SampleAnimation(animComponent.gameObject, 0); foreach (AnimationState unityState in animComponent) { clipNameToClip[unityState.clip.name] = unityState.clip; unityState.clip.wrapMode = WrapMode.Loop; unityState.layer = layerIndex; unityState.blendMode = AnimationBlendMode.Blend; layerIndex++; } } void UpdateAnimationState() { Initialize(); if (clipNameToClip.Count == 0 || animComponent == null) return; Model model = (Model) this.model; if (model.states == null || model.states.Length == 0) return; for (int i = 0; i < model.states.Length; i++) { Model.DCLAnimationState state = model.states[i]; if (clipNameToClip.ContainsKey(state.clip)) { AnimationState unityState = animComponent[state.clip]; unityState.weight = state.weight; unityState.wrapMode = state.looping ? WrapMode.Loop : WrapMode.ClampForever; unityState.clip.wrapMode = unityState.wrapMode; unityState.speed = state.speed; state.clipReference = unityState.clip; if (state.shouldReset) ResetAnimation(state); if (state.playing) { if (!animComponent.IsPlaying(state.clip)) animComponent.Play(state.clip); } else { if (animComponent.IsPlaying(state.clip)) animComponent.Stop(state.clip); } } } } public void ResetAnimation(Model.DCLAnimationState state) { if (state == null || state.clipReference == null) { Debug.LogError("Clip not found"); return; } animComponent.Stop(state.clip); //Manually sample the animation. If the reset is not played again the frame 0 wont be applied state.clipReference.SampleAnimation(animComponent.gameObject, 0); } public Model.DCLAnimationState GetStateByString(string stateName) { Model model = (Model) this.model; for (var i = 0; i < model.states.Length; i++) { if (model.states[i].name == stateName) { return model.states[i]; } } return null; } public override int GetClassId() { return (int) CLASS_ID_COMPONENT.ANIMATOR; } } }
30.796791
118
0.52648
[ "Apache-2.0" ]
Marguelgtz/explorer
unity-client/Assets/Scripts/MainScripts/DCL/Components/Animator/DCLAnimator.cs
5,759
C#
namespace SPNATI_Character_Editor.Controls { partial class ImageFileSelectControl { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.txtValue = new Desktop.CommonControls.TextField(); this.cmdBrowse = new Desktop.Skinning.SkinnedButton(); this.openFileDialog1 = new SPNATI_Character_Editor.Controls.CharacterImageDialog(); this.SuspendLayout(); // // txtValue // this.txtValue.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right))); this.txtValue.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.None; this.txtValue.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.None; this.txtValue.Location = new System.Drawing.Point(0, 0); this.txtValue.Multiline = false; this.txtValue.Name = "txtValue"; this.txtValue.PlaceholderText = ""; this.txtValue.ReadOnly = true; this.txtValue.Size = new System.Drawing.Size(318, 20); this.txtValue.TabIndex = 0; // // cmdBrowse // this.cmdBrowse.Anchor = System.Windows.Forms.AnchorStyles.Right; this.cmdBrowse.Background = Desktop.Skinning.SkinnedBackgroundType.Surface; this.cmdBrowse.FieldType = Desktop.Skinning.SkinnedFieldType.Surface; this.cmdBrowse.Flat = false; this.cmdBrowse.ForeColor = System.Drawing.Color.Blue; this.cmdBrowse.Location = new System.Drawing.Point(324, -1); this.cmdBrowse.Name = "cmdBrowse"; this.cmdBrowse.Size = new System.Drawing.Size(27, 22); this.cmdBrowse.TabIndex = 1; this.cmdBrowse.Text = "..."; this.cmdBrowse.UseVisualStyleBackColor = true; this.cmdBrowse.Click += new System.EventHandler(this.CmdBrowse_Click); // // openFileDialog1 // this.openFileDialog1.Filter = ""; this.openFileDialog1.IncludeOpponents = false; this.openFileDialog1.UseAbsolutePaths = false; // // ImageFileSelectControl // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.cmdBrowse); this.Controls.Add(this.txtValue); this.Name = "ImageFileSelectControl"; this.Size = new System.Drawing.Size(351, 20); this.ResumeLayout(false); } #endregion private Desktop.CommonControls.TextField txtValue; private Desktop.Skinning.SkinnedButton cmdBrowse; private CharacterImageDialog openFileDialog1; } }
34.449438
148
0.723744
[ "MIT" ]
laytonc32/spnati
editor source/SPNATI Character Editor/Controls/EditControls/ImageFileSelectControl.Designer.cs
3,068
C#
using UnityEngine; using System; [Serializable] public struct CameraBufferSettings { public bool allowHDR; public bool copyColor; public bool copyColorReflection; public bool copyDepth; public bool copyDepthReflections; [Range(CameraRenderer.renderScaleMin, CameraRenderer.renderScaleMax)] public float renderScale; public enum BicubicRescalingMode { Off, UpOnly, UpAndDown } public BicubicRescalingMode bicubicRescaling; [Serializable] public struct FXAA { public bool enabled; [Range(0.0312f, 0.0833f)] public float fixedThreshold; [Range(0.063f, 0.333f)] public float relativeThreshold; [Range(0f, 1f)] public float subpixelBlending; public enum Quality { Low, Medium, High } public Quality quality; } public FXAA fxaa; }
23.102564
74
0.653718
[ "MIT" ]
Alekssasho/UnityCustomRenderingPipeline
Assets/Custom RP/Runtime/CameraBufferSettings.cs
903
C#
using System; using DCL.Components; using DCL.Controllers; using DCL.Helpers; using DCL.Interface; using Newtonsoft.Json; using UnityEngine; using UnityEngine.Profiling; namespace DCL { public class DebugBridge : MonoBehaviour { [Serializable] class ToggleSceneBoundingBoxesPayload { public string sceneId; public bool enabled; } private ILogger debugLogger = new Logger(Debug.unityLogger.logHandler); private IDebugController debugController; public void Setup(IDebugController debugController) { this.debugController = debugController; } // Beware this SetDebug() may be called before Awake() somehow... [ContextMenu("Set Debug mode")] public void SetDebug() { debugController.SetDebug(); } public void HideFPSPanel() { debugController.HideFPSPanel(); } public void ShowFPSPanel() { debugController.ShowFPSPanel(); } public void SetSceneDebugPanel() { debugController.SetSceneDebugPanel(); } public void SetEngineDebugPanel() { debugController.SetEngineDebugPanel(); } [ContextMenu("Dump Scenes Load Info")] public void DumpScenesLoadInfo() { bool originalLoggingValue = Debug.unityLogger.logEnabled; Debug.unityLogger.logEnabled = true; foreach (var kvp in DCL.Environment.i.world.state.loadedScenes) { IParcelScene scene = kvp.Value; debugLogger.Log("Dumping state for scene: " + kvp.Value.sceneData.id); scene.GetWaitingComponentsDebugInfo(); } Debug.unityLogger.logEnabled = originalLoggingValue; } [ContextMenu("Dump Scene Metrics Offenders")] public void DumpSceneMetricsOffenders() { bool originalLoggingValue = Debug.unityLogger.logEnabled; Debug.unityLogger.logEnabled = true; var worstMetricOffenses = DataStore.i.Get<DataStore_SceneMetrics>().worstMetricOffenses; foreach (var offense in worstMetricOffenses) { debugLogger.Log($"Scene: {offense.Key} ... Metrics: {offense.Value}"); } Debug.unityLogger.logEnabled = originalLoggingValue; } public void SetDisableAssetBundles() { RendereableAssetLoadHelper.defaultLoadingType = RendereableAssetLoadHelper.LoadingType.GLTF_ONLY; } [ContextMenu("Dump Renderers Lockers Info")] public void DumpRendererLockersInfo() { bool originalLoggingValue = Debug.unityLogger.logEnabled; Debug.unityLogger.logEnabled = true; RenderingController renderingController = FindObjectOfType<RenderingController>(); if (renderingController == null) { debugLogger.Log("RenderingController not found. Aborting."); return; } debugLogger.Log($"Renderer is locked? {!renderingController.renderingActivatedAckLock.isUnlocked}"); debugLogger.Log($"Renderer is active? {CommonScriptableObjects.rendererState.Get()}"); System.Collections.Generic.HashSet<object> lockIds = renderingController.renderingActivatedAckLock.GetLockIdsCopy(); foreach (var lockId in lockIds) { debugLogger.Log($"Renderer is locked by id: {lockId} of type {lockId.GetType()}"); } Debug.unityLogger.logEnabled = originalLoggingValue; } public void CrashPayloadRequest() { bool originalLoggingValue = Debug.unityLogger.logEnabled; Debug.unityLogger.logEnabled = true; var crashPayload = CrashPayloadUtils.ComputePayload ( DCL.Environment.i.world.state.loadedScenes, debugController.GetTrackedMovements(), debugController.GetTrackedTeleportPositions() ); CrashPayloadResponse(crashPayload); Debug.unityLogger.logEnabled = originalLoggingValue; } public void CrashPayloadResponse(CrashPayload payload) { string json = JsonConvert.SerializeObject(payload); WebInterface.MessageFromEngine("CrashPayloadResponse", json); } [ContextMenu("Dump Crash Payload")] public void DumpCrashPayload() { bool originalLoggingValue = Debug.unityLogger.logEnabled; Debug.unityLogger.logEnabled = true; debugLogger.Log( $"MEMORY -- total {Profiler.GetTotalAllocatedMemoryLong()} ... used by mono {Profiler.GetMonoUsedSizeLong()}"); var payload = CrashPayloadUtils.ComputePayload ( DCL.Environment.i.world.state.loadedScenes, debugController.GetTrackedMovements(), debugController.GetTrackedTeleportPositions() ); foreach (var field in payload.fields) { string dump = JsonConvert.SerializeObject(field.Value); debugLogger.Log($"Crash payload ({field.Key}): {dump}"); } string fullDump = JsonConvert.SerializeObject(payload); debugLogger.Log($"Full crash payload size: {fullDump.Length}"); Debug.unityLogger.logEnabled = originalLoggingValue; } public void RunPerformanceMeterTool(float durationInSeconds) { debugController.RunPerformanceMeterTool(durationInSeconds); } public void InstantiateBotsAtWorldPos(string configJson) { debugController.InstantiateBotsAtWorldPos(configJson); } public void InstantiateBotsAtCoords(string configJson) { debugController.InstantiateBotsAtCoords(configJson); } public void StartBotsRandomizedMovement(string configJson) { debugController.StartBotsRandomizedMovement(configJson); } public void StopBotsMovement() { debugController.StopBotsMovement(); } public void RemoveBot(long targetEntityId) { debugController.RemoveBot(targetEntityId); } public void ClearBots() { debugController.ClearBots(); } public void ToggleSceneBoundingBoxes(string payload) { ToggleSceneBoundingBoxesPayload data = JsonUtility.FromJson<ToggleSceneBoundingBoxesPayload>(payload); DataStore.i.debugConfig.showSceneBoundingBoxes.AddOrSet(data.sceneId, data.enabled); } public void TogglePreviewMenu(string payload) { PreviewMenuPayload data = JsonUtility.FromJson<PreviewMenuPayload>(payload); DataStore.i.debugConfig.isPreviewMenuActive.Set(data.enabled); } public void ToggleSceneSpawnPoints(string payload) { ToggleSpawnPointsPayload data = Utils.FromJsonWithNulls<ToggleSpawnPointsPayload>(payload); // handle `undefined` `enabled` which means to update "spawnpoints" without changing it enabled state if (!data.enabled.HasValue) { var prevData = DataStore.i.debugConfig.showSceneSpawnPoints.Get(data.sceneId); data.enabled = prevData == null || !prevData.enabled.HasValue ? false : prevData.enabled; } DataStore.i.debugConfig.showSceneSpawnPoints.AddOrSet(data.sceneId, data); } #if UNITY_EDITOR [ContextMenu("Run Performance Meter Tool for 30 seconds")] public void DebugPerformanceMeter() { RunPerformanceMeterTool(30); } [ContextMenu("Instantiate 3 bots at player coordinates")] public void DebugBotsInstantiation() { InstantiateBotsAtCoords("{ " + "\"amount\":3, " + "\"areaWidth\":15, " + "\"areaDepth\":15 " + "}"); } #endif } }
33.66129
127
0.606133
[ "Apache-2.0" ]
Timothyoung97/unity-renderer
unity-renderer/Assets/Scripts/MainScripts/DCL/WorldRuntime/DebugController/DebugBridge.cs
8,350
C#
// This is an open source non-commercial project. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com // ReSharper disable CheckNamespace // ReSharper disable CommentTypo // ReSharper disable IdentifierTypo // ReSharper disable UnusedMember.Global // ReSharper disable UnusedType.Global /* SiberianUtility.cs -- полезные методы для работы с гридом, ячейками, колонками и строками * Ars Magna project, http://arsmagna.ru */ #region Using directives using System.Windows.Forms; using AM; #endregion #nullable enable namespace ManagedIrbis.WinForms.Grid { /// <summary> /// Полезные методы для работы с гридом, ячейками, колонками и строками. /// </summary> public static class SiberianUtility { #region Public methods /// <summary> /// Добавление к гриду целочисленной колонки. /// </summary> public static SiberianColumn AddIntegerColumn ( this SiberianGrid grid, string? title = null ) { var result = grid.CreateColumn<SiberianIntegerColumn>(); result.Title = title; return result; } // method AddIntegerColumn /// <summary> /// Добавление к гриду целочисленной колонки. /// </summary> public static SiberianColumn AddPropertyColumn ( this SiberianGrid grid, string propertyName, string? title = null ) { var result = grid.CreateColumn<SiberianPropertyColumn>(); result.Title = title; result.Member = propertyName; return result; } // method AddPropertyColumn /// <summary> /// Добавление к гриду текстовой колонки. /// </summary> public static SiberianColumn AddTextColumn ( this SiberianGrid grid, string? title = null ) { var result = grid.CreateColumn<SiberianTextColumn>(); result.Title = title; return result; } // method AddTextColumn /// <summary> /// Получаем колонку, которой принадлежит ячейка. /// </summary> public static SiberianColumn EnsureColumn (this SiberianCell cell) => cell.Column.ThrowIfNull (nameof (cell.Column)); /// <summary> /// Получаем грид, которому принадлежит ячейка. /// </summary> public static SiberianGrid EnsureGrid (this SiberianCell cell) => cell.Grid.ThrowIfNull (nameof (cell.Grid)); /// <summary> /// Получаем строку, которой принадлежит ячейка. /// </summary> public static SiberianRow EnsureRow (this SiberianCell cell) => cell.Row.ThrowIfNull (nameof (cell.Row)); /// <summary> /// Получение размеров указанного текста. /// </summary> public static void MeasureText ( this SiberianGrid grid, string text, SiberianDimensions dimensions ) { var size = dimensions.ToSize(); var font = grid.Font; var flags = TextFormatFlags.Left | TextFormatFlags.Top | TextFormatFlags.NoPrefix; var result = TextRenderer.MeasureText ( text, font, size, flags ); dimensions.Width = result.Width; dimensions.Height = result.Height; } // method MeasureText /// <summary> /// Установка заголовка. /// </summary> public static T SetTitle<T>(this T column, string? title) where T : SiberianColumn { column.Title = title; return column; } // method SetFillWidth /// <summary> /// Установка относительной ширины колонки. /// </summary> public static T SetFillWidth<T>(this T column, int width) where T : SiberianColumn { column.FillWidth = width; return column; } // method SetFillWidth /// <summary> /// Установка минимальной ширины колонки. /// </summary> public static T SetMinWidth<T>(this T column, int width) where T : SiberianColumn { column.MinWidth = width; return column; } // method SetMinWidth /// <summary> /// Установка абсолютной ширины колонки. /// </summary> public static T SetWidth<T>(this T column, int width) where T : SiberianColumn { column.Width = width; return column; } // method SetWidth #endregion } // class SiberianUtility } // namespace ManagedIrbis.WinForms.Grid
28.4
92
0.554326
[ "MIT" ]
amironov73/ManagedIrbis5
Source/Libs/ManagedIrbis5.WinForms/Source/Grid/SiberianUtility.cs
5,453
C#
using eDriven.Core.Geom; namespace eDriven.Gui.Containers { /// <summary> /// Provides container scrolling /// </summary> public interface IScrollable { /// <summary> /// Content scrolling /// </summary> //bool ScrollContent { get; set; } bool ClipContent { get; set; } /// <summary> /// Scroll position of container's content /// </summary> //Point ScrollPosition { get; } /// <summary> /// Horizontal scroll position /// </summary> float HorizontalScrollPosition { get; set; } /// <summary> /// Vertical scroll position /// </summary> float VerticalScrollPosition { get; set; } /// <summary> /// The amount by which the container will scroll vertically for each mouse wheel tick /// </summary> float MouseWheelStep { get; set; } //bool CanScroll(float scrollBy); /// <summary> /// Scrolls the scrollable container<br/> /// Returns the residuum (unscrolled pixels)<br/> /// Mouse even dispatcher could decide to use the residuum to scroll the parent scrollable container /// </summary> /// <param name="amount"></param> /// <returns></returns> Point ScrollBy(Point amount); } }
28.914894
108
0.555556
[ "MIT" ]
dkozar/edriven-gui
eDriven/eDriven.Gui/Containers/Core/IScrollable.cs
1,359
C#
using Amazon.EC2.Model; using Microsoft.AspNetCore.Mvc; using Microsoft.IdentityModel.Protocols; using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Threading.Tasks; using System.Web.Mvc; using JsonResult = Microsoft.AspNetCore.Mvc.JsonResult; using ViewResult = Microsoft.AspNetCore.Mvc.ViewResult; namespace CSVImport.Controllers { public class LoginController { public ViewResult LoginForm() { return ViewResult(); } public JsonResult Loginvalidate(UserData) { HttpClient client = new HttpClient(); string _url = ConfigurationManager.AppSettings["webapibaseurl"]; client.BaseAddress = new Uri(_url); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); MediaTypeFormatter jsonFormatter = new JsonMediaTypeFormatter(); HttpResponseMessage response = client.GetAsync("URL").Result; string content1 = response.Content.ReadAsStringAsync().Result; if (response.StatusCode.ToString() == "OK") { return JsonResult(content1, JsonRequestBehavior.AllowGet); } } private JsonResult JsonResult(string content1, JsonRequestBehavior allowGet) { throw new NotImplementedException(); } private ViewResult ViewResult() { throw new NotImplementedException(); } } }
32.269231
110
0.650775
[ "MIT" ]
Thapelo101/CSVImport
CSVImport/CSVImport/Controllers/LoginController.cs
1,680
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; using CandidateTesting.JoseAntonio.ConvertToAgora.Templates; using CandidateTesting.JoseAntonio.ConvertToAgora.Converters; using System.Collections.Generic; namespace CandidateTesting.JoseAntonio.ConvertToAgora.Tests { [TestClass] public class ConverterTest { [TestMethod] public void MustBePossibleToConvertMinhaCdnRecordToAgoraRecord() { string minhaCdnRecord = "312|200|HIT|\"GET /robots.txt HTTP/1.1\"|100.2"; string expectedAgoraRecord = "\"Minha CDN\" GET 200 /robots.txt 100 312 HIT"; MinhaCdnTemplate minhaCdnTemplate = new MinhaCdnTemplate(minhaCdnRecord); AgoraTemplate agoraTemplate = MinhaCdnToAgoraConverter.ToAgoraTemplate(minhaCdnTemplate); Assert.AreEqual(expectedAgoraRecord, agoraTemplate.ToString()); } [TestMethod] public void MustBePossibleToConvertAListOfMinhaCdnRecordToAgoraRecord() { List<string> minhaCdnRecords = new List<string> { "312|200|HIT|\"GET /robots.txt HTTP/1.1\"|100.2", "101|200|MISS|\"POST /myImages HTTP/1.1\"|319.4", "199|404|MISS|\"GET /not-found HTTP/1.1\"|142.9", "312|200|INVALIDATE|\"GET /robots.txt HTTP/1.1\"|245.1" }; List<string> expectedAgoraRecords = new List<string> { "\"Minha CDN\" GET 200 /robots.txt 100 312 HIT", "\"Minha CDN\" POST 200 /myImages 319 101 MISS", "\"Minha CDN\" GET 404 /not-found 143 199 MISS", "\"Minha CDN\" GET 200 /robots.txt 245 312 INVALIDATE", }; List<MinhaCdnTemplate> minhaCdnTemplates = new List<MinhaCdnTemplate>(); foreach (string minhaCdnRecord in minhaCdnRecords) { minhaCdnTemplates.Add(new MinhaCdnTemplate(minhaCdnRecord)); } List<AgoraTemplate> agoraTemplates = MinhaCdnToAgoraConverter.ToAgoraTemplate((minhaCdnTemplates)); for (int i = 0; i < agoraTemplates.Count; i++) { Assert.AreEqual(expectedAgoraRecords[i], agoraTemplates[i].ToString()); } } } }
39.448276
111
0.615822
[ "MIT" ]
otenbr/CandidateTesting.JoseAntonio.ConvertToAgora
ConvertToAgora.Tests/ConverterTest.cs
2,288
C#
// 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; using System.Collections; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Text.Json; using System.Text.Json.Serialization; using Microsoft.AspNetCore.Mvc.ApplicationModels; using Microsoft.AspNetCore.Mvc.Controllers; using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.AspNetCore.Mvc.Formatters; using Microsoft.AspNetCore.Mvc.Infrastructure; using Microsoft.AspNetCore.Mvc.ModelBinding; using Microsoft.AspNetCore.Mvc.ModelBinding.Binders; using Microsoft.AspNetCore.Mvc.ModelBinding.Metadata; using Microsoft.AspNetCore.Mvc.ModelBinding.Validation; using Microsoft.AspNetCore.WebUtilities; namespace Microsoft.AspNetCore.Mvc { /// <summary> /// Provides programmatic configuration for the MVC framework. /// </summary> public class MvcOptions : IEnumerable<ICompatibilitySwitch> { internal const int DefaultMaxModelBindingCollectionSize = FormReader.DefaultValueCountLimit; internal const int DefaultMaxModelBindingRecursionDepth = 32; private readonly IReadOnlyList<ICompatibilitySwitch> _switches = Array.Empty<ICompatibilitySwitch>(); private int _maxModelStateErrors = ModelStateDictionary.DefaultMaxAllowedErrors; private int _maxModelBindingCollectionSize = DefaultMaxModelBindingCollectionSize; private int _maxModelBindingRecursionDepth = DefaultMaxModelBindingRecursionDepth; private int? _maxValidationDepth = 32; /// <summary> /// Creates a new instance of <see cref="MvcOptions"/>. /// </summary> public MvcOptions() { CacheProfiles = new Dictionary<string, CacheProfile>(StringComparer.OrdinalIgnoreCase); Conventions = new List<IApplicationModelConvention>(); Filters = new FilterCollection(); FormatterMappings = new FormatterMappings(); InputFormatters = new FormatterCollection<IInputFormatter>(); OutputFormatters = new FormatterCollection<IOutputFormatter>(); ModelBinderProviders = new List<IModelBinderProvider>(); ModelBindingMessageProvider = new DefaultModelBindingMessageProvider(); ModelMetadataDetailsProviders = new List<IMetadataDetailsProvider>(); ModelValidatorProviders = new List<IModelValidatorProvider>(); ValueProviderFactories = new List<IValueProviderFactory>(); } /// <summary> /// Gets or sets a value that determines if routing should use endpoints internally, or if legacy routing /// logic should be used. Endpoint routing is used to match HTTP requests to MVC actions, and to generate /// URLs with <see cref="IUrlHelper"/>. /// </summary> /// <value> /// The default value is <see langword="true"/>. /// </value> public bool EnableEndpointRouting { get; set; } = true; /// <summary> /// Gets or sets the flag which decides whether body model binding (for example, on an /// action method parameter with <see cref="FromBodyAttribute"/>) should treat empty /// input as valid. <see langword="false"/> by default. /// </summary> /// <example> /// When <see langword="false"/>, actions that model bind the request body (for example, /// using <see cref="FromBodyAttribute"/>) will register an error in the /// <see cref="ModelStateDictionary"/> if the incoming request body is empty. /// </example> public bool AllowEmptyInputInBodyModelBinding { get; set; } /// <summary> /// Gets a Dictionary of CacheProfile Names, <see cref="CacheProfile"/> which are pre-defined settings for /// response caching. /// </summary> public IDictionary<string, CacheProfile> CacheProfiles { get; } /// <summary> /// Gets a list of <see cref="IApplicationModelConvention"/> instances that will be applied to /// the <see cref="ApplicationModel"/> when discovering actions. /// </summary> public IList<IApplicationModelConvention> Conventions { get; } /// <summary> /// Gets a collection of <see cref="IFilterMetadata"/> which are used to construct filters that /// apply to all actions. /// </summary> public FilterCollection Filters { get; } /// <summary> /// Used to specify mapping between the URL Format and corresponding media type. /// </summary> public FormatterMappings FormatterMappings { get; } /// <summary> /// Gets a list of <see cref="IInputFormatter"/>s that are used by this application. /// </summary> public FormatterCollection<IInputFormatter> InputFormatters { get; } /// <summary> /// Gets or sets a value that detemines if the inference of <see cref="RequiredAttribute"/> for /// for properties and parameters of non-nullable reference types is suppressed. If <c>false</c> /// (the default), then all non-nullable reference types will behave as-if <c>[Required]</c> has /// been applied. If <c>true</c>, this behavior will be suppressed; nullable reference types and /// non-nullable reference types will behave the same for the purposes of validation. /// </summary> /// <remarks> /// <para> /// This option controls whether MVC model binding and validation treats nullable and non-nullable /// reference types differently. /// </para> /// <para> /// By default, MVC will treat a non-nullable reference type parameters and properties as-if /// <c>[Required]</c> has been applied, resulting in validation errors when no value was bound. /// </para> /// <para> /// MVC does not support non-nullable reference type annotations on type arguments and type parameter /// contraints. The framework will not infer any validation attributes for generic-typed properties /// or collection elements. /// </para> /// </remarks> public bool SuppressImplicitRequiredAttributeForNonNullableReferenceTypes { get; set; } /// <summary> /// Gets or sets a value that determines if buffering is disabled for input formatters that /// synchronously read from the HTTP request body. /// </summary> public bool SuppressInputFormatterBuffering { get; set; } /// <summary> /// Gets or sets the flag that determines if buffering is disabled for output formatters that /// synchronously write to the HTTP response body. /// </summary> public bool SuppressOutputFormatterBuffering { get; set; } /// <summary> /// Gets or sets the maximum number of validation errors that are allowed by this application before further /// errors are ignored. /// </summary> public int MaxModelValidationErrors { get => _maxModelStateErrors; set { if (value < 0) { throw new ArgumentOutOfRangeException(nameof(value)); } _maxModelStateErrors = value; } } /// <summary> /// Gets a list of <see cref="IModelBinderProvider"/>s used by this application. /// </summary> public IList<IModelBinderProvider> ModelBinderProviders { get; } /// <summary> /// Gets the default <see cref="ModelBinding.Metadata.ModelBindingMessageProvider"/>. Changes here are copied to the /// <see cref="ModelMetadata.ModelBindingMessageProvider"/> property of all <see cref="ModelMetadata"/> /// instances unless overridden in a custom <see cref="IBindingMetadataProvider"/>. /// </summary> public DefaultModelBindingMessageProvider ModelBindingMessageProvider { get; } /// <summary> /// Gets a list of <see cref="IMetadataDetailsProvider"/> instances that will be used to /// create <see cref="ModelMetadata"/> instances. /// </summary> /// <remarks> /// A provider should implement one or more of the following interfaces, depending on what /// kind of details are provided: /// <ul> /// <li><see cref="IBindingMetadataProvider"/></li> /// <li><see cref="IDisplayMetadataProvider"/></li> /// <li><see cref="IValidationMetadataProvider"/></li> /// </ul> /// </remarks> public IList<IMetadataDetailsProvider> ModelMetadataDetailsProviders { get; } /// <summary> /// Gets a list of <see cref="IModelValidatorProvider"/>s used by this application. /// </summary> public IList<IModelValidatorProvider> ModelValidatorProviders { get; } /// <summary> /// Gets a list of <see cref="IOutputFormatter"/>s that are used by this application. /// </summary> public FormatterCollection<IOutputFormatter> OutputFormatters { get; } /// <summary> /// Gets or sets the flag which causes content negotiation to ignore Accept header /// when it contains the media type */*. <see langword="false"/> by default. /// </summary> public bool RespectBrowserAcceptHeader { get; set; } /// <summary> /// Gets or sets the flag which decides whether an HTTP 406 Not Acceptable response /// will be returned if no formatter has been selected to format the response. /// <see langword="false"/> by default. /// </summary> public bool ReturnHttpNotAcceptable { get; set; } /// <summary> /// Gets a list of <see cref="IValueProviderFactory"/> used by this application. /// </summary> public IList<IValueProviderFactory> ValueProviderFactories { get; } /// <summary> /// Gets or sets the SSL port that is used by this application when <see cref="RequireHttpsAttribute"/> /// is used. If not set the port won't be specified in the secured URL e.g. https://localhost/path. /// </summary> public int? SslPort { get; set; } /// <summary> /// Gets or sets the default value for the Permanent property of <see cref="RequireHttpsAttribute"/>. /// </summary> public bool RequireHttpsPermanent { get; set; } /// <summary> /// Gets or sets the maximum depth to constrain the validation visitor when validating. Set to <see langword="null" /> /// to disable this feature. /// <para> /// <see cref="ValidationVisitor"/> traverses the object graph of the model being validated. For models /// that are very deep or are infinitely recursive, validation may result in stack overflow. /// </para> /// <para> /// When not <see langword="null"/>, <see cref="ValidationVisitor"/> will throw if /// traversing an object exceeds the maximum allowed validation depth. /// </para> /// </summary> /// <value> /// The default value is <c>32</c>. /// </value> public int? MaxValidationDepth { get => _maxValidationDepth; set { if (value != null && value <= 0) { throw new ArgumentOutOfRangeException(nameof(value)); } _maxValidationDepth = value; } } /// <summary> /// Gets or sets a value that determines whether the validation visitor will perform validation of a complex type /// if validation fails for any of its children. /// <seealso cref="ValidationVisitor.ValidateComplexTypesIfChildValidationFails"/> /// </summary> /// <value> /// The default value is <see langword="false"/>. /// </value> public bool ValidateComplexTypesIfChildValidationFails { get; set; } /// <summary> /// Gets or sets a value that determines if MVC will remove the suffix "Async" applied to /// controller action names. /// <para> /// <see cref="ControllerActionDescriptor.ActionName"/> is used to construct the route to the action as /// well as in view lookup. When <see langword="true"/>, MVC will trim the suffix "Async" applied /// to action method names. /// For example, the action name for <c>ProductsController.ListProductsAsync</c> will be /// canonicalized as <c>ListProducts.</c>. Consequently, it will be routeable at /// <c>/Products/ListProducts</c> with views looked up at <c>/Views/Products/ListProducts.cshtml</c>. /// </para> /// <para> /// This option does not affect values specified using using <see cref="ActionNameAttribute"/>. /// </para> /// </summary> /// <value> /// The default value is <see langword="true"/>. /// </value> public bool SuppressAsyncSuffixInActionNames { get; set; } = true; /// <summary> /// Gets or sets the maximum size of a complex collection to model bind. When this limit is reached, the model /// binding system will throw an <see cref="InvalidOperationException"/>. /// </summary> /// <remarks> /// <para> /// When binding a collection, some element binders may succeed unconditionally and model binding may run out /// of memory. This limit constrains such unbounded collection growth; it is a safeguard against incorrect /// model binders and models. /// </para> /// <para> /// This limit does not <em>correct</em> the bound model. The <see cref="InvalidOperationException"/> instead /// informs the developer of an issue in their model or model binder. The developer must correct that issue. /// </para> /// <para> /// This limit does not apply to collections of simple types. When /// <see cref="CollectionModelBinder{TElement}"/> relies entirely on <see cref="IValueProvider"/>s, it cannot /// create collections larger than the available data. /// </para> /// <para> /// A very high value for this option (<c>int.MaxValue</c> for example) effectively removes the limit and is /// not recommended. /// </para> /// </remarks> /// <value>The default value is <c>1024</c>, matching <see cref="FormReader.DefaultValueCountLimit"/>.</value> public int MaxModelBindingCollectionSize { get => _maxModelBindingCollectionSize; set { // Disallowing an empty collection would cause the CollectionModelBinder to throw unconditionally. if (value <= 0) { throw new ArgumentOutOfRangeException(nameof(value)); } _maxModelBindingCollectionSize = value; } } /// <summary> /// Gets or sets the maximum recursion depth of the model binding system. The /// <see cref="DefaultModelBindingContext"/> will throw an <see cref="InvalidOperationException"/> if more than /// this number of <see cref="IModelBinder"/>s are on the stack. That is, an attempt to recurse beyond this /// level will fail. /// </summary> /// <remarks> /// <para> /// For some self-referential models, some binders may succeed unconditionally and model binding may result in /// stack overflow. This limit constrains such unbounded recursion; it is a safeguard against incorrect model /// binders and models. This limit also protects against very deep model type hierarchies lacking /// self-references. /// </para> /// <para> /// This limit does not <em>correct</em> the bound model. The <see cref="InvalidOperationException"/> instead /// informs the developer of an issue in their model. The developer must correct that issue. /// </para> /// <para> /// A very high value for this option (<c>int.MaxValue</c> for example) effectively removes the limit and is /// not recommended. /// </para> /// </remarks> /// <value>The default value is <c>32</c>, matching the default <see cref="MaxValidationDepth"/> value.</value> public int MaxModelBindingRecursionDepth { get => _maxModelBindingRecursionDepth; set { // Disallowing one model binder (if supported) would cause the model binding system to throw // unconditionally. DefaultModelBindingContext always allows a top-level binder i.e. its own creation. if (value <= 1) { throw new ArgumentOutOfRangeException(nameof(value)); } _maxModelBindingRecursionDepth = value; } } /// <summary> /// Gets the <see cref="JsonSerializerOptions"/> used by <see cref="SystemTextJsonInputFormatter"/> and /// <see cref="SystemTextJsonOutputFormatter"/>. /// </summary> public JsonSerializerOptions SerializerOptions { get; } = new JsonSerializerOptions { // Limit the object graph we'll consume to a fixed depth. This prevents stackoverflow exceptions // from deserialization errors that might occur from deeply nested objects. // This value is the same for model binding and Json.Net's serialization. MaxDepth = DefaultMaxModelBindingRecursionDepth, // Use camel casing for properties PropertyNamingPolicy = JsonNamingPolicy.CamelCase, }; IEnumerator<ICompatibilitySwitch> IEnumerable<ICompatibilitySwitch>.GetEnumerator() => _switches.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => _switches.GetEnumerator(); } }
47.494792
126
0.628633
[ "Apache-2.0" ]
Deckhandfirststar01/AspNetCore
src/Mvc/Mvc.Core/src/MvcOptions.cs
18,238
C#
// // MRNativeGroup.cs // // Author: // Steve Jakab <> // // Copyright (c) 2016 Steve Jakab // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Collections; using System.Collections.Generic; namespace PortableRealm { public class MRNativeGroup { #region Properties public MRNative this[int index] { get { return mMembers[index]; } set{ mMembers[index] = value; } } #endregion #region Methods public MRNativeGroup () { } #endregion #region Members private List<MRNative> mMembers = new List<MRNative>(); private bool mHireAsGroup; private bool spawnAtStart; private MRDwelling.eDwelling[] mSpawnLocations; #endregion } }
24.927536
80
0.741279
[ "MIT" ]
portablemagicrealm/portablerealm
Assets/Standard Assets (Mobile)/Scripts/Denizens/MRNativeGroup.cs
1,722
C#
using System; using System.Collections; using System.Collections.Generic; using EnTTSharp.Entities.Helpers; using EnTTSharp.Entities.Pools; namespace EnTTSharp.Entities { public abstract class MultiViewBase<TEntityKey, TEnumerator> : IEntityView<TEntityKey> where TEnumerator : IEnumerator<TEntityKey> where TEntityKey: IEntityKey { readonly EventHandler<TEntityKey> onCreated; readonly EventHandler<TEntityKey> onDestroyed; protected readonly List<IReadOnlyPool<TEntityKey>> Sets; /// <summary> /// Use this as a general fallback during the construction of /// subclasses, where it may not yet be safe to use the overloaded /// 'Contains' method. /// </summary> protected readonly Func<TEntityKey, bool> IsMemberPredicate; public bool AllowParallelExecution { get; set; } protected MultiViewBase(IEntityPoolAccess<TEntityKey> registry, IReadOnlyList<IReadOnlyPool<TEntityKey>> entries) { this.Registry = registry ?? throw new ArgumentNullException(nameof(registry)); if (entries == null || entries.Count == 0) { throw new ArgumentException(); } onCreated = OnCreated; onDestroyed = OnDestroyed; this.Sets = new List<IReadOnlyPool<TEntityKey>>(entries); foreach (var pool in Sets) { pool.Destroyed += onDestroyed; pool.Created += onCreated; } IsMemberPredicate = IsMember; } ~MultiViewBase() { Disposing(false); } public event EventHandler<TEntityKey> Destroyed; public event EventHandler<TEntityKey> Created; protected virtual void OnCreated(object sender, TEntityKey e) { if (Contains(e)) { Created?.Invoke(sender, e); } } protected virtual void OnDestroyed(object sender, TEntityKey e) { var countContained = 0; foreach (var pool in Sets) { if (pool.Contains(e)) { countContained += 1; } } if (countContained == Sets.Count - 1) { Destroyed?.Invoke(sender, e); } } public void Reserve(int capacity) { foreach (var pool in Sets) { pool.Reserve(capacity); } } protected IEntityPoolAccess<TEntityKey> Registry { get; } public void RemoveComponent<TComponent>(TEntityKey entity) { Registry.RemoveComponent<TComponent>(entity); } public bool ReplaceComponent<TComponent>(TEntityKey entity, in TComponent c) { return Registry.ReplaceComponent(entity, in c); } public virtual void Respect<TComponent>() { // adhoc views ignore the respect command. } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } IEnumerator<TEntityKey> IEnumerable<TEntityKey>.GetEnumerator() { return GetEnumerator(); } public abstract TEnumerator GetEnumerator(); public abstract int EstimatedSize { get; } protected bool IsMember(TEntityKey e) { foreach (var set in Sets) { if (!set.Contains(e)) { return false; } } return true; } public void Reset(TEntityKey entity) { Registry.Reset(entity); } public virtual bool Contains(TEntityKey e) { return IsMember(e); } public bool IsValid(TEntityKey entity) { return Registry.IsValid(entity); } public bool IsOrphan(TEntityKey entity) { return Registry.IsOrphan(entity); } public void Apply(ViewDelegates.Apply<TEntityKey> bulk) { var p = EntityKeyListPool<TEntityKey>.Reserve(this); try { foreach (var e in p) { bulk(this, e); } } finally { EntityKeyListPool<TEntityKey>.Release(p); } } public void ApplyWithContext<TContext>(TContext c, ViewDelegates.ApplyWithContext<TEntityKey, TContext> bulk) { var p = EntityKeyListPool<TEntityKey>.Reserve(this); try { foreach (var e in p) { bulk(this, c, e); } } finally { EntityKeyListPool<TEntityKey>.Release(p); } } public bool GetComponent<TComponent>(TEntityKey entity, out TComponent data) { return Registry.GetComponent(entity, out data); } public void WriteBack<TComponent>(TEntityKey entity, in TComponent data) { Registry.WriteBack(entity, in data); } public void AssignOrReplace<TComponent>(TEntityKey entity) { Registry.AssignOrReplace<TComponent>(entity); } public void AssignOrReplace<TComponent>(TEntityKey entity, TComponent c) { Registry.AssignOrReplace(entity, c); } public void AssignOrReplace<TComponent>(TEntityKey entity, in TComponent c) { Registry.AssignOrReplace(entity, in c); } public bool HasTag<TTag>() { return Registry.HasTag<TTag>(); } public void AttachTag<TTag>(TEntityKey entity) { Registry.AttachTag<TTag>(entity); } public void AttachTag<TTag>(TEntityKey entity, in TTag tag) { Registry.AttachTag(entity, in tag); } public void RemoveTag<TTag>() { Registry.RemoveTag<TTag>(); } public bool TryGetTag<TTag>(out TEntityKey k, out TTag tag) { return Registry.TryGetTag(out k, out tag); } public bool HasComponent<TOtherComponent>(TEntityKey entity) { return Registry.HasComponent<TOtherComponent>(entity); } public TOtherComponent AssignComponent<TOtherComponent>(TEntityKey entity) { return Registry.AssignComponent<TOtherComponent>(entity); } public void AssignComponent<TOtherComponent>(TEntityKey entity, in TOtherComponent c) { Registry.AssignComponent(entity, in c); } TOtherComponent IEntityViewControl<TEntityKey>.AssignOrReplace<TOtherComponent>(TEntityKey entity) { return Registry.AssignOrReplace<TOtherComponent>(entity); } public virtual void CopyTo(RawList<TEntityKey> k) { k.Clear(); k.Capacity = Math.Max(k.Capacity, EstimatedSize); foreach (var e in this) { k.Add(e); } } public void Dispose() { Disposing(true); GC.SuppressFinalize(this); } protected bool Disposed { get; private set; } protected virtual void Disposing(bool disposing) { if (Disposed) { return; } Disposed = true; foreach (var pool in Sets) { pool.Destroyed -= onDestroyed; pool.Created -= onCreated; } } protected static IReadOnlyPool<TEntityKey> FindMinimumEntrySet(IReadOnlyList<IReadOnlyPool<TEntityKey>> sets) { IReadOnlyPool<TEntityKey> s = null; var count = int.MaxValue; foreach (var set in sets) { if (set.Count < count) { s = set; count = s.Count; } } if (s == null) { throw new ArgumentException(); } return s; } } }
27.346278
117
0.523314
[ "MIT" ]
RabbitStewDio/EnTTSharp
src/EnTTSharp/Entities/MultiViewBase.cs
8,452
C#
#region (c) 2010-2011 Lokad - CQRS for Windows Azure - New BSD License // Copyright (c) Lokad 2010-2011, http://www.lokad.com // This code is released as Open Source under the terms of the New BSD Licence #endregion using System; using System.Collections.Generic; using Autofac; using Autofac.Core; using Lokad.Cqrs.Core.Dispatch; using Lokad.Cqrs.Core.Envelope; using Lokad.Cqrs.Core.Outbox; using Lokad.Cqrs.Core.Reactive; using Lokad.Cqrs.Core.Serialization; using Lokad.Cqrs.Core; using Lokad.Cqrs.Feature.DirectoryDispatch; using Lokad.Cqrs.Feature.MemoryPartition; // ReSharper disable UnusedMethodReturnValue.Global namespace Lokad.Cqrs.Build.Engine { /// <summary> /// Fluent API for creating and configuring <see cref="CqrsEngineHost"/> /// </summary> public class CqrsEngineBuilder : HideObjectMembersFromIntelliSense, IAdvancedEngineBuilder { readonly SerializationContractRegistry _dataSerialization = new SerializationContractRegistry(); IEnvelopeSerializer _envelopeSerializer = new EnvelopeSerializerWithDataContracts(); Func<Type[], IDataSerializer> _dataSerializer = types => new DataSerializerWithDataContracts(types); readonly StorageModule _storage = new StorageModule(); Action<IComponentRegistry, SerializationContractRegistry> _directory; public CqrsEngineBuilder() { // default _directory = (registry, contractRegistry) => new DispatchDirectoryModule().Configure(registry, contractRegistry); _activators.Add(context => new MemoryQueueWriterFactory(context.Resolve<MemoryAccount>())); } readonly IList<Func<IComponentContext, IQueueWriterFactory>> _activators = new List<Func<IComponentContext, IQueueWriterFactory>>(); readonly List<IObserver<ISystemEvent>> _observers = new List<IObserver<ISystemEvent>> { new ImmediateTracingObserver() }; void IAdvancedEngineBuilder.CustomDataSerializer(Func<Type[], IDataSerializer> serializer) { _dataSerializer = serializer; } void IAdvancedEngineBuilder.CustomEnvelopeSerializer(IEnvelopeSerializer serializer) { _envelopeSerializer = serializer; } void IAdvancedEngineBuilder.RegisterQueueWriterFactory(Func<IComponentContext,IQueueWriterFactory> activator) { _activators.Add(activator); } readonly List<IModule> _moduleEnlistments = new List<IModule>(); void IAdvancedEngineBuilder.RegisterModule(IModule module) { _moduleEnlistments.Add(module); } /// <summary> /// Configures the message domain for the instance of <see cref="CqrsEngineHost"/>. /// </summary> /// <param name="config">configuration syntax.</param> /// <returns>same builder for inline multiple configuration statements</returns> public void Domain(Action<DispatchDirectoryModule> config) { _directory = (registry, contractRegistry) => { var m = new DispatchDirectoryModule(); config(m); m.Configure(registry, contractRegistry); }; } readonly ContainerBuilder _builder = new ContainerBuilder(); void IAdvancedEngineBuilder.ConfigureContainer(Action<ContainerBuilder> build) { build(_builder); } void IAdvancedEngineBuilder.RegisterObserver(IObserver<ISystemEvent> observer) { _observers.Add(observer); } IList<IObserver<ISystemEvent>> IAdvancedEngineBuilder.Observers { get { return _observers; } } public void Memory(Action<MemoryModule> configure) { var m = new MemoryModule(); configure(m); Advanced.RegisterModule(m); } public void File(Action<FileModule> configure) { var m = new FileModule(); configure(m); Advanced.RegisterModule(m); } /// <summary> /// Adds configuration to the storage module. /// </summary> /// <param name="configure">The configure.</param> public void Storage(Action<StorageModule> configure) { configure(_storage); } /// <summary> /// Builds this <see cref="CqrsEngineHost"/>. /// </summary> /// <returns>new instance of cloud engine host</returns> public CqrsEngineHost Build() { // nonconditional registrations // System presets _builder.RegisterType<DispatcherProcess>(); _builder.RegisterInstance(new MemoryAccount()); foreach (var module in _moduleEnlistments) { _builder.RegisterModule(module); } var container = _builder.Build(); var system = new SystemObserver(_observers.ToArray()); var reg = container.ComponentRegistry; Configure(reg, system); var processes = container.Resolve<IEnumerable<IEngineProcess>>(); var scope = container.Resolve<ILifetimeScope>(); var host = new CqrsEngineHost(scope, system, processes); host.Initialize(); return host; } void Configure(IComponentRegistry reg, ISystemObserver system) { reg.Register(system); // domain should go before serialization _directory(reg, _dataSerialization); _storage.Configure(reg); var types = _dataSerialization.GetAndMakeReadOnly(); var dataSerializer = _dataSerializer(types); var streamer = new EnvelopeStreamer(_envelopeSerializer, dataSerializer); reg.Register(BuildRegistry); reg.Register(dataSerializer); reg.Register<IEnvelopeStreamer>(c => streamer); reg.Register(new MessageDuplicationManager()); } QueueWriterRegistry BuildRegistry(IComponentContext c) { var r = new QueueWriterRegistry(); foreach (var activator in _activators) { var factory = activator(c); r.Add(factory); } return r; } public IAdvancedEngineBuilder Advanced { get { return this; } } } }
33.9801
141
0.595315
[ "BSD-3-Clause" ]
abdullin/lokad-cqrs
Framework/Lokad.Cqrs.Portable/Build/Engine/CqrsEngineBuilder.cs
6,830
C#
using NUnit.Framework; using NLog; using SmartBulkCopy; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using System; using DotNetEnv; namespace SmartBulkCopy.Tests { public class ClusteredColumnstoreTests: BaseTests { [Test] public async Task ClusteredColumnstore_Small() { var tar = await AnalyzeTable("schema1.clustered_columnstore"); Assert.AreEqual(AnalysisOutcome.Success, tar.Outcome); Assert.IsInstanceOf(typeof(NoPartitionsCopyInfo), tar.CopyInfo[0]); Assert.AreEqual(1, tar.CopyInfo.Count); Assert.AreEqual(OrderHintType.None, tar.CopyInfo[0].OrderHintType); Assert.AreEqual("", tar.CopyInfo[0].SourceTableInfo.PrimaryIndex.GetOrderByString()); Assert.AreEqual("", tar.CopyInfo[0].SourceTableInfo.PrimaryIndex.GetPartitionByString()); } [Test] public async Task ClusteredColumnstore_Big() { var tar = await AnalyzeTable("dbo.LINEITEM_CLUSTERED_COLUMNSTORE"); Assert.AreEqual(AnalysisOutcome.Success, tar.Outcome); Assert.IsInstanceOf(typeof(LogicalPartitionCopyInfo), tar.CopyInfo[0]); Assert.AreEqual(3, tar.CopyInfo.Count); Assert.AreEqual(OrderHintType.None, tar.CopyInfo[0].OrderHintType); Assert.AreEqual("", tar.CopyInfo[0].SourceTableInfo.PrimaryIndex.GetOrderByString()); Assert.AreEqual("", tar.CopyInfo[0].SourceTableInfo.PrimaryIndex.GetPartitionByString()); } [Test] public async Task ClusteredColumnstore_Big_Partitioned() { var tar = await AnalyzeTable("dbo.LINEITEM_CLUSTERED_COLUMNSTORE_PARTITIONED"); Assert.AreEqual(AnalysisOutcome.Success, tar.Outcome); Assert.IsInstanceOf(typeof(PhysicalPartitionCopyInfo), tar.CopyInfo[0]); Assert.AreEqual(85, tar.CopyInfo.Count); Assert.AreEqual(OrderHintType.PartionKeyOnly, tar.CopyInfo[0].OrderHintType); Assert.AreEqual("", tar.CopyInfo[0].SourceTableInfo.PrimaryIndex.GetOrderByString()); Assert.AreEqual("L_COMMITDATE", tar.CopyInfo[0].SourceTableInfo.PrimaryIndex.GetPartitionByString()); } } }
43.169811
113
0.681818
[ "MIT" ]
Splaxi/smartbulkcopy
tests/ClusteredColumnstore.cs
2,288
C#
using System; using System.Collections.Generic; using Kuni.Core.Models; using System.Windows.Input; using MvvmCross.ViewModels; using MvvmCross; using Kuni.Core.Services.Abstract; using System.Threading.Tasks; using Kuni.Core.Models.DB; using Newtonsoft.Json; using Kuni.Core.Providers.LocalDBProvider; using System.Linq; namespace Kuni.Core.ViewModels.iOSSpecific { public class iCatalogDetailViewModel : BaseViewModel { #region Private Variables IProductsService _productService; ILocalDbProvider _dbProvider; #endregion #region Constructor Implementation public iCatalogDetailViewModel (IProductsService productService, ILocalDbProvider dbProvider) { _productService = productService; _dbProvider = dbProvider; } public void Init (int productId) { this.ProductId = productId; PopulateProductData (); } #endregion #region Properties private int _productId; public int ProductId { get{ return _productId; } set { _productId = value; RaisePropertyChanged (() => ProductId); } } private int _imageCount; public int ImageCount { get{ return _imageCount; } set { _imageCount = _imageUrls.Count; RaisePropertyChanged (() => ImageCount); ImageCountName = string.Format ("{0} სურათი", _imageCount); } } private string _imageCountName; public string ImageCountName { get { return _imageCountName; } set { _imageCountName = value; RaisePropertyChanged (() => ImageCountName); } } private List<string> _imageUrls; public List<string> ImageUrls { get { return _imageUrls; } set { _imageUrls = value; RaisePropertyChanged (() => ImageUrls); } } private string _currentImageUrl; public string CurrentImageUrl { get{ return _currentImageUrl; } set { _currentImageUrl = value; RaisePropertyChanged (() => CurrentImageUrl); } } private int _productTypeId; public int ProductTypeID { get{ return _productTypeId; } set { _productTypeId = value; RaisePropertyChanged (() => ProductTypeID); } } private string _productName; public string ProductName { get{ return _productName; } set { _productName = value; RaisePropertyChanged (() => ProductName); } } private string _productDesctiption; public string ProductDescription { get{ return _productDesctiption; } set { _productDesctiption = value; RaisePropertyChanged (() => ProductDescription); } } private int _productPrice; public int ProductPrice { get{ return _productPrice; } set { _productPrice = value; RaisePropertyChanged (() => ProductPrice); } } private string _catalogID; public string CatalogID { get{ return _catalogID; } set { _catalogID = value; RaisePropertyChanged (() => CatalogID); } } private int _productDiscountPercent; public int ProductDiscountPercent { get{ return _productDiscountPercent; } set { _productDiscountPercent = value; RaisePropertyChanged (() => ProductDiscountPercent); } } private bool _discountVisibility; public bool DiscountVisibility { get{ return _discountVisibility; } set { _discountVisibility = value; RaisePropertyChanged (() => DiscountVisibility); } } private List<DiscountModel> _userDiscounts; public List<DiscountModel> UserDiscounts { get{ return _userDiscounts; } set { _userDiscounts = value; RaisePropertyChanged (() => UserDiscounts); } } private int _productOldPrice; public int ProductOldPrice { get{ return _productOldPrice; } set { _productOldPrice = value; RaisePropertyChanged (() => ProductOldPrice); } } private List<DeliveryMethod> _deliveryMethods; public List<DeliveryMethod> DeliveryMethods { get{ return _deliveryMethods; } set { _deliveryMethods = value; RaisePropertyChanged (() => DeliveryMethods); } } #endregion #region Methods public void GoToBuyProduct (DeliveryMethod deliveryMethod) { NavigationCommand<iBuyProductViewModel> (new { currentImageUrl = _currentImageUrl, productName = _productName, productID = _productId, productPrice = _productPrice, deliveryMethodId = deliveryMethod.DeliveryMethodId, productTypeID = _productTypeId, note = deliveryMethod.Note, discounts = JsonConvert.SerializeObject (_userDiscounts) }); } private void PopulateProductData () { InvokeOnMainThread (() => { _dialog.ShowProgressDialog (ApplicationStrings.Loading); }); Task.Run (async() => { UserInfo currentUser = _dbProvider.Get<UserInfo> ().FirstOrDefault (); var productInfo = await _productService.GetProductByID (ProductId, int.Parse (currentUser.UserId)); InvokeOnMainThread (() => { _dialog.DismissProgressDialog (); }); if (productInfo.Success) { if (productInfo.Result != null) { this.ProductName = productInfo.Result.ProductName; if (productInfo.Result.ProductImages.Count != 0) this.CurrentImageUrl = productInfo.Result.ProductImages [0]; this.ProductTypeID = productInfo.Result.ProductTypeID; this.ProductPrice = productInfo.Result.DiscountedPrice; this.ProductDiscountPercent = productInfo.Result.DiscountedPercent; this.ImageUrls = productInfo.Result.ProductImages; this.ImageCount = ImageUrls.Count; this.ProductDescription = productInfo.Result.PoductDescription; this.ProductOldPrice = productInfo.Result.ProductPrice; this.CatalogID = productInfo.Result.CatalogID; this.DeliveryMethods = productInfo.Result.DeliveryMethods; this.UserDiscounts = productInfo.Result.UserDiscounts; } } else { if (!string.IsNullOrWhiteSpace (productInfo.DisplayMessage)) { InvokeOnMainThread (() => { _dialog.ShowToast (productInfo.DisplayMessage); }); } } }); } #endregion } }
23.308594
103
0.698676
[ "MIT" ]
nininea2/unicard_app_base
Kuni.Core/ViewModels/iOSSpecific/iCatalogDetailViewModel.cs
5,981
C#
/* * Original author: Brendan MacLean <brendanx .at. u.washington.edu>, * MacCoss Lab, Department of Genome Sciences, UW * * Copyright 2012 University of Washington - Seattle, WA * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Windows.Forms; using pwiz.Common.Collections; using pwiz.Skyline.Controls.SeqNode; using pwiz.Skyline.Model; using pwiz.Skyline.Properties; using pwiz.Skyline.Util; using pwiz.Skyline.Util.Extensions; using ZedGraph; namespace pwiz.Skyline.Controls.Graphs { public abstract class SummaryBarGraphPaneBase : SummaryGraphPane { public class ToolTipImplementation : ITipProvider { public class TargetCurveList : List<CurveItem> { private SummaryBarGraphPaneBase _parent; public TargetCurveList(SummaryBarGraphPaneBase parent) { _parent = parent; } public new void Add(CurveItem curve) { //all targets must be on the same axis if (Count > 0) Assume.AreEqual(base[0].GetYAxis(_parent), curve.GetYAxis(_parent), @"All target curves for a tooltip must be on the same axis."); base.Add(curve); } public CurveItem ClearAndAdd(CurveItem curve) { Clear(); Add(curve); return curve; } public Axis GetYAxis() { if (Count == 0) return null; return base[0].GetYAxis(_parent); } public bool IsTarget(CurveItem curve) { return this.Any(c => ReferenceEquals(c, curve)); } } private SummaryBarGraphPaneBase _parent; private bool _isVisible; private NodeTip _tip; private TableDesc _table; internal RenderTools RenderTools = new RenderTools(); public int ReplicateIndex { get; private set; } public TargetCurveList TargetCurves { get; private set; } public ToolTipImplementation(SummaryBarGraphPaneBase parent) { _parent = parent; TargetCurves = new TargetCurveList(parent); } public ITipProvider TipProvider { get { return this; } } bool ITipProvider.HasTip => true; Size ITipProvider.RenderTip(Graphics g, Size sizeMax, bool draw) { var size = _table.CalcDimensions(g); if (draw) _table.Draw(g); return new Size((int)size.Width + 2, (int)size.Height + 2); } public void AddLine(string description, string data) { if (_table == null) _table = new TableDesc(); _table.AddDetailRow(description, data, RenderTools); } public void ClearData() { _table?.Clear(); } public void Draw(int dataIndex, Point cursorPos) { if (_isVisible) { if (ReplicateIndex == dataIndex) return; Hide(); } if (_table == null || _table.Count == 0 || !TargetCurves.Any()) return; ReplicateIndex = dataIndex; var basePoint = new UserPoint(dataIndex + 1, _parent.GetToolTipDataSeries()[ReplicateIndex] / _parent.YScale, _parent, TargetCurves.GetYAxis() ?? _parent.YAxis); using (var g = _parent.GraphSummary.GraphControl.CreateGraphics()) { var size = _table.CalcDimensions(g); var offset = new Size(0, -(int)(size.Height + size.Height / _table.Count)); if (_tip == null) _tip = new NodeTip(_parent); _tip.SetTipProvider(TipProvider, new Rectangle(basePoint.Screen(offset), new Size()), cursorPos); } _isVisible = true; } public void Hide() { if (_isVisible) { _tip?.HideTip(); _isVisible = false; } } #region Test Methods public List<string> TipLines { get { return _table.Select((rowDesc) => string.Join(TextUtil.SEPARATOR_TSV_STR, rowDesc.Select(cell => cell.Text)) ).ToList(); } } #endregion private class UserPoint { private GraphPane _graph; private Axis _yAxis; public int X { get; private set; } public float Y { get; private set; } public UserPoint(int x, float y, GraphPane graph) { X = x; Y = y; _graph = graph; _yAxis = graph.YAxis; } public UserPoint(int x, float y, GraphPane graph, Axis yAxis) : this(x, y, graph) { if(yAxis is Y2Axis) _yAxis = yAxis; } public PointF User() { return new PointF(X, Y); } public Point Screen() { return new Point( (int)_graph.XAxis.Scale.Transform(X), (int)_yAxis.Scale.Transform(Y)); } public Point Screen(Size OffsetScreen) { return new Point( (int)(_graph.XAxis.Scale.Transform(X) + OffsetScreen.Width), (int)(_yAxis.Scale.Transform(Y) + OffsetScreen.Height)); } public PointF PF() { return new PointF( _graph.XAxis.Scale.Transform(X) / _graph.Rect.Width, _yAxis.Scale.Transform(Y) / _graph.Rect.Height); } public PointD PF(SizeF OffsetPF) { return new PointD( _graph.XAxis.Scale.Transform(X) / _graph.Rect.Width + OffsetPF.Width, _yAxis.Scale.Transform(Y) / _graph.Rect.Height + OffsetPF.Height); } } } public virtual void PopulateTooltip(int index){} /// <summary> /// Override if you need to implement tooltips in your graph. /// </summary> /// <returns>A list of y-coordinates where tooltips should be displayed. /// List index is the replicate index.</returns> public virtual ImmutableList<float> GetToolTipDataSeries() { //This provides a clear error message if this method is invoked by mistake in a class that doesn't implement tooltips. throw new NotImplementedException(@"Method GetToolTipDataSeries is not implemented."); } /// <summary> /// Additional scaling factor for tooltip's vertical position. /// </summary> public virtual float YScale { get { return 1.0f; } } /// <summary> /// Create a new tooltip instance in the child class constructor if you /// want to show thw tooltips. /// </summary> public ToolTipImplementation ToolTip { get; protected set; } protected static bool ShowSelection { get { return Settings.Default.ShowReplicateSelection; } } protected static IList<Color> COLORS_TRANSITION {get { return GraphChromatogram.COLORS_LIBRARY; }} protected static IList<Color> COLORS_GROUPS {get { return GraphChromatogram.COLORS_GROUPS; }} protected static int GetColorIndex(TransitionGroupDocNode nodeGroup, int countLabelTypes, ref Adduct charge, ref int iCharge) { return GraphChromatogram.GetColorIndex(nodeGroup, countLabelTypes, ref charge, ref iCharge); } protected SummaryBarGraphPaneBase(GraphSummary graphSummary) : base(graphSummary) { _axisLabelScaler = new AxisLabelScaler(this); } public void Clear() { CurveList.Clear(); GraphObjList.Clear(); ToolTip?.Hide(); } protected virtual int FirstDataIndex { get { return 0; } } protected abstract int SelectedIndex { get; } protected abstract IdentityPath GetIdentityPath(CurveItem curveItem, int barIndex); public override bool HandleKeyDownEvent(object sender, KeyEventArgs keyEventArgs) { switch (keyEventArgs.KeyCode) { case Keys.Left: case Keys.Up: ChangeSelection(SelectedIndex - 1, null); return true; case Keys.Right: case Keys.Down: ChangeSelection(SelectedIndex + 1, null); return true; } return false; } protected abstract void ChangeSelection(int selectedIndex, IdentityPath identityPath); public override bool HandleMouseMoveEvent(ZedGraphControl sender, MouseEventArgs mouseEventArgs) { if (mouseEventArgs.Button != MouseButtons.None) return base.HandleMouseMoveEvent(sender, mouseEventArgs); CurveItem nearestCurve; int iNearest; if (!FindNearestPoint(new PointF(mouseEventArgs.X, mouseEventArgs.Y), out nearestCurve, out iNearest)) { ToolTip?.Hide(); var axis = GetNearestXAxis(sender, mouseEventArgs); if (axis != null) { GraphSummary.Cursor = Cursors.Hand; return true; } return false; } if (ToolTip != null && ToolTip.TargetCurves.IsTarget(nearestCurve)) { PopulateTooltip(iNearest); ToolTip.Draw(iNearest, mouseEventArgs.Location); sender.Cursor = Cursors.Hand; return true; } else ToolTip?.Hide(); IdentityPath identityPath = GetIdentityPath(nearestCurve, iNearest); if (identityPath == null) { return false; } GraphSummary.Cursor = Cursors.Hand; return true; } public override void HandleMouseOutEvent(object sender, EventArgs e) { ToolTip?.Hide(); } private XAxis GetNearestXAxis(ZedGraphControl sender, MouseEventArgs mouseEventArgs) { using (Graphics g = sender.CreateGraphics()) { object nearestObject; int index; if (FindNearestObject(new PointF(mouseEventArgs.X, mouseEventArgs.Y), g, out nearestObject, out index)) { var axis = nearestObject as XAxis; if (axis != null) return axis; } } return null; } public override bool HandleMouseDownEvent(ZedGraphControl sender, MouseEventArgs mouseEventArgs) { CurveItem nearestCurve; int iNearest; var axis = GetNearestXAxis(sender, mouseEventArgs); if (axis != null) { iNearest = (int)axis.Scale.ReverseTransform(mouseEventArgs.X - axis.MajorTic.Size); if (iNearest < 0) return false; ChangeSelection(iNearest, GraphSummary.StateProvider.SelectedPath); return true; } if (!FindNearestPoint(new PointF(mouseEventArgs.X, mouseEventArgs.Y), out nearestCurve, out iNearest)) { return false; } IdentityPath identityPath = GetIdentityPath(nearestCurve, iNearest); if (identityPath == null) { return false; } ChangeSelection(iNearest, identityPath); return true; } public override void OnClose(EventArgs e) { if (ToolTip != null) { ToolTip.Hide(); ToolTip.RenderTools.Dispose(); } } public override void Draw(Graphics g) { _chartBottom = Chart.Rect.Bottom; HandleResizeEvent(); base.Draw(g); if (IsRedrawRequired(g)) base.Draw(g); } public override void HandleResizeEvent() { ScaleAxisLabels(); } protected virtual bool IsRedrawRequired(Graphics g) { // Have to call HandleResizeEvent twice, since the X-scale may not be up // to date before calling Draw. If nothing changes, this will be a no-op HandleResizeEvent(); return (Chart.Rect.Bottom != _chartBottom); } private float _chartBottom; protected AxisLabelScaler _axisLabelScaler; protected string[] OriginalXAxisLabels { get { return _axisLabelScaler.OriginalTextLabels ?? XAxis.Scale.TextLabels; } set { _axisLabelScaler.OriginalTextLabels = value; } } protected void ScaleAxisLabels() { _axisLabelScaler.FirstDataIndex = FirstDataIndex; _axisLabelScaler.ScaleAxisLabels(); } protected bool IsRepeatRemovalAllowed { get { return _axisLabelScaler.IsRepeatRemovalAllowed; } set { _axisLabelScaler.IsRepeatRemovalAllowed = value; } } #region Test Support Methods public string[] GetOriginalXAxisLabels() { return _axisLabelScaler.OriginalTextLabels ?? XAxis.Scale.TextLabels; } #endregion } }
35.447727
155
0.510739
[ "Apache-2.0" ]
vagisha/pwiz
pwiz_tools/Skyline/Controls/Graphs/SummaryBarGraphPaneBase.cs
15,597
C#
using System; using System.Collections.Generic; using System.Linq.Expressions; using UnityEditor; using UnityEngine; using Cinemachine.Utility; namespace Cinemachine.Editor { [CustomEditor(typeof(CinemachineGroupComposer))] internal class CinemachineGroupComposerEditor : CinemachineComposerEditor { // Specialization private CinemachineGroupComposer MyTarget { get { return target as CinemachineGroupComposer; } } protected string FieldPath<TValue>(Expression<Func<CinemachineGroupComposer, TValue>> expr) { return ReflectionHelpers.GetFieldPath(expr); } protected override List<string> GetExcludedPropertiesInInspector() { List<string> excluded = base.GetExcludedPropertiesInInspector(); CinemachineBrain brain = CinemachineCore.Instance.FindPotentialTargetBrain(MyTarget.VirtualCamera); bool ortho = brain != null ? brain.OutputCamera.orthographic : false; if (ortho) { excluded.Add(FieldPath(x => x.m_AdjustmentMode)); excluded.Add(FieldPath(x => x.m_MinimumFOV)); excluded.Add(FieldPath(x => x.m_MaximumFOV)); excluded.Add(FieldPath(x => x.m_MaxDollyIn)); excluded.Add(FieldPath(x => x.m_MaxDollyOut)); excluded.Add(FieldPath(x => x.m_MinimumDistance)); excluded.Add(FieldPath(x => x.m_MaximumDistance)); } else { excluded.Add(FieldPath(x => x.m_MinimumOrthoSize)); excluded.Add(FieldPath(x => x.m_MaximumOrthoSize)); switch (MyTarget.m_AdjustmentMode) { case CinemachineGroupComposer.AdjustmentMode.DollyOnly: excluded.Add(FieldPath(x => x.m_MinimumFOV)); excluded.Add(FieldPath(x => x.m_MaximumFOV)); break; case CinemachineGroupComposer.AdjustmentMode.ZoomOnly: excluded.Add(FieldPath(x => x.m_MaxDollyIn)); excluded.Add(FieldPath(x => x.m_MaxDollyOut)); excluded.Add(FieldPath(x => x.m_MinimumDistance)); excluded.Add(FieldPath(x => x.m_MaximumDistance)); break; default: break; } } return excluded; } public override void OnInspectorGUI() { if (MyTarget.IsValid && MyTarget.LookAtTargetGroup == null) EditorGUILayout.HelpBox( "The Framing settings will be ignored because the LookAt target is not a kind of CinemachineTargetGroup", MessageType.Info); base.OnInspectorGUI(); } [DrawGizmo(GizmoType.Active | GizmoType.InSelectionHierarchy, typeof(CinemachineGroupComposer))] private static void DrawGroupComposerGizmos(CinemachineGroupComposer target, GizmoType selectionType) { // Show the group bounding box, as viewed from the camera position if (target.LookAtTargetGroup != null) { Matrix4x4 m = Gizmos.matrix; Bounds b = target.LastBounds; Gizmos.matrix = target.LastBoundsMatrix; Gizmos.color = Color.yellow; if (target.VcamState.Lens.Orthographic) Gizmos.DrawWireCube(b.center, b.size); else { float z = b.center.z; Vector3 e = b.extents; Gizmos.DrawFrustum( Vector3.zero, Mathf.Atan2(e.y, z) * Mathf.Rad2Deg * 2, z + e.z, z - e.z, e.x / e.y); } Gizmos.matrix = m; } } } }
41.642105
126
0.555865
[ "MIT" ]
Axedas/hex-game
New Unity Project (1)/Library/PackageCache/com.unity.cinemachine@2.3.4/Editor/Editors/CinemachineGroupComposerEditor.cs
3,956
C#
#nullable disable using Brimborium.Json.Internal; namespace Brimborium.Json.Formatters { // multi dimentional array serialize to [[seq], [seq]] public sealed class TwoDimentionalArrayFormatter<T> : IJsonFormatter<T[,]> { public void Serialize(JsonWriter writer, T[,] value, IJsonFormatterResolver formatterResolver) { if (value == null) { writer.WriteNull(); } else { var formatter = formatterResolver.GetFormatterWithVerify<T>(); var iLength = value.GetLength(0); var jLength = value.GetLength(1); writer.WriteBeginArray(); for (int i = 0; i < iLength; i++) { if (i != 0) writer.WriteValueSeparator(); writer.WriteBeginArray(); for (int j = 0; j < jLength; j++) { if (j != 0) writer.WriteValueSeparator(); formatter.Serialize(writer, value[i, j], formatterResolver); } writer.WriteEndArray(); } writer.WriteEndArray(); } } public T[,] Deserialize(JsonReader reader, IJsonFormatterResolver formatterResolver) { if (reader.ReadIsNull()) return null; var buffer = new ArrayBuffer<ArrayBuffer<T>>(4); var formatter = formatterResolver.GetFormatterWithVerify<T>(); var guessInnerLength = 0; var outerCount = 0; reader.ReadIsBeginArrayWithVerify(); while (!reader.ReadIsEndArrayWithSkipValueSeparator(ref outerCount)) { var innerArray = new ArrayBuffer<T>(guessInnerLength == 0 ? 4 : guessInnerLength); var innerCount = 0; reader.ReadIsBeginArrayWithVerify(); while (!reader.ReadIsEndArrayWithSkipValueSeparator(ref innerCount)) { innerArray.Add(formatter.Deserialize(reader, formatterResolver)); } guessInnerLength = innerArray.Size; buffer.Add(innerArray); } var t = new T[buffer.Size, guessInnerLength]; for (int i = 0; i < buffer.Size; i++) { for (int j = 0; j < guessInnerLength; j++) { t[i, j] = buffer.Buffer[i].Buffer[j]; } } return t; } } public sealed class ThreeDimentionalArrayFormatter<T> : IJsonFormatter<T[,,]> { public void Serialize(JsonWriter writer, T[,,] value, IJsonFormatterResolver formatterResolver) { if (value == null) { writer.WriteNull(); } else { var formatter = formatterResolver.GetFormatterWithVerify<T>(); var iLength = value.GetLength(0); var jLength = value.GetLength(1); var kLength = value.GetLength(2); writer.WriteBeginArray(); for (int i = 0; i < iLength; i++) { if (i != 0) writer.WriteValueSeparator(); writer.WriteBeginArray(); for (int j = 0; j < jLength; j++) { if (j != 0) writer.WriteValueSeparator(); writer.WriteBeginArray(); for (int k = 0; k < kLength; k++) { if (k != 0) writer.WriteValueSeparator(); formatter.Serialize(writer, value[i, j, k], formatterResolver); } writer.WriteEndArray(); } writer.WriteEndArray(); } writer.WriteEndArray(); } } public T[,,] Deserialize(JsonReader reader, IJsonFormatterResolver formatterResolver) { if (reader.ReadIsNull()) return null; var buffer = new ArrayBuffer<ArrayBuffer<ArrayBuffer<T>>>(4); var formatter = formatterResolver.GetFormatterWithVerify<T>(); var guessInnerLength2 = 0; var guessInnerLength = 0; var outerCount = 0; reader.ReadIsBeginArrayWithVerify(); while (!reader.ReadIsEndArrayWithSkipValueSeparator(ref outerCount)) { var innerArray = new ArrayBuffer<ArrayBuffer<T>>(guessInnerLength == 0 ? 4 : guessInnerLength); var innerCount = 0; reader.ReadIsBeginArrayWithVerify(); while (!reader.ReadIsEndArrayWithSkipValueSeparator(ref innerCount)) { var innerArray2 = new ArrayBuffer<T>(guessInnerLength2 == 0 ? 4 : guessInnerLength2); var innerCount2 = 0; reader.ReadIsBeginArrayWithVerify(); while (!reader.ReadIsEndArrayWithSkipValueSeparator(ref innerCount2)) { innerArray2.Add(formatter.Deserialize(reader, formatterResolver)); } guessInnerLength2 = innerArray2.Size; innerArray.Add(innerArray2); } guessInnerLength = innerArray.Size; buffer.Add(innerArray); } var t = new T[buffer.Size, guessInnerLength, guessInnerLength2]; for (int i = 0; i < buffer.Size; i++) { for (int j = 0; j < guessInnerLength; j++) { for (int k = 0; k < guessInnerLength2; k++) { t[i, j, k] = buffer.Buffer[i].Buffer[j].Buffer[k]; } } } return t; } } public sealed class FourDimentionalArrayFormatter<T> : IJsonFormatter<T[,,,]> { public void Serialize(JsonWriter writer, T[,,,] value, IJsonFormatterResolver formatterResolver) { if (value == null) { writer.WriteNull(); } else { var formatter = formatterResolver.GetFormatterWithVerify<T>(); var iLength = value.GetLength(0); var jLength = value.GetLength(1); var kLength = value.GetLength(2); var lLength = value.GetLength(3); writer.WriteBeginArray(); for (int i = 0; i < iLength; i++) { if (i != 0) writer.WriteValueSeparator(); writer.WriteBeginArray(); for (int j = 0; j < jLength; j++) { if (j != 0) writer.WriteValueSeparator(); writer.WriteBeginArray(); for (int k = 0; k < kLength; k++) { if (k != 0) writer.WriteValueSeparator(); writer.WriteBeginArray(); for (int l = 0; l < lLength; l++) { if (l != 0) writer.WriteValueSeparator(); formatter.Serialize(writer, value[i, j, k, l], formatterResolver); } writer.WriteEndArray(); } writer.WriteEndArray(); } writer.WriteEndArray(); } writer.WriteEndArray(); } } public T[,,,] Deserialize(JsonReader reader, IJsonFormatterResolver formatterResolver) { if (reader.ReadIsNull()) return null; var buffer = new ArrayBuffer<ArrayBuffer<ArrayBuffer<ArrayBuffer<T>>>>(4); var formatter = formatterResolver.GetFormatterWithVerify<T>(); var guessInnerLength3 = 0; var guessInnerLength2 = 0; var guessInnerLength = 0; var outerCount = 0; reader.ReadIsBeginArrayWithVerify(); while (!reader.ReadIsEndArrayWithSkipValueSeparator(ref outerCount)) { var innerArray = new ArrayBuffer<ArrayBuffer<ArrayBuffer<T>>>(guessInnerLength == 0 ? 4 : guessInnerLength); var innerCount = 0; reader.ReadIsBeginArrayWithVerify(); while (!reader.ReadIsEndArrayWithSkipValueSeparator(ref innerCount)) { var innerArray2 = new ArrayBuffer<ArrayBuffer<T>>(guessInnerLength2 == 0 ? 4 : guessInnerLength2); var innerCount2 = 0; reader.ReadIsBeginArrayWithVerify(); while (!reader.ReadIsEndArrayWithSkipValueSeparator(ref innerCount2)) { var innerArray3 = new ArrayBuffer<T>(guessInnerLength3 == 0 ? 4 : guessInnerLength3); var innerCount3 = 0; reader.ReadIsBeginArrayWithVerify(); while (!reader.ReadIsEndArrayWithSkipValueSeparator(ref innerCount3)) { innerArray3.Add(formatter.Deserialize(reader, formatterResolver)); } guessInnerLength3 = innerArray3.Size; innerArray2.Add(innerArray3); } guessInnerLength2 = innerArray2.Size; innerArray.Add(innerArray2); } guessInnerLength = innerArray.Size; buffer.Add(innerArray); } var t = new T[buffer.Size, guessInnerLength, guessInnerLength2, guessInnerLength3]; for (int i = 0; i < buffer.Size; i++) { for (int j = 0; j < guessInnerLength; j++) { for (int k = 0; k < guessInnerLength2; k++) { for (int l = 0; l < guessInnerLength3; l++) { t[i, j, k, l] = buffer.Buffer[i].Buffer[j].Buffer[k].Buffer[l]; } } } } return t; } } }
39.022222
124
0.475607
[ "MIT" ]
grimmborium/Brimborium.Json
try1/src/Brimborium.Json/Formatters/MultiDimentionalArrayFormatter.cs
10,538
C#
using System; using System.Threading.Tasks; using Microsoft.Azure.Management.Monitor.Fluent.Models; using Microsoft.Extensions.Logging; using Promitor.Core.Scraping.Configuration.Model; using Promitor.Core.Scraping.Configuration.Model.Metrics.ResourceTypes; using Promitor.Core.Telemetry.Interfaces; using Promitor.Integrations.AzureMonitor; namespace Promitor.Core.Scraping.ResourceTypes { public class ContainerInstanceScraper : Scraper<ContainerInstanceMetricDefinition> { private const string ResourceUriTemplate = "subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.ContainerInstance/containerGroups/{2}"; public ContainerInstanceScraper(AzureMetadata azureMetadata, MetricDefaults metricDefaults, AzureMonitorClient azureMonitorClient, ILogger logger, IExceptionTracker exceptionTracker) : base(azureMetadata, metricDefaults, azureMonitorClient, logger, exceptionTracker) { } protected override async Task<double> ScrapeResourceAsync(string subscriptionId, string resourceGroupName, ContainerInstanceMetricDefinition metricDefinition, AggregationType aggregationType, TimeSpan aggregationInterval) { var resourceUri = string.Format(ResourceUriTemplate, AzureMetadata.SubscriptionId, AzureMetadata.ResourceGroupName, metricDefinition.ContainerGroup); var metricName = metricDefinition.AzureMetricConfiguration.MetricName; var foundMetricValue = await AzureMonitorClient.QueryMetricAsync(metricName, aggregationType, aggregationInterval, resourceUri); return foundMetricValue; } } }
52.451613
229
0.796433
[ "MIT" ]
brandonh-msft/promitor
src/Promitor.Core.Scraping/ResourceTypes/ContainerInstanceScraper.cs
1,628
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class UICollar : MonoBehaviour { [SerializeField, Tooltip("Collar")] private Color _color = Color.white; [SerializeField, Tooltip("イメージリスト")] private List<Image> _imageList = new List<Image>(); [SerializeField, Tooltip("イメージリスト")] private List<Text> _textList = new List<Text>(); private void Awake() { ChangeColor(); } // Start is called before the first frame update void Start() { } private void ChangeColor() { foreach(Image image in _imageList) { image.color = _color; } foreach(Text text in _textList) { text.color = _color; } } // Update is called once per frame void Update() { } }
17.930233
52
0.673152
[ "Unlicense" ]
kurokurogamer/MAKINAS
MACHINA/Assets/Scripts/UI/UICollar.cs
801
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; namespace MyLibrary.Web.Pages { public class ErrorModel : PageModel { public string RequestId { get; set; } public bool ShowRequestId => !string.IsNullOrEmpty(RequestId); [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public void OnGet() { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier; } } }
25.916667
92
0.696141
[ "MIT" ]
msotiroff/Softuni-learning
C# Web Module/CSharp-Web-Asp.Net.Core-MVC/02.BasicsAndRazorPages/src/MyLibrary/MyLibrary.Web/Pages/Error.cshtml.cs
622
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace IdentityServerWithIdentity.Models.ManageViewModels { public class SetPasswordViewModel { [Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)] [DataType(DataType.Password)] [Display(Name = "New password")] public string NewPassword { get; set; } [DataType(DataType.Password)] [Display(Name = "Confirm new password")] [Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")] public string ConfirmPassword { get; set; } public string StatusMessage { get; set; } } }
33.2
125
0.683133
[ "BSD-3-Clause", "MIT" ]
MalikWaseemJaved/presentations
.NETCore/ASP.NETCore/v3.1/Security/IdentityServer/IdentityServerWithIdentity/Models/ManageViewModels/SetPasswordViewModel.cs
832
C#
// MIT License // // Copyright (c) 2019 Peter Malik. (MalikP.) // // File: AbstractClientBuilder.cs // Company: MalikP. // // Repository: https://github.com/peterM/IVAO-Library // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. using System; using MalikP.IVAO.Library.Common.Enums; using MalikP.IVAO.Library.Models.Other; namespace MalikP.IVAO.Library.Models.Clients { public abstract class AbstractClientBuilder<TBuilder> { protected string callsign; protected string vid; protected string name; protected ClientType clientType; protected GPS location; protected string server; protected string protocol; protected DateTime connectionTime; protected string softwareName; protected string softwareVersion; protected AdministrativeRating administrativeVersion; protected int clientRating; public TBuilder WithCallsign(string callsign) { this.callsign = callsign; return GetBuilder(); } public TBuilder WithVID(string vid) { this.vid = vid; return GetBuilder(); } public TBuilder WithName(string name) { this.name = name; return GetBuilder(); } protected TBuilder WithClientType(ClientType clientType) { this.clientType = clientType; return GetBuilder(); } public TBuilder WithLocation(GPS location) { this.location = location; return GetBuilder(); } public TBuilder WithServer(string server) { this.server = server; return GetBuilder(); } public TBuilder WithProtocol(string protocol) { this.protocol = protocol; return GetBuilder(); } public TBuilder WithConnectionTime(DateTime connectionTime) { this.connectionTime = connectionTime; return GetBuilder(); } public TBuilder WithSoftwareName(string softwareName) { this.softwareName = softwareName; return GetBuilder(); } public TBuilder WithSoftwareVersion(string softwareVersion) { this.softwareVersion = softwareVersion; return GetBuilder(); } public TBuilder WithAdministrativeVersion(AdministrativeRating administrativeVersion) { this.administrativeVersion = administrativeVersion; return GetBuilder(); } public TBuilder WithClientRating(int clientRating) { this.clientRating = clientRating; return GetBuilder(); } protected abstract TBuilder GetBuilder(); } }
30.816
93
0.646417
[ "MIT" ]
peterM/IVAO-Library
src/MalikP. IVAO Library/MalikP.IVAO.Library/Models/Clients/AbstractClientBuilder.cs
3,854
C#
using Gallery.Data.Models; namespace Gallery.Data.Repositories { public interface ILoggingRepository : IEntityBaseRepository<Error> { } }
16.888889
70
0.743421
[ "MIT" ]
PiotrKantorowicz1/PhotoGalleryApp
Gallery.Data/Repositories/ILoggingRepository.cs
154
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the cognito-idp-2016-04-18.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.CognitoIdentityProvider.Model { /// <summary> /// Container for the parameters to the GetGroup operation. /// Gets a group. /// /// /// <para> /// Calling this action requires developer credentials. /// </para> /// </summary> public partial class GetGroupRequest : AmazonCognitoIdentityProviderRequest { private string _groupName; private string _userPoolId; /// <summary> /// Gets and sets the property GroupName. /// <para> /// The name of the group. /// </para> /// </summary> [AWSProperty(Required=true, Min=1, Max=128)] public string GroupName { get { return this._groupName; } set { this._groupName = value; } } // Check to see if GroupName property is set internal bool IsSetGroupName() { return this._groupName != null; } /// <summary> /// Gets and sets the property UserPoolId. /// <para> /// The user pool ID for the user pool. /// </para> /// </summary> [AWSProperty(Required=true, Min=1, Max=55)] public string UserPoolId { get { return this._userPoolId; } set { this._userPoolId = value; } } // Check to see if UserPoolId property is set internal bool IsSetUserPoolId() { return this._userPoolId != null; } } }
28.630952
109
0.612058
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/CognitoIdentityProvider/Generated/Model/GetGroupRequest.cs
2,405
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Diagnostics.ContractsLight; using BuildXL.FrontEnd.Script.Evaluator; using BuildXL.FrontEnd.Script.Values; using BuildXL.Utilities; using static BuildXL.Utilities.FormattableStringEx; using LineInfo = TypeScript.Net.Utilities.LineInfo; namespace BuildXL.FrontEnd.Script.Expressions { /// <summary> /// Switch expression clause. /// </summary> public class SwitchExpressionClause : Expression { /// <nodoc/> public bool IsDefaultFallthrough { get; set; } /// <nodoc /> public Expression Match { get; } /// <nodoc /> public Expression Expression { get; } /// <nodoc /> public SwitchExpressionClause( Expression match, Expression expression, LineInfo location) : base(location) { Contract.Requires(match != null); Contract.Requires(expression != null); Match = match; Expression = expression; } /// <nodoc /> public SwitchExpressionClause( Expression expression, LineInfo location) : base(location) { Contract.Requires(expression != null); IsDefaultFallthrough = true; Expression = expression; } /// <nodoc /> public SwitchExpressionClause(DeserializationContext context, LineInfo location) : base(location) { IsDefaultFallthrough = context.Reader.ReadBoolean(); if (!IsDefaultFallthrough) { Match = ReadExpression(context); } Expression = ReadExpression(context); } /// <inheritdoc /> protected override void DoSerialize(BuildXLWriter writer) { writer.Write(IsDefaultFallthrough); if (!IsDefaultFallthrough) { Match.Serialize(writer); } Expression.Serialize(writer); } /// <inheritdoc /> public override void Accept(Visitor visitor) { visitor.Visit(this); } /// <inheritdoc /> public override SyntaxKind Kind => SyntaxKind.SwitchExpressionClause; /// <inheritdoc /> public override string ToDebugString() { var match = IsDefaultFallthrough ? "default" : Match.ToDebugString(); return I($"{match} : {Expression.ToDebugString()}"); } /// <inheritdoc /> protected override EvaluationResult DoEval(Context context, ModuleLiteral env, EvaluationStackFrame frame) { return Expression.Eval(context, env, frame); } } }
29.514851
115
0.558873
[ "MIT" ]
AzureMentor/BuildXL
Public/Src/FrontEnd/Script/Ast/Expressions/SwitchExpressionClause.cs
2,981
C#
using System.Reflection; [assembly: AssemblyTitle("Lex.Db for .Net 4.6")]
15.4
48
0.714286
[ "MIT" ]
demigor/lex.db
lib/Lex.Db.Net46/Properties/AssemblyInfo.cs
79
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace TinyNavigationHelper.WPF.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
35.580645
151
0.572983
[ "MIT" ]
ScarletKuro/TinyNavigationHelper
src/TinyNavigationHelper.WPF/Properties/Settings.Designer.cs
1,105
C#
using System; namespace Contentstack.Utils.Models { public class TextNode: Node { public bool bold { get; set; } public bool italic { get; set; } public bool underline { get; set; } public bool strikethrough { get; set; } public bool inlineCode { get; set; } public bool subscript { get; set; } public bool superscript { get; set; } public string text { get; set; } } }
27.9375
47
0.58613
[ "MIT" ]
contentstack/contentstack-utils-dotnet
Contentstack.Utils/Models/TextNode.cs
449
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using LeakBlocker.Libraries.Common.Collections; using LeakBlocker.Libraries.Common.Entities.Security; using LeakBlocker.Server.Service.InternalTools.LocalStorages; namespace LeakBlocker.Server.Service.InternalTools.SingletonImplementation.LocalStorages { internal sealed class AgentsSetupListStorage : BaseConfigurationManager<ReadOnlySet<BaseComputerAccount>>, IAgentsSetupListStorage { private const string fileName = "AgentsSetupListStorage.lbConfig"; public AgentsSetupListStorage() : base(fileName) { } public override ReadOnlySet<BaseComputerAccount> Current { get { return base.Current ?? ReadOnlySet<BaseComputerAccount>.Empty; } } public void AddAndSave(BaseComputerAccount computer) { SaveIfDifferent(Current.UnionWith(computer).ToReadOnlySet()); } } }
30.058824
134
0.699609
[ "MIT" ]
imanushin/leak-blocker
Projects/LeakBlocker.Server.Service/InternalTools/SingletonImplementation/LocalStorages/AgentsSetupListStorage.cs
1,024
C#
using System.Collections.Generic; using Essensoft.AspNetCore.Payment.Alipay.Response; namespace Essensoft.AspNetCore.Payment.Alipay.Request { /// <summary> /// mybank.credit.sceneprod.drawdown.apply /// </summary> public class MybankCreditSceneprodDrawdownApplyRequest : IAlipayRequest<MybankCreditSceneprodDrawdownApplyResponse> { /// <summary> /// 场景金融银行直投业务放款申请 /// </summary> public string BizContent { get; set; } #region IAlipayRequest Members private bool needEncrypt = false; private string apiVersion = "1.0"; private string terminalType; private string terminalInfo; private string prodCode; private string notifyUrl; private string returnUrl; private AlipayObject bizModel; public void SetNeedEncrypt(bool needEncrypt) { this.needEncrypt = needEncrypt; } public bool GetNeedEncrypt() { return needEncrypt; } public void SetNotifyUrl(string notifyUrl) { this.notifyUrl = notifyUrl; } public string GetNotifyUrl() { return notifyUrl; } public void SetReturnUrl(string returnUrl) { this.returnUrl = returnUrl; } public string GetReturnUrl() { return returnUrl; } public void SetTerminalType(string terminalType) { this.terminalType = terminalType; } public string GetTerminalType() { return terminalType; } public void SetTerminalInfo(string terminalInfo) { this.terminalInfo = terminalInfo; } public string GetTerminalInfo() { return terminalInfo; } public void SetProdCode(string prodCode) { this.prodCode = prodCode; } public string GetProdCode() { return prodCode; } public string GetApiName() { return "mybank.credit.sceneprod.drawdown.apply"; } public void SetApiVersion(string apiVersion) { this.apiVersion = apiVersion; } public string GetApiVersion() { return apiVersion; } public IDictionary<string, string> GetParameters() { var parameters = new AlipayDictionary { { "biz_content", BizContent } }; return parameters; } public AlipayObject GetBizModel() { return bizModel; } public void SetBizModel(AlipayObject bizModel) { this.bizModel = bizModel; } #endregion } }
22.935484
119
0.552391
[ "MIT" ]
lzw316/payment
src/Essensoft.AspNetCore.Payment.Alipay/Request/MybankCreditSceneprodDrawdownApplyRequest.cs
2,874
C#
using FujiyBlog.Core.DomainObjects; using System.Collections.Generic; namespace FujiyBlog.Web.Areas.Admin.ViewModels { public class AdminCategoriesList { public AdminCategoriesList() { NewCategory = new Category(); } public IDictionary<Category, int> CategoriesPostCount { get; set; } public Category NewCategory { get; set; } } }
24.8125
75
0.65995
[ "MIT" ]
felipepessoto/FujiyBlog
src/FujiyBlog.Web/Areas/Admin/ViewModels/AdminCategoriesList.cs
399
C#
// Copyright (c) Jerry Lee. All rights reserved. Licensed under the MIT License. // See LICENSE in the project root for license information. using System.Collections; using System.Collections.Generic; namespace UniSharper { /// <summary> /// Support a simple chain execution for <see cref="IEnumerator"/>. /// </summary> /// <seealso cref="IEnumerator"/> public class CoroutineEnumerator : IEnumerator { private readonly Queue<IEnumerator> coroutineQueue; private object current; /// <summary> /// Initializes a new instance of the <see cref="CoroutineEnumerator"/> class with some coroutines. /// </summary> /// <param name="coroutines">The coroutines.</param> public CoroutineEnumerator(params IEnumerator[] coroutines) => coroutineQueue = new Queue<IEnumerator>(coroutines); /// <summary> /// Gets the element in the collection at the current position of the enumerator. /// </summary> /// <value>The element in the collection at the current position of the enumerator.</value> public object Current => current; /// <summary> /// Enqueues the specified coroutine. /// </summary> /// <param name="coroutine">The coroutine.</param> public void Enqueue(IEnumerator coroutine) => coroutineQueue.Enqueue(coroutine); /// <summary> /// Advances the enumerator to the next element of the collection. /// </summary> /// <returns> /// <c>true</c> if the enumerator was successfully advanced to the next element; /// <c>false</c> if the enumerator has passed the end of the collection. /// </returns> public bool MoveNext() { while (coroutineQueue.Count > 0) { current = coroutineQueue.Dequeue(); return true; } return false; } /// <summary> /// Sets the enumerator to its initial position, which is before the first element in the collection. /// </summary> public void Reset() => coroutineQueue.Clear(); } }
36.116667
123
0.610521
[ "MIT" ]
cosmos53076/UniSharper.Core
Runtime/CoroutineEnumerator.cs
2,169
C#
namespace Blazorise.States { /// <summary> /// Holds the information about the current state of the <see cref="BarDropdown"/> component. /// </summary> public record BarDropdownState { /// <summary> /// Gets or sets the dropdown menu visibilty state. /// </summary> public bool Visible { get; init; } /// <summary> /// Gets or sets the bar mode in which the dropdown is placed. /// </summary> public BarMode Mode { get; init; } /// <summary> /// Gets or sets the visibilty of the bar component. /// </summary> public bool BarVisible { get; init; } /// <summary> /// Gets or sets the hierarchy index of the dropdown in the bar component. /// </summary> public int NestedIndex { get; init; } /// <summary> /// True if dropdown is in vertical inline mode and the bar is visible. /// </summary> public bool IsInlineDisplay => Mode == BarMode.VerticalInline && BarVisible; } }
32.121212
97
0.569811
[ "MIT" ]
CPlusPlus17/Blazorise
Source/Blazorise/States/BarDropdownState.cs
1,062
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using FortniteReplayReader; using FortniteReplayReader.Models; using Unreal.Core.Models.Enums; using Unreal.Core.Exceptions; namespace cli { class Program { static ReplayReader reader = new ReplayReader(); public static List<string> replayFiles = new List<string>(); static void Main(string[] args) { var appDataReplayFolder = @"%LOCALAPPDATA%\FortniteGame\Saved\Demos"; var replayFolder = Environment.ExpandEnvironmentVariables(appDataReplayFolder); Log($"Replay folder: {replayFolder}"); var replayFile = GetNewestFile(replayFolder); PrintReplayInformationFromReplayFile(replayFile); using var watcher = new FileSystemWatcher(replayFolder); watcher.NotifyFilter = NotifyFilters.Attributes | NotifyFilters.CreationTime | NotifyFilters.DirectoryName | NotifyFilters.FileName | NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.Security | NotifyFilters.Size; watcher.Changed += OnChanged; watcher.Error += OnError; watcher.Filter = "*.replay"; watcher.EnableRaisingEvents = true; Console.ReadLine(); } static void Log(Object o) { Console.WriteLine(o); } private static string GetNewestFile(string path) { var file = new DirectoryInfo(path).GetFiles().OrderByDescending(o => o.LastWriteTime).FirstOrDefault(); return Path.Join(path, file.Name); } static void PrintReplayInformationFromReplayFile(string path) { try { var read = reader.ReadReplay(path); PrintReplayInformationFromReplay(read); replayFiles.Clear(); Console.WriteLine("Waiting for next game"); } catch (IOException) { Log("Could not open replay"); } catch (InvalidReplayException) { if (!replayFiles.Contains(path)) { Log($"In progress: {path}"); replayFiles.Add(path); } } } static void PrintReplayInformationFromReplay(FortniteReplay replay) { var totalPlayerCount = Convert.ToInt32(replay.TeamStats.TotalPlayers); var realPlayers = replay.PlayerData.Where(player => player.EpicId != null && player.EpicId.Length > 0).Distinct(); var realPlayerCount = realPlayers.Count(); var botCount = totalPlayerCount-realPlayerCount; Log($"Bots: {botCount}"); Log($"Players: {realPlayerCount}"); Log($"Total: {totalPlayerCount}"); } private static void OnChanged(object sender, FileSystemEventArgs e) { if (e.ChangeType != WatcherChangeTypes.Changed) { return; } PrintReplayInformationFromReplayFile(e.FullPath); } private static void OnError(object sender, ErrorEventArgs e) => PrintException(e.GetException()); private static void PrintException(Exception ex) { Console.WriteLine($"Message: {ex.Message}"); Console.WriteLine("Stacktrace:"); Console.WriteLine(ex.StackTrace); Console.WriteLine(); PrintException(ex.InnerException); } } }
35.447619
126
0.570392
[ "MIT" ]
flyrev/Fortnite-Replay-Analyzer
cli/Program.cs
3,724
C#
namespace microCommerce.Ioc { public interface IDependencyRegistrar { /// <summary> /// Register services and interfaces /// </summary> /// <param name="context">Container builder</param> /// <param name="typeFinder">Type finder</param> /// <param name="config">Config</param> void Register(DependencyContext context); /// <summary> /// Gets order of this dependency registrar implementation /// </summary> int Priority { get; } } }
29.611111
66
0.585366
[ "MIT" ]
BOBO41/microCommerce
src/Libraries/microCommerce.Ioc/IDependencyRegistrar.cs
533
C#
using System; using System.Collections.Generic; namespace Metaheuristics { public class GA2OptFirst4TSP : IMetaheuristic, ITunableMetaheuristic { protected double timePenalty = 250; protected double popSize = 2; protected double mutProbability = 0.3; public void Start(string fileInput, string fileOutput, int timeLimit) { TSPInstance instance = new TSPInstance(fileInput); // Setting the parameters of the GA for this instance of the problem. int[] lowerBounds = new int[instance.NumberCities]; int[] upperBounds = new int[instance.NumberCities]; for (int i = 0; i < instance.NumberCities; i++) { lowerBounds[i] = 0; upperBounds[i] = instance.NumberCities - 1; } DiscreteGA genetic = new DiscreteGA2OptFirst4TSP(instance, (int)popSize, mutProbability, lowerBounds, upperBounds); // Solving the problem and writing the best solution found. genetic.Run(timeLimit - (int)timePenalty); TSPSolution solution = new TSPSolution(instance, genetic.BestIndividual); solution.Write(fileOutput); } public string Name { get { return "GA with 2-opt (first improvement) local search for TSP"; } } public MetaheuristicType Type { get { return MetaheuristicType.GA; } } public ProblemType Problem { get { return ProblemType.TSP; } } public string[] Team { get { return About.Team; } } public void UpdateParameters(double[] parameters) { timePenalty = parameters[0]; popSize = parameters[1]; mutProbability = parameters[2]; } } }
24.873016
118
0.695597
[ "MIT" ]
yasserglez/metaheuristics
Problems/TSP/GA2OptFirst4TSP/GA2OptFirst4TSP.cs
1,567
C#
/* // <copyright> // dotNetRDF is free and open source software licensed under the MIT License // ------------------------------------------------------------------------- // // Copyright (c) 2009-2017 dotNetRDF Project (http://dotnetrdf.org/) // // 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. // </copyright> */ using System; using System.Xml; using VDS.RDF.Parsing; using VDS.RDF.Query; using VDS.RDF.Query.Expressions; namespace VDS.RDF.Nodes { /// <summary> /// Valued Node representing a Time Span value /// </summary> public class TimeSpanNode : LiteralNode, IValuedNode { private TimeSpan _value; /// <summary> /// Creates a new Time span node /// </summary> /// <param name="g">Graph</param> /// <param name="value">Time Span</param> public TimeSpanNode(IGraph g, TimeSpan value) : this(g, value, XmlConvert.ToString(value), UriFactory.Create(XmlSpecsHelper.XmlSchemaDataTypeDuration)) { } /// <summary> /// Creates a new Time span node /// </summary> /// <param name="g">Graph</param> /// <param name="value">Time Span</param> /// <param name="lexicalValue">Lexical value</param> public TimeSpanNode(IGraph g, TimeSpan value, String lexicalValue) : this(g, value, lexicalValue, UriFactory.Create(XmlSpecsHelper.XmlSchemaDataTypeDuration)) { } /// <summary> /// Creates a new Time span node /// </summary> /// <param name="g">Graph</param> /// <param name="value">Time Span</param> /// <param name="lexicalValue">Lexical value</param> /// <param name="dtUri">Data type URI</param> public TimeSpanNode(IGraph g, TimeSpan value, String lexicalValue, Uri dtUri) : base(g, lexicalValue, dtUri) { _value = value; } /// <summary> /// Gets the date time value as a string /// </summary> /// <returns></returns> public string AsString() { return Value; } /// <summary> /// Throws an error as date times cannot be converted to integers /// </summary> /// <returns></returns> public long AsInteger() { throw new RdfQueryException("Cannot convert Time Spans to other types"); } /// <summary> /// Throws an error as date times cannot be converted to decimals /// </summary> /// <returns></returns> public decimal AsDecimal() { throw new RdfQueryException("Cannot convert Time Spans to other types"); } /// <summary> /// Throws an error as date times cannot be converted to floats /// </summary> /// <returns></returns> public float AsFloat() { throw new RdfQueryException("Cannot convert Time Spans to other types"); } /// <summary> /// Throws an error as date times cannot be converted to doubles /// </summary> /// <returns></returns> public double AsDouble() { throw new RdfQueryException("Cannot convert Time Spans to other types"); } /// <summary> /// Throws an error as date times cannot be converted to booleans /// </summary> /// <returns></returns> public bool AsBoolean() { throw new RdfQueryException("Cannot convert Time Spans to other types"); } /// <summary> /// Gets the date time value of the node /// </summary> /// <returns></returns> public DateTime AsDateTime() { throw new RdfQueryException("Cannot convert Time Spans to other types"); } /// <summary> /// Gets the date time value of the node /// </summary> /// <returns></returns> public DateTimeOffset AsDateTimeOffset() { throw new RdfQueryException("Cannot convert Time Spans to other types"); } /// <summary> /// Gets the time span value of the node /// </summary> /// <returns></returns> public TimeSpan AsTimeSpan() { return _value; } /// <summary> /// Gets the URI of the datatype this valued node represents as a String /// </summary> public String EffectiveType { get { return DataType.AbsoluteUri; } } /// <summary> /// Gets the numeric type of the node /// </summary> public SparqlNumericType NumericType { get { return SparqlNumericType.NaN; } } } }
33.101695
121
0.576378
[ "MIT" ]
DFihnn/dotnetrdf
Libraries/dotNetRDF/Nodes/TimeSpanNode.cs
5,859
C#
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Mandrill.Requests.Templates { /// <summary> /// Class TemplateTimeSeriesRequest. /// </summary> public class TemplateTimeSeriesRequest : RequestBase { public TemplateTimeSeriesRequest(string name) { Name = name; } /// <summary> /// Gets or sets the template name. /// </summary> /// <value>The template name.</value> [JsonProperty("name")] public string Name { get; set; } } }
20.821429
54
0.668954
[ "Apache-2.0" ]
marcusscott/Mandrill-dotnet
src/Mandrill/Requests/Templates/TemplateTimeSeriesRequests.cs
585
C#
using System; using XMPP_API.Classes.Network.XML.Messages.Processor; namespace XMPP_API.Classes.Network.XML.Messages.Features.SASL.Plain { internal class PlainSASLMechanism: AbstractSASLMechanism { //--------------------------------------------------------Attributes:-----------------------------------------------------------------\\ #region --Attributes-- #endregion //--------------------------------------------------------Constructor:----------------------------------------------------------------\\ #region --Constructors-- /// <summary> /// Basic Constructor /// </summary> /// <history> /// 24/08/2017 Created [Fabian Sauter] /// </history> public PlainSASLMechanism(string id, string password, SASLConnection saslConnection) : base(id, password, saslConnection) { } #endregion //--------------------------------------------------------Set-, Get- Methods:---------------------------------------------------------\\ #region --Set-, Get- Methods-- #endregion //--------------------------------------------------------Misc Methods:---------------------------------------------------------------\\ #region --Misc Methods (Public)-- public override AbstractMessage generateResponse(AbstractMessage msg) { throw new NotImplementedException(); } public override SelectSASLMechanismMessage getSelectSASLMechanismMessage() { return new SelectSASLMechanismMessage("PLAIN", encodeStringBase64("\0" + ID + "\0" + PASSWORD)); } #endregion #region --Misc Methods (Private)-- #endregion #region --Misc Methods (Protected)-- #endregion //--------------------------------------------------------Events:---------------------------------------------------------------------\\ #region --Events-- #endregion } }
33.196721
144
0.408395
[ "MPL-2.0" ]
LibreHacker/UWPX-Client
XMPP_API/Classes/Network/XML/Messages/Features/SASL/Plain/PlainSASLMechanism.cs
2,027
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class GameControlScript : MonoBehaviour { public GameObject timeIsUp, restartButton; public GameObject heart1, heart2, heart3, gameOver; public static int lovehealth; // Use this for initialization void Start () { lovehealth = 9; heart1.gameObject.SetActive(true); heart2.gameObject.SetActive(true); heart3.gameObject.SetActive(true); gameOver.gameObject.SetActive(false); } // Update is called once per frame void Update () { if (TimeLeftScript.timeLeft <= 0) { Time.timeScale = 0; timeIsUp.gameObject.SetActive(true); restartButton.gameObject.SetActive(true); gameOver.gameObject.SetActive(true); } if (lovehealth > 3) lovehealth = 9; switch (lovehealth) { case 3: heart1.gameObject.SetActive(true); heart2.gameObject.SetActive(true); heart3.gameObject.SetActive(true); break; case 2: heart1.gameObject.SetActive(true); heart2.gameObject.SetActive(true); heart3.gameObject.SetActive(false); break; case 1: heart1.gameObject.SetActive(true); heart2.gameObject.SetActive(false); heart3.gameObject.SetActive(false); break; case 0: heart1.gameObject.SetActive(false); heart2.gameObject.SetActive(false); heart3.gameObject.SetActive(false); gameOver.gameObject.SetActive(true); restartButton.gameObject.SetActive(true); Time.timeScale = 0; break; } } public void restartScene() { timeIsUp.gameObject.SetActive(false); restartButton.gameObject.SetActive(false); Time.timeScale = 1; TimeLeftScript.timeLeft = 300f; lovehealth = 9; ScoreTextScript.coinAmount = 0; SceneManager.LoadScene("sceneStageMenu"); } }
28.455696
57
0.576957
[ "MIT" ]
edosept/ALVGames
Assets/Scripts/Count/GameControlScript.cs
2,250
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using Microsoft.VisualBasic; namespace MyPaint { public partial class Form2 : Form { int bianshu = 0; int count = 0; area area1 = new area(); public struct pointz { public double X; public double Y; public double Z; } public pointz[] points = null; public Form2() { bianshu = Convert.ToInt32(Interaction.InputBox("输入多边形边数上限", "", "", 50, 50)); if (bianshu >= 3) { points = new pointz[bianshu]; } InitializeComponent(); } private void pictureBox1_MouseDown(object sender, MouseEventArgs e) { try { if (e.Button == MouseButtons.Left && count <= bianshu) { double Z = Convert.ToDouble(Interaction.InputBox("输入点的高程值", "", "", 50, 50)); points[count].X = e.X; points[count].Y = e.Y; points[count].Z = Z; ++count; } else if (e.Button == MouseButtons.Right) { Point[] point = new Point[count+1]; for (int i = 0; i < count; i++) { point[i].X = Convert.ToInt32(points[i].X); point[i].Y = Convert.ToInt32(points[i].Y); } point[count].X = Convert.ToInt32(point[0].X); point[count].Y = Convert.ToInt32(point[0].Y); Graphics g = pictureBox1.CreateGraphics(); g.DrawLines(new Pen(Color.Red, 1), point); g.Dispose(); } } catch (Exception ex) { MessageBox.Show(""+ex); } } private void 计算空间面积ToolStripMenuItem_Click(object sender, EventArgs e) { Pointz[] pointz=new Pointz[points.Length]; for (int i = 0; i < points.Length; i++) { pointz[i].x = points[i].X; pointz[i].y = points[i].Y; pointz[i].z = points[i].Z; } MessageBox.Show(""+area1.kongmianji(pointz)); } } }
29.476744
97
0.444181
[ "Apache-2.0" ]
henshin123/-demo
MyPaint/Form2.cs
2,581
C#
using System; using ywcai.core.control; using ywcai.global.config; namespace ywcai.core.veiw { partial class RemoteDesk { private ControlCenter ctrlCenter = new ControlCenter(); private void StartLocalService() { ctrlCenter.StartServer(); ctrlCenter.setPsw(label_token.Text.ToString()); } } }
21.352941
63
0.639118
[ "Apache-2.0" ]
ywcai/RemoteDesk_win
src/core/view/MainForm.CoreProccess .cs
365
C#
#region License // Copyright 2010 John Sheehan // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System; using System.Net; using System.Threading; using System.Threading.Tasks; namespace RestSharp { public partial class RestClient { /// <summary> /// Executes the request and callback asynchronously, authenticating if needed /// </summary> /// <param name="request">Request to be executed</param> /// <param name="callback">Callback function to be executed upon completion providing access to the async handle.</param> /// <param name="httpMethod">HTTP call method (GET, PUT, etc)</param> public virtual RestRequestAsyncHandle ExecuteAsync(IRestRequest request, Action<IRestResponse, RestRequestAsyncHandle> callback, Method httpMethod) { var method = Enum.GetName(typeof(Method), httpMethod); switch (httpMethod) { case Method.COPY: case Method.MERGE: case Method.PATCH: case Method.POST: case Method.PUT: return ExecuteAsync(request, callback, method, DoAsPostAsync); default: return ExecuteAsync(request, callback, method, DoAsGetAsync); } } /// <summary> /// Executes the request and callback asynchronously, authenticating if needed /// </summary> /// <param name="request">Request to be executed</param> /// <param name="callback">Callback function to be executed upon completion providing access to the async handle.</param> public virtual RestRequestAsyncHandle ExecuteAsync(IRestRequest request, Action<IRestResponse, RestRequestAsyncHandle> callback) => ExecuteAsync(request, callback, request.Method); /// <summary> /// Executes a GET-style request and callback asynchronously, authenticating if needed /// </summary> /// <param name="request">Request to be executed</param> /// <param name="callback">Callback function to be executed upon completion providing access to the async handle.</param> /// <param name="httpMethod">The HTTP method to execute</param> public virtual RestRequestAsyncHandle ExecuteAsyncGet(IRestRequest request, Action<IRestResponse, RestRequestAsyncHandle> callback, string httpMethod) => ExecuteAsync(request, callback, httpMethod, DoAsGetAsync); /// <summary> /// Executes a POST-style request and callback asynchronously, authenticating if needed /// </summary> /// <param name="request">Request to be executed</param> /// <param name="callback">Callback function to be executed upon completion providing access to the async handle.</param> /// <param name="httpMethod">The HTTP method to execute</param> public virtual RestRequestAsyncHandle ExecuteAsyncPost(IRestRequest request, Action<IRestResponse, RestRequestAsyncHandle> callback, string httpMethod) { request.Method = Method.POST; // Required by RestClient.BuildUri... return ExecuteAsync(request, callback, httpMethod, DoAsPostAsync); } /// <summary> /// Executes the request and callback asynchronously, authenticating if needed /// </summary> /// <typeparam name="T">Target deserialization type</typeparam> /// <param name="request">Request to be executed</param> /// <param name="callback">Callback function to be executed upon completion</param> /// <param name="httpMethod">Override the request http method</param> public virtual RestRequestAsyncHandle ExecuteAsync<T>(IRestRequest request, Action<IRestResponse<T>, RestRequestAsyncHandle> callback, Method httpMethod) { if (request == null) throw new ArgumentNullException(nameof(request)); if (callback == null) throw new ArgumentNullException(nameof(callback)); request.Method = httpMethod; return ExecuteAsync(request, callback); } /// <summary> /// Executes the request and callback asynchronously, authenticating if needed /// </summary> /// <typeparam name="T">Target deserialization type</typeparam> /// <param name="request">Request to be executed</param> /// <param name="callback">Callback function to be executed upon completion</param> public virtual RestRequestAsyncHandle ExecuteAsync<T>(IRestRequest request, Action<IRestResponse<T>, RestRequestAsyncHandle> callback) => ExecuteAsync(request, (response, asyncHandle) => DeserializeResponse(request, callback, response, asyncHandle)); /// <summary> /// Executes a GET-style request and callback asynchronously, authenticating if needed /// </summary> /// <typeparam name="T">Target deserialization type</typeparam> /// <param name="request">Request to be executed</param> /// <param name="callback">Callback function to be executed upon completion</param> /// <param name="httpMethod">The HTTP method to execute</param> public virtual RestRequestAsyncHandle ExecuteAsyncGet<T>(IRestRequest request, Action<IRestResponse<T>, RestRequestAsyncHandle> callback, string httpMethod) { return ExecuteAsyncGet(request, (response, asyncHandle) => DeserializeResponse(request, callback, response, asyncHandle), httpMethod); } /// <summary> /// Executes a POST-style request and callback asynchronously, authenticating if needed /// </summary> /// <typeparam name="T">Target deserialization type</typeparam> /// <param name="request">Request to be executed</param> /// <param name="callback">Callback function to be executed upon completion</param> /// <param name="httpMethod">The HTTP method to execute</param> public virtual RestRequestAsyncHandle ExecuteAsyncPost<T>(IRestRequest request, Action<IRestResponse<T>, RestRequestAsyncHandle> callback, string httpMethod) { return ExecuteAsyncPost(request, (response, asyncHandle) => DeserializeResponse(request, callback, response, asyncHandle), httpMethod); } /// <summary> /// Executes a GET-style request asynchronously, authenticating if needed /// </summary> /// <typeparam name="T">Target deserialization type</typeparam> /// <param name="request">Request to be executed</param> public virtual Task<IRestResponse<T>> ExecuteGetTaskAsync<T>(IRestRequest request) => ExecuteGetTaskAsync<T>(request, CancellationToken.None); /// <summary> /// Executes a GET-style request asynchronously, authenticating if needed /// </summary> /// <typeparam name="T">Target deserialization type</typeparam> /// <param name="request">Request to be executed</param> /// <param name="token">The cancellation token</param> public virtual Task<IRestResponse<T>> ExecuteGetTaskAsync<T>(IRestRequest request, CancellationToken token) => ExecuteTaskAsync<T>(request, token, Method.GET); /// <summary> /// Executes a POST-style request asynchronously, authenticating if needed /// </summary> /// <typeparam name="T">Target deserialization type</typeparam> /// <param name="request">Request to be executed</param> public virtual Task<IRestResponse<T>> ExecutePostTaskAsync<T>(IRestRequest request) => ExecutePostTaskAsync<T>(request, CancellationToken.None); /// <summary> /// Executes a POST-style request asynchronously, authenticating if needed /// </summary> /// <typeparam name="T">Target deserialization type</typeparam> /// <param name="request">Request to be executed</param> /// <param name="token">The cancellation token</param> public virtual Task<IRestResponse<T>> ExecutePostTaskAsync<T>(IRestRequest request, CancellationToken token) => ExecuteTaskAsync<T>(request, token, Method.POST); /// <summary> /// Executes the request asynchronously, authenticating if needed /// </summary> /// <typeparam name="T">Target deserialization type</typeparam> /// <param name="request">Request to be executed</param> /// <param name="httpMethod">Override the request method</param> public virtual Task<IRestResponse<T>> ExecuteTaskAsync<T>(IRestRequest request, Method httpMethod) => ExecuteTaskAsync<T>(request, CancellationToken.None, httpMethod); /// <summary> /// Executes the request asynchronously, authenticating if needed /// </summary> /// <typeparam name="T">Target deserialization type</typeparam> /// <param name="request">Request to be executed</param> public virtual Task<IRestResponse<T>> ExecuteTaskAsync<T>(IRestRequest request) => ExecuteTaskAsync<T>(request, CancellationToken.None); /// <summary> /// Executes the request asynchronously, authenticating if needed /// </summary> /// <typeparam name="T">Target deserialization type</typeparam> /// <param name="request">Request to be executed</param> /// <param name="token">The cancellation token</param> /// <param name="httpMethod">Override the request method</param> public virtual Task<IRestResponse<T>> ExecuteTaskAsync<T>(IRestRequest request, CancellationToken token, Method httpMethod) { if (request == null) throw new ArgumentNullException(nameof(request)); request.Method = httpMethod; return ExecuteTaskAsync<T>(request, token); } /// <summary> /// Executes the request asynchronously, authenticating if needed /// </summary> /// <typeparam name="T">Target deserialization type</typeparam> /// <param name="request">Request to be executed</param> /// <param name="token">The cancellation token</param> public virtual Task<IRestResponse<T>> ExecuteTaskAsync<T>(IRestRequest request, CancellationToken token) { if (request == null) throw new ArgumentNullException(nameof(request)); var taskCompletionSource = new TaskCompletionSource<IRestResponse<T>>(); try { var async = ExecuteAsync<T>( request, (response, _) => { if (token.IsCancellationRequested) taskCompletionSource.TrySetCanceled(); // Don't run TrySetException, since we should set Error properties and swallow exceptions // to be consistent with sync methods else taskCompletionSource.TrySetResult(response); }); var registration = token.Register(() => { async.Abort(); taskCompletionSource.TrySetCanceled(); }); taskCompletionSource.Task.ContinueWith(t => registration.Dispose(), token); } catch (Exception ex) { taskCompletionSource.TrySetException(ex); } return taskCompletionSource.Task; } /// <summary> /// Executes the request asynchronously, authenticating if needed /// </summary> /// <param name="request">Request to be executed</param> public virtual Task<IRestResponse> ExecuteTaskAsync(IRestRequest request) => ExecuteTaskAsync(request, CancellationToken.None); /// <summary> /// Executes a GET-style asynchronously, authenticating if needed /// </summary> /// <param name="request">Request to be executed</param> public virtual Task<IRestResponse> ExecuteGetTaskAsync(IRestRequest request) => ExecuteGetTaskAsync(request, CancellationToken.None); /// <summary> /// Executes a GET-style asynchronously, authenticating if needed /// </summary> /// <param name="request">Request to be executed</param> /// <param name="token">The cancellation token</param> public virtual Task<IRestResponse> ExecuteGetTaskAsync(IRestRequest request, CancellationToken token) => ExecuteTaskAsync(request, token, Method.GET); /// <summary> /// Executes a POST-style asynchronously, authenticating if needed /// </summary> /// <param name="request">Request to be executed</param> public virtual Task<IRestResponse> ExecutePostTaskAsync(IRestRequest request) => ExecutePostTaskAsync(request, CancellationToken.None); /// <summary> /// Executes a POST-style asynchronously, authenticating if needed /// </summary> /// <param name="request">Request to be executed</param> /// <param name="token">The cancellation token</param> public virtual Task<IRestResponse> ExecutePostTaskAsync(IRestRequest request, CancellationToken token) => ExecuteTaskAsync(request, token, Method.POST); /// <summary> /// Executes the request asynchronously, authenticating if needed /// </summary> /// <param name="request">Request to be executed</param> /// <param name="token">The cancellation token</param> /// <param name="httpMethod">Override the request method</param> public virtual Task<IRestResponse> ExecuteTaskAsync(IRestRequest request, CancellationToken token, Method httpMethod) { if (request == null) throw new ArgumentNullException(nameof(request)); request.Method = httpMethod; return ExecuteTaskAsync(request, token); } /// <summary> /// Executes the request asynchronously, authenticating if needed /// </summary> /// <param name="request">Request to be executed</param> /// <param name="token">The cancellation token</param> public virtual Task<IRestResponse> ExecuteTaskAsync(IRestRequest request, CancellationToken token) { if (request == null) throw new ArgumentNullException(nameof(request)); var taskCompletionSource = new TaskCompletionSource<IRestResponse>(); try { var async = ExecuteAsync( request, (response, _) => { if (token.IsCancellationRequested) taskCompletionSource.TrySetCanceled(); // Don't run TrySetException, since we should set Error // properties and swallow exceptions to be consistent // with sync methods else taskCompletionSource.TrySetResult(response); }); var registration = token.Register(() => { async.Abort(); taskCompletionSource.TrySetCanceled(); }); taskCompletionSource.Task.ContinueWith(t => registration.Dispose(), token); } catch (Exception ex) { taskCompletionSource.TrySetException(ex); } return taskCompletionSource.Task; } private RestRequestAsyncHandle ExecuteAsync(IRestRequest request, Action<IRestResponse, RestRequestAsyncHandle> callback, string httpMethod, Func<IHttp, Action<HttpResponse>, string, HttpWebRequest> getWebRequest) { AuthenticateIfNeeded(this, request); var http = ConfigureHttp(request); var asyncHandle = new RestRequestAsyncHandle(); Action<HttpResponse> responseCb = r => ProcessResponse(request, r, asyncHandle, callback); if (UseSynchronizationContext && SynchronizationContext.Current != null) { var ctx = SynchronizationContext.Current; var cb = responseCb; responseCb = resp => ctx.Post(s => cb(resp), null); } asyncHandle.WebRequest = getWebRequest(http, responseCb, httpMethod); return asyncHandle; } private static HttpWebRequest DoAsGetAsync(IHttp http, Action<HttpResponse> responseCb, string method) => http.AsGetAsync(responseCb, method); private static HttpWebRequest DoAsPostAsync(IHttp http, Action<HttpResponse> responseCb, string method) => http.AsPostAsync(responseCb, method); private static void ProcessResponse(IRestRequest request, HttpResponse httpResponse, RestRequestAsyncHandle asyncHandle, Action<IRestResponse, RestRequestAsyncHandle> callback) { var restResponse = ConvertToRestResponse(request, httpResponse); callback(restResponse, asyncHandle); } private void DeserializeResponse<T>(IRestRequest request, Action<IRestResponse<T>, RestRequestAsyncHandle> callback, IRestResponse response, RestRequestAsyncHandle asyncHandle) { IRestResponse<T> restResponse; try { restResponse = Deserialize<T>(request, response); } catch (Exception ex) { restResponse = new RestResponse<T> { Request = request, ResponseStatus = ResponseStatus.Error, ErrorMessage = ex.Message, ErrorException = ex }; } callback(restResponse, asyncHandle); } } }
46.35122
129
0.613134
[ "Apache-2.0" ]
284171004/RestSharp
RestSharp/RestClient.Async.cs
19,006
C#
/**************************************************************************** The MIT License(MIT) Copyright(c) 2016 Bohn Technology Solutions, LLC Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using CottonHarvestDataTransferApp.Data; namespace CottonHarvestDataTransferApp.EF { /// <summary> /// Entity Framework / MS SQL Local db specific implementation /// of a dataprovider for storage /// </summary> public class DataProvider : IUnitOfWorkDataProvider, IDisposable { AppDBContext context = null; public IDataSourcesRepository DataSources { get; private set; } public IOrganizationsRepository Organizations { get; private set; } public ISourceFilesRepository SourceFiles { get; private set; } public ISettingsRepository Settings { get; private set; } public IOutputFilesRepository OutputFiles { get; private set; } public DataProvider() { context = new AppDBContext(); DataSources = (IDataSourcesRepository) new DataSourcesRepository(context); Organizations = (IOrganizationsRepository) new OrganizationsRepository(context); SourceFiles = (ISourceFilesRepository) new SourceFilesRepository(context); OutputFiles = (IOutputFilesRepository)new OutputFilesRepository(context); Settings = (ISettingsRepository) new SettingsRepository(context); } public void Dispose() { context.Dispose(); } public void SaveChanges() { context.SaveChanges(); } } }
40.926471
92
0.684872
[ "MIT" ]
bohntech/CottonHarvestFileDownload
CottonHarvestDataTransferApp.EF/DataProvider.cs
2,785
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VendingMachine.Process.CustomException { /// <summary> /// 釣銭切れエラー /// </summary> public class OutOfChangeException : Exception { public override string Message => "釣銭切れです!"; } }
18.529412
48
0.742857
[ "MIT" ]
YoshisakiMiyuki/VendingMachine
VendingMachine/VendingMachine.Process/CustomException/OutOfChangeException.cs
345
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Formatting { internal class WrappingFormattingRule : BaseFormattingRule { public override void AddSuppressOperations(List<SuppressOperation> list, SyntaxNode node, SyntaxToken lastToken, OptionSet optionSet, NextAction<SuppressOperation> nextOperation) { nextOperation.Invoke(list); AddBraceSuppressOperations(list, node, lastToken); AddStatementExceptBlockSuppressOperations(list, node); AddSpecificNodesSuppressOperations(list, node); if (!optionSet.GetOption(CSharpFormattingOptions.WrappingPreserveSingleLine)) { RemoveSuppressOperationForBlock(list, node); } if (!optionSet.GetOption(CSharpFormattingOptions.WrappingKeepStatementsOnSingleLine)) { RemoveSuppressOperationForStatementMethodDeclaration(list, node); } } private ValueTuple<SyntaxToken, SyntaxToken> GetSpecificNodeSuppressionTokenRange(SyntaxNode node) { var embeddedStatement = node.GetEmbeddedStatement(); if (embeddedStatement != null) { var firstTokenOfEmbeddedStatement = embeddedStatement.GetFirstToken(includeZeroWidth: true); if (embeddedStatement.IsKind(SyntaxKind.Block)) { return ValueTuple.Create( firstTokenOfEmbeddedStatement.GetPreviousToken(includeZeroWidth: true), embeddedStatement.GetLastToken(includeZeroWidth: true)); } else { return ValueTuple.Create( firstTokenOfEmbeddedStatement.GetPreviousToken(includeZeroWidth: true), firstTokenOfEmbeddedStatement); } } switch (node) { case SwitchSectionSyntax switchSection: return ValueTuple.Create(switchSection.GetFirstToken(includeZeroWidth: true), switchSection.GetLastToken(includeZeroWidth: true)); case AnonymousMethodExpressionSyntax anonymousMethod: return ValueTuple.Create(anonymousMethod.DelegateKeyword, anonymousMethod.GetLastToken(includeZeroWidth: true)); } return default; } private void AddSpecificNodesSuppressOperations(List<SuppressOperation> list, SyntaxNode node) { var tokens = GetSpecificNodeSuppressionTokenRange(node); if (!tokens.Equals(default)) { AddSuppressWrappingIfOnSingleLineOperation(list, tokens.Item1, tokens.Item2); } } private void AddStatementExceptBlockSuppressOperations(List<SuppressOperation> list, SyntaxNode node) { var statementNode = node as StatementSyntax; if (statementNode == null || statementNode.Kind() == SyntaxKind.Block) { return; } var firstToken = statementNode.GetFirstToken(includeZeroWidth: true); var lastToken = statementNode.GetLastToken(includeZeroWidth: true); AddSuppressWrappingIfOnSingleLineOperation(list, firstToken, lastToken); } private void RemoveSuppressOperationForStatementMethodDeclaration(List<SuppressOperation> list, SyntaxNode node) { var statementNode = node as StatementSyntax; if (!(statementNode == null || statementNode.Kind() == SyntaxKind.Block)) { var firstToken = statementNode.GetFirstToken(includeZeroWidth: true); var lastToken = statementNode.GetLastToken(includeZeroWidth: true); RemoveSuppressOperation(list, firstToken, lastToken); } var tokens = GetSpecificNodeSuppressionTokenRange(node); if (!tokens.Equals(default)) { RemoveSuppressOperation(list, tokens.Item1, tokens.Item2); } var ifStatementNode = node as IfStatementSyntax; if (ifStatementNode?.Else != null) { RemoveSuppressOperation(list, ifStatementNode.Else.ElseKeyword, ifStatementNode.Else.Statement.GetFirstToken(includeZeroWidth: true)); } } private void RemoveSuppressOperationForBlock(List<SuppressOperation> list, SyntaxNode node) { var bracePair = GetBracePair(node); if (!bracePair.IsValidBracePair()) { return; } var firstTokenOfNode = node.GetFirstToken(includeZeroWidth: true); if (node.IsLambdaBodyBlock()) { // include lambda itself. firstTokenOfNode = node.Parent.GetFirstToken(includeZeroWidth: true); } // suppress wrapping on whole construct that owns braces and also brace pair itself if it is on same line RemoveSuppressOperation(list, firstTokenOfNode, bracePair.Item2); RemoveSuppressOperation(list, bracePair.Item1, bracePair.Item2); } private ValueTuple<SyntaxToken, SyntaxToken> GetBracePair(SyntaxNode node) { if (node is BaseMethodDeclarationSyntax methodDeclaration && methodDeclaration.Body != null) { return ValueTuple.Create(methodDeclaration.Body.OpenBraceToken, methodDeclaration.Body.CloseBraceToken); } if (node is PropertyDeclarationSyntax propertyDeclaration && propertyDeclaration.AccessorList != null) { return ValueTuple.Create(propertyDeclaration.AccessorList.OpenBraceToken, propertyDeclaration.AccessorList.CloseBraceToken); } if (node is AccessorDeclarationSyntax accessorDeclaration && accessorDeclaration.Body != null) { return ValueTuple.Create(accessorDeclaration.Body.OpenBraceToken, accessorDeclaration.Body.CloseBraceToken); } return node.GetBracePair(); } protected void RemoveSuppressOperation( List<SuppressOperation> list, SyntaxToken startToken, SyntaxToken endToken) { if (startToken.Kind() == SyntaxKind.None || endToken.Kind() == SyntaxKind.None) { return; } var span = TextSpan.FromBounds(startToken.SpanStart, endToken.Span.End); for (int i = 0; i < list.Count; i++) { if (list[i] != null && list[i].TextSpan.Start >= span.Start && list[i].TextSpan.End <= span.End) { list[i] = null; } } } } }
40.855556
186
0.629589
[ "Apache-2.0" ]
DaiMichael/roslyn
src/Workspaces/CSharp/Portable/Formatting/Rules/WrappingFormattingRule.cs
7,356
C#
namespace Workflow.Messages { public class BeginDataCenterProcessing : WorkflowCommand { public BeginDataCenterProcessing(string workflowId) { WorkflowId = workflowId; } } }
20.181818
60
0.644144
[ "MIT" ]
ErikMuir/NServiceBusDemo
lift-and-shift/NServiceBusWorkflow/Workflow/Messages/Commands/BeginDataCenterProcessing.cs
222
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/d3d12.h in the Windows SDK for Windows 10.0.20348.0 // Original source is Copyright © Microsoft. All rights reserved. using System; namespace TerraFX.Interop.DirectX; public unsafe partial struct D3D12_META_COMMAND_DESC { public Guid Id; [NativeTypeName("LPCWSTR")] public ushort* Name; public D3D12_GRAPHICS_STATES InitializationDirtyState; public D3D12_GRAPHICS_STATES ExecutionDirtyState; }
27.857143
145
0.774359
[ "MIT" ]
JeremyKuhne/terrafx.interop.windows
sources/Interop/Windows/DirectX/um/d3d12/D3D12_META_COMMAND_DESC.cs
587
C#
using IbanLib.Countries; using NUnit.Framework; namespace IbanLib.Splitters.Test { [TestFixture] public abstract class ASplitterTest { protected ICountry GetCountryFromIBan(string iban) { return Getter.GetCountry(iban.Substring(0, 2)); } } }
21.071429
59
0.657627
[ "MIT" ]
epreviati/IbanLib
IbanLib.Splitters.Test/ASplitterTest.cs
297
C#
namespace GameCreator.Inventory { using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; using GameCreator.Core; using GameCreator.Characters; using GameCreator.Variables; [AddComponentMenu("")] public class ActionInstantiateSkin : IAction { public enum Operation { Add, Remove } public TargetCharacter character = new TargetCharacter(TargetCharacter.Target.Invoker); [Space] public Operation action = Operation.Add; public GameObjectProperty prefab = new GameObjectProperty(); [Space, Tooltip("(Optional) store the garment instance in a variable")] public VariableProperty storeReference = new VariableProperty(); public override bool InstantExecute(GameObject target, IAction[] actions, int index) { GameObject instance = null; switch (this.action) { case Operation.Add: instance = SkinmeshManager.Wear( this.prefab.GetValue(target), this.character.GetCharacter(target) ); break; case Operation.Remove: instance = SkinmeshManager.TakeOff( this.prefab.GetValue(target), this.character.GetCharacter(target) ); break; } this.storeReference.Set(instance, target); return true; } #if UNITY_EDITOR public const string CUSTOM_ICON_PATH = "Assets/Plugins/GameCreator/Inventory/Icons/Actions/"; public static new string NAME = "Inventory/Instantiate Skinned Mesh"; private const string NODE_TITLE = "Add skin-mesh {0} on {1}"; public override string GetNodeTitle() { return string.Format(NODE_TITLE, this.prefab, this.character); } #endif } }
30.787879
101
0.58563
[ "MIT" ]
Signal-K/Unity-Demo
Assets/Plugins/GameCreator/Inventory/Mono/Actions/ActionInstantiateSkin.cs
2,034
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Text; using System.Web; using DataTablesNetSample.DataTables; using DataTablesNetSample.Helper; using Ionic.Zip; using Newtonsoft.Json; namespace DataTablesNetSample.DataProviders { /// <summary> /// Class DemoDataProvider. /// </summary> // ReSharper disable once ClassWithVirtualMembersNeverInherited.Global public class DemoDataProvider: IDataTableProvider<int, DemoDataEntry> { private List<DemoDataEntry> _data; private static IEnumerable<DataTableColumn> _columns; /// <summary> /// Get a specific entry out of the list of displayed data. /// </summary> /// <param name="key">the primary key of the data element to be retrieved</param> /// <returns>The retrieved data element</returns> public DemoDataEntry Get(int key) { return _data.SingleOrDefault(x => x.Id == key); } public string Name => "Demo"; public void Initialize() { CreateColumns(); } private void CreateColumns() { if (_columns != null) { return; // done } _columns = new List<DataTableColumn> { new DataTableColumn { Name = "Id", }, new DataTableColumn { Name = "FirstName", }, new DataTableColumn { Name = "LastName", }, new DataTableColumn { Name = "Gender", }, new DataTableColumn { Name = "Email", }, }; } /// <summary> /// Initiate data load. /// </summary> /// <param name="parameters">a list of parameters dependant on the provider implementation.</param> /// <returns><c>true</c> if data is available to be displayed, <c>false</c> otherwise.</returns> /// <remarks> /// <para>No calls to <see cref="IDataTableProvider.GetData"/> should be performed before loading data.</para> /// </remarks> public bool LoadData(params object[] parameters) { string filename = parameters[0] as string; if (HttpContext.Current.Session["Data"] != null && (string) HttpContext.Current.Session["FileName"] == filename) { // data hasn't changed return true; } using (ZipFile zipFile = new ZipFile(filename, Encoding.UTF8)) { ZipEntry entry = zipFile["MOCK_DATA.json"]; using (TextReader reader = new StreamReader(entry.OpenReader())) { _data = JsonConvert.DeserializeObject<List<DemoDataEntry>>(reader.ReadToEnd()); } HttpContext.Current.Session["Data"] = _data; HttpContext.Current.Session["FileName"] = filename; } return true; // false might help to identify errors during loading } /// <summary> /// Retrieve data towards the frontend. /// </summary> /// <param name="model">The model.</param> /// <returns>System.String.</returns> /// <remarks>For a detailed description of the target data format please refer to http://datatables.net/manual/server-side (setion "Returned Data")</remarks> public string GetData(DataTableParameterModel model) { List<DemoDataEntry> data = (List<DemoDataEntry>)HttpContext.Current.Session["Data"]; var predicate = BuildFilter<DemoDataEntry>(model); int totalCount = data.Count; data = data.AsQueryable().Where(predicate).ToList(); int filterCount = data.Count; IOrderedQueryable<DemoDataEntry> sortQuery = CreateSortedQuery(model, data.AsQueryable()); data = sortQuery.ToList(); if (model.DisplayLength > 0) { data = data.Skip(model.DisplayStart).Take(model.DisplayLength).ToList(); } StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter writer = new JsonTextWriter(sw)) { #if DEBUG writer.Formatting = Formatting.Indented; #endif writer.WriteStartObject(); writer.WritePropertyName("draw"); writer.WriteValue(model.Draw); writer.WritePropertyName("recordsTotal"); writer.WriteValue(totalCount); writer.WritePropertyName("recordsFiltered"); writer.WriteValue(filterCount); writer.WritePropertyName("data"); writer.WriteStartArray(); foreach (DemoDataEntry entity in data) { writer.WriteStartObject(); writer.WritePropertyName("DT_RowId"); writer.WriteValue(entity.Id); foreach (DataTableColumn column in Columns.Where(x => x.IsMapped && !x.RowAttribute)) { writer.WritePropertyName(column.Name); writer.WriteValue(column.GetValue(entity)); } writer.WritePropertyName("DT_RowAttr"); writer.WriteStartObject(); foreach (DataTableColumn column in Columns.Where(x => x.RowAttribute)) { writer.WritePropertyName(column.RowAttributeName ?? column.Name); writer.WriteValue(column.GetValue(entity)); } writer.WriteEndObject(); writer.WriteEndObject(); } writer.WriteEnd(); writer.WriteEndObject(); } return sb.ToString(); } protected virtual Expression<Func<T, bool>> BuildFilter<T>(DataTableParameterModel model) { var predicate = PredicateBuilder.True<T>(); // ReSharper disable once LoopCanBeConvertedToQuery foreach ( DataTableParameterModel.DataTableColumn column in model.Columns.Where(x => x.Searchable && !string.IsNullOrWhiteSpace(x.SearchValue))) { // x => var parameterExp = Expression.Parameter(typeof(T), "type"); // x => x.<PropertyName> var propertyExp = Expression.Property(parameterExp, column.Name); Expression condition; MethodInfo toLowerMethod = typeof(string).GetMethod("ToLower", new Type[] { }); MethodInfo containsMethod = typeof(string).GetMethod("Contains", new[] { typeof(string) }); MethodInfo toStringMethod = typeof(int).GetMethod("ToString", new Type[] { }); if (propertyExp.Type == typeof (int)) { // x.<PropertyName>.ToString() var propertyStringExp = Expression.Call(propertyExp, toStringMethod); // x.<PropertyName>.ToString().Contains(<searchValue>) condition = Expression.Call(propertyStringExp, containsMethod, Expression.Constant(column.SearchValue)); } else { // <searchValue>.ToLower() var someValue = Expression.Call(Expression.Constant(column.SearchValue, typeof(string)), toLowerMethod); // x.<PropertyName>.ToLower() var toLowerMethodExp = Expression.Call(propertyExp, toLowerMethod); // x.<PropertyName>.ToLower().Contains(<searchValue>.ToLower()) var containsMethodExp = Expression.Call(toLowerMethodExp, containsMethod, someValue); // x.<PropertyName> != null var nullCheck = Expression.NotEqual(propertyExp, Expression.Constant(null, typeof(object))); // x => x.<PropertyName> != null && x.<PropertyName>.ToLower().Contains(<SearchString>.ToLower()) condition = Expression.AndAlso(nullCheck, containsMethodExp); } // Build a expression that is a function that gets a element of <T> as input and returns true or false if t.propertyName contains searchstring Expression<Func<T, bool>> lambda = Expression.Lambda<Func<T, bool>>( condition, parameterExp); predicate = predicate.And(lambda); } return predicate; } protected virtual IOrderedQueryable<T> CreateSortedQuery<T>(DataTableParameterModel parameterModel, IQueryable<T> baseQuery) { var orderedQuery = (IOrderedQueryable<T>)baseQuery; for (int i = 0; i < parameterModel.SortingCols; ++i) { var ascending = string.Equals("asc", parameterModel.SortDirs[i], StringComparison.OrdinalIgnoreCase); int sortCol = parameterModel.SortColumns[i]; Expression<Func<T, IComparable>> orderByExpression = GetOrderByExpression<T>(sortCol, parameterModel); if (ascending) { orderedQuery = (i == 0) ? orderedQuery.OrderBy(orderByExpression) : orderedQuery.ThenBy(orderByExpression); } else { orderedQuery = (i == 0) ? orderedQuery.OrderByDescending(orderByExpression) : orderedQuery.ThenByDescending(orderByExpression); } } return orderedQuery; } protected virtual Expression<Func<T, IComparable>> GetOrderByExpression<T>(int sortCol, DataTableParameterModel model) { string propertyName = model.Columns[sortCol].Name; if (string.IsNullOrWhiteSpace(propertyName)) { propertyName = model.Columns.First(x => x.Name != null).Name; } Type t = typeof(T); PropertyInfo info = t.GetProperty(propertyName); var parameter = Expression.Parameter(t); var property = Expression.Property(parameter, info); var funcType = typeof(Func<,>).MakeGenericType(t, typeof(IComparable)); var lambda = Expression.Lambda(funcType, Expression.Convert(property, typeof(IComparable)), parameter); return (Expression<Func<T, IComparable>>)lambda; } public IEnumerable<DataTableColumn> Columns { get { CreateColumns(); return _columns; } } /// <summary> /// retrieve a single column. /// </summary> /// <param name="columnName">Name of the column.</param> /// <returns>The column definition.</returns> public DataTableColumn GetColumn(string columnName) { return Columns.Single(x => x.Name == columnName); } } }
42.603774
165
0.55775
[ "MIT" ]
steven-r/AspNetDatatablesSample
DataTablesNetSample/DataTablesNetSample/DataProviders/DemoDataProvider.cs
11,292
C#
using System; using ShoppingSpree.Core; namespace ShoppingSpree { public class StartUp { static void Main(string[] args) { try { Engine engine = new Engine(); engine.Run(); } catch (Exception e) { Console.WriteLine(e.Message); } } } }
17.565217
45
0.418317
[ "MIT" ]
tonchevaAleksandra/C-Sharp-OOP
Encapsulation/ShoppingSpree/StartUp.cs
406
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace ChilliSource.Cloud.Web.MVC { /// <summary> /// Represents support for creating modal window. /// </summary> public static class ModalHelper { /// <summary> /// Creates model container which will host a partial view. /// </summary> /// <param name="helper">The System.Web.Mvc.HtmlHelper instance that this method extends.</param> /// <param name="id">Id of modal.</param> /// <param name="title">The title for modal window.</param> /// <param name="showClose">True to display close button, otherwise not.</param> /// <param name="showPrint">True to display print button, otherwise not.</param> /// <returns>An HTML string for the modal window.</returns> public static MvcHtmlString ModalContainer(this HtmlHelper helper, string id, string title = "", bool showClose = true, bool showPrint = false) { return new MvcHtmlString(ModalContainer(id, title, showClose, showPrint)); } /// <summary> /// Creates model container which will host a partial view. /// </summary> /// <param name="id">Id of modal.</param> /// <param name="title">The title for modal window.</param> /// <param name="showClose">True to display close button, otherwise not.</param> /// <param name="showPrint">True to display print button, otherwise not.</param> /// <returns>The string for the modal window.</returns> public static string ModalContainer(string id, string title = "", bool showClose = true, bool showPrint = false) { string format = @"<div id=""{0}"" class=""modal hide""><div class=""modal-header"">{1}{2}{3}</div><div class=""modal-body"" id=""{0}_content""></div></div>"; string titleFormat = "<h3>{0}</h3>"; string close = @"<a class=""close"" data-dismiss=""modal"">×</a>"; string print = @"<a class=""print"" onclick=""window.print();""></a>"; if (!showClose) close = ""; if (!showPrint) print = ""; titleFormat = String.IsNullOrEmpty(title) ? "" : String.Format(titleFormat, title); return String.Format(format, id, close, print, titleFormat); } private static string AppendJsonData(string source, string value) { if (!string.IsNullOrEmpty(source)) return String.Format("{0}, {1}", source, value); return value; } /// <summary> /// Returns HTML string of the link to open modal window. /// </summary> /// <param name="id">The id of the link.</param> /// <param name="url">The URL of the link.</param> /// <param name="title">The title of the link.</param> /// <param name="width">The width of the modal window.</param> /// <param name="height">The height of the modal window.</param> /// <param name="iconClasses">CSS class for the icon of the link.</param> /// <param name="htmlAttributes">An object that contains the HTML attributes.</param> /// <param name="commandOnly">True to return link without "onclick" event, otherwise with "onclick" event.</param> /// <param name="dynamicData">The dynamic data passed to "ajaxLoad" function.</param> /// <param name="BackgroundDrop">True to add CSS "backdrop: 'static'", otherwise not.</param> /// <param name="EscapeKey">True to add CSS "keyboard: false"</param> /// <returns>An HTML string of the link to open modal window.</returns> [Obsolete] public static string ModalOpen(string id, string url, string title = "", int? width = null, int? height = null, string iconClasses = "", object htmlAttributes = null, bool commandOnly = false, string dynamicData = "", bool BackgroundDrop = true, bool EscapeKey = true) { string options = ""; if (!BackgroundDrop) options = AppendJsonData(options, "backdrop: 'static'"); if (!EscapeKey) options = AppendJsonData(options, "keyboard: false"); options = (options.Length == 0) ? "'show'" : String.Format("{{ {0} }}", options); string onclick = @"$.ajaxLoad('{0}_content', '{1}', {2}, function() {{ $('#{0}').modal({5}){3}{4}; }});"; string widthCss = ".css({{'width':'{0}'}})"; string heightCss = ".css({{'height':'{0}'}})"; //FYI Max height is 500px! widthCss = width.HasValue ? String.Format(widthCss, width.Value) : ""; heightCss = height.HasValue ? String.Format(heightCss, height.Value) : ""; TagBuilder tag = new TagBuilder("a"); tag.InnerHtml = title; if (!String.IsNullOrEmpty(iconClasses)) { var iconTag = new TagBuilder("i"); iconTag.AddCssClass(iconClasses); tag.InnerHtml = iconTag.ToString() + " " + tag.InnerHtml; } string onclickFormatted = String.Format(onclick, id, url, String.IsNullOrEmpty(dynamicData) ? "null" : dynamicData, widthCss, heightCss, options); if (commandOnly) return onclickFormatted; tag.Attributes.Add("onclick", onclickFormatted); tag.Attributes.Add("href", "javascript:void(0);"); if (htmlAttributes != null) tag.MergeAttributes(HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes)); return tag.ToString(TagRenderMode.Normal); } } }
53.607477
277
0.588389
[ "MIT" ]
BlueChilli/ChilliSource.Cloud.Web.MVC
src/ChilliSource.Cloud.Web.MVC/Extensions/Helpers/Modal.cs
5,739
C#
using System.Collections.Generic; using NitroSharp.Content; using NitroSharp.Graphics; using NitroSharp.NsScript.VM; using Veldrid; namespace NitroSharp.Saving { internal sealed class GameSavingContext { private readonly List<Texture> _textures = new(); public GameSavingContext(World world) { World = world; } public World World { get; } public IReadOnlyList<Texture> StandaloneTextures => _textures; public int AddStandaloneTexture(Texture texture) { int id = _textures.Count; _textures.Add(texture); return id; } } internal sealed class GameLoadingContext { public IReadOnlyList<Texture> StandaloneTextures { get; init; } public GameContext GameContext { get; init; } public RenderContext Rendering { get; init; } public ContentManager Content { get; init; } public NsScriptVM VM { get; init; } public GameProcess Process { get; init; } public Backlog Backlog { get; init; } } }
27.2
71
0.633272
[ "MIT" ]
CommitteeOfZero/nitrosharp
src/NitroSharp/Saving/Context.cs
1,090
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace GrapeCity.DataVisualization.Chart.TestSite { public class Test { public Test() { this.Id = 0; this.Name = ""; this.Path = ""; this.Content = ""; } /// <summary> /// Gets or sets the test id. /// </summary> public long Id { get; set; } /// <summary> /// Gets or sets the test name. /// </summary> public string Name { get; set; } /// <summary> /// Gets or sets the test path. /// </summary> public string Path { get; set; } /// <summary> /// Gets or sets the test content. /// </summary> public string Content { get; set; } /// <summary> /// Clone test. /// </summary> /// <returns></returns> public Test Clone() { return new Test() { Id = this.Id, Name = this.Name, Path = this.Path, Content = this.Content, }; } } }
22.203704
52
0.442035
[ "MIT" ]
robin-han/react-netcore-testsite
Models/Test.cs
1,201
C#
namespace RecepiesProject.Data.Common { using System; using System.Threading.Tasks; public interface IDbQueryRunner : IDisposable { Task RunQueryAsync(string query, params object[] parameters); } }
20.727273
69
0.701754
[ "Apache-2.0" ]
AKermanov/recipes-project
src/Data/RecepiesProject.Data.Common/IDbQueryRunner.cs
230
C#
using System; using System.Collections.Generic; using System.Text; using Telerik.DataSource; namespace gRPCsample.Shared { public class DataEnvelope<T> { /// <summary> /// Use this when there is data grouping /// </summary> public List<AggregateFunctionsGroup> GroupedData { get; set; } /// <summary> /// Use this when there is no data grouping and the response is flat data, like in the common case. /// </summary> public List<T> CurrentPageData { get; set; } /// <summary> /// Always set this to the total number of records. /// </summary> public int TotalItemCount { get; set; } } }
25.888889
107
0.60372
[ "MIT" ]
EdCharbeneau/blazor-ui
common/grpc-example/datasource-request-result/gRPCsample/Shared/JSON/DataEnvelope.cs
701
C#
// Copyright (c) Just Eat, 2017. All rights reserved. // Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information. using System.Net.Http; namespace JustEat.HttpClientInterception.Matching { /// <summary> /// Represents a class that tests for matches for HTTP requests for a registered HTTP interception. /// </summary> internal abstract class RequestMatcher { /// <summary> /// Returns a value indicating whether the specified <see cref="HttpRequestMessage"/> is considered a match. /// </summary> /// <param name="request">The HTTP request to consider a match against.</param> /// <returns> /// <see langword="true"/> if <paramref name="request"/> is considered a match; otherwise <see langword="false"/>. /// </returns> public abstract bool IsMatch(HttpRequestMessage request); } }
40.26087
122
0.669546
[ "Apache-2.0" ]
NuKeeperBot/httpclient-interception
src/HttpClientInterception/Matching/RequestMatcher.cs
926
C#
using Xunit; namespace NStandard.UnitValues.Test { public class StorageUnitTests { [Fact] public void Test1() { var a = StorageValue.Parse(".5 MB"); var b = new StorageValue(512, "KB"); Assert.Equal(1, (a + b).GetValue("MB")); Assert.Equal(1024, (a + b).GetValue("KB")); Assert.Equal(1024, (a + b).Unit("KB").Value); Assert.Equal(1, (a + b).Value); Assert.Equal(0, (a - b).Value); Assert.Equal(1, (a * 2).Value); Assert.Equal(0.25, (a / 2).Value); Assert.True(a == b); Assert.False(a != b); Assert.False(a < b); Assert.True(a <= b); Assert.False(a > b); Assert.True(a >= b); } [Fact] public void Test2() { var values = new StorageValue[3].Let(i => new StorageValue(i * 5, "kb")); var sum = new StorageValue(); sum.QuickSum(values); Assert.Equal(15 * 1024, sum.BitValue); var average = new StorageValue(); average.QuickAverage(values); Assert.Equal(5 * 1024, average.BitValue); } } }
26.234043
85
0.472019
[ "MIT" ]
zmjack/NStd
Tests/NStandard.Test/UnitValues/StorageUnitTests.cs
1,235
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net; using System.IO; namespace WindowsFormsApplication_GetTemperature { class GetTemMethod { public string GetTemMethodtemp(string city) { string sURL,sURL1,sURL2; sURL1 = "https://weather.cit.api.here.com/weather/1.0/report.json?product=observation&name="; sURL2 = "&app_id=DemoAppId01082013GAL&app_code=AJKnXv84fjrb0KIHawS0Tg"; sURL = sURL1 + city + sURL2; WebRequest wrGETURL; wrGETURL = WebRequest.Create(sURL); WebProxy myProxy = new WebProxy("myproxy", 80); myProxy.BypassProxyOnLocal = true; wrGETURL.Proxy = WebProxy.GetDefaultProxy(); Stream objStream; objStream = wrGETURL.GetResponse().GetResponseStream(); StreamReader objReader = new StreamReader(objStream); string sLine = ""; int start = 0; int end = 0; //int i = 0; sLine = objReader.ReadToEnd(); start = sLine.LastIndexOf(",\"temperature\":\""); // ,"temperature":" ,\"temperature\":\" sLine = sLine.Substring(start + 16); end = sLine.LastIndexOf("\",\"tem"); sLine = sLine.Substring(0, end); // \",\"tem return sLine; } } }
30.625
106
0.570748
[ "MIT" ]
ricky10116/Csharp_WebService_Get_Temperature
WindowsFormsApplication_GetTemperature/WindowsFormsApplication_GetTemperature/GetTemMethod.cs
1,472
C#
using Microsoft.Xna.Framework; using SoulsFormats; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DSAnimStudio { public class NewMesh : IDisposable { public List<FlverSubmeshRenderer> Submeshes = new List<FlverSubmeshRenderer>(); private bool[] DefaultDrawMask = new bool[Model.DRAW_MASK_LENGTH]; public bool[] DrawMask = new bool[Model.DRAW_MASK_LENGTH]; private object _lock_submeshes = new object(); public BoundingBox Bounds; public bool TextureReloadQueued = false; public FLVER2.FLVERHeader Flver2Header = null; public void DefaultAllMaskValues() { for (int i = 0; i < Model.DRAW_MASK_LENGTH; i++) { DrawMask[i] = DefaultDrawMask[i]; } } public List<string> GetAllTexNamesToLoad() { List<string> result = new List<string>(); lock (_lock_submeshes) { if (Submeshes != null) { foreach (var sm in Submeshes) { result.AddRange(sm.GetAllTexNamesToLoad()); } } } return result; } public NewMesh(FLVER2 flver, bool useSecondUV, Dictionary<string, int> boneIndexRemap = null, bool ignoreStaticTransforms = false) { LoadFLVER2(flver, useSecondUV, boneIndexRemap, ignoreStaticTransforms); } public NewMesh(FLVER0 flver, bool useSecondUV, Dictionary<string, int> boneIndexRemap = null, bool ignoreStaticTransforms = false) { LoadFLVER0(flver, useSecondUV, boneIndexRemap, ignoreStaticTransforms); } private void LoadFLVER2(FLVER2 flver, bool useSecondUV, Dictionary<string, int> boneIndexRemap = null, bool ignoreStaticTransforms = false) { Flver2Header = flver.Header; lock (_lock_submeshes) { Submeshes = new List<FlverSubmeshRenderer>(); } foreach (var submesh in flver.Meshes) { // Blacklist some materials that don't have good shaders and just make the viewer look like a mess MTD mtd = null;// InterrootLoader.GetMTD(Path.GetFileName(flver.Materials[submesh.MaterialIndex].MTD)); if (mtd != null) { if (mtd.ShaderPath.Contains("FRPG_Water_Env")) continue; if (mtd.ShaderPath.Contains("FRPG_Water_Reflect.spx")) continue; } var smm = new FlverSubmeshRenderer(this, flver, submesh, useSecondUV, boneIndexRemap, ignoreStaticTransforms); Bounds = new BoundingBox(); lock (_lock_submeshes) { Submeshes.Add(smm); Bounds = BoundingBox.CreateMerged(Bounds, smm.Bounds); } } } private void LoadFLVER0(FLVER0 flver, bool useSecondUV, Dictionary<string, int> boneIndexRemap = null, bool ignoreStaticTransforms = false) { Flver2Header = null; lock (_lock_submeshes) { Submeshes = new List<FlverSubmeshRenderer>(); } foreach (var submesh in flver.Meshes) { // Blacklist some materials that don't have good shaders and just make the viewer look like a mess MTD mtd = null;// InterrootLoader.GetMTD(Path.GetFileName(flver.Materials[submesh.MaterialIndex].MTD)); if (mtd != null) { if (mtd.ShaderPath.Contains("FRPG_Water_Env")) continue; if (mtd.ShaderPath.Contains("FRPG_Water_Reflect.spx")) continue; } var smm = new FlverSubmeshRenderer(this, flver, submesh, useSecondUV, boneIndexRemap, ignoreStaticTransforms); Bounds = new BoundingBox(); lock (_lock_submeshes) { Submeshes.Add(smm); Bounds = BoundingBox.CreateMerged(Bounds, smm.Bounds); } } } public void Draw(int lod, bool motionBlur, bool forceNoBackfaceCulling, bool isSkyboxLol, NewAnimSkeleton_FLVER skeleton = null, Action<Exception> onDrawFail = null) { if (TextureReloadQueued) { TryToLoadTextures(); TextureReloadQueued = false; } lock (_lock_submeshes) { if (Submeshes == null) return; foreach (var submesh in Submeshes) { try { submesh.Draw(lod, motionBlur, DrawMask, forceNoBackfaceCulling, skeleton, onDrawFail); } catch (Exception ex) { onDrawFail?.Invoke(ex); } } } } public void TryToLoadTextures() { lock (_lock_submeshes) { if (Submeshes == null) return; foreach (var sm in Submeshes) sm.TryToLoadTextures(); } } public void Dispose() { if (Submeshes != null) { for (int i = 0; i < Submeshes.Count; i++) { if (Submeshes[i] != null) Submeshes[i].Dispose(); } Submeshes = null; } } } }
32.167568
173
0.507646
[ "MIT" ]
Meowmaritus/DSAnimStudio
DSAnimStudio/NewMesh.cs
5,953
C#
using System.Security.Cryptography.X509Certificates; using System.Threading.Tasks; using JuvoLogger; using System.Reactive.Subjects; namespace Rtsp { using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Globalization; using System.IO; using System.Net.Sockets; using System.Text; using System.Threading; using Rtsp.Messages; /// <summary> /// Rtsp lister /// </summary> public class RtspListener : IDisposable { private static readonly ILogger _logger = LoggerManager.GetInstance().GetLogger("JuvoPlayer"); private IRtspTransport _transport; private Task _listenTask; private Stream _stream; private int _sequenceNumber; private Dictionary<int, RtspRequest> _sentMessage = new Dictionary<int, RtspRequest>(); private Subject<string> _rtspErrorSubject; /// <summary> /// Initializes a new instance of the <see cref="RtspListener"/> class from a TCP connection. /// </summary> /// <param name="connection">The connection.</param> public RtspListener(IRtspTransport connection, Subject<string> rtspErrorSubject) { if (connection == null) throw new ArgumentNullException("connection"); Contract.EndContractBlock(); _transport = connection; _rtspErrorSubject = rtspErrorSubject; } /// <summary> /// Gets the remote address. /// </summary> /// <value>The remote adress.</value> public string RemoteAdress { get { return _transport.RemoteAddress; } } /// <summary> /// Starts this instance. /// </summary> public void Start(CancellationToken token) { _stream = _transport.GetStream(); _listenTask = new Task((o) => DoJob(token), token); _listenTask.ContinueWith((task) => { if (task.Exception != null && !((CancellationToken)task.AsyncState).IsCancellationRequested) { _rtspErrorSubject?.OnNext(task.Exception.Message); } _logger.Info("RTPS Listen Task completed."); }); _listenTask.Start(); } /// <summary> /// Stops this instance. /// </summary> public void Stop() { // brutally close the TCP socket.... // I hope the teardown was sent elsewhere _transport.Close(); } /// <summary> /// Enable auto reconnect. /// </summary> public bool AutoReconnect { get; set; } /// <summary> /// Occurs when message is received. /// </summary> public event EventHandler<RtspChunkEventArgs> MessageReceived; /// <summary> /// Raises the <see cref="E:MessageReceived"/> event. /// </summary> /// <param name="e">The <see cref="Rtsp.RtspChunkEventArgs"/> instance containing the event data.</param> protected void OnMessageReceived(RtspChunkEventArgs e) { EventHandler<RtspChunkEventArgs> handler = MessageReceived; if (handler != null) handler(this, e); } /// <summary> /// Occurs when Data is received. /// </summary> public event EventHandler<RtspChunkEventArgs> DataReceived; /// <summary> /// Raises the <see cref="E:DataReceived"/> event. /// </summary> /// <param name="rtspChunkEventArgs">The <see cref="Rtsp.RtspChunkEventArgs"/> instance containing the event data.</param> protected void OnDataReceived(RtspChunkEventArgs rtspChunkEventArgs) { EventHandler<RtspChunkEventArgs> handler = DataReceived; if (handler != null) handler(this, rtspChunkEventArgs); } /// <summary> /// Does the reading job. /// </summary> /// <remarks> /// This method read one message from TCP connection. /// If it a response it add the associate question. /// The stopping is made by the closing of the TCP connection. /// </remarks> private void DoJob(CancellationToken token) { try { _logger.Info($"RTSP Connection with {_transport.RemoteAddress} started"); // token & _transport determine object's status while (!token.IsCancellationRequested && _transport?.Connected == true) { // La lectuer est blocking sauf si la connection est coupé RtspChunk currentMessage = ReadOneMessage(); if (currentMessage != null) { if (!(currentMessage is RtspData)) { // on logue le tout if (currentMessage.SourcePort != null) _logger.Info($"Receive from {currentMessage.SourcePort.RemoteAdress}"); currentMessage.LogMessage(); } if (currentMessage is RtspResponse) { RtspResponse response = currentMessage as RtspResponse; lock (_sentMessage) { // add the original question to the response. RtspRequest originalRequest; if (_sentMessage.TryGetValue(response.CSeq, out originalRequest)) { _sentMessage.Remove(response.CSeq); response.OriginalRequest = originalRequest; } else { _logger.Warn($"Receive response not asked {response.CSeq}"); } } OnMessageReceived(new RtspChunkEventArgs(response)); } else if (currentMessage is RtspRequest) { OnMessageReceived(new RtspChunkEventArgs(currentMessage)); } else if (currentMessage is RtspData) { OnDataReceived(new RtspChunkEventArgs(currentMessage)); } } else { _stream.Close(); break; } } } catch (OperationCanceledException) { _logger.Info("Operation canceled"); _stream.Close(); } // Don't report IO/Socket errors when canceled. // May occur as a result of connection termination catch (IOException error) when (!token.IsCancellationRequested) { _logger.Error("IO Error" + error); _stream.Close(); throw; } catch (SocketException error) when (!token.IsCancellationRequested) { _logger.Error("Socket Error" + error); _stream.Close(); throw; } catch (ObjectDisposedException error) { _logger.Error("Object Disposed" + error); throw; } catch (Exception error) { _logger.Error("Unknown Error" + error); throw; } finally { _logger.Info($"RTSP Connection with {_transport.RemoteAddress} terminated"); } } [Serializable] private enum ReadingState { NewCommand, Headers, Data, End, InterleavedData, MoreInterleavedData, } /// <summary> /// Sends the message. /// </summary> /// <param name="message">A message.</param> /// <returns><see cref="true"/> if it is Ok, otherwise <see cref="false"/></returns> public bool SendMessage(RtspMessage message) { if (message == null) throw new ArgumentNullException("message"); Contract.EndContractBlock(); if (!_transport.Connected) { if (!AutoReconnect) return false; _logger.Warn("Reconnect to a client, strange !!"); try { Reconnect(); } catch (SocketException) { // on a pas put se connecter on dit au manager de plus compter sur nous return false; } } // if it it a request we store the original message // and we renumber it. //TODO handle lost message (for example every minute cleanup old message) if (message is RtspRequest requestMsg) { // Original message has CSeq set. Make it so. message.CSeq = ++_sequenceNumber; RtspMessage originalMessage = message.Clone() as RtspMessage; ((RtspRequest)originalMessage).ContextData = requestMsg.ContextData; lock (_sentMessage) { _sentMessage.Add(message.CSeq, originalMessage as RtspRequest); } } _logger.Info("Send Message"); message.LogMessage(); message.SendTo(_transport.GetStream()); return true; } public Task Connect(string url) { return _transport.Connect(url); } /// <summary> /// Reconnect this instance of RtspListener. /// </summary> /// <exception cref="System.Net.Sockets.SocketException">Error during socket </exception> public void Reconnect() { //if it is already connected do not reconnect if (_transport.Connected) return; // If it is not connected listenthread should have die. if (_listenTask != null && !_listenTask.IsCompleted) _listenTask.Wait(); _stream?.Dispose(); // reconnect _transport.Reconnect(); _stream = _transport.GetStream(); // If listen thread exist restart it if (_listenTask != null) Start((CancellationToken)_listenTask.AsyncState); } /// <summary> /// Reads one message. /// </summary> /// <param name="commandStream">The Rtsp stream reader</param> /// <returns>Message reader</returns> public RtspChunk ReadOneMessage() { var commandStream = _transport.GetStream(); if (commandStream == null) throw new ArgumentNullException("commandStream"); Contract.EndContractBlock(); ReadingState currentReadingState = ReadingState.NewCommand; // current decode message , create a fake new to permit compile. RtspChunk currentMessage = null; int size = 0; int byteReaden = 0; List<byte> buffer = new List<byte>(256); string oneLine = String.Empty; while (currentReadingState != ReadingState.End) { // if the system is not reading binary data. if (currentReadingState != ReadingState.Data && currentReadingState != ReadingState.MoreInterleavedData) { oneLine = String.Empty; bool needMoreChar = true; // I do not know to make readline blocking while (needMoreChar) { int currentByte = commandStream.ReadByte(); switch (currentByte) { case -1: // the read is blocking, so if we got -1 it is because the client close; currentReadingState = ReadingState.End; needMoreChar = false; break; case '\n': oneLine = ASCIIEncoding.UTF8.GetString(buffer.ToArray()); buffer.Clear(); needMoreChar = false; break; case '\r': // simply ignore this break; case '$': // if first caracter of packet is $ it is an interleaved data packet if (currentReadingState == ReadingState.NewCommand && buffer.Count == 0) { currentReadingState = ReadingState.InterleavedData; needMoreChar = false; } else goto default; break; default: buffer.Add((byte)currentByte); break; } } } switch (currentReadingState) { case ReadingState.NewCommand: currentMessage = RtspMessage.GetRtspMessage(oneLine); currentReadingState = ReadingState.Headers; break; case ReadingState.Headers: string line = oneLine; if (string.IsNullOrEmpty(line)) { currentReadingState = ReadingState.Data; ((RtspMessage)currentMessage).InitialiseDataFromContentLength(); } else { ((RtspMessage)currentMessage).AddHeader(line); } break; case ReadingState.Data: if (currentMessage.Data.Length > 0) { // Read the remaning data int byteCount = commandStream.Read(currentMessage.Data, byteReaden, currentMessage.Data.Length - byteReaden); if (byteCount <= 0) { currentReadingState = ReadingState.End; break; } byteReaden += byteCount; _logger.Info($"Read {byteReaden} byte of data"); } // if we haven't read all go there again else go to end. if (byteReaden >= currentMessage.Data.Length) currentReadingState = ReadingState.End; break; case ReadingState.InterleavedData: currentMessage = new RtspData(); int channelByte = commandStream.ReadByte(); if (channelByte == -1) { currentReadingState = ReadingState.End; break; } ((RtspData)currentMessage).Channel = channelByte; int sizeByte1 = commandStream.ReadByte(); if (sizeByte1 == -1) { currentReadingState = ReadingState.End; break; } int sizeByte2 = commandStream.ReadByte(); if (sizeByte2 == -1) { currentReadingState = ReadingState.End; break; } size = (sizeByte1 << 8) + sizeByte2; currentMessage.Data = new byte[size]; currentReadingState = ReadingState.MoreInterleavedData; break; case ReadingState.MoreInterleavedData: // apparently non blocking { int byteCount = commandStream.Read(currentMessage.Data, byteReaden, size - byteReaden); if (byteCount <= 0) { currentReadingState = ReadingState.End; break; } byteReaden += byteCount; if (byteReaden < size) currentReadingState = ReadingState.MoreInterleavedData; else currentReadingState = ReadingState.End; break; } default: break; } } if (currentMessage != null) currentMessage.SourcePort = this; return currentMessage; } /// <summary> /// Begins the send data. /// </summary> /// <param name="aRtspData">A Rtsp data.</param> /// <param name="asyncCallback">The async callback.</param> /// <param name="aState">A state.</param> public IAsyncResult BeginSendData(RtspData aRtspData, AsyncCallback asyncCallback, object state) { if (aRtspData == null) throw new ArgumentNullException("aRtspData"); Contract.EndContractBlock(); return BeginSendData(aRtspData.Channel, aRtspData.Data, asyncCallback, state); } /// <summary> /// Begins the send data. /// </summary> /// <param name="channel">The channel.</param> /// <param name="frame">The frame.</param> /// <param name="asyncCallback">The async callback.</param> /// <param name="aState">A state.</param> public IAsyncResult BeginSendData(int channel, byte[] frame, AsyncCallback asyncCallback, object state) { if (frame == null) throw new ArgumentNullException("frame"); if (frame.Length > 0xFFFF) throw new ArgumentException("frame too large", "frame"); Contract.EndContractBlock(); if (!_transport.Connected) { if (!AutoReconnect) return null; // cannot write when transport is disconnected _logger.Warn("Reconnect to a client, strange !!"); Reconnect(); } byte[] data = new byte[4 + frame.Length]; // add 4 bytes for the header data[0] = 36; // '$' character data[1] = (byte)channel; data[2] = (byte)((frame.Length & 0xFF00) >> 8); data[3] = (byte)((frame.Length & 0x00FF)); System.Array.Copy(frame, 0, data, 4, frame.Length); return _stream.BeginWrite(data, 0, data.Length, asyncCallback, state); } /// <summary> /// Ends the send data. /// </summary> /// <param name="result">The result.</param> public void EndSendData(IAsyncResult result) { try { _stream.EndWrite(result); } catch (Exception e) { // Error, for example stream has already been Disposed _logger.Warn("Error during end send (can be ignored) " + e); result = null; } } /// <summary> /// Send data (Synchronous) /// </summary> /// <param name="channel">The channel.</param> /// <param name="frame">The frame.</param> public void SendData(int channel, byte[] frame) { if (frame == null) throw new ArgumentNullException("frame"); if (frame.Length > 0xFFFF) throw new ArgumentException("frame too large", "frame"); Contract.EndContractBlock(); if (!_transport.Connected) { if (!AutoReconnect) throw new Exception("Connection is lost"); _logger.Warn("Reconnect to a client, strange !!"); Reconnect(); } byte[] data = new byte[4 + frame.Length]; // add 4 bytes for the header data[0] = 36; // '$' character data[1] = (byte)channel; data[2] = (byte)((frame.Length & 0xFF00) >> 8); data[3] = (byte)((frame.Length & 0x00FF)); System.Array.Copy(frame, 0, data, 4, frame.Length); lock (_stream) { _stream.Write(data, 0, data.Length); } } #region IDisposable Membres public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { // Dispose "owned" elements only. _stream?.Dispose(); _stream = null; _transport = null; // Not owned } } #endregion } }
38.235
131
0.452596
[ "MIT" ]
Acidburn0zzz/JuvoPlayer
thirdparty/RTSP/RTSPListener.cs
22,345
C#
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; namespace LinqToDB.Linq.Builder { using LinqToDB.Expressions; using SqlQuery; partial class TableBuilder { static IBuildContext BuildCteContext(ExpressionBuilder builder, BuildInfo buildInfo) { var methodCall = (MethodCallExpression)buildInfo.Expression; Expression bodyExpr; IQueryable? query = null; string? name = null; bool isRecursive = false; switch (methodCall.Arguments.Count) { case 1 : bodyExpr = methodCall.Arguments[0].Unwrap(); break; case 2 : bodyExpr = methodCall.Arguments[0].Unwrap(); name = methodCall.Arguments[1].EvaluateExpression() as string; break; case 3 : query = methodCall.Arguments[0].EvaluateExpression() as IQueryable; bodyExpr = methodCall.Arguments[1].Unwrap(); name = methodCall.Arguments[2].EvaluateExpression() as string; isRecursive = true; break; default: throw new InvalidOperationException(); } bodyExpr = builder.ConvertExpression(bodyExpr); builder.RegisterCte(query, bodyExpr, () => new CteClause(null, bodyExpr.Type.GetGenericArguments()[0], isRecursive, name)); var cte = builder.BuildCte(bodyExpr, cteClause => { var info = new BuildInfo(buildInfo, bodyExpr, new SelectQuery()); var sequence = builder.BuildSequence(info); if (cteClause == null) cteClause = new CteClause(sequence.SelectQuery, bodyExpr.Type.GetGenericArguments()[0], isRecursive, name); else { cteClause.Body = sequence.SelectQuery; cteClause.Name = name; } return Tuple.Create(cteClause, (IBuildContext?)sequence); } ); var cteBuildInfo = new BuildInfo(buildInfo, bodyExpr, buildInfo.SelectQuery); var cteContext = new CteTableContext(builder, cteBuildInfo, cte.Item1, bodyExpr); // populate all fields if (isRecursive) cteContext.ConvertToSql(null, 0, ConvertFlags.All); return cteContext; } static CteTableContext BuildCteContextTable(ExpressionBuilder builder, BuildInfo buildInfo) { var queryable = (IQueryable)buildInfo.Expression.EvaluateExpression()!; var cteInfo = builder.RegisterCte(queryable, null, () => new CteClause(null, queryable.ElementType, false, "")); var cteBuildInfo = new BuildInfo(buildInfo, cteInfo.Item3, buildInfo.SelectQuery); var cteContext = new CteTableContext(builder, cteBuildInfo, cteInfo.Item1, cteInfo.Item3); return cteContext; } class CteTableContext : TableContext { private readonly CteClause _cte; private readonly Expression _cteExpression; private IBuildContext? _cteQueryContext; public CteTableContext(ExpressionBuilder builder, BuildInfo buildInfo, CteClause cte, Expression cteExpression) : base(builder, buildInfo, new SqlCteTable(builder.MappingSchema, cte)) { _cte = cte; _cteExpression = cteExpression; } IBuildContext? GetQueryContext() { return _cteQueryContext ??= Builder.GetCteContext(_cteExpression); } public override IsExpressionResult IsExpression(Expression? expression, int level, RequestFor requestFlag) { var queryContext = GetQueryContext(); if (queryContext == null) return base.IsExpression(expression, level, requestFlag); return queryContext.IsExpression(expression, level, requestFlag); } static string? GenerateAlias(Expression? expression) { string? alias = null; var current = expression; while (current?.NodeType == ExpressionType.MemberAccess) { var ma = (MemberExpression) current; alias = alias == null ? ma.Member.Name : ma.Member.Name + "_" + alias; current = ma.Expression; } return alias; } public override SqlInfo[] ConvertToSql(Expression? expression, int level, ConvertFlags flags) { var queryContext = GetQueryContext(); if (queryContext == null) return base.ConvertToSql(expression, level, flags); var baseInfos = base.ConvertToSql(null, 0, ConvertFlags.All); if (flags != ConvertFlags.All && _cte.Fields!.Length == 0 && queryContext.SelectQuery.Select.Columns.Count > 0) { // it means that queryContext context already has columns and we need all of them. For example for Distinct. ConvertToSql(null, 0, ConvertFlags.All); } expression = SequenceHelper.CorrectExpression(expression, this, queryContext); var infos = queryContext.ConvertToIndex(expression, level, flags); var result = infos .Select(info => { var baseInfo = baseInfos.FirstOrDefault(bi => bi.CompareMembers(info)); var alias = flags == ConvertFlags.Field ? GenerateAlias(expression) : null; if (alias == null) { alias = baseInfo?.MemberChain.LastOrDefault()?.Name ?? info.MemberChain.LastOrDefault()?.Name; } var field = RegisterCteField(baseInfo?.Sql, info.Sql, info.Index, alias); return new SqlInfo(info.MemberChain, field); }) .ToArray(); return result; } static string? GetColumnFriendlyAlias(SqlColumn column) { string? alias = null; var visited = new HashSet<ISqlExpression>(); ISqlExpression current = column; while (current is SqlColumn clmn && !visited.Contains(clmn)) { if (clmn.RawAlias != null) { alias = clmn.RawAlias; break; } visited.Add(clmn); current = clmn.Expression; } if (alias == null) { var field = current as SqlField; alias = field?.Name; } if (alias == null) alias = column.Alias; return alias; } void UpdateMissingFields() { // Collecting missed fields which has field in query. Should never happen. if (_cteQueryContext != null) { for (int i = 0; i < _cte.Fields!.Length; i++) { if (_cte.Fields[i] == null) { var column = _cte.Body!.Select.Columns[i]; _cte.Fields[i] = new SqlField(column.Alias!, column.Alias!); } } } } public override int ConvertToParentIndex(int index, IBuildContext? context) { if (context == _cteQueryContext) { var queryColumn = context!.SelectQuery.Select.Columns[index]; var alias = GetColumnFriendlyAlias(queryColumn); var field = RegisterCteField(null, queryColumn, index, alias); index = SelectQuery.Select.Add(field); UpdateMissingFields(); } return Parent?.ConvertToParentIndex(index, this) ?? index; } SqlField RegisterCteField(ISqlExpression? baseExpression, ISqlExpression expression, int index, string? alias) { if (expression == null) throw new ArgumentNullException(nameof(expression)); var cteField = _cte.RegisterFieldMapping(index, () => { var f = QueryHelper.GetUnderlyingField(baseExpression ?? expression); var newField = f == null ? new SqlField(expression.SystemType!, alias, expression.CanBeNull) : new SqlField(f); if (alias != null) newField.Name = alias; newField.PhysicalName = newField.Name; return newField; }); var field = SqlTable[cteField.Name!]; if (field == null) { field = new SqlField(cteField); SqlTable.Add(field); } return field; } public override void BuildQuery<T>(Query<T> query, ParameterExpression queryParameter) { var queryContext = GetQueryContext(); if (queryContext == null) base.BuildQuery(query, queryParameter); else { queryContext.Parent = this; queryContext.BuildQuery(query, queryParameter); } } public override Expression BuildExpression(Expression? expression, int level, bool enforceServerSide) { var queryContext = GetQueryContext(); if (queryContext == null) return base.BuildExpression(expression, level, enforceServerSide); queryContext.Parent = this; return queryContext.BuildExpression(expression, level, true); } public override SqlStatement GetResultStatement() { if (_cte.Fields!.Length == 0) { ConvertToSql(null, 0, ConvertFlags.Key); } return base.GetResultStatement(); } } } }
30.113074
127
0.650199
[ "MIT" ]
AndreyAndryushinPSB/linq2db
Source/LinqToDB/Linq/Builder/TableBuilder.CteTableContext.cs
8,242
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace workspacer { /// <summary> /// IWorkspace provides a common interface for workspace-related operations. /// workspaces logically contain a set of windows, and allow callers to interact with the /// windows via a set of methods, and all the organization of the windows via layout engines /// </summary> public interface IWorkspace { /// <summary> /// name of the workspace /// </summary> string Name { get; set; } /// <summary> /// name of the currently active layout /// </summary> string LayoutName { get; } /// <summary> /// names of the layout engines contained by this workspace /// </summary> IEnumerable<string> LayoutEngineNames { get; } /// <summary> /// set of windows that are contained within the workspace /// </summary> IEnumerable<IWindow> Windows { get; } /// <summary> /// set of windows that are contained within the workspace and which workspacer can layout. /// </summary> IList<IWindow> ManagedWindows { get; } /// <summary> /// currently focused window in the workspace, or null if there is no focused window in the workspace /// </summary> IWindow FocusedWindow { get; } /// <summary> /// the last focused window in the workspace /// </summary> IWindow LastFocusedWindow { get; } /// <summary> /// whether the workspace is currently indicating (flashing) /// </summary> bool IsIndicating { get; set; } void AddWindow(IWindow window, bool layout = true); void RemoveWindow(IWindow window, bool layout = true); void UpdateWindow(IWindow window, WindowUpdateType type, bool layout = true); /// <summary> /// close the currently focused window /// </summary> void CloseFocusedWindow(); // mod-shift-c /// <summary> /// rotate to the previous layout /// </summary> void PreviousLayoutEngine(); // mod-space /// <summary> /// rotate to the next layout /// </summary> void NextLayoutEngine(); // mod-space /// <summary> /// switches to the target layout /// </summary> void SwitchLayoutEngineToIndex(int targetIndex); /// <summary> /// reset the active layout /// </summary> void ResetLayout(); // mod-n /// <summary> /// focus the last focused window /// </summary> void FocusLastFocusedWindow(); /// <summary> /// rotate focus to the next window /// </summary> void FocusNextWindow(); // mod-j /// <summary> /// rotate focus to the previous window /// </summary> void FocusPreviousWindow(); // mod-k /// <summary> /// focus the primary window /// </summary> void FocusPrimaryWindow(); // mod-m /// <summary> /// swap the focus and primary windows /// </summary> void SwapFocusAndPrimaryWindow(); // mod-return /// <summary> /// swap the focus and next windows /// </summary> void SwapFocusAndNextWindow(); // mod-shift-j /// <summary> /// swap the focus and previous windows /// </summary> void SwapFocusAndPreviousWindow(); // mod-shift-k /// <summary> /// shrink the primary area of the active layout /// </summary> void ShrinkPrimaryArea(); // mod-h /// <summary> /// expand the primary area of the active layout /// </summary> void ExpandPrimaryArea(); // mod-l /// <summary> /// increase the number of primary windows in the active layout /// </summary> void IncrementNumberOfPrimaryWindows(); // mod-comma /// <summary> /// decrease the number of primary windows in the active layout /// </summary> void DecrementNumberOfPrimaryWindows(); // mod-period /// <summary> /// force a layout of the workspace /// </summary> void DoLayout(); /// <summary> /// swap the specified window to a (x,y) point in the workspace /// </summary> /// <param name="window">window to swap</param> /// <param name="x">x coordinate of the point</param> /// <param name="y">y coordinate of the point</param> void SwapWindowToPoint(IWindow window, int x, int y); /// <summary> /// check if the given point is in the workspace /// </summary> /// <param name="x">x coordinate of the point</param> /// <param name="y">y coordinate of the point</param> /// <returns>true if the point is inside the workspace, false otherwise</returns> bool IsPointInside(int x, int y); } }
31.419753
109
0.564047
[ "MIT" ]
dalyIsaac/workspacer
src/workspacer.Shared/Workspace/IWorkspace.cs
5,090
C#
// ReSharper disable UnusedAutoPropertyAccessor.Global namespace AlfaBot.Host.Model { /// <summary> /// DTO object for User controller /// </summary> public class UserOutDto { /// <summary> /// ChatId for User /// </summary> public long ChatId { get; set; } /// <summary> /// Telegram name /// </summary> public string TelegramName { get; set; } /// <summary> /// Correct name from answer /// </summary> public string Name { get; set; } /// <summary> /// Contact phone from contact telegram /// </summary> public string Phone { get; set; } /// <summary> /// Email from answer /// </summary> public string EMail { get; set; } /// <summary> /// Name of the university from answer /// </summary> public string University { get; set; } /// <summary> /// Profession from the answers /// </summary> public string Profession { get; set; } /// <summary> /// Course number from the answers /// </summary> public string Course { get; set; } } }
26.061224
54
0.483164
[ "MIT" ]
egorsh0/alfa-findit-telegram
src/AlfaBot.Host/Model/UserOutDto.cs
1,277
C#
using System.Collections.Generic; using System.IO; using System.Linq; using CSharpFunctionalExtensions; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.DependencyInjection; using NBitcoin; using Stratis.Bitcoin.Features.Wallet; using Stratis.Bitcoin.Features.Wallet.Controllers; using Stratis.Bitcoin.Features.Wallet.Interfaces; using Stratis.Bitcoin.Features.Wallet.Models; using Stratis.Bitcoin.IntegrationTests.Common; using Stratis.Bitcoin.IntegrationTests.Common.EnvironmentMockUpHelpers; using Stratis.Bitcoin.IntegrationTests.Common.ReadyData; using Stratis.Bitcoin.Networks; using Stratis.Bitcoin.Tests.Common; using Stratis.Bitcoin.Utilities.JsonErrors; using Xunit; namespace Stratis.Bitcoin.IntegrationTests.Wallet { public class WalletTests { private const string Password = "password"; private const string WalletName = "mywallet"; private const string Passphrase = "passphrase"; private const string Account = "account 0"; private readonly Network network; public WalletTests() { this.network = new BitcoinRegTest(); } [Fact] public void WalletCanReceiveAndSendCorrectly() { using (NodeBuilder builder = NodeBuilder.Create(this)) { CoreNode stratisSender = builder.CreateStratisPowNode(this.network).WithWallet().Start(); CoreNode stratisReceiver = builder.CreateStratisPowNode(this.network).WithWallet().Start(); int maturity = (int)stratisSender.FullNode.Network.Consensus.CoinbaseMaturity; TestHelper.MineBlocks(stratisSender, maturity + 1 + 5); // The mining should add coins to the wallet long total = stratisSender.FullNode.WalletManager().GetSpendableTransactionsInWallet(WalletName).Sum(s => s.Transaction.Amount); Assert.Equal(Money.COIN * 6 * 50, total); // Sync both nodes TestHelper.ConnectAndSync(stratisSender, stratisReceiver); // Send coins to the receiver HdAddress sendto = stratisReceiver.FullNode.WalletManager().GetUnusedAddress(new WalletAccountReference(WalletName, Account)); Transaction trx = stratisSender.FullNode.WalletTransactionHandler().BuildTransaction(CreateContext(stratisSender.FullNode.Network, new WalletAccountReference(WalletName, Account), Password, sendto.ScriptPubKey, Money.COIN * 100, FeeType.Medium, 101)); // Broadcast to the other node stratisSender.FullNode.NodeController<WalletController>().SendTransaction(new SendTransactionRequest(trx.ToHex())); // Wait for the transaction to arrive TestBase.WaitLoop(() => stratisReceiver.CreateRPCClient().GetRawMempool().Length > 0); TestBase.WaitLoop(() => stratisReceiver.FullNode.WalletManager().GetSpendableTransactionsInWallet(WalletName).Any()); long receivetotal = stratisReceiver.FullNode.WalletManager().GetSpendableTransactionsInWallet(WalletName).Sum(s => s.Transaction.Amount); Assert.Equal(Money.COIN * 100, receivetotal); Assert.Null(stratisReceiver.FullNode.WalletManager().GetSpendableTransactionsInWallet(WalletName).First().Transaction.BlockHeight); // Generate two new blocks so the transaction is confirmed TestHelper.MineBlocks(stratisSender, 2); // Wait for block repo for block sync to work TestBase.WaitLoop(() => TestHelper.AreNodesSynced(stratisReceiver, stratisSender)); Assert.Equal(Money.Coins(100), stratisReceiver.FullNode.WalletManager().GetBalances(WalletName, Account).Single().AmountConfirmed); } } [Fact] public void WalletCanReorg() { // This test has 4 parts: // Send first transaction from one wallet to another and wait for it to be confirmed // Send a second transaction and wait for it to be confirmed // Connect to a longer chain that causes a reorg so that the second trasnaction is undone // Mine the second transaction back in to the main chain using (NodeBuilder builder = NodeBuilder.Create(this)) { CoreNode stratisSender = builder.CreateStratisPowNode(this.network).WithWallet().Start(); CoreNode stratisReceiver = builder.CreateStratisPowNode(this.network).WithWallet().Start(); CoreNode stratisReorg = builder.CreateStratisPowNode(this.network).WithWallet().Start(); int maturity = (int)stratisSender.FullNode.Network.Consensus.CoinbaseMaturity; TestHelper.MineBlocks(stratisSender, maturity + 1 + 15); int currentBestHeight = maturity + 1 + 15; // The mining should add coins to the wallet. long total = stratisSender.FullNode.WalletManager().GetSpendableTransactionsInWallet(WalletName).Sum(s => s.Transaction.Amount); Assert.Equal(Money.COIN * 16 * 50, total); // Sync all nodes. TestHelper.ConnectAndSync(stratisReceiver, stratisSender); TestHelper.ConnectAndSync(stratisReceiver, stratisReorg); TestHelper.ConnectAndSync(stratisSender, stratisReorg); // Build Transaction 1. // Send coins to the receiver. HdAddress sendto = stratisReceiver.FullNode.WalletManager().GetUnusedAddress(new WalletAccountReference(WalletName, Account)); Transaction transaction1 = stratisSender.FullNode.WalletTransactionHandler().BuildTransaction(CreateContext(stratisSender.FullNode.Network, new WalletAccountReference(WalletName, Account), Password, sendto.ScriptPubKey, Money.COIN * 100, FeeType.Medium, 101)); // Broadcast to the other node. stratisSender.FullNode.NodeController<WalletController>().SendTransaction(new SendTransactionRequest(transaction1.ToHex())); // Wait for the transaction to arrive. TestBase.WaitLoop(() => stratisReceiver.CreateRPCClient().GetRawMempool().Length > 0); Assert.NotNull(stratisReceiver.CreateRPCClient().GetRawTransaction(transaction1.GetHash(), null, false)); TestBase.WaitLoop(() => stratisReceiver.FullNode.WalletManager().GetSpendableTransactionsInWallet(WalletName).Any()); long receivetotal = stratisReceiver.FullNode.WalletManager().GetSpendableTransactionsInWallet(WalletName).Sum(s => s.Transaction.Amount); Assert.Equal(Money.COIN * 100, receivetotal); Assert.Null(stratisReceiver.FullNode.WalletManager().GetSpendableTransactionsInWallet(WalletName).First().Transaction.BlockHeight); // Generate two new blocks so the transaction is confirmed. TestHelper.MineBlocks(stratisSender, 1); int transaction1MinedHeight = currentBestHeight + 1; TestHelper.MineBlocks(stratisSender, 1); currentBestHeight = currentBestHeight + 2; // Wait for block repo for block sync to work. TestBase.WaitLoop(() => TestHelper.AreNodesSynced(stratisReceiver, stratisSender)); TestBase.WaitLoop(() => TestHelper.AreNodesSynced(stratisReceiver, stratisReorg)); Assert.Equal(currentBestHeight, stratisReceiver.FullNode.ChainIndexer.Tip.Height); TestBase.WaitLoop(() => transaction1MinedHeight == stratisReceiver.FullNode.WalletManager().GetSpendableTransactionsInWallet(WalletName).First().Transaction.BlockHeight); // Build Transaction 2. // Remove the reorg node. TestHelper.Disconnect(stratisReceiver, stratisReorg); TestHelper.Disconnect(stratisSender, stratisReorg); ChainedHeader forkblock = stratisReceiver.FullNode.ChainIndexer.Tip; // Send more coins to the wallet sendto = stratisReceiver.FullNode.WalletManager().GetUnusedAddress(new WalletAccountReference(WalletName, Account)); Transaction transaction2 = stratisSender.FullNode.WalletTransactionHandler().BuildTransaction(CreateContext(stratisSender.FullNode.Network, new WalletAccountReference(WalletName, Account), Password, sendto.ScriptPubKey, Money.COIN * 10, FeeType.Medium, 101)); stratisSender.FullNode.NodeController<WalletController>().SendTransaction(new SendTransactionRequest(transaction2.ToHex())); // Wait for the transaction to arrive TestBase.WaitLoop(() => stratisReceiver.CreateRPCClient().GetRawMempool().Length > 0); Assert.NotNull(stratisReceiver.CreateRPCClient().GetRawTransaction(transaction2.GetHash(), null, false)); TestBase.WaitLoop(() => stratisReceiver.FullNode.WalletManager().GetSpendableTransactionsInWallet(WalletName).Any()); long newamount = stratisReceiver.FullNode.WalletManager().GetSpendableTransactionsInWallet(WalletName).Sum(s => s.Transaction.Amount); Assert.Equal(Money.COIN * 110, newamount); Assert.Contains(stratisReceiver.FullNode.WalletManager().GetSpendableTransactionsInWallet(WalletName), b => b.Transaction.BlockHeight == null); // Mine more blocks so it gets included in the chain. TestHelper.MineBlocks(stratisSender, 1); int transaction2MinedHeight = currentBestHeight + 1; TestHelper.MineBlocks(stratisSender, 1); currentBestHeight = currentBestHeight + 2; TestBase.WaitLoop(() => TestHelper.AreNodesSynced(stratisReceiver, stratisSender)); Assert.Equal(currentBestHeight, stratisReceiver.FullNode.ChainIndexer.Tip.Height); TestBase.WaitLoop(() => stratisReceiver.FullNode.WalletManager().GetSpendableTransactionsInWallet(WalletName).Any(b => b.Transaction.BlockHeight == transaction2MinedHeight)); // Create a reorg by mining on two different chains. // Advance both chains, one chain is longer. TestHelper.MineBlocks(stratisSender, 2); TestHelper.MineBlocks(stratisReorg, 10); currentBestHeight = forkblock.Height + 10; // Connect the reorg chain. TestHelper.Connect(stratisReceiver, stratisReorg); TestHelper.Connect(stratisSender, stratisReorg); // Wait for the chains to catch up. TestBase.WaitLoop(() => TestHelper.AreNodesSynced(stratisReceiver, stratisSender)); TestBase.WaitLoop(() => TestHelper.AreNodesSynced(stratisReceiver, stratisReorg, true)); Assert.Equal(currentBestHeight, stratisReceiver.FullNode.ChainIndexer.Tip.Height); // Ensure wallet reorg completes. TestBase.WaitLoop(() => stratisReceiver.FullNode.WalletManager().WalletTipHash == stratisReorg.CreateRPCClient().GetBestBlockHash()); // Check the wallet amount was rolled back. long newtotal = stratisReceiver.FullNode.WalletManager().GetSpendableTransactionsInWallet(WalletName).Sum(s => s.Transaction.Amount); Assert.Equal(receivetotal, newtotal); TestBase.WaitLoop(() => maturity + 1 + 16 == stratisReceiver.FullNode.WalletManager().GetSpendableTransactionsInWallet(WalletName).First().Transaction.BlockHeight); // ReBuild Transaction 2. // After the reorg transaction2 was returned back to mempool. stratisSender.FullNode.NodeController<WalletController>().SendTransaction(new SendTransactionRequest(transaction2.ToHex())); TestBase.WaitLoop(() => stratisReceiver.CreateRPCClient().GetRawMempool().Length > 0); // Mine the transaction again. TestHelper.MineBlocks(stratisSender, 1); transaction2MinedHeight = currentBestHeight + 1; TestHelper.MineBlocks(stratisSender, 1); currentBestHeight = currentBestHeight + 2; TestBase.WaitLoop(() => TestHelper.AreNodesSynced(stratisReceiver, stratisSender)); TestBase.WaitLoop(() => TestHelper.AreNodesSynced(stratisReceiver, stratisReorg)); Assert.Equal(currentBestHeight, stratisReceiver.FullNode.ChainIndexer.Tip.Height); long newsecondamount = stratisReceiver.FullNode.WalletManager().GetSpendableTransactionsInWallet(WalletName).Sum(s => s.Transaction.Amount); Assert.Equal(newamount, newsecondamount); TestBase.WaitLoop(() => stratisReceiver.FullNode.WalletManager().GetSpendableTransactionsInWallet(WalletName).Any(b => b.Transaction.BlockHeight == transaction2MinedHeight)); } } [Fact] public void BuildTransaction_From_ManyUtxos_EnoughFundsForFee() { using (NodeBuilder builder = NodeBuilder.Create(this)) { CoreNode node1 = builder.CreateStratisPowNode(this.network).WithWallet().Start(); CoreNode node2 = builder.CreateStratisPowNode(this.network).WithWallet().Start(); int maturity = (int) node1.FullNode.Network.Consensus.CoinbaseMaturity; TestHelper.MineBlocks(node1, maturity + 1 + 15); int currentBestHeight = maturity + 1 + 15; // The mining should add coins to the wallet. long total = node1.FullNode.WalletManager().GetSpendableTransactionsInWallet(WalletName).Sum(s => s.Transaction.Amount); Assert.Equal(Money.COIN * 16 * 50, total); // Sync all nodes. TestHelper.ConnectAndSync(node1, node2); const int utxosToSend = 500; const int howManyTimes = 8; for (int i = 0; i < howManyTimes; i++) { HdAddress sendto = node2.FullNode.WalletManager().GetUnusedAddress(new WalletAccountReference(WalletName, Account)); SendManyUtxosTransaction(node1, sendto.ScriptPubKey, Money.FromUnit(907700, MoneyUnit.Satoshi), utxosToSend); } TestBase.WaitLoop(() => node1.CreateRPCClient().GetRawMempool().Length == howManyTimes); TestHelper.MineBlocks(node1, 1); TestHelper.WaitForNodeToSync(node1, node2); var transactionsToSpend = node2.FullNode.WalletManager().GetSpendableTransactionsInWallet(WalletName); Assert.Equal(utxosToSend * howManyTimes, transactionsToSpend.Count()); // Firstly, build a tx with value 1. Previously this would fail as the WalletTransactionHandler didn't pass enough UTXOs. IActionResult result = node2.FullNode.NodeController<WalletController>().BuildTransaction( new BuildTransactionRequest { WalletName = WalletName, AccountName = "account 0", FeeAmount = "0.1", Password = Password, Recipients = new List<RecipientModel> { new RecipientModel { Amount = "1", DestinationAddress = node1.FullNode.WalletManager() .GetUnusedAddress(new WalletAccountReference(WalletName, Account)).Address } } }); JsonResult jsonResult = (JsonResult) result; Assert.NotNull(((WalletBuildTransactionModel)jsonResult.Value).TransactionId); } } [Fact] public void Given_TheNodeHadAReorg_And_WalletTipIsBehindConsensusTip_When_ANewBlockArrives_Then_WalletCanRecover() { using (NodeBuilder builder = NodeBuilder.Create(this)) { CoreNode stratisSender = builder.CreateStratisPowNode(this.network).WithReadyBlockchainData(ReadyBlockchain.BitcoinRegTest10Miner).Start(); CoreNode stratisReceiver = builder.CreateStratisPowNode(this.network).Start(); CoreNode stratisReorg = builder.CreateStratisPowNode(this.network).WithWallet().Start(); // Sync all nodes. TestHelper.ConnectAndSync(stratisReceiver, stratisSender); TestHelper.ConnectAndSync(stratisReceiver, stratisReorg); TestHelper.ConnectAndSync(stratisSender, stratisReorg); // Remove the reorg node. TestHelper.Disconnect(stratisReceiver, stratisReorg); TestHelper.Disconnect(stratisSender, stratisReorg); // Create a reorg by mining on two different chains. // Advance both chains, one chain is longer. TestHelper.MineBlocks(stratisSender, 2); TestHelper.MineBlocks(stratisReorg, 10); // Rewind the wallet for the stratisReceiver node. (stratisReceiver.FullNode.NodeService<IWalletSyncManager>() as WalletSyncManager).SyncFromHeight(5); // Connect the reorg chain. TestHelper.ConnectAndSync(stratisReceiver, stratisReorg); TestHelper.ConnectAndSync(stratisSender, stratisReorg); // Wait for the chains to catch up. TestBase.WaitLoop(() => TestHelper.AreNodesSynced(stratisReceiver, stratisSender)); TestBase.WaitLoop(() => TestHelper.AreNodesSynced(stratisReceiver, stratisReorg)); Assert.Equal(20, stratisReceiver.FullNode.ChainIndexer.Tip.Height); TestHelper.MineBlocks(stratisSender, 5); TestBase.WaitLoop(() => TestHelper.AreNodesSynced(stratisReceiver, stratisSender)); Assert.Equal(25, stratisReceiver.FullNode.ChainIndexer.Tip.Height); } } [Fact] public void Given_TheNodeHadAReorg_And_ConsensusTipIsdifferentFromWalletTip_When_ANewBlockArrives_Then_WalletCanRecover() { using (NodeBuilder builder = NodeBuilder.Create(this)) { CoreNode stratisSender = builder.CreateStratisPowNode(this.network).WithReadyBlockchainData(ReadyBlockchain.BitcoinRegTest10Miner).Start(); CoreNode stratisReceiver = builder.CreateStratisPowNode(this.network).Start(); CoreNode stratisReorg = builder.CreateStratisPowNode(this.network).WithDummyWallet().Start(); // Sync all nodes. TestHelper.ConnectAndSync(stratisReceiver, stratisSender); TestHelper.ConnectAndSync(stratisReceiver, stratisReorg); TestHelper.ConnectAndSync(stratisSender, stratisReorg); // Remove the reorg node and wait for node to be disconnected. TestHelper.Disconnect(stratisReceiver, stratisReorg); TestHelper.Disconnect(stratisSender, stratisReorg); // Create a reorg by mining on two different chains. // Advance both chains, one chain is longer. TestHelper.MineBlocks(stratisSender, 2); TestHelper.MineBlocks(stratisReorg, 10); // Connect the reorg chain. TestHelper.ConnectAndSync(stratisReceiver, stratisReorg); TestHelper.ConnectAndSync(stratisSender, stratisReorg); // Wait for the chains to catch up. TestBase.WaitLoop(() => TestHelper.AreNodesSynced(stratisReceiver, stratisSender)); TestBase.WaitLoop(() => TestHelper.AreNodesSynced(stratisReceiver, stratisReorg)); Assert.Equal(20, stratisReceiver.FullNode.ChainIndexer.Tip.Height); // Rewind the wallet in the stratisReceiver node. (stratisReceiver.FullNode.NodeService<IWalletSyncManager>() as WalletSyncManager).SyncFromHeight(10); TestHelper.MineBlocks(stratisSender, 5); TestBase.WaitLoop(() => TestHelper.AreNodesSynced(stratisReceiver, stratisSender)); Assert.Equal(25, stratisReceiver.FullNode.ChainIndexer.Tip.Height); } } [Fact] public void WalletCanCatchupWithBestChain() { using (NodeBuilder builder = NodeBuilder.Create(this)) { CoreNode stratisminer = builder.CreateStratisPowNode(this.network).WithReadyBlockchainData(ReadyBlockchain.BitcoinRegTest10Miner).Start(); // Push the wallet back. stratisminer.FullNode.Services.ServiceProvider.GetService<IWalletSyncManager>().SyncFromHeight(5); TestHelper.MineBlocks(stratisminer, 5); } } [Fact(Skip = "Investigate PeerConnector shutdown timeout issue")] public void WalletCanRecoverOnStartup() { using (NodeBuilder builder = NodeBuilder.Create(this)) { CoreNode stratisNodeSync = builder.CreateStratisPowNode(this.network).WithWallet().Start(); TestHelper.MineBlocks(stratisNodeSync, 10); // Set the tip of best chain some blocks in the past stratisNodeSync.FullNode.ChainIndexer.SetTip(stratisNodeSync.FullNode.ChainIndexer.GetHeader(stratisNodeSync.FullNode.ChainIndexer.Height - 5)); // Stop the node (it will persist the chain with the reset tip) stratisNodeSync.FullNode.Dispose(); CoreNode newNodeInstance = builder.CloneStratisNode(stratisNodeSync); // Load the node, this should hit the block store recover code newNodeInstance.Start(); // Check that store recovered to be the same as the best chain. Assert.Equal(newNodeInstance.FullNode.ChainIndexer.Tip.HashBlock, newNodeInstance.FullNode.WalletManager().WalletTipHash); } } public static TransactionBuildContext CreateContext(Network network, WalletAccountReference accountReference, string password, Script destinationScript, Money amount, FeeType feeType, int minConfirmations) { return new TransactionBuildContext(network) { AccountReference = accountReference, MinConfirmations = minConfirmations, FeeType = feeType, WalletPassword = password, Recipients = new[] { new Recipient { Amount = amount, ScriptPubKey = destinationScript } }.ToList() }; } /// <summary> /// Copies the test wallet into data folder for node if it isn't already present. /// </summary> /// <param name="path">The path of the folder to move the wallet to.</param> private void InitializeTestWallet(string path) { string testWalletPath = Path.Combine(path, "test.wallet.json"); if (!File.Exists(testWalletPath)) File.Copy("Data/test.wallet.json", testWalletPath); } private static Result<WalletSendTransactionModel> SendManyUtxosTransaction(CoreNode node, Script scriptPubKey, Money amount, int utxos = 1) { Recipient[] recipients = new Recipient[utxos]; for (int i = 0; i < recipients.Length; i++) { recipients[i] = new Recipient { Amount = amount, ScriptPubKey = scriptPubKey }; } var txBuildContext = new TransactionBuildContext(node.FullNode.Network) { AccountReference = new WalletAccountReference(WalletName, "account 0"), MinConfirmations = 1, FeeType = FeeType.Medium, WalletPassword = Password, Recipients = recipients.ToList() }; Transaction trx = (node.FullNode.NodeService<IWalletTransactionHandler>() as IWalletTransactionHandler).BuildTransaction(txBuildContext); // Broadcast to the other node. IActionResult result = node.FullNode.NodeController<WalletController>().SendTransaction(new SendTransactionRequest(trx.ToHex())); if (result is ErrorResult errorResult) { var errorResponse = (ErrorResponse)errorResult.Value; return Result.Fail<WalletSendTransactionModel>(errorResponse.Errors[0].Message); } JsonResult response = (JsonResult)result; return Result.Ok((WalletSendTransactionModel)response.Value); } } }
55.660714
276
0.648219
[ "MIT" ]
AYCHPay/AYCHPayGenesisFullnode
src/Stratis.Bitcoin.IntegrationTests/Wallet/WalletTests.cs
24,938
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Win32; namespace BPUtil { /// <summary> /// Provides utility methods for accessing the Windows Registry. /// </summary> public static class RegistryUtil { /// <summary> /// Set = true to read entries written by 32 bit programs on 64 bit Windows. /// /// On 32 bit Windows, this setting has no effect. /// </summary> public static bool Force32BitRegistryAccess = false; /// <summary> /// Gets HKEY_LOCAL_MACHINE in either the 32 or 64 bit view depending on RegistryUtil configuration and OS version. /// </summary> /// <returns></returns> public static RegistryKey HKLM { get { if (!Force32BitRegistryAccess && Environment.Is64BitOperatingSystem) return RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64); else return RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32); } } /// <summary> /// Gets HKEY_CURRENT_USER in either the 32 or 64 bit view depending on RegistryUtil configuration and OS version. /// </summary> /// <returns></returns> public static RegistryKey HKCU { get { if (!Force32BitRegistryAccess && Environment.Is64BitOperatingSystem) return RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry64); else return RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry32); } } /// <summary> /// Returns the requested RegistryKey or null if the key does not exist. /// </summary> /// <param name="path">A path relative to HKEY_LOCAL_MACHINE. E.g. "SOFTWARE\\Microsoft"</param> /// <returns></returns> public static RegistryKey GetHKLMKey(string path) { return HKLM.OpenSubKey(path); } /// <summary> /// Returns the requested RegistryKey or null if the key does not exist. /// </summary> /// <param name="path">A path relative to HKEY_CURRENT_USER. E.g. "SOFTWARE\\Microsoft"</param> /// <returns></returns> public static RegistryKey GetHKCUKey(string path) { return HKCU.OpenSubKey(path); } /// <summary> /// Gets the value of a registry key in HKEY_LOCAL_MACHINE. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="path">A path relative to HKEY_LOCAL_MACHINE. E.g. "SOFTWARE\\Microsoft"</param> /// <param name="key">Key</param> /// <param name="defaultValue">Value to return if the key does not exist.</param> /// <returns></returns> public static T GetHKLMValue<T>(string path, string key, T defaultValue) { object value = HKLM.OpenSubKey(path)?.GetValue(key); if (value == null) return defaultValue; return (T)value; } /// <summary> /// Gets the value of a registry key in HKEY_CURRENT_USER. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="path">A path relative to HKEY_CURRENT_USER. E.g. "SOFTWARE\\Microsoft"</param> /// <param name="key">Key</param> /// <param name="defaultValue">Value to return if the key does not exist.</param> /// <returns></returns> public static T GetHKCUValue<T>(string path, string key, T defaultValue) { object value = HKCU.OpenSubKey(path)?.GetValue(key); if (value == null) return defaultValue; return (T)value; } /// <summary> /// Attempts to set the value of the specified registry key, throwing an exception if it fails. /// </summary> /// <param name="path">Path to the folder where the key is located, relative to HKEY_LOCAL_MACHINE.</param> /// <param name="key">Name of the key to set the value of.</param> /// <param name="value">Value to set.</param> /// <param name="valueKind">The type of value stored in this registry key.</param> /// <returns></returns> public static void SetHKLMValue(string path, string key, object value, RegistryValueKind valueKind = RegistryValueKind.Unknown) { RegistryKey sk = HKLM.CreateSubKey(path); if (valueKind == RegistryValueKind.Unknown) sk.SetValue(key, value); sk.SetValue(key, value, valueKind); } /// <summary> /// Attempts to set the value of the specified registry key, throwing an exception if it fails. /// </summary> /// <param name="path">Path to the folder where the key is located, relative to HKEY_CURRENT_USER.</param> /// <param name="key">Name of the key to set the value of.</param> /// <param name="value">Value to set.</param> /// <param name="valueKind">The type of value stored in this registry key.</param> /// <returns></returns> public static void SetHKCUValue(string path, string key, object value, RegistryValueKind valueKind = RegistryValueKind.Unknown) { RegistryKey sk = HKCU.CreateSubKey(path); if (valueKind == RegistryValueKind.Unknown) sk.SetValue(key, value); sk.SetValue(key, value, valueKind); } /// <summary> /// Attempts to set the value of the specified registry key, returning true if successful or false if not. /// </summary> /// <param name="path">Path to the folder where the key is located, relative to HKEY_LOCAL_MACHINE.</param> /// <param name="key">Name of the key to set the value of.</param> /// <param name="value">Value to set.</param> /// <param name="valueKind">The type of value stored in this registry key.</param> /// <returns></returns> public static bool SetHKLMValueSafe(string path, string key, object value, RegistryValueKind valueKind = RegistryValueKind.Unknown) { try { SetHKLMValue(path, key, value, valueKind); return true; } catch { return false; } } /// <summary> /// Attempts to set the value of the specified registry key, returning true if successful or false if not. /// </summary> /// <param name="path">Path to the folder where the key is located, relative to HKEY_CURRENT_USER.</param> /// <param name="key">Name of the key to set the value of.</param> /// <param name="value">Value to set.</param> /// <param name="valueKind">The type of value stored in this registry key.</param> /// <returns></returns> public static bool SetHKCUValueSafe(string path, string key, object value, RegistryValueKind valueKind = RegistryValueKind.Unknown) { try { SetHKCUValue(path, key, value, valueKind); return true; } catch { return false; } } public static string GetStringValue(RegistryKey key, string name) { object obj = key.GetValue(name); if (obj == null) return ""; return obj.ToString(); } public static int GetIntValue(RegistryKey key, string name, int defaultValue) { object obj = key.GetValue(name); if (obj == null) return defaultValue; if (typeof(int).IsAssignableFrom(obj.GetType())) return (int)obj; int val; if (int.TryParse(obj.ToString(), out val)) return val; return defaultValue; } public static long GetLongValue(RegistryKey key, string name, long defaultValue) { //if (ThrowWhenReadingIncompatibleValueTypes) //{ // RegistryValueKind kind = key.GetValueKind(name); // if (kind != RegistryValueKind.QWord) // throw new Exception("Type of \"" + key.Name + "/" + name + "\" is " + kind + ". Expected QWord."); //} object obj = key.GetValue(name); if (obj == null) return defaultValue; if (typeof(long).IsAssignableFrom(obj.GetType())) return (long)obj; long val; if (long.TryParse(obj.ToString(), out val)) return val; return defaultValue; } } /// <summary> /// Provides a cleaner interface for reading registry values from a RegistryKey. /// </summary> public class RegEdit { public readonly RegistryKey key; /// <summary> /// If true, values must already exist and be the expected type, or else an exception will be thrown. /// </summary> public bool typeCheck = false; public RegEdit(RegistryKey key) { this.key = key; } /// <summary> /// Reads a String value. /// </summary> /// <param name="name">Case-insensitive value name.</param> /// <returns></returns> public string String(string name) { if (typeCheck) { RegistryValueKind kind = key.GetValueKind(name); if (kind != RegistryValueKind.String) throw new Exception("Type of \"" + key.Name + "/" + name + "\" is " + kind + ". Expected String."); } else if (key == null || !key.GetValueNames().Contains(name, true)) return null; else { RegistryValueKind kind = key.GetValueKind(name); if (kind != RegistryValueKind.String) return null; } return (string)this.key.GetValue(name); } /// <summary> /// Reads a DWord (32 bit integer) value. /// </summary> /// <param name="name">Case-insensitive value name.</param> /// <returns></returns> public int DWord(string name) { if (typeCheck) { RegistryValueKind kind = key.GetValueKind(name); if (kind != RegistryValueKind.DWord) throw new Exception("Type of \"" + key.Name + "/" + name + "\" is " + kind + ". Expected DWord."); } else if (key == null || !key.GetValueNames().Contains(name, true)) return 0; else { RegistryValueKind kind = key.GetValueKind(name); if (kind != RegistryValueKind.DWord) return 0; } return (int)this.key.GetValue(name); } /// <summary> /// Reads a QWord (64 bit integer) value. /// </summary> /// <param name="name">Case-insensitive value name.</param> /// <returns></returns> public long QWord(string name) { if (typeCheck) { RegistryValueKind kind = key.GetValueKind(name); if (kind != RegistryValueKind.QWord) throw new Exception("Type of \"" + key.Name + "/" + name + "\" is " + kind + ". Expected QWord."); } else if (key == null || !key.GetValueNames().Contains(name, true)) return 0; else { RegistryValueKind kind = key.GetValueKind(name); if (kind != RegistryValueKind.QWord) return 0; } return (long)this.key.GetValue(name); } /// <summary> /// Writes a String value. /// </summary> /// <param name="name">Value name</param> /// <param name="value"></param> public void String(string name, string value) { if (typeCheck) { RegistryValueKind kind = key.GetValueKind(name); if (kind != RegistryValueKind.String) throw new Exception("Type of \"" + key.Name + "/" + name + "\" is " + kind + ". Expected String."); } if (value == null) value = ""; this.key.SetValue(name, value, RegistryValueKind.String); } /// <summary> /// Writes a DWord (32 bit integer) value. /// </summary> /// <param name="name">Value name</param> /// <param name="value"></param> public void DWord(string name, int value) { if (typeCheck) { RegistryValueKind kind = key.GetValueKind(name); if (kind != RegistryValueKind.DWord) throw new Exception("Type of \"" + key.Name + "/" + name + "\" is " + kind + ". Expected DWord."); } this.key.SetValue(name, value, RegistryValueKind.DWord); } /// <summary> /// Writes a QWord (64 bit integer) value. /// </summary> /// <param name="name">Value name</param> /// <param name="value"></param> public void QWord(string name, long value) { if (typeCheck) { RegistryValueKind kind = key.GetValueKind(name); if (kind != RegistryValueKind.QWord) throw new Exception("Type of \"" + key.Name + "/" + name + "\" is " + kind + ". Expected QWord."); } this.key.SetValue(name, value, RegistryValueKind.QWord); } } }
33.38484
133
0.659244
[ "Unlicense" ]
bp2008/BPUtil
BPUtil/RegistryUtil.cs
11,453
C#
using Stepometer.Page; using System; using System.Collections.Generic; using Stepometer.Controls; using Xamarin.Forms; namespace Stepometer { public partial class AppShell : Shell { public Dictionary<string, Type> Routes { get; private set; } = new Dictionary<string, Type>(); public AppShell() { InitializeComponent(); RegisterRoutes(); BindingContext = this; } void RegisterRoutes() { Routes.Add(nameof(LoginPage), typeof(LoginPage)); Routes.Add(nameof(StepometerPage), typeof(StepometerPage)); Routes.Add(nameof(HistoryPage), typeof(HistoryPage)); Routes.Add(nameof(FriendsPage), typeof(FriendsPage)); Routes.Add(nameof(AchievePage), typeof(AchievePage)); foreach (var item in Routes) { Routing.RegisterRoute(item.Key, item.Value); } } } }
28.323529
102
0.597092
[ "MIT" ]
BlockiyDmitriy/Stepometer.Client
Stepometr/Stepometr/Stepometr/AppShell.xaml.cs
965
C#
// Copyright (c) Josef Pihrt. All rights reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. namespace Orang.CommandLine { internal abstract class CommonListCommandOptions : AbstractCommandOptions { internal CommonListCommandOptions() { } public string Filter { get; internal set; } } }
28.642857
160
0.700748
[ "Apache-2.0" ]
atifaziz/Orang
src/CommandLine/CommandOptions/CommonListCommandOptions.cs
403
C#