source
stringclasses 1
value | id
stringlengths 40
40
| language
stringclasses 2
values | date
stringclasses 1
value | author
stringclasses 1
value | url
stringclasses 1
value | title
stringclasses 1
value | extra
stringlengths 528
1.53k
| quality_signals
stringlengths 139
178
| text
stringlengths 6
1.05M
|
---|---|---|---|---|---|---|---|---|---|
TheStack | 33202e96162a5eadab5acdbf38efc4145772a91a | C#code:C# | {"size": 2983, "ext": "cs", "max_stars_repo_path": "src/LodeRunner.API.Test/IntegrationTests/ApiWebApplicationFactory.cs", "max_stars_repo_name": "retaildevcrews/lr", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/LodeRunner.API.Test/IntegrationTests/ApiWebApplicationFactory.cs", "max_issues_repo_name": "retaildevcrews/lr", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/LodeRunner.API.Test/IntegrationTests/ApiWebApplicationFactory.cs", "max_forks_repo_name": "retaildevcrews/lr", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 42.014084507, "max_line_length": 157, "alphanum_fraction": 0.6614146832} | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System;
using System.Threading;
using LodeRunner.API.Core;
using LodeRunner.API.Middleware;
using LodeRunner.Core;
using LodeRunner.Core.Interfaces;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Swashbuckle.AspNetCore.SwaggerGen;
namespace LodeRunner.API.Test.IntegrationTests
{
/// <summary>
/// Represents ApiWebApplicationFactory.
/// </summary>
/// <typeparam name="TStartup">The type of the startup.</typeparam>
public class ApiWebApplicationFactory<TStartup> : WebApplicationFactory<TStartup>
where TStartup : class
{
/// <summary>
/// Creates a <see cref="T:Microsoft.AspNetCore.Hosting.IWebHostBuilder" /> used to set up <see cref="T:Microsoft.AspNetCore.TestHost.TestServer" />.
/// </summary>
/// <returns>
/// A <see cref="T:Microsoft.AspNetCore.Hosting.IWebHostBuilder" /> instance.
/// </returns>
/// <remarks>
/// The default implementation of this method looks for a <c>public static IWebHostBuilder CreateWebHostBuilder(string[] args)</c>
/// method defined on the entry point of the assembly of <typeparamref name="TEntryPoint" /> and invokes it passing an empty string
/// array as arguments.
/// </remarks>
protected override IWebHostBuilder CreateWebHostBuilder()
{
var builder = WebHost.CreateDefaultBuilder()
.UseStartup<TStartup>()
// .UseTestServer()
// .UseUrls($"http://*:{8089}/")
.UseShutdownTimeout(TimeSpan.FromSeconds(10));
return builder;
}
/// <summary>
/// Gives a fixture an opportunity to configure the application before it gets built.
/// </summary>
/// <param name="builder">The <see cref="T:Microsoft.AspNetCore.Hosting.IWebHostBuilder" /> for the application.</param>
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
Config config = new ();
Secrets.LoadSecrets(config);
CancellationTokenSource cancelTokenSource = new ();
NgsaLog ngsalog = new () { Name = typeof(ApiWebApplicationFactory<TStartup>).FullName };
builder.ConfigureServices(services =>
{
services.AddSingleton<CancellationTokenSource>(cancelTokenSource);
services.AddSingleton<NgsaLog>(ngsalog);
services.AddSingleton<Config>(config);
services.AddSingleton<ICosmosConfig>(provider => provider.GetRequiredService<Config>());
});
}
}
} |
||||
TheStack | 3320dc07244e8ec5d87031680ad6452b4be8c690 | C#code:C# | {"size": 1821, "ext": "cs", "max_stars_repo_path": "samples/TestFtpServer/ServerInfo/BackgroundUploadsInfo.cs", "max_stars_repo_name": "workgroupengineering/FtpServer", "max_stars_repo_stars_event_min_datetime": "2015-10-14T05:16:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T09:05:19.000Z", "max_issues_repo_path": "samples/TestFtpServer/ServerInfo/BackgroundUploadsInfo.cs", "max_issues_repo_name": "564064202/FtpServer", "max_issues_repo_issues_event_min_datetime": "2015-10-15T17:57:41.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-10T19:58:13.000Z", "max_forks_repo_path": "samples/TestFtpServer/ServerInfo/BackgroundUploadsInfo.cs", "max_forks_repo_name": "564064202/FtpServer", "max_forks_repo_forks_event_min_datetime": "2015-12-10T12:13:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T03:51:49.000Z"} | {"max_stars_count": 351.0, "max_issues_count": 111.0, "max_forks_count": 149.0, "avg_line_length": 33.7222222222, "max_line_length": 118, "alphanum_fraction": 0.6112026359} | // <copyright file="BackgroundUploadsInfo.cs" company="Fubar Development Junker">
// Copyright (c) Fubar Development Junker. All rights reserved.
// </copyright>
using System.Collections.Generic;
using FubarDev.FtpServer.BackgroundTransfer;
namespace TestFtpServer.ServerInfo
{
/// <summary>
/// Information about the background transfer worker.
/// </summary>
public class BackgroundUploadsInfo : IExtendedModuleInfo, ISimpleModuleInfo
{
private readonly IBackgroundTransferWorker _backgroundTransferWorker;
/// <summary>
/// Initializes a new instance of the <see cref="BackgroundUploadsInfo"/>.
/// </summary>
/// <param name="backgroundTransferWorker">The background transfer worker to get the information from.</param>
public BackgroundUploadsInfo(
IBackgroundTransferWorker backgroundTransferWorker)
{
_backgroundTransferWorker = backgroundTransferWorker;
}
/// <inheritdoc />
public string Name { get; } = "background-uploads";
/// <inheritdoc />
public IEnumerable<(string label, string value)> GetInfo()
{
var states = _backgroundTransferWorker.GetStates();
yield return ("Background uploads", $"{states.Count}");
}
/// <inheritdoc />
public IEnumerable<string> GetExtendedInfo()
{
var states = _backgroundTransferWorker.GetStates();
foreach (var info in states)
{
yield return $"File {info.FileName}";
yield return $"\tStatus={info.Status}";
if (info.Transferred != null)
{
yield return $"\tTransferred={info.Transferred.Value}";
}
}
}
}
}
|
||||
TheStack | 332252358b0aa7e46f09f7b0ba906f5f01ff93b6 | C#code:C# | {"size": 300, "ext": "cs", "max_stars_repo_path": "src/MailCheck.Dkim.Evaluator/Implicit/ServiceTypeImplicitProvider.cs", "max_stars_repo_name": "ukncsc/MailCheck.Public.Dkim", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/MailCheck.Dkim.Evaluator/Implicit/ServiceTypeImplicitProvider.cs", "max_issues_repo_name": "ukncsc/MailCheck.Public.Dkim", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/MailCheck.Dkim.Evaluator/Implicit/ServiceTypeImplicitProvider.cs", "max_forks_repo_name": "ukncsc/MailCheck.Public.Dkim", "max_forks_repo_forks_event_min_datetime": "2021-04-11T09:44:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-11T09:44:38.000Z"} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": 1.0, "avg_line_length": 33.3333333333, "max_line_length": 107, "alphanum_fraction": 0.7533333333} | using MailCheck.Dkim.Evaluator.Domain;
namespace MailCheck.Dkim.Evaluator.Implicit
{
public class ServiceTypeImplicitProvider : ImplicitTagProviderStrategyBase<ServiceType>
{
public ServiceTypeImplicitProvider() : base(t => new ServiceType("*", ServiceTypeType.Any, true)){}
}
} |
||||
TheStack | 3322b6b10ea994d10ea9513ee2f02ab558981dae | C#code:C# | {"size": 24399, "ext": "cs", "max_stars_repo_path": "Informacionna_Sistema/WindowsFormsApplication1/SearchTeachers.Designer.cs", "max_stars_repo_name": "PeciSavkov/Information-System", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Informacionna_Sistema/WindowsFormsApplication1/SearchTeachers.Designer.cs", "max_issues_repo_name": "PeciSavkov/Information-System", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Informacionna_Sistema/WindowsFormsApplication1/SearchTeachers.Designer.cs", "max_forks_repo_name": "PeciSavkov/Information-System", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 56.2188940092, "max_line_length": 156, "alphanum_fraction": 0.6616254765} | namespace WindowsFormsApplication1
{
partial class SearchTeachers
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(SearchTeachers));
this.dgvTeachers = new System.Windows.Forms.DataGridView();
this.idTeacherDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.titleDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.nameDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.middlenameDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.surnameDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.officeDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.numberDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.teachersBindingSource = new System.Windows.Forms.BindingSource(this.components);
this.database1DataSet = new WindowsFormsApplication1.Database1DataSet();
this.btnSearchTch = new System.Windows.Forms.Button();
this.label1 = new System.Windows.Forms.Label();
this.teachersTableAdapter = new WindowsFormsApplication1.Database1DataSetTableAdapters.TeachersTableAdapter();
this.txtName = new System.Windows.Forms.TextBox();
this.txtSurname = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.searchNameToolStrip = new System.Windows.Forms.ToolStrip();
this.nameToolStripLabel = new System.Windows.Forms.ToolStripLabel();
this.nameToolStripTextBox = new System.Windows.Forms.ToolStripTextBox();
this.searchNameToolStripButton = new System.Windows.Forms.ToolStripButton();
this.searchSurnameToolStrip = new System.Windows.Forms.ToolStrip();
this.surnameToolStripLabel = new System.Windows.Forms.ToolStripLabel();
this.surnameToolStripTextBox = new System.Windows.Forms.ToolStripTextBox();
this.searchSurnameToolStripButton = new System.Windows.Forms.ToolStripButton();
this.searchNameSurnameToolStrip = new System.Windows.Forms.ToolStrip();
this.nameToolStripLabel1 = new System.Windows.Forms.ToolStripLabel();
this.nameToolStripTextBox1 = new System.Windows.Forms.ToolStripTextBox();
this.surnameToolStripLabel1 = new System.Windows.Forms.ToolStripLabel();
this.surnameToolStripTextBox1 = new System.Windows.Forms.ToolStripTextBox();
this.searchNameSurnameToolStripButton = new System.Windows.Forms.ToolStripButton();
this.pictureBox2 = new System.Windows.Forms.PictureBox();
this.searchNameToolStrip1 = new System.Windows.Forms.ToolStrip();
this.nameToolStripLabel2 = new System.Windows.Forms.ToolStripLabel();
this.nameToolStripTextBox2 = new System.Windows.Forms.ToolStripTextBox();
this.searchNameToolStripButton1 = new System.Windows.Forms.ToolStripButton();
((System.ComponentModel.ISupportInitialize)(this.dgvTeachers)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.teachersBindingSource)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.database1DataSet)).BeginInit();
this.searchNameToolStrip.SuspendLayout();
this.searchSurnameToolStrip.SuspendLayout();
this.searchNameSurnameToolStrip.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).BeginInit();
this.searchNameToolStrip1.SuspendLayout();
this.SuspendLayout();
//
// dgvTeachers
//
this.dgvTeachers.AllowUserToAddRows = false;
this.dgvTeachers.AllowUserToDeleteRows = false;
this.dgvTeachers.AutoGenerateColumns = false;
this.dgvTeachers.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dgvTeachers.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.idTeacherDataGridViewTextBoxColumn,
this.titleDataGridViewTextBoxColumn,
this.nameDataGridViewTextBoxColumn,
this.middlenameDataGridViewTextBoxColumn,
this.surnameDataGridViewTextBoxColumn,
this.officeDataGridViewTextBoxColumn,
this.numberDataGridViewTextBoxColumn});
this.dgvTeachers.DataSource = this.teachersBindingSource;
this.dgvTeachers.Location = new System.Drawing.Point(12, 143);
this.dgvTeachers.Name = "dgvTeachers";
this.dgvTeachers.ReadOnly = true;
this.dgvTeachers.Size = new System.Drawing.Size(645, 263);
this.dgvTeachers.TabIndex = 0;
this.dgvTeachers.Visible = false;
//
// idTeacherDataGridViewTextBoxColumn
//
this.idTeacherDataGridViewTextBoxColumn.DataPropertyName = "Id_Teacher";
this.idTeacherDataGridViewTextBoxColumn.HeaderText = "Id_Teacher";
this.idTeacherDataGridViewTextBoxColumn.Name = "idTeacherDataGridViewTextBoxColumn";
this.idTeacherDataGridViewTextBoxColumn.ReadOnly = true;
this.idTeacherDataGridViewTextBoxColumn.Visible = false;
//
// titleDataGridViewTextBoxColumn
//
this.titleDataGridViewTextBoxColumn.DataPropertyName = "Title";
this.titleDataGridViewTextBoxColumn.HeaderText = "Title";
this.titleDataGridViewTextBoxColumn.Name = "titleDataGridViewTextBoxColumn";
this.titleDataGridViewTextBoxColumn.ReadOnly = true;
//
// nameDataGridViewTextBoxColumn
//
this.nameDataGridViewTextBoxColumn.DataPropertyName = "Name";
this.nameDataGridViewTextBoxColumn.HeaderText = "Name";
this.nameDataGridViewTextBoxColumn.Name = "nameDataGridViewTextBoxColumn";
this.nameDataGridViewTextBoxColumn.ReadOnly = true;
//
// middlenameDataGridViewTextBoxColumn
//
this.middlenameDataGridViewTextBoxColumn.DataPropertyName = "Middlename";
this.middlenameDataGridViewTextBoxColumn.HeaderText = "Middlename";
this.middlenameDataGridViewTextBoxColumn.Name = "middlenameDataGridViewTextBoxColumn";
this.middlenameDataGridViewTextBoxColumn.ReadOnly = true;
//
// surnameDataGridViewTextBoxColumn
//
this.surnameDataGridViewTextBoxColumn.DataPropertyName = "Surname";
this.surnameDataGridViewTextBoxColumn.HeaderText = "Surname";
this.surnameDataGridViewTextBoxColumn.Name = "surnameDataGridViewTextBoxColumn";
this.surnameDataGridViewTextBoxColumn.ReadOnly = true;
//
// officeDataGridViewTextBoxColumn
//
this.officeDataGridViewTextBoxColumn.DataPropertyName = "Office";
this.officeDataGridViewTextBoxColumn.HeaderText = "Office";
this.officeDataGridViewTextBoxColumn.Name = "officeDataGridViewTextBoxColumn";
this.officeDataGridViewTextBoxColumn.ReadOnly = true;
//
// numberDataGridViewTextBoxColumn
//
this.numberDataGridViewTextBoxColumn.DataPropertyName = "Number";
this.numberDataGridViewTextBoxColumn.HeaderText = "Number";
this.numberDataGridViewTextBoxColumn.Name = "numberDataGridViewTextBoxColumn";
this.numberDataGridViewTextBoxColumn.ReadOnly = true;
//
// teachersBindingSource
//
this.teachersBindingSource.DataMember = "Teachers";
this.teachersBindingSource.DataSource = this.database1DataSet;
//
// database1DataSet
//
this.database1DataSet.DataSetName = "Database1DataSet";
this.database1DataSet.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema;
//
// btnSearchTch
//
this.btnSearchTch.Font = new System.Drawing.Font("Arial", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
this.btnSearchTch.Location = new System.Drawing.Point(16, 62);
this.btnSearchTch.Name = "btnSearchTch";
this.btnSearchTch.Size = new System.Drawing.Size(150, 50);
this.btnSearchTch.TabIndex = 1;
this.btnSearchTch.Text = "Търси";
this.btnSearchTch.UseVisualStyleBackColor = true;
this.btnSearchTch.Click += new System.EventHandler(this.btnSearchTch_Click);
//
// label1
//
this.label1.AutoSize = true;
this.label1.Font = new System.Drawing.Font("Arial", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
this.label1.Location = new System.Drawing.Point(12, 9);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(47, 19);
this.label1.TabIndex = 2;
this.label1.Text = "Име:";
//
// teachersTableAdapter
//
this.teachersTableAdapter.ClearBeforeFill = true;
//
// txtName
//
this.txtName.Location = new System.Drawing.Point(106, 10);
this.txtName.Name = "txtName";
this.txtName.Size = new System.Drawing.Size(146, 20);
this.txtName.TabIndex = 3;
//
// txtSurname
//
this.txtSurname.Location = new System.Drawing.Point(106, 36);
this.txtSurname.Name = "txtSurname";
this.txtSurname.Size = new System.Drawing.Size(146, 20);
this.txtSurname.TabIndex = 5;
//
// label2
//
this.label2.AutoSize = true;
this.label2.Font = new System.Drawing.Font("Arial", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
this.label2.Location = new System.Drawing.Point(12, 35);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(88, 19);
this.label2.TabIndex = 4;
this.label2.Text = "Фамилия:";
//
// searchNameToolStrip
//
this.searchNameToolStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.nameToolStripLabel,
this.nameToolStripTextBox,
this.searchNameToolStripButton});
this.searchNameToolStrip.Location = new System.Drawing.Point(0, 0);
this.searchNameToolStrip.Name = "searchNameToolStrip";
this.searchNameToolStrip.Size = new System.Drawing.Size(677, 25);
this.searchNameToolStrip.TabIndex = 6;
this.searchNameToolStrip.Text = "searchNameToolStrip";
this.searchNameToolStrip.Visible = false;
//
// nameToolStripLabel
//
this.nameToolStripLabel.Name = "nameToolStripLabel";
this.nameToolStripLabel.Size = new System.Drawing.Size(42, 22);
this.nameToolStripLabel.Text = "Name:";
//
// nameToolStripTextBox
//
this.nameToolStripTextBox.Name = "nameToolStripTextBox";
this.nameToolStripTextBox.Size = new System.Drawing.Size(100, 25);
//
// searchNameToolStripButton
//
this.searchNameToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.searchNameToolStripButton.Name = "searchNameToolStripButton";
this.searchNameToolStripButton.Size = new System.Drawing.Size(78, 22);
this.searchNameToolStripButton.Text = "SearchName";
this.searchNameToolStripButton.Click += new System.EventHandler(this.searchNameToolStripButton_Click);
//
// searchSurnameToolStrip
//
this.searchSurnameToolStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.surnameToolStripLabel,
this.surnameToolStripTextBox,
this.searchSurnameToolStripButton});
this.searchSurnameToolStrip.Location = new System.Drawing.Point(0, 0);
this.searchSurnameToolStrip.Name = "searchSurnameToolStrip";
this.searchSurnameToolStrip.Size = new System.Drawing.Size(677, 25);
this.searchSurnameToolStrip.TabIndex = 7;
this.searchSurnameToolStrip.Text = "searchSurnameToolStrip";
this.searchSurnameToolStrip.Visible = false;
//
// surnameToolStripLabel
//
this.surnameToolStripLabel.Name = "surnameToolStripLabel";
this.surnameToolStripLabel.Size = new System.Drawing.Size(57, 22);
this.surnameToolStripLabel.Text = "Surname:";
//
// surnameToolStripTextBox
//
this.surnameToolStripTextBox.Name = "surnameToolStripTextBox";
this.surnameToolStripTextBox.Size = new System.Drawing.Size(100, 25);
//
// searchSurnameToolStripButton
//
this.searchSurnameToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.searchSurnameToolStripButton.Name = "searchSurnameToolStripButton";
this.searchSurnameToolStripButton.Size = new System.Drawing.Size(93, 22);
this.searchSurnameToolStripButton.Text = "SearchSurname";
this.searchSurnameToolStripButton.Click += new System.EventHandler(this.searchSurnameToolStripButton_Click);
//
// searchNameSurnameToolStrip
//
this.searchNameSurnameToolStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.nameToolStripLabel1,
this.nameToolStripTextBox1,
this.surnameToolStripLabel1,
this.surnameToolStripTextBox1,
this.searchNameSurnameToolStripButton});
this.searchNameSurnameToolStrip.Location = new System.Drawing.Point(0, 0);
this.searchNameSurnameToolStrip.Name = "searchNameSurnameToolStrip";
this.searchNameSurnameToolStrip.Size = new System.Drawing.Size(677, 25);
this.searchNameSurnameToolStrip.TabIndex = 8;
this.searchNameSurnameToolStrip.Text = "searchNameSurnameToolStrip";
this.searchNameSurnameToolStrip.Visible = false;
//
// nameToolStripLabel1
//
this.nameToolStripLabel1.Name = "nameToolStripLabel1";
this.nameToolStripLabel1.Size = new System.Drawing.Size(42, 22);
this.nameToolStripLabel1.Text = "Name:";
//
// nameToolStripTextBox1
//
this.nameToolStripTextBox1.Name = "nameToolStripTextBox1";
this.nameToolStripTextBox1.Size = new System.Drawing.Size(100, 25);
//
// surnameToolStripLabel1
//
this.surnameToolStripLabel1.Name = "surnameToolStripLabel1";
this.surnameToolStripLabel1.Size = new System.Drawing.Size(57, 22);
this.surnameToolStripLabel1.Text = "Surname:";
//
// surnameToolStripTextBox1
//
this.surnameToolStripTextBox1.Name = "surnameToolStripTextBox1";
this.surnameToolStripTextBox1.Size = new System.Drawing.Size(100, 25);
//
// searchNameSurnameToolStripButton
//
this.searchNameSurnameToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.searchNameSurnameToolStripButton.Name = "searchNameSurnameToolStripButton";
this.searchNameSurnameToolStripButton.Size = new System.Drawing.Size(125, 22);
this.searchNameSurnameToolStripButton.Text = "SearchNameSurname";
this.searchNameSurnameToolStripButton.Click += new System.EventHandler(this.searchNameSurnameToolStripButton_Click);
//
// pictureBox2
//
this.pictureBox2.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox2.Image")));
this.pictureBox2.Location = new System.Drawing.Point(172, 62);
this.pictureBox2.Name = "pictureBox2";
this.pictureBox2.Size = new System.Drawing.Size(41, 40);
this.pictureBox2.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
this.pictureBox2.TabIndex = 11;
this.pictureBox2.TabStop = false;
//
// searchNameToolStrip1
//
this.searchNameToolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.nameToolStripLabel2,
this.nameToolStripTextBox2,
this.searchNameToolStripButton1});
this.searchNameToolStrip1.Location = new System.Drawing.Point(0, 0);
this.searchNameToolStrip1.Name = "searchNameToolStrip1";
this.searchNameToolStrip1.Size = new System.Drawing.Size(677, 25);
this.searchNameToolStrip1.TabIndex = 12;
this.searchNameToolStrip1.Text = "searchNameToolStrip1";
this.searchNameToolStrip1.Visible = false;
//
// nameToolStripLabel2
//
this.nameToolStripLabel2.Name = "nameToolStripLabel2";
this.nameToolStripLabel2.Size = new System.Drawing.Size(42, 22);
this.nameToolStripLabel2.Text = "Name:";
//
// nameToolStripTextBox2
//
this.nameToolStripTextBox2.Name = "nameToolStripTextBox2";
this.nameToolStripTextBox2.Size = new System.Drawing.Size(100, 23);
//
// searchNameToolStripButton1
//
this.searchNameToolStripButton1.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.searchNameToolStripButton1.Name = "searchNameToolStripButton1";
this.searchNameToolStripButton1.Size = new System.Drawing.Size(78, 19);
this.searchNameToolStripButton1.Text = "SearchName";
this.searchNameToolStripButton1.Click += new System.EventHandler(this.searchNameToolStripButton1_Click);
//
// SearchTeachers
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(677, 426);
this.Controls.Add(this.searchNameToolStrip1);
this.Controls.Add(this.pictureBox2);
this.Controls.Add(this.searchNameToolStrip);
this.Controls.Add(this.searchSurnameToolStrip);
this.Controls.Add(this.searchNameSurnameToolStrip);
this.Controls.Add(this.txtSurname);
this.Controls.Add(this.label2);
this.Controls.Add(this.txtName);
this.Controls.Add(this.label1);
this.Controls.Add(this.btnSearchTch);
this.Controls.Add(this.dgvTeachers);
this.Name = "SearchTeachers";
this.Text = "Търсене на учители";
this.Load += new System.EventHandler(this.SearchTeachers_Load);
((System.ComponentModel.ISupportInitialize)(this.dgvTeachers)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.teachersBindingSource)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.database1DataSet)).EndInit();
this.searchNameToolStrip.ResumeLayout(false);
this.searchNameToolStrip.PerformLayout();
this.searchSurnameToolStrip.ResumeLayout(false);
this.searchSurnameToolStrip.PerformLayout();
this.searchNameSurnameToolStrip.ResumeLayout(false);
this.searchNameSurnameToolStrip.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).EndInit();
this.searchNameToolStrip1.ResumeLayout(false);
this.searchNameToolStrip1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.DataGridView dgvTeachers;
private System.Windows.Forms.Button btnSearchTch;
private System.Windows.Forms.Label label1;
private Database1DataSet database1DataSet;
private System.Windows.Forms.BindingSource teachersBindingSource;
private Database1DataSetTableAdapters.TeachersTableAdapter teachersTableAdapter;
private System.Windows.Forms.DataGridViewTextBoxColumn idTeacherDataGridViewTextBoxColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn titleDataGridViewTextBoxColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn nameDataGridViewTextBoxColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn middlenameDataGridViewTextBoxColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn surnameDataGridViewTextBoxColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn officeDataGridViewTextBoxColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn numberDataGridViewTextBoxColumn;
private System.Windows.Forms.TextBox txtName;
private System.Windows.Forms.TextBox txtSurname;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.ToolStrip searchNameToolStrip;
private System.Windows.Forms.ToolStripLabel nameToolStripLabel;
private System.Windows.Forms.ToolStripTextBox nameToolStripTextBox;
private System.Windows.Forms.ToolStripButton searchNameToolStripButton;
private System.Windows.Forms.ToolStrip searchSurnameToolStrip;
private System.Windows.Forms.ToolStripLabel surnameToolStripLabel;
private System.Windows.Forms.ToolStripTextBox surnameToolStripTextBox;
private System.Windows.Forms.ToolStripButton searchSurnameToolStripButton;
private System.Windows.Forms.ToolStrip searchNameSurnameToolStrip;
private System.Windows.Forms.ToolStripLabel nameToolStripLabel1;
private System.Windows.Forms.ToolStripTextBox nameToolStripTextBox1;
private System.Windows.Forms.ToolStripLabel surnameToolStripLabel1;
private System.Windows.Forms.ToolStripTextBox surnameToolStripTextBox1;
private System.Windows.Forms.ToolStripButton searchNameSurnameToolStripButton;
private System.Windows.Forms.PictureBox pictureBox2;
private System.Windows.Forms.ToolStrip searchNameToolStrip1;
private System.Windows.Forms.ToolStripLabel nameToolStripLabel2;
private System.Windows.Forms.ToolStripTextBox nameToolStripTextBox2;
private System.Windows.Forms.ToolStripButton searchNameToolStripButton1;
}
} |
||||
TheStack | 3323053fde9b003523329bcac71462f19bd3d523 | C#code:C# | {"size": 108, "ext": "cs", "max_stars_repo_path": "WoWDatabaseEditor/MainModule.cs", "max_stars_repo_name": "Crypticaz/WoWDatabaseEditor", "max_stars_repo_stars_event_min_datetime": "2021-12-06T16:01:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-06T16:01:03.000Z", "max_issues_repo_path": "WoWDatabaseEditor/MainModule.cs", "max_issues_repo_name": "gitter-badger/WoWDatabaseEditor", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "WoWDatabaseEditor/MainModule.cs", "max_forks_repo_name": "gitter-badger/WoWDatabaseEditor", "max_forks_repo_forks_event_min_datetime": "2020-03-14T08:54:27.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-14T08:54:27.000Z"} | {"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": 1.0, "avg_line_length": 13.5, "max_line_length": 40, "alphanum_fraction": 0.6944444444} | using WDE.Module;
namespace WoWDatabaseEditorCore
{
public class MainModule : ModuleBase
{
}
} |
||||
TheStack | 3326b27f208ede123e97760f045a9d9b4a03531c | C#code:C# | {"size": 899, "ext": "cs", "max_stars_repo_path": "ZuounMenu/Database/Usuario.cs", "max_stars_repo_name": "gmonteeeiro/manutencao-estoque", "max_stars_repo_stars_event_min_datetime": "2019-05-20T02:53:44.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-20T02:53:44.000Z", "max_issues_repo_path": "ZuounMenu/Database/Usuario.cs", "max_issues_repo_name": "gmonteeeiro/manutencao-estoque", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ZuounMenu/Database/Usuario.cs", "max_forks_repo_name": "gmonteeeiro/manutencao-estoque", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 24.2972972973, "max_line_length": 64, "alphanum_fraction": 0.4760845384} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Database
{
public class Usuario
{
private readonly MySQL my;
public Usuario()
{
my = new MySQL();
}
/// <summary>
/// Valida se o usuário e senha informado estão corretos
/// </summary>
/// <param name="user">Usuário</param>
/// <param name="pass">Senha</param>
/// <returns></returns>
public bool UsuarioValido(string user, string pass)
{
string sql = $@"SELECT 1
FROM usuario
WHERE user = '{user}'
AND senha = '{pass}';";
my.ExecuteReader(sql);
bool valido = my.HasRows();
my.FechaConexao();
return valido;
}
}
}
|
||||
TheStack | 33278704c1794b0a5bc06202e32292506e8eb5dd | C#code:C# | {"size": 1798, "ext": "cs", "max_stars_repo_path": "PracticePlugin/CustomEffectPoolsInstaller.cs", "max_stars_repo_name": "AceofShovels/PracticePlugin", "max_stars_repo_stars_event_min_datetime": "2019-01-05T23:39:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T13:21:08.000Z", "max_issues_repo_path": "PracticePlugin/CustomEffectPoolsInstaller.cs", "max_issues_repo_name": "AceofShovels/PracticePlugin", "max_issues_repo_issues_event_min_datetime": "2022-03-20T02:13:03.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T11:15:17.000Z", "max_forks_repo_path": "PracticePlugin/CustomEffectPoolsInstaller.cs", "max_forks_repo_name": "AceofShovels/PracticePlugin", "max_forks_repo_forks_event_min_datetime": "2019-01-22T03:07:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T13:22:08.000Z"} | {"max_stars_count": 14.0, "max_issues_count": 4.0, "max_forks_count": 9.0, "avg_line_length": 54.4848484848, "max_line_length": 204, "alphanum_fraction": 0.7296996663} | using Zenject;
namespace PracticePlugin
{
/*
public class CustomEffectPoolsInstaller : EffectPoolsInstaller
{
public override void ManualInstallBindings(DiContainer container, bool shortBeatEffect)
{
try
{
container.BindMemoryPool<FlyingTextEffect, FlyingTextEffect.Pool>().WithInitialSize(20).FromComponentInNewPrefab(this._flyingTextEffectPrefab);
container.BindMemoryPool<FlyingScoreEffect, FlyingScoreEffect.Pool>().WithInitialSize(20).FromComponentInNewPrefab(this._flyingScoreEffectPrefab);
container.BindMemoryPool<FlyingSpriteEffect, FlyingSpriteEffect.Pool>().WithInitialSize(20).FromComponentInNewPrefab(this._flyingSpriteEffectPrefab);
container.BindMemoryPool<NoteDebris, NoteDebris.Pool>().WithInitialSize(40).FromComponentInNewPrefab(this._noteDebrisHDConditionVariable ? this._noteDebrisHDPrefab : this._noteDebrisLWPrefab);
container.BindMemoryPool<BeatEffect, BeatEffect.Pool>().WithInitialSize(20).FromComponentInNewPrefab(shortBeatEffect ? this._shortBeatEffectPrefab : this._beatEffectPrefab);
container.BindMemoryPool<NoteCutSoundEffect, NoteCutSoundEffect.Pool>().WithInitialSize(16).FromComponentInNewPrefab(this._noteCutSoundEffectPrefab);
container.BindMemoryPool<BombCutSoundEffect, BombCutSoundEffect.Pool>().WithInitialSize(20).FromComponentInNewPrefab(this._bombCutSoundEffectPrefab);
}
catch (System.Exception ex)
{
System.Console.WriteLine(ex.ToString());
}
}
private CustomNoteCutSoundEffect ReplacePrefab()
{
return CustomNoteCutSoundEffect.CopyOriginal(_noteCutSoundEffectPrefab);
}
}
*/
} |
||||
TheStack | 33279f49d476ba73ae1f2d20c0954df2711c4443 | C#code:C# | {"size": 780, "ext": "cs", "max_stars_repo_path": "Blocks/Level/Blocks/Block.cs", "max_stars_repo_name": "BlocksTeam/Blocks", "max_stars_repo_stars_event_min_datetime": "2019-11-05T18:09:58.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-08T06:24:56.000Z", "max_issues_repo_path": "Blocks/Level/Blocks/Block.cs", "max_issues_repo_name": "BlocksTeam/Blocks", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Blocks/Level/Blocks/Block.cs", "max_forks_repo_name": "BlocksTeam/Blocks", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 4.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 19.0243902439, "max_line_length": 56, "alphanum_fraction": 0.3525641026} | /*
╔══╗─ ╔╗─── ╔═══╗ ╔═══╗ ╔╗╔═╗ ╔═══╗
║╔╗║─ ║║─── ║╔═╗║ ║╔═╗║ ║║║╔╝ ║╔═╗║
║╚╝╚╗ ║║─── ║║─║║ ║║─╚╝ ║╚╝╝─ ║╚══╗
║╔═╗║ ║║─╔╗ ║║─║║ ║║─╔╗ ║╔╗║─ ╚══╗║
║╚═╝║ ║╚═╝║ ║╚═╝║ ║╚═╝║ ║║║╚╗ ║╚═╝║
╚═══╝ ╚═══╝ ╚═══╝ ╚═══╝ ╚╝╚═╝ ╚═══╝
* https://github.com/blocksteam/Blocks
* Contact Us: [email protected]
*/
using System;
using Blocks.Utils;
namespace Blocks.Level.Blocks
{
/// <summary>
/// Block of Minecraft World.
/// </summary>
public abstract class Block : MetaTag
{
public int Id
{
protected set;
get;
}
public string Name
{
protected set;
get;
}
public override string ToString()
{
return Name;
}
}
}
|
||||
TheStack | 33281216debbe4fd0b7a9c53850ce66cc8a6fa7b | C#code:C# | {"size": 7727, "ext": "cs", "max_stars_repo_path": "src/SHAutomation.Core/Caching/CacheService.cs", "max_stars_repo_name": "tomaustin700/SHAutomation", "max_stars_repo_stars_event_min_datetime": "2020-07-05T16:27:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-05T16:27:23.000Z", "max_issues_repo_path": "src/SHAutomation.Core/Caching/CacheService.cs", "max_issues_repo_name": "tomaustin700/SHAutomation", "max_issues_repo_issues_event_min_datetime": "2020-07-28T07:46:03.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T09:09:50.000Z", "max_forks_repo_path": "src/SHAutomation.Core/Caching/CacheService.cs", "max_forks_repo_name": "tomaustin700/SHAutomation", "max_forks_repo_forks_event_min_datetime": "2020-07-12T15:00:48.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-29T08:36:22.000Z"} | {"max_stars_count": 1.0, "max_issues_count": 22.0, "max_forks_count": 3.0, "avg_line_length": 35.1227272727, "max_line_length": 150, "alphanum_fraction": 0.4806522583} | using StackExchange.Redis;
using System;
using System.Text.RegularExpressions;
using SHAutomation.Core.StaticClasses;
using System.IO;
using System.Threading;
using Newtonsoft.Json;
using SHAutomation.Core.Classes;
using SHAutomation.Core.Logging;
namespace SHAutomation.Core.Caching
{
public class CacheService : ICacheService
{
private bool _usingRedis;
private string _branchNameRegex;
private IDatabase _database;
private readonly ILoggingService _loggingService;
public CacheService(ILoggingService loggingService)
{
Init();
_loggingService = loggingService;
}
public CacheService(string pathToConfigFile, ILoggingService loggingService)
{
Init(pathToConfigFile);
_loggingService = loggingService;
}
private void Init()
{
Init(null);
}
private void Init(string pathToConfigFile)
{
if (!string.IsNullOrEmpty(pathToConfigFile))
{
var config = JsonConvert.DeserializeObject<ConfigFile>(File.ReadAllText(pathToConfigFile));
if (!string.IsNullOrEmpty(config.RedisEndpoint))
_usingRedis = true;
RedisManager.EndPoint = config.RedisEndpoint;
RedisManager.Password = config.RedisPassword;
RedisManager.Port = config.RedisPort;
RedisManager.UseSSL = config.RedisUseSSL;
RedisManager.KeyExpiry = config.KeyExpiry;
RedisManager.UpdateExpiryIfTTLLessThan = config.UpdateExpiryIfTTLLessThan;
_branchNameRegex = @"\d\.\d\d"; //config.BranchMatchRegex.Replace(@"\\", @"\");
}
}
public void SetCacheValue(string key, string value)
{
if (_usingRedis)
{
if (_database == null)
{
try
{
_database = RedisManager.Connection.GetDatabase();
}
catch (Exception ex)
{
try
{
if (ex is ObjectDisposedException || ex is RedisTimeoutException)
{
_loggingService.Error(ex);
RedisManager.ForceReconnect();
_database = RedisManager.Connection.GetDatabase();
}
}
catch
{
_loggingService.Error("Retry attempt to get Redis DB failed, setting Redis DB to null to prevent usage");
_database = null;
}
}
}
if (_database != null)
{
try
{
_database.StringSet(key, value, expiry: RedisManager.KeyExpiry.HasValue ? RedisManager.KeyExpiry.Value : (TimeSpan?)null);
}
catch (Exception ex)
{
if (ex is RedisTimeoutException || ex is RedisConnectionException)
{
_loggingService.Warn("Encountered issue performing Redis StringSet so retrying");
_loggingService.Warn(ex.Message);
_database.StringSet(key, value, expiry: RedisManager.KeyExpiry.HasValue ? RedisManager.KeyExpiry.Value : (TimeSpan?)null);
}
else
_loggingService.Error(ex.Message);
}
}
}
else
{
string appDataFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "SHAutomation");
if (!Directory.Exists(appDataFolder))
Directory.CreateDirectory(appDataFolder);
var path = Path.Combine(appDataFolder, key + ".json");
if (!File.Exists(path))
{
File.Create(path).Dispose();
}
File.WriteAllText(path, value);
}
}
public string GetCacheValue(string key, string testName)
{
if (_usingRedis)
{
ThreadPool.SetMinThreads(300, 300);
try
{
_database = RedisManager.Connection.GetDatabase();
}
catch (Exception ex)
{
try
{
if (ex is ObjectDisposedException || ex is RedisTimeoutException)
{
_loggingService.Error(ex);
RedisManager.ForceReconnect();
_database = RedisManager.Connection.GetDatabase();
}
}
catch
{
_loggingService.Error("Retry attempt to get Redis DB failed, setting Redis DB to null to prevent usage");
_database = null;
}
}
var cacheValue = _database.StringGetWithExpiry(key);
if (string.IsNullOrEmpty(cacheValue.Value) && key != testName)
{
try
{
cacheValue = _database.StringGetWithExpiry(testName);
}
catch (Exception ex)
{
if (ex is RedisTimeoutException || ex is RedisConnectionException)
{
_loggingService.Warn("Encountered issue performing Redis StringGet so retrying");
_loggingService.Warn(ex.Message);
cacheValue = _database.StringGetWithExpiry(testName);
}
else
_loggingService.Error(ex.Message);
return null;
}
}
if (cacheValue.Expiry.HasValue && RedisManager.KeyExpiry.HasValue && RedisManager.UpdateExpiryIfTTLLessThan.HasValue
&& cacheValue.Expiry.Value < RedisManager.UpdateExpiryIfTTLLessThan.Value)
_database.KeyExpire(testName, RedisManager.KeyExpiry);
return cacheValue.Value;
}
else
{
string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "SHAutomation", key + ".json");
if (File.Exists(path))
{
return File.ReadAllText(path);
}
else
return string.Empty;
}
}
public string GenerateCacheKey(string testName)
{
var branchName = Environment.GetEnvironmentVariable("Build_SourceBranchName");
var regex = !string.IsNullOrEmpty(_branchNameRegex) ? _branchNameRegex : null; //@"\d\.\d\d"
if (string.IsNullOrEmpty(branchName))
return testName;
else
{
if (!string.IsNullOrEmpty(regex) && Regex.IsMatch(branchName, regex))
return testName + "_" + branchName;
else
return testName;
}
}
}
}
|
||||
TheStack | 332840a89661d21821c8ec27f40385c84a14104e | C#code:C# | {"size": 4196, "ext": "cs", "max_stars_repo_path": "cs_ctp/proxy/OrderField.cs", "max_stars_repo_name": "xzstar/Rainbird2", "max_stars_repo_stars_event_min_datetime": "2017-02-28T21:14:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-11T11:10:04.000Z", "max_issues_repo_path": "cs_ctp/proxy/OrderField.cs", "max_issues_repo_name": "xzstar/Rainbird2", "max_issues_repo_issues_event_min_datetime": "2017-09-05T08:07:05.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-26T06:27:02.000Z", "max_forks_repo_path": "cs_ctp/proxy/OrderField.cs", "max_forks_repo_name": "xzstar/Rainbird2", "max_forks_repo_forks_event_min_datetime": "2017-02-01T04:47:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-17T03:26:57.000Z"} | {"max_stars_count": 215.0, "max_issues_count": 27.0, "max_forks_count": 101.0, "avg_line_length": 29.1388888889, "max_line_length": 194, "alphanum_fraction": 0.6472831268} | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HaiFeng
{
/// <summary>
/// 报单
/// </summary>
public class OrderField : BindableBase
{
/// <summary>
/// 报单标识
/// </summary>
[DisplayName("报单编号")]
public string OrderID { get { return _OrderID; } set { if (value != null) SetProperty(ref _OrderID, value); } }
private string _OrderID = string.Empty;
/// <summary>
/// 合约
/// </summary>
[DisplayName("合约")]
public string InstrumentID { get { return _InstrumentID; } set { if (value != null) SetProperty(ref _InstrumentID, value); } }
private string _InstrumentID = string.Empty;
/// <summary>
/// 买卖
/// </summary>
[DisplayName("买卖")]
public DirectionType Direction { get { return _Direction; } set { SetProperty(ref _Direction, value); } }
private DirectionType _Direction;
/// <summary>
/// 开平
/// </summary>
[DisplayName("开平")]
public OffsetType Offset { get { return _Offset; } set { SetProperty(ref _Offset, value); } }
private OffsetType _Offset;
/// <summary>
/// 报价
/// </summary>
[DisplayName("报单价格")]
public double LimitPrice { get { return _LimitPrice; } set { SetProperty(ref _LimitPrice, value); } }
private double _LimitPrice;
/// <summary>
/// 成交均价
/// </summary>
[DisplayName("成交均价")]
public double AvgPrice { get { return _AvgPrice; } set { SetProperty(ref _AvgPrice, value); } }
private double _AvgPrice;
/// <summary>
/// 报单时间(交易所)
/// </summary>
[DisplayName("报单时间")]
public string InsertTime { get { return _InsertTime; } set { if (value != null) SetProperty(ref _InsertTime, value); } }
private string _InsertTime = string.Empty;
/// <summary>
/// 最后成交时间(撤单状态时为撤单时间-IsLocal有效)
/// </summary>
[DisplayName("成撤时间")]
public string TradeTime { get { return _TradeTime; } set { if (value != null) SetProperty(ref _TradeTime, value); } }
private string _TradeTime = string.Empty;
/// <summary>
/// 末次成交量,trade更新
/// </summary>
[DisplayName("末次成交量")]
public int TradeVolume { get { return _TradeVolume; } set { SetProperty(ref _TradeVolume, value); } }
private int _TradeVolume;
/// <summary>
/// 报单数量
/// </summary>
[DisplayName("报单数量")]
public int Volume { get { return _Volume; } set { SetProperty(ref _Volume, value); } }
private int _Volume;
/// <summary>
/// 未成交,trade更新
/// </summary>
[DisplayName("未成交手数")]
public int VolumeLeft { get { return _VolumeLeft; } set { SetProperty(ref _VolumeLeft, value); } }
private int _VolumeLeft;
/// <summary>
/// 投保
/// </summary>
[DisplayName("投保")]
public HedgeType Hedge { get { return _Hedge; } set { SetProperty(ref _Hedge, value); } }
private HedgeType _Hedge;
/// <summary>
/// 状态
/// </summary>
[DisplayName("状态")]
public OrderStatus Status { get { return _Status; } set { SetProperty(ref _Status, value); } }
private OrderStatus _Status;
/// <summary>
/// 状态描述
/// </summary>
[DisplayName("详细状态")]
public string StatusMsg { get { return _StatusMsg; } set { if (value != null) SetProperty(ref _StatusMsg, value); } }
private string _StatusMsg = string.Empty;
/// <summary>
/// 是否自身委托
/// </summary>
[DisplayName("本地报单")]
public bool IsLocal { get { return _IsLocal; } set { SetProperty(ref _IsLocal, value); } }
private bool _IsLocal;
/// <summary>
/// 客户自定义字段(xSpeed仅支持数字)
/// </summary>
[DisplayName("自定义")]
public int Custom { get { return _Custom; } set { SetProperty(ref _Custom, value); } }
private int _Custom;
/// <summary>
/// 交易所生成的ID
/// </summary>
[DisplayName("交易所编号")]
public string SysID { get { return _SysID; } set { if (value != null) SetProperty(ref _SysID, value); } }
private string _SysID = string.Empty;
/// <summary>
/// 返回:标识,合约,买卖,开平,报价,手数,报单时间,成交均价,剩余手数,成交时间,状态,状态信息,本地,自定义,交易所编号
/// </summary>
/// <returns></returns>
public override string ToString()
{
return $"{_OrderID}, {_InstrumentID},{_Direction},{_Offset},{_LimitPrice},{_Volume},{_InsertTime},{_AvgPrice},{_VolumeLeft},{_TradeTime},{_Status},{_StatusMsg},{_IsLocal},{_Custom},{_SysID}";
}
}
}
|
||||
TheStack | 332850e4875d29c2bbf894fe6525a9282564bf9e | C#code:C# | {"size": 130, "ext": "cs", "max_stars_repo_path": "Lib/Neon.ModelGenerator/Stub.cs", "max_stars_repo_name": "codelastnight/neonKUBE", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Lib/Neon.ModelGenerator/Stub.cs", "max_issues_repo_name": "codelastnight/neonKUBE", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lib/Neon.ModelGenerator/Stub.cs", "max_forks_repo_name": "codelastnight/neonKUBE", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 11.8181818182, "max_line_length": 33, "alphanum_fraction": 0.7} | using System;
using System.Collections.Generic;
using System.Text;
namespace Neon.ModelGenerator
{
class Stub
{
}
}
|
||||
TheStack | 332a05839759b0fae57377df8008021d658b323b | C#code:C# | {"size": 1304, "ext": "cs", "max_stars_repo_path": "ElmCommunicator/ElmCommunicatorTests/Commands/ElmCommands/SetProtocolSetSendMessageTests.cs", "max_stars_repo_name": "cracker4o/elm327lib", "max_stars_repo_stars_event_min_datetime": "2015-02-19T16:50:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T10:32:28.000Z", "max_issues_repo_path": "ElmCommunicator/ElmCommunicatorTests/Commands/ElmCommands/SetProtocolSetSendMessageTests.cs", "max_issues_repo_name": "cracker4o/elm327lib", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ElmCommunicator/ElmCommunicatorTests/Commands/ElmCommands/SetProtocolSetSendMessageTests.cs", "max_forks_repo_name": "cracker4o/elm327lib", "max_forks_repo_forks_event_min_datetime": "2015-03-18T03:51:27.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-13T01:28:39.000Z"} | {"max_stars_count": 10.0, "max_issues_count": null, "max_forks_count": 10.0, "avg_line_length": 32.6, "max_line_length": 78, "alphanum_fraction": 0.6648773006} | // Copyright 2015 Tosho Toshev
//
// 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 ElmCommunicatorPortable.Commands.ElmCommands;
using NUnit.Framework;
namespace ElmCommunicatorTests.Commands.ElmCommands
{
public class SetProtocolSetSendMessageTests
{
[SetUp]
public void SetUp()
{
}
[Test]
public void ShouldContainOnlyOneLetterInDataField()
{
var command = new SetProtocolSetSendMessage(11);
Assert.AreEqual(1, command.Data.Length);
}
[Test]
public void ShouldSetDoubleZerosForDataWhenTheResetIsTrue()
{
var command = new SetProtocolSetSendMessage(0, true);
Assert.AreEqual("00", command.Data);
}
}
} |
||||
TheStack | 332a20273bf86ad90526d8adf13c79d562af96e2 | C#code:C# | {"size": 844, "ext": "cs", "max_stars_repo_path": "src/StatusAggregator/Container/ContainerWrapper.cs", "max_stars_repo_name": "nikhgup/NuGet.Jobs", "max_stars_repo_stars_event_min_datetime": "2015-05-25T10:40:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T10:55:18.000Z", "max_issues_repo_path": "src/StatusAggregator/Container/ContainerWrapper.cs", "max_issues_repo_name": "nikhgup/NuGet.Jobs", "max_issues_repo_issues_event_min_datetime": "2015-03-31T18:55:14.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T18:52:09.000Z", "max_forks_repo_path": "src/StatusAggregator/Container/ContainerWrapper.cs", "max_forks_repo_name": "nikhgup/NuGet.Jobs", "max_forks_repo_forks_event_min_datetime": "2015-04-06T14:55:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-24T09:26:04.000Z"} | {"max_stars_count": 44.0, "max_issues_count": 320.0, "max_forks_count": 21.0, "avg_line_length": 29.1034482759, "max_line_length": 111, "alphanum_fraction": 0.6765402844} | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Threading.Tasks;
using Microsoft.WindowsAzure.Storage.Blob;
namespace StatusAggregator.Container
{
public class ContainerWrapper : IContainerWrapper
{
private readonly CloudBlobContainer _container;
public ContainerWrapper(CloudBlobContainer container)
{
_container = container;
}
public Task CreateIfNotExistsAsync()
{
return _container.CreateIfNotExistsAsync();
}
public Task SaveBlobAsync(string name, string contents)
{
var blob = _container.GetBlockBlobReference(name);
return blob.UploadTextAsync(contents);
}
}
} |
||||
TheStack | 332adf580900bd13a2cff828b5fcb3a5754b3adb | C#code:C# | {"size": 216, "ext": "cs", "max_stars_repo_path": "Blib/IOperacoesBD.cs", "max_stars_repo_name": "Le-alves/Montreal-Capacitacao", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Blib/IOperacoesBD.cs", "max_issues_repo_name": "Le-alves/Montreal-Capacitacao", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Blib/IOperacoesBD.cs", "max_forks_repo_name": "Le-alves/Montreal-Capacitacao", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 18.0, "max_line_length": 44, "alphanum_fraction": 0.5787037037} | namespace AtivSem01
{
interface IOperacoesBD
{
void Inserir (string nome);
void Alterar (string nome);
void Deletar (string nome);
void Pesquisar (string nome);
} |
||||
TheStack | 332b3187ba1340d6c06d89c8329f2c9e6ca91e45 | C#code:C# | {"size": 4567, "ext": "cs", "max_stars_repo_path": "UnityProject/Assets/Source/ComponentBindings/ComponentBindingDrawer.cs", "max_stars_repo_name": "MaximilianRue/comp-bind", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "UnityProject/Assets/Source/ComponentBindings/ComponentBindingDrawer.cs", "max_issues_repo_name": "MaximilianRue/comp-bind", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "UnityProject/Assets/Source/ComponentBindings/ComponentBindingDrawer.cs", "max_forks_repo_name": "MaximilianRue/comp-bind", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 35.6796875, "max_line_length": 110, "alphanum_fraction": 0.5966717758} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEditorInternal;
using UnityEngine;
using UnityEditor;
namespace CompBind
{
/// <summary>
/// Visualizes a <see cref="BindableComponent"/> instance in the editor.
/// </summary>
/// <remarks>
/// Unless not overwritten, this drawer will also be used for
/// all user-defined derivations of <see cref="BindableComponent"/>.
/// </remarks>
///
[CustomEditor(typeof(BindableComponent), true)]
class ComponentBindingDrawer : UnityEditor.Editor
{
private ReorderableList list;
BindableComponent componentBinding;
string[] callbackNames;
public void OnEnable()
{
componentBinding = target as BindableComponent;
callbackNames = componentBinding.GetCallbacks().Keys.ToArray();
list = new ReorderableList(
serializedObject,
serializedObject.FindProperty("selectedBindings"),
draggable: true,
displayAddButton: true,
displayRemoveButton: true,
displayHeader: true
);
list.drawHeaderCallback = drawHeaderCallback;
list.elementHeightCallback = elementHeightCallback;
list.drawElementCallback = drawElementCallback;
}
public override void OnInspectorGUI()
{
serializedObject.Update();
GUILayout.Space(EditorGUIUtility.singleLineHeight * 0.5f);
list.DoLayoutList();
serializedObject.ApplyModifiedProperties();
EditorUtility.SetDirty(target);
}
protected void drawHeaderCallback(Rect position)
{
EditorGUI.LabelField(position, "Component Bindings");
}
protected float elementHeightCallback(int index)
{
return 2 * EditorGUIUtility.standardVerticalSpacing + EditorGUIUtility.singleLineHeight;
}
protected void drawElementCallback(Rect position, int drawerEntryIndex, bool isActive, bool isFocused)
{
position.y += EditorGUIUtility.standardVerticalSpacing;
position.height = EditorGUIUtility.singleLineHeight;
EditorGUI.BeginChangeCheck();
var goRect = new Rect(position);
goRect.width = position.width * 0.5f;
string bindingPath = EditorGUI.TextField(goRect, serializedObject
.FindProperty("selectedBindings")
.GetArrayElementAtIndex(drawerEntryIndex)
.FindPropertyRelative("BindingPath")
.stringValue);
if (EditorGUI.EndChangeCheck())
{
// Binding path was changed
serializedObject
.FindProperty("selectedBindings")
.GetArrayElementAtIndex(drawerEntryIndex)
.FindPropertyRelative("BindingPath")
.stringValue = bindingPath;
}
EditorGUI.BeginChangeCheck();
var popupRect = new Rect(goRect);
popupRect.x += goRect.width;
popupRect.x += EditorGUIUtility.standardVerticalSpacing;
popupRect.width = position.width - goRect.width;
popupRect.width -= EditorGUIUtility.standardVerticalSpacing;
int fieldIndex = EditorGUI.Popup(
popupRect,
getIndex(drawerEntryIndex),
callbackNames
);
if (EditorGUI.EndChangeCheck())
{
// Switch selected callback
serializedObject
.FindProperty("selectedBindings")
.GetArrayElementAtIndex(drawerEntryIndex)
.FindPropertyRelative("CallbackName")
.stringValue = callbackNames[fieldIndex];
serializedObject.ApplyModifiedProperties();
}
position.y += EditorGUIUtility.singleLineHeight;
position.y += EditorGUIUtility.standardVerticalSpacing;
}
int getIndex(int elementIndex)
{
string currentlySelected = serializedObject
.FindProperty("selectedBindings")
.GetArrayElementAtIndex(elementIndex)
.FindPropertyRelative("CallbackName")
.stringValue;
return Array.IndexOf(callbackNames, currentlySelected);
}
}
}
|
||||
TheStack | 332b534cb50d6949f54080e93a00c75252373a10 | C#code:C# | {"size": 1932, "ext": "cs", "max_stars_repo_path": "Entity Framework/Kuno.EntityFramework/Search/EntityFrameworkSearchModule.cs", "max_stars_repo_name": "kuno-framework/kuno", "max_stars_repo_stars_event_min_datetime": "2018-06-26T08:43:15.000Z", "max_stars_repo_stars_event_max_datetime": "2018-06-26T08:46:40.000Z", "max_issues_repo_path": "Entity Framework/Kuno.EntityFramework/Search/EntityFrameworkSearchModule.cs", "max_issues_repo_name": "kuno-framework/kuno", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Entity Framework/Kuno.EntityFramework/Search/EntityFrameworkSearchModule.cs", "max_forks_repo_name": "kuno-framework/kuno", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 2.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 32.2, "max_line_length": 97, "alphanum_fraction": 0.6076604555} | /*
* Copyright (c) Kuno Contributors
*
* This file is subject to the terms and conditions defined in
* the LICENSE file, which is part of this source code package.
*/
using System.Data.Entity;
using Autofac;
using Kuno.Search;
using Kuno.Validation;
namespace Kuno.EntityFramework.Search
{
/// <summary>
/// An Autofac module for configuring the Entity Framework Search module.
/// </summary>
/// <seealso cref="Autofac.Module" />
internal class EntityFrameworkSearchModule : Module
{
private readonly EntityFrameworkOptions _options;
private readonly KunoStack _stack;
/// <summary>
/// Initializes a new instance of the <see cref="EntityFrameworkSearchModule" /> class.
/// </summary>
/// <param name="stack">The configured stack.</param>
/// <param name="options">The options to use.</param>
public EntityFrameworkSearchModule(KunoStack stack, EntityFrameworkOptions options)
{
Argument.NotNull(options, nameof(options));
_stack = stack;
_options = options;
}
/// <summary>
/// Override to add registrations to the container.
/// </summary>
/// <param name="builder">
/// The builder through which components can be
/// registered.
/// </param>
/// <remarks>Note that the ContainerBuilder parameter is unique to this module.</remarks>
protected override void Load(ContainerBuilder builder)
{
base.Load(builder);
builder.Register(c => new SearchContext(_options))
.AsSelf()
.As<ISearchContext>()
.AllPropertiesAutowired();
if (_options.Search.EnableMigrations)
{
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<SearchContext>());
}
}
}
} |
||||
TheStack | 332c55f30468db62c664afd004a3be94c3ca9142 | C#code:C# | {"size": 454, "ext": "cs", "max_stars_repo_path": "BeatOn/ClientModels/ToastType.cs", "max_stars_repo_name": "kodzitive/BeatOn", "max_stars_repo_stars_event_min_datetime": "2019-10-05T07:56:32.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-22T00:13:05.000Z", "max_issues_repo_path": "BeatOn/ClientModels/ToastType.cs", "max_issues_repo_name": "jakibaki/BeatOn", "max_issues_repo_issues_event_min_datetime": "2020-09-07T12:39:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-02T05:50:01.000Z", "max_forks_repo_path": "BeatOn/ClientModels/ToastType.cs", "max_forks_repo_name": "jakibaki/BeatOn", "max_forks_repo_forks_event_min_datetime": "2019-10-04T22:16:09.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-22T00:13:02.000Z"} | {"max_stars_count": 8.0, "max_issues_count": 10.0, "max_forks_count": 8.0, "avg_line_length": 18.16, "max_line_length": 48, "alphanum_fraction": 0.7202643172} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace BeatOn.ClientModels
{
[JsonConverter(typeof(StringEnumConverter))]
public enum ToastType
{
Error,
Warning,
Info,
Success
}
} |
||||
TheStack | 332cf6541a1d76c2c105ecfcf28fd14513c1aa22 | C#code:C# | {"size": 522, "ext": "cs", "max_stars_repo_path": "src/Microsoft.Diagnostics.Runtime/src/Extensions/AccessorHelpers.cs", "max_stars_repo_name": "swift-kim/clrmd", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Microsoft.Diagnostics.Runtime/src/Extensions/AccessorHelpers.cs", "max_issues_repo_name": "swift-kim/clrmd", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Microsoft.Diagnostics.Runtime/src/Extensions/AccessorHelpers.cs", "max_forks_repo_name": "swift-kim/clrmd", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 29.0, "max_line_length": 83, "alphanum_fraction": 0.6819923372} | // 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;
namespace Microsoft.Diagnostics.Runtime
{
internal static class AccessorHelpers
{
public static V GetOrDefault<K, V>(this Dictionary<K, V> dictionary, K key)
{
dictionary.TryGetValue(key, out V value);
return value;
}
}
}
|
||||
TheStack | 332e58a8c4cfa080f966d7f9b08374edd818a664 | C#code:C# | {"size": 161, "ext": "cs", "max_stars_repo_path": "Components/Backlog/ProjectClient/IProjectClient.cs", "max_stars_repo_name": "vmware-tanzu-learning/pal-tracker-distributed-dotnet", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Components/Backlog/ProjectClient/IProjectClient.cs", "max_issues_repo_name": "vmware-tanzu-learning/pal-tracker-distributed-dotnet", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Components/Backlog/ProjectClient/IProjectClient.cs", "max_forks_repo_name": "vmware-tanzu-learning/pal-tracker-distributed-dotnet", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 17.8888888889, "max_line_length": 46, "alphanum_fraction": 0.7080745342} | using System.Threading.Tasks;
namespace Backlog.ProjectClient
{
public interface IProjectClient
{
Task<ProjectInfo> Get(long projectId);
}
} |
||||
TheStack | 332fefcbdb700a7ac55b20fbcc44d0f5522194a5 | C#code:C# | {"size": 1500, "ext": "cs", "max_stars_repo_path": "Exam Preparation 4/DungeonsAndCodeWizards/Bags/Bag.cs", "max_stars_repo_name": "danieldamianov/C-OOP-Basics", "max_stars_repo_stars_event_min_datetime": "2020-01-17T23:13:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-17T23:13:47.000Z", "max_issues_repo_path": "Exam Preparation 4/DungeonsAndCodeWizards/Bags/Bag.cs", "max_issues_repo_name": "danieldamianov/C-OOP-Basics", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Exam Preparation 4/DungeonsAndCodeWizards/Bags/Bag.cs", "max_forks_repo_name": "danieldamianov/C-OOP-Basics", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 28.3018867925, "max_line_length": 104, "alphanum_fraction": 0.5406666667} | using DungeonsAndCodeWizards.Items;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DungeonsAndCodeWizards.Bags
{
public abstract class Bag
{
private const int defaultCapacity = 100;
private List<Item> items;
protected Bag(int capacity)
{
items = new List<Item>();
this.Capacity = capacity;
}
public int Capacity { get; }
public int Load => this.items.Sum(item => item.Weight);
public IReadOnlyCollection<Item> Items => items.AsReadOnly();
public void AddItem(Item item)
{
if (item.Weight + this.Load > this.Capacity)
{
throw new InvalidOperationException("Bag is full!");
}
this.items.Add(item);
}
public Item GetItem(string name)
{
if (this.items.Count == 0)
{
throw new InvalidOperationException("Bag is empty!");
}
if (this.items.Exists(it => it.GetType().Name == name) == false) // CHECK LATER AGAIN !!!!!!
{
throw new ArgumentException($"No item with name {name} in bag!");
}
// TODO :: CHECK IF ITEM EXISTS IN THE BAG !!!
Item item = this.items.Last(it => it.GetType().Name == name);
this.items.Remove(this.items.Last(it => it.GetType().Name == name));
return item;
}
}
}
|
||||
TheStack | 33300c30b9c83aef0e34a5b9f801f66beb639c72 | C#code:C# | {"size": 22516, "ext": "cs", "max_stars_repo_path": "BasicDesk.App/obj/Debug/netcoreapp2.1/Razor/Views/Shared/ApprovalDetailsPartial.g.cshtml.cs", "max_stars_repo_name": "LyuboslavKrastev/BasicDesk-Project-CSharp-MVC-Frameworks-ASP.NET-Core", "max_stars_repo_stars_event_min_datetime": "2020-04-12T17:54:05.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-12T17:54:05.000Z", "max_issues_repo_path": "BasicDesk.App/obj/Debug/netcoreapp2.1/Razor/Views/Shared/ApprovalDetailsPartial.g.cshtml.cs", "max_issues_repo_name": "LyuboslavKrastev/BasicDesk", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "BasicDesk.App/obj/Debug/netcoreapp2.1/Razor/Views/Shared/ApprovalDetailsPartial.g.cshtml.cs", "max_forks_repo_name": "LyuboslavKrastev/BasicDesk", "max_forks_repo_forks_event_min_datetime": "2019-01-11T13:52:00.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-11T13:52:00.000Z"} | {"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": 1.0, "avg_line_length": 62.5444444444, "max_line_length": 308, "alphanum_fraction": 0.690486765} | #pragma checksum "C:\Users\Zorko\Documents\BasicDesk\BasicDesk-Project-CSharp-MVC-Frameworks-ASP.NET-Core\BasicDesk.App\Views\Shared\ApprovalDetailsPartial.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "5318d3524b6b70ee2dd464ebc58cc3298ece9c14"
// <auto-generated/>
#pragma warning disable 1591
[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_Shared_ApprovalDetailsPartial), @"mvc.1.0.view", @"/Views/Shared/ApprovalDetailsPartial.cshtml")]
[assembly:global::Microsoft.AspNetCore.Mvc.Razor.Compilation.RazorViewAttribute(@"/Views/Shared/ApprovalDetailsPartial.cshtml", typeof(AspNetCore.Views_Shared_ApprovalDetailsPartial))]
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;
#line 1 "C:\Users\Zorko\Documents\BasicDesk\BasicDesk-Project-CSharp-MVC-Frameworks-ASP.NET-Core\BasicDesk.App\Views\_ViewImports.cshtml"
using BasicDesk.App;
#line default
#line hidden
#line 2 "C:\Users\Zorko\Documents\BasicDesk\BasicDesk-Project-CSharp-MVC-Frameworks-ASP.NET-Core\BasicDesk.App\Views\_ViewImports.cshtml"
using BasicDesk.App.Models;
#line default
#line hidden
#line 3 "C:\Users\Zorko\Documents\BasicDesk\BasicDesk-Project-CSharp-MVC-Frameworks-ASP.NET-Core\BasicDesk.App\Views\_ViewImports.cshtml"
using BasicDesk.Data.Models.Solution;
#line default
#line hidden
#line 4 "C:\Users\Zorko\Documents\BasicDesk\BasicDesk-Project-CSharp-MVC-Frameworks-ASP.NET-Core\BasicDesk.App\Views\_ViewImports.cshtml"
using BasicDesk.App.Models.ViewModels;
#line default
#line hidden
#line 5 "C:\Users\Zorko\Documents\BasicDesk\BasicDesk-Project-CSharp-MVC-Frameworks-ASP.NET-Core\BasicDesk.App\Views\_ViewImports.cshtml"
using BasicDesk.App.Models.Common.BindingModels;
#line default
#line hidden
#line 6 "C:\Users\Zorko\Documents\BasicDesk\BasicDesk-Project-CSharp-MVC-Frameworks-ASP.NET-Core\BasicDesk.App\Views\_ViewImports.cshtml"
using BasicDesk.App.Helpers.Messages;
#line default
#line hidden
#line 7 "C:\Users\Zorko\Documents\BasicDesk\BasicDesk-Project-CSharp-MVC-Frameworks-ASP.NET-Core\BasicDesk.App\Views\_ViewImports.cshtml"
using BasicDesk.App.Helpers;
#line default
#line hidden
#line 8 "C:\Users\Zorko\Documents\BasicDesk\BasicDesk-Project-CSharp-MVC-Frameworks-ASP.NET-Core\BasicDesk.App\Views\_ViewImports.cshtml"
using BasicDesk.App.Models.Common.ViewModels;
#line default
#line hidden
#line 9 "C:\Users\Zorko\Documents\BasicDesk\BasicDesk-Project-CSharp-MVC-Frameworks-ASP.NET-Core\BasicDesk.App\Views\_ViewImports.cshtml"
using BasicDesk.Data.Models;
#line default
#line hidden
#line 2 "C:\Users\Zorko\Documents\BasicDesk\BasicDesk-Project-CSharp-MVC-Frameworks-ASP.NET-Core\BasicDesk.App\Views\Shared\ApprovalDetailsPartial.cshtml"
using Microsoft.AspNetCore.Identity;
#line default
#line hidden
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"5318d3524b6b70ee2dd464ebc58cc3298ece9c14", @"/Views/Shared/ApprovalDetailsPartial.cshtml")]
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"d96ffe35850e90bc8a938653933dc8ffd63c5d13", @"/Views/_ViewImports.cshtml")]
public class Views_Shared_ApprovalDetailsPartial : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<IEnumerable<RequestApprovalViewModel>>
{
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = 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_1 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-area", "", 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("asp-controller", "Approvals", 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("asp-action", "ApproveApproval", 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("asp-action", "DenyApproval", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
#line hidden
#pragma warning disable 0169
private string __tagHelperStringValueBuffer;
#pragma warning restore 0169
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext __tagHelperExecutionContext;
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner __tagHelperRunner = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner();
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.FormTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper;
private global::Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper;
#pragma warning disable 1998
public async override global::System.Threading.Tasks.Task ExecuteAsync()
{
#line 4 "C:\Users\Zorko\Documents\BasicDesk\BasicDesk-Project-CSharp-MVC-Frameworks-ASP.NET-Core\BasicDesk.App\Views\Shared\ApprovalDetailsPartial.cshtml"
string color = "";
#line default
#line hidden
#line 7 "C:\Users\Zorko\Documents\BasicDesk\BasicDesk-Project-CSharp-MVC-Frameworks-ASP.NET-Core\BasicDesk.App\Views\Shared\ApprovalDetailsPartial.cshtml"
if (Model.Any())
{
#line default
#line hidden
BeginContext(179, 43, true);
WriteLiteral("<div id=\"approvals\" style=\"display:none\">\r\n");
EndContext();
#line 10 "C:\Users\Zorko\Documents\BasicDesk\BasicDesk-Project-CSharp-MVC-Frameworks-ASP.NET-Core\BasicDesk.App\Views\Shared\ApprovalDetailsPartial.cshtml"
foreach (var approval in Model)
{
if(approval.Status == "Denied")
{
color = "red";
}
else if(approval.Status == "Approved")
{
color = "lawngreen";
}
else
{
color = "yellow";
}
#line default
#line hidden
BeginContext(529, 261, true);
WriteLiteral(@" <div class=""panel-group"">
<div class=""panel"">
<div class=""panel-heading clearfix"">
<div class=""pull-left""><strong>Approval</strong></div>
</div>
<div class=""panel-body""");
EndContext();
BeginWriteAttribute("style", " style=\"", 790, "\"", 821, 2);
WriteAttributeValue("", 798, "background-color:", 798, 17, true);
#line 29 "C:\Users\Zorko\Documents\BasicDesk\BasicDesk-Project-CSharp-MVC-Frameworks-ASP.NET-Core\BasicDesk.App\Views\Shared\ApprovalDetailsPartial.cshtml"
WriteAttributeValue("", 815, color, 815, 6, false);
#line default
#line hidden
EndWriteAttribute();
BeginContext(822, 43, true);
WriteLiteral(">\r\n <p><strong>Subject: ");
EndContext();
BeginContext(866, 16, false);
#line 30 "C:\Users\Zorko\Documents\BasicDesk\BasicDesk-Project-CSharp-MVC-Frameworks-ASP.NET-Core\BasicDesk.App\Views\Shared\ApprovalDetailsPartial.cshtml"
Write(approval.Subject);
#line default
#line hidden
EndContext();
BeginContext(882, 54, true);
WriteLiteral("</strong></p>\r\n <p><strong>Status: ");
EndContext();
BeginContext(937, 15, false);
#line 31 "C:\Users\Zorko\Documents\BasicDesk\BasicDesk-Project-CSharp-MVC-Frameworks-ASP.NET-Core\BasicDesk.App\Views\Shared\ApprovalDetailsPartial.cshtml"
Write(approval.Status);
#line default
#line hidden
EndContext();
BeginContext(952, 67, true);
WriteLiteral("</strong></p>\r\n\r\n <strong>Description: </strong>");
EndContext();
BeginContext(1020, 20, false);
#line 33 "C:\Users\Zorko\Documents\BasicDesk\BasicDesk-Project-CSharp-MVC-Frameworks-ASP.NET-Core\BasicDesk.App\Views\Shared\ApprovalDetailsPartial.cshtml"
Write(approval.Description);
#line default
#line hidden
EndContext();
BeginContext(1040, 121, true);
WriteLiteral("\r\n </div>\r\n <div class=\"panel-footer\">\r\n <div class=\"col-md-offset-5\">\r\n");
EndContext();
#line 37 "C:\Users\Zorko\Documents\BasicDesk\BasicDesk-Project-CSharp-MVC-Frameworks-ASP.NET-Core\BasicDesk.App\Views\Shared\ApprovalDetailsPartial.cshtml"
if (approval.ApproverId == userManager.GetUserId(User))
{
if (approval.Status == "Denied")
{
#line default
#line hidden
BeginContext(1406, 83, true);
WriteLiteral(" <p class=\"danger\"><strong>Denied</strong></p>\r\n");
EndContext();
#line 43 "C:\Users\Zorko\Documents\BasicDesk\BasicDesk-Project-CSharp-MVC-Frameworks-ASP.NET-Core\BasicDesk.App\Views\Shared\ApprovalDetailsPartial.cshtml"
}
else if (approval.Status == "Approved")
{
#line default
#line hidden
BeginContext(1632, 86, true);
WriteLiteral(" <p class=\"success\"><strong>Approved</strong></p>\r\n");
EndContext();
#line 47 "C:\Users\Zorko\Documents\BasicDesk\BasicDesk-Project-CSharp-MVC-Frameworks-ASP.NET-Core\BasicDesk.App\Views\Shared\ApprovalDetailsPartial.cshtml"
}
else
{
#line default
#line hidden
BeginContext(1826, 36, true);
WriteLiteral(" ");
EndContext();
BeginContext(1862, 316, false);
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("form", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "d67c9f2a665342a488262d915d051bdc", async() => {
BeginContext(2029, 142, true);
WriteLiteral("\r\n <button type=\"submit\" class=\"btn btn-success\">Approve</button>\r\n ");
EndContext();
}
);
__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);
__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Method = (string)__tagHelperAttribute_0.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_0);
__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Area = (string)__tagHelperAttribute_1.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_1);
__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Controller = (string)__tagHelperAttribute_2.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_2);
__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Action = (string)__tagHelperAttribute_3.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_3);
if (__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.RouteValues == null)
{
throw new InvalidOperationException(InvalidTagHelperIndexerAssignment("asp-route-approvalId", "Microsoft.AspNetCore.Mvc.TagHelpers.FormTagHelper", "RouteValues"));
}
BeginWriteTagHelperAttribute();
#line 50 "C:\Users\Zorko\Documents\BasicDesk\BasicDesk-Project-CSharp-MVC-Frameworks-ASP.NET-Core\BasicDesk.App\Views\Shared\ApprovalDetailsPartial.cshtml"
WriteLiteral(approval.Id);
#line default
#line hidden
__tagHelperStringValueBuffer = EndWriteTagHelperAttribute();
__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.RouteValues["approvalId"] = __tagHelperStringValueBuffer;
__tagHelperExecutionContext.AddTagHelperAttribute("asp-route-approvalId", __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.RouteValues["approvalId"], global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
BeginWriteTagHelperAttribute();
#line 50 "C:\Users\Zorko\Documents\BasicDesk\BasicDesk-Project-CSharp-MVC-Frameworks-ASP.NET-Core\BasicDesk.App\Views\Shared\ApprovalDetailsPartial.cshtml"
WriteLiteral(approval.RequestId);
#line default
#line hidden
__tagHelperStringValueBuffer = EndWriteTagHelperAttribute();
__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.RouteValues["requestId"] = __tagHelperStringValueBuffer;
__tagHelperExecutionContext.AddTagHelperAttribute("asp-route-requestId", __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.RouteValues["requestId"], global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
EndContext();
BeginContext(2178, 38, true);
WriteLiteral("\r\n ");
EndContext();
BeginContext(2216, 308, false);
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("form", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "5eb828df66e34859a58e191bbb190cbf", async() => {
BeginContext(2379, 138, true);
WriteLiteral("\r\n <button type=\"submit\" class=\"btn btn-danger\">Deny</button>\r\n ");
EndContext();
}
);
__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);
__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Method = (string)__tagHelperAttribute_0.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_0);
__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Area = (string)__tagHelperAttribute_1.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_1);
__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Controller = (string)__tagHelperAttribute_2.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_2);
__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Action = (string)__tagHelperAttribute_4.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_4);
if (__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.RouteValues == null)
{
throw new InvalidOperationException(InvalidTagHelperIndexerAssignment("asp-route-approvalId", "Microsoft.AspNetCore.Mvc.TagHelpers.FormTagHelper", "RouteValues"));
}
BeginWriteTagHelperAttribute();
#line 53 "C:\Users\Zorko\Documents\BasicDesk\BasicDesk-Project-CSharp-MVC-Frameworks-ASP.NET-Core\BasicDesk.App\Views\Shared\ApprovalDetailsPartial.cshtml"
WriteLiteral(approval.Id);
#line default
#line hidden
__tagHelperStringValueBuffer = EndWriteTagHelperAttribute();
__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.RouteValues["approvalId"] = __tagHelperStringValueBuffer;
__tagHelperExecutionContext.AddTagHelperAttribute("asp-route-approvalId", __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.RouteValues["approvalId"], global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
BeginWriteTagHelperAttribute();
#line 53 "C:\Users\Zorko\Documents\BasicDesk\BasicDesk-Project-CSharp-MVC-Frameworks-ASP.NET-Core\BasicDesk.App\Views\Shared\ApprovalDetailsPartial.cshtml"
WriteLiteral(approval.RequestId);
#line default
#line hidden
__tagHelperStringValueBuffer = EndWriteTagHelperAttribute();
__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.RouteValues["requestId"] = __tagHelperStringValueBuffer;
__tagHelperExecutionContext.AddTagHelperAttribute("asp-route-requestId", __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.RouteValues["requestId"], global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
EndContext();
BeginContext(2524, 2, true);
WriteLiteral("\r\n");
EndContext();
#line 56 "C:\Users\Zorko\Documents\BasicDesk\BasicDesk-Project-CSharp-MVC-Frameworks-ASP.NET-Core\BasicDesk.App\Views\Shared\ApprovalDetailsPartial.cshtml"
}
}
#line default
#line hidden
BeginContext(2621, 88, true);
WriteLiteral(" </div>\r\n </div>\r\n </div>\r\n </div>\r\n");
EndContext();
#line 64 "C:\Users\Zorko\Documents\BasicDesk\BasicDesk-Project-CSharp-MVC-Frameworks-ASP.NET-Core\BasicDesk.App\Views\Shared\ApprovalDetailsPartial.cshtml"
}
#line default
#line hidden
BeginContext(2716, 8, true);
WriteLiteral("</div>\r\n");
EndContext();
#line 66 "C:\Users\Zorko\Documents\BasicDesk\BasicDesk-Project-CSharp-MVC-Frameworks-ASP.NET-Core\BasicDesk.App\Views\Shared\ApprovalDetailsPartial.cshtml"
}
#line default
#line hidden
BeginContext(2727, 6, true);
WriteLiteral("\r\n\r\n\r\n");
EndContext();
}
#pragma warning restore 1998
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public UserManager<User> userManager { get; private set; }
[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<IEnumerable<RequestApprovalViewModel>> Html { get; private set; }
}
}
#pragma warning restore 1591
|
||||
TheStack | 333121625a6a9d85351d7757101b898e06967ca7 | C#code:C# | {"size": 598, "ext": "cs", "max_stars_repo_path": "src/Serenity.Net.Services/RequestHandlers/Save/ISaveHandler.cs", "max_stars_repo_name": "ArsenioInojosa/Serenity", "max_stars_repo_stars_event_min_datetime": "2015-01-18T03:47:49.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-04T22:07:31.000Z", "max_issues_repo_path": "src/Serenity.Net.Services/RequestHandlers/Save/ISaveHandler.cs", "max_issues_repo_name": "ArsenioInojosa/Serenity", "max_issues_repo_issues_event_min_datetime": "2015-02-22T13:50:18.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-07T07:33:50.000Z", "max_forks_repo_path": "src/Serenity.Net.Services/RequestHandlers/Save/ISaveHandler.cs", "max_forks_repo_name": "ArsenioInojosa/Serenity", "max_forks_repo_forks_event_min_datetime": "2015-02-04T08:39:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-03T15:48:14.000Z"} | {"max_stars_count": 2311.0, "max_issues_count": 5209.0, "max_forks_count": 904.0, "avg_line_length": 37.375, "max_line_length": 111, "alphanum_fraction": 0.6672240803} | namespace Serenity.Services
{
public interface ISaveHandler<TRow, TSaveRequest, TSaveResponse>
: ICreateHandler<TRow, TSaveRequest, TSaveResponse>, IUpdateHandler<TRow, TSaveRequest, TSaveResponse>
where TRow : class, IRow, IIdRow, new()
where TSaveRequest : SaveRequest<TRow>, new()
where TSaveResponse : SaveResponse, new()
{
}
public interface ISaveHandler<TRow> : ISaveHandler<TRow, SaveRequest<TRow>, SaveResponse>,
ICreateHandler<TRow>, IUpdateHandler<TRow>
where TRow : class, IRow, IIdRow, new()
{
}
} |
||||
TheStack | 3331530cd6950988fb470cfb2702053c7068d6e5 | C#code:C# | {"size": 1310, "ext": "cs", "max_stars_repo_path": "Poseidon.Attachment.Caller/Facade/IAttachmentService.cs", "max_stars_repo_name": "robertzml/Poseidon.Attachment", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Poseidon.Attachment.Caller/Facade/IAttachmentService.cs", "max_issues_repo_name": "robertzml/Poseidon.Attachment", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Poseidon.Attachment.Caller/Facade/IAttachmentService.cs", "max_forks_repo_name": "robertzml/Poseidon.Attachment", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 24.7169811321, "max_line_length": 66, "alphanum_fraction": 0.5503816794} | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Poseidon.Attachment.Caller.Facade
{
using Poseidon.Base.Framework;
using Poseidon.Attachment.Core.DL;
using Poseidon.Attachment.Core.Utility;
/// <summary>
/// 附件业务访问服务接口
/// </summary>
public interface IAttachmentService : IBaseService<Attachment>
{
/// <summary>
/// 异步上传单个附件
/// </summary>
/// <param name="data">上传附件信息</param>
/// <returns></returns>
Task<Attachment> UploadAsync(UploadInfo data);
/// <summary>
/// 同步上传单个附件
/// </summary>
/// <param name="data">上传附件信息</param>
/// <returns></returns>
Attachment Upload(UploadInfo data);
/// <summary>
/// 同步下载附件
/// </summary>
/// <param name="id"></param>
Stream Download(string id);
/// <summary>
/// 按文件夹获取附件
/// </summary>
/// <param name="folder">文件夹</param>
/// <returns></returns>
IEnumerable<Attachment> FindByFolder(string folder);
/// <summary>
/// 获取文件夹列表
/// </summary>
/// <returns></returns>
List<string> GetFolders();
}
}
|
||||
TheStack | b593a6a6a52cdbc73500f56fcafdebfff6f89a6f | C#code:C# | {"size": 6824, "ext": "cs", "max_stars_repo_path": "sdk/dotnet/ContainerRegistry/V20190601Preview/Outputs/RunResponse.cs", "max_stars_repo_name": "pulumi/pulumi-azure-nextgen", "max_stars_repo_stars_event_min_datetime": "2020-09-21T09:41:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-26T13:21:59.000Z", "max_issues_repo_path": "sdk/dotnet/ContainerRegistry/V20190601Preview/Outputs/RunResponse.cs", "max_issues_repo_name": "pulumi/pulumi-azure-nextgen", "max_issues_repo_issues_event_min_datetime": "2020-09-21T09:38:45.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-01T11:16:03.000Z", "max_forks_repo_path": "sdk/dotnet/ContainerRegistry/V20190601Preview/Outputs/RunResponse.cs", "max_forks_repo_name": "pulumi/pulumi-azure-nextgen", "max_forks_repo_forks_event_min_datetime": "2020-09-29T14:14:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-10T20:38:16.000Z"} | {"max_stars_count": 31.0, "max_issues_count": 231.0, "max_forks_count": 4.0, "avg_line_length": 33.4509803922, "max_line_length": 133, "alphanum_fraction": 0.5934935522} | // *** 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.ContainerRegistry.V20190601Preview.Outputs
{
[OutputType]
public sealed class RunResponse
{
/// <summary>
/// The machine configuration of the run agent.
/// </summary>
public readonly Outputs.AgentPropertiesResponse? AgentConfiguration;
/// <summary>
/// The dedicated agent pool for the run.
/// </summary>
public readonly string? AgentPoolName;
/// <summary>
/// The time the run was scheduled.
/// </summary>
public readonly string? CreateTime;
/// <summary>
/// The list of custom registries that were logged in during this run.
/// </summary>
public readonly ImmutableArray<string> CustomRegistries;
/// <summary>
/// The time the run finished.
/// </summary>
public readonly string? FinishTime;
/// <summary>
/// The resource ID.
/// </summary>
public readonly string Id;
/// <summary>
/// The image update trigger that caused the run. This is applicable if the task has base image trigger configured.
/// </summary>
public readonly Outputs.ImageUpdateTriggerResponse? ImageUpdateTrigger;
/// <summary>
/// The value that indicates whether archiving is enabled or not.
/// </summary>
public readonly bool? IsArchiveEnabled;
/// <summary>
/// The last updated time for the run.
/// </summary>
public readonly string? LastUpdatedTime;
/// <summary>
/// The image description for the log artifact.
/// </summary>
public readonly Outputs.ImageDescriptorResponse LogArtifact;
/// <summary>
/// The name of the resource.
/// </summary>
public readonly string Name;
/// <summary>
/// The list of all images that were generated from the run. This is applicable if the run generates base image dependencies.
/// </summary>
public readonly ImmutableArray<Outputs.ImageDescriptorResponse> OutputImages;
/// <summary>
/// The platform properties against which the run will happen.
/// </summary>
public readonly Outputs.PlatformPropertiesResponse? Platform;
/// <summary>
/// The provisioning state of a run.
/// </summary>
public readonly string? ProvisioningState;
/// <summary>
/// The error message received from backend systems after the run is scheduled.
/// </summary>
public readonly string RunErrorMessage;
/// <summary>
/// The unique identifier for the run.
/// </summary>
public readonly string? RunId;
/// <summary>
/// The type of run.
/// </summary>
public readonly string? RunType;
/// <summary>
/// The scope of the credentials that were used to login to the source registry during this run.
/// </summary>
public readonly string? SourceRegistryAuth;
/// <summary>
/// The source trigger that caused the run.
/// </summary>
public readonly Outputs.SourceTriggerDescriptorResponse? SourceTrigger;
/// <summary>
/// The time the run started.
/// </summary>
public readonly string? StartTime;
/// <summary>
/// The current status of the run.
/// </summary>
public readonly string? Status;
/// <summary>
/// Metadata pertaining to creation and last modification of the resource.
/// </summary>
public readonly Outputs.SystemDataResponse SystemData;
/// <summary>
/// The task against which run was scheduled.
/// </summary>
public readonly string? Task;
/// <summary>
/// The timer trigger that caused the run.
/// </summary>
public readonly Outputs.TimerTriggerDescriptorResponse? TimerTrigger;
/// <summary>
/// The type of the resource.
/// </summary>
public readonly string Type;
/// <summary>
/// The update trigger token passed for the Run.
/// </summary>
public readonly string? UpdateTriggerToken;
[OutputConstructor]
private RunResponse(
Outputs.AgentPropertiesResponse? agentConfiguration,
string? agentPoolName,
string? createTime,
ImmutableArray<string> customRegistries,
string? finishTime,
string id,
Outputs.ImageUpdateTriggerResponse? imageUpdateTrigger,
bool? isArchiveEnabled,
string? lastUpdatedTime,
Outputs.ImageDescriptorResponse logArtifact,
string name,
ImmutableArray<Outputs.ImageDescriptorResponse> outputImages,
Outputs.PlatformPropertiesResponse? platform,
string? provisioningState,
string runErrorMessage,
string? runId,
string? runType,
string? sourceRegistryAuth,
Outputs.SourceTriggerDescriptorResponse? sourceTrigger,
string? startTime,
string? status,
Outputs.SystemDataResponse systemData,
string? task,
Outputs.TimerTriggerDescriptorResponse? timerTrigger,
string type,
string? updateTriggerToken)
{
AgentConfiguration = agentConfiguration;
AgentPoolName = agentPoolName;
CreateTime = createTime;
CustomRegistries = customRegistries;
FinishTime = finishTime;
Id = id;
ImageUpdateTrigger = imageUpdateTrigger;
IsArchiveEnabled = isArchiveEnabled;
LastUpdatedTime = lastUpdatedTime;
LogArtifact = logArtifact;
Name = name;
OutputImages = outputImages;
Platform = platform;
ProvisioningState = provisioningState;
RunErrorMessage = runErrorMessage;
RunId = runId;
RunType = runType;
SourceRegistryAuth = sourceRegistryAuth;
SourceTrigger = sourceTrigger;
StartTime = startTime;
Status = status;
SystemData = systemData;
Task = task;
TimerTrigger = timerTrigger;
Type = type;
UpdateTriggerToken = updateTriggerToken;
}
}
}
|
||||
TheStack | b594ac87b06a241f72a38c6b7e9862010d3edebd | C#code:C# | {"size": 834, "ext": "cs", "max_stars_repo_path": "src/Dibix.Testing/Configuration/InitializerConfigurationProxyDecisionStrategy.cs", "max_stars_repo_name": "Serviceware/Dibix", "max_stars_repo_stars_event_min_datetime": "2021-06-18T09:12:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T15:52:49.000Z", "max_issues_repo_path": "src/Dibix.Testing/Configuration/InitializerConfigurationProxyDecisionStrategy.cs", "max_issues_repo_name": "Serviceware/Dibix", "max_issues_repo_issues_event_min_datetime": "2021-08-24T18:49:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-24T18:49:46.000Z", "max_forks_repo_path": "src/Dibix.Testing/Configuration/InitializerConfigurationProxyDecisionStrategy.cs", "max_forks_repo_name": "Serviceware/Dibix", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 11.0, "max_issues_count": 1.0, "max_forks_count": null, "avg_line_length": 37.9090909091, "max_line_length": 154, "alphanum_fraction": 0.6774580336} | using System;
using System.Reflection;
namespace Dibix.Testing
{
internal sealed class InitializerConfigurationProxyDecisionStrategy : ConfigurationProxyDecisionStrategy
{
protected override bool ShouldBeWrapped(PropertyInfo property)
{
FieldInfo backingField = property.DeclaringType.GetField($"<{property.Name}>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance);
if (backingField == null)
return false;
ConstructorInfo constructor = property.DeclaringType.GetConstructor(Type.EmptyTypes);
if (constructor == null)
return false;
// TODO: Analyze the IL to determine if the property has an initializer (by setting the backing field to a value in the ctor)
return false;
}
}
} |
||||
TheStack | b5951154a6f55fafa56be71a6ff15f19a9e49878 | C#code:C# | {"size": 399, "ext": "cs", "max_stars_repo_path": "Semester2/HW_4_Task_1/HW_4_Task_1/Operand.cs", "max_stars_repo_name": "Semen-Tagiltsev/HomeWork_Semester_2", "max_stars_repo_stars_event_min_datetime": "2021-03-05T14:52:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-18T18:06:28.000Z", "max_issues_repo_path": "Semester2/HW_4_Task_1/HW_4_Task_1/Operand.cs", "max_issues_repo_name": "Semen-Tagiltsev/HomeWork_Semester_2", "max_issues_repo_issues_event_min_datetime": "2021-08-05T09:06:59.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-05T09:06:59.000Z", "max_forks_repo_path": "Semester2/HW_4_Task_1/HW_4_Task_1/Operand.cs", "max_forks_repo_name": "semtagg/ProgrammingSPBU", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 3.0, "max_issues_count": 1.0, "max_forks_count": null, "avg_line_length": 18.1363636364, "max_line_length": 42, "alphanum_fraction": 0.5162907268} | using System;
namespace HW_4_Task_1
{
/// <summary>
/// Tree node for expression operands.
/// </summary>
class Operand : INode
{
public double Value { get; set; }
public Operand(double value)
=> Value = value;
public double Calculate()
=> Value;
public void Print()
=> Console.Write($"{Value} ");
}
}
|
||||
TheStack | b5955ac489b9933bf33913b268e435897ba4c39a | C#code:C# | {"size": 1373, "ext": "cs", "max_stars_repo_path": "src/Microsoft.Owin.Hosting/Constants.cs", "max_stars_repo_name": "zerouid/katanaproject", "max_stars_repo_stars_event_min_datetime": "2018-09-10T08:36:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-03T20:57:08.000Z", "max_issues_repo_path": "src/Microsoft.Owin.Hosting/Constants.cs", "max_issues_repo_name": "zerouid/katanaproject", "max_issues_repo_issues_event_min_datetime": "2019-12-24T13:53:41.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-24T13:53:41.000Z", "max_forks_repo_path": "src/Microsoft.Owin.Hosting/Constants.cs", "max_forks_repo_name": "zerouid/katanaproject", "max_forks_repo_forks_event_min_datetime": "2018-10-25T15:15:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-03T06:34:29.000Z"} | {"max_stars_count": 6.0, "max_issues_count": 1.0, "max_forks_count": 8.0, "avg_line_length": 44.2903225806, "max_line_length": 133, "alphanum_fraction": 0.6991988347} | // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
namespace Microsoft.Owin.Hosting
{
internal static class Constants
{
internal const string HostTraceOutput = "host.TraceOutput";
internal const string HostTraceSource = "host.TraceSource";
internal const string HostOnAppDisposing = "host.OnAppDisposing";
internal const string HostAddresses = "host.Addresses";
internal const string HostAppName = "host.AppName";
internal const string HostAppMode = "host.AppMode";
internal const string AppModeDevelopment = "development";
internal const string OwinServerFactory = "OwinServerFactory";
internal const string SettingsOwinServer = "owin:Server";
internal const string EnvOwnServer = "OWIN_SERVER";
internal const string DefaultServer = "Microsoft.Owin.Host.HttpListener";
internal const string SettingsPort = "owin:Port";
internal const string EnvPort = "PORT";
internal const int DefaultPort = 5000;
internal const string SettingsOwinAppStartup = "owin:AppStartup";
internal const string Scheme = "scheme";
internal const string Host = "host";
internal const string Port = "port";
internal const string Path = "path";
}
}
|
||||
TheStack | b59699c26c1b2782a0d1aafe78d859ca58f5cfdd | C#code:C# | {"size": 572, "ext": "cs", "max_stars_repo_path": "Assets/Scripts/Terrain/TerrainType.cs", "max_stars_repo_name": "NateBowman/RunBabyRun", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Assets/Scripts/Terrain/TerrainType.cs", "max_issues_repo_name": "NateBowman/RunBabyRun", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Assets/Scripts/Terrain/TerrainType.cs", "max_forks_repo_name": "NateBowman/RunBabyRun", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 38.1333333333, "max_line_length": 121, "alphanum_fraction": 0.3618881119} | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="TerrainType.cs">
// Copyright (c) Nathan Bowman. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Terrain
{
public enum TerrainType
{
FlatTerrain,
Ramp,
}
} |
||||
TheStack | b596eca6f5150ae2fa50ebe1c7cfc37b47f810e5 | C#code:C# | {"size": 9664, "ext": "cs", "max_stars_repo_path": "WinDirStat.Net.Wpf.Base/Native/Win32.FindFile.cs", "max_stars_repo_name": "ImportTaste/WinDirStat.Net", "max_stars_repo_stars_event_min_datetime": "2019-05-16T06:53:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T13:39:27.000Z", "max_issues_repo_path": "WinDirStat.Net.Wpf.Base/Native/Win32.FindFile.cs", "max_issues_repo_name": "ImportTaste/WinDirStat.Net", "max_issues_repo_issues_event_min_datetime": "2019-05-24T18:39:06.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-15T19:07:33.000Z", "max_forks_repo_path": "WinDirStat.Net.Wpf.Base/Native/Win32.FindFile.cs", "max_forks_repo_name": "ImportTaste/WinDirStat.Net", "max_forks_repo_forks_event_min_datetime": "2019-05-24T18:40:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-06T02:23:37.000Z"} | {"max_stars_count": 42.0, "max_issues_count": 5.0, "max_forks_count": 14.0, "avg_line_length": 42.3859649123, "max_line_length": 102, "alphanum_fraction": 0.6988824503} | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using FILETIME = System.Runtime.InteropServices.ComTypes.FILETIME;
namespace WinDirStat.Net.Native {
partial class Win32 {
/// <summary>
/// Searches a directory for a file or subdirectory with a name and attributes that match those
/// specified.
/// </summary>
///
/// <param name="lpFileName">
/// The directory or path, and the file name. The file name can include wildcard characters, for
/// example, an asterisk (*) or a question mark (?).
/// </param>
/// <param name="fInfoLevelId">The information level of the returned data.</param>
/// <param name="lpFindFileData">
/// A reference to the <see cref="Win32FindData"/> that receives the file data.
/// </param>
/// <param name="fSearchOp">
/// The type of filtering to perform that is different from wildcard matching.
/// </param>
/// <param name="lpSearchFilter">
/// A pointer to the search criteria if the specified fSearchOp needs structured search information.
/// </param>
/// <param name="dwAdditionalFlags">Specifies additional flags that control the search.</param>
/// <returns>
/// If the function succeeds, the return value is a search handle used in a subsequent call to
/// <see cref="FindNextFile"/> or <see cref="FindClose"/>, and the <paramref name="lpFindFileData"/>
/// parameter contains information about the first file or directory found.
/// <para/>
/// If the function fails or fails to locate files from the search string in the lpFileName
/// parameter, the return value is <see cref="InvalidHandle"/>.
/// </returns>
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern IntPtr FindFirstFileEx(
string lpFileName,
FindExInfoLevels fInfoLevelId,
out Win32FindData lpFindFileData,
FindExSearchOps fSearchOp,
IntPtr lpSearchFilter,
[MarshalAs(UnmanagedType.U4)] FindExFlags dwAdditionalFlags);
/// <summary>
/// Continues a file search from a previous call to the <see cref="FindFirstFileEx"/> function.
/// </summary>
///
/// <param name="hFindFile">
/// The search handle returned by a previous call to the <see cref="FindFirstFileEx"/> function.
/// </param>
/// <param name="lpFindFileData">
/// A pointer to the <see cref="Win32FindData"/> structure that receives information about the found
/// file or subdirectory.
/// </param>
/// <returns>
/// If the function succeeds, the return value is true and the <paramref name="lpFindFileData"/>
/// parameter contains information about the next file or directory found.
/// </returns>
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern bool FindNextFile(
IntPtr hFindFile,
out Win32FindData lpFindFileData);
/// <summary>
/// Closes a file search handle opened by the <see cref="FindFirstFileEx"/> function.
/// </summary>
///
/// <param name="hFindFile">The file search handle.</param>
/// <returns>If the function succeeds, the return value is true.</returns>
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool FindClose(
IntPtr hFindFile);
/// <summary>
/// Contains information about the file that is found by the <see cref="FindFirstFileEx"/>, or <see
/// cref="FindNextFile"/> function.
/// </summary>
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct Win32FindData {
/// <summary>The file attributes of a file.</summary>
[MarshalAs(UnmanagedType.U4)]
public FileAttributes dwFileAttributes;
/// <summary>
/// A <see cref="FILETIME"/> structure that specifies when a file or directory was created.
/// </summary>
public FILETIME ftCreationTime;
/// <summary>
/// For a file, the structure specifies when the file was last read from, written to, or for
/// executable files, run.
/// <para/>
/// For a directory, the structure specifies when the directory is created. If the underlying
/// file system does not support last access time, this member is zero.
/// <para/>
/// On the FAT file system, the specified date for both files and directories is correct, but the
/// time of day is always set to midnight.
/// </summary>
public FILETIME ftLastAccessTime;
/// <summary>
/// For a file, the structure specifies when the file was last written to, truncated, or
/// overwritten. The date and time are not updated when file attributes or security descriptors
/// are changed.
/// </summary>
public FILETIME ftLastWriteTime;
/// <summary>The high-order <see cref="uint"/> value of the file size, in bytes.</summary>
public int nFileSizeHigh;
/// <summary>The low-order <see cref="uint"/> value of the file size, in bytes.</summary>
public uint nFileSizeLow;
/// <summary>Reserved for future use.</summary>
public uint dwReserved0;
/// <summary>Reserved for future use.</summary>
public uint dwReserved1;
/// <summary>The name of the file.</summary>
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public string cFileName;
//[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 14)]
//public string cAlternateFileName;
/// <summary>True if the file is a directory.</summary>
public bool IsDirectory {
get => (dwFileAttributes.HasFlag(FileAttributes.Directory));
}
/// <summary>True if the file is a symbolic link.</summary>
public bool IsSymbolicLink {
get => (dwFileAttributes.HasFlag(FileAttributes.ReparsePoint));
}
/// <summary>True if the file is a relative directory and should be ignored.</summary>
public bool IsRelativeDirectory {
get => (cFileName == "." || cFileName == "..");
}
/// <summary>The full size of the file.</summary>
public long Size {
get => ((long) nFileSizeHigh << 32) | nFileSizeLow;
}
/// <summary>The UTC creation time of the file.</summary>
public DateTime CreationTimeUtc {
get => ftCreationTime.ToDateTimeUtc();
}
/// <summary>The local creation time of the file.</summary>
public DateTime CreationTime {
get => ftCreationTime.ToDateTime();
}
/// <summary>The UTC last access time of the file.</summary>
public DateTime LastAccessTimeUtc {
get => ftLastAccessTime.ToDateTimeUtc();
}
/// <summary>The local last access time of the file.</summary>
public DateTime LastAccessTime {
get => ftLastAccessTime.ToDateTime();
}
/// <summary>The UTC last write time of the file.</summary>
public DateTime LastWriteTimeUtc {
get => ftLastWriteTime.ToDateTimeUtc();
}
/// <summary>The local last write time of the file.</summary>
public DateTime LastWriteTime {
get => ftLastWriteTime.ToDateTime();
}
}
public enum FindExInfoLevels {
/// <summary>
/// The FindFirstFileEx function retrieves a standard set of attribute information. The data is
/// returned in a <see cref="Win32FindData"/> structure.
/// </summary>
Standard,
/// <summary>
/// The FindFirstFileEx function does not query the short file name, improving overall
/// enumeration speed.The data is returned in a WIN32_FIND_DATA structure, and the
/// cAlternateFileName member is always a NULL string. Windows Server 2008, Windows Vista,
/// Windows Server 2003 and Windows XP: This value is not supported until Windows Server 2008 R2
/// and Windows 7.
/// </summary>
Basic,
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
MaxInfoLevel,
}
public enum FindExSearchOps {
/// <summary>
/// The search for a file that matches a specified file name. The lpSearchFilter parameter of
/// <see cref="FindFirstFileEx"/> must be NULL when this search operation is used.
/// </summary>
NameMatch,
/// <summary>
/// This is an advisory flag. If the file system supports directory filtering, the function
/// searches for a file that matches the specified name and is also a directory. If the file
/// system does not support directory filtering, this flag is silently ignored. The
/// lpSearchFilter parameter of the FindFirstFileEx function must be NULL when this search value
/// is used. If directory filtering is desired, this flag can be used on all file systems, but
/// because it is an advisory flag and only affects file systems that support it, the application
/// must examine the file attribute data stored in the lpFindFileData parameter of the <see cref=
/// "FindFirstFileEx"/> function to determine whether the function has returned a handle to a
/// directory.
/// </summary>
LimitToDirectories,
/// <summary>This filtering type is not available.</summary>
LimitToDevices,
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
MaxSearchOp,
}
[Flags]
public enum FindExFlags : uint {
/// <summary>No flags.</summary>
None = 0,
/// <summary>Searches are case-sensitive.</summary>
CaseSensitive = 1,
/// <summary>
/// Uses a larger buffer for directory queries, which can increase performance of the find
/// operation. Windows Server 2008, Windows Vista, Windows Server 2003 and Windows XP: This
/// value is not supported until Windows Server 2008 R2 and Windows 7.
/// </summary>
LargeFetch = 2,
/// <summary>
/// Limits the results to files that are physically on disk. This flag is only relevant when a
/// file virtualization filter is present.
/// </summary>
OnDiskEntriesOnly = 4,
}
}
}
|
||||
TheStack | b59908d0fa7b2d8302a2b0309bf4699f6b50ec18 | C#code:C# | {"size": 3862, "ext": "cs", "max_stars_repo_path": "DotNetGB.WpfGui/EmulatorDisplay.xaml.cs", "max_stars_repo_name": "paulirwin/dotnetgb", "max_stars_repo_stars_event_min_datetime": "2020-09-20T17:10:46.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-20T17:10:46.000Z", "max_issues_repo_path": "DotNetGB.WpfGui/EmulatorDisplay.xaml.cs", "max_issues_repo_name": "paulirwin/dotnetgb", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DotNetGB.WpfGui/EmulatorDisplay.xaml.cs", "max_forks_repo_name": "paulirwin/dotnetgb", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 24.1375, "max_line_length": 137, "alphanum_fraction": 0.4274987053} | using System;
using System.Threading;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using DotNetGB.Hardware;
namespace DotNetGB.WpfGui
{
public partial class EmulatorDisplay : IDisplay
{
public const int DISPLAY_WIDTH = 160;
public const int DISPLAY_HEIGHT = 144;
private const int STRIDE = DISPLAY_WIDTH * 3; // 3 bytes (24 bits) per pixel
public static readonly int[] COLORS = {
0xe6f8da, 0x99c886, 0x437969, 0x051f2a
};
private readonly byte[] _pixels;
private volatile bool _enabled;
private volatile bool _doStop;
private volatile bool _doRefresh;
private int _i;
private readonly Int32Rect _rect = new Int32Rect(0, 0, DISPLAY_WIDTH, DISPLAY_HEIGHT);
public EmulatorDisplay()
{
InitializeComponent();
Loaded += OnLoaded;
_pixels = new byte[DISPLAY_WIDTH * DISPLAY_HEIGHT * STRIDE];
Array.Fill(_pixels, (byte)0);
}
public WriteableBitmap Display { get; } = new WriteableBitmap(DISPLAY_WIDTH, DISPLAY_HEIGHT, 96d, 96d, PixelFormats.Rgb24, null);
private void OnLoaded(object sender, RoutedEventArgs e)
{
DisplayImage.Source = Display;
DrawImage();
}
public void PutDmgPixel(int color)
{
int c = COLORS[color];
byte r = (byte)(c >> 16);
byte g = (byte)((c >> 8) & 0xff);
byte b = (byte)(c & 0xff);
_pixels[_i++] = r;
_pixels[_i++] = g;
_pixels[_i++] = b;
}
public void PutColorPixel(int gbcRgb)
{
byte r = (byte)((gbcRgb & 0x1f) * 8);
byte g = (byte)(((gbcRgb >> 5) & 0x1f) * 8);
byte b = (byte)(((gbcRgb >> 10) & 0x1f) * 8);
_pixels[_i++] = r;
_pixels[_i++] = g;
_pixels[_i++] = b;
}
public void RequestRefresh()
{
_doRefresh = true;
lock (this)
{
Monitor.PulseAll(this);
}
}
public void WaitForRefresh()
{
while (_doRefresh)
{
lock (this)
{
try
{
Monitor.Wait(this, 1);
}
catch (ThreadInterruptedException)
{
break;
}
}
}
}
public void EnableLcd()
{
_enabled = true;
}
public void DisableLcd()
{
_enabled = false;
}
public void Run()
{
_doStop = false;
_doRefresh = false;
_enabled = true;
while (!_doStop)
{
lock (this)
{
try
{
Monitor.Wait(this, 1);
}
catch (ThreadInterruptedException)
{
break;
}
}
if (_doRefresh)
{
Dispatcher.InvokeAsync(DrawImage);
lock (this)
{
_i = 0;
_doRefresh = false;
Monitor.PulseAll(this);
}
}
}
}
public void Stop()
{
_doStop = true;
}
private void DrawImage()
{
Display.Lock();
Display.WritePixels(_rect, _pixels, STRIDE, 0);
Display.Unlock();
}
}
}
|
||||
TheStack | b59971740c79738dc67b4daf8c1ca0d4c4b1dc6c | C#code:C# | {"size": 2315, "ext": "cs", "max_stars_repo_path": "test/GoodREST.Core.Test.Services/CustomerService.cs", "max_stars_repo_name": "tailored-apps/GoodREST.IO", "max_stars_repo_stars_event_min_datetime": "2019-06-04T16:23:43.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-24T16:47:49.000Z", "max_issues_repo_path": "test/GoodREST.Core.Test.Services/CustomerService.cs", "max_issues_repo_name": "tailored-apps/GoodREST.IO", "max_issues_repo_issues_event_min_datetime": "2019-04-11T14:55:07.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-27T12:43:07.000Z", "max_forks_repo_path": "test/GoodREST.Core.Test.Services/CustomerService.cs", "max_forks_repo_name": "tailored-apps/GoodREST.IO", "max_forks_repo_forks_event_min_datetime": "2020-06-01T06:38:42.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-01T06:38:42.000Z"} | {"max_stars_count": 28.0, "max_issues_count": 16.0, "max_forks_count": 1.0, "avg_line_length": 28.9375, "max_line_length": 97, "alphanum_fraction": 0.5524838013} | using GoodREST.Annotations;
using GoodREST.Core.Test.DataModel.Messages;
using GoodREST.Extensions;
using GoodREST.Middleware.Services;
using System;
namespace GoodREST.Core.Test.Services
{
[ServiceDescription(Description = "Customer Service")]
public class CustomerService : ServiceBase
{
private readonly IMockingRepository mockingRepository;
public CustomerService(IMockingRepository mockingRepository)
{
this.mockingRepository = mockingRepository;
}
public GetCustomersResponse Get(GetCustomers request)
{
var response = new GetCustomersResponse();
try
{
response.Customers = this.mockingRepository.GetCustomers();
response.Ok();
}
catch (Exception ex)
{
response.ConvertExceptionAsError(ex, 500);
}
return response;
}
public PostCustomerResponse Post(PostCustomer request)
{
var response = new PostCustomerResponse();
try
{
response.Customer = mockingRepository.Save(request.Customer);
response.Ok();
}
catch (Exception ex)
{
response.ConvertExceptionAsError(ex, 500);
}
return response;
}
public PutCustomerResponse Put(PutCustomer request)
{
var response = new PutCustomerResponse();
try
{
var customerToUpdate = mockingRepository.GetCustomer(request.Id);
response.Customer = mockingRepository.Update(customerToUpdate, request.Customer);
response.Ok();
}
catch (Exception ex)
{
response.ConvertExceptionAsError(ex, 500);
}
return response;
}
public DeleteCustomerResponse Delete(DeleteCustomer request)
{
var response = new DeleteCustomerResponse(); try
{
response.HttpStatusCode = 200;
}
catch (Exception ex)
{
response.ConvertExceptionAsError(ex, 500);
}
return response;
}
}
} |
||||
TheStack | b59b7861131128cc64ba562eab063534658dc261 | C#code:C# | {"size": 14230, "ext": "cs", "max_stars_repo_path": "DoAn_QLCC/Log_Options.Designer.cs", "max_stars_repo_name": "broteam168/Child-Manager", "max_stars_repo_stars_event_min_datetime": "2020-06-22T12:12:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-10T15:38:05.000Z", "max_issues_repo_path": "DoAn_QLCC/Log_Options.Designer.cs", "max_issues_repo_name": "broteam168/Child-Manager", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DoAn_QLCC/Log_Options.Designer.cs", "max_forks_repo_name": "broteam168/Child-Manager", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 2.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 53.9015151515, "max_line_length": 173, "alphanum_fraction": 0.6137034434} | namespace DoAn_QLCC
{
partial class Log_Options
{
/// <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.label1 = new System.Windows.Forms.Label();
this.panel1 = new System.Windows.Forms.Panel();
this.label_size_WebCam = new System.Windows.Forms.Label();
this.label_Size_screenShoots = new System.Windows.Forms.Label();
this.Label_Web_Size = new System.Windows.Forms.Label();
this.Label_Size_App = new System.Windows.Forms.Label();
this.Label_ClipBoard_Size = new System.Windows.Forms.Label();
this.label_KeystrokeSize = new System.Windows.Forms.Label();
this.label7 = new System.Windows.Forms.Label();
this.label6 = new System.Windows.Forms.Label();
this.label5 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.simpleButton3 = new DevExpress.XtraEditors.SimpleButton();
this.simpleButton2 = new DevExpress.XtraEditors.SimpleButton();
this.simpleButton1 = new DevExpress.XtraEditors.SimpleButton();
this.panel1.SuspendLayout();
this.SuspendLayout();
//
// label1
//
this.label1.BackColor = System.Drawing.SystemColors.InactiveCaption;
this.label1.Dock = System.Windows.Forms.DockStyle.Top;
this.label1.Font = new System.Drawing.Font("Tahoma", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label1.Location = new System.Drawing.Point(0, 0);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(876, 31);
this.label1.TabIndex = 0;
this.label1.Text = "Log";
//
// panel1
//
this.panel1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.panel1.Controls.Add(this.label_size_WebCam);
this.panel1.Controls.Add(this.label_Size_screenShoots);
this.panel1.Controls.Add(this.Label_Web_Size);
this.panel1.Controls.Add(this.Label_Size_App);
this.panel1.Controls.Add(this.Label_ClipBoard_Size);
this.panel1.Controls.Add(this.label_KeystrokeSize);
this.panel1.Controls.Add(this.label7);
this.panel1.Controls.Add(this.label6);
this.panel1.Controls.Add(this.label5);
this.panel1.Controls.Add(this.label4);
this.panel1.Controls.Add(this.label3);
this.panel1.Controls.Add(this.label2);
this.panel1.Controls.Add(this.simpleButton3);
this.panel1.Controls.Add(this.simpleButton2);
this.panel1.Controls.Add(this.simpleButton1);
this.panel1.Font = new System.Drawing.Font("Tahoma", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.panel1.Location = new System.Drawing.Point(4, 34);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(872, 445);
this.panel1.TabIndex = 1;
//
// label_size_WebCam
//
this.label_size_WebCam.Font = new System.Drawing.Font("Tahoma", 15.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label_size_WebCam.Location = new System.Drawing.Point(627, 343);
this.label_size_WebCam.Name = "label_size_WebCam";
this.label_size_WebCam.Size = new System.Drawing.Size(110, 30);
this.label_size_WebCam.TabIndex = 16;
this.label_size_WebCam.Text = "0 bytes";
//
// label_Size_screenShoots
//
this.label_Size_screenShoots.Font = new System.Drawing.Font("Tahoma", 15.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label_Size_screenShoots.Location = new System.Drawing.Point(673, 297);
this.label_Size_screenShoots.Name = "label_Size_screenShoots";
this.label_Size_screenShoots.Size = new System.Drawing.Size(110, 30);
this.label_Size_screenShoots.TabIndex = 15;
this.label_Size_screenShoots.Text = "0 bytes";
//
// Label_Web_Size
//
this.Label_Web_Size.Font = new System.Drawing.Font("Tahoma", 15.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.Label_Web_Size.Location = new System.Drawing.Point(303, 373);
this.Label_Web_Size.Name = "Label_Web_Size";
this.Label_Web_Size.Size = new System.Drawing.Size(110, 30);
this.Label_Web_Size.TabIndex = 14;
this.Label_Web_Size.Text = "0 bytes";
this.Label_Web_Size.Click += new System.EventHandler(this.Label_Web_Size_Click);
//
// Label_Size_App
//
this.Label_Size_App.Font = new System.Drawing.Font("Tahoma", 15.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.Label_Size_App.Location = new System.Drawing.Point(282, 343);
this.Label_Size_App.Name = "Label_Size_App";
this.Label_Size_App.Size = new System.Drawing.Size(110, 30);
this.Label_Size_App.TabIndex = 13;
this.Label_Size_App.Text = "0 bytes";
//
// Label_ClipBoard_Size
//
this.Label_ClipBoard_Size.Font = new System.Drawing.Font("Tahoma", 15.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.Label_ClipBoard_Size.Location = new System.Drawing.Point(282, 313);
this.Label_ClipBoard_Size.Name = "Label_ClipBoard_Size";
this.Label_ClipBoard_Size.Size = new System.Drawing.Size(110, 30);
this.Label_ClipBoard_Size.TabIndex = 12;
this.Label_ClipBoard_Size.Text = "0 bytes";
//
// label_KeystrokeSize
//
this.label_KeystrokeSize.Font = new System.Drawing.Font("Tahoma", 15.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label_KeystrokeSize.Location = new System.Drawing.Point(282, 279);
this.label_KeystrokeSize.Name = "label_KeystrokeSize";
this.label_KeystrokeSize.Size = new System.Drawing.Size(110, 30);
this.label_KeystrokeSize.TabIndex = 11;
this.label_KeystrokeSize.Text = "0 bytes";
//
// label7
//
this.label7.Font = new System.Drawing.Font("Tahoma", 15.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label7.Location = new System.Drawing.Point(442, 343);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(233, 30);
this.label7.TabIndex = 10;
this.label7.Text = "WebCam logs size :";
//
// label6
//
this.label6.Font = new System.Drawing.Font("Tahoma", 15.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label6.Location = new System.Drawing.Point(89, 373);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(231, 30);
this.label6.TabIndex = 9;
this.label6.Text = "Web broswer logs size:";
this.label6.Click += new System.EventHandler(this.label6_Click);
//
// label5
//
this.label5.Font = new System.Drawing.Font("Tahoma", 15.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label5.Location = new System.Drawing.Point(442, 297);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(238, 30);
this.label5.TabIndex = 8;
this.label5.Text = "ScreenShoots logs size :";
//
// label4
//
this.label4.Font = new System.Drawing.Font("Tahoma", 15.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label4.Location = new System.Drawing.Point(89, 343);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(212, 30);
this.label4.TabIndex = 7;
this.label4.Text = "Application logs size:";
//
// label3
//
this.label3.Font = new System.Drawing.Font("Tahoma", 15.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label3.Location = new System.Drawing.Point(89, 313);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(212, 30);
this.label3.TabIndex = 6;
this.label3.Text = "ClipBoard logs size:";
//
// label2
//
this.label2.Font = new System.Drawing.Font("Tahoma", 15.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label2.Location = new System.Drawing.Point(89, 279);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(212, 30);
this.label2.TabIndex = 5;
this.label2.Text = "Keystroke logs size:";
//
// simpleButton3
//
this.simpleButton3.Appearance.Font = new System.Drawing.Font("Tahoma", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.simpleButton3.Appearance.Options.UseFont = true;
this.simpleButton3.Location = new System.Drawing.Point(452, 112);
this.simpleButton3.Name = "simpleButton3";
this.simpleButton3.Size = new System.Drawing.Size(268, 62);
this.simpleButton3.TabIndex = 4;
this.simpleButton3.Text = "Stop Logging";
this.simpleButton3.Click += new System.EventHandler(this.simpleButton3_Click);
//
// simpleButton2
//
this.simpleButton2.Appearance.Font = new System.Drawing.Font("Tahoma", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.simpleButton2.Appearance.Options.UseFont = true;
this.simpleButton2.Location = new System.Drawing.Point(77, 180);
this.simpleButton2.Name = "simpleButton2";
this.simpleButton2.Size = new System.Drawing.Size(243, 75);
this.simpleButton2.TabIndex = 3;
this.simpleButton2.Text = "Clear Log...";
this.simpleButton2.Click += new System.EventHandler(this.simpleButton2_Click);
//
// simpleButton1
//
this.simpleButton1.Appearance.Font = new System.Drawing.Font("Tahoma", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.simpleButton1.Appearance.Options.UseFont = true;
this.simpleButton1.Location = new System.Drawing.Point(77, 52);
this.simpleButton1.Name = "simpleButton1";
this.simpleButton1.Size = new System.Drawing.Size(243, 75);
this.simpleButton1.TabIndex = 1;
this.simpleButton1.Text = "View log...";
this.simpleButton1.Click += new System.EventHandler(this.simpleButton1_Click);
//
// Log_Options
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(876, 474);
this.Controls.Add(this.panel1);
this.Controls.Add(this.label1);
this.Name = "Log_Options";
this.Text = "Log general";
this.Load += new System.EventHandler(this.Log_Options_Load);
this.panel1.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Panel panel1;
private DevExpress.XtraEditors.SimpleButton simpleButton1;
private DevExpress.XtraEditors.SimpleButton simpleButton2;
private System.Windows.Forms.Label label_KeystrokeSize;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label2;
private DevExpress.XtraEditors.SimpleButton simpleButton3;
private System.Windows.Forms.Label Label_ClipBoard_Size;
private System.Windows.Forms.Label label_size_WebCam;
private System.Windows.Forms.Label label_Size_screenShoots;
private System.Windows.Forms.Label Label_Web_Size;
private System.Windows.Forms.Label Label_Size_App;
}
} |
||||
TheStack | b59ba41200d9401a724d38c550b63fedd87baafd | C#code:C# | {"size": 88, "ext": "cshtml", "max_stars_repo_path": "Source/Web/SportsBook.Web/Views/Shared/EditorTemplates/ContentCommentTemplate.cshtml", "max_stars_repo_name": "emilti/sportsbook", "max_stars_repo_stars_event_min_datetime": "2021-07-13T16:28:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-13T16:28:51.000Z", "max_issues_repo_path": "Source/Web/SportsBook.Web/Views/Shared/EditorTemplates/ContentCommentTemplate.cshtml", "max_issues_repo_name": "emilti/sportsbook", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Source/Web/SportsBook.Web/Views/Shared/EditorTemplates/ContentCommentTemplate.cshtml", "max_forks_repo_name": "emilti/sportsbook", "max_forks_repo_forks_event_min_datetime": "2018-06-09T16:15:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-12T18:50:58.000Z"} | {"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": 2.0, "avg_line_length": 44.0, "max_line_length": 73, "alphanum_fraction": 0.7272727273} | @model string
<textarea class="form-control" rows="5" name="content">@Model</textarea> |
||||
TheStack | b59be06b1c715b9542fddb1e8a3f4d78a6f5cb2d | C#code:C# | {"size": 12503, "ext": "cs", "max_stars_repo_path": "JobToolkit.DBRepository.Standard/DBJobRepository.cs", "max_stars_repo_name": "iTecBridge/JobToolkit", "max_stars_repo_stars_event_min_datetime": "2017-03-14T20:32:49.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-01T00:25:46.000Z", "max_issues_repo_path": "JobToolkit.DBRepository.Standard/DBJobRepository.cs", "max_issues_repo_name": "InfoTechBridge/JobToolkit", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "JobToolkit.DBRepository.Standard/DBJobRepository.cs", "max_forks_repo_name": "InfoTechBridge/JobToolkit", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 5.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 37.6596385542, "max_line_length": 156, "alphanum_fraction": 0.5025993761} | using JobToolkit.Core;
using ORMToolkit.Core;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace JobToolkit.DBRepository
{
public class DBJobRepository : IJobRepository, IEnumerable
{
private readonly IFormatter Formatter;
private readonly IDataManager DataManager;
public DBJobRepository(IDataManager dataManager)
{
this.DataManager = dataManager;
this.Formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
}
public DBJobRepository(IDataManager dataManager, IFormatter formatter)
{
this.DataManager = dataManager;
this.Formatter = formatter;
}
public virtual string Add(Job job)
{
var dbJob = new DBJob
{
Id = job.Id,
Title = job.Title,
TaskData = SerializeTaskAsString(job.Task),
Priority = job.Priority,
Enabled = job.Enabled,
Status = job.Status,
ScheduleTime = job.ScheduleTime,
Cron = job.Cron?.Expression,
NextScheduleTime = job.NextScheduleTime,
ScheduleEndTime = job.ScheduleEndTime,
LastExecutanInfoId = job.LastExecutanInfo?.Id,
MaxRetryAttempts = job.AutomaticRetry?.MaxRetryAttempts,
Owner = job.Owner,
Description = job.Description,
CreateTime = job.CreateTime,
UpdateTime = job.UpdateTime,
};
DataManager.Insert(dbJob);
return job.Id;
}
public virtual Job Get(string jobId)
{
Job job = null;
var dbJob = DataManager.Get<DBJob>(new { Id = jobId });
if(dbJob != null)
{
job = new Job(Deserialize(dbJob.TaskData))
{
Id = dbJob.Id,
Title = dbJob.Title,
Priority = dbJob.Priority,
Enabled = dbJob.Enabled,
Status = dbJob.Status,
Cron = dbJob.Cron != null ? new CronExpression(dbJob.Cron) : null,
ScheduleTime = dbJob.ScheduleTime,
NextScheduleTime = dbJob.NextScheduleTime,
ScheduleEndTime = dbJob.ScheduleEndTime,
LastExecutanInfo = null,
AutomaticRetry = dbJob.MaxRetryAttempts != null ? new AutomaticRetryPolicy() { MaxRetryAttempts = dbJob.MaxRetryAttempts.Value } : null,
Owner = dbJob.Owner,
Description = dbJob.Description,
CreateTime = dbJob.CreateTime,
UpdateTime = dbJob.UpdateTime,
};
if (dbJob.LastExecutanInfoId != null)
{
var dbJobExec = DataManager.Get<DBJobExec>(new { Id = dbJob.LastExecutanInfoId, JobId = dbJob.Id });
if (dbJobExec != null)
{
job.LastExecutanInfo = new JobExecutanInfo()
{
Id = dbJobExec.Id,
JobId = dbJobExec.JobId,
RetryNumber = dbJobExec.RetryNumber,
StartTime = dbJobExec.StartTime,
EndTime = dbJobExec.EndTime,
Status = dbJobExec.Status,
Description = dbJobExec.Description,
NextRetryTime = dbJobExec.NextRetryTime,
};
}
}
}
return job;
}
public virtual void Update(Job job)
{
var dbJob = new
{
Id = job.Id,
Title = job.Title,
TaskData = SerializeTaskAsString(job.Task),
Priority = job.Priority,
Enabled = job.Enabled,
Status = job.Status,
ScheduleTime = job.ScheduleTime,
Cron = job.Cron?.Expression,
NextScheduleTime = job.NextScheduleTime,
ScheduleEndTime = job.ScheduleEndTime,
LastExecutanInfoId = job.LastExecutanInfo?.Id,
MaxRetryAttempts = job.AutomaticRetry?.MaxRetryAttempts,
Owner = job.Owner,
Description = job.Description,
UpdateTime = job.UpdateTime,
};
DataManager.Update<DBJob>(dbJob, new { Id = job.Id });
}
public virtual void UpdatExecStatus(Job job)
{
var dbJob = new
{
Status = job.Status,
NextScheduleTime = job.NextScheduleTime,
LastExecutanInfoId = job.LastExecutanInfo?.Id,
UpdateTime = job.UpdateTime
};
DataManager.Update<DBJob>(dbJob, new { Id = job.Id });
if (job.LastExecutanInfo != null)
{
if (job.LastExecutanInfo.Status == JobExecutanStatus.Running) // new execInfo
{
var dbJobExec = new DBJobExec
{
Id = job.LastExecutanInfo.Id,
JobId = job.LastExecutanInfo.JobId,// job.Id,
RetryNumber = job.LastExecutanInfo.RetryNumber,
StartTime = job.LastExecutanInfo.StartTime,
EndTime = job.LastExecutanInfo.EndTime,
Status = job.LastExecutanInfo.Status,
Description = job.LastExecutanInfo.Description,
NextRetryTime = job.LastExecutanInfo.NextRetryTime,
};
DataManager.Insert(dbJobExec);
}
else
{
var dbJobExec = new
{
EndTime = job.LastExecutanInfo.EndTime,
Status = job.LastExecutanInfo.Status,
Description = job.LastExecutanInfo.Description,
NextRetryTime = job.LastExecutanInfo.NextRetryTime
};
DataManager.Update<DBJobExec>(dbJobExec, new { Id = job.LastExecutanInfo.Id });
}
}
}
public virtual Job Remove(string jobId)
{
var job = Get(jobId);
if(job != null)
{
//DataManager.Delete<JobExecutanInfo>(new { Id = job.LastExecutanInfo.Id });
//DataManager.Delete<DBJob>(new { Id = job.Id });
}
return job;
}
public virtual void RemoveAll()
{
throw new NotImplementedException();
}
public virtual List<Job> GetAll()
{
return GetAll(new JobDataQueryCriteria());
}
public virtual List<Job> GetAll(JobDataQueryCriteria criteria)
{
string sql = @"select Job.*, JobExec.RetryNumber, JobExec.StartTime, JobExec.EndTime
, JobExec.Status as ExecStatus, JobExec.Description as ExecDescription, JobExec.NextRetryTime
from job left join JobExec on job.LastExecutanInfoId = JobExec.id";
string whereStr = ParseCriteria(criteria);
if (!string.IsNullOrEmpty(whereStr))
sql += " where " + whereStr;
List<Job> jobs = new List<Job>();
var resault = DataManager.Query<DBJobSummary>(sql, criteria);
foreach (var item in resault)
{
JobExecutanInfo lastExecutanInfo = null;
if (item.LastExecutanInfoId != null)
{
lastExecutanInfo = new JobExecutanInfo()
{
Id = item.LastExecutanInfoId,
JobId = item.Id,
RetryNumber = item.RetryNumber,
StartTime = item.StartTime,
EndTime = item.EndTime,
Status = (JobExecutanStatus)item.ExecStatus,
Description = item.ExecDescription,
NextRetryTime = item.NextRetryTime,
};
}
Job job = new Job(Deserialize(item.TaskData))
{
Id = item.Id,
Title = item.Title,
Priority = item.Priority,
Enabled = item.Enabled,
Status = (JobStatus)item.Status,
Cron = item.Cron != null ? new CronExpression(item.Cron) : null,
ScheduleTime = item.ScheduleTime,
NextScheduleTime = item.NextScheduleTime,
ScheduleEndTime = item.ScheduleEndTime,
LastExecutanInfo = lastExecutanInfo,
AutomaticRetry = item.MaxRetryAttempts != null ? new AutomaticRetryPolicy() { MaxRetryAttempts = item.MaxRetryAttempts.Value } : null,
Owner = item.Owner,
Description = item.Description,
CreateTime = item.CreateTime,
UpdateTime = item.UpdateTime,
};
jobs.Add(job);
}
return jobs;
}
private string ParseCriteria(JobDataQueryCriteria criteria)
{
string whereStr = "";
if (criteria.Id != null)
whereStr += " and job.Id = @Id";
if (criteria.NextScheduleTimeIsNull != null)
{
if (criteria.NextScheduleTimeIsNull.GetValueOrDefault())
whereStr += " and job.NextScheduleTime is null";
else
whereStr += " and job.NextScheduleTime is not null";
}
if (criteria.NextScheduleTimeBe != null)
whereStr += " and job.NextScheduleTime >= @NextScheduleTimeBe";
if (criteria.NextScheduleTimeLe != null)
whereStr += " and job.NextScheduleTime <= @NextScheduleTimeLe";
if (criteria.Status != null)
whereStr += " and job.Status = @Status";
if (whereStr.StartsWith(" and "))
whereStr = whereStr.Remove(0, 5);
return whereStr;
}
public virtual IEnumerator<Job> GetEnumerator()
{
foreach (var item in GetAll())
yield return (Job)item;
}
IEnumerator IEnumerable.GetEnumerator()
{
// call the generic version
return this.GetEnumerator();
}
protected byte[] SerializeTask(IJobTask task)
{
byte[] taskData;
using (MemoryStream stream = new MemoryStream())
{
Formatter.Serialize(stream, task);
taskData = stream.ToArray();
}
return taskData;
}
protected string SerializeTaskAsString(IJobTask task)
{
byte[] taskData = SerializeTask(task);
//return Encoding.UTF8.GetString(taskData);
return BitConverter.ToString(taskData).Replace("-", string.Empty);
}
protected JobTask Deserialize(byte[] taskData)
{
JobTask task;
using (MemoryStream stream = new MemoryStream(taskData))
{
task = (JobTask)Formatter.Deserialize(stream);
}
return task;
}
protected JobTask Deserialize(string taskDataStr)
{
//byte[] taskData = Encoding.UTF8.GetBytes(taskDataStr);
byte[] taskData = StringToByteArray(taskDataStr);
return Deserialize(taskData);
}
protected static byte[] StringToByteArray(String hex)
{
int NumberChars = hex.Length;
byte[] bytes = new byte[NumberChars / 2];
for (int i = 0; i < NumberChars; i += 2)
bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
return bytes;
}
}
}
|
||||
TheStack | b59c3e9910a5a87171c24c19114bdafe63cd605e | C#code:C# | {"size": 26817, "ext": "cs", "max_stars_repo_path": "KSFramework/Assets/KSFramework/KEngine/KEngine/CoreModules/ResourceModule/KResourceModule.cs", "max_stars_repo_name": "IdolMenendez/KSFramework", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "KSFramework/Assets/KSFramework/KEngine/KEngine/CoreModules/ResourceModule/KResourceModule.cs", "max_issues_repo_name": "IdolMenendez/KSFramework", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "KSFramework/Assets/KSFramework/KEngine/KEngine/CoreModules/ResourceModule/KResourceModule.cs", "max_forks_repo_name": "IdolMenendez/KSFramework", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 37.2458333333, "max_line_length": 189, "alphanum_fraction": 0.5450646978} | #region Copyright (c) 2015 KEngine / Kelly <http://github.com/mr-kelly>, All rights reserved.
// KEngine - Toolset and framework for Unity3D
// ===================================
//
// Filename: KResourceModule.cs
// Date: 2015/12/03
// Author: Kelly
// Email: [email protected]
// Github: https://github.com/mr-kelly/KEngine
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library.
#endregion
using System;
using System.Collections;
using System.IO;
using UnityEngine;
using Object = UnityEngine.Object;
namespace KEngine
{
public enum KResourceQuality
{
Sd = 2,
Hd = 1,
Ld = 4,
}
/// <summary>
/// 资源路径优先级,优先使用
/// </summary>
public enum KResourcePathPriorityType
{
Invalid,
/// <summary>
/// 忽略PersitentDataPath, 优先寻找Resources或StreamingAssets路径 (取决于ResourcePathType)
/// </summary>
InAppPathPriority,
/// <summary>
/// 尝试在Persistent目錄尋找,找不到再去StreamingAssets,
/// 这一般用于进行热更新版本号判断后,设置成该属性
/// </summary>
PersistentDataPathPriority,
}
public class KResourceModule : MonoBehaviour
{
static KResourceModule()
{
InitResourcePath();
}
public delegate void AsyncLoadABAssetDelegate(Object asset, object[] args);
public enum LoadingLogLevel
{
None,
ShowTime,
ShowDetail,
}
public static KResourceQuality Quality = KResourceQuality.Sd;
public static float TextureScale
{
get { return 1f / (float)Quality; }
}
private static KResourceModule _Instance;
public static KResourceModule Instance
{
get
{
if (_Instance == null)
{
GameObject resMgr = GameObject.Find("_ResourceModule_");
if (resMgr == null)
{
resMgr = new GameObject("_ResourceModule_");
GameObject.DontDestroyOnLoad(resMgr);
}
_Instance = resMgr.AddComponent<KResourceModule>();
}
return _Instance;
}
}
public static bool LoadByQueue = false;
public static int LogLevel = (int)LoadingLogLevel.None;
public static string BuildPlatformName
{
get { return GetBuildPlatformName(); }
} // ex: IOS, Android, AndroidLD
public static string FileProtocol
{
get { return GetFileProtocol(); }
} // for WWW...with file:///xxx
/// <summary>
/// Product Folder's Relative Path - Default: ../Product, which means Assets/../Product
/// </summary>
public static string ProductRelPath
{
get { return KEngine.AppEngine.GetConfig(KEngineDefaultConfigs.ProductRelPath); }
}
/// <summary>
/// Product Folder Full Path , Default: C:\xxxxx\xxxx\../Product
/// </summary>
public static string EditorProductFullPath
{
get { return Path.GetFullPath(ProductRelPath); }
}
/// <summary>
/// StreamingAssetsPath/Bundles/Android/ etc.
/// WWW的读取,是需要Protocol前缀的
/// </summary>
public static string ProductPathWithProtocol { get; private set; }
public static string ProductPathWithoutFileProtocol { get; private set; }
/// <summary>
/// Bundles/Android/ etc... no prefix for streamingAssets
/// </summary>
public static string BundlesPathRelative { get; private set; }
public static string ApplicationPath { get; private set; }
public static string DocumentResourcesPathWithoutFileProtocol
{
get
{
return string.Format("{0}/", GetAppDataPath()); // 各平台通用
}
}
public static string DocumentResourcesPath;
/// <summary>
/// 是否優先找下載的資源?還是app本身資源優先. 优先下载的资源,即采用热更新的资源
/// </summary>
public static KResourcePathPriorityType ResourcePathPriorityType =
KResourcePathPriorityType.PersistentDataPathPriority;
public static System.Func<string, string> CustomGetResourcesPath; // 自定义资源路径。。。
/// <summary>
/// 统一在字符串后加上.box, 取决于配置的AssetBundle后缀
/// </summary>
/// <param name="path"></param>
/// <param name="formats"></param>
/// <returns></returns>
public static string GetAssetBundlePath(string path, params object[] formats)
{
return string.Format(path + KEngine.AppEngine.GetConfig("KEngine", "AssetBundleExt"), formats);
}
// 检查资源是否存在
public static bool ContainsResourceUrl(string resourceUrl)
{
string fullPath;
return GetResourceFullPath(resourceUrl, false, out fullPath, false) != GetResourceFullPathType.Invalid;
}
/// <summary>
/// 完整路径,www加载
/// </summary>
/// <param name="url"></param>
/// <param name="inAppPathType"></param>
/// <param name="withFileProtocol">是否带有file://前缀</param>
/// <param name="isLog"></param>
/// <returns></returns>
public static string GetResourceFullPath(string url, bool withFileProtocol = true, bool isLog = true)
{
string fullPath;
if (GetResourceFullPath(url, withFileProtocol, out fullPath, isLog) != GetResourceFullPathType.Invalid)
return fullPath;
return null;
}
/// <summary>
/// 用于GetResourceFullPath函数,返回的类型判断
/// </summary>
public enum GetResourceFullPathType
{
Invalid,
InApp,
InDocument,
}
public static bool IsResourceExist(string url)
{
string fullPath;
var hasDocUrl = TryGetDocumentResourceUrl(url, false, out fullPath);
var hasInAppUrl = TryGetInAppStreamingUrl(url, false, out fullPath);
return hasDocUrl || hasInAppUrl;
}
/// <summary>
/// 根据相对路径,获取到StreamingAssets完整路径,或Resources中的路径
/// </summary>
/// <param name="url"></param>
/// <param name="fullPath"></param>
/// <param name="inAppPathType"></param>
/// <param name="isLog"></param>
/// <returns></returns>
public static GetResourceFullPathType GetResourceFullPath(string url, bool withFileProtocol, out string fullPath,
bool isLog = true)
{
if (string.IsNullOrEmpty(url))
Log.Error("尝试获取一个空的资源路径!");
string docUrl;
//此路径为下载后的资源路径
bool hasDocUrl = TryGetDocumentResourceUrl(url, withFileProtocol, out docUrl);
string inAppUrl;
bool hasInAppUrl = TryGetInAppStreamingUrl(url, withFileProtocol, out inAppUrl);
if (ResourcePathPriorityType == KResourcePathPriorityType.PersistentDataPathPriority) // 優先下載資源模式
{
if (hasDocUrl)
{
if (Application.isEditor)
Log.Warning("[Use PersistentDataPath] {0}", docUrl);
fullPath = docUrl;
return GetResourceFullPathType.InDocument;
}
// 優先下載資源,但又沒有下載資源文件!使用本地資源目錄
}
if (!hasInAppUrl) // 连本地资源都没有,直接失败吧 ?? 沒有本地資源但又遠程資源?竟然!!?
{
if (isLog)
Log.Error("[Not Found] StreamingAssetsPath Url Resource: {0}", url);
fullPath = null;
return GetResourceFullPathType.Invalid;
}
fullPath = inAppUrl; // 直接使用本地資源!
return GetResourceFullPathType.InApp;
}
/// <summary>
/// 獲取app數據目錄,可寫,同Application.PersitentDataPath,但在windows平台時為了避免www類中文目錄無法讀取問題,單獨實現
/// </summary>
/// <returns></returns>
public static string GetAppDataPath()
{
// Windows 时使用特定的目录,避免中文User的存在
// 去掉自定义PersistentDataPath, 2015/11/18, 务必要求Windows Users是英文
//if (Application.platform == RuntimePlatform.WindowsEditor || Application.platform == RuntimePlatform.WindowsPlayer || Application.platform == RuntimePlatform.WindowsWebPlayer)
//{
// string dataPath = Application.dataPath + "/../Library/UnityWinPersistentDataPath";
// if (!Directory.Exists(dataPath))
// Directory.CreateDirectory(dataPath);
// return dataPath;
//}
return Application.persistentDataPath;
}
public static bool IsEditorLoadAsset
{
get
{
return AppEngine.GetConfig("KEngine", "IsEditorLoadAsset").ToInt32() != 0 && Application.isEditor;
}
}
/// <summary>
/// (not android ) only! Android资源不在目录!
/// Editor返回文件系统目录,运行时返回StreamingAssets目录
/// </summary>
/// <param name="url"></param>
/// <param name="withFileProtocol">是否带有file://前缀</param>
/// <param name="newUrl"></param>
/// <returns></returns>
public static bool TryGetInAppStreamingUrl(string url, bool withFileProtocol, out string newUrl)
{
if (withFileProtocol)
newUrl = ProductPathWithProtocol + url;
else
newUrl = ProductPathWithoutFileProtocol + url;
// 注意,StreamingAssetsPath在Android平台時,壓縮在apk里面,不要做文件檢查了
if (!Application.isEditor && Application.platform == RuntimePlatform.Android)
{
if (!KEngineAndroidPlugin.IsAssetExists(url))
return false;
}
else
{
// Debug.LogError(ProductPathWithoutFileProtocol + url + ">>>>>");
// Editor, 非android运行,直接进行文件检查
if (!File.Exists(ProductPathWithoutFileProtocol + url))
{
return false;
}
}
// Windows/Edtiro平台下,进行大小敏感判断
if (Application.isEditor)
{
var result = FileExistsWithDifferentCase(ProductPathWithoutFileProtocol + url);
if (!result)
{
Log.Error("[大小写敏感]发现一个资源 {0},大小写出现问题,在Windows可以读取,手机不行,请改表修改!", url);
}
}
return true;
}
/// <summary>
/// 大小写敏感地进行文件判断, Windows Only
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
private static bool FileExistsWithDifferentCase(string filePath)
{
if (File.Exists(filePath))
{
string directory = Path.GetDirectoryName(filePath);
string fileTitle = Path.GetFileName(filePath);
string[] files = Directory.GetFiles(directory, fileTitle);
var realFilePath = files[0].Replace("\\", "/");
filePath = filePath.Replace("\\", "/");
filePath = filePath.Replace("//", "/");
return String.CompareOrdinal(realFilePath, filePath) == 0;
}
return false;
}
/// <summary>
/// 可被WWW读取的Resource路径
/// </summary>
/// <param name="url"></param>
/// <param name="withFileProtocol">是否带有file://前缀</param>
/// <param name="newUrl"></param>
/// <returns></returns>
public static bool TryGetDocumentResourceUrl(string url, bool withFileProtocol, out string newUrl)
{
if (withFileProtocol)
newUrl = DocumentResourcesPath + url;
else
newUrl = DocumentResourcesPathWithoutFileProtocol + url;
// Debug.LogError(newUrl + ">>>");
// Debug.LogError(DocumentResourcesPathWithoutFileProtocol + url + "|||");
if (File.Exists(DocumentResourcesPathWithoutFileProtocol + url))
{
return true;
}
return false;
}
private void Awake()
{
if (_Instance != null)
Debuger.Assert(_Instance == this);
//InvokeRepeating("CheckGcCollect", 0f, 3f);
if (Debug.isDebugBuild)
{
Log.Info("ResourceManager ApplicationPath: {0}", ApplicationPath);
Log.Info("ResourceManager ProductPathWithProtocol: {0}", ProductPathWithProtocol);
Log.Info("ResourceManager ProductPathWithoutProtocol: {0}", ProductPathWithoutFileProtocol);
Log.Info("ResourceManager DocumentResourcesPath: {0}", DocumentResourcesPath);
Log.Info("================================================================================");
}
}
private void Update()
{
AbstractResourceLoader.CheckGcCollect();
}
private static string _unityEditorEditorUserBuildSettingsActiveBuildTarget;
/// <summary>
/// UnityEditor.EditorUserBuildSettings.activeBuildTarget, Can Run in any platform~
/// </summary>
public static string UnityEditor_EditorUserBuildSettings_activeBuildTarget
{
get
{
if (Application.isPlaying && !string.IsNullOrEmpty(_unityEditorEditorUserBuildSettingsActiveBuildTarget))
{
return _unityEditorEditorUserBuildSettingsActiveBuildTarget;
}
var assemblies = System.AppDomain.CurrentDomain.GetAssemblies();
foreach (var a in assemblies)
{
if (a.GetName().Name == "UnityEditor")
{
Type lockType = a.GetType("UnityEditor.EditorUserBuildSettings");
//var retObj = lockType.GetMethod(staticMethodName,
// System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public)
// .Invoke(null, args);
//return retObj;
var p = lockType.GetProperty("activeBuildTarget");
var em = p.GetGetMethod().Invoke(null, new object[] { }).ToString();
_unityEditorEditorUserBuildSettingsActiveBuildTarget = em;
return em;
}
}
return null;
}
}
/// <summary>
/// Different platform's assetBundles is incompatible.
/// CosmosEngine put different platform's assetBundles in different folder.
/// Here, get Platform name that represent the AssetBundles Folder.
/// </summary>
/// <returns>Platform folder Name</returns>
public static string GetBuildPlatformName()
{
string buildPlatformName = "Windows"; // default
if (Application.isEditor)
{
var buildTarget = UnityEditor_EditorUserBuildSettings_activeBuildTarget;
//UnityEditor.EditorUserBuildSettings.activeBuildTarget;
switch (buildTarget)
{
case "StandaloneOSXIntel":
case "StandaloneOSXIntel64":
case "StandaloneOSXUniversal":
case "StandaloneOSX":
buildPlatformName = "MacOS";
break;
case "StandaloneWindows": // UnityEditor.BuildTarget.StandaloneWindows:
case "StandaloneWindows64": // UnityEditor.BuildTarget.StandaloneWindows64:
buildPlatformName = "Windows";
break;
case "Android": // UnityEditor.BuildTarget.Android:
buildPlatformName = "Android";
break;
case "iPhone": // UnityEditor.BuildTarget.iPhone:
case "iOS":
buildPlatformName = "iOS";
break;
default:
Debuger.Assert(false);
break;
}
}
else
{
switch (Application.platform)
{
case RuntimePlatform.OSXPlayer:
buildPlatformName = "MacOS";
break;
case RuntimePlatform.Android:
buildPlatformName = "Android";
break;
case RuntimePlatform.IPhonePlayer:
buildPlatformName = "iOS";
break;
case RuntimePlatform.WindowsPlayer:
#if !UNITY_5_4_OR_NEWER
case RuntimePlatform.WindowsWebPlayer:
#endif
buildPlatformName = "Windows";
break;
default:
Debuger.Assert(false);
break;
}
}
if (Quality != KResourceQuality.Sd) // SD no need add
buildPlatformName += Quality.ToString().ToUpper();
return buildPlatformName;
}
/// <summary>
/// On Windows, file protocol has a strange rule that has one more slash
/// </summary>
/// <returns>string, file protocol string</returns>
public static string GetFileProtocol()
{
string fileProtocol = "file://";
if (Application.platform == RuntimePlatform.WindowsEditor ||
Application.platform == RuntimePlatform.WindowsPlayer
#if !UNITY_5_4_OR_NEWER
|| Application.platform == RuntimePlatform.WindowsWebPlayer
#endif
)
fileProtocol = "file:///";
return fileProtocol;
}
public static string BundlesDirName
{
get { return KEngine.AppEngine.GetConfig(KEngineDefaultConfigs.StreamingBundlesFolderName); }
}
/// <summary>
/// Unity Editor load AssetBundle directly from the Asset Bundle Path,
/// whth file:// protocol
/// </summary>
public static string EditorAssetBundleFullPath
{
get
{
string editorAssetBundlePath = Path.GetFullPath(KEngine.AppEngine.GetConfig(KEngineDefaultConfigs.AssetBundleBuildRelPath)); // for editoronly
return editorAssetBundlePath;
}
}
/// <summary>
/// Load Async Asset Bundle
/// </summary>
/// <param name="path"></param>
/// <param name="callback">cps style async</param>
/// <returns></returns>
public static AbstractResourceLoader LoadBundleAsync(string path, AssetFileLoader.AssetFileBridgeDelegate callback = null)
{
var request = AssetFileLoader.Load(path, callback);
return request;
}
/// <summary>
/// load asset bundle immediatly
/// </summary>
/// <param name="path"></param>
/// <param name="callback"></param>
/// <returns></returns>
public static AbstractResourceLoader LoadBundle(string path, AssetFileLoader.AssetFileBridgeDelegate callback = null)
{
var request = AssetFileLoader.Load(path, callback, LoaderMode.Sync);
return request;
}
/// <summary>
/// check file exists of streamingAssets. On Android will use plugin to do that.
/// </summary>
/// <param name="path">relative path, when file is "file:///android_asset/test.txt", the pat is "test.txt"</param>
/// <returns></returns>
public static bool IsStreamingAssetsExists(string path)
{
if (Application.platform == RuntimePlatform.Android)
return KEngineAndroidPlugin.IsAssetExists(path);
var fullPath = Path.Combine(Application.streamingAssetsPath, path);
return File.Exists(fullPath);
}
/// <summary>
/// Load file from streamingAssets. On Android will use plugin to do that.
/// </summary>
/// <param name="path">relative path, when file is "file:///android_asset/test.txt", the pat is "test.txt"</param>
/// <returns></returns>
public static byte[] LoadSyncFromStreamingAssets(string path)
{
if (!IsStreamingAssetsExists(path))
throw new Exception("Not exist StreamingAssets path: " + path);
if (Application.platform == RuntimePlatform.Android)
return KEngineAndroidPlugin.GetAssetBytes(path);
var fullPath = Path.Combine(Application.streamingAssetsPath, path);
return ReadAllBytes(fullPath);
}
public static bool IsPersistentDataExist(string path)
{
var fullPath = Path.Combine(Application.persistentDataPath, path);
return File.Exists(fullPath);
}
public static byte[] LoadSyncFromPersistentDataPath(string path)
{
if (!IsPersistentDataExist(path))
throw new Exception("Not exist PersistentData path: " + path);
var fullPath = Path.Combine(Application.persistentDataPath, path);
return ReadAllBytes(fullPath);
}
/// <summary>
/// 无视锁文件,直接读bytes
/// </summary>
/// <param name="resPath"></param>
public static byte[] ReadAllBytes(string resPath)
{
byte[] bytes;
using (FileStream fs = File.Open(resPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
bytes = new byte[fs.Length];
fs.Read(bytes, 0, (int)fs.Length);
}
return bytes;
}
/// <summary>
/// Initialize the path of AssetBundles store place ( Maybe in PersitentDataPath or StreamingAssetsPath )
/// </summary>
/// <returns></returns>
static void InitResourcePath()
{
string editorProductPath = EditorProductFullPath;
BundlesPathRelative = string.Format("{0}/{1}/", BundlesDirName, GetBuildPlatformName());
DocumentResourcesPath = FileProtocol + DocumentResourcesPathWithoutFileProtocol;
switch (Application.platform)
{
case RuntimePlatform.WindowsEditor:
case RuntimePlatform.OSXEditor:
{
ApplicationPath = string.Format("{0}{1}", GetFileProtocol(), editorProductPath);
ProductPathWithProtocol = GetFileProtocol() + EditorProductFullPath + "/";
ProductPathWithoutFileProtocol = EditorProductFullPath + "/";
// Resources folder
}
break;
case RuntimePlatform.WindowsPlayer:
case RuntimePlatform.OSXPlayer:
{
string path = Application.streamingAssetsPath.Replace('\\', '/');//Application.dataPath.Replace('\\', '/');
// path = path.Substring(0, path.LastIndexOf('/') + 1);
ApplicationPath = string.Format("{0}{1}", GetFileProtocol(), Application.dataPath);
ProductPathWithProtocol = string.Format("{0}{1}/", GetFileProtocol(), path);
ProductPathWithoutFileProtocol = string.Format("{0}/", path);
// Resources folder
}
break;
case RuntimePlatform.Android:
{
ApplicationPath = string.Concat("jar:", GetFileProtocol(), Application.dataPath, "!/assets");
ProductPathWithProtocol = string.Concat(ApplicationPath, "/");
ProductPathWithoutFileProtocol = string.Concat(Application.dataPath,
"!/assets/");
// 注意,StramingAsset在Android平台中,是在壓縮的apk里,不做文件檢查
// Resources folder
}
break;
case RuntimePlatform.IPhonePlayer:
{
ApplicationPath =
System.Uri.EscapeUriString(GetFileProtocol() + Application.streamingAssetsPath); // MacOSX下,带空格的文件夹,空格字符需要转义成%20
ProductPathWithProtocol = string.Format("{0}/", ApplicationPath);
// only iPhone need to Escape the fucking Url!!! other platform works without it!!! Keng Die!
ProductPathWithoutFileProtocol = Application.streamingAssetsPath + "/";
// Resources folder
}
break;
default:
{
Debuger.Assert(false);
}
break;
}
}
public static void LogRequest(string resType, string resPath)
{
if (LogLevel < (int)LoadingLogLevel.ShowDetail)
return;
Log.Info("[Request] {0}, {1}", resType, resPath);
}
public static void LogLoadTime(string resType, string resPath, System.DateTime begin)
{
if (LogLevel < (int)LoadingLogLevel.ShowTime)
return;
Log.Info("[Load] {0}, {1}, {2}s", resType, resPath, (System.DateTime.Now - begin).TotalSeconds);
}
/// <summary>
/// Collect all KEngine's resource unused loaders
/// </summary>
public static void Collect()
{
while (AbstractResourceLoader.UnUsesLoaders.Count > 0)
AbstractResourceLoader.DoGarbageCollect();
Resources.UnloadUnusedAssets();
System.GC.Collect();
}
}
}
|
||||
TheStack | b59e2f1760647d622b9c9f1e7d87ab48be1f9d97 | C#code:C# | {"size": 557, "ext": "cs", "max_stars_repo_path": "WebApi/UseCases/Products/V1/DeleteProduct/DeleteProductResponse.cs", "max_stars_repo_name": "satishchatap/zellar", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "WebApi/UseCases/Products/V1/DeleteProduct/DeleteProductResponse.cs", "max_issues_repo_name": "satishchatap/zellar", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "WebApi/UseCases/Products/V1/DeleteProduct/DeleteProductResponse.cs", "max_forks_repo_name": "satishchatap/zellar", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 23.2083333333, "max_line_length": 78, "alphanum_fraction": 0.5852782765} | using Domain;
using System;
using System.ComponentModel.DataAnnotations;
namespace WebApi.UseCases.Products.V1.DeleteProduct
{
/// <summary>
/// Delete Product Response
/// </summary>
public class DeleteProductResponse
{
/// <summary>
/// Delete Product Response constructor.
/// </summary>
public DeleteProductResponse(Product product) => this.Id = product.Id;
/// <summary>
/// Gets product ID.
/// </summary>
[Required]
public int Id { get; }
}
}
|
||||
TheStack | b59e97ebd8254e4018ce0b4c1fdcb12ce7a55a80 | C#code:C# | {"size": 9618, "ext": "cs", "max_stars_repo_path": "test/FluentILUnitTests/IfExpressionUnitTests.cs", "max_stars_repo_name": "arlm/FluentIL", "max_stars_repo_stars_event_min_datetime": "2019-07-17T11:58:06.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-17T11:58:06.000Z", "max_issues_repo_path": "test/FluentILUnitTests/IfExpressionUnitTests.cs", "max_issues_repo_name": "arlm/FluentIL", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/FluentILUnitTests/IfExpressionUnitTests.cs", "max_forks_repo_name": "arlm/FluentIL", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 31.6381578947, "max_line_length": 113, "alphanum_fraction": 0.4924100645} | namespace FluentILUnitTests
{
using System;
using System.Linq.Expressions;
using FluentIL;
using FluentIL.Expressions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
[TestClass]
public class IfExpressionUnitTests
{
[TestMethod]
public void EmitIfWithSimpleEqualsConstantExpression()
{
var method = this.CreateType<int, bool>(
e => e.LdArg1<int>() == 10);
Assert.IsTrue(method(10));
Assert.IsFalse(method(1));
Assert.IsFalse(method(-1));
}
[TestMethod]
public void EmitIfWithSimpleNotEqualsConstantExpression()
{
var method = this.CreateType<int, bool>(
e => e.LdArg1<int>() != 10);
Assert.IsFalse(method(10));
Assert.IsTrue(method(1));
Assert.IsTrue(method(-2));
}
[TestMethod]
public void EmitIfWithSimpleGreaterThanConstantExpression()
{
var method = this.CreateType<int, bool>(
e => e.LdArg1<int>() > 10);
Assert.IsTrue(method(20));
Assert.IsFalse(method(10));
Assert.IsFalse(method(-10));
}
[TestMethod]
public void EmitIfWithSimpleGreaterThanOrEqualConstantExpression()
{
var method = this.CreateType<int, bool>(
e => e.LdArg1<int>() >= 10);
Assert.IsTrue(method(20));
Assert.IsTrue(method(10));
Assert.IsFalse(method(1));
}
[TestMethod]
public void EmitIfWithSimpleLessThanConstantExpression()
{
var method = this.CreateType<int, bool>(
e => e.LdArg1<int>() < 10);
Assert.IsTrue(method(1));
Assert.IsFalse(method(10));
Assert.IsFalse(method(20));
}
[TestMethod]
public void EmitIfWithSimpleLessThanOrEqualConstantExpression()
{
var method = this.CreateType<int, bool>(
e => e.LdArg1<int>() <= 10);
Assert.IsTrue(method(1));
Assert.IsTrue(method(10));
Assert.IsFalse(method(20));
}
[TestMethod]
public void EmitIfWithSimpleEqualsExpression()
{
var method = this.CreateType<int, int, bool>(
e => e.LdArg1<int>() == e.LdArg2<int>());
Assert.IsTrue(method(10, 10));
Assert.IsFalse(method(10, 1));
Assert.IsFalse(method(1, 2));
}
[TestMethod]
public void EmitIfWithSimpleNotEqualsExpression()
{
var method = this.CreateType<int, int, bool>(
e => e.LdArg1<int>() != e.LdArg2<int>());
Assert.IsFalse(method(10, 10));
Assert.IsTrue(method(10, 1));
Assert.IsTrue(method(1, 2));
}
[TestMethod]
public void EmitIfWithSimpleGreaterThanExpression()
{
var method = this.CreateType<int, int, bool>(
e => e.LdArg1<int>() > e.LdArg2<int>());
Assert.IsTrue(method(20, 10));
Assert.IsFalse(method(10, 10));
Assert.IsFalse(method(1, 2));
}
[TestMethod]
public void EmitIfWithSimpleGreaterThanOrEqualExpression()
{
var method = this.CreateType<int, int, bool>(
e => e.LdArg1<int>() >= e.LdArg2<int>());
Assert.IsTrue(method(20, 10));
Assert.IsTrue(method(10, 10));
Assert.IsFalse(method(1, 2));
}
[TestMethod]
public void EmitIfWithSimpleLessThanExpression()
{
var method = this.CreateType<int, int, bool>(
e => e.LdArg1<int>() < e.LdArg2<int>());
Assert.IsTrue(method(10, 20));
Assert.IsFalse(method(10, 10));
Assert.IsFalse(method(2, 1));
}
[TestMethod]
public void EmitIfWithSimpleLessThanOrEqualExpression()
{
var method = this.CreateType<int, int, bool>(
e => e.LdArg1<int>() <= e.LdArg2<int>());
Assert.IsTrue(method(10, 20));
Assert.IsTrue(method(10, 10));
Assert.IsFalse(method(2, 1));
}
[TestMethod]
public void EmitIfWithEqualsAndNotEqualsExpression()
{
var method = this.CreateType<int, int, bool>(
e => e.LdArg1<int>() == 10 && e.LdArg2<int>() != 10);
Assert.IsTrue(method(10, 1));
Assert.IsFalse(method(10, 10));
Assert.IsTrue(method(10, 20));
Assert.IsFalse(method(1, 20));
}
[TestMethod]
public void EmitIfWithEqualsAndGreaterThanExpression()
{
var method = this.CreateType<int, int, bool>(
e => e.LdArg1<int>() == 10 && e.LdArg2<int>() > 10);
Assert.IsTrue(method(10, 20));
Assert.IsFalse(method(10, 10));
Assert.IsFalse(method(1, 20));
}
[TestMethod]
public void EmitIfWithEqualsAndGreaterThanOrEqualExpression()
{
var method = this.CreateType<int, int, bool>(
e => e.LdArg1<int>() == 10 && e.LdArg2<int>() >= 10);
Assert.IsTrue(method(10, 20));
Assert.IsTrue(method(10, 10));
Assert.IsFalse(method(1, 20));
Assert.IsFalse(method(1, 10));
}
[TestMethod]
public void EmitIfWithEqualsAndLessThanExpression()
{
var method = this.CreateType<int, int, bool>(
e => e.LdArg1<int>() == 10 && e.LdArg2<int>() < 10);
Assert.IsTrue(method(10, 1));
Assert.IsFalse(method(10, 10));
Assert.IsFalse(method(1, 20));
Assert.IsFalse(method(1, 1));
}
[TestMethod]
public void EmitIfWithEqualsAndLessThanOrEqualExpression()
{
var method = this.CreateType<int, int, bool>(
e => e.LdArg1<int>() == 10 && e.LdArg2<int>() <= 10);
Assert.IsTrue(method(10, 1));
Assert.IsTrue(method(10, 10));
Assert.IsFalse(method(1, 20));
Assert.IsFalse(method(1, 10));
}
[TestMethod]
public void EmitIfWithEqualsOrNotEqualsExpression()
{
var method = this.CreateType<int, int, bool>(
e => e.LdArg1<int>() == 10 || e.LdArg2<int>() != 10);
Assert.IsTrue(method(10, 1));
Assert.IsTrue(method(10, 10));
Assert.IsTrue(method(1, 20));
Assert.IsFalse(method(1, 10));
}
[TestMethod]
public void EmitIfWithModulusEqualsExpression()
{
var method = this.CreateType<int, bool>(
e => (e.LdArg1<int>() % 2) == 0);
Assert.IsTrue(method(10));
Assert.IsTrue(method(20));
Assert.IsFalse(method(1));
Assert.IsFalse(method(3));
}
[TestMethod]
public void EmitIfWithModulusNotEqualsExpression()
{
var method = this.CreateType<int, bool>(
e => (e.LdArg1<int>() % 2) != 0);
Assert.IsFalse(method(10));
Assert.IsFalse(method(20));
Assert.IsTrue(method(1));
Assert.IsTrue(method(3));
}
private Func<T, TResult> CreateType<T, TResult>(Expression<Func<IExpression, bool>> expression)
{
var methodName = $"Method_{Guid.NewGuid()}";
var testTypeBuilder = TypeFactory
.Default
.NewType($"TestType_{Guid.NewGuid()}")
.Public();
testTypeBuilder
.NewMethod(methodName)
.Param<int>("arg1")
.Returns<bool>()
.Public()
.Body(il => il
.DeclareLocal<bool>(out ILocal result)
.LdcI4_0()
.StLoc0()
.Nop()
.If(expression,
i => i
.LdcI4_1()
.StLoc0())
.LdLoc0()
.Ret()
);
var type = testTypeBuilder.CreateType();
var instance = Activator.CreateInstance(type);
return instance.GetMethodFunc<T, TResult>(methodName);
}
private Func<T1, T2, TResult> CreateType<T1, T2, TResult>(Expression<Func<IExpression, bool>> expression)
{
var methodName = $"Method_{Guid.NewGuid()}";
var testTypeBuilder = TypeFactory
.Default
.NewType($"TestType_{Guid.NewGuid()}")
.Public();
testTypeBuilder
.NewMethod(methodName)
.Param<int>("arg1")
.Param<int>("arg2")
.Returns<bool>()
.Public()
.Body(il => il
.DeclareLocal<bool>(out ILocal result)
.LdcI4_0()
.StLoc0()
.Nop()
.If(expression,
i => i
.LdcI4_1()
.StLoc0())
.LdLoc0()
.Ret()
);
var type = testTypeBuilder.CreateType();
var instance = Activator.CreateInstance(type);
return instance.GetMethodFunc<T1, T2, TResult>(methodName);
}
}
} |
||||
TheStack | b59f937f13cc499f437b40087d2ee9bb1fb114c2 | C#code:C# | {"size": 1052, "ext": "cs", "max_stars_repo_path": "tests/FakerFactory.cs", "max_stars_repo_name": "saraedum/MiddleMail", "max_stars_repo_stars_event_min_datetime": "2020-06-17T20:46:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-05T18:48:58.000Z", "max_issues_repo_path": "tests/FakerFactory.cs", "max_issues_repo_name": "saraedum/MiddleMail", "max_issues_repo_issues_event_min_datetime": "2020-06-18T12:52:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-20T05:12:21.000Z", "max_forks_repo_path": "tests/FakerFactory.cs", "max_forks_repo_name": "saraedum/MiddleMail", "max_forks_repo_forks_event_min_datetime": "2020-06-17T20:46:25.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-18T19:19:46.000Z"} | {"max_stars_count": 3.0, "max_issues_count": 16.0, "max_forks_count": 2.0, "avg_line_length": 32.875, "max_line_length": 92, "alphanum_fraction": 0.6929657795} | using System;
using System.Linq;
using Bogus;
using MiddleMail;
using MiddleMail.Model;
using MimeKit;
namespace MiddleMail.Tests {
public static class FakerFactory {
public static Faker<EmailMessage> EmailMessageFaker = new Faker<EmailMessage>()
.CustomInstantiator(f => new EmailMessage(
id: Guid.NewGuid(),
from: (f.Name.FullName(), f.Internet.Email()),
to: (f.Name.FullName(), f.Internet.Email()),
replyTo: (f.Name.FullName(), f.Internet.Email()),
subject: f.Lorem.Sentence(),
plainText: f.Lorem.Sentences(),
htmlText: f.Lorem.Sentences(),
headers: null,
tags: f.Lorem.Words().ToList()));
public static Faker<MimeMessage> MimeMessageFaker = new Faker<MimeMessage>()
.CustomInstantiator(f => new MimeMessage(
from: new MailboxAddress[] { new MailboxAddress(f.Name.FullName(), f.Internet.Email())},
to: new MailboxAddress[] { new MailboxAddress(f.Name.FullName(), f.Internet.Email())},
subject: f.Lorem.Sentence(),
body: new TextPart("plain") { Text = f.Lorem.Sentences(10)}));
}
}
|
||||
TheStack | b59f9a452f40dc106231e20abb521d7dd87dcd3e | C#code:C# | {"size": 217, "ext": "cs", "max_stars_repo_path": "src/XEngine.AssetLoader/AssetBundleInfo.cs", "max_stars_repo_name": "moto2002/tianqi_src", "max_stars_repo_stars_event_min_datetime": "2017-06-04T12:30:50.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-12T09:33:10.000Z", "max_issues_repo_path": "src/XEngine.AssetLoader/AssetBundleInfo.cs", "max_issues_repo_name": "corefan/tianqi_src", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/XEngine.AssetLoader/AssetBundleInfo.cs", "max_forks_repo_name": "corefan/tianqi_src", "max_forks_repo_forks_event_min_datetime": "2017-07-18T13:38:00.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-29T03:42:11.000Z"} | {"max_stars_count": 5.0, "max_issues_count": null, "max_forks_count": 7.0, "avg_line_length": 11.4210526316, "max_line_length": 29, "alphanum_fraction": 0.7281105991} | using System;
namespace XEngine.AssetLoader
{
[Serializable]
public class AssetBundleInfo
{
public string filename;
public string hash;
public int package;
public int offset;
public int length;
}
}
|
||||
TheStack | b5a189d937c8af7b745b75b92691aed6a8a57141 | C#code:C# | {"size": 1295, "ext": "cs", "max_stars_repo_path": "Sources/Engine/NeoAxis.Core/Libraries/BulletSharp/Collision/UnionFind.cs", "max_stars_repo_name": "intensifier/NeoAxisEngine", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Sources/Engine/NeoAxis.Core/Libraries/BulletSharp/Collision/UnionFind.cs", "max_issues_repo_name": "intensifier/NeoAxisEngine", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Sources/Engine/NeoAxis.Core/Libraries/BulletSharp/Collision/UnionFind.cs", "max_forks_repo_name": "intensifier/NeoAxisEngine", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 15.2352941176, "max_line_length": 63, "alphanum_fraction": 0.667953668} | using System;
using static BulletSharp.UnsafeNativeMethods;
namespace BulletSharp
{
public class Element
{
internal IntPtr Native;
internal Element(IntPtr native)
{
Native = native;
}
public int Id
{
get => btElement_getId(Native);
set => btElement_setId(Native, value);
}
public int Sz
{
get => btElement_getSz(Native);
set => btElement_setSz(Native, value);
}
}
public class UnionFind
{
internal IntPtr Native;
internal UnionFind(IntPtr native)
{
Native = native;
}
public void Allocate(int n)
{
btUnionFind_allocate(Native, n);
}
public int Find(int p, int q)
{
return btUnionFind_find(Native, p, q);
}
public int Find(int x)
{
return btUnionFind_find2(Native, x);
}
public void Free()
{
btUnionFind_Free(Native);
}
public Element GetElement(int index)
{
return new Element(btUnionFind_getElement(Native, index));
}
public bool IsRoot(int x)
{
return btUnionFind_isRoot(Native, x);
}
public void Reset(int n)
{
btUnionFind_reset(Native, n);
}
public void SortIslands()
{
btUnionFind_sortIslands(Native);
}
public void Unite(int p, int q)
{
btUnionFind_unite(Native, p, q);
}
public int NumElements => btUnionFind_getNumElements(Native);
}
}
|
||||
TheStack | b5a2f54b070fad1a0a959e1ec3533c0b124f6d5f | C#code:C# | {"size": 16390, "ext": "cs", "max_stars_repo_path": "sdk/dotnet/Hsm/Module.cs", "max_stars_repo_name": "suresh198526/pulumi-azure", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sdk/dotnet/Hsm/Module.cs", "max_issues_repo_name": "suresh198526/pulumi-azure", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sdk/dotnet/Hsm/Module.cs", "max_forks_repo_name": "suresh198526/pulumi-azure", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 43.8235294118, "max_line_length": 640, "alphanum_fraction": 0.5620500305} | // *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** 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.Azure.Hsm
{
/// <summary>
/// Manages a Dedicated Hardware Security Module.
///
/// > **Note**: Before using this resource, it's required to submit the request of registering the providers and features with Azure CLI `az provider register --namespace Microsoft.HardwareSecurityModules && az feature register --namespace Microsoft.HardwareSecurityModules --name AzureDedicatedHSM && az provider register --namespace Microsoft.Network && az feature register --namespace Microsoft.Network --name AllowBaremetalServers` and ask service team ([email protected]) to approve. See more details from https://docs.microsoft.com/en-us/azure/dedicated-hsm/tutorial-deploy-hsm-cli#prerequisites.
///
/// > **Note**: If the quota is not enough in some region, please submit the quota request to service team.
///
/// ## Example Usage
///
/// ```csharp
/// using Pulumi;
/// using Azure = Pulumi.Azure;
///
/// class MyStack : Stack
/// {
/// public MyStack()
/// {
/// var exampleResourceGroup = new Azure.Core.ResourceGroup("exampleResourceGroup", new Azure.Core.ResourceGroupArgs
/// {
/// Location = "West Europe",
/// });
/// var exampleVirtualNetwork = new Azure.Network.VirtualNetwork("exampleVirtualNetwork", new Azure.Network.VirtualNetworkArgs
/// {
/// AddressSpaces =
/// {
/// "10.2.0.0/16",
/// },
/// Location = exampleResourceGroup.Location,
/// ResourceGroupName = exampleResourceGroup.Name,
/// });
/// var exampleSubnet = new Azure.Network.Subnet("exampleSubnet", new Azure.Network.SubnetArgs
/// {
/// ResourceGroupName = exampleResourceGroup.Name,
/// VirtualNetworkName = exampleVirtualNetwork.Name,
/// AddressPrefixes =
/// {
/// "10.2.0.0/24",
/// },
/// });
/// var example2 = new Azure.Network.Subnet("example2", new Azure.Network.SubnetArgs
/// {
/// ResourceGroupName = exampleResourceGroup.Name,
/// VirtualNetworkName = exampleVirtualNetwork.Name,
/// AddressPrefixes =
/// {
/// "10.2.1.0/24",
/// },
/// Delegations =
/// {
/// new Azure.Network.Inputs.SubnetDelegationArgs
/// {
/// Name = "first",
/// ServiceDelegation = new Azure.Network.Inputs.SubnetDelegationServiceDelegationArgs
/// {
/// Name = "Microsoft.HardwareSecurityModules/dedicatedHSMs",
/// Actions =
/// {
/// "Microsoft.Network/networkinterfaces/*",
/// "Microsoft.Network/virtualNetworks/subnets/join/action",
/// },
/// },
/// },
/// },
/// });
/// var example3 = new Azure.Network.Subnet("example3", new Azure.Network.SubnetArgs
/// {
/// ResourceGroupName = exampleResourceGroup.Name,
/// VirtualNetworkName = exampleVirtualNetwork.Name,
/// AddressPrefixes =
/// {
/// "10.2.255.0/26",
/// },
/// });
/// var examplePublicIp = new Azure.Network.PublicIp("examplePublicIp", new Azure.Network.PublicIpArgs
/// {
/// Location = exampleResourceGroup.Location,
/// ResourceGroupName = exampleResourceGroup.Name,
/// AllocationMethod = "Dynamic",
/// });
/// var exampleVirtualNetworkGateway = new Azure.Network.VirtualNetworkGateway("exampleVirtualNetworkGateway", new Azure.Network.VirtualNetworkGatewayArgs
/// {
/// Location = exampleResourceGroup.Location,
/// ResourceGroupName = exampleResourceGroup.Name,
/// Type = "ExpressRoute",
/// VpnType = "PolicyBased",
/// Sku = "Standard",
/// IpConfigurations =
/// {
/// new Azure.Network.Inputs.VirtualNetworkGatewayIpConfigurationArgs
/// {
/// PublicIpAddressId = examplePublicIp.Id,
/// PrivateIpAddressAllocation = "Dynamic",
/// SubnetId = example3.Id,
/// },
/// },
/// });
/// var exampleModule = new Azure.Hsm.Module("exampleModule", new Azure.Hsm.ModuleArgs
/// {
/// Location = exampleResourceGroup.Location,
/// ResourceGroupName = exampleResourceGroup.Name,
/// SkuName = "SafeNet Luna Network HSM A790",
/// NetworkProfile = new Azure.Hsm.Inputs.ModuleNetworkProfileArgs
/// {
/// NetworkInterfacePrivateIpAddresses =
/// {
/// "10.2.1.8",
/// },
/// SubnetId = example2.Id,
/// },
/// StampId = "stamp2",
/// Tags =
/// {
/// { "env", "Test" },
/// },
/// }, new CustomResourceOptions
/// {
/// DependsOn =
/// {
/// exampleVirtualNetworkGateway,
/// },
/// });
/// }
///
/// }
/// ```
///
/// ## Import
///
/// Dedicated Hardware Security Module can be imported using the `resource id`, e.g.
///
/// ```sh
/// $ pulumi import azure:hsm/module:Module example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/group1/providers/Microsoft.HardwareSecurityModules/dedicatedHSMs/hsm1
/// ```
/// </summary>
public partial class Module : Pulumi.CustomResource
{
/// <summary>
/// The Azure Region where the Dedicated Hardware Security Module should exist. Changing this forces a new Dedicated Hardware Security Module to be created.
/// </summary>
[Output("location")]
public Output<string> Location { get; private set; } = null!;
/// <summary>
/// The name which should be used for this Dedicated Hardware Security Module. Changing this forces a new Dedicated Hardware Security Module to be created.
/// </summary>
[Output("name")]
public Output<string> Name { get; private set; } = null!;
/// <summary>
/// A `network_profile` block as defined below.
/// </summary>
[Output("networkProfile")]
public Output<Outputs.ModuleNetworkProfile> NetworkProfile { get; private set; } = null!;
/// <summary>
/// The name of the Resource Group where the Dedicated Hardware Security Module should exist. Changing this forces a new Dedicated Hardware Security Module to be created.
/// </summary>
[Output("resourceGroupName")]
public Output<string> ResourceGroupName { get; private set; } = null!;
/// <summary>
/// The sku name of the dedicated hardware security module. Changing this forces a new Dedicated Hardware Security Module to be created.
/// </summary>
[Output("skuName")]
public Output<string> SkuName { get; private set; } = null!;
/// <summary>
/// The ID of the stamp. Possible values are `stamp1` or `stamp2`. Changing this forces a new Dedicated Hardware Security Module to be created.
/// </summary>
[Output("stampId")]
public Output<string?> StampId { get; private set; } = null!;
/// <summary>
/// A mapping of tags which should be assigned to the Dedicated Hardware Security Module.
/// </summary>
[Output("tags")]
public Output<ImmutableDictionary<string, string>?> Tags { get; private set; } = null!;
/// <summary>
/// The Dedicated Hardware Security Module zones. Changing this forces a new Dedicated Hardware Security Module to be created.
/// </summary>
[Output("zones")]
public Output<ImmutableArray<string>> Zones { get; private set; } = null!;
/// <summary>
/// Create a Module resource with the given unique name, arguments, and options.
/// </summary>
///
/// <param name="name">The unique name of the resource</param>
/// <param name="args">The arguments used to populate this resource's properties</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public Module(string name, ModuleArgs args, CustomResourceOptions? options = null)
: base("azure:hsm/module:Module", name, args ?? new ModuleArgs(), MakeResourceOptions(options, ""))
{
}
private Module(string name, Input<string> id, ModuleState? state = null, CustomResourceOptions? options = null)
: base("azure:hsm/module:Module", name, state, MakeResourceOptions(options, id))
{
}
private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id)
{
var defaultOptions = new CustomResourceOptions
{
Version = Utilities.Version,
};
var merged = CustomResourceOptions.Merge(defaultOptions, options);
// Override the ID if one was specified for consistency with other language SDKs.
merged.Id = id ?? merged.Id;
return merged;
}
/// <summary>
/// Get an existing Module resource's state with the given name, ID, and optional extra
/// properties used to qualify the lookup.
/// </summary>
///
/// <param name="name">The unique name of the resulting resource.</param>
/// <param name="id">The unique provider ID of the resource to lookup.</param>
/// <param name="state">Any extra arguments used during the lookup.</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public static Module Get(string name, Input<string> id, ModuleState? state = null, CustomResourceOptions? options = null)
{
return new Module(name, id, state, options);
}
}
public sealed class ModuleArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The Azure Region where the Dedicated Hardware Security Module should exist. Changing this forces a new Dedicated Hardware Security Module to be created.
/// </summary>
[Input("location")]
public Input<string>? Location { get; set; }
/// <summary>
/// The name which should be used for this Dedicated Hardware Security Module. Changing this forces a new Dedicated Hardware Security Module to be created.
/// </summary>
[Input("name")]
public Input<string>? Name { get; set; }
/// <summary>
/// A `network_profile` block as defined below.
/// </summary>
[Input("networkProfile", required: true)]
public Input<Inputs.ModuleNetworkProfileArgs> NetworkProfile { get; set; } = null!;
/// <summary>
/// The name of the Resource Group where the Dedicated Hardware Security Module should exist. Changing this forces a new Dedicated Hardware Security Module to be created.
/// </summary>
[Input("resourceGroupName", required: true)]
public Input<string> ResourceGroupName { get; set; } = null!;
/// <summary>
/// The sku name of the dedicated hardware security module. Changing this forces a new Dedicated Hardware Security Module to be created.
/// </summary>
[Input("skuName", required: true)]
public Input<string> SkuName { get; set; } = null!;
/// <summary>
/// The ID of the stamp. Possible values are `stamp1` or `stamp2`. Changing this forces a new Dedicated Hardware Security Module to be created.
/// </summary>
[Input("stampId")]
public Input<string>? StampId { get; set; }
[Input("tags")]
private InputMap<string>? _tags;
/// <summary>
/// A mapping of tags which should be assigned to the Dedicated Hardware Security Module.
/// </summary>
public InputMap<string> Tags
{
get => _tags ?? (_tags = new InputMap<string>());
set => _tags = value;
}
[Input("zones")]
private InputList<string>? _zones;
/// <summary>
/// The Dedicated Hardware Security Module zones. Changing this forces a new Dedicated Hardware Security Module to be created.
/// </summary>
public InputList<string> Zones
{
get => _zones ?? (_zones = new InputList<string>());
set => _zones = value;
}
public ModuleArgs()
{
}
}
public sealed class ModuleState : Pulumi.ResourceArgs
{
/// <summary>
/// The Azure Region where the Dedicated Hardware Security Module should exist. Changing this forces a new Dedicated Hardware Security Module to be created.
/// </summary>
[Input("location")]
public Input<string>? Location { get; set; }
/// <summary>
/// The name which should be used for this Dedicated Hardware Security Module. Changing this forces a new Dedicated Hardware Security Module to be created.
/// </summary>
[Input("name")]
public Input<string>? Name { get; set; }
/// <summary>
/// A `network_profile` block as defined below.
/// </summary>
[Input("networkProfile")]
public Input<Inputs.ModuleNetworkProfileGetArgs>? NetworkProfile { get; set; }
/// <summary>
/// The name of the Resource Group where the Dedicated Hardware Security Module should exist. Changing this forces a new Dedicated Hardware Security Module to be created.
/// </summary>
[Input("resourceGroupName")]
public Input<string>? ResourceGroupName { get; set; }
/// <summary>
/// The sku name of the dedicated hardware security module. Changing this forces a new Dedicated Hardware Security Module to be created.
/// </summary>
[Input("skuName")]
public Input<string>? SkuName { get; set; }
/// <summary>
/// The ID of the stamp. Possible values are `stamp1` or `stamp2`. Changing this forces a new Dedicated Hardware Security Module to be created.
/// </summary>
[Input("stampId")]
public Input<string>? StampId { get; set; }
[Input("tags")]
private InputMap<string>? _tags;
/// <summary>
/// A mapping of tags which should be assigned to the Dedicated Hardware Security Module.
/// </summary>
public InputMap<string> Tags
{
get => _tags ?? (_tags = new InputMap<string>());
set => _tags = value;
}
[Input("zones")]
private InputList<string>? _zones;
/// <summary>
/// The Dedicated Hardware Security Module zones. Changing this forces a new Dedicated Hardware Security Module to be created.
/// </summary>
public InputList<string> Zones
{
get => _zones ?? (_zones = new InputList<string>());
set => _zones = value;
}
public ModuleState()
{
}
}
}
|
||||
TheStack | b5a450877098733bd180f5b2f2e74ae7809df0f9 | C#code:C# | {"size": 2889, "ext": "cs", "max_stars_repo_path": "Aersysm/EveresList.aspx.cs", "max_stars_repo_name": "TanHaoran/NurseService1.0", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Aersysm/EveresList.aspx.cs", "max_issues_repo_name": "TanHaoran/NurseService1.0", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Aersysm/EveresList.aspx.cs", "max_forks_repo_name": "TanHaoran/NurseService1.0", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 30.4105263158, "max_line_length": 151, "alphanum_fraction": 0.502596054} | using Aersysm.Domain;
using Aersysm.Persistence;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Services.admin
{
public partial class EveresList : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
SetPageData();
}
}
public void SetPageData()
{
IList<aers_tbl_hospital> listhosp = new aers_tbl_events_ycSqlMapDao().hospitalFindAll();
IList<aers_tbl_hospdep> listdep = new aers_tbl_hospdepSqlMapDao().hospdepFindAll();
IList<aers_tbl_eventsresume> list = new aers_tbl_eventsresumeSqlMapDao().GetEventsresumeList().OrderByDescending(o => o.EveresId).ToList();
IList<aers_sys_statecode> listcode = new aers_sys_statecodeSqlMapDao().FindAll();
foreach (aers_tbl_eventsresume item in list)
{
aers_sys_statecode code = listcode.FirstOrDefault(o => o.ECodeValue == item.EveresName);
if (code != null)
{
item.EveresName = code.ECodeTag;
}
aers_tbl_hospital hosp = listhosp.FirstOrDefault(o => o.HospId == item.HospId);
if (hosp != null)
{
item.HospId = hosp.HospName;
}
aers_tbl_hospdep dep = listdep.FirstOrDefault(o => o.HospdepId == item.HospDepId);
if (dep != null)
{
item.HospDepId = dep.HospdepName;
}
switch (item.ExamineState.ToString())
{
case "0":
item.ExamineState = "审核中";
break;
case "1":
item.ExamineState = "已审核";
break;
case "2":
item.ExamineState = "未通过";
break;
case "3":
item.ExamineState = "未上报";
break;
default:
item.ExamineState = "--";
break;
}
}
GridView1.DataSource = list;
GridView1.DataBind();
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes.Add("onmouseover", "currentColor= this.style.backgroundColor;this.style.backgroundColor='#33CCFF'");
e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=currentColor");
}
}
}
} |
||||
TheStack | b5a4d2fc9ef976b9604d760d8bf792805b3825fe | C#code:C# | {"size": 94, "ext": "cshtml", "max_stars_repo_path": "WebApp2/Pages/Page2.cshtml", "max_stars_repo_name": "lifewithcoffee/WebApplication3", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "WebApp2/Pages/Page2.cshtml", "max_issues_repo_name": "lifewithcoffee/WebApplication3", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "WebApp2/Pages/Page2.cshtml", "max_forks_repo_name": "lifewithcoffee/WebApplication3", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 10.4444444444, "max_line_length": 32, "alphanum_fraction": 0.6170212766} | @page
@model WebApp2.Pages.Page2Model
@{
ViewData["Title"] = "Page2";
}
<h1>Page2</h1>
|
||||
TheStack | b5a4f7d859fb6fc9d313bd9416cb892705994e12 | C#code:C# | {"size": 5053, "ext": "cs", "max_stars_repo_path": "Chroma.NALO/Compression/BZip2Crc.cs", "max_stars_repo_name": "Ciastex/Chroma", "max_stars_repo_stars_event_min_datetime": "2020-06-22T09:29:24.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-20T16:35:32.000Z", "max_issues_repo_path": "Chroma.NALO/Compression/BZip2Crc.cs", "max_issues_repo_name": "Ciastex/Chroma", "max_issues_repo_issues_event_min_datetime": "2020-06-22T11:07:09.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-12T17:00:17.000Z", "max_forks_repo_path": "Chroma.NALO/Compression/BZip2Crc.cs", "max_forks_repo_name": "Ciastex/Chroma", "max_forks_repo_forks_event_min_datetime": "2020-06-24T13:22:55.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-24T13:22:55.000Z"} | {"max_stars_count": 7.0, "max_issues_count": 16.0, "max_forks_count": 1.0, "avg_line_length": 45.9363636364, "max_line_length": 116, "alphanum_fraction": 0.6388284188} | using System;
namespace Chroma.NALO.Compression
{
internal sealed class BZip2Crc
{
private const uint CrcInit = 0xFFFFFFFF;
private static readonly uint[] _crcTable =
{
0x00000000, 0x04C11DB7, 0x09823B6E, 0x0D4326D9,
0x130476DC, 0x17C56B6B, 0x1A864DB2, 0x1E475005,
0x2608EDB8, 0x22C9F00F, 0x2F8AD6D6, 0x2B4BCB61,
0x350C9B64, 0x31CD86D3, 0x3C8EA00A, 0x384FBDBD,
0x4C11DB70, 0x48D0C6C7, 0x4593E01E, 0x4152FDA9,
0x5F15ADAC, 0x5BD4B01B, 0x569796C2, 0x52568B75,
0x6A1936C8, 0x6ED82B7F, 0x639B0DA6, 0x675A1011,
0x791D4014, 0x7DDC5DA3, 0x709F7B7A, 0x745E66CD,
0x9823B6E0, 0x9CE2AB57, 0x91A18D8E, 0x95609039,
0x8B27C03C, 0x8FE6DD8B, 0x82A5FB52, 0x8664E6E5,
0xBE2B5B58, 0xBAEA46EF, 0xB7A96036, 0xB3687D81,
0xAD2F2D84, 0xA9EE3033, 0xA4AD16EA, 0xA06C0B5D,
0xD4326D90, 0xD0F37027, 0xDDB056FE, 0xD9714B49,
0xC7361B4C, 0xC3F706FB, 0xCEB42022, 0xCA753D95,
0xF23A8028, 0xF6FB9D9F, 0xFBB8BB46, 0xFF79A6F1,
0xE13EF6F4, 0xE5FFEB43, 0xE8BCCD9A, 0xEC7DD02D,
0x34867077, 0x30476DC0, 0x3D044B19, 0x39C556AE,
0x278206AB, 0x23431B1C, 0x2E003DC5, 0x2AC12072,
0x128E9DCF, 0x164F8078, 0x1B0CA6A1, 0x1FCDBB16,
0x018AEB13, 0x054BF6A4, 0x0808D07D, 0x0CC9CDCA,
0x7897AB07, 0x7C56B6B0, 0x71159069, 0x75D48DDE,
0x6B93DDDB, 0x6F52C06C, 0x6211E6B5, 0x66D0FB02,
0x5E9F46BF, 0x5A5E5B08, 0x571D7DD1, 0x53DC6066,
0x4D9B3063, 0x495A2DD4, 0x44190B0D, 0x40D816BA,
0xACA5C697, 0xA864DB20, 0xA527FDF9, 0xA1E6E04E,
0xBFA1B04B, 0xBB60ADFC, 0xB6238B25, 0xB2E29692,
0x8AAD2B2F, 0x8E6C3698, 0x832F1041, 0x87EE0DF6,
0x99A95DF3, 0x9D684044, 0x902B669D, 0x94EA7B2A,
0xE0B41DE7, 0xE4750050, 0xE9362689, 0xEDF73B3E,
0xF3B06B3B, 0xF771768C, 0xFA325055, 0xFEF34DE2,
0xC6BCF05F, 0xC27DEDE8, 0xCF3ECB31, 0xCBFFD686,
0xD5B88683, 0xD1799B34, 0xDC3ABDED, 0xD8FBA05A,
0x690CE0EE, 0x6DCDFD59, 0x608EDB80, 0x644FC637,
0x7A089632, 0x7EC98B85, 0x738AAD5C, 0x774BB0EB,
0x4F040D56, 0x4BC510E1, 0x46863638, 0x42472B8F,
0x5C007B8A, 0x58C1663D, 0x558240E4, 0x51435D53,
0x251D3B9E, 0x21DC2629, 0x2C9F00F0, 0x285E1D47,
0x36194D42, 0x32D850F5, 0x3F9B762C, 0x3B5A6B9B,
0x0315D626, 0x07D4CB91, 0x0A97ED48, 0x0E56F0FF,
0x1011A0FA, 0x14D0BD4D, 0x19939B94, 0x1D528623,
0xF12F560E, 0xF5EE4BB9, 0xF8AD6D60, 0xFC6C70D7,
0xE22B20D2, 0xE6EA3D65, 0xEBA91BBC, 0xEF68060B,
0xD727BBB6, 0xD3E6A601, 0xDEA580D8, 0xDA649D6F,
0xC423CD6A, 0xC0E2D0DD, 0xCDA1F604, 0xC960EBB3,
0xBD3E8D7E, 0xB9FF90C9, 0xB4BCB610, 0xB07DABA7,
0xAE3AFBA2, 0xAAFBE615, 0xA7B8C0CC, 0xA379DD7B,
0x9B3660C6, 0x9FF77D71, 0x92B45BA8, 0x9675461F,
0x8832161A, 0x8CF30BAD, 0x81B02D74, 0x857130C3,
0x5D8A9099, 0x594B8D2E, 0x5408ABF7, 0x50C9B640,
0x4E8EE645, 0x4A4FFBF2, 0x470CDD2B, 0x43CDC09C,
0x7B827D21, 0x7F436096, 0x7200464F, 0x76C15BF8,
0x68860BFD, 0x6C47164A, 0x61043093, 0x65C52D24,
0x119B4BE9, 0x155A565E, 0x18197087, 0x1CD86D30,
0x029F3D35, 0x065E2082, 0x0B1D065B, 0x0FDC1BEC,
0x3793A651, 0x3352BBE6, 0x3E119D3F, 0x3AD08088,
0x2497D08D, 0x2056CD3A, 0x2D15EBE3, 0x29D4F654,
0xC5A92679, 0xC1683BCE, 0xCC2B1D17, 0xC8EA00A0,
0xD6AD50A5, 0xD26C4D12, 0xDF2F6BCB, 0xDBEE767C,
0xE3A1CBC1, 0xE760D676, 0xEA23F0AF, 0xEEE2ED18,
0xF0A5BD1D, 0xF464A0AA, 0xF9278673, 0xFDE69BC4,
0x89B8FD09, 0x8D79E0BE, 0x803AC667, 0x84FBDBD0,
0x9ABC8BD5, 0x9E7D9662, 0x933EB0BB, 0x97FFAD0C,
0xAFB010B1, 0xAB710D06, 0xA6322BDF, 0xA2F33668,
0xBCB4666D, 0xB8757BDA, 0xB5365D03, 0xB1F740B4
};
private uint _checkValue;
public BZip2Crc()
=> Reset();
public void Reset()
=> _checkValue = CrcInit;
public long Value => ~_checkValue;
public void Update(int bval)
=> _checkValue = unchecked(_crcTable[(byte)(((_checkValue >> 24) & 0xFF) ^ bval)] ^ (_checkValue << 8));
public void Update(byte[] buffer)
{
if (buffer == null)
throw new ArgumentNullException(nameof(buffer));
Update(new ArraySegment<byte>(buffer, 0, buffer.Length));
}
public void Update(ArraySegment<byte> segment)
{
if (segment == null || segment.Array == null)
throw new ArgumentNullException(nameof(segment), "Segment or segment's array field was null.");
var count = segment.Count;
var offset = segment.Offset;
while (--count >= 0)
Update(segment.Array[offset++]);
}
}
} |
||||
TheStack | b5a51c96598a8e49a1a7492b3415c8a6e4f75f3a | C#code:C# | {"size": 6105, "ext": "cs", "max_stars_repo_path": "Beat&Nest/Assets/SC Post Effects/Effects/LightStreaks/LightStreaks.cs", "max_stars_repo_name": "TereanYu/BeatNest", "max_stars_repo_stars_event_min_datetime": "2019-01-31T03:33:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-04T10:00:05.000Z", "max_issues_repo_path": "Beat&Nest/Assets/SC Post Effects/Effects/LightStreaks/LightStreaks.cs", "max_issues_repo_name": "TereanYu/BeatNest", "max_issues_repo_issues_event_min_datetime": "2020-05-20T04:00:05.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-20T04:13:51.000Z", "max_forks_repo_path": "Beat&Nest/Assets/SC Post Effects/Effects/LightStreaks/LightStreaks.cs", "max_forks_repo_name": "TereanYu/BeatNest", "max_forks_repo_forks_event_min_datetime": "2019-06-24T09:12:41.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-04T12:33:14.000Z"} | {"max_stars_count": 14.0, "max_issues_count": 1.0, "max_forks_count": 2.0, "avg_line_length": 40.4304635762, "max_line_length": 157, "alphanum_fraction": 0.638984439} | using System;
using UnityEngine;
using UnityEngine.Rendering;
#if SCPE
using UnityEngine.Rendering.PostProcessing;
#endif
namespace SCPE
{
#if !SCPE
public class LightStreaks : ScriptableObject
{
}
}
#else
[Serializable]
[PostProcess(typeof(LightStreaksRenderer), PostProcessEvent.BeforeStack, "SC Post Effects/Rendering/Light Streaks", true)]
public sealed class LightStreaks : PostProcessEffectSettings
{
public enum Quality
{
Performance,
Appearance
}
[Serializable]
public sealed class BlurMethodParameter : ParameterOverride<Quality> { }
[DisplayName("Quality"), Tooltip("Choose between Box and Gaussian blurring methods.\n\nBox blurring is more efficient but has a limited blur range")]
public BlurMethodParameter quality = new BlurMethodParameter { value = Quality.Appearance };
[Range(0f, 1f), DisplayName("Streaks Only"), Tooltip("Shows only the effect, to alow for finetuning")]
public BoolParameter debug = new BoolParameter { value = false };
[Header("Anamorphic Lensfares")]
[Range(0f, 1f), Tooltip("Intensity")]
public FloatParameter intensity = new FloatParameter { value = 1f };
[Range(0.01f, 3f), Tooltip("Luminance threshold, pixels above this threshold will contribute to the effect")]
public FloatParameter luminanceThreshold = new FloatParameter { value = 1f };
[Range(-1f, 1f), Tooltip("Direction")]
public FloatParameter direction = new FloatParameter { value = -1f };
[Header("Blur")]
[Range(0f, 10f), DisplayName("Length"), Tooltip("The amount of blurring that must be performed")]
public FloatParameter blur = new FloatParameter { value = 1f };
[Range(1, 8), Tooltip("The number of times the effect is blurred. More iterations provide a smoother effect but induce more drawcalls.")]
public IntParameter iterations = new IntParameter { value = 2 };
[Range(1, 8), Tooltip("Every step halfs the resolution of the blur effect. Lower resolution provides a smoother blur but may induce flickering")]
public IntParameter downscaling = new IntParameter { value = 2 };
public override bool IsEnabledAndSupported(PostProcessRenderContext context)
{
if (enabled.value)
{
if (blur == 0 || intensity == 0 || direction == 0) { return false; }
return true;
}
return false;
}
}
public sealed class LightStreaksRenderer : PostProcessEffectRenderer<LightStreaks>
{
Shader shader;
private int emissionTex;
RenderTexture aoRT;
public override void Init()
{
shader = Shader.Find("Hidden/SC Post Effects/Light Streaks");
emissionTex = Shader.PropertyToID("_BloomTex");
}
public override void Release()
{
base.Release();
}
enum Pass
{
LuminanceDiff,
BlurFast,
Blur,
Blend,
Debug
}
public override void Render(PostProcessRenderContext context)
{
var sheet = context.propertySheets.Get(shader);
CommandBuffer cmd = context.command;
int blurMode = (settings.quality.value == LightStreaks.Quality.Performance) ? (int)Pass.BlurFast : (int)Pass.Blur;
//float luminanceThreshold = (context.isSceneView) ? settings.luminanceThreshold / 20f : settings.luminanceThreshold;
float luminanceThreshold = Mathf.GammaToLinearSpace(settings.luminanceThreshold.value);
sheet.properties.SetFloat("_Threshold", luminanceThreshold);
sheet.properties.SetFloat("_Blur", settings.blur);
sheet.properties.SetFloat("_Intensity", settings.intensity);
// Create RT for storing edge detection in
context.command.GetTemporaryRT(emissionTex, context.width, context.height, 0, FilterMode.Bilinear, context.sourceFormat);
//Luminance difference check on RT
context.command.BlitFullscreenTriangle(context.source, emissionTex, sheet, (int)Pass.LuminanceDiff);
int downSamples = settings.downscaling + 1;
// get two smaller RTs
int blurredID = Shader.PropertyToID("_Temp1");
int blurredID2 = Shader.PropertyToID("_Temp2");
cmd.GetTemporaryRT(blurredID, context.width/ downSamples, context.height/ downSamples, 0, FilterMode.Bilinear);
cmd.GetTemporaryRT(blurredID2, context.width/ downSamples, context.height/ downSamples, 0, FilterMode.Bilinear);
//Pass into blur target texture
cmd.Blit(emissionTex, blurredID);
float ratio = Mathf.Clamp(settings.direction, -1, 1);
float rw = ratio < 0 ? -ratio : 0f;
float rh = ratio > 0 ? ratio * 8 : 0f;
for (int i = 0; i < settings.iterations; i++)
{
// vertical blur 1
cmd.SetGlobalVector("_BlurOffsets", new Vector4(rw * settings.blur / context.screenWidth, rh / context.screenHeight, 0, 0));
context.command.BlitFullscreenTriangle(blurredID, blurredID2, sheet, blurMode);
// vertical blur 2
cmd.SetGlobalVector("_BlurOffsets", new Vector4((rw * settings.blur) * 2f / context.screenWidth, rh * 2f / context.screenHeight, 0, 0));
context.command.BlitFullscreenTriangle(blurredID2, blurredID, sheet, blurMode);
}
context.command.SetGlobalTexture("_BloomTex", blurredID);
//Blend AO tex with image
context.command.BlitFullscreenTriangle(context.source, context.destination, sheet, (settings.debug) ? (int)Pass.Debug : (int)Pass.Blend);
// release
context.command.ReleaseTemporaryRT(blurredID);
context.command.ReleaseTemporaryRT(blurredID2);
context.command.ReleaseTemporaryRT(emissionTex);
}
}
}
#endif |
||||
TheStack | b5a54bcd1788beadff837239a484a38b6e048724 | C#code:C# | {"size": 25578, "ext": "cs", "max_stars_repo_path": "OWWC.MULTI/Views/WorldcupPage.xaml.cs", "max_stars_repo_name": "cptalpdeniz/OverwatchWorldCupApp2018", "max_stars_repo_stars_event_min_datetime": "2020-03-03T12:21:07.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-03T12:21:07.000Z", "max_issues_repo_path": "OWWC.MULTI/Views/WorldcupPage.xaml.cs", "max_issues_repo_name": "cptalpdeniz/OverwatchWorldCupApp2018", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "OWWC.MULTI/Views/WorldcupPage.xaml.cs", "max_forks_repo_name": "cptalpdeniz/OverwatchWorldCupApp2018", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 50.3503937008, "max_line_length": 149, "alphanum_fraction": 0.4668856048} | using System.Net;
using System;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using OWWC.MULTI.Countries;
using OWWC.MULTI.Services;
using Foundation;
using HtmlAgilityPack;
using System.Text.RegularExpressions;
namespace OWWC.MULTI.Views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class WorldcupPage : ContentPage
{
public string[] GetNextGamesLive(string team1, string team2)
{
string[] teams = new string[6];
DateTime currentDate = DateTime.UtcNow.Date;
bool isTwelveHourFormat = false;
var DeviceHourFormat = DependencyService.Get<IHourFormat>();
isTwelveHourFormat = DeviceHourFormat.CheckTwelveHourFormat();
if (currentDate == FRGroupStage.Day1.Date)
{
for (int i = 0; i < 5; i++)
{
if (team1 == FRGroupStage.home[i] && team2 == FRGroupStage.away[i])
{
if (i < 3)
{
if (isTwelveHourFormat)
{
game1Date.Text = FRGroupStage.Day1.Match[i].Date.ToLocalTime().ToString("MMM dd, h:mm tt");
game2Date.Text = FRGroupStage.Day1.Match[i + 1].Date.ToLocalTime().ToString("MMM dd, h:mm tt");
game3Date.Text = FRGroupStage.Day1.Match[i + 2].Date.ToLocalTime().ToString("MMM dd, h:mm tt");
}
else
{
game1Date.Text = FRGroupStage.Day1.Match[i].Date.ToLocalTime().ToString("MMM dd, HH:mm");
game2Date.Text = FRGroupStage.Day1.Match[i + 1].Date.ToLocalTime().ToString("MMM dd, HH:mm");
game3Date.Text = FRGroupStage.Day1.Match[i + 2].Date.ToLocalTime().ToString("MMM dd, HH:mm");
}
teams[0] = FRGroupStage.home[i];
teams[1] = FRGroupStage.away[i];
teams[2] = FRGroupStage.home[i + 1];
teams[3] = FRGroupStage.away[i + 1];
teams[4] = FRGroupStage.home[i + 2];
teams[5] = FRGroupStage.away[i + 2];
return teams;
}
else if (i == 3)
{
if (isTwelveHourFormat)
{
game1Date.Text = FRGroupStage.Day1.Match[i].Date.ToLocalTime().ToString("MMM dd, h:mm tt");
game2Date.Text = FRGroupStage.Day1.Match[i + 1].Date.ToLocalTime().ToString("MMM dd, h:mm tt");
game3Date.Text = FRGroupStage.Day2.Match[0].Date.ToLocalTime().ToString("MMM dd, h:mm tt");
}
else
{
game1Date.Text = FRGroupStage.Day1.Match[i].Date.ToLocalTime().ToString("MMM dd, HH:mm");
game2Date.Text = FRGroupStage.Day1.Match[i + 1].Date.ToLocalTime().ToString("MMM dd, HH:mm");
game3Date.Text = FRGroupStage.Day2.Match[0].Date.ToLocalTime().ToString("MMM dd, HH:mm");
}
teams[0] = FRGroupStage.home[i];
teams[1] = FRGroupStage.away[i];
teams[2] = FRGroupStage.home[i + 1];
teams[3] = FRGroupStage.away[i + 1];
teams[4] = FRGroupStage.home[0];
teams[5] = FRGroupStage.away[0];
return teams;
}
else
{
if (isTwelveHourFormat)
{
game1Date.Text = FRGroupStage.Day1.Match[i].Date.ToLocalTime().ToString("MMM dd, h:mm tt");
game2Date.Text = FRGroupStage.Day2.Match[0].Date.ToLocalTime().ToString("MMM dd, h:mm tt");
game3Date.Text = FRGroupStage.Day2.Match[1].Date.ToLocalTime().ToString("MMM dd, h:mm tt");
}
else
{
game1Date.Text = FRGroupStage.Day1.Match[i].Date.ToLocalTime().ToString("MMM dd, HH:mm");
game2Date.Text = FRGroupStage.Day2.Match[0].Date.ToLocalTime().ToString("MMM dd, HH:mm");
game3Date.Text = FRGroupStage.Day2.Match[1].Date.ToLocalTime().ToString("MMM dd, HH:mm");
}
teams[0] = FRGroupStage.home[i];
teams[1] = FRGroupStage.away[i];
teams[2] = FRGroupStage.home[0];
teams[3] = FRGroupStage.away[0];
teams[4] = FRGroupStage.home[1];
teams[5] = FRGroupStage.away[1];
return teams;
}
}
}
}
else if (currentDate == FRGroupStage.Day2.Date)
{
for (int i = 5; i < 10; i++)
{
if (team1 == FRGroupStage.home[i] && team2 == FRGroupStage.away[i])
{
if (i < 8)
{
if (isTwelveHourFormat)
{
game1Date.Text = FRGroupStage.Day2.Match[(i - 5)].Date.ToLocalTime().ToString("MMM dd, h:mm tt");
game2Date.Text = FRGroupStage.Day2.Match[(i - 5) + 1].Date.ToLocalTime().ToString("MMM dd, h:mm tt");
game3Date.Text = FRGroupStage.Day2.Match[(i - 5) + 2].Date.ToLocalTime().ToString("MMM dd, h:mm tt");
}
else
{
game1Date.Text = FRGroupStage.Day2.Match[(i - 5)].Date.ToLocalTime().ToString("MMM dd, HH:mm");
game2Date.Text = FRGroupStage.Day2.Match[(i - 5) + 1].Date.ToLocalTime().ToString("MMM dd, HH:mm");
game3Date.Text = FRGroupStage.Day2.Match[(i - 5) + 2].Date.ToLocalTime().ToString("MMM dd, HH:mm");
}
teams[0] = FRGroupStage.home[i];
teams[1] = FRGroupStage.away[i];
teams[2] = FRGroupStage.home[i + 1];
teams[3] = FRGroupStage.away[i + 1];
teams[4] = FRGroupStage.home[i + 2];
teams[5] = FRGroupStage.away[i + 2];
return teams;
}
else if (i == 8)
{
if (isTwelveHourFormat)
{
game1Date.Text = FRGroupStage.Day2.Match[(i - 5)].Date.ToLocalTime().ToString("MMM dd, h:mm tt");
game2Date.Text = FRGroupStage.Day2.Match[(i - 5) + 1].Date.ToLocalTime().ToString("MMM dd, h:mm tt");
game3Date.Text = FRGroupStage.Day3.Match[0].Date.ToLocalTime().ToString("MMM dd, h:mm tt");
}
else
{
game1Date.Text = FRGroupStage.Day2.Match[(i - 5)].Date.ToLocalTime().ToString("MMM dd, HH:mm");
game2Date.Text = FRGroupStage.Day2.Match[(i - 5) + 1].Date.ToLocalTime().ToString("MMM dd, HH:mm");
game3Date.Text = FRGroupStage.Day3.Match[0].Date.ToLocalTime().ToString("MMM dd, HH:mm");
}
teams[0] = FRGroupStage.home[i];
teams[1] = FRGroupStage.away[i];
teams[2] = FRGroupStage.home[i + 1];
teams[3] = FRGroupStage.away[i + 1];
teams[4] = FRGroupStage.home[i + 2];
teams[5] = FRGroupStage.away[i + 2];
return teams;
}
else
{
if (isTwelveHourFormat)
{
game1Date.Text = FRGroupStage.Day2.Match[(i - 5)].Date.ToLocalTime().ToString("MMM dd, h:mm tt");
game2Date.Text = FRGroupStage.Day3.Match[0].Date.ToLocalTime().ToString("MMM dd, h:mm tt");
game3Date.Text = FRGroupStage.Day3.Match[1].Date.ToLocalTime().ToString("MMM dd, h:mm tt");
}
else
{
game1Date.Text = FRGroupStage.Day2.Match[(i - 5)].Date.ToLocalTime().ToString("MMM dd, HH:mm");
game2Date.Text = FRGroupStage.Day3.Match[0].Date.ToLocalTime().ToString("MMM dd, HH:mm");
game3Date.Text = FRGroupStage.Day3.Match[1].Date.ToLocalTime().ToString("MMM dd, HH:mm");
}
teams[0] = FRGroupStage.home[i];
teams[1] = FRGroupStage.away[i];
teams[2] = FRGroupStage.home[i + 1];
teams[3] = FRGroupStage.away[i + 1];
teams[4] = FRGroupStage.home[i + 2];
teams[5] = FRGroupStage.away[i + 2];
return teams;
}
}
}
}
else if (currentDate == FRGroupStage.Day3.Date)
{
for (int i = 10; i < 15; i++)
{
if (team1 == FRGroupStage.home[i] && team2 == FRGroupStage.away[i])
{
if (i < 13)
{
if (isTwelveHourFormat)
{
game1Date.Text = FRGroupStage.Day3.Match[(i - 10)].Date.ToLocalTime().ToString("MMM dd, h:mm tt");
game2Date.Text = FRGroupStage.Day3.Match[(i - 10) + 1].Date.ToLocalTime().ToString("MMM dd, h:mm tt");
game3Date.Text = FRGroupStage.Day3.Match[(i - 10) + 2].Date.ToLocalTime().ToString("MMM dd, h:mm tt");
}
else
{
game1Date.Text = FRGroupStage.Day3.Match[(i - 10)].Date.ToLocalTime().ToString("MMM dd, HH:mm");
game2Date.Text = FRGroupStage.Day3.Match[(i - 10) + 1].Date.ToLocalTime().ToString("MMM dd, HH:mm");
game3Date.Text = FRGroupStage.Day3.Match[(i - 10) + 2].Date.ToLocalTime().ToString("MMM dd, HH:mm");
}
teams[0] = FRGroupStage.home[(i - 10)];
teams[1] = FRGroupStage.away[(i - 10)];
teams[2] = FRGroupStage.home[(i - 10) + 1];
teams[3] = FRGroupStage.away[(i - 10) + 1];
teams[4] = FRGroupStage.home[(i - 10) + 2];
teams[5] = FRGroupStage.away[(i - 10) + 2];
return teams;
}
else
{
if (isTwelveHourFormat)
{
game1Date.Text = FRGroupStage.Day3.Match[2].Date.ToLocalTime().ToString("MMM dd, h:mm tt");
game2Date.Text = FRGroupStage.Day3.Match[3].Date.ToLocalTime().ToString("MMM dd, h:mm tt");
game3Date.Text = FRGroupStage.Day3.Match[4].Date.ToLocalTime().ToString("MMM dd, h:mm tt");
}
else
{
game1Date.Text = FRGroupStage.Day3.Match[2].Date.ToLocalTime().ToString("MMM dd, HH:mm");
game2Date.Text = FRGroupStage.Day3.Match[3].Date.ToLocalTime().ToString("MMM dd, HH:mm");
game3Date.Text = FRGroupStage.Day3.Match[4].Date.ToLocalTime().ToString("MMM dd, HH:mm");
}
teams[0] = FRGroupStage.home[12];
teams[1] = FRGroupStage.away[12];
teams[2] = FRGroupStage.home[13];
teams[3] = FRGroupStage.away[13];
teams[4] = FRGroupStage.home[14];
teams[5] = FRGroupStage.away[14];
return teams;
}
}
}
}
return teams;
}
public string[] GetNextGames()
{
string[] teams = new string[6];
DateTime currentDate = DateTime.UtcNow;
var DeviceHourFormat = DependencyService.Get<IHourFormat>();
bool isTwelveHourFormat = DeviceHourFormat.CheckTwelveHourFormat();
if (currentDate > FRGroupStage.Day1.Match[4].Date && currentDate < FRGroupStage.Day2.Match[0].Date)
{
if (isTwelveHourFormat)
{
game1Date.Text = FRGroupStage.Day2.Match[0].Date.ToLocalTime().ToString("MMM dd, h:mm tt");
game2Date.Text = FRGroupStage.Day2.Match[1].Date.ToLocalTime().ToString("MMM dd, h:mm tt");
game3Date.Text = FRGroupStage.Day2.Match[2].Date.ToLocalTime().ToString("MMM dd, h:mm tt");
}
else
{
game1Date.Text = FRGroupStage.Day2.Match[0].Date.ToLocalTime().ToString("MMM dd, HH:mm");
game2Date.Text = FRGroupStage.Day2.Match[1].Date.ToLocalTime().ToString("MMM dd, HH:mm");
game3Date.Text = FRGroupStage.Day2.Match[2].Date.ToLocalTime().ToString("MMM dd, HH:mm");
}
teams[0] = FRGroupStage.Day2.Match[0].Home;
teams[1] = FRGroupStage.Day2.Match[0].Away;
teams[2] = FRGroupStage.Day2.Match[1].Home;
teams[3] = FRGroupStage.Day2.Match[1].Away;
teams[4] = FRGroupStage.Day2.Match[2].Home;
teams[5] = FRGroupStage.Day2.Match[2].Away;
return teams;
}
else if (currentDate > FRGroupStage.Day2.Match[4].Date && currentDate < FRGroupStage.Day3.Match[0].Date)
{
if (isTwelveHourFormat)
{
game1Date.Text = FRGroupStage.Day3.Match[0].Date.ToLocalTime().ToString("MMM dd, h:mm tt");
game2Date.Text = FRGroupStage.Day3.Match[1].Date.ToLocalTime().ToString("MMM dd, h:mm tt");
game3Date.Text = FRGroupStage.Day3.Match[2].Date.ToLocalTime().ToString("MMM dd, h:mm tt");
}
else
{
game1Date.Text = FRGroupStage.Day3.Match[0].Date.ToLocalTime().ToString("MMM dd, HH:mm");
game2Date.Text = FRGroupStage.Day3.Match[1].Date.ToLocalTime().ToString("MMM dd, HH:mm");
game3Date.Text = FRGroupStage.Day3.Match[2].Date.ToLocalTime().ToString("MMM dd, HH:mm");
}
teams[0] = FRGroupStage.Day3.Match[0].Home;
teams[1] = FRGroupStage.Day3.Match[0].Away;
teams[2] = FRGroupStage.Day3.Match[1].Home;
teams[3] = FRGroupStage.Day3.Match[1].Away;
teams[4] = FRGroupStage.Day3.Match[2].Home;
teams[5] = FRGroupStage.Day3.Match[2].Away;
return teams;
}
else
{
if (isTwelveHourFormat)
{
game1Date.Text = FRGroupStage.Day3.Match[2].Date.ToLocalTime().ToString("MMM dd, h:mm tt");
game2Date.Text = FRGroupStage.Day3.Match[3].Date.ToLocalTime().ToString("MMM dd, h:mm tt");
game3Date.Text = FRGroupStage.Day3.Match[4].Date.ToLocalTime().ToString("MMM dd, h:mm tt");
}
else
{
game1Date.Text = FRGroupStage.Day3.Match[2].Date.ToLocalTime().ToString("MMM dd, HH:mm");
game2Date.Text = FRGroupStage.Day3.Match[3].Date.ToLocalTime().ToString("MMM dd, HH:mm");
game3Date.Text = FRGroupStage.Day3.Match[4].Date.ToLocalTime().ToString("MMM dd, HH:mm");
}
teams[0] = FRGroupStage.Day3.Match[2].Home;
teams[1] = FRGroupStage.Day3.Match[2].Away;
teams[2] = FRGroupStage.Day3.Match[3].Home;
teams[3] = FRGroupStage.Day3.Match[3].Away;
teams[4] = FRGroupStage.Day3.Match[4].Home;
teams[5] = FRGroupStage.Day3.Match[4].Away;
return teams;
}
}
public WorldcupPage()
{
InitializeComponent();
if (TwitchClass.GetLiveWC())
{
liveGame.IsVisible = true;
var titleText = TwitchClass.getStreams.Streams[0].Title; //test this part
int index = titleText.IndexOf(" v", StringComparison.Ordinal);
if (index > 0)
liveText1.Text = titleText.Substring(0, index);
if (titleText.Contains("vs. "))
{
index = titleText.IndexOf("vs. ", StringComparison.Ordinal) + "vs. ".Length;
}
else if (titleText.Contains("vs"))
{
index = titleText.IndexOf("vs ", StringComparison.Ordinal) + "vs ".Length;
}
int index2 = titleText.IndexOf(" |", StringComparison.Ordinal);
var tempor = titleText.Substring(index);
index2 = tempor.IndexOf(" |", StringComparison.Ordinal);
liveText2.Text = titleText.Substring(index, index2);
team1.Text = liveText1.Text;
team2.Text = liveText2.Text;
Country country1 = OpeningPage._countries[team1.Text];
Country country2 = OpeningPage._countries[team2.Text];
flag1.Source = ImageSource.FromFile(country1.GetFlag());
flag2.Source = ImageSource.FromFile(country2.GetFlag());
string[] Teams = new string[6];
Teams = GetNextGamesLive(team1.Text, team2.Text);
team3.Text = Teams[2];
team4.Text = Teams[3];
team5.Text = Teams[4];
team6.Text = Teams[5];
Country country3 = OpeningPage._countries[Teams[2]];
Country country4 = OpeningPage._countries[Teams[3]];
Country country5 = OpeningPage._countries[Teams[4]];
Country country6 = OpeningPage._countries[Teams[5]];
flag3.Source = ImageSource.FromFile(country3.GetFlag());
flag4.Source = ImageSource.FromFile(country4.GetFlag());
flag5.Source = ImageSource.FromFile(country5.GetFlag());
flag6.Source = ImageSource.FromFile(country6.GetFlag());
}
else
{
liveGame.IsVisible = false;
string[] Teams = new string[6];
Teams = GetNextGames();
team1.Text = Teams[0];
team2.Text = Teams[1];
team3.Text = Teams[2];
team4.Text = Teams[3];
team5.Text = Teams[4];
team6.Text = Teams[5];
Country country1 = OpeningPage._countries[Teams[0]];
Country country2 = OpeningPage._countries[Teams[1]];
Country country3 = OpeningPage._countries[Teams[2]];
Country country4 = OpeningPage._countries[Teams[3]];
Country country5 = OpeningPage._countries[Teams[4]];
Country country6 = OpeningPage._countries[Teams[5]];
flag1.Source = ImageSource.FromFile(country1.GetFlag());
flag2.Source = ImageSource.FromFile(country2.GetFlag());
flag3.Source = ImageSource.FromFile(country3.GetFlag());
flag4.Source = ImageSource.FromFile(country4.GetFlag());
flag5.Source = ImageSource.FromFile(country5.GetFlag());
flag6.Source = ImageSource.FromFile(country6.GetFlag());
}
NewsGrid0.Margin = new Thickness(2, 10);
NewsGrid1.Margin = new Thickness(2, 10);
NewsGrid2.Margin = new Thickness(2, 10);
int count = 0;
var url = "https://overwatchleague.com/en-us/news";
var web = new HtmlWeb();
var doc = web.Load(url);
var block = "//*[@id='tab1']/div[1]/div[";
string title;
string[] titleTextArray = new string[5];
string[] newsImage = new string[5];
DateTime[] DateText = new DateTime[5];
for (int i = 1; true; i++)
{
if (count > 3)
{
break;
}
var xpath = block + i.ToString() + "]/div[2]/div/div/div/span[1]";
if (doc.DocumentNode.SelectNodes(xpath)[0].InnerText.Contains("Feature"))
{
title = block + i.ToString() + "]/div[2]/div/h6/a";
titleTextArray[count] = doc.DocumentNode.SelectNodes(title)[0].InnerText;
var xpathDate = block + i.ToString() + "]/div[2]/div/div/div/span[2]/time";
var dateTemp = doc.DocumentNode.SelectNodes(xpathDate)[0].Attributes["datetime"].Value;
DateText[count] = DateTime.ParseExact(dateTemp, "yyyy-MM-dd'T'HH:mm:ss.fff'Z\'", null);
var imagepath = block + i.ToString() + "]/div[1]/a";
var imagelink = doc.DocumentNode.SelectNodes(imagepath)[0].Attributes["style"].Value;
var index = imagelink.IndexOf("url('", StringComparison.Ordinal) + "url('".Length;
var index2 = imagelink.IndexOf("');", StringComparison.Ordinal);
newsImage[count] = imagelink.Substring(index, index2 - index);
var urlpath = block + i.ToString() + "]/div[2]/div/h6/a";
ConstantsClass.NewsUrl[count] = "http://overwatchleague.com" + doc.DocumentNode.SelectNodes(urlpath)[0].Attributes["href"].Value;
count++;
}
}
//*[@id="tab1"]/div[1]/div[1]/div[2]/div/h6/a
var newsGrid1TapGesture = new TapGestureRecognizer();
newsGrid1TapGesture.Tapped += (s, e) =>
{
Navigation.PushAsync(new NewsContent1());
};
NewsGrid0.GestureRecognizers.Add(newsGrid1TapGesture);
var newsGrid2TapGesture = new TapGestureRecognizer();
newsGrid2TapGesture.Tapped += (s, e) =>
{
Navigation.PushAsync(new NewsContent2());
};
NewsGrid1.GestureRecognizers.Add(newsGrid2TapGesture);
var newsGrid3TapGesture = new TapGestureRecognizer();
newsGrid3TapGesture.Tapped += (s, e) =>
{
Navigation.PushAsync(new NewsContent3());
};
NewsGrid2.GestureRecognizers.Add(newsGrid3TapGesture);
var newsGrid4TapGesture = new TapGestureRecognizer();
newsGrid3TapGesture.Tapped += (s, e) =>
{
Navigation.PushAsync(new NewsContent4());
};
NewsGrid3.GestureRecognizers.Add(newsGrid4TapGesture);
newsImage0.Source = ImageSource.FromUri(new Uri(newsImage[0]));
title0.Text = titleTextArray[0];
date0.Text = DateText[0].ToString("MMM dd");
newsImage1.Source = ImageSource.FromUri(new Uri(newsImage[1]));
title1.Text = titleTextArray[1];
date1.Text = DateText[1].ToString("MMM dd");
newsImage2.Source = ImageSource.FromUri(new Uri(newsImage[2]));
title2.Text = titleTextArray[2];
date2.Text = DateText[2].ToString("MMM dd");
newsImage3.Source = ImageSource.FromUri(new Uri(newsImage[3]));
title3.Text = titleTextArray[3];
date3.Text = DateText[3].ToString("MMM dd");
}
async void OnAboutTextClick(object sender, EventArgs e)
{
await Navigation.PushAsync(new AboutPage());
}
}
}
|
||||
TheStack | b5a57e764e5b74ff164db65d3887c81f65d5a4a4 | C#code:C# | {"size": 4486, "ext": "cs", "max_stars_repo_path": "sdk/src/Services/EC2/Generated/Model/AnalysisSecurityGroupRule.cs", "max_stars_repo_name": "philasmar/aws-sdk-net", "max_stars_repo_stars_event_min_datetime": "2021-09-17T15:33:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-17T15:33:32.000Z", "max_issues_repo_path": "sdk/src/Services/EC2/Generated/Model/AnalysisSecurityGroupRule.cs", "max_issues_repo_name": "philasmar/aws-sdk-net", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sdk/src/Services/EC2/Generated/Model/AnalysisSecurityGroupRule.cs", "max_forks_repo_name": "philasmar/aws-sdk-net", "max_forks_repo_forks_event_min_datetime": "2022-01-22T02:39:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-22T02:39:11.000Z"} | {"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": 1.0, "avg_line_length": 27.8633540373, "max_line_length": 102, "alphanum_fraction": 0.5171645118} | /*
* 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.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.EC2.Model
{
/// <summary>
/// Describes a security group rule.
/// </summary>
public partial class AnalysisSecurityGroupRule
{
private string _cidr;
private string _direction;
private PortRange _portRange;
private string _prefixListId;
private string _protocol;
private string _securityGroupId;
/// <summary>
/// Gets and sets the property Cidr.
/// <para>
/// The IPv4 address range, in CIDR notation.
/// </para>
/// </summary>
public string Cidr
{
get { return this._cidr; }
set { this._cidr = value; }
}
// Check to see if Cidr property is set
internal bool IsSetCidr()
{
return this._cidr != null;
}
/// <summary>
/// Gets and sets the property Direction.
/// <para>
/// The direction. The following are possible values:
/// </para>
/// <ul> <li>
/// <para>
/// egress
/// </para>
/// </li> <li>
/// <para>
/// ingress
/// </para>
/// </li> </ul>
/// </summary>
public string Direction
{
get { return this._direction; }
set { this._direction = value; }
}
// Check to see if Direction property is set
internal bool IsSetDirection()
{
return this._direction != null;
}
/// <summary>
/// Gets and sets the property PortRange.
/// <para>
/// The port range.
/// </para>
/// </summary>
public PortRange PortRange
{
get { return this._portRange; }
set { this._portRange = value; }
}
// Check to see if PortRange property is set
internal bool IsSetPortRange()
{
return this._portRange != null;
}
/// <summary>
/// Gets and sets the property PrefixListId.
/// <para>
/// The prefix list ID.
/// </para>
/// </summary>
public string PrefixListId
{
get { return this._prefixListId; }
set { this._prefixListId = value; }
}
// Check to see if PrefixListId property is set
internal bool IsSetPrefixListId()
{
return this._prefixListId != null;
}
/// <summary>
/// Gets and sets the property Protocol.
/// <para>
/// The protocol name.
/// </para>
/// </summary>
public string Protocol
{
get { return this._protocol; }
set { this._protocol = value; }
}
// Check to see if Protocol property is set
internal bool IsSetProtocol()
{
return this._protocol != null;
}
/// <summary>
/// Gets and sets the property SecurityGroupId.
/// <para>
/// The security group ID.
/// </para>
/// </summary>
public string SecurityGroupId
{
get { return this._securityGroupId; }
set { this._securityGroupId = value; }
}
// Check to see if SecurityGroupId property is set
internal bool IsSetSecurityGroupId()
{
return this._securityGroupId != null;
}
}
} |
||||
TheStack | b5a5e18534cf26b926bcd15ae339a14238c193c6 | C#code:C# | {"size": 13279, "ext": "cs", "max_stars_repo_path": "SimpleECS/Generators.cs", "max_stars_repo_name": "DanielGilbert/SimpleECS", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "SimpleECS/Generators.cs", "max_issues_repo_name": "DanielGilbert/SimpleECS", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SimpleECS/Generators.cs", "max_forks_repo_name": "DanielGilbert/SimpleECS", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 59.28125, "max_line_length": 199, "alphanum_fraction": 0.4212666616} | namespace SimpleECS
{
using System.IO;
internal class Generator
{
static string Pattern(string value, int count, bool comma_sep = true)
{
string result = "";
for (int i = 1; i < count; ++i)
{
result += value.Replace("#", i.ToString());
if (comma_sep) result += ", ";
}
result += value.Replace("#", (count).ToString());
return result;
}
/// <summary>
/// Generates the create entity functions to file located at path.
/// Count is the amount of functions to generate
/// </summary>
public static void EntityCreateFunctions(string file_path, int count)
{
using (StreamWriter writer = new StreamWriter(file_path))
{
writer.WriteLine($"namespace {nameof(SimpleECS)}");
writer.WriteLine("{");
writer.WriteLine(" public partial class World");
writer.WriteLine(" {");
for (int i = 1; i <= count; ++i)
{
writer.WriteLine($" public Entity CreateEntity<{Pattern("C#", i)}>({Pattern("in C# c#", i)})");
writer.WriteLine(" {");
writer.WriteLine(" signature.Clear();");
writer.WriteLine($" signature{Pattern(".Add<C#>()", i, false)};");
writer.WriteLine($" return CreateEntityWithArchetype(GetArchetype(signature)){Pattern(".Set(c#)", i, false)};");
writer.WriteLine(" }");
writer.WriteLine("");
}
writer.WriteLine(" }");
writer.WriteLine("}");
}
}
/// <summary>
/// Generates foreach functions for archetypes
/// </summary>
public static void ForeachFunctionsArchetypes(string file_path, int count)
{
using (StreamWriter writer = new StreamWriter(file_path))
{
writer.WriteLine("namespace SimpleECS");
writer.WriteLine("{");
{
writer.WriteLine(" using Delegates;");
writer.WriteLine("");
writer.WriteLine("public partial class World");
writer.WriteLine("{");
{
writer.WriteLine(" public partial class Archetype");
writer.WriteLine(" {");
{
for (int size = 1; size <= count; ++size)
{
writer.WriteLine(" /// <summary>");
writer.WriteLine($" /// Allows iteration of components in archetype, can add up to {count} components");
writer.WriteLine(" /// </summary>");
writer.WriteLine($" public void Foreach<{Pattern("C#", size)}>(in query<{Pattern("C#", size)}> action)");
writer.WriteLine(" {");
writer.WriteLine(" if (entity_count > 0" + Pattern("&& TryGetArray<C#>(out var pool_c#)", size, false) + ")");
writer.WriteLine(" for (int i = entity_count - 1; i >= 0; --i)");
writer.WriteLine($" action({Pattern("ref pool_c#[i]", size)});");
writer.WriteLine(" }");
writer.WriteLine("");
}
for (int size = 1; size <= count; ++size)
{
writer.WriteLine(" /// <summary>");
writer.WriteLine($" /// Allows iteration of components in archetype, can add up to {count} components");
writer.WriteLine(" /// </summary>");
writer.WriteLine($" public void Foreach<{Pattern("C#", size)}>(in {nameof(Delegates.query_e)}<{Pattern("C#", size)}> action)");
writer.WriteLine(" {");
writer.WriteLine(" if (entity_count > 0" + Pattern("&& TryGetArray<C#>(out var pool_c#)", size, false) + ")");
writer.WriteLine(" for (int i = entity_count - 1; i >= 0; --i)");
writer.WriteLine($" action(entity_pool[i], {Pattern("ref pool_c#[i]", size)});");
writer.WriteLine(" }");
writer.WriteLine("");
}
}
writer.WriteLine("}");
}
writer.WriteLine("}");
}
}
}
public static void GenerateQueryFunctions(int data, int comp, string file_path)
{
using (StreamWriter writer = new StreamWriter(file_path))
{
writer.WriteLine(" namespace SimpleECS");
writer.WriteLine("{");
writer.WriteLine(" using Delegates;");
writer.WriteLine(" public partial class Query");
writer.WriteLine(" {");
for (int c = 1; c <= comp; ++c)
{
string c_val = Pattern("C#", c);
WriteDocumentation(writer);
writer.WriteLine($" public void Foreach<{c_val}>(in query_c{c}<{c_val}> query)");
writer.WriteLine(" {");
writer.WriteLine(" Update();");
writer.WriteLine(" if (archetype_count == 0) return;");
writer.WriteLine(" world.AllowStructuralChanges = false;");
writer.WriteLine(" for (int i = archetype_count - 1; i >= 0; --i)");
writer.WriteLine(" {");
writer.WriteLine(" var archetype = matching_archetypes[i];");
var archs = Pattern("&& archetype.TryGetArray(out C#[] pool_c#)", c, false);
writer.WriteLine($" if (archetype.entity_count > 0 {archs})");
writer.WriteLine(" for (int e = archetype.entity_count - 1; e >= 0; --e)");
writer.WriteLine($" query({Pattern("ref pool_c#[e]", c)});");
writer.WriteLine(" }");
writer.WriteLine(" world.AllowStructuralChanges = true;");
writer.WriteLine(" }");
// entity
WriteDocumentation(writer);
writer.WriteLine($" public void Foreach<{c_val}>(in query_ec{c}<{c_val}> query)");
writer.WriteLine(" {");
writer.WriteLine(" Update();");
writer.WriteLine(" if (archetype_count == 0) return;");
writer.WriteLine(" world.AllowStructuralChanges = false;");
writer.WriteLine(" for (int i = archetype_count - 1; i >= 0; --i)");
writer.WriteLine(" {");
writer.WriteLine(" var archetype = matching_archetypes[i];");
writer.WriteLine($" if (archetype.entity_count > 0 {archs})");
writer.WriteLine(" for (int e = archetype.entity_count - 1; e >= 0; --e)");
writer.WriteLine($" query(archetype.entity_pool[e], {Pattern("ref pool_c#[e]", c)});");
writer.WriteLine(" }");
writer.WriteLine(" world.AllowStructuralChanges = true;");
writer.WriteLine(" }");
}
for (int w = 1; w <= data; ++w)
for (int c = 1; c <= comp; ++c)
{
string w_val = Pattern("W#", w);
string c_val = Pattern("C#", c);
WriteDocumentation(writer);
writer.WriteLine($" public void Foreach<{w_val}, {c_val}>(in query_w{w}c{c}<{w_val}, {c_val}> query)");
writer.WriteLine(" {");
writer.WriteLine(" Update();");
writer.WriteLine(" if (archetype_count == 0) return;");
writer.WriteLine(" world.AllowStructuralChanges = false;");
writer.WriteLine(Pattern(" ref var d# = ref world.GetData<W#>(); \n", w, false));
writer.WriteLine(" for (int i = archetype_count - 1; i >= 0; --i)");
writer.WriteLine(" {");
writer.WriteLine(" var archetype = matching_archetypes[i];");
var archs = Pattern("&& archetype.TryGetArray(out C#[] pool_c#)", c, false);
writer.WriteLine($" if (archetype.entity_count > 0 {archs})");
writer.WriteLine(" for (int e = archetype.entity_count - 1; e >= 0; --e)");
writer.WriteLine($" query({Pattern("d#", w)}, {Pattern("ref pool_c#[e]", c)});");
writer.WriteLine(" }");
writer.WriteLine(" world.AllowStructuralChanges = true;");
writer.WriteLine(" }");
// entity
WriteDocumentation(writer);
writer.WriteLine($" public void Foreach<{w_val}, {c_val}>(in query_ew{w}c{c}<{w_val}, {c_val}> query)");
writer.WriteLine(" {");
writer.WriteLine(" Update();");
writer.WriteLine(" if (archetype_count == 0) return;");
writer.WriteLine(" world.AllowStructuralChanges = false;");
writer.WriteLine(Pattern(" ref var d# = ref world.GetData<W#>(); \n", w, false));
writer.WriteLine(" for (int i = archetype_count - 1; i >= 0; --i)");
writer.WriteLine(" {");
writer.WriteLine(" var archetype = matching_archetypes[i];");
writer.WriteLine($" if (archetype.entity_count > 0 {archs})");
writer.WriteLine(" for (int e = archetype.entity_count - 1; e >= 0; --e)");
writer.WriteLine($" query(archetype.entity_pool[e], {Pattern("d#", w)}, {Pattern("ref pool_c#[e]", c)});");
writer.WriteLine(" }");
writer.WriteLine(" world.AllowStructuralChanges = true;");
writer.WriteLine(" }");
}
writer.WriteLine(" }");
writer.WriteLine("");
writer.WriteLine(" namespace Delegates");
writer.WriteLine(" {");
for (int c = 1; c <= comp; ++c)
{
writer.WriteLine($" public delegate void query_c{c}<{Pattern("C#", c)}>({Pattern("ref C# c#", c)});");
writer.WriteLine($" public delegate void query_ec{c}<{Pattern("C#", c)}>(Entity entity, {Pattern("ref C# c#", c)});");
}
for (int w = 1; w <= data; ++w)
for (int c = 1; c <= comp; ++c)
{
writer.WriteLine($" public delegate void query_w{w}c{c}<{Pattern("W#", w)}, {Pattern("C#", c)}>({Pattern("in W# w#", w)}, {Pattern("ref C# c#", c)});");
writer.WriteLine($" public delegate void query_ew{w}c{c}<{Pattern("W#", w)}, {Pattern("C#", c)}>(Entity entity, {Pattern("in W# w#", w)}, {Pattern("ref C# c#", c)});");
}
writer.WriteLine(" }");
writer.WriteLine("}");
}
void WriteDocumentation(StreamWriter writer)
{
writer.WriteLine("/// <summary>");
writer.WriteLine("/// Iterates over entities that matches query.");
writer.WriteLine("/// Add Entity in First position to access Entity.");
writer.WriteLine($"/// Add (in W world_data) to access world data, can add up to {data} world data.");
writer.WriteLine($"/// Add (ref C component) to access entity components, can add up to {comp} components.");
writer.WriteLine("/// </summary>");
}
}
}
} |
||||
TheStack | b5a602312f7edeb8f53373d53e5dfd333214e0c9 | C#code:C# | {"size": 1663, "ext": "cs", "max_stars_repo_path": "Server/Message/GroupMsgReader.cs", "max_stars_repo_name": "Lekashi/LunaMultiplayer", "max_stars_repo_stars_event_min_datetime": "2017-12-12T05:37:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T19:55:12.000Z", "max_issues_repo_path": "Server/Message/GroupMsgReader.cs", "max_issues_repo_name": "Lekashi/LunaMultiplayer", "max_issues_repo_issues_event_min_datetime": "2017-12-13T12:56:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-18T21:58:44.000Z", "max_forks_repo_path": "Server/Message/GroupMsgReader.cs", "max_forks_repo_name": "Lekashi/LunaMultiplayer", "max_forks_repo_forks_event_min_datetime": "2017-12-20T09:06:45.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T05:24:56.000Z"} | {"max_stars_count": 316.0, "max_issues_count": 303.0, "max_forks_count": 179.0, "avg_line_length": 37.7954545455, "max_line_length": 118, "alphanum_fraction": 0.6217678894} | using System.Linq;
using LmpCommon.Message.Data.Groups;
using LmpCommon.Message.Interface;
using LmpCommon.Message.Server;
using LmpCommon.Message.Types;
using Server.Client;
using Server.Context;
using Server.Message.Base;
using Server.Server;
using Server.System;
namespace Server.Message
{
public class GroupMsgReader : ReaderBase
{
public override void HandleMessage(ClientStructure client, IClientMessageBase message)
{
var data = (GroupBaseMsgData)message.Data;
switch (data.GroupMessageType)
{
case GroupMessageType.ListRequest:
var msgData = ServerContext.ServerMessageFactory.CreateNewMessageData<GroupListResponseMsgData>();
msgData.Groups = GroupSystem.Groups.Values.ToArray();
msgData.GroupsCount = msgData.Groups.Length;
MessageQueuer.SendToClient<GroupSrvMsg>(client, msgData);
//We don't use this message anymore so we can recycle it
message.Recycle();
break;
case GroupMessageType.CreateGroup:
GroupSystem.CreateGroup(client.PlayerName, ((GroupCreateMsgData)data).GroupName);
break;
case GroupMessageType.RemoveGroup:
GroupSystem.RemoveGroup(client.PlayerName, ((GroupRemoveMsgData)data).GroupName);
break;
case GroupMessageType.GroupUpdate:
GroupSystem.UpdateGroup(client.PlayerName, ((GroupUpdateMsgData)data).Group);
break;
}
}
}
}
|
||||
TheStack | b5a78d2c953303e65bb2d91a57471c076aa47181 | C#code:C# | {"size": 437, "ext": "cs", "max_stars_repo_path": "src/Microsoft/JSInterop/0.Core/src/Component/ComponentMemberCollectionDefaults.cs", "max_stars_repo_name": "teroneko/Teronis.DotNet", "max_stars_repo_stars_event_min_datetime": "2020-02-10T21:39:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T19:52:24.000Z", "max_issues_repo_path": "src/Microsoft/JSInterop/0.Core/src/Component/ComponentMemberCollectionDefaults.cs", "max_issues_repo_name": "teroneko/Teronis.DotNet", "max_issues_repo_issues_event_min_datetime": "2020-06-12T07:00:34.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-26T14:19:32.000Z", "max_forks_repo_path": "src/Microsoft/JSInterop/0.Core/src/Component/ComponentMemberCollectionDefaults.cs", "max_forks_repo_name": "teroneko/Teronis.DotNet", "max_forks_repo_forks_event_min_datetime": "2020-07-17T01:46:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-09T23:11:34.000Z"} | {"max_stars_count": 30.0, "max_issues_count": 13.0, "max_forks_count": 3.0, "avg_line_length": 29.1333333333, "max_line_length": 101, "alphanum_fraction": 0.7391304348} | // Copyright (c) Teroneko.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Reflection;
namespace Teronis.Microsoft.JSInterop.Component
{
internal class ComponentMemberCollectionDefaults
{
public const BindingFlags COMPONENT_PROPERTY_BINDING_FLAGS = BindingFlags.Instance
| BindingFlags.Public
| BindingFlags.NonPublic;
}
}
|
||||
TheStack | b5a7f75cddf11a47a0a0147113d28e64434d270f | C#code:C# | {"size": 1641, "ext": "cs", "max_stars_repo_path": "src/LinqToSalesforce.VsPlugin2017/Helpers/DteExtensions.cs", "max_stars_repo_name": "forki/LinqToSalesforce", "max_stars_repo_stars_event_min_datetime": "2017-03-02T22:29:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-15T13:08:09.000Z", "max_issues_repo_path": "src/LinqToSalesforce.VsPlugin2017/Helpers/DteExtensions.cs", "max_issues_repo_name": "forki/LinqToSalesforce", "max_issues_repo_issues_event_min_datetime": "2017-03-20T21:49:31.000Z", "max_issues_repo_issues_event_max_datetime": "2018-06-08T19:10:57.000Z", "max_forks_repo_path": "src/LinqToSalesforce.VsPlugin2017/Helpers/DteExtensions.cs", "max_forks_repo_name": "forki/LinqToSalesforce", "max_forks_repo_forks_event_min_datetime": "2016-12-14T20:55:01.000Z", "max_forks_repo_forks_event_max_datetime": "2018-06-06T21:20:52.000Z"} | {"max_stars_count": 15.0, "max_issues_count": 13.0, "max_forks_count": 9.0, "avg_line_length": 28.7894736842, "max_line_length": 113, "alphanum_fraction": 0.5734308349} | using System;
using System.Collections.Generic;
using EnvDTE;
using VSLangProj;
namespace LinqToSalesforce.VsPlugin2017.Helpers
{
public static class DteExtensions
{
public static IEnumerable<Project> GetSolutionProjects(this DTE dte)
{
Projects solutionProjects = dte.Solution.Projects;
foreach (var project in solutionProjects)
{
yield return (Project) project;
}
}
public static Project GetCurrentProject(this DTE dte)
{
var activeSolutionProjects = (Array)dte.ActiveSolutionProjects;
if (activeSolutionProjects.Length <= 0)
return null;
return (Project)activeSolutionProjects.GetValue(0);
}
public static VSProject GetCurrentVsProject(this DTE dte) => GetCurrentProject(dte)?.Object as VSProject;
public static IEnumerable<Reference> GetReferences(this Project project)
{
var vsProject = project?.Object as VSProject;
if (vsProject == null)
yield break;
foreach (var r in vsProject.References)
yield return (Reference)r;
}
public static IEnumerable<ProjectItem> GetProjectFiles(this Project project)
{
if (project == null)
yield break;
foreach (var p in project.Collection)
{
var proj = (Project)p;
foreach (var sp in proj.ProjectItems)
{
yield return (ProjectItem)sp;
}
}
}
}
}
|
||||
TheStack | b5a997b2e5018f92632b0742b4078ff02a616f5a | C#code:C# | {"size": 652, "ext": "cs", "max_stars_repo_path": "CBreeze/UncommonSense.CBreeze.Core/ByteVariable.cs", "max_stars_repo_name": "mprise-indigo/UncommonSense.CBreeze", "max_stars_repo_stars_event_min_datetime": "2018-04-12T09:46:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-29T20:09:52.000Z", "max_issues_repo_path": "CBreeze/UncommonSense.CBreeze.Core/ByteVariable.cs", "max_issues_repo_name": "mprise-indigo/UncommonSense.CBreeze", "max_issues_repo_issues_event_min_datetime": "2018-01-26T20:48:27.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-01T19:02:18.000Z", "max_forks_repo_path": "CBreeze/UncommonSense.CBreeze.Core/ByteVariable.cs", "max_forks_repo_name": "mprise-indigo/UncommonSense.CBreeze", "max_forks_repo_forks_event_min_datetime": "2018-05-18T10:08:27.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-12T08:32:31.000Z"} | {"max_stars_count": 6.0, "max_issues_count": 32.0, "max_forks_count": 4.0, "avg_line_length": 19.1764705882, "max_line_length": 56, "alphanum_fraction": 0.5352760736} | using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using UncommonSense.CBreeze.Common;
namespace UncommonSense.CBreeze.Core
{
public class ByteVariable : Variable, IHasDimensions
{
public ByteVariable(string name) : this(0, name)
{
}
public ByteVariable(int id, string name)
: base(id, name)
{
}
public string Dimensions
{
get;
set;
}
public override VariableType Type
{
get
{
return VariableType.Byte;
}
}
}
} |
||||
TheStack | b5ab572815cdb23abd68b860c163688b9eec4d1f | C#code:C# | {"size": 571, "ext": "cs", "max_stars_repo_path": "INBOUND/App_Code/FormField_Code/FormFieldTextBoxIntSetting.cs", "max_stars_repo_name": "nsadovin/Wilstream", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "INBOUND/App_Code/FormField_Code/FormFieldTextBoxIntSetting.cs", "max_issues_repo_name": "nsadovin/Wilstream", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "INBOUND/App_Code/FormField_Code/FormFieldTextBoxIntSetting.cs", "max_forks_repo_name": "nsadovin/Wilstream", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 30.0526315789, "max_line_length": 260, "alphanum_fraction": 0.7478108581} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
/// <summary>
/// Сводное описание для FormFieldTextBoxPhoneSetting
/// </summary>
public class FormFieldTextBoxIntSetting
{
public FormFieldTextBoxIntSetting()
{
//
// TODO: добавьте логику конструктора
//
}
//<?xml version="1.0" encoding="utf-16"?><FormFieldTextBoxPhoneSetting xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><DefaultAon>false</DefaultAon><Format>999-9999</Format></FormFieldTextBoxPhoneSetting>
} |
||||
TheStack | b5ac4269e63e704620c49bb8dac576093963fefc | C#code:C# | {"size": 689, "ext": "cs", "max_stars_repo_path": "IMDBConsumer/IMDBConsumer.Web.Dto/Token.cs", "max_stars_repo_name": "TheArchitect123/UWP-Wpf-Apps", "max_stars_repo_stars_event_min_datetime": "2020-10-27T16:24:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-27T16:24:33.000Z", "max_issues_repo_path": "IMDBConsumer/IMDBConsumer.Web.Dto/Token.cs", "max_issues_repo_name": "TheArchitect123/UWP-Wpf-Apps", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "IMDBConsumer/IMDBConsumer.Web.Dto/Token.cs", "max_forks_repo_name": "TheArchitect123/UWP-Wpf-Apps", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 29.9565217391, "max_line_length": 112, "alphanum_fraction": 0.6269956459} | using System;
namespace IMDBConsumer.Web.Dto
{
/// <summary>
/// Holds the access information required in order to authenticate
/// </summary>
public class Token
{
//Access Token Information
public string accessToken { get; set; }
public string refreshToken { get; set; }
public string authorizationHeader { get; set; }
//Expiration -- If Expired make sure to regenerate this object through the app, to avoid login redirects
public DateTime expiresOnUtc { get; set; }
public string userId { get; set; }
public string firstName { get; set; }
public string lastName { get; set; }
}
}
|
||||
TheStack | b5ad217e4a2d935ce56e44cce4c841009a2bb1df | C#code:C# | {"size": 49703, "ext": "cs", "max_stars_repo_path": "src/Features/Core/Portable/EditAndContinue/EditSession.cs", "max_stars_repo_name": "dustincoleman/roslyn", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Features/Core/Portable/EditAndContinue/EditSession.cs", "max_issues_repo_name": "dustincoleman/roslyn", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Features/Core/Portable/EditAndContinue/EditSession.cs", "max_forks_repo_name": "dustincoleman/roslyn", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 49.3574975174, "max_line_length": 216, "alphanum_fraction": 0.5801460676} | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Debugging;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.EditAndContinue
{
internal sealed class EditSession : IDisposable
{
private readonly CancellationTokenSource _cancellationSource = new CancellationTokenSource();
internal readonly DebuggingSession DebuggingSession;
internal readonly EditSessionTelemetry Telemetry;
/// <summary>
/// The solution captured when entering the break state.
/// </summary>
internal readonly Solution BaseSolution;
private readonly ImmutableDictionary<ActiveMethodId, ImmutableArray<NonRemappableRegion>> _nonRemappableRegions;
/// <summary>
/// Lazily calculated map of base active statements.
/// </summary>
internal readonly AsyncLazy<ActiveStatementsMap> BaseActiveStatements;
/// <summary>
/// For each base active statement the exception regions around that statement.
/// </summary>
internal readonly AsyncLazy<ImmutableArray<ActiveStatementExceptionRegions>> BaseActiveExceptionRegions;
/// <summary>
/// Results of changed documents analysis.
/// The work is triggered by an incremental analyzer on idle or explicitly when "continue" operation is executed.
/// Contains analyses of the latest observed document versions.
/// </summary>
private readonly Dictionary<DocumentId, (Document Document, AsyncLazy<DocumentAnalysisResults> Results)> _analyses
= new Dictionary<DocumentId, (Document, AsyncLazy<DocumentAnalysisResults>)>();
private readonly object _analysesGuard = new object();
/// <summary>
/// Errors to be reported when a project is updated but the corresponding module does not support EnC.
///
/// The capability of a module to apply edits may change during edit session if the user attaches debugger to
/// an additional process that doesn't support EnC (or detaches from such process). The diagnostic reflects
/// the state of the module when queried for the first time. Before we actually apply an edit to the module
/// we need to query again instead of just reusing the diagnostic.
/// </summary>
private readonly Dictionary<Guid, ImmutableArray<LocationlessDiagnostic>> _moduleDiagnostics
= new Dictionary<Guid, ImmutableArray<LocationlessDiagnostic>>();
private readonly object _moduleDiagnosticsGuard = new object();
/// <summary>
/// A <see cref="DocumentId"/> is added whenever <see cref="EditAndContinueDiagnosticAnalyzer"/> reports
/// rude edits or module diagnostics. At the end of the session we ask the diagnostic analyzer to reanalyze
/// the documents to clean up the diagnostics.
/// </summary>
private readonly HashSet<DocumentId> _documentsWithReportedDiagnostics = new HashSet<DocumentId>();
private readonly object _documentsWithReportedDiagnosticsGuard = new object();
private bool _changesApplied;
internal EditSession(DebuggingSession debuggingSession, EditSessionTelemetry telemetry)
{
Debug.Assert(debuggingSession != null);
Debug.Assert(telemetry != null);
DebuggingSession = debuggingSession;
_nonRemappableRegions = debuggingSession.NonRemappableRegions;
Telemetry = telemetry;
BaseSolution = debuggingSession.LastCommittedSolution;
BaseActiveStatements = new AsyncLazy<ActiveStatementsMap>(GetBaseActiveStatementsAsync, cacheResult: true);
BaseActiveExceptionRegions = new AsyncLazy<ImmutableArray<ActiveStatementExceptionRegions>>(GetBaseActiveExceptionRegionsAsync, cacheResult: true);
}
internal CancellationToken CancellationToken => _cancellationSource.Token;
internal void Cancel() => _cancellationSource.Cancel();
public void Dispose()
{
_cancellationSource.Dispose();
}
internal void ModuleInstanceLoadedOrUnloaded(Guid mvid)
{
// invalidate diagnostic cache for the module:
lock (_moduleDiagnosticsGuard)
{
_moduleDiagnostics.Remove(mvid);
}
}
public ImmutableArray<LocationlessDiagnostic> GetModuleDiagnostics(Guid mvid, string projectDisplayName)
{
ImmutableArray<LocationlessDiagnostic> result;
lock (_moduleDiagnosticsGuard)
{
if (_moduleDiagnostics.TryGetValue(mvid, out result))
{
return result;
}
}
var newResult = ImmutableArray<LocationlessDiagnostic>.Empty;
if (!DebuggingSession.DebugeeModuleMetadataProvider.IsEditAndContinueAvailable(mvid, out var errorCode, out var localizedMessage))
{
var descriptor = EditAndContinueDiagnosticDescriptors.GetModuleDiagnosticDescriptor(errorCode);
newResult = ImmutableArray.Create(new LocationlessDiagnostic(descriptor, new[] { projectDisplayName, localizedMessage }));
}
lock (_moduleDiagnosticsGuard)
{
if (!_moduleDiagnostics.TryGetValue(mvid, out result))
{
_moduleDiagnostics.Add(mvid, result = newResult);
}
}
return result;
}
private Project GetBaseProject(ProjectId id)
=> BaseSolution.GetProject(id);
private async Task<ActiveStatementsMap> GetBaseActiveStatementsAsync(CancellationToken cancellationToken)
{
try
{
return CreateActiveStatementsMap(BaseSolution, await DebuggingSession.ActiveStatementProvider.GetActiveStatementsAsync(cancellationToken).ConfigureAwait(false));
}
catch (Exception e) when (FatalError.ReportWithoutCrashUnlessCanceled(e))
{
return new ActiveStatementsMap(
SpecializedCollections.EmptyReadOnlyDictionary<DocumentId, ImmutableArray<ActiveStatement>>(),
SpecializedCollections.EmptyReadOnlyDictionary<ActiveInstructionId, ActiveStatement>());
}
}
private ActiveStatementsMap CreateActiveStatementsMap(Solution solution, ImmutableArray<ActiveStatementDebugInfo> debugInfos)
{
var byDocument = PooledDictionary<DocumentId, ArrayBuilder<ActiveStatement>>.GetInstance();
var byInstruction = PooledDictionary<ActiveInstructionId, ActiveStatement>.GetInstance();
bool supportsEditAndContinue(DocumentId documentId)
=> EditAndContinueWorkspaceService.SupportsEditAndContinue(solution.GetProject(documentId.ProjectId));
foreach (var debugInfo in debugInfos)
{
var documentName = debugInfo.DocumentNameOpt;
if (documentName == null)
{
// Ignore active statements that do not have a source location.
continue;
}
var documentIds = solution.GetDocumentIdsWithFilePath(documentName);
var firstDocumentId = documentIds.FirstOrDefault(supportsEditAndContinue);
if (firstDocumentId == null)
{
// Ignore active statements that don't belong to the solution or language that supports EnC service.
continue;
}
if (!byDocument.TryGetValue(firstDocumentId, out var primaryDocumentActiveStatements))
{
byDocument.Add(firstDocumentId, primaryDocumentActiveStatements = ArrayBuilder<ActiveStatement>.GetInstance());
}
var activeStatement = new ActiveStatement(
ordinal: byInstruction.Count,
primaryDocumentOrdinal: primaryDocumentActiveStatements.Count,
documentIds: documentIds,
flags: debugInfo.Flags,
span: GetUpToDateSpan(debugInfo),
instructionId: debugInfo.InstructionId,
threadIds: debugInfo.ThreadIds);
primaryDocumentActiveStatements.Add(activeStatement);
// TODO: associate only those documents that are from a project with the right module id
// https://github.com/dotnet/roslyn/issues/24320
for (var i = 1; i < documentIds.Length; i++)
{
var documentId = documentIds[i];
if (!supportsEditAndContinue(documentId))
{
continue;
}
if (!byDocument.TryGetValue(documentId, out var linkedDocumentActiveStatements))
{
byDocument.Add(documentId, linkedDocumentActiveStatements = ArrayBuilder<ActiveStatement>.GetInstance());
}
linkedDocumentActiveStatements.Add(activeStatement);
}
try
{
byInstruction.Add(debugInfo.InstructionId, activeStatement);
}
catch (ArgumentException)
{
throw new InvalidOperationException($"Multiple active statements with the same instruction id returned by " +
$"{DebuggingSession.ActiveStatementProvider.GetType()}.{nameof(IActiveStatementProvider.GetActiveStatementsAsync)}");
}
}
return new ActiveStatementsMap(byDocument.ToDictionaryAndFree(), byInstruction.ToDictionaryAndFree());
}
private LinePositionSpan GetUpToDateSpan(ActiveStatementDebugInfo activeStatementInfo)
{
if ((activeStatementInfo.Flags & ActiveStatementFlags.MethodUpToDate) != 0)
{
return activeStatementInfo.LinePositionSpan;
}
// Map active statement spans in non-remappable regions to the latest source locations.
if (_nonRemappableRegions.TryGetValue(activeStatementInfo.InstructionId.MethodId, out var regionsInMethod))
{
foreach (var region in regionsInMethod)
{
if (region.Span.Contains(activeStatementInfo.LinePositionSpan))
{
return activeStatementInfo.LinePositionSpan.AddLineDelta(region.LineDelta);
}
}
}
// The active statement is in a method that's not up-to-date but the active span have not changed.
// We only add changed spans to non-remappable regions map, so we won't find unchanged span there.
// Return the original span.
return activeStatementInfo.LinePositionSpan;
}
private async Task<ImmutableArray<ActiveStatementExceptionRegions>> GetBaseActiveExceptionRegionsAsync(CancellationToken cancellationToken)
{
try
{
var baseActiveStatements = await BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false);
var instructionMap = baseActiveStatements.InstructionMap;
using var builderDisposer = ArrayBuilder<ActiveStatementExceptionRegions>.GetInstance(instructionMap.Count, out var builder);
builder.Count = instructionMap.Count;
foreach (var activeStatement in instructionMap.Values)
{
var document = BaseSolution.GetDocument(activeStatement.PrimaryDocumentId);
var sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
var syntaxRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var analyzer = document.Project.LanguageServices.GetService<IEditAndContinueAnalyzer>();
var exceptionRegions = analyzer.GetExceptionRegions(sourceText, syntaxRoot, activeStatement.Span, activeStatement.IsNonLeaf, out var isCovered);
builder[activeStatement.Ordinal] = new ActiveStatementExceptionRegions(exceptionRegions, isCovered);
}
return builder.ToImmutable();
}
catch (Exception e) when (FatalError.ReportWithoutCrashUnlessCanceled(e))
{
return ImmutableArray<ActiveStatementExceptionRegions>.Empty;
}
}
private ImmutableArray<(DocumentId DocumentId, AsyncLazy<DocumentAnalysisResults> Results)> GetChangedDocumentsAnalyses(Project baseProject, Project project)
{
var changes = project.GetChanges(baseProject);
var changedDocuments =
changes.GetChangedDocuments().
Concat(changes.GetAddedDocuments()).
Select(id => project.GetDocument(id)).
Where(d => !EditAndContinueWorkspaceService.IsDesignTimeOnlyDocument(d)).
ToArray();
if (changedDocuments.Length == 0)
{
return ImmutableArray<(DocumentId, AsyncLazy<DocumentAnalysisResults>)>.Empty;
}
lock (_analysesGuard)
{
return changedDocuments.SelectAsArray(d => (d.Id, GetDocumentAnalysisNoLock(d)));
}
}
private async Task<HashSet<ISymbol>> GetAllAddedSymbolsAsync(Project project, CancellationToken cancellationToken)
{
try
{
(Document Document, AsyncLazy<DocumentAnalysisResults> Results)[] analyses;
lock (_analysesGuard)
{
analyses = _analyses.Values.ToArray();
}
HashSet<ISymbol> addedSymbols = null;
foreach (var (document, lazyResults) in analyses)
{
// Only consider analyses for documents that belong the currently analyzed project.
if (document.Project == project)
{
var results = await lazyResults.GetValueAsync(cancellationToken).ConfigureAwait(false);
if (!results.HasChangesAndErrors)
{
foreach (var edit in results.SemanticEdits)
{
if (edit.Kind == SemanticEditKind.Insert)
{
if (addedSymbols == null)
{
addedSymbols = new HashSet<ISymbol>();
}
addedSymbols.Add(edit.NewSymbol);
}
}
}
}
}
return addedSymbols;
}
catch (Exception e) when (FatalError.ReportWithoutCrashUnlessCanceledAndPropagate(e))
{
throw ExceptionUtilities.Unreachable;
}
}
public AsyncLazy<DocumentAnalysisResults> GetDocumentAnalysis(Document document)
{
lock (_analysesGuard)
{
return GetDocumentAnalysisNoLock(document);
}
}
private AsyncLazy<DocumentAnalysisResults> GetDocumentAnalysisNoLock(Document document)
{
if (_analyses.TryGetValue(document.Id, out var analysis) && analysis.Document == document)
{
return analysis.Results;
}
var analyzer = document.Project.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>();
var lazyResults = new AsyncLazy<DocumentAnalysisResults>(
asynchronousComputeFunction: async cancellationToken =>
{
try
{
var baseActiveStatements = await BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false);
if (!baseActiveStatements.DocumentMap.TryGetValue(document.Id, out var documentBaseActiveStatements))
{
documentBaseActiveStatements = ImmutableArray<ActiveStatement>.Empty;
}
var trackingService = BaseSolution.Workspace.Services.GetService<IActiveStatementTrackingService>();
var baseProject = GetBaseProject(document.Project.Id);
return await analyzer.AnalyzeDocumentAsync(baseProject, documentBaseActiveStatements, document, trackingService, cancellationToken).ConfigureAwait(false);
}
catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
},
cacheResult: true);
_analyses[document.Id] = (document, lazyResults);
return lazyResults;
}
internal ImmutableArray<DocumentId> GetDocumentsWithReportedDiagnostics()
{
lock (_documentsWithReportedDiagnosticsGuard)
{
return ImmutableArray.CreateRange(_documentsWithReportedDiagnostics);
}
}
internal void TrackDocumentWithReportedDiagnostics(DocumentId documentId)
{
lock (_documentsWithReportedDiagnosticsGuard)
{
_documentsWithReportedDiagnostics.Add(documentId);
}
}
/// <summary>
/// Determines the status of projects containing given <paramref name="sourceFilePath"/> or the entire solution if <paramref name="sourceFilePath"/> is null.
/// Invoked by the debugger on every step. It is critical for stepping performance that this method returns as fast as possible in absence of changes.
/// </summary>
public async Task<SolutionUpdateStatus> GetSolutionUpdateStatusAsync(Solution solution, string sourceFilePath, CancellationToken cancellationToken)
{
try
{
if (_changesApplied)
{
return SolutionUpdateStatus.None;
}
if (BaseSolution == solution)
{
return SolutionUpdateStatus.None;
}
var projects = (sourceFilePath == null) ? solution.Projects :
from documentId in solution.GetDocumentIdsWithFilePath(sourceFilePath)
select solution.GetDocument(documentId).Project;
bool anyChanges = false;
foreach (var project in projects)
{
if (!EditAndContinueWorkspaceService.SupportsEditAndContinue(project))
{
continue;
}
var baseProject = GetBaseProject(project.Id);
// When debugging session is started some projects might not have been loaded to the workspace yet.
// We capture the base solution. Edits in files that are in projects that haven't been loaded won't be applied
// and will result in source mismatch when the user steps into them.
//
// TODO (https://github.com/dotnet/roslyn/issues/1204):
// hook up the debugger reported error, check that the project has not been loaded and report a better error.
// Here, we assume these projects are not modified.
if (baseProject == null)
{
EditAndContinueWorkspaceService.Log.Write("EnC state of '{0}' [0x{1:X8}] queried: project not loaded", project.Id.DebugName, project.Id);
continue;
}
var changedDocumentAnalyses = GetChangedDocumentsAnalyses(baseProject, project);
if (changedDocumentAnalyses.Length == 0)
{
continue;
}
var projectSummary = await GetProjectAnalysisSymmaryAsync(changedDocumentAnalyses, cancellationToken).ConfigureAwait(false);
if (projectSummary == ProjectAnalysisSummary.ValidChanges)
{
var (mvid, _) = await DebuggingSession.GetProjectModuleIdAsync(baseProject.Id, cancellationToken).ConfigureAwait(false);
if (mvid == Guid.Empty)
{
// project not built
EditAndContinueWorkspaceService.Log.Write("EnC state of '{0}' [0x{1:X8}] queried: project not built", project.Id.DebugName, project.Id);
continue;
}
if (!GetModuleDiagnostics(mvid, project.Name).IsEmpty)
{
EditAndContinueWorkspaceService.Log.Write("EnC state of '{0}' [0x{1:X8}] queried: module blocking EnC", project.Id.DebugName, project.Id);
return SolutionUpdateStatus.Blocked;
}
}
EditAndContinueWorkspaceService.Log.Write("EnC state of '{0}' [0x{1:X8}] queried: {2}", project.Id.DebugName, project.Id, projectSummary);
switch (projectSummary)
{
case ProjectAnalysisSummary.NoChanges:
continue;
case ProjectAnalysisSummary.CompilationErrors:
case ProjectAnalysisSummary.RudeEdits:
return SolutionUpdateStatus.Blocked;
case ProjectAnalysisSummary.ValidChanges:
case ProjectAnalysisSummary.ValidInsignificantChanges:
anyChanges = true;
continue;
default:
throw ExceptionUtilities.UnexpectedValue(projectSummary);
}
}
return anyChanges ? SolutionUpdateStatus.Ready : SolutionUpdateStatus.None;
}
catch (Exception e) when (FatalError.ReportWithoutCrashUnlessCanceledAndPropagate(e))
{
throw ExceptionUtilities.Unreachable;
}
}
private async Task<ProjectAnalysisSummary> GetProjectAnalysisSymmaryAsync(
ImmutableArray<(DocumentId DocumentId, AsyncLazy<DocumentAnalysisResults> Results)> documentAnalyses,
CancellationToken cancellationToken)
{
bool hasChanges = false;
bool hasSignificantValidChanges = false;
foreach (var analysis in documentAnalyses)
{
var result = await analysis.Results.GetValueAsync(cancellationToken).ConfigureAwait(false);
// skip documents that actually were not changed:
if (!result.HasChanges)
{
continue;
}
// rude edit detection wasn't completed due to errors in compilation:
if (result.HasChangesAndCompilationErrors)
{
return ProjectAnalysisSummary.CompilationErrors;
}
// rude edits detected:
if (!result.RudeEditErrors.IsEmpty)
{
return ProjectAnalysisSummary.RudeEdits;
}
hasChanges = true;
hasSignificantValidChanges |= result.HasSignificantValidChanges;
}
if (!hasChanges)
{
// we get here if a document is closed and reopen without any actual change:
return ProjectAnalysisSummary.NoChanges;
}
if (!hasSignificantValidChanges)
{
return ProjectAnalysisSummary.ValidInsignificantChanges;
}
return ProjectAnalysisSummary.ValidChanges;
}
private static async Task<ProjectChanges> GetProjectChangesAsync(ImmutableArray<(DocumentId Document, AsyncLazy<DocumentAnalysisResults> Results)> changedDocumentAnalyses, CancellationToken cancellationToken)
{
try
{
var allEdits = ArrayBuilder<SemanticEdit>.GetInstance();
var allLineEdits = ArrayBuilder<(DocumentId, ImmutableArray<LineChange>)>.GetInstance();
var activeStatementsInChangedDocuments = ArrayBuilder<(DocumentId, ImmutableArray<ActiveStatement>, ImmutableArray<ImmutableArray<LinePositionSpan>>)>.GetInstance();
foreach (var (documentId, asyncResult) in changedDocumentAnalyses)
{
var result = await asyncResult.GetValueAsync(cancellationToken).ConfigureAwait(false);
if (!result.HasSignificantValidChanges)
{
continue;
}
// we shouldn't be asking for deltas in presence of errors:
Debug.Assert(!result.HasChangesAndErrors);
allEdits.AddRange(result.SemanticEdits);
if (result.LineEdits.Length > 0)
{
allLineEdits.Add((documentId, result.LineEdits));
}
if (result.ActiveStatements.Length > 0)
{
activeStatementsInChangedDocuments.Add((documentId, result.ActiveStatements, result.ExceptionRegions));
}
}
return new ProjectChanges(allEdits.ToImmutableAndFree(), allLineEdits.ToImmutableAndFree(), activeStatementsInChangedDocuments.ToImmutableAndFree());
}
catch (Exception e) when (FatalError.ReportWithoutCrashUnlessCanceledAndPropagate(e))
{
throw ExceptionUtilities.Unreachable;
}
}
internal ImmutableArray<LocationlessDiagnostic> GetDebugeeStateDiagnostics()
{
return ImmutableArray<LocationlessDiagnostic>.Empty;
}
public async Task<SolutionUpdate> EmitSolutionUpdateAsync(Solution solution, CancellationToken cancellationToken)
{
var deltas = ArrayBuilder<Deltas>.GetInstance();
var emitBaselines = ArrayBuilder<(ProjectId, EmitBaseline)>.GetInstance();
var readers = ArrayBuilder<IDisposable>.GetInstance();
var diagnostics = ArrayBuilder<(ProjectId, ImmutableArray<Diagnostic>)>.GetInstance();
try
{
bool isBlocked = false;
foreach (var project in solution.Projects)
{
if (!EditAndContinueWorkspaceService.SupportsEditAndContinue(project))
{
continue;
}
var baseProject = GetBaseProject(project.Id);
// TODO (https://github.com/dotnet/roslyn/issues/1204):
// When debugging session is started some projects might not have been loaded to the workspace yet.
// We capture the base solution. Edits in files that are in projects that haven't been loaded won't be applied
// and will result in source mismatch when the user steps into them.
// TODO: hook up the debugger reported error, check that the project has not been loaded and report a better error.
// Here, we assume these projects are not modified.
if (baseProject == null)
{
EditAndContinueWorkspaceService.Log.Write("Emitting update of '{0}' [0x{1:X8}]: project not loaded", project.Id.DebugName, project.Id);
continue;
}
var (mvid, mvidReadError) = await DebuggingSession.GetProjectModuleIdAsync(project.Id, cancellationToken).ConfigureAwait(false);
if (mvid == Guid.Empty && mvidReadError == null)
{
EditAndContinueWorkspaceService.Log.Write("Emitting update of '{0}' [0x{1:X8}]: project not built", project.Id.DebugName, project.Id);
continue;
}
var changedDocumentAnalyses = GetChangedDocumentsAnalyses(baseProject, project);
var projectSummary = await GetProjectAnalysisSymmaryAsync(changedDocumentAnalyses, cancellationToken).ConfigureAwait(false);
if (projectSummary != ProjectAnalysisSummary.ValidChanges)
{
Telemetry.LogProjectAnalysisSummary(projectSummary, ImmutableArray<string>.Empty);
if (projectSummary == ProjectAnalysisSummary.CompilationErrors || projectSummary == ProjectAnalysisSummary.RudeEdits)
{
isBlocked = true;
}
continue;
}
if (mvidReadError != null)
{
// The error hasn't been reported by GetDocumentDiagnosticsAsync since it might have been intermittent.
// The MVID is required for emit so we consider the error permanent and report it here.
diagnostics.Add((project.Id, ImmutableArray.Create(mvidReadError)));
Telemetry.LogProjectAnalysisSummary(projectSummary, ImmutableArray.Create(mvidReadError.Descriptor.Id));
isBlocked = true;
continue;
}
var moduleDiagnostics = GetModuleDiagnostics(mvid, project.Name);
if (!moduleDiagnostics.IsEmpty)
{
Telemetry.LogProjectAnalysisSummary(projectSummary, moduleDiagnostics.SelectAsArray(d => d.Descriptor.Id));
isBlocked = true;
continue;
}
var projectChanges = await GetProjectChangesAsync(changedDocumentAnalyses, cancellationToken).ConfigureAwait(false);
var currentCompilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false);
var allAddedSymbols = await GetAllAddedSymbolsAsync(project, cancellationToken).ConfigureAwait(false);
var baseActiveStatements = await BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false);
var baseActiveExceptionRegions = await BaseActiveExceptionRegions.GetValueAsync(cancellationToken).ConfigureAwait(false);
var lineEdits = projectChanges.LineChanges.SelectAsArray((lineChange, p) => (p.GetDocument(lineChange.DocumentId).FilePath, lineChange.Changes), project);
// Dispatch to a background thread - the compiler reads symbols and ISymUnmanagedReader requires MTA thread.
// We also don't want to block the UI thread - emit might perform IO.
if (Thread.CurrentThread.GetApartmentState() != ApartmentState.MTA)
{
await Task.Factory.SafeStartNew(Emit, cancellationToken, TaskScheduler.Default).ConfigureAwait(false);
}
else
{
Emit();
}
void Emit()
{
Debug.Assert(Thread.CurrentThread.GetApartmentState() == ApartmentState.MTA, "SymReader requires MTA");
var baseline = DebuggingSession.GetOrCreateEmitBaseline(project.Id, mvid);
// The metadata blob is guaranteed to not be disposed while "continue" operation is being executed.
// If it is disposed it means it had been disposed when "continue" operation started.
if (baseline == null || baseline.OriginalMetadata.IsDisposed)
{
// If we have no baseline the module has not been loaded yet.
// We need to create the baseline from compiler outputs.
var outputs = DebuggingSession.CompilationOutputsProvider.GetCompilationOutputs(project.Id);
if (CreateInitialBaselineForDeferredModuleUpdate(outputs, out var createBaselineDiagnostics, out baseline, out var debugInfoReaderProvider, out var metadataReaderProvider))
{
readers.Add(metadataReaderProvider);
readers.Add(debugInfoReaderProvider);
}
else
{
diagnostics.Add((project.Id, createBaselineDiagnostics));
Telemetry.LogProjectAnalysisSummary(projectSummary, createBaselineDiagnostics);
isBlocked = true;
return;
}
}
EditAndContinueWorkspaceService.Log.Write("Emitting update of '{0}' [0x{1:X8}]", project.Id.DebugName, project.Id);
using var pdbStream = SerializableBytes.CreateWritableStream();
using var metadataStream = SerializableBytes.CreateWritableStream();
using var ilStream = SerializableBytes.CreateWritableStream();
var updatedMethods = ImmutableArray.CreateBuilder<MethodDefinitionHandle>();
var emitResult = currentCompilation.EmitDifference(
baseline,
projectChanges.SemanticEdits,
s => allAddedSymbols?.Contains(s) ?? false,
metadataStream,
ilStream,
pdbStream,
updatedMethods,
cancellationToken);
if (emitResult.Success)
{
var updatedMethodTokens = updatedMethods.SelectAsArray(h => MetadataTokens.GetToken(h));
// Determine all active statements whose span changed and exception region span deltas.
GetActiveStatementAndExceptionRegionSpans(
mvid,
baseActiveStatements,
baseActiveExceptionRegions,
updatedMethodTokens,
_nonRemappableRegions,
projectChanges.NewActiveStatements,
out var activeStatementsInUpdatedMethods,
out var nonRemappableRegions);
deltas.Add(new Deltas(
mvid,
ilStream.ToImmutableArray(),
metadataStream.ToImmutableArray(),
pdbStream.ToImmutableArray(),
updatedMethodTokens,
lineEdits,
nonRemappableRegions,
activeStatementsInUpdatedMethods));
emitBaselines.Add((project.Id, emitResult.Baseline));
}
else
{
// error
isBlocked = true;
}
// TODO: https://github.com/dotnet/roslyn/issues/36061
// We should only report diagnostics from emit phase.
// Syntax and semantic diagnostics are already reported by the diagnostic analyzer.
// Currently we do not have means to distinguish between diagnostics reported from compilation and emit phases.
// Querying diagnostics of the entire compilation or just the updated files migth be slow.
// In fact, it is desirable to allow emitting deltas for symbols affected by the change while allowing untouched
// method bodies to have errors.
diagnostics.Add((project.Id, emitResult.Diagnostics));
Telemetry.LogProjectAnalysisSummary(projectSummary, emitResult.Diagnostics);
}
}
if (isBlocked)
{
deltas.Free();
emitBaselines.Free();
foreach (var reader in readers)
{
reader.Dispose();
}
readers.Free();
return SolutionUpdate.Blocked(diagnostics.ToImmutableAndFree());
}
return new SolutionUpdate(
(deltas.Count > 0) ? SolutionUpdateStatus.Ready : SolutionUpdateStatus.None,
deltas.ToImmutableAndFree(),
readers.ToImmutableAndFree(),
emitBaselines.ToImmutableAndFree(),
diagnostics.ToImmutableAndFree());
}
catch (Exception e) when (FatalError.ReportWithoutCrashUnlessCanceledAndPropagate(e))
{
throw ExceptionUtilities.Unreachable;
}
}
private static unsafe bool CreateInitialBaselineForDeferredModuleUpdate(
CompilationOutputs compilationOutputs,
out ImmutableArray<Diagnostic> diagnostics,
out EmitBaseline baseline,
out DebugInformationReaderProvider debugInfoReaderProvider,
out MetadataReaderProvider metadataReaderProvider)
{
// Since the module has not been loaded to the debuggee the debugger does not have its metadata or symbols available yet.
// Read the metadata and symbols from the disk. Close the files as soon as we are done emitting the delta to minimize
// the time when they are being locked. Since we need to use the baseline that is produced by delta emit for the subsequent
// delta emit we need to keep the module metadata and symbol info backing the symbols of the baseline alive in memory.
// Alternatively, we could drop the data once we are done with emitting the delta and re-emit the baseline again
// when we need it next time and the module is loaded.
diagnostics = default;
baseline = null;
debugInfoReaderProvider = null;
metadataReaderProvider = null;
bool success = false;
string fileBeingRead = compilationOutputs.PdbDisplayPath;
try
{
debugInfoReaderProvider = compilationOutputs.OpenPdb();
if (debugInfoReaderProvider == null)
{
throw new FileNotFoundException();
}
var debugInfoReader = debugInfoReaderProvider.CreateEditAndContinueMethodDebugInfoReader();
fileBeingRead = compilationOutputs.AssemblyDisplayPath;
metadataReaderProvider = compilationOutputs.OpenAssemblyMetadata(prefetch: true);
if (metadataReaderProvider == null)
{
throw new FileNotFoundException();
}
var metadataReader = metadataReaderProvider.GetMetadataReader();
var moduleMetadata = ModuleMetadata.CreateFromMetadata((IntPtr)metadataReader.MetadataPointer, metadataReader.MetadataLength);
baseline = EmitBaseline.CreateInitialBaseline(
moduleMetadata,
debugInfoReader.GetDebugInfo,
debugInfoReader.GetLocalSignature,
debugInfoReader.IsPortable);
success = true;
}
catch (Exception e)
{
var descriptor = EditAndContinueDiagnosticDescriptors.GetDescriptor(EditAndContinueErrorCode.ErrorReadingFile);
diagnostics = ImmutableArray.Create(Diagnostic.Create(descriptor, Location.None, new[] { fileBeingRead, e.Message }));
}
finally
{
if (!success)
{
debugInfoReaderProvider?.Dispose();
metadataReaderProvider?.Dispose();
}
}
return success;
}
// internal for testing
internal static void GetActiveStatementAndExceptionRegionSpans(
Guid moduleId,
ActiveStatementsMap baseActiveStatements,
ImmutableArray<ActiveStatementExceptionRegions> baseActiveExceptionRegions,
ImmutableArray<int> updatedMethodTokens,
ImmutableDictionary<ActiveMethodId, ImmutableArray<NonRemappableRegion>> previousNonRemappableRegions,
ImmutableArray<(DocumentId DocumentId, ImmutableArray<ActiveStatement> ActiveStatements, ImmutableArray<ImmutableArray<LinePositionSpan>> ExceptionRegions)> newActiveStatementsInChangedDocuments,
out ImmutableArray<(Guid ThreadId, ActiveInstructionId OldInstructionId, LinePositionSpan NewSpan)> activeStatementsInUpdatedMethods,
out ImmutableArray<(ActiveMethodId Method, NonRemappableRegion Region)> nonRemappableRegions)
{
var changedNonRemappableSpans = PooledDictionary<(int MethodToken, int MethodVersion, LinePositionSpan BaseSpan), LinePositionSpan>.GetInstance();
var activeStatementsInUpdatedMethodsBuilder = ArrayBuilder<(Guid, ActiveInstructionId, LinePositionSpan)>.GetInstance();
var nonRemappableRegionsBuilder = ArrayBuilder<(ActiveMethodId Method, NonRemappableRegion Region)>.GetInstance();
// Process active statements and their exception regions in changed documents of this project/module:
foreach (var (documentId, newActiveStatements, newExceptionRegions) in newActiveStatementsInChangedDocuments)
{
var oldActiveStatements = baseActiveStatements.DocumentMap[documentId];
Debug.Assert(oldActiveStatements.Length == newActiveStatements.Length);
Debug.Assert(newActiveStatements.Length == newExceptionRegions.Length);
for (var i = 0; i < newActiveStatements.Length; i++)
{
var oldActiveStatement = oldActiveStatements[i];
var newActiveStatement = newActiveStatements[i];
var oldInstructionId = oldActiveStatement.InstructionId;
var methodToken = oldInstructionId.MethodId.Token;
var methodVersion = oldInstructionId.MethodId.Version;
var isMethodUpdated = updatedMethodTokens.Contains(methodToken);
if (isMethodUpdated)
{
foreach (var threadId in oldActiveStatement.ThreadIds)
{
activeStatementsInUpdatedMethodsBuilder.Add((threadId, oldInstructionId, newActiveStatement.Span));
}
}
void AddNonRemappableRegion(LinePositionSpan oldSpan, LinePositionSpan newSpan, bool isExceptionRegion)
{
if (oldActiveStatement.IsMethodUpToDate)
{
// Start tracking non-remappable regions for active statements in methods that were up-to-date
// when break state was entered and now being updated (regardless of whether the active span changed or not).
if (isMethodUpdated)
{
var lineDelta = oldSpan.GetLineDelta(newSpan: newSpan);
nonRemappableRegionsBuilder.Add((oldInstructionId.MethodId, new NonRemappableRegion(oldSpan, lineDelta, isExceptionRegion)));
}
// If the method has been up-to-date and it is not updated now then either the active statement span has not changed,
// or the entire method containing it moved. In neither case do we need to start tracking non-remapable region
// for the active statement since movement of whole method bodies (if any) is handled only on PDB level without
// triggering any remapping on the IL level.
}
else if (oldSpan != newSpan)
{
// The method is not up-to-date hence we maintain non-remapable span map for it that needs to be updated.
changedNonRemappableSpans[(methodToken, methodVersion, oldSpan)] = newSpan;
}
}
AddNonRemappableRegion(oldActiveStatement.Span, newActiveStatement.Span, isExceptionRegion: false);
var j = 0;
foreach (var oldSpan in baseActiveExceptionRegions[oldActiveStatement.Ordinal].Spans)
{
AddNonRemappableRegion(oldSpan, newExceptionRegions[oldActiveStatement.PrimaryDocumentOrdinal][j++], isExceptionRegion: true);
}
}
}
activeStatementsInUpdatedMethods = activeStatementsInUpdatedMethodsBuilder.ToImmutableAndFree();
// Gather all active method instances contained in this project/module that are not up-to-date:
var unremappedActiveMethods = PooledHashSet<ActiveMethodId>.GetInstance();
foreach (var (instruction, baseActiveStatement) in baseActiveStatements.InstructionMap)
{
if (moduleId == instruction.MethodId.ModuleId && !baseActiveStatement.IsMethodUpToDate)
{
unremappedActiveMethods.Add(instruction.MethodId);
}
}
if (unremappedActiveMethods.Count > 0)
{
foreach (var (methodInstance, regionsInMethod) in previousNonRemappableRegions)
{
// Skip non-remappable regions that belong to method instances that are from a different module
// or no longer active (all active statements in these method instances have been remapped to newer versions).
if (!unremappedActiveMethods.Contains(methodInstance))
{
continue;
}
foreach (var region in regionsInMethod)
{
// We have calculated changes against a base snapshot (last break state):
var baseSpan = region.Span.AddLineDelta(region.LineDelta);
NonRemappableRegion newRegion;
if (changedNonRemappableSpans.TryGetValue((methodInstance.Token, methodInstance.Version, baseSpan), out var newSpan))
{
// all spans must be of the same size:
Debug.Assert(newSpan.End.Line - newSpan.Start.Line == baseSpan.End.Line - baseSpan.Start.Line);
Debug.Assert(region.Span.End.Line - region.Span.Start.Line == baseSpan.End.Line - baseSpan.Start.Line);
newRegion = region.WithLineDelta(region.Span.GetLineDelta(newSpan: newSpan));
}
else
{
newRegion = region;
}
nonRemappableRegionsBuilder.Add((methodInstance, newRegion));
}
}
}
nonRemappableRegions = nonRemappableRegionsBuilder.ToImmutableAndFree();
changedNonRemappableSpans.Free();
unremappedActiveMethods.Free();
}
internal void ChangesApplied()
{
Debug.Assert(!_changesApplied);
_changesApplied = true;
}
}
}
|
||||
TheStack | b5ae51616f5130b85e1630e849ca978cecd24e72 | C#code:C# | {"size": 5242, "ext": "cs", "max_stars_repo_path": "QuestionCreator/Forms/easy.cs", "max_stars_repo_name": "mekk1t/trainer", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "QuestionCreator/Forms/easy.cs", "max_issues_repo_name": "mekk1t/trainer", "max_issues_repo_issues_event_min_datetime": "2021-05-01T18:23:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-03T12:52:31.000Z", "max_forks_repo_path": "QuestionCreator/Forms/easy.cs", "max_forks_repo_name": "mekk1t/trainer", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": 2.0, "max_forks_count": null, "avg_line_length": 32.1595092025, "max_line_length": 128, "alphanum_fraction": 0.5150705837} | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json;
using QuestionCreator.Forms;
using WebApplication.Models.Easy;
namespace QuestionCreator
{
public partial class Easy : Form
{
public Easy()
{
InitializeComponent();
FormClosed += Form_Closed;
Text = $"Работа с вопросами для легкого теста ver.{Application.ProductVersion}";
ToolStripMenuItem openImage = new ToolStripMenuItem("Открыть изображение");
ToolStripMenuItem cleanImage = new ToolStripMenuItem("Очистить");
openImage.Click += openImage_Click;
cleanImage.Click += cleanImage_Click;
contextMenuStrip1.Items.AddRange(new[] { openImage, cleanImage });
pictureBox1.ContextMenuStrip = contextMenuStrip1;
}
Image image;
bool opened = false;
string answer;
string image_location;
string pictureName;
public void openImage_Click(object sender, EventArgs e)
{
DialogResult dialogResult = openFileDialog1.ShowDialog();
if (dialogResult == DialogResult.OK)
{
image = Image.FromFile(openFileDialog1.FileName);
pictureBox1.Image = image;
image_location = openFileDialog1.FileName;
pictureName = Path.GetFileNameWithoutExtension(openFileDialog1.FileName);
label3.Text = pictureName;
label3.Visible = true;
opened = true;
}
}
private void cleanImage_Click(object sender, EventArgs e)
{
pictureBox1.Image = null;
opened = false;
}
private void saveJson()
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Файлы в формате JSON(.json)|*.json";
sfd.FileName = pictureName;
if (sfd.ShowDialog() == DialogResult.OK)
{
string filename = sfd.FileName;
EasyQuestionViewModel json = new EasyQuestionViewModel
{
Question = richTextBox1.Text,
Options = new string[]
{
textBox1.Text, textBox2.Text, textBox3.Text, textBox4.Text
},
CorrectAnswer = answer,
SelectedAnswer = "0",
ImageBase64 = ($"data:image/jpeg; base64,{Convert.ToBase64String(File.ReadAllBytes(image_location))}")
};
MessageBox.Show(filename);
File.WriteAllText(filename, JsonConvert.SerializeObject(json, Formatting.Indented));
Close();
Easy easy = new Easy();
easy.Show();
}
}
private void button1_Click(object sender, EventArgs e)
{
if (opened)
{
saveJson();
} else
{
MessageBox.Show("Вы картиночку забыли");
}
}
private void textBox_TextChanged(object sender, EventArgs e)
{
if (textBox1.Text != "" & textBox2.Text != "" & textBox3.Text != "" & textBox4.Text != "" & richTextBox1.Text != "")
{
radioButton1.Enabled = radioButton2.Enabled = radioButton3.Enabled = radioButton4.Enabled = true;
} else
{
radioButton1.Enabled = radioButton2.Enabled = radioButton3.Enabled = radioButton4.Enabled = false;
radioButton1.Checked = radioButton2.Checked = radioButton3.Checked = radioButton4.Checked = false;
button1.Enabled = false;
answer = "";
}
}
void radioButton_CheckedChanged(object sender, EventArgs e)
{
RadioButton rb = sender as RadioButton;
if (rb == null)
{
return;
}
if (rb.Checked)
{
button1.Enabled = true;
string action = rb.Text;
switch (action)
{
case "1":
answer = textBox1.Text;
break;
case "2":
answer = textBox2.Text;
break;
case "3":
answer = textBox3.Text;
break;
case "4":
answer = textBox4.Text;
break;
}
}
}
private void button2_Click(object sender, EventArgs e)
{
Form form = Application.OpenForms[0];
form.Show();
Close();
}
private void Form_Closed( object sender, FormClosedEventArgs e)
{
Form form = Application.OpenForms[0];
form.Show();
Controls.Clear();
}
}
}
|
||||
TheStack | b5b09bbed04fade9f3d4fe255135b572b3d953d6 | C#code:C# | {"size": 12191, "ext": "cs", "max_stars_repo_path": "test/FunctionalTests/Taupo/Source/Taupo.Astoria/LinqToAstoria/DataServiceQueryVerifier.cs", "max_stars_repo_name": "Sreejithpin/odata.net", "max_stars_repo_stars_event_min_datetime": "2022-01-14T04:52:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-14T04:52:44.000Z", "max_issues_repo_path": "test/FunctionalTests/Taupo/Source/Taupo.Astoria/LinqToAstoria/DataServiceQueryVerifier.cs", "max_issues_repo_name": "Sreejithpin/odata.net", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/FunctionalTests/Taupo/Source/Taupo.Astoria/LinqToAstoria/DataServiceQueryVerifier.cs", "max_forks_repo_name": "Sreejithpin/odata.net", "max_forks_repo_forks_event_min_datetime": "2021-06-07T15:52:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-07T15:52:35.000Z"} | {"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": 1.0, "avg_line_length": 46.0037735849, "max_line_length": 200, "alphanum_fraction": 0.6239028792} | //---------------------------------------------------------------------
// <copyright file="DataServiceQueryVerifier.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
// </copyright>
//---------------------------------------------------------------------
namespace Microsoft.Test.Taupo.Astoria.LinqToAstoria
{
#if WINDOWS_PHONE || WIN8
using System;
using System.Collections.Generic;
using Microsoft.OData.Client;
using System.Globalization;
using System.Linq;
using System.Reflection;
using Microsoft.Test.Taupo.Astoria.Client;
using Microsoft.Test.Taupo.Astoria.Contracts;
using Microsoft.Test.Taupo.Astoria.Contracts.Client;
using Microsoft.Test.Taupo.Astoria.Contracts.LinqToAstoria;
using Microsoft.Test.Taupo.Common;
using Microsoft.Test.Taupo.Contracts;
using Microsoft.Test.Taupo.Query.Contracts;
using Microsoft.Test.Taupo.Query.Contracts.CommonExpressions;
using Microsoft.Test.Taupo.Utilities;
using CoreLinq = System.Linq.Expressions;
using DSC = Microsoft.OData.Service.Common;
/// <summary>
/// QueryVerifier for Windows Phone platform which uses the product's linq translator to run queries and execute tests.
/// </summary>
[ImplementationName(typeof(IQueryVerifier), "ClientQuery")]
public class DataServiceQueryVerifier : IQueryVerifier
{
private AstoriaWorkspace workspace;
private List<QueryExpression> pendingQueries = new List<QueryExpression>();
/// <summary>
/// Initializes a new instance of the DataServiceQueryVerifier class.
/// </summary>
/// <param name="workspace">The workspace.</param>
public DataServiceQueryVerifier(AstoriaWorkspace workspace)
{
this.workspace = workspace;
this.Logger = Logger.Null;
this.IsAsync = true;
}
/// <summary>
/// Gets or sets the logger used to print diagnostic messages.
/// </summary>
/// <value>The logger.</value>
[InjectDependency]
public Logger Logger { get; set; }
/// <summary>
/// Gets or sets the code builder used to generate code.
/// </summary>
[InjectDependency(IsRequired = true)]
public ILinqToAstoriaQueryResolver LinqQueryResolver { get; set; }
/// <summary>
/// Gets or sets the code builder used to generate code.
/// </summary>
[InjectDependency(IsRequired = true)]
public ILinqToAstoriaQuerySpanGenerator SpanGenerator { get; set; }
/// <summary>
/// Gets or sets the query expression evaluator.
/// </summary>
[InjectDependency(IsRequired = true)]
public IQueryExpressionEvaluator Evaluator { get; set; }
/// <summary>
/// Gets or sets the result comparer.
/// </summary>
[InjectDependency(IsRequired = true)]
public IClientQueryResultComparer ResultComparer { get; set; }
/// <summary>
/// Gets or sets the uri query visitor.
/// </summary>
[InjectDependency(IsRequired = true)]
public IClientQueryVersionErrorCalculator LinqToAstoriaErrorCalculator { get; set; }
/// <summary>
/// Gets or sets the uri query visitor.
/// </summary>
[InjectDependency(IsRequired = true)]
public IQueryToUriStringConverter UriQueryVisitor { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this instance is async.
/// </summary>
/// <value><c>true</c> if this instance is async; otherwise, <c>false</c>.</value>
[InjectTestParameter("Asynchronous", DefaultValueDescription = "true")]
public bool IsAsync { get; set; }
/// <summary>
/// Gets or sets the DataServiceContextCreator
/// </summary>
[InjectDependency(IsRequired = true)]
public IDataServiceContextCreator DataServiceContextCreator { get; set; }
/// <summary>
/// Gets or sets the DataServiceContextScope
/// </summary>
[InjectDependency(IsRequired = true)]
public IDataServiceContextTrackingScope DataServiceContextScope { get; set; }
/// <summary>
/// Gets or sets logger to be used for printing diagnostics messages.
/// </summary>
[InjectDependency]
public Logger Log { get; set; }
#if !WINDOWS_PHONE
/// <summary>
/// Gets or sets the sending request event verifier to use
/// </summary>
[InjectDependency(IsRequired = true)]
public ISendingRequestEventVerifier SendingRequestEventVerifier { get; set; }
#endif
/// <summary>
/// Gets or sets a value indicating whether ExecuteURI test parameter is true.
/// </summary>
/// <value><c>true</c> if ExecuteURI test parameter is true; otherwise, <c>false</c>.</value>
[InjectTestParameter("ExecuteURI", DefaultValueDescription = "false")]
public bool IsExecuteURI { get; set; }
/// <summary>
/// Verify the passed query tree.
/// </summary>
/// <param name="expression">The query tree which will be verified</param>
public virtual void Verify(QueryExpression expression)
{
ExceptionUtilities.CheckAllRequiredDependencies(this);
ExceptionUtilities.Assert(this.IsAsync, "this verifier can only run async");
this.ThrowSkippedExceptionIfQueryExpressionNotSupported(expression);
var resolvedQuery = this.LinqQueryResolver.Resolve(expression);
var dataServiceContext = this.DataServiceContextCreator.CreateContext(this.DataServiceContextScope, this.workspace.ContextType, this.workspace.ServiceUri);
if (this.IsExecuteURI)
{
// TODO: update this verifier to call ExecuteUriAndCompare if ExecuteURI test parameter is set to true
}
else
{
ClientQueryGenerator queryGenerator = new ClientQueryGenerator(new CSharpGenericTypeBuilder());
DataServiceContext clientContext = dataServiceContext.Product as DataServiceContext;
CoreLinq.Expression queryLinqExpression = queryGenerator.Generate(resolvedQuery, clientContext);
IQueryProvider queryProvider = clientContext.CreateQuery<int>("Set").Provider as IQueryProvider;
DataServiceQuery dataServiceQuery = queryProvider.CreateQuery(queryLinqExpression) as DataServiceQuery;
this.ResultComparer.EnqueueNextQuery(resolvedQuery);
AsyncExecutionContext.EnqueueAsynchronousAction((queryContinuation) =>
{
this.Log.WriteLine(LogLevel.Info, dataServiceQuery.ToString());
QueryValue baselineValue = this.GetBaselineValue(resolvedQuery);
DataServiceProtocolVersion maxProtocolVersion = this.workspace.ConceptualModel.GetMaxProtocolVersion();
#if WINDOWS_PHONE
DataServiceProtocolVersion maxClientProtocolVersion = DataServiceProtocolVersion.V4;
#else
DataServiceProtocolVersion maxClientProtocolVersion = ((DSC.DataServiceProtocolVersion)dataServiceContext.MaxProtocolVersion.Product).ToTestEnum();
#endif
// Calculate version errors
ExpectedClientErrorBaseline clientError = this.LinqToAstoriaErrorCalculator.CalculateExpectedClientVersionError(resolvedQuery, true, maxClientProtocolVersion, maxProtocolVersion);
if (clientError != null)
{
this.Log.WriteLine(LogLevel.Info, "Expected client exception: " + clientError.ExpectedExceptionType.ToString());
}
Type queryType = dataServiceQuery.ElementType;
MethodInfo genericExecuteMethod = this.ResultComparer.GetType().GetMethod("ExecuteAndCompare").MakeGenericMethod(queryType);
genericExecuteMethod.Invoke(this.ResultComparer, new object[] { queryContinuation, this.IsAsync, dataServiceQuery, baselineValue, clientContext, clientError });
});
}
}
private QueryValue GetBaselineValue(QueryExpression resolvedQuery)
{
QueryValue baselineValue = this.Evaluator.Evaluate(resolvedQuery);
// get the expand segments and select segments from the query
this.UriQueryVisitor.ComputeUri(resolvedQuery);
string select = this.UriQueryVisitor.SelectString;
string expand = this.UriQueryVisitor.ExpandString;
IEnumerable<string> selectedPaths = (new string[] { }).AsEnumerable();
IEnumerable<string> expandedPaths = (new string[] { }).AsEnumerable();
if (select != null)
{
selectedPaths = select.Split(new string[] { "," }, StringSplitOptions.None).AsEnumerable();
}
if (expand != null)
{
expandedPaths = expand.Split(new string[] { "," }, StringSplitOptions.None).AsEnumerable();
}
baselineValue = this.SpanGenerator.GenerateSpan(baselineValue, expandedPaths, selectedPaths);
return baselineValue;
}
private void ThrowSkippedExceptionIfQueryExpressionNotSupported(QueryExpression expression)
{
QueryCustomFunctionCallExpression customFunctionCallExpression = expression as QueryCustomFunctionCallExpression;
if (!this.IsExecuteURI && customFunctionCallExpression != null)
{
throw new TestSkippedException(string.Format(CultureInfo.InvariantCulture, "Invalid Query '{0}', operation query not supported through DataServiceQuery", expression.ToString()));
}
// Uri will always work, Client linq has cases where it will not
ODataUriToClientLinqReplacingVisitor visitor = new ODataUriToClientLinqReplacingVisitor();
visitor.ReplaceExpression(expression);
if (visitor.InvalidClientQuery == true)
{
throw new TestSkippedException(string.Format(CultureInfo.InvariantCulture, "Invalid Query '{0}', query not supported using Linq to Astoria client", expression.ToString()));
}
}
/// <summary>
/// Class visits QueryExpression and indicates whether this expression is valid for a client
/// query test
/// </summary>
private class ODataUriToClientLinqReplacingVisitor : LinqToAstoriaExpressionReplacingVisitor
{
internal ODataUriToClientLinqReplacingVisitor()
{
this.InvalidClientQuery = false;
}
internal bool InvalidClientQuery { get; private set; }
/// <summary>
/// Overrides the Visit expression and finds and analyzes property expressions to see if the KeyExpression is before
/// If it is then this is an invalid query for the client
/// </summary>
/// <param name="expression">Expression to be analyzed</param>
/// <returns>The same expression</returns>
public override QueryExpression Visit(QueryPropertyExpression expression)
{
var keyExpression = expression.Instance as LinqToAstoriaKeyExpression;
if (keyExpression != null)
{
this.InvalidClientQuery = true;
}
return base.Visit(expression);
}
}
}
#else
/// <summary>
/// Stub verifier class, this class is only available on the Windows Phone platform
/// </summary>
public class DataServiceQueryVerifier
{
}
#endif
} |
||||
TheStack | b5b0dce98e67ca1afd7087aade2de1b9a5e7501f | C#code:C# | {"size": 3760, "ext": "cs", "max_stars_repo_path": "FreeBuild.cs", "max_stars_repo_name": "0x89A/Free-Build", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "FreeBuild.cs", "max_issues_repo_name": "0x89A/Free-Build", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "FreeBuild.cs", "max_forks_repo_name": "0x89A/Free-Build", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 34.1818181818, "max_line_length": 148, "alphanum_fraction": 0.5561170213} | using System.Collections.Generic;
using Oxide.Core.Libraries.Covalence;
namespace Oxide.Plugins
{
[Info("Free Build", "0x89A", "2.0.1")]
[Description("Allows building, upgrading and placing deployables for free")]
class FreeBuild : CovalencePlugin
{
private const string usePerm = "freebuild.allow";
private HashSet<BasePlayer> activePlayers = new HashSet<BasePlayer>();
bool freeDeployables = false;
bool requireChat = false;
string chatCommand = string.Empty;
void Init()
{
permission.RegisterPermission(usePerm, this);
if (requireChat) AddCovalenceCommand(chatCommand, nameof(Command), usePerm);
}
object CanAffordToPlace(BasePlayer player, Planner planner, Construction construction)
{
if (IsAllowed(player)) return true;
else return null;
}
object OnPayForPlacement(BasePlayer player, Planner planner, Construction construction)
{
if (IsAllowed(player) && DeployableCheck(construction.deployable)) return true;
else return null;
}
object OnPayForUpgrade(BasePlayer player, BuildingBlock block, ConstructionGrade gradeTarget)
{
if (IsAllowed(player)) return true;
else return null;
}
private void Command(IPlayer iplayer, string command, string[] args)
{
BasePlayer player = iplayer.Object as BasePlayer;
if (player == null) return;
if (activePlayers.Contains(player))
{
activePlayers.Remove(player);
player.ChatMessage(lang.GetMessage("Disabled", this, player.UserIDString));
}
else
{
activePlayers.Add(player);
player.ChatMessage(lang.GetMessage("Enabled", this, player.UserIDString));
}
}
private bool IsAllowed(BasePlayer player)
{
return requireChat ? activePlayers.Contains(player) : permission.UserHasPermission(player.UserIDString, usePerm);
}
private bool DeployableCheck(Deployable deployable)
{
return !(deployable != null && !freeDeployables && deployable.fullName.Contains("deployed"));
}
protected override void LoadDefaultMessages()
{
lang.RegisterMessages(new Dictionary<string, string>
{
["Enabled"] = "Free build <color=green>enabled</color>",
["Disabled"] = "Free build <color=red>disabled</color>",
}, this);
}
protected override void LoadConfig()
{
base.LoadConfig();
try
{
if (!(Config["Require Chat Command"] is bool) || !(Config["Chat Command"] is string) || !(Config["Deployables Are Free"] is bool))
throw new System.Exception();
requireChat = (bool)Config["Require Chat Command"];
freeDeployables = (bool)Config["Deployables Are Free"];
chatCommand = (string)Config["Chat Command"];
Config.Save();
}
catch
{
PrintWarning("Configuration is corrupt, generating new configuration");
LoadDefaultConfig();
}
}
protected override void LoadDefaultConfig()
{
Config["Chat Command"] = "freebuild";
Config["Require Chat Command"] = true;
Config["Deployables Are Free"] = true;
Config.Save();
}
}
}
|
||||
TheStack | b5b175e70dbca6129cf1da304b4c358fc9684820 | C#code:C# | {"size": 1049, "ext": "cs", "max_stars_repo_path": "NewsApp/Controller/SubscriptionController.cs", "max_stars_repo_name": "anuitex/Global-News", "max_stars_repo_stars_event_min_datetime": "2020-11-18T11:13:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-05T08:14:24.000Z", "max_issues_repo_path": "NewsApp/Controller/SubscriptionController.cs", "max_issues_repo_name": "anuitex/Global-News", "max_issues_repo_issues_event_min_datetime": "2021-03-09T21:45:51.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-26T19:38:55.000Z", "max_forks_repo_path": "NewsApp/Controller/SubscriptionController.cs", "max_forks_repo_name": "anuitex/Global-News", "max_forks_repo_forks_event_min_datetime": "2021-09-01T06:01:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-24T08:05:53.000Z"} | {"max_stars_count": 2.0, "max_issues_count": 10.0, "max_forks_count": 2.0, "avg_line_length": 26.8974358974, "max_line_length": 80, "alphanum_fraction": 0.6244041945} | using Models;
using System.Net.Mail;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Services.Interfaces;
namespace NewsApp.Controller
{
[Route("api/[controller]")]
[ApiController]
public class SubscriptionController : BaseController
{
private ISubscriptionService _subscriptionService;
public SubscriptionController(ISubscriptionService subscriptionService)
{
_subscriptionService = subscriptionService;
}
[Route("/addSubscription")]
[HttpPost]
public async Task<ActionResult> AddSubsctiption(SubcsriptionModel model)
{
if (string.IsNullOrWhiteSpace(model.Email))
{
return BadRequest("You shuold provide valid email");
}
bool result = await _subscriptionService.AddSubscription(model);
if (result)
{
return Ok("You subscribed to news!");
}
return BadRequest("Something went wrong!");
}
}
} |
||||
TheStack | b5b387cc47794d9a2e7a89afc61536e225694b98 | C#code:C# | {"size": 4989, "ext": "cs", "max_stars_repo_path": "ConsensusCore.Node/Repositories/NodeInMemoryRepository.ShardRepository.cs", "max_stars_repo_name": "xucito/consensus-core", "max_stars_repo_stars_event_min_datetime": "2020-06-11T06:41:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-23T11:25:33.000Z", "max_issues_repo_path": "ConsensusCore.Node/Repositories/NodeInMemoryRepository.ShardRepository.cs", "max_issues_repo_name": "xucito/consensus-core", "max_issues_repo_issues_event_min_datetime": "2019-08-02T20:24:06.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-02T20:24:06.000Z", "max_forks_repo_path": "ConsensusCore.Node/Repositories/NodeInMemoryRepository.ShardRepository.cs", "max_forks_repo_name": "xucito/consensus-core", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 3.0, "max_issues_count": 1.0, "max_forks_count": null, "avg_line_length": 40.5609756098, "max_line_length": 179, "alphanum_fraction": 0.6598516737} | using ConsensusCore.Domain.BaseClasses;
using ConsensusCore.Domain.Interfaces;
using ConsensusCore.Domain.Models;
using ConsensusCore.Domain.Utility;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsensusCore.Node.Repositories
{
public partial class NodeInMemoryRepository<Z> : IShardRepository
where Z : BaseState, new()
{
public Task<bool> AddDataReversionRecordAsync(DataReversionRecord record)
{
DataReversionRecords.Add(SystemExtension.Clone(record));
return Task.FromResult(true);
}
public Task<bool> AddShardMetadataAsync(ShardMetadata shardMetadata)
{
ShardMetadata.Add(shardMetadata.ShardId, shardMetadata);
return Task.FromResult(true);
}
public Task<bool> AddShardWriteOperationAsync(ShardWriteOperation operation)
{
return Task.FromResult(ShardWriteOperations.TryAdd(operation.Id, SystemExtension.Clone(operation)));
}
public Task<SortedDictionary<int, ShardWriteOperation>> GetAllObjectShardWriteOperationAsync(Guid shardId, Guid objectId)
{
var result = new SortedDictionary<int, ShardWriteOperation>();
foreach (var operation in ShardWriteOperations.Where(so => so.Value.Data.Id == objectId && so.Value.Data.ShardId == shardId))
{
result.Add(operation.Value.Pos, operation.Value);
}
return Task.FromResult(result);
}
public Task<List<ShardMetadata>> GetAllShardMetadataAsync()
{
return Task.FromResult(ShardMetadata.Select(sm => sm.Value).ToList());
}
public Task<IEnumerable<ShardWriteOperation>> GetAllShardWriteOperationsAsync(Guid shardId)
{
return Task.FromResult(SystemExtension.Clone(ShardWriteOperations.Select(so => so.Value)));
}
public Task<SortedDictionary<int, ShardWriteOperation>> GetAllUnappliedOperationsAsync(Guid shardId)
{
var sortedSWO = ShardWriteOperations.Where(swo => swo.Value.Data.ShardId == shardId).ToList();
SortedDictionary<int, ShardWriteOperation> result = new SortedDictionary<int, ShardWriteOperation>();
foreach (var operation in sortedSWO)
{
result.Add(operation.Value.Pos, operation.Value);
}
return Task.FromResult(result);
}
public Task<ShardMetadata> GetShardMetadataAsync(Guid shardId)
{
return Task.FromResult(ShardMetadata.GetValueOrDefault(shardId));
}
public Task<ShardWriteOperation> GetShardWriteOperationAsync(Guid shardId, int syncPos)
{
return Task.FromResult(SystemExtension.Clone(ShardWriteOperations.Where(swo => swo.Value.Data.ShardId == shardId && swo.Value.Pos == syncPos).FirstOrDefault().Value));
}
public Task<ShardWriteOperation> GetShardWriteOperationAsync(string transacionId)
{
if (ShardWriteOperations.ContainsKey(transacionId))
{
return Task.FromResult(ShardWriteOperations[transacionId]);
}
return Task.FromResult< ShardWriteOperation>(null);
}
public Task<SortedDictionary<int, ShardWriteOperation>> GetShardWriteOperationsAsync(Guid shardId, int from, int to)
{
var writes = ShardWriteOperations.Where(swo => swo.Value.Data.ShardId == shardId && swo.Value.Pos >= from && swo.Value.Pos <= to);
SortedDictionary<int, ShardWriteOperation> operations = new SortedDictionary<int, ShardWriteOperation>();
foreach (var write in writes)
{
operations.Add(write.Value.Pos, write.Value);
}
return Task.FromResult(operations);
}
public int GetTotalShardWriteOperationsCount(Guid shardId)
{
return ShardWriteOperations.Count();
}
public bool IsObjectMarkedForDeletion(Guid shardId, Guid objectId)
{
return ObjectDeletionMarker.Where(odm => odm.ObjectId == objectId && odm.ShardId == shardId).Count() > 0;
}
public Task<bool> MarkObjectForDeletionAsync(ObjectDeletionMarker marker)
{
ObjectDeletionMarker.Add(SystemExtension.Clone(marker));
return Task.FromResult(true);
}
public Task<bool> MarkShardWriteOperationAppliedAsync(string operationId)
{
if (ShardWriteOperations.ContainsKey(operationId))
return Task.FromResult(ShardWriteOperations[operationId].Applied = true);
return Task.FromResult(false);
}
public async Task<bool> RemoveShardWriteOperationAsync(Guid shardId, int pos)
{
return ShardWriteOperations.TryRemove((await GetShardWriteOperationAsync(shardId, pos)).Id, out _);
}
}
}
|
||||
TheStack | b5b408fb10327ed58110790d8c09495ec7fea48b | C#code:C# | {"size": 873, "ext": "cs", "max_stars_repo_path": "src/Kelson.Common.Vectors/IVector.cs", "max_stars_repo_name": "KelsonBall/RaymarchingSim", "max_stars_repo_stars_event_min_datetime": "2019-02-11T21:39:14.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-11T21:39:14.000Z", "max_issues_repo_path": "src/Kelson.Common.Vectors/IVector.cs", "max_issues_repo_name": "KelsonBall/RaymarchingSim", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Kelson.Common.Vectors/IVector.cs", "max_forks_repo_name": "KelsonBall/RaymarchingSim", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 34.92, "max_line_length": 58, "alphanum_fraction": 0.7010309278} | using System.Runtime.CompilerServices;
namespace Kelson.Common.Vectors
{
public interface IVector<TSelf>
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
double MagnitudeSquared();
[MethodImpl(MethodImplOptions.AggressiveInlining)]
double Magnitude();
[MethodImpl(MethodImplOptions.AggressiveInlining)]
double Dot(in TSelf other);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
TSelf Add(in TSelf other);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
TSelf Sub(in TSelf other);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
TSelf Scale(double scalar);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
double AngularMagnitude(in TSelf other);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
TSelf Unit();
}
}
|
||||
TheStack | b5b41d5a9c3030da5143654d6ad5e9189277fb8b | C#code:C# | {"size": 628, "ext": "cs", "max_stars_repo_path": "UnityDevToolbox/Common/Interfaces/IAssetBundleReader.cs", "max_stars_repo_name": "bnoazx005/UnityDevToolbox", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "UnityDevToolbox/Common/Interfaces/IAssetBundleReader.cs", "max_issues_repo_name": "bnoazx005/UnityDevToolbox", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "UnityDevToolbox/Common/Interfaces/IAssetBundleReader.cs", "max_forks_repo_name": "bnoazx005/UnityDevToolbox", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 26.1666666667, "max_line_length": 102, "alphanum_fraction": 0.7484076433} | using UnityEngine;
namespace UnityDevToolbox.Interfaces
{
public delegate void OnAssetBundleLoadedCallback(IAssetBundleReader assetBundleReader);
public delegate void OnErrorCallback(object errorData);
public interface IAssetBundleReader
{
void OpenAsync(OnAssetBundleLoadedCallback onLoadedCallback, OnErrorCallback onErrorCallback);
bool Close();
bool ContainsAsset(string name);
UnityEngine.Object LoadAsset(string assetName);
T LoadAsset<T>(string assetName) where T : UnityEngine.Object;
AssetBundleRequest LoadAssetAsync(string assetName);
}
}
|
||||
TheStack | b5b42b238631f62d8f937dbe7fbc31aa1149f9a7 | C#code:C# | {"size": 920, "ext": "cs", "max_stars_repo_path": "src/01.framework/01-Alabo/Datas/Stores/Column/EfCore/ColumnAsyncEfCoreStore.cs", "max_stars_repo_name": "tongxin3267/alabo", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/01.framework/01-Alabo/Datas/Stores/Column/EfCore/ColumnAsyncEfCoreStore.cs", "max_issues_repo_name": "tongxin3267/alabo", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/01.framework/01-Alabo/Datas/Stores/Column/EfCore/ColumnAsyncEfCoreStore.cs", "max_forks_repo_name": "tongxin3267/alabo", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 32.8571428571, "max_line_length": 101, "alphanum_fraction": 0.677173913} | using Alabo.Datas.Stores.Add.EfCore;
using Alabo.Datas.UnitOfWorks;
using Alabo.Domains.Entities.Core;
using Alabo.Exceptions;
using Alabo.Extensions;
using Alabo.Reflections;
using System.Threading.Tasks;
namespace Alabo.Datas.Stores.Column.EfCore {
public abstract class ColumnAsyncEfCoreStore<TEntity, TKey> : AddAsyncEfCoreStore<TEntity, TKey>,
IColumnAsyncStore<TEntity, TKey>
where TEntity : class, IKey<TKey>, IVersion, IEntity {
protected ColumnAsyncEfCoreStore(IUnitOfWork unitOfWork) : base(unitOfWork) {
}
public async Task<object> GetFieldValueAsync(object id, string field) {
if (id.IsNullOrEmpty() || field.IsNullOrEmpty()) {
throw new ValidException("Id或者字段设置不能为空");
}
var find = await GetSingleAsync(id);
var value = field.GetPropertyValue(find);
return value;
}
}
} |
||||
TheStack | b5b4755ffbf45a3c2eb8f77ee9fc77f35a6e80d9 | C#code:C# | {"size": 1444, "ext": "cs", "max_stars_repo_path": "demo/WalkingTec.Mvvm.Demo/ViewModels/StudentVMs/StudentVM.cs", "max_stars_repo_name": "17713017177/WTM", "max_stars_repo_stars_event_min_datetime": "2019-10-25T10:24:27.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-26T03:01:19.000Z", "max_issues_repo_path": "demo/WalkingTec.Mvvm.Demo/ViewModels/StudentVMs/StudentVM.cs", "max_issues_repo_name": "17713017177/WTM", "max_issues_repo_issues_event_min_datetime": "2019-09-29T07:01:28.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-29T07:01:28.000Z", "max_forks_repo_path": "demo/WalkingTec.Mvvm.Demo/ViewModels/StudentVMs/StudentVM.cs", "max_forks_repo_name": "17713017177/WTM", "max_forks_repo_forks_event_min_datetime": "2022-02-22T03:31:15.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-22T03:31:15.000Z"} | {"max_stars_count": 3.0, "max_issues_count": 1.0, "max_forks_count": 1.0, "avg_line_length": 27.7692307692, "max_line_length": 102, "alphanum_fraction": 0.5927977839} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WalkingTec.Mvvm.Core;
using WalkingTec.Mvvm.Core.Extensions;
using WalkingTec.Mvvm.Demo.Models;
using WalkingTec.Mvvm.Demo.ViewModels.MajorVMs;
namespace WalkingTec.Mvvm.Demo.ViewModels.StudentVMs
{
public class StudentVM : BaseCRUDVM<Student>
{
public MajorListVM MajorList { get; set; }
public List<Guid> SelectedMajorIds { get; set; }
public StudentVM()
{
MajorList = new MajorListVM();
SetInclude(x => x.StudentMajor);
}
protected override void InitVM()
{
SelectedMajorIds = Entity.StudentMajor.Select(x => x.MajorId).ToList();
}
public override void DoAdd()
{
Entity.StudentMajor = new List<StudentMajor>();
if (SelectedMajorIds != null)
{
foreach (var majorid in SelectedMajorIds)
{
Entity.StudentMajor.Add(new StudentMajor { MajorId = majorid });
}
}
base.DoAdd();
}
public override void DoEdit(bool updateAllFields = false)
{
Entity.StudentMajor = new List<StudentMajor>();
SelectedMajorIds?.ForEach(x => Entity.StudentMajor.Add(new StudentMajor { MajorId = x }));
base.DoEdit(updateAllFields);
}
}
}
|
||||
TheStack | b5b8883bba0477693315af243f5e3294f3c45253 | C#code:C# | {"size": 599, "ext": "cs", "max_stars_repo_path": "Assets/Scripts/Utils/EnumExtensions.cs", "max_stars_repo_name": "redmoon-games/SimpleMergeSource", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Assets/Scripts/Utils/EnumExtensions.cs", "max_issues_repo_name": "redmoon-games/SimpleMergeSource", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Assets/Scripts/Utils/EnumExtensions.cs", "max_forks_repo_name": "redmoon-games/SimpleMergeSource", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 17.6176470588, "max_line_length": 84, "alphanum_fraction": 0.592654424} | using System;
using System.Collections.Generic;
namespace Utils
{
public static class EnumExtensions
{
public static int[] ToIntArray<T>(this T[] @enum) where T : Enum, IConvertible
{
var ints = new int[@enum.Length];
for (int i = 0; i < @enum.Length; i++)
{
ints[i] = Convert.ToInt32(@enum[i]);
}
return ints;
}
public static int[] ToIntArray<T>(this List<T> @enum) where T : Enum, IConvertible
{
var ints = new int[@enum.Count];
for (int i = 0; i < @enum.Count; i++)
{
ints[i] = Convert.ToInt32(@enum[i]);
}
return ints;
}
}
} |
||||
TheStack | b5ba1746130a104437d7cc74c0a3f3fb138390f9 | C#code:C# | {"size": 1952, "ext": "cs", "max_stars_repo_path": "test/Mono.Linker.Tests.Cases/Reflection/AssemblyImportedViaReflectionWithDerivedType.cs", "max_stars_repo_name": "tannergooding/linker", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/Mono.Linker.Tests.Cases/Reflection/AssemblyImportedViaReflectionWithDerivedType.cs", "max_issues_repo_name": "tannergooding/linker", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/Mono.Linker.Tests.Cases/Reflection/AssemblyImportedViaReflectionWithDerivedType.cs", "max_forks_repo_name": "tannergooding/linker", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 47.6097560976, "max_line_length": 204, "alphanum_fraction": 0.7699795082} | using System;
using Mono.Linker.Tests.Cases.Expectations.Assertions;
using Mono.Linker.Tests.Cases.Expectations.Metadata;
using Mono.Linker.Tests.Cases.Reflection.Dependencies;
namespace Mono.Linker.Tests.Cases.Reflection
{
[IgnoreTestCase ("Requires support for using a type in an unreferences assembly via reflection")]
[SetupCompileBefore ("base.dll", new[] { "Dependencies/AssemblyImportedViaReflectionWithDerivedType_Base.cs" })]
[SetupCompileBefore ("reflection.dll", new[] { "Dependencies/AssemblyImportedViaReflectionWithDerivedType_Reflect.cs" }, references: new[] { "base.dll" }, addAsReference: false)]
[KeptAssembly ("base.dll")]
[KeptAssembly ("reflection.dll")]
[KeptMemberInAssembly ("base.dll", typeof (AssemblyImportedViaReflectionWithDerivedType_Base), "Method()")]
[KeptMemberInAssembly ("reflection.dll", "Mono.Linker.Tests.Cases.Reflection.Dependencies.AssemblyImportedViaReflectionWithDerivedType_Reflect", "Method()")]
public class AssemblyImportedViaReflectionWithDerivedType
{
public static void Main ()
{
// Cause a the new assembly to be included via reflection usage
const string newAssemblyType = "Mono.Linker.Tests.Cases.Reflection.Dependencies.AssemblyImportedViaReflectionWithDerivedType_Reflect, reflection, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null";
var res = Type.GetType (newAssemblyType, true);
// Foo and the reflection assembly both have a class the inherits from the base type.
// by using `Method` here and marking the reflection type above, we've introduced a requirement that `Method` be marked on the type in the reflection assembly as well
var obj = new Foo ();
var val = obj.Method ();
}
[Kept]
[KeptMember (".ctor()")]
[KeptBaseType (typeof (AssemblyImportedViaReflectionWithDerivedType_Base))]
class Foo : AssemblyImportedViaReflectionWithDerivedType_Base
{
[Kept]
public override string Method ()
{
return "Foo";
}
}
}
} |
||||
TheStack | b5bdc02897bd75f8b588ff925b182bcc31505a29 | C#code:C# | {"size": 1170, "ext": "cs", "max_stars_repo_path": "DemoB/Models/EavContext.cs", "max_stars_repo_name": "jhoye/ReactScratchPad", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "DemoB/Models/EavContext.cs", "max_issues_repo_name": "jhoye/ReactScratchPad", "max_issues_repo_issues_event_min_datetime": "2021-03-10T15:56:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-11T11:10:44.000Z", "max_forks_repo_path": "DemoB/Models/EavContext.cs", "max_forks_repo_name": "jhoye/ReactScratchPad", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": 12.0, "max_forks_count": null, "avg_line_length": 28.5365853659, "max_line_length": 82, "alphanum_fraction": 0.6846153846} | using DemoB.Models.Meta;
using DemoB.Models.Values;
using Microsoft.EntityFrameworkCore;
namespace DemoB.Models
{
public class EavContext : DbContext
{
public EavContext(DbContextOptions<EavContext> options) : base(options)
{
}
#region Meta
public DbSet<EntityType> EntityTypes { get; set; }
public DbSet<EntityTypeAttribute> EntityTypeAttributes { get; set;}
public DbSet<EntityTypeRelationship> EntityTypeRelationships { get; set; }
public DbSet<ValueType> ValueTypes { get; set; }
#endregion
public DbSet<Entity> Entities { get; set; }
public DbSet<Attribute> Attributes { get; set; }
public DbSet<Relationship> Relationships { get; set; }
public DbSet<AttributeBooleanValue> AttributeBooleanValues { get; set; }
public DbSet<AttributeIntegerValue> AttributeIntegerValues { get; set; }
public DbSet<AttributeDecimalValue> AttributeDecimalValues { get; set; }
public DbSet<AttributeTextValue> AttributeTextValues { get; set; }
public DbSet<AttributeDateTimeValue> AttributeDateTimeValues { get; set; }
}
} |
||||
TheStack | b5be58ce5a3c336effb6ce192c91b04e6fda8b60 | C#code:C# | {"size": 408, "ext": "cs", "max_stars_repo_path": "src/MockHttp/Language/Flow/ICallbackResult.cs", "max_stars_repo_name": "qkhaipham/MockHttp", "max_stars_repo_stars_event_min_datetime": "2020-03-27T16:54:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T19:46:20.000Z", "max_issues_repo_path": "src/MockHttp/Language/Flow/ICallbackResult.cs", "max_issues_repo_name": "qkhaipham/MockHttp", "max_issues_repo_issues_event_min_datetime": "2020-01-11T18:30:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-15T07:59:34.000Z", "max_forks_repo_path": "src/MockHttp/Language/Flow/ICallbackResult.cs", "max_forks_repo_name": "qkhaipham/MockHttp", "max_forks_repo_forks_event_min_datetime": "2021-02-02T23:47:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T14:48:26.000Z"} | {"max_stars_count": 15.0, "max_issues_count": 5.0, "max_forks_count": 2.0, "avg_line_length": 29.1428571429, "max_line_length": 144, "alphanum_fraction": 0.7843137255} | using System.ComponentModel;
namespace MockHttp.Language.Flow
{
/// <summary>
/// Implements the fluent API.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public interface ICallbackResult<out TResponseResult, out TThrowsResult> : IResponds<TResponseResult>, IThrows<TThrowsResult>, IFluentInterface
where TResponseResult : IResponseResult
where TThrowsResult : IThrowsResult
{
}
} |
||||
TheStack | b5be69a8fd08220fe9b29b58d534d6a079a7eb6f | C#code:C# | {"size": 451, "ext": "cs", "max_stars_repo_path": "Web2-Microservices/AirlineMicroservice/Models/AirlineRate.cs", "max_stars_repo_name": "bojanpisic/WebApp-Microservice-Arhitecture", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Web2-Microservices/AirlineMicroservice/Models/AirlineRate.cs", "max_issues_repo_name": "bojanpisic/WebApp-Microservice-Arhitecture", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Web2-Microservices/AirlineMicroservice/Models/AirlineRate.cs", "max_forks_repo_name": "bojanpisic/WebApp-Microservice-Arhitecture", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 21.4761904762, "max_line_length": 46, "alphanum_fraction": 0.6119733925} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace AirlineMicroservice.Models
{
public class AirlineRate
{
public int AirlineRateId { get; set; }
public float Rate { get; set; }
//public int AirlineId { get; set; }
public Airline Airline { get; set; }
public string UserId { get; set; }
public AirlineRate()
{
}
}
}
|
||||
TheStack | b5c2a4ed720afc5749dbeb2686daa90a8865f7ae | C#code:C# | {"size": 5067, "ext": "cs", "max_stars_repo_path": "Encryption Software/VigenereCipher.cs", "max_stars_repo_name": "Ominira/VigenereCipher", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Encryption Software/VigenereCipher.cs", "max_issues_repo_name": "Ominira/VigenereCipher", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Encryption Software/VigenereCipher.cs", "max_forks_repo_name": "Ominira/VigenereCipher", "max_forks_repo_forks_event_min_datetime": "2019-11-16T17:30:31.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-16T17:30:31.000Z"} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": 1.0, "avg_line_length": 29.1206896552, "max_line_length": 95, "alphanum_fraction": 0.4055654233} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WindowsFormsApplication1
{
public class VigenereCipher
{
public VigenereCipher() { }
public String EncryptText(String inputString, String key)
{
int tableRowSize = 26;
int tableColumnSize = 26;
int[,] vignereTable = new int[26,26];
for (int rows = 0; rows < tableRowSize; rows++)
{
for (int columns = 0; columns < tableColumnSize; columns++)
{
vignereTable[rows, columns] = (rows + columns) % 26;
}
}
inputString = inputString.ToUpper();
key = key.ToUpper();
String cipherText = "";
int keyIndex = 0;
for (int instrTextIndex = 0; instrTextIndex < inputString.Length; instrTextIndex++)
{
char instrChar = inputString[instrTextIndex];
int asciival = (int) instrChar;
if (instrChar == ' ')
{
cipherText += instrChar;
continue;
}
if (Char.IsPunctuation(instrChar))
{
cipherText += instrChar;
continue;
}
if (asciival == 13)
{
cipherText += "\r";
continue;
}
if (asciival == 10)
{
cipherText += "\n";
continue;
}
if (asciival == 9)
{
cipherText += "\t";
continue;
}
if(asciival < 65 || asciival > 90)
{
cipherText += instrChar;
continue;
}
int basicInputStringValue = ((int)instrChar) - 65;
char kChar = key[keyIndex];
int basicKeyValue = ((int)kChar) - 65;
int tableEntry = vignereTable[basicInputStringValue,basicKeyValue];
char cChar = (char)(tableEntry + 65);
cipherText += cChar;
keyIndex++;
if (keyIndex == key.Length)
keyIndex = 0;
}
return cipherText;
}
public String DecryptText(String cipherText, String key)
{
int tableRowSize = 26;
int tableColumnSize = 26;
int[,] vignereTable = new int[26, 26];
for (int rows = 0; rows < tableRowSize; rows++)
{
for (int columns = 0; columns < tableColumnSize; columns++)
{
vignereTable[rows, columns] = (rows + columns) % 26;
}
}
cipherText = cipherText.ToUpper();
key = key.ToUpper();
String decipherText = "";
int keyIndex = 0;
for (int ctextIndex = 0; ctextIndex < cipherText.Length; ctextIndex++)
{
char cChar = cipherText[ctextIndex];
int asciival = (int)cChar;
if (cChar == ' ')
{
decipherText += cChar;
continue;
}
if (Char.IsNumber(cChar))
{
decipherText += cChar;
continue;
}
if (Char.IsPunctuation(cChar))
{
decipherText += cChar;
continue;
}
if (asciival == 13)
{
decipherText += "\r";
continue;
}
if (asciival == 10)
{
decipherText += "\n";
continue;
}
if (asciival == 9)
{
decipherText += "\t";
continue;
}
if (asciival < 65 || asciival > 90)
{
decipherText += asciival;
continue;
}
int basicCipherTextValue = ((int)cChar) - 65;
char kChar = key[keyIndex];
int basicKeyValue = ((int)kChar) - 65;
for (int dctIndex = 0; dctIndex < tableColumnSize; dctIndex++)
{
if (vignereTable[basicKeyValue, dctIndex] == basicCipherTextValue)
{
char potcChar = (char)(vignereTable[basicKeyValue, dctIndex] + 65);
char potdChar = (char)(dctIndex + 65);
decipherText += potdChar;
}
}
keyIndex++;
if (keyIndex == key.Length)
keyIndex = 0;
}
return decipherText;
}
}
}
|
||||
TheStack | b5c3d2c7718457901735c60693ec1b557be64c35 | C#code:C# | {"size": 2766, "ext": "cs", "max_stars_repo_path": "CleanArchitecture/src/WebUI/Startup.cs", "max_stars_repo_name": "VeselinBPavlov/clean-architecture-mvc-template", "max_stars_repo_stars_event_min_datetime": "2021-08-29T01:13:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T01:13:54.000Z", "max_issues_repo_path": "CleanArchitecture/src/WebUI/Startup.cs", "max_issues_repo_name": "mpaulohs/clean-architecture-mvc-template", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CleanArchitecture/src/WebUI/Startup.cs", "max_forks_repo_name": "mpaulohs/clean-architecture-mvc-template", "max_forks_repo_forks_event_min_datetime": "2021-08-29T01:13:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-29T01:13:51.000Z"} | {"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": 1.0, "avg_line_length": 35.4615384615, "max_line_length": 106, "alphanum_fraction": 0.6634128706} | using CleanArchitecture.Application;
using CleanArchitecture.Application.Common.Interfaces;
using CleanArchitecture.Infrastructure;
using CleanArchitecture.WebUI.Exstensions;
using CleanArchitecture.WebUI.Filters;
using CleanArchitecture.WebUI.Services;
using FluentValidation.AspNetCore;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace CleanArchitecture.WebUI
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddApplication();
services.AddInfrastructure(Configuration);
services.AddDatabaseDeveloperPageExceptionFilter();
services.AddScoped<ICurrentUserService, CurrentUserService>();
services.AddControllersWithViews(options =>
options.Filters.Add<ServerExceptionFilterAttribute>())
.AddFluentValidation();
services.AddRazorPages();
//services.AddAuthentication(options =>
//{
// options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
// options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
// options.DefaultForbidScheme = CookieAuthenticationDefaults.AuthenticationScheme;
// options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
// options.DefaultSignOutScheme = CookieAuthenticationDefaults.AuthenticationScheme;
// options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
//});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseMigrationsEndPoint();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpointsWithAreas();
}
}
}
|
||||
TheStack | b5c635e24c3dcd4411797ce5abba78794b03b824 | C#code:C# | {"size": 1354, "ext": "cs", "max_stars_repo_path": "src/Cofoundry.Domain/CQS/Framework/Query/IQueryExecutor.cs", "max_stars_repo_name": "BearerPipelineTest/cofoundry", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Cofoundry.Domain/CQS/Framework/Query/IQueryExecutor.cs", "max_issues_repo_name": "BearerPipelineTest/cofoundry", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Cofoundry.Domain/CQS/Framework/Query/IQueryExecutor.cs", "max_forks_repo_name": "BearerPipelineTest/cofoundry", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 37.6111111111, "max_line_length": 103, "alphanum_fraction": 0.6144756278} | using System.Threading.Tasks;
namespace Cofoundry.Domain.CQS
{
/// <summary>
/// Handles the execution IQuery instances.
/// </summary>
public interface IQueryExecutor
{
/// <summary>
/// Handles the execution the specified <paramref name="query"/>.
/// </summary>
/// <param name="query">Query to execute.</param>
Task<TResult> ExecuteAsync<TResult>(IQuery<TResult> query);
/// <summary>
/// Handles the execution the specified <paramref name="query"/>.
/// </summary>
/// <param name="query">Query to execute.</param>
/// <param name="executionContext">
/// Optional custom execution context which can be used to impersonate/elevate permissions
/// or change the execution date.
/// </param>
Task<TResult> ExecuteAsync<TResult>(IQuery<TResult> query, IExecutionContext executionContext);
/// <summary>
/// Handles the execution the specified <paramref name="query"/>.
/// </summary>
/// <param name="query">Query to execute.</param>
/// <param name="userContext">
/// Optional user context which can be used to impersonate/elevate permissions.
/// </param>
Task<TResult> ExecuteAsync<TResult>(IQuery<TResult> query, IUserContext userContext);
}
}
|
||||
TheStack | b5c8c8af9d46b46e31beee4ae200a227680b6b1d | C#code:C# | {"size": 645, "ext": "cs", "max_stars_repo_path": "Assembly-CSharp/Patches/SaveGameData.cs", "max_stars_repo_name": "lukasjuhrich/HollowKnight.Modding", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Assembly-CSharp/Patches/SaveGameData.cs", "max_issues_repo_name": "lukasjuhrich/HollowKnight.Modding", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Assembly-CSharp/Patches/SaveGameData.cs", "max_forks_repo_name": "lukasjuhrich/HollowKnight.Modding", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 25.8, "max_line_length": 113, "alphanum_fraction": 0.7162790698} | using System;
using System.Collections.Generic;
using MonoMod;
// ReSharper disable All
#pragma warning disable 1591
namespace Modding.Patches
{
[MonoModPatch("global::SaveGameData")]
public class SaveGameData : global::SaveGameData
{
[Obsolete("PolymorphicModData is used now.")]
public ModSettingsDictionary modData;
public Dictionary<string, string> PolymorphicModData;
[MonoModIgnore]
public SaveGameData(global::PlayerData playerData, SceneData sceneData) : base(playerData, sceneData) { }
public SerializableStringDictionary LoadedMods;
public string Name;
}
} |
||||
TheStack | b5c8fb076ddba79c43cd939fcfe2ad6e3b67ee04 | C#code:C# | {"size": 351, "ext": "cs", "max_stars_repo_path": "ReferencedDependency/GenericDependency.cs", "max_stars_repo_name": "remogloor/Equals", "max_stars_repo_stars_event_min_datetime": "2022-03-22T02:10:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T02:10:53.000Z", "max_issues_repo_path": "ReferencedDependency/GenericDependency.cs", "max_issues_repo_name": "planetarium/Equals4.Foldy", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ReferencedDependency/GenericDependency.cs", "max_forks_repo_name": "planetarium/Equals4.Foldy", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 19.5, "max_line_length": 52, "alphanum_fraction": 0.6239316239} | using System.Collections;
using System.Collections.Generic;
public struct GenericDependency<T> : IEnumerable<T>
{
public IEnumerator<T> GetEnumerator()
{
yield return (T)(object)Prop;
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public int Prop { get; set; }
}
|
||||
TheStack | b5ca521b86575459eded7c429043322b64d4b446 | C#code:C# | {"size": 2339, "ext": "cs", "max_stars_repo_path": "tests/LicenseManager.Tests/Repositories/InMemoryLicenseRepositoryTests.cs", "max_stars_repo_name": "MaciejGrodecki/LicenseManager", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tests/LicenseManager.Tests/Repositories/InMemoryLicenseRepositoryTests.cs", "max_issues_repo_name": "MaciejGrodecki/LicenseManager", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/LicenseManager.Tests/Repositories/InMemoryLicenseRepositoryTests.cs", "max_forks_repo_name": "MaciejGrodecki/LicenseManager", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 29.9871794872, "max_line_length": 99, "alphanum_fraction": 0.6259085079} | using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using LicenseManager.Core.Domain;
using LicenseManager.Core.Repositories;
using LicenseManager.Infrastructure.Repositories;
using Xunit;
namespace LicenseManager.Tests.Repositories
{
public class InMemoryLicenseRepositoryTests
{
private readonly ILicenseRepository _repository;
private static readonly LicenseType _licenseType = new LicenseType(Guid.NewGuid(), "OEM");
private static readonly License _license = new License(
"MS Office 2010", 10, _licenseType.LicenseTypeId, DateTime.Now, "1234-5678-AA18");
public InMemoryLicenseRepositoryTests()
{
//Arrange
_repository = new InMemoryLicenseRepository();
}
[Fact]
public async Task When_adding_new_license_it_should_be_added_correctly_to_the_collection()
{
//Act
await _repository.AddAsync(_license);
//Assert
var existingLicense = await _repository.GetAsync(_license.LicenseId);
Assert.Equal(_license, existingLicense);
}
[Fact]
public async Task Invoking_BrowseAsync_should_return_collection_of_license_objects()
{
//Act
var licenses = await _repository.BrowseAsync();
//Assert
Assert.IsType<HashSet<License>>(licenses);
}
[Fact]
public async Task Invoking_GetAsync_with_licenseId_parameter_should_return_license_object()
{
//Arrange
await _repository.AddAsync(_license);
//Act
var existingLicense = await _repository.GetAsync(_license.LicenseId);
//Assert
Assert.IsType(typeof(License), existingLicense);
Assert.Equal(_license, existingLicense);
}
[Fact]
public async Task Invoking_RemoveAsync_should_remove_license_object_from_collection()
{
//Arrange
await _repository.AddAsync(_license);
//Act
await _repository.RemoveAsync(_license);
var license = await _repository.GetAsync(_license.LicenseId);
//Assert
Assert.Null(license);
}
}
} |
||||
TheStack | b5cb1d7963dbeef4a7fd56eaa37db62a34f6d9b0 | C#code:C# | {"size": 17202, "ext": "cs", "max_stars_repo_path": "src/Test/winswTests/ServiceDescriptorTests.cs", "max_stars_repo_name": "buokae/winsw", "max_stars_repo_stars_event_min_datetime": "2020-03-11T15:11:06.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-11T15:11:06.000Z", "max_issues_repo_path": "src/Test/winswTests/ServiceDescriptorTests.cs", "max_issues_repo_name": "buokae/winsw", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Test/winswTests/ServiceDescriptorTests.cs", "max_forks_repo_name": "buokae/winsw", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 38.5695067265, "max_line_length": 126, "alphanum_fraction": 0.5375537728} | using System;
using System.Diagnostics;
using NUnit.Framework;
using winsw;
using winswTests.Util;
using WMI;
namespace winswTests
{
[TestFixture]
public class ServiceDescriptorTests
{
private ServiceDescriptor _extendedServiceDescriptor;
private const string ExpectedWorkingDirectory = @"Z:\Path\SubPath";
private const string Username = "User";
private const string Password = "Password";
private const string Domain = "Domain";
private const string AllowServiceAccountLogonRight = "true";
[SetUp]
public void SetUp()
{
string seedXml =
$@"<service>
<id>service.exe</id>
<name>Service</name>
<description>The service.</description>
<executable>node.exe</executable>
<arguments>My Arguments</arguments>
<logmode>rotate</logmode>
<serviceaccount>
<domain>{Domain}</domain>
<user>{Username}</user>
<password>{Password}</password>
<allowservicelogon>{AllowServiceAccountLogonRight}</allowservicelogon>
</serviceaccount>
<workingdirectory>{ExpectedWorkingDirectory}</workingdirectory>
<logpath>C:\logs</logpath>
</service>";
_extendedServiceDescriptor = ServiceDescriptor.FromXML(seedXml);
}
[Test]
public void DefaultStartMode()
{
Assert.That(_extendedServiceDescriptor.StartMode, Is.EqualTo(StartMode.Automatic));
}
[Test]
public void IncorrectStartMode()
{
string seedXml =
$@"<service>
<id>service.exe</id>
<name>Service</name>
<description>The service.</description>
<executable>node.exe</executable>
<arguments>My Arguments</arguments>
<startmode>rotate</startmode>
<logmode>rotate</logmode>
<serviceaccount>
<domain>{Domain}</domain>
<user>{Username}</user>
<password>{Password}</password>
<allowservicelogon>{AllowServiceAccountLogonRight}</allowservicelogon>
</serviceaccount>
<workingdirectory>{ExpectedWorkingDirectory}</workingdirectory>
<logpath>C:\logs</logpath>
</service>";
_extendedServiceDescriptor = ServiceDescriptor.FromXML(seedXml);
Assert.Throws<ArgumentException>(() => _ = _extendedServiceDescriptor.StartMode);
}
[Test]
public void ChangedStartMode()
{
string seedXml =
$@"<service>
<id>service.exe</id>
<name>Service</name>
<description>The service.</description>
<executable>node.exe</executable>
<arguments>My Arguments</arguments>
<startmode>manual</startmode>
<logmode>rotate</logmode>
<serviceaccount>
<domain>{Domain}</domain>
<user>{Username}</user>
<password>{Password}</password>
<allowservicelogon>{AllowServiceAccountLogonRight}</allowservicelogon>
</serviceaccount>
<workingdirectory>{ExpectedWorkingDirectory}</workingdirectory>
<logpath>C:\logs</logpath>
</service>";
_extendedServiceDescriptor = ServiceDescriptor.FromXML(seedXml);
Assert.That(_extendedServiceDescriptor.StartMode, Is.EqualTo(StartMode.Manual));
}
[Test]
public void VerifyWorkingDirectory()
{
Debug.WriteLine("_extendedServiceDescriptor.WorkingDirectory :: " + _extendedServiceDescriptor.WorkingDirectory);
Assert.That(_extendedServiceDescriptor.WorkingDirectory, Is.EqualTo(ExpectedWorkingDirectory));
}
[Test]
public void VerifyServiceLogonRight()
{
Assert.That(_extendedServiceDescriptor.AllowServiceAcountLogonRight, Is.EqualTo(true));
}
[Test]
public void VerifyUsername()
{
Debug.WriteLine("_extendedServiceDescriptor.WorkingDirectory :: " + _extendedServiceDescriptor.WorkingDirectory);
Assert.That(_extendedServiceDescriptor.ServiceAccountUser, Is.EqualTo(Domain + "\\" + Username));
}
[Test]
public void VerifyPassword()
{
Debug.WriteLine("_extendedServiceDescriptor.WorkingDirectory :: " + _extendedServiceDescriptor.WorkingDirectory);
Assert.That(_extendedServiceDescriptor.ServiceAccountPassword, Is.EqualTo(Password));
}
[Test]
public void Priority()
{
var sd = ServiceDescriptor.FromXML("<service><id>test</id><priority>normal</priority></service>");
Assert.That(sd.Priority, Is.EqualTo(ProcessPriorityClass.Normal));
sd = ServiceDescriptor.FromXML("<service><id>test</id><priority>idle</priority></service>");
Assert.That(sd.Priority, Is.EqualTo(ProcessPriorityClass.Idle));
sd = ServiceDescriptor.FromXML("<service><id>test</id></service>");
Assert.That(sd.Priority, Is.EqualTo(ProcessPriorityClass.Normal));
}
[Test]
public void StopParentProcessFirstIsFalseByDefault()
{
Assert.False(_extendedServiceDescriptor.StopParentProcessFirst);
}
[Test]
public void CanParseStopParentProcessFirst()
{
const string seedXml = "<service>"
+ "<stopparentprocessfirst>true</stopparentprocessfirst>"
+ "</service>";
var serviceDescriptor = ServiceDescriptor.FromXML(seedXml);
Assert.True(serviceDescriptor.StopParentProcessFirst);
}
[Test]
public void CanParseStopTimeout()
{
const string seedXml = "<service>"
+ "<stoptimeout>60sec</stoptimeout>"
+ "</service>";
var serviceDescriptor = ServiceDescriptor.FromXML(seedXml);
Assert.That(serviceDescriptor.StopTimeout, Is.EqualTo(TimeSpan.FromSeconds(60)));
}
[Test]
public void CanParseStopTimeoutFromMinutes()
{
const string seedXml = "<service>"
+ "<stoptimeout>10min</stoptimeout>"
+ "</service>";
var serviceDescriptor = ServiceDescriptor.FromXML(seedXml);
Assert.That(serviceDescriptor.StopTimeout, Is.EqualTo(TimeSpan.FromMinutes(10)));
}
[Test]
public void CanParseLogname()
{
const string seedXml = "<service>"
+ "<logname>MyTestApp</logname>"
+ "</service>";
var serviceDescriptor = ServiceDescriptor.FromXML(seedXml);
Assert.That(serviceDescriptor.LogName, Is.EqualTo("MyTestApp"));
}
[Test]
public void CanParseOutfileDisabled()
{
const string seedXml = "<service>"
+ "<outfiledisabled>true</outfiledisabled>"
+ "</service>";
var serviceDescriptor = ServiceDescriptor.FromXML(seedXml);
Assert.That(serviceDescriptor.OutFileDisabled, Is.EqualTo(true));
}
[Test]
public void CanParseErrfileDisabled()
{
const string seedXml = "<service>"
+ "<errfiledisabled>true</errfiledisabled>"
+ "</service>";
var serviceDescriptor = ServiceDescriptor.FromXML(seedXml);
Assert.That(serviceDescriptor.ErrFileDisabled, Is.EqualTo(true));
}
[Test]
public void CanParseOutfilePattern()
{
const string seedXml = "<service>"
+ "<outfilepattern>.out.test.log</outfilepattern>"
+ "</service>";
var serviceDescriptor = ServiceDescriptor.FromXML(seedXml);
Assert.That(serviceDescriptor.OutFilePattern, Is.EqualTo(".out.test.log"));
}
[Test]
public void CanParseErrfilePattern()
{
const string seedXml = "<service>"
+ "<errfilepattern>.err.test.log</errfilepattern>"
+ "</service>";
var serviceDescriptor = ServiceDescriptor.FromXML(seedXml);
Assert.That(serviceDescriptor.ErrFilePattern, Is.EqualTo(".err.test.log"));
}
[Test]
public void LogModeRollBySize()
{
const string seedXml = "<service>"
+ "<logpath>c:\\</logpath>"
+ "<log mode=\"roll-by-size\">"
+ "<sizeThreshold>112</sizeThreshold>"
+ "<keepFiles>113</keepFiles>"
+ "</log>"
+ "</service>";
var serviceDescriptor = ServiceDescriptor.FromXML(seedXml);
serviceDescriptor.BaseName = "service";
var logHandler = serviceDescriptor.LogHandler as SizeBasedRollingLogAppender;
Assert.NotNull(logHandler);
Assert.That(logHandler.SizeTheshold, Is.EqualTo(112 * 1024));
Assert.That(logHandler.FilesToKeep, Is.EqualTo(113));
}
[Test]
public void LogModeRollByTime()
{
const string seedXml = "<service>"
+ "<logpath>c:\\</logpath>"
+ "<log mode=\"roll-by-time\">"
+ "<period>7</period>"
+ "<pattern>log pattern</pattern>"
+ "</log>"
+ "</service>";
var serviceDescriptor = ServiceDescriptor.FromXML(seedXml);
serviceDescriptor.BaseName = "service";
var logHandler = serviceDescriptor.LogHandler as TimeBasedRollingLogAppender;
Assert.NotNull(logHandler);
Assert.That(logHandler.Period, Is.EqualTo(7));
Assert.That(logHandler.Pattern, Is.EqualTo("log pattern"));
}
[Test]
public void LogModeRollBySizeTime()
{
const string seedXml = "<service>"
+ "<logpath>c:\\</logpath>"
+ "<log mode=\"roll-by-size-time\">"
+ "<sizeThreshold>10240</sizeThreshold>"
+ "<pattern>yyyy-MM-dd</pattern>"
+ "<autoRollAtTime>00:00:00</autoRollAtTime>"
+ "</log>"
+ "</service>";
var serviceDescriptor = ServiceDescriptor.FromXML(seedXml);
serviceDescriptor.BaseName = "service";
var logHandler = serviceDescriptor.LogHandler as RollingSizeTimeLogAppender;
Assert.NotNull(logHandler);
Assert.That(logHandler.SizeTheshold, Is.EqualTo(10240 * 1024));
Assert.That(logHandler.FilePattern, Is.EqualTo("yyyy-MM-dd"));
Assert.That(logHandler.AutoRollAtTime, Is.EqualTo((TimeSpan?)new TimeSpan(0, 0, 0)));
}
[Test]
public void VerifyServiceLogonRightGraceful()
{
const string seedXml = "<service>"
+ "<serviceaccount>"
+ "<domain>" + Domain + "</domain>"
+ "<user>" + Username + "</user>"
+ "<password>" + Password + "</password>"
+ "<allowservicelogon>true1</allowservicelogon>"
+ "</serviceaccount>"
+ "</service>";
var serviceDescriptor = ServiceDescriptor.FromXML(seedXml);
Assert.That(serviceDescriptor.AllowServiceAcountLogonRight, Is.EqualTo(false));
}
[Test]
public void VerifyServiceLogonRightOmitted()
{
const string seedXml = "<service>"
+ "<serviceaccount>"
+ "<domain>" + Domain + "</domain>"
+ "<user>" + Username + "</user>"
+ "<password>" + Password + "</password>"
+ "</serviceaccount>"
+ "</service>";
var serviceDescriptor = ServiceDescriptor.FromXML(seedXml);
Assert.That(serviceDescriptor.AllowServiceAcountLogonRight, Is.EqualTo(false));
}
[Test]
public void VerifyWaitHint_FullXML()
{
var sd = ConfigXmlBuilder.create()
.WithTag("waithint", "20 min")
.ToServiceDescriptor(true);
Assert.That(sd.WaitHint, Is.EqualTo(TimeSpan.FromMinutes(20)));
}
/// <summary>
/// Test for https://github.com/kohsuke/winsw/issues/159
/// </summary>
[Test]
public void VerifyWaitHint_XMLWithoutVersion()
{
var sd = ConfigXmlBuilder.create(printXMLVersion: false)
.WithTag("waithint", "21 min")
.ToServiceDescriptor(true);
Assert.That(sd.WaitHint, Is.EqualTo(TimeSpan.FromMinutes(21)));
}
[Test]
public void VerifyWaitHint_XMLWithoutComment()
{
var sd = ConfigXmlBuilder.create(xmlComment: null)
.WithTag("waithint", "22 min")
.ToServiceDescriptor(true);
Assert.That(sd.WaitHint, Is.EqualTo(TimeSpan.FromMinutes(22)));
}
[Test]
public void VerifyWaitHint_XMLWithoutVersionAndComment()
{
var sd = ConfigXmlBuilder.create(xmlComment: null, printXMLVersion: false)
.WithTag("waithint", "23 min")
.ToServiceDescriptor(true);
Assert.That(sd.WaitHint, Is.EqualTo(TimeSpan.FromMinutes(23)));
}
[Test]
public void VerifySleepTime()
{
var sd = ConfigXmlBuilder.create().WithTag("sleeptime", "3 hrs").ToServiceDescriptor(true);
Assert.That(sd.SleepTime, Is.EqualTo(TimeSpan.FromHours(3)));
}
[Test]
public void VerifyResetFailureAfter()
{
var sd = ConfigXmlBuilder.create().WithTag("resetfailure", "75 sec").ToServiceDescriptor(true);
Assert.That(sd.ResetFailureAfter, Is.EqualTo(TimeSpan.FromSeconds(75)));
}
[Test]
public void VerifyStopTimeout()
{
var sd = ConfigXmlBuilder.create().WithTag("stoptimeout", "35 secs").ToServiceDescriptor(true);
Assert.That(sd.StopTimeout, Is.EqualTo(TimeSpan.FromSeconds(35)));
}
/// <summary>
/// https://github.com/kohsuke/winsw/issues/178
/// </summary>
[Test]
public void Arguments_LegacyParam()
{
var sd = ConfigXmlBuilder.create().WithTag("arguments", "arg").ToServiceDescriptor(true);
Assert.That(sd.Arguments, Is.EqualTo("arg"));
}
[Test]
public void Arguments_NewParam_Single()
{
var sd = ConfigXmlBuilder.create()
.WithTag("argument", "--arg1=2")
.ToServiceDescriptor(true);
Assert.That(sd.Arguments, Is.EqualTo(" --arg1=2"));
}
[Test]
public void Arguments_NewParam_MultipleArgs()
{
var sd = ConfigXmlBuilder.create()
.WithTag("argument", "--arg1=2")
.WithTag("argument", "--arg2=123")
.WithTag("argument", "--arg3=null")
.ToServiceDescriptor(true);
Assert.That(sd.Arguments, Is.EqualTo(" --arg1=2 --arg2=123 --arg3=null"));
}
/// <summary>
/// Ensures that the new single-argument field has a higher priority.
/// </summary>
[Test]
public void Arguments_Bothparam_Priorities()
{
var sd = ConfigXmlBuilder.create()
.WithTag("arguments", "--arg1=2 --arg2=3")
.WithTag("argument", "--arg2=123")
.WithTag("argument", "--arg3=null")
.ToServiceDescriptor(true);
Assert.That(sd.Arguments, Is.EqualTo(" --arg2=123 --arg3=null"));
}
[TestCase(true)]
[TestCase(false)]
public void DelayedStart_RoundTrip(bool enabled)
{
var bldr = ConfigXmlBuilder.create();
if (enabled)
{
bldr = bldr.WithDelayedAutoStart();
}
var sd = bldr.ToServiceDescriptor();
Assert.That(sd.DelayedAutoStart, Is.EqualTo(enabled));
}
}
}
|
||||
TheStack | b5cc5154c643ba301f5487aa6d4dfb986776ce53 | C#code:C# | {"size": 2098, "ext": "cs", "max_stars_repo_path": "Wbs.Everdigm.Web/Wbs.Everdigm.Web/main/terminal_testing_content.aspx.cs", "max_stars_repo_name": "wanbangsoftware/Everdigm", "max_stars_repo_stars_event_min_datetime": "2017-10-18T16:56:16.000Z", "max_stars_repo_stars_event_max_datetime": "2017-10-18T16:56:16.000Z", "max_issues_repo_path": "Wbs.Everdigm.Web/Wbs.Everdigm.Web/main/terminal_testing_content.aspx.cs", "max_issues_repo_name": "wanbangsoftware/Everdigm", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Wbs.Everdigm.Web/Wbs.Everdigm.Web/main/terminal_testing_content.aspx.cs", "max_forks_repo_name": "wanbangsoftware/Everdigm", "max_forks_repo_forks_event_min_datetime": "2019-10-08T20:02:27.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-08T20:02:27.000Z"} | {"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": 1.0, "avg_line_length": 36.1724137931, "max_line_length": 115, "alphanum_fraction": 0.4961868446} | using System;
using System.Linq;
using Wbs.Everdigm.BLL;
using Wbs.Everdigm.Database;
namespace Wbs.Everdigm.Web.main
{
public partial class terminal_testing_content : BasePage
{
protected override void Page_Load(object sender, EventArgs e)
{
base.Page_Load(sender, e);
ShowTerminalInfo();
}
/// <summary>
/// 终端信息业务处理逻辑
/// </summary>
private TerminalBLL BLLInstance { get { return new TerminalBLL(); } }
private EquipmentBLL EquipmentInstance { get { return new EquipmentBLL(); } }
/// <summary>
/// 格式化显示终端信息
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
private string ToString(TB_Terminal obj)
{
return string.Format("{0}(Sim card no.: {1}, Satellite no.: {2})", obj.Number, obj.Sim, obj.Satellite);
}
/// <summary>
/// 显示正在测试的终端的基本信息
/// </summary>
private void ShowTerminalInfo()
{
if (string.IsNullOrEmpty(_key)) {
ShowNotification("", "Could not begin the test program, paramenter is null.", false);
}
else
{
var t = BLLInstance.Find(f => f.Number.Equals(_key) && f.Delete == false);
if (null != t)
{
var mac = t.TB_Equipment.FirstOrDefault();
terminalInfo.InnerHtml = t.Number;
var link = (LinkType)t.OnlineStyle;
terminalContent.Value = "Sim card: " + t.Sim + "<br />Satellite: " +
((null == t.Satellite) ? "not install" : t.TB_Satellite.CardNo) + "<br />Equipment: " +
(null == mac ? "" : EquipmentInstance.GetFullNumber(mac)) + "<br />Link: " + link;
terminalCardNumber.Value = t.Sim;
}
else
{
ShowNotification("", "No terminal like \"" + _key + "\" exists.", false);
}
}
}
}
} |
||||
TheStack | b5cca59780133d6e0daea0fc5b96c32981710107 | C#code:C# | {"size": 2729, "ext": "cs", "max_stars_repo_path": "root/programs/CS/Frameworks/Infrastructure/Business/Util/MyUserInfo.cs", "max_stars_repo_name": "OpenTouryoProject/OpenTouryo", "max_stars_repo_stars_event_min_datetime": "2015-02-10T14:39:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T23:56:20.000Z", "max_issues_repo_path": "root/programs/CS/Frameworks/Infrastructure/Business/Util/MyUserInfo.cs", "max_issues_repo_name": "OpenTouryoProject/OpenTouryo", "max_issues_repo_issues_event_min_datetime": "2015-01-13T07:28:11.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T10:43:31.000Z", "max_forks_repo_path": "root/programs/CS/Frameworks/Infrastructure/Business/Util/MyUserInfo.cs", "max_forks_repo_name": "OpenTouryoProject/OpenTouryo", "max_forks_repo_forks_event_min_datetime": "2015-01-07T09:09:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-17T06:47:32.000Z"} | {"max_stars_count": 60.0, "max_issues_count": 302.0, "max_forks_count": 35.0, "avg_line_length": 30.3222222222, "max_line_length": 84, "alphanum_fraction": 0.4752656651} | //**********************************************************************************
//* Copyright (C) 2007,2016 Hitachi Solutions,Ltd.
//**********************************************************************************
#region Apache License
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
//**********************************************************************************
//* クラス名 :MyUserInfo
//* クラス日本語名 :ユーザ情報クラス(必要なコンテキスト情報を追加)(テンプレート)
//*
//* 作成者 :生技 西野
//* 更新履歴 :
//*
//* 日時 更新者 内容
//* ---------- ---------------- -------------------------------------------------
//* 20xx/xx/xx XX XX 新規作成(テンプレート)
//* 2010/09/24 西野 大介 フィールドの追加
//* 2010/09/24 西野 大介 共通引数クラス内にユーザ情報を格納したので
//**********************************************************************************
using System;
using Touryo.Infrastructure.Framework.Util;
namespace Touryo.Infrastructure.Business.Util
{
/// <summary>ユーザ情報クラス(必要なコンテキスト情報を追加)</summary>
/// <remarks>自由に(拡張して)利用できる。</remarks>
[Serializable()]
public class MyUserInfo : UserInfo
{
/// <summary>ユーザ名</summary>
private string _userName = "";
/// <summary>IPアドレス</summary>
private string _ipAddress;
/// <summary>コンストラクタ</summary>
/// <param name="userName">ユーザ名</param>
/// <param name="ipAddress">IPアドレス</param>
/// <remarks>自由に利用できる。</remarks>
public MyUserInfo(string userName, string ipAddress)
{
this._userName = userName;
this._ipAddress = ipAddress;
}
/// <summary>ユーザ名</summary>
/// <remarks>自由に利用できる。</remarks>
public string UserName
{
set
{
this._userName = value;
}
get
{
return this._userName;
}
}
/// <summary>IPアドレス</summary>
/// <remarks>自由に利用できる。</remarks>
public string IPAddress
{
set
{
this._ipAddress = value;
}
get
{
return this._ipAddress;
}
}
}
}
|
||||
TheStack | b5ce17fb055166145cc41deba5932e4e31a9b43d | C#code:C# | {"size": 14828, "ext": "cs", "max_stars_repo_path": "Tests/Tests.SystematicTesting/Rewriting/TaskExceptionFilterTests.cs", "max_stars_repo_name": "arunt1204/coyote-rl", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tests/Tests.SystematicTesting/Rewriting/TaskExceptionFilterTests.cs", "max_issues_repo_name": "arunt1204/coyote-rl", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tests/Tests.SystematicTesting/Rewriting/TaskExceptionFilterTests.cs", "max_forks_repo_name": "arunt1204/coyote-rl", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 33.2466367713, "max_line_length": 125, "alphanum_fraction": 0.5397221473} | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.Coyote.SystematicTesting.Tests.Exceptions
{
/// <summary>
/// Tests that we can insert an <see cref="ExecutionCanceledException"/> filter.
/// </summary>
public class TaskExceptionFilterTests : BaseSystematicTest
{
public TaskExceptionFilterTests(ITestOutputHelper output)
: base(output)
{
}
private static void TestFilterMethod()
{
// Test catch Exception
try
{
throw new ExecutionCanceledException();
}
catch (Exception ex)
{
Debug.WriteLine(ex.GetType().FullName);
}
}
[Fact(Timeout = 5000)]
public void TestAddExceptionFilter()
{
// The rewritten code should add a !(e is ExecutionCanceledException) filter
// which should allow this exception to escape the catch block.
this.RunWithException<ExecutionCanceledException>(TestFilterMethod);
}
private static void TestFilterMethod2()
{
// Test catch RuntimeException
try
{
throw new ExecutionCanceledException();
}
catch (RuntimeException ex)
{
Debug.WriteLine(ex.GetType().FullName);
}
}
[Fact(Timeout = 5000)]
public void TestAddExceptionFilter2()
{
// The rewritten code should add a !(e is ExecutionCanceledException) filter
// which should allow this exception to escape the catch block.
this.RunWithException<ExecutionCanceledException>(TestFilterMethod2);
}
private static void TestFilterMethod3()
{
// Test catch all
try
{
throw new ExecutionCanceledException();
}
catch
{
Debug.WriteLine("caught");
}
}
[Fact(Timeout = 5000)]
public void TestAddExceptionFilter3()
{
// The rewritten code should add a !(e is ExecutionCanceledException) filter
// which should allow this exception to escape the catch block.
this.RunWithException<ExecutionCanceledException>(TestFilterMethod3);
}
private static void TestFilterMethod4()
{
// Test filter is unmodified if it is already correct!
try
{
throw new ExecutionCanceledException();
}
catch (Exception ex) when (!(ex is ExecutionCanceledException))
{
Debug.WriteLine(ex.GetType().FullName);
}
}
[Fact(Timeout = 5000)]
public void TestAddExceptionFilter4()
{
// The non-rewritten code should allow the ExecutionCanceledException through
// and the rewritten code should be the same because the code should not be rewritten.
this.RunWithException<ExecutionCanceledException>(TestFilterMethod4);
}
private static void TestFilterMethod5()
{
// Test more interesting filter is also unmodified if it is already correct!
try
{
throw new ExecutionCanceledException();
}
catch (Exception ex) when (!(ex is NullReferenceException) && !(ex is ExecutionCanceledException))
{
Debug.WriteLine(ex.GetType().FullName);
}
}
[Fact(Timeout = 5000)]
public void TestAddExceptionFilter5()
{
// The non-rewritten code should allow the ExecutionCanceledException through
// and the rewritten code should be the same because the code should not be rewritten.
this.RunWithException<ExecutionCanceledException>(TestFilterMethod5);
}
private static void TestFilterMethod6()
{
// Test more interesting filter is also unmodified if it is already correct!
// Test we can parse a slightly different order of expressions in the filter.
try
{
throw new ExecutionCanceledException();
}
catch (Exception ex) when (!(ex is ExecutionCanceledException) && !(ex is NullReferenceException))
{
Debug.WriteLine(ex.GetType().FullName);
}
}
[Fact(Timeout = 5000)]
public void TestAddExceptionFilter6()
{
// The non-rewritten code should allow the ExecutionCanceledException through
// and the rewritten code should be the same because the code should not be rewritten.
this.RunWithException<ExecutionCanceledException>(TestFilterMethod6);
}
private static void TestComplexFilterMethod()
{
// This test case we cannot yet handle because filter is too complex.
// This '|| debugging' expression causes the filter to catch ExecutionCanceledException
// which is bad, but this is hard to fix.
bool debugging = true;
try
{
throw new ExecutionCanceledException();
}
catch (Exception ex) when (!(ex is ExecutionCanceledException) || debugging)
{
Debug.WriteLine(ex.GetType().FullName);
}
}
[Fact(Timeout = 5000)]
public void TestEditComplexFilter()
{
// The rewritten code should add a !(e is ExecutionCanceledException) filter
// which should allow this exception to escape the catch block.
this.RunWithException<ExecutionCanceledException>(TestComplexFilterMethod);
}
private static void TestComplexFilterMethod2()
{
// This test case we cannot yet handle because filter is too complex.
// This '&& debugging' expression causes the filter to catch ExecutionCanceledException
// which is bad, but this is hard to fix.
bool debugging = true;
try
{
throw new ExecutionCanceledException();
}
catch (Exception ex) when (!(ex is NullReferenceException) && debugging)
{
Debug.WriteLine(ex.GetType().FullName);
}
}
[Fact(Timeout = 5000)]
public void TestEditComplexFilter2()
{
// The rewritten code should add a !(e is ExecutionCanceledException) filter
// which should allow this exception to escape the catch block.
this.RunWithException<ExecutionCanceledException>(TestComplexFilterMethod2);
}
private static void TestComplexFilterMethod3()
{
try
{
throw new ExecutionCanceledException();
}
catch (Exception ex) when (!(ex is NullReferenceException))
{
Debug.WriteLine(ex.GetType().FullName);
}
}
[Fact(Timeout = 5000)]
public void TestEditComplexFilter3()
{
// The rewritten code should add a !(e is ExecutionCanceledException) filter
// which should allow this exception to escape the catch block.
this.RunWithException<ExecutionCanceledException>(TestComplexFilterMethod3);
}
private static void TestComplexFilterMethod4()
{
// Test a crazy filter expression we cannot even parse...
int x = 10;
string suffix = "bad";
try
{
Task.Run(() =>
{
throw new ExecutionCanceledException();
}).Wait();
}
catch (Exception ex) when (ex.GetType().Name != (x > 10 ? "Foo" : "Bar" + suffix))
{
Debug.WriteLine(ex.GetType().FullName);
}
}
[Fact(Timeout = 5000)]
public void TestEditComplexFilter4()
{
// The rewritten code should add a !(e is ExecutionCanceledException) filter
// which should allow this exception to escape the catch block.
this.RunWithException<ExecutionCanceledException>(TestComplexFilterMethod4);
}
private static void TestRethrowMethod()
{
// Test catch all, but it is ok because it does a rethrow,
// so this code should be unmodified.
try
{
throw new ExecutionCanceledException();
}
catch (Exception)
{
throw;
}
}
[Fact(Timeout = 5000)]
public void TestIgnoreRethrowCase()
{
// The non-rewritten code should rethrow the exception
// and the rewritten code should be the same because the code should not be rewritten.
this.RunWithException<ExecutionCanceledException>(TestRethrowMethod);
}
private static void TestRethrowMethod2()
{
// Test catch all with specific filter for ExecutionCanceledException,
// but it is ok because it does a rethrow, so this code should be unmodified.
try
{
throw new ExecutionCanceledException();
}
catch (Exception ex) when (ex is ExecutionCanceledException)
{
throw;
}
}
[Fact(Timeout = 5000)]
public void TestIgnoreRethrowCase2()
{
// The non-rewritten code should rethrow the exception
// and the rewritten code should be the same because the code should not be rewritten.
this.RunWithException<ExecutionCanceledException>(TestRethrowMethod2);
}
private static void TestConditionalTryCatchMethod()
{
// Test conditional branch around try/catch is fixed up when the rewritten code
// causes this branch instruction to have to be modified from brtrue_s to brtrue.
StringBuilder sb = new StringBuilder();
bool something = true;
if (something)
{
try
{
sb.AppendLine(string.Format("This is the try block {0}, {1}", "foo", 123));
throw new InvalidOperationException();
}
catch (Exception ex)
{
sb.AppendLine(string.Format("This is the catch block {0}, {1}", ex.Message, 123));
if (ex.InnerException != null)
{
sb.AppendLine(string.Format("This is the inner exception {0}, {1}", ex.InnerException.Message, 123));
}
throw;
}
}
}
[Fact(Timeout = 5000)]
public void TestConditionalTryCatch()
{
this.RunWithException<InvalidOperationException>(TestConditionalTryCatchMethod);
}
private static void TestMultiCatchBlockMethod()
{
// Test we can handle multiple catch blocks.
try
{
throw new InvalidOperationException();
}
catch (InvalidOperationException)
{
throw;
}
catch (Exception)
{
Console.WriteLine("exception handled");
}
}
[Fact(Timeout = 5000)]
public void TestMultiCatchBlock()
{
this.RunWithException<InvalidOperationException>(TestMultiCatchBlockMethod);
}
private static void TestMultiCatchFilterMethod()
{
// Test we can handle multiple catch blocks with a filter.
try
{
throw new InvalidOperationException();
}
catch (InvalidOperationException)
{
throw;
}
catch (Exception e) when (!(e is NullReferenceException))
{
Console.WriteLine("exception handled");
}
}
[Fact(Timeout = 5000)]
public void TestMultiCatchFilter()
{
this.RunWithException<InvalidOperationException>(TestMultiCatchFilterMethod);
}
private static void TestMultiCatchBlockWithFilterMethod()
{
// Test we can handle multiple catch blocks with a filter.
try
{
throw new InvalidOperationException();
}
catch (InvalidOperationException)
{
throw;
}
catch (Exception e) when (!(e is NullReferenceException))
{
Console.WriteLine("exception handled");
}
catch (NullReferenceException)
{
Console.WriteLine("Don't care!");
}
}
[Fact(Timeout = 5000)]
public void TestMultiCatchBlockWithFilter()
{
this.RunWithException<InvalidOperationException>(TestMultiCatchBlockWithFilterMethod);
}
private static void TestExceptionHandlerInsideLockMethod()
{
object l = new object();
lock (l)
{
try
{
throw new InvalidOperationException();
}
catch (Exception)
{
Console.WriteLine("exception handled");
throw;
}
}
}
[Fact(Timeout = 5000)]
public void TestExceptionHandlerInsideLock()
{
this.RunWithException<InvalidOperationException>(TestExceptionHandlerInsideLockMethod);
}
private static void TestTryUsingTryMethod()
{
try
{
using var s = new StringWriter();
try
{
throw new InvalidOperationException();
}
catch (Exception)
{
s.Close();
throw;
}
}
catch (Exception)
{
Console.WriteLine("exception handled");
}
}
[Fact(Timeout = 5000)]
public void TestTryUsingTry()
{
this.Test(TestTryUsingTryMethod);
}
}
}
|
||||
TheStack | b5cfdf4c7b098ef25aae89ba25d25a9e0566c34e | C#code:C# | {"size": 438, "ext": "cs", "max_stars_repo_path": "Cyberarms.IntrusionDetection.Api/Plugin/PluginTypes.cs", "max_stars_repo_name": "EFTEC/Cyberarms", "max_stars_repo_stars_event_min_datetime": "2018-02-13T22:28:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-31T09:49:01.000Z", "max_issues_repo_path": "Cyberarms.IntrusionDetection.Api/Plugin/PluginTypes.cs", "max_issues_repo_name": "EFTEC/Cyberarms", "max_issues_repo_issues_event_min_datetime": "2018-07-31T17:46:16.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-23T05:45:04.000Z", "max_forks_repo_path": "Cyberarms.IntrusionDetection.Api/Plugin/PluginTypes.cs", "max_forks_repo_name": "EFTEC/Cyberarms", "max_forks_repo_forks_event_min_datetime": "2018-02-13T22:28:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-15T10:10:42.000Z"} | {"max_stars_count": 33.0, "max_issues_count": 16.0, "max_forks_count": 35.0, "avg_line_length": 19.9090909091, "max_line_length": 51, "alphanum_fraction": 0.5502283105} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Cyberarms.IntrusionDetection.Api.Plugin {
/// <summary>
/// Plugin types
/// </summary>
public enum PluginTypes {
/// <summary>
/// Type is agent
/// </summary>
Agent = 0,
/// <summary>
/// Type is Listener
/// </summary>
NotificationListener = 1
}
}
|
||||
TheStack | b5d14eac0d7df4a41d48c2d5d8098943dd84c747 | C#code:C# | {"size": 476, "ext": "cs", "max_stars_repo_path": "src/Uno.UI/UI/Xaml/Shapes/Line.Android.cs", "max_stars_repo_name": "Daoting/uno", "max_stars_repo_stars_event_min_datetime": "2020-07-18T21:13:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-19T08:58:58.000Z", "max_issues_repo_path": "src/Uno.UI/UI/Xaml/Shapes/Line.Android.cs", "max_issues_repo_name": "Daoting/uno", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Uno.UI/UI/Xaml/Shapes/Line.Android.cs", "max_forks_repo_name": "Daoting/uno", "max_forks_repo_forks_event_min_datetime": "2020-02-10T19:31:22.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T19:31:22.000Z"} | {"max_stars_count": 3.0, "max_issues_count": null, "max_forks_count": 1.0, "avg_line_length": 25.0526315789, "max_line_length": 97, "alphanum_fraction": 0.7710084034} | using Windows.Foundation;
using Uno.UI;
namespace Windows.UI.Xaml.Shapes
{
public partial class Line : ArbitraryShapeBase
{
protected override Android.Graphics.Path GetPath(Size availableSize)
{
var output = new Android.Graphics.Path();
output.MoveTo(ViewHelper.LogicalToPhysicalPixels(X1), ViewHelper.LogicalToPhysicalPixels(Y1));
output.LineTo(ViewHelper.LogicalToPhysicalPixels(X2), ViewHelper.LogicalToPhysicalPixels(Y2));
return output;
}
}
}
|
||||
TheStack | b5d211d4cee5a727f7f7152ee00f2f1f4519b6e3 | C#code:C# | {"size": 1480, "ext": "cs", "max_stars_repo_path": "Crypto/CryptoProcessorBuilder.cs", "max_stars_repo_name": "BBGONE/CryptCPTest", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Crypto/CryptoProcessorBuilder.cs", "max_issues_repo_name": "BBGONE/CryptCPTest", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Crypto/CryptoProcessorBuilder.cs", "max_forks_repo_name": "BBGONE/CryptCPTest", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 31.4893617021, "max_line_length": 110, "alphanum_fraction": 0.6047297297} | using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace CryptCPTest.Crypto
{
public class CryptoProcessorBuilder
{
private List<Func<CryptoContext, Task>> inputLine { get; set; }
private List<Func<CryptoContext, Task>> outputLine { get; set; }
public CryptoProcessorBuilder()
{
inputLine = new List<Func<CryptoContext, Task>>();
outputLine = new List<Func<CryptoContext, Task>>();
}
/// <summary>
/// Добавление шагов обработки входящего файла - добавляются в порядке обработки входящего сообщения
/// </summary>
/// <param name="inputFunc"></param>
public void AddInputStep(Func<CryptoContext, Task> inputFunc)
{
inputLine.Add(inputFunc);
}
/// <summary>
/// Добавление шагов обработки исходящего файла - добавляются в порядке обработки исходящего сообщения
/// </summary>
/// <param name="outputFunc"></param>
public void AddOutputStep(Func<CryptoContext, Task> outputFunc)
{
outputLine.Add(outputFunc);
}
/// <summary>
/// Создать CryptoProcessor
/// </summary>
/// <returns></returns>
public CryptoProcessor Build()
{
CryptoProcessor cryptoProcessor = new CryptoProcessor(inputLine.ToArray(), outputLine.ToArray());
return cryptoProcessor;
}
}
}
|
||||
TheStack | b5d2c0daf6d6e5620ba5f3389d8ad78e80a432ab | C#code:C# | {"size": 690, "ext": "cs", "max_stars_repo_path": "Perspex.Base/Platform/PlatformHandle.cs", "max_stars_repo_name": "GeorgeHahn/Perspex", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Perspex.Base/Platform/PlatformHandle.cs", "max_issues_repo_name": "GeorgeHahn/Perspex", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Perspex.Base/Platform/PlatformHandle.cs", "max_forks_repo_name": "GeorgeHahn/Perspex", "max_forks_repo_forks_event_min_datetime": "2019-11-16T00:19:25.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-16T00:19:25.000Z"} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": 1.0, "avg_line_length": 28.75, "max_line_length": 75, "alphanum_fraction": 0.5057971014} | // -----------------------------------------------------------------------
// <copyright file="PlatformHandle.cs" company="Steven Kirk">
// Copyright 2014 MIT Licence. See licence.md for more information.
// </copyright>
// -----------------------------------------------------------------------
namespace Perspex.Platform
{
using System;
public class PlatformHandle : IPlatformHandle
{
public PlatformHandle(IntPtr handle, string descriptor)
{
this.Handle = handle;
this.HandleDescriptor = descriptor;
}
public IntPtr Handle { get; private set; }
public string HandleDescriptor { get; private set; }
}
}
|
||||
TheStack | b5d3159d3193c26fa05d690b1e646be4e12b84ed | C#code:C# | {"size": 3140, "ext": "cs", "max_stars_repo_path": "serdes/Streamiz.Kafka.Net.SchemaRegistry.SerDes.Protobuf/SchemaProtobufSerDes.cs", "max_stars_repo_name": "vimal-sivasubramanian/kafka-streams-dotnet", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "serdes/Streamiz.Kafka.Net.SchemaRegistry.SerDes.Protobuf/SchemaProtobufSerDes.cs", "max_issues_repo_name": "vimal-sivasubramanian/kafka-streams-dotnet", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "serdes/Streamiz.Kafka.Net.SchemaRegistry.SerDes.Protobuf/SchemaProtobufSerDes.cs", "max_forks_repo_name": "vimal-sivasubramanian/kafka-streams-dotnet", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 40.2564102564, "max_line_length": 154, "alphanum_fraction": 0.6439490446} | using Confluent.Kafka;
using Confluent.Kafka.SyncOverAsync;
using Confluent.SchemaRegistry;
using Confluent.SchemaRegistry.Serdes;
using Google.Protobuf;
using Streamiz.Kafka.Net.Errors;
using Streamiz.Kafka.Net.SchemaRegistry.SerDes.Mock;
using Streamiz.Kafka.Net.SerDes;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Streamiz.Kafka.Net.SchemaRegistry.SerDes.Protobuf
{
/// <summary>
/// SerDes for Protobuf
/// </summary>
/// <typeparam name="T"></typeparam>
public class SchemaProtobufSerDes<T> : SchemaSerDes<T> where T : class, IMessage<T>, new()
{
private Confluent.SchemaRegistry.SchemaRegistryConfig GetConfig(ISchemaRegistryConfig config)
{
Confluent.SchemaRegistry.SchemaRegistryConfig c = new Confluent.SchemaRegistry.SchemaRegistryConfig();
c.Url = config.SchemaRegistryUrl;
if (config.SchemaRegistryMaxCachedSchemas.HasValue)
{
c.MaxCachedSchemas = config.SchemaRegistryMaxCachedSchemas;
}
if (config.SchemaRegistryRequestTimeoutMs.HasValue)
{
c.RequestTimeoutMs = config.SchemaRegistryRequestTimeoutMs;
}
return c;
}
private Confluent.SchemaRegistry.Serdes.ProtobufSerializerConfig GetSerializerConfig(ISchemaRegistryConfig config)
{
Confluent.SchemaRegistry.Serdes.ProtobufSerializerConfig c = new Confluent.SchemaRegistry.Serdes.ProtobufSerializerConfig();
if (config.AutoRegisterSchemas.HasValue)
{
c.AutoRegisterSchemas = config.AutoRegisterSchemas;
}
if (config.SubjectNameStrategy.HasValue)
{
c.SubjectNameStrategy = (Confluent.SchemaRegistry.SubjectNameStrategy)config.SubjectNameStrategy.Value;
}
return c;
}
/// <summary>
/// Initialize method with a current context which contains <see cref="IStreamConfig"/>.
/// Can be used to initialize the serdes according to some parameters present in the configuration such as the schema.registry.url
/// </summary>
/// <param name="context">SerDesContext with stream configuration</param>
public override void Initialize(SerDesContext context)
{
if (!isInitialized)
{
if (context.Config is ISchemaRegistryConfig)
{
var schemaConfig = context.Config as ISchemaRegistryConfig;
registryClient = GetSchemaRegistryClient(GetConfig(schemaConfig));
deserializer = new ProtobufDeserializer<T>(schemaConfig as Config);
serializer = new ProtobufSerializer<T>(registryClient, GetSerializerConfig(schemaConfig));
isInitialized = true;
}
else
{
throw new StreamConfigException($"Configuration must inherited from ISchemaRegistryConfig for SchemaProtobufSerDes<{typeof(T).Name}");
}
}
}
}
} |
||||
TheStack | b5d439e1e598b831ffe5b2394baa667b19ff4d60 | C#code:C# | {"size": 829, "ext": "cs", "max_stars_repo_path": "NotifyIconWpf/Extensions.cs", "max_stars_repo_name": "samgrogan/notify-icon.net", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "NotifyIconWpf/Extensions.cs", "max_issues_repo_name": "samgrogan/notify-icon.net", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NotifyIconWpf/Extensions.cs", "max_forks_repo_name": "samgrogan/notify-icon.net", "max_forks_repo_forks_event_min_datetime": "2021-01-05T11:14:22.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-05T11:14:22.000Z"} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": 1.0, "avg_line_length": 26.7419354839, "max_line_length": 94, "alphanum_fraction": 0.5186972256} | using System;
using System.Drawing;
using System.Windows.Media;
using System.Windows;
using System.IO;
namespace NotifyIcon.Wpf
{
internal static class Extensions
{
// Convert an ImageSource to an Icon
public static Icon ToIcon(this ImageSource imageSource)
{
try {
string imageSourcePath = imageSource?.ToString();
if (imageSourcePath != null) {
Uri imageSourceUri = new Uri(imageSourcePath);
Stream iconStream = Application.GetResourceStream(imageSourceUri)?.Stream;
if (iconStream != null) {
return new Icon(iconStream);
}
}
}
catch
{
}
return null;
}
}
}
|
||||
TheStack | b5d5ae909fed46d420aeba941f8b5e63acfe64c7 | C#code:C# | {"size": 342, "ext": "cs", "max_stars_repo_path": "NUnitCheatSheet/NUnitCheatSheet/CustomPropertyAttribute.cs", "max_stars_repo_name": "EntelectCodeDojo/Testing", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "NUnitCheatSheet/NUnitCheatSheet/CustomPropertyAttribute.cs", "max_issues_repo_name": "EntelectCodeDojo/Testing", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NUnitCheatSheet/NUnitCheatSheet/CustomPropertyAttribute.cs", "max_forks_repo_name": "EntelectCodeDojo/Testing", "max_forks_repo_forks_event_min_datetime": "2016-08-02T11:19:41.000Z", "max_forks_repo_forks_event_max_datetime": "2016-08-02T11:19:41.000Z"} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": 1.0, "avg_line_length": 24.4285714286, "max_line_length": 68, "alphanum_fraction": 0.6871345029} | using System;
using NUnit.Framework;
namespace NUnitCheatSheet
{
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public class CustomPropertyAttribute : PropertyAttribute
{
public CustomPropertyAttribute(CustomPropertyValue value)
: base("Custom", value.ToString())
{
}
}
} |
||||
TheStack | b5d5dd0402c2692f21eebf0d900f622343dc1b53 | C#code:C# | {"size": 5370, "ext": "cs", "max_stars_repo_path": "libwasm/Interpret/Variable.cs", "max_stars_repo_name": "jonathanvdc/cs-wasm", "max_stars_repo_stars_event_min_datetime": "2017-06-12T06:53:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-26T18:09:05.000Z", "max_issues_repo_path": "libwasm/Interpret/Variable.cs", "max_issues_repo_name": "jonathanvdc/cs-wasm", "max_issues_repo_issues_event_min_datetime": "2018-10-24T23:41:59.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-26T14:33:06.000Z", "max_forks_repo_path": "libwasm/Interpret/Variable.cs", "max_forks_repo_name": "jonathanvdc/cs-wasm", "max_forks_repo_forks_event_min_datetime": "2017-11-21T00:09:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T04:19:43.000Z"} | {"max_stars_count": 30.0, "max_issues_count": 3.0, "max_forks_count": 5.0, "avg_line_length": 34.8701298701, "max_line_length": 94, "alphanum_fraction": 0.5154562384} | using System;
namespace Wasm.Interpret
{
/// <summary>
/// Describes a WebAssembly variable.
/// </summary>
public sealed class Variable
{
/// <summary>
/// Creates a variable with the given value, type and mutability.
/// </summary>
/// <param name="value">The variable's value.</param>
/// <param name="type">The variable's type.</param>
/// <param name="isMutable">The variable's mutability.</param>
private Variable(object value, WasmValueType type, bool isMutable)
{
this.val = value;
this.Type = type;
this.IsMutable = isMutable;
}
/// <summary>
/// The variable's value.
/// </summary>
private object val;
/// <summary>
/// Gets this variable's type.
/// </summary>
/// <returns>The variable's type.</returns>
public WasmValueType Type { get; private set; }
/// <summary>
/// Gets this variable's mutability.
/// </summary>
/// <returns>The variable's mutability.</returns>
public bool IsMutable { get; private set; }
/// <summary>
/// Gets this variable's value.
/// </summary>
/// <returns>The variable's value.</returns>
public T Get<T>()
{
return (T)val;
}
/// <summary>
/// Sets this variable's value.
/// </summary>
/// <param name="Value">The variable's new value.</param>
public void Set<T>(T Value)
{
if (!IsMutable)
{
throw new WasmException("Cannot assign a value to an immutable variable.");
}
if (!IsInstanceOf<T>(Value, Type))
{
throw new WasmException(
"Cannot assign a value of type '" + GetTypeName(Value) +
"' to a variable of type '" + ((object)Type).ToString() + "'.");
}
val = Value;
}
/// <summary>
/// Creates a new variable from the given value.
/// </summary>
/// <param name="type">The variable's type.</param>
/// <param name="isMutable">The variable's mutability.</param>
/// <param name="value">The variable's initial value.</param>
/// <returns>The newly-created variable.</returns>
public static Variable Create<T>(WasmValueType type, bool isMutable, T value)
{
if (!IsInstanceOf<T>(value, type))
{
throw new WasmException(
"Cannot create a variable of type '" + ((object)type).ToString() +
"' with an initial value of type '" + GetTypeName(value) + "'.");
}
return new Variable(value, type, isMutable);
}
/// <summary>
/// Creates a new variable of the given type and mutability, and initializes
/// it with the default value for the given type.
/// </summary>
/// <param name="type">The variable's type.</param>
/// <param name="isMutable">The variable's mutability.</param>
/// <returns>The newly-created variable.</returns>
public static Variable CreateDefault(WasmValueType type, bool isMutable)
{
return Create<object>(type, isMutable, GetDefaultValue(type));
}
/// <summary>
/// Gets the default value for the given WebAssembly value tyoe.
/// </summary>
/// <param name="type">A WebAssembly value type.</param>
/// <returns>The default value.</returns>
public static object GetDefaultValue(WasmValueType type)
{
switch (type)
{
case WasmValueType.Int32:
return default(int);
case WasmValueType.Int64:
return default(long);
case WasmValueType.Float32:
return default(float);
case WasmValueType.Float64:
return default(double);
default:
throw new WasmException("Unknown value type: " + type);
}
}
/// <summary>
/// Checks if the given value is an instance of the given WebAssembly value type.
/// </summary>
/// <param name="value">A value.</param>
/// <param name="type">A WebAssembly value type.</param>
/// <returns>
/// <c>true</c> if the given value is an instance of the given WebAssembly value type;
/// otherwise, <c>false</c>.
/// </returns>
public static bool IsInstanceOf<T>(T value, WasmValueType type)
{
switch (type)
{
case WasmValueType.Int32:
return value is int;
case WasmValueType.Int64:
return value is long;
case WasmValueType.Float32:
return value is float;
case WasmValueType.Float64:
return value is double;
default:
throw new WasmException("Unknown value type: " + type);
}
}
private static string GetTypeName(object value)
{
return value.GetType().Name;
}
}
} |
||||
TheStack | b5d66ff80af98d72f65bfd3fd64ce434c64d051c | C#code:C# | {"size": 748, "ext": "cs", "max_stars_repo_path": "MagicalCryptoWallet/Converters/FeeRatePerKbConverter.cs", "max_stars_repo_name": "lontivero/MagicalCryptoWallet", "max_stars_repo_stars_event_min_datetime": "2018-02-10T20:58:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-19T08:08:28.000Z", "max_issues_repo_path": "MagicalCryptoWallet/Converters/FeeRatePerKbConverter.cs", "max_issues_repo_name": "lontivero/MagicalCryptoWallet", "max_issues_repo_issues_event_min_datetime": "2018-02-13T07:04:50.000Z", "max_issues_repo_issues_event_max_datetime": "2018-04-07T05:10:59.000Z", "max_forks_repo_path": "MagicalCryptoWallet/Converters/FeeRatePerKbConverter.cs", "max_forks_repo_name": "lontivero/MagicalCryptoWallet", "max_forks_repo_forks_event_min_datetime": "2018-02-16T19:56:08.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-08T14:10:27.000Z"} | {"max_stars_count": 8.0, "max_issues_count": 65.0, "max_forks_count": 5.0, "avg_line_length": 24.9333333333, "max_line_length": 118, "alphanum_fraction": 0.7379679144} | using NBitcoin;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;
namespace MagicalCryptoWallet.Converters
{
public class FeeRatePerKbConverter : JsonConverter
{
/// <inheritdoc />
public override bool CanConvert(Type objectType)
{
return objectType == typeof(FeeRate);
}
/// <inheritdoc />
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var value = ((long)reader.Value);
return new FeeRate(new Money(value));
}
/// <inheritdoc />
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteValue(((FeeRate)value).FeePerK.Satoshi.ToString());
}
}
} |
||||
TheStack | b5d7e136a41cc8867c532ede8e81363113239ba3 | C#code:C# | {"size": 3913, "ext": "cs", "max_stars_repo_path": "mko.NaLisp/Core/Inspector.cs", "max_stars_repo_name": "mk-prg-net/mk-prg-net.lib", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mko.NaLisp/Core/Inspector.cs", "max_issues_repo_name": "mk-prg-net/mk-prg-net.lib", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mko.NaLisp/Core/Inspector.cs", "max_forks_repo_name": "mk-prg-net/mk-prg-net.lib", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 32.0737704918, "max_line_length": 127, "alphanum_fraction": 0.487094301} | //<unit_header>
//----------------------------------------------------------------
//
// Martin Korneffel: IT Beratung/Softwareentwicklung
// Stuttgart, den 1.4.2014
//
// Projekt.......: mko.Algo
// Name..........: Inspector.cs
// Aufgabe/Fkt...: Validiert NaLisp- Ausdrücke.
// Ein Inspector prüft einen NaLisp bezüglich seines korrekten statischen Aufbaus.
// Inspector: {NaLisp} → {true, false}
// Für jeden Namen kann eine Validierungsfunktion registriert werden. Diese wird vom Inspector
// aufgerufen, wenn ein NaLisp zu überprüfen ist.
// Nur validierte NaLisp dürfen evaluiert werden.
//
//
//
//
//<unit_environment>
//------------------------------------------------------------------
// Zielmaschine..: PC
// Betriebssystem: Windows 7 mit .NET 4.5
// Werkzeuge.....: Visual Studio 2012
// Autor.........: Martin Korneffel (mko)
// Version 1.0...: 1.4.2014
//
// </unit_environment>
//
//<unit_history>
//------------------------------------------------------------------
//
// Version.......: 1.1
// Autor.........: Martin Korneffel (mko)
// Datum.........:
// Änderungen....:
//
//</unit_history>
//</unit_header>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace mko.NaLisp.Core
{
public partial class Inspector
{
public static Inspector _ = new Inspector();
/// <summary>
/// Protokolliert die Interpretation eines TASP
/// </summary>
NaLispStack StackInstance = new NaLispStack();
/// <summary>
/// Untersucht einen TASP- Term auf Fehlerfreiheit. Alle IsValid- Eigenschaften im TASP- Term werdengesetzt
/// </summary>
/// <param name="SubTerm"></param>
/// <returns></returns>
public ProtocolEntry Validate(INaLisp RootTerm)
{
StackInstance.Clear();
return ValidateR(RootTerm);
}
/// <summary>
/// mko, 10.11.2015
/// Validieren als asynchrone Methode
/// </summary>
/// <param name="RootTerm"></param>
/// <returns></returns>
public async Task<ProtocolEntry> ValidateAsync(NaLisp RootTerm)
{
ProtocolEntry pe = null;
await Task.Run(() => pe = Validate(RootTerm));
return pe;
}
ProtocolEntry ValidateR(INaLisp SubTerm)
{
try
{
StackInstance.Push(SubTerm);
if (SubTerm is ITerminal)
{
return ((ITerminal)SubTerm).Validate(StackInstance);
}
else
{
var NonTerm = (INonTerminal)SubTerm;
if (NonTerm.Elements.Any())
{
// Validieren der Listenelemente (Kinder)
ProtocolEntry[] ChildProtocolEntries = new ProtocolEntry[NonTerm.Elements.Length];
for (int i = 0; i < ChildProtocolEntries.Length; i++)
{
ChildProtocolEntries[i] = ValidateR(NonTerm.Elements[i]);
}
// Validieren der Liste insgesamt
var res = NonTerm.Validate(StackInstance, ChildProtocolEntries);
res.ChildProtocolEntries = ChildProtocolEntries;
return res;
}
else
return new ProtocolEntry(SubTerm, false, false, null, "NonTerminal NaLisp enthält keine Kindelemente");
}
}
finally
{
StackInstance.Pop();
}
}
}
}
|
||||
TheStack | b5d873e1429719f4d02485f1b4bda73ac778fc84 | C#code:C# | {"size": 791, "ext": "cs", "max_stars_repo_path": "SourceCode/App/Extensions/ToastServiceExtensions.cs", "max_stars_repo_name": "proggy/Tellurian.Trains.ModulesRegistryApp", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "SourceCode/App/Extensions/ToastServiceExtensions.cs", "max_issues_repo_name": "proggy/Tellurian.Trains.ModulesRegistryApp", "max_issues_repo_issues_event_min_datetime": "2021-05-20T19:25:59.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T19:25:59.000Z", "max_forks_repo_path": "SourceCode/App/Extensions/ToastServiceExtensions.cs", "max_forks_repo_name": "proggy/Tellurian.Trains.ModulesRegistryApp", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": 1.0, "max_forks_count": null, "avg_line_length": 34.3913043478, "max_line_length": 125, "alphanum_fraction": 0.6460176991} | using Blazored.Toast.Services;
using Microsoft.Extensions.Localization;
namespace ModulesRegistry.Extensions
{
public static class ToastServiceExtensions
{
public static void ShowSuccessOrFailure(this IToastService me, IStringLocalizer localizer, int count, string message)
{
if (count > 0)
me.ShowSuccess(localizer[message], localizer["Success"].ToString());
else if (count < 0)
me.ShowInfo(localizer[message], localizer["Info"].ToString());
else
me.ShowError(localizer[message], localizer["Fault"].ToString());
}
public static void ShowNotFound<T>(this IToastService me, IStringLocalizer localizer) =>
me.ShowError(localizer.NotFound<T>());
}
}
|
||||
TheStack | b5d875578de0ce90420f6cd9b74d42c186ed13cb | C#code:C# | {"size": 1998, "ext": "cs", "max_stars_repo_path": "src/Infrastructure/src/Emulator/Peripherals/Peripherals/PCI/PCIeMemory.cs", "max_stars_repo_name": "UPBIoT/renode-iot", "max_stars_repo_stars_event_min_datetime": "2020-11-30T08:22:04.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-01T00:57:12.000Z", "max_issues_repo_path": "src/Infrastructure/src/Emulator/Peripherals/Peripherals/PCI/PCIeMemory.cs", "max_issues_repo_name": "UPBIoT/renode-iot", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Infrastructure/src/Emulator/Peripherals/Peripherals/PCI/PCIeMemory.cs", "max_forks_repo_name": "UPBIoT/renode-iot", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 3.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 33.3, "max_line_length": 167, "alphanum_fraction": 0.6061061061} | //
// Copyright (c) 2010-2018 Antmicro
//
// This file is licensed under the MIT License.
// Full license text is available in 'licenses/MIT.txt'.
//
using System;
using System.Collections.Generic;
using Antmicro.Renode.Core;
using Antmicro.Renode.Core.Structure;
using Antmicro.Renode.Core.Structure.Registers;
using Antmicro.Renode.Logging;
using Antmicro.Renode.Peripherals.Bus;
using Antmicro.Renode.Peripherals.PCI.BAR;
using Antmicro.Renode.Utilities;
namespace Antmicro.Renode.Peripherals.PCI
{
public class PCIeMemory : PCIeEndpoint
{
public PCIeMemory(IPCIeRouter parent, uint size) : base(parent)
{
this.memory = new uint[size / 4];
for(var i = 0u; i < HeaderType.MaxNumberOfBARs(); ++i)
{
AddBaseAddressRegister(i, new MemoryBaseAddressRegister(size, MemoryBaseAddressRegister.BarType.LocateIn32Bit, true));
}
}
public override void Reset()
{
base.Reset();
Array.Clear(memory, 0, memory.Length);
}
protected override void WriteDoubleWordToBar(uint bar, long offset, uint value)
{
offset /= 4; //we keep uints, so we divide the offset
if(offset >= memory.Length)
{
this.Log(LogLevel.Warning, "Trying to write 0x{0:X} out of memory range, at offset 0x{1:X}. Size of memory is 0x{2:X}.", value, offset, memory.Length);
return;
}
memory[offset] = value;
}
protected override uint ReadDoubleWordFromBar(uint bar, long offset)
{
offset /= 4; //we keep uints, so we divide the offset
if(offset >= memory.Length)
{
this.Log(LogLevel.Warning, "Trying to read from offset 0x{0:X}, beyond the memory range 0x{1:X}.", offset, memory.Length);
return 0u;
}
return memory[offset];
}
private uint[] memory;
}
} |
||||
TheStack | b5d89a9672976190c6c1b8ab51399585d49dc1d9 | C#code:C# | {"size": 14584, "ext": "cs", "max_stars_repo_path": "SoccerBase/BackgroundWorks/Method1.cs", "max_stars_repo_name": "TheHalcyonSavant/SoccerBase", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "SoccerBase/BackgroundWorks/Method1.cs", "max_issues_repo_name": "TheHalcyonSavant/SoccerBase", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SoccerBase/BackgroundWorks/Method1.cs", "max_forks_repo_name": "TheHalcyonSavant/SoccerBase", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 54.0148148148, "max_line_length": 164, "alphanum_fraction": 0.4626302798} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Globalization;
using System.Data.SqlClient;
namespace SoccerBase.BackgroundWorks
{
class Method1
{
public SqlConnection Connection;
public string rowFormat = @"<tr style='background-color:{0};'>
<td class='No'>{1}</td>
<td class='ID'>{2}</td>
<td class='Country'>{3}</td>
<td class='League'>{4}</td>
<td class='Season'>{5}</td>
<td class='Round'>{6}</td>
<td class='Date'>{7}</td>
<td class='HomeTeam'>{8}</td>
<td class='AwayTeam'>{9}</td>
<td class='Forecast'>{10}</td>
<td class='Tip'>{11}</td>
<td class='Odds'>{12}</td>
<td class='Score'>{13}</td>
<td class='Guessed'>{14}</td>
<td class='SpentMoney'>{15}</td>
<td class='WonMoney'>{16}</td>
</tr>";
public string html;
public List<string> topCountries, topLeagues;
public int groups, groupCounter, matchIndex = 0, innerMatchIndex, roundIndex = 0, wonRounds = 0, lostRounds = 0,
lastGroupCounter = -1, lastGroupIndex = -1, minMatches;
public bool isTip1, isTipX, isTip2, isScore1, isScoreX, isScore2, isIncremental, isSmallBet, isMediumBet, isBigBet, isGroupAll, isBreaked = false;
public double smallBet, mediumBet, bigBet, investedMoney, profit = 0.0, profitPercent, propInvest = 1, minInvest = 0.0, maxInvest = 0.0, maxGroupInvest,
allInvestment = 0.0, allProfit = 0.0;
public void processRound(string date, bool bOutput = true)
{
if (!bOutput) innerMatchIndex = 0;
else if (innerMatchIndex < minMatches) return;
string q = @"SELECT i.ID ID, i.Country Country, i.League League, i.Season Season, i.Round Round, sr.Date Date, i.HomeTeam HomeTeam, i.AwayTeam AwayTeam,
i.ForecastH ForecastH, i.ForecastD ForecastD, i.ForecastA ForecastA, i.TipGoalsH TipGoalsH, i.TipGoalsA TipGoalsA,
sr.HomeOdds HomeOdds, sr.DrawOdds DrawOdds, sr.AwayOdds AwayOdds, i.ScoreH ScoreH, i.ScoreA ScoreA, i.Guessed Guessed
FROM dbo.Ivnet i, SoccerBase.dbo.SportRadar sr
WHERE i.SportRadarID = sr.ID AND i.Guessed IS NOT NULL AND sr.Date = @Date AND i.Country IN ('" + String.Join("','", topCountries) + @"') AND
i.League IN ('" + String.Join("','", topLeagues) + "')";
SqlCommand selectCmd = new SqlCommand(q, Connection);
selectCmd.Parameters.AddWithValue("@Date", date);
SqlDataReader reader;
using (reader = selectCmd.ExecuteReader())
{
int i = 0, j, tipWinner, scoreWinner, groupIndex = 0, forecastTemp, avgForecastWin = 0, avgForecastLost = 0, temp, groupLength;
int[] forecastsGroup = new int[groups];
double odds, currentInvestment, wonMoney = 0.0, currentWon;
if (bOutput)
{
html += String.Format("<p2>Round {0}:</p2>",++roundIndex);
html += @"<table border='1' style='font-family:Verdana;font-size:12px;'><thead><tr>
<th>No:</th><th>ID</th><th>Country</th><th>League</th><th>Season</th><th>Round</th><th>Date</th>
<th>Home Team</th><th>Away Team</th><th>Forecast</th><th>Tip</th><th>Odds</th><th>Score</th><th>Guessed</th>
<th>Spent Money</th><th>Won Money</th></tr></thead><tbody>";
}
bool isGuessed, takeMoney, isLastGroupIndex, isLastGroupIndex2;
double[] investmentGroup = new double[groups], oddsGroup = new double[groups];
bool[] wonGroup = new bool[groups];
investedMoney = 0.0;
groupCounter = 0;
while (reader.Read())
{
tipWinner = (byte)reader["TipGoalsH"] - (byte)reader["TipGoalsA"];
tipWinner = tipWinner >= 0 ? (tipWinner > 0 ? 0 : 1) : 2;
scoreWinner = (byte)reader["ScoreH"] - (byte)reader["ScoreA"];
scoreWinner = scoreWinner >= 0 ? (scoreWinner > 0 ? 0 : 1) : 2;
if (tipWinner == 0 && !isTip1) continue;
if (tipWinner == 1 && !isTipX) continue;
if (tipWinner == 2 && !isTip2) continue;
if (scoreWinner == 0 && !isScore1) continue;
if (scoreWinner == 1 && !isScoreX) continue;
if (scoreWinner == 2 && !isScore2) continue;
if (tipWinner == 0)
{
odds = (double)reader["HomeOdds"];
forecastTemp = (byte)reader["ForecastH"];
}
else if (tipWinner == 1)
{
odds = (double)reader["DrawOdds"];
forecastTemp = (byte)reader["ForecastD"];
}
else
{
odds = (double)reader["AwayOdds"];
forecastTemp = (byte)reader["ForecastA"];
}
currentInvestment = 0.0;
if (odds < 1.25) continue;
if (odds >= 1.25 && odds <= 1.5 && isBigBet) currentInvestment = bigBet;
else if (odds > 1.5 && odds <= 2.2 && isMediumBet) currentInvestment = mediumBet;
else if (odds > 2.2 && isSmallBet) currentInvestment = smallBet;
else continue;
groupIndex = i++ % groups;
if (!bOutput) innerMatchIndex++;
currentWon = 0.0;
isGuessed = (bool)reader["Guessed"];
investmentGroup[groupIndex] = currentInvestment;
wonGroup[groupIndex] = isGuessed;
oddsGroup[groupIndex] = odds;
forecastsGroup[groupIndex] = forecastTemp;
takeMoney = false;
isLastGroupIndex = groupIndex == groups - 1;
isLastGroupIndex2 = isGroupAll && bOutput && groupCounter == lastGroupCounter && groupIndex == lastGroupIndex;
//if (bOutput) Console.WriteLine("groupCounter: {0}, lastGroupCounter: {1}", groupCounter, lastGroupCounter);
if (isLastGroupIndex || isLastGroupIndex2)
{
groupCounter++;
if (isLastGroupIndex2) groupLength = lastGroupIndex + 1;
else groupLength = groups;
currentInvestment = 0.0;
for (j = 0; j < groupLength; j++) currentInvestment += investmentGroup[j];
currentInvestment /= groupLength;
if (isIncremental)
{
currentInvestment *= propInvest;
if (currentInvestment < smallBet) currentInvestment = smallBet;
if (currentInvestment > maxGroupInvest) currentInvestment = maxGroupInvest;
/*
* maxInvest can't work like this,
* unless you re-code everything
if (investedMoney + currentInvestment > maxInvest)
{
isBreaked = true;
//Console.WriteLine("Breaket: {0}", investedMoney + currentInvestment);
break;
}
*/
}
investedMoney += currentInvestment;
currentWon = 1.0;
for (j = 0; j < groupLength; j++) currentWon *= oddsGroup[j];
currentWon *= currentInvestment;
takeMoney = true;
for (j = 0; j < groupLength; j++)
{
if (!wonGroup[j])
{
takeMoney = false;
break;
}
}
forecastTemp = 0;
for (j = 0; j < groupLength; j++) forecastTemp += forecastsGroup[j];
forecastTemp /= groupLength;
if (takeMoney)
{
wonMoney += currentWon;
avgForecastWin = avgForecastWin > 0 ? (avgForecastWin + forecastTemp) / 2 : avgForecastWin + forecastTemp;
}
else
{
temp = avgForecastLost;
avgForecastLost = avgForecastLost > 0 ? (avgForecastLost + forecastTemp) / 2 : avgForecastLost + forecastTemp;
}
}
if (bOutput) html += String.Format(rowFormat,
isGuessed ? "transparent" : "pink",
++matchIndex,
reader["ID"],
reader["Country"],
reader["League"],
reader["Season"],
reader["Round"],
String.Format("{0:yyyy-MM-dd}", reader["Date"]),
reader["HomeTeam"],
reader["AwayTeam"],
boldSpan(reader["ForecastH"], 0, tipWinner) + " " +
boldSpan(reader["ForecastD"], 1, tipWinner) + " " +
boldSpan(reader["ForecastA"], 2, tipWinner),
reader["TipGoalsH"] + ":" + reader["TipGoalsA"],
boldSpan(reader["HomeOdds"], 0, scoreWinner) + " " +
boldSpan(reader["DrawOdds"], 1, scoreWinner) + " " +
boldSpan(reader["AwayOdds"], 2, scoreWinner),
reader["ScoreH"] + ":" + reader["ScoreA"],
isGuessed ? "Yes" : "No",
isLastGroupIndex || isLastGroupIndex2 ? currentInvestment.ToString("F") : "",
(isLastGroupIndex || isLastGroupIndex2) && takeMoney ? currentWon.ToString("F") : ""
);
} // while (reader.Read())
lastGroupCounter = -1;
lastGroupIndex = -1;
if (!bOutput)
{
//Console.WriteLine("{0}) bOutput:{1},i:{2},grIdx:{3},grCnter:{4},Breaked:{5},lastGrIdx:{6},lastGrCnter:{7}",
// matchIndex, bOutput, i, groupIndex, groupCounter, isBreaked, lastGroupIndex, lastGroupCounter);
if (isGroupAll && groupIndex < groups - 1)
{
//Console.WriteLine(matchIndex);
groupLength = groupIndex + 1;
isBreaked = false;
currentInvestment = 0.0;
for (j = 0; j < groupLength; j++) currentInvestment += investmentGroup[j];
currentInvestment /= groupLength;
if (isIncremental)
{
currentInvestment *= propInvest;
if (currentInvestment < smallBet) currentInvestment = smallBet;
if (currentInvestment > maxGroupInvest) currentInvestment = maxGroupInvest;
}
if (!isBreaked)
{
investedMoney += currentInvestment;
currentWon = 1.0;
for (j = 0; j < groupLength; j++) currentWon *= oddsGroup[j];
currentWon *= currentInvestment;
takeMoney = true;
for (j = 0; j < groupLength; j++)
{
if (!wonGroup[j])
{
takeMoney = false;
break;
}
}
if (takeMoney) wonMoney += currentWon;
lastGroupCounter = groupCounter;
lastGroupIndex = groupIndex;
}
}
}
else
{
//Console.WriteLine("{0}) bOutput:{1},i:{2},grIdx:{3},grCnter:{4},Breaked:{5},lastGrIdx:{6},lastGrCnter:{7}",
// matchIndex, bOutput, i, groupIndex, groupCounter, isBreaked, lastGroupIndex, lastGroupCounter);
profit = wonMoney - investedMoney;
profitPercent = profit / investedMoney * 100;
if (profit < 0) lostRounds++;
else wonRounds++;
string sum = @"</tbody></table>
<table style='background-color:{0};font-family:Verdana;font-size:13px;'>
<tbody>
<tr><td>Invested:</td><td>{1:0.00}</td> <td>Average Forecast Winners:</td><td>{6}</td></tr>
<tr><td>Won:</td><td>{2:0.00}</td> <td>Average Forecast Loosers:</td><td>{7}</td></tr>
<tr><td>Profit:</td><td>{3:0.00}</td> <td>All Profit:</td><td>{8:0.00}</td></tr>
<tr><td>Percent:</td><td>{4:0}%</td></tr>
<tr><td>Date:</td><td>{5}</td></tr>
</tbody>
</table><br/>";
allInvestment += investedMoney;
allProfit += profit;
DateTime dt = DateTime.Parse(date);
sum = String.Format(sum, profit < 0 ? "pink" : "transparent", investedMoney, wonMoney, profit, profitPercent, dt.ToString("yyyy-MM-dd, dddd"),
avgForecastWin, avgForecastLost, allProfit);
html += sum;
}
} // using (reader = selectCmd.ExecuteReader())
}
public static string boldSpan(object value, int currCol, int boldedCol)
{
if (currCol == boldedCol) return "<b>" + value.ToString() + "</b>";
return value.ToString();
}
}
}
|
||||
TheStack | b5d8be7e62f728001a0ea3dad6afd038812480ad | C#code:C# | {"size": 1222, "ext": "cshtml", "max_stars_repo_path": "src/Orchard.Web/Themes/OrchardProsTheme/Views/OrchardPros/Reply/Edit.cshtml", "max_stars_repo_name": "sfmskywalker/Orchard-Pros", "max_stars_repo_stars_event_min_datetime": "2019-07-18T23:37:15.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-19T17:59:24.000Z", "max_issues_repo_path": "src/Orchard.Web/Themes/OrchardProsTheme/Views/OrchardPros/Reply/Edit.cshtml", "max_issues_repo_name": "sfmskywalker/Orchard-Pros", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Orchard.Web/Themes/OrchardProsTheme/Views/OrchardPros/Reply/Edit.cshtml", "max_forks_repo_name": "sfmskywalker/Orchard-Pros", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 2.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 39.4193548387, "max_line_length": 143, "alphanum_fraction": 0.4615384615} | @model OrchardPros.ViewModels.ReplyViewModel
@{
Layout.Title = @T("Edit Reply");
}
@Html.ValidationSummary()
<!-- Post a reply -->
<div id="post-reply" class="container">
@using (Html.BeginFormAntiForgeryPost(Url.Action("Edit", "Reply", new { area = "OrchardPros" }), FormMethod.Post, new { role = "form" })) {
<div class="row">
<div class="col-md-8">
<section>
<h2>@T("Edit reply")</h2>
<fieldset class="form-group">
@Html.TextBoxFor(m => m.Title, new { @class = "form-control" })
@Html.EditorFor(m => m.Body, "Markdown")
</fieldset>
<fieldset class="form-group">
<button type="submit" class="btn btn-success btn-post">@T("Update Reply")</button>
</fieldset>
</section>
</div> <!-- /.col-md-8 -->
<div class="col-md-4">
<aside>
@Html.Editor("Attachments", "AttachmentsViewModel")
</aside>
</div> <!-- /.col-md-4 -->
</div>
<!-- /.row -->
}
</div>
<!-- /.container Post a reply --> |
||||
TheStack | b5d9165adb64d5c11067440666ab09dd89fed57e | C#code:C# | {"size": 2661, "ext": "cs", "max_stars_repo_path": "BBDown.Core/APP/Header/Locale.cs", "max_stars_repo_name": "ZHider/BBDown", "max_stars_repo_stars_event_min_datetime": "2020-07-26T12:31:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T11:44:26.000Z", "max_issues_repo_path": "BBDown.Core/APP/Header/Locale.cs", "max_issues_repo_name": "ZHider/BBDown", "max_issues_repo_issues_event_min_datetime": "2020-07-27T05:42:02.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:53:37.000Z", "max_forks_repo_path": "BBDown.Core/APP/Header/Locale.cs", "max_forks_repo_name": "ZHider/BBDown", "max_forks_repo_forks_event_min_datetime": "2020-08-07T14:36:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T11:15:35.000Z"} | {"max_stars_count": 2562.0, "max_issues_count": 216.0, "max_forks_count": 348.0, "avg_line_length": 39.1323529412, "max_line_length": 108, "alphanum_fraction": 0.6738068395} | // <auto-generated>
// This file was generated by a tool; you should avoid making direct changes.
// Consider using 'partial classes' to extend these types
// Input: locale.proto
// </auto-generated>
#region Designer generated code
#pragma warning disable CS0612, CS0618, CS1591, CS3021, IDE0079, IDE1006, RCS1036, RCS1057, RCS1085, RCS1192
[global::ProtoBuf.ProtoContract()]
public partial class Locale : global::ProtoBuf.IExtensible
{
private global::ProtoBuf.IExtension __pbn__extensionData;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
=> global::ProtoBuf.Extensible.GetExtensionObject(ref __pbn__extensionData, createIfMissing);
[global::ProtoBuf.ProtoMember(1)]
public LocaleIds cLocale { get; set; }
[global::ProtoBuf.ProtoMember(2)]
public LocaleIds sLocale { get; set; }
[global::ProtoBuf.ProtoContract()]
public partial class LocaleIds : global::ProtoBuf.IExtensible
{
private global::ProtoBuf.IExtension __pbn__extensionData;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
=> global::ProtoBuf.Extensible.GetExtensionObject(ref __pbn__extensionData, createIfMissing);
[global::ProtoBuf.ProtoMember(1, Name = @"language")]
[global::System.ComponentModel.DefaultValue("")]
public string Language
{
get => __pbn__Language ?? "";
set => __pbn__Language = value;
}
public bool ShouldSerializeLanguage() => __pbn__Language != null;
public void ResetLanguage() => __pbn__Language = null;
private string __pbn__Language;
[global::ProtoBuf.ProtoMember(2, Name = @"script")]
[global::System.ComponentModel.DefaultValue("")]
public string Script
{
get => __pbn__Script ?? "";
set => __pbn__Script = value;
}
public bool ShouldSerializeScript() => __pbn__Script != null;
public void ResetScript() => __pbn__Script = null;
private string __pbn__Script;
[global::ProtoBuf.ProtoMember(3, Name = @"region")]
[global::System.ComponentModel.DefaultValue("")]
public string Region
{
get => __pbn__Region ?? "";
set => __pbn__Region = value;
}
public bool ShouldSerializeRegion() => __pbn__Region != null;
public void ResetRegion() => __pbn__Region = null;
private string __pbn__Region;
}
}
#pragma warning restore CS0612, CS0618, CS1591, CS3021, IDE0079, IDE1006, RCS1036, RCS1057, RCS1085, RCS1192
#endregion
|
||||
TheStack | b5d97a8df4096bee259df55512bd86e72b47ab3f | C#code:C# | {"size": 3420, "ext": "cs", "max_stars_repo_path": "UnityProject/Packages/net.droidman.ohmyframework.core/OhMyFramework/Editor/OmfSettingsWindow.cs", "max_stars_repo_name": "ouyangwenyuan/OhMyFramework", "max_stars_repo_stars_event_min_datetime": "2020-12-16T05:25:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-29T07:28:12.000Z", "max_issues_repo_path": "UnityProject/Packages/net.droidman.ohmyframework.core/OhMyFramework/Editor/OmfSettingsWindow.cs", "max_issues_repo_name": "ouyangwenyuan/OhMyFramework", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "UnityProject/Packages/net.droidman.ohmyframework.core/OhMyFramework/Editor/OmfSettingsWindow.cs", "max_forks_repo_name": "ouyangwenyuan/OhMyFramework", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 2.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 29.2307692308, "max_line_length": 115, "alphanum_fraction": 0.4997076023} | using System;
using System.Linq;
using OhMyFramework.Core;
using UnityEditor;
using UnityEngine;
namespace OhMyFramework.Editor
{
enum Tabs
{
General,
UserInterface,
AssetBundle,
Server,
Storage,
Config,
Etc
}
public class OmfSettingsWindow : EditorWindow
{
private Tabs _selectedTab;
private bool _showBugReportSignupForm;
private string[] _tabs = Enum.GetNames(typeof (Tabs)).ToArray();
[MenuItem(MenuPathConst.OhMyFrameworkConfigs)]
public static void ShowWindow()
{
// var window = GetWindow<OhMyFrameworkConfigsWindow>();
// window.titleContent = new GUIContent("OhMyFrameworkConfigs");
// window.Show();
GetWindowWithRect<OmfSettingsWindow>(new Rect(0, 0, 520, 520), true, "OhMyFramework Configs", true);
}
private void OnGUI()
{
// title or logo
EditorGUILayout.BeginVertical();
GUILayout.Label("OhMyFramework");
EditorGUILayout.EndVertical();
// Draw tab buttons
var rect = EditorGUILayout.BeginVertical(GUI.skin.box);
--rect.width;
var height = 18;
EditorGUI.BeginChangeCheck();
// EditorGUI.BeginDisabledGroup(!_enableTabChange);
for (var i = 0; i < _tabs.Length; ++i)
{
var xStart = Mathf.RoundToInt(i*rect.width/_tabs.Length);
var xEnd = Mathf.RoundToInt((i + 1)*rect.width/_tabs.Length);
var pos = new Rect(rect.x + xStart, rect.y, xEnd - xStart, height);
if (GUI.Toggle(pos, (int) _selectedTab == i, new GUIContent(_tabs[i]), EditorStyles.toolbarButton))
{
_selectedTab = (Tabs) i;
}
}
GUILayoutUtility.GetRect(10f, height);
// Draw selected tab
DrawTabGeneral();
switch (_selectedTab)
{
case Tabs.General:
// DrawTabGeneral();
break;
case Tabs.UserInterface:
// DrawTabLayout();
break;
case Tabs.AssetBundle:
// DrawTabBugReporter();
break;
case Tabs.Storage:
// DrawTabShortcuts();
break;
case Tabs.Server:
// DrawTabAdvanced();
break;
case Tabs.Config:
// DrawTabShortcuts();
break;
case Tabs.Etc:
// DrawTabAdvanced();
break;
}
EditorGUILayout.EndVertical();
//foot 版权信息
EditorGUILayout.BeginVertical();
GUILayout.Label("copyright@OhMyFramework");
EditorGUILayout.EndVertical();
if (GUI.changed)
{
EditorUtility.SetDirty(OmfSettings.Instance);
}
}
private void DrawTabGeneral()
{
OmfSettings.Instance.IsEnabled = true;
GUILayout.Label("General");
// Expand content area to fit all available space
GUILayout.FlexibleSpace();
}
}
} |
||||
TheStack | b5da1c940fc555fe61bb7ba5c7f3e626af8e85ba | C#code:C# | {"size": 25595, "ext": "cs", "max_stars_repo_path": "TES3Oblivion/Converters/CellConverter.cs", "max_stars_repo_name": "SaintBahamut/TES3Tool", "max_stars_repo_stars_event_min_datetime": "2019-02-26T18:47:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T16:34:26.000Z", "max_issues_repo_path": "TES3Oblivion/Converters/CellConverter.cs", "max_issues_repo_name": "NullCascade/TES3Tool", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "TES3Oblivion/Converters/CellConverter.cs", "max_forks_repo_name": "NullCascade/TES3Tool", "max_forks_repo_forks_event_min_datetime": "2019-02-10T14:22:23.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-29T07:32:20.000Z"} | {"max_stars_count": 3.0, "max_issues_count": null, "max_forks_count": 2.0, "avg_line_length": 44.2820069204, "max_line_length": 184, "alphanum_fraction": 0.5521000195} | using System;
using System.Collections.Generic;
using System.Linq;
using static Utility.Common;
using static TES3Oblivion.Helpers;
using static TES3Oblivion.RecordConverter;
using static TES3Oblivion.SIPostProcessing.Definitions.BodyParts;
using TES3Oblivion.SIPostProcessing.Definitions;
using TES4Lib.Base;
using TES4Lib.Enums;
using System.Threading.Tasks;
using TES3Oblivion.Records.SIPostProcessing.Definitions;
using TES3Oblivion.SIPostProcessing;
namespace TES3Oblivion
{
public static class CellConverter
{
public static TES3Lib.TES3 ConvertInteriorsAndExteriors(TES4Lib.TES4 tes4)
{
ConvertRecords(tes4, "SE");
ConvertedRecords.Add("CELL", new List<ConvertedRecordData>());
ConvertedRecords.Add("PGRD", new List<ConvertedRecordData>());
ConvertInteriorCells(tes4);
ConvertExteriorCells(tes4);
UpdateDoorReferences();
//SI
PostProcessing();
var tes3 = new TES3Lib.TES3();
TES3Lib.Records.TES3 header = createTES3HEader();
tes3.Records.Add(header);
EquipementSplitter.SELL0NPCOrderKnightArmor100();
foreach (var record in Enum.GetNames(typeof(TES3Lib.RecordTypes)))
{
//SI
if (record.Equals("BODY"))
{
tes3.Records.AddRange(GetListOfBodyParts());
}
if (!ConvertedRecords.ContainsKey(record)) continue;
tes3.Records.AddRange(ConvertedRecords[record].Select(x => x.Record));
}
//dispose helper structures
ConvertedRecords = new Dictionary<string, List<ConvertedRecordData>>();
CellReferences = new List<ConvertedCellReference>();
DoorReferences = new List<TES3Lib.Records.REFR>();
var dupex = tes3.Records.Find(x => x.GetEditorId() == "SEOrderKnightArmor1Iron\0");
return tes3;
}
public static TES3Lib.TES3 ConvertInteriors(TES4Lib.TES4 tes4)
{
ConvertedRecords.Add("CELL", new List<ConvertedRecordData>());
ConvertInteriorCells(tes4);
UpdateDoorReferences();
Console.WriteLine($"INTERIOR CELL AND REFERENCED RECORDS CONVERSION DONE \n BUILDING TES3 PLUGIN/MASTER INSTANCE");
var tes3 = new TES3Lib.TES3();
TES3Lib.Records.TES3 header = createTES3HEader();
tes3.Records.Add(header);
foreach (var record in Enum.GetNames(typeof(TES3Lib.RecordTypes)))
{
if (!ConvertedRecords.ContainsKey(record)) continue;
tes3.Records.InsertRange(tes3.Records.Count, ConvertedRecords[record].Select(x => x.Record));
}
//dispose helper structures
ConvertedRecords = new Dictionary<string, List<ConvertedRecordData>>();
CellReferences = new List<ConvertedCellReference>();
DoorReferences = new List<TES3Lib.Records.REFR>();
return tes3;
}
public static TES3Lib.TES3 ConvertExteriors(TES4Lib.TES4 tes4)
{
ConvertedRecords.Add("CELL", new List<ConvertedRecordData>());
ConvertExteriorCells(tes4);
Console.WriteLine($"EXTERIOR CELL AND REFERENCED RECORDS CONVERSION DONE \n BUILDING TES3 PLUGIN/MASTER INSTANCE");
var tes3 = new TES3Lib.TES3();
TES3Lib.Records.TES3 header = createTES3HEader();
tes3.Records.Add(header);
foreach (var record in Enum.GetNames(typeof(TES3Lib.RecordTypes)))
{
if (!ConvertedRecords.ContainsKey(record)) continue;
tes3.Records.InsertRange(tes3.Records.Count, ConvertedRecords[record].Select(x => x.Record));
}
//dispose helper structures
ConvertedRecords = new Dictionary<string, List<ConvertedRecordData>>();
CellReferences = new List<ConvertedCellReference>();
DoorReferences = new List<TES3Lib.Records.REFR>();
return tes3;
}
private static void ConvertInteriorCells(TES4Lib.TES4 tes4)
{
//convert cells
var cellGroupsTop = tes4.Groups.FirstOrDefault(x => x.Label == "CELL");
if (IsNull(cellGroupsTop))
{
Console.WriteLine("no CELL records");
return;
}
foreach (var cellBlock in cellGroupsTop.Groups)
{
ProcessInteriorSubBlocks(cellBlock);
}
}
private static void ConvertExteriorCells(TES4Lib.TES4 tes4)
{
//convert cells
var wrldGroupsTop = tes4.Groups.FirstOrDefault(x => x.Label == "WRLD");
if (IsNull(wrldGroupsTop))
{
Console.WriteLine("no WRLD records");
return;
}
foreach (TES4Lib.Records.WRLD wrld in wrldGroupsTop.Records)
{
Console.WriteLine($"Converting worldspace {wrld.FULL.DisplayName}");
var wrldFormId = wrld.FormId;
var worldChildren = wrldGroupsTop.Groups.FirstOrDefault(x => x.Label == wrldFormId);
if (IsNull(worldChildren))
{
Console.WriteLine($"{wrld.FULL.DisplayName} has no WorldChildren");
continue;
}
//Here are records ROAD
foreach (var exteriorCellBlock in worldChildren.Groups)
{
if (exteriorCellBlock.Type.Equals(GroupLabel.CellChildren)) continue;
ProcessExteriorSubBlocks(exteriorCellBlock);
}
//process extra CELL record
var wrldCell = worldChildren.Records.FirstOrDefault(x => x.Name.Equals("CELL")) as TES4Lib.Records.CELL;
if (!IsNull(wrldCell))
{
//gardens hacks
if (wrld.EDID.EditorId.Equals("SEManiaGarden\0") || wrld.EDID.EditorId.Equals("SEDementiaGarden\0"))
{
wrldCell.DATA.Flags.Add(TES4Lib.Enums.Flags.CellFlag.IsInteriorCell);
wrldCell.DATA.Flags.Add(TES4Lib.Enums.Flags.CellFlag.BehaveLikeExterior);
var convertedGardenCell = ConvertCELL(wrldCell);
var gWrldCellChildren = worldChildren.Groups.FirstOrDefault(x => x.Type.Equals(GroupLabel.CellChildren));
ConvertCellChildren(ref convertedGardenCell, gWrldCellChildren, wrld.FormId);
DistributeGardenReferences(convertedGardenCell, wrld.EDID.EditorId);
continue;
}
var convertedCell = ConvertCELL(wrldCell);
var wrldCellChildren = worldChildren.Groups.FirstOrDefault(x => x.Type.Equals(GroupLabel.CellChildren));
ConvertCellChildren(ref convertedCell, wrldCellChildren, wrld.FormId);
DistributeWorldSpaceReferecnes(convertedCell);
}
//merge path grids: mabye some other time
//foreach (var exteriorCellPathGrid in ExteriorPathGrids)
//{
// var mergedGrid = MergeExteriorPathGrids(exteriorCellPathGrid.Value);
// ConvertedRecords["PGRD"].Add(new ConvertedRecordData("PGRD", "PGRD", "PGRD", mergedGrid));
//}
}
}
private static void DistributeGardenReferences(TES3Lib.Records.CELL convertedCell, string gardenWorldName)
{
string cellName = gardenWorldName == "SEManiaGarden\0" ? "SEManiaGardenExterior\0" : "SEDementiaGardenExterior\0";
ConvertedRecordData targetConvertedCell = ConvertedRecords["CELL"].FirstOrDefault(x =>
(x.Record as TES3Lib.Records.CELL).NAME.EditorId.Equals(cellName));
foreach (var cellReference in convertedCell.REFR)
{
if (!IsNull(targetConvertedCell))
{
var cellRecord = targetConvertedCell.Record as TES3Lib.Records.CELL;
cellRecord.NAM0.ReferenceCount++;
cellReference.FRMR.ObjectIndex = cellRecord.NAM0.ReferenceCount;
cellRecord.REFR.Add(cellReference);
//need update parent formId
var convertedReference = CellReferences.FirstOrDefault(x => x.Reference.Equals(cellReference));
convertedReference.ParentCellFormId = targetConvertedCell.OriginFormId;
}
}
}
private static void DistributeWorldSpaceReferecnes(TES3Lib.Records.CELL convertedCell)
{
foreach (var cellReference in convertedCell.REFR)
{
int cellGrindX = (int)(cellReference.DATA.XPos / Config.mwCellSize);
int cellGrindY = (int)(cellReference.DATA.YPos / Config.mwCellSize);
ConvertedRecordData targetConvertedCell = ConvertedRecords["CELL"].FirstOrDefault(x =>
(x.Record as TES3Lib.Records.CELL).DATA.GridX.Equals(cellGrindX) && (x.Record as TES3Lib.Records.CELL).DATA.GridY.Equals(cellGrindY));
if (!IsNull(targetConvertedCell))
{
var cellRecord = targetConvertedCell.Record as TES3Lib.Records.CELL;
cellRecord.NAM0.ReferenceCount++;
cellReference.FRMR.ObjectIndex = cellRecord.NAM0.ReferenceCount;
cellRecord.REFR.Add(cellReference);
//need update parent formId
var convertedReference = CellReferences.FirstOrDefault(x => x.Reference.Equals(cellReference));
convertedReference.ParentCellFormId = targetConvertedCell.OriginFormId;
}
else
{
Console.WriteLine($"target cell at coordinates {cellGrindX}.{cellGrindY} not found");
}
}
}
private static TES3Lib.Records.PGRD MergeExteriorPathGrids(List<ConvertedExteriorPathgrid> pathGrids)
{
var mergedPGRD = new TES3Lib.Records.PGRD() { DATA = new TES3Lib.Subrecords.PGRD.DATA() };
mergedPGRD.DATA.Granularity = pathGrids[0].PathGrid.DATA.Granularity;
mergedPGRD.DATA.GridX = pathGrids[0].PathGrid.DATA.GridX;
mergedPGRD.DATA.GridY = pathGrids[0].PathGrid.DATA.GridY;
var points = new List<TES3Lib.Subrecords.PGRD.PGRP.Point>();
var edges = new List<int>();
int offset = 0;
foreach (var subGrid in pathGrids)
{
if (IsNull(subGrid.PathGrid.PGRC)) continue;
offset = points.Count;
points.AddRange(subGrid.PathGrid.PGRP.Points);
edges.AddRange(Array.ConvertAll(subGrid.PathGrid.PGRC.Edges, edge => edge + offset).ToList());
}
mergedPGRD.PGRP = new TES3Lib.Subrecords.PGRD.PGRP { Points = points.ToArray() };
mergedPGRD.PGRC = new TES3Lib.Subrecords.PGRD.PGRC { Edges = edges.ToArray() };
mergedPGRD.DATA.Points = (short)points.Count;
var cell = ConvertedRecords["CELL"].FirstOrDefault( x =>
(x.Record as TES3Lib.Records.CELL).DATA.GridX.Equals(mergedPGRD.DATA.GridX) &&
(x.Record as TES3Lib.Records.CELL).DATA.GridY.Equals(mergedPGRD.DATA.GridY)).Record as TES3Lib.Records.CELL;
mergedPGRD.NAME = new TES3Lib.Subrecords.Shared.NAME();
if (!IsNull(cell.NAME) && !cell.NAME.EditorId.Equals("\0"))
{
mergedPGRD.NAME.EditorId = cell.NAME.EditorId;
}
else if (!IsNull(cell.RGNN))
{
mergedPGRD.NAME.EditorId = cell.RGNN.RegionName;
}
else
{
mergedPGRD.NAME.EditorId = "Wilderness\0";
}
return mergedPGRD;
}
private static void ProcessInteriorSubBlocks(Group interiorSubBlock)
{
foreach (var cellSubBlock in interiorSubBlock.Groups)
{
foreach (TES4Lib.Records.CELL interiorCell in cellSubBlock.Records)
{
string cellFormId = interiorCell.FormId;
if (interiorCell.Flag.Contains(TES4Lib.Enums.Flags.RecordFlag.Deleted)) continue;
//hack for now to get SI only
if ((interiorCell.EDID.EditorId.Contains("SE") || interiorCell.EDID.EditorId.Contains("XP")) && !IsNull(interiorCell.FULL))
{
var convertedCell = ConvertCELL(interiorCell);
if (IsNull(convertedCell)) throw new Exception("Output cell was null");
var cellChildren = cellSubBlock.Groups.FirstOrDefault(x => x.Label == interiorCell.FormId);
if (IsNull(cellChildren)) continue;
Console.WriteLine($"BEGIN CONVERTING \"{convertedCell.NAME.EditorId}\" CELL");
ConvertCellChildren(ref convertedCell, cellChildren, cellFormId);
foreach (var item in ConvertedRecords["CELL"])
{
bool cellWithSameNameExists = (item.Record as TES3Lib.Records.CELL).NAME.EditorId.Equals(convertedCell.NAME.EditorId);
if (cellWithSameNameExists)
{
convertedCell.NAME.EditorId = CellNameFormatter($"{convertedCell.NAME.EditorId.Replace("\0", " ")}{interiorCell.EDID.EditorId}");
break;
}
}
ConvertedRecords["CELL"].Add(new ConvertedRecordData(interiorCell.FormId, "CELL", interiorCell.EDID.EditorId, convertedCell));
Console.WriteLine($"DONE CONVERTING \"{convertedCell.NAME.EditorId}\" CELL");
}
}
}
}
private static void ProcessExteriorSubBlocks(Group exteriorCellBlock)
{
foreach (var subBlocks in exteriorCellBlock.Groups)
{
foreach (TES4Lib.Records.CELL exteriorCell in subBlocks.Records)
{
bool cellMerge = false;
string cellFormId = exteriorCell.FormId;
//mania/dementia garden hacks
if (!IsNull(exteriorCell.EDID) && (exteriorCell.EDID.EditorId.Equals("SEDementiaGardenExterior\0") || exteriorCell.EDID.EditorId.Equals("SEManiaGardenExterior\0")))
{
exteriorCell.DATA.Flags.Add(TES4Lib.Enums.Flags.CellFlag.IsInteriorCell);
exteriorCell.DATA.Flags.Add(TES4Lib.Enums.Flags.CellFlag.BehaveLikeExterior);
var gardenCell = ConvertCELL(exteriorCell);
var gardenChildren = subBlocks.Groups.FirstOrDefault(x => x.Label == exteriorCell.FormId);
ConvertCellChildren(ref gardenCell, gardenChildren, cellFormId);
ConvertedRecords["CELL"].Add(new ConvertedRecordData(exteriorCell.FormId, "CELL", exteriorCell.EDID.EditorId, gardenCell));
return;
}
var convertedCell = ConvertCELL(exteriorCell);
// resolve if this cell at this grid already exist
foreach (var alreadyConvertedCell in ConvertedRecords["CELL"])
{
if (convertedCell.Equals(alreadyConvertedCell.Record as TES3Lib.Records.CELL))
{
cellMerge = true;
cellFormId = alreadyConvertedCell.OriginFormId;
alreadyConvertedCell.OriginFormId += exteriorCell.FormId; //store all source cells formid as one string
convertedCell = mergeExteriorCells(alreadyConvertedCell.Record as TES3Lib.Records.CELL, convertedCell);
Console.WriteLine("merging subcells...");
break;
}
}
var cellChildren = subBlocks.Groups.FirstOrDefault(x => x.Label == exteriorCell.FormId);
if (IsNull(cellChildren))
{
Console.WriteLine("cell has no objects");
continue;
}
ConvertCellChildren(ref convertedCell, cellChildren, cellFormId);
if (!cellMerge)
{
//if (IsNull(convertedCell.RGNN) && convertedCell.REFR.Count.Equals(0)) return;
var editorId = !IsNull(exteriorCell.EDID) ? exteriorCell.EDID.EditorId : $"{exteriorCell.XCLC.GridX},{exteriorCell.XCLC.GridY}";
ConvertedRecords["CELL"].Add(new ConvertedRecordData(exteriorCell.FormId, "CELL", editorId, convertedCell));
}
Console.WriteLine($"DONE CONVERTING \"{convertedCell.DATA.GridX},{convertedCell.DATA.GridY}\" CELL");
}
}
}
private static void ConvertCellChildren(ref TES3Lib.Records.CELL mwCELL, Group cellChildren, string originalCellFormId)
{
foreach (var childrenType in cellChildren.Groups)
{
if (IsNull(mwCELL.NAM0))
{
mwCELL.NAM0 = new TES3Lib.Subrecords.CELL.NAM0 { ReferenceCount = 1 };
}
foreach (var obRef in childrenType.Records)
{
if (obRef.Flag.Contains(TES4Lib.Enums.Flags.RecordFlag.Deleted)) continue;
TES3Lib.Records.REFR mwREFR;
var referenceTypeName = obRef.GetType().Name;
if (referenceTypeName.Equals("REFR"))
{
var obREFR = obRef as TES4Lib.Records.REFR;
if (IsNull(obREFR.NAME)) continue;
var ReferenceBaseFormId = obREFR.NAME.BaseFormId;
var BaseId = GetBaseId(ReferenceBaseFormId);
if (string.IsNullOrEmpty(BaseId)) continue;
mwREFR = ConvertREFR(obREFR, BaseId, mwCELL.NAM0.ReferenceCount, mwCELL.DATA.Flags.Contains(TES3Lib.Enums.Flags.CellFlag.IsInteriorCell));
CellReferences.Add(new ConvertedCellReference(originalCellFormId, obREFR.FormId, mwREFR)); //for tracking
{// disable exterior statics as requested, remove when SI mod will be finished
if (!mwCELL.DATA.Flags.Contains(TES3Lib.Enums.Flags.CellFlag.IsInteriorCell))
if (ConvertedRecords.ContainsKey("STAT") && ConvertedRecords["STAT"].Any(x => x.EditorId.Equals(BaseId)))
continue;
}
mwCELL.REFR.Add(mwREFR);
mwCELL.NAM0.ReferenceCount++;
continue;
}
if (referenceTypeName.Equals("ACRE"))
{
var obACRE = obRef as TES4Lib.Records.ACRE;
if (IsNull(obACRE.NAME)) continue;
var ReferenceBaseFormId = obACRE.NAME.BaseFormId;
var BaseId = GetBaseId(ReferenceBaseFormId);
if (string.IsNullOrEmpty(BaseId)) continue;
mwREFR = ConvertACRE(obACRE, BaseId, mwCELL.NAM0.ReferenceCount, mwCELL.DATA.Flags.Contains(TES3Lib.Enums.Flags.CellFlag.IsInteriorCell));
CellReferences.Add(new ConvertedCellReference(originalCellFormId, obACRE.FormId, mwREFR)); //for tracking
mwCELL.REFR.Add(mwREFR);
mwCELL.NAM0.ReferenceCount++;
continue;
}
if (referenceTypeName.Equals("ACHR"))
{
var obACHR = obRef as TES4Lib.Records.ACHR;
if (IsNull(obACHR.NAME)) continue;
var ReferenceBaseFormId = obACHR.NAME.BaseFormId;
var BaseId = GetBaseId(ReferenceBaseFormId);
if (string.IsNullOrEmpty(BaseId)) continue;
mwREFR = ConvertACHR(obACHR, BaseId, mwCELL.NAM0.ReferenceCount, mwCELL.DATA.Flags.Contains(TES3Lib.Enums.Flags.CellFlag.IsInteriorCell));
CellReferences.Add(new ConvertedCellReference(originalCellFormId, obACHR.FormId, mwREFR)); //for tracking
mwCELL.REFR.Add(mwREFR);
mwCELL.NAM0.ReferenceCount++;
continue;
}
if (referenceTypeName.Equals("LAND"))
{
continue;
}
if (referenceTypeName.Equals("PGRD"))
{
if (mwCELL.DATA.Flags.Contains(TES3Lib.Enums.Flags.CellFlag.IsInteriorCell))
{
var obPGRD = obRef as TES4Lib.Records.PGRD;
var mwPGRD = ConvertPGRD(obPGRD, mwCELL);
ConvertedRecords["PGRD"].Add(new ConvertedRecordData(originalCellFormId, "CELL", mwCELL.NAME.EditorId, mwPGRD));
continue;
}
//else
//{
// var coordinates = $"{mwPGRD.DATA.GridX},{mwPGRD.DATA.GridY}";
// if (!ExteriorPathGrids.ContainsKey(coordinates))
// {
// ExteriorPathGrids.Add(coordinates, new List<ConvertedExteriorPathgrid>());
// }
// ExteriorPathGrids[coordinates].Add(new ConvertedExteriorPathgrid(mwPGRD, obPGRD.PGRI));
// continue;
//}
}
}
}
}
/// <summary>
/// Convert all non hierarchical records from loaded TES4 file
/// </summary>
/// <param name="tes4">TES4 ESM/ESP with records</param>
/// <param name="prefix">optional prefix for records editorId to convert</param>
private static void ConvertRecords(TES4Lib.TES4 tes4, string prefix = null)
{
foreach (TES4Lib.Base.Group group in tes4.Groups)
{
if (group.Label.Equals("CELL") || group.Label.Equals("DIAL") || group.Label.Equals("WRLD")) continue;
foreach (TES4Lib.Base.Record record in group.Records)
{
string editorId = record.GetEditorId();
if (string.IsNullOrEmpty(editorId) || editorId.Equals("SE14GSEscortList\0")) continue;
if (!string.IsNullOrEmpty(prefix))
{
if (editorId.StartsWith(prefix) || editorId.StartsWith("XP"))
{
ConvertedRecordData mwRecord = ConvertRecord(record);
if (IsNull(mwRecord)) continue;
if (!ConvertedRecords.ContainsKey(mwRecord.Type)) ConvertedRecords.Add(mwRecord.Type, new List<ConvertedRecordData>());
ConvertedRecords[mwRecord.Type].Add(mwRecord);
}
}
else
{
ConvertedRecordData mwRecord = ConvertRecord(record);
if (!ConvertedRecords.ContainsKey(mwRecord.Type)) ConvertedRecords.Add(mwRecord.Type, new List<ConvertedRecordData>());
ConvertedRecords[mwRecord.Type].Add(mwRecord);
}
}
}
}
private static void PostProcessing()
{
//1 split TODO
Parallel.ForEach(ConvertedRecords["CLOT"], item => {
if (EquipementProcessMap.ProcessItem.ContainsKey(item.EditorId))
{
EquipementProcessMap.ProcessItem[item.EditorId].Invoke(item.Record as TES3Lib.Base.IEquipement);
}
});
//Parallel.ForEach(ConvertedRecords["ARMO"], item => {
// if (EquipementItemsMap.ProcessItem.ContainsKey(item.EditorId))
// {
// EquipementItemsMap.ProcessItem[item.EditorId].Invoke(item.Record as TES3Lib.Base.IEquipement);
// }
//});
}
private static TES3Lib.Records.CELL mergeExteriorCells(TES3Lib.Records.CELL cellBase, TES3Lib.Records.CELL cellToMerge)
{
cellBase.NAME = cellBase.NAME.EditorId.Equals("\0") ? cellToMerge.NAME : cellBase.NAME;
cellBase.RGNN = IsNull(cellBase.RGNN) ? cellToMerge.RGNN : cellBase.RGNN;
return cellBase;
}
}
}
|
||||
TheStack | b5da4fcdaac8956f3f627a2611aebc21b70bd819 | C#code:C# | {"size": 3654, "ext": "cs", "max_stars_repo_path": "#build/#tools/AssemblyResolver/Steps/Step8.RewriteAndCopyMainAssemblies.cs", "max_stars_repo_name": "muojp/SharpLab", "max_stars_repo_stars_event_min_datetime": "2018-01-17T14:58:29.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-29T09:23:01.000Z", "max_issues_repo_path": "#build/#tools/AssemblyResolver/Steps/Step8.RewriteAndCopyMainAssemblies.cs", "max_issues_repo_name": "peachpiecompiler/SharpLab", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "#build/#tools/AssemblyResolver/Steps/Step8.RewriteAndCopyMainAssemblies.cs", "max_forks_repo_name": "peachpiecompiler/SharpLab", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 7.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 50.0547945205, "max_line_length": 171, "alphanum_fraction": 0.6160372195} | using System;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using AssemblyResolver.Common;
using Mono.Cecil;
namespace AssemblyResolver.Steps {
public static class Step8 {
public static void RewriteAndCopyMainAssemblies(
IImmutableDictionary<AssemblyShortName, AssemblyDetails> mainAssemblies,
string targetDirectoryPath,
IImmutableDictionary<AssemblyShortName, AssemblyDetails> usedRoslynAssemblies
) {
FluentConsole.White.Line("Rewriting and copying main assemblies…");
foreach (var assembly in mainAssemblies.Values) {
FluentConsole.Gray.Line($" {assembly.Definition.Name.Name}");
// ReSharper disable once AssignNullToNotNullAttribute
var targetPath = Path.Combine(targetDirectoryPath, Path.GetFileName(assembly.Path));
var rewritten = false;
foreach (var reference in assembly.Definition.MainModule.AssemblyReferences) {
FluentConsole.Gray.Line($" {reference.FullName}");
var roslynAssembly = usedRoslynAssemblies.GetValueOrDefault(reference.Name);
if (roslynAssembly == null)
continue;
if (RewriteReference(reference, roslynAssembly.Definition.Name))
FluentConsole.Gray.Line($" => {roslynAssembly.Definition.Name.FullName}");
rewritten = true;
}
if (rewritten) {
WriteAssembly(assembly, targetPath, mainAssemblies);
}
else {
Copy.File(assembly.Path, targetPath);
}
Copy.PdbIfExists(assembly.Path, targetPath);
}
}
private static void WriteAssembly(AssemblyDetails assembly, string targetPath, IImmutableDictionary<AssemblyShortName, AssemblyDetails> mainAssemblies) {
var assemblyName = assembly.Definition.Name;
assemblyName.PublicKey = new byte[0];
assemblyName.PublicKeyToken = new byte[0];
assemblyName.HasPublicKey = false;
var targetDirectoryPath = Path.GetDirectoryName(targetPath);
var resolver = (BaseAssemblyResolver)assembly.Definition.MainModule.AssemblyResolver;
foreach (var defaultPath in resolver.GetSearchDirectories()) {
resolver.RemoveSearchDirectory(defaultPath);
}
resolver.AddSearchDirectory(targetDirectoryPath);
resolver.ResolveFailure += (sender, reference) => {
var mainAssembly = mainAssemblies.GetValueOrDefault(reference.Name);
if (mainAssembly == null)
return null;
return mainAssembly.Definition;
};
assembly.Definition.Write(targetPath);
}
private static bool RewriteReference(AssemblyNameReference reference, AssemblyNameReference newReference) {
if (reference.Name != newReference.Name)
throw new ArgumentException($"Reference {reference.Name} cannot be rewritten to {newReference.Name}.");
if ((newReference.PublicKeyToken?.SequenceEqual(reference.PublicKeyToken) ?? (reference.PublicKeyToken == null)) && newReference.Version == reference.Version)
return false;
reference.PublicKeyToken = newReference.PublicKeyToken;
reference.Version = newReference.Version;
return true;
}
}
}
|
||||
TheStack | b5db22719665978642c5d277a5d7893c9b81b98e | C#code:C# | {"size": 895, "ext": "cs", "max_stars_repo_path": "src/Essensoft.Paylink.Alipay/Response/KoubeiCateringOrderPayCancelResponse.cs", "max_stars_repo_name": "essensoft/paymen", "max_stars_repo_stars_event_min_datetime": "2019-06-01T15:49:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-04T06:25:03.000Z", "max_issues_repo_path": "src/Essensoft.Paylink.Alipay/Response/KoubeiCateringOrderPayCancelResponse.cs", "max_issues_repo_name": "essensoft/paymen", "max_issues_repo_issues_event_min_datetime": "2019-06-20T08:03:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-28T10:19:27.000Z", "max_forks_repo_path": "src/Essensoft.Paylink.Alipay/Response/KoubeiCateringOrderPayCancelResponse.cs", "max_forks_repo_name": "essensoft/paymen", "max_forks_repo_forks_event_min_datetime": "2019-06-01T15:48:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-26T13:49:45.000Z"} | {"max_stars_count": 522.0, "max_issues_count": 74.0, "max_forks_count": 170.0, "avg_line_length": 25.5714285714, "max_line_length": 70, "alphanum_fraction": 0.5597765363} | using System.Text.Json.Serialization;
namespace Essensoft.Paylink.Alipay.Response
{
/// <summary>
/// KoubeiCateringOrderPayCancelResponse.
/// </summary>
public class KoubeiCateringOrderPayCancelResponse : AlipayResponse
{
/// <summary>
/// 撤销操作:REFUND-退款,CLOSE-关闭
/// </summary>
[JsonPropertyName("action")]
public string Action { get; set; }
/// <summary>
/// 外部支付订单号,唯一标识本 次支付的requestID
/// </summary>
[JsonPropertyName("out_pay_no")]
public string OutPayNo { get; set; }
/// <summary>
/// 口碑内部支付订单号,和外部支付订单号一一映射
/// </summary>
[JsonPropertyName("pay_no")]
public string PayNo { get; set; }
/// <summary>
/// 支付宝交易号
/// </summary>
[JsonPropertyName("trade_no")]
public string TradeNo { get; set; }
}
}
|
||||
TheStack | b5dd62e356ccd18314f52a2068f1ab516fffa647 | C#code:C# | {"size": 3377, "ext": "cs", "max_stars_repo_path": "src/VectorMath/DVector2.cs", "max_stars_repo_name": "stauders/SpaceSim", "max_stars_repo_stars_event_min_datetime": "2016-02-14T23:44:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-12T13:06:22.000Z", "max_issues_repo_path": "src/VectorMath/DVector2.cs", "max_issues_repo_name": "stauders/SpaceSim", "max_issues_repo_issues_event_min_datetime": "2018-12-29T05:48:45.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-30T17:37:08.000Z", "max_forks_repo_path": "src/VectorMath/DVector2.cs", "max_forks_repo_name": "stauders/SpaceSim", "max_forks_repo_forks_event_min_datetime": "2016-02-15T01:05:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-21T01:34:30.000Z"} | {"max_stars_count": 173.0, "max_issues_count": 1.0, "max_forks_count": 22.0, "avg_line_length": 22.9727891156, "max_line_length": 75, "alphanum_fraction": 0.4249333728} | using System;
namespace VectorMath
{
[Serializable]
public class DVector2
{
public static DVector2 Zero { get { return new DVector2(0, 0); } }
public double X;
public double Y;
public DVector2() { }
public DVector2(double x, double y)
{
X = x;
Y = y;
}
public void Reset()
{
X = 0;
Y = 0;
}
public void Normalize()
{
// Do not try to normalize zero vectors
if (X ==0 && Y == 0) return;
double length = Length();
X /= length;
Y /= length;
}
public DVector2 Normalized()
{
return Clone() / Length();
}
public void Negate()
{
X = -X;
Y = -Y;
}
public DVector2 Clone()
{
return new DVector2(X, Y);
}
public static DVector2 operator +(DVector2 a, DVector2 b)
{
return new DVector2(a.X + b.X, a.Y + b.Y);
}
public static DVector2 operator -(DVector2 a, DVector2 b)
{
return new DVector2(a.X - b.X, a.Y - b.Y);
}
public static DVector2 operator *(DVector2 a, double b)
{
return new DVector2(a.X * b, a.Y * b);
}
public static DVector2 operator /(DVector2 a, DVector2 b)
{
return new DVector2(a.X / b.X, a.Y / b.Y);
}
public static DVector2 operator /(DVector2 a, double b)
{
return new DVector2(a.X / b, a.Y / b);
}
public void Accumulate(DVector2 other)
{
X += other.X;
Y += other.Y;
}
public DVector2 Divide(float scalar)
{
return new DVector2(X / scalar, Y / scalar);
}
public DVector2 Divide(double scalar)
{
return new DVector2(X / scalar, Y / scalar);
}
public double Dot(DVector2 v)
{
return X * v.X + Y * v.Y;
}
public double Cross(DVector2 v)
{
return X * v.Y - Y * v.X;
}
public double Length()
{
return Math.Sqrt(X * X + Y * Y);
}
public double LengthSquared()
{
return X * X + Y * Y;
}
public double Angle()
{
return Math.Atan2(Y, X);
}
public Vector2 ToVector2()
{
return new Vector2((float)X, (float)Y);
}
public static DVector2 Lerp(DVector2 from, DVector2 to, double t)
{
return new DVector2(from.X + t * (to.X - from.X),
from.Y + t * (to.Y - from.Y));
}
public static DVector2 FromAngle(double angle)
{
return new DVector2(Math.Cos(angle), Math.Sin(angle));
}
public static double Distance(DVector2 v1, DVector2 v2)
{
return (v2 - v1).Length();
}
public override string ToString()
{
return "{" + Math.Round(X, 5) + "," + Math.Round(Y, 5) + "}";
}
}
}
|
||||
TheStack | b5dd63c9ad6173b4da6473649ce3e48901897803 | C#code:C# | {"size": 1963, "ext": "cs", "max_stars_repo_path": "ServiceRequests.xaml.cs", "max_stars_repo_name": "samirahmt2018/EquipmentManager", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ServiceRequests.xaml.cs", "max_issues_repo_name": "samirahmt2018/EquipmentManager", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ServiceRequests.xaml.cs", "max_forks_repo_name": "samirahmt2018/EquipmentManager", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 26.527027027, "max_line_length": 100, "alphanum_fraction": 0.5420275089} | using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace Equipment_Manager
{
/// <summary>
/// Interaction logic for ServiceRequests.xaml
/// </summary>
public partial class ServiceRequests : Window
{
string serviceRequestID = "", equipmentID = "";
DataTable servReq;
public ServiceRequests()
{
InitializeComponent();
try
{
servReq = DBManager.SelectPendingServiceRequests();
service_requestes.ItemsSource = servReq.AsDataView();
}
catch
{
}
}
private void service_requestes_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
try
{
serviceRequestID = servReq.Rows[service_requestes.SelectedIndex][0].ToString();
equipmentID = servReq.Rows[service_requestes.SelectedIndex][1].ToString();
}
catch
{
}
}
private void insertButton_Click(object sender, RoutedEventArgs e)
{
try
{
if (serviceRequestID != "")
{
ServiceOrder wo = new ServiceOrder(serviceRequestID, equipmentID);
wo.ShowDialog();
servReq = DBManager.SelectPendingServiceRequests();
service_requestes.ItemsSource = servReq.AsDataView();
}
}
catch
{
}
}
}
}
|