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 | da216df7c3a7ae50c7dd1b8eabab9b37f22b9952 | C#code:C# | {"size": 3248, "ext": "cs", "max_stars_repo_path": "StyleCop.Analyzers/StyleCop.Analyzers.CodeFixes/ReadabilityRules/SA1104SA1105CodeFixProvider.cs", "max_stars_repo_name": "wdolek/StyleCopAnalyzers", "max_stars_repo_stars_event_min_datetime": "2015-01-05T23:44:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T09:58:42.000Z", "max_issues_repo_path": "StyleCop.Analyzers/StyleCop.Analyzers.CodeFixes/ReadabilityRules/SA1104SA1105CodeFixProvider.cs", "max_issues_repo_name": "wdolek/StyleCopAnalyzers", "max_issues_repo_issues_event_min_datetime": "2015-01-01T10:19:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T20:42:21.000Z", "max_forks_repo_path": "StyleCop.Analyzers/StyleCop.Analyzers.CodeFixes/ReadabilityRules/SA1104SA1105CodeFixProvider.cs", "max_forks_repo_name": "wdolek/StyleCopAnalyzers", "max_forks_repo_forks_event_min_datetime": "2015-01-14T13:15:17.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T10:39:30.000Z"} | {"max_stars_count": 2228.0, "max_issues_count": 3109.0, "max_forks_count": 642.0, "avg_line_length": 43.3066666667, "max_line_length": 150, "alphanum_fraction": 0.680726601} | // Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
namespace StyleCop.Analyzers.ReadabilityRules
{
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Composition;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp;
using StyleCop.Analyzers.Helpers;
/// <summary>
/// This class provides a code fix for the SA1104 diagnostic.
/// </summary>
[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(SA1104SA1105CodeFixProvider))]
[Shared]
internal class SA1104SA1105CodeFixProvider : CodeFixProvider
{
/// <inheritdoc/>
public override ImmutableArray<string> FixableDiagnosticIds { get; } =
ImmutableArray.Create(
SA110xQueryClauses.SA1104Descriptor.Id,
SA110xQueryClauses.SA1105Descriptor.Id);
/// <inheritdoc/>
public override FixAllProvider GetFixAllProvider()
{
return CustomFixAllProviders.BatchFixer;
}
/// <inheritdoc/>
public override Task RegisterCodeFixesAsync(CodeFixContext context)
{
foreach (var diagnostic in context.Diagnostics)
{
context.RegisterCodeFix(
CodeAction.Create(
ReadabilityResources.SA1104SA1105CodeFix,
cancellationToken => GetTransformedDocumentAsync(context.Document, diagnostic, cancellationToken),
nameof(SA1104SA1105CodeFixProvider)),
diagnostic);
}
return SpecializedTasks.CompletedTask;
}
private static async Task<Document> GetTransformedDocumentAsync(Document document, Diagnostic diagnostic, CancellationToken cancellationToken)
{
var syntaxRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var token = syntaxRoot.FindToken(diagnostic.Location.SourceSpan.Start);
var settings = SettingsHelper.GetStyleCopSettings(document.Project.AnalyzerOptions, syntaxRoot.SyntaxTree, cancellationToken);
var indentationTrivia = QueryIndentationHelpers.GetQueryIndentationTrivia(settings.Indentation, token);
var precedingToken = token.GetPreviousToken();
var triviaList = precedingToken.TrailingTrivia.AddRange(token.LeadingTrivia);
var processedTriviaList = triviaList.WithoutTrailingWhitespace().Add(SyntaxFactory.CarriageReturnLineFeed);
var replaceMap = new Dictionary<SyntaxToken, SyntaxToken>()
{
[precedingToken] = precedingToken.WithTrailingTrivia(processedTriviaList),
[token] = token.WithLeadingTrivia(indentationTrivia),
};
var newSyntaxRoot = syntaxRoot.ReplaceTokens(replaceMap.Keys, (t1, t2) => replaceMap[t1]).WithoutFormatting();
return document.WithSyntaxRoot(newSyntaxRoot);
}
}
}
|
||||
TheStack | da24a291ce76cb6fa998cd128e309ca54c659e86 | C#code:C# | {"size": 1540, "ext": "cs", "max_stars_repo_path": "src/NVT.lib/DB.cs", "max_stars_repo_name": "jcapellman/NCAT", "max_stars_repo_stars_event_min_datetime": "2020-02-11T20:08:54.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-11T20:08:54.000Z", "max_issues_repo_path": "src/NVT.lib/DB.cs", "max_issues_repo_name": "jcapellman/NVT", "max_issues_repo_issues_event_min_datetime": "2019-12-26T16:06:41.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-30T14:26:13.000Z", "max_forks_repo_path": "src/NVT.lib/DB.cs", "max_forks_repo_name": "jcapellman/NCAT", "max_forks_repo_forks_event_min_datetime": "2021-04-05T11:55:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-05T11:55:45.000Z"} | {"max_stars_count": 1.0, "max_issues_count": 56.0, "max_forks_count": 1.0, "avg_line_length": 26.1016949153, "max_line_length": 80, "alphanum_fraction": 0.5149350649} | using System;
using System.Collections.Generic;
using System.Linq;
using LiteDB;
using NVT.lib.JSONObjects;
using NVT.lib.Objects;
namespace NVT.lib
{
public class DB
{
private const string DB_FILENAME = "ips.db";
public static bool CheckDB(ref NetworkConnectionItem item)
{
if (item == null)
{
throw new ArgumentNullException(nameof(item));
}
using (var db = new LiteDatabase(DB_FILENAME))
{
var items = db.GetCollection<NetworkConnectionItem>();
var ipAddress = item.IPAddress;
var existingItem = items.FindOne(a => a.IPAddress == ipAddress);
if (existingItem == null)
{
return false;
}
item.City = existingItem.City;
item.Country = existingItem.Country;
item.ISP = existingItem.ISP;
item.Latitude = existingItem.Latitude;
item.Longitude = existingItem.Longitude;
return true;
}
}
public static void AddToDB(NetworkConnectionItem item)
{
if (item == null)
{
throw new ArgumentNullException(nameof(item));
}
using (var db = new LiteDatabase(DB_FILENAME))
{
var items = db.GetCollection<NetworkConnectionItem>();
items.Insert(item);
}
}
}
} |
||||
TheStack | da24bac1af3a576eede7cbb1ea411272960f4e33 | C#code:C# | {"size": 802, "ext": "cs", "max_stars_repo_path": "Domain/Entities/Transaction/TransactionRecurrency.cs", "max_stars_repo_name": "Huray-hub/FinancialOrganizer", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Domain/Entities/Transaction/TransactionRecurrency.cs", "max_issues_repo_name": "Huray-hub/FinancialOrganizer", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Domain/Entities/Transaction/TransactionRecurrency.cs", "max_forks_repo_name": "Huray-hub/FinancialOrganizer", "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.8695652174, "max_line_length": 114, "alphanum_fraction": 0.7132169576} | using System.Collections.Generic;
namespace Domain.Entities.Transaction
{
public class TransactionRecurrency : BaseEntity
{
public TransactionRecurrency()
{
RecurrentTransactionInstallments = new HashSet<RecurrentTransactionInstallment>();
}
public bool HasLimitations { get; set; }
public int FrequencyType { get; set; }
public int TransactionId { get; set; }
public Transaction Transaction { get; set; }
public RecurrentTransactionLimitation RecurrentTransactionLimitation { get; set; }
public ICollection<RecurrentTransactionInstallment> RecurrentTransactionInstallments { get; private set; }
public RecurrentTransactionCustomFrequency RecurrentTransactionCustomFrequency { get; set; }
}
}
|
||||
TheStack | da25cab8dd5fb9725edd11c7095f9a0a24eef765 | C#code:C# | {"size": 1894, "ext": "cs", "max_stars_repo_path": "Comuns/Seguranca/Encryption.cs", "max_stars_repo_name": "thiarley/ArquiteturaBasica", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Comuns/Seguranca/Encryption.cs", "max_issues_repo_name": "thiarley/ArquiteturaBasica", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Comuns/Seguranca/Encryption.cs", "max_forks_repo_name": "thiarley/ArquiteturaBasica", "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.137254902, "max_line_length": 110, "alphanum_fraction": 0.5945089757} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO;
using System.Runtime.InteropServices;
namespace ArquiteturaBasica.Comuns.Seguranca
{
/// <summary>
/// Classe com definições para as classes de criptografia.
/// </summary>
public class Encryption
{
/// <summary>
/// Chave 64 bits para os arquivos.
/// </summary>
protected static string sEncryptFileKey = "\t8???Z??";
/// <summary>
/// Vetor de bytes utilizados para a criptografia (Chave Externa)
/// </summary>
protected static byte[] bIV =
{ 0x50, 0x08, 0xF1, 0xDD, 0xDE, 0x3C, 0xF2, 0x18,
0x44, 0x74, 0x19, 0x2C, 0x53, 0x49, 0xAB, 0xBC };
/// <summary>
/// Representação de valor em base 64 (Chave Interna)
/// O Valor representa a transformação para base64 de
/// um conjunto de 32 caracteres (8 * 32 = 256bits)
/// A chave é: "Criptografia"
/// Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes("Criptografia xxxxxx"))
/// </summary>
protected const string cryptoKey = "Q3JpcHRvZ3JhZmlhIHByb2pldG8gRGFiaUF0bGFudGU=";
/// <summary>
/// Função para gerar Chave de 64 bits.
/// </summary>
/// <returns></returns>
protected static string GenerateKey()
{
// Criar uma instância do algoritmo Symetric. Chave e IV é gerado automaticamente.
DESCryptoServiceProvider desCrypto = (DESCryptoServiceProvider)DESCryptoServiceProvider.Create();
// Use a chave gerada automaticamente para criptografia.
return ASCIIEncoding.ASCII.GetString(desCrypto.Key);
}
}
}
|
||||
TheStack | da269a41cdcd22247d998f514da02b7dff09b048 | C#code:C# | {"size": 7074, "ext": "cs", "max_stars_repo_path": "dropbox-sdk-dotnet/Dropbox.Api/Generated/TeamLog/GovernancePolicyAddFolderFailedDetails.cs", "max_stars_repo_name": "omer-koren/dropbox-sdk-dotnet", "max_stars_repo_stars_event_min_datetime": "2015-06-23T15:28:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T18:58:15.000Z", "max_issues_repo_path": "dropbox-sdk-dotnet/Dropbox.Api/Generated/TeamLog/GovernancePolicyAddFolderFailedDetails.cs", "max_issues_repo_name": "omer-koren/dropbox-sdk-dotnet", "max_issues_repo_issues_event_min_datetime": "2015-10-06T10:44:10.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T22:27:39.000Z", "max_forks_repo_path": "dropbox-sdk-dotnet/Dropbox.Api/Generated/TeamLog/GovernancePolicyAddFolderFailedDetails.cs", "max_forks_repo_name": "brandboxmarketplace/dropbox-sdk-dotnet", "max_forks_repo_forks_event_min_datetime": "2015-07-15T19:31:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T18:58:20.000Z"} | {"max_stars_count": 356.0, "max_issues_count": 210.0, "max_forks_count": 551.0, "avg_line_length": 38.0322580645, "max_line_length": 144, "alphanum_fraction": 0.5363302234} | // <auto-generated>
// Auto-generated by StoneAPI, do not modify.
// </auto-generated>
namespace Dropbox.Api.TeamLog
{
using sys = System;
using col = System.Collections.Generic;
using re = System.Text.RegularExpressions;
using enc = Dropbox.Api.Stone;
/// <summary>
/// <para>Couldn't add a folder to a policy.</para>
/// </summary>
public class GovernancePolicyAddFolderFailedDetails
{
#pragma warning disable 108
/// <summary>
/// <para>The encoder instance.</para>
/// </summary>
internal static enc.StructEncoder<GovernancePolicyAddFolderFailedDetails> Encoder = new GovernancePolicyAddFolderFailedDetailsEncoder();
/// <summary>
/// <para>The decoder instance.</para>
/// </summary>
internal static enc.StructDecoder<GovernancePolicyAddFolderFailedDetails> Decoder = new GovernancePolicyAddFolderFailedDetailsDecoder();
/// <summary>
/// <para>Initializes a new instance of the <see
/// cref="GovernancePolicyAddFolderFailedDetails" /> class.</para>
/// </summary>
/// <param name="governancePolicyId">Policy ID.</param>
/// <param name="name">Policy name.</param>
/// <param name="folder">Folder.</param>
/// <param name="policyType">Policy type.</param>
/// <param name="reason">Reason.</param>
public GovernancePolicyAddFolderFailedDetails(string governancePolicyId,
string name,
string folder,
PolicyType policyType = null,
string reason = null)
{
if (governancePolicyId == null)
{
throw new sys.ArgumentNullException("governancePolicyId");
}
if (name == null)
{
throw new sys.ArgumentNullException("name");
}
if (folder == null)
{
throw new sys.ArgumentNullException("folder");
}
this.GovernancePolicyId = governancePolicyId;
this.Name = name;
this.Folder = folder;
this.PolicyType = policyType;
this.Reason = reason;
}
/// <summary>
/// <para>Initializes a new instance of the <see
/// cref="GovernancePolicyAddFolderFailedDetails" /> class.</para>
/// </summary>
/// <remarks>This is to construct an instance of the object when
/// deserializing.</remarks>
[sys.ComponentModel.EditorBrowsable(sys.ComponentModel.EditorBrowsableState.Never)]
public GovernancePolicyAddFolderFailedDetails()
{
}
/// <summary>
/// <para>Policy ID.</para>
/// </summary>
public string GovernancePolicyId { get; protected set; }
/// <summary>
/// <para>Policy name.</para>
/// </summary>
public string Name { get; protected set; }
/// <summary>
/// <para>Folder.</para>
/// </summary>
public string Folder { get; protected set; }
/// <summary>
/// <para>Policy type.</para>
/// </summary>
public PolicyType PolicyType { get; protected set; }
/// <summary>
/// <para>Reason.</para>
/// </summary>
public string Reason { get; protected set; }
#region Encoder class
/// <summary>
/// <para>Encoder for <see cref="GovernancePolicyAddFolderFailedDetails" />.</para>
/// </summary>
private class GovernancePolicyAddFolderFailedDetailsEncoder : enc.StructEncoder<GovernancePolicyAddFolderFailedDetails>
{
/// <summary>
/// <para>Encode fields of given value.</para>
/// </summary>
/// <param name="value">The value.</param>
/// <param name="writer">The writer.</param>
public override void EncodeFields(GovernancePolicyAddFolderFailedDetails value, enc.IJsonWriter writer)
{
WriteProperty("governance_policy_id", value.GovernancePolicyId, writer, enc.StringEncoder.Instance);
WriteProperty("name", value.Name, writer, enc.StringEncoder.Instance);
WriteProperty("folder", value.Folder, writer, enc.StringEncoder.Instance);
if (value.PolicyType != null)
{
WriteProperty("policy_type", value.PolicyType, writer, global::Dropbox.Api.TeamLog.PolicyType.Encoder);
}
if (value.Reason != null)
{
WriteProperty("reason", value.Reason, writer, enc.StringEncoder.Instance);
}
}
}
#endregion
#region Decoder class
/// <summary>
/// <para>Decoder for <see cref="GovernancePolicyAddFolderFailedDetails" />.</para>
/// </summary>
private class GovernancePolicyAddFolderFailedDetailsDecoder : enc.StructDecoder<GovernancePolicyAddFolderFailedDetails>
{
/// <summary>
/// <para>Create a new instance of type <see
/// cref="GovernancePolicyAddFolderFailedDetails" />.</para>
/// </summary>
/// <returns>The struct instance.</returns>
protected override GovernancePolicyAddFolderFailedDetails Create()
{
return new GovernancePolicyAddFolderFailedDetails();
}
/// <summary>
/// <para>Set given field.</para>
/// </summary>
/// <param name="value">The field value.</param>
/// <param name="fieldName">The field name.</param>
/// <param name="reader">The json reader.</param>
protected override void SetField(GovernancePolicyAddFolderFailedDetails value, string fieldName, enc.IJsonReader reader)
{
switch (fieldName)
{
case "governance_policy_id":
value.GovernancePolicyId = enc.StringDecoder.Instance.Decode(reader);
break;
case "name":
value.Name = enc.StringDecoder.Instance.Decode(reader);
break;
case "folder":
value.Folder = enc.StringDecoder.Instance.Decode(reader);
break;
case "policy_type":
value.PolicyType = global::Dropbox.Api.TeamLog.PolicyType.Decoder.Decode(reader);
break;
case "reason":
value.Reason = enc.StringDecoder.Instance.Decode(reader);
break;
default:
reader.Skip();
break;
}
}
}
#endregion
}
}
|
||||
TheStack | da276eecf0c70f587e9016399dbda086dad4db13 | C#code:C# | {"size": 3374, "ext": "cs", "max_stars_repo_path": "Legacy/Witch/ArcARC.cs", "max_stars_repo_name": "RikuNoctis/GARbro", "max_stars_repo_stars_event_min_datetime": "2015-07-05T11:49:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:21:34.000Z", "max_issues_repo_path": "Legacy/Witch/ArcARC.cs", "max_issues_repo_name": "coregameHD/GARbro", "max_issues_repo_issues_event_min_datetime": "2015-08-27T19:36:53.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T08:39:37.000Z", "max_forks_repo_path": "Legacy/Witch/ArcARC.cs", "max_forks_repo_name": "coregameHD/GARbro", "max_forks_repo_forks_event_min_datetime": "2015-01-22T12:42:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T07:09:03.000Z"} | {"max_stars_count": 1163.0, "max_issues_count": 503.0, "max_forks_count": 237.0, "avg_line_length": 40.1666666667, "max_line_length": 87, "alphanum_fraction": 0.5711321873} | //! \file ArcARC.cs
//! \date 2018 Jan 15
//! \brief Witch resource archive.
//
// Copyright (C) 2018 by morkt
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.IO;
// [000708][Witch] Milkyway
namespace GameRes.Formats.Witch
{
[Export(typeof(ArchiveFormat))]
public class ArcOpener : ArchiveFormat
{
public override string Tag { get { return "ARC/WITCH"; } }
public override string Description { get { return "Witch resource archive"; } }
public override uint Signature { get { return 0x20435241; } } // 'ARC '
public override bool IsHierarchic { get { return false; } }
public override bool CanWrite { get { return false; } }
public override ArcFile TryOpen (ArcView file)
{
if (file.View.ReadInt32 (4) != 0)
return null;
using (var index = file.CreateStream())
{
long index_pos = 0x10;
var id = new byte[8];
var dir = new List<Entry>();
for (;;)
{
index.Position = index_pos;
if (8 != index.Read (id, 0, 8))
return null;
if (!id.AsciiEqual ("DIR \0\0\0\0"))
break;
index.ReadInt32();
int name_length = index.ReadInt32();
if (name_length <= 0)
return null;
index.Seek (0x10, SeekOrigin.Current);
uint size = index.ReadUInt32();
uint offset = index.ReadUInt32();
var name = index.ReadCString (name_length);
index_pos += 0x28 + name_length;
var entry = FormatCatalog.Instance.Create<Entry> (name);
entry.Offset = offset;
entry.Size = size;
if (!entry.CheckPlacement (file.MaxOffset))
return null;
dir.Add (entry);
}
if (0 == dir.Count)
return null;
return new ArcFile (file, this, dir);
}
}
}
}
|
||||
TheStack | da281ab7cf996b99ae0b882c3642ca07d50ea369 | C#code:C# | {"size": 199, "ext": "cshtml", "max_stars_repo_path": "src/SpotifySync.Web/Views/_ViewImports.cshtml", "max_stars_repo_name": "nfiles/spotify-sync", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/SpotifySync.Web/Views/_ViewImports.cshtml", "max_issues_repo_name": "nfiles/spotify-sync", "max_issues_repo_issues_event_min_datetime": "2018-07-19T16:11:32.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-02T02:45:40.000Z", "max_forks_repo_path": "src/SpotifySync.Web/Views/_ViewImports.cshtml", "max_forks_repo_name": "nfiles/spotify-sync", "max_forks_repo_forks_event_min_datetime": "2018-03-21T01:08:02.000Z", "max_forks_repo_forks_event_max_datetime": "2018-03-21T01:08:02.000Z"} | {"max_stars_count": null, "max_issues_count": 6.0, "max_forks_count": 1.0, "avg_line_length": 33.1666666667, "max_line_length": 53, "alphanum_fraction": 0.8090452261} | @using SpotifySync.Web
@using SpotifySync.Web.Models;
@using Microsoft.Extensions.Options;
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper *, Microsoft.AspNetCore.SpaServices
|
||||
TheStack | da2874cb29e65f6aaa5b2be8f065c3fe713bc9f1 | C#code:C# | {"size": 4385, "ext": "cs", "max_stars_repo_path": "DeployProjectToCatalogTask.cs", "max_stars_repo_name": "sqlsimon/SSISBuild", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "DeployProjectToCatalogTask.cs", "max_issues_repo_name": "sqlsimon/SSISBuild", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DeployProjectToCatalogTask.cs", "max_forks_repo_name": "sqlsimon/SSISBuild", "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": 27.2360248447, "max_line_length": 118, "alphanum_fraction": 0.6779931585} | using System;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
namespace Microsoft.SqlServer.IntegrationServices.Build
{
/// <summary>
/// This Task connects to an SSIS Catalog and deploys the given project files.
/// Ensure that the account running MSBuild has permission to deploy to the catalog.
/// </summary>
public class DeployProjectToCatalogTask : Task
{
/// <summary>
/// One or more paths to .ispac deployment files.
/// </summary>
[Required]
public ITaskItem[] DeploymentFile { get; set; }
/// <summary>
/// The SQL instance name of the SSIS Catalog to deploy to.
/// </summary>
[Required]
public string Instance { get; set; }
/// <summary>
/// The folder on the catalog to deploy to.
/// If this folder does not exist, it will be created if <see cref="CreateFolder"/> is true.
/// </summary>
[Required]
public string Folder { get; set; }
/// <summary>
/// Should the SSIS Catalog Folder be created if it is not already there.
/// This property is optional. The default value is true.
/// </summary>
public bool CreateFolder { get; set; }
/// <summary>
/// The name of the SSIS catalog to deploy to.
/// This property is optional. The default value is "SSISDB".
/// </summary>
public string Catalog { get; set; }
public DeployProjectToCatalogTask()
{
Catalog = "SSISDB";
CreateFolder = true;
}
public override bool Execute()
{
bool result = true;
var csb = new SqlConnectionStringBuilder
{
DataSource = Instance, IntegratedSecurity = true, InitialCatalog = Catalog
};
Log.LogMessage(SR.ConnectingToServer(csb.ConnectionString));
using (var conn = new SqlConnection(csb.ConnectionString))
{
try
{
conn.Open();
}
catch (Exception e)
{
Log.LogError(SR.ConnectionError);
Log.LogErrorFromException(e);
return false;
}
foreach (var taskItem in DeploymentFile)
{
try
{
Log.LogMessage("------");
string projectPath = taskItem.ItemSpec;
if (CreateFolder)
{
EnsureFolderExists(conn, Folder);
}
string projectName = Path.GetFileNameWithoutExtension(projectPath);
var bytes = File.ReadAllBytes(projectPath);
var deploymentCmd = GetDeploymentCommand(conn, Folder, projectName, bytes);
try
{
Log.LogMessage(SR.DeployingProject(projectPath));
deploymentCmd.ExecuteNonQuery();
}
catch (Exception)
{
Log.LogError(SR.DeploymentFailed);
throw;
}
}
catch (Exception e)
{
Log.LogErrorFromException(e, true);
result = false;
}
}
}
return result;
}
private void EnsureFolderExists(SqlConnection connection, string folder)
{
if (!FolderExists(connection, folder))
{
CreateCatalogFolder(connection, folder);
}
}
private static bool FolderExists(SqlConnection connection, string folder)
{
var cmd = GetFolderCommand(connection, folder);
var folderId = cmd.ExecuteScalar();
return (folderId != null && folderId != DBNull.Value);
}
private void CreateCatalogFolder(SqlConnection connection, string folder)
{
var cmd = new SqlCommand("[catalog].[create_folder]", connection) {CommandType = CommandType.StoredProcedure};
cmd.Parameters.AddWithValue("folder_name", folder);
Log.LogMessage(SR.CreatingFolder(folder));
cmd.ExecuteNonQuery();
}
private static SqlCommand GetFolderCommand(SqlConnection connection, string folder)
{
var cmd = new SqlCommand("SELECT folder_id FROM [catalog].[folders] WHERE name = @FolderName", connection);
cmd.Parameters.AddWithValue("@FolderName", folder);
return cmd;
}
private static SqlCommand GetDeploymentCommand(SqlConnection connection, string folder, string name, byte[] project)
{
// build the deployment command
var cmd = new SqlCommand("[catalog].[deploy_project]", connection) { CommandType = CommandType.StoredProcedure };
cmd.Parameters.AddWithValue("folder_name", folder);
cmd.Parameters.AddWithValue("project_name", name);
cmd.Parameters.AddWithValue("project_stream", project);
cmd.Parameters.AddWithValue("operation_id", SqlDbType.BigInt).Direction = ParameterDirection.Output;
return cmd;
}
}
}
|
||||
TheStack | da28f4a8adcba969488e3100c797ac80f1baf51a | C#code:C# | {"size": 285, "ext": "cs", "max_stars_repo_path": "HCMS.Web.ViewModels/Manager/Tasks/ProjectTasksViewModel.cs", "max_stars_repo_name": "IwanGaydarow/InternProject", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "HCMS.Web.ViewModels/Manager/Tasks/ProjectTasksViewModel.cs", "max_issues_repo_name": "IwanGaydarow/InternProject", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "HCMS.Web.ViewModels/Manager/Tasks/ProjectTasksViewModel.cs", "max_forks_repo_name": "IwanGaydarow/InternProject", "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.9230769231, "max_line_length": 62, "alphanum_fraction": 0.698245614} | namespace HCMS.Web.ViewModels.Manager.Tasks
{
using System.Collections.Generic;
using AutoMapper;
using HCMS.Data.Models;
using HCMS.Services.Mapping;
public class ProjectTasksViewModel
{
public IEnumerable<TasksViewModel> Tasks { get; set; }
}
}
|
||||
TheStack | da2a494972aa215f834f7763ef39fe6037cef180 | C#code:C# | {"size": 2028, "ext": "cs", "max_stars_repo_path": "samples/ReverseProxy.Sample/Startup.cs", "max_stars_repo_name": "thelgevold/reverse-proxy", "max_stars_repo_stars_event_min_datetime": "2020-04-28T13:32:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T06:48:50.000Z", "max_issues_repo_path": "samples/ReverseProxy.Sample/Startup.cs", "max_issues_repo_name": "thelgevold/reverse-proxy", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "samples/ReverseProxy.Sample/Startup.cs", "max_forks_repo_name": "thelgevold/reverse-proxy", "max_forks_repo_forks_event_min_datetime": "2020-11-16T07:16:58.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-16T07:16:58.000Z"} | {"max_stars_count": 5.0, "max_issues_count": null, "max_forks_count": 1.0, "avg_line_length": 36.8727272727, "max_line_length": 123, "alphanum_fraction": 0.6055226824} | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Net;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.ReverseProxy.Core.Configuration.DependencyInjection;
namespace Microsoft.ReverseProxy.Sample {
/// <summary>
/// ASP .NET Core pipeline initialization.
/// </summary>
public class Startup {
private readonly IConfiguration _configuration;
/// <summary>
/// Initializes a new instance of the <see cref="Startup"/> class.
/// </summary>
public Startup (IConfiguration configuration) {
_configuration = configuration;
}
/// <summary>
/// This method gets called by the runtime. Use this method to add services to the container.
/// </summary>
public void ConfigureServices (IServiceCollection services) {
services.AddControllers ();
services.AddReverseProxy ().LoadFromConfig (_configuration.GetSection ("ReverseProxy"), reloadOnChange : true);
}
/// <summary>
/// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
/// </summary>
public void Configure (IApplicationBuilder app) {
app.UseHttpsRedirection ();
app.UseRouting ();
app.UseAuthorization ();
app.UseEndpoints (endpoints => {
endpoints.MapControllers ();
endpoints.MapReverseProxy (proxyPipeline => {
proxyPipeline.UseProxyLoadBalancing ();
proxyPipeline.Use ((context, next) => {
var connection = context.Connection;
context.Request.Headers.AppendCommaSeparatedValues ("Best-Friend", "Buddy");
return next ();
});
});
});
}
}
} |
||||
TheStack | da2c13197a8f56744764608f27cbaffadebc9c28 | C#code:C# | {"size": 885, "ext": "cs", "max_stars_repo_path": "Version 1.0/FREDApi/FREDApi/Categories/APIFacades/CategoryRelatedTags.cs", "max_stars_repo_name": "rcapel/FRED-API-Toolkit", "max_stars_repo_stars_event_min_datetime": "2016-03-10T14:20:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-29T15:55:52.000Z", "max_issues_repo_path": "Version 1.0/FREDApi/FREDApi/Categories/APIFacades/CategoryRelatedTags.cs", "max_issues_repo_name": "rcapel/FRED-API-Toolkit", "max_issues_repo_issues_event_min_datetime": "2016-09-28T23:39:15.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-29T23:12:43.000Z", "max_forks_repo_path": "Version 1.0/FREDApi/FREDApi/Categories/APIFacades/CategoryRelatedTags.cs", "max_forks_repo_name": "rcapel/FRED-API-Toolkit", "max_forks_repo_forks_event_min_datetime": "2016-05-20T02:39:46.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-14T18:32:46.000Z"} | {"max_stars_count": 11.0, "max_issues_count": 2.0, "max_forks_count": 2.0, "avg_line_length": 30.5172413793, "max_line_length": 130, "alphanum_fraction": 0.7661016949} | using FRED.API.Categories.Arguments;
using FRED.API.Base.APIFacades;
using FRED.API.Tags.Data;
namespace FRED.API.Categories.APIFacades
{
/// <summary>
/// Provides a facade for consuming the fred/category/related_tags API endpoint. Results are returned in a TagContainer instance.
/// </summary>
public class CategoryRelatedTags : ApiBase<CategoryRelatedTagsArguments, TagContainer>
{
}
/// <summary>
/// Provides a facade for consuming the fred/category/related_tags API endpoint. Results are returned as a JSON string.
/// </summary>
public class CategoryRelatedTagsJson : ApiBase<CategoryRelatedTagsArguments, string>
{
}
/// <summary>
/// Provides a facade for consuming the fred/category/related_tags API endpoint. Results are returned as an XML string.
/// </summary>
public class CategoryRelatedTagsXml : XmlApiFacade<CategoryRelatedTagsArguments>
{
}
}
|
||||
TheStack | da2e218ec7edaac1e15915cdf4db557e91ecaff6 | C#code:C# | {"size": 726, "ext": "cs", "max_stars_repo_path": "aspnetcore/host-and-deploy/health-checks/samples/6.x/HealthChecksSample/HealthChecks/StartupHealthCheck.cs", "max_stars_repo_name": "jongalloway/AspNetCore.Docs", "max_stars_repo_stars_event_min_datetime": "2015-02-17T23:50:40.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-02T14:15:35.000Z", "max_issues_repo_path": "aspnetcore/host-and-deploy/health-checks/samples/6.x/HealthChecksSample/HealthChecks/StartupHealthCheck.cs", "max_issues_repo_name": "jongalloway/AspNetCore.Docs", "max_issues_repo_issues_event_min_datetime": "2015-02-13T00:00:04.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-02T15:20:33.000Z", "max_forks_repo_path": "aspnetcore/host-and-deploy/health-checks/samples/6.x/HealthChecksSample/HealthChecks/StartupHealthCheck.cs", "max_forks_repo_name": "jongalloway/AspNetCore.Docs", "max_forks_repo_forks_event_min_datetime": "2015-02-22T06:59:04.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-02T14:45:00.000Z"} | {"max_stars_count": 5343.0, "max_issues_count": 8758.0, "max_forks_count": 13865.0, "avg_line_length": 25.9285714286, "max_line_length": 99, "alphanum_fraction": 0.6955922865} | using Microsoft.Extensions.Diagnostics.HealthChecks;
namespace HealthChecksSample.HealthChecks;
// <snippet_Class>
public class StartupHealthCheck : IHealthCheck
{
private volatile bool _isReady;
public bool StartupCompleted
{
get => _isReady;
set => _isReady = value;
}
public Task<HealthCheckResult> CheckHealthAsync(
HealthCheckContext context, CancellationToken cancellationToken = default)
{
if (StartupCompleted)
{
return Task.FromResult(HealthCheckResult.Healthy("The startup task has completed."));
}
return Task.FromResult(HealthCheckResult.Unhealthy("That startup task is still running."));
}
}
// </snippet_Class>
|
||||
TheStack | da2e34379cb9ad2dc70b056b86987827bbaa1d0f | C#code:C# | {"size": 6266, "ext": "cs", "max_stars_repo_path": "test/Tizen.NUI.Tests/Tizen.NUI.Devel.Tests/testcase/public/XamlBinding/TSSizeTypeConverter.cs", "max_stars_repo_name": "lavataste/TizenFX", "max_stars_repo_stars_event_min_datetime": "2018-01-01T19:10:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-03T07:38:55.000Z", "max_issues_repo_path": "test/Tizen.NUI.Tests/Tizen.NUI.Devel.Tests/testcase/public/XamlBinding/TSSizeTypeConverter.cs", "max_issues_repo_name": "lavataste/TizenFX", "max_issues_repo_issues_event_min_datetime": "2017-12-27T05:26:36.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T10:49:53.000Z", "max_forks_repo_path": "test/Tizen.NUI.Tests/Tizen.NUI.Devel.Tests/testcase/public/XamlBinding/TSSizeTypeConverter.cs", "max_forks_repo_name": "lavataste/TizenFX", "max_forks_repo_forks_event_min_datetime": "2017-12-26T06:29:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T03:16:35.000Z"} | {"max_stars_count": 149.0, "max_issues_count": 2078.0, "max_forks_count": 394.0, "avg_line_length": 37.7469879518, "max_line_length": 100, "alphanum_fraction": 0.5920842643} | using NUnit.Framework;
using System;
using Tizen.NUI.Binding;
using Tizen.NUI.Xaml;
namespace Tizen.NUI.Devel.Tests
{
using tlog = Tizen.Log;
[TestFixture]
[Description("public/XamlBinding/SizeTypeConverter")]
internal class PublicSizeTypeConverterTest
{
private const string tag = "NUITEST";
[SetUp]
public void Init()
{
tlog.Info(tag, "Init() is called!");
}
[TearDown]
public void Destroy()
{
tlog.Info(tag, "Destroy() is called!");
}
[Test]
[Category("P1")]
[Description("SizeTypeConverter SizeTypeConverter")]
[Property("SPEC", "Tizen.NUI.Binding.SizeTypeConverter.SizeTypeConverter C")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "CONSTR")]
public void SizeTypeConverterConstructor()
{
tlog.Debug(tag, $"SizeTypeConverterConstructor START");
Type type = typeof(string);
SizeTypeConverter t2 = new SizeTypeConverter();
Assert.IsNotNull(t2, "null SizeTypeConverter");
Assert.IsInstanceOf<SizeTypeConverter>(t2, "Should return SizeTypeConverter instance.");
tlog.Debug(tag, $"SizeTypeConverterConstructor END");
}
[Test]
[Category("P1")]
[Description("SizeTypeConverter ConvertFromInvariantString")]
[Property("SPEC", "Tizen.NUI.Binding.SizeTypeConverter.ConvertFromInvariantString M")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "MR")]
public void ConvertFromInvariantStringTest()
{
tlog.Debug(tag, $"ConvertFromInvariantStringTest START");
try
{
SizeTypeConverter t2 = new SizeTypeConverter();
Assert.IsNotNull(t2, "null SizeTypeConverter");
var b = t2.ConvertFromInvariantString("2,2");
Assert.IsNotNull(b, "null Binding");
var b2 = t2.ConvertFromInvariantString("2,2,2");
Assert.IsNotNull(b2, "null Binding");
}
catch (Exception e)
{
Assert.Fail("Caught Exception" + e.ToString());
}
tlog.Debug(tag, $"ConvertFromInvariantStringTest END (OK)");
}
[Test]
[Category("P1")]
[Description("SizeTypeConverter ConvertToString")]
[Property("SPEC", "Tizen.NUI.Binding.SizeTypeConverter.ConvertToString M")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "MR")]
public void ConvertToStringTest2()
{
tlog.Debug(tag, $"ConvertToStringTest2 START");
SizeTypeConverter t2 = new SizeTypeConverter();
Assert.IsNotNull(t2, "null SizeTypeConverter");
var ret1 = t2.ConvertToString(null);
Assert.AreEqual(string.Empty, ret1, "null ImageShadow");
var ret2 = t2.ConvertToString(new Size(2,2,2));
Assert.IsNotNull(ret2, "null Size");
tlog.Debug(tag, $"ConvertToStringTest2 END");
}
[Test]
[Category("P2")]
[Description("SizeTypeConverter ConvertFromInvariantString")]
[Property("SPEC", "Tizen.NUI.Binding.SizeTypeConverter.ConvertFromInvariantString M")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "MR")]
public void ConvertFromInvariantStringTest3()
{
tlog.Debug(tag, $"ConvertFromInvariantStringTest3 START");
SizeTypeConverter t2 = new SizeTypeConverter();
Assert.IsNotNull(t2, "null SizeTypeConverter");
Assert.Throws<InvalidOperationException>(() => t2.ConvertFromInvariantString(null));
tlog.Debug(tag, $"ConvertFromInvariantStringTest3 END");
}
[Test]
[Category("P1")]
[Description("Size2DTypeConverter ConvertFromInvariantString")]
[Property("SPEC", "Tizen.NUI.Binding.Size2DTypeConverter.ConvertFromInvariantString M")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "MR")]
public void ConvertFromInvariantStringTest2()
{
tlog.Debug(tag, $"ConvertFromInvariantStringTest2 START");
try
{
Size2DTypeConverter t2 = new Size2DTypeConverter();
Assert.IsNotNull(t2, "null Size2DTypeConverter");
var b = t2.ConvertFromInvariantString("2,2");
Assert.IsNotNull(b, "null Binding");
}
catch (Exception e)
{
Assert.Fail("Caught Exception" + e.ToString());
}
tlog.Debug(tag, $"ConvertFromInvariantStringTest2 END (OK)");
}
[Test]
[Category("P1")]
[Description("Size2DTypeConverter ConvertToString")]
[Property("SPEC", "Tizen.NUI.Binding.Size2DTypeConverter.ConvertToString M")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "MR")]
public void ConvertToStringTest3()
{
tlog.Debug(tag, $"ConvertToStringTest2 START");
Size2DTypeConverter t2 = new Size2DTypeConverter();
Assert.IsNotNull(t2, "null Size2DTypeConverter");
var ret1 = t2.ConvertToString(null);
Assert.AreEqual(string.Empty, ret1, "null ImageShadow");
var ret2 = t2.ConvertToString(new Size2D(2, 2));
Assert.IsNotNull(ret2, "null Size");
tlog.Debug(tag, $"ConvertToStringTest3 END");
}
[Test]
[Category("P2")]
[Description("Size2DTypeConverter ConvertFromInvariantString")]
[Property("SPEC", "Tizen.NUI.Binding.Size2DTypeConverter.ConvertFromInvariantString M")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "MR")]
public void ConvertFromInvariantStringTest4()
{
tlog.Debug(tag, $"ConvertFromInvariantStringTest4 START");
Size2DTypeConverter t2 = new Size2DTypeConverter();
Assert.IsNotNull(t2, "null Size2DTypeConverter");
Assert.Throws<InvalidOperationException>(() => t2.ConvertFromInvariantString(null));
tlog.Debug(tag, $"ConvertFromInvariantStringTest4 END");
}
}
} |
||||
TheStack | da2f0e2589880d4aa0e4ee4a71606a527bcddc87 | C#code:C# | {"size": 13382, "ext": "cs", "max_stars_repo_path": "GygaxCore/Tools/CoordinateSystem.cs", "max_stars_repo_name": "ph463/Gygax", "max_stars_repo_stars_event_min_datetime": "2019-03-07T19:11:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-24T08:57:27.000Z", "max_issues_repo_path": "GygaxCore/Tools/CoordinateSystem.cs", "max_issues_repo_name": "ph463/Gygax", "max_issues_repo_issues_event_min_datetime": "2016-09-27T15:13:37.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-05T06:29:16.000Z", "max_forks_repo_path": "GygaxCore/Tools/CoordinateSystem.cs", "max_forks_repo_name": "ph463/Gygax", "max_forks_repo_forks_event_min_datetime": "2016-06-22T13:37:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-09T07:18:38.000Z"} | {"max_stars_count": 11.0, "max_issues_count": 36.0, "max_forks_count": 10.0, "avg_line_length": 34.4896907216, "max_line_length": 170, "alphanum_fraction": 0.4855029144} | using System;
using System.CodeDom;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Accord.Math.Decompositions;
using Emgu.CV.Features2D;
using HelixToolkit.Wpf;
using HelixToolkit.Wpf.SharpDX;
using HelixToolkit.Wpf.SharpDX.Core;
using Microsoft.VisualBasic.FileIO;
using SharpDX;
using Matrix = Accord.Math.Matrix;
using System.Windows.Media.Media3D;
using Accord.Imaging;
using AForge;
namespace GygaxCore.DataStructures
{
/// <summary>
/// http://nghiaho.com/?page_id=671
/// </summary>
public class CoordinateSystem
{
public bool ReferenceSystem;
public CoordinateSystem ParentCoordinateSystem;
public List<Correspondence> Correspondences = new List<Correspondence>();
public Matrix3D Transformation;
public struct Correspondence
{
public Vector3 ParentCoordinateSystem;
public Vector3 LocalCoordinateSystem;
}
public Correspondence Centroid;
public SharpDX.Quaternion Rotation
{
get
{
SharpDX.Quaternion returnValue;
var rotationMatrix = RotationMatrix;
rotationMatrix.Transpose();
SharpDX.Quaternion.RotationMatrix(ref rotationMatrix, out returnValue);
return returnValue;
}
}
public Vector3 ConvertToParentCoordinate(Vector3 localPoint)
{
return (MultiplyMatrixVector(RotationMatrix, localPoint) + Translation - Centroid.ParentCoordinateSystem) / (float)Scaling + Centroid.ParentCoordinateSystem;
}
public Vector3 ConvertToLocalCoordinate(Vector3 parentPoint)
{
var invertedRotationMatrix = RotationMatrix;
invertedRotationMatrix.Transpose();
return MultiplyMatrixVector(invertedRotationMatrix, parentPoint - Translation);
}
public static Vector3 MultiplyMatrixVector(Matrix3x3 m, Vector3 v)
{
return new Vector3(m.M11 * v.X + m.M12 * v.Y + m.M13 * v.Z, m.M21 * v.X + m.M22 * v.Y + m.M23 * v.Z, m.M31 * v.X + m.M32 * v.Y + m.M33 * v.Z);
}
public Matrix3x3 RotationMatrix => new Matrix3x3(
(float)_matrix[0, 0], (float)_matrix[0, 1], (float)_matrix[0, 2],
(float)_matrix[1, 0], (float)_matrix[1, 1], (float)_matrix[1, 2],
(float)_matrix[2, 0], (float)_matrix[2, 1], (float)_matrix[2, 2]);
private double[,] _matrix = new double[3,3];
public Vector3 Translation;
public float Error => FindError();
public void CalculateHomography()
{
FindCentroid();
FindOptimalRotation();
FindTranslation();
FindScaling();
}
private float FindError()
{
double v =
Correspondences.Sum(
correspondence =>
Math.Pow(
(ConvertToParentCoordinate(correspondence.LocalCoordinateSystem) - correspondence.ParentCoordinateSystem).Length(), 2));
return (float)v;
}
private void FindCentroid()
{
var n = Correspondences.Count;
Centroid.LocalCoordinateSystem = Correspondences.Aggregate(Centroid.LocalCoordinateSystem,
(current, correspondence) => current + correspondence.LocalCoordinateSystem/n);
Centroid.ParentCoordinateSystem = Correspondences.Aggregate(Centroid.ParentCoordinateSystem,
(current, correspondence) => current + correspondence.ParentCoordinateSystem/n);
}
private void FindOptimalRotation()
{
var h = new double[3,3];
foreach (var correspondence in Correspondences)
{
var pa = correspondence.LocalCoordinateSystem - Centroid.LocalCoordinateSystem;
var pb = correspondence.ParentCoordinateSystem - Centroid.ParentCoordinateSystem;
var pam = Matrix.Create<double>(3, 1);
pam[0, 0] = pa.X;
pam[1, 0] = pa.Y;
pam[2, 0] = pa.Z;
var pbm = Matrix.Create<double>(1, 3);
pbm[0, 0] = pb.X;
pbm[0, 1] = pb.Y;
pbm[0, 2] = pb.Z;
var hl = Matrix.Add(h, Matrix.Multiply(pam, pbm));
h = hl;
}
var svd = new SingularValueDecomposition(h);
var r = Matrix.Multiply(svd.RightSingularVectors,Matrix.Transpose(svd.LeftSingularVectors));
if (Matrix.Determinant(r) < 0)
{
var v = svd.RightSingularVectors;
v[0, 2] *= -1;
v[1, 2] *= -1;
v[2, 2] *= -1;
r = Matrix.Multiply(v, Matrix.Transpose(svd.LeftSingularVectors));
}
_matrix = r;
}
private void FindTranslation()
{
var pam = Matrix.Create<double>(3, 1);
pam[0, 0] = Centroid.LocalCoordinateSystem.X;
pam[1, 0] = Centroid.LocalCoordinateSystem.Y;
pam[2, 0] = Centroid.LocalCoordinateSystem.Z;
var pbm = Matrix.Create<double>(3, 1);
pbm[0, 0] = Centroid.ParentCoordinateSystem.X;
pbm[1, 0] = Centroid.ParentCoordinateSystem.Y;
pbm[2, 0] = Centroid.ParentCoordinateSystem.Z;
var a = Matrix.Add(Matrix.Multiply(-1, Matrix.Multiply(_matrix, pam)), pbm);
Translation = new Vector3((float)a[0,0], (float)a[1, 0], (float)a[2, 0]);
}
public Double Scaling;
private void FindScaling()
{
Scaling = 0.0;
foreach (var correspondence in Correspondences)
{
var parentVectorLength =
(correspondence.ParentCoordinateSystem - Centroid.ParentCoordinateSystem).Length();
var localVectorLength =
(correspondence.LocalCoordinateSystem - Centroid.LocalCoordinateSystem).Length();
Scaling += localVectorLength/parentVectorLength;
}
Scaling /= Correspondences.Count;
}
public void LoadCorrespondences(string filename)
{
using (TextFieldParser parser = new TextFieldParser(filename))
{
parser.TextFieldType = FieldType.Delimited;
parser.SetDelimiters(",");
while (!parser.EndOfData)
{
//Processing row
string[] fields = parser.ReadFields();
if (fields.Count() != 6)
return;
Correspondences.Add(new Correspondence()
{
LocalCoordinateSystem = new Vector3(
float.Parse(fields[0]),
float.Parse(fields[1]),
float.Parse(fields[2])
),
ParentCoordinateSystem = new Vector3(
float.Parse(fields[3]),
float.Parse(fields[4]),
float.Parse(fields[5])
)
});
}
}
}
public static Matrix3D OpenTransformation(string filename)
{
if (!File.Exists(filename))
return Matrix3D.Identity;
var fileUri = new Uri(filename);
if (!File.Exists(fileUri.LocalPath))
return Matrix3D.Identity;
StreamReader sr = new StreamReader(fileUri.LocalPath, ASCIIEncoding.ASCII);
var s = Array.ConvertAll(sr.ReadLine().Trim().Split(','), double.Parse);
if (s.Count() != 16)
throw new Exception("Not a proper transformation file");
return new Matrix3D
{
M11 = s[0],
M12 = s[1],
M13 = s[2],
M14 = s[3],
M21 = s[4],
M22 = s[5],
M23 = s[6],
M24 = s[7],
M31 = s[8],
M32 = s[9],
M33 = s[10],
M34 = s[11],
OffsetX = s[12],
OffsetY = s[13],
OffsetZ = s[14],
M44 = s[15],
};
}
public static void WriteTransformation(Uri filename, Matrix3D transformation)
{
var t = transformation;
var p = new[]
{
t.M11, t.M12, t.M13, t.M14,
t.M21, t.M22, t.M23, t.M24,
t.M31, t.M32, t.M33, t.M34,
t.OffsetX, t.OffsetY, t.OffsetZ,t.M44,
};
var l = string.Join(",", p.Select(c => c.ToString(CultureInfo.InvariantCulture)).ToArray());
using (StreamWriter writer =
new StreamWriter(filename.LocalPath))
{
writer.Write(l);
}
}
//public void SaveTransform(string fileUri)
//{
// const string separator = ",";
// using (StreamWriter writer = new StreamWriter(fileUri))
// {
// writer.WriteLine(
// RotationMatrix.M11 + separator +
// RotationMatrix.M12 + separator +
// RotationMatrix.M13 + separator +
// RotationMatrix.M21 + separator +
// RotationMatrix.M22 + separator +
// RotationMatrix.M23 + separator +
// RotationMatrix.M31 + separator +
// RotationMatrix.M32 + separator +
// RotationMatrix.M33 + separator +
// Translation.X + separator +
// Translation.Y + separator +
// Translation.Z + separator +
// Scaling
// );
// }
//}
//public void LoadTransform(string fileUri)
//{
// using (TextFieldParser parser = new TextFieldParser(fileUri))
// {
// parser.TextFieldType = FieldType.Delimited;
// parser.SetDelimiters(",");
// while (!parser.EndOfData)
// {
// //Processing row
// string[] fields = parser.ReadFields();
// if (fields.Count() != 13)
// return;
// _matrix[0, 0] = float.Parse(fields[0]);
// _matrix[0, 1] = float.Parse(fields[1]);
// _matrix[0, 2] = float.Parse(fields[2]);
// _matrix[1, 0] = float.Parse(fields[3]);
// _matrix[1, 1] = float.Parse(fields[4]);
// _matrix[1, 2] = float.Parse(fields[5]);
// _matrix[2, 0] = float.Parse(fields[6]);
// _matrix[2, 1] = float.Parse(fields[7]);
// _matrix[2, 2] = float.Parse(fields[8]);
// Translation = new Vector3(
// float.Parse(fields[9]),
// float.Parse(fields[10]),
// float.Parse(fields[11])
// );
// Scaling = float.Parse(fields[12]);
// }
// }
//}
public void AddTestelements()
{
Correspondences = new List<Correspondence>();
const int n = 10;
var t = Matrix.Random(3, 1);
var svd = new SingularValueDecomposition(Matrix.Random(3, 3));
var r = Matrix.Multiply(svd.LeftSingularVectors, svd.RightSingularVectors);
if (Matrix.Determinant(r) < 0)
{
var v = svd.RightSingularVectors;
v[0, 2] *= -1;
v[1, 2] *= -1;
v[2, 2] *= -1;
r = Matrix.Multiply(v, Matrix.Transpose(svd.LeftSingularVectors));
}
var a = Matrix.Random(3, n);
var tExpanded = t;
for (int i = 0; i < n-1; i++)
tExpanded = Matrix.InsertColumn(tExpanded, Matrix.GetColumn(t,0));
var b = Matrix.Add(Matrix.Multiply(r, a),tExpanded);
for (int i = 0; i < n; i++)
{
Correspondences.Add(new Correspondence
{
LocalCoordinateSystem = new Vector3(Matrix.GetColumn(a, i).Select(j => (float)j).ToArray()),
ParentCoordinateSystem = new Vector3(Matrix.GetColumn(b, i).Select(j => (float)j).ToArray())
});
}
}
}
}
|