content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
// <copyright file="BrowserTypes.cs" company="Automate The Planet Ltd.">
// Copyright 2016 Automate The Planet Ltd.
// Licensed under the Apache License, Version 2.0 (the "License");
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
// <author>Anton Angelov</author>
// <site>http://automatetheplanet.com/</site>
namespace BehavioursDesignPattern.Core
{
public enum BrowserTypes
{
Firefox,
InternetExplorer,
Chrome,
NotSet
}
} | 38.083333 | 85 | 0.723195 | [
"Apache-2.0"
] | alanmacgowan/AutomateThePlanet-Learning-Series | DesignPatternsInAutomatedTesting-Series/BehavioursDesignPattern/Core/BrowserTypes.cs | 916 | C# |
// FILE AUTOGENERATED. DO NOT MODIFY
using System;
namespace Starfield.Core.Block.Blocks {
[Block("minecraft:potatoes", 307, 6342, 6349, 6342)]
public class BlockPotatoes : BlockBase {
public override ushort State {
get {
if(Age == 0) {
return 6342;
}
if(Age == 1) {
return 6343;
}
if(Age == 2) {
return 6344;
}
if(Age == 3) {
return 6345;
}
if(Age == 4) {
return 6346;
}
if(Age == 5) {
return 6347;
}
if(Age == 6) {
return 6348;
}
if(Age == 7) {
return 6349;
}
return DefaultState;
}
set {
if(value == 6342) {
Age = 0;
}
if(value == 6343) {
Age = 1;
}
if(value == 6344) {
Age = 2;
}
if(value == 6345) {
Age = 3;
}
if(value == 6346) {
Age = 4;
}
if(value == 6347) {
Age = 5;
}
if(value == 6348) {
Age = 6;
}
if(value == 6349) {
Age = 7;
}
}
}
public int Age { get; set; } = 0;
public BlockPotatoes() {
State = DefaultState;
}
public BlockPotatoes(ushort state) : base(state) {
if(state < MinimumState || state > MaximumState) {
throw new ArgumentOutOfRangeException("state");
}
State = state;
}
public BlockPotatoes(int age) {
Age = age;
}
}
} | 22.23 | 64 | 0.292398 | [
"MIT"
] | StarfieldMC/Starfield | Starfield.Core/Block/Blocks/BlockPotatoes.cs | 2,223 | C# |
using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.Serialization;
using Newtonsoft.Json;
namespace Alpaca.Markets
{
[SuppressMessage(
"Microsoft.Performance", "CA1812:Avoid uninstantiated internal classes",
Justification = "Object instances of this class will be created by Newtonsoft.JSON library.")]
internal sealed class JsonLastTrade : ILastTrade
{
internal sealed class Last
{
[JsonProperty(PropertyName = "x", Required = Required.Always)]
public Int64 Exchange { get; set; }
[JsonProperty(PropertyName = "p", Required = Required.Always)]
public Decimal Price { get; set; }
[JsonProperty(PropertyName = "s", Required = Required.Always)]
public Int64 Size { get; set; }
[JsonProperty(PropertyName = "t", Required = Required.Always)]
public Int64 Timestamp { get; set; }
[JsonProperty(PropertyName = "T", Required = Required.Always)]
public String Symbol { get; set; }
}
[JsonProperty(PropertyName = "results", Required = Required.Always)]
public Last Nested { get; set; }
[JsonProperty(PropertyName = "status", Required = Required.Always)]
public String Status { get; set; }
[JsonIgnore]
public String Symbol => Nested.Symbol;
[JsonIgnore]
public Int64 Exchange => Nested.Exchange;
[JsonIgnore]
public Decimal Price => Nested.Price;
[JsonIgnore]
public Int64 Size => Nested.Size;
[JsonIgnore]
public DateTime Time { get; private set; }
[OnDeserialized]
internal void OnDeserializedMethod(
StreamingContext context)
{
Time = DateTimeHelper.FromUnixTimeNanoseconds(Nested.Timestamp);
}
}
}
| 31.216667 | 102 | 0.619861 | [
"Apache-2.0"
] | Xallen79/alpaca-trade-api-csharp | Alpaca.Markets/Messages/JsonLastTrade.cs | 1,875 | C# |
using FortnoxNET.Utils;
using Newtonsoft.Json;
namespace FortnoxNET.Models.Contract
{
[JsonPropertyClass("Contracts")]
public class ContractSubset
{
[JsonReadOnly]
[JsonProperty(PropertyName = "@url")]
public string Url { get; set; }
public bool? Continuous { get; set; }
[JsonReadOnly]
public int? ContractLength { get; set; }
public string Currency { get; set; }
public string CustomerName { get; set; }
public string CustomerNumber { get; set; }
public string DocumentNumber { get; set; }
public int? InvoiceInterval { get; set; }
[JsonReadOnly]
public int? InvoicesRemaining { get; set; }
public string LastInvoiceDate { get; set; }
public string PeriodStart { get; set; }
public string PeriodEnd { get; set; }
public string Status { get; set; }
public string TemplateNumber { get; set; }
public decimal? Total { get; set; }
}
}
| 22.622222 | 51 | 0.602161 | [
"MIT"
] | PolrSE/fortnox.NET | Fortnox.NET/Models/Contract/ContractSubset.cs | 1,020 | C# |
using System;
using System.Xml;
using System.Text;
namespace AIMLbot.AIMLTagHandlers
{
/// <summary>
/// The thatstar element tells the AIML interpreter that it should substitute the contents of a
/// wildcard from a pattern-side that element.
///
/// The thatstar element has an optional integer index attribute that indicates which wildcard
/// to use; the minimum acceptable value for the index is "1" (the first wildcard).
///
/// An AIML interpreter should raise an error if the index attribute of a star specifies a
/// wildcard that does not exist in the that element's pattern content. Not specifying the index
/// is the same as specifying an index of "1".
///
/// The thatstar element does not have any content.
/// </summary>
public class thatstar : AIMLbot.Utils.AIMLTagHandler
{
/// <summary>
/// Ctor
/// </summary>
/// <param name="bot">The bot involved in this request</param>
/// <param name="user">The user making the request</param>
/// <param name="query">The query that originated this node</param>
/// <param name="request">The request inputted into the system</param>
/// <param name="result">The result to be passed to the user</param>
/// <param name="templateNode">The node to be processed</param>
public thatstar(AIMLbot.Bot bot,
AIMLbot.User user,
AIMLbot.Utils.SubQuery query,
AIMLbot.Request request,
AIMLbot.Result result,
XmlNode templateNode)
: base(bot, user, query, request, result, templateNode)
{
}
protected override string ProcessChange()
{
if (this.templateNode.Name.ToLower() == "thatstar")
{
if (this.templateNode.Attributes.Count == 0)
{
if (this.query.ThatStar.Count > 0)
{
return (string)this.query.ThatStar[0];
}
else
{
this.bot.writeToLog("ERROR! An out of bounds index to thatstar was encountered when processing the input: " + this.request.rawInput);
}
}
else if (this.templateNode.Attributes.Count == 1)
{
if (this.templateNode.Attributes[0].Name.ToLower() == "index")
{
if (this.templateNode.Attributes[0].Value.Length > 0)
{
try
{
int result = Convert.ToInt32(this.templateNode.Attributes[0].Value.Trim());
if (this.query.ThatStar.Count > 0)
{
if (result > 0)
{
return (string)this.query.ThatStar[result - 1];
}
else
{
this.bot.writeToLog("ERROR! An input tag with a bady formed index (" + this.templateNode.Attributes[0].Value + ") was encountered processing the input: " + this.request.rawInput);
}
}
else
{
this.bot.writeToLog("ERROR! An out of bounds index to thatstar was encountered when processing the input: " + this.request.rawInput);
}
}
catch
{
this.bot.writeToLog("ERROR! A thatstar tag with a bady formed index (" + this.templateNode.Attributes[0].Value + ") was encountered processing the input: " + this.request.rawInput);
}
}
}
}
}
return string.Empty;
}
}
}
| 45.763441 | 219 | 0.468985 | [
"MIT"
] | Karthikeyu/AR-VoicechatBot-Unity | Assets/gitFiles/AIMLBot/AIMLbot/AIMLTagHandlers/thatstar.cs | 4,256 | C# |
//----------------------------------------------------------------------------------------
// Copyright © 2007 - 2017 Tangible Software Solutions Inc.
// This class can be used by anyone provided that the copyright notice remains intact.
//
// This class includes methods to convert Java rectangular arrays (jagged arrays
// with inner arrays of the same length).
//----------------------------------------------------------------------------------------
internal static class RectangularArrays
{
internal static float[][] ReturnRectangularFloatArray(int size1, int size2)
{
float[][] newArray = new float[size1][];
for (int array1 = 0; array1 < size1; array1++)
{
newArray[array1] = new float[size2];
}
return newArray;
}
} | 39.5 | 91 | 0.512658 | [
"BSD-3-Clause"
] | AG-Teammate/transform-swf-net-core | RectangularArrays.cs | 793 | C# |
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
using UnrealBuildTool;
using System.Collections.Generic;
[SupportedPlatforms(UnrealTargetPlatform.Win64, UnrealTargetPlatform.Mac)]
public class MinidumpDiagnosticsTarget : TargetRules
{
public MinidumpDiagnosticsTarget( TargetInfo Target ) : base(Target)
{
Type = TargetType.Program;
LinkType = TargetLinkType.Monolithic;
LaunchModuleName = "MinidumpDiagnostics";
}
// TargetRules interface.
public override void SetupGlobalEnvironment(
TargetInfo Target,
ref LinkEnvironmentConfiguration OutLinkEnvironmentConfiguration,
ref CPPEnvironmentConfiguration OutCPPEnvironmentConfiguration
)
{
bCompileLeanAndMeanUE = true;
bCompileICU = false;
// Don't need editor
bBuildEditor = false;
// MinidumpDiagnostics doesn't ever compile with the engine linked in
bCompileAgainstEngine = false;
bIncludeADO = false;
//bCompileICU = false;
// MinidumpDiagnostics.exe has no exports, so no need to verify that a .lib and .exp file was emitted by the linker.
OutLinkEnvironmentConfiguration.bHasExports = false;
// Do NOT produce additional console app exe
OutLinkEnvironmentConfiguration.bIsBuildingConsoleApplication = true;
OutCPPEnvironmentConfiguration.Definitions.Add("MINIDUMPDIAGNOSTICS=1");
OutCPPEnvironmentConfiguration.Definitions.Add("NOINITCRASHREPORTER=1");
}
}
| 30.282609 | 118 | 0.79038 | [
"MIT"
] | CaptainUnknown/UnrealEngine_NVIDIAGameWorks | Engine/Source/Programs/MinidumpDiagnostics/MinidumpDiagnostics.Target.cs | 1,393 | C# |
/////////////////////////////////////////////////////////////////////////////////
//
// vp_EditorApplicationQuit.cs
// © VisionPunk. All Rights Reserved.
// https://twitter.com/VisionPunk
// http://www.visionpunk.com
//
// description: this is a small convenience feature allowing the game to quit
// itself when running in the editor by means of vp_GlobalEvent
// "EditorApplicationQuit"
//
/////////////////////////////////////////////////////////////////////////////////
using UnityEngine;
using UnityEditor;
[InitializeOnLoad]
public class vp_EditorApplicationQuit : Editor
{
static vp_EditorApplicationQuit()
{
vp_GlobalEvent.Register("EditorApplicationQuit", () => { EditorApplication.isPlaying = false; });
}
}
| 26.428571 | 99 | 0.574324 | [
"Apache-2.0"
] | M4RZB4Ni/FpsShooter | Assets/UFPS/Base/Scripts/Core/Editor/vp_EditorApplicationQuit.cs | 743 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("DML")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("DML")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("6c0adbc2-8aa3-4e22-8e9c-46fe2c23f4c2")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.756757 | 84 | 0.745168 | [
"MIT"
] | Ranin26/msdn-code-gallery-microsoft | Visual Studio Product Team/Official Visual Studio 2010 Samples for C# 4.0/46872-Official Visual Studio 2010 Samples for C# 4.0/LINQ to XML - Using Data Manipulation Language (DML)/C#/DML/Properties/AssemblyInfo.cs | 1,400 | C# |
public class BattleReport
{
public Unit[] units;
public float duration;
public bool isWin;
}
| 15 | 26 | 0.685714 | [
"MIT"
] | alkaitagi/INNO-F21-PCGG | Assets/Scripts/Simulation/BattleReport.cs | 105 | C# |
namespace StockSharp.Community
{
using System;
using System.ServiceModel;
/// <summary>
/// The interface describing the registration service.
/// </summary>
[ServiceContract(Namespace = "http://stocksharp.com/services/sessionservice.svc")]
public interface ISessionService
{
/// <summary>
/// Create a new activity session.
/// </summary>
/// <param name="product">Product.</param>
/// <param name="sessionId">Session ID (authentication).</param>
/// <returns>Session ID (activity).</returns>
[OperationContract]
long CreateSession(Products product, Guid sessionId);
/// <summary>
/// Track the session is alive.
/// </summary>
/// <param name="sessionId">Session ID (activity).</param>
[OperationContract]
void Ping(long sessionId);
/// <summary>
/// Close the session.
/// </summary>
/// <param name="sessionId">Session ID (activity).</param>
[OperationContract]
void CloseSession(long sessionId);
}
} | 27.314286 | 83 | 0.680962 | [
"Apache-2.0"
] | 1M15M3/StockSharp | Community/ISessionService.cs | 956 | C# |
using System.Collections.Generic;
using System.Linq;
using System.Text.Json.Serialization;
using WcPhdc.OpenHim.Mediator.Models;
namespace WcPhdc.OpenHim.Mediator.Configuration
{
public class MediatorConfig
{
[JsonPropertyName("openHimAuth")]
public OpenHimAuth OpenHimAuth { get; set; }
[JsonPropertyName("mediatorCore")]
public MediatorCore MediatorCore { get; set; }
[JsonPropertyName("mediatorSetup")]
public MediatorSetup MediatorSetup { get; set; }
[JsonPropertyName("orchestrations"), JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
public List<Orchestration> Orchestrations { get; set; } = new List<Orchestration>();
public bool HasOrchestrations()
{
return Orchestrations != null && Orchestrations.Any();
}
}
public class OpenHimAuth
{
[JsonPropertyName("coreUsername")]
public string CoreUsername { get; set; }
[JsonPropertyName("corePassword")]
public string CorePassword { get; set; }
[JsonPropertyName("apiClientName")]
public string ApiClientName { get; set; }
[JsonPropertyName("apiClientPassword")]
public string ApiClientPassword { get; set; }
[JsonPropertyName("trustSelfSigned")]
public bool TrustSelfSigned { get; set; }
[JsonPropertyName("ignoreOutgoingOpenHimAuthFailures")]
public bool IgnoreOutgoingOpenHimAuthFailures { get; set; }
}
public class MediatorCore
{
[JsonPropertyName("openHimCoreHost")]
public string OpenHimCoreHost { get; set; }
[JsonPropertyName("openHimCoreAuthPath")]
public string OpenHimCoreAuthPath { get; set; }
[JsonPropertyName("openHimRegisterMediatorPath")]
public string OpenHimRegisterMediatorPath { get; set; }
[JsonPropertyName("openHimHeartbeatpath")]
public string OpenHimHeartbeatPath { get; set; }
[JsonPropertyName("heartbeatEnabled")]
public bool HeartbeatEnabled { get; set; }
[JsonPropertyName("heartbeatInterval")]
public int HeartbeatInterval { get; set; }
}
public class MediatorSetup
{
[JsonPropertyName("urn")]
public string Urn { get; set; }
[JsonPropertyName("version")]
public string Version { get; set; }
[JsonPropertyName("name")]
public string Name { get; set; }
[JsonPropertyName("description")]
public string Description { get; set; }
[JsonPropertyName("defaultChannelConfig")]
public ChannelConfig[] DefaultChannelConfig { get; set; }
[JsonPropertyName("endpoints")]
public Location[] Endpoints { get; set; }
}
public class ChannelConfig
{
[JsonPropertyName("name")]
public string Name { get; set; }
[JsonPropertyName("urlPattern")]
public string UrlPattern { get; set; }
[JsonPropertyName("type")]
public string Type { get; set; }
[JsonPropertyName("routes")]
public Location[] Routes { get; set; }
[JsonPropertyName("allow")]
public string[] Allow { get; set; }
}
public class Location
{
[JsonPropertyName("name")]
public string Name { get; set; }
[JsonPropertyName("host")]
public string Host { get; set; }
[JsonPropertyName("port")]
public string Port { get; set; }
[JsonPropertyName("primary")]
public bool Primary { get; set; }
[JsonPropertyName("type")]
public string Type { get; set; }
[JsonPropertyName("path")]
public string Path { get; set; }
}
}
| 28.419847 | 108 | 0.627182 | [
"Apache-2.0"
] | mornemaritz/openhim-mediator-hl7-validator | src/WcPhdc.OpenHim.Mediator/Configuration/MediatorConfig.cs | 3,725 | C# |
// ***********************************************************************
// Assembly : IronyModManager
// Author : Mario
// Created : 03-18-2020
//
// Last Modified By : Mario
// Last Modified On : 02-27-2022
// ***********************************************************************
// <copyright file="MainConflictSolverViewModel.cs" company="Mario">
// Mario
// </copyright>
// <summary></summary>
// ***********************************************************************
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reactive;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Text;
using System.Threading.Tasks;
using Avalonia.Collections;
using Avalonia.Threading;
using IronyModManager.Common;
using IronyModManager.Common.Events;
using IronyModManager.Common.ViewModels;
using IronyModManager.DI;
using IronyModManager.Implementation.Actions;
using IronyModManager.Implementation.Hotkey;
using IronyModManager.Implementation.Overlay;
using IronyModManager.Localization;
using IronyModManager.Localization.Attributes;
using IronyModManager.Models.Common;
using IronyModManager.Services.Common;
using IronyModManager.Shared;
using IronyModManager.Shared.Models;
using IronyModManager.ViewModels.Controls;
using ReactiveUI;
using SmartFormat;
using ValueType = IronyModManager.Shared.Models.ValueType;
namespace IronyModManager.ViewModels
{
/// <summary>
/// Class MainConflictSolverControlViewModel.
/// Implements the <see cref="IronyModManager.Common.ViewModels.BaseViewModel" />
/// </summary>
/// <seealso cref="IronyModManager.Common.ViewModels.BaseViewModel" />
[ExcludeFromCoverage("This should be tested via functional testing.")]
public class MainConflictSolverControlViewModel : BaseViewModel
{
#region Fields
/// <summary>
/// The invalid key
/// </summary>
private const string InvalidKey = "invalid";
/// <summary>
/// The localization directory
/// </summary>
private static readonly string LocalizationDirectory = $"{Shared.Constants.LocalizationDirectory}{Path.DirectorySeparatorChar}";
/// <summary>
/// The application action
/// </summary>
private readonly IAppAction appAction;
/// <summary>
/// The hotkey pressed handler
/// </summary>
private readonly ConflictSolverViewHotkeyPressedHandler hotkeyPressedHandler;
/// <summary>
/// The identifier generator
/// </summary>
private readonly IIDGenerator idGenerator;
/// <summary>
/// The localization manager
/// </summary>
private readonly ILocalizationManager localizationManager;
/// <summary>
/// The logger
/// </summary>
private readonly ILogger logger;
/// <summary>
/// The mod patch collection service
/// </summary>
private readonly IModPatchCollectionService modPatchCollectionService;
/// <summary>
/// The notification action
/// </summary>
private readonly INotificationAction notificationAction;
/// <summary>
/// The cached invalids
/// </summary>
private IHierarchicalDefinitions cachedInvalids;
/// <summary>
/// The filtering conflicts
/// </summary>
private bool filteringConflicts = false;
/// <summary>
/// The invalids checked
/// </summary>
private bool invalidsChecked;
/// <summary>
/// The take left binary
/// </summary>
private bool takeLeftBinary = false;
#endregion Fields
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="MainConflictSolverControlViewModel" /> class.
/// </summary>
/// <param name="hotkeyPressedHandler">The hotkey pressed handler.</param>
/// <param name="idGenerator">The identifier generator.</param>
/// <param name="modPatchCollectionService">The mod patch collection service.</param>
/// <param name="localizationManager">The localization manager.</param>
/// <param name="mergeViewer">The merge viewer.</param>
/// <param name="binaryMergeViewer">The binary merge viewer.</param>
/// <param name="modCompareSelector">The mod compare selector.</param>
/// <param name="ignoreConflictsRules">The ignore conflicts rules.</param>
/// <param name="modFilter">The mod filter.</param>
/// <param name="resetConflicts">The reset conflicts.</param>
/// <param name="dbSearch">The database search.</param>
/// <param name="customConflicts">The custom conflicts.</param>
/// <param name="logger">The logger.</param>
/// <param name="notificationAction">The notification action.</param>
/// <param name="appAction">The application action.</param>
public MainConflictSolverControlViewModel(ConflictSolverViewHotkeyPressedHandler hotkeyPressedHandler, IIDGenerator idGenerator,
IModPatchCollectionService modPatchCollectionService, ILocalizationManager localizationManager,
MergeViewerControlViewModel mergeViewer, MergeViewerBinaryControlViewModel binaryMergeViewer,
ModCompareSelectorControlViewModel modCompareSelector, ModConflictIgnoreControlViewModel ignoreConflictsRules,
ConflictSolverModFilterControlViewModel modFilter, ConflictSolverResetConflictsControlViewModel resetConflicts,
ConflictSolverDBSearchControlViewModel dbSearch, ConflictSolverCustomConflictsControlViewModel customConflicts,
ILogger logger, INotificationAction notificationAction, IAppAction appAction)
{
this.idGenerator = idGenerator;
this.modPatchCollectionService = modPatchCollectionService;
this.localizationManager = localizationManager;
this.logger = logger;
this.notificationAction = notificationAction;
this.appAction = appAction;
this.hotkeyPressedHandler = hotkeyPressedHandler;
MergeViewer = mergeViewer;
ModCompareSelector = modCompareSelector;
BinaryMergeViewer = binaryMergeViewer;
IgnoreConflictsRules = ignoreConflictsRules;
ModFilter = modFilter;
ResetConflicts = resetConflicts;
DatabaseSearch = dbSearch;
CustomConflicts = customConflicts;
}
#endregion Constructors
#region Properties
/// <summary>
/// Gets or sets the back.
/// </summary>
/// <value>The back.</value>
[StaticLocalization(LocalizationResources.Conflict_Solver.Back)]
public virtual string Back { get; protected set; }
/// <summary>
/// Gets or sets the back command.
/// </summary>
/// <value>The back command.</value>
public virtual ReactiveCommand<Unit, Unit> BackCommand { get; set; }
/// <summary>
/// Gets or sets a value indicating whether [back triggered].
/// </summary>
/// <value><c>true</c> if [back triggered]; otherwise, <c>false</c>.</value>
public virtual bool BackTriggered { get; protected set; }
/// <summary>
/// Gets or sets the binary merge viewer.
/// </summary>
/// <value>The binary merge viewer.</value>
public virtual MergeViewerBinaryControlViewModel BinaryMergeViewer { get; protected set; }
/// <summary>
/// Gets or sets the conflicted objects.
/// </summary>
/// <value>The conflicted objects.</value>
[StaticLocalization(LocalizationResources.Conflict_Solver.ConflictedObjects)]
public virtual string ConflictedObjects { get; protected set; }
/// <summary>
/// Gets or sets the conflicts.
/// </summary>
/// <value>The conflicts.</value>
public virtual IConflictResult Conflicts { get; set; }
/// <summary>
/// Gets or sets the context menu definition.
/// </summary>
/// <value>The context menu definition.</value>
public virtual IHierarchicalDefinitions ContextMenuDefinition { get; set; }
/// <summary>
/// Gets or sets the custom conflicts.
/// </summary>
/// <value>The custom conflicts.</value>
public virtual ConflictSolverCustomConflictsControlViewModel CustomConflicts { get; protected set; }
/// <summary>
/// Gets or sets the database search.
/// </summary>
/// <value>The database search.</value>
public virtual ConflictSolverDBSearchControlViewModel DatabaseSearch { get; protected set; }
/// <summary>
/// Gets or sets a value indicating whether [editing ignore conflicts rules].
/// </summary>
/// <value><c>true</c> if [editing ignore conflicts rules]; otherwise, <c>false</c>.</value>
public virtual bool EditingIgnoreConflictsRules { get; protected set; }
/// <summary>
/// Gets or sets the hierarchal conflicts.
/// </summary>
/// <value>The hierarchal conflicts.</value>
public virtual AvaloniaList<IHierarchicalDefinitions> HierarchalConflicts { get; protected set; }
/// <summary>
/// Gets or sets the ignore.
/// </summary>
/// <value>The ignore.</value>
[StaticLocalization(LocalizationResources.Conflict_Solver.Ignore)]
public virtual string Ignore { get; protected set; }
/// <summary>
/// Gets or sets the ignore command.
/// </summary>
/// <value>The ignore command.</value>
public virtual ReactiveCommand<Unit, Unit> IgnoreCommand { get; protected set; }
/// <summary>
/// Gets or sets the ignore conflicts rules.
/// </summary>
/// <value>The ignore conflicts rules.</value>
public virtual ModConflictIgnoreControlViewModel IgnoreConflictsRules { get; protected set; }
/// <summary>
/// Gets or sets a value indicating whether [ignore enabled].
/// </summary>
/// <value><c>true</c> if [ignore enabled]; otherwise, <c>false</c>.</value>
public virtual bool IgnoreEnabled { get; protected set; }
/// <summary>
/// Gets or sets the ignore rules.
/// </summary>
/// <value>The ignore rules.</value>
[StaticLocalization(LocalizationResources.Conflict_Solver.IgnoreRules)]
public virtual string IgnoreRules { get; protected set; }
/// <summary>
/// Gets or sets the ignore rules command.
/// </summary>
/// <value>The ignore rules command.</value>
public virtual ReactiveCommand<Unit, Unit> IgnoreRulesCommand { get; protected set; }
/// <summary>
/// Gets or sets the invalid.
/// </summary>
/// <value>The invalid.</value>
[StaticLocalization(LocalizationResources.Conflict_Solver.InvalidConflicts.Name)]
public virtual string Invalid { get; protected set; }
/// <summary>
/// Gets or sets the invalid conflict path.
/// </summary>
/// <value>The invalid conflict path.</value>
public virtual string InvalidConflictPath { get; protected set; }
/// <summary>
/// Gets or sets the invalid custom patch.
/// </summary>
/// <value>The invalid custom patch.</value>
[StaticLocalization(LocalizationResources.Conflict_Solver.InvalidConflicts.ContextMenu.CustomPatch)]
public virtual string InvalidCustomPatch { get; protected set; }
/// <summary>
/// Gets or sets the invalid custom patch command.
/// </summary>
/// <value>The invalid custom patch command.</value>
public virtual ReactiveCommand<Unit, Unit> InvalidCustomPatchCommand { get; protected set; }
/// <summary>
/// Gets or sets the invalid open directory.
/// </summary>
/// <value>The invalid open directory.</value>
[StaticLocalization(LocalizationResources.Conflict_Solver.InvalidConflicts.ContextMenu.OpenDirectory)]
public virtual string InvalidOpenDirectory { get; protected set; }
/// <summary>
/// Gets or sets the invalid open directory command.
/// </summary>
/// <value>The invalid open directory command.</value>
public virtual ReactiveCommand<Unit, Unit> InvalidOpenDirectoryCommand { get; protected set; }
/// <summary>
/// Gets or sets the invalid open file.
/// </summary>
/// <value>The invalid open file.</value>
[StaticLocalization(LocalizationResources.Conflict_Solver.InvalidConflicts.ContextMenu.OpenFile)]
public virtual string InvalidOpenFile { get; protected set; }
/// <summary>
/// Gets or sets the invalid open file command.
/// </summary>
/// <value>The invalid open file command.</value>
public virtual ReactiveCommand<Unit, Unit> InvalidOpenFileCommand { get; protected set; }
/// <summary>
/// Gets or sets a value indicating whether this instance is binary conflict.
/// </summary>
/// <value><c>true</c> if this instance is binary conflict; otherwise, <c>false</c>.</value>
public virtual bool IsBinaryConflict { get; protected set; }
/// <summary>
/// Gets or sets a value indicating whether this instance is binary viewer visible.
/// </summary>
/// <value><c>true</c> if this instance is binary viewer visible; otherwise, <c>false</c>.</value>
public virtual bool IsBinaryViewerVisible { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this instance is conflict solver available.
/// </summary>
/// <value><c>true</c> if this instance is conflict solver available; otherwise, <c>false</c>.</value>
public virtual bool IsConflictSolverAvailable { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this instance is merge viewer visible.
/// </summary>
/// <value><c>true</c> if this instance is merge viewer visible; otherwise, <c>false</c>.</value>
public virtual bool IsMergeViewerVisible { get; set; }
/// <summary>
/// Gets or sets the left side.
/// </summary>
/// <value>The left side.</value>
[StaticLocalization(LocalizationResources.Conflict_Solver.LeftSide)]
public virtual string LeftSide { get; protected set; }
/// <summary>
/// Gets or sets the merge viewer.
/// </summary>
/// <value>The merge viewer.</value>
public virtual MergeViewerControlViewModel MergeViewer { get; protected set; }
/// <summary>
/// Gets or sets the mod compare selector.
/// </summary>
/// <value>The mod compare selector.</value>
public virtual ModCompareSelectorControlViewModel ModCompareSelector { get; protected set; }
/// <summary>
/// Gets or sets the mod filter.
/// </summary>
/// <value>The mod filter.</value>
public virtual ConflictSolverModFilterControlViewModel ModFilter { get; protected set; }
/// <summary>
/// Gets or sets the number of conflicts caption.
/// </summary>
/// <value>The number of conflicts caption.</value>
public virtual string NumberOfConflictsCaption { get; protected set; }
/// <summary>
/// Gets or sets the index of the previous conflict.
/// </summary>
/// <value>The index of the previous conflict.</value>
public virtual int? PreviousConflictIndex { get; set; }
/// <summary>
/// Gets or sets a value indicating whether [read only].
/// </summary>
/// <value><c>true</c> if [read only]; otherwise, <c>false</c>.</value>
public virtual bool ReadOnly { get; protected set; }
/// <summary>
/// Gets or sets the reset conflicts.
/// </summary>
/// <value>The reset conflicts.</value>
public virtual ConflictSolverResetConflictsControlViewModel ResetConflicts { get; protected set; }
/// <summary>
/// Gets or sets the reset conflicts column.
/// </summary>
/// <value>The reset conflicts column.</value>
public virtual int ResetConflictsColumn { get; protected set; }
/// <summary>
/// Gets or sets the resolve.
/// </summary>
/// <value>The resolve.</value>
[StaticLocalization(LocalizationResources.Conflict_Solver.Resolve)]
public virtual string Resolve { get; protected set; }
/// <summary>
/// Gets or sets the resolve command.
/// </summary>
/// <value>The resolve command.</value>
public virtual ReactiveCommand<Unit, Unit> ResolveCommand { get; protected set; }
/// <summary>
/// Gets or sets a value indicating whether [resolve enabled].
/// </summary>
/// <value><c>true</c> if [resolve enabled]; otherwise, <c>false</c>.</value>
public virtual bool ResolveEnabled { get; protected set; }
/// <summary>
/// Gets or sets a value indicating whether [resolving conflict].
/// </summary>
/// <value><c>true</c> if [resolving conflict]; otherwise, <c>false</c>.</value>
public virtual bool ResolvingConflict { get; protected set; }
/// <summary>
/// Gets or sets the right side.
/// </summary>
/// <value>The right side.</value>
[StaticLocalization(LocalizationResources.Conflict_Solver.RightSide)]
public virtual string RightSide { get; protected set; }
/// <summary>
/// Gets or sets the selected conflict.
/// </summary>
/// <value>The selected conflict.</value>
public virtual IHierarchicalDefinitions SelectedConflict { get; set; }
/// <summary>
/// Gets or sets the selected conflict override.
/// </summary>
/// <value>The selected conflict override.</value>
public virtual int? SelectedConflictOverride { get; protected set; }
/// <summary>
/// Gets or sets the selected mod collection.
/// </summary>
/// <value>The selected mod collection.</value>
public virtual IModCollection SelectedModCollection { get; set; }
/// <summary>
/// Gets or sets the selected mods order.
/// </summary>
/// <value>The selected mods order.</value>
public virtual IList<string> SelectedModsOrder { get; set; }
/// <summary>
/// Gets or sets the selected parent conflict.
/// </summary>
/// <value>The selected parent conflict.</value>
public virtual IHierarchicalDefinitions SelectedParentConflict { get; set; }
#endregion Properties
#region Methods
/// <summary>
/// Initializes the specified read only.
/// </summary>
/// <param name="readOnly">if set to <c>true</c> [read only].</param>
public void Initialize(bool readOnly)
{
ReadOnly = readOnly;
ResetConflictsColumn = readOnly ? 0 : 1;
ResetConflicts.SetParameters(readOnly);
BinaryMergeViewer.SetParameters(readOnly);
ModCompareSelector.Reset();
IgnoreEnabled = false;
BackTriggered = false;
if (Conflicts.Conflicts.HasResetDefinitions())
{
var sbResolved = new StringBuilder();
var sbIgnored = new StringBuilder();
var allHierarchalDefinitions = Conflicts.Conflicts.GetHierarchicalDefinitions();
var modListFormat = localizationManager.GetResource(LocalizationResources.Conflict_Solver.ResetWarning.ListOfConflictsFormat);
foreach (var conflict in allHierarchalDefinitions.Where(p => p.ResetType != ResetType.None))
{
foreach (var child in conflict.Children.Where(p => p.ResetType != ResetType.None))
{
switch (child.ResetType)
{
case ResetType.Resolved:
sbResolved.AppendLine(Smart.Format(modListFormat, new { ParentDirectory = conflict.Name, child.Name }));
break;
case ResetType.Ignored:
sbIgnored.AppendLine(Smart.Format(modListFormat, new { ParentDirectory = conflict.Name, child.Name }));
break;
default:
break;
}
}
}
var msgFormat = string.Empty;
if (readOnly)
{
if (sbIgnored.Length > 0 && sbResolved.Length > 0)
{
msgFormat = localizationManager.GetResource(LocalizationResources.Conflict_Solver.ResetWarning.AnalyzeModeAll);
}
else if (sbResolved.Length > 0)
{
msgFormat = localizationManager.GetResource(LocalizationResources.Conflict_Solver.ResetWarning.AnalyzeModeResolvedOnly);
}
else
{
msgFormat = localizationManager.GetResource(LocalizationResources.Conflict_Solver.ResetWarning.AnalyzeModeIgnoredOnly);
}
}
else
{
if (sbIgnored.Length > 0 && sbResolved.Length > 0)
{
msgFormat = localizationManager.GetResource(LocalizationResources.Conflict_Solver.ResetWarning.RegularModeAll);
}
else if (sbResolved.Length > 0)
{
msgFormat = localizationManager.GetResource(LocalizationResources.Conflict_Solver.ResetWarning.RegularModeResolvedOnly);
}
else
{
msgFormat = localizationManager.GetResource(LocalizationResources.Conflict_Solver.ResetWarning.RegularModeIgnoredOnly);
}
}
var msg = Smart.Format(msgFormat, new
{
Environment.NewLine,
ListOfConflictsResolved = sbResolved.ToString(),
ListOfConflictsIgnored = sbIgnored.ToString()
});
var title = localizationManager.GetResource(LocalizationResources.Conflict_Solver.ResetWarning.Title);
Dispatcher.UIThread.SafeInvoke(() => notificationAction.ShowPromptAsync(title, title, msg, NotificationType.Warning, PromptType.OK));
}
}
/// <summary>
/// Called when [locale changed].
/// </summary>
/// <param name="newLocale">The new locale.</param>
/// <param name="oldLocale">The old locale.</param>
public override void OnLocaleChanged(string newLocale, string oldLocale)
{
FilterHierarchalConflictsAsync(Conflicts).ConfigureAwait(false);
base.OnLocaleChanged(newLocale, oldLocale);
}
/// <summary>
/// Sets the parameters.
/// </summary>
/// <param name="hierarchicalDefinition">The hierarchical definition.</param>
public virtual void SetParameters(IHierarchicalDefinitions hierarchicalDefinition)
{
InvalidConflictPath = string.Empty;
if (!IsConflictSolverAvailable && hierarchicalDefinition != null)
{
if (hierarchicalDefinition.AdditionalData is IDefinition definition)
{
ContextMenuDefinition = hierarchicalDefinition;
InvalidConflictPath = modPatchCollectionService.ResolveFullDefinitionPath(definition);
}
}
}
/// <summary>
/// Evaluates the definition validity.
/// </summary>
/// <returns>System.Threading.Tasks.Task.</returns>
protected virtual async Task EvaluateDefinitionValidity()
{
var patchDefinition = ModCompareSelector.VirtualDefinitions.FirstOrDefault(p => modPatchCollectionService.IsPatchMod(p.ModName));
var validationResult = modPatchCollectionService.Validate(patchDefinition);
if (!validationResult.IsValid)
{
var title = localizationManager.GetResource(LocalizationResources.Conflict_Solver.ResolutionSaveError.Title);
var message = localizationManager.GetResource(validationResult.ErrorLine.HasValue ? LocalizationResources.Conflict_Solver.ResolutionSaveError.MessageLine : LocalizationResources.Conflict_Solver.ResolutionSaveError.MessageNoLine);
await Dispatcher.UIThread.SafeInvokeAsync(async () => await notificationAction.ShowPromptAsync(title, title, message.FormatSmart(new { Environment.NewLine, validationResult.ErrorMessage, Line = validationResult.ErrorLine, Column = validationResult.ErrorColumn }), NotificationType.Error, PromptType.OK));
}
else
{
await Dispatcher.UIThread.SafeInvokeAsync(async () => await ResolveConflictAsync(true).ConfigureAwait(true));
}
}
/// <summary>
/// Evals the viewer visibility.
/// </summary>
protected virtual void EvalViewerVisibility()
{
IsBinaryViewerVisible = IsBinaryConflict && IsConflictSolverAvailable;
IsMergeViewerVisible = !IsBinaryConflict && IsConflictSolverAvailable;
MergeViewer.CanPerformHotKeyActions = IsMergeViewerVisible;
}
/// <summary>
/// Filter hierarchal conflicts as an asynchronous operation.
/// </summary>
/// <param name="conflictResult">The conflict result.</param>
/// <param name="selectedDefinitionOverride">The selected definition override.</param>
/// <returns>A Task representing the asynchronous operation.</returns>
protected virtual async Task FilterHierarchalConflictsAsync(IConflictResult conflictResult, IHierarchicalDefinitions selectedDefinitionOverride = null)
{
while (filteringConflicts)
{
await Task.Delay(25);
}
filteringConflicts = true;
var index = PreviousConflictIndex;
PreviousConflictIndex = null;
if (conflictResult != null && conflictResult.Conflicts != null)
{
var conflicts = conflictResult.Conflicts.GetHierarchicalDefinitions().ToAvaloniaList();
var resolved = new List<IHierarchicalDefinitions>();
if (conflictResult.ResolvedConflicts != null)
{
resolved.AddRange(conflictResult.ResolvedConflicts.GetHierarchicalDefinitions());
}
if (conflictResult.IgnoredConflicts != null)
{
resolved.AddRange(conflictResult.IgnoredConflicts.GetHierarchicalDefinitions());
}
if (conflictResult.RuleIgnoredConflicts != null)
{
resolved.AddRange(conflictResult.RuleIgnoredConflicts.GetHierarchicalDefinitions());
}
foreach (var topLevelResolvedConflicts in resolved)
{
IEnumerable<IHierarchicalDefinitions> topLevelConflicts;
if (topLevelResolvedConflicts.Name.StartsWith(LocalizationDirectory, StringComparison.OrdinalIgnoreCase))
{
topLevelConflicts = conflicts.Where(p => p.Name.StartsWith(LocalizationDirectory, StringComparison.OrdinalIgnoreCase));
}
else
{
topLevelConflicts = conflicts.Where(p => p.Name.Equals(topLevelResolvedConflicts.Name));
}
if (topLevelConflicts.Any())
{
foreach (var topLevelConflict in topLevelConflicts)
{
foreach (var childResolvedConflict in topLevelResolvedConflicts.Children)
{
var child = topLevelConflict.Children.FirstOrDefault(p => p.Key.Equals(childResolvedConflict.Key));
if (child != null)
{
topLevelConflict.Children.Remove(child);
}
}
}
}
}
conflicts.RemoveAll(conflicts.Where(p => p.Children == null || p.Children.Count == 0).ToList());
if (!invalidsChecked)
{
invalidsChecked = true;
var invalid = conflictResult.AllConflicts.GetByValueType(ValueType.Invalid);
if (invalid?.Count() > 0)
{
var invalidDef = DIResolver.Get<IHierarchicalDefinitions>();
invalidDef.Name = Invalid;
invalidDef.Key = InvalidKey;
var children = new List<IHierarchicalDefinitions>();
foreach (var item in invalid)
{
var invalidChild = DIResolver.Get<IHierarchicalDefinitions>();
invalidChild.Name = item.File;
var message = item.ErrorColumn.HasValue || item.ErrorLine.HasValue ?
localizationManager.GetResource(LocalizationResources.Conflict_Solver.InvalidConflicts.Error) :
localizationManager.GetResource(LocalizationResources.Conflict_Solver.InvalidConflicts.ErrorNoLine);
invalidChild.Key = Smart.Format(message, new
{
item.ModName,
Line = item.ErrorLine,
Column = item.ErrorColumn,
Environment.NewLine,
Message = item.ErrorMessage,
item.File
});
invalidChild.AdditionalData = item;
children.Add(invalidChild);
}
invalidDef.Children = children;
cachedInvalids = invalidDef;
conflicts.Add(invalidDef);
}
}
if (cachedInvalids != null)
{
conflicts.Add(cachedInvalids);
}
var selectedParentConflict = SelectedParentConflict;
HierarchalConflicts = conflicts;
NumberOfConflictsCaption = Smart.Format(localizationManager.GetResource(LocalizationResources.Conflict_Solver.ConflictCount), new { Count = conflicts.Where(p => p.Key != InvalidKey).SelectMany(p => p.Children).Count() });
int? previousConflictIndex = null;
if (HierarchalConflicts.Any() && selectedParentConflict == null)
{
selectedParentConflict = HierarchalConflicts.FirstOrDefault();
}
if (selectedParentConflict != null)
{
var conflictName = selectedParentConflict.Name;
selectedParentConflict = null;
var newSelected = HierarchalConflicts.FirstOrDefault(p => p.Name.Equals(conflictName));
if (newSelected != null)
{
previousConflictIndex = index;
if (selectedDefinitionOverride != null)
{
var overrideMatch = newSelected.Children.FirstOrDefault(p => p.Key.Equals(selectedDefinitionOverride.Key));
if (overrideMatch != null)
{
previousConflictIndex = newSelected.Children.ToList().IndexOf(overrideMatch);
}
}
if (previousConflictIndex.GetValueOrDefault() > (newSelected.Children.Count - 1))
{
previousConflictIndex = newSelected.Children.Count - 1;
}
selectedParentConflict = newSelected;
}
}
PreviousConflictIndex = previousConflictIndex;
SelectedParentConflict = selectedParentConflict;
}
else
{
HierarchalConflicts = null;
}
filteringConflicts = false;
}
/// <summary>
/// Called when [activated].
/// </summary>
/// <param name="disposables">The disposables.</param>
protected override void OnActivated(CompositeDisposable disposables)
{
var resolvingEnabled = this.WhenAnyValue(v => v.ResolvingConflict, v => !v);
var backTriggered = this.WhenAnyValue(v => v.BackTriggered, v => !v);
BackCommand = ReactiveCommand.CreateFromTask(async () =>
{
var id = idGenerator.GetNextId();
await TriggerOverlayAsync(id, true);
await Task.Delay(100);
BinaryMergeViewer.Reset(true);
BackTriggered = true;
Conflicts?.Dispose();
Conflicts = null;
SelectedModsOrder = null;
SelectedModCollection = null;
cachedInvalids = null;
invalidsChecked = false;
var args = new NavigationEventArgs()
{
State = NavigationState.Main
};
ReactiveUI.MessageBus.Current.SendMessage(args);
BackTriggered = false;
await TriggerOverlayAsync(id, false);
}, backTriggered).DisposeWith(disposables);
ResolveCommand = ReactiveCommand.CreateFromTask(() =>
{
return EvaluateDefinitionValidity();
}, resolvingEnabled).DisposeWith(disposables);
IgnoreCommand = ReactiveCommand.Create(() =>
{
ResolveConflictAsync(false).ConfigureAwait(true);
}, resolvingEnabled).DisposeWith(disposables);
InvalidOpenDirectoryCommand = ReactiveCommand.CreateFromTask(async () =>
{
if (!string.IsNullOrWhiteSpace(InvalidConflictPath))
{
await appAction.OpenAsync(Path.GetDirectoryName(InvalidConflictPath));
}
}).DisposeWith(disposables);
InvalidOpenFileCommand = ReactiveCommand.CreateFromTask(async () =>
{
if (!string.IsNullOrWhiteSpace(InvalidConflictPath))
{
await appAction.OpenAsync(InvalidConflictPath);
}
}).DisposeWith(disposables);
this.WhenAnyValue(p => p.Conflicts).Subscribe(s =>
{
FilterHierarchalConflictsAsync(s).ConfigureAwait(false);
IgnoreConflictsRules.CollectionName = SelectedModCollection.Name;
IgnoreConflictsRules.ConflictResult = s;
ResetConflicts.SetParameters(s, SelectedModCollection.Name);
DatabaseSearch.SetParameters(s);
CustomConflicts.SetParameters(s, SelectedModCollection.Name);
MergeViewer.InitParameters();
if (ModFilter.IsActivated)
{
ModFilter.SetConflictResult(Conflicts, SelectedModsOrder.ToList(), SelectedModCollection.Name);
}
}).DisposeWith(disposables);
this.WhenAnyValue(v => v.SelectedParentConflict).Subscribe(s =>
{
IsConflictSolverAvailable = !(s?.Key == InvalidKey);
EvalViewerVisibility();
}).DisposeWith(disposables);
this.WhenAnyValue(v => v.SelectedConflict).Subscribe(s =>
{
if (Conflicts?.Conflicts != null && !string.IsNullOrWhiteSpace(s?.Key) && IsConflictSolverAvailable)
{
PreviousConflictIndex = SelectedParentConflict.Children.ToList().IndexOf(s);
var conflicts = Conflicts.Conflicts.GetByTypeAndId(s.Key).ToObservableCollection();
ModCompareSelector.SelectedModsOrder = SelectedModsOrder;
ModCompareSelector.CollectionName = SelectedModCollection.Name;
ModCompareSelector.IsBinaryConflict = IsBinaryConflict = conflicts?.FirstOrDefault()?.ValueType == ValueType.Binary;
ModCompareSelector.Definitions = conflicts;
var left = ModCompareSelector.DefinitionSelection?.LeftSelectedDefinition;
var right = ModCompareSelector.DefinitionSelection?.RightSelectedDefinition;
MergeViewer.SetSidePatchMod(left, right);
MergeViewer.SetText(string.Empty, string.Empty, true, lockScroll: true);
MergeViewer.ExitEditMode();
EvalViewerVisibility();
IgnoreEnabled = true;
}
else
{
if (HierarchalConflicts == null || !HierarchalConflicts.Any())
{
ModCompareSelector.Reset();
BinaryMergeViewer.Reset(false);
MergeViewer.SetText(string.Empty, string.Empty, true, lockScroll: true);
}
PreviousConflictIndex = null;
IgnoreEnabled = false;
}
}).DisposeWith(disposables);
this.WhenAnyValue(v => v.ModCompareSelector.IsActivated).Where(p => p).Subscribe(s =>
{
this.WhenAnyValue(v => v.ModCompareSelector.DefinitionSelection).Subscribe(s =>
{
if (s != null && IsConflictSolverAvailable)
{
MergeViewer.EditingYaml = s.LeftSelectedDefinition.Type.StartsWith(Shared.Constants.LocalizationDirectory);
MergeViewer.EditingLua = s.LeftSelectedDefinition.File.EndsWith(Parser.Common.Constants.LuaExtension, StringComparison.OrdinalIgnoreCase);
MergeViewer.SetSidePatchMod(s.LeftSelectedDefinition, s.RightSelectedDefinition);
MergeViewer.SetText(s.LeftSelectedDefinition.Code, s.RightSelectedDefinition.Code, lockScroll: true);
MergeViewer.ExitEditMode();
if (!IsBinaryConflict)
{
BinaryMergeViewer.EnableSelection = ResolveEnabled = s.LeftSelectedDefinition != null &&
s.RightSelectedDefinition != null &&
s.LeftSelectedDefinition != s.RightSelectedDefinition &&
(modPatchCollectionService.IsPatchMod(s.LeftSelectedDefinition.ModName) || modPatchCollectionService.IsPatchMod(s.RightSelectedDefinition.ModName));
}
else
{
BinaryMergeViewer.Reset(false);
ResolveEnabled = false;
BinaryMergeViewer.EnableSelection = s.LeftSelectedDefinition != null &&
s.RightSelectedDefinition != null &&
s.LeftSelectedDefinition != s.RightSelectedDefinition;
BinaryMergeViewer.SetLeft(s.LeftSelectedDefinition);
BinaryMergeViewer.SetRight(s.RightSelectedDefinition);
}
}
else
{
BinaryMergeViewer.Reset(false);
ResolveEnabled = false;
}
}).DisposeWith(disposables);
}).DisposeWith(disposables);
this.WhenAnyValue(v => v.BinaryMergeViewer.IsActivated).Where(p => p).Subscribe(s =>
{
Observable.Merge(BinaryMergeViewer.TakeLeftCommand.Select(s => true), BinaryMergeViewer.TakeRightCommand.Select(s => false)).Subscribe(s =>
{
takeLeftBinary = s;
ResolveEnabled = true;
}).DisposeWith(disposables);
}).DisposeWith(disposables);
this.WhenAnyValue(p => p.MergeViewer.LeftSide).Where(p => !string.IsNullOrWhiteSpace(p)).Subscribe(s =>
{
var virtualDefinitions = ModCompareSelector.VirtualDefinitions;
if (MergeViewer.LeftSidePatchMod && virtualDefinitions != null)
{
var patchDefinition = virtualDefinitions.FirstOrDefault(p => modPatchCollectionService.IsPatchMod(p.ModName));
SyncCode(patchDefinition);
}
}).DisposeWith(disposables);
this.WhenAnyValue(p => p.MergeViewer.RightSide).Where(p => !string.IsNullOrWhiteSpace(p)).Subscribe(s =>
{
var virtualDefinitions = ModCompareSelector.VirtualDefinitions;
if (MergeViewer.RightSidePatchMod && virtualDefinitions != null)
{
var patchDefinition = virtualDefinitions.FirstOrDefault(p => modPatchCollectionService.IsPatchMod(p.ModName));
SyncCode(patchDefinition);
}
}).DisposeWith(disposables);
this.WhenAnyValue(v => v.IgnoreConflictsRules.IsActivated).Where(p => p).Subscribe(s =>
{
Observable.Merge(IgnoreConflictsRules.SaveCommand, IgnoreConflictsRules.CancelCommand).Subscribe(result =>
{
switch (result.State)
{
case Implementation.CommandState.Success:
EditingIgnoreConflictsRules = false;
FilterHierarchalConflictsAsync(Conflicts, SelectedConflict).ConfigureAwait(false);
break;
case Implementation.CommandState.NotExecuted:
EditingIgnoreConflictsRules = false;
break;
default:
break;
}
}).DisposeWith(disposables);
}).DisposeWith(disposables);
IgnoreRulesCommand = ReactiveCommand.Create(() =>
{
EditingIgnoreConflictsRules = true;
}).DisposeWith(disposables);
InvalidCustomPatchCommand = ReactiveCommand.Create(() =>
{
if (ContextMenuDefinition.AdditionalData is IDefinition definition)
{
CustomConflicts.SetContent(definition.File, definition.Code);
}
}).DisposeWith(disposables);
this.WhenAnyValue(p => p.ModFilter.IsActivated).Where(p => p).Subscribe(s =>
{
ModFilter.SetConflictResult(Conflicts, SelectedModsOrder.ToList(), SelectedModCollection.Name);
this.WhenAnyValue(p => p.ModFilter.HasSavedState).Where(p => p).Subscribe(s =>
{
FilterHierarchalConflictsAsync(Conflicts, SelectedConflict).ConfigureAwait(false);
}).DisposeWith(disposables);
}).DisposeWith(disposables);
this.WhenAnyValue(p => p.ResetConflicts.IsActivated).Where(p => p).Subscribe(s =>
{
ResetConflicts.ResetCommand.Subscribe(s =>
{
if (s.State == Implementation.CommandState.Success)
{
FilterHierarchalConflictsAsync(Conflicts, SelectedConflict).ConfigureAwait(false);
}
}).DisposeWith(disposables);
}).DisposeWith(disposables);
this.WhenAnyValue(p => p.CustomConflicts.Saved).Where(p => p).Subscribe(s =>
{
ResetConflicts.Refresh();
}).DisposeWith(disposables);
var previousEditTextState = false;
this.WhenAnyValue(v => v.EditingIgnoreConflictsRules).Subscribe(s =>
{
if (s != previousEditTextState)
{
previousEditTextState = s;
}
}).DisposeWith(disposables);
hotkeyPressedHandler.Subscribe(m =>
{
async Task performModSelectionAction()
{
if (!filteringConflicts && (SelectedParentConflict?.Children.Any()).GetValueOrDefault())
{
int? newSelectedConflict = null;
var col = SelectedParentConflict != null ? SelectedParentConflict.Children.ToList() : new List<IHierarchicalDefinitions>();
switch (m.Hotkey)
{
case Enums.HotKeys.Shift_Up:
if (SelectedConflict == null)
{
newSelectedConflict = col.Count - 1;
}
else
{
var index = col.IndexOf(SelectedConflict);
index--;
if (index < 0)
{
index = 0;
}
newSelectedConflict = index;
}
break;
case Enums.HotKeys.Shift_Down:
if (SelectedConflict == null)
{
newSelectedConflict = 0;
}
else
{
var index = col.IndexOf(SelectedConflict);
index++;
if (index > col.Count - 1)
{
index = col.Count - 1;
}
newSelectedConflict = index;
}
break;
default:
break;
}
if (newSelectedConflict != null)
{
await Dispatcher.UIThread.SafeInvokeAsync(() =>
{
SelectedConflictOverride = newSelectedConflict;
});
}
}
}
async Task performModParentSelectionAction()
{
if (!filteringConflicts && (HierarchalConflicts?.Any()).GetValueOrDefault())
{
IHierarchicalDefinitions parent = null;
var col = HierarchalConflicts.ToList();
switch (m.Hotkey)
{
case Enums.HotKeys.Ctrl_Shift_P:
if (SelectedParentConflict == null)
{
parent = col.LastOrDefault();
}
else
{
var index = col.IndexOf(SelectedParentConflict);
index--;
if (index < 0)
{
index = 0;
}
parent = col[index];
}
break;
case Enums.HotKeys.Ctrl_Shift_N:
if (SelectedParentConflict == null)
{
parent = col.FirstOrDefault();
}
else
{
var index = col.IndexOf(SelectedParentConflict);
index++;
if (index > col.Count - 1)
{
index = col.Count - 1;
}
parent = col[index];
}
break;
default:
break;
}
if (parent != null)
{
await Dispatcher.UIThread.SafeInvokeAsync(() =>
{
SelectedParentConflict = parent;
});
}
}
}
if (m.Hotkey == Enums.HotKeys.Shift_Down || m.Hotkey == Enums.HotKeys.Shift_Up)
{
performModSelectionAction().ConfigureAwait(false);
}
else if (m.Hotkey == Enums.HotKeys.Ctrl_R)
{
if (ResolveEnabled && !ResolvingConflict)
{
EvaluateDefinitionValidity().ConfigureAwait(false);
}
}
else if (m.Hotkey == Enums.HotKeys.Ctrl_I)
{
if (IgnoreEnabled && !ResolvingConflict)
{
Dispatcher.UIThread.SafeInvoke(() => ResolveConflictAsync(false).ConfigureAwait(true));
}
}
else
{
performModParentSelectionAction().ConfigureAwait(false);
}
}).DisposeWith(disposables);
base.OnActivated(disposables);
}
/// <summary>
/// resolve conflict as an asynchronous operation.
/// </summary>
/// <param name="resolve">if set to <c>true</c> [resolve].</param>
/// <returns>A Task representing the asynchronous operation.</returns>
protected virtual async Task ResolveConflictAsync(bool resolve)
{
if (ResolvingConflict)
{
return;
}
ResolvingConflict = true;
if (ModCompareSelector.VirtualDefinitions != null && ModCompareSelector.VirtualDefinitions.Any())
{
IHierarchicalDefinitions conflictParent = null;
int? conflictParentIdx = null;
int parentIdx = HierarchalConflicts.ToList().IndexOf(SelectedParentConflict);
foreach (var item in HierarchalConflicts)
{
if (item.Children.Contains(SelectedConflict))
{
conflictParent = item;
var conflictParentChildren = new List<IHierarchicalDefinitions>(item.Children);
conflictParentIdx = conflictParentChildren.IndexOf(SelectedConflict);
break;
}
}
var id = idGenerator.GetNextId();
await TriggerOverlayAsync(id, true, localizationManager.GetResource(LocalizationResources.Conflict_Solver.OverlayResolve));
IDefinition patchDefinition = null;
if (!IsBinaryConflict)
{
patchDefinition = ModCompareSelector.VirtualDefinitions.FirstOrDefault(p => modPatchCollectionService.IsPatchMod(p.ModName));
}
else
{
if (resolve)
{
patchDefinition = takeLeftBinary ? ModCompareSelector.DefinitionSelection.LeftSelectedDefinition : ModCompareSelector.DefinitionSelection.RightSelectedDefinition;
}
else
{
patchDefinition = ModCompareSelector.Definitions.FirstOrDefault();
}
}
if (patchDefinition != null)
{
var generatedFileNames = patchDefinition.GeneratedFileNames;
foreach (var fileNames in ModCompareSelector.Definitions.Select(p => p.GeneratedFileNames))
{
foreach (var item in fileNames)
{
generatedFileNames.Add(item);
}
}
patchDefinition.GeneratedFileNames = generatedFileNames;
SyncCode(patchDefinition);
try
{
if (await Task.Run(async () => resolve ?
await modPatchCollectionService.ApplyModPatchAsync(Conflicts, patchDefinition, SelectedModCollection.Name) :
await modPatchCollectionService.IgnoreModPatchAsync(Conflicts, patchDefinition, SelectedModCollection.Name)))
{
await FilterHierarchalConflictsAsync(Conflicts);
IHierarchicalDefinitions selectedConflict = null;
if (conflictParentIdx.HasValue && HierarchalConflicts.Any())
{
foreach (var item in HierarchalConflicts)
{
if (item.Name.Equals(conflictParent.Name))
{
if (conflictParentIdx.Value > (item.Children.Count - 1))
{
conflictParentIdx = item.Children.Count - 1;
}
else if (conflictParentIdx.Value < 0)
{
conflictParentIdx = 0;
}
selectedConflict = item.Children.Select(p => p).ToList()[conflictParentIdx.GetValueOrDefault()];
break;
}
}
}
SelectedConflict = selectedConflict;
ResetConflicts.Refresh();
}
}
catch (Exception ex)
{
var title = localizationManager.GetResource(LocalizationResources.SavingError.Title);
var message = localizationManager.GetResource(LocalizationResources.SavingError.Message);
logger.Error(ex);
notificationAction.ShowNotification(title, message, NotificationType.Error, 30);
}
}
if (SelectedConflict == null)
{
if (parentIdx > (HierarchalConflicts.Count - 1))
{
parentIdx = HierarchalConflicts.Count - 1;
}
else if (parentIdx < 0)
{
parentIdx = 0;
}
if (HierarchalConflicts.Any())
{
// Force a refresh of the UI
SelectedParentConflict = null;
SelectedParentConflict = HierarchalConflicts.ElementAt(parentIdx);
}
}
await TriggerOverlayAsync(id, false);
}
ResolvingConflict = false;
}
/// <summary>
/// Synchronizes the code.
/// </summary>
/// <param name="definition">The definition.</param>
protected virtual void SyncCode(IDefinition definition)
{
if (definition != null)
{
if (MergeViewer.LeftSidePatchMod)
{
definition.Code = MergeViewer.LeftSide;
}
else
{
definition.Code = MergeViewer.RightSide;
}
}
}
#endregion Methods
}
}
| 45.701575 | 320 | 0.533106 | [
"MIT"
] | Sciencmine/IronyModManager | src/IronyModManager/ViewModels/MainConflictSolverViewModel.cs | 58,043 | C# |
/*
* Copyright 2015-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using Amazon.Runtime.Internal.Transform;
using AWSSDK_DotNet35.UnitTests;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
namespace AWSSDK.UnitTests
{
[TestClass]
public class SimpleTypeUnmarshallerTests
{
private static readonly string JsonWithValues = "{'Priority': 1, 'ReservoirQuotaTTL': 1533081600, 'StartTimeISO8601': '2018-08-01T00:00:00.0000000Z', 'StartTimeEpoch': 1533081600, 'StartTimeRFC822': 'Wed, 01 Aug 2018 00:00:00 GMT'}".Replace("'", "\"");
private static readonly string JsonWithNullValues = "{'Priority': null, 'ReservoirQuotaTTL': null, 'StartTimeISO8601': null, 'StartTimeEpoch': null, 'StartTimeRFC822': null}".Replace("'", "\"");
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Runtime")]
public void TestJsonUnmarshalling()
{
var model = UnmarshallModel(JsonWithValues);
var nullModel = UnmarshallModel(JsonWithNullValues);
Assert.AreEqual(1, model.Priority);
Assert.AreEqual(null, nullModel.Priority);
var expected = new DateTime(2018, 8, 1, 0, 0, 0, DateTimeKind.Utc);
Assert.AreEqual(expected, model.ReservoirQuotaTTL.Value.ToUniversalTime());
Assert.AreEqual(DateTimeKind.Utc, model.ReservoirQuotaTTL.Value.Kind);
Assert.AreEqual(null, nullModel.ReservoirQuotaTTL);
Assert.AreEqual(expected, model.StartTimeISO8601.ToUniversalTime());
Assert.AreEqual(DateTimeKind.Local, model.StartTimeISO8601.Kind);
Assert.AreEqual(DateTime.MinValue, nullModel.StartTimeISO8601);
Assert.AreEqual(DateTimeKind.Unspecified, nullModel.StartTimeISO8601.Kind);
Assert.AreEqual(expected, model.StartTimeEpoch.ToUniversalTime());
Assert.AreEqual(DateTimeKind.Utc, model.StartTimeEpoch.Kind);
Assert.AreEqual(DateTime.MinValue, nullModel.StartTimeEpoch);
Assert.AreEqual(DateTimeKind.Unspecified, nullModel.StartTimeEpoch.Kind);
Assert.AreEqual(expected, model.StartTimeRFC822.ToUniversalTime());
Assert.AreEqual(DateTimeKind.Local, model.StartTimeRFC822.Kind);
Assert.AreEqual(DateTime.MinValue, nullModel.StartTimeRFC822);
Assert.AreEqual(DateTimeKind.Unspecified, nullModel.StartTimeRFC822.Kind);
}
private Model UnmarshallModel(string json)
{
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(json), true, null);
context.Read();
int targetDepth = context.CurrentDepth;
var model = new Model();
bool isSetPriority = false, isSetReservoirQuotaTTL = false, isSetStartTimeISO8601 = false,
isSetStartTimeEpoch = false, isSetStartTimeRFC822 = false;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("Priority", targetDepth))
{
var unmarshaller = NullableIntUnmarshaller.Instance;
model.Priority = unmarshaller.Unmarshall(context);
isSetPriority = true;
}
if (context.TestExpression("ReservoirQuotaTTL", targetDepth))
{
var unmarshaller = NullableDateTimeUnmarshaller.Instance;
model.ReservoirQuotaTTL = unmarshaller.Unmarshall(context);
isSetReservoirQuotaTTL = true;
}
if (context.TestExpression("StartTimeISO8601", targetDepth))
{
var unmarshaller = DateTimeUnmarshaller.Instance;
model.StartTimeISO8601 = unmarshaller.Unmarshall(context);
isSetStartTimeISO8601 = true;
}
if (context.TestExpression("StartTimeEpoch", targetDepth))
{
var unmarshaller = DateTimeUnmarshaller.Instance;
model.StartTimeEpoch = unmarshaller.Unmarshall(context);
isSetStartTimeEpoch = true;
}
if (context.TestExpression("StartTimeRFC822", targetDepth))
{
var unmarshaller = DateTimeUnmarshaller.Instance;
model.StartTimeRFC822 = unmarshaller.Unmarshall(context);
isSetStartTimeRFC822 = true;
}
}
if (!(isSetPriority && isSetReservoirQuotaTTL && isSetStartTimeISO8601 && isSetStartTimeEpoch && isSetStartTimeRFC822))
{
throw new Exception($"Could not parse all properties in JSON '{json}'");
}
return model;
}
class Model
{
public int? Priority { get; set; }
public DateTime? ReservoirQuotaTTL { get; set; }
public DateTime StartTimeISO8601 { get; set; }
public DateTime StartTimeEpoch { get; set; }
public DateTime StartTimeRFC822 { get; set; }
}
}
}
| 47.932203 | 260 | 0.62995 | [
"Apache-2.0"
] | Bio2hazard/aws-sdk-net | sdk/test/UnitTests/Custom/Marshalling/SimpleTypeUnmarshallerTests.cs | 5,658 | C# |
// ***********************************************************************
// Assembly : MPT.CSI.OOAPI
// Author : Mark Thomas
// Created : 11-22-2018
//
// Last Modified By : Mark Thomas
// Last Modified On : 12-11-2018
// ***********************************************************************
// <copyright file="Diaphragm.cs" company="">
// Copyright © 2018
// </copyright>
// <summary></summary>
// ***********************************************************************
using System.Collections.Generic;
using MPT.CSI.Serialize.Models.Components.StructureLayout;
using MPT.CSI.Serialize.Models.Support;
namespace MPT.CSI.Serialize.Models.Components.Definitions.Abstractions
{
/// <summary>
/// Class Diaphragm.
/// </summary>
public class Diaphragm : IUniqueName
{
// TODO: Include all relevant objects
// TODO: Implement eDiaphragmOption
// TODO: Consider constraints in general
#region Fields & Properties
/// <summary>
/// The nodes associated with the diaphragm.
/// </summary>
/// <value>The nodes.</value>
public List<Point> Nodes { get; protected set; }
/// <summary>
/// The areas associated with the diaphragm.
/// </summary>
/// <value>The areas.</value>
public List<Area> Areas { get; protected set; }
/// <summary>
/// The name of an existing diaphragm.
/// </summary>
/// <value>The name.</value>
public string Name { get; protected set; }
/// <summary>
/// True: The diaphragm is semi-rigid.
/// False: The diaphragm is rigid.
/// </summary>
/// <value><c>true</c> if this instance is semi rigid; otherwise, <c>false</c>.</value>
public bool IsSemiRigid { get; protected set; }
#endregion
#region Initialization
/// <summary>
/// Factories the specified application.
/// </summary>
/// <param name="uniqueName">Name of the unique.</param>
/// <returns>Diaphragm.</returns>
internal static Diaphragm Factory(string uniqueName)
{
Diaphragm diaphragm = new Diaphragm(uniqueName);
return diaphragm;
}
/// <summary>
/// Initializes a new instance of the <see cref="Diaphragm" /> class.
/// </summary>
/// <param name="name">The name.</param>
protected Diaphragm(string name)
{
Name = name;
}
#endregion
#region Get/Add/Remove
/// <summary>
/// Retrieves the diaphragm for a specified object.
/// </summary>
/// <param name="area">The area.</param>
/// <returns>Diaphragm.</returns>
public Diaphragm GetDiaphragm(Area area)
{
string diaphragmName = ""; //_areaObject.GetDiaphragm(area.Name);
return string.IsNullOrEmpty(diaphragmName) ? null : Factory(diaphragmName);
}
/// <summary>
/// Retrieves the diaphragm for a specified object.
/// </summary>
/// <param name="node">The node.</param>
/// <returns>Diaphragm.</returns>
public Diaphragm GetDiaphragm(Point node)
{
string diaphragmName = ""; //_pointObject.GetDiaphragm(node.Name, out var diaphragmOption, out var diaphragmName);
return string.IsNullOrEmpty(diaphragmName) ? null : Factory(diaphragmName);
}
/// <summary>
/// Adds to diaphragm.
/// </summary>
/// <param name="area">The area.</param>
public void AddToDiaphragm(Area area)
{
if (Areas.Contains(area)) return;
Areas.Add(area);
}
/// <summary>
/// Removes from diaphragm.
/// </summary>
/// <param name="area">The area.</param>
public void RemoveFromDiaphragm(Area area)
{
if (!Areas.Contains(area)) return;
Areas.Remove(area);
}
/// <summary>
/// Adds to diaphragm.
/// </summary>
/// <param name="node">The node.</param>
public void AddToDiaphragm(Point node)
{
if (Nodes.Contains(node)) return;
Nodes.Add(node);
}
/// <summary>
/// Adds to diaphragm of bounding area.
/// </summary>
/// <param name="node">The node.</param>
public void AddToDiaphragmOfBoundingArea(Point node)
{
if (Nodes.Contains(node)) return;
// TODO: Finish - determine how to implement eDiaphragmOption 'inheriting from area object'
//Points.Add(node);
}
/// <summary>
/// Removes from diaphragm.
/// </summary>
/// <param name="node">The node.</param>
public void RemoveFromDiaphragm(Point node)
{
if (!Nodes.Contains(node)) return;
Nodes.Remove(node);
}
#endregion
}
} | 32.152866 | 126 | 0.523574 | [
"MIT"
] | MarkPThomas/MPT.Net | MPT/CSI/API/MPT.CSI.Serialize/Models/Components/Definitions/Abstractions/Diaphragm.cs | 5,051 | C# |
namespace Apim.DevOps.Toolkit.Core.ArmTemplates
{
public class ArmTemplateParameterMetadata
{
public string Description { get; set; }
}
} | 20.428571 | 48 | 0.769231 | [
"MIT"
] | andrewdmoreno/dotnet-apim | src/apimtemplate/Core/ArmTemplates/ArmTemplateParameterMetadata.cs | 145 | C# |
using Chloe.Data;
using Chloe.DbExpressions;
using Chloe.Descriptors;
using Chloe.Exceptions;
using System.Data;
namespace Chloe.SqlServer
{
public partial class MsSqlContext : DbContext
{
static Action<TEntity, IDataReader> GetMapper<TEntity>(PrimitivePropertyDescriptor propertyDescriptor, int ordinal)
{
var dbValueReader = DataReaderConstant.GetDbValueReader(propertyDescriptor.PropertyType);
Action<TEntity, IDataReader> mapper = (TEntity entity, IDataReader reader) =>
{
object value = dbValueReader.GetValue(reader, ordinal);
if (value == null || value == DBNull.Value)
throw new ChloeException($"Unable to get the {propertyDescriptor.Property.Name} value from data reader.");
propertyDescriptor.SetValue(entity, value);
};
return mapper;
}
static string AppendInsertRangeSqlTemplate(DbTable table, List<PrimitivePropertyDescriptor> mappingPropertyDescriptors)
{
StringBuilder sqlBuilder = new StringBuilder();
sqlBuilder.Append("INSERT INTO ");
sqlBuilder.Append(AppendTableName(table));
sqlBuilder.Append("(");
for (int i = 0; i < mappingPropertyDescriptors.Count; i++)
{
PrimitivePropertyDescriptor mappingPropertyDescriptor = mappingPropertyDescriptors[i];
if (i > 0)
sqlBuilder.Append(",");
sqlBuilder.Append(Utils.QuoteName(mappingPropertyDescriptor.Column.Name));
}
sqlBuilder.Append(") VALUES");
string sqlTemplate = sqlBuilder.ToString();
return sqlTemplate;
}
static string AppendTableName(DbTable table)
{
if (string.IsNullOrEmpty(table.Schema))
return Utils.QuoteName(table.Name);
return string.Format("{0}.{1}", Utils.QuoteName(table.Schema), Utils.QuoteName(table.Name));
}
}
}
| 35.964912 | 127 | 0.621951 | [
"MIT"
] | softworm/Chloe | src/Chloe.SqlServer/MsSqlContext_Helper.cs | 2,052 | C# |
namespace CarRentalSystem.Domain.Specifications.CarAds
{
using System;
using System.Linq.Expressions;
using Models.CarAds;
public class CarAdByCategorySpecification : Specification<CarAd>
{
private readonly int? category;
public CarAdByCategorySpecification(int? category)
=> this.category = category;
protected override bool Include => this.category != null;
public override Expression<Func<CarAd, bool>> ToExpression()
=> carAd => carAd.Category.Id == this.category;
}
} | 29.315789 | 68 | 0.67684 | [
"MIT"
] | kalintsenkov/CarRentalSystem | src/Domain/Specifications/CarAds/CarAdByCategorySpecification.cs | 559 | C# |
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
namespace AttSample.Scripts {
public class SampleSceneController : MonoBehaviour {
public Text attStatus;
public Text idfa;
private void Start()
{
RefreshATTStatus();
}
public void ClickRequest()
{
StartCoroutine(RequestATT());
}
public void RefreshATTStatus()
{
Debug.Log("ATT:" + AttPlugin.GetTrackingAuthorizationStatus());
attStatus.text = "ATT: " + AttPlugin.GetTrackingAuthorizationStatus();
idfa.text = "idfa\n" + UnityEngine.iOS.Device.advertisingIdentifier;
}
private IEnumerator RequestATT()
{
#if UNITY_EDITOR || UNITY_IOS
// iOSのATT対応
if (AttPlugin.IsNotDetermined()) {
// TODO ATTダイアログの前に独自ダイアログを表示したい場合は、ここに書く
// ATTダイアログのポップアップ
yield return AttPlugin.RequestTrackingAuthorization();
} else
yield return AttPlugin.RequestTrackingAuthorization();
#endif
RefreshATTStatus();
// TODO ATTダイアログの表示が終わったら、広告SDKをイニシャライズ
}
}
}
| 25.75 | 79 | 0.630185 | [
"MIT"
] | bigstupidx/ios-att-sample | Assets/AttSample/Scripts/SampleSceneController.cs | 1,273 | C# |
using System;
namespace Lit.Db
{
/// <summary>
/// Foreign key property.
/// </summary>
public class DbForeignKey<TR, TK> : IDbForeignKeyRef<TR>
where TR : class, new()
{
/// <summary>
/// Data access reference.
/// </summary>
public IDbDataAccess Db { get; set; }
/// <summary>
/// Key value.
/// </summary>
public TK Key { get => key; set => SetKey(value); }
private TK key;
/// <summary>
/// Key value as object
/// </summary>
object IDbForeignKeyRef.KeyAsObject { get => Key; set { Key = value != null ? (TK)value : default; } }
/// <summary>
/// Primary record.
/// </summary>
public TR Record => GetRecord();
private WeakReference<TR> weakReference;
#region Constructor
public DbForeignKey()
{
}
#endregion
/// <summary>
/// Key update.
/// </summary>
private void SetKey(TK value)
{
if (key == null && value != null || key != null && !key.Equals(value))
{
key = value;
weakReference = null;
}
}
/// <summary>
/// Tries to load the record.
/// </summary>
private TR GetRecord()
{
TR record = null;
if (!weakReference?.TryGetTarget(out record) ?? true)
{
var db = Db;
if (db != null)
{
record = db.Get<TR, TK>(key);
if (weakReference == null)
{
weakReference = new WeakReference<TR>(record);
}
else
{
weakReference.SetTarget(record);
}
}
}
return record;
}
/// <summary>
/// ToString gets the key value.
/// </summary>
public override string ToString()
{
return Key.ToString();
}
}
}
| 23.944444 | 110 | 0.417169 | [
"MIT"
] | lisandropodesta/lit.net | Lit.Db/Model/DbForeignKey.cs | 2,157 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Viewer.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}
| 35.333333 | 151 | 0.580189 | [
"MIT"
] | nifanfa/BitFont | Viewer/Properties/Settings.Designer.cs | 1,062 | C# |
// Copyright (c) DotSpatial Team. All rights reserved.
// Licensed under the MIT license. See License.txt file in the project root for full license information.
using System;
using System.Drawing;
namespace DotSpatial.Symbology
{
/// <summary>
/// Event args of a SnapShot event.
/// </summary>
public class SnapShotEventArgs : EventArgs
{
#region Private Variables
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="SnapShotEventArgs"/> class.
/// </summary>
/// <param name="inPicture">The bitmap of the event.</param>
public SnapShotEventArgs(Bitmap inPicture)
{
Picture = inPicture;
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the picture that was taken by the snapshot.
/// </summary>
public Bitmap Picture { get; protected set; }
#endregion
}
} | 25.825 | 106 | 0.581801 | [
"MIT"
] | AlexanderSemenyak/DotSpatial | Source/DotSpatial.Symbology/SnapShotEventArgs.cs | 1,033 | C# |
// *** 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.Oci.Marketplace.Outputs
{
[OutputType]
public sealed class GetAcceptedAgreementsAcceptedAgreementResult
{
/// <summary>
/// The unique identifier for the terms of use agreement itself.
/// </summary>
public readonly string AgreementId;
/// <summary>
/// The unique identifier for the compartment.
/// </summary>
public readonly string CompartmentId;
/// <summary>
/// The defined tags associated with this resource, if any. Each key is predefined and scoped to namespaces. For more information, see [Resource Tags](https://docs.cloud.oracle.com/iaas/Content/General/Concepts/resourcetags.htm). Example: `{"Operations.CostCenter": "42"}`
/// </summary>
public readonly ImmutableDictionary<string, object> DefinedTags;
/// <summary>
/// The display name of the resource.
/// </summary>
public readonly string DisplayName;
/// <summary>
/// The freeform tags associated with this resource, if any. Each tag is a simple key-value pair with no predefined name, type, or namespace. For more information, see [Resource Tags](https://docs.cloud.oracle.com/iaas/Content/General/Concepts/resourcetags.htm). Example: `{"Department": "Finance"}`
/// </summary>
public readonly ImmutableDictionary<string, object> FreeformTags;
/// <summary>
/// The unique identifier for the acceptance of the agreement within a specific compartment.
/// </summary>
public readonly string Id;
/// <summary>
/// The unique identifier for the listing.
/// </summary>
public readonly string ListingId;
/// <summary>
/// The version of the package. Package versions are unique within a listing.
/// </summary>
public readonly string PackageVersion;
public readonly string Signature;
/// <summary>
/// The time the agreement was accepted.
/// </summary>
public readonly string TimeAccepted;
[OutputConstructor]
private GetAcceptedAgreementsAcceptedAgreementResult(
string agreementId,
string compartmentId,
ImmutableDictionary<string, object> definedTags,
string displayName,
ImmutableDictionary<string, object> freeformTags,
string id,
string listingId,
string packageVersion,
string signature,
string timeAccepted)
{
AgreementId = agreementId;
CompartmentId = compartmentId;
DefinedTags = definedTags;
DisplayName = displayName;
FreeformTags = freeformTags;
Id = id;
ListingId = listingId;
PackageVersion = packageVersion;
Signature = signature;
TimeAccepted = timeAccepted;
}
}
}
| 36.808989 | 307 | 0.630342 | [
"ECL-2.0",
"Apache-2.0"
] | EladGabay/pulumi-oci | sdk/dotnet/Marketplace/Outputs/GetAcceptedAgreementsAcceptedAgreementResult.cs | 3,276 | C# |
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using eCommerce.cs.Data;
namespace eCommerce.cs.Data.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
partial class ApplicationDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "2.1.4-rtm-31024")
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("eCommerce.cs.Data.Entities.Order", b =>
{
b.Property<int>("OrderID")
.ValueGeneratedOnAdd()
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<decimal>("Cost");
b.Property<DateTime>("CreatedAt");
b.Property<string>("CustomerEmail");
b.Property<string>("CustomerName");
b.Property<string>("CustomerPhoneNumber");
b.Property<bool>("IsConfirmed");
b.HasKey("OrderID");
b.ToTable("Orders");
});
modelBuilder.Entity("eCommerce.cs.Data.Entities.OrderDetail", b =>
{
b.Property<int>("OrderDetailID")
.ValueGeneratedOnAdd()
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<int>("OrderID");
b.Property<int>("ProductID");
b.HasKey("OrderDetailID");
b.HasIndex("OrderID");
b.HasIndex("ProductID");
b.ToTable("OrderDetails");
});
modelBuilder.Entity("eCommerce.cs.Data.Entities.Product", b =>
{
b.Property<int>("ProductID")
.ValueGeneratedOnAdd()
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Image");
b.Property<bool>("IsAvailable");
b.Property<decimal>("Price");
b.Property<string>("ProductName")
.IsRequired();
b.Property<int>("ProductTypeID");
b.Property<int>("SpecialTagID");
b.HasKey("ProductID");
b.HasIndex("ProductTypeID");
b.HasIndex("SpecialTagID");
b.ToTable("Products");
});
modelBuilder.Entity("eCommerce.cs.Data.Entities.ProductType", b =>
{
b.Property<int>("ProductTypeID")
.ValueGeneratedOnAdd()
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("ProductTypeName")
.IsRequired();
b.HasKey("ProductTypeID");
b.ToTable("ProductTypes");
});
modelBuilder.Entity("eCommerce.cs.Data.Entities.SpecialTag", b =>
{
b.Property<int>("TagID")
.ValueGeneratedOnAdd()
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("TagName")
.IsRequired();
b.HasKey("TagID");
b.ToTable("SpecialTags");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b =>
{
b.Property<string>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Name")
.HasMaxLength(256);
b.Property<string>("NormalizedName")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("NormalizedName")
.IsUnique()
.HasName("RoleNameIndex")
.HasFilter("[NormalizedName] IS NOT NULL");
b.ToTable("AspNetRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("RoleId")
.IsRequired();
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUser", b =>
{
b.Property<string>("Id")
.ValueGeneratedOnAdd();
b.Property<int>("AccessFailedCount");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Email")
.HasMaxLength(256);
b.Property<bool>("EmailConfirmed");
b.Property<bool>("LockoutEnabled");
b.Property<DateTimeOffset?>("LockoutEnd");
b.Property<string>("NormalizedEmail")
.HasMaxLength(256);
b.Property<string>("NormalizedUserName")
.HasMaxLength(256);
b.Property<string>("PasswordHash");
b.Property<string>("PhoneNumber");
b.Property<bool>("PhoneNumberConfirmed");
b.Property<string>("SecurityStamp");
b.Property<bool>("TwoFactorEnabled");
b.Property<string>("UserName")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasName("UserNameIndex")
.HasFilter("[NormalizedUserName] IS NOT NULL");
b.ToTable("AspNetUsers");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider")
.HasMaxLength(128);
b.Property<string>("ProviderKey")
.HasMaxLength(128);
b.Property<string>("ProviderDisplayName");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("RoleId");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.ToTable("AspNetUserRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("LoginProvider")
.HasMaxLength(128);
b.Property<string>("Name")
.HasMaxLength(128);
b.Property<string>("Value");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens");
});
modelBuilder.Entity("eCommerce.cs.Data.Entities.OrderDetail", b =>
{
b.HasOne("eCommerce.cs.Data.Entities.Order", "Order")
.WithMany()
.HasForeignKey("OrderID")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("eCommerce.cs.Data.Entities.Product", "Product")
.WithMany()
.HasForeignKey("ProductID")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("eCommerce.cs.Data.Entities.Product", b =>
{
b.HasOne("eCommerce.cs.Data.Entities.ProductType", "ProductType")
.WithMany()
.HasForeignKey("ProductTypeID")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("eCommerce.cs.Data.Entities.SpecialTag", "SpecialTag")
.WithMany()
.HasForeignKey("SpecialTagID")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole")
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole")
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
#pragma warning restore 612, 618
}
}
}
| 35.373259 | 125 | 0.480589 | [
"MIT"
] | gorkemozturk/eCommerce.cs | eCommerce.cs/Data/Migrations/ApplicationDbContextModelSnapshot.cs | 12,701 | C# |
using System;
using System.Collections.Generic;
using Centaurus.Xdr;
namespace Centaurus.Models
{
[XdrContract]
public class QuantaBatch : Message
{
public override MessageTypes MessageType => MessageTypes.QuantaBatch;
[XdrField(0)]
public List<MessageEnvelope> Quanta { get; set; }
}
}
| 20.625 | 77 | 0.687879 | [
"MIT"
] | PinkDiamond1/centaurus | Centaurus.Models/InternalMessages/QuantaBatch.cs | 332 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Smoke : MonoBehaviour {
//private Animator anim;
public Animator anim;
private void Start () {
anim = GetComponent<Animator>();
//Debug.Log(anim == null ? "null" : anim.name);
}
public void StartEffect() {
//anim.SetTrigger("start");
GetComponent<Animator>().SetTrigger("start");
}
public void EndEffect() {
//PoolManager.Release(this);
if (gameObject.activeSelf) PoolManager.Release(this);
}
public void Init(Vector2 position) {
transform.position = position;
StartEffect();
}
}
| 20.2 | 55 | 0.70297 | [
"MIT"
] | MikanHako1024/MySoulKnight | Assets/Scripts/Smoke.cs | 608 | C# |
namespace AkkaNetNeuralNet.Core.Model
{
public class DogProfile : IDogProfile
{
public DogProfile(decimal ageAtDeath, Sex sex, Breed breed, decimal adultBodymass, decimal householdIncome)
{
AgeAtDeath = ageAtDeath;
Sex = sex;
Breed = breed;
AdultBodymass = adultBodymass;
HouseholdIncome = householdIncome;
}
public decimal AgeAtDeath { get; }
public Sex Sex { get; }
public Breed Breed { get; }
public decimal AdultBodymass { get; }
public decimal HouseholdIncome { get; }
}
}
| 29.333333 | 115 | 0.599026 | [
"Apache-2.0"
] | MatthewMcGowan/AkkaNetNeuralNet | AkkaNetNeuralNet/AkkaNetNeuralNet.Core/Model/DogProfile.cs | 618 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the opensearch-2021-01-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.OpenSearchService.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.OpenSearchService.Model.Internal.MarshallTransformations
{
/// <summary>
/// ListPackagesForDomain Request Marshaller
/// </summary>
public class ListPackagesForDomainRequestMarshaller : IMarshaller<IRequest, ListPackagesForDomainRequest> , IMarshaller<IRequest,AmazonWebServiceRequest>
{
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public IRequest Marshall(AmazonWebServiceRequest input)
{
return this.Marshall((ListPackagesForDomainRequest)input);
}
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="publicRequest"></param>
/// <returns></returns>
public IRequest Marshall(ListPackagesForDomainRequest publicRequest)
{
IRequest request = new DefaultRequest(publicRequest, "Amazon.OpenSearchService");
request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2021-01-01";
request.HttpMethod = "GET";
if (!publicRequest.IsSetDomainName())
throw new AmazonOpenSearchServiceException("Request object does not have required field DomainName set");
request.AddPathResource("{DomainName}", StringUtils.FromString(publicRequest.DomainName));
if (publicRequest.IsSetMaxResults())
request.Parameters.Add("maxResults", StringUtils.FromInt(publicRequest.MaxResults));
if (publicRequest.IsSetNextToken())
request.Parameters.Add("nextToken", StringUtils.FromString(publicRequest.NextToken));
request.ResourcePath = "/2021-01-01/domain/{DomainName}/packages";
request.UseQueryString = true;
return request;
}
private static ListPackagesForDomainRequestMarshaller _instance = new ListPackagesForDomainRequestMarshaller();
internal static ListPackagesForDomainRequestMarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static ListPackagesForDomainRequestMarshaller Instance
{
get
{
return _instance;
}
}
}
} | 37.042553 | 157 | 0.665422 | [
"Apache-2.0"
] | Hazy87/aws-sdk-net | sdk/src/Services/OpenSearchService/Generated/Model/Internal/MarshallTransformations/ListPackagesForDomainRequestMarshaller.cs | 3,482 | C# |
// <copyright company="PetaPoco - CollaboratingPlatypus">
// Apache License, Version 2.0 https://github.com/CollaboratingPlatypus/PetaPoco/blob/master/LICENSE.txt
// </copyright>
// <author>PetaPoco - CollaboratingPlatypus</author>
// <date>2015/12/28</date>
using System.Reflection;
using Xunit;
namespace PetaPoco.Tests.Integration.Databases.Sqlite
{
[Collection("SqliteTests")]
public class SqliteDatabaseTests : BaseDatabaseTests
{
private readonly SqliteDBTestProvider _provider;
public SqliteDatabaseTests()
: this(new SqliteDBTestProvider())
{
}
private SqliteDatabaseTests(SqliteDBTestProvider provider)
: base(provider)
{
_provider = provider;
}
/// <remarks>
/// This is required because we can't use the Mapper.* methods, as we're testing many different databases and it would
/// apply Sqlite logic incorrectly.
/// </remarks>
protected override void AfterDbCreate(Database db)
{
base.AfterDbCreate(db);
// ReSharper disable once PossibleNullReferenceException
db.GetType().GetField("_defaultMapper", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(db, _provider.GetDatabase().DefaultMapper);
}
}
} | 33.45 | 152 | 0.659193 | [
"Apache-2.0"
] | Arasz/PetaPoco | PetaPoco.Tests.Integration/Databases/Sqlite/SqliteDatabaseTests.cs | 1,338 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Academia.controls
{
public partial class ControlExercicios : UserControl
{
public ControlExercicios()
{
InitializeComponent();
}
}
}
| 19.380952 | 56 | 0.710074 | [
"MIT"
] | FSantosx/Academia | controls/ControlExercicios.cs | 409 | C# |
using System;
using NServiceBus.Extensions.DispatchRetries;
using Polly;
namespace NServiceBus
{
public static class MessageHandlerContextExtensions
{
public static void OverrideImmediateDispatchRetryPolicy(this IMessageHandlerContext context, AsyncPolicy immediateDispatchRetryPolicy)
{
if (immediateDispatchRetryPolicy == null)
{
throw new ArgumentNullException(nameof(immediateDispatchRetryPolicy));
}
var overrides = context.Extensions.Get<DispatchRetriesOverrides>(Constants.Overrides);
overrides.ImmediateDispatchPolicyOverride = immediateDispatchRetryPolicy;
}
public static void OverrideBatchDispatchRetryPolicy(this IMessageHandlerContext context, AsyncPolicy batchDispatchRetryPolicy)
{
if (batchDispatchRetryPolicy == null)
{
throw new ArgumentNullException(nameof(batchDispatchRetryPolicy));
}
var overrides = context.Extensions.Get<DispatchRetriesOverrides>(Constants.Overrides);
overrides.BatchDispatchPolicyOverride = batchDispatchRetryPolicy;
}
}
} | 38.096774 | 142 | 0.704488 | [
"Apache-2.0"
] | mauroservienti/NServiceBus.Extensions.DispatchRetries | src/NServiceBus.Extensions.DispatchRetries/MessageHandlerContextExtensions.cs | 1,183 | C# |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows;
using Microsoft.Xna.Framework;
namespace QuadTreeLib
{
internal class QuadNode<T>
{
#region Properties
/// <summary>
/// The node that this guy is inside of
/// </summary>
public QuadNode<T> Parent { get; internal set; }
/// <summary>
/// The four child nodes of this dude
/// </summary>
private QuadNode<T>[] _nodes = new QuadNode<T>[4];
/// <summary>
/// Get one of the child nodes via the [] operator
/// </summary>
/// <param name="direction"></param>
/// <returns></returns>
internal QuadNode<T> this[EDirection direction]
{
get
{
return _nodes[(int)direction];
}
set
{
//hold onto the node
_nodes[(int)direction] = value;
//set the node's parent to this dude
if (value != null)
{
value.Parent = this;
}
}
}
public ReadOnlyCollection<QuadNode<T>> Nodes;
internal List<T> quadObjects = new List<T>();
public ReadOnlyCollection<T> Objects;
/// <summary>
/// The size and location of this node
/// </summary>
public Rectangle Bounds { get; internal set; }
#endregion //Properties
#region Methods
/// <summary>
/// Constructor
/// </summary>
/// <param name="bounds"></param>
public QuadNode(Rectangle bounds)
{
Bounds = bounds;
Nodes = new ReadOnlyCollection<QuadNode<T>>(_nodes);
Objects = new ReadOnlyCollection<T>(quadObjects);
}
/// <summary>
/// constructor
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <param name="width"></param>
/// <param name="height"></param>
public QuadNode(int x, int y, int width, int height)
: this(new Rectangle(x, y, width, height))
{
}
/// <summary>
/// whether or not there are any child nodes of this dude
/// </summary>
/// <returns></returns>
public bool HasChildNodes()
{
return _nodes[0] != null;
}
#endregion //Methods
}
} | 20.670103 | 59 | 0.619451 | [
"MIT"
] | dmanning23/QuadTree | QuadTree/QuadTree.SharedProject/QuadNode.cs | 2,005 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Axe.Windows.Core.Types;
using System;
using System.Collections.Generic;
using Axe.Windows.Core.Bases;
using UIAutomationClient;
using Axe.Windows.Core.Attributes;
using Axe.Windows.Desktop.Utility;
using Axe.Windows.Desktop.Types;
namespace Axe.Windows.Desktop.UIAutomation.Patterns
{
/// <summary>
/// Control pattern wrapper for Selection Control Pattern
/// https://msdn.microsoft.com/en-us/library/windows/desktop/ee671285(v=vs.85).aspx
/// </summary>
[PatternEvent(Id = EventType.UIA_Selection_InvalidatedEventId)]
public class SelectionPattern : A11yPattern
{
IUIAutomationSelectionPattern Pattern;
public SelectionPattern(A11yElement e, IUIAutomationSelectionPattern p) : base(e, PatternType.UIA_SelectionPatternId)
{
Pattern = p;
PopulateProperties();
}
private void PopulateProperties()
{
#pragma warning disable CA2000 // Properties are disposed in A11yPattern.Dispose()
this.Properties.Add(new A11yPatternProperty() { Name = "CanSelectMultiple", Value = Convert.ToBoolean(this.Pattern.CurrentCanSelectMultiple) });
this.Properties.Add(new A11yPatternProperty() { Name = "IsSelectionRequired", Value = Convert.ToBoolean(this.Pattern.CurrentIsSelectionRequired) });
#pragma warning restore CA2000 // Properties are disposed in A11yPattern.Dispose()
}
[PatternMethod]
public IList<DesktopElement> GetSelection()
{
return this.Pattern.GetCurrentSelection().ToListOfDesktopElements();
}
protected override void Dispose(bool disposing)
{
if (Pattern != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(Pattern);
this.Pattern = null;
}
base.Dispose(disposing);
}
}
}
| 37.303571 | 161 | 0.667784 | [
"MIT"
] | lisli1/axe-windows | src/Desktop/UIAutomation/Patterns/SelectionPattern.cs | 2,034 | C# |
namespace JulMar.Core.Interfaces
{
/// <summary>
/// This interface describes a simple Undo service
/// </summary>
public interface IUndoService
{
/// <summary>
/// Maximum number of supported operations.
/// </summary>
int MaxSupportedOperations { get; set; }
/// <summary>
/// Returns true if we have at least one UNDO operation we can perform
/// </summary>
bool CanUndo { get; }
/// <summary>
/// True if at least one REDO operation is available.
/// </summary>
bool CanRedo { get; }
/// <summary>
/// Executes the next UNDO operation.
/// </summary>
/// <returns>True if an undo was executed</returns>
bool Undo();
/// <summary>
/// Executes the last REDO operation.
/// </summary>
/// <returns>True if a REDO operation occurred</returns>
bool Redo();
/// <summary>
/// Adds a new undo operation to the stack.
/// </summary>
/// <param name="undoOp">operation</param>
/// <param name="noInsertIfExecutingOperation">Do not insert record if currently running undo/redo</param>
/// <returns>True if record inserted, false if not</returns>
bool Add(ISupportUndo undoOp, bool noInsertIfExecutingOperation = true);
/// <summary>
/// Clears all the undo/redo events. This should be used if some
/// action makes the operations invalid (clearing a collection where you are tracking changes to indexes inside it for example)
/// </summary>
void Clear();
}
} | 34.77551 | 136 | 0.561033 | [
"MIT"
] | AsimKhan2019/MVVM-Helpers | Julmar.Wpf.Helpers/Julmar.Core/Interfaces/IUndoService.cs | 1,704 | C# |
using System.Collections.Generic;
using BotCore.Core.CurrencyBot.DomainModels;
using BotCore.Core.CurrencyBot.Entities;
namespace BotCore.Core.CurrencyBot.Interfaces
{
public interface IMessageService
{
/// <summary>
/// Get paginated string that contains currencies
/// </summary>
/// <param name="currencies"></param>
/// <returns>
/// For example:
/// U.S. Dollar (USD) \r\n Belarusian Rubel (BYN)
/// </returns>
string GetAllCurrenciesMessageAsync(IEnumerable<Currency> currencies);
/// <summary>
/// Get currency rate gain message
/// </summary>
/// <param name="gain"></param>
/// <returns>
/// For example:
/// 1 USD: 5 BYN (+4.0505)
/// </returns>
string GetCurrencyRateGainMessageAsync(CurrencyGain gain);
/// <summary>
/// Get currency rate message
/// </summary>
/// <param name="currency"></param>
/// <param name="amount"></param>
/// <returns>
/// For example:
/// 1000 USD - 50000 BYN
/// </returns>
string GetCurrencyRateMessageAsync(CurrencyModel currency, double amount);
}
} | 31.75 | 82 | 0.551969 | [
"MIT"
] | vorobeyDmitriy/BotCore | samples/BotCore.CurrencyBot.Core/Interfaces/IMessageService.cs | 1,272 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using NewBindingSample.Model;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using NewBindingSample.Views;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
namespace NewBindingSample
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
private void OnStandardBindingClicked(object sender, RoutedEventArgs e)
{
Frame.Navigate(typeof (StandardBinding));
}
private void OnMvvmBindingClicked(object sender, RoutedEventArgs e)
{
Frame.Navigate(typeof (MvvmBinding));
}
private void OnEventsBindingClicked(object sender, RoutedEventArgs e)
{
Frame.Navigate(typeof (EventsBinding));
}
private void OnListBindingClicked(object sender, RoutedEventArgs e)
{
Frame.Navigate(typeof(ListBinding));
}
}
}
| 28 | 106 | 0.686658 | [
"MIT"
] | qmatteoq/Windows10-Samples | Windows10/NewBindingSample/MainPage.xaml.cs | 1,486 | C# |
namespace Abacus.Geometry
{
public struct Square2D : IShape2D
{
private Vector2 _lowXyCorner;
private double _sideLength;
public Square2D(Vector2 lowXyCorner, double sideLength)
{
_lowXyCorner = lowXyCorner;
_sideLength = sideLength;
}
public double SideLength
{
get { return _sideLength; }
set { _sideLength = value; }
}
public Vector2 LowXyCorner
{
get { return _lowXyCorner; }
set { _lowXyCorner = value; }
}
public double MinX
{
get { return LowXyCorner.X; }
}
public double MaxX
{
get { return LowXyCorner.X + SideLength; }
}
public double MinY
{
get { return LowXyCorner.Y; }
}
public double MaxY
{
get { return LowXyCorner.Y + SideLength; }
}
public bool ContainsPoint(Vector2 v)
{
return (v.X >= MinX && v.X <= MaxX) && (v.Y >= MinY && v.Y <= MaxY);
}
public double Area
{
get { return SideLength*SideLength; }
}
public Vector2[] GetCorners()
{
double x = LowXyCorner.X;
double y = LowXyCorner.Y;
return new[]
{
new Vector2(MinX, MinY),
new Vector2(MaxX, MaxY),
new Vector2(MaxX, MinY),
new Vector2(MinX, MaxY)
};
}
}
} | 22.5 | 80 | 0.466667 | [
"MIT"
] | rexcardan/Abacus | Abacus/Geometry/Square2D.cs | 1,577 | C# |
using System;
using Contracts;
namespace KourageousTourists
{
public class KourageousSelfieParameter: KourageousParameter
{
public KourageousSelfieParameter() : base() {}
public KourageousSelfieParameter(CelestialBody target, string kerbal) : base(target, kerbal) {}
protected override string GetHashString() {
return "walk" + this.targetBody.bodyName + this.tourist;
}
protected override string GetTitle() {
return String.Format ("Take photo of {0} from the surface of {1}",
tourist, targetBody.bodyName);
}
protected override string GetMessageComplete() {
return String.Format ("{0} was pictured on the surface of {1}",
tourist, targetBody.bodyName);
}
protected override void OnRegister() {
KourageousTouristsAddOn.selfieListeners.Add (onSelfieTaken);
}
protected override void OnUnregister() {
KourageousTouristsAddOn.selfieListeners.Remove (onSelfieTaken);
}
private void onSelfieTaken() {
foreach (Vessel v in FlightGlobals.VesselsLoaded) {
if (v.isEVA &&
v.mainBody == targetBody &&
v.GetVesselCrew () [0].name.Equals (tourist) &&
v.situation == Vessel.Situations.LANDED) {
base.SetComplete ();
break;
}
}
}
}
}
| 23.653846 | 97 | 0.703252 | [
"MIT"
] | takoss/KourageousTourists | KourageousTourists/KourageousTourists/Contracts/KourageousSelfieParameter.cs | 1,232 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Avalonia.Controls.Platform.Surfaces;
using Avalonia.Platform;
using Avalonia.Win32.Interop;
using SharpDX;
using SharpDX.DXGI;
namespace Avalonia.Direct2D1
{
class HwndRenderTarget : SwapChainRenderTarget
{
private readonly IPlatformHandle _window;
public HwndRenderTarget(IPlatformHandle window)
{
_window = window;
}
protected override SwapChain1 CreateSwapChain(Factory2 dxgiFactory, SwapChainDescription1 swapChainDesc)
{
return new SwapChain1(dxgiFactory, DxgiDevice, _window.Handle, ref swapChainDesc);
}
protected override Size2F GetWindowDpi()
{
if (UnmanagedMethods.ShCoreAvailable)
{
uint dpix, dpiy;
var monitor = UnmanagedMethods.MonitorFromWindow(
_window.Handle,
UnmanagedMethods.MONITOR.MONITOR_DEFAULTTONEAREST);
if (UnmanagedMethods.GetDpiForMonitor(
monitor,
UnmanagedMethods.MONITOR_DPI_TYPE.MDT_EFFECTIVE_DPI,
out dpix,
out dpiy) == 0)
{
return new Size2F(dpix, dpiy);
}
}
return new Size2F(96, 96);
}
protected override Size2 GetWindowSize()
{
UnmanagedMethods.RECT rc;
UnmanagedMethods.GetClientRect(_window.Handle, out rc);
return new Size2(rc.right - rc.left, rc.bottom - rc.top);
}
}
}
| 28.847458 | 112 | 0.590482 | [
"MIT"
] | BOBO41/Avalonia | src/Windows/Avalonia.Direct2D1/HwndRenderTarget.cs | 1,704 | C# |
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using CliModline.Utils;
namespace CliModline.Test
{
[TestClass]
public class ModLineTest
{
private readonly string expectCrLf = "abc\r\ndef\r\n123";
private readonly string expectLf = "abc\ndef\n123";
private readonly string expectCr = "abc\rdef\r123";
[TestMethod]
public void NonConstract()
{
var source = "abcdef123";
var target = new ModLine(source);
var expect1 = NewLineKind.None;
Assert.AreEqual(expect1, target.OriginalKind);
Assert.AreEqual(source, target.GetCrLf());
}
[TestMethod]
public void CrLfConstract()
{
var source = "abc\r\ndef\r\n123";
var target = new ModLine(source);
var expect1 = NewLineKind.CRLF;
Assert.AreEqual(expect1, target.OriginalKind);
Assert.AreEqual(expectCrLf, target.GetCrLf());
Assert.AreEqual(expectLf, target.GetLf());
Assert.AreEqual(expectCr, target.GetCr());
}
[TestMethod]
public void LfConstract()
{
var source = "abc\ndef\n123";
var target = new ModLine(source);
var expect1 = NewLineKind.LF;
Assert.AreEqual(expect1, target.OriginalKind);
Assert.AreEqual(expectCrLf, target.GetCrLf());
Assert.AreEqual(expectLf, target.GetLf());
Assert.AreEqual(expectCr, target.GetCr());
}
[TestMethod]
public void CrConstract()
{
var source = "abc\rdef\r123";
var target = new ModLine(source);
var expect1 = NewLineKind.CR;
Assert.AreEqual(expect1, target.OriginalKind);
Assert.AreEqual(expectCrLf, target.GetCrLf());
Assert.AreEqual(expectLf, target.GetLf());
Assert.AreEqual(expectCr, target.GetCr());
}
[TestMethod]
public void MixedCrLf_CrConstract()
{
var source = "abc\r\ndef\r123";
var target = new ModLine(source);
var expect1 = NewLineKind.Mixed;
Assert.AreEqual(expect1, target.OriginalKind);
Assert.AreEqual(expectCrLf, target.GetCrLf());
Assert.AreEqual(expectLf, target.GetLf());
Assert.AreEqual(expectCr, target.GetCr());
}
[TestMethod]
public void MixedCrLf_LfConstract()
{
var source = "abc\r\ndef\n123";
var target = new ModLine(source);
var expect1 = NewLineKind.Mixed;
Assert.AreEqual(expect1, target.OriginalKind);
Assert.AreEqual(expectCrLf, target.GetCrLf());
Assert.AreEqual(expectLf, target.GetLf());
Assert.AreEqual(expectCr, target.GetCr());
}
[TestMethod]
public void MixedCr_LfConstract()
{
var source = "abc\rdef\n123";
var target = new ModLine(source);
var expect1 = NewLineKind.Mixed;
Assert.AreEqual(expect1, target.OriginalKind);
Assert.AreEqual(expectCrLf, target.GetCrLf());
Assert.AreEqual(expectLf, target.GetLf());
Assert.AreEqual(expectCr, target.GetCr());
}
}
}
| 31.857143 | 65 | 0.573393 | [
"BSD-3-Clause"
] | MakMokMak/CliModline | CliModline.Test/ModLineTest.cs | 3,347 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.Logic.V20160601.Outputs
{
/// <summary>
/// The Edifact agreement validation settings.
/// </summary>
[OutputType]
public sealed class EdifactValidationSettingsResponse
{
/// <summary>
/// The value indicating whether to allow leading and trailing spaces and zeroes.
/// </summary>
public readonly bool AllowLeadingAndTrailingSpacesAndZeroes;
/// <summary>
/// The value indicating whether to check for duplicate group control number.
/// </summary>
public readonly bool CheckDuplicateGroupControlNumber;
/// <summary>
/// The value indicating whether to check for duplicate interchange control number.
/// </summary>
public readonly bool CheckDuplicateInterchangeControlNumber;
/// <summary>
/// The value indicating whether to check for duplicate transaction set control number.
/// </summary>
public readonly bool CheckDuplicateTransactionSetControlNumber;
/// <summary>
/// The validity period of interchange control number.
/// </summary>
public readonly int InterchangeControlNumberValidityDays;
/// <summary>
/// The trailing separator policy.
/// </summary>
public readonly string TrailingSeparatorPolicy;
/// <summary>
/// The value indicating whether to trim leading and trailing spaces and zeroes.
/// </summary>
public readonly bool TrimLeadingAndTrailingSpacesAndZeroes;
/// <summary>
/// The value indicating whether to validate character set in the message.
/// </summary>
public readonly bool ValidateCharacterSet;
/// <summary>
/// The value indicating whether to Whether to validate EDI types.
/// </summary>
public readonly bool ValidateEdiTypes;
/// <summary>
/// The value indicating whether to Whether to validate XSD types.
/// </summary>
public readonly bool ValidateXsdTypes;
[OutputConstructor]
private EdifactValidationSettingsResponse(
bool allowLeadingAndTrailingSpacesAndZeroes,
bool checkDuplicateGroupControlNumber,
bool checkDuplicateInterchangeControlNumber,
bool checkDuplicateTransactionSetControlNumber,
int interchangeControlNumberValidityDays,
string trailingSeparatorPolicy,
bool trimLeadingAndTrailingSpacesAndZeroes,
bool validateCharacterSet,
bool validateEdiTypes,
bool validateXsdTypes)
{
AllowLeadingAndTrailingSpacesAndZeroes = allowLeadingAndTrailingSpacesAndZeroes;
CheckDuplicateGroupControlNumber = checkDuplicateGroupControlNumber;
CheckDuplicateInterchangeControlNumber = checkDuplicateInterchangeControlNumber;
CheckDuplicateTransactionSetControlNumber = checkDuplicateTransactionSetControlNumber;
InterchangeControlNumberValidityDays = interchangeControlNumberValidityDays;
TrailingSeparatorPolicy = trailingSeparatorPolicy;
TrimLeadingAndTrailingSpacesAndZeroes = trimLeadingAndTrailingSpacesAndZeroes;
ValidateCharacterSet = validateCharacterSet;
ValidateEdiTypes = validateEdiTypes;
ValidateXsdTypes = validateXsdTypes;
}
}
}
| 39.4 | 98 | 0.681806 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/Logic/V20160601/Outputs/EdifactValidationSettingsResponse.cs | 3,743 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.DataFactory.Outputs
{
/// <summary>
/// The MongoDB database dataset.
/// </summary>
[OutputType]
public sealed class MongoDbV2CollectionDatasetResponse
{
/// <summary>
/// List of tags that can be used for describing the Dataset.
/// </summary>
public readonly ImmutableArray<object> Annotations;
/// <summary>
/// The collection name of the MongoDB database. Type: string (or Expression with resultType string).
/// </summary>
public readonly object Collection;
/// <summary>
/// Dataset description.
/// </summary>
public readonly string? Description;
/// <summary>
/// The folder that this Dataset is in. If not specified, Dataset will appear at the root level.
/// </summary>
public readonly Outputs.DatasetResponseFolder? Folder;
/// <summary>
/// Linked service reference.
/// </summary>
public readonly Outputs.LinkedServiceReferenceResponse LinkedServiceName;
/// <summary>
/// Parameters for dataset.
/// </summary>
public readonly ImmutableDictionary<string, Outputs.ParameterSpecificationResponse>? Parameters;
/// <summary>
/// Columns that define the physical type schema of the dataset. Type: array (or Expression with resultType array), itemType: DatasetSchemaDataElement.
/// </summary>
public readonly object? Schema;
/// <summary>
/// Columns that define the structure of the dataset. Type: array (or Expression with resultType array), itemType: DatasetDataElement.
/// </summary>
public readonly object? Structure;
/// <summary>
/// Type of dataset.
/// Expected value is 'MongoDbV2Collection'.
/// </summary>
public readonly string Type;
[OutputConstructor]
private MongoDbV2CollectionDatasetResponse(
ImmutableArray<object> annotations,
object collection,
string? description,
Outputs.DatasetResponseFolder? folder,
Outputs.LinkedServiceReferenceResponse linkedServiceName,
ImmutableDictionary<string, Outputs.ParameterSpecificationResponse>? parameters,
object? schema,
object? structure,
string type)
{
Annotations = annotations;
Collection = collection;
Description = description;
Folder = folder;
LinkedServiceName = linkedServiceName;
Parameters = parameters;
Schema = schema;
Structure = structure;
Type = type;
}
}
}
| 34.337079 | 159 | 0.622709 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/DataFactory/Outputs/MongoDbV2CollectionDatasetResponse.cs | 3,056 | C# |
// -----------------------------------------------------------------------------
// <copyright file="IAlerterRepository" company="Matt Scheetz">
// Copyright (c) Matt Scheetz All Rights Reserved
// </copyright>
// <author name="Matt Scheetz" date="12/3/2018 7:37:26 PM" />
// -----------------------------------------------------------------------------
namespace Cryptobitfolio.Data.Interfaces.Database
{
#region Usings
using Cryptobitfolio.Business.Entities.Portfolio;
#endregion Usings
public interface IAlerterRepository : IDatabaseRepositoryBase<Alerter>
{
}
} | 31.473684 | 81 | 0.525084 | [
"MIT"
] | mscheetz/cryptobitfolio | Cryptobitfolio/Cryptobitfolio.Data/Interfaces/Database/IAlerterRepository.cs | 600 | C# |
using MedicalAppointment.Core.DTOs.Appointment;
using MedicalAppointment.Core.Interfaces;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace MedicalAppointment.Core.Services
{
public class AppointmentReportService
{
private readonly IAppointmentService _appointmentService;
public AppointmentReportService(IAppointmentService appointmentService)
{
_appointmentService = appointmentService;
}
public async Task<AppointmentReportDto> CreateAsync()
{
return new AppointmentReportDto()
{
TotalNumber = await _appointmentService.GetAppointmentsNumberAsync()
};
}
}
}
| 26.928571 | 84 | 0.697613 | [
"MIT"
] | andrija-mitrovic/MedicalAppointment | MedicalAppointment.Core/Services/AppointmentReportService.cs | 756 | C# |
// Copyright 2022 Google LLC
//
// 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
//
// https://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.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Recommender.V1.Snippets
{
// [START recommender_v1_generated_Recommender_MarkRecommendationFailed_sync]
using Google.Cloud.Recommender.V1;
public sealed partial class GeneratedRecommenderClientSnippets
{
/// <summary>Snippet for MarkRecommendationFailed</summary>
/// <remarks>
/// This snippet has been automatically generated for illustrative purposes only.
/// It may require modifications to work in your environment.
/// </remarks>
public void MarkRecommendationFailedRequestObject()
{
// Create client
RecommenderClient recommenderClient = RecommenderClient.Create();
// Initialize request argument(s)
MarkRecommendationFailedRequest request = new MarkRecommendationFailedRequest
{
RecommendationName = RecommendationName.FromProjectLocationRecommenderRecommendation("[PROJECT]", "[LOCATION]", "[RECOMMENDER]", "[RECOMMENDATION]"),
StateMetadata = { { "", "" }, },
Etag = "",
};
// Make the request
Recommendation response = recommenderClient.MarkRecommendationFailed(request);
}
}
// [END recommender_v1_generated_Recommender_MarkRecommendationFailed_sync]
}
| 42.26087 | 165 | 0.689815 | [
"Apache-2.0"
] | AlexandrTrf/google-cloud-dotnet | apis/Google.Cloud.Recommender.V1/Google.Cloud.Recommender.V1.GeneratedSnippets/RecommenderClient.MarkRecommendationFailedRequestObjectSnippet.g.cs | 1,944 | C# |
//#define COSMOSDEBUG
using System;
using System.Collections.Generic;
using System.IO;
using Cosmos.HAL.BlockDevice;
using Cosmos.System.FileSystem.FAT;
using Cosmos.System.FileSystem.Listing;
using Cosmos.System.FileSystem.VFS;
namespace Cosmos.System.FileSystem
{
// ReSharper disable once InconsistentNaming
/// <summary>
/// Cosmos default virtual file system.
/// </summary>
/// <seealso cref="Cosmos.System.FileSystem.VFS.VFSBase" />
public class CosmosVFS : VFSBase
{
private List<Partition> mPartitions;
private List<FileSystem> mFileSystems;
private FileSystem mCurrentFileSystem;
/// <summary>
/// Initializes the virtual file system.
/// </summary>
public override void Initialize()
{
mPartitions = new List<Partition>();
mFileSystems = new List<FileSystem>();
InitializePartitions();
if (mPartitions.Count > 0)
{
InitializeFileSystems();
}
}
/// <summary>
/// Creates a new file.
/// </summary>
/// <param name="aPath">The full path including the file to create.</param>
/// <returns></returns>
/// <exception cref="ArgumentNullException"></exception>
/// <exception cref="ArgumentException">aPath</exception>
public override DirectoryEntry CreateFile(string aPath)
{
Global.mFileSystemDebugger.SendInternal("--- CosmosVFS.CreateFile ---");
if (aPath == null)
{
throw new ArgumentNullException(nameof(aPath));
}
if (aPath.Length == 0)
{
throw new ArgumentException("aPath");
}
Global.mFileSystemDebugger.SendInternal("aPath =");
Global.mFileSystemDebugger.SendInternal(aPath);
if (File.Exists(aPath))
{
Global.mFileSystemDebugger.SendInternal("File already exists.");
return GetFile(aPath);
}
Global.mFileSystemDebugger.SendInternal("File doesn't exist.");
string xFileToCreate = Path.GetFileName(aPath);
Global.mFileSystemDebugger.SendInternal("After GetFileName");
Global.mFileSystemDebugger.SendInternal("xFileToCreate =");
Global.mFileSystemDebugger.SendInternal(xFileToCreate);
string xParentDirectory = Path.GetDirectoryName(aPath);
Global.mFileSystemDebugger.SendInternal("After removing last path part");
Global.mFileSystemDebugger.SendInternal("xParentDirectory =");
Global.mFileSystemDebugger.SendInternal(xParentDirectory);
DirectoryEntry xParentEntry = GetDirectory(xParentDirectory);
if (xParentEntry == null)
{
Global.mFileSystemDebugger.SendInternal("Parent directory doesn't exist.");
xParentEntry = CreateDirectory(xParentDirectory);
}
Global.mFileSystemDebugger.SendInternal("Parent directory exists.");
var xFS = GetFileSystemFromPath(xParentDirectory);
return xFS.CreateFile(xParentEntry, xFileToCreate);
}
/// <summary>
/// Creates a directory.
/// </summary>
/// <param name="aPath">The full path including the directory to create.</param>
/// <returns></returns>
/// <exception cref="ArgumentNullException"></exception>
/// <exception cref="ArgumentException">aPath</exception>
public override DirectoryEntry CreateDirectory(string aPath)
{
Global.mFileSystemDebugger.SendInternal("-- CosmosVFS.CreateDirectory ---");
if (aPath == null)
{
throw new ArgumentNullException(nameof(aPath));
}
if (aPath.Length == 0)
{
throw new ArgumentException("aPath");
}
Global.mFileSystemDebugger.SendInternal("aPath =");
Global.mFileSystemDebugger.SendInternal(aPath);
if (Directory.Exists(aPath))
{
Global.mFileSystemDebugger.SendInternal("Path already exists.");
return GetDirectory(aPath);
}
Global.mFileSystemDebugger.SendInternal("Path doesn't exist.");
aPath = aPath.TrimEnd(DirectorySeparatorChar, AltDirectorySeparatorChar);
string xDirectoryToCreate = Path.GetFileName(aPath);
Global.mFileSystemDebugger.SendInternal("After GetFileName");
Global.mFileSystemDebugger.SendInternal("xDirectoryToCreate =");
Global.mFileSystemDebugger.SendInternal(xDirectoryToCreate);
string xParentDirectory = Path.GetDirectoryName(aPath);
Global.mFileSystemDebugger.SendInternal("After removing last path part");
Global.mFileSystemDebugger.SendInternal("xParentDirectory =");
Global.mFileSystemDebugger.SendInternal(xParentDirectory);
DirectoryEntry xParentEntry = GetDirectory(xParentDirectory);
if (xParentEntry == null)
{
Global.mFileSystemDebugger.SendInternal("Parent directory doesn't exist.");
xParentEntry = CreateDirectory(xParentDirectory);
}
Global.mFileSystemDebugger.SendInternal("Parent directory exists.");
var xFS = GetFileSystemFromPath(xParentDirectory);
return xFS.CreateDirectory(xParentEntry, xDirectoryToCreate);
}
/// <summary>
/// Deletes a file.
/// </summary>
/// <param name="aPath">The full path.</param>
/// <returns></returns>
public override bool DeleteFile(DirectoryEntry aPath)
{
try
{
var xFS = GetFileSystemFromPath(aPath.mFullPath);
xFS.DeleteFile(aPath);
return true;
}
catch
{
return false;
}
}
/// <summary>
/// Deletes an empty directory.
/// </summary>
/// <param name="aPath">The full path.</param>
/// <returns></returns>
public override bool DeleteDirectory(DirectoryEntry aPath)
{
try
{
if (GetDirectoryListing(aPath).Count > 0)
{
throw new Exception("Directory is not empty");
}
var xFS = GetFileSystemFromPath(aPath.mFullPath);
xFS.DeleteDirectory(aPath);
return true;
}
catch
{
return false;
}
}
/// <summary>
/// Gets the directory listing for a path.
/// </summary>
/// <param name="aPath">The full path.</param>
/// <returns></returns>
public override List<DirectoryEntry> GetDirectoryListing(string aPath)
{
var xFS = GetFileSystemFromPath(aPath);
var xDirectory = DoGetDirectoryEntry(aPath, xFS);
return xFS.GetDirectoryListing(xDirectory);
}
/// <summary>
/// Gets the directory listing for a directory entry.
/// </summary>
/// <param name="aDirectory">The directory entry.</param>
/// <returns></returns>
public override List<DirectoryEntry> GetDirectoryListing(DirectoryEntry aDirectory)
{
if (aDirectory == null || String.IsNullOrEmpty(aDirectory.mFullPath))
{
throw new ArgumentException("Argument is null or empty", nameof(aDirectory));
}
return GetDirectoryListing(aDirectory.mFullPath);
}
/// <summary>
/// Gets the directory entry for a directory.
/// </summary>
/// <param name="aPath">The full path path.</param>
/// <returns>A directory entry for the directory.</returns>
/// <exception cref="Exception"></exception>
public override DirectoryEntry GetDirectory(string aPath)
{
try
{
var xFileSystem = GetFileSystemFromPath(aPath);
var xEntry = DoGetDirectoryEntry(aPath, xFileSystem);
if ((xEntry != null) && (xEntry.mEntryType == DirectoryEntryTypeEnum.Directory))
{
return xEntry;
}
}
catch (Exception)
{
Global.mFileSystemDebugger.SendInternal("CosmosVFS.GetDirectory - DoGetDirectoryEntry failed, returning null. aPath = " + aPath);
return null;
}
throw new Exception(aPath + " was found, but is not a directory.");
}
/// <summary>
/// Gets the directory entry for a file.
/// </summary>
/// <param name="aPath">The full path.</param>
/// <returns>A directory entry for the file.</returns>
/// <exception cref="Exception"></exception>
public override DirectoryEntry GetFile(string aPath)
{
try
{
var xFileSystem = GetFileSystemFromPath(aPath);
var xEntry = DoGetDirectoryEntry(aPath, xFileSystem);
if ((xEntry != null) && (xEntry.mEntryType == DirectoryEntryTypeEnum.File))
{
return xEntry;
}
}
catch (Exception)
{
Global.mFileSystemDebugger.SendInternal("CosmosVFS.GetFile - DoGetDirectoryEntry failed, returning null. aPath = " + aPath);
return null;
}
throw new Exception(aPath + " was found, but is not a file.");
}
/// <summary>
/// Gets the volumes for all registered file systems.
/// </summary>
/// <returns>A list of directory entries for all volumes.</returns>
public override List<DirectoryEntry> GetVolumes()
{
List<DirectoryEntry> xVolumes = new List<DirectoryEntry>();
for (int i = 0; i < mFileSystems.Count; i++)
{
xVolumes.Add(GetVolume(mFileSystems[i]));
}
return xVolumes;
}
/// <summary>
/// Gets the directory entry for a volume.
/// </summary>
/// <param name="aPath">The volume root path.</param>
/// <returns>A directory entry for the volume.</returns>
public override DirectoryEntry GetVolume(string aPath)
{
if (string.IsNullOrEmpty(aPath))
{
return null;
}
var xFileSystem = GetFileSystemFromPath(aPath);
if (xFileSystem != null)
{
return GetVolume(xFileSystem);
}
return null;
}
/// <summary>
/// Gets the attributes for a File / Directory.
/// </summary>
/// <param name="aPath">The path of the File / Directory.</param>
/// <returns>The File / Directory attributes.</returns>
public override FileAttributes GetFileAttributes(string aPath)
{
/*
* We are limiting ourselves to the simpler attributes File and Directory for now.
* I think that in the end FAT does not support anything else
*/
Global.mFileSystemDebugger.SendInternal($"CosmosVFS.GetFileAttributes() for path {aPath}");
var xFileSystem = GetFileSystemFromPath(aPath);
var xEntry = DoGetDirectoryEntry(aPath, xFileSystem);
if (xEntry == null)
throw new Exception($"{aPath} is neither a file neither a directory");
switch (xEntry.mEntryType)
{
case DirectoryEntryTypeEnum.File:
Global.mFileSystemDebugger.SendInternal($"It is a File");
return FileAttributes.Normal;
case DirectoryEntryTypeEnum.Directory:
Global.mFileSystemDebugger.SendInternal($"It is a Directory");
return FileAttributes.Directory;
case DirectoryEntryTypeEnum.Unknown:
default:
throw new Exception($"{aPath} is neither a file neither a directory");
}
}
/// <summary>
/// Sets the attributes for a File / Directory.
/// </summary>
/// <param name="aPath">The path of the File / Directory.</param>
/// <param name="fileAttributes">The attributes of the File / Directory.</param>
public override void SetFileAttributes(string aPath, FileAttributes fileAttributes)
{
throw new NotImplementedException("SetFileAttributes not implemented");
}
/// <summary>
/// Initializes the partitions for all block devices.
/// </summary>
protected virtual void InitializePartitions()
{
for (int i = 0; i < BlockDevice.Devices.Count; i++)
{
if (BlockDevice.Devices[i] is Partition)
{
mPartitions.Add((Partition)BlockDevice.Devices[i]);
}
}
if (mPartitions.Count > 0)
{
for (int i = 0; i < mPartitions.Count; i++)
{
Global.mFileSystemDebugger.SendInternal("Partition #: ");
Global.mFileSystemDebugger.SendInternal(i + 1);
global::System.Console.WriteLine("Partition #: " + (i + 1));
Global.mFileSystemDebugger.SendInternal("Block Size:");
Global.mFileSystemDebugger.SendInternal(mPartitions[i].BlockSize);
global::System.Console.WriteLine("Block Size: " + mPartitions[i].BlockSize + " bytes");
Global.mFileSystemDebugger.SendInternal("Block Count:");
Global.mFileSystemDebugger.SendInternal(mPartitions[i].BlockCount);
global::System.Console.WriteLine("Block Count: " + mPartitions[i].BlockCount);
Global.mFileSystemDebugger.SendInternal("Size:");
Global.mFileSystemDebugger.SendInternal(mPartitions[i].BlockCount * mPartitions[i].BlockSize / 1024 / 1024);
global::System.Console.WriteLine("Size: " + mPartitions[i].BlockCount * mPartitions[i].BlockSize / 1024 / 1024 + " MB");
}
}
else
{
global::System.Console.WriteLine("No partitions found!");
}
}
/// <summary>
/// Initializes the file system for all partitions.
/// </summary>
protected virtual void InitializeFileSystems()
{
for (int i = 0; i < mPartitions.Count; i++)
{
string xRootPath = string.Concat(i, VolumeSeparatorChar, DirectorySeparatorChar);
var xSize = (long)(mPartitions[i].BlockCount * mPartitions[i].BlockSize / 1024 / 1024);
switch (FileSystem.GetFileSystemType(mPartitions[i]))
{
case FileSystemType.FAT:
mFileSystems.Add(new FatFileSystem(mPartitions[i], xRootPath, xSize));
break;
default:
global::System.Console.WriteLine("Unknown filesystem type!");
return;
}
if ((mFileSystems.Count > 0) && (mFileSystems[mFileSystems.Count - 1].mRootPath == xRootPath))
{
string xMessage = string.Concat("Initialized ", mFileSystems.Count, " filesystem(s)...");
global::System.Console.WriteLine(xMessage);
mFileSystems[i].DisplayFileSystemInfo();
Directory.SetCurrentDirectory(xRootPath);
}
else
{
string xMessage = string.Concat("No filesystem found on partition #", i);
global::System.Console.WriteLine(xMessage);
}
}
}
/// <summary>
/// Gets the file system from a path.
/// </summary>
/// <param name="aPath">The path.</param>
/// <returns>The file system for the path.</returns>
/// <exception cref="Exception">Unable to determine filesystem for path: + aPath</exception>
private FileSystem GetFileSystemFromPath(string aPath)
{
Global.mFileSystemDebugger.SendInternal("--- CosmosVFS.GetFileSystemFromPath ---");
if (String.IsNullOrEmpty(aPath))
{
throw new ArgumentException("Argument is null or empty", nameof(aPath));
}
Global.mFileSystemDebugger.SendInternal("aPath =");
Global.mFileSystemDebugger.SendInternal(aPath);
string xPath = Path.GetPathRoot(aPath);
Global.mFileSystemDebugger.SendInternal("xPath after GetPathRoot =");
Global.mFileSystemDebugger.SendInternal(xPath);
if ((mCurrentFileSystem != null) && (xPath == mCurrentFileSystem.mRootPath))
{
Global.mFileSystemDebugger.SendInternal("Returning current file system.");
return mCurrentFileSystem;
}
for (int i = 0; i < mFileSystems.Count; i++)
{
if (mFileSystems[i].mRootPath == xPath)
{
Global.mFileSystemDebugger.SendInternal("Found filesystem.");
mCurrentFileSystem = mFileSystems[i];
return mCurrentFileSystem;
}
}
throw new Exception("Unable to determine filesystem for path: " + aPath);
}
/// <summary>
/// Attempts to get a directory entry for a path in a file system.
/// </summary>
/// <param name="aPath">The path.</param>
/// <param name="aFS">The file system.</param>
/// <returns>A directory entry for the path.</returns>
/// <exception cref="ArgumentNullException">aFS</exception>
/// <exception cref="Exception">Path part ' + xPathPart + ' not found!</exception>
private DirectoryEntry DoGetDirectoryEntry(string aPath, FileSystem aFS)
{
Global.mFileSystemDebugger.SendInternal("--- CosmosVFS.DoGetDirectoryEntry ---");
if (String.IsNullOrEmpty(aPath))
{
throw new ArgumentException("Argument is null or empty", nameof(aPath));
}
if (aFS == null)
{
throw new ArgumentNullException(nameof(aFS));
}
Global.mFileSystemDebugger.SendInternal("aPath =");
Global.mFileSystemDebugger.SendInternal(aPath);
string[] xPathParts = VFSManager.SplitPath(aPath);
DirectoryEntry xBaseDirectory = GetVolume(aFS);
if (xPathParts.Length == 1)
{
Global.mFileSystemDebugger.SendInternal("Returning the volume.");
return xBaseDirectory;
}
// start at index 1, because 0 is the volume
for (int i = 1; i < xPathParts.Length; i++)
{
var xPathPart = xPathParts[i].ToLower();
var xPartFound = false;
var xListing = aFS.GetDirectoryListing(xBaseDirectory);
for (int j = 0; j < xListing.Count; j++)
{
var xListingItem = xListing[j];
string xListingItemName = xListingItem.mName.ToLower();
xPathPart = xPathPart.ToLower();
if (xListingItemName == xPathPart)
{
xBaseDirectory = xListingItem;
xPartFound = true;
break;
}
}
if (!xPartFound)
{
throw new Exception("Path part '" + xPathPart + "' not found!");
}
}
return xBaseDirectory;
}
/// <summary>
/// Gets the root directory entry for a volume in a file system.
/// </summary>
/// <param name="aFS">The file system containing the volume.</param>
/// <returns>A directory entry for the volume.</returns>
private DirectoryEntry GetVolume(FileSystem aFS)
{
Global.mFileSystemDebugger.SendInternal("--- CosmosVFS.GetVolume ---");
if (aFS == null)
{
Global.mFileSystemDebugger.SendInternal("File system is null.");
throw new ArgumentNullException(nameof(aFS));
}
return aFS.GetRootDirectory();
}
}
}
| 38.101449 | 145 | 0.55097 | [
"BSD-3-Clause"
] | KimTooFlex/Cosmos | source/Cosmos.System2/FileSystem/CosmosVFS.cs | 21,034 | C# |
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
namespace ufollow.Application
{
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
}
}
| 24.444444 | 77 | 0.606818 | [
"Apache-2.0"
] | ufollow/api | src/ufollow.Application/Program.cs | 442 | C# |
using Network;
namespace LoginService.Network.GameServerPackets
{
internal class LoginServer : ServerPacket
{
private const byte Opcode = 0xA1;
private readonly int _key;
public LoginServer(int randomKey)
{
_key = randomKey;
}
public override void Write()
{
WriteByte(Opcode);
WriteInt(_key);
}
}
}
| 19.714286 | 48 | 0.562802 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | dr3dd/L2Interlude | LoginService/Network/GameServerPackets/LoginServer.cs | 416 | C# |
using System;
using System.IO;
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Crypto.IO;
using Org.BouncyCastle.Security;
namespace Org.BouncyCastle.Crypto.Operators
{
public class Asn1DigestFactory : IDigestFactory
{
public static Asn1DigestFactory Get(DerObjectIdentifier oid)
{
return new Asn1DigestFactory(DigestUtilities.GetDigest(oid), oid);
}
public static Asn1DigestFactory Get(String mechanism)
{
DerObjectIdentifier oid = DigestUtilities.GetObjectIdentifier(mechanism);
return new Asn1DigestFactory(DigestUtilities.GetDigest(oid), oid);
}
private readonly IDigest mDigest;
private readonly DerObjectIdentifier mOid;
public Asn1DigestFactory(IDigest digest, DerObjectIdentifier oid)
{
this.mDigest = digest;
this.mOid = oid;
}
public virtual object AlgorithmDetails
{
get { return new AlgorithmIdentifier(mOid); }
}
public virtual int DigestLength
{
get { return mDigest.GetDigestSize(); }
}
public virtual IStreamCalculator CreateCalculator()
{
return new DfDigestStream(mDigest);
}
}
internal class DfDigestStream : IStreamCalculator
{
private readonly DigestSink mStream;
public DfDigestStream(IDigest digest)
{
this.mStream = new DigestSink(digest);
}
public Stream Stream
{
get { return mStream; }
}
public object GetResult()
{
byte[] result = new byte[mStream.Digest.GetDigestSize()];
mStream.Digest.DoFinal(result, 0);
return new SimpleBlockResult(result);
}
}
}
| 27.394366 | 89 | 0.587661 | [
"MIT"
] | straight-coding/EmbedTools | crypto/src/crypto/operators/Asn1DigestFactory.cs | 1,947 | C# |
//
// TensorFlow.cs; Bindings to the TensorFlow C API for .NET
//
// Authors:
// Miguel de Icaza (miguel@microsoft.com)
// ㄴThank you! (AinL
//
// Strongly typed API
// The API generally takes a TF_Status that defaults to null, if the value is null, on error, this raises an exception, otherwise, the error is returned on the TF_Status.
// You can use TFStatus.Default for a value to use when you do not want to create the value yourself and are ok reusing the value.
//
// Guidaance on doing language bindings for Tensorflow:
// https://www.tensorflow.org/versions/r0.11/how_tos/language_bindings/
using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Globalization;
using System.Linq;
using TF_Status = System.IntPtr;
using TF_SessionOptions = System.IntPtr;
using TF_Graph = System.IntPtr;
using TF_OperationDescription = System.IntPtr;
using TF_Operation = System.IntPtr;
using TF_Session = System.IntPtr;
using TF_DeprecatedSession = System.IntPtr;
using TF_Tensor = System.IntPtr;
using TF_ImportGraphDefOptions = System.IntPtr;
using TF_Library = System.IntPtr;
using TF_BufferPtr = System.IntPtr;
using size_t = System.UIntPtr;
using System.Numerics;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Diagnostics;
using System.Reflection;
namespace TensorFlow
{
public abstract class NativeBinding
{
public const string TensorFlowLibrary = "libtensorflow";
public delegate void Print(string s);
protected abstract Print InternalPrintFunc { get; set; }
public static Print PrintFunc
{
get
{
return Current.InternalPrintFunc;
}
set
{
Current.InternalPrintFunc = value;
}
}
public static NativeBinding _current;
public static NativeBinding Current
{
get
{
if (_current == null)
throw new Exception("NativeBinding is not inited!\nPlease call { TensorFlow.[Platform].NativeBinding.Init(); } before use library.");
return _current;
}
set
{
if (_current == null)
{
_current = value;
}
else
throw new Exception("NativeBinding is alreay Inited");
}
}
static NativeBinding()
{
}
public unsafe static void MemoryCopy(void* source, void* destination, long destinationSizeInBytes, long sourceBytesToCopy)
{
Current.InternalMemoryCopy(source, destination, destinationSizeInBytes, sourceBytesToCopy);
}
protected unsafe abstract void InternalMemoryCopy(void* source, void* destination, long destinationSizeInBytes, long sourceBytesToCopy);
public static void Log(string msg)
{
PrintFunc(msg);
}
}
/// <summary>
/// Contains TensorFlow fundamental methods and utility functions.
/// </summary>
public static class TFCore
{
internal static string GetStr(this IntPtr x) => Marshal.PtrToStringAnsi(x);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe IntPtr TF_Version();
static TFCore()
{
CheckSize();
}
/// <summary>
/// Returns the version of the TensorFlow runtime in use.
/// </summary>
/// <value>The version.</value>
public static string Version => TF_Version().GetStr();
// extern size_t TF_DataTypeSize (TF_DataType dt);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern IntPtr TF_DataTypeSize(TFDataType dt);
/// <summary>
/// Gets the size in bytes of the specified TensorFlow data type.
/// </summary>
/// <returns>The data type size.</returns>
/// <param name="dt">Dt.</param>
public static long GetDataTypeSize(TFDataType dt) => (long)TF_DataTypeSize(dt);
// extern TF_Buffer * TF_GetAllOpList ();
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe IntPtr TF_GetAllOpList();
/// <summary>
/// Retrieves the ProtocolBuffer describing all of the available operations in
/// the TensorFlow library in current use.
/// </summary>
/// <returns>The buffer contains a ProtocolBuffer encoded payload, you need a ProtocolBuffer reader to process the contents.</returns>
public static TFBuffer GetAllOpList()
{
return new TFBuffer(TF_GetAllOpList());
}
private static bool sizeChecked = false;
internal static void CheckSize()
{
if (sizeChecked)
return;
unsafe
{
if (sizeof(IntPtr) == 4)
{
Debug.WriteLine(
"Your excutable is builded in x86. This may occur runtime errors\n" +
"The TensorFlow native libraries should compiled in 64 bit mode, you should run in 64 bit mode\n" +
"With Mono, do that with mono --arch=64 executable.exe, if using an IDE like MonoDevelop,\n" +
"Xamarin Studio or Visual Studio for Mac, Build/Compiler settings, make sure that " +
"\"Platform Target\" has x64 selected.");
}
sizeChecked = true;
}
}
}
/// <summary>
/// Base class for many TensorFlow data types that provides a common idiom to dispose and
/// release resources associated with the native data types. Generally, you do not need to use this.
/// </summary>
/// <remarks>
/// <para>
/// This implements the Dispose pattern in a reusable form for TensorFlow types.
/// </para>
/// <para>
/// Subclasses invoke the constructor with the handle that this will wrap, and must
/// override the NativeDispose method (internal) to release the associated resource.
/// </para>
/// </remarks>
public abstract class TFDisposable : IDisposable
{
internal IntPtr handle;
bool disposed = false;
/// <summary>
/// Returns the opaque handle to the object that this TFDisposable owns.
/// </summary>
/// <value>The handle.</value>
public IntPtr Handle => handle;
static TFDisposable()
{
TFCore.CheckSize();
}
/// <summary>
/// Initializes a new instance of the <see cref="T:TensorFlow.TFDisposable"/> class.
/// </summary>
public TFDisposable()
{ }
/// <summary>
/// Initializes a new instance of the <see cref="T:TensorFlow.TFDisposable"/> class
/// from the handle that it will wrap.
/// </summary>
public TFDisposable(IntPtr handle)
{
this.handle = handle;
}
/// <summary>
/// Releases all resource used by the <see cref="T:TensorFlow.TFDisposable"/> object.
/// </summary>
/// <remarks>Call Dispose when you are finished using the <see cref="T:TensorFlow.TFDisposable"/>. The
/// Dispose method leaves the <see cref="T:TensorFlow.TFDisposable"/> in an unusable state. After
/// calling Dispose, you must release all references to the <see cref="T:TensorFlow.TFDisposable"/> so
/// the garbage collector can reclaim the memory that the <see cref="T:TensorFlow.TFDisposable"/> was occupying.</remarks>
public void Dispose()
{
if (!disposed)
{
Dispose(true);
GC.SuppressFinalize(this);
disposed = true;
}
}
~TFDisposable()
{
Dispose(false);
}
// Must be implemented in subclasses to dispose the unmanaged object, it does
// not need to take care of zeroing out the handle, that is done by the Dispose
// method inherited from TFDisposable
internal abstract void NativeDispose(IntPtr handle);
/// <summary>
/// Dispose the specified object
/// </summary>
/// <param name="disposing">If set to <c>true</c> it means that this method was called from Dispose, otherwise from the finalizer.</param>
public virtual void Dispose(bool disposing)
{
if (disposing)
{
if (handle != IntPtr.Zero)
NativeDispose(handle);
handle = IntPtr.Zero;
}
}
internal static void ObjectDisposedException()
{
throw new ObjectDisposedException("The object was disposed");
}
}
/// <summary>
/// TensorFlow Exception
/// </summary>
public class TFException : Exception {
/// <summary>
/// Initializes a new instance of the <see cref="T:TensorFlow.TFException"/> class with a message.
/// </summary>
/// <param name="message">Message.</param>
public TFException (string message) : base (message) { }
}
/// <summary>
/// Used to track the result of TensorFlow operations.
/// </summary>
/// <remarks>
/// <para>
/// TFStatus is used to track the status of a call to some TensorFlow
/// operations. Instances of this object are passed to various
/// TensorFlow operations and you can use the <see cref="P:TensorFlow.TFStatus.Ok"/>
/// to quickly check if the operation succeeded, or get more detail from the
/// <see cref="P:TensorFlow.TFStatus.StatusCode"/> and a human-readable text
/// using the <see cref="P:TensorFlow.TFStatus.StatusMessage"/> property.
/// </para>
/// <para>
/// The convenience <see cref="M:TensorFlow.TFStatus.Raise"/> can be used
/// to raise a <see cref="P:TensorFlow.TFException"/> if the status of the
/// operation did not succeed.
/// </para>
/// </remarks>
public class TFStatus : TFDisposable
{
// extern TF_Status * TF_NewStatus ();
[DllImport (NativeBinding.TensorFlowLibrary)]
internal static extern unsafe TF_Status TF_NewStatus ();
/// <summary>
/// Per-thread global status that you can use if you do not need to create a new instance of this object.
/// </summary>
/// <remarks>
/// This is provided as a convenience for APIs that take a TFStatus. While the TFStatus is usually an
/// optional parameter, when it is made optional, API calls that fail raise an exception. Use this
/// property to pass a TFStatus without having to allocate a new one. The problem with this of course
/// is that you risk having multiple parts of your code override this thread-global variable.
/// </remarks>
[ThreadStatic] public static TFStatus Default = new TFStatus ();
/// <summary>
/// Initializes a new instance of the <see cref="T:TensorFlow.TFStatus"/> class.
/// </summary>
public TFStatus() : base(TF_NewStatus())
{
}
// extern void TF_DeleteStatus (TF_Status *);
[DllImport(NativeBinding.TensorFlowLibrary)]
internal static extern unsafe void TF_DeleteStatus(TF_Status status);
internal override void NativeDispose(IntPtr handle)
{
TF_DeleteStatus(handle);
}
// extern void TF_SetStatus (TF_Status *s, TF_Code code, const char *msg);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe void TF_SetStatus(TF_Status s, TFCode code, string msg);
/// <summary>
/// Sets the status code on this TFStatus.
/// </summary>
/// <param name="code">Code.</param>
/// <param name="msg">Message.</param>
public void SetStatusCode(TFCode code, string msg)
{
TF_SetStatus(handle, code, msg);
}
// extern TF_Code TF_GetCode (const TF_Status *s);
[DllImport(NativeBinding.TensorFlowLibrary)]
internal static extern unsafe TFCode TF_GetCode(TF_Status s);
/// <summary>
/// Gets the status code for the status code.
/// </summary>
/// <value>The status code as an enumeration.</value>
public TFCode StatusCode
{
get
{
return TF_GetCode(handle);
}
}
// extern const char * TF_Message (const TF_Status *s);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe IntPtr TF_Message(TF_Status s);
/// <summary>
/// Gets a human-readable status message.
/// </summary>
/// <value>The status message.</value>
public string StatusMessage => TF_Message(handle).GetStr();
/// <summary>
/// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:TensorFlow.TFStatus"/>.
/// </summary>
/// <returns>A <see cref="T:System.String"/> that represents the current <see cref="T:TensorFlow.TFStatus"/>.</returns>
public override string ToString()
{
return string.Format("[TFStatus: StatusCode={0}, StatusMessage={1}]", StatusCode, StatusMessage);
}
/// <summary>
/// Gets a value indicating whether this <see cref="T:TensorFlow.TFStatus"/> state has been set to ok.
/// </summary>
/// <value><c>true</c> if ok; otherwise, <c>false</c>.</value>
public bool Ok => StatusCode == TFCode.Ok;
/// <summary>
/// Gets a value indicating whether this <see cref="T:TensorFlow.TFStatus"/> state has been set to an error.
/// </summary>
/// <value><c>true</c> if error; otherwise, <c>false</c>.</value>
public bool Error => StatusCode != TFCode.Ok;
/// <summary>
/// Convenience method that raises an exception if the current status is an error.
/// </summary>
/// <remarks>
/// You can use this method as a convenience to raise an exception after you
/// invoke an operation if the operation did not succeed.
/// </remarks>
public void Raise()
{
if (TF_GetCode(handle) != TFCode.Ok)
throw new TFException(StatusMessage);
}
//
// Utility function used to simplify implementing the idiom
// where the user optionally provides a TFStatus, if it is provided,
// the error is returned there; If it is not provided, then an
// exception is raised.
//
internal bool CheckMaybeRaise(TFStatus incomingStatus, bool last = true)
{
if (incomingStatus == null)
{
if (handle == IntPtr.Zero)
Debug.WriteLine("oops");
if (StatusCode != TFCode.Ok)
{
var e = new TFException(StatusMessage);
Dispose();
throw e;
}
if (last)
Dispose();
return true;
}
return StatusCode == TFCode.Ok;
}
internal static TFStatus Setup(TFStatus incoming)
{
return incoming == null ? new TFStatus() : incoming;
}
}
internal class TFString
{
// extern size_t TF_StringEncode (const char *src, size_t src_len, char *dst, size_t dst_len, TF_Status *status);
[DllImport(NativeBinding.TensorFlowLibrary)]
internal static extern unsafe size_t TF_StringEncode(byte* src, size_t src_len, sbyte* dst, size_t dst_len, TF_Status status);
// extern size_t TF_StringDecode (const char *src, size_t src_len, const char **dst, size_t *dst_len, TF_Status *status);
[DllImport(NativeBinding.TensorFlowLibrary)]
internal static extern unsafe size_t TF_StringDecode(sbyte* src, size_t src_len, sbyte** dst, size_t* dst_len, TF_Status status);
// extern size_t TF_StringEncodedSize (size_t len);
[DllImport(NativeBinding.TensorFlowLibrary)]
internal static extern size_t TF_StringEncodedSize(size_t len);
}
/// <summary>
/// The session options object holds configuration options that you want to use during your session, like the TensorFlow target or the configuration.
/// </summary>
public class TFSessionOptions : TFDisposable
{
// extern TF_SessionOptions * TF_NewSessionOptions ();
[DllImport (NativeBinding.TensorFlowLibrary)]
internal static extern unsafe TF_SessionOptions TF_NewSessionOptions ();
public TFSessionOptions() : base(TF_NewSessionOptions()) { }
// extern void TF_DeleteSessionOptions (TF_SessionOptions *);
[DllImport(NativeBinding.TensorFlowLibrary)]
internal static extern unsafe void TF_DeleteSessionOptions(TF_SessionOptions options);
internal override void NativeDispose(IntPtr handle)
{
TF_DeleteSessionOptions(handle);
}
// extern void TF_SetTarget (TF_SessionOptions *options, const char *target);
[DllImport (NativeBinding.TensorFlowLibrary)]
static extern unsafe void TF_SetTarget (TF_SessionOptions options, string target);
/// <summary>
/// Sets the target in options.
/// </summary>
/// <param name="target">target can be empty, a single entry, or a comma separated list of entries.
/// Each entry is in one of the following formats: "local", ip:port, host:port.</param>
///
public void SetTarget (string target)
{
if (handle == IntPtr.Zero)
ObjectDisposedException ();
TF_SetTarget (handle, target);
}
// extern void TF_SetConfig (TF_SessionOptions *options, const void *proto, size_t proto_len, TF_Status *status);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe void TF_SetConfig(TF_SessionOptions options, IntPtr proto, size_t proto_len, TF_Status status);
/// <summary>
/// Sets the configuration information for the session.
/// </summary>
/// <param name="protoData">Serialized protocol buffer for the tensorflow.ConfigProto message.</param>
/// <param name="length">Length of the buffer.</param>
/// <param name="status">If config was not parsed successfully as a ConfigProto, the error is recorded here.</param>
/// <remarks>
/// The configuration option is a Protocol Buffer representing the tensorflow.ConfigProto
/// </remarks>
public void SetConfig (IntPtr protoData, int length, TFStatus status = null)
{
if (handle == IntPtr.Zero)
ObjectDisposedException();
var cstatus = TFStatus.Setup(status);
TF_SetConfig(handle, protoData, (UIntPtr)length, cstatus.handle);
cstatus.CheckMaybeRaise(status);
}
}
/// <summary>
/// Represents a computation graph. Graphs may be shared between sessions and are thread safe.
/// </summary>
/// <remarks>
/// <para>
/// Graphs consist of operations (represented by TFOperation objects), these can be named, or
/// the runtime will automatically assign a name.
/// </para>
/// <para>
/// For debugging purposes, you might want to group operations together, for this, call the
/// WithScope method with your new scope, which will create a new namespace for your object names.
/// </para>
/// <para>
/// For example, if you call WithScope ("demo"), and add an operation named "add" inside the
/// scope, the full name of the operation will be "demo/add", if you create a new scope inside, say
/// "hot", and add a "sub" operation there the result will be "demo/hot/sub".
/// </para>
/// </remarks>
public partial class TFGraph : TFDisposable
{
// extern TF_Graph * TF_NewGraph ();
[DllImport (NativeBinding.TensorFlowLibrary)]
static extern unsafe TF_Graph TF_NewGraph ();
/// <summary>
/// Initializes a new instance of the <see cref="T:TensorFlow.TFGraph"/> class.
/// </summary>
public TFGraph() : base(TF_NewGraph())
{
}
internal TFGraph(IntPtr handle) : base(handle)
{
}
// extern void TF_DeleteGraph (TF_Graph *);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe void TF_DeleteGraph(TF_Graph graph);
internal override void NativeDispose(IntPtr handle)
{
TF_DeleteGraph(handle);
}
// extern void TF_GraphSetTensorShape (TF_Graph *graph, TF_Output output, const int64_t *dims, const int num_dims, TF_Status *status);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe void TF_GraphSetTensorShape(TF_Graph graph, TFOutput output, long[] dims, int num_dims, TF_Status status);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe void TF_GraphSetTensorShape(TF_Graph graph, TFOutput output, IntPtr dims, int num_dims, TF_Status status);
public void SetTensorShape(TFOutput output, long[] dims, TFStatus status = null)
{
if (handle == IntPtr.Zero)
ObjectDisposedException();
var cstatus = TFStatus.Setup(status);
if (dims == null)
TF_GraphSetTensorShape(handle, output, IntPtr.Zero, 0, cstatus.handle);
else
TF_GraphSetTensorShape(handle, output, dims, dims.Length, cstatus.handle);
cstatus.CheckMaybeRaise(status);
}
// extern int TF_GraphGetTensorNumDims (TF_Graph *graph, TF_Output output, TF_Status *status);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe int TF_GraphGetTensorNumDims(TF_Graph graph, TFOutput output, TF_Status status);
public int GetTensorNumDims(TFOutput output, TFStatus status = null)
{
if (handle == IntPtr.Zero)
ObjectDisposedException();
var cstatus = TFStatus.Setup(status);
var code = TF_GraphGetTensorNumDims(handle, output, cstatus.handle);
cstatus.CheckMaybeRaise(status);
return code;
}
// extern void TF_GraphGetTensorShape (TF_Graph *graph, TF_Output output, int64_t *dims, int num_dims, TF_Status *status);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe void TF_GraphGetTensorShape(TF_Graph graph, TFOutput output, long[] dims, int num_dims, TF_Status status);
public long[] GetTensorShape(TFOutput output, TFStatus status = null)
{
if (handle == IntPtr.Zero)
ObjectDisposedException();
var cstatus = TFStatus.Setup(status);
var n = TF_GraphGetTensorNumDims(handle, output, cstatus.handle);
if (!cstatus.CheckMaybeRaise(status, last: false))
return null;
var dims = new long[n];
TF_GraphGetTensorShape(handle, output, dims, dims.Length, cstatus.handle);
cstatus.CheckMaybeRaise(status);
return dims;
}
// extern void TF_GraphToGraphDef (TF_Graph *graph, TF_Buffer *output_graph_def, TF_Status *status);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe void TF_GraphToGraphDef(TF_Graph graph, LLBuffer* output_graph_def, TF_Status status);
public void ToGraphDef(TFBuffer outputGraphDef, TFStatus status = null)
{
if (handle == IntPtr.Zero)
ObjectDisposedException();
if (outputGraphDef == null)
throw new ArgumentNullException(nameof(outputGraphDef));
var cstatus = TFStatus.Setup(status);
unsafe
{
TF_GraphToGraphDef(handle, outputGraphDef.LLBuffer, cstatus.handle);
}
cstatus.CheckMaybeRaise(status);
}
// extern void TF_GraphImportGraphDef (TF_Graph *graph, const TF_Buffer *graph_def, const TF_ImportGraphDefOptions *options, TF_Status *status);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe void TF_GraphImportGraphDef(TF_Graph graph, LLBuffer* graph_def, TF_ImportGraphDefOptions options, TF_Status status);
/// <summary>
/// Import a serialized graph into this graph, using the specified prefix.
/// </summary>
/// <returns>The import.</returns>
/// <param name="graphDef">A buffer containing the serialized graph.</param>
/// <param name="prefix">A prefix that will be prepended to names of nodes in the <paramref name="graphDef"/> when they are imported into the graph.</param>
/// <param name="status">Status buffer.</param>
public void Import(TFBuffer graphDef, string prefix = "", TFStatus status = null)
{
if (handle == IntPtr.Zero)
ObjectDisposedException();
if (graphDef == null)
throw new ArgumentNullException(nameof(graphDef));
if (prefix == null)
throw new ArgumentNullException(nameof(prefix));
using (var options = new TFImportGraphDefOptions())
{
options.SetPrefix(prefix);
Import(graphDef, options, status);
}
}
/// <summary>
/// Import a serialized graph into this graph, using the specified importing options.
/// </summary>
/// <returns>The import.</returns>
/// <param name="graphDef">A buffer containing the serialized graph.</param>
/// <param name="options">Importing graph options.</param>
/// <param name="status">Status buffer.</param>
public void Import(TFBuffer graphDef, TFImportGraphDefOptions options, TFStatus status = null)
{
if (handle == IntPtr.Zero)
ObjectDisposedException();
if (graphDef == null)
throw new ArgumentNullException(nameof(graphDef));
if (options == null)
throw new ArgumentNullException(nameof(options));
var cstatus = TFStatus.Setup(status);
unsafe
{
TF_GraphImportGraphDef(handle, graphDef.LLBuffer, options.handle, cstatus.handle);
}
cstatus.CheckMaybeRaise(status, false);
}
/// <summary>
/// Import a serialized graph held in a byte array into this graph, using the specified prefix.
/// </summary>
/// <returns>The import.</returns>
/// <param name="buffer">A byte array containing the serialized graph.</param>
/// <param name="prefix">A prefix that will be prepended to names of nodes in the <paramref name="graphDef"/> when they are imported into the graph.</param>
/// <param name="status">Status buffer.</param>
public void Import(byte[] buffer, string prefix = "", TFStatus status = null)
{
if (handle == IntPtr.Zero)
ObjectDisposedException();
if (buffer == null)
throw new ArgumentNullException(nameof(buffer));
if (prefix == null)
throw new ArgumentNullException(nameof(prefix));
using (var options = new TFImportGraphDefOptions())
{
options.SetPrefix(prefix);
Import(buffer, options, status);
}
}
/// <summary>
/// Import a serialized graph held in a byte array into this graph, using the specified import options.
/// </summary>
/// <returns>The import.</returns>
/// <param name="buffer">A byte array containing the serialized graph.</param>
/// <param name="options">Importing graph options.</param>
/// <param name="status">Status buffer.</param>
public void Import(byte[] buffer, TFImportGraphDefOptions options, TFStatus status = null)
{
if (handle == IntPtr.Zero)
ObjectDisposedException();
if (buffer == null)
throw new ArgumentNullException(nameof(buffer));
if (options == null)
throw new ArgumentNullException(nameof(options));
var cstatus = TFStatus.Setup(status);
//ck
using (var tb = new TFBuffer(buffer, 0, buffer.Length))
{
Import(tb, options, status);
}
cstatus.CheckMaybeRaise(cstatus);
}
// extern TF_Operation * TF_GraphOperationByName (TF_Graph *graph, const char *oper_name);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe TF_Operation TF_GraphOperationByName(TF_Graph graph, string oper_name);
/// <summary>
/// Gets the <see cref="T:TensorFlow.TFGraph"/> with the specified name, or null if the named operation does not exist in the graph.
/// </summary>
/// <param name="name">Name to lookup.</param>
public TFOperation this[string name]
{
get
{
if (handle == IntPtr.Zero)
ObjectDisposedException();
var h = TF_GraphOperationByName(handle, name);
if (h == IntPtr.Zero)
return null;
return new TFOperation(this, h);
}
}
// extern TF_Operation * TF_GraphNextOperation (TF_Graph *graph, size_t *pos);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe TF_Operation TF_GraphNextOperation(TF_Graph graph, ref IntPtr token);
/// <summary>
/// Returns the enumerator that returns all the TFOperations in a graph.
/// </summary>
/// <returns>The enumerator.</returns>
public IEnumerable<TFOperation> GetEnumerator()
{
if (handle == IntPtr.Zero)
ObjectDisposedException();
IntPtr token = IntPtr.Zero;
IntPtr operll;
while ((operll = TF_GraphNextOperation(handle, ref token)) != IntPtr.Zero)
yield return new TFOperation(this, operll);
}
/// <summary>
/// Returns the tensor shape for the specific output pparameters as an array of longs.
/// </summary>
/// <returns>null for single dimension, .</returns>
/// <param name="output">The output operation to probe.</param>
/// <param name="status">Status.</param>
public long[] GetShape(TFOutput output, TFStatus status = null)
{
if (handle == IntPtr.Zero)
ObjectDisposedException();
var cstatus = TFStatus.Setup(status);
var ndims = TF_GraphGetTensorNumDims(handle, output, cstatus.handle);
if (!cstatus.CheckMaybeRaise(status, last: false))
return null;
if (ndims == 0)
return null;
var ret = new long[ndims];
TF_GraphGetTensorShape(handle, output, ret, ndims, cstatus.handle);
cstatus.CheckMaybeRaise(status);
return ret;
}
/// <summary>
/// Returns the current name scope in use, to change this, use the WithScope method.
/// </summary>
/// <value>The current name scope.</value>
public string CurrentNameScope { get; internal set; } = "";
/// <summary>
/// Creates a new namescope by setting the scope to the description provided.
/// </summary>
/// <returns>A new scope that will remain in use until the return TFScope is disposed.</returns>
/// <param name="nameScopeDesc">The namescope description, if the value is null, this
/// will reset the toplevel namescope to be the empty value. </param>
/// <remarks>
/// <para>
/// To more easily name your operations and group then, you can use the
/// WithScope method to set a current name scope that alter the complete name
/// of an operation added to the graph.
/// </para>
/// <para>
/// The graph starts with a scope set to the empty string, you can introduce new
/// scopes by calling WithScope, and can be conveniently used with the C# using
/// statement, like this:
/// </para>
/// <code>
/// Assert (graph.CurrentNamescope, "");
/// using (var nested = graph.WithScope ("nested")){
/// Assert (graph.CurrentNameScope, "nested");
/// using (var inner = graph.WithScope ("inner")){
/// Assert (graph.CurrentNameScope, "nested/inner");
/// }
/// }
/// </code>
/// </remarks>
public TFScope WithScope (string nameScopeDesc)
{
var scope = new TFScope (this);
if (scope == null)
CurrentNameScope = "";
else if (CurrentNameScope.Length == 0)
CurrentNameScope = nameScopeDesc;
else
CurrentNameScope = CurrentNameScope + "/" + nameScopeDesc;
return scope;
}
Dictionary<string, int> values = new Dictionary<string, int>();
string MakeName(string operName, string userName)
{
if (userName == null)
{
var k = CurrentNameScope == "" ? operName : CurrentNameScope + "/" + operName;
return MakeUnique(k);
}
if (CurrentNameScope == "")
return userName;
return CurrentNameScope + "/" + userName;
}
string MakeUnique(string name)
{
int val = 0;
if (!values.TryGetValue(name, out val))
val = 0;
else
val++;
values[name] = val;
return name + val;
}
internal int LastId;
internal int GetNextId()
{
return LastId++;
}
[DllImport(NativeBinding.TensorFlowLibrary)]
unsafe extern static void TF_GraphImportGraphDefWithReturnOutputs(
TF_Graph graph, LLBuffer* graph_def,
TF_ImportGraphDefOptions options, TFOutput* return_outputs,
int num_return_outputs, TF_Status status);
/// <summary>
/// Imports a graph serialized into the graph
/// </summary>
/// <param name="graphDef">Serialized graph definition (in protocol buffer format).</param>
/// <param name="options">Import options.</param>
/// <param name="returnOutputs">Array large enough to contain all the return options.</param>
/// <param name="status">Status, optional.</param>
public void ImportGraphDef(TFBuffer graphDef, TFImportGraphDefOptions options, TFOutput[] returnOutputs, TFStatus status = null)
{
if (handle == IntPtr.Zero)
ObjectDisposedException();
if (graphDef == null)
throw new ArgumentNullException(nameof(graphDef));
if (options == null)
throw new ArgumentNullException(nameof(options));
var cstatus = TFStatus.Setup(status);
unsafe
{
if (returnOutputs == null)
{
TF_GraphImportGraphDefWithReturnOutputs(handle, graphDef.LLBuffer, options.handle, null, 0, cstatus.handle);
}
else
{
fixed (TFOutput* first = &returnOutputs[0])
{
TF_GraphImportGraphDefWithReturnOutputs(handle, graphDef.LLBuffer, options.handle, first, returnOutputs.Length, cstatus.handle);
}
}
}
}
[StructLayout(LayoutKind.Sequential)]
unsafe struct TFWhileParams
{
public int ninputs;
public TF_Graph cond_graph;
public TFOutput* cond_inputs;
public TFOutput cond_output;
public TF_Graph body_graph;
public TFOutput* body_inputs;
public TFOutput* body_outputs;
public IntPtr charPtrName;
}
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe TFWhileParams TF_NewWhile(TF_Graph g, TFOutput[] inputs, int ninputs, TF_Status status);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern void TF_AbortWhile(ref TFWhileParams pars);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe void TF_FinishWhile(ref TFWhileParams pars, TF_Status status, TFOutput* outputs);
static unsafe TFOutput[] CopyFrom(TFOutput* ptr, int n)
{
var r = new TFOutput[n];
for (int i = 0; i < n; i++)
r[i] = ptr[i];
return r;
}
/// <summary>
/// Signature of the method that will be invoked by the TFGraph.While method to construct a while loop
/// </summary>
/// <remarks>
/// <para>
/// The method should build up the condition on the conditionGraph and the body of the while
/// loop in the provided bodyGraph. It should set the condOutput to the value used as the
/// condition output and the array of values in bodyOutputs to the final outputs as well as the
/// name to be used, if not set, one will be assigned.
/// </para>
/// <para>
/// The conditionGraph represents the while condition and the inputs are the current values of the
/// input variables (condInputs). The output should be a scalar boolean.
/// </para>
/// <para>
/// The loop body graph is in bodyGraph, The inputs are the current values of the loop
/// variables. The outputs are the updated values of the loop variables.
/// </para>
/// <para>
/// You can use the passed status record problems with it.
/// </para>
/// </remarks>
public delegate void WhileConstructor (TFGraph conditionGraph, TFOutput [] condInputs, out TFOutput condOutput, TFGraph bodyGraph, TFOutput [] bodyInputs, TFOutput [] bodyOutputs, out string name);
/// <summary>
/// Constructs a while loop with the specified inputs and a callback that composes the while loop
/// </summary>
/// <param name="inputs">Inputs.</param>
/// <param name="constructor">Callback method that fills out the various while loop parameters.</param>
/// <returns>
/// An array of TFOutputs from creating the While loop, or null if there is an error creating the
/// while loop, or if the constructor raised an exception when it was invoked.
/// </returns>
public TFOutput[] While(TFOutput[] inputs, WhileConstructor constructor, TFStatus status = null)
{
if (handle == IntPtr.Zero)
ObjectDisposedException();
if (inputs == null)
throw new ArgumentNullException(nameof(inputs));
if (constructor == null)
throw new ArgumentNullException(nameof(constructor));
var cstatus = TFStatus.Setup(status);
TFWhileParams result = TF_NewWhile(handle, inputs, inputs.Length, cstatus.handle);
if (cstatus.Error)
return null;
try
{
// Call constructor here
// Wrap the various TF_graphs (with owns=false)
// Marshal the condInputs, bodyInputs
string name;
int n = result.ninputs;
TFOutput[] bodyOutputs = new TFOutput[n];
unsafe
{
var condGraph = new TFGraphUnowned(result.cond_graph);
var bodyGraph = new TFGraphUnowned(result.body_graph);
constructor(condGraph, CopyFrom(result.cond_inputs, n), out result.cond_output, bodyGraph, CopyFrom(result.body_inputs, n), bodyOutputs, out name);
}
if (name == null || name == "")
name = MakeUnique("while");
// On return, copy the condOutput and bodyOututs
var text = Encoding.UTF8.GetBytes(name);
result.charPtrName = Marshal.AllocHGlobal(text.Length + 1);
Marshal.Copy(text, 0, result.charPtrName, text.Length);
Marshal.WriteByte(result.charPtrName, text.Length, 0);
unsafe
{
for (int i = 0; i < n; i++)
result.body_outputs[i] = bodyOutputs[i];
var ret = new TFOutput[inputs.Length];
fixed (TFOutput* first = &ret[0])
TF_FinishWhile(ref result, cstatus.handle, first);
if (cstatus.CheckMaybeRaise(status))
return ret;
}
return null;
}
catch
{
TF_AbortWhile(ref result);
return null;
}
}
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe void TF_AddGradients(TF_Graph graph, TFOutput* ys, int ny, TFOutput* xs, int nx, TFOutput* dx, TF_Status status, TFOutput* dy);
/// <summary>
/// Adds a gradient: the operations needed to compute the partial derivatives of sum of <paramref name="y"/>` wrt to <paramref name="x"/>.
/// </summary>
/// <returns>The partial derivatives, the size of the array is the same as the length of the <paramref name="y"/> array.</returns>
/// <param name="y">The y elements.</param>
/// <param name="x">The x elements.</param>
/// <param name="dx">Initial gradients, which represent the symbolic partial derivatives of some loss function `L` w.r.t. <paramref name="y"/> ).
/// If the parameter is null, the implementation will use dx for 'OnesLike' for all shapes in <paramref name="y"/></param>
/// <param name="status">Status.</param>
/// <remarks>
/// d(y[0] + y[1]+ ...)/dx[0], d(y[0] + y[1] + ...)/dx[1]z...
/// </remarks>
public TFOutput[] AddGradients(TFOutput[] y, TFOutput[] x, TFOutput[] dx = null, TFStatus status = null)
{
if (y == null)
throw new ArgumentNullException(nameof(y));
if (x == null)
throw new ArgumentNullException(nameof(x));
if (dx != null)
{
if (dx.Length != y.Length)
throw new ArgumentException("If dx is not null, the size of the gradients must match the size of y", nameof(dx));
}
var cstatus = TFStatus.Setup(status);
var ret = new TFOutput[x.Length];
unsafe
{
fixed (TFOutput* pret = &ret[0])
{
fixed (TFOutput* py = &y[0])
{
fixed (TFOutput* px = &x[0])
{
if (dx == null)
{
TF_AddGradients(handle, py, y.Length, px, x.Length, (TFOutput*)null, status.Handle, pret);
}
else
{
fixed (TFOutput* pdx = &dx[0])
{
TF_AddGradients(handle, py, y.Length, px, x.Length, pdx, status.Handle, pret);
}
}
}
}
}
}
if (!cstatus.CheckMaybeRaise(status, last: false))
return null;
return ret;
}
}
//
// A TFGraph that will not release the undelying handle, this is used
// when we want to surface a TFGraph that we do not own, so we do not
// want to delete the handle when this object is collected
//
internal class TFGraphUnowned : TFGraph
{
internal TFGraphUnowned(IntPtr handle) : base(handle)
{
}
internal override void NativeDispose(TF_Status handle)
{
// nothing, we do not own the handle
}
}
/// <summary>
/// TFGraph name scope handle
/// </summary>
/// <remarks>
/// Instances of this class when disposed restore the CurrentNameScope to the
/// value they had when the TFGraph.WithScope method was called.
/// </remarks>
public class TFScope : IDisposable
{
TFGraph container;
string name;
internal TFScope(TFGraph container)
{
this.container = container;
name = container.CurrentNameScope;
}
/// <summary>
/// Pops the name space to the previous namescope in use.
/// </summary>
/// <remarks>Call <see cref="Dispose"/> when you are finished using the <see cref="T:TensorFlow.TFScope"/>
/// to restore the previous name scope in use in the <see cref="T:TensorFlow.TFGraph"/>.
/// </remarks>
public void Dispose ()
{
container.CurrentNameScope = name;
}
}
/// <summary>
/// Low-level TensorFlow operation builder
/// </summary>
/// <remarks>
/// <para>This is the low-level API that is used to create operations by manually specificying all
/// the parameters of an operation (inputs, outputs, attribute descriptions) that can then
/// be attached into a graph.
/// </para>
/// <para>
/// Generally, you will instead be using the methods surfaced in <see cref="T:TensorFlow.TFGraph"/>
/// that surfaces a C# high-level API that has already been bound to the built-in TensorFlow
/// nodes.
/// </para>
/// <para>
/// You create instances bound to a graph, add inputs, attributes and so on, and when you are done
/// you can call the <see cref="FinishOperation"/> method that will turn this TFOperationDesc
/// into a <see cref="T:TensorFlow.TFOperation"/>.
/// </para>
/// </remarks>
public class TFOperationDesc : TFDisposable
{
string opType, operName;
TFGraph graph;
// extern TF_OperationDescription * TF_NewOperation (TF_Graph *graph, const char *op_type, const char *oper_name);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe TF_OperationDescription TF_NewOperation(TF_Graph graph, string opType, string oper_name);
public TFOperationDesc(TFGraph graph, string opType, string operName) : base(IntPtr.Zero)
{
if (graph == null)
throw new ArgumentNullException("graph");
handle = TF_NewOperation(graph.handle, opType, operName);
this.graph = graph;
this.opType = opType;
this.operName = operName;
}
internal override void NativeDispose(IntPtr handle)
{
// If you reach this, you never called FinishOperation
Debug.WriteLine($"TFOperationDescription({opType},{operName} was never turned into an TFOperation");
}
// extern void TF_SetDevice (TF_OperationDescription *desc, const char *device);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe void TF_SetDevice(TF_OperationDescription desc, string device);
public TFOperationDesc SetDevice(string device)
{
if (handle == IntPtr.Zero)
ObjectDisposedException();
if (device == null)
throw new ArgumentNullException("device");
TF_SetDevice(handle, device);
return this;
}
// extern void TF_AddInput (TF_OperationDescription *desc, TF_Output input);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe void TF_AddInput(TF_OperationDescription desc, TFOutput input);
/// <summary>
/// Adds the specified input to the operation
/// </summary>
/// <returns>The input.</returns>
/// <param name="input">Input.</param>
public TFOperationDesc AddInput(TFOutput input)
{
if (handle == IntPtr.Zero)
ObjectDisposedException();
TF_AddInput(handle, input);
return this;
}
// extern void TF_AddInputList (TF_OperationDescription *desc, const TF_Output *inputs, int num_inputs);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe void TF_AddInputList(TF_OperationDescription desc, TFOutput[] inputs, int num_inputs);
/// <summary>
/// Adds a series of inputs to the operation.
/// </summary>
/// <param name="inputs">Inputs, this is a params array for your convenience.</param>
public TFOperationDesc AddInputs(params TFOutput[] inputs)
{
if (handle == IntPtr.Zero)
ObjectDisposedException();
if (inputs == null || inputs.Length == 0)
return this;
TF_AddInputList(handle, inputs, inputs.Length);
return this;
}
// extern void TF_AddControlInput (TF_OperationDescription *desc, TF_Operation *input);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe void TF_AddControlInput(TF_OperationDescription desc, TF_Operation input);
/// <summary>
/// Ensure that the operation does not execute before the control operation does.
/// </summary>
/// <param name="control">Operation that must be executed before running this operation.</param>
/// <remarks>
/// <para>
/// A control input is an Operation that must be executed before running the operation
/// currently being built.
/// </para>
/// <para>
/// For example, an Assert operation may be added as a control input for this operation.
/// The Assert now behaves as a pre-condition that will always verify itself before
/// running the operation.
/// </para>
/// </remarks>
public TFOperationDesc AddControlInput (TFOperation control)
{
if (handle == IntPtr.Zero)
ObjectDisposedException ();
if (control == null)
throw new ArgumentNullException ("input");
TF_AddControlInput(handle, control.handle);
return this;
}
// extern void TF_ColocateWith (TF_OperationDescription *desc, TF_Operation *op);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe void TF_ColocateWith(TF_OperationDescription desc, TF_Operation op);
public TFOperationDesc ColocateWith(TFOperation op)
{
if (handle == IntPtr.Zero)
ObjectDisposedException();
if (op == null)
throw new ArgumentNullException("op");
TF_ColocateWith(handle, op.handle);
return this;
}
// extern void TF_SetAttrString (TF_OperationDescription *desc, const char *attr_name, const void *value, size_t length);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe void TF_SetAttrString(TF_OperationDescription desc, string attr_name, IntPtr value, size_t length);
public TFOperationDesc SetAttr(string attrName, string value)
{
if (handle == IntPtr.Zero)
ObjectDisposedException();
if (attrName == null)
throw new ArgumentNullException(nameof(attrName));
var bytes = Encoding.UTF8.GetBytes(value);
var buf = Marshal.AllocHGlobal(bytes.Length + 1);
Marshal.Copy(bytes, 0, buf, bytes.Length);
TF_SetAttrString(handle, attrName, buf, (UIntPtr)bytes.Length);
return this;
}
// extern void TF_SetAttrStringList (TF_OperationDescription *desc, const char *attr_name, const void *const *values, const size_t *lengths, int num_values);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe void TF_SetAttrStringList(TF_OperationDescription desc, string attr_name, IntPtr[] values, UIntPtr[] lengths, int num_values);
public TFOperationDesc SetAttr(string attrName, string[] values)
{
if (handle == IntPtr.Zero)
ObjectDisposedException();
if (attrName == null)
throw new ArgumentNullException(nameof(attrName));
if (values == null)
throw new ArgumentNullException(nameof(values));
int n = values.Length;
var unmanaged = new IntPtr[n];
var lenghts = new UIntPtr[n];
for (int i = 0; i < n; i++)
{
var bytes = Encoding.UTF8.GetBytes(values[i]);
var buf = Marshal.AllocHGlobal(bytes.Length + 1);
var bc = bytes.Length;
Marshal.Copy(bytes, 0, buf, bc);
unmanaged[i] = buf;
lenghts[i] = (size_t)bc;
}
TF_SetAttrStringList(handle, attrName, unmanaged, lenghts, n);
return this;
}
// extern void TF_SetAttrInt (TF_OperationDescription *desc, const char *attr_name, int64_t value);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe void TF_SetAttrInt(TF_OperationDescription desc, string attr_name, long value);
public TFOperationDesc SetAttr(string attrName, long value)
{
if (handle == IntPtr.Zero)
ObjectDisposedException();
if (attrName == null)
throw new ArgumentNullException(nameof(attrName));
TF_SetAttrInt(handle, attrName, value);
return this;
}
// extern void TF_SetAttrIntList (TF_OperationDescription *desc, const char *attr_name, const int64_t *values, int num_values);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe void TF_SetAttrIntList(TF_OperationDescription desc, string attr_name, long[] values, int num_values);
public TFOperationDesc SetAttr(string attrName, long[] values)
{
if (handle == IntPtr.Zero)
ObjectDisposedException();
if (attrName == null)
throw new ArgumentNullException(nameof(attrName));
if (values == null)
throw new ArgumentNullException(nameof(values));
TF_SetAttrIntList(handle, attrName, values, values.Length);
return this;
}
// extern void TF_SetAttrFloat (TF_OperationDescription *desc, const char *attr_name, float value);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe void TF_SetAttrFloat(TF_OperationDescription desc, string attr_name, float value);
public TFOperationDesc SetAttr(string attrName, float value)
{
if (handle == IntPtr.Zero)
ObjectDisposedException();
if (attrName == null)
throw new ArgumentNullException(nameof(attrName));
TF_SetAttrFloat(handle, attrName, value);
return this;
}
// extern void TF_SetAttrFloatList (TF_OperationDescription *desc, const char *attr_name, const float *values, int num_values);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe void TF_SetAttrFloatList(TF_OperationDescription desc, string attr_name, float[] values, int num_values);
public TFOperationDesc SetAttr(string attrName, float[] values)
{
if (handle == IntPtr.Zero)
ObjectDisposedException();
if (attrName == null)
throw new ArgumentNullException(nameof(attrName));
if (values == null)
throw new ArgumentNullException(nameof(values));
TF_SetAttrFloatList(handle, attrName, values, values.Length);
return this;
}
// extern void TF_SetAttrBool (TF_OperationDescription *desc, const char *attr_name, unsigned char value);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe void TF_SetAttrBool(TF_OperationDescription desc, string attr_name, byte value);
public TFOperationDesc SetAttr(string attrName, bool value)
{
if (handle == IntPtr.Zero)
ObjectDisposedException();
if (attrName == null)
throw new ArgumentNullException(nameof(attrName));
TF_SetAttrBool(handle, attrName, (byte)(value ? 1 : 0));
return this;
}
// extern void TF_SetAttrBoolList (TF_OperationDescription *desc, const char *attr_name, const unsigned char *values, int num_values);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe void TF_SetAttrBoolList(TF_OperationDescription desc, string attr_name, bool[] values, int num_values);
public TFOperationDesc SetAttr(string attrName, bool[] values)
{
if (handle == IntPtr.Zero)
ObjectDisposedException();
if (attrName == null)
throw new ArgumentNullException(nameof(attrName));
if (values == null)
throw new ArgumentNullException(nameof(values));
TF_SetAttrBoolList(handle, attrName, values, values.Length);
return this;
}
// extern void TF_SetAttrType (TF_OperationDescription *desc, const char *attr_name, TF_DataType value);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe void TF_SetAttrType(TF_OperationDescription desc, string attr_name, TFDataType value);
public TFOperationDesc SetAttrType(string attrName, TFDataType dataType)
{
if (handle == IntPtr.Zero)
ObjectDisposedException();
if (attrName == null)
throw new ArgumentNullException(nameof(attrName));
TF_SetAttrType(handle, attrName, dataType);
return this;
}
// extern void TF_SetAttrTypeList (TF_OperationDescription *desc, const char *attr_name, const TF_DataType *values, int num_values);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe void TF_SetAttrTypeList(TF_OperationDescription desc, string attr_name, TFDataType[] values, int num_values);
public TFOperationDesc SetAttrType(string attrName, params TFDataType[] dataType)
{
if (handle == IntPtr.Zero)
ObjectDisposedException();
if (attrName == null)
throw new ArgumentNullException(nameof(attrName));
if (dataType == null)
throw new ArgumentNullException(nameof(dataType));
TF_SetAttrTypeList(handle, attrName, dataType, dataType.Length);
return this;
}
// extern void TF_SetAttrShape (TF_OperationDescription *desc, const char *attr_name, const int64_t *dims, int num_dims);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe void TF_SetAttrShape(TF_OperationDescription desc, string attr_name, long[] dims, int num_dims);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe void TF_SetAttrShape(TF_OperationDescription desc, string attr_name, IntPtr dims, int num_dims);
public TFOperationDesc SetAttrShape(string attrName, TFShape shape)
{
if (handle == IntPtr.Zero)
ObjectDisposedException();
if (attrName == null)
throw new ArgumentNullException(nameof(attrName));
if (shape == null || shape.dims == null)
TF_SetAttrShape(handle, attrName, null, -1);
else
TF_SetAttrShape(handle, attrName, shape.dims, shape.dims.Length);
return this;
}
// extern void TF_SetAttrShapeList (TF_OperationDescription *desc, const char *attr_name, const int64_t *const *dims, const int *num_dims, int num_shapes);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe void TF_SetAttrShapeList(TF_OperationDescription desc, string attr_name, IntPtr dims, int[] num_dims, int num_shapes);
public TFOperationDesc SetAttrShape(string attrName, TFShape[] shapeList)
{
if (handle == IntPtr.Zero)
ObjectDisposedException();
if (attrName == null)
throw new ArgumentNullException(nameof(attrName));
if (shapeList == null)
throw new ArgumentNullException(nameof(shapeList));
int num_shapes = shapeList.Length;
var num_dims = new int[shapeList.Length];
unsafe
{
var unmanaged = Marshal.AllocHGlobal(sizeof(IntPtr) * num_shapes);
int ofs = 0;
for (int i = 0; i < num_shapes; i++)
{
IntPtr array = Marshal.AllocHGlobal(sizeof(long) * shapeList[i].dims.Length);
Marshal.Copy(shapeList[i].dims, 0, array, shapeList[i].dims.Length);
Marshal.WriteIntPtr(unmanaged, ofs, array);
ofs += sizeof(IntPtr);
}
TF_SetAttrShapeList(handle, attrName, unmanaged, num_dims, num_shapes);
ofs = 0;
for (int i = 0; i < num_shapes; i++)
{
var ptr = Marshal.ReadIntPtr(unmanaged, ofs);
Marshal.FreeHGlobal(ptr);
ofs += sizeof(IntPtr);
}
Marshal.FreeHGlobal(unmanaged);
}
return this;
}
// extern void TF_SetAttrTensorShapeProto (TF_OperationDescription *desc, const char *attr_name, const void *proto, size_t proto_len, TF_Status *status);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe void TF_SetAttrTensorShapeProto(TF_OperationDescription desc, string attr_name, IntPtr proto, size_t proto_len, TF_Status status);
public TFOperationDesc SetAttrTensorShapeProto(string attrName, IntPtr proto, size_t protoLen, TFStatus status = null)
{
if (handle == IntPtr.Zero)
ObjectDisposedException();
var cstatus = TFStatus.Setup(status);
TF_SetAttrTensorShapeProto(handle, attrName, proto, protoLen, cstatus.handle);
cstatus.CheckMaybeRaise(status);
return this;
}
// extern void TF_SetAttrTensorShapeProtoList (TF_OperationDescription *desc, const char *attr_name, const void *const *protos, const size_t *proto_lens, int num_shapes, TF_Status *status);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe void TF_SetAttrTensorShapeProtoList(TF_OperationDescription desc, string attr_name, void** protos, size_t* proto_lens, int num_shapes, TF_Status status);
// TODO:
// extern void TF_SetAttrTensor (TF_OperationDescription *desc, const char *attr_name, TF_Tensor *value, TF_Status *status);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe void TF_SetAttrTensor(TF_OperationDescription desc, string attr_name, TF_Tensor value, TF_Status status);
public TFOperationDesc SetAttr(string attrName, TFTensor tensor, TFStatus status = null)
{
if (handle == IntPtr.Zero)
ObjectDisposedException();
if (attrName == null)
throw new ArgumentNullException(nameof(attrName));
if (tensor == null)
throw new ArgumentNullException("tensor");
var cstatus = TFStatus.Setup(status);
TF_SetAttrTensor(handle, attrName, tensor.handle, cstatus.handle);
cstatus.CheckMaybeRaise(status);
return this;
}
// extern void TF_SetAttrTensorList (TF_OperationDescription *desc, const char *attr_name, TF_Tensor *const *values, int num_values, TF_Status *status);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe void TF_SetAttrTensorList(TF_OperationDescription desc, string attr_name, IntPtr[] values, int num_values, TF_Status status);
public TFOperationDesc SetAttr(string attrName, TFTensor[] tensor, TFStatus status = null)
{
if (handle == IntPtr.Zero)
ObjectDisposedException();
if (attrName == null)
throw new ArgumentNullException(nameof(attrName));
if (tensor == null)
throw new ArgumentNullException(nameof(tensor));
var cstatus = TFStatus.Setup(status);
var unmanaged = new IntPtr[tensor.Length];
for (int i = 0; i < tensor.Length; i++)
unmanaged[i] = tensor[i].handle;
TF_SetAttrTensorList(handle, attrName, unmanaged, unmanaged.Length, cstatus.handle);
cstatus.CheckMaybeRaise(status);
return this;
}
// extern void TF_SetAttrValueProto (TF_OperationDescription *desc, const char *attr_name, const void *proto, size_t proto_len, TF_Status *status);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe void TF_SetAttrValueProto(TF_OperationDescription desc, string attr_name, void* proto, size_t proto_len, TF_Status status);
// TODO:
// extern TF_Operation * TF_FinishOperation (TF_OperationDescription *desc, TF_Status *status);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe TF_Operation TF_FinishOperation(TF_OperationDescription desc, TF_Status status);
/// <summary>
/// Turns the operation description into an actual operation in the graph.
/// </summary>
/// <returns>The operation on success, or null on error.</returns>
/// <param name="status">Optional status, on failure the operation is not added to the graph. If you pass null (the default), this operation throws on error conditions.</param>
public TFOperation FinishOperation (TFStatus status = null)
{
if (handle == IntPtr.Zero)
ObjectDisposedException ();
var cstatus = TFStatus.Setup(status);
var h = TF_FinishOperation(handle, cstatus.handle);
cstatus.CheckMaybeRaise(status);
handle = IntPtr.Zero;
GC.SuppressFinalize(this);
if (status != null && status.Error)
return null;
return new TFOperation(graph, h);
}
}
/// <summary>
/// Represents a computation node in the graph. Tensorflow operations are attached to a <see cref="T:Tensorflow.TFGraph"/>.
/// </summary>
/// <remarks>
/// TFOperations are usually created by invoking one of the methods in
/// <see cref="T:Tensorflow.TFGraph"/>, but they can also be constructed
/// manually using the low-level <see cref="T:Tensorflow.TFOperationDesc"/> API.
/// </remarks>
public partial class TFOperation
{
internal IntPtr handle;
/// <summary>
/// Gets the handle to the unmanaged TF_Operation object.
/// </summary>
/// <value>The handle.</value>
public IntPtr Handle => handle;
// Pointer to the graph, to keep it from collecting if there are TFOperations alive.
internal TFGraph graph;
internal TFOperation(TFGraph graph, IntPtr handle)
{
this.handle = handle;
this.graph = graph;
}
// extern const char * TF_OperationName (TF_Operation *oper);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe IntPtr TF_OperationName(TF_Operation oper);
/// <summary>
/// The name for this operation/
/// </summary>
/// <value>The name.</value>
public string Name => handle == IntPtr.Zero ? "<ObjectDisposed>" : TF_OperationName(handle).GetStr();
// extern const char * TF_OperationOpType (TF_Operation *oper);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe IntPtr TF_OperationOpType(TF_Operation oper);
public string OpType => handle == IntPtr.Zero ? "<ObjectDisposedException>" : TF_OperationOpType(handle).GetStr();
// extern const char * TF_OperationDevice (TF_Operation *oper);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe IntPtr TF_OperationDevice(TF_Operation oper);
// public string Device => TF_OperationDevice (handle).GetStr ();
// extern int TF_OperationNumOutputs (TF_Operation *oper);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe int TF_OperationNumOutputs(TF_Operation oper);
/// <summary>
/// Gets the number of outputs on this operation.
/// </summary>
/// <value>The number outputs.</value>
public int NumOutputs => handle == IntPtr.Zero ? -1 : TF_OperationNumOutputs(handle);
// extern int TF_OperationOutputListLength (TF_Operation *oper, const char *arg_name, TF_Status *status);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe int TF_OperationOutputListLength(TF_Operation oper, string arg_name, TF_Status status);
public int OutputListLength(string argName, TFStatus status = null)
{
if (handle == IntPtr.Zero)
TFDisposable.ObjectDisposedException();
var cstatus = TFStatus.Setup(status);
var res = TF_OperationOutputListLength(handle, argName, cstatus.handle);
cstatus.CheckMaybeRaise(status);
return res;
}
// extern int TF_OperationNumInputs (TF_Operation *oper);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe int TF_OperationNumInputs(TF_Operation oper);
/// <summary>
/// Gets the number of inputs for this operation.
/// </summary>
/// <value>The number inputs.</value>
public int NumInputs => TF_OperationNumInputs(handle);
// extern int TF_OperationInputListLength (TF_Operation *oper, const char *arg_name, TF_Status *status);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe int TF_OperationInputListLength(TF_Operation oper, string arg_name, TF_Status status);
public int InputListLength(string argName, TFStatus status = null)
{
if (handle == IntPtr.Zero)
TFDisposable.ObjectDisposedException();
var cstatus = TFStatus.Setup(status);
var res = TF_OperationInputListLength(handle, argName, cstatus.handle);
cstatus.CheckMaybeRaise(status);
return res;
}
// extern int TF_OperationNumControlInputs (TF_Operation *oper);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe int TF_OperationNumControlInputs(TF_Operation oper);
public int NumControlInputs => TF_OperationNumControlInputs(handle);
// extern int TF_OperationGetControlInputs (TF_Operation *oper, TF_Operation **control_inputs, int max_control_inputs);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe int TF_OperationGetControlInputs(TF_Operation oper, TF_Operation control_inputs, int max_control_inputs);
// extern int TF_OperationNumControlOutputs (TF_Operation *oper);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe int TF_OperationNumControlOutputs(TF_Operation oper);
public int NumControlOutputs => TF_OperationNumControlOutputs(handle);
// extern int TF_OperationGetControlOutputs (TF_Operation *oper, TF_Operation **control_outputs, int max_control_outputs);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe int TF_OperationGetControlOutputs(TF_Operation oper, [Out] [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] IntPtr[] control_outputs, int max_control_outputs);
TFOperation[] ControlOutputs
{
get
{
var n = NumControlOutputs;
var arr = new IntPtr[n];
TF_OperationGetControlOutputs(handle, arr, n);
var ret = new TFOperation[n];
for (int i = 0; i < n; i++)
ret[i] = new TFOperation(graph, arr[i]);
return ret;
}
}
// extern TF_AttrMetadata TF_OperationGetAttrMetadata (TF_Operation *oper, const char *attr_name, TF_Status *status);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe TFAttributeMetadata TF_OperationGetAttrMetadata(TF_Operation oper, string attr_name, TF_Status status);
public TFAttributeMetadata GetAttributeMetadata(string attrName, TFStatus status = null)
{
if (handle == IntPtr.Zero)
TFDisposable.ObjectDisposedException();
var cstatus = TFStatus.Setup(status);
var x = TF_OperationGetAttrMetadata(handle, attrName, cstatus.handle);
cstatus.CheckMaybeRaise(status);
return x;
}
// extern void TF_OperationGetAttrString (TF_Operation *oper, const char *attr_name, void *value, size_t max_length, TF_Status *status);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe void TF_OperationGetAttrString(TF_Operation oper, string attr_name, void* value, size_t max_length, TF_Status status);
// TODO:
// extern void TF_OperationGetAttrStringList (TF_Operation *oper, const char *attr_name, void **values, size_t *lengths, int max_values, void *storage, size_t storage_size, TF_Status *status);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe void TF_OperationGetAttrStringList(TF_Operation oper, string attr_name, void** values, size_t* lengths, int max_values, void* storage, size_t storage_size, TF_Status status);
// TODO:
// extern void TF_OperationGetAttrInt (TF_Operation *oper, const char *attr_name, int64_t *value, TF_Status *status);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe void TF_OperationGetAttrInt(TF_Operation oper, string attr_name, long* value, TF_Status status);
// TODO:
// extern void TF_OperationGetAttrIntList (TF_Operation *oper, const char *attr_name, int64_t *values, int max_values, TF_Status *status);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe void TF_OperationGetAttrIntList(TF_Operation oper, string attr_name, long* values, int max_values, TF_Status status);
// TODO:
// extern void TF_OperationGetAttrFloat (TF_Operation *oper, const char *attr_name, float *value, TF_Status *status);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe void TF_OperationGetAttrFloat(TF_Operation oper, string attr_name, float* value, TF_Status status);
// TODO:
// extern void TF_OperationGetAttrFloatList (TF_Operation *oper, const char *attr_name, float *values, int max_values, TF_Status *status);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe void TF_OperationGetAttrFloatList(TF_Operation oper, string attr_name, float* values, int max_values, TF_Status status);
// TODO:
// extern void TF_OperationGetAttrBool (TF_Operation *oper, const char *attr_name, unsigned char *value, TF_Status *status);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe void TF_OperationGetAttrBool(TF_Operation oper, string attr_name, byte* value, TF_Status status);
// TODO:
// extern void TF_OperationGetAttrBoolList (TF_Operation *oper, const char *attr_name, unsigned char *values, int max_values, TF_Status *status);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe void TF_OperationGetAttrBoolList(TF_Operation oper, string attr_name, byte* values, int max_values, TF_Status status);
// TODO:
// extern void TF_OperationGetAttrType (TF_Operation *oper, const char *attr_name, TF_DataType *value, TF_Status *status);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe void TF_OperationGetAttrType(TF_Operation oper, string attr_name, TFDataType* value, TF_Status status);
// TODO:
// extern void TF_OperationGetAttrTypeList (TF_Operation *oper, const char *attr_name, TF_DataType *values, int max_values, TF_Status *status);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe void TF_OperationGetAttrTypeList(TF_Operation oper, string attr_name, TFDataType* values, int max_values, TF_Status status);
// TODO:
// extern void TF_OperationGetAttrShape (TF_Operation *oper, const char *attr_name, int64_t *value, int num_dims, TF_Status *status);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe void TF_OperationGetAttrShape(TF_Operation oper, string attr_name, long* value, int num_dims, TF_Status status);
// TODO:
// extern void TF_OperationGetAttrShapeList (TF_Operation *oper, const char *attr_name, int64_t **dims, int *num_dims, int num_shapes, int64_t *storage, int storage_size, TF_Status *status);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe void TF_OperationGetAttrShapeList(TF_Operation oper, string attr_name, long** dims, int* num_dims, int num_shapes, long* storage, int storage_size, TF_Status status);
// TODO:
// extern void TF_OperationGetAttrTensorShapeProto (TF_Operation *oper, const char *attr_name, TF_Buffer *value, TF_Status *status);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe void TF_OperationGetAttrTensorShapeProto(TF_Operation oper, string attr_name, LLBuffer* value, TF_Status status);
// TODO:
// extern void TF_OperationGetAttrTensorShapeProtoList (TF_Operation *oper, const char *attr_name, TF_Buffer **values, int max_values, TF_Status *status);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe void TF_OperationGetAttrTensorShapeProtoList(TF_Operation oper, string attr_name, LLBuffer** values, int max_values, TF_Status status);
// TODO:
// extern void TF_OperationGetAttrTensor (TF_Operation *oper, const char *attr_name, TF_Tensor **value, TF_Status *status);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe void TF_OperationGetAttrTensor(TF_Operation oper, string attr_name, TF_Tensor* value, TF_Status status);
// TODO:
// extern void TF_OperationGetAttrTensorList (TF_Operation *oper, const char *attr_name, TF_Tensor **values, int max_values, TF_Status *status);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe void TF_OperationGetAttrTensorList(TF_Operation oper, string attr_name, TF_Tensor* values, int max_values, TF_Status status);
// TODO:
// extern void TF_OperationGetAttrValueProto (TF_Operation *oper, const char *attr_name, TF_Buffer *output_attr_value, TF_Status *status);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe void TF_OperationGetAttrValueProto(TF_Operation oper, string attr_name, LLBuffer* output_attr_value, TF_Status status);
// TODO:
// extern void TF_OperationToNodeDef (TF_Operation *oper, TF_Buffer *output_node_def, TF_Status *status);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe void TF_OperationToNodeDef(TF_Operation oper, LLBuffer* output_node_def, TF_Status status);
/// <summary>
/// Encodes the TFOperation as a protocol buffer payload
/// </summary>
/// <returns>The buffer with the encoded operation in the protocol buffer format.</returns>
/// <param name="status">Status.</param>
/// <remarks>
/// </remarks>
public TFBuffer ToNodeDef(TFStatus status = null)
{
if (handle == IntPtr.Zero)
TFDisposable.ObjectDisposedException();
var cstatus = TFStatus.Setup(status);
var r = new TFBuffer();
unsafe
{
TF_OperationToNodeDef(handle, r.LLBuffer, cstatus.handle);
}
// No need to raise, we can return null in that case.
if (!cstatus.Ok)
{
r.Dispose();
return null;
}
return r;
}
/// <summary>
/// Returns the handle to the idx-th output of the operation.
/// </summary>
/// <param name="idx">Index of the output in the operation.</param>
public TFOutput this[int idx]
{
get
{
return new TFOutput(this, idx);
}
}
}
/// <summary>
/// Contains options that are used to control how graph importing works.
/// </summary>
public class TFImportGraphDefOptions : TFDisposable
{
// extern TF_ImportGraphDefOptions * TF_NewImportGraphDefOptions ();
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe TF_ImportGraphDefOptions TF_NewImportGraphDefOptions();
public TFImportGraphDefOptions() : base(TF_NewImportGraphDefOptions())
{
}
// extern void TF_DeleteImportGraphDefOptions (TF_ImportGraphDefOptions *opts);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe void TF_DeleteImportGraphDefOptions(TF_ImportGraphDefOptions opts);
internal override void NativeDispose(IntPtr handle)
{
TF_DeleteImportGraphDefOptions(handle);
}
// extern void TF_ImportGraphDefOptionsSetPrefix (TF_ImportGraphDefOptions *opts, const char *prefix);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe void TF_ImportGraphDefOptionsSetPrefix(TF_ImportGraphDefOptions opts, string prefix);
public void SetPrefix(string prefix)
{
if (handle == IntPtr.Zero)
ObjectDisposedException();
TF_ImportGraphDefOptionsSetPrefix(handle, prefix);
}
// extern void TF_ImportGraphDefOptionsAddInputMapping (TF_ImportGraphDefOptions *opts, const char* src_name, int src_index, TF_Output dst);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe void TF_ImportGraphDefOptionsAddInputMapping(TF_ImportGraphDefOptions opts, string src_name, int src_index, TFOutput dst);
/// <summary>
/// Adds an input mapping from a source name and index to a destination output
/// </summary>
/// <param name="srcName">Source name.</param>
/// <param name="srcIndex">Source index (in the source).</param>
/// <param name="dst">Replacement value for the srcName:srcIndex.</param>
/// <remarks>
/// Set any imported nodes with input `src_name:src_index` to have that input
/// replaced with `dst`. `src_name` refers to a node in the graph to be imported,
/// `dst` references a node already existing in the graph being imported into.
/// </remarks>
public void AddInputMapping(string srcName, int srcIndex, TFOutput dst)
{
if (handle == IntPtr.Zero)
ObjectDisposedException();
TF_ImportGraphDefOptionsAddInputMapping(handle, srcName, srcIndex, dst);
}
[DllImport(NativeBinding.TensorFlowLibrary)]
extern static void TF_ImportGraphDefOptionsAddControlDependency(TF_ImportGraphDefOptions opts, TF_Operation oper);
/// <summary>
/// Cause the imported graph to have a control dependency on the provided operation.
/// </summary>
/// <param name="operation">This operation should exist in the graph being imported to.</param>
public void AddControlDependency(TFOperation operation)
{
if (operation == null)
throw new ArgumentNullException(nameof(operation));
if (handle == IntPtr.Zero)
ObjectDisposedException();
TF_ImportGraphDefOptionsAddControlDependency(handle, operation.handle);
}
[DllImport(NativeBinding.TensorFlowLibrary)]
extern static void TF_ImportGraphDefOptionsAddReturnOutput(TF_ImportGraphDefOptions opts, string oper_name, int index);
/// <summary>
/// Add an output in the graph definition to be returned via the return outputs parameter.
/// </summary>
/// <param name="operName">Operation name.</param>
/// <param name="index">Operation index.</param>
/// <remarks>
/// If the output is remapped via an input
/// mapping, the corresponding existing tensor in graph will be returned.
/// </remarks>
public void AddReturnOutput(string operName, int index)
{
if (operName == null)
throw new ArgumentNullException(nameof(operName));
if (handle == IntPtr.Zero)
ObjectDisposedException();
TF_ImportGraphDefOptionsAddReturnOutput(handle, operName, index);
}
[DllImport(NativeBinding.TensorFlowLibrary)]
extern static int TF_ImportGraphDefOptionsNumReturnOutputs(TF_ImportGraphDefOptions opts);
/// <summary>
/// Gets the number return outputs added via AddReturnOutput.
/// </summary>
/// <value>The number return outputs.</value>
public int NumReturnOutputs
{
get
{
if (handle == IntPtr.Zero)
ObjectDisposedException();
return TF_ImportGraphDefOptionsNumReturnOutputs(handle);
}
}
[DllImport(NativeBinding.TensorFlowLibrary)]
extern static void TF_ImportGraphDefOptionsRemapControlDependency(TF_ImportGraphDefOptions opts, string srcName, TF_Operation dst);
/// <summary>
/// Sets any imported nodes with a given control input to have it replaced with an operation
/// </summary>
/// <param name="srcName">Node in the graph to be imported.</param>
/// <param name="destination">References an operation that already exists in the graph being imported.</param>
/// <remarks>
/// Set any imported nodes with control input <paramref name="srcName"/> to have that input
/// replaced with <paramref name="destination"/>.
/// </remarks>
public void RemapControlDependency (string srcName, TFOperation destination)
{
if (srcName == null)
throw new ArgumentNullException (nameof (srcName));
if (destination == null)
throw new ArgumentNullException (nameof (destination));
if (destination.Handle == IntPtr.Zero)
throw new ObjectDisposedException (nameof (destination));
TF_ImportGraphDefOptionsRemapControlDependency (handle, srcName, destination.Handle);
}
}
/// <summary>
/// Drives the execution of a graph
/// </summary>
/// <remarks>
/// <para>
/// This creates a new context to execute a TFGraph. You can use the
/// constructor to create an empty session, or you can load an existing
/// model using the <see cref="FromSavedModel"/> static method in this class.
/// </para>
/// <para>
/// To execute operations with the graph, call the <see cref="GetRunner"/> method
/// which returns an object that you can use to build the operation by providing
/// the inputs, requesting the operations that you want to execute and the desired outputs.
/// </para>
/// <para>
/// The <see cref="GetRunner"/> method is a high-level helper function that wraps a
/// call to the <see cref="Run"/> method which just takes too many parameters that must
/// be kept in sync.
/// </para>
/// </remarks>
public class TFSession : TFDisposable
{
// extern TF_Session * TF_NewSession (TF_Graph *graph, const TF_SessionOptions *opts, TF_Status *status);
[DllImport (NativeBinding.TensorFlowLibrary)]
static extern unsafe TF_Session TF_NewSession (TF_Graph graph, TF_SessionOptions opts, TF_Status status);
public TFGraph Graph { get; private set; }
TFSession(IntPtr handle, TFGraph graph) : base(handle)
{
Graph = graph;
}
public TFSession(TFGraph graph, TFSessionOptions sessionOptions, TFStatus status = null) : base(IntPtr.Zero)
{
Graph = graph;
var cstatus = TFStatus.Setup(status);
var h = TF_NewSession(graph.handle, sessionOptions.handle, cstatus.handle);
cstatus.CheckMaybeRaise(status);
handle = h;
}
public TFSession(TFGraph graph, TFStatus status = null) : base(IntPtr.Zero)
{
Graph = graph;
var cstatus = TFStatus.Setup(status);
var empty = TFSessionOptions.TF_NewSessionOptions();
var h = TF_NewSession(graph.handle, empty, cstatus.handle);
TFSessionOptions.TF_DeleteSessionOptions(empty);
cstatus.CheckMaybeRaise(status);
handle = h;
}
public TFSession(TFStatus status = null) : this(new TFGraph(), status)
{
}
// extern TF_Session * TF_LoadSessionFromSavedModel (const TF_SessionOptions *session_options, const TF_Buffer *run_options, const char *export_dir, const char *const *tags, int tags_len, TF_Graph *graph, TF_Buffer *meta_graph_def, TF_Status *status);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe TF_Session TF_LoadSessionFromSavedModel(TF_SessionOptions session_options, LLBuffer* run_options, string export_dir, string[] tags, int tags_len, TF_Graph graph, LLBuffer* meta_graph_def, TF_Status status);
public TFSession FromSavedModel(TFSessionOptions sessionOptions, TFBuffer runOptions, string exportDir, string[] tags, TFGraph graph, TFBuffer metaGraphDef, TFStatus status = null)
{
if (graph == null)
throw new ArgumentNullException(nameof(graph));
if (tags == null)
throw new ArgumentNullException(nameof(tags));
if (exportDir == null)
throw new ArgumentNullException(nameof(exportDir));
if (runOptions == null)
throw new ArgumentNullException(nameof(runOptions));
if (metaGraphDef == null)
throw new ArgumentNullException(nameof(metaGraphDef));
var cstatus = TFStatus.Setup(status);
unsafe
{
var h = TF_LoadSessionFromSavedModel(sessionOptions.handle, runOptions.LLBuffer, exportDir, tags, tags.Length, graph.handle, metaGraphDef.LLBuffer, cstatus.handle);
if (cstatus.CheckMaybeRaise(status))
{
return new TFSession(h, graph);
}
}
return null;
}
// extern void TF_CloseSession (TF_Session *, TF_Status *status);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe void TF_CloseSession(TF_Session session, TF_Status status);
public void CloseSession(TFStatus status = null)
{
if (handle == IntPtr.Zero)
ObjectDisposedException();
var cstatus = TFStatus.Setup(status);
TF_CloseSession(handle, cstatus.handle);
cstatus.CheckMaybeRaise(status);
}
// extern void TF_DeleteSession (TF_Session *, TF_Status *status);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe void TF_DeleteSession(TF_Session session, TF_Status status);
public void DeleteSession(TFStatus status = null)
{
if (handle == IntPtr.Zero)
ObjectDisposedException();
var cstatus = TFStatus.Setup(status);
TF_DeleteSession(handle, cstatus.handle);
cstatus.CheckMaybeRaise(status);
}
internal override void NativeDispose(IntPtr handle)
{
using (var s = new TFStatus())
{
TF_DeleteSession(handle, s.handle);
}
}
// extern void TF_SessionRun (TF_Session *session, const TF_Buffer *run_options, const TF_Output *inputs, TF_Tensor *const *input_values, int ninputs, const TF_Output *outputs, TF_Tensor **output_values, int noutputs, const TF_Operation *const *target_opers, int ntargets, TF_Buffer *run_metadata, TF_Status *);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe void TF_SessionRun(TF_Session session, LLBuffer* run_options, TFOutput[] inputs, TF_Tensor[] input_values, int ninputs, TFOutput[] outputs, TF_Tensor[] output_values, int noutputs, TF_Operation[] target_opers, int ntargets, LLBuffer* run_metadata, TF_Status status);
/// <summary>
/// Use the runner class to easily configure inputs, outputs and targets to be passed to the session runner.
/// </summary>
/// <remarks>
/// <para>
/// The runner has a simple API that allows developers to call the AddTarget, AddInput, AddOutput and Fetch
/// to construct the parameters that will be passed to the TFSession.Run method.
/// </para>
/// <para>
/// Instances of this class are created by calling the GetRunner method on the TFSession.
/// </para>
/// <para>
/// The various methods in this class return an instance to the Runner itsel, to allow
/// to easily construct chains of execution like this:
/// </para>
/// <code>
/// var result = session.GetRunner ().AddINput (myInput).Fetch (MyOutput).Run ();
/// </code>
/// <para>
/// You do not need to chain the operations, this works just the same:
/// </para>
/// <code>
/// runner = session.GetRunner ();
/// runner.AddInput(myInput);
/// runner.Fetch(myOutput);
/// var results = runner.Run();
/// </code>
/// </remarks>
public class Runner
{
List<TFOutput> inputs = new List<TFOutput> (), outputs = new List<TFOutput> ();
List<TFTensor> inputValues = new List<TFTensor> ();
List<TFOperation> targets = new List<TFOperation> ();
TFSession session;
internal Runner(TFSession session)
{
this.session = session;
}
/// <summary>
/// Adds an input to the session
/// </summary>
/// <returns>An instance to the runner, so you can easily chain the operations together.</returns>
/// <param name="input">Incoming port.</param>
/// <param name="value">Value to assing to the incoming port.</param>
public Runner AddInput(TFOutput input, TFTensor value)
{
if (value == null)
throw new ArgumentNullException(nameof(value));
inputs.Add(input);
inputValues.Add(value);
return this;
}
/// <summary>
/// Adds an input to the session specified by name, with an optional index in the operation (separated by a colon).
/// </summary>
/// <returns>An instance to the runner, so you can easily chain the operations together.</returns>
/// <param name="input">Incoming port, with an optional index separated by a colon.</param>
/// <param name="value">Value to assing to the incoming port.</param>
public Runner AddInput(string input, TFTensor value)
{
if (value == null)
throw new ArgumentNullException(nameof(value));
inputs.Add(ParseOutput(input));
inputValues.Add(value);
return this;
}
/// <summary>
/// Adds the specified operations as the ones to be retrieved.
/// </summary>
/// <returns>An instance to the runner, so you can easily chain the operations together.</returns>
/// <param name="targets">One or more targets.</param>
public Runner AddTarget(params TFOperation[] targets)
{
foreach (var t in targets)
this.targets.Add(t);
return this;
}
// Parses user strings that contain both the operation name and an index.
TFOutput ParseOutput(string operation)
{
var p = operation.IndexOf(':');
if (p != -1 && p != operation.Length - 1)
{
var op = operation.Substring(0, p);
if (int.TryParse(operation.Substring(p + 1), out var idx))
{
return session.Graph[op][idx];
}
}
return session.Graph[operation][0];
}
/// <summary>
/// Adds the specified operation names as the ones to be retrieved.
/// </summary>
/// <returns>An instance to the runner, so you can easily chain the operations together.</returns>
/// <param name="targets">One or more target names.</param>
public Runner AddTarget(params string[] targetNames)
{
foreach (var tn in targetNames)
this.targets.Add(session.Graph[tn]);
return this;
}
/// <summary>
/// Makes the Run method return the index-th output of the tensor referenced by operation.
/// </summary>
/// <returns>The instance of runner, to allow chaining operations.</returns>
/// <param name="operation">The name of the operation in the graph.</param>
/// <param name="index">The index of the output in the operation.</param>
public Runner Fetch(string operation, int index)
{
var op = session.Graph[operation];
outputs.Add(op[index]);
return this;
}
/// <summary>
/// Makes the Run method return the output of the tensor referenced by operation, the operation string can contain the output index.
/// </summary>
/// <returns>The instance of runner, to allow chaining operations.</returns>
/// <param name="operation">The name of the operation in the graph, which might be a simple name, or it might be name:index,
/// where the index is the .</param>
/// <param name="index">The index of the output in the operation.</param>
public Runner Fetch(string operation)
{
var op = ParseOutput(operation);
outputs.Add(op);
return this;
}
/// <summary>
/// Makes the Run method return the output of the tensor referenced by output
/// </summary>
/// <returns>The instance of runner, to allow chaining operations.</returns>
/// <param name="output">The output referencing a specified tensor.</param>
public Runner Fetch(TFOutput output)
{
outputs.Add(output);
return this;
}
/// <summary>
/// Makes the Run method return the output of all the tensor referenced by outputs.
/// </summary>
/// <returns>The instance of runner, to allow chaining operations.</returns>
/// <param name="outputs">The outputs referencing a specified tensor.</param>
public Runner Fetch (params TFOutput [] outputs)
{
foreach (var output in outputs)
this.outputs.Add (output);
return this;
}
/// <summary>
/// Makes the Run method return the output of all the tensor referenced by outputs.
/// </summary>
/// <returns>The instance of runner, to allow chaining operations.</returns>
/// <param name="outputs">The output sreferencing a specified tensor.</param>
public Runner Fetch (params string [] outputs)
{
foreach (var output in outputs)
this.outputs.Add (ParseOutput (output));
return this;
}
/// <summary>
/// Protocol buffer encoded block containing the metadata passed to the <see cref="M:TensorFlow.TFSession.Run"/> method.
/// </summary>
public TFBuffer RunMetadata;
/// <summary>
/// Protocol buffer encoded block containing the run options passed to the <see cref="M:TensorFlow.TFSession.Run"/> method.
/// </summary>
public TFBuffer RunOptions;
/// <summary>
/// Execute the graph fragments necessary to compute all requested fetches.
/// </summary>
/// <returns>One TFTensor for each call to Fetch that you made, in the order that you made them.</returns>
/// <param name="status">Status.</param>
public TFTensor[] Run(TFStatus status = null)
{
return session.Run(inputs.ToArray(), inputValues.ToArray(), outputs.ToArray(), targets.ToArray(), RunMetadata, RunOptions, status);
}
/// <summary>
/// Run the specified operation, by adding it implicity to the output, single return value
/// </summary>
/// <param name="operation">The output of the operation.</param>
/// <param name="status">Optional, status.</param>
/// <remarks>
/// This method is a convenience method, and when you call it, it will clear any
/// calls that you might have done to Fetch() and use the specified operation to Fetch
/// instead.
/// </remarks>
public TFTensor Run(TFOutput operation, TFStatus status = null)
{
outputs.Clear();
Fetch(operation);
return Run(status)[0];
}
}
/// <summary>
/// Gets a new runner, this provides a simpler API to prepare the inputs to run on a session
/// </summary>
/// <returns>The runner.</returns>
/// <remarks>
/// The runner has a simple API that allows developers to call the AddTarget, AddInput, AddOutput and Fetch
/// to construct the parameters that will be passed to the TFSession.Run method.
///
/// The Run method will return an array of TFTensor values, one for each invocation to the Fetch method.
/// </remarks>
public Runner GetRunner()
{
return new Runner(this);
}
/// <summary>
/// Executes a pipeline given the specified inputs, inputValues, outputs, targetOpers, runMetadata and runOptions.
/// A simpler API is available by calling the <see cref="M:GetRunner"/> method which performs all the bookkeeping
/// necessary.
/// </summary>
/// <returns>An array of tensors fetched from the requested outputs.</returns>
/// <param name="inputs">Inputs nodes.</param>
/// <param name="inputValues">Input values.</param>
/// <param name="outputs">Output nodes.</param>
/// <param name="targetOpers">Target operations to execute.</param>
/// <param name="runMetadata">Run metadata.</param>
/// <param name="runOptions">Run options.</param>
/// <param name="status">Status code.</param>
public TFTensor[] Run(TFOutput[] inputs, TFTensor[] inputValues, TFOutput[] outputs, TFOperation[] targetOpers = null, TFBuffer runMetadata = null, TFBuffer runOptions = null, TFStatus status = null)
{
if (handle == IntPtr.Zero)
ObjectDisposedException();
if (inputs == null)
throw new ArgumentNullException(nameof(inputs));
if (inputValues == null)
throw new ArgumentNullException(nameof(inputValues));
if (outputs == null)
throw new ArgumentNullException(nameof(outputs));
int iLen = inputs.Length;
if (iLen != inputValues.Length)
throw new ArgumentException("inputs and inputValues have different lengths", "inputs");
int oLen = outputs.Length;
// runOptions and runMetadata might be null
var cstatus = TFStatus.Setup(status);
// Create arrays for the unmanaged versions
var ivals = new IntPtr[iLen];
for (int i = 0; i < iLen; i++)
ivals[i] = inputValues[i].handle;
// I believe this might not be necessary, the output values in TF_SessionRun looks like a write-only result
var ovals = new IntPtr[outputs.Length];
IntPtr[] topers = null;
int tLen = 0;
if (targetOpers != null)
{
tLen = targetOpers.Length;
topers = new IntPtr[tLen];
for (int i = 0; i < tLen; i++)
topers[i] = targetOpers[i].handle;
}
unsafe
{
TF_SessionRun(handle, runOptions == null ? null : runOptions.LLBuffer, inputs, ivals, iLen, outputs, ovals, oLen, topers, tLen, runMetadata == null ? null : runMetadata.LLBuffer, cstatus.handle);
}
cstatus.CheckMaybeRaise(status);
var result = new TFTensor[oLen];
for (int i = 0; i < oLen; i++)
{
result[i] = new TFTensor(ovals[i]);
}
return result;
}
// extern void TF_SessionPRunSetup (TF_Session, const TF_Output *inputs, int ninputs, const TF_Output *outputs, int noutputs, const TF_Operation *const *target_opers, int ntargets, const char **handle, TF_Status *);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe void TF_SessionPRunSetup(TF_Session session, TFOutput[] inputs, int ninputs, TFOutput[] outputs, int noutputs, TF_Operation[] target_opers, int ntargets, out IntPtr returnHandle, TF_Status status);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe void TF_DeletePRunHandle(IntPtr partialRunHandle);
/// <summary>
/// Token returned from using one of the Partial Run Setup methods from <see cref="T:TensorFlow.TFSession"/>,
/// and use this token subsequently for other invocations.
/// </summary>
/// <remarks>
/// Calling Dispose on this object will release the resources associated with setting up
/// a partial run.
/// </remarks>
public class PartialRunToken : IDisposable
{
internal IntPtr token;
void IDisposable.Dispose()
{
if (token == IntPtr.Zero)
{
TF_DeletePRunHandle(token);
token = IntPtr.Zero;
}
}
}
/// <summary>
/// Prepares the session for a partial run.
/// </summary>
/// <returns>A token that can be used to call <see cref="PartialRun"/> repeatedly. To complete your partial run, you should call Dispose on the resulting method.</returns>
/// <param name="inputs">Inputs.</param>
/// <param name="outputs">Outputs.</param>
/// <param name="targetOpers">Target operations to run.</param>
/// <param name="status">Status.</param>
public PartialRunToken PartialRunSetup (TFOutput [] inputs, TFOutput [] outputs, TFOperation [] targetOpers, TFStatus status = null)
{
if (handle == IntPtr.Zero)
ObjectDisposedException ();
if (inputs == null)
throw new ArgumentNullException (nameof (inputs));
if (outputs == null)
throw new ArgumentNullException (nameof (outputs));
if (targetOpers == null)
throw new ArgumentNullException (nameof (targetOpers));
IntPtr returnHandle;
var cstatus = TFStatus.Setup (status);
int tLen = targetOpers.Length;
var topers = new IntPtr [tLen];
for (int i = 0; i < tLen; i++)
topers [i] = targetOpers [i].handle;
TF_SessionPRunSetup(handle, inputs, inputs.Length, outputs, outputs.Length, topers, tLen, out returnHandle, cstatus.handle);
cstatus.CheckMaybeRaise(status);
return new PartialRunToken() { token = returnHandle };
}
// extern void TF_SessionPRun (TF_Session *, const char *handle, const TF_Output *inputs, TF_Tensor *const *input_values, int ninputs, const TF_Output *outputs, TF_Tensor **output_values, int noutputs, const TF_Operation *const *target_opers, int ntargets, TF_Status *);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe void TF_SessionPRun(TF_Session session, IntPtr partialHandle, TFOutput[] inputs, TF_Tensor[] input_values, int ninputs, TFOutput[] outputs, TF_Tensor[] output_values, int noutputs, TF_Operation[] target_opers, int ntargets, TF_Status status);
public TFTensor[] PartialRun(PartialRunToken token, TFOutput[] inputs, TFTensor[] inputValues, TFOutput[] outputs, TFOperation[] targetOpers, TFStatus status = null)
{
if (handle == IntPtr.Zero)
ObjectDisposedException();
if (inputs == null)
throw new ArgumentNullException(nameof(inputs));
if (inputValues == null)
throw new ArgumentNullException(nameof(inputValues));
if (outputs == null)
throw new ArgumentNullException(nameof(outputs));
if (targetOpers == null)
throw new ArgumentNullException(nameof(targetOpers));
int iLen = inputs.Length;
if (iLen != inputValues.Length)
throw new ArgumentException("inputs and inputValues have different lengths", "inputs");
int oLen = outputs.Length;
// runOptions and runMetadata might be null
var cstatus = TFStatus.Setup(status);
// Create arrays for the unmanaged versions
var ivals = new IntPtr[iLen];
for (int i = 0; i < iLen; i++)
ivals[i] = inputValues[i].handle;
var ovals = new IntPtr[oLen];
int tLen = targetOpers.Length;
var topers = new IntPtr[tLen];
for (int i = 0; i < tLen; i++)
topers[i] = targetOpers[i].handle;
unsafe
{
TF_SessionPRun(handle, token.token, inputs, ivals, iLen, outputs, ovals, oLen, topers, tLen, cstatus.handle);
}
cstatus.CheckMaybeRaise(status);
var result = new TFTensor[oLen];
for (int i = 0; i < oLen; i++)
{
result[i] = new TFTensor(ovals[i]);
}
return result;
}
}
public class TFLibrary : TFDisposable
{
// extern TF_Library * TF_LoadLibrary (const char *library_filename, TF_Status *status);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe TF_Library TF_LoadLibrary(string library_filename, TF_Status status);
TFLibrary(IntPtr handle) : base(handle) { }
public static TFLibrary FromFile(string libraryFile, TFStatus status = null)
{
var cstatus = TFStatus.Setup(status);
var h = TF_LoadLibrary(libraryFile, cstatus.handle);
cstatus.CheckMaybeRaise(status);
return new TFLibrary(h);
}
// extern TF_Buffer TF_GetOpList (TF_Library *lib_handle);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe LLBuffer TF_GetOpList(TF_Library lib_handle);
/// <summary>
/// Retrieves the ProtocolBuffer describing the available operations in
/// the loaded TensorFlow library.
/// </summary>
/// <returns>The buffer contains a ProtocolBuffer encoded payload, you need a ProtocolBuffer reader to process the contents.</returns>
TFBuffer GetOpList()
{
return new TFBuffer(TF_GetOpList(handle).data);
}
// extern void TF_DeleteLibraryHandle (TF_Library *lib_handle);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe void TF_DeleteLibraryHandle(TF_Library lib_handle);
internal override void NativeDispose(IntPtr handle)
{
TF_DeleteLibraryHandle(handle);
}
}
/// <summary>
/// The data type for a specific tensor.
/// </summary>
/// <remarks>
/// Tensors have uniform data types, all the elements of the tensor are of this
/// type and they dictate how TensorFlow will treat the data stored.
/// </remarks>
public enum TFDataType : uint
{
/// <summary>
/// Single precission floatint point, 32-bits (C# float)
/// </summary>
Float = 1,
/// <summary>
/// Double precission floatint point, 64-bits (C# double)
/// </summary>
Double = 2,
/// <summary>
/// 32-bit signed integers (C# int)
/// </summary>
Int32 = 3,
/// <summary>
/// 8 bit unsigned integers (C# byte)
/// </summary>
UInt8 = 4,
/// <summary>
/// 16-bit signed integers (C# short)
/// </summary>
Int16 = 5,
/// <summary>
/// 8-bit signed integers (C# sbyte)
/// </summary>
Int8 = 6,
/// <summary>
/// Binary blob
/// </summary>
String = 7,
/// <summary>
/// Single precission complex numbers (32-bit floats)
/// </summary>
Complex64 = 8,
/// <summary>
/// 32-bit float based complex numbers
/// </summary>
Complex = 8,
/// <summary>
/// 64-bit signed integers (C# long)
/// </summary>
Int64 = 9,
Bool = 10,
/// <summary>
/// Quantized 8-bit signed integer
/// </summary>
QInt8 = 11,
/// <summary>
/// Quantized 8-bit unsigned integer
/// </summary>
QUInt8 = 12,
/// <summary>
/// Quantized 32-bit signed integer
/// </summary>
QInt32 = 13,
/// <summary>
/// Float32 truncated to 16 bits. Only for cast operations.
/// </summary>
BFloat16 = 14,
/// <summary>
/// Quantized 16-bit signed integer
/// </summary>
QInt16 = 15,
/// <summary>
/// Quantized 16-bit unsigned integer
/// </summary>
QUInt16 = 16,
/// <summary>
/// 16-bit unsigned integers (C# long)
/// </summary>
UInt16 = 17,
/// <summary>
/// Double precission complex numbers (32-bit floats)
/// </summary>
Complex128 = 18,
Half = 19,
Resource = 20
}
/// <summary>
/// Status code for invoking a tensorflow operation.
/// </summary>
public enum TFCode : uint
{
Ok = 0,
Cancelled = 1,
Unknown = 2,
InvalidArgument = 3,
DeadlineExceeded = 4,
NotFound = 5,
AlreadyExists = 6,
PermissionDenied = 7,
Unauthenticated = 16,
ResourceExhausted = 8,
FailedPrecondition = 9,
Aborted = 10,
OutOfRange = 11,
Unimplemented = 12,
Internal = 13,
Unavailable = 14,
DataLoss = 15
}
[StructLayout(LayoutKind.Sequential)]
public struct TFInput
{
public unsafe TF_Operation Operation;
public int Index;
// extern TF_Output TF_OperationInput (TF_Input oper_in);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern TFOutput TF_OperationInput(TFInput oper_in);
public TFOutput GetOutput(TFInput operIn)
{
return TF_OperationInput(operIn);
}
// extern TF_DataType TF_OperationInputType (TF_Input oper_in);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern TFDataType TF_OperationInputType(TFInput oper_in);
public TFDataType InputType => TF_OperationInputType(this);
}
/// <summary>
/// Represents a specific output of an operation on a tensor.
/// </summary>
/// <remarks>
/// <para>
/// TFOutput objects represent one of the outputs of an operation in the graph
/// (TFGraph). Outputs have a data type, and eventually a shape that you can
/// retrieve by calling the <see cref="M:TensorFlow.TFGraph.GetShape"/> method.
/// </para>
/// <para>
/// These can be passed as an input argument to a function for adding operations
/// to a graph, or to the TFSession's Run and GetRunner method as values to be
/// fetched.
/// </para>
/// </remarks>
[StructLayout (LayoutKind.Sequential)]
public struct TFOutput
{
unsafe TF_Operation LLOperation;
public int Index;
// extern int TF_OperationOutputNumConsumers (TF_Output oper_out);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern int TF_OperationOutputNumConsumers(TFOutput oper_out);
/// <summary>
/// Gets the number consumers.
/// </summary>
/// <value>The number consumers.</value>
/// <remarks>
/// This number can change when new operations are added to the graph.
/// </remarks>
public int NumConsumers => TF_OperationOutputNumConsumers(this);
// extern TF_DataType TF_OperationOutputType (TF_Output oper_out);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern TFDataType TF_OperationOutputType(TFOutput oper_out);
/// <summary>
/// Gets the type of the output.
/// </summary>
/// <value>The type of the output.</value>
public TFDataType OutputType => TF_OperationOutputType(this);
/// <summary>
/// Initializes a new TFOutput instance.
/// </summary>
/// <param name="operation">The operation to which to attach the output.</param>
/// <param name="index">The index of the output within the operation, if not specified, it defaults to zero.</param>
public TFOutput(TFOperation operation, int index = 0)
{
if (operation == null)
throw new ArgumentNullException(nameof(operation));
LLOperation = operation.handle;
Index = index;
}
/// <summary>
/// Initializes a new TFOutput instance from another TFOutput
/// </summary>
/// <param name="operation">The other TFOutput that is having its operation attached.</param>
/// <param name="index">The index of the output within the operation, if not specified, it defaults to zero.</param>
public TFOutput(TFOutput output, int index = 0)
{
if (output.LLOperation == null)
throw new ArgumentNullException("Outputs does not have a valid operation pointer");
LLOperation = output.LLOperation;
Index = index;
}
// extern int TF_OperationOutputConsumers (TF_Output oper_out, TF_Input *consumers, int max_consumers);
[DllImport(NativeBinding.TensorFlowLibrary)]
static extern unsafe int TF_OperationOutputConsumers(TFOutput oper_out, TFInput* consumers, int max_consumers);
/// <summary>
/// Get list of all current consumers of a specific output of an operation
/// </summary>
/// <value>The output consumers.</value>
/// <remarks>
/// A concurrent modification of the graph can increase the number of consumers of
/// an operation.
/// This can return null if the TFOutput does not point to a valid object.
/// </remarks>
public TFInput[] OutputConsumers
{
get
{
var result = new TFInput[NumConsumers];
unsafe
{
fixed (TFInput* first = &result[0])
TF_OperationOutputConsumers(this, first, result.Length);
}
return result;
}
}
/// <summary>
/// The associated operation.
/// </summary>
/// <value>The operation.</value>
public TFOperation Operation => new TFOperation(null, LLOperation);
public override string ToString()
{
return string.Format("[TFOutput: LLOperation=0x{0:X} Index={1} Operation={2}]", (long)LLOperation, Index, Operation);
}
}
/// <summary>
/// Low-level: Enumeration describing the types of a metadata attribute
/// </summary>
public enum TFAttributeType : uint
{
/// <summary>
/// The type of the attribute is a string
/// </summary>
String = 0,
/// <summary>
/// The type of the attribute is an int.
/// </summary>
Int = 1,
/// <summary>
/// The type of the attribute is a float
/// </summary>
Float = 2,
/// <summary>
/// The type of the attribute is a bool.
/// </summary>
Bool = 3,
/// <summary>
/// The type of the attribute is a type.
/// </summary>
Type = 4,
/// <summary>
/// The type of the attribute is a tensor shape
/// </summary>
Shape = 5,
/// <summary>
/// The type of the attribute is a tensor
/// </summary>
Tensor = 6,
/// <summary>
/// The type of the attribute is a placeholder
/// </summary>
Placeholder = 7,
/// <summary>
/// The type of the attribute is a function
/// </summary>
Func = 8
}
/// <summary>
/// Low-level: this describes the tensorflow type information for an attribute in the low-level attributes used by operations.
/// </summary>
/// <remarks>
/// This is a low-level operation returned by the <see cref="M:TensorFlow.TFOperation.GetAttributeMetadata"/>.
/// This is included for completeness, but is not generally used from C#, as you have access to the high-level
/// bindings in the <see cref="T:TensorFlow.TFGraph"/> type.
/// </remarks>
[StructLayout(LayoutKind.Sequential)]
public struct TFAttributeMetadata
{
byte isList;
public bool IsList => isList != 0;
public long ListSize;
public TFAttributeType Type;
public long TotalSize;
public override string ToString()
{
return string.Format($"[TFAttributeMetadata IsList={IsList} ListSize={ListSize} Type={Type} TotalSize={TotalSize}]");
}
}
/// <summary>
/// Represents the shape of a tensor
/// </summary>
/// <remarks>
/// <para>
/// The shapes can be created by calling the constructor with the number of dimensions
/// in the shape. The null value is used to specify that the shape is unknown,
/// an empty array is used to create a scalar, and other values are used to specify
/// the number of dimensions.
/// </para>
/// <para>
/// For the Unknown case, you can use <see cref="P:TensorFlor.TFShape.Unknown"/>, for
/// scalars, you can use the <see cref="P:TensorFlor.TFShape.Scalar"/> shape.
/// </para>
/// <para>
/// To create a 2-element vector, use:
/// new TFShape (2)
/// </para>
/// <para>
/// To create a 2x3 matrix, use:
/// new TFShape (2, 3)
/// </para>
/// <para>
/// To create a shape with an unknown number of elements, you can pass the value
/// -1. This is typically used to indicate the shape of tensors that represent a
/// variable-sized batch of values.
/// </para>
/// <para>
/// To create a matrix with 4 columns and an unknown number of rows:
/// var batch = new TFShape (-1, 4)
/// </para>
/// </remarks>
public class TFShape
{
/// <summary>
/// Represents an unknown number of dimensions in the tensor.
/// </summary>
/// <value>The unknown.</value>
public static TFShape Unknown => new TFShape (null);
/// <summary>
/// This shape is used to represent scalar values.
/// </summary>
/// <value>The scalar.</value>
public static TFShape Scalar => new TFShape(new long[0]);
internal long[] dims;
/// <summary>
/// Initializes a new instance of the <see cref="T:TensorFlow.TFShape"/> class.
/// </summary>
/// <param name="args">This is a params argument, so you can provide multiple values to it.
/// A null value means that this is an unknown shape, a single value is used to create a vector,
/// two values are used to create a 2-D matrix and so on.
/// </param>
/// <remarks>
///
/// </remarks>
public TFShape(params long[] args)
{
this.dims = args;
}
/// <summary>
/// Gets the length of the specified dimension in the tensor
/// </summary>
/// <returns>The length, -1 for shapes that have an unknown dimension.</returns>
/// <param name="dimension">Dimension.</param>
public int GetLength(int dimension) => dims == null ? -1 : dims.GetLength(dimension);
/// <summary>
/// Number of dimensions represented by this shape.
/// </summary>
/// <value>The number dimensions, -1 if the number of dimensions is unknown, 0 if the shape represent a scalar, 1 for a vector, 2 for a matrix and so on..</value>
public int NumDimensions => dims == null ? -1 : dims.Length;
/// <summary>
/// Gets a value indicating whether all the dimensions in the <see cref="T:TensorFlow.TFShape"/> are fully specified.
/// </summary>
/// <value><c>true</c> if is fully specified; otherwise, <c>false</c>.</value>
public bool IsFullySpecified
{
get
{
if (dims == null)
return false;
foreach (var j in dims)
if (j == -1)
return false;
return true;
}
}
/// <summary>
/// Returns the shape as an array
/// </summary>
/// <returns>null if the shape represents an unknown shape, otherwise an array with N elements, one per dimension, and each element can be either -1 (if the dimension size is unspecified) or the size of the dimension.</returns>
public long[] ToArray()
{
if (dims == null)
return null;
var ret = (long[])dims.Clone();
return ret;
}
/// <summary>
/// Returns the shape as an array
/// </summary>
/// <returns>null if the shape represents an unknown shape, otherwise an array with N elements, one per dimension, and each element can be either -1 (if the dimension size is unspecified) or the size of the dimension.</returns>
public int[] ToIntArray()
{
if (dims == null)
return null;
var ret = new int[dims.Length];
for (int i = 0; i < dims.Length; i++)
{
checked
{
ret[i] = (int)dims[i];
}
}
return ret;
}
/// <summary>
/// Gets a value indicating whether one of the dimensions <see cref="T:TensorFlow.TFShape"/> in the shape is larger than Int32.MaxValue.
/// </summary>
/// <value><c>true</c> if is long array; otherwise, <c>false</c>.</value>
public bool IsLongArray
{
get
{
foreach (var l in dims)
if (l > Int32.MaxValue)
return true;
return false;
}
}
public override string ToString()
{
if (dims == null)
return "unknown";
return "[" + String.Join(", ", dims.Select(x => x == -1 ? "?" : x.ToString())) + "]";
}
/// <summary>
/// Gets the dimensions for the specified index.
/// </summary>
/// <param name="idx">Index.</param>
public long this[int idx] => dims[idx];
/// <summary>
/// Returns the shape as a 1-dimensional tensor with each element corresponding to the specified shape dimension.
/// </summary>
/// <returns>The tensor.</returns>
public TFTensor AsTensor()
{
return new TFTensor(ToIntArray());
}
/// <summary>
/// Adds a <see cref="TensorFlow.TFShape"/> to a <see cref="TensorFlow.TFShape"/>, yielding a shape made up of the concatenation of the first and the second shapes.
/// </summary>
/// <param name="left">The first <see cref="TensorFlow.TFShape"/> to add.</param>
/// <param name="right">The second <see cref="TensorFlow.TFShape"/> to add.</param>
/// <returns>The <see cref="T:TensorFlow.TFShape"/> that is the sum of the values of <c>left</c> and <c>right</c>.</returns>
public static TFShape operator +(TFShape left, TFShape right)
{
if (left == null)
return right;
if (right == null)
return left;
var full = new long[left.dims.Length + right.dims.Length];
Array.Copy(left.dims, full, left.dims.Length);
Array.Copy(right.dims, 0, full, left.dims.Length, right.dims.Length);
return new TFShape(full);
}
}
}
| 42.092696 | 319 | 0.615521 | [
"MIT"
] | JaridKG/TensorFlowSharp | TensorFlowSharp/Tensorflow.cs | 128,513 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("CubeProperties")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CubeProperties")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("9ce985b5-5945-4438-8ef2-5c7fb05131dc")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.72973 | 84 | 0.748567 | [
"MIT"
] | VeselinBPavlov/programming-fundamentals | 10. Methods. Debugging and Troubleshooting Code - Exercises/CubeProperties/Properties/AssemblyInfo.cs | 1,399 | C# |
/*
* Copyright 2011-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System;
using System.Globalization;
using Amazon.Runtime.Internal.Util;
using System.Collections.Generic;
using Amazon.Util;
#if BCL || NETSTANDARD
using Amazon.Runtime.CredentialManagement;
#endif
namespace Amazon.Runtime
{
#if BCL || NETSTANDARD
/// <summary>
/// Determines the endpoint discovery enabled value based on an environment variable. If no value is found in the
/// environment then an InvalidOperationException is thrown.
/// </summary>
public class EnvironmentVariableAWSEndpointDiscoveryEnabled
{
public const string ENVIRONMENT_VARIABLE_AWS_ENABLE_ENDPOINT_DISCOVERY = "AWS_ENABLE_ENDPOINT_DISCOVERY";
public bool Enabled { get; private set; }
/// <summary>
/// Attempts to construct an instance of EnvironmentVariable AWS_ENABLED_ENDPOINT_DISCOVERY. If no value is found in the
/// environment then an InvalidOperationException is thrown.
/// </summary>
public EnvironmentVariableAWSEndpointDiscoveryEnabled()
{
string enabledValue = Environment.GetEnvironmentVariable(ENVIRONMENT_VARIABLE_AWS_ENABLE_ENDPOINT_DISCOVERY);
if (string.IsNullOrEmpty(enabledValue))
{
throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture,
"The environment variable {0} was not set with a boolean value.", ENVIRONMENT_VARIABLE_AWS_ENABLE_ENDPOINT_DISCOVERY));
}
bool enabled;
if(!bool.TryParse(enabledValue, out enabled))
{
throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture,
"The environment variable {0} was set with value {1}, but it could not be parsed as a valid boolean value.", ENVIRONMENT_VARIABLE_AWS_ENABLE_ENDPOINT_DISCOVERY, enabledValue));
}
this.Enabled = enabled;
var logger = Logger.GetLogger(typeof(EnvironmentVariableAWSEndpointDiscoveryEnabled));
logger.InfoFormat("Endpoint discovery enabled found using environment variable.");
}
}
/// <summary>
/// Determines endpoint discovery enabled based on a <see cref="CredentialProfile"/> stored in an <see cref="ICredentialProfileSource"/>.
/// If the profile doesn't exist or there is no endpoint discovery enabled information an InvalidOperationException is thrown.
/// </summary>
public class ProfileAWSEndpointDiscoveryEnabled
{
public bool Enabled { get; private set; }
/// <summary>
/// Attempts to construct an instance of <see cref="ProfileAWSEndpointDiscoveryEnabled"/>.
/// If the AWS_PROFILE environment variable is set the instance will be constructed using that profile,
/// otherwise it will use the default profile.
///
/// If the profile doesn't exist or there is no endpoint discovery enabled information an InvalidOperationException is thrown.
/// </summary>
/// <param name="source">The ICredentialProfileSource to read the profile from.</param>
public ProfileAWSEndpointDiscoveryEnabled(ICredentialProfileSource source)
{
var profileName = Environment.GetEnvironmentVariable(FallbackCredentialsFactory.AWS_PROFILE_ENVIRONMENT_VARIABLE);
if (profileName == null)
profileName = FallbackCredentialsFactory.DefaultProfileName;
Setup(source, profileName);
}
/// <summary>
/// Attempts to construct an instance of <see cref="ProfileAWSEndpointDiscoveryEnabled"/>.
/// If the profile doesn't exist or there is no endpoint discovery enabled information an InvalidOperationException is thrown.
/// </summary>
/// <param name="source">The ICredentialProfileSource to read the profile from.</param>
/// <param name="profileName">The name of the profile.</param>
public ProfileAWSEndpointDiscoveryEnabled(ICredentialProfileSource source, string profileName)
{
Setup(source, profileName);
}
private void Setup(ICredentialProfileSource source, string profileName)
{
bool? enabled = null;
CredentialProfile profile;
if (source.TryGetProfile(profileName, out profile))
{
enabled = profile.EndpointDiscoveryEnabled;
}
else
throw new InvalidOperationException("Unable to find a profile named '" + profileName + "' in store " + source.GetType());
if (enabled == null)
throw new InvalidOperationException("There is no endpoint_discovery_enabled set in the profile named '" + profileName + "' in store " + source.GetType());
else
{
this.Enabled = enabled.Value;
var logger = Logger.GetLogger(typeof(ProfileAWSRegion));
logger.InfoFormat("endpoint_discovery_enabled found in profile '" + profileName + "' in store " + source.GetType());
}
}
}
#endif
/// <summary>
/// Probing mechanism to determine the endpoint discovery enabled value from various sources.
/// </summary>
public static class FallbackEndpointDiscoveryEnabledFactory
{
#if BCL || NETSTANDARD
private static CredentialProfileStoreChain credentialProfileChain = new CredentialProfileStoreChain();
#endif
private static object _lock = new object();
static FallbackEndpointDiscoveryEnabledFactory()
{
Reset();
}
private delegate bool ConfigGenerator();
private static List<ConfigGenerator> EnabledGenerators { get; set; }
public static void Reset()
{
endpointDiscoveryEnabled = null;
EnabledGenerators = new List<ConfigGenerator>
{
#if BCL || NETSTANDARD
() => (new EnvironmentVariableAWSEndpointDiscoveryEnabled()).Enabled,
() => (new ProfileAWSEndpointDiscoveryEnabled(credentialProfileChain)).Enabled,
#endif
};
}
private static bool? endpointDiscoveryEnabled;
public static bool? GetEnabled()
{
lock (_lock)
{
if (endpointDiscoveryEnabled != null)
return endpointDiscoveryEnabled;
List<Exception> errors = new List<Exception>();
//Determine the Enabled flag
foreach (var generator in EnabledGenerators)
{
try
{
endpointDiscoveryEnabled = generator();
}
catch (Exception e)
{
errors.Add(e);
continue;
}
if (endpointDiscoveryEnabled.HasValue)
break;
}
return endpointDiscoveryEnabled;
}
}
}
}
| 41.395722 | 196 | 0.63028 | [
"Apache-2.0"
] | AltairMartinez/aws-sdk-unity-net | src/Core/Amazon.Runtime/EndpointDiscoveryEnabled.cs | 7,743 | C# |
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using FluentNHibernate.Conventions;
using FluentNHibernate.Conventions.Inspections;
using FluentNHibernate.MappingModel;
using FluentNHibernate.Utils.Reflection;
using NUnit.Framework;
namespace FluentNHibernate.Testing.ConventionsTests.Inspection
{
[TestFixture, Category("Inspection DSL")]
public class KeyInspectorMapsToKeyMapping
{
private KeyMapping mapping;
private IKeyInspector inspector;
[SetUp]
public void CreateDsl()
{
mapping = new KeyMapping();
inspector = new KeyInspector(mapping);
}
[Test]
public void ColumnsCollectionHasSameCountAsMapping()
{
mapping.AddColumn(new ColumnMapping());
inspector.Columns.Count().ShouldEqual(1);
}
[Test]
public void ColumnsCollectionOfInspectors()
{
mapping.AddColumn(new ColumnMapping());
inspector.Columns.First().ShouldBeOfType<IColumnInspector>();
}
[Test]
public void ColumnsCollectionIsEmpty()
{
inspector.Columns.IsEmpty().ShouldBeTrue();
}
[Test]
public void ForeignKeyMapped()
{
mapping.ForeignKey = "key";
inspector.ForeignKey.ShouldEqual("key");
}
[Test]
public void ForeignKeyIsSet()
{
mapping.ForeignKey = "key";
inspector.IsSet(Prop(x => x.ForeignKey))
.ShouldBeTrue();
}
[Test]
public void ForeignKeyIsNotSet()
{
inspector.IsSet(Prop(x => x.ForeignKey))
.ShouldBeFalse();
}
[Test]
public void OnDeleteMapped()
{
mapping.OnDelete = "cascade";
inspector.OnDelete.ShouldEqual(OnDelete.Cascade);
}
[Test]
public void OnDeleteIsSet()
{
mapping.OnDelete = "cascade";
inspector.IsSet(Prop(x => x.OnDelete))
.ShouldBeTrue();
}
[Test]
public void OnDeleteIsNotSet()
{
inspector.IsSet(Prop(x => x.OnDelete))
.ShouldBeFalse();
}
[Test]
public void PropertyRefMapped()
{
mapping.PropertyRef = "ref";
inspector.PropertyRef.ShouldEqual("ref");
}
[Test]
public void PropertyRefIsSet()
{
mapping.PropertyRef = "ref";
inspector.IsSet(Prop(x => x.PropertyRef))
.ShouldBeTrue();
}
[Test]
public void PropertyRefIsNotSet()
{
inspector.IsSet(Prop(x => x.PropertyRef))
.ShouldBeFalse();
}
#region Helpers
private Member Prop(Expression<Func<IKeyInspector, object>> propertyExpression)
{
return ReflectionHelper.GetMember(propertyExpression);
}
#endregion
}
} | 26.330579 | 88 | 0.535782 | [
"BSD-3-Clause"
] | JamesKovacs/fluent-nhibernate | src/FluentNHibernate.Testing/ConventionsTests/Inspection/KeyInspectorMapsToKeyMapping.cs | 3,186 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RuriLib.Interfaces
{
/// <summary>
/// Interface for requesting user interaction (e.g. confirmations).
/// </summary>
public interface IAlerter
{
/// <summary>
/// Asks a yes or no question to the user.
/// </summary>
/// <param name="message">The body of the alert</param>
/// <param name="title">The caption of the alert</param>
/// <returns>True if the user answered yes.</returns>
bool YesOrNo(string message, string title);
}
}
| 27.869565 | 71 | 0.628705 | [
"MIT"
] | BLACKOB/SilverBullet | RuriLib/Interfaces/IAlerter.cs | 643 | C# |
using System.Collections.Generic;
namespace Logging.Constants
{
public static class WebConstants
{
public const string ParentObject = "parentObject";
public const string RequestUserSecurityProfile = "UserSecurityProfile";
public const string PatchMethod = "PATCH";
public const string RequestGuid = "RequestGuid";
public const string RequestIdHeaderKey = "x-request-id";
public const string AuditTrailCloudCall = "AuditTrailCloudCall";
public const string LogContextDictionary = "LogContextDictionary";
public const string RequestControllerName = "RequestControllerName";
public const string RequestActionName = "RequestActionName";
public static readonly IList<string> ExcludedSensitiveHeadersIndexOf = new List<string> { "authorization" };
}
}
| 35.458333 | 115 | 0.720329 | [
"MIT"
] | sreejankumar/Logging | src/libs/Logging/Constants/WebConstants.cs | 853 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Diagnostics;
using Microsoft.Build.Shared;
using BuildResult = Microsoft.Build.Execution.BuildResult;
namespace Microsoft.Build.BackEnd
{
/// <summary>
/// This class is used by the Scheduler to unblock a blocked build request on the BuildRequestEngine.
/// There are two cases:
/// 1. The request was blocked waiting on a target in the same project. In this case this class will contain
/// no information other than the request id.
/// 2. The request was blocked on some set of build requests. This class will then contain the build results
/// needed to satisfy those requests.
/// </summary>
internal class BuildRequestUnblocker : ITranslatable, INodePacket
{
/// <summary>
/// The node request id of the request which is blocked and now will either result or have results reported.
/// </summary>
private int _blockedGlobalRequestId = BuildRequest.InvalidGlobalRequestId;
/// <summary>
/// The build result which we wish to report.
/// </summary>
private BuildResult _buildResult;
/// <summary>
/// Constructor for deserialization.
/// </summary>
internal BuildRequestUnblocker(ITranslator translator)
{
Translate(translator);
}
/// <summary>
/// Constructor for the unblocker where we are blocked waiting for a target.
/// </summary>
internal BuildRequestUnblocker(int globalRequestIdToResume)
{
ErrorUtilities.VerifyThrowArgumentOutOfRange(globalRequestIdToResume != BuildRequest.InvalidGlobalRequestId, nameof(globalRequestIdToResume));
_blockedGlobalRequestId = globalRequestIdToResume;
}
/// <summary>
/// Constructor for the unblocker where we are blocked waiting for results.
/// </summary>
internal BuildRequestUnblocker(BuildResult buildResult)
{
ErrorUtilities.VerifyThrowArgumentNull(buildResult, nameof(buildResult));
_buildResult = buildResult;
_blockedGlobalRequestId = buildResult.ParentGlobalRequestId;
}
/// <summary>
/// Constructor for the unblocker for circular dependencies
/// </summary>
internal BuildRequestUnblocker(BuildRequest parentRequest, BuildResult buildResult)
: this(buildResult)
{
ErrorUtilities.VerifyThrowArgumentNull(parentRequest, nameof(parentRequest));
_blockedGlobalRequestId = parentRequest.GlobalRequestId;
}
/// <summary>
/// Returns the type of packet.
/// </summary>
public NodePacketType Type
{
[DebuggerStepThrough]
get
{ return NodePacketType.BuildRequestUnblocker; }
}
/// <summary>
/// Accessor for the blocked node request id.
/// </summary>
public int BlockedRequestId
{
[DebuggerStepThrough]
get
{
return _blockedGlobalRequestId;
}
}
/// <summary>
/// Accessor for the build results, if any.
/// </summary>
public BuildResult Result
{
[DebuggerStepThrough]
get
{
return _buildResult;
}
}
#region INodePacketTranslatable Members
/// <summary>
/// Serialization method.
/// </summary>
public void Translate(ITranslator translator)
{
translator.Translate(ref _blockedGlobalRequestId);
translator.Translate(ref _buildResult);
}
#endregion
/// <summary>
/// Factory for serialization.
/// </summary>
internal static INodePacket FactoryForDeserialization(ITranslator translator)
{
return new BuildRequestUnblocker(translator);
}
}
}
| 33.387097 | 154 | 0.614251 | [
"MIT"
] | 0xced/msbuild | src/Build/BackEnd/Shared/BuildRequestUnblocker.cs | 4,142 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Threading.Tasks;
using Xunit;
using VerifyCS = Test.Utilities.CSharpCodeFixVerifier<
Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.OverloadOperatorEqualsOnOverridingValueTypeEqualsAnalyzer,
Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.OverloadOperatorEqualsOnOverridingValueTypeEqualsFixer>;
using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier<
Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.OverloadOperatorEqualsOnOverridingValueTypeEqualsAnalyzer,
Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.OverloadOperatorEqualsOnOverridingValueTypeEqualsFixer>;
namespace Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.UnitTests
{
public partial class OverloadOperatorEqualsOnOverridingValueTypeEqualsTests
{
[Fact]
public async Task CA2231CSharpCodeFixNoEqualsOperator()
{
await VerifyCS.VerifyCodeFixAsync(@"
using System;
// value type without overriding Equals
public struct [|A|]
{
public override bool Equals(Object obj)
{
return true;
}
}
",
@"
using System;
// value type without overriding Equals
public struct A
{
public override bool Equals(Object obj)
{
return true;
}
public static bool operator ==(A left, A right)
{
return left.Equals(right);
}
public static bool operator !=(A left, A right)
{
return !(left == right);
}
}
");
}
[Fact]
public async Task CA2231BasicCodeFixNoEqualsOperator()
{
await VerifyVB.VerifyCodeFixAsync(@"
Imports System
Public Structure [|A|]
Public Overloads Overrides Function Equals(obj As Object) As Boolean
Return True
End Function
End Structure
",
@"
Imports System
Public Structure A
Public Overloads Overrides Function Equals(obj As Object) As Boolean
Return True
End Function
Public Shared Operator =(left As A, right As A) As Boolean
Return left.Equals(right)
End Operator
Public Shared Operator <>(left As A, right As A) As Boolean
Return Not left = right
End Operator
End Structure
");
}
}
}
| 26.747126 | 161 | 0.718522 | [
"Apache-2.0"
] | LingxiaChen/roslyn-analyzers | src/Microsoft.CodeQuality.Analyzers/UnitTests/ApiDesignGuidelines/OverloadOperatorEqualsOnOverridingValueTypeEqualsTests.Fixer.cs | 2,329 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Utils;
using Aliyun.Acs.CloudAPI.Transform.V20160714;
namespace Aliyun.Acs.CloudAPI.Model.V20160714
{
public class DescribeAppsRequest : RpcAcsRequest<DescribeAppsResponse>
{
public DescribeAppsRequest()
: base("CloudAPI", "2016-07-14", "DescribeApps")
{
}
private long? _appId;
private string _appOwner;
private int? _pageNumber;
private int? _pageSize;
public long? AppId
{
get
{
return _appId;
}
set
{
_appId = value;
DictionaryUtil.Add(QueryParameters, "AppId", value.ToString());
}
}
public string AppOwner
{
get
{
return _appOwner;
}
set
{
_appOwner = value;
DictionaryUtil.Add(QueryParameters, "AppOwner", value);
}
}
public int? PageNumber
{
get
{
return _pageNumber;
}
set
{
_pageNumber = value;
DictionaryUtil.Add(QueryParameters, "PageNumber", value.ToString());
}
}
public int? PageSize
{
get
{
return _pageSize;
}
set
{
_pageSize = value;
DictionaryUtil.Add(QueryParameters, "PageSize", value.ToString());
}
}
public override DescribeAppsResponse GetResponse(Core.Transform.UnmarshallerContext unmarshallerContext)
{
return DescribeAppsResponseUnmarshaller.Unmarshall(unmarshallerContext);
}
}
} | 22.814433 | 112 | 0.678717 | [
"Apache-2.0"
] | VAllens/aliyun-openapi-sdk-net-core | src/aliyun-net-sdk-cloudapi/Model/V20160714/DescribeAppsRequest.cs | 2,213 | C# |
namespace I.SimpleHandmadeFramework.Server.Http.Responses
{
using Enums;
public class HttpViewResponse : HttpResponse
{
public HttpViewResponse(string content) : base(HttpStatusCode._200_OK)
{
this.Content = content;
}
}
}
| 21.307692 | 78 | 0.646209 | [
"MIT"
] | spzvtbg/05-Web | I.SimpleHandmadeFramework/I.SimpleHandmadeFramework.Server/Http/Responses/HttpViewResponse.cs | 279 | C# |
using System;
using Microsoft.Maui.Controls;
namespace Microsoft.Maui.Controls.ControlGallery
{
internal class ScaleRotate : ContentPage
{
public ScaleRotate()
{
Label label = new Label
{
Text = "SCALE AND\nROTATE",
HorizontalTextAlignment = TextAlignment.Center,
HorizontalOptions = LayoutOptions.Center,
VerticalOptions = LayoutOptions.CenterAndExpand
};
// Label and Slider for Scale property.
Label scaleSliderValue = new Label
{
VerticalTextAlignment = TextAlignment.Center
};
Grid.SetRow(scaleSliderValue, 0);
Grid.SetColumn(scaleSliderValue, 0);
Slider scaleSlider = new Slider
{
Maximum = 10
};
Grid.SetRow(scaleSlider, 0);
Grid.SetColumn(scaleSlider, 1);
// Set Bindings.
scaleSliderValue.BindingContext = scaleSlider;
scaleSliderValue.SetBinding(Label.TextProperty,
new Binding("Value", BindingMode.OneWay, null, null, "Scale = {0:F1}"));
scaleSlider.BindingContext = label;
scaleSlider.SetBinding(Slider.ValueProperty,
new Binding("Scale", BindingMode.TwoWay));
// Label and Slider for ScaleX property.
Label scaleXSliderValue = new Label
{
VerticalTextAlignment = TextAlignment.Center
};
Grid.SetRow(scaleXSliderValue, 1);
Grid.SetColumn(scaleXSliderValue, 0);
Slider scaleXSlider = new Slider
{
Maximum = 10
};
Grid.SetRow(scaleXSlider, 1);
Grid.SetColumn(scaleXSlider, 1);
// Set Bindings.
scaleXSliderValue.BindingContext = scaleXSlider;
scaleXSliderValue.SetBinding(Label.TextProperty,
new Binding("Value", BindingMode.OneWay, null, null, "ScaleX = {0:F1}"));
scaleXSlider.BindingContext = label;
scaleXSlider.SetBinding(Slider.ValueProperty,
new Binding("ScaleX", BindingMode.TwoWay));
// Label and Slider for Rotation property.
Label rotationSliderValue = new Label
{
VerticalTextAlignment = TextAlignment.Center
};
Grid.SetRow(rotationSliderValue, 2);
Grid.SetColumn(rotationSliderValue, 0);
Slider rotationSlider = new Slider
{
Maximum = 360
};
Grid.SetRow(rotationSlider, 2);
Grid.SetColumn(rotationSlider, 1);
// Set Bindings.
rotationSliderValue.BindingContext = rotationSlider;
rotationSliderValue.SetBinding(Label.TextProperty,
new Binding("Value", BindingMode.OneWay, null, null, "Rotation = {0:F0}"));
rotationSlider.BindingContext = label;
rotationSlider.SetBinding(Slider.ValueProperty,
new Binding("Rotation", BindingMode.TwoWay));
// Label and Slider for AnchorX property.
Label anchorxStepperValue = new Label
{
VerticalTextAlignment = TextAlignment.Center
};
Grid.SetRow(anchorxStepperValue, 3);
Grid.SetColumn(anchorxStepperValue, 0);
Stepper anchorxStepper = new Stepper
{
Maximum = 2,
Minimum = -1,
Increment = 0.5
};
Grid.SetRow(anchorxStepper, 3);
Grid.SetColumn(anchorxStepper, 1);
// Set bindings.
anchorxStepperValue.BindingContext = anchorxStepper;
anchorxStepperValue.SetBinding(Label.TextProperty,
new Binding("Value", BindingMode.OneWay, null, null, "AnchorX = {0:F1}"));
anchorxStepper.BindingContext = label;
anchorxStepper.SetBinding(Stepper.ValueProperty,
new Binding("AnchorX", BindingMode.TwoWay));
// Label and Slider for AnchorY property.
Label anchoryStepperValue = new Label
{
VerticalTextAlignment = TextAlignment.Center
};
Grid.SetRow(anchoryStepperValue, 4);
Grid.SetColumn(anchoryStepperValue, 0);
Stepper anchoryStepper = new Stepper
{
Maximum = 2,
Minimum = -1,
Increment = 0.5
};
Grid.SetRow(anchoryStepper, 4);
Grid.SetColumn(anchoryStepper, 1);
// Set bindings.
anchoryStepperValue.BindingContext = anchoryStepper;
anchoryStepperValue.SetBinding(Label.TextProperty,
new Binding("Value", BindingMode.OneWay, null, null, "AnchorY = {0:F1}"));
anchoryStepper.BindingContext = label;
anchoryStepper.SetBinding(Stepper.ValueProperty,
new Binding("AnchorY", BindingMode.TwoWay));
// Assemble the page.
Content = new StackLayout
{
Children =
{
label,
new Grid
{
Padding = 10,
RowDefinitions =
{
new RowDefinition { Height = GridLength.Auto },
new RowDefinition { Height = GridLength.Auto },
new RowDefinition { Height = GridLength.Auto },
new RowDefinition { Height = GridLength.Auto },
new RowDefinition { Height = GridLength.Auto },
},
ColumnDefinitions =
{
new ColumnDefinition { Width = GridLength.Auto },
new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star)}
},
Children =
{
scaleSliderValue,
scaleSlider,
scaleXSliderValue,
scaleXSlider,
rotationSliderValue,
rotationSlider,
anchorxStepperValue,
anchorxStepper,
anchoryStepperValue,
anchoryStepper
}
}
}
};
}
}
}
| 26.805405 | 79 | 0.688445 | [
"MIT"
] | jongalloway/maui | src/ControlGallery/src/Xamarin.Forms.Controls/GalleryPages/ScaleRotate.cs | 4,961 | C# |
using System.ComponentModel.DataAnnotations;
using System.Text.Json.Serialization;
namespace VaccineVerify.Controllers
{
///{
/// "presentationType": "QueryByFrame",
/// "challengeId": "RhOtpTa8vNh1EId6sJ7AVD3prerMMDSkfWZrUPzt",
/// "claims": {
/// "id": "did:key:z6MkmGHPWdKjLqiTydLHvRRdHPNDdUDKDudjiF87RNFjM2fb",
/// "http://schema.org/country_of_vaccination": "CH",
/// "http://schema.org/date_of_birth": "1953-07-21",
/// "http://schema.org/family_name": "Bob",
/// "http://schema.org/given_name": "Lammy",
/// "http://schema.org/medicinal_product_code": "Pfizer/BioNTech Comirnaty EU/1/20/1528",
/// "http://schema.org/number_of_doses": "2",
/// "http://schema.org/total_number_of_doses": "2",
/// "http://schema.org/vaccination_date": "2021-05-12"
/// },
/// "verified": true,
/// "holder": "did:key:z6MkmGHPWdKjLqiTydLHvRRdHPNDdUDKDudjiF87RNFjM2fb"
///}
public class VerifiedVaccinationData
{
[JsonPropertyName("presentationType")]
public string PresentationType { get; set; }
[Key]
[JsonPropertyName("challengeId")]
public string ChallengeId { get; set; }
[JsonPropertyName("claims")]
public VerifiedVaccinationDataClaims Claims { get; set; } = new VerifiedVaccinationDataClaims();
[JsonPropertyName("verified")]
public bool Verified { get; set; }
[JsonPropertyName("holder")]
public string Holder { get; set; }
}
}
| 40.4 | 105 | 0.597772 | [
"MIT"
] | swiss-ssi-group/MattrZeroKnowledgeProofsAspNetCore | src/VaccineVerify/Controllers/VerifiedVaccinationData.cs | 1,618 | C# |
// Copyright (c) Teroneko.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Linq;
namespace Teronis.Extensions
{
public static class EnumExtensions
{
public const bool IgnoreZeroWhenCrushingContainingBits = false;
public static IEnumerable<EnumType> CrushContainingBitsToEnumerable<EnumType>(this EnumType enumValue, bool ignoreZero = IgnoreZeroWhenCrushingContainingBits)
where EnumType : struct, IComparable, IFormattable, IConvertible
{
var enumValue2 = (Enum)(object)enumValue;
var enumerator = Enum.GetValues(typeof(EnumType)).GetEnumerator();
bool hasFlag(out EnumType enumValue3) =>
enumValue2.HasFlag((Enum)(object)(enumValue3 = (EnumType)enumerator.Current!));
if (enumerator.MoveNext() && !ignoreZero && hasFlag(out var enumValue4)) {
yield return enumValue4;
}
while (enumerator.MoveNext() && hasFlag(out enumValue4)) {
yield return enumValue4;
}
}
public static EnumType[] CrushContainingBitsToArray<EnumType>(this EnumType enumValue, bool ignoreZero = IgnoreZeroWhenCrushingContainingBits)
where EnumType : struct, IComparable, IFormattable, IConvertible
=> CrushContainingBitsToEnumerable(enumValue, ignoreZero).ToArray();
public static EnumType CombineEachEnumValue<EnumType>() where EnumType : struct, IComparable, IFormattable, IConvertible
{
var retVal = 0;
foreach (var enumVal in Enum.GetValues(typeof(EnumType)).Cast<int>()) {
retVal |= enumVal;
}
return (EnumType)(object)retVal;
}
}
}
| 38.354167 | 166 | 0.66214 | [
"MIT"
] | Teroneko-NET-Tools/Teronis.NetStandard.Core | src/Core/src/Extensions/EnumExtensions.cs | 1,843 | C# |
// ======================================
// Copyright © 2019 Vadim Prokopchuk. All rights reserved.
// Contacts: mailvadimprokopchuk@gmail.com
// License: http://opensource.org/licenses/MIT
// ======================================
using System.Web.Http;
namespace LR3
{
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
}
}
}
| 25.421053 | 65 | 0.569358 | [
"MIT"
] | VadimProkopchuk/PRM | LR3/Global.asax.cs | 486 | C# |
using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("AWSSDK.Lex")]
#if BCL35
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - Amazon Lex Runtime Service. Amazon Lex is a service for building conversational interactions into any application using voice or text.")]
#elif BCL45
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (4.5) - Amazon Lex Runtime Service. Amazon Lex is a service for building conversational interactions into any application using voice or text.")]
#elif PCL
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (PCL) - Amazon Lex Runtime Service. Amazon Lex is a service for building conversational interactions into any application using voice or text.")]
#elif UNITY
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (Unity) - Amazon Lex Runtime Service. Amazon Lex is a service for building conversational interactions into any application using voice or text.")]
#elif NETSTANDARD13
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 1.3)- Amazon Lex Runtime Service. Amazon Lex is a service for building conversational interactions into any application using voice or text.")]
#elif NETSTANDARD20
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 2.0)- Amazon Lex Runtime Service. Amazon Lex is a service for building conversational interactions into any application using voice or text.")]
#else
#error Unknown platform constant - unable to set correct AssemblyDescription
#endif
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("Amazon Web Services SDK for .NET")]
[assembly: AssemblyCompany("Amazon.com, Inc")]
[assembly: AssemblyCopyright("Copyright 2009-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("3.3")]
[assembly: AssemblyFileVersion("3.3.100.7")]
#if WINDOWS_PHONE || UNITY
[assembly: System.CLSCompliant(false)]
# else
[assembly: System.CLSCompliant(true)]
#endif
#if BCL
[assembly: System.Security.AllowPartiallyTrustedCallers]
#endif | 50.881356 | 225 | 0.775816 | [
"Apache-2.0"
] | FoxBearBear/aws-sdk-net | sdk/src/Services/Lex/Properties/AssemblyInfo.cs | 3,002 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
namespace Zenva.VR
{
[RequireComponent(typeof(Collider))]
[RequireComponent(typeof(Rigidbody))]
public class Grabbable : MonoBehaviour
{
// options when releasing the item
public enum ReleaseAction { nothing, backToOrigin, throws }
[Tooltip("Does it face the foward direction of the hand that grabs it")]
public bool facesForward;
[Tooltip("What happens when releasing")]
public ReleaseAction releaseAction;
[Tooltip("Event triggered when grabbing")]
public UnityEvent OnGrab;
[Tooltip("Event triggered when releasing")]
public UnityEvent OnRelease;
// who is grabbing this
GrabController grabCtrl;
// original position and rotation
Vector3 originalPosition;
Quaternion originalRotation;
// original parent
Transform originalParent;
// rigid body
Rigidbody rb;
// original kinematic status
bool isKinematic;
// keep track of the controller velocity for throwing
Vector3 ctrlVelocity;
Vector3 prevPosition;
void Awake()
{
rb = GetComponent<Rigidbody>();
isKinematic = rb.isKinematic;
originalParent = transform.parent;
}
void FixedUpdate()
{
// calculate the velocity based on the previous and current position
if(grabCtrl && releaseAction == ReleaseAction.throws)
{
ctrlVelocity = (transform.position - prevPosition) / Time.fixedDeltaTime;
prevPosition = transform.position;
}
}
public void Grab(GrabController grabCtrl)
{
// can be called if already grabbing
if (this.grabCtrl) return;
this.grabCtrl = grabCtrl;
// keep for when releasing
originalPosition = transform.position;
originalRotation = transform.rotation;
prevPosition = originalPosition;
// face to the same direction as the controller
if (facesForward)
transform.forward = grabCtrl.transform.forward;
// set as child of the controller
transform.parent = grabCtrl.transform;
// set rigidbody to kinematic
rb.isKinematic = true;
// trigger event
OnGrab.Invoke();
}
public void Release()
{
// can't be called if not grabbing
if (!grabCtrl) return;
// return to it's original parent if any
transform.parent = originalParent;
// restore rigid body
rb.isKinematic = isKinematic;
// handle release actions
switch (releaseAction)
{
case ReleaseAction.backToOrigin:
BackToOrigin();
break;
case ReleaseAction.throws:
ThrowItem();
break;
}
// trigger event
OnRelease.Invoke();
// disconnect from controller
grabCtrl = null;
}
void BackToOrigin()
{
transform.position = originalPosition;
transform.rotation = originalRotation;
}
void ThrowItem()
{
// needs a non-kinematic RB
rb.isKinematic = false;
// set controller velocity
rb.velocity = ctrlVelocity;
}
}
}
| 26.891304 | 89 | 0.55322 | [
"MIT"
] | ReanSchwarzer1/VR-FPRPG-Proto | Assets/ZenvaVR/ZenvaVR/Toolkit/Scripts/Grabbable.cs | 3,713 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using SmallCode_Website.Data;
using SmallCode_Website.Models;
namespace SmallCode_Website.Pages
{
public class HomeModel : PageModel
{
private UsersDBContext _db;
public List<Codes> _allCode;
public HomeModel(UsersDBContext db)
{
_db = db;
List < Codes > codes= _db.Codes.ToList();
_allCode = codes;
}
public void OnGet()
{
}
}
}
| 20.6 | 53 | 0.642395 | [
"MIT"
] | saliherdemk/Smallcode-Website | SmallCode Website/Pages/Home.cshtml.cs | 618 | C# |
using EPAS.DataEntity.Entity.Common;
using System.ComponentModel;
namespace EPAS.DataEntity.Enum
{
//生产物料预约状态
public enum RegisterWarehouseAppointmentStatus
{
[DescriptionAttribute("zh-CN,成功;en-US,Success;")]
Success = 1,
[DescriptionAttribute("zh-CN,失败;en-US,Fail")]
Fail = 2,
[DescriptionAttribute("zh-CN,取消;en-US,Cancel")]
Cancel = 3
}
}
| 17.25 | 57 | 0.63285 | [
"MPL-2.0"
] | whw0828/EPASServer | EPASFramework/EPAS.DataEntity/Enum/RegisterWarehouseAppointmentStatus.cs | 444 | C# |
using System;
using System.Collections.Generic;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using ProtoBuf;
namespace ET
{
[ProtoContract]
[Config]
public partial class SkillConfigCategory : ProtoObject
{
public static SkillConfigCategory Instance;
[ProtoIgnore]
[BsonIgnore]
private Dictionary<int, SkillConfig> dict = new Dictionary<int, SkillConfig>();
[BsonElement]
[ProtoMember(1)]
private List<SkillConfig> list = new List<SkillConfig>();
public SkillConfigCategory()
{
Instance = this;
}
[ProtoAfterDeserialization]
public void AfterDeserialization()
{
foreach (SkillConfig config in list)
{
this.dict.Add(config.Id, config);
}
list.Clear();
this.EndInit();
}
public SkillConfig Get(int id)
{
this.dict.TryGetValue(id, out SkillConfig item);
if (item == null)
{
throw new Exception($"配置找不到,配置表名: {nameof (SkillConfig)},配置id: {id}");
}
return item;
}
public bool Contain(int id)
{
return this.dict.ContainsKey(id);
}
public Dictionary<int, SkillConfig> GetAll()
{
return this.dict;
}
public SkillConfig GetOne()
{
if (this.dict == null || this.dict.Count <= 0)
{
return null;
}
return this.dict.Values.GetEnumerator().Current;
}
}
[ProtoContract]
public partial class SkillConfig: ProtoObject, IConfig
{
[ProtoMember(1, IsRequired = true)]
public int Id { get; set; }
[ProtoMember(2, IsRequired = true)]
public string Name { get; set; }
[ProtoMember(3, IsRequired = true)]
public string Desc { get; set; }
[ProtoMember(4, IsRequired = true)]
public string Icon { get; set; }
[ProtoMember(5, IsRequired = true)]
public int SkillLoop { get; set; }
[BsonRepresentation(BsonType.Double, AllowTruncation = true)]
[ProtoMember(6, IsRequired = true)]
public float MaxRadius { get; set; }
[ProtoMember(7, IsRequired = true)]
public string TargetCamp { get; set; }
[ProtoMember(8, IsRequired = true)]
public string TargetType { get; set; }
[ProtoMember(9, IsRequired = true)]
public string DamageType { get; set; }
[ProtoMember(10, IsRequired = true)]
public string DamageScale { get; set; }
[BsonRepresentation(BsonType.Double, AllowTruncation = true)]
[ProtoMember(11, IsRequired = true)]
public float SkillTime { get; set; }
[ProtoMember(12, IsRequired = true)]
public string SkillTree { get; set; }
[ProtoMember(13, IsRequired = true)]
public string LevelData { get; set; }
[ProtoAfterDeserialization]
public void AfterDeserialization()
{
this.EndInit();
}
}
}
| 27 | 87 | 0.590924 | [
"MIT"
] | chengxu-yh/ET | Unity/Assets/Model/Generate/Config/SkillConfig.cs | 3,023 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Xml.XPath;
using ILLink.Shared;
using Mono.Cecil;
namespace Mono.Linker.Steps
{
public class DescriptorMarker : ProcessLinkerXmlBase
{
const string NamespaceElementName = "namespace";
const string _required = "required";
const string _preserve = "preserve";
const string _accessors = "accessors";
static readonly string[] _accessorsAll = new string[] { "all" };
static readonly char[] _accessorsSep = new char[] { ';' };
public DescriptorMarker(LinkContext context, Stream documentStream, string xmlDocumentLocation)
: base(context, documentStream, xmlDocumentLocation)
{
}
public DescriptorMarker(LinkContext context, Stream documentStream, EmbeddedResource resource, AssemblyDefinition resourceAssembly, string xmlDocumentLocation = "<unspecified>")
: base(context, documentStream, resource, resourceAssembly, xmlDocumentLocation)
{
}
public void Mark()
{
bool stripDescriptors = _context.IsOptimizationEnabled(CodeOptimizations.RemoveDescriptors, _resource?.Assembly);
ProcessXml(stripDescriptors, _context.IgnoreDescriptors);
}
protected override AllowedAssemblies AllowedAssemblySelector { get => AllowedAssemblies.AnyAssembly; }
protected override void ProcessAssembly(AssemblyDefinition assembly, XPathNavigator nav, bool warnOnUnresolvedTypes)
{
if (GetTypePreserve(nav) == TypePreserve.All)
{
foreach (var type in assembly.MainModule.Types)
MarkAndPreserveAll(type, nav);
foreach (var exportedType in assembly.MainModule.ExportedTypes)
_context.MarkingHelpers.MarkExportedType(exportedType, assembly.MainModule, new DependencyInfo(DependencyKind.XmlDescriptor, assembly.MainModule), GetMessageOriginForPosition(nav));
}
else
{
ProcessTypes(assembly, nav, warnOnUnresolvedTypes);
ProcessNamespaces(assembly, nav);
}
}
void ProcessNamespaces(AssemblyDefinition assembly, XPathNavigator nav)
{
foreach (XPathNavigator namespaceNav in nav.SelectChildren(NamespaceElementName, XmlNamespace))
{
if (!ShouldProcessElement(namespaceNav))
continue;
string fullname = GetFullName(namespaceNav);
bool foundMatch = false;
foreach (TypeDefinition type in assembly.MainModule.Types)
{
if (type.Namespace != fullname)
continue;
foundMatch = true;
MarkAndPreserveAll(type, nav);
}
if (!foundMatch)
{
LogWarning(namespaceNav, DiagnosticId.XmlCouldNotFindAnyTypeInNamespace, fullname);
}
}
}
void MarkAndPreserveAll(TypeDefinition type, XPathNavigator nav)
{
_context.Annotations.Mark(type, new DependencyInfo(DependencyKind.XmlDescriptor, _xmlDocumentLocation), GetMessageOriginForPosition(nav));
_context.Annotations.SetPreserve(type, TypePreserve.All);
if (!type.HasNestedTypes)
return;
foreach (TypeDefinition nested in type.NestedTypes)
MarkAndPreserveAll(nested, nav);
}
protected override TypeDefinition? ProcessExportedType(ExportedType exported, AssemblyDefinition assembly, XPathNavigator nav)
{
_context.MarkingHelpers.MarkExportedType(exported, assembly.MainModule, new DependencyInfo(DependencyKind.XmlDescriptor, _xmlDocumentLocation), GetMessageOriginForPosition(nav));
return base.ProcessExportedType(exported, assembly, nav);
}
protected override void ProcessType(TypeDefinition type, XPathNavigator nav)
{
Debug.Assert(ShouldProcessElement(nav));
TypePreserve preserve = GetTypePreserve(nav);
switch (preserve)
{
case TypePreserve.Fields when !type.HasFields:
LogWarning(nav, DiagnosticId.TypeHasNoFieldsToPreserve, type.GetDisplayName());
break;
case TypePreserve.Methods when !type.HasMethods:
LogWarning(nav, DiagnosticId.TypeHasNoMethodsToPreserve, type.GetDisplayName());
break;
case TypePreserve.Fields:
case TypePreserve.Methods:
case TypePreserve.All:
_context.Annotations.SetPreserve(type, preserve);
break;
}
bool required = IsRequired(nav);
ProcessTypeChildren(type, nav, required);
if (!required)
return;
_context.Annotations.Mark(type, new DependencyInfo(DependencyKind.XmlDescriptor, _xmlDocumentLocation), GetMessageOriginForPosition(nav));
if (type.IsNested)
{
var currentType = type;
while (currentType.IsNested)
{
var parent = currentType.DeclaringType;
_context.Annotations.Mark(parent, new DependencyInfo(DependencyKind.DeclaringType, currentType), GetMessageOriginForPosition(nav));
currentType = parent;
}
}
}
static TypePreserve GetTypePreserve(XPathNavigator nav)
{
string attribute = GetAttribute(nav, _preserve);
if (string.IsNullOrEmpty(attribute))
return nav.HasChildren ? TypePreserve.Nothing : TypePreserve.All;
if (Enum.TryParse(attribute, true, out TypePreserve result))
return result;
return TypePreserve.Nothing;
}
protected override void ProcessField(TypeDefinition type, FieldDefinition field, XPathNavigator nav)
{
if (_context.Annotations.IsMarked(field))
LogWarning(nav, DiagnosticId.XmlDuplicatePreserveMember, field.FullName);
_context.Annotations.Mark(field, new DependencyInfo(DependencyKind.XmlDescriptor, _xmlDocumentLocation), GetMessageOriginForPosition(nav));
}
protected override void ProcessMethod(TypeDefinition type, MethodDefinition method, XPathNavigator nav, object? customData)
{
if (_context.Annotations.IsMarked(method))
LogWarning(nav, DiagnosticId.XmlDuplicatePreserveMember, method.GetDisplayName());
_context.Annotations.MarkIndirectlyCalledMethod(method);
_context.Annotations.SetAction(method, MethodAction.Parse);
if (customData is bool required && !required)
{
_context.Annotations.AddPreservedMethod(type, method);
}
else
{
_context.Annotations.Mark(method, new DependencyInfo(DependencyKind.XmlDescriptor, _xmlDocumentLocation), GetMessageOriginForPosition(nav));
}
}
void ProcessMethodIfNotNull(TypeDefinition type, MethodDefinition method, XPathNavigator nav, object? customData)
{
if (method == null)
return;
ProcessMethod(type, method, nav, customData);
}
protected override MethodDefinition? GetMethod(TypeDefinition type, string signature)
{
if (type.HasMethods)
foreach (MethodDefinition meth in type.Methods)
if (signature == GetMethodSignature(meth, false))
return meth;
return null;
}
public static string GetMethodSignature(MethodDefinition meth, bool includeGenericParameters)
{
StringBuilder sb = new StringBuilder();
sb.Append(meth.ReturnType.FullName);
sb.Append(" ");
sb.Append(meth.Name);
if (includeGenericParameters && meth.HasGenericParameters)
{
sb.Append("`");
sb.Append(meth.GenericParameters.Count);
}
sb.Append("(");
if (meth.HasParameters)
{
for (int i = 0; i < meth.Parameters.Count; i++)
{
if (i > 0)
sb.Append(",");
sb.Append(meth.Parameters[i].ParameterType.FullName);
}
}
sb.Append(")");
return sb.ToString();
}
protected override void ProcessEvent(TypeDefinition type, EventDefinition @event, XPathNavigator nav, object? customData)
{
if (_context.Annotations.IsMarked(@event))
LogWarning(nav, DiagnosticId.XmlDuplicatePreserveMember, @event.FullName);
ProcessMethod(type, @event.AddMethod, nav, customData);
ProcessMethod(type, @event.RemoveMethod, nav, customData);
ProcessMethodIfNotNull(type, @event.InvokeMethod, nav, customData);
}
protected override void ProcessProperty(TypeDefinition type, PropertyDefinition property, XPathNavigator nav, object? customData, bool fromSignature)
{
string[] accessors = fromSignature ? GetAccessors(nav) : _accessorsAll;
if (_context.Annotations.IsMarked(property))
LogWarning(nav, DiagnosticId.XmlDuplicatePreserveMember, property.FullName);
if (Array.IndexOf(accessors, "all") >= 0)
{
ProcessMethodIfNotNull(type, property.GetMethod, nav, customData);
ProcessMethodIfNotNull(type, property.SetMethod, nav, customData);
return;
}
if (property.GetMethod != null && Array.IndexOf(accessors, "get") >= 0)
ProcessMethod(type, property.GetMethod, nav, customData);
else if (property.GetMethod == null)
LogWarning(nav, DiagnosticId.XmlCouldNotFindGetAccesorOfPropertyOnType, property.Name, type.FullName);
if (property.SetMethod != null && Array.IndexOf(accessors, "set") >= 0)
ProcessMethod(type, property.SetMethod, nav, customData);
else if (property.SetMethod == null)
LogWarning(nav, DiagnosticId.XmlCouldNotFindSetAccesorOfPropertyOnType, property.Name, type.FullName);
}
static bool IsRequired(XPathNavigator nav)
{
string attribute = GetAttribute(nav, _required);
if (attribute == null || attribute.Length == 0)
return true;
return bool.TryParse(attribute, out bool result) && result;
}
protected static string[] GetAccessors(XPathNavigator nav)
{
string accessorsValue = GetAttribute(nav, _accessors);
if (accessorsValue != null)
{
string[] accessors = accessorsValue.Split(
_accessorsSep, StringSplitOptions.RemoveEmptyEntries);
if (accessors.Length > 0)
{
for (int i = 0; i < accessors.Length; ++i)
accessors[i] = accessors[i].ToLower();
return accessors;
}
}
return _accessorsAll;
}
}
}
| 39.931741 | 201 | 0.606667 | [
"MIT"
] | 333fred/runtime | src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ReferenceSource/DescriptorMarker.cs | 11,700 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections;
using System.Collections.Generic;
namespace System.ServiceModel.Channels
{
public sealed class UnderstoodHeaders : IEnumerable<MessageHeaderInfo>
{
private MessageHeaders _messageHeaders;
private bool _modified;
internal UnderstoodHeaders(MessageHeaders messageHeaders, bool modified)
{
_messageHeaders = messageHeaders;
_modified = modified;
}
internal bool Modified
{
get { return _modified; }
set { _modified = value; }
}
public void Add(MessageHeaderInfo headerInfo)
{
_messageHeaders.AddUnderstood(headerInfo);
_modified = true;
}
public bool Contains(MessageHeaderInfo headerInfo)
{
return _messageHeaders.IsUnderstood(headerInfo);
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
public IEnumerator<MessageHeaderInfo> GetEnumerator()
{
return _messageHeaders.GetUnderstoodEnumerator();
}
public void Remove(MessageHeaderInfo headerInfo)
{
_messageHeaders.RemoveUnderstood(headerInfo);
_modified = true;
}
}
}
| 26.962963 | 101 | 0.626374 | [
"MIT"
] | 777Eternal777/wcf | src/System.Private.ServiceModel/src/System/ServiceModel/Channels/UnderstoodHeaders.cs | 1,456 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MDC.Domain.Entities;
using MDC.Domain.Interfaces.Repository;
using MDC.Domain.Tools;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace MDC.WebApi.Controllers
{
[Produces("application/json")]
[Route("store")]
public class StoreController : Controller
{
private readonly IStoreRepository _storeRepository;
public StoreController(IStoreRepository storeRepository)
{
_storeRepository = storeRepository;
}
// GET: store
[HttpGet]
public IEnumerable<Store> Get()
{
return _storeRepository.GetAll();
}
// GET: store/5
[HttpGet("{id}", Name = "GetStore")]
public Store Get(string id)
{
return _storeRepository.GetById(id);
}
// POST: store
[HttpPost]
public void Post([FromBody]Store value)
{
value.Id = GuidSqlite.getGuid();
_storeRepository.Add(value);
}
// PUT: api/store/5
[HttpPut("{id}")]
public void Put(string id, [FromBody]Store value)
{
_storeRepository.Update(value);
}
// DELETE: store/5
[HttpDelete("{id}")]
public void Delete(string id)
{
_storeRepository.Remove(id);
}
}
}
| 24.065574 | 64 | 0.575613 | [
"MIT"
] | MoniqueOliveiraApostolo/mdc | MDC/MDC.WebApi/Controllers/StoreController.cs | 1,470 | C# |
namespace Kaffee.Models
{
public class RefreshTokenRequest
{
public string RefreshToken { get; set; }
}
}
| 15.875 | 48 | 0.637795 | [
"MIT"
] | wel-shy/kaffee-api | src/Kaffee/Models/Requests/RefreshTokenRequest.cs | 127 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TRec.BusinessLayer
{
public class Goal : IComparable<Goal>
{
public Guid GoalId { get; set; }
public Guid UserId { get; set; }
public string Description { get; set; }
public string TargetMeasure { get; set; }
public DateTime TargetCompletionDate { get; set; }
public bool Completed { get; set; }
public string ResultMeasure { get; set; }
public int ResultMeasureRating { get; set; }
public DateTime ActualCompletionDate { get; set; }
public int ResultTimelinessRating { get; set; }
public string Positives { get; set; }
public string Improvements { get; set; }
#region IComparable<Goal> Members
public int CompareTo( Goal other )
{
return TargetCompletionDate.CompareTo( other.TargetCompletionDate );
}
#endregion
}
}
| 23 | 81 | 0.597101 | [
"MIT"
] | PaulBenfield/TRec | TRec.BusinessLayer/Goal.cs | 1,037 | C# |
using SEDC.Class07.MovieStore.Entities.BaseModels;
using SEDC.Class07.MovieStore.Entities.Enumerations;
using System;
using System.Collections.Generic;
using System.Text;
namespace SEDC.Class07.MovieStore.Entities.Models
{
public class Employee : Member
{
private double Salary { get; set; }
public double HoursPerMonth { get; set; }
public double Bonus { get; set; }
public Employee(string firstName, string lastName, int age, string userName, string password, int phoneNumber, Role role, double hoursPerMonth)
: base(firstName, lastName, age, userName, password, phoneNumber, role)
{
Salary = 300;
HoursPerMonth = hoursPerMonth;
}
public double SetBonus(double hoursPerMonth)
{
if (HoursPerMonth <= 160)
{
Bonus = 1;
}
else
{
Bonus = 1.3;
}
return Bonus;
}
public double GetBasicSalary()
{
return Salary;
}
public double SetSalary()
{
Salary = Salary * SetBonus(HoursPerMonth);
return Salary;
}
}
}
| 24.352941 | 151 | 0.555556 | [
"MIT"
] | vladimir-koloski/C-Homeworks | Homework01/SEDC.Class07.MovieStore/SEDC.Class07.MovieStore.BaseModels/Models/Employee.cs | 1,244 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace FluentFTP {
/// <summary>
/// The result of an upload or download operation
/// </summary>
public enum FtpStatus {
/// <summary>
/// The upload or download failed with an error transfering, or the source file did not exist
/// </summary>
Failed = 0,
/// <summary>
/// The upload or download completed succesfully
/// </summary>
Success = 1,
/// <summary>
/// The upload or download was skipped because the file already existed on the target
/// </summary>
Skipped = 2
}
}
| 20.857143 | 95 | 0.666096 | [
"MIT"
] | 0xced/FluentFTP | FluentFTP/Enums/FtpStatus.cs | 586 | C# |
/*******************************************************************************
* Copyright 2012-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file.
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
* *****************************************************************************
*
* AWS Tools for Windows (TM) PowerShell (TM)
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using System.Text;
using Amazon.PowerShell.Common;
using Amazon.Runtime;
using Amazon.Redshift;
using Amazon.Redshift.Model;
namespace Amazon.PowerShell.Cmdlets.RS
{
/// <summary>
/// Modifies a scheduled action.
/// </summary>
[Cmdlet("Edit", "RSScheduledAction", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.Medium)]
[OutputType("Amazon.Redshift.Model.ModifyScheduledActionResponse")]
[AWSCmdlet("Calls the Amazon Redshift ModifyScheduledAction API operation.", Operation = new[] {"ModifyScheduledAction"}, SelectReturnType = typeof(Amazon.Redshift.Model.ModifyScheduledActionResponse))]
[AWSCmdletOutput("Amazon.Redshift.Model.ModifyScheduledActionResponse",
"This cmdlet returns an Amazon.Redshift.Model.ModifyScheduledActionResponse object containing multiple properties. The object can also be referenced from properties attached to the cmdlet entry in the $AWSHistory stack."
)]
public partial class EditRSScheduledActionCmdlet : AmazonRedshiftClientCmdlet, IExecutor
{
#region Parameter ResizeCluster_Classic
/// <summary>
/// <para>
/// <para>A boolean value indicating whether the resize operation is using the classic resize
/// process. If you don't provide this parameter or set the value to <code>false</code>,
/// the resize type is elastic. </para>
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
[Alias("TargetAction_ResizeCluster_Classic")]
public System.Boolean? ResizeCluster_Classic { get; set; }
#endregion
#region Parameter PauseCluster_ClusterIdentifier
/// <summary>
/// <para>
/// <para>The identifier of the cluster to be paused.</para>
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
[Alias("TargetAction_PauseCluster_ClusterIdentifier")]
public System.String PauseCluster_ClusterIdentifier { get; set; }
#endregion
#region Parameter ResizeCluster_ClusterIdentifier
/// <summary>
/// <para>
/// <para>The unique identifier for the cluster to resize.</para>
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
[Alias("TargetAction_ResizeCluster_ClusterIdentifier")]
public System.String ResizeCluster_ClusterIdentifier { get; set; }
#endregion
#region Parameter ResumeCluster_ClusterIdentifier
/// <summary>
/// <para>
/// <para>The identifier of the cluster to be resumed.</para>
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
[Alias("TargetAction_ResumeCluster_ClusterIdentifier")]
public System.String ResumeCluster_ClusterIdentifier { get; set; }
#endregion
#region Parameter ResizeCluster_ClusterType
/// <summary>
/// <para>
/// <para>The new cluster type for the specified cluster.</para>
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
[Alias("TargetAction_ResizeCluster_ClusterType")]
public System.String ResizeCluster_ClusterType { get; set; }
#endregion
#region Parameter Enable
/// <summary>
/// <para>
/// <para>A modified enable flag of the scheduled action. If true, the scheduled action is active.
/// If false, the scheduled action is disabled. </para>
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public System.Boolean? Enable { get; set; }
#endregion
#region Parameter EndTime
/// <summary>
/// <para>
/// <para>A modified end time of the scheduled action. For more information about this parameter,
/// see <a>ScheduledAction</a>. </para>
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public System.DateTime? EndTime { get; set; }
#endregion
#region Parameter IamRole
/// <summary>
/// <para>
/// <para>A different IAM role to assume to run the target action. For more information about
/// this parameter, see <a>ScheduledAction</a>.</para>
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public System.String IamRole { get; set; }
#endregion
#region Parameter ResizeCluster_NodeType
/// <summary>
/// <para>
/// <para>The new node type for the nodes you are adding. If not specified, the cluster's current
/// node type is used.</para>
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
[Alias("TargetAction_ResizeCluster_NodeType")]
public System.String ResizeCluster_NodeType { get; set; }
#endregion
#region Parameter ResizeCluster_NumberOfNode
/// <summary>
/// <para>
/// <para>The new number of nodes for the cluster. If not specified, the cluster's current number
/// of nodes is used.</para>
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
[Alias("TargetAction_ResizeCluster_NumberOfNodes")]
public System.Int32? ResizeCluster_NumberOfNode { get; set; }
#endregion
#region Parameter Schedule
/// <summary>
/// <para>
/// <para>A modified schedule in either <code>at( )</code> or <code>cron( )</code> format. For
/// more information about this parameter, see <a>ScheduledAction</a>.</para>
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public System.String Schedule { get; set; }
#endregion
#region Parameter ScheduledActionDescription
/// <summary>
/// <para>
/// <para>A modified description of the scheduled action. </para>
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public System.String ScheduledActionDescription { get; set; }
#endregion
#region Parameter ScheduledActionName
/// <summary>
/// <para>
/// <para>The name of the scheduled action to modify. </para>
/// </para>
/// </summary>
#if !MODULAR
[System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true)]
#else
[System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true, Mandatory = true)]
[System.Management.Automation.AllowEmptyString]
[System.Management.Automation.AllowNull]
#endif
[Amazon.PowerShell.Common.AWSRequiredParameter]
public System.String ScheduledActionName { get; set; }
#endregion
#region Parameter StartTime
/// <summary>
/// <para>
/// <para>A modified start time of the scheduled action. For more information about this parameter,
/// see <a>ScheduledAction</a>. </para>
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public System.DateTime? StartTime { get; set; }
#endregion
#region Parameter Select
/// <summary>
/// Use the -Select parameter to control the cmdlet output. The default value is '*'.
/// Specifying -Select '*' will result in the cmdlet returning the whole service response (Amazon.Redshift.Model.ModifyScheduledActionResponse).
/// Specifying the name of a property of type Amazon.Redshift.Model.ModifyScheduledActionResponse will result in that property being returned.
/// Specifying -Select '^ParameterName' will result in the cmdlet returning the selected cmdlet parameter value.
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public string Select { get; set; } = "*";
#endregion
#region Parameter PassThru
/// <summary>
/// Changes the cmdlet behavior to return the value passed to the ScheduledActionName parameter.
/// The -PassThru parameter is deprecated, use -Select '^ScheduledActionName' instead. This parameter will be removed in a future version.
/// </summary>
[System.Obsolete("The -PassThru parameter is deprecated, use -Select '^ScheduledActionName' instead. This parameter will be removed in a future version.")]
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public SwitchParameter PassThru { get; set; }
#endregion
#region Parameter Force
/// <summary>
/// This parameter overrides confirmation prompts to force
/// the cmdlet to continue its operation. This parameter should always
/// be used with caution.
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public SwitchParameter Force { get; set; }
#endregion
protected override void ProcessRecord()
{
base.ProcessRecord();
var resourceIdentifiersText = FormatParameterValuesForConfirmationMsg(nameof(this.ScheduledActionName), MyInvocation.BoundParameters);
if (!ConfirmShouldProceed(this.Force.IsPresent, resourceIdentifiersText, "Edit-RSScheduledAction (ModifyScheduledAction)"))
{
return;
}
var context = new CmdletContext();
// allow for manipulation of parameters prior to loading into context
PreExecutionContextLoad(context);
#pragma warning disable CS0618, CS0612 //A class member was marked with the Obsolete attribute
if (ParameterWasBound(nameof(this.Select)))
{
context.Select = CreateSelectDelegate<Amazon.Redshift.Model.ModifyScheduledActionResponse, EditRSScheduledActionCmdlet>(Select) ??
throw new System.ArgumentException("Invalid value for -Select parameter.", nameof(this.Select));
if (this.PassThru.IsPresent)
{
throw new System.ArgumentException("-PassThru cannot be used when -Select is specified.", nameof(this.Select));
}
}
else if (this.PassThru.IsPresent)
{
context.Select = (response, cmdlet) => this.ScheduledActionName;
}
#pragma warning restore CS0618, CS0612 //A class member was marked with the Obsolete attribute
context.Enable = this.Enable;
context.EndTime = this.EndTime;
context.IamRole = this.IamRole;
context.Schedule = this.Schedule;
context.ScheduledActionDescription = this.ScheduledActionDescription;
context.ScheduledActionName = this.ScheduledActionName;
#if MODULAR
if (this.ScheduledActionName == null && ParameterWasBound(nameof(this.ScheduledActionName)))
{
WriteWarning("You are passing $null as a value for parameter ScheduledActionName which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues.");
}
#endif
context.StartTime = this.StartTime;
context.PauseCluster_ClusterIdentifier = this.PauseCluster_ClusterIdentifier;
context.ResizeCluster_Classic = this.ResizeCluster_Classic;
context.ResizeCluster_ClusterIdentifier = this.ResizeCluster_ClusterIdentifier;
context.ResizeCluster_ClusterType = this.ResizeCluster_ClusterType;
context.ResizeCluster_NodeType = this.ResizeCluster_NodeType;
context.ResizeCluster_NumberOfNode = this.ResizeCluster_NumberOfNode;
context.ResumeCluster_ClusterIdentifier = this.ResumeCluster_ClusterIdentifier;
// allow further manipulation of loaded context prior to processing
PostExecutionContextLoad(context);
var output = Execute(context) as CmdletOutput;
ProcessOutput(output);
}
#region IExecutor Members
public object Execute(ExecutorContext context)
{
var cmdletContext = context as CmdletContext;
// create request
var request = new Amazon.Redshift.Model.ModifyScheduledActionRequest();
if (cmdletContext.Enable != null)
{
request.Enable = cmdletContext.Enable.Value;
}
if (cmdletContext.EndTime != null)
{
request.EndTime = cmdletContext.EndTime.Value;
}
if (cmdletContext.IamRole != null)
{
request.IamRole = cmdletContext.IamRole;
}
if (cmdletContext.Schedule != null)
{
request.Schedule = cmdletContext.Schedule;
}
if (cmdletContext.ScheduledActionDescription != null)
{
request.ScheduledActionDescription = cmdletContext.ScheduledActionDescription;
}
if (cmdletContext.ScheduledActionName != null)
{
request.ScheduledActionName = cmdletContext.ScheduledActionName;
}
if (cmdletContext.StartTime != null)
{
request.StartTime = cmdletContext.StartTime.Value;
}
// populate TargetAction
var requestTargetActionIsNull = true;
request.TargetAction = new Amazon.Redshift.Model.ScheduledActionType();
Amazon.Redshift.Model.PauseClusterMessage requestTargetAction_targetAction_PauseCluster = null;
// populate PauseCluster
var requestTargetAction_targetAction_PauseClusterIsNull = true;
requestTargetAction_targetAction_PauseCluster = new Amazon.Redshift.Model.PauseClusterMessage();
System.String requestTargetAction_targetAction_PauseCluster_pauseCluster_ClusterIdentifier = null;
if (cmdletContext.PauseCluster_ClusterIdentifier != null)
{
requestTargetAction_targetAction_PauseCluster_pauseCluster_ClusterIdentifier = cmdletContext.PauseCluster_ClusterIdentifier;
}
if (requestTargetAction_targetAction_PauseCluster_pauseCluster_ClusterIdentifier != null)
{
requestTargetAction_targetAction_PauseCluster.ClusterIdentifier = requestTargetAction_targetAction_PauseCluster_pauseCluster_ClusterIdentifier;
requestTargetAction_targetAction_PauseClusterIsNull = false;
}
// determine if requestTargetAction_targetAction_PauseCluster should be set to null
if (requestTargetAction_targetAction_PauseClusterIsNull)
{
requestTargetAction_targetAction_PauseCluster = null;
}
if (requestTargetAction_targetAction_PauseCluster != null)
{
request.TargetAction.PauseCluster = requestTargetAction_targetAction_PauseCluster;
requestTargetActionIsNull = false;
}
Amazon.Redshift.Model.ResumeClusterMessage requestTargetAction_targetAction_ResumeCluster = null;
// populate ResumeCluster
var requestTargetAction_targetAction_ResumeClusterIsNull = true;
requestTargetAction_targetAction_ResumeCluster = new Amazon.Redshift.Model.ResumeClusterMessage();
System.String requestTargetAction_targetAction_ResumeCluster_resumeCluster_ClusterIdentifier = null;
if (cmdletContext.ResumeCluster_ClusterIdentifier != null)
{
requestTargetAction_targetAction_ResumeCluster_resumeCluster_ClusterIdentifier = cmdletContext.ResumeCluster_ClusterIdentifier;
}
if (requestTargetAction_targetAction_ResumeCluster_resumeCluster_ClusterIdentifier != null)
{
requestTargetAction_targetAction_ResumeCluster.ClusterIdentifier = requestTargetAction_targetAction_ResumeCluster_resumeCluster_ClusterIdentifier;
requestTargetAction_targetAction_ResumeClusterIsNull = false;
}
// determine if requestTargetAction_targetAction_ResumeCluster should be set to null
if (requestTargetAction_targetAction_ResumeClusterIsNull)
{
requestTargetAction_targetAction_ResumeCluster = null;
}
if (requestTargetAction_targetAction_ResumeCluster != null)
{
request.TargetAction.ResumeCluster = requestTargetAction_targetAction_ResumeCluster;
requestTargetActionIsNull = false;
}
Amazon.Redshift.Model.ResizeClusterMessage requestTargetAction_targetAction_ResizeCluster = null;
// populate ResizeCluster
var requestTargetAction_targetAction_ResizeClusterIsNull = true;
requestTargetAction_targetAction_ResizeCluster = new Amazon.Redshift.Model.ResizeClusterMessage();
System.Boolean? requestTargetAction_targetAction_ResizeCluster_resizeCluster_Classic = null;
if (cmdletContext.ResizeCluster_Classic != null)
{
requestTargetAction_targetAction_ResizeCluster_resizeCluster_Classic = cmdletContext.ResizeCluster_Classic.Value;
}
if (requestTargetAction_targetAction_ResizeCluster_resizeCluster_Classic != null)
{
requestTargetAction_targetAction_ResizeCluster.Classic = requestTargetAction_targetAction_ResizeCluster_resizeCluster_Classic.Value;
requestTargetAction_targetAction_ResizeClusterIsNull = false;
}
System.String requestTargetAction_targetAction_ResizeCluster_resizeCluster_ClusterIdentifier = null;
if (cmdletContext.ResizeCluster_ClusterIdentifier != null)
{
requestTargetAction_targetAction_ResizeCluster_resizeCluster_ClusterIdentifier = cmdletContext.ResizeCluster_ClusterIdentifier;
}
if (requestTargetAction_targetAction_ResizeCluster_resizeCluster_ClusterIdentifier != null)
{
requestTargetAction_targetAction_ResizeCluster.ClusterIdentifier = requestTargetAction_targetAction_ResizeCluster_resizeCluster_ClusterIdentifier;
requestTargetAction_targetAction_ResizeClusterIsNull = false;
}
System.String requestTargetAction_targetAction_ResizeCluster_resizeCluster_ClusterType = null;
if (cmdletContext.ResizeCluster_ClusterType != null)
{
requestTargetAction_targetAction_ResizeCluster_resizeCluster_ClusterType = cmdletContext.ResizeCluster_ClusterType;
}
if (requestTargetAction_targetAction_ResizeCluster_resizeCluster_ClusterType != null)
{
requestTargetAction_targetAction_ResizeCluster.ClusterType = requestTargetAction_targetAction_ResizeCluster_resizeCluster_ClusterType;
requestTargetAction_targetAction_ResizeClusterIsNull = false;
}
System.String requestTargetAction_targetAction_ResizeCluster_resizeCluster_NodeType = null;
if (cmdletContext.ResizeCluster_NodeType != null)
{
requestTargetAction_targetAction_ResizeCluster_resizeCluster_NodeType = cmdletContext.ResizeCluster_NodeType;
}
if (requestTargetAction_targetAction_ResizeCluster_resizeCluster_NodeType != null)
{
requestTargetAction_targetAction_ResizeCluster.NodeType = requestTargetAction_targetAction_ResizeCluster_resizeCluster_NodeType;
requestTargetAction_targetAction_ResizeClusterIsNull = false;
}
System.Int32? requestTargetAction_targetAction_ResizeCluster_resizeCluster_NumberOfNode = null;
if (cmdletContext.ResizeCluster_NumberOfNode != null)
{
requestTargetAction_targetAction_ResizeCluster_resizeCluster_NumberOfNode = cmdletContext.ResizeCluster_NumberOfNode.Value;
}
if (requestTargetAction_targetAction_ResizeCluster_resizeCluster_NumberOfNode != null)
{
requestTargetAction_targetAction_ResizeCluster.NumberOfNodes = requestTargetAction_targetAction_ResizeCluster_resizeCluster_NumberOfNode.Value;
requestTargetAction_targetAction_ResizeClusterIsNull = false;
}
// determine if requestTargetAction_targetAction_ResizeCluster should be set to null
if (requestTargetAction_targetAction_ResizeClusterIsNull)
{
requestTargetAction_targetAction_ResizeCluster = null;
}
if (requestTargetAction_targetAction_ResizeCluster != null)
{
request.TargetAction.ResizeCluster = requestTargetAction_targetAction_ResizeCluster;
requestTargetActionIsNull = false;
}
// determine if request.TargetAction should be set to null
if (requestTargetActionIsNull)
{
request.TargetAction = null;
}
CmdletOutput output;
// issue call
var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint);
try
{
var response = CallAWSServiceOperation(client, request);
object pipelineOutput = null;
pipelineOutput = cmdletContext.Select(response, this);
output = new CmdletOutput
{
PipelineOutput = pipelineOutput,
ServiceResponse = response
};
}
catch (Exception e)
{
output = new CmdletOutput { ErrorResponse = e };
}
return output;
}
public ExecutorContext CreateContext()
{
return new CmdletContext();
}
#endregion
#region AWS Service Operation Call
private Amazon.Redshift.Model.ModifyScheduledActionResponse CallAWSServiceOperation(IAmazonRedshift client, Amazon.Redshift.Model.ModifyScheduledActionRequest request)
{
Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "Amazon Redshift", "ModifyScheduledAction");
try
{
#if DESKTOP
return client.ModifyScheduledAction(request);
#elif CORECLR
return client.ModifyScheduledActionAsync(request).GetAwaiter().GetResult();
#else
#error "Unknown build edition"
#endif
}
catch (AmazonServiceException exc)
{
var webException = exc.InnerException as System.Net.WebException;
if (webException != null)
{
throw new Exception(Utils.Common.FormatNameResolutionFailureMessage(client.Config, webException.Message), webException);
}
throw;
}
}
#endregion
internal partial class CmdletContext : ExecutorContext
{
public System.Boolean? Enable { get; set; }
public System.DateTime? EndTime { get; set; }
public System.String IamRole { get; set; }
public System.String Schedule { get; set; }
public System.String ScheduledActionDescription { get; set; }
public System.String ScheduledActionName { get; set; }
public System.DateTime? StartTime { get; set; }
public System.String PauseCluster_ClusterIdentifier { get; set; }
public System.Boolean? ResizeCluster_Classic { get; set; }
public System.String ResizeCluster_ClusterIdentifier { get; set; }
public System.String ResizeCluster_ClusterType { get; set; }
public System.String ResizeCluster_NodeType { get; set; }
public System.Int32? ResizeCluster_NumberOfNode { get; set; }
public System.String ResumeCluster_ClusterIdentifier { get; set; }
public System.Func<Amazon.Redshift.Model.ModifyScheduledActionResponse, EditRSScheduledActionCmdlet, object> Select { get; set; } =
(response, cmdlet) => response;
}
}
}
| 49.672897 | 290 | 0.645456 | [
"Apache-2.0"
] | QPC-database/aws-tools-for-powershell | modules/AWSPowerShell/Cmdlets/Redshift/Basic/Edit-RSScheduledAction-Cmdlet.cs | 26,575 | C# |
using System;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using System.Security.Claims;
using System.IdentityModel.Tokens.Jwt;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using KiancaAPI.DTOs;
namespace KiancaAPI.Controllers
{
[Produces("application/json")]
[Route("api/[Controller]")]
[ApiController]
public class AutorizaController : ControllerBase
{
private readonly IConfiguration _config;
public AutorizaController(IConfiguration config)
{
_config = config;
}
[HttpGet]
public ActionResult<string> Get()
{
return "AutorizaController :: Acessado em: " + DateTime.Now.ToLongDateString();
}
[HttpGet("obtertoken")]
public ActionResult ObterToken([FromQuery]string email)
{
if (String.IsNullOrEmpty(email))
{
ModelState.AddModelError(string.Empty, "Email inválido...");
return BadRequest(ModelState);
}
return Ok(GerarToken(email));
}
private UsuarioTokenDTO GerarToken(string email)
{
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.UniqueName, email),
new Claim("qualquerchave", "qualquervalor"),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var expireHours = double.Parse(_config["TokenConfiguration:ExpireHours"]);
var expiration = DateTime.UtcNow.AddHours(expireHours);
JwtSecurityToken token = new JwtSecurityToken(
issuer: _config["TokenConfiguration:Issuer"],
audience: _config["TokenConfiguration:Audience"],
claims: claims,
expires: expiration,
signingCredentials: credentials
);
return new UsuarioTokenDTO()
{
Authenticated = true,
Token = new JwtSecurityTokenHandler().WriteToken(token),
Expiration = expiration,
Message = "Token JWT OK"
};
}
}
} | 33.083333 | 91 | 0.597397 | [
"MIT"
] | ricardotondello/KiancasApi-BackEnd | src/Controllers/AutorizaController.cs | 2,385 | C# |
// Copyright (c) Microsoft. All rights reserved.
[assembly: System.Runtime.CompilerServices.InternalsVisibleToAttribute("Microsoft.Azure.Devices.Edge.Agent.Diagnostics.Test")]
namespace Microsoft.Azure.Devices.Edge.Agent.Diagnostics
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Devices.Edge.Agent.Diagnostics.Publisher;
using Microsoft.Azure.Devices.Edge.Agent.Diagnostics.Storage;
using Microsoft.Azure.Devices.Edge.Agent.Diagnostics.Util;
using Microsoft.Azure.Devices.Edge.Util;
using Microsoft.Azure.Devices.Edge.Util.Concurrency;
using Microsoft.Azure.Devices.Edge.Util.Metrics;
using Microsoft.Azure.Devices.Edge.Util.TransientFaultHandling;
using Microsoft.Extensions.Logging;
public class MetricsWorker : IDisposable
{
public static RetryStrategy RetryStrategy = new ExponentialBackoff(20, TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(30), TimeSpan.FromMinutes(1), false);
readonly IMetricsScraper scraper;
readonly IMetricsStorage storage;
readonly IMetricsPublisher uploader;
readonly AsyncLock scrapeUploadLock = new AsyncLock();
static readonly ILogger Log = Logger.Factory.CreateLogger<MetricsScraper>();
readonly MetricTransformer metricFilter;
PeriodicTask scrape;
PeriodicTask upload;
public MetricsWorker(IMetricsScraper scraper, IMetricsStorage storage, IMetricsPublisher uploader)
{
this.scraper = Preconditions.CheckNotNull(scraper, nameof(scraper));
this.storage = Preconditions.CheckNotNull(storage, nameof(storage));
this.uploader = Preconditions.CheckNotNull(uploader, nameof(uploader));
this.metricFilter = new MetricTransformer()
.AddAllowedTags((MetricsConstants.MsTelemetry, true.ToString()))
.AddDisallowedTags(
("quantile", "0.1"),
("quantile", "0.5"),
("quantile", "0.99"))
.AddTagsToRemove(MetricsConstants.MsTelemetry, MetricsConstants.IotHubLabel, MetricsConstants.DeviceIdLabel)
.AddTagsToModify(
("id", this.ReplaceDeviceId),
("module_name", this.ReplaceModuleId),
("to", name => name.CreateSha256()),
("from", name => name.CreateSha256()),
("to_route_input", name => name.CreateSha256()),
("from_route_output", name => name.CreateSha256()));
}
public void Start(TimeSpan scrapingInterval, TimeSpan uploadInterval)
{
this.scrape = new PeriodicTask(this.Scrape, scrapingInterval, scrapingInterval, Log, "Metrics Scrape");
TimeSpan uploadJitter = new TimeSpan((long)(uploadInterval.Ticks * new Random().NextDouble()));
this.upload = new PeriodicTask(this.Upload, uploadJitter, uploadInterval, Log, "Metrics Upload");
}
internal async Task Scrape(CancellationToken cancellationToken)
{
using (await this.scrapeUploadLock.LockAsync(cancellationToken))
{
Log.LogInformation("Scraping Metrics");
IEnumerable<Metric> scrapedMetrics = await this.scraper.ScrapeEndpointsAsync(cancellationToken);
scrapedMetrics = this.metricFilter.TransformMetrics(scrapedMetrics);
Log.LogInformation("Storing Metrics");
await this.storage.StoreMetricsAsync(scrapedMetrics);
Log.LogInformation("Scraped and Stored Metrics");
}
}
internal async Task Upload(CancellationToken cancellationToken)
{
if (!await this.TryUploadAndClear(cancellationToken))
{
await this.BeginUploadRetry(cancellationToken);
}
}
async Task<bool> TryUploadAndClear(CancellationToken cancellationToken)
{
using (await this.scrapeUploadLock.LockAsync(cancellationToken))
{
Log.LogInformation($"Uploading Metrics");
IEnumerable<Metric> metricsToUpload = (await this.storage.GetAllMetricsAsync()).CondenseTimeSeries();
try
{
if (await this.uploader.PublishAsync(metricsToUpload, cancellationToken))
{
Log.LogInformation($"Published metrics");
await this.storage.RemoveAllReturnedMetricsAsync();
return true;
}
else
{
Log.LogInformation($"Failed to publish metrics");
return false;
}
}
catch (Exception ex)
{
// If unexpected error publishing metrics, delete stored ones to prevent storage buildup.
Log.LogError($"Unexpected error publishing metrics. Deleting stored metrics.");
await this.storage.RemoveAllReturnedMetricsAsync();
throw ex;
}
}
}
async Task BeginUploadRetry(CancellationToken cancellationToken)
{
int retryNum = 0;
var shouldRetry = RetryStrategy.GetShouldRetry();
while (shouldRetry(retryNum++, null, out TimeSpan backoffDelay))
{
Log.LogInformation($"Metric publish set to retry in {backoffDelay.Humanize()}");
await Task.Delay(backoffDelay, cancellationToken);
if (await this.TryUploadAndClear(cancellationToken))
{
// Upload succeded, end loop
return;
}
}
Log.LogInformation($"Upload retries exeeded {retryNum} allowed attempts. Deleting stored metrics.");
using (await this.scrapeUploadLock.LockAsync(cancellationToken))
{
await this.storage.RemoveAllReturnedMetricsAsync();
Log.LogInformation($"Deleted stored metrics.");
}
}
/// <summary>
/// Replaces the device id in some edgeHub metrics with "device".
///
/// EdgeHub metrics id comes in the form of 'deviceId/moduleName' in the case of an edgeDevice
/// and 'deviceId' in the case of downstream leaf devices.
/// </summary>
/// <param name="id">Metric id tag.</param>
/// <returns>Id tag with deviceId removed.</returns>
string ReplaceDeviceId(string id)
{
const string deviceIdReplacement = "device";
// Id is in the form of 'deviceId/moduleId'
string[] parts = id.Split('/');
if (parts.Length == 2)
{
return $"{deviceIdReplacement}/{this.ReplaceModuleId(parts[1])}";
}
// Id is just 'deviceId'
return deviceIdReplacement;
}
string ReplaceModuleId(string id)
{
// Don't hash system modules
if (id.StartsWith("$"))
{
return id;
}
return id.CreateSha256();
}
public void Dispose()
{
this.scrape?.Dispose();
this.upload?.Dispose();
}
}
}
| 41.707182 | 162 | 0.592131 | [
"MIT"
] | zasherif/iotedge | edge-agent/src/Microsoft.Azure.Devices.Edge.Agent.Diagnostics/MetricsWorker.cs | 7,549 | C# |
using System;
namespace Craftgate.Response
{
public class WalletResponse
{
public long Id { get; set; }
public DateTime? CreatedDate { get; set; }
public DateTime? UpdatedDate { get; set; }
public decimal Amount { get; set; }
public decimal WithdrawalAmount { get; set; }
public string Currency { get; set; }
public long MemberId { get; set; }
}
} | 27.733333 | 53 | 0.605769 | [
"MIT"
] | craftgate/craftgate-dotnet-client | Craftgate/Response/WalletResponse.cs | 416 | C# |
/*
* MIT License
*
* Copyright(c) 2018 thrzn41
*
* 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 Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;
namespace Thrzn41.WebexTeams.Version1
{
/// <summary>
/// <see cref="Space"/> list.
/// </summary>
[JsonObject(MemberSerialization.OptIn)]
public class SpaceList : TeamsListData<Space>
{
}
}
| 35.292683 | 81 | 0.737388 | [
"MIT"
] | thrzn41/WebexTeamsAPIClient | CSharp/MultiTarget.Thrzn41.WebexTeams/Version1/SpaceList.cs | 1,449 | C# |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Xml.Serialization;
using CsvHelper;
using DataImportApp.Application.Common;
using DataImportApp.Domain.Entities;
using DataImportApp.Domain.Enums;
using Microsoft.AspNetCore.Http;
namespace DataImportApp.Application.Implementations.Common
{
internal class TransactionDataImporter : ITransactionDataImporter
{
public List<Transaction> GetListFromCsvFile(IFormFile csvFile)
{
try
{
if (csvFile == null)
{
throw new ArgumentNullException(nameof(csvFile));
}
List<Transaction> transactions = new List<Transaction>();
StreamReader streamReader = new StreamReader(csvFile.OpenReadStream());
using (CsvReader csv = new CsvReader(streamReader, CultureInfo.InvariantCulture))
{
while (csv.Read())
{
string transactionId = csv[0];
decimal amount = Convert.ToDecimal(csv[1], CultureInfo.InvariantCulture);
string currency = csv[2];
string transactionDate = csv[3];
string status = csv[4];
string[] record = csv.Context.Record;
Transaction transaction = new Transaction()
{
Id = transactionId,
Amount = amount,
CurrencyCode = currency,
TransactionDate = DateTime.ParseExact(transactionDate, "dd/MM/yyyy hh:mm:ss", CultureInfo.InvariantCulture),
Status = (TransactionStatus)Enum.Parse(typeof(TransactionStatus), status)
};
transactions.Add(transaction);
}
}
return transactions;
}
catch (Exception exception)
{
Console.WriteLine(exception);
throw;
}
}
public List<Transaction> GetListFromXmlFile(IFormFile xmlFile)
{
try
{
if (xmlFile == null)
{
throw new ArgumentNullException(nameof(xmlFile));
}
List<Transaction> transactions = new List<Transaction>();
using (StreamReader reader = new StreamReader(xmlFile.OpenReadStream()))
{
XmlRootAttribute xRoot = new XmlRootAttribute
{
ElementName = "Transactions"
};
XmlSerializer serializer = new XmlSerializer(typeof(XmlTransactions), xRoot);
XmlTransactions xmlTransactions = (XmlTransactions)serializer.Deserialize(reader);
if (xmlTransactions?.Transactions.Count > 0)
{
foreach (XmlTransaction item in xmlTransactions.Transactions)
{
Transaction transaction = new Transaction()
{
Id = item.Id,
Amount = item.PaymentDetails.Amount,
CurrencyCode = item.PaymentDetails.CurrencyCode,
TransactionDate = DateTime.ParseExact(item.TransactionDate, "yyyy-MM-ddTHH:mm:ss", CultureInfo.InvariantCulture),
Status = (TransactionStatus)Enum.Parse(typeof(TransactionStatus), item.Status)
};
transactions.Add(transaction);
}
}
}
return transactions;
}
catch (Exception exception)
{
Console.WriteLine(exception);
throw;
}
}
}
[Serializable]
[XmlRootAttribute("Transactions")]
public class XmlTransactions
{
[XmlElement("Transaction")]
public List<XmlTransaction> Transactions { get; set; }
}
[Serializable]
public class XmlTransaction
{
[XmlAttribute("id")]
public string Id { get; set; }
[XmlElement("TransactionDate")]
public string TransactionDate { get; set; }
[XmlElement("PaymentDetails")]
public PaymentDetails PaymentDetails { get; set; }
[XmlElement("Status")]
public string Status { get; set; }
}
[Serializable]
public class PaymentDetails
{
[XmlElement("Amount")]
public decimal Amount { get; set; }
[XmlElement("CurrencyCode")]
public string CurrencyCode { get; set; }
}
}
| 34.326389 | 145 | 0.510621 | [
"Apache-2.0"
] | TanvirArjel/DataImportApp | src/Api/DataImportApp.Application/Implementations/Common/TransactionDataImporter.cs | 4,945 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Cofoundry.Core.DependencyInjection;
using Cofoundry.Domain.Internal;
namespace Cofoundry.Domain.Registration
{
public class CustomEntitiesDependencyRegistration : IDependencyRegistration
{
public void Register(IContainerRegister container)
{
var singletonOptions = RegistrationOptions.SingletonScope();
container
.Register<ICustomEntityDisplayModelMapper, CustomEntityDisplayModelMapper>()
.Register<ICustomEntityDataModelMapper, CustomEntityDataModelMapper>()
.Register<ICustomEntityCache, CustomEntityCache>()
.Register<ICustomEntityRepository, CustomEntityRepository>()
.RegisterAll<ICustomEntityRoutingRule>(singletonOptions)
.RegisterAll<ICustomEntityDefinition>(singletonOptions)
.RegisterAll<ICustomEntityDisplayModel>()
.RegisterAllGenericImplementations(typeof(ICustomEntityDisplayModelMapper<,>))
.RegisterSingleton<ICustomEntityDefinitionRepository, CustomEntityDefinitionRepository>()
.Register<ICustomEntityRenderSummaryMapper, CustomEntityRenderSummaryMapper>()
.Register<ICustomEntitySummaryMapper, CustomEntitySummaryMapper>()
.Register<ICustomEntityVersionSummaryMapper, CustomEntityVersionSummaryMapper>()
.Register<ICustomEntityDefinitionMicroSummaryMapper, CustomEntityDefinitionMicroSummaryMapper>()
.Register<ICustomEntityDefinitionSummaryMapper, CustomEntityDefinitionSummaryMapper>()
.Register<ICustomEntityRouteMapper, CustomEntityRouteMapper>()
.Register<ICustomEntityRouteDataBuilderFactory, CustomEntityRouteDataBuilderFactory>()
.RegisterAllGenericImplementations(typeof(ICustomEntityRouteDataBuilder<,>))
;
}
}
}
| 50.425 | 112 | 0.724839 | [
"MIT"
] | OliveiraLands/cofoundry | src/Cofoundry.Domain/Domain/CustomEntities/Bootstrap/CustomEntitiesDependencyRegistration.cs | 2,019 | C# |
using _0_Framework.Infrastructure;
namespace DiscountManagement.Infrastructure.Configuration.Permissions {
public class DiscountPermissionExposer: IPermissionExposer {
public Dictionary<string, List<PermissionDto>> Expose() {
return new Dictionary<string, List<PermissionDto>> {
{
"Colleague Discount", new List<PermissionDto> {
new PermissionDto(DiscountPermissions.ListColleagueDiscounts, "لیست تخفیف همکاران"),
new PermissionDto(DiscountPermissions.SearchColleagueDiscounts, "جستجو در تخفیف همکاران"),
new PermissionDto(DiscountPermissions.EditColleagueDiscounts, "ویرایش تخفیف همکار"),
new PermissionDto(DiscountPermissions.CreateColleagueDiscounts, "تعریف تخفیف همکار"),
new PermissionDto(DiscountPermissions.RemoveColleagueDiscounts, "حذف تخفیف همکار"),
}
},
{
"Customer Discount", new List<PermissionDto> {
new PermissionDto(DiscountPermissions.ListCustomerDiscounts, "لیست تخفیف مشتری"),
new PermissionDto(DiscountPermissions.SearchCustomerDiscounts, "جستجو در تخفیف مشتری"),
new PermissionDto(DiscountPermissions.EditCustomerDiscounts, "ویرایش تخفیف مشتری"),
new PermissionDto(DiscountPermissions.CreateCustomerDiscounts, "تعریف تخفیف مشتری"),
}
},
};
}
}
}
| 56.321429 | 114 | 0.615092 | [
"MIT"
] | AmirhosseinKeshtkar/Lampshade | DiscountManagement.Configuration/Permissions/DiscountPermissionExposer.cs | 1,720 | C# |
// Copyright 2020-2021 Mykhailo Shevchuk & Contributors
//
// Licensed under the MIT license;
// you may not use this file except in compliance with the License.
//
// 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 LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using Serilog.Configuration;
using Serilog.Events;
using Serilog.Formatting;
using Serilog.Formatting.Display;
using Serilog.Sinks.Grafana.Loki.HttpClients;
using Serilog.Sinks.Grafana.Loki.Utils;
[assembly: InternalsVisibleTo("Serilog.Sinks.Grafana.Loki.Tests")]
namespace Serilog.Sinks.Grafana.Loki
{
/// <summary>
/// Class containing extension methods to <see cref="LoggerConfiguration"/>, configuring sinks
/// sending log events to Grafana Loki using HTTP.
/// </summary>
public static class LoggerConfigurationLokiExtensions
{
private const string DefaultOutputTemplate =
"[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}";
/// <summary>
/// Adds a non-durable sink that will send log events to Grafana Loki.
/// A non-durable sink will lose data after a system or process restart.
/// </summary>
/// <param name="sinkConfiguration">
/// The logger configuration.
/// </param>
/// <param name="uri">
/// The root URI of Loki.
/// </param>
/// <param name="labels">
/// The globals log event labels, which will be user for enriching all requests.
/// </param>
/// <param name="filtrationMode">
/// The mode for labels filtration
/// </param>
/// <param name="filtrationLabels">
/// The list of label keys used for filtration
/// </param>
/// <param name="credentials">
/// Auth <see cref="LokiCredentials"/>.
/// </param>
/// <param name="outputTemplate">
/// A message template describing the format used to write to the sink.
/// Default value is <code>"[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}"</code>.
/// </param>
/// <param name="restrictedToMinimumLevel">
/// The minimum level for events passed through the sink.
/// Default value is <see cref="LevelAlias.Minimum"/>.
/// </param>
/// <param name="batchPostingLimit">
/// The maximum number of events to post in a single batch. Default value is 1000.
/// </param>
/// <param name="queueLimit">
/// The maximum number of events stored in the queue in memory, waiting to be posted over
/// the network. Default value is infinitely.
/// </param>
/// <param name="period">
/// The time to wait between checking for event batches. Default value is 2 seconds.
/// </param>
/// <param name="textFormatter">
/// The formatter rendering individual log events into text, for example JSON. Default
/// value is <see cref="MessageTemplateTextFormatter"/>.
/// </param>
/// <param name="httpClient">
/// A custom <see cref="ILokiHttpClient"/> implementation. Default value is
/// <see cref="LokiHttpClient"/>.
/// </param>
/// <param name="createLevelLabel">
/// Should level label be created. Default value is false
/// The level label always won't be created while using <see cref="ILabelAwareTextFormatter"/>
/// </param>
/// <returns>Logger configuration, allowing configuration to continue.</returns>
public static LoggerConfiguration GrafanaLoki(
this LoggerSinkConfiguration sinkConfiguration,
string uri,
IEnumerable<LokiLabel>? labels = null,
LokiLabelFiltrationMode? filtrationMode = null,
IEnumerable<string>? filtrationLabels = null,
LokiCredentials? credentials = null,
string outputTemplate = DefaultOutputTemplate,
LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
int batchPostingLimit = 1000,
int? queueLimit = null,
TimeSpan? period = null,
ITextFormatter? textFormatter = null,
ILokiHttpClient? httpClient = null,
bool createLevelLabel = false)
{
if (sinkConfiguration == null)
{
throw new ArgumentNullException(nameof(sinkConfiguration));
}
createLevelLabel = createLevelLabel && textFormatter is not ILabelAwareTextFormatter {ExcludeLevelLabel: true};
var batchFormatter = new LokiBatchFormatter(labels, filtrationMode, filtrationLabels, createLevelLabel);
period ??= TimeSpan.FromSeconds(1);
textFormatter ??= new MessageTemplateTextFormatter(outputTemplate);
httpClient ??= new LokiHttpClient();
httpClient.SetCredentials(credentials);
var sink = new LokiSink(
LokiRoutesBuilder.BuildLogsEntriesRoute(uri),
batchPostingLimit,
queueLimit,
period.Value,
textFormatter,
batchFormatter,
httpClient);
return sinkConfiguration.Sink(sink, restrictedToMinimumLevel);
}
}
} | 43.139535 | 123 | 0.627134 | [
"MIT"
] | MaximPopov/serilog-sinks-grafana-loki | src/Serilog.Sinks.Grafana.Loki/LoggerConfigurationLokiExtensions.cs | 5,567 | C# |
using System;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Text;
using System.IO;
using NumSharp;
namespace Tensorflow
{
public class MnistModelLoader : IModelLoader<MnistDataSet>
{
private const string DEFAULT_SOURCE_URL = "https://storage.googleapis.com/cvdf-datasets/mnist/";
private const string TRAIN_IMAGES = "train-images-idx3-ubyte.gz";
private const string TRAIN_LABELS = "train-labels-idx1-ubyte.gz";
private const string TEST_IMAGES = "t10k-images-idx3-ubyte.gz";
private const string TEST_LABELS = "t10k-labels-idx1-ubyte.gz";
public static async Task<Datasets<MnistDataSet>> LoadAsync(string trainDir, bool oneHot = false, int? trainSize = null, int? validationSize = null, int? testSize = null, bool showProgressInConsole = false)
{
var loader = new MnistModelLoader();
var setting = new ModelLoadSetting
{
TrainDir = trainDir,
OneHot = oneHot,
ShowProgressInConsole = showProgressInConsole
};
if (trainSize.HasValue)
setting.TrainSize = trainSize.Value;
if (validationSize.HasValue)
setting.ValidationSize = validationSize.Value;
if (testSize.HasValue)
setting.TestSize = testSize.Value;
return await loader.LoadAsync(setting);
}
public async Task<Datasets<MnistDataSet>> LoadAsync(ModelLoadSetting setting)
{
if (setting.TrainSize.HasValue && setting.ValidationSize >= setting.TrainSize.Value)
throw new ArgumentException("Validation set should be smaller than training set");
var sourceUrl = setting.SourceUrl;
if (string.IsNullOrEmpty(sourceUrl))
sourceUrl = DEFAULT_SOURCE_URL;
// load train images
await this.DownloadAsync(sourceUrl + TRAIN_IMAGES, setting.TrainDir, TRAIN_IMAGES, showProgressInConsole: setting.ShowProgressInConsole)
.ShowProgressInConsole(setting.ShowProgressInConsole);
await this.UnzipAsync(Path.Combine(setting.TrainDir, TRAIN_IMAGES), setting.TrainDir, showProgressInConsole: setting.ShowProgressInConsole)
.ShowProgressInConsole(setting.ShowProgressInConsole);
var trainImages = ExtractImages(Path.Combine(setting.TrainDir, Path.GetFileNameWithoutExtension(TRAIN_IMAGES)), limit: setting.TrainSize);
// load train labels
await this.DownloadAsync(sourceUrl + TRAIN_LABELS, setting.TrainDir, TRAIN_LABELS, showProgressInConsole: setting.ShowProgressInConsole)
.ShowProgressInConsole(setting.ShowProgressInConsole);
await this.UnzipAsync(Path.Combine(setting.TrainDir, TRAIN_LABELS), setting.TrainDir, showProgressInConsole: setting.ShowProgressInConsole)
.ShowProgressInConsole(setting.ShowProgressInConsole);
var trainLabels = ExtractLabels(Path.Combine(setting.TrainDir, Path.GetFileNameWithoutExtension(TRAIN_LABELS)), one_hot: setting.OneHot, limit: setting.TrainSize);
// load test images
await this.DownloadAsync(sourceUrl + TEST_IMAGES, setting.TrainDir, TEST_IMAGES, showProgressInConsole: setting.ShowProgressInConsole)
.ShowProgressInConsole(setting.ShowProgressInConsole);
await this.UnzipAsync(Path.Combine(setting.TrainDir, TEST_IMAGES), setting.TrainDir, showProgressInConsole: setting.ShowProgressInConsole)
.ShowProgressInConsole(setting.ShowProgressInConsole);
var testImages = ExtractImages(Path.Combine(setting.TrainDir, Path.GetFileNameWithoutExtension(TEST_IMAGES)), limit: setting.TestSize);
// load test labels
await this.DownloadAsync(sourceUrl + TEST_LABELS, setting.TrainDir, TEST_LABELS, showProgressInConsole: setting.ShowProgressInConsole)
.ShowProgressInConsole(setting.ShowProgressInConsole);
await this.UnzipAsync(Path.Combine(setting.TrainDir, TEST_LABELS), setting.TrainDir, showProgressInConsole: setting.ShowProgressInConsole)
.ShowProgressInConsole(setting.ShowProgressInConsole);
var testLabels = ExtractLabels(Path.Combine(setting.TrainDir, Path.GetFileNameWithoutExtension(TEST_LABELS)), one_hot: setting.OneHot, limit: setting.TestSize);
var end = trainImages.shape[0];
var validationSize = setting.ValidationSize;
var validationImages = trainImages[np.arange(validationSize)];
var validationLabels = trainLabels[np.arange(validationSize)];
trainImages = trainImages[np.arange(validationSize, end)];
trainLabels = trainLabels[np.arange(validationSize, end)];
var dtype = setting.DataType;
var reshape = setting.ReShape;
var train = new MnistDataSet(trainImages, trainLabels, dtype, reshape);
var validation = new MnistDataSet(validationImages, validationLabels, dtype, reshape);
var test = new MnistDataSet(testImages, testLabels, dtype, reshape);
return new Datasets<MnistDataSet>(train, validation, test);
}
private NDArray ExtractImages(string file, int? limit = null)
{
if (!Path.IsPathRooted(file))
file = Path.Combine(AppContext.BaseDirectory, file);
using (var bytestream = new FileStream(file, FileMode.Open))
{
var magic = Read32(bytestream);
if (magic != 2051)
throw new Exception($"Invalid magic number {magic} in MNIST image file: {file}");
var num_images = Read32(bytestream);
num_images = limit == null ? num_images : Math.Min(num_images, (int)limit);
var rows = Read32(bytestream);
var cols = Read32(bytestream);
var buf = new byte[rows * cols * num_images];
bytestream.Read(buf, 0, buf.Length);
var data = np.frombuffer(buf, np.@byte);
data = data.reshape(num_images, rows, cols, 1);
return data;
}
}
private NDArray ExtractLabels(string file, bool one_hot = false, int num_classes = 10, int? limit = null)
{
if (!Path.IsPathRooted(file))
file = Path.Combine(AppContext.BaseDirectory, file);
using (var bytestream = new FileStream(file, FileMode.Open))
{
var magic = Read32(bytestream);
if (magic != 2049)
throw new Exception($"Invalid magic number {magic} in MNIST label file: {file}");
var num_items = Read32(bytestream);
num_items = limit == null ? num_items : Math.Min(num_items, (int)limit);
var buf = new byte[num_items];
bytestream.Read(buf, 0, buf.Length);
var labels = np.frombuffer(buf, np.uint8);
if (one_hot)
return DenseToOneHot(labels, num_classes);
return labels;
}
}
private NDArray DenseToOneHot(NDArray labels_dense, int num_classes)
{
var num_labels = labels_dense.shape[0];
var index_offset = np.arange(num_labels) * num_classes;
var labels_one_hot = np.zeros(num_labels, num_classes);
var labels = labels_dense.Data<byte>();
for (int row = 0; row < num_labels; row++)
{
var col = labels[row];
labels_one_hot.SetData(1.0, row, col);
}
return labels_one_hot;
}
private int Read32(FileStream bytestream)
{
var buffer = new byte[sizeof(uint)];
var count = bytestream.Read(buffer, 0, 4);
return np.frombuffer(buffer, ">u4").Data<int>()[0];
}
}
}
| 44.016216 | 213 | 0.627656 | [
"Apache-2.0"
] | BlueCode2019/TensorFlow.NET | src/TensorFlowNET.Core/Data/MnistModelLoader.cs | 8,145 | C# |
namespace Minsk.CodeAnalysis.Syntax
{
public abstract class StatementSyntax : SyntaxNode
{
}
} | 17.666667 | 54 | 0.716981 | [
"MIT"
] | Neme12/minsk | src/Minsk/CodeAnalysis/Syntax/StatementSyntax.cs | 106 | C# |
using NUnit.Framework;
using NUnit.Framework.TUnit;
using System;
using Tizen.NUI;
using Tizen.NUI.BaseComponents;
namespace Tizen.NUI.Devel.Tests
{
using tlog = Tizen.Log;
[TestFixture]
[Description("public/Events/GestureDetector")]
class PublicGestureDetectorTest
{
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("GestureDetector constructor")]
[Property("SPEC", "Tizen.NUI.GestureDetector.GestureDetector C")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "CONSTR")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void GestureDetectorConstructor()
{
tlog.Debug(tag, $"GestureDetectorConstructor START");
var testingTarget = new GestureDetector();
Assert.IsNotNull(testingTarget, "should be not null");
Assert.IsInstanceOf<GestureDetector>(testingTarget, "should be an instance of testing target class!");
testingTarget.Dispose();
tlog.Debug(tag, $"GestureDetectorConstructor END (OK)");
Assert.Pass("GestureDetectorConstructor");
}
//[Test]
//[Category("P1")]
//[Description("GestureDetector constructor")]
//[Property("SPEC", "Tizen.NUI.GestureDetector.GestureDetector C")]
//[Property("SPEC_URL", "-")]
//[Property("CRITERIA", "CONSTR")]
//[Property("AUTHOR", "guowei.wang@samsung.com")]
//public void GestureDetectorConstructorWithGestureDetector()
//{
// tlog.Debug(tag, $"GestureDetectorConstructorWithGestureDetector START");
// using (GestureDetector detector = new GestureDetector())
// {
// var testingTarget = new GestureDetector(detector);
// Assert.IsNotNull(testingTarget, "should be not null");
// Assert.IsInstanceOf<GestureDetector>(testingTarget, "should be an instance of testing target class!");
// testingTarget.Dispose();
// }
// tlog.Debug(tag, $"GestureDetectorConstructorWithGestureDetector END (OK)");
// Assert.Pass("GestureDetectorConstructor");
//}
[Test]
[Category("P1")]
[Description("GestureDetector Attach")]
[Property("SPEC", "Tizen.NUI.GestureDetector.Attach M")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "MR")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void GestureDetectorAttach()
{
tlog.Debug(tag, $"GestureDetectorAttach START");
var testingTarget = new LongPressGestureDetector();
Assert.IsNotNull(testingTarget, "should be not null");
Assert.IsInstanceOf<LongPressGestureDetector>(testingTarget, "should be an instance of testing target class!");
using (View view = new View())
{
Window.Instance.GetDefaultLayer().Add(view);
testingTarget.Attach(view);
testingTarget.Detach(view);
Window.Instance.GetDefaultLayer().Remove(view);
}
testingTarget.Dispose();
tlog.Debug(tag, $"GestureDetectorAttach END (OK)");
Assert.Pass("GestureDetectorAttach");
}
[Test]
[Category("P1")]
[Description("GestureDetector DetachAll")]
[Property("SPEC", "Tizen.NUI.GestureDetector.DetachAll M")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "MR")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void GestureDetectorDetachAll()
{
tlog.Debug(tag, $"GestureDetectorDetachAll START");
var testingTarget = new LongPressGestureDetector();
Assert.IsNotNull(testingTarget, "should be not null");
Assert.IsInstanceOf<LongPressGestureDetector>(testingTarget, "should be an instance of testing target class!");
using (View view = new View())
{
testingTarget.Attach(view);
testingTarget.DetachAll();
}
testingTarget.Dispose();
tlog.Debug(tag, $"GestureDetectorDetachAll END (OK)");
Assert.Pass("GestureDetectorDetachAll");
}
[Test]
[Category("P1")]
[Description("GestureDetector GetAttachedViewCount")]
[Property("SPEC", "Tizen.NUI.GestureDetector.GetAttachedViewCount M")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "MR")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void GestureDetectorGetAttachedViewCount()
{
tlog.Debug(tag, $"GestureDetectorGetAttachedViewCount START");
var testingTarget = new LongPressGestureDetector();
Assert.IsNotNull(testingTarget, "should be not null");
Assert.IsInstanceOf<LongPressGestureDetector>(testingTarget, "should be an instance of testing target class!");
using (View view = new View())
{
testingTarget.Attach(view);
tlog.Debug(tag, "AttachedViewCount : " + testingTarget.GetAttachedViewCount());
testingTarget.Detach(view);
}
testingTarget.Dispose();
tlog.Debug(tag, $"GestureDetectorGetAttachedViewCount END (OK)");
Assert.Pass("GestureDetectorGetAttachedViewCount");
}
[Test]
[Category("P1")]
[Description("GestureDetector GetAttachedView")]
[Property("SPEC", "Tizen.NUI.GestureDetector.GetAttachedView M")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "MR")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void GestureDetectorGetAttachedView()
{
tlog.Debug(tag, $"GestureDetectorGetAttachedView START");
var testingTarget = new LongPressGestureDetector();
Assert.IsNotNull(testingTarget, "should be not null");
Assert.IsInstanceOf<LongPressGestureDetector>(testingTarget, "should be an instance of testing target class!");
using (View view = new View())
{
testingTarget.Attach(view);
testingTarget.GetAttachedView(0);
testingTarget.Detach(view);
}
testingTarget.Dispose();
tlog.Debug(tag, $"GestureDetectorGetAttachedView END (OK)");
Assert.Pass("GestureDetectorGetAttachedView");
}
//[Test]
//[Category("P1")]
//[Description("GestureDetector Assign")]
//[Property("SPEC", "Tizen.NUI.GestureDetector.Assign M")]
//[Property("SPEC_URL", "-")]
//[Property("CRITERIA", "MR")]
//[Property("AUTHOR", "guowei.wang@samsung.com")]
//public void GestureDetectorAssign()
//{
// tlog.Debug(tag, $"GestureDetectorAssign START");
// using (GestureDetector detector = new GestureDetector())
// {
// var testingTarget = detector.Assign(detector);
// Assert.IsNotNull(testingTarget, "should be not null");
// Assert.IsInstanceOf<GestureDetector>(testingTarget, "should be an instance of testing target class!");
// }
// tlog.Debug(tag, $"GestureDetectorAssign END (OK)");
// Assert.Pass("GestureDetectorAssign");
//}
[Test]
[Category("P1")]
[Description("GestureDetector DownCast")]
[Property("SPEC", "Tizen.NUI.GestureDetector.DownCast M")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "MR")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void GestureDetectorDownCast()
{
tlog.Debug(tag, $"GestureDetectorDownCast START");
using (GestureDetector detector = new GestureDetector())
{
var testingTarget = GestureDetector.DownCast(detector);
Assert.IsInstanceOf<GestureDetector>(testingTarget, "should be an instance of testing target class!");
testingTarget.Dispose();
}
tlog.Debug(tag, $"GestureDetectorDownCast END (OK)");
Assert.Pass("GestureDetectorDownCast");
}
[Test]
[Category("P1")]
[Description("GestureDetector getCPtr")]
[Property("SPEC", "Tizen.NUI.GestureDetector.getCPtr M")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "MR")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void GestureDetectorgetCPtr()
{
tlog.Debug(tag, $"GestureDetectorgetCPtr START");
var testingTarget = new GestureDetector();
Assert.IsNotNull(testingTarget, "should be not null");
Assert.IsInstanceOf<GestureDetector>(testingTarget, "should be an instance of testing target class!");
try
{
GestureDetector.getCPtr(testingTarget);
}
catch (Exception e)
{
tlog.Debug(tag, e.Message.ToString());
Assert.Fail("Caught Exception : Failed!");
}
testingTarget.Dispose();
tlog.Debug(tag, $"GestureDetectorgetCPtr END (OK)");
Assert.Pass("GestureDetectorgetCPtr");
}
}
}
| 37.639535 | 123 | 0.580064 | [
"Apache-2.0",
"MIT"
] | SaraMohSamara/TizenFX | test/Tizen.NUI.Tests/Tizen.NUI.Devel.Tests/testcase/public/Events/TSGestureDetector.cs | 9,713 | C# |
namespace TableOfNothing.Configuration.EsotericStrategies
{
public interface IEsotericStrategy
{
string GetConfiguration();
}
} | 21 | 57 | 0.734694 | [
"Apache-2.0"
] | allenmichael/TableOfNothing | TableOfNothing/Configuration/EsotericStrategies/IEsotericStrategy.cs | 147 | C# |
// Copyright 2022 Google LLC
//
// 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
//
// https://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.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Talent.V4.Snippets
{
// [START jobs_v4_generated_CompanyService_GetCompany_sync]
using Google.Cloud.Talent.V4;
public sealed partial class GeneratedCompanyServiceClientSnippets
{
/// <summary>Snippet for GetCompany</summary>
/// <remarks>
/// This snippet has been automatically generated for illustrative purposes only.
/// It may require modifications to work in your environment.
/// </remarks>
public void GetCompanyRequestObject()
{
// Create client
CompanyServiceClient companyServiceClient = CompanyServiceClient.Create();
// Initialize request argument(s)
GetCompanyRequest request = new GetCompanyRequest
{
CompanyName = CompanyName.FromProjectTenantCompany("[PROJECT]", "[TENANT]", "[COMPANY]"),
};
// Make the request
Company response = companyServiceClient.GetCompany(request);
}
}
// [END jobs_v4_generated_CompanyService_GetCompany_sync]
}
| 38.636364 | 105 | 0.683529 | [
"Apache-2.0"
] | AlexandrTrf/google-cloud-dotnet | apis/Google.Cloud.Talent.V4/Google.Cloud.Talent.V4.GeneratedSnippets/CompanyServiceClient.GetCompanyRequestObjectSnippet.g.cs | 1,700 | C# |
using System.Collections.Generic;
using System.IO;
namespace Winforms.Cartesian.Linq
{
public static class DataBase
{
static DataBase()
{
var reader = new StreamReader(File.OpenRead(@"cities.csv"));
var read = new List<City>();
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
if (line != null)
{
var values = line.Split(',');
read.Add(new City
{
Name = values[0],
Population = double.Parse(values[1]),
Area = double.Parse(values[2]),
Country = values[3]
});
}
}
Cities = read.ToArray();
}
public static City[] Cities { get; private set; }
}
}
| 24.184211 | 72 | 0.420022 | [
"MIT"
] | Coding-Enthusiast/Live-Charts | Examples/WinForms/Cartesian/Linq/DataBase.cs | 921 | C# |
using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore.Migrations;
namespace imperugo.aspnet.core.training.Migrations
{
public partial class addedComments : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Comments",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("Autoincrement", true),
CreateAt = table.Column<DateTimeOffset>(nullable: false),
Email = table.Column<string>(nullable: true),
Message = table.Column<string>(nullable: true),
Name = table.Column<string>(nullable: true),
PostId = table.Column<int>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Comments", x => x.Id);
table.ForeignKey(
name: "FK_Comments_Posts_PostId",
column: x => x.PostId,
principalTable: "Posts",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateIndex(
name: "IX_Comments_PostId",
table: "Comments",
column: "PostId");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Comments");
}
}
}
| 35.829787 | 77 | 0.507126 | [
"MIT"
] | imperugo/.NET-Core-Training | 011 - EntityFramework/imperugo.aspnet.core.training/Migrations/20160707145203_addedComments.cs | 1,686 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace SharpGLTF.Schema2
{
using ROOT = ModelRoot;
static class BinarySerialization
{
#region constants
public const uint GLTFHEADER = 0x46546C67;
public const uint GLTFVERSION2 = 2;
public const uint CHUNKJSON = 0x4E4F534A;
public const uint CHUNKBIN = 0x004E4942;
#endregion
#region read
public static bool IsBinaryHeader(Byte a, Byte b, Byte c, Byte d)
{
uint magic = 0;
magic |= (uint)a;
magic |= (uint)b << 8;
magic |= (uint)c << 16;
magic |= (uint)d << 24;
return magic == GLTFHEADER;
}
internal static bool _Identify(Stream stream)
{
Guard.NotNull(stream, nameof(stream));
Guard.IsTrue(stream.CanSeek, nameof(stream), "A seekable stream is required for glTF/GLB format identification");
var currPos = stream.Position;
var a = stream.ReadByte();
var b = stream.ReadByte();
var c = stream.ReadByte();
var d = stream.ReadByte();
stream.Position = currPos; // restart read position
return IsBinaryHeader((Byte)a, (Byte)b, (Byte)c, (Byte)d);
}
public static IReadOnlyDictionary<UInt32, Byte[]> ReadBinaryFile(Stream stream)
{
Guard.NotNull(stream, nameof(stream));
// WARNING: BinaryReader requires Encoding.ASCII because
// the binaryReader.PeekChar() must read single bytes
// in some cases, trying to read the end of the file will throw
// an exception if encoding is UTF8 and there's just 1 byte left to read.
using (var binaryReader = new BinaryReader(stream, Encoding.ASCII))
{
_ReadBinaryHeader(binaryReader);
var chunks = new Dictionary<uint, Byte[]>();
// keep reading until EndOfFile exception
while (true)
{
if (binaryReader.PeekChar() < 0) break;
uint chunkLength = binaryReader.ReadUInt32();
if ((chunkLength & 3) != 0)
{
throw new InvalidDataException($"The chunk must be padded to 4 bytes: {chunkLength}");
}
uint chunkId = binaryReader.ReadUInt32();
var data = binaryReader.ReadBytes((int)chunkLength);
chunks[chunkId] = data;
}
return chunks;
}
}
private static void _ReadBinaryHeader(BinaryReader binaryReader)
{
Guard.NotNull(binaryReader, nameof(binaryReader));
uint magic = binaryReader.ReadUInt32();
Guard.IsTrue(magic == GLTFHEADER, nameof(magic), $"Unexpected magic number: {magic}");
uint version = binaryReader.ReadUInt32();
Guard.IsTrue(version == GLTFVERSION2, nameof(version), $"Unknown version number: {version}");
uint length = binaryReader.ReadUInt32();
long fileLength = binaryReader.BaseStream.Length;
Guard.IsTrue(length == fileLength, nameof(length), $"The specified length of the file ({length}) is not equal to the actual length of the file ({fileLength}).");
}
#endregion
#region write
/// <summary>
/// Tells if a given model can be stored as Binary format.
/// </summary>
/// <param name="model">the model to test</param>
/// <returns>null if it can be stored as binary, or an exception object if it can't</returns>
/// <remarks>
/// Due to the limitations of Binary Format, not all models can be saved as Binary.
/// </remarks>
public static Exception IsBinaryCompatible(ROOT model)
{
try
{
Guard.NotNull(model, nameof(model));
Guard.IsTrue(model.LogicalBuffers.Count <= 1, nameof(model), $"GLB format only supports one binary buffer, {model.LogicalBuffers.Count} found. It can be solved by calling {nameof(ModelRoot.MergeImages)} and {nameof(ModelRoot.MergeBuffers)}");
}
catch (ArgumentException ex)
{
return ex;
}
// todo: buffer[0].Uri must be null
return null;
}
/// <summary>
/// Writes a <see cref="ROOT"/> instance into a <see cref="BinaryWriter"/>.
/// </summary>
/// <param name="binaryWriter">The destination <see cref="BinaryWriter"/> stream.</param>
/// <param name="model">The source <see cref="ROOT"/> instance.</param>
public static void WriteBinaryModel(this BinaryWriter binaryWriter, ROOT model)
{
var ex = IsBinaryCompatible(model); if (ex != null) throw ex;
var jsonText = model.GetJSON(false);
var jsonChunk = Encoding.UTF8.GetBytes(jsonText);
var jsonPadding = jsonChunk.Length & 3; if (jsonPadding != 0) jsonPadding = 4 - jsonPadding;
var buffer = model.LogicalBuffers.Count > 0 ? model.LogicalBuffers[0].Content : null;
if (buffer != null && buffer.Length == 0) buffer = null;
var binPadding = buffer == null ? 0 : buffer.Length & 3; if (binPadding != 0) binPadding = 4 - binPadding;
int fullLength = 4 + 4 + 4;
fullLength += 8 + jsonChunk.Length + jsonPadding;
if (buffer != null) fullLength += 8 + buffer.Length + binPadding;
binaryWriter.Write(GLTFHEADER);
binaryWriter.Write(GLTFVERSION2);
binaryWriter.Write(fullLength);
binaryWriter.Write(jsonChunk.Length + jsonPadding);
binaryWriter.Write(CHUNKJSON);
binaryWriter.Write(jsonChunk);
for (int i = 0; i < jsonPadding; ++i) binaryWriter.Write((Byte)0x20);
if (buffer != null)
{
binaryWriter.Write(buffer.Length + binPadding);
binaryWriter.Write(CHUNKBIN);
binaryWriter.Write(buffer);
for (int i = 0; i < binPadding; ++i) binaryWriter.Write((Byte)0);
}
}
#endregion
}
}
| 36.466667 | 259 | 0.549512 | [
"MIT"
] | jcansdale-test/SharpGLTF | src/SharpGLTF.Core/IO/BinarySerialization.cs | 6,566 | C# |
namespace tv.Crystal.UI.CustomControls
{
partial class BaseForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(BaseForm));
this.SuspendLayout();
//
// BaseForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(59)))), ((int)(((byte)(111)))), ((int)(((byte)(155)))));
this.ClientSize = new System.Drawing.Size(1353, 749);
this.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.KeyPreview = true;
this.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.MaximizeBox = false;
this.Name = "BaseForm";
this.ResumeLayout(false);
}
#endregion
}
}
| 35.87037 | 139 | 0.628807 | [
"MIT"
] | kottamam/Crystal | infoSoft.Crystal.UI/CustomControls/BaseForm.Designer.cs | 1,939 | C# |
#pragma warning disable 108 // new keyword hiding
#pragma warning disable 114 // new keyword hiding
namespace Windows.UI.Input.Inking
{
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__
public enum InkManipulationMode
{
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__
Inking = 0,
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__
Erasing = 1,
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__
Selecting = 2,
#endif
}
#endif
}
| 33 | 99 | 0.704545 | [
"Apache-2.0"
] | AbdalaMask/uno | src/Uno.UWP/Generated/3.0.0.0/Windows.UI.Input.Inking/InkManipulationMode.cs | 660 | C# |
using System.Runtime.InteropServices;
namespace IctBaden.PiXtend.WiringPi
{
/// <summary>
/// Provides access to the Thread priority and interrupts for IO
/// </summary>
public class PiThreadInterrupts
{
[DllImport("libwiringPi.so", EntryPoint = "piHiPri")]
public static extern int PiHiPri(int priority);
[DllImport("libwiringPi.so", EntryPoint = "waitForInterrupt")]
public static extern int WaitForInterrupt(int pin, int timeout);
//This is the C# equivelant to "void (*function)(void))" required by wiringPi to define a callback method
public delegate void IsrCallback();
[DllImport("libwiringPi.so", EntryPoint = "wiringPiISR")]
public static extern int WiringPiISR(int pin, int mode, IsrCallback method);
public enum InterruptLevels
{
IntEdgeSetup = 0,
IntEdgeFalling = 1,
IntEdgeRising = 2,
IntEdgeBoth = 3
}
//static extern int piThreadCreate(string name);
}
} | 32.59375 | 113 | 0.641419 | [
"MIT"
] | FrankPfattheicher/PiXtendV2 | IctBaden.PiXtend.NET40/WiringPi/PiThreadInterrupts.cs | 1,045 | C# |
using System;
namespace BonusScore
{
class BonusScore
{
static void Main(string[] args)
{
int number = int.Parse(Console.ReadLine());
double bonus = 0.0;
if (number <= 100)
{
bonus = 5;
}
else if (number > 1000)
{
bonus = 0.10 * number;
}
else
{
bonus = 0.20 * number;
}
if (number % 2 == 0)
{
bonus += 1;
}
else if (number % 10 == 5)
{
bonus += 2;
}
double totalScore = bonus + number;
Console.WriteLine(bonus);
Console.WriteLine(totalScore);
}
}
}
| 19.571429 | 55 | 0.352798 | [
"MIT"
] | delbusque/My-SoftUni-projects-homework-and-exercises | Basics/02-ConditionalStatementsExercise/BonusScore/BonusScore.cs | 824 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
namespace WithoutHaste.DataFiles.DotNet
{
/// <summary>
/// Represents a link in the comments to an internal generic-type parameter.
/// </summary>
public class DotNetCommentTypeParameterLink : DotNetCommentParameterLink
{
#region Constructors
/// <summary></summary>
public DotNetCommentTypeParameterLink(string name) : base(name)
{
}
/// <summary></summary>
public DotNetCommentTypeParameterLink(string name, CommentTag tag) : base(name)
{
Tag = tag;
}
/// <summary>Parses .Net XML documentation for typeparamref.</summary>
/// <example><![CDATA[<typeparamref name="T" />]]></example>
public static new DotNetCommentTypeParameterLink FromVisualStudioXml(XElement element)
{
ValidateXmlTag(element, "typeparamref");
return new DotNetCommentTypeParameterLink(element.GetAttributeValue("name"), DotNetComment.GetTag(element));
}
#endregion
}
}
| 26.394737 | 111 | 0.739781 | [
"MIT"
] | WithoutHaste/WithoutHaste.DataFiles | DataFiles/DotNet/DotNetCommentTypeParameterLink.cs | 1,005 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace VideoStore
{
class Beutor
{
public static void Main(string[] args)
{
M().GetAwaiter().GetResult();
}
public async static Task M()
{
Barman barman = new Barman();
Stopwatch stopwatch = Stopwatch.StartNew();
Task<Bere> comandaDeBere = barman.ToarnaBere();
Task<Tzuica> comandaDeTzuica = barman.ToarnaTzuica();
// Deferred
await Task.WhenAll(comandaDeBere, comandaDeTzuica);
Bere bere = comandaDeBere.Result;
Tzuica tzuica = comandaDeTzuica.Result;
//Task<Bere> bere = barman.ToarnaBere();
//Task<Tzuica> tzuica = barman.ToarnaTzuica();
Console.WriteLine("21A venit comanda. savurez: " + bere + " cu " + tzuica);
stopwatch.Stop();
Console.WriteLine($"Took {stopwatch.ElapsedMilliseconds}");
Console.ReadLine();
}
}
class Barman
{
public async Task<Bere> ToarnaBere()
{
Console.WriteLine("Torn bere");
await Task.Delay(1000);
return new Bere();
}
public async Task<Tzuica> ToarnaTzuica()
{
Console.WriteLine("Torn tzuica");
await Task.Delay(1000);
return new Tzuica();
}
}
class Bere { }
class Tzuica { }
}
| 26.627119 | 87 | 0.561426 | [
"MIT"
] | pgrigoro/training | kata/kata-videostore-cs/VideoStore/Class5.cs | 1,573 | C# |
namespace Server
{
partial class Form
{
/// <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.groupCreateUser = new System.Windows.Forms.GroupBox();
this.btnDisplayUsers = new System.Windows.Forms.Button();
this.btnRemoveUser = new System.Windows.Forms.Button();
this.btnResetPassword = new System.Windows.Forms.Button();
this.textPassword = new System.Windows.Forms.TextBox();
this.textUsername = new System.Windows.Forms.TextBox();
this.btnAddUser = new System.Windows.Forms.Button();
this.label2 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.textMessages = new System.Windows.Forms.TextBox();
this.btnStart = new System.Windows.Forms.Button();
this.btnStop = new System.Windows.Forms.Button();
this.groupServer = new System.Windows.Forms.GroupBox();
this.lblServerStatus = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.groupSendMessage = new System.Windows.Forms.GroupBox();
this.textSendMessage = new System.Windows.Forms.TextBox();
this.btnSendMessage = new System.Windows.Forms.Button();
this.groupCreateUser.SuspendLayout();
this.groupServer.SuspendLayout();
this.groupSendMessage.SuspendLayout();
this.SuspendLayout();
//
// groupCreateUser
//
this.groupCreateUser.Controls.Add(this.btnDisplayUsers);
this.groupCreateUser.Controls.Add(this.btnRemoveUser);
this.groupCreateUser.Controls.Add(this.btnResetPassword);
this.groupCreateUser.Controls.Add(this.textPassword);
this.groupCreateUser.Controls.Add(this.textUsername);
this.groupCreateUser.Controls.Add(this.btnAddUser);
this.groupCreateUser.Controls.Add(this.label2);
this.groupCreateUser.Controls.Add(this.label1);
this.groupCreateUser.Location = new System.Drawing.Point(12, 116);
this.groupCreateUser.Margin = new System.Windows.Forms.Padding(3, 15, 3, 3);
this.groupCreateUser.Name = "groupCreateUser";
this.groupCreateUser.Size = new System.Drawing.Size(227, 153);
this.groupCreateUser.TabIndex = 0;
this.groupCreateUser.TabStop = false;
this.groupCreateUser.Text = "Create User";
//
// btnDisplayUsers
//
this.btnDisplayUsers.Enabled = false;
this.btnDisplayUsers.Location = new System.Drawing.Point(113, 116);
this.btnDisplayUsers.Name = "btnDisplayUsers";
this.btnDisplayUsers.Size = new System.Drawing.Size(95, 23);
this.btnDisplayUsers.TabIndex = 7;
this.btnDisplayUsers.Text = "Display Users";
this.btnDisplayUsers.UseVisualStyleBackColor = true;
this.btnDisplayUsers.Click += new System.EventHandler(this.btnDisplayUsers_Click);
//
// btnRemoveUser
//
this.btnRemoveUser.Enabled = false;
this.btnRemoveUser.Location = new System.Drawing.Point(113, 87);
this.btnRemoveUser.Name = "btnRemoveUser";
this.btnRemoveUser.Size = new System.Drawing.Size(95, 23);
this.btnRemoveUser.TabIndex = 6;
this.btnRemoveUser.Text = "Remove User";
this.btnRemoveUser.UseVisualStyleBackColor = true;
this.btnRemoveUser.Click += new System.EventHandler(this.btnRemoveUser_Click);
//
// btnResetPassword
//
this.btnResetPassword.Enabled = false;
this.btnResetPassword.Location = new System.Drawing.Point(9, 116);
this.btnResetPassword.Name = "btnResetPassword";
this.btnResetPassword.Size = new System.Drawing.Size(95, 23);
this.btnResetPassword.TabIndex = 5;
this.btnResetPassword.Text = "ResetPassword";
this.btnResetPassword.UseVisualStyleBackColor = true;
this.btnResetPassword.Click += new System.EventHandler(this.btnResetPassword_Click);
//
// textPassword
//
this.textPassword.Enabled = false;
this.textPassword.Location = new System.Drawing.Point(70, 51);
this.textPassword.Name = "textPassword";
this.textPassword.PasswordChar = '*';
this.textPassword.Size = new System.Drawing.Size(138, 20);
this.textPassword.TabIndex = 4;
//
// textUsername
//
this.textUsername.Enabled = false;
this.textUsername.Location = new System.Drawing.Point(70, 23);
this.textUsername.Name = "textUsername";
this.textUsername.Size = new System.Drawing.Size(138, 20);
this.textUsername.TabIndex = 3;
//
// btnAddUser
//
this.btnAddUser.Enabled = false;
this.btnAddUser.Location = new System.Drawing.Point(9, 87);
this.btnAddUser.Name = "btnAddUser";
this.btnAddUser.Size = new System.Drawing.Size(95, 23);
this.btnAddUser.TabIndex = 2;
this.btnAddUser.Text = "Add User";
this.btnAddUser.UseVisualStyleBackColor = true;
this.btnAddUser.Click += new System.EventHandler(this.btnAddUser_Click);
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(8, 54);
this.label2.Margin = new System.Windows.Forms.Padding(3, 15, 3, 0);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(56, 13);
this.label2.TabIndex = 1;
this.label2.Text = "Password:";
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(6, 26);
this.label1.Margin = new System.Windows.Forms.Padding(3, 10, 3, 0);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(58, 13);
this.label1.TabIndex = 0;
this.label1.Text = "Username:";
//
// textMessages
//
this.textMessages.Location = new System.Drawing.Point(260, 12);
this.textMessages.Multiline = true;
this.textMessages.Name = "textMessages";
this.textMessages.ReadOnly = true;
this.textMessages.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.textMessages.Size = new System.Drawing.Size(362, 403);
this.textMessages.TabIndex = 1;
//
// btnStart
//
this.btnStart.Location = new System.Drawing.Point(6, 20);
this.btnStart.Name = "btnStart";
this.btnStart.Size = new System.Drawing.Size(104, 23);
this.btnStart.TabIndex = 2;
this.btnStart.Text = "Start";
this.btnStart.UseVisualStyleBackColor = true;
this.btnStart.Click += new System.EventHandler(this.btnStart_Click);
//
// btnStop
//
this.btnStop.Location = new System.Drawing.Point(6, 49);
this.btnStop.Name = "btnStop";
this.btnStop.Size = new System.Drawing.Size(104, 23);
this.btnStop.TabIndex = 3;
this.btnStop.Text = "Stop";
this.btnStop.UseVisualStyleBackColor = true;
this.btnStop.Click += new System.EventHandler(this.btnStop_Click);
//
// groupServer
//
this.groupServer.Controls.Add(this.lblServerStatus);
this.groupServer.Controls.Add(this.label3);
this.groupServer.Controls.Add(this.btnStart);
this.groupServer.Controls.Add(this.btnStop);
this.groupServer.Location = new System.Drawing.Point(12, 12);
this.groupServer.Name = "groupServer";
this.groupServer.Size = new System.Drawing.Size(227, 86);
this.groupServer.TabIndex = 4;
this.groupServer.TabStop = false;
this.groupServer.Text = "Server";
//
// lblServerStatus
//
this.lblServerStatus.AutoSize = true;
this.lblServerStatus.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblServerStatus.ForeColor = System.Drawing.Color.Red;
this.lblServerStatus.Location = new System.Drawing.Point(144, 49);
this.lblServerStatus.Name = "lblServerStatus";
this.lblServerStatus.Size = new System.Drawing.Size(56, 17);
this.lblServerStatus.TabIndex = 5;
this.lblServerStatus.Text = "Offline";
this.lblServerStatus.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// label3
//
this.label3.AutoSize = true;
this.label3.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label3.Location = new System.Drawing.Point(127, 20);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(94, 17);
this.label3.TabIndex = 4;
this.label3.Text = "Server Status";
//
// groupSendMessage
//
this.groupSendMessage.Controls.Add(this.textSendMessage);
this.groupSendMessage.Controls.Add(this.btnSendMessage);
this.groupSendMessage.Location = new System.Drawing.Point(12, 287);
this.groupSendMessage.Margin = new System.Windows.Forms.Padding(3, 15, 3, 3);
this.groupSendMessage.Name = "groupSendMessage";
this.groupSendMessage.Size = new System.Drawing.Size(227, 128);
this.groupSendMessage.TabIndex = 5;
this.groupSendMessage.TabStop = false;
this.groupSendMessage.Text = "Send Message";
//
// textSendMessage
//
this.textSendMessage.Enabled = false;
this.textSendMessage.Location = new System.Drawing.Point(11, 23);
this.textSendMessage.Multiline = true;
this.textSendMessage.Name = "textSendMessage";
this.textSendMessage.Size = new System.Drawing.Size(197, 60);
this.textSendMessage.TabIndex = 3;
//
// btnSendMessage
//
this.btnSendMessage.Enabled = false;
this.btnSendMessage.Location = new System.Drawing.Point(11, 89);
this.btnSendMessage.Name = "btnSendMessage";
this.btnSendMessage.Size = new System.Drawing.Size(75, 23);
this.btnSendMessage.TabIndex = 2;
this.btnSendMessage.Text = "Send";
this.btnSendMessage.UseVisualStyleBackColor = true;
this.btnSendMessage.Click += new System.EventHandler(this.btnSendMessage_Click);
//
// Form
//
this.AcceptButton = this.btnSendMessage;
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(634, 429);
this.Controls.Add(this.groupSendMessage);
this.Controls.Add(this.groupServer);
this.Controls.Add(this.textMessages);
this.Controls.Add(this.groupCreateUser);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.Name = "Form";
this.Text = "Server";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Form_Closing);
this.groupCreateUser.ResumeLayout(false);
this.groupCreateUser.PerformLayout();
this.groupServer.ResumeLayout(false);
this.groupServer.PerformLayout();
this.groupSendMessage.ResumeLayout(false);
this.groupSendMessage.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.GroupBox groupCreateUser;
private System.Windows.Forms.Button btnResetPassword;
private System.Windows.Forms.TextBox textPassword;
private System.Windows.Forms.TextBox textUsername;
private System.Windows.Forms.Button btnAddUser;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Button btnStart;
private System.Windows.Forms.Button btnStop;
private System.Windows.Forms.GroupBox groupServer;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.GroupBox groupSendMessage;
private System.Windows.Forms.TextBox textSendMessage;
private System.Windows.Forms.Button btnSendMessage;
public System.Windows.Forms.Label lblServerStatus;
public System.Windows.Forms.TextBox textMessages;
private System.Windows.Forms.Button btnDisplayUsers;
private System.Windows.Forms.Button btnRemoveUser;
}
}
| 49.362416 | 173 | 0.591027 | [
"MIT"
] | Icemaush/Multi-Client_ChatApplication | Server/Form.Designer.cs | 14,712 | C# |
/*
* SCORM Cloud Rest API
*
* REST API used for SCORM Cloud integrations.
*
* OpenAPI spec version: 2.0
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using SwaggerDateConverter = Com.RusticiSoftware.Cloud.V2.Client.SwaggerDateConverter;
namespace Com.RusticiSoftware.Cloud.V2.Model
{
/// <summary>
/// DispatchIdSchema
/// </summary>
[DataContract]
public partial class DispatchIdSchema : IEquatable<DispatchIdSchema>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="DispatchIdSchema" /> class.
/// </summary>
/// <param name="id">id.</param>
/// <param name="data">data.</param>
public DispatchIdSchema(string id = default(string), DispatchSchema data = default(DispatchSchema))
{
this.Id = id;
this.Data = data;
}
/// <summary>
/// Gets or Sets Id
/// </summary>
[DataMember(Name="id", EmitDefaultValue=false)]
public string Id { get; set; }
/// <summary>
/// Gets or Sets Data
/// </summary>
[DataMember(Name="data", EmitDefaultValue=false)]
public DispatchSchema Data { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class DispatchIdSchema {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" Data: ").Append(Data).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as DispatchIdSchema);
}
/// <summary>
/// Returns true if DispatchIdSchema instances are equal
/// </summary>
/// <param name="input">Instance of DispatchIdSchema to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(DispatchIdSchema input)
{
if (input == null)
return false;
return
(
this.Id == input.Id ||
(this.Id != null &&
this.Id.Equals(input.Id))
) &&
(
this.Data == input.Data ||
(this.Data != null &&
this.Data.Equals(input.Data))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.Id != null)
hashCode = hashCode * 59 + this.Id.GetHashCode();
if (this.Data != null)
hashCode = hashCode * 59 + this.Data.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| 31.531915 | 140 | 0.549933 | [
"Apache-2.0"
] | RusticiSoftware/scormcloud-api-v2-client-net | src/Com.RusticiSoftware.Cloud.V2/Model/DispatchIdSchema.cs | 4,446 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.