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
//------------------------------------------------------------------------------ // <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 WindowsNetworkTypeSwitcher.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; } } } }
34.870968
151
0.587419
[ "MIT" ]
FloTurtle/WindowsNetworkTypeSwitcher
WindowsNetworkTypeSwitcher/Properties/Settings.Designer.cs
1,083
C#
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MyExtensions { //Only 2 dimensional (for now) //Also only 2 states public class CellularAutomaton { public const int MaxStates = byte.MaxValue; public enum BorderType { Solid, Empty, Normal } //Not very efficient memory, but I'm "naive" private int swapSection = 0; private byte[, ,] swapGrid; private Random random; private static Random randomSeeds = new Random(); private readonly object SeedLocker = new object(); public CellularAutomaton(int width, int height, int seed = 0) { swapGrid = new byte[width + 2, height + 2, 2]; if (seed != 0) { random = new Random(seed); } else { lock (SeedLocker) { random = new Random(randomSeeds.Next()); } } } public void Simulate(List<int> surviveStates, List<int> bornStates, BorderType border, double fillPercent, int simulations) { swapSection = 0; //Initialize for (int i = 0; i < swapGrid.GetLength(0); i++) for (int j = 0; j < swapGrid.GetLength(1); j++) swapGrid[i, j, swapSection] = (byte)(random.NextDouble() <= fillPercent ? 1 : 0); //Fix up edges for (int i = 0; i < swapGrid.GetLength(0); i++) { if (border == BorderType.Empty) { swapGrid[i, 0, swapSection] = 0; swapGrid[i, swapGrid.GetLength(1) - 1, swapSection] = 0; } else if (border == BorderType.Solid) { swapGrid[i, 0, swapSection] = 1; swapGrid[i, swapGrid.GetLength(1) - 1, swapSection] = 1; } } for (int i = 0; i < swapGrid.GetLength(1); i++) { if (border == BorderType.Empty) { swapGrid[0, i, swapSection] = 0; swapGrid[swapGrid.GetLength(0) - 1, i, swapSection] = 0; } else if (border == BorderType.Solid) { swapGrid[0, i, swapSection] = 1; swapGrid[swapGrid.GetLength(0) - 1, i, swapSection] = 1; } } //Simulate for (int i = 0; i < simulations; i++) { Parallel.For(1, swapGrid.GetLength(0) - 1, x => { for (int y = 1; y < swapGrid.GetLength(1) - 1; y++) { int alives = 0; for (int xx = -1; xx <= 1; xx++) for (int yy = -1; yy <= 1; yy++) if (!(xx == 0 && yy == 0) && swapGrid[x + xx, y + yy, swapSection] > 0) alives++; //Swap states if necessary if (swapGrid[x, y, swapSection] == 0 && bornStates.Contains(alives) || swapGrid[x, y, swapSection] == 1 && !surviveStates.Contains(alives)) swapGrid[x, y, (swapSection + 1) % 2] = (byte)((swapGrid[x, y, swapSection] + 1) % 2); else swapGrid[x, y, (swapSection + 1) % 2] = swapGrid[x, y, swapSection]; } }); swapSection = (swapSection + 1) % 2; } } public byte[,] GetGrid() { byte[,] realGrid = new byte[swapGrid.GetLength(0) - 2, swapGrid.GetLength(1) - 2]; for (int i = 1; i < swapGrid.GetLength(0) - 1; i++) for (int j = 1; j < swapGrid.GetLength(1) - 1; j++) realGrid[i - 1, j - 1] = swapGrid[i, j, swapSection]; return realGrid; } public Bitmap GetImage(int expand = 1) { byte[,] data = GetGrid(); Bitmap image = new Bitmap(data.GetLength(0) * expand, data.GetLength(1) * expand); using (Graphics g = Graphics.FromImage(image)) { for (int i = 0; i < data.GetLength(0); i++) for (int j = 0; j < data.GetLength(1); j++) g.FillRectangle((data[i, j] == 1 ? Brushes.Black : Brushes.Gray), i * expand, j * expand, expand, expand); //image.SetPixel(i, j, (data[i, j] == 1 ? Color.Black : Color.White)); } return image; } } }
26.485507
125
0.585226
[ "MIT" ]
randomouscrap98/MyExtensions
MyExtensions/CellularAutomaton.cs
3,657
C#
using System; using System.Threading.Tasks; namespace FreeSql { public interface ICache { /// <summary> /// 缓存数据时序列化方法,若无设置则默认使用 Json.net /// </summary> Func<object, string> Serialize { get; set; } /// <summary> /// 获取缓存数据时反序列化方法,若无设置则默认使用 Json.net /// </summary> Func<string, Type, object> Deserialize { get; set; } /// <summary> /// 缓存可序列化数据 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key">缓存键</param> /// <param name="data">可序列化数据</param> /// <param name="timeoutSeconds">缓存秒数,&lt;=0时永久缓存</param> void Set<T>(string key, T data, int timeoutSeconds = 0); /// <summary> /// 循环或批量获取缓存数据 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"></param> /// <returns></returns> T Get<T>(string key); /// <summary> /// 循环或批量获取缓存数据 /// </summary> /// <param name="key"></param> /// <returns></returns> string Get(string key); /// <summary> /// 循环或批量删除缓存键 /// </summary> /// <param name="keys">缓存键[数组]</param> void Remove(params string[] keys); /// <summary> /// 缓存壳 /// </summary> /// <typeparam name="T">缓存类型</typeparam> /// <param name="key">缓存键</param> /// <param name="timeoutSeconds">缓存秒数</param> /// <param name="getData">获取源数据的函数</param> /// <returns></returns> T Shell<T>(string key, int timeoutSeconds, Func<T> getData); /// <summary> /// 缓存壳(哈希表) /// </summary> /// <typeparam name="T">缓存类型</typeparam> /// <param name="key">缓存键</param> /// <param name="field">字段</param> /// <param name="timeoutSeconds">缓存秒数</param> /// <param name="getData">获取源数据的函数</param> /// <returns></returns> T Shell<T>(string key, string field, int timeoutSeconds, Func<T> getData); /// <summary> /// 缓存可序列化数据 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key">缓存键</param> /// <param name="data">可序列化数据</param> /// <param name="timeoutSeconds">缓存秒数,&lt;=0时永久缓存</param> Task SetAsync<T>(string key, T data, int timeoutSeconds = 0); /// <summary> /// 循环或批量获取缓存数据 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"></param> /// <returns></returns> Task<T> GetAsync<T>(string key); /// <summary> /// 循环或批量获取缓存数据 /// </summary> /// <param name="key"></param> /// <returns></returns> Task<string> GetAsync(string key); /// <summary> /// 循环或批量删除缓存键 /// </summary> /// <param name="keys">缓存键[数组]</param> Task RemoveAsync(params string[] keys); /// <summary> /// 缓存壳 /// </summary> /// <typeparam name="T">缓存类型</typeparam> /// <param name="key">缓存键</param> /// <param name="timeoutSeconds">缓存秒数</param> /// <param name="getDataAsync">获取源数据的函数</param> /// <returns></returns> Task<T> ShellAsync<T>(string key, int timeoutSeconds, Func<Task<T>> getDataAsync); /// <summary> /// 缓存壳(哈希表) /// </summary> /// <typeparam name="T">缓存类型</typeparam> /// <param name="key">缓存键</param> /// <param name="field">字段</param> /// <param name="timeoutSeconds">缓存秒数</param> /// <param name="getDataAsync">获取源数据的函数</param> /// <returns></returns> Task<T> ShellAsync<T>(string key, string field, int timeoutSeconds, Func<Task<T>> getDataAsync); } }
29.321101
98
0.601377
[ "MIT" ]
orm-core-group/FreeSql
FreeSql/Interface/ICache.cs
3,736
C#
using Contoso.Provisioning.Cloud.SyncWeb.ApplicationLogic; using Contoso.Provisioning.Cloud.SyncWeb.Modules; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Xml.Linq; namespace Contoso.Provisioning.Cloud.SyncWeb { public partial class Default : System.Web.UI.Page { private IEnumerable<XElement> templates; protected void Page_PreInit(object sender, EventArgs e) { Uri redirectUrl; switch (SharePointContextProvider.CheckRedirectionStatus(Context, out redirectUrl)) { case RedirectionStatus.Ok: return; case RedirectionStatus.ShouldRedirect: Response.Redirect(redirectUrl.AbsoluteUri, endResponse: true); break; case RedirectionStatus.CanNotRedirect: Response.Write("An error occurred while processing your request."); Response.End(); break; } } protected void Page_Load(object sender, EventArgs e) { string validationScript = @" $(document).ready(function () { $('#btnCreate').click(function () { var valid = true; for (i = 0; i < validationChecks.length; i++) { var v = validationChecks[i](); if (!v) valid = false; } return valid; }); var isDialog = decodeURIComponent(getQueryStringParameter('IsDlg')); if (isDialog == '1') { MakeSSCDialogPageVisible(); UpdateSSCDialogPageSize(); $('#btnCancel').click(function () { closeDialog(); return false; }); } });"; ScriptManager.RegisterClientScriptBlock(this, typeof(Default), "ValidationScript", validationScript, true); //load templates each time based on dialog if (Page.Request["IsDlg"].Contains("1")) { templates = this.Configuration.Root.Descendants("Template").Where(i => !i.Attribute("SubWebOnly").Value.Equals("true", StringComparison.CurrentCultureIgnoreCase)); lblBasePath.Text = Request["SPHostUrl"].Substring(0, 8 + Request["SPHostUrl"].Substring(8).IndexOf("/")) + "/"; } else { templates = this.Configuration.Root.Descendants("Template").Where(i => !i.Attribute("RootWebOnly").Value.Equals("true", StringComparison.CurrentCultureIgnoreCase)); lblBasePath.Text = Request["SPHostUrl"] + "/"; btnCancel.Click += btnCancel_Click; } if (!this.IsPostBack) { //get url path to host site (will serve as base path for subsites) Uri url = SharePointContext.GetSPHostUrl(HttpContext.Current.Request); // Show the available templates from configuration foreach (XElement element in templates) { listSites.Items.Add(new ListItem(element.Attribute("Title").Value, element.Attribute("Name").Value)); } } //load modules every time since they are dynamic LoadModules(); // Verify that configuration list exists in the root site of the tenant / web application new DeployManager().EnsureConfigurationListInTenant(Page.Request["SPHostUrl"]); } public XDocument Configuration { get { if (Cache["Config"] == null) { string fileUrl = Server.MapPath("~/Configuration/Configuration.xml"); XDocument doc = XDocument.Load(fileUrl); Cache["Config"] = doc; return doc; } else { return (XDocument)Cache["Config"]; } } } protected void btnCancel_Click(object sender, EventArgs e) { Response.Redirect(Page.Request["SPHostUrl"]); } protected void btnCreate_Click(object sender, EventArgs e) { var spContext = SharePointContextProvider.Current.GetSharePointContext(Context); var clientContext = spContext.CreateUserClientContextForSPHost(); //check if we should create site collection or subsite Microsoft.SharePoint.Client.Web newWeb = null; if (Page.Request["IsDlg"].Contains("1")) { newWeb = new DeployManager().CreateSiteCollection( Page.Request["SPHostUrl"], txtUrl.Text, listSites.SelectedValue, txtTitle.Text, txtDescription.Text, clientContext, this, this.Configuration); //update the client context var newWebUri = new Uri(newWeb.Url); var token = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, newWebUri.Authority, TokenHelper.GetRealmFromTargetUrl(newWebUri)).AccessToken; clientContext = TokenHelper.GetClientContextWithAccessToken(newWeb.Url, token); newWeb = clientContext.Web; clientContext.Load(newWeb); clientContext.ExecuteQuery(); } else { newWeb = new DeployManager().CreateSubSite( txtUrl.Text, listSites.SelectedValue, txtTitle.Text, txtDescription.Text, clientContext, this, this.Configuration); } //Call Provision on each provisioning module foreach (Control ctrl in pnlModules.Controls) { if (ctrl is BaseProvisioningModule) ((BaseProvisioningModule)ctrl).Provision(clientContext, newWeb); } //dispose the clientContext clientContext.Dispose(); if (Page.Request["IsDlg"].Contains("1")) { //redirect to new site ScriptManager.RegisterClientScriptBlock(this, typeof(Default), "RedirectToSite", "navigateParent('" + newWeb.Url + "');", true); } else { // Redirect to just created site Response.Redirect(newWeb.Url); } } private void LoadModules() { if (listSites.SelectedIndex != -1) { //change the options var templateElement = templates.ElementAt(listSites.SelectedIndex); var modules = templateElement.Descendants("Module"); foreach (var module in modules) { BaseProvisioningModule ctrl = (BaseProvisioningModule)this.LoadControl(module.Attribute("CtrlSrc").Value); pnlModules.Controls.Add(ctrl); } //update the path if (Page.Request["IsDlg"].Contains("1")) { //get host web as base path lblBasePath.Text = Request["SPHostUrl"].Substring(0, 8 + Request["SPHostUrl"].Substring(8).IndexOf("/")) + "/" + templateElement.Attribute("ManagedPath").Value + "/"; } } else pnlModules.Controls.Clear(); } protected void listSites_SelectedIndexChanged(object sender, EventArgs e) { //load the modules //loadModules(); } } }
40.279188
186
0.535476
[ "Apache-2.0" ]
Chipzter/PnP
Solutions/Provisioning.Cloud.Sync/Provisioning.Cloud.SyncWeb/Pages/Default.aspx.cs
7,937
C#
using System; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; namespace SoftUni.WebServer.Data.Migrations { public partial class InitialMigration : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "ProductTypes", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Type = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_ProductTypes", x => x.Id); }); migrationBuilder.CreateTable( name: "Roles", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), RoleName = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Roles", x => x.Id); }); migrationBuilder.CreateTable( name: "Products", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Name = table.Column<string>(nullable: false), Price = table.Column<decimal>(nullable: false), Description = table.Column<string>(nullable: false), ProductTypeId = table.Column<int>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Products", x => x.Id); table.ForeignKey( name: "FK_Products_ProductTypes_ProductTypeId", column: x => x.ProductTypeId, principalTable: "ProductTypes", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateTable( name: "Users", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Username = table.Column<string>(nullable: false), PasswordHash = table.Column<string>(nullable: false), FullName = table.Column<string>(nullable: false), Email = table.Column<string>(nullable: false), RoleId = table.Column<int>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Users", x => x.Id); table.ForeignKey( name: "FK_Users_Roles_RoleId", column: x => x.RoleId, principalTable: "Roles", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateTable( name: "Orders", columns: table => new { Id = table.Column<Guid>(nullable: false), ProductId = table.Column<int>(nullable: true), ClientId = table.Column<int>(nullable: true), OrderedOn = table.Column<DateTime>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Orders", x => x.Id); table.ForeignKey( name: "FK_Orders_Users_ClientId", column: x => x.ClientId, principalTable: "Users", principalColumn: "Id", onDelete: ReferentialAction.Restrict); table.ForeignKey( name: "FK_Orders_Products_ProductId", column: x => x.ProductId, principalTable: "Products", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateTable( name: "ProductOrder", columns: table => new { Id = table.Column<int>(nullable: false), IdProduct = table.Column<int>(nullable: false), IdOrder = table.Column<Guid>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_ProductOrder", x => new { x.IdProduct, x.IdOrder }); table.ForeignKey( name: "FK_ProductOrder_Orders_IdOrder", column: x => x.IdOrder, principalTable: "Orders", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_ProductOrder_Products_IdProduct", column: x => x.IdProduct, principalTable: "Products", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateIndex( name: "IX_Orders_ClientId", table: "Orders", column: "ClientId"); migrationBuilder.CreateIndex( name: "IX_Orders_ProductId", table: "Orders", column: "ProductId"); migrationBuilder.CreateIndex( name: "IX_ProductOrder_IdOrder", table: "ProductOrder", column: "IdOrder"); migrationBuilder.CreateIndex( name: "IX_Products_ProductTypeId", table: "Products", column: "ProductTypeId"); migrationBuilder.CreateIndex( name: "IX_Users_RoleId", table: "Users", column: "RoleId"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "ProductOrder"); migrationBuilder.DropTable( name: "Orders"); migrationBuilder.DropTable( name: "Users"); migrationBuilder.DropTable( name: "Products"); migrationBuilder.DropTable( name: "Roles"); migrationBuilder.DropTable( name: "ProductTypes"); } } }
40.121547
122
0.474663
[ "MIT" ]
zrusev/SoftUni_2016
07. C# Web Basics - May 2018/C# Web Development Basics - 01 July 2018/SoftUni.WebServer.Data/Migrations/20180703151810_InitialMigration.cs
7,264
C#
using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace RzaolyScan.Services { public interface IQrScanningService { Task<string> ScanAsync(); } }
16.846154
39
0.726027
[ "MIT" ]
Aliwave/rzasite-laravel
RzaolyScan/RzaolyScan/RzaolyScan/Services/IQrScanningService.cs
221
C#
// Copyright © 2015 The CefSharp Authors. All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. namespace CefSharp { /// <summary> /// Values that represent key event types. /// </summary> public enum KeyEventType { /// <summary> /// Notification that a key transitioned from "up" to "down". /// </summary> RawKeyDown = 0, /// <summary> /// Notification that a key was pressed. This does not necessarily correspond /// to a character depending on the key and language. Use KEYEVENT_CHAR for /// character input. /// </summary> KeyDown, /// <summary> /// Notification that a key was released. /// </summary> KeyUp, /// <summary> /// Notification that a character was typed. Use this for text input. Key /// down events may generate 0, 1, or more than one character event depending /// on the key, locale, and operating system. /// </summary> Char } }
29.972973
100
0.586114
[ "BSD-3-Clause" ]
364988343/CefSharp.Net40
CefSharp/Enums/KeyEventType.cs
1,110
C#
using System.Xml.Serialization; namespace CarDealer.Dtos.Import { [XmlType("Part")] public class ImportPartDto { [XmlElement("name")] public string Name { get; set; } [XmlElement("price")] public decimal Price { get; set; } [XmlElement("quantity")] public int Quantity { get; set; } [XmlElement("supplierId")] public int SupplierId { get; set; } } } //<Part> // <name>Unexposed bumper</name> // <price>1003.34</price> // <quantity>10</quantity> // <supplierId>12</supplierId> //</Part>
22.384615
43
0.580756
[ "MIT" ]
DanielBankov/SoftUni
C# DB Fundamentals/Databases Advanced - Entity Framework/XML Processing/CarDealer - Skeleton/CarDealer/Dtos/Import/ImportPartDto.cs
584
C#
using UnityEngine; using System.Collections; public class CubeSpeed : Cube { public override void AwakeChild() { // SET CUBE EFFECT IN YOUR AWAKE FUNCTION effect = Cube.CubeEffect_e.SPEED; } public override void setActiveChild(bool active_) { if (active_) { tag = "speed"; } else { tag = "Untagged"; } } }
18.227273
56
0.558603
[ "MIT" ]
spencewenski/494p3
Assets/Scripts/CubeSpeed.cs
403
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace TreeView { public partial class TreeView { /// <summary> /// form1 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlForm form1; /// <summary> /// XmlSrc control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.XmlDataSource XmlSrc; } }
31.441176
84
0.48363
[ "MIT" ]
Spurch/ASP-.NET-WebForms
TreeView/TreeView.aspx.designer.cs
1,071
C#
namespace NetworkListMgr { partial class ModifyDialog { /// <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.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); this.lbl_profileName = new System.Windows.Forms.Label(); this.profileName = new System.Windows.Forms.TextBox(); this.lbl_profileDesc = new System.Windows.Forms.Label(); this.profileDesc = new System.Windows.Forms.TextBox(); this.lbl_signName = new System.Windows.Forms.Label(); this.lbl_signDesc = new System.Windows.Forms.Label(); this.signName = new System.Windows.Forms.TextBox(); this.signDesc = new System.Windows.Forms.TextBox(); this.btn_confirm = new System.Windows.Forms.Button(); this.btn_cancel = new System.Windows.Forms.Button(); this.tableLayoutPanel1.SuspendLayout(); this.SuspendLayout(); // // tableLayoutPanel1 // this.tableLayoutPanel1.ColumnCount = 4; this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 25F)); this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 25F)); this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 25F)); this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 25F)); this.tableLayoutPanel1.Controls.Add(this.lbl_profileName, 0, 0); this.tableLayoutPanel1.Controls.Add(this.profileName, 1, 0); this.tableLayoutPanel1.Controls.Add(this.lbl_profileDesc, 0, 1); this.tableLayoutPanel1.Controls.Add(this.profileDesc, 1, 1); this.tableLayoutPanel1.Controls.Add(this.lbl_signName, 0, 2); this.tableLayoutPanel1.Controls.Add(this.lbl_signDesc, 0, 3); this.tableLayoutPanel1.Controls.Add(this.signName, 1, 2); this.tableLayoutPanel1.Controls.Add(this.signDesc, 1, 3); this.tableLayoutPanel1.Controls.Add(this.btn_confirm, 2, 4); this.tableLayoutPanel1.Controls.Add(this.btn_cancel, 0, 4); this.tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill; this.tableLayoutPanel1.Location = new System.Drawing.Point(0, 0); this.tableLayoutPanel1.Margin = new System.Windows.Forms.Padding(4); this.tableLayoutPanel1.Name = "tableLayoutPanel1"; this.tableLayoutPanel1.Padding = new System.Windows.Forms.Padding(8); this.tableLayoutPanel1.RowCount = 5; this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 20F)); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 20F)); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 20F)); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 20F)); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 20F)); this.tableLayoutPanel1.Size = new System.Drawing.Size(445, 264); this.tableLayoutPanel1.TabIndex = 0; // // lbl_profileName // this.lbl_profileName.AutoSize = true; this.lbl_profileName.Dock = System.Windows.Forms.DockStyle.Fill; this.lbl_profileName.Location = new System.Drawing.Point(19, 18); this.lbl_profileName.Margin = new System.Windows.Forms.Padding(11, 10, 11, 10); this.lbl_profileName.Name = "lbl_profileName"; this.lbl_profileName.Size = new System.Drawing.Size(85, 29); this.lbl_profileName.TabIndex = 0; this.lbl_profileName.Text = "配置名称"; this.lbl_profileName.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; // // profileName // this.tableLayoutPanel1.SetColumnSpan(this.profileName, 3); this.profileName.Dock = System.Windows.Forms.DockStyle.Fill; this.profileName.Location = new System.Drawing.Point(126, 18); this.profileName.Margin = new System.Windows.Forms.Padding(11, 10, 11, 10); this.profileName.Name = "profileName"; this.profileName.Size = new System.Drawing.Size(300, 25); this.profileName.TabIndex = 1; this.profileName.TextChanged += new System.EventHandler(this.ProfileName_TextChanged); // // lbl_profileDesc // this.lbl_profileDesc.AutoSize = true; this.lbl_profileDesc.Dock = System.Windows.Forms.DockStyle.Fill; this.lbl_profileDesc.Location = new System.Drawing.Point(19, 67); this.lbl_profileDesc.Margin = new System.Windows.Forms.Padding(11, 10, 11, 10); this.lbl_profileDesc.Name = "lbl_profileDesc"; this.lbl_profileDesc.Size = new System.Drawing.Size(85, 29); this.lbl_profileDesc.TabIndex = 2; this.lbl_profileDesc.Text = "配置描述"; this.lbl_profileDesc.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; // // profileDesc // this.tableLayoutPanel1.SetColumnSpan(this.profileDesc, 3); this.profileDesc.Dock = System.Windows.Forms.DockStyle.Fill; this.profileDesc.Location = new System.Drawing.Point(126, 67); this.profileDesc.Margin = new System.Windows.Forms.Padding(11, 10, 11, 10); this.profileDesc.Name = "profileDesc"; this.profileDesc.Size = new System.Drawing.Size(300, 25); this.profileDesc.TabIndex = 3; // // lbl_signName // this.lbl_signName.AutoSize = true; this.lbl_signName.Dock = System.Windows.Forms.DockStyle.Fill; this.lbl_signName.Location = new System.Drawing.Point(19, 116); this.lbl_signName.Margin = new System.Windows.Forms.Padding(11, 10, 11, 10); this.lbl_signName.Name = "lbl_signName"; this.lbl_signName.Size = new System.Drawing.Size(85, 29); this.lbl_signName.TabIndex = 4; this.lbl_signName.Text = "Sign名称"; this.lbl_signName.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; // // lbl_signDesc // this.lbl_signDesc.AutoSize = true; this.lbl_signDesc.Dock = System.Windows.Forms.DockStyle.Fill; this.lbl_signDesc.Location = new System.Drawing.Point(19, 165); this.lbl_signDesc.Margin = new System.Windows.Forms.Padding(11, 10, 11, 10); this.lbl_signDesc.Name = "lbl_signDesc"; this.lbl_signDesc.Size = new System.Drawing.Size(85, 29); this.lbl_signDesc.TabIndex = 5; this.lbl_signDesc.Text = "Sign描述"; this.lbl_signDesc.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; // // signName // this.tableLayoutPanel1.SetColumnSpan(this.signName, 3); this.signName.Dock = System.Windows.Forms.DockStyle.Fill; this.signName.Location = new System.Drawing.Point(126, 116); this.signName.Margin = new System.Windows.Forms.Padding(11, 10, 11, 10); this.signName.Name = "signName"; this.signName.Size = new System.Drawing.Size(300, 25); this.signName.TabIndex = 6; // // signDesc // this.tableLayoutPanel1.SetColumnSpan(this.signDesc, 3); this.signDesc.Dock = System.Windows.Forms.DockStyle.Fill; this.signDesc.Location = new System.Drawing.Point(126, 165); this.signDesc.Margin = new System.Windows.Forms.Padding(11, 10, 11, 10); this.signDesc.Name = "signDesc"; this.signDesc.Size = new System.Drawing.Size(300, 25); this.signDesc.TabIndex = 7; // // btn_confirm // this.tableLayoutPanel1.SetColumnSpan(this.btn_confirm, 2); this.btn_confirm.Dock = System.Windows.Forms.DockStyle.Fill; this.btn_confirm.Location = new System.Drawing.Point(233, 214); this.btn_confirm.Margin = new System.Windows.Forms.Padding(11, 10, 11, 10); this.btn_confirm.Name = "btn_confirm"; this.btn_confirm.Size = new System.Drawing.Size(193, 32); this.btn_confirm.TabIndex = 8; this.btn_confirm.Text = "应用"; this.btn_confirm.UseVisualStyleBackColor = true; this.btn_confirm.Click += new System.EventHandler(this.Button_OK_Click); // // btn_cancel // this.tableLayoutPanel1.SetColumnSpan(this.btn_cancel, 2); this.btn_cancel.Dock = System.Windows.Forms.DockStyle.Fill; this.btn_cancel.Location = new System.Drawing.Point(19, 214); this.btn_cancel.Margin = new System.Windows.Forms.Padding(11, 10, 11, 10); this.btn_cancel.Name = "btn_cancel"; this.btn_cancel.Size = new System.Drawing.Size(192, 32); this.btn_cancel.TabIndex = 9; this.btn_cancel.Text = "取消"; this.btn_cancel.UseVisualStyleBackColor = true; this.btn_cancel.Click += new System.EventHandler(this.Button_Cancel_Click); // // ModifyDialog // this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 15F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(445, 264); this.Controls.Add(this.tableLayoutPanel1); this.Margin = new System.Windows.Forms.Padding(4); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "ModifyDialog"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "ModifyDialog"; this.Shown += new System.EventHandler(this.ModifyDialog_Shown); this.tableLayoutPanel1.ResumeLayout(false); this.tableLayoutPanel1.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; private System.Windows.Forms.Label lbl_profileName; private System.Windows.Forms.TextBox profileName; private System.Windows.Forms.Label lbl_profileDesc; private System.Windows.Forms.TextBox profileDesc; private System.Windows.Forms.Label lbl_signName; private System.Windows.Forms.Label lbl_signDesc; private System.Windows.Forms.TextBox signName; private System.Windows.Forms.TextBox signDesc; private System.Windows.Forms.Button btn_confirm; private System.Windows.Forms.Button btn_cancel; } }
54.200893
134
0.631085
[ "Apache-2.0" ]
Xusser/NetworkListMgr
NetworkListMgr/NetworkListMgr/ModifyDialog.Designer.cs
12,175
C#
//////////////////////////////////////////////////////////////////////////////// // // MIZUTANI KIRIN // Copyright 2016-2020 MIZUTANI KIRIN All Rights Reserved. // // NOTICE: MIZUTANI KIRIN permits you to use, modify, and distribute this file // in accordance with the terms of the license agreement accompanying it. // //////////////////////////////////////////////////////////////////////////////// //#define MovieEnable using UnityEngine; using System; using System.Text; using System.Collections.Generic; using UnityEngine.UI; namespace KirinUtil { [Serializable] public class OrderData { public string id; public float value; } [RequireComponent(typeof(KRNMedia))] [RequireComponent(typeof(KRNFile))] public class Util : MonoBehaviour { [NonSerialized] public static string version = "ver1.0.6"; [NonSerialized] public static string copylight = "Copyright 2016-2020 MIZUTANI KIRIN All Rights Reserved."; [NonSerialized] public static KRNMedia media; [NonSerialized] public static KRNFile file; [NonSerialized] public static NetManager net; [NonSerialized] public static SoundManager sound; [NonSerialized] public static ImageManager image; #if MovieEnable [NonSerialized] public static MovieManager movie; #endif private void Awake() { media = gameObject.GetComponent<KRNMedia>(); file = gameObject.GetComponent<KRNFile>(); net = gameObject.GetComponent<NetManager>(); if (gameObject.transform.Find("soundManager") != null) sound = gameObject.transform.Find("soundManager").gameObject.GetComponent<SoundManager>(); if (gameObject.transform.Find("imageManager") != null) image = gameObject.transform.Find("imageManager").gameObject.GetComponent<ImageManager>(); #if MovieEnable if (gameObject.transform.Find("movieManager") != null) movie = gameObject.transform.Find("movieManager").gameObject.GetComponent<MovieManager>(); #endif } private void Update() { BasicSettingUpdate(); } //---------------------------------- // BasicSetting //---------------------------------- #region BasicSetting private static bool cursorVisible = true; private static bool set = false; private static Vector3 mousePosPre = Vector3.zero; private static float cursorTimer; public static void BasicSetting(bool _cursor) { print("BasicSetting"); set = true; cursorVisible = _cursor; } public static void BasicSetting(Vector2 screenSize, bool fullscreen, int targetFps, bool _cursor) { print("BasicSetting"); Application.targetFrameRate = targetFps; Screen.SetResolution((int)screenSize.x, (int)screenSize.y, fullscreen); set = true; cursorVisible = _cursor; } private void BasicSettingUpdate() { if (!set) return; if (Input.GetKeyUp(KeyCode.Escape)) { Application.Quit(); } // カーソルを非表示 if (!cursorVisible) { Vector3 mousePos = Input.mousePosition; if (mousePos != mousePosPre) { Cursor.visible = true; cursorTimer = 0.0f; } else { if (cursorTimer >= 2.0f) { Cursor.visible = false; } else { cursorTimer += Time.deltaTime; } } mousePosPre = mousePos; } } #endregion //---------------------------------- // ShuffleArray //---------------------------------- #region ShuffleArray public static int[] ShuffleArray(int[] arr) { int length = arr.Length; int[] newArr = new int[length]; newArr = arr; while (length != 0) { int rnd = (int)Mathf.Floor(UnityEngine.Random.value * length); length--; var tmp = newArr[length]; newArr[length] = newArr[rnd]; newArr[rnd] = tmp; } return newArr; } public static float[] ShuffleArray(float[] arr) { int length = arr.Length; float[] newArr = new float[length]; newArr = arr; while (length != 0) { int rnd = (int)Mathf.Floor(UnityEngine.Random.value * length); length--; var tmp = newArr[length]; newArr[length] = newArr[rnd]; newArr[rnd] = tmp; } return newArr; } public static string[] ShuffleArray(string[] arr) { int length = arr.Length; string[] newArr = new string[length]; newArr = arr; while (length != 0) { int rnd = (int)Mathf.Floor(UnityEngine.Random.value * length); length--; var tmp = newArr[length]; newArr[length] = newArr[rnd]; newArr[rnd] = tmp; } return newArr; } public static Vector3[] ShuffleArray(Vector3[] arr) { int length = arr.Length; Vector3[] newArr = new Vector3[length]; newArr = arr; while (length != 0) { int rnd = (int)Mathf.Floor(UnityEngine.Random.value * length); length--; var tmp = newArr[length]; newArr[length] = newArr[rnd]; newArr[rnd] = tmp; } return newArr; } #endregion //---------------------------------- // DayArea //---------------------------------- #region DayArea public static bool DayArea(string _startDate, string _endDate) { bool flag = false; int now_month = DateTime.Now.Month; int now_date = DateTime.Now.Day; //---------------------------------- // init //---------------------------------- // 日にち if (_startDate == "" || _startDate == null || _endDate == "" || _endDate == null) { flag = true; } else { string[] start_day = _startDate.Split("/"[0]); int start_month = int.Parse(start_day[0]); int start_date = int.Parse(start_day[1]); string[] end_day = _endDate.Split("/"[0]); int end_month = int.Parse(end_day[0]); int end_date = int.Parse(end_day[1]); if (start_month < end_month) { // 通常 if (now_month > start_month && now_month < end_month) { // 月が範囲内の場合 flag = true; } else if (now_month == start_month) { // start_monthと同じ月の場合 if (now_date > start_date) { // 日が範囲内の場合 flag = true; } else if (now_date == start_date) { // 日がstart_dateと同じ場合 flag = true; } } else if (now_month == end_month) { // end_monthと同じ月の場合 if (now_date < end_date) { // 日が範囲内の場合 flag = true; } else if (now_date == end_date) { // 日がend_dateと同じ場合 flag = true; } } } else if (start_month > end_month) { // 年を越す if (now_month > start_month || now_month < end_month) { // 月が範囲内の場合 flag = true; } else if (now_month == start_month) { // start_monthと同じ月の場合 if (now_date > start_date) { // 日が範囲内の場合 flag = true; } else if (now_date == start_date) { // 日がstart_dateと同じ場合 flag = true; } } else if (now_month == end_month) { // end_monthと同じ月の場合 if (now_date < end_date) { // 日が範囲内の場合 flag = true; } else if (now_date == end_date) { // 日がend_dateと同じ場合 flag = true; } } } else { if (now_month == start_month) { // start_monthとend_monthが同じ月 if (now_date > start_date && now_date < end_date) { // 日が範囲内の場合 flag = true; } else if (now_date == start_date) { // 日がstart_dateと同じ場合 flag = true; } else if (now_date == end_date) { // 日がend_dateと同じ場合 flag = true; } else { // 今日の日付とは違うが常時表示 //if( start_date == end_date){ // if( now_date == start_date ) flag = true; //} } } } } return flag; } #endregion //---------------------------------- // TimeArea //---------------------------------- #region TimeArea public static bool TimeArea(string startTime, string nowTime, string endTime) { bool returnFlag = false; string[] startTimeTmp = startTime.Split(":"[0]); int startHour = int.Parse(startTimeTmp[0]); int startMinute = int.Parse(startTimeTmp[1]); string[] nowTimeTmp = nowTime.Split(":"[0]); int nowHour = int.Parse(nowTimeTmp[0]); int nowMinute = int.Parse(nowTimeTmp[1]); string[] endTimeTmp = endTime.Split(":"[0]); int endHour = int.Parse(endTimeTmp[0]); int endMinute = int.Parse(endTimeTmp[1]); // if (nowHour > startHour) { // 10:50 - 14:45 - if (nowHour < endHour) { // (1) 10:50 - 14:45 - 16:20 returnFlag = true; } else if (nowHour == endHour) { if (nowMinute > endMinute) { // (2) 10:50 - 14:45 - 14:20 returnFlag = false; } else { // (3) 10:50 - 14:45 - 14:50 returnFlag = true; } } else { if (startHour < endHour) { // (4) 10:50 - 14:45 - 13:20 returnFlag = false; } else if (startHour == endHour) { if (startMinute > endMinute) { // (5) 10:50 - 14:45 - 10:40 returnFlag = true; } else { // (6) 10:50 - 14:45 - 10:52; returnFlag = false; } } else { // (7) 11:50 - 14:45 - 10:50; returnFlag = true; } } } else if (nowHour == startHour) { // 14:20 - 14:45 - if (nowMinute >= startMinute) { if (nowHour < endHour) { // (5) 14:20 - 14:45 - 16:20 returnFlag = true; } else if (nowHour == endHour) { if (nowMinute > endMinute) { if (startMinute >= endMinute) { // (6) 14:20 - 14:45 - 14:10 returnFlag = true; } else { // (7) 14:20 - 14:45 - 14:30 returnFlag = false; } } else { // (7) 14:20 - 14:45 - 14:50 returnFlag = true; } } else { // (4) 14:20 - 14:45 - 13:50 returnFlag = true; } } else { if (startHour < endHour) { // (4) 14:50 - 14:45 - 15:20 returnFlag = false; } else if (startHour == endHour) { if (startMinute > endMinute) { // (4) 14:50 - 14:45 - 14:20 returnFlag = false; } else if (startMinute == endMinute) { // (4) 14:50 - 14:45 - 14:50 returnFlag = true; } else { // (4) 14:50 - 14:45 - 14:55 returnFlag = false; } } else { // (4) 14:50 - 14:45 - 13:20 returnFlag = false; } } } else { // 18:20 - 14:45 - if (nowHour < endHour) { if (startHour > endHour) { // (4) 18:20 - 14:45 - 16:20 returnFlag = true; } else if (startHour == endHour) { if (startMinute < endMinute) { // 18:20 - 14:45 - 18:30 returnFlag = false; } else if (startMinute == endMinute) { // 18:20 - 14:45 - 18:20 returnFlag = true; } else { // 18:30 - 14:45 - 18:20 returnFlag = true; } } else { // 18:20 - 14:45 - 19:20 returnFlag = false; } } else if (nowHour == endHour) { if (nowMinute > endMinute) { // (2) 18:20 - 14:45 - 14:20 returnFlag = false; } else { // (3) 18:20 - 14:45 - 14:50 returnFlag = true; } } else { // (3) 18:20 - 14:45 - 12:50 returnFlag = false; } } return returnFlag; } #endregion //---------------------------------- // WeekArea //---------------------------------- #region WeekArea public static bool WeekArea(int _startWeek, int _endWeek) { bool returnFlag = false; int nowWeek = WeekNum(System.DateTime.Now.DayOfWeek.ToString()); if (_startWeek < _endWeek) { // 通常時 if (nowWeek >= _startWeek && nowWeek <= _endWeek) { returnFlag = true; } } else if (_startWeek > _endWeek) { // 土日を挟む時 if (nowWeek >= _startWeek) { returnFlag = true; } else if (nowWeek <= _endWeek) { returnFlag = true; } } else if (_startWeek == _endWeek) { // _startWeekと_endWeekが同じ時 if (nowWeek == _startWeek) { returnFlag = true; } } return returnFlag; } private static int WeekNum(string week) { int weekNum = -1; if (week == "Sunday") weekNum = 0; else if (week == "Monday") weekNum = 1; else if (week == "Tuesday") weekNum = 2; else if (week == "Wednesday") weekNum = 3; else if (week == "Thursday") weekNum = 4; else if (week == "Friday") weekNum = 5; else if (week == "Saturday") weekNum = 6; return weekNum; } #endregion //---------------------------------- // 2点間の角度 //---------------------------------- public static float Angle2(Vector2 p1, Vector2 p2) { float dx = p2.x - p1.x; float dy = p2.y - p1.y; float rad = Mathf.Atan2(dy, dx); return rad * Mathf.Rad2Deg; } //---------------------------------- // 3点の角度 //---------------------------------- #region Angle3 public static float Angle3(Vector2 p0, Vector2 p1, Vector2 p2) { float[] ba = new float[2]; ba[0] = p0.x - p1.x; ba[1] = p0.y - p1.y; float[] bc = new float[2]; bc[0] = p2.x - p1.x; bc[1] = p2.y - p1.y; float babc = ba[0] * bc[0] + ba[1] * bc[1]; float ban = (ba[0] * ba[0]) + (ba[1] * ba[1]); float bcn = (bc[0] * bc[0]) + (bc[1] * bc[1]); float radian = Mathf.Acos(babc / (Mathf.Sqrt(ban * bcn))); float angle = (float)(radian * 180 / Mathf.PI); // 結果(ラジアンから角度に変換) return angle; } /*private float GetDeltaAngle(Vector2 p0, Vector2 p1, Vector2 p2) { float deltaAngle = Angle2(p0, p1) - Angle2(p0, p2); deltaAngle += deltaAngle > 180 ? -360 : 0; deltaAngle += deltaAngle < -180 ? 360 : 0; return deltaAngle; }*/ #endregion //---------------------------------- // 0-360度にする //---------------------------------- public static float To360Angle(float angle) { float fixAngle = angle; if (angle < 0) { while (fixAngle < 0) { fixAngle += 360; } } else if (angle > 360) { while (fixAngle > 360) { fixAngle -= 360; } } return fixAngle; } //---------------------------------- // Radian //---------------------------------- #region Radian public static float Deg2Rad(float degAngle) { return Mathf.Deg2Rad * degAngle; } public static float Rad2Deg(float radian) { return Mathf.Rad2Deg * radian; } #endregion //---------------------------------- // AddZero //---------------------------------- // 指定した桁数にする。 // AddZero(1, 2) = 01 public static string AddZero(int num, int digits) { string returnSt = ""; int numKeta = num.ToString().Length; int addZero = digits - numKeta; if (addZero < 0) addZero = 0; for (int i = 0; i < addZero; i++) { returnSt += "0"; } returnSt += num; return returnSt; } //---------------------------------- // 小数点の桁数を揃える //---------------------------------- // PointAlignment(小数点の数字, 小数点何位に揃えるか) public static string PointAlignment(float num, int pointNum) { float point2 = PointRound(num, pointNum); string numSt = point2.ToString(); if (numSt.IndexOf("."[0]) == -1) { numSt += "."; for (int i = 0; i < pointNum; i++) { numSt += "0"; } } else { string[] st = numSt.Split("."[0]); if (st.Length == 2) { int loopNum = pointNum - st[1].Length; for (int i = 0; i < loopNum; i++) { numSt += "0"; } } } return numSt; } //---------------------------------- // 四捨五入 //---------------------------------- // PointRound(小数点の数字, 小数点何位を四捨五入するか) public static float PointRound(float num, int pointNum) { if (num.ToString().IndexOf(".") == -1) return num; if (pointNum <= 0) return num; float point = 0; int scaleUp = 1; float scaleDown = 1; for (int i = 0; i < pointNum; i++) { scaleUp *= 10; scaleDown *= 0.1f; } point = RoundToInt(num * scaleUp); point = point * scaleDown; if (point.ToString().IndexOf(".") != -1) { string[] point2St = point.ToString().Split("."[0]); if (point2St[1].Length > pointNum) { point2St[1] = point2St[1].Substring(0, pointNum); point = float.Parse(point2St[0] + "." + point2St[1]); } } return point; } //---------------------------------- // FrameRate //---------------------------------- #region FrameRate private static int frameCount; private static float prevTime; private static float framerate = 0.0f; public static int FrameRateUpdate(float calcSpanTime = 1, Text fpsText = null) { ++frameCount; float time = Time.realtimeSinceStartup - prevTime; if (time >= calcSpanTime) { framerate = frameCount / time; frameCount = 0; prevTime = Time.realtimeSinceStartup; } int fpsInt = Mathf.FloorToInt(framerate); if (fpsText != null) fpsText.text = fpsInt.ToString(); return fpsInt; } #endregion //---------------------------------- // GetRandomString //---------------------------------- public static string GetRandomString(int length) { string passwordChars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; StringBuilder stringBuilder = new StringBuilder(length); System.Random random = new System.Random(); for (int index1 = 0; index1 < length; ++index1) { int index2 = random.Next(passwordChars.Length); char passwordChar = passwordChars[index2]; stringBuilder.Append(passwordChar); } return stringBuilder.ToString(); } //---------------------------------- // 特定文字のカウント //---------------------------------- public static int CountOf(string message, string[] strArray) { int count = 0; foreach (string str in strArray) { int index = str.IndexOf(message, 0); while (index != -1) { count++; index = str.IndexOf(message, index + str.Length); } } return count; } //---------------------------------- // UIScene //---------------------------------- /*#region UIScene private static List<GameObject> sceneUI; private static int sceneNum; public static void SceneInit(List<GameObject> uis) { sceneUI = new List<GameObject>(); for (int i = 0; i < uis.Count; i++) { sceneUI.Add(uis[i]); uis[i].SetActive(false); } uis[0].SetActive(true); sceneNum = 0; } public static void ChangeScene() { int sceneNumPre = sceneNum; sceneNum++; if (sceneNum >= sceneUI.Count) sceneNum = 0; SceneFade(sceneNumPre, sceneNum); } public static void ChangeSceneUI(int num) { SceneFade(sceneNum, num); sceneNum = num; } public static int GetSceneNum() { return sceneNum; } private static void SceneFade(int numPre, int numNext) { iTween.Stop(sceneUI[numPre]); iTween.Stop(sceneUI[numNext]); media.FadeOutUI(sceneUI[numPre], 0.5f, 0); media.FadeInUI(sceneUI[numNext], 0.5f, 0); } #endregion*/ //---------------------------------- // world座標をCanvas座標に変換 //---------------------------------- #region world座標をCanvas座標に変換 public static Vector2 GetUIPos(Camera uiCamera, Camera worldCamera, Canvas canvas, GameObject targetObj) { var uiPos = Vector2.zero; var canvasRect = canvas.GetComponent<RectTransform>(); var screenPos = RectTransformUtility.WorldToScreenPoint(worldCamera, targetObj.transform.position); RectTransformUtility.ScreenPointToLocalPointInRectangle(canvasRect, screenPos, uiCamera, out uiPos); //uiPos = new Vector2(uiPos.x + canvasRect.sizeDelta.x * 0.5f, uiPos.y + canvasRect.sizeDelta.y * 0.5f); return uiPos; } public static Vector2 GetUIPos(Camera uiCamera, Camera worldCamera, Canvas canvas, Vector3 targetPos) { var uiPos = Vector2.zero; var canvasRect = canvas.GetComponent<RectTransform>(); var screenPos = RectTransformUtility.WorldToScreenPoint(worldCamera, targetPos); RectTransformUtility.ScreenPointToLocalPointInRectangle(canvasRect, screenPos, uiCamera, out uiPos); //uiPos = new Vector2(uiPos.x + canvasRect.sizeDelta.x * 0.5f, uiPos.y + canvasRect.sizeDelta.y * 0.5f); return uiPos; } #endregion //---------------------------------- // Canvas座標をworld座標に変換 //---------------------------------- #region Canvas座標をworld座標に変換 // mouse public static Vector3 GetWorldMousePos(Camera camera, float z) { Vector3 mousePos = Input.mousePosition; Vector3 pos = camera.ScreenToWorldPoint(mousePos); pos.z = z; return pos; } // object public static Vector3 GetWorldPos(Camera camera, Canvas canvas, Vector3 canvasPos, float z) { RectTransform canvasRect = canvas.GetComponent<RectTransform>(); canvasPos.x += canvasRect.sizeDelta.x * 0.5f; canvasPos.y += canvasRect.sizeDelta.y * 0.5f; canvasPos.z = z; Vector3 pos = camera.ScreenToWorldPoint(canvasPos); //pos.z = z; return pos; } #endregion //---------------------------------- // position //---------------------------------- #region position public static void PosX(GameObject obj, float x) { obj.transform.position = new Vector3(x, obj.transform.position.y, obj.transform.position.z); } public static void PosY(GameObject obj, float y) { obj.transform.position = new Vector3(obj.transform.position.x, y, obj.transform.position.z); } public static void PosZ(GameObject obj, float z) { obj.transform.position = new Vector3(obj.transform.position.x, obj.transform.position.y, z); } public static void LocalPosX(GameObject obj, float x) { obj.transform.localPosition = new Vector3(x, obj.transform.localPosition.y, obj.transform.localPosition.z); } public static void LocalPosY(GameObject obj, float y) { obj.transform.localPosition = new Vector3(obj.transform.localPosition.x, y, obj.transform.localPosition.z); } public static void LocalPosZ(GameObject obj, float z) { obj.transform.localPosition = new Vector3(obj.transform.localPosition.x, obj.transform.localPosition.y, z); } #endregion //---------------------------------- // scale //---------------------------------- #region scale public static void Scale(GameObject obj, float scale) { obj.transform.localScale = new Vector3(scale, scale, scale); } public static void ScaleX(GameObject obj, float x) { obj.transform.localScale = new Vector3(x, obj.transform.localScale.y, obj.transform.localScale.z); } public static void ScaleY(GameObject obj, float y) { obj.transform.localScale = new Vector3(obj.transform.localScale.x, y, obj.transform.localScale.z); } public static void ScaleZ(GameObject obj, float z) { obj.transform.localScale = new Vector3(obj.transform.localScale.x, obj.transform.localScale.y, z); } #endregion //---------------------------------- // 改行処理 //---------------------------------- // <br>をEnvironment.NewLineにする public static string GetLineText(string str) { string lineSt = ""; //print("GetLineText: " + str.IndexOf("<br>")); if (str.IndexOf("<br>") != -1) { string[] del = { "<br>" }; string[] st = str.Split(del, StringSplitOptions.None); for (int i = 0; i < st.Length; i++) { if (i != st.Length - 1) lineSt += st[i] + Environment.NewLine; else lineSt += st[i]; } print(lineSt); } else { lineSt = str; } return lineSt; } //---------------------------------- // デバッグ用StopWatch // (コードの処理速度を計るためのもの) //---------------------------------- #region デバッグ用StopWatch private static System.Diagnostics.Stopwatch stopwatch; public static void DebugWatchStart() { stopwatch = new System.Diagnostics.Stopwatch(); stopwatch.Start(); } public static void DebugWatchStop(Text debugText = null) { stopwatch.Stop(); string message = stopwatch.ElapsedMilliseconds + "ms"; print(message); if (debugText != null) debugText.text = message; } #endregion //---------------------------------- // List中の最大/最小を探しList番号 // を返す //---------------------------------- #region Find Max value public static int GetMaxListNum(List<float> thisList) { int listNum = 0; float maxNum = 0; for (int i = 0; i < thisList.Count; i++) { if (thisList[i] > maxNum) { maxNum = thisList[i]; listNum = i; } } return listNum; } public static int GetMaxListNum(List<int> thisList) { int listNum = 0; int maxNum = 0; for (int i = 0; i < thisList.Count; i++) { if (thisList[i] > maxNum) { maxNum = thisList[i]; listNum = i; } } return listNum; } public static int GetMaxListNum(List<GameObject> thisList, AxisType type, bool isLocal) { int listNum = 0; float maxNum = 0; if (isLocal) { for (int i = 0; i < thisList.Count; i++) { if (type == AxisType.X) { if (thisList[i].transform.localPosition.x > maxNum) { maxNum = thisList[i].transform.localPosition.x; listNum = i; } } else if (type == AxisType.Y) { if (thisList[i].transform.localPosition.y > maxNum) { maxNum = thisList[i].transform.localPosition.y; listNum = i; } } else if (type == AxisType.Z) { if (thisList[i].transform.localPosition.z > maxNum) { maxNum = thisList[i].transform.localPosition.z; listNum = i; } } } } else { for (int i = 0; i < thisList.Count; i++) { if (type == AxisType.X) { if (thisList[i].transform.position.x > maxNum) { maxNum = thisList[i].transform.position.x; listNum = i; } } else if (type == AxisType.Y) { if (thisList[i].transform.position.y > maxNum) { maxNum = thisList[i].transform.position.y; listNum = i; } } else if (type == AxisType.Z) { if (thisList[i].transform.position.z > maxNum) { maxNum = thisList[i].transform.position.z; listNum = i; } } } } return listNum; } #endregion #region Find Min value public static int GetMinListNum(List<float> thisList) { int listNum = 0; float minNum = thisList[0]; for (int i = 0; i < thisList.Count; i++) { if (thisList[i] < minNum) { minNum = thisList[i]; listNum = i; } } return listNum; } public static int GetMinListNum(List<int> thisList) { int listNum = 0; int minNum = thisList[0]; for (int i = 0; i < thisList.Count; i++) { if (thisList[i] < minNum) { minNum = thisList[i]; listNum = i; } } return listNum; } public static int GetMinListNum(List<GameObject> thisList, AxisType type, bool isLocal) { int listNum = 0; float minNum = 0; if (isLocal) { if (type == AxisType.X) minNum = thisList[0].transform.localPosition.x; else if (type == AxisType.Y) minNum = thisList[0].transform.localPosition.y; else if (type == AxisType.Z) minNum = thisList[0].transform.localPosition.z; for (int i = 0; i < thisList.Count; i++) { if (type == AxisType.X) { if (thisList[i].transform.localPosition.x < minNum) { minNum = thisList[i].transform.localPosition.x; listNum = i; } } else if (type == AxisType.Y) { if (thisList[i].transform.localPosition.y < minNum) { minNum = thisList[i].transform.localPosition.y; listNum = i; } } else if (type == AxisType.Z) { if (thisList[i].transform.localPosition.z < minNum) { minNum = thisList[i].transform.localPosition.z; listNum = i; } } } } else { if (type == AxisType.X) minNum = thisList[0].transform.position.x; else if (type == AxisType.Y) minNum = thisList[0].transform.position.y; else if (type == AxisType.Z) minNum = thisList[0].transform.position.z; for (int i = 0; i < thisList.Count; i++) { if (type == AxisType.X) { if (thisList[i].transform.position.x < minNum) { minNum = thisList[i].transform.position.x; listNum = i; } } else if (type == AxisType.Y) { if (thisList[i].transform.position.y < minNum) { minNum = thisList[i].transform.position.y; listNum = i; } } else if (type == AxisType.Z) { if (thisList[i].transform.position.z < minNum) { minNum = thisList[i].transform.position.z; listNum = i; } } } } return listNum; } #endregion //---------------------------------- // 中心点を取得 //---------------------------------- #region CenterPos // CenterPos public static float CenterPosX(GameObject obj0, GameObject obj1) { return CenterValue(obj0.transform.position.x, obj1.transform.position.x); } public static float CenterPosY(GameObject obj0, GameObject obj1) { return CenterValue(obj0.transform.position.y, obj1.transform.position.y); } public static float CenterPosZ(GameObject obj0, GameObject obj1) { return CenterValue(obj0.transform.position.z, obj1.transform.position.z); } public static Vector3 CenterPos(GameObject obj0, GameObject obj1) { Vector3 centerPos = new Vector3( CenterPosX(obj0, obj1), CenterPosY(obj0, obj1), CenterPosZ(obj0, obj1) ); return centerPos; } // CenterLocalPos public static float CenterLocalPosX(GameObject obj0, GameObject obj1) { return CenterValue(obj0.transform.localPosition.x, obj1.transform.localPosition.x); } public static float CenterLocalPosY(GameObject obj0, GameObject obj1) { return CenterValue(obj0.transform.localPosition.y, obj1.transform.localPosition.y); } public static float CenterLocalPosZ(GameObject obj0, GameObject obj1) { return CenterValue(obj0.transform.localPosition.z, obj1.transform.localPosition.z); } public static Vector3 CenterLocalPos(GameObject obj0, GameObject obj1) { Vector3 centerPos = new Vector3( CenterLocalPosX(obj0, obj1), CenterLocalPosY(obj0, obj1), CenterLocalPosZ(obj0, obj1) ); return centerPos; } // 数値 public static float CenterValue(float pos0, float pos1) { return (pos0 - pos1) / 2f + pos0; } #endregion //---------------------------------- // Splitして指定した配列番号の値を // 取得する //---------------------------------- #region Splitして指定した配列番号の値を取得 public static int GetSplitInt(string message, string splitStr, int getNum) { string[] data = message.Split(splitStr[0]); return int.Parse(data[getNum]); } public static float GetSplitFloat(string message, string splitStr, int getNum) { string[] data = message.Split(splitStr[0]); return float.Parse(data[getNum]); } public static string GetSplitString(string message, string splitStr, int getNum) { string[] data = message.Split(splitStr[0]); return data[getNum]; } public static long GetSplitLong(string message, string splitStr, int getNum) { string[] data = message.Split(splitStr[0]); return long.Parse(data[getNum]); } public static int[] GetSplitInt(string message, string splitStr) { string[] data = message.Split(splitStr[0]); // intに変更 int[] dataInt = new int[data.Length]; for (int i = 0; i < dataInt.Length; i++) { dataInt[i] = int.Parse(data[i]); } return dataInt; } public static float[] GetSplitFloat(string message, string splitStr) { string[] data = message.Split(splitStr[0]); // floatに変更 float[] dataFloat = new float[data.Length]; for (int i = 0; i < dataFloat.Length; i++) { dataFloat[i] = float.Parse(data[i]); } return dataFloat; } public static long[] GetSplitLong(string message, string splitStr) { string[] data = message.Split(splitStr[0]); // longに変更 long[] dataLong = new long[data.Length]; for (int i = 0; i < dataLong.Length; i++) { dataLong[i] = long.Parse(data[i]); } return dataLong; } #endregion //---------------------------------- // 区切り文字の処理 //---------------------------------- #region 指定した区切り文字で区切りListで値を返す public static List<string> GetSplitStringList(string str, string separate) { if (str == "") return null; List<string> dataList = new List<string>(); string[] dataArray = str.Split(separate[0]); dataList.AddRange(dataArray); return dataList; } public static List<int> GetSplitIntList(string str, string separate) { if (str == "") return null; List<int> dataList = new List<int>(); string[] dataArray = str.Split(separate[0]); for (int i = 0; i < dataArray.Length; i++) { dataList.Add(int.Parse(dataArray[i])); } return dataList; } public static List<float> GetSplitFloatList(string str, string separate) { if (str == "") return null; List<float> dataList = new List<float>(); string[] dataArray = str.Split(separate[0]); for (int i = 0; i < dataArray.Length; i++) { dataList.Add(float.Parse(dataArray[i])); } return dataList; } #endregion #region Listを指定した区切り文字で区切ったstringを返す public static string GetSeparatedString(List<string> dataList, string separate) { if (dataList == null || dataList.Count == 0) return ""; string data = ""; for (int i = 0; i < dataList.Count - 1; i++) { data += dataList[i] + separate; } data += dataList[dataList.Count - 1]; return data; } public static string GetSeparatedString(List<int> dataList, string separate) { if (dataList == null || dataList.Count == 0) return ""; string data = ""; for (int i = 0; i < dataList.Count - 1; i++) { data += dataList[i] + separate; } data += dataList[dataList.Count - 1]; return data; } public static string GetSeparatedString(List<float> dataList, string separate) { if (dataList == null || dataList.Count == 0) return ""; string data = ""; for (int i = 0; i < dataList.Count - 1; i++) { data += dataList[i] + separate; } data += dataList[dataList.Count - 1]; return data; } #endregion //---------------------------------- // オブジェクトのListを小さい順番 // で返す。(id、数値) //---------------------------------- #region GetOrderList public static List<OrderData> GetOrderList(List<string> idList, List<float> valueList, Direction direction) { List<OrderData> userDataList = new List<OrderData>(); for (int i = 0; i < idList.Count; i++) { OrderData thisData = new OrderData(); thisData.id = idList[i]; thisData.value = valueList[i]; userDataList.Add(thisData); } if (direction == Direction.Up) userDataList.Sort((a, b) => Math.Sign(b.value - a.value)); else userDataList.Sort((a, b) => Math.Sign(a.value - b.value)); return userDataList; } #endregion //---------------------------------- // 四捨五入 //---------------------------------- #region 四捨五入 public static float Round(float value) { return (float)Math.Round(value, MidpointRounding.AwayFromZero); } public static int RoundToInt(float value) { return (int)Math.Round(value, MidpointRounding.AwayFromZero); } #endregion //---------------------------------- // 検索文字がリストにあるかどうか //---------------------------------- #region 検索文字がリストにあるかどうか public static bool MatchWord(List<string> wordList, string matchWord) { bool match = false; for (int i = 0; i < wordList.Count; i++) { if (wordList[i] == matchWord) { match = true; break; } } return match; } #endregion #region 該当id検索してリスト番号を返す public static int GetListNum(List<string> idList, string id) { int listNum = -1; for (int i = 0; i < idList.Count; i++) { if (idList[i] == id) { listNum = i; break; } } return listNum; } #endregion //---------------------------------- // 等間隔に並べる //---------------------------------- #region 等間隔 public static void EquidistantX(List<GameObject> objList, float startX, float endX, float posY) { float areaWidth = Mathf.Abs(endX - startX); float oneWidth = areaWidth / (float)(objList.Count + 1); for (int i = 0; i < objList.Count; i++) { objList[i].transform.localPosition = new Vector3( startX + oneWidth * (i + 1), posY, 0 ); } } public static void EquidistantX(List<GameObject> objList, float startX, float endX) { float areaWidth = Mathf.Abs(endX - startX); float oneWidth = areaWidth / (float)(objList.Count + 1); for (int i = 0; i < objList.Count; i++) { objList[i].transform.localPosition = new Vector3( startX + oneWidth * (i + 1), objList[i].transform.localPosition.y, 0 ); } } public static void EquidistantY(List<GameObject> objList, float startY, float endY, float posX) { float areaHeight = Mathf.Abs(endY - startY); float oneHeight = areaHeight / (float)(objList.Count + 1); for (int i = 0; i < objList.Count; i++) { objList[i].transform.localPosition = new Vector3( posX, startY + oneHeight * (i + 1), 0 ); } } public static void EquidistantY(List<GameObject> objList, float startY, float endY) { float areaHeight = Mathf.Abs(endY - startY); float oneHeight = areaHeight / (float)(objList.Count + 1); for (int i = 0; i < objList.Count; i++) { objList[i].transform.localPosition = new Vector3( objList[i].transform.localPosition.x, startY + oneHeight * (i + 1), 0 ); } } #endregion } }
34.389758
119
0.436818
[ "MIT" ]
mizutanikirin/Re.Unity
Assets/KirinUtil/Scripts/Util.cs
49,408
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.ApplicationModel; using Windows.ApplicationModel.Activation; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; namespace UWP.Test { /// <summary> /// Provides application-specific behavior to supplement the default Application class. /// </summary> sealed partial class App : Application { /// <summary> /// Initializes the singleton application object. This is the first line of authored code /// executed, and as such is the logical equivalent of main() or WinMain(). /// </summary> public App() { this.InitializeComponent(); this.Suspending += OnSuspending; } /// <summary> /// Invoked when the application is launched normally by the end user. Other entry points /// will be used such as when the application is launched to open a specific file. /// </summary> /// <param name="e">Details about the launch request and process.</param> protected override void OnLaunched(LaunchActivatedEventArgs e) { Frame rootFrame = Window.Current.Content as Frame; // Do not repeat app initialization when the Window already has content, // just ensure that the window is active if (rootFrame == null) { // Create a Frame to act as the navigation context and navigate to the first page rootFrame = new Frame(); rootFrame.NavigationFailed += OnNavigationFailed; if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) { //TODO: Load state from previously suspended application } // Place the frame in the current Window Window.Current.Content = rootFrame; } if (e.PrelaunchActivated == false) { if (rootFrame.Content == null) { // When the navigation stack isn't restored navigate to the first page, // configuring the new page by passing required information as a navigation // parameter rootFrame.Navigate(typeof(MainPage), e.Arguments); } // Ensure the current window is active Window.Current.Activate(); } } /// <summary> /// Invoked when Navigation to a certain page fails /// </summary> /// <param name="sender">The Frame which failed navigation</param> /// <param name="e">Details about the navigation failure</param> void OnNavigationFailed(object sender, NavigationFailedEventArgs e) { throw new Exception("Failed to load Page " + e.SourcePageType.FullName); } /// <summary> /// Invoked when application execution is being suspended. Application state is saved /// without knowing whether the application will be terminated or resumed with the contents /// of memory still intact. /// </summary> /// <param name="sender">The source of the suspend request.</param> /// <param name="e">Details about the suspend request.</param> private void OnSuspending(object sender, SuspendingEventArgs e) { var deferral = e.SuspendingOperation.GetDeferral(); //TODO: Save application state and stop any background activity deferral.Complete(); } } }
38.811881
99
0.613776
[ "MIT" ]
1iveowl/SSDP.UPnP.PCL
src/test/UWP.Test/App.xaml.cs
3,922
C#
// ------------------------------------------------------------------------------ // <autogenerated> // This code was generated by a tool. // Mono Runtime Version: 4.0.30319.1 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </autogenerated> // ------------------------------------------------------------------------------ namespace GLFullScreen { // Should subclass MonoMac.AppKit.NSResponder [Foundation.Register("AppDelegate")] public partial class AppDelegate { } }
29.578947
81
0.485765
[ "Apache-2.0" ]
DavidAlphaFox/mac-samples
GLFullScreen/GLFullScreen/MainMenu.xib.designer.cs
562
C#
using JsonEnvelopes.Example.Commands; using JsonEnvelopes.Example.Services; using MediatR; using System; using System.Collections.Generic; using System.Text; using System.Threading; using System.Threading.Tasks; namespace JsonEnvelopes.Example.Handlers { public class CreateCharacterHandler : ICommandHandler<CreateCharacter>, IRequestHandler<CreateCharacter, bool> { public Task<bool> HandleAsync(CreateCharacter command) { Console.WriteLine($"{command}"); return Task.FromResult(true); } public Task<bool> HandleAsync(object command) => HandleAsync((CreateCharacter)command); public Task<bool> Handle(CreateCharacter command, CancellationToken cancellationToken) => HandleAsync(command); } public class CreateCharacterMediatRHandler : IRequestHandler<CreateCharacter, bool> { public Task<bool> Handle(CreateCharacter command, CancellationToken cancellationToken) { Console.WriteLine($"{command}"); return Task.FromResult(true); } } }
28.307692
114
0.695652
[ "MIT" ]
DaneVinson/JsonEnvelopes
JsonEnvelopes.Example/Handlers/CreateCharacterHandler.cs
1,106
C#
using CQRSlite.Domain; using CQRSlite.Snapshotting; using Microsoft.Extensions.Configuration; using System; using System.Collections.Generic; using System.Reflection; using System.Text; namespace CQRSlite.Storage { public class AttributeSnapshotStrategy : ISnapshotStrategy { public const string DEFAULT_SNAPSHOT_INTERVAL_KEY = "CQRSlite.Storage.DefaultSnapshotInterval"; private int defaultSnapshotInterval = 100; public AttributeSnapshotStrategy(IConfiguration config) { if(config != null && !string.IsNullOrEmpty(config[DEFAULT_SNAPSHOT_INTERVAL_KEY])) { int.TryParse(config[DEFAULT_SNAPSHOT_INTERVAL_KEY], out defaultSnapshotInterval); } } public bool IsSnapshotable(Type aggregateType) { if (aggregateType.GetTypeInfo().BaseType == null) return false; if (aggregateType.GetTypeInfo().BaseType.GetTypeInfo().IsGenericType && aggregateType.GetTypeInfo().BaseType.GetGenericTypeDefinition() == typeof(SnapshotAggregateRoot<>)) return true; return IsSnapshotable(aggregateType.GetTypeInfo().BaseType); } public bool ShouldMakeSnapShot(AggregateRoot aggregate) { int snapshotInterval = defaultSnapshotInterval; // Get instance of the attribute. SnapshotStrategyAttribute snapshotStrategy = (SnapshotStrategyAttribute)Attribute.GetCustomAttribute(aggregate.GetType(), typeof(SnapshotStrategyAttribute)); if(snapshotStrategy != null) { snapshotInterval = snapshotStrategy.Interval; } if (!IsSnapshotable(aggregate.GetType())) return false; var i = aggregate.Version; for (var j = 0; j < aggregate.GetUncommittedChanges().Length; j++) if (++i % snapshotInterval == 0 && i != 0) return true; return false; } } }
39.313725
128
0.65187
[ "Apache-2.0" ]
628426/CQRSlite
Framework/CQRSlite.Storage/AttributeSnapshotStrategy.cs
2,007
C#
using Sutro.Core.Settings; namespace Sutro.Core.FillTypes { public class FillTypeFactory { private IPrintProfileFFF settings; public FillTypeFactory(IPrintProfileFFF settings) { this.settings = settings; } public IFillType Bridge() { return new BridgeFillType(settings.Part.BridgeVolumeScale, settings.Part.CarefulExtrudeSpeed * settings.Part.BridgeExtrudeSpeedX); } public IFillType Default() { return new DefaultFillType(); } public IFillType InnerPerimeter() { return new InnerPerimeterFillType(1, settings.Part.InnerPerimeterSpeedX); } public IFillType InteriorShell() { return new InteriorShellFillType(); } public IFillType OpenShellCurve() { return new OpenShellCurveFillType(); } public IFillType OuterPerimeter() { return new OuterPerimeterFillType(1, settings.Part.OuterPerimeterSpeedX); } public IFillType SkirtBrim(PrintProfileFFF settings) { return new SkirtBrimFillType(); } public IFillType Solid() { return new SolidFillType(1, settings.Part.SolidFillSpeedX); } public IFillType Sparse() { return new SparseFillType(); } public IFillType Support() { return new SupportFillType(settings.Part.SupportVolumeScale, settings.Part.OuterPerimeterSpeedX); } } }
24.96875
142
0.595119
[ "MIT" ]
SutroMachine/Sutro.Core
Sutro.Core/FillTypes/FillTypeFactory.cs
1,600
C#
/***************************************************************************** Copyright 2018 The TensorFlow.NET Authors. 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. 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 NumSharp; using System; using Tensorflow; using Tensorflow.Hub; using static Tensorflow.Python; namespace TensorFlowNET.Examples { /// <summary> /// Neural Network classifier for Hand Written Digits /// Sample Neural Network architecture with two layers implemented for classifying MNIST digits. /// Use Stochastic Gradient Descent (SGD) optimizer. /// http://www.easy-tensorflow.com/tf-tutorials/neural-networks /// </summary> public class DigitRecognitionNN : IExample { public bool Enabled { get; set; } = true; public bool IsImportingGraph { get; set; } = false; public string Name => "Digits Recognition Neural Network"; const int img_h = 28; const int img_w = 28; int img_size_flat = img_h * img_w; // 784, the total number of pixels int n_classes = 10; // Number of classes, one class per digit // Hyper-parameters int epochs = 10; int batch_size = 100; float learning_rate = 0.001f; int h1 = 200; // number of nodes in the 1st hidden layer Datasets<MnistDataSet> mnist; Tensor x, y; Tensor loss, accuracy; Operation optimizer; int display_freq = 100; float accuracy_test = 0f; float loss_test = 1f; public bool Run() { PrepareData(); BuildGraph(); using (var sess = tf.Session()) { Train(sess); Test(sess); }; return loss_test < 0.09 && accuracy_test > 0.95; } public Graph BuildGraph() { var graph = new Graph().as_default(); // Placeholders for inputs (x) and outputs(y) x = tf.placeholder(tf.float32, shape: (-1, img_size_flat), name: "X"); y = tf.placeholder(tf.float32, shape: (-1, n_classes), name: "Y"); // Create a fully-connected layer with h1 nodes as hidden layer var fc1 = fc_layer(x, h1, "FC1", use_relu: true); // Create a fully-connected layer with n_classes nodes as output layer var output_logits = fc_layer(fc1, n_classes, "OUT", use_relu: false); // Define the loss function, optimizer, and accuracy var logits = tf.nn.softmax_cross_entropy_with_logits(labels: y, logits: output_logits); loss = tf.reduce_mean(logits, name: "loss"); optimizer = tf.train.AdamOptimizer(learning_rate: learning_rate, name: "Adam-op").minimize(loss); var correct_prediction = tf.equal(tf.argmax(output_logits, 1), tf.argmax(y, 1), name: "correct_pred"); accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32), name: "accuracy"); // Network predictions var cls_prediction = tf.argmax(output_logits, axis: 1, name: "predictions"); return graph; } private Tensor fc_layer(Tensor x, int num_units, string name, bool use_relu = true) { var in_dim = x.shape[1]; var initer = tf.truncated_normal_initializer(stddev: 0.01f); var W = tf.get_variable("W_" + name, dtype: tf.float32, shape: (in_dim, num_units), initializer: initer); var initial = tf.constant(0f, num_units); var b = tf.get_variable("b_" + name, dtype: tf.float32, initializer: initial); var layer = tf.matmul(x, W) + b; if (use_relu) layer = tf.nn.relu(layer); return layer; } public Graph ImportGraph() => throw new NotImplementedException(); public void Predict(Session sess) => throw new NotImplementedException(); public void PrepareData() { mnist = MnistModelLoader.LoadAsync(".resources/mnist", oneHot: true, showProgressInConsole: true).Result; } public void Train(Session sess) { // Number of training iterations in each epoch var num_tr_iter = mnist.Train.Labels.len / batch_size; var init = tf.global_variables_initializer(); sess.run(init); float loss_val = 100.0f; float accuracy_val = 0f; foreach (var epoch in range(epochs)) { print($"Training epoch: {epoch + 1}"); // Randomly shuffle the training data at the beginning of each epoch var (x_train, y_train) = mnist.Randomize(mnist.Train.Data, mnist.Train.Labels); foreach (var iteration in range(num_tr_iter)) { var start = iteration * batch_size; var end = (iteration + 1) * batch_size; var (x_batch, y_batch) = mnist.GetNextBatch(x_train, y_train, start, end); // Run optimization op (backprop) sess.run(optimizer, new FeedItem(x, x_batch), new FeedItem(y, y_batch)); if (iteration % display_freq == 0) { // Calculate and display the batch loss and accuracy var result = sess.run(new[] { loss, accuracy }, new FeedItem(x, x_batch), new FeedItem(y, y_batch)); loss_val = result[0]; accuracy_val = result[1]; print($"iter {iteration.ToString("000")}: Loss={loss_val.ToString("0.0000")}, Training Accuracy={accuracy_val.ToString("P")}"); } } // Run validation after every epoch var results1 = sess.run(new[] { loss, accuracy }, new FeedItem(x, mnist.Validation.Data), new FeedItem(y, mnist.Validation.Labels)); loss_val = results1[0]; accuracy_val = results1[1]; print("---------------------------------------------------------"); print($"Epoch: {epoch + 1}, validation loss: {loss_val.ToString("0.0000")}, validation accuracy: {accuracy_val.ToString("P")}"); print("---------------------------------------------------------"); } } public void Test(Session sess) { var result = sess.run(new[] { loss, accuracy }, new FeedItem(x, mnist.Test.Data), new FeedItem(y, mnist.Test.Labels)); loss_test = result[0]; accuracy_test = result[1]; print("---------------------------------------------------------"); print($"Test loss: {loss_test.ToString("0.0000")}, test accuracy: {accuracy_test.ToString("P")}"); print("---------------------------------------------------------"); } } }
41.243243
151
0.54076
[ "Apache-2.0" ]
jingle1000/TensorFlow.NET
test/TensorFlowNET.Examples/ImageProcessing/DigitRecognitionNN.cs
7,632
C#
using System.Collections.Generic; namespace Serious.IO.Messages { /// <summary> /// The response from calling https://api.ab.bot/api/cli/list. This is used by the Abbot CLI to /// retrieve info about a skill and start an editing session. /// </summary> public class SkillListResponse { /// <summary> /// The field the results are ordered by. /// </summary> public SkillOrderBy OrderBy { get; set; } = SkillOrderBy.Name; /// <summary> /// The direction the results are ordered by. /// </summary> public OrderDirection OrderDirection { get; set; } = OrderDirection.Ascending; /// <summary> /// The requested results. /// </summary> public IList<SkillGetResponse> Results { get; set; } = null!; } }
31.923077
99
0.593976
[ "MIT" ]
aseriousbiz/abbot-cli
src/Abbot.Messages/Responses/SkillListResponse.cs
830
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BrowserGameEngine.Persistence { public class FileStorage : IBlobStorage { private readonly DirectoryInfo directory; public FileStorage(DirectoryInfo directory) { this.directory = directory; EnsureDirectory(); } private void EnsureDirectory() { directory.Create(); } private FileInfo GetFile(string name) { return new FileInfo(Path.Combine(directory.FullName, name)); } public bool Exists(string name) => GetFile(name).Exists; public async Task<byte[]> Load(string name) { var file = GetFile(name); if (!file.Exists) throw new FileNotFoundException("File not found", file.FullName); return await File.ReadAllBytesAsync(file.FullName); } public async Task Store(string name, byte[] blob) { EnsureDirectory(); await File.WriteAllBytesAsync(GetFile(name).FullName, blob); } } }
25.076923
86
0.736196
[ "Apache-2.0" ]
discostu105/bge
src/BrowserGameEngine.Persistence/FileStorage.cs
980
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 어셈블리에 대한 일반 정보는 다음 특성 집합을 통해 // 제어됩니다. 어셈블리와 관련된 정보를 수정하려면 // 이러한 특성 값을 변경하세요. [assembly: AssemblyTitle("UsingCallback")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("UsingCallback")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // ComVisible을 false로 설정하면 이 어셈블리의 형식이 COM 구성 요소에 // 표시되지 않습니다. COM에서 이 어셈블리의 형식에 액세스하려면 // 해당 형식에 대해 ComVisible 특성을 true로 설정하세요. [assembly: ComVisible(false)] // 이 프로젝트가 COM에 노출되는 경우 다음 GUID는 typelib의 ID를 나타냅니다. [assembly: Guid("9209ac3c-1cce-46ab-8e95-1dca460e24b7")] // 어셈블리의 버전 정보는 다음 네 가지 값으로 구성됩니다. // // 주 버전 // 부 버전 // 빌드 번호 // 수정 버전 // // 모든 값을 지정하거나 아래와 같이 '*'를 사용하여 빌드 번호 및 수정 번호가 자동으로 // 지정되도록 할 수 있습니다. // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
28.756757
56
0.698308
[ "MIT" ]
totalintelli/UsingCallback
UsingCallback/Properties/AssemblyInfo.cs
1,505
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ZLMediaKit.Common.Dtos.HookResultDto { public interface IHookServerStartedResult : IHookCommonResult { } public class HookServerStartedResult: HookCommonResult, IHookServerStartedResult { } }
20.294118
84
0.773913
[ "MIT" ]
chengxiaosheng/ZLMediaKit.HttpApi
ZLMediaKit.Common/Dtos/HookResultDto/IHookServerStartedResult.cs
347
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.Speech.AudioFormat; using System.Speech.Internal; using System.Speech.Internal.ObjectTokens; namespace System.Speech.Recognition { // This represents the attributes various speech recognizers may, or may not support. public class RecognizerInfo : IDisposable { #region Constructors private RecognizerInfo(ObjectToken token, CultureInfo culture) { // Retrieve the token name _id = token.Name; // Retrieve default display name _description = token.Description; // Store full object token id for internal use. // NOTE - SAPI returns the wrong hive for tokenenum tokens (always HKLM). // Do not rely on the path to be correct in all cases. _sapiObjectTokenId = token.Id; _name = token.TokenName(); _culture = culture; // Enum all values and add to custom table Dictionary<string, string> attrs = new(); foreach (string keyName in token.Attributes.GetValueNames()) { string attributeValue; if (token.Attributes.TryGetString(keyName, out attributeValue)) { attrs[keyName] = attributeValue; } } _attributes = new ReadOnlyDictionary<string, string>(attrs); string audioFormats; if (token.Attributes.TryGetString("AudioFormats", out audioFormats)) { _supportedAudioFormats = new ReadOnlyCollection<SpeechAudioFormatInfo>( SapiAttributeParser.GetAudioFormatsFromString(audioFormats) ); } else { _supportedAudioFormats = new ReadOnlyCollection<SpeechAudioFormatInfo>( new List<SpeechAudioFormatInfo>() ); } _objectToken = token; } internal static RecognizerInfo Create(ObjectToken token) { // Token for recognizer should have Attributes. if (token.Attributes == null) { return null; } // Get other attributes string langId; // must have a language id if (!token.Attributes.TryGetString("Language", out langId)) { return null; } CultureInfo cultureInfo = SapiAttributeParser.GetCultureInfoFromLanguageString(langId); if (cultureInfo != null) { return new RecognizerInfo(token, cultureInfo); } else { return null; } } internal ObjectToken GetObjectToken() { return _objectToken; } /// <summary> /// For IDisposable. /// RecognizerInfo can be constructed through creating a new object token (usage of _recognizerInfo in RecognizerBase), /// so dispose needs to be called. /// </summary> public void Dispose() { _objectToken.Dispose(); GC.SuppressFinalize(this); } #endregion #region public Properties public string Id { get { return _id; } } public string Name { get { return _name; } } public string Description { get { return _description; } } public CultureInfo Culture { get { return _culture; } } public ReadOnlyCollection<SpeechAudioFormatInfo> SupportedAudioFormats { get { return _supportedAudioFormats; } } public IDictionary<string, string> AdditionalInfo { get { return _attributes; } } #endregion #region Internal Properties #endregion #region Private Fields // This table stores each attribute private ReadOnlyDictionary<string, string> _attributes; // Named attributes - these get initialized in constructor private string _id; private string _name; private string _description; private string _sapiObjectTokenId; private CultureInfo _culture; private ReadOnlyCollection<SpeechAudioFormatInfo> _supportedAudioFormats; private ObjectToken _objectToken; #endregion } }
29.59375
127
0.571067
[ "MIT" ]
belav/runtime
src/libraries/System.Speech/src/Recognition/RecognizerInfo.cs
4,735
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 ds-2015-04-16.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.DirectoryService.Model { /// <summary> /// Container for the parameters to the VerifyTrust operation. /// AWS Directory Service for Microsoft Active Directory allows you to configure and verify /// trust relationships. /// /// /// <para> /// This action verifies a trust relationship between your Microsoft AD in the AWS cloud /// and an external domain. /// </para> /// </summary> public partial class VerifyTrustRequest : AmazonDirectoryServiceRequest { private string _trustId; /// <summary> /// Gets and sets the property TrustId. /// <para> /// The unique Trust ID of the trust relationship to verify. /// </para> /// </summary> public string TrustId { get { return this._trustId; } set { this._trustId = value; } } // Check to see if TrustId property is set internal bool IsSetTrustId() { return this._trustId != null; } } }
30.09375
100
0.652648
[ "Apache-2.0" ]
Bynder/aws-sdk-net
sdk/src/Services/DirectoryService/Generated/Model/VerifyTrustRequest.cs
1,926
C#
// Copyright © 2015 Dmitry Sikorsky. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.Linq; using ExtCore.Data.EntityFramework; using Microsoft.EntityFrameworkCore; using Platformus.Barebone.Data.Extensions; using Platformus.Domain.Data.Abstractions; using Platformus.Domain.Data.Entities; namespace Platformus.Domain.Data.EntityFramework.SqlServer { /// <summary> /// Implements the <see cref="IDataTypeRepository"/> interface and represents the repository /// for manipulating the <see cref="DataType"/> entities in the context of SQL Server database. /// </summary> public class DataTypeRepository : RepositoryBase<DataType>, IDataTypeRepository { /// <summary> /// Gets the data type by the identifier. /// </summary> /// <param name="id">The unique identifier of the data type.</param> /// <returns>Found data type with the given identifier.</returns> public DataType WithKey(int id) { return this.dbSet.Find(id); } /// <summary> /// Gets all the data types using sorting by position (ascending). /// </summary> /// <returns>Found data types.</returns> public IEnumerable<DataType> All() { return this.dbSet.AsNoTracking().OrderBy(dt => dt.Position); } /// <summary> /// Gets all the data types using the given filtering, sorting, and paging. /// </summary> /// <param name="orderBy">The data type property name to sort by.</param> /// <param name="direction">The sorting direction.</param> /// <param name="skip">The number of data types that should be skipped.</param> /// <param name="take">The number of data types that should be taken.</param> /// <param name="filter">The filtering query.</param> /// <returns>Found data types using the given filtering, sorting, and paging.</returns> public IEnumerable<DataType> Range(string orderBy, string direction, int skip, int take, string filter) { return this.GetFilteredDataTypes(dbSet.AsNoTracking(), filter).OrderBy(orderBy, direction).Skip(skip).Take(take); } /// <summary> /// Creates the data type. /// </summary> /// <param name="dataType">The data type to create.</param> public void Create(DataType dataType) { this.dbSet.Add(dataType); } /// <summary> /// Edits the data type. /// </summary> /// <param name="dataType">The data type to edit.</param> public void Edit(DataType dataType) { this.storageContext.Entry(dataType).State = EntityState.Modified; } /// <summary> /// Deletes the data type specified by the identifier. /// </summary> /// <param name="id">The unique identifier of the data type to delete.</param> public void Delete(int id) { this.Delete(this.WithKey(id)); } /// <summary> /// Deletes the data type. /// </summary> /// <param name="dataType">The data type to delete.</param> public void Delete(DataType dataType) { this.storageContext.Database.ExecuteSqlCommand( @" DELETE FROM DataTypeParameterValues WHERE DataTypeParameterId IN (SELECT Id FROM DataTypeParameters WHERE DataTypeId = {0}); DELETE FROM DataTypeParameters WHERE DataTypeId = {0}; DELETE FROM SerializedObjects WHERE ObjectId IN (SELECT Id FROM Objects WHERE ClassId IN (SELECT ClassId FROM Members WHERE PropertyDataTypeId = {0})); CREATE TABLE #Dictionaries (Id INT PRIMARY KEY); INSERT INTO #Dictionaries SELECT StringValueId FROM Properties WHERE MemberId IN (SELECT Id FROM Members WHERE PropertyDataTypeId = {0}) AND StringValueId IS NOT NULL; DELETE FROM Properties WHERE MemberId IN (SELECT Id FROM Members WHERE PropertyDataTypeId = {0}); DELETE FROM Localizations WHERE DictionaryId IN (SELECT Id FROM #Dictionaries); DELETE FROM Dictionaries WHERE Id IN (SELECT Id FROM #Dictionaries); DELETE FROM Members WHERE PropertyDataTypeId = {0}; ", dataType.Id ); this.dbSet.Remove(dataType); } /// <summary> /// Counts the number of the data types with the given filtering. /// </summary> /// <param name="filter">The filtering query.</param> /// <returns>The number of data types found.</returns> public int Count(string filter) { return this.GetFilteredDataTypes(dbSet, filter).Count(); } private IQueryable<DataType> GetFilteredDataTypes(IQueryable<DataType> dataTypes, string filter) { if (string.IsNullOrEmpty(filter)) return dataTypes; return dataTypes.Where(dt => dt.Name.ToLower().Contains(filter.ToLower())); } } }
39.295082
177
0.675428
[ "Apache-2.0" ]
TarasKovalenko/Platformus
src/Platformus.Domain.Data.EntityFramework.SqlServer/DataTypeRepository.cs
4,797
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Sandbox.Dynamic_Programming { public class Substrings { /// <summary> /// Given an input string and a length num, return all substrings with exactly num distinct characters. /// </summary> /// <param name="inputStr"> (duh) the input string</param> /// <param name="num"> How many distinct, contiguous characters the substring must have. /// eg: If InputStr was "abecedfhj" and num=4; the substrings returned would be {abec,cedf,edfh,dfhj} since they all have 4 contiguous distinct chars.</param> /// <returns></returns> public static List<string> subStringsKDist(string inputStr, int num) { char[] letters = inputStr.ToCharArray(); List<string> substrings = new List<string>(); for (int i = 0, n = letters.Count() - num; i <= n; i++) { HashSet<char> uniques = new HashSet<char>(); for (int j = i, m = i + num; j < m; j++) { uniques.Add(letters[j]); } if (uniques.Count == num) { substrings.Add(inputStr.Substring(i, 4)); } } return substrings; } } }
34.285714
167
0.53125
[ "MIT" ]
juanuberti/Sandbox
Sandbox/Dynamic Programming/Substrings.cs
1,442
C#
// This is EBurNiFication - https://github.com/picrap/EBurNiFication - MIT License namespace Eburnification.Symbols.Ebnf { public class RepetitionSymbol : CharCharacterSymbol<RepetitionSymbol> { protected override char Character => '*'; } }
29.111111
83
0.725191
[ "MIT" ]
picrap/EBurNiFication
Eburnification/Symbols/Ebnf/RepetitionSymbol.cs
264
C#
#pragma warning disable 108 // new keyword hiding #pragma warning disable 114 // new keyword hiding namespace Windows.UI.Xaml.Controls { #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__ [global::Uno.NotImplemented] #endif public partial class SemanticZoomViewChangedEventArgs { #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "NET461", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__", "__MACOS__")] public global::Windows.UI.Xaml.Controls.SemanticZoomLocation SourceItem { get { throw new global::System.NotImplementedException("The member SemanticZoomLocation SemanticZoomViewChangedEventArgs.SourceItem is not implemented in Uno."); } set { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.UI.Xaml.Controls.SemanticZoomViewChangedEventArgs", "SemanticZoomLocation SemanticZoomViewChangedEventArgs.SourceItem"); } } #endif #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "NET461", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__", "__MACOS__")] public bool IsSourceZoomedInView { get { throw new global::System.NotImplementedException("The member bool SemanticZoomViewChangedEventArgs.IsSourceZoomedInView is not implemented in Uno."); } set { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.UI.Xaml.Controls.SemanticZoomViewChangedEventArgs", "bool SemanticZoomViewChangedEventArgs.IsSourceZoomedInView"); } } #endif #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "NET461", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__", "__MACOS__")] public global::Windows.UI.Xaml.Controls.SemanticZoomLocation DestinationItem { get { throw new global::System.NotImplementedException("The member SemanticZoomLocation SemanticZoomViewChangedEventArgs.DestinationItem is not implemented in Uno."); } set { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.UI.Xaml.Controls.SemanticZoomViewChangedEventArgs", "SemanticZoomLocation SemanticZoomViewChangedEventArgs.DestinationItem"); } } #endif #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "NET461", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__", "__MACOS__")] public SemanticZoomViewChangedEventArgs() { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.UI.Xaml.Controls.SemanticZoomViewChangedEventArgs", "SemanticZoomViewChangedEventArgs.SemanticZoomViewChangedEventArgs()"); } #endif // Forced skipping of method Windows.UI.Xaml.Controls.SemanticZoomViewChangedEventArgs.SemanticZoomViewChangedEventArgs() // Forced skipping of method Windows.UI.Xaml.Controls.SemanticZoomViewChangedEventArgs.IsSourceZoomedInView.get // Forced skipping of method Windows.UI.Xaml.Controls.SemanticZoomViewChangedEventArgs.IsSourceZoomedInView.set // Forced skipping of method Windows.UI.Xaml.Controls.SemanticZoomViewChangedEventArgs.SourceItem.get // Forced skipping of method Windows.UI.Xaml.Controls.SemanticZoomViewChangedEventArgs.SourceItem.set // Forced skipping of method Windows.UI.Xaml.Controls.SemanticZoomViewChangedEventArgs.DestinationItem.get // Forced skipping of method Windows.UI.Xaml.Controls.SemanticZoomViewChangedEventArgs.DestinationItem.set } }
55.102941
212
0.785695
[ "Apache-2.0" ]
AbdalaMask/uno
src/Uno.UI/Generated/3.0.0.0/Windows.UI.Xaml.Controls/SemanticZoomViewChangedEventArgs.cs
3,747
C#
using Core.Infrastructure.Interfaces.Configuration; using System.Threading; using System.Threading.Tasks; using System.Web.Mvc; using Web.Site.Services.Interfaces; namespace Web.Site.Controllers { public class HomeController : BaseController { private readonly IApiService _apiService; private readonly IConfigurationProvider _configurationProvider; public HomeController( IConfigurationProvider configurationProvider, IApiService apiService ) : base(configurationProvider) { _apiService = apiService; _configurationProvider = configurationProvider; } public async Task<ActionResult> Index() { ViewBag.CaptchaSiteKey = _configurationProvider.GetSharedEnvironmentConfigByCulture("Captcha:SiteKey", Thread.CurrentThread.CurrentCulture); ViewBag.PrivacyNoticeUrl = string.Format( _configurationProvider.GetSharedConfig("Legal:PrivacyNoticeLink"), _configurationProvider.GetSharedEnvironmentConfigByCulture("Mldz:SiteId", Thread.CurrentThread.CurrentCulture)); return View(); } public ActionResult Holding() { ViewBag.CaptchaSiteKey = _configurationProvider.GetSharedEnvironmentConfigByCulture("Captcha:SiteKey", Thread.CurrentThread.CurrentCulture); ViewBag.PrivacyNoticeUrl = string.Format( _configurationProvider.GetSharedConfig("Legal:PrivacyNoticeLink"), _configurationProvider.GetSharedEnvironmentConfigByCulture("Mldz:SiteId", Thread.CurrentThread.CurrentCulture)); return View(); } } }
40.577778
114
0.650602
[ "MIT" ]
sourcewalker/hexago.net
Source/Web/Web.Site/Controllers/HomeController.cs
1,828
C#
using System; using System.Collections.Generic; using Android.Runtime; using Java.Interop; namespace Com.Qmuiteam.Qmui.Widget.PullLayout { // Metadata.xml XPath class reference: path="/api/package[@name='com.qmuiteam.qmui.widget.pullLayout']/class[@name='QMUIPullLoadMoreView']" [global::Android.Runtime.Register ("com/qmuiteam/qmui/widget/pullLayout/QMUIPullLoadMoreView", DoNotGenerateAcw=true)] public partial class QMUIPullLoadMoreView : global::AndroidX.ConstraintLayout.Widget.ConstraintLayout, global::Com.Qmuiteam.Qmui.Widget.PullLayout.QMUIPullLayout.IActionPullWatcherView { static readonly JniPeerMembers _members = new XAPeerMembers ("com/qmuiteam/qmui/widget/pullLayout/QMUIPullLoadMoreView", typeof (QMUIPullLoadMoreView)); internal static IntPtr class_ref { get { return _members.JniPeerType.PeerReference.Handle; } } public override global::Java.Interop.JniPeerMembers JniPeerMembers { get { return _members; } } protected override IntPtr ThresholdClass { get { return _members.JniPeerType.PeerReference.Handle; } } protected override global::System.Type ThresholdType { get { return _members.ManagedPeerType; } } protected QMUIPullLoadMoreView (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} // Metadata.xml XPath constructor reference: path="/api/package[@name='com.qmuiteam.qmui.widget.pullLayout']/class[@name='QMUIPullLoadMoreView']/constructor[@name='QMUIPullLoadMoreView' and count(parameter)=1 and parameter[1][@type='android.content.Context']]" [Register (".ctor", "(Landroid/content/Context;)V", "")] public unsafe QMUIPullLoadMoreView (global::Android.Content.Context context) : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { const string __id = "(Landroid/content/Context;)V"; if (((global::Java.Lang.Object) this).Handle != IntPtr.Zero) return; try { JniArgumentValue* __args = stackalloc JniArgumentValue [1]; __args [0] = new JniArgumentValue ((context == null) ? IntPtr.Zero : ((global::Java.Lang.Object) context).Handle); var __r = _members.InstanceMethods.StartCreateInstance (__id, ((object) this).GetType (), __args); SetHandle (__r.Handle, JniHandleOwnership.TransferLocalRef); _members.InstanceMethods.FinishCreateInstance (__id, this, __args); } finally { global::System.GC.KeepAlive (context); } } // Metadata.xml XPath constructor reference: path="/api/package[@name='com.qmuiteam.qmui.widget.pullLayout']/class[@name='QMUIPullLoadMoreView']/constructor[@name='QMUIPullLoadMoreView' and count(parameter)=2 and parameter[1][@type='android.content.Context'] and parameter[2][@type='android.util.AttributeSet']]" [Register (".ctor", "(Landroid/content/Context;Landroid/util/AttributeSet;)V", "")] public unsafe QMUIPullLoadMoreView (global::Android.Content.Context context, global::Android.Util.IAttributeSet attrs) : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { const string __id = "(Landroid/content/Context;Landroid/util/AttributeSet;)V"; if (((global::Java.Lang.Object) this).Handle != IntPtr.Zero) return; try { JniArgumentValue* __args = stackalloc JniArgumentValue [2]; __args [0] = new JniArgumentValue ((context == null) ? IntPtr.Zero : ((global::Java.Lang.Object) context).Handle); __args [1] = new JniArgumentValue ((attrs == null) ? IntPtr.Zero : ((global::Java.Lang.Object) attrs).Handle); var __r = _members.InstanceMethods.StartCreateInstance (__id, ((object) this).GetType (), __args); SetHandle (__r.Handle, JniHandleOwnership.TransferLocalRef); _members.InstanceMethods.FinishCreateInstance (__id, this, __args); } finally { global::System.GC.KeepAlive (context); global::System.GC.KeepAlive (attrs); } } // Metadata.xml XPath constructor reference: path="/api/package[@name='com.qmuiteam.qmui.widget.pullLayout']/class[@name='QMUIPullLoadMoreView']/constructor[@name='QMUIPullLoadMoreView' and count(parameter)=3 and parameter[1][@type='android.content.Context'] and parameter[2][@type='android.util.AttributeSet'] and parameter[3][@type='int']]" [Register (".ctor", "(Landroid/content/Context;Landroid/util/AttributeSet;I)V", "")] public unsafe QMUIPullLoadMoreView (global::Android.Content.Context context, global::Android.Util.IAttributeSet attrs, int defStyleAttr) : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { const string __id = "(Landroid/content/Context;Landroid/util/AttributeSet;I)V"; if (((global::Java.Lang.Object) this).Handle != IntPtr.Zero) return; try { JniArgumentValue* __args = stackalloc JniArgumentValue [3]; __args [0] = new JniArgumentValue ((context == null) ? IntPtr.Zero : ((global::Java.Lang.Object) context).Handle); __args [1] = new JniArgumentValue ((attrs == null) ? IntPtr.Zero : ((global::Java.Lang.Object) attrs).Handle); __args [2] = new JniArgumentValue (defStyleAttr); var __r = _members.InstanceMethods.StartCreateInstance (__id, ((object) this).GetType (), __args); SetHandle (__r.Handle, JniHandleOwnership.TransferLocalRef); _members.InstanceMethods.FinishCreateInstance (__id, this, __args); } finally { global::System.GC.KeepAlive (context); global::System.GC.KeepAlive (attrs); } } static Delegate cb_onActionFinished; #pragma warning disable 0169 static Delegate GetOnActionFinishedHandler () { if (cb_onActionFinished == null) cb_onActionFinished = JNINativeWrapper.CreateDelegate ((_JniMarshal_PP_V) n_OnActionFinished); return cb_onActionFinished; } static void n_OnActionFinished (IntPtr jnienv, IntPtr native__this) { var __this = global::Java.Lang.Object.GetObject<global::Com.Qmuiteam.Qmui.Widget.PullLayout.QMUIPullLoadMoreView> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); __this.OnActionFinished (); } #pragma warning restore 0169 // Metadata.xml XPath method reference: path="/api/package[@name='com.qmuiteam.qmui.widget.pullLayout']/class[@name='QMUIPullLoadMoreView']/method[@name='onActionFinished' and count(parameter)=0]" [Register ("onActionFinished", "()V", "GetOnActionFinishedHandler")] public virtual unsafe void OnActionFinished () { const string __id = "onActionFinished.()V"; try { _members.InstanceMethods.InvokeVirtualVoidMethod (__id, this, null); } finally { } } static Delegate cb_onActionTriggered; #pragma warning disable 0169 static Delegate GetOnActionTriggeredHandler () { if (cb_onActionTriggered == null) cb_onActionTriggered = JNINativeWrapper.CreateDelegate ((_JniMarshal_PP_V) n_OnActionTriggered); return cb_onActionTriggered; } static void n_OnActionTriggered (IntPtr jnienv, IntPtr native__this) { var __this = global::Java.Lang.Object.GetObject<global::Com.Qmuiteam.Qmui.Widget.PullLayout.QMUIPullLoadMoreView> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); __this.OnActionTriggered (); } #pragma warning restore 0169 // Metadata.xml XPath method reference: path="/api/package[@name='com.qmuiteam.qmui.widget.pullLayout']/class[@name='QMUIPullLoadMoreView']/method[@name='onActionTriggered' and count(parameter)=0]" [Register ("onActionTriggered", "()V", "GetOnActionTriggeredHandler")] public virtual unsafe void OnActionTriggered () { const string __id = "onActionTriggered.()V"; try { _members.InstanceMethods.InvokeVirtualVoidMethod (__id, this, null); } finally { } } static Delegate cb_onPull_Lcom_qmuiteam_qmui_widget_pullLayout_QMUIPullLayout_PullAction_I; #pragma warning disable 0169 static Delegate GetOnPull_Lcom_qmuiteam_qmui_widget_pullLayout_QMUIPullLayout_PullAction_IHandler () { if (cb_onPull_Lcom_qmuiteam_qmui_widget_pullLayout_QMUIPullLayout_PullAction_I == null) cb_onPull_Lcom_qmuiteam_qmui_widget_pullLayout_QMUIPullLayout_PullAction_I = JNINativeWrapper.CreateDelegate ((_JniMarshal_PPLI_V) n_OnPull_Lcom_qmuiteam_qmui_widget_pullLayout_QMUIPullLayout_PullAction_I); return cb_onPull_Lcom_qmuiteam_qmui_widget_pullLayout_QMUIPullLayout_PullAction_I; } static void n_OnPull_Lcom_qmuiteam_qmui_widget_pullLayout_QMUIPullLayout_PullAction_I (IntPtr jnienv, IntPtr native__this, IntPtr native_pullAction, int currentTargetOffset) { var __this = global::Java.Lang.Object.GetObject<global::Com.Qmuiteam.Qmui.Widget.PullLayout.QMUIPullLoadMoreView> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); var pullAction = global::Java.Lang.Object.GetObject<global::Com.Qmuiteam.Qmui.Widget.PullLayout.QMUIPullLayout.PullAction> (native_pullAction, JniHandleOwnership.DoNotTransfer); __this.OnPull (pullAction, currentTargetOffset); } #pragma warning restore 0169 // Metadata.xml XPath method reference: path="/api/package[@name='com.qmuiteam.qmui.widget.pullLayout']/class[@name='QMUIPullLoadMoreView']/method[@name='onPull' and count(parameter)=2 and parameter[1][@type='com.qmuiteam.qmui.widget.pullLayout.QMUIPullLayout.PullAction'] and parameter[2][@type='int']]" [Register ("onPull", "(Lcom/qmuiteam/qmui/widget/pullLayout/QMUIPullLayout$PullAction;I)V", "GetOnPull_Lcom_qmuiteam_qmui_widget_pullLayout_QMUIPullLayout_PullAction_IHandler")] public virtual unsafe void OnPull (global::Com.Qmuiteam.Qmui.Widget.PullLayout.QMUIPullLayout.PullAction pullAction, int currentTargetOffset) { const string __id = "onPull.(Lcom/qmuiteam/qmui/widget/pullLayout/QMUIPullLayout$PullAction;I)V"; try { JniArgumentValue* __args = stackalloc JniArgumentValue [2]; __args [0] = new JniArgumentValue ((pullAction == null) ? IntPtr.Zero : ((global::Java.Lang.Object) pullAction).Handle); __args [1] = new JniArgumentValue (currentTargetOffset); _members.InstanceMethods.InvokeVirtualVoidMethod (__id, this, __args); } finally { global::System.GC.KeepAlive (pullAction); } } } }
52.206349
344
0.763454
[ "MIT" ]
daddycoding/XamarinQMUI
XamarinQMUI/QMUI.Droid/Additions/Com.Qmuiteam.Qmui.Widget.PullLayout.QMUIPullLoadMoreView.cs
9,867
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class LeftPaddle : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update () { //Si se presiona W, se movera hacia arriba. if (Input.GetKey(KeyCode.W)) { this.transform.Translate (Vector3.up); } //Si se presiona S, se movera hacia abajo. if (Input.GetKey(KeyCode.S)) { this.transform.Translate (Vector3.down); } //Si se presiona A, se movera hacia izquierda. if (Input.GetKey(KeyCode.A)) { this.transform.Translate (Vector3.left); } //Si se presiona D, se movera hacia derecha. if (Input.GetKey(KeyCode.D)) { this.transform.Translate (Vector3.right); } } }
16.73913
48
0.67013
[ "MIT" ]
Santiagos7/SantiagoBarrera-Partial2-TableTennis
SantiagoBarrera-TableTennis/Assets/Scripts/LeftPaddle.cs
772
C#
using System.Collections.Generic; namespace Pierre.Models { public class Treat { public Treat() { this.Flavors = new HashSet<TreatFlavor>(); } public int TreatId { get; set; } public string TreatName { get; set; } public virtual ApplicationUser User { get; set; } public virtual ICollection<TreatFlavor> Flavors { get; set; } } }
21.823529
65
0.657682
[ "MIT" ]
Prestwick97/Pierre.Solution
Pierre/Models/Treat.cs
371
C#
/* Copyright (C) 2012-2014 de4dot@gmail.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace dnlib.IO { /// <summary> /// Extension methods /// </summary> public static partial class IOExtensions { } }
40.806452
74
0.743083
[ "MIT" ]
Georgeto/dnlib
src/IO/IOExtensions.cs
1,267
C#
/* part of Pyrolite, by Irmen de Jong (irmen@razorvine.net) */ using System; using System.Text.RegularExpressions; // ReSharper disable InconsistentNaming // ReSharper disable UnusedMember.Global namespace Razorvine.Pyro { /// <summary> /// The Pyro URI object. /// </summary> [Serializable] public class PyroURI { public string protocol { get; } public string objectid { get; } public string host { get; } public int port { get; } public PyroURI() { protocol="PYRO"; } public PyroURI(PyroURI other) { protocol = other.protocol; objectid = other.objectid; host = other.host; port = other.port; } public PyroURI(string uri) { Regex r = new Regex("(PYRO[A-Z]*):(\\S+?)(@(\\S+))?$"); Match m = r.Match(uri); if (m.Success) { protocol = m.Groups[1].Value; objectid = m.Groups[2].Value; var loc = m.Groups[4].Value.Split(':'); host = loc[0]; port = int.Parse(loc[1]); } else { throw new PyroException("invalid URI string"); } } public PyroURI(string objectid, string host, int port) { protocol = "PYRO"; this.objectid = objectid; this.host = host; this.port = port; } public override string ToString() { return "<PyroURI " + protocol + ":" + objectid + "@" + host + ":" + port + ">"; } #region Equals and GetHashCode implementation public override bool Equals(object obj) { PyroURI other = obj as PyroURI; if (other == null) return false; return other.ToString()==ToString(); } public override int GetHashCode() { return ToString().GetHashCode(); } public static bool operator ==(PyroURI lhs, PyroURI rhs) { if (ReferenceEquals(lhs, rhs)) return true; if (ReferenceEquals(lhs, null) || ReferenceEquals(rhs, null)) return false; return lhs.Equals(rhs); } public static bool operator !=(PyroURI lhs, PyroURI rhs) { return !(lhs == rhs); } #endregion } }
20.733333
81
0.652733
[ "MIT" ]
sreekanth370/Pyrolite
dotnet/Razorvine.Pyrolite/Pyrolite/Pyro/PyroURI.cs
1,866
C#
// Copyright (c) Gaurav Aroraa // Licensed under the MIT License. See License.txt in the project root for license information. using System; using NUnit.Framework; namespace TDD_Katas_project.FizzBuzzKata { [TestFixture] [Category("TheFizzBuzzKata")] public class TestFizzBuzz { #region Private members private string _resultFizz; #endregion #region Setup/TearDown [TestFixtureSetUp] public void Setup() { _resultFizz = @"1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz 16 17 Fizz 19 Buzz Fizz 22 23 Fizz Buzz 26 Fizz 28 29 FizzBuzz 31 32 Fizz 34 Buzz Fizz 37 38 Fizz Buzz 41 Fizz 43 44 FizzBuzz 46 47 Fizz 49 Buzz Fizz 52 53 Fizz Buzz 56 Fizz 58 59 FizzBuzz 61 62 Fizz 64 Buzz Fizz 67 68 Fizz Buzz 71 Fizz 73 74 FizzBuzz 76 77 Fizz 79 Buzz Fizz 82 83 Fizz Buzz 86 Fizz 88 89 FizzBuzz 91 92 Fizz 94 Buzz Fizz 97 98 Fizz Buzz"; } [TestFixtureTearDown] public void TearDown() { _resultFizz = null; } #endregion #region Test Methods [Test] public void CanTestFizz() { Console.WriteLine(FizzBuzz.PrintFizzBuzz()); Assert.That(FizzBuzz.PrintFizzBuzz(), Is.EqualTo(_resultFizz)); } [Test] [TestCase(-1)] [TestCase(101)] [TestCase(0)] public void CanThrowArgumentExceptionWhenSuppliedNumberDoesNotMeetRule(int number) { var exception = Assert.Throws<ArgumentException>(() => FizzBuzz.PrintFizzBuzz(number)); Assert.That(exception.Message, Is.EqualTo(string.Format("entered number is [{0}], which does not meet rule, entered number should be between 1 to 100.", number))); } [Test] [TestCase(1, "1")] [TestCase(3, "Fizz")] [TestCase(5, "Buzz")] [TestCase(15, "FizzBuzz")] [TestCase(30, "FizzBuzz")] public void CanTestSingleNumber(int number, string expectedresult) { var actualresult = FizzBuzz.PrintFizzBuzz(number); Assert.That(actualresult, Is.EqualTo(expectedresult), string.Format("result of entered number [{0}] is [{1}] but it should be [{2}]", number, actualresult, expectedresult)); } #endregion } }
36.738462
442
0.609296
[ "MIT" ]
airesdiegom66/tdd-master
Src/CSharp/Net Framework/FizzBuzzKata/TestFizzBuzz.cs
2,390
C#
// This file is auto-generated, don't edit it. Thanks. using System; using System.Collections.Generic; using System.IO; using Tea; namespace Aliyun.SDK.Hosting.Client.Models { /** * 获取视频雪碧图地址 url response */ public class GetVideoPreviewSpriteURLResponse : TeaModel { /// <summary> /// col /// </summary> [NameInMap("col")] [Validation(Required=false)] public long? Col { get; set; } /// <summary> /// count /// </summary> [NameInMap("count")] [Validation(Required=false)] public long? Count { get; set; } /// <summary> /// frame_count /// </summary> [NameInMap("frame_count")] [Validation(Required=false)] public long? FrameCount { get; set; } /// <summary> /// frame_height /// </summary> [NameInMap("frame_height")] [Validation(Required=false)] public long? FrameHeight { get; set; } /// <summary> /// frame_width /// </summary> [NameInMap("frame_width")] [Validation(Required=false)] public long? FrameWidth { get; set; } /// <summary> /// row /// </summary> [NameInMap("row")] [Validation(Required=false)] public long? Row { get; set; } /// <summary> /// sprite_url_list /// </summary> [NameInMap("sprite_url_list")] [Validation(Required=false)] public List<string> SpriteUrlList { get; set; } } }
23.447761
62
0.52387
[ "Apache-2.0" ]
18730298725/alibabacloud-pds-sdk
hosting/csharp/core/Models/GetVideoPreviewSpriteURLResponse.cs
1,589
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Liquid_VCMP_browser { public partial class FirstStartup : Form { protected Dictionary<string, string> languages = new Dictionary<string, string>(); public FirstStartup() { InitializeComponent(); } private void FirstStartup_Load(object sender, EventArgs e) { } private void button2_Click(object sender, EventArgs e) { Application.Exit(); } private void button3_Click(object sender, EventArgs e) { ConfigurationManager.configuration.defaultidentity.nickname = metroTextBox1.Text; ConfigurationManager.configuration.updater.url = metroTextBox2.Text; ConfigurationManager.configuration.updater.password = metroTextBox3.Text; ConfigurationManager.configuration.updater.check = checkBox1.Checked; ConfigurationManager.configuration.downloadmirror.url = metroTextBox5.Text; ConfigurationManager.configuration.downloadmirror.check = checkBox2.Checked; ConfigurationManager.configuration.directories.vicecity = metroTextBox4.Text; ConfigurationManager.configuration.internationalization.language = languages[comboBox1.Text]; try { System.IO.File.Create(Application.StartupPath + "/vcmp-config.json").Close(); } catch { Error error = new Error(); error.labelError.Text = "Failed to create the file 'vcmp-config.json'"; error.Show(); Close(); } try { ConfigurationManager.Save(); } catch { Error error = new Error(); error.labelError.Text = "Failed to save configuration"; error.Show(); Close(); return; } Application.Restart(); } private void openFileDialog1_FileOk(object sender, CancelEventArgs e) { metroTextBox4.Text = openFileDialog1.FileName; } private void button1_Click(object sender, EventArgs e) { openFileDialog1.ShowDialog(this); } private void FirstStartup_Shown(object sender, EventArgs e) { string[] languagefiles = new string[0]; try { languagefiles = System.IO.Directory.GetFiles(Application.StartupPath + "/internationalization"); } catch { Error error = new Error(); error.labelError.Text = "Failed to read directory 'internationalization' - please verify your installation"; error.Show(); Close(); return; } foreach (string _language in languagefiles) { string language = System.IO.Path.GetFileName(_language).Replace(".json", ""); try { LanguageManager.Load(language); languages.Add(LanguageManager.language.name, language); comboBox1.Items.Add(LanguageManager.language.name); comboBox1.SelectedItem = LanguageManager.language.name; } catch { Error error = new Error(); error.labelError.Text = "Failed to process language file '" + language + "'"; error.Show(); Close(); return; } } } private void FirstStartup_FormClosed(object sender, FormClosedEventArgs e) { Application.Exit(); } } }
29.897059
124
0.550664
[ "MIT" ]
iFlake/Liquid-VCMP-browser
Liquid VCMP browser/Liquid VCMP browser/FirstStartup.cs
4,068
C#
using Rtp; using System; using NUnit.Framework; namespace TestRtp { [TestFixture] public class RtpMessageTest { [Test] public void ParseTest() { byte[] bytes1 = new byte[] { 0xff, 0xff, 0xff, 0xff, 0xb2, 0xEA, 0x46, 0x5C, 0x06, 0xE7, 0x95, 0xA7, 0x00, 0x01, 0x50, 0x61, 0x00, 0x00, 0x00, 0x01, // CSRC1 0x00, 0x00, 0x00, 0x02, // CSRC2 0x01, 0x0A, 0x03, 0xC0, }; int startIndex1 = 4; int length = bytes1.Length; var message1 = RtpMessage.Parse(bytes1, startIndex1, length); Assert.AreEqual(message1.Version, 2, "Rtp.Version"); Assert.AreEqual(message1.Padding, true, "Rtp.Padding"); Assert.AreEqual(message1.Extension, true, "Rtp.Extension"); Assert.AreEqual(message1.CsrcCount, 2, "Rtp.CsrcCount"); Assert.AreEqual(message1.Marker, true, "Rtp.Marker"); Assert.AreEqual(message1.PayloadType, 106, "Rtp.PayloadType"); Assert.AreEqual(message1.SequenceNumber, 0x465c, "Rtp.SequenceNumber"); Assert.AreEqual(message1.Timestamp, 0x006E795A7u, "Rtp.Timestamp"); Assert.AreEqual(message1.Ssrc, 0x00015061u, "Rtp.Ssrc"); Assert.AreEqual(message1.CsrcList[0], 0x00000001u, "CsrcList[0]"); Assert.AreEqual(message1.CsrcList[1], 0x00000002u, "CsrcList[1]"); Assert.AreEqual(message1.GetPayloadLength(startIndex1, bytes1.Length), 4, "Rtp.PayloadLength"); } [Test] [ExpectedException(typeof(NotImplementedException))] public void GetBytesTest() { RtpMessage target = new RtpMessage(); // TODO: Initialize to an appropriate value byte[] bytes = null; // TODO: Initialize to an appropriate value int startIndex = 0; // TODO: Initialize to an appropriate value target.GetBytes(bytes, startIndex); Assert.Inconclusive("A method that does not return a value cannot be verified."); } [Test] public void IsRtpMessageTest() { byte[] bytes1 = new byte[] { 0xff, 0xff, 0xff, 0xff, 0xb2, 0xEA, 0x46, 0x5C, }; byte[] bytes2 = new byte[] { 0xb2, 0xC8, 0x46, 0x5C, }; byte[] bytes3 = new byte[] { 0xb2, 0xC9, 0x46, 0x5C, }; byte[] bytes4 = new byte[] { 0x02, 0xEA, 0x46, 0x5C, }; Assert.IsTrue(RtpMessage.IsRtpMessage(bytes1, 4, bytes1.Length)); Assert.IsFalse(RtpMessage.IsRtpMessage(bytes2, 0, bytes2.Length)); Assert.IsFalse(RtpMessage.IsRtpMessage(bytes3, 0, bytes3.Length)); Assert.IsFalse(RtpMessage.IsRtpMessage(bytes4, 0, bytes4.Length)); } } }
28.952381
98
0.680921
[ "MIT" ]
OverCube/sipserver
Tests/Rtp/RtpMessageTest.cs
2,434
C#
namespace System.Data.SQLite { public partial class Sqlite3 { /* ** 2007 May 1 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** This file contains code used to implement incremental BLOB I/O. ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** SQLITE_SOURCE_ID: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2 ** ************************************************************************* */ //#include "sqliteInt.h" //#include "vdbeInt.h" #if !SQLITE_OMIT_INCRBLOB /* ** Valid sqlite3_blob* handles point to Incrblob structures. */ typedef struct Incrblob Incrblob; struct Incrblob { int flags; /* Copy of "flags" passed to sqlite3_blob_open() */ int nByte; /* Size of open blob, in bytes */ int iOffset; /* Byte offset of blob in cursor data */ BtCursor *pCsr; /* Cursor pointing at blob row */ sqlite3_stmt *pStmt; /* Statement holding cursor open */ sqlite3 db; /* The associated database */ }; /* ** Open a blob handle. */ int sqlite3_blob_open( sqlite3* db, /* The database connection */ string zDb, /* The attached database containing the blob */ string zTable, /* The table containing the blob */ string zColumn, /* The column containing the blob */ sqlite_int64 iRow, /* The row containing the glob */ int flags, /* True -> read/write access, false -> read-only */ sqlite3_blob **ppBlob /* Handle for accessing the blob returned here */ ){ int nAttempt = 0; int iCol; /* Index of zColumn in row-record */ /* This VDBE program seeks a btree cursor to the identified ** db/table/row entry. The reason for using a vdbe program instead ** of writing code to use the b-tree layer directly is that the ** vdbe program will take advantage of the various transaction, ** locking and error handling infrastructure built into the vdbe. ** ** After seeking the cursor, the vdbe executes an OP_ResultRow. ** Code external to the Vdbe then "borrows" the b-tree cursor and ** uses it to implement the blob_read(), blob_write() and ** blob_bytes() functions. ** ** The sqlite3_blob_close() function finalizes the vdbe program, ** which closes the b-tree cursor and (possibly) commits the ** transaction. */ static const VdbeOpList openBlob[] = { {OP_Transaction, 0, 0, 0}, /* 0: Start a transaction */ {OP_VerifyCookie, 0, 0, 0}, /* 1: Check the schema cookie */ {OP_TableLock, 0, 0, 0}, /* 2: Acquire a read or write lock */ /* One of the following two instructions is replaced by an OP_Noop. */ {OP_OpenRead, 0, 0, 0}, /* 3: Open cursor 0 for reading */ {OP_OpenWrite, 0, 0, 0}, /* 4: Open cursor 0 for read/write */ {OP_Variable, 1, 1, 1}, /* 5: Push the rowid to the stack */ {OP_NotExists, 0, 9, 1}, /* 6: Seek the cursor */ {OP_Column, 0, 0, 1}, /* 7 */ {OP_ResultRow, 1, 0, 0}, /* 8 */ {OP_Close, 0, 0, 0}, /* 9 */ {OP_Halt, 0, 0, 0}, /* 10 */ }; Vdbe *v = 0; int rc = SQLITE_OK; string zErr = 0; Table *pTab; Parse *pParse; *ppBlob = 0; sqlite3_mutex_enter(db->mutex); pParse = sqlite3StackAllocRaw(db, sizeof(*pParse)); if( pParse==0 ){ rc = SQLITE_NOMEM; goto blob_open_out; } do { memset(pParse, 0, sizeof(Parse)); pParse->db = db; sqlite3BtreeEnterAll(db); pTab = sqlite3LocateTable(pParse, 0, zTable, zDb); if( pTab && IsVirtual(pTab) ){ pTab = 0; sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable); } #if !SQLITE_OMIT_VIEW if( pTab && pTab->pSelect ){ pTab = 0; sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable); } #endif if( null==pTab ){ if( pParse->zErrMsg ){ sqlite3DbFree(db, zErr); zErr = pParse->zErrMsg; pParse->zErrMsg = 0; } rc = SQLITE_ERROR; sqlite3BtreeLeaveAll(db); goto blob_open_out; } /* Now search pTab for the exact column. */ for(iCol=0; iCol < pTab->nCol; iCol++) { if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){ break; } } if( iCol==pTab->nCol ){ sqlite3DbFree(db, zErr); zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn); rc = SQLITE_ERROR; sqlite3BtreeLeaveAll(db); goto blob_open_out; } /* If the value is being opened for writing, check that the ** column is not indexed, and that it is not part of a foreign key. ** It is against the rules to open a column to which either of these ** descriptions applies for writing. */ if( flags ){ string zFault = 0; Index *pIdx; #if !SQLITE_OMIT_FOREIGN_KEY if( db->flags&SQLITE_ForeignKeys ){ /* Check that the column is not part of an FK child key definition. It ** is not necessary to check if it is part of a parent key, as parent ** key columns must be indexed. The check below will pick up this ** case. */ FKey *pFKey; for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){ int j; for(j=0; j<pFKey->nCol; j++){ if( pFKey->aCol[j].iFrom==iCol ){ zFault = "foreign key"; } } } } #endif for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ int j; for(j=0; j<pIdx->nColumn; j++){ if( pIdx->aiColumn[j]==iCol ){ zFault = "indexed"; } } } if( zFault ){ sqlite3DbFree(db, zErr); zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault); rc = SQLITE_ERROR; sqlite3BtreeLeaveAll(db); goto blob_open_out; } } v = sqlite3VdbeCreate(db); if( v ){ int iDb = sqlite3SchemaToIndex(db, pTab->pSchema); sqlite3VdbeAddOpList(v, sizeof(openBlob)/sizeof(VdbeOpList), openBlob); flags = !!flags; /* flags = (flags ? 1 : 0); */ /* Configure the OP_Transaction */ sqlite3VdbeChangeP1(v, 0, iDb); sqlite3VdbeChangeP2(v, 0, flags); /* Configure the OP_VerifyCookie */ sqlite3VdbeChangeP1(v, 1, iDb); sqlite3VdbeChangeP2(v, 1, pTab->pSchema->schema_cookie); sqlite3VdbeChangeP3(v, 1, pTab->pSchema->iGeneration); /* Make sure a mutex is held on the table to be accessed */ sqlite3VdbeUsesBtree(v, iDb); /* Configure the OP_TableLock instruction */ #if SQLITE_OMIT_SHARED_CACHE sqlite3VdbeChangeToNoop(v, 2, 1); #else sqlite3VdbeChangeP1(v, 2, iDb); sqlite3VdbeChangeP2(v, 2, pTab->tnum); sqlite3VdbeChangeP3(v, 2, flags); sqlite3VdbeChangeP4(v, 2, pTab->zName, P4_TRANSIENT); #endif /* Remove either the OP_OpenWrite or OpenRead. Set the P2 ** parameter of the other to pTab->tnum. */ sqlite3VdbeChangeToNoop(v, 4 - flags, 1); sqlite3VdbeChangeP2(v, 3 + flags, pTab->tnum); sqlite3VdbeChangeP3(v, 3 + flags, iDb); /* Configure the number of columns. Configure the cursor to ** think that the table has one more column than it really ** does. An OP_Column to retrieve this imaginary column will ** always return an SQL NULL. This is useful because it means ** we can invoke OP_Column to fill in the vdbe cursors type ** and offset cache without causing any IO. */ sqlite3VdbeChangeP4(v, 3+flags, SQLITE_INT_TO_PTR(pTab->nCol+1),P4_INT32); sqlite3VdbeChangeP2(v, 7, pTab->nCol); if( null==db->mallocFailed ){ pParse->nVar = 1; pParse->nMem = 1; pParse->nTab = 1; sqlite3VdbeMakeReady(v, pParse); } } sqlite3BtreeLeaveAll(db); goto blob_open_out; } sqlite3_bind_int64((sqlite3_stmt )v, 1, iRow); rc = sqlite3_step((sqlite3_stmt )v); if( rc!=SQLITE_ROW ){ nAttempt++; rc = sqlite3_finalize((sqlite3_stmt )v); sqlite3DbFree(db, zErr); zErr = sqlite3MPrintf(db, sqlite3_errmsg(db)); v = 0; } } while( nAttempt<5 && rc==SQLITE_SCHEMA ); if( rc==SQLITE_ROW ){ /* The row-record has been opened successfully. Check that the ** column in question contains text or a blob. If it contains ** text, it is up to the caller to get the encoding right. */ Incrblob *pBlob; u32 type = v->apCsr[0]->aType[iCol]; if( type<12 ){ sqlite3DbFree(db, zErr); zErr = sqlite3MPrintf(db, "cannot open value of type %s", type==0?"null": type==7?"real": "integer" ); rc = SQLITE_ERROR; goto blob_open_out; } pBlob = (Incrblob )sqlite3DbMallocZero(db, sizeof(Incrblob)); if( db->mallocFailed ){ sqlite3DbFree(db, ref pBlob); goto blob_open_out; } pBlob->flags = flags; pBlob->pCsr = v->apCsr[0]->pCursor; sqlite3BtreeEnterCursor(pBlob->pCsr); sqlite3BtreeCacheOverflow(pBlob->pCsr); sqlite3BtreeLeaveCursor(pBlob->pCsr); pBlob->pStmt = (sqlite3_stmt )v; pBlob->iOffset = v->apCsr[0]->aOffset[iCol]; pBlob->nByte = sqlite3VdbeSerialTypeLen(type); pBlob->db = db; *ppBlob = (sqlite3_blob )pBlob; rc = SQLITE_OK; }else if( rc==SQLITE_OK ){ sqlite3DbFree(db, zErr); zErr = sqlite3MPrintf(db, "no such rowid: %lld", iRow); rc = SQLITE_ERROR; } blob_open_out: if( v && (rc!=SQLITE_OK || db->mallocFailed) ){ sqlite3VdbeFinalize(v); } sqlite3Error(db, rc, zErr); sqlite3DbFree(db, zErr); sqlite3StackFree(db, pParse); rc = sqlite3ApiExit(db, rc); sqlite3_mutex_leave(db->mutex); return rc; } /* ** Close a blob handle that was previously created using ** sqlite3_blob_open(). */ int sqlite3_blob_close(sqlite3_blob *pBlob){ Incrblob *p = (Incrblob )pBlob; int rc; sqlite3 db; if( p ){ db = p->db; sqlite3_mutex_enter(db->mutex); rc = sqlite3_finalize(p->pStmt); sqlite3DbFree(db, ref p); sqlite3_mutex_leave(db->mutex); }else{ rc = SQLITE_OK; } return rc; } /* ** Perform a read or write operation on a blob */ static int blobReadWrite( sqlite3_blob *pBlob, void *z, int n, int iOffset, int (*xCall)(BtCursor*, u32, u32, void) ){ int rc; Incrblob *p = (Incrblob )pBlob; Vdbe *v; sqlite3 db; if( p==0 ) return SQLITE_MISUSE_BKPT(); db = p->db; sqlite3_mutex_enter(db->mutex); v = (Vdbe)p->pStmt; if( n<0 || iOffset<0 || (iOffset+n)>p->nByte ){ /* Request is out of range. Return a transient error. */ rc = SQLITE_ERROR; sqlite3Error(db, SQLITE_ERROR, 0); } else if( v==0 ){ /* If there is no statement handle, then the blob-handle has ** already been invalidated. Return SQLITE_ABORT in this case. */ rc = SQLITE_ABORT; }else{ /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is ** returned, clean-up the statement handle. */ Debug.Assert( db == v->db ); sqlite3BtreeEnterCursor(p->pCsr); rc = xCall(p->pCsr, iOffset+p->iOffset, n, z); sqlite3BtreeLeaveCursor(p->pCsr); if( rc==SQLITE_ABORT ){ sqlite3VdbeFinalize(v); p->pStmt = null; }else{ db->errCode = rc; v->rc = rc; } } rc = sqlite3ApiExit(db, rc); sqlite3_mutex_leave(db->mutex); return rc; } /* ** Read data from a blob handle. */ int sqlite3_blob_read(sqlite3_blob *pBlob, object *z, int n, int iOffset){ return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData); } /* ** Write data to a blob handle. */ int sqlite3_blob_write(sqlite3_blob *pBlob, string z, int n, int iOffset){ return blobReadWrite(pBlob, (void )z, n, iOffset, sqlite3BtreePutData); } /* ** Query a blob handle for the size of the data. ** ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob ** so no mutex is required for access. */ int sqlite3_blob_bytes(sqlite3_blob *pBlob){ Incrblob *p = (Incrblob )pBlob; return p ? p->nByte : 0; } #endif // * #if !SQLITE_OMIT_INCRBLOB */ } }
29.5275
84
0.642283
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
ehsan2022002/VirastarE
System.Data.SQLite/src/vdbeblob_c.cs
11,811
C#
namespace Forcura.NPPES.Models { public class NPPESIdentifier { public string Identifier { get; set; } public string Code { get; set; } public string State { get; set; } public string Issuer { get; set; } public string Description { get; set; } } }
25.166667
47
0.592715
[ "Apache-2.0" ]
griffengorsuchres/npi-api-net
NPPESAPI.net/Models/NPPESIdentifier.cs
304
C#
using Episememe.Api.Configuration; using Episememe.Api.Json; using Episememe.Api.Utilities; using Episememe.Application; using Episememe.Infrastructure; using Episememe.Infrastructure.Database; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace Episememe.Api { public class Startup { private readonly IWebHostEnvironment _env; public Startup(IConfiguration configuration, IWebHostEnvironment env) { Configuration = configuration; _env = env; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddApplication(); services.AddInfrastructure(Configuration); if (_env.IsDevelopment()) { services.ConfigureSwagger(); } if (_env.IsDesktop()) { services.DisableAuthentication(); } else { services.AddJwtAuthentication(Configuration); } services.AddControllers() .AddJsonOptions(options => { options.JsonSerializerOptions.Converters.Add(new UtcTimeConverter()); }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IDatabaseMigrationService databaseMigration) { databaseMigration.Migrate(); if (_env.IsDevelopment() || _env.IsDesktop()) { app.EnableCors(); } if (_env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.ExposeSwagger(); } app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } } }
28.280488
106
0.586028
[ "BSD-3-Clause" ]
marax27/Episememe
server/Episememe.Api/Startup.cs
2,319
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("MetroDom.Conductor")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("MetroDom.Conductor")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("170e75c8-6739-42d3-8e81-e4703989fa94")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.081081
84
0.745919
[ "MIT" ]
fotijr/MetroDom
MetroDom.Conductor/Properties/AssemblyInfo.cs
1,412
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ZencoderWrapper { public class JobListingJob { public DateTime? created_at { get; set; } public DateTime? finished_at { get; set; } public DateTime? updated_at { get; set; } public DateTime? submitted_at { get; set; } public string pass_through { get; set; } public int id { get; set; } public bool test { get; set; } public string state { get; set; } public JobListingMediaFile input_media_file { get; set; } public List<JobListingOutputMediaFile> output_media_files { get; set; } public List<JobListingFile> thumbnails { get; set; } } }
32.043478
79
0.647218
[ "MIT" ]
cdeutsch/ZencoderWrapper
ZencoderWrapper/JobListingJob.cs
739
C#
using GalaSoft.MvvmLight.Command; using Newtonsoft.Json; using Npgsql; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Data; using System.IO; using System.Linq; using System.Net; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media; using System.Windows.Threading; using System.Xml; using System.Xml.Serialization; namespace UnicodeReader { public class MainWindowViewModel : INotifyPropertyChanged { public MainWindowViewModel() { //FeedList = new ObservableCollection<Feed>() //{ // new Feed(){Title = "All Feed",Url="all feed"}, // new Feed(){Title = "EN Feed",Url="https://blogs.embarcadero.com/feed/"}, // new Feed(){Title = "JA Feed",Url="https://blogs.embarcadero.com/ja/feed/"}, // new Feed(){Title = "DE Feed",Url="https://blogs.embarcadero.com/de/feed/"}, // new Feed(){Title = "RU Feed",Url="https://blogs.embarcadero.com/ru/feed/"}, // new Feed(){Title = "PT Feed",Url="https://blogs.embarcadero.com/pt/feed/"}, // new Feed(){Title = "ES Feed",Url="https://blogs.embarcadero.com/es/feed/"}, //}; FeedList = new ObservableCollection<Feed>(); FeedItemsList = new ObservableCollection<FeedItem>(); RefreshCommand = new RelayCommand(GetFeedItems); ConnectCommand = new RelayCommand(GetConnection); ThemeCommand = new RelayCommand<Grid>(ChangeTheme); //ServerName = "localhost"; //Port = "5432"; //User = "postgres"; //Password = "postgres"; //Database = "Test"; Background = (Brush)(new BrushConverter().ConvertFrom("#20262F")); ; Foreground = Brushes.White; HumbergerIcon = "pack://application:,,,/Icons/humbergerwhite.png"; RefreshIcon = "pack://application:,,,/Icons/refreshwhite.png"; ThemeIcon = "pack://application:,,,/Icons/themeiconwhite.png"; Arrow = "pack://application:,,,/Icons/navigatewhite.png"; RightArrow = "pack://application:,,,/Icons/rightarrowwhite.png"; } private Brush _foreground; public Brush Foreground { get { return _foreground; } set { _foreground = value; OnPropertyChanged(nameof(Foreground)); } } private Brush _background; public Brush Background { get { return _background; } set { _background = value; OnPropertyChanged(nameof(Background)); } } private string _humbergerIcon; public string HumbergerIcon { get { return _humbergerIcon; } set { _humbergerIcon = value; OnPropertyChanged(nameof(HumbergerIcon)); } } private string _refreshIcon; public string RefreshIcon { get { return _refreshIcon; } set { _refreshIcon = value; OnPropertyChanged(nameof(RefreshIcon)); } } private string _arrow; public string Arrow { get { return _arrow; } set { _arrow = value; OnPropertyChanged(nameof(Arrow)); } } private string _rightArrow; public string RightArrow { get { return _rightArrow; } set { _rightArrow = value; OnPropertyChanged(nameof(RightArrow)); } } private string _themeIcon; public string ThemeIcon { get { return _themeIcon; } set { _themeIcon = value; OnPropertyChanged(nameof(ThemeIcon)); } } private ObservableCollection<Feed> _feedList; public ObservableCollection<Feed> FeedList { get { return _feedList; } set { _feedList = value; OnPropertyChanged(nameof(FeedList)); } } private Feed _selectedFeed; public Feed SelectedFeed { get { return _selectedFeed; } set { _selectedFeed = value; OnPropertyChanged(nameof(SelectedFeed)); GetFeedItemsFromDatabase(); IsWebBrowserVisible = false; } } private ObservableCollection<FeedItem> _feedItemsList; public ObservableCollection<FeedItem> FeedItemsList { get { return _feedItemsList; } set { _feedItemsList = value; OnPropertyChanged(nameof(FeedItemsList)); } } private FeedItem _selectedFeedItem; public FeedItem SelectedFeedItem { get { return _selectedFeedItem; } set { _selectedFeedItem = value; OnPropertyChanged(nameof(SelectedFeedItem)); GetFeedUrl(); } } private bool _isBackDropVisible; public bool IsBackDropVisible { get { return _isBackDropVisible; } set { _isBackDropVisible = value; OnPropertyChanged(nameof(IsBackDropVisible)); } } private Uri _feedUrl; public Uri FeedUrl { get { return _feedUrl; } set { _feedUrl = value; OnPropertyChanged(nameof(FeedUrl)); } } private bool _isBusy; public bool IsBusy { get { return _isBusy; } set { _isBusy = value; OnPropertyChanged("IsBusy"); } } private bool _isListBusy; public bool IsListBusy { get { return _isListBusy; } set { _isListBusy = value; OnPropertyChanged("IsListBusy"); } } private bool _isWebBrowserVisible; public bool IsWebBrowserVisible { get { return _isWebBrowserVisible; } set { _isWebBrowserVisible = value; OnPropertyChanged(nameof(IsWebBrowserVisible)); } } private string _serverName; public string ServerName { get { return _serverName; } set { _serverName = value; OnPropertyChanged(nameof(ServerName)); } } private string _port; public string Port { get { return _port; } set { _port = value; OnPropertyChanged(nameof(Port)); } } private string _user; public string User { get { return _user; } set { _user = value; OnPropertyChanged(nameof(User)); } } private string _password; public string Password { get { return _password; } set { _password = value; OnPropertyChanged(nameof(Password)); } } private string _database; public string Database { get { return _database; } set { _database = value; OnPropertyChanged(nameof(Database)); } } private ObservableCollection<FeedItem> defaultFeedItems { get; set; } = new ObservableCollection<FeedItem>(); public ICommand RefreshCommand { get; set; } public ICommand ConnectCommand { get; set; } public ICommand ThemeCommand { get; set; } private NpgsqlConnection GetConnectionString() { try { if (string.IsNullOrWhiteSpace(ServerName)) { MessageBox.Show("Server name required!!", "Unicode Reader", MessageBoxButton.OK); return null; } if (string.IsNullOrWhiteSpace(Port)) { MessageBox.Show("Port number required!!", "Unicode Reader", MessageBoxButton.OK); return null; } if (string.IsNullOrWhiteSpace(User)) { MessageBox.Show("Username required!!", "Unicode Reader", MessageBoxButton.OK); return null; } if (string.IsNullOrWhiteSpace(Password)) { MessageBox.Show("Password required!!", "Unicode Reader", MessageBoxButton.OK); return null; } if (string.IsNullOrWhiteSpace(Database)) { MessageBox.Show("Database name required!!", "Unicode Reader", MessageBoxButton.OK); return null; } NpgsqlConnection connection = new NpgsqlConnection(); connection.ConnectionString = $"Server={ServerName};Port={Port};User Id={User};Password={Password};Database={Database};"; connection.Open(); return connection; } catch (Exception) { throw; } } private void GetConnection() { try { NpgsqlCommand cmd = new NpgsqlCommand(); cmd.Connection = GetConnectionString(); if (cmd.Connection != null) { cmd.CommandText = "select id,description,link from channels"; cmd.CommandType = CommandType.Text; NpgsqlDataReader dr = cmd.ExecuteReader(); FeedList = new ObservableCollection<Feed>(); while (dr.Read()) { var feed = new Feed(); feed.Id = (int)dr[0]; feed.Title = dr[1].ToString(); feed.Url = dr[2].ToString(); FeedList.Add(feed); } } else { return; } } catch (Exception e) { throw; } } private void GetFeedItemsFromDatabase() { var worker = new BackgroundWorker(); worker.DoWork += (o, ea) => { defaultFeedItems.Clear(); NpgsqlCommand cmd = new NpgsqlCommand(); cmd.Connection = GetConnectionString(); if (SelectedFeed != null) { if (SelectedFeed.Url != "All feed") cmd.CommandText = "select title,link from articles where channel =" + SelectedFeed.Id; else cmd.CommandText = "select title,link from articles"; } cmd.CommandType = CommandType.Text; NpgsqlDataReader dr = cmd.ExecuteReader(); while (dr.Read()) { var feedItem = new FeedItem() { title = dr[0].ToString(), link = dr[1].ToString() }; defaultFeedItems.Add(feedItem); } Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, new Action(() => { FeedItemsList = new ObservableCollection<FeedItem>(defaultFeedItems); })); }; worker.RunWorkerCompleted += (o, ea) => { IsListBusy = false; }; worker.RunWorkerAsync(); } private void GetFeedItems() { IsListBusy = true; var worker = new BackgroundWorker(); worker.DoWork += (o, ea) => { GetFeedItemsData(); }; worker.RunWorkerCompleted += (o, ea) => { IsListBusy = false; }; worker.RunWorkerAsync(); } private void GetFeedItemsData() { if (SelectedFeed != null) { var itemList = new List<FeedItem>(); if (SelectedFeed.Url != "All feed") { XmlDocument xDoc = new XmlDocument(); xDoc.Load(SelectedFeed.Url); foreach (var item in xDoc.GetElementsByTagName("item")) { var items = JsonConvert.DeserializeObject<Root>(JsonConvert.SerializeObject(item)).Item.ToFeedItem(); itemList.Add(items); } } else { foreach (var feedUrl in FeedList.Where(x => x.Url != "All feed").ToList()) { XmlDocument xDoc = new XmlDocument(); xDoc.Load(feedUrl.Url); foreach (var item in xDoc.GetElementsByTagName("item")) { var items = JsonConvert.DeserializeObject<Root>(JsonConvert.SerializeObject(item)).Item.ToFeedItem(); itemList.Add(items); } } } var uniqueFeeds = itemList.Where(y => !defaultFeedItems.Any(df => df.link == y.link)).ToList(); InsertData(uniqueFeeds, SelectedFeed.Id); Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, new Action(() => { foreach (var item in uniqueFeeds) { defaultFeedItems.Add(item); } FeedItemsList = new ObservableCollection<FeedItem>(itemList); })); } } private void InsertData(List<FeedItem> feedItems, int id) { NpgsqlCommand cmd = new NpgsqlCommand(); cmd.Connection = GetConnectionString(); foreach (var item in feedItems) { cmd = new NpgsqlCommand(); cmd.Connection = GetConnectionString(); cmd.CommandText = "Insert into articles(title,description,content,link,is_read,timestamp,channel) values(@title,@description,@content,@link,@is_read,@timestamp,@channel)"; cmd.CommandType = CommandType.Text; cmd.Parameters.Add(new NpgsqlParameter("@title", item.title)); cmd.Parameters.Add(new NpgsqlParameter("@description", item.description)); cmd.Parameters.Add(new NpgsqlParameter("@content", item.ContentEncoded)); cmd.Parameters.Add(new NpgsqlParameter("@link", item.link)); cmd.Parameters.Add(new NpgsqlParameter("@is_read", false)); cmd.Parameters.Add(new NpgsqlParameter("@timestamp", Convert.ToDateTime(item.pubDate))); cmd.Parameters.Add(new NpgsqlParameter("@channel", id)); cmd.ExecuteNonQuery(); cmd.Dispose(); } } private void GetFeedUrl() { IsWebBrowserVisible = true; FeedUrl = null; IsBusy = true; var worker = new BackgroundWorker(); worker.DoWork += (o, ea) => { Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, new Action(() => { if (SelectedFeedItem != null) { FeedUrl = new Uri(SelectedFeedItem.link); } })); }; worker.RunWorkerCompleted += (o, ea) => { IsBusy = false; }; worker.RunWorkerAsync(); } private void ChangeTheme(Grid grid) { var color = (Brush)(new BrushConverter().ConvertFrom("#20262F")); var bg = grid.Background as Brush; if (grid.Background.ToString() == color.ToString()) { grid.Background = Brushes.White; Foreground = Brushes.Black; HumbergerIcon = "pack://application:,,,/Icons/humbergerBlack.png"; RefreshIcon = "pack://application:,,,/Icons/refreshblack.png"; ThemeIcon = "pack://application:,,,/Icons/themeicon.png"; Arrow = "pack://application:,,,/Icons/navigateblack.png"; RightArrow = "pack://application:,,,/Icons/rightarrowblack.png"; } else { grid.Background = (Brush)(new BrushConverter().ConvertFrom("#20262F")); Foreground = Brushes.White; HumbergerIcon = "pack://application:,,,/Icons/humbergerwhite.png"; RefreshIcon = "pack://application:,,,/Icons/refreshwhite.png"; ThemeIcon = "pack://application:,,,/Icons/themeiconwhite.png"; Arrow = "pack://application:,,,/Icons/navigatewhite.png"; RightArrow = "pack://application:,,,/Icons/rightarrowwhite.png"; } } public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged([CallerMemberName] string name = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name)); } } public static class Utility { public static FeedItem ToFeedItem(this Item item) { return new FeedItem() { link = item.link, title = item.title, pubDate = item.pubDate, ContentEncoded = item.ContentEncoded.CdataSection, description = item.description.CdataSection }; } } public class Feed { public int Id { get; set; } public string Title { get; set; } public string Url { get; set; } } public class FeedItem { public string title { get; set; } public string link { get; set; } public string pubDate { get; set; } public string description { get; set; } public string ContentEncoded { get; set; } } public class Description { [JsonProperty("#cdata-section")] public string CdataSection { get; set; } } public class ContentEncoded { [JsonProperty("#cdata-section")] public string CdataSection { get; set; } } public class Item { public string title { get; set; } public string link { get; set; } public string pubDate { get; set; } public Description description { get; set; } [JsonProperty("content:encoded")] public ContentEncoded ContentEncoded { get; set; } } public class Root { public Item Item { get; set; } } }
35.905769
187
0.523218
[ "MIT" ]
Embarcadero/ComparisonResearch
unicode-reader/wpf/UnicodeReader/UnicodeReader/MainWindowViewModel.cs
18,673
C#
using System.Data.Common; using Abp.Zero.EntityFramework; using PlugInDemo.Authorization.Roles; using PlugInDemo.MultiTenancy; using PlugInDemo.Users; namespace PlugInDemo.EntityFramework { public class PlugInDemoDbContext : AbpZeroDbContext<Tenant, Role, User> { //TODO: Define an IDbSet for your Entities... /* NOTE: * Setting "Default" to base class helps us when working migration commands on Package Manager Console. * But it may cause problems when working Migrate.exe of EF. If you will apply migrations on command line, do not * pass connection string name to base classes. ABP works either way. */ public PlugInDemoDbContext() : base("Default") { } /* NOTE: * This constructor is used by ABP to pass connection string defined in PlugInDemoDataModule.PreInitialize. * Notice that, actually you will not directly create an instance of PlugInDemoDbContext since ABP automatically handles it. */ public PlugInDemoDbContext(string nameOrConnectionString) : base(nameOrConnectionString) { } //This constructor is used in tests public PlugInDemoDbContext(DbConnection connection) : base(connection, true) { } } }
32.119048
134
0.659007
[ "MIT" ]
Jimmey-Jiang/aspnetboilerplate-samples
PlugInDemo/PlugInDemo.EntityFramework/EntityFramework/PlugInDemoDbContext.cs
1,351
C#
// <auto-generated /> using System; using ConsoleApp7; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace ConsoleApp7.Migrations { [DbContext(typeof(BloggingContext))] partial class BloggingContextModelSnapshot : ModelSnapshot { protected override void BuildModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "2.1.2-rtm-30932") .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("ConsoleApp7.Blog", b => { b.Property<int>("BlogId") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Url"); b.HasKey("BlogId"); b.ToTable("Blogs"); }); modelBuilder.Entity("ConsoleApp7.BlogLL", b => { b.Property<int>("FlogLLId") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Url"); b.HasKey("FlogLLId"); b.ToTable("BlogsLL"); b.HasData( new { FlogLLId = 1, Url = "http://blogs.msdn.com/adonet" } ); }); modelBuilder.Entity("ConsoleApp7.BlogPBF", b => { b.Property<int>("BlogId") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Url"); b.HasKey("BlogId"); b.ToTable("BlogsPBF"); }); modelBuilder.Entity("ConsoleApp7.BlogTPH", b => { b.Property<int>("BlogId") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Url"); b.HasKey("BlogId"); b.ToTable("BlogsTPH"); }); modelBuilder.Entity("ConsoleApp7.Post", b => { b.Property<int>("PostId") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("BlogId"); b.Property<string>("Content"); b.Property<string>("Discriminator") .IsRequired(); b.Property<string>("Title"); b.HasKey("PostId"); b.HasIndex("BlogId"); b.ToTable("Posts"); b.HasDiscriminator<string>("Discriminator").HasValue("Post"); }); modelBuilder.Entity("ConsoleApp7.PostLL", b => { b.Property<int>("FostLLId") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Content"); b.Property<int>("FlogLLId"); b.Property<string>("PostType") .IsRequired(); b.Property<string>("Title"); b.HasKey("FostLLId"); b.HasIndex("FlogLLId"); b.ToTable("PostsLL"); b.HasDiscriminator<string>("PostType").HasValue("Moe"); b.HasData( new { FostLLId = 1, Content = "I wrote an app using EF Core!", FlogLLId = 1, Title = "Hello World" } ); }); modelBuilder.Entity("ConsoleApp7.PostPBF", b => { b.Property<int>("PostId") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("BlogId"); b.Property<string>("Content"); b.Property<string>("Discriminator") .IsRequired(); b.Property<string>("Title"); b.HasKey("PostId"); b.HasIndex("BlogId"); b.ToTable("PostsPBF"); b.HasDiscriminator<string>("Discriminator").HasValue("PostPBF"); }); modelBuilder.Entity("ConsoleApp7.PostTPH", b => { b.Property<int>("PostId") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("BlogId"); b.Property<string>("Content"); b.Property<string>("Discriminator") .IsRequired(); b.Property<string>("Title"); b.Property<int>("WidgetId"); b.HasKey("PostId"); b.HasIndex("BlogId"); b.HasIndex("WidgetId"); b.ToTable("PostsTPH"); b.HasDiscriminator<string>("Discriminator").HasValue("PostTPH"); }); modelBuilder.Entity("ConsoleApp7.WidgetTPH", b => { b.Property<int>("WidgetId") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.HasKey("WidgetId"); b.ToTable("WidgetTPH"); }); modelBuilder.Entity("ConsoleApp7.DumbAsAPost", b => { b.HasBaseType("ConsoleApp7.Post"); b.Property<bool>("Stupid"); b.ToTable("DumbAsAPost"); b.HasDiscriminator().HasValue("dumb"); }); modelBuilder.Entity("ConsoleApp7.VideoPost", b => { b.HasBaseType("ConsoleApp7.Post"); b.Property<DateTime>("ReleaseDate"); b.Property<string>("VideoTitle"); b.ToTable("VideoPost"); b.HasDiscriminator().HasValue("video"); }); modelBuilder.Entity("ConsoleApp7.DumbAsAPostLL", b => { b.HasBaseType("ConsoleApp7.PostLL"); b.Property<bool>("Stupid"); b.ToTable("DumbAsAPostLL"); b.HasDiscriminator().HasValue("Curly"); b.HasData( new { FostLLId = 3, Content = "This is as dumb as a post", FlogLLId = 1, Title = "Hello World, The Silent Picture", Stupid = true } ); }); modelBuilder.Entity("ConsoleApp7.VideoPostLL", b => { b.HasBaseType("ConsoleApp7.PostLL"); b.Property<DateTime>("ReleaseDate"); b.Property<string>("VideoTitle"); b.ToTable("VideoPostLL"); b.HasDiscriminator().HasValue("Larry"); b.HasData( new { FostLLId = 2, Content = "Lareum ipsum, alpha, beta, crapper...", FlogLLId = 1, Title = "Hello World, The Movie", ReleaseDate = new DateTime(2019, 8, 14, 0, 0, 0, 0, DateTimeKind.Local), VideoTitle = "this is the Video Title" } ); }); modelBuilder.Entity("ConsoleApp7.DumbAsAPostPBF", b => { b.HasBaseType("ConsoleApp7.PostPBF"); b.Property<bool>("Stupid"); b.ToTable("DumbAsAPostPBF"); b.HasDiscriminator().HasValue("dumb"); }); modelBuilder.Entity("ConsoleApp7.VideoPostPBF", b => { b.HasBaseType("ConsoleApp7.PostPBF"); b.Property<DateTime>("ReleaseDate"); b.Property<string>("VideoTitle"); b.ToTable("VideoPostPBF"); b.HasDiscriminator().HasValue("video"); }); modelBuilder.Entity("ConsoleApp7.DumbAsAPostTPH", b => { b.HasBaseType("ConsoleApp7.PostTPH"); b.Property<bool>("Stupid"); b.ToTable("DumbAsAPostTPH"); b.HasDiscriminator().HasValue("DumbAsAPostTPH"); }); modelBuilder.Entity("ConsoleApp7.VideoPostTPH", b => { b.HasBaseType("ConsoleApp7.PostTPH"); b.Property<DateTime>("ReleaseDate"); b.Property<string>("VideoTitle"); b.ToTable("VideoPostTPH"); b.HasDiscriminator().HasValue("VideoPostTPH"); }); modelBuilder.Entity("ConsoleApp7.Post", b => { b.HasOne("ConsoleApp7.Blog", "Blog") .WithMany("Posts") .HasForeignKey("BlogId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("ConsoleApp7.PostLL", b => { b.HasOne("ConsoleApp7.BlogLL", "Flog") .WithMany("Fosts") .HasForeignKey("FlogLLId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("ConsoleApp7.PostPBF", b => { b.HasOne("ConsoleApp7.BlogPBF", "Blog") .WithMany("posts") .HasForeignKey("BlogId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("ConsoleApp7.PostTPH", b => { b.HasOne("ConsoleApp7.BlogTPH", "Blog") .WithMany("Posts") .HasForeignKey("BlogId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("ConsoleApp7.WidgetTPH", "Foobar") .WithMany() .HasForeignKey("WidgetId") .OnDelete(DeleteBehavior.Cascade); }); #pragma warning restore 612, 618 } } }
33.682493
256
0.472293
[ "MIT" ]
jrbirdmanFA/EFCoreDocsApp-SQLSERVER
ConsoleApp7/Migrations/BloggingContextModelSnapshot.cs
11,353
C#
// *********************************************************************** // Assembly : ACBr.Net.CTe // Author : RFTD // Created : 10-14-2016 // // Last Modified By : RFTD // Last Modified On : 10-14-2016 // *********************************************************************** // <copyright file="CTeTomador.cs" company="ACBr.Net"> // The MIT License (MIT) // Copyright (c) 2016 Grupo ACBr.Net // // 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> // <summary></summary> // *********************************************************************** using ACBr.Net.DFe.Core.Attributes; namespace ACBr.Net.CTe { public enum CTeTomador { [DFeEnum("0")] Remetente, [DFeEnum("1")] Expedidor, [DFeEnum("2")] Recebedor, [DFeEnum("3")] Destinatario, [DFeEnum("4")] Outros } }
35.528302
83
0.619225
[ "MIT" ]
ACBrNet/ACBr.Net.CTe
src/ACBr.Net.CTe.Shared/CTeTomador.cs
1,883
C#
using System.Text.Json.Serialization; namespace Essensoft.AspNetCore.Payment.Alipay.Domain { /// <summary> /// AlipayCommerceFixTaskQueryModel Data Structure. /// </summary> public class AlipayCommerceFixTaskQueryModel : AlipayObject { /// <summary> /// 工单唯一id。 获取途径:创建工单的返回结果id,或者通知消息中的工单id进行查询。 /// </summary> [JsonPropertyName("task_id")] public long TaskId { get; set; } } }
26.176471
63
0.644944
[ "MIT" ]
LuohuaRain/payment
src/Essensoft.AspNetCore.Payment.Alipay/Domain/AlipayCommerceFixTaskQueryModel.cs
517
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="IAppLifecycleBehavior.cs" company="Kephas Software SRL"> // Copyright (c) Kephas Software SRL. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // </copyright> // <summary> // Declares the IAppLifecycleBehavior interface. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace Kephas.Application { using System.Threading; using System.Threading.Tasks; using Kephas.Operations; using Kephas.Services; /// <summary> /// Singleton service contract for application lifecycle behavior. /// </summary> /// <remarks> /// An application lifecycle behavior intercepts the initialization and finalization of the application /// and reacts to them. /// </remarks> [SingletonAppServiceContract(AllowMultiple = true)] public interface IAppLifecycleBehavior { /// <summary> /// Interceptor called before the application starts its asynchronous initialization. /// </summary> /// <remarks> /// To interrupt the application initialization, simply throw an appropriate exception. /// </remarks> /// <param name="appContext">Context for the application.</param> /// <param name="cancellationToken">Optional. The cancellation token.</param> /// <returns> /// An asynchronous result yielding the operation result. /// </returns> Task<IOperationResult> BeforeAppInitializeAsync( IContext appContext, CancellationToken cancellationToken = default); /// <summary> /// Interceptor called after the application completes its asynchronous initialization. /// </summary> /// <param name="appContext">Context for the application.</param> /// <param name="cancellationToken">Optional. The cancellation token.</param> /// <returns> /// An asynchronous result yielding the operation result. /// </returns> Task<IOperationResult> AfterAppInitializeAsync( IContext appContext, CancellationToken cancellationToken = default); /// <summary> /// Interceptor called before the application starts its asynchronous finalization. /// </summary> /// <remarks> /// To interrupt finalization, simply throw any appropriate exception. /// Caution! Interrupting the finalization may cause the application to remain in an undefined state. /// </remarks> /// <param name="appContext">Context for the application.</param> /// <param name="cancellationToken">Optional. The cancellation token.</param> /// <returns> /// An asynchronous result yielding the operation result. /// </returns> Task<IOperationResult> BeforeAppFinalizeAsync( IContext appContext, CancellationToken cancellationToken = default); /// <summary> /// Interceptor called after the application completes its asynchronous finalization. /// </summary> /// <param name="appContext">Context for the application.</param> /// <param name="cancellationToken">Optional. The cancellation token.</param> /// <returns> /// An asynchronous result yielding the operation result. /// </returns> Task<IOperationResult> AfterAppFinalizeAsync(IContext appContext, CancellationToken cancellationToken = default); } }
45.231707
121
0.61553
[ "MIT" ]
snakefoot/kephas
src/Kephas.Core/Application/IAppLifecycleBehavior.cs
3,711
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; using tvn.cosine.exceptions; using tvn.cosine.ai.logic.propositional.inference; using tvn.cosine.ai.logic.propositional.kb; using tvn.cosine.ai.logic.propositional.parsing; using tvn.cosine.ai.logic.propositional.parsing.ast; namespace tvn_cosine.ai.test.unit.logic.propositional.inference { [TestClass] public class PLFCEntailsTest { private PLParser parser; private PLFCEntails plfce; [TestInitialize] public void setUp() { parser = new PLParser(); plfce = new PLFCEntails(); } [TestMethod] public void testAIMAExample() { KnowledgeBase kb = new KnowledgeBase(); kb.tell("P => Q"); kb.tell("L & M => P"); kb.tell("B & L => M"); kb.tell("A & P => L"); kb.tell("A & B => L"); kb.tell("A"); kb.tell("B"); PropositionSymbol q = (PropositionSymbol)parser.parse("Q"); Assert.AreEqual(true, plfce.plfcEntails(kb, q)); } [TestMethod] [ExpectedException(typeof(IllegalArgumentException))] public void testKBWithNonDefiniteClauses() { KnowledgeBase kb = new KnowledgeBase(); kb.tell("P => Q"); kb.tell("L & M => P"); kb.tell("B & L => M"); kb.tell("~A & P => L"); // Not a definite clause kb.tell("A & B => L"); kb.tell("A"); kb.tell("B"); PropositionSymbol q = (PropositionSymbol)parser.parse("Q"); Assert.AreEqual(true, plfce.plfcEntails(kb, q)); } } }
29.431034
71
0.543644
[ "Apache-2.0" ]
itoledo/Birdie.Tesseract
tvn-cosine.ai/tvn-cosine.ai.test/unit/logic/propositional/inference/PLFCEntailsTest.cs
1,709
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using MySql.Data.MySqlClient; namespace Swimming_Pool_Management_System { public partial class Pool_Maintenance_List : Form { public Pool_Maintenance_List() { InitializeComponent(); } private void label3_Click(object sender, EventArgs e) { Application.Exit(); } private void pictureBox2_Click(object sender, EventArgs e) { if (labelUser.Text == "Admin") { this.Hide(); Dashboard dashboard = new Dashboard(); dashboard.Show(); } else if (labelUser.Text == "Sailfish Team Leader") { this.Hide(); Sailfish_Dashboard sailfishDash = new Sailfish_Dashboard(); sailfishDash.Show(); } else if (labelUser.Text == "Grenfin Team Leader") { this.Hide(); Grenfin_Dashboard grenfinDash = new Grenfin_Dashboard(); grenfinDash.Show(); } else if (labelUser.Text == "Dolphin Team Leader") { this.Hide(); Dolphin_Dashboard dolphinDash = new Dolphin_Dashboard(); dolphinDash.Show(); } else if (labelUser.Text == "Grenada Team Leader") { this.Hide(); Grenada_Team_Dashboard grenadaDash = new Grenada_Team_Dashboard(); grenadaDash.Show(); } } POOLMAINTENANCE poolMain = new POOLMAINTENANCE(); private void Pool_Maintenance_List_Load(object sender, EventArgs e) { //populating the datagridview with swimmer's data MySqlCommand command = new MySqlCommand("SELECT * FROM `pool_maintenance`"); dataGridView1.ReadOnly = true; dataGridView1.RowTemplate.Height = 30; dataGridView1.DataSource = poolMain.getPoolMains(command); dataGridView1.AllowUserToAddRows = false; labelUser.Text = GLOBAL.userType; } private void buttonRefresh_Click(object sender, EventArgs e) { //populating the datagridview with swimmer's data MySqlCommand command = new MySqlCommand("SELECT * FROM `pool_maintenance`"); dataGridView1.ReadOnly = true; dataGridView1.RowTemplate.Height = 30; dataGridView1.DataSource = poolMain.getPoolMains(command); dataGridView1.AllowUserToAddRows = false; } private void buttonAdd_Click(object sender, EventArgs e) { if (labelUser.Text == "Admin") { this.Hide(); Pool_Maintenance poolMain = new Pool_Maintenance(); poolMain.Show(); } } } }
32.536842
88
0.566807
[ "MIT" ]
smcqueen-95/swimming-pool-mangement-system
Pool Maintenance List.cs
3,093
C#
using System; using System.Collections.Concurrent; using System.Linq; namespace Xapu.Extensions.Selects { internal static class QueryableSelectorBag { private static readonly ConcurrentDictionary<Type, object> Instances = new ConcurrentDictionary<Type, object>(); public static IQueryableSelector GetForQueryableType(Type type) { if (!Instances.ContainsKey(type)) Instances[type] = CreateForQueryableType(type); return (IQueryableSelector)Instances[type]; } public static IQueryableSelector<TElement> GetForElementType<TElement>(IQueryable<TElement> source) { var type = source.GetType(); if (!Instances.ContainsKey(type)) Instances[type] = new QueryableSelector<TElement>(); return (IQueryableSelector<TElement>)Instances[type]; } private static IQueryableSelector CreateForQueryableType(Type sourceType) { var selectorType = typeof(QueryableSelector<>); var elementType = sourceType.GetCollectionElementType(); var instanceType = selectorType.MakeGenericType(elementType); var instance = Activator.CreateInstance(instanceType); return (IQueryableSelector)instance; } } }
32.365854
120
0.664657
[ "Apache-2.0" ]
valtermro/Xapu.Extensions.Selects
src/Xapu.Extensions.Selects/Core/Bags/QueryableSelectorBag.cs
1,329
C#
// ----------------------------------------------------------------------- // <copyright file="MockAuthenticationFactory.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // ----------------------------------------------------------------------- namespace Microsoft.Store.PartnerCenter.PowerShell.Tests.Factories { using System; using System.Security; using Authentication; using Common; using IdentityModel.Clients.ActiveDirectory; using PowerShell.Factories; /// <summary> /// Factory that mocks authenticaton operations. /// </summary> public class MockAuthenticationFactory : IAuthenticationFactory { public PartnerContext Authenticate(string applicationId, EnvironmentName environment, string username, SecureString password, string tenantId) { throw new NotImplementedException(); } /// <summary> /// Authenticates the user using the specified parameters. /// </summary> /// <param name="context">The partner's execution context.</param> /// <param name="password">The password used to authenicate the user. This value can be null.</param> /// <returns>The result from the authentication request.</returns> /// <exception cref="ArgumentNullException"> /// <paramref name="context"/> is null. /// </exception> public AuthenticationResult Authenticate(PartnerContext context, SecureString password) { context.AssertNotNull(nameof(context)); throw new NotImplementedException(); } } }
38.44186
150
0.610405
[ "MIT" ]
cblackuk/Partner-Center-PowerShell
test/PowerShell.Tests/Factories/MockAuthenticationFactory.cs
1,655
C#
namespace ModuleZeroSampleProject.Web.Models.Account { public class LoginFormViewModel { public string ReturnUrl { get; set; } public bool IsMultiTenancyEnabled { get; set; } } }
23.111111
55
0.677885
[ "MIT" ]
FadiAlalloush/questions-answers
src/ModuleZeroSampleProject.Web/Models/Account/LoginFormViewModel.cs
210
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="TimeStamp.cs" company="Brandon Seydel"> // N/A // </copyright> // -------------------------------------------------------------------------------------------------------------------- using Newtonsoft.Json; using System; namespace MailChimp.Net.Models { /// <summary> /// The TimeStamp. /// </summary> public class TimeStamp { /// <summary> /// Gets or sets the Timestamp. /// </summary> [JsonProperty("timestamp")] public DateTime Timestamp { get; set; } } }
24.814815
119
0.364179
[ "MIT" ]
Argenteneo/MailChimp.Net
MailChimp.Net/Models/TimeStamp.cs
670
C#
// Copyright (c) 2020 Yann Crumeyrolle. All rights reserved. // Licensed under the MIT license. See LICENSE in the project root for license information. using System; using System.Buffers; using System.Buffers.Binary; using System.Diagnostics; using System.Numerics; using System.Runtime.InteropServices; namespace JsonWebToken.Cryptography { // PBKDF2 is defined in NIST SP800-132, Sec. 5.3. // http://csrc.nist.gov/publications/nistpubs/800-132/nist-sp800-132.pdf internal static class Pbkdf2 { public static void DeriveKey(byte[] password, ReadOnlySpan<byte> salt, Sha2 prf, uint iterationCount, Span<byte> destination) { Debug.Assert(password != null); Debug.Assert(salt != null); Debug.Assert(destination.Length > 0); int numBytesWritten = 0; int numBytesRemaining = destination.Length; Span<byte> saltWithBlockIndex = stackalloc byte[checked(salt.Length + sizeof(uint))]; salt.CopyTo(saltWithBlockIndex); Span<byte> hmacKey = stackalloc byte[prf.BlockSize * 2]; var hashAlgorithm = new Hmac(prf, password, hmacKey); int wSize = prf.GetWorkingSetSize(int.MaxValue); int blockSize = hashAlgorithm.BlockSize; byte[]? arrayToReturn = null; try { Span<byte> W = wSize > Constants.MaxStackallocBytes ? (arrayToReturn = ArrayPool<byte>.Shared.Rent(wSize)) : stackalloc byte[wSize]; Span<byte> currentBlock = stackalloc byte[hashAlgorithm.HashSize]; Span<byte> iterationBlock = stackalloc byte[hashAlgorithm.HashSize]; Span<byte> blockIndexDestination = saltWithBlockIndex.Slice(saltWithBlockIndex.Length - sizeof(uint)); for (uint blockIndex = 1; numBytesRemaining > 0; blockIndex++) { BinaryPrimitives.WriteUInt32BigEndian(blockIndexDestination, blockIndex); hashAlgorithm.ComputeHash(saltWithBlockIndex, currentBlock, W); // U_1 currentBlock.CopyTo(iterationBlock); for (int iter = 1; iter < iterationCount; iter++) { hashAlgorithm.ComputeHash(currentBlock, currentBlock, W); Xor(src: currentBlock, dest: iterationBlock); } int numBytesToCopy = Math.Min(numBytesRemaining, iterationBlock.Length); iterationBlock.Slice(0, numBytesToCopy).CopyTo(destination.Slice(numBytesWritten)); numBytesWritten += numBytesToCopy; numBytesRemaining -= numBytesToCopy; } } finally { if (arrayToReturn != null) { ArrayPool<byte>.Shared.Return(arrayToReturn); } } } private static unsafe void Xor(Span<byte> src, Span<byte> dest) { fixed (byte* srcPtr = &MemoryMarshal.GetReference(src)) fixed (byte* destPtr = &MemoryMarshal.GetReference(dest)) { byte* srcCurrent = srcPtr; byte* destCurrent = destPtr; byte* srcEnd = srcPtr + src.Length; if (srcEnd - srcCurrent >= sizeof(int)) { // align to sizeof(int) while (((ulong)srcCurrent & (sizeof(int) - 1)) != 0) { *destCurrent++ ^= *srcCurrent++; } if (Vector.IsHardwareAccelerated && ((Vector<byte>.Count & (sizeof(int) - 1)) == 0) && (srcEnd - srcCurrent) >= Vector<byte>.Count) { // align to Vector<byte>.Count while ((ulong)srcCurrent % (uint)Vector<byte>.Count != 0) { Debug.Assert(srcCurrent < srcEnd); *(int*)destCurrent ^= *(int*)srcCurrent; srcCurrent += sizeof(int); destCurrent += sizeof(int); } if (srcEnd - srcCurrent >= Vector<byte>.Count) { do { *(Vector<byte>*)destCurrent ^= *(Vector<byte>*)srcCurrent; srcCurrent += Vector<byte>.Count; destCurrent += Vector<byte>.Count; } while (srcEnd - srcCurrent >= Vector<byte>.Count); } } // process remaining data (or all, if couldn't use SIMD) 4 bytes at a time. while (srcEnd - srcCurrent >= sizeof(int)) { *(int*)destCurrent ^= *(int*)srcCurrent; srcCurrent += sizeof(int); destCurrent += sizeof(int); } } // do any remaining data a byte at a time. while (srcCurrent != srcEnd) { *destCurrent++ ^= *srcCurrent++; } } } } }
42.289063
151
0.49843
[ "MIT" ]
signature-opensource/Jwt
src/JsonWebToken/Cryptography/Pbkdf2.cs
5,415
C#
using Esfa.Recruit.Provider.Web.Configuration.Routing; using Esfa.Recruit.Provider.Web.RouteModel; using Microsoft.AspNetCore.Mvc; using System.Threading.Tasks; using Esfa.Recruit.Provider.Web.Configuration; using Esfa.Recruit.Provider.Web.Extensions; using Esfa.Recruit.Provider.Web.Orchestrators.Part2; using Esfa.Recruit.Provider.Web.ViewModels.Part2.ProviderContactDetails; using Esfa.Recruit.Shared.Web.Extensions; using Microsoft.AspNetCore.Authorization; namespace Esfa.Recruit.Provider.Web.Controllers.Part2 { [Route(RoutePaths.AccountVacancyRoutePath)] [Authorize(Policy = nameof(PolicyNames.HasContributorOrAbovePermission))] public class ProviderContactDetailsController : Controller { private readonly ProviderContactDetailsOrchestrator _orchestrator; public ProviderContactDetailsController(ProviderContactDetailsOrchestrator orchestrator) { _orchestrator = orchestrator; } [HttpGet("provider-contact-details", Name = RouteNames.ProviderContactDetails_Get)] public async Task<IActionResult> ProviderContactDetails(VacancyRouteModel vrm) { var vm = await _orchestrator.GetProviderContactDetailsViewModelAsync(vrm); return View(vm); } [HttpPost("provider-contact-details", Name = RouteNames.ProviderContactDetails_Post)] public async Task<IActionResult> ProviderContactDetails(ProviderContactDetailsEditModel m) { var response = await _orchestrator.PostProviderContactDetailsEditModelAsync(m, User.ToVacancyUser()); if (!response.Success) { response.AddErrorsToModelState(ModelState); } if (!ModelState.IsValid) { var vm = await _orchestrator.GetProviderContactDetailsViewModelAsync(m); return View(vm); } return RedirectToRoute(RouteNames.Vacancy_Preview_Get); } } }
39.098039
113
0.713139
[ "MIT" ]
SkillsFundingAgency/das-recru
src/Provider/Provider.Web/Controllers/Part2/ProviderContactDetailsController.cs
1,996
C#
using UnityEngine; namespace DetectionService { public struct DetectionRay { public readonly Ray Ray; public readonly Vector3 StartPoint; public readonly Vector3 Direction; public readonly Vector3 EndPoint; public DetectionRay(Ray ray, Vector3 startPoint, Vector3 endPoint, Vector3 direction) { StartPoint = startPoint; EndPoint = endPoint; Direction = direction; Ray = ray; } } }
24.95
93
0.61523
[ "MIT" ]
muveso/Unity-Detection-Sensor
UnitySensorSystem/Assets/DetectionService/Ray.cs
501
C#
using System; using System.Windows.Data; using System.Windows.Markup; namespace FtpClient.Converters { public class ConnectButtonStatusConverter : IMultiValueConverter { public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture) { bool v1 = (bool)values[0]; bool v2 = (bool)values[1]; return !(v1 || v2); } public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } public sealed class ConnectButtonStatusConverterExtension : MarkupExtension { public override object ProvideValue(IServiceProvider serviceProvider) { return new ConnectButtonStatusConverter(); } } }
27.8125
129
0.658427
[ "MIT" ]
Norgerman/FtpClient
FtpClient/Converters/ConnectButtonStatusConverter.cs
892
C#
namespace Microsoft.ComponentDetection.Contracts { public interface IDetectorDependencies { ILogger Logger { get; set; } IComponentStreamEnumerableFactory ComponentStreamEnumerableFactory { get; set; } IPathUtilityService PathUtilityService { get; set; } ICommandLineInvocationService CommandLineInvocationService { get; set; } IFileUtilityService FileUtilityService { get; set; } IObservableDirectoryWalkerFactory DirectoryWalkerFactory { get; set; } IDockerService DockerService { get; set; } IEnvironmentVariableService EnvironmentVariableService { get; set; } } }
30
88
0.716667
[ "MIT" ]
ByAgenT/component-detection
src/Microsoft.ComponentDetection.Contracts/IDetectorDependencies.cs
662
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.ML.Runtime; using Microsoft.ML.Runtime.CommandLine; using Microsoft.ML.Runtime.Data; using Microsoft.ML.Runtime.EntryPoints; using Microsoft.ML.Runtime.Internal.Utilities; using Microsoft.ML.Runtime.Model; using Microsoft.ML.Transforms; using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; [assembly: LoadableClass(typeof(MultiClassClassifierEvaluator), typeof(MultiClassClassifierEvaluator), typeof(MultiClassClassifierEvaluator.Arguments), typeof(SignatureEvaluator), "Multi-Class Classifier Evaluator", MultiClassClassifierEvaluator.LoadName, "MultiClassClassifier", "MultiClass")] [assembly: LoadableClass(typeof(MultiClassMamlEvaluator), typeof(MultiClassMamlEvaluator), typeof(MultiClassMamlEvaluator.Arguments), typeof(SignatureMamlEvaluator), "Multi-Class Classifier Evaluator", MultiClassClassifierEvaluator.LoadName, "MultiClassClassifier", "MultiClass")] // This is for deserialization of the per-instance transform. [assembly: LoadableClass(typeof(MultiClassPerInstanceEvaluator), null, typeof(SignatureLoadRowMapper), "", MultiClassPerInstanceEvaluator.LoaderSignature)] namespace Microsoft.ML.Runtime.Data { public sealed class MultiClassClassifierEvaluator : RowToRowEvaluatorBase<MultiClassClassifierEvaluator.Aggregator> { public sealed class Arguments { [Argument(ArgumentType.AtMostOnce, HelpText = "Output top K accuracy", ShortName = "topkacc")] public int? OutputTopKAcc; [Argument(ArgumentType.AtMostOnce, HelpText = "Use the textual class label names in the report, if available", ShortName = "n")] public bool Names = true; } public const string AccuracyMicro = "Accuracy(micro-avg)"; public const string AccuracyMacro = "Accuracy(macro-avg)"; public const string TopKAccuracy = "Top K accuracy"; public const string PerClassLogLoss = "Per class log-loss"; public const string LogLoss = "Log-loss"; public const string LogLossReduction = "Log-loss reduction"; public enum Metrics { [EnumValueDisplay(MultiClassClassifierEvaluator.AccuracyMicro)] AccuracyMicro, [EnumValueDisplay(MultiClassClassifierEvaluator.AccuracyMacro)] AccuracyMacro, [EnumValueDisplay(MultiClassClassifierEvaluator.LogLoss)] LogLoss, [EnumValueDisplay(MultiClassClassifierEvaluator.LogLossReduction)] LogLossReduction, } public const string LoadName = "MultiClassClassifierEvaluator"; private readonly int? _outputTopKAcc; private readonly bool _names; public MultiClassClassifierEvaluator(IHostEnvironment env, Arguments args) : base(env, LoadName) { Host.AssertValue(args, "args"); Host.CheckUserArg(args.OutputTopKAcc == null || args.OutputTopKAcc > 0, nameof(args.OutputTopKAcc)); _outputTopKAcc = args.OutputTopKAcc; _names = args.Names; } protected override void CheckScoreAndLabelTypes(RoleMappedSchema schema) { var score = schema.GetUniqueColumn(MetadataUtils.Const.ScoreValueKind.Score); var t = score.Type; if (t.VectorSize < 2 || t.ItemType != NumberType.Float) throw Host.Except("Score column '{0}' has type {1} but must be a vector of two or more items of type R4", score.Name, t); Host.Check(schema.Label != null, "Could not find the label column"); t = schema.Label.Type; if (t != NumberType.Float && t.KeyCount <= 0) throw Host.Except("Label column '{0}' has type {1} but must be a float or a known-cardinality key", schema.Label.Name, t); } protected override Aggregator GetAggregatorCore(RoleMappedSchema schema, string stratName) { var score = schema.GetUniqueColumn(MetadataUtils.Const.ScoreValueKind.Score); Host.Assert(score.Type.VectorSize > 0); int numClasses = score.Type.VectorSize; var classNames = GetClassNames(schema); return new Aggregator(Host, classNames, numClasses, schema.Weight != null, _outputTopKAcc, stratName); } private ReadOnlyMemory<char>[] GetClassNames(RoleMappedSchema schema) { ReadOnlyMemory<char>[] names; // Get the label names from the score column if they exist, or use the default names. var scoreInfo = schema.GetUniqueColumn(MetadataUtils.Const.ScoreValueKind.Score); var mdType = schema.Schema.GetMetadataTypeOrNull(MetadataUtils.Kinds.SlotNames, scoreInfo.Index); var labelNames = default(VBuffer<ReadOnlyMemory<char>>); if (mdType != null && mdType.IsKnownSizeVector && mdType.ItemType.IsText) { schema.Schema.GetMetadata(MetadataUtils.Kinds.SlotNames, scoreInfo.Index, ref labelNames); names = new ReadOnlyMemory<char>[labelNames.Length]; labelNames.CopyTo(names); } else { var score = schema.GetColumns(MetadataUtils.Const.ScoreValueKind.Score); Host.Assert(Utils.Size(score) == 1); Host.Assert(score[0].Type.VectorSize > 0); int numClasses = score[0].Type.VectorSize; names = Enumerable.Range(0, numClasses).Select(i => i.ToString().AsMemory()).ToArray(); } return names; } protected override IRowMapper CreatePerInstanceRowMapper(RoleMappedSchema schema) { Host.CheckParam(schema.Label != null, nameof(schema), "Schema must contain a label column"); var scoreInfo = schema.GetUniqueColumn(MetadataUtils.Const.ScoreValueKind.Score); int numClasses = scoreInfo.Type.VectorSize; return new MultiClassPerInstanceEvaluator(Host, schema.Schema, scoreInfo, schema.Label.Name); } public override IEnumerable<MetricColumn> GetOverallMetricColumns() { yield return new MetricColumn("AccuracyMicro", AccuracyMicro); yield return new MetricColumn("AccuracyMacro", AccuracyMacro); yield return new MetricColumn("TopKAccuracy", TopKAccuracy); yield return new MetricColumn("LogLoss<class name>", PerClassLogLoss, MetricColumn.Objective.Minimize, isVector: true, namePattern: new Regex(string.Format(@"^{0}(?<class>.+)", LogLoss), RegexOptions.IgnoreCase), groupName: "class", nameFormat: string.Format("{0} (class {{0}})", PerClassLogLoss)); yield return new MetricColumn("LogLoss", LogLoss, MetricColumn.Objective.Minimize); yield return new MetricColumn("LogLossReduction", LogLossReduction); } protected override void GetAggregatorConsolidationFuncs(Aggregator aggregator, AggregatorDictionaryBase[] dictionaries, out Action<uint, ReadOnlyMemory<char>, Aggregator> addAgg, out Func<Dictionary<string, IDataView>> consolidate) { var stratCol = new List<uint>(); var stratVal = new List<ReadOnlyMemory<char>>(); var isWeighted = new List<bool>(); var microAcc = new List<double>(); var macroAcc = new List<double>(); var logLoss = new List<double>(); var logLossRed = new List<double>(); var topKAcc = new List<double>(); var perClassLogLoss = new List<double[]>(); var counts = new List<double[]>(); var weights = new List<double[]>(); var confStratCol = new List<uint>(); var confStratVal = new List<ReadOnlyMemory<char>>(); bool hasStrats = Utils.Size(dictionaries) > 0; bool hasWeight = aggregator.Weighted; addAgg = (stratColKey, stratColVal, agg) => { Host.Check(agg.Weighted == hasWeight, "All aggregators must either be weighted or unweighted"); Host.Check((agg.UnweightedCounters.OutputTopKAcc > 0) == (aggregator.UnweightedCounters.OutputTopKAcc > 0), "All aggregators must either compute top-k accuracy or not compute top-k accuracy"); stratCol.Add(stratColKey); stratVal.Add(stratColVal); isWeighted.Add(false); microAcc.Add(agg.UnweightedCounters.MicroAvgAccuracy); macroAcc.Add(agg.UnweightedCounters.MacroAvgAccuracy); logLoss.Add(agg.UnweightedCounters.LogLoss); logLossRed.Add(agg.UnweightedCounters.Reduction); if (agg.UnweightedCounters.OutputTopKAcc > 0) topKAcc.Add(agg.UnweightedCounters.TopKAccuracy); perClassLogLoss.Add(agg.UnweightedCounters.PerClassLogLoss); confStratCol.AddRange(agg.UnweightedCounters.ConfusionTable.Select(x => stratColKey)); confStratVal.AddRange(agg.UnweightedCounters.ConfusionTable.Select(x => stratColVal)); counts.AddRange(agg.UnweightedCounters.ConfusionTable); if (agg.Weighted) { stratCol.Add(stratColKey); stratVal.Add(stratColVal); isWeighted.Add(true); microAcc.Add(agg.WeightedCounters.MicroAvgAccuracy); macroAcc.Add(agg.WeightedCounters.MacroAvgAccuracy); logLoss.Add(agg.WeightedCounters.LogLoss); logLossRed.Add(agg.WeightedCounters.Reduction); if (agg.WeightedCounters.OutputTopKAcc > 0) topKAcc.Add(agg.WeightedCounters.TopKAccuracy); perClassLogLoss.Add(agg.WeightedCounters.PerClassLogLoss); weights.AddRange(agg.WeightedCounters.ConfusionTable); } }; consolidate = () => { var overallDvBldr = new ArrayDataViewBuilder(Host); if (hasStrats) { overallDvBldr.AddColumn(MetricKinds.ColumnNames.StratCol, GetKeyValueGetter(dictionaries), 0, dictionaries.Length, stratCol.ToArray()); overallDvBldr.AddColumn(MetricKinds.ColumnNames.StratVal, TextType.Instance, stratVal.ToArray()); } if (hasWeight) overallDvBldr.AddColumn(MetricKinds.ColumnNames.IsWeighted, BoolType.Instance, isWeighted.ToArray()); overallDvBldr.AddColumn(AccuracyMicro, NumberType.R8, microAcc.ToArray()); overallDvBldr.AddColumn(AccuracyMacro, NumberType.R8, macroAcc.ToArray()); overallDvBldr.AddColumn(LogLoss, NumberType.R8, logLoss.ToArray()); overallDvBldr.AddColumn(LogLossReduction, NumberType.R8, logLossRed.ToArray()); if (aggregator.UnweightedCounters.OutputTopKAcc > 0) overallDvBldr.AddColumn(TopKAccuracy, NumberType.R8, topKAcc.ToArray()); overallDvBldr.AddColumn(PerClassLogLoss, aggregator.GetSlotNames, NumberType.R8, perClassLogLoss.ToArray()); var confDvBldr = new ArrayDataViewBuilder(Host); if (hasStrats) { confDvBldr.AddColumn(MetricKinds.ColumnNames.StratCol, GetKeyValueGetter(dictionaries), 0, dictionaries.Length, confStratCol.ToArray()); confDvBldr.AddColumn(MetricKinds.ColumnNames.StratVal, TextType.Instance, confStratVal.ToArray()); } ValueGetter<VBuffer<ReadOnlyMemory<char>>> getSlotNames = (ref VBuffer<ReadOnlyMemory<char>> dst) => dst = new VBuffer<ReadOnlyMemory<char>>(aggregator.ClassNames.Length, aggregator.ClassNames); confDvBldr.AddColumn(MetricKinds.ColumnNames.Count, getSlotNames, NumberType.R8, counts.ToArray()); if (hasWeight) confDvBldr.AddColumn(MetricKinds.ColumnNames.Weight, getSlotNames, NumberType.R8, weights.ToArray()); var result = new Dictionary<string, IDataView> { { MetricKinds.OverallMetrics, overallDvBldr.GetDataView() }, { MetricKinds.ConfusionMatrix, confDvBldr.GetDataView() } }; return result; }; } public sealed class Aggregator : AggregatorBase { public sealed class Counters { private readonly int _numClasses; public readonly int? OutputTopKAcc; private double _totalLogLoss; private double _numInstances; private double _numCorrect; private double _numCorrectTopK; private readonly double[] _sumWeightsOfClass; private readonly double[] _totalPerClassLogLoss; public readonly double[][] ConfusionTable; public double MicroAvgAccuracy { get { return _numInstances > 0 ? _numCorrect / _numInstances : 0; } } public double MacroAvgAccuracy { get { if (_numInstances == 0) return 0; double macroAvgAccuracy = 0; int countOfNonEmptyClasses = 0; for (int i = 0; i < _numClasses; ++i) { if (_sumWeightsOfClass[i] > 0) { countOfNonEmptyClasses++; macroAvgAccuracy += ConfusionTable[i][i] / _sumWeightsOfClass[i]; } } return countOfNonEmptyClasses > 0 ? macroAvgAccuracy / countOfNonEmptyClasses : 0; } } public double LogLoss { get { return _numInstances > 0 ? _totalLogLoss / _numInstances : 0; } } public double Reduction { get { // reduction -- prior log loss is entropy double entropy = 0; for (int i = 0; i < _numClasses; ++i) { if (_sumWeightsOfClass[i] != 0) entropy += _sumWeightsOfClass[i] * Math.Log(_sumWeightsOfClass[i] / _numInstances); } entropy /= -_numInstances; return 100 * (entropy - LogLoss) / entropy; } } public double TopKAccuracy { get { return _numInstances > 0 ? _numCorrectTopK / _numInstances : 0; } } // The per class average log loss is calculated by dividing the weighted sum of the log loss of examples // in each class by the total weight of examples in that class. public double[] PerClassLogLoss { get { var res = new double[_totalPerClassLogLoss.Length]; for (int i = 0; i < _totalPerClassLogLoss.Length; i++) res[i] = _sumWeightsOfClass[i] > 0 ? _totalPerClassLogLoss[i] / _sumWeightsOfClass[i] : 0; return res; } } public Counters(int numClasses, int? outputTopKAcc) { _numClasses = numClasses; OutputTopKAcc = outputTopKAcc; _sumWeightsOfClass = new double[numClasses]; _totalPerClassLogLoss = new double[numClasses]; ConfusionTable = new double[numClasses][]; for (int i = 0; i < ConfusionTable.Length; i++) ConfusionTable[i] = new double[numClasses]; } public void Update(int[] indices, double loglossCurr, int label, float weight) { Contracts.Assert(Utils.Size(indices) == _numClasses); int assigned = indices[0]; _numInstances += weight; if (label < _numClasses) _sumWeightsOfClass[label] += weight; _totalLogLoss += loglossCurr * weight; if (label < _numClasses) _totalPerClassLogLoss[label] += loglossCurr * weight; if (assigned == label) { _numCorrect += weight; ConfusionTable[label][label] += weight; _numCorrectTopK += weight; } else if (label < _numClasses) { if (OutputTopKAcc > 0) { int idx = Array.IndexOf(indices, label); if (0 <= idx && idx < OutputTopKAcc) _numCorrectTopK += weight; } ConfusionTable[label][assigned] += weight; } } } private ValueGetter<float> _labelGetter; private ValueGetter<VBuffer<float>> _scoreGetter; private ValueGetter<float> _weightGetter; private VBuffer<float> _scores; private readonly float[] _scoresArr; private int[] _indicesArr; private const float Epsilon = (float)1e-15; public readonly Counters UnweightedCounters; public readonly Counters WeightedCounters; public readonly bool Weighted; private long _numUnknownClassInstances; private long _numNegOrNonIntegerLabels; public readonly ReadOnlyMemory<char>[] ClassNames; public Aggregator(IHostEnvironment env, ReadOnlyMemory<char>[] classNames, int scoreVectorSize, bool weighted, int? outputTopKAcc, string stratName) : base(env, stratName) { Host.Assert(outputTopKAcc == null || outputTopKAcc > 0); Host.Assert(scoreVectorSize > 0); Host.Assert(Utils.Size(classNames) == scoreVectorSize); _scoresArr = new float[scoreVectorSize]; UnweightedCounters = new Counters(scoreVectorSize, outputTopKAcc); Weighted = weighted; WeightedCounters = Weighted ? new Counters(scoreVectorSize, outputTopKAcc) : null; ClassNames = classNames; } public override void InitializeNextPass(IRow row, RoleMappedSchema schema) { Host.Assert(PassNum < 1); Host.AssertValue(schema.Label); var score = schema.GetUniqueColumn(MetadataUtils.Const.ScoreValueKind.Score); Host.Assert(score.Type.VectorSize == _scoresArr.Length); _labelGetter = RowCursorUtils.GetLabelGetter(row, schema.Label.Index); _scoreGetter = row.GetGetter<VBuffer<float>>(score.Index); Host.AssertValue(_labelGetter); Host.AssertValue(_scoreGetter); if (schema.Weight != null) _weightGetter = row.GetGetter<float>(schema.Weight.Index); } public override void ProcessRow() { float label = 0; _labelGetter(ref label); if (float.IsNaN(label)) { NumUnlabeledInstances++; return; } if (label < 0 || label != (int)label) { _numNegOrNonIntegerLabels++; return; } _scoreGetter(ref _scores); Host.Check(_scores.Length == _scoresArr.Length); if (VBufferUtils.HasNaNs(in _scores) || VBufferUtils.HasNonFinite(in _scores)) { NumBadScores++; return; } _scores.CopyTo(_scoresArr); float weight = 1; if (_weightGetter != null) { _weightGetter(ref weight); if (!FloatUtils.IsFinite(weight)) { NumBadWeights++; weight = 1; } } // Sort classes by prediction strength. // Use stable OrderBy instead of Sort(), which may give different results on different machines. if (Utils.Size(_indicesArr) < _scoresArr.Length) _indicesArr = new int[_scoresArr.Length]; int j = 0; foreach (var index in Enumerable.Range(0, _scoresArr.Length).OrderByDescending(i => _scoresArr[i])) _indicesArr[j++] = index; var intLabel = (int)label; // log-loss double logloss; if (intLabel < _scoresArr.Length) { // REVIEW: This assumes that the predictions are probabilities, not just relative scores // for the classes. Is this a correct assumption? float p = Math.Min(1, Math.Max(Epsilon, _scoresArr[intLabel])); logloss = -Math.Log(p); } else { // Penalize logloss if the label was not seen during training logloss = -Math.Log(Epsilon); _numUnknownClassInstances++; } UnweightedCounters.Update(_indicesArr, logloss, intLabel, 1); if (WeightedCounters != null) WeightedCounters.Update(_indicesArr, logloss, intLabel, weight); } protected override List<string> GetWarningsCore() { var warnings = base.GetWarningsCore(); if (_numUnknownClassInstances > 0) { warnings.Add(string.Format( "Found {0} test instances with class values not seen in the training set. LogLoss is reported higher than usual because of these instances.", _numUnknownClassInstances)); } if (_numNegOrNonIntegerLabels > 0) { warnings.Add(string.Format( "Found {0} test instances with labels that are either negative or non integers. These instances were ignored", _numNegOrNonIntegerLabels)); } return warnings; } public void GetSlotNames(ref VBuffer<ReadOnlyMemory<char>> slotNames) { var values = slotNames.Values; if (Utils.Size(values) < ClassNames.Length) values = new ReadOnlyMemory<char>[ClassNames.Length]; for (int i = 0; i < ClassNames.Length; i++) values[i] = string.Format("(class {0})", ClassNames[i]).AsMemory(); slotNames = new VBuffer<ReadOnlyMemory<char>>(ClassNames.Length, values); } } public sealed class Result { /// <summary> /// Gets the micro-average accuracy of the model. /// </summary> /// <remarks> /// The micro-average is the fraction of instances predicted correctly. /// /// The micro-average metric weighs each class according to the number of instances that belong /// to it in the dataset. /// </remarks> public double AccuracyMicro { get; } /// <summary> /// Gets the macro-average accuracy of the model. /// </summary> /// <remarks> /// The macro-average is computed by taking the average over all the classes of the fraction /// of correct predictions in this class (the number of correctly predicted instances in the class, /// divided by the total number of instances in the class). /// /// The macro-average metric gives the same weight to each class, no matter how many instances from /// that class the dataset contains. /// </remarks> public double AccuracyMacro { get; } /// <summary> /// Gets the average log-loss of the classifier. /// </summary> /// <remarks> /// The log-loss metric, is computed as follows: /// LL = - (1/m) * sum( log(p[i])) /// where m is the number of instances in the test set. /// p[i] is the probability returned by the classifier if the instance belongs to class 1, /// and 1 minus the probability returned by the classifier if the instance belongs to class 0. /// </remarks> public double LogLoss { get; } /// <summary> /// Gets the log-loss reduction (also known as relative log-loss, or reduction in information gain - RIG) /// of the classifier. /// </summary> /// <remarks> /// The log-loss reduction is scaled relative to a classifier that predicts the prior for every example: /// (LL(prior) - LL(classifier)) / LL(prior) /// This metric can be interpreted as the advantage of the classifier over a random prediction. /// For example, if the RIG equals 20, it can be interpreted as "the probability of a correct prediction is /// 20% better than random guessing". /// </remarks> public double LogLossReduction { get; private set; } /// <summary> /// If positive, this is the top-K for which the <see cref="TopKAccuracy"/> is calculated. /// </summary> public int TopK { get; } /// <summary> /// If <see cref="TopK"/> is positive, this is the relative number of examples where /// the true label is one of the top k predicted labels by the predictor. /// </summary> public double TopKAccuracy { get; } /// <summary> /// Gets the log-loss of the classifier for each class. /// </summary> /// <remarks> /// The log-loss metric, is computed as follows: /// LL = - (1/m) * sum( log(p[i])) /// where m is the number of instances in the test set. /// p[i] is the probability returned by the classifier if the instance belongs to the class, /// and 1 minus the probability returned by the classifier if the instance does not belong to the class. /// </remarks> public double[] PerClassLogLoss { get; } internal Result(IExceptionContext ectx, IRow overallResult, int topK) { double FetchDouble(string name) => RowCursorUtils.Fetch<double>(ectx, overallResult, name); AccuracyMicro = FetchDouble(MultiClassClassifierEvaluator.AccuracyMicro); AccuracyMacro = FetchDouble(MultiClassClassifierEvaluator.AccuracyMacro); LogLoss = FetchDouble(MultiClassClassifierEvaluator.LogLoss); LogLossReduction = FetchDouble(MultiClassClassifierEvaluator.LogLossReduction); TopK = topK; if (topK > 0) TopKAccuracy = FetchDouble(MultiClassClassifierEvaluator.TopKAccuracy); var perClassLogLoss = RowCursorUtils.Fetch<VBuffer<double>>(ectx, overallResult, MultiClassClassifierEvaluator.PerClassLogLoss); PerClassLogLoss = new double[perClassLogLoss.Length]; perClassLogLoss.CopyTo(PerClassLogLoss); } } /// <summary> /// Evaluates scored multiclass classification data. /// </summary> /// <param name="data">The scored data.</param> /// <param name="label">The name of the label column in <paramref name="data"/>.</param> /// <param name="score">The name of the score column in <paramref name="data"/>.</param> /// <param name="predictedLabel">The name of the predicted label column in <paramref name="data"/>.</param> /// <returns>The evaluation results for these outputs.</returns> public Result Evaluate(IDataView data, string label, string score, string predictedLabel) { Host.CheckValue(data, nameof(data)); Host.CheckNonEmpty(label, nameof(label)); Host.CheckNonEmpty(score, nameof(score)); Host.CheckNonEmpty(predictedLabel, nameof(predictedLabel)); var roles = new RoleMappedData(data, opt: false, RoleMappedSchema.ColumnRole.Label.Bind(label), RoleMappedSchema.CreatePair(MetadataUtils.Const.ScoreValueKind.Score, score), RoleMappedSchema.CreatePair(MetadataUtils.Const.ScoreValueKind.PredictedLabel, predictedLabel)); var resultDict = Evaluate(roles); Host.Assert(resultDict.ContainsKey(MetricKinds.OverallMetrics)); var overall = resultDict[MetricKinds.OverallMetrics]; Result result; using (var cursor = overall.GetRowCursor(i => true)) { var moved = cursor.MoveNext(); Host.Assert(moved); result = new Result(Host, cursor, _outputTopKAcc ?? 0); moved = cursor.MoveNext(); Host.Assert(!moved); } return result; } } public sealed class MultiClassPerInstanceEvaluator : PerInstanceEvaluatorBase { public const string LoaderSignature = "MulticlassPerInstance"; private static VersionInfo GetVersionInfo() { return new VersionInfo( modelSignature: "MLTIINST", //verWrittenCur: 0x00010001, // Initial verWrittenCur: 0x00010002, // Serialize the class names verReadableCur: 0x00010002, verWeCanReadBack: 0x00010001, loaderSignature: LoaderSignature, loaderAssemblyName: typeof(MultiClassPerInstanceEvaluator).Assembly.FullName); } private const int AssignedCol = 0; private const int LogLossCol = 1; private const int SortedScoresCol = 2; private const int SortedClassesCol = 3; private const uint VerInitial = 0x00010001; public const string Assigned = "Assigned"; public const string LogLoss = "Log-loss"; public const string SortedScores = "SortedScores"; public const string SortedClasses = "SortedClasses"; private const float Epsilon = (float)1e-15; private readonly int _numClasses; private readonly ReadOnlyMemory<char>[] _classNames; private readonly ColumnType[] _types; public MultiClassPerInstanceEvaluator(IHostEnvironment env, Schema schema, ColumnInfo scoreInfo, string labelCol) : base(env, schema, Contracts.CheckRef(scoreInfo, nameof(scoreInfo)).Name, labelCol) { CheckInputColumnTypes(schema); _numClasses = scoreInfo.Type.VectorSize; _types = new ColumnType[4]; if (schema.HasSlotNames(ScoreIndex, _numClasses)) { var classNames = default(VBuffer<ReadOnlyMemory<char>>); schema.GetMetadata(MetadataUtils.Kinds.SlotNames, ScoreIndex, ref classNames); _classNames = new ReadOnlyMemory<char>[_numClasses]; classNames.CopyTo(_classNames); } else _classNames = Utils.BuildArray(_numClasses, i => i.ToString().AsMemory()); var key = new KeyType(DataKind.U4, 0, _numClasses); _types[AssignedCol] = key; _types[LogLossCol] = NumberType.R8; _types[SortedScoresCol] = new VectorType(NumberType.R4, _numClasses); _types[SortedClassesCol] = new VectorType(key, _numClasses); } private MultiClassPerInstanceEvaluator(IHostEnvironment env, ModelLoadContext ctx, ISchema schema) : base(env, ctx, schema) { CheckInputColumnTypes(schema); // *** Binary format ** // base // int: number of classes // int[]: Ids of the class names _numClasses = ctx.Reader.ReadInt32(); Host.CheckDecode(_numClasses > 0); if (ctx.Header.ModelVerWritten > VerInitial) { _classNames = new ReadOnlyMemory<char>[_numClasses]; for (int i = 0; i < _numClasses; i++) _classNames[i] = ctx.LoadNonEmptyString().AsMemory(); } else _classNames = Utils.BuildArray(_numClasses, i => i.ToString().AsMemory()); _types = new ColumnType[4]; var key = new KeyType(DataKind.U4, 0, _numClasses); _types[AssignedCol] = key; _types[LogLossCol] = NumberType.R8; _types[SortedScoresCol] = new VectorType(NumberType.R4, _numClasses); _types[SortedClassesCol] = new VectorType(key, _numClasses); } public static MultiClassPerInstanceEvaluator Create(IHostEnvironment env, ModelLoadContext ctx, ISchema schema) { Contracts.CheckValue(env, nameof(env)); env.CheckValue(ctx, nameof(ctx)); ctx.CheckAtModel(GetVersionInfo()); return new MultiClassPerInstanceEvaluator(env, ctx, schema); } public override void Save(ModelSaveContext ctx) { Host.CheckValue(ctx, nameof(ctx)); ctx.CheckAtModel(); ctx.SetVersionInfo(GetVersionInfo()); // *** Binary format ** // base // int: number of classes // int[]: Ids of the class names base.Save(ctx); Host.Assert(_numClasses > 0); ctx.Writer.Write(_numClasses); for (int i = 0; i < _numClasses; i++) ctx.SaveNonEmptyString(_classNames[i].ToString()); } public override Func<int, bool> GetDependencies(Func<int, bool> activeOutput) { Host.Assert(ScoreIndex >= 0); Host.Assert(LabelIndex >= 0); // The score column is needed if any of the outputs are active. The label column is needed only // if the log-loss output is active. return col => col == LabelIndex && activeOutput(LogLossCol) || col == ScoreIndex && (activeOutput(AssignedCol) || activeOutput(SortedScoresCol) || activeOutput(SortedClassesCol) || activeOutput(LogLossCol)); } public override Delegate[] CreateGetters(IRow input, Func<int, bool> activeOutput, out Action disposer) { disposer = null; var getters = new Delegate[4]; if (!activeOutput(AssignedCol) && !activeOutput(SortedClassesCol) && !activeOutput(SortedScoresCol) && !activeOutput(LogLossCol)) return getters; long cachedPosition = -1; VBuffer<float> scores = default(VBuffer<float>); float label = 0; var scoresArr = new float[_numClasses]; int[] sortedIndices = new int[_numClasses]; var labelGetter = activeOutput(LogLossCol) ? RowCursorUtils.GetLabelGetter(input, LabelIndex) : (ref float dst) => dst = float.NaN; var scoreGetter = input.GetGetter<VBuffer<float>>(ScoreIndex); Action updateCacheIfNeeded = () => { if (cachedPosition != input.Position) { labelGetter(ref label); scoreGetter(ref scores); scores.CopyTo(scoresArr); int j = 0; foreach (var index in Enumerable.Range(0, scoresArr.Length).OrderByDescending(i => scoresArr[i])) sortedIndices[j++] = index; cachedPosition = input.Position; } }; if (activeOutput(AssignedCol)) { ValueGetter<uint> assignedFn = (ref uint dst) => { updateCacheIfNeeded(); dst = (uint)sortedIndices[0] + 1; }; getters[AssignedCol] = assignedFn; } if (activeOutput(SortedScoresCol)) { ValueGetter<VBuffer<float>> topKScoresFn = (ref VBuffer<float> dst) => { updateCacheIfNeeded(); var values = dst.Values; if (Utils.Size(values) < _numClasses) values = new float[_numClasses]; for (int i = 0; i < _numClasses; i++) values[i] = scores.GetItemOrDefault(sortedIndices[i]); dst = new VBuffer<float>(_numClasses, values); }; getters[SortedScoresCol] = topKScoresFn; } if (activeOutput(SortedClassesCol)) { ValueGetter<VBuffer<uint>> topKClassesFn = (ref VBuffer<uint> dst) => { updateCacheIfNeeded(); var values = dst.Values; if (Utils.Size(values) < _numClasses) values = new uint[_numClasses]; for (int i = 0; i < _numClasses; i++) values[i] = (uint)sortedIndices[i] + 1; dst = new VBuffer<uint>(_numClasses, values); }; getters[SortedClassesCol] = topKClassesFn; } if (activeOutput(LogLossCol)) { ValueGetter<double> logLossFn = (ref double dst) => { updateCacheIfNeeded(); if (float.IsNaN(label)) { dst = double.NaN; return; } int intLabel = (int)label; if (intLabel < _numClasses) { float p = Math.Min(1, Math.Max(Epsilon, scoresArr[intLabel])); dst = -Math.Log(p); return; } // Penalize logloss if the label was not seen during training dst = -Math.Log(Epsilon); }; getters[LogLossCol] = logLossFn; } return getters; } public override Schema.Column[] GetOutputColumns() { var infos = new Schema.Column[4]; var assignedColKeyValues = new Schema.Metadata.Builder(); assignedColKeyValues.AddKeyValues(_numClasses, TextType.Instance, CreateKeyValueGetter()); infos[AssignedCol] = new Schema.Column(Assigned, _types[AssignedCol], assignedColKeyValues.GetMetadata()); infos[LogLossCol] = new Schema.Column(LogLoss, _types[LogLossCol], null); var sortedScores = new Schema.Metadata.Builder(); sortedScores.AddSlotNames(_numClasses, CreateSlotNamesGetter(_numClasses, "Score")); var sortedClasses = new Schema.Metadata.Builder(); sortedClasses.AddSlotNames(_numClasses, CreateSlotNamesGetter(_numClasses, "Class")); sortedClasses.AddKeyValues(_numClasses, TextType.Instance, CreateKeyValueGetter()); infos[SortedScoresCol] = new Schema.Column(SortedScores, _types[SortedScoresCol], sortedScores.GetMetadata()); infos[SortedClassesCol] = new Schema.Column(SortedClasses, _types[SortedClassesCol], sortedClasses.GetMetadata()); return infos; } // REVIEW: Figure out how to avoid having the column name in each slot name. private ValueGetter<VBuffer<ReadOnlyMemory<char>>> CreateSlotNamesGetter(int numTopClasses, string suffix) { return (ref VBuffer<ReadOnlyMemory<char>> dst) => { var values = dst.Values; if (Utils.Size(values) < numTopClasses) values = new ReadOnlyMemory<char>[numTopClasses]; for (int i = 1; i <= numTopClasses; i++) values[i - 1] = string.Format("#{0} {1}", i, suffix).AsMemory(); dst = new VBuffer<ReadOnlyMemory<char>>(numTopClasses, values); }; } private ValueGetter<VBuffer<ReadOnlyMemory<char>>> CreateKeyValueGetter() { return (ref VBuffer<ReadOnlyMemory<char>> dst) => { var values = dst.Values; if (Utils.Size(values) < _numClasses) values = new ReadOnlyMemory<char>[_numClasses]; for (int i = 0; i < _numClasses; i++) values[i] = _classNames[i]; dst = new VBuffer<ReadOnlyMemory<char>>(_numClasses, values); }; } private void CheckInputColumnTypes(ISchema schema) { Host.AssertNonEmpty(ScoreCol); Host.AssertNonEmpty(LabelCol); var t = schema.GetColumnType(ScoreIndex); if (t.VectorSize < 2 || t.ItemType != NumberType.Float) throw Host.Except("Score column '{0}' has type '{1}' but must be a vector of two or more items of type R4", ScoreCol, t); t = schema.GetColumnType(LabelIndex); if (t != NumberType.Float && t.KeyCount <= 0) throw Host.Except("Label column '{0}' has type '{1}' but must be a float or a known-cardinality key", LabelCol, t); } } public sealed class MultiClassMamlEvaluator : MamlEvaluatorBase { public class Arguments : ArgumentsBase { [Argument(ArgumentType.AtMostOnce, HelpText = "Output top-K accuracy.", ShortName = "topkacc")] public int? OutputTopKAcc; [Argument(ArgumentType.AtMostOnce, HelpText = "Output top-K classes.", ShortName = "topk")] public int NumTopClassesToOutput = 3; [Argument(ArgumentType.AtMostOnce, HelpText = "Maximum number of classes in confusion matrix.", ShortName = "nccf")] public int NumClassesConfusionMatrix = 10; [Argument(ArgumentType.AtMostOnce, HelpText = "Output per class statistics and confusion matrix.", ShortName = "opcs")] public bool OutputPerClassStatistics = false; } private const string TopKAccuracyFormat = "Top-{0}-accuracy"; private readonly bool _outputPerClass; private readonly int _numTopClasses; private readonly int _numConfusionTableClasses; private readonly int? _outputTopKAcc; private readonly MultiClassClassifierEvaluator _evaluator; protected override IEvaluator Evaluator { get { return _evaluator; } } public MultiClassMamlEvaluator(IHostEnvironment env, Arguments args) : base(args, env, MetadataUtils.Const.ScoreColumnKind.MultiClassClassification, "MultiClassMamlEvaluator") { Host.CheckValue(args, nameof(args)); // REVIEW: why do we need to insist on at least 2? Host.CheckUserArg(2 <= args.NumTopClassesToOutput, nameof(args.NumTopClassesToOutput)); Host.CheckUserArg(2 <= args.NumClassesConfusionMatrix, nameof(args.NumClassesConfusionMatrix)); Host.CheckUserArg(args.OutputTopKAcc == null || args.OutputTopKAcc > 0, nameof(args.OutputTopKAcc)); Host.CheckUserArg(2 <= args.NumClassesConfusionMatrix, nameof(args.NumClassesConfusionMatrix)); _numTopClasses = args.NumTopClassesToOutput; _outputPerClass = args.OutputPerClassStatistics; _numConfusionTableClasses = args.NumClassesConfusionMatrix; _outputTopKAcc = args.OutputTopKAcc; var evalArgs = new MultiClassClassifierEvaluator.Arguments { OutputTopKAcc = _outputTopKAcc }; _evaluator = new MultiClassClassifierEvaluator(Host, evalArgs); } protected override void PrintFoldResultsCore(IChannel ch, Dictionary<string, IDataView> metrics) { Host.AssertValue(metrics); if (!metrics.TryGetValue(MetricKinds.OverallMetrics, out IDataView fold)) throw ch.Except("No overall metrics found"); if (!metrics.TryGetValue(MetricKinds.ConfusionMatrix, out IDataView conf)) throw ch.Except("No confusion matrix found"); // Change the name of the Top-k-accuracy column. if (_outputTopKAcc != null) fold = ChangeTopKAccColumnName(fold); // Drop the per-class information. if (!_outputPerClass) fold = DropPerClassColumn(fold); var unweightedConf = MetricWriter.GetConfusionTable(Host, conf, out string weightedConf, false, _numConfusionTableClasses); var unweightedFold = MetricWriter.GetPerFoldResults(Host, fold, out string weightedFold); ch.Assert(string.IsNullOrEmpty(weightedConf) == string.IsNullOrEmpty(weightedFold)); if (!string.IsNullOrEmpty(weightedConf)) { ch.Info(weightedConf); ch.Info(weightedFold); } ch.Info(unweightedConf); ch.Info(unweightedFold); } protected override IDataView CombineOverallMetricsCore(IDataView[] metrics) { var overallList = new List<IDataView>(); for (int i = 0; i < metrics.Length; i++) { var idv = metrics[i]; if (!_outputPerClass) idv = DropPerClassColumn(idv); overallList.Add(idv); } var views = overallList.ToArray(); if (_outputPerClass) { EvaluateUtils.ReconcileSlotNames<double>(Host, views, MultiClassClassifierEvaluator.PerClassLogLoss, NumberType.R8, def: double.NaN); for (int i = 0; i < overallList.Count; i++) { var idv = views[i]; // Find the old per-class log-loss column and drop it. for (int col = 0; col < idv.Schema.ColumnCount; col++) { if (idv.Schema.IsHidden(col) && idv.Schema.GetColumnName(col).Equals(MultiClassClassifierEvaluator.PerClassLogLoss)) { idv = new ChooseColumnsByIndexTransform(Host, new ChooseColumnsByIndexTransform.Arguments() { Drop = true, Index = new[] { col } }, idv); break; } } views[i] = idv; } } return base.CombineOverallMetricsCore(views); } protected override IDataView GetOverallResultsCore(IDataView overall) { // Change the name of the Top-k-accuracy column. if (_outputTopKAcc != null) overall = ChangeTopKAccColumnName(overall); return overall; } private IDataView ChangeTopKAccColumnName(IDataView input) { input = new ColumnsCopyingTransformer(Host, (MultiClassClassifierEvaluator.TopKAccuracy, string.Format(TopKAccuracyFormat, _outputTopKAcc))).Transform(input); return ColumnSelectingTransformer.CreateDrop(Host, input, MultiClassClassifierEvaluator.TopKAccuracy ); } private IDataView DropPerClassColumn(IDataView input) { if (input.Schema.TryGetColumnIndex(MultiClassClassifierEvaluator.PerClassLogLoss, out int perClassCol)) { input = ColumnSelectingTransformer.CreateDrop(Host, input, MultiClassClassifierEvaluator.PerClassLogLoss); } return input; } public override IEnumerable<MetricColumn> GetOverallMetricColumns() { yield return new MetricColumn("AccuracyMicro", MultiClassClassifierEvaluator.AccuracyMicro); yield return new MetricColumn("AccuracyMacro", MultiClassClassifierEvaluator.AccuracyMacro); yield return new MetricColumn("TopKAccuracy", string.Format(TopKAccuracyFormat, _outputTopKAcc)); if (_outputPerClass) { yield return new MetricColumn("LogLoss<class name>", MultiClassClassifierEvaluator.PerClassLogLoss, MetricColumn.Objective.Minimize, isVector: true, namePattern: new Regex(string.Format(@"^{0}(?<class>.+)", MultiClassClassifierEvaluator.LogLoss), RegexOptions.IgnoreCase)); } yield return new MetricColumn("LogLoss", MultiClassClassifierEvaluator.LogLoss, MetricColumn.Objective.Minimize); yield return new MetricColumn("LogLossReduction", MultiClassClassifierEvaluator.LogLossReduction); } protected override IEnumerable<string> GetPerInstanceColumnsToSave(RoleMappedSchema schema) { Host.CheckValue(schema, nameof(schema)); Host.CheckParam(schema.Label != null, nameof(schema), "Schema must contain a label column"); // Output the label column. yield return schema.Label.Name; // Return the output columns. yield return MultiClassPerInstanceEvaluator.Assigned; yield return MultiClassPerInstanceEvaluator.LogLoss; yield return MultiClassPerInstanceEvaluator.SortedScores; yield return MultiClassPerInstanceEvaluator.SortedClasses; } // Multi-class evaluator adds four per-instance columns: "Assigned", "Top scores", "Top classes" and "Log-loss". protected override IDataView GetPerInstanceMetricsCore(IDataView perInst, RoleMappedSchema schema) { // If the label column is a key without key values, convert it to I8, just for saving the per-instance // text file, since if there are different key counts the columns cannot be appended. if (!perInst.Schema.TryGetColumnIndex(schema.Label.Name, out int labelCol)) throw Host.Except("Could not find column '{0}'", schema.Label.Name); var labelType = perInst.Schema.GetColumnType(labelCol); if (labelType.IsKey && (!perInst.Schema.HasKeyValues(labelCol, labelType.KeyCount) || labelType.RawKind != DataKind.U4)) { perInst = LambdaColumnMapper.Create(Host, "ConvertToDouble", perInst, schema.Label.Name, schema.Label.Name, perInst.Schema.GetColumnType(labelCol), NumberType.R8, (in uint src, ref double dst) => dst = src == 0 ? double.NaN : src - 1 + (double)labelType.AsKey.Min); } var perInstSchema = perInst.Schema; if (perInstSchema.TryGetColumnIndex(MultiClassPerInstanceEvaluator.SortedClasses, out int sortedClassesIndex)) { var type = perInstSchema.GetColumnType(sortedClassesIndex); if (_numTopClasses < type.VectorSize) { // Wrap with a DropSlots transform to pick only the first _numTopClasses slots. var args = new DropSlotsTransform.Arguments { Column = new DropSlotsTransform.Column[] { new DropSlotsTransform.Column { Name = MultiClassPerInstanceEvaluator.SortedClasses, Slots = new[] { new DropSlotsTransform.Range() { Min = _numTopClasses } } } } }; perInst = new DropSlotsTransform(Host, args, perInst); } } // Wrap with a DropSlots transform to pick only the first _numTopClasses slots. if (perInst.Schema.TryGetColumnIndex(MultiClassPerInstanceEvaluator.SortedScores, out int sortedScoresIndex)) { var type = perInst.Schema.GetColumnType(sortedScoresIndex); if (_numTopClasses < type.VectorSize) { var args = new DropSlotsTransform.Arguments { Column = new DropSlotsTransform.Column[] { new DropSlotsTransform.Column() { Name = MultiClassPerInstanceEvaluator.SortedScores, Slots = new[] { new DropSlotsTransform.Range() { Min = _numTopClasses } } } } }; perInst = new DropSlotsTransform(Host, args, perInst); } } return perInst; } } public static partial class Evaluate { [TlcModule.EntryPoint(Name = "Models.ClassificationEvaluator", Desc = "Evaluates a multi class classification scored dataset.")] public static CommonOutputs.ClassificationEvaluateOutput MultiClass(IHostEnvironment env, MultiClassMamlEvaluator.Arguments input) { Contracts.CheckValue(env, nameof(env)); var host = env.Register("EvaluateMultiClass"); host.CheckValue(input, nameof(input)); EntryPointUtils.CheckInputArgs(host, input); MatchColumns(host, input, out string label, out string weight, out string name); var evaluator = new MultiClassMamlEvaluator(host, input); var data = new RoleMappedData(input.Data, label, null, null, weight, name); var metrics = evaluator.Evaluate(data); var warnings = ExtractWarnings(host, metrics); var overallMetrics = ExtractOverallMetrics(host, metrics, evaluator); var perInstanceMetrics = evaluator.GetPerInstanceMetrics(data); var confusionMatrix = ExtractConfusionMatrix(host, metrics); return new CommonOutputs.ClassificationEvaluateOutput() { Warnings = warnings, OverallMetrics = overallMetrics, PerInstanceMetrics = perInstanceMetrics, ConfusionMatrix = confusionMatrix }; } } }
47.263993
179
0.564949
[ "MIT" ]
robosek/machinelearning
src/Microsoft.ML.Data/Evaluators/MulticlassClassifierEvaluator.cs
56,575
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; using System.ComponentModel; namespace Azure.AI.MetricsAdvisor.Models { /// <summary> data source type. </summary> public readonly partial struct DataFeedSourceKind : IEquatable<DataFeedSourceKind> { private readonly string _value; /// <summary> Initializes a new instance of <see cref="DataFeedSourceKind"/>. </summary> /// <exception cref="ArgumentNullException"> <paramref name="value"/> is null. </exception> public DataFeedSourceKind(string value) { _value = value ?? throw new ArgumentNullException(nameof(value)); } private const string AzureApplicationInsightsValue = "AzureApplicationInsights"; private const string AzureBlobValue = "AzureBlob"; private const string AzureCosmosDbValue = "AzureCosmosDB"; private const string AzureDataExplorerValue = "AzureDataExplorer"; private const string AzureDataLakeStorageValue = "AzureDataLakeStorageGen2"; private const string AzureEventHubsValue = "AzureEventHubs"; private const string LogAnalyticsValue = "AzureLogAnalytics"; private const string AzureTableValue = "AzureTable"; private const string InfluxDbValue = "InfluxDB"; private const string MongoDbValue = "MongoDB"; private const string MySqlValue = "MySql"; private const string PostgreSqlValue = "PostgreSql"; private const string SqlServerValue = "SqlServer"; /// <summary> Determines if two <see cref="DataFeedSourceKind"/> values are the same. </summary> public static bool operator ==(DataFeedSourceKind left, DataFeedSourceKind right) => left.Equals(right); /// <summary> Determines if two <see cref="DataFeedSourceKind"/> values are not the same. </summary> public static bool operator !=(DataFeedSourceKind left, DataFeedSourceKind right) => !left.Equals(right); /// <summary> Converts a string to a <see cref="DataFeedSourceKind"/>. </summary> public static implicit operator DataFeedSourceKind(string value) => new DataFeedSourceKind(value); /// <inheritdoc /> [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is DataFeedSourceKind other && Equals(other); /// <inheritdoc /> public bool Equals(DataFeedSourceKind other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); /// <inheritdoc /> [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value?.GetHashCode() ?? 0; /// <inheritdoc /> public override string ToString() => _value; } }
48.913793
137
0.695805
[ "MIT" ]
93mishra/azure-sdk-for-net
sdk/metricsadvisor/Azure.AI.MetricsAdvisor/src/Generated/Models/DataFeedSourceKind.cs
2,837
C#
// Copyright 2020-present Etherna Sagl // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. namespace Etherna.MongODM.Core.Serialization.Serializers { public interface IReferenceContainerSerializer : IModelMapsContainerSerializer { bool UseCascadeDelete { get; } } }
37
82
0.72973
[ "Apache-2.0" ]
Etherna/mongodm
src/MongODM.Core/Serialization/Serializers/IReferenceContainerSerializer.cs
816
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Infosys.Solutions.Superbot.Resource.Entity { using System; using System.Collections.Generic; public partial class resource { public resource() { this.Audit_Logs = new HashSet<Audit_Logs>(); this.healthcheck_details = new HashSet<healthcheck_details>(); this.observable_resource_map = new HashSet<observable_resource_map>(); this.resource_dependency_map = new HashSet<resource_dependency_map>(); this.resource_attributes = new HashSet<resource_attributes>(); this.resource_observable_remediation_plan_map = new HashSet<resource_observable_remediation_plan_map>(); this.resource_observable_action_map = new HashSet<resource_observable_action_map>(); this.resource_observable_action_map1 = new HashSet<resource_observable_action_map>(); } public string ResourceId { get; set; } public string ResourceName { get; set; } public int ResourceTypeId { get; set; } public string Source { get; set; } public string CreatedBy { get; set; } public System.DateTime CreateDate { get; set; } public string ModifiedBy { get; set; } public Nullable<System.DateTime> ModifiedDate { get; set; } public System.DateTime ValidityStart { get; set; } public System.DateTime ValidityEnd { get; set; } public int TenantId { get; set; } public string ResourceRef { get; set; } public Nullable<int> PlatformId { get; set; } public string VersionNumber { get; set; } public string Comments { get; set; } public Nullable<bool> IsActive { get; set; } public virtual ICollection<Audit_Logs> Audit_Logs { get; set; } public virtual ICollection<healthcheck_details> healthcheck_details { get; set; } public virtual ICollection<observable_resource_map> observable_resource_map { get; set; } public virtual ICollection<resource_dependency_map> resource_dependency_map { get; set; } public virtual ICollection<resource_attributes> resource_attributes { get; set; } public virtual ICollection<resource_observable_remediation_plan_map> resource_observable_remediation_plan_map { get; set; } public virtual ICollection<resource_observable_action_map> resource_observable_action_map { get; set; } public virtual ICollection<resource_observable_action_map> resource_observable_action_map1 { get; set; } } }
53.535714
132
0.647765
[ "Apache-2.0" ]
Infosys/Intelligent-Bot-Management-
Superbot/Source/DataEntity/resource.cs
2,998
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ #nullable enable namespace FormatDraft202012Feature.ValidationOfIDEMailAddresses { using System; using System.Collections.Immutable; using System.Text; using System.Text.Json; using System.Text.RegularExpressions; using Corvus.Json; /// <summary> /// A type generated from a JsonSchema specification. /// </summary> public readonly struct Schema : IJsonValue, IEquatable<Schema> { private readonly JsonElement jsonElementBacking; /// <summary> /// Initializes a new instance of the <see cref="Schema"/> struct. /// </summary> /// <param name="value">The backing <see cref="JsonElement"/>.</param> public Schema(JsonElement value) { this.jsonElementBacking = value; } /// <summary> /// Gets a value indicating whether this is backed by a JSON element. /// </summary> public bool HasJsonElement => true ; /// <summary> /// Gets the value as a JsonElement. /// </summary> public JsonElement AsJsonElement { get { return this.jsonElementBacking; } } /// <inheritdoc/> public JsonValueKind ValueKind { get { return this.jsonElementBacking.ValueKind; } } /// <inheritdoc/> public JsonAny AsAny { get { return new JsonAny(this.jsonElementBacking); } } /// <summary> /// Conversion from any. /// </summary> /// <param name="value">The value from which to convert.</param> public static implicit operator Schema(JsonAny value) { if (value.HasJsonElement) { return new Schema(value.AsJsonElement); } return value.As<Schema>(); } /// <summary> /// Conversion to any. /// </summary> /// <param name="value">The value from which to convert.</param> public static implicit operator JsonAny(Schema value) { return value.AsAny; } /// <summary> /// Standard equality operator. /// </summary> /// <param name="lhs">The left hand side of the comparison.</param> /// <param name="rhs">The right hand side of the comparison.</param> /// <returns>True if they are equal.</returns> public static bool operator ==(Schema lhs, Schema rhs) { return lhs.Equals(rhs); } /// <summary> /// Standard inequality operator. /// </summary> /// <param name="lhs">The left hand side of the comparison.</param> /// <param name="rhs">The right hand side of the comparison.</param> /// <returns>True if they are not equal.</returns> public static bool operator !=(Schema lhs, Schema rhs) { return !lhs.Equals(rhs); } /// <inheritdoc/> public override bool Equals(object? obj) { if (obj is Schema entity) { return this.Equals(entity); } return false; } /// <inheritdoc/> public override int GetHashCode() { JsonValueKind valueKind = this.ValueKind; return valueKind switch { JsonValueKind.Object => this.AsObject().GetHashCode(), JsonValueKind.Array => this.AsArray().GetHashCode(), JsonValueKind.Number => this.AsNumber().GetHashCode(), JsonValueKind.String => this.AsString().GetHashCode(), JsonValueKind.True or JsonValueKind.False => this.AsBoolean().GetHashCode(), JsonValueKind.Null => JsonNull.NullHashCode, _ => JsonAny.UndefinedHashCode, }; } /// <summary> /// Writes the object to the <see cref="Utf8JsonWriter"/>. /// </summary> /// <param name="writer">The writer to which to write the object.</param> public void WriteTo(Utf8JsonWriter writer) { if (this.jsonElementBacking.ValueKind != JsonValueKind.Undefined) { this.jsonElementBacking.WriteTo(writer); return; } writer.WriteNullValue(); } /// <inheritdoc/> public bool Equals<T>(T other) where T : struct, IJsonValue { JsonValueKind valueKind = this.ValueKind; if (other.ValueKind != valueKind) { return false; } return valueKind switch { JsonValueKind.Object => this.AsObject().Equals(other.AsObject()), JsonValueKind.Array => this.AsArray().Equals(other.AsArray()), JsonValueKind.Number => this.AsNumber().Equals(other.AsNumber()), JsonValueKind.String => this.AsString().Equals(other.AsString()), JsonValueKind.True or JsonValueKind.False => this.AsBoolean().Equals(other.AsBoolean()), JsonValueKind.Null => true, _ => false, }; } /// <inheritdoc/> public bool Equals(Schema other) { JsonValueKind valueKind = this.ValueKind; if (other.ValueKind != valueKind) { return false; } return valueKind switch { JsonValueKind.Object => this.AsObject().Equals(other.AsObject()), JsonValueKind.Array => this.AsArray().Equals(other.AsArray()), JsonValueKind.Number => this.AsNumber().Equals(other.AsNumber()), JsonValueKind.String => this.AsString().Equals(other.AsString()), JsonValueKind.True or JsonValueKind.False => this.AsBoolean().Equals(other.AsBoolean()), JsonValueKind.Null => true, _ => false, }; } /// <inheritdoc/> public T As<T>() where T : struct, IJsonValue { return this.As<Schema, T>(); } /// <inheritdoc/> public ValidationContext Validate(in ValidationContext? validationContext = null, ValidationLevel level = ValidationLevel.Flag) { ValidationContext result = validationContext ?? ValidationContext.ValidContext; if (level != ValidationLevel.Flag) { result = result.UsingStack(); } JsonValueKind valueKind = this.ValueKind; result = this.ValidateFormat(valueKind, result, level); if (level == ValidationLevel.Flag && !result.IsValid) { return result; } return result; } private ValidationContext ValidateFormat(JsonValueKind valueKind, ValidationContext result, ValidationLevel level) { if (valueKind == JsonValueKind.String) { return Corvus.Json.Validate.TypeIdnEmail(this, result, level); } return result; } } }
22.91623
135
0.458191
[ "Apache-2.0" ]
corvus-dotnet/Corvus.JsonSchema
Solutions/Corvus.JsonSchema.Benchmarking/202012/FormatDraft202012/ValidationOfIDEMailAddresses/Schema.cs
8,754
C#
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authentication.OpenIdConnect; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.HttpOverrides; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.IdentityModel.Tokens; namespace netcore5_oidc { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddAuthentication(options => { options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme; }) .AddCookie() .AddOpenIdConnect(options => { options.SignInScheme = "Cookies"; options.Authority = Configuration["oidc:Authority"]; options.RequireHttpsMetadata = true; options.ClientId = Configuration["oidc:ClientId"]; options.ClientSecret = Configuration["oidc:ClientSecret"]; options.ResponseType = "code"; options.CallbackPath = "/signin-oidc"; options.GetClaimsFromUserInfoEndpoint = true; options.Scope.Add("openid"); options.Scope.Add("profile"); options.SaveTokens = true; options.TokenValidationParameters = new TokenValidationParameters { NameClaimType = "name", RoleClaimType = "groups", ValidateIssuer = true }; options.UsePkce = true; }); services.AddAuthorization(options => { options.FallbackPolicy = options.DefaultPolicy; }); services.AddRazorPages().AddMvcOptions(options => { }).AddRazorRuntimeCompilation(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseRouting(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseForwardedHeaders(new ForwardedHeadersOptions { RequireHeaderSymmetry = false, ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto }); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}" ); }); } } }
34.836364
143
0.599426
[ "Apache-2.0" ]
jtstuedle/netcore-oidc-client
Startup.cs
3,832
C#
using Dominio.Interfaces.Repositorio.Comum; using Dominio.Interfaces.Servicos.Comum; using System.Collections.Generic; using System.Data; namespace Dominio.Servicos.Comum { public class Servico<TEntity> : IServico<TEntity> where TEntity : class { private readonly IRepositorio<TEntity> _repositorio; public Servico(IRepositorio<TEntity> repositorio) { _repositorio = repositorio; } public TEntity Adicionar(TEntity entity, IDbTransaction transaction = null, int? commandTimeout = default(int?)) { return _repositorio.Adicionar(entity, transaction); } public void Atualizar(TEntity entity, IDbTransaction transaction = null, int? commandTimeout = default(int?)) { _repositorio.Atualizar(entity, transaction); } public void Deletar(TEntity entity, IDbTransaction transaction = null, int? commandTimeout = default(int?)) { _repositorio.Deletar(entity, transaction); } public TEntity ObterPorId(int id) { return _repositorio.ObterPorId(id); } public IEnumerable<TEntity> ObterTodos() { return _repositorio.ObterTodos(); } } }
28.086957
120
0.633127
[ "Apache-2.0" ]
isaiasccruz/AspNetCoreMVCBasicCRUD
DominioCore/Servicos/Comum/Servico.cs
1,294
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.AspNetCore.WebUtilities; namespace WebApplication4.Areas.Identity.Pages.Account { [AllowAnonymous] public class ConfirmEmailModel : PageModel { private readonly UserManager<IdentityUser> _userManager; public ConfirmEmailModel(UserManager<IdentityUser> userManager) { _userManager = userManager; } [TempData] public string StatusMessage { get; set; } public async Task<IActionResult> OnGetAsync(string userId, string code) { if (userId == null || code == null) { return RedirectToPage("/Index"); } var user = await _userManager.FindByIdAsync(userId); if (user == null) { return NotFound($"Unable to load user with ID '{userId}'."); } code = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(code)); var result = await _userManager.ConfirmEmailAsync(user, code); StatusMessage = result.Succeeded ? "Thank you for confirming your email." : "Error confirming your email."; return Page(); } } }
30.829787
119
0.642512
[ "MIT" ]
Padawan2612/Consola_Inicial_OFF
miPrimerApp/WebApplication4/WebApplication4/Areas/Identity/Pages/Account/ConfirmEmail.cshtml.cs
1,451
C#
// <copyright file="SignInPage.cs" company="Automate The Planet Ltd."> // Copyright 2019 Automate The Planet Ltd. // Licensed under the Apache License, Version 2.0 (the "License"); // You may not use this file except in compliance with the License. // You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> // <author>Anton Angelov</author> // <site>http://automatetheplanet.com/</site> using AdvancedBehavioursDesignPattern.Base; using OpenQA.Selenium; namespace AdvancedBehavioursDesignPattern.Pages.SignInPage { public partial class SignInPage : BasePage { public SignInPage(IWebDriver driver) : base(driver) { } public void Login(string email, string password) { EmailInput.SendKeys(email); PasswordInput.SendKeys(password); SignInButton.Click(); } public void WaitForPageToLoad() { // wait for a specific element to show up. } } }
35.184211
85
0.691847
[ "Apache-2.0" ]
FrancielleWN/AutomateThePlanet-Learning-Series
DesignPatternsInAutomatedTesting-Series/AdvancedBehavioursDesignPattern/Pages/SignInPage/SignInPage.cs
1,339
C#
using System.IO; using System.Text; namespace Alex.API.Services { public interface IStorageSystem { #region Json bool TryWriteJson<T>(string key, T value); bool TryReadJson<T>(string key, out T value); bool TryReadJson<T>(string key, out T value, Encoding encoding); #endregion #region Bytes bool TryWriteBytes(string key, byte[] value); bool TryReadBytes(string key, out byte[] value); #endregion #region String bool TryWriteString(string key, string value); bool TryWriteString(string key, string value, Encoding encoding); bool TryReadString(string key, out string value); bool TryReadString(string key, out string value, Encoding encoding); #endregion #region Directory bool TryGetDirectory(string key, out DirectoryInfo info); bool TryCreateDirectory(string key); bool TryDeleteDirectory(string key); #endregion bool Exists(string key); bool Delete(string key); FileStream OpenFileStream(string key, FileMode access); } }
24.791667
76
0.618487
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
lvyitian1/Alex
src/Alex.API/Services/Abstractions/IStorageSystem.cs
1,192
C#
using System; namespace Orckestra.Composer.Cart.Parameters.Order { public class GetShipmentNotesParam { /// <summary> /// The scope of the shipment. /// </summary> public string Scope { get; set; } /// <summary> /// The overture identifier of the shipment. /// </summary> public Guid ShipmentId { get; set; } } }
21.777778
52
0.561224
[ "MIT" ]
InnaBoitsun/BetterRetailGroceryTest
src/Orckestra.Composer.Cart/Parameters/Order/GetShipmentNotesParam.cs
394
C#
using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using System.Text; using Utf8Json.Formatters; namespace Utf8Json.Resolvers { public sealed class BuiltinResolver : IJsonFormatterResolver { public static readonly IJsonFormatterResolver Instance = new BuiltinResolver(); BuiltinResolver() { } public IJsonFormatter<T> GetFormatter<T>() { return FormatterCache<T>.formatter; } static class FormatterCache<T> { public static readonly IJsonFormatter<T> formatter; static FormatterCache() { // Reduce IL2CPP code generate size(don't write long code in <T>) formatter = (IJsonFormatter<T>)BuiltinResolverGetFormatterHelper.GetFormatter(typeof(T)); } } // used from PrimitiveObjectFormatter internal static class BuiltinResolverGetFormatterHelper { static readonly Dictionary<Type, object> formatterMap = new Dictionary<Type, object>() { // Primitive {typeof(Int16), Int16Formatter.Default}, {typeof(Int32), Int32Formatter.Default}, {typeof(Int64), Int64Formatter.Default}, {typeof(UInt16), UInt16Formatter.Default}, {typeof(UInt32), UInt32Formatter.Default}, {typeof(UInt64), UInt64Formatter.Default}, {typeof(Single), SingleFormatter.Default}, {typeof(Double), DoubleFormatter.Default}, {typeof(bool), BooleanFormatter.Default}, {typeof(byte), ByteFormatter.Default}, {typeof(sbyte), SByteFormatter.Default}, // Nulllable Primitive {typeof(Nullable<Int16>), NullableInt16Formatter.Default}, {typeof(Nullable<Int32>), NullableInt32Formatter.Default}, {typeof(Nullable<Int64>), NullableInt64Formatter.Default}, {typeof(Nullable<UInt16>), NullableUInt16Formatter.Default}, {typeof(Nullable<UInt32>), NullableUInt32Formatter.Default}, {typeof(Nullable<UInt64>), NullableUInt64Formatter.Default}, {typeof(Nullable<Single>), NullableSingleFormatter.Default}, {typeof(Nullable<Double>), NullableDoubleFormatter.Default}, {typeof(Nullable<bool>), NullableBooleanFormatter.Default}, {typeof(Nullable<byte>), NullableByteFormatter.Default}, {typeof(Nullable<sbyte>), NullableSByteFormatter.Default}, // StandardClassLibraryFormatter // DateTime {typeof(DateTime), ISO8601DateTimeFormatter.Default}, // ISO8601 {typeof(TimeSpan), ISO8601TimeSpanFormatter.Default}, {typeof(DateTimeOffset), ISO8601DateTimeOffsetFormatter.Default}, {typeof(DateTime?), new StaticNullableFormatter<DateTime>(ISO8601DateTimeFormatter.Default)}, // ISO8601 {typeof(TimeSpan?), new StaticNullableFormatter<TimeSpan>(ISO8601TimeSpanFormatter.Default)}, {typeof(DateTimeOffset?),new StaticNullableFormatter<DateTimeOffset>(ISO8601DateTimeOffsetFormatter.Default)}, {typeof(string), NullableStringFormatter.Default}, {typeof(char), CharFormatter.Default}, {typeof(Nullable<char>), NullableCharFormatter.Default}, {typeof(decimal), DecimalFormatter.Default}, {typeof(decimal?), new StaticNullableFormatter<decimal>(DecimalFormatter.Default)}, {typeof(Guid), GuidFormatter.Default}, {typeof(Guid?), new StaticNullableFormatter<Guid>(GuidFormatter.Default)}, {typeof(Uri), UriFormatter.Default}, {typeof(Version), VersionFormatter.Default}, {typeof(StringBuilder), StringBuilderFormatter.Default}, {typeof(BitArray), BitArrayFormatter.Default}, {typeof(Type), TypeFormatter.Default}, // special primitive {typeof(byte[]), ByteArrayFormatter.Default}, // otpmitized primitive array formatter {typeof(Int16[]), Int16ArrayFormatter.Default}, {typeof(Int32[]), Int32ArrayFormatter.Default}, {typeof(Int64[]), Int64ArrayFormatter.Default}, {typeof(UInt16[]), UInt16ArrayFormatter.Default}, {typeof(UInt32[]), UInt32ArrayFormatter.Default}, {typeof(UInt64[]), UInt64ArrayFormatter.Default}, {typeof(Single[]), SingleArrayFormatter.Default}, {typeof(Double[]), DoubleArrayFormatter.Default}, {typeof(Boolean[]), BooleanArrayFormatter.Default}, {typeof(SByte[]), SByteArrayFormatter.Default}, {typeof(Char[]), CharArrayFormatter.Default}, {typeof(string[]), NullableStringArrayFormatter.Default}, // well known collections {typeof(List<Int16>), new ListFormatter<Int16>()}, {typeof(List<Int32>), new ListFormatter<Int32>()}, {typeof(List<Int64>), new ListFormatter<Int64>()}, {typeof(List<UInt16>), new ListFormatter<UInt16>()}, {typeof(List<UInt32>), new ListFormatter<UInt32>()}, {typeof(List<UInt64>), new ListFormatter<UInt64>()}, {typeof(List<Single>), new ListFormatter<Single>()}, {typeof(List<Double>), new ListFormatter<Double>()}, {typeof(List<Boolean>), new ListFormatter<Boolean>()}, {typeof(List<byte>), new ListFormatter<byte>()}, {typeof(List<SByte>), new ListFormatter<SByte>()}, {typeof(List<DateTime>), new ListFormatter<DateTime>()}, {typeof(List<Char>), new ListFormatter<Char>()}, {typeof(List<string>), new ListFormatter<string>()}, { typeof(ArraySegment<byte>), ByteArraySegmentFormatter.Default }, { typeof(ArraySegment<byte>?),new StaticNullableFormatter<ArraySegment<byte>>(ByteArraySegmentFormatter.Default) }, #if NETSTANDARD {typeof(System.Numerics.BigInteger), BigIntegerFormatter.Default}, {typeof(System.Numerics.BigInteger?), new StaticNullableFormatter<System.Numerics.BigInteger>(BigIntegerFormatter.Default)}, {typeof(System.Numerics.Complex), ComplexFormatter.Default}, {typeof(System.Numerics.Complex?), new StaticNullableFormatter<System.Numerics.Complex>(ComplexFormatter.Default)}, {typeof(System.Dynamic.ExpandoObject), ExpandoObjectFormatter.Default }, {typeof(System.Threading.Tasks.Task), TaskUnitFormatter.Default}, #endif }; internal static object GetFormatter(Type t) { object formatter; if (formatterMap.TryGetValue(t, out formatter)) { return formatter; } return null; } } } }
50.337838
141
0.588591
[ "MIT" ]
aisinker/AkyuiUnity
Assets/AkyuiUnity/Loader/Libraries/Utf8Json/Resolvers/BuiltinResolver.cs
7,452
C#
using System.Collections.Generic; using System.ComponentModel; using GoogleTestAdapter.Common; // ReSharper disable NotResolvedInText namespace GoogleTestAdapter.ProcessExecution { [TypeConverter(typeof(DebuggerKindConverter))] public enum DebuggerKind { VsTestFramework, Native, ManagedAndNative } public static class DebuggerKindExtensions { private static readonly DebuggerKindConverter Converter = new DebuggerKindConverter(); public static string ToReadableString(this DebuggerKind debuggerKind) { return Converter.ConvertToString(debuggerKind); } } public class DebuggerKindConverter : EnumConverterBase<DebuggerKind> { public const string VsTestFramework = "VsTest framework"; public const string Native = "Native"; public const string ManagedAndNative = "Managed and native"; public DebuggerKindConverter() : base(new Dictionary<DebuggerKind, string> { { DebuggerKind.VsTestFramework, VsTestFramework}, { DebuggerKind.Native, Native}, { DebuggerKind.ManagedAndNative, ManagedAndNative}, }) {} } }
31.702703
94
0.709292
[ "Apache-2.0" ]
csoltenborn/GoogleTestAdapter
GoogleTestAdapter/Core/ProcessExecution/DebuggerKind.cs
1,175
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 dms-2016-01-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.DatabaseMigrationService.Model { /// <summary> /// Container for the parameters to the DescribeReplicationTaskAssessmentResults operation. /// Returns the task assessment results from the Amazon S3 bucket that DMS creates in /// your account. This action always returns the latest results. /// /// /// <para> /// For more information about DMS task assessments, see <a href="https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Tasks.AssessmentReport.html">Creating /// a task assessment report</a> in the <a href="https://docs.aws.amazon.com/https:/docs.aws.amazon.com/dms/latest/userguide/Welcome.html"> /// Database Migration Service User Guide</a>. /// </para> /// </summary> public partial class DescribeReplicationTaskAssessmentResultsRequest : AmazonDatabaseMigrationServiceRequest { private string _marker; private int? _maxRecords; private string _replicationTaskArn; /// <summary> /// Gets and sets the property Marker. /// <para> /// An optional pagination token provided by a previous request. If this parameter is /// specified, the response includes only records beyond the marker, up to the value specified /// by <code>MaxRecords</code>. /// </para> /// </summary> public string Marker { get { return this._marker; } set { this._marker = value; } } // Check to see if Marker property is set internal bool IsSetMarker() { return this._marker != null; } /// <summary> /// Gets and sets the property MaxRecords. /// <para> /// The maximum number of records to include in the response. If more records exist than /// the specified <code>MaxRecords</code> value, a pagination token called a marker is /// included in the response so that the remaining results can be retrieved. /// </para> /// /// <para> /// Default: 100 /// </para> /// /// <para> /// Constraints: Minimum 20, maximum 100. /// </para> /// </summary> public int MaxRecords { get { return this._maxRecords.GetValueOrDefault(); } set { this._maxRecords = value; } } // Check to see if MaxRecords property is set internal bool IsSetMaxRecords() { return this._maxRecords.HasValue; } /// <summary> /// Gets and sets the property ReplicationTaskArn. /// <para> /// The Amazon Resource Name (ARN) string that uniquely identifies the task. When this /// input parameter is specified, the API returns only one result and ignore the values /// of the <code>MaxRecords</code> and <code>Marker</code> parameters. /// </para> /// </summary> public string ReplicationTaskArn { get { return this._replicationTaskArn; } set { this._replicationTaskArn = value; } } // Check to see if ReplicationTaskArn property is set internal bool IsSetReplicationTaskArn() { return this._replicationTaskArn != null; } } }
35.618644
161
0.625506
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/DatabaseMigrationService/Generated/Model/DescribeReplicationTaskAssessmentResultsRequest.cs
4,203
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Drawing; using System.Windows.Forms; namespace TouchKB { class LockableTouchKey : GraphicTouchKey { private Bitmap lockedReleasedBmp_ = null; private Bitmap lockedPressedBmp_ = null; public LockableTouchKey(Point Position, int ScanCode, InputLanguage InLang, Bitmap ReleasedBmp, Bitmap PressedBmp, Bitmap LockedReleasedBmp, Bitmap LockedPressedBmp) : base(Position, ScanCode, InLang, ReleasedBmp, PressedBmp) { lockedReleasedBmp_ = LockedReleasedBmp; lockedPressedBmp_ = LockedPressedBmp; } public LockableTouchKey(Point Position, int ScanCode, InputLanguage InLang, Rectangle TxtRect, Bitmap ReleasedBmp, Bitmap PressedBmp, Bitmap LockedReleasedBmp, Bitmap LockedPressedBmp) : base(Position, ScanCode, InLang, TxtRect, ReleasedBmp, PressedBmp) { lockedReleasedBmp_ = LockedReleasedBmp; lockedPressedBmp_ = LockedPressedBmp; } protected override Bitmap DoGetReleasedBmp(bool Locked) { return Locked && lockedReleasedBmp_ != null ? lockedReleasedBmp_ : base.DoGetReleasedBmp(Locked); } protected override Bitmap DoGetPressedBmp(bool Locked) { return Locked && lockedPressedBmp_ != null ? lockedPressedBmp_ : base.DoGetPressedBmp(Locked); } } }
35.673913
109
0.622182
[ "Unlicense" ]
gcardi/TouchKB
TouchKB/LockableTouchKey.cs
1,643
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System.Collections.Generic; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace Microsoft.Bot.Schema.Tests { [TestClass] public class ActivityTest { [TestMethod] public void GetConversationReference() { var activity = CreateActivity(); var conversationReference = activity.GetConversationReference(); Assert.AreEqual(activity.Id, conversationReference.ActivityId); Assert.AreEqual(activity.From.Id, conversationReference.User.Id); Assert.AreEqual(activity.Recipient.Id, conversationReference.Bot.Id); Assert.AreEqual(activity.Conversation.Id, conversationReference.Conversation.Id); Assert.AreEqual(activity.ChannelId, conversationReference.ChannelId); Assert.AreEqual(activity.ServiceUrl, conversationReference.ServiceUrl); } [TestMethod] public void GetReplyConversationReference() { var activity = CreateActivity(); var reply = new ResourceResponse { Id = "1234", }; var conversationReference = activity.GetReplyConversationReference(reply); Assert.AreEqual(reply.Id, conversationReference.ActivityId); Assert.AreEqual(activity.From.Id, conversationReference.User.Id); Assert.AreEqual(activity.Recipient.Id, conversationReference.Bot.Id); Assert.AreEqual(activity.Conversation.Id, conversationReference.Conversation.Id); Assert.AreEqual(activity.ChannelId, conversationReference.ChannelId); Assert.AreEqual(activity.ServiceUrl, conversationReference.ServiceUrl); } [TestMethod] public void RemoveRecipientMention_forTeams() { var activity = CreateActivity(); activity.Text = "<at>firstName</at> lastName\n"; var expectedStrippedName = "lastName"; var mention = new Mention { Mentioned = new ChannelAccount() { Id = activity.Recipient.Id, Name = "firstName", }, Text = null, Type = "mention", }; var lst = new List<Entity>(); var output = JsonConvert.SerializeObject(mention); var entity = JsonConvert.DeserializeObject<Entity>(output); lst.Add(entity); activity.Entities = lst; var strippedActivityText = activity.RemoveRecipientMention(); Assert.AreEqual(strippedActivityText, expectedStrippedName); } [TestMethod] public void RemoveRecipientMention_forNonTeamsScenario() { var activity = CreateActivity(); activity.Text = "<at>firstName</at> lastName\n"; var expectedStrippedName = "lastName"; var mention = new Mention { Mentioned = new ChannelAccount() { Id = activity.Recipient.Id, Name = "<at>firstName</at>", }, Text = "<at>firstName</at>", Type = "mention", }; var lst = new List<Entity>(); var output = JsonConvert.SerializeObject(mention); var entity = JsonConvert.DeserializeObject<Entity>(output); lst.Add(entity); activity.Entities = lst; var strippedActivityText = activity.RemoveRecipientMention(); Assert.AreEqual(strippedActivityText, expectedStrippedName); } [TestMethod] public void ApplyConversationReference_isIncoming() { var activity = CreateActivity(); var conversationReference = new ConversationReference { ChannelId = "cr_123", ServiceUrl = "cr_serviceUrl", Conversation = new ConversationAccount { Id = "cr_456", }, User = new ChannelAccount { Id = "cr_abc", }, Bot = new ChannelAccount { Id = "cr_def", }, ActivityId = "cr_12345", }; activity.ApplyConversationReference(conversationReference, true); Assert.AreEqual(conversationReference.ChannelId, activity.ChannelId); Assert.AreEqual(conversationReference.ServiceUrl, activity.ServiceUrl); Assert.AreEqual(conversationReference.Conversation.Id, activity.Conversation.Id); Assert.AreEqual(conversationReference.User.Id, activity.From.Id); Assert.AreEqual(conversationReference.Bot.Id, activity.Recipient.Id); Assert.AreEqual(conversationReference.ActivityId, activity.Id); } [TestMethod] public void ApplyConversationReference() { var activity = CreateActivity(); var conversationReference = new ConversationReference { ChannelId = "123", ServiceUrl = "serviceUrl", Conversation = new ConversationAccount { Id = "456", }, User = new ChannelAccount { Id = "abc", }, Bot = new ChannelAccount { Id = "def", }, ActivityId = "12345", }; activity.ApplyConversationReference(conversationReference, false); Assert.AreEqual(conversationReference.ChannelId, activity.ChannelId); Assert.AreEqual(conversationReference.ServiceUrl, activity.ServiceUrl); Assert.AreEqual(conversationReference.Conversation.Id, activity.Conversation.Id); Assert.AreEqual(conversationReference.Bot.Id, activity.From.Id); Assert.AreEqual(conversationReference.User.Id, activity.Recipient.Id); Assert.AreEqual(conversationReference.ActivityId, activity.ReplyToId); } [TestMethod] public void CreateTraceAllowsNullRecipient() { // https://github.com/Microsoft/botbuilder-dotnet/issues/1580 var activity = CreateActivity(); activity.Recipient = null; var trace = activity.CreateTrace("test"); // CreateTrace flips Recipient and From Assert.IsNull(trace.From.Id); } private Activity CreateActivity() { var account1 = new ChannelAccount { Id = "ChannelAccount_Id_1", Name = "ChannelAccount_Name_1", Properties = new JObject { { "Name", "Value" } }, Role = "ChannelAccount_Role_1", }; var account2 = new ChannelAccount { Id = "ChannelAccount_Id_2", Name = "ChannelAccount_Name_2", Properties = new JObject { { "Name", "Value" } }, Role = "ChannelAccount_Role_2", }; var conversationAccount = new ConversationAccount { ConversationType = "a", Id = "123", IsGroup = true, Name = "Name", Properties = new JObject { { "Name", "Value" } }, Role = "ConversationAccount_Role", }; var activity = new Activity { Id = "123", From = account1, Recipient = account2, Conversation = conversationAccount, ChannelId = "ChannelId123", ServiceUrl = "ServiceUrl123", }; return activity; } } }
35.406114
93
0.553774
[ "MIT" ]
swagatmishra2007/botbuilder-dotnet
tests/Microsoft.Bot.Schema.Tests/ActivityTest.cs
8,110
C#
using System.Threading; using MyAdb.Commands; namespace MyAdb { public class MultiThreadObject { private static MultiThreadObject _instance; private static readonly object _lockFlag = new object(); private readonly ManualResetEvent _event; private int _count; private int _result = Command.OK; public static MultiThreadObject Instance { get { lock (_lockFlag) { if (_instance == null) _instance = new MultiThreadObject(); } return _instance; } } protected MultiThreadObject() { _event = new ManualResetEvent(false); } public void Start(int count) { _count = count; } public void CommandFinish(int commandResult) { lock (_lockFlag) { _count--; if (commandResult != Command.OK) { _result = commandResult; Utils.BeepIfCan(); } if (_count == 0) _event.Set(); } } public int Wait() { _event.WaitOne(); _event.Close(); return _result; } } }
22.03125
64
0.446099
[ "Apache-2.0" ]
yshinkarev/MyAdb
MultiThreadObject.cs
1,412
C#
using System.ServiceModel; using System.ServiceModel.Channels; namespace ServiceStack.ServiceClient.Web { [ServiceContract(Namespace = "http://services.servicestack.net/", CallbackContract = typeof(IDuplexCallback))] public interface IDuplex { [OperationContract(Action = "*", ReplyAction = "*")] void BeginSend(Message msg); } }
31.083333
115
0.691689
[ "BSD-3-Clause" ]
bcuff/ServiceStack
src/ServiceStack.Common/ServiceClient.Web/IDuplex.cs
373
C#
using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Tbs.EntityFrameworkCore; using Abp.Authorization; using Abp.BackgroundJobs; using Abp.Notifications; namespace Tbs.Migrations { [DbContext(typeof(TbsDbContext))] [Migration("20170721012248_m4")] partial class m4 { protected override void BuildTargetModel(ModelBuilder modelBuilder) { modelBuilder .HasAnnotation("ProductVersion", "1.1.1") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("Abp.Application.Editions.Edition", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<string>("DisplayName") .IsRequired() .HasMaxLength(64); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("Name") .IsRequired() .HasMaxLength(32); b.HasKey("Id"); b.ToTable("AbpEditions"); }); modelBuilder.Entity("Abp.Application.Features.FeatureSetting", b => { b.Property<long>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<string>("Discriminator") .IsRequired(); b.Property<string>("Name") .IsRequired() .HasMaxLength(128); b.Property<string>("Value") .IsRequired() .HasMaxLength(2000); b.HasKey("Id"); b.ToTable("AbpFeatures"); b.HasDiscriminator<string>("Discriminator").HasValue("FeatureSetting"); }); modelBuilder.Entity("Abp.Auditing.AuditLog", b => { b.Property<long>("Id") .ValueGeneratedOnAdd(); b.Property<string>("BrowserInfo") .HasMaxLength(256); b.Property<string>("ClientIpAddress") .HasMaxLength(64); b.Property<string>("ClientName") .HasMaxLength(128); b.Property<string>("CustomData") .HasMaxLength(2000); b.Property<string>("Exception") .HasMaxLength(2000); b.Property<int>("ExecutionDuration"); b.Property<DateTime>("ExecutionTime"); b.Property<int?>("ImpersonatorTenantId"); b.Property<long?>("ImpersonatorUserId"); b.Property<string>("MethodName") .HasMaxLength(256); b.Property<string>("Parameters") .HasMaxLength(1024); b.Property<string>("ServiceName") .HasMaxLength(256); b.Property<int?>("TenantId"); b.Property<long?>("UserId"); b.HasKey("Id"); b.HasIndex("TenantId", "ExecutionDuration"); b.HasIndex("TenantId", "ExecutionTime"); b.HasIndex("TenantId", "UserId"); b.ToTable("AbpAuditLogs"); }); modelBuilder.Entity("Abp.Authorization.PermissionSetting", b => { b.Property<long>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<string>("Discriminator") .IsRequired(); b.Property<bool>("IsGranted"); b.Property<string>("Name") .IsRequired() .HasMaxLength(128); b.Property<int?>("TenantId"); b.HasKey("Id"); b.HasIndex("TenantId", "Name"); b.ToTable("AbpPermissions"); b.HasDiscriminator<string>("Discriminator").HasValue("PermissionSetting"); }); modelBuilder.Entity("Abp.Authorization.Roles.RoleClaim", b => { b.Property<long>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<int>("RoleId"); b.Property<int?>("TenantId"); b.Property<int?>("UserId"); b.HasKey("Id"); b.HasIndex("RoleId"); b.HasIndex("UserId"); b.HasIndex("TenantId", "ClaimType"); b.ToTable("AbpRoleClaims"); }); modelBuilder.Entity("Abp.Authorization.Users.UserAccount", b => { b.Property<long>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<string>("EmailAddress"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastLoginTime"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<int?>("TenantId"); b.Property<long>("UserId"); b.Property<long?>("UserLinkId"); b.Property<string>("UserName"); b.HasKey("Id"); b.HasIndex("EmailAddress"); b.HasIndex("UserName"); b.HasIndex("TenantId", "EmailAddress"); b.HasIndex("TenantId", "UserId"); b.HasIndex("TenantId", "UserName"); b.ToTable("AbpUserAccounts"); }); modelBuilder.Entity("Abp.Authorization.Users.UserClaim", b => { b.Property<long>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<int?>("TenantId"); b.Property<long>("UserId"); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "ClaimType"); b.ToTable("AbpUserClaims"); }); modelBuilder.Entity("Abp.Authorization.Users.UserLogin", b => { b.Property<long>("Id") .ValueGeneratedOnAdd(); b.Property<string>("LoginProvider") .IsRequired() .HasMaxLength(128); b.Property<string>("ProviderKey") .IsRequired() .HasMaxLength(256); b.Property<int?>("TenantId"); b.Property<long>("UserId"); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "UserId"); b.HasIndex("TenantId", "LoginProvider", "ProviderKey"); b.ToTable("AbpUserLogins"); }); modelBuilder.Entity("Abp.Authorization.Users.UserLoginAttempt", b => { b.Property<long>("Id") .ValueGeneratedOnAdd(); b.Property<string>("BrowserInfo") .HasMaxLength(256); b.Property<string>("ClientIpAddress") .HasMaxLength(64); b.Property<string>("ClientName") .HasMaxLength(128); b.Property<DateTime>("CreationTime"); b.Property<byte>("Result"); b.Property<string>("TenancyName") .HasMaxLength(64); b.Property<int?>("TenantId"); b.Property<long?>("UserId"); b.Property<string>("UserNameOrEmailAddress") .HasMaxLength(255); b.HasKey("Id"); b.HasIndex("UserId", "TenantId"); b.HasIndex("TenancyName", "UserNameOrEmailAddress", "Result"); b.ToTable("AbpUserLoginAttempts"); }); modelBuilder.Entity("Abp.Authorization.Users.UserOrganizationUnit", b => { b.Property<long>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long>("OrganizationUnitId"); b.Property<int?>("TenantId"); b.Property<long>("UserId"); b.HasKey("Id"); b.HasIndex("TenantId", "OrganizationUnitId"); b.HasIndex("TenantId", "UserId"); b.ToTable("AbpUserOrganizationUnits"); }); modelBuilder.Entity("Abp.Authorization.Users.UserRole", b => { b.Property<long>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<int>("RoleId"); b.Property<int?>("TenantId"); b.Property<long>("UserId"); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "RoleId"); b.HasIndex("TenantId", "UserId"); b.ToTable("AbpUserRoles"); }); modelBuilder.Entity("Abp.Authorization.Users.UserToken", b => { b.Property<long>("Id") .ValueGeneratedOnAdd(); b.Property<string>("LoginProvider"); b.Property<string>("Name"); b.Property<int?>("TenantId"); b.Property<long>("UserId"); b.Property<string>("Value"); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "UserId"); b.ToTable("AbpUserTokens"); }); modelBuilder.Entity("Abp.BackgroundJobs.BackgroundJobInfo", b => { b.Property<long>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<bool>("IsAbandoned"); b.Property<string>("JobArgs") .IsRequired() .HasMaxLength(1048576); b.Property<string>("JobType") .IsRequired() .HasMaxLength(512); b.Property<DateTime?>("LastTryTime"); b.Property<DateTime>("NextTryTime"); b.Property<byte>("Priority"); b.Property<short>("TryCount"); b.HasKey("Id"); b.HasIndex("IsAbandoned", "NextTryTime"); b.ToTable("AbpBackgroundJobs"); }); modelBuilder.Entity("Abp.Configuration.Setting", b => { b.Property<long>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("Name") .IsRequired() .HasMaxLength(256); b.Property<int?>("TenantId"); b.Property<long?>("UserId"); b.Property<string>("Value") .HasMaxLength(2000); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "Name"); b.ToTable("AbpSettings"); }); modelBuilder.Entity("Abp.Localization.ApplicationLanguage", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<string>("DisplayName") .IsRequired() .HasMaxLength(64); b.Property<string>("Icon") .HasMaxLength(128); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("Name") .IsRequired() .HasMaxLength(10); b.Property<int?>("TenantId"); b.HasKey("Id"); b.HasIndex("TenantId", "Name"); b.ToTable("AbpLanguages"); }); modelBuilder.Entity("Abp.Localization.ApplicationLanguageText", b => { b.Property<long>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<string>("Key") .IsRequired() .HasMaxLength(256); b.Property<string>("LanguageName") .IsRequired() .HasMaxLength(10); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("Source") .IsRequired() .HasMaxLength(128); b.Property<int?>("TenantId"); b.Property<string>("Value") .IsRequired() .HasMaxLength(67108864); b.HasKey("Id"); b.HasIndex("TenantId", "Source", "LanguageName", "Key"); b.ToTable("AbpLanguageTexts"); }); modelBuilder.Entity("Abp.Notifications.NotificationInfo", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<string>("Data") .HasMaxLength(1048576); b.Property<string>("DataTypeName") .HasMaxLength(512); b.Property<string>("EntityId") .HasMaxLength(96); b.Property<string>("EntityTypeAssemblyQualifiedName") .HasMaxLength(512); b.Property<string>("EntityTypeName") .HasMaxLength(250); b.Property<string>("ExcludedUserIds") .HasMaxLength(131072); b.Property<string>("NotificationName") .IsRequired() .HasMaxLength(96); b.Property<byte>("Severity"); b.Property<string>("TenantIds") .HasMaxLength(131072); b.Property<string>("UserIds") .HasMaxLength(131072); b.HasKey("Id"); b.ToTable("AbpNotifications"); }); modelBuilder.Entity("Abp.Notifications.NotificationSubscriptionInfo", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<string>("EntityId") .HasMaxLength(96); b.Property<string>("EntityTypeAssemblyQualifiedName") .HasMaxLength(512); b.Property<string>("EntityTypeName") .HasMaxLength(250); b.Property<string>("NotificationName") .HasMaxLength(96); b.Property<int?>("TenantId"); b.Property<long>("UserId"); b.HasKey("Id"); b.HasIndex("NotificationName", "EntityTypeName", "EntityId", "UserId"); b.HasIndex("TenantId", "NotificationName", "EntityTypeName", "EntityId", "UserId"); b.ToTable("AbpNotificationSubscriptions"); }); modelBuilder.Entity("Abp.Notifications.TenantNotificationInfo", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<string>("Data") .HasMaxLength(1048576); b.Property<string>("DataTypeName") .HasMaxLength(512); b.Property<string>("EntityId") .HasMaxLength(96); b.Property<string>("EntityTypeAssemblyQualifiedName") .HasMaxLength(512); b.Property<string>("EntityTypeName") .HasMaxLength(250); b.Property<string>("NotificationName") .IsRequired() .HasMaxLength(96); b.Property<byte>("Severity"); b.Property<int?>("TenantId"); b.HasKey("Id"); b.HasIndex("TenantId"); b.ToTable("AbpTenantNotifications"); }); modelBuilder.Entity("Abp.Notifications.UserNotificationInfo", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<int>("State"); b.Property<int?>("TenantId"); b.Property<Guid>("TenantNotificationId"); b.Property<long>("UserId"); b.HasKey("Id"); b.HasIndex("UserId", "State", "CreationTime"); b.ToTable("AbpUserNotifications"); }); modelBuilder.Entity("Abp.Organizations.OrganizationUnit", b => { b.Property<long>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Code") .IsRequired() .HasMaxLength(95); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<string>("DisplayName") .IsRequired() .HasMaxLength(128); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<long?>("ParentId"); b.Property<int?>("TenantId"); b.HasKey("Id"); b.HasIndex("ParentId"); b.HasIndex("TenantId", "Code"); b.ToTable("AbpOrganizationUnits"); }); modelBuilder.Entity("Tbs.Authorization.Roles.Role", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<string>("DisplayName") .IsRequired() .HasMaxLength(64); b.Property<bool>("IsDefault"); b.Property<bool>("IsDeleted"); b.Property<bool>("IsStatic"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("Name") .IsRequired() .HasMaxLength(32); b.Property<string>("NormalizedName") .IsRequired() .HasMaxLength(32); b.Property<int?>("TenantId"); b.HasKey("Id"); b.HasIndex("CreatorUserId"); b.HasIndex("DeleterUserId"); b.HasIndex("LastModifierUserId"); b.HasIndex("TenantId", "NormalizedName"); b.ToTable("AbpRoles"); }); modelBuilder.Entity("Tbs.Authorization.Users.User", b => { b.Property<long>("Id") .ValueGeneratedOnAdd(); b.Property<int>("AccessFailedCount"); b.Property<string>("AuthenticationSource") .HasMaxLength(64); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<bool>("DepotSide"); b.Property<string>("EmailAddress") .IsRequired() .HasMaxLength(256); b.Property<string>("EmailConfirmationCode") .HasMaxLength(328); b.Property<bool>("IsActive"); b.Property<bool>("IsDeleted"); b.Property<bool>("IsEmailConfirmed"); b.Property<bool>("IsLockoutEnabled"); b.Property<bool>("IsPhoneNumberConfirmed"); b.Property<bool>("IsTwoFactorEnabled"); b.Property<DateTime?>("LastLoginTime"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<DateTime?>("LockoutEndDateUtc"); b.Property<string>("Name") .IsRequired() .HasMaxLength(32); b.Property<string>("NormalizedEmailAddress") .IsRequired() .HasMaxLength(256); b.Property<string>("NormalizedUserName") .IsRequired() .HasMaxLength(32); b.Property<string>("OperatePassword") .HasMaxLength(20); b.Property<string>("Password") .IsRequired() .HasMaxLength(128); b.Property<string>("PasswordResetCode") .HasMaxLength(328); b.Property<string>("PhoneNumber"); b.Property<string>("RoleName") .HasMaxLength(32); b.Property<string>("SecurityStamp"); b.Property<string>("Surname") .IsRequired() .HasMaxLength(32); b.Property<int?>("TenantId"); b.Property<string>("UserName") .IsRequired() .HasMaxLength(32); b.Property<string>("WhName") .HasMaxLength(8); b.HasKey("Id"); b.HasIndex("CreatorUserId"); b.HasIndex("DeleterUserId"); b.HasIndex("LastModifierUserId"); b.HasIndex("TenantId", "NormalizedEmailAddress"); b.HasIndex("TenantId", "NormalizedUserName"); b.ToTable("AbpUsers"); }); modelBuilder.Entity("Tbs.DomainModels.Article", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int?>("ArticleRecordId"); b.Property<int?>("ArticleRecordId1"); b.Property<int>("ArticleTypeId"); b.Property<string>("BindInfo") .HasMaxLength(20); b.Property<string>("Cn") .IsRequired() .HasMaxLength(10); b.Property<int>("DepotId"); b.Property<string>("Name") .IsRequired() .HasMaxLength(20); b.Property<string>("Rfid") .HasMaxLength(20); b.Property<int>("TenantId"); b.HasKey("Id"); b.HasIndex("ArticleRecordId1"); b.HasIndex("ArticleTypeId"); b.HasIndex("DepotId"); b.ToTable("Articles"); }); modelBuilder.Entity("Tbs.DomainModels.ArticleRecord", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int>("ArticleId"); b.Property<int>("DepotId"); b.Property<DateTime>("LendTime"); b.Property<string>("Remark") .HasMaxLength(250); b.Property<DateTime?>("ReturnTime"); b.Property<int>("TenantId"); b.Property<string>("WorkerCn") .IsRequired() .HasMaxLength(8); b.Property<int>("WorkerId"); b.Property<string>("WorkerName") .IsRequired() .HasMaxLength(8); b.HasKey("Id"); b.HasIndex("DepotId"); b.HasIndex("TenantId", "DepotId", "ArticleId"); b.ToTable("ArticleRecords"); }); modelBuilder.Entity("Tbs.DomainModels.ArticleType", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("BindTo") .HasMaxLength(1); b.Property<string>("Cn") .IsRequired() .HasMaxLength(1); b.Property<string>("Name") .IsRequired() .HasMaxLength(8); b.Property<int>("TenantId"); b.HasKey("Id"); b.ToTable("ArticleTypes"); }); modelBuilder.Entity("Tbs.DomainModels.DaySettle", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CarryoutDate"); b.Property<int>("DepotId"); b.Property<string>("Message") .HasMaxLength(200); b.Property<DateTime>("OperateTime"); b.Property<int?>("RoutesCount"); b.Property<int>("TenantId"); b.Property<int?>("VtAffairsCount"); b.HasKey("Id"); b.HasIndex("DepotId"); b.HasIndex("TenantId", "DepotId", "CarryoutDate"); b.ToTable("DaySettles"); }); modelBuilder.Entity("Tbs.DomainModels.Depot", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Cn") .IsRequired() .HasMaxLength(2); b.Property<double?>("Latitude"); b.Property<double?>("Longitude"); b.Property<string>("Name") .IsRequired() .HasMaxLength(8); b.Property<int>("TenantId"); b.Property<bool>("UseRouteForIdentify"); b.HasKey("Id"); b.ToTable("Depots"); }); modelBuilder.Entity("Tbs.DomainModels.DepotFeature", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int>("DepotId"); b.Property<double?>("Latitude"); b.Property<string>("Name") .IsRequired() .HasMaxLength(8); b.Property<string>("Value"); b.HasKey("Id"); b.ToTable("DepotFeatures"); }); modelBuilder.Entity("Tbs.DomainModels.DepotSetting", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int>("DepotId"); b.Property<string>("Name") .IsRequired() .HasMaxLength(8); b.Property<string>("Value"); b.HasKey("Id"); b.ToTable("DepotSettings"); }); modelBuilder.Entity("Tbs.DomainModels.DepotSignin", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int>("DepotId"); b.Property<string>("EndTime") .IsRequired() .HasMaxLength(5); b.Property<string>("LateTime") .IsRequired() .HasMaxLength(5); b.Property<string>("Name") .IsRequired() .HasMaxLength(8); b.Property<string>("StartTime") .IsRequired() .HasMaxLength(5); b.Property<int>("TenantId"); b.HasKey("Id"); b.HasIndex("DepotId"); b.ToTable("DepotSignins"); }); modelBuilder.Entity("Tbs.DomainModels.Manager", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Cn") .IsRequired() .HasMaxLength(8); b.Property<string>("Mobile") .HasMaxLength(11); b.Property<string>("Name") .IsRequired() .HasMaxLength(8); b.Property<int>("TenantId"); b.HasKey("Id"); b.ToTable("Managers"); }); modelBuilder.Entity("Tbs.DomainModels.Outlet", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Ciphertext") .HasMaxLength(10); b.Property<string>("Cn") .IsRequired() .HasMaxLength(8); b.Property<int?>("CustomerId"); b.Property<int?>("DepotId"); b.Property<double?>("Latitude"); b.Property<double?>("Longitude"); b.Property<string>("Name") .IsRequired() .HasMaxLength(20); b.Property<string>("Password") .HasMaxLength(10); b.Property<int>("TenantId"); b.HasKey("Id"); b.HasIndex("DepotId"); b.HasIndex("TenantId", "Cn") .IsUnique(); b.ToTable("Outlets"); }); modelBuilder.Entity("Tbs.DomainModels.PreRoute", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int>("DepotId"); b.Property<string>("Remark") .HasMaxLength(50); b.Property<string>("ReturnTime") .IsRequired() .HasMaxLength(5); b.Property<string>("RouteCn") .IsRequired() .HasMaxLength(8); b.Property<string>("RouteName") .IsRequired() .HasMaxLength(20); b.Property<int>("RouteTypeId"); b.Property<string>("SetoutTime") .IsRequired() .HasMaxLength(5); b.Property<int>("TenantId"); b.Property<int?>("VehicleId"); b.HasKey("Id"); b.HasIndex("DepotId"); b.HasIndex("VehicleId"); b.HasIndex("TenantId", "DepotId", "RouteTypeId"); b.ToTable("PreRoutes"); }); modelBuilder.Entity("Tbs.DomainModels.PreRouteTask", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ArriveTime") .IsRequired() .HasMaxLength(5); b.Property<int>("OutletId"); b.Property<int>("PreRouteId"); b.Property<int>("TaskTypeId"); b.HasKey("Id"); b.HasIndex("OutletId"); b.HasIndex("PreRouteId"); b.HasIndex("TaskTypeId"); b.ToTable("PreRouteTasks"); }); modelBuilder.Entity("Tbs.DomainModels.Route", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CarryoutDate"); b.Property<int>("DepotId"); b.Property<string>("Remark") .HasMaxLength(50); b.Property<string>("ReturnTime") .IsRequired() .HasMaxLength(5); b.Property<string>("RouteCn") .IsRequired() .HasMaxLength(8); b.Property<string>("RouteName") .IsRequired() .HasMaxLength(20); b.Property<int>("RouteTypeId"); b.Property<string>("SetoutTime") .IsRequired() .HasMaxLength(5); b.Property<string>("Status") .IsRequired() .HasMaxLength(2); b.Property<int>("TenantId"); b.Property<int?>("VehicleId") .IsRequired(); b.HasKey("Id"); b.HasIndex("DepotId"); b.HasIndex("TenantId", "DepotId", "CarryoutDate"); b.ToTable("Routes"); }); modelBuilder.Entity("Tbs.DomainModels.RouteIdentify", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("IdentifyTime"); b.Property<int>("OutletId"); b.Property<int>("RouteId"); b.HasKey("Id"); b.HasIndex("OutletId"); b.ToTable("RouteIdentifies"); }); modelBuilder.Entity("Tbs.DomainModels.RouteLog", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ActionName") .IsRequired() .HasMaxLength(8); b.Property<string>("Message") .HasMaxLength(200); b.Property<DateTime>("OperateTime"); b.Property<int>("RouteId"); b.Property<long>("UserId"); b.HasKey("Id"); b.ToTable("RouteLogs"); }); modelBuilder.Entity("Tbs.DomainModels.RouteRole", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ArticleTypeList") .HasMaxLength(50); b.Property<string>("Name") .IsRequired() .HasMaxLength(8); b.Property<string>("PeerGroupNo"); b.Property<bool>("Required"); b.Property<int>("RouteTypeId"); b.HasKey("Id"); b.HasIndex("RouteTypeId"); b.ToTable("RouteRoles"); }); modelBuilder.Entity("Tbs.DomainModels.RouteTask", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ArriveTime") .IsRequired() .HasMaxLength(5); b.Property<DateTime?>("IdentifyTime"); b.Property<int>("OutletId"); b.Property<int?>("Qtum"); b.Property<string>("Remark") .HasMaxLength(50); b.Property<int>("RouteId"); b.Property<int>("TaskTypeId"); b.HasKey("Id"); b.HasIndex("OutletId"); b.HasIndex("RouteId"); b.HasIndex("TaskTypeId"); b.ToTable("RouteTasks"); }); modelBuilder.Entity("Tbs.DomainModels.RouteType", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int>("ActivateAhead"); b.Property<int>("ArticleAhead"); b.Property<int>("ArticleDeadline"); b.Property<string>("EarliestTime") .IsRequired() .HasMaxLength(5); b.Property<string>("IdentifyRoleName") .HasMaxLength(8); b.Property<string>("LatestTime") .IsRequired() .HasMaxLength(5); b.Property<string>("Name") .IsRequired() .HasMaxLength(8); b.Property<bool>("NeedApproval"); b.Property<string>("SetoutRoleName") .HasMaxLength(8); b.Property<int>("TenantId"); b.HasKey("Id"); b.ToTable("RouteTypes"); }); modelBuilder.Entity("Tbs.DomainModels.RouteWorker", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime?>("LendTime"); b.Property<string>("RecordList") .HasMaxLength(50); b.Property<DateTime?>("ReturnTime"); b.Property<int>("RouteId"); b.Property<int>("RouteRoleId"); b.Property<string>("RouteRoleName") .IsRequired() .HasMaxLength(8); b.Property<string>("WorkerCn") .IsRequired() .HasMaxLength(8); b.Property<int>("WorkerId"); b.Property<string>("WorkerName") .IsRequired() .HasMaxLength(8); b.HasKey("Id"); b.HasIndex("RouteId"); b.ToTable("RouteWorkers"); }); modelBuilder.Entity("Tbs.DomainModels.Signin", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CarryoutDate"); b.Property<int>("DepotId"); b.Property<int>("LateDistance"); b.Property<string>("Name") .IsRequired() .HasMaxLength(8); b.Property<DateTime>("SigninTime"); b.Property<int>("TenantId"); b.Property<string>("Worker") .IsRequired() .HasMaxLength(20); b.HasKey("Id"); b.HasIndex("DepotId"); b.HasIndex("TenantId", "DepotId", "CarryoutDate", "Name"); b.ToTable("Signins"); }); modelBuilder.Entity("Tbs.DomainModels.TaskType", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int>("BasicPrice"); b.Property<string>("Cn") .IsRequired() .HasMaxLength(2); b.Property<string>("GroupName") .HasMaxLength(8); b.Property<string>("Name") .IsRequired() .HasMaxLength(8); b.Property<int>("TenantId"); b.HasKey("Id"); b.ToTable("TaskTypes"); }); modelBuilder.Entity("Tbs.DomainModels.Vault", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int>("DepotId"); b.Property<string>("Name") .IsRequired() .HasMaxLength(8); b.Property<int>("TenantId"); b.Property<int>("WarehouseId"); b.HasKey("Id"); b.HasIndex("DepotId"); b.ToTable("Vaults"); }); modelBuilder.Entity("Tbs.DomainModels.VaultRole", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Name") .IsRequired() .HasMaxLength(8); b.Property<bool>("Required"); b.Property<bool>("Single"); b.Property<int>("VaultTypeId"); b.HasKey("Id"); b.HasIndex("VaultTypeId"); b.ToTable("VaultRoles"); }); modelBuilder.Entity("Tbs.DomainModels.VaultType", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int>("ActivateAhead"); b.Property<string>("EarliestTime") .IsRequired() .HasMaxLength(5); b.Property<string>("LatestTime") .IsRequired() .HasMaxLength(5); b.Property<string>("Name") .IsRequired() .HasMaxLength(8); b.Property<bool>("NeedApproval"); b.Property<int>("TenantId"); b.Property<int>("VerifyAhead"); b.Property<int>("VerifyDeadline"); b.HasKey("Id"); b.ToTable("VaultTypes"); }); modelBuilder.Entity("Tbs.DomainModels.Vehicle", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Cn") .IsRequired() .HasMaxLength(8); b.Property<int>("DepotId"); b.Property<string>("License") .IsRequired() .HasMaxLength(7); b.Property<int?>("MainWorkerId"); b.Property<byte[]>("Photo"); b.Property<int?>("SubWorkerId"); b.Property<int>("TenantId"); b.Property<int?>("Worker1Id"); b.Property<int?>("Worker2Id"); b.Property<int?>("Worker3Id"); b.Property<int?>("Worker4Id"); b.Property<int?>("Worker5Id"); b.Property<int?>("Worker6Id"); b.HasKey("Id"); b.HasIndex("DepotId"); b.HasIndex("TenantId", "Cn") .IsUnique(); b.ToTable("Vehicles"); }); modelBuilder.Entity("Tbs.DomainModels.VtAffair", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CarryoutDate"); b.Property<int>("DepotId"); b.Property<string>("EndTime") .IsRequired() .HasMaxLength(5); b.Property<DateTime>("LastActiveTime"); b.Property<string>("Remark") .HasMaxLength(50); b.Property<string>("StartTime") .IsRequired() .HasMaxLength(5); b.Property<string>("Status") .IsRequired() .HasMaxLength(2); b.Property<int>("TenantId"); b.Property<int>("VaultTypeId"); b.Property<string>("VtName") .IsRequired() .HasMaxLength(8); b.HasKey("Id"); b.HasIndex("DepotId"); b.HasIndex("TenantId", "DepotId", "CarryoutDate"); b.ToTable("VtAffairs"); }); modelBuilder.Entity("Tbs.DomainModels.VtAffairWorker", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime?>("CheckIn"); b.Property<DateTime?>("CheckOut"); b.Property<int>("VaultRoleId"); b.Property<string>("VaultRoleName") .IsRequired() .HasMaxLength(8); b.Property<int>("VtAffairId"); b.Property<string>("WorkerCn") .IsRequired() .HasMaxLength(8); b.Property<int>("WorkerId"); b.Property<string>("WorkerName") .IsRequired() .HasMaxLength(8); b.HasKey("Id"); b.HasIndex("VtAffairId"); b.ToTable("VtAffairWorkers"); }); modelBuilder.Entity("Tbs.DomainModels.Warehouse", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ArticleTypeList") .HasMaxLength(50); b.Property<int>("DepotId"); b.Property<string>("DepotList") .HasMaxLength(100); b.Property<string>("Name") .IsRequired() .HasMaxLength(8); b.Property<string>("ShiftList") .HasMaxLength(50); b.Property<int>("TenantId"); b.HasKey("Id"); b.HasIndex("DepotId"); b.ToTable("Warehouses"); }); modelBuilder.Entity("Tbs.DomainModels.WhAffair", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CarryoutDate"); b.Property<int>("DepotId"); b.Property<string>("EndTime") .IsRequired() .HasMaxLength(5); b.Property<DateTime>("LastActiveTime"); b.Property<string>("Remark") .HasMaxLength(50); b.Property<string>("StartTime") .IsRequired() .HasMaxLength(5); b.Property<string>("Status") .IsRequired() .HasMaxLength(2); b.Property<int>("TenantId"); b.Property<string>("WhName") .IsRequired() .HasMaxLength(8); b.HasKey("Id"); b.HasIndex("DepotId"); b.HasIndex("TenantId", "DepotId", "CarryoutDate"); b.ToTable("WhAffairs"); }); modelBuilder.Entity("Tbs.DomainModels.WhAffairWorker", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime?>("CheckIn"); b.Property<DateTime?>("CheckOut"); b.Property<int>("WhAffairId"); b.Property<string>("WorkerCn") .IsRequired() .HasMaxLength(8); b.Property<int>("WorkerId"); b.Property<string>("WorkerName") .IsRequired() .HasMaxLength(8); b.HasKey("Id"); b.HasIndex("WhAffairId"); b.ToTable("WhAffairWorkers"); }); modelBuilder.Entity("Tbs.DomainModels.Worker", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Cn") .IsRequired() .HasMaxLength(8); b.Property<int>("DepotId"); b.Property<string>("DeviceId") .HasMaxLength(50); b.Property<string>("Finger") .HasMaxLength(1024); b.Property<string>("IDCardNo") .HasMaxLength(18); b.Property<string>("IDNumber") .HasMaxLength(18); b.Property<string>("Mobile") .HasMaxLength(11); b.Property<string>("Name") .IsRequired() .HasMaxLength(8); b.Property<string>("Password") .HasMaxLength(10); b.Property<byte[]>("Photo"); b.Property<int>("TenantId"); b.HasKey("Id"); b.HasIndex("DepotId"); b.HasIndex("TenantId", "Cn") .IsUnique(); b.ToTable("Workers"); }); modelBuilder.Entity("Tbs.MultiTenancy.Tenant", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ConnectionString") .HasMaxLength(1024); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<int?>("EditionId"); b.Property<bool>("IsActive"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("Name") .IsRequired() .HasMaxLength(128); b.Property<string>("TenancyName") .IsRequired() .HasMaxLength(64); b.HasKey("Id"); b.HasIndex("CreatorUserId"); b.HasIndex("DeleterUserId"); b.HasIndex("EditionId"); b.HasIndex("LastModifierUserId"); b.HasIndex("TenancyName"); b.ToTable("AbpTenants"); }); modelBuilder.Entity("Abp.Application.Features.EditionFeatureSetting", b => { b.HasBaseType("Abp.Application.Features.FeatureSetting"); b.Property<int>("EditionId"); b.HasIndex("EditionId", "Name"); b.ToTable("AbpFeatures"); b.HasDiscriminator().HasValue("EditionFeatureSetting"); }); modelBuilder.Entity("Abp.MultiTenancy.TenantFeatureSetting", b => { b.HasBaseType("Abp.Application.Features.FeatureSetting"); b.Property<int>("TenantId"); b.HasIndex("TenantId", "Name"); b.ToTable("AbpFeatures"); b.HasDiscriminator().HasValue("TenantFeatureSetting"); }); modelBuilder.Entity("Abp.Authorization.Roles.RolePermissionSetting", b => { b.HasBaseType("Abp.Authorization.PermissionSetting"); b.Property<int>("RoleId"); b.HasIndex("RoleId"); b.ToTable("AbpPermissions"); b.HasDiscriminator().HasValue("RolePermissionSetting"); }); modelBuilder.Entity("Abp.Authorization.Users.UserPermissionSetting", b => { b.HasBaseType("Abp.Authorization.PermissionSetting"); b.Property<long>("UserId"); b.HasIndex("UserId"); b.ToTable("AbpPermissions"); b.HasDiscriminator().HasValue("UserPermissionSetting"); }); modelBuilder.Entity("Abp.Authorization.Roles.RoleClaim", b => { b.HasOne("Tbs.Authorization.Roles.Role") .WithMany("Claims") .HasForeignKey("UserId"); }); modelBuilder.Entity("Abp.Authorization.Users.UserClaim", b => { b.HasOne("Tbs.Authorization.Users.User") .WithMany("Claims") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Users.UserLogin", b => { b.HasOne("Tbs.Authorization.Users.User") .WithMany("Logins") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Users.UserRole", b => { b.HasOne("Tbs.Authorization.Users.User") .WithMany("Roles") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Users.UserToken", b => { b.HasOne("Tbs.Authorization.Users.User") .WithMany("Tokens") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Configuration.Setting", b => { b.HasOne("Tbs.Authorization.Users.User") .WithMany("Settings") .HasForeignKey("UserId"); }); modelBuilder.Entity("Abp.Organizations.OrganizationUnit", b => { b.HasOne("Abp.Organizations.OrganizationUnit", "Parent") .WithMany("Children") .HasForeignKey("ParentId"); }); modelBuilder.Entity("Tbs.Authorization.Roles.Role", b => { b.HasOne("Tbs.Authorization.Users.User", "CreatorUser") .WithMany() .HasForeignKey("CreatorUserId"); b.HasOne("Tbs.Authorization.Users.User", "DeleterUser") .WithMany() .HasForeignKey("DeleterUserId"); b.HasOne("Tbs.Authorization.Users.User", "LastModifierUser") .WithMany() .HasForeignKey("LastModifierUserId"); }); modelBuilder.Entity("Tbs.Authorization.Users.User", b => { b.HasOne("Tbs.Authorization.Users.User", "CreatorUser") .WithMany() .HasForeignKey("CreatorUserId"); b.HasOne("Tbs.Authorization.Users.User", "DeleterUser") .WithMany() .HasForeignKey("DeleterUserId"); b.HasOne("Tbs.Authorization.Users.User", "LastModifierUser") .WithMany() .HasForeignKey("LastModifierUserId"); }); modelBuilder.Entity("Tbs.DomainModels.Article", b => { b.HasOne("Tbs.DomainModels.ArticleRecord", "ArticleRecord") .WithMany() .HasForeignKey("ArticleRecordId1"); b.HasOne("Tbs.DomainModels.ArticleType", "ArticleType") .WithMany() .HasForeignKey("ArticleTypeId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("Tbs.DomainModels.Depot", "Depot") .WithMany() .HasForeignKey("DepotId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Tbs.DomainModels.ArticleRecord", b => { b.HasOne("Tbs.DomainModels.Depot", "Depot") .WithMany() .HasForeignKey("DepotId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Tbs.DomainModels.DaySettle", b => { b.HasOne("Tbs.DomainModels.Depot", "Depot") .WithMany() .HasForeignKey("DepotId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Tbs.DomainModels.DepotSignin", b => { b.HasOne("Tbs.DomainModels.Depot", "Depot") .WithMany() .HasForeignKey("DepotId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Tbs.DomainModels.Outlet", b => { b.HasOne("Tbs.DomainModels.Depot", "Depot") .WithMany() .HasForeignKey("DepotId"); }); modelBuilder.Entity("Tbs.DomainModels.PreRoute", b => { b.HasOne("Tbs.DomainModels.Depot", "Depot") .WithMany() .HasForeignKey("DepotId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("Tbs.DomainModels.Vehicle", "Vehicle") .WithMany() .HasForeignKey("VehicleId"); }); modelBuilder.Entity("Tbs.DomainModels.PreRouteTask", b => { b.HasOne("Tbs.DomainModels.Outlet", "Outlet") .WithMany() .HasForeignKey("OutletId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("Tbs.DomainModels.PreRoute") .WithMany("Tasks") .HasForeignKey("PreRouteId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("Tbs.DomainModels.TaskType", "TaskType") .WithMany() .HasForeignKey("TaskTypeId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Tbs.DomainModels.Route", b => { b.HasOne("Tbs.DomainModels.Depot", "Depot") .WithMany() .HasForeignKey("DepotId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Tbs.DomainModels.RouteIdentify", b => { b.HasOne("Tbs.DomainModels.Outlet", "Outlet") .WithMany() .HasForeignKey("OutletId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Tbs.DomainModels.RouteRole", b => { b.HasOne("Tbs.DomainModels.RouteType") .WithMany("Roles") .HasForeignKey("RouteTypeId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Tbs.DomainModels.RouteTask", b => { b.HasOne("Tbs.DomainModels.Outlet", "Outlet") .WithMany() .HasForeignKey("OutletId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("Tbs.DomainModels.Route") .WithMany("Tasks") .HasForeignKey("RouteId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("Tbs.DomainModels.TaskType", "TaskType") .WithMany() .HasForeignKey("TaskTypeId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Tbs.DomainModels.RouteWorker", b => { b.HasOne("Tbs.DomainModels.Route") .WithMany("Workers") .HasForeignKey("RouteId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Tbs.DomainModels.Signin", b => { b.HasOne("Tbs.DomainModels.Depot", "Depot") .WithMany() .HasForeignKey("DepotId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Tbs.DomainModels.Vault", b => { b.HasOne("Tbs.DomainModels.Depot", "Depot") .WithMany() .HasForeignKey("DepotId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Tbs.DomainModels.VaultRole", b => { b.HasOne("Tbs.DomainModels.VaultType") .WithMany("Roles") .HasForeignKey("VaultTypeId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Tbs.DomainModels.Vehicle", b => { b.HasOne("Tbs.DomainModels.Depot", "Depot") .WithMany() .HasForeignKey("DepotId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Tbs.DomainModels.VtAffair", b => { b.HasOne("Tbs.DomainModels.Depot", "Depot") .WithMany() .HasForeignKey("DepotId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Tbs.DomainModels.VtAffairWorker", b => { b.HasOne("Tbs.DomainModels.VtAffair") .WithMany("Workers") .HasForeignKey("VtAffairId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Tbs.DomainModels.Warehouse", b => { b.HasOne("Tbs.DomainModels.Depot", "Depot") .WithMany() .HasForeignKey("DepotId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Tbs.DomainModels.WhAffair", b => { b.HasOne("Tbs.DomainModels.Depot", "Depot") .WithMany() .HasForeignKey("DepotId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Tbs.DomainModels.WhAffairWorker", b => { b.HasOne("Tbs.DomainModels.WhAffair") .WithMany("Workers") .HasForeignKey("WhAffairId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Tbs.DomainModels.Worker", b => { b.HasOne("Tbs.DomainModels.Depot", "Depot") .WithMany() .HasForeignKey("DepotId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Tbs.MultiTenancy.Tenant", b => { b.HasOne("Tbs.Authorization.Users.User", "CreatorUser") .WithMany() .HasForeignKey("CreatorUserId"); b.HasOne("Tbs.Authorization.Users.User", "DeleterUser") .WithMany() .HasForeignKey("DeleterUserId"); b.HasOne("Abp.Application.Editions.Edition", "Edition") .WithMany() .HasForeignKey("EditionId"); b.HasOne("Tbs.Authorization.Users.User", "LastModifierUser") .WithMany() .HasForeignKey("LastModifierUserId"); }); modelBuilder.Entity("Abp.Application.Features.EditionFeatureSetting", b => { b.HasOne("Abp.Application.Editions.Edition", "Edition") .WithMany() .HasForeignKey("EditionId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Roles.RolePermissionSetting", b => { b.HasOne("Tbs.Authorization.Roles.Role") .WithMany("Permissions") .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Users.UserPermissionSetting", b => { b.HasOne("Tbs.Authorization.Users.User") .WithMany("Permissions") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); } } }
31.164639
117
0.412763
[ "MIT" ]
jiangyimin/Tbs
src/Tbs.EntityFrameworkCore/Migrations/20170721012248_m4.Designer.cs
71,743
C#
using SacredUtils.resources.prp; using System.Windows; using static SacredUtils.SourceFiles.Logger; namespace SacredUtils.resources.pgs { public partial class GamePlaySettingsThree { public GamePlaySettingsThree() { InitializeComponent(); DataContext = new GamePlaySettingsThreeProperty(); Log.Info("Initialization components for game play settings three done!"); } private void ToTwoPageBtn_Click(object sender, RoutedEventArgs e) => MainWindow.MainWindowInstance.SettingsFrame.Content = MainWindow.GamePlayStgTwo; } }
31.157895
157
0.731419
[ "Apache-2.0" ]
MairwunNx/SacredUtils
SacredUtils/SourceFiles/pgs/GamePlaySettingsThree.xaml.cs
594
C#
// ========================================================================== // Notifo.io // ========================================================================== // Copyright (c) Sebastian Stehle // All rights reserved. Licensed under the MIT license. // ========================================================================== namespace Notifo.Areas.Api.Controllers.Web.Dtos { public enum ConnectionMode { SignalR, SignalRSockets, Polling } }
29.058824
78
0.342105
[ "MIT" ]
anhgeeky/notifo
backend/src/Notifo/Areas/Api/Controllers/Web/Dtos/ConnectionMode.cs
496
C#
using System.IO; using Microsoft.AspNetCore.Hosting; namespace EasyParking { public class Program { public static void Main(string[] args) { var host = new WebHostBuilder() .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() .UseStartup<Startup>() .Build(); host.Run(); } } }
21.47619
64
0.518847
[ "MIT" ]
olegmusin/EasyParking
EasyParking/EasyParking/Program.cs
453
C#
using System; using System.Data; #if !NETSTANDARD1_3 namespace DotNet.Kit.Dapper { internal sealed class DataTableHandler : SqlMapper.ITypeHandler { public object Parse(Type destinationType, object value) { throw new NotImplementedException(); } public void SetValue(IDbDataParameter parameter, object value) { TableValuedParameter.Set(parameter, value as DataTable, null); } } } #endif
24.842105
74
0.658898
[ "MIT" ]
Meowv/DotNet.Kit
src/DotNet.Kit/SqlHelper/DataTableHandler.cs
474
C#
/* * * (c) Copyright Ascensio System Limited 2010-2020 * * 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 ASC.Common.Web; using ASC.Core; using ASC.CRM.Core; using ASC.CRM.Core.Dao; using ASC.Files.Core; using ASC.VoipService; using ASC.VoipService.Dao; using ASC.Web.Projects.Core; using Autofac; using FilesGlobal = ASC.Web.Files.Classes.Global; namespace ASC.Api.CRM { public class CRMApiBase : IDisposable { private IDaoFactory filesDaoFactory; private readonly ILifetimeScope scope; private readonly ILifetimeScope crmScope; public CRMApiBase() { scope = DIHelper.Resolve(); ProjectsDaoFactory = scope.Resolve<Projects.Core.DataInterfaces.IDaoFactory>(); crmScope = Web.CRM.Core.DIHelper.Resolve(); DaoFactory = crmScope.Resolve<DaoFactory>(); } protected DaoFactory DaoFactory { get; private set; } protected IVoipProvider VoipProvider { get { return VoipDao.GetProvider(); } } protected Projects.Core.DataInterfaces.IDaoFactory ProjectsDaoFactory { get; private set; } protected IDaoFactory FilesDaoFactory { get { return filesDaoFactory ?? (filesDaoFactory = FilesGlobal.DaoFactory); } } public void Dispose() { if (scope != null) { scope.Dispose(); } if (crmScope != null) { crmScope.Dispose(); } } } }
27.64
99
0.641582
[ "Apache-2.0" ]
Ektai-Solution-Pty-Ltd/CommunityServer
module/ASC.Api/ASC.Api.CRM/CRMApiBase.cs
2,073
C#
using System; using System.Runtime.CompilerServices; namespace AutoLot.Services.Logging { public interface IAppLogging<T> { void LogAppError(Exception exception, string message, [CallerMemberName] string memberName = "", [CallerFilePath] string sourceFilePath = "", [CallerLineNumber] int sourceLineNumber = 0); void LogAppError(string message, [CallerMemberName] string memberName = "", [CallerFilePath] string sourceFilePath = "", [CallerLineNumber] int sourceLineNumber = 0); void LogAppCritical(Exception exception, string message, [CallerMemberName] string memberName = "", [CallerFilePath] string sourceFilePath = "", [CallerLineNumber] int sourceLineNumber = 0); void LogAppCritical(string message, [CallerMemberName] string memberName = "", [CallerFilePath] string sourceFilePath = "", [CallerLineNumber] int sourceLineNumber = 0); void LogAppDebug(string message, [CallerMemberName] string memberName = "", [CallerFilePath] string sourceFilePath = "", [CallerLineNumber] int sourceLineNumber = 0); void LogAppTrace(string message, [CallerMemberName] string memberName = "", [CallerFilePath] string sourceFilePath = "", [CallerLineNumber] int sourceLineNumber = 0); void LogAppInformation(string message, [CallerMemberName] string memberName = "", [CallerFilePath] string sourceFilePath = "", [CallerLineNumber] int sourceLineNumber = 0); void LogAppWarning(string message, [CallerMemberName] string memberName = "", [CallerFilePath] string sourceFilePath = "", [CallerLineNumber] int sourceLineNumber = 0); } }
39.416667
64
0.63055
[ "BSD-3-Clause", "MIT" ]
MalikWaseemJaved/presentations
.NETCore/ASP.NETCore/v5.0/AutoLot50/AutoLot.Services/Logging/IAppLogging.cs
1,894
C#
namespace Larva.RaftAlgo { /// <summary> /// Raft settings /// </summary> public class InMemoryRaftSettings : IRaftSettings { /// <summary> /// /// </summary> public int MinElectionTimeoutMilliseconds { get; set; } /// <summary> /// /// </summary> public int MaxElectionTimeoutMilliseconds { get; set; } /// <summary> /// /// </summary> public int HeartbeatMilliseconds { get; set; } /// <summary> /// /// </summary> public int CommandTimeoutMilliseconds { get; set; } /// <summary> /// /// </summary> public int AppendEntriesBatchSize { get; set; } } }
22.606061
63
0.490617
[ "MIT" ]
freshncp/Larva.RaftAlgo
src/Larva.RaftAlgo/InMemoryRaftSettings.cs
746
C#
using System; using System.Diagnostics; using System.IO; using System.Linq; namespace onchange { public class Program { private readonly Settings _settings; private readonly FileSystemWatcher _watcher; static void Main(string[] args) { var program = new Program(args); program.WaitForFinish(); } private void WaitForFinish() { _watcher.EnableRaisingEvents = true; Console.WriteLine("Started watcher " + Directory.GetCurrentDirectory()); Console.WriteLine("Press return to stop watching for changes."); Console.ReadLine(); } protected Program(string[] args) { _settings = Settings.ParseArguments(args); _watcher = new FileSystemWatcher(Directory.GetCurrentDirectory()) { IncludeSubdirectories = true, Filter = _settings.Filter }; _watcher.Changed += OnChange; } private void OnChange(object sender, FileSystemEventArgs e) { ExecuteAction(e.FullPath); } public void ExecuteAction(string fullPath) { Console.WriteLine("change: " + fullPath); var text = RunProcess(_settings.Action); Console.WriteLine(text); foreach (var reaction in _settings.Reactions.Where(reaction => reaction.RegEx.IsMatch(text))) { RunProcess(reaction.Program); } } protected virtual string RunProcess(string program) { var p = new Process { StartInfo = { FileName = program, RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false } }; p.Start(); p.WaitForExit(); var text = p.StandardOutput.ReadToEnd() + "\n" + p.StandardError.ReadToEnd(); return text; } } }
21.961039
96
0.668244
[ "Unlicense" ]
morkeleb/onchange
onchange/Program.cs
1,693
C#
// <copyright file="DistributedContextDeserializationTest.cs" company="OpenTelemetry Authors"> // Copyright 2018, OpenTelemetry Authors // // 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. // </copyright> using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using OpenTelemetry.Internal; using Xunit; namespace OpenTelemetry.Context.Propagation.Test { public class DistributedContextDeserializationTest { private readonly DistributedContextBinarySerializer serializer; public DistributedContextDeserializationTest() { DistributedContext.Carrier = AsyncLocalDistributedContextCarrier.Instance; serializer = new DistributedContextBinarySerializer(); } [Fact] public void TestConstants() { // Refer to the JavaDoc on SerializationUtils for the definitions on these constants. Assert.Equal(0, SerializationUtils.VersionId); Assert.Equal(0, SerializationUtils.TagFieldId); Assert.Equal(8192, SerializationUtils.TagContextSerializedSizeLimit); } [Fact] public void TestNoTagsSerialization() { DistributedContext dc = serializer.FromByteArray(serializer.ToByteArray(DistributedContext.Empty)); Assert.Empty(dc.Entries); dc = serializer.FromByteArray(new byte[] { SerializationUtils.VersionId }); // One byte that represents Version ID. Assert.Empty(dc.Entries); } [Fact] public void TestDeserializeEmptyByteArrayThrowException() { Assert.Equal(DistributedContext.Empty, serializer.FromByteArray(new byte[0])); } [Fact] public void TestDeserializeTooLargeByteArrayThrowException() { var output = new MemoryStream(); output.WriteByte(SerializationUtils.VersionId); for (var i = 0; i < SerializationUtils.TagContextSerializedSizeLimit / 8 - 1; i++) { // Each tag will be with format {key : "0123", value : "0123"}, so the length of it is 8. String str; if (i < 10) { str = "000" + i; } else if (i < 100) { str = "00" + i; } else if (i < 1000) { str = "0" + i; } else { str = i.ToString(); } EncodeTagToOutPut(str, str, output); } // The last tag will be of size 9, so the total size of the TagContext (8193) will be one byte // more than limit. EncodeTagToOutPut("last", "last1", output); var bytes = output.ToArray(); Assert.Equal(DistributedContext.Empty, serializer.FromByteArray(bytes)); } // Deserializing this inPut should cause an error, even though it represents a relatively small // TagContext. [Fact] public void TestDeserializeTooLargeByteArrayThrowException_WithDuplicateTagKeys() { var output = new MemoryStream(); output.WriteByte(SerializationUtils.VersionId); for (var i = 0; i < SerializationUtils.TagContextSerializedSizeLimit / 8 - 1; i++) { // Each tag will be with format {key : "key_", value : "0123"}, so the length of it is 8. String str; if (i < 10) { str = "000" + i; } else if (i < 100) { str = "00" + i; } else if (i < 1000) { str = "0" + i; } else { str = i.ToString(); } EncodeTagToOutPut("key_", str, output); } // The last tag will be of size 9, so the total size of the TagContext (8193) will be one byte // more than limit. EncodeTagToOutPut("key_", "last1", output); var bytes = output.ToArray(); Assert.Equal(DistributedContext.Empty, serializer.FromByteArray(bytes)); } [Fact] public void TestDeserializeOneTag() { var output = new MemoryStream(); output.WriteByte(SerializationUtils.VersionId); EncodeTagToOutPut("Key", "Value", output); DistributedContext expected = DistributedContextBuilder.CreateContext("Key", "Value"); Assert.Equal(expected, serializer.FromByteArray(output.ToArray())); } [Fact] public void TestDeserializeMultipleTags() { var output = new MemoryStream(); output.WriteByte(SerializationUtils.VersionId); EncodeTagToOutPut("Key1", "Value1", output); EncodeTagToOutPut("Key2", "Value2", output); DistributedContext expected = DistributedContextBuilder.CreateContext(new List<DistributedContextEntry>(2) { new DistributedContextEntry("Key1", "Value1"), new DistributedContextEntry("Key2", "Value2") }); Assert.Equal(expected, serializer.FromByteArray(output.ToArray())); } [Fact] public void TestDeserializeDuplicateKeys() { var output = new MemoryStream(); output.WriteByte(SerializationUtils.VersionId); EncodeTagToOutPut("Key1", "Value1", output); EncodeTagToOutPut("Key1", "Value2", output); DistributedContext expected = DistributedContextBuilder.CreateContext("Key1", "Value2"); Assert.Equal(expected, serializer.FromByteArray(output.ToArray())); } [Fact] public void TestDeserializeNonConsecutiveDuplicateKeys() { var output = new MemoryStream(); output.WriteByte(SerializationUtils.VersionId); EncodeTagToOutPut("Key1", "Value1", output); EncodeTagToOutPut("Key2", "Value2", output); EncodeTagToOutPut("Key3", "Value3", output); EncodeTagToOutPut("Key1", "Value4", output); EncodeTagToOutPut("Key2", "Value5", output); DistributedContext expected = DistributedContextBuilder.CreateContext(new List<DistributedContextEntry>(3) { new DistributedContextEntry("Key1", "Value4"), new DistributedContextEntry("Key2", "Value5"), new DistributedContextEntry("Key3", "Value3"), }); Assert.Equal(expected, serializer.FromByteArray(output.ToArray())); } [Fact] public void TestDeserializeDuplicateTags() { var output = new MemoryStream(); output.WriteByte(SerializationUtils.VersionId); EncodeTagToOutPut("Key1", "Value1", output); EncodeTagToOutPut("Key1", "Value2", output); DistributedContext expected = DistributedContextBuilder.CreateContext("Key1", "Value2"); Assert.Equal(expected, serializer.FromByteArray(output.ToArray())); } [Fact] public void TestDeserializeNonConsecutiveDuplicateTags() { var output = new MemoryStream(); output.WriteByte(SerializationUtils.VersionId); EncodeTagToOutPut("Key1", "Value1", output); EncodeTagToOutPut("Key2", "Value2", output); EncodeTagToOutPut("Key3", "Value3", output); EncodeTagToOutPut("Key1", "Value1", output); EncodeTagToOutPut("Key2", "Value2", output); DistributedContext expected = DistributedContextBuilder.CreateContext(new List<DistributedContextEntry>(3) { new DistributedContextEntry("Key1", "Value1"), new DistributedContextEntry("Key2", "Value2"), new DistributedContextEntry("Key3", "Value3"), }); Assert.Equal(expected, serializer.FromByteArray(output.ToArray())); } [Fact] public void StopParsingAtUnknownField() { var output = new MemoryStream(); output.WriteByte(SerializationUtils.VersionId); EncodeTagToOutPut("Key1", "Value1", output); EncodeTagToOutPut("Key2", "Value2", output); // Write unknown field ID 1. output.WriteByte(1); output.Write(new byte[] { 1, 2, 3, 4 }, 0, 4); EncodeTagToOutPut("Key3", "Value3", output); DistributedContext expected = DistributedContextBuilder.CreateContext(new List<DistributedContextEntry>(2) { new DistributedContextEntry("Key1", "Value1"), new DistributedContextEntry("Key2", "Value2"), }); Assert.Equal(expected, serializer.FromByteArray(output.ToArray())); } [Fact] public void StopParsingAtUnknownTagAtStart() { var output = new MemoryStream(); output.WriteByte(SerializationUtils.VersionId); // Write unknown field ID 1. output.WriteByte(1); output.Write(new byte[] { 1, 2, 3, 4 }, 0, 4); EncodeTagToOutPut("Key", "Value", output); Assert.Equal(DistributedContext.Empty, serializer.FromByteArray(output.ToArray())); } [Fact] public void TestDeserializeWrongFormat() { // encoded tags should follow the format <version_id>(<tag_field_id><tag_encoding>)* Assert.Equal(DistributedContext.Empty, serializer.FromByteArray(new byte[3])); } [Fact] public void TestDeserializeWrongVersionId() { Assert.Equal(DistributedContext.Empty, serializer.FromByteArray(new byte[] { SerializationUtils.VersionId + 1 })); } [Fact] public void TestDeserializeNegativeVersionId() { Assert.Equal(DistributedContext.Empty, serializer.FromByteArray(new byte[] { 0xff })); } // <tag_encoding> == // <tag_key_len><tag_key><tag_val_len><tag_val> // <tag_key_len> == varint encoded integer // <tag_key> == tag_key_len bytes comprising tag key name // <tag_val_len> == varint encoded integer // <tag_val> == tag_val_len bytes comprising UTF-8 string private static void EncodeTagToOutPut(String key, String value, MemoryStream output) { output.WriteByte(SerializationUtils.TagFieldId); EncodeString(key, output); EncodeString(value, output); } private static void EncodeString(String input, MemoryStream output) { var length = input.Length; var bytes = new byte[VarInt.VarIntSize(length)]; VarInt.PutVarInt(length, bytes, 0); output.Write(bytes, 0, bytes.Length); var inPutBytes = Encoding.UTF8.GetBytes(input); output.Write(inPutBytes, 0, inPutBytes.Length); } } }
41.810169
217
0.558618
[ "Apache-2.0" ]
FrancisChung/opentelemetry-dotnet
test/OpenTelemetry.Tests/Impl/DistributedContext/Propagation/DistributedContextDeserializationTest.cs
12,336
C#
//----------------------------------------------------------------------- // <copyright file="IDateTimeNowTimeProvider.cs" company="Akka.NET Project"> // Copyright (C) 2009-2016 Typesafe Inc. <http://www.typesafe.com> // Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; namespace Akka.Actor { /// <summary> /// Marks that an <see cref="ITimeProvider"/> uses <see cref="DateTimeOffset.UtcNow"/>, /// i.e. system time, to provide <see cref="ITimeProvider.Now"/>. /// </summary> public interface IDateTimeOffsetNowTimeProvider : ITimeProvider { } }
36
92
0.536111
[ "Apache-2.0" ]
EnterpriseProductsLP/akka.net
src/core/Akka/Actor/Scheduler/IDateTimeNowTimeProvider.cs
722
C#
namespace Everyday.Web.Models { public class TaskCategory { public int TaskId { get; set; } public Task Task { get; set; } public int CategoryId { get; set; } public Category Category { get; set; } } }
22.363636
46
0.581301
[ "MIT" ]
smith-neil/everyday
server/Everyday.Web/Models/TaskCategory.cs
246
C#
using Handelabra.Sentinels.Engine.Controller; using Handelabra.Sentinels.Engine.Model; using System; using System.Collections; using System.Collections.Generic; using System.Linq; namespace Cauldron.Anathema { public class AnathemaRampageCardController : CardController { public AnathemaRampageCardController(Card card, TurnTakerController turnTakerController) : base(card, turnTakerController) { } public override IEnumerator Play() { //Find the hero with the most cards in hand List<TurnTaker> storedResults = new List<TurnTaker>(); IEnumerator coroutine = base.FindHeroWithMostCardsInHand(storedResults, 1, 1, null, null, false, false); if (base.UseUnityCoroutines) { yield return base.GameController.StartCoroutine(coroutine); } else { base.GameController.ExhaustCoroutine(coroutine); } TurnTaker turnTaker = storedResults.FirstOrDefault<TurnTaker>(); if (turnTaker != null) { //Anathema deals the Hero target with the most cards in hand {H-1} melee damage. HeroTurnTakerController hero = base.FindHeroTurnTakerController(turnTaker as HeroTurnTaker); IEnumerator coroutine2 = base.DealDamage(base.CharacterCard, hero.CharacterCard, base.H - 1, DamageType.Melee, false, false, false, null, null, null, false, base.GetCardSource(null)); if (base.UseUnityCoroutines) { yield return base.GameController.StartCoroutine(coroutine2); } else { base.GameController.ExhaustCoroutine(coroutine2); } } //Until the start of the next Villain Turn, increase damage dealt by Villain targets by 1 and reduce damage dealt to Villain targets by 1. ReduceDamageStatusEffect reduceDamageStatusEffect = new ReduceDamageStatusEffect(1); reduceDamageStatusEffect.TargetCriteria.IsVillain = true; ; reduceDamageStatusEffect.UntilStartOfNextTurn(this.TurnTaker); IEnumerator reduceCoroutine = this.AddStatusEffect(reduceDamageStatusEffect, true); IncreaseDamageStatusEffect increaseDamageStatusEffect = new IncreaseDamageStatusEffect(1); increaseDamageStatusEffect.SourceCriteria.IsVillain = true; ; increaseDamageStatusEffect.UntilStartOfNextTurn(this.TurnTaker); IEnumerator increaseCoroutine = this.AddStatusEffect(increaseDamageStatusEffect, true); if (this.UseUnityCoroutines) { yield return this.GameController.StartCoroutine(reduceCoroutine); yield return this.GameController.StartCoroutine(increaseCoroutine); } else { this.GameController.ExhaustCoroutine(reduceCoroutine); this.GameController.ExhaustCoroutine(increaseCoroutine); } yield break; } } }
36.430556
187
0.771636
[ "MIT" ]
LNBertolini/CauldronMods
Controller/Villains/Anathema/Cards/AnathemaRampageCardController.cs
2,625
C#
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel // // 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.Collections.Generic; using SharpDX.Toolkit.Serialization; namespace SharpDX.Toolkit.Graphics { public partial class EffectData { public class CompilerArguments : IDataSerializable { /// <summary> /// The absolute path to the FX source file used to compile this effect. /// </summary> public string FilePath; /// <summary> /// The absolute path to dependency file path generated when compiling this effect. /// </summary> public string DependencyFilePath; /// <summary> /// The flags used to compile an effect. /// </summary> public EffectCompilerFlags CompilerFlags; /// <summary> /// The macros used to compile this effect (may be null). /// </summary> public List<ShaderMacro> Macros; /// <summary> /// The list of include directory used to compile this file (may be null) /// </summary> public List<string> IncludeDirectoryList; void IDataSerializable.Serialize(BinarySerializer serializer) { serializer.Serialize(ref FilePath); serializer.Serialize(ref DependencyFilePath); serializer.SerializeEnum(ref CompilerFlags); serializer.Serialize(ref Macros, SerializeFlags.Nullable); serializer.Serialize(ref IncludeDirectoryList, serializer.Serialize, SerializeFlags.Nullable); } public override string ToString() { return string.Format("FilePath: {0}, CompilerFlags: {1}", FilePath, CompilerFlags); } } } }
42.057971
110
0.649897
[ "MIT" ]
baetz-daniel/Toolkit
Source/Toolkit/SharpDX.Toolkit/Graphics/EffectData.CompilerArguments.cs
2,904
C#
// <auto-generated> // Generated by the protocol buffer compiler. DO NOT EDIT! // source: monopoly/announce_bankrupt_spec.proto // </auto-generated> #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Monopoly.Protobuf { /// <summary>Holder for reflection information generated from monopoly/announce_bankrupt_spec.proto</summary> public static partial class AnnounceBankruptSpecReflection { #region Descriptor /// <summary>File descriptor for monopoly/announce_bankrupt_spec.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static AnnounceBankruptSpecReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CiVtb25vcG9seS9hbm5vdW5jZV9iYW5rcnVwdF9zcGVjLnByb3RvEghtb25v", "cG9seSIpChdBbm5vdW5jZUJhbmtydXB0UGF5bG9hZBIOCgZwbGF5ZXIYASAB", "KAlCFKoCEU1vbm9wb2x5LlByb3RvYnVmYgZwcm90bzM=")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { }, new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Monopoly.Protobuf.AnnounceBankruptPayload), global::Monopoly.Protobuf.AnnounceBankruptPayload.Parser, new[]{ "Player" }, null, null, null, null) })); } #endregion } #region Messages /// <summary> /// type : "announce_bankrupt" /// packet_type : D /// </summary> public sealed partial class AnnounceBankruptPayload : pb::IMessage<AnnounceBankruptPayload> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<AnnounceBankruptPayload> _parser = new pb::MessageParser<AnnounceBankruptPayload>(() => new AnnounceBankruptPayload()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<AnnounceBankruptPayload> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Monopoly.Protobuf.AnnounceBankruptSpecReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public AnnounceBankruptPayload() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public AnnounceBankruptPayload(AnnounceBankruptPayload other) : this() { player_ = other.player_; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public AnnounceBankruptPayload Clone() { return new AnnounceBankruptPayload(this); } /// <summary>Field number for the "player" field.</summary> public const int PlayerFieldNumber = 1; private string player_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Player { get { return player_; } set { player_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as AnnounceBankruptPayload); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(AnnounceBankruptPayload other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Player != other.Player) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Player.Length != 0) hash ^= Player.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (Player.Length != 0) { output.WriteRawTag(10); output.WriteString(Player); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (Player.Length != 0) { output.WriteRawTag(10); output.WriteString(Player); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Player.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Player); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(AnnounceBankruptPayload other) { if (other == null) { return; } if (other.Player.Length != 0) { Player = other.Player; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { Player = input.ReadString(); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 10: { Player = input.ReadString(); break; } } } } #endif } #endregion } #endregion Designer generated code
33.190045
201
0.679755
[ "MIT" ]
SeawolvesAtCali/Monopoly
protos/gen_csharp/Monopoly/Protobuf/AnnounceBankruptSpec.cs
7,335
C#
using System; using System.Collections.Generic; using Web.Models; namespace Web.ViewModels { internal class PlayerConnectedViewModel { public PlayerConnectedViewModel(GameSession game) { this.GameId = game.Id; Code = game.Code; this.Users = new List<UserViewModel>(); foreach(UserGameSessions user in game.Users){ Users.Add(new UserViewModel(user)); } GameCanStart = true; GameStarted = game.InProgress == true; } public Guid GameId { get; set; } public string Code { get; set; } public Boolean GameCanStart { get; set; } public Boolean GameStarted { get; set; } public List<UserViewModel> Users { get; set; } } internal class GameCreationViewModel { public GameCreationViewModel(GameSession game) { GameId = game.Id; ErrorMessage = ""; Success = true; } public Guid GameId { get; set; } public string ErrorMessage { get; set; } public Boolean Success { get; set; } } }
25.755556
58
0.56428
[ "MIT" ]
csutorasr-homeworks/softwareachitecture
src/Web/ViewModels/GameViewModel.cs
1,161
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using DocStoreApi.BusinessLogic; using NUnit.Framework; namespace DocStoreTests { [TestFixture] public class DocStoreHelperTests { [Test] public void CreateDocStore() { var dsh = new ManageDocStoreHelper(); // TODO: Get this from web.config string docStoreName = Constants.DocStoreName; string docStoreRoot = Constants.DocStoreRoot; bool isCreated = dsh.CreateDocStore(docStoreName, docStoreRoot); } } }
24.269231
76
0.664025
[ "MIT" ]
pjsvis/DocStore
DocStoreTests/DocStoreHelperTests.cs
633
C#
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================================= ** ** Class: ThreadStateException ** ** Author: Derek Yenzer (dereky) ** ** Purpose: An exception class to indicate that the Thread class is in an ** invalid state for the method. ** ** Date: April 1, 1998 ** =============================================================================*/ namespace System.Threading { using System; using System.Runtime.Serialization; /// <include file='doc\ThreadStateException.uex' path='docs/doc[@for="ThreadStateException"]/*' /> [Serializable()] public class ThreadStateException : SystemException { /// <include file='doc\ThreadStateException.uex' path='docs/doc[@for="ThreadStateException.ThreadStateException"]/*' /> public ThreadStateException() : base(Environment.GetResourceString("Arg_ThreadStateException")) { SetErrorCode(__HResults.COR_E_THREADSTATE); } /// <include file='doc\ThreadStateException.uex' path='docs/doc[@for="ThreadStateException.ThreadStateException1"]/*' /> public ThreadStateException(String message) : base(message) { SetErrorCode(__HResults.COR_E_THREADSTATE); } /// <include file='doc\ThreadStateException.uex' path='docs/doc[@for="ThreadStateException.ThreadStateException2"]/*' /> public ThreadStateException(String message, Exception innerException) : base(message, innerException) { SetErrorCode(__HResults.COR_E_THREADSTATE); } /// <include file='doc\ThreadStateException.uex' path='docs/doc[@for="ThreadStateException.ThreadStateException3"]/*' /> protected ThreadStateException(SerializationInfo info, StreamingContext context) : base (info, context) { } } }
40.479167
129
0.60525
[ "Unlicense" ]
bestbat/Windows-Server
com/netfx/src/clr/bcl/system/threading/threadstateexception.cs
1,943
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Xml.Serialization { using System; using System.IO; using System.Collections; using System.ComponentModel; using System.Threading; using System.Reflection; using System.Security; using System.Globalization; using System.Diagnostics.CodeAnalysis; ///<internalonly/> public abstract class XmlSerializationGeneratedCode { internal void Init(TempAssembly? tempAssembly) { } // this method must be called at the end of serialization internal void Dispose() { } } internal class XmlSerializationCodeGen { private readonly IndentedWriter _writer; private int _nextMethodNumber; private readonly Hashtable _methodNames = new Hashtable(); private readonly ReflectionAwareCodeGen _raCodeGen; private readonly TypeScope[] _scopes; private readonly TypeDesc? _stringTypeDesc; private readonly TypeDesc? _qnameTypeDesc; private readonly string _access; private readonly string _className; private TypeMapping[]? _referencedMethods; private int _references; private readonly Hashtable _generatedMethods = new Hashtable(); [RequiresUnreferencedCode("Calls GetTypeDesc")] internal XmlSerializationCodeGen(IndentedWriter writer, TypeScope[] scopes, string access, string className) { _writer = writer; _scopes = scopes; if (scopes.Length > 0) { _stringTypeDesc = scopes[0].GetTypeDesc(typeof(string)); _qnameTypeDesc = scopes[0].GetTypeDesc(typeof(XmlQualifiedName)); } _raCodeGen = new ReflectionAwareCodeGen(writer); _className = className; _access = access; } internal IndentedWriter Writer { get { return _writer; } } internal int NextMethodNumber { get { return _nextMethodNumber; } set { _nextMethodNumber = value; } } internal ReflectionAwareCodeGen RaCodeGen { get { return _raCodeGen; } } internal TypeDesc? StringTypeDesc { get { return _stringTypeDesc; } } internal TypeDesc? QnameTypeDesc { get { return _qnameTypeDesc; } } internal string ClassName { get { return _className; } } internal string Access { get { return _access; } } internal TypeScope[] Scopes { get { return _scopes; } } internal Hashtable MethodNames { get { return _methodNames; } } internal Hashtable GeneratedMethods { get { return _generatedMethods; } } [RequiresUnreferencedCode("calls WriteStructMethod")] internal virtual void GenerateMethod(TypeMapping mapping) { } [RequiresUnreferencedCode("calls GenerateMethod")] internal void GenerateReferencedMethods() { while (_references > 0) { TypeMapping mapping = _referencedMethods![--_references]; GenerateMethod(mapping); } } internal string? ReferenceMapping(TypeMapping mapping) { if (!mapping.IsSoap) { if (_generatedMethods[mapping] == null) { _referencedMethods = EnsureArrayIndex(_referencedMethods!, _references); _referencedMethods[_references++] = mapping; } } return (string?)_methodNames[mapping]; } private TypeMapping[] EnsureArrayIndex(TypeMapping[] a, int index) { if (a == null) return new TypeMapping[32]; if (index < a.Length) return a; TypeMapping[] b = new TypeMapping[a.Length + 32]; Array.Copy(a, b, index); return b; } internal void WriteQuotedCSharpString(string? value) { _raCodeGen.WriteQuotedCSharpString(value); } internal void GenerateHashtableGetBegin(string privateName, string publicName) { _writer.Write(typeof(Hashtable).FullName); _writer.Write(" "); _writer.Write(privateName); _writer.WriteLine(" = null;"); _writer.Write("public override "); _writer.Write(typeof(Hashtable).FullName); _writer.Write(" "); _writer.Write(publicName); _writer.WriteLine(" {"); _writer.Indent++; _writer.WriteLine("get {"); _writer.Indent++; _writer.Write("if ("); _writer.Write(privateName); _writer.WriteLine(" == null) {"); _writer.Indent++; _writer.Write(typeof(Hashtable).FullName); _writer.Write(" _tmp = new "); _writer.Write(typeof(Hashtable).FullName); _writer.WriteLine("();"); } internal void GenerateHashtableGetEnd(string privateName) { _writer.Write("if ("); _writer.Write(privateName); _writer.Write(" == null) "); _writer.Write(privateName); _writer.WriteLine(" = _tmp;"); _writer.Indent--; _writer.WriteLine("}"); _writer.Write("return "); _writer.Write(privateName); _writer.WriteLine(";"); _writer.Indent--; _writer.WriteLine("}"); _writer.Indent--; _writer.WriteLine("}"); } internal void GeneratePublicMethods(string privateName, string publicName, string?[] methods, XmlMapping[] xmlMappings) { GenerateHashtableGetBegin(privateName, publicName); if (methods != null && methods.Length != 0 && xmlMappings != null && xmlMappings.Length == methods.Length) { for (int i = 0; i < methods.Length; i++) { if (methods[i] == null) continue; _writer.Write("_tmp["); WriteQuotedCSharpString(xmlMappings[i].Key); _writer.Write("] = "); WriteQuotedCSharpString(methods[i]); _writer.WriteLine(";"); } } GenerateHashtableGetEnd(privateName); } internal void GenerateSupportedTypes(Type?[] types) { _writer.Write("public override "); _writer.Write(typeof(bool).FullName); _writer.Write(" CanSerialize("); _writer.Write(typeof(Type).FullName); _writer.WriteLine(" type) {"); _writer.Indent++; Hashtable uniqueTypes = new Hashtable(); for (int i = 0; i < types.Length; i++) { Type? type = types[i]; if (type == null) continue; if (!type.IsPublic && !type.IsNestedPublic) continue; if (uniqueTypes[type] != null) continue; if (DynamicAssemblies.IsTypeDynamic(type)) continue; if (type.IsGenericType || type.ContainsGenericParameters && DynamicAssemblies.IsTypeDynamic(type.GetGenericArguments())) continue; uniqueTypes[type] = type; _writer.Write("if (type == typeof("); _writer.Write(CodeIdentifier.GetCSharpName(type)); _writer.WriteLine(")) return true;"); } _writer.WriteLine("return false;"); _writer.Indent--; _writer.WriteLine("}"); } internal string GenerateBaseSerializer(string baseSerializer, string readerClass, string writerClass, CodeIdentifiers classes) { baseSerializer = CodeIdentifier.MakeValid(baseSerializer); baseSerializer = classes.AddUnique(baseSerializer, baseSerializer); _writer.WriteLine(); _writer.Write("public abstract class "); _writer.Write(CodeIdentifier.GetCSharpName(baseSerializer)); _writer.Write(" : "); _writer.Write(typeof(System.Xml.Serialization.XmlSerializer).FullName); _writer.WriteLine(" {"); _writer.Indent++; _writer.Write("protected override "); _writer.Write(typeof(System.Xml.Serialization.XmlSerializationReader).FullName); _writer.WriteLine(" CreateReader() {"); _writer.Indent++; _writer.Write("return new "); _writer.Write(readerClass); _writer.WriteLine("();"); _writer.Indent--; _writer.WriteLine("}"); _writer.Write("protected override "); _writer.Write(typeof(System.Xml.Serialization.XmlSerializationWriter).FullName); _writer.WriteLine(" CreateWriter() {"); _writer.Indent++; _writer.Write("return new "); _writer.Write(writerClass); _writer.WriteLine("();"); _writer.Indent--; _writer.WriteLine("}"); _writer.Indent--; _writer.WriteLine("}"); return baseSerializer; } internal string GenerateTypedSerializer(string? readMethod, string? writeMethod, XmlMapping mapping, CodeIdentifiers classes, string baseSerializer, string readerClass, string writerClass) { string serializerName = CodeIdentifier.MakeValid(Accessor.UnescapeName(mapping.Accessor.Mapping!.TypeDesc!.Name)); serializerName = classes.AddUnique($"{serializerName}Serializer", mapping); _writer.WriteLine(); _writer.Write("public sealed class "); _writer.Write(CodeIdentifier.GetCSharpName(serializerName)); _writer.Write(" : "); _writer.Write(baseSerializer); _writer.WriteLine(" {"); _writer.Indent++; _writer.WriteLine(); _writer.Write("public override "); _writer.Write(typeof(bool).FullName); _writer.Write(" CanDeserialize("); _writer.Write(typeof(XmlReader).FullName); _writer.WriteLine(" xmlReader) {"); _writer.Indent++; if (mapping.Accessor.Any) { _writer.WriteLine("return true;"); } else { _writer.Write("return xmlReader.IsStartElement("); WriteQuotedCSharpString(mapping.Accessor.Name); _writer.Write(", "); WriteQuotedCSharpString(mapping.Accessor.Namespace); _writer.WriteLine(");"); } _writer.Indent--; _writer.WriteLine("}"); if (writeMethod != null) { _writer.WriteLine(); _writer.Write("protected override void Serialize(object objectToSerialize, "); _writer.Write(typeof(System.Xml.Serialization.XmlSerializationWriter).FullName); _writer.WriteLine(" writer) {"); _writer.Indent++; _writer.Write("(("); _writer.Write(writerClass); _writer.Write(")writer)."); _writer.Write(writeMethod); _writer.Write("("); if (mapping is XmlMembersMapping) { _writer.Write("(object[])"); } _writer.WriteLine("objectToSerialize);"); _writer.Indent--; _writer.WriteLine("}"); } if (readMethod != null) { _writer.WriteLine(); _writer.Write("protected override object Deserialize("); _writer.Write(typeof(System.Xml.Serialization.XmlSerializationReader).FullName); _writer.WriteLine(" reader) {"); _writer.Indent++; _writer.Write("return (("); _writer.Write(readerClass); _writer.Write(")reader)."); _writer.Write(readMethod); _writer.WriteLine("();"); _writer.Indent--; _writer.WriteLine("}"); } _writer.Indent--; _writer.WriteLine("}"); return serializerName; } private void GenerateTypedSerializers(Hashtable serializers) { string privateName = "typedSerializers"; GenerateHashtableGetBegin(privateName, "TypedSerializers"); foreach (string key in serializers.Keys) { _writer.Write("_tmp.Add("); WriteQuotedCSharpString(key); _writer.Write(", new "); _writer.Write((string?)serializers[key]); _writer.WriteLine("());"); } GenerateHashtableGetEnd("typedSerializers"); } //GenerateGetSerializer(serializers, xmlMappings); private void GenerateGetSerializer(Hashtable serializers, XmlMapping[] xmlMappings) { _writer.Write("public override "); _writer.Write(typeof(System.Xml.Serialization.XmlSerializer).FullName); _writer.Write(" GetSerializer("); _writer.Write(typeof(Type).FullName); _writer.WriteLine(" type) {"); _writer.Indent++; for (int i = 0; i < xmlMappings.Length; i++) { if (xmlMappings[i] is XmlTypeMapping) { Type? type = xmlMappings[i].Accessor.Mapping!.TypeDesc!.Type; if (type == null) continue; if (!type.IsPublic && !type.IsNestedPublic) continue; if (DynamicAssemblies.IsTypeDynamic(type)) continue; if (type.IsGenericType || type.ContainsGenericParameters && DynamicAssemblies.IsTypeDynamic(type.GetGenericArguments())) continue; _writer.Write("if (type == typeof("); _writer.Write(CodeIdentifier.GetCSharpName(type)); _writer.Write(")) return new "); _writer.Write((string?)serializers[xmlMappings[i].Key!]); _writer.WriteLine("();"); } } _writer.WriteLine("return null;"); _writer.Indent--; _writer.WriteLine("}"); } internal void GenerateSerializerContract(string className, XmlMapping[] xmlMappings, Type?[] types, string readerType, string?[] readMethods, string writerType, string?[] writerMethods, Hashtable serializers) { _writer.WriteLine(); _writer.Write("public class XmlSerializerContract : global::"); _writer.Write(typeof(System.Xml.Serialization.XmlSerializerImplementation).FullName); _writer.WriteLine(" {"); _writer.Indent++; _writer.Write("public override global::"); _writer.Write(typeof(System.Xml.Serialization.XmlSerializationReader).FullName); _writer.Write(" Reader { get { return new "); _writer.Write(readerType); _writer.WriteLine("(); } }"); _writer.Write("public override global::"); _writer.Write(typeof(System.Xml.Serialization.XmlSerializationWriter).FullName); _writer.Write(" Writer { get { return new "); _writer.Write(writerType); _writer.WriteLine("(); } }"); GeneratePublicMethods(nameof(readMethods), "ReadMethods", readMethods, xmlMappings); GeneratePublicMethods("writeMethods", "WriteMethods", writerMethods, xmlMappings); GenerateTypedSerializers(serializers); GenerateSupportedTypes(types); GenerateGetSerializer(serializers, xmlMappings); _writer.Indent--; _writer.WriteLine("}"); } internal static bool IsWildcard(SpecialMapping mapping) { if (mapping is SerializableMapping) return ((SerializableMapping)mapping).IsAny; return mapping.TypeDesc!.CanBeElementValue; } } }
39.811138
216
0.560698
[ "MIT" ]
333fred/runtime
src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationGeneratedCode.cs
16,442
C#
using System; namespace YY.DBTools.Core.Helpers { public sealed class EnumHelper { public static T GetEnumValueByName<T>(string storageTypeByName) where T : struct, Enum { Enum.TryParse(storageTypeByName, true, out T EnumValue); return EnumValue; } } }
22.785714
94
0.623824
[ "MIT" ]
YPermitin/YY.DBTools
Libs/YY.DBTools.Core/Helpers/EnumHelper.cs
321
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Configuration; namespace DaisyFx.TestHelpers { public class SourceTestRunner<TSource, T> where TSource : ISource<T> { private readonly IServiceProvider _services; private readonly string _name; private readonly IConfiguration _configuration; public SourceTestRunner(IServiceProvider services, params (string key, string value)[] configurationValues) { _services = services; _name = typeof(TSource).Name; var configurationKeyValuePairs = configurationValues.Select( kv => new KeyValuePair<string, string>($"{_name}:{kv.key}", kv.value)); _configuration = new ConfigurationBuilder().AddInMemoryCollection(configurationKeyValuePairs).Build(); } public async Task Execute(SourceNextDelegate<T> next, CancellationToken ct) { using var source = InstanceFactory.Create<TSource>(_services, new("test", _name, _configuration)); await source.ExecuteAsync(next, ct); } } }
35.147059
115
0.683682
[ "Apache-2.0" ]
DaisyFx/DaisyFx
tests/DaisyFx.TestHelpers/SourceTestRunner.cs
1,197
C#
using CoreWCF.IdentityModel.Tokens; using CoreWCF; using System; using System.Collections.Generic; using System.Text; namespace CoreWCF.IdentityModel.Selectors { internal class SecurityTokenRequirement { const string Namespace = "http://schemas.microsoft.com/ws/2006/05/identitymodel/securitytokenrequirement"; const string tokenTypeProperty = Namespace + "/TokenType"; const string keyUsageProperty = Namespace + "/KeyUsage"; const string keyTypeProperty = Namespace + "/KeyType"; const string keySizeProperty = Namespace + "/KeySize"; const string requireCryptographicTokenProperty = Namespace + "/RequireCryptographicToken"; const string peerAuthenticationMode = Namespace + "/PeerAuthenticationMode"; const string isOptionalTokenProperty = Namespace + "/IsOptionalTokenProperty"; const bool defaultRequireCryptographicToken = false; const SecurityKeyUsage defaultKeyUsage = SecurityKeyUsage.Signature; const SecurityKeyType defaultKeyType = SecurityKeyType.SymmetricKey; const int defaultKeySize = 0; const bool defaultIsOptionalToken = false; Dictionary<string, object> properties; public SecurityTokenRequirement() { properties = new Dictionary<string, object>(); Initialize(); } static public string TokenTypeProperty { get { return tokenTypeProperty; } } static public string KeyUsageProperty { get { return keyUsageProperty; } } static public string KeyTypeProperty { get { return keyTypeProperty; } } static public string KeySizeProperty { get { return keySizeProperty; } } static public string RequireCryptographicTokenProperty { get { return requireCryptographicTokenProperty; } } static public string PeerAuthenticationMode { get { return peerAuthenticationMode; } } static public string IsOptionalTokenProperty { get { return isOptionalTokenProperty; } } public string TokenType { get { string result; return (TryGetProperty<string>(TokenTypeProperty, out result)) ? result : null; } set { properties[TokenTypeProperty] = value; } } internal bool IsOptionalToken { get { bool result; return (TryGetProperty<bool>(IsOptionalTokenProperty, out result)) ? result : defaultIsOptionalToken; } set { properties[IsOptionalTokenProperty] = value; } } public bool RequireCryptographicToken { get { bool result; return (TryGetProperty<bool>(RequireCryptographicTokenProperty, out result)) ? result : defaultRequireCryptographicToken; } set { properties[RequireCryptographicTokenProperty] = (object)value; } } public SecurityKeyUsage KeyUsage { get { SecurityKeyUsage result; return (TryGetProperty<SecurityKeyUsage>(KeyUsageProperty, out result)) ? result : defaultKeyUsage; } set { SecurityKeyUsageHelper.Validate(value); properties[KeyUsageProperty] = (object)value; } } public SecurityKeyType KeyType { get { SecurityKeyType result; return (TryGetProperty<SecurityKeyType>(KeyTypeProperty, out result)) ? result : defaultKeyType; } set { SecurityKeyTypeHelper.Validate(value); properties[KeyTypeProperty] = (object)value; } } public int KeySize { get { int result; return (TryGetProperty<int>(KeySizeProperty, out result)) ? result : defaultKeySize; } set { if (value < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(value), SR.ValueMustBeNonNegative)); } Properties[KeySizeProperty] = value; } } public IDictionary<string, object> Properties { get { return properties; } } void Initialize() { KeyType = defaultKeyType; KeyUsage = defaultKeyUsage; RequireCryptographicToken = defaultRequireCryptographicToken; KeySize = defaultKeySize; IsOptionalToken = defaultIsOptionalToken; } public TValue GetProperty<TValue>(string propertyName) { TValue result; if (!TryGetProperty<TValue>(propertyName, out result)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.SecurityTokenRequirementDoesNotContainProperty, propertyName))); } return result; } public bool TryGetProperty<TValue>(string propertyName, out TValue result) { object dictionaryValue; if (!Properties.TryGetValue(propertyName, out dictionaryValue)) { result = default(TValue); return false; } if (dictionaryValue != null && !typeof(TValue).IsAssignableFrom(dictionaryValue.GetType())) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.SecurityTokenRequirementHasInvalidTypeForProperty, propertyName, dictionaryValue.GetType(), typeof(TValue)))); } result = (TValue)dictionaryValue; return true; } } }
35.432749
219
0.588711
[ "MIT" ]
0x53A/CoreWCF
src/CoreWCF.Primitives/src/CoreWCF/IdentityModel/Selectors/SecurityTokenRequirement.cs
6,061
C#