content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
using System;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Columns;
using BenchmarkDotNet.Configs;
using BenchmarkDotNet.Diagnosers;
using BenchmarkDotNet.Exporters;
using BenchmarkDotNet.Jobs;
using BenchmarkDotNet.Loggers;
using BenchmarkDotNet.Running;
namespace SpanBenchmark
{
class Program
{
static void Main(string[] args)
{
BenchmarkRunner.Run<CsvLineReaderBenchmark>(new BenchmarkConfig());
}
}
public class BenchmarkConfig : ManualConfig
{
public BenchmarkConfig()
{
Add(Job.Default);
Add(DefaultColumnProviders.Instance);
Add(MarkdownExporter.GitHub);
Add(new ConsoleLogger());
Add(new HtmlExporter());
Add(MemoryDiagnoser.Default);
}
}
public class CsvLineReaderBenchmark
{
private static readonly string s_csvLine = $"1,{Guid.NewGuid()},1.25,true,hogefuga";
[Benchmark]
public Record StringSplit()
{
string[] split = s_csvLine.Split(',', 5);
return new Record()
{
UserId = int.Parse(split[0]),
SessionId = Guid.Parse(split[1]),
Rate = double.Parse(split[2]),
Enabled = bool.Parse(split[3]),
Comment = split[4]
};
}
[Benchmark]
public Record Span()
{
var reader = new SpanCsvReader(s_csvLine);
var record = new Record()
{
UserId = int.Parse(reader.ReadNext()),
SessionId = Guid.Parse(reader.ReadNext()),
Rate = double.Parse(reader.ReadNext()),
Enabled = bool.Parse(reader.ReadNext()),
Comment = new string(reader.ReadNext())
};
return record;
}
private ref struct SpanCsvReader
{
private ReadOnlySpan<char> _chars;
public SpanCsvReader(string s)
{
_chars = s.AsSpan();
}
public ReadOnlySpan<char> ReadNext()
{
var commaIndex = _chars.IndexOf(',');
if (commaIndex > 0)
{
var ret = _chars.Slice(0, commaIndex);
_chars = _chars.Slice(commaIndex + 1);
return ret;
}
else
{
var ret = _chars;
_chars = ReadOnlySpan<char>.Empty;
return ret;
}
}
}
}
public class Record
{
public int UserId { get; set; }
public Guid SessionId { get; set; }
public double Rate { get; set; }
public bool Enabled { get; set; }
public string Comment { get; set; }
}
} | 26.87156 | 92 | 0.499488 | [
"MIT"
] | wipiano/csharp-misc | Misc2018/SpanBenchmark/Program.cs | 2,931 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
namespace DemoApi
{
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.12 | 76 | 0.691542 | [
"MIT"
] | pmckanry/demo-api | DemoApi/Program.cs | 605 | 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.Aws.WafV2.Inputs
{
public sealed class WebAclRuleStatementNotStatementStatementNotStatementStatementAndStatementStatementIpSetReferenceStatementArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The Amazon Resource Name (ARN) of the IP Set that this statement references.
/// </summary>
[Input("arn", required: true)]
public Input<string> Arn { get; set; } = null!;
public WebAclRuleStatementNotStatementStatementNotStatementStatementAndStatementStatementIpSetReferenceStatementArgs()
{
}
}
}
| 34.576923 | 155 | 0.723026 | [
"ECL-2.0",
"Apache-2.0"
] | mdop-wh/pulumi-aws | sdk/dotnet/WafV2/Inputs/WebAclRuleStatementNotStatementStatementNotStatementStatementAndStatementStatementIpSetReferenceStatementArgs.cs | 899 | C# |
using NUnit.Framework;
using Securo.GlobalPlatform.Interfaces;
using Securo.GlobalPlatform.Model;
using Securo.GlobalPlatform.SecureMessaging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Securo.GlobalPlatform.SecureMessaging.Tests
{
[TestFixture()]
public class SecureSessionDetailsCreatorTests
{
private ISecureSessionDetailsCreator cut;
[TestCase("0000417100760397383602020040D46349081C02164BC640D23E80D6", (byte)0x02)]
[TestCase("00000346020614090044010360C77C60598FC0D3D4F21520D3A7E8CB34", (byte)0x03)]
public void ShouldCreateSessionDetails(string cardRecognitionData, byte scpMode)
{
// arrange
cut = new SecureSessionDetailsCreator();
// act
var result = cut.Create(cardRecognitionData);
// assert
Assert.AreEqual(result.ScpInfo.ScpIdentifier, scpMode);
}
}
} | 30.90625 | 92 | 0.718908 | [
"MIT"
] | dimatteo31/securo-gp | tests/Securo.GlobalPlatform.Tests/SecureMessaging/SecureSessionDetailsCreatorTests.cs | 991 | 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("ACAT-French")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ACAT-French")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("0078065e-aaff-4ff2-a340-40e49e47cea1")]
// 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.702703 | 84 | 0.743369 | [
"Apache-2.0"
] | 125m125/acat | src/LanguagePacks/French/Resources/Properties/AssemblyInfo.cs | 1,398 | C# |
// Copyright 2010 Max Toro Q.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Schema;
using Saxon.Api;
namespace myxsl.net.saxon {
sealed class SaxonAtomicValueWrapper : XPathItem {
readonly XdmAtomicValue atomicValue;
XmlSchemaType _XmlType;
public XdmAtomicValue UnderlyingObject { get { return atomicValue; } }
public override bool IsNode {
get { return false; }
}
public override object TypedValue {
get { return this.atomicValue.Value; }
}
public override string Value {
get { return this.atomicValue.ToString(); }
}
public override bool ValueAsBoolean {
get { return (bool)this.TypedValue; }
}
public override DateTime ValueAsDateTime {
get { return (DateTime)this.TypedValue; }
}
public override double ValueAsDouble {
get { return (double)this.TypedValue; }
}
public override int ValueAsInt {
get { return (int)this.TypedValue; }
}
public override long ValueAsLong {
get { return (long)this.TypedValue; }
}
public override Type ValueType {
get { return this.TypedValue.GetType(); }
}
public override XmlSchemaType XmlType {
get {
if (_XmlType == null)
_XmlType = XmlSchemaType.GetBuiltInSimpleType(this.atomicValue.GetPrimitiveTypeName().ToXmlQualifiedName());
return _XmlType;
}
}
public SaxonAtomicValueWrapper(XdmAtomicValue atomicValue) {
if (atomicValue == null) throw new ArgumentNullException("atomicValue");
this.atomicValue = atomicValue;
}
public override object ValueAs(Type returnType, IXmlNamespaceResolver nsResolver) {
throw new NotImplementedException();
}
}
}
| 28.853933 | 124 | 0.639019 | [
"BSD-3-Clause"
] | mdavid/nuxleus | src/Nuxleus.Xameleon/Saxon/SaxonAtomicValueWrapper.cs | 2,570 | C# |
using System.Collections.Generic;
using Tetra.EntityManagement;
using UnityEngine;
namespace Tetra.Rendering
{
public class EntityRenderer<T> : EntityRenderer where T : Entity
{
public override void Draw()
{
for (int i = 0; entities.Count > i; i++)
Graphics.DrawMesh(mesh, entities[i].matrix, material, layer, camera, subMeshIndex, entities[i].materialPropertyBlock, castShadows, receiveShadows);
}
public void SetEntities(List<T> entities) => this.entities = entities;
private List<T> entities { get; set; }
public EntityRenderer(List<T> entities, Mesh mesh, Material material, Camera camera, int layer = 8, int subMeshIndex = 0, bool castShadows = false, bool receiveShadows = false )
: base(mesh, material, camera, layer, subMeshIndex, castShadows, receiveShadows)
=> this.entities = entities;
}
public abstract class EntityRenderer : AbstractRenderer
{
protected EntityRenderer(Mesh mesh, Material material, Camera camera, int layer = 8, int subMeshIndex = 0, bool castShadows = false, bool receiveShadows = false)
: base(mesh, material, camera, layer, subMeshIndex, castShadows, receiveShadows) { }
}
} | 43.448276 | 186 | 0.676984 | [
"Unlicense"
] | Slaktus/Tetra | Tetra/Rendering/EntityRenderer.cs | 1,262 | C# |
// <copyright file="RectStruct.cs" company="Flogard Services">
// The MIT License (MIT)
//
// Copyright (c) 2020 Trym Lund Flogard and contributors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// </copyright>
using System.Runtime.InteropServices;
namespace WindowExtensions
{
/// <summary>
/// The RECT structure defines the coordinates of the upper-left and lower-right corners of a rectangle.
/// </summary>
/// <see http="http://msdn.microsoft.com/en-us/library/dd162897%28VS.85%29.aspx"/>
/// <remarks>
/// By convention, the right and bottom edges of the rectangle are normally considered exclusive.
/// In other words, the pixel whose coordinates are ( right, bottom ) lies immediately outside of the the rectangle.
/// For example, when RECT is passed to the FillRect function, the rectangle is filled up to, but not including,
/// the right column and bottom row of pixels. This structure is identical to the RECTL structure.
/// </remarks>
[StructLayout(LayoutKind.Sequential)]
public struct RectStruct
{
/// <summary>
/// The x-coordinate of the upper-left corner of the rectangle.
/// </summary>
public int Left;
/// <summary>
/// The y-coordinate of the upper-left corner of the rectangle.
/// </summary>
public int Top;
/// <summary>
/// The x-coordinate of the lower-right corner of the rectangle.
/// </summary>
public int Right;
/// <summary>
/// The y-coordinate of the lower-right corner of the rectangle.
/// </summary>
public int Bottom;
}
}
| 42.571429 | 120 | 0.692394 | [
"MIT"
] | trympet/wpf-window-extensions | Structures/RectStruct.cs | 2,684 | C# |
using Native.Csharp.App.Gameplay;
using Native.Csharp.App.UserInteract;
using Native.Csharp.App.Util;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace Native.Csharp.App
{
public class Values
{
public List<Dice> dices = new List<Dice>
{
new Dice(1, 4),
new Dice(2, 4),
new Dice(3, 4),
new Dice(1, 6),
new Dice(2, 6),
new Dice(1, 8),
new Dice(1, 10),
new Dice(1, 20),
new Dice(1, 100)
};
public const string RegexDice = "^\\d+d\\d+$";
public const string RegexName = "^[\\u4e00-\\u9fa5]+$";
public const string RegexLocaleKey = "\\{[A-Z_]+\\}";
public const string RegexLocaleKeyArgument = "\\{[a-z_]+\\}";
public static readonly int[] BAB_Half = new int[21]
{
0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10
};
public static readonly int[] BAB_viertel = new int[21]
{
0, 0, 1, 2, 3, 3, 4, 5, 6, 6, 7, 8, 9, 9, 10, 11, 12, 12, 13, 14, 15
};
public static readonly int[] BAB_Full = new int[21]
{
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20
};
public static readonly int[] SavingWeak = new int[21]
{
0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6
};
public static readonly int[] SavingStrong = new int[21]
{
0, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12
};
public static readonly int[,] SpellSlotTableStandard = new int[21,10]
{
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{3, 1, 0, 0, 0, 0, 0, 0, 0, 0 },
{4, 2, 0, 0, 0, 0, 0, 0, 0, 0 },
{4, 2, 1, 0, 0, 0, 0, 0, 0, 0 },
{4, 3, 2, 0, 0, 0, 0, 0, 0, 0 },
{4, 3, 2, 1, 0, 0, 0, 0, 0, 0 },
{4, 3, 3, 2, 0, 0, 0, 0, 0, 0 },
{4, 4, 3, 2, 1, 0, 0, 0, 0, 0 },
{4, 4, 3, 3, 2, 0, 0, 0, 0, 0 },
{4, 4, 4, 3, 2, 1, 0, 0, 0, 0 },
{4, 4, 4, 3, 3, 2, 0, 0, 0, 0 },
{4, 4, 4, 4, 3, 2, 1, 0, 0, 0 },
{4, 4, 4, 4, 3, 3, 2, 0, 0, 0 },
{4, 4, 4, 4, 4, 3, 2, 1, 0, 0 },
{4, 4, 4, 4, 4, 3, 3, 2, 0, 0 },
{4, 4, 4, 4, 4, 4, 3, 2, 1, 0 },
{4, 4, 4, 4, 4, 4, 3, 3, 2, 0 },
{4, 4, 4, 4, 4, 4, 4, 3, 2, 1 },
{4, 4, 4, 4, 4, 4, 4, 3, 3, 2 },
{4, 4, 4, 4, 4, 4, 4, 4, 3, 3 },
{4, 4, 4, 4, 4, 4, 4, 4, 4, 4 }
};
public readonly Flag Flag_ActionHeal = new Flag(Flag.Action_FlagName_ActionType, Flag.Action_FlagContent_TypeHeal); //是一个治疗动作
public readonly Flag Flag_FromNature = new Flag(Flag.Action_FlagName_Sender, Flag.Action_FlagContent_SourceNature); //来源为自然
public readonly Flag Flag_FromTime = new Flag(Flag.Action_FlagName_Sender, Flag.Action_FlagContent_SourceTime); //来源为时间流逝
public readonly Flag Flag_ObjectCharacter = new Flag(Flag.Action_FlagName_Object, Flag.Action_FlagContent_SourceCharacter); //目标为角色
public readonly Flag Flag_CanBenefitFromRest = new Flag(Flag.Status_FlagName_CanBenefitFromRest, "true");
public readonly Flag Flag_CanNotBenefitFromRest = new Flag(Flag.Status_FlagName_CanBenefitFromRest, "false");
public static readonly TimeSpan Day = new TimeSpan(TimeSpan.TicksPerDay);
public static readonly TimeSpan Hour = new TimeSpan(TimeSpan.TicksPerHour);
public static readonly TimeSpan Minute = new TimeSpan(TimeSpan.TicksPerMinute);
public Dice GetDice(string target)
{
MatchCollection matches = Regex.Matches(target, RegexDice);
if (matches.Count > 0)
{
foreach (Dice dice in dices)
if (target == dice.ToString())
return dice;
return ParseDice(matches[0].Value);
}
return null;
}
public static int GetModifier(int Property)
{
return (Property / 2 - 5);
}
private Dice ParseDice(string dice)
{
MatchCollection matches = Regex.Matches(dice, "\\d+");
Dice result = new Dice(byte.Parse(matches[0].Value), byte.Parse(matches[1].Value));
if (result.IsValid())
return result;
return null;
}
public static string TimeToString(TimeSpan time)
{
string result = "";
if (time.Days != 0)
result += time.Days + "天";
if (time.Hours != 0)
result += time.Hours + "小时";
if (time.Minutes != 0)
result += time.Minutes + "分钟";
if (time.Seconds != 0)
result += time.Seconds + "秒";
return result;
}
}
}
| 36.728571 | 139 | 0.491054 | [
"MIT"
] | apflu/DungeonBot | Native.Csharp/App/Values.cs | 5,204 | 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.Insights.V20200501Preview
{
/// <summary>
/// The scheduled query rule resource.
/// </summary>
[AzureNativeResourceType("azure-native:insights/v20200501preview:ScheduledQueryRule")]
public partial class ScheduledQueryRule : Pulumi.CustomResource
{
[Output("actions")]
public Output<ImmutableArray<Outputs.ActionResponse>> Actions { get; private set; } = null!;
/// <summary>
/// The api-version used when creating this alert rule
/// </summary>
[Output("createdWithApiVersion")]
public Output<string> CreatedWithApiVersion { get; private set; } = null!;
/// <summary>
/// The rule criteria that defines the conditions of the scheduled query rule.
/// </summary>
[Output("criteria")]
public Output<Outputs.ScheduledQueryRuleCriteriaResponse> Criteria { get; private set; } = null!;
/// <summary>
/// The description of the scheduled query rule.
/// </summary>
[Output("description")]
public Output<string?> Description { get; private set; } = null!;
/// <summary>
/// The display name of the alert rule
/// </summary>
[Output("displayName")]
public Output<string?> DisplayName { get; private set; } = null!;
/// <summary>
/// The flag which indicates whether this scheduled query rule is enabled. Value should be true or false
/// </summary>
[Output("enabled")]
public Output<bool> Enabled { get; private set; } = null!;
/// <summary>
/// The etag field is *not* required. If it is provided in the response body, it must also be provided as a header per the normal etag convention. Entity tags are used for comparing two or more entities from the same requested resource. HTTP/1.1 uses entity tags in the etag (section 14.19), If-Match (section 14.24), If-None-Match (section 14.26), and If-Range (section 14.27) header fields.
/// </summary>
[Output("etag")]
public Output<string> Etag { get; private set; } = null!;
/// <summary>
/// How often the scheduled query rule is evaluated represented in ISO 8601 duration format.
/// </summary>
[Output("evaluationFrequency")]
public Output<string> EvaluationFrequency { get; private set; } = null!;
/// <summary>
/// True if alert rule is legacy Log Analytic rule
/// </summary>
[Output("isLegacyLogAnalyticsRule")]
public Output<bool> IsLegacyLogAnalyticsRule { get; private set; } = null!;
/// <summary>
/// Metadata used by portal/tooling/etc to render different UX experiences for resources of the same type; e.g. ApiApps are a kind of Microsoft.Web/sites type. If supported, the resource provider must validate and persist this value.
/// </summary>
[Output("kind")]
public Output<string> Kind { get; private set; } = null!;
/// <summary>
/// The geo-location where the resource lives
/// </summary>
[Output("location")]
public Output<string> Location { get; private set; } = null!;
/// <summary>
/// Mute actions for the chosen period of time (in ISO 8601 duration format) after the alert is fired.
/// </summary>
[Output("muteActionsDuration")]
public Output<string?> MuteActionsDuration { get; private set; } = null!;
/// <summary>
/// The name of the resource
/// </summary>
[Output("name")]
public Output<string> Name { get; private set; } = null!;
/// <summary>
/// If specified then overrides the query time range (default is WindowSize*NumberOfEvaluationPeriods)
/// </summary>
[Output("overrideQueryTimeRange")]
public Output<string?> OverrideQueryTimeRange { get; private set; } = null!;
/// <summary>
/// The list of resource id's that this scheduled query rule is scoped to.
/// </summary>
[Output("scopes")]
public Output<ImmutableArray<string>> Scopes { get; private set; } = null!;
/// <summary>
/// Severity of the alert. Should be an integer between [0-4]. Value of 0 is severest
/// </summary>
[Output("severity")]
public Output<double> Severity { get; private set; } = null!;
/// <summary>
/// Resource tags.
/// </summary>
[Output("tags")]
public Output<ImmutableDictionary<string, string>?> Tags { get; private set; } = null!;
/// <summary>
/// List of resource type of the target resource(s) on which the alert is created/updated. For example if the scope is a resource group and targetResourceTypes is Microsoft.Compute/virtualMachines, then a different alert will be fired for each virtual machine in the resource group which meet the alert criteria
/// </summary>
[Output("targetResourceTypes")]
public Output<ImmutableArray<string>> TargetResourceTypes { get; private set; } = null!;
/// <summary>
/// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts"
/// </summary>
[Output("type")]
public Output<string> Type { get; private set; } = null!;
/// <summary>
/// The period of time (in ISO 8601 duration format) on which the Alert query will be executed (bin size).
/// </summary>
[Output("windowSize")]
public Output<string> WindowSize { get; private set; } = null!;
/// <summary>
/// Create a ScheduledQueryRule resource with the given unique name, arguments, and options.
/// </summary>
///
/// <param name="name">The unique name of the resource</param>
/// <param name="args">The arguments used to populate this resource's properties</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public ScheduledQueryRule(string name, ScheduledQueryRuleArgs args, CustomResourceOptions? options = null)
: base("azure-native:insights/v20200501preview:ScheduledQueryRule", name, args ?? new ScheduledQueryRuleArgs(), MakeResourceOptions(options, ""))
{
}
private ScheduledQueryRule(string name, Input<string> id, CustomResourceOptions? options = null)
: base("azure-native:insights/v20200501preview:ScheduledQueryRule", name, null, MakeResourceOptions(options, id))
{
}
private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id)
{
var defaultOptions = new CustomResourceOptions
{
Version = Utilities.Version,
Aliases =
{
new Pulumi.Alias { Type = "azure-nextgen:insights/v20200501preview:ScheduledQueryRule"},
new Pulumi.Alias { Type = "azure-native:insights:ScheduledQueryRule"},
new Pulumi.Alias { Type = "azure-nextgen:insights:ScheduledQueryRule"},
new Pulumi.Alias { Type = "azure-native:insights/v20180416:ScheduledQueryRule"},
new Pulumi.Alias { Type = "azure-nextgen:insights/v20180416:ScheduledQueryRule"},
new Pulumi.Alias { Type = "azure-native:insights/v20210201preview:ScheduledQueryRule"},
new Pulumi.Alias { Type = "azure-nextgen:insights/v20210201preview:ScheduledQueryRule"},
},
};
var merged = CustomResourceOptions.Merge(defaultOptions, options);
// Override the ID if one was specified for consistency with other language SDKs.
merged.Id = id ?? merged.Id;
return merged;
}
/// <summary>
/// Get an existing ScheduledQueryRule resource's state with the given name, ID, and optional extra
/// properties used to qualify the lookup.
/// </summary>
///
/// <param name="name">The unique name of the resulting resource.</param>
/// <param name="id">The unique provider ID of the resource to lookup.</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public static ScheduledQueryRule Get(string name, Input<string> id, CustomResourceOptions? options = null)
{
return new ScheduledQueryRule(name, id, options);
}
}
public sealed class ScheduledQueryRuleArgs : Pulumi.ResourceArgs
{
[Input("actions")]
private InputList<Inputs.ActionArgs>? _actions;
public InputList<Inputs.ActionArgs> Actions
{
get => _actions ?? (_actions = new InputList<Inputs.ActionArgs>());
set => _actions = value;
}
/// <summary>
/// The rule criteria that defines the conditions of the scheduled query rule.
/// </summary>
[Input("criteria", required: true)]
public Input<Inputs.ScheduledQueryRuleCriteriaArgs> Criteria { get; set; } = null!;
/// <summary>
/// The description of the scheduled query rule.
/// </summary>
[Input("description")]
public Input<string>? Description { get; set; }
/// <summary>
/// The display name of the alert rule
/// </summary>
[Input("displayName")]
public Input<string>? DisplayName { get; set; }
/// <summary>
/// The flag which indicates whether this scheduled query rule is enabled. Value should be true or false
/// </summary>
[Input("enabled", required: true)]
public Input<bool> Enabled { get; set; } = null!;
/// <summary>
/// How often the scheduled query rule is evaluated represented in ISO 8601 duration format.
/// </summary>
[Input("evaluationFrequency", required: true)]
public Input<string> EvaluationFrequency { get; set; } = null!;
/// <summary>
/// The geo-location where the resource lives
/// </summary>
[Input("location")]
public Input<string>? Location { get; set; }
/// <summary>
/// Mute actions for the chosen period of time (in ISO 8601 duration format) after the alert is fired.
/// </summary>
[Input("muteActionsDuration")]
public Input<string>? MuteActionsDuration { get; set; }
/// <summary>
/// If specified then overrides the query time range (default is WindowSize*NumberOfEvaluationPeriods)
/// </summary>
[Input("overrideQueryTimeRange")]
public Input<string>? OverrideQueryTimeRange { get; set; }
/// <summary>
/// The name of the resource group.
/// </summary>
[Input("resourceGroupName", required: true)]
public Input<string> ResourceGroupName { get; set; } = null!;
/// <summary>
/// The name of the rule.
/// </summary>
[Input("ruleName")]
public Input<string>? RuleName { get; set; }
[Input("scopes", required: true)]
private InputList<string>? _scopes;
/// <summary>
/// The list of resource id's that this scheduled query rule is scoped to.
/// </summary>
public InputList<string> Scopes
{
get => _scopes ?? (_scopes = new InputList<string>());
set => _scopes = value;
}
/// <summary>
/// Severity of the alert. Should be an integer between [0-4]. Value of 0 is severest
/// </summary>
[Input("severity", required: true)]
public Input<double> Severity { get; set; } = null!;
[Input("tags")]
private InputMap<string>? _tags;
/// <summary>
/// Resource tags.
/// </summary>
public InputMap<string> Tags
{
get => _tags ?? (_tags = new InputMap<string>());
set => _tags = value;
}
[Input("targetResourceTypes")]
private InputList<string>? _targetResourceTypes;
/// <summary>
/// List of resource type of the target resource(s) on which the alert is created/updated. For example if the scope is a resource group and targetResourceTypes is Microsoft.Compute/virtualMachines, then a different alert will be fired for each virtual machine in the resource group which meet the alert criteria
/// </summary>
public InputList<string> TargetResourceTypes
{
get => _targetResourceTypes ?? (_targetResourceTypes = new InputList<string>());
set => _targetResourceTypes = value;
}
/// <summary>
/// The period of time (in ISO 8601 duration format) on which the Alert query will be executed (bin size).
/// </summary>
[Input("windowSize", required: true)]
public Input<string> WindowSize { get; set; } = null!;
public ScheduledQueryRuleArgs()
{
}
}
}
| 43.163987 | 402 | 0.608239 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/Insights/V20200501Preview/ScheduledQueryRule.cs | 13,424 | C# |
/*
* Licensed to SharpSoftware under one or more contributor
* license agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*
* SharpSoftware licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System.Collections.Generic;
using Itinero.Optimization.Models.TimeWindows;
using Itinero.Optimization.Models.Vehicles;
using Itinero.Optimization.Models.Visits;
namespace Itinero.Optimization.Models
{
/// <summary>
/// Contains extension methods for model validation.
/// </summary>
public static class ModelValidation
{
/// <summary>
/// Validates the model, returns a message if invalid.
/// </summary>
/// <param name="model">The model.</param>
/// <param name="message">The message if invalid.</param>
/// <returns>True if valid, false otherwise.</returns>
internal static bool IsValid(this Model model, out string message)
{
if (model.VehiclePool == null)
{
message = "No vehicle pool defined.";
return false;
}
if (!model.VehiclePool.IsValid(out var vpMessage))
{
message = $"Invalid vehicle pool: {vpMessage}";
return false;
}
if (model.Visits == null ||
model.Visits.Length == 0)
{
message = "No visits defined.";
return false;
}
if (!model.Visits.AreValid(out message))
{
message = $"Invalid visit: {message}";
return false;
}
message = string.Empty;
return true;
}
/// <summary>
/// Validates that the given vehicle pool is valid.
/// </summary>
/// <param name="vehiclePool">The vehicle pool.</param>
/// <param name="message">The message if invalid.</param>
/// <returns>True if valid, false otherwise.</returns>
private static bool IsValid(this VehiclePool vehiclePool, out string message)
{
if (vehiclePool.Vehicles == null ||
vehiclePool.Vehicles.Length == 0)
{
message = "No vehicles defined in vehicle pool, at least one vehicle is required.";
return false;
}
for (var v = 0; v < vehiclePool.Vehicles.Length; v++)
{
var vehicle = vehiclePool.Vehicles[v];
if (vehicle == null)
{
message = $"Vehicle at index {v} is null.";
return false;
}
if (!vehicle.IsValid(out message))
{
message = $"Vehicle at index {v} is invalid: {message}";
return false;
}
}
message = string.Empty;
return true;
}
/// <summary>
/// Validates that the given vehicle is valid.
/// </summary>
/// <param name="vehicle">The vehicle.</param>
/// <param name="message">The message if invalid.</param>
/// <returns>True if valid, false otherwise.</returns>
private static bool IsValid(this Vehicle vehicle, out string message)
{
if (string.IsNullOrWhiteSpace(vehicle.Metric))
{
message = $"Vehicle doesn't have a metric.";
return false;
}
if (string.IsNullOrWhiteSpace(vehicle.Profile))
{
message = $"Vehicle doesn't have a profile.";
return false;
}
if (vehicle.CapacityConstraints != null)
{
for (var cc = 0; cc < vehicle.CapacityConstraints.Length; cc++)
{
var capacityContraint = vehicle.CapacityConstraints[cc];
if (capacityContraint == null)
{
message = $"Vehicle has a capacity constraint at index {cc} that's null.";
return false;
}
if (string.IsNullOrWhiteSpace(capacityContraint.Metric))
{
message = $"Vehicle has a capacity constraint at index {cc} that doesn't have a proper metric set.";
return false;
}
if (capacityContraint.Capacity <= 0)
{
message = $"Vehicle has a capacity constraint at index {cc} that has a capacity <= 0.";
return false;
}
}
}
message = string.Empty;
return true;
}
/// <summary>
/// Validates the visits and checks if they are valid.
/// </summary>
/// <param name="visits">The visits.</param>
/// <param name="message">The message if invalid.</param>
/// <returns>True if valid, false otherwise.</returns>
private static bool AreValid(this Visit[] visits, out string message)
{
var visitCostMetrics = new HashSet<string>();
for (var v = 0; v < visits.Length; v++)
{
var visit = visits[v];
if (visit == null)
{
message = $"Visit at index {v} is null.";
return false;
}
if (!visit.TimeWindow.IsValid(out var twMessage))
{
message = $"Time window for visit at index {v} invalid: {twMessage}";
return false;
}
var visitCosts = visit.VisitCosts;
if (visitCosts != null)
{
visitCostMetrics.Clear();
for (var vc = 0; vc < visitCosts.Length; vc++)
{
var visitCost = visitCosts[vc];
if (visitCost == null)
{
message = $"Visit at index {v} has a visit cost at index {vc} that is null.";
return false;
}
if (visitCost.Value < 0)
{
message = $"Visit at index {v} has a visit cost at index {vc} that has a value < 0.";
return false;
}
if (visitCostMetrics.Contains(visitCost.Metric))
{
message = $"Visit at index {v} has a visit cost at index {vc} that has a duplicate metric {visitCost.Metric}.";
return false;
}
visitCostMetrics.Add(visitCost.Metric);
}
}
}
message = string.Empty;
return true;
}
/// <summary>
/// Validates the time window and checks if it's valid.
/// </summary>
/// <param name="tw">The time window.</param>
/// <param name="message">The message if invalid.</param>
/// <returns>True if valid, false otherwise.</returns>
private static bool IsValid(this TimeWindow tw, out string message)
{
if (tw == null)
{
message = string.Empty;
return true;
}
if (tw.IsEmpty)
{
message = string.Empty;
return true;
}
if (tw.Min >= tw.Max)
{
message = $"Max has to be >= min: {tw}";
return false;
}
message = string.Empty;
return true;
}
}
} | 36.519313 | 139 | 0.482783 | [
"Apache-2.0"
] | itinero/logistics | src/Itinero.Optimization/Models/ModelValidation.cs | 8,511 | C# |
using Abp.AutoMapper;
using FuelWerx.Invoices.Dto;
using System;
using System.Runtime.CompilerServices;
namespace FuelWerx.Web.Areas.Mpa.Models.Invoices
{
[AutoMapFrom(new Type[] { typeof(GetInvoiceResourceForEditOutput) })]
public class CreateOrUpdateInvoiceResourcesModalViewModel : GetInvoiceResourceForEditOutput
{
public long InvoiceId
{
get;
set;
}
public virtual string InvoiceName
{
get;
set;
}
public CreateOrUpdateInvoiceResourcesModalViewModel(GetInvoiceResourceForEditOutput output)
{
output.MapTo<GetInvoiceResourceForEditOutput, CreateOrUpdateInvoiceResourcesModalViewModel>(this);
}
public string FileSizeDisplay(long fileSize)
{
string[] strArrays = new string[] { "B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };
int num = 0;
while (fileSize >= (long)1024)
{
num++;
fileSize = fileSize / (long)1024;
}
return string.Format("{0} {1}", fileSize, strArrays[num]);
}
}
} | 24.05 | 101 | 0.709979 | [
"MIT"
] | zberg007/fuelwerx | src/FuelWerx.Web/Areas/Mpa/Models/Invoices/CreateOrUpdateInvoiceResourcesModalViewModel.cs | 962 | C# |
/*******************************************************
*
* 作者:胡庆访
* 创建时间:20111110
* 说明:此文件只包含一个类,具体内容见类型注释。
* 运行环境:.NET 4.0
* 版本号:1.0.0
*
* 历史记录:
* 创建文件 胡庆访 20111110
*
*******************************************************/
using System.Collections.Generic;
using System.Linq;
using Rafy.Serialization;
using System;
using System.Runtime.Serialization;
namespace Rafy.Serialization.Mobile
{
/// <summary>
/// Defines a dictionary that can be serialized through
/// the MobileFormatter.
/// </summary>
/// <typeparam name="K">Key value: any primitive or IMobileObject type.</typeparam>
/// <typeparam name="V">Value: any primitive or IMobileObject type.</typeparam>
[Serializable]
public class MobileDictionary<K, V> : Dictionary<K, V>, IMobileObject
{
private bool _keyIsMobile;
private bool _valueIsMobile;
/// <summary>
/// Creates an instance of the object.
/// </summary>
public MobileDictionary()
{
DetermineTypes();
}
/// <summary>
/// Creates an instance of the object based
/// on the supplied dictionary, whose elements
/// are copied to the new dictionary.
/// </summary>
/// <param name="capacity">The initial number of elements
/// the dictionary can contain.</param>
public MobileDictionary(int capacity)
: base(capacity)
{
DetermineTypes();
}
/// <summary>
/// Creates an instance of the object based
/// on the supplied dictionary, whose elements
/// are copied to the new dictionary.
/// </summary>
/// <param name="comparer">The comparer to use when
/// comparing keys.</param>
public MobileDictionary(IEqualityComparer<K> comparer)
: base(comparer)
{
DetermineTypes();
}
/// <summary>
/// Creates an instance of the object based
/// on the supplied dictionary, whose elements
/// are copied to the new dictionary.
/// </summary>
/// <param name="dict">Source dictionary.</param>
public MobileDictionary(Dictionary<K, V> dict)
: base(dict)
{
DetermineTypes();
}
private void DetermineTypes()
{
_keyIsMobile = typeof(IMobileObject).IsAssignableFrom(typeof(K));
_valueIsMobile = typeof(IMobileObject).IsAssignableFrom(typeof(V));
}
#region Mobile Serialization
private const string _keyPrefix = "k";
private const string _valuePrefix = "v";
void IMobileObject.SerializeRef(ISerializationContext context)
{
var formatter = context.RefFormatter;
int count = 0;
foreach (var key in this.Keys)
{
if (_keyIsMobile)
{
context.AddRef(_keyPrefix + count, key);
}
else
{
context.AddState(_keyPrefix + count, key);
}
if (_valueIsMobile)
{
context.AddRef(_valuePrefix + count, this[key]);
}
else
{
V value = this[key];
context.AddState(_valuePrefix + count, value);
}
count++;
}
}
void IMobileObject.SerializeState(ISerializationContext info)
{
info.AddState("count", this.Keys.Count);
}
void IMobileObject.DeserializeState(ISerializationContext info) { }
void IMobileObject.DeserializeRef(ISerializationContext info)
{
int count = info.GetState<int>("count");
for (int index = 0; index < count; index++)
{
K key;
if (_keyIsMobile)
key = (K)info.GetRef(_keyPrefix + index);
else
key = info.GetState<K>(_keyPrefix + index);
V value;
if (_valueIsMobile)
value = (V)info.GetRef(_valuePrefix + index);
else
value = info.GetState<V>(_valuePrefix + index);
Add(key, value);
}
}
#endregion
#region System Serialization
protected MobileDictionary(SerializationInfo info, StreamingContext context)
: base(info, context) { }
#endregion
}
} | 28.81875 | 87 | 0.517458 | [
"MIT"
] | zgynhqf/trunk | Rafy/Rafy/ManagedProperty/Serialization/Mobile/MobileDictionary.cs | 4,723 | C# |
// License text here
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ZigBeeNet.ZCL.Protocol;
using ZigBeeNet.ZCL.Field;
using ZigBeeNet.ZCL.Clusters.RSSILocation;
namespace ZigBeeNet.ZCL.Clusters.RSSILocation
{
/// <summary>
/// Get Location Data Command value object class.
/// <para>
/// Cluster: RSSI Location. Command is sent TO the server.
/// This command is a specific command used for the RSSI Location cluster.
/// </para>
/// Code is auto-generated. Modifications may be overwritten!
/// </summary>
public class GetLocationDataCommand : ZclCommand
{
/// <summary>
/// Header command message field.
/// </summary>
public byte Header { get; set; }
/// <summary>
/// Number Responses command message field.
/// </summary>
public byte NumberResponses { get; set; }
/// <summary>
/// Target Address command message field.
/// </summary>
public IeeeAddress TargetAddress { get; set; }
/// <summary>
/// Default constructor.
/// </summary>
public GetLocationDataCommand()
{
GenericCommand = false;
ClusterId = 11;
CommandId = 3;
CommandDirection = ZclCommandDirection.CLIENT_TO_SERVER;
}
internal override void Serialize(ZclFieldSerializer serializer)
{
serializer.Serialize(Header, ZclDataType.Get(DataType.BITMAP_8_BIT));
serializer.Serialize(NumberResponses, ZclDataType.Get(DataType.UNSIGNED_8_BIT_INTEGER));
serializer.Serialize(TargetAddress, ZclDataType.Get(DataType.IEEE_ADDRESS));
}
internal override void Deserialize(ZclFieldDeserializer deserializer)
{
Header = deserializer.Deserialize<byte>(ZclDataType.Get(DataType.BITMAP_8_BIT));
NumberResponses = deserializer.Deserialize<byte>(ZclDataType.Get(DataType.UNSIGNED_8_BIT_INTEGER));
TargetAddress = deserializer.Deserialize<IeeeAddress>(ZclDataType.Get(DataType.IEEE_ADDRESS));
}
public override string ToString()
{
var builder = new StringBuilder();
builder.Append("GetLocationDataCommand [");
builder.Append(base.ToString());
builder.Append(", Header=");
builder.Append(Header);
builder.Append(", NumberResponses=");
builder.Append(NumberResponses);
builder.Append(", TargetAddress=");
builder.Append(TargetAddress);
builder.Append(']');
return builder.ToString();
}
}
}
| 33 | 111 | 0.62306 | [
"EPL-1.0"
] | AutomationGarage/ZigbeeNet | libraries/ZigBeeNet/ZCL/Clusters/RSSILocation/GetLocationDataCommand.cs | 2,708 | C# |
using System;
using System.Collections.Generic;
using System.Runtime.Remoting.Messaging;
using System.Text;
using Senparc.Weixin.Context;
using Senparc.Weixin.MP.Entities;
namespace GRGcms.API.Weixin.Handler
{
public class CustomMessageContext : MessageContext<IRequestMessageBase, IResponseMessageBase>
{
public CustomMessageContext()
{
base.MessageContextRemoved += CustomMessageContext_MessageContextRemoved;
}
/// <summary>
/// 当上下文过期,被移除时触发的时间
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void CustomMessageContext_MessageContextRemoved(object sender, Senparc.Weixin.Context.WeixinContextRemovedEventArgs<IRequestMessageBase, IResponseMessageBase> e)
{
/* 注意,这个事件不是实时触发的(当然你也可以专门写一个线程监控)
* 为了提高效率,根据WeixinContext中的算法,这里的过期消息会在过期后下一条请求执行之前被清除
*/
var messageContext = e.MessageContext as CustomMessageContext;
if (messageContext == null)
{
return;//如果是正常的调用,messageContext不会为null
}
//TODO:这里根据需要执行消息过期时候的逻辑,下面的代码仅供参考
//Log.InfoFormat("{0}的消息上下文已过期",e.OpenId);
//api.SendMessage(e.OpenId, "由于长时间未搭理客服,您的客服状态已退出!");
}
}
}
| 32 | 169 | 0.646341 | [
"MIT"
] | zengfanmao/mpds | LiveVideoSDK/VIMS.Cms/GRGcms.API/Weixin/Handler/CustomMessageContext.cs | 1,622 | 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.AWSMarketplaceMetering")]
#if BCL35
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - AWSMarketplace Metering. The AWS Marketplace Metering Service enables sellers to price their products along new pricing dimensions. After a integrating their product with the AWS Marketplace Metering Service, that product will emit an hourly record capturing the usage of any single pricing dimension. Buyers can easily subscribe to software priced by this new dimension on the AWS Marketplace website and only pay for what they use.")]
#elif BCL45
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (4.5) - AWSMarketplace Metering. The AWS Marketplace Metering Service enables sellers to price their products along new pricing dimensions. After a integrating their product with the AWS Marketplace Metering Service, that product will emit an hourly record capturing the usage of any single pricing dimension. Buyers can easily subscribe to software priced by this new dimension on the AWS Marketplace website and only pay for what they use.")]
#elif PCL
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (PCL) - AWSMarketplace Metering. The AWS Marketplace Metering Service enables sellers to price their products along new pricing dimensions. After a integrating their product with the AWS Marketplace Metering Service, that product will emit an hourly record capturing the usage of any single pricing dimension. Buyers can easily subscribe to software priced by this new dimension on the AWS Marketplace website and only pay for what they use.")]
#elif UNITY
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (Unity) - AWSMarketplace Metering. The AWS Marketplace Metering Service enables sellers to price their products along new pricing dimensions. After a integrating their product with the AWS Marketplace Metering Service, that product will emit an hourly record capturing the usage of any single pricing dimension. Buyers can easily subscribe to software priced by this new dimension on the AWS Marketplace website and only pay for what they use.")]
#elif CORECLR
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (CoreCLR)- AWSMarketplace Metering. The AWS Marketplace Metering Service enables sellers to price their products along new pricing dimensions. After a integrating their product with the AWS Marketplace Metering Service, that product will emit an hourly record capturing the usage of any single pricing dimension. Buyers can easily subscribe to software priced by this new dimension on the AWS Marketplace website and only pay for what they use.")]
#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-2018 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.1.29")]
#if WINDOWS_PHONE || UNITY
[assembly: System.CLSCompliant(false)]
# else
[assembly: System.CLSCompliant(true)]
#endif
#if BCL
[assembly: System.Security.AllowPartiallyTrustedCallers]
#endif | 74.649123 | 516 | 0.79577 | [
"Apache-2.0"
] | phillip-haydon/aws-sdk-net | sdk/src/Services/AWSMarketplaceMetering/Properties/AssemblyInfo.cs | 4,255 | 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 attendance_diary
{
public partial class Admin_view_workers : Form
{
DataTable dt = new DataTable();
API_Controller api = new API_Controller();
public Admin_view_workers()
{
InitializeComponent();
dataGridView1.DataSource = dt;
Cmb_workers.Items.AddRange(api.WorkersToCmb(api.getAllWorkers()).ToArray());
}
private void ComboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
dt.Columns.Clear();
dt.Rows.Clear();
DataRow dr = dt.NewRow();
string[] words = Cmb_workers.SelectedItem.ToString().Split(' ');
string worker_name = words[0];
string worker_surname = words[1];
string worker_id = api.getWorkerId(api.getAllWorkers(), worker_name, worker_surname);
List <Time> listek = api.returnListTime(api.getAllTime(), worker_id);
for(int x = 0; x < listek.Count; x++)
{
if (dt.Rows.Count <= 0)
{
if (listek[x].worker_id == worker_id)
{
DataColumn dc1 = new DataColumn("Ime", typeof(string));
DataColumn dc2 = new DataColumn("Priimek", typeof(string));
DataColumn dc3 = new DataColumn("Ime gradbišča", typeof(string));
DataColumn dc4 = new DataColumn("Datum", typeof(string));
DataColumn dc5 = new DataColumn("Število opravljenih minut", typeof(string));
dt.Columns.Add(dc1);
dt.Columns.Add(dc2);
dt.Columns.Add(dc3);
dt.Columns.Add(dc4);
dt.Columns.Add(dc5);
dt.Rows.Add(worker_name, worker_surname, api.getConstructionName(api.getAllConstructions(), listek[x].construction_id), listek[x].Timestamp_date, listek[x].Shift);
dataGridView1.DataSource = dt;
}
}
else
{
if (listek[x].worker_id == worker_id)
{
dt.Rows.Add(worker_name, worker_surname, api.getConstructionName(api.getAllConstructions(), listek[x].construction_id), listek[x].Timestamp_date, listek[x].Shift);
dataGridView1.DataSource = dt;
}
}
}
}
private void Btn_export_Click(object sender, EventArgs e)
{
Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
Microsoft.Office.Interop.Excel._Worksheet worksheet = null;
app.Visible = true;
worksheet = workbook.Sheets["List1"];
worksheet = workbook.ActiveSheet;
worksheet.Name = "Exported from gridview";
for (int i = 1; i < dataGridView1.Columns.Count + 1; i++)
{
worksheet.Cells[1, i] = dataGridView1.Columns[i - 1].HeaderText;
}
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
for (int j = 0; j < dataGridView1.Columns.Count; j++)
{
worksheet.Cells[i + 2, j + 1] = dataGridView1.Rows[i].Cells[j].Value.ToString();
}
}
}
}
}
| 34.383929 | 187 | 0.529213 | [
"CC0-1.0"
] | SamoPritrznik/Attendance-Diary | attendance-diary/Admin_view_workers.cs | 3,856 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UpdatePosition : MonoBehaviour {
public Transform player1;
public Transform player2;
private Transform currentPosition;
private float newX;
private float newY;
// Use this for initialization
void Start () {
currentPosition = GetComponent<Transform>();
}
// Update is called once per frame
void Update () {
if (NumPlayersChecker.numOfPlayers == 2) {
newX = (player1.position.x + player2.position.x) / 2;
newY = (player1.position.y + player2.position.y) / 2;
currentPosition.position = new Vector3(newX, newY, currentPosition.position.z);
} else {
currentPosition.position = player1.position;
}
}
}
| 24.727273 | 91 | 0.64951 | [
"MIT"
] | kmikus/team2-ist440 | Project-CandleLIT/Assets/Scripts/Camera/UpdatePosition.cs | 818 | C# |
using Banking.Shared.Helpers;
using Banking.Shared.Models;
using Microsoft.Data.SqlClient;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;
namespace Banking.Infrastructure.Repositories
{
public class ClientQueryRepository : IQueryRepository
{
readonly ConnectionString _connectionString;
public ClientQueryRepository(ConnectionString connectionString)
{
_connectionString = connectionString;
}
public async Task<TransactionListModel> GetAccountTransactions(Guid accountId)
{
string query = $"SELECT * FROM transactions WHERE SourceAccountId = '{ accountId }'";
using var connection = new SqlConnection(_connectionString.Value);
await connection.OpenAsync();
var result = await ExecuteQuery<TransactionModel>(query);
return new TransactionListModel(result);
}
public async Task<TransactionListModel> GetAccountTransactionsBetween(Guid accountId, DateTime startDate, DateTime endDate)
{
string query = $"SELECT * FROM transactions WHERE SourceAccountId = '{ accountId }' " +
$"AND Date BETWEEN '{startDate}' AND '{endDate}'";
using var connection = new SqlConnection(_connectionString.Value);
await connection.OpenAsync();
var result = await ExecuteQuery<TransactionModel>(query);
return new TransactionListModel(result);
}
public async Task<TransactionListModel> GetAccountTransactionsByIds(Guid accountId, string listOfIds)
{
string query = $"SELECT * FROM transactions WHERE SourceAccountId = '{ accountId }' " +
$"AND Id in ({listOfIds})";
var result = await ExecuteQuery<TransactionModel>(query);
return new TransactionListModel(result);
}
public async Task<AccountListModel> GetClientAccounts(Guid clientId)
{
string query = $"SELECT * FROM accounts WHERE ClientId = @ClientId AND IsClosed = 0";
using var connection = new SqlConnection(_connectionString.Value);
await connection.OpenAsync();
var result = await connection.QueryAsync<AccountModel>(query, new { ClientId = clientId });
return new AccountListModel(result.ToList());
}
public async Task<IEnumerable<ClientModel>> GetClients()
{
string query = "SELECT Id, CNP, (FirstName + ' ' + LastName) as FullName, Address, Total FROM clients C " +
"JOIN(SELECT ClientId, SUM(Amount) AS Total FROM accounts WHERE IsClosed = 0 GROUP BY ClientId) A ON C.Id = A.ClientId";
return await ExecuteQuery<ClientModel>(query);
}
public async Task<IEnumerable<ClientModel>> GetClientsByName(string name)
{
var extraOption = string.IsNullOrWhiteSpace(name)
? ""
: $" WHERE CONCAT(FirstName,' ', LastName) LIKE '%{name}%'";
string query = "SELECT Id, CNP, concat(FirstName, ' ', LastName) as FullName, Address, Total FROM clients C " +
"JOIN(SELECT ClientId, SUM(Amount) AS Total FROM accounts WHERE IsClosed = 0 GROUP BY ClientId) A ON C.Id = A.ClientId " +
$"{extraOption}";
return await ExecuteQuery<ClientModel>(query);
}
public async Task<IEnumerable<ClientModel>> GetClientsSortedByAmount(string searchedName, string sorted)
{
string extraOption = string.IsNullOrWhiteSpace(searchedName)
? ""
: $"WHERE (FirstName + ' ' + LastName) LIKE '%{searchedName}%'";
string query = "SELECT Id, CNP, (FirstName + ' ' + LastName) as FullName, Address, Total FROM clients C " +
"JOIN(SELECT ClientId, SUM(Amount) AS Total FROM accounts WHERE IsClosed = 0 GROUP BY ClientId) A ON C.Id = A.ClientId " +
$" {extraOption} ORDER BY Total {sorted}";
return await ExecuteQuery<ClientModel>(query);
}
public async Task<IEnumerable<ClientModel>> GetClientsSortedByName(string searchedName, string sorted)
{
var extraOption = string.IsNullOrWhiteSpace(searchedName)
? ""
: "WHERE (FirstName + ' ' + LastName) LIKE '%{searchedName}%'";
string query = "SELECT Id, CNP, (FirstName + ' ' + LastName) as FullName, Address, Total FROM clients C " +
"JOIN(SELECT ClientId, SUM(Amount) AS Total FROM accounts WHERE IsClosed = 0 GROUP BY ClientId) A ON C.Id = A.ClientId " +
$" {extraOption} ORDER BY FullName { sorted }";
return await ExecuteQuery<ClientModel>(query);
}
async Task<IEnumerable<T>> ExecuteQuery<T>(string query)
{
using var connection = new SqlConnection(_connectionString.Value);
await connection.OpenAsync();
var result = await connection.QueryAsync<T>(query);
return result;
}
}
}
| 40.015504 | 142 | 0.626501 | [
"MIT"
] | t-rolfin/Banking_IntShip | src/Banking.Infrastructure/Repositories/ClientQueryRepository.cs | 5,164 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using Wiffzack.Devices.CardTerminals.Protocols.ZVT.ApplicationLayer;
using Wiffzack.Devices.CardTerminals.Common;
namespace Wiffzack.Devices.CardTerminals.Protocols.ZVT.TransportLayer
{
/// <summary>
/// Encapsulates an Apdu for transmission over Network
/// </summary>
public class NetworkTpdu : TpduBase
{
/// <summary>
/// If available, extracts one whole apdu and removes the data from buffer
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public static NetworkTpdu CreateFromBuffer(ByteBuffer data, bool removeFromBuffer)
{
if (data.Count > 2)
{
List<byte> myData = new List<byte>();
myData.Add(data[0]);
myData.Add(data[1]);
//Length calculation
//There are 2 length modes, if the single length byte is 0xff
//then the 2 following bytes are interpreted as length
int length;
byte bLength = data[2];
myData.Add(data[2]);
int dataStartIndex = 2;
if (bLength == 0xFF)
{
dataStartIndex += 2;
if (data.Count >= 5)
{
myData.Add(data[3]);
myData.Add(data[4]);
length = BitConverter.ToUInt16(new byte[] { data[3], data[4] }, 0);
}
else
return null;
}
else
{
dataStartIndex++;
length = bLength;
}
if (data.Count >= dataStartIndex + length)
{
for(int i = dataStartIndex; i<dataStartIndex+length; i++)
myData.Add(data[i]);
if(removeFromBuffer)
data.Remove(myData.Count);
return new NetworkTpdu(myData.ToArray());
}
}
return null;
}
public NetworkTpdu(IZvtApdu apdu)
:this(apdu.GetRawApduData())
{
}
public NetworkTpdu(byte[] data)
{
this.ApduData = data;
}
private NetworkTpdu()
{
}
}
}
| 30.333333 | 92 | 0.451334 | [
"MIT"
] | Europa-Park/zvtlib | CardTerminalLibrary/Protocols/ZVT/TransportLayer/NetworkTpdu.cs | 2,550 | C# |
using System.Collections.Generic;
using Essensoft.AspNetCore.Payment.Alipay.Response;
namespace Essensoft.AspNetCore.Payment.Alipay.Request
{
/// <summary>
/// ant.merchant.expand.indirect.online.modify
/// </summary>
public class AntMerchantExpandIndirectOnlineModifyRequest : IAlipayRequest<AntMerchantExpandIndirectOnlineModifyResponse>
{
/// <summary>
/// 线上间连商户修改
/// </summary>
public string BizContent { get; set; }
#region IAlipayRequest Members
private bool needEncrypt = false;
private string apiVersion = "1.0";
private string terminalType;
private string terminalInfo;
private string prodCode;
private string notifyUrl;
private string returnUrl;
private AlipayObject bizModel;
public void SetNeedEncrypt(bool needEncrypt)
{
this.needEncrypt = needEncrypt;
}
public bool GetNeedEncrypt()
{
return needEncrypt;
}
public void SetNotifyUrl(string notifyUrl)
{
this.notifyUrl = notifyUrl;
}
public string GetNotifyUrl()
{
return notifyUrl;
}
public void SetReturnUrl(string returnUrl)
{
this.returnUrl = returnUrl;
}
public string GetReturnUrl()
{
return returnUrl;
}
public void SetTerminalType(string terminalType)
{
this.terminalType = terminalType;
}
public string GetTerminalType()
{
return terminalType;
}
public void SetTerminalInfo(string terminalInfo)
{
this.terminalInfo = terminalInfo;
}
public string GetTerminalInfo()
{
return terminalInfo;
}
public void SetProdCode(string prodCode)
{
this.prodCode = prodCode;
}
public string GetProdCode()
{
return prodCode;
}
public string GetApiName()
{
return "ant.merchant.expand.indirect.online.modify";
}
public void SetApiVersion(string apiVersion)
{
this.apiVersion = apiVersion;
}
public string GetApiVersion()
{
return apiVersion;
}
public IDictionary<string, string> GetParameters()
{
var parameters = new AlipayDictionary
{
{ "biz_content", BizContent }
};
return parameters;
}
public AlipayObject GetBizModel()
{
return bizModel;
}
public void SetBizModel(AlipayObject bizModel)
{
this.bizModel = bizModel;
}
#endregion
}
}
| 23 | 125 | 0.552945 | [
"MIT"
] | lzw316/payment | src/Essensoft.AspNetCore.Payment.Alipay/Request/AntMerchantExpandIndirectOnlineModifyRequest.cs | 2,870 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace Kartverket.ReportGenerator.Models
{
public class MetadataEntry
{
[Key]
public string Uuid { get; set; }
public int SortOrder { get; set; }
}
} | 21.333333 | 44 | 0.69375 | [
"MIT"
] | kartverket/Geonorge.Rapportgenerator | Kartverket.ReportGenerator/Models/MetadataEntry.cs | 322 | C# |
/*
* Copyright (C) 2015 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
namespace com.opengamma.strata.market.curve
{
//JAVA TO C# CONVERTER TODO TASK: This Java 'import static' statement cannot be converted to C#:
// import static com.opengamma.strata.collect.TestHelper.assertSerialization;
//JAVA TO C# CONVERTER TODO TASK: This Java 'import static' statement cannot be converted to C#:
// import static com.opengamma.strata.collect.TestHelper.coverBeanEquals;
//JAVA TO C# CONVERTER TODO TASK: This Java 'import static' statement cannot be converted to C#:
// import static com.opengamma.strata.collect.TestHelper.coverImmutableBean;
//JAVA TO C# CONVERTER TODO TASK: This Java 'import static' statement cannot be converted to C#:
// import static org.assertj.core.api.Assertions.assertThat;
using Test = org.testng.annotations.Test;
using ParameterMetadata = com.opengamma.strata.market.param.ParameterMetadata;
/// <summary>
/// Test <seealso cref="ConstantCurve"/>.
/// </summary>
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public class ConstantCurveTest
public class ConstantCurveTest
{
private const string NAME = "TestCurve";
private static readonly CurveName CURVE_NAME = CurveName.of(NAME);
private static readonly CurveMetadata METADATA = DefaultCurveMetadata.of(CURVE_NAME);
private static readonly CurveMetadata METADATA2 = DefaultCurveMetadata.of("Test2");
private const double VALUE = 6d;
//-------------------------------------------------------------------------
public virtual void test_of_String()
{
ConstantCurve test = ConstantCurve.of(NAME, VALUE);
assertThat(test.Name).isEqualTo(CURVE_NAME);
assertThat(test.YValue).isEqualTo(VALUE);
assertThat(test.ParameterCount).isEqualTo(1);
assertThat(test.getParameter(0)).isEqualTo(VALUE);
assertThat(test.getParameterMetadata(0)).isEqualTo(ParameterMetadata.empty());
assertThat(test.withParameter(0, 2d)).isEqualTo(ConstantCurve.of(NAME, 2d));
assertThat(test.withPerturbation((i, v, m) => v + 1d)).isEqualTo(ConstantCurve.of(NAME, VALUE + 1d));
assertThat(test.Metadata).isEqualTo(METADATA);
assertThat(test.withMetadata(METADATA2)).isEqualTo(ConstantCurve.of(METADATA2, VALUE));
}
public virtual void test_of_CurveName()
{
ConstantCurve test = ConstantCurve.of(CURVE_NAME, VALUE);
assertThat(test.Name).isEqualTo(CURVE_NAME);
assertThat(test.YValue).isEqualTo(VALUE);
assertThat(test.ParameterCount).isEqualTo(1);
assertThat(test.getParameter(0)).isEqualTo(VALUE);
assertThat(test.getParameterMetadata(0)).isEqualTo(ParameterMetadata.empty());
assertThat(test.withParameter(0, 2d)).isEqualTo(ConstantCurve.of(NAME, 2d));
assertThat(test.Metadata).isEqualTo(METADATA);
assertThat(test.withMetadata(METADATA2)).isEqualTo(ConstantCurve.of(METADATA2, VALUE));
}
public virtual void test_of_CurveMetadata()
{
ConstantCurve test = ConstantCurve.of(METADATA, VALUE);
assertThat(test.Name).isEqualTo(CURVE_NAME);
assertThat(test.YValue).isEqualTo(VALUE);
assertThat(test.ParameterCount).isEqualTo(1);
assertThat(test.getParameter(0)).isEqualTo(VALUE);
assertThat(test.getParameterMetadata(0)).isEqualTo(ParameterMetadata.empty());
assertThat(test.withParameter(0, 2d)).isEqualTo(ConstantCurve.of(NAME, 2d));
assertThat(test.Metadata).isEqualTo(METADATA);
assertThat(test.withMetadata(METADATA2)).isEqualTo(ConstantCurve.of(METADATA2, VALUE));
}
//-------------------------------------------------------------------------
public virtual void test_lookup()
{
ConstantCurve test = ConstantCurve.of(CURVE_NAME, VALUE);
assertThat(test.yValue(0d)).isEqualTo(VALUE);
assertThat(test.yValue(-10d)).isEqualTo(VALUE);
assertThat(test.yValue(100d)).isEqualTo(VALUE);
assertThat(test.yValueParameterSensitivity(0d).Sensitivity.toArray()).containsExactly(1d);
assertThat(test.yValueParameterSensitivity(-10d).Sensitivity.toArray()).containsExactly(1d);
assertThat(test.yValueParameterSensitivity(100d).Sensitivity.toArray()).containsExactly(1d);
assertThat(test.firstDerivative(0d)).isEqualTo(0d);
assertThat(test.firstDerivative(-10d)).isEqualTo(0d);
assertThat(test.firstDerivative(100d)).isEqualTo(0d);
}
//-------------------------------------------------------------------------
public virtual void coverage()
{
ConstantCurve test = ConstantCurve.of(CURVE_NAME, VALUE);
coverImmutableBean(test);
ConstantCurve test2 = ConstantCurve.of("Coverage", 9d);
coverBeanEquals(test, test2);
}
public virtual void test_serialization()
{
ConstantCurve test = ConstantCurve.of(CURVE_NAME, VALUE);
assertSerialization(test);
}
}
} | 43.745455 | 104 | 0.729011 | [
"Apache-2.0"
] | ckarcz/Strata.ConvertedToCSharp | modules/market/src/test/java/com/opengamma/strata/market/curve/ConstantCurveTest.cs | 4,814 | C# |
public class Solution {
public int NumIslands(char[][] grid) {
if (grid== null || grid.Length ==0)
return 0;
var rn = grid.Length;
var cn = grid[0].Length;
var res = 0;
for(var r = 0; r < rn; r++){
for(var c = 0; c < cn; c++){
if (grid[r][c] == '1'){
grid[r][c] = '0';
res++;
var q = new Queue<ValueTuple<int,int>>();
q.Enqueue((r,c));
while(q.Count > 0){
(var rr, var cc) = q.Dequeue();
if (rr+1 < rn && grid[rr+1][cc] == '1'){
grid[rr+1][cc] = '0';
q.Enqueue((rr+1, cc));
}
if (rr-1 >= 0 && grid[rr-1][cc] == '1'){
grid[rr-1][cc] = '0';
q.Enqueue((rr-1, cc));
}
if (cc+1 < cn && grid[rr][cc+1] == '1'){
grid[rr][cc+1] = '0';
q.Enqueue((rr, cc+1));
}
if (cc-1 >= 0 && grid[rr][cc-1] == '1'){
grid[rr][cc-1] = '0';
q.Enqueue((rr, cc-1));
}
}
}
}
}
return res;
}
} | 33.3 | 64 | 0.234234 | [
"MIT"
] | Igorium/Leetcode | medium/200. Number of Islands.txt.cs | 1,665 | C# |
// Copyright (c) Josef Pihrt and Contributors. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Roslynator.CSharp.Analysis.If
{
internal sealed class IfElseToAssignmentWithExpressionAnalysis : IfAnalysis
{
public IfElseToAssignmentWithExpressionAnalysis(
IfStatementSyntax ifStatement,
ExpressionStatementSyntax expressionStatement,
SemanticModel semanticModel) : base(ifStatement, semanticModel)
{
ExpressionStatement = expressionStatement;
}
public override IfAnalysisKind Kind
{
get { return IfAnalysisKind.IfElseToAssignmentWithExpression; }
}
public override string Title
{
get { return "Convert 'if' to assignment"; }
}
public ExpressionStatementSyntax ExpressionStatement { get; }
}
} | 33.5 | 156 | 0.692537 | [
"Apache-2.0"
] | onexey/Roslynator | src/Common/CSharp/Analysis/If/IfElseToAssignmentWithExpressionAnalysis.cs | 1,007 | C# |
namespace Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api202101
{
using Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.PowerShell;
/// <summary>
/// A PowerShell PSTypeConverter to support converting to an instance of <see cref="Operation" />
/// </summary>
public partial class OperationTypeConverter : global::System.Management.Automation.PSTypeConverter
{
/// <summary>
/// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" />
/// parameter.
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <returns>
/// <c>true</c> if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" />
/// parameter, otherwise <c>false</c>.
/// </returns>
public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue);
/// <summary>
/// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" />
/// parameter.
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object" /> instance to check if it can be converted to the <see cref="Operation"
/// /> type.</param>
/// <returns>
/// <c>true</c> if the instance could be converted to a <see cref="Operation" /> type, otherwise <c>false</c>
/// </returns>
public static bool CanConvertFrom(dynamic sourceValue)
{
if (null == sourceValue)
{
return true;
}
global::System.Type type = sourceValue.GetType();
if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type))
{
// we say yest to PSObjects
return true;
}
if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type))
{
// we say yest to Hashtables/dictionaries
return true;
}
try
{
if (null != sourceValue.ToJsonString())
{
return true;
}
}
catch
{
// Not one of our objects
}
try
{
string text = sourceValue.ToString()?.Trim();
return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Json.JsonType.Object;
}
catch
{
// Doesn't look like it can be treated as JSON
}
return false;
}
/// <summary>
/// Determines if the <see cref="sourceValue" /> parameter can be converted to the <see cref="destinationType" /> parameter
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <returns>
/// <c>true</c> if the converter can convert the <see cref="sourceValue" /> parameter to the <see cref="destinationType" />
/// parameter, otherwise <c>false</c>
/// </returns>
public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false;
/// <summary>
/// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider"
/// /> and <see cref="ignoreCase" />
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <param name="formatProvider">not used by this TypeConverter.</param>
/// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param>
/// <returns>
/// an instance of <see cref="Operation" />, or <c>null</c> if there is no suitable conversion.
/// </returns>
public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue);
/// <summary>
/// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider"
/// /> and <see cref="ignoreCase" />
/// </summary>
/// <param name="sourceValue">the value to convert into an instance of <see cref="Operation" />.</param>
/// <returns>
/// an instance of <see cref="Operation" />, or <c>null</c> if there is no suitable conversion.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api202101.IOperation ConvertFrom(dynamic sourceValue)
{
if (null == sourceValue)
{
return null;
}
global::System.Type type = sourceValue.GetType();
if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api202101.IOperation).IsAssignableFrom(type))
{
return sourceValue;
}
try
{
return Operation.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());;
}
catch
{
// Unable to use JSON pattern
}
if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type))
{
return Operation.DeserializeFromPSObject(sourceValue);
}
if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type))
{
return Operation.DeserializeFromDictionary(sourceValue);
}
return null;
}
/// <summary>NotImplemented -- this will return <c>null</c></summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <param name="formatProvider">not used by this TypeConverter.</param>
/// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param>
/// <returns>will always return <c>null</c>.</returns>
public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null;
}
} | 50.605634 | 241 | 0.575703 | [
"MIT"
] | Agazoth/azure-powershell | src/Kusto/generated/api/Models/Api202101/Operation.TypeConverter.cs | 7,045 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EDI_Parser.Attributes
{
public class SegmentIdAttribute:Attribute
{
public string Id{get;set;}
public SegmentIdAttribute(string id)
{
this.Id = id;
}
}
}
| 18.888889 | 45 | 0.652941 | [
"MIT"
] | shaggydp/EDIParser | EDI Parser/Attributes/SegmentIdAttribute.cs | 342 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Axiverse.Mathematics.Geometry
{
/// <summary>
/// A two dimensional ray.
/// </summary>
public struct Ray2
{
/// <summary>
/// The origin of the ray.
/// </summary>
public Vector2 Origin;
/// <summary>
/// The direction vector of the ray.
/// </summary>
public Vector2 Direction;
/// <summary>
/// Constructs a two-dimensional ray.
/// </summary>
/// <param name="origin"></param>
/// <param name="direction"></param>
public Ray2(Vector2 origin, Vector2 direction)
{
Origin = origin;
Direction = direction;
}
}
}
| 22.75 | 54 | 0.543346 | [
"MIT"
] | AxiverseCode/Axiverse | Source/Libraries/Axiverse.Mathematics/Geometry/Ray2.cs | 821 | C# |
// <copyright file="BaseOtlpGrpcExportClient.cs" company="OpenTelemetry Authors">
// Copyright The OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using System;
using System.Threading;
using System.Threading.Tasks;
using Grpc.Core;
using OpenTelemetry.Internal;
#if NETSTANDARD2_1 || NET5_0_OR_GREATER
using Grpc.Net.Client;
#endif
namespace OpenTelemetry.Exporter.OpenTelemetryProtocol.Implementation.ExportClient
{
/// <summary>Base class for sending OTLP export request over gRPC.</summary>
/// <typeparam name="TRequest">Type of export request.</typeparam>
internal abstract class BaseOtlpGrpcExportClient<TRequest> : IExportClient<TRequest>
{
protected BaseOtlpGrpcExportClient(OtlpExporterOptions options)
{
Guard.ThrowIfNull(options);
Guard.ThrowIfInvalidTimeout(options.TimeoutMilliseconds);
ExporterClientValidation.EnsureUnencryptedSupportIsEnabled(options);
this.Endpoint = new UriBuilder(options.Endpoint).Uri;
this.Headers = options.GetMetadataFromHeaders();
this.TimeoutMilliseconds = options.TimeoutMilliseconds;
}
#if NETSTANDARD2_1 || NET5_0_OR_GREATER
internal GrpcChannel Channel { get; set; }
#else
internal Channel Channel { get; set; }
#endif
internal Uri Endpoint { get; }
internal Metadata Headers { get; }
internal int TimeoutMilliseconds { get; }
/// <inheritdoc/>
public abstract bool SendExportRequest(TRequest request, CancellationToken cancellationToken = default);
/// <inheritdoc/>
public virtual bool Shutdown(int timeoutMilliseconds)
{
if (this.Channel == null)
{
return true;
}
if (timeoutMilliseconds == -1)
{
this.Channel.ShutdownAsync().Wait();
return true;
}
else
{
return Task.WaitAny(new Task[] { this.Channel.ShutdownAsync(), Task.Delay(timeoutMilliseconds) }) == 0;
}
}
}
}
| 33.56962 | 119 | 0.667798 | [
"Apache-2.0"
] | TylerHelmuth/opentelemetry-dotnet | src/OpenTelemetry.Exporter.OpenTelemetryProtocol/Implementation/ExportClient/BaseOtlpGrpcExportClient.cs | 2,652 | C# |
using ColossalFramework;
namespace WhatThe.Mods.CitiesSkylines.ServiceDispatcher
{
/// <summary>
/// Handles frame based buckets for object updates.
/// </summary>
internal class Bucketeer
{
/// <summary>
/// The factor.
/// </summary>
private uint factor;
/// <summary>
/// The mask.
/// </summary>
private uint mask;
/// <summary>
/// Initializes a new instance of the <see cref="Bucketeer"/> class.
/// </summary>
/// <param name="mask">The mask.</param>
/// <param name="factor">The factor.</param>
public Bucketeer(uint mask, uint factor)
{
this.mask = mask;
this.factor = factor;
}
/// <summary>
/// Gets the bucket boundaries.
/// </summary>
/// <param name="bucket">The bucket.</param>
/// <returns>The bucket boundaries.</returns>
public Boundaries GetBoundaries(uint bucket)
{
bucket = bucket & this.mask;
return new Boundaries(bucket * this.factor, ((bucket + 1) * this.factor) - 1);
}
/// <summary>
/// Gets the end bucket.
/// </summary>
/// <returns>The end bucket.</returns>
public uint GetEnd()
{
return Singleton<SimulationManager>.instance.m_currentFrameIndex & this.mask;
}
/// <summary>
/// Gets the next bucket.
/// </summary>
/// <param name="bucket">The current/last bucket.</param>
/// <returns>The next bucket.</returns>
public uint GetNext(uint bucket)
{
return bucket & this.mask;
}
/// <summary>
/// Bucket boundaries.
/// </summary>
public struct Boundaries
{
/// <summary>
/// The first identifier.
/// </summary>
public readonly ushort FirstId;
/// <summary>
/// The last identifier.
/// </summary>
public readonly ushort LastId;
/// <summary>
/// Initializes a new instance of the <see cref="Boundaries" /> struct.
/// </summary>
/// <param name="firstId">The first object id.</param>
/// <param name="lastId">The last object id.</param>
public Boundaries(uint firstId, uint lastId)
{
this.FirstId = (ushort)firstId;
this.LastId = (ushort)lastId;
}
}
}
} | 28.955056 | 90 | 0.49903 | [
"MIT",
"Unlicense"
] | DinkyToyz/wtmcsServiceDispatcher | wtmcsServiceDispatcher/Util/Bucketeer.cs | 2,579 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ThresholdNoAdaptation : ThresholdAdaptiveProcedure
{
readonly float threshold;
/// <param name="threshold">constant value for the threshold</param>
public ThresholdNoAdaptation(float threshold) {
this.threshold = threshold;
}
public override float GetThreshold() {
return threshold;
}
public override void UpdateThreshold(float value) {}
}
| 21.304348 | 72 | 0.714286 | [
"Apache-2.0"
] | exporl/lars-common | Core/Procedures/ThresholdNoAdaptation.cs | 492 | C# |
using System;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
using Stubble.Core.Settings;
namespace Stubble.Extensions.JsonNet
{
public static class JsonNet
{
public static RendererSettingsBuilder AddJsonNet(this RendererSettingsBuilder builder)
{
foreach(var getter in ValueGetters)
{
builder.AddValueGetter(getter.Key, getter.Value);
}
builder.AddSectionBlacklistType(typeof(JObject));
return builder;
}
internal static readonly Dictionary<Type, RendererSettingsDefaults.ValueGetterDelegate> ValueGetters = new Dictionary<Type, RendererSettingsDefaults.ValueGetterDelegate>
{
{
typeof (JObject), (value, key, ignoreCase) =>
{
var token = (JObject)value;
var comparison =
ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
var childToken = token.GetValue(key, comparison);
if (childToken == null) return null;
switch (childToken.Type)
{
case JTokenType.Array:
case JTokenType.Object:
return childToken;
}
var jValue = childToken as JValue;
return jValue?.Value;
}
},
{
typeof (JProperty), (value, key, ignoreCase) =>
{
var childToken = ((JProperty)value).Value;
var jValue = childToken as JValue;
return jValue?.Value ?? childToken;
}
},
};
}
}
| 32.824561 | 178 | 0.499198 | [
"MIT"
] | StubbleOrg/Stubble.Extensions.JsonNet | src/Stubble.Extensions.JsonNet/JsonNet.cs | 1,873 | C# |
/*
Copyright (C) 2019 Alex Watt (alexwatt@hotmail.com)
This file is part of Highlander Project https://github.com/alexanderwatt/Hghlander.Net
Highlander is free software: you can redistribute it and/or modify it
under the terms of the Highlander license. You should have received a
copy of the license along with this program; if not, license is
available at <https://github.com/alexanderwatt/Hghlander.Net/blob/develop/LICENSE>.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the license for more details.
*/
#region Using directives
using System;
#endregion
namespace FpML.V5r10.Reporting.ModelFramework.PricingStructures
{
/// <summary>
/// The Pricing Structure Interface
/// </summary>
public interface ISwaptionATMVolatilitySurface : IVolatilitySurface
{
/// <summary>
/// Gets the volatility using a DateTime expiry and a tenor value.
/// </summary>
/// <param name="baseDate">The base date.</param>
/// <param name="expirationAsDate">The expiration date.</param>
/// <param name="tenor">The underlying tenor.</param>
/// <returns>The interpolated value.</returns>
Double GetValueByExpiryDateAndTenor(DateTime baseDate, DateTime expirationAsDate, String tenor);
/// <summary>
/// Gets the volatility using a DateTime expiry and a tenor value.
/// </summary>
/// <param name="expirationTerm">The expiration term.</param>
/// <param name="tenor">The underlying tenor.</param>
/// <returns>The interpolated value.</returns>
Double GetValueByExpiryTermAndTenor(String expirationTerm, String tenor);
}
} | 38.425532 | 104 | 0.702658 | [
"BSD-3-Clause"
] | mmrath/Highlander.Net | Metadata/FpML.V5r10/FpML.V5r10.Reporting.ModelFramework/PricingStructures/ISwaptionATMVolatilitySurface.cs | 1,806 | C# |
//Copyright 2004 - $Date: 2008-11-15 23:58:07 +0100 (za, 15 nov 2008) $ by PeopleWare n.v..
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//http://www.apache.org/licenses/LICENSE-2.0
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
using System;
using System.Diagnostics.Contracts;
using System.Runtime.Serialization;
namespace PPWCode.Vernacular.Exceptions.I
{
/// <summary>
/// This error is thrown when an external condition occurs, which we know can happen
/// (however unlikely), which we do not want to deal with in our application.
/// <inheritdoc cref="Error" />
/// </summary>
/// <remarks>
/// <para>Most often,
/// these are exceptional conditions of a technical nature. These conditions are
/// considered <em>preconditions</em> on the system level. Examples are a disk that is full,
/// a network connection that cannot be established, a power failure, etcetera.
/// The indented audience of these errors is neither the end user, nor the developer,
/// but the <strong>administrator</strong>, who is responsible for system configuration,
/// integration and infrastructure.</para>
/// <para>The <see cref="Exception.Message"/> should express the error as closely as
/// possible.
/// It is the only channel to which to communicate to the administrator what went wrong.
/// If you cannot pinpoint the exact nature of the error, the message should say so
/// explicitly. If you become aware of the external condition you do not want to deal
/// with through an <see cref="Exception"/>, it should be carried
/// by an instance of this class as its <see cref="Exception.InnerException"/>.</para>
/// <para>These errors should not be mentioned in the exception part of a method contract.
/// They could be mentioned in the preconditions of a method contract, but in general
/// this is not appropriate. <c>ExternalError</c>s are a mechanism to signal
/// <em>system precondition</em> violations to administrators, it is not a part of the
/// contract between developers, but rather a contract between developers in general and
/// the system administrator. These errors could be documented in a document that
/// communicates between developers and administrators (e.g., installation documentations),
/// and this should be done in specific cases. But most often, these
/// system preconditions are considered implicit (e.g., when we need a database, it is
/// implied that the database connection works).</para>
/// <para>It probably does not make sense to create subtypes of this error for specific
/// situations. There is no need for internationalization for external errors. If there
/// is extra information that we can communicate to the administrator, we can add it to
/// the message.</para>
/// </remarks>
[Serializable]
public class ExternalError :
Error
{
public const string ExceptionWithExternalCauseMessage = "An exception occurred, which appears to be of an external nature.";
public const string UnspecifiedExternalErrorMessage = "Could not continue due to an unspecified external error.";
public ExternalError()
: base(UnspecifiedExternalErrorMessage)
{
Contract.Ensures((Message == UnspecifiedExternalErrorMessage) && (InnerException == null));
}
public ExternalError(string message)
: base(message ?? UnspecifiedExternalErrorMessage)
{
Contract.Ensures((message != null ? Message == message : Message == UnspecifiedExternalErrorMessage)
&& (InnerException == null));
}
public ExternalError(string message, System.Exception innerException)
: base(message ?? (innerException == null ? UnspecifiedExternalErrorMessage : ExceptionWithExternalCauseMessage), innerException)
{
Contract.Ensures((message != null
? Message == message
: Message == (innerException == null ? UnspecifiedExternalErrorMessage : ExceptionWithExternalCauseMessage))
&& (InnerException == innerException));
}
public ExternalError(System.Exception innerException)
: base((innerException == null ? UnspecifiedExternalErrorMessage : ExceptionWithExternalCauseMessage), innerException)
{
Contract.Ensures((Message == (innerException == null ? UnspecifiedExternalErrorMessage : ExceptionWithExternalCauseMessage)) && (InnerException == innerException));
}
protected ExternalError(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
}
}
| 54.510417 | 177 | 0.683356 | [
"Apache-2.0"
] | jandockx/ppwcode | dotnet/Vernacular/Exceptions/I/1.n/1.0/solution/I/ExternalError.cs | 5,235 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.IO;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Threading.Tasks;
namespace System.Web.Http.ModelBinding
{
// Supports JQuery schema on FormURL.
public class JQueryMvcFormUrlEncodedFormatter : FormUrlEncodedMediaTypeFormatter
{
private readonly HttpConfiguration _configuration = null;
public JQueryMvcFormUrlEncodedFormatter()
{
}
public JQueryMvcFormUrlEncodedFormatter(HttpConfiguration config)
{
_configuration = config;
}
public override bool CanReadType(Type type)
{
if (type == null)
{
throw new ArgumentNullException("type");
}
return true;
}
public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
{
if (type == null)
{
throw new ArgumentNullException("type");
}
if (readStream == null)
{
throw new ArgumentNullException("readStream");
}
// For simple types, defer to base class
if (base.CanReadType(type))
{
return base.ReadFromStreamAsync(type, readStream, content, formatterLogger);
}
return ReadFromStreamAsyncCore(type, readStream, content, formatterLogger);
}
private async Task<object> ReadFromStreamAsyncCore(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
{
object obj = await base.ReadFromStreamAsync(typeof(FormDataCollection), readStream, content, formatterLogger);
FormDataCollection fd = (FormDataCollection)obj;
try
{
return fd.ReadAs(type, String.Empty, RequiredMemberSelector, formatterLogger, _configuration);
}
catch (Exception e)
{
if (formatterLogger == null)
{
throw;
}
formatterLogger.LogError(String.Empty, e);
return GetDefaultValueForType(type);
}
}
}
}
| 31.623377 | 143 | 0.594251 | [
"Apache-2.0"
] | 1508553303/AspNetWebStack | src/System.Web.Http/ModelBinding/JQueryMVCFormUrlEncodedFormatter.cs | 2,437 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
namespace SwmSuite.Data.DataObjects {
[Serializable]
[XmlType( Namespace = "SimpleWorkfloorManagementSuiteNameSpace" )]
public class TaskData : DataObjectBase {
#region -_ Private Members _-
#endregion
#region -_ Public Properties _-
/// <summary>
/// Gets or sets the internal id of the employee this task applies to.
/// </summary>
public int EmployeeSysId { get; set; }
/// <summary>
/// Gets or sets the internal id of the taskdescription describing this task.
/// </summary>
public int TaskDescriptionSysId { get; set; }
#endregion
#region -_ Construction _-
/// <summary>
/// Default constructor.
/// </summary>
public TaskData() {
}
/// <summary>
/// Custom constructor.
/// </summary>
/// <param name="employeeSysId">The internal id of the employee this task applies to.</param>
/// <param name="taskDescriptionSysId">The internal id of the taskdescription describing this task.</param>
public TaskData( int employeeSysId , int taskDescriptionSysId ) {
this.EmployeeSysId = employeeSysId;
this.TaskDescriptionSysId = taskDescriptionSysId;
}
#endregion
#region -_ Public Methods _-
/// <summary>
/// Convert this task to its string representation.
/// </summary>
/// <returns>An empty string.</returns>
public override string ToString() {
return String.Empty;
}
#endregion
}
}
| 22.149254 | 109 | 0.692049 | [
"Unlicense"
] | Djohnnie/SwmSuite-Original | SwmSuite.Framework.DataObjects/TaskData.cs | 1,486 | C# |
using Newtonsoft.Json;
namespace Yandex.Checkout.V3
{
/// <summary>
/// Payment amount
/// </summary>
public class Amount
{
/// <summary>
/// Value
/// </summary>
[JsonProperty()]
public decimal Value { get; set; }
/// <summary>
/// Three letter currency code (ex: RUB)
/// </summary>
public string Currency { get; set; } = "RUB";
}
}
| 19.727273 | 53 | 0.493088 | [
"MIT"
] | Sierra93/Yandex.Checkout.V3 | Yandex.Checkout.V3/Amount.cs | 436 | C# |
using System;
using System.Net;
using System.Windows;
namespace SC2MiM.Common.Entities
{
public class Match
{
public String Carte { get; set; }
public String Type { get; set; }
public String Resultat { get; set; }
public bool IsWin { get; set; }
public DateTime Date { get; set; }
public int Point { get; set; }
public String DateString
{
get
{
return this.Date.ToString();
}
}
public String PointString
{
get
{
if (IsWin)
return "+" + Point.ToString();
else
return "-" + Point.ToString();
}
}
//public BitmapImage ResultImage
//{
// get
// {
// if (IsWin)
// return new BitmapImage(UriHelper.Create("Images/MatchWin.png"));
// else
// return new BitmapImage(UriHelper.Create("Images/MatchLost.png"));
// }
//}
//public SolidColorBrush PointColor
//{
// get
// {
// if (IsWin)
// return new SolidColorBrush(Colors.Green);
// else
// return new SolidColorBrush(Colors.Red);
// }
//}
}
}
| 23.666667 | 87 | 0.426761 | [
"MIT"
] | Mimetis/SC2Sniffer | SC2MiM.Common/Entities/Match.cs | 1,422 | C# |
using System;
using System.Collections.Generic;
class SpeedRacing
{
static void Main()
{
var cars = new Dictionary<string, Car>();
var carsNumber = int.Parse(Console.ReadLine());
for (int counter = 0; counter < carsNumber; counter++)
{
var carData = Console.ReadLine().Split();
var model = carData[0];
var amountOfFuel = decimal.Parse(carData[1]);
var consumPerKm = decimal.Parse(carData[2]);
if (!cars.ContainsKey(model))
{
cars[model] = new Car(model, amountOfFuel, consumPerKm);
}
}
while (true)
{
var input = Console.ReadLine();
if ("End" == input)
{
break;
}
var commandData = input.Split();
var command = commandData[0];
var model = commandData[1];
var distance = int.Parse(commandData[2]);
var car = cars[model];
car.CalculateTraveling(distance);
}
foreach (KeyValuePair<string, Car> kvp in cars)
{
Console.WriteLine(kvp.Value);
}
}
} | 27.767442 | 72 | 0.504188 | [
"Apache-2.0"
] | genadi60/C--OOP-Basic | Defining Classes - Exercise/07.SpeedRacing/SpeedRacing.cs | 1,196 | C# |
/*
* Copyright 2012 The Netty Project
*
* The Netty Project 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.
*
* Copyright (c) 2020 The Dotnetty-Span-Fork Project (cuteant@outlook.com) All rights reserved.
*
* https://github.com/cuteant/dotnetty-span-fork
*
* Licensed under the MIT license. See LICENSE file in the project root for full license information.
*/
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
// Largely based from https://github.com/dotnet/corefx/blob/release/3.0/src/System.Memory/src/System/Buffers/SequenceReader.Search.cs
namespace DotNetty.Buffers
{
using System;
using System.Buffers;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using DotNetty.Common.Internal;
partial struct ByteBufferReader
{
/// <summary>Try to read everything up to the given <paramref name="delimiter"/>.</summary>
/// <param name="span">The read data, if any.</param>
/// <param name="delimiter">The delimiter to look for.</param>
/// <param name="advancePastDelimiter">True to move past the <paramref name="delimiter"/> if found.</param>
/// <returns>True if the <paramref name="delimiter"/> was found.</returns>
public bool TryReadTo(out ReadOnlySpan<byte> span, byte delimiter, bool advancePastDelimiter = true)
{
ReadOnlySpan<byte> remaining = UnreadSpan;
#if NET
int index = remaining.IndexOf(delimiter);
#else
int index = SpanHelpers.IndexOf(ref MemoryMarshal.GetReference(remaining), delimiter, remaining.Length);
#endif
uint uIndex = (uint)index;
if (SharedConstants.TooBigOrNegative >= uIndex) // index != -1
{
span = 0u >= uIndex ? default : remaining.Slice(0, index);
AdvanceCurrentSpan(index + (advancePastDelimiter ? 1 : 0));
return true;
}
return TryReadToSlow(out span, delimiter, advancePastDelimiter);
}
[MethodImpl(MethodImplOptions.NoInlining)]
private bool TryReadToSlow(out ReadOnlySpan<byte> span, byte delimiter, bool advancePastDelimiter)
{
if (!TryReadToInternal(out ReadOnlySequence<byte> sequence, delimiter, advancePastDelimiter, _currentSpan.Length - _currentSpanIndex))
{
span = default;
return false;
}
span = sequence.IsSingleSegment ? sequence.First.Span : sequence.ToArray();
return true;
}
/// <summary>Try to read everything up to the given <paramref name="delimiter"/>, ignoring delimiters that are
/// preceded by <paramref name="delimiterEscape"/>.</summary>
/// <param name="span">The read data, if any.</param>
/// <param name="delimiter">The delimiter to look for.</param>
/// <param name="delimiterEscape">If found prior to <paramref name="delimiter"/> it will skip that occurrence.</param>
/// <param name="advancePastDelimiter">True to move past the <paramref name="delimiter"/> if found.</param>
/// <returns>True if the <paramref name="delimiter"/> was found.</returns>
public bool TryReadTo(out ReadOnlySpan<byte> span, byte delimiter, byte delimiterEscape, bool advancePastDelimiter = true)
{
ReadOnlySpan<byte> remaining = UnreadSpan;
#if NET
int index = remaining.IndexOf(delimiter);
#else
int index = SpanHelpers.IndexOf(ref MemoryMarshal.GetReference(remaining), delimiter, remaining.Length);
#endif
if ((index > 0 && remaining[index - 1] != delimiterEscape) || 0u >= (uint)index)
{
span = remaining.Slice(0, index);
AdvanceCurrentSpan(index + (advancePastDelimiter ? 1 : 0));
return true;
}
// This delimiter might be skipped, go down the slow path
return TryReadToSlow(out span, delimiter, delimiterEscape, index, advancePastDelimiter);
}
[MethodImpl(MethodImplOptions.NoInlining)]
private bool TryReadToSlow(out ReadOnlySpan<byte> span, byte delimiter, byte delimiterEscape, int index, bool advancePastDelimiter)
{
if (!TryReadToSlow(out ReadOnlySequence<byte> sequence, delimiter, delimiterEscape, index, advancePastDelimiter))
{
span = default;
return false;
}
Debug.Assert(sequence.Length > 0);
span = sequence.IsSingleSegment ? sequence.First.Span : sequence.ToArray();
return true;
}
private bool TryReadToSlow(out ReadOnlySequence<byte> sequence, byte delimiter, byte delimiterEscape, int index, bool advancePastDelimiter)
{
ByteBufferReader copy = this;
ReadOnlySpan<byte> remaining = UnreadSpan;
bool priorEscape = false;
do
{
uint uIndex = (uint)index;
if (SharedConstants.TooBigOrNegative >= uIndex) // index >= 0
{
if (0u >= uIndex && priorEscape) // index == 0
{
// We were in the escaped state, so skip this delimiter
priorEscape = false;
Advance(index + 1);
remaining = UnreadSpan;
goto Continue;
}
else if (index > 0 && remaining[index - 1] == delimiterEscape)
{
// This delimiter might be skipped
// Count our escapes
int escapeCount = 1;
var idx = SpanHelpers.LastIndexNotOf(
ref MemoryMarshal.GetReference(remaining),
delimiterEscape,
index - 1);
if ((uint)idx > SharedConstants.TooBigOrNegative && priorEscape) // i < 0
{
// Started and ended with escape, increment once more
escapeCount++;
}
escapeCount += index - 2 - idx;
if ((escapeCount & 1) != 0)
{
// An odd escape count means we're currently escaped,
// skip the delimiter and reset escaped state.
Advance(index + 1);
priorEscape = false;
remaining = UnreadSpan;
goto Continue;
}
}
// Found the delimiter. Move to it, slice, then move past it.
AdvanceCurrentSpan(index);
sequence = _sequence.Slice(copy.Position, Position);
if (advancePastDelimiter)
{
Advance(1);
}
return true;
}
else
{
// No delimiter, need to check the end of the span for odd number of escapes then advance
var remainingLen = remaining.Length;
if ((uint)remainingLen > 0u && remaining[remainingLen - 1] == delimiterEscape)
{
int escapeCount = 1;
var idx = SpanHelpers.LastIndexNotOf(
ref MemoryMarshal.GetReference(remaining),
delimiterEscape,
remainingLen - 1);
escapeCount += remainingLen - 2 - idx;
if ((uint)idx > SharedConstants.TooBigOrNegative && priorEscape) // idx < 0
{
priorEscape = 0u >= (uint)(escapeCount & 1); // equivalent to incrementing escapeCount before setting priorEscape
}
else
{
priorEscape = (escapeCount & 1) != 0;
}
}
else
{
priorEscape = false;
}
}
// Nothing in the current span, move to the end, checking for the skip delimiter
AdvanceCurrentSpan(remaining.Length);
remaining = _currentSpan;
Continue:
#if NET
index = remaining.IndexOf(delimiter);
#else
index = SpanHelpers.IndexOf(ref MemoryMarshal.GetReference(remaining), delimiter, remaining.Length);
#endif
} while (!End);
// Didn't find anything, reset our original state.
this = copy;
sequence = default;
return false;
}
/// <summary>Try to read everything up to the given <paramref name="delimiter"/>.</summary>
/// <param name="sequence">The read data, if any.</param>
/// <param name="delimiter">The delimiter to look for.</param>
/// <param name="advancePastDelimiter">True to move past the <paramref name="delimiter"/> if found.</param>
/// <returns>True if the <paramref name="delimiter"/> was found.</returns>
public bool TryReadTo(out ReadOnlySequence<byte> sequence, byte delimiter, bool advancePastDelimiter = true)
{
return TryReadToInternal(out sequence, delimiter, advancePastDelimiter);
}
private bool TryReadToInternal(out ReadOnlySequence<byte> sequence, byte delimiter, bool advancePastDelimiter, int skip = 0)
{
Debug.Assert(skip >= 0);
ByteBufferReader copy = this;
if (skip > 0) { Advance(skip); }
ReadOnlySpan<byte> remaining = UnreadSpan;
while (_moreData)
{
#if NET
int index = remaining.IndexOf(delimiter);
#else
int index = SpanHelpers.IndexOf(ref MemoryMarshal.GetReference(remaining), delimiter, remaining.Length);
#endif
uint uIndex = (uint)index;
if (SharedConstants.TooBigOrNegative >= uIndex) // index != -1
{
// Found the delimiter. Move to it, slice, then move past it.
if (uIndex > 0u) // 此时 index 为非负值
{
AdvanceCurrentSpan(index);
}
sequence = _sequence.Slice(copy.Position, Position);
if (advancePastDelimiter)
{
Advance(1);
}
return true;
}
AdvanceCurrentSpan(remaining.Length);
remaining = _currentSpan;
}
// Didn't find anything, reset our original state.
this = copy;
sequence = default;
return false;
}
/// <summary>Try to read everything up to the given <paramref name="delimiter"/>, ignoring delimiters that are
/// preceded by <paramref name="delimiterEscape"/>.</summary>
/// <param name="sequence">The read data, if any.</param>
/// <param name="delimiter">The delimiter to look for.</param>
/// <param name="delimiterEscape">If found prior to <paramref name="delimiter"/> it will skip that occurrence.</param>
/// <param name="advancePastDelimiter">True to move past the <paramref name="delimiter"/> if found.</param>
/// <returns>True if the <paramref name="delimiter"/> was found.</returns>
public bool TryReadTo(out ReadOnlySequence<byte> sequence, byte delimiter, byte delimiterEscape, bool advancePastDelimiter = true)
{
ByteBufferReader copy = this;
ReadOnlySpan<byte> remaining = UnreadSpan;
bool priorEscape = false;
while (_moreData)
{
#if NET
int index = remaining.IndexOf(delimiter);
#else
int index = SpanHelpers.IndexOf(ref MemoryMarshal.GetReference(remaining), delimiter, remaining.Length);
#endif
uint uIndex = (uint)index;
if (SharedConstants.TooBigOrNegative >= uIndex) // index != -1
{
if (0u >= uIndex && priorEscape) // index == 0
{
// We were in the escaped state, so skip this delimiter
priorEscape = false;
Advance(index + 1);
remaining = UnreadSpan;
continue;
}
else if (uIndex > 0u && remaining[index - 1] == delimiterEscape) // 此时 index 为非负值
{
// This delimiter might be skipped
// Count our escapes
var idx = SpanHelpers.LastIndexNotOf(
ref MemoryMarshal.GetReference(remaining),
delimiterEscape,
index);
int escapeCount = SharedConstants.TooBigOrNegative >= (uint)idx ? index - idx - 1 : index;
if (escapeCount == index && priorEscape)
{
// Started and ended with escape, increment once more
escapeCount++;
}
priorEscape = false;
if ((escapeCount & 1) != 0)
{
// Odd escape count means we're in the escaped state, so skip this delimiter
Advance(index + 1);
remaining = UnreadSpan;
continue;
}
}
// Found the delimiter. Move to it, slice, then move past it.
if (uIndex > 0u) { Advance(index); } // 此时 index 为非负值
sequence = _sequence.Slice(copy.Position, Position);
if (advancePastDelimiter) { Advance(1); }
return true;
}
// No delimiter, need to check the end of the span for odd number of escapes then advance
{
var remainingLen = remaining.Length;
var idx = SpanHelpers.LastIndexNotOf(
ref MemoryMarshal.GetReference(remaining),
delimiterEscape,
remainingLen);
int escapeCount = SharedConstants.TooBigOrNegative >= (uint)idx ? remainingLen - idx - 1 : remainingLen;
if (priorEscape && escapeCount == remainingLen)
{
escapeCount++;
}
priorEscape = escapeCount % 2 != 0;
}
// Nothing in the current span, move to the end, checking for the skip delimiter
Advance(remaining.Length);
remaining = _currentSpan;
}
// Didn't find anything, reset our original state.
this = copy;
sequence = default;
return false;
}
/// <summary>Try to read everything up to the given <paramref name="delimiters"/>.</summary>
/// <param name="span">The read data, if any.</param>
/// <param name="delimiters">The delimiters to look for.</param>
/// <param name="advancePastDelimiter">True to move past the first found instance of any of the given <paramref name="delimiters"/>.</param>
/// <returns>True if any of the <paramref name="delimiters"/> were found.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool TryReadToAny(out ReadOnlySpan<byte> span, in ReadOnlySpan<byte> delimiters, bool advancePastDelimiter = true)
{
ReadOnlySpan<byte> remaining = UnreadSpan;
#if NET
int index = delimiters.Length == 2
? remaining.IndexOfAny(delimiters[0], delimiters[1])
: remaining.IndexOfAny(delimiters);
#else
var index = SpanHelpers.IndexOfAny(ref MemoryMarshal.GetReference(remaining), remaining.Length, ref MemoryMarshal.GetReference(delimiters), delimiters.Length);
#endif
if (SharedConstants.TooBigOrNegative >= (uint)index) // index != -1
{
span = remaining.Slice(0, index);
Advance(index + (advancePastDelimiter ? 1 : 0));
return true;
}
return TryReadToAnySlow(out span, delimiters, advancePastDelimiter);
}
[MethodImpl(MethodImplOptions.NoInlining)]
private bool TryReadToAnySlow(out ReadOnlySpan<byte> span, in ReadOnlySpan<byte> delimiters, bool advancePastDelimiter)
{
if (!TryReadToAnyInternal(out ReadOnlySequence<byte> sequence, delimiters, advancePastDelimiter, _currentSpan.Length - _currentSpanIndex))
{
span = default;
return false;
}
span = sequence.IsSingleSegment ? sequence.First.Span : sequence.ToArray();
return true;
}
/// <summary>Try to read everything up to the given <paramref name="delimiters"/>.</summary>
/// <param name="sequence">The read data, if any.</param>
/// <param name="delimiters">The delimiters to look for.</param>
/// <param name="advancePastDelimiter">True to move past the first found instance of any of the given <paramref name="delimiters"/>.</param>
/// <returns>True if any of the <paramref name="delimiters"/> were found.</returns>
public bool TryReadToAny(out ReadOnlySequence<byte> sequence, in ReadOnlySpan<byte> delimiters, bool advancePastDelimiter = true)
{
return TryReadToAnyInternal(out sequence, delimiters, advancePastDelimiter);
}
private bool TryReadToAnyInternal(out ReadOnlySequence<byte> sequence, in ReadOnlySpan<byte> delimiters, bool advancePastDelimiter, int skip = 0)
{
ByteBufferReader copy = this;
if (skip > 0) { Advance(skip); }
ReadOnlySpan<byte> remaining = UnreadSpan;
ref byte delimiterSpace = ref MemoryMarshal.GetReference(delimiters);
while (!End)
{
#if NET
int index = delimiters.Length == 2
? remaining.IndexOfAny(delimiters[0], delimiters[1])
: remaining.IndexOfAny(delimiters);
#else
int index = SpanHelpers.IndexOfAny(ref MemoryMarshal.GetReference(remaining), remaining.Length, ref delimiterSpace, delimiters.Length);
#endif
uint uIndex = (uint)index;
if (SharedConstants.TooBigOrNegative >= uIndex) // index != -1
{
// Found one of the delimiters. Move to it, slice, then move past it.
if (uIndex > 0u) { AdvanceCurrentSpan(index); } // 此时 index 为非负值
sequence = _sequence.Slice(copy.Position, Position);
if (advancePastDelimiter) { Advance(1); }
return true;
}
Advance(remaining.Length);
remaining = _currentSpan;
}
// Didn't find anything, reset our original state.
this = copy;
sequence = default;
return false;
}
/// <summary>
/// Try to read everything up to the given <paramref name="delimiter"/>.
/// </summary>
/// <param name="span">The read data, if any.</param>
/// <param name="delimiter">The delimiter to look for.</param>
/// <param name="advancePastDelimiter">True to move past the <paramref name="delimiter"/> if found.</param>
/// <returns>True if the <paramref name="delimiter"/> was found.</returns>
public bool TryReadTo(out ReadOnlySpan<byte> span, ReadOnlySpan<byte> delimiter, bool advancePastDelimiter = true)
{
ReadOnlySpan<byte> remaining = UnreadSpan;
#if NET
int index = remaining.IndexOf(delimiter);
#else
int index = SpanHelpers.IndexOf(ref MemoryMarshal.GetReference(remaining), remaining.Length, ref MemoryMarshal.GetReference(delimiter), delimiter.Length);
#endif
if (index >= 0)
{
span = remaining.Slice(0, index);
AdvanceCurrentSpan(index + (advancePastDelimiter ? delimiter.Length : 0));
return true;
}
// This delimiter might be skipped, go down the slow path
return TryReadToSlow(out span, delimiter, advancePastDelimiter);
}
private bool TryReadToSlow(out ReadOnlySpan<byte> span, ReadOnlySpan<byte> delimiter, bool advancePastDelimiter)
{
if (!TryReadTo(out ReadOnlySequence<byte> sequence, delimiter, advancePastDelimiter))
{
span = default;
return false;
}
Debug.Assert(sequence.Length > 0);
span = sequence.IsSingleSegment ? sequence.First.Span : sequence.ToArray();
return true;
}
/// <summary>Try to read data until the entire given <paramref name="delimiter"/> matches.</summary>
/// <param name="sequence">The read data, if any.</param>
/// <param name="delimiter">The multi (byte) delimiter.</param>
/// <param name="advancePastDelimiter">True to move past the <paramref name="delimiter"/> if found.</param>
/// <returns>True if the <paramref name="delimiter"/> was found.</returns>
public bool TryReadTo(out ReadOnlySequence<byte> sequence, in ReadOnlySpan<byte> delimiter, bool advancePastDelimiter = true)
{
if (0u >= (uint)delimiter.Length)
{
sequence = default;
return true;
}
ByteBufferReader copy = this;
bool advanced = false;
while (!End)
{
if (!TryReadTo(out sequence, delimiter[0], advancePastDelimiter: false))
{
this = copy;
return false;
}
if (1u >= (uint)delimiter.Length) // 此时 delimiter.Length 最小值为 1
{
if (advancePastDelimiter)
{
Advance(1);
}
return true;
}
if (IsNext(delimiter))
{
// Probably a faster way to do this, potentially by avoiding the Advance in the previous TryReadTo call
if (advanced)
{
sequence = copy._sequence.Slice(copy._consumed, _consumed - copy._consumed);
}
if (advancePastDelimiter)
{
Advance(delimiter.Length);
}
return true;
}
else
{
Advance(1);
advanced = true;
}
}
this = copy;
sequence = default;
return false;
}
/// <summary>Advance until the given <paramref name="delimiter"/>, if found.</summary>
/// <param name="delimiter">The delimiter to search for.</param>
/// <param name="advancePastDelimiter">True to move past the <paramref name="delimiter"/> if found.</param>
/// <returns>True if the given <paramref name="delimiter"/> was found.</returns>
public bool TryAdvanceTo(byte delimiter, bool advancePastDelimiter = true)
{
ReadOnlySpan<byte> remaining = UnreadSpan;
#if NET
int index = remaining.IndexOf(delimiter);
#else
int index = SpanHelpers.IndexOf(ref MemoryMarshal.GetReference(remaining), delimiter, remaining.Length);
#endif
if (SharedConstants.TooBigOrNegative >= (uint)index) // ndex != -1
{
Advance(advancePastDelimiter ? index + 1 : index);
return true;
}
return TryReadToInternal(out _, delimiter, advancePastDelimiter);
}
/// <summary>Advance until any of the given <paramref name="delimiters"/>, if found.</summary>
/// <param name="delimiters">The delimiters to search for.</param>
/// <param name="advancePastDelimiter">True to move past the first found instance of any of the given <paramref name="delimiters"/>.</param>
/// <returns>True if any of the given <paramref name="delimiters"/> were found.</returns>
public bool TryAdvanceToAny(in ReadOnlySpan<byte> delimiters, bool advancePastDelimiter = true)
{
ReadOnlySpan<byte> remaining = UnreadSpan;
#if NET
int index = remaining.IndexOfAny(delimiters);
#else
int index = SpanHelpers.IndexOfAny(ref MemoryMarshal.GetReference(remaining), remaining.Length, ref MemoryMarshal.GetReference(delimiters), delimiters.Length);
#endif
if (SharedConstants.TooBigOrNegative >= (uint)index) // ndex != -1
{
AdvanceCurrentSpan(index + (advancePastDelimiter ? 1 : 0));
return true;
}
return TryReadToAnyInternal(out _, delimiters, advancePastDelimiter);
}
/// <summary>Advance past consecutive instances of the given <paramref name="value"/>.</summary>
/// <returns>How many positions the reader has been advanced.</returns>
public long AdvancePast(byte value)
{
long start = _consumed;
do
{
// Advance past all matches in the current span
var searchSpan = _currentSpan.Slice(_currentSpanIndex);
var idx = SpanHelpers.IndexNotOf(
ref MemoryMarshal.GetReference(searchSpan),
value,
searchSpan.Length);
int advanced = SharedConstants.TooBigOrNegative >= (uint)idx ? idx : _currentSpan.Length - _currentSpanIndex;
if (0u >= (uint)advanced)
{
// Didn't advance at all in this span, exit.
break;
}
AdvanceCurrentSpan(advanced);
// If we're at postion 0 after advancing and not at the End,
// we're in a new span and should continue the loop.
} while (0u >= (uint)_currentSpanIndex && !End);
return _consumed - start;
}
/// <summary>Skip consecutive instances of any of the given <paramref name="values"/>.</summary>
/// <returns>How many positions the reader has been advanced.</returns>
public long AdvancePastAny(in ReadOnlySpan<byte> values)
{
long start = _consumed;
do
{
// Advance past all matches in the current span
var searchSpan = _currentSpan.Slice(_currentSpanIndex);
var idx = SpanHelpers.IndexNotOfAny(
ref MemoryMarshal.GetReference(searchSpan),
searchSpan.Length,
ref MemoryMarshal.GetReference(values),
values.Length);
int advanced = SharedConstants.TooBigOrNegative >= (uint)idx ? _currentSpanIndex + idx : _currentSpan.Length - _currentSpanIndex;
if (0u >= (uint)advanced)
{
// Didn't advance at all in this span, exit.
break;
}
AdvanceCurrentSpan(advanced);
// If we're at postion 0 after advancing and not at the End,
// we're in a new span and should continue the loop.
} while (0u >= (uint)_currentSpanIndex && !End);
return _consumed - start;
}
/// <summary>Advance past consecutive instances of any of the given values.</summary>
/// <returns>How many positions the reader has been advanced.</returns>
public long AdvancePastAny(byte value0, byte value1, byte value2, byte value3)
{
long start = _consumed;
do
{
// Advance past all matches in the current span
var searchSpan = _currentSpan.Slice(_currentSpanIndex);
var idx = SpanHelpers.IndexNotOfAny(
ref MemoryMarshal.GetReference(searchSpan),
value0, value1, value2, value3,
searchSpan.Length);
int advanced = SharedConstants.TooBigOrNegative >= (uint)idx ? idx : _currentSpan.Length - _currentSpanIndex;
if (0u >= (uint)advanced)
{
// Didn't advance at all in this span, exit.
break;
}
AdvanceCurrentSpan(advanced);
// If we're at postion 0 after advancing and not at the End,
// we're in a new span and should continue the loop.
} while (0u >= (uint)_currentSpanIndex && !End);
return _consumed - start;
}
/// <summary>Advance past consecutive instances of any of the given values.</summary>
/// <returns>How many positions the reader has been advanced.</returns>
public long AdvancePastAny(byte value0, byte value1, byte value2)
{
long start = _consumed;
do
{
// Advance past all matches in the current span
var searchSpan = _currentSpan.Slice(_currentSpanIndex);
var idx = SpanHelpers.IndexNotOfAny(
ref MemoryMarshal.GetReference(searchSpan),
value0, value1, value2,
searchSpan.Length);
int advanced = SharedConstants.TooBigOrNegative >= (uint)idx ? idx : _currentSpan.Length - _currentSpanIndex;
if (0u >= (uint)advanced)
{
// Didn't advance at all in this span, exit.
break;
}
AdvanceCurrentSpan(advanced);
// If we're at postion 0 after advancing and not at the End,
// we're in a new span and should continue the loop.
} while (0u >= (uint)_currentSpanIndex && !End);
return _consumed - start;
}
/// <summary>Advance past consecutive instances of any of the given values.</summary>
/// <returns>How many positions the reader has been advanced.</returns>
public long AdvancePastAny(byte value0, byte value1)
{
long start = _consumed;
do
{
// Advance past all matches in the current span
var searchSpan = _currentSpan.Slice(_currentSpanIndex);
var idx = SpanHelpers.IndexNotOfAny(
ref MemoryMarshal.GetReference(searchSpan),
value0, value1,
searchSpan.Length);
int advanced = SharedConstants.TooBigOrNegative >= (uint)idx ? idx : _currentSpan.Length - _currentSpanIndex;
if (0u >= (uint)advanced)
{
// Didn't advance at all in this span, exit.
break;
}
AdvanceCurrentSpan(advanced);
// If we're at postion 0 after advancing and not at the End,
// we're in a new span and should continue the loop.
} while (0u >= (uint)_currentSpanIndex && !End);
return _consumed - start;
}
/// <summary>
/// Moves the reader to the end of the sequence.
/// </summary>
public void AdvanceToEnd()
{
if (_moreData)
{
Consumed = Length;
CurrentSpan = default;
CurrentSpanIndex = 0;
_currentPosition = Sequence.End;
_nextPosition = default;
_moreData = false;
}
}
/// <summary>Check to see if the given <paramref name="next"/> value is next.</summary>
/// <param name="next">The value to compare the next items to.</param>
/// <param name="advancePast">Move past the <paramref name="next"/> value if found.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool IsNext(byte next, bool advancePast = false)
{
if (End) { return false; }
if (_currentSpan[_currentSpanIndex] == next)
{
if (advancePast) { AdvanceCurrentSpan(1); }
return true;
}
return false;
}
/// <summary>Check to see if the given <paramref name="next"/> values are next.</summary>
/// <param name="next">The span to compare the next items to.</param>
/// <param name="advancePast">Move past the <paramref name="next"/> values if found.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool IsNext(in ReadOnlySpan<byte> next, bool advancePast = false)
{
ReadOnlySpan<byte> unread = UnreadSpan;
if (unread.StartsWith(next))
{
if (advancePast) { AdvanceCurrentSpan(next.Length); }
return true;
}
// Only check the slow path if there wasn't enough to satisfy next
return (uint)unread.Length < (uint)next.Length && IsNextSlow(next, advancePast);
}
[MethodImpl(MethodImplOptions.NoInlining)]
private unsafe bool IsNextSlow(ReadOnlySpan<byte> next, bool advancePast)
{
ReadOnlySpan<byte> currentSpan = UnreadSpan;
// We should only come in here if we need more data than we have in our current span
Debug.Assert(currentSpan.Length < next.Length);
int fullLength = next.Length;
SequencePosition nextPosition = _nextPosition;
while (next.StartsWith(currentSpan))
{
if (next.Length == currentSpan.Length)
{
// Fully matched
if (advancePast) { Advance(fullLength); }
return true;
}
// Need to check the next segment
while (true)
{
if (!_sequence.TryGet(ref nextPosition, out ReadOnlyMemory<byte> nextSegment, advance: true))
{
// Nothing left
return false;
}
if ((uint)nextSegment.Length > 0u)
{
next = next.Slice(currentSpan.Length);
currentSpan = nextSegment.Span;
if ((uint)currentSpan.Length > (uint)next.Length)
{
currentSpan = currentSpan.Slice(0, next.Length);
}
break;
}
}
}
return false;
}
}
}
| 43.005903 | 171 | 0.540932 | [
"MIT"
] | cuteant/SpanNetty | src/DotNetty.Buffers/Reader/ByteBufferReader.Search.cs | 36,488 | C# |
namespace Backdrops
{
public class Wallpaper
{
public int ID;
public int CategoryID;
public string CategoryName;
public string ImageURL;
public string ThumbURL;
public string Title;
public string Description;
public string Tags;
public string Size;
public string User;
public string CopyrightName;
public string CopyrightURL;
public int Width;
public int Height;
public int DownloadCount;
public float Rating;
}
}
| 24.130435 | 36 | 0.607207 | [
"MIT"
] | ApexWeed/backdrops | Backdrops/Wallpaper.cs | 557 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using BenchmarkDotNet.Attributes;
namespace Contoso.GameNetCore.Routing.Matching
{
public class RouteEndpointAzureBenchmark : MatcherAzureBenchmarkBase
{
[Benchmark]
public void CreateEndpoints()
{
SetupEndpoints();
}
}
} | 28.8125 | 112 | 0.67462 | [
"Apache-2.0"
] | bclnet/GameNetCore | src/Proto/Routing/perf/Matching/RouteEndpointAzureBenchmark.cs | 461 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium.DevTools;
namespace OpenQA.Selenium.Remote
{
public class RemoteNetwork : INetwork
{
private Lazy<DevToolsSession> session;
private List<NetworkRequestHandler> requestHandlers = new List<NetworkRequestHandler>();
private List<NetworkAuthenticationHandler> authenticationHandlers = new List<NetworkAuthenticationHandler>();
public RemoteNetwork(IWebDriver driver)
{
// Use of Lazy<T> means this exception won't be thrown until the user first
// attempts to access the DevTools session, probably on the first call to
// StartMonitoring().
this.session = new Lazy<DevToolsSession>(() =>
{
IDevTools devToolsDriver = driver as IDevTools;
if (session == null)
{
throw new WebDriverException("Driver must implement IDevTools to use these features");
}
return devToolsDriver.GetDevToolsSession();
});
}
public event EventHandler<NetworkResponseRecievedEventArgs> NetworkResponseReceived;
public event EventHandler<NetworkRequestSentEventArgs> NetworkRequestSent;
public async Task StartMonitoring()
{
this.session.Value.Domains.Network.RequestPaused += OnRequestPaused;
this.session.Value.Domains.Network.AuthRequired += OnAuthRequired;
this.session.Value.Domains.Network.ResponsePaused += OnResponsePaused;
await this.session.Value.Domains.Network.EnableFetchForAllPatterns();
await this.session.Value.Domains.Network.EnableNetwork();
await this.session.Value.Domains.Network.DisableNetworkCaching();
}
public async Task StopMonitoring()
{
this.session.Value.Domains.Network.ResponsePaused -= OnResponsePaused;
this.session.Value.Domains.Network.AuthRequired -= OnAuthRequired;
this.session.Value.Domains.Network.RequestPaused -= OnRequestPaused;
await this.session.Value.Domains.Network.EnableNetworkCaching();
}
public void AddRequestHandler(NetworkRequestHandler handler)
{
if (handler == null)
{
throw new ArgumentNullException("handler", "Request handler cannot be null");
}
if (handler.RequestMatcher == null)
{
throw new ArgumentException("Matcher for request cannot be null", "handler");
}
if (handler.RequestTransformer == null && handler.ResponseSupplier == null)
{
throw new ArgumentException("Request transformer and response supplier cannot both be null", "handler");
}
this.requestHandlers.Add(handler);
}
public void ClearRequestHandlers()
{
this.requestHandlers.Clear();
}
public void AddAuthenticationHandler(NetworkAuthenticationHandler handler)
{
if (handler == null)
{
throw new ArgumentNullException("handler", "Authentication handler cannot be null");
}
if (handler.UriMatcher == null)
{
throw new ArgumentException("Matcher for delegate for URL cannot be null", "handler");
}
if (handler.Credentials == null)
{
throw new ArgumentException("Credentials to use for authentication cannot be null", "handler");
}
var passwordCredentials = handler.Credentials as PasswordCredentials;
if (passwordCredentials == null)
{
throw new ArgumentException("Credentials must contain user name and password (PasswordCredentials)", "handler");
}
this.authenticationHandlers.Add(handler);
}
public void ClearAuthenticationHandlers()
{
this.authenticationHandlers.Clear();
}
private async void OnAuthRequired(object sender, AuthRequiredEventArgs e)
{
string requestId = e.RequestId;
Uri uri = new Uri(e.Uri);
bool successfullyAuthenticated = false;
foreach (var authenticationHandler in this.authenticationHandlers)
{
if (authenticationHandler.UriMatcher.Invoke(uri))
{
PasswordCredentials credentials = authenticationHandler.Credentials as PasswordCredentials;
await this.session.Value.Domains.Network.ContinueWithAuth(e.RequestId, credentials.UserName, credentials.Password);
successfullyAuthenticated = true;
break;
}
}
if (!successfullyAuthenticated)
{
await this.session.Value.Domains.Network.CancelAuth(e.RequestId);
}
}
private async void OnRequestPaused(object sender, RequestPausedEventArgs e)
{
if (this.NetworkRequestSent != null)
{
this.NetworkRequestSent(this, new NetworkRequestSentEventArgs(e.RequestData));
}
foreach (var handler in this.requestHandlers)
{
if (handler.RequestMatcher.Invoke(e.RequestData))
{
if (handler.RequestTransformer != null)
{
await this.session.Value.Domains.Network.ContinueRequest(handler.RequestTransformer(e.RequestData));
return;
}
if (handler.ResponseSupplier != null)
{
await this.session.Value.Domains.Network.ContinueRequestWithResponse(e.RequestData, handler.ResponseSupplier(e.RequestData));
return;
}
}
}
await this.session.Value.Domains.Network.ContinueRequestWithoutModification(e.RequestData);
}
private async void OnResponsePaused(object sender, ResponsePausedEventArgs e)
{
await this.session.Value.Domains.Network.AddResponseBody(e.ResponseData);
await this.session.Value.Domains.Network.ContinueResponseWithoutModification(e.ResponseData);
if (this.NetworkResponseReceived != null)
{
this.NetworkResponseReceived(this, new NetworkResponseRecievedEventArgs(e.ResponseData));
}
}
}
}
| 39.192982 | 149 | 0.603253 | [
"Apache-2.0"
] | Blazemeter/selenium | dotnet/src/webdriver/Remote/RemoteNetwork.cs | 6,702 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace NetOffice.DeveloperToolbox.ToolboxControls.ProxyView
{
interface IRefresh : IDisposable
{
void RefreshAsync(Action<IRefresh> complete, Control syncRoot);
bool IsCurrentlyRefresh { get; }
}
} | 23 | 71 | 0.744928 | [
"MIT"
] | NetOfficeFw/NetOfficeToolbox | DeveloperToolbox/ToolboxControls/ProxyView/IRefresh.cs | 347 | C# |
using JetBrains.Annotations;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace gm.modularity
{
public interface IDependedProvider
{
[NotNull]
Type[] GetDependeds();
}
}
| 17.1875 | 38 | 0.712727 | [
"MIT"
] | zfeihong/iot | framework/src/gm.core/gm/modularity/interface/IDependedProvider.cs | 277 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by Entitas.CodeGeneration.Plugins.ComponentEntityApiGenerator.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
public partial class GameEntity {
public DictionaryComponent dictionary { get { return (DictionaryComponent)GetComponent(GameComponentsLookup.Dictionary); } }
public bool hasDictionary { get { return HasComponent(GameComponentsLookup.Dictionary); } }
public void AddDictionary(System.Collections.Generic.Dictionary<string, string> newDict) {
var index = GameComponentsLookup.Dictionary;
var component = (DictionaryComponent)CreateComponent(index, typeof(DictionaryComponent));
component.dict = newDict;
AddComponent(index, component);
}
public void ReplaceDictionary(System.Collections.Generic.Dictionary<string, string> newDict) {
var index = GameComponentsLookup.Dictionary;
var component = (DictionaryComponent)CreateComponent(index, typeof(DictionaryComponent));
component.dict = newDict;
ReplaceComponent(index, component);
}
public void RemoveDictionary() {
RemoveComponent(GameComponentsLookup.Dictionary);
}
}
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by Entitas.CodeGeneration.Plugins.ComponentMatcherApiGenerator.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
public sealed partial class GameMatcher {
static Entitas.IMatcher<GameEntity> _matcherDictionary;
public static Entitas.IMatcher<GameEntity> Dictionary {
get {
if (_matcherDictionary == null) {
var matcher = (Entitas.Matcher<GameEntity>)Entitas.Matcher<GameEntity>.AllOf(GameComponentsLookup.Dictionary);
matcher.componentNames = GameComponentsLookup.componentNames;
_matcherDictionary = matcher;
}
return _matcherDictionary;
}
}
}
| 41.982456 | 128 | 0.615963 | [
"MIT"
] | ADADebug/Entitas-CSharp | Tests/Unity/VisualDebugging/Assets/Sources/Generated/Game/Components/GameDictionaryComponent.cs | 2,393 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace browser
{
public partial class Form2 : Form
{
string[] nowdata;
string build;
public Form2(string[] data)
{
nowdata = data;
build = data[0] + ":";
build = build + data[1] + ":";
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text != "")
{
build = build + textBox1.Text;
System.IO.File.AppendAllText("lhmp/favorite.txt", build + Environment.NewLine);
this.Close();
}
}
private void Form2_Load(object sender, EventArgs e)
{
}
}
}
| 22.525 | 95 | 0.528302 | [
"Apache-2.0"
] | LHMPTeam/lhmp-old | Others/browser/Form2.cs | 903 | C# |
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using System;
using System.Collections.Generic;
using System.Text;
namespace Model
{
public class ModelData
{
public static Action<ULTypeInfo> onAddType;
public static Action<ULTypeInfo> onRemoveType;
public const string GloableNamespaceName = "gloable";
static Dictionary<string, ULTypeInfo> TypeNames = new Dictionary<string, ULTypeInfo>();
public static List<ULTypeInfo> GetTypeList() { return new List<ULTypeInfo>(TypeNames.Values); }
public static ULTypeInfo FindTypeByFullName(string full_name)
{
if (string.IsNullOrEmpty(full_name))
return null;
if(TypeNames.TryGetValue(full_name,out var v))
{
return v;
}
return null;
}
public static ULTypeInfo FindTypeInNamepsace(string name,List<string> namespaceList)
{
foreach(var t in TypeNames.Values)
{
if(t.Name == name && namespaceList.Contains(t.Namespace))
{
return t;
}
}
return null;
}
public static bool HasNamepsace(string ns)
{
foreach (var t in TypeNames.Values)
{
if (t.Namespace == ns)
{
return true;
}
}
return false;
}
public static void AddType(ULTypeInfo typeInfo)
{
typeInfo.onNameChanged = (last, newName) =>
{
TypeNames.Remove(typeInfo.Namespace+"."+ last);
TypeNames.Add(typeInfo.Namespace + "." + newName, typeInfo);
};
TypeNames.Add(typeInfo.FullName, typeInfo);
onAddType?.Invoke(typeInfo);
}
public static void RemoveType(string FullName)
{
if(TypeNames.TryGetValue(FullName,out var t))
{
t.onNameChanged = null;
TypeNames.Remove(FullName);
onRemoveType?.Invoke(t);
}
}
public static void UpdateType(ULTypeInfo typeInfo)
{
RemoveType(typeInfo.FullName);
AddType(typeInfo);
}
public static void Save()
{
try
{
var fs = new System.IO.FileStream("model.dat", System.IO.FileMode.OpenOrCreate);
//List<ULTypeInfo> type_list = new List<ULTypeInfo>(TypeNames.Values);
MongoDB.Bson.Serialization.BsonSerializer.Serialize(new MongoDB.Bson.IO.BsonBinaryWriter(fs), TypeNames);
fs.SetLength(fs.Position);
fs.Close();
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
}
public static void Load()
{
if(!System.IO.File.Exists("model.dat"))
{
return;
}
try
{
var fs = new System.IO.FileStream("model.dat", System.IO.FileMode.Open);
TypeNames = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<Dictionary<string,ULTypeInfo>>(fs);
List<ULTypeInfo> type_list = new List<ULTypeInfo>(TypeNames.Values);
TypeNames.Clear();
foreach(var t in type_list)
{
TypeNames[t.FullName] = t;
}
fs.Close();
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
}
}
//名称规范:
//命名空间.类.成员.(参数,局部变量)
//global. 全局类,无命名空间
//local.局部变量,包括参数
//output.id[0] 节点输出参数
//this.成员
//base.父类的方法
public enum EModifier
{
Public,
Protected,
Private,
}
[BsonIgnoreExtraElements]
public class ULTypeInfo
{
[BsonIgnore]
public System.Action<string, string> onNameChanged;
//[BsonId]
//[BsonRepresentation(BsonType.ObjectId)]
//public string id { get; set; }
[BsonElement("Name")]
string _name { get; set; }
[BsonIgnore]
public string Name { get { return _name; } set { if (_name != value) { string tempName = _name; _name = value; onNameChanged?.Invoke(tempName, _name); } } }
public string Namespace { get; set; }
public string Parent { get; set; }
public EModifier ExportType { get; set; }
public bool IsValueType { get; set; }
public bool IsInterface { get; set; }
public bool IsEnum { get; set; }
public List<ULMemberInfo> Members = new List<ULMemberInfo>();
public string FullName {
get
{
return Namespace + "." + Name;
}
}
}
public class ULMemberInfo
{
public string DeclareTypeName { get; set; }
[BsonIgnore]
public ULTypeInfo DeclareType { get { return Model.ModelData.FindTypeByFullName(DeclareTypeName); } }
public string TypeName { get; set; }
[BsonIgnore]
public ULTypeInfo Type { get { return Model.ModelData.FindTypeByFullName(TypeName); } }
public string Name { get; set; }
[BsonIgnore]
public string FullName { get { return DeclareTypeName + "." + Name; } }
public EModifier Modifier { get; set; }
public bool IsStatic { get; set; }
public Dictionary<string, string> Ext { get; set; }
public enum EMemberType
{
Field,
Property,
Method,
Event,
Enum,
PropertyGet,
PropertySet,
PropertyAdd,
PropertyRemove
}
public string Name_PropertyGet { get { return Name + "_get"; } }
public string Name_PropertySet { get { return Name + "_set"; } }
public string Name_PropertyAdd { get { return Name + "_add"; } }
public string Name_PropertyRemove { get { return Name + "_remove"; } }
public EMemberType MemberType { get; set; }
public class MethodArg
{
public string TypeName { get; set; }
public string ArgName { get; set; }
}
public List<MethodArg> Args { get; set; }
public ULNodeBlock MethodBody;
}
[BsonKnownTypes(typeof(ULStatementSwitch))]
[BsonKnownTypes(typeof(ULStatementDo))]
[BsonKnownTypes(typeof(ULStatementReturn))]
[BsonKnownTypes(typeof(ULCall))]
[BsonKnownTypes(typeof(ULStatementBreak))]
[BsonKnownTypes(typeof(ULStatementFor))]
[BsonKnownTypes(typeof(ULStatementWhile))]
[BsonKnownTypes(typeof(ULStatementIf))]
[BsonKnownTypes(typeof(ULNodeBlock))]
public class ULStatement
{
[BsonIgnore]
public ULNodeBlock Parent;
}
public class ULNodeBlock: ULStatement
{
public List<ULStatement> statements = new List<ULStatement>();
void AfterDeserialization()
{
foreach(var s in statements)
{
s.Parent = this;
}
}
}
public class ULStatementIf : ULStatement
{
public string arg { get; set; }
public ULNodeBlock trueBlock { get; set; }
public ULNodeBlock falseBlock { get; set; }
}
public class ULStatementWhile : ULStatement
{
public string arg { get; set; }
public ULNodeBlock block { get; set; }
}
public class ULStatementFor : ULStatement
{
public string Declaration { get; set; }
public string Condition { get; set; }
public List<string> Incrementors { get; set; }
public ULNodeBlock block { get; set; }
}
public class ULStatementBreak : ULStatement
{
}
public class ULStatementReturn : ULStatement
{
public string Arg;
}
public class ULStatementDo : ULStatement
{
public string arg { get; set; }
public ULNodeBlock block { get; set; }
}
public class ULStatementSwitch : ULStatement
{
public string Condition { get; set; }
public class Section
{
public List<string> Labels { get; set; }
public List<ULNodeBlock> Statements { get; set; }
}
public List<Section> Sections { get; set; }
}
public class ULCall : ULStatement
{
public ULCall()
{
id = Guid.NewGuid().ToString();
}
public string id { get; set; }
public string Name { get; set; }
List<string> _args;
public List<string> Args
{
get
{
if (_args == null)
{
_args = new List<string>();
}
return _args;
}
set
{
_args = value;
}
}
public string GetOutputName(int index)
{
return "output." + id + "[" + index + "]";
}
public enum ECallType
{
Method,
//GetProperty,
//SetProperty,
Constructor,
GetField,
SetField,
GetLocal,
SetLocal,
GetArg,
SetArg,
GetThis,
Const,
Assign,
Identifier,
CreateArray,
GetBase,
ElementAccess,
DeclarationLocal
}
public ECallType callType { get; set; }
}
}
| 25.843501 | 164 | 0.524069 | [
"MIT"
] | xiongfang/UL | UL/ULEditor/Model/UL.cs | 9,847 | 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("Password Generator")]
[assembly: AssemblyDescription("Password Generator Website")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Murray Grant")]
[assembly: AssemblyProduct("Password Generator")]
[assembly: AssemblyCopyright("Copyright © Murray Grant 2013")]
[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("f7b1a927-462c-4835-9ac3-ad4117242e71")]
// 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 Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 40.388889 | 85 | 0.737276 | [
"Apache-2.0"
] | ligos/MakeMeAPassword | MakeMeAPassword.Web/Properties/AssemblyInfo.cs | 1,457 | C# |
using AccountingSystems.PurchaseOrders.Dto;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace AccountingSystems.Web.Models.PurchaseOrder
{
public class PurchaseOrderListViewModel
{
public IReadOnlyList<PurchaseOrderListDto> PurchaseOrders { get; set; }
}
}
| 24 | 79 | 0.782738 | [
"MIT"
] | CorinthDev-Github/Invoice-and-Accounting-System | aspnet-core/src/AccountingSystems.Web.Mvc/Models/PurchaseOrder/PurchaseOrderListViewModel.cs | 338 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Web;
using Mindscape.Raygun4Net.Messages;
using NUnit.Framework;
namespace Mindscape.Raygun4Net.Tests
{
[TestFixture]
public class RaygunClientTests
{
private FakeRaygunClient _client;
private Exception _exception = new NullReferenceException("The thing is null");
[SetUp]
public void SetUp()
{
_client = new FakeRaygunClient();
}
// User tests
[Test]
public void DefaultUser()
{
Assert.IsNull(_client.User);
}
[Test]
public void UserProperty()
{
_client.User = "Robbie Robot";
Assert.AreEqual("Robbie Robot", _client.User);
}
[Test]
public void MessageWithUser()
{
_client.User = "Robbie Robot";
RaygunMessage message = _client.CreateMessage(_exception);
Assert.AreEqual("Robbie Robot", message.Details.User.Identifier);
}
// Application version tests
[Test]
public void DefaultApplicationVersion()
{
Assert.IsNull(_client.ApplicationVersion);
}
[Test]
public void ApplicationVersionProperty()
{
_client.ApplicationVersion = "Custom Version";
Assert.AreEqual("Custom Version", _client.ApplicationVersion);
}
[Test]
public void SetCustomApplicationVersion()
{
_client.ApplicationVersion = "Custom Version";
RaygunMessage message = _client.CreateMessage(_exception);
Assert.AreEqual("Custom Version", message.Details.Version);
}
// Exception stripping tests
[Test]
public void StripTargetInvocationExceptionByDefault()
{
TargetInvocationException wrapper = new TargetInvocationException(_exception);
RaygunMessage message = _client.CreateMessage(wrapper);
Assert.AreEqual("System.NullReferenceException", message.Details.Error.ClassName);
}
[Test]
public void StripHttpUnhandledExceptionByDefault()
{
HttpUnhandledException wrapper = new HttpUnhandledException("Something went wrong", _exception);
RaygunMessage message = _client.CreateMessage(wrapper);
Assert.AreEqual("System.NullReferenceException", message.Details.Error.ClassName);
}
[Test]
public void StripSpecifiedWrapperException()
{
_client.AddWrapperExceptions(new Type[] { typeof(WrapperException) });
WrapperException wrapper = new WrapperException(_exception);
RaygunMessage message = _client.CreateMessage(wrapper);
Assert.AreEqual("System.NullReferenceException", message.Details.Error.ClassName);
}
[Test]
public void DontStripIfNoInnerException()
{
HttpUnhandledException wrapper = new HttpUnhandledException();
RaygunMessage message = _client.CreateMessage(wrapper);
Assert.AreEqual("System.Web.HttpUnhandledException", message.Details.Error.ClassName);
Assert.IsNull(message.Details.Error.InnerError);
}
[Test]
public void StripMultipleWrapperExceptions()
{
HttpUnhandledException wrapper = new HttpUnhandledException("Something went wrong", _exception);
TargetInvocationException wrapper2 = new TargetInvocationException(wrapper);
RaygunMessage message = _client.CreateMessage(wrapper2);
Assert.AreEqual("System.NullReferenceException", message.Details.Error.ClassName);
}
// Validation tests
[Test]
public void NoAPIKeyIsInvalid()
{
Assert.IsFalse(_client.Validate());
}
[Test]
public void APIKeyIsValid()
{
FakeRaygunClient client = new FakeRaygunClient("MY_API_KEY");
Assert.IsTrue(client.Validate());
}
// Tags and user custom data tests
[Test]
public void TagsAreNullByDefault()
{
RaygunMessage message = _client.CreateMessage(_exception);
Assert.IsNull(message.Details.Tags);
}
[Test]
public void Tags()
{
IList<string> tags = new List<string>();
tags.Add("Very Important");
tags.Add("WPF");
RaygunMessage message = _client.CreateMessage(_exception, tags);
Assert.IsNotNull(message.Details.Tags);
Assert.AreEqual(2, message.Details.Tags.Count);
Assert.Contains("Very Important", (ICollection)message.Details.Tags);
Assert.Contains("WPF", (ICollection)message.Details.Tags);
}
[Test]
public void UserCustomDataIsNullByDefault()
{
RaygunMessage message = _client.CreateMessage(_exception);
Assert.IsNull(message.Details.UserCustomData);
}
[Test]
public void UserCustomData()
{
IDictionary data = new Dictionary<string, string>();
data.Add("x", "42");
data.Add("obj", "NULL");
RaygunMessage message = _client.CreateMessage(_exception, null, data);
Assert.IsNotNull(message.Details.UserCustomData);
Assert.AreEqual(2, message.Details.UserCustomData.Count);
Assert.AreEqual("42", message.Details.UserCustomData["x"]);
Assert.AreEqual("NULL", message.Details.UserCustomData["obj"]);
}
}
} | 27.819672 | 102 | 0.69338 | [
"MIT"
] | ghuntley/raygun4net | Mindscape.Raygun4Net.Tests/RaygunClientTests.cs | 5,093 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TestHelper;
namespace Microsoft.Azure.WebJobs.Extensions.DurableTask.Analyzers.Test.Entity
{
[TestClass]
public class DispatchEntityNameAnalyzerTests : CodeFixVerifier
{
private static readonly string DiagnosticId = DispatchEntityNameAnalyzer.DiagnosticId;
private static readonly DiagnosticSeverity Severity = DiagnosticSeverity.Warning;
private const string ExpectedFix = @"
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.DurableTask;
public class MyEmptyEntity : IMyEmptyEntity
{
[FunctionName(""MyEmptyEntity"")]
public static Task Run([EntityTrigger] IDurableEntityContext ctx) => ctx.DispatchAsync<MyEmptyEntity>();
}";
[TestMethod]
public void DispatchCall_NoDiagnosticTestCases()
{
VerifyCSharpDiagnostic(ExpectedFix);
}
// Tests SyntaxKind.IdentifierName
[TestMethod]
public void DispatchCall_UsingObject()
{
var test = @"
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.DurableTask;
public class MyEmptyEntity : IMyEmptyEntity
{
[FunctionName(""MyEmptyEntity"")]
public static Task Run([EntityTrigger] IDurableEntityContext ctx) => ctx.DispatchAsync<Object>();
}";
var expectedDiagnostics = new DiagnosticResult
{
Id = DiagnosticId,
Message = string.Format(Resources.DispatchEntityNameAnalyzerMessageFormat, "Object", "MyEmptyEntity"),
Severity = Severity,
Locations =
new[] {
new DiagnosticResultLocation("Test0.cs", 9, 96)
}
};
VerifyCSharpDiagnostic(test, expectedDiagnostics);
VerifyCSharpFix(test, ExpectedFix);
}
// Tests SyntaxKind.PredefinedType
[TestMethod]
public void DispatchCall_UsingString()
{
var test = @"
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.DurableTask;
public class MyEmptyEntity : IMyEmptyEntity
{
[FunctionName(""MyEmptyEntity"")]
public static Task Run([EntityTrigger] IDurableEntityContext ctx) => ctx.DispatchAsync<string>();
}";
var expectedDiagnostics = new DiagnosticResult
{
Id = DiagnosticId,
Message = string.Format(Resources.DispatchEntityNameAnalyzerMessageFormat, "string", "MyEmptyEntity"),
Severity = Severity,
Locations =
new[] {
new DiagnosticResultLocation("Test0.cs", 9, 96)
}
};
VerifyCSharpDiagnostic(test, expectedDiagnostics);
VerifyCSharpFix(test, ExpectedFix);
}
// Tests SyntaxKind.GenericName
[TestMethod]
public void DispatchCall_UsingList()
{
var test = @"
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.DurableTask;
public class MyEmptyEntity : IMyEmptyEntity
{
[FunctionName(""MyEmptyEntity"")]
public static Task Run([EntityTrigger] IDurableEntityContext ctx) => ctx.DispatchAsync<List<string>>();
}";
var expectedDiagnostics = new DiagnosticResult
{
Id = DiagnosticId,
Message = string.Format(Resources.DispatchEntityNameAnalyzerMessageFormat, "List<string>", "MyEmptyEntity"),
Severity = Severity,
Locations =
new[] {
new DiagnosticResultLocation("Test0.cs", 9, 96)
}
};
VerifyCSharpDiagnostic(test, expectedDiagnostics);
VerifyCSharpFix(test, ExpectedFix);
}
// Tests SyntaxKind.ArrayType
[TestMethod]
public void DispatchCall_UsingArray()
{
var test = @"
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.DurableTask;
public class MyEmptyEntity : IMyEmptyEntity
{
[FunctionName(""MyEmptyEntity"")]
public static Task Run([EntityTrigger] IDurableEntityContext ctx) => ctx.DispatchAsync<string[]>();
}";
var expectedDiagnostics = new DiagnosticResult
{
Id = DiagnosticId,
Message = string.Format(Resources.DispatchEntityNameAnalyzerMessageFormat, "string[]", "MyEmptyEntity"),
Severity = Severity,
Locations =
new[] {
new DiagnosticResultLocation("Test0.cs", 9, 96)
}
};
VerifyCSharpDiagnostic(test, expectedDiagnostics);
VerifyCSharpFix(test, ExpectedFix);
}
// Tests SyntaxKind.TupleType
[TestMethod]
public void DispatchCall_UsingValueTuple()
{
var test = @"
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.DurableTask;
public class MyEmptyEntity : IMyEmptyEntity
{
[FunctionName(""MyEmptyEntity"")]
public static Task Run([EntityTrigger] IDurableEntityContext ctx) => ctx.DispatchAsync<(string, int)>();
}";
var expectedDiagnostics = new DiagnosticResult
{
Id = DiagnosticId,
Message = string.Format(Resources.DispatchEntityNameAnalyzerMessageFormat, "(string, int)", "MyEmptyEntity"),
Severity = Severity,
Locations =
new[] {
new DiagnosticResultLocation("Test0.cs", 9, 96)
}
};
VerifyCSharpDiagnostic(test, expectedDiagnostics);
VerifyCSharpFix(test, ExpectedFix);
}
// Tests interface not defined in user code
[TestMethod]
public void DispatchCall_ILogger()
{
var test = @"
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.DurableTask;
public class MyEmptyEntity : IMyEmptyEntity
{
[FunctionName(""MyEmptyEntity"")]
public static Task Run([EntityTrigger] IDurableEntityContext ctx) => ctx.DispatchAsync<ILogger>();
}";
var expectedDiagnostics = new DiagnosticResult
{
Id = DiagnosticId,
Message = string.Format(Resources.DispatchEntityNameAnalyzerMessageFormat, "ILogger", "MyEmptyEntity"),
Severity = Severity,
Locations =
new[] {
new DiagnosticResultLocation("Test0.cs", 9, 96)
}
};
VerifyCSharpDiagnostic(test, expectedDiagnostics);
VerifyCSharpFix(test, ExpectedFix);
}
protected override CodeFixProvider GetCSharpCodeFixProvider()
{
return new DispatchEntityNameCodeFixProvider();
}
protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer()
{
return new DispatchEntityNameAnalyzer();
}
}
}
| 34.053097 | 125 | 0.613176 | [
"MIT"
] | Azure/azure-functions-durable-extension | test/WebJobs.Extensions.DurableTask.Analyzers.Test/Entity/DispatchEntityNameAnalyzerTests.cs | 7,698 | C# |
// Copyright 2014 The Rector & Visitors of the University of Virginia
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AppCenter.Analytics;
using Sensus.Context;
using Sensus.Exceptions;
using Sensus.Extensions;
using System.Linq;
using System.Text.RegularExpressions;
#if __IOS__
using Sensus.Notifications;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
#endif
namespace Sensus.Callbacks
{
/// <summary>
/// Sensus schedules operations via a scheduler.
/// </summary>
public abstract class CallbackScheduler
{
public const string SENSUS_CALLBACK_KEY = "SENSUS-CALLBACK";
public const string SENSUS_CALLBACK_INVOCATION_ID_KEY = "SENSUS-CALLBACK-INVOCATION-ID";
private ConcurrentDictionary<string, ScheduledCallback> _idCallback;
public CallbackScheduler()
{
_idCallback = new ConcurrentDictionary<string, ScheduledCallback>();
}
protected abstract Task RequestLocalInvocationAsync(ScheduledCallback callback);
protected abstract void CancelLocalInvocation(ScheduledCallback callback);
public virtual async Task<ScheduledCallbackState> ScheduleCallbackAsync(ScheduledCallback callback)
{
// the next execution time is computed from the time the current method is called, as the
// caller may hang on to the ScheduledCallback for some time before calling the current method.
// we set the time here, before adding it to the collection below, so that any callback
// in the collection will certainly have a next execution time.
callback.NextExecution = DateTime.Now + callback.Delay;
if (callback.State != ScheduledCallbackState.Created)
{
SensusException.Report("Attemped to schedule callback " + callback.Id + ", which is in the " + callback.State + " state and not the " + ScheduledCallbackState.Created + " state.");
callback.State = ScheduledCallbackState.Unknown;
}
else if (_idCallback.TryAdd(callback.Id, callback))
{
callback.InvocationId = Guid.NewGuid().ToString();
BatchNextExecutionWithToleratedDelay(callback);
// the state needs to be updated after batching is performed, so that other callbacks don't
// attempt to batch with it, but before the invocations are requested, so that if the invocation
// comes back immediately (e.g., being scheduled in the past) the callback is scheduled and
// ready to run.
callback.State = ScheduledCallbackState.Scheduled;
await RequestLocalInvocationAsync(callback);
}
else
{
SensusServiceHelper.Get().Logger.Log("Attempted to schedule duplicate callback for " + callback.Id + ".", LoggingLevel.Normal, GetType());
}
return callback.State;
}
/// <summary>
/// Batches the <see cref="ScheduledCallback.NextExecution"/> value within the parameters of toleration (<see cref="ScheduledCallback.DelayToleranceBefore"/>
/// and <see cref="ScheduledCallback.DelayToleranceAfter"/>), given the <see cref="ScheduledCallback"/>s that are already scheduled to run.
/// </summary>
/// <param name="callback">Callback.</param>
private void BatchNextExecutionWithToleratedDelay(ScheduledCallback callback)
{
callback.Batched = false;
// if delay tolerance is allowed, look for other scheduled callbacks in range of the delay tolerance.
if (callback.DelayToleranceTotal.Ticks > 0)
{
DateTime rangeStart = callback.NextExecution.Value - callback.DelayToleranceBefore;
DateTime rangeEnd = callback.NextExecution.Value + callback.DelayToleranceAfter;
ScheduledCallback closestCallbackInRange = _idCallback.Values.Where(existingCallback => existingCallback != callback && // the current callback will already have been added to the collection. don't consider it.
existingCallback.NextExecution.Value >= rangeStart && // consider callbacks within range of the current
existingCallback.NextExecution.Value <= rangeEnd && // consider callbacks within range of the current
!existingCallback.Batched && // don't consider batching with other callbacks that are themselves batched, as this can potentially create batch cycling if the delay tolerance values are large.
existingCallback.State == ScheduledCallbackState.Scheduled) // consider callbacks that are already scheduled. we don't want to batch with callbacks that are, e.g., running or recently completed.
// get existing callback with execution time closest to the current callback's time
.OrderBy(existingCallback => Math.Abs(callback.NextExecution.Value.Ticks - existingCallback.NextExecution.Value.Ticks))
// there might not be a callback within range
.FirstOrDefault();
// use the closest if there is one in range
if (closestCallbackInRange != null)
{
SensusServiceHelper.Get().Logger.Log("Batching callback " + callback.Id + ":" + Environment.NewLine +
"\tCurrent time: " + callback.NextExecution + Environment.NewLine +
"\tRange: " + rangeStart + " -- " + rangeEnd + Environment.NewLine +
"\tNearest: " + closestCallbackInRange.Id + Environment.NewLine +
"\tNew time: " + closestCallbackInRange.NextExecution, LoggingLevel.Normal, GetType());
callback.NextExecution = closestCallbackInRange.NextExecution;
callback.Batched = true;
}
}
}
public bool ContainsCallback(ScheduledCallback callback)
{
if (callback == null)
{
SensusException.Report("Attempted to check contains of null callback.");
return false;
}
// we should never get a null callback id, but it seems that we are from android.
else if (callback.Id == null)
{
SensusException.Report("Attempted to check contains of callback that has null id.");
return false;
}
else
{
return _idCallback.ContainsKey(callback.Id);
}
}
protected ScheduledCallback TryGetCallback(string id)
{
ScheduledCallback callback;
_idCallback.TryGetValue(id, out callback);
return callback;
}
/// <summary>
/// Raises each <see cref="ScheduledCallback"/> whose <see cref="ScheduledCallback.Id"/> matches a pattern.
/// </summary>
/// <returns>Task.</returns>
/// <param name="idPattern">Identifier pattern.</param>
public async Task RaiseCallbacksAsync(Regex idPattern)
{
foreach (ScheduledCallback callback in _idCallback.Values.Where(callback => idPattern.IsMatch(callback.Id)))
{
await RaiseCallbackAsync(callback, callback.InvocationId);
}
}
/// <summary>
/// See <see cref="RaiseCallbackAsync(ScheduledCallback, string)"/>.
/// </summary>
/// <returns>Task.</returns>
/// <param name="callbackId">Callback identifier.</param>
/// <param name="invocationId">Invocation identifier.</param>
public async Task RaiseCallbackAsync(string callbackId, string invocationId)
{
await RaiseCallbackAsync(TryGetCallback(callbackId), invocationId);
}
/// <summary>
/// Raises a <see cref="ScheduledCallback"/>. This involves initiating the <see cref="ScheduledCallback"/>, setting up cancellation timing
/// for the callback's action based on the <see cref="ScheduledCallback.Timeout"/>, and scheduling the next invocation of the
/// <see cref="ScheduledCallback"/> in the case of repeating <see cref="ScheduledCallback"/>s. See <see cref="CancelRaisedCallback(ScheduledCallback)"/>
/// for how to cancel a <see cref="ScheduledCallback"/> after it has been raised. Unlike other methods called via the app's entry points
/// (e.g., push notifications, alarms, etc.), this method does not take a <see cref="CancellationToken"/>. The reason for this is that
/// raising <see cref="ScheduledCallback"/>s is done from several locations, and cancellation is only needed due to background considerations
/// on iOS. So we've centralized background-sensitive cancellation into the iOS override of this method.
/// </summary>
/// <returns>Async task</returns>
/// <param name="callback">Callback to raise.</param>
/// <param name="invocationId">Identifier of invocation.</param>
public virtual async Task RaiseCallbackAsync(ScheduledCallback callback, string invocationId)
{
try
{
if (callback == null)
{
throw new NullReferenceException("Attemped to raise null callback.");
}
if (SensusServiceHelper.Get() == null)
{
throw new NullReferenceException("Attempted to raise callback with null service helper.");
}
// the same callback must not be run multiple times concurrently, so drop the current callback if it's already running. multiple
// callers might compete for the same callback, but only one will win the lock below and it will exclude all others until the
// the callback has finished executing. furthermore, the callback must not run multiple times in sequence (e.g., if the callback
// is raised by the local scheduling system and then later by a remote push notification). this is handled by tracking invocation
// identifiers, which are only runnable once.
string initiationError = null;
lock (callback)
{
if (callback.State != ScheduledCallbackState.Scheduled)
{
initiationError += "Callback " + callback.Id + " is not scheduled. Current state: " + callback.State;
}
if (invocationId != callback.InvocationId)
{
initiationError += (initiationError == null ? "" : ". ") + "Invocation ID provided for callback " + callback.Id + " does not match the one on record.";
}
if (initiationError == null)
{
callback.State = ScheduledCallbackState.Running;
}
}
if (initiationError == null)
{
try
{
if (callback.Canceller.IsCancellationRequested)
{
SensusServiceHelper.Get().Logger.Log("Callback " + callback.Id + " was cancelled before it was raised.", LoggingLevel.Normal, GetType());
}
else
{
SensusServiceHelper.Get().Logger.Log("Raising callback " + callback.Id + ".", LoggingLevel.Normal, GetType());
#if __ANDROID__
// on android we wouldn't have yet notified the user using the callback's message. on ios, the
// message would have already been displayed to the user if the app was in the background. on
// ios we do not display callback messages if the app is foregrounded. see the notification
// delegate for how this is done.
await SensusContext.Current.Notifier.IssueNotificationAsync("Sensus", callback.UserNotificationMessage, callback.Id, true, callback.Protocol, null, callback.NotificationUserResponseAction, callback.NotificationUserResponseMessage);
#endif
// if the callback specified a timeout, request cancellation at the specified time.
if (callback.Timeout.HasValue)
{
callback.Canceller.CancelAfter(callback.Timeout.Value);
}
await callback.ActionAsync(callback.Canceller.Token);
}
}
catch (Exception raiseException)
{
SensusException.Report("Callback " + callback.Id + " threw an exception: " + raiseException.Message, raiseException);
}
finally
{
// the cancellation token source for the current callback might have been canceled. if this is a repeating callback then we'll need a new
// cancellation token source because they cannot be reset and we're going to use the same scheduled callback again for the next repeat.
// if we enter the _idCallback lock before CancelRaisedCallback does, then the next raise will be cancelled. if CancelRaisedCallback enters the
// _idCallback lock first, then the cancellation token source will be overwritten here and the cancel will not have any effect on the next
// raise. the latter case is a reasonable outcome, since the purpose of CancelRaisedCallback is to terminate a callback that is currently in
// progress, and the current callback is no longer in progress. if the desired outcome is complete discontinuation of the repeating callback
// then UnscheduleRepeatingCallback should be used -- this method first cancels any raised callbacks and then removes the callback entirely.
try
{
if (callback.RepeatDelay.HasValue)
{
callback.Canceller = new CancellationTokenSource();
}
}
catch (Exception ex)
{
SensusException.Report("Exception while assigning new callback canceller.", ex);
}
finally
{
callback.State = ScheduledCallbackState.Completed;
// schedule callback again if it is still scheduled with a valid repeat delay
if (ContainsCallback(callback) &&
callback.RepeatDelay.HasValue &&
callback.RepeatDelay.Value.Ticks > 0)
{
callback.NextExecution = DateTime.Now + callback.RepeatDelay.Value;
callback.InvocationId = Guid.NewGuid().ToString(); // set the new invocation ID before resetting the state so that concurrent callers won't run (their invocation IDs won't match)
BatchNextExecutionWithToleratedDelay(callback);
// the state needs to be updated after batching is performed, so that other callbacks don't
// attempt to batch with it, but before the invocations are requested, so that if the invocation
// comes back immediately (e.g., being scheduled in the past) the callback is scheduled and
// ready to run.
callback.State = ScheduledCallbackState.Scheduled;
await RequestLocalInvocationAsync(callback);
#if __IOS__
await RequestRemoteInvocationAsync(callback);
#endif
}
else
{
await UnscheduleCallbackAsync(callback);
}
}
}
}
else
{
SensusServiceHelper.Get().Logger.Log("Initiation error for callback " + callback.Id + ": " + initiationError, LoggingLevel.Normal, GetType());
}
}
catch (Exception ex)
{
SensusException.Report("Exception raising callback: " + ex.Message, ex);
}
}
#if __IOS__
/// <summary>
/// Requests remote invocation for a <see cref="ScheduledCallback"/>, to be delivered in parallel with the
/// local invocation loop on iOS. Only one of these (the remote or local) will ultimately be allowed to
/// run -- whichever arrives first.
/// </summary>
/// <returns>Task.</returns>
/// <param name="callback">Callback.</param>
protected async Task RequestRemoteInvocationAsync(ScheduledCallback callback)
{
// not all callbacks are associated with a protocol (e.g., the app-level health test). because push notifications are
// currently tied to the remote data store of the protocol, we don't currently provide PNR support for such callbacks.
// on race conditions, it might be the case that the system attempts to schedule a duplicate callback. if this happens
// the duplicate will not be assigned a next execution, and the system will try to unschedule/delete it. skip such
// callbacks below.
if (callback.Protocol != null && callback.NextExecution.HasValue)
{
try
{
// the request id must differentiate the current device. furthermore, it needs to identify the
// request as one for a callback. lastly, it needs to identify the particular callback that it
// targets. the id does not include the callback invocation, as any newer requests for the
// callback should obsolete older requests.
string id = SensusServiceHelper.Get().DeviceId + "." + SENSUS_CALLBACK_KEY + "." + callback.Id;
PushNotificationUpdate update = new PushNotificationUpdate
{
Type = PushNotificationUpdateType.Callback,
Content = JObject.Parse("{" +
"\"callback-id\":" + JsonConvert.ToString(callback.Id) + "," +
"\"invocation-id\":" + JsonConvert.ToString(callback.InvocationId) +
"}")
};
PushNotificationRequest request = new PushNotificationRequest(id, SensusServiceHelper.Get().DeviceId, callback.Protocol, update, PushNotificationRequest.LocalFormat, callback.NextExecution.Value, callback.PushNotificationBackendKey);
await SensusContext.Current.Notifier.SendPushNotificationRequestAsync(request, CancellationToken.None);
}
catch (Exception ex)
{
SensusException.Report("Exception while sending push notification request for scheduled callback: " + ex.Message, ex);
}
}
}
protected async Task CancelRemoteInvocationAsync(ScheduledCallback callback)
{
await SensusContext.Current.Notifier.DeletePushNotificationRequestAsync(callback.PushNotificationBackendKey, callback.Protocol, CancellationToken.None);
}
#endif
public void TestHealth()
{
foreach (ScheduledCallback callback in _idCallback.Values)
{
// the following states should be extremely short-lived. if they are present
// then something has likely gone wrong. track the event.
if (callback.State == ScheduledCallbackState.Created ||
callback.State == ScheduledCallbackState.Completed)
{
string eventName = TrackedEvent.Warning + ":" + GetType().Name;
Dictionary<string, string> properties = new Dictionary<string, string>
{
{ "Callback State", callback.State + ":" + callback.Id }
};
Analytics.TrackEvent(eventName, properties);
}
else if (callback.State == ScheduledCallbackState.Scheduled)
{
// if the callback is scheduled and has a next execution time, check for latency.
if (callback.NextExecution.HasValue)
{
TimeSpan latency = DateTime.Now - callback.NextExecution.Value;
if (latency.TotalMinutes > 1)
{
string eventName = TrackedEvent.Warning + ":" + GetType().Name;
Dictionary<string, string> properties = new Dictionary<string, string>
{
{ "Callback Latency", latency.TotalMinutes.RoundToWhole(5) + ":" + callback.Id }
};
Analytics.TrackEvent(eventName, properties);
}
}
else
{
// report missing next execution time
string eventName = TrackedEvent.Warning + ":" + GetType().Name;
Dictionary<string, string> properties = new Dictionary<string, string>
{
{ "Callback Next Execution", "NONE" }
};
Analytics.TrackEvent(eventName, properties);
}
}
}
}
/// <summary>
/// Cancels a callback that has been raised and is currently executing.
/// </summary>
/// <param name="callback">Callback.</param>
public void CancelRaisedCallback(ScheduledCallback callback)
{
if (callback == null)
{
return;
}
callback.Canceller.Cancel();
SensusServiceHelper.Get().Logger.Log("Cancelled callback " + callback.Id + ".", LoggingLevel.Normal, GetType());
}
/// <summary>
/// Unschedules the callback, first cancelling any executions that are currently running and then removing the callback from the scheduler.
/// </summary>
/// <param name="callback">Callback.</param>
public async Task UnscheduleCallbackAsync(ScheduledCallback callback)
{
if (callback == null)
{
return;
}
SensusServiceHelper.Get().Logger.Log("Unscheduling callback " + callback.Id + ".", LoggingLevel.Normal, GetType());
// interrupt any current executions
CancelRaisedCallback(callback);
// remove from the scheduler
_idCallback.TryRemove(callback.Id, out ScheduledCallback removedCallback);
CancelLocalInvocation(callback);
#if __IOS__
await CancelRemoteInvocationAsync(callback);
#else
await Task.CompletedTask;
#endif
SensusServiceHelper.Get().Logger.Log("Unscheduled callback " + callback.Id + ".", LoggingLevel.Normal, GetType());
}
/// <summary>
/// Unschedules the callback.
/// </summary>
/// <returns>Task.</returns>
/// <param name="id">Identifier.</param>
public async Task UnscheduleCallbackAsync(string id)
{
ScheduledCallback callback = TryGetCallback(id);
if (callback != null)
{
await UnscheduleCallbackAsync(callback);
}
}
/// <summary>
/// Unschedules each <see cref="ScheduledCallback"/> whose <see cref="ScheduledCallback.Id"/> matches a pattern.
/// </summary>
/// <returns>Task.</returns>
/// <param name="idPattern">Identifier pattern.</param>
public async Task UnscheduleCallbacksAsync(Regex idPattern)
{
foreach (ScheduledCallback callback in _idCallback.Values.Where(callback => idPattern.IsMatch(callback.Id)))
{
await UnscheduleCallbackAsync(callback);
}
}
}
} | 52.932136 | 327 | 0.561183 | [
"Apache-2.0"
] | TeachmanLab/sensus | Sensus.Shared/Callbacks/CallbackScheduler.cs | 26,521 | C# |
//
// Copyright 2021 Google LLC
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Google.Solutions.IapDesktop.Application.Services.ProjectModel
{
public class ProjectAddedEvent
{
public string ProjectId { get; }
public ProjectAddedEvent(string projectId)
{
this.ProjectId = projectId;
}
}
public class ProjectDeletedEvent
{
public string ProjectId { get; }
public ProjectDeletedEvent(string projectId)
{
this.ProjectId = projectId;
}
}
public class ActiveProjectChangedEvent
{
public IProjectModelNode ActiveNode { get; }
internal ActiveProjectChangedEvent(IProjectModelNode activeNode)
{
this.ActiveNode = activeNode;
}
}
}
| 28.1 | 72 | 0.69573 | [
"Apache-2.0"
] | Bhisma19/iap-desktop | sources/Google.Solutions.IapDesktop.Application/Services/ProjectModel/ProjectModelEvents.cs | 1,688 | C# |
using System.Collections.Concurrent;
namespace System.Runtime.Remoting.Messaging;
/// <summary>
/// CallContext for .NET Standard and .NET Core
/// for more info: http://www.cazzulino.com/callcontext-netstandard-netcore.html
/// </summary>
public static class CallContext
{
private static readonly ConcurrentDictionary<string, AsyncLocal<object>> State;
static CallContext()
{
State = new ConcurrentDictionary<string, AsyncLocal<object>>();
}
#pragma warning disable CS8601
/// <summary>
/// Set data
/// </summary>
/// <param name="name"></param>
/// <param name="data"></param>
public static void SetData(string name, object data) =>
State.GetOrAdd(name, _ => new AsyncLocal<object>()).Value = data;
#pragma warning restore CS8601
/// <summary>
/// Get data
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public static object GetData(string name) =>
State.TryGetValue(name, out var data) ? data.Value : null;
} | 27.864865 | 83 | 0.654704 | [
"Apache-2.0"
] | cosmos-loops/Cosmos.Standard | src/Cosmos.Extensions.Asyncs/System/Runtime/Remoting/Messaging/CallContext.cs | 1,031 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using AspNetCoreTemplate.Data.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace AspNetCoreTemplate.Web.Areas.Identity.Pages.Account.Manage
{
public class SetPasswordModel : PageModel
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
public SetPasswordModel(
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager)
{
_userManager = userManager;
_signInManager = signInManager;
}
[BindProperty]
public InputModel Input { get; set; }
[TempData]
public string StatusMessage { get; set; }
public class InputModel
{
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "New password")]
public string NewPassword { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm new password")]
[Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
public async Task<IActionResult> OnGetAsync()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
var hasPassword = await _userManager.HasPasswordAsync(user);
if (hasPassword)
{
return RedirectToPage("./ChangePassword");
}
return Page();
}
public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
{
return Page();
}
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
var addPasswordResult = await _userManager.AddPasswordAsync(user, Input.NewPassword);
if (!addPasswordResult.Succeeded)
{
foreach (var error in addPasswordResult.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
return Page();
}
await _signInManager.RefreshSignInAsync(user);
StatusMessage = "Your password has been set.";
return RedirectToPage();
}
}
}
| 32.010638 | 129 | 0.586906 | [
"MIT"
] | mirakis97/OnlineCosmeticSalon | OnlineCosmeticSalon.Web/Web/AspNetCoreTemplate.Web/Areas/Identity/Pages/Account/Manage/SetPassword.cshtml.cs | 3,011 | C# |
using System;
using ImageProcessing.App.DomainLayer.Code.Enums;
using ImageProcessing.App.DomainLayer.DomainFactory.ColorMatrix.Interface;
using ImageProcessing.App.DomainLayer.DomainModel.ColorMatrix.Implementation;
using ImageProcessing.App.DomainLayer.DomainModel.ColorMatrix.Interface;
namespace ImageProcessing.App.DomainLayer.DomainFactory.ColorMatrix.Implementation
{
public sealed class ColorMatrixFactory : IColorMatrixFactory
{
public IColorMatrix Get(ClrMatrix matrix)
=> matrix
switch
{
ClrMatrix.Grayscale240M
=> new GrayscaleSmpte240MColorMatrix(),
ClrMatrix.Grayscale601
=> new GrayscaleRec601ColorMatrix(),
ClrMatrix.Grayscale709
=> new GrayscaleRec709ColorMatrix(),
ClrMatrix.Identity
=> new IdentityColorMatrix(),
ClrMatrix.Inverse
=> new InversionColorMatrix(),
ClrMatrix.SepiaTone
=> new SepiaToneColorMatrix(),
ClrMatrix.RgbToYiq
=> new RgbToYiqColorMatrix(),
ClrMatrix.YiqToRgb
=> new YiqToRgbColorMatrix(),
ClrMatrix.XyzToRgb
=> new XyzEToRgbColorMatrix(),
ClrMatrix.RgbToXyz
=> new RgbToXyzEColorMatrix(),
ClrMatrix.PolaroidTone
=> new PolaroidToneColorMatrix(),
ClrMatrix.Unknown
=> new UnknownColorMatrix(),
_ => throw new NotImplementedException(nameof(matrix))
};
}
}
| 36.266667 | 82 | 0.608456 | [
"Apache-2.0"
] | Softenraged/Image-Processing | Source/ImageProcessing.App.DomainLayer/DomainFactory/ColorMatrix/Implementation/ColorMatrixFactory.cs | 1,632 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using NUnit.Framework;
using Shouldly;
using Stackage.Core.Abstractions.Metrics;
namespace Stackage.Core.Tests.DefaultMiddleware.RateLimiting
{
public class rate_limited_request : middleware_scenario
{
private HttpResponseMessage _fooResponse;
private HttpResponseMessage _barResponse;
private string _fooContent;
private string _barContent;
[OneTimeSetUp]
public async Task setup_scenario()
{
using (var server = TestService.CreateServer())
{
var foo = TestService.GetAsync(server, "/foo");
await Task.Delay(1);
var bar = TestService.GetAsync(server, "/bar");
await Task.WhenAll(foo, bar);
_fooResponse = foo.Result;
_barResponse = bar.Result;
_fooContent = await _fooResponse.Content.ReadAsStringAsync();
_barContent = await _barResponse.Content.ReadAsStringAsync();
}
}
protected override void ConfigureConfiguration(IConfigurationBuilder configurationBuilder)
{
base.ConfigureConfiguration(configurationBuilder);
configurationBuilder.AddInMemoryCollection(new Dictionary<string, string>
{
{"STACKAGE:RATELIMITING:ENABLED", "true"},
{"STACKAGE:RATELIMITING:REQUESTSPERPERIOD", "1"},
{"STACKAGE:RATELIMITING:PERIODSECONDS", "1"},
{"STACKAGE:RATELIMITING:BURSTSIZE", "1"},
{"STACKAGE:RATELIMITING:MAXWAITMS", "10"}
});
}
protected override void Configure(IApplicationBuilder app)
{
base.Configure(app);
app.UseMiddleware<StubResponseMiddleware>(new StubResponseOptions(HttpStatusCode.OK, "content") {Latency = TimeSpan.FromMilliseconds(50)});
}
[Test]
public void foo_request_should_return_200()
{
_fooResponse.StatusCode.ShouldBe(HttpStatusCode.OK);
}
[Test]
public void bar_request_should_return_429()
{
_barResponse.StatusCode.ShouldBe((HttpStatusCode) 429);
}
[Test]
public void foo_request_should_return_content()
{
_fooContent.ShouldBe("content");
}
[Test]
public void bar_request_should_return_json_error_content()
{
_barContent.ShouldBe("{\"message\":\"Too Many Requests\"}");
}
[Test]
public void should_return_content_type_json()
{
_barResponse.Content.Headers.ContentType.MediaType.ShouldBe("application/json");
}
[Test]
public void should_not_log_a_message()
{
Logger.Entries.Count.ShouldBe(0);
}
[Test]
public void should_write_four_metrics()
{
Assert.That(MetricSink.Metrics.Count, Is.EqualTo(4));
}
[Test]
public void should_write_foo_start_metric()
{
MetricSink.Metrics.Count(x => x.Name == "http_request_start" && (string) x.Dimensions["path"] == "/foo").ShouldBe(1);
}
[Test]
public void should_write_bar_start_metric()
{
MetricSink.Metrics.Count(x => x.Name == "http_request_start" && (string) x.Dimensions["path"] == "/bar").ShouldBe(1);
}
[Test]
public void should_write_foo_end_metric()
{
var metric = (Gauge) MetricSink.Metrics.Single(x => x.Name == "http_request_end" && (string) x.Dimensions["path"] == "/foo");
Assert.That(metric.Dimensions["method"], Is.EqualTo("GET"));
Assert.That(metric.Dimensions["statusCode"], Is.EqualTo(200));
}
[Test]
public void should_write_bar_end_metric()
{
var metric = (Gauge) MetricSink.Metrics.Single(x => x.Name == "http_request_end" && (string) x.Dimensions["path"] == "/bar");
Assert.That(metric.Dimensions["method"], Is.EqualTo("GET"));
Assert.That(metric.Dimensions["statusCode"], Is.EqualTo(429));
}
}
}
| 30.651852 | 148 | 0.637264 | [
"MIT"
] | concilify/stackage-core-nuget | package/Stackage.Core.Tests/DefaultMiddleware/RateLimiting/rate_limited_request.cs | 4,138 | C# |
using Suls.ViewModels.Submissions;
namespace Suls.Services.Submissions
{
public interface ISubmissionsService
{
public void CreateSubmission(string problemId, string userId, SubmissionInputModel model);
void DeleteSubmission(string submissionId);
}
}
| 23.5 | 98 | 0.751773 | [
"MIT"
] | GeorgiGradev/C-Web | 01. C# Web Basics/11. Exams/01. Suls/MySolution/Suls/Services/Submissions/ISubmissionsService.cs | 284 | C# |
using System.Collections.Generic;
using Essensoft.AspNetCore.Payment.Alipay.Response;
namespace Essensoft.AspNetCore.Payment.Alipay.Request
{
/// <summary>
/// koubei.servindustry.reservation.payshop.identify
/// </summary>
public class KoubeiServindustryReservationPayshopIdentifyRequest : IAlipayRequest<KoubeiServindustryReservationPayshopIdentifyResponse>
{
/// <summary>
/// 判断是否旺铺
/// </summary>
public string BizContent { get; set; }
#region IAlipayRequest Members
private bool needEncrypt = false;
private string apiVersion = "1.0";
private string terminalType;
private string terminalInfo;
private string prodCode;
private string notifyUrl;
private string returnUrl;
private AlipayObject bizModel;
public void SetNeedEncrypt(bool needEncrypt)
{
this.needEncrypt = needEncrypt;
}
public bool GetNeedEncrypt()
{
return needEncrypt;
}
public void SetNotifyUrl(string notifyUrl)
{
this.notifyUrl = notifyUrl;
}
public string GetNotifyUrl()
{
return notifyUrl;
}
public void SetReturnUrl(string returnUrl)
{
this.returnUrl = returnUrl;
}
public string GetReturnUrl()
{
return returnUrl;
}
public void SetTerminalType(string terminalType)
{
this.terminalType = terminalType;
}
public string GetTerminalType()
{
return terminalType;
}
public void SetTerminalInfo(string terminalInfo)
{
this.terminalInfo = terminalInfo;
}
public string GetTerminalInfo()
{
return terminalInfo;
}
public void SetProdCode(string prodCode)
{
this.prodCode = prodCode;
}
public string GetProdCode()
{
return prodCode;
}
public string GetApiName()
{
return "koubei.servindustry.reservation.payshop.identify";
}
public void SetApiVersion(string apiVersion)
{
this.apiVersion = apiVersion;
}
public string GetApiVersion()
{
return apiVersion;
}
public IDictionary<string, string> GetParameters()
{
var parameters = new AlipayDictionary
{
{ "biz_content", BizContent }
};
return parameters;
}
public AlipayObject GetBizModel()
{
return bizModel;
}
public void SetBizModel(AlipayObject bizModel)
{
this.bizModel = bizModel;
}
#endregion
}
}
| 23.193548 | 139 | 0.557371 | [
"MIT"
] | lzw316/payment | src/Essensoft.AspNetCore.Payment.Alipay/Request/KoubeiServindustryReservationPayshopIdentifyRequest.cs | 2,890 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// Este código foi gerado por uma ferramenta.
// Versão de Tempo de Execução: 4.0.30319.42000
//
// As alterações ao arquivo poderão causar comportamento incorreto e serão perdidas se
// o código for recriado
// </auto-generated>
//------------------------------------------------------------------------------
namespace ControleEstoqueComEF6.Properties
{
/// <summary>
/// Uma classe de recurso fortemente tipados, para pesquisar cadeias de caracteres localizadas etc.
/// </summary>
// Esta classe foi gerada automaticamente pela StronglyTypedResourceBuilder
// classe através de uma ferramenta como ResGen ou Visual Studio.
// Para adicionar ou remover um associado, edite o arquivo .ResX e execute ResGen novamente
// com a opção /str ou reconstrua seu projeto VS.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources
{
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources()
{
}
/// <summary>
/// Retorna a instância cacheada de ResourceManager utilizada por esta classe.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager
{
get
{
if ((resourceMan == null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("ControleEstoqueComEF6.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Substitui a propriedade CurrentUICulture do thread atual para todas
/// as pesquisas de recursos que usam esta classe de recursos fortemente tipados.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture
{
get
{
return resourceCulture;
}
set
{
resourceCulture = value;
}
}
}
}
| 41.267606 | 187 | 0.62116 | [
"CC0-1.0"
] | Luscas-PandC/Entra21-NoturnoLucas-Forms | ControleEstoqueComEF6/Properties/Resources.Designer.cs | 2,945 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
internal partial class Interop
{
internal static class IID
{
// 0000000C-0000-0000-C000-000000000046
internal static Guid IStream = new Guid(0x0000000C, 0x0000, 0x0000, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46);
// 00000109-0000-0000-C000-000000000046
internal static Guid IPersistStream = new Guid(0x00000109, 0x0000, 0x0000, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46);
// 7BF80980-BF32-101A-8BBB-00AA00300CAB
internal static Guid IPicture = new Guid(0x7BF80980, 0xBF32, 0x101A, 0x8B, 0xBB, 0x00, 0xAA, 0x00, 0x30, 0x0C, 0xAB);
}
}
| 39.285714 | 131 | 0.700606 | [
"MIT"
] | kant2002/winforms | src/System.Windows.Forms.Primitives/src/Interop/Interop.IID.cs | 825 | C# |
using System;
namespace Primelabs.Twingly.KestrelApi.Exceptions
{
public class KestrelApiException : ApplicationException
{
public KestrelApiException(string message) : base(message) {}
public KestrelApiException(string message, Exception innerException) : base(message, innerException) {}
}
} | 32.2 | 111 | 0.748447 | [
"MIT"
] | twingly/KestrelApi | KestrelApi/Exceptions/KestrelApiException.cs | 322 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
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 Windows.Globalization;
// The User Control item template is documented at http://go.microsoft.com/fwlink/?LinkId=234236
namespace SDKTemplate
{
public sealed partial class LanguageOverride : UserControl
{
List<ComboBoxValue> comboBoxValues;
int lastSelectionIndex;
public delegate void LanguageOverrideChangedEventHandler(object sender, EventArgs e);
public event LanguageOverrideChangedEventHandler LanguageOverrideChanged;
public LanguageOverride()
{
this.InitializeComponent();
Loaded += Control_Loaded;
}
void Control_Loaded(object sender, RoutedEventArgs e)
{
comboBoxValues = new List<ComboBoxValue>();
// First show the default setting
comboBoxValues.Add(new ComboBoxValue() { DisplayName = "Use language preferences (recommended)", LanguageTag = "" });
// If there are app languages that the user speaks, show them next
// Note: the first (non-override) language, if set as the primary language override
// would give the same result as not having any primary language override. There's
// still a difference, though: If the user changes their language preferences, the
// default setting (no override) would mean that the actual primary app language
// could change. But if it's set as an override, then it will remain the primary
// app language after the user changes their language preferences.
for (var i = 0; i < ApplicationLanguages.Languages.Count; i++)
{
this.LanguageOverrideComboBox_AddLanguage(new Windows.Globalization.Language(ApplicationLanguages.Languages[i]));
}
// Now add a divider followed by all the app manifest languages (in case the user
// wants to pick a language not currently in their profile)
// NOTE: If an app is deployed using a bundle with resource packages, the following
// addition to the list may not be useful: The set of languages returned by
// ApplicationLanguages.ManifestLanguages will consist of only those manifest
// languages in the main app package or in the resource packages that are installed
// and registered for the current user. Language resource packages get deployed for
// the user if the language is in the user's profile. Therefore, the only difference
// from the set returned by ApplicationLanguages.Languages above would depend on
// which languages are included in the main app package.
comboBoxValues.Add(new ComboBoxValue() { DisplayName = "——————", LanguageTag = "-" });
// Create a List and sort it before adding items
List<Windows.Globalization.Language> manifestLanguageObjects = new List<Windows.Globalization.Language>();
foreach (var lang in ApplicationLanguages.ManifestLanguages)
{
manifestLanguageObjects.Add(new Windows.Globalization.Language(lang));
}
IEnumerable<Windows.Globalization.Language> orderedManifestLanguageObjects = manifestLanguageObjects.OrderBy(lang => lang.DisplayName);
foreach (var lang in orderedManifestLanguageObjects)
{
this.LanguageOverrideComboBox_AddLanguage(lang);
}
LanguageOverrideComboBox.ItemsSource = comboBoxValues;
LanguageOverrideComboBox.SelectedIndex = comboBoxValues.FindIndex(FindCurrent);
LanguageOverrideComboBox.SelectionChanged += LanguageOverrideComboBox_SelectionChanged;
lastSelectionIndex = LanguageOverrideComboBox.SelectedIndex;
}
private void LanguageOverrideComboBox_AddLanguage(Windows.Globalization.Language lang)
{
comboBoxValues.Add(new ComboBoxValue() { DisplayName = lang.NativeName, LanguageTag = lang.LanguageTag });
}
private static bool FindCurrent(ComboBoxValue value)
{
if (value.LanguageTag == Windows.Globalization.ApplicationLanguages.PrimaryLanguageOverride)
{
return true;
}
return false;
}
private void LanguageOverrideComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ComboBox combo = sender as ComboBox;
// Don't accept the list item for the divider (tag = "-")
if (combo.SelectedValue.ToString() == "-")
{
combo.SelectedIndex = lastSelectionIndex;
}
else
{
lastSelectionIndex = combo.SelectedIndex;
// Set the persistent application language override
Windows.Globalization.ApplicationLanguages.PrimaryLanguageOverride = combo.SelectedValue.ToString();
if (LanguageOverrideChanged != null) LanguageOverrideChanged(this, new EventArgs());
}
}
}
public class ComboBoxValue
{
public string DisplayName { get; set; }
public string LanguageTag { get; set; }
}
}
| 43.421053 | 148 | 0.643636 | [
"MIT"
] | CrZGerry/Windows-universal-samples | Samples/ApplicationResources/cs/languageoverride.xaml.cs | 5,657 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace AspNetCore.Controllers
{
public class ValuesController
{
public static readonly string ServerResponse = "Hello World!";
[HttpGet("/")]
public string Hello() => ServerResponse;
// GET api/values
[HttpGet("/api/values")]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/values/5
[HttpGet("/api/values/{id}")]
public string Get(int id)
{
return "value is " + id;
}
}
}
| 25.628571 | 71 | 0.618729 | [
"MIT"
] | LuisRGameloft/corert | tests/src/Functional/AspNetCore/Controllers/ValuesController.cs | 899 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
namespace Avalon.Utils
{
public class ProcessKiller
{
public static void KillProcessByName(string processName)
{
Process[] processes = Process.GetProcessesByName(processName);
if (processes != null)
{
foreach (Process process in processes)
{
try
{
process.Kill();
}
catch { }
}
}
}
}
}
| 23.678571 | 75 | 0.458522 | [
"Unlicense"
] | Canaan-Creative/Avalon-nano | gui_1.0/AvalonDevice/ProcessKiller.cs | 665 | C# |
using DesignPatterns.Structural.Flyweights;
using FluentAssertions;
using Xunit;
namespace DesignPatterns.Tests.Structural.Flyweights
{
public class CompanyInformationTests
{
[Fact]
public void CompanyInformationShouldNotHaveMultipleAllocations()
{
var companyInfo1 = CompanyInformationFactory.Company;
var companyInfo2 = CompanyInformationFactory.Company;
companyInfo1.Should().BeSameAs(companyInfo2);
companyInfo1.WebSite.Should().BeSameAs(companyInfo2.WebSite);
companyInfo1.Name.Should().BeSameAs(companyInfo2.Name);
}
}
} | 31.65 | 73 | 0.704581 | [
"MIT"
] | luizmotta01/dotnet-design-patterns | tests/DesignPatterns.Tests/Structural/Flyweights/CompanyInformationTests.cs | 635 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MapEditor.UI.Core.Transitions {
public class ManagedType_Byte :IManagedType {
#region IManagedType Members
/// <summary>
/// Returns the type we are managing.
/// </summary>
public Type getManagedType() {
return typeof (byte);
}
/// <summary>
/// Returns a copy of the byte passed in.
/// </summary>
public object copy(object o) {
byte value = (byte) o;
return value;
}
/// <summary>
/// Returns the value between the start and end for the percentage passed in.
/// </summary>
public object getIntermediateValue(object start, object end, double dPercentage) {
byte iStart = (byte) start;
byte iEnd = (byte) end;
return Utility.interpolate(iStart, iEnd, dPercentage);
}
#endregion
}
} | 23.486486 | 84 | 0.686997 | [
"MIT"
] | oxysoft/PokeSharp | src/MapEditor.UI/Core/Transitions/ManagedType_Byte.cs | 871 | C# |
// Copyright 2016 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using GoogleCloudExtension.Analytics;
using GoogleCloudExtension.Utils;
using System.Diagnostics;
using System.Windows.Input;
namespace GoogleCloudExtension.MySQLInstaller
{
/// <summary>
/// This class is the view model for the <seealso cref="MySQLInstallerWindow"/> dialog.
/// </summary>
internal class MySQLInstallerViewModel : ViewModelBase
{
private readonly MySQLInstallerWindow _owner;
/// <summary>
/// The command to execute when the Download button is pressed.
/// </summary>
public ICommand DownloadCommand { get; }
public MySQLInstallerViewModel(MySQLInstallerWindow owner)
{
_owner = owner;
DownloadCommand = new WeakCommand(OpenDownload);
}
private void OpenDownload()
{
ExtensionAnalytics.ReportCommand(CommandName.OpenMySQLInstallerDownload, CommandInvocationSource.Button);
var url = $"https://dev.mysql.com/downloads/installer/";
Debug.WriteLine($"Opening page to download MySQL Installer: {url}");
Process.Start(url);
_owner.Close();
}
}
}
| 34.096154 | 117 | 0.685843 | [
"Apache-2.0"
] | david0718/google-cloud-visualstudio | GoogleCloudExtension/GoogleCloudExtension/MySQLInstaller/MySQLInstallerViewModel.cs | 1,775 | C# |
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Web;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using Microsoft.Owin.Security;
using ConctWeb.Models;
namespace ConctWeb
{
public class EmailService : IIdentityMessageService
{
public Task SendAsync(IdentityMessage message)
{
// Plug in your email service here to send an email.
return Task.FromResult(0);
}
}
public class SmsService : IIdentityMessageService
{
public Task SendAsync(IdentityMessage message)
{
// Plug in your SMS service here to send a text message.
return Task.FromResult(0);
}
}
// Configure the application user manager used in this application. UserManager is defined in ASP.NET Identity and is used by the application.
public class ApplicationUserManager : UserManager<ApplicationUser>
{
public ApplicationUserManager(IUserStore<ApplicationUser> store)
: base(store)
{
}
public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
{
var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()));
// Configure validation logic for usernames
manager.UserValidator = new UserValidator<ApplicationUser>(manager)
{
AllowOnlyAlphanumericUserNames = false,
RequireUniqueEmail = true
};
// Configure validation logic for passwords
manager.PasswordValidator = new PasswordValidator
{
RequiredLength = 6,
RequireNonLetterOrDigit = true,
RequireDigit = true,
RequireLowercase = true,
RequireUppercase = true,
};
// Configure user lockout defaults
manager.UserLockoutEnabledByDefault = true;
manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
manager.MaxFailedAccessAttemptsBeforeLockout = 5;
// Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
// You can write your own provider and plug it in here.
manager.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider<ApplicationUser>
{
MessageFormat = "Your security code is {0}"
});
manager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider<ApplicationUser>
{
Subject = "Security Code",
BodyFormat = "Your security code is {0}"
});
manager.EmailService = new EmailService();
manager.SmsService = new SmsService();
var dataProtectionProvider = options.DataProtectionProvider;
if (dataProtectionProvider != null)
{
manager.UserTokenProvider =
new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
}
return manager;
}
}
// Configure the application sign-in manager which is used in this application.
public class ApplicationSignInManager : SignInManager<ApplicationUser, string>
{
public ApplicationSignInManager(ApplicationUserManager userManager, IAuthenticationManager authenticationManager)
: base(userManager, authenticationManager)
{
}
public override Task<ClaimsIdentity> CreateUserIdentityAsync(ApplicationUser user)
{
return user.GenerateUserIdentityAsync((ApplicationUserManager)UserManager);
}
public static ApplicationSignInManager Create(IdentityFactoryOptions<ApplicationSignInManager> options, IOwinContext context)
{
return new ApplicationSignInManager(context.GetUserManager<ApplicationUserManager>(), context.Authentication);
}
}
}
| 39.290909 | 152 | 0.659417 | [
"MIT"
] | nlainez/ContactWeb | ConctWeb/App_Start/IdentityConfig.cs | 4,324 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using Microsoft.Identity.Client.Cache.Items;
using Microsoft.Identity.Client.OAuth2;
namespace Microsoft.Identity.Client.AuthScheme.SSHCertificates
{
internal class SSHCertAuthenticationScheme : IAuthenticationScheme
{
internal const string SSHCertTokenType = "ssh-cert";
private readonly string _jwk;
public SSHCertAuthenticationScheme(string keyId, string jwk)
{
if (string.IsNullOrEmpty(keyId))
{
throw new ArgumentNullException(nameof(keyId));
}
if (string.IsNullOrEmpty(jwk))
{
throw new ArgumentNullException(nameof(jwk));
}
KeyId = keyId;
_jwk = jwk;
}
public string AuthorizationHeaderPrefix =>
throw new MsalClientException(
MsalError.SSHCertUsedAsHttpHeader,
MsalErrorMessage.SSHCertUsedAsHttpHeader);
public string AccessTokenType => SSHCertTokenType;
public string KeyId { get; }
public string FormatAccessToken(MsalAccessTokenCacheItem msalAccessTokenCacheItem)
{
return msalAccessTokenCacheItem.Secret;
}
public IDictionary<string, string> GetTokenRequestParams()
{
return new Dictionary<string, string>()
{
{ OAuth2Parameter.TokenType, SSHCertTokenType },
{ OAuth2Parameter.RequestConfirmation , _jwk }
};
}
}
}
| 30.127273 | 90 | 0.626433 | [
"MIT"
] | pavel-petrenko/microsoft-authentication-library-for-dotnet | src/client/Microsoft.Identity.Client/AuthScheme/SSHCertificates/SSHCertAuthenticationScheme.cs | 1,659 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Avalonia;
using Avalonia.Styling;
using FFXIVAPP.Client.Properties;
namespace FFXIVAPP.Client.Themes
{
public static class ThemeManager
{
public static List<ThemeItem> AvailableThemes => new List<ThemeItem>
{
Default,
new ThemeItem("Red|Light", () => new Themes.RedLight()),
};
public static ThemeItem Default => new ThemeItem("Blue|Light", () => new Themes.BlueLight());
private static string _currentTheme = null;
public static void SetTheme(string themeName)
{
if (themeName != null && themeName == _currentTheme)
return;
Action<Styles> setter;
if (Application.Current.Styles.Count == 0)
setter = (s) => Application.Current.Styles.Add(s);
else
setter = (s) => Application.Current.Styles[0] = s;
var theme = AvailableThemes.FirstOrDefault(t => t.Name == themeName);
if (theme == null)
{
theme = AvailableThemes.Single(t => t.Name == "Blue|Light");
Settings.Default.Theme = theme.Name;
}
setter(theme.Theme());
}
}
public class ThemeItem
{
public string Name { get; set; }
public Func<Styles> Theme { get; set; }
public ThemeItem(string name, Func<Styles> theme)
{
Name = name;
Theme = theme;
}
}
} | 28.740741 | 101 | 0.552835 | [
"MIT"
] | teast/ffxivapp | FFXIVAPP.Client/Themes/ThemeManager.cs | 1,552 | 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.Linq;
using System.Xml.Linq;
using Microsoft.AspNetCore.DataProtection.XmlEncryption;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace CustomEncryptorSample;
public class CustomXmlDecryptor : IXmlDecryptor
{
private readonly ILogger _logger;
public CustomXmlDecryptor(IServiceProvider services)
{
_logger = services.GetRequiredService<ILoggerFactory>().CreateLogger<CustomXmlDecryptor>();
}
public XElement Decrypt(XElement encryptedElement)
{
if (encryptedElement == null)
{
throw new ArgumentNullException(nameof(encryptedElement));
}
return new XElement(encryptedElement.Elements().Single());
}
}
| 28 | 99 | 0.742188 | [
"MIT"
] | AndrewTriesToCode/aspnetcore | src/DataProtection/samples/CustomEncryptorSample/CustomXmlDecryptor.cs | 898 | 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 cloudfront-2020-05-31.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.CloudFront.Model
{
/// <summary>
/// This is the response object from the TagResource operation.
/// </summary>
public partial class TagResourceResponse : AmazonWebServiceResponse
{
}
} | 30.210526 | 109 | 0.709059 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/CloudFront/Generated/Model/TagResourceResponse.cs | 1,148 | C# |
namespace BackupServiceDaemon.Backuping {
public class BackupProgress {
public int Percentage { get; set; }
public string Status { get; set; }
}
}
| 24.428571 | 43 | 0.649123 | [
"MIT"
] | VikiFandaMisa/BackupServiceDaemon | Backuping/BackupProgress.cs | 171 | C# |
using System;
using System.Linq;
using System.Reactive.Linq;
using System.Windows.Forms;
namespace WordWebService
{
public partial class TextEntryForm: Form
{
public TextEntryForm()
{
InitializeComponent();
var textChanges = Observable
.FromEventPattern(
h => edit.TextChanged += h,
h => edit.TextChanged -= h)
.Select(_ => edit.Text);
textChanges
.Throttle(TimeSpan.FromMilliseconds(500))
.DistinctUntilChanged()
.SelectLatest(WordList.FetchAsyncWithCancel)
.ObserveOn(this)
.Subscribe(LoadWords);
}
private void LoadWords(string[] items)
{
list.Items.Clear();
// ReSharper disable once CoVariantArrayConversion
list.Items.AddRange(items);
}
}
}
| 26 | 62 | 0.53953 | [
"BSD-3-Clause"
] | MiloszKrajewski/dnug-rx | src/WordWebService/TextEntryForm.cs | 938 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player2Versus : MonoBehaviour
{
public float Speed;
public float JumpForce;
public bool isJumping;//para identificar se est pulando
public float LifePlayer;
public bool isDead;
private Rigidbody2D rig;
private Animator anim;
// Vetrano Atributos
public int AtVeterano;
public float Def;
//VARIÁVEIS DE ATAQUE
public bool isAtk;
private float timeAtk;
public GameObject pointAtk;//ponto de ataque
//VARIÁVEIS DE DEFESA
public bool isDefense;
private float timeDefense;
public GameObject pointDefense;
//VARIÁVEIS DA ENERGIA
public GameObject energy;//prefabe da energia
public Transform pointPower;//ponto de energia
public float velocidadeEnergy;//velocidade da energia
public bool isPower;
//VARIÁVEIS DO ULTIMATE
public GameObject ultimate;//prefab do ultimate
public GameObject ultimateLeft;//prefab do ultimate indo para
public Transform pointUltimate;//ponto do ultimate
public float velocidadeUltimate;//velocidade do ultimate
public bool isUltimate;//verificar se esta soltando o ultimate
//VARIÁVEIS DE COMBO
public int noOfClicks = 0;//contador de hits
float lastClickedTime = 0;//ultimo ataque que o player deu
public float maxComboDelay;//maximo de delay para ir para outro ataque do combo
////
public float attackRate = 2f;
float nextAttackTime = 0f;
//VÁRIAVEIS DE SOM
public AudioSource AudioPunch;
public static bool CheckUltimate;
public static bool CheckEnergia;
public static Player2Versus current;
public GameObject transitionRound;
void Start()
{
if( (PlayerPrefs.GetInt("Veterano") != null) && (PlayerPrefs.GetInt("Veterano") != -10) )
{
AtVeterano = PlayerPrefs.GetInt("Veterano");
Debug.Log(AtVeterano);
}
else
{
AtVeterano = EscolhaVet.vet;
}
rig = GetComponent<Rigidbody2D>();
anim = GetComponent<Animator>();
current = this;
if (AtVeterano == 0)
{
Def = 0.2f * 3;
Speed = Speed * 1;
}
if (AtVeterano == 1)
{
Def = 0.2f * 2;
Speed = Speed * 1;
}
if (AtVeterano == 2)
{
Def = 0.2f * 2;
Speed = Speed * 1.6f;
}
}
void Update()
{
if((!isDead) && (!PlayerVersus.current.isDead) && (Time.timeScale == 1) )
{
if((Input.GetKey(KeyCode.D)) && (!isDefense) && (isAtk == false) && (ControlVersus.current.canPlay == true) && (!isPower) && (!PlayerVersus.current.isDead) && (PlayerVersus.current.GetComponent<PlayerVersus>().enabled) )
{
rig.velocity = new Vector2(Speed * Time.deltaTime, rig.velocity.y);
anim.SetBool("isWalking", true);
transform.localEulerAngles = new Vector3(0, 0, 0);//rotacionado para a direita
}
else
{
rig.velocity = new Vector2(0f, rig.velocity.y);
anim.SetBool("isWalking", false);
}
if( (Input.GetKey(KeyCode.A)) && (!isDefense) && (isAtk == false) && (ControlVersus.current.canPlay == true) && (!isPower) && (!PlayerVersus.current.isDead) && (PlayerVersus.current.GetComponent<PlayerVersus>().enabled) )
{
rig.velocity = new Vector2(-Speed * Time.deltaTime, rig.velocity.y);
anim.SetBool("isWalking", true);
transform.localEulerAngles = new Vector3(0, 180, 0);//rotacionado para a esquerda
}
/*PULO*/
if((Input.GetKeyDown(KeyCode.Space)) && (!isJumping))
{
rig.AddForce(Vector2.up * JumpForce, ForceMode2D.Impulse);
anim.SetBool("isJumping", true);
isJumping = true;
}
/*ATAQUE - COMBO*/
if(Time.time - lastClickedTime > maxComboDelay)//verificando se ultrapassou o tempo para dar outro ataque do combo, para não continuar o combo
{
noOfClicks = 0;
anim.SetBool("isAtk", false);
}
if(Time.time >= nextAttackTime)
{
if(Input.GetKeyDown(KeyCode.M) && (PlayerVersus2.current.GetComponent<Rigidbody2D>().bodyType == RigidbodyType2D.Dynamic) )
{
//AudioPunch.Play();
anim.SetBool("isJumping", false);//para poder dar golpe no ar
//verifica se clicou
lastClickedTime = Time.time;
noOfClicks++;
if(noOfClicks == 1)
{
anim.SetBool("isAtk", true);
isAtk = true;
}
noOfClicks = Mathf.Clamp(noOfClicks, 0, 3); //numero absoluto de cliques/ataques do combo entre 0 e 3
nextAttackTime = Time.time + 0.5f / attackRate;
}
}
/*DEFESA*/
if((Input.GetKeyDown(KeyCode.S)) && (!isDefense))
{
anim.SetBool("isDefense", true);
//anim.SetBool("isJumping", false);
isDefense = true;
timeDefense = 2f;//duração da defesa
pointDefense.SetActive(isDefense);
}
timeDefense -= Time.deltaTime;
if((timeDefense <= 0) || (Input.GetKeyUp(KeyCode.S)) )
{
isDefense = false;
anim.SetBool("isDefense", isDefense);
pointDefense.SetActive(isDefense);
}
/*SOLTAR ENERGIA*/
if ((Input.GetKeyDown(KeyCode.Q)) && (!isJumping) && ((BarraEnergy.current.Energy >= BarraEnergy.current.gastoEnergy) || (BarraEnergy.current.Energ >= 20f)) )
{
anim.SetBool("isPower", true);
isPower = true;
//SoltarEnergia();
}
/*SOLTAR ULTIMATE*/
if ((Input.GetKeyDown(KeyCode.E)) && (!isJumping) && (BarraEnergy.current.Energ >= 60f) )
{
if(transform.localEulerAngles.y == 0)
{
anim.SetBool("isUltimate", true);
}
else
{
anim.SetBool("isUltimateLeft", true);
}
//SoltarUltimate();
}
}
else
{
anim.SetBool("isWalking", false);
}
}
//SOLTAR ENERGIA
public void SoltarEnergia()
{
CheckEnergia = true;
GameObject energytile = Instantiate(energy, pointPower.position, transform.rotation);//criando energia no ponto deinido
//calculo direção do player
if(transform.eulerAngles.y == 180)//esta para a esquerda
{
energytile.GetComponent<Rigidbody2D>().velocity = new Vector2(-velocidadeEnergy, 0);
}
else
{
energytile.GetComponent<Rigidbody2D>().velocity = new Vector2(velocidadeEnergy, 0);
}
anim.SetBool("isPower", false);
isPower = false;
}
//SOLTAR ULTIMATE
public void SoltarUltimate()
{
CheckUltimate = true;
if(transform.eulerAngles.y == 180)//esa para a esquerda
{
GameObject ultimatetile = Instantiate(ultimateLeft, pointUltimate.position, transform.rotation);
//ultimatetile.GetComponent<SpriteRenderer>().flipX = true;
ultimatetile.GetComponent<Rigidbody2D>().velocity = new Vector2(-velocidadeUltimate, 0);
anim.SetBool("isUltimateLeft", false);
}
if(transform.eulerAngles.y == 0) //para direita
{
GameObject ultimatetile = Instantiate(ultimate, pointUltimate.position, transform.rotation);
ultimatetile.GetComponent<Rigidbody2D>().velocity = new Vector2(velocidadeUltimate, 0);
anim.SetBool("isUltimate", false);
}
}
//verifica se clicou mais de umas no ataque, para mandar outro hit do combo
public void return1()
{
if(noOfClicks >= 1)
{
anim.SetBool("isAtk2", true);
anim.SetBool("isAtk", false);
}
else
{
anim.SetBool("isAtk", false);//desativa o o primerio hit pois não clicou para continuar
noOfClicks = 0;
isAtk = false;
}
}
public void return2()
{
if(noOfClicks >= 2)
{
anim.SetBool("isAtk3", true);
}
else
{
anim.SetBool("isAtk2", false);//desativa o segundo hit pois não clicou para continuar
//anim.SetBool("isAtk", false);
noOfClicks = 0;
isAtk = false;
}
}
public void return3()
{
//desativa todos se não clicar por muito tempo
// anim.SetBool("isAtk", false);
anim.SetBool("isAtk2", false);
anim.SetBool("isAtk3", false);
noOfClicks = 0;
isAtk = false;
}
//DESATIVANDO PULO
private void OnCollisionEnter2D(Collision2D colisor)
{
if ( (colisor.gameObject.layer == 8) )
{
isJumping = false;
anim.SetBool("isJumping", false);
}
}
//DANO COMUM NO PLAYER
public void TakeDamage(float FullDamage)
{
FullDamage -= Def;
LifePlayer -= FullDamage;
if(!isPower)
{
anim.SetTrigger("isDamage");
}
if(LifePlayer <= 0)
{
isDead = true;
anim.SetBool("isDead", true);
//DestroyBody();
PlayerVersus.current.DestroyBody();
}
}
//SUPER DANO NO PLAYER
public void FullTakeDamage(float damage)
{
damage -= Def;
LifePlayer -= damage;
if (!isPower)
{
anim.SetTrigger("isFullDamage");
}
if (LifePlayer <= 0)
{
isDead = true;
anim.SetBool("isDead", true);
//DestroyBody();
PlayerVersus.current.DestroyBody();
}
}
//ROUND PERDIDO / GAME OVER
public void DestroyBody()
{
//GetComponent<BoxCollider2D>().enabled = false;
//GetComponent<CircleCollider2D>().enabled = false;
//GetComponent<CapsuleCollider2D>().enabled = false;
GetComponent<Rigidbody2D>().bodyType = RigidbodyType2D.Static;
//transitionRound.SetActive(true);
}
//REATIVANDO PLAYER
public void ReativeBody()
{
anim.SetBool("isDead", false);
//gameObject.GetComponent<Transform>().position = new Vector3(-11.34f, -1.71f, 0);//colocando player na posição inicial
//Cam.current.GetComponent<Transform>().position = new Vector3(0.29f, 2.95f, -4f);//colocando camera na posição inicial
transform.localEulerAngles = new Vector3(0, 0, 0);//rotacionando para a direita
GetComponent<BoxCollider2D>().enabled = true;
GetComponent<CircleCollider2D>().enabled = true;
GetComponent<CapsuleCollider2D>().enabled = true;
GetComponent<Rigidbody2D>().bodyType = RigidbodyType2D.Dynamic;
//isDead = true;
this.enabled = true;
}
}
| 26.921296 | 229 | 0.543938 | [
"MIT"
] | PabloXT14/Projeto_TCC-Jogo_School_Fighter | Arquivos do Projeto/SchoolFigther/Assets/AssetsLuta2/Scripts/Vesus/Player2Versus.cs | 11,650 | C# |
using SFA.DAS.EmployerAccounts.Exceptions;
using CommonOrganisationType = SFA.DAS.Common.Domain.Types.OrganisationType;
using ReferenceDataOrganisationType = SFA.DAS.ReferenceData.Types.DTO.OrganisationType;
namespace SFA.DAS.EmployerAccounts.Extensions
{
/// <remarks>
/// There are two organisation types used within MA - one from ReferenceData and one from common types (there is also a third from commitments but this is not relevant here).
/// The two organisation types look similar but are not identical and are subtly incompatible. I suspect this was by accident but now it is running free in the wild it is a bit
/// more difficult to fix.
/// There has always been an implicit mapping that occurs when the json from reference data is de-serialised in MA. This mapping was hitherto obscured but a recent update to
/// reference data that added the organisation type to the API has made the mapping a lot more obvious.
/// This class provides extensions methods to encapsulate this mapping.
/// </remarks>
public static class OrganisationTypeExtensions
{
/// <summary>
/// Map the supplied reference data organisation type to a common organisation type.
/// This is always possible but both education and public bodies in the reference data world map to public bodies
/// in the common types world. So once we've mapped one of these values from ref data we can not map them back.
/// </summary>
public static CommonOrganisationType ToCommonOrganisationType(this ReferenceDataOrganisationType organisationType)
{
switch (organisationType)
{
case ReferenceDataOrganisationType.Charity:
return CommonOrganisationType.Charities;
case ReferenceDataOrganisationType.Company:
return CommonOrganisationType.CompaniesHouse;
case ReferenceDataOrganisationType.EducationOrganisation:
return CommonOrganisationType.PublicBodies;
case ReferenceDataOrganisationType.PublicSector:
return CommonOrganisationType.PublicBodies;
default:
return CommonOrganisationType.Other;
}
}
/// <summary>
/// Maps the supplied common organisation type to a reference data organisation type and throws an exception if this cannot be done.
/// </summary>
public static ReferenceDataOrganisationType ToReferenceDataOrganisationType(this CommonOrganisationType organisationType)
{
if (organisationType.TryToReferenceDataOrganisationType(out ReferenceDataOrganisationType result))
{
return result;
}
// It is not possible to convert values of PublicBodies and Other to a reference data organisation type (as the mapping is 1:m).
throw new InvalidOrganisationTypeConversionException($"Can not convert Reference Data {organisationType} to a value of {typeof(ReferenceDataOrganisationType).FullName}");
}
/// <summary>
/// Maps the supplied common organisation type to a reference data organisation type and returns false if this cannot be done.
/// </summary>
public static bool TryToReferenceDataOrganisationType(this CommonOrganisationType organisationType, out ReferenceDataOrganisationType referenceDataType)
{
switch (organisationType)
{
case CommonOrganisationType.Charities:
referenceDataType = ReferenceDataOrganisationType.Charity;
return true;
case CommonOrganisationType.CompaniesHouse:
referenceDataType = ReferenceDataOrganisationType.Company;
return true;
default:
// We have to set the out param to something and there is no 'unknown'
referenceDataType = ReferenceDataOrganisationType.Charity;
return false;
}
}
public static string GetFriendlyName(this CommonOrganisationType commonOrganisationType)
{
switch (commonOrganisationType)
{
case CommonOrganisationType.CompaniesHouse: return "Companies House";
case CommonOrganisationType.Charities: return "Charity Commission";
case CommonOrganisationType.PublicBodies: return "Public Bodies";
case CommonOrganisationType.PensionsRegulator: return "Pensions Regulator";
default: return "Other";
}
}
}
}
| 54.022727 | 184 | 0.665755 | [
"MIT"
] | SkillsFundingAgency/das-employerapprenticeshipsservice | src/SFA.DAS.EmployerAccounts/Extensions/OrganisationTypeExtensions.cs | 4,756 | C# |
using System;
using System.Linq;
namespace additional01
{
public class Program
{
public static void Main(string[] args)
{
int arrayLength = 0;
if (int.TryParse(Console.ReadLine(), out arrayLength))
{
int[] array = new int[arrayLength];
int index = -1;
array = Console.ReadLine()
.Split()
.Select(int.Parse)
.ToArray();
for (int i = 0; i < arrayLength; i++)
{
int minValue = int.MaxValue;
for (int j = i; j < arrayLength; j++)
{
if (array[j] < minValue)
{
minValue = array[j];
index = j;
}
}
array[index] = array[i];
array[i] = minValue;
}
Console.WriteLine(string.Join(" ", array));
}
}
}
}
| 25.068182 | 66 | 0.356301 | [
"MIT"
] | BorislavVladimirov/Microinvest-Academy | MicrointvestArrays/additional01/Program.cs | 1,105 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
namespace CSharpGL
{
public partial class vermilion
{
//uint vglLoadTexture(string filename, uint texture, vglImageData image)
//{
//}
}
}
| 16.833333 | 80 | 0.683168 | [
"MIT"
] | AugusZhan/CSharpGL | Infrastructure/CSharpGL.Models/DDS/vermilion_vglLoadTexture.cs | 305 | C# |
using Vostok.Metrics.Primitives.Counter;
using Vostok.Metrics.Primitives.Gauge;
using Vostok.Metrics.Primitives.Timer;
namespace Vostok.Metrics.Scraping
{
// NOTE (tsup): We do not inherit configs from ScrapableMetricConfig to keep back-compatibility.
internal static class ConfigExtensions
{
public static ScrapableMetricConfig ToScrapableMetricConfig(this CounterConfig config)
{
return new ScrapableMetricConfig
{
ScrapePeriod = config.ScrapePeriod,
ScrapeOnDispose = config.ScrapeOnDispose,
Unit = config.Unit
};
}
public static ScrapableMetricConfig ToScrapableMetricConfig(this HistogramConfig config)
{
return new ScrapableMetricConfig
{
ScrapePeriod = config.ScrapePeriod,
ScrapeOnDispose = config.ScrapeOnDispose,
Unit = config.Unit
};
}
public static ScrapableMetricConfig ToScrapableMetricConfig(this GaugeConfig config)
{
return new ScrapableMetricConfig
{
ScrapePeriod = config.ScrapePeriod,
ScrapeOnDispose = config.ScrapeOnDispose,
Unit = config.Unit
};
}
public static ScrapableMetricConfig ToScrapableMetricConfig(this SummaryConfig config)
{
return new ScrapableMetricConfig
{
ScrapePeriod = config.ScrapePeriod,
ScrapeOnDispose = config.ScrapeOnDispose,
Unit = config.Unit
};
}
}
} | 33.08 | 101 | 0.60399 | [
"MIT"
] | vostok/metrics | Vostok.Metrics/Scraping/ConfigExtensions.cs | 1,656 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter;
using Microsoft.Protocols.TestTools;
using Microsoft.Protocols.TestTools.StackSdk;
using Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Fscc;
using Microsoft.SpecExplorer.Runtime.Testing;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Microsoft.Protocols.TestSuites.FileSharing.FSA.TestSuite
{
[TestClassAttribute()]
public partial class QuotaInfoTestCases : PtfTestClassBase
{
#region Variables
private FSAAdapter fsaAdapter;
#endregion
#region Class Initialization and Cleanup
[ClassInitializeAttribute()]
public static void ClassInitialize(TestContext context)
{
PtfTestClassBase.Initialize(context);
}
[ClassCleanupAttribute()]
public static void ClassCleanup()
{
PtfTestClassBase.Cleanup();
}
#endregion
#region Test Initialization and Cleanup
protected override void TestInitialize()
{
this.InitializeTestManager();
this.fsaAdapter = new FSAAdapter();
this.fsaAdapter.Initialize(BaseTestSite);
this.fsaAdapter.LogTestCaseDescription(BaseTestSite);
//Need to connect to RootDirectory for query or set quota info.
this.fsaAdapter.ShareName = this.fsaAdapter.RootDirectory;
BaseTestSite.Log.Add(LogEntryKind.Comment, "Test environment:");
BaseTestSite.Log.Add(LogEntryKind.Comment, "\t 1. File System: " + this.fsaAdapter.FileSystem.ToString());
BaseTestSite.Log.Add(LogEntryKind.Comment, "\t 2. Transport: " + this.fsaAdapter.Transport.ToString());
BaseTestSite.Log.Add(LogEntryKind.Comment, "\t 3. Share Path: " + this.fsaAdapter.UncSharePath);
this.fsaAdapter.FsaInitial();
}
protected override void TestCleanup()
{
this.fsaAdapter.Dispose();
base.TestCleanup();
this.CleanupTestManager();
}
#endregion
}
}
| 36.655738 | 118 | 0.673971 | [
"MIT"
] | 0neb1n/WindowsProtocolTestSuites | TestSuites/FileServer/src/FSA/TestSuite/QuotaInformation/QuotaInfoTestCases.cs | 2,236 | C# |
// ------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version: 16.0.0.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
// ------------------------------------------------------------------------------
namespace ServiceClientGenerator.Generators.Marshallers
{
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System;
/// <summary>
/// Class to produce the template output
/// </summary>
#line 1 "C:\Users\costleya\Work\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryEC2ResponseUnmarshaller.tt"
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "16.0.0.0")]
public partial class AWSQueryEC2ResponseUnmarshaller : BaseResponseUnmarshaller
{
#line hidden
/// <summary>
/// Create the template output
/// </summary>
public override string TransformText()
{
#line 6 "C:\Users\costleya\Work\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryEC2ResponseUnmarshaller.tt"
AddLicenseHeader();
AddCommonUsingStatements();
#line default
#line hidden
this.Write("namespace ");
#line 11 "C:\Users\costleya\Work\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryEC2ResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.Namespace));
#line default
#line hidden
this.Write(".Model.Internal.MarshallTransformations\r\n{\r\n /// <summary>\r\n /// Response U" +
"nmarshaller for ");
#line 14 "C:\Users\costleya\Work\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryEC2ResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.UnmarshallerBaseName));
#line default
#line hidden
this.Write(" operation\r\n /// </summary> \r\n public class ");
#line 16 "C:\Users\costleya\Work\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryEC2ResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.UnmarshallerBaseName));
#line default
#line hidden
this.Write(@"ResponseUnmarshaller : EC2ResponseUnmarshaller
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name=""context""></param>
/// <returns></returns>
public override AmazonWebServiceResponse Unmarshall(XmlUnmarshallerContext context)
{
");
#line 25 "C:\Users\costleya\Work\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryEC2ResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.UnmarshallerBaseName));
#line default
#line hidden
this.Write("Response response = new ");
#line 25 "C:\Users\costleya\Work\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryEC2ResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Operation.Name));
#line default
#line hidden
this.Write("Response();\r\n\r\n");
#line 27 "C:\Users\costleya\Work\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryEC2ResponseUnmarshaller.tt"
if (this.HasSuppressedResult)
{
#line default
#line hidden
this.Write(" while (context.Read())\r\n {\r\n\t\t\t\r\n\t\t\t}\r\n");
#line 34 "C:\Users\costleya\Work\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryEC2ResponseUnmarshaller.tt"
}
else
{
#line default
#line hidden
this.Write(@" int originalDepth = context.CurrentDepth;
int targetDepth = originalDepth + 1;
if (context.IsStartOfDocument)
targetDepth = 2;
while (context.ReadAtDepth(originalDepth))
{
if (context.IsStartElement || context.IsAttribute)
{
");
#line 49 "C:\Users\costleya\Work\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryEC2ResponseUnmarshaller.tt"
if(this.Structure != null)
{
if(this.IsWrapped)
{
#line default
#line hidden
this.Write(" if ( context.TestExpression(\".\", targetDepth))\r\n " +
" {\r\n response.");
#line 57 "C:\Users\costleya\Work\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryEC2ResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(MemberAccessorFor(this.Structure.Name)));
#line default
#line hidden
this.Write(" = ");
#line 57 "C:\Users\costleya\Work\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryEC2ResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Structure.Name));
#line default
#line hidden
this.Write("Unmarshaller.Instance.Unmarshall(context);\r\n continue;\r\n " +
" }\r\n");
#line 60 "C:\Users\costleya\Work\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryEC2ResponseUnmarshaller.tt"
}
else
{
foreach (var member in this.Structure.Members)
{
var testExpression = GeneratorHelpers.DetermineAWSQueryTestExpression(member);
#line default
#line hidden
this.Write(" if (context.TestExpression(\"");
#line 68 "C:\Users\costleya\Work\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryEC2ResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(testExpression));
#line default
#line hidden
this.Write("\", targetDepth))\r\n {\r\n var unmarshaller" +
" = ");
#line 70 "C:\Users\costleya\Work\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryEC2ResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.DetermineTypeUnmarshallerInstantiate()));
#line default
#line hidden
this.Write(";\r\n");
#line 71 "C:\Users\costleya\Work\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryEC2ResponseUnmarshaller.tt"
if (member.IsList)
{
#line default
#line hidden
this.Write(" var item = unmarshaller.Unmarshall(context);\r\n " +
" response.");
#line 76 "C:\Users\costleya\Work\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryEC2ResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(MemberAccessorFor(member.PropertyName)));
#line default
#line hidden
this.Write(".Add(item);\r\n");
#line 77 "C:\Users\costleya\Work\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryEC2ResponseUnmarshaller.tt"
}
else
{
#line default
#line hidden
this.Write(" response.");
#line 82 "C:\Users\costleya\Work\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryEC2ResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(MemberAccessorFor(member.PropertyName)));
#line default
#line hidden
this.Write(" = unmarshaller.Unmarshall(context);\r\n");
#line 83 "C:\Users\costleya\Work\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryEC2ResponseUnmarshaller.tt"
}
#line default
#line hidden
this.Write(" continue;\r\n }\r\n");
#line 88 "C:\Users\costleya\Work\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryEC2ResponseUnmarshaller.tt"
}
}
}
#line default
#line hidden
this.Write(" } \r\n }\r\n");
#line 95 "C:\Users\costleya\Work\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryEC2ResponseUnmarshaller.tt"
}
#line default
#line hidden
this.Write(@"
return response;
}
/// <summary>
/// Unmarshaller error response to exception.
/// </summary>
/// <param name=""context""></param>
/// <param name=""innerException""></param>
/// <param name=""statusCode""></param>
/// <returns></returns>
public override AmazonServiceException UnmarshallException(XmlUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode)
{
ErrorResponse errorResponse = ErrorResponseUnmarshaller.GetInstance().Unmarshall(context);
");
#line 112 "C:\Users\costleya\Work\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryEC2ResponseUnmarshaller.tt"
foreach (var exception in this.Operation.Exceptions)
{
#line default
#line hidden
this.Write(" if (errorResponse.Code != null && errorResponse.Code.Equals(\"");
#line 116 "C:\Users\costleya\Work\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryEC2ResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(exception.Code));
#line default
#line hidden
this.Write("\"))\r\n {\r\n return new ");
#line 118 "C:\Users\costleya\Work\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryEC2ResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(exception.Name));
#line default
#line hidden
this.Write("(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, e" +
"rrorResponse.RequestId, statusCode);\r\n }\r\n");
#line 120 "C:\Users\costleya\Work\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryEC2ResponseUnmarshaller.tt"
}
#line default
#line hidden
this.Write(" return new ");
#line 123 "C:\Users\costleya\Work\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryEC2ResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.BaseException));
#line default
#line hidden
this.Write("(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, e" +
"rrorResponse.RequestId, statusCode);\r\n }\r\n");
#line 125 "C:\Users\costleya\Work\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryEC2ResponseUnmarshaller.tt"
this.AddResponseSingletonMethod();
#line default
#line hidden
this.Write(" }\r\n}\r\n");
return this.GenerationEnvironment.ToString();
}
#line 130 "C:\Users\costleya\Work\aws-sdk-net\generator\ServiceClientGeneratorLib\Generators\Marshallers\AWSQueryEC2ResponseUnmarshaller.tt"
// if the result fields have been wrapped in a subordinate structure, wire the accessor
// to use it when addressing a member
string MemberAccessorFor(string memberName)
{
return string.IsNullOrEmpty(WrappedResultMember) ? memberName : WrappedResultMember;
}
#line default
#line hidden
}
#line default
#line hidden
}
| 41.33642 | 152 | 0.5921 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | generator/ServiceClientGeneratorLib/Generators/Marshallers/AWSQueryEC2ResponseUnmarshaller.cs | 13,395 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using Infrastructure.EF.Data.Contracts;
namespace Infrastructure.Config
{
public class HttpManager : IHttpManager
{
public const string ContextName = "HttpContext";
public ApplicationDbContext Context()
{
if (HttpContext.Current.Items[ContextName] == null)
{
HttpContext.Current.Items[ContextName] = new ApplicationDbContext();
}
return HttpContext.Current.Items[ContextName] as ApplicationDbContext;
}
public void CloseConnection()
{
var context = HttpContext.Current.Items[ContextName] as ApplicationDbContext;
if (context != null)
{
context.Dispose();
}
}
}
}
| 25.657143 | 89 | 0.61804 | [
"MIT"
] | ViniciusTavares/.Net-DDD-Sample | Infrastructure.EF.Data/Config/HttpManager.cs | 900 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="MagicRepositoryExtensions.cs" company="nGratis">
// The MIT License (MIT)
//
// Copyright (c) 2014 - 2021 Cahya Ong
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// </copyright>
// <author>Cahya Ong - cahya.ong@gmail.com</author>
// <creation_timestamp>Tuesday, April 7, 2020 5:45:08 AM UTC</creation_timestamp>
// --------------------------------------------------------------------------------------------------------------------
namespace nGratis.AI.Kvasir.Core.Test
{
using System;
using System.Threading.Tasks;
using FluentAssertions;
using FluentAssertions.Execution;
using Moq.AI.Kvasir;
using nGratis.AI.Kvasir.Contract;
using Xunit;
using MockBuilder = Moq.AI.Kvasir.MockBuilder;
public class MagicRepositoryExtensions
{
public class GetCardSetAsyncMethod
{
[Fact]
public async Task WhenGettingNameForExistingCardSet_ShouldReturnIt()
{
// Arrange.
var mockRepository = MockBuilder
.CreateMock<IUnprocessedMagicRepository>()
.WithCardSets("[_MOCK_NAME_01_]", "[_MOCK_NAME_02_]", "[_MOCK_NAME_03_]");
// Act.
var cardSet = await mockRepository.Object.GetCardSetAsync("[_MOCK_NAME_02_]");
// Assert.
cardSet
.Should().NotBeNull();
using (new AssertionScope())
{
cardSet
.Code
.Should().Be("[_MOCK_CODE_02_]");
cardSet
.Name
.Should().Be("[_MOCK_NAME_02_]");
cardSet
.ReleasedTimestamp
.Should().Be(DateTime.Parse("2020-01-01"));
}
}
[Fact]
public void WhenGettingNameForNonExistingCardSet_ShouldThrowKvasirException()
{
// Arrange.
var mockRepository = MockBuilder
.CreateMock<IUnprocessedMagicRepository>()
.WithCardSets("[_MOCK_NAME_]");
// Act & Assert.
mockRepository.Object
.Awaiting(self => self.GetCardSetAsync("[_MOCK_ANOTHER_NAME_]"))
.Should().Throw<KvasirException>()
.WithMessage(
"Failed to find card set! " +
"Name: [[_MOCK_ANOTHER_NAME_]].");
}
[Fact]
public void WhenGettingNameForMultipleDifferentCardSets_ShouldThrowKvasirException()
{
// Arrange.
var mockRepository = MockBuilder
.CreateMock<IUnprocessedMagicRepository>()
.WithCardSets("[_MOCK_NAME_]", "[_MOCK_NAME_]");
// Act & Assert.
mockRepository.Object
.Awaiting(self => self.GetCardSetAsync("[_MOCK_NAME_]"))
.Should().Throw<KvasirException>()
.WithMessage(
"Found more than 1 card set! " +
"Name: [[_MOCK_NAME_]].");
}
}
}
} | 38.102564 | 120 | 0.538807 | [
"MIT"
] | cahyaong/ai.kvasir | Source/Kvasir.Core.Test/IO/MagicRepositoryExtensions.cs | 4,460 | C# |
using System;
namespace _01.Resurrection
{
class Program
{
static void Main()
{
int numOfPhoenixes = int.Parse(Console.ReadLine());
for (int i = 0; i < numOfPhoenixes; i++)
{
int totalLength = int.Parse(Console.ReadLine());
decimal totalWidth = decimal.Parse(Console.ReadLine());
int totalWingLength = int.Parse(Console.ReadLine());
decimal totalYears = (decimal)Math.Pow(totalLength, 2) * (totalWidth + 2 * totalWingLength);
Console.WriteLine(totalYears);
}
}
}
} | 31.5 | 108 | 0.542857 | [
"MIT"
] | CvetelinLozanov/SoftUni-C- | Programing Fundamentals C#/Progr. Fund. Extended Retake Exam - 04 Sept 2017/01. Resurrection/Program.cs | 632 | C# |
namespace MyPet.Domain.AdoptionAds.Models
{
public class AdoptionConstants
{
public class AdoptionCategory
{
public const int MinAdoptionCategoryNameLength = 2;
public const int MaxAdoptionCategoryNameLength = 100;
}
public class AdoptionAd
{
public const int MinAdoptionAdTitleLength = 2;
public const int MaxAdoptionAdTitleLength = 100;
public const int MinAdoptionAdDescriptionLength = 1;
public const int MaxAdoptionAdDescriptionLength = 1000;
}
}
}
| 28.047619 | 67 | 0.63837 | [
"MIT"
] | Domin1k/My-Pet | Server/Core/MyPet.Domain/AdoptionAds/Models/AdoptionConstants.cs | 591 | C# |
using System.Collections.ObjectModel;
namespace Mistware.Utils
{
/// <summary>
/// Holds a collection of Key/Value objects
/// KeyList and KeyPair classes are quite simlar to other classes, but their use can result in simpler code.
/// </summary>
public class KeyList : Collection<KeyPair>
{
/// <summary>
/// Add a Pair to the Pairs collection
/// </summary>
public void Add(string key, string value)
{
KeyPair pair = new KeyPair(key, value);
base.Add(pair);
}
}
/// <summary>
/// Holds a collection of Pair objects
/// KeyList and KeyPair classes are quite simlar to other classes, but their use can result in simpler code.
/// </summary>
public class KeyList<T,S> : Collection<KeyPair<T,S>>
{
/// <summary>
/// Add a Pair to the Pairs collection
/// </summary>
public void Add(T key, S value)
{
KeyPair<T,S> pair = new KeyPair<T,S>(key, value);
base.Add(pair);
}
}
/// <summary>
/// Represents a KeyPair of string values (key and value)
/// </summary>
public class KeyPair : KeyPair<string,string>
{
public KeyPair(string key, string value) : base(key, value) { }
}
/// <summary>
/// Represents a simple pair of Key and Value
/// </summary>
/// <typeparam name="T">The type of <see cref="Key"/></typeparam>
/// <typeparam name="S">The type of <see cref="Value"/></typeparam>
public class KeyPair<T,S>
{
/// <summary>
/// Create a KeyPair with the default values for <see cref="Key"/>
/// and <see cref="Value"/>
/// </summary>
public KeyPair()
: this(default(T), default(S))
{
}
/// <summary>
/// Creates a new KeyPair
/// </summary>
/// <param name="key">The initial value of <see cref="Key"/></param>
/// <param name="value">The initisl value of <see cref="Value"/></param>
public KeyPair(T key, S value)
{
Key = key;
Value = value;
}
/// <summary>
/// The key of the KeyPair
/// </summary>
public T Key
{
get;
set;
}
/// <summary>
/// The value of the KeyPair
/// </summary>
public S Value
{
get;
set;
}
/// <summary>
/// Gets a string description of the KeyPair
/// </summary>
/// <returns>The pair's key and value separated by an '=' </returns>
public override string ToString()
{
return string.Format("({0} = {1})", Key, Value);
}
/// <summary>
/// Checks if this KeyPair equals another
/// </summary>
/// <param name="obj">The object to check the equality of</param>
/// <returns>True if <paramref name="obj"/> is a <c>KeyPair</c> and its keys and values
/// are equal</returns>
public override bool Equals(object obj)
{
if (obj is KeyPair<T, S>)
{
var other = (KeyPair<T, S>)obj;
if (!System.Object.Equals(this.Key, other.Key)) return false;
if (!System.Object.Equals(this.Value, other.Value)) return false;
return true;
}
return false;
}
/// <summary>
/// Gets a hashcode for this KeyPair
/// </summary>
/// <returns>The hashcodes of the <c>KeyPair</c>'s key and value XORed together</returns>
public override int GetHashCode()
{
int keyHash = Key != null ? Key.GetHashCode() : 0;
int valueHash = Value != null ? Value.GetHashCode() : 0;
return keyHash ^ valueHash;
}
}
}
| 29.111111 | 113 | 0.510433 | [
"BSD-3-Clause"
] | julianpratt/ReportDist | Data/Entities/KeyList.cs | 3,930 | C# |
// Copyright (c) 2008-2021, Hazelcast, Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Hazelcast.Metrics
{
internal enum MetricValueType : byte
{
// values must align with Java
Long = 0,
Double = 1
}
}
| 32.583333 | 75 | 0.70844 | [
"Apache-2.0"
] | Serdaro/hazelcast-csharp-client | src/Hazelcast.Net/Metrics/MetricValueType.cs | 784 | C# |
using Microsoft.Extensions.DependencyInjection;
using Volo.Abp.Modularity;
namespace LYearUiSample.EntityFrameworkCore
{
[DependsOn(
typeof(LYearUiSampleEntityFrameworkCoreModule)
)]
public class LYearUiSampleEntityFrameworkCoreDbMigrationsModule : AbpModule
{
public override void ConfigureServices(ServiceConfigurationContext context)
{
context.Services.AddAbpDbContext<LYearUiSampleMigrationsDbContext>();
}
}
}
| 28.529412 | 83 | 0.742268 | [
"MIT"
] | wagnerhsu/sample-Abp.AspNetCore.Mvc.UI.Theme.LYear | samples/LYearUiSample.EntityFrameworkCore.DbMigrations/EntityFrameworkCore/LYearUiSampleEntityFrameworkCoreDbMigrationsModule.cs | 487 | C# |
// <copyright file="VegaDistributedTestClient.cs" company="Microsoft Corporation">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
namespace Microsoft.Vega.DistributedTest
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Fabric;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using DistTestCommonProto;
using Grpc.Core;
using Microsoft.Extensions.Configuration;
using Microsoft.Vega.DistributedJobControllerProto;
using Microsoft.Vega.Test.Helpers;
using Microsoft.VisualStudio.TestTools.UnitTesting;
/// <summary>
/// Client program to communicate with the distributed job controller, start test, and collect result
/// </summary>
[TestClass]
public sealed class VegaDistributedTestClient : IDisposable
{
/// <summary>
/// IP address or the host name of the server
/// </summary>
private static string serverAddress;
/// <summary>
/// Global log function
/// </summary>
private static Action<string> log = Console.WriteLine;
/// <summary>
/// Parameters passed by TAEF in the form of "TE.exe VegaDistributedTestClient /p:Key=Value"
/// </summary>
private static IDictionary<string, object> testProperties;
/// <summary>
/// The root node name
/// </summary>
private static string rootNodeName = "DistPerf";
/// <summary>
/// IP address or the host name of the Vega service
/// </summary>
private static string vegaAddress;
/// <summary>
/// The vega port number
/// </summary>
private static string vegaPortNumber;
/// <summary>
/// Name or regex of the node which initiates the primary failover
/// </summary>
private static string killerNodeName;
/// <summary>
/// Cancellation for all test jobs
/// </summary>
private static CancellationTokenSource cancellationSource;
/// <summary>
/// The default test parameters
/// </summary>
private static Dictionary<string, string> defaultTestParameters;
/// <summary>
/// The distributed test client
/// </summary>
private static DistributedJobControllerSvc.DistributedJobControllerSvcClient distTestClient;
/// <summary>
/// Minimum data payload size
/// </summary>
private static int minDataSize = 256;
/// <summary>
/// Maximum data payload size
/// </summary>
private static int maxDataSize = 16384;
/// <summary>
/// Request timeout to the backend
/// </summary>
private static int requestTimeout = 100000;
/// <summary>
/// Number of thread to send request in parallel
/// </summary>
private static int threadCount = -1;
/// <summary>
/// Number of seconds each test should run
/// </summary>
private static int testCaseSeconds = 100;
/// <summary>
/// Number of batched operation in a group
/// </summary>
private static int batchOpCount = 32;
/// <summary>
/// Number of async task to await in a batch
/// </summary>
private static int asyncTaskCount = 64;
/// <summary>
/// The create test will create a large number of small trees (child number 0 - 20)
/// and a small number (20 - 50) large trees, which have a lot more children.
/// Each thread in the test switches between creating small trees and large trees continuously.
/// So this magic number actually means, after creating one small tree,
/// how many large tree nodes should it create.
/// </summary>
private static int largeTreeRatio = 50;
/// <summary>
/// The watcher count per node
/// </summary>
private static int watcherCountPerNode = 0;
/// <summary>
/// The application settings
/// </summary>
private static IConfiguration appSettings;
/// <summary>
/// The empty message
/// </summary>
private static Empty emptyMessage = new Empty();
/// <summary>
/// The GRPC channel
/// </summary>
private static Channel grpcChannel;
/// <summary>
/// Initializes the test class
/// </summary>
/// <param name="context">Test context object</param>
[ClassInitialize]
public static void ClassInitialize(TestContext context)
{
var path = Assembly.GetExecutingAssembly().Location;
var builder = new ConfigurationBuilder().SetBasePath(Path.GetDirectoryName(path)).AddJsonFile("appSettings.json");
appSettings = builder.Build();
Helpers.SetupTraceLog(Path.Combine(appSettings["LogFolder"], "VegaDistributedTestClient.LogPath"));
log = (s) => Trace.TraceInformation(s);
cancellationSource = new CancellationTokenSource();
serverAddress = appSettings["ServerAddress"];
vegaAddress = appSettings["VegaAddress"];
vegaPortNumber = appSettings["VegaPortNumber"];
killerNodeName = appSettings["KillerNodeName"];
minDataSize = int.Parse(appSettings["MinDataSize"]);
maxDataSize = int.Parse(appSettings["MaxDataSize"]);
batchOpCount = int.Parse(appSettings["BatchOpCount"]);
testCaseSeconds = int.Parse(appSettings["TestCaseSeconds"]);
requestTimeout = int.Parse(appSettings["RequestTimeout"]);
threadCount = int.Parse(appSettings["ThreadCount"]);
asyncTaskCount = int.Parse(appSettings["AsyncTaskCount"]);
largeTreeRatio = int.Parse(appSettings["LargeTreeRatio"]);
watcherCountPerNode = int.Parse(appSettings["WatcherCountPerNode"]);
testProperties = context.Properties;
// If TAEF provides some parameters, take them and override app.config
if (testProperties != null)
{
if (testProperties.ContainsKey("ServerAddress"))
{
serverAddress = testProperties["ServerAddress"] as string;
}
if (testProperties.ContainsKey("VegaAddress"))
{
vegaAddress = testProperties["VegaAddress"] as string;
}
if (testProperties.ContainsKey("VegaPortNumber"))
{
vegaPortNumber = testProperties["VegaPortNumber"] as string;
}
if (testProperties.ContainsKey("KillerNodeName"))
{
killerNodeName = testProperties["KillerNodeName"] as string;
}
if (testProperties.ContainsKey("RootNodeName"))
{
rootNodeName = testProperties["RootNodeName"] as string;
}
}
else
{
// Only handle Ctrl-C when running from main()
Console.CancelKeyPress += (sender, args) =>
{
if (!cancellationSource.IsCancellationRequested)
{
args.Cancel = true;
cancellationSource.Cancel();
log($"Ctrl-C intercepted. Graceful shutdown started. Press Ctrl-C again to abort.");
}
};
}
defaultTestParameters = new Dictionary<string, string>
{
{ "VegaAddress", vegaAddress },
{ "VegaPort", vegaPortNumber },
{ "RootNodeName", rootNodeName },
{ "MinDataSize", minDataSize.ToString() },
{ "MaxDataSize", maxDataSize.ToString() },
{ "BatchOpCount", batchOpCount.ToString() },
{ "TestCaseSeconds", testCaseSeconds.ToString() },
{ "RequestTimeout", requestTimeout.ToString() },
{ "ThreadCount", threadCount.ToString() },
{ "AsyncTaskCount", asyncTaskCount.ToString() },
{ "LargeTreeRatio", largeTreeRatio.ToString() },
{ "WatcherCountPerNode", watcherCountPerNode.ToString() },
};
TestInitialize().GetAwaiter().GetResult();
}
/// <summary>
/// Test cleanup
/// </summary>
[ClassCleanup]
public static void TestClassCleanup()
{
cancellationSource.Dispose();
grpcChannel.ShutdownAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Disposes this object
/// </summary>
public void Dispose()
{
GC.SuppressFinalize(this);
}
/// <summary>
/// Pings Madari service using TCP connection and measures the connection time
/// </summary>
[TestMethod]
[TestCategory("Functional")]
public void TestTcpPing()
{
this.RunTestJobAsync(
"TestTcpPing",
new Dictionary<string, string>
{
{ "Hosts", vegaAddress },
{ "Ports", vegaPortNumber },
}).GetAwaiter().GetResult();
}
/// <summary>
/// Ping-pong test.
/// </summary>
[TestMethod]
[TestCategory("Functional")]
public void TestPingPong()
{
this.RunTestJobAsync(
"TestPingPong",
defaultTestParameters,
new string[] { "ProcessedCounts" })
.GetAwaiter().GetResult();
}
/// <summary>
/// create node test.
/// </summary>
[TestMethod]
[TestCategory("Functional")]
public void TestCreateNode()
{
this.RunTestJobAsync(
"TestCreateNode",
defaultTestParameters,
new string[] { "ProcessedCounts" })
.GetAwaiter().GetResult();
}
/// <summary>
/// get full subtree test.
/// </summary>
[TestMethod]
[TestCategory("Functional")]
public void TestGetFullSubtree()
{
this.RunTestJobAsync(
"TestGetFullSubtree",
defaultTestParameters,
new string[] { "ProcessedCounts" })
.GetAwaiter().GetResult();
}
/// <summary>
/// get node test.
/// </summary>
[TestMethod]
[TestCategory("Functional")]
public void TestGetNode()
{
this.RunTestJobAsync(
"TestGetNode",
defaultTestParameters,
new string[] { "ProcessedCounts" })
.GetAwaiter().GetResult();
}
/// <summary>
/// set node test.
/// </summary>
[TestMethod]
[TestCategory("Functional")]
public void TestSetNode()
{
this.RunTestJobAsync(
"TestSetNode",
defaultTestParameters,
new string[] { "ProcessedCounts" })
.GetAwaiter().GetResult();
}
/// <summary>
/// batch create node test.
/// </summary>
[TestMethod]
[TestCategory("Functional")]
public void TestBatchCreate()
{
this.RunTestJobAsync(
"TestBatchCreate",
defaultTestParameters,
new string[] { "ProcessedCounts" })
.GetAwaiter().GetResult();
}
/// <summary>
/// multi create node test.
/// </summary>
[TestMethod]
[TestCategory("Functional")]
public void TestMultiCreate()
{
this.RunTestJobAsync(
"TestMultiCreate",
defaultTestParameters,
new string[] { "ProcessedCounts" })
.GetAwaiter().GetResult();
}
/// <summary>
/// Delete node test.
/// </summary>
[TestMethod]
[TestCategory("Functional")]
public void TestDeleteNode()
{
this.RunTestJobAsync(
"TestDeleteNode",
defaultTestParameters,
new string[] { "ProcessedCounts" })
.GetAwaiter().GetResult();
}
/// <summary>
/// Test the NSM/LNM VNET Publishing
/// </summary>
[TestMethod]
[TestCategory("Functional")]
public void TestLnmVnetPublishingScenario()
{
this.RunTestJobAsync(
"TestLnmVnetPublishingScenario",
defaultTestParameters,
new string[] { "ProcessedCounts" })
.GetAwaiter().GetResult();
}
/// <summary>
/// Test the Publish/Subscribe scenario.
/// </summary>
[TestMethod]
[TestCategory("Functional")]
public void TestPublishSubscribeScenario()
{
this.RunTestJobAsync(
"TestPublishSubscribeScenario",
new Dictionary<string, string>
{
{ "VegaAddress", vegaAddress },
{ "VegaPort", vegaPortNumber },
{ "ThreadCount", threadCount.ToString() },
{ "MinDataSize", minDataSize.ToString() },
{ "MaxDataSize", maxDataSize.ToString() },
{ "RequestTimeout", requestTimeout.ToString() },
{ "TestRepetitions", appSettings["TestRepetitions"] },
{ "PartitionCount", appSettings["PartitionCount"] },
{ "NodeCountPerPartition", appSettings["NodeCountPerPartition"] },
{ "ChannelCount", appSettings["ChannelCount"] },
},
new string[] { "CreateLatency", "ReadLatency", "SetLatency", "DeleteLatency", "InstallWatcherLatency" })
.GetAwaiter().GetResult();
}
/// <summary>
/// Async entry of the console program
/// </summary>
/// <returns>async task</returns>
private static async Task TestInitialize()
{
string endpoint = $"{serverAddress}:18600";
if (string.IsNullOrEmpty(serverAddress))
{
using (var fabricClient = new FabricClient())
{
endpoint = await GetFirstJobControllerEndpoint(fabricClient).ConfigureAwait(false);
}
}
grpcChannel = new Channel(endpoint, ChannelCredentials.Insecure);
distTestClient = new DistributedJobControllerSvc.DistributedJobControllerSvcClient(grpcChannel);
var ids = await distTestClient.GetServiceInstanceIdentitiesAsync(emptyMessage);
log($"Number of runners: {ids.ServiceInstanceIdentities.Count}");
log(string.Join("\n", ids.ServiceInstanceIdentities));
}
/// <summary>
/// Get the endpoint of the first job controller micro-service
/// </summary>
/// <param name="fabricClient">Service fabric client for querying the naming service</param>
/// <returns>Endpoint string of the job controller</returns>
private static async Task<string> GetFirstJobControllerEndpoint(FabricClient fabricClient)
{
var nameFilter = new Regex("VegaDistTest", RegexOptions.IgnoreCase);
var query = fabricClient.QueryManager;
foreach (var app in await query.GetApplicationListAsync().ConfigureAwait(false))
{
if (!nameFilter.IsMatch(app.ApplicationTypeName))
{
continue;
}
foreach (var service in await query.GetServiceListAsync(app.ApplicationName).ConfigureAwait(false))
{
if (!nameFilter.IsMatch(service.ServiceTypeName))
{
continue;
}
foreach (var partition in await query.GetPartitionListAsync(service.ServiceName).ConfigureAwait(false))
{
foreach (var replica in await query.GetReplicaListAsync(partition.PartitionInformation.Id).ConfigureAwait(false))
{
var match = Regex.Match(replica.ReplicaAddress, "\"GrpcEndpoint\":\"([^\"]+)\"");
if (match.Success)
{
return $"{match.Groups[1].Value.Replace(@"\", string.Empty).Replace(@"http://", string.Empty)}";
}
}
}
}
}
return string.Empty;
}
/// <summary>
/// Runs a test job
/// </summary>
/// <param name="scenarioName">Class name of the test job</param>
/// <param name="parameters">Test parameters in key-value pairs</param>
/// <param name="metricNames">metrics that will be pulled from job</param>
/// <param name="parameterOverrideName">specify the parameter override file name, default to scenarioName</param>
/// <returns>async task</returns>
private async Task RunTestJobAsync(
string scenarioName,
Dictionary<string, string> parameters,
string[] metricNames = null,
string parameterOverrideName = null)
{
// try to read overriden parameters from current directory
string parameterOverrideFile = $"{parameterOverrideName ?? scenarioName}.ParameterOverride";
if (File.Exists(parameterOverrideFile))
{
foreach (var line in File.ReadLines(parameterOverrideFile))
{
bool isOverriden = false;
var pair = line.Split(new char[] { ',' });
if (pair.Count() == 2)
{
var key = pair[0].Trim();
var value = pair[1].Trim();
if (parameters.ContainsKey(key))
{
parameters[key] = value;
isOverriden = true;
}
}
if (!isOverriden)
{
log($"invalid overriding parameter: {line}.");
}
}
}
var startTime = DateTime.Now;
log($"Starting test {scenarioName} with below parameters");
foreach (var pair in parameters)
{
log($"\t{pair.Key}, {pair.Value}");
}
int maxRunningTime = 0;
if (parameters.ContainsKey("MaxRunningTime"))
{
maxRunningTime = int.Parse(parameters["MaxRunningTime"]);
}
await distTestClient.StartJobAsync(new StartJobRequest()
{
Scenario = scenarioName,
Parameters = { GrpcHelper.GetJobParametersFromDictionary(parameters) },
});
JobState[] jobStates = null;
while (!cancellationSource.Token.IsCancellationRequested)
{
if (maxRunningTime > 0 && (DateTime.Now - startTime).TotalSeconds > maxRunningTime)
{
log($"Hit the max running time ({maxRunningTime} seconds), cancelling jobs...");
await distTestClient.CancelRunningJobAsync(emptyMessage);
break;
}
try
{
jobStates = (await distTestClient.GetJobStatesAsync(emptyMessage)).JobStates.ToArray();
}
catch (Exception ex)
{
log($"Exception hit while reading job states from controller, will retry in 10 seconds... ex: {ex}");
await Task.Delay(10000, cancellationSource.Token).ConfigureAwait(false);
continue;
}
log($"{DateTime.Now} - Job states:");
foreach (var jobState in jobStates)
{
if (jobState != null)
{
log(jobState.ToString());
}
else
{
// should investigate why service returns null.
log("NULL state ...");
}
}
if (jobStates.All(j => j.Completed))
{
if (metricNames != null)
{
log($"Fetching metrics...");
foreach (var metricName in metricNames)
{
int startIndex = 0;
int pageSize = 1000;
List<double> metrics = new List<double>();
while (!cancellationSource.Token.IsCancellationRequested)
{
var temp = (await distTestClient.GetJobMetricsAsync(new GetJobMetricsRequest
{
MetricName = metricName,
StartIndex = startIndex,
PageSize = pageSize,
})).JobMetrics;
if (temp.Count == 0)
{
break;
}
startIndex += pageSize;
metrics.AddRange(temp);
}
if (metrics.Count() > 0)
{
log($"Test outcome {scenarioName} - {metricName} : {Utilities.GetReport(metrics.ToArray())}");
}
}
}
break;
}
else
{
try
{
await Task.Delay(10000, cancellationSource.Token).ConfigureAwait(false);
}
catch (TaskCanceledException)
{
}
}
}
if (cancellationSource.Token.IsCancellationRequested)
{
await distTestClient.CancelRunningJobAsync(emptyMessage);
}
log($"Test was run with below parameters.");
foreach (var pair in parameters)
{
log($"\t{pair.Key}, {pair.Value}");
}
log($"Test duration: {(DateTime.Now - startTime).TotalSeconds} seconds. Range Local: {startTime} - {DateTime.Now}, UTC: {startTime.ToUniversalTime()} - {DateTime.Now.ToUniversalTime()}");
Assert.AreEqual(0, jobStates.Count(jobState => !jobState.Passed));
}
}
}
| 36.169725 | 199 | 0.506574 | [
"MIT"
] | Azure/RingMaster | src/Tests/VegaDistributedTest/VegaDistributedTestClient/VegaDistributedTestClient.cs | 23,657 | C# |
using DOTP.DRM.Models;
using DOTP.RaidManager;
using DOTP.Users;
using System.Web.Mvc;
namespace DOTP.DRM.Controllers
{
public class CharactersController : Controller
{
#region /Characters/Add
//
// GET: /Characters/Add
public ActionResult Add()
{
if (!Manager.IsReallyAuthenticated(Request))
return RedirectToAction("LogOn", "Account");
return View();
}
//
// POST: /Characters/Add
[HttpPost]
public ActionResult Add(AddCharacterModel model)
{
if (!Manager.IsReallyAuthenticated(Request))
return RedirectToAction("LogOn", "Account");
var newChar = new Character()
{
Name = model.Name,
Level = int.Parse(model.Level),
Race = model.Race,
Class = model.Class,
AccountID = Manager.GetCurrentUser().ID,
PrimarySpecialization = model.PrimarySpecialization,
SecondarySpecialization = model.SecondarySpecialization
};
string errorMsg;
if (!Character.Store.TryCreate(newChar, out errorMsg))
return new JsonResult() { Data = new AddCharacterResponse(false, errorMsg) };
return new JsonResult() { Data = new AddCharacterResponse(true, "") };
}
#endregion
#region /Characters/Edit
//
// GET: /Characters/Edit/?Name=<Name>
public ActionResult Edit(string Name)
{
if (!Manager.IsReallyAuthenticated(Request))
return RedirectToAction("LogOn", "Account");
var character = Character.Store.ReadOneOrDefault(c => c.Name == Name);
if (null == character)
return RedirectToAction("Index", "Characters");
if (Manager.GetCurrentUser().ID != character.AccountID)
return RedirectToAction("Index", "Characters");
var model = new EditCharacterModel()
{
OldName = character.Name,
Name = character.Name,
Level = character.Level.ToString(),
Race = character.Race,
Class = character.Class,
PrimarySpecialization = character.PrimarySpecialization,
SecondarySpecialization = character.SecondarySpecialization
};
return View(model);
}
//
// POST: /Characters/Edit
[HttpPost]
public ActionResult Edit(EditCharacterModel model)
{
if (!Manager.IsReallyAuthenticated(Request))
return RedirectToAction("LogOn", "Account");
var character = new Character()
{
Name = model.Name,
Level = int.Parse(model.Level),
Race = model.Race,
Class = model.Class,
AccountID = Manager.GetCurrentUser().ID,
PrimarySpecialization = model.PrimarySpecialization,
SecondarySpecialization = model.SecondarySpecialization
};
string errorMsg;
if (!Character.Store.TryModify(model.OldName, character, out errorMsg))
return new JsonResult() { Data = new AddCharacterResponse(false, errorMsg) };
return new JsonResult() { Data = new AddCharacterResponse(true, "") };
}
#endregion
#region /Characters/Delete
//
// GET: /Characters/Delete/?Name=<Name>
public ActionResult Delete(string Name)
{
if (!Manager.IsReallyAuthenticated(Request))
return RedirectToAction("LogOn", "Account");
ViewBag.Character = Character.Store.ReadOneOrDefault(c => c.Name == Name);
if (null == ViewBag.Character)
return RedirectToAction("Index", "Characters");
if (Manager.GetCurrentUser().ID != ViewBag.Character.AccountID)
return RedirectToAction("Index", "Characters");
return View();
}
//
// POST: /Characters/Delete
[HttpPost]
public ActionResult Delete(string Name, int AccountID)
{
if (!Manager.IsReallyAuthenticated(Request))
return RedirectToAction("LogOn", "Account");
string errorMsg;
if (!Character.Store.TryDelete(Name, out errorMsg))
return new JsonResult() { Data = new AddCharacterResponse(false, errorMsg) };
return new JsonResult() { Data = new AddCharacterResponse(true, "") };
}
#endregion
#region /Characters/
//
// GET: /Characters/
public ActionResult Index()
{
if (!Manager.IsReallyAuthenticated(Request))
return RedirectToAction("LogOn", "Account");
ViewBag.Characters = Character.Store.ReadAll(c => c.AccountID == Manager.GetCurrentUser().ID);
return View();
}
#endregion
#region AddCharacterResponse
private class AddCharacterResponse
{
public bool Success { get; set; }
public string ErrorMessage { get; set; }
public AddCharacterResponse(bool success, string errorMsg)
{
Success = success;
ErrorMessage = errorMsg;
}
}
#endregion
}
}
| 29.232804 | 106 | 0.549683 | [
"BSD-2-Clause"
] | anxkha/DRM | DOTP.DRM/Controllers/CharactersController.cs | 5,527 | C# |
namespace JsDataGrids.UI.Models
{
public class ErrorViewModel
{
public string RequestId { get; set; }
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
}
}
| 19.8 | 70 | 0.661616 | [
"MIT"
] | hpscodemaverick/JavascriptDataGrids | JsGrid.UI/Models/ErrorViewModel.cs | 198 | C# |
/*
* Tencent is pleased to support the open source community by making Puerts available.
* Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
* Puerts is licensed under the BSD 3-Clause License, except for the third-party components listed in the file 'LICENSE' which may be subject to their corresponding license terms.
* This file is subject to the terms and conditions defined in file 'LICENSE', which is part of this source code package.
*/
using System;
namespace Puerts
{
public static class Utils
{
public static long TwoIntToLong(int a, int b)
{
return (long)a << 32 | b & 0xFFFFFFFFL;
}
public static void LongToTwoInt(long c, out int a, out int b)
{
a = (int)(c >> 32);
b = (int)c;
}
public static IntPtr GetObjectPtr(int jsEnvIdx, Type type, object obj)
{
var jsEnv = JsEnv.jsEnvs[jsEnvIdx];
return new IntPtr(type.IsValueType() ? jsEnv.objectPool.AddBoxedValueType(obj) : jsEnv.objectPool.FindOrAddObject(obj));
}
public static object GetSelf(int jsEnvIdx, IntPtr self)
{
return JsEnv.jsEnvs[jsEnvIdx].objectPool.Get(self.ToInt32());
}
}
} | 35.111111 | 179 | 0.643196 | [
"BSD-3-Clause"
] | SirXuNian/puerts | unity/Assets/Puerts/Src/Utils.cs | 1,266 | C# |
// ********************************************************************************************************
// Product Name: DotSpatial.Projection
// Description: The basic module for MapWindow version 6.0
// ********************************************************************************************************
// The contents of this file are subject to the MIT License (MIT)
// you may not use this file except in compliance with the License. You may obtain a copy of the License at
// http://dotspatial.codeplex.com/license
//
// Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF
// ANY KIND, either expressed or implied. See the License for the specific language governing rights and
// limitations under the License.
//
// The original content was ported from the C language from the 4.6 version of Proj4 libraries.
// Frank Warmerdam has released the full content of that version under the MIT license which is
// recognized as being approximately equivalent to public domain. The original work was done
// mostly by Gerald Evenden. The latest versions of the C libraries can be obtained here:
// http://trac.osgeo.org/proj/
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 8/12/2009 2:26:13 PM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
// Name | Date | Comment
// --------------------|------------|------------------------------------------------------------
// Ted Dunsford | 5/3/2010 | Updated project to DotSpatial.Projection and license to LGPL
// ********************************************************************************************************
using System;
namespace DotSpatial.Projections.Transforms
{
/// <summary>
/// WinkelTripel
/// </summary>
public class WinkelTripel : Transform
{
#region Private Variables
private double _cosphi1;
#endregion
#region Constructors
/// <summary>
/// Creates a new instance of WinkelTripel
/// </summary>
public WinkelTripel()
{
Name = "Winkel_Tripel";
Proj4Name = "wintri";
}
#endregion
#region Methods
/// <inheritdoc />
protected override void OnForward(double[] lp, double[] xy, int startIndex, int numPoints)
{
for (int i = startIndex; i < startIndex + numPoints; i++)
{
int phi = i * 2 + PHI;
int lam = i * 2 + LAMBDA;
int x = i * 2 + X;
int y = i * 2 + Y;
double c, d;
if ((d = Math.Acos(Math.Cos(lp[phi]) * Math.Cos(c = 0.5 * lp[lam]))) != 0)
{
xy[x] = 2 * d * Math.Cos(lp[phi]) * Math.Sin(c) * (xy[y] = 1 / Math.Sin(d));
xy[y] *= d * Math.Sin(lp[phi]);
}
else
xy[x] = xy[y] = 0;
xy[x] = (xy[x] + lp[lam] * _cosphi1) * 0.5;
xy[y] = (xy[y] + lp[phi]) * 0.5;
}
}
/// <summary>
/// Initializes the transform using the parameters from the specified coordinate system information
/// </summary>
/// <param name="projInfo">A ProjectionInfo class contains all the standard and custom parameters needed to initialize this transform</param>
protected override void OnInit(ProjectionInfo projInfo)
{
if (projInfo.StandardParallel1 != null)
{
_cosphi1 = Math.Cos(projInfo.Phi1);
if (_cosphi1 == 0) throw new ProjectionException(22);
}
else
{
/* 50d28' or acos(2/pi) */
_cosphi1 = 0.636619772367581343;
}
}
#endregion
}
} | 39.732673 | 150 | 0.496885 | [
"MIT"
] | sdrmaps/dotspatial | Source/DotSpatial.Projections/Transforms/WinkelTripel.cs | 4,013 | C# |
using Microsoft.EntityFrameworkCore.Migrations;
using System;
using System.Collections.Generic;
namespace SOH.Web.Migrations
{
public partial class ChangeToIdentityRole : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
}
protected override void Down(MigrationBuilder migrationBuilder)
{
}
}
}
| 19.3 | 71 | 0.69171 | [
"MIT"
] | nguyenlamlll/SaigonOperaHouse | SOH/SOH.Web/Data/Migrations/20180315034923_ChangeToIdentityRole.cs | 388 | C# |
//------------------------------------------------------------
// Game Framework
// Copyright © 2013-2019 Jiang Yin. All rights reserved.
// Homepage: http://gameframework.cn/
// Feedback: mailto:jiangyin@gameframework.cn
//------------------------------------------------------------
using GameFramework.Entity;
using System;
using UnityEngine;
namespace UnityGameFramework.Runtime
{
/// <summary>
/// 实体。
/// </summary>
public sealed class Entity : MonoBehaviour, IEntity
{
private int m_Id;
private string m_EntityAssetName;
private IEntityGroup m_EntityGroup;
private EntityLogic m_EntityLogic;
/// <summary>
/// 获取实体编号。
/// </summary>
public int Id
{
get
{
return m_Id;
}
}
/// <summary>
/// 获取实体资源名称。
/// </summary>
public string EntityAssetName
{
get
{
return m_EntityAssetName;
}
}
/// <summary>
/// 获取实体实例。
/// </summary>
public object Handle
{
get
{
return gameObject;
}
}
/// <summary>
/// 获取实体所属的实体组。
/// </summary>
public IEntityGroup EntityGroup
{
get
{
return m_EntityGroup;
}
}
/// <summary>
/// 获取实体逻辑。
/// </summary>
public EntityLogic Logic
{
get
{
return m_EntityLogic;
}
}
/// <summary>
/// 实体初始化。
/// </summary>
/// <param name="entityId">实体编号。</param>
/// <param name="entityAssetName">实体资源名称。</param>
/// <param name="entityGroup">实体所属的实体组。</param>
/// <param name="isNewInstance">是否是新实例。</param>
/// <param name="userData">用户自定义数据。</param>
public void OnInit(int entityId, string entityAssetName, IEntityGroup entityGroup, bool isNewInstance, object userData)
{
m_Id = entityId;
m_EntityAssetName = entityAssetName;
if (isNewInstance)
{
m_EntityGroup = entityGroup;
}
else if (m_EntityGroup != entityGroup)
{
Log.Error("Entity group is inconsistent for non-new-instance entity.");
return;
}
ShowEntityInfo showEntityInfo = (ShowEntityInfo)userData;
Type entityLogicType = showEntityInfo.EntityLogicType;
if (entityLogicType == null)
{
Log.Error("Entity logic type is invalid.");
return;
}
if (m_EntityLogic != null)
{
if (m_EntityLogic.GetType() == entityLogicType)
{
m_EntityLogic.enabled = true;
return;
}
Destroy(m_EntityLogic);
m_EntityLogic = null;
}
m_EntityLogic = gameObject.AddComponent(entityLogicType) as EntityLogic;
if (m_EntityLogic == null)
{
Log.Error("Entity '{0}' can not add entity logic.", entityAssetName);
return;
}
m_EntityLogic.OnInit(showEntityInfo.UserData);
}
/// <summary>
/// 实体回收。
/// </summary>
public void OnRecycle()
{
m_Id = 0;
m_EntityLogic.enabled = false;
}
/// <summary>
/// 实体显示。
/// </summary>
/// <param name="userData">用户自定义数据。</param>
public void OnShow(object userData)
{
ShowEntityInfo showEntityInfo = (ShowEntityInfo)userData;
m_EntityLogic.OnShow(showEntityInfo.UserData);
}
/// <summary>
/// 实体隐藏。
/// </summary>
public void OnHide(object userData)
{
m_EntityLogic.OnHide(userData);
}
/// <summary>
/// 实体附加子实体。
/// </summary>
/// <param name="childEntity">附加的子实体。</param>
/// <param name="userData">用户自定义数据。</param>
public void OnAttached(IEntity childEntity, object userData)
{
AttachEntityInfo attachEntityInfo = (AttachEntityInfo)userData;
m_EntityLogic.OnAttached(((Entity)childEntity).Logic, attachEntityInfo.ParentTransform, attachEntityInfo.UserData);
}
/// <summary>
/// 实体解除子实体。
/// </summary>
/// <param name="childEntity">解除的子实体。</param>
/// <param name="userData">用户自定义数据。</param>
public void OnDetached(IEntity childEntity, object userData)
{
m_EntityLogic.OnDetached(((Entity)childEntity).Logic, userData);
}
/// <summary>
/// 实体附加子实体。
/// </summary>
/// <param name="parentEntity">被附加的父实体。</param>
/// <param name="userData">用户自定义数据。</param>
public void OnAttachTo(IEntity parentEntity, object userData)
{
AttachEntityInfo attachEntityInfo = (AttachEntityInfo)userData;
m_EntityLogic.OnAttachTo(((Entity)parentEntity).Logic, attachEntityInfo.ParentTransform, attachEntityInfo.UserData);
}
/// <summary>
/// 实体解除子实体。
/// </summary>
/// <param name="parentEntity">被解除的父实体。</param>
/// <param name="userData">用户自定义数据。</param>
public void OnDetachFrom(IEntity parentEntity, object userData)
{
m_EntityLogic.OnDetachFrom(((Entity)parentEntity).Logic, userData);
}
/// <summary>
/// 实体轮询。
/// </summary>
/// <param name="elapseSeconds">逻辑流逝时间,以秒为单位。</param>
/// <param name="realElapseSeconds">真实流逝时间,以秒为单位。</param>
public void OnUpdate(float elapseSeconds, float realElapseSeconds)
{
m_EntityLogic.OnUpdate(elapseSeconds, realElapseSeconds);
}
}
}
| 28.905213 | 128 | 0.504181 | [
"MIT"
] | Iamdevelope/UnityGameFramework | Scripts/Runtime/Entity/Entity.cs | 6,570 | C# |
// Uncomment the following to provide samples for PageResult<T>. Must also add the Microsoft.AspNet.WebApi.OData
// package to your project.
////#define Handle_PageResultOfT
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net.Http.Headers;
using System.Reflection;
using System.Web;
using System.Web.Http;
using hms.entappsettings.webapi.Utils;
#if Handle_PageResultOfT
using System.Web.Http.OData;
#endif
namespace hms.entappsettings.webapi.Areas.HelpPage
{
/// <summary>
/// Use this class to customize the Help Page.
/// For example you can set a custom <see cref="System.Web.Http.Description.IDocumentationProvider"/> to supply the documentation
/// or you can provide the samples for the requests/responses.
/// </summary>
public static class HelpPageConfig
{
/// <summary>
///
/// </summary>
/// <param name="config"></param>
[SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters",
MessageId = "hms.entappsettings.webapi.Areas.HelpPage.TextSample.#ctor(System.String)",
Justification = "End users may choose to merge this string with existing localized resources.")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly",
MessageId = "bsonspec",
Justification = "Part of a URI.")]
public static void Register(HttpConfiguration config)
{
//// Uncomment the following to use the documentation from XML documentation file.
//config.SetDocumentationProvider(new XmlDocumentationProvider(HttpContext.Current.Server.MapPath("~/App_Data/XmlDocument.xml")));
config.SetDocumentationProvider(
new MultiXmlDocumentationProvider(
HttpContext.Current.Server.MapPath("~/App_Data/hms.entappsettings.webapi.xml"),
HttpContext.Current.Server.MapPath("~/App_Data/hms.entappsettings.contracts.xml")));
//// Uncomment the following to use "sample string" as the sample for all actions that have string as the body parameter or return type.
//// Also, the string arrays will be used for IEnumerable<string>. The sample objects will be serialized into different media type
//// formats by the available formatters.
//config.SetSampleObjects(new Dictionary<Type, object>
//{
// {typeof(string), "sample string"},
// {typeof(IEnumerable<string>), new string[]{"sample 1", "sample 2"}}
//});
// Extend the following to provide factories for types not handled automatically (those lacking parameterless
// constructors) or for which you prefer to use non-default property values. Line below provides a fallback
// since automatic handling will fail and GeneratePageResult handles only a single type.
#if Handle_PageResultOfT
config.GetHelpPageSampleGenerator().SampleObjectFactories.Add(GeneratePageResult);
#endif
// Extend the following to use a preset object directly as the sample for all actions that support a media
// type, regardless of the body parameter or return type. The lines below avoid display of binary content.
// The BsonMediaTypeFormatter (if available) is not used to serialize the TextSample object.
config.SetSampleForMediaType(
new TextSample("Binary JSON content. See http://bsonspec.org for details."),
new MediaTypeHeaderValue("application/bson"));
//// Uncomment the following to use "[0]=foo&[1]=bar" directly as the sample for all actions that support form URL encoded format
//// and have IEnumerable<string> as the body parameter or return type.
//config.SetSampleForType("[0]=foo&[1]=bar", new MediaTypeHeaderValue("application/x-www-form-urlencoded"), typeof(IEnumerable<string>));
//// Uncomment the following to use "1234" directly as the request sample for media type "text/plain" on the controller named "Values"
//// and action named "Put".
//config.SetSampleRequest("1234", new MediaTypeHeaderValue("text/plain"), "Values", "Put");
//// Uncomment the following to use the image on "../images/aspNetHome.png" directly as the response sample for media type "image/png"
//// on the controller named "Values" and action named "Get" with parameter "id".
//config.SetSampleResponse(new ImageSample("../images/aspNetHome.png"), new MediaTypeHeaderValue("image/png"), "Values", "Get", "id");
//// Uncomment the following to correct the sample request when the action expects an HttpRequestMessage with ObjectContent<string>.
//// The sample will be generated as if the controller named "Values" and action named "Get" were having string as the body parameter.
//config.SetActualRequestType(typeof(string), "Values", "Get");
//// Uncomment the following to correct the sample response when the action returns an HttpResponseMessage with ObjectContent<string>.
//// The sample will be generated as if the controller named "Values" and action named "Post" were returning a string.
//config.SetActualResponseType(typeof(string), "Values", "Post");
}
#if Handle_PageResultOfT
private static object GeneratePageResult(HelpPageSampleGenerator sampleGenerator, Type type)
{
if (type.IsGenericType)
{
Type openGenericType = type.GetGenericTypeDefinition();
if (openGenericType == typeof(PageResult<>))
{
// Get the T in PageResult<T>
Type[] typeParameters = type.GetGenericArguments();
Debug.Assert(typeParameters.Length == 1);
// Create an enumeration to pass as the first parameter to the PageResult<T> constuctor
Type itemsType = typeof(List<>).MakeGenericType(typeParameters);
object items = sampleGenerator.GetSampleObject(itemsType);
// Fill in the other information needed to invoke the PageResult<T> constuctor
Type[] parameterTypes = new Type[] { itemsType, typeof(Uri), typeof(long?), };
object[] parameters = new object[] { items, null, (long)ObjectGenerator.DefaultCollectionSize, };
// Call PageResult(IEnumerable<T> items, Uri nextPageLink, long? count) constructor
ConstructorInfo constructor = type.GetConstructor(parameterTypes);
return constructor.Invoke(parameters);
}
}
return null;
}
#endif
}
} | 56.601626 | 149 | 0.662166 | [
"Apache-2.0"
] | nrogoff/EnterpriseAppSettings | src/dotNET/hms.entappsettings.webapi/hms.entappsettings.webapi/Areas/HelpPage/App_Start/HelpPageConfig.cs | 6,962 | C# |
// Copyright (c) Microsoft Corporation
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using System;
using System.Linq;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Microsoft.Xbox.Services.ContextualSearch
{
public class ContextualSearchGameClipThumbnail
{
public ContextualSearchGameClipThumbnailType ThumbnailType
{
get;
private set;
}
public ulong FileSize
{
get;
private set;
}
public Uri Url
{
get;
private set;
}
}
}
| 19.735294 | 101 | 0.606557 | [
"MIT"
] | Barallob/xbox-live-unity-plugin | CSharpSource/Source/api/ContextualSearch/ContextualSearchGameClipThumbnail.cs | 671 | C# |
public abstract class Behavior : IBehavior
{
protected Behavior()
{
this.ToDelayRecurrentEffect = true;
}
public int SourceInitialDamage { get; private set; }
public bool IsTriggered { get; set; }
public bool ToDelayRecurrentEffect { get; set; }
public abstract void ApplyTriggerEffect(Blob source);
public void Trigger(Blob source)
{
this.SourceInitialDamage = source.Damage;
this.IsTriggered = true;
this.ApplyTriggerEffect(source);
}
public abstract void ApplyRecurrentEffect(Blob source);
} | 24.041667 | 59 | 0.679376 | [
"MIT"
] | mayapeneva/C-Sharp-OOP-Advanced | 07.SOLID/Exer_Blobs/Entities/Behaviors/Behavior.cs | 579 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.