content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
using System;
using Microsoft.EntityFrameworkCore.Migrations;
namespace Data.Migrations
{
public partial class Initial : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "AspNetRoles",
columns: table => new
{
Id = table.Column<string>(nullable: false),
Name = table.Column<string>(maxLength: 256, nullable: true),
NormalizedName = table.Column<string>(maxLength: 256, nullable: true),
ConcurrencyStamp = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetRoles", x => x.Id);
});
migrationBuilder.CreateTable(
name: "AspNetUsers",
columns: table => new
{
Id = table.Column<string>(nullable: false),
UserName = table.Column<string>(maxLength: 256, nullable: true),
NormalizedUserName = table.Column<string>(maxLength: 256, nullable: true),
Email = table.Column<string>(maxLength: 256, nullable: true),
NormalizedEmail = table.Column<string>(maxLength: 256, nullable: true),
EmailConfirmed = table.Column<bool>(nullable: false),
PasswordHash = table.Column<string>(nullable: true),
SecurityStamp = table.Column<string>(nullable: true),
ConcurrencyStamp = table.Column<string>(nullable: true),
PhoneNumber = table.Column<string>(nullable: true),
PhoneNumberConfirmed = table.Column<bool>(nullable: false),
TwoFactorEnabled = table.Column<bool>(nullable: false),
LockoutEnd = table.Column<DateTimeOffset>(nullable: true),
LockoutEnabled = table.Column<bool>(nullable: false),
AccessFailedCount = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUsers", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Directors",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
FullName = table.Column<string>(nullable: true),
Nationality = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Directors", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Genres",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Name = table.Column<string>(nullable: true),
Description = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Genres", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Grades",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Score = table.Column<double>(nullable: false),
Comment = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Grades", x => x.Id);
});
migrationBuilder.CreateTable(
name: "AspNetRoleClaims",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
RoleId = table.Column<string>(nullable: false),
ClaimType = table.Column<string>(nullable: true),
ClaimValue = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetRoleClaims", x => x.Id);
table.ForeignKey(
name: "FK_AspNetRoleClaims_AspNetRoles_RoleId",
column: x => x.RoleId,
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserClaims",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
UserId = table.Column<string>(nullable: false),
ClaimType = table.Column<string>(nullable: true),
ClaimValue = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserClaims", x => x.Id);
table.ForeignKey(
name: "FK_AspNetUserClaims_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserLogins",
columns: table => new
{
LoginProvider = table.Column<string>(nullable: false),
ProviderKey = table.Column<string>(nullable: false),
ProviderDisplayName = table.Column<string>(nullable: true),
UserId = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserLogins", x => new { x.LoginProvider, x.ProviderKey });
table.ForeignKey(
name: "FK_AspNetUserLogins_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserRoles",
columns: table => new
{
UserId = table.Column<string>(nullable: false),
RoleId = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserRoles", x => new { x.UserId, x.RoleId });
table.ForeignKey(
name: "FK_AspNetUserRoles_AspNetRoles_RoleId",
column: x => x.RoleId,
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_AspNetUserRoles_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserTokens",
columns: table => new
{
UserId = table.Column<string>(nullable: false),
LoginProvider = table.Column<string>(nullable: false),
Name = table.Column<string>(nullable: false),
Value = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserTokens", x => new { x.UserId, x.LoginProvider, x.Name });
table.ForeignKey(
name: "FK_AspNetUserTokens_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Movies",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Title = table.Column<string>(nullable: true),
ImageURL = table.Column<string>(nullable: true),
Year = table.Column<int>(nullable: false),
Description = table.Column<string>(nullable: true),
DirectorId = table.Column<int>(nullable: false),
GradeId = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Movies", x => x.Id);
table.ForeignKey(
name: "FK_Movies_Directors_DirectorId",
column: x => x.DirectorId,
principalTable: "Directors",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_Movies_Grades_GradeId",
column: x => x.GradeId,
principalTable: "Grades",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "MovieGenres",
columns: table => new
{
MovieId = table.Column<int>(nullable: false),
GenreId = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_MovieGenres", x => new { x.MovieId, x.GenreId });
table.ForeignKey(
name: "FK_MovieGenres_Genres_GenreId",
column: x => x.GenreId,
principalTable: "Genres",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_MovieGenres_Movies_MovieId",
column: x => x.MovieId,
principalTable: "Movies",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.InsertData(
table: "AspNetRoles",
columns: new[] { "Id", "ConcurrencyStamp", "Name", "NormalizedName" },
values: new object[] { "40dadb93-e16d-4624-a92c-516be0443baa", "c010a5eb-8782-4cb0-ac57-ac080d5d99e2", "User", "USER" });
migrationBuilder.InsertData(
table: "AspNetRoles",
columns: new[] { "Id", "ConcurrencyStamp", "Name", "NormalizedName" },
values: new object[] { "4b787043-51be-4016-bfed-43d24ca637e8", "7008ca50-ab6d-4345-92ae-e7ddf2e663f3", "Administrator", "ADMINISTRATOR" });
migrationBuilder.CreateIndex(
name: "IX_AspNetRoleClaims_RoleId",
table: "AspNetRoleClaims",
column: "RoleId");
migrationBuilder.CreateIndex(
name: "RoleNameIndex",
table: "AspNetRoles",
column: "NormalizedName",
unique: true,
filter: "[NormalizedName] IS NOT NULL");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserClaims_UserId",
table: "AspNetUserClaims",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserLogins_UserId",
table: "AspNetUserLogins",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserRoles_RoleId",
table: "AspNetUserRoles",
column: "RoleId");
migrationBuilder.CreateIndex(
name: "EmailIndex",
table: "AspNetUsers",
column: "NormalizedEmail");
migrationBuilder.CreateIndex(
name: "UserNameIndex",
table: "AspNetUsers",
column: "NormalizedUserName",
unique: true,
filter: "[NormalizedUserName] IS NOT NULL");
migrationBuilder.CreateIndex(
name: "IX_MovieGenres_GenreId",
table: "MovieGenres",
column: "GenreId");
migrationBuilder.CreateIndex(
name: "IX_Movies_DirectorId",
table: "Movies",
column: "DirectorId");
migrationBuilder.CreateIndex(
name: "IX_Movies_GradeId",
table: "Movies",
column: "GradeId");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "AspNetRoleClaims");
migrationBuilder.DropTable(
name: "AspNetUserClaims");
migrationBuilder.DropTable(
name: "AspNetUserLogins");
migrationBuilder.DropTable(
name: "AspNetUserRoles");
migrationBuilder.DropTable(
name: "AspNetUserTokens");
migrationBuilder.DropTable(
name: "MovieGenres");
migrationBuilder.DropTable(
name: "AspNetRoles");
migrationBuilder.DropTable(
name: "AspNetUsers");
migrationBuilder.DropTable(
name: "Genres");
migrationBuilder.DropTable(
name: "Movies");
migrationBuilder.DropTable(
name: "Directors");
migrationBuilder.DropTable(
name: "Grades");
}
}
}
| 41.935393 | 155 | 0.47391 | [
"MIT"
] | desitynikolova/Movies-ASP-NET-Core-Project | Data/Migrations/20210514112829_Initial.cs | 14,931 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BulletController : MonoBehaviour
{
public float speed;
private GameController gameController;
void Start()
{
var rb = GetComponent<Rigidbody>();
rb.velocity = transform.forward*speed;
gameController = GameObject.FindWithTag("GameController").GetComponent<GameController>();
}
//void OnTriggerEnter(Collider other)
//{
// if (other.CompareTag("Hazard"))
// {
// Destroy(gameObject);
// }
//}
void OnCollisionEnter(Collision other)
{
if (other.collider.CompareTag("Hazard"))
{
gameController.AddHit();
//Destroy(gameObject);
//Destroy(other.gameObject);
}
}
}
| 23.941176 | 97 | 0.60688 | [
"MIT"
] | kofon95/SpaceShooter | Assets/Scripts/BulletController.cs | 816 | C# |
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Natsnudasoft.RgbLedSequencerWebInterface.Data;
namespace Natsnudasoft.RgbLedSequencerWebInterface.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
[Migration("20170702114621_Initial")]
partial class Initial
{
[System.Diagnostics.CodeAnalysis.SuppressMessage(
"Microsoft.Design",
"CA1062",
Justification = "Validated not null.")]
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
modelBuilder
.HasAnnotation("ProductVersion", "1.1.2")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("Natsnudasoft.RgbLedSequencerWebInterface.Models.ColorStringItem", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int>("Index");
b.Property<int>("SequenceStepId");
b.Property<string>("Value")
.IsRequired()
.HasMaxLength(7);
b.HasKey("Id");
b.HasIndex("SequenceStepId");
b.ToTable("ColorString");
});
modelBuilder.Entity("Natsnudasoft.RgbLedSequencerWebInterface.Models.SequenceItem", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<byte>("SequenceIndex");
b.Property<string>("SequenceName")
.IsRequired()
.HasMaxLength(100);
b.Property<DateTimeOffset>("Timestamp");
b.HasKey("Id");
b.ToTable("Sequence");
});
modelBuilder.Entity("Natsnudasoft.RgbLedSequencerWebInterface.Models.SequenceStepItem", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int>("SequenceId");
b.Property<int>("StepDelay");
b.HasKey("Id");
b.HasIndex("SequenceId");
b.ToTable("SequenceStep");
});
modelBuilder.Entity("Natsnudasoft.RgbLedSequencerWebInterface.Models.ColorStringItem", b =>
{
b.HasOne("Natsnudasoft.RgbLedSequencerWebInterface.Models.SequenceStepItem", "SequenceStep")
.WithMany("Colors")
.HasForeignKey("SequenceStepId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Natsnudasoft.RgbLedSequencerWebInterface.Models.SequenceStepItem", b =>
{
b.HasOne("Natsnudasoft.RgbLedSequencerWebInterface.Models.SequenceItem", "Sequence")
.WithMany("Steps")
.HasForeignKey("SequenceId")
.OnDelete(DeleteBehavior.Cascade);
});
}
}
}
| 35 | 117 | 0.534821 | [
"Apache-2.0"
] | natsnudasoft/RgbLedSequencerWebInterface | src/RgbLedSequencerWebInterface/Migrations/20170702114621_Initial.Designer.cs | 3,360 | 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 ec2-2016-11-15.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.EC2.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
namespace Amazon.EC2.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for DescribeClientVpnRoutes operation
/// </summary>
public class DescribeClientVpnRoutesResponseUnmarshaller : EC2ResponseUnmarshaller
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public override AmazonWebServiceResponse Unmarshall(XmlUnmarshallerContext context)
{
DescribeClientVpnRoutesResponse response = new DescribeClientVpnRoutesResponse();
int originalDepth = context.CurrentDepth;
int targetDepth = originalDepth + 1;
if (context.IsStartOfDocument)
targetDepth = 2;
while (context.ReadAtDepth(originalDepth))
{
if (context.IsStartElement || context.IsAttribute)
{
if (context.TestExpression("nextToken", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.NextToken = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("routes/item", targetDepth))
{
var unmarshaller = ClientVpnRouteUnmarshaller.Instance;
var item = unmarshaller.Unmarshall(context);
response.Routes.Add(item);
continue;
}
}
}
return response;
}
/// <summary>
/// Unmarshaller error response to exception.
/// </summary>
/// <param name="context"></param>
/// <param name="innerException"></param>
/// <param name="statusCode"></param>
/// <returns></returns>
public override AmazonServiceException UnmarshallException(XmlUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode)
{
ErrorResponse errorResponse = ErrorResponseUnmarshaller.GetInstance().Unmarshall(context);
return new AmazonEC2Exception(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
private static DescribeClientVpnRoutesResponseUnmarshaller _instance = new DescribeClientVpnRoutesResponseUnmarshaller();
internal static DescribeClientVpnRoutesResponseUnmarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static DescribeClientVpnRoutesResponseUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 36.722222 | 158 | 0.625567 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/EC2/Generated/Model/Internal/MarshallTransformations/DescribeClientVpnRoutesResponseUnmarshaller.cs | 3,966 | C# |
using System;
using System.IO;
using System.Management;
namespace PurpleSharp.Lib
{
//Most of this is based on SharpExec (https://github.com/anthemtotheego/SharpExec)
class RemoteLauncher
{
public static string readFile(string rhost, string path, string ruser, string rpwd, string domain)
{
string txt = "";
path = @"\\"+rhost+"\\"+path.Replace(":", "$");
using (new Impersonation(domain, ruser, rpwd))
{
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
StreamReader sr = new StreamReader(fs);
txt = sr.ReadToEnd();
sr.Close();
}
return txt.Trim();
}
public static void upload(string uploadPath, string executionPath, string rhost, string ruser, string rpwd, string domain)
{
string share = executionPath.Replace(":", "$");
string destpath = @"\\" + rhost + @"\" + share;
if (ruser == "" && rpwd == "")
{
//string share = executionPath.Replace(":", "$");
//string destpath = @"\\" + rhost + @"\" + share;
//Console.WriteLine("[+] Grabbing file from " + uploadPath);
File.Copy(uploadPath, destpath);
Console.WriteLine("[+] File uploaded successfully");
}
else
{
using (new Impersonation(domain, ruser, rpwd))
{
//string share = executionPath.Replace(":", "$");
//string destpath = @"\\" + rhost + @"\" + share;
//Console.WriteLine("[+] Grabbing file from " + uploadPath);
/*
Console.WriteLine("ExecutionPath is: " + executionPath);
Console.WriteLine("uploadPath is: " + uploadPath);
Console.WriteLine("share is: " + share);
Console.WriteLine("destpath is is: " + destpath);
*/
File.Copy(uploadPath, destpath);
//Console.WriteLine("[+] File uploaded successfully");
}
}
}
public static void delete(string executionPath, string rhost, string username, string password, string domain)
{
try
{
if (username == "" && password == "")
{
string share = executionPath.Replace(":", "$");
string destpath = @"\\" + rhost + @"\" + share;
//Console.WriteLine("[+] Deleting " + destpath);
File.Delete(destpath);
//Console.WriteLine("[+] File removed successfully");
Console.WriteLine();
}
else
{
using (new Impersonation(domain, username, password))
{
string share = executionPath.Replace(":", "$");
string destpath = @"\\" + rhost + @"\" + share;
//Console.WriteLine("[+] Deleting " + destpath);
File.Delete(destpath);
//Console.WriteLine("[+] File removed successfully");
}
}
}
catch
{
Console.WriteLine("[!] File was not removed. Please remove manually");
}
}
public static void wmiexec(string rhost, string executionPath, string cmdArgs, string domain, string username, string password)
{
object[] myProcess = { executionPath + " " + cmdArgs };
if (username == "" && password == "")
{
ManagementScope myScope = new ManagementScope(String.Format("\\\\{0}\\root\\cimv2", rhost));
ManagementClass myClass = new ManagementClass(myScope, new ManagementPath("Win32_Process"), new ObjectGetOptions());
//Console.WriteLine("[+] Executing command: " + executionPath + " " + cmdArgs + " On:" + rhost);
myClass.InvokeMethod("Create", myProcess);
//Console.WriteLine("[!] Process created successfully");
}
else
{
ConnectionOptions myConnection = new ConnectionOptions();
string uname = domain + @"\" + username;
myConnection.Impersonation = ImpersonationLevel.Impersonate;
myConnection.EnablePrivileges = true;
myConnection.Timeout = new TimeSpan(0, 0, 30);
myConnection.Username = uname;
myConnection.Password = password;
ManagementScope myScope = new ManagementScope(String.Format("\\\\{0}\\root\\cimv2", rhost), myConnection);
ManagementClass myClass = new ManagementClass(myScope, new ManagementPath("Win32_Process"), new ObjectGetOptions());
//Console.WriteLine("[+] Executing command " + executionPath + " " + cmdArgs + " on:" + rhost);
myClass.InvokeMethod("Create", myProcess);
//Console.WriteLine("[!] Process created successfully");
}
}
}
} | 42.736 | 135 | 0.496818 | [
"BSD-3-Clause"
] | FDlucifer/PurpleSharp | PurpleSharp/Lib/RemoteLauncher.cs | 5,344 | C# |
using Microsoft.EntityFrameworkCore.Migrations;
namespace TinTucCongNghe.Migrations
{
public partial class TinTucCongNghe : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
}
protected override void Down(MigrationBuilder migrationBuilder)
{
}
}
}
| 18.833333 | 71 | 0.675516 | [
"MIT"
] | nmsdzbmt/TinTucCongNghe-Angular-ABP | aspnet-core/src/TinTucCongNghe.EntityFrameworkCore/Migrations/20210619100412_TinTucCongNghe.cs | 341 | C# |
namespace SqlNotebook {
partial class OptionsForm {
/// <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._okBtn = new System.Windows.Forms.Button();
this._cancelBtn = new System.Windows.Forms.Button();
this._autoCreateChk = new System.Windows.Forms.CheckBox();
this._autoCreateCmb = new System.Windows.Forms.ComboBox();
this._helpExternalBrowserChk = new System.Windows.Forms.CheckBox();
this.SuspendLayout();
//
// _okBtn
//
this._okBtn.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this._okBtn.Location = new System.Drawing.Point(242, 85);
this._okBtn.Name = "_okBtn";
this._okBtn.Size = new System.Drawing.Size(88, 26);
this._okBtn.TabIndex = 0;
this._okBtn.Text = "OK";
this._okBtn.UseVisualStyleBackColor = true;
this._okBtn.Click += new System.EventHandler(this.OkBtn_Click);
//
// _cancelBtn
//
this._cancelBtn.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this._cancelBtn.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this._cancelBtn.Location = new System.Drawing.Point(336, 85);
this._cancelBtn.Name = "_cancelBtn";
this._cancelBtn.Size = new System.Drawing.Size(88, 26);
this._cancelBtn.TabIndex = 1;
this._cancelBtn.Text = "Cancel";
this._cancelBtn.UseVisualStyleBackColor = true;
//
// _autoCreateChk
//
this._autoCreateChk.AutoSize = true;
this._autoCreateChk.Location = new System.Drawing.Point(12, 13);
this._autoCreateChk.Name = "_autoCreateChk";
this._autoCreateChk.Size = new System.Drawing.Size(235, 19);
this._autoCreateChk.TabIndex = 2;
this._autoCreateChk.Text = "Automatically create in new notebooks:";
this._autoCreateChk.UseVisualStyleBackColor = true;
this._autoCreateChk.CheckedChanged += new System.EventHandler(this.AutoCreateChk_CheckedChanged);
//
// _autoCreateCmb
//
this._autoCreateCmb.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this._autoCreateCmb.FormattingEnabled = true;
this._autoCreateCmb.Items.AddRange(new object[] {
"New note",
"New console",
"New script"});
this._autoCreateCmb.Location = new System.Drawing.Point(253, 10);
this._autoCreateCmb.Name = "_autoCreateCmb";
this._autoCreateCmb.Size = new System.Drawing.Size(108, 23);
this._autoCreateCmb.TabIndex = 3;
//
// _helpExternalBrowserChk
//
this._helpExternalBrowserChk.AutoSize = true;
this._helpExternalBrowserChk.Location = new System.Drawing.Point(12, 39);
this._helpExternalBrowserChk.Name = "_helpExternalBrowserChk";
this._helpExternalBrowserChk.Size = new System.Drawing.Size(281, 19);
this._helpExternalBrowserChk.TabIndex = 4;
this._helpExternalBrowserChk.Text = "Use external browser for viewing documentation";
this._helpExternalBrowserChk.UseVisualStyleBackColor = true;
//
// OptionsForm
//
this.AcceptButton = this._okBtn;
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.CancelButton = this._cancelBtn;
this.ClientSize = new System.Drawing.Size(436, 123);
this.Controls.Add(this._helpExternalBrowserChk);
this.Controls.Add(this._autoCreateCmb);
this.Controls.Add(this._autoCreateChk);
this.Controls.Add(this._cancelBtn);
this.Controls.Add(this._okBtn);
this.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "OptionsForm";
this.ShowIcon = false;
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Options";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button _okBtn;
private System.Windows.Forms.Button _cancelBtn;
private System.Windows.Forms.CheckBox _autoCreateChk;
private System.Windows.Forms.ComboBox _autoCreateCmb;
private System.Windows.Forms.CheckBox _helpExternalBrowserChk;
}
} | 48.138211 | 161 | 0.613748 | [
"MIT"
] | mfrigillana/sqlnotebook | src/SqlNotebook/OptionsForm.Designer.cs | 5,923 | C# |
using System;
using System.Runtime.Serialization;
namespace ValveQuery
{
/// <summary>
/// Base for all GameServer Exception.
/// </summary>
[Serializable]
public class GameServerException : Exception
{
public GameServerException()
: base()
{
}
public GameServerException(string message)
: base(message)
{
}
public GameServerException(string message, Exception innerException)
: base(message, innerException)
{
}
protected GameServerException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
}
}
| 17.272727 | 81 | 0.712281 | [
"MIT"
] | Deathreus/ValveQuery | ValveQuery/Exceptions/GameServerException.cs | 570 | C# |
// -------------------------------------------------------------------------
// Copyright © 2019 Province of British Columbia
//
// 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 HealthGateway.Database.Models
{
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using HealthGateway.Database.Constants;
/// <summary>
/// A model object storing VaccineProof Requests.
/// </summary>
public class VaccineProofRequestCache : AuditableEntity
{
/// <summary>
/// Gets or sets the unique id for this entry.
/// </summary>
[Column("VaccineProofRequestCacheId")]
public Guid Id { get; set; }
/// <summary>
/// Gets or sets a unique identifier for the person of this entry.
/// </summary>
[Required]
[MaxLength(54)]
public string? PersonIdentifier { get; set; }
/// <summary>
/// Gets or sets the base6 encoded md5 hash of the SHC Image.
/// </summary>
[Required]
public string? ShcImageHash { get; set; }
/// <summary>
/// Gets or sets the VaccineProofTemplate used for the entry.
/// </summary>
[Required]
public VaccineProofTemplate ProofTemplate { get; set; }
/// <summary>
/// Gets or sets the date and time when this entry expires.
/// </summary>
[Required]
public DateTime? ExpiryDateTime { get; set; }
/// <summary>
/// Gets or sets the associated response id from the Vaccine Proof Request.
/// </summary>
[Required]
public string? VaccineProofResponseId { get; set; }
}
}
| 35.212121 | 83 | 0.590361 | [
"Apache-2.0"
] | bcgov/healthgateway | Apps/Database/src/Models/VaccineProofRequestCache.cs | 2,325 | C# |
/*
* Copyright (c) 2018 THL A29 Limited, a Tencent company. 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.
*/
namespace TencentCloud.Essbasic.V20210526.Models
{
using Newtonsoft.Json;
using System.Collections.Generic;
using TencentCloud.Common;
public class CreateConsoleLoginUrlResponse : AbstractModel
{
/// <summary>
/// 控制台url
/// </summary>
[JsonProperty("ConsoleUrl")]
public string ConsoleUrl{ get; set; }
/// <summary>
/// 渠道合作企业是否认证开通腾讯电子签。
/// 当渠道合作企业未完成认证开通腾讯电子签,建议先调用同步企业信息(SyncProxyOrganization)和同步经办人信息(SyncProxyOrganizationOperators)接口成功后再跳转到登录页面。
/// </summary>
[JsonProperty("IsActivated")]
public bool? IsActivated{ get; set; }
/// <summary>
/// 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
/// </summary>
[JsonProperty("RequestId")]
public string RequestId{ get; set; }
/// <summary>
/// For internal usage only. DO NOT USE IT.
/// </summary>
public override void ToMap(Dictionary<string, string> map, string prefix)
{
this.SetParamSimple(map, prefix + "ConsoleUrl", this.ConsoleUrl);
this.SetParamSimple(map, prefix + "IsActivated", this.IsActivated);
this.SetParamSimple(map, prefix + "RequestId", this.RequestId);
}
}
}
| 32.711864 | 120 | 0.648705 | [
"Apache-2.0"
] | TencentCloud/tencentcloud-sdk-dotnet | TencentCloud/Essbasic/V20210526/Models/CreateConsoleLoginUrlResponse.cs | 2,134 | 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.
namespace Microsoft.ML.Runtime.Data
{
/// <summary>
/// A class for mapping an input to an output cursor assuming no output columns
/// are requested, given a bindings object. This can be useful for transforms
/// utilizing the <see cref="ColumnBindingsBase"/>, but for which it is
/// inconvenient or inefficient to handle the "no output selected" case in their
/// own implementation.
/// </summary>
public sealed class BindingsWrappedRowCursor : SynchronizedCursorBase<IRowCursor>, IRowCursor
{
private readonly ColumnBindingsBase _bindings;
public Schema Schema => _bindings.AsSchema;
/// <summary>
/// Creates a wrapped version of the cursor
/// </summary>
/// <param name="provider">Channel provider</param>
/// <param name="input">The input cursor</param>
/// <param name="bindings">The bindings object, </param>
public BindingsWrappedRowCursor(IChannelProvider provider, IRowCursor input, ColumnBindingsBase bindings)
: base(provider, input)
{
Ch.CheckValue(input, nameof(input));
Ch.CheckValue(bindings, nameof(bindings));
_bindings = bindings;
}
public bool IsColumnActive(int col)
{
Ch.Check(0 <= col & col < _bindings.ColumnCount, "col");
bool isSrc;
col = _bindings.MapColumnIndex(out isSrc, col);
return isSrc && Input.IsColumnActive(col);
}
public ValueGetter<TValue> GetGetter<TValue>(int col)
{
Ch.Check(IsColumnActive(col), "col");
bool isSrc;
col = _bindings.MapColumnIndex(out isSrc, col);
Ch.Assert(isSrc);
return Input.GetGetter<TValue>(col);
}
}
}
| 37.962264 | 113 | 0.629722 | [
"MIT"
] | ArieJones/machinelearning | src/Microsoft.ML.Data/Transforms/BindingsWrappedRowCursor.cs | 2,012 | C# |
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using MonoDragons.Core.Graphics;
using MonoDragons.Core.Scenes;
using System;
using MonoDragons.Core.Physics;
namespace MonoDragons.Core.Render
{
public sealed class HideViewportExternals : IScene
{
private readonly IScene _inner;
private readonly MustInit<Texture2D> _black = new MustInit<Texture2D>(nameof(HideViewportExternals));
public HideViewportExternals(IScene inner)
{
_inner = inner;
}
public void Init()
{
_inner.Init();
_black.Init(new RectangleTexture(Color.Black).Create());
}
public void Update(TimeSpan delta)
{
_inner.Update(delta);
}
public void Draw(Transform2 transform)
{
_inner.Draw(transform);
HideExternals();
}
private void HideExternals()
{
World.Draw(_black.Get(), new Rectangle(new Point((int)Math.Round(CurrentDisplay.GameWidth / CurrentDisplay.Scale), 0),
new Point(5000, 5000)), Color.Black);
World.Draw(_black.Get(), new Rectangle(new Point(0, (int)Math.Round(CurrentDisplay.GameHeight / CurrentDisplay.Scale)),
new Point(5000, 5000)), Color.Black);
}
public void Dispose()
{
}
}
} | 28.408163 | 131 | 0.608477 | [
"MIT"
] | EnigmaDragons/ZFS | src/MonoDragons.Core/Render/HideViewportExternals.cs | 1,394 | C# |
// Copyright Naked Objects Group Ltd, 45 Station Road, Henley on Thames, UK, RG9 1AT
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and limitations under the License.
using System;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using Microsoft.Extensions.Logging;
using NakedFramework.Architecture.Adapter;
using NakedFramework.Architecture.Facet;
using NakedFramework.Architecture.Framework;
using NakedFramework.Architecture.Interactions;
using NakedFramework.Architecture.Spec;
using NakedFramework.Core.Util;
using NakedFramework.Metamodel.Error;
using NakedFramework.Metamodel.Facet;
namespace NakedObjects.Reflector.Facet {
[Serializable]
public sealed class ActionValidationFacet : FacetAbstract, IActionValidationFacet, IImperativeFacet {
private readonly ILogger<ActionValidationFacet> logger;
private readonly MethodInfo method;
[field: NonSerialized] private Func<object, object[], object> methodDelegate;
public ActionValidationFacet(MethodInfo method, ISpecification holder, ILogger<ActionValidationFacet> logger)
: base(typeof(IActionValidationFacet), holder) {
this.method = method;
this.logger = logger;
methodDelegate = LogNull(DelegateUtils.CreateDelegate(method), logger);
}
protected override string ToStringValues() => $"method={method}";
[OnDeserialized]
private void OnDeserialized(StreamingContext context) => methodDelegate = LogNull(DelegateUtils.CreateDelegate(method), logger);
#region IActionValidationFacet Members
public string Invalidates(IInteractionContext ic) => InvalidReason(ic.Target, ic.Framework, ic.ProposedArguments);
public Exception CreateExceptionFor(IInteractionContext ic) => new ActionArgumentsInvalidException(ic, Invalidates(ic));
public string InvalidReason(INakedObjectAdapter target, INakedFramework framework, INakedObjectAdapter[] proposedArguments) {
if (methodDelegate != null) {
return (string) methodDelegate(target.GetDomainObject(), proposedArguments.Select(no => no.GetDomainObject()).ToArray());
}
//Fall back (e.g. if method has > 6 params) on reflection...
logger.LogWarning($"Invoking validate method via reflection as no delegate {target}.{method}");
return (string) InvokeUtils.Invoke(method, target, proposedArguments);
}
#endregion
#region IImperativeFacet Members
public MethodInfo GetMethod() => method;
public Func<object, object[], object> GetMethodDelegate() => methodDelegate;
#endregion
}
// Copyright (c) Naked Objects Group Ltd.
} | 45.642857 | 137 | 0.734898 | [
"Apache-2.0"
] | NakedObjectsGroup/NakedObjectsFramework | NakedObjects/NakedObjects.Reflector/Facet/ActionValidationFacet.cs | 3,195 | 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 redshift-2012-12-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.Redshift.Model
{
/// <summary>
/// Container for the parameters to the DescribeDefaultClusterParameters operation.
/// Returns a list of parameter settings for the specified parameter group family.
///
///
/// <para>
/// For more information about parameters and parameter groups, go to <a href="https://docs.aws.amazon.com/redshift/latest/mgmt/working-with-parameter-groups.html">Amazon
/// Redshift Parameter Groups</a> in the <i>Amazon Redshift Cluster Management Guide</i>.
/// </para>
/// </summary>
public partial class DescribeDefaultClusterParametersRequest : AmazonRedshiftRequest
{
private string _marker;
private int? _maxRecords;
private string _parameterGroupFamily;
/// <summary>
/// Gets and sets the property Marker.
/// <para>
/// An optional parameter that specifies the starting point to return a set of response
/// records. When the results of a <a>DescribeDefaultClusterParameters</a> request exceed
/// the value specified in <code>MaxRecords</code>, AWS returns a value in the <code>Marker</code>
/// field of the response. You can retrieve the next set of response records by providing
/// the returned marker value in the <code>Marker</code> parameter and retrying the request.
///
/// </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 response records to return in each call. If the number of remaining
/// response records exceeds the specified <code>MaxRecords</code> value, a value is returned
/// in a <code>marker</code> field of the response. You can retrieve the next set of records
/// by retrying the command with the returned marker value.
/// </para>
///
/// <para>
/// Default: <code>100</code>
/// </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 ParameterGroupFamily.
/// <para>
/// The name of the cluster parameter group family.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public string ParameterGroupFamily
{
get { return this._parameterGroupFamily; }
set { this._parameterGroupFamily = value; }
}
// Check to see if ParameterGroupFamily property is set
internal bool IsSetParameterGroupFamily()
{
return this._parameterGroupFamily != null;
}
}
} | 35.596639 | 175 | 0.622521 | [
"Apache-2.0"
] | DetlefGolze/aws-sdk-net | sdk/src/Services/Redshift/Generated/Model/DescribeDefaultClusterParametersRequest.cs | 4,236 | C# |
/* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms,
* with or without modification, are permitted provided
* that the following conditions are met:
*
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
using NUnit.Framework;
using XenAdmin;
using XenAdmin.Controls;
using XenAdmin.Plugins;
using XenAPI;
namespace XenAdminTests.TabsAndMenus
{
[TestFixture, Category(TestCategories.UICategoryB)]
public class PluginTabsAndMenus : TabsAndMenus
{
private List<string> _folders = new List<string>();
private readonly string[] XenCenterTabs = new[] {"Home", "XenCenterTabPageTest", "Search"};
private readonly string[] PoolTabs = new[] { "General", "Memory", "Storage", "Networking", "HA", "WLB", "Users", "PoolTabPageTest", "AllTabPageTest", "Search" };
private readonly string[] HostTabs = new[] { "General", "Memory", "Storage", "Networking", "NICs", "Console", "Performance", "Users", "ServerTabPageTest", "AllTabPageTest", "Search" };
private readonly string[] VMTabs = new[] { "General", "Memory", "Storage", "Networking", "Console", "Performance", "Snapshots", "VMTabPageTest", "AllTabPageTest", "Search" };
private readonly string[] DefaultTemplateTabs = new[] { "General", "Memory", "Networking", "DefaultTemplateTabPageTest", "AllTabPageTest", "Search" };
private readonly string[] UserTemplateTabs = new[] { "General", "Memory", "Storage", "Networking", "UserTemplateTabPageTest", "AllTabPageTest", "Search" };
private readonly string[] SRTabs = new[] { "General", "Storage", "SRTabPageTest", "AllTabPageTest", "Search" };
public PluginTabsAndMenus()
: base("state4.xml")
{
CheckHelp = false;
}
[TestFixtureSetUp]
public void TestFixtureSetUp()
{
string plugins = Path.Combine(Program.AssemblyDir, "Plugins");
string vendorDir = "plugin-vendor";
string[] names = new string[] { "MenuItemFeatureTestPlugin", "ParentMenuItemFeatureTestPlugin", "TabPageFeatureTestPlugin" };
foreach (string name in names)
{
string folder = plugins + "\\" + vendorDir + "\\" + name;
string file = folder + "\\" + name + ".xcplugin.xml";
if (!Directory.Exists(folder))
{
_folders.Add(folder);
Directory.CreateDirectory(folder);
}
Assembly assembly = Assembly.GetExecutingAssembly();
Stream stream = assembly.GetManifestResourceStream("XenAdminTests.TestResources.PluginResources." + name + ".xcplugin.xml");
using (StreamReader sr = new StreamReader(stream))
{
File.WriteAllText(file, sr.ReadToEnd());
}
}
MW(delegate
{
MainWindowWrapper.PluginManager.ReloadPlugins();
});
EnableAllPlugins();
}
[TestFixtureTearDown]
public void TestFixtureTearDown()
{
foreach (string folder in _folders)
{
if (Directory.Exists(folder))
{
Directory.Delete(folder, true);
}
}
MW(delegate
{
MainWindowWrapper.PluginManager.ReloadPlugins();
});
}
[Test]
public void Tabs_XenCenterNode()
{
VerifyTabs(null, XenCenterTabs);
}
[Test]
public void Tabs_Pool()
{
VerifyTabs(GetAnyPool(), PoolTabs);
}
[Test]
public void Tabs_Host()
{
foreach (Host host in GetAllXenObjects<Host>())
{
VerifyTabs(host, HostTabs);
}
}
[Test]
public void Tabs_VM()
{
foreach (VM vm in GetAllXenObjects<VM>(v => !v.is_a_template && !v.is_control_domain))
{
VerifyTabs(vm, VMTabs);
}
}
[Test]
public void Tabs_DefaultTemplate()
{
EnsureDefaultTemplatesShown();
VerifyTabs(GetAnyDefaultTemplate(), DefaultTemplateTabs);
}
[Test]
public void Tabs_UserTemplate()
{
EnsureDefaultTemplatesShown();
foreach (VM vm in GetAllXenObjects<VM>(v => v.is_a_template && !v.DefaultTemplate && !v.is_a_snapshot))
{
VerifyTabs(vm, UserTemplateTabs);
}
}
[Test]
public void Tabs_SR()
{
EnsureChecked(MainWindowWrapper.ViewMenuItems.LocalStorageToolStripMenuItem);
foreach (SR sr in GetAllXenObjects<SR>(s => !s.IsToolsSR))
{
VerifyTabs(sr, SRTabs);
}
}
[Test]
public void TestMenuItems()
{
MW(delegate
{
MainWindowWrapper.FileMenu.ShowDropDown();
Assert.AreEqual("the label", GetVisibleToolStripItems(MainWindowWrapper.FileMenu.DropDownItems)[6].Text);
Assert.AreEqual("groupTest", GetVisibleToolStripItems(MainWindowWrapper.FileMenu.DropDownItems)[7].Text);
MainWindowWrapper.ViewMenu.ShowDropDown();
Assert.AreEqual("view_ShellTest1", GetVisibleToolStripItems(MainWindowWrapper.ViewMenu.DropDownItems)[5].Text);
MainWindowWrapper.PoolMenu.ShowDropDown();
Assert.AreEqual("pool_ShellTest1", GetVisibleToolStripItems(MainWindowWrapper.PoolMenu.DropDownItems)[20].Text);
MainWindowWrapper.HostMenu.ShowDropDown();
Assert.AreEqual("server_ShellTest1", GetVisibleToolStripItems(MainWindowWrapper.HostMenu.DropDownItems)[21].Text);
MainWindowWrapper.VMMenu.ShowDropDown();
Assert.AreEqual("vm_ShellTest1", GetVisibleToolStripItems(MainWindowWrapper.VMMenu.DropDownItems)[19].Text);
MainWindowWrapper.TemplatesMenu.ShowDropDown();
Assert.AreEqual("templates_ShellTest1", GetVisibleToolStripItems(MainWindowWrapper.TemplatesMenu.DropDownItems)[7].Text);
MainWindowWrapper.ToolsMenu.ShowDropDown();
Assert.AreEqual("tools_ShellTest1", GetVisibleToolStripItems(MainWindowWrapper.ToolsMenu.DropDownItems)[8].Text);
MainWindowWrapper.HelpMenu.ShowDropDown();
Assert.AreEqual("help_ShellTest1", GetVisibleToolStripItems(MainWindowWrapper.HelpMenu.DropDownItems)[8].Text);
});
}
[Test]
public void ClickAllNodes()
{
MW(delegate
{
foreach (VirtualTreeNode node in new List<VirtualTreeNode>(MainWindowWrapper.TreeView.AllNodes))
{
node.EnsureVisible();
node.TreeView.SelectedNode = node;
Application.DoEvents();
foreach (TabPage page in MainWindowWrapper.TheTabControl.TabPages)
{
if (page.Tag is TabPageFeature)
{
MainWindowWrapper.TheTabControl.SelectedTab = page;
Application.DoEvents();
}
}
}
});
}
}
}
| 39.704846 | 193 | 0.581826 | [
"BSD-2-Clause"
] | GaborApatiNagy/xenadmin | XenAdminTests/TabsAndMenus/PluginTabsAndMenus.cs | 9,015 | C# |
using MediatR;
using Microsoft.Extensions.Logging;
namespace CleanArchitecture.Application.Common.Behaviours;
public class UnhandledExceptionBehaviour<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse> where TRequest : notnull
{
private readonly ILogger<TRequest> _logger;
public UnhandledExceptionBehaviour(ILogger<TRequest> logger)
{
_logger = logger;
}
public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)
{
try
{
return await next();
}
catch (Exception ex)
{
var requestName = typeof(TRequest).Name;
_logger.LogError(ex, "CleanArchitecture Request: Unhandled Exception for Request {Name} {@Request}", requestName, request);
throw;
}
}
}
| 28.032258 | 135 | 0.681243 | [
"MIT"
] | AamilShohail/Clean-Architecture- | src/Application/Common/Behaviours/UnhandledExceptionBehaviour.cs | 871 | C# |
//#define SUPPRESS_BOOLINTEXPLOIT
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using UELib.Tokens;
namespace UELib.Core
{
using System.Text;
public partial class UStruct
{
/// <summary>
/// Decompiles the bytecodes from the 'Owner'
/// </summary>
public partial class UByteCodeDecompiler : IUnrealDecompilable
{
/// <summary>
/// The Struct that contains the bytecode that we have to deserialize and decompile!
/// </summary>
private readonly UStruct _Container;
/// <summary>
/// Pointer to the ObjectStream buffer of 'Owner'
/// </summary>
private UObjectStream Buffer{ get{ return _Container.Buffer; } }
private UnrealPackage Package{ get{ return _Container.Package; } }
/// <summary>
/// A collection of deserialized tokens, in their correspondence stream order.
/// </summary>
public List<Token> DeserializedTokens{ get; private set; }
[System.ComponentModel.DefaultValue(-1)]
public int CurrentTokenIndex{ get; set; }
public Token NextToken
{
get{ return DeserializedTokens[++ CurrentTokenIndex]; }
}
public Token PeekToken
{
[Pure]get{ return DeserializedTokens[CurrentTokenIndex + 1]; }
}
public Token PreviousToken
{
[Pure]get{ return DeserializedTokens[CurrentTokenIndex - 1]; }
}
public Token CurrentToken
{
[Pure]get{ return DeserializedTokens[CurrentTokenIndex]; }
}
public UByteCodeDecompiler( UStruct container )
{
_Container = container;
AlignMemorySizes();
}
#region Deserialize
/// <summary>
/// The current simulated-memory-aligned position in @Buffer.
/// </summary>
private uint CodePosition{ get; set; }
private const byte IndexMemorySize = 4;
private byte _NameMemorySize = IndexMemorySize;
private byte _ObjectMemorySize = IndexMemorySize;
private void AlignMemorySizes()
{
const short vNameSizeTo8 = 500;
if( Buffer.Version >= vNameSizeTo8 )
{
_NameMemorySize = 8;
}
const short vObjectSizeTo8 = 587;
if( Buffer.Version >= vObjectSizeTo8
#if TERA
&& Package.Build != UnrealPackage.GameBuild.BuildName.Tera
#endif
)
{
_ObjectMemorySize = 8;
}
}
private void AlignSize( byte size )
{
CodePosition += size;
}
private void AlignSize( int size )
{
AlignSize( (byte)size );
}
private void AlignNameSize()
{
AlignSize( _NameMemorySize );
}
private void AlignObjectSize()
{
AlignSize( _ObjectMemorySize );
}
/// <summary>
/// Fix the values of UE1/UE2 tokens to match the UE3 token values.
/// </summary>
private byte FixToken( byte tokenCode )
{
// Adjust UE2 tokens to UE3
if( _Container.Package.Version >= 184
&&
(
(tokenCode >= (byte)ExprToken.Unknown && tokenCode < (byte)ExprToken.ReturnNothing)
||
(tokenCode > (byte)ExprToken.NoDelegate && tokenCode < (byte)ExprToken.ExtendedNative))
)
{
++ tokenCode;
}
#if APB
if( _Container.Package.Build == UnrealPackage.GameBuild.BuildName.APB && _Container.Package.LicenseeVersion >= 32 )
{
if( tokenCode == (byte)ExprToken.Return )
{
tokenCode = (byte)ExprToken.LocalVariable;
}
else if( tokenCode == (byte)ExprToken.LocalVariable )
{
tokenCode = (byte)ExprToken.Return;
}
else if( tokenCode == (byte)ExprToken.Jump )
{
tokenCode = (byte)ExprToken.JumpIfNot;
}
else if( tokenCode == (byte)ExprToken.JumpIfNot )
{
tokenCode = (byte)ExprToken.Jump;
}
else if( tokenCode == (byte)ExprToken.Case )
{
tokenCode = (byte)ExprToken.Nothing;
}
else if( tokenCode == (byte)ExprToken.Nothing )
{
tokenCode = (byte)ExprToken.Case;
}
}
#endif
return tokenCode;
}
private bool _WasDeserialized;
public void Deserialize()
{
if( _WasDeserialized )
return;
_WasDeserialized = true;
try
{
_Container.EnsureBuffer();
Buffer.Seek( _Container.ScriptOffset, System.IO.SeekOrigin.Begin );
CodePosition = 0;
var codeSize = _Container.ByteScriptSize;
CurrentTokenIndex = -1;
DeserializedTokens = new List<Token>();
_Labels = new List<ULabelEntry>();
while( CodePosition < codeSize )
{
try
{
var t = DeserializeNext();
if( !(t is EndOfScriptToken) )
continue;
if( CodePosition < codeSize )
{
Console.WriteLine( "End of script detected, but the loop condition is still true." );
}
break;
}
catch( SystemException e )
{
if( e is System.IO.EndOfStreamException )
{
Console.WriteLine( "Couldn't backup from this error! Decompiling aborted!" );
return;
}
Console.WriteLine( "Object:" + _Container.Name );
Console.WriteLine( "Failed to deserialize token at position:" + CodePosition );
Console.WriteLine( "Exception:" + e.Message );
Console.WriteLine( "Stack:" + e.StackTrace );
}
}
}
finally
{
_Container.MaybeDisposeBuffer();
}
}
private void DeserializeDebugToken()
{
Buffer.StartPeek();
byte token = FixToken( Buffer.ReadByte() );
Buffer.EndPeek();
if( token == (byte)ExprToken.DebugInfo )
{
DeserializeNext();
}
}
private NativeFunctionToken FindNativeTable( int nativeIndex )
{
var nativeFuncToken = new NativeFunctionToken();
try
{
var nativeTableItem = _Container.Package.NTLPackage != null
? _Container.Package.NTLPackage.FindTableItem( nativeIndex )
: null;
if( nativeTableItem != null )
{
nativeFuncToken.NativeTable = nativeTableItem;
}
else
{
// TODO: Rewrite as FindChild( lambda )
var table = _Container.Package.Exports.Find(
e => (e.ClassName == "Function" && ((UFunction)(e.Object)).NativeToken == nativeIndex)
);
if( table != null )
{
var func = table.Object as UFunction;
if( func != null )
{
nativeTableItem = new NativeTableItem( func );
nativeFuncToken.NativeTable = nativeTableItem;
}
}
}
}
catch( ArgumentOutOfRangeException )
{
// ...
}
return nativeFuncToken;
}
private Token DeserializeNext( byte tokenCode = Byte.MaxValue )
{
var tokenPosition = CodePosition;
if( tokenCode == Byte.MaxValue )
{
tokenCode = FixToken( Buffer.ReadByte() );
AlignSize( sizeof(byte) );
}
Token tokenItem = null;
if( tokenCode >= (byte)ExprToken.FirstNative )
{
tokenItem = FindNativeTable( tokenCode );
}
else if( tokenCode >= (byte)ExprToken.ExtendedNative )
{
tokenItem = FindNativeTable( (tokenCode - (byte)ExprToken.ExtendedNative) << 8 | Buffer.ReadByte() );
AlignSize( sizeof(byte) );
}
else switch( tokenCode )
{
#region Cast
case (byte)ExprToken.DynamicCast:
tokenItem = new DynamicCastToken();
break;
case (byte)ExprToken.MetaCast:
tokenItem = new MetaCastToken();
break;
case (byte)ExprToken.InterfaceCast:
if( Buffer.Version < PrimitveCastVersion ) // UE1
{
tokenItem = new IntToStringToken();
}
else
{
tokenItem = new InterfaceCastToken();
}
break;
// Redefined, can be RotatorToVector!(UE1)
case (byte)ExprToken.PrimitiveCast:
if( Buffer.Version < PrimitveCastVersion ) // UE1
{
tokenItem = new RotatorToVectorToken();
}
else // UE2+
{
// Next byte represents the CastToken!
tokenCode = Buffer.ReadByte();
AlignSize( sizeof(byte) );
tokenItem = DeserializeCastToken( tokenCode );
//tokenitem = new PrimitiveCastToken();
}
break;
#endregion
#region Context
case (byte)ExprToken.ClassContext:
tokenItem = new ClassContextToken();
break;
case (byte)ExprToken.InterfaceContext:
if( Buffer.Version < PrimitveCastVersion )
{
tokenItem = new ByteToStringToken();
}
else
{
tokenItem = new InterfaceContextToken();
}
break;
case (byte)ExprToken.Context:
tokenItem = new ContextToken();
break;
case (byte)ExprToken.StructMember:
tokenItem = new StructMemberToken();
break;
#endregion
#region Assigns
case (byte)ExprToken.Let:
tokenItem = new LetToken();
break;
case (byte)ExprToken.LetBool:
tokenItem = new LetBoolToken();
break;
case (byte)ExprToken.EndParmValue:
tokenItem = new EndParmValueToken();
break;
// Redefined, can be FloatToBool!(UE1)
case (byte)ExprToken.LetDelegate:
if( Buffer.Version < PrimitveCastVersion )
{
tokenItem = new FloatToBoolToken();
}
else
{
tokenItem = new LetDelegateToken();
}
break;
// Redefined, can be NameToBool!(UE1)
case (byte)ExprToken.Conditional:
tokenItem = new ConditionalToken();
break;
case (byte)ExprToken.Eval: // case (byte)ExprToken.DynArrayFindStruct: case (byte)ExprToken.Conditional:
if( Buffer.Version < PrimitveCastVersion )
{
tokenItem = new NameToBoolToken();
}
else if( Buffer.Version >= 300 )
{
tokenItem = new DynamicArrayFindStructToken();
}
else
{
tokenItem = new ConditionalToken();
}
break;
#endregion
#region Jumps
case (byte)ExprToken.Return:
tokenItem = new ReturnToken();
break;
case (byte)ExprToken.ReturnNothing:
if( Buffer.Version < PrimitveCastVersion )
{
tokenItem = new ByteToIntToken();
}
// Definitely existed since GoW(490)
else if( Buffer.Version > 420 && (DeserializedTokens.Count > 0 && !(DeserializedTokens[DeserializedTokens.Count - 1] is ReturnToken)) ) // Should only be done if the last token wasn't Return
{
tokenItem = new DynamicArrayInsertToken();
}
else
{
tokenItem = new ReturnNothingToken();
}
break;
case (byte)ExprToken.GotoLabel:
tokenItem = new GoToLabelToken();
break;
case (byte)ExprToken.Jump:
tokenItem = new JumpToken();
break;
case (byte)ExprToken.JumpIfNot:
tokenItem = new JumpIfNotToken();
break;
case (byte)ExprToken.Switch:
tokenItem = new SwitchToken();
break;
case (byte)ExprToken.Case:
tokenItem = new CaseToken();
break;
case (byte)ExprToken.DynArrayIterator:
if( Buffer.Version < PrimitveCastVersion )
{
tokenItem = new RotatorToStringToken();
}
else
{
tokenItem = new ArrayIteratorToken();
}
break;
case (byte)ExprToken.Iterator:
tokenItem = new IteratorToken();
break;
case (byte)ExprToken.IteratorNext:
tokenItem = new IteratorNextToken();
break;
case (byte)ExprToken.IteratorPop:
tokenItem = new IteratorPopToken();
break;
case (byte)ExprToken.FilterEditorOnly:
tokenItem = new FilterEditorOnlyToken();
break;
#endregion
#region Variables
case (byte)ExprToken.NativeParm:
tokenItem = new NativeParameterToken();
break;
// Referenced variables that are from this function e.g. Local and params
case (byte)ExprToken.InstanceVariable:
tokenItem = new InstanceVariableToken();
break;
case (byte)ExprToken.LocalVariable:
tokenItem = new LocalVariableToken();
break;
case (byte)ExprToken.StateVariable:
tokenItem = new StateVariableToken();
break;
// Referenced variables that are default
case (byte)ExprToken.UndefinedVariable:
#if BORDERLANDS2
if( _Container.Package.Build == UnrealPackage.GameBuild.BuildName.Borderlands2 )
{
tokenItem = new DynamicVariableToken();
break;
}
#endif
tokenItem = new UndefinedVariableToken();
break;
case (byte)ExprToken.DefaultVariable:
tokenItem = new DefaultVariableToken();
break;
// UE3+
case (byte)ExprToken.OutVariable:
tokenItem = new OutVariableToken();
break;
case (byte)ExprToken.BoolVariable:
tokenItem = new BoolVariableToken();
break;
// Redefined, can be FloatToInt!(UE1)
case (byte)ExprToken.DelegateProperty:
if( Buffer.Version < PrimitveCastVersion )
{
tokenItem = new FloatToIntToken();
}
else
{
tokenItem = new DelegatePropertyToken();
}
break;
case (byte)ExprToken.DefaultParmValue:
if( Buffer.Version < PrimitveCastVersion ) // StringToInt
{
tokenItem = new StringToIntToken();
}
else
{
tokenItem = new DefaultParameterToken();
}
break;
#endregion
#region Misc
// Redefined, can be BoolToFloat!(UE1)
case (byte)ExprToken.DebugInfo:
if( Buffer.Version < PrimitveCastVersion )
{
tokenItem = new BoolToFloatToken();
}
else
{
tokenItem = new DebugInfoToken();
}
break;
case (byte)ExprToken.Nothing:
tokenItem = new NothingToken();
break;
case (byte)ExprToken.EndFunctionParms:
tokenItem = new EndFunctionParmsToken();
break;
case (byte)ExprToken.IntZero:
tokenItem = new IntZeroToken();
break;
case (byte)ExprToken.IntOne:
tokenItem = new IntOneToken();
break;
case (byte)ExprToken.True:
tokenItem = new TrueToken();
break;
case (byte)ExprToken.False:
tokenItem = new FalseToken();
break;
case (byte)ExprToken.NoDelegate:
if( Buffer.Version < PrimitveCastVersion )
{
tokenItem = new IntToFloatToken();
}
else
{
tokenItem = new NoDelegateToken();
}
break;
// No value passed to an optional parameter.
case (byte)ExprToken.NoParm:
tokenItem = new NoParmToken();
break;
case (byte)ExprToken.NoObject:
tokenItem = new NoObjectToken();
break;
case (byte)ExprToken.Self:
tokenItem = new SelfToken();
break;
// End of state code.
case (byte)ExprToken.Stop:
tokenItem = new StopToken();
break;
case (byte)ExprToken.Assert:
tokenItem = new AssertToken();
break;
case (byte)ExprToken.LabelTable:
tokenItem = new LabelTableToken();
break;
case (byte)ExprToken.EndOfScript: //CastToken.BoolToString:
if( Buffer.Version < PrimitveCastVersion )
{
tokenItem = new BoolToStringToken();
}
else
{
tokenItem = new EndOfScriptToken();
}
break;
case (byte)ExprToken.Skip:
tokenItem = new SkipToken();
break;
case (byte)ExprToken.StructCmpEq:
tokenItem = new StructCmpEqToken();
break;
case (byte)ExprToken.StructCmpNE:
tokenItem = new StructCmpNeToken();
break;
case (byte)ExprToken.DelegateCmpEq:
tokenItem = new DelegateCmpEqToken();
break;
case (byte)ExprToken.DelegateFunctionCmpEq:
if( Buffer.Version < PrimitveCastVersion )
{
tokenItem = new IntToBoolToken();
}
else
{
tokenItem = new DelegateFunctionCmpEqToken();
}
break;
case (byte)ExprToken.DelegateCmpNE:
tokenItem = new DelegateCmpNEToken();
break;
case (byte)ExprToken.DelegateFunctionCmpNE:
if( Buffer.Version < PrimitveCastVersion )
{
tokenItem = new IntToBoolToken();
}
else
{
tokenItem = new DelegateFunctionCmpNEToken();
}
break;
case (byte)ExprToken.InstanceDelegate:
tokenItem = new InstanceDelegateToken();
break;
case (byte)ExprToken.EatString:
tokenItem = new EatStringToken();
break;
case (byte)ExprToken.New:
tokenItem = new NewToken();
break;
case (byte)ExprToken.FunctionEnd: // case (byte)ExprToken.DynArrayFind:
if( Buffer.Version < 300 )
{
tokenItem = new EndOfScriptToken();
}
else
{
tokenItem = new DynamicArrayFindToken();
}
break;
case (byte)ExprToken.VarInt:
case (byte)ExprToken.VarFloat:
case (byte)ExprToken.VarByte:
case (byte)ExprToken.VarBool:
//case (byte)ExprToken.VarObject: // See UndefinedVariable
tokenItem = new DynamicVariableToken();
break;
#endregion
#region Constants
case (byte)ExprToken.IntConst:
tokenItem = new IntConstToken();
break;
case (byte)ExprToken.ByteConst:
tokenItem = new ByteConstToken();
break;
case (byte)ExprToken.IntConstByte:
tokenItem = new IntConstByteToken();
break;
case (byte)ExprToken.FloatConst:
tokenItem = new FloatConstToken();
break;
// ClassConst?
case (byte)ExprToken.ObjectConst:
tokenItem = new ObjectConstToken();
break;
case (byte)ExprToken.NameConst:
tokenItem = new NameConstToken();
break;
case (byte)ExprToken.StringConst:
tokenItem = new StringConstToken();
break;
case (byte)ExprToken.UniStringConst:
tokenItem = new UniStringConstToken();
break;
case (byte)ExprToken.RotatorConst:
tokenItem = new RotatorConstToken();
break;
case (byte)ExprToken.VectorConst:
tokenItem = new VectorConstToken();
break;
#endregion
#region Functions
case (byte)ExprToken.FinalFunction:
tokenItem = new FinalFunctionToken();
break;
case (byte)ExprToken.VirtualFunction:
tokenItem = new VirtualFunctionToken();
break;
case (byte)ExprToken.GlobalFunction:
tokenItem = new GlobalFunctionToken();
break;
// Redefined, can be FloatToByte!(UE1)
case (byte)ExprToken.DelegateFunction:
if( Buffer.Version < PrimitveCastVersion )
{
tokenItem = new FloatToByteToken();
}
else
{
tokenItem = new DelegateFunctionToken();
}
break;
#endregion
#region Arrays
case (byte)ExprToken.ArrayElement:
tokenItem = new ArrayElementToken();
break;
case (byte)ExprToken.DynArrayElement:
tokenItem = new DynamicArrayElementToken();
break;
case (byte)ExprToken.DynArrayLength:
tokenItem = new DynamicArrayLengthToken();
break;
case (byte)ExprToken.DynArrayInsert:
if( Buffer.Version < PrimitveCastVersion )
{
tokenItem = new BoolToByteToken();
}
else
{
tokenItem = new DynamicArrayInsertToken();
}
break;
case (byte)ExprToken.DynArrayInsertItem:
if( Buffer.Version < PrimitveCastVersion )
{
tokenItem = new VectorToStringToken();
}
else
{
tokenItem = new DynamicArrayInsertItemToken();
}
break;
// Redefined, can be BoolToInt!(UE1)
case (byte)ExprToken.DynArrayRemove:
if( Buffer.Version < PrimitveCastVersion )
{
tokenItem = new BoolToIntToken();
}
else
{
tokenItem = new DynamicArrayRemoveToken();
}
break;
case (byte)ExprToken.DynArrayRemoveItem:
if( Buffer.Version < PrimitveCastVersion )
{
tokenItem = new NameToStringToken();
}
else
{
tokenItem = new DynamicArrayRemoveItemToken();
}
break;
case (byte)ExprToken.DynArrayAdd:
if( Buffer.Version < PrimitveCastVersion )
{
tokenItem = new FloatToStringToken();
}
else
{
tokenItem = new DynamicArrayAddToken();
}
break;
case (byte)ExprToken.DynArrayAddItem:
if( Buffer.Version < PrimitveCastVersion )
{
tokenItem = new ObjectToStringToken();
}
else
{
tokenItem = new DynamicArrayAddItemToken();
}
break;
case (byte)ExprToken.DynArraySort:
tokenItem = new DynamicArraySortToken();
break;
// See FunctionEnd and Eval
/*case (byte)ExprToken.DynArrayFind:
break;
case (byte)ExprToken.DynArrayFindStruct:
break;*/
#endregion
default:
{
#region Casts
if( Buffer.Version < PrimitveCastVersion )
{
// No other token was matched. Check if it matches any of the CastTokens
// We don't just use PrimitiveCast detection due compatible with UE1 games
tokenItem = DeserializeCastToken( tokenCode );
}
break;
#endregion
}
}
if( tokenItem == null )
{
tokenItem = new UnknownExprToken();
}
tokenItem.Decompiler = this;
tokenItem.RepresentToken = tokenCode;
tokenItem.Position = tokenPosition;// + (uint)Owner._ScriptOffset;
tokenItem.StoragePosition = (uint)Buffer.Position - (uint)_Container.ScriptOffset - 1;
// IMPORTANT:Add before deserialize, due the possibility that the tokenitem might deserialize other tokens as well.
DeserializedTokens.Add( tokenItem );
tokenItem.Deserialize( Buffer );
// Includes all sizes of followed tokens as well! e.g. i = i + 1; is summed here but not i = i +1; (not>>)i ++;
tokenItem.Size = (ushort)(CodePosition - tokenPosition);
tokenItem.StorageSize = (ushort)((uint)Buffer.Position - (uint)_Container.ScriptOffset - tokenItem.StoragePosition);
tokenItem.PostDeserialized();
return tokenItem;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1822:MarkMembersAsStatic" )]
private Token DeserializeCastToken( byte castToken )
{
Token tokenitem = null;
switch( (Tokens.CastToken)castToken )
{
case Tokens.CastToken.StringToRotator:
tokenitem = new StringToRotatorToken();
break;
case Tokens.CastToken.VectorToRotator:
tokenitem = new VectorToRotatorToken();
break;
case Tokens.CastToken.StringToVector:
tokenitem = new StringToVectorToken();
break;
case Tokens.CastToken.RotatorToVector:
tokenitem = new RotatorToVectorToken();
break;
case Tokens.CastToken.IntToFloat:
tokenitem = new IntToFloatToken();
break;
case Tokens.CastToken.StringToFloat:
tokenitem = new StringToFloatToken();
break;
case Tokens.CastToken.BoolToFloat:
tokenitem = new BoolToFloatToken();
break;
case Tokens.CastToken.StringToInt:
tokenitem = new StringToIntToken();
break;
case Tokens.CastToken.FloatToInt:
tokenitem = new FloatToIntToken();
break;
case Tokens.CastToken.BoolToInt:
tokenitem = new BoolToIntToken();
break;
case Tokens.CastToken.RotatorToBool:
tokenitem = new RotatorToBoolToken();
break;
case Tokens.CastToken.VectorToBool:
tokenitem = new VectorToBoolToken();
break;
case Tokens.CastToken.StringToBool:
tokenitem = new StringToBoolToken();
break;
case Tokens.CastToken.ByteToBool:
tokenitem = new ByteToBoolToken();
break;
case Tokens.CastToken.FloatToBool:
tokenitem = new FloatToBoolToken();
break;
case Tokens.CastToken.NameToBool:
tokenitem = new NameToBoolToken();
break;
case Tokens.CastToken.ObjectToBool:
tokenitem = new ObjectToBoolToken();
break;
case Tokens.CastToken.IntToBool:
tokenitem = new IntToBoolToken();
break;
case Tokens.CastToken.StringToByte:
tokenitem = new StringToByteToken();
break;
case Tokens.CastToken.FloatToByte:
tokenitem = new FloatToByteToken();
break;
case Tokens.CastToken.BoolToByte:
tokenitem = new BoolToByteToken();
break;
case Tokens.CastToken.ByteToString:
tokenitem = new ByteToStringToken();
break;
case Tokens.CastToken.IntToString:
tokenitem = new IntToStringToken();
break;
case Tokens.CastToken.BoolToString:
tokenitem = new BoolToStringToken();
break;
case Tokens.CastToken.FloatToString:
tokenitem = new FloatToStringToken();
break;
case Tokens.CastToken.NameToString:
tokenitem = new NameToStringToken();
break;
case Tokens.CastToken.VectorToString:
tokenitem = new VectorToStringToken();
break;
case Tokens.CastToken.RotatorToString:
tokenitem = new RotatorToStringToken();
break;
case Tokens.CastToken.StringToName:
tokenitem = new StringToNameToken();
break;
case Tokens.CastToken.ByteToInt:
tokenitem = new ByteToIntToken();
break;
case Tokens.CastToken.IntToByte:
tokenitem = new IntToByteToken();
break;
case Tokens.CastToken.ByteToFloat:
tokenitem = new ByteToFloatToken();
break;
case Tokens.CastToken.ObjectToString:
tokenitem = new ObjectToStringToken();
break;
case Tokens.CastToken.InterfaceToString:
tokenitem = new InterfaceToStringToken();
break;
case Tokens.CastToken.InterfaceToBool:
tokenitem = new InterfaceToBoolToken();
break;
case Tokens.CastToken.InterfaceToObject:
tokenitem = new InterfaceToObjectToken();
break;
case Tokens.CastToken.ObjectToInterface:
tokenitem = new ObjectToInterfaceToken();
break;
case Tokens.CastToken.DelegateToString:
tokenitem = new DelegateToStringToken();
break;
}
// Unsure what this is, found in: ClanManager1h_6T.CMBanReplicationInfo.Timer:
// xyz = UnknownCastToken(0x1b);
// UnknownCastToken(0x1b)
// UnknownCastToken(0x1b)
if( castToken == 0x1b )
tokenitem = new FloatToIntToken();
return tokenitem ?? new UnknownCastToken();
}
#endregion
#if DECOMPILE
#region Decompile
public class NestManager
{
public UByteCodeDecompiler Decompiler;
public class Nest : IUnrealDecompilable
{
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1008:EnumsShouldHaveZeroValue" )]
public enum NestType : byte
{
Scope = 0,
If = 1,
Else = 2,
ForEach = 4,
Switch = 5, Case = 6, Default = 7,
Loop = 8
}
/// <summary>
/// Position of this Nest (CodePosition)
/// </summary>
public uint Position;
public NestType Type;
public Token Creator;
public virtual string Decompile()
{
return String.Empty;
}
public bool IsPastOffset( uint position )
{
return position >= Position;
}
public override string ToString()
{
return "Type:" + Type + " Position:" + Position;
}
}
public class NestBegin : Nest
{
public override string Decompile()
{
#if DEBUG_NESTS
return "\r\n" + UDecompilingState.Tabs + "//<" + Type + ">";
#else
return Type != NestType.Case && Type != NestType.Default
? UnrealConfig.PrintBeginBracket()
: String.Empty;
#endif
}
}
public class NestEnd : Nest
{
public override string Decompile()
{
#if DEBUG_NESTS
return "\r\n" + UDecompilingState.Tabs + "//</" + Type + ">";
#else
return Type != NestType.Case && Type != NestType.Default
? UnrealConfig.PrintEndBracket()
: String.Empty;
#endif
}
}
public readonly List<Nest> Nests = new List<Nest>();
public void AddNest( Nest.NestType type, uint position, uint endPosition, Token creator = null )
{
creator = creator ?? Decompiler.CurrentToken;
Nests.Add( new NestBegin{Position = position, Type = type, Creator = creator} );
Nests.Add( new NestEnd{Position = endPosition, Type = type, Creator = creator} );
}
public NestBegin AddNestBegin( Nest.NestType type, uint position, Token creator = null )
{
var n = new NestBegin {Position = position, Type = type};
Nests.Add( n );
n.Creator = creator ?? Decompiler.CurrentToken;
return n;
}
public NestEnd AddNestEnd( Nest.NestType type, uint position, Token creator = null )
{
var n = new NestEnd {Position = position, Type = type};
Nests.Add( n );
n.Creator = creator ?? Decompiler.CurrentToken;
return n;
}
}
private NestManager _Nester;
// Checks if we're currently within a nest of type nestType in any stack!
private NestManager.Nest IsWithinNest( NestManager.Nest.NestType nestType )
{
for( int i = _NestChain.Count - 1; i >= 0; -- i )
{
if( _NestChain[i].Type == nestType )
{
return _NestChain[i];
}
}
return null;
}
private NestManager.Nest GetMostRecentEndNest( NestManager.Nest.NestType nestType )
{
for( int i = _Nester.Nests.Count - 1; i >= 0; -- i )
{
if( _Nester.Nests[i] is NestManager.NestEnd && _Nester.Nests[i].Type == nestType )
{
return _Nester.Nests[i];
}
}
return null;
}
// Checks if the current nest is of type nestType in the current stack!
// Only BeginNests that have been decompiled will be tested for!
private NestManager.Nest IsInNest( NestManager.Nest.NestType nestType )
{
int i = _NestChain.Count - 1;
if( i == -1 )
return null;
if( _NestChain[i].Type == nestType )
{
return _NestChain[i];
}
return null;
}
private NestManager.Nest CurNestBegin()
{
for( int i = _Nester.Nests.Count - 1; i >= 0; -- i )
{
if( _Nester.Nests[i] is NestManager.NestBegin )
{
return _Nester.Nests[i];
}
}
return null;
}
private NestManager.Nest CurNestEnd()
{
for( int i = _Nester.Nests.Count - 1; i >= 0; -- i )
{
if( _Nester.Nests[i] is NestManager.NestEnd )
{
return _Nester.Nests[i];
}
}
return null;
}
public void InitDecompile()
{
_NestChain.Clear();
_Nester = new NestManager{Decompiler = this};
CurrentTokenIndex = -1;
CodePosition = 0;
FieldToken.LastField = null;
// TODO: Corrigate detection and version.
DefaultParameterToken._NextParamIndex = 0;
if( Package.Version > 300 )
{
var func = _Container as UFunction;
if( func != null && func.Params != null )
{
DefaultParameterToken._NextParamIndex = func.Params.FindIndex(
p => p.HasPropertyFlag( Flags.PropertyFlagsLO.OptionalParm )
);
}
}
// Reset these, in case of a loop in the Decompile function that did not finish due exception errors!
_IsWithinClassContext = false;
_CanAddSemicolon = false;
_MustCommentStatement = false;
_PostIncrementTabs = 0;
_PostDecrementTabs = 0;
_PreIncrementTabs = 0;
_PreDecrementTabs = 0;
PreComment = String.Empty;
PostComment = String.Empty;
_TempLabels = new List<ULabelEntry>();
if( _Labels != null )
{
for( int i = 0; i < _Labels.Count; ++ i )
{
// No duplicates, caused by having multiple goto's with the same destination
if( !_TempLabels.Exists( p => p.Position == _Labels[i].Position ) )
{
_TempLabels.Add( _Labels[i] );
}
}
}
}
public void JumpTo( ushort codeOffset )
{
var index = DeserializedTokens.FindIndex( t => t.Position == codeOffset );
if( index == -1 )
return;
CurrentTokenIndex = index;
}
public Token TokenAt( ushort codeOffset )
{
return DeserializedTokens.Find( t => t.Position == codeOffset );
}
/// <summary>
/// Whether we are currently decompiling within a ClassContext token.
///
/// HACK: For static calls -> class'ClassA'.static.FuncA();
/// </summary>
private bool _IsWithinClassContext;
private bool _CanAddSemicolon;
private bool _MustCommentStatement;
private byte _PostIncrementTabs;
private byte _PostDecrementTabs;
private byte _PreIncrementTabs;
private byte _PreDecrementTabs;
public string PreComment;
public string PostComment;
public string Decompile()
{
// Make sure that everything is deserialized!
if( !_WasDeserialized )
{
Deserialize();
}
var output = new StringBuilder();
// Original indention, so that we can restore it later, necessary if decompilation fails to reduce nesting indention.
string initTabs = UDecompilingState.Tabs;
#if DEBUG_TOKENPOSITIONS
UDecompilingState.AddTabs( 3 );
#endif
try
{
//Initialize==========
InitDecompile();
bool spewOutput = false;
int tokenBeginIndex = 0;
Token lastStatementToken = null;
while( CurrentTokenIndex + 1 < DeserializedTokens.Count )
{
try
{
//Decompile chain==========
{
string tokenOutput;
var newToken = NextToken;
output.Append( DecompileLabels() );
try
{
// FIX: Formatting issue on debug-compiled packages
if( newToken is DebugInfoToken )
{
string nestsOutput = DecompileNests();
if( nestsOutput.Length != 0 )
{
output.Append( nestsOutput );
spewOutput = true;
}
continue;
}
}
catch( Exception e )
{
output.Append( "// (" + e.GetType().Name + ")" );
}
try
{
tokenBeginIndex = CurrentTokenIndex;
tokenOutput = newToken.Decompile();
if( CurrentTokenIndex + 1 < DeserializedTokens.Count && PeekToken is EndOfScriptToken )
{
var firstToken = newToken is DebugInfoToken ? lastStatementToken : newToken;
if( firstToken is ReturnToken )
{
var lastToken = newToken is DebugInfoToken ? PreviousToken : CurrentToken;
if( lastToken is NothingToken || lastToken is ReturnNothingToken )
{
_MustCommentStatement = true;
}
}
}
}
catch( Exception e )
{
tokenOutput = newToken.GetType().Name + "-" + CurrentToken.GetType().Name
+ "(" + e + ")";
}
// HACK: for multiple cases for one block of code, etc!
if( _PreDecrementTabs > 0 )
{
UDecompilingState.RemoveTabs( _PreDecrementTabs );
_PreDecrementTabs = 0;
}
if( _PreIncrementTabs > 0 )
{
UDecompilingState.AddTabs( _PreIncrementTabs );
_PreIncrementTabs = 0;
}
if( _MustCommentStatement && UnrealConfig.SuppressComments )
continue;
if( !UnrealConfig.SuppressComments )
{
if( PreComment.Length != 0 )
{
tokenOutput = PreComment + "\r\n" + UDecompilingState.Tabs + tokenOutput;
PreComment = String.Empty;
}
if( PostComment.Length != 0 )
{
tokenOutput += PostComment;
PostComment = String.Empty;
}
}
//Preprocess output==========
{
#if DEBUG_HIDDENTOKENS
if( tokenOutput.Length == 0 )
{
tokenOutput = "<" + newToken.GetType().Name + "/>";
_MustCommentStatement = true;
}
#endif
// Previous did spew and this one spews? then a new line is required!
if( tokenOutput.Length != 0 )
{
// Spew before?
if( spewOutput )
{
output.Append( "\r\n" );
}
else spewOutput = true;
}
if( spewOutput )
{
if( _MustCommentStatement )
{
tokenOutput = "//" + tokenOutput;
_MustCommentStatement = false;
}
#if DEBUG_TOKENPOSITIONS
output.Append( String.Format( initTabs + "({0:X3}{1:X3})",
newToken.Position,
CurrentToken.Position + CurrentToken.Size
) );
var orgTabs = UDecompilingState.Tabs;
var spaces = Math.Max( 3*UnrealConfig.Indention.Length, 8 );
UDecompilingState.RemoveSpaces( spaces );
#endif
output.Append( UDecompilingState.Tabs + tokenOutput );
#if DEBUG_TOKENPOSITIONS
UDecompilingState.Tabs = orgTabs;
#endif
// One of the decompiled tokens wanted to be ended.
if( _CanAddSemicolon )
{
output.Append( ";" );
_CanAddSemicolon = false;
}
}
}
lastStatementToken = newToken;
}
//Postprocess output==========
if( _PostDecrementTabs > 0 )
{
UDecompilingState.RemoveTabs( _PostDecrementTabs );
_PostDecrementTabs = 0;
}
if( _PostIncrementTabs > 0 )
{
UDecompilingState.AddTabs( _PostIncrementTabs );
_PostIncrementTabs = 0;
}
try
{
string nestsOutput = DecompileNests();
if( nestsOutput.Length != 0 )
{
output.Append( nestsOutput );
spewOutput = true;
}
output.Append( DecompileLabels() );
}
catch( Exception e )
{
output.Append( "\r\n" + UDecompilingState.Tabs + "// Failed to format nests!:"
+ e + "\r\n"
+ UDecompilingState.Tabs + "// " + _Nester.Nests.Count + " & "
+ _Nester.Nests[_Nester.Nests.Count - 1] );
spewOutput = true;
}
}
catch( Exception e )
{
output.Append( "\r\n" + UDecompilingState.Tabs
+ "// Failed to decompile this line:\r\n" );
UDecompilingState.AddTab();
output.Append( UDecompilingState.Tabs + "/* "
+ FormatTokens( tokenBeginIndex, CurrentTokenIndex ) + " */\r\n" );
UDecompilingState.RemoveTab();
output.Append( UDecompilingState.Tabs + "// " + FormatTabs( e.Message ) );
spewOutput = true;
}
}
try
{
// Decompile remaining nests
output.Append( DecompileNests( true ) );
}
catch( Exception e )
{
output.Append( "\r\n" + UDecompilingState.Tabs
+ "// Failed to format remaining nests!:" + e + "\r\n"
+ UDecompilingState.Tabs + "// " + _Nester.Nests.Count + " & "
+ _Nester.Nests[_Nester.Nests.Count - 1] );
}
}
catch( Exception e )
{
output.AppendFormat(
"{0} // Failed to decompile this {1}'s code." +
"\r\n {2} at position {3} " +
"\r\n Message: {4} " +
"\r\n\r\n StackTrace: {5}",
UDecompilingState.Tabs,
_Container.Class.Name,
UDecompilingState.Tabs,
CodePosition,
FormatTabs( e.Message ),
FormatTabs( e.StackTrace )
);
}
finally
{
UDecompilingState.Tabs = initTabs;
}
return output.ToString();
}
private readonly List<NestManager.Nest> _NestChain = new List<NestManager.Nest>();
private static string FormatTabs( string nonTabbedText )
{
return nonTabbedText.Replace( "\n", "\n" + UDecompilingState.Tabs );
}
private string FormatTokens( int beginIndex, int endIndex )
{
string output = String.Empty;
for( int i = beginIndex; i < endIndex; ++ i )
{
output += DeserializedTokens[i].GetType().Name
+ (i % 4 == 0 ? "\r\n" + UDecompilingState.Tabs : " ");
}
return output;
}
private string DecompileLabels()
{
string output = String.Empty;
for( int i = 0; i < _TempLabels.Count; ++ i )
{
var label = _TempLabels[i];
if( PeekToken.Position < label.Position )
continue;
var isStateLabel = !label.Name.StartsWith( "J0x", StringComparison.Ordinal );
output += isStateLabel
? String.Format( "\r\n{0}:\r\n", label.Name )
: String.Format( "\r\n{0}:", UDecompilingState.Tabs + label.Name );
_TempLabels.RemoveAt( i );
-- i;
}
return output;
}
private string DecompileNests( bool outputAllRemainingNests = false )
{
string output = String.Empty;
// Give { priority hence separated loops
for( int i = 0; i < _Nester.Nests.Count; ++ i )
{
if( !(_Nester.Nests[i] is NestManager.NestBegin) )
continue;
if( _Nester.Nests[i].IsPastOffset( CurrentToken.Position ) || outputAllRemainingNests )
{
output += _Nester.Nests[i].Decompile();
UDecompilingState.AddTab();
_NestChain.Add( _Nester.Nests[i] );
_Nester.Nests.RemoveAt( i -- );
}
}
for( int i = 0; i < _Nester.Nests.Count; ++ i )
{
if( !(_Nester.Nests[i] is NestManager.NestEnd) )
continue;
if( _Nester.Nests[i].IsPastOffset( CurrentToken.Position + CurrentToken.Size )
|| outputAllRemainingNests )
{
UDecompilingState.RemoveTab();
output += _Nester.Nests[i].Decompile();
// TODO: This should not happen!
if( _NestChain.Count > 0 )
{
_NestChain.RemoveAt( _NestChain.Count - 1 );
}
_Nester.Nests.RemoveAt( i -- );
}
}
return output;
}
#endregion
#region Disassemble
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1822:MarkMembersAsStatic" )]
public string Disassemble()
{
return String.Empty;
}
#endregion
#endif
}
}
} | 39.525215 | 214 | 0.39175 | [
"MIT"
] | Bakkes/Unreal-Library | src/ByteCodeDecompiler.cs | 64,270 | C# |
using System;
using System.IO;
using System.Linq;
using Abp.Reflection.Extensions;
namespace MyProject.Web
{
/// <summary>
/// This class is used to find root path of the web project in;
/// unit tests (to find views) and entity framework core command line commands (to find conn string).
/// </summary>
public static class WebContentDirectoryFinder
{
public static string CalculateContentRootFolder()
{
var coreAssemblyDirectoryPath = Path.GetDirectoryName(typeof(MyProjectCoreModule).GetAssembly().Location);
if (coreAssemblyDirectoryPath == null)
{
throw new Exception("Could not find location of MyProject.Core assembly!");
}
var directoryInfo = new DirectoryInfo(coreAssemblyDirectoryPath);
while (!DirectoryContains(directoryInfo.FullName, "MyProject.sln"))
{
if (directoryInfo.Parent == null)
{
throw new Exception("Could not find content root folder!");
}
directoryInfo = directoryInfo.Parent;
}
var webMvcFolder = Path.Combine(directoryInfo.FullName, "src", "MyProject.Web.Mvc");
if (Directory.Exists(webMvcFolder))
{
return webMvcFolder;
}
var webHostFolder = Path.Combine(directoryInfo.FullName, "src", "MyProject.Web.Host");
if (Directory.Exists(webHostFolder))
{
return webHostFolder;
}
throw new Exception("Could not find root folder of the web project!");
}
private static bool DirectoryContains(string directory, string fileName)
{
return Directory.GetFiles(directory).Any(filePath => string.Equals(Path.GetFileName(filePath), fileName));
}
}
}
| 35.055556 | 118 | 0.602219 | [
"MIT"
] | CadeXu/ABP | abpMySql/aspnet-core/src/MyProject.Core/Web/WebContentFolderHelper.cs | 1,895 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace PomodoroTimer.Enums
{
public enum TimerState
{
Running,
Paused,
Stoped,
Complated,
}
}
| 14 | 33 | 0.619048 | [
"MIT"
] | firakti/PomodoroTimer | PomodoroTimer/PomodoroTimer/Enums/TimerState.cs | 212 | C# |
//-----------------------------------------------------------------------------
// Filename: SIPRequestAuthenticationResult.cs
//
// Description: Holds the results of a SIP request authorisation attempt.
//
// Author(s):
// Aaron Clauson (aaron@sipsorcery.com)
//
// History:
// 08 Mar 2009 Aaron Clauson Created, Hobart, Australia.
//
// License:
// BSD 3-Clause "New" or "Revised" License, see included LICENSE.md file.
//-----------------------------------------------------------------------------
namespace SIPSorcery.SIP.App
{
public class SIPRequestAuthenticationResult
{
public bool Authenticated;
public bool WasAuthenticatedByIP;
public SIPResponseStatusCodesEnum ErrorResponse;
public SIPAuthenticationHeader AuthenticationRequiredHeader;
public SIPRequestAuthenticationResult(bool isAuthenticated, bool wasAuthenticatedByIP)
{
Authenticated = isAuthenticated;
WasAuthenticatedByIP = wasAuthenticatedByIP;
}
public SIPRequestAuthenticationResult(SIPResponseStatusCodesEnum errorResponse, SIPAuthenticationHeader authenticationRequiredHeader)
{
Authenticated = false;
ErrorResponse = errorResponse;
AuthenticationRequiredHeader = authenticationRequiredHeader;
}
}
}
| 35.205128 | 142 | 0.611799 | [
"Apache-2.0"
] | Ali-Russell/sipsorcery | src/app/SIPRequestAuthoriser/SIPRequestAuthenticationResult.cs | 1,375 | 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("SQL Server To SQLite Converter")]
[assembly: AssemblyDescription("Convert SQL Server databases to SQLite databases")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SQLite Converter")]
[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("5c16baa6-f948-40b6-a215-d454fd8c37d8")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
[assembly: AssemblyVersion("1.20.1507.0")]
[assembly: AssemblyFileVersion("1.20.1507.0")]
| 39.212121 | 85 | 0.739567 | [
"MIT"
] | jschultz/sqlconverter | SolutionInfo.cs | 1,294 | 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 auditmanager-2017-07-25.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.AuditManager.Model
{
/// <summary>
/// This is the response object from the DeleteAssessmentFramework operation.
/// </summary>
public partial class DeleteAssessmentFrameworkResponse : AmazonWebServiceResponse
{
}
} | 30.078947 | 110 | 0.740157 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/AuditManager/Generated/Model/DeleteAssessmentFrameworkResponse.cs | 1,143 | C# |
using ApeVolo.Common.Extention;
namespace ApeVolo.Common.Model;
/// <summary>
/// 数据库表信息
/// </summary>
public class TableInfo
{
/// <summary>
/// 字段Id
/// </summary>
public int ColumnId { get; set; }
/// <summary>
/// 字段名
/// </summary>
public string Name { get; set; }
/// <summary>
/// 字段类型
/// </summary>
public string Type { get; set; }
/// <summary>
/// 是否为主键
/// </summary>
public bool IsKey { get; set; }
/// <summary>
/// 是否为空
/// </summary>
public bool IsNullable { get; set; }
/// <summary>
/// 字段描述说明
/// </summary>
public string Description
{
get { return _description.IsNullOrEmpty() ? Name : _description; }
set { _description = value; }
}
private string _description { get; set; }
} | 18.466667 | 74 | 0.531889 | [
"Apache-2.0"
] | xianhc/apevolo-api | ApeVolo.Common/Model/TableInfo.cs | 893 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.Network.V20170901.Outputs
{
[OutputType]
public sealed class ApplicationGatewayRedirectConfigurationResponse
{
/// <summary>
/// A unique read-only string that changes whenever the resource is updated.
/// </summary>
public readonly string? Etag;
/// <summary>
/// Resource ID.
/// </summary>
public readonly string? Id;
/// <summary>
/// Include path in the redirected url.
/// </summary>
public readonly bool? IncludePath;
/// <summary>
/// Include query string in the redirected url.
/// </summary>
public readonly bool? IncludeQueryString;
/// <summary>
/// Name of the resource that is unique within a resource group. This name can be used to access the resource.
/// </summary>
public readonly string? Name;
/// <summary>
/// Path rules specifying redirect configuration.
/// </summary>
public readonly ImmutableArray<Outputs.SubResourceResponse> PathRules;
/// <summary>
/// Supported http redirection types - Permanent, Temporary, Found, SeeOther.
/// </summary>
public readonly string? RedirectType;
/// <summary>
/// Request routing specifying redirect configuration.
/// </summary>
public readonly ImmutableArray<Outputs.SubResourceResponse> RequestRoutingRules;
/// <summary>
/// Reference to a listener to redirect the request to.
/// </summary>
public readonly Outputs.SubResourceResponse? TargetListener;
/// <summary>
/// Url to redirect the request to.
/// </summary>
public readonly string? TargetUrl;
/// <summary>
/// Type of the resource.
/// </summary>
public readonly string? Type;
/// <summary>
/// Url path maps specifying default redirect configuration.
/// </summary>
public readonly ImmutableArray<Outputs.SubResourceResponse> UrlPathMaps;
[OutputConstructor]
private ApplicationGatewayRedirectConfigurationResponse(
string? etag,
string? id,
bool? includePath,
bool? includeQueryString,
string? name,
ImmutableArray<Outputs.SubResourceResponse> pathRules,
string? redirectType,
ImmutableArray<Outputs.SubResourceResponse> requestRoutingRules,
Outputs.SubResourceResponse? targetListener,
string? targetUrl,
string? type,
ImmutableArray<Outputs.SubResourceResponse> urlPathMaps)
{
Etag = etag;
Id = id;
IncludePath = includePath;
IncludeQueryString = includeQueryString;
Name = name;
PathRules = pathRules;
RedirectType = redirectType;
RequestRoutingRules = requestRoutingRules;
TargetListener = targetListener;
TargetUrl = targetUrl;
Type = type;
UrlPathMaps = urlPathMaps;
}
}
}
| 32.735849 | 118 | 0.605476 | [
"Apache-2.0"
] | pulumi-bot/pulumi-azure-native | sdk/dotnet/Network/V20170901/Outputs/ApplicationGatewayRedirectConfigurationResponse.cs | 3,470 | C# |
using NUnit.Framework;
namespace TwitchWrapper.Tests
{
[TestFixture]
public class TwitchClientTests
{
[Test]
public void TheTwitchClientMustDoSomething()
{
Assert.True(true);
}
}
}
| 16.2 | 52 | 0.588477 | [
"MIT"
] | andy-c-jones/TwitchAPIWrapper | TwitchWrapper.Tests/TwitchClientTests.cs | 245 | C# |
//-----------------------------------------------------------------------
// <copyright file="DeadlineFailureDetectorSpec.cs" company="Akka.NET Project">
// Copyright (C) 2009-2019 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2019 .NET Foundation <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using Akka.TestKit;
using FluentAssertions;
using Xunit;
namespace Akka.Remote.Tests
{
public class DeadlineFailureDetectorSpec : AkkaSpec
{
[Fact]
public void DeadlineFailureDetector_must_mark_node_as_monitored_after_a_series_of_successful_heartbeats()
{
var timeInterval = new List<long> {0, 1000, 100, 100};
var fd = CreateFailureDetector(4.Seconds(), FailureDetectorSpecHelpers.FakeTimeGenerator(timeInterval));
fd.IsMonitoring.Should().BeFalse();
fd.HeartBeat();
fd.HeartBeat();
fd.HeartBeat();
fd.IsMonitoring.Should().BeTrue();
fd.IsAvailable.Should().BeTrue();
}
[Fact]
public void DeadlineFailureDetector_must_mark_node_as_dead_if_heartbeats_are_missed()
{
var timeInterval = new List<long> { 0, 1000, 100, 100, 7000 };
var fd = CreateFailureDetector(4.Seconds(), FailureDetectorSpecHelpers.FakeTimeGenerator(timeInterval));
fd.HeartBeat(); //0
fd.HeartBeat(); //1000
fd.HeartBeat(); //1100
fd.IsAvailable.Should().BeTrue(); //1200
fd.IsAvailable.Should().BeFalse(); //8200
}
[Fact]
public void DeadlineFailureDetector_must_mark_node_as_available_if_it_starts_heartbeat_again_after_being_marked_dead()
{
var regularIntervals = new List<long> {0L}.Concat(Enumerable.Repeat(1000L, 999));
var timeIntervals =
regularIntervals.Concat(new List<long> {(5*60*1000), 100, 900, 100, 7000, 100, 900, 100, 900}).ToList();
var fd = CreateFailureDetector(4.Seconds(), FailureDetectorSpecHelpers.FakeTimeGenerator(timeIntervals));
for (var i = 0; i < 1000; i++) fd.HeartBeat();
fd.IsAvailable.Should().BeFalse(); //after the long pause
fd.HeartBeat();
fd.IsAvailable.Should().BeTrue();
fd.HeartBeat();
fd.IsAvailable.Should().BeFalse(); //after the 7 second pause
fd.HeartBeat();
fd.IsAvailable.Should().BeTrue();
fd.HeartBeat();
fd.IsAvailable.Should().BeTrue();
}
[Fact]
public void DeadlineFailureDetector_must_accept_some_configured_missing_heartbeats()
{
var timeInterval = new List<long> { 0, 1000, 1000, 1000, 4000, 1000, 1000 };
var fd = CreateFailureDetector(4.Seconds(), FailureDetectorSpecHelpers.FakeTimeGenerator(timeInterval));
fd.HeartBeat();
fd.HeartBeat();
fd.HeartBeat();
fd.HeartBeat();
fd.IsAvailable.Should().BeTrue();
fd.HeartBeat();
fd.IsAvailable.Should().BeTrue();
}
[Fact]
public void DeadlineFailureDetector_must_fail_after_configured_acceptable_missing_heartbeats()
{
var timeInterval = new List<long> { 0, 1000, 1000, 1000, 1000, 1000, 500, 500, 5000 };
var fd = CreateFailureDetector(4.Seconds(), FailureDetectorSpecHelpers.FakeTimeGenerator(timeInterval));
fd.HeartBeat();
fd.HeartBeat();
fd.HeartBeat();
fd.HeartBeat();
fd.HeartBeat();
fd.HeartBeat();
fd.IsAvailable.Should().BeTrue();
fd.HeartBeat();
fd.IsAvailable.Should().BeFalse();
}
[Fact]
public void DeadlineFailureDetector_must_work_with_MonotonicClock()
{
var fd = CreateFailureDetector(4.Seconds());
fd.IsAvailable.Should().BeTrue();
fd.HeartBeat();
fd.IsAvailable.Should().BeTrue();
}
private DeadlineFailureDetector CreateFailureDetector(TimeSpan acceptableLostDuration, Clock clock = null)
{
return new DeadlineFailureDetector(acceptableLostDuration, 1.Seconds(), clock);
}
}
}
| 38.284483 | 126 | 0.590858 | [
"Apache-2.0"
] | IgorFedchenko/akka.net | src/core/Akka.Remote.Tests/DeadlineFailureDetectorSpec.cs | 4,443 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.ContainerRegistry.V20190601Preview.Inputs
{
/// <summary>
/// The properties that determine the run agent configuration.
/// </summary>
public sealed class AgentPropertiesArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The CPU configuration in terms of number of cores required for the run.
/// </summary>
[Input("cpu")]
public Input<int>? Cpu { get; set; }
public AgentPropertiesArgs()
{
}
}
}
| 28 | 83 | 0.660099 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/ContainerRegistry/V20190601Preview/Inputs/AgentPropertiesArgs.cs | 812 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace System.Collections.Tests
{
public static partial class BitArray_OperatorsTests
{
private const int BitsPerByte = 8;
private const int BitsPerInt32 = 32;
public static IEnumerable<object[]> Not_Operator_Data()
{
foreach (int size in new[] { 0, 1, BitsPerByte, BitsPerByte * 2, BitsPerInt32, BitsPerInt32 * 2, short.MaxValue })
{
yield return new object[] { Enumerable.Repeat(true, size).ToArray() };
yield return new object[] { Enumerable.Repeat(false, size).ToArray() };
yield return new object[] { Enumerable.Range(0, size).Select(i => i % 2 == 1).ToArray() };
}
}
[Theory]
[MemberData(nameof(Not_Operator_Data))]
public static void Not(bool[] data)
{
BitArray bitArray = new BitArray(data);
BitArray bitArrayNot = bitArray.Not();
Assert.Equal(bitArray.Length, bitArrayNot.Length);
Assert.Same(bitArray, bitArrayNot);
for (int i = 0; i < bitArray.Length; i++)
{
Assert.Equal(!data[i], bitArrayNot[i]);
}
}
public static IEnumerable<object[]> And_Operator_Data()
{
yield return new object[] { new bool[0], new bool[0], new bool[0] };
foreach (int size in new[] { 1, BitsPerByte, BitsPerByte * 2, BitsPerInt32, BitsPerInt32 * 2, short.MaxValue })
{
bool[] allTrue = Enumerable.Repeat(true, size).ToArray();
bool[] allFalse = Enumerable.Repeat(false, size).ToArray();
bool[] alternating = Enumerable.Range(0, size).Select(i => i % 2 == 1).ToArray();
yield return new object[] { allTrue, allTrue, allTrue };
yield return new object[] { allTrue, allFalse, allFalse };
yield return new object[] { allFalse, allTrue, allFalse };
yield return new object[] { allFalse, allFalse, allFalse };
yield return new object[] { allTrue, alternating, alternating };
yield return new object[] { alternating, allTrue, alternating };
yield return new object[] { allFalse, alternating, allFalse };
yield return new object[] { alternating, allFalse, allFalse };
}
}
[Theory]
[MemberData(nameof(And_Operator_Data))]
public static void And_Operator(bool[] l, bool[] r, bool[] expected)
{
BitArray left = new BitArray(l);
BitArray right = new BitArray(r);
BitArray actual = left.And(right);
Assert.Same(left, actual);
Assert.Equal(actual.Length, expected.Length);
for (int i = 0; i < expected.Length; i++)
{
Assert.Equal(expected[i], actual[i]);
}
}
public static IEnumerable<object[]> Or_Operator_Data()
{
yield return new object[] { new bool[0], new bool[0], new bool[0] };
foreach (int size in new[] { 1, BitsPerByte, BitsPerByte * 2, BitsPerInt32, BitsPerInt32 * 2, short.MaxValue })
{
bool[] allTrue = Enumerable.Repeat(true, size).ToArray();
bool[] allFalse = Enumerable.Repeat(false, size).ToArray();
bool[] alternating = Enumerable.Range(0, size).Select(i => i % 2 == 1).ToArray();
yield return new object[] { allTrue, allTrue, allTrue };
yield return new object[] { allTrue, allFalse, allTrue };
yield return new object[] { allFalse, allTrue, allTrue };
yield return new object[] { allFalse, allFalse, allFalse };
yield return new object[] { allTrue, alternating, allTrue };
yield return new object[] { alternating, allTrue, allTrue };
yield return new object[] { allFalse, alternating, alternating };
yield return new object[] { alternating, allFalse, alternating };
}
}
[Theory]
[MemberData(nameof(Or_Operator_Data))]
public static void Or_Operator(bool[] l, bool[] r, bool[] expected)
{
BitArray left = new BitArray(l);
BitArray right = new BitArray(r);
BitArray actual = left.Or(right);
Assert.Same(left, actual);
Assert.Equal(actual.Length, expected.Length);
for (int i = 0; i < expected.Length; i++)
{
Assert.Equal(expected[i], actual[i]);
}
}
public static IEnumerable<object[]> Xor_Operator_Data()
{
yield return new object[] { new bool[0], new bool[0], new bool[0] };
foreach (int size in new[] { 1, BitsPerByte, BitsPerByte * 2, BitsPerInt32, BitsPerInt32 * 2, short.MaxValue })
{
bool[] allTrue = Enumerable.Repeat(true, size).ToArray();
bool[] allFalse = Enumerable.Repeat(false, size).ToArray();
bool[] alternating = Enumerable.Range(0, size).Select(i => i % 2 == 1).ToArray();
bool[] inverse = Enumerable.Range(0, size).Select(i => i % 2 == 0).ToArray();
yield return new object[] { allTrue, allTrue, allFalse };
yield return new object[] { allTrue, allFalse, allTrue };
yield return new object[] { allFalse, allTrue, allTrue };
yield return new object[] { allFalse, allFalse, allFalse };
yield return new object[] { allTrue, alternating, inverse };
yield return new object[] { alternating, allTrue, inverse };
yield return new object[] { allFalse, alternating, alternating };
yield return new object[] { alternating, allFalse, alternating };
yield return new object[] { alternating, inverse, allTrue };
yield return new object[] { inverse, alternating, allTrue };
}
}
[Theory]
[MemberData(nameof(Xor_Operator_Data))]
public static void Xor_Operator(bool[] l, bool[] r, bool[] expected)
{
BitArray left = new BitArray(l);
BitArray right = new BitArray(r);
BitArray actual = left.Xor(right);
Assert.Same(left, actual);
Assert.Equal(actual.Length, expected.Length);
for (int i = 0; i < expected.Length; i++)
{
Assert.Equal(expected[i], actual[i]);
}
}
[Fact]
public static void And_Invalid()
{
BitArray bitArray1 = new BitArray(11, false);
BitArray bitArray2 = new BitArray(6, false);
// Different lengths
Assert.Throws<ArgumentException>(null, () => bitArray1.And(bitArray2));
Assert.Throws<ArgumentException>(null, () => bitArray2.And(bitArray1));
AssertExtensions.Throws<ArgumentNullException>("value", () => bitArray1.And(null));
}
[Fact]
public static void Or_Invalid()
{
BitArray bitArray1 = new BitArray(11, false);
BitArray bitArray2 = new BitArray(6, false);
// Different lengths
Assert.Throws<ArgumentException>(null, () => bitArray1.Or(bitArray2));
Assert.Throws<ArgumentException>(null, () => bitArray2.Or(bitArray1));
AssertExtensions.Throws<ArgumentNullException>("value", () => bitArray1.Or(null));
}
[Fact]
public static void Xor_Invalid()
{
BitArray bitArray1 = new BitArray(11, false);
BitArray bitArray2 = new BitArray(6, false);
// Different lengths
Assert.Throws<ArgumentException>(null, () => bitArray1.Xor(bitArray2));
Assert.Throws<ArgumentException>(null, () => bitArray2.Xor(bitArray1));
AssertExtensions.Throws<ArgumentNullException>("value", () => bitArray1.Xor(null));
}
}
}
| 43.217617 | 126 | 0.563601 | [
"MIT"
] | Acidburn0zzz/corefx | src/System.Collections/tests/BitArray/BitArray_OperatorsTests.cs | 8,341 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// <auto-generated/>
// Template Source: ComplexType.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json.Serialization;
/// <summary>
/// The type MacOsVppAppAssignmentSettings.
/// </summary>
public partial class MacOsVppAppAssignmentSettings : MobileAppAssignmentSettings
{
/// <summary>
/// Initializes a new instance of the <see cref="MacOsVppAppAssignmentSettings"/> class.
/// </summary>
public MacOsVppAppAssignmentSettings()
{
this.ODataType = "microsoft.graph.macOsVppAppAssignmentSettings";
}
/// <summary>
/// Gets or sets uninstallOnDeviceRemoval.
/// Whether or not to uninstall the app when device is removed from Intune.
/// </summary>
[JsonPropertyName("uninstallOnDeviceRemoval")]
public bool? UninstallOnDeviceRemoval { get; set; }
/// <summary>
/// Gets or sets useDeviceLicensing.
/// Whether or not to use device licensing.
/// </summary>
[JsonPropertyName("useDeviceLicensing")]
public bool? UseDeviceLicensing { get; set; }
}
}
| 35.5 | 153 | 0.586038 | [
"MIT"
] | ScriptBox99/msgraph-beta-sdk-dotnet | src/Microsoft.Graph/Generated/model/MacOsVppAppAssignmentSettings.cs | 1,633 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PageButtonMove : MonoBehaviour {
float t = 0f;
float x;
public GameObject NextPageButton1, NextPageButton2;
private void Start()
{
x = NextPageButton1.transform.position.x;
}
void Update () {
t += Time.deltaTime;
if (t <= 0.25f)
{
NextPageButton1.transform.Translate(Vector2.up * 30f * Time.deltaTime);
NextPageButton2.transform.Translate(Vector2.up * 30f * Time.deltaTime);
}
else if (t > 0.7f && t <= 0.95f)
{
NextPageButton1.transform.Translate(Vector2.down * 30f * Time.deltaTime);
NextPageButton2.transform.Translate(Vector2.down * 30f * Time.deltaTime);
}
else if (t > 1.1f)
{
t = 0f;
NextPageButton1.transform.position = new Vector3(x, NextPageButton1.transform.position.y, NextPageButton1.transform.position.z);
NextPageButton2.transform.position = new Vector3(x, NextPageButton2.transform.position.y, NextPageButton2.transform.position.z);
}
}
}
| 32.243243 | 140 | 0.610226 | [
"MIT"
] | GreenApple-SeoyeonJang/TMT | TMT/Assets/Scripts/BackgroundScript/PageButtonMove.cs | 1,195 | C# |
using Kontur.Extern.Api.Client.Exceptions;
// ReSharper disable CommentTypo
namespace Kontur.Extern.Api.Client.Models.Numbers
{
/// <summary>
/// ИНН для ИП. Формат данных: 123456789012
/// </summary>
public record Inn
{
public static readonly RegexBasedParser<Inn> Parser =
new(@"^\d{12}$", v => new Inn(v), (param, value) => Errors.InvalidAuthorityNumber(param, value, AuthorityNumberKind.Inn, "XXXXXXXXXXXX"));
public static Inn Parse(string value) => Parser.Parse(value);
private Inn(string value) => Value = value;
public string Value { get; }
public AuthorityNumberKind Kind => AuthorityNumberKind.Inn;
public override string ToString() => Value;
}
} | 31.125 | 150 | 0.655957 | [
"MIT"
] | skbkontur/extern-csharp-sdk | src/Kontur.Extern.Api.Client/Models/Numbers/Inn.cs | 767 | C# |
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Grammophone.DataAccess.EntityFramework
{
/// <summary>
/// Used to convert from and to Entity Framework types.
/// </summary>
internal static class TypeConversions
{
/// <summary>
/// Convert from <see cref="EntityState"/> to <see cref="TrackingState"/>.
/// </summary>
public static TrackingState EntityStateToTrackingState(EntityState entityState)
=> (TrackingState)entityState;
/// <summary>
/// Convert from <see cref="TrackingState"/> to <see cref="EntityState"/>.
/// </summary>
public static EntityState TrackingStateToEntityState(TrackingState trackingState)
=> (EntityState)trackingState;
}
}
| 28.035714 | 83 | 0.735032 | [
"MIT"
] | grammophone/Grammophone.DataAccess.EntityFramework | TypeConversions.cs | 787 | C# |
/*
* Copyright 2011-14 Peter Curran (peter@currans.eu). All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY PETER CURRAN "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL PETER CURRAN OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those of the author alone.
*/
using System.Collections.Generic;
using System.Windows.Forms;
using Microsoft.ManagementConsole;
using SystemX509 = System.Security.Cryptography.X509Certificates;
using Org.BouncyCastle.X509;
using OSCA;
using OSCASnapin.CAinfo;
using OSCASnapin.ConfigManager;
namespace OSCASnapin
{
/// <summary>
/// CertListView class - Loads and allows selection of certificates.
/// </summary>
internal class CertListView : MmcListView
{
private Configuration mgrConfig = Configuration.Instance;
protected CaInfoContext context;
// MUST be public
public CertListView()
{
}
protected override void OnShow()
{
base.OnShow();
Refresh();
}
/// <summary>
/// Define the ListView's structure
/// </summary>
/// <param name="status">status for updating the console</param>
protected override void OnInitialize(AsyncStatus status)
{
// do default handling
base.OnInitialize(status);
// Start listening for scope node events
((CertsNode)this.ScopeNode).Changed += new CertsNode.ChangedDelegate(OnScopeNodeChange);
// get the certStatus
context = (CaInfoContext)this.ViewDescriptionTag;
// Create a set of columns for use in the list view
this.Columns[0].Title = "Subject";
this.Columns[0].SetWidth(200);
if ((context.certStatus == CertStatus.Current) || (context.certStatus == CertStatus.Expired))
{
// Add detail column
this.Columns.Add(new MmcListViewColumn("Issue Date", 100));
this.Columns.Add(new MmcListViewColumn("Expiry Date", 100));
this.Columns.Add(new MmcListViewColumn("Profile", 75));
this.Columns.Add(new MmcListViewColumn("Serial Number", 200));
}
else
{
// Add detail columns
this.Columns.Add(new MmcListViewColumn("Revocation Date", 100));
this.Columns.Add(new MmcListViewColumn("Revocation Reason", 100));
this.Columns.Add(new MmcListViewColumn("Profile", 75));
this.Columns.Add(new MmcListViewColumn("Serial Number", 200));
}
// Set to show all columns
this.Mode = MmcListViewMode.Report;
// set to show refresh as an option
this.SelectionData.EnabledStandardVerbs = StandardVerbs.Refresh;
// Load the list with values
Refresh();
}
/// <summary>
/// Do any cleanup. In this case Stop listening for scope node events
/// </summary>
/// <param name="status"></param>
protected override void OnShutdown(SyncStatus status)
{
((CertsNode)this.ScopeNode).Changed -= new CertsNode.ChangedDelegate(OnScopeNodeChange);
}
/// <summary>
/// Handle any change to the scope node. In this case just refresh views
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
internal void OnScopeNodeChange(object sender, CertsNode.ChangedEventArgs e)
{
if (e.Status == "IssueCert")
{
Refresh();
}
}
/// <summary>
/// Define actions for selection
/// </summary>
/// <param name="status">status for updating the console</param>
protected override void OnSelectionChanged(SyncStatus status)
{
if (this.SelectedNodes.Count == 0)
{
this.SelectionData.Clear();
}
else
{
this.ActionsPaneItems.Clear();
this.SelectionData.ActionsPaneItems.Clear();
switch (context.certStatus)
{
case CertStatus.Current:
this.SelectionData.Update(null, this.SelectedNodes.Count > 1, null, null);
if (mgrConfig.Permitted("ViewCert"))
this.SelectionData.ActionsPaneItems.Add(new Microsoft.ManagementConsole.Action
("View", "View this certificate", 4, "ViewCert"));
if (mgrConfig.Permitted("ExportCert"))
this.SelectionData.ActionsPaneItems.Add(new Microsoft.ManagementConsole.Action
("Export", "Export this certificate", 4, "ExportCert"));
if (context.caInfo.CAStatus == CAstatus.Running)
{
if (mgrConfig.Permitted("RevokeCert"))
this.SelectionData.ActionsPaneItems.Add(new Microsoft.ManagementConsole.Action
("Revoke", "Revoke this certificate", 4, "RevokeCert"));
if (mgrConfig.Permitted("RenewCert"))
this.SelectionData.ActionsPaneItems.Add(new Microsoft.ManagementConsole.Action
("Renew", "Renew this certificate", 4, "RenewCert"));
if (mgrConfig.Permitted("RekeyCert"))
this.SelectionData.ActionsPaneItems.Add(new Microsoft.ManagementConsole.Action
("Rekey", "Rekey this certificate", 4, "RekeyCert"));
}
break;
case CertStatus.Revoked:
this.SelectionData.Update(null, this.SelectedNodes.Count > 1, null, null);
if (mgrConfig.Permitted("ViewCert"))
this.SelectionData.ActionsPaneItems.Add(new Microsoft.ManagementConsole.Action
("View", "View this certificate", 4, "ViewCert"));
if (mgrConfig.Permitted("ExportCert"))
this.SelectionData.ActionsPaneItems.Add(new Microsoft.ManagementConsole.Action
("Export", "Export this certificate", 4, "ExportCert"));
if (context.caInfo.CAStatus == CAstatus.Running)
{
if (mgrConfig.Permitted("UnRevokeCert"))
this.SelectionData.ActionsPaneItems.Add(new Microsoft.ManagementConsole.Action
("UnRevoke", "Remove Revocation", 4, "UnRevokeCert"));
}
break;
case CertStatus.Expired:
this.SelectionData.Update(null, this.SelectedNodes.Count > 1, null, null);
if (mgrConfig.Permitted("ViewCert"))
this.SelectionData.ActionsPaneItems.Add(new Microsoft.ManagementConsole.Action
("View", "View this certificate", 4, "ViewCert"));
if (mgrConfig.Permitted("ExportCert"))
this.SelectionData.ActionsPaneItems.Add(new Microsoft.ManagementConsole.Action
("Export", "Export this certificate", 4, "ExportCert"));
break;
}
}
}
/// <summary>
///
/// </summary>
/// <param name="status"></param>
protected override void OnRefresh(AsyncStatus status)
{
Refresh();
}
/// <summary>
/// Handle short cut style menu actions for selection
/// </summary>
/// <param name="action">triggered action</param>
/// <param name="status">asynchronous status used to update the console</param>
protected override void OnSelectionAction(Microsoft.ManagementConsole.Action action, AsyncStatus status)
{
X509Certificate cert = (X509Certificate)this.SelectedNodes[0].Tag;
switch ((string)action.Tag)
{
case "ViewCert":
SystemX509.X509Certificate2UI.DisplayCertificate(new SystemX509.X509Certificate2(cert.GetEncoded()));
break;
case "ExportCert":
CertSave certSave = new CertSave(context.caInfo);
certSave.cert = cert;
this.SnapIn.Console.ShowDialog(certSave);
break;
case "RevokeCert":
revokeCert revoke = new revokeCert(cert);
if (this.SnapIn.Console.ShowDialog(revoke) == DialogResult.OK)
{
context.caInfo.RevokeCertificate(cert, (CRLReason)revoke.cbReason.SelectedIndex);
Refresh();
}
break;
case "RenewCert":
break;
case "RekeyCert":
RekeyCert rekey = new RekeyCert(context.caInfo, cert );
if (this.SnapIn.Console.ShowDialog(rekey) == DialogResult.OK)
{
certSave = new CertSave(context.caInfo);
certSave.cert = rekey.cert;
this.SnapIn.Console.ShowDialog(certSave);
Refresh();
}
break;
case "UnRevokeCert":
context.caInfo.UnRevokeCertificate(cert);
Refresh();
break;
}
}
/// <summary>
/// Loads the ListView with data
/// </summary>
internal void Refresh()
{
// Clear existing information
this.ResultNodes.Clear();
// Load current information
List<DataBase> certs = context.caInfo.GetCerts(context.certStatus);
foreach (var cert in certs)
{
ResultNode node = new ResultNode();
node.DisplayName = cert.dn;
if (context.certStatus == CertStatus.Revoked)
{
node.ImageIndex = 5;
node.SubItemDisplayNames.Add(cert.revDate);
node.SubItemDisplayNames.Add(cert.revReason);
node.SubItemDisplayNames.Add(cert.profile);
node.SubItemDisplayNames.Add(cert.serialNumber);
node.Tag = cert.certificate;
}
else // Current or Expired
{
node.ImageIndex = 4;
node.SubItemDisplayNames.Add(cert.created);
node.SubItemDisplayNames.Add(cert.expiry);
node.SubItemDisplayNames.Add(cert.profile);
node.SubItemDisplayNames.Add(cert.serialNumber);
node.Tag = cert.certificate;
}
this.ResultNodes.Add(node);
}
}
}
}
| 44.105802 | 146 | 0.530295 | [
"BSD-2-Clause"
] | hugocurran/OSCA2 | OSCAmmc/CertListView.cs | 12,925 | C# |
using System.Collections.Generic;
using System.Linq;
namespace Xyperico.Base.StandardFormats.vCards
{
public class vCardMultiValueSet<T>
where T : vCardMultiValue<T>
{
public List<T> Items { get; private set; }
public T Default
{
get
{
if (Items.Count > 0)
{
T defaultItem = Items[0];
foreach (T item in Items)
{
if (item.Pref < defaultItem.Pref)
defaultItem = item;
}
return defaultItem;
}
else
{
return null;
}
}
}
public T this[string type]
{
get
{
return Items.Where(i => i.Type == type).FirstOrDefault();
}
}
public vCardMultiValueSet()
{
Items = new List<T>();
}
}
}
| 17.3 | 66 | 0.469364 | [
"MIT"
] | JornWildt/Xyperico | Xyperico.Base/Xyperico.Base.StandardFormats/vCards/vCardMultiValueSet.cs | 867 | C# |
/*
* freee API
*
* <h1 id=\"freee_api\">freee API</h1> <hr /> <h2 id=\"start_guide\">スタートガイド</h2> <p>freee API開発がはじめての方は<a href=\"https://developer.freee.co.jp/getting-started\">freee API スタートガイド</a>を参照してください。</p> <hr /> <h2 id=\"specification\">仕様</h2> <pre><code>【重要】会計freee APIの新バージョンについて 2020年12月まで、2つのバージョンが利用できる状態です。古いものは2020年12月に利用不可となります。<br> 新しいAPIを利用するにはリクエストヘッダーに以下を指定します。 X-Api-Version: 2020-06-15<br> 指定がない場合は2020年12月に廃止予定のAPIを利用することとなります。<br> 【重要】APIのバージョン指定をせずに利用し続ける場合 2020年12月に新しいバージョンのAPIに自動的に切り替わります。 詳細は、<a href=\"https://developer.freee.co.jp/release-note/2948\" target=\"_blank\">リリースノート</a>をご覧ください。<br> 旧バージョンのAPIリファレンスを確認したい場合は、<a href=\"https://freee.github.io/freee-api-schema/\" target=\"_blank\">旧バージョンのAPIリファレンスページ</a>をご覧ください。 </code></pre> <h3 id=\"api_endpoint\">APIエンドポイント</h3> <p>https://api.freee.co.jp/ (httpsのみ)</p> <h3 id=\"about_authorize\">認証について</h3> <p>OAuth2.0を利用します。詳細は<a href=\"https://developer.freee.co.jp/docs\" target=\"_blank\">ドキュメントの認証</a>パートを参照してください。</p> <h3 id=\"data_format\">データフォーマット</h3> <p>リクエスト、レスポンスともにJSON形式をサポートしていますが、詳細は、API毎の説明欄(application/jsonなど)を確認してください。</p> <h3 id=\"compatibility\">後方互換性ありの変更</h3> <p>freeeでは、APIを改善していくために以下のような変更は後方互換性ありとして通知なく変更を入れることがあります。アプリケーション実装者は以下を踏まえて開発を行ってください。</p> <ul> <li>新しいAPIリソース・エンドポイントの追加</li> <li>既存のAPIに対して必須ではない新しいリクエストパラメータの追加</li> <li>既存のAPIレスポンスに対する新しいプロパティの追加</li> <li>既存のAPIレスポンスに対するプロパティの順番の入れ変え</li> <li>keyとなっているidやcodeの長さの変更(長くする)</li> </ul> <h3 id=\"common_response_header\">共通レスポンスヘッダー</h3> <p>すべてのAPIのレスポンスには以下のHTTPヘッダーが含まれます。</p> <ul> <li> <p>X-Freee-Request-ID</p> <ul> <li>各リクエスト毎に発行されるID</li> </ul> </li> </ul> <h3 id=\"common_error_response\">共通エラーレスポンス</h3> <ul> <li> <p>ステータスコードはレスポンス内のJSONに含まれる他、HTTPヘッダにも含まれる</p> </li> <li> <p>一部のエラーレスポンスにはエラーコードが含まれます。<br>詳細は、<a href=\"https://developer.freee.co.jp/tips/faq/40x-checkpoint\">HTTPステータスコード400台エラー時のチェックポイント</a>を参照してください</p> </li> <p>type</p> <ul> <li>status : HTTPステータスコードの説明</li> <li>validation : エラーの詳細の説明(開発者向け)</li> </ul> </li> </ul> <p>レスポンスの例</p> <pre><code> { "status_code" : 400, "errors" : [ { "type" : "status", "messages" : ["不正なリクエストです。"] }, { "type" : "validation", "messages" : ["Date は不正な日付フォーマットです。入力例:2013-01-01"] } ] }</code></pre> </br> <h3 id=\"api_rate_limit\">API使用制限</h3> <p>freeeは一定期間に過度のアクセスを検知した場合、APIアクセスをコントロールする場合があります。</p> <p>その際のhttp status codeは403となります。制限がかかってから10分程度が過ぎると再度使用することができるようになります。</p> <h4 id=\"reports_api_endpoint\">/reportsエンドポイント</h4> <p>freeeは/reportsエンドポイントに対して1秒間に10以上のアクセスを検知した場合、APIアクセスをコントロールする場合があります。その際のhttp status codeは429(too many requests)となります。</p> <p>レスポンスボディのmetaプロパティに以下を含めます。</p> <ul> <li>設定されている上限値</li> <li>上限に達するまでの使用可能回数</li> <li>(上限値に達した場合)使用回数がリセットされる時刻</li> </ul> <h3 id=\"plan_api_rate_limit\">プラン別のAPI Rate Limit</h3> <table border=\"1\"> <tbody> <tr> <th style=\"padding: 10px\"><strong>会計freeeプラン名</strong></th> <th style=\"padding: 10px\"><strong>事業所とアプリケーション毎に1日でのAPIコール数</strong></th> </tr> <tr> <td style=\"padding: 10px\">エンタープライズ</td> <td style=\"padding: 10px\">10,000</td> </tr> <tr> <td style=\"padding: 10px\">プロフェッショナル</td> <td style=\"padding: 10px\">5,000</td> </tr> <tr> <td style=\"padding: 10px\">ベーシック</td> <td style=\"padding: 10px\">3,000</td> </tr> <tr> <td style=\"padding: 10px\">ミニマム</td> <td style=\"padding: 10px\">3,000</td> </tr> <tr> <td style=\"padding: 10px\">上記以外</td> <td style=\"padding: 10px\">3,000</td> </tr> </tbody> </table> <h3 id=\"webhook\">Webhookについて</h3> <p>詳細は<a href=\"https://developer.freee.co.jp/docs/accounting/webhook\" target=\"_blank\">会計Webhook概要</a>を参照してください。</p> <hr /> <h2 id=\"contact\">連絡先</h2> <p>ご不明点、ご要望等は <a href=\"https://support.freee.co.jp/hc/ja/requests/new\">freee サポートデスクへのお問い合わせフォーム</a> からご連絡ください。</p> <hr />© Since 2013 freee K.K.
*
* The version of the OpenAPI document: v1.0
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Net.Mime;
using Freee.Accounting.Client;
using Freee.Accounting.Models;
namespace Freee.Accounting.Api
{
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public interface IExpenseApplicationsApiSync : IApiAccessor
{
#region Synchronous Operations
/// <summary>
/// 経費申請の作成
/// </summary>
/// <remarks>
/// <h2 id=\"_1\">概要</h2> <p>指定した事業所の経費申請を作成する</p> <h2 id=\"_2\">注意点</h2> <ul> <li>本APIでは、経費申請の下書きを作成することができます。申請作業はWebから行ってください。</li> <li>現在、申請経路はWeb上からのみ入力できます。Web上での申請時に指定してください。</li> <li>申請時には、申請タイトル(title)に加え、申請日(issue_date)、項目行については金額(amount)、日付(transaction_date)、内容(description)が必須項目となります。申請時の業務効率化のため、API入力をお勧めします。</li> <li>個人アカウントの場合は、プレミアムプランでご利用できます。</li> <li>法人アカウントの場合は、ベーシックプラン、プロフェッショナルプラン、エンタープライズプランでご利用できます。</li> </ul>
/// </remarks>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="expenseApplicationCreateParams">経費申請の作成 (optional)</param>
/// <returns>ExpenseApplicationResponse</returns>
ExpenseApplicationResponse CreateExpenseApplication(ExpenseApplicationCreateParams expenseApplicationCreateParams = default(ExpenseApplicationCreateParams));
/// <summary>
/// 経費申請の作成
/// </summary>
/// <remarks>
/// <h2 id=\"_1\">概要</h2> <p>指定した事業所の経費申請を作成する</p> <h2 id=\"_2\">注意点</h2> <ul> <li>本APIでは、経費申請の下書きを作成することができます。申請作業はWebから行ってください。</li> <li>現在、申請経路はWeb上からのみ入力できます。Web上での申請時に指定してください。</li> <li>申請時には、申請タイトル(title)に加え、申請日(issue_date)、項目行については金額(amount)、日付(transaction_date)、内容(description)が必須項目となります。申請時の業務効率化のため、API入力をお勧めします。</li> <li>個人アカウントの場合は、プレミアムプランでご利用できます。</li> <li>法人アカウントの場合は、ベーシックプラン、プロフェッショナルプラン、エンタープライズプランでご利用できます。</li> </ul>
/// </remarks>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="expenseApplicationCreateParams">経費申請の作成 (optional)</param>
/// <returns>ApiResponse of ExpenseApplicationResponse</returns>
ApiResponse<ExpenseApplicationResponse> CreateExpenseApplicationWithHttpInfo(ExpenseApplicationCreateParams expenseApplicationCreateParams = default(ExpenseApplicationCreateParams));
/// <summary>
/// 経費申請の削除
/// </summary>
/// <remarks>
/// <h2 id=\"\">概要</h2> <p>指定した事業所の経費申請を削除する</p> <h2 id=\"_2\">注意点</h2> <ul> <li>個人アカウントの場合は、プレミアムプランでご利用できます。</li> <li>法人アカウントの場合は、ベーシックプラン、プロフェッショナルプラン、エンタープライズプランでご利用できます。</li> </ul>
/// </remarks>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id"></param>
/// <param name="companyId">事業所ID</param>
/// <returns></returns>
void DestroyExpenseApplication(int id, int companyId);
/// <summary>
/// 経費申請の削除
/// </summary>
/// <remarks>
/// <h2 id=\"\">概要</h2> <p>指定した事業所の経費申請を削除する</p> <h2 id=\"_2\">注意点</h2> <ul> <li>個人アカウントの場合は、プレミアムプランでご利用できます。</li> <li>法人アカウントの場合は、ベーシックプラン、プロフェッショナルプラン、エンタープライズプランでご利用できます。</li> </ul>
/// </remarks>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id"></param>
/// <param name="companyId">事業所ID</param>
/// <returns>ApiResponse of Object(void)</returns>
ApiResponse<Object> DestroyExpenseApplicationWithHttpInfo(int id, int companyId);
/// <summary>
/// 経費申請詳細の取得
/// </summary>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">経費申請ID</param>
/// <param name="companyId">事業所ID</param>
/// <returns>ExpenseApplicationResponse</returns>
ExpenseApplicationResponse GetExpenseApplication(int id, int companyId);
/// <summary>
/// 経費申請詳細の取得
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">経費申請ID</param>
/// <param name="companyId">事業所ID</param>
/// <returns>ApiResponse of ExpenseApplicationResponse</returns>
ApiResponse<ExpenseApplicationResponse> GetExpenseApplicationWithHttpInfo(int id, int companyId);
/// <summary>
/// 経費申請一覧の取得
/// </summary>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="companyId">事業所ID</param>
/// <param name="offset">取得レコードのオフセット (デフォルト: 0) (optional)</param>
/// <param name="limit">取得レコードの件数 (デフォルト: 50, 最小: 1, 最大: 500) (optional)</param>
/// <returns>ExpenseApplicationsIndexResponse</returns>
ExpenseApplicationsIndexResponse GetExpenseApplications(int companyId, int? offset = default(int?), int? limit = default(int?));
/// <summary>
/// 経費申請一覧の取得
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="companyId">事業所ID</param>
/// <param name="offset">取得レコードのオフセット (デフォルト: 0) (optional)</param>
/// <param name="limit">取得レコードの件数 (デフォルト: 50, 最小: 1, 最大: 500) (optional)</param>
/// <returns>ApiResponse of ExpenseApplicationsIndexResponse</returns>
ApiResponse<ExpenseApplicationsIndexResponse> GetExpenseApplicationsWithHttpInfo(int companyId, int? offset = default(int?), int? limit = default(int?));
/// <summary>
/// 経費申請の更新
/// </summary>
/// <remarks>
/// <h2 id=\"\">概要</h2> <p>指定した事業所の経費申請を更新する</p> <h2 id=\"_2\">注意点</h2> <ul> <li>本APIでは、経費申請の下書きを更新することができます。申請作業はWebから行ってください。</li> <li>現在、申請経路はWeb上からのみ入力できます。Web上での申請時に指定してください。</li> <li>申請時には、申請タイトル(title)に加え、申請日(issue_date)、項目行については金額(amount)、日付(transaction_date)、内容(description)が必須項目となります。申請時の業務効率化のため、API入力をお勧めします。</li> <li>個人アカウントの場合は、プレミアムプランでご利用できます。</li> <li>法人アカウントの場合は、ベーシックプラン、プロフェッショナルプラン、エンタープライズプランでご利用できます。</li> </ul>
/// </remarks>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id"></param>
/// <param name="expenseApplicationUpdateParams">経費申請の更新 (optional)</param>
/// <returns>ExpenseApplicationResponse</returns>
ExpenseApplicationResponse UpdateExpenseApplication(int id, ExpenseApplicationUpdateParams expenseApplicationUpdateParams = default(ExpenseApplicationUpdateParams));
/// <summary>
/// 経費申請の更新
/// </summary>
/// <remarks>
/// <h2 id=\"\">概要</h2> <p>指定した事業所の経費申請を更新する</p> <h2 id=\"_2\">注意点</h2> <ul> <li>本APIでは、経費申請の下書きを更新することができます。申請作業はWebから行ってください。</li> <li>現在、申請経路はWeb上からのみ入力できます。Web上での申請時に指定してください。</li> <li>申請時には、申請タイトル(title)に加え、申請日(issue_date)、項目行については金額(amount)、日付(transaction_date)、内容(description)が必須項目となります。申請時の業務効率化のため、API入力をお勧めします。</li> <li>個人アカウントの場合は、プレミアムプランでご利用できます。</li> <li>法人アカウントの場合は、ベーシックプラン、プロフェッショナルプラン、エンタープライズプランでご利用できます。</li> </ul>
/// </remarks>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id"></param>
/// <param name="expenseApplicationUpdateParams">経費申請の更新 (optional)</param>
/// <returns>ApiResponse of ExpenseApplicationResponse</returns>
ApiResponse<ExpenseApplicationResponse> UpdateExpenseApplicationWithHttpInfo(int id, ExpenseApplicationUpdateParams expenseApplicationUpdateParams = default(ExpenseApplicationUpdateParams));
#endregion Synchronous Operations
}
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public interface IExpenseApplicationsApiAsync : IApiAccessor
{
#region Asynchronous Operations
/// <summary>
/// 経費申請の作成
/// </summary>
/// <remarks>
/// <h2 id=\"_1\">概要</h2> <p>指定した事業所の経費申請を作成する</p> <h2 id=\"_2\">注意点</h2> <ul> <li>本APIでは、経費申請の下書きを作成することができます。申請作業はWebから行ってください。</li> <li>現在、申請経路はWeb上からのみ入力できます。Web上での申請時に指定してください。</li> <li>申請時には、申請タイトル(title)に加え、申請日(issue_date)、項目行については金額(amount)、日付(transaction_date)、内容(description)が必須項目となります。申請時の業務効率化のため、API入力をお勧めします。</li> <li>個人アカウントの場合は、プレミアムプランでご利用できます。</li> <li>法人アカウントの場合は、ベーシックプラン、プロフェッショナルプラン、エンタープライズプランでご利用できます。</li> </ul>
/// </remarks>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="expenseApplicationCreateParams">経費申請の作成 (optional)</param>
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <returns>Task of ExpenseApplicationResponse</returns>
System.Threading.Tasks.Task<ExpenseApplicationResponse> CreateExpenseApplicationAsync(ExpenseApplicationCreateParams expenseApplicationCreateParams = default(ExpenseApplicationCreateParams), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// 経費申請の作成
/// </summary>
/// <remarks>
/// <h2 id=\"_1\">概要</h2> <p>指定した事業所の経費申請を作成する</p> <h2 id=\"_2\">注意点</h2> <ul> <li>本APIでは、経費申請の下書きを作成することができます。申請作業はWebから行ってください。</li> <li>現在、申請経路はWeb上からのみ入力できます。Web上での申請時に指定してください。</li> <li>申請時には、申請タイトル(title)に加え、申請日(issue_date)、項目行については金額(amount)、日付(transaction_date)、内容(description)が必須項目となります。申請時の業務効率化のため、API入力をお勧めします。</li> <li>個人アカウントの場合は、プレミアムプランでご利用できます。</li> <li>法人アカウントの場合は、ベーシックプラン、プロフェッショナルプラン、エンタープライズプランでご利用できます。</li> </ul>
/// </remarks>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="expenseApplicationCreateParams">経費申請の作成 (optional)</param>
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <returns>Task of ApiResponse (ExpenseApplicationResponse)</returns>
System.Threading.Tasks.Task<ApiResponse<ExpenseApplicationResponse>> CreateExpenseApplicationWithHttpInfoAsync(ExpenseApplicationCreateParams expenseApplicationCreateParams = default(ExpenseApplicationCreateParams), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// 経費申請の削除
/// </summary>
/// <remarks>
/// <h2 id=\"\">概要</h2> <p>指定した事業所の経費申請を削除する</p> <h2 id=\"_2\">注意点</h2> <ul> <li>個人アカウントの場合は、プレミアムプランでご利用できます。</li> <li>法人アカウントの場合は、ベーシックプラン、プロフェッショナルプラン、エンタープライズプランでご利用できます。</li> </ul>
/// </remarks>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id"></param>
/// <param name="companyId">事業所ID</param>
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <returns>Task of void</returns>
System.Threading.Tasks.Task DestroyExpenseApplicationAsync(int id, int companyId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// 経費申請の削除
/// </summary>
/// <remarks>
/// <h2 id=\"\">概要</h2> <p>指定した事業所の経費申請を削除する</p> <h2 id=\"_2\">注意点</h2> <ul> <li>個人アカウントの場合は、プレミアムプランでご利用できます。</li> <li>法人アカウントの場合は、ベーシックプラン、プロフェッショナルプラン、エンタープライズプランでご利用できます。</li> </ul>
/// </remarks>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id"></param>
/// <param name="companyId">事業所ID</param>
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <returns>Task of ApiResponse</returns>
System.Threading.Tasks.Task<ApiResponse<Object>> DestroyExpenseApplicationWithHttpInfoAsync(int id, int companyId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// 経費申請詳細の取得
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">経費申請ID</param>
/// <param name="companyId">事業所ID</param>
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <returns>Task of ExpenseApplicationResponse</returns>
System.Threading.Tasks.Task<ExpenseApplicationResponse> GetExpenseApplicationAsync(int id, int companyId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// 経費申請詳細の取得
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">経費申請ID</param>
/// <param name="companyId">事業所ID</param>
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <returns>Task of ApiResponse (ExpenseApplicationResponse)</returns>
System.Threading.Tasks.Task<ApiResponse<ExpenseApplicationResponse>> GetExpenseApplicationWithHttpInfoAsync(int id, int companyId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// 経費申請一覧の取得
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="companyId">事業所ID</param>
/// <param name="offset">取得レコードのオフセット (デフォルト: 0) (optional)</param>
/// <param name="limit">取得レコードの件数 (デフォルト: 50, 最小: 1, 最大: 500) (optional)</param>
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <returns>Task of ExpenseApplicationsIndexResponse</returns>
System.Threading.Tasks.Task<ExpenseApplicationsIndexResponse> GetExpenseApplicationsAsync(int companyId, int? offset = default(int?), int? limit = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// 経費申請一覧の取得
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="companyId">事業所ID</param>
/// <param name="offset">取得レコードのオフセット (デフォルト: 0) (optional)</param>
/// <param name="limit">取得レコードの件数 (デフォルト: 50, 最小: 1, 最大: 500) (optional)</param>
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <returns>Task of ApiResponse (ExpenseApplicationsIndexResponse)</returns>
System.Threading.Tasks.Task<ApiResponse<ExpenseApplicationsIndexResponse>> GetExpenseApplicationsWithHttpInfoAsync(int companyId, int? offset = default(int?), int? limit = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// 経費申請の更新
/// </summary>
/// <remarks>
/// <h2 id=\"\">概要</h2> <p>指定した事業所の経費申請を更新する</p> <h2 id=\"_2\">注意点</h2> <ul> <li>本APIでは、経費申請の下書きを更新することができます。申請作業はWebから行ってください。</li> <li>現在、申請経路はWeb上からのみ入力できます。Web上での申請時に指定してください。</li> <li>申請時には、申請タイトル(title)に加え、申請日(issue_date)、項目行については金額(amount)、日付(transaction_date)、内容(description)が必須項目となります。申請時の業務効率化のため、API入力をお勧めします。</li> <li>個人アカウントの場合は、プレミアムプランでご利用できます。</li> <li>法人アカウントの場合は、ベーシックプラン、プロフェッショナルプラン、エンタープライズプランでご利用できます。</li> </ul>
/// </remarks>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id"></param>
/// <param name="expenseApplicationUpdateParams">経費申請の更新 (optional)</param>
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <returns>Task of ExpenseApplicationResponse</returns>
System.Threading.Tasks.Task<ExpenseApplicationResponse> UpdateExpenseApplicationAsync(int id, ExpenseApplicationUpdateParams expenseApplicationUpdateParams = default(ExpenseApplicationUpdateParams), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// 経費申請の更新
/// </summary>
/// <remarks>
/// <h2 id=\"\">概要</h2> <p>指定した事業所の経費申請を更新する</p> <h2 id=\"_2\">注意点</h2> <ul> <li>本APIでは、経費申請の下書きを更新することができます。申請作業はWebから行ってください。</li> <li>現在、申請経路はWeb上からのみ入力できます。Web上での申請時に指定してください。</li> <li>申請時には、申請タイトル(title)に加え、申請日(issue_date)、項目行については金額(amount)、日付(transaction_date)、内容(description)が必須項目となります。申請時の業務効率化のため、API入力をお勧めします。</li> <li>個人アカウントの場合は、プレミアムプランでご利用できます。</li> <li>法人アカウントの場合は、ベーシックプラン、プロフェッショナルプラン、エンタープライズプランでご利用できます。</li> </ul>
/// </remarks>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id"></param>
/// <param name="expenseApplicationUpdateParams">経費申請の更新 (optional)</param>
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <returns>Task of ApiResponse (ExpenseApplicationResponse)</returns>
System.Threading.Tasks.Task<ApiResponse<ExpenseApplicationResponse>> UpdateExpenseApplicationWithHttpInfoAsync(int id, ExpenseApplicationUpdateParams expenseApplicationUpdateParams = default(ExpenseApplicationUpdateParams), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
#endregion Asynchronous Operations
}
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public interface IExpenseApplicationsApi : IExpenseApplicationsApiSync, IExpenseApplicationsApiAsync
{
}
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public partial class ExpenseApplicationsApi : IExpenseApplicationsApi
{
private Freee.Accounting.Client.ExceptionFactory _exceptionFactory = (name, response) => null;
/// <summary>
/// Initializes a new instance of the <see cref="ExpenseApplicationsApi"/> class.
/// </summary>
/// <returns></returns>
public ExpenseApplicationsApi() : this((string)null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ExpenseApplicationsApi"/> class.
/// </summary>
/// <returns></returns>
public ExpenseApplicationsApi(String basePath)
{
this.Configuration = Freee.Accounting.Client.Configuration.MergeConfigurations(
Freee.Accounting.Client.GlobalConfiguration.Instance,
new Freee.Accounting.Client.Configuration { BasePath = basePath }
);
this.Client = new Freee.Accounting.Client.ApiClient(this.Configuration.BasePath);
this.AsynchronousClient = new Freee.Accounting.Client.ApiClient(this.Configuration.BasePath);
this.ExceptionFactory = Freee.Accounting.Client.Configuration.DefaultExceptionFactory;
}
/// <summary>
/// Initializes a new instance of the <see cref="ExpenseApplicationsApi"/> class
/// using Configuration object
/// </summary>
/// <param name="configuration">An instance of Configuration</param>
/// <returns></returns>
public ExpenseApplicationsApi(Freee.Accounting.Client.Configuration configuration)
{
if (configuration == null) throw new ArgumentNullException("configuration");
this.Configuration = Freee.Accounting.Client.Configuration.MergeConfigurations(
Freee.Accounting.Client.GlobalConfiguration.Instance,
configuration
);
this.Client = new Freee.Accounting.Client.ApiClient(this.Configuration.BasePath);
this.AsynchronousClient = new Freee.Accounting.Client.ApiClient(this.Configuration.BasePath);
ExceptionFactory = Freee.Accounting.Client.Configuration.DefaultExceptionFactory;
}
/// <summary>
/// Initializes a new instance of the <see cref="ExpenseApplicationsApi"/> class
/// using a Configuration object and client instance.
/// </summary>
/// <param name="client">The client interface for synchronous API access.</param>
/// <param name="asyncClient">The client interface for asynchronous API access.</param>
/// <param name="configuration">The configuration object.</param>
public ExpenseApplicationsApi(Freee.Accounting.Client.ISynchronousClient client, Freee.Accounting.Client.IAsynchronousClient asyncClient, Freee.Accounting.Client.IReadableConfiguration configuration)
{
if (client == null) throw new ArgumentNullException("client");
if (asyncClient == null) throw new ArgumentNullException("asyncClient");
if (configuration == null) throw new ArgumentNullException("configuration");
this.Client = client;
this.AsynchronousClient = asyncClient;
this.Configuration = configuration;
this.ExceptionFactory = Freee.Accounting.Client.Configuration.DefaultExceptionFactory;
}
/// <summary>
/// The client for accessing this underlying API asynchronously.
/// </summary>
public Freee.Accounting.Client.IAsynchronousClient AsynchronousClient { get; set; }
/// <summary>
/// The client for accessing this underlying API synchronously.
/// </summary>
public Freee.Accounting.Client.ISynchronousClient Client { get; set; }
/// <summary>
/// Gets the base path of the API client.
/// </summary>
/// <value>The base path</value>
public String GetBasePath()
{
return this.Configuration.BasePath;
}
/// <summary>
/// Gets or sets the configuration object
/// </summary>
/// <value>An instance of the Configuration</value>
public Freee.Accounting.Client.IReadableConfiguration Configuration { get; set; }
/// <summary>
/// Provides a factory method hook for the creation of exceptions.
/// </summary>
public Freee.Accounting.Client.ExceptionFactory ExceptionFactory
{
get
{
if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1)
{
throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported.");
}
return _exceptionFactory;
}
set { _exceptionFactory = value; }
}
/// <summary>
/// 経費申請の作成 <h2 id=\"_1\">概要</h2> <p>指定した事業所の経費申請を作成する</p> <h2 id=\"_2\">注意点</h2> <ul> <li>本APIでは、経費申請の下書きを作成することができます。申請作業はWebから行ってください。</li> <li>現在、申請経路はWeb上からのみ入力できます。Web上での申請時に指定してください。</li> <li>申請時には、申請タイトル(title)に加え、申請日(issue_date)、項目行については金額(amount)、日付(transaction_date)、内容(description)が必須項目となります。申請時の業務効率化のため、API入力をお勧めします。</li> <li>個人アカウントの場合は、プレミアムプランでご利用できます。</li> <li>法人アカウントの場合は、ベーシックプラン、プロフェッショナルプラン、エンタープライズプランでご利用できます。</li> </ul>
/// </summary>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="expenseApplicationCreateParams">経費申請の作成 (optional)</param>
/// <returns>ExpenseApplicationResponse</returns>
public ExpenseApplicationResponse CreateExpenseApplication(ExpenseApplicationCreateParams expenseApplicationCreateParams = default(ExpenseApplicationCreateParams))
{
Freee.Accounting.Client.ApiResponse<ExpenseApplicationResponse> localVarResponse = CreateExpenseApplicationWithHttpInfo(expenseApplicationCreateParams);
return localVarResponse.Data;
}
/// <summary>
/// 経費申請の作成 <h2 id=\"_1\">概要</h2> <p>指定した事業所の経費申請を作成する</p> <h2 id=\"_2\">注意点</h2> <ul> <li>本APIでは、経費申請の下書きを作成することができます。申請作業はWebから行ってください。</li> <li>現在、申請経路はWeb上からのみ入力できます。Web上での申請時に指定してください。</li> <li>申請時には、申請タイトル(title)に加え、申請日(issue_date)、項目行については金額(amount)、日付(transaction_date)、内容(description)が必須項目となります。申請時の業務効率化のため、API入力をお勧めします。</li> <li>個人アカウントの場合は、プレミアムプランでご利用できます。</li> <li>法人アカウントの場合は、ベーシックプラン、プロフェッショナルプラン、エンタープライズプランでご利用できます。</li> </ul>
/// </summary>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="expenseApplicationCreateParams">経費申請の作成 (optional)</param>
/// <returns>ApiResponse of ExpenseApplicationResponse</returns>
public Freee.Accounting.Client.ApiResponse<ExpenseApplicationResponse> CreateExpenseApplicationWithHttpInfo(ExpenseApplicationCreateParams expenseApplicationCreateParams = default(ExpenseApplicationCreateParams))
{
Freee.Accounting.Client.RequestOptions localVarRequestOptions = new Freee.Accounting.Client.RequestOptions();
String[] _contentTypes = new String[] {
"application/json",
"application/x-www-form-urlencoded"
};
// to determine the Accept header
String[] _accepts = new String[] {
"application/json"
};
var localVarContentType = Freee.Accounting.Client.ClientUtils.SelectHeaderContentType(_contentTypes);
if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType);
var localVarAccept = Freee.Accounting.Client.ClientUtils.SelectHeaderAccept(_accepts);
if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept);
localVarRequestOptions.Data = expenseApplicationCreateParams;
// authentication (oauth2) required
// oauth required
if (!String.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
// make the HTTP request
var localVarResponse = this.Client.Post<ExpenseApplicationResponse>("/api/1/expense_applications", localVarRequestOptions, this.Configuration);
if (this.ExceptionFactory != null)
{
Exception _exception = this.ExceptionFactory("CreateExpenseApplication", localVarResponse);
if (_exception != null) throw _exception;
}
return localVarResponse;
}
/// <summary>
/// 経費申請の作成 <h2 id=\"_1\">概要</h2> <p>指定した事業所の経費申請を作成する</p> <h2 id=\"_2\">注意点</h2> <ul> <li>本APIでは、経費申請の下書きを作成することができます。申請作業はWebから行ってください。</li> <li>現在、申請経路はWeb上からのみ入力できます。Web上での申請時に指定してください。</li> <li>申請時には、申請タイトル(title)に加え、申請日(issue_date)、項目行については金額(amount)、日付(transaction_date)、内容(description)が必須項目となります。申請時の業務効率化のため、API入力をお勧めします。</li> <li>個人アカウントの場合は、プレミアムプランでご利用できます。</li> <li>法人アカウントの場合は、ベーシックプラン、プロフェッショナルプラン、エンタープライズプランでご利用できます。</li> </ul>
/// </summary>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="expenseApplicationCreateParams">経費申請の作成 (optional)</param>
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <returns>Task of ExpenseApplicationResponse</returns>
public async System.Threading.Tasks.Task<ExpenseApplicationResponse> CreateExpenseApplicationAsync(ExpenseApplicationCreateParams expenseApplicationCreateParams = default(ExpenseApplicationCreateParams), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
Freee.Accounting.Client.ApiResponse<ExpenseApplicationResponse> localVarResponse = await CreateExpenseApplicationWithHttpInfoAsync(expenseApplicationCreateParams, cancellationToken).ConfigureAwait(false);
return localVarResponse.Data;
}
/// <summary>
/// 経費申請の作成 <h2 id=\"_1\">概要</h2> <p>指定した事業所の経費申請を作成する</p> <h2 id=\"_2\">注意点</h2> <ul> <li>本APIでは、経費申請の下書きを作成することができます。申請作業はWebから行ってください。</li> <li>現在、申請経路はWeb上からのみ入力できます。Web上での申請時に指定してください。</li> <li>申請時には、申請タイトル(title)に加え、申請日(issue_date)、項目行については金額(amount)、日付(transaction_date)、内容(description)が必須項目となります。申請時の業務効率化のため、API入力をお勧めします。</li> <li>個人アカウントの場合は、プレミアムプランでご利用できます。</li> <li>法人アカウントの場合は、ベーシックプラン、プロフェッショナルプラン、エンタープライズプランでご利用できます。</li> </ul>
/// </summary>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="expenseApplicationCreateParams">経費申請の作成 (optional)</param>
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <returns>Task of ApiResponse (ExpenseApplicationResponse)</returns>
public async System.Threading.Tasks.Task<Freee.Accounting.Client.ApiResponse<ExpenseApplicationResponse>> CreateExpenseApplicationWithHttpInfoAsync(ExpenseApplicationCreateParams expenseApplicationCreateParams = default(ExpenseApplicationCreateParams), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
Freee.Accounting.Client.RequestOptions localVarRequestOptions = new Freee.Accounting.Client.RequestOptions();
String[] _contentTypes = new String[] {
"application/json",
"application/x-www-form-urlencoded"
};
// to determine the Accept header
String[] _accepts = new String[] {
"application/json"
};
var localVarContentType = Freee.Accounting.Client.ClientUtils.SelectHeaderContentType(_contentTypes);
if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType);
var localVarAccept = Freee.Accounting.Client.ClientUtils.SelectHeaderAccept(_accepts);
if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept);
localVarRequestOptions.Data = expenseApplicationCreateParams;
// authentication (oauth2) required
// oauth required
if (!String.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
// make the HTTP request
var localVarResponse = await this.AsynchronousClient.PostAsync<ExpenseApplicationResponse>("/api/1/expense_applications", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false);
if (this.ExceptionFactory != null)
{
Exception _exception = this.ExceptionFactory("CreateExpenseApplication", localVarResponse);
if (_exception != null) throw _exception;
}
return localVarResponse;
}
/// <summary>
/// 経費申請の削除 <h2 id=\"\">概要</h2> <p>指定した事業所の経費申請を削除する</p> <h2 id=\"_2\">注意点</h2> <ul> <li>個人アカウントの場合は、プレミアムプランでご利用できます。</li> <li>法人アカウントの場合は、ベーシックプラン、プロフェッショナルプラン、エンタープライズプランでご利用できます。</li> </ul>
/// </summary>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id"></param>
/// <param name="companyId">事業所ID</param>
/// <returns></returns>
public void DestroyExpenseApplication(int id, int companyId)
{
DestroyExpenseApplicationWithHttpInfo(id, companyId);
}
/// <summary>
/// 経費申請の削除 <h2 id=\"\">概要</h2> <p>指定した事業所の経費申請を削除する</p> <h2 id=\"_2\">注意点</h2> <ul> <li>個人アカウントの場合は、プレミアムプランでご利用できます。</li> <li>法人アカウントの場合は、ベーシックプラン、プロフェッショナルプラン、エンタープライズプランでご利用できます。</li> </ul>
/// </summary>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id"></param>
/// <param name="companyId">事業所ID</param>
/// <returns>ApiResponse of Object(void)</returns>
public Freee.Accounting.Client.ApiResponse<Object> DestroyExpenseApplicationWithHttpInfo(int id, int companyId)
{
Freee.Accounting.Client.RequestOptions localVarRequestOptions = new Freee.Accounting.Client.RequestOptions();
String[] _contentTypes = new String[] {
};
// to determine the Accept header
String[] _accepts = new String[] {
"application/json"
};
var localVarContentType = Freee.Accounting.Client.ClientUtils.SelectHeaderContentType(_contentTypes);
if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType);
var localVarAccept = Freee.Accounting.Client.ClientUtils.SelectHeaderAccept(_accepts);
if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept);
localVarRequestOptions.PathParameters.Add("id", Freee.Accounting.Client.ClientUtils.ParameterToString(id)); // path parameter
localVarRequestOptions.QueryParameters.Add(Freee.Accounting.Client.ClientUtils.ParameterToMultiMap("", "company_id", companyId));
// authentication (oauth2) required
// oauth required
if (!String.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
// make the HTTP request
var localVarResponse = this.Client.Delete<Object>("/api/1/expense_applications/{id}", localVarRequestOptions, this.Configuration);
if (this.ExceptionFactory != null)
{
Exception _exception = this.ExceptionFactory("DestroyExpenseApplication", localVarResponse);
if (_exception != null) throw _exception;
}
return localVarResponse;
}
/// <summary>
/// 経費申請の削除 <h2 id=\"\">概要</h2> <p>指定した事業所の経費申請を削除する</p> <h2 id=\"_2\">注意点</h2> <ul> <li>個人アカウントの場合は、プレミアムプランでご利用できます。</li> <li>法人アカウントの場合は、ベーシックプラン、プロフェッショナルプラン、エンタープライズプランでご利用できます。</li> </ul>
/// </summary>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id"></param>
/// <param name="companyId">事業所ID</param>
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <returns>Task of void</returns>
public async System.Threading.Tasks.Task DestroyExpenseApplicationAsync(int id, int companyId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await DestroyExpenseApplicationWithHttpInfoAsync(id, companyId, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// 経費申請の削除 <h2 id=\"\">概要</h2> <p>指定した事業所の経費申請を削除する</p> <h2 id=\"_2\">注意点</h2> <ul> <li>個人アカウントの場合は、プレミアムプランでご利用できます。</li> <li>法人アカウントの場合は、ベーシックプラン、プロフェッショナルプラン、エンタープライズプランでご利用できます。</li> </ul>
/// </summary>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id"></param>
/// <param name="companyId">事業所ID</param>
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <returns>Task of ApiResponse</returns>
public async System.Threading.Tasks.Task<Freee.Accounting.Client.ApiResponse<Object>> DestroyExpenseApplicationWithHttpInfoAsync(int id, int companyId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
Freee.Accounting.Client.RequestOptions localVarRequestOptions = new Freee.Accounting.Client.RequestOptions();
String[] _contentTypes = new String[] {
};
// to determine the Accept header
String[] _accepts = new String[] {
"application/json"
};
var localVarContentType = Freee.Accounting.Client.ClientUtils.SelectHeaderContentType(_contentTypes);
if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType);
var localVarAccept = Freee.Accounting.Client.ClientUtils.SelectHeaderAccept(_accepts);
if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept);
localVarRequestOptions.PathParameters.Add("id", Freee.Accounting.Client.ClientUtils.ParameterToString(id)); // path parameter
localVarRequestOptions.QueryParameters.Add(Freee.Accounting.Client.ClientUtils.ParameterToMultiMap("", "company_id", companyId));
// authentication (oauth2) required
// oauth required
if (!String.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
// make the HTTP request
var localVarResponse = await this.AsynchronousClient.DeleteAsync<Object>("/api/1/expense_applications/{id}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false);
if (this.ExceptionFactory != null)
{
Exception _exception = this.ExceptionFactory("DestroyExpenseApplication", localVarResponse);
if (_exception != null) throw _exception;
}
return localVarResponse;
}
/// <summary>
/// 経費申請詳細の取得
/// </summary>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">経費申請ID</param>
/// <param name="companyId">事業所ID</param>
/// <returns>ExpenseApplicationResponse</returns>
public ExpenseApplicationResponse GetExpenseApplication(int id, int companyId)
{
Freee.Accounting.Client.ApiResponse<ExpenseApplicationResponse> localVarResponse = GetExpenseApplicationWithHttpInfo(id, companyId);
return localVarResponse.Data;
}
/// <summary>
/// 経費申請詳細の取得
/// </summary>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">経費申請ID</param>
/// <param name="companyId">事業所ID</param>
/// <returns>ApiResponse of ExpenseApplicationResponse</returns>
public Freee.Accounting.Client.ApiResponse<ExpenseApplicationResponse> GetExpenseApplicationWithHttpInfo(int id, int companyId)
{
Freee.Accounting.Client.RequestOptions localVarRequestOptions = new Freee.Accounting.Client.RequestOptions();
String[] _contentTypes = new String[] {
};
// to determine the Accept header
String[] _accepts = new String[] {
"application/json"
};
var localVarContentType = Freee.Accounting.Client.ClientUtils.SelectHeaderContentType(_contentTypes);
if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType);
var localVarAccept = Freee.Accounting.Client.ClientUtils.SelectHeaderAccept(_accepts);
if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept);
localVarRequestOptions.PathParameters.Add("id", Freee.Accounting.Client.ClientUtils.ParameterToString(id)); // path parameter
localVarRequestOptions.QueryParameters.Add(Freee.Accounting.Client.ClientUtils.ParameterToMultiMap("", "company_id", companyId));
// authentication (oauth2) required
// oauth required
if (!String.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
// make the HTTP request
var localVarResponse = this.Client.Get<ExpenseApplicationResponse>("/api/1/expense_applications/{id}", localVarRequestOptions, this.Configuration);
if (this.ExceptionFactory != null)
{
Exception _exception = this.ExceptionFactory("GetExpenseApplication", localVarResponse);
if (_exception != null) throw _exception;
}
return localVarResponse;
}
/// <summary>
/// 経費申請詳細の取得
/// </summary>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">経費申請ID</param>
/// <param name="companyId">事業所ID</param>
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <returns>Task of ExpenseApplicationResponse</returns>
public async System.Threading.Tasks.Task<ExpenseApplicationResponse> GetExpenseApplicationAsync(int id, int companyId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
Freee.Accounting.Client.ApiResponse<ExpenseApplicationResponse> localVarResponse = await GetExpenseApplicationWithHttpInfoAsync(id, companyId, cancellationToken).ConfigureAwait(false);
return localVarResponse.Data;
}
/// <summary>
/// 経費申請詳細の取得
/// </summary>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id">経費申請ID</param>
/// <param name="companyId">事業所ID</param>
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <returns>Task of ApiResponse (ExpenseApplicationResponse)</returns>
public async System.Threading.Tasks.Task<Freee.Accounting.Client.ApiResponse<ExpenseApplicationResponse>> GetExpenseApplicationWithHttpInfoAsync(int id, int companyId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
Freee.Accounting.Client.RequestOptions localVarRequestOptions = new Freee.Accounting.Client.RequestOptions();
String[] _contentTypes = new String[] {
};
// to determine the Accept header
String[] _accepts = new String[] {
"application/json"
};
var localVarContentType = Freee.Accounting.Client.ClientUtils.SelectHeaderContentType(_contentTypes);
if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType);
var localVarAccept = Freee.Accounting.Client.ClientUtils.SelectHeaderAccept(_accepts);
if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept);
localVarRequestOptions.PathParameters.Add("id", Freee.Accounting.Client.ClientUtils.ParameterToString(id)); // path parameter
localVarRequestOptions.QueryParameters.Add(Freee.Accounting.Client.ClientUtils.ParameterToMultiMap("", "company_id", companyId));
// authentication (oauth2) required
// oauth required
if (!String.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
// make the HTTP request
var localVarResponse = await this.AsynchronousClient.GetAsync<ExpenseApplicationResponse>("/api/1/expense_applications/{id}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false);
if (this.ExceptionFactory != null)
{
Exception _exception = this.ExceptionFactory("GetExpenseApplication", localVarResponse);
if (_exception != null) throw _exception;
}
return localVarResponse;
}
/// <summary>
/// 経費申請一覧の取得
/// </summary>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="companyId">事業所ID</param>
/// <param name="offset">取得レコードのオフセット (デフォルト: 0) (optional)</param>
/// <param name="limit">取得レコードの件数 (デフォルト: 50, 最小: 1, 最大: 500) (optional)</param>
/// <returns>ExpenseApplicationsIndexResponse</returns>
public ExpenseApplicationsIndexResponse GetExpenseApplications(int companyId, int? offset = default(int?), int? limit = default(int?))
{
Freee.Accounting.Client.ApiResponse<ExpenseApplicationsIndexResponse> localVarResponse = GetExpenseApplicationsWithHttpInfo(companyId, offset, limit);
return localVarResponse.Data;
}
/// <summary>
/// 経費申請一覧の取得
/// </summary>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="companyId">事業所ID</param>
/// <param name="offset">取得レコードのオフセット (デフォルト: 0) (optional)</param>
/// <param name="limit">取得レコードの件数 (デフォルト: 50, 最小: 1, 最大: 500) (optional)</param>
/// <returns>ApiResponse of ExpenseApplicationsIndexResponse</returns>
public Freee.Accounting.Client.ApiResponse<ExpenseApplicationsIndexResponse> GetExpenseApplicationsWithHttpInfo(int companyId, int? offset = default(int?), int? limit = default(int?))
{
Freee.Accounting.Client.RequestOptions localVarRequestOptions = new Freee.Accounting.Client.RequestOptions();
String[] _contentTypes = new String[] {
};
// to determine the Accept header
String[] _accepts = new String[] {
"application/json"
};
var localVarContentType = Freee.Accounting.Client.ClientUtils.SelectHeaderContentType(_contentTypes);
if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType);
var localVarAccept = Freee.Accounting.Client.ClientUtils.SelectHeaderAccept(_accepts);
if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept);
localVarRequestOptions.QueryParameters.Add(Freee.Accounting.Client.ClientUtils.ParameterToMultiMap("", "company_id", companyId));
if (offset != null)
{
localVarRequestOptions.QueryParameters.Add(Freee.Accounting.Client.ClientUtils.ParameterToMultiMap("", "offset", offset));
}
if (limit != null)
{
localVarRequestOptions.QueryParameters.Add(Freee.Accounting.Client.ClientUtils.ParameterToMultiMap("", "limit", limit));
}
// authentication (oauth2) required
// oauth required
if (!String.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
// make the HTTP request
var localVarResponse = this.Client.Get<ExpenseApplicationsIndexResponse>("/api/1/expense_applications", localVarRequestOptions, this.Configuration);
if (this.ExceptionFactory != null)
{
Exception _exception = this.ExceptionFactory("GetExpenseApplications", localVarResponse);
if (_exception != null) throw _exception;
}
return localVarResponse;
}
/// <summary>
/// 経費申請一覧の取得
/// </summary>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="companyId">事業所ID</param>
/// <param name="offset">取得レコードのオフセット (デフォルト: 0) (optional)</param>
/// <param name="limit">取得レコードの件数 (デフォルト: 50, 最小: 1, 最大: 500) (optional)</param>
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <returns>Task of ExpenseApplicationsIndexResponse</returns>
public async System.Threading.Tasks.Task<ExpenseApplicationsIndexResponse> GetExpenseApplicationsAsync(int companyId, int? offset = default(int?), int? limit = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
Freee.Accounting.Client.ApiResponse<ExpenseApplicationsIndexResponse> localVarResponse = await GetExpenseApplicationsWithHttpInfoAsync(companyId, offset, limit, cancellationToken).ConfigureAwait(false);
return localVarResponse.Data;
}
/// <summary>
/// 経費申請一覧の取得
/// </summary>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="companyId">事業所ID</param>
/// <param name="offset">取得レコードのオフセット (デフォルト: 0) (optional)</param>
/// <param name="limit">取得レコードの件数 (デフォルト: 50, 最小: 1, 最大: 500) (optional)</param>
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <returns>Task of ApiResponse (ExpenseApplicationsIndexResponse)</returns>
public async System.Threading.Tasks.Task<Freee.Accounting.Client.ApiResponse<ExpenseApplicationsIndexResponse>> GetExpenseApplicationsWithHttpInfoAsync(int companyId, int? offset = default(int?), int? limit = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
Freee.Accounting.Client.RequestOptions localVarRequestOptions = new Freee.Accounting.Client.RequestOptions();
String[] _contentTypes = new String[] {
};
// to determine the Accept header
String[] _accepts = new String[] {
"application/json"
};
var localVarContentType = Freee.Accounting.Client.ClientUtils.SelectHeaderContentType(_contentTypes);
if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType);
var localVarAccept = Freee.Accounting.Client.ClientUtils.SelectHeaderAccept(_accepts);
if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept);
localVarRequestOptions.QueryParameters.Add(Freee.Accounting.Client.ClientUtils.ParameterToMultiMap("", "company_id", companyId));
if (offset != null)
{
localVarRequestOptions.QueryParameters.Add(Freee.Accounting.Client.ClientUtils.ParameterToMultiMap("", "offset", offset));
}
if (limit != null)
{
localVarRequestOptions.QueryParameters.Add(Freee.Accounting.Client.ClientUtils.ParameterToMultiMap("", "limit", limit));
}
// authentication (oauth2) required
// oauth required
if (!String.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
// make the HTTP request
var localVarResponse = await this.AsynchronousClient.GetAsync<ExpenseApplicationsIndexResponse>("/api/1/expense_applications", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false);
if (this.ExceptionFactory != null)
{
Exception _exception = this.ExceptionFactory("GetExpenseApplications", localVarResponse);
if (_exception != null) throw _exception;
}
return localVarResponse;
}
/// <summary>
/// 経費申請の更新 <h2 id=\"\">概要</h2> <p>指定した事業所の経費申請を更新する</p> <h2 id=\"_2\">注意点</h2> <ul> <li>本APIでは、経費申請の下書きを更新することができます。申請作業はWebから行ってください。</li> <li>現在、申請経路はWeb上からのみ入力できます。Web上での申請時に指定してください。</li> <li>申請時には、申請タイトル(title)に加え、申請日(issue_date)、項目行については金額(amount)、日付(transaction_date)、内容(description)が必須項目となります。申請時の業務効率化のため、API入力をお勧めします。</li> <li>個人アカウントの場合は、プレミアムプランでご利用できます。</li> <li>法人アカウントの場合は、ベーシックプラン、プロフェッショナルプラン、エンタープライズプランでご利用できます。</li> </ul>
/// </summary>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id"></param>
/// <param name="expenseApplicationUpdateParams">経費申請の更新 (optional)</param>
/// <returns>ExpenseApplicationResponse</returns>
public ExpenseApplicationResponse UpdateExpenseApplication(int id, ExpenseApplicationUpdateParams expenseApplicationUpdateParams = default(ExpenseApplicationUpdateParams))
{
Freee.Accounting.Client.ApiResponse<ExpenseApplicationResponse> localVarResponse = UpdateExpenseApplicationWithHttpInfo(id, expenseApplicationUpdateParams);
return localVarResponse.Data;
}
/// <summary>
/// 経費申請の更新 <h2 id=\"\">概要</h2> <p>指定した事業所の経費申請を更新する</p> <h2 id=\"_2\">注意点</h2> <ul> <li>本APIでは、経費申請の下書きを更新することができます。申請作業はWebから行ってください。</li> <li>現在、申請経路はWeb上からのみ入力できます。Web上での申請時に指定してください。</li> <li>申請時には、申請タイトル(title)に加え、申請日(issue_date)、項目行については金額(amount)、日付(transaction_date)、内容(description)が必須項目となります。申請時の業務効率化のため、API入力をお勧めします。</li> <li>個人アカウントの場合は、プレミアムプランでご利用できます。</li> <li>法人アカウントの場合は、ベーシックプラン、プロフェッショナルプラン、エンタープライズプランでご利用できます。</li> </ul>
/// </summary>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id"></param>
/// <param name="expenseApplicationUpdateParams">経費申請の更新 (optional)</param>
/// <returns>ApiResponse of ExpenseApplicationResponse</returns>
public Freee.Accounting.Client.ApiResponse<ExpenseApplicationResponse> UpdateExpenseApplicationWithHttpInfo(int id, ExpenseApplicationUpdateParams expenseApplicationUpdateParams = default(ExpenseApplicationUpdateParams))
{
Freee.Accounting.Client.RequestOptions localVarRequestOptions = new Freee.Accounting.Client.RequestOptions();
String[] _contentTypes = new String[] {
"application/json",
"application/x-www-form-urlencoded"
};
// to determine the Accept header
String[] _accepts = new String[] {
"application/json"
};
var localVarContentType = Freee.Accounting.Client.ClientUtils.SelectHeaderContentType(_contentTypes);
if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType);
var localVarAccept = Freee.Accounting.Client.ClientUtils.SelectHeaderAccept(_accepts);
if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept);
localVarRequestOptions.PathParameters.Add("id", Freee.Accounting.Client.ClientUtils.ParameterToString(id)); // path parameter
localVarRequestOptions.Data = expenseApplicationUpdateParams;
// authentication (oauth2) required
// oauth required
if (!String.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
// make the HTTP request
var localVarResponse = this.Client.Put<ExpenseApplicationResponse>("/api/1/expense_applications/{id}", localVarRequestOptions, this.Configuration);
if (this.ExceptionFactory != null)
{
Exception _exception = this.ExceptionFactory("UpdateExpenseApplication", localVarResponse);
if (_exception != null) throw _exception;
}
return localVarResponse;
}
/// <summary>
/// 経費申請の更新 <h2 id=\"\">概要</h2> <p>指定した事業所の経費申請を更新する</p> <h2 id=\"_2\">注意点</h2> <ul> <li>本APIでは、経費申請の下書きを更新することができます。申請作業はWebから行ってください。</li> <li>現在、申請経路はWeb上からのみ入力できます。Web上での申請時に指定してください。</li> <li>申請時には、申請タイトル(title)に加え、申請日(issue_date)、項目行については金額(amount)、日付(transaction_date)、内容(description)が必須項目となります。申請時の業務効率化のため、API入力をお勧めします。</li> <li>個人アカウントの場合は、プレミアムプランでご利用できます。</li> <li>法人アカウントの場合は、ベーシックプラン、プロフェッショナルプラン、エンタープライズプランでご利用できます。</li> </ul>
/// </summary>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id"></param>
/// <param name="expenseApplicationUpdateParams">経費申請の更新 (optional)</param>
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <returns>Task of ExpenseApplicationResponse</returns>
public async System.Threading.Tasks.Task<ExpenseApplicationResponse> UpdateExpenseApplicationAsync(int id, ExpenseApplicationUpdateParams expenseApplicationUpdateParams = default(ExpenseApplicationUpdateParams), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
Freee.Accounting.Client.ApiResponse<ExpenseApplicationResponse> localVarResponse = await UpdateExpenseApplicationWithHttpInfoAsync(id, expenseApplicationUpdateParams, cancellationToken).ConfigureAwait(false);
return localVarResponse.Data;
}
/// <summary>
/// 経費申請の更新 <h2 id=\"\">概要</h2> <p>指定した事業所の経費申請を更新する</p> <h2 id=\"_2\">注意点</h2> <ul> <li>本APIでは、経費申請の下書きを更新することができます。申請作業はWebから行ってください。</li> <li>現在、申請経路はWeb上からのみ入力できます。Web上での申請時に指定してください。</li> <li>申請時には、申請タイトル(title)に加え、申請日(issue_date)、項目行については金額(amount)、日付(transaction_date)、内容(description)が必須項目となります。申請時の業務効率化のため、API入力をお勧めします。</li> <li>個人アカウントの場合は、プレミアムプランでご利用できます。</li> <li>法人アカウントの場合は、ベーシックプラン、プロフェッショナルプラン、エンタープライズプランでご利用できます。</li> </ul>
/// </summary>
/// <exception cref="Freee.Accounting.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="id"></param>
/// <param name="expenseApplicationUpdateParams">経費申請の更新 (optional)</param>
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <returns>Task of ApiResponse (ExpenseApplicationResponse)</returns>
public async System.Threading.Tasks.Task<Freee.Accounting.Client.ApiResponse<ExpenseApplicationResponse>> UpdateExpenseApplicationWithHttpInfoAsync(int id, ExpenseApplicationUpdateParams expenseApplicationUpdateParams = default(ExpenseApplicationUpdateParams), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
Freee.Accounting.Client.RequestOptions localVarRequestOptions = new Freee.Accounting.Client.RequestOptions();
String[] _contentTypes = new String[] {
"application/json",
"application/x-www-form-urlencoded"
};
// to determine the Accept header
String[] _accepts = new String[] {
"application/json"
};
var localVarContentType = Freee.Accounting.Client.ClientUtils.SelectHeaderContentType(_contentTypes);
if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType);
var localVarAccept = Freee.Accounting.Client.ClientUtils.SelectHeaderAccept(_accepts);
if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept);
localVarRequestOptions.PathParameters.Add("id", Freee.Accounting.Client.ClientUtils.ParameterToString(id)); // path parameter
localVarRequestOptions.Data = expenseApplicationUpdateParams;
// authentication (oauth2) required
// oauth required
if (!String.IsNullOrEmpty(this.Configuration.AccessToken))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
// make the HTTP request
var localVarResponse = await this.AsynchronousClient.PutAsync<ExpenseApplicationResponse>("/api/1/expense_applications/{id}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false);
if (this.ExceptionFactory != null)
{
Exception _exception = this.ExceptionFactory("UpdateExpenseApplication", localVarResponse);
if (_exception != null) throw _exception;
}
return localVarResponse;
}
}
}
| 67.138862 | 4,141 | 0.674763 | [
"MIT"
] | zawazawazawazawa/freee-accounting-sdk-csharp | src/Freee.Accounting/Api/ExpenseApplicationsApi.cs | 83,267 | C# |
/*
Written in 2013-2019 by Peter O.
Parts of the code were adapted by Peter O. from
public-domain code by Wei Dai.
Parts of the GCD function adapted by Peter O.
from public domain GCD code by Christian
Stigen Larsen (http://csl.sublevel3.org).
Any copyright to this work is released to the Public Domain.
In case this is not possible, this work is also
licensed under Creative Commons Zero (CC0):
https://creativecommons.org/publicdomain/zero/1.0/
*/
using System;
using System.Text;
// TODO: In next major version, perhaps change GetSigned/UnsignedBitLength
// to return MaxValue on overflow
// TODO: In next major version, perhaps change GetLowBit/GetDigitCount
// to return MaxValue on overflow
// TODO: Perhaps add overload to FromBytes to take a sign and magnitude
namespace PeterO.Numbers {
/// <summary>Represents an arbitrary-precision integer. (The "E" stands
/// for "extended", and has this prefix to group it with the other
/// classes common to this library, particularly EDecimal, EFloat, and
/// ERational.)
/// <para>Instances of this class are immutable, so they are inherently
/// safe for use by multiple threads. Multiple instances of this object
/// with the same value are interchangeable, but they should be
/// compared using the "Equals" method rather than the "=="
/// operator.</para>
/// <para><b>Security note</b></para>
/// <para>It is not recommended to implement security-sensitive
/// algorithms using the methods in this class, for several
/// reasons:</para>
/// <list>
/// <item><c>EInteger</c> objects are immutable, so they can't be
/// modified, and the memory they occupy is not guaranteed to be
/// cleared in a timely fashion due to garbage collection. This is
/// relevant for applications that use many-bit-long numbers as secret
/// parameters.</item>
/// <item>The methods in this class (especially those that involve
/// arithmetic) are not guaranteed to be "constant-time"
/// (non-data-dependent) for all relevant inputs. Certain attacks that
/// involve encrypted communications have exploited the timing and
/// other aspects of such communications to derive keying material or
/// cleartext indirectly.</item></list>
/// <para>Applications should instead use dedicated security libraries
/// to handle big numbers in security-sensitive
/// algorithms.</para></summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage(
"Microsoft.Design",
"CA1036",
Justification = "Awaiting advice at dotnet/dotnet-api-docs#2937.")]
public sealed partial class EInteger : IComparable<EInteger>,
IEquatable<EInteger> {
private const string Digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private const int Toom3Threshold = 100;
private const int Toom4Threshold = 400;
private const int MultRecursionThreshold = 10;
private const int RecursiveDivisionLimit = (Toom3Threshold * 2) + 1;
private const int CacheFirst = -24;
private const int CacheLast = 128;
private const int ShortMask = 0xffff;
internal static readonly int[] CharToDigit = {
36, 36, 36, 36, 36, 36,
36,
36,
36, 36, 36, 36, 36, 36, 36, 36,
36, 36, 36, 36, 36, 36, 36, 36,
36, 36, 36, 36, 36, 36, 36, 36,
36, 36, 36, 36, 36, 36, 36, 36,
36, 36, 36, 36, 36, 36, 36, 36,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 36, 36, 36, 36, 36, 36,
36, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 36, 36, 36, 36,
36, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 36, 36, 36, 36,
};
internal static readonly int[] MaxSafeInts = {
1073741823, 715827881,
536870911, 429496728, 357913940, 306783377, 268435455, 238609293,
214748363, 195225785, 178956969, 165191048, 153391688, 143165575,
134217727, 126322566, 119304646, 113025454, 107374181, 102261125,
97612892, 93368853, 89478484, 85899344, 82595523, 79536430, 76695843,
74051159, 71582787, 69273665, 67108863, 65075261, 63161282, 61356674,
59652322,
};
private static readonly EInteger ValueOne = new EInteger(
1, new short[] { 1 }, false);
private static readonly EInteger ValueTen = new EInteger(
1, new short[] { 10 }, false);
private static readonly EInteger ValueZero = new EInteger(
0, new short[] { 0 }, false);
private readonly bool negative;
private readonly int wordCount;
private readonly short[] words;
private static readonly EInteger[] Cache = EIntegerCache(CacheFirst,
CacheLast);
private static EInteger[] EIntegerCache(int first, int last) {
#if DEBUG
if (first < -65535) {
throw new ArgumentException("first (" + first + ") is not greater" +
"\u0020or equal" + "\u0020to " + (-65535));
}
if (first > 65535) {
throw new ArgumentException("first (" + first + ") is not less or" +
"\u0020equal to" + "\u002065535");
}
if (last < -65535) {
throw new ArgumentException("last (" + last + ") is not greater or" +
"\u0020equal" + "\u0020to " + (-65535));
}
if (last > 65535) {
throw new ArgumentException("last (" + last + ") is not less or" +
"\u0020equal to" + "65535");
}
#endif
var i = 0;
var cache = new EInteger[(last - first) + 1];
for (i = first; i <= last; ++i) {
if (i == 0) {
cache[i - first] = ValueZero;
} else if (i == 1) {
cache[i - first] = ValueOne;
} else if (i == 10) {
cache[i - first] = ValueTen;
} else {
int iabs = Math.Abs(i);
var words = new short[] {
unchecked((short)iabs),
};
cache[i - first] = new EInteger(1, words, i < 0);
}
}
return cache;
}
internal EInteger(int wordCount, short[] reg, bool negative) {
#if DEBUG
if (wordCount > 0) {
if (reg == null) {
throw new InvalidOperationException();
}
if (wordCount > reg.Length) {
throw new InvalidOperationException();
}
if (reg[wordCount - 1] == 0) {
throw new InvalidOperationException();
}
}
#endif
this.wordCount = wordCount;
this.words = reg;
this.negative = negative;
}
/// <summary>Gets the number 1 as an arbitrary-precision
/// integer.</summary>
/// <value>The number 1 as an arbitrary-precision integer.</value>
public static EInteger One {
get {
return ValueOne;
}
}
/// <summary>Gets the number 10 as an arbitrary-precision
/// integer.</summary>
/// <value>The number 10 as an arbitrary-precision integer.</value>
public static EInteger Ten {
get {
return ValueTen;
}
}
/// <summary>Gets the number zero as an arbitrary-precision
/// integer.</summary>
/// <value>The number zero as an arbitrary-precision integer.</value>
public static EInteger Zero {
get {
return ValueZero;
}
}
/// <summary>Gets a value indicating whether this value is
/// even.</summary>
/// <value><c>true</c> if this value is even; otherwise, <c>false</c>.</value>
public bool IsEven {
get {
return !this.GetUnsignedBit(0);
}
}
/// <summary>Gets a value indicating whether this object's value is a
/// power of two, and greater than 0.</summary>
/// <value><c>true</c> if this object's value is a power of two, and
/// greater than 0; otherwise, <c>false</c>.</value>
public bool IsPowerOfTwo {
get {
int wc = this.wordCount;
if (this.negative || wc == 0 ||
(wc > 1 && this.words[0] != 0)) {
return false;
}
for (var i = 0; i < wc - 1; ++i) {
if (this.words[i] != 0) {
return false;
}
}
int lastw = ((int)this.words[wc - 1]) & 0xffff;
if (lastw == 0) {
throw new InvalidOperationException();
}
while ((lastw & 1) == 0) {
lastw >>= 1;
}
return lastw == 1;
}
}
/// <summary>Gets a value indicating whether this value is 0.</summary>
/// <value><c>true</c> if this value is 0; otherwise, <c>false</c>.</value>
public bool IsZero {
get {
return this.wordCount == 0;
}
}
/// <summary>Gets the sign of this object's value.</summary>
/// <value>The sign of this object's value.</value>
public int Sign {
get {
return (this.wordCount == 0) ? 0 : (this.negative ? -1 : 1);
}
}
internal static EInteger FromInts(int[] intWords, int count) {
var words = new short[count << 1];
var j = 0;
for (var i = 0; i < count; ++i, j += 2) {
int w = intWords[i];
words[j] = unchecked((short)w);
words[j + 1] = unchecked((short)(w >> 16));
}
int newwordCount = words.Length;
while (newwordCount != 0 && words[newwordCount - 1] == 0) {
--newwordCount;
}
return (newwordCount == 0) ? EInteger.Zero :
new EInteger(newwordCount, words, false);
}
/// <summary>Initializes an arbitrary-precision integer from an array
/// of bytes.</summary>
/// <param name='bytes'>A byte array consisting of the two's-complement
/// form (see
/// <see cref='PeterO.Numbers.EDecimal'>"Forms of numbers"</see> ) of
/// the arbitrary-precision integer to create. The byte array is
/// encoded using the rules given in the FromBytes(bytes, offset,
/// length, littleEndian) overload.</param>
/// <param name='littleEndian'>If true, the byte order is
/// little-endian, or least-significant-byte first. If false, the byte
/// order is big-endian, or most-significant-byte first.</param>
/// <returns>An arbitrary-precision integer. Returns 0 if the byte
/// array's length is 0.</returns>
/// <exception cref='ArgumentNullException'>The parameter <paramref
/// name='bytes'/> is null.</exception>
public static EInteger FromBytes(byte[] bytes, bool littleEndian) {
if (bytes == null) {
throw new ArgumentNullException(nameof(bytes));
}
return FromBytes(bytes, 0, bytes.Length, littleEndian);
}
/// <summary>Initializes an arbitrary-precision integer from a portion
/// of an array of bytes. The portion of the byte array is encoded
/// using the following rules:
/// <list>
/// <item>Positive numbers have the first byte's highest bit cleared,
/// and negative numbers have the bit set.</item>
/// <item>The last byte contains the lowest 8-bits, the next-to-last
/// contains the next lowest 8 bits, and so on. For example, the number
/// 300 can be encoded as <c>0x01, 0x2C</c> and 200 as <c>0x00,
/// 0xC8</c>. (Note that the second example contains a set high bit in
/// <c>0xC8</c>, so an additional 0 is added at the start to ensure
/// it's interpreted as positive.)</item>
/// <item>To encode negative numbers, take the absolute value of the
/// number, subtract by 1, encode the number into bytes, and toggle
/// each bit of each byte. Any further bits that appear beyond the most
/// significant bit of the number will be all ones. For example, the
/// number -450 can be encoded as <c>0xfe, 0x70</c> and -52869 as
/// <c>0xff, 0x31, 0x7B</c>. (Note that the second example contains a
/// cleared high bit in <c>0x31, 0x7B</c>, so an additional 0xff is
/// added at the start to ensure it's interpreted as
/// negative.)</item></list>
/// <para>For little-endian, the byte order is reversed from the byte
/// order just discussed.</para></summary>
/// <param name='bytes'>A byte array consisting of the two's-complement
/// form (see
/// <see cref='PeterO.Numbers.EDecimal'>"Forms of numbers"</see> ) of
/// the arbitrary-precision integer to create. The byte array is
/// encoded using the rules given in the FromBytes(bytes, offset,
/// length, littleEndian) overload.</param>
/// <param name='offset'>An index starting at 0 showing where the
/// desired portion of <paramref name='bytes'/> begins.</param>
/// <param name='length'>The length, in bytes, of the desired portion
/// of <paramref name='bytes'/> (but not more than <paramref
/// name='bytes'/> 's length).</param>
/// <param name='littleEndian'>If true, the byte order is
/// little-endian, or least-significant-byte first. If false, the byte
/// order is big-endian, or most-significant-byte first.</param>
/// <returns>An arbitrary-precision integer. Returns 0 if the byte
/// array's length is 0.</returns>
/// <exception cref='ArgumentNullException'>The parameter <paramref
/// name='bytes'/> is null.</exception>
/// <exception cref='ArgumentException'>Either <paramref
/// name='offset'/> or <paramref name='length'/> is less than 0 or
/// greater than <paramref name='bytes'/> 's length, or <paramref
/// name='bytes'/> 's length minus <paramref name='offset'/> is less
/// than <paramref name='length'/>.</exception>
public static EInteger FromBytes(
byte[] bytes,
int offset,
int length,
bool littleEndian) {
if (bytes == null) {
throw new ArgumentNullException(nameof(bytes));
}
if (offset < 0) {
throw new ArgumentException("offset (" + offset + ") is not greater" +
"\u0020or equal to 0");
}
if (offset > bytes.Length) {
throw new ArgumentException("offset (" + offset + ") is not less or" +
"\u0020equal to " + bytes.Length);
}
if (length < 0) {
throw new ArgumentException("length (" + length + ") is not " +
"greater or equal to 0");
}
if (length > bytes.Length) {
throw new ArgumentException("length (" + length + ") is not less or" +
"\u0020equal to " + bytes.Length);
}
if (bytes.Length - offset < length) {
throw new ArgumentException("bytes's length minus " + offset + " (" +
(bytes.Length - offset) + ") is not greater or equal to " + length);
}
if (length == 0) {
return EInteger.Zero;
} else if (length == 1) {
return (((int)bytes[offset] & 0x80) == 0) ?
FromInt32((int)bytes[offset]) :
FromInt32(-1 - ((~bytes[offset]) & 0x7f));
}
int len = length;
int wordLength = (len >> 1) + (len & 1);
var newreg = new short[wordLength];
int valueJIndex = littleEndian ? len - 1 : 0;
var numIsNegative = false;
bool odd = (len & 1) != 0;
int evenedLen = odd ? len - 1 : len;
var j = 0;
if (littleEndian) {
for (var i = 0; i < evenedLen; i += 2, j++) {
int index2 = i + 1;
int nrj = ((int)bytes[offset + i]) & 0xff;
nrj |= ((int)bytes[offset + i + 1]) << 8;
newreg[j] = unchecked((short)nrj);
}
if (odd) {
newreg[evenedLen >> 1] =
unchecked((short)(((int)bytes[offset + evenedLen]) & 0xff));
}
numIsNegative = (bytes[offset + len - 1] & 0x80) != 0;
} else {
for (var i = 0; i < evenedLen; i += 2, j++) {
int index = len - 1 - i;
int index2 = len - 2 - i;
int nrj = ((int)bytes[offset + index]) & 0xff;
nrj |= ((int)bytes[offset + index2]) << 8;
newreg[j] = unchecked((short)nrj);
}
if (odd) {
newreg[evenedLen >> 1] = unchecked((short)(((int)bytes[offset]) &
0xff));
}
numIsNegative = (bytes[offset] & 0x80) != 0;
}
if (numIsNegative) {
// Sign extension and two's-complement
if (odd) {
newreg[len >> 1] |= unchecked((short)0xff00);
}
j = (len >> 1) + 1;
for (; j < newreg.Length; ++j) {
newreg[j] = unchecked((short)0xffff); // sign extend remaining words
}
TwosComplement(newreg, 0, (int)newreg.Length);
}
int newwordCount = newreg.Length;
while (newwordCount != 0 && newreg[newwordCount - 1] == 0) {
--newwordCount;
}
return (newwordCount == 0) ? EInteger.Zero :
new EInteger(newwordCount, newreg, numIsNegative);
}
/// <summary>Converts a boolean value (true or false) to an
/// arbitrary-precision integer.</summary>
/// <param name='boolValue'>Either true or false.</param>
/// <returns>The number 1 if <paramref name='boolValue'/> is true;
/// otherwise, 0.</returns>
public static EInteger FromBoolean(bool boolValue) {
return boolValue ? ValueOne : ValueZero;
}
/// <summary>Converts a 32-bit signed integer to an arbitrary-precision
/// integer.</summary>
/// <param name='intValue'>The parameter <paramref name='intValue'/> is
/// a 32-bit signed integer.</param>
/// <returns>An arbitrary-precision integer with the same value as the
/// 64-bit number.</returns>
public static EInteger FromInt32(int intValue) {
if (intValue >= CacheFirst && intValue <= CacheLast) {
return Cache[intValue - CacheFirst];
}
short[] retreg;
bool retnegative;
int retwordcount;
retnegative = intValue < 0;
if ((intValue >> 15) == 0) {
retreg = new short[2];
if (retnegative) {
intValue = -intValue;
}
retreg[0] = (short)(intValue & ShortMask);
retwordcount = 1;
} else if (intValue == Int32.MinValue) {
retreg = new short[2];
retreg[0] = 0;
retreg[1] = unchecked((short)0x8000);
retwordcount = 2;
} else {
unchecked {
retreg = new short[2];
if (retnegative) {
intValue = -intValue;
}
retreg[0] = (short)(intValue & ShortMask);
intValue >>= 16;
retreg[1] = (short)(intValue & ShortMask);
retwordcount = (retreg[1] == 0) ? 1 : 2;
}
}
return new EInteger(retwordcount, retreg, retnegative);
}
/// <summary>Converts an unsigned integer expressed as a 64-bit signed
/// integer to an arbitrary-precision integer.</summary>
/// <param name='longerValue'>A 64-bit signed integer. If this value is
/// 0 or greater, the return value will represent it. If this value is
/// less than 0, the return value will store 2^64 plus this value
/// instead.</param>
/// <returns>An arbitrary-precision integer. If <paramref
/// name='longerValue'/> is 0 or greater, the return value will
/// represent it. If <paramref name='longerValue'/> is less than 0, the
/// return value will store 2^64 plus this value instead.</returns>
public static EInteger FromInt64AsUnsigned(long longerValue) {
if (longerValue >= 0) {
return EInteger.FromInt64(longerValue);
} else {
return EInteger.FromInt32(1).ShiftLeft(64).Add(longerValue);
}
}
/// <summary>Converts a 64-bit signed integer to an arbitrary-precision
/// integer.</summary>
/// <param name='longerValue'>The parameter <paramref
/// name='longerValue'/> is a 64-bit signed integer.</param>
/// <returns>An arbitrary-precision integer with the same value as the
/// 64-bit number.</returns>
public static EInteger FromInt64(long longerValue) {
if (longerValue >= CacheFirst && longerValue <= CacheLast) {
return Cache[(int)(longerValue - CacheFirst)];
}
short[] retreg;
bool retnegative;
int retwordcount;
unchecked {
retnegative = longerValue < 0;
if ((longerValue >> 16) == 0) {
retreg = new short[1];
var intValue = (int)longerValue;
if (retnegative) {
intValue = -intValue;
}
retreg[0] = (short)(intValue & ShortMask);
retwordcount = 1;
} else if ((longerValue >> 31) == 0) {
retreg = new short[2];
var intValue = (int)longerValue;
if (retnegative) {
intValue = -intValue;
}
retreg[0] = (short)(intValue & ShortMask);
retreg[1] = (short)((intValue >> 16) & ShortMask);
retwordcount = 2;
} else if (longerValue == Int64.MinValue) {
retreg = new short[4];
retreg[0] = 0;
retreg[1] = 0;
retreg[2] = 0;
retreg[3] = unchecked((short)0x8000);
retwordcount = 4;
} else {
retreg = new short[4];
long ut = longerValue;
if (retnegative) {
ut = -ut;
}
retreg[0] = (short)(ut & ShortMask);
ut >>= 16;
retreg[1] = (short)(ut & ShortMask);
ut >>= 16;
retreg[2] = (short)(ut & ShortMask);
ut >>= 16;
retreg[3] = (short)(ut & ShortMask);
// at this point, the word count can't
// be 0 (the check for 0 was already done above)
retwordcount = 4;
while (retwordcount != 0 &&
retreg[retwordcount - 1] == 0) {
--retwordcount;
}
}
}
return new EInteger(retwordcount, retreg, retnegative);
}
// Approximate number of digits, multiplied by 100, that fit in
// each 16-bit word of an EInteger. This is used to calculate
// an upper bound on the EInteger's word array size based on
// the radix and the number of digits. Calculated from:
// ceil(ln(65536)*100/ln(radix)).
internal static readonly int[] DigitsInWord = {
0, 0,
1600, 1010, 800, 690, 619, 570, 534, 505, 482, 463, 447,
433, 421, 410, 400, 392, 384, 377, 371, 365, 359, 354,
349, 345, 341, 337, 333, 330, 327, 323, 320, 318, 315,
312, 310, 308,
};
/// <summary>Converts a string to an arbitrary-precision integer in a
/// given radix.</summary>
/// <param name='str'>A string described by the FromRadixSubstring
/// method.</param>
/// <param name='radix'>A base from 2 to 36. Depending on the radix,
/// the string can use the basic digits 0 to 9 (U+0030 to U+0039) and
/// then the basic upper-case letters A to Z (U+0041 to U+005A). For
/// example, 0-9 in radix 10, and 0-9, then A-F in radix 16. Where a
/// basic upper-case letter A to Z is allowed in the string, the
/// corresponding basic lower-case letter (U+0061 to U+007a) is allowed
/// instead.</param>
/// <returns>An arbitrary-precision integer with the same value as the
/// given string.</returns>
/// <exception cref='ArgumentNullException'>The parameter <paramref
/// name='str'/> is null.</exception>
/// <exception cref='FormatException'>The string is empty or in an
/// invalid format.</exception>
public static EInteger FromRadixString(string str, int radix) {
if (str == null) {
throw new ArgumentNullException(nameof(str));
}
return FromRadixSubstring(str, radix, 0, str.Length);
}
/// <summary>Converts a portion of a string to an arbitrary-precision
/// integer in a given radix.</summary>
/// <param name='str'>A text string. The desired portion of the string
/// must contain only characters allowed by the given radix, except
/// that it may start with a minus sign ("-", U+002D) to indicate a
/// negative number. The desired portion is not allowed to contain
/// white space characters, including spaces. The desired portion may
/// start with any number of zeros.</param>
/// <param name='radix'>A base from 2 to 36. Depending on the radix,
/// the string can use the basic digits 0 to 9 (U+0030 to U+0039) and
/// then the basic upper-case letters A to Z (U+0041 to U+005A). For
/// example, 0-9 in radix 10, and 0-9, then A-F in radix 16. Where a
/// basic upper-case letter A to Z is allowed in the string, the
/// corresponding basic lower-case letter (U+0061 to U+007a) is allowed
/// instead.</param>
/// <param name='index'>The index of the string that starts the string
/// portion.</param>
/// <param name='endIndex'>The index of the string that ends the string
/// portion. The length will be index + endIndex - 1.</param>
/// <returns>An arbitrary-precision integer with the same value as
/// given in the string portion.</returns>
/// <exception cref='ArgumentNullException'>The parameter <paramref
/// name='str'/> is null.</exception>
/// <exception cref='FormatException'>The string portion is empty or in
/// an invalid format.</exception>
public static EInteger FromRadixSubstring(
string str,
int radix,
int index,
int endIndex) {
if (str == null) {
throw new ArgumentNullException(nameof(str));
}
return EIntegerTextString.FromRadixSubstringImpl(
str,
radix,
index,
endIndex,
true);
}
/// <summary>Converts a portion of a sequence of <c>char</c> s to an
/// arbitrary-precision integer.</summary>
/// <param name='cs'>A sequence of <c>char</c> s, the desired portion
/// of which describes an integer in base-10 (decimal) form. The
/// desired portion of the sequence of <c>char</c> s must contain only
/// basic digits 0 to 9 (U+0030 to U+0039), except that it may start
/// with a minus sign ("-", U+002D) to indicate a negative number. The
/// desired portion is not allowed to contain white space characters,
/// including spaces. The desired portion may start with any number of
/// zeros.</param>
/// <param name='index'>The index of the sequence of <c>char</c> s that
/// starts the desired portion.</param>
/// <param name='endIndex'>The index of the sequence of <c>char</c> s
/// that ends the desired portion. The length will be index + endIndex
/// - 1.</param>
/// <returns>An arbitrary-precision integer with the same value as
/// given in the sequence of <c>char</c> s portion.</returns>
/// <exception cref='ArgumentException'>The parameter <paramref
/// name='index'/> is less than 0, <paramref name='endIndex'/> is less
/// than 0, or either is greater than the sequence's length, or
/// <paramref name='endIndex'/> is less than <paramref
/// name='index'/>.</exception>
/// <exception cref='ArgumentNullException'>The parameter <paramref
/// name='cs'/> is null.</exception>
public static EInteger FromSubstring(
char[] cs,
int index,
int endIndex) {
if (cs == null) {
throw new ArgumentNullException(nameof(cs));
}
return FromRadixSubstring(cs, 10, index, endIndex);
}
/// <summary>Converts a sequence of <c>char</c> s to an
/// arbitrary-precision integer.</summary>
/// <param name='cs'>A sequence of <c>char</c> s describing an integer
/// in base-10 (decimal) form. The sequence must contain only basic
/// digits 0 to 9 (U+0030 to U+0039), except that it may start with a
/// minus sign ("-", U+002D) to indicate a negative number. The
/// sequence is not allowed to contain white space characters,
/// including spaces. The sequence may start with any number of
/// zeros.</param>
/// <returns>An arbitrary-precision integer with the same value as
/// given in the sequence of <c>char</c> s.</returns>
/// <exception cref='FormatException'>The parameter <paramref
/// name='cs'/> is in an invalid format.</exception>
/// <exception cref='ArgumentNullException'>The parameter <paramref
/// name='cs'/> is null.</exception>
public static EInteger FromString(char[] cs) {
if (cs == null) {
throw new ArgumentNullException(nameof(cs));
}
int len = cs.Length;
if (len == 1) {
char c = cs[0];
if (c >= '0' && c <= '9') {
return FromInt32((int)(c - '0'));
}
throw new FormatException();
}
return FromRadixSubstring(cs, 10, 0, len);
}
/// <summary>Converts a sequence of <c>char</c> s to an
/// arbitrary-precision integer in a given radix.</summary>
/// <param name='cs'>A sequence of <c>char</c> s described by the
/// FromRadixSubstring method.</param>
/// <param name='radix'>A base from 2 to 36. Depending on the radix,
/// the sequence of <c>char</c> s can use the basic digits 0 to 9
/// (U+0030 to U+0039) and then the basic upper-case letters A to Z
/// (U+0041 to U+005A). For example, 0-9 in radix 10, and 0-9, then A-F
/// in radix 16. Where a basic upper-case letter A to Z is allowed in
/// the sequence of <c>char</c> s, the corresponding basic lower-case
/// letter (U+0061 to U+007a) is allowed instead.</param>
/// <returns>An arbitrary-precision integer with the same value as the
/// given sequence of <c>char</c> s.</returns>
/// <exception cref='ArgumentNullException'>The parameter <paramref
/// name='cs'/> is null.</exception>
/// <exception cref='FormatException'>The sequence of <c>char</c> s is
/// empty or in an invalid format.</exception>
public static EInteger FromRadixString(char[] cs, int radix) {
if (cs == null) {
throw new ArgumentNullException(nameof(cs));
}
return FromRadixSubstring(cs, radix, 0, cs.Length);
}
/// <summary>Converts a portion of a sequence of <c>char</c> s to an
/// arbitrary-precision integer in a given radix.</summary>
/// <param name='cs'>A text sequence of <c>char</c> s. The desired
/// portion of the sequence of <c>char</c> s must contain only
/// characters allowed by the given radix, except that it may start
/// with a minus sign ("-", U+002D) to indicate a negative number. The
/// desired portion is not allowed to contain white space characters,
/// including spaces. The desired portion may start with any number of
/// zeros.</param>
/// <param name='radix'>A base from 2 to 36. Depending on the radix,
/// the sequence of <c>char</c> s can use the basic digits 0 to 9
/// (U+0030 to U+0039) and then the basic upper-case letters A to Z
/// (U+0041 to U+005A). For example, 0-9 in radix 10, and 0-9, then A-F
/// in radix 16. Where a basic upper-case letter A to Z is allowed in
/// the sequence of <c>char</c> s, the corresponding basic lower-case
/// letter (U+0061 to U+007a) is allowed instead.</param>
/// <param name='index'>The index of the sequence of <c>char</c> s that
/// starts the desired portion.</param>
/// <param name='endIndex'>The index of the sequence of <c>char</c> s
/// that ends the desired portion. The length will be index + endIndex
/// - 1.</param>
/// <returns>An arbitrary-precision integer with the same value as
/// given in the sequence's portion.</returns>
/// <exception cref='ArgumentNullException'>The parameter <paramref
/// name='cs'/> is null.</exception>
/// <exception cref='FormatException'>The portion is empty or in an
/// invalid format.</exception>
public static EInteger FromRadixSubstring(
char[] cs,
int radix,
int index,
int endIndex) {
if (cs == null) {
throw new ArgumentNullException(nameof(cs));
}
return EIntegerCharArrayString.FromRadixSubstringImpl(
cs,
radix,
index,
endIndex,
true);
}
/// <summary>Converts a portion of a sequence of bytes (interpreted as
/// text) to an arbitrary-precision integer. Each byte in the sequence
/// has to be a character in the Basic Latin range (0x00 to 0x7f or
/// U+0000 to U+007F) of the Unicode Standard.</summary>
/// <param name='bytes'>A sequence of bytes (interpreted as text), the
/// desired portion of which describes an integer in base-10 (decimal)
/// form. The desired portion of the sequence of bytes (interpreted as
/// text) must contain only basic digits 0 to 9 (U+0030 to U+0039),
/// except that it may start with a minus sign ("-", U+002D) to
/// indicate a negative number. The desired portion is not allowed to
/// contain white space characters, including spaces. The desired
/// portion may start with any number of zeros.</param>
/// <param name='index'>The index of the sequence of bytes (interpreted
/// as text) that starts the desired portion.</param>
/// <param name='endIndex'>The index of the sequence of bytes
/// (interpreted as text) that ends the desired portion. The length
/// will be index + endIndex - 1.</param>
/// <returns>An arbitrary-precision integer with the same value as
/// given in the sequence of bytes (interpreted as text)
/// portion.</returns>
/// <exception cref='ArgumentException'>The parameter <paramref
/// name='index'/> is less than 0, <paramref name='endIndex'/> is less
/// than 0, or either is greater than the sequence's length, or
/// <paramref name='endIndex'/> is less than <paramref
/// name='index'/>.</exception>
/// <exception cref='ArgumentNullException'>The parameter <paramref
/// name='bytes'/> is null.</exception>
public static EInteger FromSubstring(
byte[] bytes,
int index,
int endIndex) {
if (bytes == null) {
throw new ArgumentNullException(nameof(bytes));
}
return FromRadixSubstring(bytes, 10, index, endIndex);
}
/// <summary>Converts a sequence of bytes (interpreted as text) to an
/// arbitrary-precision integer. Each byte in the sequence has to be a
/// code point in the Basic Latin range (0x00 to 0x7f or U+0000 to
/// U+007F) of the Unicode Standard.</summary>
/// <param name='bytes'>A sequence of bytes describing an integer in
/// base-10 (decimal) form. The sequence must contain only basic digits
/// 0 to 9 (U+0030 to U+0039), except that it may start with a minus
/// sign ("-", U+002D) to indicate a negative number. The sequence is
/// not allowed to contain white space characters, including spaces.
/// The sequence may start with any number of zeros.</param>
/// <returns>An arbitrary-precision integer with the same value as
/// given in the sequence of bytes.</returns>
/// <exception cref='FormatException'>The parameter <paramref
/// name='bytes'/> is in an invalid format.</exception>
/// <exception cref='ArgumentNullException'>The parameter <paramref
/// name='bytes'/> is null.</exception>
public static EInteger FromString(byte[] bytes) {
if (bytes == null) {
throw new ArgumentNullException(nameof(bytes));
}
int len = bytes.Length;
if (len == 1) {
byte c = bytes[0];
if (c >= '0' && c <= '9') {
return FromInt32((int)(c - '0'));
}
throw new FormatException();
}
return FromRadixSubstring(bytes, 10, 0, len);
}
/// <summary>Converts a sequence of bytes (interpreted as text) to an
/// arbitrary-precision integer in a given radix. Each byte in the
/// sequence has to be a character in the Basic Latin range (0x00 to
/// 0x7f or U+0000 to U+007F) of the Unicode Standard.</summary>
/// <param name='bytes'>A sequence of bytes (interpreted as text)
/// described by the FromRadixSubstring method.</param>
/// <param name='radix'>A base from 2 to 36. Depending on the radix,
/// the sequence of bytes can use the basic digits 0 to 9 (U+0030 to
/// U+0039) and then the basic upper-case letters A to Z (U+0041 to
/// U+005A). For example, 0-9 in radix 10, and 0-9, then A-F in radix
/// 16. Where a basic upper-case letter A to Z is allowed in the
/// sequence of bytes, the corresponding basic lower-case letter
/// (U+0061 to U+007a) is allowed instead.</param>
/// <returns>An arbitrary-precision integer with the same value as the
/// given sequence of bytes.</returns>
/// <exception cref='ArgumentNullException'>The parameter <paramref
/// name='bytes'/> is null.</exception>
/// <exception cref='FormatException'>The sequence of bytes
/// (interpreted as text) is empty or in an invalid format.</exception>
public static EInteger FromRadixString(byte[] bytes, int radix) {
if (bytes == null) {
throw new ArgumentNullException(nameof(bytes));
}
return FromRadixSubstring(bytes, radix, 0, bytes.Length);
}
/// <summary>Converts a portion of a sequence of bytes (interpreted as
/// text) to an arbitrary-precision integer in a given radix. Each byte
/// in the sequence has to be a character in the Basic Latin range
/// (0x00 to 0x7f or U+0000 to U+007F) of the Unicode
/// Standard.</summary>
/// <param name='bytes'>A sequence of bytes (interpreted as text). The
/// desired portion of the sequence of bytes (interpreted as text) must
/// contain only characters allowed by the given radix, except that it
/// may start with a minus sign ("-", U+002D) to indicate a negative
/// number. The desired portion is not allowed to contain white space
/// characters, including spaces. The desired portion may start with
/// any number of zeros.</param>
/// <param name='radix'>A base from 2 to 36. Depending on the radix,
/// the sequence of bytes (interpreted as text) can use the basic
/// digits 0 to 9 (U+0030 to U+0039) and then the basic upper-case
/// letters A to Z (U+0041 to U+005A). For example, 0-9 in radix 10,
/// and 0-9, then A-F in radix 16. Where a basic upper-case letter A to
/// Z is allowed in the sequence of bytes (interpreted as text), the
/// corresponding basic lower-case letter (U+0061 to U+007a) is allowed
/// instead.</param>
/// <param name='index'>The index of the sequence of bytes (interpreted
/// as text) that starts the desired portion.</param>
/// <param name='endIndex'>The index of the sequence of bytes
/// (interpreted as text) that ends the desired portion. The length
/// will be index + endIndex - 1.</param>
/// <returns>An arbitrary-precision integer with the same value as
/// given in the sequence's portion.</returns>
/// <exception cref='ArgumentNullException'>The parameter <paramref
/// name='bytes'/> is null.</exception>
/// <exception cref='FormatException'>The portion is empty or in an
/// invalid format.</exception>
public static EInteger FromRadixSubstring(
byte[] bytes,
int radix,
int index,
int endIndex) {
if (bytes == null) {
throw new ArgumentNullException(nameof(bytes));
}
return EIntegerByteArrayString.FromRadixSubstringImpl(
bytes,
radix,
index,
endIndex,
true);
}
/// <summary>Converts a string to an arbitrary-precision
/// integer.</summary>
/// <param name='str'>A text string describing an integer in base-10
/// (decimal) form. The string must contain only basic digits 0 to 9
/// (U+0030 to U+0039), except that it may start with a minus sign
/// ("-", U+002D) to indicate a negative number. The string is not
/// allowed to contain white space characters, including spaces. The
/// string may start with any number of zeros.</param>
/// <returns>An arbitrary-precision integer with the same value as
/// given in the string.</returns>
/// <exception cref='FormatException'>The parameter <paramref
/// name='str'/> is in an invalid format.</exception>
/// <exception cref='ArgumentNullException'>The parameter <paramref
/// name='str'/> is null.</exception>
public static EInteger FromString(string str) {
if (str == null) {
throw new ArgumentNullException(nameof(str));
}
int len = str.Length;
if (len == 1) {
char c = str[0];
if (c >= '0' && c <= '9') {
return FromInt32((int)(c - '0'));
}
throw new FormatException();
}
return FromRadixSubstring(str, 10, 0, len);
}
/// <summary>Converts a portion of a string to an arbitrary-precision
/// integer.</summary>
/// <param name='str'>A text string, the desired portion of which
/// describes an integer in base-10 (decimal) form. The desired portion
/// of the string must contain only basic digits 0 to 9 (U+0030 to
/// U+0039), except that it may start with a minus sign ("-", U+002D)
/// to indicate a negative number. The desired portion is not allowed
/// to contain white space characters, including spaces. The desired
/// portion may start with any number of zeros.</param>
/// <param name='index'>The index of the string that starts the string
/// portion.</param>
/// <param name='endIndex'>The index of the string that ends the string
/// portion. The length will be index + endIndex - 1.</param>
/// <returns>An arbitrary-precision integer with the same value as
/// given in the string portion.</returns>
/// <exception cref='ArgumentException'>The parameter <paramref
/// name='index'/> is less than 0, <paramref name='endIndex'/> is less
/// than 0, or either is greater than the string's length, or <paramref
/// name='endIndex'/> is less than <paramref
/// name='index'/>.</exception>
/// <exception cref='ArgumentNullException'>The parameter <paramref
/// name='str'/> is null.</exception>
public static EInteger FromSubstring(
string str,
int index,
int endIndex) {
if (str == null) {
throw new ArgumentNullException(nameof(str));
}
return FromRadixSubstring(str, 10, index, endIndex);
}
/// <summary>Returns the absolute value of this object's
/// value.</summary>
/// <returns>This object's value with the sign removed.</returns>
public EInteger Abs() {
return (this.wordCount == 0 || !this.negative) ? this : new
EInteger(this.wordCount, this.words, false);
}
/// <summary>Adds this arbitrary-precision integer and another
/// arbitrary-precision integer and returns the result.</summary>
/// <param name='bigintAugend'>Another arbitrary-precision
/// integer.</param>
/// <returns>The sum of the two numbers, that is, this
/// arbitrary-precision integer plus another arbitrary-precision
/// integer.</returns>
/// <exception cref='ArgumentNullException'>The parameter <paramref
/// name='bigintAugend'/> is null.</exception>
public EInteger Add(EInteger bigintAugend) {
if (bigintAugend == null) {
throw new ArgumentNullException(nameof(bigintAugend));
}
if (this.wordCount == 0) {
return bigintAugend;
}
if (bigintAugend.wordCount == 0) {
return this;
}
short[] sumreg;
if (bigintAugend.wordCount == 1 && this.wordCount == 1) {
if (this.negative == bigintAugend.negative) {
int intSum = (((int)this.words[0]) & ShortMask) +
(((int)bigintAugend.words[0]) & ShortMask);
sumreg = new short[2];
sumreg[0] = unchecked((short)intSum);
sumreg[1] = unchecked((short)(intSum >> 16));
return new EInteger(
((intSum >> 16) == 0) ? 1 : 2,
sumreg,
this.negative);
} else {
int a = ((int)this.words[0]) & ShortMask;
int b = ((int)bigintAugend.words[0]) & ShortMask;
if (a == b) {
return EInteger.Zero;
}
if (a > b) {
a -= b;
sumreg = new short[2];
sumreg[0] = unchecked((short)a);
return new EInteger(1, sumreg, this.negative);
}
b -= a;
sumreg = new short[2];
sumreg[0] = unchecked((short)b);
return new EInteger(1, sumreg, !this.negative);
}
}
if ((!this.negative) == (!bigintAugend.negative)) {
// both nonnegative or both negative
int addendCount = this.wordCount;
int augendCount = bigintAugend.wordCount;
if (augendCount <= 2 && addendCount <= 2 &&
(this.wordCount < 2 || (this.words[1] >> 15) == 0) &&
(bigintAugend.wordCount < 2 || (bigintAugend.words[1] >> 15) == 0)) {
int a = ((int)this.words[0]) & ShortMask;
if (this.wordCount == 2) {
a |= (((int)this.words[1]) & ShortMask) << 16;
}
int b = ((int)bigintAugend.words[0]) & ShortMask;
if (bigintAugend.wordCount == 2) {
b |= (((int)bigintAugend.words[1]) & ShortMask) << 16;
}
a = unchecked((int)(a + b));
sumreg = new short[2];
sumreg[0] = unchecked((short)(a & ShortMask));
sumreg[1] = unchecked((short)((a >> 16) & ShortMask));
int wcount = (sumreg[1] == 0) ? 1 : 2;
return new EInteger(wcount, sumreg, this.negative);
}
if (augendCount <= 2 && addendCount <= 2) {
int a = ((int)this.words[0]) & ShortMask;
if (this.wordCount == 2) {
a |= (((int)this.words[1]) & ShortMask) << 16;
}
int b = ((int)bigintAugend.words[0]) & ShortMask;
if (bigintAugend.wordCount == 2) {
b |= (((int)bigintAugend.words[1]) & ShortMask) << 16;
}
long longResult = ((long)a) & 0xffffffffL;
longResult += ((long)b) & 0xffffffffL;
if ((longResult >> 32) == 0) {
a = unchecked((int)longResult);
sumreg = new short[2];
sumreg[0] = unchecked((short)(a & ShortMask));
sumreg[1] = unchecked((short)((a >> 16) & ShortMask));
int wcount = (sumreg[1] == 0) ? 1 : 2;
return new EInteger(wcount, sumreg, this.negative);
}
}
// DebugUtility.Log("" + this + " + " + bigintAugend);
var wordLength2 = (int)Math.Max(
this.words.Length,
bigintAugend.words.Length);
sumreg = new short[wordLength2];
int carry;
int desiredLength = Math.Max(addendCount, augendCount);
if (addendCount == augendCount) {
carry = AddInternal(
sumreg,
0,
this.words,
0,
bigintAugend.words,
0,
addendCount);
} else if (addendCount > augendCount) {
// Addend is bigger
carry = AddInternal(
sumreg,
0,
this.words,
0,
bigintAugend.words,
0,
augendCount);
Array.Copy(
this.words,
augendCount,
sumreg,
augendCount,
addendCount - augendCount);
if (carry != 0) {
carry = IncrementWords(
sumreg,
augendCount,
addendCount - augendCount,
(short)carry);
}
} else {
// Augend is bigger
carry = AddInternal(
sumreg,
0,
this.words,
0,
bigintAugend.words,
0,
(int)addendCount);
Array.Copy(
bigintAugend.words,
addendCount,
sumreg,
addendCount,
augendCount - addendCount);
if (carry != 0) {
carry = IncrementWords(
sumreg,
addendCount,
(int)(augendCount - addendCount),
(short)carry);
}
}
var needShorten = true;
if (carry != 0) {
int nextIndex = desiredLength;
int len = nextIndex + 1;
sumreg = CleanGrow(sumreg, len);
sumreg[nextIndex] = (short)carry;
needShorten = false;
}
int sumwordCount = CountWords(sumreg);
if (sumwordCount == 0) {
return EInteger.Zero;
}
if (needShorten) {
sumreg = ShortenArray(sumreg, sumwordCount);
}
return new EInteger(sumwordCount, sumreg, this.negative);
}
EInteger minuend = this;
EInteger subtrahend = bigintAugend;
if (this.negative) {
// this is negative, b is nonnegative
minuend = bigintAugend;
subtrahend = this;
}
// Do a subtraction
int words1Size = minuend.wordCount;
int words2Size = subtrahend.wordCount;
var diffNeg = false;
#if DEBUG
if (words1Size > minuend.words.Length) {
throw new InvalidOperationException();
}
if (words2Size > subtrahend.words.Length) {
throw new InvalidOperationException();
}
#endif
short borrow;
var wordLength = (int)Math.Max(
minuend.words.Length,
subtrahend.words.Length);
var diffReg = new short[wordLength];
if (words1Size == words2Size) {
if (Compare(minuend.words, 0, subtrahend.words, 0, (int)words1Size) >=
0) {
// words1 is at least as high as words2
SubtractInternal(
diffReg,
0,
minuend.words,
0,
subtrahend.words,
0,
words1Size);
} else {
// words1 is less than words2
SubtractInternal(
diffReg,
0,
subtrahend.words,
0,
minuend.words,
0,
words1Size);
diffNeg = true; // difference will be negative
}
} else if (words1Size > words2Size) {
// words1 is greater than words2
borrow = (short)SubtractInternal(
diffReg,
0,
minuend.words,
0,
subtrahend.words,
0,
words2Size);
Array.Copy(
minuend.words,
words2Size,
diffReg,
words2Size,
words1Size - words2Size);
DecrementWords(
diffReg,
words2Size,
words1Size - words2Size,
borrow);
} else {
// words1 is less than words2
borrow = (short)SubtractInternal(
diffReg,
0,
subtrahend.words,
0,
minuend.words,
0,
words1Size);
Array.Copy(
subtrahend.words,
words1Size,
diffReg,
words1Size,
words2Size - words1Size);
DecrementWords(
diffReg,
words1Size,
words2Size - words1Size,
borrow);
diffNeg = true;
}
int count = CountWords(diffReg);
if (count == 0) {
return EInteger.Zero;
}
diffReg = ShortenArray(diffReg, count);
return new EInteger(count, diffReg, diffNeg);
}
/// <summary>Converts this object's value to a 32-bit signed integer,
/// throwing an exception if it can't fit.</summary>
/// <returns>A 32-bit signed integer.</returns>
/// <exception cref=' T:System.OverflowException'>This object's value
/// is too big to fit a 32-bit signed integer.</exception>
[Obsolete("Renamed to ToInt32Checked.")]
public int AsInt32Checked() {
return this.ToInt32Checked();
}
/// <summary>Converts this object's value to a 32-bit signed integer.
/// If the value can't fit in a 32-bit integer, returns the lower 32
/// bits of this object's two's-complement form (see
/// <see cref='PeterO.Numbers.EDecimal'>"Forms of numbers"</see> ) (in
/// which case the return value might have a different sign than this
/// object's value).</summary>
/// <returns>A 32-bit signed integer.</returns>
[Obsolete("Renamed to ToInt32Unchecked.")]
public int AsInt32Unchecked() {
return this.ToInt32Unchecked();
}
/// <summary>Converts this object's value to a 64-bit signed integer,
/// throwing an exception if it can't fit.</summary>
/// <returns>A 64-bit signed integer.</returns>
/// <exception cref=' T:System.OverflowException'>This object's value
/// is too big to fit a 64-bit signed integer.</exception>
[Obsolete("Renamed to ToInt64Checked.")]
public long AsInt64Checked() {
return this.ToInt64Checked();
}
/// <summary>Converts this object's value to a 64-bit signed integer.
/// If the value can't fit in a 64-bit integer, returns the lower 64
/// bits of this object's two's-complement form (see
/// <see cref='PeterO.Numbers.EDecimal'>"Forms of numbers"</see> ) (in
/// which case the return value might have a different sign than this
/// object's value).</summary>
/// <returns>A 64-bit signed integer.</returns>
[Obsolete("Renamed to ToInt64Unchecked.")]
public long AsInt64Unchecked() {
return this.ToInt64Unchecked();
}
/// <summary>Returns whether this object's value can fit in a 32-bit
/// signed integer.</summary>
/// <returns><c>true</c> if this object's value is from -2147483648
/// through 2147483647; otherwise, <c>false</c>.</returns>
public bool CanFitInInt32() {
int c = this.wordCount;
if (c > 2) {
return false;
}
if (c == 2 && (this.words[1] & 0x8000) != 0) {
return this.negative && this.words[1] == unchecked((short)0x8000) &&
this.words[0] == 0;
}
return true;
}
/// <summary>Returns whether this object's value can fit in a 64-bit
/// signed integer.</summary>
/// <returns><c>true</c> if this object's value is from
/// -9223372036854775808 through 9223372036854775807; otherwise,
/// <c>false</c>.</returns>
public bool CanFitInInt64() {
int c = this.wordCount;
if (c > 4) {
return false;
}
if (c == 4 && (this.words[3] & 0x8000) != 0) {
return this.negative && this.words[3] == unchecked((short)0x8000) &&
this.words[2] == 0 && this.words[1] == 0 &&
this.words[0] == 0;
}
return true;
}
/// <summary>Compares an arbitrary-precision integer with this
/// instance.</summary>
/// <param name='other'>The integer to compare to this value.</param>
/// <returns>Zero if the values are equal; a negative number if this
/// instance is less, or a positive number if this instance is greater.
/// <para>This implementation returns a positive number if <paramref
/// name='other'/> is null, to conform to the.NET definition of
/// CompareTo. This is the case even in the Java version of this
/// library, for consistency's sake, even though implementations of
/// <c>Comparable.CompareTo()</c> in Java ought to throw an exception
/// if they receive a null argument rather than treating null as less
/// or greater than any object.</para>.</returns>
public int CompareTo(EInteger other) {
if (other == null) {
return 1;
}
if (this == other) {
return 0;
}
int size = this.wordCount, tempSize = other.wordCount;
int sa = size == 0 ? 0 : (this.negative ? -1 : 1);
int sb = tempSize == 0 ? 0 : (other.negative ? -1 : 1);
if (sa != sb) {
return (sa < sb) ? -1 : 1;
}
if (sa == 0) {
return 0;
}
if (size == tempSize) {
if (size == 1 && this.words[0] == other.words[0]) {
return 0;
} else {
short[] words1 = this.words;
short[] words2 = other.words;
while (unchecked(size--) != 0) {
int an = ((int)words1[size]) & ShortMask;
int bn = ((int)words2[size]) & ShortMask;
if (an > bn) {
return (sa > 0) ? 1 : -1;
}
if (an < bn) {
return (sa > 0) ? -1 : 1;
}
}
return 0;
}
}
return ((size > tempSize) ^ (sa <= 0)) ? 1 : -1;
}
/// <summary>Returns the greater of two arbitrary-precision
/// integers.</summary>
/// <param name='first'>The first integer to compare.</param>
/// <param name='second'>The second integer to compare.</param>
/// <returns>The greater of the two integers.</returns>
/// <exception cref='ArgumentNullException'>The parameter <paramref
/// name='first'/> or <paramref name='second'/> is null.</exception>
public static EInteger Max(EInteger first, EInteger second) {
if (first == null) {
throw new ArgumentNullException(nameof(first));
}
if (second == null) {
throw new ArgumentNullException(nameof(second));
}
return first.CompareTo(second) > 0 ? first : second;
}
/// <summary>Returns the smaller of two arbitrary-precision
/// integers.</summary>
/// <param name='first'>The first integer to compare.</param>
/// <param name='second'>The second integer to compare.</param>
/// <returns>The smaller of the two integers.</returns>
/// <exception cref='ArgumentNullException'>The parameter <paramref
/// name='first'/> or <paramref name='second'/> is null.</exception>
public static EInteger Min(EInteger first, EInteger second) {
if (first == null) {
throw new ArgumentNullException(nameof(first));
}
if (second == null) {
throw new ArgumentNullException(nameof(second));
}
return first.CompareTo(second) < 0 ? first : second;
}
/// <summary>Of two arbitrary-precision integers, returns the one with
/// the greater absolute value. If both integers have the same absolute
/// value, this method has the same effect as Max.</summary>
/// <param name='first'>The first integer to compare.</param>
/// <param name='second'>The second integer to compare.</param>
/// <returns>The integer with the greater absolute value.</returns>
/// <exception cref='ArgumentNullException'>The parameter <paramref
/// name='first'/> or <paramref name='second'/> is null.</exception>
public static EInteger MaxMagnitude(EInteger first, EInteger second) {
if (first == null) {
throw new ArgumentNullException(nameof(first));
}
if (second == null) {
throw new ArgumentNullException(nameof(second));
}
int cmp = first.Abs().CompareTo(second.Abs());
return (cmp == 0) ? Max(first, second) : (cmp > 0 ? first : second);
}
/// <summary>Of two arbitrary-precision integers, returns the one with
/// the smaller absolute value. If both integers have the same absolute
/// value, this method has the same effect as Min.</summary>
/// <param name='first'>The first integer to compare.</param>
/// <param name='second'>The second integer to compare.</param>
/// <returns>The integer with the smaller absolute value.</returns>
/// <exception cref='ArgumentNullException'>The parameter <paramref
/// name='first'/> or <paramref name='second'/> is null.</exception>
public static EInteger MinMagnitude(EInteger first, EInteger second) {
if (first == null) {
throw new ArgumentNullException(nameof(first));
}
if (second == null) {
throw new ArgumentNullException(nameof(second));
}
int cmp = first.Abs().CompareTo(second.Abs());
return (cmp == 0) ? Min(first, second) : (cmp < 0 ? first : second);
}
/// <summary>Adds this arbitrary-precision integer and a 32-bit signed
/// integer and returns the result.</summary>
/// <param name='intValue'>The parameter <paramref name='intValue'/> is
/// a 32-bit signed integer.</param>
/// <returns>The sum of the two numbers, that is, this
/// arbitrary-precision integer plus a 32-bit signed integer.</returns>
public EInteger Add(int intValue) {
if (intValue == 0) {
return this;
}
if (this.wordCount == 0) {
return EInteger.FromInt32(intValue);
}
if (this.wordCount == 1 && intValue >= -0x7ffe0000 && intValue <
0x7ffe0000) {
short[] sumreg;
int intSum = this.negative ?
intValue - (((int)this.words[0]) & ShortMask) :
intValue + (((int)this.words[0]) & ShortMask);
if (intSum >= CacheFirst && intSum <= CacheLast) {
return Cache[intSum - CacheFirst];
} else if ((intSum >> 16) == 0) {
sumreg = new short[1];
sumreg[0] = unchecked((short)intSum);
return new EInteger(
1,
sumreg,
false);
} else if (intSum > 0) {
sumreg = new short[2];
sumreg[0] = unchecked((short)intSum);
sumreg[1] = unchecked((short)(intSum >> 16));
return new EInteger(
2,
sumreg,
false);
} else if (intSum > -65536) {
#if DEBUG
if (intSum >= 0) {
throw new ArgumentException("intSum (" + intSum + ") is not less" +
"\u0020than 0");
}
#endif
sumreg = new short[1];
intSum = -intSum;
sumreg[0] = unchecked((short)intSum);
return new EInteger(
1,
sumreg,
true);
} else {
#if DEBUG
if (intSum >= 0) {
throw new ArgumentException("intSum (" + intSum + ") is not less" +
"\u0020than 0");
}
#endif
sumreg = new short[2];
intSum = -intSum;
sumreg[0] = unchecked((short)intSum);
sumreg[1] = unchecked((short)(intSum >> 16));
return new EInteger(
2,
sumreg,
true);
}
}
return this.Add(EInteger.FromInt32(intValue));
}
/// <summary>Subtracts a 32-bit signed integer from this
/// arbitrary-precision integer and returns the result.</summary>
/// <param name='intValue'>The parameter <paramref name='intValue'/> is
/// a 32-bit signed integer.</param>
/// <returns>The difference between the two numbers, that is, this
/// arbitrary-precision integer minus a 32-bit signed
/// integer.</returns>
public EInteger Subtract(int intValue) {
return (intValue == Int32.MinValue) ?
this.Subtract(EInteger.FromInt32(intValue)) : ((intValue == 0) ?
this : this.Add(-intValue));
}
/// <summary>Multiplies this arbitrary-precision integer by a 32-bit
/// signed integer and returns the result.</summary>
/// <param name='intValue'>The parameter <paramref name='intValue'/> is
/// a 32-bit signed integer.</param>
/// <returns>The product of the two numbers, that is, this
/// arbitrary-precision integer times a 32-bit signed
/// integer.</returns>
/// <example>
/// <code>EInteger result = EInteger.FromString("5").Multiply(200);</code>
/// .
/// </example>
public EInteger Multiply(int intValue) {
return this.Multiply(EInteger.FromInt32(intValue));
}
/// <summary>Divides this arbitrary-precision integer by a 32-bit
/// signed integer and returns the result. The result of the division
/// is rounded down (the fractional part is discarded). Except if the
/// result of the division is 0, it will be negative if this
/// arbitrary-precision integer is positive and the other 32-bit signed
/// integer is negative, or vice versa, and will be positive if both
/// are positive or both are negative.</summary>
/// <param name='intValue'>The divisor.</param>
/// <returns>The result of dividing this arbitrary-precision integer by
/// a 32-bit signed integer. The result of the division is rounded down
/// (the fractional part is discarded). Except if the result of the
/// division is 0, it will be negative if this arbitrary-precision
/// integer is positive and the other 32-bit signed integer is
/// negative, or vice versa, and will be positive if both are positive
/// or both are negative.</returns>
/// <exception cref='DivideByZeroException'>Attempted to divide by
/// zero.</exception>
public EInteger Divide(int intValue) {
return this.Divide(EInteger.FromInt32(intValue));
}
/// <summary>Returns the remainder that would result when this
/// arbitrary-precision integer is divided by a 32-bit signed integer.
/// The remainder is the number that remains when the absolute value of
/// this arbitrary-precision integer is divided by the absolute value
/// of the other 32-bit signed integer; the remainder has the same sign
/// (positive or negative) as this arbitrary-precision
/// integer.</summary>
/// <param name='intValue'>The parameter <paramref name='intValue'/> is
/// a 32-bit signed integer.</param>
/// <returns>The remainder that would result when this
/// arbitrary-precision integer is divided by a 32-bit signed
/// integer.</returns>
/// <exception cref='DivideByZeroException'>Attempted to divide by
/// zero.</exception>
/// <exception cref='ArgumentNullException'>The parameter <paramref
/// name='intValue'/> is null.</exception>
public EInteger Remainder(int intValue) {
return this.Remainder(EInteger.FromInt32(intValue));
}
/// <summary>Compares an arbitrary-precision integer with this
/// instance.</summary>
/// <param name='intValue'>The parameter <paramref name='intValue'/> is
/// a 32-bit signed integer.</param>
/// <returns>Zero if the values are equal; a negative number if this
/// instance is less, or a positive number if this instance is
/// greater.</returns>
public int CompareTo(int intValue) {
int c = this.wordCount;
if (c > 2) {
return this.negative ? -1 : 1;
}
if (c == 2 && (this.words[1] & 0x8000) != 0) {
if (this.negative && this.words[1] == unchecked((short)0x8000) &&
this.words[0] == 0) {
// This value is Int32.MinValue
return intValue == Int32.MinValue ? 0 : -1;
} else {
return this.negative ? -1 : 1;
}
}
int thisInt = this.ToInt32Unchecked();
return thisInt == intValue ? 0 : (thisInt < intValue ? -1 : 1);
}
/// <summary>Divides this arbitrary-precision integer by another
/// arbitrary-precision integer and returns the result. The result of
/// the division is rounded down (the fractional part is discarded).
/// Except if the result of the division is 0, it will be negative if
/// this arbitrary-precision integer is positive and the other
/// arbitrary-precision integer is negative, or vice versa, and will be
/// positive if both are positive or both are negative.</summary>
/// <param name='bigintDivisor'>The divisor.</param>
/// <returns>The result of dividing this arbitrary-precision integer by
/// another arbitrary-precision integer. The result of the division is
/// rounded down (the fractional part is discarded). Except if the
/// result of the division is 0, it will be negative if this
/// arbitrary-precision integer is positive and the other
/// arbitrary-precision integer is negative, or vice versa, and will be
/// positive if both are positive or both are negative.</returns>
/// <exception cref='ArgumentNullException'>The parameter <paramref
/// name='bigintDivisor'/> is null.</exception>
/// <exception cref='DivideByZeroException'>Attempted to divide by
/// zero.</exception>
public EInteger Divide(EInteger bigintDivisor) {
if (bigintDivisor == null) {
throw new ArgumentNullException(nameof(bigintDivisor));
}
int words1Size = this.wordCount;
int words2Size = bigintDivisor.wordCount;
// ---- Special cases
if (words2Size == 0) {
// Divisor is 0
throw new DivideByZeroException();
}
if (words1Size < words2Size) {
// Dividend is less than divisor (includes case
// where dividend is 0)
return EInteger.Zero;
}
// DebugUtility.Log("divide " + this + " " + bigintDivisor);
if (words1Size <= 2 && words2Size <= 2 && this.CanFitInInt32() &&
bigintDivisor.CanFitInInt32()) {
int valueASmall = this.ToInt32Checked();
int valueBSmall = bigintDivisor.ToInt32Checked();
if (valueASmall != Int32.MinValue || valueBSmall != -1) {
int result = valueASmall / valueBSmall;
return EInteger.FromInt32(result);
}
}
if (words1Size <= 4 && words2Size <= 4 && this.CanFitInInt64() &&
bigintDivisor.CanFitInInt64()) {
long valueALong = this.ToInt64Checked();
long valueBLong = bigintDivisor.ToInt64Checked();
if (valueALong != Int64.MinValue || valueBLong != -1) {
long resultLong = valueALong / valueBLong;
return EInteger.FromInt64(resultLong);
}
}
short[] quotReg;
int quotwordCount;
if (words2Size == 1) {
// divisor is small, use a fast path
quotReg = new short[this.words.Length];
quotwordCount = this.wordCount;
FastDivide(quotReg, this.words, words1Size, bigintDivisor.words[0]);
while (quotwordCount != 0 && quotReg[quotwordCount - 1] == 0) {
--quotwordCount;
}
return (quotwordCount != 0) ? new EInteger(
quotwordCount,
quotReg,
this.negative ^ bigintDivisor.negative) : EInteger.Zero;
}
// ---- General case
quotReg = new short[(int)(words1Size - words2Size + 1)];
GeneralDivide(
this.words,
0,
this.wordCount,
bigintDivisor.words,
0,
bigintDivisor.wordCount,
quotReg,
0,
null,
0);
quotwordCount = CountWords(quotReg);
quotReg = ShortenArray(quotReg, quotwordCount);
return (quotwordCount != 0) ? new EInteger(quotwordCount,
quotReg,
this.negative ^ bigintDivisor.negative) :
EInteger.Zero;
}
private static int LinearMultiplySubtractMinuend1Bigger(
short[] resultArr,
int resultStart,
short[] minuendArr,
int minuendArrStart,
int factor1,
short[] factor2,
int factor2Start,
int factor2Count) {
#if DEBUG
if (factor2Count <= 0 || (factor1 >> 16) != 0) {
throw new InvalidOperationException();
}
#endif
var a = 0;
var b = 0;
const int SMask = ShortMask;
var cc = 0;
if (factor1 == 0) {
for (var i = 0; i < factor2Count; ++i) {
b = ((int)minuendArr[minuendArrStart + i] & SMask) - cc;
resultArr[resultStart + i] = unchecked((short)b);
cc = (b >> 31) & 1;
}
} else {
for (var i = 0; i < factor2Count; ++i) {
a = unchecked((((int)factor2[factor2Start + i]) & SMask) * factor1);
a = unchecked(a + cc);
b = ((int)minuendArr[minuendArrStart + i] & SMask) - (a & SMask);
resultArr[resultStart + i] = unchecked((short)b);
cc = (a >> 16) + ((b >> 31) & 1);
cc &= SMask;
}
}
a = cc;
b = ((int)minuendArr[minuendArrStart + factor2Count] & SMask) - a;
resultArr[resultStart + factor2Count] = unchecked((short)b);
cc = (b >> 31) & 1;
return cc;
}
private static void DivideThreeBlocksByTwo(
short[] valueALow,
int posALow,
short[] valueAMidHigh,
int posAMidHigh,
short[] b,
int posB,
int blockCount,
short[] quot,
int posQuot,
short[] rem,
int posRem,
short[] tmp) {
// NOTE: size of 'quot' equals 'blockCount' * 2
// NOTE: size of 'rem' equals 'blockCount' * 2
#if DEBUG
if (quot != null) {
if (posQuot < 0) {
throw new ArgumentException("posQuot(" + posQuot +
") is less than 0");
}
if (posQuot > quot.Length) {
throw new ArgumentException("posQuot(" + posQuot +
") is more than " + quot.Length);
}
if ((blockCount * 2) < 0) {
throw new ArgumentException("blockCount*2(" + (blockCount * 2) +
") is less than 0");
}
if ((blockCount * 2) > quot.Length) {
throw new ArgumentException("blockCount*2(" + (blockCount * 2) +
") is more than " + quot.Length);
}
if (quot.Length - posQuot < blockCount * 2) {
throw new ArgumentException("quot's length minus " + posQuot + "(" +
(quot.Length - posQuot) + ") is less than " + (blockCount * 2));
}
}
if (rem != null) {
if (posRem < 0) {
throw new ArgumentException("posRem(" + posRem +
") is less than 0");
}
if (posRem > rem.Length) {
throw new ArgumentException("posRem(" + posRem +
") is more than " + rem.Length);
}
if ((blockCount * 2) < 0) {
throw new ArgumentException("blockCount*2(" + (blockCount * 2) +
") is less than 0");
}
if ((blockCount * 2) > rem.Length) {
throw new ArgumentException("blockCount*2(" + (blockCount * 2) +
") is more than " + rem.Length);
}
if (rem.Length - posRem < blockCount * 2) {
throw new ArgumentException("rem's length minus " + posRem + "(" +
(rem.Length - posRem) + ") is less than " + (blockCount * 2));
}
}
if (tmp.Length < blockCount * 6) {
throw new ArgumentException("tmp.Length(" + tmp.Length +
") is less than " + (blockCount * 6));
}
#endif
// Implements Algorithm 2 of Burnikel & Ziegler 1998
int c;
// If AHigh is less than BHigh
if (
WordsCompare(
valueAMidHigh,
posAMidHigh + blockCount,
blockCount,
b,
posB + blockCount,
blockCount) < 0) {
// Divide AMidHigh by BHigh
RecursiveDivideInner(
valueAMidHigh,
posAMidHigh,
b,
posB + blockCount,
quot,
posQuot,
rem,
posRem,
blockCount);
// Copy remainder to temp at block position 4
Array.Copy(rem, posRem, tmp, blockCount * 4, blockCount);
Array.Clear(tmp, blockCount * 5, blockCount);
} else {
// BHigh is less than AHigh
// set quotient to all ones
short allones = unchecked((short)0xffff);
for (var i = 0; i < blockCount; ++i) {
quot[posQuot + i] = allones;
}
Array.Clear(quot, posQuot + blockCount, blockCount);
// copy AMidHigh to temp
Array.Copy(
valueAMidHigh,
posAMidHigh,
tmp,
blockCount * 4,
blockCount * 2);
// subtract BHigh from temp's high block
SubtractInternal(
tmp,
blockCount * 5,
tmp,
blockCount * 5,
b,
posB + blockCount,
blockCount);
// add BHigh to temp
c = AddInternal(
tmp,
blockCount * 4,
tmp,
blockCount * 4,
b,
posB + blockCount,
blockCount);
IncrementWords(tmp, blockCount * 5, blockCount, (short)c);
}
AsymmetricMultiply(
tmp,
0,
tmp,
blockCount * 2,
quot,
posQuot,
blockCount,
b,
posB,
blockCount);
int bc3 = blockCount * 3;
Array.Copy(valueALow, posALow, tmp, bc3, blockCount);
Array.Clear(tmp, blockCount * 2, blockCount);
c = SubtractInternal(tmp, bc3, tmp, bc3, tmp, 0, blockCount * 3);
if (c != 0) {
while (true) {
c = AddInternal(tmp, bc3, tmp, bc3, b, posB, blockCount * 2);
c = IncrementWords(tmp, blockCount * 5, blockCount, (short)c);
DecrementWords(quot, posQuot, blockCount * 2, (short)1);
if (c != 0) {
break;
}
}
}
Array.Copy(tmp, bc3, rem, posRem, blockCount * 2);
}
private static void RecursiveDivideInner(
short[] a,
int posA,
short[] b,
int posB,
short[] quot,
int posQuot,
short[] rem,
int posRem,
int blockSize) {
// NOTE: size of 'a', 'quot', and 'rem' is 'blockSize'*2
// NOTE: size of 'b' is 'blockSize'
#if DEBUG
if (a == null) {
throw new ArgumentNullException(nameof(a));
}
if (posA < 0) {
throw new ArgumentException("posA(" + posA +
") is less than 0");
}
if (posA > a.Length) {
throw new ArgumentException("posA(" + posA + ") is more than " +
a.Length);
}
if ((blockSize * 2) < 0) {
throw new ArgumentException("(blockSize*2)(" + (blockSize * 2) +
") is less than 0");
}
if ((blockSize * 2) > a.Length) {
throw new ArgumentException("(blockSize*2)(" + (blockSize * 2) +
") is more than " + a.Length);
}
if ((a.Length - posA) < (blockSize * 2)) {
throw new ArgumentException("a's length minus " + posA + "(" +
(a.Length - posA) + ") is less than " + (blockSize * 2));
}
if (b == null) {
throw new ArgumentNullException(nameof(b));
}
if (posB < 0) {
throw new ArgumentException("posB(" + posB +
") is less than 0");
}
if (posB > b.Length) {
throw new ArgumentException("posB(" + posB + ") is more than " +
b.Length);
}
if (blockSize < 0) {
throw new ArgumentException("blockSize(" + blockSize +
") is less than 0");
}
if (blockSize > b.Length) {
throw new ArgumentException("blockSize(" + blockSize +
") is more than " + b.Length);
}
if (b.Length - posB < blockSize) {
throw new ArgumentException("b's length minus " + posB + "(" +
(b.Length - posB) + ") is less than " + blockSize);
}
if (quot != null) {
if (posQuot < 0) {
throw new ArgumentException("posQuot(" + posQuot +
") is less than 0");
}
if (posQuot > quot.Length) {
throw new ArgumentException("posQuot(" + posQuot +
") is more than " + quot.Length);
}
if ((blockSize * 2) < 0) {
throw new ArgumentException("blockSize*2(" + (blockSize * 2) +
") is less than 0");
}
if ((blockSize * 2) > quot.Length) {
throw new ArgumentException("blockSize*2(" + (blockSize * 2) +
") is more than " + quot.Length);
}
if (quot.Length - posQuot < blockSize * 2) {
throw new ArgumentException("quot's length minus " + posQuot + "(" +
(quot.Length - posQuot) + ") is less than " + (blockSize * 2));
}
}
if (rem != null) {
if (posRem < 0) {
throw new ArgumentException("posRem(" + posRem +
") is less than 0");
}
if (posRem > rem.Length) {
throw new ArgumentException("posRem(" + posRem +
") is more than " + rem.Length);
}
if ((blockSize * 2) < 0) {
throw new ArgumentException("blockSize*2(" + (blockSize * 2) +
") is less than 0");
}
if ((blockSize * 2) > rem.Length) {
throw new ArgumentException("blockSize*2(" + (blockSize * 2) +
") is more than " + rem.Length);
}
if (rem.Length - posRem < (blockSize * 2)) {
throw new ArgumentException("rem's length minus " + posRem + "(" +
(rem.Length - posRem) + ") is less than " + (blockSize * 2));
}
}
#endif
// Implements Algorithm 1 of Burnikel & Ziegler 1998
if (blockSize < RecursiveDivisionLimit || (blockSize & 1) == 1) {
GeneralDivide(
a,
posA,
blockSize * 2,
b,
posB,
blockSize,
quot,
posQuot,
rem,
posRem);
} else {
int halfBlock = blockSize >> 1;
var tmp = new short[halfBlock * 10];
Array.Clear(quot, posQuot, blockSize * 2);
Array.Clear(rem, posRem, blockSize);
DivideThreeBlocksByTwo(
a,
posA + halfBlock,
a,
posA + blockSize,
b,
posB,
halfBlock,
tmp,
halfBlock * 6,
tmp,
halfBlock * 8,
tmp);
DivideThreeBlocksByTwo(
a,
posA,
tmp,
halfBlock * 8,
b,
posB,
halfBlock,
quot,
posQuot,
rem,
posRem,
tmp);
Array.Copy(tmp, halfBlock * 6, quot, posQuot + halfBlock, halfBlock);
}
}
private static void RecursiveDivide(
short[] a,
int posA,
int countA,
short[] b,
int posB,
int countB,
short[] quot,
int posQuot,
short[] rem,
int posRem) {
#if DEBUG
if (countB <= RecursiveDivisionLimit) {
throw new ArgumentException("countB(" + countB +
") is not greater than " + RecursiveDivisionLimit);
}
if (a == null) {
throw new ArgumentNullException(nameof(a));
}
if (posA < 0) {
throw new ArgumentException("posA(" + posA +
") is less than 0");
}
if (posA > a.Length) {
throw new ArgumentException("posA(" + posA + ") is more than " +
a.Length);
}
if (countA < 0) {
throw new ArgumentException("countA(" + countA +
") is less than 0");
}
if (countA > a.Length) {
throw new ArgumentException("countA(" + countA +
") is more than " + a.Length);
}
if (a.Length - posA < countA) {
throw new ArgumentException("a's length minus " + posA + "(" +
(a.Length - posA) + ") is less than " + countA);
}
if (b == null) {
throw new ArgumentNullException(nameof(b));
}
if (posB < 0) {
throw new ArgumentException("posB(" + posB +
") is less than 0");
}
if (posB > b.Length) {
throw new ArgumentException("posB(" + posB + ") is more than " +
b.Length);
}
if (countB < 0) {
throw new ArgumentException("countB(" + countB +
") is less than 0");
}
if (countB > b.Length) {
throw new ArgumentException("countB(" + countB +
") is more than " + b.Length);
}
if (b.Length - posB < countB) {
throw new ArgumentException("b's length minus " + posB + "(" +
(b.Length - posB) + ") is less than " + countB);
}
if (rem != null) {
if (posRem < 0) {
throw new ArgumentException("posRem(" + posRem +
") is less than 0");
}
if (posRem > rem.Length) {
throw new ArgumentException("posRem(" + posRem +
") is more than " + rem.Length);
}
if (countB < 0) {
throw new ArgumentException("countB(" + countB +
") is less than 0");
}
if (countB > rem.Length) {
throw new ArgumentException("countB(" + countB +
") is more than " + rem.Length);
}
if (rem.Length - posRem < countB) {
throw new ArgumentException("rem's length minus " + posRem + "(" +
(rem.Length - posRem) + ") is less than " + countB);
}
}
#endif
int workPosA, workPosB, i;
short[] workA = a;
short[] workB = b;
workPosA = posA;
workPosB = posB;
int blocksB = RecursiveDivisionLimit;
var shiftB = 0;
var m = 1;
while (blocksB < countB) {
blocksB <<= 1;
m <<= 1;
}
workB = new short[blocksB];
workPosB = 0;
Array.Copy(b, posB, workB, blocksB - countB, countB);
var shiftA = 0;
var extraWord = 0;
int wordsA = countA + (blocksB - countB);
if ((b[countB - 1] & 0x8000) == 0) {
int x = b[countB - 1];
while ((x & 0x8000) == 0) {
++shiftB;
x <<= 1;
}
x = a[countA - 1];
while ((x & 0x8000) == 0) {
++shiftA;
x <<= 1;
}
if (shiftA < shiftB) {
// Shifting A would require an extra word
++extraWord;
}
ShiftWordsLeftByBits(
workB,
workPosB + blocksB - countB,
countB,
shiftB);
}
int blocksA = (wordsA + extraWord + (blocksB - 1)) / blocksB;
int totalWordsA = blocksA * blocksB;
workA = new short[totalWordsA];
workPosA = 0;
Array.Copy(
a,
posA,
workA,
workPosA + (blocksB - countB),
countA);
ShiftWordsLeftByBits(
workA,
workPosA + (blocksB - countB),
countA + extraWord,
shiftB);
// Start division
// "tmprem" holds temporary space for the following:
// - blocksB: Remainder
// - blocksB * 2: Dividend
// - blocksB * 2: Quotient
var tmprem = new short[blocksB * 5];
var size = 0;
for (i = blocksA - 1; i >= 0; --i) {
int workAIndex = workPosA + (i * blocksB);
// Set the low part of the sub-dividend with the working
// block of the dividend
Array.Copy(workA, workAIndex, tmprem, blocksB, blocksB);
// Clear the quotient
Array.Clear(tmprem, blocksB * 3, blocksB << 1);
RecursiveDivideInner(
tmprem,
blocksB,
workB,
workPosB,
tmprem,
blocksB * 3,
tmprem,
0,
blocksB);
if (quot != null) {
size = Math.Min(blocksB, quot.Length - (i * blocksB));
// DebugUtility.Log("quot len=" + quot.Length + ",bb=" + blocksB +
// ",size=" + size + " [" + countA + "," + countB + "]");
if (size > 0) {
Array.Copy(
tmprem,
blocksB * 3,
quot,
posQuot + (i * blocksB),
size);
}
}
// Set the high part of the sub-dividend with the remainder
Array.Copy(tmprem, 0, tmprem, blocksB << 1, blocksB);
}
if (rem != null) {
Array.Copy(tmprem, blocksB - countB, rem, posRem, countB);
ShiftWordsRightByBits(rem, posRem, countB, shiftB);
}
}
private static string WordsToString(short[] a, int pos, int len) {
while (len != 0 && a[pos + len - 1] == 0) {
--len;
}
if (len == 0) {
return "\"0\"";
}
var words = new short[len];
Array.Copy(a, pos, words, 0, len);
return "\"" + new EInteger(len, words, false).ToString() + "\"";
}
private static string WordsToStringHex(short[] a, int pos, int len) {
while (len != 0 && a[pos + len - 1] == 0) {
--len;
}
if (len == 0) {
return "\"0\"";
}
var words = new short[len];
Array.Copy(a, pos, words, 0, len);
return "\"" + new EInteger(len, words, false).ToRadixString(16) +
"\"";
}
private static string WordsToString2(
short[] a,
int pos,
int len,
short[] b,
int pos2,
int len2) {
var words = new short[len + len2];
Array.Copy(a, pos, words, 0, len);
Array.Copy(b, pos2, words, len, len2);
len += len2;
while (len != 0 && words[len - 1] == 0) {
--len;
}
return (len == 0) ? "\"0\"" : ("\"" + new EInteger(
len,
words,
false).ToString() + "\"");
}
private static void GeneralDivide(
short[] a,
int posA,
int countA,
short[] b,
int posB,
int countB,
short[] quot,
int posQuot,
short[] rem,
int posRem) {
#if DEBUG
if (!(countA > 0 && countB > 0)) {
throw new ArgumentException("doesn't satisfy countA>0 && countB>0");
}
if (a == null) {
throw new ArgumentNullException(nameof(a));
}
if (posA < 0) {
throw new ArgumentException("posA(" + posA +
") is less than 0");
}
if (posA > a.Length) {
throw new ArgumentException("posA(" + posA + ") is more than " +
a.Length);
}
if (countA < 0) {
throw new ArgumentException("countA(" + countA +
") is less than 0");
}
if (countA > a.Length) {
throw new ArgumentException("countA(" + countA +
") is more than " + a.Length);
}
if (a.Length - posA < countA) {
throw new ArgumentException("a's length minus " + posA + "(" +
(a.Length - posA) + ") is less than " + countA);
}
if (b == null) {
throw new ArgumentNullException(nameof(b));
}
if (posB < 0) {
throw new ArgumentException("posB(" + posB +
") is less than 0");
}
if (posB > b.Length) {
throw new ArgumentException("posB(" + posB + ") is more than " +
b.Length);
}
if (countB < 0) {
throw new ArgumentException("countB(" + countB +
") is less than 0");
}
if (countB > b.Length) {
throw new ArgumentException("countB(" + countB +
") is more than " + b.Length);
}
if (b.Length - posB < countB) {
throw new ArgumentException("b's length minus " + posB + "(" +
(b.Length - posB) + ") is less than " + countB);
}
if (quot != null) {
if (posQuot < 0) {
throw new ArgumentException("posQuot(" + posQuot +
") is less than 0");
}
if (posQuot > quot.Length) {
throw new ArgumentException("posQuot(" + posQuot +
") is more than " + quot.Length);
}
if (countA - countB + 1 < 0) {
throw new ArgumentException("(countA-countB+1)(" + (countA -
countB + 1) + ") is less than 0");
}
if (countA - countB + 1 > quot.Length) {
throw new ArgumentException("(countA-countB+1)(" + (countA -
countB + 1) + ") is more than " + quot.Length);
}
if ((quot.Length - posQuot) < (countA - countB + 1)) {
throw new ArgumentException("quot's length minus " + posQuot + "(" +
(quot.Length - posQuot) + ") is less than " +
(countA - countB + 1));
}
}
if (rem != null) {
if (posRem < 0) {
throw new ArgumentException("posRem(" + posRem +
") is less than 0");
}
if (posRem > rem.Length) {
throw new ArgumentException("posRem(" + posRem +
") is more than " + rem.Length);
}
if (countB < 0) {
throw new ArgumentException("countB(" + countB +
") is less than 0");
}
if (countB > rem.Length) {
throw new ArgumentException("countB(" + countB +
") is more than " + rem.Length);
}
if (rem.Length - posRem < countB) {
throw new ArgumentException("rem's length minus " + posRem + "(" +
(rem.Length - posRem) + ") is less than " + countB);
}
}
#endif
int origQuotSize = countA - countB + 1;
int origCountA = countA;
int origCountB = countB;
while (countB > 0 && b[posB + countB - 1] == 0) {
--countB;
}
while (countA > 0 && a[posA + countA - 1] == 0) {
--countA;
}
int newQuotSize = countA - countB + 1;
if (quot != null) {
if (newQuotSize < 0 || newQuotSize >= origQuotSize) {
Array.Clear(quot, posQuot, Math.Max(0, origQuotSize));
} else {
Array.Clear(
quot,
posQuot + newQuotSize,
Math.Max(0, origQuotSize - newQuotSize));
}
}
if (rem != null) {
Array.Clear(rem, posRem + countB, origCountB - countB);
}
#if DEBUG
if (countA != 0 && !(a[posA + countA - 1] != 0)) {
throw new InvalidOperationException();
}
if (countB == 0 || !(b[posB + countB - 1] != 0)) {
throw new InvalidOperationException();
}
#endif
if (countA < countB) {
// A is less than B, so quotient is 0, remainder is "a"
if (quot != null) {
Array.Clear(quot, posQuot, Math.Max(0, origQuotSize));
}
if (rem != null) {
Array.Copy(a, posA, rem, posRem, origCountA);
}
return;
} else if (countA == countB) {
int cmp = Compare(a, posA, b, posB, countA);
if (cmp == 0) {
// A equals B, so quotient is 1, remainder is 0
if (quot != null) {
quot[posQuot] = 1;
Array.Clear(quot, posQuot + 1, Math.Max(0, origQuotSize - 1));
}
if (rem != null) {
Array.Clear(rem, posRem, countA);
}
return;
} else if (cmp < 0) {
// A is less than B, so quotient is 0, remainder is "a"
if (quot != null) {
Array.Clear(quot, posQuot, Math.Max(0, origQuotSize));
}
if (rem != null) {
Array.Copy(a, posA, rem, posRem, origCountA);
}
return;
}
}
if (countB == 1) {
// Divisor is a single word
short shortRemainder = FastDivideAndRemainder(
quot,
posQuot,
a,
posA,
countA,
b[posB]);
if (rem != null) {
rem[posRem] = shortRemainder;
}
return;
}
int workPosA, workPosB;
short[] workAB = null;
short[] workA = a;
short[] workB = b;
workPosA = posA;
workPosB = posB;
if (countB > RecursiveDivisionLimit) {
RecursiveDivide(
a,
posA,
countA,
b,
posB,
countB,
quot,
posQuot,
rem,
posRem);
return;
}
var sh = 0;
var noShift = false;
if ((b[posB + countB - 1] & 0x8000) == 0) {
// Normalize a and b by shifting both until the high
// bit of b is the highest bit of the last word
int x = b[posB + countB - 1];
if (x == 0) {
throw new InvalidOperationException();
}
while ((x & 0x8000) == 0) {
++sh;
x <<= 1;
}
workAB = new short[countA + 1 + countB];
workPosA = 0;
workPosB = countA + 1;
workA = workAB;
workB = workAB;
Array.Copy(a, posA, workA, workPosA, countA);
Array.Copy(b, posB, workB, workPosB, countB);
ShiftWordsLeftByBits(workA, workPosA, countA + 1, sh);
ShiftWordsLeftByBits(workB, workPosB, countB, sh);
} else {
noShift = true;
workA = new short[countA + 1];
workPosA = 0;
Array.Copy(a, posA, workA, workPosA, countA);
}
var c = 0;
short pieceBHigh = workB[workPosB + countB - 1];
int pieceBHighInt = ((int)pieceBHigh) & ShortMask;
int endIndex = workPosA + countA;
#if DEBUG
// Assert that pieceBHighInt is normalized
if (!((pieceBHighInt & 0x8000) != 0)) {
throw new ArgumentException("doesn't satisfy(pieceBHighInt &" +
"\u00200x8000)!=0");
}
#endif
short pieceBNextHigh = workB[workPosB + countB - 2];
int pieceBNextHighInt = ((int)pieceBNextHigh) & ShortMask;
for (int offset = countA - countB; offset >= 0; --offset) {
int wpoffset = workPosA + offset;
int wpaNextHigh = ((int)workA[wpoffset + countB - 1]) & ShortMask;
var wpaHigh = 0;
if (!noShift || wpoffset + countB < endIndex) {
wpaHigh = ((int)workA[wpoffset + countB]) & ShortMask;
}
int dividend = unchecked(wpaNextHigh + (wpaHigh << 16));
int divnext = ((int)workA[wpoffset + countB - 2]) & ShortMask;
int quorem0 = (dividend >> 31) == 0 ? (dividend / pieceBHighInt) :
unchecked((int)(((long)dividend & 0xffffffffL) / pieceBHighInt));
int quorem1 = unchecked(dividend - (quorem0 * pieceBHighInt));
// DebugUtility.Log("{0:X8}/{1:X4} = {2:X8},{3:X4}",
// dividend, pieceBHigh, quorem0, quorem1);
long t = (((long)quorem1) << 16) | (divnext & 0xffffL);
// NOTE: quorem0 won't be higher than (1<< 16)+1 as long as
// pieceBHighInt is
// normalized (see Burnikel & Ziegler 1998). Since the following
// code block
// corrects all cases where quorem0 is too high by 2, and all
// remaining cases
// will reduce quorem0 by 1 if it's at least (1<< 16), quorem0 will
// be guaranteed to
// have a bit length of 16 or less by the end of the code block.
if ((quorem0 >> 16) != 0 ||
(unchecked(quorem0 * pieceBNextHighInt) & 0xffffffffL) > t) {
quorem1 += pieceBHighInt;
--quorem0;
if ((quorem1 >> 16) == 0) {
t = (((long)quorem1) << 16) | (divnext & 0xffffL);
if ((quorem0 >> 16) != 0 ||
(unchecked(quorem0 * pieceBNextHighInt) & 0xffffffffL) > t) {
--quorem0;
if (rem == null && offset == 0) {
// We can stop now and break; all cases where quorem0
// is 2 too big will have been caught by now
if (quot != null) {
quot[posQuot + offset] = unchecked((short)quorem0);
}
break;
}
}
}
}
int q1 = quorem0 & ShortMask;
#if DEBUG
int q2 = (quorem0 >> 16) & ShortMask;
if (q2 != 0) {
// NOTE: The checks above should have ensured that quorem0 can't
// be longer than 16 bits.
throw new InvalidOperationException();
}
#endif
c = LinearMultiplySubtractMinuend1Bigger(
workA,
wpoffset,
workA,
wpoffset,
q1,
workB,
workPosB,
countB);
if (c != 0) {
// T(workA,workPosA,countA+1,"workA X");
c = AddInternal(
workA,
wpoffset,
workA,
wpoffset,
workB,
workPosB,
countB);
c = IncrementWords(workA, wpoffset + countB, 1, (short)c);
// T(workA,workPosA,countA+1,"workA "+c);
--quorem0;
}
if (quot != null) {
quot[posQuot + offset] = unchecked((short)quorem0);
}
}
if (rem != null) {
if (sh != 0) {
ShiftWordsRightByBits(workA, workPosA, countB + 1, sh);
}
Array.Copy(workA, workPosA, rem, posRem, countB);
}
}
/// <summary>Divides this arbitrary-precision integer by a 32-bit
/// signed integer and returns a two-item array containing the result
/// of the division and the remainder, in that order. The result of the
/// division is rounded down (the fractional part is discarded). Except
/// if the result of the division is 0, it will be negative if this
/// arbitrary-precision integer is positive and the other 32-bit signed
/// integer is negative, or vice versa, and will be positive if both
/// are positive or both are negative. The remainder is the number that
/// remains when the absolute value of this arbitrary-precision integer
/// is divided by the absolute value of the other 32-bit signed
/// integer; the remainder has the same sign (positive or negative) as
/// this arbitrary-precision integer.</summary>
/// <param name='intDivisor'>The number to divide by.</param>
/// <returns>An array of two items: the first is the result of the
/// division as an arbitrary-precision integer, and the second is the
/// remainder as an arbitrary-precision integer. The result of division
/// is the result of the Divide method on the two operands, and the
/// remainder is the result of the Remainder method on the two
/// operands.</returns>
/// <exception cref='DivideByZeroException'>The parameter <paramref
/// name='intDivisor'/> is 0.</exception>
public EInteger[] DivRem(int intDivisor) {
return this.DivRem(EInteger.FromInt32(intDivisor));
}
/// <summary>Adds this arbitrary-precision integer and a 64-bit signed
/// integer and returns the result.</summary>
/// <param name='longValue'>The parameter <paramref name='longValue'/>
/// is a 64-bit signed integer.</param>
/// <returns>The sum of the two numbers, that is, this
/// arbitrary-precision integer plus a 64-bit signed integer.</returns>
public EInteger Add(long longValue) {
return this.Add(EInteger.FromInt64(longValue));
}
/// <summary>Subtracts a 64-bit signed integer from this
/// arbitrary-precision integer and returns the result.</summary>
/// <param name='longValue'>The parameter <paramref name='longValue'/>
/// is a 64-bit signed integer.</param>
/// <returns>The difference between the two numbers, that is, this
/// arbitrary-precision integer minus a 64-bit signed
/// integer.</returns>
public EInteger Subtract(long longValue) {
return this.Subtract(EInteger.FromInt64(longValue));
}
/// <summary>Multiplies this arbitrary-precision integer by a 64-bit
/// signed integer and returns the result.</summary>
/// <param name='longValue'>The parameter <paramref name='longValue'/>
/// is a 64-bit signed integer.</param>
/// <returns>The product of the two numbers, that is, this
/// arbitrary-precision integer times a 64-bit signed
/// integer.</returns>
public EInteger Multiply(long longValue) {
return this.Multiply(EInteger.FromInt64(longValue));
}
/// <summary>Divides this arbitrary-precision integer by a 64-bit
/// signed integer and returns the result. The result of the division
/// is rounded down (the fractional part is discarded). Except if the
/// result of the division is 0, it will be negative if this
/// arbitrary-precision integer is positive and the other 64-bit signed
/// integer is negative, or vice versa, and will be positive if both
/// are positive or both are negative.</summary>
/// <param name='longValue'>The parameter <paramref name='longValue'/>
/// is a 64-bit signed integer.</param>
/// <returns>The result of dividing this arbitrary-precision integer by
/// a 64-bit signed integer. The result of the division is rounded down
/// (the fractional part is discarded). Except if the result of the
/// division is 0, it will be negative if this arbitrary-precision
/// integer is positive and the other 64-bit signed integer is
/// negative, or vice versa, and will be positive if both are positive
/// or both are negative.</returns>
public EInteger Divide(long longValue) {
return this.Divide(EInteger.FromInt64(longValue));
}
/// <summary>Returns the remainder that would result when this
/// arbitrary-precision integer is divided by a 64-bit signed integer.
/// The remainder is the number that remains when the absolute value of
/// this arbitrary-precision integer is divided by the absolute value
/// of the other 64-bit signed integer; the remainder has the same sign
/// (positive or negative) as this arbitrary-precision
/// integer.</summary>
/// <param name='longValue'>The parameter <paramref name='longValue'/>
/// is a 64-bit signed integer.</param>
/// <returns>The remainder that would result when this
/// arbitrary-precision integer is divided by a 64-bit signed
/// integer.</returns>
public EInteger Remainder(long longValue) {
return this.Remainder(EInteger.FromInt64(longValue));
}
/// <summary>Compares an arbitrary-precision integer with this
/// instance.</summary>
/// <param name='longValue'>The parameter <paramref name='longValue'/>
/// is a 64-bit signed integer.</param>
/// <returns>Zero if the values are equal; a negative number if this
/// instance is less, or a positive number if this instance is
/// greater.</returns>
public int CompareTo(long longValue) {
return this.CompareTo(EInteger.FromInt64(longValue));
}
/// <summary>Divides this arbitrary-precision integer by a 64-bit
/// signed integer and returns a two-item array containing the result
/// of the division and the remainder, in that order. The result of the
/// division is rounded down (the fractional part is discarded). Except
/// if the result of the division is 0, it will be negative if this
/// arbitrary-precision integer is positive and the other 64-bit signed
/// integer is negative, or vice versa, and will be positive if both
/// are positive or both are negative. The remainder is the number that
/// remains when the absolute value of this arbitrary-precision integer
/// is divided by the absolute value of the other 64-bit signed
/// integer; the remainder has the same sign (positive or negative) as
/// this arbitrary-precision integer.</summary>
/// <param name='intDivisor'>The parameter <paramref
/// name='intDivisor'/> is a 64-bit signed integer.</param>
/// <returns>An array of two items: the first is the result of the
/// division as an arbitrary-precision integer, and the second is the
/// remainder as an arbitrary-precision integer. The result of division
/// is the result of the Divide method on the two operands, and the
/// remainder is the result of the Remainder method on the two
/// operands.</returns>
public EInteger[] DivRem(long intDivisor) {
return this.DivRem(EInteger.FromInt64(intDivisor));
}
/// <summary>Divides this arbitrary-precision integer by another
/// arbitrary-precision integer and returns a two-item array containing
/// the result of the division and the remainder, in that order. The
/// result of the division is rounded down (the fractional part is
/// discarded). Except if the result of the division is 0, it will be
/// negative if this arbitrary-precision integer is positive and the
/// other arbitrary-precision integer is negative, or vice versa, and
/// will be positive if both are positive or both are negative. The
/// remainder is the number that remains when the absolute value of
/// this arbitrary-precision integer is divided by the absolute value
/// of the other arbitrary-precision integer; the remainder has the
/// same sign (positive or negative) as this arbitrary-precision
/// integer.</summary>
/// <param name='divisor'>The number to divide by.</param>
/// <returns>An array of two items: the first is the result of the
/// division as an arbitrary-precision integer, and the second is the
/// remainder as an arbitrary-precision integer. The result of division
/// is the result of the Divide method on the two operands, and the
/// remainder is the result of the Remainder method on the two
/// operands.</returns>
/// <exception cref='DivideByZeroException'>The parameter <paramref
/// name='divisor'/> is 0.</exception>
/// <exception cref='ArgumentNullException'>The parameter <paramref
/// name='divisor'/> is null.</exception>
public EInteger[] DivRem(EInteger divisor) {
if (divisor == null) {
throw new ArgumentNullException(nameof(divisor));
}
int words1Size = this.wordCount;
int words2Size = divisor.wordCount;
if (words2Size == 0) {
// Divisor is 0
throw new DivideByZeroException();
}
if (words1Size < words2Size) {
// Dividend is less than divisor (includes case
// where dividend is 0)
return new[] { EInteger.Zero, this };
}
if (words2Size == 1) {
// divisor is small, use a fast path
var quotient = new short[this.wordCount];
int smallRemainder;
switch (divisor.words[0]) {
case 2:
smallRemainder = (int)FastDivideAndRemainderTwo(
quotient,
0,
this.words,
0,
words1Size);
break;
case 10:
smallRemainder = (int)FastDivideAndRemainderTen(
quotient,
0,
this.words,
0,
words1Size);
break;
default:
// DebugUtility.Log("smalldiv=" + (divisor.words[0]));
smallRemainder = ((int)FastDivideAndRemainder(
quotient,
0,
this.words,
0,
words1Size,
divisor.words[0])) & ShortMask;
break;
}
int count = this.wordCount;
while (count != 0 &&
quotient[count - 1] == 0) {
--count;
}
if (count == 0) {
return new[] { EInteger.Zero, this };
}
quotient = ShortenArray(quotient, count);
var bigquo = new EInteger(
count,
quotient,
this.negative ^ divisor.negative);
if (this.negative) {
smallRemainder = -smallRemainder;
}
return new[] { bigquo, EInteger.FromInt64(smallRemainder) };
}
if (this.CanFitInInt32() && divisor.CanFitInInt32()) {
long dividendSmall = this.ToInt32Checked();
long divisorSmall = divisor.ToInt32Checked();
if (dividendSmall != Int32.MinValue || divisorSmall != -1) {
long quotientSmall = dividendSmall / divisorSmall;
long remainderSmall = dividendSmall - (quotientSmall * divisorSmall);
return new[] {
EInteger.FromInt64(quotientSmall),
EInteger.FromInt64(remainderSmall),
};
}
} else if (this.CanFitInInt64() && divisor.CanFitInInt64()) {
long dividendLong = this.ToInt64Checked();
long divisorLong = divisor.ToInt64Checked();
if (dividendLong != Int64.MinValue || divisorLong != -1) {
long quotientLong = dividendLong / divisorLong;
long remainderLong = dividendLong - (quotientLong * divisorLong);
return new[] {
EInteger.FromInt64(quotientLong),
EInteger.FromInt64(remainderLong),
};
}
// DebugUtility.Log("int64divrem {0}/{1}"
// , this.ToInt64Checked(), divisor.ToInt64Checked());
}
// --- General case
var bigRemainderreg = new short[(int)words2Size];
var quotientreg = new short[(int)(words1Size - words2Size + 1)];
GeneralDivide(
this.words,
0,
this.wordCount,
divisor.words,
0,
divisor.wordCount,
quotientreg,
0,
bigRemainderreg,
0);
int remCount = CountWords(bigRemainderreg);
int quoCount = CountWords(quotientreg);
bigRemainderreg = ShortenArray(bigRemainderreg, remCount);
quotientreg = ShortenArray(quotientreg, quoCount);
EInteger bigrem = (remCount == 0) ? EInteger.Zero : new
EInteger(remCount, bigRemainderreg, this.negative);
EInteger bigquo2 = (quoCount == 0) ? EInteger.Zero : new
EInteger(quoCount, quotientreg, this.negative ^ divisor.negative);
return new[] { bigquo2, bigrem };
}
/// <summary>Determines whether this object and another object are
/// equal and have the same type.</summary>
/// <param name='obj'>The parameter <paramref name='obj'/> is an
/// arbitrary object.</param>
/// <returns><c>true</c> if this object and another object are equal;
/// otherwise, <c>false</c>.</returns>
public override bool Equals(object obj) {
var other = obj as EInteger;
if (other == null) {
return false;
}
if (this.wordCount == other.wordCount) {
if (this.negative != other.negative) {
return false;
}
for (var i = 0; i < this.wordCount; ++i) {
if (this.words[i] != other.words[i]) {
return false;
}
}
return true;
}
return false;
}
private static EInteger LeftShiftBigIntVar(EInteger ei,
EInteger bigShift) {
if (ei.IsZero) {
return ei;
}
while (bigShift.Sign > 0) {
var shift = 1000000;
if (bigShift.CompareTo((EInteger)1000000) < 0) {
shift = bigShift.ToInt32Checked();
}
ei <<= shift;
bigShift -= (EInteger)shift;
}
return ei;
}
private static long GcdLong(long u, long v) {
// Adapted from Christian Stigen Larsen's
// public domain GCD code
#if DEBUG
if (!(u >= 0 && v >= 0)) {
throw new ArgumentException("doesn't satisfy u>= 0 && v>= 0");
}
#endif
var shl = 0;
while (u != 0 && v != 0 && u != v) {
bool eu = (u & 1L) == 0;
bool ev = (v & 1L) == 0;
if (eu && ev) {
++shl;
u >>= 1;
v >>= 1;
} else if (eu && !ev) {
u >>= 1;
} else if (!eu && ev) {
v >>= 1;
} else if (u >= v) {
u = (u - v) >> 1;
} else {
long tmp = u;
u = (v - u) >> 1;
v = tmp;
}
}
return (u == 0) ? (v << shl) : (u << shl);
}
/// <summary>Returns the greatest common divisor of this integer and
/// the given integer. The greatest common divisor (GCD) is also known
/// as the greatest common factor (GCF). This method works even if
/// either or both integers are negative.</summary>
/// <param name='bigintSecond'>Another arbitrary-precision integer. Can
/// be negative.</param>
/// <returns>The greatest common divisor of this integer and the given
/// integer.</returns>
/// <exception cref='ArgumentNullException'>The parameter <paramref
/// name='bigintSecond'/> is null.</exception>
/// <exception cref='DivideByZeroException'>Attempted to divide by
/// zero.</exception>
/// <exception cref='ArgumentException'>BigPower is
/// negative.</exception>
public EInteger Gcd(EInteger bigintSecond) {
if (bigintSecond == null) {
throw new ArgumentNullException(nameof(bigintSecond));
}
if (this.IsZero) {
return bigintSecond.Abs();
}
EInteger thisValue = this.Abs();
if (bigintSecond.IsZero) {
return thisValue;
}
bigintSecond = bigintSecond.Abs();
if (bigintSecond.Equals(EInteger.One) ||
thisValue.Equals(bigintSecond)) {
return bigintSecond;
}
if (thisValue.Equals(EInteger.One)) {
return thisValue;
}
if (Math.Max(thisValue.wordCount, bigintSecond.wordCount) > 12) {
// if (Math.Max(thisValue.wordCount, bigintSecond.wordCount) > 250) {
return SubquadraticGCD(thisValue, bigintSecond);
} else {
return BaseGcd(thisValue, bigintSecond);
}
}
private static EInteger BaseGcd(EInteger thisValue, EInteger bigintSecond) {
if (thisValue.CanFitInInt64() && bigintSecond.CanFitInInt64()) {
long u = thisValue.ToInt64Unchecked();
long v = bigintSecond.ToInt64Unchecked();
return EInteger.FromInt64(GcdLong(u, v));
} else {
bool bigger = thisValue.CompareTo(bigintSecond) >= 0;
if (!bigger) {
EInteger ta = thisValue;
thisValue = bigintSecond;
bigintSecond = ta;
}
EInteger eia = thisValue;
EInteger eib = bigintSecond;
// DebugUtility.Log("wc="+eia.wordCount+"/"+eib.wordCount);
while (eib.wordCount > 3) {
// Lehmer's algorithm
EInteger eiaa, eibb, eicc, eidd;
EInteger eish = eia.GetUnsignedBitLengthAsEInteger();
eish = eish.Subtract(48);
EInteger eiee = eia.ShiftRight(eish);
EInteger eiff = eib.ShiftRight(eish);
eiaa = eidd = EInteger.One;
eibb = eicc = EInteger.Zero;
while (true) {
EInteger eifc = eiff.Add(eicc);
EInteger eifd = eiff.Add(eidd);
if (eifc.IsZero || eifd.IsZero) {
EInteger ta = eibb.IsZero ? eib :
eia.Multiply(eiaa).Add(eib.Multiply(eibb));
EInteger tb = eibb.IsZero ? eia.Remainder(eib) :
eia.Multiply(eicc).Add(eib.Multiply(eidd));
eia = ta;
eib = tb;
// DebugUtility.Log("z tawc="+eia.wordCount+"/"+eib.wordCount);
break;
}
EInteger eiq = eiee.Add(eiaa).Divide(eifc);
EInteger eiq2 = eiee.Add(eibb).Divide(eifd);
if (!eiq.Equals(eiq2)) {
EInteger ta = eibb.IsZero ? eib :
eia.Multiply(eiaa).Add(eib.Multiply(eibb));
EInteger tb = eibb.IsZero ? eia.Remainder(eib) :
eia.Multiply(eicc).Add(eib.Multiply(eidd));
// DebugUtility.Log("eia/b="+eia.wordCount+"/"+eib.wordCount);
// DebugUtility.Log("eiaa/bb="+eiaa.wordCount+"/"+eibb.wordCount);
eia = ta;
eib = tb;
break;
} else if (eiq.CanFitInInt32() &&
eidd.CanFitInInt32() && eicc.CanFitInInt32()) {
EInteger t = eiff;
// DebugUtility.Log("eiq eiffccdd="+eiff.wordCount+"/"+
// eicc.wordCount+"/"+eidd.wordCount);
int eiqi = eiq.ToInt32Checked();
eiff = eiee.Subtract(eiff.Multiply(eiqi));
eiee = t;
t = eicc;
eicc = eiaa.Subtract((long)eicc.ToInt32Checked() * eiqi);
eiaa = t;
t = eidd;
eidd = eibb.Subtract((long)eidd.ToInt32Checked() * eiqi);
// DebugUtility.Log("->eiffccdd="+eiff.wordCount+"/"+
// eicc.wordCount+"/"+eidd.wordCount);
eibb = t;
} else {
EInteger t = eiff;
// DebugUtility.Log("eiffccdd="+eiff.wordCount+"/"+
// eicc.wordCount+"/"+eidd.wordCount);
eiff = eiee.Subtract(eiff.Multiply(eiq));
eiee = t;
t = eicc;
eicc = eiaa.Subtract(eicc.Multiply(eiq));
eiaa = t;
t = eidd;
eidd = eibb.Subtract(eidd.Multiply(eiq));
// DebugUtility.Log("->eiffccdd="+eiff.wordCount+"/"+
// eicc.wordCount+"/"+eidd.wordCount);
eibb = t;
}
}
}
if (eib.IsZero) {
return eia;
}
while (!eib.IsZero) {
if (eia.wordCount <= 3 && eib.wordCount <= 3) {
return EInteger.FromInt64(
GcdLong(eia.ToInt64Checked(), eib.ToInt64Checked()));
}
EInteger ta = eib;
eib = eia.Remainder(eib);
eia = ta;
}
return eia;
}
}
private static EInteger MinBitLength(EInteger eia, EInteger eib) {
return EInteger.Min(BL(eia), BL(eib));
}
private static EInteger MaxBitLength(EInteger eia, EInteger eib) {
return EInteger.Max(BL(eia), BL(eib));
}
private static void SDivStep(EInteger[] eiam, EInteger eis) {
// a, b, m[0] ... m[3]
if (eiam[0].CompareTo(eiam[1]) > 0) {
// a > b
EInteger eia = eiam[0];
EInteger eib = eiam[1];
EInteger[] divrem = eia.DivRem(eib);
if (BL(divrem[1]).CompareTo(eis) <= 0) {
divrem[0] = divrem[0].Subtract(1);
if (divrem[0].Sign < 0) {
throw new InvalidOperationException();
}
divrem[1] = divrem[1].Add(eib);
}
eiam[3] = eiam[3].Add(eiam[2].Multiply(divrem[0]));
eiam[5] = eiam[5].Add(eiam[4].Multiply(divrem[0]));
eiam[0] = divrem[1];
} else {
// a <= b
EInteger eia = eiam[1];
EInteger eib = eiam[0];
EInteger[] divrem = eia.DivRem(eib);
if (BL(divrem[1]).CompareTo(eis) <= 0) {
divrem[0] = divrem[0].Subtract(1);
if (divrem[0].Sign < 0) {
throw new InvalidOperationException();
}
divrem[1] = divrem[1].Add(eib);
}
eiam[2] = eiam[2].Add(eiam[3].Multiply(divrem[0]));
eiam[4] = eiam[4].Add(eiam[5].Multiply(divrem[0]));
eiam[1] = divrem[1];
}
}
private static void LSDivStep(long[] longam, long ls) {
if (longam[0] < 0) {
throw new ArgumentException("longam[0] (" + longam[0] + ") is not" +
"\u0020greater or equal to 0");
}
if (longam[1] < 0) {
throw new ArgumentException("longam[1] (" + longam[1] + ") is not" +
"\u0020greater or equal to 0");
}
checked {
// a, b, m[0] ... m[3]
if (longam[0] > longam[1]) {
// a > b
long a = longam[0];
long b = longam[1];
long ddiv = a / b;
var ldivrem = new long[] {
ddiv, a - (ddiv * b),
};
if (LBL(ldivrem[1]) <= ls) {
--ldivrem[0];
if (ldivrem[0] < 0) {
throw new InvalidOperationException();
}
ldivrem[1] += b;
}
longam[3] += longam[2] * ldivrem[0];
longam[5] += longam[4] * ldivrem[0];
longam[0] = ldivrem[1];
} else {
// a <= b
long a = longam[1];
long b = longam[0];
long ddiv = a / b;
var ldivrem = new long[] {
ddiv, a - (ddiv * b),
};
if (LBL(ldivrem[1]) <= ls) {
--ldivrem[0];
if (ldivrem[0] < 0) {
throw new InvalidOperationException();
}
ldivrem[1] += b;
}
longam[2] += longam[3] * ldivrem[0];
longam[4] += longam[5] * ldivrem[0];
longam[1] = ldivrem[1];
}
}
}
private static EInteger BL(EInteger eia) {
if (eia.IsZero) {
return EInteger.Zero;
}
EInteger ret = eia.GetUnsignedBitLengthAsEInteger();
return ret;
}
private static int LBL(long mantlong) {
#if DEBUG
if (mantlong < Int64.MinValue + 1) {
throw new InvalidOperationException("\"mantlong\" (" + mantlong + ")" +
"\u0020is not" + "\u0020greater or equal to " + Int64.MinValue + 1);
}
#endif
return (mantlong == 0) ? 0 : NumberUtility.BitLength(Math.Abs(mantlong));
}
private static long[] LHalfGCD(long longa, long longb) {
#if DEBUG
if (longa < 0) {
throw new InvalidOperationException("\"longa\" (" + longa + ") is not" +
"\u0020greater or equal to 0");
}
if (longb < 0) {
throw new InvalidOperationException("\"longb\" (" + longb + ") is not" +
"\u0020greater or equal to 0");
}
#endif
if (longa == 0 || longb == 0) {
// DebugUtility.Log("LHalfGCD failed");
return new long[] { longa, longb, 1, 0, 0, 1 };
}
long olonga = longa;
long olongb = longb;
var ret = new long[6];
// DebugUtility.Log("LHalfGCD " + longa + " " + longb);
checked {
int ln = Math.Max(LBL(longa), LBL(longb));
int lnmin = Math.Min(LBL(longa), LBL(longb));
int ls = (ln >> 1) + 1;
if (lnmin <= ls) {
// DebugUtility.Log("LHalfGCD failed: nmin<= s");
return new long[] { longa, longb, 1, 0, 0, 1 };
}
if (lnmin > ((ln * 3) >> 2) + 2) {
int p1 = ln >> 1;
long nhalfmask = (1L << p1) - 1;
long longah = longa >> p1;
long longal = longa & nhalfmask;
long longbh = longb >> p1;
long longbl = longb & nhalfmask;
long[] ret2 = LHalfGCD(longah, longbh);
if (ret2 == null) {
return null;
}
Array.Copy(ret2, 0, ret, 0, 6);
longa = (longal * ret2[5]) - (longbl * ret2[3]);
longb = (longbl * ret2[2]) - (longal * ret2[4]);
longa += ret2[0] << p1;
longb += ret2[1] << p1;
if (longa < 0 || longb < 0) {
throw new InvalidOperationException(
"Internal error: longa=" + olonga + " olongb=" +
olongb);
}
} else {
// Set M to identity
ret[2] = 1;
ret[3] = 0;
ret[4] = 0;
ret[5] = 1;
}
ret[0] = longa;
ret[1] = longb;
while (Math.Max(LBL(ret[0]), LBL(ret[1])) > ((ln * 3) >> 2) + 1 &&
LBL(ret[0] - ret[1]) > ls) {
if (ret[0] < 0 || ret[1] < 0) {
throw new InvalidOperationException(
"Internal error: longa=" + olonga + " olongb=" +
olongb);
}
LSDivStep(ret, ls);
}
longa = ret[0];
longb = ret[1];
if (Math.Min(LBL(longa), LBL(longb)) > ls + 2) {
ln = Math.Max(LBL(longa), LBL(longb));
int p1 = ((ls * 2) - ln) + 1;
long nhalfmask = (1L << p1) - 1;
long longah = longa >> p1;
long longal = longa & nhalfmask;
long longbh = longb >> p1;
long longbl = longb & nhalfmask;
long[] ret2 = LHalfGCD(longah, longbh);
if (ret2 == null) {
return null;
}
longa = (longal * ret2[5]) - (longbl * ret2[3]);
longb = (longbl * ret2[2]) - (longal * ret2[4]);
longa += ret2[0] << p1;
longb += ret2[1] << p1;
if (longa < 0 || longb < 0) {
throw new InvalidOperationException("Internal error");
}
long ma, mb, mc, md;
ma = (ret[2] * ret2[2]) + (ret[3] * ret2[4]);
mb = (ret[2] * ret2[3]) + (ret[3] * ret2[5]);
mc = (ret[4] * ret2[2]) + (ret[5] * ret2[4]);
md = (ret[4] * ret2[3]) + (ret[5] * ret2[5]);
ret[2] = ma;
ret[3] = mb;
ret[4] = mc;
ret[5] = md;
}
ret[0] = longa;
ret[1] = longb;
while (LBL(ret[0] - ret[1]) > ls) {
if (ret[0] < 0 || ret[1] < 0) {
throw new InvalidOperationException("Internal error");
}
LSDivStep(ret, ls);
}
if (ret[0] < 0 || ret[1] < 0) {
throw new InvalidOperationException("Internal error");
}
#if DEBUG
/* long[] lret3 = SlowSgcd(olonga, olongb);
if (ret[0] != lret3[0] || ret[1] != lret3[1] ||
ret[2] != lret3[2] || ret[3] != lret3[3] ||
ret[4] != lret3[4] || ret[5] != lret3[5]) {
var sb = new StringBuilder();
sb.Append("eia1=" + olonga + "\n");
sb.Append("eib1=" + olongb + "\n");
for (int k = 0; k < 6; ++k) {
sb.Append("expected_" + k + "=" + lret3[k] + "\n");
sb.Append("got______" + k + "=" + ret[k] + "\n");
}
throw new InvalidOperationException("" + sb);
}
*/
// Verify det(M) == 1
if (ret[2] < 0 || ret[3] < 0 || ret[4] < 0 ||
ret[5] < 0) {
throw new InvalidOperationException("Internal error");
}
if ((ret[2] * ret[5]) - (ret[3] * ret[4]) != 1) {
throw new InvalidOperationException("Internal error");
}
if (LBL(ret[0] - ret[1]) > ls) {
throw new InvalidOperationException("Internal error");
}
#endif
}
return ret;
}
private static long[] SlowSgcd(long longa, long longb) {
var ret = new long[] { longa, longb, 1, 0, 0, 1 };
int ls = Math.Max(LBL(longa), LBL(longb));
ls = (ls >> 1) + 1;
while (LBL(ret[0] - ret[1]) > ls) {
LSDivStep(ret, ls);
}
return ret;
}
private static EInteger[] SlowSgcd(EInteger eia, EInteger eib) {
var ret = new EInteger[] {
eia, eib, EInteger.One, EInteger.Zero,
EInteger.Zero, EInteger.One,
};
EInteger eis = EInteger.Max(BL(eia), BL(eib));
eis = eis.ShiftRight(1).Add(1);
while (BL(ret[0].Subtract(ret[1])).CompareTo(eis) > 0) {
SDivStep(ret, eis);
}
return ret;
}
// Implements Niels Moeller's Half-GCD algorithm from 2008
private static EInteger[] HalfGCD(EInteger eia, EInteger eib) {
if (eia.Sign < 0) {
throw new InvalidOperationException("doesn't satisfy !eia.IsNegative");
}
if (eib.Sign < 0) {
throw new InvalidOperationException("doesn't satisfy !eib.IsNegative");
}
EInteger oeia = eia;
EInteger oeib = eib;
if (eia.IsZero || eib.IsZero) {
// DebugUtility.Log("HalfGCD failed");
return new EInteger[] {
eia, eib, EInteger.One, EInteger.Zero,
EInteger.Zero, EInteger.One,
};
}
var ret = new EInteger[6];
// DebugUtility.Log("HalfGCD " + eia + " " + eib);
if (eia.CanFitInInt64() && eib.CanFitInInt64()) {
long[] lret = LHalfGCD(eia.ToInt64Checked(), eib.ToInt64Checked());
if (lret == null) {
return null;
}
for (int i = 0; i < 6; ++i) {
ret[i] = EInteger.FromInt64(lret[i]);
}
return ret;
}
EInteger ein = MaxBitLength(eia, eib);
EInteger einmin = MinBitLength(eia, eib);
long ln = ein.CanFitInInt64() ? ein.ToInt64Checked() : -1;
EInteger eis = ein.ShiftRight(1).Add(1);
if (einmin.CompareTo(eis) <= 0) {
// DebugUtility.Log("HalfGCD failed: nmin<= s");
return new EInteger[] {
eia, eib, EInteger.One, EInteger.Zero,
EInteger.Zero, EInteger.One,
};
}
EInteger eiah, eial, eibh, eibl;
if (einmin.CompareTo(ein.Multiply(3).ShiftRight(2).Add(2)) > 0) {
EInteger p1 = ein.ShiftRight(1);
#if DEBUG
if (!(eia.Sign >= 0)) {
throw new ArgumentException("doesn't satisfy eia.Sign>= 0");
}
if (!(eib.Sign >= 0)) {
throw new ArgumentException("doesn't satisfy eib.Sign>= 0");
}
#endif
eiah = eia.ShiftRight(p1);
eial = eia.LowBits(p1);
eibh = eib.ShiftRight(p1);
eibl = eib.LowBits(p1);
EInteger[] ret2 = HalfGCD(eiah, eibh);
if (ret2 == null) {
return null;
}
Array.Copy(ret2, 0, ret, 0, 6);
eia = eial.Multiply(ret2[5]).Subtract(eibl.Multiply(ret2[3]));
eib = eibl.Multiply(ret2[2]).Subtract(eial.Multiply(ret2[4]));
eia = eia.Add(ret2[0].ShiftLeft(p1));
eib = eib.Add(ret2[1].ShiftLeft(p1));
if (eia.Sign < 0 || eib.Sign < 0) {
throw new InvalidOperationException(
"Internal error: oeia=" + oeia + " oeib=" +
oeib + " eiah=" + eiah + " eibh=" + eibh);
}
} else {
// Set M to identity
ret[2] = ret[5] = EInteger.FromInt32(1);
ret[3] = ret[4] = EInteger.FromInt32(0);
}
ret[0] = eia;
ret[1] = eib;
/*
for (int k = 0; k < 6; ++k) {
DebugUtility.Log("ret_afterloop1_"+ k + "=" +
ret[k].ToRadixString(16));
}
*/ while (MaxBitLength(ret[0], ret[1]).CompareTo(
ein.Multiply(3).ShiftRight(2).Add(1)) > 0 &&
BL(ret[0].Subtract(ret[1])).CompareTo(eis) > 0) {
if (ret[0].Sign < 0 || ret[1].Sign < 0) {
throw new InvalidOperationException(
"Internal error: eia=" + oeia + " oeib=" +
oeib);
}
SDivStep(ret, eis);
// for (int k = 0; k < 6; ++k) {
// DebugUtility.Log("ret_loop2_"+ k + "=" + ret[k].ToRadixString(16));
// }
}
// for (int k = 0; k < 6; ++k) {
// DebugUtility.Log("ret_afterloop2_"+ k + "=" +
// ret[k].ToRadixString(16));
// }
eia = ret[0];
eib = ret[1];
if (MinBitLength(eia, eib).CompareTo(eis.Add(2)) > 0) {
ein = MaxBitLength(eia, eib);
EInteger p1 = eis.Add(eis).Subtract(ein).Add(1);
eiah = eia.ShiftRight(p1);
eial = eia.LowBits(p1);
eibh = eib.ShiftRight(p1);
eibl = eib.LowBits(p1);
EInteger[] ret2 = HalfGCD(eiah, eibh);
if (ret2 == null) {
return null;
}
eia = eial.Multiply(ret2[5]).Subtract(eibl.Multiply(ret2[3]));
eib = eibl.Multiply(ret2[2]).Subtract(eial.Multiply(ret2[4]));
eia = eia.Add(ret2[0].ShiftLeft(p1));
eib = eib.Add(ret2[1].ShiftLeft(p1));
if (eia.Sign < 0 || eib.Sign < 0) {
throw new InvalidOperationException("Internal error");
}
EInteger ma, mb, mc, md;
// DebugUtility.Log("m "+Arrays.toString(new
// EInteger[] { ret[2], ret[3], ret[4], ret[5]}));
// DebugUtility.Log("m' "+Arrays.toString(new
// EInteger[] { ret2[2], ret2[3], ret2[4], ret2[5]}));
ma = ret[2].Multiply(ret2[2]).Add(ret[3].Multiply(ret2[4]));
mb = ret[2].Multiply(ret2[3]).Add(ret[3].Multiply(ret2[5]));
mc = ret[4].Multiply(ret2[2]).Add(ret[5].Multiply(ret2[4]));
md = ret[4].Multiply(ret2[3]).Add(ret[5].Multiply(ret2[5]));
ret[2] = ma;
ret[3] = mb;
ret[4] = mc;
ret[5] = md;
// DebugUtility.Log("newm "+Arrays.toString(ret));
}
ret[0] = eia;
ret[1] = eib;
// for (int k = 0; k < 6; ++k) {
// DebugUtility.Log("ret_afterloop3["+k+"]=" +
// ret[k].ToRadixString(16));
// }
while (BL(ret[0].Subtract(ret[1])).CompareTo(eis) > 0) {
if (ret[0].Sign < 0 || ret[1].Sign < 0) {
throw new InvalidOperationException("Internal error");
}
SDivStep(ret, eis);
// DebugUtility.Log("[sdiv2]ret="+Arrays.toString(ret));
}
#if DEBUG
/* EInteger[] ret3 = SlowSgcd(oeia, oeib);
if (!ret[0].Equals(ret3[0]) ||
!ret[1].Equals(ret3[1]) ||
!ret[2].Equals(ret3[2]) ||
!ret[3].Equals(ret3[3]) ||
!ret[4].Equals(ret3[4]) ||
!ret[5].Equals(ret3[5])) {
var sb = new StringBuilder();
sb.Append("eia1=" + oeia + "\n");
sb.Append("eib1=" + oeib + "\n");
for (int k = 0; k < 6; ++k) {
sb.Append("expected_" + k + "=" + ret3[k] + "\n");
sb.Append("got______" + k + "=" + ret[k] + "\n");
}
throw new InvalidOperationException("" + sb);
}
*/
if (ret[0].Sign < 0 || ret[1].Sign < 0) {
throw new InvalidOperationException("Internal error");
}
// Verify det(M) == 1
if (ret[2].Sign < 0 || ret[3].Sign < 0 || ret[4].Sign < 0 ||
ret[5].Sign < 0) {
throw new InvalidOperationException("Internal error");
}
if
(ret[2].Multiply(ret[5]).Subtract(ret[3].Multiply(ret[4])).CompareTo(1) !=
0) {
throw new InvalidOperationException("Internal error");
}
if (BL(ret[0].Subtract(ret[1])).CompareTo(eis) > 0) {
throw new InvalidOperationException("Internal error");
}
#endif
return ret;
}
private static EInteger SubquadraticGCD(EInteger eia, EInteger eib) {
EInteger ein = MaxBitLength(eia, eib);
var ret = new EInteger[] { eia, eib };
while (true) {
if (ein.CompareTo(48) < 0) {
break;
}
// DebugUtility.Log("eia=" + ret[0].ToRadixString(16));
// DebugUtility.Log("eib=" + ret[1].ToRadixString(16));
EInteger nhalf = ein.ShiftRight(1);
EInteger eiah = ret[0].ShiftRight(nhalf);
EInteger eial = ret[0].LowBits(nhalf);
EInteger eibh = ret[1].ShiftRight(nhalf);
EInteger eibl = ret[1].LowBits(nhalf);
// DebugUtility.Log("eiah->" + eiah.ToRadixString(16));
// DebugUtility.Log("eibh->" + eibh.ToRadixString(16));
EInteger[] hgcd = HalfGCD(eiah, eibh);
if (hgcd == null) {
// DebugUtility.Log("hgcd failed");
break;
}
eia = eial.Multiply(hgcd[5]).Subtract(eibl.Multiply(hgcd[3]));
eib = eibl.Multiply(hgcd[2]).Subtract(eial.Multiply(hgcd[4]));
eia = eia.Add(hgcd[0].ShiftLeft(nhalf));
eib = eib.Add(hgcd[1].ShiftLeft(nhalf));
// DebugUtility.Log("eia->" + eia.ToRadixString(16));
// DebugUtility.Log("eib->" + eib.ToRadixString(16));
if (eia.Sign < 0 || eib.Sign < 0) {
var sb = new StringBuilder();
sb.Append("eia=" + ret[0] + "\n");
sb.Append("eib=" + ret[1] + "\n");
for (int k = 0; k < 6; ++k) {
sb.Append("hgcd_" + k + "=" + hgcd[k].ToRadixString(16));
sb.Append("\n");
}
throw new InvalidOperationException("Internal error\n" + sb);
}
if (ret[0].Equals(eia) && ret[1].Equals(eib)) {
// Didn't change
break;
}
ein = MaxBitLength(eia, eib);
ret[0] = eia;
ret[1] = eib;
}
// DebugUtility.Log("eia final "+eia.ToRadixString(16));
// DebugUtility.Log("eib final "+eib.ToRadixString(16));
return BaseGcd(ret[0], ret[1]);
}
/// <summary>Returns the number of decimal digits used by this integer,
/// in the form of an arbitrary-precision integer.</summary>
/// <returns>The number of digits in the decimal form of this integer.
/// Returns 1 if this number is 0.</returns>
public EInteger GetDigitCountAsEInteger() {
// NOTE: All digit counts can currently fit in Int64, so just
// use GetDigitCountAsInt64 for the time being
return EInteger.FromInt64(this.GetDigitCountAsInt64());
}
/// <summary>Returns the number of decimal digits used by this
/// integer.</summary>
/// <returns>The number of digits in the decimal form of this integer.
/// Returns 1 if this number is 0.</returns>
/// <exception cref='OverflowException'>The return value would exceed
/// the range of a 32-bit signed integer.</exception>
[Obsolete("This method may overflow. Use GetDigitCountAsEInteger instead.")]
public int GetDigitCount() {
long dc = this.GetDigitCountAsInt64();
if (dc < Int32.MinValue || dc > Int32.MaxValue) {
throw new OverflowException();
}
return checked((int)dc);
}
/// <summary>Returns the number of decimal digits used by this integer,
/// in the form of a 64-bit signed integer.</summary>
/// <returns>The number of digits in the decimal form of this integer.
/// Returns 1 if this number is 0. Returns 2^63 - 1(
/// <c>Int64.MaxValue</c> in.NET or <c>Long.MAX_VALUE</c> in Java) if
/// the number of decimal digits is 2^63 - 1 or greater. (Use
/// <c>GetDigitCountAsEInteger</c> instead if the application relies on
/// the exact number of decimal digits.).</returns>
public long GetDigitCountAsInt64() {
// NOTE: Currently can't be 2^63-1 or greater, due to int32 word counts
EInteger ei = this;
long retval;
if (ei.IsZero) {
return 1;
}
retval = 0L;
while (true) {
if (ei.CanFitInInt64()) {
long value = ei.ToInt64Checked();
if (value == 0) {
// Treat zero after division as having no digits
break;
}
if (value == Int64.MinValue) {
retval += 19;
break;
}
if (value < 0) {
value = -value;
}
if (value >= 1000000000L) {
retval += (value >= 1000000000000000000L) ? 19 : ((value >=
100000000000000000L) ? 18 : ((value >= 10000000000000000L) ?
17 : ((value >= 1000000000000000L) ? 16 :
((value >= 100000000000000L) ? 15 : ((value
>= 10000000000000L) ?
14 : ((value >= 1000000000000L) ? 13 : ((value
>= 100000000000L) ? 12 : ((value >=
10000000000L) ?
11 : ((value >= 1000000000L) ? 10 : 9)))))))));
} else {
var v2 = (int)value;
retval += (v2 >= 100000000) ? 9 : ((v2 >= 10000000) ? 8 : ((v2 >=
1000000) ? 7 : ((v2 >= 100000) ? 6 : ((v2
>= 10000) ? 5 : ((v2 >= 1000) ? 4 : ((v2 >= 100) ?
3 : ((v2 >= 10) ? 2 : 1)))))));
}
break;
}
// NOTE: Bitlength accurate for wordCount<1000000 here, only as
// an approximation
int bitlen = (ei.wordCount < 1000000) ?
(int)ei.GetUnsignedBitLengthAsInt64() :
Int32.MaxValue;
var maxDigits = 0;
var minDigits = 0;
if (bitlen <= 2135) {
// (x*631305) >> 21 is an approximation
// to trunc(x*log10(2)) that is correct up
// to x = 2135; the multiplication would require
// up to 31 bits in all cases up to 2135
// (cases up to 63 are already handled above)
minDigits = 1 + (((bitlen - 1) * 631305) >> 21);
maxDigits = 1 + ((bitlen * 631305) >> 21);
if (minDigits == maxDigits) {
// Number of digits is the same for
// all numbers with this bit length
retval += minDigits;
break;
}
} else if (bitlen <= 6432162) {
// Much more accurate approximation
// Approximation of ln(2)/ln(10)
minDigits = 1 + (int)(((long)(bitlen - 1) * 661971961083L) >> 41);
maxDigits = 1 + (int)(((long)bitlen * 661971961083L) >> 41);
if (minDigits == maxDigits) {
// Number of digits is the same for
// all numbers with this bit length
retval += minDigits;
break;
}
}
if (ei.wordCount >= 100) {
long digits = ei.wordCount * 3;
EInteger pow = NumberUtility.FindPowerOfTen(digits);
EInteger div = ei.Divide(pow);
retval += digits;
ei = div;
continue;
}
if (bitlen <= 2135) {
retval += ei.Abs().CompareTo(NumberUtility.FindPowerOfTen(
minDigits)) >= 0 ? maxDigits : minDigits;
break;
} else if (bitlen < 50000) {
retval += ei.Abs().CompareTo(NumberUtility.FindPowerOfTen(
minDigits + 1)) >= 0 ? maxDigits + 1 : minDigits + 1;
break;
}
short[] tempReg = null;
int currentCount = ei.wordCount;
var done = false;
while (!done && currentCount != 0) {
if (currentCount == 1 || (currentCount == 2 && tempReg[1] == 0)) {
int rest = ((int)tempReg[0]) & ShortMask;
if (rest >= 10000) {
retval += 5;
} else if (rest >= 1000) {
retval += 4;
} else if (rest >= 100) {
retval += 3;
} else if (rest >= 10) {
retval += 2;
} else {
++retval;
}
break;
}
if (currentCount == 2 && tempReg[1] > 0 && tempReg[1] <= 0x7fff) {
int rest = ((int)tempReg[0]) & ShortMask;
rest |= (((int)tempReg[1]) & ShortMask) << 16;
if (rest >= 1000000000) {
retval += 10;
} else if (rest >= 100000000) {
retval += 9;
} else if (rest >= 10000000) {
retval += 8;
} else if (rest >= 1000000) {
retval += 7;
} else if (rest >= 100000) {
retval += 6;
} else if (rest >= 10000) {
retval += 5;
} else if (rest >= 1000) {
retval += 4;
} else if (rest >= 100) {
retval += 3;
} else if (rest >= 10) {
retval += 2;
} else {
++retval;
}
break;
} else {
int wci = currentCount;
short remainderShort = 0;
int quo, rem;
var firstdigit = false;
short[] dividend = tempReg ?? ei.words;
// Divide by 10000
while (!done && (wci--) > 0) {
int curValue = ((int)dividend[wci]) & ShortMask;
int currentDividend = unchecked((int)(curValue |
((int)remainderShort << 16)));
quo = currentDividend / 10000;
if (!firstdigit && quo != 0) {
firstdigit = true;
// Since we are dividing from left to right, the first
// nonzero result is the first part of the
// new quotient
// NOTE: Bitlength accurate for wci<1000000 here, only as
// an approximation
bitlen = (wci < 1000000) ? GetUnsignedBitLengthEx(
quo,
wci + 1) :
Int32.MaxValue;
if (bitlen <= 2135) {
// (x*631305) >> 21 is an approximation
// to trunc(x*log10(2)) that is correct up
// to x = 2135; the multiplication would require
// up to 31 bits in all cases up to 2135
// (cases up to 64 are already handled above)
minDigits = 1 + (((bitlen - 1) * 631305) >> 21);
maxDigits = 1 + ((bitlen * 631305) >> 21);
if (minDigits == maxDigits) {
// Number of digits is the same for
// all numbers with this bit length
// NOTE: The 4 is the number of digits just
// taken out of the number, and "i" is the
// number of previously known digits
retval += minDigits + 4;
done = true;
break;
}
if (minDigits > 1) {
int maxDigitEstimate = maxDigits + 4;
int minDigitEstimate = minDigits + 4;
retval += ei.Abs().CompareTo(NumberUtility.FindPowerOfTen(
minDigitEstimate)) >= 0 ? retval +
maxDigitEstimate : retval +
minDigitEstimate;
done = true;
break;
}
} else if (bitlen <= 6432162) {
// Much more accurate approximation
// Approximation of ln(2)/ln(10)
minDigits = 1 + (int)(((long)(bitlen - 1) * 661971961083L) >>
41);
maxDigits = 1 + (int)(((long)bitlen * 661971961083L) >> 41);
if (minDigits == maxDigits) {
// Number of digits is the same for
// all numbers with this bit length
retval += minDigits + 4;
done = true;
break;
}
}
}
if (tempReg == null) {
if (quo != 0) {
tempReg = new short[ei.wordCount];
Array.Copy(ei.words, tempReg, tempReg.Length);
// Use the calculated word count during division;
// zeros that may have occurred in division
// are not incorporated in the tempReg
currentCount = wci + 1;
tempReg[wci] = unchecked((short)quo);
}
} else {
tempReg[wci] = unchecked((short)quo);
}
rem = currentDividend - (10000 * quo);
remainderShort = unchecked((short)rem);
}
// Recalculate word count
while (currentCount != 0 && tempReg[currentCount - 1] == 0) {
--currentCount;
}
retval += 4;
}
}
}
return retval;
}
/// <summary>Returns the hash code for this instance. No application or
/// process IDs are used in the hash code calculation.</summary>
/// <returns>A 32-bit signed integer.</returns>
public override int GetHashCode() {
var hashCodeValue = 0;
unchecked {
hashCodeValue += 1000000007 * this.Sign;
if (this.words != null) {
for (var i = 0; i < this.wordCount; ++i) {
hashCodeValue += 1000000013 * this.words[i];
}
}
}
return hashCodeValue;
}
/// <summary>Gets the bit position of the lowest set bit in this
/// number's absolute value. (This will also be the position of the
/// lowest set bit in the number's two's-complement form (see
/// <see cref='PeterO.Numbers.EDecimal'>"Forms of numbers"</see>
/// ).).</summary>
/// <returns>The bit position of the lowest bit set in the number's
/// absolute value, starting at 0. Returns -1 if this value is
/// 0.</returns>
[Obsolete("This method may overflow. Use GetLowBitAsEInteger instead.")]
public int GetLowBit() {
return this.GetLowBitAsEInteger().ToInt32Checked();
}
/// <summary>Gets the bit position of the lowest set bit in this
/// number's absolute value, in the form of a 64-bit signed integer.
/// (This will also be the position of the lowest set bit in the
/// number's two's-complement form (see
/// <see cref='PeterO.Numbers.EDecimal'>"Forms of numbers"</see>
/// ).).</summary>
/// <returns>The bit position of the lowest bit set in the number's
/// absolute value, starting at 0. Returns -1 if this value is 0 or
/// odd. Returns 2^63 - 1 ( <c>Int64.MaxValue</c> in.NET or
/// <c>Long.MAX_VALUE</c> in Java) if this number is other than zero
/// but the lowest set bit is at 2^63 - 1 or greater. (Use
/// <c>GetLowBitAsEInteger</c> instead if the application relies on the
/// exact value of the lowest set bit position.).</returns>
public long GetLowBitAsInt64() {
// NOTE: Currently can't be 2^63-1 or greater, due to int32 word counts
long retSetBitLong = 0;
for (var i = 0; i < this.wordCount; ++i) {
int c = ((int)this.words[i]) & ShortMask;
if (c == 0) {
retSetBitLong += 16;
} else {
int rsb = (((c << 15) & ShortMask) != 0) ? 0 : ((((c <<
14) & ShortMask) != 0) ? 1 : ((((c <<
13) & ShortMask) != 0) ? 2 : ((((c <<
12) & ShortMask) != 0) ? 3 : ((((c << 11) &
0xffff) != 0) ? 4 : ((((c << 10) & ShortMask) != 0) ?
5 : ((((c << 9) & ShortMask) != 0) ? 6 : ((((c <<
8) & ShortMask) != 0) ? 7 : ((((c << 7) &
ShortMask) != 0) ? 8 : ((((c << 6) & ShortMask) != 0) ? 9 :
((((c << 5) & ShortMask) != 0) ? 10 : ((((c <<
4) & ShortMask) != 0) ? 11 : ((((c << 3) &
0xffff) != 0) ? 12 : ((((c << 2) &
0xffff) != 0) ? 13 : ((((c << 1) &
ShortMask) != 0) ? 14 : 15))))))))))))));
retSetBitLong += rsb;
return retSetBitLong;
}
}
return -1;
}
/// <summary>Gets the bit position of the lowest set bit in this
/// number's absolute value, in the form of an arbitrary-precision
/// integer. (This will also be the position of the lowest set bit in
/// the number's two's-complement form (see
/// <see cref='PeterO.Numbers.EDecimal'>"Forms of numbers"</see>
/// ).).</summary>
/// <returns>The bit position of the lowest bit set in the number's
/// absolute value, starting at 0. Returns -1 if this value is 0 or
/// odd.</returns>
public EInteger GetLowBitAsEInteger() {
return EInteger.FromInt64(this.GetLowBitAsInt64());
}
/// <summary>Returns whether a bit is set in the two's-complement form
/// (see
/// <see cref='PeterO.Numbers.EDecimal'>"Forms of numbers"</see> ) of
/// this object's value.</summary>
/// <param name='bigIndex'>The index, starting at zero, of the bit to
/// test, where 0 is the least significant bit, 1 is the next least
/// significant bit, and so on.</param>
/// <returns><c>true</c> if the given bit is set in the two'
/// s-complement form (see
/// <see cref='PeterO.Numbers.EDecimal'>"Forms of numbers"</see> ) of
/// this object's value; otherwise, <c>false</c>.</returns>
/// <exception cref='ArgumentNullException'>The parameter <paramref
/// name='bigIndex'/> is null.</exception>
public bool GetSignedBit(EInteger bigIndex) {
if (bigIndex == null) {
throw new ArgumentNullException(nameof(bigIndex));
}
if (bigIndex.Sign < 0) {
throw new ArgumentOutOfRangeException(nameof(bigIndex));
}
if (this.negative) {
if (bigIndex.CanFitInInt32()) {
return this.GetSignedBit(bigIndex.ToInt32Checked());
}
EInteger valueEWordPos = bigIndex.Divide(16);
if (valueEWordPos.CompareTo(this.words.Length) >= 0) {
return true;
}
long tcindex = 0;
while (valueEWordPos.CompareTo(EInteger.FromInt64(tcindex)) > 0 &&
this.words[checked((int)tcindex)] == 0) {
++tcindex;
}
short tc;
// NOTE: array indices are currently limited to Int32
int wordpos = valueEWordPos.ToInt32Checked();
unchecked {
tc = this.words[wordpos];
if (tcindex == wordpos) {
--tc;
}
tc = (short)~tc;
}
int mod15 = bigIndex.Remainder(16).ToInt32Checked();
return (bool)(((tc >> mod15) & 1) != 0);
} else {
return this.GetUnsignedBit(bigIndex);
}
}
/// <summary>Returns whether a bit is set in the two's-complement form
/// (see
/// <see cref='PeterO.Numbers.EDecimal'>"Forms of numbers"</see> ) of
/// this object's value.</summary>
/// <param name='index'>The index, starting at 0, of the bit to test,
/// where 0 is the least significant bit, 1 is the next least
/// significant bit, and so on.</param>
/// <returns><c>true</c> if the given bit is set in the two'
/// s-complement form (see
/// <see cref='PeterO.Numbers.EDecimal'>"Forms of numbers"</see> ) of
/// this object's value; otherwise, <c>false</c>.</returns>
public bool GetSignedBit(int index) {
if (index < 0) {
throw new ArgumentOutOfRangeException(nameof(index));
}
if (this.wordCount == 0) {
return false;
}
if (this.negative) {
var tcindex = 0;
int wordpos = index / 16;
if (wordpos >= this.words.Length) {
return true;
}
while (tcindex < wordpos && this.words[tcindex] == 0) {
++tcindex;
}
short tc;
unchecked {
tc = this.words[wordpos];
if (tcindex == wordpos) {
--tc;
}
tc = (short)~tc;
}
return (bool)(((tc >> (int)(index & 15)) & 1) != 0);
}
return this.GetUnsignedBit(index);
}
/// <summary>Finds the minimum number of bits needed to represent this
/// object's value, except for its sign, and returns that number of
/// bits as an arbitrary-precision integer. If the value is negative,
/// finds the number of bits in the value equal to this object's
/// absolute value minus 1. For example, all integers in the interval
/// [-(2^63), (2^63) - 1], which is the same as the range of integers
/// in Java's and.NET's <c>long</c> type, have a signed bit length of
/// 63 or less, and all other integers have a signed bit length of
/// greater than 63.</summary>
/// <returns>The number of bits in this object's value, except for its
/// sign. Returns 0 if this object's value is 0 or negative
/// 1.</returns>
public EInteger GetSignedBitLengthAsEInteger() {
// NOTE: Currently can't be 2^63-1 or greater, due to int32 word counts
return EInteger.FromInt64(this.GetSignedBitLengthAsInt64());
}
/// <summary>Finds the minimum number of bits needed to represent this
/// object's value, except for its sign, and returns that number of
/// bits as a 64-bit signed integer. If the value is negative, finds
/// the number of bits in the value equal to this object's absolute
/// value minus 1. For example, all integers in the interval [-(2^63),
/// (2^63) - 1], which is the same as the range of integers in Java's
/// and.NET's <c>long</c> type, have a signed bit length of 63 or less,
/// and all other integers have a signed bit length of greater than
/// 63.</summary>
/// <returns>The number of bits in this object's value, except for its
/// sign. Returns 0 if this object's value is 0 or negative 1. If the
/// return value would be greater than 2^63 - 1 ( <c>Int64.MaxValue</c>
/// in.NET or <c>Long.MAX_VALUE</c> in Java), returns 2^63 - 1 instead.
/// (Use <c>GetSignedBitLengthAsEInteger</c> instead of this method if
/// the application relies on the exact number of bits.).</returns>
public long GetSignedBitLengthAsInt64() {
// NOTE: Currently can't be 2^63-1 or greater, due to int32 word counts
int wc = this.wordCount;
if (wc != 0) {
if (this.negative) {
// Two's complement operation
EInteger eiabs = this.Abs();
long eiabsbl = eiabs.GetSignedBitLengthAsInt64();
if (eiabs.IsPowerOfTwo) {
// Absolute value is a power of 2
--eiabsbl;
}
return eiabsbl;
}
int numberValue = ((int)this.words[wc - 1]) & ShortMask;
var wcextra = 0;
if (numberValue != 0) {
wcextra = 16;
unchecked {
if ((numberValue >> 8) == 0) {
numberValue <<= 8;
wcextra -= 8;
}
if ((numberValue >> 12) == 0) {
numberValue <<= 4;
wcextra -= 4;
}
if ((numberValue >> 14) == 0) {
numberValue <<= 2;
wcextra -= 2;
}
wcextra = ((numberValue >> 15) == 0) ? wcextra - 1 : wcextra;
}
}
return (((long)wc - 1) * 16) + wcextra;
}
return 0;
}
/// <summary>Finds the minimum number of bits needed to represent this
/// object's value, except for its sign. If the value is negative,
/// finds the number of bits in the value equal to this object's
/// absolute value minus 1. For example, all integers in the interval
/// [-(2^63), (2^63) - 1], which is the same as the range of integers
/// in Java's and.NET's <c>long</c> type, have a signed bit length of
/// 63 or less, and all other integers have a signed bit length of
/// greater than 63.</summary>
/// <returns>The number of bits in this object's value, except for its
/// sign. Returns 0 if this object's value is 0 or negative
/// 1.</returns>
/// <exception cref='OverflowException'>The return value would exceed
/// the range of a 32-bit signed integer.</exception>
[Obsolete("This method may overflow. Use GetSignedBitLength" +
"AsEInteger instead.")]
public int GetSignedBitLength() {
return this.GetSignedBitLengthAsEInteger().ToInt32Checked();
}
/// <summary>Returns whether a bit is set in this number's absolute
/// value.</summary>
/// <param name='bigIndex'>The index, starting at zero, of the bit to
/// test, where 0 is the least significant bit, 1 is the next least
/// significant bit, and so on.</param>
/// <returns><c>true</c> if the given bit is set in this number's
/// absolute value.</returns>
/// <exception cref='ArgumentNullException'>The parameter <paramref
/// name='bigIndex'/> is null.</exception>
public bool GetUnsignedBit(EInteger bigIndex) {
if (bigIndex == null) {
throw new ArgumentNullException(nameof(bigIndex));
}
if (bigIndex.Sign < 0) {
throw new ArgumentException("bigIndex(" + bigIndex +
") is less than 0");
}
if (bigIndex.CanFitInInt32()) {
return this.GetUnsignedBit(bigIndex.ToInt32Checked());
}
if (bigIndex.Divide(16).CompareTo(this.words.Length) < 0) {
return false;
}
int index = bigIndex.ShiftRight(4).ToInt32Checked();
int indexmod = bigIndex.Remainder(16).ToInt32Checked();
return (bool)(((this.words[index] >> (int)indexmod) & 1) != 0);
}
/// <summary>Returns whether a bit is set in this number's absolute
/// value.</summary>
/// <param name='index'>The index, starting at 0, of the bit to test,
/// where 0 is the least significant bit, 1 is the next least
/// significant bit, and so on.</param>
/// <returns><c>true</c> if the given bit is set in this number's
/// absolute value.</returns>
public bool GetUnsignedBit(int index) {
if (index < 0) {
throw new ArgumentException("index(" + index + ") is less than 0");
}
return ((index >> 4) < this.words.Length) &&
((bool)(((this.words[index >> 4] >> (int)(index & 15)) & 1) != 0));
}
/// <summary>Finds the minimum number of bits needed to represent this
/// number's absolute value, and returns that number of bits as an
/// arbitrary-precision integer. For example, all integers in the
/// interval [-((2^63) - 1), (2^63) - 1] have an unsigned bit length of
/// 63 or less, and all other integers have an unsigned bit length of
/// greater than 63. This interval is not the same as the range of
/// integers in Java's and.NET's <c>long</c> type.</summary>
/// <returns>The number of bits in this object's absolute value.
/// Returns 0 if this object's value is 0, and returns 1 if the value
/// is negative 1.</returns>
public EInteger GetUnsignedBitLengthAsEInteger() {
// NOTE: Currently can't be 2^63-1 or greater, due to int32 word counts
return EInteger.FromInt64(this.GetUnsignedBitLengthAsInt64());
}
/// <summary>Finds the minimum number of bits needed to represent this
/// number's absolute value, and returns that number of bits as a
/// 64-bit signed integer. For example, all integers in the interval
/// [-((2^63) - 1), (2^63) - 1] have an unsigned bit length of 63 or
/// less, and all other integers have an unsigned bit length of greater
/// than 63. This interval is not the same as the range of integers in
/// Java's and.NET's <c>long</c> type.</summary>
/// <returns>The number of bits in this object's absolute value.
/// Returns 0 if this object's value is 0, and returns 1 if the value
/// is negative 1. If the return value would be greater than 2^63 - 1(
/// <c>Int64.MaxValue</c> in.NET or <c>Long.MAX_VALUE</c> in Java),
/// returns 2^63 - 1 instead. (Use
/// <c>GetUnsignedBitLengthAsEInteger</c> instead of this method if the
/// application relies on the exact number of bits.).</returns>
public long GetUnsignedBitLengthAsInt64() {
// NOTE: Currently can't be 2^63-1 or greater, due to int32 word counts
int wc = this.wordCount;
if (wc != 0) {
int numberValue = ((int)this.words[wc - 1]) & ShortMask;
long longBase = ((long)wc - 1) << 4;
if (numberValue == 0) {
return longBase;
}
wc = 16;
unchecked {
if ((numberValue >> 8) == 0) {
numberValue <<= 8;
wc -= 8;
}
if ((numberValue >> 12) == 0) {
numberValue <<= 4;
wc -= 4;
}
if ((numberValue >> 14) == 0) {
numberValue <<= 2;
wc -= 2;
}
if ((numberValue >> 15) == 0) {
--wc;
}
}
return longBase + wc;
}
return 0;
}
/// <summary>Finds the minimum number of bits needed to represent this
/// number's absolute value. For example, all integers in the interval
/// [-((2^63) - 1), (2^63) - 1] have an unsigned bit length of 63 or
/// less, and all other integers have an unsigned bit length of greater
/// than 63. This interval is not the same as the range of integers in
/// Java's and.NET's <c>long</c> type.</summary>
/// <returns>The number of bits in this object's absolute value.
/// Returns 0 if this object's value is 0, and returns 1 if the value
/// is negative 1.</returns>
/// <exception cref='OverflowException'>The return value would exceed
/// the range of a 32-bit signed integer.</exception>
[Obsolete("This method may overflow. Use GetUnsignedBitLength" +
"AsEInteger instead.")]
public int GetUnsignedBitLength() {
return this.GetUnsignedBitLengthAsEInteger().ToInt32Checked();
}
/// <summary>Finds the modulus remainder that results when this
/// instance is divided by the value of an arbitrary-precision integer.
/// The modulus remainder is the same as the normal remainder if the
/// normal remainder is positive, and equals divisor plus normal
/// remainder if the normal remainder is negative.</summary>
/// <param name='divisor'>The number to divide by.</param>
/// <returns>An arbitrary-precision integer.</returns>
/// <exception cref='ArgumentException'>The parameter <paramref
/// name='divisor'/> is less than 0.</exception>
/// <exception cref='ArgumentNullException'>The parameter <paramref
/// name='divisor'/> is null.</exception>
public EInteger Mod(EInteger divisor) {
if (divisor == null) {
throw new ArgumentNullException(nameof(divisor));
}
if (divisor.Sign < 0) {
throw new ArithmeticException("Divisor is negative");
}
EInteger remainderEInt = this.Remainder(divisor);
if (remainderEInt.Sign < 0) {
remainderEInt = divisor.Add(remainderEInt);
}
return remainderEInt;
}
/// <summary>Finds the modulus remainder that results when this
/// instance is divided by the value of another integer. The modulus
/// remainder is the same as the normal remainder if the normal
/// remainder is positive, and equals divisor plus normal remainder if
/// the normal remainder is negative.</summary>
/// <param name='smallDivisor'>The divisor of the modulus.</param>
/// <returns>The modulus remainder.</returns>
/// <exception cref='ArgumentException'>The parameter <paramref
/// name='smallDivisor'/> is less than 0.</exception>
public EInteger Mod(int smallDivisor) {
if (smallDivisor < 0) {
throw new ArithmeticException("Divisor is negative");
}
EInteger remainderEInt = this.Remainder(smallDivisor);
if (remainderEInt.Sign < 0) {
remainderEInt = EInteger.FromInt32(smallDivisor).Add(remainderEInt);
}
return remainderEInt;
}
/// <summary>Calculates the remainder when this arbitrary-precision
/// integer raised to a certain power is divided by another
/// arbitrary-precision integer.</summary>
/// <param name='pow'>The power to raise this integer by.</param>
/// <param name='mod'>The integer to divide the raised number
/// by.</param>
/// <returns>An arbitrary-precision integer.</returns>
/// <exception cref='ArgumentNullException'>The parameter <paramref
/// name='pow'/> or <paramref name='mod'/> is null.</exception>
public EInteger ModPow(EInteger pow, EInteger mod) {
if (pow == null) {
throw new ArgumentNullException(nameof(pow));
}
if (mod == null) {
throw new ArgumentNullException(nameof(mod));
}
if (pow.Sign < 0) {
throw new ArgumentException("pow(" + pow + ") is less than 0");
}
if (mod.Sign <= 0) {
throw new ArgumentException("mod(" + mod + ") is not greater than 0");
}
EInteger r = EInteger.One;
EInteger eiv = this;
while (!pow.IsZero) {
if (!pow.IsEven) {
r = (r * (EInteger)eiv).Mod(mod);
}
pow >>= 1;
if (!pow.IsZero) {
eiv = (eiv * (EInteger)eiv).Mod(mod);
}
}
return r;
}
/// <summary>Multiplies this arbitrary-precision integer by another
/// arbitrary-precision integer and returns the result.</summary>
/// <param name='bigintMult'>Another arbitrary-precision
/// integer.</param>
/// <returns>The product of the two numbers, that is, this
/// arbitrary-precision integer times another arbitrary-precision
/// integer.</returns>
/// <exception cref='ArgumentNullException'>The parameter <paramref
/// name='bigintMult'/> is null.</exception>
public EInteger Multiply(EInteger bigintMult) {
if (bigintMult == null) {
throw new ArgumentNullException(nameof(bigintMult));
}
if (this.wordCount == 0 || bigintMult.wordCount == 0) {
return EInteger.Zero;
}
if (this.wordCount == 1 && this.words[0] == 1) {
return this.negative ? bigintMult.Negate() : bigintMult;
}
if (bigintMult.wordCount == 1 && bigintMult.words[0] == 1) {
return bigintMult.negative ? this.Negate() : this;
}
// DebugUtility.Log("multiply " + this + " " + bigintMult);
short[] productreg;
int productwordCount;
var needShorten = true;
if (this.wordCount == 1) {
int wc;
if (bigintMult.wordCount == 1) {
// NOTE: Result can't be 0 here, since checks
// for 0 were already made earlier in this function
productreg = new short[2];
int ba = ((int)this.words[0]) & ShortMask;
int bb = ((int)bigintMult.words[0]) & ShortMask;
ba = unchecked(ba * bb);
productreg[0] = unchecked((short)(ba & ShortMask));
productreg[1] = unchecked((short)((ba >> 16) & ShortMask));
short preg = productreg[1];
wc = (preg == 0) ? 1 : 2;
return new EInteger(
wc,
productreg,
this.negative ^ bigintMult.negative);
}
wc = bigintMult.wordCount;
int regLength = wc + 1;
productreg = new short[regLength];
productreg[wc] = LinearMultiply(
productreg,
0,
bigintMult.words,
0,
this.words[0],
wc);
productwordCount = productreg.Length;
needShorten = false;
} else if (bigintMult.wordCount == 1) {
int wc = this.wordCount;
int regLength = wc + 1;
productreg = new short[regLength];
productreg[wc] = LinearMultiply(
productreg,
0,
this.words,
0,
bigintMult.words[0],
wc);
productwordCount = productreg.Length;
needShorten = false;
} else if (this.Equals(bigintMult)) {
int words1Size = this.wordCount;
productreg = new short[words1Size + words1Size];
productwordCount = productreg.Length;
var workspace = new short[words1Size + words1Size];
RecursiveSquare(
productreg,
0,
workspace,
0,
this.words,
0,
words1Size);
} else if (this.wordCount <= MultRecursionThreshold &&
bigintMult.wordCount <= MultRecursionThreshold) {
int wc = this.wordCount + bigintMult.wordCount;
productreg = new short[wc];
productwordCount = productreg.Length;
SchoolbookMultiply(
productreg,
0,
this.words,
0,
this.wordCount,
bigintMult.words,
0,
bigintMult.wordCount);
needShorten = false;
} else {
int words1Size = this.wordCount;
int words2Size = bigintMult.wordCount;
productreg = new short[words1Size + words2Size];
var workspace = new short[words1Size + words2Size];
productwordCount = productreg.Length;
AsymmetricMultiply(
productreg,
0,
workspace,
0,
this.words,
0,
words1Size,
bigintMult.words,
0,
words2Size);
}
// Recalculate word count
while (productwordCount != 0 && productreg[productwordCount - 1] == 0) {
--productwordCount;
}
if (needShorten) {
productreg = ShortenArray(productreg, productwordCount);
}
return new EInteger(
productwordCount,
productreg,
this.negative ^ bigintMult.negative);
}
private static EInteger MakeEInteger(
short[] words,
int wordsEnd,
int offset,
int count) {
if (offset >= wordsEnd) {
return EInteger.Zero;
}
int ct = Math.Min(count, wordsEnd - offset);
while (ct != 0 && words[offset + ct - 1] == 0) {
--ct;
}
if (ct == 0) {
return EInteger.Zero;
}
var newwords = new short[ct];
Array.Copy(words, offset, newwords, 0, ct);
return new EInteger(ct, newwords, false);
}
private static void Toom3(
short[] resultArr,
int resultStart,
short[] wordsA,
int wordsAStart,
int countA,
short[] wordsB,
int wordsBStart,
int countB) {
int imal = Math.Max(countA, countB);
int im3 = (imal / 3) + (((imal % 3) + 2) / 3);
EInteger m3mul16 = EInteger.FromInt32(im3).ShiftLeft(4);
EInteger x0 = MakeEInteger(
wordsA,
wordsAStart + countA,
wordsAStart,
im3);
EInteger x1 = MakeEInteger(
wordsA,
wordsAStart + countA,
wordsAStart + im3,
im3);
EInteger x2 = MakeEInteger(
wordsA,
wordsAStart + countA,
wordsAStart + (im3 * 2),
im3);
EInteger w0, wt1, wt2, wt3, w4;
if (wordsA == wordsB && wordsAStart == wordsBStart &&
countA == countB) {
// Same array, offset, and count, so we're squaring
w0 = x0.Multiply(x0);
w4 = x2.Multiply(x2);
EInteger x2x0 = x2.Add(x0);
wt1 = x2x0.Add(x1);
wt2 = x2x0.Subtract(x1);
wt3 = x2.ShiftLeft(2).Add(x1.ShiftLeft(1)).Add(x0);
wt1 = wt1.Multiply(wt1);
wt2 = wt2.Multiply(wt2);
wt3 = wt3.Multiply(wt3);
} else {
EInteger y0 = MakeEInteger(
wordsB,
wordsBStart + countB,
wordsBStart,
im3);
EInteger y1 = MakeEInteger(
wordsB,
wordsBStart + countB,
wordsBStart + im3,
im3);
EInteger y2 = MakeEInteger(
wordsB,
wordsBStart + countB,
wordsBStart + (im3 * 2),
im3);
w0 = x0.Multiply(y0);
w4 = x2.Multiply(y2);
EInteger x2x0 = x2.Add(x0);
EInteger y2y0 = y2.Add(y0);
wt1 = x2x0.Add(x1).Multiply(y2y0.Add(y1));
wt2 = x2x0.Subtract(x1).Multiply(y2y0.Subtract(y1));
wt3 = x2.ShiftLeft(2).Add(x1.ShiftLeft(1)).Add(x0)
.Multiply(y2.ShiftLeft(2).Add(y1.ShiftLeft(1)).Add(y0));
}
EInteger w4mul2 = w4.ShiftLeft(1);
EInteger w4mul12 = w4mul2.Multiply(6);
EInteger w0mul3 = w0.Multiply(3);
EInteger w3 = w0mul3.Subtract(w4mul12).Subtract(wt1.Multiply(3))
.Subtract(wt2).Add(wt3).Divide(6);
EInteger w2 = wt1.Add(wt2).Subtract(w0.ShiftLeft(1))
.Subtract(w4mul2).ShiftRight(1);
EInteger w1 = wt1.Multiply(6).Add(w4mul12)
.Subtract(wt3).Subtract(wt2).Subtract(wt2)
.Subtract(w0mul3).Divide(6);
if (m3mul16.CompareTo(0x70000000) < 0) {
im3 <<= 4; // multiply by 16
w0 = w0.Add(w1.ShiftLeft(im3));
w0 = w0.Add(w2.ShiftLeft(im3 * 2));
w0 = w0.Add(w3.ShiftLeft(im3 * 3));
w0 = w0.Add(w4.ShiftLeft(im3 * 4));
} else {
w0 = w0.Add(w1.ShiftLeft(m3mul16));
w0 = w0.Add(w2.ShiftLeft(m3mul16.Multiply(2)));
w0 = w0.Add(w3.ShiftLeft(m3mul16.Multiply(3)));
w0 = w0.Add(w4.ShiftLeft(m3mul16.Multiply(4)));
}
Array.Clear(resultArr, resultStart, countA + countB);
Array.Copy(
w0.words,
0,
resultArr,
resultStart,
Math.Min(countA + countB, w0.wordCount));
}
private static EInteger Interpolate(
EInteger[] wts,
int[] values,
int divisor) {
EInteger ret = EInteger.Zero;
for (int i = 0; i < wts.Length; ++i) {
int v = values[i];
if (v == 0) {
continue;
} else {
ret = (v == 1) ? ret.Add(wts[i]) : ((v == -1) ? ret.Subtract(
wts[i]) : ret.Add(wts[i].Multiply(v)));
}
}
return ret.Divide(divisor);
}
/*
public EInteger Toom4Multiply(EInteger eib) {
var r = new short[this.wordCount + eib.wordCount];
Toom4(r, 0, this.words, 0, this.wordCount, eib.words, 0, eib.wordCount);
EInteger ret = MakeEInteger(r, r.Length, 0, r.Length);
return (this.negative^eib.negative) ? ret.Negate() : ret;
}
*/
private static void Toom4(
short[] resultArr,
int resultStart,
short[] wordsA,
int wordsAStart,
int countA,
short[] wordsB,
int wordsBStart,
int countB) {
int imal = Math.Max(countA, countB);
int im3 = (imal / 4) + (((imal % 4) + 3) / 4);
EInteger m3mul16 = EInteger.FromInt32(im3).ShiftLeft(4);
EInteger x0 = MakeEInteger(
wordsA,
wordsAStart + countA,
wordsAStart,
im3);
EInteger x1 = MakeEInteger(
wordsA,
wordsAStart + countA,
wordsAStart + im3,
im3);
EInteger x2 = MakeEInteger(
wordsA,
wordsAStart + countA,
wordsAStart + (im3 * 2),
im3);
EInteger x3 = MakeEInteger(
wordsA,
wordsAStart + countA,
wordsAStart + (im3 * 3),
im3);
EInteger w0, wt1, wt2, wt3, wt4, wt5, w6;
if (wordsA == wordsB && wordsAStart == wordsBStart &&
countA == countB) {
// Same array, offset, and count, so we're squaring
w0 = x0.Multiply(x0);
w6 = x3.Multiply(x3);
EInteger x2mul2 = x2.ShiftLeft(1);
EInteger x1mul4 = x1.ShiftLeft(2);
EInteger x0mul8 = x0.ShiftLeft(3);
EInteger x1x3 = x1.Add(x3);
EInteger x0x2 = x0.Add(x2);
wt1 = x3.Add(x2mul2).Add(x1mul4).Add(x0mul8);
wt2 = x3.Negate().Add(x2mul2).Subtract(x1mul4).Add(x0mul8);
wt3 = x0x2.Add(x1x3);
wt4 = x0x2.Subtract(x1x3);
wt5 = x0.Add(
x3.ShiftLeft(3)).Add(x2.ShiftLeft(2)).Add(x1.ShiftLeft(1));
wt1 = wt1.Multiply(wt1);
wt2 = wt2.Multiply(wt2);
wt3 = wt3.Multiply(wt3);
wt4 = wt4.Multiply(wt4);
wt5 = wt5.Multiply(wt5);
} else {
EInteger y0 = MakeEInteger(
wordsB,
wordsBStart + countB,
wordsBStart,
im3);
EInteger y1 = MakeEInteger(
wordsB,
wordsBStart + countB,
wordsBStart + im3,
im3);
EInteger y2 = MakeEInteger(
wordsB,
wordsBStart + countB,
wordsBStart + (im3 * 2),
im3);
EInteger y3 = MakeEInteger(
wordsB,
wordsBStart + countB,
wordsBStart + (im3 * 3),
im3);
w0 = x0.Multiply(y0);
w6 = x3.Multiply(y3);
EInteger x2mul2 = x2.ShiftLeft(1);
EInteger x1mul4 = x1.ShiftLeft(2);
EInteger x0mul8 = x0.ShiftLeft(3);
EInteger y2mul2 = y2.ShiftLeft(1);
EInteger y1mul4 = y1.ShiftLeft(2);
EInteger y0mul8 = y0.ShiftLeft(3);
EInteger x1x3 = x1.Add(x3);
EInteger x0x2 = x0.Add(x2);
EInteger y1y3 = y1.Add(y3);
EInteger y0y2 = y0.Add(y2);
wt1 = x3.Add(x2mul2).Add(x1mul4).Add(x0mul8);
wt1 = wt1.Multiply(y3.Add(y2mul2).Add(y1mul4).Add(y0mul8));
wt2 = x3.Negate().Add(x2mul2).Subtract(x1mul4).Add(x0mul8);
wt2 = wt2.Multiply(
y3.Negate().Add(y2mul2).Subtract(y1mul4).Add(y0mul8));
wt3 = x0x2.Add(x1x3);
wt3 = wt3.Multiply(y0y2.Add(y1y3));
wt4 = x0x2.Subtract(x1x3);
wt4 = wt4.Multiply(y0y2.Subtract(y1y3));
wt5 = x0.Add(
x3.ShiftLeft(3)).Add(x2.ShiftLeft(2)).Add(x1.ShiftLeft(1));
wt5 = wt5.Multiply(
y0.Add(
y3.ShiftLeft(3)).Add(y2.ShiftLeft(2)).Add(y1.ShiftLeft(1)));
}
EInteger[] wts = { w0, wt1, wt2, wt3, wt4, wt5, w6 };
var wts2 = new int[] {
-90, 5, -3, -60, 20, 2,
-90,
};
EInteger w1 = Interpolate(wts, wts2, 180);
wts2 = new int[] {
-120,
1,
1,
-4,
-4,
0,
6,
};
EInteger w2 = Interpolate(wts, wts2, 24);
wts2 = new int[] {
45,
-1,
0,
27,
-7,
-1,
45,
};
EInteger w3 = Interpolate(wts,
wts2,
18);
wts2 = new int[] {
96,
-1,
-1,
16,
16,
0,
-30,
};
EInteger w4 = Interpolate(
wts,
wts2,
24);
wts2 = new int[] {
-360, 5, 3, -120, -40, 8,
-360,
};
EInteger w5 = Interpolate(wts,
wts2,
180);
if (m3mul16.CompareTo(0x70000000) < 0) {
im3 <<= 4; // multiply by 16
w0 = w0.Add(w1.ShiftLeft(im3));
w0 = w0.Add(w2.ShiftLeft(im3 * 2));
w0 = w0.Add(w3.ShiftLeft(im3 * 3));
w0 = w0.Add(w4.ShiftLeft(im3 * 4));
w0 = w0.Add(w5.ShiftLeft(im3 * 5));
w0 = w0.Add(w6.ShiftLeft(im3 * 6));
} else {
w0 = w0.Add(w1.ShiftLeft(m3mul16));
w0 = w0.Add(w2.ShiftLeft(m3mul16.Multiply(2)));
w0 = w0.Add(w3.ShiftLeft(m3mul16.Multiply(3)));
w0 = w0.Add(w4.ShiftLeft(m3mul16.Multiply(4)));
w0 = w0.Add(w5.ShiftLeft(m3mul16.Multiply(5)));
w0 = w0.Add(w6.ShiftLeft(m3mul16.Multiply(6)));
}
Array.Clear(resultArr, resultStart, countA + countB);
Array.Copy(
w0.words,
0,
resultArr,
resultStart,
Math.Min(countA + countB, w0.wordCount));
}
/// <summary>Gets the value of this object with the sign
/// reversed.</summary>
/// <returns>This object's value with the sign reversed.</returns>
public EInteger Negate() {
return this.wordCount == 0 ? this : new EInteger(
this.wordCount,
this.words,
!this.negative);
}
/// <summary>Raises an arbitrary-precision integer to a
/// power.</summary>
/// <param name='longPower'>The exponent to raise this integer
/// to.</param>
/// <returns>The result. Returns 1 if <paramref name='longPower'/> is
/// 0.</returns>
/// <exception cref='ArgumentException'>BigPower is
/// negative.</exception>
public EInteger Pow(long longPower) {
if (longPower < 0) {
throw new ArgumentException("bigPower is negative");
}
if (longPower == 0) {
return EInteger.One;
}
return (longPower < Int32.MaxValue) ? this.Pow((int)longPower) :
this.Pow(EInteger.FromInt64(longPower));
}
/// <summary>Raises an arbitrary-precision integer to a
/// power.</summary>
/// <param name='bigPower'>The exponent to raise this integer
/// to.</param>
/// <returns>The result. Returns 1 if <paramref name='bigPower'/> is
/// 0.</returns>
/// <exception cref='ArgumentNullException'>The parameter <paramref
/// name='bigPower'/> is null.</exception>
/// <exception cref='ArgumentException'>BigPower is
/// negative.</exception>
public EInteger Pow(EInteger bigPower) {
if (bigPower == null) {
throw new ArgumentNullException(nameof(bigPower));
}
if (bigPower.Sign < 0) {
throw new ArgumentException("bigPower is negative");
}
if (bigPower.Sign == 0) {
// however 0 to the power of 0 is undefined
return EInteger.One;
}
if (bigPower.CompareTo(1) == 0) {
return this;
}
if (this.IsZero || this.CompareTo(1) == 0) {
return this;
}
if (this.CompareTo(-1) == 0) {
return bigPower.IsEven ? EInteger.FromInt32(1) : this;
}
EInteger bitLength = this.GetUnsignedBitLengthAsEInteger();
if (!this.IsPowerOfTwo) {
bitLength = bitLength.Subtract(1);
}
// DebugUtility.Log("sizeNeeded=" + bitLength.Multiply(bigPower));
// DebugUtility.Log("bigPower=" + bigPower);
if (bigPower.CanFitInInt32()) {
return this.Pow(bigPower.ToInt32Checked());
}
EInteger bp = bigPower;
EInteger ret = EInteger.One;
EInteger rmax = this.Pow(Int32.MaxValue);
while (!bp.CanFitInInt32()) {
ret = ret.Multiply(rmax);
bp = bp.Subtract(Int32.MaxValue);
}
int lastp = bp.ToInt32Checked();
ret = (lastp == Int32.MaxValue) ? ret.Multiply(rmax) :
ret.Multiply(this.Pow(lastp));
return ret;
}
/// <summary>Raises an arbitrary-precision integer to a
/// power.</summary>
/// <param name='powerSmall'>The exponent to raise this integer
/// to.</param>
/// <returns>The result. Returns 1 if <paramref name='powerSmall'/> is
/// 0.</returns>
public EInteger Pow(int powerSmall) {
if (powerSmall < 0) {
throw new ArgumentException("powerSmall(" + powerSmall +
") is less than 0");
}
EInteger thisVar = this;
if (powerSmall == 0) {
// however 0 to the power of 0 is undefined
return EInteger.One;
}
if (powerSmall == 1) {
return this;
}
if (this.IsZero || this.CompareTo(1) == 0) {
return this;
}
if (this.CompareTo(-1) == 0) {
return (powerSmall & 1) == 0 ? EInteger.FromInt32(1) : this;
}
if (powerSmall == 2) {
return thisVar.Multiply(thisVar);
}
if (powerSmall == 3) {
return thisVar.Multiply(thisVar).Multiply(thisVar);
}
EInteger r = EInteger.One;
// bool negatePower = (powerSmall & 1) != 0 && thisVar.Sign < 0;
// thisVar = thisVar.Abs();
while (powerSmall != 0) {
if ((powerSmall & 1) != 0) {
r *= (EInteger)thisVar;
}
powerSmall >>= 1;
if (powerSmall != 0) {
thisVar *= (EInteger)thisVar;
}
}
return r; // negatePower ? r.Negate() : r;
}
/// <summary>Raises an arbitrary-precision integer to a power, which is
/// given as another arbitrary-precision integer.</summary>
/// <param name='power'>The exponent to raise to.</param>
/// <returns>The result. Returns 1 if <paramref name='power'/> is
/// 0.</returns>
/// <exception cref='ArgumentException'>The parameter <paramref
/// name='power'/> is less than 0.</exception>
/// <exception cref='ArgumentNullException'>The parameter <paramref
/// name='power'/> is null.</exception>
[Obsolete("Use Pow instead.")]
public EInteger PowBigIntVar(EInteger power) {
if (power == null) {
throw new ArgumentNullException(nameof(power));
}
return this.Pow(power);
}
/// <summary>Returns the remainder that would result when this
/// arbitrary-precision integer is divided by another
/// arbitrary-precision integer. The remainder is the number that
/// remains when the absolute value of this arbitrary-precision integer
/// is divided by the absolute value of the other arbitrary-precision
/// integer; the remainder has the same sign (positive or negative) as
/// this arbitrary-precision integer.</summary>
/// <param name='divisor'>The number to divide by.</param>
/// <returns>The remainder that would result when this
/// arbitrary-precision integer is divided by another
/// arbitrary-precision integer.</returns>
/// <exception cref='DivideByZeroException'>Attempted to divide by
/// zero.</exception>
/// <exception cref='ArgumentNullException'>The parameter <paramref
/// name='divisor'/> is null.</exception>
public EInteger Remainder(EInteger divisor) {
if (divisor == null) {
throw new ArgumentNullException(nameof(divisor));
}
int words1Size = this.wordCount;
int words2Size = divisor.wordCount;
if (words2Size == 0) {
throw new DivideByZeroException();
}
if (words1Size < words2Size) {
// dividend is less than divisor
return this;
}
if (words2Size == 1) {
short shortRemainder = FastRemainder(
this.words,
this.wordCount,
divisor.words[0]);
int smallRemainder = ((int)shortRemainder) & ShortMask;
if (this.negative) {
smallRemainder = -smallRemainder;
}
return EInteger.FromInt64(smallRemainder);
}
if (this.PositiveCompare(divisor) < 0) {
return this;
}
var remainderReg = new short[(int)words2Size];
GeneralDivide(
this.words,
0,
this.wordCount,
divisor.words,
0,
divisor.wordCount,
null,
0,
remainderReg,
0);
int count = CountWords(remainderReg);
if (count == 0) {
return EInteger.Zero;
}
remainderReg = ShortenArray(remainderReg, count);
return new EInteger(count, remainderReg, this.negative);
}
/// <summary>Returns an arbitrary-precision integer with the bits
/// shifted to the right. For this operation, the arbitrary-precision
/// integer is treated as a two's-complement form (see
/// <see cref='PeterO.Numbers.EDecimal'>"Forms of numbers"</see> ).
/// Thus, for negative values, the arbitrary-precision integer is
/// sign-extended.</summary>
/// <param name='eshift'>The number of bits to shift. Can be negative,
/// in which case this is the same as ShiftLeft with the absolute value
/// of this parameter.</param>
/// <returns>An arbitrary-precision integer.</returns>
/// <exception cref='ArgumentNullException'>The parameter <paramref
/// name='eshift'/> is null.</exception>
public EInteger ShiftRight(EInteger eshift) {
if (eshift == null) {
throw new ArgumentNullException(nameof(eshift));
}
EInteger valueETempShift = eshift;
EInteger ret = this;
if (valueETempShift.Sign < 0) {
return ret.ShiftLeft(valueETempShift.Negate());
}
while (!valueETempShift.CanFitInInt32()) {
valueETempShift = valueETempShift.Subtract(0x7ffffff0);
ret = ret.ShiftRight(0x7ffffff0);
}
return ret.ShiftRight(valueETempShift.ToInt32Checked());
}
/// <summary>Returns an arbitrary-precision integer with the bits
/// shifted to the left by a number of bits given as an
/// arbitrary-precision integer. A value of 1 doubles this value, a
/// value of 2 multiplies it by 4, a value of 3 by 8, a value of 4 by
/// 16, and so on.</summary>
/// <param name='eshift'>The number of bits to shift. Can be negative,
/// in which case this is the same as ShiftRight with the absolute
/// value of this parameter.</param>
/// <returns>An arbitrary-precision integer.</returns>
/// <exception cref='ArgumentNullException'>The parameter <paramref
/// name='eshift'/> is null.</exception>
public EInteger ShiftLeft(EInteger eshift) {
if (eshift == null) {
throw new ArgumentNullException(nameof(eshift));
}
EInteger valueETempShift = eshift;
EInteger ret = this;
if (valueETempShift.Sign < 0) {
return ret.ShiftRight(valueETempShift.Negate());
}
while (!valueETempShift.CanFitInInt32()) {
valueETempShift = valueETempShift.Subtract(0x7ffffff0);
ret = ret.ShiftLeft(0x7ffffff0);
}
return ret.ShiftLeft(valueETempShift.ToInt32Checked());
}
/// <summary>Returns an arbitrary-precision integer with the bits
/// shifted to the left by a number of bits. A value of 1 doubles this
/// value, a value of 2 multiplies it by 4, a value of 3 by 8, a value
/// of 4 by 16, and so on.</summary>
/// <param name='numberBits'>The number of bits to shift. Can be
/// negative, in which case this is the same as shiftRight with the
/// absolute value of this parameter.</param>
/// <returns>An arbitrary-precision integer.</returns>
public EInteger ShiftLeft(int numberBits) {
if (numberBits == 0 || this.wordCount == 0) {
return this;
}
if (numberBits < 0) {
return (numberBits == Int32.MinValue) ?
this.ShiftRight(1).ShiftRight(Int32.MaxValue) :
this.ShiftRight(-numberBits);
}
int numWords = this.wordCount;
var shiftWords = (int)(numberBits >> 4);
var shiftBits = (int)(numberBits & 15);
if (!this.negative) {
// Determine shifted integer's word count in advance;
// it's more cache-friendly to do so because the
// unshifted word has less memory
int lastWord = ((int)this.words[this.wordCount - 1]) & 0xffff;
int lastWordBL = NumberUtility.BitLength(lastWord) +
shiftBits;
var newWordCount = 0;
if (lastWordBL <= 16) {
// New bit count is such that an additional word
// is not needed
newWordCount = numWords + shiftWords;
} else {
newWordCount = numWords + BitsToWords(numberBits);
}
var ret = new short[newWordCount];
Array.Copy(this.words, 0, ret, shiftWords, numWords);
ShiftWordsLeftByBits(
ret,
shiftWords,
newWordCount - shiftWords,
shiftBits);
#if DEBUG
if (newWordCount <= 0 || ret[newWordCount - 1] == 0) {
throw new InvalidOperationException();
}
#endif
return new EInteger(newWordCount, ret, false);
} else {
var ret = new short[numWords + BitsToWords((int)numberBits)];
Array.Copy(this.words, ret, numWords);
TwosComplement(ret, 0, (int)ret.Length);
ShiftWordsLeftByWords(ret, 0, numWords + shiftWords, shiftWords);
ShiftWordsLeftByBits(
ret,
(int)shiftWords,
numWords + BitsToWords(shiftBits),
shiftBits);
TwosComplement(ret, 0, (int)ret.Length);
return new EInteger(CountWords(ret), ret, true);
}
}
private static void OrWords(short[] r, short[] a, short[] b, int n) {
for (var i = 0; i < n; ++i) {
r[i] = unchecked((short)(a[i] | b[i]));
}
}
private static void XorWords(short[] r, short[] a, short[] b, int n) {
for (var i = 0; i < n; ++i) {
r[i] = unchecked((short)(a[i] ^ b[i]));
}
}
private static void NotWords(short[] r, int n) {
for (var i = 0; i < n; ++i) {
r[i] = unchecked((short)(~r[i]));
}
}
private static void AndWords(short[] r, short[] a, short[] b, int n) {
for (var i = 0; i < n; ++i) {
r[i] = unchecked((short)(a[i] & b[i]));
}
}
/// <summary>Returns an arbitrary-precision integer with every bit
/// flipped from this one (also called an inversion or NOT
/// operation).</summary>
/// <returns>An arbitrary-precision integer in which each bit in its
/// two's complement representation is set if the corresponding bit of
/// this integer is clear, and vice versa. Returns -1 if this integer
/// is 0. If this integer is positive, the return value is negative,
/// and vice versa. This method uses the two's complement form of
/// negative integers (see
/// <see cref='PeterO.Numbers.EDecimal'>"Forms of numbers"</see> ). For
/// example, in binary, NOT 10100 = ...11101011 (or in decimal, NOT 20
/// = -21). In binary, NOT ...11100110 = 11001 (or in decimal, NOT -26
/// = 25).</returns>
public EInteger Not() {
if (this.wordCount == 0) {
return EInteger.FromInt32(-1);
}
var valueXaNegative = false;
var valueXaWordCount = 0;
var valueXaReg = new short[this.wordCount];
Array.Copy(this.words, valueXaReg, valueXaReg.Length);
valueXaWordCount = this.wordCount;
if (this.negative) {
TwosComplement(valueXaReg, 0, (int)valueXaReg.Length);
}
NotWords(
valueXaReg,
(int)valueXaReg.Length);
if (this.negative) {
TwosComplement(valueXaReg, 0, (int)valueXaReg.Length);
}
valueXaNegative = !this.negative;
valueXaWordCount = CountWords(valueXaReg);
return (valueXaWordCount == 0) ? EInteger.Zero : new
EInteger(valueXaWordCount, valueXaReg, valueXaNegative);
}
/// <summary>Extracts the lowest bits of this integer. This is
/// equivalent to <c>And(2^longBitCount - 1)</c>, but is more
/// efficient when this integer is non-negative and longBitCount's
/// value is large.</summary>
/// <param name='longBitCount'>The number of bits to extract from the
/// lowest part of this integer.</param>
/// <returns>A value equivalent to <c>And(2^longBitCount - 1)</c>.</returns>
public EInteger LowBits(long longBitCount) {
if (longBitCount < 0) {
throw new ArgumentException("\"longBitCount\" (" + longBitCount +
") is" + "\u0020not greater or equal to 0");
}
return (longBitCount <= Int32.MaxValue) ?
this.LowBits((int)longBitCount) :
this.LowBits(EInteger.FromInt64(longBitCount));
}
/// <summary>Extracts the lowest bits of this integer. This is
/// equivalent to <c>And(2^bitCount - 1)</c>, but is more efficient
/// when this integer is non-negative and bitCount's value is
/// large.</summary>
/// <param name='bitCount'>The number of bits to extract from the
/// lowest part of this integer.</param>
/// <returns>A value equivalent to <c>And(2^bitCount - 1)</c>.</returns>
public EInteger LowBits(int bitCount) {
if (bitCount < 0) {
throw new ArgumentException("\"bitCount\" (" + bitCount + ") is" +
"\u0020not greater or equal to 0");
}
if (bitCount == 0 || this.Sign == 0) {
return EInteger.Zero;
}
if (this.Sign > 0) {
long bits = this.GetUnsignedBitLengthAsInt64();
if (bits <= bitCount) {
return this;
}
}
if (!this.negative) {
long otherWordCount = BitsToWords(bitCount);
if (this.wordCount < otherWordCount) {
return this;
} else if (otherWordCount == 0) {
return EInteger.Zero;
} else {
int intOtherWordCount = checked((int)otherWordCount);
int bitRemainder = bitCount & 15;
int smallerCount = Math.Min(this.wordCount, intOtherWordCount);
var result = new short[intOtherWordCount];
if (bitRemainder == 0) {
Array.Copy(this.words, 0, result, 0, intOtherWordCount);
} else {
short shortMask = unchecked((short)((1 << bitRemainder) - 1));
// DebugUtility.Log("wc={0} bc={1} br={2}
// sm={3}",otherWordCount,bitCount,bitRemainder,shortMask);
Array.Copy(this.words, 0, result, 0, intOtherWordCount - 1);
result[intOtherWordCount - 1] = unchecked((short)(
this.words[intOtherWordCount - 1] & shortMask));
}
smallerCount = CountWords(result);
return (smallerCount == 0) ? EInteger.Zero : new
EInteger(smallerCount, result, false);
}
}
return this.And(EInteger.One.ShiftLeft(bitCount).Subtract(1));
}
/// <summary>Extracts the lowest bits of this integer. This is
/// equivalent to <c>And(2^bigBitCount - 1)</c>, but is more efficient
/// when this integer is non-negative and bigBitCount's value is
/// large.</summary>
/// <param name='bigBitCount'>The number of bits to extract from the
/// lowest part of this integer.</param>
/// <returns>A value equivalent to <c>And(2^bigBitCount - 1)</c>.</returns>
/// <exception cref='ArgumentNullException'>The parameter <paramref
/// name='bigBitCount'/> is null.</exception>
public EInteger LowBits(EInteger bigBitCount) {
if (bigBitCount == null) {
throw new ArgumentNullException(nameof(bigBitCount));
}
if (bigBitCount.Sign < 0) {
throw new ArgumentException("\"bigBitCount.Sign\" (" +
bigBitCount.Sign + ") is not greater or equal to 0");
}
if (bigBitCount.Sign == 0 || this.Sign == 0) {
return EInteger.Zero;
}
if (this.Sign > 0) {
EInteger bigBits = this.GetUnsignedBitLengthAsEInteger();
if (bigBits.CompareTo(bigBitCount) <= 0) {
return this;
}
if (bigBitCount.CanFitInInt32()) {
return this.LowBits((int)bigBitCount.ToInt32Checked());
}
}
if (!this.negative) {
EInteger bigOtherWordCount = bigBitCount.Add(15).Divide(16);
if (
EInteger.FromInt32(this.wordCount).CompareTo(bigOtherWordCount) <
0) {
return this;
}
long otherWordCount = bigOtherWordCount.ToInt32Checked();
if (otherWordCount == 0) {
return EInteger.Zero;
} else {
int intOtherWordCount = checked((int)otherWordCount);
int bitRemainder = bigBitCount.Remainder(16).ToInt32Checked();
int smallerCount = Math.Min(this.wordCount, intOtherWordCount);
var result = new short[intOtherWordCount];
if (bitRemainder == 0) {
Array.Copy(this.words, 0, result, 0, intOtherWordCount);
} else {
short shortMask = unchecked((short)((1 << bitRemainder) - 1));
// DebugUtility.Log("wc={0} bc={1} br={2} sm={3}
// big",otherWordCount,bigBitCount,bitRemainder,shortMask);
Array.Copy(this.words, 0, result, 0, intOtherWordCount - 1);
result[intOtherWordCount - 1] = unchecked((short)(
this.words[intOtherWordCount - 1] & shortMask));
}
smallerCount = CountWords(result);
return (smallerCount == 0) ? EInteger.Zero : new
EInteger(smallerCount, result, false);
}
}
return this.And(EInteger.One.ShiftLeft(bigBitCount).Subtract(1));
}
/// <summary>Does an AND operation between this arbitrary-precision
/// integer and another one.</summary>
/// <param name='other'>Another arbitrary-precision integer that
/// participates in the operation.</param>
/// <returns>An arbitrary-precision integer in which each bit is set if
/// the corresponding bits of this integer and the other integer (in
/// their two's-complement representation) are both set. For example,
/// in binary, 10110 AND 01100 = 00100 (or in decimal, 22 AND 12 = 4).
/// This method uses the two's complement form of negative integers
/// (see
/// <see cref='PeterO.Numbers.EDecimal'>"Forms of numbers"</see> ). For
/// example, in binary, ...11100111 AND 01100 = 00100 (or in decimal,
/// -25 AND 12 = 4).</returns>
/// <exception cref='ArgumentNullException'>The parameter <paramref
/// name='other'/> is null.</exception>
/// <remarks>Each arbitrary-precision integer is treated as a
/// two's-complement form (see
/// <see cref='PeterO.Numbers.EDecimal'>"Forms of numbers"</see> ) for
/// the purposes of this operator.</remarks>
public EInteger And(EInteger other) {
if (other == null) {
throw new ArgumentNullException(nameof(other));
}
if (other.IsZero || this.IsZero) {
return EInteger.Zero;
}
if (!this.negative && !other.negative) {
int smallerCount = Math.Min(this.wordCount, other.wordCount);
short[] smaller = (this.wordCount == smallerCount) ?
this.words : other.words;
short[] bigger = (this.wordCount == smallerCount) ?
other.words : this.words;
var result = new short[smallerCount];
for (var i = 0; i < smallerCount; ++i) {
result[i] = unchecked((short)(smaller[i] & bigger[i]));
}
smallerCount = CountWords(result);
return (smallerCount == 0) ? EInteger.Zero : new
EInteger(smallerCount, result, false);
}
var valueXaNegative = false;
var valueXaWordCount = 0;
var valueXaReg = new short[this.wordCount];
Array.Copy(this.words, valueXaReg, valueXaReg.Length);
var valueXbNegative = false;
var valueXbReg = new short[other.wordCount];
Array.Copy(other.words, valueXbReg, valueXbReg.Length);
valueXaNegative = this.negative;
valueXaWordCount = this.wordCount;
valueXbNegative = other.negative;
valueXaReg = CleanGrow(
valueXaReg,
Math.Max(valueXaReg.Length, valueXbReg.Length));
valueXbReg = CleanGrow(
valueXbReg,
Math.Max(valueXaReg.Length, valueXbReg.Length));
if (valueXaNegative) {
TwosComplement(valueXaReg, 0, (int)valueXaReg.Length);
}
if (valueXbNegative) {
TwosComplement(valueXbReg, 0, (int)valueXbReg.Length);
}
valueXaNegative &= valueXbNegative;
AndWords(valueXaReg, valueXaReg, valueXbReg, (int)valueXaReg.Length);
if (valueXaNegative) {
TwosComplement(valueXaReg, 0, (int)valueXaReg.Length);
}
valueXaWordCount = CountWords(valueXaReg);
return (valueXaWordCount == 0) ? EInteger.Zero : new
EInteger(valueXaWordCount, valueXaReg, valueXaNegative);
}
/// <summary>Does an OR operation between this arbitrary-precision
/// integer and another one.</summary>
/// <param name='second'>Another arbitrary-precision integer that
/// participates in the operation.</param>
/// <returns>An arbitrary-precision integer in which each bit is set if
/// the corresponding bit of this integer is set, the other integer's
/// corresponding bit is set, or both. For example, in binary, 10110 OR
/// 11010 = 11110 (or in decimal, 22 OR 26 = 30). This method uses the
/// two's complement form of negative integers (see
/// <see cref='PeterO.Numbers.EDecimal'>"Forms of numbers"</see> ). For
/// example, in binary, ...11101110 OR 01011 = ...11101111 (or in
/// decimal, -18 OR 11 = -17).</returns>
/// <exception cref='ArgumentNullException'>The parameter <paramref
/// name='second'/> is null.</exception>
/// <remarks>Each arbitrary-precision integer is treated as a
/// two's-complement form (see
/// <see cref='PeterO.Numbers.EDecimal'>"Forms of numbers"</see> ) for
/// the purposes of this operator.</remarks>
public EInteger Or(EInteger second) {
if (second == null) {
throw new ArgumentNullException(nameof(second));
}
if (this.wordCount == 0) {
return second;
}
if (second.wordCount == 0) {
return this;
}
if (!this.negative && !second.negative) {
int smallerCount = Math.Min(this.wordCount, second.wordCount);
int biggerCount = Math.Max(this.wordCount, second.wordCount);
short[] smaller = (this.wordCount == smallerCount) ?
this.words : second.words;
short[] bigger = (this.wordCount == smallerCount) ?
second.words : this.words;
var result = new short[biggerCount];
for (var i = 0; i < smallerCount; ++i) {
result[i] = unchecked((short)(smaller[i] | bigger[i]));
}
Array.Copy(
bigger,
smallerCount,
result,
smallerCount,
biggerCount - smallerCount);
#if DEBUG
if (!(biggerCount > 0)) {
throw new InvalidOperationException(
"doesn't satisfy biggerCount>0");
}
if (!(biggerCount == CountWords(result))) {
throw new InvalidOperationException("doesn't satisfy" +
"\u0020biggerCount==CountWords(result)");
}
#endif
return new EInteger(biggerCount, result, false);
}
var valueXaNegative = false;
var valueXaWordCount = 0;
var valueXaReg = new short[this.wordCount];
Array.Copy(this.words, valueXaReg, valueXaReg.Length);
var valueXbNegative = false;
var valueXbReg = new short[second.wordCount];
Array.Copy(second.words, valueXbReg, valueXbReg.Length);
valueXaNegative = this.negative;
valueXaWordCount = this.wordCount;
valueXbNegative = second.negative;
valueXaReg = CleanGrow(
valueXaReg,
Math.Max(valueXaReg.Length, valueXbReg.Length));
valueXbReg = CleanGrow(
valueXbReg,
Math.Max(valueXaReg.Length, valueXbReg.Length));
if (valueXaNegative) {
TwosComplement(valueXaReg, 0, (int)valueXaReg.Length);
}
if (valueXbNegative) {
TwosComplement(valueXbReg, 0, (int)valueXbReg.Length);
}
valueXaNegative |= valueXbNegative;
OrWords(valueXaReg, valueXaReg, valueXbReg, (int)valueXaReg.Length);
if (valueXaNegative) {
TwosComplement(valueXaReg, 0, (int)valueXaReg.Length);
}
valueXaWordCount = CountWords(valueXaReg);
return (valueXaWordCount == 0) ? EInteger.Zero : new
EInteger(valueXaWordCount, valueXaReg, valueXaNegative);
}
/// <summary>Does an AND NOT operation between this arbitrary-precision
/// integer and another one.</summary>
/// <param name='second'>Another arbitrary-precision integer that
/// participates in the operation.</param>
/// <returns>An arbitrary-precision integer in which each bit is set if
/// the corresponding bit of this integer is set, and the other
/// integer's corresponding bit is
/// <i>not</i> set. For example, in binary, 10110 AND NOT 11010 = 00100
/// (or in decimal, 22 AND NOT 26 = 4). This method uses the two's
/// complement form of negative integers (see
/// <see cref='PeterO.Numbers.EDecimal'>"Forms of numbers"</see> ). For
/// example, in binary, ...11101110 AND NOT 01011 = 00100 (or in
/// decimal, -18 OR 11 = 4).</returns>
/// <exception cref='ArgumentNullException'>The parameter <paramref
/// name='second'/> is null.</exception>
/// <remarks>Each arbitrary-precision integer is treated as a
/// two's-complement form (see
/// <see cref='PeterO.Numbers.EDecimal'>"Forms of numbers"</see> ) for
/// the purposes of this operator.</remarks>
public EInteger AndNot(EInteger second) {
if (second == null) {
throw new ArgumentNullException(nameof(second));
}
return this.And(second.Not());
}
/// <summary>Does an OR NOT operation between this arbitrary-precision
/// integer and another one.</summary>
/// <param name='second'>Another arbitrary-precision integer that
/// participates in the operation.</param>
/// <returns>An arbitrary-precision integer in which each bit is set if
/// the corresponding bit of this integer is set, the other integer's
/// corresponding bit is
/// <i>not</i> set, or both. For example, in binary, 10110 OR NOT 11010
/// = 00100 (or in decimal, 22 OR NOT 26 = 23). This method uses the
/// two's complement form of negative integers (see
/// <see cref='PeterO.Numbers.EDecimal'>"Forms of numbers"</see> ). For
/// example, in binary, ...11101110 OR NOT 01011 = ...11111110 (or in
/// decimal, -18 OR 11 = -2).</returns>
/// <exception cref='ArgumentNullException'>The parameter <paramref
/// name='second'/> is null.</exception>
/// <remarks>Each arbitrary-precision integer is treated as a
/// two's-complement form (see
/// <see cref='PeterO.Numbers.EDecimal'>"Forms of numbers"</see> ) for
/// the purposes of this operator.</remarks>
public EInteger OrNot(EInteger second) {
if (second == null) {
throw new ArgumentNullException(nameof(second));
}
return this.Or(second.Not());
}
/// <summary>Does an OR NOT operation between this arbitrary-precision
/// integer and another one.</summary>
/// <param name='second'>Another arbitrary-precision integer that
/// participates in the operation.</param>
/// <returns>An arbitrary-precision integer in which each bit is set if
/// the corresponding bit of this integer is set, the other integer's
/// corresponding bit is
/// <i>not</i> set, or both. For example, in binary, 10110 OR NOT 11010
/// = 00100 (or in decimal, 22 OR NOT 26 = 23). This method uses the
/// two's complement form of negative integers (see
/// <see cref='PeterO.Numbers.EDecimal'>"Forms of numbers"</see> ). For
/// example, in binary, ...11101110 OR NOT 01011 = ...11111110 (or in
/// decimal, -18 OR 11 = -2).</returns>
/// <exception cref='ArgumentNullException'>The parameter <paramref
/// name='second'/> is null.</exception>
/// <remarks>Each arbitrary-precision integer is treated as a
/// two's-complement form (see
/// <see cref='PeterO.Numbers.EDecimal'>"Forms of numbers"</see> ) for
/// the purposes of this operator.</remarks>
[Obsolete("Does the incorrect implication operation. Use Imply instead.")]
public EInteger Imp(EInteger second) {
return this.OrNot(second);
}
/// <summary>Does an implication or IMP operation between this
/// arbitrary-precision integer and another one. Also means SECOND OR
/// NOT FIRST.</summary>
/// <param name='second'>Another arbitrary-precision integer that
/// participates in the operation.</param>
/// <returns>An arbitrary-precision integer in which each bit is set if
/// the corresponding bit of the other integer is set, this integer's
/// corresponding bit is
/// <i>not</i> set, or both. For example, in binary, 10110 OR NOT 11010
/// = 11010 IMP 10110 = 00100 (or in decimal, 22 OR NOT 26 = 23). This
/// method uses the two's complement form of negative integers (see
/// <see cref='PeterO.Numbers.EDecimal'>"Forms of numbers"</see> ). For
/// example, in binary, ...11101110 OR NOT 01011 = 01011 IMP...11101110
/// =...11111110 (or in decimal, -18 OR 11 = -2).</returns>
/// <exception cref='ArgumentNullException'>The parameter <paramref
/// name='second'/> is null.</exception>
/// <remarks>Each arbitrary-precision integer is treated as a
/// two's-complement form (see
/// <see cref='PeterO.Numbers.EDecimal'>"Forms of numbers"</see> ) for
/// the purposes of this operator.</remarks>
private EInteger Imply(EInteger second) {
if (second == null) {
throw new ArgumentNullException(nameof(second));
}
return second.OrNot(this);
}
/// <summary>Does an XOR NOT operation (or equivalence operation, EQV
/// operation, or exclusive-OR NOT operation) between this
/// arbitrary-precision integer and another one.</summary>
/// <param name='second'>Another arbitrary-precision integer that
/// participates in the operation.</param>
/// <returns>An arbitrary-precision integer in which each bit is set if
/// the corresponding bit of this integer is set or the other integer's
/// corresponding bit is
/// <i>not</i> set, but not both. For example, in binary, 10110 XOR NOT
/// 11010 = 10011 (or in decimal, 22 XOR NOT 26 = 19). This method uses
/// the two's complement form of negative integers (see
/// <see cref='PeterO.Numbers.EDecimal'>"Forms of numbers"</see> ). For
/// example, in binary, ...11101110 XOR NOT 01011 = ...11111010 (or in
/// decimal, -18 OR 11 = -6).</returns>
/// <exception cref='ArgumentNullException'>The parameter <paramref
/// name='second'/> is null.</exception>
/// <remarks>Each arbitrary-precision integer is treated as a
/// two's-complement form (see
/// <see cref='PeterO.Numbers.EDecimal'>"Forms of numbers"</see> ) for
/// the purposes of this operator.</remarks>
public EInteger XorNot(EInteger second) {
if (second == null) {
throw new ArgumentNullException(nameof(second));
}
return this.Xor(second.Not());
}
/// <summary>Does an XOR NOT operation (or equivalence operation, EQV
/// operation, or exclusive-OR NOT operation) between this
/// arbitrary-precision integer and another one.</summary>
/// <param name='second'>Another arbitrary-precision integer that
/// participates in the operation.</param>
/// <returns>An arbitrary-precision integer in which each bit is set if
/// the corresponding bit of this integer is set or the other integer's
/// corresponding bit is
/// <i>not</i> set, but not both. For example, in binary, 10110 XOR NOT
/// 11010 = 10011 (or in decimal, 22 XOR NOT 26 = 19). This method uses
/// the two's complement form of negative integers (see
/// <see cref='PeterO.Numbers.EDecimal'>"Forms of numbers"</see> ). For
/// example, in binary, ...11101110 XOR NOT 01011 = ...11111010 (or in
/// decimal, -18 OR 11 = -6).</returns>
/// <exception cref='ArgumentNullException'>The parameter <paramref
/// name='second'/> is null.</exception>
/// <remarks>Each arbitrary-precision integer is treated as a
/// two's-complement form (see
/// <see cref='PeterO.Numbers.EDecimal'>"Forms of numbers"</see> ) for
/// the purposes of this operator.</remarks>
public EInteger Eqv(EInteger second) {
if (second == null) {
throw new ArgumentNullException(nameof(second));
}
return this.XorNot(second);
}
/// <summary>Does an exclusive OR (XOR) operation between this
/// arbitrary-precision integer and another one.</summary>
/// <param name='other'>Another arbitrary-precision integer that
/// participates in the operation.</param>
/// <returns>An arbitrary-precision integer in which each bit is set if
/// the corresponding bit is set in one input integer but not in the
/// other. For example, in binary, 11010 XOR 01001 = 10011 (or in
/// decimal, 26 XOR 9 = 19). This method uses the two's complement form
/// of negative integers (see
/// <see cref='PeterO.Numbers.EDecimal'>"Forms of numbers"</see> ). For
/// example, in binary, ...11101101 XOR 00011 = ...11101110 (or in
/// decimal, -19 XOR 3 = -18).</returns>
/// <exception cref='ArgumentNullException'>The parameter <paramref
/// name='other'/> is null.</exception>
public EInteger Xor(EInteger other) {
if (other == null) {
throw new ArgumentNullException(nameof(other));
}
if (this.Equals(other)) {
return EInteger.Zero;
}
if (this.wordCount == 0) {
return other;
}
if (other.wordCount == 0) {
return this;
}
if (!this.negative && !other.negative) {
int smallerCount = Math.Min(this.wordCount, other.wordCount);
int biggerCount = Math.Max(this.wordCount, other.wordCount);
short[] smaller = (this.wordCount == smallerCount) ?
this.words : other.words;
short[] bigger = (this.wordCount == smallerCount) ?
other.words : this.words;
var result = new short[biggerCount];
for (var i = 0; i < smallerCount; ++i) {
result[i] = unchecked((short)(smaller[i] ^ bigger[i]));
}
Array.Copy(
bigger,
smallerCount,
result,
smallerCount,
biggerCount - smallerCount);
smallerCount = (smallerCount == biggerCount) ?
CountWords(result) : biggerCount;
#if DEBUG
if (!(smallerCount == CountWords(result))) {
throw new ArgumentException("doesn't satisfy" +
"\u0020smallerCount==CountWords(result)");
}
#endif
return (smallerCount == 0) ? EInteger.Zero :
new EInteger(smallerCount, result, false);
}
var valueXaNegative = false;
var valueXaWordCount = 0;
var valueXaReg = new short[this.wordCount];
Array.Copy(this.words, valueXaReg, valueXaReg.Length);
var valueXbNegative = false;
var valueXbReg = new short[other.wordCount];
Array.Copy(other.words, valueXbReg, valueXbReg.Length);
valueXaNegative = this.negative;
valueXaWordCount = this.wordCount;
valueXbNegative = other.negative;
valueXaReg = CleanGrow(
valueXaReg,
Math.Max(valueXaReg.Length, valueXbReg.Length));
valueXbReg = CleanGrow(
valueXbReg,
Math.Max(valueXaReg.Length, valueXbReg.Length));
if (valueXaNegative) {
TwosComplement(valueXaReg, 0, (int)valueXaReg.Length);
}
if (valueXbNegative) {
TwosComplement(valueXbReg, 0, (int)valueXbReg.Length);
}
valueXaNegative ^= valueXbNegative;
XorWords(valueXaReg, valueXaReg, valueXbReg, (int)valueXaReg.Length);
if (valueXaNegative) {
TwosComplement(valueXaReg, 0, (int)valueXaReg.Length);
}
valueXaWordCount = CountWords(valueXaReg);
return (valueXaWordCount == 0) ? EInteger.Zero : new
EInteger(valueXaWordCount, valueXaReg, valueXaNegative);
}
private short[] Copy() {
var words = new short[this.words.Length];
Array.Copy(this.words, words, this.wordCount);
return words;
}
private static int WordsCompare(
short[] words,
int wordCount,
short[] words2,
int wordCount2) {
return WordsCompare(words, 0, wordCount, words2, 0, wordCount2);
}
private static int WordsCompare(
short[] words,
int pos1,
int wordCount,
short[] words2,
int pos2,
int wordCount2) {
// NOTE: Assumes the number is nonnegative
int size = wordCount;
if (size == 0) {
return (wordCount2 == 0) ? 0 : -1;
} else if (wordCount2 == 0) {
return 1;
}
if (size == wordCount2) {
if (size == 1 && words[pos1] == words2[pos2]) {
return 0;
} else {
int p1 = pos1 + size - 1;
int p2 = pos2 + size - 1;
while (unchecked(size--) != 0) {
int an = ((int)words[p1]) & ShortMask;
int bn = ((int)words2[p2]) & ShortMask;
if (an > bn) {
return 1;
}
if (an < bn) {
return -1;
}
--p1;
--p2;
}
return 0;
}
}
return (size > wordCount2) ? 1 : -1;
}
private static long WordsToLongUnchecked(short[] words, int wordCount) {
// NOTE: Assumes the number is nonnegative
var c = (int)wordCount;
if (c == 0) {
return 0L;
}
long ivv = 0;
int intRetValue = ((int)words[0]) & ShortMask;
if (c > 1) {
intRetValue |= (((int)words[1]) & ShortMask) << 16;
}
if (c > 2) {
int intRetValue2 = ((int)words[2]) & ShortMask;
if (c > 3) {
intRetValue2 |= (((int)words[3]) & ShortMask) << 16;
}
ivv = ((long)intRetValue) & 0xffffffffL;
ivv |= ((long)intRetValue2) << 32;
return ivv;
}
ivv = ((long)intRetValue) & 0xffffffffL;
return ivv;
}
private static bool WordsEqual(
short[] words,
int wordCount,
short[] words2,
int wordCount2) {
// NOTE: Assumes the number is nonnegative
if (wordCount == wordCount2) {
for (var i = 0; i < wordCount; ++i) {
if (words[i] != words2[i]) {
return false;
}
}
return true;
}
return false;
}
private static bool WordsIsEven(short[] words, int wordCount) {
return wordCount == 0 || (words[0] & 0x01) == 0;
}
private static int WordsShiftRightTwo(short[] words, int wordCount) {
// NOTE: Assumes the number is nonnegative
if (wordCount != 0) {
int u;
var carry = 0;
for (int i = wordCount - 1; i >= 0; --i) {
int w = words[i];
u = ((w & 0xfffc) >> 2) | carry;
carry = (w << 14) & 0xc000;
words[i] = unchecked((short)u);
}
if (words[wordCount - 1] == 0) {
--wordCount;
}
}
return wordCount;
}
private static int WordsShiftRightEight(short[] words, int wordCount) {
// NOTE: Assumes the number is nonnegative
if (wordCount != 0) {
int u;
var carry = 0;
for (int i = wordCount - 1; i >= 0; --i) {
int w = words[i];
u = ((w & 0xff00) >> 8) | carry;
carry = (w << 8) & 0xff00;
words[i] = unchecked((short)u);
}
if (words[wordCount - 1] == 0) {
--wordCount;
}
}
return wordCount;
}
private static int WordsShiftRightFour(short[] words, int wordCount) {
// NOTE: Assumes the number is nonnegative
if (wordCount != 0) {
int u;
var carry = 0;
for (int i = wordCount - 1; i >= 0; --i) {
int w = words[i];
u = ((w & 0xfff0) >> 4) | carry;
carry = (w << 12) & 0xf000;
words[i] = unchecked((short)u);
}
if (words[wordCount - 1] == 0) {
--wordCount;
}
}
return wordCount;
}
private static int WordsShiftRightOne(short[] words, int wordCount) {
// NOTE: Assumes the number is nonnegative
if (wordCount != 0) {
int u;
var carry = 0;
for (int i = wordCount - 1; i >= 0; --i) {
int w = words[i];
u = ((w & 0xfffe) >> 1) | carry;
carry = (w << 15) & 0x8000;
words[i] = unchecked((short)u);
}
if (words[wordCount - 1] == 0) {
--wordCount;
}
}
return wordCount;
}
private static int WordsSubtract(
short[] words,
int wordCount,
short[] subtrahendWords,
int subtrahendCount) {
// NOTE: Assumes this value is at least as high as the subtrahend
// and both numbers are nonnegative
var borrow = (short)SubtractInternal(
words,
0,
words,
0,
subtrahendWords,
0,
subtrahendCount);
if (borrow != 0) {
DecrementWords(
words,
subtrahendCount,
(int)(wordCount - subtrahendCount),
borrow);
}
while (wordCount != 0 && words[wordCount - 1] == 0) {
--wordCount;
}
return wordCount;
}
/// <summary>Returns an arbitrary-precision integer with the bits
/// shifted to the right. For this operation, the arbitrary-precision
/// integer is treated as a two's-complement form (see
/// <see cref='PeterO.Numbers.EDecimal'>"Forms of numbers"</see> ).
/// Thus, for negative values, the arbitrary-precision integer is
/// sign-extended.</summary>
/// <param name='numberBits'>The number of bits to shift. Can be
/// negative, in which case this is the same as shiftLeft with the
/// absolute value of this parameter.</param>
/// <returns>An arbitrary-precision integer.</returns>
public EInteger ShiftRight(int numberBits) {
if (numberBits == 0 || this.wordCount == 0) {
return this;
}
if (numberBits < 0) {
return (numberBits == Int32.MinValue) ?
this.ShiftLeft(1).ShiftLeft(Int32.MaxValue) :
this.ShiftLeft(-numberBits);
}
var numWords = (int)this.wordCount;
var shiftWords = (int)(numberBits >> 4);
var shiftBits = (int)(numberBits & 15);
short[] ret;
int retWordCount;
if (this.negative) {
ret = new short[this.words.Length];
Array.Copy(this.words, ret, numWords);
TwosComplement(ret, 0, (int)ret.Length);
ShiftWordsRightByWordsSignExtend(ret, 0, numWords, shiftWords);
if (numWords > shiftWords) {
ShiftWordsRightByBitsSignExtend(
ret,
0,
numWords - shiftWords,
shiftBits);
}
TwosComplement(ret, 0, (int)ret.Length);
retWordCount = ret.Length;
} else {
if (shiftWords >= numWords) {
return EInteger.Zero;
}
ret = new short[this.words.Length];
Array.Copy(this.words, shiftWords, ret, 0, numWords - shiftWords);
if (shiftBits != 0) {
ShiftWordsRightByBits(ret, 0, numWords - shiftWords, shiftBits);
}
retWordCount = numWords - shiftWords;
}
while (retWordCount != 0 &&
ret[retWordCount - 1] == 0) {
--retWordCount;
}
if (retWordCount == 0) {
return EInteger.Zero;
}
if (shiftWords > 2) {
ret = ShortenArray(ret, retWordCount);
}
return new EInteger(retWordCount, ret, this.negative);
}
/// <summary>Finds the square root of this instance's value, rounded
/// down.</summary>
/// <returns>The square root of this object's value. Returns 0 if this
/// value is 0 or less.</returns>
public EInteger Sqrt() {
EInteger[] srrem = this.SqrtRemInternal(false);
return srrem[0];
}
/// <summary>Calculates the square root and the remainder.</summary>
/// <returns>An array of two arbitrary-precision integers: the first
/// integer is the square root, and the second is the difference
/// between this value and the square of the first integer. Returns two
/// zeros if this value is 0 or less, or one and zero if this value
/// equals 1.</returns>
public EInteger[] SqrtRem() {
return this.SqrtRemInternal(true);
}
/// <summary>Finds the nth root of this instance's value, rounded
/// down.</summary>
/// <param name='root'>The root to find; must be 1 or greater. If this
/// value is 2, this method finds the square root; if 3, the cube root,
/// and so on.</param>
/// <returns>The square root of this object's value. Returns 0 if this
/// value is 0 or less.</returns>
/// <exception cref='ArgumentNullException'>The parameter <paramref
/// name='root'/> is null.</exception>
public EInteger Root(EInteger root) {
if (root == null) {
throw new ArgumentNullException(nameof(root));
}
EInteger[] srrem = this.RootRemInternal(root, false);
return srrem[0];
}
/// <summary>Calculates the nth root and the remainder.</summary>
/// <param name='root'>The root to find; must be 1 or greater. If this
/// value is 2, this method finds the square root; if 3, the cube root,
/// and so on.</param>
/// <returns>An array of two arbitrary-precision integers: the first
/// integer is the nth root, and the second is the difference between
/// this value and the nth power of the first integer. Returns two
/// zeros if this value is 0 or less, or one and zero if this value
/// equals 1.</returns>
/// <exception cref='ArgumentNullException'>The parameter <paramref
/// name='root'/> is null.</exception>
public EInteger[] RootRem(EInteger root) {
if (root == null) {
throw new ArgumentNullException(nameof(root));
}
return this.RootRemInternal(root, true);
}
/// <summary>Finds the nth root of this instance's value, rounded
/// down.</summary>
/// <param name='root'>The root to find; must be 1 or greater. If this
/// value is 2, this method finds the square root; if 3, the cube root,
/// and so on.</param>
/// <returns>The square root of this object's value. Returns 0 if this
/// value is 0 or less.</returns>
public EInteger Root(int root) {
EInteger[] srrem = this.RootRemInternal(EInteger.FromInt32(root), false);
return srrem[0];
}
/// <summary>Calculates the nth root and the remainder.</summary>
/// <param name='root'>The root to find; must be 1 or greater. If this
/// value is 2, this method finds the square root; if 3, the cube root,
/// and so on.</param>
/// <returns>An array of two arbitrary-precision integers: the first
/// integer is the nth root, and the second is the difference between
/// this value and the nth power of the first integer. Returns two
/// zeros if this value is 0 or less, or one and zero if this value
/// equals 1.</returns>
public EInteger[] RootRem(int root) {
return this.RootRemInternal(EInteger.FromInt32(root), true);
}
/// <summary>Subtracts an arbitrary-precision integer from this
/// arbitrary-precision integer and returns the result.</summary>
/// <param name='subtrahend'>Another arbitrary-precision
/// integer.</param>
/// <returns>The difference between the two numbers, that is, this
/// arbitrary-precision integer minus another arbitrary-precision
/// integer.</returns>
/// <exception cref='ArgumentNullException'>The parameter <paramref
/// name='subtrahend'/> is null.</exception>
public EInteger Subtract(EInteger subtrahend) {
if (subtrahend == null) {
throw new ArgumentNullException(nameof(subtrahend));
}
return (this.wordCount == 0) ? subtrahend.Negate() :
((subtrahend.wordCount == 0) ? this : this.Add(subtrahend.Negate()));
}
/// <summary>Returns a byte array of this integer's value. The byte
/// array will take the number's two's-complement form (see
/// <see cref='PeterO.Numbers.EDecimal'>"Forms of numbers"</see> ),
/// using the fewest bytes necessary to store its value unambiguously.
/// If this value is negative, the bits that appear beyond the most
/// significant bit of the number will be all ones. The resulting byte
/// array can be passed to the <c>FromBytes()</c> method (with the same
/// byte order) to reconstruct this integer's value.</summary>
/// <param name='littleEndian'>See the 'littleEndian' parameter of the
/// <c>FromBytes()</c> method.</param>
/// <returns>A byte array. If this value is 0, returns a byte array
/// with the single element 0.</returns>
public byte[] ToBytes(bool littleEndian) {
int sign = this.Sign;
if (sign == 0) {
return new[] { (byte)0 };
}
if (sign > 0) {
int byteCount = this.ByteCount();
int byteArrayLength = byteCount;
if (this.GetUnsignedBit((byteCount * 8) - 1)) {
++byteArrayLength;
}
var bytes = new byte[byteArrayLength];
var j = 0;
for (var i = 0; i < byteCount; i += 2, j++) {
int index = littleEndian ? i : bytes.Length - 1 - i;
int index2 = littleEndian ? i + 1 : bytes.Length - 2 - i;
bytes[index] = (byte)(this.words[j] & 0xff);
if (index2 >= 0 && index2 < byteArrayLength) {
bytes[index2] = (byte)((this.words[j] >> 8) & 0xff);
}
}
return bytes;
} else {
var regdata = new short[this.words.Length];
Array.Copy(this.words, regdata, this.words.Length);
TwosComplement(regdata, 0, (int)regdata.Length);
int byteCount = regdata.Length * 2;
for (int i = regdata.Length - 1; i >= 0; --i) {
if (regdata[i] == unchecked((short)0xffff)) {
byteCount -= 2;
} else if ((regdata[i] & 0xff80) == 0xff80) {
// signed first byte, 0xff second
--byteCount;
break;
} else if ((regdata[i] & 0x8000) == 0x8000) {
// signed second byte
break;
} else {
// unsigned second byte
++byteCount;
break;
}
}
if (byteCount == 0) {
byteCount = 1;
}
var bytes = new byte[byteCount];
bytes[littleEndian ? bytes.Length - 1 : 0] = (byte)0xff;
byteCount = Math.Min(byteCount, regdata.Length * 2);
var j = 0;
for (var i = 0; i < byteCount; i += 2, j++) {
int index = littleEndian ? i : bytes.Length - 1 - i;
int index2 = littleEndian ? i + 1 : bytes.Length - 2 - i;
bytes[index] = (byte)(regdata[j] & 0xff);
if (index2 >= 0 && index2 < byteCount) {
bytes[index2] = (byte)((regdata[j] >> 8) & 0xff);
}
}
return bytes;
}
}
/// <summary>Converts this object's value to a 32-bit signed integer,
/// throwing an exception if it can't fit.</summary>
/// <returns>A 32-bit signed integer.</returns>
/// <exception cref=' T:System.OverflowException'>This object's value
/// is too big to fit a 32-bit signed integer.</exception>
public int ToInt32Checked() {
int count = this.wordCount;
if (count == 0) {
return 0;
}
if (count > 2) {
throw new OverflowException();
}
if (count == 2 && (this.words[1] & 0x8000) != 0) {
if (this.negative && this.words[1] == unchecked((short)0x8000) &&
this.words[0] == 0) {
return Int32.MinValue;
}
throw new OverflowException();
}
return this.ToInt32Unchecked();
}
/// <summary>Converts this object's value to a 32-bit signed integer.
/// If the value can't fit in a 32-bit integer, returns the lower 32
/// bits of this object's two's-complement form (see
/// <see cref='PeterO.Numbers.EDecimal'>"Forms of numbers"</see> ) (in
/// which case the return value might have a different sign than this
/// object's value).</summary>
/// <returns>A 32-bit signed integer.</returns>
public int ToInt32Unchecked() {
var c = (int)this.wordCount;
if (c == 0) {
return 0;
}
int intRetValue = ((int)this.words[0]) & ShortMask;
if (c > 1) {
intRetValue |= (((int)this.words[1]) & ShortMask) << 16;
}
if (this.negative) {
intRetValue = unchecked(intRetValue - 1);
intRetValue = unchecked(~intRetValue);
}
return intRetValue;
}
/// <summary>Converts this object's value to a 64-bit signed integer,
/// throwing an exception if it can't fit.</summary>
/// <returns>A 64-bit signed integer.</returns>
/// <exception cref=' T:System.OverflowException'>This object's value
/// is too big to fit a 64-bit signed integer.</exception>
public long ToInt64Checked() {
int count = this.wordCount;
if (count == 0) {
return 0L;
}
if (count > 4) {
throw new OverflowException();
}
if (count == 4 && (this.words[3] & 0x8000) != 0) {
if (this.negative && this.words[3] == unchecked((short)0x8000) &&
this.words[2] == 0 && this.words[1] == 0 &&
this.words[0] == 0) {
return Int64.MinValue;
}
throw new OverflowException();
}
return this.ToInt64Unchecked();
}
/// <summary>Converts this object's value to a 64-bit signed integer.
/// If the value can't fit in a 64-bit integer, returns the lower 64
/// bits of this object's two's-complement form (see
/// <see cref='PeterO.Numbers.EDecimal'>"Forms of numbers"</see> ) (in
/// which case the return value might have a different sign than this
/// object's value).</summary>
/// <returns>A 64-bit signed integer.</returns>
public long ToInt64Unchecked() {
var c = (int)this.wordCount;
if (c == 0) {
return 0L;
}
long ivv = 0;
int intRetValue = ((int)this.words[0]) & ShortMask;
if (c > 1) {
intRetValue |= (((int)this.words[1]) & ShortMask) << 16;
}
if (c > 2) {
int intRetValue2 = ((int)this.words[2]) & ShortMask;
if (c > 3) {
intRetValue2 |= (((int)this.words[3]) & ShortMask) << 16;
}
if (this.negative) {
if (intRetValue == 0) {
intRetValue = unchecked(intRetValue - 1);
intRetValue2 = unchecked(intRetValue2 - 1);
} else {
intRetValue = unchecked(intRetValue - 1);
}
intRetValue = unchecked(~intRetValue);
intRetValue2 = unchecked(~intRetValue2);
}
ivv = ((long)intRetValue) & 0xffffffffL;
ivv |= ((long)intRetValue2) << 32;
return ivv;
}
ivv = ((long)intRetValue) & 0xffffffffL;
if (this.negative) {
ivv = -ivv;
}
return ivv;
}
// Estimated number of base-N digits, divided by 8 (or estimated
// number of half-digits divided by 16) contained in each 16-bit
// word of an EInteger. Used in divide-and-conquer to guess
// the power-of-base needed to split an EInteger by roughly half.
// Calculated from: ln(65536)*(16/2)/ln(base)
private static int[] estimatedHalfDigitCountPerWord = {
0, 0,
128, 80, 64, 55, 49, 45, 42, 40, 38, 37, 35, 34, 33,
32, 32, 31, 30, 30, 29, 29, 28, 28, 27, 27, 27, 26,
26, 26, 26, 25, 25, 25, 25, 24, 24,
};
private void ToRadixStringGeneral(
StringBuilder outputSB,
int radix) {
#if DEBUG
if (this.negative) {
throw new InvalidOperationException("doesn't satisfy !this.negative");
}
#endif
var i = 0;
if (this.wordCount >= 100) {
var rightBuilder = new StringBuilder();
long digits = ((long)estimatedHalfDigitCountPerWord[radix] *
this.wordCount) / 16;
EInteger pow = null;
if (radix == 10) {
pow = NumberUtility.FindPowerOfTen(digits);
} else {
pow = (radix == 5) ?
NumberUtility.FindPowerOfFiveFromBig(EInteger.FromInt64(digits)) :
EInteger.FromInt32(radix).Pow(EInteger.FromInt64(digits));
}
EInteger[] divrem = this.DivRem(pow);
// DebugUtility.Log("divrem wc=" + divrem[0].wordCount + " wc=" + (//
// divrem[1].wordCount));
divrem[0].ToRadixStringGeneral(outputSB, radix);
divrem[1].ToRadixStringGeneral(rightBuilder, radix);
for (i = rightBuilder.Length; i < digits; ++i) {
outputSB.Append('0');
}
outputSB.Append(rightBuilder.ToString());
return;
}
char[] s;
short[] tempReg;
int numWordCount;
if (radix == 10) {
if (this.CanFitInInt64()) {
outputSB.Append(FastInteger.LongToString(this.ToInt64Unchecked()));
return;
}
tempReg = new short[this.wordCount];
Array.Copy(this.words, tempReg, tempReg.Length);
numWordCount = tempReg.Length;
while (numWordCount != 0 && tempReg[numWordCount - 1] == 0) {
--numWordCount;
}
s = new char[(numWordCount << 4) + 1];
while (numWordCount != 0) {
if (numWordCount == 1 && tempReg[0] > 0 && tempReg[0] <= 0x7fff) {
int rest = tempReg[0];
while (rest != 0) {
// accurate approximation to rest/10 up to 43698,
// and rest can go up to 32767
int newrest = (rest * 26215) >> 18;
s[i++] = Digits[rest - (newrest * 10)];
rest = newrest;
}
break;
}
if (numWordCount == 2 && tempReg[1] > 0 && tempReg[1] <= 0x7fff) {
int rest = ((int)tempReg[0]) & ShortMask;
rest |= (((int)tempReg[1]) & ShortMask) << 16;
while (rest != 0) {
int newrest = (rest < 81920) ? (((rest * 52429) >> 19) & 8191) :
(rest / 10);
s[i++] = Digits[rest - (newrest * 10)];
rest = newrest;
}
break;
} else {
int wci = numWordCount;
short remainderShort = 0;
int quo, rem;
// Divide by 10000
while ((wci--) > 0) {
int currentDividend = unchecked((int)((((int)tempReg[wci]) &
0xffff) | ((int)remainderShort << 16)));
quo = currentDividend / 10000;
tempReg[wci] = unchecked((short)quo);
rem = currentDividend - (10000 * quo);
remainderShort = unchecked((short)rem);
}
int remainderSmall = remainderShort;
// Recalculate word count
while (numWordCount != 0 && tempReg[numWordCount - 1] == 0) {
--numWordCount;
}
// accurate approximation to rest/10 up to 16388,
// and rest can go up to 9999
int newrest = (remainderSmall * 3277) >> 15;
s[i++] = Digits[(int)(remainderSmall - (newrest * 10))];
remainderSmall = newrest;
newrest = (remainderSmall * 3277) >> 15;
s[i++] = Digits[(int)(remainderSmall - (newrest * 10))];
remainderSmall = newrest;
newrest = (remainderSmall * 3277) >> 15;
s[i++] = Digits[(int)(remainderSmall - (newrest * 10))];
remainderSmall = newrest;
s[i++] = Digits[remainderSmall];
}
}
ReverseChars(s, 0, i);
outputSB.Append(s, 0, i);
return;
}
tempReg = new short[this.wordCount];
Array.Copy(this.words, tempReg, tempReg.Length);
numWordCount = tempReg.Length;
while (numWordCount != 0 && tempReg[numWordCount - 1] == 0) {
--numWordCount;
}
i = 0;
s = new char[(numWordCount << 4) + 1];
while (numWordCount != 0) {
if (numWordCount == 1 && tempReg[0] > 0 && tempReg[0] <= 0x7fff) {
int rest = tempReg[0];
while (rest != 0) {
int newrest = rest / radix;
s[i++] = Digits[rest - (newrest * radix)];
rest = newrest;
}
break;
}
if (numWordCount == 2 && tempReg[1] > 0 && tempReg[1] <= 0x7fff) {
int rest = ((int)tempReg[0]) & ShortMask;
rest |= (((int)tempReg[1]) & ShortMask) << 16;
while (rest != 0) {
int newrest = rest / radix;
s[i++] = Digits[rest - (newrest * radix)];
rest = newrest;
}
break;
} else {
int wci = numWordCount;
short remainderShort = 0;
int quo, rem;
// Divide by radix
while ((wci--) > 0) {
int currentDividend = unchecked((int)((((int)tempReg[wci]) &
0xffff) | ((int)remainderShort << 16)));
quo = currentDividend / radix;
tempReg[wci] = unchecked((short)quo);
rem = currentDividend - (radix * quo);
remainderShort = unchecked((short)rem);
}
int remainderSmall = remainderShort;
// Recalculate word count
while (numWordCount != 0 && tempReg[numWordCount - 1] == 0) {
--numWordCount;
}
s[i++] = Digits[remainderSmall];
}
}
ReverseChars(s, 0, i);
outputSB.Append(s, 0, i);
}
/// <summary>Generates a string representing the value of this object,
/// in the given radix.</summary>
/// <param name='radix'>A radix from 2 through 36. For example, to
/// generate a hexadecimal (base-16) string, specify 16. To generate a
/// decimal (base-10) string, specify 10.</param>
/// <returns>A string representing the value of this object. If this
/// value is 0, returns "0". If negative, the string will begin with a
/// minus sign ("-", U+002D). Depending on the radix, the string will
/// use the basic digits 0 to 9 (U+0030 to U+0039) and then the basic
/// upper-case letters A to Z (U+0041 to U+005A). For example, 0-9 in
/// radix 10, and 0-9, then A-F in radix 16.</returns>
public string ToRadixString(int radix) {
if (radix < 2) {
throw new ArgumentException("radix(" + radix +
") is less than 2");
}
if (radix > 36) {
throw new ArgumentException("radix(" + radix +
") is more than 36");
}
if (this.wordCount == 0) {
return "0";
}
if (radix == 10) {
// Decimal
if (this.CanFitInInt64()) {
return FastInteger.LongToString(this.ToInt64Unchecked());
}
var sb = new StringBuilder();
if (this.negative) {
sb.Append('-');
}
this.Abs().ToRadixStringGeneral(sb, radix);
return sb.ToString();
}
if (radix == 16) {
// Hex
var sb = new System.Text.StringBuilder();
if (this.negative) {
sb.Append('-');
}
var firstBit = true;
int word = this.words[this.wordCount - 1];
for (int i = 0; i < 4; ++i) {
if (!firstBit || (word & 0xf000) != 0) {
sb.Append(Digits[(word >> 12) & 0x0f]);
firstBit = false;
}
word <<= 4;
}
for (int j = this.wordCount - 2; j >= 0; --j) {
word = this.words[j];
for (int i = 0; i < 4; ++i) {
sb.Append(Digits[(word >> 12) & 0x0f]);
word <<= 4;
}
}
return sb.ToString();
}
if (radix == 2) {
// Binary
var sb = new System.Text.StringBuilder();
if (this.negative) {
sb.Append('-');
}
var firstBit = true;
int word = this.words[this.wordCount - 1];
for (int i = 0; i < 16; ++i) {
if (!firstBit || (word & 0x8000) != 0) {
sb.Append((word & 0x8000) == 0 ? '0' : '1');
firstBit = false;
}
word <<= 1;
}
for (int j = this.wordCount - 2; j >= 0; --j) {
word = this.words[j];
for (int i = 0; i < 16; ++i) {
sb.Append((word & 0x8000) == 0 ? '0' : '1');
word <<= 1;
}
}
return sb.ToString();
} else {
// Other radixes
var sb = new StringBuilder();
if (this.negative) {
sb.Append('-');
}
this.Abs().ToRadixStringGeneral(sb, radix);
return sb.ToString();
}
}
/// <summary>Converts this object to a text string in base
/// 10.</summary>
/// <returns>A string representation of this object. If this value is
/// 0, returns "0". If negative, the string will begin with a minus
/// sign ("-", U+002D). The string will use the basic digits 0 to 9
/// (U+0030 to U+0039).</returns>
public override string ToString() {
if (this.IsZero) {
return "0";
}
return this.CanFitInInt64() ?
FastInteger.LongToString(this.ToInt64Unchecked()) :
this.ToRadixString(10);
}
private static int AddInternal(
short[] c,
int cstart,
short[] words1,
int astart,
short[] words2,
int bstart,
int n) {
unchecked {
int u;
u = 0;
bool evn = (n & 1) == 0;
int valueNEven = evn ? n : n - 1;
var i = 0;
while (i < valueNEven) {
u = (((int)words1[astart + i]) & ShortMask) +
(((int)words2[bstart + i]) & ShortMask) + (u >> 16);
c[cstart + i] = (short)u;
++i;
u = (((int)words1[astart + i]) & ShortMask) +
(((int)words2[bstart + i]) & ShortMask) + (u >> 16);
c[cstart + i] = (short)u;
++i;
}
if (!evn) {
u = (((int)words1[astart + valueNEven]) & ShortMask) +
(((int)words2[bstart + valueNEven]) & ShortMask) + (u >> 16);
c[cstart + valueNEven] = (short)u;
}
return u >> 16;
}
}
private static int AddUnevenSize(
short[] c,
int cstart,
short[] wordsBigger,
int astart,
int acount,
short[] wordsSmaller,
int bstart,
int bcount) {
#if DEBUG
if (acount < bcount) {
throw new ArgumentException("acount(" + acount + ") is less than " +
bcount);
}
#endif
unchecked {
int u;
u = 0;
for (var i = 0; i < bcount; i += 1) {
u = (((int)wordsBigger[astart + i]) & ShortMask) +
(((int)wordsSmaller[bstart + i]) & ShortMask) + (short)(u >> 16);
c[cstart + i] = (short)u;
}
for (int i = bcount; i < acount; i += 1) {
u = (((int)wordsBigger[astart + i]) & ShortMask) + (short)(u >> 16);
c[cstart + i] = (short)u;
}
return ((int)u >> 16) & ShortMask;
}
}
// Multiplies two operands of different sizes
private static void AsymmetricMultiply(
short[] resultArr,
int resultStart, // uses words1Count + words2Count
short[] tempArr,
int tempStart, // uses words1Count + words2Count
short[] words1,
int words1Start,
int words1Count,
short[] words2,
int words2Start,
int words2Count) {
// DebugUtility.Log("AsymmetricMultiply " + words1Count + " " +
// words2Count + " [r=" + resultStart + " t=" + tempStart + " a=" +
// words1Start + " b=" + words2Start + "]");
#if DEBUG
if (resultArr == null) {
throw new ArgumentNullException(nameof(resultArr));
}
if (resultStart < 0) {
throw new ArgumentException("resultStart(" + resultStart +
") is less than 0");
}
if (resultStart > resultArr.Length) {
throw new ArgumentException("resultStart(" + resultStart +
") is more than " + resultArr.Length);
}
if (words1Count + words2Count < 0) {
throw new ArgumentException("words1Count plus words2Count(" +
(words1Count + words2Count) + ") is less than " +
"0");
}
if (words1Count + words2Count > resultArr.Length) {
throw new ArgumentException("words1Count plus words2Count(" +
(words1Count + words2Count) + ") is more than " + resultArr.Length);
}
if (resultArr.Length - resultStart < words1Count + words2Count) {
throw new ArgumentException("resultArr.Length minus resultStart(" +
(resultArr.Length - resultStart) + ") is less than " + (words1Count +
words2Count));
}
if (tempArr == null) {
throw new ArgumentNullException(nameof(tempArr));
}
if (tempStart < 0) {
throw new ArgumentException("tempStart(" + tempStart +
") is less than 0");
}
if (tempStart > tempArr.Length) {
throw new ArgumentException("tempStart(" + tempStart +
") is more than " + tempArr.Length);
}
if (words1Count + words2Count < 0) {
throw new ArgumentException("words1Count plus words2Count(" +
(words1Count + words2Count) + ") is less than " +
"0");
}
if (words1Count + words2Count > tempArr.Length) {
throw new ArgumentException("words1Count plus words2Count(" +
(words1Count + words2Count) + ") is more than " + tempArr.Length);
}
if (tempArr.Length - tempStart < words1Count + words2Count) {
throw new ArgumentException("tempArr.Length minus tempStart(" +
(tempArr.Length - tempStart) + ") is less than " + (words1Count +
words2Count));
}
if (words1 == null) {
throw new ArgumentNullException(nameof(words1));
}
if (words1Start < 0) {
throw new ArgumentException("words1Start(" + words1Start +
") is less than 0");
}
if (words1Start > words1.Length) {
throw new ArgumentException("words1Start(" + words1Start +
") is more than " + words1.Length);
}
if (words1Count < 0) {
throw new ArgumentException("words1Count(" + words1Count +
") is less than 0");
}
if (words1Count > words1.Length) {
throw new ArgumentException("words1Count(" + words1Count +
") is more than " + words1.Length);
}
if (words1.Length - words1Start < words1Count) {
throw new ArgumentException("words1.Length minus words1Start(" +
(words1.Length - words1Start) + ") is less than " + words1Count);
}
if (words2 == null) {
throw new ArgumentNullException(nameof(words2));
}
if (words2Start < 0) {
throw new ArgumentException("words2Start(" + words2Start +
") is less than 0");
}
if (words2Start > words2.Length) {
throw new ArgumentException("words2Start(" + words2Start +
") is more than " + words2.Length);
}
if (words2Count < 0) {
throw new ArgumentException("words2Count(" + words2Count +
") is less than 0");
}
if (words2Count > words2.Length) {
throw new ArgumentException("words2Count(" + words2Count +
") is more than " + words2.Length);
}
if (words2.Length - words2Start < words2Count) {
throw new ArgumentException("words2.Length minus words2Start(" +
(words2.Length - words2Start) + ") is less than " + words2Count);
}
#endif
if (words1Count == words2Count) {
if (words1Start == words2Start && words1 == words2) {
// Both operands have the same value and the same word count
RecursiveSquare(
resultArr,
resultStart,
tempArr,
tempStart,
words1,
words1Start,
words1Count);
} else if (words1Count == 2) {
// Both operands have a word count of 2
BaselineMultiply2(
resultArr,
resultStart,
words1,
words1Start,
words2,
words2Start);
} else {
// Other cases where both operands have the same word count
SameSizeMultiply(
resultArr,
resultStart,
tempArr,
tempStart,
words1,
words1Start,
words2,
words2Start,
words1Count);
}
return;
}
if (words1Count > words2Count) {
// Ensure that words1 is smaller by swapping if necessary
short[] tmp1 = words1;
words1 = words2;
words2 = tmp1;
int tmp3 = words1Start;
words1Start = words2Start;
words2Start = tmp3;
int tmp2 = words1Count;
words1Count = words2Count;
words2Count = tmp2;
}
if (words1Count == 1 || (words1Count == 2 && words1[words1Start + 1] ==
0)) {
switch (words1[words1Start]) {
case 0:
// words1 is zero, so result is 0
Array.Clear((short[])resultArr, resultStart, words2Count + 2);
return;
case 1:
Array.Copy(
words2,
words2Start,
resultArr,
resultStart,
(int)words2Count);
resultArr[resultStart + words2Count] = (short)0;
resultArr[resultStart + words2Count + 1] = (short)0;
return;
default:
resultArr[resultStart + words2Count] = LinearMultiply(
resultArr,
resultStart,
words2,
words2Start,
words1[words1Start],
words2Count);
resultArr[resultStart + words2Count + 1] = (short)0;
return;
}
}
if (words1Count == 2 && (words2Count & 1) == 0) {
int a0 = ((int)words1[words1Start]) & ShortMask;
int a1 = ((int)words1[words1Start + 1]) & ShortMask;
resultArr[resultStart + words2Count] = (short)0;
resultArr[resultStart + words2Count + 1] = (short)0;
AtomicMultiplyOpt(
resultArr,
resultStart,
a0,
a1,
words2,
words2Start,
0,
words2Count);
AtomicMultiplyAddOpt(
resultArr,
resultStart,
a0,
a1,
words2,
words2Start,
2,
words2Count);
return;
}
if (words1Count <= MultRecursionThreshold && words2Count <=
MultRecursionThreshold) {
SchoolbookMultiply(
resultArr,
resultStart,
words1,
words1Start,
words1Count,
words2,
words2Start,
words2Count);
} else if (words1Count >= Toom4Threshold && words2Count >=
Toom4Threshold) {
Toom4(
resultArr,
resultStart,
words1,
words1Start,
words1Count,
words2,
words2Start,
words2Count);
} else if (words1Count >= Toom3Threshold && words2Count >=
Toom3Threshold) {
Toom3(
resultArr,
resultStart,
words1,
words1Start,
words1Count,
words2,
words2Start,
words2Count);
} else {
int wordsRem = words2Count % words1Count;
int evenmult = (words2Count / words1Count) & 1;
int i;
// DebugUtility.Log("counts=" + words1Count + "," + words2Count +
// " res=" + (resultStart + words1Count) + " temp=" + (tempStart +
// (words1Count << 1)) + " rem=" + wordsRem + " evenwc=" + evenmult);
if (wordsRem == 0) {
// words2Count is divisible by words1count
if (evenmult == 0) {
SameSizeMultiply(
resultArr,
resultStart,
tempArr,
tempStart,
words1,
words1Start,
words2,
words2Start,
words1Count);
Array.Copy(
resultArr,
resultStart + words1Count,
tempArr,
(int)(tempStart + (words1Count << 1)),
words1Count);
for (i = words1Count << 1; i < words2Count; i += words1Count << 1) {
SameSizeMultiply(
tempArr,
tempStart + words1Count + i,
tempArr,
tempStart,
words1,
words1Start,
words2,
words2Start + i,
words1Count);
}
for (i = words1Count; i < words2Count; i += words1Count << 1) {
SameSizeMultiply(
resultArr,
resultStart + i,
tempArr,
tempStart,
words1,
words1Start,
words2,
words2Start + i,
words1Count);
}
} else {
for (i = 0; i < words2Count; i += words1Count << 1) {
SameSizeMultiply(
resultArr,
resultStart + i,
tempArr,
tempStart,
words1,
words1Start,
words2,
words2Start + i,
words1Count);
}
for (i = words1Count; i < words2Count; i += words1Count << 1) {
SameSizeMultiply(
tempArr,
tempStart + words1Count + i,
tempArr,
tempStart,
words1,
words1Start,
words2,
words2Start + i,
words1Count);
}
}
if (
AddInternal(
resultArr,
resultStart + words1Count,
resultArr,
resultStart + words1Count,
tempArr,
tempStart + (words1Count << 1),
words2Count - words1Count) != 0) {
IncrementWords(
resultArr,
(int)(resultStart + words2Count),
words1Count,
(short)1);
}
} else if ((words1Count + words2Count) >= (words1Count << 2)) {
// DebugUtility.Log("Chunked Linear Multiply long");
ChunkedLinearMultiply(
resultArr,
resultStart,
tempArr,
tempStart,
words2,
words2Start,
words2Count,
words1,
words1Start,
words1Count);
} else if (words1Count + 1 == words2Count ||
(words1Count + 2 == words2Count && words2[words2Start +
words2Count - 1] == 0)) {
Array.Clear(
(short[])resultArr,
resultStart,
words1Count + words2Count);
// Multiply the low parts of each operand
SameSizeMultiply(
resultArr,
resultStart,
tempArr,
tempStart,
words1,
words1Start,
words2,
words2Start,
words1Count);
// Multiply the high parts
// while adding carry from the high part of the product
short carry = LinearMultiplyAdd(
resultArr,
resultStart + words1Count,
words1,
words1Start,
words2[words2Start + words1Count],
words1Count);
resultArr[resultStart + words1Count + words1Count] = carry;
} else {
var t2 = new short[words1Count << 2];
// DebugUtility.Log("Chunked Linear Multiply Short");
ChunkedLinearMultiply(
resultArr,
resultStart,
t2,
0,
words2,
words2Start,
words2Count,
words1,
words1Start,
words1Count);
}
}
}
private static void AtomicMultiplyAddOpt(
short[] c,
int valueCstart,
int valueA0,
int valueA1,
short[] words2,
int words2Start,
int istart,
int iend) {
short s;
int d;
int first1MinusFirst0 = ((int)valueA1 - valueA0) & ShortMask;
valueA1 &= 0xffff;
valueA0 &= 0xffff;
unchecked {
if (valueA1 >= valueA0) {
for (int i = istart; i < iend; i += 4) {
int b0 = ((int)words2[words2Start + i]) & ShortMask;
int b1 = ((int)words2[words2Start + i + 1]) & ShortMask;
int csi = valueCstart + i;
if (b0 >= b1) {
s = (short)0;
d = first1MinusFirst0 * (((int)b0 - b1) & ShortMask);
} else {
s = (short)first1MinusFirst0;
d = (((int)s) & ShortMask) * (((int)b0 - b1) & ShortMask);
}
int valueA0B0 = valueA0 * b0;
int a0b0high = (valueA0B0 >> 16) & ShortMask;
int tempInt;
tempInt = valueA0B0 + (((int)c[csi]) & ShortMask);
c[csi] = (short)(((int)tempInt) & ShortMask);
int valueA1B1 = valueA1 * b1;
int a1b1low = valueA1B1 & ShortMask;
int a1b1high = ((int)(valueA1B1 >> 16)) & ShortMask;
tempInt = (((int)(tempInt >> 16)) & ShortMask) +
(((int)valueA0B0) & 0xffff) + (((int)d) & ShortMask) + a1b1low +
(((int)c[csi + 1]) & ShortMask);
c[csi + 1] = (short)(((int)tempInt) & ShortMask);
tempInt = (((int)(tempInt >> 16)) & ShortMask) + a1b1low +
a0b0high + (((int)(d >> 16)) & ShortMask) +
a1b1high - (((int)s) & ShortMask) + (((int)c[csi + 2]) &
ShortMask);
c[csi + 2] = (short)(((int)tempInt) & ShortMask);
tempInt = (((int)(tempInt >> 16)) & ShortMask) + a1b1high +
(((int)c[csi + 3]) & ShortMask);
c[csi + 3] = (short)(((int)tempInt) & ShortMask);
if ((tempInt >> 16) != 0) {
++c[csi + 4];
c[csi + 5] += (short)((c[csi + 4] == 0) ? 1 : 0);
}
}
} else {
for (int i = istart; i < iend; i += 4) {
int valueB0 = ((int)words2[words2Start + i]) & ShortMask;
int valueB1 = ((int)words2[words2Start + i + 1]) & ShortMask;
int csi = valueCstart + i;
if (valueB0 > valueB1) {
s = (short)(((int)valueB0 - valueB1) & ShortMask);
d = first1MinusFirst0 * (((int)s) & ShortMask);
} else {
s = (short)0;
d = (((int)valueA0 - valueA1) & ShortMask) * (((int)valueB1 -
valueB0) & ShortMask);
}
int valueA0B0 = valueA0 * valueB0;
int a0b0high = (valueA0B0 >> 16) & ShortMask;
int tempInt;
tempInt = valueA0B0 + (((int)c[csi]) & ShortMask);
c[csi] = (short)(((int)tempInt) & ShortMask);
int valueA1B1 = valueA1 * valueB1;
int a1b1low = valueA1B1 & ShortMask;
int a1b1high = (valueA1B1 >> 16) & ShortMask;
tempInt = (((int)(tempInt >> 16)) & ShortMask) +
(((int)valueA0B0) & 0xffff) + (((int)d) & ShortMask) + a1b1low +
(((int)c[csi + 1]) & ShortMask);
c[csi + 1] = (short)(((int)tempInt) & ShortMask);
tempInt = (((int)(tempInt >> 16)) & ShortMask) + a1b1low +
a0b0high + (((int)(d >> 16)) & ShortMask) +
a1b1high - (((int)s) & ShortMask) + (((int)c[csi + 2]) &
ShortMask);
c[csi + 2] = (short)(((int)tempInt) & ShortMask);
tempInt = (((int)(tempInt >> 16)) & ShortMask) + a1b1high +
(((int)c[csi + 3]) & ShortMask);
c[csi + 3] = (short)(((int)tempInt) & ShortMask);
if ((tempInt >> 16) != 0) {
++c[csi + 4];
c[csi + 5] += (short)((c[csi + 4] == 0) ? 1 : 0);
}
}
}
}
}
private static void AtomicMultiplyOpt(
short[] c,
int valueCstart,
int valueA0,
int valueA1,
short[] words2,
int words2Start,
int istart,
int iend) {
short s;
int d;
int first1MinusFirst0 = ((int)valueA1 - valueA0) & ShortMask;
valueA1 &= 0xffff;
valueA0 &= 0xffff;
unchecked {
if (valueA1 >= valueA0) {
for (int i = istart; i < iend; i += 4) {
int valueB0 = ((int)words2[words2Start + i]) & ShortMask;
int valueB1 = ((int)words2[words2Start + i + 1]) & ShortMask;
int csi = valueCstart + i;
if (valueB0 >= valueB1) {
s = (short)0;
d = first1MinusFirst0 * (((int)valueB0 - valueB1) & ShortMask);
} else {
s = (short)first1MinusFirst0;
d = (((int)s) & ShortMask) * (((int)valueB0 - valueB1) &
ShortMask);
}
int valueA0B0 = valueA0 * valueB0;
c[csi] = (short)(((int)valueA0B0) & ShortMask);
int a0b0high = (valueA0B0 >> 16) & ShortMask;
int valueA1B1 = valueA1 * valueB1;
int tempInt;
tempInt = a0b0high + (((int)valueA0B0) & ShortMask) + (((int)d) &
0xffff) + (((int)valueA1B1) & ShortMask);
c[csi + 1] = (short)tempInt;
tempInt = valueA1B1 + (((int)(tempInt >> 16)) & ShortMask) +
a0b0high + (((int)(d >> 16)) & ShortMask) + (((int)(valueA1B1 >>
16)) & ShortMask) - (((int)s) & ShortMask);
c[csi + 2] = (short)tempInt;
tempInt >>= 16;
c[csi + 3] = (short)tempInt;
}
} else {
for (int i = istart; i < iend; i += 4) {
int valueB0 = ((int)words2[words2Start + i]) & ShortMask;
int valueB1 = ((int)words2[words2Start + i + 1]) & ShortMask;
int csi = valueCstart + i;
if (valueB0 > valueB1) {
s = (short)(((int)valueB0 - valueB1) & ShortMask);
d = first1MinusFirst0 * (((int)s) & ShortMask);
} else {
s = (short)0;
d = (((int)valueA0 - valueA1) & ShortMask) * (((int)valueB1 -
valueB0) & ShortMask);
}
int valueA0B0 = valueA0 * valueB0;
int a0b0high = (valueA0B0 >> 16) & ShortMask;
c[csi] = (short)(((int)valueA0B0) & ShortMask);
int valueA1B1 = valueA1 * valueB1;
int tempInt;
tempInt = a0b0high + (((int)valueA0B0) & ShortMask) + (((int)d) &
0xffff) + (((int)valueA1B1) & ShortMask);
c[csi + 1] = (short)tempInt;
tempInt = valueA1B1 + (((int)(tempInt >> 16)) & ShortMask) +
a0b0high + (((int)(d >> 16)) & ShortMask) + (((int)(valueA1B1 >>
16)) & ShortMask) - (((int)s) & ShortMask);
c[csi + 2] = (short)tempInt;
tempInt >>= 16;
c[csi + 3] = (short)tempInt;
}
}
}
}
// Multiplies two words by two words with overflow checking
private static void BaselineMultiply2(
short[] result,
int rstart,
short[] words1,
int astart,
short[] words2,
int bstart) {
unchecked {
int p;
short c;
int d;
int a0 = ((int)words1[astart]) & ShortMask;
int a1 = ((int)words1[astart + 1]) & ShortMask;
int b0 = ((int)words2[bstart]) & ShortMask;
int b1 = ((int)words2[bstart + 1]) & ShortMask;
p = a0 * b0;
c = (short)p;
d = ((int)p >> 16) & ShortMask;
result[rstart] = c;
c = (short)d;
d = ((int)d >> 16) & ShortMask;
p = a0 * b1;
p += ((int)c) & ShortMask;
c = (short)p;
d += ((int)p >> 16) & ShortMask;
p = a1 * b0;
p += ((int)c) & ShortMask;
d += ((int)p >> 16) & ShortMask;
result[rstart + 1] = (short)p;
p = a1 * b1;
p += d;
result[rstart + 2] = (short)p;
result[rstart + 3] = (short)(p >> 16);
}
}
// Multiplies four words by four words with overflow checking
private static void BaselineMultiply4(
short[] result,
int rstart,
short[] words1,
int astart,
short[] words2,
int bstart) {
long p;
int c;
long d;
unchecked {
// DebugUtility.Log("ops={0:X4}{1:X4}{2:X4}{3:X4} {4:X4}{5:X4}{6:X4}{7:X4}",
// words1[astart + 3], words1[astart + 2], words1[astart + 1], words1[astart],
// words2[bstart + 3], words2[bstart + 2], words2[bstart + 1],
// words2[bstart]);
long a0 = ((long)words1[astart]) & 0xffffL;
a0 |= (((long)words1[astart + 1]) & 0xffffL) << 16;
long a1 = ((long)words1[astart + 2]) & 0xffffL;
a1 |= (((long)words1[astart + 3]) & 0xffffL) << 16;
long b0 = ((long)words2[bstart]) & 0xffffL;
b0 |= (((long)words2[bstart + 1]) & 0xffffL) << 16;
long b1 = ((long)words2[bstart + 2]) & 0xffffL;
b1 |= (((long)words2[bstart + 3]) & 0xffffL) << 16;
p = a0 * b0;
d = (p >> 32) & 0xffffffffL;
result[rstart] = (short)p;
result[rstart + 1] = (short)(p >> 16);
c = (int)d;
d = (d >> 32) & 0xffffffffL;
p = a0 * b1;
p += ((long)c) & 0xffffffffL;
c = (int)p;
d += (p >> 32) & 0xffffffffL;
p = a1 * b0;
p += ((long)c) & 0xffffffffL;
d += (p >> 32) & 0xffffffffL;
result[rstart + 2] = (short)p;
result[rstart + 3] = (short)(p >> 16);
p = a1 * b1;
p += d;
// DebugUtility.Log("opsx={0:X16} {1:X16}",a1,b1);
result[rstart + 4] = (short)p;
result[rstart + 5] = (short)(p >> 16);
result[rstart + 6] = (short)(p >> 32);
result[rstart + 7] = (short)(p >> 48);
}
}
// Multiplies eight words by eight words without overflow
private static void BaselineMultiply8(
short[] result,
int rstart,
short[] words1,
int astart,
short[] words2,
int bstart) {
unchecked {
int p;
short c;
int d;
const int SMask = ShortMask;
int a0 = ((int)words1[astart]) & SMask;
int a1 = ((int)words1[astart + 1]) & SMask;
int a2 = ((int)words1[astart + 2]) & SMask;
int a3 = ((int)words1[astart + 3]) & SMask;
int a4 = ((int)words1[astart + 4]) & SMask;
int a5 = ((int)words1[astart + 5]) & SMask;
int a6 = ((int)words1[astart + 6]) & SMask;
int a7 = ((int)words1[astart + 7]) & SMask;
int b0 = ((int)words2[bstart]) & SMask;
int b1 = ((int)words2[bstart + 1]) & SMask;
int b2 = ((int)words2[bstart + 2]) & SMask;
int b3 = ((int)words2[bstart + 3]) & SMask;
int b4 = ((int)words2[bstart + 4]) & SMask;
int b5 = ((int)words2[bstart + 5]) & SMask;
int b6 = ((int)words2[bstart + 6]) & SMask;
int b7 = ((int)words2[bstart + 7]) & SMask;
p = a0 * b0;
c = (short)p;
d = ((int)p >> 16) & SMask;
result[rstart] = c;
c = (short)d;
d = ((int)d >> 16) & SMask;
p = a0 * b1;
p += ((int)c) & SMask;
c = (short)p;
d += ((int)p >> 16) & SMask;
p = a1 * b0;
p += ((int)c) & SMask;
c = (short)p;
d += ((int)p >> 16) & SMask;
result[rstart + 1] = c;
c = (short)d;
d = ((int)d >> 16) & SMask;
p = a0 * b2;
p += ((int)c) & SMask;
c = (short)p;
d += ((int)p >> 16) & SMask;
p = a1 * b1;
p += ((int)c) & SMask;
c = (short)p;
d += ((int)p >> 16) & SMask;
p = a2 * b0;
p += ((int)c) & SMask;
c = (short)p;
d += ((int)p >> 16) & SMask;
result[rstart + 2] = c;
c = (short)d;
d = ((int)d >> 16) & SMask;
p = a0 * b3;
p += ((int)c) & SMask;
c = (short)p;
d += ((int)p >> 16) & SMask;
p = a1 * b2;
p += ((int)c) & SMask;
c = (short)p;
d += ((int)p >> 16) & SMask;
p = a2 * b1;
p += ((int)c) & SMask;
c = (short)p;
d += ((int)p >> 16) & SMask;
p = a3 * b0;
p += ((int)c) & SMask;
c = (short)p;
d += ((int)p >> 16) & SMask;
result[rstart + 3] = c;
c = (short)d;
d = ((int)d >> 16) & SMask;
p = a0 * b4;
p += ((int)c) & SMask;
c = (short)p;
d += ((int)p >> 16) & SMask;
p = a1 * b3;
p += ((int)c) & SMask;
d += ((int)p >> 16) & SMask;
p = (a2 * b2) + (p & ShortMask);
d += ((int)p >> 16) & SMask;
p = (a3 * b1) + (p & ShortMask);
d += ((int)p >> 16) & SMask;
p = (a4 * b0) + (p & ShortMask);
d += ((int)p >> 16) & SMask;
result[rstart + 4] = (short)p;
c = (short)d;
d = ((int)d >> 16) & SMask;
p = a0 * b5;
p += ((int)c) & SMask;
c = (short)p;
d += ((int)p >> 16) & SMask;
p = a1 * b4;
p += ((int)c) & SMask;
c = (short)p;
d += ((int)p >> 16) & SMask;
p = a2 * b3;
p += ((int)c) & SMask;
c = (short)p;
d += ((int)p >> 16) & SMask;
p = a3 * b2;
p += ((int)c) & SMask;
c = (short)p;
d += ((int)p >> 16) & SMask;
p = a4 * b1;
p += ((int)c) & SMask;
c = (short)p;
d += ((int)p >> 16) & SMask;
p = a5 * b0;
p += ((int)c) & SMask;
c = (short)p;
d += ((int)p >> 16) & SMask;
result[rstart + 5] = c;
c = (short)d;
d = ((int)d >> 16) & SMask;
p = a0 * b6;
p += ((int)c) & SMask;
c = (short)p;
d += ((int)p >> 16) & SMask;
p = a1 * b5;
p += ((int)c) & SMask;
c = (short)p;
d += ((int)p >> 16) & SMask;
p = a2 * b4;
p += ((int)c) & SMask;
c = (short)p;
d += ((int)p >> 16) & SMask;
p = a3 * b3;
p += ((int)c) & SMask;
c = (short)p;
d += ((int)p >> 16) & SMask;
p = a4 * b2;
p += ((int)c) & SMask;
c = (short)p;
d += ((int)p >> 16) & SMask;
p = a5 * b1;
p += ((int)c) & SMask;
c = (short)p;
d += ((int)p >> 16) & SMask;
p = a6 * b0;
p += ((int)c) & SMask;
c = (short)p;
d += ((int)p >> 16) & SMask;
result[rstart + 6] = c;
c = (short)d;
d = ((int)d >> 16) & SMask;
p = a0 * b7;
p += ((int)c) & SMask;
c = (short)p;
d += ((int)p >> 16) & SMask;
p = a1 * b6;
p += ((int)c) & SMask;
c = (short)p;
d += ((int)p >> 16) & SMask;
p = a2 * b5;
p += ((int)c) & SMask;
c = (short)p;
d += ((int)p >> 16) & SMask;
p = a3 * b4;
p += ((int)c) & SMask;
c = (short)p;
d += ((int)p >> 16) & SMask;
p = a4 * b3;
p += ((int)c) & SMask;
c = (short)p;
d += ((int)p >> 16) & SMask;
p = a5 * b2;
p += ((int)c) & SMask;
c = (short)p;
d += ((int)p >> 16) & SMask;
p = a6 * b1;
p += ((int)c) & SMask;
c = (short)p;
d += ((int)p >> 16) & SMask;
p = a7 * b0;
p += ((int)c) & SMask;
c = (short)p;
d += ((int)p >> 16) & SMask;
result[rstart + 7] = c;
c = (short)d;
d = ((int)d >> 16) & SMask;
p = a1 * b7;
p += ((int)c) & SMask;
c = (short)p;
d += ((int)p >> 16) & SMask;
p = a2 * b6;
p += ((int)c) & SMask;
c = (short)p;
d += ((int)p >> 16) & SMask;
p = a3 * b5;
p += ((int)c) & SMask;
c = (short)p;
d += ((int)p >> 16) & SMask;
p = a4 * b4;
p += ((int)c) & SMask;
c = (short)p;
d += ((int)p >> 16) & SMask;
p = a5 * b3;
p += ((int)c) & SMask;
c = (short)p;
d += ((int)p >> 16) & SMask;
p = a6 * b2;
p += ((int)c) & SMask;
c = (short)p;
d += ((int)p >> 16) & SMask;
p = a7 * b1;
p += ((int)c) & SMask;
c = (short)p;
d += ((int)p >> 16) & SMask;
result[rstart + 8] = c;
c = (short)d;
d = ((int)d >> 16) & SMask;
p = a2 * b7;
p += ((int)c) & SMask;
c = (short)p;
d += ((int)p >> 16) & SMask;
p = a3 * b6;
p += ((int)c) & SMask;
c = (short)p;
d += ((int)p >> 16) & SMask;
p = a4 * b5;
p += ((int)c) & SMask;
c = (short)p;
d += ((int)p >> 16) & SMask;
p = a5 * b4;
p += ((int)c) & SMask;
c = (short)p;
d += ((int)p >> 16) & SMask;
p = a6 * b3;
p += ((int)c) & SMask;
c = (short)p;
d += ((int)p >> 16) & SMask;
p = a7 * b2;
p += ((int)c) & SMask;
c = (short)p;
d += ((int)p >> 16) & SMask;
result[rstart + 9] = c;
c = (short)d;
d = ((int)d >> 16) & SMask;
p = a3 * b7;
p += ((int)c) & SMask;
c = (short)p;
d += ((int)p >> 16) & SMask;
p = a4 * b6;
p += ((int)c) & SMask;
c = (short)p;
d += ((int)p >> 16) & SMask;
p = a5 * b5;
p += ((int)c) & SMask;
c = (short)p;
d += ((int)p >> 16) & SMask;
p = a6 * b4;
p += ((int)c) & SMask;
c = (short)p;
d += ((int)p >> 16) & SMask;
p = a7 * b3;
p += ((int)c) & SMask;
c = (short)p;
d += ((int)p >> 16) & SMask;
result[rstart + 10] = c;
c = (short)d;
d = ((int)d >> 16) & SMask;
p = a4 * b7;
p += ((int)c) & SMask;
c = (short)p;
d += ((int)p >> 16) & SMask;
p = a5 * b6;
p += ((int)c) & SMask;
c = (short)p;
d += ((int)p >> 16) & SMask;
p = a6 * b5;
p += ((int)c) & SMask;
c = (short)p;
d += ((int)p >> 16) & SMask;
p = a7 * b4;
p += ((int)c) & SMask;
c = (short)p;
d += ((int)p >> 16) & SMask;
result[rstart + 11] = c;
c = (short)d;
d = ((int)d >> 16) & SMask;
p = a5 * b7;
p += ((int)c) & SMask;
c = (short)p;
d += ((int)p >> 16) & SMask;
p = a6 * b6;
p += ((int)c) & SMask;
c = (short)p;
d += ((int)p >> 16) & SMask;
p = a7 * b5;
p += ((int)c) & SMask;
c = (short)p;
d += ((int)p >> 16) & SMask;
result[rstart + 12] = c;
c = (short)d;
d = ((int)d >> 16) & SMask;
p = a6 * b7;
p += ((int)c) & SMask;
c = (short)p;
d += ((int)p >> 16) & SMask;
p = a7 * b6;
p += ((int)c) & SMask;
c = (short)p;
d += ((int)p >> 16) & SMask;
result[rstart + 13] = c;
p = a7 * b7;
p += d;
result[rstart + 14] = (short)p;
result[rstart + 15] =
(short)(p >> 16);
}
}
//-----------------------------
// Baseline Square
//-----------------------------
private static void BaselineSquare2(
short[] result,
int rstart,
short[] words1,
int astart) {
unchecked {
int p;
short c;
int d;
int e;
p = (((int)words1[astart]) & ShortMask) * (((int)words1[astart]) &
0xffff);
result[rstart] = (short)p;
e = ((int)p >> 16) & ShortMask;
p = (((int)words1[astart]) & ShortMask) * (((int)words1[astart + 1]) &
0xffff);
c = (short)p;
d = ((int)p >> 16) & ShortMask;
d = (int)((d << 1) + (((int)c >> 15) & 1));
c <<= 1;
e += ((int)c) & ShortMask;
c = (short)e;
e = d + (((int)e >> 16) & ShortMask);
result[rstart + 1] = c;
p = (((int)words1[astart + 1]) & ShortMask) * (((int)words1[astart +
1]) & ShortMask);
p += e;
result[rstart + 2] = (short)p;
result[rstart + 3] = (short)(p >>
16);
}
}
private static void BaselineSquare4(
short[] result,
int rstart,
short[] words1,
int astart) {
unchecked {
int p;
short c;
int d;
int e;
p = (((int)words1[astart]) & ShortMask) * (((int)words1[astart]) &
0xffff);
result[rstart] = (short)p;
e = ((int)p >> 16) & ShortMask;
p = (((int)words1[astart]) & ShortMask) * (((int)words1[astart + 1]) &
0xffff);
c = (short)p;
d = ((int)p >> 16) & ShortMask;
d = (int)((d << 1) + (((int)c >> 15) & 1));
c <<= 1;
e += ((int)c) & ShortMask;
c = (short)e;
e = d + (((int)e >> 16) & ShortMask);
result[rstart + 1] = c;
p = (((int)words1[astart]) & ShortMask) * (((int)words1[astart + 2]) &
0xffff);
c = (short)p;
d = ((int)p >> 16) & ShortMask;
d = (int)((d << 1) + (((int)c >> 15) & 1));
c <<= 1;
p = (((int)words1[astart + 1]) & ShortMask) * (((int)words1[astart +
1]) & ShortMask);
p += ((int)c) & ShortMask;
c = (short)p;
d += ((int)p >> 16) & ShortMask;
e += ((int)c) & ShortMask;
c = (short)e;
e = d + (((int)e >> 16) & ShortMask);
result[rstart + 2] = c;
p = (((int)words1[astart]) & ShortMask) * (((int)words1[astart + 3]) &
0xffff);
c = (short)p;
d = ((int)p >> 16) & ShortMask;
p = (((int)words1[astart + 1]) & ShortMask) * (((int)words1[astart +
2]) & ShortMask);
p += ((int)c) & ShortMask;
c = (short)p;
d += ((int)p >> 16) & ShortMask;
d = (int)((d << 1) + (((int)c >> 15) & 1));
c <<= 1;
e += ((int)c) & ShortMask;
c = (short)e;
e = d + (((int)e >> 16) &
0xffff);
result[rstart + 3] = c;
p = (((int)words1[astart + 1]) & ShortMask) * (((int)words1[astart +
3]) & ShortMask);
c = (short)p;
d = ((int)p >> 16) & ShortMask;
d = (int)((d << 1) + (((int)c >> 15) & 1));
c <<= 1;
p = (((int)words1[astart + 2]) & ShortMask) * (((int)words1[astart +
2]) & ShortMask);
p += ((int)c) & ShortMask;
c = (short)p;
d += ((int)p >> 16) & ShortMask;
e += ((int)c) & ShortMask;
c = (short)e;
e = d + (((int)e >> 16) & ShortMask);
result[rstart + 4] = c;
p = (((int)words1[astart + 2]) & ShortMask) * (((int)words1[astart +
3]) & ShortMask);
c = (short)p;
d = ((int)p >> 16) & ShortMask;
d = (int)((d << 1) + (((int)c >> 15) & 1));
c <<= 1;
e += ((int)c) & ShortMask;
c = (short)e;
e = d + (((int)e >> 16) &
0xffff);
result[rstart + (2 * 4) - 3] = c;
p = (((int)words1[astart + 3]) & ShortMask) * (((int)words1[astart +
3]) & ShortMask);
p += e;
result[rstart + 6] = (short)p;
result[rstart + 7] = (short)(p >>
16);
}
}
private static void BaselineSquare8(
short[] result,
int rstart,
short[] words1,
int astart) {
unchecked {
int p;
short c;
int d;
int e;
p = (((int)words1[astart]) & ShortMask) * (((int)words1[astart]) &
0xffff);
result[rstart] = (short)p;
e = ((int)p >> 16) & ShortMask;
p = (((int)words1[astart]) & ShortMask) * (((int)words1[astart + 1]) &
0xffff);
c = (short)p;
d = ((int)p >> 16) & ShortMask;
d = (int)((d << 1) + (((int)c >> 15) & 1));
c <<= 1;
e += ((int)c) & ShortMask;
c = (short)e;
e = d + (((int)e >> 16) & ShortMask);
result[rstart + 1] = c;
p = (((int)words1[astart]) & ShortMask) * (((int)words1[astart + 2]) &
0xffff);
c = (short)p;
d = ((int)p >> 16) & ShortMask;
d = (int)((d << 1) + (((int)c >> 15) & 1));
c <<= 1;
p = (((int)words1[astart + 1]) & ShortMask) * (((int)words1[astart +
1]) & ShortMask);
p += ((int)c) & ShortMask;
c = (short)p;
d += ((int)p >> 16) & ShortMask;
e += ((int)c) & ShortMask;
c = (short)e;
e = d + (((int)e >> 16) & ShortMask);
result[rstart + 2] = c;
p = (((int)words1[astart]) & ShortMask) * (((int)words1[astart + 3]) &
0xffff);
c = (short)p;
d = ((int)p >> 16) & ShortMask;
p = (((int)words1[astart + 1]) & ShortMask) * (((int)words1[astart +
2]) & ShortMask);
p += ((int)c) & ShortMask;
c = (short)p;
d += ((int)p >> 16) & ShortMask;
d = (int)((d << 1) + (((int)c >> 15) & 1));
c <<= 1;
e += ((int)c) & ShortMask;
c = (short)e;
e = d + (((int)e >> 16) &
0xffff);
result[rstart + 3] = c;
p = (((int)words1[astart]) & ShortMask) * (((int)words1[astart + 4]) &
0xffff);
c = (short)p;
d = ((int)p >> 16) & ShortMask;
p = (((int)words1[astart + 1]) & ShortMask) * (((int)words1[astart +
3]) & ShortMask);
p += ((int)c) & ShortMask;
c = (short)p;
d += ((int)p >> 16) & ShortMask;
d = (int)((d << 1) + (((int)c >> 15) & 1));
c <<= 1;
p = (((int)words1[astart + 2]) & ShortMask) * (((int)words1[astart +
2]) & ShortMask);
p += ((int)c) & ShortMask;
c = (short)p;
d += ((int)p >> 16) & ShortMask;
e += ((int)c) & ShortMask;
c = (short)e;
e = d + (((int)e >> 16) & ShortMask);
result[rstart + 4] = c;
p = (((int)words1[astart]) & ShortMask) * (((int)words1[astart + 5]) &
0xffff);
c = (short)p;
d = ((int)p >> 16) & ShortMask;
p = (((int)words1[astart + 1]) & ShortMask) * (((int)words1[astart +
4]) & ShortMask);
p += ((int)c) & ShortMask;
c = (short)p;
d += ((int)p >> 16) & ShortMask;
p = (((int)words1[astart + 2]) & ShortMask) * (((int)words1[astart +
3]) & ShortMask);
p += ((int)c) & ShortMask;
c = (short)p;
d += ((int)p >> 16) & ShortMask;
d = (int)((d << 1) + (((int)c >> 15) & 1));
c <<= 1;
e += ((int)c) & ShortMask;
c = (short)e;
e = d + (((int)e >> 16) &
0xffff);
result[rstart + 5] = c;
p = (((int)words1[astart]) & ShortMask) * (((int)words1[astart + 6]) &
0xffff);
c = (short)p;
d = ((int)p >> 16) & ShortMask;
p = (((int)words1[astart + 1]) & ShortMask) * (((int)words1[astart +
5]) & ShortMask);
p += ((int)c) & ShortMask;
c = (short)p;
d += ((int)p >> 16) & ShortMask;
p = (((int)words1[astart + 2]) & ShortMask) * (((int)words1[astart +
4]) & ShortMask);
p += ((int)c) & ShortMask;
c = (short)p;
d += ((int)p >> 16) & ShortMask;
d = (int)((d << 1) + (((int)c >> 15) & 1));
c <<= 1;
p = (((int)words1[astart + 3]) & ShortMask) * (((int)words1[astart +
3]) & ShortMask);
p += ((int)c) & ShortMask;
c = (short)p;
d += ((int)p >> 16) & ShortMask;
e += ((int)c) & ShortMask;
c = (short)e;
e = d + (((int)e >> 16) & ShortMask);
result[rstart + 6] = c;
p = (((int)words1[astart]) & ShortMask) * (((int)words1[astart + 7]) &
0xffff);
c = (short)p;
d = ((int)p >> 16) & ShortMask;
p = (((int)words1[astart + 1]) & ShortMask) * (((int)words1[astart +
6]) & ShortMask);
p += ((int)c) & ShortMask;
c = (short)p;
d += ((int)p >> 16) & ShortMask;
p = (((int)words1[astart + 2]) & ShortMask) * (((int)words1[astart +
5]) & ShortMask);
p += ((int)c) & ShortMask;
c = (short)p;
d += ((int)p >> 16) & ShortMask;
p = (((int)words1[astart + 3]) & ShortMask) * (((int)words1[astart +
4]) & ShortMask);
p += ((int)c) & ShortMask;
c = (short)p;
d += ((int)p >> 16) & ShortMask;
d = (int)((d << 1) + (((int)c >> 15) & 1));
c <<= 1;
e += ((int)c) & ShortMask;
c = (short)e;
e = d + (((int)e >> 16) &
0xffff);
result[rstart + 7] = c;
p = (((int)words1[astart + 1]) & ShortMask) * (((int)words1[astart +
7]) & ShortMask);
c = (short)p;
d = ((int)p >> 16) & ShortMask;
p = (((int)words1[astart + 2]) & ShortMask) * (((int)words1[astart +
6]) & ShortMask);
p += ((int)c) & ShortMask;
c = (short)p;
d += ((int)p >> 16) & ShortMask;
p = (((int)words1[astart + 3]) & ShortMask) * (((int)words1[astart +
5]) & ShortMask);
p += ((int)c) & ShortMask;
c = (short)p;
d += ((int)p >> 16) & ShortMask;
d = (int)((d << 1) + (((int)c >> 15) & 1));
c <<= 1;
p = (((int)words1[astart + 4]) & ShortMask) * (((int)words1[astart +
4]) & ShortMask);
p += ((int)c) & ShortMask;
c = (short)p;
d += ((int)p >> 16) & ShortMask;
e += ((int)c) & ShortMask;
c = (short)e;
e = d + (((int)e >> 16) & ShortMask);
result[rstart + 8] = c;
p = (((int)words1[astart + 2]) & ShortMask) * (((int)words1[astart +
7]) & ShortMask);
c = (short)p;
d = ((int)p >> 16) & ShortMask;
p = (((int)words1[astart + 3]) & ShortMask) * (((int)words1[astart +
6]) & ShortMask);
p += ((int)c) & ShortMask;
c = (short)p;
d += ((int)p >> 16) & ShortMask;
p = (((int)words1[astart + 4]) & ShortMask) * (((int)words1[astart +
5]) & ShortMask);
p += ((int)c) & ShortMask;
c = (short)p;
d += ((int)p >> 16) & ShortMask;
d = (int)((d << 1) + (((int)c >> 15) & 1));
c <<= 1;
e += ((int)c) & ShortMask;
c = (short)e;
e = d + (((int)e >> 16) &
0xffff);
result[rstart + 9] = c;
p = (((int)words1[astart + 3]) & ShortMask) * (((int)words1[astart +
7]) & ShortMask);
c = (short)p;
d = ((int)p >> 16) & ShortMask;
p = (((int)words1[astart + 4]) & ShortMask) * (((int)words1[astart +
6]) & ShortMask);
p += ((int)c) & ShortMask;
c = (short)p;
d += ((int)p >> 16) & ShortMask;
d = (int)((d << 1) + (((int)c >> 15) & 1));
c <<= 1;
p = (((int)words1[astart + 5]) & ShortMask) * (((int)words1[astart +
5]) & ShortMask);
p += ((int)c) & ShortMask;
c = (short)p;
d += ((int)p >> 16) & ShortMask;
e += ((int)c) & ShortMask;
c = (short)e;
e = d + (((int)e >> 16) & ShortMask);
result[rstart + 10] = c;
p = (((int)words1[astart + 4]) & ShortMask) * (((int)words1[astart +
7]) & ShortMask);
c = (short)p;
d = ((int)p >> 16) & ShortMask;
p = (((int)words1[astart + 5]) & ShortMask) * (((int)words1[astart +
6]) & ShortMask);
p += ((int)c) & ShortMask;
c = (short)p;
d += ((int)p >> 16) & ShortMask;
d = (int)((d << 1) + (((int)c >> 15) & 1));
c <<= 1;
e += ((int)c) & ShortMask;
c = (short)e;
e = d + (((int)e >> 16) &
0xffff);
result[rstart + 11] = c;
p = (((int)words1[astart + 5]) & ShortMask) * (((int)words1[astart +
7]) & ShortMask);
c = (short)p;
d = ((int)p >> 16) & ShortMask;
d = (int)((d << 1) + (((int)c >> 15) & 1));
c <<= 1;
p = (((int)words1[astart + 6]) & ShortMask) * (((int)words1[astart +
6]) & ShortMask);
p += ((int)c) & ShortMask;
c = (short)p;
d += ((int)p >> 16) & ShortMask;
e += ((int)c) & ShortMask;
c = (short)e;
e = d + (((int)e >> 16) & ShortMask);
result[rstart + 12] = c;
p = (((int)words1[astart + 6]) & ShortMask) * (((int)words1[astart +
7]) & ShortMask);
c = (short)p;
d = ((int)p >> 16) & ShortMask;
d = (int)((d << 1) + (((int)c >> 15) & 1));
c <<= 1;
e += ((int)c) & ShortMask;
c = (short)e;
e = d + (((int)e >> 16) &
0xffff);
result[rstart + 13] = c;
p = (((int)words1[astart + 7]) & ShortMask) * (((int)words1[astart +
7]) & ShortMask);
p += e;
result[rstart + 14] = (short)p;
result[rstart + 15] =
(short)(p >> 16);
}
}
private static int BitPrecision(short numberValue) {
if (numberValue == 0) {
return 0;
}
var i = 16;
unchecked {
if ((numberValue >> 8) == 0) {
numberValue <<= 8;
i -= 8;
}
if ((numberValue >> 12) == 0) {
numberValue <<= 4;
i -= 4;
}
if ((numberValue >> 14) == 0) {
numberValue <<= 2;
i -= 2;
}
if ((numberValue >> 15) == 0) {
--i;
}
}
return i;
}
private static int BitsToWords(int bitCount) {
return ((bitCount & 0x0f) == 0) ? (bitCount >> 4) : (bitCount >> 4) + 1;
}
private static void ChunkedLinearMultiply(
short[] productArr,
int cstart,
short[] tempArr,
int tempStart, // uses bcount*4 space
short[] words1,
int astart,
int acount, // Equal size or longer
short[] words2,
int bstart,
int bcount) {
#if DEBUG
if (acount < bcount) {
throw new ArgumentException("acount(" + acount + ") is less than " +
bcount);
}
if (productArr == null) {
throw new ArgumentNullException(nameof(productArr));
}
if (cstart < 0) {
throw new ArgumentException("cstart(" + cstart + ") is less than " +
"0");
}
if (cstart > productArr.Length) {
throw new ArgumentException("cstart(" + cstart + ") is more than " +
productArr.Length);
}
if (acount + bcount < 0) {
throw new ArgumentException("acount plus bcount(" + (acount +
bcount) + ") is less than 0");
}
if (acount + bcount > productArr.Length) {
throw new ArgumentException("acount plus bcount(" + (acount +
bcount) + ") is more than " + productArr.Length);
}
if (productArr.Length - cstart < acount + bcount) {
throw new ArgumentException("productArr.Length minus cstart(" +
(productArr.Length - cstart) + ") is less than " + (acount + bcount));
}
if (tempArr == null) {
throw new ArgumentNullException(nameof(tempArr));
}
if (tempStart < 0) {
throw new ArgumentException("tempStart(" + tempStart +
") is less than 0");
}
if (tempStart > tempArr.Length) {
throw new ArgumentException("tempStart(" + tempStart +
") is more than " + tempArr.Length);
}
if ((bcount * 4) < 0) {
throw new ArgumentException("bcount * 4 less than 0(" + (bcount * 4) +
")");
}
if ((bcount * 4) > tempArr.Length) {
throw new ArgumentException("bcount * 4 more than " + tempArr.Length +
" (" + (bcount * 4) + ")");
}
if (tempArr.Length - tempStart < bcount * 4) {
throw new ArgumentException("tempArr.Length minus tempStart(" +
(tempArr.Length - tempStart) + ") is less than " + (bcount * 4));
}
if (words1 == null) {
throw new ArgumentNullException(nameof(words1));
}
if (astart < 0) {
throw new ArgumentException("astart(" + astart + ") is less than " +
"0");
}
if (astart > words1.Length) {
throw new ArgumentException("astart(" + astart + ") is more than " +
words1.Length);
}
if (acount < 0) {
throw new ArgumentException("acount(" + acount + ") is less than " +
"0");
}
if (acount > words1.Length) {
throw new ArgumentException("acount(" + acount + ") is more than " +
words1.Length);
}
if (words1.Length - astart < acount) {
throw new ArgumentException("words1.Length minus astart(" +
(words1.Length - astart) + ") is less than " +
acount);
}
if (words2 == null) {
throw new ArgumentNullException(nameof(words2));
}
if (bstart < 0) {
throw new ArgumentException("bstart(" + bstart + ") is less than " +
"0");
}
if (bstart > words2.Length) {
throw new ArgumentException("bstart(" + bstart + ") is more than " +
words2.Length);
}
if (bcount < 0) {
throw new ArgumentException("bcount(" + bcount + ") is less than " +
"0");
}
if (bcount > words2.Length) {
throw new ArgumentException("bcount(" + bcount + ") is more than " +
words2.Length);
}
if (words2.Length - bstart < bcount) {
throw new ArgumentException("words2.Length minus bstart(" +
(words2.Length - bstart) + ") is less than " +
bcount);
}
#endif
unchecked {
var carryPos = 0;
// Set carry to zero
Array.Clear((short[])productArr, cstart, bcount);
for (var i = 0; i < acount; i += bcount) {
int diff = acount - i;
if (diff > bcount) {
SameSizeMultiply(
tempArr,
tempStart,
tempArr,
tempStart + bcount + bcount,
words1,
astart + i,
words2,
bstart,
bcount);
// Add carry
AddUnevenSize(
tempArr,
tempStart,
tempArr,
tempStart,
bcount + bcount,
productArr,
cstart + carryPos,
bcount);
// Copy product and carry
Array.Copy(
tempArr,
tempStart,
productArr,
cstart + i,
bcount + bcount);
carryPos += bcount;
} else {
AsymmetricMultiply(
tempArr,
tempStart, // uses diff + bcount space
tempArr,
tempStart + diff + bcount, // uses diff + bcount
words1,
astart + i,
diff,
words2,
bstart,
bcount);
// Add carry
AddUnevenSize(
tempArr,
tempStart,
tempArr,
tempStart,
diff + bcount,
productArr,
cstart + carryPos,
bcount);
// Copy product without carry
Array.Copy(
tempArr,
tempStart,
productArr,
cstart + i,
diff + bcount);
}
}
}
}
internal static short[] CleanGrow(short[] a, int size) {
if (size > a.Length) {
var newa = new short[size];
Array.Copy(a, newa, a.Length);
return newa;
}
return a;
}
private static int Compare(
short[] words1,
int astart,
short[] words2,
int bstart,
int n) {
while (unchecked(n--) != 0) {
int an = ((int)words1[astart + n]) & ShortMask;
int bn = ((int)words2[bstart + n]) & ShortMask;
if (an > bn) {
return 1;
}
if (an < bn) {
return -1;
}
}
return 0;
}
private static int CompareWithWords1IsOneBigger(
short[] words1,
int astart,
short[] words2,
int bstart,
int words1Count) {
// NOTE: Assumes that words2's count is 1 less
if (words1[astart + words1Count - 1] != 0) {
return 1;
}
int w1c = words1Count;
--w1c;
while (unchecked(w1c--) != 0) {
int an = ((int)words1[astart + w1c]) & ShortMask;
int bn = ((int)words2[bstart + w1c]) & ShortMask;
if (an > bn) {
return 1;
}
if (an < bn) {
return -1;
}
}
return 0;
}
internal static int CountWords(short[] array) {
int n = array.Length;
while (n != 0 && array[n - 1] == 0) {
--n;
}
return (int)n;
}
internal static int CountWords(short[] array, int pos, int len) {
int n = len;
while (n != 0 && array[pos + n - 1] == 0) {
--n;
}
return (int)n;
}
private static int DecrementWords(
short[] words1,
int words1Start,
int n,
short words2) {
unchecked {
short tmp = words1[words1Start];
words1[words1Start] = (short)(tmp - words2);
if ((((int)words1[words1Start]) & ShortMask) <= (((int)tmp) &
ShortMask)) {
return 0;
}
for (int i = 1; i < n; ++i) {
tmp = words1[words1Start + i];
--words1[words1Start + i];
if (tmp != 0) {
return 0;
}
}
return 1;
}
}
private static short Divide32By16(
int dividendLow,
short divisorShort,
bool returnRemainder) {
int tmpInt;
var dividendHigh = 0;
int intDivisor = ((int)divisorShort) & ShortMask;
for (var i = 0; i < 32; ++i) {
tmpInt = dividendHigh >> 31;
dividendHigh <<= 1;
dividendHigh = unchecked((int)(dividendHigh | ((int)((dividendLow >>
31) & 1))));
dividendLow <<= 1;
tmpInt |= dividendHigh;
// unsigned greater-than-or-equal check
if (((tmpInt >> 31) != 0) || (tmpInt >= intDivisor)) {
unchecked {
dividendHigh -= intDivisor;
++dividendLow;
}
}
}
return returnRemainder ? unchecked((short)(((int)dividendHigh) &
0xffff)) : unchecked((short)(((int)dividendLow) &
0xffff));
}
private static short DivideUnsigned(int x, short y) {
if ((x >> 31) == 0) {
// x is already nonnegative
int iy = ((int)y) & ShortMask;
return unchecked((short)((int)x / iy));
} else {
long longX = ((long)x) & 0xffffffffL;
int iy = ((int)y) & ShortMask;
return unchecked((short)(longX / iy));
}
}
private static void FastDivide(
short[] quotientReg,
short[] dividendReg,
int count,
short divisorSmall) {
switch (divisorSmall) {
case 2:
FastDivideAndRemainderTwo(quotientReg, 0, dividendReg, 0, count);
break;
case 10:
FastDivideAndRemainderTen(quotientReg, 0, dividendReg, 0, count);
break;
default:
FastDivideAndRemainder(
quotientReg,
0,
dividendReg,
0,
count,
divisorSmall);
break;
}
}
private static short FastDivideAndRemainderTwo(
short[] quotientReg,
int quotientStart,
short[] dividendReg,
int dividendStart,
int count) {
int quo;
var rem = 0;
int currentDividend;
int ds = dividendStart + count - 1;
int qs = quotientStart + count - 1;
for (var i = 0; i < count; ++i) {
currentDividend = ((int)dividendReg[ds]) & ShortMask;
currentDividend |= rem << 16;
quo = currentDividend >> 1;
quotientReg[qs] = unchecked((short)quo);
rem = currentDividend & 1;
--ds;
--qs;
}
return unchecked((short)rem);
}
private static short FastDivideAndRemainderTen(
short[] quotientReg,
int quotientStart,
short[] dividendReg,
int dividendStart,
int count) {
int quo;
var rem = 0;
int currentDividend;
int ds = dividendStart + count - 1;
int qs = quotientStart + count - 1;
for (var i = 0; i < count; ++i) {
currentDividend = ((int)dividendReg[ds]) & ShortMask;
currentDividend |= rem << 16;
// Fast division by 10
quo = (currentDividend >= 81920) ? currentDividend / 10 :
(((currentDividend * 52429) >> 19) & 8191);
quotientReg[qs] = unchecked((short)quo);
rem = currentDividend - (10 * quo);
--ds;
--qs;
}
return unchecked((short)rem);
}
private static short FastDivideAndRemainder(
short[] quotientReg,
int quotientStart,
short[] dividendReg,
int dividendStart,
int count,
short divisorSmall) {
int idivisor = ((int)divisorSmall) & ShortMask;
int quo;
var rem = 0;
int ds = dividendStart + count - 1;
int qs = quotientStart + count - 1;
int currentDividend;
if (idivisor < 0x8000) {
for (var i = 0; i < count; ++i) {
currentDividend = ((int)dividendReg[ds]) & ShortMask;
currentDividend |= rem << 16;
quo = currentDividend / idivisor;
quotientReg[qs] = unchecked((short)quo);
rem = currentDividend - (idivisor * quo);
--ds;
--qs;
}
} else {
for (var i = 0; i < count; ++i) {
currentDividend = ((int)dividendReg[ds]) & ShortMask;
currentDividend |= rem << 16;
if ((currentDividend >> 31) == 0) {
quo = currentDividend / idivisor;
quotientReg[qs] = unchecked((short)quo);
rem = currentDividend - (idivisor * quo);
} else {
quo = ((int)DivideUnsigned(
currentDividend,
divisorSmall)) & ShortMask;
quotientReg[qs] = unchecked((short)quo);
rem = unchecked(currentDividend - (idivisor * quo));
}
--ds;
--qs;
}
}
return unchecked((short)rem);
}
private static short FastRemainder(
short[] dividendReg,
int count,
short divisorSmall) {
int i = count;
short remainder = 0;
while ((i--) > 0) {
int dividendSmall = unchecked((int)((((int)dividendReg[i]) &
ShortMask) | ((int)remainder << 16)));
remainder = RemainderUnsigned(
dividendSmall,
divisorSmall);
}
return remainder;
}
private static short GetHighHalfAsBorrow(int val) {
return unchecked((short)(0 - ((val >> 16) & ShortMask)));
}
private static int GetLowHalf(int val) {
return val & ShortMask;
}
private static int GetUnsignedBitLengthEx(int numberValue, int wordCount) {
// NOTE: Currently called only if wordCount <= 1000000,
// so that overflow issues with Int32s are not present
int wc = wordCount;
if (wc != 0) {
wc = (wc - 1) << 4;
if (numberValue == 0) {
return wc;
}
wc += 16;
unchecked {
if ((numberValue >> 8) == 0) {
numberValue <<= 8;
wc -= 8;
}
if ((numberValue >> 12) == 0) {
numberValue <<= 4;
wc -= 4;
}
if ((numberValue >> 14) == 0) {
numberValue <<= 2;
wc -= 2;
}
if ((numberValue >> 15) == 0) {
--wc;
}
}
return wc;
}
return 0;
}
internal static short[] GrowForCarry(short[] a, short carry) {
int oldLength = a.Length;
short[] ret = CleanGrow(a, oldLength + 1);
ret[oldLength] = carry;
return ret;
}
internal static int IncrementWords(
short[] words1,
int words1Start,
int n,
short words2) {
unchecked {
short tmp = words1[words1Start];
words1[words1Start] = (short)(tmp + words2);
if ((((int)words1[words1Start]) & ShortMask) >= (((int)tmp) &
ShortMask)) {
return 0;
}
for (int i = 1; i < n; ++i) {
++words1[words1Start + i];
if (words1[words1Start + i] != 0) {
return 0;
}
}
return 1;
}
}
private static short LinearMultiply(
short[] productArr,
int cstart,
short[] words1,
int astart,
short words2,
int n) {
unchecked {
short carry = 0;
int bint = ((int)words2) & ShortMask;
for (var i = 0; i < n; ++i) {
int p;
p = (((int)words1[astart + i]) & ShortMask) * bint;
p += ((int)carry) & ShortMask;
productArr[cstart + i] = (short)p;
carry = (short)(p >> 16);
}
return carry;
}
}
private static short LinearMultiplyAdd(
short[] productArr,
int cstart,
short[] words1,
int astart,
short words2,
int n) {
short carry = 0;
int bint = ((int)words2) & ShortMask;
for (var i = 0; i < n; ++i) {
int p;
p = unchecked((((int)words1[astart + i]) & ShortMask) * bint);
p = unchecked(p + (((int)carry) & ShortMask));
p = unchecked(p + (((int)productArr[cstart + i]) & ShortMask));
productArr[cstart + i] = unchecked((short)p);
carry = (short)(p >> 16);
}
return carry;
}
private static void RecursiveSquare(
short[] resultArr,
int resultStart,
short[] tempArr,
int tempStart,
short[] words1,
int words1Start,
int count) {
if (count <= MultRecursionThreshold) {
switch (count) {
case 2:
BaselineSquare2(resultArr, resultStart, words1, words1Start);
break;
case 4:
BaselineSquare4(resultArr, resultStart, words1, words1Start);
break;
case 8:
BaselineSquare8(resultArr, resultStart, words1, words1Start);
break;
default:
SchoolbookSquare(
resultArr,
resultStart,
words1,
words1Start,
count);
break;
}
} else if (count >= Toom4Threshold) {
Toom4(
resultArr,
resultStart,
words1,
words1Start,
count,
words1,
words1Start,
count);
} else if (count >= Toom3Threshold) {
Toom3(
resultArr,
resultStart,
words1,
words1Start,
count,
words1,
words1Start,
count);
} else if ((count & 1) == 0) {
int count2 = count >> 1;
RecursiveSquare(
resultArr,
resultStart,
tempArr,
tempStart + count,
words1,
words1Start,
count2);
RecursiveSquare(
resultArr,
resultStart + count,
tempArr,
tempStart + count,
words1,
words1Start + count2,
count2);
SameSizeMultiply(
tempArr,
tempStart,
tempArr,
tempStart + count,
words1,
words1Start,
words1,
words1Start + count2,
count2);
int carry = AddInternal(
resultArr,
resultStart + count2,
resultArr,
resultStart + count2,
tempArr,
tempStart,
count);
carry += AddInternal(
resultArr,
resultStart + count2,
resultArr,
resultStart + count2,
tempArr,
tempStart,
count);
IncrementWords(
resultArr,
(int)(resultStart + count + count2),
count2,
(short)carry);
} else {
SameSizeMultiply(
resultArr,
resultStart,
tempArr,
tempStart,
words1,
words1Start,
words1,
words1Start,
count);
}
}
private static short RemainderUnsigned(int x, short y) {
unchecked {
int iy = ((int)y) & ShortMask;
return ((x >> 31) == 0) ? ((short)(((int)x % iy) & ShortMask)) :
Divide32By16(x, y, true);
}
}
private static void ReverseChars(char[] chars, int offset, int length) {
int half = length >> 1;
int right = offset + length - 1;
for (var i = 0; i < half; i++, right--) {
char value = chars[offset + i];
chars[offset + i] = chars[right];
chars[right] = value;
}
}
// NOTE: Renamed from RecursiveMultiply to better show that
// this function only takes operands of the same size, as opposed
// to AsymmetricMultiply.
private static void SameSizeMultiply(
short[] resultArr, // size 2*count
int resultStart,
short[] tempArr, // size 2*count
int tempStart,
short[] words1,
int words1Start, // size count
short[] words2,
int words2Start, // size count
int count) {
// DebugUtility.Log("RecursiveMultiply " + count + " " + count +
// " [r=" + resultStart + " t=" + tempStart + " a=" + words1Start +
// " b=" + words2Start + "]");
#if DEBUG
if (resultArr == null) {
throw new ArgumentNullException(nameof(resultArr));
}
if (resultStart < 0) {
throw new ArgumentException("resultStart(" + resultStart +
") is less than 0");
}
if (resultStart > resultArr.Length) {
throw new ArgumentException("resultStart(" + resultStart +
") is more than " + resultArr.Length);
}
if (count + count < 0) {
throw new ArgumentException("count plus count(" + (count + count) +
") is less than 0");
}
if (count + count > resultArr.Length) {
throw new ArgumentException("count plus count(" + (count + count) +
") is more than " + resultArr.Length);
}
if (resultArr.Length - resultStart < count + count) {
throw new ArgumentException("resultArr.Length minus resultStart(" +
(resultArr.Length - resultStart) +
") is less than " + (count + count));
}
if (tempArr == null) {
throw new ArgumentNullException(nameof(tempArr));
}
if (tempStart < 0) {
throw new ArgumentException("tempStart(" + tempStart +
") is less than 0");
}
if (tempStart > tempArr.Length) {
throw new ArgumentException("tempStart(" + tempStart +
") is more than " + tempArr.Length);
}
if (count + count < 0) {
throw new ArgumentException("count plus count(" + (count + count) +
") is less than 0");
}
if (count + count > tempArr.Length) {
throw new ArgumentException("count plus count(" + (count + count) +
") is more than " + tempArr.Length);
}
if (tempArr.Length - tempStart < count + count) {
throw new ArgumentException("tempArr.Length minus tempStart(" +
(tempArr.Length - tempStart) + ") is less than " + (count + count));
}
if (words1 == null) {
throw new ArgumentNullException(nameof(words1));
}
if (words1Start < 0) {
throw new ArgumentException("words1Start(" + words1Start +
") is less than 0");
}
if (words1Start > words1.Length) {
throw new ArgumentException("words1Start(" + words1Start +
") is more than " + words1.Length);
}
if (count < 0) {
throw new ArgumentException("count(" + count + ") is less than " +
"0");
}
if (count > words1.Length) {
throw new ArgumentException("count(" + count + ") is more than " +
words1.Length);
}
if (words1.Length - words1Start < count) {
throw new ArgumentException("words1.Length minus words1Start(" +
(words1.Length - words1Start) + ") is less than " +
count);
}
if (words2 == null) {
throw new ArgumentNullException(nameof(words2));
}
if (words2Start < 0) {
throw new ArgumentException("words2Start(" + words2Start +
") is less than 0");
}
if (words2Start > words2.Length) {
throw new ArgumentException("words2Start(" + words2Start +
") is more than " + words2.Length);
}
if (count < 0) {
throw new ArgumentException("count(" + count + ") is less than " +
"0");
}
if (count > words2.Length) {
throw new ArgumentException("count(" + count + ") is more than " +
words2.Length);
}
if (words2.Length - words2Start < count) {
throw new ArgumentException("words2.Length minus words2Start(" +
(words2.Length - words2Start) + ") is less than " +
count);
}
#endif
if (count <= MultRecursionThreshold) {
switch (count) {
case 2:
BaselineMultiply2(
resultArr,
resultStart,
words1,
words1Start,
words2,
words2Start);
break;
case 4:
BaselineMultiply4(
resultArr,
resultStart,
words1,
words1Start,
words2,
words2Start);
break;
case 8:
BaselineMultiply8(
resultArr,
resultStart,
words1,
words1Start,
words2,
words2Start);
break;
default:
SchoolbookMultiply(
resultArr,
resultStart,
words1,
words1Start,
count,
words2,
words2Start,
count);
break;
}
} else if (count >= Toom4Threshold) {
Toom4(
resultArr,
resultStart,
words1,
words1Start,
count,
words2,
words2Start,
count);
} else if (count >= Toom3Threshold) {
Toom3(
resultArr,
resultStart,
words1,
words1Start,
count,
words2,
words2Start,
count);
} else {
int countA = count;
while (countA != 0 && words1[words1Start + countA - 1] == 0) {
--countA;
}
int countB = count;
while (countB != 0 && words2[words2Start + countB - 1] == 0) {
--countB;
}
var offset2For1 = 0;
var offset2For2 = 0;
if (countA == 0 || countB == 0) {
// words1 or words2 is empty, so result is 0
Array.Clear((short[])resultArr, resultStart, count << 1);
return;
}
// Split words1 and words2 in two parts each
// Words1 is split into HighA and LowA
// Words2 is split into HighB and LowB
if ((count & 1) == 0) {
// Count is even, so each part will be equal size
int count2 = count >> 1;
if (countA <= count2 && countB <= count2) {
// Both words1 and words2 are smaller than half the
// count (their high parts are 0)
// DebugUtility.Log("Can be smaller: " + AN + "," + BN + "," +
// (count2));
Array.Clear((short[])resultArr, resultStart + count, count);
if (count2 == 8) {
BaselineMultiply8(
resultArr,
resultStart,
words1,
words1Start,
words2,
words2Start);
} else {
SameSizeMultiply(
resultArr,
resultStart,
tempArr,
tempStart,
words1,
words1Start,
words2,
words2Start,
count2);
}
return;
}
int resultMediumHigh = resultStart + count;
int resultHigh = resultMediumHigh + count2;
int resultMediumLow = resultStart + count2;
int tsn = tempStart + count;
// Find the part of words1 with the higher value
// so we can compute the absolute value
offset2For1 = Compare(
words1,
words1Start,
words1,
words1Start + count2,
count2) > 0 ? 0 : count2;
var tmpvar = (int)(words1Start + (count2 ^
offset2For1));
// Abs(LowA - HighA)
SubtractInternal(
resultArr,
resultStart,
words1,
words1Start + offset2For1,
words1,
tmpvar,
count2);
// Find the part of words2 with the higher value
// so we can compute the absolute value
offset2For2 = Compare(
words2,
words2Start,
words2,
words2Start + count2,
count2) > 0 ? 0 : count2;
// Abs(LowB - HighB)
int tmp = words2Start + (count2 ^ offset2For2);
SubtractInternal(
resultArr,
resultMediumLow,
words2,
words2Start + offset2For2,
words2,
tmp,
count2);
// Medium-high/high result = HighA * HighB
SameSizeMultiply(
resultArr,
resultMediumHigh,
tempArr,
tsn,
words1,
words1Start + count2,
words2,
words2Start + count2,
count2);
// Temp = Abs(LowA-HighA) * Abs(LowB-HighB)
SameSizeMultiply(
tempArr,
tempStart,
tempArr,
tsn,
resultArr,
resultStart,
resultArr,
resultMediumLow,
count2);
// Low/Medium-low result = LowA * LowB
SameSizeMultiply(
resultArr,
resultStart,
tempArr,
tsn,
words1,
words1Start,
words2,
words2Start,
count2);
// Medium high result = Low(HighA * HighB) + High(LowA * LowB)
int c2 = AddInternal(
resultArr,
resultMediumHigh,
resultArr,
resultMediumHigh,
resultArr,
resultMediumLow,
count2);
int c3 = c2;
// Medium low result = Low(HighA * HighB) + High(LowA * LowB) +
// Low(LowA * LowB)
c2 += AddInternal(
resultArr,
resultMediumLow,
resultArr,
resultMediumHigh,
resultArr,
resultStart,
count2);
// Medium high result = Low(HighA * HighB) + High(LowA * LowB) +
// High(HighA * HighB)
c3 += AddInternal(
resultArr,
resultMediumHigh,
resultArr,
resultMediumHigh,
resultArr,
resultHigh,
count2);
if (offset2For1 == offset2For2) {
// If high parts of both words were greater
// than their low parts
// or if low parts of both words were greater
// than their high parts
// Medium low/Medium high result = Medium low/Medium high result
// - Low(Temp)
c3 -= SubtractInternal(
resultArr,
resultMediumLow,
resultArr,
resultMediumLow,
tempArr,
tempStart,
count);
} else {
// Medium low/Medium high result = Medium low/Medium high result
// + Low(Temp)
c3 += AddInternal(
resultArr,
resultMediumLow,
resultArr,
resultMediumLow,
tempArr,
tempStart,
count);
}
// Add carry
c3 += IncrementWords(resultArr, resultMediumHigh, count2, (short)c2);
if (c3 != 0) {
IncrementWords(resultArr, resultHigh, count2, (short)c3);
}
} else {
// Count is odd, high part will be 1 shorter
int countHigh = count >> 1; // Shorter part
int countLow = count - countHigh; // Longer part
offset2For1 = CompareWithWords1IsOneBigger(
words1,
words1Start,
words1,
words1Start + countLow,
countLow) > 0 ? 0 : countLow;
// Abs(LowA - HighA)
if (offset2For1 == 0) {
SubtractWords1IsOneBigger(
resultArr,
resultStart,
words1,
words1Start,
words1,
words1Start + countLow,
countLow);
} else {
SubtractWords2IsOneBigger(
resultArr,
resultStart,
words1,
words1Start + countLow,
words1,
words1Start,
countLow);
}
offset2For2 = CompareWithWords1IsOneBigger(
words2,
words2Start,
words2,
words2Start + countLow,
countLow) > 0 ? 0 : countLow;
// Abs(LowB, HighB)
if (offset2For2 == 0) {
SubtractWords1IsOneBigger(
tempArr,
tempStart,
words2,
words2Start,
words2,
words2Start + countLow,
countLow);
} else {
SubtractWords2IsOneBigger(
tempArr,
tempStart,
words2,
words2Start + countLow,
words2,
words2Start,
countLow);
}
// Temp = Abs(LowA-HighA) * Abs(LowB-HighB)
int shorterOffset = countHigh << 1;
int longerOffset = countLow << 1;
SameSizeMultiply(
tempArr,
tempStart + shorterOffset,
resultArr,
resultStart + shorterOffset,
resultArr,
resultStart,
tempArr,
tempStart,
countLow);
// Save part of temp since temp will overlap in part
// in the Low/Medium low result multiply
short resultTmp0 = tempArr[tempStart + shorterOffset];
short resultTmp1 = tempArr[tempStart + shorterOffset + 1];
// Medium high/high result = HighA * HighB
SameSizeMultiply(
resultArr,
resultStart + longerOffset,
resultArr,
resultStart,
words1,
words1Start + countLow,
words2,
words2Start + countLow,
countHigh);
// Low/Medium low result = LowA * LowB
SameSizeMultiply(
resultArr,
resultStart,
tempArr,
tempStart,
words1,
words1Start,
words2,
words2Start,
countLow);
// Restore part of temp
tempArr[tempStart + shorterOffset] = resultTmp0;
tempArr[tempStart + shorterOffset + 1] = resultTmp1;
int countMiddle = countLow << 1;
// Medium high result = Low(HighA * HighB) + High(LowA * LowB)
int c2 = AddInternal(
resultArr,
resultStart + countMiddle,
resultArr,
resultStart + countMiddle,
resultArr,
resultStart + countLow,
countLow);
int c3 = c2;
// Medium low result = Low(HighA * HighB) + High(LowA * LowB) +
// Low(LowA * LowB)
c2 += AddInternal(
resultArr,
resultStart + countLow,
resultArr,
resultStart + countMiddle,
resultArr,
resultStart,
countLow);
// Medium high result = Low(HighA * HighB) + High(LowA * LowB) +
// High(HighA * HighB)
c3 += AddUnevenSize(
resultArr,
resultStart + countMiddle,
resultArr,
resultStart + countMiddle,
countLow,
resultArr,
resultStart + countMiddle + countLow,
countLow - 2);
if (offset2For1 == offset2For2) {
// If high parts of both words were greater
// than their low parts
// or if low parts of both words were greater
// than their high parts
// Medium low/Medium high result = Medium low/Medium high result
// - Low(Temp)
c3 -= SubtractInternal(
resultArr,
resultStart + countLow,
resultArr,
resultStart + countLow,
tempArr,
tempStart + shorterOffset,
countLow << 1);
} else {
// Medium low/Medium high result = Medium low/Medium high result
// + Low(Temp)
c3 += AddInternal(
resultArr,
resultStart + countLow,
resultArr,
resultStart + countLow,
tempArr,
tempStart + shorterOffset,
countLow << 1);
}
// Add carry
c3 += IncrementWords(
resultArr,
resultStart + countMiddle,
countLow,
(short)c2);
if (c3 != 0) {
IncrementWords(
resultArr,
resultStart + countMiddle + countLow,
countLow - 2,
(short)c3);
}
}
}
}
private static void SchoolbookMultiplySameLengthEven(
short[] resultArr,
int resultStart,
short[] words1,
int words1Start,
short[] words2,
int words2Start,
int count) {
int resultPos;
long carry = 0;
long p;
long valueBint;
unchecked {
valueBint = ((int)words2[words2Start]) & ShortMask;
valueBint |= (((long)words2[words2Start + 1]) & ShortMask) << 16;
for (int j = 0; j < count; j += 2) {
p = ((int)words1[words1Start + j]) & ShortMask;
p |= (((long)words1[words1Start + j + 1]) & ShortMask) << 16;
p *= valueBint + carry;
resultArr[resultStart + j] = (short)p;
resultArr[resultStart + j + 1] = (short)(p >> 16);
carry = (p >> 32) & 0xffffffffL;
}
resultArr[resultStart + count] = (short)carry;
resultArr[resultStart + count + 1] = (short)(carry >> 16);
for (int i = 2; i < count; i += 2) {
resultPos = resultStart + i;
carry = 0;
valueBint = ((int)words2[words2Start + i]) & ShortMask;
valueBint |= (((long)words2[words2Start + i + 1]) & ShortMask) << 16;
for (int j = 0; j < count; j += 2, resultPos += 2) {
p = ((int)words1[words1Start + j]) & ShortMask;
p |= (((long)words1[words1Start + j + 1]) & ShortMask) << 16;
p *= valueBint + carry;
p += ((int)resultArr[resultPos]) & ShortMask;
p += (((int)resultArr[resultPos + 1]) & ShortMask) << 16;
resultArr[resultPos] = (short)p;
resultArr[resultPos + 1] = (short)(p >> 16);
carry = (p >> 32) & 0xffffffffL;
}
resultArr[resultStart + i + count] = (short)carry;
resultArr[resultStart + i + count + 1] = (short)(carry >> 16);
}
}
}
private static void SchoolbookMultiplySameLengthOdd(
short[] resultArr,
int resultStart,
short[] words1,
int words1Start,
short[] words2,
int words2Start,
int count) {
int resultPos;
long carry = 0;
long p;
long valueBint;
unchecked {
valueBint = ((int)words2[words2Start]) & ShortMask;
valueBint |= (count > 1) ? (((long)words2[words2Start + 1]) &
ShortMask) << 16 : 0;
for (int j = 0; j < count; j += 2) {
p = ((int)words1[words1Start + j]) & ShortMask;
if (j + 1 < count) {
p |= ((long)words1[words1Start + j + 1]) & ShortMask;
}
p *= valueBint + carry;
resultArr[resultStart + j] = (short)p;
if (j + 1 < count) {
resultArr[resultStart + j + 1] = (short)(p >> 16);
}
carry = (p >> 32) & 0xffffffffL;
}
resultArr[resultStart + count] = (short)carry;
if (count > 1) {
resultArr[resultStart + count + 1] = (short)(carry >> 16);
}
for (int i = 2; i < count; i += 2) {
resultPos = resultStart + i;
carry = 0;
valueBint = ((int)words2[words2Start + i]) & ShortMask;
if (i + 1 < count) {
valueBint |= (((long)words2[words2Start + i + 1]) & ShortMask) <<
16;
}
for (int j = 0; j < count; j += 2, resultPos += 2) {
p = ((int)words1[words1Start + j]) & ShortMask;
if (j + 1 < count) {
p |= (((long)words1[words1Start + j + 1]) & ShortMask) << 16;
}
p *= valueBint + carry;
p += ((int)resultArr[resultPos]) & ShortMask;
if (j + 1 < count) {
p += (((int)resultArr[resultPos + 1]) & ShortMask) << 16;
resultArr[resultPos] = (short)p;
resultArr[resultPos + 1] = (short)(p >> 16);
carry = (p >> 32) & 0xffffffffL;
} else {
resultArr[resultPos] = (short)p;
carry = p >> 16;
}
}
resultArr[resultStart + i + count] = (short)carry;
if (i + 1 < count) {
resultArr[resultStart + i + count + 1] = (short)(carry >> 16);
}
}
}
}
private static void SchoolbookMultiply(
short[] resultArr,
int resultStart,
short[] words1,
int words1Start,
int words1Count,
short[] words2,
int words2Start,
int words2Count) {
#if DEBUG
// Avoid overlaps
if (resultArr == words1) {
int m1 = Math.Max(resultStart, words1Start);
int m2 = Math.Min(
resultStart + words1Count + words2Count,
words1Start + words1Count);
if (m1 < m2) {
throw new InvalidOperationException();
}
}
if (resultArr == words2) {
int m1 = Math.Max(resultStart, words2Start);
int m2 = Math.Min(
resultStart + words1Count + words2Count,
words2Start + words2Count);
if (m1 < m2) {
throw new InvalidOperationException();
}
}
if (words1Count <= 0) {
throw new ArgumentException("words1Count(" + words1Count +
") is not greater than 0");
}
if (words2Count <= 0) {
throw new ArgumentException("words2Count(" + words2Count +
") is not greater than 0");
}
#endif
if (words1Count == words2Count && (words1Count & 1) == 0) {
/* if ((words1Count & 1) == 0) {
SchoolbookMultiplySameLengthEven(
resultArr,
resultStart,
words1,
words1Start,
words2,
words2Start,
words1Count);
return;
} else {
SchoolbookMultiplySameLengthOdd(
resultArr,
resultStart,
words1,
words1Start,
words2,
words2Start,
words1Count);
return;
}
*/
}
int resultPos, carry, valueBint;
if (words1Count < words2Count) {
// words1 is shorter than words2, so put words2 on top
carry = 0;
valueBint = ((int)words1[words1Start]) & ShortMask;
for (int j = 0; j < words2Count; ++j) {
int p;
p = unchecked((((int)words2[words2Start + j]) & ShortMask) *
valueBint);
p = unchecked(p + carry);
resultArr[resultStart + j] = unchecked((short)p);
carry = (p >> 16) & ShortMask;
}
resultArr[resultStart + words2Count] = unchecked((short)carry);
for (var i = 1; i < words1Count; ++i) {
resultPos = resultStart + i;
carry = 0;
valueBint = ((int)words1[words1Start + i]) & ShortMask;
for (int j = 0; j < words2Count; ++j, ++resultPos) {
int p;
p = unchecked((((int)words2[words2Start + j]) & ShortMask) *
valueBint);
p = unchecked(p + carry);
p = unchecked(p + (((int)resultArr[resultPos]) & ShortMask));
resultArr[resultPos] = unchecked((short)p);
carry = (p >> 16) & ShortMask;
}
resultArr[resultStart + i + words2Count] = unchecked((short)carry);
}
} else {
// words2 is shorter or the same length as words1
carry = 0;
valueBint = ((int)words2[words2Start]) & ShortMask;
for (int j = 0; j < words1Count; ++j) {
int p;
p = unchecked((((int)words1[words1Start + j]) & ShortMask) *
valueBint);
p = unchecked(p + carry);
resultArr[resultStart + j] = unchecked((short)p);
carry = (p >> 16) & ShortMask;
}
resultArr[resultStart + words1Count] = unchecked((short)carry);
for (var i = 1; i < words2Count; ++i) {
resultPos = resultStart + i;
carry = 0;
valueBint = ((int)words2[words2Start + i]) & ShortMask;
for (int j = 0; j < words1Count; ++j, ++resultPos) {
int p;
p = unchecked((((int)words1[words1Start + j]) & ShortMask) *
valueBint);
p = unchecked(p + carry);
p = unchecked(p + (((int)resultArr[resultPos]) & ShortMask));
resultArr[resultPos] = unchecked((short)p);
carry = (p >> 16) & ShortMask;
}
resultArr[resultStart + i + words1Count] = unchecked((short)carry);
}
}
}
private static void SchoolbookSquare(
short[] resultArr,
int resultStart,
short[] words1,
int words1Start,
int words1Count) {
// Method assumes that resultArr was already zeroed,
// if resultArr is the same as words1
int cstart;
for (var i = 0; i < words1Count; ++i) {
cstart = resultStart + i;
unchecked {
short carry = 0;
int valueBint = ((int)words1[words1Start + i]) & ShortMask;
for (int j = 0; j < words1Count; ++j) {
int p;
p = (((int)words1[words1Start + j]) & ShortMask) * valueBint;
p += ((int)carry) & ShortMask;
if (i != 0) {
p += ((int)resultArr[cstart + j]) & ShortMask;
}
resultArr[cstart + j] = (short)p;
carry = (short)(p >> 16);
}
resultArr[cstart + words1Count] = carry;
}
}
}
private static short ShiftWordsLeftByBits(
short[] r,
int rstart,
int count,
int shiftBits) {
#if DEBUG
if (shiftBits >= 16) {
throw new ArgumentException("doesn't satisfy shiftBits<16");
}
#endif
int u;
var carry = 0;
if (shiftBits != 0) {
int sb16 = 16 - shiftBits;
int rs = rstart;
for (var i = 0; i < count; ++i, ++rs) {
u = r[rs];
r[rs] = unchecked((short)((u << shiftBits) | carry));
carry = (u & ShortMask) >> sb16;
}
}
return unchecked((short)carry);
}
private static void ShiftWordsLeftByWords(
short[] r,
int rstart,
int n,
int shiftWords) {
shiftWords = Math.Min(shiftWords, n);
if (shiftWords != 0) {
for (int i = n - 1; i >= shiftWords; --i) {
r[rstart + i] = r[rstart + i - shiftWords];
}
Array.Clear((short[])r, rstart, shiftWords);
}
}
private static short ShiftWordsRightByBits(
short[] r,
int rstart,
int n,
int shiftBits) {
short u, carry = 0;
unchecked {
if (shiftBits != 0) {
for (int i = n; i > 0; --i) {
u = r[rstart + i - 1];
r[rstart + i - 1] = (short)((((((int)u) & ShortMask) >>
(int)shiftBits) & ShortMask) | (((int)carry) &
0xffff));
carry = (short)((((int)u) & ShortMask) << (int)(16 - shiftBits));
}
}
return carry;
}
}
private static short ShiftWordsRightByBitsSignExtend(
short[] r,
int rstart,
int n,
int shiftBits) {
unchecked {
short u, carry = (short)((int)0xffff << (int)(16 - shiftBits));
if (shiftBits != 0) {
for (int i = n; i > 0; --i) {
u = r[rstart + i - 1];
r[rstart + i - 1] = (short)(((((int)u) & ShortMask) >>
(int)shiftBits) | (((int)carry) & ShortMask));
carry = (short)((((int)u) & ShortMask) << (int)(16 - shiftBits));
}
}
return carry;
}
}
private static void ShiftWordsRightByWordsSignExtend(
short[] r,
int rstart,
int n,
int shiftWords) {
shiftWords = Math.Min(shiftWords, n);
if (shiftWords != 0) {
for (var i = 0; i + shiftWords < n; ++i) {
r[rstart + i] = r[rstart + i + shiftWords];
}
rstart += n - shiftWords;
// Sign extend
for (var i = 0; i < shiftWords; ++i) {
r[rstart + i] = unchecked((short)0xffff);
}
}
}
private static short[] ShortenArray(short[] reg, int wordCount) {
if (reg.Length > 32) {
int newLength = wordCount;
if (newLength < reg.Length && (reg.Length - newLength) >= 16) {
// Reallocate the array if the desired length
// is much smaller than the current length
var newreg = new short[newLength];
Array.Copy(reg, newreg, Math.Min(newLength, reg.Length));
reg = newreg;
}
}
return reg;
}
private static int SubtractWords1IsOneBigger(
short[] c,
int cstart,
short[] words1,
int astart,
short[] words2,
int bstart,
int words1Count) {
// Assumes that words2's count is 1 less
unchecked {
int u;
u = 0;
int cm1 = words1Count - 1;
for (var i = 0; i < cm1; i += 1) {
u = (((int)words1[astart]) & ShortMask) - (((int)words2[bstart]) &
0xffff) - (int)((u >> 31) & 1);
c[cstart++] = (short)u;
++astart;
++bstart;
}
u = (((int)words1[astart]) & ShortMask) - (int)((u >> 31) & 1);
c[cstart++] = (short)u;
return (int)((u >> 31) & 1);
}
}
private static int SubtractWords2IsOneBigger(
short[] c,
int cstart,
short[] words1,
int astart,
short[] words2,
int bstart,
int words2Count) {
// Assumes that words1's count is 1 less
int u;
u = 0;
int cm1 = words2Count - 1;
for (var i = 0; i < cm1; i += 1) {
u = unchecked((((int)words1[astart]) & ShortMask) -
(((int)words2[bstart]) & ShortMask) - (int)((u >> 31) & 1));
c[cstart++] = unchecked((short)u);
++astart;
++bstart;
}
u = 0 - unchecked((((int)words2[bstart]) & ShortMask) - (int)((u >>
31) & 1));
c[cstart++] = unchecked((short)u);
return (int)((u >> 31) & 1);
}
private static int SubtractInternal(
short[] c,
int cstart,
short[] words1,
int astart,
short[] words2,
int bstart,
int n) {
var u = 0;
bool odd = (n & 1) != 0;
if (odd) {
--n;
}
var mask = 0xffff;
for (var i = 0; i < n; i += 2) {
int wb0 = words2[bstart] & mask;
int wb1 = words2[bstart + 1] & mask;
int wa0 = words1[astart] & mask;
int wa1 = words1[astart + 1] & mask;
u = unchecked(wa0 - wb0 - (int)((u >> 31) & 1));
c[cstart++] = unchecked((short)u);
u = unchecked(wa1 - wb1 - (int)((u >> 31) & 1));
c[cstart++] = unchecked((short)u);
astart += 2;
bstart += 2;
}
if (odd) {
u = unchecked((((int)words1[astart]) & mask) -
(((int)words2[bstart]) & mask) - (int)((u >> 31) & 1));
c[cstart++] = unchecked((short)u);
++astart;
++bstart;
}
return (int)((u >> 31) & 1);
}
private static void TwosComplement(
short[] words1,
int words1Start,
int n) {
DecrementWords(words1, words1Start, n, (short)1);
for (var i = 0; i < n; ++i) {
words1[words1Start + i] = unchecked((short)(~words1[words1Start +
i]));
}
}
private int ByteCount() {
int wc = this.wordCount;
if (wc == 0) {
return 0;
}
short s = this.words[wc - 1];
wc = (wc - 1) << 1;
return (s == 0) ? wc : (((s >> 8) == 0) ? wc + 1 : wc + 2);
}
private int PositiveCompare(EInteger t) {
int size = this.wordCount, tempSize = t.wordCount;
return (
size == tempSize) ? Compare(
this.words,
0,
t.words,
0,
(int)size) : (size > tempSize ? 1 : -1);
}
private EInteger[] RootRemInternal(EInteger root, bool useRem) {
if (root.CompareTo(1) == 0) {
EInteger thisValue = this;
return new[] { thisValue, EInteger.Zero };
}
if (root.CompareTo(1) < 0) {
throw new ArgumentOutOfRangeException(nameof(root));
}
if (root.CompareTo(2) == 0) {
return this.SqrtRemInternal(useRem);
}
if (this.Sign <= 0) {
return new[] { EInteger.Zero, EInteger.Zero };
}
if (this.Equals(EInteger.One)) {
return new[] { EInteger.One, EInteger.Zero };
}
// if (this.CanFitInInt64()) {
// long v = this.ToInt64Checked();
// int bl = NumberUtility.BitLength(v);
// }
EInteger bl = this.GetUnsignedBitLengthAsEInteger();
EInteger rm1 = root.Subtract(1);
EInteger shift = EInteger.Max(
EInteger.Zero,
bl.Multiply(rm1).Divide(root).Subtract(1));
EInteger ret = this.ShiftRight(shift);
// NOTE: ret is an upper bound of the root
if (ret.Sign > 0) {
// DebugUtility.Log("this->"+this+" initial->"+ret);
while (true) {
EInteger oldret = ret;
// DebugUtility.Log(" thiswc -> " + this.wordCount +
// " :: wc -> " + ret.wordCount + (ret.wordCount==1 ?
// ("=>"+this) : ""));
ret = this.Divide(ret.Pow(rm1)).Add(ret.Multiply(rm1)).Divide(root);
if (oldret.Equals(ret)) {
break;
}
if (ret.CompareTo(oldret) > 0) {
// Starting to vacillate; break
ret = oldret;
break;
}
}
}
if (useRem) {
EInteger erem = this.Subtract(ret.Pow(root));
if (erem.Sign < 0) {
throw new InvalidOperationException();
}
return new[] { ret, erem };
} else {
return new[] { ret, null };
}
}
private EInteger[] SqrtRemInternal(bool useRem) {
if (this.Sign <= 0) {
return new[] { EInteger.Zero, EInteger.Zero };
}
if (this.Equals(EInteger.One)) {
return new[] { EInteger.One, EInteger.Zero };
}
EInteger bigintX;
EInteger bigintY;
EInteger thisValue = this;
if (thisValue.CanFitInInt32()) {
int smallValue = thisValue.ToInt32Checked();
int smallPowerBits =
(thisValue.GetUnsignedBitLengthAsEInteger().ToInt32Checked() + 1)
/ 2;
// No need to check for zero; already done above
var smallintX = 0;
int smallintY = 1 << smallPowerBits;
do {
smallintX = smallintY;
smallintY = smallValue / smallintX;
smallintY += smallintX;
smallintY >>= 1;
} while (smallintY < smallintX);
if (!useRem) {
return new[] { (EInteger)smallintX, null };
}
smallintY = smallintX * smallintX;
smallintY = smallValue - smallintY;
return new[] {
(EInteger)smallintX, (EInteger)smallintY,
};
}
EInteger valueEPowerBits =
thisValue.GetUnsignedBitLengthAsEInteger().Add(1).Divide(2);
if (this.wordCount >= 4) {
int wordsPerPart = (this.wordCount >> 2) +
((this.wordCount & 3) > 0 ? 1 : 0);
long bitsPerPart = wordsPerPart * 16;
EInteger valueEBitsPerPart = EInteger.FromInt64(bitsPerPart);
long totalBits = bitsPerPart * 4;
EInteger valueEBitLength = this.GetUnsignedBitLengthAsEInteger();
bool bitLengthEven = valueEBitLength.IsEven;
bigintX = this;
EInteger eshift = EInteger.Zero;
if (valueEBitLength.CompareTo(EInteger.FromInt64(totalBits).Subtract(
1)) < 0) {
long targetLength = bitLengthEven ? totalBits : (totalBits - 1);
eshift = EInteger.FromInt64(targetLength).Subtract(valueEBitLength);
bigintX = bigintX.ShiftLeft(eshift);
}
// DebugUtility.Log("this=" + (this.ToRadixString(16)));
// DebugUtility.Log("bigx=" + (bigintX.ToRadixString(16)));
short[] ww = bigintX.words;
var w1 = new short[wordsPerPart];
var w2 = new short[wordsPerPart];
var w3 = new short[wordsPerPart * 2];
Array.Copy(ww, 0, w1, 0, wordsPerPart);
Array.Copy(ww, wordsPerPart, w2, 0, wordsPerPart);
Array.Copy(ww, wordsPerPart * 2, w3, 0, wordsPerPart * 2);
#if DEBUG
if (!((ww[(wordsPerPart * 4) - 1] & 0xc000) != 0)) {
throw new ArgumentException("doesn't satisfy" +
"\u0020(ww[wordsPerPart*4-1]&0xC000)!=0");
}
#endif
var e1 = new EInteger(CountWords(w1), w1, false);
var e2 = new EInteger(CountWords(w2), w2, false);
var e3 = new EInteger(CountWords(w3), w3, false);
EInteger[] srem = e3.SqrtRemInternal(true);
// DebugUtility.Log("sqrt0({0})[depth={3}] = {1},{2}"
// , e3, srem[0], srem[1], 0);
// DebugUtility.Log("sqrt1({0})[depth={3}] = {1},{2}"
// , e3, srem2[0], srem2[1], 0);
// if (!srem[0].Equals(srem2[0]) || !srem[1].Equals(srem2[1])) {
// throw new InvalidOperationException(this.ToString());
// }
EInteger[] qrem = srem[1].ShiftLeft(
valueEBitsPerPart).Add(e2).DivRem(
srem[0].ShiftLeft(1));
EInteger sqroot =
srem[0].ShiftLeft(valueEBitsPerPart).Add(qrem[0]);
EInteger sqrem = qrem[1].ShiftLeft(
valueEBitsPerPart).Add(e1).Subtract(
qrem[0].Multiply(qrem[0]));
// DebugUtility.Log("sqrem=" + sqrem + ",sqroot=" + sqroot);
if (sqrem.Sign < 0) {
if (useRem) {
sqrem = sqrem.Add(sqroot.ShiftLeft(1)).Subtract(EInteger.One);
}
sqroot = sqroot.Subtract(EInteger.One);
#if DEBUG
if (!(sqroot.Sign >= 0)) {
throw new ArgumentException("doesn't satisfy sqroot.Sign>= 0");
}
#endif
}
var retarr = new EInteger[2];
retarr[0] = sqroot.ShiftRight(eshift.ShiftRight(1));
if (useRem) {
if (eshift.IsZero) {
retarr[1] = sqrem;
} else {
retarr[1] = this.Subtract(retarr[0].Multiply(retarr[0]));
}
}
return retarr;
}
bigintX = EInteger.Zero;
bigintY = EInteger.One.ShiftLeft(valueEPowerBits);
do {
bigintX = bigintY;
// DebugUtility.Log("" + thisValue + " " + bigintX);
bigintY = thisValue / (EInteger)bigintX;
bigintY += bigintX;
bigintY >>= 1;
} while (bigintY != null && bigintY.CompareTo(bigintX) < 0);
if (!useRem) {
return new[] { bigintX, null };
}
bigintY = bigintX * (EInteger)bigintX;
bigintY = thisValue - (EInteger)bigintY;
return new[] {
bigintX, bigintY,
};
}
/// <summary>Returns one added to this arbitrary-precision
/// integer.</summary>
/// <returns>The given arbitrary-precision integer plus one.</returns>
public EInteger Increment() {
return this.Add(EInteger.One);
}
/// <summary>Returns one subtracted from this arbitrary-precision
/// integer.</summary>
/// <returns>The given arbitrary-precision integer minus one.</returns>
public EInteger Decrement() {
return this.Subtract(EInteger.One);
}
// Begin integer conversions
/// <summary>Converts this number's value to a byte (from 0 to 255) if
/// it can fit in a byte (from 0 to 255).</summary>
/// <returns>This number's value as a byte (from 0 to 255).</returns>
/// <exception cref='OverflowException'>This value is less than 0 or
/// greater than 255.</exception>
public byte ToByteChecked() {
int val = this.ToInt32Checked();
if (val < 0 || val > 255) {
throw new OverflowException("This object's value is out of range");
}
return unchecked((byte)(val & 0xff));
}
/// <summary>Converts this number to a byte (from 0 to 255), returning
/// the least-significant bits of this number's two's-complement
/// form.</summary>
/// <returns>This number, converted to a byte (from 0 to
/// 255).</returns>
public byte ToByteUnchecked() {
int val = this.ToInt32Unchecked();
return unchecked((byte)(val & 0xff));
}
/// <summary>Converts a byte (from 0 to 255) to an arbitrary-precision
/// integer.</summary>
/// <param name='inputByte'>The number to convert as a byte (from 0 to
/// 255).</param>
/// <returns>This number's value as an arbitrary-precision
/// integer.</returns>
public static EInteger FromByte(byte inputByte) {
int val = ((int)inputByte) & 0xff;
return FromInt32(val);
}
/// <summary>Converts this number's value to a 16-bit signed integer if
/// it can fit in a 16-bit signed integer.</summary>
/// <returns>This number's value as a 16-bit signed integer.</returns>
/// <exception cref='OverflowException'>This value is less than -32768
/// or greater than 32767.</exception>
public short ToInt16Checked() {
int val = this.ToInt32Checked();
if (val < -32768 || val > 32767) {
throw new OverflowException("This object's value is out of range");
}
return unchecked((short)(val & ShortMask));
}
/// <summary>Converts this number to a 16-bit signed integer, returning
/// the least-significant bits of this number's two's-complement
/// form.</summary>
/// <returns>This number, converted to a 16-bit signed
/// integer.</returns>
public short ToInt16Unchecked() {
int val = this.ToInt32Unchecked();
return unchecked((short)(val & ShortMask));
}
/// <summary>Converts a 16-bit signed integer to an arbitrary-precision
/// integer.</summary>
/// <param name='inputInt16'>The number to convert as a 16-bit signed
/// integer.</param>
/// <returns>This number's value as an arbitrary-precision
/// integer.</returns>
public static EInteger FromInt16(short inputInt16) {
var val = (int)inputInt16;
return FromInt32(val);
}
// End integer conversions
}
}
| 36.302713 | 86 | 0.533515 | [
"CC0-1.0"
] | peteroupc/Numbers | Numbers/PeterO/Numbers/EInteger.cs | 363,971 | C# |
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
namespace Butler.Helper
{
public class NullToVisibliltyConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return value != null ? Visibility.Visible : Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
} | 25.1 | 97 | 0.770916 | [
"MIT"
] | megai2/ArcDps-Butler | Butler/Butler/Helper/NullToVisibliltyConverter.cs | 504 | C# |
using NetOffice.Attributes;
namespace NetOffice.WordApi.Enums
{
/// <summary>
/// SupportByVersion Word 9, 10, 11, 12, 14, 15, 16
/// </summary>
[SupportByVersion("Word", 9, 10, 11, 12, 14, 15, 16)]
[EntityType(EntityType.IsEnum)]
public enum WdSummaryMode
{
/// <summary>
/// SupportByVersion Word 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <remarks>0</remarks>
[SupportByVersion("Word", 9, 10, 11, 12, 14, 15, 16)]
wdSummaryModeHighlight = 0,
/// <summary>
/// SupportByVersion Word 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <remarks>1</remarks>
[SupportByVersion("Word", 9, 10, 11, 12, 14, 15, 16)]
wdSummaryModeHideAllButSummary = 1,
/// <summary>
/// SupportByVersion Word 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <remarks>2</remarks>
[SupportByVersion("Word", 9, 10, 11, 12, 14, 15, 16)]
wdSummaryModeInsert = 2,
/// <summary>
/// SupportByVersion Word 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <remarks>3</remarks>
[SupportByVersion("Word", 9, 10, 11, 12, 14, 15, 16)]
wdSummaryModeCreateNew = 3
}
} | 31.948718 | 61 | 0.529695 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | ehsan2022002/VirastarE | Office/Word/Enums/WdSummaryMode.cs | 1,248 | C# |
// SQL Notebook
// Copyright (C) 2016 Brian Luft
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
// Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using SqlNotebookScript.Utils;
namespace SqlNotebookScript.TableFunctions {
public sealed class ListXlsWorksheetsFunction : CustomTableFunction {
public override string Name => "list_xls_worksheets";
public override string CreateTableSql =>
@"CREATE TABLE list_xls_worksheets (_file_path HIDDEN, number INTEGER, name)";
public override int HiddenColumnCount => 1;
public override IEnumerable<object[]> Execute(object[] hiddenValues) {
var filePath = ArgUtil.GetStrArg(hiddenValues[0], "file-path", Name);
if (!File.Exists(filePath)) {
throw new Exception($"{Name.ToUpper()}: File not found.");
}
try {
return XlsUtil.ReadWorksheetNames(filePath).Select((name, i) => new object[] {
filePath, i + 1, name
}).ToList();
} catch (Exception ex) {
throw new Exception($"{Name.ToUpper()}: {ex.Message}");
}
}
}
}
| 46.270833 | 119 | 0.69068 | [
"MIT"
] | mfrigillana/sqlnotebook | src/SqlNotebookScript/TableFunctions/ListXlsWorksheetsFunction.cs | 2,223 | C# |
namespace Alex.MoLang.Runtime.Value
{
public interface IMoValue<T> : IMoValue
{
new T Value { get; }
}
public interface IMoValue
{
object Value { get; }
bool Equals(IMoValue b);
string AsString() => Value.ToString();
virtual double AsDouble() => Value is double db ? db : 0d;
virtual float AsFloat() => Value is float flt ? flt : (float)AsDouble();
virtual bool AsBool() => Value is bool b ? b : AsDouble() > 0;
}
public static class MoValue
{
public static IMoValue FromObject(object value)
{
if (value is IMoValue moValue) {
return moValue;
}
if (value is string str)
{
return new StringValue(str);
}
return new DoubleValue(value);
}
}
} | 18.710526 | 74 | 0.639944 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | kennyvv/Alex | src/Alex.MoLang/Runtime/Value/MoValue.cs | 711 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System.Collections.Generic;
using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Http;
using Aliyun.Acs.Core.Transform;
using Aliyun.Acs.Core.Utils;
using Aliyun.Acs.Domain;
using Aliyun.Acs.Domain.Transform;
using Aliyun.Acs.Domain.Transform.V20180129;
namespace Aliyun.Acs.Domain.Model.V20180129
{
public class SaveBatchTaskForCreatingOrderActivateRequest : RpcAcsRequest<SaveBatchTaskForCreatingOrderActivateResponse>
{
public SaveBatchTaskForCreatingOrderActivateRequest()
: base("Domain", "2018-01-29", "SaveBatchTaskForCreatingOrderActivate")
{
}
private List<OrderActivateParam> orderActivateParams;
private string promotionNo;
private string userClientIp;
private string couponNo;
private bool? useCoupon;
private string lang;
private bool? usePromotion;
public List<OrderActivateParam> OrderActivateParams
{
get
{
return orderActivateParams;
}
set
{
orderActivateParams = value;
for (int i = 0; i < orderActivateParams.Count; i++)
{
DictionaryUtil.Add(QueryParameters,"OrderActivateParam." + (i + 1) + ".Country", orderActivateParams[i].Country);
DictionaryUtil.Add(QueryParameters,"OrderActivateParam." + (i + 1) + ".SubscriptionDuration", orderActivateParams[i].SubscriptionDuration);
DictionaryUtil.Add(QueryParameters,"OrderActivateParam." + (i + 1) + ".PermitPremiumActivation", orderActivateParams[i].PermitPremiumActivation);
DictionaryUtil.Add(QueryParameters,"OrderActivateParam." + (i + 1) + ".City", orderActivateParams[i].City);
DictionaryUtil.Add(QueryParameters,"OrderActivateParam." + (i + 1) + ".Dns2", orderActivateParams[i].Dns2);
DictionaryUtil.Add(QueryParameters,"OrderActivateParam." + (i + 1) + ".Dns1", orderActivateParams[i].Dns1);
DictionaryUtil.Add(QueryParameters,"OrderActivateParam." + (i + 1) + ".RegistrantProfileId", orderActivateParams[i].RegistrantProfileId);
DictionaryUtil.Add(QueryParameters,"OrderActivateParam." + (i + 1) + ".AliyunDns", orderActivateParams[i].AliyunDns);
DictionaryUtil.Add(QueryParameters,"OrderActivateParam." + (i + 1) + ".ZhCity", orderActivateParams[i].ZhCity);
DictionaryUtil.Add(QueryParameters,"OrderActivateParam." + (i + 1) + ".TelExt", orderActivateParams[i].TelExt);
DictionaryUtil.Add(QueryParameters,"OrderActivateParam." + (i + 1) + ".ZhRegistrantName", orderActivateParams[i].ZhRegistrantName);
DictionaryUtil.Add(QueryParameters,"OrderActivateParam." + (i + 1) + ".Province", orderActivateParams[i].Province);
DictionaryUtil.Add(QueryParameters,"OrderActivateParam." + (i + 1) + ".PostalCode", orderActivateParams[i].PostalCode);
DictionaryUtil.Add(QueryParameters,"OrderActivateParam." + (i + 1) + ".Email", orderActivateParams[i].Email);
DictionaryUtil.Add(QueryParameters,"OrderActivateParam." + (i + 1) + ".ZhRegistrantOrganization", orderActivateParams[i].ZhRegistrantOrganization);
DictionaryUtil.Add(QueryParameters,"OrderActivateParam." + (i + 1) + ".Address", orderActivateParams[i].Address);
DictionaryUtil.Add(QueryParameters,"OrderActivateParam." + (i + 1) + ".TelArea", orderActivateParams[i].TelArea);
DictionaryUtil.Add(QueryParameters,"OrderActivateParam." + (i + 1) + ".DomainName", orderActivateParams[i].DomainName);
DictionaryUtil.Add(QueryParameters,"OrderActivateParam." + (i + 1) + ".ZhAddress", orderActivateParams[i].ZhAddress);
DictionaryUtil.Add(QueryParameters,"OrderActivateParam." + (i + 1) + ".RegistrantType", orderActivateParams[i].RegistrantType);
DictionaryUtil.Add(QueryParameters,"OrderActivateParam." + (i + 1) + ".Telephone", orderActivateParams[i].Telephone);
DictionaryUtil.Add(QueryParameters,"OrderActivateParam." + (i + 1) + ".TrademarkDomainActivation", orderActivateParams[i].TrademarkDomainActivation);
DictionaryUtil.Add(QueryParameters,"OrderActivateParam." + (i + 1) + ".ZhProvince", orderActivateParams[i].ZhProvince);
DictionaryUtil.Add(QueryParameters,"OrderActivateParam." + (i + 1) + ".RegistrantOrganization", orderActivateParams[i].RegistrantOrganization);
DictionaryUtil.Add(QueryParameters,"OrderActivateParam." + (i + 1) + ".EnableDomainProxy", orderActivateParams[i].EnableDomainProxy);
DictionaryUtil.Add(QueryParameters,"OrderActivateParam." + (i + 1) + ".RegistrantName", orderActivateParams[i].RegistrantName);
}
}
}
public string PromotionNo
{
get
{
return promotionNo;
}
set
{
promotionNo = value;
DictionaryUtil.Add(QueryParameters, "PromotionNo", value);
}
}
public string UserClientIp
{
get
{
return userClientIp;
}
set
{
userClientIp = value;
DictionaryUtil.Add(QueryParameters, "UserClientIp", value);
}
}
public string CouponNo
{
get
{
return couponNo;
}
set
{
couponNo = value;
DictionaryUtil.Add(QueryParameters, "CouponNo", value);
}
}
public bool? UseCoupon
{
get
{
return useCoupon;
}
set
{
useCoupon = value;
DictionaryUtil.Add(QueryParameters, "UseCoupon", value.ToString());
}
}
public string Lang
{
get
{
return lang;
}
set
{
lang = value;
DictionaryUtil.Add(QueryParameters, "Lang", value);
}
}
public bool? UsePromotion
{
get
{
return usePromotion;
}
set
{
usePromotion = value;
DictionaryUtil.Add(QueryParameters, "UsePromotion", value.ToString());
}
}
public class OrderActivateParam
{
private string country;
private int? subscriptionDuration;
private bool? permitPremiumActivation;
private string city;
private string dns2;
private string dns1;
private long? registrantProfileId;
private bool? aliyunDns;
private string zhCity;
private string telExt;
private string zhRegistrantName;
private string province;
private string postalCode;
private string email;
private string zhRegistrantOrganization;
private string address;
private string telArea;
private string domainName;
private string zhAddress;
private string registrantType;
private string telephone;
private bool? trademarkDomainActivation;
private string zhProvince;
private string registrantOrganization;
private bool? enableDomainProxy;
private string registrantName;
public string Country
{
get
{
return country;
}
set
{
country = value;
}
}
public int? SubscriptionDuration
{
get
{
return subscriptionDuration;
}
set
{
subscriptionDuration = value;
}
}
public bool? PermitPremiumActivation
{
get
{
return permitPremiumActivation;
}
set
{
permitPremiumActivation = value;
}
}
public string City
{
get
{
return city;
}
set
{
city = value;
}
}
public string Dns2
{
get
{
return dns2;
}
set
{
dns2 = value;
}
}
public string Dns1
{
get
{
return dns1;
}
set
{
dns1 = value;
}
}
public long? RegistrantProfileId
{
get
{
return registrantProfileId;
}
set
{
registrantProfileId = value;
}
}
public bool? AliyunDns
{
get
{
return aliyunDns;
}
set
{
aliyunDns = value;
}
}
public string ZhCity
{
get
{
return zhCity;
}
set
{
zhCity = value;
}
}
public string TelExt
{
get
{
return telExt;
}
set
{
telExt = value;
}
}
public string ZhRegistrantName
{
get
{
return zhRegistrantName;
}
set
{
zhRegistrantName = value;
}
}
public string Province
{
get
{
return province;
}
set
{
province = value;
}
}
public string PostalCode
{
get
{
return postalCode;
}
set
{
postalCode = value;
}
}
public string Email
{
get
{
return email;
}
set
{
email = value;
}
}
public string ZhRegistrantOrganization
{
get
{
return zhRegistrantOrganization;
}
set
{
zhRegistrantOrganization = value;
}
}
public string Address
{
get
{
return address;
}
set
{
address = value;
}
}
public string TelArea
{
get
{
return telArea;
}
set
{
telArea = value;
}
}
public string DomainName
{
get
{
return domainName;
}
set
{
domainName = value;
}
}
public string ZhAddress
{
get
{
return zhAddress;
}
set
{
zhAddress = value;
}
}
public string RegistrantType
{
get
{
return registrantType;
}
set
{
registrantType = value;
}
}
public string Telephone
{
get
{
return telephone;
}
set
{
telephone = value;
}
}
public bool? TrademarkDomainActivation
{
get
{
return trademarkDomainActivation;
}
set
{
trademarkDomainActivation = value;
}
}
public string ZhProvince
{
get
{
return zhProvince;
}
set
{
zhProvince = value;
}
}
public string RegistrantOrganization
{
get
{
return registrantOrganization;
}
set
{
registrantOrganization = value;
}
}
public bool? EnableDomainProxy
{
get
{
return enableDomainProxy;
}
set
{
enableDomainProxy = value;
}
}
public string RegistrantName
{
get
{
return registrantName;
}
set
{
registrantName = value;
}
}
}
public override bool CheckShowJsonItemName()
{
return false;
}
public override SaveBatchTaskForCreatingOrderActivateResponse GetResponse(UnmarshallerContext unmarshallerContext)
{
return SaveBatchTaskForCreatingOrderActivateResponseUnmarshaller.Unmarshall(unmarshallerContext);
}
}
}
| 20.92196 | 155 | 0.614677 | [
"Apache-2.0"
] | bitType/aliyun-openapi-net-sdk | aliyun-net-sdk-domain/Domain/Model/V20180129/SaveBatchTaskForCreatingOrderActivateRequest.cs | 11,528 | C# |
#pragma checksum "D:\New folder\AuthSystem\Identity\Areas\Identity\Pages\Account\Manage\EnableAuthenticator.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "63d2a2d6a8223e583fa6a19676ae504270a8630f"
// <auto-generated/>
#pragma warning disable 1591
[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Areas_Identity_Pages_Account_Manage_EnableAuthenticator), @"mvc.1.0.razor-page", @"/Areas/Identity/Pages/Account/Manage/EnableAuthenticator.cshtml")]
namespace AspNetCore
{
#line hidden
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
#nullable restore
#line 1 "D:\New folder\AuthSystem\Identity\Areas\Identity\Pages\_ViewImports.cshtml"
using Microsoft.AspNetCore.Identity;
#line default
#line hidden
#nullable disable
#nullable restore
#line 2 "D:\New folder\AuthSystem\Identity\Areas\Identity\Pages\_ViewImports.cshtml"
using Identity.Areas.Identity;
#line default
#line hidden
#nullable disable
#nullable restore
#line 3 "D:\New folder\AuthSystem\Identity\Areas\Identity\Pages\_ViewImports.cshtml"
using Identity.Areas.Identity.Pages;
#line default
#line hidden
#nullable disable
#nullable restore
#line 5 "D:\New folder\AuthSystem\Identity\Areas\Identity\Pages\_ViewImports.cshtml"
using Identity.Areas.Identity.Data;
#line default
#line hidden
#nullable disable
#nullable restore
#line 1 "D:\New folder\AuthSystem\Identity\Areas\Identity\Pages\Account\_ViewImports.cshtml"
using Identity.Areas.Identity.Pages.Account;
#line default
#line hidden
#nullable disable
#nullable restore
#line 1 "D:\New folder\AuthSystem\Identity\Areas\Identity\Pages\Account\Manage\_ViewImports.cshtml"
using Identity.Areas.Identity.Pages.Account.Manage;
#line default
#line hidden
#nullable disable
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"63d2a2d6a8223e583fa6a19676ae504270a8630f", @"/Areas/Identity/Pages/Account/Manage/EnableAuthenticator.cshtml")]
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"645f76a122d83fed8c44f81d098b19cb225cb3f6", @"/Areas/Identity/Pages/_ViewImports.cshtml")]
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"9cefdd3fe012df3a30e83087f56b7b21ba4d0457", @"/Areas/Identity/Pages/Account/_ViewImports.cshtml")]
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"454db40f67dbc9a1f15993ed939088e6e3026d55", @"/Areas/Identity/Pages/Account/Manage/_ViewImports.cshtml")]
public class Areas_Identity_Pages_Account_Manage_EnableAuthenticator : global::Microsoft.AspNetCore.Mvc.RazorPages.Page
{
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("name", "_StatusMessage", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_1 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("control-label"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_2 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("form-control"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_3 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("autocomplete", new global::Microsoft.AspNetCore.Html.HtmlString("off"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_4 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("text-danger"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_5 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("id", new global::Microsoft.AspNetCore.Html.HtmlString("send-code"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_6 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("method", "post", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_7 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("name", "_ValidationScriptsPartial", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
#line hidden
#pragma warning disable 0649
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext __tagHelperExecutionContext;
#pragma warning restore 0649
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner __tagHelperRunner = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner();
#pragma warning disable 0169
private string __tagHelperStringValueBuffer;
#pragma warning restore 0169
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __backed__tagHelperScopeManager = null;
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __tagHelperScopeManager
{
get
{
if (__backed__tagHelperScopeManager == null)
{
__backed__tagHelperScopeManager = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope);
}
return __backed__tagHelperScopeManager;
}
}
private global::Microsoft.AspNetCore.Mvc.TagHelpers.PartialTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_PartialTagHelper;
private global::Microsoft.AspNetCore.Mvc.TagHelpers.FormTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper;
private global::Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper;
private global::Microsoft.AspNetCore.Mvc.TagHelpers.LabelTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper;
private global::Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper;
private global::Microsoft.AspNetCore.Mvc.TagHelpers.ValidationMessageTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper;
private global::Microsoft.AspNetCore.Mvc.TagHelpers.ValidationSummaryTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationSummaryTagHelper;
#pragma warning disable 1998
public async override global::System.Threading.Tasks.Task ExecuteAsync()
{
#nullable restore
#line 3 "D:\New folder\AuthSystem\Identity\Areas\Identity\Pages\Account\Manage\EnableAuthenticator.cshtml"
ViewData["Title"] = "Configure authenticator app";
ViewData["ActivePage"] = ManageNavPages.TwoFactorAuthentication;
#line default
#line hidden
#nullable disable
WriteLiteral("\r\n");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("partial", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "63d2a2d6a8223e583fa6a19676ae504270a8630f8284", async() => {
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_PartialTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.PartialTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_PartialTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_PartialTagHelper.Name = (string)__tagHelperAttribute_0.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_0);
#nullable restore
#line 8 "D:\New folder\AuthSystem\Identity\Areas\Identity\Pages\Account\Manage\EnableAuthenticator.cshtml"
__Microsoft_AspNetCore_Mvc_TagHelpers_PartialTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.StatusMessage);
#line default
#line hidden
#nullable disable
__tagHelperExecutionContext.AddTagHelperAttribute("for", __Microsoft_AspNetCore_Mvc_TagHelpers_PartialTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n<h4>");
#nullable restore
#line 9 "D:\New folder\AuthSystem\Identity\Areas\Identity\Pages\Account\Manage\EnableAuthenticator.cshtml"
Write(ViewData["Title"]);
#line default
#line hidden
#nullable disable
WriteLiteral(@"</h4>
<div>
<p>To use an authenticator app go through the following steps:</p>
<ol class=""list"">
<li>
<p>
Download a two-factor authenticator app like Microsoft Authenticator for
<a href=""https://go.microsoft.com/fwlink/?Linkid=825072"">Android</a> and
<a href=""https://go.microsoft.com/fwlink/?Linkid=825073"">iOS</a> or
Google Authenticator for
<a href=""https://play.google.com/store/apps/details?id=com.google.android.apps.authenticator2&hl=en"">Android</a> and
<a href=""https://itunes.apple.com/us/app/google-authenticator/id388497605?mt=8"">iOS</a>.
</p>
</li>
<li>
<p>Scan the QR Code or enter this key <kbd>");
#nullable restore
#line 24 "D:\New folder\AuthSystem\Identity\Areas\Identity\Pages\Account\Manage\EnableAuthenticator.cshtml"
Write(Model.SharedKey);
#line default
#line hidden
#nullable disable
WriteLiteral(@"</kbd> into your two factor authenticator app. Spaces and casing do not matter.</p>
<div class=""alert alert-info"">Learn how to <a href=""https://go.microsoft.com/fwlink/?Linkid=852423"">enable QR code generation</a>.</div>
<div id=""qrCode""></div>
<div id=""qrCodeData"" data-url=""");
#nullable restore
#line 27 "D:\New folder\AuthSystem\Identity\Areas\Identity\Pages\Account\Manage\EnableAuthenticator.cshtml"
Write(Html.Raw(@Model.AuthenticatorUri));
#line default
#line hidden
#nullable disable
WriteLiteral(@"""></div>
</li>
<li>
<p>
Once you have scanned the QR code or input the key above, your two factor authentication app will provide you
with a unique code. Enter the code in the confirmation box below.
</p>
<div class=""row"">
<div class=""col-md-6"">
");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("form", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "63d2a2d6a8223e583fa6a19676ae504270a8630f12268", async() => {
WriteLiteral("\r\n <div class=\"form-group\">\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("label", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "63d2a2d6a8223e583fa6a19676ae504270a8630f12609", async() => {
WriteLiteral("Verification Code");
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.LabelTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper);
#nullable restore
#line 38 "D:\New folder\AuthSystem\Identity\Areas\Identity\Pages\Account\Manage\EnableAuthenticator.cshtml"
__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Input.Code);
#line default
#line hidden
#nullable disable
__tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "63d2a2d6a8223e583fa6a19676ae504270a8630f14293", async() => {
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper);
#nullable restore
#line 39 "D:\New folder\AuthSystem\Identity\Areas\Identity\Pages\Account\Manage\EnableAuthenticator.cshtml"
__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Input.Code);
#line default
#line hidden
#nullable disable
__tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_3);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("span", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "63d2a2d6a8223e583fa6a19676ae504270a8630f16002", async() => {
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.ValidationMessageTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper);
#nullable restore
#line 40 "D:\New folder\AuthSystem\Identity\Areas\Identity\Pages\Account\Manage\EnableAuthenticator.cshtml"
__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Input.Code);
#line default
#line hidden
#nullable disable
__tagHelperExecutionContext.AddTagHelperAttribute("asp-validation-for", __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_4);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n </div>\r\n <button type=\"submit\" class=\"btn btn-primary\">Verify</button>\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("div", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "63d2a2d6a8223e583fa6a19676ae504270a8630f17823", async() => {
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationSummaryTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.ValidationSummaryTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationSummaryTagHelper);
#nullable restore
#line 43 "D:\New folder\AuthSystem\Identity\Areas\Identity\Pages\Account\Manage\EnableAuthenticator.cshtml"
__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationSummaryTagHelper.ValidationSummary = global::Microsoft.AspNetCore.Mvc.Rendering.ValidationSummary.ModelOnly;
#line default
#line hidden
#nullable disable
__tagHelperExecutionContext.AddTagHelperAttribute("asp-validation-summary", __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationSummaryTagHelper.ValidationSummary, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_4);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n ");
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.FormTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_5);
__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Method = (string)__tagHelperAttribute_6.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_6);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n </div>\r\n </div>\r\n </li>\r\n </ol>\r\n</div>\r\n\r\n");
DefineSection("Scripts", async() => {
WriteLiteral("\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("partial", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "63d2a2d6a8223e583fa6a19676ae504270a8630f20974", async() => {
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_PartialTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.PartialTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_PartialTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_PartialTagHelper.Name = (string)__tagHelperAttribute_7.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_7);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n");
}
);
}
#pragma warning restore 1998
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<EnableAuthenticatorModel> Html { get; private set; }
public global::Microsoft.AspNetCore.Mvc.ViewFeatures.ViewDataDictionary<EnableAuthenticatorModel> ViewData => (global::Microsoft.AspNetCore.Mvc.ViewFeatures.ViewDataDictionary<EnableAuthenticatorModel>)PageContext?.ViewData;
public EnableAuthenticatorModel Model => ViewData.Model;
}
}
#pragma warning restore 1591
| 70.027273 | 351 | 0.74127 | [
"MIT"
] | namchokGithub/AuthSystem | Identity/obj/Debug/netcoreapp3.1/Razor/Areas/Identity/Pages/Account/Manage/EnableAuthenticator.cshtml.g.cs | 23,109 | C# |
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using LetterboxCamera;
namespace LetterboxCamera {
public class FoodTracker : MonoBehaviour {
public DragonClass dragon;
public Text[] textPieces;
// Use this for initialization
void Start() {
}
// Update is called once per frame
void Update() {
for (int i = 0; i < textPieces.Length; i++) {
textPieces[i].text = (dragon.GetFruit() + dragon.GetMeat()).ToString();
}
}
}
} | 23.24 | 88 | 0.555938 | [
"MIT"
] | Indexu/AlanAlbusAdventures | src/Alan and Albus Adventures/Assets/Plugins/Auto Letterbox/Demos/Game Demo/Scripts/FoodTracker.cs | 583 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
namespace Azure
{
internal class NoBodyResponse<T> : Response<T>
{
private readonly Response _response;
public NoBodyResponse(Response response)
{
_response = response;
}
public override T Value
{
get
{
throw new ResponseBodyNotFoundException(_response.Status, _response.ReasonPhrase);
}
}
public override Response GetRawResponse() => _response;
#pragma warning disable CA1064 // Exceptions should be public
private class ResponseBodyNotFoundException : Exception
#pragma warning restore CA1064 // Exceptions should be public
{
public int Status { get; }
public ResponseBodyNotFoundException(int status, string message)
: base(message)
{
Status = status;
}
}
}
}
| 25 | 98 | 0.594146 | [
"MIT"
] | MAtifSaeed/azure-sdk-for-net | sdk/core/Azure.Core/src/Shared/NoBodyResponse{T}.cs | 1,027 | C# |
namespace XCReceiptPrinterTester
{
partial class Form1
{
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
/// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows 窗体设计器生成的代码
/// <summary>
/// 设计器支持所需的方法 - 不要修改
/// 使用代码编辑器修改此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Text = "Form1";
}
#endregion
}
}
| 24.97619 | 73 | 0.524309 | [
"MIT"
] | xuchao1984/XCReceiptPrinter | XCReceiptPrinterTester/Form1.Designer.cs | 1,205 | C# |
using System.Resources;
using System.Reflection;
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("DynamoAutomation")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Bad Monkeys")]
[assembly: AssemblyProduct("DynamoAutomation")]
[assembly: AssemblyCopyright("Copyright © gmp 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("492a518b-55c9-46e5-be5c-0513b6761299")]
// 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.31.0.0")]
[assembly: AssemblyFileVersion("1.31.0.0")]
[assembly: NeutralResourcesLanguage("en-US")]
| 37.25641 | 84 | 0.747419 | [
"MIT"
] | andydandy74/DynamoAutomation | addin_src/Properties/AssemblyInfo.cs | 1,456 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
namespace SLIDDES.Modular.Editor
{
[CustomEditor(typeof(EventListenerDouble))]
public class EditorEventListenerDouble : EditorEventListener<double>
{
private EventListenerDouble selectedType;
protected SerializedProperty m_eventConditionProp;
protected SerializedProperty m_compareValueProp;
public override void OnEnable()
{
selectedType = (EventListenerDouble)target;
base.OnEnable();
m_eventConditionProp = serializedObject.FindProperty("eventCondition");
m_compareValueProp = serializedObject.FindProperty("compareValue");
}
public override void OnInspectorGUI()
{
DrawGUIEventObjectField();
if(selected.Event != null)
EditorGUILayout.PropertyField(m_eventConditionProp);
if(selectedType.eventCondition != EventListenerDouble.EventCondition.none)
EditorGUILayout.PropertyField(m_compareValueProp);
if(selected.Event != null)
EditorGUILayout.PropertyField(m_ResponseProp);
serializedObject.ApplyModifiedProperties();
}
public override void DrawGUIEventObjectField()
{
selected.Event = (Event<double>)EditorGUILayout.ObjectField(new GUIContent("Event", "The event to listen for"), selected.Event, typeof(DoubleEvent), false);
}
}
}
| 35.302326 | 168 | 0.679183 | [
"MIT"
] | MrSliddes/SLIDDES-Unity-Modular | Editor/Scripts/Event Listener/EditorEventListenerDouble.cs | 1,518 | C# |
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using MyBudget.App.Services;
namespace MyBudget.App.Controllers
{
[Authorize]
public class HomeController : BaseController
{
private readonly IBudgetService _budgetService;
public HomeController(IBudgetService budgetService)
{
_budgetService = budgetService;
}
public async Task<IActionResult> Index()
{
var model = await _budgetService.GetBudgetsAsync(UserId);
return View(model);
}
public IActionResult Error()
{
return View();
}
}
} | 23.5 | 69 | 0.622695 | [
"MIT"
] | LukaszKot/MyBudget | src/MyBudget/MyBudget.App/Controllers/HomeController.cs | 707 | 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 dynamodb-2012-08-10.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.DynamoDBv2.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.DynamoDBv2.Model.Internal.MarshallTransformations
{
/// <summary>
/// UpdateGlobalSecondaryIndexAction Marshaller
/// </summary>
public class UpdateGlobalSecondaryIndexActionMarshaller : IRequestMarshaller<UpdateGlobalSecondaryIndexAction, JsonMarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="requestObject"></param>
/// <param name="context"></param>
/// <returns></returns>
public void Marshall(UpdateGlobalSecondaryIndexAction requestObject, JsonMarshallerContext context)
{
if(requestObject.IsSetIndexName())
{
context.Writer.WritePropertyName("IndexName");
context.Writer.Write(requestObject.IndexName);
}
if(requestObject.IsSetProvisionedThroughput())
{
context.Writer.WritePropertyName("ProvisionedThroughput");
context.Writer.WriteObjectStart();
var marshaller = ProvisionedThroughputMarshaller.Instance;
marshaller.Marshall(requestObject.ProvisionedThroughput, context);
context.Writer.WriteObjectEnd();
}
}
/// <summary>
/// Singleton Marshaller.
/// </summary>
public readonly static UpdateGlobalSecondaryIndexActionMarshaller Instance = new UpdateGlobalSecondaryIndexActionMarshaller();
}
} | 36.164384 | 139 | 0.667424 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/DynamoDBv2/Generated/Model/Internal/MarshallTransformations/UpdateGlobalSecondaryIndexActionMarshaller.cs | 2,640 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using Microsoft.EntityFrameworkCore.Metadata.Conventions.Infrastructure;
namespace Microsoft.EntityFrameworkCore.Metadata.Conventions
{
/// <summary>
/// Base type for inheritance discovery conventions
/// </summary>
[Obsolete]
public abstract class InheritanceDiscoveryConventionBase
{
/// <summary>
/// Creates a new instance of <see cref="InheritanceDiscoveryConventionBase" />.
/// </summary>
/// <param name="dependencies"> Parameter object containing dependencies for this convention. </param>
protected InheritanceDiscoveryConventionBase(ProviderConventionSetBuilderDependencies dependencies)
{
Dependencies = dependencies;
}
/// <summary>
/// Parameter object containing service dependencies.
/// </summary>
protected virtual ProviderConventionSetBuilderDependencies Dependencies { get; }
/// <summary>
/// Finds an entity type in the model that's associated with a CLR type that the given entity type's
/// associated CLR type is derived from and is the closest one in the CLR hierarchy.
/// </summary>
/// <param name="entityType"> The entity type. </param>
protected virtual IConventionEntityType? FindClosestBaseType(IConventionEntityType entityType)
{
var baseType = entityType.ClrType.BaseType;
var model = entityType.Model;
IConventionEntityType? baseEntityType = null;
while (baseType != null
&& baseEntityType == null
&& baseType != typeof(object))
{
baseEntityType = model.FindEntityType(baseType);
baseType = baseType.BaseType;
}
return baseEntityType;
}
}
}
| 39.098039 | 112 | 0.640421 | [
"MIT"
] | FelicePollano/efcore | src/EFCore/Metadata/Conventions/InheritanceDiscoveryConventionBase.cs | 1,994 | C# |
namespace Signum.Upgrade.Upgrades;
class Upgrade_20211111_ReplaceDefaultExecute : CodeUpgradeBase
{
public override string Description => "Replace eoc.defaultClick( with return eoc.defaultClick(";
public override void Execute(UpgradeContext uctx)
{
uctx.ForeachCodeFile($@"*.tsx", uctx.ReactDirectory, file =>
{
file.Replace("eoc.defaultClick(", "/*TODO: fix*/ eoc.defaultClick(");
});
}
}
| 30.533333 | 101 | 0.657205 | [
"MIT"
] | Faridmehr/framework | Signum.Upgrade/Upgrades/Upgrade_20211111_ReplaceDefaultExecute.cs | 458 | C# |
// WARNING
//
// This file has been generated automatically by Visual Studio from the outlets and
// actions declared in your storyboard file.
// Manual changes to this file will not be maintained.
//
using Foundation;
using System;
using System.CodeDom.Compiler;
using UIKit;
namespace vitavol
{
[Register ("VC_SCSites")]
partial class VC_SCSites
{
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIKit.UIButton B_Back { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIKit.UITableView TV_Sites { get; set; }
void ReleaseDesignerOutlets ()
{
if (B_Back != null) {
B_Back.Dispose ();
B_Back = null;
}
if (TV_Sites != null) {
TV_Sites.Dispose ();
TV_Sites = null;
}
}
}
} | 24.368421 | 84 | 0.530238 | [
"Apache-2.0"
] | coxthepilot/vitasa | vitasa_apps/vitavol/VC_SCSites.designer.cs | 926 | 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("Speeds")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Speeds")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[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("219823c4-516a-4ea4-9c8c-ff017c881414")]
// 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")]
| 37.27027 | 84 | 0.746193 | [
"MIT"
] | DimitarZhelezov/CSharp-2-Telerik-Academy_ | Speeds/Properties/AssemblyInfo.cs | 1,380 | C# |
using System.Collections.Generic;
using System.Linq;
using GenericBlogAPI.Core.Entities;
using Newtonsoft.Json;
namespace GenericBlogAPI.Models
{
public class PostResponse
{
[JsonProperty(PropertyName = "metadata")]
public Metadata Metadata { get; set; }
[JsonProperty(PropertyName = "posts")]
public IEnumerable<Post> Posts { get; set; }
public PostResponse(RequestParameters requestParameters, IEnumerable<BlogFeedContent> blogFeedContent)
{
LoadMetadaAttribute(requestParameters);
LoadPostsAttribute(blogFeedContent);
}
private void LoadMetadaAttribute(RequestParameters requestParameters)
{
Metadata = new Metadata(requestParameters.Limit, requestParameters.Offset);
}
private void LoadPostsAttribute(IEnumerable<BlogFeedContent> blogFeedContent)
{
Posts = blogFeedContent.Select(item => new Post(item));
}
}
} | 30.75 | 110 | 0.678862 | [
"MIT"
] | jeduardocosta/GenericBlogApi | src/GenericBlogAPI/Models/PostResponse.cs | 986 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
namespace Metaseed.Data
{
[Serializable]
public class NameDescription_DependencyObject : DependencyObject, INameDescription
{
public string NameText
{
get { return (string)GetValue(NameTextProperty); }
set { SetValue(NameTextProperty, value); }
}
// Using a DependencyProperty as the backing store for Name. This enables animation, styling, binding, etc...
public static readonly DependencyProperty NameTextProperty =
DependencyProperty.Register("NameText", typeof(string), typeof(NameDescription_DependencyObject), new PropertyMetadata(null));
public string Description
{
get { return (string)GetValue(DescriptionProperty); }
set { SetValue(DescriptionProperty, value); }
}
// Using a DependencyProperty as the backing store for Description. This enables animation, styling, binding, etc...
public static readonly DependencyProperty DescriptionProperty =
DependencyProperty.Register("Description", typeof(string), typeof(NameDescription_DependencyObject), new PropertyMetadata(null));
}
}
| 37.470588 | 141 | 0.700157 | [
"MIT"
] | metaseed/MetaStudio | src/Metaseed.Core/Data/NameDescription_DependencyObject.cs | 1,276 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace Scorpio
{
/// <summary>
///
/// </summary>
[DebuggerStepThrough]
public static class Check
{
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value"></param>
/// <param name="parameterName"></param>
/// <returns></returns>
public static T NotNull<T>(T value, string parameterName)
{
if (value == null)
{
throw new ArgumentNullException(parameterName);
}
return value;
}
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value"></param>
/// <param name="parameterName"></param>
/// <param name="message"></param>
/// <returns></returns>
public static T NotNull<T>(T value, string parameterName, string message)
{
if (value == null)
{
throw new ArgumentNullException(parameterName, message);
}
return value;
}
/// <summary>
///
/// </summary>
/// <param name="value"></param>
/// <param name="parameterName"></param>
/// <returns></returns>
public static string NotNullOrWhiteSpace(string value, string parameterName)
{
if (value.IsNullOrWhiteSpace())
{
throw new ArgumentException($"{parameterName} can not be null, empty or white space!", parameterName);
}
return value;
}
/// <summary>
///
/// </summary>
/// <param name="value"></param>
/// <param name="parameterName"></param>
/// <returns></returns>
public static string NotNullOrEmpty(string value, string parameterName)
{
if (value.IsNullOrEmpty())
{
throw new ArgumentException($"{parameterName} can not be null or empty!", parameterName);
}
return value;
}
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value"></param>
/// <param name="parameterName"></param>
/// <returns></returns>
public static ICollection<T> NotNullOrEmpty<T>(ICollection<T> value, string parameterName)
{
if (value.IsNullOrEmpty())
{
throw new ArgumentException(parameterName + " can not be null or empty!", parameterName);
}
return value;
}
}
}
| 27.616162 | 118 | 0.495611 | [
"MIT"
] | project-scorpio/scorpio | src/Core/src/Scorpio.Utilities/Scorpio/Check.cs | 2,736 | C# |
using System;
namespace Reactive.Streams.TCK.Support
{
public class SubscriberBufferOverflowException : Exception
{
public SubscriberBufferOverflowException(string message) : base(message)
{
}
public SubscriberBufferOverflowException(string message, Exception innerException)
: base(message, innerException)
{
}
}
} | 23.705882 | 90 | 0.647643 | [
"CC0-1.0"
] | OsirisTerje/reactive-streams-dotnet | src/tck/Reactive.Streams.TCK/Support/SubscriberBufferOverflowException.cs | 405 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ElementInfoLocalization.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>
// Implements the element information localization class.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace Kephas.Reflection.Localization
{
using System;
using Kephas.Localization;
/// <summary>
/// Localization information for <see cref="IElementInfo"/>.
/// </summary>
public abstract class ElementInfoLocalization : Localization, IElementInfoLocalization
{
private string? name;
private string? description;
private string? shortName;
private string? prompt;
/// <summary>
/// Initializes a new instance of the <see cref="ElementInfoLocalization"/> class.
/// </summary>
protected ElementInfoLocalization()
{
// ReSharper disable once VirtualMemberCallInConstructor
this.DisplayInfo = this.GetDisplayInfo(null);
}
/// <summary>
/// Initializes a new instance of the <see cref="ElementInfoLocalization"/> class.
/// </summary>
/// <param name="elementInfo">Information describing the element.</param>
protected ElementInfoLocalization(IElementInfo elementInfo)
{
elementInfo = elementInfo ?? throw new ArgumentNullException(nameof(elementInfo));
// ReSharper disable once VirtualMemberCallInConstructor
this.DisplayInfo = this.GetDisplayInfo(elementInfo);
}
/// <summary>
/// Gets or sets the localized name.
/// </summary>
/// <value>
/// The localized name.
/// </value>
public virtual string? Name
{
get => this.DisplayInfo == null
? this.name
: this.DisplayInfo.GetName();
set => this.name = value;
}
/// <summary>
/// Gets or sets the localized description.
/// </summary>
/// <value>
/// The localized description.
/// </value>
public virtual string? Description
{
get => this.DisplayInfo == null
? this.description
: this.DisplayInfo.GetDescription();
set => this.description = value;
}
/// <summary>
/// Gets or sets the localized short name.
/// </summary>
/// <remarks>
/// The short name can be used for example in column headers.
/// </remarks>
/// <value>
/// The localized short name.
/// </value>
public string? ShortName
{
get => this.DisplayInfo == null
? this.shortName
: this.DisplayInfo.GetShortName();
set => this.shortName = value;
}
/// <summary>
/// Gets or sets the localized value that will be used to set the watermark for prompts in the UI.
/// </summary>
/// <value>
/// The localized value that will be used to set the watermark for prompts in the UI.
/// </value>
public string? Prompt
{
get => this.DisplayInfo == null
? this.prompt
: this.DisplayInfo.GetPrompt();
set => this.prompt = value;
}
/// <summary>
/// Gets the <see cref="IDisplayInfo"/> used to extract the localized values.
/// </summary>
protected IDisplayInfo? DisplayInfo { get; }
/// <summary>
/// Tries to get the display attribute from the provided <see cref="IElementInfo"/>.
/// </summary>
/// <param name="elementInfo">Information describing the element.</param>
/// <returns>
/// A <see cref="IDisplayInfo"/> attribute or <c>null</c>.
/// </returns>
protected virtual IDisplayInfo? GetDisplayInfo(IElementInfo? elementInfo) =>
elementInfo?.GetDisplayInfo();
}
} | 35.598361 | 120 | 0.535574 | [
"MIT"
] | kephas-software/kephas | src/Kephas.Reflection/Reflection/Localization/ElementInfoLocalization.cs | 4,345 | C# |
using Steamworks;
using System;
using System.Threading;
using System.Threading.Tasks;
using UnityEngine;
namespace Mirror.FizzySteam
{
public class LegacyClient : LegacyCommon, IClient
{
public bool Error { get; private set; }
public bool Connected { get; private set; }
private event Action<byte[], int> OnReceivedData;
private event Action OnConnected;
private event Action OnDisconnected;
private TimeSpan ConnectionTimeout;
private SteamId hostSteamID = 0;
private TaskCompletionSource<Task> connectedComplete;
private CancellationTokenSource cancelToken;
private LegacyClient(FizzyFacepunch transport) : base(transport)
{
ConnectionTimeout = TimeSpan.FromSeconds(Math.Max(1, transport.Timeout));
}
public static LegacyClient CreateClient(FizzyFacepunch transport, string host)
{
LegacyClient c = new LegacyClient(transport);
c.OnConnected += () => transport.OnClientConnected.Invoke();
c.OnDisconnected += () => transport.OnClientDisconnected.Invoke();
c.OnReceivedData += (data, channel) => transport.OnClientDataReceived.Invoke(new ArraySegment<byte>(data), channel);
if (SteamClient.IsValid)
{
c.Connect(host);
}
else
{
Debug.LogError("SteamWorks not initialized.");
c.OnConnectionFailed(new SteamId());
}
return c;
}
private async void Connect(string host)
{
cancelToken = new CancellationTokenSource();
try
{
hostSteamID = ulong.Parse(host);
connectedComplete = new TaskCompletionSource<Task>();
OnConnected += SetConnectedComplete;
SendInternal(hostSteamID, InternalMessages.CONNECT);
Task connectedCompleteTask = connectedComplete.Task;
Task timeOutTask = Task.Delay(ConnectionTimeout, cancelToken.Token);
if (await Task.WhenAny(connectedCompleteTask, timeOutTask) != connectedCompleteTask)
{
if (cancelToken.IsCancellationRequested)
{
Debug.LogError($"The connection attempt was cancelled.");
}
else if (timeOutTask.IsCompleted)
{
Debug.LogError($"Connection to {host} timed out.");
}
OnConnected -= SetConnectedComplete;
Debug.LogError("Connection timed out.");
OnConnectionFailed(hostSteamID);
}
OnConnected -= SetConnectedComplete;
}
catch (FormatException)
{
Debug.LogError($"Connection string was not in the right format. Did you enter a SteamId?");
Error = true;
}
catch (Exception ex)
{
Debug.LogError(ex.Message);
Error = true;
}
finally
{
if (Error)
{
OnConnectionFailed(new SteamId());
}
}
}
public void Disconnect()
{
Debug.Log("Sending Disconnect message");
SendInternal(hostSteamID, InternalMessages.DISCONNECT);
Dispose();
cancelToken?.Cancel();
WaitForClose(hostSteamID);
}
private void SetConnectedComplete() => connectedComplete.SetResult(connectedComplete.Task);
protected override void OnReceiveData(byte[] data, SteamId clientSteamID, int channel)
{
if (clientSteamID != hostSteamID)
{
Debug.LogError("Received a message from an unknown");
return;
}
OnReceivedData.Invoke(data, channel);
}
protected override void OnNewConnection(SteamId id)
{
if (hostSteamID == id)
{
SteamNetworking.AcceptP2PSessionWithUser(id);
}
else
{
Debug.LogError("P2P Acceptance Request from unknown host ID.");
}
}
protected override void OnReceiveInternalData(InternalMessages type, SteamId clientSteamID)
{
switch (type)
{
case InternalMessages.ACCEPT_CONNECT:
if (!Connected)
{
Connected = true;
Debug.Log("Connection established.");
OnConnected.Invoke();
}
break;
case InternalMessages.DISCONNECT:
if (Connected)
{
Connected = false;
Debug.Log("Disconnected.");
OnDisconnected.Invoke();
}
break;
default:
Debug.Log("Received unknown message type");
break;
}
}
public void Send(byte[] data, int channelId) => Send(hostSteamID, data, channelId);
protected override void OnConnectionFailed(SteamId remoteId) => OnDisconnected.Invoke();
public void FlushData() { }
}
} | 28.121951 | 122 | 0.625542 | [
"MIT"
] | Chykary/FizzyFacepunch | LegacyClient.cs | 4,614 | C# |
using System;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
namespace BlazorServer.Data.Migrations
{
public partial class CreateIdentitySchema : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "AspNetRoles",
columns: table => new
{
Id = table.Column<string>(nullable: false),
Name = table.Column<string>(maxLength: 256, nullable: true),
NormalizedName = table.Column<string>(maxLength: 256, nullable: true),
ConcurrencyStamp = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetRoles", x => x.Id);
});
migrationBuilder.CreateTable(
name: "AspNetUsers",
columns: table => new
{
Id = table.Column<string>(nullable: false),
UserName = table.Column<string>(maxLength: 256, nullable: true),
NormalizedUserName = table.Column<string>(maxLength: 256, nullable: true),
Email = table.Column<string>(maxLength: 256, nullable: true),
NormalizedEmail = table.Column<string>(maxLength: 256, nullable: true),
EmailConfirmed = table.Column<bool>(nullable: false),
PasswordHash = table.Column<string>(nullable: true),
SecurityStamp = table.Column<string>(nullable: true),
ConcurrencyStamp = table.Column<string>(nullable: true),
PhoneNumber = table.Column<string>(nullable: true),
PhoneNumberConfirmed = table.Column<bool>(nullable: false),
TwoFactorEnabled = table.Column<bool>(nullable: false),
LockoutEnd = table.Column<DateTimeOffset>(nullable: true),
LockoutEnabled = table.Column<bool>(nullable: false),
AccessFailedCount = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUsers", x => x.Id);
});
migrationBuilder.CreateTable(
name: "AspNetRoleClaims",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
RoleId = table.Column<string>(nullable: false),
ClaimType = table.Column<string>(nullable: true),
ClaimValue = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetRoleClaims", x => x.Id);
table.ForeignKey(
name: "FK_AspNetRoleClaims_AspNetRoles_RoleId",
column: x => x.RoleId,
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserClaims",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
UserId = table.Column<string>(nullable: false),
ClaimType = table.Column<string>(nullable: true),
ClaimValue = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserClaims", x => x.Id);
table.ForeignKey(
name: "FK_AspNetUserClaims_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserLogins",
columns: table => new
{
LoginProvider = table.Column<string>(maxLength: 128, nullable: false),
ProviderKey = table.Column<string>(maxLength: 128, nullable: false),
ProviderDisplayName = table.Column<string>(nullable: true),
UserId = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserLogins", x => new { x.LoginProvider, x.ProviderKey });
table.ForeignKey(
name: "FK_AspNetUserLogins_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserRoles",
columns: table => new
{
UserId = table.Column<string>(nullable: false),
RoleId = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserRoles", x => new { x.UserId, x.RoleId });
table.ForeignKey(
name: "FK_AspNetUserRoles_AspNetRoles_RoleId",
column: x => x.RoleId,
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_AspNetUserRoles_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserTokens",
columns: table => new
{
UserId = table.Column<string>(nullable: false),
LoginProvider = table.Column<string>(maxLength: 128, nullable: false),
Name = table.Column<string>(maxLength: 128, nullable: false),
Value = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserTokens", x => new { x.UserId, x.LoginProvider, x.Name });
table.ForeignKey(
name: "FK_AspNetUserTokens_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_AspNetRoleClaims_RoleId",
table: "AspNetRoleClaims",
column: "RoleId");
migrationBuilder.CreateIndex(
name: "RoleNameIndex",
table: "AspNetRoles",
column: "NormalizedName",
unique: true,
filter: "[NormalizedName] IS NOT NULL");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserClaims_UserId",
table: "AspNetUserClaims",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserLogins_UserId",
table: "AspNetUserLogins",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserRoles_RoleId",
table: "AspNetUserRoles",
column: "RoleId");
migrationBuilder.CreateIndex(
name: "EmailIndex",
table: "AspNetUsers",
column: "NormalizedEmail");
migrationBuilder.CreateIndex(
name: "UserNameIndex",
table: "AspNetUsers",
column: "NormalizedUserName",
unique: true,
filter: "[NormalizedUserName] IS NOT NULL");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "AspNetRoleClaims");
migrationBuilder.DropTable(
name: "AspNetUserClaims");
migrationBuilder.DropTable(
name: "AspNetUserLogins");
migrationBuilder.DropTable(
name: "AspNetUserRoles");
migrationBuilder.DropTable(
name: "AspNetUserTokens");
migrationBuilder.DropTable(
name: "AspNetRoles");
migrationBuilder.DropTable(
name: "AspNetUsers");
}
}
}
| 43.090498 | 122 | 0.498582 | [
"MIT"
] | kaanlab/PolicyBasedAuthWithBlazor | src/BlazorServer/Data/Migrations/00000000000000_CreateIdentitySchema.cs | 9,525 | 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("StaticNotStirred_UI")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("StaticNotStirred_UI")]
[assembly: AssemblyCopyright("Copyright © 2020")]
[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("2201fb35-3051-4812-aa02-5fc9a00066ff")]
// 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 | 84 | 0.750356 | [
"MIT"
] | bimsharp/AecHackathon20202_StaticNotStirred | ApatosReshoring_UI/Properties/AssemblyInfo.cs | 1,409 | C# |
using NUnit.Framework;
namespace Bellatrix.Web.GettingStarted
{
[TestFixture]
public class LoggingTests : NUnit.WebTest
{
[Test]
[Category(Categories.CI)]
public void AddCustomMessagesToLog()
{
App.Navigation.Navigate("http://demos.bellatrix.solutions/");
Select sortDropDown = App.Components.CreateByNameEndingWith<Select>("orderby");
Anchor protonMReadMoreButton = App.Components.CreateByInnerTextContaining<Anchor>("Read more");
Anchor addToCartFalcon9 = App.Components.CreateByAttributesContaining<Anchor>("data-product_id", "28").ToBeClickable();
Anchor viewCartButton = App.Components.CreateByClassContaining<Anchor>("added_to_cart wc-forward").ToBeClickable();
sortDropDown.SelectByText("Sort by price: low to high");
protonMReadMoreButton.Hover();
// 1. Sometimes is useful to add information to the generated test log.
// To do it you can use the BELLATRIX built-in logger through accessing it via App service.
Logger.LogInformation("Before adding Falcon 9 rocket to cart.");
addToCartFalcon9.Focus();
addToCartFalcon9.Click();
viewCartButton.Click();
// Generated Log, as you can see the above custom message is added to the log.
// #### Start Chrome on PORT = 53153
// Start Test
// Class = LoggingTests Name = AddCustomMessagesToLog
// Select 'Sort by price: low to high' from control (Name ending with orderby)
// Hover control (InnerText containing Read more)
// Before adding Falcon 9 rocket to cart.
// Focus control (data-product_id = 28)
// Click control (data-product_id = 28)
// Click control (Class = added_to_cart wc-forward)
}
}
}
/////1. Open the tests that you made in the page objects section
//2.Add some debug logging information
//3. Customize the logs to include the current date and time
//4. Execute your tests | 45.326087 | 131 | 0.648441 | [
"Apache-2.0"
] | ViktorVakareev/BELLATRIX | templates/Bellatrix.Web.GettingStarted/23. Logging/LoggingTests.cs | 2,087 | C# |
/*
* Copyright (C) Sportradar AG. See LICENSE for full license governing this code
*/
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Sportradar.OddsFeed.SDK.Common.Internal
{
/// <summary>
/// Defines a pool of <see cref="SemaphoreSlim"/> instances which can be used to synchronize access to a shared resource
/// </summary>
internal interface ISemaphorePool : IDisposable
{
/// <summary>
/// Acquires a <see cref="SemaphoreSlim"/> - either one already associated with the specified identifier
/// or an unused one.
/// </summary>
/// <param name="id">The id to be associated with the acquired <see cref="SemaphoreSlim"/> instance.</param>
/// <returns>A <see cref="Task{SemaphoreSlim}"/> representing an async operation</returns>
Task<SemaphoreSlim> Acquire(string id);
/// <summary>
/// Releases the <see cref="SemaphoreSlim"/> previously acquired with the same id
/// </summary>
/// <param name="id">The Id which was used to acquire the semaphore being released .</param>
/// <exception cref="ArgumentException"></exception>
void Release(string id);
}
} | 40.566667 | 124 | 0.655711 | [
"Apache-2.0"
] | Honore-Gaming/UnifiedOddsSdkNetCore | src/Sportradar.OddsFeed.SDK/Common/Internal/ISemaphorePool.cs | 1,217 | C# |
using System;
namespace Strong_number
{
class Program
{
static void Main(string[] args)
{
int number = int.Parse(Console.ReadLine());
string numberToString = number.ToString();
int lastDigit = 0;
int everyDigit = number;
int sum = 0;
int operation = 1;
for (int i = 0; i < numberToString.Length; i++)
{
operation = 1;
lastDigit = everyDigit % 10;
for (int x1 = 1; x1 <= lastDigit; x1++)
{
operation *= x1;
}
sum += operation;
everyDigit /= 10;
}
if (sum == number)
{
Console.WriteLine("yes");
}
else
{
Console.WriteLine("no");
}
}
}
}
| 24.157895 | 59 | 0.388889 | [
"MIT"
] | ErsanYashar/SoftUni-C--Fundamentals | Basic Syntax, Conditional Statements and Loops - Exercise/Strong number/Program.cs | 920 | 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 inspector-2016-02-16.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.Inspector.Model
{
/// <summary>
/// Contains information about an Amazon Inspector agent. This data type is used as a
/// request parameter in the <a>ListAssessmentRunAgents</a> action.
/// </summary>
public partial class AgentFilter
{
private List<string> _agentHealthCodes = new List<string>();
private List<string> _agentHealths = new List<string>();
/// <summary>
/// Gets and sets the property AgentHealthCodes.
/// <para>
/// The detailed health state of the agent. Values can be set to <b>IDLE</b>, <b>RUNNING</b>,
/// <b>SHUTDOWN</b>, <b>UNHEALTHY</b>, <b>THROTTLED</b>, and <b>UNKNOWN</b>.
/// </para>
/// </summary>
[AWSProperty(Required=true, Min=0, Max=10)]
public List<string> AgentHealthCodes
{
get { return this._agentHealthCodes; }
set { this._agentHealthCodes = value; }
}
// Check to see if AgentHealthCodes property is set
internal bool IsSetAgentHealthCodes()
{
return this._agentHealthCodes != null && this._agentHealthCodes.Count > 0;
}
/// <summary>
/// Gets and sets the property AgentHealths.
/// <para>
/// The current health state of the agent. Values can be set to <b>HEALTHY</b> or <b>UNHEALTHY</b>.
/// </para>
/// </summary>
[AWSProperty(Required=true, Min=0, Max=10)]
public List<string> AgentHealths
{
get { return this._agentHealths; }
set { this._agentHealths = value; }
}
// Check to see if AgentHealths property is set
internal bool IsSetAgentHealths()
{
return this._agentHealths != null && this._agentHealths.Count > 0;
}
}
} | 34.15 | 107 | 0.629941 | [
"Apache-2.0"
] | DetlefGolze/aws-sdk-net | sdk/src/Services/Inspector/Generated/Model/AgentFilter.cs | 2,732 | C# |
/* CIL Tools
* Copyright (c) 2022, MSDN.WhiteKnight (https://github.com/MSDN-WhiteKnight)
* License: BSD 2.0 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CilTools.Syntax;
namespace CilView.Core.Syntax
{
public static class SyntaxReader
{
static bool IsWhitespace(string str)
{
for (int i = 0; i < str.Length; i++)
{
if (!char.IsWhiteSpace(str[i])) return false;
}
return true;
}
public static SyntaxNode[] ReadAllNodes(string src)
{
List<SyntaxNode> nodes = new List<SyntaxNode>();
TokenReader reader = new TokenReader(src);
string[] tokens = reader.ReadAll().ToArray();
if (tokens.Length == 0) return new SyntaxNode[0];
string leadingWhitespace;
int i = 0;
if (IsWhitespace(tokens[0]))
{
leadingWhitespace = tokens[0];
i = 1;
}
else
{
leadingWhitespace = string.Empty;
}
while (true)
{
if (i >= tokens.Length) break;
if (i + 1 >= tokens.Length)
{
nodes.Add(SyntaxFactory.CreateFromToken(tokens[i], leadingWhitespace, string.Empty));
break;
}
else if (IsWhitespace(tokens[i + 1]))
{
nodes.Add(SyntaxFactory.CreateFromToken(tokens[i], leadingWhitespace, tokens[i + 1]));
i += 2;
}
else
{
nodes.Add(SyntaxFactory.CreateFromToken(tokens[i], leadingWhitespace, string.Empty));
i++;
}
leadingWhitespace = string.Empty;
}
return nodes.ToArray();
}
}
}
| 28.042254 | 106 | 0.472627 | [
"BSD-3-Clause"
] | MSDN-WhiteKnight/CilBytecodeParser | CilView.Core/Syntax/SyntaxReader.cs | 1,993 | C# |
namespace GRA
{
public static class ClaimType
{
public static readonly string AuthenticatedAt = "GRA.AuthenticatedAt";
public static readonly string BranchId = "GRA.BranchId";
public static readonly string Permission = "GRA.Permission";
public static readonly string SiteId = "GRA.SiteId";
public static readonly string SystemId = "GRA.SystemId";
public static readonly string UserId = "GRA.UserId";
}
}
| 35.769231 | 78 | 0.683871 | [
"MIT"
] | MCLD/greatreadingadventure | src/GRA/ClaimType.cs | 467 | C# |
using System.Collections.Generic;
using System.Text.Json.Serialization;
namespace Essensoft.AspNetCore.Payment.Alipay.Domain
{
/// <summary>
/// JointAccountMemberRespDTO Data Structure.
/// </summary>
public class JointAccountMemberRespDTO : AlipayObject
{
/// <summary>
/// 额度模型
/// </summary>
[JsonPropertyName("account_quota")]
public List<JointAccountQuotaDTO> AccountQuota { get; set; }
/// <summary>
/// 成员支付宝登录号
/// </summary>
[JsonPropertyName("logon_id")]
public string LogonId { get; set; }
/// <summary>
/// 姓名
/// </summary>
[JsonPropertyName("name")]
public string Name { get; set; }
/// <summary>
/// 员工当前状态: 邀请中(PROCESSING)、正常(NORMAL)
/// </summary>
[JsonPropertyName("status")]
public string Status { get; set; }
/// <summary>
/// 用户支付宝会员号
/// </summary>
[JsonPropertyName("user_id")]
public string UserId { get; set; }
}
}
| 25.5 | 68 | 0.54902 | [
"MIT"
] | lzw316/payment | src/Essensoft.AspNetCore.Payment.Alipay/Domain/JointAccountMemberRespDTO.cs | 1,149 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Net;
using System.Text;
using System.Windows.Forms;
using Office365APIEditor.ViewerHelper;
using Office365APIEditor.ViewerHelper.Data;
using Office365APIEditor.ViewerHelper.Data.AttachmentAPI;
using Office365APIEditor.ViewerHelper.Data.MailAPI;
namespace Office365APIEditor.UI
{
public partial class SendMailForm : Form
{
FolderInfo targetFolder;
string targetFolderDisplayName;
string draftItemId;
private ViewerRequestHelper viewerRequestHelper;
List<FileAttachment> attachments;
public SendMailForm()
{
InitializeComponent();
targetFolder = new FolderInfo();
targetFolderDisplayName = null;
draftItemId = "";
}
public SendMailForm(string DraftItemId)
{
InitializeComponent();
targetFolder = new FolderInfo();
targetFolderDisplayName = null;
draftItemId = DraftItemId;
}
public SendMailForm(FolderInfo TargetFolderInfo, string TargetFolderDisplayName)
{
InitializeComponent();
targetFolder = TargetFolderInfo;
targetFolderDisplayName = TargetFolderDisplayName;
draftItemId = "";
}
private async void SendMailForm_LoadAsync(object sender, EventArgs e)
{
Icon = Properties.Resources.DefaultIcon;
attachments = new List<FileAttachment>();
// Display the window in the center of the parent window.
Location = new Point(Owner.Location.X + (Owner.Width - Width) / 2, Owner.Location.Y + (Owner.Height - Height) / 2);
comboBox_Importance.SelectedIndex = 1;
comboBox_BodyType.SelectedIndex = 0;
if (draftItemId != "")
{
// Editing a draft item.
button_Attachments.Enabled = false;
// When sending a draft item, it must be saved to SentItems.
checkBox_SaveToSentItems.Checked = true;
checkBox_SaveToSentItems.Enabled = false;
viewerRequestHelper = new ViewerRequestHelper();
NewEmailMessage draftItem;
try
{
draftItem = await viewerRequestHelper.GetDraftMessageAsync(draftItemId);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, "Office365APIEditor", MessageBoxButtons.OK, MessageBoxIcon.Error);
Close();
return;
}
if (comboBox_Importance.InvokeRequired)
{
comboBox_Importance.Invoke(new MethodInvoker(delegate
{
comboBox_Importance.SelectedIndex = (int)draftItem.Importance;
}));
}
else
{
comboBox_Importance.SelectedIndex = (int)draftItem.Importance;
}
if (comboBox_Importance.InvokeRequired)
{
comboBox_Importance.Invoke(new MethodInvoker(delegate
{
comboBox_Importance.SelectedIndex = (int)draftItem.Importance; ;
}));
}
else
{
comboBox_Importance.SelectedIndex = (int)draftItem.Importance;
}
if (checkBox_RequestDeliveryReceipt.InvokeRequired)
{
checkBox_RequestDeliveryReceipt.Invoke(new MethodInvoker(delegate
{
checkBox_RequestDeliveryReceipt.Checked = draftItem.IsDeliveryReceiptRequested;
}));
}
else
{
checkBox_RequestDeliveryReceipt.Checked = draftItem.IsDeliveryReceiptRequested;
}
if (checkBox_RequestReadReceipt.InvokeRequired)
{
checkBox_RequestReadReceipt.Invoke(new MethodInvoker(delegate
{
checkBox_RequestReadReceipt.Checked = draftItem.IsReadReceiptRequested;
}));
}
else
{
checkBox_RequestReadReceipt.Checked = draftItem.IsReadReceiptRequested;
}
if (textBox_To.InvokeRequired)
{
textBox_To.Invoke(new MethodInvoker(delegate
{
textBox_To.Text = RecipientsString(draftItem.ToRecipients);
}));
}
else
{
textBox_To.Text = RecipientsString(draftItem.ToRecipients);
}
if (textBox_Cc.InvokeRequired)
{
textBox_Cc.Invoke(new MethodInvoker(delegate
{
textBox_Cc.Text = RecipientsString(draftItem.CcRecipients);
}));
}
else
{
textBox_Cc.Text = RecipientsString(draftItem.CcRecipients);
}
if (textBox_Bcc.InvokeRequired)
{
textBox_Bcc.Invoke(new MethodInvoker(delegate
{
textBox_Bcc.Text = RecipientsString(draftItem.BccRecipients);
}));
}
else
{
textBox_Bcc.Text = RecipientsString(draftItem.BccRecipients);
}
if (textBox_Subject.InvokeRequired)
{
textBox_Subject.Invoke(new MethodInvoker(delegate
{
textBox_Subject.Text = draftItem.Subject;
}));
}
else
{
textBox_Subject.Text = draftItem.Subject;
}
if (textBox_Body.InvokeRequired)
{
textBox_Body.Invoke(new MethodInvoker(delegate
{
textBox_Body.Text = draftItem.Body.Content;
}));
}
else
{
textBox_Body.Text = draftItem.Body.Content;
}
if (comboBox_BodyType.InvokeRequired)
{
comboBox_BodyType.Invoke(new MethodInvoker(delegate
{
comboBox_BodyType.SelectedIndex = (int)draftItem.Body.ContentType;
}));
}
else
{
comboBox_BodyType.SelectedIndex = (int)draftItem.Body.ContentType;
}
var attachList = await viewerRequestHelper.GetAllAttachmentsAsync(FolderContentType.Message, draftItemId);
foreach (var attach in attachList)
{
Dictionary<string, string> fullAttachInfo = await viewerRequestHelper.GetAttachmentAsync(FolderContentType.Message, draftItemId, attach.Id);
string tempType = "";
string tempName = "";
string tempContentBytes = "";
foreach (KeyValuePair<string, string> item in fullAttachInfo)
{
if (item.Key.ToLowerInvariant() == "@odata.type")
{
tempType = (item.Value == null) ? "" : item.Value.ToString();
}
else if (item.Key.ToLowerInvariant() == "name")
{
tempName = (item.Value == null) ? "" : item.Value.ToString();
}
else if (item.Key.ToLowerInvariant() == "contentbytes")
{
tempContentBytes = (item.Value == null) ? "" : item.Value.ToString();
}
}
if (tempType == (Util.UseMicrosoftGraphInMailboxViewer ? "#microsoft.graph.fileAttachment" : "#Microsoft.OutlookServices.FileAttachment"))
{
// This is a FileAttachment
attachments.Add(FileAttachment.CreateFromContentBytes(tempName, tempContentBytes));
}
}
if (button_Attachments.InvokeRequired)
{
button_Attachments.Invoke(new MethodInvoker(delegate
{
button_Attachments.Enabled = true;
}));
}
else
{
button_Attachments.Enabled = true;
}
}
}
private string RecipientsString(List<Recipient> mailAddresses)
{
List<string> temp = new List<string>();
foreach (var recipient in mailAddresses)
{
temp.Add(recipient.EmailAddress.Address);
}
return string.Join("; ", temp.ToArray());
}
private async void Button_Send_ClickAsync(object sender, EventArgs e)
{
// Send new mail.
Enabled = false;
viewerRequestHelper = new ViewerRequestHelper();
NewEmailMessage newItem;
try
{
newItem = CreateNewEmailMessageObject();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Office365APIEditor", MessageBoxButtons.OK, MessageBoxIcon.Error);
Enabled = true;
return;
}
try
{
if (draftItemId == "")
{
await viewerRequestHelper.SendMailAsync(newItem, checkBox_SaveToSentItems.Checked);
}
else
{
// This is a draft message.
// Update then send it.
await viewerRequestHelper.UpdateDraftAsync(draftItemId, newItem);
await viewerRequestHelper.SendMailAsync(draftItemId);
}
Close();
}
catch (WebException ex)
{
if (ex.Response == null)
{
MessageBox.Show(ex.Message, "Office365APIEditor", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
string jsonResponse = "";
using (Stream responseStream = ex.Response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.Default);
jsonResponse = reader.ReadToEnd();
}
HttpWebResponse response = (HttpWebResponse)ex.Response;
MessageBox.Show(response.StatusCode.ToString() + Environment.NewLine + jsonResponse + Environment.NewLine, "Office365APIEditor", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Office365APIEditor", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
Enabled = true;
}
}
private async void Button_Save_Click(object sender, EventArgs e)
{
// Save new mail.
Enabled = false;
viewerRequestHelper = new ViewerRequestHelper();
NewEmailMessage newItem;
try
{
newItem = CreateNewEmailMessageObject();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Office365APIEditor", MessageBoxButtons.OK, MessageBoxIcon.Error);
Enabled = true;
return;
}
try
{
if (draftItemId == "")
{
await viewerRequestHelper.SaveDraftAsync(newItem);
}
else
{
// This is a draft message.
await viewerRequestHelper.UpdateDraftAsync(draftItemId, newItem);
}
Close();
}
catch (WebException ex)
{
if (ex.Response == null)
{
MessageBox.Show(ex.Message, "Office365APIEditor", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
string jsonResponse = "";
using (Stream responseStream = ex.Response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.Default);
jsonResponse = reader.ReadToEnd();
}
HttpWebResponse response = (HttpWebResponse)ex.Response;
MessageBox.Show(response.StatusCode.ToString() + Environment.NewLine + jsonResponse + Environment.NewLine, "Office365APIEditor", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Office365APIEditor", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
Enabled = true;
}
}
private NewEmailMessage CreateNewEmailMessageObject()
{
NewEmailMessage newItem = new NewEmailMessage();
try
{
List<Recipient> toMailAddresses = new List<Recipient>();
if (textBox_To.Text != "")
{
foreach (var recipient in textBox_To.Text.Split(';'))
{
toMailAddresses.Add(new Recipient("", recipient.Trim()));
}
}
newItem.ToRecipients = toMailAddresses;
List<Recipient> ccMailAddresses = new List<Recipient>();
if (textBox_Cc.Text != "")
{
foreach (var recipient in textBox_Cc.Text.Split(';'))
{
ccMailAddresses.Add(new Recipient("", recipient.Trim()));
}
}
newItem.CcRecipients = ccMailAddresses;
List<Recipient> bccMailAddresses = new List<Recipient>();
if (textBox_Bcc.Text != "")
{
foreach (var recipient in textBox_Bcc.Text.Split(';'))
{
bccMailAddresses.Add(new Recipient("", recipient.Trim()));
}
}
newItem.BccRecipients = bccMailAddresses;
}
catch (Exception ex)
{
throw new Exception("Invalid recipients. " + ex.Message, ex);
}
newItem.Subject = textBox_Subject.Text;
newItem.Body.ContentType = (BodyType)comboBox_BodyType.SelectedIndex;
newItem.Body.Content = textBox_Body.Text;
newItem.Importance = (Importance)comboBox_Importance.SelectedIndex;
newItem.IsDeliveryReceiptRequested = checkBox_RequestDeliveryReceipt.Checked;
newItem.IsReadReceiptRequested = checkBox_RequestReadReceipt.Checked;
newItem.Attachments = attachments;
return newItem;
}
private void Button_Attachments_Click(object sender, EventArgs e)
{
NewAttachmentForm newAttachmentForm = new NewAttachmentForm(attachments);
if (newAttachmentForm.ShowDialog(out List<ViewerHelper.Data.AttachmentAPI.FileAttachment> newAttachments) == DialogResult.OK)
{
attachments = newAttachments;
}
}
}
} | 35.28178 | 193 | 0.492224 | [
"MIT"
] | ConnectionMaster/Office365APIEditor | Office365APIEditor/UI/SendMailForm.cs | 16,655 | C# |
/*******************************************************************************
* Copyright 2012-2019 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.
* *****************************************************************************
*
* AWS Tools for Windows (TM) PowerShell (TM)
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using System.Text;
using Amazon.PowerShell.Common;
using Amazon.Runtime;
using Amazon.AppStream;
using Amazon.AppStream.Model;
namespace Amazon.PowerShell.Cmdlets.APS
{
/// <summary>
/// Associates the specified fleet with the specified stack.
/// </summary>
[Cmdlet("Register", "APSFleet", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.Medium)]
[OutputType("None")]
[AWSCmdlet("Calls the Amazon AppStream AssociateFleet API operation.", Operation = new[] {"AssociateFleet"}, SelectReturnType = typeof(Amazon.AppStream.Model.AssociateFleetResponse))]
[AWSCmdletOutput("None or Amazon.AppStream.Model.AssociateFleetResponse",
"This cmdlet does not generate any output." +
"The service response (type Amazon.AppStream.Model.AssociateFleetResponse) can be referenced from properties attached to the cmdlet entry in the $AWSHistory stack."
)]
public partial class RegisterAPSFleetCmdlet : AmazonAppStreamClientCmdlet, IExecutor
{
#region Parameter FleetName
/// <summary>
/// <para>
/// <para>The name of the fleet. </para>
/// </para>
/// </summary>
#if !MODULAR
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
#else
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true, Mandatory = true)]
[System.Management.Automation.AllowEmptyString]
[System.Management.Automation.AllowNull]
#endif
[Amazon.PowerShell.Common.AWSRequiredParameter]
public System.String FleetName { get; set; }
#endregion
#region Parameter StackName
/// <summary>
/// <para>
/// <para>The name of the stack.</para>
/// </para>
/// </summary>
#if !MODULAR
[System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true)]
#else
[System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true, Mandatory = true)]
[System.Management.Automation.AllowEmptyString]
[System.Management.Automation.AllowNull]
#endif
[Amazon.PowerShell.Common.AWSRequiredParameter]
public System.String StackName { get; set; }
#endregion
#region Parameter Select
/// <summary>
/// Use the -Select parameter to control the cmdlet output. The cmdlet doesn't have a return value by default.
/// Specifying -Select '*' will result in the cmdlet returning the whole service response (Amazon.AppStream.Model.AssociateFleetResponse).
/// Specifying -Select '^ParameterName' will result in the cmdlet returning the selected cmdlet parameter value.
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public string Select { get; set; } = "*";
#endregion
#region Parameter PassThru
/// <summary>
/// Changes the cmdlet behavior to return the value passed to the StackName parameter.
/// The -PassThru parameter is deprecated, use -Select '^StackName' instead. This parameter will be removed in a future version.
/// </summary>
[System.Obsolete("The -PassThru parameter is deprecated, use -Select '^StackName' instead. This parameter will be removed in a future version.")]
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public SwitchParameter PassThru { get; set; }
#endregion
#region Parameter Force
/// <summary>
/// This parameter overrides confirmation prompts to force
/// the cmdlet to continue its operation. This parameter should always
/// be used with caution.
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public SwitchParameter Force { get; set; }
#endregion
protected override void ProcessRecord()
{
base.ProcessRecord();
var resourceIdentifiersText = FormatParameterValuesForConfirmationMsg(nameof(this.StackName), MyInvocation.BoundParameters);
if (!ConfirmShouldProceed(this.Force.IsPresent, resourceIdentifiersText, "Register-APSFleet (AssociateFleet)"))
{
return;
}
var context = new CmdletContext();
// allow for manipulation of parameters prior to loading into context
PreExecutionContextLoad(context);
#pragma warning disable CS0618, CS0612 //A class member was marked with the Obsolete attribute
if (ParameterWasBound(nameof(this.Select)))
{
context.Select = CreateSelectDelegate<Amazon.AppStream.Model.AssociateFleetResponse, RegisterAPSFleetCmdlet>(Select) ??
throw new System.ArgumentException("Invalid value for -Select parameter.", nameof(this.Select));
if (this.PassThru.IsPresent)
{
throw new System.ArgumentException("-PassThru cannot be used when -Select is specified.", nameof(this.Select));
}
}
else if (this.PassThru.IsPresent)
{
context.Select = (response, cmdlet) => this.StackName;
}
#pragma warning restore CS0618, CS0612 //A class member was marked with the Obsolete attribute
context.FleetName = this.FleetName;
#if MODULAR
if (this.FleetName == null && ParameterWasBound(nameof(this.FleetName)))
{
WriteWarning("You are passing $null as a value for parameter FleetName which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues.");
}
#endif
context.StackName = this.StackName;
#if MODULAR
if (this.StackName == null && ParameterWasBound(nameof(this.StackName)))
{
WriteWarning("You are passing $null as a value for parameter StackName which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues.");
}
#endif
// allow further manipulation of loaded context prior to processing
PostExecutionContextLoad(context);
var output = Execute(context) as CmdletOutput;
ProcessOutput(output);
}
#region IExecutor Members
public object Execute(ExecutorContext context)
{
var cmdletContext = context as CmdletContext;
// create request
var request = new Amazon.AppStream.Model.AssociateFleetRequest();
if (cmdletContext.FleetName != null)
{
request.FleetName = cmdletContext.FleetName;
}
if (cmdletContext.StackName != null)
{
request.StackName = cmdletContext.StackName;
}
CmdletOutput output;
// issue call
var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint);
try
{
var response = CallAWSServiceOperation(client, request);
object pipelineOutput = null;
pipelineOutput = cmdletContext.Select(response, this);
output = new CmdletOutput
{
PipelineOutput = pipelineOutput,
ServiceResponse = response
};
}
catch (Exception e)
{
output = new CmdletOutput { ErrorResponse = e };
}
return output;
}
public ExecutorContext CreateContext()
{
return new CmdletContext();
}
#endregion
#region AWS Service Operation Call
private Amazon.AppStream.Model.AssociateFleetResponse CallAWSServiceOperation(IAmazonAppStream client, Amazon.AppStream.Model.AssociateFleetRequest request)
{
Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "Amazon AppStream", "AssociateFleet");
try
{
#if DESKTOP
return client.AssociateFleet(request);
#elif CORECLR
return client.AssociateFleetAsync(request).GetAwaiter().GetResult();
#else
#error "Unknown build edition"
#endif
}
catch (AmazonServiceException exc)
{
var webException = exc.InnerException as System.Net.WebException;
if (webException != null)
{
throw new Exception(Utils.Common.FormatNameResolutionFailureMessage(client.Config, webException.Message), webException);
}
throw;
}
}
#endregion
internal partial class CmdletContext : ExecutorContext
{
public System.String FleetName { get; set; }
public System.String StackName { get; set; }
public System.Func<Amazon.AppStream.Model.AssociateFleetResponse, RegisterAPSFleetCmdlet, object> Select { get; set; } =
(response, cmdlet) => null;
}
}
}
| 44.131148 | 280 | 0.606426 | [
"Apache-2.0"
] | 5u5hma/aws-tools-for-powershell | modules/AWSPowerShell/Cmdlets/AppStream/Basic/Register-APSFleet-Cmdlet.cs | 10,768 | C# |
//-----------------------------------------------------------------------
// <copyright file="TwitterFavoriteAsync.cs" company="Patrick 'Ricky' Smith">
// This file is part of the Twitterizer library (http://www.twitterizer.net/)
//
// Copyright (c) 2010, Patrick "Ricky" Smith (ricky@digitally-born.com)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this list
// of conditions and the following disclaimer.
// - Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other
// materials provided with the distribution.
// - Neither the name of the Twitterizer nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
// </copyright>
// <author>Ricky Smith</author>
// <summary>The asynchronous twitter favorite class.</summary>
//-----------------------------------------------------------------------
namespace Twitterizer
{
using System;
/// <summary>
/// An asynchronous wrapper around the <see cref="TwitterFavorite"/> class.
/// </summary>
public static class TwitterFavoriteAsync
{
/// <summary>
/// Favorites the status specified in the ID parameter as the authenticating user.
/// </summary>
/// <param name="tokens">The tokens.</param>
/// <param name="statusId">The status id.</param>
/// <param name="options">The options.</param>
/// <param name="timeout">The timeout.</param>
/// <param name="function">The function.</param>
/// <returns></returns>
public static IAsyncResult Create(OAuthTokens tokens, decimal statusId, OptionalProperties options, TimeSpan timeout, Action<TwitterAsyncResponse<TwitterStatus>> function)
{
return AsyncUtility.ExecuteAsyncMethod(tokens, statusId, options, timeout, TwitterFavorite.Create, function);
}
/// <summary>
/// Un-favorites the status specified in the ID parameter as the authenticating user.
/// </summary>
/// <param name="tokens">The tokens.</param>
/// <param name="statusId">The status id.</param>
/// <param name="options">The options.</param>
/// <param name="timeout">The timeout.</param>
/// <param name="function">The function.</param>
/// <returns></returns>
public static IAsyncResult Delete(OAuthTokens tokens, decimal statusId, OptionalProperties options, TimeSpan timeout, Action<TwitterAsyncResponse<TwitterStatus>> function)
{
return AsyncUtility.ExecuteAsyncMethod(tokens, statusId, options, timeout, TwitterFavorite.Delete, function);
}
/// <summary>
/// Returns the 20 most recent favorite statuses for the authenticating user or user specified by the ID parameter in the requested format.
/// </summary>
/// <param name="tokens">The tokens.</param>
/// <param name="options">The options.</param>
/// <param name="timeout">The timeout.</param>
/// <param name="function">The function.</param>
/// <returns></returns>
public static IAsyncResult List(OAuthTokens tokens, ListFavoritesOptions options, TimeSpan timeout, Action<TwitterAsyncResponse<TwitterStatusCollection>> function)
{
return AsyncUtility.ExecuteAsyncMethod(tokens, options, timeout, TwitterFavorite.List, function);
}
}
}
| 54.623529 | 180 | 0.656257 | [
"MIT",
"BSD-3-Clause"
] | HemantNegi/Twitterizer | Twitterizer2.Async/TwitterFavoriteAsync.cs | 4,645 | C# |
namespace DevFreela.Application.ViewModels
{
public class UserViewModel
{
public UserViewModel(string fullName, string email)
{
FullName = fullName;
Email = email;
}
public string FullName { get; private set; }
public string Email { get; private set; }
}
}
| 22.333333 | 59 | 0.585075 | [
"MIT"
] | WanderleiSantos/DevFreela | DevFreela.Application/ViewModels/UserViewModel.cs | 337 | C# |
using System;
using System.Threading.Tasks;
using Core.Net;
using Core.Ircx.Objects;
using Core.Ircx;
using CSharpTools;
using System.Security.Cryptography;
using System.Collections.Generic;
namespace Core
{
public class Program
{
public static ServerSettings Config;
public static string BasePath = AppDomain.CurrentDomain.BaseDirectory;
public static List<Authentication.SSPCredentials> Credentials = new List<Authentication.SSPCredentials>();
public static Server BaseServer;
public static Engine engine;
public static void Main(string[] args)
{
System.Runtime.Loader.AssemblyLoadContext.Default.Unloading += Default_Unloading;
Config = (ServerSettings)Settings.LoadObject(BasePath + "settings.json", typeof(ServerSettings));
if (Config == null) {
Config = new ServerSettings();
Config.version = System.Reflection.Assembly.GetEntryAssembly().GetName().Version.ToString();
Config.major = System.Reflection.Assembly.GetEntryAssembly().GetName().Version.Major;
Config.minor = System.Reflection.Assembly.GetEntryAssembly().GetName().Version.Minor;
Config.build = System.Reflection.Assembly.GetEntryAssembly().GetName().Version.Build;
}
ObjIDGenerator.ServerID = Config.ServerID;
Credentials = (List<Authentication.SSPCredentials>)Settings.LoadObject(BasePath + "credentials.json", typeof(List<Authentication.SSPCredentials>));
if (Credentials == null) { Credentials = new List<Authentication.SSPCredentials>(); }
Core.Authentication.SSP.EnumerateSupportPackages();
Core.Authentication.Package.GateKeeper gkp = new Authentication.Package.GateKeeper();
for (int x = 0; x < args.Length; x++)
{
switch (args[x])
{
case "-console":
{
Debug.EnableVerbose();
break;
}
case "-bindip":
{
if (args.Length > x + 1) // base 0 (plus 1 for base 1), plus 1
{
Config.BindIP = args[x + 1];
}
break;
}
case "-remoteip":
{
if (args.Length > x + 1) // base 0 (plus 1 for base 1), plus 1
{
Config.ExternalIP = args[x + 1];
}
break;
}
case "-debug":
{
Debug.Enable();
break;
}
case "-bindport":
{
if (args.Length > x + 1) // base 0 (plus 1 for base 1), plus 1
{
int.TryParse(args[x + 1], out Config.BindPort);
}
break;
}
}
}
Debug.Out(String.Format("port: {0} buffSize: {1} backLog: {2} maxClients: {3} maxClientsPerIP: {4}", Config.BindPort, Config.BufferSize, Config.BackLog, Config.MaxClients, Config.MaxClientsPerIP));
BaseServer = new Server(Program.Config.ServerName);
List<ChannelSettings> Channels = (List<ChannelSettings>)Settings.LoadObject(BasePath + "channels.json", typeof(List<ChannelSettings>)); //new List<ChannelSettings>();
if (Channels == null) { Channels = new List<ChannelSettings>(); }
for (int c = 0; c < Channels.Count; c++)
{
Channel channel = BaseServer.AddChannel(Channels[c].Name);
if (Channels[c].Topic != null) { channel.Properties.Topic.Value = Channels[c].Topic; }
else { channel.Properties.Topic.Value = Resources.Null; }
channel.Properties.TopicLastChanged = Channels[c].TopicLastChanged;
channel.Properties.Ownerkey.Value = Channels[c].Ownerkey;
channel.Properties.Hostkey.Value = Channels[c].Hostkey;
channel.Properties.Subject.Value = Channels[c].Subject;
channel.Modes.Registered.Value = Channels[c].Registered;
channel.Modes.UserLimit.Value = Channels[c].UserLimit;
channel.Modes.Subscriber.Value = Channels[c].Subscriber;
channel.Modes.AuthOnly.Value = Channels[c].AuthOnly;
}
Core.Ircx.Runtime.Stats.ExportCategories(BaseServer);
System.Net.IPAddress ip = null;
if (Config.BindIP != null) {
System.Net.IPAddress.TryParse(Config.BindIP, out ip);
}
if (ip == null) { ip = new System.Net.IPAddress(new byte[] { 127, 0, 0, 1 }); }
Debug.Out(String.Format("Binding on {0}:{1}", ip.ToString(), Config.BindPort));
engine = new Engine(BaseServer, ip, Config.BufferSize, Config.MaxClientsPerIP);
engine.Start(ip, Config.BindPort, Config.BufferSize, Config.BackLog);
}
private static void Default_Unloading(System.Runtime.Loader.AssemblyLoadContext obj)
{
if (engine != null) { engine.Stop(); }
}
}
}
| 44.736 | 209 | 0.526645 | [
"MIT"
] | IRC7/IRC7 | Program.cs | 5,594 | C# |
/*******************************************************************************
* Copyright (C) Git Corporation. All rights reserved.
*
* Author: 情缘
* Create Date: 2016-05-12 11:02:33
*
* Description: Git.Framework
* http://www.cnblogs.com/qingyuan/
* Revision History:
* Date Author Description
* 2016-05-12 11:02:33 情缘
*********************************************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Git.Storage.Common.Enum
{
public enum EAllocate
{
}
}
| 23.423077 | 82 | 0.477833 | [
"MIT"
] | colin08/yun_gitwms | Git.WMS.Web/Git.Storage.Common/Enum/EAllocate.cs | 619 | C# |
// YWMenu - YourWishIsMine's Menu
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace YWMenuNS
{
class YWMenu
{
public static Char playerDirection;
public string[] Menu(string question, Dictionary<char, string> choices, List<string> errorMessages)
{
Random rand = new Random();
ConsoleKeyInfo keyPressed;
string[] result = { "***ERROR***", ""};
string message = "";
string regExPattern = @"[0-9a-zA-Z\?]";
Regex regEx = new Regex(regExPattern);
do
{
if (message != "")
{
Console.WriteLine("\n" + message);
}
result[0] = "***ERROR***";
Console.WriteLine();
foreach (KeyValuePair<char, string> item in choices)
{
Console.Write("[{0}], ", item.Key);
}
Console.Write("[?]\n");
Console.Write("{0}: ", question);
do
{
keyPressed = Console.ReadKey(true);
playerDirection = keyPressed.KeyChar;
}
while (!(regEx.IsMatch(keyPressed.KeyChar.ToString())));
Console.WriteLine();
foreach (KeyValuePair<char, string> item in choices)
{
if (keyPressed.KeyChar.ToString().ToLower() == item.Key.ToString().ToLower())
{
result[0] = item.Key.ToString();
result[1] = item.Value;
}
}
if (keyPressed.KeyChar.ToString() == "?")
{
result[0] = "HELP";
message = "";
Console.WriteLine();
foreach (KeyValuePair<char, string> item in choices)
{
Console.WriteLine("[{0}] - {1}", item.Key, item.Value);
}
}
if (result[0] == "***ERROR***")
{
message = errorMessages[rand.Next(0, errorMessages.Count)];
}
} while (result[0] == "***ERROR***" || result[0] == "HELP");
return result;
}
}
}
| 36.80597 | 108 | 0.412409 | [
"MIT"
] | johnschwarz/Wizards-Castle-40th-Anniversary-CSharp-Edition | YWMenu.cs | 2,468 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using YTSubConverter.Shared.Formats.Ass;
using YTSubConverter.Shared.Util;
namespace YTSubConverter.Shared.Animations
{
internal static class Animator
{
public static IEnumerable<AssLine> Expand(AssDocument document, AssLine originalLine)
{
List<AnimationWithSectionIndex> anims = GetAnimationsWithSectionIndex(originalLine);
if (anims.Count == 0)
{
yield return originalLine;
yield break;
}
SortedList<TimeRange, List<AnimationWithSectionIndex>> animClusters = ClusterAnimations(originalLine, anims);
AssLine lastLine = CreateInitialLine(originalLine, anims);
if (animClusters.Count == 0 || animClusters.Keys[0].Start > lastLine.Start)
yield return lastLine;
for (int i = 0; i < animClusters.Count; i++)
{
TimeRange clusterRange = animClusters.Keys[i];
List<AnimationWithSectionIndex> clusterAnims = animClusters.Values[i];
foreach (AssLine frameLine in CreateFrameLines(document, lastLine, clusterRange, clusterAnims))
{
lastLine.End = frameLine.Start;
yield return lastLine = frameLine;
}
DateTime interAnimStart = clusterRange.End;
DateTime interAnimEnd = i < animClusters.Count - 1 ? animClusters.Keys[i + 1].Start : originalLine.End;
if (interAnimEnd > interAnimStart)
yield return lastLine = CreatePostAnimationClusterLine(originalLine, lastLine, interAnimStart, interAnimEnd, clusterAnims);
}
lastLine.End = originalLine.End;
}
private static List<AnimationWithSectionIndex> GetAnimationsWithSectionIndex(AssLine line)
{
List<AnimationWithSectionIndex> animations = new List<AnimationWithSectionIndex>();
foreach (Animation anim in line.Animations.Where(a => a is MoveAnimation))
{
animations.Add(new AnimationWithSectionIndex(anim, -1));
}
foreach (Animation anim in line.Animations.Where(a => !(a is MoveAnimation)))
{
animations.Add(new AnimationWithSectionIndex(anim, -1));
}
for (int i = 0; i < line.Sections.Count; i++)
{
AssSection section = (AssSection)line.Sections[i];
foreach (Animation anim in section.Animations)
{
animations.Add(new AnimationWithSectionIndex(anim, i));
}
}
return animations;
}
private static SortedList<TimeRange, List<AnimationWithSectionIndex>> ClusterAnimations(AssLine line, List<AnimationWithSectionIndex> allAnims)
{
List<TimeRange> clusterRanges = GetAnimationClusterTimeRanges(allAnims.Select(a => a.Animation));
TimeRange lineRange = new TimeRange(line.Start, line.End);
var clusters = new SortedList<TimeRange, List<AnimationWithSectionIndex>>();
foreach (TimeRange clusterRange in clusterRanges)
{
if (!clusterRange.Overlaps(lineRange))
continue;
List<AnimationWithSectionIndex> clusterAnims = new List<AnimationWithSectionIndex>();
foreach (AnimationWithSectionIndex animWithSection in allAnims)
{
if (clusterRange.Contains(animWithSection.Animation.StartTime) && animWithSection.Animation.EndTime > animWithSection.Animation.StartTime)
clusterAnims.Add(animWithSection);
}
clusterRange.IntersectWith(lineRange);
clusterRange.Start = TimeUtil.RoundTimeToFrameCenter(clusterRange.Start);
clusterRange.End = TimeUtil.RoundTimeToFrameCenter(clusterRange.End);
clusters.FetchValue(clusterRange, () => new List<AnimationWithSectionIndex>()).AddRange(clusterAnims);
}
return clusters;
}
private static List<TimeRange> GetAnimationClusterTimeRanges(IEnumerable<Animation> animations)
{
List<TimeRange> clusterRanges = new List<TimeRange>();
foreach (Animation animation in animations)
{
TimeRange animationRange = new TimeRange(animation.StartTime, animation.EndTime);
for (int i = clusterRanges.Count - 1; i >= 0; i--)
{
if (clusterRanges[i].Overlaps(animationRange))
{
animationRange.UnionWith(clusterRanges[i]);
clusterRanges.RemoveAt(i);
}
}
clusterRanges.Add(animationRange);
}
return clusterRanges;
}
private static AssLine CreateInitialLine(AssLine originalLine, List<AnimationWithSectionIndex> anims)
{
AssLine newLine = (AssLine)originalLine.Clone();
newLine.Start = TimeUtil.RoundTimeToFrameCenter(newLine.Start);
foreach (AnimationWithSectionIndex anim in anims.Where(a => a.Animation.EndTime < originalLine.Start)
.OrderBy(a => a.Animation.EndTime))
{
ApplyAnimation(newLine, anim, 1);
}
foreach (AnimationWithSectionIndex anim in anims.Where(a => a.Animation.AffectsPast && a.Animation.StartTime >= originalLine.Start)
.OrderByDescending(a => a.Animation.StartTime))
{
ApplyAnimation(newLine, anim, 0);
}
return newLine;
}
private static AssLine CreatePostAnimationClusterLine(AssLine originalLine, AssLine lastLine, DateTime start, DateTime end, List<AnimationWithSectionIndex> animsWithSection)
{
AssLine newLine = (AssLine)lastLine.Clone();
newLine.Start = start;
newLine.End = end;
foreach (AnimationWithSectionIndex animWithSection in animsWithSection.OrderBy(a => a.Animation.EndTime))
{
if (animWithSection.Animation.AffectsText)
ResetText(newLine, originalLine);
ApplyAnimation(newLine, animWithSection, 1);
}
return newLine;
}
private static IEnumerable<AssLine> CreateFrameLines(AssDocument document, AssLine originalLine, TimeRange timeRange, List<AnimationWithSectionIndex> animations)
{
int rangeStartFrame = TimeUtil.StartTimeToFrame(timeRange.Start);
int rangeEndFrame = TimeUtil.EndTimeToFrame(timeRange.End);
int subStepFrames = (rangeEndFrame + 1 - rangeStartFrame) % GlobalSettings.FrameStep;
int lastIterationFrame = rangeEndFrame + 1 - subStepFrames - GlobalSettings.FrameStep;
bool needTextReset = animations.Any(a => a.Animation.AffectsText);
AssLine frameLine = originalLine;
for (int frame = rangeStartFrame; frame <= lastIterationFrame; frame += GlobalSettings.FrameStep)
{
frameLine = (AssLine)frameLine.Clone();
frameLine.Start = TimeUtil.FrameToStartTime(frame);
frameLine.End = frame < lastIterationFrame
? TimeUtil.FrameToEndTime(frame + GlobalSettings.FrameStep - 1)
: timeRange.End;
frameLine.Position = originalLine.Position ?? document.GetDefaultPosition(originalLine.AnchorPoint);
if (needTextReset)
ResetText(frameLine, originalLine);
float interpFrame = frame + (GlobalSettings.FrameStep - 1) / 2.0f;
foreach (AnimationWithSectionIndex animWithSection in animations)
{
int animStartFrame = TimeUtil.StartTimeToFrame(animWithSection.Animation.StartTime);
int animEndFrame = TimeUtil.EndTimeToFrame(animWithSection.Animation.EndTime);
if (interpFrame >= animStartFrame && interpFrame < animEndFrame)
{
float t = (interpFrame - animStartFrame) / (animEndFrame - animStartFrame);
ApplyAnimation(frameLine, animWithSection, t);
}
else if (interpFrame >= animEndFrame && interpFrame < animEndFrame + GlobalSettings.FrameStep)
{
ApplyAnimation(frameLine, animWithSection, 1);
}
}
yield return frameLine;
}
}
private static void ApplyAnimation(AssLine line, AnimationWithSectionIndex animWithSectionIdx, float t)
{
animWithSectionIdx.Animation.Apply(line, animWithSectionIdx.SectionIndex >= 0 ? (AssSection)line.Sections[animWithSectionIdx.SectionIndex] : null, t);
}
private static void ResetText(AssLine frameLine, AssLine originalLine)
{
for (int i = 0; i < frameLine.Sections.Count; i++)
{
frameLine.Sections[i].Text = originalLine.Sections[i].Text;
}
}
private struct AnimationWithSectionIndex
{
public AnimationWithSectionIndex(Animation animation, int sectionIndex)
{
Animation = animation;
SectionIndex = sectionIndex;
}
public Animation Animation;
public int SectionIndex;
}
}
}
| 45.926606 | 182 | 0.582901 | [
"MIT"
] | Meigyoku-Thmn/YTSubConverter | YTSubConverter.Shared/Animations/Animator.cs | 10,014 | C# |
/**
* Copyright 2015 Canada Health Infoway, Inc.
*
* 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.
*
* Author: $LastChangedBy: jmis $
* Last modified: $LastChangedDate: 2015-09-15 10:24:28 -0400 (Tue, 15 Sep 2015) $
* Revision: $LastChangedRevision: 9776 $
*/
/* This class was auto-generated by the message builder generator tools. */
namespace Ca.Infoway.Messagebuilder.Model.Pcs_cerx_v01_r04_3.Pharmacy.Porx_mt060210ca {
using Ca.Infoway.Messagebuilder.Annotation;
using Ca.Infoway.Messagebuilder.Datatype;
using Ca.Infoway.Messagebuilder.Datatype.Impl;
using Ca.Infoway.Messagebuilder.Datatype.Lang;
using Ca.Infoway.Messagebuilder.Domainvalue;
using Ca.Infoway.Messagebuilder.Model;
using Ca.Infoway.Messagebuilder.Model.Pcs_cerx_v01_r04_3.Common.Coct_mt050203ca;
using Ca.Infoway.Messagebuilder.Model.Pcs_cerx_v01_r04_3.Common.Coct_mt090107ca;
using Ca.Infoway.Messagebuilder.Model.Pcs_cerx_v01_r04_3.Common.Coct_mt120600ca;
using Ca.Infoway.Messagebuilder.Model.Pcs_cerx_v01_r04_3.Common.Coct_mt220110ca;
using Ca.Infoway.Messagebuilder.Model.Pcs_cerx_v01_r04_3.Merged;
using Ca.Infoway.Messagebuilder.Model.Pcs_cerx_v01_r04_3.Pharmacy.Merged;
using Ca.Infoway.Messagebuilder.Model.Pcs_cerx_v01_r04_3.Pharmacy.Porx_mt980030ca;
using Ca.Infoway.Messagebuilder.Model.Pcs_cerx_v01_r04_3.Pharmacy.Porx_mt980040ca;
using System;
using System.Collections.Generic;
/**
* <summary>Business Name: Other Medication</summary>
*
* <p>routeCode must not be used when code is SNOMED and is
* mandatory otherwise</p> <p>Status can only be 'ACTIVE' or
* 'COMPLETE'</p> <p>Annotation is only permitted if Annotation
* Indicator is not present and vice versa</p> <p>Reported
* Issue is only permitted if Issue Indicator is not present
* and vice versa</p> <p>Necessary component of a person's
* overall medication profile. Allows DUR checking against a
* more complete drug profile.</p> <p>A record of a medication
* the patient is believed to be taking, but for which an
* electronic order does not exist. "Other active
* medications" include any drug product deemed relevant
* to the patient's drug profile, but which was not
* specifically ordered by a prescriber in a DIS-enabled
* jurisdiction. Examples include over-the counter medications
* that were not specifically ordered, herbal remedies, and
* recreational drugs. Prescription drugs that the patient may
* be taking but was not prescribed on the EHR (e.g.
* institutionally administered or out-of-jurisdiction
* prescriptions) will also be recorded here.</p>
*/
[Hl7PartTypeMappingAttribute(new string[] {"PORX_MT060210CA.OtherMedication"})]
public class OtherMedication : MessagePartBean {
private II id;
private CD code;
private CS statusCode;
private IVL<TS, Interval<PlatformDate>> effectiveTime;
private CV confidentialityCode;
private CV routeCode;
private Ca.Infoway.Messagebuilder.Model.Pcs_cerx_v01_r04_3.Common.Coct_mt050203ca.Patient subjectPatient;
private Ca.Infoway.Messagebuilder.Model.Pcs_cerx_v01_r04_3.Common.Coct_mt220110ca.DrugProduct consumableMedication;
private Ca.Infoway.Messagebuilder.Model.Pcs_cerx_v01_r04_3.Common.Coct_mt090107ca.Provider responsiblePartyAssignedPerson;
private Ca.Infoway.Messagebuilder.Model.Pcs_cerx_v01_r04_3.Merged.RefusedBy author;
private Ca.Infoway.Messagebuilder.Model.Pcs_cerx_v01_r04_3.Merged.RecordedAt location;
private IList<Ca.Infoway.Messagebuilder.Model.Pcs_cerx_v01_r04_3.Pharmacy.Porx_mt980040ca.AdministrationInstructions> componentDosageInstruction;
private IList<Ca.Infoway.Messagebuilder.Model.Pcs_cerx_v01_r04_3.Pharmacy.Merged.StatusChanges> subjectOf1ControlActEvent;
private BL subjectOf2DetectedIssueIndicator;
private IList<Ca.Infoway.Messagebuilder.Model.Pcs_cerx_v01_r04_3.Common.Coct_mt120600ca.Notes> subjectOf3Annotation;
private BL subjectOf4AnnotationIndicator;
private IList<Ca.Infoway.Messagebuilder.Model.Pcs_cerx_v01_r04_3.Pharmacy.Porx_mt980030ca.Issues> subjectOf5DetectedIssueEvent;
public OtherMedication() {
this.id = new IIImpl();
this.code = new CDImpl();
this.statusCode = new CSImpl();
this.effectiveTime = new IVLImpl<TS, Interval<PlatformDate>>();
this.confidentialityCode = new CVImpl();
this.routeCode = new CVImpl();
this.componentDosageInstruction = new List<Ca.Infoway.Messagebuilder.Model.Pcs_cerx_v01_r04_3.Pharmacy.Porx_mt980040ca.AdministrationInstructions>();
this.subjectOf1ControlActEvent = new List<Ca.Infoway.Messagebuilder.Model.Pcs_cerx_v01_r04_3.Pharmacy.Merged.StatusChanges>();
this.subjectOf2DetectedIssueIndicator = new BLImpl(false);
this.subjectOf3Annotation = new List<Ca.Infoway.Messagebuilder.Model.Pcs_cerx_v01_r04_3.Common.Coct_mt120600ca.Notes>();
this.subjectOf4AnnotationIndicator = new BLImpl(false);
this.subjectOf5DetectedIssueEvent = new List<Ca.Infoway.Messagebuilder.Model.Pcs_cerx_v01_r04_3.Pharmacy.Porx_mt980030ca.Issues>();
}
/**
* <summary>Business Name: A:Administration Record Id</summary>
*
* <remarks>Relationship: PORX_MT060210CA.OtherMedication.id
* Conformance/Cardinality: MANDATORY (1) <p>Allows for the
* unique referencing of a specific active medication record.
* Thus the mandatory requirement. .</p> <p>This is an
* identifier assigned to a unique instance of an active
* medication record.</p></remarks>
*/
[Hl7XmlMappingAttribute(new string[] {"id"})]
public Identifier Id {
get { return this.id.Value; }
set { this.id.Value = value; }
}
/**
* <summary>Business Name: Other Medication Type</summary>
*
* <remarks>Relationship: PORX_MT060210CA.OtherMedication.code
* Conformance/Cardinality: MANDATORY (1) <p>Must be 'DRUG'
* unless using SNOMED</p> <p>Needed to convey the meaning of
* this class and is therefore mandatory.</p><p>The element
* allows 'CD' to provide support for SNOMED.</p> <p>Indicates
* that the record is a drug administration rather than an
* immunization or other type of administration. For SNOMED,
* may also include route, drug and other information.</p></remarks>
*/
[Hl7XmlMappingAttribute(new string[] {"code"})]
public ActCode Code {
get { return (ActCode) this.code.Value; }
set { this.code.Value = value; }
}
/**
* <summary>Business Name: B:Other Medication Status</summary>
*
* <remarks>Relationship:
* PORX_MT060210CA.OtherMedication.statusCode
* Conformance/Cardinality: MANDATORY (1) <p>Used to determine
* whether the medication should be considered in performing
* DUR checking.</p><p>Attribute is mandatory to ensure that a
* medication recorded in EHR/DIS is in some state.</p><p>Note
* ------ The provider might know that the patient is not
* taking the medication but not necessarily when the patient
* stopped it. Thus the status of the medication could be set
* to 'completed' by the provider without necessarily setting
* an End Date on the medication record.</p> <p>Indicates the
* status of the other medication record created on the
* EHR/DIS. Valid statuses for other medication records are:
* 'active' and 'completed' only.</p></remarks>
*/
[Hl7XmlMappingAttribute(new string[] {"statusCode"})]
public ActStatus StatusCode {
get { return (ActStatus) this.statusCode.Value; }
set { this.statusCode.Value = value; }
}
/**
* <summary>Business Name: C:Drug Active Period</summary>
*
* <remarks>Relationship:
* PORX_MT060210CA.OtherMedication.effectiveTime
* Conformance/Cardinality: REQUIRED (1) <p>ZDP.13.2.2</p>
* <p>ZDP.13.3</p> <p>ZDP.13.4</p> <p>ZDP.13.5</p> <p>Used to
* help determine whether the medication is currently active.
* Because this information won't always be available, the
* attribute is marked as 'populated'.</p> <p>Indicates the
* time-period in which the patient has been taking or is
* expected to be taking the medication.</p></remarks>
*/
[Hl7XmlMappingAttribute(new string[] {"effectiveTime"})]
public Interval<PlatformDate> EffectiveTime {
get { return this.effectiveTime.Value; }
set { this.effectiveTime.Value = value; }
}
/**
* <summary>Business Name: D:Other Medication Masking Indicator</summary>
*
* <remarks>Relationship:
* PORX_MT060210CA.OtherMedication.confidentialityCode
* Conformance/Cardinality: OPTIONAL (0-1) <p>Provides support
* for additional confidentiality constraint to reflect the
* wishes of the patient.</p><p>The attribute is optional
* because not all systems will support masking.</p> <p>Denotes
* access restriction place on the other medication record.
* Methods for accessing masked other medications will be
* governed by each jurisdiction (e.g. court orders, shared
* secret/consent, etc.).</p></remarks>
*/
[Hl7XmlMappingAttribute(new string[] {"confidentialityCode"})]
public x_VeryBasicConfidentialityKind ConfidentialityCode {
get { return (x_VeryBasicConfidentialityKind) this.confidentialityCode.Value; }
set { this.confidentialityCode.Value = value; }
}
/**
* <summary>Business Name: E:Route of Administration</summary>
*
* <remarks>Relationship:
* PORX_MT060210CA.OtherMedication.routeCode
* Conformance/Cardinality: OPTIONAL (0-1) <p>RXR.1</p>
* <p>Route of administration</p> <p>Ensures consistency in
* description of routes. Provides potential for cross-checking
* dosage form and route. Because this information is
* pre-coordinated into 'code' for SNOMED, it is marked as
* optional.</p> <p>This is the means by which the patient is
* taking the medication.</p></remarks>
*/
[Hl7XmlMappingAttribute(new string[] {"routeCode"})]
public RouteOfAdministration RouteCode {
get { return (RouteOfAdministration) this.routeCode.Value; }
set { this.routeCode.Value = value; }
}
/**
* <summary>Relationship: PORX_MT060210CA.Subject10.patient</summary>
*
* <remarks>Conformance/Cardinality: MANDATORY (1)</remarks>
*/
[Hl7XmlMappingAttribute(new string[] {"subject/patient"})]
public Ca.Infoway.Messagebuilder.Model.Pcs_cerx_v01_r04_3.Common.Coct_mt050203ca.Patient SubjectPatient {
get { return this.subjectPatient; }
set { this.subjectPatient = value; }
}
/**
* <summary>Relationship:
* PORX_MT060210CA.Consumable2.medication</summary>
*
* <remarks>Conformance/Cardinality: MANDATORY (1)</remarks>
*/
[Hl7XmlMappingAttribute(new string[] {"consumable/medication"})]
public Ca.Infoway.Messagebuilder.Model.Pcs_cerx_v01_r04_3.Common.Coct_mt220110ca.DrugProduct ConsumableMedication {
get { return this.consumableMedication; }
set { this.consumableMedication = value; }
}
/**
* <summary>Relationship:
* PORX_MT060210CA.ResponsibleParty.assignedPerson</summary>
*
* <remarks>Conformance/Cardinality: REQUIRED (1)</remarks>
*/
[Hl7XmlMappingAttribute(new string[] {"responsibleParty/assignedPerson"})]
public Ca.Infoway.Messagebuilder.Model.Pcs_cerx_v01_r04_3.Common.Coct_mt090107ca.Provider ResponsiblePartyAssignedPerson {
get { return this.responsiblePartyAssignedPerson; }
set { this.responsiblePartyAssignedPerson = value; }
}
/**
* <summary>Relationship:
* PORX_MT060210CA.OtherMedication.author</summary>
*
* <remarks>Conformance/Cardinality: MANDATORY (1)</remarks>
*/
[Hl7XmlMappingAttribute(new string[] {"author"})]
public Ca.Infoway.Messagebuilder.Model.Pcs_cerx_v01_r04_3.Merged.RefusedBy Author {
get { return this.author; }
set { this.author = value; }
}
/**
* <summary>Relationship:
* PORX_MT060210CA.OtherMedication.location</summary>
*
* <remarks>Conformance/Cardinality: MANDATORY (1)</remarks>
*/
[Hl7XmlMappingAttribute(new string[] {"location"})]
public Ca.Infoway.Messagebuilder.Model.Pcs_cerx_v01_r04_3.Merged.RecordedAt Location {
get { return this.location; }
set { this.location = value; }
}
/**
* <summary>Relationship:
* PORX_MT060210CA.Component.dosageInstruction</summary>
*
* <remarks>Conformance/Cardinality: REQUIRED (1)</remarks>
*/
[Hl7XmlMappingAttribute(new string[] {"component/dosageInstruction"})]
public IList<Ca.Infoway.Messagebuilder.Model.Pcs_cerx_v01_r04_3.Pharmacy.Porx_mt980040ca.AdministrationInstructions> ComponentDosageInstruction {
get { return this.componentDosageInstruction; }
}
/**
* <summary>Relationship:
* PORX_MT060210CA.Subject11.controlActEvent</summary>
*
* <remarks>Conformance/Cardinality: REQUIRED (1)</remarks>
*/
[Hl7XmlMappingAttribute(new string[] {"subjectOf1/controlActEvent"})]
public IList<Ca.Infoway.Messagebuilder.Model.Pcs_cerx_v01_r04_3.Pharmacy.Merged.StatusChanges> SubjectOf1ControlActEvent {
get { return this.subjectOf1ControlActEvent; }
}
/**
* <summary>Relationship:
* PORX_MT060210CA.Subject9.detectedIssueIndicator</summary>
*
* <remarks>Conformance/Cardinality: REQUIRED (1)</remarks>
*/
[Hl7XmlMappingAttribute(new string[] {"subjectOf2/detectedIssueIndicator"})]
public bool? SubjectOf2DetectedIssueIndicator {
get { return this.subjectOf2DetectedIssueIndicator.Value; }
set { this.subjectOf2DetectedIssueIndicator.Value = value; }
}
/**
* <summary>Relationship: PORX_MT060210CA.Subject14.annotation</summary>
*
* <remarks>Conformance/Cardinality: REQUIRED (1)</remarks>
*/
[Hl7XmlMappingAttribute(new string[] {"subjectOf3/annotation"})]
public IList<Ca.Infoway.Messagebuilder.Model.Pcs_cerx_v01_r04_3.Common.Coct_mt120600ca.Notes> SubjectOf3Annotation {
get { return this.subjectOf3Annotation; }
}
/**
* <summary>Relationship:
* PORX_MT060210CA.Subject15.annotationIndicator</summary>
*
* <remarks>Conformance/Cardinality: REQUIRED (1)</remarks>
*/
[Hl7XmlMappingAttribute(new string[] {"subjectOf4/annotationIndicator"})]
public bool? SubjectOf4AnnotationIndicator {
get { return this.subjectOf4AnnotationIndicator.Value; }
set { this.subjectOf4AnnotationIndicator.Value = value; }
}
/**
* <summary>Relationship:
* PORX_MT060210CA.Subject.detectedIssueEvent</summary>
*
* <remarks>Conformance/Cardinality: REQUIRED (1)</remarks>
*/
[Hl7XmlMappingAttribute(new string[] {"subjectOf5/detectedIssueEvent"})]
public IList<Ca.Infoway.Messagebuilder.Model.Pcs_cerx_v01_r04_3.Pharmacy.Porx_mt980030ca.Issues> SubjectOf5DetectedIssueEvent {
get { return this.subjectOf5DetectedIssueEvent; }
}
}
} | 50.377193 | 162 | 0.653607 | [
"ECL-2.0",
"Apache-2.0"
] | CanadaHealthInfoway/message-builder-dotnet | message-builder-release-v01_r04_3/Main/Ca/Infoway/Messagebuilder/Model/Pcs_cerx_v01_r04_3/Pharmacy/Porx_mt060210ca/OtherMedication.cs | 17,229 | 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.Runtime.InteropServices;
using System;
internal class NullableTest
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((WithOnlyFXTypeStruct?)o) == null;
}
private static int Main()
{
WithOnlyFXTypeStruct? s = null;
if (BoxUnboxToNQ(s) && BoxUnboxToQ(s) && BoxUnboxToNQGen(s) && BoxUnboxToQGen(s))
return ExitCode.Passed;
else
return ExitCode.Failed;
}
}
| 22.125 | 89 | 0.614689 | [
"MIT"
] | belav/runtime | src/tests/JIT/jit64/valuetypes/nullable/box-unbox/null/box-unbox-null044.cs | 885 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// <auto-generated/>
// Template Source: Templates\CSharp\Requests\EntityCollectionRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The type OnPremisesPublishingProfileAgentsCollectionRequest.
/// </summary>
public partial class OnPremisesPublishingProfileAgentsCollectionRequest : BaseRequest, IOnPremisesPublishingProfileAgentsCollectionRequest
{
/// <summary>
/// Constructs a new OnPremisesPublishingProfileAgentsCollectionRequest.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="options">Query and header option name value pairs for the request.</param>
public OnPremisesPublishingProfileAgentsCollectionRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Adds the specified OnPremisesAgent to the collection via POST.
/// </summary>
/// <param name="onPremisesAgent">The OnPremisesAgent to add.</param>
/// <returns>The created OnPremisesAgent.</returns>
public System.Threading.Tasks.Task<OnPremisesAgent> AddAsync(OnPremisesAgent onPremisesAgent)
{
return this.AddAsync(onPremisesAgent, CancellationToken.None);
}
/// <summary>
/// Adds the specified OnPremisesAgent to the collection via POST.
/// </summary>
/// <param name="onPremisesAgent">The OnPremisesAgent to add.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created OnPremisesAgent.</returns>
public System.Threading.Tasks.Task<OnPremisesAgent> AddAsync(OnPremisesAgent onPremisesAgent, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "POST";
return this.SendAsync<OnPremisesAgent>(onPremisesAgent, cancellationToken);
}
/// <summary>
/// Gets the collection page.
/// </summary>
/// <returns>The collection page.</returns>
public System.Threading.Tasks.Task<IOnPremisesPublishingProfileAgentsCollectionPage> GetAsync()
{
return this.GetAsync(CancellationToken.None);
}
/// <summary>
/// Gets the collection page.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The collection page.</returns>
public async System.Threading.Tasks.Task<IOnPremisesPublishingProfileAgentsCollectionPage> GetAsync(CancellationToken cancellationToken)
{
this.Method = "GET";
var response = await this.SendAsync<OnPremisesPublishingProfileAgentsCollectionResponse>(null, cancellationToken).ConfigureAwait(false);
if (response != null && response.Value != null && response.Value.CurrentPage != null)
{
if (response.AdditionalData != null)
{
object nextPageLink;
response.AdditionalData.TryGetValue("@odata.nextLink", out nextPageLink);
var nextPageLinkString = nextPageLink as string;
if (!string.IsNullOrEmpty(nextPageLinkString))
{
response.Value.InitializeNextPageRequest(
this.Client,
nextPageLinkString);
}
// Copy the additional data collection to the page itself so that information is not lost
response.Value.AdditionalData = response.AdditionalData;
}
return response.Value;
}
return null;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public IOnPremisesPublishingProfileAgentsCollectionRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
public IOnPremisesPublishingProfileAgentsCollectionRequest Expand(Expression<Func<OnPremisesAgent, object>> expandExpression)
{
if (expandExpression == null)
{
throw new ArgumentNullException(nameof(expandExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(expandExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$expand", value));
}
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IOnPremisesPublishingProfileAgentsCollectionRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
public IOnPremisesPublishingProfileAgentsCollectionRequest Select(Expression<Func<OnPremisesAgent, object>> selectExpression)
{
if (selectExpression == null)
{
throw new ArgumentNullException(nameof(selectExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(selectExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$select", value));
}
return this;
}
/// <summary>
/// Adds the specified top value to the request.
/// </summary>
/// <param name="value">The top value.</param>
/// <returns>The request object to send.</returns>
public IOnPremisesPublishingProfileAgentsCollectionRequest Top(int value)
{
this.QueryOptions.Add(new QueryOption("$top", value.ToString()));
return this;
}
/// <summary>
/// Adds the specified filter value to the request.
/// </summary>
/// <param name="value">The filter value.</param>
/// <returns>The request object to send.</returns>
public IOnPremisesPublishingProfileAgentsCollectionRequest Filter(string value)
{
this.QueryOptions.Add(new QueryOption("$filter", value));
return this;
}
/// <summary>
/// Adds the specified skip value to the request.
/// </summary>
/// <param name="value">The skip value.</param>
/// <returns>The request object to send.</returns>
public IOnPremisesPublishingProfileAgentsCollectionRequest Skip(int value)
{
this.QueryOptions.Add(new QueryOption("$skip", value.ToString()));
return this;
}
/// <summary>
/// Adds the specified orderby value to the request.
/// </summary>
/// <param name="value">The orderby value.</param>
/// <returns>The request object to send.</returns>
public IOnPremisesPublishingProfileAgentsCollectionRequest OrderBy(string value)
{
this.QueryOptions.Add(new QueryOption("$orderby", value));
return this;
}
}
}
| 41.497717 | 153 | 0.59276 | [
"MIT"
] | OfficeGlobal/msgraph-beta-sdk-dotnet | src/Microsoft.Graph/Requests/Generated/OnPremisesPublishingProfileAgentsCollectionRequest.cs | 9,088 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNextGen.Cdn.V20191231.Outputs
{
[OutputType]
public sealed class DeliveryRuleRequestUriConditionResponse
{
/// <summary>
/// The name of the condition for the delivery rule.
/// </summary>
public readonly string Name;
/// <summary>
/// Defines the parameters for the condition.
/// </summary>
public readonly Outputs.RequestUriMatchConditionParametersResponse Parameters;
[OutputConstructor]
private DeliveryRuleRequestUriConditionResponse(
string name,
Outputs.RequestUriMatchConditionParametersResponse parameters)
{
Name = name;
Parameters = parameters;
}
}
}
| 29.083333 | 86 | 0.664756 | [
"Apache-2.0"
] | test-wiz-sec/pulumi-azure-nextgen | sdk/dotnet/Cdn/V20191231/Outputs/DeliveryRuleRequestUriConditionResponse.cs | 1,047 | C# |
using System;
namespace Gw2Sharp.WebApi.V2.Models
{
/// <summary>
/// Represents a guild team game.
/// </summary>
public class GuildTeamGame
{
//TODO: Check if all properties are actually correct.
/// <summary>
/// The game id.
/// </summary>
public Guid Id { get; set; }
/// <summary>
/// The map id.
/// Can be resolved against <see cref="IGw2WebApiV2Client.Maps"/>.
/// </summary>
public int MapId { get; set; }
/// <summary>
/// The start time.
/// </summary>
public DateTimeOffset Started { get; set; }
/// <summary>
/// The end time.
/// </summary>
public DateTimeOffset Ended { get; set; }
/// <summary>
/// The result.
/// </summary>
public ApiEnum<PvpResult> Result { get; set; } = new ApiEnum<PvpResult>();
/// <summary>
/// The team.
/// </summary>
public ApiEnum<PvpTeam> Team { get; set; } = new ApiEnum<PvpTeam>();
/// <summary>
/// The team scores.
/// </summary>
public PvpTeamScores Scores { get; set; } = new PvpTeamScores();
/// <summary>
/// The rating type.
/// </summary>
public ApiEnum<PvpRatingType> RatingType { get; set; } = new ApiEnum<PvpRatingType>();
}
}
| 25.759259 | 94 | 0.504673 | [
"MIT"
] | Archomeda/Gw2Sharp | Gw2Sharp/WebApi/V2/Models/Guild/GuildTeamGame.cs | 1,391 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Charlotte.Utils
{
public class CrashUtils
{
public static bool IsCrashed_Range_Range(double l1, double r1, double l2, double r2)
{
if (r1 < l1) throw null; // test
if (r2 < l2) throw null; // test
return l1 < r2 && l2 < r1;
}
public static bool IsCrashed_Rect_Rect(
double l1, double t1, double r1, double b1,
double l2, double t2, double r2, double b2
)
{
return
IsCrashed_Range_Range(l1, r1, l2, r2) &&
IsCrashed_Range_Range(t1, b1, t2, b2);
}
public static bool IsCrashed_Rect_Line(
double l, double t, double r, double b,
double x1, double y1,
double x2, double y2
)
{
// HACK: 雑な判定
return IsCrashed_Rect_Rect(
l, t, r, b,
Math.Min(x1, x2),
Math.Min(y1, y2),
Math.Max(x1, x2),
Math.Max(y1, y2)
);
}
public static bool IsCrashed_Range_Point(double l, double r, double p)
{
if (r < l) throw null; // test
return l < p && p < r;
}
public static bool IsCrashed_Rect_Point(
double l, double t, double r, double b,
double x, double y
)
{
return
IsCrashed_Range_Point(l, r, x) &&
IsCrashed_Range_Point(t, b, y);
}
public static double GetDistance(MapPoint a, MapPoint b)
{
return GetDistance(a.X, a.Y, b.X, b.Y);
}
public static double GetDistance(double x1, double y1, double x2, double y2)
{
return GetDistance(x1 - x2, y1 - y2);
}
public static double GetDistance(double x, double y)
{
return Math.Sqrt(x * x + y * y);
}
}
}
| 20.636364 | 86 | 0.63562 | [
"MIT"
] | stackprobe/Annex | Bodewig/GeoDemo/Server/Server/Utils/CrashUtils.cs | 1,599 | C# |
using System.Collections.Generic;
using System.Threading.Tasks;
using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Rollvolet.CRM.API.Builders.Interfaces;
using Rollvolet.CRM.API.Collectors;
using Rollvolet.CRM.APIContracts.DTO;
using Rollvolet.CRM.APIContracts.DTO.Buildings;
using Rollvolet.CRM.APIContracts.DTO.Invoices;
using Rollvolet.CRM.APIContracts.DTO.Requests;
using Rollvolet.CRM.APIContracts.DTO.Telephones;
using Rollvolet.CRM.APIContracts.JsonApi;
using Rollvolet.CRM.Domain.Exceptions;
using Rollvolet.CRM.Domain.Managers.Interfaces;
using Rollvolet.CRM.Domain.Models;
namespace Rollvolet.CRM.API.Controllers
{
[ApiController]
[Route("[controller]")]
public class BuildingsController : ControllerBase
{
private readonly IBuildingManager _buildingManager;
private readonly ITelephoneManager _telephoneManager;
private readonly ICountryManager _countryManager;
private readonly ILanguageManager _languageManager;
private readonly IHonorificPrefixManager _honorificPrefixManager;
private readonly IRequestManager _requestManager;
private readonly IInvoiceManager _invoiceManager;
private readonly IIncludedCollector _includedCollector;
private readonly IMapper _mapper;
private readonly IJsonApiBuilder _jsonApiBuilder;
public BuildingsController(IBuildingManager buildingManager, ITelephoneManager telephoneManager, ICountryManager countryManager,
ILanguageManager languageManager, IHonorificPrefixManager honorificPrefixManager,
IRequestManager requestManager, IInvoiceManager invoiceManager,
IIncludedCollector includedCollector, IMapper mapper, IJsonApiBuilder jsonApiBuilder)
{
_buildingManager = buildingManager;
_telephoneManager = telephoneManager;
_countryManager = countryManager;
_languageManager = languageManager;
_honorificPrefixManager = honorificPrefixManager;
_requestManager = requestManager;
_invoiceManager = invoiceManager;
_includedCollector = includedCollector;
_mapper = mapper;
_jsonApiBuilder = jsonApiBuilder;
}
[HttpGet]
public async Task<IActionResult> GetAllAsync()
{
var querySet = _jsonApiBuilder.BuildQuerySet(HttpContext.Request.Query);
var pagedBuildings = await _buildingManager.GetAllAsync(querySet);
var buildingDtos = _mapper.Map<IEnumerable<BuildingDto>>(pagedBuildings.Items, opt => opt.Items["include"] = querySet.Include);
var included = _includedCollector.CollectIncluded(pagedBuildings.Items, querySet.Include);
var links = _jsonApiBuilder.BuildCollectionLinks(HttpContext.Request.Path, querySet, pagedBuildings);
var meta = _jsonApiBuilder.BuildCollectionMetadata(pagedBuildings);
return Ok(new ResourceResponse() { Meta = meta, Links = links, Data = buildingDtos, Included = included });
}
[HttpGet("{id}")]
public async Task<IActionResult> GetByIdAsync(int id)
{
var querySet = _jsonApiBuilder.BuildQuerySet(HttpContext.Request.Query);
var building = await _buildingManager.GetByIdAsync(id, querySet);
var buildingDto = _mapper.Map<BuildingDto>(building, opt => opt.Items["include"] = querySet.Include);
var included = _includedCollector.CollectIncluded(building, querySet.Include);
var links = _jsonApiBuilder.BuildSingleResourceLinks(HttpContext.Request.Path, querySet);
return Ok(new ResourceResponse() { Links = links, Data = buildingDto, Included = included });
}
[HttpPost]
public async Task<IActionResult> CreateAsync([FromBody] ResourceRequest<BuildingRequestDto> resource)
{
if (resource.Data.Type != "buildings") return StatusCode(409);
var building = _mapper.Map<Building>(resource.Data);
building = await _buildingManager.CreateAsync(building);
var buildingDto = _mapper.Map<BuildingDto>(building);
var links = _jsonApiBuilder.BuildNewSingleResourceLinks(HttpContext.Request.Path, buildingDto.Id);
return Created(links.Self, new ResourceResponse() { Links = links, Data = buildingDto });
}
[HttpPatch("{id}")]
public async Task<IActionResult> UpdateAsync(string id, [FromBody] ResourceRequest<BuildingRequestDto> resource)
{
if (resource.Data.Type != "buildings" || resource.Data.Id != id) return StatusCode(409);
var building = _mapper.Map<Building>(resource.Data);
building = await _buildingManager.UpdateAsync(building);
var buildingDto = _mapper.Map<BuildingDto>(building);
var links = _jsonApiBuilder.BuildSingleResourceLinks(HttpContext.Request.Path);
return Ok(new ResourceResponse() { Links = links, Data = buildingDto });
}
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteAsync(int id)
{
await _buildingManager.DeleteAsync(id);
return NoContent();
}
[HttpGet("{buildingId}/requests")]
[HttpGet("{buildingId}/links/requests")]
public async Task<IActionResult> GetRelatedRequestsByIdAsync(int buildingId)
{
var querySet = _jsonApiBuilder.BuildQuerySet(HttpContext.Request.Query);
var pagedRequests = await _requestManager.GetAllByBuildingIdAsync(buildingId, querySet);
var requestDtos = _mapper.Map<IEnumerable<RequestDto>>(pagedRequests.Items, opt => opt.Items["include"] = querySet.Include);
var included = _includedCollector.CollectIncluded(pagedRequests.Items, querySet.Include);
var links = _jsonApiBuilder.BuildCollectionLinks(HttpContext.Request.Path, querySet, pagedRequests);
var meta = _jsonApiBuilder.BuildCollectionMetadata(pagedRequests);
return Ok(new ResourceResponse() { Meta = meta, Links = links, Data = requestDtos, Included = included });
}
[HttpGet("{buildingId}/invoices")]
[HttpGet("{buildingId}/links/invoices")]
public async Task<IActionResult> GetRelatedInvoicesByIdAsync(int buildingId)
{
var querySet = _jsonApiBuilder.BuildQuerySet(HttpContext.Request.Query);
var pagedInvoices = await _invoiceManager.GetAllByBuildingIdAsync(buildingId, querySet);
var invoiceDtos = _mapper.Map<IEnumerable<InvoiceDto>>(pagedInvoices.Items, opt => opt.Items["include"] = querySet.Include);
var included = _includedCollector.CollectIncluded(pagedInvoices.Items, querySet.Include);
var links = _jsonApiBuilder.BuildCollectionLinks(HttpContext.Request.Path, querySet, pagedInvoices);
var meta = _jsonApiBuilder.BuildCollectionMetadata(pagedInvoices);
return Ok(new ResourceResponse() { Meta = meta, Links = links, Data = invoiceDtos, Included = included });
}
[HttpGet("{buildingId}/telephones")]
[HttpGet("{buildingId}/links/telephones")]
public async Task<IActionResult> GetRelatedTelephonesByIdAsync(int buildingId)
{
var querySet = _jsonApiBuilder.BuildQuerySet(HttpContext.Request.Query);
querySet.Include.Fields = new string[] {"country", "telephone-type"};
var pagedTelephones = await _telephoneManager.GetAllByBuildingIdAsync(buildingId, querySet);
var telephoneDtos = _mapper.Map<IEnumerable<TelephoneDto>>(pagedTelephones.Items, opt => opt.Items["include"] = querySet.Include);
var included = _includedCollector.CollectIncluded(pagedTelephones.Items, querySet.Include);
var links = _jsonApiBuilder.BuildCollectionLinks(HttpContext.Request.Path, querySet, pagedTelephones);
var meta = _jsonApiBuilder.BuildCollectionMetadata(pagedTelephones);
return Ok(new ResourceResponse() { Meta = meta, Links = links, Data = telephoneDtos, Included = included });
}
[HttpGet("{buildingId}/country")]
[HttpGet("{buildingId}/links/country")]
public async Task<IActionResult> GetRelatedCountryByIdAsync(int buildingId)
{
CountryDto countryDto;
try
{
var country = await _countryManager.GetByBuildingIdAsync(buildingId);
countryDto = _mapper.Map<CountryDto>(country);
}
catch (EntityNotFoundException)
{
countryDto = null;
}
var links = _jsonApiBuilder.BuildSingleResourceLinks(HttpContext.Request.Path);
return Ok(new ResourceResponse() { Links = links, Data = countryDto });
}
[HttpGet("{buildingId}/language")]
[HttpGet("{buildingId}/links/language")]
public async Task<IActionResult> GetRelatedLanguageByIdAsync(int buildingId)
{
LanguageDto languageDto;
try
{
var language = await _languageManager.GetByBuildingIdAsync(buildingId);
languageDto = _mapper.Map<LanguageDto>(language);
}
catch (EntityNotFoundException)
{
languageDto = null;
}
var links = _jsonApiBuilder.BuildSingleResourceLinks(HttpContext.Request.Path);
return Ok(new ResourceResponse() { Links = links, Data = languageDto });
}
[HttpGet("{buildingId}/honorific-prefix")]
[HttpGet("{buildingId}/links/honorific-prefix")]
public async Task<IActionResult> GetRelatedHonorificPrefixByIdAsync(int buildingId)
{
HonorificPrefixDto honorificPrefixDto;
try
{
var honorificPrefix = await _honorificPrefixManager.GetByBuildingIdAsync(buildingId);
honorificPrefixDto = _mapper.Map<HonorificPrefixDto>(honorificPrefix);
}
catch (EntityNotFoundException)
{
honorificPrefixDto = null;
}
var links = _jsonApiBuilder.BuildSingleResourceLinks(HttpContext.Request.Path);
return Ok(new ResourceResponse() { Links = links, Data = honorificPrefixDto });
}
}
} | 46.657778 | 142 | 0.673176 | [
"MIT"
] | rollvolet/crm-ap | src/Rollvolet.CRM.API/Controllers/BuildingsController.cs | 10,498 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BESSy.Json.Tests.Documentation.Samples.Serializer
{
public class PopulateObject
{
#region Types
public class Account
{
public string Email { get; set; }
public bool Active { get; set; }
public DateTime CreatedDate { get; set; }
public IList<string> Roles { get; set; }
}
#endregion
public void Example()
{
#region Usage
Account account = new Account
{
Email = "james@example.com",
Active = true,
CreatedDate = new DateTime(2013, 1, 20, 0, 0, 0, DateTimeKind.Utc),
Roles = new List<string>
{
"User",
"Admin"
}
};
string json = @"{
'Active': false,
'Roles': [
'Expired'
]
}";
JsonConvert.PopulateObject(json, account);
Console.WriteLine(account.Email);
// james@example.com
Console.WriteLine(account.Active);
// false
Console.WriteLine(string.Join(", ", account.Roles));
// User, Admin, Expired
#endregion
}
}
} | 25.436364 | 83 | 0.468192 | [
"MIT"
] | thehexgod/BESSy.JSON | Src/BESSy.Json.Tests/Documentation/Samples/Serializer/PopulateObject.cs | 1,401 | C# |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Diagnostics.ContractsLight;
using BuildXL.Utilities;
namespace BuildXL.Pips.DirectedGraph
{
/// <summary>
/// Inclusive range of <see cref="NodeId"/>s.
/// </summary>
public readonly struct NodeRange : IEquatable<NodeRange>
{
/// <summary>
/// First node in the range. Set to <see cref="NodeId.Invalid"/> if this range is empty.
/// </summary>
public readonly NodeId FromInclusive;
/// <summary>
/// Last node in the range. Set to <see cref="NodeId.Invalid"/> if this range is empty.
/// </summary>
public readonly NodeId ToInclusive;
/// <summary>
/// Creates a non-empty node range.
/// </summary>
public NodeRange(NodeId fromInclusive, NodeId toInclusive)
{
Contract.Requires(fromInclusive.IsValid && toInclusive.IsValid);
Contract.Requires(fromInclusive.Value <= toInclusive.Value);
FromInclusive = fromInclusive;
ToInclusive = toInclusive;
}
/// <summary>
/// Creates a range normally if <paramref name="fromInclusive"/> and <paramref name="toInclusive"/> form a nonempty range.
/// If instead the range is non-representable ('from' greater than 'to'), an empty range is returned instead.
/// </summary>
public static NodeRange CreatePossiblyEmpty(NodeId fromInclusive, NodeId toInclusive)
{
Contract.Requires(fromInclusive.IsValid && toInclusive.IsValid);
return fromInclusive.Value <= toInclusive.Value ? new NodeRange(fromInclusive, toInclusive) : Empty;
}
/// <summary>
/// Creates a range which includes all possible nodes with a value at least as large as <paramref name="lowerBound"/>.
/// </summary>
public static NodeRange CreateLowerBound(NodeId lowerBound)
{
Contract.Requires(lowerBound.IsValid);
return new NodeRange(lowerBound, NodeId.Max);
}
/// <summary>
/// Creates a range which includes all possible nodes with a value no larger than <paramref name="upperBound"/>.
/// </summary>
public static NodeRange CreateUpperBound(NodeId upperBound)
{
Contract.Requires(upperBound.IsValid);
return new NodeRange(NodeId.Min, upperBound);
}
/// <summary>
/// Indicates if this range contains the specified node.
/// </summary>
public bool Contains(NodeId node)
{
Contract.Requires(node.IsValid);
return node.Value <= ToInclusive.Value && node.Value >= FromInclusive.Value;
}
/// <summary>
/// Empty range.
/// </summary>
public static NodeRange Empty => default(NodeRange);
/// <summary>
/// Indicates if this range is equivalent <see cref="Empty"/>.
/// </summary>
public bool IsEmpty => !FromInclusive.IsValid;
/// <summary>
/// Number of nodes represented by this range.
/// </summary>
public int Size => IsEmpty ? 0 : (int)(ToInclusive.Value - FromInclusive.Value + 1);
/// <inheritdoc />
public bool Equals(NodeRange other)
{
return ToInclusive == other.ToInclusive && FromInclusive == other.FromInclusive;
}
/// <inheritdoc />
public override bool Equals(object obj)
{
return StructUtilities.Equals(this, obj);
}
/// <inheritdoc />
public override int GetHashCode()
{
return HashCodeHelper.Combine(FromInclusive.GetHashCode(), ToInclusive.GetHashCode());
}
/// <nodoc />
public static bool operator ==(NodeRange left, NodeRange right)
{
return left.Equals(right);
}
/// <nodoc />
public static bool operator !=(NodeRange left, NodeRange right)
{
return !left.Equals(right);
}
}
}
| 34.201613 | 131 | 0.575336 | [
"MIT"
] | BearerPipelineTest/BuildXL | Public/Src/Pips/Dll/DirectedGraph/NodeRange.cs | 4,243 | C# |
////////////////////////////////////////////////////////////////////////////////
//NUnit tests for "EF Core Provider for LCPI OLE DB"
// IBProvider and Contributors. 22.11.2020.
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using NUnit.Framework;
using xdb=lcpi.data.oledb;
namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D1.Query.Operators.SET_001.LeftShift.Complete.Int32.NullableInt16{
////////////////////////////////////////////////////////////////////////////////
using T_DATA1=System.Int32;
using T_DATA2=System.Nullable<System.Int16>;
////////////////////////////////////////////////////////////////////////////////
//class TestSet_P01__param_field
public static class TestSet_P01__param_field
{
private const string c_NameOf__TABLE ="TEST_MODIFY_ROW2";
private const string c_NameOf__COL_DATA1 ="COL_INTEGER";
private const string c_NameOf__COL_DATA2 ="COL2_SMALLINT";
private sealed class MyContext:TestBaseDbContext
{
[Table(c_NameOf__TABLE)]
public sealed class TEST_RECORD
{
[Key]
[Column("TEST_ID")]
public System.Int64? TEST_ID { get; set; }
[Column(c_NameOf__COL_DATA1)]
public T_DATA1 COL_DATA1 { get; set; }
[Column(c_NameOf__COL_DATA2)]
public T_DATA2 COL_DATA2 { get; set; }
};//class TEST_RECORD
//----------------------------------------------------------------------
public DbSet<TEST_RECORD> testTable { get; set; }
//----------------------------------------------------------------------
public MyContext(xdb.OleDbTransaction tr)
:base(tr)
{
}//MyContext
};//class MyContext
//-----------------------------------------------------------------------
[Test]
public static void Test_001__value__value()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
const T_DATA1 c_value1=7;
T_DATA2 c_value2=4;
System.Int64? testID=Helper__InsertRow(db,c_value1,c_value2);
Assert.AreEqual
(112,
c_value1<<c_value2);
var vv1=c_value1;
var recs=db.testTable.Where(r => (vv1<<r.COL_DATA2)==112 && r.TEST_ID==testID);
int nRecs=0;
foreach(var r in recs)
{
Assert.AreEqual
(0,
nRecs);
++nRecs;
Assert.IsTrue
(r.TEST_ID.HasValue);
Assert.AreEqual
(testID,
r.TEST_ID.Value);
Assert.AreEqual
(c_value1,
r.COL_DATA1);
Assert.AreEqual
(c_value2,
r.COL_DATA2);
}//foreach r
var sqlt
=new TestSqlTemplate()
.T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_DATA1).T(", ").N("t",c_NameOf__COL_DATA2).EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL()
.T("WHERE (BIN_SHL(").P_I4("__vv1_0").T(", ").N("t",c_NameOf__COL_DATA2).T(") = 112) AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_1").T(")");
db.CheckTextOfLastExecutedCommand
(sqlt);
Assert.AreEqual
(1,
nRecs);
}//using db
tr.Rollback();
}//using tr
}//using cn
}//Test_001
//Helper methods --------------------------------------------------------
private static System.Int64 Helper__InsertRow(MyContext db,
T_DATA1 valueForColData1,
T_DATA2 valueForColData2)
{
var newRecord=new MyContext.TEST_RECORD();
newRecord.COL_DATA1 =valueForColData1;
newRecord.COL_DATA2 =valueForColData2;
db.testTable.Add(newRecord);
db.SaveChanges();
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("INSERT INTO ").N(c_NameOf__TABLE).T(" (").N(c_NameOf__COL_DATA1).T(", ").N(c_NameOf__COL_DATA2).T(")").EOL()
.T("VALUES (").P("p0").T(", ").P("p1").T(")").EOL()
.T("RETURNING ").N("TEST_ID").EOL()
.T("INTO ").P("p2").T(";"));
Assert.IsTrue
(newRecord.TEST_ID.HasValue);
Console.WriteLine("TEST_ID: {0}",newRecord.TEST_ID.Value);
return newRecord.TEST_ID.Value;
}//Helper__InsertRow
};//class TestSet_P01__param_field
////////////////////////////////////////////////////////////////////////////////
}//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D1.Query.Operators.SET_001.LeftShift.Complete.Int32.NullableInt16
| 28.847134 | 152 | 0.56083 | [
"MIT"
] | ibprovider/Lcpi.EFCore.LcpiOleDb | Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D1/Query/Operators/SET_001/LeftShift/Complete/Int32/NullableInt16/TestSet_P01__param_field.cs | 4,531 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SharpDX;
using System.IO;
using System.Xml;
using TC = System.ComponentModel.TypeConverterAttribute;
using EXP = System.ComponentModel.ExpandableObjectConverter;
namespace RageKit.GameFiles
{
[TC(typeof(EXP))] public class CarColsFile : GameFile, PackedFile
{
public PsoFile Pso { get; set; }
public string Xml { get; set; }
public CVehicleModelInfoVarGlobal VehicleModelInfo { get; set; }
public CarColsFile() : base(null, GameFileType.CarCols)
{ }
public CarColsFile(RpfFileEntry entry) : base(entry, GameFileType.CarCols)
{
}
public void Load(byte[] data, RpfFileEntry entry)
{
RpfFileEntry = entry;
Name = entry.Name;
FilePath = Name;
//can be PSO .ymt or XML .meta
MemoryStream ms = new MemoryStream(data);
if (PsoFile.IsPSO(ms))
{
Pso = new PsoFile();
Pso.Load(data);
Xml = PsoXml.GetXml(Pso); //yep let's just convert that to XML :P
}
else
{
Xml = TextUtil.GetUTF8Text(data);
}
XmlDocument xdoc = new XmlDocument();
if (!string.IsNullOrEmpty(Xml))
{
try
{
xdoc.LoadXml(Xml);
}
catch (Exception ex)
{
var msg = ex.Message;
}
}
else
{ }
if (xdoc.DocumentElement != null)
{
VehicleModelInfo = new CVehicleModelInfoVarGlobal(xdoc.DocumentElement);
}
Loaded = true;
}
}
[TC(typeof(EXP))] public class CVehicleModelInfoVarGlobal
{
public CVehicleModelInfoVarGlobal_465922034 VehiclePlates { get; set; }
public CVehicleModelColor[] Colors { get; set; }
public CVehicleMetallicSetting[] MetallicSettings { get; set; }
public CVehicleWindowColor[] WindowColors { get; set; }
public vehicleLightSettings[] Lights { get; set; }
public sirenSettings[] Sirens { get; set; }
public CVehicleKit[] Kits { get; set; }
public CVehicleWheel[][] Wheels { get; set; }
public CVehicleModelInfoVarGlobal_3062246906 GlobalVariationData { get; set; }
public CVehicleXenonLightColor[] XenonLightColors { get; set; }
public CVehicleModelInfoVarGlobal(XmlNode node)
{
//for carcols wheels:
//< Item /> < !--VWT_SPORT-- >
//< Item /> < !--VWT_MUSCLE-- >
//< Item /> < !--VWT_LOWRIDER-- >
//< Item /> < !--VWT_SUV-- >
//< Item /> < !--VWT_OFFROAD-- >
//< Item /> < !--VWT_TUNER-- >
//< Item /> < !--VWT_BIKE-- >
//< Item /> < !--VWT_HIEND-- >
//< Item /> < !--VWT_SUPERMOD1-- >
//< Item > < !--VWT_SUPERMOD2-- >
XmlNode cnode;
cnode = node.SelectSingleNode("VehiclePlates");
if (cnode != null)
{
VehiclePlates = new CVehicleModelInfoVarGlobal_465922034(cnode);
}
cnode = node.SelectSingleNode("Colors");
if (cnode != null)
{
var items = cnode.SelectNodes("Item");
if (items.Count > 0)
{
Colors = new CVehicleModelColor[items.Count];
for (int i = 0; i < items.Count; i++)
{
Colors[i] = new CVehicleModelColor(items[i]);
}
}
}
cnode = node.SelectSingleNode("MetallicSettings");
if (cnode != null)
{
var items = cnode.SelectNodes("Item");
if (items.Count > 0)
{
MetallicSettings = new CVehicleMetallicSetting[items.Count];
for (int i = 0; i < items.Count; i++)
{
MetallicSettings[i] = new CVehicleMetallicSetting(items[i]);
}
}
}
cnode = node.SelectSingleNode("WindowColors");
if (cnode != null)
{
var items = cnode.SelectNodes("Item");
if (items.Count > 0)
{
WindowColors = new CVehicleWindowColor[items.Count];
for (int i = 0; i < items.Count; i++)
{
WindowColors[i] = new CVehicleWindowColor(items[i]);
}
}
}
cnode = node.SelectSingleNode("Lights");
if (cnode != null)
{
var items = cnode.SelectNodes("Item");
if (items.Count > 0)
{
Lights = new vehicleLightSettings[items.Count];
for (int i = 0; i < items.Count; i++)
{
Lights[i] = new vehicleLightSettings(items[i]);
}
}
}
cnode = node.SelectSingleNode("Sirens");
if (cnode != null)
{
var items = cnode.SelectNodes("Item");
if (items.Count > 0)
{
Sirens = new sirenSettings[items.Count];
for (int i = 0; i < items.Count; i++)
{
Sirens[i] = new sirenSettings(items[i]);
}
}
}
cnode = node.SelectSingleNode("Kits");
if (cnode != null)
{
var items = cnode.SelectNodes("Item");
if (items.Count > 0)
{
Kits = new CVehicleKit[items.Count];
for (int i = 0; i < items.Count; i++)
{
Kits[i] = new CVehicleKit(items[i]);
}
}
}
cnode = node.SelectSingleNode("Wheels");
if (cnode != null)
{
var items = cnode.SelectNodes("Item");
if (items.Count > 0)
{
Wheels = new CVehicleWheel[items.Count][];
for (int i = 0; i < items.Count; i++)
{
var item = items[i];
var items2 = item.SelectNodes("Item");
if (items2.Count > 0)
{
var wheelarr = new CVehicleWheel[items2.Count];
for (int j = 0; j < items2.Count; j++)
{
wheelarr[j] = new CVehicleWheel(items2[j]);
}
Wheels[i] = wheelarr;
}
}
}
}
cnode = node.SelectSingleNode("GlobalVariationData");
if (cnode != null)
{
GlobalVariationData = new CVehicleModelInfoVarGlobal_3062246906(cnode);
}
cnode = node.SelectSingleNode("XenonLightColors");
if (cnode != null)
{
var items = cnode.SelectNodes("Item");
if (items.Count > 0)
{
XenonLightColors = new CVehicleXenonLightColor[items.Count];
for (int i = 0; i < items.Count; i++)
{
XenonLightColors[i] = new CVehicleXenonLightColor(items[i]);
}
}
}
}
}
[TC(typeof(EXP))] public class CVehicleModelInfoVarGlobal_465922034 //VehiclePlates
{
public CVehicleModelInfoVarGlobal_3027500557[] Textures { get; set; }
public int DefaultTexureIndex { get; set; }
public byte NumericOffset { get; set; }
public byte AlphabeticOffset { get; set; }
public byte SpaceOffset { get; set; }
public byte RandomCharOffset { get; set; }
public byte NumRandomChar { get; set; }
public CVehicleModelInfoVarGlobal_465922034(XmlNode node)
{
XmlNode cnode = node.SelectSingleNode("Textures");
if (cnode != null)
{
var items = cnode.SelectNodes("Item");
if (items.Count > 0)
{
Textures = new CVehicleModelInfoVarGlobal_3027500557[items.Count];
for (int i = 0; i < items.Count; i++)
{
Textures[i] = new CVehicleModelInfoVarGlobal_3027500557(items[i]);
}
}
}
DefaultTexureIndex = Xml.GetChildIntAttribute(node, "DefaultTextureIndex", "value");
NumericOffset = (byte)Xml.GetChildIntAttribute(node, "NumericOffset", "value");
AlphabeticOffset = (byte)Xml.GetChildIntAttribute(node, "AlphabeticOffset", "value");
SpaceOffset = (byte)Xml.GetChildIntAttribute(node, "SpaceOffset", "value");
RandomCharOffset = (byte)Xml.GetChildIntAttribute(node, "RandomCharOffset", "value");
NumRandomChar = (byte)Xml.GetChildIntAttribute(node, "NumRandomChar", "value");
}
public override string ToString()
{
return (Textures?.Length ?? 0).ToString() + " Textures";
}
}
[TC(typeof(EXP))] public class CVehicleModelInfoVarGlobal_3027500557 //VehiclePlates Texture
{
public MetaHash TextureSetName { get; set; }
public MetaHash DiffuseMapName { get; set; }
public MetaHash NormalMapName { get; set; }
public Vector4 FontExtents { get; set; }
public Vector2 MaxLettersOnPlate { get; set; }
public uint FontColor { get; set; }
public uint FontOutlineColor { get; set; }
public bool IsFontOutlineEnabled { get; set; }
public Vector2 FontOutlineMinMaxDepth { get; set; }
public CVehicleModelInfoVarGlobal_3027500557(XmlNode node)
{
TextureSetName = XmlMeta.GetHash(Xml.GetChildInnerText(node, "TextureSetName"));
DiffuseMapName = XmlMeta.GetHash(Xml.GetChildInnerText(node, "DiffuseMapName"));
NormalMapName = XmlMeta.GetHash(Xml.GetChildInnerText(node, "NormalMapName"));
FontExtents = Xml.GetChildVector4Attributes(node, "FontExtents");
MaxLettersOnPlate = Xml.GetChildVector2Attributes(node, "MaxLettersOnPlate");
FontColor = Xml.GetChildUIntAttribute(node, "FontColor", "value");
FontOutlineColor = Xml.GetChildUIntAttribute(node, "FontOutlineColor", "value");
IsFontOutlineEnabled = Xml.GetChildBoolAttribute(node, "IsFontOutlineEnabled", "value");
FontOutlineMinMaxDepth = Xml.GetChildVector2Attributes(node, "FontOutlineMinMaxDepth");
}
public override string ToString()
{
return TextureSetName.ToString() + ", " + DiffuseMapName.ToString() + ", " + NormalMapName.ToString();
}
}
[TC(typeof(EXP))] public class CVehicleModelColor
{
public uint color { get; set; }
public CVehicleModelColor_360458334 metallicID { get; set; }
public CVehicleModelColor_544262540 audioColor { get; set; }
public CVehicleModelColor_2065815796 audioPrefix { get; set; }
public MetaHash audioColorHash { get; set; }
public MetaHash audioPrefixHash { get; set; }
public string colorName { get; set; }
public CVehicleModelColor(XmlNode node)
{
color = Xml.GetChildUIntAttribute(node, "color", "value");
metallicID = Xml.GetChildEnumInnerText<CVehicleModelColor_360458334>(node, "metallicID");
audioColor = Xml.GetChildEnumInnerText<CVehicleModelColor_544262540>(node, "audioColor");
audioPrefix = Xml.GetChildEnumInnerText<CVehicleModelColor_2065815796>(node, "audioPrefix");
audioColorHash = (uint)Xml.GetChildIntAttribute(node, "audioColorHash", "value");
audioPrefixHash = (uint)Xml.GetChildIntAttribute(node, "audioPrefixHash", "value");
colorName = Xml.GetChildInnerText(node, "colorName");
}
public override string ToString()
{
return colorName;
}
}
[TC(typeof(EXP))] public class CVehicleMetallicSetting
{
public float specInt { get; set; }
public float specFalloff { get; set; }
public float specFresnel { get; set; }
public CVehicleMetallicSetting(XmlNode node)
{
specInt = Xml.GetChildFloatAttribute(node, "specInt", "value");
specFalloff = Xml.GetChildFloatAttribute(node, "specFalloff", "value");
specFresnel = Xml.GetChildFloatAttribute(node, "specFresnel", "value");
}
public override string ToString()
{
return specInt.ToString() + ", " + specFalloff.ToString() + ", " + specFresnel.ToString();
}
}
[TC(typeof(EXP))] public class CVehicleWindowColor
{
public uint color { get; set; }
public MetaHash name { get; set; }
public CVehicleWindowColor(XmlNode node)
{
color = Xml.GetChildUIntAttribute(node, "color", "value");
name = XmlMeta.GetHash(Xml.GetChildInnerText(node, "name"));
}
public override string ToString()
{
return name.ToString();
}
}
[TC(typeof(EXP))] public class vehicleLightSettings
{
public byte id { get; set; }
public vehicleLight indicator { get; set; }
public vehicleCorona rearIndicatorCorona { get; set; }
public vehicleCorona frontIndicatorCorona { get; set; }
public vehicleLight tailLight { get; set; }
public vehicleCorona tailLightCorona { get; set; }
public vehicleCorona tailLightMiddleCorona { get; set; }
public vehicleLight headLight { get; set; }
public vehicleCorona headLightCorona { get; set; }
public vehicleLight reversingLight { get; set; }
public vehicleCorona reversingLightCorona { get; set; }
public string name { get; set; }
public vehicleLightSettings(XmlNode node)
{
id = (byte)Xml.GetChildIntAttribute(node, "id", "value");
XmlNode cnode;
cnode = node.SelectSingleNode("indicator");
if (cnode != null)
{
indicator = new vehicleLight(cnode);
}
cnode = node.SelectSingleNode("rearIndicatorCorona");
if (cnode != null)
{
rearIndicatorCorona = new vehicleCorona(cnode);
}
cnode = node.SelectSingleNode("frontIndicatorCorona");
if (cnode != null)
{
frontIndicatorCorona = new vehicleCorona(cnode);
}
cnode = node.SelectSingleNode("tailLight");
if (cnode != null)
{
tailLight = new vehicleLight(cnode);
}
cnode = node.SelectSingleNode("tailLightCorona");
if (cnode != null)
{
tailLightCorona = new vehicleCorona(cnode);
}
cnode = node.SelectSingleNode("tailLightMiddleCorona");
if (cnode != null)
{
tailLightMiddleCorona = new vehicleCorona(cnode);
}
cnode = node.SelectSingleNode("headLight");
if (cnode != null)
{
headLight = new vehicleLight(cnode);
}
cnode = node.SelectSingleNode("headLightCorona");
if (cnode != null)
{
headLightCorona = new vehicleCorona(cnode);
}
cnode = node.SelectSingleNode("reversingLight");
if (cnode != null)
{
reversingLight = new vehicleLight(cnode);
}
cnode = node.SelectSingleNode("reversingLightCorona");
if (cnode != null)
{
reversingLightCorona = new vehicleCorona(cnode);
}
name = Xml.GetChildInnerText(node, "name");
}
public override string ToString()
{
return id.ToString() + ": " + name;
}
}
[TC(typeof(EXP))] public class vehicleLight
{
public float intensity { get; set; }
public float falloffMax { get; set; }
public float falloffExponent { get; set; }
public float innerConeAngle { get; set; }
public float outerConeAngle { get; set; }
public bool emmissiveBoost { get; set; }
public uint color { get; set; }
public MetaHash textureName { get; set; }
public bool mirrorTexture { get; set; }
public vehicleLight(XmlNode node)
{
intensity = Xml.GetChildFloatAttribute(node, "intensity", "value");
falloffMax = Xml.GetChildFloatAttribute(node, "falloffMax", "value");
falloffExponent = Xml.GetChildFloatAttribute(node, "falloffExponent", "value");
innerConeAngle = Xml.GetChildFloatAttribute(node, "innerConeAngle", "value");
outerConeAngle = Xml.GetChildFloatAttribute(node, "outerConeAngle", "value");
emmissiveBoost = Xml.GetChildBoolAttribute(node, "emmissiveBoost", "value");
color = Xml.GetChildUIntAttribute(node, "color", "value");
textureName = XmlMeta.GetHash(Xml.GetChildInnerText(node, "textureName"));
mirrorTexture = Xml.GetChildBoolAttribute(node, "mirrorTexture", "value");
}
}
[TC(typeof(EXP))] public class vehicleCorona
{
public float size { get; set; }
public float size_far { get; set; }
public float intensity { get; set; }
public float intensity_far { get; set; }
public uint color { get; set; }
public byte numCoronas { get; set; }
public byte distBetweenCoronas { get; set; }
public byte distBetweenCoronas_far { get; set; }
public float xRotation { get; set; }
public float yRotation { get; set; }
public float zRotation { get; set; }
public float zBias { get; set; }
public bool pullCoronaIn { get; set; }
public vehicleCorona(XmlNode node)
{
size = Xml.GetChildFloatAttribute(node, "size", "value");
size_far = Xml.GetChildFloatAttribute(node, "size_far", "value");
intensity = Xml.GetChildFloatAttribute(node, "intensity", "value");
intensity_far = Xml.GetChildFloatAttribute(node, "intensity_far", "value");
color = Xml.GetChildUIntAttribute(node, "color", "value");
numCoronas = (byte)Xml.GetChildIntAttribute(node, "numCoronas", "value");
distBetweenCoronas = (byte)Xml.GetChildIntAttribute(node, "distBetweenCoronas", "value");
distBetweenCoronas_far = (byte)Xml.GetChildIntAttribute(node, "distBetweenCoronas_far", "value");
xRotation = Xml.GetChildFloatAttribute(node, "xRotation", "value");
yRotation = Xml.GetChildFloatAttribute(node, "yRotation", "value");
zRotation = Xml.GetChildFloatAttribute(node, "zRotation", "value");
zBias = Xml.GetChildFloatAttribute(node, "zBias", "value");
pullCoronaIn = Xml.GetChildBoolAttribute(node, "pullCoronaIn", "value");
}
}
[TC(typeof(EXP))] public class sirenSettings
{
public byte id { get; set; }
public string name { get; set; }
public float timeMultiplier { get; set; }
public float lightFalloffMax { get; set; }
public float lightFalloffExponent { get; set; }
public float lightInnerConeAngle { get; set; }
public float lightOuterConeAngle { get; set; }
public float lightOffset { get; set; }
public MetaHash textureName { get; set; }
public uint sequencerBpm { get; set; }
public sirenSettings_188820339 leftHeadLight { get; set; }
public sirenSettings_188820339 rightHeadLight { get; set; }
public sirenSettings_188820339 leftTailLight { get; set; }
public sirenSettings_188820339 rightTailLight { get; set; }
public byte leftHeadLightMultiples { get; set; }
public byte rightHeadLightMultiples { get; set; }
public byte leftTailLightMultiples { get; set; }
public byte rightTailLightMultiples { get; set; }
public bool useRealLights { get; set; }
public sirenLight[] sirens { get; set; }
public sirenSettings(XmlNode node)
{
id = (byte)Xml.GetChildIntAttribute(node, "id", "value");
name = Xml.GetChildInnerText(node, "name");
timeMultiplier = Xml.GetChildFloatAttribute(node, "timeMultiplier", "value");
lightFalloffMax = Xml.GetChildFloatAttribute(node, "lightFalloffMax", "value");
lightFalloffExponent = Xml.GetChildFloatAttribute(node, "lightFalloffExponent", "value");
lightInnerConeAngle = Xml.GetChildFloatAttribute(node, "lightInnerConeAngle", "value");
lightOuterConeAngle = Xml.GetChildFloatAttribute(node, "lightOuterConeAngle", "value");
lightOffset = Xml.GetChildFloatAttribute(node, "lightOffset", "value");
textureName = XmlMeta.GetHash(Xml.GetChildInnerText(node, "textureName"));
sequencerBpm = Xml.GetChildUIntAttribute(node, "sequencerBpm", "value");
XmlNode cnode;
cnode = node.SelectSingleNode("leftHeadLight");
if (cnode != null)
{
leftHeadLight = new sirenSettings_188820339(cnode);
}
cnode = node.SelectSingleNode("rightHeadLight");
if (cnode != null)
{
rightHeadLight = new sirenSettings_188820339(cnode);
}
cnode = node.SelectSingleNode("leftTailLight");
if (cnode != null)
{
leftTailLight = new sirenSettings_188820339(cnode);
}
cnode = node.SelectSingleNode("rightTailLight");
if (cnode != null)
{
rightTailLight = new sirenSettings_188820339(cnode);
}
leftHeadLightMultiples = (byte)Xml.GetChildIntAttribute(node, "leftHeadLightMultiples", "value");
rightHeadLightMultiples = (byte)Xml.GetChildIntAttribute(node, "rightHeadLightMultiples", "value");
leftTailLightMultiples = (byte)Xml.GetChildIntAttribute(node, "leftTailLightMultiples", "value");
rightTailLightMultiples = (byte)Xml.GetChildIntAttribute(node, "rightTailLightMultiples", "value");
useRealLights = Xml.GetChildBoolAttribute(node, "useRealLights", "value");
cnode = node.SelectSingleNode("sirens");
if (cnode != null)
{
var items = cnode.SelectNodes("Item");
if (items.Count > 0)
{
sirens = new sirenLight[items.Count];
for (int i = 0; i < items.Count; i++)
{
sirens[i] = new sirenLight(items[i]);
}
}
}
}
public override string ToString()
{
return id.ToString() + ": " + name;
}
}
[TC(typeof(EXP))] public class sirenSettings_188820339
{
public uint sequencer { get; set; }
public sirenSettings_188820339(XmlNode node)
{
sequencer = Xml.GetChildUIntAttribute(node, "sequencer", "value");
}
}
[TC(typeof(EXP))] public class sirenLight
{
public sirenLight_1356743507 rotation { get; set; }
public sirenLight_1356743507 flashiness { get; set; }
public sirenCorona corona { get; set; }
public uint color { get; set; }
public float intensity { get; set; }
public byte lightGroup { get; set; }
public bool rotate { get; set; }
public bool scale { get; set; }
public byte scaleFactor { get; set; }
public bool flash { get; set; }
public bool light { get; set; }
public bool spotLight { get; set; }
public bool castShadows { get; set; }
public sirenLight(XmlNode node)
{
XmlNode cnode;
cnode = node.SelectSingleNode("rotation");
if (cnode != null)
{
rotation = new sirenLight_1356743507(cnode);
}
cnode = node.SelectSingleNode("flashiness");
if (cnode != null)
{
flashiness = new sirenLight_1356743507(cnode);
}
cnode = node.SelectSingleNode("corona");
if (cnode != null)
{
corona = new sirenCorona(cnode);
}
color = Xml.GetChildUIntAttribute(node, "color", "value");
intensity = Xml.GetChildFloatAttribute(node, "intensity", "value");
lightGroup = (byte)Xml.GetChildIntAttribute(node, "lightGroup", "value");
rotate = Xml.GetChildBoolAttribute(node, "rotate", "value");
scale = Xml.GetChildBoolAttribute(node, "scale", "value");
scaleFactor = (byte)Xml.GetChildIntAttribute(node, "scaleFactor", "value");
flash = Xml.GetChildBoolAttribute(node, "flash", "value");
light = Xml.GetChildBoolAttribute(node, "light", "value");
spotLight = Xml.GetChildBoolAttribute(node, "spotLight", "value");
castShadows = Xml.GetChildBoolAttribute(node, "castShadows", "value");
}
}
[TC(typeof(EXP))] public class sirenLight_1356743507
{
public float delta { get; set; }
public float start { get; set; }
public float speed { get; set; }
public uint sequencer { get; set; }
public byte multiples { get; set; }
public bool direction { get; set; }
public bool syncToBpm { get; set; }
public sirenLight_1356743507(XmlNode node)
{
delta = Xml.GetChildFloatAttribute(node, "delta", "value");
start = Xml.GetChildFloatAttribute(node, "start", "value");
speed = Xml.GetChildFloatAttribute(node, "speed", "value");
sequencer = Xml.GetChildUIntAttribute(node, "sequencer", "value");
multiples = (byte)Xml.GetChildIntAttribute(node, "multiples", "value");
direction = Xml.GetChildBoolAttribute(node, "direction", "value");
syncToBpm = Xml.GetChildBoolAttribute(node, "syncToBpm", "value");
}
}
[TC(typeof(EXP))] public class sirenCorona
{
public float intensity { get; set; }
public float size { get; set; }
public float pull { get; set; }
public bool faceCamera { get; set; }
public sirenCorona(XmlNode node)
{
intensity = Xml.GetChildFloatAttribute(node, "intensity", "value");
size = Xml.GetChildFloatAttribute(node, "size", "value");
pull = Xml.GetChildFloatAttribute(node, "pull", "value");
faceCamera = Xml.GetChildBoolAttribute(node, "faceCamera", "value");
}
}
[TC(typeof(EXP))] public class CVehicleKit
{
public MetaHash kitName { get; set; }
public ushort id { get; set; }
public eModKitType kitType { get; set; }
public CVehicleModVisible[] visibleMods { get; set; }
public CVehicleModLink[] linkMods { get; set; }
public CVehicleModStat[] statMods { get; set; }
public CVehicleKit_427606548[] slotNames { get; set; }
public MetaHash[] liveryNames { get; set; }
public MetaHash[] livery2Names { get; set; }
public CVehicleKit(XmlNode node)
{
kitName = XmlMeta.GetHash(Xml.GetChildInnerText(node, "kitName"));
id = (ushort)Xml.GetChildUIntAttribute(node, "id", "value");
kitType = Xml.GetChildEnumInnerText<eModKitType>(node, "kitType");
XmlNode cnode;
cnode = node.SelectSingleNode("visibleMods");
if (cnode != null)
{
var items = cnode.SelectNodes("Item");
if (items.Count > 0)
{
visibleMods = new CVehicleModVisible[items.Count];
for (int i = 0; i < items.Count; i++)
{
visibleMods[i] = new CVehicleModVisible(items[i]);
}
}
}
cnode = node.SelectSingleNode("linkMods");
if (cnode != null)
{
var items = cnode.SelectNodes("Item");
if (items.Count > 0)
{
linkMods = new CVehicleModLink[items.Count];
for (int i = 0; i < items.Count; i++)
{
linkMods[i] = new CVehicleModLink(items[i]);
}
}
}
cnode = node.SelectSingleNode("statMods");
if (cnode != null)
{
var items = cnode.SelectNodes("Item");
if (items.Count > 0)
{
statMods = new CVehicleModStat[items.Count];
for (int i = 0; i < items.Count; i++)
{
statMods[i] = new CVehicleModStat(items[i]);
}
}
}
cnode = node.SelectSingleNode("slotNames");
if (cnode != null)
{
var items = cnode.SelectNodes("Item");
if (items.Count > 0)
{
slotNames = new CVehicleKit_427606548[items.Count];
for (int i = 0; i < items.Count; i++)
{
slotNames[i] = new CVehicleKit_427606548(items[i]);
}
}
}
cnode = node.SelectSingleNode("liveryNames");
if (cnode != null)
{
var items = cnode.SelectNodes("Item");
if (items.Count > 0)
{
liveryNames = new MetaHash[items.Count];
for (int i = 0; i < items.Count; i++)
{
liveryNames[i] = XmlMeta.GetHash(items[i].InnerText);
}
}
}
cnode = node.SelectSingleNode("livery2Names");
if (cnode != null)
{
var items = cnode.SelectNodes("Item");
if (items.Count > 0)
{
livery2Names = new MetaHash[items.Count];
for (int i = 0; i < items.Count; i++)
{
livery2Names[i] = XmlMeta.GetHash(items[i].InnerText);
}
}
}
}
public override string ToString()
{
return id.ToString() + ": " + kitName.ToString();
}
}
[TC(typeof(EXP))] public class CVehicleModVisible
{
public MetaHash modelName { get; set; }
public string modShopLabel { get; set; }
public MetaHash[] linkedModels { get; set; }
public CVehicleMod_3635907608[] turnOffBones { get; set; }
public eVehicleModType type { get; set; }
public CVehicleMod_3635907608 bone { get; set; }
public CVehicleMod_3635907608 collisionBone { get; set; }
public eVehicleModCameraPos cameraPos { get; set; }
public float audioApply { get; set; }
public byte weight { get; set; }
public bool turnOffExtra { get; set; }
public bool disableBonnetCamera { get; set; }
public bool allowBonnetSlide { get; set; }
public sbyte weaponSlot { get; set; }
public sbyte weaponSlotSecondary { get; set; }
public bool disableProjectileDriveby { get; set; }
public bool disableDriveby { get; set; }
public int disableDrivebySeat { get; set; }
public int disableDrivebySeatSecondary { get; set; }
public CVehicleModVisible(XmlNode node)
{
modelName = XmlMeta.GetHash(Xml.GetChildInnerText(node, "modelName"));
modShopLabel = Xml.GetChildInnerText(node, "modShopLabel");
XmlNode cnode;
cnode = node.SelectSingleNode("linkedModels");
if (cnode != null)
{
var items = cnode.SelectNodes("Item");
if (items.Count > 0)
{
linkedModels = new MetaHash[items.Count];
for (int i = 0; i < items.Count; i++)
{
linkedModels[i] = XmlMeta.GetHash(items[i].InnerText);
}
}
}
cnode = node.SelectSingleNode("turnOffBones");
if (cnode != null)
{
var items = cnode.SelectNodes("Item");
if (items.Count > 0)
{
turnOffBones = new CVehicleMod_3635907608[items.Count];
for (int i = 0; i < items.Count; i++)
{
turnOffBones[i] = Xml.GetEnumValue<CVehicleMod_3635907608>(items[i].InnerText);
}
}
}
type = Xml.GetChildEnumInnerText<eVehicleModType>(node, "type");
bone = Xml.GetChildEnumInnerText<CVehicleMod_3635907608>(node, "bone");
collisionBone = Xml.GetChildEnumInnerText<CVehicleMod_3635907608>(node, "collisionBone");
cameraPos = Xml.GetChildEnumInnerText<eVehicleModCameraPos>(node, "cameraPos");
audioApply = Xml.GetChildFloatAttribute(node, "audioApply", "value");
weight = (byte)Xml.GetChildIntAttribute(node, "weight", "value");
turnOffExtra = Xml.GetChildBoolAttribute(node, "turnOffExtra", "value");
disableBonnetCamera = Xml.GetChildBoolAttribute(node, "disableBonnetCamera", "value");
allowBonnetSlide = Xml.GetChildBoolAttribute(node, "allowBonnetSlide", "value");
weaponSlot = (sbyte)Xml.GetChildIntAttribute(node, "weaponSlot", "value");
weaponSlotSecondary = (sbyte)Xml.GetChildIntAttribute(node, "weaponSlotSecondary", "value");
disableProjectileDriveby = Xml.GetChildBoolAttribute(node, "disableProjectileDriveby", "value");
disableDriveby = Xml.GetChildBoolAttribute(node, "disableDriveby", "value");
disableDrivebySeat = Xml.GetChildIntAttribute(node, "disableDrivebySeat", "value");
disableDrivebySeatSecondary = Xml.GetChildIntAttribute(node, "disableDrivebySeatSecondary", "value");
}
public override string ToString()
{
return modelName.ToString() + ": " + modShopLabel + ": " + type.ToString() + ": " + bone.ToString();
}
}
[TC(typeof(EXP))] public class CVehicleModLink
{
public MetaHash modelName { get; set; }
public CVehicleMod_3635907608 bone { get; set; }
public bool turnOffExtra { get; set; }
public CVehicleModLink(XmlNode node)
{
modelName = XmlMeta.GetHash(Xml.GetChildInnerText(node, "modelName"));
bone = Xml.GetChildEnumInnerText<CVehicleMod_3635907608>(node, "bone");
turnOffExtra = Xml.GetChildBoolAttribute(node, "turnOffExtra", "value");
}
public override string ToString()
{
return modelName.ToString() + ": " + bone.ToString();
}
}
[TC(typeof(EXP))] public class CVehicleModStat
{
public MetaHash identifier { get; set; }
public uint modifier { get; set; }
public float audioApply { get; set; }
public byte weight { get; set; }
public eVehicleModType type { get; set; }
public CVehicleModStat(XmlNode node)
{
identifier = XmlMeta.GetHash(Xml.GetChildInnerText(node, "identifier"));
modifier = Xml.GetChildUIntAttribute(node, "modifier", "value");
audioApply = Xml.GetChildFloatAttribute(node, "audioApply", "value");
weight = (byte)Xml.GetChildIntAttribute(node, "weight", "value");
type = Xml.GetChildEnumInnerText<eVehicleModType>(node, "type");
}
public override string ToString()
{
return identifier.ToString() + ": " + type.ToString();
}
}
[TC(typeof(EXP))] public class CVehicleKit_427606548
{
public eVehicleModType slot { get; set; }
public string name { get; set; }
public CVehicleKit_427606548(XmlNode node)
{
slot = Xml.GetChildEnumInnerText<eVehicleModType>(node, "slot");
name = Xml.GetChildInnerText(node, "name");
}
public override string ToString()
{
return name + ": " + slot.ToString();
}
}
[TC(typeof(EXP))] public class CVehicleWheel
{
public MetaHash wheelName { get; set; }
public MetaHash wheelVariation { get; set; }
public string modShopLabel { get; set; }
public float rimRadius { get; set; }
public bool rear { get; set; }
public CVehicleWheel(XmlNode node)
{
wheelName = XmlMeta.GetHash(Xml.GetChildInnerText(node, "wheelName"));
wheelVariation = XmlMeta.GetHash(Xml.GetChildInnerText(node, "wheelVariation"));
modShopLabel = Xml.GetChildInnerText(node, "modShopLabel");
rimRadius = Xml.GetChildFloatAttribute(node, "rimRadius", "value");
rear = Xml.GetChildBoolAttribute(node, "rear", "value");
}
public override string ToString()
{
return wheelName.ToString() + ": " + wheelVariation.ToString() + ": " + modShopLabel;
}
}
[TC(typeof(EXP))] public class CVehicleModelInfoVarGlobal_3062246906 //GlobalVariationData
{
public uint xenonLightColor { get; set; }
public uint xenonCoronaColor { get; set; }
public float xenonLightIntensityModifier { get; set; }
public float xenonCoronaIntensityModifier { get; set; }
public CVehicleModelInfoVarGlobal_3062246906(XmlNode node)
{
xenonLightColor = Xml.GetChildUIntAttribute(node, "xenonLightColor", "value");
xenonCoronaColor = Xml.GetChildUIntAttribute(node, "xenonCoronaColor", "value");
xenonLightIntensityModifier = Xml.GetChildFloatAttribute(node, "xenonLightIntensityModifier", "value");
xenonCoronaIntensityModifier = Xml.GetChildFloatAttribute(node, "xenonCoronaIntensityModifier", "value");
}
}
[TC(typeof(EXP))] public class CVehicleXenonLightColor
{
public uint lightColor { get; set; }
public uint coronaColor { get; set; }
public float lightIntensityModifier { get; set; }
public float coronaIntensityModifier { get; set; }
public CVehicleXenonLightColor(XmlNode node)
{
lightColor = Xml.GetChildUIntAttribute(node, "lightColor", "value");
coronaColor = Xml.GetChildUIntAttribute(node, "coronaColor", "value");
lightIntensityModifier = Xml.GetChildFloatAttribute(node, "lightIntensityModifier", "value");
coronaIntensityModifier = Xml.GetChildFloatAttribute(node, "coronaIntensityModifier", "value");
}
}
public enum CVehicleModelColor_360458334 //vehicle mod color metallic id
{
none = -1,
EVehicleModelColorMetallic_normal = 0,
EVehicleModelColorMetallic_1 = 1,
EVehicleModelColorMetallic_2 = 2,
EVehicleModelColorMetallic_3 = 3,
EVehicleModelColorMetallic_4 = 4,
EVehicleModelColorMetallic_5 = 5,
EVehicleModelColorMetallic_6 = 6,
EVehicleModelColorMetallic_7 = 7,
EVehicleModelColorMetallic_8 = 8,
EVehicleModelColorMetallic_9 = 9
}
public enum CVehicleModelColor_544262540 //vehicle mod color audio color
{
POLICE_SCANNER_COLOUR_black = 0,
POLICE_SCANNER_COLOUR_blue = 1,
POLICE_SCANNER_COLOUR_brown = 2,
POLICE_SCANNER_COLOUR_beige = 3,
POLICE_SCANNER_COLOUR_graphite = 4,
POLICE_SCANNER_COLOUR_green = 5,
POLICE_SCANNER_COLOUR_grey = 6,
POLICE_SCANNER_COLOUR_orange = 7,
POLICE_SCANNER_COLOUR_pink = 8,
POLICE_SCANNER_COLOUR_red = 9,
POLICE_SCANNER_COLOUR_silver = 10,
POLICE_SCANNER_COLOUR_white = 11,
POLICE_SCANNER_COLOUR_yellow = 12
}
public enum CVehicleModelColor_2065815796 //vehicle mod color audio prefix
{
none = 0,
POLICE_SCANNER_PREFIX_bright = 1,
POLICE_SCANNER_PREFIX_light = 2,
POLICE_SCANNER_PREFIX_dark = 3
}
public enum eModKitType //vehicle mod kit type
{
MKT_STANDARD = 0,
MKT_SPORT = 1,
MKT_SUV = 2,
MKT_SPECIAL = 3
}
public enum CVehicleMod_3635907608 //vehicle mod bone
{
none = -1,
chassis = 0,
bodyshell = 48,
bumper_f = 49,
bumper_r = 50,
wing_rf = 51,
wing_lf = 52,
bonnet = 53,
boot = 54,
exhaust = 56,
exhaust_2 = 57,
exhaust_3 = 58,
exhaust_4 = 59,
exhaust_5 = 60,
exhaust_6 = 61,
exhaust_7 = 62,
exhaust_8 = 63,
exhaust_9 = 64,
exhaust_10 = 65,
exhaust_11 = 66,
exhaust_12 = 67,
exhaust_13 = 68,
exhaust_14 = 69,
exhaust_15 = 70,
exhaust_16 = 71,
extra_1 = 401,
extra_2 = 402,
extra_3 = 403,
extra_4 = 404,
extra_5 = 405,
extra_6 = 406,
extra_7 = 407,
extra_8 = 408,
extra_9 = 409,
extra_10 = 410,
extra_11 = 411,
extra_12 = 412,
extra_13 = 413,
extra_14 = 414,
break_extra_1 = 417,
break_extra_2 = 418,
break_extra_3 = 419,
break_extra_4 = 420,
break_extra_5 = 421,
break_extra_6 = 422,
break_extra_7 = 423,
break_extra_8 = 424,
break_extra_9 = 425,
break_extra_10 = 426,
mod_col_1 = 427,
mod_col_2 = 428,
mod_col_3 = 429,
mod_col_4 = 430,
mod_col_5 = 431,
mod_col_6 = 432,
mod_col_7 = 433,
mod_col_8 = 434,
mod_col_9 = 435,
mod_col_10 = 436,
mod_col_11 = 437,
mod_col_12 = 438,
mod_col_13 = 439,
mod_col_14 = 440,
mod_col_15 = 441,
mod_col_16 = 442,
misc_a = 369,
misc_b = 370,
misc_c = 371,
misc_d = 372,
misc_e = 373,
misc_f = 374,
misc_g = 375,
misc_h = 376,
misc_i = 377,
misc_j = 378,
misc_k = 379,
misc_l = 380,
misc_m = 381,
misc_n = 382,
misc_o = 383,
misc_p = 384,
misc_q = 385,
misc_r = 386,
misc_s = 387,
misc_t = 388,
misc_u = 389,
misc_v = 390,
misc_w = 391,
misc_x = 392,
misc_y = 393,
misc_z = 394,
misc_1 = 395,
misc_2 = 396,
handlebars = 79,
steeringwheel = 80,
swingarm = 29,
forks_u = 21,
forks_l = 22,
headlight_l = 91,
headlight_r = 92,
indicator_lr = 97,
indicator_lf = 95,
indicator_rr = 98,
indicator_rf = 96,
taillight_l = 93,
taillight_r = 94,
window_lf = 42,
window_rf = 43,
window_rr = 45,
window_lr = 44,
window_lm = 46,
window_rm = 47,
hub_lf = 30,
hub_rf = 31,
windscreen_r = 41,
neon_l = 104,
neon_r = 105,
neon_f = 106,
neon_b = 107,
door_dside_f = 3,
door_dside_r = 4,
door_pside_f = 5,
door_pside_r = 6,
bobble_head = 361,
bobble_base = 362,
bobble_hand = 363,
engineblock = 364,
mod_a = 474,
mod_b = 475,
mod_c = 476,
mod_d = 477,
mod_e = 478,
mod_f = 479,
mod_g = 480,
mod_h = 481,
mod_i = 482,
mod_j = 483,
mod_k = 484,
mod_l = 485,
mod_m = 486,
mod_n = 487,
mod_o = 488,
mod_p = 489,
mod_q = 490,
mod_r = 491,
mod_s = 492,
mod_t = 493,
mod_u = 494,
mod_v = 495,
mod_w = 496,
mod_x = 497,
mod_y = 498,
mod_z = 499,
mod_aa = 500,
mod_ab = 501,
mod_ac = 502,
mod_ad = 503,
mod_ae = 504,
mod_af = 505,
mod_ag = 506,
mod_ah = 507,
mod_ai = 508,
mod_aj = 509,
mod_ak = 510,
turret_a1 = 511,
turret_a2 = 512,
turret_a3 = 513,
turret_a4 = 514,
turret_b1 = 524,
turret_b2 = 525,
turret_b3 = 526,
turret_b4 = 527,
rblade_1mod = 560,
rblade_1fast = 561,
rblade_2mod = 562,
rblade_2fast = 563,
rblade_3mod = 564,
rblade_3fast = 565,
fblade_1mod = 566,
fblade_1fast = 567,
fblade_2mod = 568,
fblade_2fast = 569,
fblade_3mod = 570,
fblade_3fast = 571,
Unk_1086719913 = 572,
Unk_3237490897 = 573,
Unk_3375838140 = 574,
Unk_2381840182 = 575,
Unk_3607058940 = 576,
Unk_3607058940_again = 577,
Unk_1208798824 = 578,
Unk_303656220 = 579,
Unk_660207018 = 580,
spike_1mod = 581,
Unk_3045655218 = 582,
Unk_2017296145 = 583,
spike_2mod = 584,
Unk_1122332083 = 585,
Unk_1123212214 = 586,
spike_3mod = 587,
Unk_4011591561 = 588,
Unk_2320654166 = 589,
scoop_1mod = 590,
scoop_2mod = 591,
scoop_3mod = 592
}
public enum eVehicleModType //vehicle mod type
{
VMT_SPOILER = 0,
VMT_BUMPER_F = 1,
VMT_BUMPER_R = 2,
VMT_SKIRT = 3,
VMT_EXHAUST = 4,
VMT_CHASSIS = 5,
VMT_GRILL = 6,
VMT_BONNET = 7,
VMT_WING_L = 8,
VMT_WING_R = 9,
VMT_ROOF = 10,
VMT_PLTHOLDER = 11,
VMT_PLTVANITY = 12,
VMT_INTERIOR1 = 13,
VMT_INTERIOR2 = 14,
VMT_INTERIOR3 = 15,
VMT_INTERIOR4 = 16,
VMT_INTERIOR5 = 17,
VMT_SEATS = 18,
VMT_STEERING = 19,
VMT_KNOB = 20,
VMT_PLAQUE = 21,
VMT_ICE = 22,
VMT_TRUNK = 23,
VMT_HYDRO = 24,
VMT_ENGINEBAY1 = 25,
VMT_ENGINEBAY2 = 26,
VMT_ENGINEBAY3 = 27,
VMT_CHASSIS2 = 28,
VMT_CHASSIS3 = 29,
VMT_CHASSIS4 = 30,
VMT_CHASSIS5 = 31,
VMT_DOOR_L = 32,
VMT_DOOR_R = 33,
VMT_LIVERY_MOD = 34,
Unk_3409280882 = 35,
VMT_ENGINE = 36,
VMT_BRAKES = 37,
VMT_GEARBOX = 38,
VMT_HORN = 39,
VMT_SUSPENSION = 40,
VMT_ARMOUR = 41,
Unk_3278520444 = 42,
VMT_TURBO = 43,
Unk_1675686396 = 44,
VMT_TYRE_SMOKE = 45,
VMT_HYDRAULICS = 46,
VMT_XENON_LIGHTS = 47,
VMT_WHEELS = 48,
VMT_WHEELS_REAR_OR_HYDRAULICS = 49
}
public enum eVehicleModCameraPos //vehicle mod camera position
{
VMCP_DEFAULT = 0,
VMCP_FRONT = 1,
VMCP_FRONT_LEFT = 2,
VMCP_FRONT_RIGHT = 3,
VMCP_REAR = 4,
VMCP_REAR_LEFT = 5,
VMCP_REAR_RIGHT = 6,
VMCP_LEFT = 7,
VMCP_RIGHT = 8,
VMCP_TOP = 9,
VMCP_BOTTOM = 10
}
}
| 37.825645 | 117 | 0.543872 | [
"MIT"
] | ThymonA/RageKit | RageKit/GameFiles/FileTypes/CarColsFile.cs | 48,381 | C# |
using System.Web;
using System.Web.Optimization;
namespace AddressBook
{
public class BundleConfig
{
// For more information on bundling, visit https://go.microsoft.com/fwlink/?LinkId=301862
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.validate*"));
// Use the development version of Modernizr to develop with and learn from. Then, when you're
// ready for production, use the build tool at https://modernizr.com to pick only the tests you need.
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
"~/Scripts/bootstrap.js"));
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.css",
"~/Content/site.css"));
}
}
}
| 38.580645 | 113 | 0.582776 | [
"MIT"
] | thiseasm/AddressBook | AddressBook/App_Start/BundleConfig.cs | 1,198 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
namespace Ying.YingUtil
{
public enum MagneticLocation
{
Left = 0,
Right = 1,
Top = 2,
Bottom = 3
}
public enum MagneticState
{
Adsorbent, // 吸附
Separation // 分离
}
public class YingMagneticManager : YingYing
{
public class ChildWindowInfo
{
public Window Child { get; set; }
public MagneticLocation Location { get; set; }
public MagneticState State { get; set; }
public bool CutstomSetLocation { get; set; }
}
public int Step { get; set; }
private Window m_mainWindow = null;
private List<ChildWindowInfo> m_childs = new List<ChildWindowInfo>();
public YingMagneticManager(Window form)
{
m_mainWindow = form;
form.LocationChanged += MainWindow_LocationChanged;
form.SizeChanged += MainWindow_SizeChanged;
form.Closed += MainWindow_WindowClosed;
Step = 20;
}
public void addChild(Window childWindow, MagneticLocation loc)
{
foreach (ChildWindowInfo info in m_childs)
{
if (info.Child == childWindow)
{
return;
}
}
ChildWindowInfo childInfo = new ChildWindowInfo();
childInfo.Child = childWindow;
childInfo.Location = loc;
childInfo.State = MagneticState.Adsorbent;
childInfo.CutstomSetLocation = false;
childWindow.LocationChanged += ChildWindow_LocationChanged;
childWindow.SizeChanged += ChildWindow_SizeChanged;
childWindow.Closed += ChildWindow_WindowClosed;
m_childs.Add(childInfo);
adsorbentChild(childInfo);
}
private ChildWindowInfo getInfo(Window form)
{
if (form == null)
{
return null;
}
foreach (ChildWindowInfo info in m_childs)
{
if (info.Child == form)
{
return info;
}
}
return null;
}
private Point getLocation(ChildWindowInfo info)
{
Point pos = new Point();
switch (info.Location)
{
case MagneticLocation.Left:
pos = new Point(m_mainWindow.Left - info.Child.ActualWidth - 6.64, m_mainWindow.Top);
break;
case MagneticLocation.Right:
pos = new Point(m_mainWindow.Left + m_mainWindow.ActualWidth + 6.64, m_mainWindow.Top + ((m_mainWindow.ActualHeight - info.Child.ActualHeight) / 2));
break;
case MagneticLocation.Top:
pos = new Point(m_mainWindow.Left, m_mainWindow.Top - info.Child.ActualHeight);
break;
case MagneticLocation.Bottom:
pos = new Point(m_mainWindow.Left, m_mainWindow.Top + m_mainWindow.ActualHeight);
break;
default:
break;
}
return pos;
}
private void setChildLocation(ChildWindowInfo info, Point location)
{
if (info.Child == null)
{
return;
}
info.CutstomSetLocation = true;
//info.Child.Location = location;
info.Child.Top = location.Y;
info.Child.Left = location.X;
info.CutstomSetLocation = false; //getYing();
}
private void setChildLocation(ChildWindowInfo info, int x, int y)
{
setChildLocation(info, new Point(x, y));
}
private void resetChildLocation(ChildWindowInfo info)
{
if (info.Child == null)
{
return;
}
Point pos = getLocation(info);
setChildLocation(info, pos);
}
private void adsorbentChild(ChildWindowInfo info)
{
info.State = MagneticState.Adsorbent;
resetChildLocation(info);
}
private void separationChild(ChildWindowInfo info)
{
info.State = MagneticState.Separation;
}
private void MainWindow_LocationChanged(object sender, EventArgs e)
{
foreach (ChildWindowInfo info in m_childs)
{
if (info.State == MagneticState.Adsorbent)
{
resetChildLocation(info);
}
}
}
private void MainWindow_SizeChanged(object sender, EventArgs e)
{
foreach (ChildWindowInfo info in m_childs)
{
if (info.State == MagneticState.Adsorbent)
{
resetChildLocation(info);
}
}
}
private void MainWindow_WindowClosed(object sender, EventArgs e)
{
}
private void ChildWindow_LocationChanged(object sender, EventArgs e)
{
ChildWindowInfo info = getInfo(sender as Window);
if (info == null)
{
return;
}
if (info.CutstomSetLocation == true)
{
return;
}
Point location = getLocation(info);
if (info.Child.Left > location.X && info.Location == MagneticLocation.Right)
{
if (info.Child.Left - location.X > Step)
{
separationChild(info);
}
else
{
adsorbentChild(info);
}
}
else if (info.Child.Left < location.X && info.Location == MagneticLocation.Left)
{
if (info.Child.Left - location.X < -Step)
{
separationChild(info);
}
else
{
adsorbentChild(info);
}
}
if (info.Child.Top > location.Y && info.Location == MagneticLocation.Bottom)
{
if (info.Child.Top - location.Y > Step)
{
separationChild(info);
}
else
{
adsorbentChild(info);
}
}
else if (info.Child.Top < location.Y && info.Location == MagneticLocation.Top)
{
if (info.Child.Top - location.Y < -Step)
{
separationChild(info);
}
else
{
adsorbentChild(info);
}
}
}
private void ChildWindow_SizeChanged(object sender, EventArgs e)
{
ChildWindowInfo info = getInfo(sender as Window);
if (info != null && info.State == MagneticState.Adsorbent)
{
resetChildLocation(info);
}
}
private void ChildWindow_WindowClosed(object sender, EventArgs e)
{
ChildWindowInfo info = getInfo(sender as Window);
if (info != null)
{
m_childs.Remove(info);
}
}
}
}
| 28.354478 | 169 | 0.486906 | [
"MIT"
] | iZhangYingYing/YingLauncher | YingClient/Ying/Ying/YingUtils/YingMagneticManager.cs | 7,609 | C# |
using System;
namespace RavenNest.DataModels
{
public class UserNotification : Entity<UserNotification>
{
private Guid id; public Guid Id { get => id; set => Set(ref id, value); }
private Guid userId; public Guid UserId { get => userId; set => Set(ref userId, value); }
private string icon; public string Icon { get => icon; set => Set(ref icon, value); }
private string title; public string Title { get => title; set => Set(ref title, value); }
private string description; public string Description { get => description; set => Set(ref description, value); }
private string redirectUrl; public string RedirectUrl { get => redirectUrl; set => Set(ref redirectUrl, value); }
private bool hasRead; public bool HasRead { get => hasRead; set => Set(ref hasRead, value); }
private DateTime time; public DateTime Time { get => time; set => Set(ref time, value); }
}
}
| 55.294118 | 121 | 0.655319 | [
"MIT"
] | zerratar/RavenNest | src/RavenNest.DataModels/UserNotification.cs | 942 | C# |
using System;
using System.Diagnostics;
using Geisha.Common.Math;
using Geisha.Engine.Core.Components;
using Geisha.Engine.Core.Diagnostics;
using Geisha.Engine.Core.SceneModel;
using Geisha.Engine.Rendering;
using Geisha.Engine.Rendering.Backend;
using Geisha.Engine.Rendering.Components;
using Geisha.Engine.Rendering.Systems;
using Geisha.TestUtils;
using NSubstitute;
using NUnit.Framework;
namespace Geisha.Engine.UnitTests.Rendering.Systems
{
[TestFixture]
public class RenderingSystemTests
{
private const int ScreenWidth = 200;
private const int ScreenHeight = 100;
private IRenderer2D _renderer2D = null!;
private IRenderingBackend _renderingBackend = null!;
private IAggregatedDiagnosticInfoProvider _aggregatedDiagnosticInfoProvider = null!;
private IDebugRendererForRenderingSystem _debugRendererForRenderingSystem = null!;
private readonly RenderingConfiguration.IBuilder _renderingConfigurationBuilder = RenderingConfiguration.CreateBuilder();
[SetUp]
public void SetUp()
{
_renderer2D = Substitute.For<IRenderer2D>();
_renderer2D.ScreenWidth.Returns(ScreenWidth);
_renderer2D.ScreenHeight.Returns(ScreenHeight);
_renderingBackend = Substitute.For<IRenderingBackend>();
_renderingBackend.Renderer2D.Returns(_renderer2D);
_aggregatedDiagnosticInfoProvider = Substitute.For<IAggregatedDiagnosticInfoProvider>();
_debugRendererForRenderingSystem = Substitute.For<IDebugRendererForRenderingSystem>();
}
[Test]
public void RenderScene_Should_BeginRendering_Clear_EndRendering_GivenAnEmptyScene()
{
// Arrange
var renderingSystem = GetRenderingSystem();
var scene = TestSceneFactory.Create();
// Act
renderingSystem.RenderScene(scene);
// Assert
Received.InOrder(() =>
{
_renderer2D.BeginRendering();
_renderer2D.Clear(Color.FromArgb(255, 255, 255, 255));
_renderer2D.EndRendering(false);
});
}
[Test]
public void RenderScene_ShouldCallInFollowingOrder_BeginRendering_Clear_RenderSprite_EndRendering()
{
// Arrange
var renderingSystem = GetRenderingSystem();
var renderingSceneBuilder = new RenderingSceneBuilder();
renderingSceneBuilder.AddCamera();
renderingSceneBuilder.AddSprite();
var scene = renderingSceneBuilder.Build();
// Act
renderingSystem.RenderScene(scene);
// Assert
Received.InOrder(() =>
{
_renderer2D.BeginRendering();
_renderer2D.Clear(Color.FromArgb(255, 255, 255, 255));
_renderer2D.RenderSprite(Arg.Any<Sprite>(), Arg.Any<Matrix3x3>());
_renderer2D.EndRendering(false);
});
}
[TestCase(true)]
[TestCase(false)]
public void RenderScene_Should_EndRendering_WithWaitForVSync_BasedOnRenderingConfiguration(bool enableVSync)
{
// Arrange
SetupVSync(enableVSync);
var renderingSystem = GetRenderingSystem();
var scene = TestSceneFactory.Create();
// Act
renderingSystem.RenderScene(scene);
// Assert
_renderer2D.Received().EndRendering(enableVSync);
}
[Test]
public void RenderScene_ShouldIgnoreOrderInLayer_WhenEntitiesAreInDifferentSortingLayers()
{
// Arrange
const string otherSortingLayer = "Other";
SetupSortingLayers(RenderingConfiguration.DefaultSortingLayerName, otherSortingLayer);
var renderingSystem = GetRenderingSystem();
var renderingSceneBuilder = new RenderingSceneBuilder();
renderingSceneBuilder.AddCamera();
var entity1 = renderingSceneBuilder.AddSprite(orderInLayer: 0, sortingLayerName: otherSortingLayer);
var entity2 = renderingSceneBuilder.AddSprite(orderInLayer: 1);
var scene = renderingSceneBuilder.Build();
// Act
renderingSystem.RenderScene(scene);
// Assert
Received.InOrder(() =>
{
_renderer2D.RenderSprite(entity2.GetSprite(), entity2.Get2DTransformationMatrix());
_renderer2D.RenderSprite(entity1.GetSprite(), entity1.Get2DTransformationMatrix());
});
}
[Test]
public void RenderScene_ShouldNotRenderSprite_WhenSceneContainsEntityWithSpriteRendererAndTransformButDoesNotContainCamera()
{
// Arrange
var renderingSystem = GetRenderingSystem();
var renderingSceneBuilder = new RenderingSceneBuilder();
renderingSceneBuilder.AddSprite();
var scene = renderingSceneBuilder.Build();
// Act
renderingSystem.RenderScene(scene);
// Assert
_renderer2D.DidNotReceive().RenderSprite(Arg.Any<Sprite>(), Arg.Any<Matrix3x3>());
}
[Test]
public void RenderScene_ShouldPerformCameraTransformationOnEntity_WhenSceneContainsEntityAndCamera()
{
// Arrange
var renderingSystem = GetRenderingSystem();
var renderingSceneBuilder = new RenderingSceneBuilder();
var cameraTransform = new Transform2DComponent
{
Translation = new Vector2(10, -10),
Rotation = 0,
Scale = Vector2.One
};
renderingSceneBuilder.AddCamera(cameraTransform);
var entity = renderingSceneBuilder.AddSprite(Transform2DComponent.CreateDefault());
var scene = renderingSceneBuilder.Build();
// Act
renderingSystem.RenderScene(scene);
// Assert
_renderer2D.Received(1).RenderSprite(entity.GetSprite(), Matrix3x3.CreateTranslation(new Vector2(-10, 10)));
}
[Test]
public void RenderScene_ShouldApplyViewRectangleOfCamera_WhenSceneContainsEntityAndCamera()
{
// Arrange
var renderingSystem = GetRenderingSystem();
var renderingSceneBuilder = new RenderingSceneBuilder();
var cameraTransform = new Transform2DComponent
{
Translation = new Vector2(10, -10),
Rotation = 0,
Scale = Vector2.One
};
var cameraEntity = renderingSceneBuilder.AddCamera(cameraTransform);
var camera = cameraEntity.GetComponent<CameraComponent>();
// Camera view rectangle is twice the screen resolution
camera.ViewRectangle = new Vector2(ScreenWidth * 2, ScreenHeight * 2);
var entity = renderingSceneBuilder.AddSprite(Transform2DComponent.CreateDefault());
var scene = renderingSceneBuilder.Build();
// Act
renderingSystem.RenderScene(scene);
// Assert
_renderer2D.Received(1).RenderSprite(entity.GetSprite(),
// Sprite transform is half the scale and translation due to camera view rectangle
new Matrix3x3(m11: 0.5, m12: 0, m13: -5, m21: 0, m22: 0.5, m23: 5, m31: 0, m32: 0, m33: 1));
}
[Test]
public void RenderScene_ShouldApplyViewRectangleOfCameraWithOverscanMatchedByHeight_WhenCameraAndScreenAspectRatioDiffers()
{
// Arrange
var renderingSystem = GetRenderingSystem();
var renderingSceneBuilder = new RenderingSceneBuilder();
var cameraTransform = new Transform2DComponent
{
Translation = new Vector2(10, -10),
Rotation = 0,
Scale = Vector2.One
};
var cameraEntity = renderingSceneBuilder.AddCamera(cameraTransform);
var camera = cameraEntity.GetComponent<CameraComponent>();
camera.AspectRatioBehavior = AspectRatioBehavior.Overscan;
// Camera view rectangle 4xScreenWidth and 2xScreenHeight
// Camera view rectangle is 4:1 ratio while screen is 2:1 ratio
camera.ViewRectangle = new Vector2(ScreenWidth * 4, ScreenHeight * 2);
var entity = renderingSceneBuilder.AddSprite(Transform2DComponent.CreateDefault());
var scene = renderingSceneBuilder.Build();
// Act
renderingSystem.RenderScene(scene);
// Assert
_renderer2D.Received(1).RenderSprite(entity.GetSprite(),
// Sprite transform is half the scale and translation due to camera view rectangle being scaled by height to match
new Matrix3x3(m11: 0.5, m12: 0, m13: -5, m21: 0, m22: 0.5, m23: 5, m31: 0, m32: 0, m33: 1));
}
[Test]
public void RenderScene_ShouldApplyViewRectangleOfCameraWithOverscanMatchedByWidth_WhenCameraAndScreenAspectRatioDiffers()
{
// Arrange
var renderingSystem = GetRenderingSystem();
var renderingSceneBuilder = new RenderingSceneBuilder();
var cameraTransform = new Transform2DComponent
{
Translation = new Vector2(10, -10),
Rotation = 0,
Scale = Vector2.One
};
var cameraEntity = renderingSceneBuilder.AddCamera(cameraTransform);
var camera = cameraEntity.GetComponent<CameraComponent>();
camera.AspectRatioBehavior = AspectRatioBehavior.Overscan;
// Camera view rectangle 2xScreenWidth and 4xScreenHeight
// Camera view rectangle is 1:1 ratio while screen is 2:1 ratio
camera.ViewRectangle = new Vector2(ScreenWidth * 2, ScreenHeight * 4);
var entity = renderingSceneBuilder.AddSprite(Transform2DComponent.CreateDefault());
var scene = renderingSceneBuilder.Build();
// Act
renderingSystem.RenderScene(scene);
// Assert
_renderer2D.Received(1).RenderSprite(entity.GetSprite(),
// Sprite transform is half the scale and translation due to camera view rectangle being scaled by width to match
new Matrix3x3(m11: 0.5, m12: 0, m13: -5, m21: 0, m22: 0.5, m23: 5, m31: 0, m32: 0, m33: 1));
}
[Test]
public void RenderScene_ShouldApplyViewRectangleOfCameraWithUnderscanMatchedByHeight_WhenCameraAndScreenAspectRatioDiffers()
{
// Arrange
var renderingSystem = GetRenderingSystem();
var renderingSceneBuilder = new RenderingSceneBuilder();
var cameraTransform = new Transform2DComponent
{
Translation = new Vector2(10, -10),
Rotation = 0,
Scale = Vector2.One
};
var cameraEntity = renderingSceneBuilder.AddCamera(cameraTransform);
var camera = cameraEntity.GetComponent<CameraComponent>();
camera.AspectRatioBehavior = AspectRatioBehavior.Underscan;
// Camera view rectangle 1xScreenWidth and 2xScreenHeight
// Camera view rectangle is 1:1 ratio while screen is 2:1 ratio
camera.ViewRectangle = new Vector2(ScreenWidth, ScreenHeight * 2);
var entity = renderingSceneBuilder.AddSprite(Transform2DComponent.CreateDefault());
var scene = renderingSceneBuilder.Build();
// Act
renderingSystem.RenderScene(scene);
// Assert
Received.InOrder(() =>
{
_renderer2D.Clear(Color.FromArgb(255, 255, 255, 255));
_renderer2D.Clear(Color.FromArgb(255, 0, 0, 0));
_renderer2D.SetClippingRectangle(Arg.Is<Rectangle>(r => r.Width == ScreenHeight && r.Height == ScreenHeight));
_renderer2D.Clear(Color.FromArgb(255, 255, 255, 255));
_renderer2D.Received(1).RenderSprite(entity.GetSprite(),
// Sprite transform is half the scale and translation due to camera view rectangle being scaled by height to match
new Matrix3x3(m11: 0.5, m12: 0, m13: -5, m21: 0, m22: 0.5, m23: 5, m31: 0, m32: 0, m33: 1));
_renderer2D.ClearClipping();
});
}
[Test]
public void RenderScene_ShouldApplyViewRectangleOfCameraWithUnderscanMatchedByWidth_WhenCameraAndScreenAspectRatioDiffers()
{
// Arrange
var renderingSystem = GetRenderingSystem();
var renderingSceneBuilder = new RenderingSceneBuilder();
var cameraTransform = new Transform2DComponent
{
Translation = new Vector2(10, -10),
Rotation = 0,
Scale = Vector2.One
};
var cameraEntity = renderingSceneBuilder.AddCamera(cameraTransform);
var camera = cameraEntity.GetComponent<CameraComponent>();
camera.AspectRatioBehavior = AspectRatioBehavior.Underscan;
// Camera view rectangle 2xScreenWidth and 1xScreenHeight
// Camera view rectangle is 4:1 ratio while screen is 2:1 ratio
camera.ViewRectangle = new Vector2(ScreenWidth * 2, ScreenHeight);
var entity = renderingSceneBuilder.AddSprite(Transform2DComponent.CreateDefault());
var scene = renderingSceneBuilder.Build();
// Act
renderingSystem.RenderScene(scene);
// Assert
Received.InOrder(() =>
{
_renderer2D.Clear(Color.FromArgb(255, 255, 255, 255));
_renderer2D.Clear(Color.FromArgb(255, 0, 0, 0));
_renderer2D.SetClippingRectangle(Arg.Is<Rectangle>(r => r.Width == ScreenWidth && r.Height == (ScreenHeight / 2d)));
_renderer2D.Clear(Color.FromArgb(255, 255, 255, 255));
_renderer2D.Received(1).RenderSprite(entity.GetSprite(),
// Sprite transform is half the scale and translation due to camera view rectangle being scaled by width to match
new Matrix3x3(m11: 0.5, m12: 0, m13: -5, m21: 0, m22: 0.5, m23: 5, m31: 0, m32: 0, m33: 1));
_renderer2D.ClearClipping();
});
}
[Test]
public void RenderScene_ShouldRenderDiagnosticInfo_AfterRenderingScene()
{
// Arrange
var diagnosticInfo1 = GetRandomDiagnosticInfo();
var diagnosticInfo2 = GetRandomDiagnosticInfo();
var diagnosticInfo3 = GetRandomDiagnosticInfo();
_aggregatedDiagnosticInfoProvider.GetAllDiagnosticInfo().Returns(new[] {diagnosticInfo1, diagnosticInfo2, diagnosticInfo3});
var renderingSystem = GetRenderingSystem();
var renderingSceneBuilder = new RenderingSceneBuilder();
renderingSceneBuilder.AddCamera();
var entity1 = renderingSceneBuilder.AddSprite(orderInLayer: 0);
var entity2 = renderingSceneBuilder.AddSprite(orderInLayer: 1);
var entity3 = renderingSceneBuilder.AddSprite(orderInLayer: 2);
var scene = renderingSceneBuilder.Build();
// Act
renderingSystem.RenderScene(scene);
// Assert
Received.InOrder(() =>
{
_renderer2D.RenderSprite(entity1.GetSprite(), entity1.Get2DTransformationMatrix());
_renderer2D.RenderSprite(entity2.GetSprite(), entity2.Get2DTransformationMatrix());
_renderer2D.RenderSprite(entity3.GetSprite(), entity3.Get2DTransformationMatrix());
_renderer2D.RenderText(diagnosticInfo1.ToString(), Arg.Any<FontSize>(), Arg.Any<Color>(), Arg.Any<Matrix3x3>());
_renderer2D.RenderText(diagnosticInfo2.ToString(), Arg.Any<FontSize>(), Arg.Any<Color>(), Arg.Any<Matrix3x3>());
_renderer2D.RenderText(diagnosticInfo3.ToString(), Arg.Any<FontSize>(), Arg.Any<Color>(), Arg.Any<Matrix3x3>());
});
}
[Test]
public void RenderScene_ShouldRenderInOrderOf_OrderInLayer_WhenEntitiesAreInTheSameSortingLayer()
{
// Arrange
var renderingSystem = GetRenderingSystem();
var renderingSceneBuilder = new RenderingSceneBuilder();
renderingSceneBuilder.AddCamera();
var entity1 = renderingSceneBuilder.AddSprite(orderInLayer: 1);
var entity2 = renderingSceneBuilder.AddSprite(orderInLayer: -1);
var entity3 = renderingSceneBuilder.AddSprite(orderInLayer: 0);
var scene = renderingSceneBuilder.Build();
// Act
renderingSystem.RenderScene(scene);
// Assert
Received.InOrder(() =>
{
_renderer2D.RenderSprite(entity2.GetSprite(), entity2.Get2DTransformationMatrix());
_renderer2D.RenderSprite(entity3.GetSprite(), entity3.Get2DTransformationMatrix());
_renderer2D.RenderSprite(entity1.GetSprite(), entity1.Get2DTransformationMatrix());
});
}
[Test]
public void RenderScene_ShouldRenderInSortingLayersOrder_Default_Background_Foreground()
{
// Arrange
const string backgroundSortingLayerName = "Background";
const string foregroundSortingLayerName = "Foreground";
SetupSortingLayers(RenderingConfiguration.DefaultSortingLayerName, backgroundSortingLayerName, foregroundSortingLayerName);
var renderingSystem = GetRenderingSystem();
var renderingSceneBuilder = new RenderingSceneBuilder();
renderingSceneBuilder.AddCamera();
var entity1 = renderingSceneBuilder.AddSprite(sortingLayerName: foregroundSortingLayerName);
var entity2 = renderingSceneBuilder.AddSprite(sortingLayerName: RenderingConfiguration.DefaultSortingLayerName);
var entity3 = renderingSceneBuilder.AddSprite(sortingLayerName: backgroundSortingLayerName);
var scene = renderingSceneBuilder.Build();
// Act
renderingSystem.RenderScene(scene);
// Assert
Received.InOrder(() =>
{
_renderer2D.RenderSprite(entity2.GetSprite(), entity2.Get2DTransformationMatrix());
_renderer2D.RenderSprite(entity3.GetSprite(), entity3.Get2DTransformationMatrix());
_renderer2D.RenderSprite(entity1.GetSprite(), entity1.Get2DTransformationMatrix());
});
}
[Test]
public void RenderScene_ShouldRenderInSortingLayersOrder_Foreground_Background_Default()
{
// Arrange
const string backgroundSortingLayerName = "Background";
const string foregroundSortingLayerName = "Foreground";
SetupSortingLayers(foregroundSortingLayerName, backgroundSortingLayerName, RenderingConfiguration.DefaultSortingLayerName);
var renderingSystem = GetRenderingSystem();
var renderingSceneBuilder = new RenderingSceneBuilder();
renderingSceneBuilder.AddCamera();
var entity1 = renderingSceneBuilder.AddSprite(sortingLayerName: foregroundSortingLayerName);
var entity2 = renderingSceneBuilder.AddSprite(sortingLayerName: RenderingConfiguration.DefaultSortingLayerName);
var entity3 = renderingSceneBuilder.AddSprite(sortingLayerName: backgroundSortingLayerName);
var scene = renderingSceneBuilder.Build();
// Act
renderingSystem.RenderScene(scene);
// Assert
Received.InOrder(() =>
{
_renderer2D.RenderSprite(entity1.GetSprite(), entity1.Get2DTransformationMatrix());
_renderer2D.RenderSprite(entity3.GetSprite(), entity3.Get2DTransformationMatrix());
_renderer2D.RenderSprite(entity2.GetSprite(), entity2.Get2DTransformationMatrix());
});
}
[Test]
public void RenderScene_ShouldRenderOnlyEntities_ThatHaveVisibleSpriteRenderer()
{
// Arrange
var renderingSystem = GetRenderingSystem();
var renderingSceneBuilder = new RenderingSceneBuilder();
renderingSceneBuilder.AddCamera();
var entity1 = renderingSceneBuilder.AddSprite(visible: true);
var entity2 = renderingSceneBuilder.AddSprite(visible: false);
var scene = renderingSceneBuilder.Build();
// Act
renderingSystem.RenderScene(scene);
// Assert
_renderer2D.Received(1).RenderSprite(entity1.GetSprite(), entity1.Get2DTransformationMatrix());
_renderer2D.DidNotReceive().RenderSprite(entity2.GetSprite(), entity2.Get2DTransformationMatrix());
}
[Test]
public void RenderScene_ShouldRenderSprite_WhenSceneContainsEntityWithSpriteRendererAndTransform()
{
// Arrange
var renderingSystem = GetRenderingSystem();
var renderingSceneBuilder = new RenderingSceneBuilder();
renderingSceneBuilder.AddCamera();
var entity = renderingSceneBuilder.AddSprite();
var scene = renderingSceneBuilder.Build();
// Act
renderingSystem.RenderScene(scene);
// Assert
_renderer2D.Received(1).RenderSprite(entity.GetSprite(), entity.Get2DTransformationMatrix());
}
[Test]
public void RenderScene_ShouldRenderText_WhenSceneContainsEntityWithTextRendererAndTransform()
{
// Arrange
var renderingSystem = GetRenderingSystem();
var renderingSceneBuilder = new RenderingSceneBuilder();
renderingSceneBuilder.AddCamera();
var entity = renderingSceneBuilder.AddText();
var scene = renderingSceneBuilder.Build();
// Act
renderingSystem.RenderScene(scene);
// Assert
var textRenderer = entity.GetComponent<TextRendererComponent>();
Debug.Assert(textRenderer.Text != null, "textRenderer.Text != null");
_renderer2D.Received(1).RenderText(textRenderer.Text, textRenderer.FontSize, textRenderer.Color, entity.Get2DTransformationMatrix());
}
[Test]
public void RenderScene_ShouldRenderRectangle_WhenSceneContainsEntityWithRectangleRendererAndTransform()
{
// Arrange
var renderingSystem = GetRenderingSystem();
var renderingSceneBuilder = new RenderingSceneBuilder();
renderingSceneBuilder.AddCamera();
var entity = renderingSceneBuilder.AddRectangle();
var scene = renderingSceneBuilder.Build();
// Act
renderingSystem.RenderScene(scene);
// Assert
var rectangleRenderer = entity.GetComponent<RectangleRendererComponent>();
_renderer2D.Received(1).RenderRectangle(Arg.Is<Rectangle>(r =>
Math.Abs(r.Width - rectangleRenderer.Dimension.X) < 0.001 && Math.Abs(r.Height - rectangleRenderer.Dimension.Y) < 0.001),
rectangleRenderer.Color, rectangleRenderer.FillInterior,
entity.Get2DTransformationMatrix());
}
[Test]
public void RenderScene_ShouldRenderEllipse_WhenSceneContainsEntityWithEllipseRendererAndTransform()
{
// Arrange
var renderingSystem = GetRenderingSystem();
var renderingSceneBuilder = new RenderingSceneBuilder();
renderingSceneBuilder.AddCamera();
var entity = renderingSceneBuilder.AddEllipse();
var scene = renderingSceneBuilder.Build();
// Act
renderingSystem.RenderScene(scene);
// Assert
var ellipseRenderer = entity.GetComponent<EllipseRendererComponent>();
_renderer2D.Received(1).RenderEllipse(new Ellipse(ellipseRenderer.RadiusX, ellipseRenderer.RadiusY), ellipseRenderer.Color,
ellipseRenderer.FillInterior, entity.Get2DTransformationMatrix());
}
[Test]
public void RenderScene_ShouldSetScreenWidthAndScreenHeightOnCameraComponent()
{
// Arrange
const int screenWidth = 123;
const int screenHeight = 456;
_renderer2D.ScreenWidth.Returns(screenWidth);
_renderer2D.ScreenHeight.Returns(screenHeight);
var renderingSystem = GetRenderingSystem();
var renderingSceneBuilder = new RenderingSceneBuilder();
var cameraEntity = renderingSceneBuilder.AddCamera();
var scene = renderingSceneBuilder.Build();
// Act
renderingSystem.RenderScene(scene);
// Assert
var cameraComponent = cameraEntity.GetComponent<CameraComponent>();
Assert.That(cameraComponent.ScreenWidth, Is.EqualTo(screenWidth));
Assert.That(cameraComponent.ScreenHeight, Is.EqualTo(screenHeight));
}
[Test]
public void RenderScene_ShouldRenderEntityTransformedWithParentTransform_WhenEntityHasParentWithTransform2DComponent()
{
// Arrange
var renderingSystem = GetRenderingSystem();
var renderingSceneBuilder = new RenderingSceneBuilder();
renderingSceneBuilder.AddCamera();
var (parentEntity, childEntity) = renderingSceneBuilder.AddParentEllipseWithChildEllipse();
var scene = renderingSceneBuilder.Build();
var parentExpectedTransform = parentEntity.Get2DTransformationMatrix();
var childExpectedTransform = parentExpectedTransform * childEntity.Get2DTransformationMatrix();
// Act
renderingSystem.RenderScene(scene);
// Assert
var parentEllipseRenderer = parentEntity.GetComponent<EllipseRendererComponent>();
_renderer2D.Received(1).RenderEllipse(new Ellipse(parentEllipseRenderer.RadiusX, parentEllipseRenderer.RadiusY), parentEllipseRenderer.Color,
parentEllipseRenderer.FillInterior, parentExpectedTransform);
var childEllipseRenderer = childEntity.GetComponent<EllipseRendererComponent>();
_renderer2D.Received(1).RenderEllipse(new Ellipse(childEllipseRenderer.RadiusX, childEllipseRenderer.RadiusY), childEllipseRenderer.Color,
childEllipseRenderer.FillInterior, childExpectedTransform);
}
[Test]
public void RenderScene_ShouldDrawDebugInformation()
{
// Arrange
var renderingSystem = GetRenderingSystem();
var renderingSceneBuilder = new RenderingSceneBuilder();
renderingSceneBuilder.AddCamera();
var entity = renderingSceneBuilder.AddSprite();
var scene = renderingSceneBuilder.Build();
// Act
renderingSystem.RenderScene(scene);
// Assert
Received.InOrder(() =>
{
_renderer2D.RenderSprite(entity.GetSprite(), entity.Get2DTransformationMatrix());
_debugRendererForRenderingSystem.Received(1).DrawDebugInformation(_renderer2D, Matrix3x3.Identity);
});
}
private RenderingSystem GetRenderingSystem()
{
return new RenderingSystem(
_renderingBackend,
_renderingConfigurationBuilder.Build(),
_aggregatedDiagnosticInfoProvider,
_debugRendererForRenderingSystem
);
}
private void SetupVSync(bool enableVSync)
{
_renderingConfigurationBuilder.WithEnableVSync(enableVSync);
}
private void SetupSortingLayers(params string[] sortingLayers)
{
_renderingConfigurationBuilder.WithSortingLayersOrder(sortingLayers);
}
private static DiagnosticInfo GetRandomDiagnosticInfo()
{
return new DiagnosticInfo(Guid.NewGuid().ToString(), Guid.NewGuid().ToString());
}
private class RenderingSceneBuilder
{
private readonly Scene _scene = TestSceneFactory.Create();
public Entity AddCamera(Transform2DComponent? transformComponent = null)
{
var entity = new Entity();
entity.AddComponent(transformComponent ?? Transform2DComponent.CreateDefault());
entity.AddComponent(new CameraComponent
{
ViewRectangle = new Vector2(ScreenWidth, ScreenHeight)
});
_scene.AddEntity(entity);
return entity;
}
public Entity AddSprite(
Transform2DComponent? transformComponent = null,
int orderInLayer = 0,
string sortingLayerName = RenderingConfiguration.DefaultSortingLayerName,
bool visible = true)
{
var entity = new Entity();
entity.AddComponent(transformComponent ?? RandomTransform2DComponent());
entity.AddComponent(new SpriteRendererComponent
{
Sprite = new Sprite(Substitute.For<ITexture>()),
OrderInLayer = orderInLayer,
SortingLayerName = sortingLayerName,
Visible = visible
});
_scene.AddEntity(entity);
return entity;
}
public Entity AddText()
{
var entity = new Entity();
entity.AddComponent(RandomTransform2DComponent());
entity.AddComponent(new TextRendererComponent
{
Text = Utils.Random.GetString(),
FontSize = FontSize.FromPoints(Utils.Random.NextDouble()),
Color = Color.FromArgb(Utils.Random.Next())
});
_scene.AddEntity(entity);
return entity;
}
public Entity AddRectangle()
{
var entity = new Entity();
entity.AddComponent(RandomTransform2DComponent());
entity.AddComponent(new RectangleRendererComponent
{
Dimension = Utils.RandomVector2(),
Color = Color.FromArgb(Utils.Random.Next()),
FillInterior = Utils.Random.NextBool()
});
_scene.AddEntity(entity);
return entity;
}
public Entity AddEllipse()
{
var entity = CreateEllipse();
_scene.AddEntity(entity);
return entity;
}
public (Entity parent, Entity child) AddParentEllipseWithChildEllipse()
{
var parent = CreateEllipse();
var child = CreateEllipse();
parent.AddChild(child);
_scene.AddEntity(parent);
return (parent, child);
}
public Scene Build()
{
return _scene;
}
private static Transform2DComponent RandomTransform2DComponent()
{
return new Transform2DComponent
{
Translation = Utils.RandomVector2(),
Rotation = Utils.Random.NextDouble(),
Scale = Utils.RandomVector2()
};
}
private static Entity CreateEllipse()
{
var entity = new Entity();
entity.AddComponent(RandomTransform2DComponent());
entity.AddComponent(new EllipseRendererComponent
{
RadiusX = Utils.Random.NextDouble(),
RadiusY = Utils.Random.NextDouble(),
Color = Color.FromArgb(Utils.Random.Next()),
FillInterior = Utils.Random.NextBool()
});
return entity;
}
}
}
internal static class EntityExtensions
{
public static Sprite GetSprite(this Entity entity) => entity.GetComponent<SpriteRendererComponent>().Sprite ??
throw new ArgumentException("Entity must have SpriteRendererComponent with non-null Sprite.");
public static Matrix3x3 Get2DTransformationMatrix(this Entity entity) => entity.GetComponent<Transform2DComponent>().ToMatrix();
}
} | 42.651102 | 156 | 0.619176 | [
"MIT"
] | dawidkomorowski/geisha | test/Geisha.Engine.UnitTests/Rendering/Systems/RenderingSystemTests.cs | 32,886 | C# |
namespace Scout
{
partial class BaseDialog
{
/// <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.SuspendLayout();
//
// BaseDialog
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.WhiteSmoke;
this.ClientSize = new System.Drawing.Size(292, 266);
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "BaseDialog";
this.Text = "BaseDialog";
this.ResumeLayout(false);
}
#endregion
}
} | 28.22449 | 102 | 0.596529 | [
"MIT"
] | eng/luckymonk-scout | BaseDialog.Designer.cs | 1,383 | C# |
using System.Collections.Generic;
using System.Threading.Tasks;
using Volo.Abp.Domain.Repositories;
namespace Light.Abp.DicManagement
{
public interface IComplexDicRepository : IRepository<ComplexDic, int>
{
Task<List<string>> GetCategoriesAsync();
Task<List<ComplexDic>> GetListByCategoryAsync(string category);
}
} | 26.692308 | 73 | 0.74928 | [
"MIT"
] | seventh88/abp-dic-management | src/Light.Abp.DicManagement.Domain/ComplexDic/IComplexDicRepository.cs | 349 | C# |
using System;
using System.Windows.Forms;
using System.IO;
using System.Linq;
using Aerial;
using System.Diagnostics;
using System.Collections.Generic;
using System.Net;
using System.Web.Script.Serialization;
namespace ScreenSaver
{
public partial class SettingsForm : Form
{
public SettingsForm()
{
InitializeComponent();
LoadSettings();
//timer to update the number of current downloads every second
var myTimer = new Timer();
myTimer.Tick += new EventHandler(updateNumCurrDownloads);
myTimer.Interval = 1 * 1000; //1 second
myTimer.Start();
}
/// <summary>
/// Load display text from the Registry
/// </summary>
private void LoadSettings()
{
var settings = new RegSettings();
chkDifferentMonitorMovies.Checked = settings.DifferentMoviesOnDual;
chkUseTimeOfDay.Checked = settings.UseTimeOfDay;
chkMultiscreenDisabled.Checked = settings.MultiscreenDisabled;
chkCacheVideos.Checked = settings.CacheVideos;
if(settings.CacheLocation == null || settings.CacheLocation == "")
{
txtCacheFolderPath.Text = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Aerial").ToString();
}
else
{
txtCacheFolderPath.Text = settings.CacheLocation;
}
if (String.IsNullOrEmpty(settings.JsonURL))
{
changeVideoSourceText.Text = AerialGlobalVars.appleVideosURI;
} else
{
changeVideoSourceText.Text = settings.JsonURL;
}
changeCacheLocationButton.Enabled = settings.CacheVideos;
ShowSpace();
PopulateChosenVideoGroup();
InitPlayer();
}
private void InitPlayer()
{
this.player.enableContextMenu = false;
this.player.settings.autoStart = true;
this.player.settings.enableErrorDialogs = true;
this.player.stretchToFit = true;
this.player.uiMode = "none";
}
private void PopulateChosenVideoGroup()
{
var movies = AerialContext.GetAllMovies();
movies.Sort();
if (movies.Count == 0) return; // error
AddHumanNumbers(movies);
var selected = new RegSettings().ChosenMovies.Split(';').ToList();
tvChosen.BuildTree(movies, selected);
}
private void tvChosen_AfterSelect(object sender, TreeViewEventArgs e)
{
Trace.WriteLine("Selected tree element " + e.Node.FullPath);
if (cbLivePreview.Checked && e.Node.FullPath.Contains("\\"))
{
string url = tvChosen.GetUrl(e.Node.FullPath);
player.URL = Caching.TryHit(url);
}
}
private static void AddHumanNumbers(List<Asset> movies)
{
int n = 1;
for (int i = 1; i < movies.Count; i++)
{
if (movies[i - 1].ShortName() == movies[i].ShortName())
{
movies[i - 1].numeric = n;
n++;
movies[i].numeric = n;
}
else
{
if (n != 1)
{
movies[i - 1].numeric = n;
n = 1;
movies[i].numeric = n;
}
else
{
movies[i - 1].numeric = 0;
movies[i].numeric = n;
}
}
}
if (movies.Count > 0 && movies.Last().numeric == 1) movies.Last().numeric = 0;
}
void HideChosenVideoGroup()
{
// while developing
tabs.TabPages.Remove(tabAbout);
grpChosenVideos.Hide();
}
private void updateNumCurrDownloads(object sender, EventArgs e)
{
numOfCurrDown_lbl.Text = "# of files downloading: " + Caching.NumOfCurrentDownloads;
}
private void ShowSpace()
{
var cacheSize = NativeMethods.GetExplorerFileSize(Caching.GetDirectorySize());
lblCacheSize.Text = "Current Cache Size: " + cacheSize;
var cacheFree = NativeMethods.GetExplorerFileSize(Caching.CacheSpace());
lblFreeSpace.Text = "Free Space Available on drive: " + cacheFree;
}
/// <summary>
/// Save text into the Registry.
/// </summary>
private void SaveSettings()
{
var settings = new RegSettings();
settings.DifferentMoviesOnDual = chkDifferentMonitorMovies.Checked;
settings.UseTimeOfDay = chkUseTimeOfDay.Checked;
settings.MultiscreenDisabled = chkMultiscreenDisabled.Checked;
settings.CacheVideos = chkCacheVideos.Checked;
string oldCacheDirectory = settings.CacheLocation;
settings.CacheLocation = txtCacheFolderPath.Text;
settings.JsonURL = changeVideoSourceText.Text;
settings.ChosenMovies = tvChosen.ConcatChosenEntities();
settings.SaveSettings();
Caching.UpdateCachePath(oldCacheDirectory, settings.CacheLocation);
}
private void okButton_Click(object sender, EventArgs e)
{
SaveSettings();
Close();
}
private void cancelButton_Click(object sender, EventArgs e)
{
Close();
}
private void changeCacheLocationButton_Click(object sender, EventArgs e)
{
folderBrowserDialog.SelectedPath = txtCacheFolderPath.Text;
DialogResult result = folderBrowserDialog.ShowDialog();
if (result == DialogResult.OK)
{
txtCacheFolderPath.Text = folderBrowserDialog.SelectedPath;
}
ShowSpace();
}
private void chkCacheVideos_CheckedChanged(object sender, EventArgs e)
{
changeCacheLocationButton.Enabled = chkCacheVideos.Checked;
}
private void SettingsForm_Load(object sender, EventArgs e)
{
this.lblVersion.Text = "Current Version " + AssemblyVersion.ExecutingAssemblyVersion + " (" + AssemblyVersion.CompileDate.ToShortDateString() + ")";
}
private void lblVersion_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
ProcessStartInfo sInfo = new ProcessStartInfo(getLatestReleaseURI());
Process.Start(sInfo);
}
private void btnOpenCache_Click(object sender, EventArgs e)
{
Process.Start(Caching.CacheFolder);
}
private void btnPurgeCache_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Are you sure you want to delete all cached files?", "Delete Cache?") == DialogResult.OK)
{
Caching.DeleteCache();
}
ShowSpace();
}
private void timerDiskUpdate_Tick(object sender, EventArgs e)
{
ShowSpace();
}
private string getLatestReleaseURI()
{
string releaseData = "";
using (WebClient w = new WebClient())
{
w.Headers.Add("User-Agent: Other"); //github will give a 403 if we don't define the user agent
try
{
releaseData = w.DownloadString(AerialGlobalVars.githubLatestReleaseDetails);
} catch (WebException)
{
//if we have an error reading the release data, just use the standard URL for all releases (AKA do nothing here)
}
}
var deserializedData = new JavaScriptSerializer().Deserialize<dynamic>(releaseData);
string githubURL = "";
if (String.IsNullOrEmpty(releaseData))
{
githubURL = AerialGlobalVars.githubAllReleases; //URL for all releases
} else
{
githubURL = deserializedData["html_url"];
}
return githubURL;
}
private void videoSourceResetButton_Click(object sender, EventArgs e)
{
changeVideoSourceText.Text = AerialGlobalVars.appleVideosURI;
}
private void SetToFourK_btn_Click(object sender, EventArgs e)
{
changeVideoSourceText.Text = AerialGlobalVars.applefourKVideoURI;
}
private void fullDownloadBtn_Click(object sender, EventArgs e)
{
var movies = AerialContext.GetAllMovies();
var cacheFree = NativeMethods.GetExplorerFileSize(Caching.CacheSpace());
if (MessageBox.Show("Downloading all videos may take over 10GB of space, do you want to procede? " +
"(You currently have " + cacheFree + " of space free)", "Download?", MessageBoxButtons.YesNo) != DialogResult.Yes)
{
//don't download if user cancels
return;
}
try
{
foreach (var movie in movies)
{
if (!Caching.IsHit(movie.url))
{
Caching.StartDelayedCache(movie.url);
Trace.WriteLine("Downloading " + movie.url);
} else
{
Trace.WriteLine(movie.url + " is already cached");
}
}
} catch (WebException err)
{
Trace.WriteLine("Error downloading all videos: " + err.ToString());
}
}
}
}
| 33.20598 | 160 | 0.543572 | [
"MIT"
] | gingoi/Aerial | ScreenSaver/SettingsForm.cs | 9,997 | C# |
using Bytes2you.Validation;
using Dealership.Common.Enums;
using Dealership.Contracts;
namespace Dealership.Models
{
public class Car : Vehicle, ICar
{
private int seats;
public Car(string mark, string model, decimal price, int seats)
: base(4, VehicleType.Car, mark, model, price)
{
this.Seats = seats;
}
public int Seats
{
get
{
return this.seats;
}
set
{
Guard.WhenArgument(value, "seats").IsLessThan(0).IsGreaterThan(10).Throw();
this.seats = value;
}
}
public override string ToString()
{
return base.ToString() + $" Seats: {this.Seats}\r\n";
}
}
}
| 23.764706 | 91 | 0.501238 | [
"MIT"
] | Infra1515/TelerikAcademyProblems | Telerik Academy Alpha/OOP/Workshops/Workshop3 - Car dealership/Dealership-Skeleton/Dealership/Models/Car.cs | 810 | C# |
using System;
using Rapidity.Http.Configurations;
namespace Rapidity.Http.Attributes
{
/// <summary>
///
/// </summary>
public static class AttributeExtension
{
/// <summary>
///
/// </summary>
/// <param name="attribute"></param>
/// <returns></returns>
public static CacheOption GetCacheOption(this CacheAttribute attribute)
{
var option = new CacheOption
{
Enabled = attribute.Enabled,
};
if (attribute.ExpireIn != null)
option.ExpireIn = attribute.ExpireIn;
return option;
}
/// <summary>
///
/// </summary>
/// <param name="attribute"></param>
/// <returns></returns>
public static RetryOption GetRetryOption(this RetryAttribute attribute)
{
return new RetryOption
{
RetryStatusCodes = attribute.RetryStatusCodes,
TotalTimeout = attribute.TotalTimeout,
TransientErrorRetry = attribute.TransientErrorRetry,
WaitIntervals = attribute.WaitIntervals
};
}
}
} | 28.116279 | 79 | 0.529363 | [
"MIT"
] | zhangmingjian/RapidityHttp | src/Attributes/AttributeExtension.cs | 1,211 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MenuScript : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}
| 15.526316 | 52 | 0.623729 | [
"MIT"
] | SonKatarina23/HellYea | Assets/Script/MenuScript.cs | 297 | C# |
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using Troubleshooter.Constants;
namespace Troubleshooter;
public static class PageUtility
{
private static readonly Regex pathRegex = new(@"]\(([\w /%.]+)\)", RegexOptions.Compiled);
private static readonly Regex linkRegex = new(@"]\((https?:\/\/[\w/%#?.@_\+~=&()]+)\)", RegexOptions.Compiled);
private static readonly Regex embedsRegex = new(@"<<([\w /%.]+)>>", RegexOptions.Compiled);
private static readonly Regex localImagesRegex = new(@"!\[[^\]]*\]\((?!http)(.*?)\s*(""(?:.*[^""])"")?\s*\)", RegexOptions.Compiled);
/// <summary>
/// Parse markdown text looking for page links
/// </summary>
/// <param name="text">The markdown</param>
/// <param name="path">The file path</param>
/// <returns></returns>
public static IEnumerable<(string fullPath, Group group)> LinksAsFullPaths(string text, string path)
{
string directory = Path.GetDirectoryName(path) ?? string.Empty;
MatchCollection matches = pathRegex.Matches(text);
for (int i = 0; i < matches.Count; i++)
{
Group group = matches[i].Groups[1];
string match = group.Value.ToConsistentPath().ToUnTokenized();
string fullPath = Path.GetFullPath(Path.Combine(directory, match));
yield return (fullPath, group);
}
}
/// <summary>
/// Parse markdown text looking for external links
/// </summary>
/// <param name="text">The markdown</param>
/// <returns></returns>
public static IEnumerable<(string url, Group group)> ExternalLinkUrls(string text)
{
//TODO someone who is better at regex than me can feel free to make this nicer.
// - I have no need for this other than debugging at the moment, so the fact that it captures brackets following links also does not currently matter.
MatchCollection matches = linkRegex.Matches(text);
for (int i = 0; i < matches.Count; i++)
{
Group group = matches[i].Groups[1];
string url = group.Value;
yield return (url, group);
}
}
public static IEnumerable<(string localPath, Group group)> EmbedsAsLocalEmbedPaths(string text)
{
MatchCollection matches = embedsRegex.Matches(text);
for (int i = 0; i < matches.Count; i++)
{
Group group = matches[i].Groups[1];
yield return (group.Value.ToConsistentPath().ToUnTokenized(), group);
}
}
public static IEnumerable<(string localPath, Group group)> LocalImagesAsRootPaths(string text, bool finalisePath = true)
{
MatchCollection matches = localImagesRegex.Matches(text);
for (int i = 0; i < matches.Count; i++)
{
Group group = matches[i].Groups[1];
yield return (finalisePath ? group.Value.FinalisePath() : group.Value, group);
}
}
public static string LocalEmbedToFullPath(string embedPath, Site site)
=> Path.GetFullPath(Path.Combine(site.EmbedsDirectory, embedPath));
} | 37.905405 | 152 | 0.695544 | [
"MIT"
] | vertxxyz/help.vertx.xyz | Troubleshooter/Source/Utils/PageUtility.cs | 2,805 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Reflection;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NUnit.Framework;
using Assert = NUnit.Framework.Assert;
using Description = NUnit.Framework.DescriptionAttribute;
using TestContext = Microsoft.VisualStudio.TestTools.UnitTesting.TestContext;
using CsQuery;
using CsQuery.Utility;
namespace CsQuery.Tests.Core.Selectors
{
[TestFixture, TestClass]
public class AttributeSelectors: CsQueryTest
{
public override void FixtureSetUp()
{
base.FixtureSetUp();
Dom = TestDom("TestHtml2");
}
[Test,TestMethod]
public void StartsWithOrHyphen()
{
CQ res = Dom.Select("[lang|=en]");
Assert.AreEqual(2, res.Length);
res = Dom.Select("[lang|=en-uk]");
Assert.AreEqual(1, res.Length);
}
[Test, TestMethod]
public void ContainsWord()
{
var dom = CQ.Create(@"<div data-val='quick brown' id='1'></div>
<div data-val='quick brown fox jumps' id='2'></div>
<div data-val id='3'></div>");
Assert.AreEqual(Arrays.String("1", "2"), dom["[data-val~=brown]"].Select(item=>item.Id));
Assert.AreEqual(Arrays.String("2"), dom["[data-val~=fox]"].Select(item => item.Id));
Assert.AreEqual(0, dom["[data-val~=lazy]"].Length);
}
/// <summary>
/// Default type value. Although "type='text'" is the default for input elements, CSS selectors only select on
/// attribute and should not return it.
/// </summary>
[Test, TestMethod]
public void DefaultTypeValue()
{
var dom = CQ.CreateDocument(@"<input id='input1' /><input id='input2' type='text' />");
Assert.AreEqual(1,dom["input[type=text]"].Length );
Assert.AreEqual(1,dom["[type=text]"].Length );
Assert.IsFalse(dom["#input1"].Is("[type=text]"));
Assert.IsTrue(dom["#input2"].Is("[type=text]"));
}
}
} | 29.821918 | 118 | 0.583372 | [
"MIT"
] | 842549829/CsQuery | source/CsQuery.Tests/Core/Selectors/AttributeSelectors.cs | 2,179 | C# |
/*
* OpenDoc_API-文档访问
*
* API to access AnyShare 如有任何疑问,可到开发者社区提问:https://developers.aishu.cn # Authentication - 调用需要鉴权的API,必须将token放在HTTP header中:\"Authorization: Bearer ACCESS_TOKEN\" - 对于GET请求,除了将token放在HTTP header中,也可以将token放在URL query string中:\"tokenid=ACCESS_TOKEN\"
*
* The version of the OpenAPI document: 6.0.10
*
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using OpenAPIDateConverter = AnyShareSDK.Client.OpenAPIDateConverter;
namespace AnyShareSDK.Model
{
/// <summary>
/// LinkSetReq
/// </summary>
[DataContract]
public partial class LinkSetReq : IEquatable<LinkSetReq>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="LinkSetReq" /> class.
/// </summary>
[JsonConstructorAttribute]
protected LinkSetReq() { }
/// <summary>
/// Initializes a new instance of the <see cref="LinkSetReq" /> class.
/// </summary>
/// <param name="docid">待修改外链的对象gns路径 (required).</param>
/// <param name="open">如果true,返回密码,false,密码空 (required).</param>
/// <param name="endtime">到期时间,单位:微秒 (required).</param>
/// <param name="perm">权限值,值域为[1,7],具体说明参见开启外链中的描述 (required).</param>
/// <param name="limittimes">外链使用次数。 -1为无限制,不传默认-1 .</param>
public LinkSetReq(string docid = default(string), bool? open = default(bool?), long? endtime = default(long?), long? perm = default(long?), long? limittimes = default(long?))
{
this.Docid = docid;
this.Open = open;
this.Endtime = endtime;
this.Perm = perm;
this.Limittimes = limittimes;
}
/// <summary>
/// 待修改外链的对象gns路径
/// </summary>
/// <value>待修改外链的对象gns路径</value>
[DataMember(Name="docid", EmitDefaultValue=false)]
public string Docid { get; set; }
/// <summary>
/// 如果true,返回密码,false,密码空
/// </summary>
/// <value>如果true,返回密码,false,密码空</value>
[DataMember(Name="open", EmitDefaultValue=false)]
public bool? Open { get; set; }
/// <summary>
/// 到期时间,单位:微秒
/// </summary>
/// <value>到期时间,单位:微秒 </value>
[DataMember(Name="endtime", EmitDefaultValue=false)]
public long? Endtime { get; set; }
/// <summary>
/// 权限值,值域为[1,7],具体说明参见开启外链中的描述
/// </summary>
/// <value>权限值,值域为[1,7],具体说明参见开启外链中的描述</value>
[DataMember(Name="perm", EmitDefaultValue=false)]
public long? Perm { get; set; }
/// <summary>
/// 外链使用次数。 -1为无限制,不传默认-1
/// </summary>
/// <value>外链使用次数。 -1为无限制,不传默认-1 </value>
[DataMember(Name="limittimes", EmitDefaultValue=false)]
public long? Limittimes { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class LinkSetReq {\n");
sb.Append(" Docid: ").Append(Docid).Append("\n");
sb.Append(" Open: ").Append(Open).Append("\n");
sb.Append(" Endtime: ").Append(Endtime).Append("\n");
sb.Append(" Perm: ").Append(Perm).Append("\n");
sb.Append(" Limittimes: ").Append(Limittimes).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as LinkSetReq);
}
/// <summary>
/// Returns true if LinkSetReq instances are equal
/// </summary>
/// <param name="input">Instance of LinkSetReq to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(LinkSetReq input)
{
if (input == null)
return false;
return
(
this.Docid == input.Docid ||
(this.Docid != null &&
this.Docid.Equals(input.Docid))
) &&
(
this.Open == input.Open ||
(this.Open != null &&
this.Open.Equals(input.Open))
) &&
(
this.Endtime == input.Endtime ||
(this.Endtime != null &&
this.Endtime.Equals(input.Endtime))
) &&
(
this.Perm == input.Perm ||
(this.Perm != null &&
this.Perm.Equals(input.Perm))
) &&
(
this.Limittimes == input.Limittimes ||
(this.Limittimes != null &&
this.Limittimes.Equals(input.Limittimes))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.Docid != null)
hashCode = hashCode * 59 + this.Docid.GetHashCode();
if (this.Open != null)
hashCode = hashCode * 59 + this.Open.GetHashCode();
if (this.Endtime != null)
hashCode = hashCode * 59 + this.Endtime.GetHashCode();
if (this.Perm != null)
hashCode = hashCode * 59 + this.Perm.GetHashCode();
if (this.Limittimes != null)
hashCode = hashCode * 59 + this.Limittimes.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| 36.150754 | 257 | 0.534056 | [
"MIT"
] | ArtyDinosaur404/AnyShareSDK | AnyShareSDK/Model/LinkSetReq.cs | 7,726 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.