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 SerdesNet;
namespace UAlbion.Formats.Assets.Flic
{
public class UnknownChunk : FlicChunk
{
public byte[] Bytes { get; private set; }
public override FlicChunkType Type { get; }
public UnknownChunk(FlicChunkType type) => Type = type;
public override string ToString() => $"Unknown:{Type} ({Bytes.Length} bytes)";
protected override uint LoadChunk(uint length, ISerializer s)
{
if (s == null) throw new ArgumentNullException(nameof(s));
Bytes = s.Bytes(null, null, (int)length);
return (uint)Bytes.Length;
}
}
}
| 31.8 | 86 | 0.619497 | [
"MIT"
] | Metibor/ualbion | src/Formats/Assets/Flic/UnknownChunk.cs | 638 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace CMS.ViewModels
{
public class OrdersViewModel
{
public List<OrderViewModel> Orders { get; set; }
}
public class OrderViewModel
{
public int Id { get; set; }
public int UserId { get; set; }
public string Username { get; set; }
public int StatusId { get; set; }
public string OrderStatus { get; set; }
public int TotalPrice { get; set; }
public DateTime CreatedAt { get; set; }
}
}
| 24.083333 | 56 | 0.621107 | [
"Apache-2.0"
] | izzeldeen/Youth | CMS/ViewModels/OrdersViewModel.cs | 580 | C# |
using System.Diagnostics.CodeAnalysis;
namespace BookWeb.Client
{
[ExcludeFromCodeCoverage]
public class CustomIcons
{
public static string BlazorHero { get; } = "<path d=\"M 37.00,90.00 C 37.00,90.00 328.90,90.00 328.90,90.00 328.90,90.00 328.90,410.00 328.90,410.00 328.90,410.00 37.00,410.00 37.00,410.00 37.00,410.00 37.00,90.00 37.00,90.00 Z M 381.49,90.75 C 381.49,90.75 464.00,90.75 464.00,90.75 464.00,90.75 464.00,410.00 464.00,410.00 464.00,410.00 381.49,410.00 381.49,410.00 381.49,410.00 381.49,280.80 381.49,280.80 381.49,280.80 337.37,280.80 337.37,280.80 337.37,280.80 337.37,220.44 337.37,220.44 337.37,220.44 381.49,220.44 381.49,220.44 381.49,220.44 381.49,90.75 381.49,90.75 Z M 119.51,150.36 C 119.51,150.36 119.51,220.44 119.51,220.44 119.51,220.44 236.91,220.44 236.91,220.44 236.91,220.44 236.91,280.80 236.91,280.80 236.91,280.80 119.51,280.80 119.51,280.80 119.51,280.80 119.51,349.64 119.51,349.64 119.51,349.64 246.39,349.64 246.39,349.64 246.39,349.64 246.39,150.36 246.39,150.36 246.39,150.36 119.51,150.36 119.51,150.36 Z\"/>";
}
} | 108.7 | 946 | 0.694572 | [
"MIT"
] | seantrace/BookWeb | BookWeb/Client/CustomIcons.cs | 1,089 | C# |
using Sandbox.Definitions;
using Sandbox.Game.World;
using VRage.Game;
namespace avaness.SkyboxPlugin
{
public class Skybox
{
public WorkshopInfo Info { get; }
private readonly MyObjectBuilder_EnvironmentDefinition definition;
public static Skybox Default { get; } = new Skybox(null, new MyObjectBuilder_EnvironmentDefinition());
public Skybox(WorkshopInfo workshop, MyObjectBuilder_EnvironmentDefinition definition)
{
Info = workshop;
this.definition = definition;
}
public void Load()
{
MyObjectBuilder_EnvironmentDefinition ob = definition;
MyEnvironmentDefinition def = MySector.EnvironmentDefinition;
if (def == null)
return;
def.EnvironmentTexture = ob.EnvironmentTexture;
def.EnvironmentOrientation = ob.EnvironmentOrientation;
def.SunProperties = ob.SunProperties;
}
public override string ToString()
{
return "Skybox:'" + Info.Title + "'";
}
}
}
| 28.076923 | 110 | 0.629224 | [
"Unlicense"
] | austinvaness/SkyboxPlugin | SkyboxPlugin/Skybox.cs | 1,097 | C# |
using System;
using System.Collections.Generic;
using System.IO;
namespace RT.Serialization
{
/// <summary>
/// Used by <see cref="Classify"/> to serialize and deserialize objects. Implement this to enable serialization to a
/// new format.</summary>
/// <typeparam name="TElement">
/// Type of the serialized form of an object or any sub-object.</typeparam>
public interface IClassifyFormat<TElement>
{
/// <summary>
/// Reads the serialized form from a stream.</summary>
/// <param name="stream">
/// Stream to read from.</param>
/// <returns>
/// The serialized form read from the stream.</returns>
TElement ReadFromStream(Stream stream);
/// <summary>
/// Writes the serialized form to a stream.</summary>
/// <param name="element">
/// Serialized form to write to the stream.</param>
/// <param name="stream">
/// Stream to write to.</param>
void WriteToStream(TElement element, Stream stream);
/// <summary>
/// Determines whether the specified element represents a <c>null</c> value.</summary>
/// <remarks>
/// This should return <c>true</c> if the element was generated by <see cref="FormatNullValue"/> and <c>false</c>
/// otherwise.</remarks>
bool IsNull(TElement element);
/// <summary>
/// Called when Classify expects the element to be one of the following types: <c>byte</c>, <c>sbyte</c>,
/// <c>short</c>, <c>ushort</c>, <c>int</c>, <c>uint</c>, <c>long</c>, <c>ulong</c>, <see
/// cref="System.Numerics.BigInteger"/>, <c>decimal</c>, <c>float</c>, <c>double</c>, <c>bool</c>, <c>char</c>,
/// <c>string</c>, <see cref="DateTime"/> or an enum type. The implementation is free to return a value of any of
/// these types, and Classify will automatically use <see cref="ExactConvert"/> to convert the value to the
/// required target type.</summary>
/// <remarks>
/// This should decode values passed into <see cref="FormatSimpleValue"/>, although it is acceptable if the type
/// has changed, as long as <see cref="ExactConvert"/> will convert the decoded value back to the original value.</remarks>
object GetSimpleValue(TElement element);
/// <summary>
/// Decodes the serialized form of the element type itself.</summary>
/// <remarks>
/// This should do the reverse of <see cref="FormatSelfValue"/>.</remarks>
TElement GetSelfValue(TElement element);
/// <summary>
/// Decodes a list.</summary>
/// <param name="element">
/// The element to decode.</param>
/// <param name="tupleSize">
/// If null, a variable-length list is expected; otherwise, a fixed-length list (a tuple) is expected.</param>
/// <returns>
/// A collection containing the sub-elements contained in the list. The collection returned need not have the size
/// specified by <paramref name="tupleSize"/>.</returns>
/// <remarks>
/// This should do the reverse of <see cref="FormatList"/>.</remarks>
IEnumerable<TElement> GetList(TElement element, int? tupleSize);
/// <summary>
/// Decodes a key-value pair.</summary>
/// <param name="element">
/// The element to decode.</param>
/// <param name="key">
/// Receives the key part of the pair.</param>
/// <param name="value">
/// Receives the value part of the pair.</param>
/// <remarks>
/// This should do the reverse of <see cref="FormatKeyValuePair"/>.</remarks>
void GetKeyValuePair(TElement element, out TElement key, out TElement value);
/// <summary>
/// Decodes a dictionary.</summary>
/// <param name="element">
/// The element to decode.</param>
/// <returns>
/// A collection containing the key/value pairs in the dictionary. The keys in the returned collection are
/// expected to be convertible to the correct type using <see cref="ExactConvert"/>.</returns>
/// <remarks>
/// This should decode values passed into <see cref="FormatDictionary"/>, although it is acceptable if the type of
/// the keys has changed. For example, all keys may be returned as <c>string</c>, as long as <see
/// cref="ExactConvert"/> will convert that <c>string</c> back to the original value.</remarks>
IEnumerable<KeyValuePair<object, TElement>> GetDictionary(TElement element);
/// <summary>
/// Decodes a piece of raw data.</summary>
/// <param name="element">
/// The element to decode.</param>
/// <returns>
/// The raw data decoded.</returns>
/// <remarks>
/// This should decode values passed into <see cref="FormatRawData"/>.</remarks>
byte[] GetRawData(TElement element);
/// <summary>
/// Determines whether the element is an object and contains a sub-element for the specified field.</summary>
/// <param name="element">
/// The element that may represent an object.</param>
/// <param name="fieldName">
/// The name of the field sought.</param>
/// <param name="declaringType">
/// The assembly-qualified name of the type that declares the field. (This can be null if the field name is unique
/// within the type of the object being deserialized.)</param>
/// <returns>
/// <c>true</c> if <paramref name="element"/> is an object and has the specified field; <c>false</c> otherwise.</returns>
/// <remarks>
/// This should return <c>true</c> if <paramref name="element"/> represents an element generated by <see
/// cref="FormatObject"/> in which the field with the specified <paramref name="fieldName"/> was present.</remarks>
bool HasField(TElement element, string fieldName, string declaringType);
/// <summary>
/// Returns the sub-element pertaining to the specified field.</summary>
/// <param name="element">
/// The element that represents an object.</param>
/// <param name="fieldName">
/// The name of the field within the object whose sub-element is sought.</param>
/// <param name="declaringType">
/// The assembly-qualified name of the type that declares the field. (This can be null if the field name is unique
/// within the type of the object being deserialized.)</param>
/// <returns>
/// The sub-element for the specified field.</returns>
/// <remarks>
/// <para>
/// Classify calls <see cref="HasField"/> first for each field and only calls this method if <see
/// cref="HasField"/> returned true.</para>
/// <para>
/// This should return the same element that was passed into <see cref="FormatObject"/> for the same <paramref
/// name="fieldName"/>.</para></remarks>
TElement GetField(TElement element, string fieldName, string declaringType);
/// <summary>
/// Determines the type of the object stored in the specified element.</summary>
/// <param name="element">
/// The element that represents an object.</param>
/// <param name="isFullType">
/// Receives a value indicating whether the type is a fully-qualified type name or not. This value is ignored if
/// the method returns <c>null</c>.</param>
/// <returns>
/// <c>null</c> if no type information was persisted in this element; otherwise, the decoded type name.</returns>
/// <remarks>
/// This should decode the information (the string and the boolean) encoded by <see cref="FormatWithType"/>.</remarks>
string GetType(TElement element, out bool isFullType);
/// <summary>
/// Determines whether this element represents a reference to another object in the same serialized graph.</summary>
/// <param name="element">
/// The element to decode.</param>
/// <returns>
/// <c>true</c> if this element represents such a reference; <c>false</c> otherwise.</returns>
/// <remarks>
/// This should recognize elements generated by <see cref="FormatReference"/>.</remarks>
bool IsReference(TElement element);
/// <summary>
/// Determines whether this element represents an object that can be referred to by a reference element.</summary>
/// <param name="element">
/// The element to decode.</param>
/// <returns>
/// <c>true</c> if this element is referable; <c>false</c> otherwise.</returns>
/// <remarks>
/// This should recognize elements generated by <see cref="FormatReferable"/>.</remarks>
bool IsReferable(TElement element);
/// <summary>
/// Returns the ID encoded in this element. This is called only if <see cref="IsReference"/> or <see
/// cref="IsReferable"/> returned <c>true</c>.</summary>
/// <param name="element">
/// The element to decode.</param>
/// <returns>
/// The ID encoded in this element.</returns>
/// <remarks>
/// This should return the same ID that was passed into <see cref="FormatReference"/> or <see
/// cref="FormatReferable"/>.</remarks>
int GetReferenceID(TElement element);
/// <summary>
/// Generates an element that represents a <c>null</c> value.</summary>
/// <returns>
/// The serialized form of the <c>null</c> value.</returns>
/// <remarks>
/// The returned element should be recognized by <see cref="IsNull"/>.</remarks>
TElement FormatNullValue();
/// <summary>
/// Generates an element that represents a <c>byte</c>, <c>sbyte</c>, <c>short</c>, <c>ushort</c>, <c>int</c>,
/// <c>uint</c>, <c>long</c>, <c>ulong</c>, <see cref="System.Numerics.BigInteger"/>, <c>decimal</c>,
/// <c>float</c>, <c>double</c>, <c>bool</c>, <c>char</c>, <c>string</c>, <see cref="DateTime"/> or an enum value.</summary>
/// <param name="value">
/// The value to encode.</param>
/// <returns>
/// The serialized form of the <paramref name="value"/>.</returns>
/// <remarks>
/// The returned element should be recognized by <see cref="GetSimpleValue"/>, but need not necessarily decode to
/// the same type, as long as <see cref="ExactConvert"/> will convert it to the correct value.</remarks>
TElement FormatSimpleValue(object value);
/// <summary>
/// Generates an element that represents a value of the same type as serialized elements.</summary>
/// <param name="value">
/// The value to encode.</param>
/// <returns>
/// The serialized form of the <paramref name="value"/>.</returns>
/// <remarks>
/// The returned element should be recognized by <see cref="GetSelfValue"/>.</remarks>
TElement FormatSelfValue(TElement value);
/// <summary>
/// Generates an element that represents a list.</summary>
/// <param name="isTuple">
/// Specifies whether we are serializing a variable-length list, or a tuple (fixed-length list).</param>
/// <param name="values">
/// The values to put into list form.</param>
/// <returns>
/// The serialized list.</returns>
/// <remarks>
/// The returned element should be recognized by <see cref="GetList"/>.</remarks>
TElement FormatList(bool isTuple, IEnumerable<TElement> values);
/// <summary>
/// Generates an element that represents a key-value pair.</summary>
/// <param name="key">
/// The element that represents the key.</param>
/// <param name="value">
/// The element that represents the value.</param>
/// <returns>
/// The serialized key-value pair.</returns>
/// <remarks>
/// The returned element should be recognized by <see cref="GetKeyValuePair"/>.</remarks>
TElement FormatKeyValuePair(TElement key, TElement value);
/// <summary>
/// Generates an element that represents a dictionary.</summary>
/// <param name="values">
/// The key-value pairs that compose the dictionary. The keys may be <c>string</c>s, integers, or enum values.</param>
/// <returns>
/// The serialized dictionary.</returns>
/// <remarks>
/// The returned element should be recognized by <see cref="GetDictionary"/>.</remarks>
TElement FormatDictionary(IEnumerable<KeyValuePair<object, TElement>> values);
/// <summary>
/// Generates an element that represents an object with fields.</summary>
/// <param name="fields">
/// A collection of objects containing each fields’ identifying information and serialized value.</param>
/// <returns>
/// The serialized object.</returns>
/// <remarks>
/// The returned element should be recognized by <see cref="HasField"/> and <see cref="GetField"/>, irrespective
/// of the order in which the fields are provided in <paramref name="fields"/>.</remarks>
TElement FormatObject(IEnumerable<ObjectFieldInfo<TElement>> fields);
/// <summary>
/// Generates an element that represents raw data (<c>byte[]</c>).</summary>
/// <param name="value">
/// The raw data to store.</param>
/// <returns>
/// The serialized raw data.</returns>
/// <remarks>
/// The returned element should be recognized by <see cref="GetRawData"/>.</remarks>
TElement FormatRawData(byte[] value);
/// <summary>
/// Generates an element that represents a reference to another object within the same serialized object graph.</summary>
/// <param name="refId">
/// The reference ID.</param>
/// <returns>
/// An element that represents a reference to another object with the specified <paramref name="refId"/>.</returns>
/// <remarks>
/// The returned element should be recognized by <see cref="IsReference"/>.</remarks>
TElement FormatReference(int refId);
/// <summary>
/// Converts an existing element (which may represent, for example, an object, list or dictionary) into one that
/// can be referred to by a reference (see <see cref="FormatReference"/>).</summary>
/// <param name="element">
/// The original element to be converted.</param>
/// <param name="refId">
/// The reference ID.</param>
/// <returns>
/// A representation of the original <paramref name="element"/>, which additionally encodes the referable
/// <paramref name="refId"/>.</returns>
/// <remarks>
/// The returned element should be recognized by <see cref="IsReferable"/> as well as all the other methods that
/// would have also recognized the original <paramref name="element"/>.</remarks>
TElement FormatReferable(TElement element, int refId);
/// <summary>
/// Converts an existing element (which may represent, for example, an object, list or dictionary) into one that
/// additionally knows its type.</summary>
/// <param name="element">
/// The original element to be converted.</param>
/// <param name="type">
/// A string that identifies the type of the object.</param>
/// <param name="isFullType">
/// A value indicating whether this is a fully-qualified type name or not.</param>
/// <returns>
/// A representation of the original <paramref name="element"/>, which additionally encodes the <paramref
/// name="type"/>.</returns>
/// <remarks>
/// The returned element should be recognized by <see cref="GetType"/> as well as all the other methods that would
/// have also recognized the original <paramref name="element"/>.</remarks>
TElement FormatWithType(TElement element, string type, bool isFullType);
/// <summary>
/// Throws an InvalidOperationException informing the user that an element is a reference (<see
/// cref="IsReference"/>) but the corresponding referable has not been encountered while deserializing.</summary>
/// <param name="refID">
/// The numeric reference ID.</param>
void ThrowMissingReferable(int refID);
}
/// <summary>
/// Encapsulates information about a field in an object and its value.</summary>
/// <typeparam name="TElement">
/// Type of serialized form used in <see cref="IClassifyFormat{TElement}"/>.</typeparam>
public sealed class ObjectFieldInfo<TElement>
{
/// <summary>The name of the field.</summary>
public string FieldName { get; private set; }
/// <summary>
/// The assembly-qualified name of the type that declares the field, or null if the name of the field is unique
/// within the object being serialized.</summary>
public string DeclaringType { get; private set; }
/// <summary>The value of the field.</summary>
public TElement Value { get; private set; }
/// <summary>
/// Constructor.</summary>
/// <param name="fieldName">
/// The name of the field.</param>
/// <param name="declaringType">
/// The assembly-qualified name of the type that declares the field, or null if the name of the field is unique
/// within the object being serialized.</param>
/// <param name="value">
/// The value of the field.</param>
public ObjectFieldInfo(string fieldName, string declaringType, TElement value)
{
FieldName = fieldName;
DeclaringType = declaringType;
Value = value;
}
}
}
| 53.196023 | 136 | 0.58964 | [
"MIT"
] | Emik03/RT.Util | RT.Serialization/IClassifyFormat.cs | 18,729 | C# |
namespace Player.BuildTower {
public class EventUpdatePlayerGold {
public readonly int amount;
public EventUpdatePlayerGold(int amount) {
this.amount = amount;
}
}
} | 23.444444 | 50 | 0.625592 | [
"MIT"
] | Exoduz85/SelloutDefence | Assets/Scripts/Player/BuildTower/EventUpdatePlayerGold.cs | 213 | C# |
using Grpc.Core;
using Grpc.Net.Client;
using MachineNodes.Console.Service;
using Microsoft.Extensions.Configuration;
using System;
using System.Device.Gpio;
using System.Device.Pwm.Drivers;
using System.IO;
using System.Net.Http;
Console.WriteLine("Service is starting");
// Configuration stuff
var config = new ConfigurationBuilder()
.AddJsonFile(Path.Combine(Environment.CurrentDirectory, "appsettings.json"), true)
.AddCommandLine(args)
.Build();
var lampBinding = config.GetSection(ConfigProperties.LampBindings).Get<LampOptions>();
// Bootstrapping LEDs
GpioController gpioController = new GpioController(PinNumberingScheme.Logical);
SoftwarePwmChannel pwmRed = new(lampBinding.Red, 500, dutyCycle: 1,controller: gpioController, usePrecisionTimer:true);
pwmRed.Start();
SoftwarePwmChannel pwmGreen = new(lampBinding.Green, 500, dutyCycle: 1, controller: gpioController, usePrecisionTimer: true);
pwmGreen.Start();
SoftwarePwmChannel pwmBlue = new(lampBinding.Blue, 500, dutyCycle: 1, controller: gpioController, usePrecisionTimer: true);
pwmBlue.Start();
var httpHandler = new HttpClientHandler();
// Return true to allow certificates that are untrusted/invalid
httpHandler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;
//Bootstrapping gRPC Connection
var connection = GrpcChannel.ForAddress(config[ConfigProperties.Address], new GrpcChannelOptions
{
HttpHandler = httpHandler
});
var client = new LightControlService.LightControlServiceClient(connection);
Console.WriteLine("Service is started");
//Waiting for light Updates
var lightUpdateResult = client.GetLightUpdates(new ConnectionParameters { ClientName = config[ConfigProperties.ClientName] });
await foreach (var lightUpdate in lightUpdateResult.ResponseStream.ReadAllAsync())
{
Console.WriteLine($"Color Update: rgb({lightUpdate.Red}, {lightUpdate.Green}, {lightUpdate.Blue})");
pwmRed.DutyCycle = lightUpdate.Red / 255d;
pwmGreen.DutyCycle = lightUpdate.Green / 255d;
pwmBlue.DutyCycle = lightUpdate.Blue / 255d;
Console.WriteLine($"Set DutyCycle: [R:{pwmRed.DutyCycle},G:{pwmGreen.DutyCycle},B:{pwmBlue.DutyCycle}]");
}
Console.WriteLine("Service finished");
public class LampOptions {
public int Red { get; set; }
public int Green { get; set; }
public int Blue { get; set; }
}
static class ConfigProperties
{
public const string Address = nameof(Address);
public const string ClientName = nameof(ClientName);
public const string LampBindings = nameof(LampBindings);
}
| 38 | 126 | 0.779025 | [
"MIT"
] | maSchoeller/aswe-prototype | machinenodes/MachineNodes.Console/Program.cs | 2,586 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class thiefCtrl : MonoBehaviour
{
Animator anim;
int idleHash = Animator.StringToHash("idle_thief");
int walkumpHash = Animator.StringToHash("walk_thief");
int attackHash = Animator.StringToHash("attack_thief");
int runStateHash = Animator.StringToHash("Base Layer.Run");
// Start is called before the first frame update
void Start()
{
anim = GetComponent<Animator>();
anim.SetTrigger(idleHash);
}
// Update is called once per frame
void Update()
{
//float move = Input.GetAxis("Vertical");
//anim.SetFloat("Speed", move);
AnimatorStateInfo stateInfo = anim.GetCurrentAnimatorStateInfo(0);
if (Input.GetKeyDown(KeyCode.Space))
{
print("space");
print("stateInfo.nameHashaa" + stateInfo.fullPathHash);
anim.SetTrigger(attackHash);
}
//anim.SetTrigger(jumpHash);
}
}
| 26.789474 | 74 | 0.644401 | [
"MIT"
] | AhsanSN/War-Heroes | War Heroes/Assets/animCtrl/thiefCtrl.cs | 1,020 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text.RegularExpressions;
using Websms;
namespace ASPExample
{
public partial class Default : System.Web.UI.Page
{
private static string URL = "https://api.websms.com/json";
private static uint MAX_SMS_PER_MESSAGE = 1;
private static bool TEST_MESSAGE = true;
// webmsms.com username
private static string USERNAME = "";
// websms.com password
private static string PASSWORD = "";
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Validate_Recipient(object source, ServerValidateEventArgs args)
{
Regex regx = new Regex("^\\d{1,20}$");
if (Recipient.Text.Length == 0)
{
RecipientValidator.ErrorMessage = "Required";
args.IsValid = false;
}
else if (regx.IsMatch(Recipient.Text) == false)
{
RecipientValidator.ErrorMessage = "Not a valid number";
args.IsValid = false;
}
else
{
args.IsValid = true;
}
}
protected void Send_Click(object sender, EventArgs e)
{
Page.Validate();
if (!Page.IsValid)
{
Output.Style.Add("color", "black");
Output.Text = "-";
return;
}
// Create the client.
SmsClient client = new SmsClient(USERNAME, PASSWORD, URL);
// Create new message with one recipient.
TextMessage textMessage = new TextMessage(Int64.Parse(Recipient.Text), Text.Text);
try
{
// Send the message.
MessageResponse response = client.Send(textMessage, MAX_SMS_PER_MESSAGE, TEST_MESSAGE);
// Print the response.
Output.Style.Add("color", "black");
Output.Text = response.statusMessage;
Text.Text = "";
}
catch (Exception ex)
{
// Handle exceptions.
Output.Style.Add("color", "red");
Output.Text = ex.Message;
}
}
}
} | 30.62963 | 104 | 0.506651 | [
"MIT"
] | websms-com/websmscom-csharp | examples/ASP.NET/Default.aspx.cs | 2,483 | 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 Microsoft.ML.Data;
using Microsoft.ML.Runtime;
using Microsoft.ML.Trainers.LightGbm;
namespace Microsoft.ML
{
/// <summary>
/// Collection of extension methods for the <see cref="RegressionCatalog.RegressionTrainers"/>,
/// <see cref="BinaryClassificationCatalog.BinaryClassificationTrainers"/>, <see cref="RankingCatalog.RankingTrainers"/>,
/// and <see cref="MulticlassClassificationCatalog.MulticlassClassificationTrainers"/> catalogs.
/// </summary>
public static class LightGbmExtensions
{
/// <summary>
/// Create <see cref="LightGbmRegressionTrainer"/>, which predicts a target using a gradient boosting decision tree regression model.
/// </summary>
/// <param name="catalog">The <see cref="RegressionCatalog"/>.</param>
/// <param name="labelColumnName">The name of the label column. The column data must be <see cref="System.Single"/>.</param>
/// <param name="featureColumnName">The name of the feature column. The column data must be a known-sized vector of <see cref="System.Single"/>.</param>
/// <param name="exampleWeightColumnName">The name of the example weight column (optional).</param>
/// <param name="numberOfLeaves">The maximum number of leaves in one tree.</param>
/// <param name="minimumExampleCountPerLeaf">The minimal number of data points required to form a new tree leaf.</param>
/// <param name="learningRate">The learning rate.</param>
/// <param name="numberOfIterations">The number of boosting iterations. A new tree is created in each iteration, so this is equivalent to the number of trees.</param>
/// <example>
/// <format type="text/markdown">
/// <]
/// ]]>
/// </format>
/// </example>
public static LightGbmRegressionTrainer LightGbm(this RegressionCatalog.RegressionTrainers catalog,
string labelColumnName = DefaultColumnNames.Label,
string featureColumnName = DefaultColumnNames.Features,
string exampleWeightColumnName = null,
int? numberOfLeaves = null,
int? minimumExampleCountPerLeaf = null,
double? learningRate = null,
int numberOfIterations = Defaults.NumberOfIterations)
{
Contracts.CheckValue(catalog, nameof(catalog));
var env = CatalogUtils.GetEnvironment(catalog);
return new LightGbmRegressionTrainer(env, labelColumnName, featureColumnName, exampleWeightColumnName, numberOfLeaves, minimumExampleCountPerLeaf, learningRate, numberOfIterations);
}
/// <summary>
/// Create <see cref="LightGbmRegressionTrainer"/> using advanced options, which predicts a target using a gradient boosting decision tree regression model.
/// </summary>
/// <param name="catalog">The <see cref="RegressionCatalog"/>.</param>
/// <param name="options">Trainer options.</param>
/// <example>
/// <format type="text/markdown">
/// <]
/// ]]>
/// </format>
/// </example>
public static LightGbmRegressionTrainer LightGbm(this RegressionCatalog.RegressionTrainers catalog,
LightGbmRegressionTrainer.Options options)
{
Contracts.CheckValue(catalog, nameof(catalog));
var env = CatalogUtils.GetEnvironment(catalog);
return new LightGbmRegressionTrainer(env, options);
}
/// <summary>
/// Create <see cref="LightGbmBinaryTrainer"/>, which predicts a target using a gradient boosting decision tree binary classification.
/// </summary>
/// <param name="catalog">The <see cref="BinaryClassificationCatalog"/>.</param>
/// <param name="labelColumnName">The name of the label column. The column data must be <see cref="System.Boolean"/>.</param>
/// <param name="featureColumnName">The name of the feature column. The column data must be a known-sized vector of <see cref="System.Single"/>.</param>
/// <param name="exampleWeightColumnName">The name of the example weight column (optional).</param>
/// <param name="numberOfLeaves">The maximum number of leaves in one tree.</param>
/// <param name="minimumExampleCountPerLeaf">The minimal number of data points required to form a new tree leaf.</param>
/// <param name="learningRate">The learning rate.</param>
/// <param name="numberOfIterations">The number of boosting iterations. A new tree is created in each iteration, so this is equivalent to the number of trees.</param>
/// <example>
/// <format type="text/markdown">
/// <]
/// ]]>
/// </format>
/// </example>
public static LightGbmBinaryTrainer LightGbm(this BinaryClassificationCatalog.BinaryClassificationTrainers catalog,
string labelColumnName = DefaultColumnNames.Label,
string featureColumnName = DefaultColumnNames.Features,
string exampleWeightColumnName = null,
int? numberOfLeaves = null,
int? minimumExampleCountPerLeaf = null,
double? learningRate = null,
int numberOfIterations = Defaults.NumberOfIterations)
{
Contracts.CheckValue(catalog, nameof(catalog));
var env = CatalogUtils.GetEnvironment(catalog);
return new LightGbmBinaryTrainer(env, labelColumnName, featureColumnName, exampleWeightColumnName, numberOfLeaves, minimumExampleCountPerLeaf, learningRate, numberOfIterations);
}
/// <summary>
/// Create <see cref="LightGbmBinaryTrainer"/> with advanced options, which predicts a target using a gradient boosting decision tree binary classification.
/// </summary>
/// <param name="catalog">The <see cref="BinaryClassificationCatalog"/>.</param>
/// <param name="options">Trainer options.</param>
/// <example>
/// <format type="text/markdown">
/// <]
/// ]]>
/// </format>
/// </example>
public static LightGbmBinaryTrainer LightGbm(this BinaryClassificationCatalog.BinaryClassificationTrainers catalog,
LightGbmBinaryTrainer.Options options)
{
Contracts.CheckValue(catalog, nameof(catalog));
var env = CatalogUtils.GetEnvironment(catalog);
return new LightGbmBinaryTrainer(env, options);
}
/// <summary>
/// Create <see cref="LightGbmRankingTrainer"/>, which predicts a target using a gradient boosting decision tree ranking model.
/// </summary>
/// <param name="catalog">The <see cref="RankingCatalog"/>.</param>
/// <param name="labelColumnName">The name of the label column. The column data must be <see cref="System.Single"/> or <see cref="KeyDataViewType"/>.</param>
/// <param name="featureColumnName">The name of the feature column. The column data must be a known-sized vector of <see cref="System.Single"/>.</param>
/// <param name="rowGroupColumnName">The name of the group column.</param>
/// <param name="exampleWeightColumnName">The name of the example weight column (optional).</param>
/// <param name="numberOfLeaves">The maximum number of leaves in one tree.</param>
/// <param name="minimumExampleCountPerLeaf">The minimal number of data points required to form a new tree leaf.</param>
/// <param name="learningRate">The learning rate.</param>
/// <param name="numberOfIterations">The number of boosting iterations. A new tree is created in each iteration, so this is equivalent to the number of trees.</param>
/// <example>
/// <format type="text/markdown">
/// <]
/// ]]>
/// </format>
/// </example>
public static LightGbmRankingTrainer LightGbm(this RankingCatalog.RankingTrainers catalog,
string labelColumnName = DefaultColumnNames.Label,
string featureColumnName = DefaultColumnNames.Features,
string rowGroupColumnName = DefaultColumnNames.GroupId,
string exampleWeightColumnName = null,
int? numberOfLeaves = null,
int? minimumExampleCountPerLeaf = null,
double? learningRate = null,
int numberOfIterations = Defaults.NumberOfIterations)
{
Contracts.CheckValue(catalog, nameof(catalog));
var env = CatalogUtils.GetEnvironment(catalog);
return new LightGbmRankingTrainer(env, labelColumnName, featureColumnName, rowGroupColumnName, exampleWeightColumnName,
numberOfLeaves, minimumExampleCountPerLeaf, learningRate, numberOfIterations);
}
/// <summary>
/// Create <see cref="LightGbmRankingTrainer"/> with advanced options, which predicts a target using a gradient boosting decision tree ranking model.
/// </summary>
/// <param name="catalog">The <see cref="RankingCatalog"/>.</param>
/// <param name="options">Trainer options.</param>
/// <example>
/// <format type="text/markdown">
/// <]
/// ]]>
/// </format>
/// </example>
public static LightGbmRankingTrainer LightGbm(this RankingCatalog.RankingTrainers catalog,
LightGbmRankingTrainer.Options options)
{
Contracts.CheckValue(catalog, nameof(catalog));
var env = CatalogUtils.GetEnvironment(catalog);
return new LightGbmRankingTrainer(env, options);
}
/// <summary>
/// Create <see cref="LightGbmMulticlassTrainer"/>, which predicts a target using a gradient boosting decision tree multiclass classification model.
/// </summary>
/// <param name="catalog">The <see cref="MulticlassClassificationCatalog"/>.</param>
/// <param name="labelColumnName">The name of the label column. The column data must be <see cref="KeyDataViewType"/>.</param>
/// <param name="featureColumnName">The name of the feature column. The column data must be a known-sized vector of <see cref="System.Single"/>.</param>
/// <param name="exampleWeightColumnName">The name of the example weight column (optional).</param>
/// <param name="numberOfLeaves">The maximum number of leaves in one tree.</param>
/// <param name="minimumExampleCountPerLeaf">The minimal number of data points required to form a new tree leaf.</param>
/// <param name="learningRate">The learning rate.</param>
/// <param name="numberOfIterations">The number of boosting iterations. A new tree is created in each iteration, so this is equivalent to the number of trees.</param>
/// <example>
/// <format type="text/markdown">
/// <]
/// ]]>
/// </format>
/// </example>
public static LightGbmMulticlassTrainer LightGbm(this MulticlassClassificationCatalog.MulticlassClassificationTrainers catalog,
string labelColumnName = DefaultColumnNames.Label,
string featureColumnName = DefaultColumnNames.Features,
string exampleWeightColumnName = null,
int? numberOfLeaves = null,
int? minimumExampleCountPerLeaf = null,
double? learningRate = null,
int numberOfIterations = Defaults.NumberOfIterations)
{
Contracts.CheckValue(catalog, nameof(catalog));
var env = CatalogUtils.GetEnvironment(catalog);
return new LightGbmMulticlassTrainer(env, labelColumnName, featureColumnName, exampleWeightColumnName, numberOfLeaves, minimumExampleCountPerLeaf, learningRate, numberOfIterations);
}
/// <summary>
/// Create <see cref="LightGbmMulticlassTrainer"/> with advanced options, which predicts a target using a gradient boosting decision tree multiclass classification model.
/// </summary>
/// <param name="catalog">The <see cref="MulticlassClassificationCatalog"/>.</param>
/// <param name="options">Trainer options.</param>
/// <example>
/// <format type="text/markdown">
/// <]
/// ]]>
/// </format>
/// </example>
public static LightGbmMulticlassTrainer LightGbm(this MulticlassClassificationCatalog.MulticlassClassificationTrainers catalog,
LightGbmMulticlassTrainer.Options options)
{
Contracts.CheckValue(catalog, nameof(catalog));
var env = CatalogUtils.GetEnvironment(catalog);
return new LightGbmMulticlassTrainer(env, options);
}
}
}
| 61.769565 | 193 | 0.665517 | [
"MIT"
] | GitHubPang/machinelearning | src/Microsoft.ML.LightGbm/LightGbmCatalog.cs | 14,209 | C# |
using UnityEngine;
using Overload;
using HarmonyLib;
using System.Reflection;
using System.Collections.Generic;
using System.Reflection.Emit;
namespace GameMod
{
[HarmonyPatch(typeof(ChallengeManager), "WorkerUpgradeRandomMissile")]
class ChallengeManager_WorkerUpgradeRandomMissile
{
static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> code)
{
var state = 0;
var buf1 = new List<CodeInstruction>();
foreach (var i in code)
{
switch(state)
{
// reverse order of maxing out missile ammo and upgrading it (to ignore capacity upgrades)
default:
if(i.opcode == OpCodes.Stsfld && ((FieldInfo)i.operand).DeclaringType == typeof(ChallengeManager) && ((FieldInfo)i.operand).Name == "m_recent_upgrade_timer")
{
state = 1;
}
yield return i;
break;
case 1:
if(i.opcode == OpCodes.Stelem_I4)
{
state = 2;
}
buf1.Add(i);
break;
case 2:
if(i.opcode == OpCodes.Pop)
{
yield return new CodeInstruction(OpCodes.Ldarg_0);
yield return new CodeInstruction(OpCodes.Ldarg_1);
yield return new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(ChallengeManager_WorkerUpgradeRandomMissile), "MaybePreRefillMissiles"));
foreach (var j in buf1)
{
yield return j;
}
yield return new CodeInstruction(OpCodes.Ldarg_0);
yield return new CodeInstruction(OpCodes.Ldarg_1);
yield return new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(ChallengeManager_WorkerUpgradeRandomMissile), "MaybePostRefillMissiles"));
buf1.Clear();
state = 3;
}
break;
case 3:
yield return i;
break;
}
}
if (buf1.Count > 0)
{
foreach (var j in buf1)
{
yield return j;
}
}
Debug.Log(string.Format("Patched WorkerUpgradeRandomMissile state={0}", state));
}
static void MaybePreRefillMissiles(Player p, int type)
{
switch(type)
{
// in these cases only one upgrade increases capacity, so refill before upgrading
case (int)MissileType.CREEPER:
case (int)MissileType.HUNTER:
case (int)MissileType.FALCON:
case (int)MissileType.MISSILE_POD:
p.AddMissileAmmo(1000, (MissileType)type, true, false);
break;
default:
break;
}
}
static void MaybePostRefillMissiles(Player p, int type)
{
switch (type)
{
// in these cases both upgrades increase capacity, so refill after upgrading
case (int)MissileType.NOVA:
case (int)MissileType.DEVASTATOR:
case (int)MissileType.TIMEBOMB:
case (int)MissileType.VORTEX:
p.AddMissileAmmo(1000, (MissileType)type, true, false);
break;
default:
break;
}
}
}
} | 38.31068 | 181 | 0.466548 | [
"MIT"
] | klmcdorm/olmods-n-stuff | Mod-CM-RNG/ChallengeManager.Upgrades.cs | 3,948 | 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.IO;
using System.Reflection.Metadata;
namespace BuildValidator
{
internal static class BlobReaderExtensions
{
public static void SkipNullTerminator(ref this BlobReader blobReader)
{
var b = blobReader.ReadByte();
if (b != '\0')
{
throw new InvalidDataException($"Encountered unexpected byte \"{b}\" when expecting a null terminator");
}
}
}
}
| 30.090909 | 120 | 0.648036 | [
"MIT"
] | AlekseyTs/roslyn | src/Tools/BuildValidator/BlobReaderExtensions.cs | 664 | C# |
////////////////////////////////////////////////////////////////////////////////
//NUnit tests for "EF Core Provider for LCPI OLE DB"
// IBProvider and Contributors. 11.05.2021.
using System;
using System.Data;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using NUnit.Framework;
using xdb=lcpi.data.oledb;
using structure_lib=lcpi.lib.structure;
namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D1.Query.Operators.SET_001.Equal.Complete2__objs.TimeSpan.String{
////////////////////////////////////////////////////////////////////////////////
using T_DATA1 =System.TimeSpan;
using T_DATA2 =System.String;
using T_DATA1_U=System.TimeSpan;
using T_DATA2_U=System.String;
////////////////////////////////////////////////////////////////////////////////
//class TestSet_504__param__01__VV
public static class TestSet_504__param__01__VV
{
private const string c_NameOf__TABLE ="DUAL";
private sealed class MyContext:TestBaseDbContext
{
[Table(c_NameOf__TABLE)]
public sealed class TEST_RECORD
{
[Key]
[Column("ID")]
public System.Int32? TEST_ID { get; set; }
};//class TEST_RECORD
//----------------------------------------------------------------------
public DbSet<TEST_RECORD> testTable { get; set; }
//----------------------------------------------------------------------
public MyContext(xdb.OleDbTransaction tr)
:base(tr)
{
}//MyContext
};//class MyContext
//-----------------------------------------------------------------------
[Test]
public static void Test_001__less()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
T_DATA1 vv1=new T_DATA1_U(12,14,34).Add(new System.TimeSpan(1000*1233)).Add(new System.TimeSpan(900));
T_DATA2 vv2="12:14:34.1234";
var recs=db.testTable.Where(r => ((object)vv1) /*OP{*/ == /*}OP*/ ((object)vv2));
try
{
foreach(var r in recs)
{
TestServices.ThrowSelectedRow();
}//foreach r
TestServices.ThrowWeWaitError();
}
catch(InvalidOperationException e)
{
CheckErrors.PrintException_OK(e);
Assert.IsNotNull
(e.InnerException);
Assert.IsInstanceOf<structure_lib.exceptions.t_invalid_operation_exception>
(e.InnerException);
var e2=(structure_lib.exceptions.t_invalid_operation_exception)(e.InnerException);
Assert.AreEqual
(1,
TestUtils.GetRecordCount(e2));
CheckErrors.CheckErrorRecord__local_eval_err__binary_operator_not_supported_3
(TestUtils.GetRecord(e2,0),
CheckErrors.c_src__EFCoreDataProvider__Root_Query_Local_Expressions__Op2_Code__Equal___Object__Object,
System.Linq.Expressions.ExpressionType.Equal,
"System.TimeSpan",
"System.String");
}//catch
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_001__less
//-----------------------------------------------------------------------
[Test]
public static void Test_002__equal()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
T_DATA1 vv1=new T_DATA1_U(12,14,34).Add(new System.TimeSpan(1000*1234)).Add(new System.TimeSpan(900));
T_DATA2 vv2="12:14:34.1234";
var recs=db.testTable.Where(r => ((object)vv1) /*OP{*/ == /*}OP*/ ((object)vv2));
try
{
foreach(var r in recs)
{
TestServices.ThrowSelectedRow();
}//foreach r
TestServices.ThrowWeWaitError();
}
catch(InvalidOperationException e)
{
CheckErrors.PrintException_OK(e);
Assert.IsNotNull
(e.InnerException);
Assert.IsInstanceOf<structure_lib.exceptions.t_invalid_operation_exception>
(e.InnerException);
var e2=(structure_lib.exceptions.t_invalid_operation_exception)(e.InnerException);
Assert.AreEqual
(1,
TestUtils.GetRecordCount(e2));
CheckErrors.CheckErrorRecord__local_eval_err__binary_operator_not_supported_3
(TestUtils.GetRecord(e2,0),
CheckErrors.c_src__EFCoreDataProvider__Root_Query_Local_Expressions__Op2_Code__Equal___Object__Object,
System.Linq.Expressions.ExpressionType.Equal,
"System.TimeSpan",
"System.String");
}//catch
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_002__equal
//-----------------------------------------------------------------------
[Test]
public static void Test_003__greater()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
T_DATA1 vv1=new T_DATA1_U(12,14,34).Add(new System.TimeSpan(1000*1235)).Add(new System.TimeSpan(900));
T_DATA2 vv2="12:14:34.1234";
var recs=db.testTable.Where(r => ((object)vv1) /*OP{*/ == /*}OP*/ ((object)vv2));
try
{
foreach(var r in recs)
{
TestServices.ThrowSelectedRow();
}//foreach r
TestServices.ThrowWeWaitError();
}
catch(InvalidOperationException e)
{
CheckErrors.PrintException_OK(e);
Assert.IsNotNull
(e.InnerException);
Assert.IsInstanceOf<structure_lib.exceptions.t_invalid_operation_exception>
(e.InnerException);
var e2=(structure_lib.exceptions.t_invalid_operation_exception)(e.InnerException);
Assert.AreEqual
(1,
TestUtils.GetRecordCount(e2));
CheckErrors.CheckErrorRecord__local_eval_err__binary_operator_not_supported_3
(TestUtils.GetRecord(e2,0),
CheckErrors.c_src__EFCoreDataProvider__Root_Query_Local_Expressions__Op2_Code__Equal___Object__Object,
System.Linq.Expressions.ExpressionType.Equal,
"System.TimeSpan",
"System.String");
}//catch
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_003__greater
//-----------------------------------------------------------------------
[Test]
public static void Test_ZA01NV()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
object vv1__null_obj=null;
T_DATA2 vv2="12:14:34.1234";
var recs=db.testTable.Where(r => ((object)(T_DATA1)(System.Object)vv1__null_obj) /*OP{*/ == /*}OP*/ ((object)vv2));
foreach(var r in recs)
{
TestServices.ThrowSelectedRow();
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE ").P_BOOL("__Exec_V_V_0"));
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_ZA01NV
//-----------------------------------------------------------------------
[Test]
public static void Test_ZA02VN()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
T_DATA1 vv1=new T_DATA1_U(12,14,34).Add(new System.TimeSpan(1000*1233));
object vv2__null_obj=null;
var recs=db.testTable.Where(r => ((object)vv1) /*OP{*/ == /*}OP*/ ((object)(T_DATA2)(System.Object)vv2__null_obj));
foreach(var r in recs)
{
TestServices.ThrowSelectedRow();
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE ").P_BOOL("__Exec_V_V_0"));
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_ZA02VN
//-----------------------------------------------------------------------
[Test]
public static void Test_ZA03NN()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
object vv1__null_obj=null;
object vv2__null_obj=null;
var recs=db.testTable.Where(r => ((object)(T_DATA1)(System.Object)vv1__null_obj) /*OP{*/ == /*}OP*/ ((object)(T_DATA2)(System.Object)vv2__null_obj));
int nRecs=0;
foreach(var r in recs)
{
Assert.AreEqual
(0,
nRecs);
++nRecs;
Assert.IsTrue
(r.TEST_ID.HasValue);
Assert.AreEqual
(1,
r.TEST_ID.Value);
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE ").P_BOOL("__Exec_V_V_0"));
Assert.AreEqual
(1,
nRecs);
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_ZA03NN
//-----------------------------------------------------------------------
[Test]
public static void Test_ZB01NV()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
object vv1__null_obj=null;
T_DATA2 vv2="12:14:34.1234";
var recs=db.testTable.Where(r => !(((object)(T_DATA1)(System.Object)vv1__null_obj) /*OP{*/ == /*}OP*/ ((object)vv2)));
int nRecs=0;
foreach(var r in recs)
{
Assert.AreEqual
(0,
nRecs);
++nRecs;
Assert.IsTrue
(r.TEST_ID.HasValue);
Assert.AreEqual
(1,
r.TEST_ID.Value);
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE ").P_BOOL("__Exec_V_0"));
Assert.AreEqual
(1,
nRecs);
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_ZB01NV
//-----------------------------------------------------------------------
[Test]
public static void Test_ZB02VN()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
T_DATA1 vv1=new T_DATA1_U(12,14,34).Add(new System.TimeSpan(1000*1233));
object vv2__null_obj=null;
var recs=db.testTable.Where(r => !(((object)vv1) /*OP{*/ == /*}OP*/ ((object)(T_DATA2)(System.Object)vv2__null_obj)));
int nRecs=0;
foreach(var r in recs)
{
Assert.AreEqual
(0,
nRecs);
++nRecs;
Assert.IsTrue
(r.TEST_ID.HasValue);
Assert.AreEqual
(1,
r.TEST_ID.Value);
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE ").P_BOOL("__Exec_V_0"));
Assert.AreEqual
(1,
nRecs);
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_ZB02VN
//-----------------------------------------------------------------------
[Test]
public static void Test_ZB03NN()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
object vv1__null_obj=null;
object vv2__null_obj=null;
var recs=db.testTable.Where(r => !(((object)(T_DATA1)(System.Object)vv1__null_obj) /*OP{*/ == /*}OP*/ ((object)(T_DATA2)(System.Object)vv2__null_obj)));
foreach(var r in recs)
{
TestServices.ThrowSelectedRow();
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE ").P_BOOL("__Exec_V_0"));
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_ZB03NN
};//class TestSet_504__param__01__VV
////////////////////////////////////////////////////////////////////////////////
}//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D1.Query.Operators.SET_001.Equal.Complete2__objs.TimeSpan.String
| 25.915811 | 157 | 0.577213 | [
"MIT"
] | ibprovider/Lcpi.EFCore.LcpiOleDb | Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D1/Query/Operators/SET_001/Equal/Complete2__objs/TimeSpan/String/TestSet_504__param__01__VV.cs | 12,623 | 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;
using System.Collections.Generic;
using System.Linq.Expressions;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore.Query;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.EntityFrameworkCore.Utilities;
namespace Microsoft.EntityFrameworkCore.Cosmos.Query.Internal
{
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public class SqlBinaryExpression : SqlExpression
{
private static readonly ISet<ExpressionType> _allowedOperators = new HashSet<ExpressionType>
{
ExpressionType.Add,
ExpressionType.Subtract,
ExpressionType.Multiply,
ExpressionType.Divide,
ExpressionType.Modulo,
ExpressionType.And,
ExpressionType.AndAlso,
ExpressionType.Or,
ExpressionType.OrElse,
ExpressionType.LessThan,
ExpressionType.LessThanOrEqual,
ExpressionType.GreaterThan,
ExpressionType.GreaterThanOrEqual,
ExpressionType.Equal,
ExpressionType.NotEqual,
ExpressionType.ExclusiveOr,
ExpressionType.RightShift,
ExpressionType.LeftShift
};
private static ExpressionType VerifyOperator(ExpressionType operatorType)
=> _allowedOperators.Contains(operatorType)
? operatorType
: throw new InvalidOperationException("Unsupported Binary operator type specified.");
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public SqlBinaryExpression(
ExpressionType operatorType,
[NotNull] SqlExpression left,
[NotNull] SqlExpression right,
[NotNull] Type type,
[CanBeNull] CoreTypeMapping typeMapping)
: base(type, typeMapping)
{
Check.NotNull(left, nameof(left));
Check.NotNull(right, nameof(right));
OperatorType = VerifyOperator(operatorType);
Left = left;
Right = right;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public virtual ExpressionType OperatorType { get; }
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public virtual SqlExpression Left { get; }
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public virtual SqlExpression Right { get; }
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitChildren(ExpressionVisitor visitor)
{
Check.NotNull(visitor, nameof(visitor));
var left = (SqlExpression)visitor.Visit(Left);
var right = (SqlExpression)visitor.Visit(Right);
return Update(left, right);
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public virtual SqlBinaryExpression Update([NotNull] SqlExpression left, [NotNull] SqlExpression right)
=> left != Left || right != Right
? new SqlBinaryExpression(OperatorType, left, right, Type, TypeMapping)
: this;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public override void Print(ExpressionPrinter expressionPrinter)
{
Check.NotNull(expressionPrinter, nameof(expressionPrinter));
var requiresBrackets = RequiresBrackets(Left);
if (requiresBrackets)
{
expressionPrinter.Append("(");
}
expressionPrinter.Visit(Left);
if (requiresBrackets)
{
expressionPrinter.Append(")");
}
expressionPrinter.Append(expressionPrinter.GenerateBinaryOperator(OperatorType));
requiresBrackets = RequiresBrackets(Right);
if (requiresBrackets)
{
expressionPrinter.Append("(");
}
expressionPrinter.Visit(Right);
if (requiresBrackets)
{
expressionPrinter.Append(")");
}
static bool RequiresBrackets(SqlExpression expression) => expression is SqlBinaryExpression;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public override bool Equals(object obj)
=> obj != null
&& (ReferenceEquals(this, obj)
|| obj is SqlBinaryExpression sqlBinaryExpression
&& Equals(sqlBinaryExpression));
private bool Equals(SqlBinaryExpression sqlBinaryExpression)
=> base.Equals(sqlBinaryExpression)
&& OperatorType == sqlBinaryExpression.OperatorType
&& Left.Equals(sqlBinaryExpression.Left)
&& Right.Equals(sqlBinaryExpression.Right);
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public override int GetHashCode() => HashCode.Combine(base.GetHashCode(), OperatorType, Left, Right);
}
}
| 49.119171 | 113 | 0.648418 | [
"Apache-2.0"
] | EricStG/efcore | src/EFCore.Cosmos/Query/Internal/SqlBinaryExpression.cs | 9,480 | C# |
using System.Diagnostics;
using OpenAL;
namespace UAlbion.Core.Veldrid.Audio
{
public abstract class AudioObject
{
[Conditional("DEBUG")]
protected static void Check()
{
int error = AL10.alGetError();
switch(error)
{
case AL10.AL_NO_ERROR: return;
case AL10.AL_INVALID_NAME: throw new AudioException("a bad name (ID) was passed to an OpenAL function");
case AL10.AL_INVALID_VALUE: throw new AudioException("an invalid value was passed to an OpenAL function");
case AL10.AL_INVALID_OPERATION: throw new AudioException("the requested operation is not valid");
case AL10.AL_OUT_OF_MEMORY: throw new AudioException("the requested operation resulted in OpenAL running out of memory");
}
}
}
} | 39.136364 | 137 | 0.631823 | [
"MIT"
] | BenjaminRi/ualbion | src/Core.Veldrid/Audio/AudioObject.cs | 863 | C# |
using UnityEngine;
using UnityEngine.UI;
public class CreditsButton : MonoBehaviour
{
public Button Credit;
void Start()
{
Button btn = Credit.GetComponent<Button>();
btn.onClick.AddListener(OnMouseDown);
}
void OnMouseDown()
{
Debug.Log("You clicked Credits");
}
} | 17.833333 | 51 | 0.632399 | [
"MIT"
] | umdacm/hunger-games | Assets/Scripts/CreditsButton.cs | 323 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace Xamarin.ProjectTools
{
public interface IShortFormProject
{
/// <summary>
/// If true, uses the default MSBuild wildcards for short-form projects.
/// </summary>
bool EnableDefaultItems { get; }
string Sdk { get; set; }
IList<PropertyGroup> PropertyGroups { get; }
IList<Package> PackageReferences { get; }
IList<BuildItem> OtherBuildItems { get; }
IList<IList<BuildItem>> ItemGroupList { get; }
IList<Import> Imports { get; }
void SetProperty (string name, string value, string condition = null);
}
}
| 27.5 | 74 | 0.719008 | [
"MIT"
] | AArnott/xamarin-android | src/Xamarin.Android.Build.Tasks/Tests/Xamarin.ProjectTools/Common/IShortFormProject.cs | 605 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by Entitas.CodeGenerator.ComponentsGenerator.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Entitas {
public partial class Entity {
public FindTargetComponent findTarget { get { return (FindTargetComponent)GetComponent(ComponentIds.FindTarget); } }
public bool hasFindTarget { get { return HasComponent(ComponentIds.FindTarget); } }
public Entity AddFindTarget(int newTargetCollisionType) {
var component = CreateComponent<FindTargetComponent>(ComponentIds.FindTarget);
component.targetCollisionType = newTargetCollisionType;
return AddComponent(ComponentIds.FindTarget, component);
}
public Entity ReplaceFindTarget(int newTargetCollisionType) {
var component = CreateComponent<FindTargetComponent>(ComponentIds.FindTarget);
component.targetCollisionType = newTargetCollisionType;
ReplaceComponent(ComponentIds.FindTarget, component);
return this;
}
public Entity RemoveFindTarget() {
return RemoveComponent(ComponentIds.FindTarget);
}
}
public partial class Matcher {
static IMatcher _matcherFindTarget;
public static IMatcher FindTarget {
get {
if (_matcherFindTarget == null) {
var matcher = (Matcher)Matcher.AllOf(ComponentIds.FindTarget);
matcher.componentNames = ComponentIds.componentNames;
_matcherFindTarget = matcher;
}
return _matcherFindTarget;
}
}
}
}
| 39.897959 | 125 | 0.585678 | [
"MIT"
] | kicholen/GamePrototype | Assets/Source/Generated/FindTargetComponentGeneratedExtension.cs | 1,955 | C# |
#if UNITY_EDITOR
using UnityEditor;
using UnityEngine;
namespace VLB
{
[CustomEditor(typeof(VolumetricDustParticles))]
[CanEditMultipleObjects]
public class VolumetricDustParticlesEditor : EditorCommon
{
SerializedProperty alpha, size, direction, speed, density, spawnMaxDistance, cullingEnabled, cullingMaxDistance;
static bool AreParticlesInfosUpdated() { return VolumetricDustParticles.isFeatureSupported && Application.isPlaying; }
public override bool RequiresConstantRepaint() { return AreParticlesInfosUpdated(); }
protected override void OnEnable()
{
base.OnEnable();
alpha = FindProperty((VolumetricDustParticles x) => x.alpha);
size = FindProperty((VolumetricDustParticles x) => x.size);
direction = FindProperty((VolumetricDustParticles x) => x.direction);
speed = FindProperty((VolumetricDustParticles x) => x.speed);
density = FindProperty((VolumetricDustParticles x) => x.density);
spawnMaxDistance = FindProperty((VolumetricDustParticles x) => x.spawnMaxDistance);
cullingEnabled = FindProperty((VolumetricDustParticles x) => x.cullingEnabled);
cullingMaxDistance = FindProperty((VolumetricDustParticles x) => x.cullingMaxDistance);
}
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
EditorGUILayout.Separator();
var particles = target as VolumetricDustParticles;
if (!VolumetricDustParticles.isFeatureSupported)
{
EditorGUILayout.HelpBox("Volumetric Dust Particles feature is only supported in Unity 5.5 or above", MessageType.Warning);
}
else if (particles.gameObject.activeSelf && particles.enabled && !particles.particlesAreInstantiated)
{
EditorGUILayout.HelpBox("Fail to instantiate the Particles. Please check your Config.", MessageType.Error);
ButtonOpenConfig();
}
if (HeaderFoldable("Rendering"))
{
EditorGUILayout.PropertyField(alpha, new GUIContent("Alpha", "Max alpha of the particles"));
EditorGUILayout.PropertyField(size, new GUIContent("Size", "Max size of the particles"));
}
DrawLineSeparator();
if (HeaderFoldable("Direction & Velocity"))
{
EditorGUILayout.PropertyField(direction, new GUIContent("Direction", "Direction of the particles\nCone: particles follows the cone/beam direction\nRandom: random direction"));
EditorGUILayout.PropertyField(speed, new GUIContent("Speed", "Movement speed of the particles"));
}
DrawLineSeparator();
if (HeaderFoldable("Culling"))
{
EditorGUILayout.PropertyField(cullingEnabled, new GUIContent("Enabled", "Enable particles culling based on the distance to the Main Camera.\nWe highly recommend to enable this feature to keep good runtime performances."));
if (cullingEnabled.boolValue)
EditorGUILayout.PropertyField(cullingMaxDistance, new GUIContent("Max Distance", "The particles will not be rendered if they are further than this distance to the Main Camera"));
}
DrawLineSeparator();
if (HeaderFoldable("Spawning"))
{
EditorGUILayout.PropertyField(density, new GUIContent("Density", "Control how many particles are spawned. The higher the density, the more particles are spawned, the higher the performance cost is"));
EditorGUILayout.PropertyField(spawnMaxDistance, new GUIContent("Max Distance", "The maximum distance (from the light source) where the particles are spawned.\nThe lower it is, the more the particles are gathered near the light source."));
if (VolumetricDustParticles.isFeatureSupported)
{
var infos = "Particles count:\nCurrent: ";
if (AreParticlesInfosUpdated()) infos += particles.particlesCurrentCount;
else infos += "(playtime only)";
if (particles.isCulled)
infos += string.Format(" (culled by '{0}')", particles.mainCamera.name);
infos += string.Format("\nMax: {0}", particles.particlesMaxCount);
EditorGUILayout.HelpBox(infos, MessageType.Info);
}
}
DrawLineSeparator();
if (HeaderFoldable("Infos"))
{
EditorGUILayout.HelpBox("We do not recommend to use this feature if you plan to move or change properties of the beam during playtime.", MessageType.Info);
}
serializedObject.ApplyModifiedProperties();
}
}
}
#endif
| 51.515464 | 255 | 0.626976 | [
"MIT"
] | JayneGale/BlankSlate0 | Assets/Plugins/VolumetricLightBeam/Editor/VolumetricDustParticlesEditor.cs | 4,999 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Pyro.Common.ServiceRoot;
using Pyro.DataLayer.DbModel.EntityBase;
namespace Pyro.DataLayer.DbModel.Entity
{
public class _ServiceBaseUrl : ModelBase, IDtoRootUrlStore
{
public string Url { get; set; }
public bool IsServersPrimaryUrlRoot { get; set; }
public _ServiceBaseUrl()
{
}
}
}
| 18.333333 | 60 | 0.734091 | [
"BSD-3-Clause"
] | angusmillar/Pyro | Pyro.DataLayer/DbModel/Entity/ServiceBaseUrl.cs | 442 | C# |
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Sitko.Core.App;
using Sitko.Core.Storage.Metadata;
namespace Sitko.Core.Storage.Cache
{
using JetBrains.Annotations;
// Generic parameter is required for dependency injection
// ReSharper disable once UnusedTypeParameter
public interface IStorageCache<TStorageOptions> : IAsyncDisposable where TStorageOptions : StorageOptions
{
internal Task<StorageItemDownloadInfo?> GetItemAsync(string path,
CancellationToken cancellationToken = default);
internal Task<StorageItemDownloadInfo?> GetOrAddItemAsync(string path,
Func<Task<StorageItemDownloadInfo?>> addItem,
CancellationToken cancellationToken = default);
Task RemoveItemAsync(string path, CancellationToken cancellationToken = default);
Task ClearAsync(CancellationToken cancellationToken = default);
}
// Generic interface is required for dependency injection
// ReSharper disable once UnusedTypeParameter
public interface IStorageCache<TStorageOptions, TCacheOptions> : IStorageCache<TStorageOptions>
where TCacheOptions : StorageCacheOptions where TStorageOptions : StorageOptions
{
}
public interface IStorageCacheRecord
{
StorageItemMetadata? Metadata { get; }
long FileSize { get; }
DateTimeOffset Date { get; }
public Stream OpenRead();
}
public abstract class StorageCacheOptions : BaseModuleOptions
{
[PublicAPI] public int TtlInMinutes { get; set; } = 720;
[PublicAPI] public long MaxFileSizeToStore { get; set; }
[PublicAPI] public long? MaxCacheSize { get; set; }
}
}
| 33.980392 | 109 | 0.721293 | [
"MIT"
] | IgorAlymov/Sitko.Core | src/Sitko.Core.Storage/Cache/IStorageCache.cs | 1,733 | C# |
//-----------------------------------------------------------------------------
// Torque
// Copyright GarageGames, LLC 2011
//-----------------------------------------------------------------------------
singleton CubemapData( BlankSkyCubemap )
{
cubeFace[0] = "./skybox_1";
cubeFace[1] = "./skybox_2";
cubeFace[2] = "./skybox_3";
cubeFace[3] = "./skybox_4";
cubeFace[4] = "./skybox_5";
cubeFace[5] = "./skybox_6";
};
singleton Material( BlankSkyMat )
{
cubemap = BlankSkyCubemap;
};
| 26.35 | 80 | 0.417457 | [
"MIT"
] | Ahe4d/Despacito3D | Templates/Modules/FPSGameplay/art/skies/Blank_sky/materials.cs | 508 | C# |
namespace TeslaCamViewer
{
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Threading;
using MahApps.Metro.Controls;
using MahApps.Metro.Controls.Dialogs;
public class VideoViewModel
{
public MediaElement left;
public MediaElement right;
public MediaElement front;
public MediaElement rear;
public TextBlock date;
public TabControl tabs;
public void LoadFileSet(TeslaCamFileSet set)
{
left.Stop();
right.Stop();
front.Stop();
rear.Stop();
bool playLeft = false;
bool playRight = false;
bool playFront = false;
bool playBack = false;
foreach (var cam in set.Cameras)
{
if (cam.CameraLocation == TeslaCamFile.CameraType.FRONT)
{
this.front.Source = new Uri(cam.FilePath);
playFront = true;
}
if (cam.CameraLocation == TeslaCamFile.CameraType.LEFT_REPEATER)
{
this.left.Source = new Uri(cam.FilePath);
playLeft = true;
}
if (cam.CameraLocation == TeslaCamFile.CameraType.RIGHT_REPEATER)
{
this.right.Source = new Uri(cam.FilePath);
playRight = true;
}
if (cam.CameraLocation == TeslaCamFile.CameraType.BACK)
{
this.rear.Source = new Uri(cam.FilePath);
playBack = true;
}
}
date.Text = set.Date.DisplayValue;
if (playLeft) left.Play();
if (playRight) right.Play();
if (playFront) front.Play();
if (playBack) rear.Play();
this.tabs.SelectedIndex = 1;
}
}
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : MetroWindow
{
private MainWindowViewModel model;
private TimeSpan TotalTime;
private bool paused;
public MainWindow()
{
this.model = new MainWindowViewModel();
this.DataContext = model;
this.model.LeftStatusText = "Ready";
InitializeComponent();
model.VideoModel.left = this.left;
model.VideoModel.right = this.right;
model.VideoModel.front = this.front;
model.VideoModel.rear = this.rear;
model.VideoModel.date = this.videoDate;
model.VideoModel.tabs = this.tabs;
this.displayPlaybackSpeed();
}
private void MediaElement_MediaOpened(object sender, RoutedEventArgs e)
{
TotalTime = left.NaturalDuration.TimeSpan;
var timerVideoTime = new DispatcherTimer();
timerVideoTime.Interval = TimeSpan.FromMilliseconds(100);
timerVideoTime.Tick += new EventHandler(timer_Tick);
timerVideoTime.Start();
}
void timer_Tick(object sender, EventArgs e)
{
if (left.NaturalDuration.HasTimeSpan)
if (left.NaturalDuration.TimeSpan.TotalSeconds > 0)
if (TotalTime.TotalSeconds > 0)
{
model.RightStatusText = left.Position.ToString(@"mm\:ss") + " / " + TotalTime.ToString(@"mm\:ss");
timeSlider.Value = left.Position.TotalSeconds / TotalTime.TotalSeconds;
}
}
private void SetPosition()
{
if (TotalTime.TotalSeconds > 0)
{
TimeSpan position = TimeSpan.FromSeconds(timeSlider.Value * TotalTime.TotalSeconds);
front.Position = position;
left.Position = position;
right.Position = position;
rear.Position = position;
}
}
private void timeSlider_DragStarted(object sender, System.Windows.Controls.Primitives.DragStartedEventArgs e)
{
left.Pause();
right.Pause();
front.Pause();
rear.Pause();
}
private void timeSlider_DragCompleted(object sender, System.Windows.Controls.Primitives.DragCompletedEventArgs e)
{
left.Play();
right.Play();
front.Play();
rear.Play();
}
private void timeSlider_DragDelta(object sender, System.Windows.Controls.Primitives.DragDeltaEventArgs e)
{
this.SetPosition();
}
private void OnItemMouseDoubleClick(object sender, MouseButtonEventArgs args)
{
if (sender is TreeViewItem)
{
if (!((TreeViewItem)sender).IsSelected)
{
return;
}
if (treeview.SelectedItem is TeslaCamFileSet)
{
var set = treeview.SelectedItem as TeslaCamFileSet;
model.LoadFileSet(set);
}
}
}
private void Window_Drop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
var f = files[0];
FileAttributes attr = File.GetAttributes(f);
if (attr.HasFlag(FileAttributes.Directory))
{
this.model.ListItems.Clear();
var c = new TeslaCamDirectoryCollection();
c.BuildFromBaseDirectory(f);
this.model.ListItems.Add(c);
this.model.LeftStatusText = "Location: " + f;
this.browseFrame.Navigate(new TeslaCamViewer.Views.RootCollectionView(this.model));
}
}
}
private async Task TeslaCamSearchAsync()
{
try
{
// Update Status
this.model.LeftStatusText = "Searching for TeslaCam ...";
// Placeholder variables used during and after worker task
DirectoryInfo teslaCamDir = null;
TeslaCamDirectoryCollection recentClips = null;
TeslaCamDirectoryCollection savedClips = null;
TeslaCamDirectoryCollection sentryClips = null;
// Run the following in a worker thread and wait for it to finish
await Task.Run(() =>
{
// Get all drives
var drives = System.IO.DriveInfo.GetDrives();
drives = drives.Where(e => e.DriveType == DriveType.Removable ||
e.DriveType == DriveType.Network ||
e.DriveType == DriveType.Fixed).ToArray();
// Find the first drive containing a TeslaCam folder and select that folder
teslaCamDir = (from drive in drives
let dirs = drive.RootDirectory.GetDirectories()
from dir in dirs
where dir.Name == "TeslaCam"
select dir).FirstOrDefault();
// If root is found load Recent and Saved
if (teslaCamDir != null)
{
// Get child dirs
var recentClipsDir = teslaCamDir.GetDirectories().FirstOrDefault(e => e.Name == "RecentClips");
var savedClipsDir = teslaCamDir.GetDirectories().FirstOrDefault(e => e.Name == "SavedClips");
var sentryClipsDir = teslaCamDir.GetDirectories().FirstOrDefault(e => e.Name == "SentryClips");
// Load if found
if (recentClipsDir != null)
{
recentClips = new TeslaCamDirectoryCollection();
recentClips.BuildFromBaseDirectory(recentClipsDir.FullName);
recentClips.SetDisplayName("Recent Clips");
}
if (savedClipsDir != null)
{
savedClips = new TeslaCamDirectoryCollection();
savedClips.BuildFromBaseDirectory(savedClipsDir.FullName);
savedClips.SetDisplayName("Saved Clips");
}
if (sentryClipsDir != null)
{
sentryClips = new TeslaCamDirectoryCollection();
sentryClips.BuildFromBaseDirectory(sentryClipsDir.FullName);
sentryClips.SetDisplayName("Sentry Clips");
}
}
});
// Do finial UI updating back on main thread
if (teslaCamDir != null)
{
// Update status to show drive was found
this.model.LeftStatusText = "Location: " + teslaCamDir.FullName;
// Add clips to UI tree
if (recentClips != null) { this.model.ListItems.Add(recentClips); }
if (savedClips != null) { this.model.ListItems.Add(savedClips); }
if (sentryClips != null) { this.model.ListItems.Add(sentryClips); }
// Navigate
this.browseFrame.Navigate(new TeslaCamViewer.Views.RootCollectionView(this.model));
}
else
{
// Update status to show that drive could not be found
this.model.LeftStatusText = "Ready";
await this.ShowMessageAsync("TeslaCam Drive Not Found", "A TeslaCam drive could not automatically be found. Drag a folder or file to start playing.");
}
}
catch (Exception ex)
{
this.ShowMessageAsync("Could not load TeslaCam Drive", "An error ocurred: " + ex.Message).Wait();
}
}
private async void teslaCamSearch_Menu_Click(object sender, RoutedEventArgs e)
{
this.model.ListItems.Clear();
await TeslaCamSearchAsync();
}
private void playPause_Button_Click(object sender, RoutedEventArgs e)
{
if (paused)
{
left.Play();
right.Play();
front.Play();
rear.Play();
}
else
{
left.Pause();
right.Pause();
front.Pause();
rear.Pause();
}
paused = !paused;
}
private void exit_Menu_Click(object sender, RoutedEventArgs e)
{
Application.Current.Shutdown();
}
private void MetroWindow_KeyUp(object sender, KeyEventArgs e)
{
if (e.Key == Key.Space)
playPause_Button_Click(sender, null);
if (e.Key == Key.F)
{
fullscreen_Menu.IsChecked = !fullscreen_Menu.IsChecked;
SetFullscreen(fullscreen_Menu.IsChecked);
}
if (e.Key == Key.Escape)
{
if (fullscreen_Menu.IsChecked)
{
fullscreen_Menu.IsChecked = !fullscreen_Menu.IsChecked;
SetFullscreen(fullscreen_Menu.IsChecked);
}
}
}
private async void MetroWindow_Loaded(object sender, RoutedEventArgs e)
{
if (model.EnableAutoSearch)
{
await this.TeslaCamSearchAsync();
}
}
private void about_Menu_Click(object sender, RoutedEventArgs e)
{
this.ShowMessageAsync("TeslaCam Viewer V0.4.1", "TeslaCam Viewer V0.4.1 Copyright 2019 mattw\n\nSee LICENCES.txt for more information.");
}
private void viewOnGitHub_Menu_Click(object sender, RoutedEventArgs e)
{
System.Diagnostics.Process.Start("https://github.com/mattw01/TeslaCamViewer/");
}
private void SetFullscreen(bool Enable)
{
if (Enable)
{
this.SetCurrentValue(IgnoreTaskbarOnMaximizeProperty, true);
this.SetCurrentValue(WindowStateProperty, WindowState.Maximized);
this.SetCurrentValue(UseNoneWindowStyleProperty, true);
}
else
{
this.SetCurrentValue(WindowStateProperty, WindowState.Normal);
this.SetCurrentValue(UseNoneWindowStyleProperty, false);
this.SetCurrentValue(ShowTitleBarProperty, true);
this.SetCurrentValue(IgnoreTaskbarOnMaximizeProperty, false);
}
}
private void fullscreen_Menu_Click(object sender, RoutedEventArgs e)
{
SetFullscreen(fullscreen_Menu.IsChecked);
}
private void ShowWelcomeMessage()
{
this.ShowMessageAsync("Welcome to TeslaCam Viewer!", "Getting Started:\n\nBrowse TeslaCam media in the left pane. " +
"TeslaCam drive will automatically be detected on startup, or drag a folder containing TeslaCam data anywhere onto the window. " +
"Double click event in TeslaCam Files pane to start playing.");
}
private void left_MediaEnded(object sender, RoutedEventArgs e)
{
try
{
if (model.EnableAutoPlaylist)
{
TeslaCamFileSet target = this.model.CurrentPlaybackFile;
TeslaCamEventCollection f = model.ListItems.SelectMany(d => d.Events).Where(d => d.Recordings.Contains(target)).First();
if (f != null)
{
int currentFileIndex = f.Recordings.IndexOf(target);
if (f.Recordings.Count - 1 > currentFileIndex)
{
TeslaCamFileSet nextSet = f.Recordings[currentFileIndex + 1];
model.LoadFileSet(nextSet);
var tvi = FindTviFromObjectRecursive(treeview, nextSet);
if (tvi != null)
{
tvi.IsSelected = true;
}
}
}
}
}
catch { }
}
public static TreeViewItem FindTviFromObjectRecursive(ItemsControl ic, object o)
{
TreeViewItem tvi = ic.ItemContainerGenerator.ContainerFromItem(o) as TreeViewItem;
if (tvi != null) return tvi;
foreach (object i in ic.Items)
{
TreeViewItem tvi2 = ic.ItemContainerGenerator.ContainerFromItem(i) as TreeViewItem;
tvi = FindTviFromObjectRecursive(tvi2, o);
if (tvi != null) return tvi;
}
return null;
}
private void playbackSpeed_Slider_DragDelta(object sender, System.Windows.Controls.Primitives.DragDeltaEventArgs e)
{
this.displayPlaybackSpeed();
this.left.SpeedRatio = model.CalculatedPlaybackSpeed;
this.right.SpeedRatio = model.CalculatedPlaybackSpeed;
this.front.SpeedRatio = model.CalculatedPlaybackSpeed;
this.rear.SpeedRatio = model.CalculatedPlaybackSpeed;
}
private void displayPlaybackSpeed()
{
this.playbackSpeed_Display.Header = $"Playback Speed : x {model.CalculatedPlaybackSpeed}";
}
private void deleteFolder_MenuItem_Click(object sender, RoutedEventArgs e)
{
if (this.treeview.SelectedItem is TeslaCamEventCollection)
{
TeslaCamEventCollection teslaCamEventCollection = this.treeview.SelectedItem as TeslaCamEventCollection;
try
{
Directory.Delete(teslaCamEventCollection.Directory, true);
foreach( var li in this.model.ListItems) li.Events.Remove(teslaCamEventCollection);
}
catch( IOException ioe)
{
this.model.RightStatusText = ioe.Message;
}
}
}
private void deleteAllFolders_MenuItem_Click(object sender, RoutedEventArgs e)
{
if (this.treeview.SelectedItem is TeslaCamDirectoryCollection)
{
TeslaCamDirectoryCollection teslaCamDirectoryCollection = this.treeview.SelectedItem as TeslaCamDirectoryCollection;
try
{
foreach (var ev in teslaCamDirectoryCollection.Events.ToList())
{
Directory.Delete(ev.Directory, true);
teslaCamDirectoryCollection.Events.Remove(ev);
}
}
catch (IOException ioe)
{
this.model.RightStatusText = ioe.Message;
}
}
}
}
}
| 39.422658 | 171 | 0.508041 | [
"MIT"
] | stephane-laurans/TeslaCamViewer | TeslaCamViewer/TeslaCamViewer/MainWindow.xaml.cs | 18,097 | C# |
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
#if NET6_0_OR_GREATER
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
#endif
namespace Utf8Utility.Text;
/// <content>
/// <see cref="UnicodeUtility"/>クラスのIsAscii関連処理です。
/// </content>
partial class UnicodeUtility
{
/// <summary>
/// 指定された配列が、Ascii文字のみで構成されているかどうかを判定します。
/// </summary>
/// <param name="value">配列</param>
/// <returns>
/// 指定された配列が、Ascii文字のみで構成されている場合は<see langword="true"/>、
/// それ以外は<see langword="false"/>を返します。
/// </returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool IsAscii(ReadOnlySpan<byte> value)
{
if (value.IsEmpty)
{
return false;
}
#if NET6_0_OR_GREATER
if (Avx2.IsSupported)
{
return IsAsciiAvx2(value);
}
if (Sse2.IsSupported)
{
return IsAsciiSse2(value);
}
#endif
return IsAsciiUlong(value);
}
#if NET6_0_OR_GREATER
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static bool IsAsciiAvx2(ReadOnlySpan<byte> value)
{
nuint index = 0;
var mask32 = Vector256<byte>.Zero;
ref var first = ref MemoryMarshal.GetReference(value);
if (value.Length >= Vector256<byte>.Count)
{
var endIndex = value.Length - Vector256<byte>.Count;
ref var current = ref Unsafe.As<byte, Vector256<byte>>(ref first);
do
{
mask32 = Avx2.Or(mask32, Unsafe.AddByteOffset(ref current, index));
index += (uint)Vector256<byte>.Count;
}
while ((int)index <= endIndex);
}
var result = Avx2.MoveMask(mask32);
var mask8 = 0UL;
if (value.Length - (int)index >= sizeof(ulong) * 2)
{
ref var current = ref Unsafe.As<byte, ulong>(ref Unsafe.AddByteOffset(ref first, index));
mask8 = current;
mask8 |= Unsafe.Add(ref current, 1);
index += sizeof(ulong) * 2;
}
if (value.Length - (int)index >= sizeof(ulong))
{
mask8 |= Unsafe.As<byte, ulong>(ref Unsafe.AddByteOffset(ref first, index));
index += sizeof(ulong);
}
if (value.Length - (int)index >= sizeof(uint))
{
mask8 |= Unsafe.As<byte, uint>(ref Unsafe.AddByteOffset(ref first, index));
index += sizeof(uint);
}
if (value.Length - (int)index >= sizeof(ushort))
{
mask8 |= Unsafe.As<byte, ushort>(ref Unsafe.AddByteOffset(ref first, index));
index += sizeof(ushort);
}
if ((int)index < value.Length)
{
mask8 |= Unsafe.AddByteOffset(ref first, index);
}
return ((uint)result | (mask8 & 0x8080808080808080)) == 0;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static bool IsAsciiSse2(ReadOnlySpan<byte> value)
{
nuint index = 0;
var mask16 = Vector128<byte>.Zero;
ref var first = ref MemoryMarshal.GetReference(value);
if (value.Length >= Vector128<byte>.Count)
{
var endIndex = value.Length - Vector128<byte>.Count;
ref var current = ref Unsafe.As<byte, Vector128<byte>>(ref first);
do
{
mask16 = Sse2.Or(mask16, Unsafe.AddByteOffset(ref current, index));
index += (uint)Vector128<byte>.Count;
}
while ((int)index <= endIndex);
}
var result = Sse2.MoveMask(mask16);
var mask8 = 0UL;
if (value.Length - (int)index >= sizeof(ulong))
{
mask8 |= Unsafe.As<byte, ulong>(ref Unsafe.AddByteOffset(ref first, index));
index += sizeof(ulong);
}
if (value.Length - (int)index >= sizeof(uint))
{
mask8 |= Unsafe.As<byte, uint>(ref Unsafe.AddByteOffset(ref first, index));
index += sizeof(uint);
}
if (value.Length - (int)index >= sizeof(ushort))
{
mask8 |= Unsafe.As<byte, ushort>(ref Unsafe.AddByteOffset(ref first, index));
index += sizeof(ushort);
}
if ((int)index < value.Length)
{
mask8 |= Unsafe.AddByteOffset(ref first, index);
}
return ((uint)result | (mask8 & 0x8080808080808080)) == 0;
}
#endif
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static bool IsAsciiUlong(ReadOnlySpan<byte> value)
{
nuint index = 0;
var maskA = 0UL;
var maskB = 0UL;
var maskC = 0UL;
var maskD = 0UL;
ref var first = ref MemoryMarshal.GetReference(value);
if (value.Length >= sizeof(ulong) * 4)
{
ref var current = ref Unsafe.As<byte, ulong>(ref first);
var endIndex = value.Length - (sizeof(ulong) * 4);
do
{
#if NET6_0_OR_GREATER
maskA |= Unsafe.AddByteOffset(ref current, index);
maskB |= Unsafe.AddByteOffset(ref current, index + sizeof(ulong));
maskC |= Unsafe.AddByteOffset(ref current, index + (sizeof(ulong) * 2));
maskD |= Unsafe.AddByteOffset(ref current, index + (sizeof(ulong) * 3));
#else
maskA |= Unsafe.AddByteOffset(ref current, (nint)index);
maskB |= Unsafe.AddByteOffset(ref current, (nint)(index + sizeof(ulong)));
maskC |= Unsafe.AddByteOffset(ref current, (nint)(index + (sizeof(ulong) * 2)));
maskD |= Unsafe.AddByteOffset(ref current, (nint)(index + (sizeof(ulong) * 3)));
#endif
index += sizeof(ulong) * 4;
}
while ((int)index < endIndex);
}
if (value.Length - (int)index >= sizeof(ulong) * 2)
{
#if NET6_0_OR_GREATER
ref var current = ref Unsafe.As<byte, ulong>(ref Unsafe.AddByteOffset(ref first, index));
#else
ref var current = ref Unsafe.As<byte, ulong>(ref Unsafe.AddByteOffset(ref first, (nint)index));
#endif
maskA |= current;
maskA |= Unsafe.Add(ref current, 1);
index += sizeof(ulong) * 2;
}
if (value.Length - (int)index >= sizeof(ulong))
{
#if NET6_0_OR_GREATER
maskA |= Unsafe.As<byte, ulong>(ref Unsafe.AddByteOffset(ref first, index));
#else
maskA |= Unsafe.As<byte, ulong>(ref Unsafe.AddByteOffset(ref first, (nint)index));
#endif
index += sizeof(ulong);
}
if (value.Length - (int)index >= sizeof(uint))
{
#if NET6_0_OR_GREATER
maskA |= Unsafe.As<byte, uint>(ref Unsafe.AddByteOffset(ref first, index));
#else
maskA |= Unsafe.As<byte, uint>(ref Unsafe.AddByteOffset(ref first, (nint)index));
#endif
index += sizeof(uint);
}
if (value.Length - (int)index >= sizeof(ushort))
{
#if NET6_0_OR_GREATER
maskA |= Unsafe.As<byte, ushort>(ref Unsafe.AddByteOffset(ref first, index));
#else
maskA |= Unsafe.As<byte, ushort>(ref Unsafe.AddByteOffset(ref first, (nint)index));
#endif
index += sizeof(ushort);
}
if ((int)index < value.Length)
{
#if NET6_0_OR_GREATER
maskA |= Unsafe.AddByteOffset(ref first, index);
#else
maskA |= Unsafe.AddByteOffset(ref first, (nint)index);
#endif
}
return ((maskA | maskB | maskC | maskD) & 0x8080808080808080) == 0;
}
}
| 30.955102 | 107 | 0.562632 | [
"MIT"
] | finphie/Utf8Utility | Source/Utf8Utility/Text/UnicodeUtility.IsAscii.cs | 7,748 | C# |
using System;
namespace GoodbyeApp
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
| 13.692308 | 46 | 0.516854 | [
"MIT"
] | sedc-codecademy/skwd9-net-05-oopcsharp | G2/Class01 - Intro/Code/HelloWorldApp/GoodbyeApp/Program.cs | 180 | C# |
using System;
namespace Loja.Domain.Core.Entities
{
public abstract class Entity
{
public Guid Id { get; protected set; }
public override bool Equals(object obj)
{
var compareTo = obj as Entity;
if (ReferenceEquals(this, compareTo)) return true;
if (ReferenceEquals(null, compareTo)) return false;
return Id.Equals(compareTo.Id);
}
public override string ToString()
{
return $"{GetType().Name} [Id= {Id}]";
}
}
}
| 21.88 | 63 | 0.557587 | [
"MIT"
] | LeonardoLuz2/Loja | src/Loja.Domain.Core/Entities/Entity.cs | 549 | C# |
using System.Web;
using Orchard.Localization.Services;
namespace Orchard.Tests.Stubs {
public class StubCultureSelector : ICultureSelector {
private readonly string _cultureName;
public StubCultureSelector(string cultureName) {
_cultureName = cultureName;
}
public CultureSelectorResult GetCulture(HttpContextBase context) {
return new CultureSelectorResult { Priority = 1, CultureName = _cultureName };
}
}
} | 30.3125 | 90 | 0.694845 | [
"BSD-3-Clause"
] | 1996dylanriley/Orchard | src/Orchard.Tests/Stubs/StubCultureSelector.cs | 487 | C# |
namespace Next.Abstractions.Trace
{
public interface ITraceInfoProvider
{
TraceInfo GetTraceInfo();
}
}
| 15.625 | 39 | 0.672 | [
"MIT"
] | sweepator/next | src/abstractions/Next.Abstractions.Trace/ITraceInfoProvider.cs | 127 | C# |
// Copyright (C) 2003-2010 Xtensive LLC.
// This code is distributed under MIT license terms.
// See the License.txt file in the project root for more information.
using System;
using NUnit.Framework;
using Xtensive.Core;
using Xtensive.Orm;
using Xtensive.Orm.Building.Builders;
using Xtensive.Sql;
namespace Xtensive.Orm.Tests.Sql
{
[TestFixture]
public class DriverFactoryTest
{
private string provider = TestConnectionInfoProvider.GetProvider();
protected string Url = TestConnectionInfoProvider.GetConnectionUrl();
protected string ConnectionString = TestConnectionInfoProvider.GetConnectionString();
[Test]
public void ConnectionUrlTest()
{
var url = UrlInfo.Parse("sqlserver://appserver/AdventureWorks?Connection Timeout=5");
Assert.AreEqual(url.Protocol, "sqlserver");
Assert.AreEqual(url.Host, "appserver");
Assert.AreEqual(url.Resource, "AdventureWorks");
url = UrlInfo.Parse("sqlserver://localhost/database");
Assert.AreEqual("database", url.GetDatabase());
Assert.AreEqual("default schema", url.GetSchema("default schema"));
url = UrlInfo.Parse("sqlserver://localhost/database/");
Assert.AreEqual("database", url.GetDatabase());
Assert.AreEqual("default schema", url.GetSchema("default schema"));
url = UrlInfo.Parse("sqlserver://localhost/database/schema");
Assert.AreEqual("database", url.GetDatabase());
Assert.AreEqual("schema", url.GetSchema(string.Empty));
url = UrlInfo.Parse("sqlserver://localhost/database/schema/");
Assert.AreEqual("database", url.GetDatabase());
Assert.AreEqual("schema", url.GetSchema(string.Empty));
}
[Test]
public void ServerInfoTest()
{
Require.ProviderIs(StorageProvider.SqlServer);
Require.ProviderVersionAtLeast(StorageProviderVersion.SqlServer2005);
var driver = TestSqlDriver.Create(Url);
Assert.Greater(driver.CoreServerInfo.ServerVersion.Major, 8);
}
[Test]
public void ProviderTest()
{
TestProvider(provider, ConnectionString, Url);
}
[Test]
public void SqlServerConnectionCheckTest()
{
Require.ProviderIs(StorageProvider.SqlServer);
var descriptor = ProviderDescriptor.Get(provider);
var factory = (SqlDriverFactory) Activator.CreateInstance(descriptor.DriverFactory);
var configuration = new SqlDriverConfiguration() { EnsureConnectionIsAlive = false };
var driver = factory.GetDriver(new ConnectionInfo(Url), configuration);
Assert.That(GetCheckConnectionIsAliveFlag(driver), Is.False);
configuration = configuration.Clone();
configuration.EnsureConnectionIsAlive = true;
driver = factory.GetDriver(new ConnectionInfo(Url), configuration);
Assert.That(GetCheckConnectionIsAliveFlag(driver), Is.True);
configuration = configuration.Clone();
configuration.EnsureConnectionIsAlive = true;
driver = factory.GetDriver(new ConnectionInfo(provider, ConnectionString + ";pooling=false"), configuration);
Assert.That(GetCheckConnectionIsAliveFlag(driver), Is.False);
configuration = configuration.Clone();
configuration.EnsureConnectionIsAlive = true;
driver = factory.GetDriver(new ConnectionInfo(provider, ConnectionString + ";Pooling=False"), configuration);
Assert.That(GetCheckConnectionIsAliveFlag(driver), Is.False);
configuration = configuration.Clone();
configuration.EnsureConnectionIsAlive = true;
driver = factory.GetDriver(new ConnectionInfo(provider, ConnectionString + ";pooling = false"), configuration);
Assert.That(GetCheckConnectionIsAliveFlag(driver), Is.False);
configuration = configuration.Clone();
configuration.EnsureConnectionIsAlive = true;
driver = factory.GetDriver(new ConnectionInfo(provider, ConnectionString + ";Pooling = False"), configuration);
Assert.That(GetCheckConnectionIsAliveFlag(driver), Is.False);
}
private static void TestProvider(string providerName, string connectionString, string connectionUrl)
{
Assert.IsNotNull(TestSqlDriver.Create(connectionUrl));
Assert.IsNotNull(TestSqlDriver.Create(providerName, connectionString));
}
private static bool GetCheckConnectionIsAliveFlag(SqlDriver driver)
{
const string fieldName = "checkConnectionIsAlive";
var type = typeof (Xtensive.Sql.Drivers.SqlServer.Driver);
return (bool) type.GetField(fieldName, System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)
.GetValue(driver);
}
}
} | 40.681416 | 128 | 0.728736 | [
"MIT"
] | NekrasovSt/dataobjects-net | Orm/Xtensive.Orm.Tests.Sql/DriverFactoryTest.cs | 4,597 | C# |
using System;
using System.Collections.Generic;
namespace Custom_Doubly_Linked_List
{
class DoublyLinkedList<T>
{
private ListNode<T> head;
private ListNode<T> tail;
public DoublyLinkedList()
{
this.head = new ListNode<T>();
this.tail = new ListNode<T>();
}
public int Count { get; private set; }
public void AddFirst(T element)
{
if (this.Count == 0)
{
this.head = this.tail = new ListNode<T>(element);
}
else
{
var newHead = new ListNode<T>(element);
newHead.NextNode = this.head;
this.head.PreviousNode = newHead;
this.head = newHead;
}
this.Count++;
}
public void AddLast(T element)
{
if (this.Count == 0)
{
this.head = this.tail = new ListNode<T>(element);
}
else
{
var newTail = new ListNode<T>(element);
newTail.PreviousNode = this.tail;
this.tail.NextNode = newTail;
this.tail = newTail;
}
this.Count++;
}
public T RemoveFirst()
{
if (this.Count == 0)
{
throw new InvalidOperationException("The list is empty");
}
var firstElement = this.head.Value;
this.head = this.head.NextNode;
if (this.head != null)
{
this.head.PreviousNode = null;
}
else
{
this.tail = null;
}
this.Count--;
return firstElement;
}
public T RemoveLast()
{
if (this.Count == 0)
{
throw new InvalidOperationException("The list is empty");
}
var lastElement = this.tail.Value;
this.tail = this.tail.PreviousNode;
if (this.tail != null)
{
this.tail.NextNode= null;
}
else
{
this.head = null;
}
this.Count--;
return lastElement;
}
public ListNode<T> GetNode(int index)
{
if (index < 0 || index >= this.Count)
{
throw new IndexOutOfRangeException("Index must be inside the bounds of the List");
}
var currNode = this.head;
for (int i = 0; i < this.Count; i++)
{
if (i == index)
{
break;
}
currNode = currNode.NextNode;
}
return currNode;
}
public void ForEach(Action<T> action)
{
var currNode = this.head;
while (currNode != null)
{
action(currNode.Value);
currNode = currNode.NextNode;
}
}
public T[] ToArray()
{
T[] arr = new T[this.Count];
int counter = 0;
var currNode = this.head;
while (currNode != null)
{
arr[counter] = currNode.Value;
currNode = currNode.NextNode;
counter++;
}
return arr;
}
}
}
| 23.346667 | 98 | 0.416619 | [
"MIT"
] | stanislavyv/softuni-projects | Data Structures Fundamentals/Custom Doubly Linked List/Custom Doubly Linked List/DoublyLinkedList.cs | 3,504 | C# |
/*
Written by Peter O. in 2014.
Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/
If you like this, you should donate to Peter O.
at: http://peteroupc.github.io/
*/
using System;
using PeterO;
using PeterO.Numbers;
namespace PeterO.Cbor {
internal class CBORInteger : ICBORNumber {
public object Abs(object obj) {
var val = (long)obj;
return (val == Int32.MinValue) ? (EInteger.One << 63) : ((val < 0) ?
-val : obj);
}
public EInteger AsEInteger(object obj) {
return (EInteger)(long)obj;
}
public double AsDouble(object obj) {
return (double)(long)obj;
}
public EDecimal AsEDecimal(object obj) {
return EDecimal.FromInt64((long)obj);
}
public EFloat AsEFloat(object obj) {
return EFloat.FromInt64((long)obj);
}
public ERational AsERational(object obj) {
return ERational.FromInt64((long)obj);
}
public int AsInt32(object obj, int minValue, int maxValue) {
var val = (long)obj;
if (val >= minValue && val <= maxValue) {
return (int)val;
}
throw new OverflowException("This object's value is out of range");
}
public long AsInt64(object obj) {
return (long)obj;
}
public float AsSingle(object obj) {
return (float)(long)obj;
}
public bool CanFitInDouble(object obj) {
var intItem = (long)obj;
if (intItem == Int64.MinValue) {
return true;
}
intItem = (intItem < 0) ? -intItem : intItem;
while (intItem >= (1L << 53) && (intItem & 1) == 0) {
intItem >>= 1;
}
return intItem < (1L << 53);
}
public bool CanFitInInt32(object obj) {
var val = (long)obj;
return val >= Int32.MinValue && val <= Int32.MaxValue;
}
public bool CanFitInInt64(object obj) {
return true;
}
public bool CanFitInSingle(object obj) {
var intItem = (long)obj;
if (intItem == Int64.MinValue) {
return true;
}
intItem = (intItem < 0) ? -intItem : intItem;
while (intItem >= (1L << 24) && (intItem & 1) == 0) {
intItem >>= 1;
}
return intItem < (1L << 24);
}
public bool CanTruncatedIntFitInInt32(object obj) {
var val = (long)obj;
return val >= Int32.MinValue && val <= Int32.MaxValue;
}
public bool CanTruncatedIntFitInInt64(object obj) {
return true;
}
public bool IsInfinity(object obj) {
return false;
}
public bool IsIntegral(object obj) {
return true;
}
public bool IsNaN(object obj) {
return false;
}
public bool IsNegative(object obj) {
return ((long)obj) < 0;
}
public bool IsNegativeInfinity(object obj) {
return false;
}
public bool IsPositiveInfinity(object obj) {
return false;
}
public bool IsNumberZero(object obj) {
return ((long)obj) == 0;
}
public object Negate(object obj) {
return (((long)obj) == Int64.MinValue) ? (EInteger.One << 63) :
(-((long)obj));
}
public int Sign(object obj) {
var val = (long)obj;
return (val == 0) ? 0 : ((val < 0) ? -1 : 1);
}
}
}
| 23.510949 | 74 | 0.582738 | [
"MIT"
] | JordanSchuetz/Unity-Realtime-Chat-Room-Tutorial | Assets/PubNub/ThirdParty/CBOR/PeterO/Cbor/CBORInteger.cs | 3,221 | C# |
// Copyright © Neodymium, carmineos and contributors. See LICENSE.md in the repository root for more information.
using RageLib.Resources.Common;
using System.Collections.Generic;
using System;
namespace RageLib.Resources.GTA5.PC.Clips
{
// pgBase
// crClip
public class Clip : PgBase64, IResourceXXSystemBlock
{
public override long BlockLength => 0x50;
// structure data
public byte Type;
public byte Unknown_11h;
public ushort Unknown_12h;
public uint Unknown_14h; // 0x00000000
public ulong NamePointer;
public ushort NameLength1;
public ushort NameLength2;
public uint Unknown_24h; // 0x00000000
public uint Unknown_28h; // 0x50000000
public uint Unknown_2Ch; // 0x00000000
public uint Unknown_30h;
public uint Unknown_34h; // 0x00000000
public ulong TagsPointer;
public ulong PropertiesPointer;
public uint Unknown_48h; // 0x00000001
public uint Unknown_4Ch; // 0x00000000
// reference data
public string_r Name;
public Tags Tags;
public ResourceHashMap<Property> Properties;
/// <summary>
/// Reads the data-block from a stream.
/// </summary>
public override void Read(ResourceDataReader reader, params object[] parameters)
{
base.Read(reader, parameters);
// read structure data
this.Type = reader.ReadByte();
this.Unknown_11h = reader.ReadByte();
this.Unknown_12h = reader.ReadUInt16();
this.Unknown_14h = reader.ReadUInt32();
this.NamePointer = reader.ReadUInt64();
this.NameLength1 = reader.ReadUInt16();
this.NameLength2 = reader.ReadUInt16();
this.Unknown_24h = reader.ReadUInt32();
this.Unknown_28h = reader.ReadUInt32();
this.Unknown_2Ch = reader.ReadUInt32();
this.Unknown_30h = reader.ReadUInt32();
this.Unknown_34h = reader.ReadUInt32();
this.TagsPointer = reader.ReadUInt64();
this.PropertiesPointer = reader.ReadUInt64();
this.Unknown_48h = reader.ReadUInt32();
this.Unknown_4Ch = reader.ReadUInt32();
// read reference data
this.Name = reader.ReadBlockAt<string_r>(
this.NamePointer // offset
);
this.Tags = reader.ReadBlockAt<Tags>(
this.TagsPointer // offset
);
this.Properties = reader.ReadBlockAt<ResourceHashMap<Property>>(
this.PropertiesPointer // offset
);
}
/// <summary>
/// Writes the data-block to a stream.
/// </summary>
public override void Write(ResourceDataWriter writer, params object[] parameters)
{
base.Write(writer, parameters);
// update structure data
this.NamePointer = (ulong)(this.Name != null ? this.Name.BlockPosition : 0);
this.NameLength1 = (ushort)(this.Name != null ? this.Name.Value.Length : 0);
this.NameLength2 = (ushort)(this.Name != null ? this.Name.Value.Length + 1 : 0);
this.TagsPointer = (ulong)(this.Tags != null ? this.Tags.BlockPosition : 0);
this.PropertiesPointer = (ulong)(this.Properties != null ? this.Properties.BlockPosition : 0);
// write structure data
writer.Write(this.Type);
writer.Write(this.Unknown_11h);
writer.Write(this.Unknown_12h);
writer.Write(this.Unknown_14h);
writer.Write(this.NamePointer);
writer.Write(this.NameLength1);
writer.Write(this.NameLength2);
writer.Write(this.Unknown_24h);
writer.Write(this.Unknown_28h);
writer.Write(this.Unknown_2Ch);
writer.Write(this.Unknown_30h);
writer.Write(this.Unknown_34h);
writer.Write(this.TagsPointer);
writer.Write(this.PropertiesPointer);
writer.Write(this.Unknown_48h);
writer.Write(this.Unknown_4Ch);
}
/// <summary>
/// Returns a list of data blocks which are referenced by this block.
/// </summary>
public override IResourceBlock[] GetReferences()
{
var list = new List<IResourceBlock>(base.GetReferences());
if (Name != null) list.Add(Name);
if (Tags != null) list.Add(Tags);
if (Properties != null) list.Add(Properties);
return list.ToArray();
}
public IResourceSystemBlock GetType(ResourceDataReader reader, params object[] parameters)
{
reader.Position += 16;
var type = reader.ReadByte();
reader.Position -= 17;
switch (type)
{
case 1: return new ClipAnimation();
case 2: return new ClipAnimations();
default: throw new Exception("Unknown clip type");
}
}
}
}
| 37.82963 | 113 | 0.586254 | [
"MIT"
] | carmineos/gta-toolkit | RageLib.GTA5/Resources/PC/Clips/Clip.cs | 5,108 | C# |
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Globalization;
using Avalonia.Styling;
using Avalonia.Utilities;
namespace Avalonia.Markup.Parsers
{
/// <summary>
/// Parses a <see cref="Selector"/> from text.
/// </summary>
public class SelectorParser
{
private readonly Func<string, string, Type> _typeResolver;
/// <summary>
/// Initializes a new instance of the <see cref="SelectorParser"/> class.
/// </summary>
/// <param name="typeResolver">
/// The type resolver to use. The type resolver is a function which accepts two strings:
/// a type name and a XML namespace prefix and a type name, and should return the resolved
/// type or throw an exception.
/// </param>
public SelectorParser(Func<string, string, Type> typeResolver)
{
_typeResolver = typeResolver;
}
/// <summary>
/// Parses a <see cref="Selector"/> from a string.
/// </summary>
/// <param name="s">The string.</param>
/// <returns>The parsed selector.</returns>
public Selector Parse(string s)
{
var syntax = SelectorGrammar.Parse(s);
return Create(syntax);
}
private Selector Create(IEnumerable<SelectorGrammar.ISyntax> syntax)
{
var result = default(Selector);
var results = default(List<Selector>);
foreach (var i in syntax)
{
switch (i)
{
case SelectorGrammar.OfTypeSyntax ofType:
result = result.OfType(Resolve(ofType.Xmlns, ofType.TypeName));
break;
case SelectorGrammar.IsSyntax @is:
result = result.Is(Resolve(@is.Xmlns, @is.TypeName));
break;
case SelectorGrammar.ClassSyntax @class:
result = result.Class(@class.Class);
break;
case SelectorGrammar.NameSyntax name:
result = result.Name(name.Name);
break;
case SelectorGrammar.PropertySyntax property:
{
var type = result?.TargetType;
if (type == null)
{
throw new InvalidOperationException("Property selectors must be applied to a type.");
}
var targetProperty = AvaloniaPropertyRegistry.Instance.FindRegistered(type, property.Property);
if (targetProperty == null)
{
throw new InvalidOperationException($"Cannot find '{property.Property}' on '{type}");
}
object typedValue;
if (TypeUtilities.TryConvert(
targetProperty.PropertyType,
property.Value,
CultureInfo.InvariantCulture,
out typedValue))
{
result = result.PropertyEquals(targetProperty, typedValue);
}
else
{
throw new InvalidOperationException(
$"Could not convert '{property.Value}' to '{targetProperty.PropertyType}");
}
break;
}
case SelectorGrammar.ChildSyntax child:
result = result.Child();
break;
case SelectorGrammar.DescendantSyntax descendant:
result = result.Descendant();
break;
case SelectorGrammar.TemplateSyntax template:
result = result.Template();
break;
case SelectorGrammar.NotSyntax not:
result = result.Not(x => Create(not.Argument));
break;
case SelectorGrammar.CommaSyntax comma:
if (results == null)
{
results = new List<Selector>();
}
results.Add(result);
result = null;
break;
default:
throw new NotSupportedException($"Unsupported selector grammar '{i.GetType()}'.");
}
}
if (results != null)
{
if (result != null)
{
results.Add(result);
}
result = results.Count > 1 ? Selectors.Or(results) : results[0];
}
return result;
}
private Type Resolve(string xmlns, string typeName)
{
var result = _typeResolver(xmlns, typeName);
if (result == null)
{
var type = string.IsNullOrWhiteSpace(xmlns) ? typeName : xmlns + ':' + typeName;
throw new InvalidOperationException($"Could not resolve type '{type}'");
}
return result;
}
}
}
| 38.033113 | 123 | 0.460909 | [
"MIT"
] | Artentus/Avalonia | src/Markup/Avalonia.Markup/Markup/Parsers/SelectorParser.cs | 5,743 | C# |
using Domain.Cards;
using FluentNHibernate.Mapping;
using NHibernate.Mapping;
namespace Data.Mappings
{
public class CardMapping: ClassMap<Card>
{
public CardMapping()
{
Table("Cards");
Id(x => x.Id);
Map(x => x.MultiverseId)
.Access.CamelCaseField(Prefix.Underscore)
.Not.Nullable();
Map(x => x.RelatedCardId);
Map(x => x.SetNumber)
.Access.CamelCaseField(Prefix.Underscore);
Map(x => x.Name)
.Not.Nullable()
.Access.CamelCaseField(Prefix.Underscore)
.Length(9999);
Map(x => x.SearchName).Length(9999);
Map(x => x.Description).Length(9999);
Map(x => x.Flavor).Length(9999);
HasMany(x => x.Colors)
.AsBag().Cascade.None()
.Element("Color")
.Access.CamelCaseField(Prefix.Underscore);
Map(x => x.ManaCost)
.Not.Nullable()
.Length(9999)
.Access.CamelCaseField(Prefix.Underscore);
Map(x => x.ConvertedManaCost)
.Not.Nullable()
.Access.CamelCaseField(Prefix.Underscore);
Map(x => x.SetName).Length(9999);
Map(x => x.Type)
.Length(9999)
.Not.Nullable()
.Access.CamelCaseField(Prefix.Underscore);
Map(x => x.SubType).Length(9999);
Map(x => x.Power);
Map(x => x.Toughness);
Map(x => x.Loyalty);
Map(x => x.Rarity)
.Access.CamelCaseField(Prefix.Underscore);
Map(x => x.Artist).Length(9999);
Map(x => x.SetId)
.Not.Nullable();
Map(x => x.IsToken);
Map(x => x.IsPromo);
HasMany(x => x.Rulings)
.Table("Rulings")
//.Element("Id")
.AsSet()
.Access.CamelCaseField(Prefix.Underscore)
.Not.LazyLoad();
HasMany(x => x.Formats)
.Table("Formats")
//.Element("Id")
.AsSet()
.Access.CamelCaseField(Prefix.Underscore)
.Not.LazyLoad();
Map(x => x.ReleaseDate);
}
}
}
| 32.791667 | 58 | 0.463787 | [
"MIT"
] | dicehead3/Kaartenbak | Data/Mappings/CardMapping.cs | 2,363 | C# |
using System.ComponentModel;
using System.Windows;
using MahApps.Metro.Controls;
using MahApps.Metro.Controls.Dialogs;
using MahApps.Metro.SimpleChildWindow.Demo.Properties;
namespace MahApps.Metro.SimpleChildWindow.Demo
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : MetroWindow
{
public MainWindow()
{
this.InitializeComponent();
}
private void FirstTest_OnClick(object sender, RoutedEventArgs e)
{
this.child01.SetCurrentValue(ChildWindow.IsOpenProperty, true);
}
private async void SecTest_OnClick(object sender, RoutedEventArgs e)
{
await this.ShowChildWindowAsync(new TestChildWindow(), this.RootGrid);
}
private async void ThirdTest_OnClick(object sender, RoutedEventArgs e)
{
var result = await this.ShowChildWindowAsync<bool>(new CoolChildWindow() {IsModal = true, AllowMove = true}, ChildWindowManager.OverlayFillBehavior.FullWindow);
if (result)
{
await this.ShowMessageAsync("ChildWindow Result", "He, you just clicked the 'Ok' button.");
}
else
{
await this.ShowMessageAsync("ChildWindow Result", "The dialog was canceled.");
}
}
private void CloseFirst_OnClick(object sender, RoutedEventArgs e)
{
this.child01.Close();
}
private void Child01_OnClosing(object sender, CancelEventArgs e)
{
//e.Cancel = true; // don't close
}
private async void MovingTest_OnClick(object sender, RoutedEventArgs e)
{
var childWindow = new CoolChildWindow() {IsModal = true, AllowMove = true, VerticalContentAlignment = VerticalAlignment.Top, HorizontalContentAlignment = HorizontalAlignment.Left};
var result = await this.ShowChildWindowAsync<CloseReason>(childWindow, RootGrid);
if (result == CloseReason.Cancel)
{
await this.ShowMessageAsync("ChildWindow Result", "The dialog was canceled.");
}
Settings.Default.Save();
}
}
} | 30.984375 | 192 | 0.712557 | [
"MIT"
] | GerHobbelt/MahApps.Metro.SimpleChildWindow | src/MahApps.Metro.SimpleChildWindow.Demo/MainWindow.xaml.cs | 1,985 | C# |
namespace OpenLawOffice.Word
{
partial class LoggingDialog
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.label5 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.LogLevel = new System.Windows.Forms.ComboBox();
this.button1 = new System.Windows.Forms.Button();
this.Cancel = new System.Windows.Forms.Button();
this.Save = new System.Windows.Forms.Button();
this.LogPath = new System.Windows.Forms.TextBox();
this.label3 = new System.Windows.Forms.Label();
this.EnableLogging = new System.Windows.Forms.CheckBox();
this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
this.SuspendLayout();
//
// label5
//
this.label5.Font = new System.Drawing.Font("Arial", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label5.Location = new System.Drawing.Point(12, 9);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(317, 23);
this.label5.TabIndex = 37;
this.label5.Text = "OpenLawOffice: Logging";
this.label5.TextAlign = System.Drawing.ContentAlignment.TopCenter;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Font = new System.Drawing.Font("Arial", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label1.Location = new System.Drawing.Point(12, 128);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(62, 16);
this.label1.TabIndex = 45;
this.label1.Text = "Log Level";
//
// LogLevel
//
this.LogLevel.Font = new System.Drawing.Font("Arial", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.LogLevel.FormattingEnabled = true;
this.LogLevel.Items.AddRange(new object[] {
"Off",
"Fatal",
"Error",
"Warn",
"Info",
"Debug",
"Trace"});
this.LogLevel.Location = new System.Drawing.Point(12, 150);
this.LogLevel.Name = "LogLevel";
this.LogLevel.Size = new System.Drawing.Size(313, 24);
this.LogLevel.TabIndex = 44;
//
// button1
//
this.button1.Font = new System.Drawing.Font("Arial", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.button1.Location = new System.Drawing.Point(303, 49);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(26, 26);
this.button1.TabIndex = 43;
this.button1.Text = "...";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// Cancel
//
this.Cancel.Font = new System.Drawing.Font("Arial", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.Cancel.Location = new System.Drawing.Point(10, 252);
this.Cancel.Name = "Cancel";
this.Cancel.Size = new System.Drawing.Size(315, 25);
this.Cancel.TabIndex = 42;
this.Cancel.Text = "Cancel";
this.Cancel.UseVisualStyleBackColor = true;
this.Cancel.Click += new System.EventHandler(this.Cancel_Click);
//
// Save
//
this.Save.Font = new System.Drawing.Font("Arial", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.Save.Location = new System.Drawing.Point(10, 221);
this.Save.Name = "Save";
this.Save.Size = new System.Drawing.Size(315, 25);
this.Save.TabIndex = 41;
this.Save.Text = "Save";
this.Save.UseVisualStyleBackColor = true;
this.Save.Click += new System.EventHandler(this.Save_Click);
//
// LogPath
//
this.LogPath.Font = new System.Drawing.Font("Arial", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.LogPath.Location = new System.Drawing.Point(12, 51);
this.LogPath.Name = "LogPath";
this.LogPath.Size = new System.Drawing.Size(287, 22);
this.LogPath.TabIndex = 40;
//
// label3
//
this.label3.AutoSize = true;
this.label3.Font = new System.Drawing.Font("Arial", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label3.Location = new System.Drawing.Point(12, 32);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(60, 16);
this.label3.TabIndex = 39;
this.label3.Text = "Log Path";
//
// EnableLogging
//
this.EnableLogging.AutoSize = true;
this.EnableLogging.Font = new System.Drawing.Font("Arial", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.EnableLogging.Location = new System.Drawing.Point(12, 96);
this.EnableLogging.Name = "EnableLogging";
this.EnableLogging.Size = new System.Drawing.Size(116, 20);
this.EnableLogging.TabIndex = 38;
this.EnableLogging.Text = "Enable Logging";
this.EnableLogging.UseVisualStyleBackColor = true;
//
// openFileDialog1
//
this.openFileDialog1.CheckFileExists = false;
this.openFileDialog1.FileName = "Log.txt";
this.openFileDialog1.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
//
// LoggingDialog
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(335, 285);
this.Controls.Add(this.label1);
this.Controls.Add(this.LogLevel);
this.Controls.Add(this.button1);
this.Controls.Add(this.Cancel);
this.Controls.Add(this.Save);
this.Controls.Add(this.LogPath);
this.Controls.Add(this.label3);
this.Controls.Add(this.EnableLogging);
this.Controls.Add(this.label5);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MaximumSize = new System.Drawing.Size(351, 324);
this.MinimizeBox = false;
this.MinimumSize = new System.Drawing.Size(351, 324);
this.Name = "LoggingDialog";
this.ShowIcon = false;
this.ShowInTaskbar = false;
this.Text = "OLO Logging";
this.TopMost = true;
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label label5;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.ComboBox LogLevel;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button Cancel;
private System.Windows.Forms.Button Save;
private System.Windows.Forms.TextBox LogPath;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.CheckBox EnableLogging;
private System.Windows.Forms.OpenFileDialog openFileDialog1;
}
} | 47.236842 | 161 | 0.563677 | [
"Apache-2.0"
] | NodineLegal/OpenLawOffice.Word | OpenLawOffice.Word/LoggingDialog.Designer.cs | 8,977 | C# |
// <copyright file="LogTypesRepository.cs" company="YAGNI">
// All rights reserved.
// </copyright>
// <summary>Holds implementation of LogTypesRepository class.</summary>
using System.Collections.Generic;
using System.Linq;
using LibrarySystem.Data.Logs;
using LibrarySystem.Models.Logs;
using LibrarySystem.Repositories.Abstractions;
using LibrarySystem.Repositories.Contracts.Data.Logs;
namespace LibrarySystem.Repositories.Data.Logs
{
/// <summary>
/// Represent a <see cref="LogTypesRepository"/> class. Heir of <see cref="Repository{LogType}"/>.
/// Implementator of <see cref="ILogTypesRepository"/> interface.
/// </summary>
public class LogTypesRepository : Repository<LogType>, ILogTypesRepository
{
/// <summary>
/// Initializes a new instance of the <see cref="LogTypesRepository"/> class.
/// </summary>
/// <param name="context">Context that provide connection to the database.</param>
public LogTypesRepository(LibrarySystemLogsDbContext context) : base(context)
{
}
/// <summary>
/// Gets the context as a <see cref="LibrarySystemLogsDbContext"/>.
/// </summary>
private LibrarySystemLogsDbContext LogsDbContext
{
get
{
return this.Context as LibrarySystemLogsDbContext;
}
}
/// <summary>
/// Provide instance of log type by a given name.
/// </summary>
/// <param name="logTypeName">Name of the log type.</param>
/// <returns>Instance of the log type with the given name.</returns>
public LogType GetLogTypeByName(string logTypeName)
{
return this.LogsDbContext.LogTypes.FirstOrDefault(lt => lt.Name == logTypeName);
}
}
}
| 35.392157 | 102 | 0.647091 | [
"MIT"
] | TeamYAGNI/LibrarySystem | LibrarySystem/LibrarySystem.Repositories/Data.Logs/LogTypesRepository.cs | 1,807 | C# |
using SharpReact.Core;
using SharpReact.Core.Properties;
using System.Collections.Generic;
namespace SharpReact.Wpf.Props
{
public class ItemsControl: Control
{
public ReactParam<global::System.Collections.IEnumerable>? ItemsSource { get; set; }
public ReactParam<global::System.String>? DisplayMemberPath { get; set; }
public ReactParam<global::System.Windows.DataTemplate>? ItemTemplate { get; set; }
public ReactParam<global::System.Windows.Controls.DataTemplateSelector>? ItemTemplateSelector { get; set; }
public ReactParam<global::System.String>? ItemStringFormat { get; set; }
public ReactParam<global::System.Windows.Data.BindingGroup>? ItemBindingGroup { get; set; }
public ReactParam<global::System.Windows.Style>? ItemContainerStyle { get; set; }
public ReactParam<global::System.Windows.Controls.StyleSelector>? ItemContainerStyleSelector { get; set; }
public ReactParam<global::System.Windows.Controls.ItemsPanelTemplate>? ItemsPanel { get; set; }
public ReactParam<global::System.Windows.Controls.GroupStyleSelector>? GroupStyleSelector { get; set; }
public ReactParam<global::System.Int32>? AlternationCount { get; set; }
public ReactParam<global::System.Boolean>? IsTextSearchEnabled { get; set; }
public ReactParam<global::System.Boolean>? IsTextSearchCaseSensitive { get; set; }
protected override ISharpStatefulComponent CreateComponent()
{
return new Components.ItemsControl<ItemsControl, System.Windows.Controls.ItemsControl>();
}
}
}
| 53.392857 | 109 | 0.780602 | [
"MIT"
] | MihaMarkic/SharpReact | src/Implementations/Wpf/SharpReact.Wpf/Props/ItemsControl.cs | 1,495 | C# |
//--------------------------------------------------
// Motion Framework
// Copyright©2021-2021 何冠峰
// Licensed under the MIT license
//--------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace MotionFramework.Editor
{
[CreateAssetMenu]
public class AssetScanerSetting : ScriptableObject
{
[Serializable]
public class Wrapper
{
public string ScanerDirectory = string.Empty;
public string ScanerName = string.Empty;
}
/// <summary>
/// 路径列表
/// </summary>
public List<Wrapper> Elements = new List<Wrapper>();
}
} | 22.714286 | 54 | 0.608491 | [
"MIT"
] | ArcherPeng/MotionFramework | Assets/MotionFramework/Scripts/Editor/AssetScaner/AssetScanerSetting.cs | 653 | C# |
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/
// Portions Copyright 2000-2004 Jonathan de Halleux
//
// 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 Gallio.Common;
namespace Gallio.Framework.Assertions
{
/// <summary>
/// A delegate for the <see cref="AssertionHelper.Explain(Action, AssertionFailureExplanation)" /> decorator method which
/// combines the specified inner failures into a single outer failure with a common explanation.
/// </summary>
/// <param name="innerFailures">The inner failures to combine together.</param>
/// <returns>The composite assertion failure.</returns>
public delegate AssertionFailure AssertionFailureExplanation(AssertionFailure[] innerFailures);
}
| 45.607143 | 127 | 0.729836 | [
"ECL-2.0",
"Apache-2.0"
] | Gallio/mbunit-v3 | src/Gallio/Gallio/Framework/Assertions/AssertionFailureExplanation.cs | 1,277 | C# |
using System;
using System.Collections.Generic;
using System.Security.Claims;
using Microsoft.AspNetCore.Identity;
namespace RavenDB.AspNetCore.Identity
{
public class IdentityUser
{
public class UserLogin :
IEquatable<UserLogin>,
IEquatable<UserLoginInfo>
{
public UserLogin(UserLoginInfo loginInfo)
{
if (loginInfo == null)
{
throw new ArgumentNullException(nameof(loginInfo));
}
LoginProvider = loginInfo.LoginProvider;
ProviderKey = loginInfo.ProviderKey;
ProviderDisplayName = loginInfo.ProviderDisplayName;
}
public string LoginProvider { get; private set; }
public string ProviderKey { get; private set; }
public string ProviderDisplayName { get; private set; }
public bool Equals(UserLogin other)
{
return other.LoginProvider.Equals(LoginProvider)
&& other.ProviderKey.Equals(ProviderKey);
}
public bool Equals(UserLoginInfo other)
{
return other.LoginProvider.Equals(LoginProvider)
&& other.ProviderKey.Equals(ProviderKey);
}
}
public class UserClaim : IEquatable<UserClaim>, IEquatable<Claim>
{
public UserClaim(Claim claim)
{
if (claim == null)
{
throw new ArgumentNullException(nameof(claim));
}
ClaimType = claim.Type;
ClaimValue = claim.Value;
}
public UserClaim(string claimType, string claimValue)
{
if (claimType == null)
{
throw new ArgumentNullException(nameof(claimType));
}
if (claimValue == null)
{
throw new ArgumentNullException(nameof(claimValue));
}
ClaimType = claimType;
ClaimValue = claimValue;
}
public string ClaimType { get; private set; }
public string ClaimValue { get; private set; }
public bool Equals(UserClaim other)
{
return other.ClaimType.Equals(ClaimType)
&& other.ClaimValue.Equals(ClaimValue);
}
public bool Equals(Claim other)
{
return other.Type.Equals(ClaimType)
&& other.Value.Equals(ClaimValue);
}
}
public abstract class UserContactRecord : IEquatable<UserEmail>
{
protected UserContactRecord(string value)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
Value = value;
}
public string Value { get; private set; }
public ConfirmationOccurrence ConfirmationRecord { get; private set; }
public bool IsConfirmed()
{
return ConfirmationRecord != null;
}
public void SetConfirmed()
{
SetConfirmed(new ConfirmationOccurrence());
}
public void SetConfirmed(ConfirmationOccurrence confirmationRecord)
{
if (ConfirmationRecord == null)
{
ConfirmationRecord = confirmationRecord;
}
}
public void SetUnconfirmed()
{
ConfirmationRecord = null;
}
public bool Equals(UserEmail other)
{
return other.Value.Equals(Value);
}
}
public class UserPhoneNumber :
UserContactRecord
{
public UserPhoneNumber(string phoneNumber) :
base(phoneNumber)
{
}
}
public class UserEmail :
UserContactRecord
{
public UserEmail(string email) :
base(email)
{
}
public string NormalizedValue { get; set; }
}
public IdentityUser()
{
}
public IdentityUser(string userName, string email)
: this(userName)
{
if (email != null)
{
Email = new UserEmail(email);
}
}
public IdentityUser(string userName, UserEmail email)
: this(userName)
{
if (email != null)
{
Email = email;
}
}
public IdentityUser(string userName)
{
if (userName == null)
{
throw new ArgumentNullException(nameof(userName));
}
Id = GenerateId(userName);
UserName = userName;
CreatedOn = new Occurrence();
Claims = new List<UserClaim>();
Logins = new List<UserLogin>();
Roles = new List<string>();
}
public string Id { get; private set; }
public string UserName { get; set; }
public string NormalizedUserName { get; set; }
public UserEmail Email { get; set; }
public UserPhoneNumber PhoneNumber { get; set; }
public bool IsTwoFactorEnabled { get; set; }
public List<UserClaim> Claims { get; set; }
public List<UserLogin> Logins { get; set; }
public List<string> Roles { get; set; }
public int AccessFailedCount { get; set; }
public bool IsLockoutEnabled { get; set; }
public string PasswordHash { get; set; }
public string SecurityStamp { get; set; }
public FutureOccurrence LockoutEndDate { get; private set; }
public Occurrence CreatedOn { get; private set; }
public virtual void ResetAccessFailedCount()
{
AccessFailedCount = 0;
}
public virtual void LockUntil(DateTime lockoutEndDate)
{
LockoutEndDate = new FutureOccurrence(lockoutEndDate);
}
private static string GenerateId(string userName)
{
return "IdentityUsers/" + userName.ToLower();
}
}
}
| 28.359649 | 82 | 0.504949 | [
"Apache-2.0"
] | xinix00/RavenDB.AspNetCore.Identity | src/RavenDB.AspNetCore.Identity/IdentityUser.cs | 6,468 | C# |
namespace Bus_Lite.Listeners
{
public interface IEventObserver
{
object Owner { get; }
ObserverToken Token { get; }
bool ShouldInvoke(object @event);
object Invoke(object @event);
}
}
| 20.818182 | 41 | 0.611354 | [
"MIT"
] | dawids222/Bus-Lite | Bus-Lite/Observers/IEventObserver.cs | 231 | C# |
using UnityEngine;
using System;
using ActiveObjects.Triggers;
namespace ActiveObjects
{
namespace GameSkill
{
public class ZombieCurse :
Skill
{
[RequiredField]
[Tooltip("Префаб огня.")]
public Transform FirePrefab;
[Tooltip("Урон.")]
public float Damage;
[Tooltip("Время дня при котором работает скил.")]
public TimeUnitTrigger DayTime;
[Tooltip("Периодичность нанесения урона в секундах.")]
public TimerTrigger Timer;
protected override void Awake()
{
base.Awake();
DayTime.Active += DayTime_Active;
DayTime.Deactive += DateTime_Deactive;
Timer.Active += Timer_Active;
}
protected override void Activate()
{
DayTime.Enable();
}
protected override void Deactivate()
{
DayTime.Disable();
Timer.Disable();
}
private void DayTime_Active(object sender, EventArgs e)
{
FirePrefab.gameObject.SetActive(true);
Timer.Enable();
}
private void DateTime_Deactive(object sender, EventArgs e)
{
FirePrefab.gameObject.SetActive(false);
Timer.Disable();
}
private void Timer_Active(object sender, EventArgs e)
{
Owner.ChangeHealth(-Damage, Creator);
}
}
}
} | 29.309091 | 70 | 0.503722 | [
"MIT"
] | Sumrix/DAZVillage | Assets/Scripts/ActiveObjects/Skill/ZombieCurse.cs | 1,694 | C# |
using Base;
using UnityEngine;
namespace Asteroids
{
public class SimpleNoiseFilter : INoiseFilter
{
private readonly SimpleNoiseSettings _noiseSettings;
private readonly Noise _noise;
public SimpleNoiseFilter(SimpleNoiseSettings noiseSettings)
{
_noiseSettings = noiseSettings;
_noise = new Noise();
}
public float Evaluate(Vector3 vector)
{
float noiseValue = 0;
float frequency = _noiseSettings.baseRoughness;
float amplitude = 1;
for (int i = 0; i < _noiseSettings.numberOfLayers; i++)
{
float v = _noise.Evaluate(vector * frequency + _noiseSettings.centre);
noiseValue += (v + 1) * 0.5f * amplitude;
frequency *= _noiseSettings.roughness;
amplitude *= _noiseSettings.persistence;
}
noiseValue = Mathf.Max(noiseValue, _noiseSettings.minValue);
return noiseValue * _noiseSettings.strength;
}
}
} | 29.583333 | 86 | 0.589671 | [
"MIT"
] | ArildF/Debris | Assets/Asteroids/SimpleNoiseFilter.cs | 1,065 | C# |
using ProcessUtil;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace HamsterCheese.AmongUsMemory
{
public static class Cheese
{
public static Memory.Mem mem = new Memory.Mem();
public static ProcessMemory ProcessMemory = null;
public static bool Init()
{
var state = mem.OpenProcess("Among Us");
if (state)
{
Methods.Init();
Process proc = Process.GetProcessesByName("Among Us")[0];
ProcessMemory = new ProcessMemory(proc);
ProcessMemory.Open(ProcessAccess.AllAccess);
return true;
}
return false;
}
private static ShipStatus prevShipStatus;
public static ShipStatus shipStatus;
public static AmongUsClient amongUsClient;
public static IntPtr amongUsClientPtr;
public static String shipStatusAddress;
public static IntPtr shipStatusPTR;
private static Dictionary<string, CancellationTokenSource> Tokens = new Dictionary<string, CancellationTokenSource>();
private static System.Action<uint> onChangeShipStatus;
static void _ObserveShipStatus()
{
while (Tokens.ContainsKey("ObserveShipStatus") && Tokens["ObserveShipStatus"].IsCancellationRequested == false)
{
Thread.Sleep(250);
shipStatus = Cheese.GetShipStatus();
if (prevShipStatus.OwnerId != shipStatus.OwnerId)
{
prevShipStatus = shipStatus;
onChangeShipStatus?.Invoke(shipStatus.Type);
Console.WriteLine("OnShipStatusChanged");
}
else
{
}
}
}
/// <summary>
/// Subscribe shipstatus changed.
/// </summary>
/// <param name="onChangeShipStatus"></param>
public static void ObserveShipStatus(System.Action<uint> onChangeShipStatus)
{
CancellationTokenSource cts = new CancellationTokenSource();
if (Tokens.ContainsKey("ObserveShipStatus"))
{
Tokens["ObserveShipStatus"].Cancel();
Tokens.Remove("ObserveShipStatus");
}
Tokens.Add("ObserveShipStatus", cts);
Cheese.onChangeShipStatus = onChangeShipStatus;
Task.Factory.StartNew(_ObserveShipStatus, cts.Token);
}
/// <summary>
/// Get Ship Status From AmongUs Proccess
/// </summary>
/// <returns></returns>
public static ShipStatus GetShipStatus()
{
ShipStatus shipStatus = new ShipStatus();
byte[] shipAob = Cheese.mem.ReadBytes(Pattern.ShipStatus_Pointer, Utils.SizeOf<ShipStatus>());
var aobStr = MakeAobString(shipAob, 4, "00 00 00 00 ?? ?? ?? ??");
var aobResults = Cheese.mem.AoBScan(aobStr, true, true);
aobResults.Wait();
foreach (var result in aobResults.Result)
{
byte[] resultByte = Cheese.mem.ReadBytes(result.GetAddress(), Utils.SizeOf<ShipStatus>());
ShipStatus resultInst = Utils.FromBytes<ShipStatus>(resultByte);
if (resultInst.AllVents != IntPtr.Zero && resultInst.NetId < uint.MaxValue - 10000)
{
if (resultInst.MapScale < 6470545000000 && resultInst.MapScale > 0.1f)
{
shipStatus = resultInst;
shipStatusAddress = result.GetAddress();
shipStatusPTR = new IntPtr((int)result);
//Console.WriteLine(result.GetAddress());
}
}
}
return shipStatus;
}
public static AmongUsClient getAmongUsClient()
{
AmongUsClient client = new AmongUsClient();
byte[] clientAob = Cheese.mem.ReadBytes(Pattern.AmongusClient_Pointer, Utils.SizeOf<AmongUsClient>());
var aobStr = MakeAobString(clientAob, 4, "00 00 00 00 ?? ?? ?? ??");
var aobResults = Cheese.mem.AoBScan(aobStr, true, true);
aobResults.Wait();
foreach (var result in aobResults.Result)
{
byte[] resultByte = Cheese.mem.ReadBytes(result.GetAddress(), Utils.SizeOf<AmongUsClient>());
AmongUsClient resultInst = Utils.FromBytes<AmongUsClient>(resultByte);
Console.WriteLine(result.GetAddress());
Console.WriteLine(resultInst.timer + " | " + resultInst.IsGamePublic + " | " + ClientData.gameState(new IntPtr((int)result)) + " | " + resultInst.SpawnRadius + " | " + ClientData.state(new IntPtr((int)result)) + " | " + ClientData.gameMode(new IntPtr((int)result)) + " | " + (resultInst.allObjects != IntPtr.Zero));
if (resultInst.SpawnRadius > 0.2)
{
client = resultInst;
amongUsClient = client;
//amongUsClientPtr = result.GetAddress();
amongUsClientPtr = new IntPtr((int)result);
//Console.WriteLine(result.GetAddress());
}
}
return client;
}
public static string MakeAobString(byte[] aobTarget, int length, string unknownText = "?? ?? ?? ??")
{
int cnt = 0;
// aob pattern
string aobData = "";
// read 4byte aob pattern.
foreach (var _byte in aobTarget)
{
if (_byte < 16)
aobData += "0" + _byte.ToString("X");
else
aobData += _byte.ToString("X");
if (cnt + 1 != 4)
aobData += " ";
cnt++;
if (cnt == length)
{
aobData += $" {unknownText}";
break;
}
}
return aobData;
}
/// <summary>
/// Get All Players From AmongUs Proccess
/// </summary>
/// <returns></returns>
public static List<PlayerData> GetAllPlayers()
{
List<PlayerData > datas = new List<PlayerData>();
// find player pointer
byte[] playerAoB = Cheese.mem.ReadBytes(Pattern.PlayerControl_Pointer, Utils.SizeOf<PlayerControl>());
// aob pattern
string aobData = MakeAobString(playerAoB, 4, "?? ?? ?? ??");
// get result
var result = Cheese.mem.AoBScan(aobData, true, true);
result.Wait();
var results = result.Result;
// real-player
foreach (var x in results)
{
var bytes = Cheese.mem.ReadBytes(x.GetAddress(), Utils.SizeOf<PlayerControl>());
var PlayerControl = Utils.FromBytes<PlayerControl>(bytes);
// filter garbage instance datas.
if (PlayerControl.SpawnFlags == 257 && PlayerControl.NetId < uint.MaxValue - 10000)
{
datas.Add(new PlayerData()
{
Instance = PlayerControl,
PlayerControllPTROffset = x.GetAddress(),
PlayerControllPTR = new IntPtr((int)x)
});
}
}
Console.WriteLine("data => " + datas.Count);
return datas;
}
}
}
| 37.582524 | 331 | 0.528158 | [
"MIT"
] | altskop/GlaDOS-bot | AmongUsMemory/Cheese.cs | 7,744 | C# |
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class FriendsPanelManager : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler
{
private Animator panelAnimator;
private bool isOpen = false;
void Start()
{
panelAnimator = this.GetComponent<Animator>();
}
public void OnPointerEnter(PointerEventData eventData)
{
panelAnimator.Play("Friends Panel In");
}
public void OnPointerExit(PointerEventData eventData)
{
panelAnimator.Play("Friends Panel Out");
}
} | 23.5 | 91 | 0.70922 | [
"MIT"
] | SilverMaple/TalkingBuildings | Assets/MainMenu/Scripts/FriendsPanelManager.cs | 566 | C# |
using System;
using Microsoft.AspNetCore.Mvc;
namespace Esfa.Recruit.Provider.Web.RouteModel
{
public class ApplicationReviewRouteModel : VacancyRouteModel
{
[FromRoute]
public Guid ApplicationReviewId { get; set; }
}
}
| 20.833333 | 64 | 0.712 | [
"MIT"
] | SkillsFundingAgency/das-recru | src/Provider/Provider.Web/RouteModel/ApplicationReviewRouteModel.cs | 252 | C# |
namespace Orc.FilterBuilder
{
using System;
using System.Diagnostics;
[DebuggerDisplay("{ValueControlType} {SelectedCondition} {Value}")]
public class TimeSpanValueExpression : ValueDataTypeExpression<TimeSpan>
{
public TimeSpanValueExpression()
: this(true)
{
}
public TimeSpanValueExpression(bool isNullable)
{
IsNullable = isNullable;
Value = TimeSpan.Zero;
ValueControlType = ValueControlType.TimeSpan;
}
}
}
| 24.363636 | 76 | 0.621269 | [
"MIT"
] | Orcomp/Orc.FilterBuilder | src/Orc.FilterBuilder/Expressions/TimeSpanValueExpression.cs | 538 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MoonSharp.Interpreter.DataStructs
{
/// <summary>
/// Provides facility to create a "sliced" view over an existing IList<typeparamref name="T"/>
/// </summary>
/// <typeparam name="T">The type of the items contained in the collection</typeparam>
internal class Slice<T> : IEnumerable<T>, IList<T>
{
IList<T> m_SourceList;
int m_From, m_Length;
bool m_Reversed;
/// <summary>
/// Initializes a new instance of the <see cref="Slice{T}"/> class.
/// </summary>
/// <param name="list">The list to apply the Slice view on</param>
/// <param name="from">From which index</param>
/// <param name="length">The length of the slice</param>
/// <param name="reversed">if set to <c>true</c> the view is in reversed order.</param>
public Slice(IList<T> list, int from, int length, bool reversed)
{
m_SourceList = list;
m_From = from;
m_Length = length;
m_Reversed = reversed;
}
/// <summary>
/// Gets or sets the element at the specified index.
/// </summary>
/// <param name="index">The index.</param>
/// <returns></returns>
public T this[int index]
{
get
{
return m_SourceList[CalcRealIndex(index)];
}
set
{
m_SourceList[CalcRealIndex(index)] = value;
}
}
/// <summary>
/// Gets the index from which the slice starts
/// </summary>
public int From
{
get { return m_From; }
}
/// <summary>
/// Gets the number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1" />.
/// </summary>
/// <returns>The number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1" />.</returns>
public int Count
{
get { return m_Length; }
}
/// <summary>
/// Gets a value indicating whether this <see cref="Slice{T}"/> operates in a reversed direction.
/// </summary>
/// <value>
/// <c>true</c> if this <see cref="Slice{T}"/> operates in a reversed direction; otherwise, <c>false</c>.
/// </value>
public bool Reversed
{
get { return m_Reversed; }
}
/// <summary>
/// Calculates the real index in the underlying collection
/// </summary>
private int CalcRealIndex(int index)
{
if (index < 0 || index >= m_Length)
throw new ArgumentOutOfRangeException("index");
if (m_Reversed)
{
return m_From + m_Length - index - 1;
}
else
{
return m_From + index;
}
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A <see cref="T:System.Collections.Generic.IEnumerator`1" /> that can be used to iterate through the collection.
/// </returns>
public IEnumerator<T> GetEnumerator()
{
for (int i = 0; i < m_Length; i++)
yield return m_SourceList[CalcRealIndex(i)];
}
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>
/// An <see cref="T:System.Collections.IEnumerator" /> object that can be used to iterate through the collection.
/// </returns>
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
for (int i = 0; i < m_Length; i++)
yield return m_SourceList[CalcRealIndex(i)];
}
/// <summary>
/// Converts to an array.
/// </summary>
public T[] ToArray()
{
T[] array = new T[m_Length];
for (int i = 0; i < m_Length; i++)
array[i] = m_SourceList[CalcRealIndex(i)];
return array;
}
/// <summary>
/// Converts to an list.
/// </summary>
public List<T> ToList()
{
List<T> list = new List<T>(m_Length);
for (int i = 0; i < m_Length; i++)
list.Add(m_SourceList[CalcRealIndex(i)]);
return list;
}
/// <summary>
/// Determines the index of a specific item in the <see cref="T:System.Collections.Generic.IList`1" />.
/// </summary>
/// <param name="item">The object to locate in the <see cref="T:System.Collections.Generic.IList`1" />.</param>
/// <returns>
/// The index of <paramref name="item" /> if found in the list; otherwise, -1.
/// </returns>
public int IndexOf(T item)
{
for (int i = 0; i < this.Count; i++)
{
if (this[i].Equals(item))
return i;
}
return -1;
}
/// <summary>
/// Inserts an item to the <see cref="T:System.Collections.Generic.IList`1" /> at the specified index.
/// </summary>
/// <param name="index">The zero-based index at which <paramref name="item" /> should be inserted.</param>
/// <param name="item">The object to insert into the <see cref="T:System.Collections.Generic.IList`1" />.</param>
/// <exception cref="System.InvalidOperationException">Slices are readonly</exception>
public void Insert(int index, T item)
{
throw new InvalidOperationException("Slices are readonly");
}
/// <summary>
/// Removes the <see cref="T:System.Collections.Generic.IList`1" /> item at the specified index.
/// </summary>
/// <param name="index">The zero-based index of the item to remove.</param>
/// <exception cref="System.InvalidOperationException">Slices are readonly</exception>
public void RemoveAt(int index)
{
throw new InvalidOperationException("Slices are readonly");
}
/// <summary>
/// Adds an item to the <see cref="T:System.Collections.Generic.ICollection`1" />.
/// </summary>
/// <param name="item">The object to add to the <see cref="T:System.Collections.Generic.ICollection`1" />.</param>
/// <exception cref="System.InvalidOperationException">Slices are readonly</exception>
public void Add(T item)
{
throw new InvalidOperationException("Slices are readonly");
}
/// <summary>
/// Removes all items from the <see cref="T:System.Collections.Generic.ICollection`1" />.
/// </summary>
/// <exception cref="System.InvalidOperationException">Slices are readonly</exception>
public void Clear()
{
throw new InvalidOperationException("Slices are readonly");
}
/// <summary>
/// Determines whether the <see cref="T:System.Collections.Generic.ICollection`1" /> contains a specific value.
/// </summary>
/// <param name="item">The object to locate in the <see cref="T:System.Collections.Generic.ICollection`1" />.</param>
/// <returns>
/// true if <paramref name="item" /> is found in the <see cref="T:System.Collections.Generic.ICollection`1" />; otherwise, false.
/// </returns>
public bool Contains(T item)
{
return IndexOf(item) >= 0;
}
/// <summary>
/// Copies to.
/// </summary>
/// <param name="array">The array.</param>
/// <param name="arrayIndex">Index of the array.</param>
public void CopyTo(T[] array, int arrayIndex)
{
for (int i = 0; i < Count; i++)
array[i + arrayIndex] = this[i];
}
/// <summary>
/// Gets a value indicating whether the <see cref="T:System.Collections.Generic.ICollection`1" /> is read-only.
/// </summary>
/// <returns>true if the <see cref="T:System.Collections.Generic.ICollection`1" /> is read-only; otherwise, false.</returns>
public bool IsReadOnly
{
get { return true; }
}
/// <summary>
/// Removes the first occurrence of a specific object from the <see cref="T:System.Collections.Generic.ICollection`1" />.
/// </summary>
/// <param name="item">The object to remove from the <see cref="T:System.Collections.Generic.ICollection`1" />.</param>
/// <returns>
/// true if <paramref name="item" /> was successfully removed from the <see cref="T:System.Collections.Generic.ICollection`1" />; otherwise, false. This method also returns false if <paramref name="item" /> is not found in the original <see cref="T:System.Collections.Generic.ICollection`1" />.
/// </returns>
/// <exception cref="System.InvalidOperationException">Slices are readonly</exception>
public bool Remove(T item)
{
throw new InvalidOperationException("Slices are readonly");
}
}
}
| 32.536 | 297 | 0.633268 | [
"Unlicense"
] | RenVoc/MindVector | MindVector/Assets/Fungus/Thirdparty/FungusLua/Thirdparty/MoonSharp/Interpreter/DataStructs/Slice.cs | 8,136 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// ANTLR Version: 4.3
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
// Generated from IrbisQuery.g4 by ANTLR 4.3
// Unreachable code detected
#pragma warning disable 0162
// The variable '...' is assigned but its value is never used
#pragma warning disable 0219
// Missing XML comment for publicly visible type or member '...'
#pragma warning disable 1591
namespace ManagedClient.Query {
using Antlr4.Runtime.Misc;
using IParseTreeListener = Antlr4.Runtime.Tree.IParseTreeListener;
using IToken = Antlr4.Runtime.IToken;
/// <summary>
/// This interface defines a complete listener for a parse tree produced by
/// <see cref="IrbisQueryParser"/>.
/// </summary>
[System.CodeDom.Compiler.GeneratedCode("ANTLR", "4.3")]
[System.CLSCompliant(false)]
public interface IIrbisQueryListener : IParseTreeListener {
/// <summary>
/// Enter a parse tree produced by the <c>starOperator2</c>
/// labeled alternative in <see cref="IrbisQueryParser.levelTwo"/>.
/// </summary>
/// <param name="context">The parse tree.</param>
void EnterStarOperator2([NotNull] IrbisQueryParser.StarOperator2Context context);
/// <summary>
/// Exit a parse tree produced by the <c>starOperator2</c>
/// labeled alternative in <see cref="IrbisQueryParser.levelTwo"/>.
/// </summary>
/// <param name="context">The parse tree.</param>
void ExitStarOperator2([NotNull] IrbisQueryParser.StarOperator2Context context);
/// <summary>
/// Enter a parse tree produced by the <c>starOperator3</c>
/// labeled alternative in <see cref="IrbisQueryParser.levelThree"/>.
/// </summary>
/// <param name="context">The parse tree.</param>
void EnterStarOperator3([NotNull] IrbisQueryParser.StarOperator3Context context);
/// <summary>
/// Exit a parse tree produced by the <c>starOperator3</c>
/// labeled alternative in <see cref="IrbisQueryParser.levelThree"/>.
/// </summary>
/// <param name="context">The parse tree.</param>
void ExitStarOperator3([NotNull] IrbisQueryParser.StarOperator3Context context);
/// <summary>
/// Enter a parse tree produced by the <c>starOperator1</c>
/// labeled alternative in <see cref="IrbisQueryParser.levelOne"/>.
/// </summary>
/// <param name="context">The parse tree.</param>
void EnterStarOperator1([NotNull] IrbisQueryParser.StarOperator1Context context);
/// <summary>
/// Exit a parse tree produced by the <c>starOperator1</c>
/// labeled alternative in <see cref="IrbisQueryParser.levelOne"/>.
/// </summary>
/// <param name="context">The parse tree.</param>
void ExitStarOperator1([NotNull] IrbisQueryParser.StarOperator1Context context);
/// <summary>
/// Enter a parse tree produced by the <c>plusOperator3</c>
/// labeled alternative in <see cref="IrbisQueryParser.levelThree"/>.
/// </summary>
/// <param name="context">The parse tree.</param>
void EnterPlusOperator3([NotNull] IrbisQueryParser.PlusOperator3Context context);
/// <summary>
/// Exit a parse tree produced by the <c>plusOperator3</c>
/// labeled alternative in <see cref="IrbisQueryParser.levelThree"/>.
/// </summary>
/// <param name="context">The parse tree.</param>
void ExitPlusOperator3([NotNull] IrbisQueryParser.PlusOperator3Context context);
/// <summary>
/// Enter a parse tree produced by the <c>plusOperator2</c>
/// labeled alternative in <see cref="IrbisQueryParser.levelTwo"/>.
/// </summary>
/// <param name="context">The parse tree.</param>
void EnterPlusOperator2([NotNull] IrbisQueryParser.PlusOperator2Context context);
/// <summary>
/// Exit a parse tree produced by the <c>plusOperator2</c>
/// labeled alternative in <see cref="IrbisQueryParser.levelTwo"/>.
/// </summary>
/// <param name="context">The parse tree.</param>
void ExitPlusOperator2([NotNull] IrbisQueryParser.PlusOperator2Context context);
/// <summary>
/// Enter a parse tree produced by the <c>fOperator</c>
/// labeled alternative in <see cref="IrbisQueryParser.levelOne"/>.
/// </summary>
/// <param name="context">The parse tree.</param>
void EnterFOperator([NotNull] IrbisQueryParser.FOperatorContext context);
/// <summary>
/// Exit a parse tree produced by the <c>fOperator</c>
/// labeled alternative in <see cref="IrbisQueryParser.levelOne"/>.
/// </summary>
/// <param name="context">The parse tree.</param>
void ExitFOperator([NotNull] IrbisQueryParser.FOperatorContext context);
/// <summary>
/// Enter a parse tree produced by the <c>parenOuter</c>
/// labeled alternative in <see cref="IrbisQueryParser.levelTwo"/>.
/// </summary>
/// <param name="context">The parse tree.</param>
void EnterParenOuter([NotNull] IrbisQueryParser.ParenOuterContext context);
/// <summary>
/// Exit a parse tree produced by the <c>parenOuter</c>
/// labeled alternative in <see cref="IrbisQueryParser.levelTwo"/>.
/// </summary>
/// <param name="context">The parse tree.</param>
void ExitParenOuter([NotNull] IrbisQueryParser.ParenOuterContext context);
/// <summary>
/// Enter a parse tree produced by the <c>gOperator</c>
/// labeled alternative in <see cref="IrbisQueryParser.levelOne"/>.
/// </summary>
/// <param name="context">The parse tree.</param>
void EnterGOperator([NotNull] IrbisQueryParser.GOperatorContext context);
/// <summary>
/// Exit a parse tree produced by the <c>gOperator</c>
/// labeled alternative in <see cref="IrbisQueryParser.levelOne"/>.
/// </summary>
/// <param name="context">The parse tree.</param>
void ExitGOperator([NotNull] IrbisQueryParser.GOperatorContext context);
/// <summary>
/// Enter a parse tree produced by the <c>plusOperator1</c>
/// labeled alternative in <see cref="IrbisQueryParser.levelOne"/>.
/// </summary>
/// <param name="context">The parse tree.</param>
void EnterPlusOperator1([NotNull] IrbisQueryParser.PlusOperator1Context context);
/// <summary>
/// Exit a parse tree produced by the <c>plusOperator1</c>
/// labeled alternative in <see cref="IrbisQueryParser.levelOne"/>.
/// </summary>
/// <param name="context">The parse tree.</param>
void ExitPlusOperator1([NotNull] IrbisQueryParser.PlusOperator1Context context);
/// <summary>
/// Enter a parse tree produced by the <c>reference</c>
/// labeled alternative in <see cref="IrbisQueryParser.levelThree"/>.
/// </summary>
/// <param name="context">The parse tree.</param>
void EnterReference([NotNull] IrbisQueryParser.ReferenceContext context);
/// <summary>
/// Exit a parse tree produced by the <c>reference</c>
/// labeled alternative in <see cref="IrbisQueryParser.levelThree"/>.
/// </summary>
/// <param name="context">The parse tree.</param>
void ExitReference([NotNull] IrbisQueryParser.ReferenceContext context);
/// <summary>
/// Enter a parse tree produced by <see cref="IrbisQueryParser.program"/>.
/// </summary>
/// <param name="context">The parse tree.</param>
void EnterProgram([NotNull] IrbisQueryParser.ProgramContext context);
/// <summary>
/// Exit a parse tree produced by <see cref="IrbisQueryParser.program"/>.
/// </summary>
/// <param name="context">The parse tree.</param>
void ExitProgram([NotNull] IrbisQueryParser.ProgramContext context);
/// <summary>
/// Enter a parse tree produced by the <c>entry</c>
/// labeled alternative in <see cref="IrbisQueryParser.levelOne"/>.
/// </summary>
/// <param name="context">The parse tree.</param>
void EnterEntry([NotNull] IrbisQueryParser.EntryContext context);
/// <summary>
/// Exit a parse tree produced by the <c>entry</c>
/// labeled alternative in <see cref="IrbisQueryParser.levelOne"/>.
/// </summary>
/// <param name="context">The parse tree.</param>
void ExitEntry([NotNull] IrbisQueryParser.EntryContext context);
/// <summary>
/// Enter a parse tree produced by the <c>levelTwoOuter</c>
/// labeled alternative in <see cref="IrbisQueryParser.levelThree"/>.
/// </summary>
/// <param name="context">The parse tree.</param>
void EnterLevelTwoOuter([NotNull] IrbisQueryParser.LevelTwoOuterContext context);
/// <summary>
/// Exit a parse tree produced by the <c>levelTwoOuter</c>
/// labeled alternative in <see cref="IrbisQueryParser.levelThree"/>.
/// </summary>
/// <param name="context">The parse tree.</param>
void ExitLevelTwoOuter([NotNull] IrbisQueryParser.LevelTwoOuterContext context);
/// <summary>
/// Enter a parse tree produced by the <c>dotOperator</c>
/// labeled alternative in <see cref="IrbisQueryParser.levelOne"/>.
/// </summary>
/// <param name="context">The parse tree.</param>
void EnterDotOperator([NotNull] IrbisQueryParser.DotOperatorContext context);
/// <summary>
/// Exit a parse tree produced by the <c>dotOperator</c>
/// labeled alternative in <see cref="IrbisQueryParser.levelOne"/>.
/// </summary>
/// <param name="context">The parse tree.</param>
void ExitDotOperator([NotNull] IrbisQueryParser.DotOperatorContext context);
/// <summary>
/// Enter a parse tree produced by the <c>levelOneOuter</c>
/// labeled alternative in <see cref="IrbisQueryParser.levelTwo"/>.
/// </summary>
/// <param name="context">The parse tree.</param>
void EnterLevelOneOuter([NotNull] IrbisQueryParser.LevelOneOuterContext context);
/// <summary>
/// Exit a parse tree produced by the <c>levelOneOuter</c>
/// labeled alternative in <see cref="IrbisQueryParser.levelTwo"/>.
/// </summary>
/// <param name="context">The parse tree.</param>
void ExitLevelOneOuter([NotNull] IrbisQueryParser.LevelOneOuterContext context);
}
} // namespace ManagedClient.Search
| 43.057522 | 82 | 0.705477 | [
"MIT"
] | amironov73/ManagedClient.3 | ManagedClient/Query/IrbisQueryListener.cs | 9,731 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace AdventureWorks.Data.Entities
{
using System;
using System.Collections.Generic;
public partial class ShoppingCartItem
{
public int ShoppingCartItemID { get; set; }
public string ShoppingCartID { get; set; }
public int Quantity { get; set; }
public int ProductID { get; set; }
public System.DateTime DateCreated { get; set; }
public System.DateTime ModifiedDate { get; set; }
public virtual Product Product { get; set; }
}
}
| 34.925926 | 85 | 0.54719 | [
"Apache-2.0"
] | AsimKhan2019/AdventuresWorks-Web-API | AdventureWorks.Data/Entities/ShoppingCartItem.cs | 943 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Raml.Parser.Expressions;
namespace Raml.Parser.Builders
{
public class ResponsesBuilder
{
private readonly IDictionary<string, object> dynamicRaml;
public ResponsesBuilder(IDictionary<string, object> dynamicRaml)
{
this.dynamicRaml = dynamicRaml;
}
public IEnumerable<Response> Get(string defaultMediaType)
{
var list = new List<Response>();
if (dynamicRaml == null)
return list;
foreach (var pair in dynamicRaml)
{
var value = pair.Value as IDictionary<string, object>;
if(value == null)
continue;
list.Add(new Response
{
Code = pair.Key,
Description = value.ContainsKey("description") ? value["description"] as string : null,
Body = GetBody(defaultMediaType, value),
Headers = GetHeaders(value),
Annotations = AnnotationsBuilder.GetAnnotations(value)
});
}
return list;
}
private static IDictionary<string, Parameter> GetHeaders(IDictionary<string, object> value)
{
if (!value.ContainsKey("headers"))
return new Dictionary<string, Parameter>();
var asDictionary = value["headers"] as IDictionary<string, object>;
if(asDictionary != null)
return new ParametersBuilder(asDictionary).GetAsDictionary();
var asObjArray = value["headers"] as object[];
if (asObjArray != null)
return GetObjectArrayHeaders(asObjArray);
throw new InvalidOperationException("Unable to parse headers");
}
private static IDictionary<string, Parameter> GetObjectArrayHeaders(IEnumerable<object> asObjArray)
{
var headers = new Dictionary<string, Parameter>();
foreach (IDictionary<string, object> header in asObjArray)
{
var param = new ParameterBuilder().Build(header);
var key = header["name"] as string;
if (key != null)
headers.Add(key, param);
}
return headers;
}
private static IDictionary<string, MimeType> GetBody(string defaultMediaType, IDictionary<string, object> value)
{
if (!value.ContainsKey("body"))
return null;
var objArr = value["body"] as object[];
if(objArr != null)
return new BodyBuilder((IDictionary<string, object>) objArr.First()).GetAsDictionary(defaultMediaType);
var dictionary = value["body"] as IDictionary<string, object>;
return new BodyBuilder(dictionary).GetAsDictionary(defaultMediaType);
}
public IDictionary<string, Response> GetAsDictionary(string defaultMediaType)
{
if(dynamicRaml == null)
return new Dictionary<string, Response>();
return dynamicRaml
.ToDictionary(kv => kv.Key,
kv =>
{
var value = (IDictionary<string, object>) kv.Value;
return new Response
{
Code = kv.Key,
Description =
value.ContainsKey("description")
? value["description"] as string
: null,
Body =
value.ContainsKey("body")
? new BodyBuilder(
value["body"] as IDictionary<string, object>).GetAsDictionary(defaultMediaType)
: null
};
});
}
}
} | 31.630631 | 119 | 0.593563 | [
"Apache-2.0"
] | raml-org/raml-dotnet-parser-2 | source/Raml.Parser/Builders/ResponsesBuilder.cs | 3,513 | C# |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Newtonsoft.Json;
using Skender.Stock.Indicators;
namespace Internal.Tests;
[TestClass]
public class ZigZag : TestBase
{
[TestMethod]
public void StandardClose()
{
List<ZigZagResult> results =
quotes.GetZigZag(EndType.Close, 3)
.ToList();
// assertions
// proper quantities
// should always be the same number of results as there is quotes
Assert.AreEqual(502, results.Count);
Assert.AreEqual(234, results.Where(x => x.ZigZag != null).Count());
Assert.AreEqual(234, results.Where(x => x.RetraceHigh != null).Count());
Assert.AreEqual(221, results.Where(x => x.RetraceLow != null).Count());
Assert.AreEqual(14, results.Where(x => x.PointType != null).Count());
// sample values
ZigZagResult r0 = results[249];
Assert.AreEqual(null, r0.ZigZag);
Assert.AreEqual(null, r0.RetraceHigh);
Assert.AreEqual(null, r0.RetraceLow);
Assert.AreEqual(null, r0.PointType);
ZigZagResult r1 = results[277];
Assert.AreEqual(248.13m, r1.ZigZag);
Assert.AreEqual(272.248m, r1.RetraceHigh);
Assert.AreEqual(248.13m, r1.RetraceLow);
Assert.AreEqual("L", r1.PointType);
ZigZagResult r2 = results[483];
Assert.AreEqual(272.52m, r2.ZigZag);
Assert.AreEqual(272.52m, r2.RetraceHigh);
Assert.AreEqual(248.799m, r2.RetraceLow);
Assert.AreEqual("H", r2.PointType);
ZigZagResult r3 = results[439];
Assert.AreEqual(276.0133m, NullMath.Round(r3.ZigZag, 4));
Assert.AreEqual(280.9158m, NullMath.Round(r3.RetraceHigh, 4));
Assert.AreEqual(264.5769m, NullMath.Round(r3.RetraceLow, 4));
Assert.AreEqual(null, r3.PointType);
ZigZagResult r4 = results[500];
Assert.AreEqual(241.4575m, NullMath.Round(r4.ZigZag, 4));
Assert.AreEqual(246.7933m, NullMath.Round(r4.RetraceHigh, 4));
Assert.AreEqual(null, r4.RetraceLow);
Assert.AreEqual(null, r4.PointType);
ZigZagResult r5 = results[501];
Assert.AreEqual(245.28m, r5.ZigZag);
Assert.AreEqual(245.28m, r5.RetraceHigh);
Assert.AreEqual(null, r5.RetraceLow);
Assert.AreEqual(null, r5.PointType);
}
[TestMethod]
public void StandardHighLow()
{
List<ZigZagResult> results =
quotes.GetZigZag(EndType.HighLow, 3)
.ToList();
// assertions
// proper quantities
// should always be the same number of results as there is quotes
Assert.AreEqual(502, results.Count);
Assert.AreEqual(463, results.Where(x => x.ZigZag != null).Count());
Assert.AreEqual(463, results.Where(x => x.RetraceHigh != null).Count());
Assert.AreEqual(442, results.Where(x => x.RetraceLow != null).Count());
Assert.AreEqual(30, results.Where(x => x.PointType != null).Count());
// sample values
ZigZagResult r38 = results[38];
Assert.AreEqual(null, r38.ZigZag);
Assert.AreEqual(null, r38.RetraceHigh);
Assert.AreEqual(null, r38.RetraceLow);
Assert.AreEqual(null, r38.PointType);
ZigZagResult r277 = results[277];
Assert.AreEqual(252.9550m, r277.ZigZag);
Assert.AreEqual(262.8054m, NullMath.Round(r277.RetraceHigh, 4));
Assert.AreEqual(245.4467m, NullMath.Round(r277.RetraceLow, 4));
Assert.AreEqual(null, r277.PointType);
ZigZagResult r316 = results[316];
Assert.AreEqual(249.48m, r316.ZigZag);
Assert.AreEqual(258.34m, r316.RetraceHigh);
Assert.AreEqual(249.48m, r316.RetraceLow);
Assert.AreEqual("L", r316.PointType);
ZigZagResult r456 = results[456];
Assert.AreEqual(261.3325m, NullMath.Round(r456.ZigZag, 4));
Assert.AreEqual(274.3419m, NullMath.Round(r456.RetraceHigh, 4));
Assert.AreEqual(256.1050m, NullMath.Round(r456.RetraceLow, 4));
Assert.AreEqual(null, r456.PointType);
ZigZagResult r500 = results[500];
Assert.AreEqual(240.1667m, NullMath.Round(r500.ZigZag, 4));
Assert.AreEqual(246.95083m, NullMath.Round(r500.RetraceHigh, 5));
Assert.AreEqual(null, r500.RetraceLow);
Assert.AreEqual(null, r500.PointType);
ZigZagResult r501 = results[501];
Assert.AreEqual(245.54m, r501.ZigZag);
Assert.AreEqual(245.54m, r501.RetraceHigh);
Assert.AreEqual(null, r501.RetraceLow);
Assert.AreEqual(null, r501.PointType);
}
[TestMethod]
public void NoEntry()
{
// thresholds are never met
string json = File.ReadAllText("./s-z/ZigZag/data.ethusdt.json");
IReadOnlyCollection<Quote> quotes = JsonConvert
.DeserializeObject<IReadOnlyCollection<Quote>>(json);
List<ZigZagResult> results = quotes
.GetZigZag(EndType.Close, 5m)
.ToList();
Assert.AreEqual(0, results.Count(x => x.PointType != null));
}
[TestMethod]
public void Issue632()
{
// thresholds are never met
string json = File.ReadAllText("./s-z/ZigZag/data.issue632.json");
List<Quote> quotesList = JsonConvert
.DeserializeObject<IReadOnlyCollection<Quote>>(json)
.ToList();
List<ZigZagResult> resultsList = quotesList
.GetZigZag(EndType.Close, 5m)
.ToList();
Assert.AreEqual(17, resultsList.Count);
}
[TestMethod]
public void BadData()
{
IEnumerable<ZigZagResult> r1 = Indicator.GetZigZag(badQuotes, EndType.Close);
Assert.AreEqual(502, r1.Count());
IEnumerable<ZigZagResult> r2 = Indicator.GetZigZag(badQuotes, EndType.HighLow);
Assert.AreEqual(502, r2.Count());
}
[TestMethod]
public void NoQuotes()
{
IEnumerable<ZigZagResult> r0 = noquotes.GetZigZag();
Assert.AreEqual(0, r0.Count());
IEnumerable<ZigZagResult> r1 = onequote.GetZigZag();
Assert.AreEqual(1, r1.Count());
}
[TestMethod]
public void SchrodingerScenario()
{
string json = File.ReadAllText("./s-z/ZigZag/data.schrodinger.json");
List<Quote> h = JsonConvert
.DeserializeObject<IReadOnlyCollection<Quote>>(json)
.OrderBy(x => x.Date)
.ToList();
IEnumerable<ZigZagResult> r1 = h.GetZigZag(EndType.Close, 0.25m);
Assert.AreEqual(342, r1.Count());
// first period has High/Low that exceeds threhold
// where it is both a H and L pivot simultaenously
IEnumerable<ZigZagResult> r2 = h.GetZigZag(EndType.HighLow, 3);
Assert.AreEqual(342, r2.Count());
}
[TestMethod]
public void Exceptions()
{
// bad lookback period
Assert.ThrowsException<ArgumentOutOfRangeException>(() =>
Indicator.GetZigZag(quotes, EndType.Close, 0));
}
}
| 34.845 | 87 | 0.629502 | [
"Apache-2.0"
] | mihakralj/Stock.Indicators | tests/indicators/s-z/ZigZag/ZigZag.Tests.cs | 6,969 | C# |
using System.Linq;
using AutoMapper;
using BS.API.Dtos;
using BS.API.Models;
namespace BS.API.Helpers
{
public class AutoMapperProfiles : Profile
{
public AutoMapperProfiles()
{
CreateMap<User, UserForListDto>()
.ForMember(dest => dest.PhotoUrl, opt =>
opt.MapFrom(src => src.Photos.FirstOrDefault(p => p.IsMain).Url))
.ForMember(dest => dest.Age, opt =>
opt.MapFrom(src => src.DateOfBirth.CalculateAge()));
CreateMap<User, UserForDetailedDto>()
.ForMember(dest => dest.PhotoUrl, opt =>
opt.MapFrom(src => src.Photos.FirstOrDefault(p => p.IsMain).Url))
.ForMember(dest => dest.Age, opt =>
opt.MapFrom(src => src.DateOfBirth.CalculateAge()));
CreateMap<Photo, PhotosForDetailedDto>();
CreateMap<UserForUpdateDto, User>();
CreateMap<Photo, PhotoForReturnDto>();
CreateMap<PhotoForCreationDto, Photo>();
CreateMap<UserForRegisterDto, User>();
CreateMap<MessageForCreationDto, Message>().ReverseMap();
CreateMap<Message, MessageToReturnDto>()
.ForMember(m => m.SenderPhotoUrl, opt => opt
.MapFrom(u => u.Sender.Photos.FirstOrDefault(p => p.IsMain).Url))
.ForMember(m => m.RecipientPhotoUrl, opt => opt
.MapFrom(u => u.Recipient.Photos.FirstOrDefault(p => p.IsMain).Url));
}
}
} | 43.828571 | 89 | 0.568449 | [
"MIT"
] | vladosfi/Angular-BS | BS.API/Helpers/AutoMapperProfiles.cs | 1,534 | C# |
namespace ConsoleApp1
{
public interface IUserService
{
User LoginUser(string email);
}
} | 15.714286 | 37 | 0.645455 | [
"Unlicense"
] | zanybaka/StackOverflow.com | Questions/63741243/ConsoleApp1/IUserService.cs | 112 | 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("06.MaximalKSum")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("06.MaximalKSum")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[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("592c90ab-4608-467a-83ea-d6201e558af4")]
// 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.864865 | 84 | 0.744468 | [
"MIT"
] | aliv59git/C-2N_HomeAndExam | 1.HomeArrays/06.MaximalKSum/Properties/AssemblyInfo.cs | 1,404 | C# |
using System;
using System.ComponentModel;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
namespace Delta.Graphics
{
#pragma warning disable 1591
[EditorBrowsable(EditorBrowsableState.Never)]
public class SamplerStateReader : ContentTypeReader<SamplerState>
{
protected override SamplerState Read(ContentReader input, SamplerState value)
{
if (value == null)
value = new SamplerState();
value.Name = input.ReadObject<string>();
value.AddressU = input.ReadObject<TextureAddressMode>();
value.AddressV = input.ReadObject<TextureAddressMode>();
value.AddressW = input.ReadObject<TextureAddressMode>();
value.Filter = input.ReadObject<TextureFilter>();
value.MaxAnisotropy = input.ReadObject<int>();
value.MaxMipLevel = input.ReadObject<int>();
value.MipMapLevelOfDetailBias = input.ReadObject<float>();
return value;
}
}
#pragma warning restore 1591
}
| 34.125 | 85 | 0.67033 | [
"MIT"
] | bostelk/delta | Delta.Core/Graphics/SamplerStateReader.cs | 1,094 | C# |
using ExpressionLibrary.Expressions;
using NUnit.Framework;
using System;
namespace ExpressionLibrary.Tests
{
[TestFixture(Category = "LetExpressions")]
public class LetExpressionTests
{
[TestCase("let(,1,a)")]
[TestCase("let(a,,a)")]
[TestCase("let(a,1,)")]
[TestCase("let(a,add(1,),a)")]
[TestCase("let(a,1,add(a,))")]
[TestCase("let(a,add(a,1),a)")]
public void ErrorEvaluateTests(string expression)
{
var letExpression = new LetExpression();
Assert.Throws(typeof(ArithmeticException), () => letExpression.Evaluate(expression));
}
[TestCase("let(a,1,a)", 1)]
[TestCase("let(a, 1, a)", 1)]
[TestCase("let (a,1,a)", 1)]
[TestCase("let (a , 1,a)", 1)]
[TestCase("let(a-1,1,a-1)", 1)]
[TestCase("let(a-b,1,a-b)", 1)]
[TestCase("let(abc,1,abc)", 1)]
[TestCase("let(a, add(1,1),a)", 2)]
[TestCase("let(a, mul(1,1),sub(a,1))", 0)]
[TestCase("let(a, 1, let(b, 2, add(a,b)))", 3)]
[TestCase("let(a, 1, let(abc, 2, add(a,abc)))", 3)]
[TestCase("let(abc, 1, let(b, 2, add(abc,b)))", 3)]
public void EvaluateTests(string expression, int expectedResult)
{
var letExpression = new LetExpression();
int result = letExpression.Evaluate(expression);
Assert.That(result, Is.EqualTo(expectedResult));
}
[TestCase("let(a,1,a)", true)]
[TestCase("let(a, 1, a)", true)]
[TestCase("let (a,1,a)", true)]
[TestCase("let (a , 1,a)", true)]
[TestCase("let(a, add(1,1),a)", true)]
[TestCase("let(a, mul(1,1),sub(a,1))", true)]
[TestCase("1", false)]
[TestCase("a", false)]
[TestCase("sub(1,1)", false)]
[TestCase("le", false)]
[TestCase("le(", false)]
[TestCase("l-e-t(", false)]
public void IsMatchTests(string expression, bool expectedResult)
{
bool result = LetExpression.IsMatch(expression);
Assert.That(result, Is.EqualTo(expectedResult));
}
[TestCase("let(a,1,a)", true, null)]
[TestCase("let(a, 1, a)", true, null)]
[TestCase("let (a,1,a)", true, null)]
[TestCase("let (a , 1,a)", true, null)]
[TestCase("let(a, add(1,1),a)", true, null)]
[TestCase("let(a, mul(1,1),sub(a,1))", true, null)]
[TestCase("let(a, 1, let(b, 2, add(a,b)))", true, null)]
[TestCase("let(a, 1, let(abc, 2, add(a,abc)))", true, null)]
[TestCase("let(abc,1,abc)", true, null)]
[TestCase("let(a-b,1,a-b)", true, null)]
[TestCase("let(a-1,1,a-1)", true, null)]
[TestCase("let(,1,a)", false, "No variable name was provided")]
[TestCase("let(a,,a)", false, "No value expression was provided")]
[TestCase("let(a,1,)", false, "No result expression was provided")]
[TestCase("let(a,add(1,),a)", false, "The value expression is invalid: A function requires 2 valid expressions")]
[TestCase("let(a,1,add(a,))", false, "The result expression is invalid: A function requires 2 valid expressions")]
[TestCase("let(a,add(a,1),a)", false, "The value expression cannot have the variable in it")]
[TestCase("let(mul,1,mul)", false, "Invalid variable name provided")]
[TestCase("let(div,1,div)", false, "Invalid variable name provided")]
[TestCase("let(sub,1,sub)", false, "Invalid variable name provided")]
[TestCase("let(add,1,add)", false, "Invalid variable name provided")]
[TestCase("let(let,1,let)", false, "Invalid variable name provided")]
[TestCase("let(1a,1,1a)", false, "Invalid variable name provided")]
public void ValidateExpressionTests(string expression, bool expectedResult, string expectedError)
{
var letExpression = new LetExpression();
bool result = letExpression.ValidateExpression(expression, out string error);
Assert.That(result, Is.EqualTo(expectedResult));
Assert.That(error, Is.EqualTo(expectedError));
}
}
} | 43.260417 | 122 | 0.565856 | [
"MIT"
] | middas/ExpressionCalculator | ExpressionLibrary.Tests/LetExpressionTests.cs | 4,155 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace NetClient
{
using System;
using System.Reflection;
using System.Runtime.InteropServices;
using TestLibrary;
using Server.Contract;
using Server.Contract.Servers;
using Server.Contract.Events;
class Program
{
static void Validate_BasicCOMEvent()
{
Console.WriteLine($"{nameof(Validate_BasicCOMEvent)}...");
var eventTesting = (EventTesting)new EventTestingClass();
// Verify event handler subscription
// Add event
eventTesting.OnEvent += OnEventEventHandler;
bool eventFired = false;
string message = string.Empty;
eventTesting.FireEvent();
Assert.IsTrue(eventFired, "Event didn't fire");
Assert.AreEqual(nameof(EventTesting.FireEvent), message, "Event message is incorrect");
// Remove event
eventTesting.OnEvent -= OnEventEventHandler;
// Verify event handler removed
eventFired = false;
eventTesting.FireEvent();
Assert.IsFalse(eventFired, "Event shouldn't fire");
void OnEventEventHandler(string msg)
{
eventFired = true;
message = msg;
}
}
#pragma warning disable 618 // Must test deprecated features
// The ComAwareEventInfo is used by the compiler when PIAs
// containing COM Events are embedded.
static void Validate_COMEventViaComAwareEventInfo()
{
Console.WriteLine($"{nameof(Validate_COMEventViaComAwareEventInfo)}...");
var eventTesting = (EventTesting)new EventTestingClass();
// Verify event handler subscription
// Add event
var comAwareEventInfo = new ComAwareEventInfo(typeof(TestingEvents_Event), nameof(TestingEvents_Event.OnEvent));
var handler = new TestingEvents_OnEventEventHandler(OnEventEventHandler);
comAwareEventInfo.AddEventHandler(eventTesting, handler);
bool eventFired = false;
string message = string.Empty;
eventTesting.FireEvent();
Assert.IsTrue(eventFired, "Event didn't fire");
Assert.AreEqual(nameof(EventTesting.FireEvent), message, "Event message is incorrect");
comAwareEventInfo.RemoveEventHandler(eventTesting, handler);
// Verify event handler removed
eventFired = false;
eventTesting.FireEvent();
Assert.IsFalse(eventFired, "Event shouldn't fire");
void OnEventEventHandler(string msg)
{
eventFired = true;
message = msg;
}
}
#pragma warning restore 618 // Must test deprecated features
static int Main(string[] doNotUse)
{
// RegFree COM is not supported on Windows Nano
if (Utilities.IsWindowsNanoServer)
{
return 100;
}
try
{
Validate_BasicCOMEvent();
Validate_COMEventViaComAwareEventInfo();
}
catch (Exception e)
{
Console.WriteLine($"Test Failure: {e}");
return 101;
}
return 100;
}
}
}
| 30.101695 | 124 | 0.591216 | [
"MIT"
] | 1shekhar/runtime | src/coreclr/tests/src/Interop/COM/NETClients/Events/Program.cs | 3,552 | 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 Newtonsoft.Json;
using Syncfusion.SfChart.XForms;
namespace Sensus.Shared.Probes.Network
{
/// <summary>
/// Probes information about WLAN access points.
/// </summary>
public abstract class ListeningWlanProbe : ListeningProbe
{
[JsonIgnore]
protected override bool DefaultKeepDeviceAwake
{
get
{
return false;
}
}
[JsonIgnore]
protected override string DeviceAwakeWarning
{
get
{
return "This setting should not be enabled. It does not affect iOS and will unnecessarily reduce battery life on Android.";
}
}
[JsonIgnore]
protected override string DeviceAsleepWarning
{
get
{
return null;
}
}
public sealed override string DisplayName
{
get { return "Wireless LAN Binding"; }
}
public sealed override Type DatumType
{
get { return typeof(WlanDatum); }
}
protected override ChartSeries GetChartSeries()
{
return null;
}
protected override ChartDataPoint GetChartDataPointFromDatum(Datum datum)
{
return null;
}
protected override ChartAxis GetChartPrimaryAxis()
{
throw new NotImplementedException();
}
protected override RangeAxisBase GetChartSecondaryAxis()
{
throw new NotImplementedException();
}
}
}
| 26.833333 | 139 | 0.602928 | [
"Apache-2.0"
] | w-bonelli/sensus | Sensus.Shared/Probes/Network/ListeningWlanProbe.cs | 2,254 | C# |
using OpenDreamShared.Compiler;
namespace DMCompiler.DM.Expressions {
// x() (only the identifier)
class Proc : DMExpression {
string _identifier;
public Proc(Location location, string identifier) : base(location) {
_identifier = identifier;
}
public override void EmitPushValue(DMObject dmObject, DMProc proc) {
throw new CompileErrorException(Location, "attempt to use proc as value");
}
public override ProcPushResult EmitPushProc(DMObject dmObject, DMProc proc) {
if (!dmObject.HasProc(_identifier)) {
throw new CompileErrorException(Location, $"Type {dmObject.Path} does not have a proc named \"{_identifier}\"");
}
proc.GetProc(_identifier);
return ProcPushResult.Unconditional;
}
public DMProc GetProc(DMObject dmObject) {
return dmObject.GetProcs(_identifier)?[^1];
}
}
// .
// This is an LValue _and_ a proc
class ProcSelf : LValue {
public ProcSelf(Location location)
: base(location, null)
{}
public override void EmitPushValue(DMObject dmObject, DMProc proc) {
proc.PushSelf();
}
public override ProcPushResult EmitPushProc(DMObject dmObject, DMProc proc) {
proc.PushSelf();
return ProcPushResult.Unconditional;
}
}
// ..
class ProcSuper : DMExpression {
public ProcSuper(Location location) : base(location) { }
public override void EmitPushValue(DMObject dmObject, DMProc proc) {
throw new CompileErrorException(Location, "attempt to use proc as value");
}
public override ProcPushResult EmitPushProc(DMObject dmObject, DMProc proc) {
proc.PushSuperProc();
return ProcPushResult.Unconditional;
}
}
// x(y, z, ...)
class ProcCall : DMExpression {
DMExpression _target;
ArgumentList _arguments;
public ProcCall(Location location, DMExpression target, ArgumentList arguments) : base(location) {
_target = target;
_arguments = arguments;
}
public (DMObject ProcOwner, DMProc Proc) GetTargetProc(DMObject dmObject) {
return _target switch {
Proc procTarget => (dmObject, procTarget.GetProc(dmObject)),
DereferenceProc derefTarget => derefTarget.GetProc(),
_ => (null, null)
};
}
public override void EmitPushValue(DMObject dmObject, DMProc proc) {
(DMObject procOwner, DMProc targetProc) = GetTargetProc(dmObject);
if (!DMCompiler.Settings.SuppressUnimplementedWarnings && targetProc?.Unimplemented == true) {
DMCompiler.Warning(new CompilerWarning(Location, $"{procOwner.Path}.{targetProc.Name}() is not implemented"));
}
var _procResult = _target.EmitPushProc(dmObject, proc);
switch (_procResult) {
case ProcPushResult.Unconditional:
if (_arguments.Length == 0 && _target is ProcSuper) {
proc.PushProcArguments();
} else {
_arguments.EmitPushArguments(dmObject, proc);
}
proc.Call();
break;
case ProcPushResult.Conditional: {
var skipLabel = proc.NewLabelName();
var endLabel = proc.NewLabelName();
proc.JumpIfNullIdentifier(skipLabel);
if (_arguments.Length == 0 && _target is ProcSuper) {
proc.PushProcArguments();
} else {
_arguments.EmitPushArguments(dmObject, proc);
}
proc.Call();
proc.Jump(endLabel);
proc.AddLabel(skipLabel);
proc.Pop();
proc.PushNull();
proc.AddLabel(endLabel);
break;
}
}
}
}
}
| 35.449153 | 128 | 0.557495 | [
"MIT"
] | DamianX/OpenDream | DMCompiler/DM/Expressions/Procs.cs | 4,183 | C# |
using System;
namespace OpenVIII
{
public struct RGBColor
{
public readonly Int32 R;
public readonly Int32 G;
public readonly Int32 B;
public RGBColor(Int32 r, Int32 g, Int32 b)
{
R = r;
G = g;
B = b;
}
public override String ToString()
{
return $"(R: {R}, G: {G}, B: {B})";
}
}
} | 18.086957 | 50 | 0.447115 | [
"MIT"
] | A-n-d-y/OpenVIII | Core/Field/Core/RGBColor.cs | 418 | C# |
/*
* Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
namespace TencentCloud.Antiddos.V20200309.Models
{
using Newtonsoft.Json;
using System.Collections.Generic;
using TencentCloud.Common;
public class DescribeCcBlackWhiteIpListResponse : AbstractModel
{
/// <summary>
/// CC四层黑白名单策略列表总数
/// </summary>
[JsonProperty("Total")]
public ulong? Total{ get; set; }
/// <summary>
/// CC四层黑白名单策略列表详情
/// </summary>
[JsonProperty("CcBlackWhiteIpList")]
public CcBlackWhiteIpPolicy[] CcBlackWhiteIpList{ get; set; }
/// <summary>
/// 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
/// </summary>
[JsonProperty("RequestId")]
public string RequestId{ get; set; }
/// <summary>
/// For internal usage only. DO NOT USE IT.
/// </summary>
public override void ToMap(Dictionary<string, string> map, string prefix)
{
this.SetParamSimple(map, prefix + "Total", this.Total);
this.SetParamArrayObj(map, prefix + "CcBlackWhiteIpList.", this.CcBlackWhiteIpList);
this.SetParamSimple(map, prefix + "RequestId", this.RequestId);
}
}
}
| 31.827586 | 96 | 0.641928 | [
"Apache-2.0"
] | tencentcloudapi-test/tencentcloud-sdk-dotnet | TencentCloud/Antiddos/V20200309/Models/DescribeCcBlackWhiteIpListResponse.cs | 1,952 | C# |
using System;
using System.Collections.Generic;
using HotChocolate.Language;
using HotChocolate.Resolvers;
using HotChocolate.Types;
using HotChocolate.Types.Descriptors;
using HotChocolate.Utilities;
using HotChocolate.Configuration;
using HotChocolate.Internal;
using HotChocolate.Properties;
using HotChocolate.Types.Interceptors;
using HotChocolate.Types.Introspection;
#nullable enable
namespace HotChocolate
{
/// <summary>
/// The schema builder provides a configuration API to create a GraphQL schema.
/// </summary>
public partial class SchemaBuilder : ISchemaBuilder
{
private delegate ITypeReference CreateRef(ITypeInspector typeInspector);
private readonly Dictionary<string, object?> _contextData = new();
private readonly List<FieldMiddleware> _globalComponents = new();
private readonly List<LoadSchemaDocument> _documents = new();
private readonly List<CreateRef> _types = new();
private readonly Dictionary<OperationType, CreateRef> _operations = new();
private readonly Dictionary<(Type, string?), List<CreateConvention>> _conventions = new();
private readonly Dictionary<Type, (CreateRef, CreateRef)> _clrTypes = new();
private readonly List<object> _schemaInterceptors = new();
private readonly List<object> _typeInterceptors = new()
{
typeof(IntrospectionTypeInterceptor),
typeof(InterfaceCompletionTypeInterceptor),
typeof(CostTypeInterceptor)
};
private SchemaOptions _options = new();
private IsOfTypeFallback? _isOfType;
private IServiceProvider? _services;
private CreateRef? _schema;
/// <inheritdoc />
public IDictionary<string, object?> ContextData => _contextData;
/// <inheritdoc />
public ISchemaBuilder SetSchema(Type type)
{
if (type is null)
{
throw new ArgumentNullException(nameof(type));
}
if (typeof(Schema).IsAssignableFrom(type))
{
_schema = ti => ti.GetTypeRef(type);
}
else
{
throw new ArgumentException(
TypeResources.SchemaBuilder_SchemaTypeInvalid,
nameof(type));
}
return this;
}
/// <inheritdoc />
public ISchemaBuilder SetSchema(ISchema schema)
{
if (schema is null)
{
throw new ArgumentNullException(nameof(schema));
}
if (schema is TypeSystemObjectBase)
{
_schema = _ => new SchemaTypeReference(schema);
}
else
{
throw new ArgumentException(
TypeResources.SchemaBuilder_ISchemaNotTso,
nameof(schema));
}
return this;
}
/// <inheritdoc />
public ISchemaBuilder SetSchema(Action<ISchemaTypeDescriptor> configure)
{
if (configure is null)
{
throw new ArgumentNullException(nameof(configure));
}
_schema = _ => new SchemaTypeReference(new Schema(configure));
return this;
}
/// <inheritdoc />
public ISchemaBuilder SetOptions(IReadOnlySchemaOptions options)
{
if (options is null)
{
throw new ArgumentNullException(nameof(options));
}
_options = SchemaOptions.FromOptions(options);
return this;
}
/// <inheritdoc />
public ISchemaBuilder ModifyOptions(Action<ISchemaOptions> configure)
{
if (configure is null)
{
throw new ArgumentNullException(nameof(configure));
}
configure(_options);
return this;
}
/// <inheritdoc />
public ISchemaBuilder Use(FieldMiddleware middleware)
{
if (middleware is null)
{
throw new ArgumentNullException(nameof(middleware));
}
_globalComponents.Add(middleware);
return this;
}
/// <inheritdoc />
public ISchemaBuilder AddDocument(LoadSchemaDocument loadSchemaDocument)
{
if (loadSchemaDocument is null)
{
throw new ArgumentNullException(nameof(loadSchemaDocument));
}
_documents.Add(loadSchemaDocument);
return this;
}
/// <inheritdoc />
public ISchemaBuilder AddType(Type type)
{
if (type is null)
{
throw new ArgumentNullException(nameof(type));
}
_types.Add(ti => ti.GetTypeRef(type));
return this;
}
/// <inheritdoc />
public ISchemaBuilder TryAddConvention(
Type convention,
CreateConvention factory,
string? scope = null)
{
if (convention is null)
{
throw new ArgumentNullException(nameof(convention));
}
if (factory is null)
{
throw new ArgumentNullException(nameof(factory));
}
if (!_conventions.ContainsKey((convention, scope)))
{
AddConvention(convention, factory, scope);
}
return this;
}
/// <inheritdoc />
public ISchemaBuilder AddConvention(
Type convention,
CreateConvention factory,
string? scope = null)
{
if (convention is null)
{
throw new ArgumentNullException(nameof(convention));
}
if(!_conventions.TryGetValue(
(convention, scope),
out List<CreateConvention>? factories))
{
factories = new List<CreateConvention>();
_conventions[(convention, scope)] = factories;
}
factories.Add(factory);
return this;
}
/// <inheritdoc />
[Obsolete]
public ISchemaBuilder BindClrType(Type clrType, Type schemaType)
=> BindRuntimeType(clrType, schemaType);
/// <inheritdoc />
public ISchemaBuilder BindRuntimeType(Type runtimeType, Type schemaType)
{
if (runtimeType is null)
{
throw new ArgumentNullException(nameof(runtimeType));
}
if (schemaType is null)
{
throw new ArgumentNullException(nameof(schemaType));
}
if (!schemaType.IsSchemaType())
{
throw new ArgumentException(
TypeResources.SchemaBuilder_MustBeSchemaType,
nameof(schemaType));
}
TypeContext context = SchemaTypeReference.InferTypeContext(schemaType);
_clrTypes[runtimeType] =
(ti => ti.GetTypeRef(runtimeType, context),
ti => ti.GetTypeRef(schemaType, context));
return this;
}
/// <inheritdoc />
public ISchemaBuilder AddType(INamedType namedType)
{
if (namedType is null)
{
throw new ArgumentNullException(nameof(namedType));
}
_types.Add(_ => TypeReference.Create(namedType));
return this;
}
/// <inheritdoc />
public ISchemaBuilder AddType(INamedTypeExtension typeExtension)
{
if (typeExtension is null)
{
throw new ArgumentNullException(nameof(typeExtension));
}
_types.Add(_ => TypeReference.Create(typeExtension));
return this;
}
/// <inheritdoc />
public ISchemaBuilder AddDirectiveType(DirectiveType type)
{
if (type is null)
{
throw new ArgumentNullException(nameof(type));
}
_types.Add(_ => TypeReference.Create(type));
return this;
}
/// <inheritdoc />
public ISchemaBuilder AddRootType(
Type rootType,
OperationType operation)
{
if (rootType is null)
{
throw new ArgumentNullException(nameof(rootType));
}
if (!rootType.IsClass)
{
throw new ArgumentException(
TypeResources.SchemaBuilder_RootType_MustBeClass,
nameof(rootType));
}
if (rootType.IsNonGenericSchemaType())
{
throw new ArgumentException(
TypeResources.SchemaBuilder_RootType_NonGenericType,
nameof(rootType));
}
if (rootType.IsSchemaType()
&& !typeof(ObjectType).IsAssignableFrom(rootType))
{
throw new ArgumentException(
TypeResources.SchemaBuilder_RootType_MustBeObjectType,
nameof(rootType));
}
if (_operations.ContainsKey(operation))
{
throw new ArgumentException(
string.Format(
TypeResources.SchemaBuilder_AddRootType_TypeAlreadyRegistered,
operation),
nameof(operation));
}
_operations.Add(operation, ti => ti.GetTypeRef(rootType, TypeContext.Output));
_types.Add(ti => ti.GetTypeRef(rootType, TypeContext.Output));
return this;
}
/// <inheritdoc />
public ISchemaBuilder AddRootType(
ObjectType rootType,
OperationType operation)
{
if (rootType is null)
{
throw new ArgumentNullException(nameof(rootType));
}
if (_operations.ContainsKey(operation))
{
throw new ArgumentException(
string.Format(
TypeResources.SchemaBuilder_AddRootType_TypeAlreadyRegistered,
operation),
nameof(operation));
}
SchemaTypeReference reference = TypeReference.Create(rootType);
_operations.Add(operation, _ => reference);
_types.Add(_ => reference);
return this;
}
/// <inheritdoc />
public ISchemaBuilder SetTypeResolver(IsOfTypeFallback isOfType)
{
_isOfType = isOfType ?? throw new ArgumentNullException(nameof(isOfType));
return this;
}
/// <inheritdoc />
public ISchemaBuilder AddServices(IServiceProvider services)
{
if (services is null)
{
throw new ArgumentNullException(nameof(services));
}
_services = _services is null ? services : _services.Include(services);
return this;
}
/// <inheritdoc />
public ISchemaBuilder SetContextData(string key, object? value)
{
_contextData[key] = value;
return this;
}
/// <inheritdoc />
public ISchemaBuilder SetContextData(string key, Func<object?, object?> update)
{
_contextData.TryGetValue(key, out var value);
_contextData[key] = update(value);
return this;
}
/// <inheritdoc />
public ISchemaBuilder TryAddTypeInterceptor(Type interceptor)
{
if (interceptor is null)
{
throw new ArgumentNullException(nameof(interceptor));
}
if (!typeof(ITypeInitializationInterceptor).IsAssignableFrom(interceptor))
{
throw new ArgumentException(
TypeResources.SchemaBuilder_Interceptor_NotSuppported,
nameof(interceptor));
}
if (!_typeInterceptors.Contains(interceptor))
{
_typeInterceptors.Add(interceptor);
}
return this;
}
/// <inheritdoc />
public ISchemaBuilder TryAddTypeInterceptor(ITypeInitializationInterceptor interceptor)
{
if (interceptor is null)
{
throw new ArgumentNullException(nameof(interceptor));
}
if (!_typeInterceptors.Contains(interceptor))
{
_typeInterceptors.Add(interceptor);
}
return this;
}
/// <inheritdoc />
public ISchemaBuilder TryAddSchemaInterceptor(Type interceptor)
{
if (interceptor is null)
{
throw new ArgumentNullException(nameof(interceptor));
}
if (!typeof(ISchemaInterceptor).IsAssignableFrom(interceptor))
{
throw new ArgumentException(
TypeResources.SchemaBuilder_Interceptor_NotSuppported,
nameof(interceptor));
}
if (!_schemaInterceptors.Contains(interceptor))
{
_schemaInterceptors.Add(interceptor);
}
return this;
}
/// <inheritdoc />
public ISchemaBuilder TryAddSchemaInterceptor(ISchemaInterceptor interceptor)
{
if (interceptor is null)
{
throw new ArgumentNullException(nameof(interceptor));
}
if (!_schemaInterceptors.Contains(interceptor))
{
_schemaInterceptors.Add(interceptor);
}
return this;
}
/// <summary>
/// Creates a new <see cref="SchemaBuilder"/> instance.
/// </summary>
/// <returns>
/// Returns a new instance of <see cref="SchemaBuilder"/>.
/// </returns>
public static SchemaBuilder New() => new();
}
}
| 30.20339 | 98 | 0.536686 | [
"MIT"
] | Alxandr/hotchocolate | src/HotChocolate/Core/src/Types/SchemaBuilder.cs | 14,256 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace Codx.Auth.ViewModels
{
public class ClientGrantTypeDetailsViewModel : BaseGrantTypeClaimViewModel
{
public int Id { get; set; }
}
public class ClientGrantTypeAddViewModel : BaseGrantTypeClaimViewModel
{
}
public class ClientGrantTypeEditViewModel : BaseGrantTypeClaimViewModel
{
public int Id { get; set; }
}
public class BaseGrantTypeClaimViewModel
{
public int ClientId { get; set; }
[Required]
[StringLength(250)]
public string GrantType { get; set; }
}
}
| 19.405405 | 78 | 0.685237 | [
"MIT"
] | codeandexplore/Codx.Auth | src/Codx.Auth/ViewModels/ClientGrantTypeViewModels.cs | 720 | C# |
using System.Web;
using System.Web.Mvc;
using Laser.Orchard.NewsLetters.Models;
using Orchard.ContentManagement;
using Orchard.ContentManagement.Aspects;
using Orchard.Mvc.Extensions;
namespace Laser.Orchard.NewsLetters.Extensions {
/// <summary>
/// TODO: (PH:Autoroute) Many of these are or could be redundant (see controllers)
/// </summary>
public static class UrlHelperExtensions {
#region [ Newsletter Definition ]
public static string NewsLettersForAdmin(this UrlHelper urlHelper) {
return urlHelper.Action("Index", "NewsLetterAdmin", new { area = "Laser.Orchard.NewsLetters" });
}
public static string NewsLetterCreate(this UrlHelper urlHelper) {
return urlHelper.Action("Create", "NewsLetterAdmin", new { area = "Laser.Orchard.NewsLetters" });
}
public static string NewsLetterEdit(this UrlHelper urlHelper, NewsletterDefinitionPart newsletterDefinitionPart) {
return urlHelper.Action("Edit", "NewsLetterAdmin", new { newsletterId = newsletterDefinitionPart.Id, area = "Laser.Orchard.NewsLetters" });
}
public static string NewsLetterRemove(this UrlHelper urlHelper, NewsletterDefinitionPart newsletterDefinitionPart) {
return urlHelper.Action("Remove", "NewsLetterAdmin", new { newsletterId = newsletterDefinitionPart.Id, area = "Laser.Orchard.NewsLetters" });
}
#endregion
#region [ Newsletter Subscribers ]
public static string NewsLetterSubscribers(this UrlHelper urlHelper, NewsletterDefinitionPart newsletterDefinitionPart) {
return urlHelper.Action("Index", "SubscribersAdmin", new { newsletterId = newsletterDefinitionPart.Id, area = "Laser.Orchard.NewsLetters" });
}
#endregion
#region [ Newsletter Editions ]
public static string NewsLetterEditionsForAdmin(this UrlHelper urlHelper, int newsletterDefinitionPartId) {
return urlHelper.Action("Index", "NewsLetterEditionAdmin", new { newsletterId = newsletterDefinitionPartId, area = "Laser.Orchard.NewsLetters" });
}
public static string NewsLetterEditionCreate(this UrlHelper urlHelper, int newsletterDefinitionPartId) {
return urlHelper.Action("Create", "NewsLetterEditionAdmin", new { newsletterId = newsletterDefinitionPartId, area = "Laser.Orchard.NewsLetters" });
}
public static string NewsLetterEditionEdit(this UrlHelper urlHelper, int newsletterDefinitionPartId, NewsletterEditionPart newsletterEditionPart) {
return urlHelper.Action("Edit", "NewsLetterEditionAdmin", new { Id = newsletterEditionPart.Id, newsletterId = newsletterDefinitionPartId, area = "Laser.Orchard.NewsLetters" });
}
public static string NewsLetterEditionRemove(this UrlHelper urlHelper, NewsletterEditionPart newsletterEditionPart) {
return urlHelper.Action("Remove", "NewsLetterEditionAdmin", new { newsletterEditionId = newsletterEditionPart.Id, area = "Laser.Orchard.NewsLetters" });
}
#endregion
#region [ Subscribers ]
public static string SubscriberRemove(this UrlHelper urlHelper, SubscriberRecord subscriberRecord) {
return urlHelper.Action("Remove", "SubscribersAdmin", new { id = subscriberRecord.Id, area = "Laser.Orchard.NewsLetters" });
}
public static string SubscriptionSubscribe(this UrlHelper urlHelper) {
return urlHelper.Action("Subscribe", "Subscription", new { area = "Laser.Orchard.NewsLetters" });
}
public static string SubscriptionConfirmSubscribe(this UrlHelper urlHelper) {
return urlHelper.Action("ConfirmSubscribe", "Subscription", new { area = "Laser.Orchard.NewsLetters" });
}
public static string SubscriptionUnsubscribe(this UrlHelper urlHelper) {
return urlHelper.Action("Unsubscribe", "Subscription", new { area = "Laser.Orchard.NewsLetters" });
}
public static string SubscriptionConfirmUnsubscribe(this UrlHelper urlHelper) {
return urlHelper.Action("ConfirmUnsubscribe", "Subscription", new { area = "Laser.Orchard.NewsLetters" });
}
#endregion
}
} | 56.333333 | 188 | 0.711479 | [
"Apache-2.0"
] | INVA-Spa/Laser.Orchard.Platform | src/Modules/Laser.Orchard.NewsLetters/Extensions/UrlHelperExtensions.cs | 4,225 | C# |
// <auto-generated />
using Abp.Authorization;
using Abp.BackgroundJobs;
using Abp.Events.Bus.Entities;
using Abp.Notifications;
using DF.ACE.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.EntityFrameworkCore.Storage.Internal;
using Microsoft.EntityFrameworkCore.ValueGeneration;
using System;
namespace DF.ACE.Migrations
{
[DbContext(typeof(ACEDbContext))]
[Migration("20180201051646_Upgraded_To_Abp_v3.4.0")]
partial class Upgraded_To_Abp_v340
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "2.0.1-rtm-125")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("Abp.Application.Editions.Edition", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<long?>("DeleterUserId");
b.Property<DateTime?>("DeletionTime");
b.Property<string>("DisplayName")
.IsRequired()
.HasMaxLength(64);
b.Property<bool>("IsDeleted");
b.Property<DateTime?>("LastModificationTime");
b.Property<long?>("LastModifierUserId");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(32);
b.HasKey("Id");
b.ToTable("AbpEditions");
});
modelBuilder.Entity("Abp.Application.Features.FeatureSetting", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<string>("Discriminator")
.IsRequired();
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(128);
b.Property<int?>("TenantId");
b.Property<string>("Value")
.IsRequired()
.HasMaxLength(2000);
b.HasKey("Id");
b.ToTable("AbpFeatures");
b.HasDiscriminator<string>("Discriminator").HasValue("FeatureSetting");
});
modelBuilder.Entity("Abp.Auditing.AuditLog", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("BrowserInfo")
.HasMaxLength(256);
b.Property<string>("ClientIpAddress")
.HasMaxLength(64);
b.Property<string>("ClientName")
.HasMaxLength(128);
b.Property<string>("CustomData")
.HasMaxLength(2000);
b.Property<string>("Exception")
.HasMaxLength(2000);
b.Property<int>("ExecutionDuration");
b.Property<DateTime>("ExecutionTime");
b.Property<int?>("ImpersonatorTenantId");
b.Property<long?>("ImpersonatorUserId");
b.Property<string>("MethodName")
.HasMaxLength(256);
b.Property<string>("Parameters")
.HasMaxLength(1024);
b.Property<string>("ServiceName")
.HasMaxLength(256);
b.Property<int?>("TenantId");
b.Property<long?>("UserId");
b.HasKey("Id");
b.HasIndex("TenantId", "ExecutionDuration");
b.HasIndex("TenantId", "ExecutionTime");
b.HasIndex("TenantId", "UserId");
b.ToTable("AbpAuditLogs");
});
modelBuilder.Entity("Abp.Authorization.PermissionSetting", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<string>("Discriminator")
.IsRequired();
b.Property<bool>("IsGranted");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(128);
b.Property<int?>("TenantId");
b.HasKey("Id");
b.HasIndex("TenantId", "Name");
b.ToTable("AbpPermissions");
b.HasDiscriminator<string>("Discriminator").HasValue("PermissionSetting");
});
modelBuilder.Entity("Abp.Authorization.Roles.RoleClaim", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType")
.HasMaxLength(256);
b.Property<string>("ClaimValue");
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<int>("RoleId");
b.Property<int?>("TenantId");
b.HasKey("Id");
b.HasIndex("RoleId");
b.HasIndex("TenantId", "ClaimType");
b.ToTable("AbpRoleClaims");
});
modelBuilder.Entity("Abp.Authorization.Users.UserAccount", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<long?>("DeleterUserId");
b.Property<DateTime?>("DeletionTime");
b.Property<string>("EmailAddress")
.HasMaxLength(256);
b.Property<bool>("IsDeleted");
b.Property<DateTime?>("LastLoginTime");
b.Property<DateTime?>("LastModificationTime");
b.Property<long?>("LastModifierUserId");
b.Property<int?>("TenantId");
b.Property<long>("UserId");
b.Property<long?>("UserLinkId");
b.Property<string>("UserName")
.HasMaxLength(32);
b.HasKey("Id");
b.HasIndex("EmailAddress");
b.HasIndex("UserName");
b.HasIndex("TenantId", "EmailAddress");
b.HasIndex("TenantId", "UserId");
b.HasIndex("TenantId", "UserName");
b.ToTable("AbpUserAccounts");
});
modelBuilder.Entity("Abp.Authorization.Users.UserClaim", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType")
.HasMaxLength(256);
b.Property<string>("ClaimValue");
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<int?>("TenantId");
b.Property<long>("UserId");
b.HasKey("Id");
b.HasIndex("UserId");
b.HasIndex("TenantId", "ClaimType");
b.ToTable("AbpUserClaims");
});
modelBuilder.Entity("Abp.Authorization.Users.UserLogin", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("LoginProvider")
.IsRequired()
.HasMaxLength(128);
b.Property<string>("ProviderKey")
.IsRequired()
.HasMaxLength(256);
b.Property<int?>("TenantId");
b.Property<long>("UserId");
b.HasKey("Id");
b.HasIndex("UserId");
b.HasIndex("TenantId", "UserId");
b.HasIndex("TenantId", "LoginProvider", "ProviderKey");
b.ToTable("AbpUserLogins");
});
modelBuilder.Entity("Abp.Authorization.Users.UserLoginAttempt", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("BrowserInfo")
.HasMaxLength(256);
b.Property<string>("ClientIpAddress")
.HasMaxLength(64);
b.Property<string>("ClientName")
.HasMaxLength(128);
b.Property<DateTime>("CreationTime");
b.Property<byte>("Result");
b.Property<string>("TenancyName")
.HasMaxLength(64);
b.Property<int?>("TenantId");
b.Property<long?>("UserId");
b.Property<string>("UserNameOrEmailAddress")
.HasMaxLength(255);
b.HasKey("Id");
b.HasIndex("UserId", "TenantId");
b.HasIndex("TenancyName", "UserNameOrEmailAddress", "Result");
b.ToTable("AbpUserLoginAttempts");
});
modelBuilder.Entity("Abp.Authorization.Users.UserOrganizationUnit", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<bool>("IsDeleted");
b.Property<long>("OrganizationUnitId");
b.Property<int?>("TenantId");
b.Property<long>("UserId");
b.HasKey("Id");
b.HasIndex("TenantId", "OrganizationUnitId");
b.HasIndex("TenantId", "UserId");
b.ToTable("AbpUserOrganizationUnits");
});
modelBuilder.Entity("Abp.Authorization.Users.UserRole", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<int>("RoleId");
b.Property<int?>("TenantId");
b.Property<long>("UserId");
b.HasKey("Id");
b.HasIndex("UserId");
b.HasIndex("TenantId", "RoleId");
b.HasIndex("TenantId", "UserId");
b.ToTable("AbpUserRoles");
});
modelBuilder.Entity("Abp.Authorization.Users.UserToken", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("LoginProvider");
b.Property<string>("Name");
b.Property<int?>("TenantId");
b.Property<long>("UserId");
b.Property<string>("Value");
b.HasKey("Id");
b.HasIndex("UserId");
b.HasIndex("TenantId", "UserId");
b.ToTable("AbpUserTokens");
});
modelBuilder.Entity("Abp.BackgroundJobs.BackgroundJobInfo", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<bool>("IsAbandoned");
b.Property<string>("JobArgs")
.IsRequired()
.HasMaxLength(1048576);
b.Property<string>("JobType")
.IsRequired()
.HasMaxLength(512);
b.Property<DateTime?>("LastTryTime");
b.Property<DateTime>("NextTryTime");
b.Property<byte>("Priority");
b.Property<short>("TryCount");
b.HasKey("Id");
b.HasIndex("IsAbandoned", "NextTryTime");
b.ToTable("AbpBackgroundJobs");
});
modelBuilder.Entity("Abp.Configuration.Setting", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<DateTime?>("LastModificationTime");
b.Property<long?>("LastModifierUserId");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(256);
b.Property<int?>("TenantId");
b.Property<long?>("UserId");
b.Property<string>("Value")
.HasMaxLength(2000);
b.HasKey("Id");
b.HasIndex("UserId");
b.HasIndex("TenantId", "Name");
b.ToTable("AbpSettings");
});
modelBuilder.Entity("Abp.EntityHistory.EntityChange", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("ChangeTime");
b.Property<byte>("ChangeType");
b.Property<long>("EntityChangeSetId");
b.Property<string>("EntityId")
.HasMaxLength(48);
b.Property<string>("EntityTypeFullName")
.HasMaxLength(192);
b.Property<int?>("TenantId");
b.HasKey("Id");
b.HasIndex("EntityChangeSetId");
b.HasIndex("EntityTypeFullName", "EntityId");
b.ToTable("AbpEntityChanges");
});
modelBuilder.Entity("Abp.EntityHistory.EntityChangeSet", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("BrowserInfo")
.HasMaxLength(256);
b.Property<string>("ClientIpAddress")
.HasMaxLength(64);
b.Property<string>("ClientName")
.HasMaxLength(128);
b.Property<DateTime>("CreationTime");
b.Property<string>("ExtensionData");
b.Property<int?>("ImpersonatorTenantId");
b.Property<long?>("ImpersonatorUserId");
b.Property<string>("Reason")
.HasMaxLength(256);
b.Property<int?>("TenantId");
b.Property<long?>("UserId");
b.HasKey("Id");
b.HasIndex("TenantId", "CreationTime");
b.HasIndex("TenantId", "Reason");
b.HasIndex("TenantId", "UserId");
b.ToTable("AbpEntityChangeSets");
});
modelBuilder.Entity("Abp.EntityHistory.EntityPropertyChange", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<long>("EntityChangeId");
b.Property<string>("NewValue")
.HasMaxLength(512);
b.Property<string>("OriginalValue")
.HasMaxLength(512);
b.Property<string>("PropertyName")
.HasMaxLength(96);
b.Property<string>("PropertyTypeFullName")
.HasMaxLength(192);
b.Property<int?>("TenantId");
b.HasKey("Id");
b.HasIndex("EntityChangeId");
b.ToTable("AbpEntityPropertyChanges");
});
modelBuilder.Entity("Abp.Localization.ApplicationLanguage", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<long?>("DeleterUserId");
b.Property<DateTime?>("DeletionTime");
b.Property<string>("DisplayName")
.IsRequired()
.HasMaxLength(64);
b.Property<string>("Icon")
.HasMaxLength(128);
b.Property<bool>("IsDeleted");
b.Property<bool>("IsDisabled");
b.Property<DateTime?>("LastModificationTime");
b.Property<long?>("LastModifierUserId");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(10);
b.Property<int?>("TenantId");
b.HasKey("Id");
b.HasIndex("TenantId", "Name");
b.ToTable("AbpLanguages");
});
modelBuilder.Entity("Abp.Localization.ApplicationLanguageText", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<string>("Key")
.IsRequired()
.HasMaxLength(256);
b.Property<string>("LanguageName")
.IsRequired()
.HasMaxLength(10);
b.Property<DateTime?>("LastModificationTime");
b.Property<long?>("LastModifierUserId");
b.Property<string>("Source")
.IsRequired()
.HasMaxLength(128);
b.Property<int?>("TenantId");
b.Property<string>("Value")
.IsRequired()
.HasMaxLength(67108864);
b.HasKey("Id");
b.HasIndex("TenantId", "Source", "LanguageName", "Key");
b.ToTable("AbpLanguageTexts");
});
modelBuilder.Entity("Abp.Notifications.NotificationInfo", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<string>("Data")
.HasMaxLength(1048576);
b.Property<string>("DataTypeName")
.HasMaxLength(512);
b.Property<string>("EntityId")
.HasMaxLength(96);
b.Property<string>("EntityTypeAssemblyQualifiedName")
.HasMaxLength(512);
b.Property<string>("EntityTypeName")
.HasMaxLength(250);
b.Property<string>("ExcludedUserIds")
.HasMaxLength(131072);
b.Property<string>("NotificationName")
.IsRequired()
.HasMaxLength(96);
b.Property<byte>("Severity");
b.Property<string>("TenantIds")
.HasMaxLength(131072);
b.Property<string>("UserIds")
.HasMaxLength(131072);
b.HasKey("Id");
b.ToTable("AbpNotifications");
});
modelBuilder.Entity("Abp.Notifications.NotificationSubscriptionInfo", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<string>("EntityId")
.HasMaxLength(96);
b.Property<string>("EntityTypeAssemblyQualifiedName")
.HasMaxLength(512);
b.Property<string>("EntityTypeName")
.HasMaxLength(250);
b.Property<string>("NotificationName")
.HasMaxLength(96);
b.Property<int?>("TenantId");
b.Property<long>("UserId");
b.HasKey("Id");
b.HasIndex("NotificationName", "EntityTypeName", "EntityId", "UserId");
b.HasIndex("TenantId", "NotificationName", "EntityTypeName", "EntityId", "UserId");
b.ToTable("AbpNotificationSubscriptions");
});
modelBuilder.Entity("Abp.Notifications.TenantNotificationInfo", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<string>("Data")
.HasMaxLength(1048576);
b.Property<string>("DataTypeName")
.HasMaxLength(512);
b.Property<string>("EntityId")
.HasMaxLength(96);
b.Property<string>("EntityTypeAssemblyQualifiedName")
.HasMaxLength(512);
b.Property<string>("EntityTypeName")
.HasMaxLength(250);
b.Property<string>("NotificationName")
.IsRequired()
.HasMaxLength(96);
b.Property<byte>("Severity");
b.Property<int?>("TenantId");
b.HasKey("Id");
b.HasIndex("TenantId");
b.ToTable("AbpTenantNotifications");
});
modelBuilder.Entity("Abp.Notifications.UserNotificationInfo", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreationTime");
b.Property<int>("State");
b.Property<int?>("TenantId");
b.Property<Guid>("TenantNotificationId");
b.Property<long>("UserId");
b.HasKey("Id");
b.HasIndex("UserId", "State", "CreationTime");
b.ToTable("AbpUserNotifications");
});
modelBuilder.Entity("Abp.Organizations.OrganizationUnit", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Code")
.IsRequired()
.HasMaxLength(95);
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<long?>("DeleterUserId");
b.Property<DateTime?>("DeletionTime");
b.Property<string>("DisplayName")
.IsRequired()
.HasMaxLength(128);
b.Property<bool>("IsDeleted");
b.Property<DateTime?>("LastModificationTime");
b.Property<long?>("LastModifierUserId");
b.Property<long?>("ParentId");
b.Property<int?>("TenantId");
b.HasKey("Id");
b.HasIndex("ParentId");
b.HasIndex("TenantId", "Code");
b.ToTable("AbpOrganizationUnits");
});
modelBuilder.Entity("DF.ACE.Authorization.Roles.Role", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<long?>("DeleterUserId");
b.Property<DateTime?>("DeletionTime");
b.Property<string>("Description")
.HasMaxLength(5000);
b.Property<string>("DisplayName")
.IsRequired()
.HasMaxLength(64);
b.Property<bool>("IsDefault");
b.Property<bool>("IsDeleted");
b.Property<bool>("IsStatic");
b.Property<DateTime?>("LastModificationTime");
b.Property<long?>("LastModifierUserId");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(32);
b.Property<string>("NormalizedName")
.IsRequired()
.HasMaxLength(32);
b.Property<int?>("TenantId");
b.HasKey("Id");
b.HasIndex("CreatorUserId");
b.HasIndex("DeleterUserId");
b.HasIndex("LastModifierUserId");
b.HasIndex("TenantId", "NormalizedName");
b.ToTable("AbpRoles");
});
modelBuilder.Entity("DF.ACE.Authorization.Users.User", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<int>("AccessFailedCount");
b.Property<string>("AuthenticationSource")
.HasMaxLength(64);
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<long?>("DeleterUserId");
b.Property<DateTime?>("DeletionTime");
b.Property<string>("EmailAddress")
.IsRequired()
.HasMaxLength(256);
b.Property<string>("EmailConfirmationCode")
.HasMaxLength(328);
b.Property<bool>("IsActive");
b.Property<bool>("IsDeleted");
b.Property<bool>("IsEmailConfirmed");
b.Property<bool>("IsLockoutEnabled");
b.Property<bool>("IsPhoneNumberConfirmed");
b.Property<bool>("IsTwoFactorEnabled");
b.Property<DateTime?>("LastLoginTime");
b.Property<DateTime?>("LastModificationTime");
b.Property<long?>("LastModifierUserId");
b.Property<DateTime?>("LockoutEndDateUtc");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(32);
b.Property<string>("NormalizedEmailAddress")
.IsRequired()
.HasMaxLength(256);
b.Property<string>("NormalizedUserName")
.IsRequired()
.HasMaxLength(32);
b.Property<string>("Password")
.IsRequired()
.HasMaxLength(128);
b.Property<string>("PasswordResetCode")
.HasMaxLength(328);
b.Property<string>("PhoneNumber");
b.Property<string>("SecurityStamp");
b.Property<string>("Surname")
.IsRequired()
.HasMaxLength(32);
b.Property<int?>("TenantId");
b.Property<string>("UserName")
.IsRequired()
.HasMaxLength(32);
b.HasKey("Id");
b.HasIndex("CreatorUserId");
b.HasIndex("DeleterUserId");
b.HasIndex("LastModifierUserId");
b.HasIndex("TenantId", "NormalizedEmailAddress");
b.HasIndex("TenantId", "NormalizedUserName");
b.ToTable("AbpUsers");
});
modelBuilder.Entity("DF.ACE.MultiTenancy.Tenant", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ConnectionString")
.HasMaxLength(1024);
b.Property<DateTime>("CreationTime");
b.Property<long?>("CreatorUserId");
b.Property<long?>("DeleterUserId");
b.Property<DateTime?>("DeletionTime");
b.Property<int?>("EditionId");
b.Property<bool>("IsActive");
b.Property<bool>("IsDeleted");
b.Property<DateTime?>("LastModificationTime");
b.Property<long?>("LastModifierUserId");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(128);
b.Property<string>("TenancyName")
.IsRequired()
.HasMaxLength(64);
b.HasKey("Id");
b.HasIndex("CreatorUserId");
b.HasIndex("DeleterUserId");
b.HasIndex("EditionId");
b.HasIndex("LastModifierUserId");
b.HasIndex("TenancyName");
b.ToTable("AbpTenants");
});
modelBuilder.Entity("Abp.Application.Features.EditionFeatureSetting", b =>
{
b.HasBaseType("Abp.Application.Features.FeatureSetting");
b.Property<int>("EditionId");
b.HasIndex("EditionId", "Name");
b.ToTable("AbpFeatures");
b.HasDiscriminator().HasValue("EditionFeatureSetting");
});
modelBuilder.Entity("Abp.MultiTenancy.TenantFeatureSetting", b =>
{
b.HasBaseType("Abp.Application.Features.FeatureSetting");
b.HasIndex("TenantId", "Name");
b.ToTable("AbpFeatures");
b.HasDiscriminator().HasValue("TenantFeatureSetting");
});
modelBuilder.Entity("Abp.Authorization.Roles.RolePermissionSetting", b =>
{
b.HasBaseType("Abp.Authorization.PermissionSetting");
b.Property<int>("RoleId");
b.HasIndex("RoleId");
b.ToTable("AbpPermissions");
b.HasDiscriminator().HasValue("RolePermissionSetting");
});
modelBuilder.Entity("Abp.Authorization.Users.UserPermissionSetting", b =>
{
b.HasBaseType("Abp.Authorization.PermissionSetting");
b.Property<long>("UserId");
b.HasIndex("UserId");
b.ToTable("AbpPermissions");
b.HasDiscriminator().HasValue("UserPermissionSetting");
});
modelBuilder.Entity("Abp.Authorization.Roles.RoleClaim", b =>
{
b.HasOne("DF.ACE.Authorization.Roles.Role")
.WithMany("Claims")
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Abp.Authorization.Users.UserClaim", b =>
{
b.HasOne("DF.ACE.Authorization.Users.User")
.WithMany("Claims")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Abp.Authorization.Users.UserLogin", b =>
{
b.HasOne("DF.ACE.Authorization.Users.User")
.WithMany("Logins")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Abp.Authorization.Users.UserRole", b =>
{
b.HasOne("DF.ACE.Authorization.Users.User")
.WithMany("Roles")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Abp.Authorization.Users.UserToken", b =>
{
b.HasOne("DF.ACE.Authorization.Users.User")
.WithMany("Tokens")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Abp.Configuration.Setting", b =>
{
b.HasOne("DF.ACE.Authorization.Users.User")
.WithMany("Settings")
.HasForeignKey("UserId");
});
modelBuilder.Entity("Abp.EntityHistory.EntityChange", b =>
{
b.HasOne("Abp.EntityHistory.EntityChangeSet")
.WithMany("EntityChanges")
.HasForeignKey("EntityChangeSetId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Abp.EntityHistory.EntityPropertyChange", b =>
{
b.HasOne("Abp.EntityHistory.EntityChange")
.WithMany("PropertyChanges")
.HasForeignKey("EntityChangeId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Abp.Organizations.OrganizationUnit", b =>
{
b.HasOne("Abp.Organizations.OrganizationUnit", "Parent")
.WithMany("Children")
.HasForeignKey("ParentId");
});
modelBuilder.Entity("DF.ACE.Authorization.Roles.Role", b =>
{
b.HasOne("DF.ACE.Authorization.Users.User", "CreatorUser")
.WithMany()
.HasForeignKey("CreatorUserId");
b.HasOne("DF.ACE.Authorization.Users.User", "DeleterUser")
.WithMany()
.HasForeignKey("DeleterUserId");
b.HasOne("DF.ACE.Authorization.Users.User", "LastModifierUser")
.WithMany()
.HasForeignKey("LastModifierUserId");
});
modelBuilder.Entity("DF.ACE.Authorization.Users.User", b =>
{
b.HasOne("DF.ACE.Authorization.Users.User", "CreatorUser")
.WithMany()
.HasForeignKey("CreatorUserId");
b.HasOne("DF.ACE.Authorization.Users.User", "DeleterUser")
.WithMany()
.HasForeignKey("DeleterUserId");
b.HasOne("DF.ACE.Authorization.Users.User", "LastModifierUser")
.WithMany()
.HasForeignKey("LastModifierUserId");
});
modelBuilder.Entity("DF.ACE.MultiTenancy.Tenant", b =>
{
b.HasOne("DF.ACE.Authorization.Users.User", "CreatorUser")
.WithMany()
.HasForeignKey("CreatorUserId");
b.HasOne("DF.ACE.Authorization.Users.User", "DeleterUser")
.WithMany()
.HasForeignKey("DeleterUserId");
b.HasOne("Abp.Application.Editions.Edition", "Edition")
.WithMany()
.HasForeignKey("EditionId");
b.HasOne("DF.ACE.Authorization.Users.User", "LastModifierUser")
.WithMany()
.HasForeignKey("LastModifierUserId");
});
modelBuilder.Entity("Abp.Application.Features.EditionFeatureSetting", b =>
{
b.HasOne("Abp.Application.Editions.Edition", "Edition")
.WithMany()
.HasForeignKey("EditionId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Abp.Authorization.Roles.RolePermissionSetting", b =>
{
b.HasOne("DF.ACE.Authorization.Roles.Role")
.WithMany("Permissions")
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Abp.Authorization.Users.UserPermissionSetting", b =>
{
b.HasOne("DF.ACE.Authorization.Users.User")
.WithMany("Permissions")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
#pragma warning restore 612, 618
}
}
}
| 31.729116 | 117 | 0.441107 | [
"MIT"
] | aman22275/ACE | aspnet-core/src/DF.ACE.EntityFrameworkCore/Migrations/20180201051646_Upgraded_To_Abp_v3.4.0.Designer.cs | 39,124 | C# |
namespace Epic.OnlineServices.Presence
{
public delegate void OnPresenceChangedCallback(PresenceChangedCallbackInfo data);
}
| 25.2 | 82 | 0.865079 | [
"MIT"
] | undancer/oni-data | Managed/firstpass/Epic/OnlineServices/Presence/OnPresenceChangedCallback.cs | 126 | C# |
#pragma checksum "TestFiles/Input/Inject.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "225760ec3beca02a80469066fab66433e90ddc2e"
namespace Asp
{
#line 1 "TestFiles/Input/Inject.cshtml"
using MyNamespace
#line default
#line hidden
;
using System;
using System.Linq;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using System.Threading.Tasks;
public class TestFiles_Input_Inject_cshtml : Microsoft.AspNetCore.Mvc.Razor.RazorPage<dynamic>
{
#line hidden
public TestFiles_Input_Inject_cshtml()
{
}
#line hidden
[Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public MyApp MyPropertyName { get; private set; }
[Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; }
[Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; }
[Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; }
[Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<dynamic> Html { get; private set; }
#line hidden
#pragma warning disable 1998
public override async Task ExecuteAsync()
{
}
#pragma warning restore 1998
}
}
| 36.272727 | 132 | 0.714286 | [
"Apache-2.0"
] | Mani4007/ASPNET | test/Microsoft.AspNetCore.Mvc.Razor.Host.Test/TestFiles/Output/Runtime/Inject.cs | 1,596 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Fortnox.SDK;
using Fortnox.SDK.Entities;
using Fortnox.SDK.Search;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace FortnoxSDK.Tests.ConnectorTests
{
[TestClass]
public class InvoiceTests
{
public FortnoxClient FortnoxClient = TestUtils.DefaultFortnoxClient;
[TestMethod]
public void Test_Invoice_CRUD()
{
#region Arrange
var tmpCustomer = FortnoxClient.CustomerConnector.Create(new Customer() { Name = "TmpCustomer", CountryCode = "SE", City = "Testopolis" });
var tmpArticle = FortnoxClient.ArticleConnector.Create(new Article() { Description = "TmpArticle", Type = ArticleType.Stock, PurchasePrice = 100 });
#endregion Arrange
var connector = FortnoxClient.InvoiceConnector;
#region CREATE
var newInvoice = new Invoice()
{
CustomerNumber = tmpCustomer.CustomerNumber,
InvoiceDate = new DateTime(2019, 1, 20), //"2019-01-20",
DueDate = new DateTime(2019, 2, 20), //"2019-02-20",
InvoiceType = InvoiceType.CashInvoice,
PaymentWay = PaymentWay.Cash,
Comments = "TestInvoice",
InvoiceRows = new List<InvoiceRow>()
{
new InvoiceRow(){ ArticleNumber = tmpArticle.ArticleNumber, DeliveredQuantity = 10, Price = 100},
new InvoiceRow(){ ArticleNumber = tmpArticle.ArticleNumber, DeliveredQuantity = 20, Price = 100},
new InvoiceRow(){ ArticleNumber = tmpArticle.ArticleNumber, DeliveredQuantity = 15, Price = 100}
}
};
var createdInvoice = connector.Create(newInvoice);
Assert.AreEqual("TestInvoice", createdInvoice.Comments);
Assert.AreEqual("TmpCustomer", createdInvoice.CustomerName);
Assert.AreEqual(3, createdInvoice.InvoiceRows.Count);
#endregion CREATE
#region UPDATE
createdInvoice.Comments = "UpdatedInvoice";
var updatedInvoice = connector.Update(createdInvoice);
Assert.AreEqual("UpdatedInvoice", updatedInvoice.Comments);
#endregion UPDATE
#region READ / GET
var retrievedInvoice = connector.Get(createdInvoice.DocumentNumber);
Assert.AreEqual("UpdatedInvoice", retrievedInvoice.Comments);
#endregion READ / GET
#region DELETE
//Not available, Cancel instead
connector.Cancel(createdInvoice.DocumentNumber);
var cancelledInvoice = connector.Get(createdInvoice.DocumentNumber);
Assert.AreEqual(true, cancelledInvoice.Cancelled);
#endregion DELETE
#region Delete arranged resources
FortnoxClient.CustomerConnector.Delete(tmpCustomer.CustomerNumber);
//FortnoxClient.ArticleConnector.Delete(tmpArticle.ArticleNumber);
#endregion Delete arranged resources
}
[TestMethod]
public void Test_Find()
{
#region Arrange
var tmpCustomer = FortnoxClient.CustomerConnector.Create(new Customer() { Name = "TmpCustomer", CountryCode = "SE", City = "Testopolis" });
var tmpArticle = FortnoxClient.ArticleConnector.Create(new Article() { Description = "TmpArticle", Type = ArticleType.Stock, PurchasePrice = 100 });
#endregion Arrange
var connector = FortnoxClient.InvoiceConnector;
var newInvoice = new Invoice()
{
CustomerNumber = tmpCustomer.CustomerNumber,
InvoiceDate = new DateTime(2019, 1, 20), //"2019-01-20",
DueDate = new DateTime(2019, 2, 20), //"2019-02-20",
InvoiceType = InvoiceType.CashInvoice,
PaymentWay = PaymentWay.Cash,
Comments = "TestInvoice",
InvoiceRows = new List<InvoiceRow>()
{
new InvoiceRow(){ ArticleNumber = tmpArticle.ArticleNumber, DeliveredQuantity = 10, Price = 100},
new InvoiceRow(){ ArticleNumber = tmpArticle.ArticleNumber, DeliveredQuantity = 20, Price = 100},
new InvoiceRow(){ ArticleNumber = tmpArticle.ArticleNumber, DeliveredQuantity = 15, Price = 100}
}
};
//Add entries
for (var i = 0; i < 5; i++)
{
connector.Create(newInvoice);
}
//Apply base test filter
var searchSettings = new InvoiceSearch();
searchSettings.CustomerNumber = tmpCustomer.CustomerNumber;
var fullCollection = connector.Find(searchSettings);
Assert.AreEqual(5, fullCollection.TotalResources);
Assert.AreEqual(5, fullCollection.Entities.Count);
Assert.AreEqual(1, fullCollection.TotalPages);
Assert.AreEqual(tmpCustomer.CustomerNumber, fullCollection.Entities.First().CustomerNumber);
//Apply Limit
searchSettings.Limit = 2;
var limitedCollection = connector.Find(searchSettings);
Assert.AreEqual(5, limitedCollection.TotalResources);
Assert.AreEqual(2, limitedCollection.Entities.Count);
Assert.AreEqual(3, limitedCollection.TotalPages);
//Delete entries (DELETE not supported)
foreach (var invoice in fullCollection.Entities)
connector.Cancel(invoice.DocumentNumber);
#region Delete arranged resources
FortnoxClient.CustomerConnector.Delete(tmpCustomer.CustomerNumber);
//FortnoxClient.ArticleConnector.Delete(tmpArticle.ArticleNumber);
#endregion Delete arranged resources
}
[TestMethod]
public void Test_DueDate()
{
#region Arrange
var tmpCustomer = FortnoxClient.CustomerConnector.Create(new Customer() { Name = "TmpCustomer", CountryCode = "SE", City = "Testopolis" });
var tmpArticle = FortnoxClient.ArticleConnector.Create(new Article() { Description = "TmpArticle", Type = ArticleType.Stock, PurchasePrice = 100 });
#endregion Arrange
var connector = FortnoxClient.InvoiceConnector;
var newInvoice = new Invoice()
{
CustomerNumber = tmpCustomer.CustomerNumber,
InvoiceDate = new DateTime(2019, 1, 20), //"2019-01-20",
Comments = "TestInvoice",
InvoiceRows = new List<InvoiceRow>()
{
new InvoiceRow(){ ArticleNumber = tmpArticle.ArticleNumber, DeliveredQuantity = 10, Price = 100},
new InvoiceRow(){ ArticleNumber = tmpArticle.ArticleNumber, DeliveredQuantity = 20, Price = 100},
new InvoiceRow(){ ArticleNumber = tmpArticle.ArticleNumber, DeliveredQuantity = 15, Price = 100}
}
};
var createdInvoice = connector.Create(newInvoice);
Assert.AreEqual("2019-01-20", createdInvoice.InvoiceDate?.ToString(APIConstants.DateFormat));
Assert.AreEqual("2019-02-19", createdInvoice.DueDate?.ToString(APIConstants.DateFormat));
var newInvoiceDate = new DateTime(2019, 1, 1);
var dateChange = newInvoiceDate - newInvoice.InvoiceDate.Value;
var newDueDate = createdInvoice.DueDate?.AddDays(dateChange.Days);
createdInvoice.InvoiceDate = newInvoiceDate;
createdInvoice.DueDate = newDueDate;
var updatedInvoice = connector.Update(createdInvoice);
Assert.AreEqual("2019-01-01", updatedInvoice.InvoiceDate?.ToString(APIConstants.DateFormat));
Assert.AreEqual("2019-01-31", updatedInvoice.DueDate?.ToString(APIConstants.DateFormat));
connector.Cancel(createdInvoice.DocumentNumber);
#region Delete arranged resources
FortnoxClient.CustomerConnector.Delete(tmpCustomer.CustomerNumber);
//FortnoxClient.ArticleConnector.Delete(tmpArticle.ArticleNumber);
#endregion Delete arranged resources
}
[TestMethod]
public void Test_Print()
{
#region Arrange
var cc = FortnoxClient.CustomerConnector;
var ac = FortnoxClient.ArticleConnector;
var tmpCustomer = cc.Create(new Customer() { Name = "TmpCustomer", CountryCode = "SE", City = "Testopolis" });
var tmpArticle = ac.Create(new Article() { Description = "TmpArticle", Type = ArticleType.Stock, PurchasePrice = 100 });
#endregion Arrange
var connector = FortnoxClient.InvoiceConnector;
var newInvoice = new Invoice()
{
CustomerNumber = tmpCustomer.CustomerNumber,
InvoiceDate = new DateTime(2019, 1, 20), //"2019-01-20",
DueDate = new DateTime(2019, 2, 20), //"2019-02-20",
InvoiceType = InvoiceType.CashInvoice,
PaymentWay = PaymentWay.Cash,
Comments = "TestInvoice",
InvoiceRows = new List<InvoiceRow>()
{
new InvoiceRow(){ ArticleNumber = tmpArticle.ArticleNumber, DeliveredQuantity = 10, Price = 100},
new InvoiceRow(){ ArticleNumber = tmpArticle.ArticleNumber, DeliveredQuantity = 20, Price = 100},
new InvoiceRow(){ ArticleNumber = tmpArticle.ArticleNumber, DeliveredQuantity = 15, Price = 100}
}
};
var createdInvoice = connector.Create(newInvoice);
var fileData = connector.Print(createdInvoice.DocumentNumber);
MyAssert.IsPDF(fileData);
connector.Cancel(createdInvoice.DocumentNumber);
#region Delete arranged resources
FortnoxClient.CustomerConnector.Delete(tmpCustomer.CustomerNumber);
//FortnoxClient.ArticleConnector.Delete(tmpArticle.ArticleNumber);
#endregion Delete arranged resources
}
[TestMethod]
public void Test_Email()
{
#region Arrange
var tmpCustomer = FortnoxClient.CustomerConnector.Create(new Customer() { Name = "TmpCustomer", CountryCode = "SE", City = "Testopolis", Email = "richard.randak@softwerk.se" });
var tmpArticle = FortnoxClient.ArticleConnector.Create(new Article() { Description = "TmpArticle", Type = ArticleType.Stock, PurchasePrice = 100 });
#endregion Arrange
var connector = FortnoxClient.InvoiceConnector;
var newInvoice = new Invoice()
{
CustomerNumber = tmpCustomer.CustomerNumber,
InvoiceDate = new DateTime(2019, 1, 20), //"2019-01-20",
DueDate = new DateTime(2019, 2, 20), //"2019-02-20",
InvoiceType = InvoiceType.CashInvoice,
PaymentWay = PaymentWay.Cash,
Comments = "Testing invoice email feature",
InvoiceRows = new List<InvoiceRow>()
{
new InvoiceRow(){ ArticleNumber = tmpArticle.ArticleNumber, DeliveredQuantity = 10, Price = 100},
new InvoiceRow(){ ArticleNumber = tmpArticle.ArticleNumber, DeliveredQuantity = 20, Price = 100},
new InvoiceRow(){ ArticleNumber = tmpArticle.ArticleNumber, DeliveredQuantity = 15, Price = 100}
}
};
var createdInvoice = connector.Create(newInvoice);
var emailedInvoice = connector.Email(createdInvoice.DocumentNumber);
Assert.AreEqual(emailedInvoice.DocumentNumber, createdInvoice.DocumentNumber);
connector.Cancel(createdInvoice.DocumentNumber);
#region Delete arranged resources
FortnoxClient.CustomerConnector.Delete(tmpCustomer.CustomerNumber);
//FortnoxClient.ArticleConnector.Delete(tmpArticle.ArticleNumber);
#endregion Delete arranged resources
}
[TestMethod]
public void Test_Search()
{
var connector = FortnoxClient.InvoiceConnector;
var searchSettings = new InvoiceSearch();
searchSettings.FromDate = new DateTime(2020,10, 10);
searchSettings.ToDate = new DateTime(2020, 10, 15);
var result = connector.Find(searchSettings);
Assert.IsTrue(result.Entities.Count > 0);
foreach (var invoice in result.Entities)
{
Assert.IsTrue(invoice.InvoiceDate >= searchSettings.FromDate);
Assert.IsTrue(invoice.InvoiceDate <= searchSettings.ToDate);
}
}
[TestMethod]
public void Test_Filter_By_AccountRange()
{
#region Arrange
var tmpCustomer = FortnoxClient.CustomerConnector.Create(new Customer() { Name = "TmpCustomer", CountryCode = "SE", City = "Testopolis" });
var tmpArticle = FortnoxClient.ArticleConnector.Create(new Article() { Description = "TmpArticle", Type = ArticleType.Stock, PurchasePrice = 100 });
#endregion Arrange
var connector = FortnoxClient.InvoiceConnector;
var invoice1 = new Invoice()
{
CustomerNumber = tmpCustomer.CustomerNumber,
InvoiceDate = new DateTime(2019, 1, 20), //"2019-01-20",
DueDate = new DateTime(2019, 2, 20), //"2019-02-20",
InvoiceType = InvoiceType.CashInvoice,
PaymentWay = PaymentWay.Cash,
Comments = "TestInvoice",
InvoiceRows = new List<InvoiceRow>()
{
new InvoiceRow(){ AccountNumber = 1010, ArticleNumber = tmpArticle.ArticleNumber, DeliveredQuantity = 20, Price = 100},
new InvoiceRow(){ AccountNumber = 4000, ArticleNumber = tmpArticle.ArticleNumber, DeliveredQuantity = 15, Price = 100}
}
};
var invoice2 = new Invoice()
{
CustomerNumber = tmpCustomer.CustomerNumber,
InvoiceDate = new DateTime(2019, 1, 20), //"2019-01-20",
DueDate = new DateTime(2019, 2, 20), //"2019-02-20",
InvoiceType = InvoiceType.CashInvoice,
PaymentWay = PaymentWay.Cash,
Comments = "TestInvoice",
InvoiceRows = new List<InvoiceRow>()
{
new InvoiceRow(){ AccountNumber = 2010, ArticleNumber = tmpArticle.ArticleNumber, DeliveredQuantity = 20, Price = 100},
new InvoiceRow(){ AccountNumber = 4000, ArticleNumber = tmpArticle.ArticleNumber, DeliveredQuantity = 15, Price = 100}
}
};
var invoice3 = new Invoice()
{
CustomerNumber = tmpCustomer.CustomerNumber,
InvoiceDate = new DateTime(2019, 1, 20), //"2019-01-20",
DueDate = new DateTime(2019, 2, 20), //"2019-02-20",
InvoiceType = InvoiceType.CashInvoice,
PaymentWay = PaymentWay.Cash,
Comments = "TestInvoice",
InvoiceRows = new List<InvoiceRow>()
{
new InvoiceRow(){ AccountNumber = 3000, ArticleNumber = tmpArticle.ArticleNumber, DeliveredQuantity = 20, Price = 100},
new InvoiceRow(){ AccountNumber = 3000, ArticleNumber = tmpArticle.ArticleNumber, DeliveredQuantity = 15, Price = 100}
}
};
invoice1 = connector.Create(invoice1);
invoice2 = connector.Create(invoice2);
invoice3 = connector.Create(invoice3);
var filter = new InvoiceSearch()
{
CustomerNumber = tmpCustomer.CustomerNumber,
};
var invoices = connector.Find(filter);
Assert.AreEqual(3, invoices.Entities.Count);
filter.AccountNumberFrom = "1000";
filter.AccountNumberTo = "1999";
invoices = connector.Find(filter);
Assert.AreEqual(1, invoices.Entities.Count);
Assert.AreEqual(invoice1.DocumentNumber, invoices.Entities.First().DocumentNumber);
filter.AccountNumberFrom = "2000";
filter.AccountNumberTo = "2999";
invoices = connector.Find(filter);
Assert.AreEqual(1, invoices.Entities.Count);
Assert.AreEqual(invoice2.DocumentNumber, invoices.Entities.First().DocumentNumber);
filter.AccountNumberFrom = "3000";
filter.AccountNumberTo = "3999";
invoices = connector.Find(filter);
Assert.AreEqual(1, invoices.Entities.Count);
Assert.AreEqual(invoice3.DocumentNumber, invoices.Entities.First().DocumentNumber);
filter.AccountNumberFrom = "4000";
filter.AccountNumberTo = "4999";
invoices = connector.Find(filter);
Assert.AreEqual(2, invoices.Entities.Count);
}
[TestMethod]
public void Test_InvoiceWithLabels()
{
#region Arrange
var tmpCustomer = FortnoxClient.CustomerConnector.Create(new Customer() { Name = "TmpCustomer", CountryCode = "SE", City = "Testopolis" });
var tmpArticle = FortnoxClient.ArticleConnector.Create(new Article() { Description = "TmpArticle", Type = ArticleType.Stock, PurchasePrice = 100 });
#endregion Arrange
var labelConnector = FortnoxClient.LabelConnector;
var label1 = labelConnector.Create(new Label() { Description = TestUtils.RandomString() });
var label2 = labelConnector.Create(new Label() { Description = TestUtils.RandomString() });
var connector = FortnoxClient.InvoiceConnector;
var invoice = new Invoice()
{
CustomerNumber = tmpCustomer.CustomerNumber,
InvoiceDate = new DateTime(2019, 1, 20), //"2019-01-20",
DueDate = new DateTime(2019, 2, 20), //"2019-02-20",
InvoiceType = InvoiceType.CashInvoice,
PaymentWay = PaymentWay.Cash,
Comments = "TestInvoice",
InvoiceRows = new List<InvoiceRow>()
{
new InvoiceRow(){ ArticleNumber = tmpArticle.ArticleNumber, DeliveredQuantity = 20, Price = 100},
new InvoiceRow(){ ArticleNumber = tmpArticle.ArticleNumber, DeliveredQuantity = 15, Price = 100}
},
Labels = new List<LabelReference>()
{
new LabelReference(label1.Id),
new LabelReference(label2.Id)
}
};
var createdInvoice = connector.Create(invoice);
Assert.AreEqual(2, createdInvoice.Labels.Count);
//Clean
connector.Cancel(createdInvoice.DocumentNumber);
labelConnector.Delete(label1.Id);
labelConnector.Delete(label2.Id);
}
[TestMethod]
public void Test_Invoice_FilterByLabel()
{
#region Arrange
var tmpCustomer = FortnoxClient.CustomerConnector.Create(new Customer() { Name = "TmpCustomer", CountryCode = "SE", City = "Testopolis" });
var tmpArticle = FortnoxClient.ArticleConnector.Create(new Article() { Description = "TmpArticle", Type = ArticleType.Stock, PurchasePrice = 100 });
#endregion Arrange
var labelConnector = FortnoxClient.LabelConnector;
var label1 = labelConnector.Create(new Label() { Description = TestUtils.RandomString() });
var label2 = labelConnector.Create(new Label() { Description = TestUtils.RandomString() });
var label3 = labelConnector.Create(new Label() { Description = TestUtils.RandomString() });
var connector = FortnoxClient.InvoiceConnector;
var invoice1 = new Invoice()
{
CustomerNumber = tmpCustomer.CustomerNumber,
InvoiceDate = new DateTime(2019, 1, 20), //"2019-01-20",
DueDate = new DateTime(2019, 2, 20), //"2019-02-20",
InvoiceType = InvoiceType.CashInvoice,
PaymentWay = PaymentWay.Cash,
Comments = "TestInvoice",
InvoiceRows = new List<InvoiceRow>()
{
new InvoiceRow(){ ArticleNumber = tmpArticle.ArticleNumber, DeliveredQuantity = 20, Price = 100},
new InvoiceRow(){ ArticleNumber = tmpArticle.ArticleNumber, DeliveredQuantity = 15, Price = 100}
},
Labels = new List<LabelReference>()
{
new LabelReference(label1.Id),
new LabelReference(label2.Id),
}
};
var invoice2 = new Invoice()
{
CustomerNumber = tmpCustomer.CustomerNumber,
InvoiceDate = new DateTime(2019, 1, 20), //"2019-01-20",
DueDate = new DateTime(2019, 2, 20), //"2019-02-20",
InvoiceType = InvoiceType.CashInvoice,
PaymentWay = PaymentWay.Cash,
Comments = "TestInvoice",
InvoiceRows = new List<InvoiceRow>()
{
new InvoiceRow(){ ArticleNumber = tmpArticle.ArticleNumber, DeliveredQuantity = 20, Price = 100},
new InvoiceRow(){ ArticleNumber = tmpArticle.ArticleNumber, DeliveredQuantity = 15, Price = 100}
},
Labels = new List<LabelReference>()
{
new LabelReference(label2.Id),
new LabelReference(label3.Id),
}
};
invoice1 = connector.Create(invoice1);
invoice2 = connector.Create(invoice2);
var filter = new InvoiceSearch()
{
CustomerNumber = tmpCustomer.CustomerNumber
};
var invoices = connector.Find(filter);
Assert.AreEqual(2, invoices.Entities.Count);
filter.LabelReference = label1.Id;
invoices = connector.Find(filter);
Assert.AreEqual(1, invoices.Entities.Count);
filter.LabelReference = label2.Id;
invoices = connector.Find(filter);
Assert.AreEqual(2, invoices.Entities.Count);
filter.LabelReference = label3.Id;
invoices = connector.Find(filter);
Assert.AreEqual(1, invoices.Entities.Count);
//Clean
connector.Cancel(invoice1.DocumentNumber);
connector.Cancel(invoice2.DocumentNumber);
labelConnector.Delete(label1.Id);
labelConnector.Delete(label2.Id);
}
/// <summary>
/// Prerequisites: A custom VAT 1.23% was added in the fortnox settings
/// </summary>
[TestMethod]
public void Test_Invoice_CustomVAT()
{
#region Arrange
var tmpCustomer = FortnoxClient.CustomerConnector.Create(new Customer() { Name = "TmpCustomer", CountryCode = "SE", City = "Testopolis" });
var tmpArticle = FortnoxClient.ArticleConnector.Create(new Article() { Description = "TmpArticle", Type = ArticleType.Stock, PurchasePrice = 100 });
#endregion Arrange
var connector = FortnoxClient.InvoiceConnector;
var newInvoice = new Invoice()
{
CustomerNumber = tmpCustomer.CustomerNumber,
InvoiceDate = new DateTime(2019, 1, 20), //"2019-01-20",
DueDate = new DateTime(2019, 2, 20), //"2019-02-20",
InvoiceType = InvoiceType.CashInvoice,
PaymentWay = PaymentWay.Cash,
Comments = "TestInvoice",
InvoiceRows = new List<InvoiceRow>()
{
new InvoiceRow(){ ArticleNumber = tmpArticle.ArticleNumber, DeliveredQuantity = 10, Price = 100, VAT = 1.23m},
new InvoiceRow(){ ArticleNumber = tmpArticle.ArticleNumber, DeliveredQuantity = 20, Price = 100, VAT = 1.23m},
new InvoiceRow(){ ArticleNumber = tmpArticle.ArticleNumber, DeliveredQuantity = 15, Price = 100, VAT = 1.23m}
}
};
var createdInvoice = connector.Create(newInvoice);
Assert.AreEqual(3, createdInvoice.InvoiceRows.Count);
Assert.AreEqual(1.23m, createdInvoice.InvoiceRows.First().VAT);
#region Delete arranged resources
FortnoxClient.InvoiceConnector.Cancel(createdInvoice.DocumentNumber);
FortnoxClient.CustomerConnector.Delete(tmpCustomer.CustomerNumber);
//FortnoxClient.ArticleConnector.Delete(tmpArticle.ArticleNumber);
#endregion Delete arranged resources
}
}
}
| 46.259669 | 189 | 0.594291 | [
"MIT",
"Unlicense"
] | WilliamGanrot/csharp-api-sdk | FortnoxSDK.Tests/ConnectorTests/InvoiceTests.cs | 25,119 | C# |
// <copyright file="ConfigurationService.cs" company="Automate The Planet Ltd.">
// Copyright 2021 Automate The Planet Ltd.
// Licensed under the Apache License, Version 2.0 (the "License");
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
// <author>Anton Angelov</author>
// <site>http://automatetheplanet.com/</site>
using Microsoft.Extensions.Configuration;
using System.IO;
using System.Linq;
using System.Reflection;
namespace HandlingTestEnvironmentsData
{
public sealed class ConfigurationService
{
private static ConfigurationService _instance;
public ConfigurationService() => Root = InitializeConfiguration();
public static ConfigurationService Instance
{
get
{
if (_instance == null)
{
_instance = new ConfigurationService();
}
return _instance;
}
}
public IConfigurationRoot Root { get; }
public BillingInfoDefaultValues GetBillingInfoDefaultValues()
{
var result = ConfigurationService.Instance.Root.GetSection("billingInfoDefaultValues").Get<BillingInfoDefaultValues>();
if (result == null)
{
throw new ConfigurationNotFoundException(typeof(BillingInfoDefaultValues).ToString());
}
return result;
}
public UrlSettings GetUrlSettings()
{
var result = ConfigurationService.Instance.Root.GetSection("urlSettings").Get<UrlSettings>();
if (result == null)
{
throw new ConfigurationNotFoundException(typeof(UrlSettings).ToString());
}
return result;
}
public WebSettings GetWebSettings()
=> ConfigurationService.Instance.Root.GetSection("webSettings").Get<WebSettings>();
private IConfigurationRoot InitializeConfiguration()
{
var filesInExecutionDir = Directory.GetFiles(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));
var settingsFile =
filesInExecutionDir.FirstOrDefault(x => x.Contains("testFrameworkSettings") && x.EndsWith(".json"));
var builder = new ConfigurationBuilder();
if (settingsFile != null)
{
builder.AddJsonFile(settingsFile, optional: true, reloadOnChange: true);
}
return builder.Build();
}
}
}
| 34.552941 | 131 | 0.64079 | [
"Apache-2.0"
] | AutomateThePlanet/AutomateThePlanet-Learning-Series | dotnet/Design-Architecture-Series/HandlingTestEnvironmentsData/Configuration/ConfigurationService.cs | 2,939 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/WinUser.h in the Windows SDK for Windows 10.0.20348.0
// Original source is Copyright © Microsoft. All rights reserved.
using NUnit.Framework;
using System.Runtime.InteropServices;
namespace TerraFX.Interop.UnitTests
{
/// <summary>Provides validation of the <see cref="INPUT_MESSAGE_SOURCE" /> struct.</summary>
public static unsafe partial class INPUT_MESSAGE_SOURCETests
{
/// <summary>Validates that the <see cref="INPUT_MESSAGE_SOURCE" /> struct is blittable.</summary>
[Test]
public static void IsBlittableTest()
{
Assert.That(Marshal.SizeOf<INPUT_MESSAGE_SOURCE>(), Is.EqualTo(sizeof(INPUT_MESSAGE_SOURCE)));
}
/// <summary>Validates that the <see cref="INPUT_MESSAGE_SOURCE" /> struct has the right <see cref="LayoutKind" />.</summary>
[Test]
public static void IsLayoutSequentialTest()
{
Assert.That(typeof(INPUT_MESSAGE_SOURCE).IsLayoutSequential, Is.True);
}
/// <summary>Validates that the <see cref="INPUT_MESSAGE_SOURCE" /> struct has the correct size.</summary>
[Test]
public static void SizeOfTest()
{
Assert.That(sizeof(INPUT_MESSAGE_SOURCE), Is.EqualTo(8));
}
}
}
| 39.527778 | 145 | 0.678145 | [
"MIT"
] | DaZombieKiller/terrafx.interop.windows | tests/Interop/Windows/um/winuser/INPUT_MESSAGE_SOURCETests.cs | 1,425 | C# |
// -------------------------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// -------------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Client;
using Newtonsoft.Json;
namespace Microsoft.Health.Fhir.CosmosDb.UnitTests
{
internal class CosmosDbMockingHelper
{
internal static DocumentClientException CreateDocumentClientException(string message, NameValueCollection responseHeaders, HttpStatusCode? statusCode)
{
return (DocumentClientException)CreateInstance( // internal DocumentClientException(string message, Exception innerException, INameValueCollection responseHeaders, HttpStatusCode? statusCode, Uri requestUri = null)
typeof(DocumentClientException),
message,
null,
CreateInstance( // public DictionaryNameValueCollection(NameValueCollection c)
typeof(IDocumentClient).Assembly.GetType("Microsoft.Azure.Documents.Collections.DictionaryNameValueCollection"),
responseHeaders),
statusCode,
null);
}
internal static ResourceResponse<T> CreateResourceResponse<T>(T resource, HttpStatusCode statusCode, NameValueCollection responseHeaders)
where T : Resource, new()
{
return (ResourceResponse<T>)CreateInstance( // internal ResourceResponse(DocumentServiceResponse response, ITypeResolver<TResource> typeResolver = null)
typeof(ResourceResponse<T>),
CreateDocumentServiceResponse(resource, statusCode, responseHeaders),
null);
}
internal static StoredProcedureResponse<T> CreateStoredProcedureResponse<T>(T resource, HttpStatusCode statusCode, NameValueCollection responseHeaders)
{
return (StoredProcedureResponse<T>)CreateInstance( // internal StoredProcedureResponse(DocumentServiceResponse response, JsonSerializerSettings serializerSettings = null)
typeof(StoredProcedureResponse<T>),
CreateDocumentServiceResponse(resource, statusCode, responseHeaders),
null);
}
internal static object CreateDocumentServiceResponse<T>(T resource, HttpStatusCode statusCode, NameValueCollection responseHeaders)
{
var serializer = new JsonSerializer();
var ms = new MemoryStream();
var jsonTextWriter = new JsonTextWriter(new StreamWriter(ms));
serializer.Serialize(jsonTextWriter, resource);
jsonTextWriter.Flush();
ms.Position = 0;
return CreateInstance( // internal DocumentServiceResponse(Stream body, INameValueCollection headers, HttpStatusCode statusCode, JsonSerializerSettings serializerSettings = null)
typeof(IDocumentClient).Assembly.GetType("Microsoft.Azure.Documents.DocumentServiceResponse"),
ms,
CreateInstance( // public DictionaryNameValueCollection(NameValueCollection c)
typeof(IDocumentClient).Assembly.GetType("Microsoft.Azure.Documents.Collections.DictionaryNameValueCollection"),
responseHeaders),
statusCode,
null);
}
private static object CreateInstance(Type type, params object[] args)
{
return Activator.CreateInstance(type, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public, null, args, CultureInfo.InvariantCulture);
}
}
}
| 51.701299 | 226 | 0.66516 | [
"MIT"
] | AKQHealthService/fhir-server | src/Microsoft.Health.Fhir.CosmosDb.UnitTests/CosmosDbMockingHelper.cs | 3,983 | C# |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Drawing;
using SonicRetro.SonLVL.API;
namespace S3KObjectDefinitions.Common
{
class HiddenMonitor : Monitor
{
public override string Name
{
get { return "Hidden Monitor"; }
}
public override int GetDepth(ObjectEntry obj)
{
return 5;
}
}
class Monitor : ObjectDefinition
{
private ReadOnlyCollection<byte> subtypes;
private string[] subtypeNames;
private Sprite[][] sprites;
private Sprite[] unknownSprite;
public override string Name
{
get { return "Monitor"; }
}
public override Sprite Image
{
get { return sprites[0][0]; }
}
public override ReadOnlyCollection<byte> Subtypes
{
get { return subtypes; }
}
public override string SubtypeName(byte subtype)
{
return subtypeNames[subtype];
}
public override Sprite SubtypeImage(byte subtype)
{
return GetSubtypeSprites(subtype)[0];
}
public override Sprite GetSprite(ObjectEntry obj)
{
return GetSubtypeSprites(obj.SubType)[(obj.XFlip ? 1 : 0) | (obj.YFlip ? 2 : 0)];
}
public override int GetDepth(ObjectEntry obj)
{
return 3;
}
public override void Init(ObjectData data)
{
var indexer = new MultiFileIndexer<byte>();
indexer.AddFile(new List<byte>(LevelData.ReadFile(
"../General/Sprites/Monitors/Monitors.bin", CompressionType.Nemesis)), 0);
indexer.AddFile(new List<byte>(LevelData.ReadFile(
"../General/Sprites/HUD Icon/Sonic life icon.bin", CompressionType.Nemesis)), 25088);
var art = indexer.ToArray();
var map = LevelData.ASMToBin(
"../General/Sprites/Monitors/Map - Monitor.asm", LevelData.Game.MappingsVersion);
subtypeNames = new[]
{
"Static",
"1-Up",
"Eggman",
"Rings",
"Speed Shoes",
"Flame Barrier",
"Thunder Barrier",
"Aqua Barrier",
"Invincibility",
"Super"
};
var subtypes = new byte[subtypeNames.Length];
subtypes[1] = 1;
sprites = new Sprite[subtypeNames.Length][];
sprites[0] = BuildFlippedSprites(ObjectHelper.MapToBmp(art, map, 0, 0));
sprites[1] = BuildFlippedSprites(ObjectHelper.MapToBmp(art, map, 2, 0));
var index = 2;
while (index < subtypeNames.Length)
{
subtypes[index] = (byte)index;
sprites[index++] = BuildFlippedSprites(ObjectHelper.MapToBmp(art, map, index, 0));
}
unknownSprite = BuildFlippedSprites(ObjectHelper.UnknownObject);
this.subtypes = new ReadOnlyCollection<byte>(subtypes);
}
private Sprite[] BuildFlippedSprites(Sprite sprite)
{
var flipX = new Sprite(sprite, true, false);
var flipY = new Sprite(sprite, false, true);
var flipXY = new Sprite(sprite, true, true);
return new[] { sprite, flipX, flipY, flipXY };
}
private Sprite[] GetSubtypeSprites(byte subtype)
{
return subtype < sprites.Length ? sprites[subtype] : unknownSprite;
}
}
}
| 23.379032 | 89 | 0.685754 | [
"Apache-2.0"
] | NatsumiFox/AMPS-Sonic-3-Knuckles | SonLVL INI Files/Common/Monitor.cs | 2,899 | C# |
using System;
using System.Windows.Forms;
namespace ScreenCaptureExample
{
internal static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
private static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new HomeForm());
}
}
} | 24.157895 | 65 | 0.588235 | [
"MIT"
] | hughbe/Communicate | windows/src/Demos/ScreenCaptureExample/Program.cs | 461 | C# |
using Rocket.Unturned.Player;
using SDG.Unturned;
using Steamworks;
namespace SolokLibrary.Player.Functions
{
public static class LookFunction
{
public static void DisableOverlay(CSteamID steamID)
{
UnturnedPlayer.FromCSteamID(steamID).Player.look.disableOverlay();
}
public static void DisableScope(CSteamID steamID)
{
UnturnedPlayer.FromCSteamID(steamID).Player.look.disableScope();
}
public static void DisableZoom(CSteamID steamID)
{
UnturnedPlayer.FromCSteamID(steamID).Player.look.disableZoom();
}
public static void EnableZoom(CSteamID steamID, float zoom)
{
UnturnedPlayer.FromCSteamID(steamID).Player.look.enableZoom(zoom);
}
public static void EnableScope(CSteamID steamID, float zoom, ELightingVision vision)
{
UnturnedPlayer.FromCSteamID(steamID).Player.look.enableScope(zoom, vision);
}
public static void EnableOverlay(CSteamID steamID)
{
UnturnedPlayer.FromCSteamID(steamID).Player.look.enableOverlay();
}
}
} | 33.941176 | 92 | 0.658579 | [
"MIT"
] | BarehSolok/SolokLibrary | Player/Functions/LookFunction.cs | 1,156 | C# |
#region BSD License
/*
*
* Original BSD 3-Clause License (https://github.com/ComponentFactory/Krypton/blob/master/LICENSE)
* © Component Factory Pty Ltd, 2006 - 2016, (Version 4.5.0.0) All rights reserved.
*
* New BSD 3-Clause License (https://github.com/Krypton-Suite/Standard-Toolkit/blob/master/LICENSE)
* Modifications by Peter Wagner(aka Wagnerp) & Simon Coghlan(aka Smurf-IV), et al. 2017 - 2022. All rights reserved.
*
*/
#endregion
// ReSharper disable UnusedMember.Local
namespace Krypton.Toolkit
{
/// <summary>
/// Multiline String Editor Window.
/// </summary>
internal sealed class MultilineStringEditor : KryptonForm //Form
{
#region Instance Members
private bool _saveChanges = true;
private readonly KryptonTextBox _textBox;
private readonly KryptonTextBox _owner;
private VisualStyleRenderer _sizeGripRenderer;
#endregion
#region Identity
/// <summary>
/// Initializes a new instance of the MultilineStringEditor class.
/// </summary>
/// <param name="owner"></param>
public MultilineStringEditor(KryptonTextBox owner)
{
SuspendLayout();
_textBox = new KryptonTextBox { Dock = DockStyle.Fill, Multiline = true };
_textBox.StateCommon.Border.Draw = InheritBool.False;
_textBox.KeyDown += OnKeyDownTextBox;
AutoScaleDimensions = new SizeF(6F, 13F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(284, 262);
ControlBox = false;
Controls.Add(_textBox);
FormBorderStyle = FormBorderStyle.None;
BackColor = Color.White;
Padding = new Padding(1, 1, 1, 16);
MaximizeBox = false;
MinimizeBox = false;
MinimumSize = new Size(100, 20);
AutoSize = false;
DoubleBuffered = true;
ResizeRedraw = true;
ShowIcon = false;
ShowInTaskbar = false;
StartPosition = FormStartPosition.Manual;
_owner = owner;
ResumeLayout(false);
}
#endregion
#region Public Methods
/// <summary>
/// Shows the multiline string editor.
/// </summary>
public void ShowEditor()
{
Location = _owner.PointToScreen(Point.Empty);
_textBox.Text = _owner.Text;
Show();
}
#endregion
#region Protected Override
/// <summary>
/// Closes the multiline string editor.
/// </summary>
/// <param name="e">
/// Event arguments.
/// </param>
protected override void OnDeactivate(EventArgs e)
{
base.OnDeactivate(e);
CloseEditor();
}
/// <summary>
/// Raises the Paint event.
/// </summary>
/// <param name="e">
/// A PaintEventArgs that contains the event data.
/// </param>
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
// Paint the sizing grip.
using (Bitmap gripImage = new(0x10, 0x10))
{
using (Graphics g = Graphics.FromImage(gripImage))
{
if (Application.RenderWithVisualStyles)
{
if (_sizeGripRenderer == null)
{
_sizeGripRenderer = new VisualStyleRenderer(VisualStyleElement.Status.Gripper.Normal);
}
_sizeGripRenderer.DrawBackground(g, new Rectangle(0, 0, 0x10, 0x10));
}
else
{
ControlPaint.DrawSizeGrip(g, BackColor, 0, 0, 0x10, 0x10);
}
}
e.Graphics.DrawImage(gripImage, ClientSize.Width - 0x10, ClientSize.Height - 0x10 + 1, 0x10, 0x10);
}
ControlPaint.DrawBorder(e.Graphics, ClientRectangle, Color.Gray, ButtonBorderStyle.Solid);
}
/// <summary>
/// Processes Windows messages.
/// </summary>
/// <param name="m">
/// The Windows Message to process.
/// </param>
protected override void WndProc(ref Message m)
{
var handled = false;
if (m.Msg == PI.WM_.NCHITTEST)
{
handled = OnNcHitTest(ref m);
}
else if (m.Msg == PI.WM_.GETMINMAXINFO)
{
handled = OnGetMinMaxInfo(ref m);
}
if (!handled)
{
base.WndProc(ref m);
}
}
#endregion
#region Private Methods
/// <summary>
/// Closes the editor form.
/// </summary>
private void CloseEditor()
{
if (_saveChanges)
{
_owner.Text = _textBox.Text;
}
Close();
}
/// <summary>
/// Occurs when a key is pressed while the control has focus.
/// </summary>
/// <param name="sender">The control.</param>
/// <param name="e">The event arguments.</param>
private void OnKeyDownTextBox(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Escape)
{
_saveChanges = false;
CloseEditor();
}
}
/// <summary>
/// Occurs when the MinMaxInfo needs to be retrieved by the operating system.
/// </summary>
/// <param name="m">
/// The window message.
/// </param>
/// <returns>
/// true if the message was handled; otherwise false.
/// </returns>
private bool OnGetMinMaxInfo(ref Message m)
{
PI.MINMAXINFO minMax = (PI.MINMAXINFO)Marshal.PtrToStructure(m.LParam, typeof(PI.MINMAXINFO));
if (!MaximumSize.IsEmpty)
{
minMax.ptMaxTrackSize.X = MaximumSize.Width;
minMax.ptMaxTrackSize.Y = MaximumSize.Height;
}
minMax.ptMinTrackSize.X = MinimumSize.Width;
minMax.ptMinTrackSize.Y = MinimumSize.Height;
Marshal.StructureToPtr(minMax, m.LParam, false);
return true;
}
/// <summary>
/// Occurs when the operating system needs to determine what part of the window corresponds
/// to a particular screen coordinate.
/// </summary>
/// <param name="m">
/// The window message.
/// </param>
/// <returns>
/// true if the message was handled; otherwise false.
/// </returns>
private bool OnNcHitTest(ref Message m)
{
Point clientLocation = PointToClient(Cursor.Position);
GripBounds gripBounds = new(ClientRectangle);
if (gripBounds.BottomRight.Contains(clientLocation))
{
m.Result = (IntPtr)PI.HT.BOTTOMRIGHT;
}
else if (gripBounds.Bottom.Contains(clientLocation))
{
m.Result = (IntPtr)PI.HT.BOTTOM;
}
else if (gripBounds.Right.Contains(clientLocation))
{
m.Result = (IntPtr)PI.HT.RIGHT;
}
return m.Result != IntPtr.Zero;
}
#endregion
#region Internal
// ReSharper disable IdentifierTypo
// ReSharper disable InconsistentNaming
private struct GripBounds
{
private const int GripSize = 6;
private const int CornerGripSize = GripSize << 1;
public GripBounds(Rectangle clientRectangle) => ClientRectangle = clientRectangle;
private Rectangle ClientRectangle
{
get;
//set { clientRectangle = value; }
}
public Rectangle Bottom
{
get
{
Rectangle rect = ClientRectangle;
rect.Y = rect.Bottom - GripSize + 1;
rect.Height = GripSize;
return rect;
}
}
public Rectangle BottomRight
{
get
{
Rectangle rect = ClientRectangle;
rect.Y = rect.Bottom - CornerGripSize + 1;
rect.Height = CornerGripSize;
rect.X = rect.Width - CornerGripSize + 1;
rect.Width = CornerGripSize;
return rect;
}
}
public Rectangle Top
{
get
{
Rectangle rect = ClientRectangle;
rect.Height = GripSize;
return rect;
}
}
public Rectangle TopRight
{
get
{
Rectangle rect = ClientRectangle;
rect.Height = CornerGripSize;
rect.X = rect.Width - CornerGripSize + 1;
rect.Width = CornerGripSize;
return rect;
}
}
public Rectangle Left
{
get
{
Rectangle rect = ClientRectangle;
rect.Width = GripSize;
return rect;
}
}
public Rectangle BottomLeft
{
get
{
Rectangle rect = ClientRectangle;
rect.Width = CornerGripSize;
rect.Y = rect.Height - CornerGripSize + 1;
rect.Height = CornerGripSize;
return rect;
}
}
public Rectangle Right
{
get
{
Rectangle rect = ClientRectangle;
rect.X = rect.Right - GripSize + 1;
rect.Width = GripSize;
return rect;
}
}
public Rectangle TopLeft
{
get
{
Rectangle rect = ClientRectangle;
rect.Width = CornerGripSize;
rect.Height = CornerGripSize;
return rect;
}
}
}
// ReSharper restore IdentifierTypo
// ReSharper restore InconsistentNaming
#endregion
}
} | 31.731563 | 119 | 0.485079 | [
"BSD-3-Clause"
] | Krypton-Suite/Standard-Toolkit | Source/Krypton Components/Krypton.Toolkit/Controls Visuals/MultilineStringEditor.cs | 10,760 | C# |
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System;
namespace OpenVIII
{
public abstract class Texture_Base
{
#region Fields
private const ushort blue_mask = 0x7C00;
private const ushort green_mask = 0x3E0;
private const ushort red_mask = 0x1F;
/// <summary>
/// Special Transparency Processing bit.
/// </summary>
/// <remarks>
/// The STP (special transparency processing) bit has varying special meanings. Depending on
/// the current transparency processing mode, it denotes if pixels of this color should be
/// treated as transparent or not. If transparency processing is enabled, pixels of this
/// color will be rendered transparent if the STP bit is set. A special case is black pixels
/// (RGB 0,0,0), which by default are treated as transparent by the PlayStation unless the
/// STP bit is set.
/// </remarks>
/// <see cref="http://www.psxdev.net/forum/viewtopic.php?t=109"/>
/// <seealso cref="http://www.raphnet.net/electronique/psx_adaptor/Playstation.txt"/>
private const ushort STP_mask = 0x8000;
#endregion Fields
#region Properties
public abstract int GetClutCount { get; }
public abstract int GetClutSize { get; }
public abstract int GetColorsCountPerPalette { get; }
public abstract byte GetBpp { get; }
public abstract int GetHeight { get; }
public abstract int GetOrigX { get; }
public abstract int GetOrigY { get; }
public abstract int GetWidth { get; }
#endregion Properties
#region Methods
public abstract void ForceSetClutColors(ushort newNumOfColours);
public abstract void ForceSetClutCount(ushort newClut);
public abstract Color[] GetClutColors(ushort clut);
public abstract Texture2D GetTexture();
public abstract Texture2D GetTexture(Color[] colors = null);
public abstract Texture2D GetTexture(ushort? clut = null);
public abstract void Save(string path);
/// <summary>
/// Convert ABGR1555 color to RGBA 32bit color
/// </summary>
/// <remarks>
/// FromPsColor from TEX does the same thing I think. Unsure which is better. I like the masks
/// </remarks>
public static Color ABGR1555toRGBA32bit(ushort pixel, bool ignoreAlpha = false)
{
// alert to let me know if we might need to check something.
if (pixel == 0 && !ignoreAlpha) return Color.TransparentBlack;
//https://docs.microsoft.com/en-us/windows/win32/directshow/working-with-16-bit-rgb
// had the masks. though they were doing rgb but we are doing bgr so i switched red and blue.
Color ret = new Color
{
R = (byte)MathHelper.Clamp((pixel & red_mask) << 3, 0, 255),
G = (byte)MathHelper.Clamp(((pixel & green_mask) >> 5) << 3, 0, 255),
B = (byte)MathHelper.Clamp(((pixel & blue_mask) >> 10) << 3, 0, 255),
A = 255
};
//if (GetSTP(pixel))
//{
// //ret.A = Transparency.GetAlpha;
// Debug.WriteLine($"Special Transparency Processing bit set 16 bit color: {pixel & 0x7FFF}, 32 bit color: {ret}");
// //Debug.Assert(false);
//}
//TDW has STP
return ret;
}
//public static class Transparency
//{
// /// <summary>
// /// <para>PSX Transparency Mode</para>
// /// <para>
// /// GPU first reads the pixel it wants to write to, and then calculates the color it will
// /// write from the 2 pixels according to the semi-transparency mode selected
// /// </para>
// /// <para>OFF is 100% alpha</para>
// /// <para>Mode 1 is 50%</para>
// /// <para>Mode 2 is supposed to be existing pixel plus value of new one.</para>
// /// <para>Mode 3 is supposed to be existing pixel minus value of new one.</para>
// /// <para>Mode 4 is 25%</para>
// /// <para>Unsure if the pixel is supposed to be 50% alpha before this</para>
// /// </summary>
// /// <see cref="http://www.raphnet.net/electronique/psx_adaptor/Playstation.txt"/>
// //public static readonly byte[] Modes = { 0xFF 0x7F, 0xFF, 0x7F, 0x3F }; // if 100% before calculation
// public static readonly byte[] Modes = { 0xFF, 0x3F, 0x7F, 0x7F, 0x1F }; // if 50% before calculation
// public static byte GetAlpha => Modes[0];
//}
/// <summary>
/// Get Special Transparency Processing bit.
/// </summary>
/// <param name="pixel">16 bit color</param>
/// <returns>true if bit is set and not black, otherwise false.</returns>
protected static bool GetSTP(ushort pixel) =>
// I set this to always return false for black. As it's transparency is handled in
// conversion method.
(pixel & 0x7FFF) == 0 ? false : ((pixel & STP_mask) >> 15) > 0;//If color is not black and STP bit on, possible semi-transparency.
//http://www.raphnet.net/electronique/psx_adaptor/Playstation.txt
//4 modes psx could use for Semi-Transparency. I donno which one ff8 uses or if it uses only one.
//If Black is transparent when bit is off. And visible when bit is on.
///// <summary>
///// Ratio needed to convert 16 bit to 32 bit color
///// </summary>
///// <seealso cref="https://github.com/myst6re/vincent-tim/blob/master/PsColor.h"/>
//public const double COEFF_COLOR = (double)255 / 31;
///// <summary>
///// converts 16 bit color to 32bit with alpha. alpha needs to be set true manually per pixel
///// unless you know the color value.
///// </summary>
///// <param name="color">16 bit color</param>
///// <param name="useAlpha">area is visable or not</param>
///// <returns>byte[4] red green blue alpha, i think</returns>
///// <see cref="https://github.com/myst6re/vincent-tim/blob/master/PsColor.cpp"/>
//public static Color FromPsColor(ushort color, bool useAlpha = false) => new Color((byte)Math.Round((color & 31) * COEFF_COLOR), (byte)Math.Round(((color >> 5) & 31) * COEFF_COLOR), (byte)Math.Round(((color >> 10) & 31) * COEFF_COLOR), (byte)(color == 0 && useAlpha ? 0 : 255));
public static Texture_Base Open(byte[] buffer, uint offset = 0)
{
switch (BitConverter.ToUInt32(buffer, (int)(0 + offset)))
{
case 0x1:
case 0x2:
return new TEX(buffer);
case 0x10:
return new TIM2(buffer, 0);
default:
return null;
}
}
#endregion Methods
}
} | 43.888199 | 287 | 0.581234 | [
"MIT"
] | RomanMayer7/OpenVIII | Core/Image/Texture_Base.cs | 7,068 | C# |
using System;
using System.ComponentModel;
using System.Reflection;
/** Enumeration values for GermanWeaponsForLifeForms
* The enumeration values are generated from the SISO DIS XML EBV document (R35), which was
* obtained from http://discussions.sisostds.org/default.asp?action=10&fd=31<p>
*
* Note that this has two ways to look up an enumerated instance from a value: a fast
* but brittle array lookup, and a slower and more garbage-intensive, but safer, method.
* if you want to minimize memory use, get rid of one or the other.<p>
*
* Copyright 2008-2009. This work is licensed under the BSD license, available at
* http://www.movesinstitute.org/licenses<p>
*
* @author DMcG, Jason Nelson
* Modified for use with C#:
* Peter Smith (Naval Air Warfare Center - Training Systems Division)
*/
namespace DISnet
{
public partial class DISEnumerations
{
public enum GermanWeaponsForLifeForms
{
[Description("G3 rifle")]
G3_RIFLE = 1,
[Description("G11 rifle")]
G11_RIFLE = 2,
[Description("P1 pistol")]
P1_PISTOL = 3,
[Description("MG3 machine gun")]
MG3_MACHINE_GUN = 4,
[Description("Milan missile")]
MILAN_MISSILE = 5,
[Description("MP1 Uzi submachine gun")]
MP1_UZI_SUBMACHINE_GUN = 6,
[Description("Panzerfaust 3 Light Anti-Tank Weapon")]
PANZERFAUST_3_LIGHT_ANTI_TANK_WEAPON = 7,
[Description("DM19 hand grenade")]
DM19_HAND_GRENADE = 8,
[Description("DM29 hand grenade")]
DM29_HAND_GRENADE = 9
}
} //End Parial Class
} //End Namespace
| 26.290323 | 92 | 0.674233 | [
"BSD-2-Clause"
] | rodneyp290/open-dis-csharp | C#/DIS#1.0/Examples/EnumerationExample/Enumerations/GermanWeaponsForLifeForms.cs | 1,630 | C# |
namespace View.UI.Wins
{
public static class Windows
{
public static readonly AlertWin ALERT_WIN = new AlertWin();
public static readonly ConnectingWin CONNECTING_WIN = new ConnectingWin();
public static readonly ConfirmWin CONFIRM_WIN = new ConfirmWin();
public static void CloseAll()
{
ALERT_WIN.Hide( true );
CONNECTING_WIN.Hide( true );
CONFIRM_WIN.Hide( true );
}
}
} | 24.875 | 76 | 0.728643 | [
"MIT"
] | niuniuzhu/Lockstep | Project/View/UI/Wins/Windows.cs | 400 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
namespace Microsoft.Azure.PowerShell.Cmdlets.Logz.Cmdlets
{
using static Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.Extensions;
using System;
/// <summary>
/// Sending request to update the collection when Logz.io agent has been installed on a VM for a given monitor.
/// </summary>
/// <remarks>
/// [OpenAPI] ListVmHostUpdate=>POST:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Logz/monitors/{monitorName}/vmHostUpdate"
/// </remarks>
[global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzLogzMonitorVMHost_ListExpanded", SupportsShouldProcess = true)]
[global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Logz.Models.Api20201001Preview.IVMResources))]
[global::Microsoft.Azure.PowerShell.Cmdlets.Logz.Description(@"Sending request to update the collection when Logz.io agent has been installed on a VM for a given monitor.")]
[global::Microsoft.Azure.PowerShell.Cmdlets.Logz.Generated]
public partial class UpdateAzLogzMonitorVMHost_ListExpanded : global::System.Management.Automation.PSCmdlet,
Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.IEventListener
{
/// <summary>A unique id generatd for the this cmdlet when it is instantiated.</summary>
private string __correlationId = System.Guid.NewGuid().ToString();
/// <summary>A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet)</summary>
private global::System.Management.Automation.InvocationInfo __invocationInfo;
/// <summary>A unique id generatd for the this cmdlet when ProcessRecord() is called.</summary>
private string __processRecordId;
/// <summary>
/// The <see cref="global::System.Threading.CancellationTokenSource" /> for this operation.
/// </summary>
private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource();
/// <summary>Backing field for <see cref="Body" /> property.</summary>
private Microsoft.Azure.PowerShell.Cmdlets.Logz.Models.Api20201001Preview.IVMHostUpdateRequest _body= new Microsoft.Azure.PowerShell.Cmdlets.Logz.Models.Api20201001Preview.VMHostUpdateRequest();
/// <summary>Request of a list VM Host Update Operation.</summary>
private Microsoft.Azure.PowerShell.Cmdlets.Logz.Models.Api20201001Preview.IVMHostUpdateRequest Body { get => this._body; set => this._body = value; }
/// <summary>Wait for .NET debugger to attach</summary>
[global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")]
[global::Microsoft.Azure.PowerShell.Cmdlets.Logz.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Logz.ParameterCategory.Runtime)]
public global::System.Management.Automation.SwitchParameter Break { get; set; }
/// <summary>The reference to the client API class.</summary>
public Microsoft.Azure.PowerShell.Cmdlets.Logz.Logz Client => Microsoft.Azure.PowerShell.Cmdlets.Logz.Module.Instance.ClientAPI;
/// <summary>
/// The credentials, account, tenant, and subscription used for communication with Azure
/// </summary>
[global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")]
[global::System.Management.Automation.ValidateNotNull]
[global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")]
[global::Microsoft.Azure.PowerShell.Cmdlets.Logz.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Logz.ParameterCategory.Azure)]
public global::System.Management.Automation.PSObject DefaultProfile { get; set; }
/// <summary>SendAsync Pipeline Steps to be appended to the front of the pipeline</summary>
[global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")]
[global::System.Management.Automation.ValidateNotNull]
[global::Microsoft.Azure.PowerShell.Cmdlets.Logz.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Logz.ParameterCategory.Runtime)]
public Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.SendAsyncStep[] HttpPipelineAppend { get; set; }
/// <summary>SendAsync Pipeline Steps to be prepended to the front of the pipeline</summary>
[global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be prepended to the front of the pipeline")]
[global::System.Management.Automation.ValidateNotNull]
[global::Microsoft.Azure.PowerShell.Cmdlets.Logz.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Logz.ParameterCategory.Runtime)]
public Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; }
/// <summary>Accessor for our copy of the InvocationInfo.</summary>
public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } }
/// <summary>
/// <see cref="IEventListener" /> cancellation delegate. Stops the cmdlet when called.
/// </summary>
global::System.Action Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel;
/// <summary><see cref="IEventListener" /> cancellation token.</summary>
global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.IEventListener.Token => _cancellationTokenSource.Token;
/// <summary>Backing field for <see cref="Name" /> property.</summary>
private string _name;
/// <summary>Monitor resource name</summary>
[global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Monitor resource name")]
[Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.Info(
Required = true,
ReadOnly = false,
Description = @"Monitor resource name",
SerializedName = @"monitorName",
PossibleTypes = new [] { typeof(string) })]
[global::Microsoft.Azure.PowerShell.Cmdlets.Logz.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Logz.ParameterCategory.Path)]
public string Name { get => this._name; set => this._name = value; }
/// <summary>
/// The instance of the <see cref="Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.HttpPipeline" /> that the remote call will use.
/// </summary>
private Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.HttpPipeline Pipeline { get; set; }
/// <summary>The URI for the proxy server to use</summary>
[global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "The URI for the proxy server to use")]
[global::Microsoft.Azure.PowerShell.Cmdlets.Logz.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Logz.ParameterCategory.Runtime)]
public global::System.Uri Proxy { get; set; }
/// <summary>Credentials for a proxy server to use for the remote call</summary>
[global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Credentials for a proxy server to use for the remote call")]
[global::System.Management.Automation.ValidateNotNull]
[global::Microsoft.Azure.PowerShell.Cmdlets.Logz.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Logz.ParameterCategory.Runtime)]
public global::System.Management.Automation.PSCredential ProxyCredential { get; set; }
/// <summary>Use the default credentials for the proxy</summary>
[global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Use the default credentials for the proxy")]
[global::Microsoft.Azure.PowerShell.Cmdlets.Logz.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Logz.ParameterCategory.Runtime)]
public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; }
/// <summary>Backing field for <see cref="ResourceGroupName" /> property.</summary>
private string _resourceGroupName;
/// <summary>The name of the resource group. The name is case insensitive.</summary>
[global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the resource group. The name is case insensitive.")]
[Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.Info(
Required = true,
ReadOnly = false,
Description = @"The name of the resource group. The name is case insensitive.",
SerializedName = @"resourceGroupName",
PossibleTypes = new [] { typeof(string) })]
[global::Microsoft.Azure.PowerShell.Cmdlets.Logz.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Logz.ParameterCategory.Path)]
public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; }
/// <summary>Specifies the state of the operation - install/ delete.</summary>
[global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Specifies the state of the operation - install/ delete.")]
[global::Microsoft.Azure.PowerShell.Cmdlets.Logz.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Logz.ParameterCategory.Body)]
[Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"Specifies the state of the operation - install/ delete.",
SerializedName = @"state",
PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Logz.Support.VMHostUpdateStates) })]
[global::System.Management.Automation.ArgumentCompleter(typeof(Microsoft.Azure.PowerShell.Cmdlets.Logz.Support.VMHostUpdateStates))]
public Microsoft.Azure.PowerShell.Cmdlets.Logz.Support.VMHostUpdateStates State { get => Body.State ?? ((Microsoft.Azure.PowerShell.Cmdlets.Logz.Support.VMHostUpdateStates)""); set => Body.State = value; }
/// <summary>Backing field for <see cref="SubscriptionId" /> property.</summary>
private string _subscriptionId;
/// <summary>The ID of the target subscription.</summary>
[global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of the target subscription.")]
[Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.Info(
Required = true,
ReadOnly = false,
Description = @"The ID of the target subscription.",
SerializedName = @"subscriptionId",
PossibleTypes = new [] { typeof(string) })]
[Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.DefaultInfo(
Name = @"",
Description =@"",
Script = @"(Get-AzContext).Subscription.Id")]
[global::Microsoft.Azure.PowerShell.Cmdlets.Logz.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Logz.ParameterCategory.Path)]
public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; }
/// <summary>Request of a list vm host update operation.</summary>
[global::System.Management.Automation.AllowEmptyCollection]
[global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Request of a list vm host update operation.")]
[global::Microsoft.Azure.PowerShell.Cmdlets.Logz.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Logz.ParameterCategory.Body)]
[Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"Request of a list vm host update operation.",
SerializedName = @"vmResourceIds",
PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Logz.Models.Api20201001Preview.IVMResources) })]
public Microsoft.Azure.PowerShell.Cmdlets.Logz.Models.Api20201001Preview.IVMResources[] VMResource { get => Body.VMResourceId ?? null /* arrayOf */; set => Body.VMResourceId = value; }
/// <summary>
/// <c>overrideOnDefault</c> will be called before the regular onDefault has been processed, allowing customization of what
/// happens on that response. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="responseMessage">the raw response message as an global::System.Net.Http.HttpResponseMessage.</param>
/// <param name="response">the body result as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Logz.Models.Api20.IErrorResponse"
/// /> from the remote call</param>
/// <param name="returnNow">/// Determines if the rest of the onDefault method should be processed, or if the method should
/// return immediately (set to true to skip further processing )</param>
partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.Logz.Models.Api20.IErrorResponse> response, ref global::System.Threading.Tasks.Task<bool> returnNow);
/// <summary>
/// <c>overrideOnOk</c> will be called before the regular onOk has been processed, allowing customization of what happens
/// on that response. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="responseMessage">the raw response message as an global::System.Net.Http.HttpResponseMessage.</param>
/// <param name="response">the body result as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Logz.Models.Api20201001Preview.IVMResourcesListResponse"
/// /> from the remote call</param>
/// <param name="returnNow">/// Determines if the rest of the onOk method should be processed, or if the method should return
/// immediately (set to true to skip further processing )</param>
partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.Logz.Models.Api20201001Preview.IVMResourcesListResponse> response, ref global::System.Threading.Tasks.Task<bool> returnNow);
/// <summary>
/// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet)
/// </summary>
protected override void BeginProcessing()
{
Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials);
if (Break)
{
Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.AttachDebugger.Break();
}
((Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; }
}
/// <summary>Performs clean-up after the command execution</summary>
protected override void EndProcessing()
{
((Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; }
}
/// <summary>Handles/Dispatches events during the call to the REST service.</summary>
/// <param name="id">The message id</param>
/// <param name="token">The message cancellation token. When this call is cancelled, this should be <c>true</c></param>
/// <param name="messageData">Detailed message data for the message event.</param>
/// <returns>
/// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the message is completed.
/// </returns>
async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.IEventListener.Signal(string id, global::System.Threading.CancellationToken token, global::System.Func<Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.EventData> messageData)
{
using( NoSynchronizationContext )
{
if (token.IsCancellationRequested)
{
return ;
}
switch ( id )
{
case Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.Events.Verbose:
{
WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}");
return ;
}
case Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.Events.Warning:
{
WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}");
return ;
}
case Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.Events.Information:
{
var data = messageData();
WriteInformation(data.Message, new string[]{});
return ;
}
case Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.Events.Debug:
{
WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}");
return ;
}
case Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.Events.Error:
{
WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) );
return ;
}
}
await Microsoft.Azure.PowerShell.Cmdlets.Logz.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.EventData ), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null );
if (token.IsCancellationRequested)
{
return ;
}
WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}");
}
}
/// <summary>Performs execution of the command.</summary>
protected override void ProcessRecord()
{
((Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; }
__processRecordId = System.Guid.NewGuid().ToString();
try
{
// work
if (ShouldProcess($"Call remote 'MonitorListVMHostUpdate' operation"))
{
using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.IEventListener)this).Token) )
{
asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.IEventListener)this).Token);
}
}
}
catch (global::System.AggregateException aggregateException)
{
// unroll the inner exceptions to get the root cause
foreach( var innerException in aggregateException.Flatten().InnerExceptions )
{
((Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; }
// Write exception out to error channel.
WriteError( new global::System.Management.Automation.ErrorRecord(innerException,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) );
}
}
catch (global::System.Exception exception) when ((exception as System.Management.Automation.PipelineStoppedException)== null || (exception as System.Management.Automation.PipelineStoppedException).InnerException != null)
{
((Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; }
// Write exception out to error channel.
WriteError( new global::System.Management.Automation.ErrorRecord(exception,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) );
}
finally
{
((Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.Events.CmdletProcessRecordEnd).Wait();
}
}
/// <summary>Performs execution of the command, working asynchronously if required.</summary>
/// <returns>
/// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the method is completed.
/// </returns>
protected async global::System.Threading.Tasks.Task ProcessRecordAsync()
{
using( NoSynchronizationContext )
{
await ((Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; }
await ((Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; }
Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Logz.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName);
if (null != HttpPipelinePrepend)
{
Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend);
}
if (null != HttpPipelineAppend)
{
Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend);
}
// get the client instance
try
{
await ((Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; }
await this.Client.MonitorListVMHostUpdate(SubscriptionId, ResourceGroupName, Name, Body, onOk, onDefault, this, Pipeline);
await ((Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; }
}
catch (Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.UndeclaredResponseException urexception)
{
WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId,ResourceGroupName=ResourceGroupName,Name=Name,body=Body})
{
ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action }
});
}
finally
{
await ((Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.Events.CmdletProcessRecordAsyncEnd);
}
}
}
/// <summary>Interrupts currently running code within the command.</summary>
protected override void StopProcessing()
{
((Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.IEventListener)this).Cancel();
base.StopProcessing();
}
/// <summary>
/// Intializes a new instance of the <see cref="UpdateAzLogzMonitorVMHost_ListExpanded" /> cmdlet class.
/// </summary>
public UpdateAzLogzMonitorVMHost_ListExpanded()
{
}
/// <summary>
/// a delegate that is called when the remote service returns default (any response code not handled elsewhere).
/// </summary>
/// <param name="responseMessage">the raw response message as an global::System.Net.Http.HttpResponseMessage.</param>
/// <param name="response">the body result as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Logz.Models.Api20.IErrorResponse"
/// /> from the remote call</param>
/// <returns>
/// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the method is completed.
/// </returns>
private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.Logz.Models.Api20.IErrorResponse> response)
{
using( NoSynchronizationContext )
{
var _returnNow = global::System.Threading.Tasks.Task<bool>.FromResult(false);
overrideOnDefault(responseMessage, response, ref _returnNow);
// if overrideOnDefault has returned true, then return right away.
if ((null != _returnNow && await _returnNow))
{
return ;
}
// Error Response : default
var code = (await response)?.Code;
var message = (await response)?.Message;
if ((null == code || null == message))
{
// Unrecognized Response. Create an error record based on what we have.
var ex = new Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.RestException<Microsoft.Azure.PowerShell.Cmdlets.Logz.Models.Api20.IErrorResponse>(responseMessage, await response);
WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, Name=Name, body=Body })
{
ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action }
});
}
else
{
WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, Name=Name, body=Body })
{
ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty }
});
}
}
}
/// <summary>a delegate that is called when the remote service returns 200 (OK).</summary>
/// <param name="responseMessage">the raw response message as an global::System.Net.Http.HttpResponseMessage.</param>
/// <param name="response">the body result as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Logz.Models.Api20201001Preview.IVMResourcesListResponse"
/// /> from the remote call</param>
/// <returns>
/// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the method is completed.
/// </returns>
private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.Logz.Models.Api20201001Preview.IVMResourcesListResponse> response)
{
using( NoSynchronizationContext )
{
var _returnNow = global::System.Threading.Tasks.Task<bool>.FromResult(false);
overrideOnOk(responseMessage, response, ref _returnNow);
// if overrideOnOk has returned true, then return right away.
if ((null != _returnNow && await _returnNow))
{
return ;
}
// onOk - response for 200 / application/json
// response should be returning an array of some kind. +Pageable
// pageable / value / nextLink
var result = await response;
WriteObject(result.Value,true);
if (result.NextLink != null)
{
if (responseMessage.RequestMessage is System.Net.Http.HttpRequestMessage requestMessage )
{
requestMessage = requestMessage.Clone(new global::System.Uri( result.NextLink ),Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.Method.Get );
await ((Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.Events.FollowingNextLink); if( ((Microsoft.Azure.PowerShell.Cmdlets.Logz.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; }
await this.Client.MonitorListVMHostUpdate_Call(requestMessage, onOk, onDefault, this, Pipeline);
}
}
}
}
}
} | 73.106335 | 447 | 0.66874 | [
"MIT"
] | Agazoth/azure-powershell | src/Logz/generated/cmdlets/UpdateAzLogzMonitorVMHost_ListExpanded.cs | 31,872 | C# |
global using BasicGameFrameworkLibrary.BasicGameDataClasses;
global using CommonBasicLibraries.AdvancedGeneralFunctionsAndProcesses.BasicExtensions;
global using CommonBasicLibraries.BasicDataSettingsAndProcesses;
global using static CommonBasicLibraries.BasicDataSettingsAndProcesses.BasicDataFunctions;
global using CommonBasicLibraries.CollectionClasses;
global using fs = CommonBasicLibraries.AdvancedGeneralFunctionsAndProcesses.JsonSerializers.FileHelpers;
global using js = CommonBasicLibraries.AdvancedGeneralFunctionsAndProcesses.JsonSerializers.SystemTextJsonStrings; //just in case i need those 2.
global using BasicGameFrameworkLibrary.CommonInterfaces;
global using BingoCP.Data;
global using BasicGameFrameworkLibrary.BasicEventModels;
global using BasicGameFrameworkLibrary.DIContainers;
global using MessengingHelpers;
global using CommonBasicLibraries.BasicUIProcesses;
global using BasicGameFrameworkLibrary.CommandClasses;
global using BasicGameFrameworkLibrary.ViewModels;
global using BasicGameFrameworkLibrary.ViewModelInterfaces;
global using MVVMFramework.ViewModels;
global using BingoCP.Logic;
global using BasicGameFrameworkLibrary.MiscProcesses;
global using CommonBasicLibraries.AdvancedGeneralFunctionsAndProcesses.MapHelpers;
global using BasicGameFrameworkLibrary.MultiplayerClasses.BasicPlayerClasses;
global using BasicGameFrameworkLibrary.MultiplayerClasses.SavedGameClasses;
global using BasicGameFrameworkLibrary.MultiplayerClasses.GameContainers;
global using BasicGameFrameworkLibrary.TestUtilities;
global using CommonBasicLibraries.AdvancedGeneralFunctionsAndProcesses.RandomGenerator;
global using BasicGameFrameworkLibrary.MultiplayerClasses.MainViewModels;
global using BasicGameFrameworkLibrary.GameBoardCollections;
global using System.Collections;
global using BasicGameFrameworkLibrary.MultiplayerClasses.BasicGameClasses;
global using BasicGameFrameworkLibrary.MultiplayerClasses.InterfaceMessages;
global using System.Timers;
global using System.Collections.Generic;
global using System.Linq;
global using System;
global using System.Threading.Tasks;
global using BasicGameFrameworkLibrary.SourceGeneratorHelperClasses; | 60.25 | 145 | 0.903181 | [
"MIT"
] | musictopia2/GamingPackXV3 | CP/Games/BingoCP/GlobalUsings.cs | 2,169 | C# |
using AutoMapper;
namespace Abp.AutoMapper
{
public static class AutoMapExtensions
{
/// <summary>
/// Converts an object to another using AutoMapper library.
/// There must be a mapping between objects before calling this method.
/// </summary>
/// <typeparam name="TDestination">Type of the destination object</typeparam>
/// <param name="source">Source object</param>
public static TDestination MapTo<TDestination>(this object source)
{
return Mapper.Map<TDestination>(source);
}
}
}
| 30.789474 | 85 | 0.632479 | [
"MIT"
] | mona6767/aspnetboilerplate | src/Abp.AutoMapper/AutoMapper/AutoMapExtensions.cs | 587 | C# |
using CharacterGen.CharacterClasses;
using CharacterGen.Domain.Tables;
using CharacterGen.Feats;
using NUnit.Framework;
namespace CharacterGen.Tests.Integration.Tables.Feats.Data.CharacterClasses.Domains
{
[TestFixture]
public class EvilFeatDataTests : CharacterClassFeatDataTests
{
protected override string tableName
{
get { return string.Format(TableNameConstants.Formattable.Collection.CLASSFeatData, CharacterClassConstants.Domains.Evil); }
}
[Test]
public override void CollectionNames()
{
var names = new[] { FeatConstants.CastSpellBonus };
AssertCollectionNames(names);
}
[TestCase(FeatConstants.CastSpellBonus,
FeatConstants.CastSpellBonus,
CharacterClassConstants.Domains.Evil,
0,
"",
"",
1,
0,
0,
"", true)]
public override void ClassFeatData(string name, string feat, string focusType, int frequencyQuantity, string frequencyQuantityStat, string frequencyTimePeriod, int minimumLevel, int maximumLevel, int strength, string sizeRequirement, bool allowFocusOfAll)
{
base.ClassFeatData(name, feat, focusType, frequencyQuantity, frequencyQuantityStat, frequencyTimePeriod, minimumLevel, maximumLevel, strength, sizeRequirement, allowFocusOfAll);
}
}
}
| 36.538462 | 263 | 0.673684 | [
"MIT"
] | DnDGen/CharacterGen | CharacterGen.Tests.Integration.Tables/Feats/Data/CharacterClasses/Domains/EvilFeatDataTests.cs | 1,427 | C# |
//
// NSActionCell.cs: Support for the NSActionCell class
//
// Author:
// Michael Hutchinson (mhutchinson@novell.com)
//
// Copyright 2010, Novell, Inc.
//
// 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.
//
#if !__MACCATALYST__
using System;
using ObjCRuntime;
using Foundation;
namespace AppKit {
public partial class NSActionCell {
NSObject target;
Selector action;
public event EventHandler Activated {
add {
target = ActionDispatcher.SetupAction (Target, value);
action = ActionDispatcher.Action;
MarkDirty ();
Target = target;
Action = action;
}
remove {
ActionDispatcher.RemoveAction (Target, value);
target = null;
action = null;
MarkDirty ();
}
}
}
}
#endif // !__MACCATALYST__
| 29.229508 | 73 | 0.729669 | [
"BSD-3-Clause"
] | NormanChiflen/xamarin-all-IOS | src/AppKit/NSActionCell.cs | 1,783 | C# |
/* _BEGIN_TEMPLATE_
{
"id": "TRL_541t",
"name": [
"堕落之血",
"Corrupted Blood"
],
"text": [
"<b>抽到时施放</b>\n受到3点伤害。在你抽牌后,将此牌的两张复制洗入你的牌库。",
"<b>Casts When Drawn</b>\nTake 3 damage. After you draw, shuffle two copies of this into your deck."
],
"cardClass": "NEUTRAL",
"type": "SPELL",
"cost": 1,
"rarity": null,
"set": "TROLL",
"collectible": null,
"dbfId": 50455
}
_END_TEMPLATE_ */
namespace HREngine.Bots
{
class Sim_TRL_541t : SimTemplate //* 堕落之血 Corrupted Blood
{
//<b>Casts When Drawn</b>Take 3 damage. After you draw, shuffle two copies of this into your deck.
//<b>抽到时施放</b>受到3点伤害。在你抽牌后,将此牌的两张复制洗入你的牌库。
}
} | 23.413793 | 106 | 0.615611 | [
"MIT"
] | chi-rei-den/Silverfish | cards/TROLL/TRL/Sim_TRL_541t.cs | 823 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Payment.WebAPI.Settings
{
public interface IMongoDbSettings
{
string DatabaseName { get; set; }
string ConnectionString { get; set; }
}
}
| 19.642857 | 45 | 0.701818 | [
"MIT"
] | ahmtsenlik/ApartmentManagementSystem | ApartmentManagement/Payment.WebAPI/Settings/IMongoDbSettings.cs | 277 | C# |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Soccer.BL;
using Soccer.Repository;
using System;
using System.Collections.Generic;
using System.Text;
namespace Soccer.BLTest
{
[TestClass]
public class PlayerRepositoryTest
{
[TestMethod]
public void RetrieveValid()
{
//-- Arrange
var playerRepository = new PlayerRepository();
var expected = new Player(1)
{
FirstName = "Bernd",
MiddleName = "",
LastName = "Leno",
Position = "Goalkeeper"
};
//-- Act
var actual = playerRepository.Retrieve(1);
//-- Assert
Assert.AreEqual(expected.PlayerId, actual.PlayerId);
Assert.AreEqual(expected.FirstName, actual.FirstName);
Assert.AreEqual(expected.MiddleName, actual.MiddleName);
Assert.AreEqual(expected.LastName, actual.LastName);
Assert.AreEqual(expected.Position, actual.Position);
}
}
}
| 27.358974 | 68 | 0.579194 | [
"MIT"
] | peterriley/Sports | Sports/Soccer.BLTest/PlayerRepositoryTest.cs | 1,069 | C# |
namespace SwapChainRenderingDemo
{
using System;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using DemoCore;
using HelixToolkit.Wpf.SharpDX;
using SharpDX;
using Media3D = System.Windows.Media.Media3D;
using Point3D = System.Windows.Media.Media3D.Point3D;
using Vector3D = System.Windows.Media.Media3D.Vector3D;
using Transform3D = System.Windows.Media.Media3D.Transform3D;
using Color = System.Windows.Media.Color;
using Plane = SharpDX.Plane;
using Vector3 = SharpDX.Vector3;
using Colors = System.Windows.Media.Colors;
using Color4 = SharpDX.Color4;
using TranslateTransform3D = System.Windows.Media.Media3D.TranslateTransform3D;
using HelixToolkit.Wpf;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using SharpDX.Direct3D11;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Threading;
using HelixToolkit.Wpf.SharpDX.Model;
public class MainViewModel : BaseViewModel
{
public string Name { get; set; }
public MainViewModel ViewModel { get { return this; } }
public ObservableElement3DCollection LanderModels { get; private set; } = new ObservableElement3DCollection();
public MeshGeometry3D Floor { get; private set; }
public MeshGeometry3D Sphere { get; private set; }
public LineGeometry3D CubeEdges { get; private set; }
public Transform3D ModelTransform { get; private set; }
public Transform3D FloorTransform { get; private set; }
public Transform3D Light1Transform { get; private set; }
public Transform3D Light2Transform { get; private set; }
public Transform3D Light3Transform { get; private set; }
public Transform3D Light4Transform { get; private set; }
public Transform3D Light1DirectionTransform { get; private set; }
public Transform3D Light4DirectionTransform { get; private set; }
public PhongMaterial ModelMaterial { get; set; }
public PhongMaterial FloorMaterial { get; set; }
public PhongMaterial LightModelMaterial { get; set; }
public Vector3D Light1Direction { get; set; }
public Vector3D Light4Direction { get; set; }
public Vector3D LightDirection4 { get; set; }
public Color Light1Color { get; set; }
public Color Light2Color { get; set; }
public Color Light3Color { get; set; }
public Color Light4Color { get; set; }
public Color AmbientLightColor { get; set; }
public Vector3D Light2Attenuation { get; set; }
public Vector3D Light3Attenuation { get; set; }
public Vector3D Light4Attenuation { get; set; }
public bool RenderLight1 { get; set; }
public bool RenderLight2 { get; set; }
public bool RenderLight3 { get; set; }
public bool RenderLight4 { get; set; }
public bool RenderDiffuseMap { set; get; } = true;
public bool RenderNormalMap { set; get; } = true;
private string selectedDiffuseTexture = @"TextureCheckerboard2.jpg";
public string SelectedDiffuseTexture
{
get
{
return selectedDiffuseTexture;
}
}
private string selectedNormalTexture = @"TextureCheckerboard2_dot3.jpg";
public string SelectedNormalTexture
{
get
{
return selectedNormalTexture;
}
}
public System.Windows.Media.Color DiffuseColor
{
set
{
FloorMaterial.DiffuseColor = ModelMaterial.DiffuseColor = value.ToColor4();
}
get
{
return ModelMaterial.DiffuseColor.ToColor();
}
}
public System.Windows.Media.Color ReflectiveColor
{
set
{
FloorMaterial.ReflectiveColor = ModelMaterial.ReflectiveColor = value.ToColor4();
}
get
{
return ModelMaterial.ReflectiveColor.ToColor();
}
}
public System.Windows.Media.Color EmissiveColor
{
set
{
FloorMaterial.EmissiveColor = ModelMaterial.EmissiveColor = value.ToColor4();
}
get
{
return ModelMaterial.EmissiveColor.ToColor();
}
}
public Camera Camera2 { get; } = new PerspectiveCamera { Position = new Point3D(8, 9, 7), LookDirection = new Vector3D(-5, -12, -5), UpDirection = new Vector3D(0, 1, 0) };
public Camera Camera3 { get; } = new PerspectiveCamera { Position = new Point3D(8, 9, 7), LookDirection = new Vector3D(-5, -12, -5), UpDirection = new Vector3D(0, 1, 0) };
public Camera Camera4 { get; } = new PerspectiveCamera { Position = new Point3D(8, 9, 7), LookDirection = new Vector3D(-5, -12, -5), UpDirection = new Vector3D(0, 1, 0) };
public FillMode FillMode { set; get; } = FillMode.Solid;
public int NumberOfTriangles { set; get; } = 0;
public int NumberOfVertices { set; get; } = 0;
private bool showWireframe = false;
public bool ShowWireframe
{
set
{
if (SetValue(ref showWireframe, value))
{
FillMode = value ? FillMode.Wireframe : FillMode.Solid;
}
}
get
{
return showWireframe;
}
}
public LineGeometry3D LineGeo { set; get; }
private SynchronizationContext context = SynchronizationContext.Current;
public MainViewModel()
{
EffectsManager = new DefaultEffectsManager();
// ----------------------------------------------
// titles
this.Title = "SwapChain Top Surface Rendering Demo";
this.SubTitle = "WPF & SharpDX";
// ----------------------------------------------
// camera setup
this.Camera = new PerspectiveCamera { Position = new Point3D(100,100,100), LookDirection = new Vector3D(-100,-100,-100), UpDirection = new Vector3D(0, 1, 0) };
// ----------------------------------------------
// setup scene
this.AmbientLightColor = Colors.DimGray;
this.Light1Color = Colors.White;
this.Light2Color = Colors.Red;
this.Light3Color = Colors.LightYellow;
this.Light4Color = Colors.LightBlue;
this.Light2Attenuation = new Vector3D(0.1f, 0.05f, 0.010f);
this.Light3Attenuation = new Vector3D(0.1f, 0.01f, 0.005f);
this.Light4Attenuation = new Vector3D(0.1f, 0.02f, 0.0f);
this.Light1Direction = new Vector3D(0, -10, -10);
this.Light1Transform = new TranslateTransform3D(-Light1Direction);
this.Light1DirectionTransform = CreateAnimatedTransform2(-Light1Direction, new Vector3D(0, 1, -1), 36);
this.Light2Transform = CreateAnimatedTransform1(new Vector3D(-100, 50, 0), new Vector3D(0, 0, 1), 3);
this.Light3Transform = CreateAnimatedTransform1(new Vector3D(0, 50, 100), new Vector3D(0, 1, 0), 5);
this.Light4Direction = new Vector3D(0, -100, 0);
this.Light4Transform = new TranslateTransform3D(-Light4Direction);
this.Light4DirectionTransform = CreateAnimatedTransform2(-Light4Direction, new Vector3D(1, 0, 0), 48);
// ----------------------------------------------
// light model3d
var sphere = new MeshBuilder();
sphere.AddSphere(new Vector3(0, 0, 0), 4);
Sphere = sphere.ToMeshGeometry3D();
this.LightModelMaterial = new PhongMaterial
{
AmbientColor = Colors.Gray.ToColor4(),
DiffuseColor = Colors.Gray.ToColor4(),
EmissiveColor = Colors.Yellow.ToColor4(),
SpecularColor = Colors.Black.ToColor4(),
};
Task.Run(() => { LoadFloor(); });
Task.Run(() => { LoadLander(); });
var transGroup = new Media3D.Transform3DGroup();
transGroup.Children.Add(new Media3D.ScaleTransform3D(0.04, 0.04, 0.04));
var rotateAnimation = new Rotation3DAnimation
{
RepeatBehavior = RepeatBehavior.Forever,
By = new Media3D.AxisAngleRotation3D(new Vector3D(0, 1, 0), 90),
Duration = TimeSpan.FromSeconds(4),
IsCumulative = true,
};
var rotateTransform = new Media3D.RotateTransform3D();
transGroup.Children.Add(rotateTransform);
rotateTransform.BeginAnimation(Media3D.RotateTransform3D.RotationProperty, rotateAnimation);
transGroup.Children.Add(new Media3D.TranslateTransform3D(0, 60, 0));
ModelTransform = transGroup;
}
private void LoadLander()
{
foreach(var obj in Load3ds("Car.3ds"))
{
obj.Geometry.UpdateOctree();
Task.Delay(10).Wait();
context.Post((o) => {
var model = new MeshGeometryModel3D() { Geometry = obj.Geometry };
if(obj.Material is PhongMaterialCore p)
{
model.Material = p;
}
LanderModels.Add(model);
NumberOfTriangles += obj.Geometry.Indices.Count/3;
NumberOfVertices += obj.Geometry.Positions.Count;
OnPropertyChanged(nameof(NumberOfTriangles));
OnPropertyChanged(nameof(NumberOfVertices));
}, null);
}
}
private void LoadFloor()
{
var models = Load3ds("wall12.obj").Select(x => x.Geometry as MeshGeometry3D).ToArray();
foreach(var model in models)
{
model.UpdateOctree();
}
context.Post((o) => {
Floor = models[0];
this.FloorTransform = new Media3D.TranslateTransform3D(0, 0, 0);
this.FloorMaterial = new PhongMaterial
{
AmbientColor = Colors.Gray.ToColor4(),
DiffuseColor = new Color4(0.75f, 0.75f, 0.75f, 1.0f),
SpecularColor = Colors.White.ToColor4(),
SpecularShininess = 100f
};
NumberOfTriangles += Floor.Indices.Count / 3;
NumberOfVertices += Floor.Positions.Count;
OnPropertyChanged(nameof(NumberOfTriangles));
OnPropertyChanged(nameof(NumberOfVertices));
OnPropertyChanged(nameof(Floor));
OnPropertyChanged(nameof(FloorMaterial));
}, null);
}
public List<Object3D> Load3ds(string path)
{
if (path.EndsWith(".obj", StringComparison.CurrentCultureIgnoreCase))
{
var reader = new ObjReader();
var list = reader.Read(path);
return list;
}
else if(path.EndsWith(".3ds", StringComparison.CurrentCultureIgnoreCase))
{
var reader = new StudioReader();
var list = reader.Read(path);
return list;
}
else
{
return new List<Object3D>();
}
}
private Media3D.Transform3D CreateAnimatedTransform1(Vector3D translate, Vector3D axis, double speed = 4)
{
var lightTrafo = new Media3D.Transform3DGroup();
lightTrafo.Children.Add(new Media3D.TranslateTransform3D(translate));
var rotateAnimation = new Rotation3DAnimation
{
RepeatBehavior = RepeatBehavior.Forever,
By = new Media3D.AxisAngleRotation3D(axis, 90),
Duration = TimeSpan.FromSeconds(speed / 4),
IsCumulative = true,
};
var rotateTransform = new Media3D.RotateTransform3D();
rotateTransform.BeginAnimation(Media3D.RotateTransform3D.RotationProperty, rotateAnimation);
lightTrafo.Children.Add(rotateTransform);
return lightTrafo;
}
private Media3D.Transform3D CreateAnimatedTransform2(Vector3D translate, Vector3D axis, double speed = 4)
{
var lightTrafo = new Media3D.Transform3DGroup();
lightTrafo.Children.Add(new Media3D.TranslateTransform3D(translate));
var rotateAnimation = new Rotation3DAnimation
{
RepeatBehavior = RepeatBehavior.Forever,
//By = new Media3D.AxisAngleRotation3D(axis, 180),
From = new Media3D.AxisAngleRotation3D(axis, 135),
To = new Media3D.AxisAngleRotation3D(axis, 225),
AutoReverse = true,
Duration = TimeSpan.FromSeconds(speed / 4),
//IsCumulative = true,
};
var rotateTransform = new Media3D.RotateTransform3D();
rotateTransform.BeginAnimation(Media3D.RotateTransform3D.RotationProperty, rotateAnimation);
lightTrafo.Children.Add(rotateTransform);
return lightTrafo;
}
public void OnMouseLeftButtonDownHandler(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
var viewport = sender as Viewport3DX;
if (viewport == null) { return; }
var point = e.GetPosition(viewport);
var watch = Stopwatch.StartNew();
var hitTests = viewport.FindHits(point);
watch.Stop();
Console.WriteLine("Hit test time =" + watch.ElapsedMilliseconds);
if (hitTests.Count > 0)
{
var lineBuilder = new LineBuilder();
foreach(var hit in hitTests)
{
lineBuilder.AddLine(hit.PointHit, (hit.PointHit + hit.NormalAtHit * 10));
}
LineGeo = lineBuilder.ToLineGeometry3D();
}
}
}
} | 40.651558 | 179 | 0.569059 | [
"MIT"
] | beppemarazzi/helix-toolkit | Source/Examples/WPF.SharpDX/SwapChainRenderingDemo/MainViewModel.cs | 14,352 | C# |
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
namespace IdentityServer.IDP.Device
{
public class DeviceAuthorizationInputModel : ConsentInputModel
{
public string UserCode { get; set; }
}
} | 31 | 107 | 0.733138 | [
"MIT"
] | matheusgabg/SecuringAspNetCore3WithOAuth2AndOIDC | Starter files/src/IdentityServer.IDP/Quickstart/Device/DeviceAuthorizationInputModel.cs | 341 | C# |
// This file was automatically generated and may be regenerated at any
// time. To ensure any changes are retained, modify the tool with any segment/component/group/field name
// or type changes.
namespace Machete.HL7Schema.V26
{
using HL7;
/// <summary>
/// ADT_A16_PROCEDURE (Group) -
/// </summary>
public interface ADT_A16_PROCEDURE :
HL7V26Layout
{
/// <summary>
/// PR1
/// </summary>
Segment<PR1> PR1 { get; }
/// <summary>
/// ROL
/// </summary>
SegmentList<ROL> ROL { get; }
}
} | 24.666667 | 105 | 0.572635 | [
"Apache-2.0"
] | AreebaAroosh/Machete | src/Machete.HL7Schema/Generated/V26/Groups/ADT_A16_PROCEDURE.cs | 592 | C# |
using System;
using System.Collections.Generic;
namespace Rinjani
{
public interface IQuoteAggregator
{
void HpxAggregate();
void ZbAggregate();
IList<Quote> GetHpxQuote();
IList<Quote> GetZbQuote();
}
} | 19.153846 | 37 | 0.638554 | [
"MIT"
] | myblock001/RinJani | Rinjani/Interface/IQuoteAggregator.cs | 251 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MyMedicalGuide.Data.Repositories;
namespace MyMedicalGuide.Services
{
using Data.Models;
using MyMedicalGuide.Services.Contracts;
public class DoctorsService : IDoctorsService
{
private readonly IRepository<Doctor, string> doctorsrepo;
public DoctorsService(IRepository<Doctor, string> doctorsrepo)
{
this.doctorsrepo = doctorsrepo;
}
public void Add(Doctor doctor)
{
this.doctorsrepo.Add(doctor);
this.doctorsrepo.SaveChanges();
}
public void Delete(Doctor doctor)
{
this.doctorsrepo.Delete(doctor);
this.doctorsrepo.SaveChanges();
}
public IQueryable<Doctor> GetAll()
{
return this.doctorsrepo.All();
}
public void Update(Doctor doctor)
{
this.doctorsrepo.Update(doctor);
this.doctorsrepo.SaveChanges();
}
public void Dispose()
{
this.doctorsrepo.Dispose();
}
public IQueryable<Doctor> GetAllDoctorsFromDepartmentHospital(int hospitalId, int departmentId)
{
return this.doctorsrepo
.All()
.Where(x => x.HospitalId == hospitalId && x.DepartmentId == departmentId);
}
public IQueryable<Doctor> GetDoctors(string filter)
{
string[] fullName = filter.Split(' ');
string firstName = fullName[0];
string lastName = null;
if (fullName.Length > 1)
{
lastName = fullName[1];
}
return this.doctorsrepo
.All()
.Where(x => (x.User.FirstName.Contains(firstName) &&
(lastName != null ? x.User.LastName.Contains(lastName) : true)));
}
public Doctor GetById(string id)
{
return this.doctorsrepo.GetById(id);
}
public void AddPatient(string doctorId, Patient patient)
{
this.doctorsrepo.GetById(doctorId).Patients.Add(patient);
this.doctorsrepo.SaveChanges();
}
}
}
| 27.011765 | 103 | 0.566202 | [
"MIT"
] | aleksandra992/My-Medical-Guide-ASP.NET-MVC | MyMedicalGuide/Services/MyMedicalGuide.Services/DoctorsService.cs | 2,298 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Spark.Wpf.Common.ViewModels.Matrix
{
internal class RowHeader<TItem>
{
public RowHeader(string caption, Func<TItem, object> getter, bool addAfterColumnHeaders)
{
this.Getter = getter;
this.Caption = caption;
this.AddAfterColumnHeaders = addAfterColumnHeaders;
}
public Func<TItem, object> Getter { get; }
public string Caption { get; }
public bool AddAfterColumnHeaders { get; }
}
}
| 25.375 | 96 | 0.658456 | [
"MIT"
] | jackobo/jackobs-code | DeveloperTool/Dependencies/Wpf.Common/Wpf.Common/ViewModels/Matrix/RowHeader.cs | 611 | 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.WafRegional.Outputs
{
[OutputType]
public sealed class RuleGroupActivatedRuleAction
{
/// <summary>
/// The rule type, either `REGULAR`, `RATE_BASED`, or `GROUP`. Defaults to `REGULAR`.
/// </summary>
public readonly string Type;
[OutputConstructor]
private RuleGroupActivatedRuleAction(string type)
{
Type = type;
}
}
}
| 26.821429 | 93 | 0.65779 | [
"ECL-2.0",
"Apache-2.0"
] | JakeGinnivan/pulumi-aws | sdk/dotnet/WafRegional/Outputs/RuleGroupActivatedRuleAction.cs | 751 | 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("BookShop")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("BookShop")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("b067c923-e612-4856-b11c-9fca3447ba3b")]
// 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.540541 | 84 | 0.743701 | [
"MIT"
] | KristiyanVasilev/OOP-Basics | Inheritance/BookShop/Properties/AssemblyInfo.cs | 1,392 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class maptarget : MonoBehaviour
{
public static int gogo;
// Start is called before the first frame update
void Start()
{
switch (gogo)
{
case 1:
this.transform.position = new Vector3(135, 0, -57);
break;
case 2:
this.transform.position = new Vector3(96, 0, -9);
break;
case 3:
this.transform.position = new Vector3(84, 0, -104);
break;
case 4:
this.transform.position = new Vector3(186, 0, -10);
break;
case 5:
this.transform.position = new Vector3(179, 0, -60);
break;
case 6:
this.transform.position = new Vector3(192, 0, -60);
break;
case 7:
this.transform.position = new Vector3(186, 0, -145);
break;
case 8:
this.transform.position = new Vector3(102, 0, -152);
break;
}
}
// Update is called once per frame
void Update()
{
}
}
| 27.425532 | 69 | 0.456168 | [
"MIT"
] | Taesuuu/Maps2021 | Assets/Script/maptarget.cs | 1,289 | C# |
using System;
using System.Collections.Generic;
using System.Threading;
namespace GitHub.Unity.Git.Tasks
{
public class GitConfigListTask : ProcessTaskWithListOutput<KeyValuePair<string, string>>
{
private const string TaskName = "git config list";
private readonly string arguments;
public GitConfigListTask(GitConfigSource configSource, CancellationToken token, BaseOutputListProcessor<KeyValuePair<string, string>> processor = null)
: base(token, processor ?? new ConfigOutputProcessor())
{
Name = TaskName;
var source = "";
if (configSource != GitConfigSource.NonSpecified)
{
source = "--";
source += configSource == GitConfigSource.Local
? "local"
: (configSource == GitConfigSource.User
? "system"
: "global");
}
arguments = String.Format("config {0} -l", source);
}
public override string ProcessArguments { get { return arguments; } }
public override TaskAffinity Affinity { get { return TaskAffinity.Exclusive; } }
public override string Message { get; set; } = "Reading configuration...";
}
}
| 37.823529 | 159 | 0.597201 | [
"MIT"
] | Anras573/Unity | src/GitHub.Api/Git/Tasks/GitConfigListTask.cs | 1,286 | C# |
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.Management.AlertsManagement.Models
{
using Newtonsoft.Json;
using System.Linq;
/// <summary>
/// Defines headers for ListBySubscription operation.
/// </summary>
public partial class AlertProcessingRulesListBySubscriptionHeaders
{
/// <summary>
/// Initializes a new instance of the
/// AlertProcessingRulesListBySubscriptionHeaders class.
/// </summary>
public AlertProcessingRulesListBySubscriptionHeaders()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the
/// AlertProcessingRulesListBySubscriptionHeaders class.
/// </summary>
/// <param name="xMsRequestId">Service generated Request ID.</param>
public AlertProcessingRulesListBySubscriptionHeaders(string xMsRequestId = default(string))
{
XMsRequestId = xMsRequestId;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets service generated Request ID.
/// </summary>
[JsonProperty(PropertyName = "x-ms-request-id")]
public string XMsRequestId { get; set; }
}
}
| 31.722222 | 99 | 0.6439 | [
"MIT"
] | AhmedLeithy/azure-sdk-for-net | sdk/alertsmanagement/Microsoft.Azure.Management.AlertsManagement/src/Generated/Models/AlertProcessingRulesListBySubscriptionHeaders.cs | 1,713 | C# |
#pragma checksum "D:\Code\Blazor\ConnectFourCore\ConnectFourCore\Shared\NavMenu.razor" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "b1b897abf82be056bc59965835b5f39c5907907f"
// <auto-generated/>
#pragma warning disable 1591
namespace ConnectFourCore.Shared
{
#line hidden
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components;
#nullable restore
#line 1 "D:\Code\Blazor\ConnectFourCore\ConnectFourCore\_Imports.razor"
using System.Net.Http;
#line default
#line hidden
#nullable disable
#nullable restore
#line 2 "D:\Code\Blazor\ConnectFourCore\ConnectFourCore\_Imports.razor"
using System.Net.Http.Json;
#line default
#line hidden
#nullable disable
#nullable restore
#line 3 "D:\Code\Blazor\ConnectFourCore\ConnectFourCore\_Imports.razor"
using Microsoft.AspNetCore.Components.Forms;
#line default
#line hidden
#nullable disable
#nullable restore
#line 4 "D:\Code\Blazor\ConnectFourCore\ConnectFourCore\_Imports.razor"
using Microsoft.AspNetCore.Components.Routing;
#line default
#line hidden
#nullable disable
#nullable restore
#line 5 "D:\Code\Blazor\ConnectFourCore\ConnectFourCore\_Imports.razor"
using Microsoft.AspNetCore.Components.Web;
#line default
#line hidden
#nullable disable
#nullable restore
#line 6 "D:\Code\Blazor\ConnectFourCore\ConnectFourCore\_Imports.razor"
using Microsoft.AspNetCore.Components.Web.Virtualization;
#line default
#line hidden
#nullable disable
#nullable restore
#line 7 "D:\Code\Blazor\ConnectFourCore\ConnectFourCore\_Imports.razor"
using Microsoft.AspNetCore.Components.WebAssembly.Http;
#line default
#line hidden
#nullable disable
#nullable restore
#line 8 "D:\Code\Blazor\ConnectFourCore\ConnectFourCore\_Imports.razor"
using Microsoft.JSInterop;
#line default
#line hidden
#nullable disable
#nullable restore
#line 9 "D:\Code\Blazor\ConnectFourCore\ConnectFourCore\_Imports.razor"
using ConnectFourCore;
#line default
#line hidden
#nullable disable
#nullable restore
#line 10 "D:\Code\Blazor\ConnectFourCore\ConnectFourCore\_Imports.razor"
using ConnectFourCore.Shared;
#line default
#line hidden
#nullable disable
public partial class NavMenu : Microsoft.AspNetCore.Components.ComponentBase
{
#pragma warning disable 1998
protected override void BuildRenderTree(Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder __builder)
{
__builder.OpenElement(0, "div");
__builder.AddAttribute(1, "class", "top-row pl-4 navbar navbar-dark");
__builder.AddAttribute(2, "b-33i3giyvyo");
__builder.AddMarkupContent(3, "<a class=\"navbar-brand\" href b-33i3giyvyo>ConnectFourCore</a>\r\n ");
__builder.OpenElement(4, "button");
__builder.AddAttribute(5, "class", "navbar-toggler");
__builder.AddAttribute(6, "onclick", Microsoft.AspNetCore.Components.EventCallback.Factory.Create<Microsoft.AspNetCore.Components.Web.MouseEventArgs>(this,
#nullable restore
#line 3 "D:\Code\Blazor\ConnectFourCore\ConnectFourCore\Shared\NavMenu.razor"
ToggleNavMenu
#line default
#line hidden
#nullable disable
));
__builder.AddAttribute(7, "b-33i3giyvyo");
__builder.AddMarkupContent(8, "<span class=\"navbar-toggler-icon\" b-33i3giyvyo></span>");
__builder.CloseElement();
__builder.CloseElement();
__builder.AddMarkupContent(9, "\r\n\r\n");
__builder.OpenElement(10, "div");
__builder.AddAttribute(11, "class",
#nullable restore
#line 8 "D:\Code\Blazor\ConnectFourCore\ConnectFourCore\Shared\NavMenu.razor"
NavMenuCssClass
#line default
#line hidden
#nullable disable
);
__builder.AddAttribute(12, "onclick", Microsoft.AspNetCore.Components.EventCallback.Factory.Create<Microsoft.AspNetCore.Components.Web.MouseEventArgs>(this,
#nullable restore
#line 8 "D:\Code\Blazor\ConnectFourCore\ConnectFourCore\Shared\NavMenu.razor"
ToggleNavMenu
#line default
#line hidden
#nullable disable
));
__builder.AddAttribute(13, "b-33i3giyvyo");
__builder.OpenElement(14, "ul");
__builder.AddAttribute(15, "class", "nav flex-column");
__builder.AddAttribute(16, "b-33i3giyvyo");
__builder.OpenElement(17, "li");
__builder.AddAttribute(18, "class", "nav-item px-3");
__builder.AddAttribute(19, "b-33i3giyvyo");
__builder.OpenComponent<Microsoft.AspNetCore.Components.Routing.NavLink>(20);
__builder.AddAttribute(21, "class", "nav-link");
__builder.AddAttribute(22, "href", "");
__builder.AddAttribute(23, "Match", Microsoft.AspNetCore.Components.CompilerServices.RuntimeHelpers.TypeCheck<Microsoft.AspNetCore.Components.Routing.NavLinkMatch>(
#nullable restore
#line 11 "D:\Code\Blazor\ConnectFourCore\ConnectFourCore\Shared\NavMenu.razor"
NavLinkMatch.All
#line default
#line hidden
#nullable disable
));
__builder.AddAttribute(24, "ChildContent", (Microsoft.AspNetCore.Components.RenderFragment)((__builder2) => {
__builder2.AddMarkupContent(25, "<span class=\"oi oi-home\" aria-hidden=\"true\" b-33i3giyvyo></span> Home\r\n ");
}
));
__builder.CloseComponent();
__builder.CloseElement();
__builder.AddMarkupContent(26, "\r\n ");
__builder.OpenElement(27, "li");
__builder.AddAttribute(28, "class", "nav-item px-3");
__builder.AddAttribute(29, "b-33i3giyvyo");
__builder.OpenComponent<Microsoft.AspNetCore.Components.Routing.NavLink>(30);
__builder.AddAttribute(31, "class", "nav-link");
__builder.AddAttribute(32, "href", "counter");
__builder.AddAttribute(33, "ChildContent", (Microsoft.AspNetCore.Components.RenderFragment)((__builder2) => {
__builder2.AddMarkupContent(34, "<span class=\"oi oi-plus\" aria-hidden=\"true\" b-33i3giyvyo></span> Counter\r\n ");
}
));
__builder.CloseComponent();
__builder.CloseElement();
__builder.AddMarkupContent(35, "\r\n ");
__builder.OpenElement(36, "li");
__builder.AddAttribute(37, "class", "nav-item px-3");
__builder.AddAttribute(38, "b-33i3giyvyo");
__builder.OpenComponent<Microsoft.AspNetCore.Components.Routing.NavLink>(39);
__builder.AddAttribute(40, "class", "nav-link");
__builder.AddAttribute(41, "href", "fetchdata");
__builder.AddAttribute(42, "ChildContent", (Microsoft.AspNetCore.Components.RenderFragment)((__builder2) => {
__builder2.AddMarkupContent(43, "<span class=\"oi oi-list-rich\" aria-hidden=\"true\" b-33i3giyvyo></span> Fetch data\r\n ");
}
));
__builder.CloseComponent();
__builder.CloseElement();
__builder.CloseElement();
__builder.CloseElement();
}
#pragma warning restore 1998
#nullable restore
#line 28 "D:\Code\Blazor\ConnectFourCore\ConnectFourCore\Shared\NavMenu.razor"
private bool collapseNavMenu = true;
private string NavMenuCssClass => collapseNavMenu ? "collapse" : null;
private void ToggleNavMenu()
{
collapseNavMenu = !collapseNavMenu;
}
#line default
#line hidden
#nullable disable
}
}
#pragma warning restore 1591
| 38.698492 | 176 | 0.679912 | [
"MIT"
] | jkjaervik/ConnectFour | ConnectFourCore/obj/Debug/net5.0/Razor/Shared/NavMenu.razor.g.cs | 7,701 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.