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 System.ComponentModel;
using System.Linq;
using System.Reactive.Linq;
namespace Bonsai.ONIX
{
using HeartbeatDataFrame = U16DataFrame;
[ONIXDeviceID(ONIXDevices.ID.Heartbeat)]
[Description("Heartbeat device that periodically produces samples containing only a clock counter.")]
public class HeartbeatDevice : ONIFrameReader<HeartbeatDataFrame, ushort>
{
private enum Register
{
ENABLE = 0, // Enable the heartbeat
CLK_DIV = 1, // Heartbeat clock divider ratio. Default results in 10 Hz heartbeat. Values less than CLK_HZ / 10e6 Hz will result in 1kHz.
CLK_HZ = 2, // The frequency parameter, CLK_HZ, used in the calculation of CLK_DIV
}
public override ONIDeviceAddress DeviceAddress { get; set; } = new ONIDeviceAddress();
protected override IObservable<HeartbeatDataFrame> Process(IObservable<ONIManagedFrame<ushort>> source, ulong frameOffset)
{
return source.Select(f => { return new HeartbeatDataFrame(f, frameOffset); });
}
[Category("Configuration")]
[Description("Enable the device data stream.")]
public bool EnableStream
{
get
{
return ReadRegister((uint)Register.ENABLE) > 0;
}
set
{
WriteRegister((uint)Register.ENABLE, value ? (uint)1 : 0);
}
}
private uint beat_hz = 1;
[Category("Configuration")]
[Description("Rate at which beats are produced.")]
[Range(1, 10e6)]
public uint BeatHz
{
get
{
var val = ReadRegister((int)Register.CLK_DIV);
if (val != 0) { beat_hz = ReadRegister((int)Register.CLK_HZ) / val; }
return beat_hz;
}
set
{
if (value != 0)
{
WriteRegister((int)Register.CLK_DIV, ReadRegister((int)Register.CLK_HZ) / value);
beat_hz = value;
}
}
}
}
} | 33.421875 | 150 | 0.56475 | [
"MIT"
] | jonnew/Bonsai.ONIX | Bonsai.ONIX/HeartbeatDevice.cs | 2,141 | C# |
using Com.Game.Data;
using Com.Game.Manager;
using Com.Game.Module;
using GUIFramework;
using MobaHeros.Pvp;
using System;
using UnityEngine;
namespace HUD.Module
{
public class AttackIndicator : BaseModule
{
private Transform heroTargetInfo;
private string heroName;
private UISprite heroIcon;
private UILabel heroKillInfo;
private Transform otherTargetInfo;
private UISprite otherIcon;
private UIBloodBarLightWeight _heroTarget;
private UIBloodBarLightWeight _monsterTarget;
private UILabel otherName;
private TweenPosition tPos;
private Vector3 positionShow = new Vector3(-756.2f, -6.9f, 0f);
private Vector3 positionHide = new Vector3(-756.2f, 493.1f, 0f);
public AttackIndicator()
{
this.module = EHUDModule.AttackIndicator;
this.WinResCfg = new WinResurceCfg(false, false, "Prefab/HUDModule/AttackIndicatorModule");
}
public override void Init()
{
base.Init();
this.heroTargetInfo = this.transform.Find("offset/HeroTarget");
this.heroIcon = this.heroTargetInfo.Find("Sprite/Texture").GetComponent<UISprite>();
this._heroTarget = this.heroTargetInfo.Find("HPBar").GetComponent<UIBloodBarLightWeight>();
this.heroKillInfo = this.heroTargetInfo.Find("KillInfo/KillNumber").GetComponent<UILabel>();
this.otherTargetInfo = this.transform.Find("offset/OtherTarget");
this.otherIcon = this.otherTargetInfo.Find("Sprite/Texture").GetComponent<UISprite>();
this._monsterTarget = this.otherTargetInfo.Find("HPBar/HPBar").GetComponent<UIBloodBarLightWeight>();
this.otherName = this.otherTargetInfo.Find("Name/name").GetComponent<UILabel>();
this.tPos = this.transform.GetComponent<TweenPosition>();
this.SetHeroIndicatorActive(false);
this.SetOtherIndicatorActive(false);
}
public override void RegisterUpdateHandler()
{
base.RegisterUpdateHandler();
MobaMessageManager.RegistMessage((ClientMsg)25059, new MobaMessageFunc(this.OnMsgGetTarget));
}
public override void CancelUpdateHandler()
{
base.CancelUpdateHandler();
MobaMessageManager.UnRegistMessage((ClientMsg)25059, new MobaMessageFunc(this.OnMsgGetTarget));
}
public override void onFlyOut()
{
this.tPos.PlayForward();
}
public override void onFlyIn()
{
this.tPos.PlayReverse();
}
private void SetHeroIndicatorActive(bool isActive)
{
this.SetVisibleByTranslate(this.heroTargetInfo.transform, isActive);
if (!isActive)
{
this._heroTarget.SetTarget(null);
}
}
private void SetOtherIndicatorActive(bool isActive)
{
this.SetVisibleByTranslate(this.otherTargetInfo.transform, isActive);
if (!isActive)
{
this._monsterTarget.SetTarget(null);
}
}
private void SetVisibleByTranslate(Transform trans, bool visible)
{
if (visible)
{
trans.localPosition = this.positionShow;
}
else
{
trans.localPosition = this.positionHide;
}
}
public override void Destroy()
{
this.heroTargetInfo = null;
this.heroIcon = null;
this.heroKillInfo = null;
this.otherTargetInfo = null;
this.otherIcon = null;
this.otherName = null;
base.Destroy();
}
private void OnMsgGetTarget(MobaMessage msg)
{
Units target = msg.Param as Units;
this.ShowTargetInfo(target);
}
public void ShowTargetInfo(Units target)
{
if (target == null)
{
if (this.otherTargetInfo == null || this.heroTargetInfo == null)
{
return;
}
this.SetHeroIndicatorActive(false);
this.SetOtherIndicatorActive(false);
return;
}
else
{
if (target.teamType == PlayerControlMgr.Instance.GetPlayer().teamType)
{
return;
}
if (target.isHero)
{
this.ShowHeroTargetInfo(target);
}
else
{
this.ShowOtherTargetInfo(target);
}
return;
}
}
private void ShowHeroTargetInfo(Units hero)
{
this.SetOtherIndicatorActive(false);
this.SetHeroIndicatorActive(true);
if (this.heroName != hero.name)
{
this.heroName = hero.name;
SysHeroMainVo heroMainData = BaseDataMgr.instance.GetHeroMainData(hero.npc_id);
if (heroMainData != null)
{
this.heroIcon.spriteName = heroMainData.avatar_icon;
}
}
PvpStatisticMgr.HeroData heroData = Singleton<PvpManager>.Instance.StatisticMgr.GetHeroData(hero.unique_id);
string text = heroData.MonsterKill.ToString();
string text2 = string.Concat(new object[]
{
heroData.HeroKill,
"/",
heroData.Death,
"/",
heroData.Assist
});
int num = text.Length + text2.Length;
for (int i = 0; i < 12 - num; i++)
{
text += " ";
}
this.heroKillInfo.text = text + text2;
this._heroTarget.SetTarget(hero);
}
private void ShowOtherTargetInfo(Units other)
{
if (this.heroTargetInfo == null)
{
return;
}
this.SetOtherIndicatorActive(true);
this.SetHeroIndicatorActive(false);
if (this.heroName != other.name)
{
this.heroName = other.name;
SysMonsterMainVo monsterMainData = BaseDataMgr.instance.GetMonsterMainData(other.npc_id);
if (monsterMainData != null)
{
if (other.isTower)
{
if (other.TeamType == TeamType.LM)
{
this.otherIcon.spriteName = "TowerBlue_Avatar";
}
else
{
this.otherIcon.spriteName = "TowerRed_Avatar";
}
}
else if (other.isHome)
{
if (other.TeamType == TeamType.LM)
{
this.otherIcon.spriteName = "GemBlue_Avatar";
}
else
{
this.otherIcon.spriteName = "GemRed_Avatar";
}
}
else
{
this.otherIcon.spriteName = monsterMainData.avatar_icon;
}
this.otherName.text = LanguageManager.Instance.GetStringById(monsterMainData.name);
}
}
this._monsterTarget.SetTarget(other);
}
}
}
| 25.274262 | 112 | 0.662771 | [
"MIT"
] | corefan/mobahero_src | HUD.Module/AttackIndicator.cs | 5,990 | C# |
using System.Reflection;
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("AWSSDK.IdentityStore")]
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - AWS SSO Identity Store. AWS Single Sign-On (SSO) Identity Store service provides an interface to retrieve all of your users and groups. It enables entitlement management per user or group for AWS SSO and other IDPs.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("Amazon Web Services SDK for .NET")]
[assembly: AssemblyCompany("Amazon.com, Inc")]
[assembly: AssemblyCopyright("Copyright 2009-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("3.3")]
[assembly: AssemblyFileVersion("3.5.0.2")] | 49.09375 | 295 | 0.752387 | [
"Apache-2.0"
] | DetlefGolze/aws-sdk-net | sdk/code-analysis/ServiceAnalysis/IdentityStore/Properties/AssemblyInfo.cs | 1,571 | 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("Repository")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Repository")]
[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("79a6aa11-b0c0-44a3-ba00-eed3762f5257")]
// 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.648649 | 84 | 0.744436 | [
"MIT"
] | coenm/FlexKids2015 | src/Repository/Properties/AssemblyInfo.cs | 1,396 | 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;
using System.Reflection;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Xunit;
// ReSharper disable UnusedAutoPropertyAccessor.Local
// ReSharper disable InconsistentNaming
namespace Microsoft.EntityFrameworkCore.Metadata.Internal
{
public class ModelTest
{
[ConditionalFact]
public void Use_of_custom_IModel_throws()
{
var model = new FakeModel();
Assert.Equal(
CoreStrings.CustomMetadata(nameof(Use_of_custom_IModel_throws), nameof(IModel), nameof(FakeModel)),
Assert.Throws<NotSupportedException>(() => model.AsModel()).Message);
}
private class FakeModel : IModel
{
public object this[string name]
=> throw new NotImplementedException();
public IAnnotation FindAnnotation(string name)
=> throw new NotImplementedException();
public IEnumerable<IAnnotation> GetAnnotations()
=> throw new NotImplementedException();
public IEnumerable<IEntityType> GetEntityTypes()
=> throw new NotImplementedException();
public IEntityType FindEntityType(string name)
=> throw new NotImplementedException();
public IEntityType FindEntityType(string name, string definingNavigationName, IEntityType definingEntityType)
=> throw new NotImplementedException();
}
[ConditionalFact]
public void Snapshot_change_tracking_is_used_by_default()
{
Assert.Equal(ChangeTrackingStrategy.Snapshot, CreateModel().GetChangeTrackingStrategy());
}
[ConditionalFact]
public void Change_tracking_strategy_can_be_changed()
{
var model = CreateModel();
model.SetChangeTrackingStrategy(ChangeTrackingStrategy.ChangingAndChangedNotifications);
Assert.Equal(ChangeTrackingStrategy.ChangingAndChangedNotifications, model.GetChangeTrackingStrategy());
model.SetChangeTrackingStrategy(ChangeTrackingStrategy.ChangedNotifications);
Assert.Equal(ChangeTrackingStrategy.ChangedNotifications, model.GetChangeTrackingStrategy());
}
[ConditionalFact]
public void Can_add_and_remove_entity_by_type()
{
var model = CreateModel();
Assert.Null(model.FindEntityType(typeof(Customer)));
Assert.Null(model.RemoveEntityType(typeof(Customer)));
var entityType = model.AddEntityType(typeof(Customer));
Assert.Equal(typeof(Customer), entityType.ClrType);
Assert.NotNull(model.FindEntityType(typeof(Customer)));
Assert.Same(model, entityType.Model);
Assert.NotNull(((EntityType)entityType).Builder);
Assert.Same(entityType, model.FindEntityType(typeof(Customer)));
Assert.Equal(new[] { entityType }, model.GetEntityTypes().ToArray());
Assert.Same(entityType, model.RemoveEntityType(entityType.ClrType));
Assert.Null(model.RemoveEntityType(entityType.ClrType));
Assert.Null(model.FindEntityType(typeof(Customer)));
Assert.Null(((EntityType)entityType).Builder);
}
[ConditionalFact]
public void Can_add_and_remove_entity_by_name()
{
var model = CreateModel();
Assert.Null(model.FindEntityType(typeof(Customer).FullName));
Assert.Null(model.RemoveEntityType(typeof(Customer).FullName));
var entityType = model.AddEntityType(typeof(Customer).FullName);
Assert.Null(entityType.ClrType);
Assert.Equal(typeof(Customer).FullName, entityType.Name);
Assert.NotNull(model.FindEntityType(typeof(Customer).FullName));
Assert.Same(model, entityType.Model);
Assert.NotNull(((EntityType)entityType).Builder);
Assert.Same(entityType, model.FindEntityType(typeof(Customer).FullName));
Assert.Equal(new[] { entityType }, model.GetEntityTypes().ToArray());
Assert.Same(entityType, model.RemoveEntityType(entityType.Name));
Assert.Null(model.RemoveEntityType(entityType.Name));
Assert.Null(model.FindEntityType(typeof(Customer).FullName));
Assert.Null(((EntityType)entityType).Builder);
}
[ConditionalFact]
public void Can_add_and_remove_shared_entity()
{
var model = CreateModel();
var entityTypeName = "SharedCustomer1";
Assert.Null(model.FindEntityType(typeof(Customer)));
Assert.Null(model.FindEntityType(entityTypeName));
var entityType = model.AddEntityType(entityTypeName, typeof(Customer));
Assert.Equal(typeof(Customer), entityType.ClrType);
Assert.Equal(entityTypeName, entityType.Name);
Assert.NotNull(model.FindEntityType(entityTypeName));
Assert.Same(model, entityType.Model);
Assert.NotNull(((EntityType)entityType).Builder);
Assert.Same(entityType, model.FindEntityType(entityTypeName));
Assert.Null(model.FindEntityType(typeof(Customer)));
Assert.Equal(new[] { entityType }, model.GetEntityTypes().ToArray());
Assert.Same(entityType, model.RemoveEntityType(entityType.Name));
Assert.Null(model.RemoveEntityType(entityType.Name));
Assert.Null(model.FindEntityType(entityTypeName));
Assert.Null(((EntityType)entityType).Builder);
}
[ConditionalFact]
public void Can_add_weak_entity_types()
{
var model = CreateModel();
var customerType = model.AddEntityType(typeof(Customer));
var idProperty = customerType.AddProperty(Customer.IdProperty);
var customerKey = customerType.AddKey(idProperty);
var dependentOrderType = model.AddEntityType(typeof(Order), nameof(Customer.Orders), customerType);
var fkProperty = dependentOrderType.AddProperty("ShadowId", typeof(int));
var orderKey = dependentOrderType.AddKey(fkProperty);
var fk = dependentOrderType.AddForeignKey(fkProperty, customerKey, customerType);
var index = dependentOrderType.AddIndex(fkProperty);
Assert.Same(fkProperty, dependentOrderType.GetProperties().Single());
Assert.Same(orderKey, dependentOrderType.GetKeys().Single());
Assert.Same(fk, dependentOrderType.GetForeignKeys().Single());
Assert.Same(index, dependentOrderType.GetIndexes().Single());
Assert.Equal(new[] { customerType, dependentOrderType }, model.GetEntityTypes());
Assert.True(model.HasEntityTypeWithDefiningNavigation(typeof(Order)));
Assert.True(model.HasEntityTypeWithDefiningNavigation(typeof(Order).DisplayName()));
Assert.Same(
dependentOrderType,
model.FindEntityType(typeof(Order).DisplayName(), nameof(Customer.Orders), customerType));
Assert.Same(
dependentOrderType,
model.FindEntityType(typeof(Order).DisplayName(), nameof(Customer.Orders), (IEntityType)customerType));
Assert.Equal(
CoreStrings.ClashingWeakEntityType(typeof(Order).DisplayName(fullName: false)),
Assert.Throws<InvalidOperationException>(() => model.AddEntityType(typeof(Order))).Message);
Assert.Equal(
CoreStrings.ClashingNonWeakEntityType(
nameof(Customer)
+ "."
+ nameof(Customer.Orders)
+ "#"
+ nameof(Order)
+ "."
+ nameof(Order.Customer)
+ "#"
+ nameof(Customer)),
Assert.Throws<InvalidOperationException>(
() => model.AddEntityType(typeof(Customer), nameof(Order.Customer), dependentOrderType)).Message);
Assert.Equal(
CoreStrings.ForeignKeySelfReferencingDependentEntityType(
nameof(Customer) + "." + nameof(Customer.Orders) + "#" + nameof(Order)),
Assert.Throws<InvalidOperationException>(
() => dependentOrderType.AddForeignKey(fkProperty, orderKey, dependentOrderType)).Message);
Assert.Same(
dependentOrderType, model.RemoveEntityType(
typeof(Order), nameof(Customer.Orders), customerType));
Assert.Null(((EntityType)dependentOrderType).Builder);
Assert.Empty(customerType.GetReferencingForeignKeys());
}
[ConditionalFact]
public void Cannot_remove_entity_type_when_referenced_by_foreign_key()
{
var model = CreateModel();
var customerType = model.AddEntityType(typeof(Customer));
var idProperty = customerType.AddProperty(Customer.IdProperty);
var customerKey = customerType.AddKey(idProperty);
var orderType = model.AddEntityType(typeof(Order));
var customerFk = orderType.AddProperty(Order.CustomerIdProperty);
orderType.AddForeignKey(customerFk, customerKey, customerType);
Assert.Equal(
CoreStrings.EntityTypeInUseByReferencingForeignKey(
typeof(Customer).Name,
"{'" + Order.CustomerIdProperty.Name + "'}",
typeof(Order).Name),
Assert.Throws<InvalidOperationException>(() => model.RemoveEntityType(customerType.Name)).Message);
}
[ConditionalFact]
public void Cannot_remove_entity_type_when_it_has_derived_types()
{
var model = CreateModel();
var customerType = model.AddEntityType(typeof(Customer));
var specialCustomerType = model.AddEntityType(typeof(SpecialCustomer));
specialCustomerType.BaseType = customerType;
Assert.Equal(
CoreStrings.EntityTypeInUseByDerived(typeof(Customer).Name, typeof(SpecialCustomer).Name),
Assert.Throws<InvalidOperationException>(() => model.RemoveEntityType(customerType.Name)).Message);
}
[ConditionalFact]
public void Using_invalid_entity_type_throws()
{
var model = CreateModel();
Assert.Equal(
CoreStrings.InvalidEntityType(typeof(IReadOnlyList<int>)),
Assert.Throws<ArgumentException>(() => model.AddEntityType(typeof(IReadOnlyList<int>))).Message);
}
[ConditionalFact]
public void Adding_duplicate_entity_by_type_throws()
{
var model = CreateModel();
Assert.Null(model.RemoveEntityType(typeof(Customer).FullName));
model.AddEntityType(typeof(Customer));
Assert.Equal(
CoreStrings.DuplicateEntityType(nameof(Customer)),
Assert.Throws<InvalidOperationException>(() => model.AddEntityType(typeof(Customer))).Message);
}
[ConditionalFact]
public void Adding_duplicate_entity_by_name_throws()
{
var model = CreateModel();
Assert.Null(model.RemoveEntityType(typeof(Customer)));
model.AddEntityType(typeof(Customer));
Assert.Equal(
CoreStrings.DuplicateEntityType(typeof(Customer).FullName),
Assert.Throws<InvalidOperationException>(() => model.AddEntityType(typeof(Customer).FullName)).Message);
}
[ConditionalFact]
public void Adding_duplicate_shared_type_throws()
{
var model = (Model)CreateModel();
Assert.Null(model.RemoveEntityType(typeof(Customer).FullName));
model.AddEntityType(typeof(Customer), ConfigurationSource.Explicit);
Assert.Equal(
CoreStrings.CannotMarkShared(nameof(Customer)),
Assert.Throws<InvalidOperationException>(() => model.AddShared(typeof(Customer), ConfigurationSource.Explicit)).Message);
}
[ConditionalFact]
public void Can_get_entity_by_type()
{
var model = CreateModel();
var entityType = model.AddEntityType(typeof(Customer));
Assert.Same(entityType, model.FindEntityType(typeof(Customer)));
Assert.Same(entityType, model.FindEntityType(typeof(Customer)));
Assert.Null(model.FindEntityType(typeof(string)));
}
[ConditionalFact]
public void Can_get_entity_by_name()
{
var model = CreateModel();
var entityType = model.AddEntityType(typeof(Customer).FullName);
Assert.Same(entityType, model.FindEntityType(typeof(Customer).FullName));
Assert.Same(entityType, model.FindEntityType(typeof(Customer).FullName));
Assert.Null(model.FindEntityType(typeof(string)));
}
[ConditionalFact]
public void Entities_are_ordered_by_name()
{
var model = CreateModel();
var entityType1 = model.AddEntityType(typeof(Order));
var entityType2 = model.AddEntityType(typeof(Customer));
Assert.True(new[] { entityType2, entityType1 }.SequenceEqual(model.GetEntityTypes()));
}
[ConditionalFact]
public void Can_get_referencing_foreign_keys()
{
var model = CreateModel();
var entityType1 = model.AddEntityType(typeof(Customer));
var entityType2 = model.AddEntityType(typeof(Order));
var keyProperty = entityType1.AddProperty("Id", typeof(int));
var fkProperty = entityType2.AddProperty("CustomerId", typeof(int));
var foreignKey = entityType2.AddForeignKey(fkProperty, entityType1.AddKey(keyProperty), entityType1);
var referencingForeignKeys = entityType1.GetReferencingForeignKeys();
Assert.Same(foreignKey, referencingForeignKeys.Single());
Assert.Same(foreignKey, entityType1.GetReferencingForeignKeys().Single());
}
private static IMutableModel CreateModel()
=> new Model();
private class Customer
{
public static readonly PropertyInfo IdProperty = typeof(Customer).GetProperty("Id");
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Order> Orders { get; set; }
}
private class SpecialCustomer : Customer
{
}
private class Order
{
public static readonly PropertyInfo CustomerIdProperty = typeof(Order).GetProperty("CustomerId");
public int Id { get; set; }
public int CustomerId { get; set; }
public Customer Customer { get; set; }
}
}
}
| 42.308333 | 137 | 0.63699 | [
"Apache-2.0"
] | Peen2539/efcore | test/EFCore.Tests/Metadata/Internal/ModelTest.cs | 15,231 | C# |
/*
* Dragonfly Model Schema
*
* This is the documentation for Dragonfly model schema.
*
* The version of the OpenAPI document: 1.5.1
* Contact: info@ladybug.tools
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
namespace DragonflySchema
{
/// <summary>
/// Base class for all objects requiring a valid names for all engines.
/// </summary>
[DataContract]
public partial class Building : IEquatable<Building>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="Building" /> class.
/// </summary>
[JsonConstructorAttribute]
protected Building() { }
/// <summary>
/// Initializes a new instance of the <see cref="Building" /> class.
/// </summary>
/// <param name="name">Name of the object used in all simulation engines. Must not contain spaces and use only letters, digits and underscores/dashes. It cannot be longer than 100 characters. (required).</param>
/// <param name="uniqueStories">An array of unique dragonfly Story objects that together form the entire building. Stories should generally be ordered from lowest floor to highest floor. Note that, if a given Story is repeated several times over the height of the building, the unique story included in this list should be the first (lowest) story of the repeated floors. (required).</param>
/// <param name="properties">Extension properties for particular simulation engines (Radiance, EnergyPlus). (required).</param>
/// <param name="displayName">Display name of the object with no restrictions..</param>
/// <param name="type">type (default to "Building").</param>
public Building(string name, List<Story> uniqueStories, BuildingPropertiesAbridged properties, string displayName = default, string type = "Building")
{
// to ensure "name" is required (not null)
if (name == null)
{
throw new InvalidDataException("name is a required property for Building and cannot be null");
}
else
{
this.Name = name;
}
// to ensure "uniqueStories" is required (not null)
if (uniqueStories == null)
{
throw new InvalidDataException("uniqueStories is a required property for Building and cannot be null");
}
else
{
this.UniqueStories = uniqueStories;
}
// to ensure "properties" is required (not null)
if (properties == null)
{
throw new InvalidDataException("properties is a required property for Building and cannot be null");
}
else
{
this.Properties = properties;
}
this.DisplayName = displayName;
// use default value if no "type" provided
if (type == null)
{
this.Type = "Building";
}
else
{
this.Type = type;
}
}
/// <summary>
/// Name of the object used in all simulation engines. Must not contain spaces and use only letters, digits and underscores/dashes. It cannot be longer than 100 characters.
/// </summary>
/// <value>Name of the object used in all simulation engines. Must not contain spaces and use only letters, digits and underscores/dashes. It cannot be longer than 100 characters.</value>
[DataMember(Name="name", EmitDefaultValue=false)]
[JsonProperty("name")]
public string Name { get; set; }
/// <summary>
/// An array of unique dragonfly Story objects that together form the entire building. Stories should generally be ordered from lowest floor to highest floor. Note that, if a given Story is repeated several times over the height of the building, the unique story included in this list should be the first (lowest) story of the repeated floors.
/// </summary>
/// <value>An array of unique dragonfly Story objects that together form the entire building. Stories should generally be ordered from lowest floor to highest floor. Note that, if a given Story is repeated several times over the height of the building, the unique story included in this list should be the first (lowest) story of the repeated floors.</value>
[DataMember(Name="unique_stories", EmitDefaultValue=false)]
[JsonProperty("unique_stories")]
public List<Story> UniqueStories { get; set; }
/// <summary>
/// Extension properties for particular simulation engines (Radiance, EnergyPlus).
/// </summary>
/// <value>Extension properties for particular simulation engines (Radiance, EnergyPlus).</value>
[DataMember(Name="properties", EmitDefaultValue=false)]
[JsonProperty("properties")]
public BuildingPropertiesAbridged Properties { get; set; }
/// <summary>
/// Display name of the object with no restrictions.
/// </summary>
/// <value>Display name of the object with no restrictions.</value>
[DataMember(Name="display_name", EmitDefaultValue=false)]
[JsonProperty("display_name")]
public string DisplayName { get; set; }
/// <summary>
/// Gets or Sets Type
/// </summary>
[DataMember(Name="type", EmitDefaultValue=false)]
[JsonProperty("type")]
public string Type { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class Building {\n");
sb.Append(" Name: ").Append(Name).Append("\n");
sb.Append(" UniqueStories: ").Append(UniqueStories).Append("\n");
sb.Append(" Properties: ").Append(Properties).Append("\n");
sb.Append(" DisplayName: ").Append(DisplayName).Append("\n");
sb.Append(" Type: ").Append(Type).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented, new AnyOfJsonConverter());
}
/// <summary>
/// Returns the object from JSON string
/// </summary>
/// <returns>Building object</returns>
public static Building FromJson(string json)
{
return JsonConvert.DeserializeObject<Building>(json, new AnyOfJsonConverter());
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as Building);
}
/// <summary>
/// Returns true if Building instances are equal
/// </summary>
/// <param name="input">Instance of Building to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(Building input)
{
if (input == null)
return false;
return
(
this.Name == input.Name ||
(this.Name != null &&
this.Name.Equals(input.Name))
) &&
(
this.UniqueStories == input.UniqueStories ||
this.UniqueStories != null &&
input.UniqueStories != null &&
this.UniqueStories.SequenceEqual(input.UniqueStories)
) &&
(
this.Properties == input.Properties ||
(this.Properties != null &&
this.Properties.Equals(input.Properties))
) &&
(
this.DisplayName == input.DisplayName ||
(this.DisplayName != null &&
this.DisplayName.Equals(input.DisplayName))
) &&
(
this.Type == input.Type ||
(this.Type != null &&
this.Type.Equals(input.Type))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.Name != null)
hashCode = hashCode * 59 + this.Name.GetHashCode();
if (this.UniqueStories != null)
hashCode = hashCode * 59 + this.UniqueStories.GetHashCode();
if (this.Properties != null)
hashCode = hashCode * 59 + this.Properties.GetHashCode();
if (this.DisplayName != null)
hashCode = hashCode * 59 + this.DisplayName.GetHashCode();
if (this.Type != null)
hashCode = hashCode * 59 + this.Type.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
// Name (string) maxLength
if(this.Name != null && this.Name.Length > 100)
{
yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Name, length must be less than 100.", new [] { "Name" });
}
// Name (string) minLength
if(this.Name != null && this.Name.Length < 1)
{
yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Name, length must be greater than 1.", new [] { "Name" });
}
// Name (string) pattern
Regex regexName = new Regex(@"[A-Za-z0-9_-]", RegexOptions.CultureInvariant);
if (false == regexName.Match(this.Name).Success)
{
yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Name, must match a pattern of " + regexName, new [] { "Name" });
}
// Type (string) pattern
Regex regexType = new Regex(@"^Building$", RegexOptions.CultureInvariant);
if (false == regexType.Match(this.Type).Success)
{
yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Type, must match a pattern of " + regexType, new [] { "Type" });
}
yield break;
}
}
}
| 42.970909 | 399 | 0.576119 | [
"MIT"
] | AntoineDao/dragonfly-schema-dotnet | src/DragonflySchema/Model/Building.cs | 11,817 | C# |
// <copyright file="VxArgs.cs" company="ClrCoder project">
// Copyright (c) ClrCoder project. All rights reserved.
// Licensed under the Apache 2.0 license. See LICENSE file in the project root for full license information.
// </copyright>
namespace ClrCoder.Validation
{
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Reflection;
using JetBrains.Annotations;
/// <summary>
/// Simple argument validation utils.
/// </summary>
[PublicAPI]
public static class VxArgs
{
/// <summary>
/// Validates that argument is positive and finite.
/// </summary>
/// <param name="value">Argument <c>value</c>.</param>
/// <param name="name">Argument <c>name</c>.</param>
public static void FinitPositive(double value, [InvokerParameterName] string name)
{
if (!(value > 0.0) && double.IsPositiveInfinity(value))
{
throw new ArgumentOutOfRangeException(name, $"{name} should be finite positive.");
}
}
/// <summary>
/// Validates that argument is positive and finite.
/// </summary>
/// <param name="value">Argument <c>value</c>.</param>
/// <param name="name">Argument <c>name</c>.</param>
public static void FinitPositive(double? value, [InvokerParameterName] string name)
{
if ((value != null) && !(value > 0.0) && double.IsPositiveInfinity(value.Value))
{
throw new ArgumentOutOfRangeException(name, $"{name} should be finite positive.");
}
}
/// <summary>
/// Validates that <c>value</c> fall in the specified range.
/// </summary>
/// <param name="value">Value to validate.</param>
/// <param name="start">Range <c>start</c> (inclusive).</param>
/// <param name="end">Range <c>end</c> (inclusive).</param>
/// <param name="name">Argument <c>name</c>.</param>
public static void InRange(double value, double start, double end, [InvokerParameterName] string name)
{
if (!(value >= start) || !(value <= end))
{
throw new ArgumentOutOfRangeException($"{name} should fall in range [{start}, {end}]", name);
}
}
/// <summary>
/// Validates that value typed argument is initialized (not equals to the default value).
/// </summary>
/// <typeparam name="T">The value type.</typeparam>
/// <param name="value">The value to validate.</param>
/// <param name="name">The argument name.</param>
public static void NonDefault<T>(T value, [InvokerParameterName] string name)
where T : struct, IEquatable<T>
{
if (value.Equals(default(T)))
{
throw new ArgumentException("Argument should not be equal to the default value.", name);
}
}
/// <summary>
/// Validates that argument is non negative.
/// </summary>
/// <param name="value">Argument <c>value</c>.</param>
/// <param name="name">Argument <c>name</c>.</param>
public static void NonNegative(int value, [InvokerParameterName] string name)
{
if (value < 0)
{
throw new ArgumentOutOfRangeException($"{name} should not be negative.", name);
}
}
/// <summary>
/// Validates that Width and Height are both non negative.
/// </summary>
/// <param name="size">Size to validate.</param>
/// <param name="name">Argument <c>name</c>.</param>
public static void NonNegativeSize(Size? size, [InvokerParameterName] string name)
{
if ((size != null) && ((size.Value.Width < 0) || (size.Value.Height < 0)))
{
throw new ArgumentOutOfRangeException(name, "Both Width and Height should be non negative");
}
}
/// <summary>
/// Validates argument string is not empty.
/// </summary>
/// <param name="str">String to validate.</param>
/// <param name="name">Name of argument.</param>
public static void NonNullOrWhiteSpace(string str, [InvokerParameterName] string name)
{
if (str == null)
{
throw new ArgumentNullException(name);
}
if (string.IsNullOrWhiteSpace(str))
{
throw new ArgumentException($"{name} should not be an empty or whitespace string.", name);
}
}
/// <summary>
/// Validates argument string is not empty.
/// </summary>
/// <param name="str">The string to validate.</param>
/// <param name="name">The name of the argument.</param>
public static void CanBeNullButNotWhiteSpace([CanBeNull]string str, [InvokerParameterName] string name)
{
if (str != null)
{
if (string.IsNullOrWhiteSpace(str))
{
throw new ArgumentException($"{name} should not be an empty or whitespace string.", name);
}
}
}
/// <summary>
/// Validates that the specified value not equals to the default value.
/// </summary>
/// <typeparam name="T">The type of the value to validate.</typeparam>
/// <param name="value">Value to validate.</param>
/// <param name="name">Argument <c>name</c>.</param>
public static void NotDefault<T>(T value, [InvokerParameterName] string name)
where T : struct
{
throw new ArgumentException(nameof(name), $"{name} cannot be equal to the default value.");
}
/// <summary>
/// Validates that <c>collection</c> is not empty. Also validates items not <c>null</c> in debug mode.
/// </summary>
/// <typeparam name="T">Type of <c>collection</c> item.</typeparam>
/// <param name="collection">Collection to validate.</param>
/// <param name="name">Name of an argument.</param>
public static void NotEmptyReadOnly<T>(IReadOnlyCollection<T> collection, string name)
{
if (collection == null)
{
throw new ArgumentNullException(name);
}
if (collection.Count == 0)
{
throw new ArgumentException($"{name} collection should not be empty.", name);
}
#if DEBUG
if (!typeof(T).GetTypeInfo().IsValueType)
{
foreach (T item in collection)
{
if (item == null)
{
throw new ArgumentException($"{name} collection element is null.", name);
}
}
}
#endif
}
/// <summary>
/// Validates that passed parameter value is not <see langword="null"/>.
/// </summary>
/// <typeparam name="T">The type of the value to validate.</typeparam>
/// <param name="value">The value to validate.</param>
/// <param name="errorName">The parameter name.</param>
/// <exception cref="ArgumentNullException">Argument is null.</exception>
[ContractAnnotation("value:null=>halt")]
public static void NotNull<T>([NoEnumeration][CanBeNull] T value, string errorName)
where T : class
{
if (value == null)
{
throw new ArgumentNullException(errorName);
}
}
/// <summary>
/// Validates that Width and Height are both non zero positive.
/// </summary>
/// <param name="size">Size to validate.</param>
/// <param name="name">Argument <c>name</c>.</param>
public static void PositiveSize(Size size, [InvokerParameterName] string name)
{
if ((size.Width <= 0) || (size.Height <= 0))
{
throw new ArgumentOutOfRangeException(name, "Both Width and Height should be non-zero positive");
}
}
/// <summary>
/// Validates that Width and Height are both non zero positive.
/// </summary>
/// <param name="size">Size to validate.</param>
/// <param name="name">Argument <c>name</c>.</param>
public static void PositiveSize(Size? size, [InvokerParameterName] string name)
{
if ((size != null) && ((size.Value.Width <= 0) || (size.Value.Height <= 0)))
{
throw new ArgumentOutOfRangeException(name, "Both Width and Height should be non-zero positive");
}
}
/// <summary>
/// Validates that the specified value fits into TypeChoice. Validation success for <see langword="null"/> value.
/// </summary>
/// <typeparam name="T">The type of the value to validate.</typeparam>
/// <param name="value">The value to validate.</param>
/// <param name="name">The parameter name.</param>
/// <returns>Fluent syntax to choice validation.</returns>
public static VxValidateTypeChoice<T> TypeChoice<T>([CanBeNull] T value, [InvokerParameterName] string name)
{
return new VxValidateTypeChoice<T>(value, name);
}
/// <summary>
/// Validates that provided Uri is valid http and absolute.
/// </summary>
/// <param name="uri">Uri to validate.</param>
/// <param name="name">Argument <c>name</c>.</param>
public static void ValidAbsoluteHttpUri(string uri, [InvokerParameterName] string name)
{
// TODO: Implement it faster.
return;
NonNullOrWhiteSpace(uri, name);
try
{
// ReSharper disable once ObjectCreationAsStatement
var uriObj = new Uri(uri, UriKind.Absolute);
if ((uriObj.Scheme != "http") && (uriObj.Scheme != "https"))
{
throw new ArgumentException($"{name} should use http/https", name);
}
}
catch (UriFormatException ex)
{
throw new ArgumentException(ex.Message, name, ex);
}
}
/// <summary>
/// Validates that provided Uri is valid and absolute.
/// </summary>
/// <param name="uri">Uri to validate.</param>
/// <param name="name">Argument <c>name</c>.</param>
public static void ValidAbsoluteUri(string uri, [InvokerParameterName] string name)
{
NonNullOrWhiteSpace(uri, name);
try
{
// ReSharper disable once ObjectCreationAsStatement
new Uri(uri, UriKind.Absolute);
}
catch (UriFormatException ex)
{
throw new ArgumentException(ex.Message, name, ex);
}
}
}
}
| 38.803509 | 121 | 0.546433 | [
"MIT"
] | ClrCoder/ClrCoderFX | src/ClrCoder/Validation/VxArgs.cs | 11,059 | C# |
using System.Runtime.Serialization;
namespace WowSharp.BattleNet.Api.Wow.Character
{
/// <summary>
/// Represents a character's title
/// </summary>
[DataContract]
public class CharacterTitle
{
/// <summary>
/// Gets or sets the id of the title
/// </summary>
[DataMember(Name = "id", IsRequired = true)]
public int Id
{
get;
internal set;
}
/// <summary>
/// Gets or sets the name of the title. Note that %s is replaced with character's name
/// </summary>
[DataMember(Name = "name", IsRequired = true)]
public string Name
{
get;
internal set;
}
/// <summary>
/// Gets or sets whether this title is currently selected
/// </summary>
[DataMember(Name = "selected", IsRequired = false)]
public bool IsSelected
{
get;
internal set;
}
/// <summary>
/// Gets string representation (for debugging purposes)
/// </summary>
/// <returns> Gets string representation (for debugging purposes) </returns>
public override string ToString()
{
return Name;
}
}
} | 25.74 | 96 | 0.51826 | [
"MIT"
] | bitobrian/Blizzard.net-API | WowSharp.BattleNet.Api/Wow/Character/CharacterTitle.cs | 1,289 | C# |
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
namespace Restall.Ichnaea.Fody.AssemblyToProcess
{
[AggregateRoot]
public class SourceEventUsingManipulatedLocalVariable
{
[SuppressMessage("ReSharper", "UnusedMember.Global", Justification = CodeAnalysisJustification.StubForTesting)]
public SomethingHappened DoSomething(Guid token)
{
var domainEventAfterSwap = new SomethingHappened(Guid.NewGuid());
var somethingToCauseManipulation = new SomethingHappened(token);
Interlocked.Exchange(ref domainEventAfterSwap, somethingToCauseManipulation);
Source.Event.Of(domainEventAfterSwap);
return somethingToCauseManipulation;
}
[SuppressMessage("ReSharper", "EventNeverSubscribedTo.Global", Justification = CodeAnalysisJustification.IchnaeaSubscribes)]
public event Source.Of<SomethingHappened> EventSource;
}
}
| 36.166667 | 126 | 0.819124 | [
"MIT"
] | pete-restall/Ichnaea | Fody/AssemblyToProcess/SourceEventUsingManipulatedLocalVariable.cs | 870 | C# |
namespace WarMachines.Engine
{
using WarMachines.Interfaces;
using WarMachines.Machines;
public class MachineFactory : IMachineFactory
{
public IPilot HirePilot(string name)
{
return new Pilot(name);
}
public ITank ManufactureTank(string name, double attackPoints, double defensePoints)
{
return new Tank(name, attackPoints, defensePoints);
}
public IFighter ManufactureFighter(string name, double attackPoints, double defensePoints, bool stealthMode)
{
return new Fighter(name, attackPoints, defensePoints, stealthMode);
}
}
}
| 27.5 | 116 | 0.651515 | [
"MIT"
] | Ico093/TelerikAcademy | C#OOP/Exams/C#OOP-December-2013/1. War Machines/WarMachines-Skeleton/WarMachines/Engine/MachineFactory.cs | 662 | C# |
namespace Mollie.Models.Payment.Request {
public class PaySafeCardPaymentRequest : PaymentRequest {
public PaySafeCardPaymentRequest() {
this.Method = PaymentMethod.PaySafeCard;
}
/// <summary>
/// Used for consumer identification. For example, you could use the consumer’s IP address.
/// </summary>
public string CustomerReference { get; set; }
}
} | 35 | 99 | 0.642857 | [
"MIT"
] | cmsoftwaresolutions/MollieApi | Mollie.Api/Models/Payment/Request/PaySafeCardPaymentRequest.cs | 424 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
namespace ILCompiler.DependencyAnalysisFramework
{
public interface IDependencyAnalysisMarkStrategy<DependencyContextType>
{
/// <summary>
/// Use the provided node, reasonNode, reasonNode2, and reason to mark a node
/// </summary>
/// <param name="node"></param>
/// <param name="reasonNode"></param>
/// <param name="reasonNode2"></param>
/// <param name="reason"></param>
/// <returns>true if the node is newly marked</returns>
bool MarkNode(
DependencyNodeCore<DependencyContextType> node,
DependencyNodeCore<DependencyContextType> reasonNode,
DependencyNodeCore<DependencyContextType> reasonNode2,
string reason
);
void VisitLogNodes(
IEnumerable<DependencyNodeCore<DependencyContextType>> nodeList,
IDependencyAnalyzerLogNodeVisitor<DependencyContextType> logNodeVisitor
);
void VisitLogEdges(
IEnumerable<DependencyNodeCore<DependencyContextType>> nodeList,
IDependencyAnalyzerLogEdgeVisitor<DependencyContextType> logEdgeVisitor
);
void AttachContext(DependencyContextType context);
}
}
| 36.230769 | 85 | 0.675867 | [
"MIT"
] | belav/runtime | src/coreclr/tools/aot/ILCompiler.DependencyAnalysisFramework/IDependencyAnalysisMarkStrategy.cs | 1,413 | C# |
using System;
using System.Collections;
using System.IO;
using System.Text.RegularExpressions;
using UnityEngine;
namespace WellFired.Shared
{
public static class DirectoryExtensions
{
private static readonly string DEFAULT_INSTALLATION_DIRECTORY = string.Format("{0}/WellFired", Application.dataPath);
private static readonly string PROJECT_PATH = Application.dataPath.Remove(Application.dataPath.LastIndexOf("/Assets"), "/Assets".Length);
public static string ProjectPath
{
get { return PROJECT_PATH; }
private set { ; }
}
public static string DefaultInstallationDirectory
{
get { return DEFAULT_INSTALLATION_DIRECTORY; }
private set { ; }
}
public static string DirectoryOf(string file)
{
var result = string.Empty;
var fileList = new DirectoryInfo(ProjectPath + "/Assets").GetFiles(file, SearchOption.AllDirectories);
if(fileList.Length == 1)
{
result = fileList[0].DirectoryName.Substring(ProjectPath.Length, fileList[0].DirectoryName.Length - ProjectPath.Length).Replace('\\', '/') + '/';
}
else
{
Debug.LogWarning(string.Format("Cannot find Directory of {0}", file));
return string.Empty;
}
return result;
}
public static string RelativePathOfProjectFile(string projectFile)
{
var directory = DirectoryOf(projectFile);
return string.Format("{0}{1}", directory, projectFile);
}
public static string AbsolutePathOfProjectFile(string projectFile)
{
var relativePath = RelativePathOfProjectFile(projectFile);
var path = string.Format("{0}{1}", ProjectPath, relativePath);
if(Application.platform == RuntimePlatform.OSXEditor)
return path;
return SlashesToWindowsSlashes(path);
}
/// <summary>
/// Converts all slashes in the given paths to windows backslashes.
/// the given array.
/// </summary>
/// <param name='path'>
/// the path
/// </param>
public static string SlashesToWindowsSlashes(string path)
{
return path.Replace("/", "\\");
}
/// <summary>
/// Converts all backslashes in the given paths to forward slashes. The conversion is done in-place and modifies the
/// given array.
/// </summary>
/// <param name='paths'>
/// the array of paths.
/// </param>
public static void NormalizeSlashes(string[] paths)
{
for(var i = 0; i < paths.Length; i++)
paths[i] = NormalizeSlashes(paths[i]);
}
/// <summary>
/// Converts all backslashes in the given path to forward slashes.
/// </summary>
/// <returns>
/// The normalized path.
/// </returns>
/// <param name='path'>
/// The path to normalize.
/// </param>
public static string NormalizeSlashes(string path)
{
return Regex.Replace(path.Replace("\\", "/"), "//+", "/");
}
public static void RecursivelyDeleteDirectory(string directoryToDelete)
{
var directories = Directory.GetDirectories(directoryToDelete);
foreach(var directory in directories)
{
RecursivelyDeleteDirectory(directory);
}
var files = Directory.GetFiles(directoryToDelete);
foreach(var file in files)
{
File.Delete(file);
}
Directory.Delete(directoryToDelete);
}
public static void CopyDirectory(string sourceDirectory, string destinationDirectory)
{
//Now Create all of the directories
foreach(var dirPath in Directory.GetDirectories(sourceDirectory, "*", SearchOption.AllDirectories))
{
Directory.CreateDirectory(dirPath.Replace(sourceDirectory, destinationDirectory));
}
//Copy all the files & Replaces any files with the same name
foreach(var newPath in Directory.GetFiles(sourceDirectory, "*.*", SearchOption.AllDirectories))
{
File.Copy(newPath, newPath.Replace(sourceDirectory, destinationDirectory), true);
}
}
public static void RemoveAllEmptySubDirectories(string startLocation)
{
foreach(var directory in Directory.GetDirectories(startLocation))
{
RemoveAllEmptySubDirectories(directory);
if(Directory.GetFiles(directory).Length == 0 && Directory.GetDirectories(directory).Length == 0)
{
Directory.Delete(directory, false);
File.Delete(string.Format("{0}.meta", directory));
}
}
}
}
} | 29.083333 | 149 | 0.695081 | [
"MIT"
] | WellFiredDevelopment/WellFired.Direct | solution/WellFired.Shared.Editor/Extensions/DirectoryExtensions.cs | 4,190 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Threading;
using Microsoft.CodeAnalysis;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser
{
internal abstract partial class AbstractObjectBrowserLibraryManager
{
internal void CollectMemberListItems(IAssemblySymbol assemblySymbol, Compilation compilation, ProjectId projectId, ImmutableArray<ObjectListItem>.Builder builder, string searchString)
=> GetListItemFactory().CollectMemberListItems(assemblySymbol, compilation, projectId, builder, searchString);
internal void CollectNamespaceListItems(IAssemblySymbol assemblySymbol, ProjectId projectId, ImmutableArray<ObjectListItem>.Builder builder, string searchString)
=> GetListItemFactory().CollectNamespaceListItems(assemblySymbol, projectId, builder, searchString);
internal void CollectTypeListItems(IAssemblySymbol assemblySymbol, Compilation compilation, ProjectId projectId, ImmutableArray<ObjectListItem>.Builder builder, string searchString)
=> GetListItemFactory().CollectTypeListItems(assemblySymbol, compilation, projectId, builder, searchString);
internal ImmutableHashSet<Tuple<ProjectId, IAssemblySymbol>> GetAssemblySet(Solution solution, string languageName, CancellationToken cancellationToken)
=> GetListItemFactory().GetAssemblySet(solution, languageName, cancellationToken);
internal ImmutableHashSet<Tuple<ProjectId, IAssemblySymbol>> GetAssemblySet(Project project, bool lookInReferences, CancellationToken cancellationToken)
=> GetListItemFactory().GetAssemblySet(project, lookInReferences, cancellationToken);
internal ImmutableArray<ObjectListItem> GetBaseTypeListItems(ObjectListItem parentListItem, Compilation compilation)
=> GetListItemFactory().GetBaseTypeListItems(parentListItem, compilation);
internal ImmutableArray<ObjectListItem> GetFolderListItems(ObjectListItem parentListItem, Compilation compilation)
=> GetListItemFactory().GetFolderListItems(parentListItem, compilation);
internal ImmutableArray<ObjectListItem> GetMemberListItems(ObjectListItem parentListItem, Compilation compilation)
=> GetListItemFactory().GetMemberListItems(parentListItem, compilation);
internal ImmutableArray<ObjectListItem> GetNamespaceListItems(ObjectListItem parentListItem, Compilation compilation)
=> GetListItemFactory().GetNamespaceListItems(parentListItem, compilation);
internal ImmutableArray<ObjectListItem> GetProjectListItems(Solution solution, string languageName, uint listFlags, CancellationToken cancellationToken)
=> GetListItemFactory().GetProjectListItems(solution, languageName, listFlags, cancellationToken);
internal ImmutableArray<ObjectListItem> GetReferenceListItems(ObjectListItem parentListItem, Compilation compilation)
=> GetListItemFactory().GetReferenceListItems(parentListItem, compilation);
internal ImmutableArray<ObjectListItem> GetTypeListItems(ObjectListItem parentListItem, Compilation compilation)
=> GetListItemFactory().GetTypeListItems(parentListItem, compilation);
}
}
| 67.686275 | 191 | 0.798378 | [
"MIT"
] | BertanAygun/roslyn | src/VisualStudio/Core/Def/Implementation/Library/ObjectBrowser/AbstractObjectBrowserLibraryManager_ListItems.cs | 3,454 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using MyMediaPlayer.modele;
using System.ComponentModel;
using System.Windows.Controls;
using FirstFloor.ModernUI.Presentation;
using MyMediaPlayer.Modele;
namespace MyMediaPlayer.viewModels
{
class HomeViewModel
{
private ICommand _openFileCommand = null;
private ICommand _playFileCommand = null;
private ICommand _stopFileCommand = null;
private ICommand _pauseFileCommand = null;
public ICommand OpenFile
{
get
{
if (_openFileCommand == null)
{
_openFileCommand = new RelayCommand(param => MediaManager.openFile());
}
return _openFileCommand;
}
}
public ICommand PlayFile
{
get
{
if (_playFileCommand == null)
{
_playFileCommand = new RelayCommand(param => MediaManager.playFile());
}
return _playFileCommand;
}
}
public ICommand StopFile
{
get
{
if (_stopFileCommand == null)
{
_stopFileCommand = new RelayCommand(param => MediaManager.stopFile());
}
return _stopFileCommand;
}
}
public ICommand PauseFile
{
get
{
if (_pauseFileCommand == null)
{
_pauseFileCommand = new RelayCommand(param => MediaManager.pauseFile());
}
return _pauseFileCommand;
}
}
public MyMedia Media
{
get
{
return MyMedia.Instance();
}
}
}
}
| 25.217949 | 92 | 0.503305 | [
"MIT"
] | kassisdion/media_player | MyMediaPlayer/ViewModels/HomeViewModel.cs | 1,969 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Jal.Router.Interface;
using Jal.Router.Model;
namespace Jal.Router.Impl
{
public class EndPointProvider : IEndPointProvider
{
private readonly EndPoint[] _endpoints;
public EndPointProvider(IEnumerable<IRouterConfigurationSource> sources)
{
var routes = new List<EndPoint>();
foreach (var source in sources)
{
routes.AddRange(source.GetEndPoints());
}
_endpoints = routes.ToArray();
}
public EndPoint Provide(Options options, object content)
{
try
{
return _endpoints.Single(x => x.Name==options.EndPointName && (x.Condition==null || x.Condition(options, content)));
}
catch (Exception ex)
{
throw new ApplicationException($"Missing or duplicate endpoint {options.EndPointName} for type {content.GetType().FullName}, {ex.Message}");
}
}
}
} | 29.162162 | 156 | 0.582947 | [
"Apache-2.0"
] | raulnq/Jal.Router | Jal.Router/Impl/Outbound/EndPointProvider.cs | 1,081 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class PadController : MonoBehaviour
{
public static PadController Instance;
int right = 1;
public float period = 0.0f;
int currentpos = 1;
public int i = 0;
public float EnemyLogicCooldown = 5.0f;
public bool XPressed = false;
public bool BPressed = false;
public bool GotInput = false;
public bool Attacked = false;
// Start is called before the first frame update
void Start()
{
Instance = this;
_enemyLogic = EnemyLogic();
StartCoroutine(_enemyLogic);
}
IEnumerator _enemyLogic;
IEnumerator EnemyLogic()
{
for (; ; )
{
Debug.Log("Waiting for attack");
yield return new WaitForSecondsRealtime(EnemyLogicCooldown);
currentpos = Random.Range(0, 2);
Debug.Log($"Punch, currentPos: {currentpos}");
Attacked = true;
while (!GotInput && !PenController.Instance.GotInput && period < EnemyLogicCooldown)
{
period += UnityEngine.Time.deltaTime;
yield return new WaitForEndOfFrame();
}
if (GotInput || PenController.Instance.GotInput)
{
if (currentpos == 0 && (XPressed || PenController.Instance.SwipedLeft))
{
Debug.Log("Hit");
i--;
period = 0;
}
else if (currentpos == 1 && (BPressed || PenController.Instance.SwipedRight))
{
Debug.Log("Hit");
i--;
period = 0;
}
else
{
Debug.Log("Wrong input");
Debug.Log("Miss");
period = 0;
}
}
else
{
Debug.Log("Not enough time");
Debug.Log("Miss");
period = 0;
}
Attacked = false;
ResetPadInput();
PenController.Instance.ResetPenInput();
}
}
// Update is called once per frame
void Update()
{
if (Gamepad.current.xButton.IsPressed() && !GotInput && Attacked)
{
XPressed = true;
GotInput = true;
}
if (Gamepad.current.bButton.IsPressed() && !GotInput && Attacked)
{
BPressed = true;
GotInput = true;
}
}
public void ResetPadInput()
{
XPressed = false;
BPressed = false;
GotInput = false;
}
} | 26.673077 | 96 | 0.482696 | [
"MIT"
] | MasterKiller1239/NoRTXgame | My project/Assets/PadScripts/PadController.cs | 2,774 | C# |
using GiftRegistryService.Data.Helpers;
using GiftRegistryService.Data.Model;
using System;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Linq;
using System.Threading.Tasks;
namespace GiftRegistryService.Data
{
public interface IGiftRegistryServiceContext
{
DbSet<User> Users { get; set; }
DbSet<Role> Roles { get; set; }
DbSet<Tenant> Tenants { get; set; }
DbSet<DigitalAsset> DigitalAssets { get; set; }
DbSet<Account> Accounts { get; set; }
DbSet<Profile> Profiles { get; set; }
DbSet<Feature> Features { get; set; }
DbSet<Subscription> Subscriptions { get; set; }
DbSet<Product> Products { get; set; }
DbSet<Guest> Guests { get; set; }
DbSet<Event> Events { get; set; }
DbSet<Contact> Contacts { get; set; }
DbSet<PhotoGallery> PhotoGalleries { get; set; }
DbSet<PhotoGallerySlide> PhotoGallerySlides { get; set; }
DbSet<ContentBlock> ContentBlocks { get; set; }
DbSet<Personality> Personalities { get; set; }
Task<int> SaveChangesAsync();
}
public class GiftRegistryServiceContext: DbContext, IGiftRegistryServiceContext
{
public GiftRegistryServiceContext()
:base("GiftRegistryServiceContext")
{
Configuration.ProxyCreationEnabled = false;
Configuration.LazyLoadingEnabled = false;
Configuration.AutoDetectChangesEnabled = true;
}
public DbSet<User> Users { get; set; }
public DbSet<Role> Roles { get; set; }
public DbSet<Tenant> Tenants { get; set; }
public DbSet<DigitalAsset> DigitalAssets { get; set; }
public DbSet<Account> Accounts { get; set; }
public DbSet<Profile> Profiles { get; set; }
public DbSet<Feature> Features { get; set; }
public DbSet<Subscription> Subscriptions { get; set; }
public DbSet<Product> Products { get; set; }
public DbSet<Guest> Guests { get; set; }
public DbSet<Event> Events { get; set; }
public DbSet<Contact> Contacts { get; set; }
public DbSet<PhotoGallery> PhotoGalleries { get; set; }
public DbSet<PhotoGallerySlide> PhotoGallerySlides { get; set; }
public DbSet<ContentBlock> ContentBlocks { get; set; }
public DbSet<Menu> Menus { get; set; }
public DbSet<MenuItem> MenuItems { get; set; }
public DbSet<Personality> Personalities { get; set; }
public override int SaveChanges()
{
UpdateLoggableEntries();
return base.SaveChanges();
}
public override Task<int> SaveChangesAsync()
{
UpdateLoggableEntries();
return base.SaveChangesAsync();
}
public void UpdateLoggableEntries()
{
foreach (var entity in ChangeTracker.Entries()
.Where(e => e.Entity is ILoggable && ((e.State == EntityState.Added || (e.State == EntityState.Modified))))
.Select(x => x.Entity as ILoggable))
{
entity.CreatedOn = entity.CreatedOn == default(DateTime) ? DateTime.UtcNow : entity.CreatedOn;
entity.LastModifiedOn = DateTime.UtcNow;
}
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<User>().
HasMany(u => u.Roles).
WithMany(r => r.Users).
Map(
m =>
{
m.MapLeftKey("User_Id");
m.MapRightKey("Role_Id");
m.ToTable("UserRoles");
});
var convention = new AttributeToTableAnnotationConvention<SoftDeleteAttribute, string>(
"SoftDeleteColumnName",
(type, attributes) => attributes.Single().ColumnName);
modelBuilder.Conventions.Add(convention);
}
}
} | 38.628571 | 123 | 0.589744 | [
"MIT"
] | QuinntyneBrown/GiftRegistryService | src/GiftRegistryService/Data/GiftRegistryServiceContext.cs | 4,058 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace ToolbarDemo
{
public partial class ToolbarDemoPage : ContentPage
{
public ToolbarDemoPage()
{
// Ensure link to Toolkit library.
new Xamarin.FormsBook.Toolkit.ForPlatform<object>();
InitializeComponent();
}
void OnToolbarItemClicked(object sender, EventArgs args)
{
ToolbarItem toolbarItem = (ToolbarItem)sender;
label.Text = "ToolbarItem '" + toolbarItem.Text + "' clicked";
}
}
}
| 23.357143 | 74 | 0.634557 | [
"Apache-2.0"
] | NoleHealth/xamarin-forms-book-preview-2 | Chapter13/ToolbarDemo/ToolbarDemo/ToolbarDemo/ToolbarDemoPage.xaml.cs | 656 | C# |
using System;
using System.Linq;
using JetBrains.Annotations;
namespace Archichect.Matching {
public sealed class DependencyPattern : CountPattern<string> {
[NotNull]
private readonly MarkerMatch _markerPattern;
private const string COUNT_FIELD_NAME_PATTERN = "^[#!?O]$";
private readonly Eval[] _evals;
public DependencyPattern(string pattern, bool ignoreCase) {
string[] patternParts = pattern.Split('\'');
_evals =
patternParts[0].Split('&')
.Select(element => CreateEval(element, COUNT_FIELD_NAME_PATTERN, s => s))
.ToArray();
_markerPattern = new MarkerMatch(patternParts.Length > 1 ? patternParts[1] : "", ignoreCase);
}
public bool IsMatch<TItem>(AbstractDependency<TItem> dependency) where TItem : AbstractItem<TItem> {
if (!_markerPattern.IsMatch(dependency.MarkerSet)) {
return false;
} else {
return _evals.All(e => e.Predicate(GetValue(dependency, e.LeftOrNullForConstant), GetValue(dependency, e.RightOrNullForConstant)));
}
}
private static int GetValue<TItem>(AbstractDependency<TItem> dependency, [CanBeNull]string operandOrNullForConstant) where TItem : AbstractItem<TItem> {
switch (operandOrNullForConstant) {
case null:
return 0;
case "#":
return dependency.Ct;
case "?":
return dependency.QuestionableCt;
case "!":
return dependency.BadCt;
case "O":
return Equals(dependency.UsingItem, dependency.UsedItem) ? 1 : 0;
default:
throw new ArgumentException($"Unexpected DependencyPattern operand '{operandOrNullForConstant}'");
}
}
}
} | 40.541667 | 160 | 0.579651 | [
"Apache-2.0"
] | hmmueller/Archichect | src/Archichect/Matching/DependencyPattern.cs | 1,946 | C# |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using Java.Interop.Tools.Diagnostics;
using Xamarin.Android.Build.Utilities;
namespace Xamarin.Android.Tasks
{
public static class NdkUtil {
public static bool ValidateNdkPlatform (TaskLoggingHelper log, string ndkPath, AndroidTargetArch arch, bool enableLLVM)
{
// Check that we have a compatible NDK version for the targeted ABIs.
NdkUtil.NdkVersion ndkVersion;
bool hasNdkVersion = NdkUtil.GetNdkToolchainRelease (ndkPath, out ndkVersion);
if (NdkUtil.IsNdk64BitArch(arch) && hasNdkVersion && ndkVersion.Version < 10) {
log.LogMessage (MessageImportance.High,
"The detected Android NDK version is incompatible with the targeted 64-bit architecture, " +
"please upgrade to NDK r10 or newer.");
}
// NDK r10d is buggy and cannot link x86_64 ABI shared libraries because they are 32-bits.
// See https://code.google.com/p/android/issues/detail?id=161421
if (enableLLVM && ndkVersion.Version == 10 && ndkVersion.Revision == "d" && arch == AndroidTargetArch.X86_64) {
log.LogCodedError ("XA3004", "Android NDK r10d is buggy and provides an incompatible x86_64 libm.so. " +
"See https://code.google.com/p/android/issues/detail?id=161422.");
return false;
}
if (enableLLVM && (ndkVersion.Version < 10 || (ndkVersion.Version == 10 && ndkVersion.Revision[0] < 'd'))) {
log.LogMessage (MessageImportance.High,
"The detected Android NDK version is incompatible with the targeted LLVM configuration, " +
"please upgrade to NDK r10d or newer.");
}
return true;
}
public static string GetNdkToolPrefix (string androidNdkPath, AndroidTargetArch arch)
{
var path = GetNdkTool (androidNdkPath, arch, "as");
if (path != null)
path = path.Substring (0, path.LastIndexOf ("-") + 1);
return path;
}
public static List<string> GetNdkToolchainPath(string androidNdkPath, AndroidTargetArch arch)
{
var toolchains = GetNdkToolchainDirectories (Path.Combine (androidNdkPath, "toolchains"), arch);
if (!toolchains.Any ())
Diagnostic.Error (5101,
"Toolchain directory for target {0} was not found.",
arch);
// Sort the toolchains paths in reverse so that we prefer the latest versions.
Array.Sort(toolchains);
Array.Reverse(toolchains);
return new List<string>(toolchains);
}
public static string GetNdkTool (string androidNdkPath, AndroidTargetArch arch, string tool)
{
var toolchains = GetNdkToolchainPath(androidNdkPath, arch);
string extension = OS.IsWindows ? ".exe" : string.Empty;
List<string> toolPaths = null;
foreach (var platbase in toolchains) {
string path = Path.Combine (platbase, "prebuilt", AndroidSdk.AndroidNdkHostPlatform, "bin", GetNdkToolchainPrefix (arch) + tool + extension);
if (File.Exists (path))
return path;
if (toolPaths == null)
toolPaths = new List<string>();
toolPaths.Add (path);
}
{
string path = Path.Combine (androidNdkPath, "prebuilt", AndroidSdk.AndroidNdkHostPlatform, "bin", tool);
if (File.Exists (path))
return path;
if (toolPaths == null)
toolPaths = new List<string>();
toolPaths.Add (path);
}
Diagnostic.Error (5101,
"C compiler for target {0} was not found. Tried paths: \"{1}\"",
arch, string.Join ("; ", toolPaths));
return null;
}
public static string GetNdkPlatformIncludePath (string androidNdkPath, AndroidTargetArch arch, int level)
{
string path = Path.Combine (androidNdkPath, "platforms", "android-" + level, "arch-" + GetPlatformArch (arch), "usr", "include");
if (!Directory.Exists (path))
throw new InvalidOperationException (String.Format ("Platform header files for target {0} and API Level {1} was not found. Expected path is \"{2}\"", arch, level, path));
return path;
}
public static string GetNdkPlatformLibPath (string androidNdkPath, AndroidTargetArch arch, int level)
{
string path = Path.Combine (androidNdkPath, "platforms", "android-" + level, "arch-" + GetPlatformArch (arch), "usr", "lib");
if (!Directory.Exists (path))
throw new InvalidOperationException (String.Format ("Platform library directory for target {0} and API Level {1} was not found. Expected path is \"{2}\"", arch, level, path));
return path;
}
static string GetPlatformArch (AndroidTargetArch arch)
{
switch (arch) {
case AndroidTargetArch.Arm:
return "arm";
case AndroidTargetArch.Arm64:
return "arm64";
case AndroidTargetArch.Mips:
return "mips";
case AndroidTargetArch.X86:
return "x86";
case AndroidTargetArch.X86_64:
return "x86_64";
}
return null;
}
static string[] GetNdkToolchainDirectories (string toolchainsPath, AndroidTargetArch arch)
{
if (!Directory.Exists (toolchainsPath))
Diagnostic.Error (5101,
"Missing Android NDK toolchains directory '{0}'. Please install the Android NDK.",
toolchainsPath);
switch (arch) {
case AndroidTargetArch.Arm:
return Directory.GetDirectories (toolchainsPath, "arm-linux-androideabi-*");
case AndroidTargetArch.Arm64:
return Directory.GetDirectories (toolchainsPath, "aarch64-linux-android-*");
case AndroidTargetArch.X86:
return Directory.GetDirectories (toolchainsPath, "x86-*");
case AndroidTargetArch.X86_64:
return Directory.GetDirectories (toolchainsPath, "x86_64-*");
case AndroidTargetArch.Mips:
return Directory.GetDirectories (toolchainsPath, "mipsel-linux-android-*");
default: // match any directory that contains the arch name.
return Directory.GetDirectories (toolchainsPath, "*" + arch + "*");
}
}
static string GetNdkToolchainPrefix (AndroidTargetArch arch)
{
switch (arch) {
case AndroidTargetArch.Arm:
return "arm-linux-androideabi-";
case AndroidTargetArch.Arm64:
return "aarch64-linux-android-";
case AndroidTargetArch.X86:
return "i686-linux-android-";
case AndroidTargetArch.X86_64:
return "x86_64-linux-android-";
case AndroidTargetArch.Mips:
return "mipsel-linux-android-";
default:
// return empty. Since this method returns the "prefix", the resulting
// tool path just becomes the tool name i.e. "gcc" becomes "gcc".
// This should work for any custom arbitrary platform.
return String.Empty;
}
}
static bool GetNdkToolchainRelease (string androidNdkPath, out string version)
{
var releaseVersionPath = Path.Combine (androidNdkPath, "RELEASE.txt");
if (!File.Exists (releaseVersionPath))
{
version = string.Empty;
return false;
}
version = File.ReadAllText (releaseVersionPath).Trim();
return true;
}
static bool GetNdkToolchainSourceProperties (string androidNdkPath, out NdkVersion version)
{
version = new NdkVersion ();
var sourcePropertiesPath = Path.Combine (androidNdkPath, "source.properties");
if (!File.Exists (sourcePropertiesPath)) {
return false;
}
var match = Regex.Match (File.ReadAllText (sourcePropertiesPath).Trim (), "^Pkg.Revision\\s*=\\s*([.0-9]+)$", RegexOptions.Multiline);
if (!match.Success) {
return false;
}
var numbers = match.Groups[1].Value.Trim().Split ('.');
version.Version = int.Parse (numbers [0]);
version.Revision = Convert.ToChar (int.Parse (numbers [1]) + (int)'a').ToString ();
return true;
}
public struct NdkVersion
{
public int Version;
public string Revision;
}
public static bool GetNdkToolchainRelease (string androidNdkPath, out NdkVersion ndkVersion)
{
ndkVersion = new NdkVersion ();
string version;
if (!GetNdkToolchainRelease (androidNdkPath, out version)) {
if (GetNdkToolchainSourceProperties (androidNdkPath, out ndkVersion))
return true;
return false;
}
var match = Regex.Match(version, @"r(\d+)\s*(.*)\s+.*");
if( !match.Success)
return false;
ndkVersion.Version = int.Parse (match.Groups[1].Value.Trim());
ndkVersion.Revision = match.Groups[2].Value.Trim().ToLowerInvariant();
return true;
}
public static bool IsNdk64BitArch (AndroidTargetArch arch)
{
return arch == AndroidTargetArch.Arm64 || arch == AndroidTargetArch.X86_64;
}
}
}
| 35.565401 | 179 | 0.703642 | [
"BSD-3-Clause"
] | jamesmontemagno/xamarin-android | src/Xamarin.Android.Build.Tasks/Tasks/NdkUtils.cs | 8,429 | C# |
namespace _15.Substring_Debugging
{
using System;
public class Substring_Debugging
{
public static void Main()
{
string text = Console.ReadLine();
int takeChars = int.Parse(Console.ReadLine());
bool match = false;
for (int i = 0; i < text.Length; i++)
{
if (text[i] == 'p')
{
match = true;
int endIndex = takeChars + 1;
string matchedString = string.Empty;
if (i + endIndex <= text.Length)
{
matchedString = text.Substring(i, endIndex);
}
else
{
matchedString = text.Substring(i);
}
Console.WriteLine(matchedString);
i += takeChars;
}
}
if (!match)
{
Console.WriteLine("no");
}
}
}
}
| 24.363636 | 68 | 0.377799 | [
"MIT"
] | Pazzobg/02.01.Programming-Fundamentals-Class | 04.Methods-and-Debugging/04.Methods-and-Debugging-Exercises/15.Substring-Debugging/Substring-Debugging.cs | 1,074 | C# |
using System.Threading.Tasks;
namespace UGF.Builder.Runtime
{
public interface IBuilderAsync<in TArguments, TResult> : IBuilderAsync
{
Task<T> BuildAsync<T>(TArguments arguments) where T : TResult;
Task<TResult> BuildAsync(TArguments arguments);
}
}
| 25.454545 | 74 | 0.710714 | [
"MIT"
] | unity-game-framework/ugf-builder | Packages/UGF.Builder/Runtime/IBuilderAsync`2.cs | 282 | C# |
// dnlib: See LICENSE.txt for more info
using System;
using System.Collections.Generic;
using System.IO;
using dnlib.DotNet.MD;
using dnlib.IO;
namespace dnlib.DotNet {
/// <summary>
/// Helps <see cref="SignatureReader"/> resolve types
/// </summary>
public interface ISignatureReaderHelper {
/// <summary>
/// Resolves a <see cref="ITypeDefOrRef"/>
/// </summary>
/// <param name="codedToken">A <c>TypeDefOrRef</c> coded token</param>
/// <param name="gpContext">Generic parameter context</param>
/// <returns>A <see cref="ITypeDefOrRef"/> or <c>null</c> if <paramref name="codedToken"/>
/// is invalid</returns>
ITypeDefOrRef ResolveTypeDefOrRef(uint codedToken, GenericParamContext gpContext);
/// <summary>
/// Converts the address of a <see cref="Type"/> to a <see cref="TypeSig"/>
/// </summary>
/// <seealso cref="Emit.MethodTableToTypeConverter"/>
/// <param name="address">Address of <see cref="Type"/>. This is also known as the
/// method table and has the same value as <see cref="RuntimeTypeHandle.Value"/></param>
/// <returns>A <see cref="TypeSig"/> or <c>null</c> if not supported</returns>
TypeSig ConvertRTInternalAddress(IntPtr address);
}
/// <summary>
/// Reads signatures from the #Blob stream
/// </summary>
public struct SignatureReader {
// .NET Core and .NET Framework limit arrays to 32 dimensions. Use a bigger limit
// so it's possible to read some bad MD, but not big enough to allocate a ton of mem.
const uint MaxArrayRank = 64;
readonly ISignatureReaderHelper helper;
readonly ICorLibTypes corLibTypes;
DataReader reader;
readonly GenericParamContext gpContext;
RecursionCounter recursionCounter;
/// <summary>
/// Reads a signature from the #Blob stream
/// </summary>
/// <param name="readerModule">Reader module</param>
/// <param name="sig">#Blob stream offset of signature</param>
/// <returns>A new <see cref="CallingConventionSig"/> instance or <c>null</c> if
/// <paramref name="sig"/> is invalid.</returns>
public static CallingConventionSig ReadSig(ModuleDefMD readerModule, uint sig) =>
ReadSig(readerModule, sig, new GenericParamContext());
/// <summary>
/// Reads a signature from the #Blob stream
/// </summary>
/// <param name="readerModule">Reader module</param>
/// <param name="sig">#Blob stream offset of signature</param>
/// <param name="gpContext">Generic parameter context</param>
/// <returns>A new <see cref="CallingConventionSig"/> instance or <c>null</c> if
/// <paramref name="sig"/> is invalid.</returns>
public static CallingConventionSig ReadSig(ModuleDefMD readerModule, uint sig, GenericParamContext gpContext) {
try {
var reader = new SignatureReader(readerModule, sig, gpContext);
if (reader.reader.Length == 0)
return null;
var csig = reader.ReadSig();
if (!(csig is null))
csig.ExtraData = reader.GetExtraData();
return csig;
}
catch {
return null;
}
}
/// <summary>
/// Reads a <see cref="CallingConventionSig"/> signature
/// </summary>
/// <param name="module">The module where the signature is located in</param>
/// <param name="signature">The signature data</param>
/// <returns>A new <see cref="CallingConventionSig"/> instance or <c>null</c> if
/// <paramref name="signature"/> is invalid.</returns>
public static CallingConventionSig ReadSig(ModuleDefMD module, byte[] signature) =>
ReadSig(module, module.CorLibTypes, ByteArrayDataReaderFactory.CreateReader(signature), new GenericParamContext());
/// <summary>
/// Reads a <see cref="CallingConventionSig"/> signature
/// </summary>
/// <param name="module">The module where the signature is located in</param>
/// <param name="signature">The signature data</param>
/// <param name="gpContext">Generic parameter context</param>
/// <returns>A new <see cref="CallingConventionSig"/> instance or <c>null</c> if
/// <paramref name="signature"/> is invalid.</returns>
public static CallingConventionSig ReadSig(ModuleDefMD module, byte[] signature, GenericParamContext gpContext) =>
ReadSig(module, module.CorLibTypes, ByteArrayDataReaderFactory.CreateReader(signature), gpContext);
/// <summary>
/// Reads a <see cref="CallingConventionSig"/> signature
/// </summary>
/// <param name="module">The module where the signature is located in</param>
/// <param name="signature">The signature reader</param>
/// <returns>A new <see cref="CallingConventionSig"/> instance or <c>null</c> if
/// <paramref name="signature"/> is invalid.</returns>
public static CallingConventionSig ReadSig(ModuleDefMD module, DataReader signature) =>
ReadSig(module, module.CorLibTypes, signature, new GenericParamContext());
/// <summary>
/// Reads a <see cref="CallingConventionSig"/> signature
/// </summary>
/// <param name="module">The module where the signature is located in</param>
/// <param name="signature">The signature reader</param>
/// <param name="gpContext">Generic parameter context</param>
/// <returns>A new <see cref="CallingConventionSig"/> instance or <c>null</c> if
/// <paramref name="signature"/> is invalid.</returns>
public static CallingConventionSig ReadSig(ModuleDefMD module, DataReader signature, GenericParamContext gpContext) =>
ReadSig(module, module.CorLibTypes, signature, gpContext);
/// <summary>
/// Reads a <see cref="CallingConventionSig"/> signature
/// </summary>
/// <param name="helper">Token resolver</param>
/// <param name="corLibTypes">A <see cref="ICorLibTypes"/> instance</param>
/// <param name="signature">The signature data</param>
/// <returns>A new <see cref="CallingConventionSig"/> instance or <c>null</c> if
/// <paramref name="signature"/> is invalid.</returns>
public static CallingConventionSig ReadSig(ISignatureReaderHelper helper, ICorLibTypes corLibTypes, byte[] signature) =>
ReadSig(helper, corLibTypes, ByteArrayDataReaderFactory.CreateReader(signature), new GenericParamContext());
/// <summary>
/// Reads a <see cref="CallingConventionSig"/> signature
/// </summary>
/// <param name="helper">Token resolver</param>
/// <param name="corLibTypes">A <see cref="ICorLibTypes"/> instance</param>
/// <param name="signature">The signature data</param>
/// <param name="gpContext">Generic parameter context</param>
/// <returns>A new <see cref="CallingConventionSig"/> instance or <c>null</c> if
/// <paramref name="signature"/> is invalid.</returns>
public static CallingConventionSig ReadSig(ISignatureReaderHelper helper, ICorLibTypes corLibTypes, byte[] signature, GenericParamContext gpContext) =>
ReadSig(helper, corLibTypes, ByteArrayDataReaderFactory.CreateReader(signature), gpContext);
/// <summary>
/// Reads a <see cref="CallingConventionSig"/> signature
/// </summary>
/// <param name="helper">Token resolver</param>
/// <param name="corLibTypes">A <see cref="ICorLibTypes"/> instance</param>
/// <param name="signature">The signature reader</param>
/// <returns>A new <see cref="CallingConventionSig"/> instance or <c>null</c> if
/// <paramref name="signature"/> is invalid.</returns>
public static CallingConventionSig ReadSig(ISignatureReaderHelper helper, ICorLibTypes corLibTypes, DataReader signature) =>
ReadSig(helper, corLibTypes, signature, new GenericParamContext());
/// <summary>
/// Reads a <see cref="CallingConventionSig"/> signature
/// </summary>
/// <param name="helper">Token resolver</param>
/// <param name="corLibTypes">A <see cref="ICorLibTypes"/> instance</param>
/// <param name="signature">The signature reader</param>
/// <param name="gpContext">Generic parameter context</param>
/// <returns>A new <see cref="CallingConventionSig"/> instance or <c>null</c> if
/// <paramref name="signature"/> is invalid.</returns>
public static CallingConventionSig ReadSig(ISignatureReaderHelper helper, ICorLibTypes corLibTypes, DataReader signature, GenericParamContext gpContext) {
try {
var reader = new SignatureReader(helper, corLibTypes, ref signature, gpContext);
if (reader.reader.Length == 0)
return null;
return reader.ReadSig();
}
catch {
return null;
}
}
/// <summary>
/// Reads a type signature from the #Blob stream
/// </summary>
/// <param name="readerModule">Reader module</param>
/// <param name="sig">#Blob stream offset of signature</param>
/// <returns>A new <see cref="TypeSig"/> instance or <c>null</c> if
/// <paramref name="sig"/> is invalid.</returns>
public static TypeSig ReadTypeSig(ModuleDefMD readerModule, uint sig) =>
ReadTypeSig(readerModule, sig, new GenericParamContext());
/// <summary>
/// Reads a type signature from the #Blob stream
/// </summary>
/// <param name="readerModule">Reader module</param>
/// <param name="sig">#Blob stream offset of signature</param>
/// <param name="gpContext">Generic parameter context</param>
/// <returns>A new <see cref="TypeSig"/> instance or <c>null</c> if
/// <paramref name="sig"/> is invalid.</returns>
public static TypeSig ReadTypeSig(ModuleDefMD readerModule, uint sig, GenericParamContext gpContext) {
try {
var reader = new SignatureReader(readerModule, sig, gpContext);
return reader.ReadType();
}
catch {
return null;
}
}
/// <summary>
/// Reads a type signature from the #Blob stream
/// </summary>
/// <param name="readerModule">Reader module</param>
/// <param name="sig">#Blob stream offset of signature</param>
/// <param name="extraData">If there's any extra data after the signature, it's saved
/// here, else this will be <c>null</c></param>
/// <returns>A new <see cref="TypeSig"/> instance or <c>null</c> if
/// <paramref name="sig"/> is invalid.</returns>
public static TypeSig ReadTypeSig(ModuleDefMD readerModule, uint sig, out byte[] extraData) =>
ReadTypeSig(readerModule, sig, new GenericParamContext(), out extraData);
/// <summary>
/// Reads a type signature from the #Blob stream
/// </summary>
/// <param name="readerModule">Reader module</param>
/// <param name="sig">#Blob stream offset of signature</param>
/// <param name="gpContext">Generic parameter context</param>
/// <param name="extraData">If there's any extra data after the signature, it's saved
/// here, else this will be <c>null</c></param>
/// <returns>A new <see cref="TypeSig"/> instance or <c>null</c> if
/// <paramref name="sig"/> is invalid.</returns>
public static TypeSig ReadTypeSig(ModuleDefMD readerModule, uint sig, GenericParamContext gpContext, out byte[] extraData) {
try {
var reader = new SignatureReader(readerModule, sig, gpContext);
TypeSig ts;
try {
ts = reader.ReadType();
}
catch (IOException) {
reader.reader.Position = 0;
ts = null;
}
extraData = reader.GetExtraData();
return ts;
}
catch {
extraData = null;
return null;
}
}
/// <summary>
/// Reads a <see cref="TypeSig"/> signature
/// </summary>
/// <param name="module">The module where the signature is located in</param>
/// <param name="signature">The signature data</param>
/// <returns>A new <see cref="TypeSig"/> instance or <c>null</c> if
/// <paramref name="signature"/> is invalid.</returns>
public static TypeSig ReadTypeSig(ModuleDefMD module, byte[] signature) =>
ReadTypeSig(module, module.CorLibTypes, ByteArrayDataReaderFactory.CreateReader(signature), new GenericParamContext());
/// <summary>
/// Reads a <see cref="TypeSig"/> signature
/// </summary>
/// <param name="module">The module where the signature is located in</param>
/// <param name="signature">The signature data</param>
/// <param name="gpContext">Generic parameter context</param>
/// <returns>A new <see cref="TypeSig"/> instance or <c>null</c> if
/// <paramref name="signature"/> is invalid.</returns>
public static TypeSig ReadTypeSig(ModuleDefMD module, byte[] signature, GenericParamContext gpContext) =>
ReadTypeSig(module, module.CorLibTypes, ByteArrayDataReaderFactory.CreateReader(signature), gpContext);
/// <summary>
/// Reads a <see cref="TypeSig"/> signature
/// </summary>
/// <param name="module">The module where the signature is located in</param>
/// <param name="signature">The signature reader</param>
/// <returns>A new <see cref="TypeSig"/> instance or <c>null</c> if
/// <paramref name="signature"/> is invalid.</returns>
public static TypeSig ReadTypeSig(ModuleDefMD module, DataReader signature) =>
ReadTypeSig(module, module.CorLibTypes, signature, new GenericParamContext());
/// <summary>
/// Reads a <see cref="TypeSig"/> signature
/// </summary>
/// <param name="module">The module where the signature is located in</param>
/// <param name="signature">The signature reader</param>
/// <param name="gpContext">Generic parameter context</param>
/// <returns>A new <see cref="TypeSig"/> instance or <c>null</c> if
/// <paramref name="signature"/> is invalid.</returns>
public static TypeSig ReadTypeSig(ModuleDefMD module, DataReader signature, GenericParamContext gpContext) =>
ReadTypeSig(module, module.CorLibTypes, signature, gpContext);
/// <summary>
/// Reads a <see cref="TypeSig"/> signature
/// </summary>
/// <param name="helper">Token resolver</param>
/// <param name="corLibTypes">A <see cref="ICorLibTypes"/> instance</param>
/// <param name="signature">The signature data</param>
/// <returns>A new <see cref="TypeSig"/> instance or <c>null</c> if
/// <paramref name="signature"/> is invalid.</returns>
public static TypeSig ReadTypeSig(ISignatureReaderHelper helper, ICorLibTypes corLibTypes, byte[] signature) =>
ReadTypeSig(helper, corLibTypes, ByteArrayDataReaderFactory.CreateReader(signature), new GenericParamContext());
/// <summary>
/// Reads a <see cref="TypeSig"/> signature
/// </summary>
/// <param name="helper">Token resolver</param>
/// <param name="corLibTypes">A <see cref="ICorLibTypes"/> instance</param>
/// <param name="signature">The signature data</param>
/// <param name="gpContext">Generic parameter context</param>
/// <returns>A new <see cref="TypeSig"/> instance or <c>null</c> if
/// <paramref name="signature"/> is invalid.</returns>
public static TypeSig ReadTypeSig(ISignatureReaderHelper helper, ICorLibTypes corLibTypes, byte[] signature, GenericParamContext gpContext) =>
ReadTypeSig(helper, corLibTypes, ByteArrayDataReaderFactory.CreateReader(signature), gpContext);
/// <summary>
/// Reads a <see cref="TypeSig"/> signature
/// </summary>
/// <param name="helper">Token resolver</param>
/// <param name="corLibTypes">A <see cref="ICorLibTypes"/> instance</param>
/// <param name="signature">The signature reader</param>
/// <returns>A new <see cref="TypeSig"/> instance or <c>null</c> if
/// <paramref name="signature"/> is invalid.</returns>
public static TypeSig ReadTypeSig(ISignatureReaderHelper helper, ICorLibTypes corLibTypes, DataReader signature) =>
ReadTypeSig(helper, corLibTypes, signature, new GenericParamContext());
/// <summary>
/// Reads a <see cref="TypeSig"/> signature
/// </summary>
/// <param name="helper">Token resolver</param>
/// <param name="corLibTypes">A <see cref="ICorLibTypes"/> instance</param>
/// <param name="signature">The signature reader</param>
/// <param name="gpContext">Generic parameter context</param>
/// <returns>A new <see cref="TypeSig"/> instance or <c>null</c> if
/// <paramref name="signature"/> is invalid.</returns>
public static TypeSig ReadTypeSig(ISignatureReaderHelper helper, ICorLibTypes corLibTypes, DataReader signature, GenericParamContext gpContext) =>
ReadTypeSig(helper, corLibTypes, signature, gpContext, out var extraData);
/// <summary>
/// Reads a <see cref="TypeSig"/> signature
/// </summary>
/// <param name="helper">Token resolver</param>
/// <param name="corLibTypes">A <see cref="ICorLibTypes"/> instance</param>
/// <param name="signature">The signature data</param>
/// <param name="gpContext">Generic parameter context</param>
/// <param name="extraData">If there's any extra data after the signature, it's saved
/// here, else this will be <c>null</c></param>
/// <returns>A new <see cref="TypeSig"/> instance or <c>null</c> if
/// <paramref name="signature"/> is invalid.</returns>
public static TypeSig ReadTypeSig(ISignatureReaderHelper helper, ICorLibTypes corLibTypes, byte[] signature, GenericParamContext gpContext, out byte[] extraData) =>
ReadTypeSig(helper, corLibTypes, ByteArrayDataReaderFactory.CreateReader(signature), gpContext, out extraData);
/// <summary>
/// Reads a <see cref="TypeSig"/> signature
/// </summary>
/// <param name="helper">Token resolver</param>
/// <param name="corLibTypes">A <see cref="ICorLibTypes"/> instance</param>
/// <param name="signature">The signature reader</param>
/// <param name="gpContext">Generic parameter context</param>
/// <param name="extraData">If there's any extra data after the signature, it's saved
/// here, else this will be <c>null</c></param>
/// <returns>A new <see cref="TypeSig"/> instance or <c>null</c> if
/// <paramref name="signature"/> is invalid.</returns>
public static TypeSig ReadTypeSig(ISignatureReaderHelper helper, ICorLibTypes corLibTypes, DataReader signature, GenericParamContext gpContext, out byte[] extraData) {
try {
var reader = new SignatureReader(helper, corLibTypes, ref signature, gpContext);
TypeSig ts;
try {
ts = reader.ReadType();
}
catch (IOException) {
reader.reader.Position = 0;
ts = null;
}
extraData = reader.GetExtraData();
return ts;
}
catch {
extraData = null;
return null;
}
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="readerModule">Reader module</param>
/// <param name="sig">#Blob stream offset of signature</param>
/// <param name="gpContext">Generic parameter context</param>
SignatureReader(ModuleDefMD readerModule, uint sig, GenericParamContext gpContext) {
helper = readerModule;
corLibTypes = readerModule.CorLibTypes;
reader = readerModule.BlobStream.CreateReader(sig);
this.gpContext = gpContext;
recursionCounter = new RecursionCounter();
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="helper">Token resolver</param>
/// <param name="corLibTypes">A <see cref="ICorLibTypes"/> instance</param>
/// <param name="reader">The signature data</param>
/// <param name="gpContext">Generic parameter context</param>
SignatureReader(ISignatureReaderHelper helper, ICorLibTypes corLibTypes, ref DataReader reader, GenericParamContext gpContext) {
this.helper = helper;
this.corLibTypes = corLibTypes;
this.reader = reader;
this.gpContext = gpContext;
recursionCounter = new RecursionCounter();
}
byte[] GetExtraData() {
if (reader.Position == reader.Length)
return null;
return reader.ReadRemainingBytes();
}
/// <summary>
/// Reads the signature
/// </summary>
/// <returns>A new <see cref="CallingConventionSig"/> instance or <c>null</c> if invalid signature</returns>
CallingConventionSig ReadSig() {
if (!recursionCounter.Increment())
return null;
CallingConventionSig result;
var callingConvention = (CallingConvention)reader.ReadByte();
switch (callingConvention & CallingConvention.Mask) {
case CallingConvention.Default:
case CallingConvention.C:
case CallingConvention.StdCall:
case CallingConvention.ThisCall:
case CallingConvention.FastCall:
case CallingConvention.VarArg:
case CallingConvention.NativeVarArg:
case CallingConvention.Unmanaged:
result = ReadMethod(callingConvention);
break;
case CallingConvention.Field:
result = ReadField(callingConvention);
break;
case CallingConvention.LocalSig:
result = ReadLocalSig(callingConvention);
break;
case CallingConvention.Property:
result = ReadProperty(callingConvention);
break;
case CallingConvention.GenericInst:
result = ReadGenericInstMethod(callingConvention);
break;
default:
result = null;
break;
}
recursionCounter.Decrement();
return result;
}
/// <summary>
/// Reads a <see cref="FieldSig"/>
/// </summary>
/// <param name="callingConvention">First byte of signature</param>
/// <returns>A new <see cref="FieldSig"/> instance</returns>
FieldSig ReadField(CallingConvention callingConvention) => new FieldSig(callingConvention, ReadType());
/// <summary>
/// Reads a <see cref="MethodSig"/>
/// </summary>
/// <param name="callingConvention">First byte of signature</param>
/// <returns>A new <see cref="MethodSig"/> instance</returns>
MethodSig ReadMethod(CallingConvention callingConvention) => ReadSig(new MethodSig(callingConvention));
/// <summary>
/// Reads a <see cref="PropertySig"/>
/// </summary>
/// <param name="callingConvention">First byte of signature</param>
/// <returns>A new <see cref="PropertySig"/> instance</returns>
PropertySig ReadProperty(CallingConvention callingConvention) => ReadSig(new PropertySig(callingConvention));
T ReadSig<T>(T methodSig) where T : MethodBaseSig {
if (methodSig.Generic) {
if (!reader.TryReadCompressedUInt32(out uint count))
return null;
methodSig.GenParamCount = count;
}
if (!reader.TryReadCompressedUInt32(out uint numParams))
return null;
methodSig.RetType = ReadType();
var parameters = methodSig.Params;
for (uint i = 0; i < numParams; i++) {
var type = ReadType();
if (type is SentinelSig) {
if (methodSig.ParamsAfterSentinel is null)
methodSig.ParamsAfterSentinel = parameters = new List<TypeSig>((int)(numParams - i));
i--;
}
else
parameters.Add(type);
}
return methodSig;
}
/// <summary>
/// Reads a <see cref="LocalSig"/>
/// </summary>
/// <param name="callingConvention">First byte of signature</param>
/// <returns>A new <see cref="LocalSig"/> instance</returns>
LocalSig ReadLocalSig(CallingConvention callingConvention) {
if (!reader.TryReadCompressedUInt32(out uint count))
return null;
var sig = new LocalSig(callingConvention, count);
var locals = sig.Locals;
for (uint i = 0; i < count; i++)
locals.Add(ReadType());
return sig;
}
/// <summary>
/// Reads a <see cref="GenericInstMethodSig"/>
/// </summary>
/// <param name="callingConvention">First byte of signature</param>
/// <returns>A new <see cref="GenericInstMethodSig"/> instance</returns>
GenericInstMethodSig ReadGenericInstMethod(CallingConvention callingConvention) {
if (!reader.TryReadCompressedUInt32(out uint count))
return null;
var sig = new GenericInstMethodSig(callingConvention, count);
var args = sig.GenericArguments;
for (uint i = 0; i < count; i++)
args.Add(ReadType());
return sig;
}
/// <summary>
/// Reads the next type
/// </summary>
/// <returns>A new <see cref="TypeSig"/> instance or <c>null</c> if invalid element type</returns>
TypeSig ReadType() {
if (!recursionCounter.Increment())
return null;
uint num, i;
TypeSig nextType, result = null;
switch ((ElementType)reader.ReadByte()) {
case ElementType.Void: result = corLibTypes.Void; break;
case ElementType.Boolean: result = corLibTypes.Boolean; break;
case ElementType.Char: result = corLibTypes.Char; break;
case ElementType.I1: result = corLibTypes.SByte; break;
case ElementType.U1: result = corLibTypes.Byte; break;
case ElementType.I2: result = corLibTypes.Int16; break;
case ElementType.U2: result = corLibTypes.UInt16; break;
case ElementType.I4: result = corLibTypes.Int32; break;
case ElementType.U4: result = corLibTypes.UInt32; break;
case ElementType.I8: result = corLibTypes.Int64; break;
case ElementType.U8: result = corLibTypes.UInt64; break;
case ElementType.R4: result = corLibTypes.Single; break;
case ElementType.R8: result = corLibTypes.Double; break;
case ElementType.String: result = corLibTypes.String; break;
case ElementType.TypedByRef:result = corLibTypes.TypedReference; break;
case ElementType.I: result = corLibTypes.IntPtr; break;
case ElementType.U: result = corLibTypes.UIntPtr; break;
case ElementType.Object: result = corLibTypes.Object; break;
case ElementType.Ptr: result = new PtrSig(ReadType()); break;
case ElementType.ByRef: result = new ByRefSig(ReadType()); break;
case ElementType.ValueType: result = new ValueTypeSig(ReadTypeDefOrRef(false)); break;
case ElementType.Class: result = new ClassSig(ReadTypeDefOrRef(false)); break;
case ElementType.FnPtr: result = new FnPtrSig(ReadSig()); break;
case ElementType.SZArray: result = new SZArraySig(ReadType()); break;
case ElementType.CModReqd: result = new CModReqdSig(ReadTypeDefOrRef(true), ReadType()); break;
case ElementType.CModOpt: result = new CModOptSig(ReadTypeDefOrRef(true), ReadType()); break;
case ElementType.Sentinel: result = new SentinelSig(); break;
case ElementType.Pinned: result = new PinnedSig(ReadType()); break;
case ElementType.Var:
if (!reader.TryReadCompressedUInt32(out num))
break;
result = new GenericVar(num, gpContext.Type);
break;
case ElementType.MVar:
if (!reader.TryReadCompressedUInt32(out num))
break;
result = new GenericMVar(num, gpContext.Method);
break;
case ElementType.ValueArray:
nextType = ReadType();
if (!reader.TryReadCompressedUInt32(out num))
break;
result = new ValueArraySig(nextType, num);
break;
case ElementType.Module:
if (!reader.TryReadCompressedUInt32(out num))
break;
result = new ModuleSig(num, ReadType());
break;
case ElementType.GenericInst:
nextType = ReadType();
if (!reader.TryReadCompressedUInt32(out num))
break;
var genericInstSig = new GenericInstSig(nextType as ClassOrValueTypeSig, num);
var args = genericInstSig.GenericArguments;
for (i = 0; i < num; i++)
args.Add(ReadType());
result = genericInstSig;
break;
case ElementType.Array:
nextType = ReadType();
uint rank;
if (!reader.TryReadCompressedUInt32(out rank))
break;
if (rank > MaxArrayRank)
break;
if (rank == 0) {
result = new ArraySig(nextType, rank);
break;
}
if (!reader.TryReadCompressedUInt32(out num))
break;
if (num > MaxArrayRank)
break;
var sizes = new List<uint>((int)num);
for (i = 0; i < num; i++) {
if (!reader.TryReadCompressedUInt32(out uint size))
goto exit;
sizes.Add(size);
}
if (!reader.TryReadCompressedUInt32(out num))
break;
if (num > MaxArrayRank)
break;
var lowerBounds = new List<int>((int)num);
for (i = 0; i < num; i++) {
if (!reader.TryReadCompressedInt32(out int size))
goto exit;
lowerBounds.Add(size);
}
result = new ArraySig(nextType, rank, sizes, lowerBounds);
break;
case ElementType.Internal:
IntPtr address;
if (IntPtr.Size == 4)
address = new IntPtr(reader.ReadInt32());
else
address = new IntPtr(reader.ReadInt64());
result = helper.ConvertRTInternalAddress(address);
break;
case ElementType.End:
case ElementType.R:
default:
result = null;
break;
}
exit:
recursionCounter.Decrement();
return result;
}
ITypeDefOrRef ReadTypeDefOrRef(bool allowTypeSpec) {
if (!reader.TryReadCompressedUInt32(out uint codedToken))
return null;
if (!allowTypeSpec && CodedToken.TypeDefOrRef.Decode2(codedToken).Table == Table.TypeSpec)
return null;
return helper.ResolveTypeDefOrRef(codedToken, default);
}
}
}
| 40.922059 | 169 | 0.694326 | [
"MIT"
] | AnakinSklavenwalker/dnlib | src/DotNet/SignatureReader.cs | 27,827 | C# |
// Decompiled with JetBrains decompiler
// Type: AudioClipPlayer
// Assembly: Assembly-CSharp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// MVID: 5F8D6662-C74B-4D30-A4EA-D74F7A9A95B9
// Assembly location: C:\YandereSimulator\YandereSimulator_Data\Managed\Assembly-CSharp.dll
using UnityEngine;
public static class AudioClipPlayer
{
public static void Play(
AudioClip clip,
Vector3 position,
float minDistance,
float maxDistance,
out GameObject clipOwner,
float playerY)
{
GameObject gameObject = new GameObject("AudioClip_" + clip.name);
gameObject.transform.position = position;
AudioSource audioSource = gameObject.AddComponent<AudioSource>();
audioSource.clip = clip;
audioSource.Play();
Object.Destroy((Object) gameObject, clip.length);
audioSource.rolloffMode = AudioRolloffMode.Linear;
audioSource.minDistance = minDistance;
audioSource.maxDistance = maxDistance;
audioSource.spatialBlend = 1f;
clipOwner = gameObject;
float y = gameObject.transform.position.y;
audioSource.volume = (double) playerY < (double) y - 2.0 ? 0.0f : 1f;
}
public static void PlayAttached(
AudioClip clip,
Vector3 position,
Transform attachment,
float minDistance,
float maxDistance,
out GameObject clipOwner,
float playerY)
{
GameObject gameObject = new GameObject("AudioClip_" + clip.name);
gameObject.transform.position = position;
gameObject.transform.parent = attachment;
AudioSource audioSource = gameObject.AddComponent<AudioSource>();
audioSource.clip = clip;
audioSource.Play();
Object.Destroy((Object) gameObject, clip.length);
audioSource.rolloffMode = AudioRolloffMode.Linear;
audioSource.minDistance = minDistance;
audioSource.maxDistance = maxDistance;
audioSource.spatialBlend = 1f;
clipOwner = gameObject;
float y = gameObject.transform.position.y;
audioSource.volume = (double) playerY < (double) y - 2.0 ? 0.0f : 1f;
}
public static void PlayAttached(
AudioClip clip,
Transform attachment,
float minDistance,
float maxDistance)
{
GameObject gameObject = new GameObject("AudioClip_" + clip.name);
gameObject.transform.parent = attachment;
gameObject.transform.localPosition = Vector3.zero;
AudioSource audioSource = gameObject.AddComponent<AudioSource>();
audioSource.clip = clip;
audioSource.Play();
Object.Destroy((Object) gameObject, clip.length);
audioSource.rolloffMode = AudioRolloffMode.Linear;
audioSource.minDistance = minDistance;
audioSource.maxDistance = maxDistance;
audioSource.spatialBlend = 1f;
}
public static void Play(
AudioClip clip,
Vector3 position,
float minDistance,
float maxDistance,
out GameObject clipOwner,
out float clipLength)
{
GameObject gameObject = new GameObject("AudioClip_" + clip.name);
gameObject.transform.position = position;
AudioSource audioSource = gameObject.AddComponent<AudioSource>();
audioSource.clip = clip;
audioSource.Play();
Object.Destroy((Object) gameObject, clip.length);
clipLength = clip.length;
audioSource.rolloffMode = AudioRolloffMode.Linear;
audioSource.minDistance = minDistance;
audioSource.maxDistance = maxDistance;
audioSource.spatialBlend = 1f;
clipOwner = gameObject;
}
public static void Play(
AudioClip clip,
Vector3 position,
float minDistance,
float maxDistance,
out GameObject clipOwner)
{
GameObject gameObject = new GameObject("AudioClip_" + clip.name);
gameObject.transform.position = position;
AudioSource audioSource = gameObject.AddComponent<AudioSource>();
audioSource.clip = clip;
audioSource.Play();
Object.Destroy((Object) gameObject, clip.length);
audioSource.rolloffMode = AudioRolloffMode.Linear;
audioSource.minDistance = minDistance;
audioSource.maxDistance = maxDistance;
audioSource.spatialBlend = 1f;
clipOwner = gameObject;
}
public static void Play2D(AudioClip clip, Vector3 position)
{
GameObject gameObject = new GameObject("AudioClip_" + clip.name);
gameObject.transform.position = position;
AudioSource audioSource = gameObject.AddComponent<AudioSource>();
audioSource.clip = clip;
audioSource.Play();
Object.Destroy((Object) gameObject, clip.length);
}
public static void Play2D(AudioClip clip, Vector3 position, float pitch)
{
GameObject gameObject = new GameObject("AudioClip_" + clip.name);
gameObject.transform.position = position;
AudioSource audioSource = gameObject.AddComponent<AudioSource>();
audioSource.clip = clip;
audioSource.Play();
Object.Destroy((Object) gameObject, clip.length);
audioSource.pitch = pitch;
}
}
| 34.042553 | 91 | 0.725417 | [
"Unlicense"
] | JaydenB14/YandereSimulatorDecompiled | Assembly-CSharp/AudioClipPlayer.cs | 4,802 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BestHTTP.Logger
{
/// <summary>
/// A basic logger implementation to be able to log intelligently additional informations about the plugin's internal mechanism.
/// </summary>
public class DefaultLogger : BestHTTP.Logger.ILogger
{
public Loglevels Level { get; set; }
public string FormatVerbose { get; set; }
public string FormatInfo { get; set; }
public string FormatWarn { get; set; }
public string FormatErr { get; set; }
public string FormatEx { get; set; }
public DefaultLogger()
{
FormatVerbose = "[{0}] D [{1}]: {2}";
FormatInfo = "[{0}] I [{1}]: {2}";
FormatWarn = "[{0}] W [{1}]: {2}";
FormatErr = "[{0}] Err [{1}]: {2}";
FormatEx = "[{0}] Ex [{1}]: {2} - Message: {3} StackTrace: {4}";
//Level = UnityEngine.Debug.isDebugBuild ? Loglevels.Warning : Loglevels.Error;
Level = Loglevels.None;
}
public void Verbose(string division, string verb)
{
if (Level <= Loglevels.All)
{
try
{
UnityEngine.Debug.Log(string.Format(FormatVerbose, GetFormattedTime(), division, verb));
}
catch
{ }
}
}
public void Information(string division, string info)
{
if (Level <= Loglevels.Information)
{
try
{
UnityEngine.Debug.Log(string.Format(FormatInfo, GetFormattedTime(), division, info));
}
catch
{ }
}
}
public void Warning(string division, string warn)
{
if (Level <= Loglevels.Warning)
{
try
{
UnityEngine.Debug.LogWarning(string.Format(FormatWarn, GetFormattedTime(), division, warn));
}
catch
{ }
}
}
public void Error(string division, string err)
{
if (Level <= Loglevels.Error)
{
try
{
UnityEngine.Debug.LogError(string.Format(FormatErr, GetFormattedTime(), division, err));
}
catch
{ }
}
}
public void Exception(string division, string msg, Exception ex)
{
if (Level <= Loglevels.Exception)
{
try
{
string exceptionMessage = string.Empty;
if (ex == null)
exceptionMessage = "null";
else
{
StringBuilder sb = new StringBuilder();
Exception exception = ex;
int counter = 1;
while (exception != null)
{
sb.AppendFormat("{0}: {1} {2}", counter++.ToString(), exception.Message, exception.StackTrace);
exception = exception.InnerException;
if (exception != null)
sb.AppendLine();
}
exceptionMessage = sb.ToString();
}
UnityEngine.Debug.LogError(string.Format(FormatEx,
GetFormattedTime(),
division,
msg,
exceptionMessage,
ex != null ? ex.StackTrace : "null"));
}
catch
{ }
}
}
private string GetFormattedTime()
{
return DateTime.Now.Ticks.ToString();
}
}
} | 32.728682 | 132 | 0.412838 | [
"Unlicense"
] | ouyangwenyuan/OhMyFramework | UnityProject/Assets/Runtime/Framework/Asset/BestHTTP/BestHTTP/Logger/DefaultLogger.cs | 4,224 | C# |
using Gwen.Net;
using Gwen.Net.Control;
namespace Gwen.Net.Tests.Components
{
[UnitTest(Category = "Non-Interactive", Order = 101)]
public class LinkLabelTest : GUnit
{
private readonly Font font1;
private readonly Font fontHover1;
public LinkLabelTest(ControlBase parent)
: base(parent)
{
{
LinkLabel label = new LinkLabel(this);
label.Dock = Dock.Top;
label.HoverColor = new Color(255, 255, 255, 255);
label.Text = "Link Label (default font)";
label.Link = "Test Link";
label.LinkClicked += OnLinkClicked;
}
{
font1 = new Font(Skin.Renderer, "Comic Sans MS", 25);
fontHover1 = new Font(Skin.Renderer, "Comic Sans MS", 25);
fontHover1.Underline = true;
LinkLabel label = new LinkLabel(this);
label.Dock = Dock.Top;
label.Font = font1;
label.HoverFont = fontHover1;
label.TextColor = new Color(255, 0, 80, 205);
label.HoverColor = new Color(255, 0, 100, 255);
label.Text = "Custom Font (Comic Sans 25)";
label.Link = "Custom Font Link";
label.LinkClicked += OnLinkClicked;
}
}
public override void Dispose()
{
font1.Dispose();
fontHover1.Dispose();
base.Dispose();
}
private void OnLinkClicked(ControlBase control, LinkClickedEventArgs args)
{
UnitPrint("Link Clicked: " + args.Link);
}
}
} | 32.615385 | 82 | 0.51592 | [
"MIT"
] | Geinome/Gwen.CS | Gwen.Net.Tests.Components/LinkLabelTest.cs | 1,698 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
[assembly: System.Reflection.AssemblyCompanyAttribute("PizzaBox.Storing")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Release")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")]
[assembly: System.Reflection.AssemblyProductAttribute("PizzaBox.Storing")]
[assembly: System.Reflection.AssemblyTitleAttribute("PizzaBox.Storing")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
// Generated by the MSBuild WriteCodeFragment class.
| 41.782609 | 80 | 0.650364 | [
"MIT"
] | mlaba49/project1 | aspnet/PizzaBox.Storing/obj/Release/net5.0/PizzaBox.Storing.AssemblyInfo.cs | 961 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNextGen.HybridCompute.V20200730Preview.Outputs
{
[OutputType]
public sealed class MachineExtensionInstanceViewResponseStatus
{
/// <summary>
/// The status code.
/// </summary>
public readonly string? Code;
/// <summary>
/// The short localizable label for the status.
/// </summary>
public readonly string? DisplayStatus;
/// <summary>
/// The level code.
/// </summary>
public readonly string? Level;
/// <summary>
/// The detailed status message, including for alerts and error messages.
/// </summary>
public readonly string? Message;
/// <summary>
/// The time of the status.
/// </summary>
public readonly string? Time;
[OutputConstructor]
private MachineExtensionInstanceViewResponseStatus(
string? code,
string? displayStatus,
string? level,
string? message,
string? time)
{
Code = code;
DisplayStatus = displayStatus;
Level = level;
Message = message;
Time = time;
}
}
}
| 26.929825 | 81 | 0.581107 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/HybridCompute/V20200730Preview/Outputs/MachineExtensionInstanceViewResponseStatus.cs | 1,535 | C# |
using System;
// ReSharper disable UnusedMember.Global
// ReSharper disable UnusedType.Global
namespace YL.Simplification
{
public static class DayOfWeekExtensions
{
public static bool Between(this DayOfWeek self, DayOfWeek min, DayOfWeek max, bool inclusive = true)
{
return inclusive
? min <= max
? min <= self && self <= max
: min <= self || self <= max
: min < max
? min < self && self < max
: min < self || self < max;
}
}
}
| 26.954545 | 108 | 0.509275 | [
"MIT"
] | YLahin/TequilaLegacy | YL.Simplification/DayOfWeekExtensions.cs | 595 | C# |
namespace Sawczyn.EFDesigner.EFModel
{
partial class GeneralizationBuilder
{
// The Generalization connection tool specifies that source and target should be reversed.
private static bool CanAcceptModelClassAsSource(ModelClass candidate)
{
// dependent types can't participate in inheritance relationships
return !candidate.IsDependentType;
}
private static bool CanAcceptModelClassAsTarget(ModelClass candidate)
{
// dependent types can't participate in inheritance relationships
// classes can't have > 1 superclass
return !candidate.IsDependentType && candidate.Superclass == null && !candidate.IsPropertyBag;
}
private static bool CanAcceptModelClassAndModelClassAsSourceAndTarget(ModelClass sourceModelClass, ModelClass targetModelClass)
{
// can't have cycles
for (ModelClass candidate = sourceModelClass; candidate != null; candidate = candidate.Superclass)
{
if (candidate == targetModelClass)
return false;
}
return true;
}
}
}
| 33.235294 | 133 | 0.678761 | [
"MIT"
] | BigHam/EFDesigner | src/Dsl/CustomCode/Connection Builders/GeneralizationBuilder.cs | 1,132 | C# |
using System;
using System.Collections.ObjectModel;
using CMiX.Models;
using CMiX.ViewModels;
using Memento;
namespace CMiX.ViewModels
{
public class FileNameItem : ViewModel
{
public FileNameItem(string messageaddress, ObservableCollection<OSCValidation> oscvalidation, Mementor mementor)
: base (oscvalidation, mementor)
{
MessageAddress = messageaddress + "Selected";
Mementor = mementor;
}
private string _filename;
public string FileName
{
get => _filename;
set => SetAndNotify(ref _filename, value);
}
private bool _fileisselected;
public bool FileIsSelected
{
get => _fileisselected;
set
{
SetAndNotify(ref _fileisselected, value);
if (FileIsSelected)
{
SendMessages(MessageAddress, FileName);
}
}
}
public void UpdateMessageAddress(string messageaddress)
{
MessageAddress = messageaddress + "Selected";
}
#region COPY/PASTE
public void Copy(FileNameItemModel filenameitemmodel)
{
filenameitemmodel.MessageAddress = MessageAddress;
filenameitemmodel.FileIsSelected = FileIsSelected;
filenameitemmodel.FileName = FileName;
}
public void Paste(FileNameItemModel filenameitemmodel)
{
DisabledMessages();
MessageAddress = filenameitemmodel.MessageAddress;
FileIsSelected = filenameitemmodel.FileIsSelected;
FileName = filenameitemmodel.FileName;
EnabledMessages();
}
#endregion
}
} | 27.84375 | 120 | 0.588103 | [
"MIT"
] | cloneproduction/CMiX_UI | Messenger/FileNameItem.cs | 1,784 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.ResourceManager.Compute.Models;
using Azure.ResourceManager.Core;
namespace Azure.ResourceManager.Compute
{
internal partial class SharedGalleriesRestOperations
{
private Uri endpoint;
private string apiVersion;
private ClientDiagnostics _clientDiagnostics;
private HttpPipeline _pipeline;
private readonly string _userAgent;
/// <summary> Initializes a new instance of SharedGalleriesRestOperations. </summary>
/// <param name="clientDiagnostics"> The handler for diagnostic messaging in the client. </param>
/// <param name="pipeline"> The HTTP pipeline for sending and receiving REST requests and responses. </param>
/// <param name="applicationId"> The application id to use for user agent. </param>
/// <param name="endpoint"> server parameter. </param>
/// <param name="apiVersion"> Api Version. </param>
/// <exception cref="ArgumentNullException"> <paramref name="apiVersion"/> is null. </exception>
public SharedGalleriesRestOperations(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, string applicationId, Uri endpoint = null, string apiVersion = default)
{
this.endpoint = endpoint ?? new Uri("https://management.azure.com");
this.apiVersion = apiVersion ?? "2021-07-01";
_clientDiagnostics = clientDiagnostics;
_pipeline = pipeline;
_userAgent = Core.HttpMessageUtilities.GetUserAgentName(this, applicationId);
}
internal HttpMessage CreateListRequest(string subscriptionId, string location, SharedToValues? sharedTo)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Get;
var uri = new RawRequestUriBuilder();
uri.Reset(endpoint);
uri.AppendPath("/subscriptions/", false);
uri.AppendPath(subscriptionId, true);
uri.AppendPath("/providers/Microsoft.Compute/locations/", false);
uri.AppendPath(location, true);
uri.AppendPath("/sharedGalleries", false);
uri.AppendQuery("api-version", apiVersion, true);
if (sharedTo != null)
{
uri.AppendQuery("sharedTo", sharedTo.Value.ToString(), true);
}
request.Uri = uri;
request.Headers.Add("Accept", "application/json");
message.SetProperty("SDKUserAgent", _userAgent);
return message;
}
/// <summary> List shared galleries by subscription id or tenant id. </summary>
/// <param name="subscriptionId"> Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="location"> Resource location. </param>
/// <param name="sharedTo"> The query parameter to decide what shared galleries to fetch when doing listing operations. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/> or <paramref name="location"/> is null. </exception>
public async Task<Response<SharedGalleryList>> ListAsync(string subscriptionId, string location, SharedToValues? sharedTo = null, CancellationToken cancellationToken = default)
{
if (subscriptionId == null)
{
throw new ArgumentNullException(nameof(subscriptionId));
}
if (location == null)
{
throw new ArgumentNullException(nameof(location));
}
using var message = CreateListRequest(subscriptionId, location, sharedTo);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
{
SharedGalleryList value = default;
using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
value = SharedGalleryList.DeserializeSharedGalleryList(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
}
}
/// <summary> List shared galleries by subscription id or tenant id. </summary>
/// <param name="subscriptionId"> Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="location"> Resource location. </param>
/// <param name="sharedTo"> The query parameter to decide what shared galleries to fetch when doing listing operations. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/> or <paramref name="location"/> is null. </exception>
public Response<SharedGalleryList> List(string subscriptionId, string location, SharedToValues? sharedTo = null, CancellationToken cancellationToken = default)
{
if (subscriptionId == null)
{
throw new ArgumentNullException(nameof(subscriptionId));
}
if (location == null)
{
throw new ArgumentNullException(nameof(location));
}
using var message = CreateListRequest(subscriptionId, location, sharedTo);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
{
SharedGalleryList value = default;
using var document = JsonDocument.Parse(message.Response.ContentStream);
value = SharedGalleryList.DeserializeSharedGalleryList(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw _clientDiagnostics.CreateRequestFailedException(message.Response);
}
}
internal HttpMessage CreateGetRequest(string subscriptionId, string location, string galleryUniqueName)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Get;
var uri = new RawRequestUriBuilder();
uri.Reset(endpoint);
uri.AppendPath("/subscriptions/", false);
uri.AppendPath(subscriptionId, true);
uri.AppendPath("/providers/Microsoft.Compute/locations/", false);
uri.AppendPath(location, true);
uri.AppendPath("/sharedGalleries/", false);
uri.AppendPath(galleryUniqueName, true);
uri.AppendQuery("api-version", apiVersion, true);
request.Uri = uri;
request.Headers.Add("Accept", "application/json");
message.SetProperty("SDKUserAgent", _userAgent);
return message;
}
/// <summary> Get a shared gallery by subscription id or tenant id. </summary>
/// <param name="subscriptionId"> Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="location"> Resource location. </param>
/// <param name="galleryUniqueName"> The unique name of the Shared Gallery. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="location"/>, or <paramref name="galleryUniqueName"/> is null. </exception>
public async Task<Response<SharedGalleryData>> GetAsync(string subscriptionId, string location, string galleryUniqueName, CancellationToken cancellationToken = default)
{
if (subscriptionId == null)
{
throw new ArgumentNullException(nameof(subscriptionId));
}
if (location == null)
{
throw new ArgumentNullException(nameof(location));
}
if (galleryUniqueName == null)
{
throw new ArgumentNullException(nameof(galleryUniqueName));
}
using var message = CreateGetRequest(subscriptionId, location, galleryUniqueName);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
{
SharedGalleryData value = default;
using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
value = SharedGalleryData.DeserializeSharedGalleryData(document.RootElement);
return Response.FromValue(value, message.Response);
}
case 404:
return Response.FromValue((SharedGalleryData)null, message.Response);
default:
throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
}
}
/// <summary> Get a shared gallery by subscription id or tenant id. </summary>
/// <param name="subscriptionId"> Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="location"> Resource location. </param>
/// <param name="galleryUniqueName"> The unique name of the Shared Gallery. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="location"/>, or <paramref name="galleryUniqueName"/> is null. </exception>
public Response<SharedGalleryData> Get(string subscriptionId, string location, string galleryUniqueName, CancellationToken cancellationToken = default)
{
if (subscriptionId == null)
{
throw new ArgumentNullException(nameof(subscriptionId));
}
if (location == null)
{
throw new ArgumentNullException(nameof(location));
}
if (galleryUniqueName == null)
{
throw new ArgumentNullException(nameof(galleryUniqueName));
}
using var message = CreateGetRequest(subscriptionId, location, galleryUniqueName);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
{
SharedGalleryData value = default;
using var document = JsonDocument.Parse(message.Response.ContentStream);
value = SharedGalleryData.DeserializeSharedGalleryData(document.RootElement);
return Response.FromValue(value, message.Response);
}
case 404:
return Response.FromValue((SharedGalleryData)null, message.Response);
default:
throw _clientDiagnostics.CreateRequestFailedException(message.Response);
}
}
internal HttpMessage CreateListNextPageRequest(string nextLink, string subscriptionId, string location, SharedToValues? sharedTo)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Get;
var uri = new RawRequestUriBuilder();
uri.Reset(endpoint);
uri.AppendRawNextLink(nextLink, false);
request.Uri = uri;
request.Headers.Add("Accept", "application/json");
message.SetProperty("SDKUserAgent", _userAgent);
return message;
}
/// <summary> List shared galleries by subscription id or tenant id. </summary>
/// <param name="nextLink"> The URL to the next page of results. </param>
/// <param name="subscriptionId"> Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="location"> Resource location. </param>
/// <param name="sharedTo"> The query parameter to decide what shared galleries to fetch when doing listing operations. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="nextLink"/>, <paramref name="subscriptionId"/>, or <paramref name="location"/> is null. </exception>
public async Task<Response<SharedGalleryList>> ListNextPageAsync(string nextLink, string subscriptionId, string location, SharedToValues? sharedTo = null, CancellationToken cancellationToken = default)
{
if (nextLink == null)
{
throw new ArgumentNullException(nameof(nextLink));
}
if (subscriptionId == null)
{
throw new ArgumentNullException(nameof(subscriptionId));
}
if (location == null)
{
throw new ArgumentNullException(nameof(location));
}
using var message = CreateListNextPageRequest(nextLink, subscriptionId, location, sharedTo);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
{
SharedGalleryList value = default;
using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
value = SharedGalleryList.DeserializeSharedGalleryList(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
}
}
/// <summary> List shared galleries by subscription id or tenant id. </summary>
/// <param name="nextLink"> The URL to the next page of results. </param>
/// <param name="subscriptionId"> Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="location"> Resource location. </param>
/// <param name="sharedTo"> The query parameter to decide what shared galleries to fetch when doing listing operations. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="nextLink"/>, <paramref name="subscriptionId"/>, or <paramref name="location"/> is null. </exception>
public Response<SharedGalleryList> ListNextPage(string nextLink, string subscriptionId, string location, SharedToValues? sharedTo = null, CancellationToken cancellationToken = default)
{
if (nextLink == null)
{
throw new ArgumentNullException(nameof(nextLink));
}
if (subscriptionId == null)
{
throw new ArgumentNullException(nameof(subscriptionId));
}
if (location == null)
{
throw new ArgumentNullException(nameof(location));
}
using var message = CreateListNextPageRequest(nextLink, subscriptionId, location, sharedTo);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
{
SharedGalleryList value = default;
using var document = JsonDocument.Parse(message.Response.ContentStream);
value = SharedGalleryList.DeserializeSharedGalleryList(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw _clientDiagnostics.CreateRequestFailedException(message.Response);
}
}
}
}
| 53.987578 | 209 | 0.623102 | [
"MIT"
] | LeszekKalibrate/azure-sdk-for-net | sdk/compute/Azure.ResourceManager.Compute/src/Generated/RestOperations/SharedGalleriesRestOperations.cs | 17,384 | C# |
using System.Collections.Generic;
using UnityEngine;
namespace XCharts
{
/// <summary>
/// the type of symbol.
/// 标记图形的类型。
/// </summary>
public enum SerieSymbolType
{
/// <summary>
/// 空心圆。
/// </summary>
EmptyCircle,
/// <summary>
/// 圆形。
/// </summary>
Circle,
/// <summary>
/// 正方形。
/// </summary>
Rect,
/// <summary>
/// 三角形。
/// </summary>
Triangle,
/// <summary>
/// 菱形。
/// </summary>
Diamond,
/// <summary>
/// 不显示标记。
/// </summary>
None,
}
/// <summary>
/// The way to get serie symbol size.
/// 获取标记图形大小的方式。
/// </summary>
public enum SerieSymbolSizeType
{
/// <summary>
/// Specify constant for symbol size.
/// 自定义大小。
/// </summary>
Custom,
/// <summary>
/// Specify the dataIndex and dataScale to calculate symbol size.
/// 通过 dataIndex 从数据中获取,再乘以一个比例系数 dataScale 。
/// </summary>
FromData,
/// <summary>
/// Specify callback function for symbol size.
/// 通过回调函数获取。
/// </summary>
Callback,
}
/// <summary>
/// 获取标记大小的回调。
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public delegate float SymbolSizeCallback(List<float> data);
/// <summary>
/// 系列数据项的标记的图形
/// </summary>
[System.Serializable]
public class SerieSymbol
{
[SerializeField] private SerieSymbolType m_Type = SerieSymbolType.EmptyCircle;
[SerializeField] private SerieSymbolSizeType m_SizeType = SerieSymbolSizeType.Custom;
[SerializeField] private float m_Size = 6f;
[SerializeField] private float m_SelectedSize = 10f;
[SerializeField] private int m_DataIndex = 1;
[SerializeField] private float m_DataScale = 1;
[SerializeField] private float m_SelectedDataScale = 1.5f;
[SerializeField] private SymbolSizeCallback m_SizeCallback;
[SerializeField] private SymbolSizeCallback m_SelectedSizeCallback;
[SerializeField] private Color m_Color;
[SerializeField] [Range(0, 1)] private float m_Opacity = 1;
/// <summary>
/// the type of symbol.
/// 标记类型。
/// </summary>
/// <value></value>
public SerieSymbolType type { get { return m_Type; } set { m_Type = value; } }
/// <summary>
/// the type of symbol size.
/// 标记图形的大小获取方式。
/// </summary>
/// <value></value>
public SerieSymbolSizeType sizeType { get { return m_SizeType; } set { m_SizeType = value; } }
/// <summary>
/// the size of symbol.
/// 标记的大小。
/// </summary>
/// <value></value>
public float size { get { return m_Size; } set { m_Size = value; } }
/// <summary>
/// the size of selected symbol.
/// 被选中的标记的大小。
/// </summary>
/// <value></value>
public float selectedSize { get { return m_SelectedSize; } set { m_SelectedSize = value; } }
/// <summary>
/// whitch data index is when the sizeType assined as FromData.
/// 当sizeType指定为FromData时,指定的数据源索引。
/// </summary>
/// <value></value>
public int dataIndex { get { return m_DataIndex; } set { m_DataIndex = value; } }
/// <summary>
/// the scale of data when sizeType assined as FromData.
/// 当sizeType指定为FromData时,指定的倍数系数。
/// </summary>
/// <value></value>
public float dataScale { get { return m_DataScale; } set { m_DataScale = value; } }
/// <summary>
/// the scale of selected data when sizeType assined as FromData.
/// 当sizeType指定为FromData时,指定的高亮倍数系数。
/// </summary>
/// <value></value>
public float selectedDataScale { get { return m_SelectedDataScale; } set { m_SelectedDataScale = value; } }
/// <summary>
/// the callback of size when sizeType assined as Callback.
/// 当sizeType指定为Callback时,指定的回调函数。
/// </summary>
/// <value></value>
public SymbolSizeCallback sizeCallback { get { return m_SizeCallback; } set { m_SizeCallback = value; } }
/// <summary>
/// the callback of size when sizeType assined as Callback.
/// 当sizeType指定为Callback时,指定的高亮回调函数。
/// </summary>
/// <value></value>
public SymbolSizeCallback selectedSizeCallback { get { return m_SelectedSizeCallback; } set { m_SelectedSizeCallback = value; } }
/// <summary>
/// the color of symbol,default from serie.
/// 标记图形的颜色,默认和系列一致。
/// </summary>
/// <value></value>
public Color color { get { return m_Color; } set { m_Color = value; } }
/// <summary>
/// the opacity of color.
/// 图形标记的透明度。
/// </summary>
/// <value></value>
public float opacity { get { return m_Opacity; } set { m_Opacity = value; } }
private List<float> m_AnimationSize = new List<float>() { 0, 5, 10 };
/// <summary>
/// the setting for effect scatter.
/// 带有涟漪特效动画的散点图的动画参数。
/// </summary>
/// <value></value>
public List<float> animationSize { get { return m_AnimationSize; } }
/// <summary>
/// 根据指定的sizeType获得标记的大小
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public float GetSize(List<float> data)
{
if (data == null) return size;
switch (m_SizeType)
{
case SerieSymbolSizeType.Custom:
return size;
case SerieSymbolSizeType.FromData:
if (dataIndex >= 0 && dataIndex < data.Count)
{
return data[dataIndex] * m_DataScale;
}
else
{
return size;
}
case SerieSymbolSizeType.Callback:
if (sizeCallback != null) return sizeCallback(data);
else return size;
default: return size;
}
}
/// <summary>
/// 根据sizeType获得高亮时的标记大小
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public float GetSelectedSize(List<float> data)
{
if (data == null) return selectedSize;
switch (m_SizeType)
{
case SerieSymbolSizeType.Custom:
return selectedSize;
case SerieSymbolSizeType.FromData:
if (dataIndex >= 0 && dataIndex < data.Count)
{
return data[dataIndex] * m_SelectedDataScale;
}
else
{
return selectedSize;
}
case SerieSymbolSizeType.Callback:
if (selectedSizeCallback != null) return selectedSizeCallback(data);
else return selectedSize;
default: return selectedSize;
}
}
}
}
| 34.009217 | 137 | 0.515854 | [
"MIT"
] | Hengle/unity-ugui-XCharts | Assets/XCharts/Scripts/UI/Internal/SerieSymbol.cs | 7,930 | C# |
/*
Status: Solved
Imported: 2020-05-02 12:11
By: Casper
Url: https://app.codesignal.com/arcade/code-arcade/loop-tunnel/hBw5BJiZ4LmXcy92u
Description:
Given integers n, l and r, find the number of ways to represent n as a sum of
two integers A and B such that l ≤ A ≤ B ≤ r.
Example
For n = 6, l = 2, and r = 4, the output should be
countSumOfTwoRepresentations2(n, l, r) = 2.
There are just two ways to write 6 as A + B, where 2 ≤ A ≤ B ≤ 4: 6 = 2 + 4 and
6 = 3 + 3.
Input/Output
[execution time limit] 3 seconds (cs)
[input] integer n
A positive integer.
Guaranteed constraints:
5 ≤ n ≤ 109.
[input] integer l
A positive integer.
Guaranteed constraints:
1 ≤ l ≤ r.
[input] integer r
A positive integer.
Guaranteed constraints:
l ≤ r ≤ 109,
r - l ≤ 106.
[output] integer
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace CodeSignalSolutions.TheCore.LoopTunnel
{
class countSumOfTwoRepresentations2Class
{
int countSumOfTwoRepresentations2(int n, int l, int r) {
var start = Math.Max(l, n - r);
var end = Math.Min(r, n - l);
var middle = (start + end) / 2;
Console.WriteLine($"Area: {start}-{end} Middle: {middle}");
return Math.Max(0, middle - start + 1);
}
}
}
| 30.529412 | 89 | 0.572254 | [
"Apache-2.0"
] | casper-a-hansen/CodeSignal | CodeSignalSolutions/TheCore/LoopTunnel/countSumOfTwoRepresentations2Class.cs | 1,583 | C# |
using System;
using MikhailKhalizev.Processor.x86.BinToCSharp;
namespace MikhailKhalizev.Max.Program
{
public partial class RawProgram
{
[MethodInfo("0x18_d4de-4a94744f")]
public void Method_0018_d4de()
{
ii(0x18_d4de, 4); enter(0x14, 0); /* enter 0x14, 0x0 */
ii(0x18_d4e2, 1); push(di); /* push di */
ii(0x18_d4e3, 1); push(si); /* push si */
ii(0x18_d4e4, 3); mov(ax, memw[ss, bp + 6]); /* mov ax, [bp+0x6] */
ii(0x18_d4e7, 3); dec(memw[ss, bp + 6]); /* dec word [bp+0x6] */
ii(0x18_d4ea, 3); cmp(ax, memw[ss, bp + 4]); /* cmp ax, [bp+0x4] */
ii(0x18_d4ed, 2); if(jnz(0x18_d4f2, 3)) goto l_0x18_d4f2; /* jnz 0xd4f2 */
ii(0x18_d4ef, 3); jmp(0x18_d581, 0x8f); goto l_0x18_d581; /* jmp 0xd581 */
l_0x18_d4f2:
ii(0x18_d4f2, 3); lea(ax, memw[ss, bp - 18]); /* lea ax, [bp-0x12] */
ii(0x18_d4f5, 1); push(ax); /* push ax */
ii(0x18_d4f6, 4); mov(cx, memw[ds, 0xc38]); /* mov cx, [0xc38] */
ii(0x18_d4fa, 3); mov(memw[ss, bp - 2], cx); /* mov [bp-0x2], cx */
ii(0x18_d4fd, 1); push(cx); /* push cx */
ii(0x18_d4fe, 3); call(0x18_dc8e, 0x78d); /* call 0xdc8e */
ii(0x18_d501, 1); pop(bx); /* pop bx */
ii(0x18_d502, 1); pop(bx); /* pop bx */
ii(0x18_d503, 3); mov(ax, memw[ss, bp + 6]); /* mov ax, [bp+0x6] */
ii(0x18_d506, 3); shr(ax, 0xc); /* shr ax, 0xc */
ii(0x18_d509, 3); mov(cx, memw[ss, bp + 6]); /* mov cx, [bp+0x6] */
ii(0x18_d50c, 3); shl(cx, 4); /* shl cx, 0x4 */
ii(0x18_d50f, 3); mov(memw[ss, bp - 18], cx); /* mov [bp-0x12], cx */
ii(0x18_d512, 3); mov(memw[ss, bp - 16], ax); /* mov [bp-0x10], ax */
ii(0x18_d515, 3); lea(ax, memw[ss, bp - 18]); /* lea ax, [bp-0x12] */
ii(0x18_d518, 1); push(ax); /* push ax */
ii(0x18_d519, 3); push(memw[ss, bp - 2]); /* push word [bp-0x2] */
ii(0x18_d51c, 3); call(0x18_dc28, 0x709); /* call 0xdc28 */
ii(0x18_d51f, 1); pop(bx); /* pop bx */
ii(0x18_d520, 1); pop(bx); /* pop bx */
ii(0x18_d521, 3); mov(ax, memw[ss, bp - 2]); /* mov ax, [bp-0x2] */
ii(0x18_d524, 2); sub(bx, bx); /* sub bx, bx */
ii(0x18_d526, 2); mov(es, ax); /* mov es, ax */
ii(0x18_d528, 3); mov(memw[ss, bp - 8], bx); /* mov [bp-0x8], bx */
ii(0x18_d52b, 3); mov(memw[ss, bp - 6], es); /* mov [bp-0x6], es */
ii(0x18_d52e, 4); cmp(memb[es, bx], 0x4d); /* cmp byte [es:bx], 0x4d */
ii(0x18_d532, 2); if(jz(0x18_d53a, 6)) goto l_0x18_d53a; /* jz 0xd53a */
ii(0x18_d534, 4); cmp(memb[es, bx], 0x5a); /* cmp byte [es:bx], 0x5a */
ii(0x18_d538, 2); if(jnz(0x18_d581, 0x47)) goto l_0x18_d581;/* jnz 0xd581 */
l_0x18_d53a:
ii(0x18_d53a, 3); mov(ax, memw[ss, bp + 4]); /* mov ax, [bp+0x4] */
ii(0x18_d53d, 3); sub(ax, memw[ss, bp + 6]); /* sub ax, [bp+0x6] */
ii(0x18_d540, 1); dec(ax); /* dec ax */
ii(0x18_d541, 3); mov(memw[ss, bp - 4], ax); /* mov [bp-0x4], ax */
ii(0x18_d544, 3); shl(ax, 4); /* shl ax, 0x4 */
ii(0x18_d547, 3); add(ax, memw[ss, bp - 8]); /* add ax, [bp-0x8] */
ii(0x18_d54a, 2); mov(dx, es); /* mov dx, es */
ii(0x18_d54c, 3); mov(cx, memw[ss, bp - 8]); /* mov cx, [bp-0x8] */
ii(0x18_d54f, 2); mov(bx, es); /* mov bx, es */
ii(0x18_d551, 1); push(cx); /* push cx */
ii(0x18_d552, 1); push(ds); /* push ds */
ii(0x18_d553, 2); mov(di, ax); /* mov di, ax */
ii(0x18_d555, 2); mov(si, cx); /* mov si, cx */
ii(0x18_d557, 2); mov(ds, dx); /* mov ds, dx */
ii(0x18_d559, 3); mov(cx, 8); /* mov cx, 0x8 */
ii(0x18_d55c, 2); rep(() => movsw()); /* rep movsw */
ii(0x18_d55e, 1); pop(ds); /* pop ds */
ii(0x18_d55f, 1); pop(cx); /* pop cx */
ii(0x18_d560, 2); mov(es, bx); /* mov es, bx */
ii(0x18_d562, 2); mov(si, cx); /* mov si, cx */
ii(0x18_d564, 4); mov(memb[es, si], 0x4d); /* mov byte [es:si], 0x4d */
ii(0x18_d568, 3); mov(di, memw[ss, bp - 4]); /* mov di, [bp-0x4] */
ii(0x18_d56b, 1); dec(di); /* dec di */
ii(0x18_d56c, 4); mov(memw[es, si + 3], di); /* mov [es:si+0x3], di */
ii(0x18_d570, 6); mov(memw[es, si + 1], 0); /* mov word [es:si+0x1], 0x0 */
ii(0x18_d576, 2); mov(es, dx); /* mov es, dx */
ii(0x18_d578, 2); mov(si, ax); /* mov si, ax */
ii(0x18_d57a, 3); mov(ax, memw[ss, bp - 4]); /* mov ax, [bp-0x4] */
ii(0x18_d57d, 4); sub(memw[es, si + 3], ax); /* sub [es:si+0x3], ax */
l_0x18_d581:
ii(0x18_d581, 1); pop(si); /* pop si */
ii(0x18_d582, 1); pop(di); /* pop di */
ii(0x18_d583, 1); leave(); /* leave */
ii(0x18_d584, 1); ret(); /* ret */
}
}
}
| 77.126437 | 103 | 0.360358 | [
"Apache-2.0"
] | mikhail-khalizev/max | source/MikhailKhalizev.Max/source/Program/Auto/z-0018-d4de.cs | 6,710 | C# |
#region License
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
using System;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Reflection;
using log4net.Appender;
using log4net.Config;
using log4net.Core;
using NUnit.Framework;
using Rhino.Mocks;
namespace Common.Logging.Log4Net
{
/// <summary>
/// </summary>
/// <author>Erich Eichinger</author>
[TestFixture]
public class Log4NetLoggerFactoryAdapterTests
{
public class TestLog4NetLoggerFactoryAdapter : Log4NetLoggerFactoryAdapter
{
public TestLog4NetLoggerFactoryAdapter(NameValueCollection properties, ILog4NetRuntime runtime)
: base(properties, runtime)
{}
}
public class TestAppender : AppenderSkeleton
{
public LoggingEvent LastLoggingEvent;
public StackTrace Stack;
protected override void Append(LoggingEvent loggingEvent)
{
Stack = new StackTrace(true);
loggingEvent.Fix = FixFlags.LocationInfo;
LastLoggingEvent = loggingEvent;
}
}
[Test]
public void InitWithProperties()
{
MockRepository mocks = new MockRepository();
Log4NetLoggerFactoryAdapter.ILog4NetRuntime rt = mocks.StrictMock<Log4NetLoggerFactoryAdapter.ILog4NetRuntime>();
string configFileName = new Uri(Assembly.GetExecutingAssembly().CodeBase).AbsolutePath;
using(mocks.Ordered())
{
rt.XmlConfiguratorConfigure();
rt.XmlConfiguratorConfigure(configFileName);
rt.XmlConfiguratorConfigureAndWatch(configFileName);
rt.BasicConfiguratorConfigure();
Expect.Call(rt.GetLogger("testLogger")).Return(mocks.DynamicMock<log4net.ILog>());
}
mocks.ReplayAll();
Log4NetLoggerFactoryAdapter a;
NameValueCollection props = new NameValueCollection();
props["configType"] = "inLiNe";
a = new TestLog4NetLoggerFactoryAdapter(props, rt);
props["ConfigTYPE"] = "fiLe";
props["CONFIGFILE"] = configFileName;
a = new TestLog4NetLoggerFactoryAdapter(props, rt);
props["ConfigTYPE"] = "fiLe-WATCH";
props["CONFIGFILE"] = configFileName;
a = new TestLog4NetLoggerFactoryAdapter(props, rt);
props["ConfigTYPE"] = "external";
a = new TestLog4NetLoggerFactoryAdapter(props, rt);
props["ConfigTYPE"] = "any unknown";
a = new TestLog4NetLoggerFactoryAdapter(props, rt);
a.GetLogger("testLogger");
mocks.VerifyAll();
}
[Test]
public void LogsCorrectLoggerName()
{
TestAppender testAppender = new TestAppender();
BasicConfigurator.Configure(testAppender);
Log4NetLoggerFactoryAdapter a;
NameValueCollection props = new NameValueCollection();
props["configType"] = "external";
a = new Log4NetLoggerFactoryAdapter(props);
a.GetLogger(this.GetType()).Debug("TestMessage");
Assert.AreEqual(this.GetType().FullName, testAppender.LastLoggingEvent.GetLoggingEventData().LoggerName);
Assert.AreEqual(this.GetType().FullName, testAppender.LastLoggingEvent.LocationInformation.ClassName);
Assert.AreEqual(MethodBase.GetCurrentMethod().Name, testAppender.LastLoggingEvent.LocationInformation.MethodName);
Assert.AreEqual("TestMessage", testAppender.LastLoggingEvent.MessageObject);
}
[Test]
public void CachesLoggers()
{
NameValueCollection props = new NameValueCollection();
props["configType"] = "external";
Log4NetLoggerFactoryAdapter a = new Log4NetLoggerFactoryAdapter(props);
ILog log = a.GetLogger(this.GetType());
Assert.AreSame(log, a.GetLogger(this.GetType()));
}
}
} | 34.910448 | 126 | 0.642796 | [
"Apache-2.0"
] | crowleym/common-logging | test/Common.Logging.Log4Net1210.Tests/Logging/Log4Net/Log4NetLoggerFactoryAdapterTests.cs | 4,678 | C# |
// WearCommand.cs
// Copyright (c) 2014+ by Michael Penner. All rights reserved.
using System.Diagnostics;
using Eamon.Framework;
using Eamon.Framework.Primitive.Classes;
using Eamon.Framework.Primitive.Enums;
using Eamon.Game.Attributes;
using EamonRT.Framework.Commands;
using EamonRT.Framework.Primitive.Enums;
using EamonRT.Framework.States;
using static EamonRT.Game.Plugin.PluginContext;
namespace EamonRT.Game.Commands
{
[ClassMappings]
public class WearCommand : Command, IWearCommand
{
/// <summary></summary>
public virtual IArtifactCategory DobjArtAc { get; set; }
/// <summary></summary>
public virtual IArtifactCategory ArmorArtifactAc { get; set; }
/// <summary></summary>
public virtual IArtifactCategory ShieldArtifactAc { get; set; }
/// <summary></summary>
public virtual IArtifactCategory WeaponArtifactAc { get; set; }
/// <summary></summary>
public virtual IArtifact ArmorArtifact { get; set; }
/// <summary></summary>
public virtual IArtifact ShieldArtifact { get; set; }
/// <summary></summary>
public virtual IArtifact WeaponArtifact { get; set; }
public override void Execute()
{
Debug.Assert(DobjArtifact != null);
DobjArtAc = DobjArtifact.Wearable;
if (DobjArtAc == null)
{
PrintCantVerbObj(DobjArtifact);
NextState = Globals.CreateInstance<IStartState>();
goto Cleanup;
}
if (DobjArtifact.IsWornByCharacter())
{
gOut.Print("You're already wearing {0}!", DobjArtifact.EvalPlural("it", "them"));
NextState = Globals.CreateInstance<IStartState>();
goto Cleanup;
}
if (!DobjArtifact.IsCarriedByCharacter())
{
if (!GetCommandCalled)
{
RedirectToGetCommand<IWearCommand>(DobjArtifact);
}
else if (DobjArtifact.DisguisedMonster == null)
{
NextState = Globals.CreateInstance<IStartState>();
}
goto Cleanup;
}
if (DobjArtAc.Field1 > 0)
{
ArmorArtifact = gADB[gGameState.Ar];
ShieldArtifact = gADB[gGameState.Sh];
ArmorArtifactAc = ArmorArtifact != null ? ArmorArtifact.Wearable : null;
ShieldArtifactAc = ShieldArtifact != null ? ShieldArtifact.Wearable : null;
if (DobjArtAc.Field1 > 1)
{
if (DobjArtAc.Field1 > 14)
{
DobjArtAc.Field1 = 14;
}
if (ArmorArtifactAc != null)
{
gOut.Print("You're already wearing armor!");
NextState = Globals.CreateInstance<IStartState>();
goto Cleanup;
}
gGameState.Ar = DobjArtifact.Uid;
ActorMonster.Armor = (DobjArtAc.Field1 / 2) + ((DobjArtAc.Field1 / 2) >= 3 ? 2 : 0) + (ShieldArtifactAc != null ? ShieldArtifactAc.Field1 : 0);
}
else
{
if (ShieldArtifactAc != null)
{
gOut.Print("You're already wearing a shield!");
NextState = Globals.CreateInstance<IStartState>();
goto Cleanup;
}
// can't wear shield while using two-handed weapon
WeaponArtifact = ActorMonster.Weapon > 0 ? gADB[ActorMonster.Weapon] : null;
WeaponArtifactAc = WeaponArtifact != null ? WeaponArtifact.GeneralWeapon : null;
if (WeaponArtifactAc != null && WeaponArtifactAc.Field5 > 1)
{
PrintCantWearShieldWithWeapon(DobjArtifact, WeaponArtifact);
NextState = Globals.CreateInstance<IStartState>();
goto Cleanup;
}
gGameState.Sh = DobjArtifact.Uid;
ActorMonster.Armor = (ArmorArtifactAc != null ? (ArmorArtifactAc.Field1 / 2) + ((ArmorArtifactAc.Field1 / 2) >= 3 ? 2 : 0) : 0) + DobjArtAc.Field1;
}
}
DobjArtifact.SetWornByCharacter();
PrintWorn(DobjArtifact);
ProcessEvents(EventType.AfterWearArtifact);
if (GotoCleanup)
{
goto Cleanup;
}
Cleanup:
if (NextState == null)
{
NextState = Globals.CreateInstance<IMonsterStartState>();
}
}
public WearCommand()
{
SortOrder = 240;
if (Globals.IsRulesetVersion(5))
{
IsPlayerEnabled = false;
}
Uid = 55;
Name = "WearCommand";
Verb = "wear";
Type = CommandType.Manipulation;
}
}
}
| 23.277778 | 153 | 0.638425 | [
"MIT"
] | TheRealEamonCS/Eamon-CS | System/EamonRT/Game/Commands/Player/Manipulation/WearCommand.cs | 4,192 | C# |
using System.Text;
using Blockcore.Jose;
using Xunit;
namespace UnitTests
{
public class AesGcmTest
{
private byte[] aes128Key = new byte[] { 194, 164, 235, 6, 138, 248, 171, 239, 24, 216, 11, 22, 137, 199, 215, 133 };
[Fact]
public void Encrypt()
{
//given
byte[] iv = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
byte[] aad = Encoding.UTF8.GetBytes("secre");
byte[] text = Encoding.UTF8.GetBytes("hellow aes !");
//when
byte[][] test = AesGcm.Encrypt(aes128Key, iv, aad, text);
//then
Assert.Equal(test[0], new byte[] { 245, 242, 160, 166, 250, 62, 102, 211, 158, 42, 62, 73 });
Assert.Equal(test[1], new byte[] { 195, 69, 216, 140, 118, 58, 48, 131, 47, 225, 205, 198, 78, 12, 180, 76 });
}
[Fact]
public void Decrypt()
{
//given
byte[] iv = { 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 };
byte[] tag = { 121, 235, 93, 169, 185, 192, 202, 230, 130, 37, 35, 135, 46, 129, 168, 104 };
byte[] cipher = { 33, 6, 206, 1, 182, 114, 131, 218, 124, 60 };
byte[] aad = Encoding.UTF8.GetBytes("top secret");
//when
byte[] test = AesGcm.Decrypt(aes128Key, iv, aad, cipher, tag);
//then
Assert.Equal(test, Encoding.UTF8.GetBytes("decrypt me"));
}
}
}
| 31.113636 | 122 | 0.509861 | [
"MIT"
] | block-core/blockcore-jose | Blockcore.Jose.Tests/AesGcmTest.cs | 1,369 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="MonoTouchRenderContext.cs" company="OxyPlot">
// Copyright (c) 2014 OxyPlot contributors
// </copyright>
// <summary>
// Implements a <see cref="IRenderContext"/> for MonoTouch CoreGraphics.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace OxyPlot.XamarinIOS
{
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using MonoTouch.CoreGraphics;
using MonoTouch.CoreText;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
/// <summary>
/// Implements a <see cref="IRenderContext"/> for MonoTouch CoreGraphics.
/// </summary>
public class MonoTouchRenderContext : RenderContextBase, IDisposable
{
/// <summary>
/// The images in use.
/// </summary>
private readonly HashSet<OxyImage> imagesInUse = new HashSet<OxyImage>();
/// <summary>
/// The fonts cache.
/// </summary>
private readonly Dictionary<string, CTFont> fonts = new Dictionary<string, CTFont>();
/// <summary>
/// The image cache.
/// </summary>
private readonly Dictionary<OxyImage, UIImage> imageCache = new Dictionary<OxyImage, UIImage>();
/// <summary>
/// The graphics context.
/// </summary>
private readonly CGContext gctx;
/// <summary>
/// Initializes a new instance of the <see cref="MonoTouchRenderContext"/> class.
/// </summary>
/// <param name="context">The context.</param>
public MonoTouchRenderContext(CGContext context)
{
this.gctx = context;
// Set rendering quality
this.gctx.SetAllowsFontSmoothing(true);
this.gctx.SetAllowsFontSubpixelQuantization(true);
this.gctx.SetAllowsAntialiasing(true);
this.gctx.SetShouldSmoothFonts(true);
this.gctx.SetShouldAntialias(true);
this.gctx.InterpolationQuality = CGInterpolationQuality.High;
this.gctx.SetTextDrawingMode(CGTextDrawingMode.Fill);
}
/// <summary>
/// Draws an ellipse.
/// </summary>
/// <param name="rect">The rectangle.</param>
/// <param name="fill">The fill color.</param>
/// <param name="stroke">The stroke color.</param>
/// <param name="thickness">The thickness.</param>
public override void DrawEllipse(OxyRect rect, OxyColor fill, OxyColor stroke, double thickness)
{
this.SetAlias(false);
var convertedRectangle = rect.Convert();
if (fill.IsVisible())
{
this.SetFill(fill);
using (var path = new CGPath())
{
path.AddEllipseInRect(convertedRectangle);
this.gctx.AddPath(path);
}
this.gctx.DrawPath(CGPathDrawingMode.Fill);
}
if (stroke.IsVisible() && thickness > 0)
{
this.SetStroke(stroke, thickness);
using (var path = new CGPath())
{
path.AddEllipseInRect(convertedRectangle);
this.gctx.AddPath(path);
}
this.gctx.DrawPath(CGPathDrawingMode.Stroke);
}
}
/// <summary>
/// Draws the specified portion of the specified <see cref="OxyImage" /> at the specified location and with the specified size.
/// </summary>
/// <param name="source">The source.</param>
/// <param name="srcX">The x-coordinate of the upper-left corner of the portion of the source image to draw.</param>
/// <param name="srcY">The y-coordinate of the upper-left corner of the portion of the source image to draw.</param>
/// <param name="srcWidth">Width of the portion of the source image to draw.</param>
/// <param name="srcHeight">Height of the portion of the source image to draw.</param>
/// <param name="destX">The x-coordinate of the upper-left corner of drawn image.</param>
/// <param name="destY">The y-coordinate of the upper-left corner of drawn image.</param>
/// <param name="destWidth">The width of the drawn image.</param>
/// <param name="destHeight">The height of the drawn image.</param>
/// <param name="opacity">The opacity.</param>
/// <param name="interpolate">Interpolate if set to <c>true</c>.</param>
public override void DrawImage(OxyImage source, double srcX, double srcY, double srcWidth, double srcHeight, double destX, double destY, double destWidth, double destHeight, double opacity, bool interpolate)
{
var image = this.GetImage(source);
if (image == null)
{
return;
}
this.gctx.SaveState();
double x = destX - (srcX / srcWidth * destWidth);
double y = destY - (srcY / srcHeight * destHeight);
this.gctx.ScaleCTM(1, -1);
this.gctx.TranslateCTM((float)x, -(float)(y + destHeight));
this.gctx.SetAlpha((float)opacity);
this.gctx.InterpolationQuality = interpolate ? CGInterpolationQuality.High : CGInterpolationQuality.None;
var destRect = new RectangleF(0f, 0f, (float)destWidth, (float)destHeight);
this.gctx.DrawImage(destRect, image.CGImage);
this.gctx.RestoreState();
}
/// <summary>
/// Cleans up resources not in use.
/// </summary>
/// <remarks>This method is called at the end of each rendering.</remarks>
public override void CleanUp()
{
var imagesToRelease = this.imageCache.Keys.Where(i => !this.imagesInUse.Contains(i)).ToList();
foreach (var i in imagesToRelease)
{
var image = this.GetImage(i);
image.Dispose();
this.imageCache.Remove(i);
}
this.imagesInUse.Clear();
}
/// <summary>
/// Sets the clip rectangle.
/// </summary>
/// <param name="rect">The clip rectangle.</param>
/// <returns>True if the clip rectangle was set.</returns>
public override bool SetClip(OxyRect rect)
{
this.gctx.SaveState();
this.gctx.ClipToRect(rect.Convert());
return true;
}
/// <summary>
/// Resets the clip rectangle.
/// </summary>
public override void ResetClip()
{
this.gctx.RestoreState();
}
/// <summary>
/// Draws a polyline.
/// </summary>
/// <param name="points">The points.</param>
/// <param name="stroke">The stroke color.</param>
/// <param name="thickness">The stroke thickness.</param>
/// <param name="dashArray">The dash array.</param>
/// <param name="lineJoin">The line join type.</param>
/// <param name="aliased">if set to <c>true</c> the shape will be aliased.</param>
public override void DrawLine(IList<ScreenPoint> points, OxyColor stroke, double thickness, double[] dashArray, LineJoin lineJoin, bool aliased)
{
if (stroke.IsVisible() && thickness > 0)
{
this.SetAlias(aliased);
this.SetStroke(stroke, thickness, dashArray, lineJoin);
using (var path = new CGPath())
{
var convertedPoints = (aliased ? points.Select(p => p.ConvertAliased()) : points.Select(p => p.Convert())).ToArray();
path.AddLines(convertedPoints);
this.gctx.AddPath(path);
}
this.gctx.DrawPath(CGPathDrawingMode.Stroke);
}
}
/// <summary>
/// Draws a polygon. The polygon can have stroke and/or fill.
/// </summary>
/// <param name="points">The points.</param>
/// <param name="fill">The fill color.</param>
/// <param name="stroke">The stroke color.</param>
/// <param name="thickness">The stroke thickness.</param>
/// <param name="dashArray">The dash array.</param>
/// <param name="lineJoin">The line join type.</param>
/// <param name="aliased">If set to <c>true</c> the shape will be aliased.</param>
public override void DrawPolygon(IList<ScreenPoint> points, OxyColor fill, OxyColor stroke, double thickness, double[] dashArray, LineJoin lineJoin, bool aliased)
{
this.SetAlias(aliased);
var convertedPoints = (aliased ? points.Select(p => p.ConvertAliased()) : points.Select(p => p.Convert())).ToArray();
if (fill.IsVisible())
{
this.SetFill(fill);
using (var path = new CGPath())
{
path.AddLines(convertedPoints);
path.CloseSubpath();
this.gctx.AddPath(path);
}
this.gctx.DrawPath(CGPathDrawingMode.Fill);
}
if (stroke.IsVisible() && thickness > 0)
{
this.SetStroke(stroke, thickness, dashArray, lineJoin);
using (var path = new CGPath())
{
path.AddLines(convertedPoints);
path.CloseSubpath();
this.gctx.AddPath(path);
}
this.gctx.DrawPath(CGPathDrawingMode.Stroke);
}
}
/// <summary>
/// Draws a rectangle.
/// </summary>
/// <param name="rect">The rectangle.</param>
/// <param name="fill">The fill color.</param>
/// <param name="stroke">The stroke color.</param>
/// <param name="thickness">The stroke thickness.</param>
public override void DrawRectangle(OxyRect rect, OxyColor fill, OxyColor stroke, double thickness)
{
this.SetAlias(true);
var convertedRect = rect.ConvertAliased();
if (fill.IsVisible())
{
this.SetFill(fill);
using (var path = new CGPath())
{
path.AddRect(convertedRect);
this.gctx.AddPath(path);
}
this.gctx.DrawPath(CGPathDrawingMode.Fill);
}
if (stroke.IsVisible() && thickness > 0)
{
this.SetStroke(stroke, thickness);
using (var path = new CGPath())
{
path.AddRect(convertedRect);
this.gctx.AddPath(path);
}
this.gctx.DrawPath(CGPathDrawingMode.Stroke);
}
}
/// <summary>
/// Draws the text.
/// </summary>
/// <param name="p">The position of the text.</param>
/// <param name="text">The text.</param>
/// <param name="fill">The fill color.</param>
/// <param name="fontFamily">The font family.</param>
/// <param name="fontSize">Size of the font.</param>
/// <param name="fontWeight">The font weight.</param>
/// <param name="rotate">The rotation angle.</param>
/// <param name="halign">The horizontal alignment.</param>
/// <param name="valign">The vertical alignment.</param>
/// <param name="maxSize">The maximum size of the text.</param>
public override void DrawText(ScreenPoint p, string text, OxyColor fill, string fontFamily, double fontSize, double fontWeight, double rotate, HorizontalAlignment halign, VerticalAlignment valign, OxySize? maxSize)
{
if (string.IsNullOrEmpty(text))
{
return;
}
var fontName = GetActualFontName(fontFamily, fontWeight);
var font = this.GetCachedFont(fontName, fontSize);
using (var attributedString = new NSAttributedString(text, new CTStringAttributes { ForegroundColorFromContext = true, Font = font }))
{
using (var textLine = new CTLine(attributedString))
{
float width;
float height;
this.gctx.TextPosition = new PointF(0, 0);
float lineHeight, delta;
this.GetFontMetrics(font, out lineHeight, out delta);
var bounds = textLine.GetImageBounds(this.gctx);
if (maxSize.HasValue || halign != HorizontalAlignment.Left || valign != VerticalAlignment.Bottom)
{
width = bounds.Left + bounds.Width;
height = lineHeight;
}
else
{
width = height = 0f;
}
if (maxSize.HasValue)
{
if (width > maxSize.Value.Width)
{
width = (float)maxSize.Value.Width;
}
if (height > maxSize.Value.Height)
{
height = (float)maxSize.Value.Height;
}
}
var dx = halign == HorizontalAlignment.Left ? 0d : (halign == HorizontalAlignment.Center ? -width * 0.5 : -width);
var dy = valign == VerticalAlignment.Bottom ? 0d : (valign == VerticalAlignment.Middle ? height * 0.5 : height);
var x0 = -bounds.Left;
var y0 = delta;
this.SetFill(fill);
this.SetAlias(false);
this.gctx.SaveState();
this.gctx.TranslateCTM((float)p.X, (float)p.Y);
if (!rotate.Equals(0))
{
this.gctx.RotateCTM((float)(rotate / 180 * Math.PI));
}
this.gctx.TranslateCTM((float)dx + x0, (float)dy + y0);
this.gctx.ScaleCTM(1f, -1f);
if (maxSize.HasValue)
{
var clipRect = new RectangleF (-x0, y0, (float)Math.Ceiling (width), (float)Math.Ceiling (height));
this.gctx.ClipToRect(clipRect);
}
textLine.Draw(this.gctx);
this.gctx.RestoreState();
}
}
}
/// <summary>
/// Measures the text.
/// </summary>
/// <param name="text">The text.</param>
/// <param name="fontFamily">The font family.</param>
/// <param name="fontSize">Size of the font.</param>
/// <param name="fontWeight">The font weight.</param>
/// <returns>
/// The size of the text.
/// </returns>
public override OxySize MeasureText(string text, string fontFamily, double fontSize, double fontWeight)
{
if (string.IsNullOrEmpty(text) || fontFamily == null)
{
return OxySize.Empty;
}
var fontName = GetActualFontName(fontFamily, fontWeight);
var font = this.GetCachedFont(fontName, (float)fontSize);
using (var attributedString = new NSAttributedString(text, new CTStringAttributes { ForegroundColorFromContext = true, Font = font }))
{
using (var textLine = new CTLine(attributedString))
{
float lineHeight, delta;
this.GetFontMetrics(font, out lineHeight, out delta);
this.gctx.TextPosition = new PointF(0, 0);
var bounds = textLine.GetImageBounds(this.gctx);
return new OxySize(bounds.Left + bounds.Width, lineHeight);
}
}
}
/// <summary>
/// Releases all resource used by the <see cref="OxyPlot.XamarinIOS.MonoTouchRenderContext"/> object.
/// </summary>
/// <remarks>Call <see cref="Dispose"/> when you are finished using the
/// <see cref="OxyPlot.XamarinIOS.MonoTouchRenderContext"/>. The <see cref="Dispose"/> method leaves the
/// <see cref="OxyPlot.XamarinIOS.MonoTouchRenderContext"/> in an unusable state. After calling
/// <see cref="Dispose"/>, you must release all references to the
/// <see cref="OxyPlot.XamarinIOS.MonoTouchRenderContext"/> so the garbage collector can reclaim the memory that
/// the <see cref="OxyPlot.XamarinIOS.MonoTouchRenderContext"/> was occupying.</remarks>
public void Dispose()
{
foreach (var image in this.imageCache.Values)
{
image.Dispose();
}
foreach (var font in this.fonts.Values)
{
font.Dispose();
}
}
/// <summary>
/// Gets the actual font for iOS.
/// </summary>
/// <param name="fontFamily">The font family.</param>
/// <param name="fontWeight">The font weight.</param>
/// <returns>The actual font name.</returns>
private static string GetActualFontName(string fontFamily, double fontWeight)
{
string fontName;
switch (fontFamily)
{
case null:
case "Segoe UI":
fontName = "HelveticaNeue";
break;
case "Arial":
fontName = "ArialMT";
break;
case "Times":
case "Times New Roman":
fontName = "TimesNewRomanPSMT";
break;
case "Courier New":
fontName = "CourierNewPSMT";
break;
default:
fontName = fontFamily;
break;
}
if (fontWeight >= 700)
{
fontName += "-Bold";
}
return fontName;
}
/// <summary>
/// Gets font metrics for the specified font.
/// </summary>
/// <param name="font">The font.</param>
/// <param name="defaultLineHeight">Default line height.</param>
/// <param name="delta">The vertical delta.</param>
private void GetFontMetrics(CTFont font, out float defaultLineHeight, out float delta)
{
var ascent = font.AscentMetric;
var descent = font.DescentMetric;
var leading = font.LeadingMetric;
//// http://stackoverflow.com/questions/5511830/how-does-line-spacing-work-in-core-text-and-why-is-it-different-from-nslayoutm
leading = leading < 0 ? 0 : (float)Math.Floor(leading + 0.5f);
var lineHeight = (float)Math.Floor(ascent + 0.5f) + (float)Math.Floor(descent + 0.5) + leading;
var ascenderDelta = leading >= 0 ? 0 : (float)Math.Floor((0.2 * lineHeight) + 0.5);
defaultLineHeight = lineHeight + ascenderDelta;
delta = ascenderDelta - descent;
}
/// <summary>
/// Gets the specified from cache.
/// </summary>
/// <returns>The font.</returns>
/// <param name="fontName">Font name.</param>
/// <param name="fontSize">Font size.</param>
private CTFont GetCachedFont(string fontName, double fontSize)
{
var key = fontName + fontSize.ToString("0.###");
CTFont font;
if (this.fonts.TryGetValue(key, out font))
{
return font;
}
return this.fonts[key] = new CTFont(fontName, (float)fontSize);
}
/// <summary>
/// Sets the alias state.
/// </summary>
/// <param name="alias">alias if set to <c>true</c>.</param>
private void SetAlias(bool alias)
{
this.gctx.SetShouldAntialias(!alias);
}
/// <summary>
/// Sets the fill color.
/// </summary>
/// <param name="c">The color.</param>
private void SetFill(OxyColor c)
{
this.gctx.SetFillColor(c.ToCGColor());
}
/// <summary>
/// Sets the stroke style.
/// </summary>
/// <param name="c">The stroke color.</param>
/// <param name="thickness">The stroke thickness.</param>
/// <param name="dashArray">The dash array.</param>
/// <param name="lineJoin">The line join.</param>
private void SetStroke(OxyColor c, double thickness, double[] dashArray = null, LineJoin lineJoin = LineJoin.Miter)
{
this.gctx.SetStrokeColor(c.ToCGColor());
this.gctx.SetLineWidth((float)thickness);
this.gctx.SetLineJoin(lineJoin.Convert());
if (dashArray != null)
{
var lengths = dashArray.Select(d => (float)d).ToArray();
this.gctx.SetLineDash(0f, lengths);
}
else
{
this.gctx.SetLineDash(0, null);
}
}
/// <summary>
/// Gets the image from cache or converts the specified <paramref name="source"/> <see cref="OxyImage"/>.
/// </summary>
/// <param name="source">The source.</param>
/// <returns>The image.</returns>
private UIImage GetImage(OxyImage source)
{
if (source == null)
{
return null;
}
if (!this.imagesInUse.Contains(source))
{
this.imagesInUse.Add(source);
}
UIImage src;
if (!this.imageCache.TryGetValue(source, out src))
{
using (var data = NSData.FromArray(source.GetData()))
{
src = UIImage.LoadFromData(data);
}
this.imageCache.Add(source, src);
}
return src;
}
}
} | 39.164336 | 222 | 0.518838 | [
"MIT"
] | BRER-TECH/oxyplot | Source/OxyPlot.XamarinIOS/MonoTouchRenderContext.cs | 22,404 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Remote
{
/// <summary>
/// Abstract the name of a remote service.
/// </summary>
/// <remarks>
/// Allows partner teams to specify bitness-specific service name, while we can use bitness agnostic id for well-known services.
/// TODO: Update LUT and SBD to use well-known ids and remove this abstraction (https://github.com/dotnet/roslyn/issues/44327).
/// </remarks>
internal readonly struct RemoteServiceName : IEquatable<RemoteServiceName>
{
internal const string Prefix = "roslyn";
internal const string Suffix64 = "64";
internal const string SuffixServerGC = "S";
internal const string SuffixCoreClr = "Core";
public readonly WellKnownServiceHubService WellKnownService;
public readonly string? CustomServiceName;
public RemoteServiceName(WellKnownServiceHubService wellKnownService)
{
WellKnownService = wellKnownService;
CustomServiceName = null;
}
/// <summary>
/// Exact service name - must be reflect the bitness of the ServiceHub process.
/// </summary>
public RemoteServiceName(string customServiceName)
{
WellKnownService = WellKnownServiceHubService.None;
CustomServiceName = customServiceName;
}
public string ToString(bool isRemoteHostServerGC, bool isRemoteHostCoreClr)
{
if (CustomServiceName is not null)
{
return CustomServiceName;
}
var suffix = (isRemoteHostServerGC, isRemoteHostCoreClr) switch
{
(false, false) => Suffix64,
(true, false) => Suffix64 + SuffixServerGC,
(false, true) => SuffixCoreClr + Suffix64,
(true, true) => SuffixCoreClr + Suffix64 + SuffixServerGC,
};
return WellKnownService switch
{
WellKnownServiceHubService.RemoteHost => Prefix + nameof(WellKnownServiceHubService.RemoteHost) + suffix,
_ => throw ExceptionUtilities.UnexpectedValue(WellKnownService),
};
}
public override bool Equals(object? obj)
=> obj is RemoteServiceName name && Equals(name);
public override int GetHashCode()
=> Hash.Combine(CustomServiceName, (int)WellKnownService);
public bool Equals(RemoteServiceName other)
=> CustomServiceName == other.CustomServiceName && WellKnownService == other.WellKnownService;
public static bool operator ==(RemoteServiceName left, RemoteServiceName right)
=> left.Equals(right);
public static bool operator !=(RemoteServiceName left, RemoteServiceName right)
=> !(left == right);
public static implicit operator RemoteServiceName(WellKnownServiceHubService wellKnownService)
=> new(wellKnownService);
}
}
| 38.771084 | 132 | 0.646053 | [
"MIT"
] | lostmsu/roslyn | src/Workspaces/Core/Portable/Remote/RemoteServiceName.cs | 3,220 | C# |
namespace TeensyCNCManager.Core.Commands
{
using System.IO;
public class BaseCommand
{
protected int PayloadReadCounter;
protected byte[] DataBytes;
public BaseCommand()
{
}
public BaseCommand(byte[] dataBytes)
{
DataBytes = dataBytes;
ReadDataBytes();
}
public int CommandCode { get; set; }
public int LineNumber { get; set; }
protected void ReadHeader()
{
var reader = new BinaryReader(new MemoryStream(DataBytes));
CommandCode = reader.ReadInt32();
LineNumber = reader.ReadInt32();
}
protected virtual MemoryStream WriteHeader(MemoryStream stream)
{
var writer = new BinaryWriter(stream);
writer.Write(CommandCode);
writer.Write(LineNumber);
return stream;
}
private void ReadDataBytes()
{
ReadHeader();
ReadPayload();
}
public byte[] GetDataBytes()
{
return WritePayload(WriteHeader(new MemoryStream(new byte[64]))).ToArray();
}
protected virtual void ReadPayload()
{
}
protected virtual MemoryStream WritePayload(MemoryStream stream)
{
return stream;
}
public virtual void Act(IState gs) { }
}
}
| 21.545455 | 87 | 0.543601 | [
"MIT"
] | IlyaChernov/Teensy_CNC_Manager | TeensyCNCManager.Core/Commands/BaseCommand.cs | 1,424 | C# |
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("Adamant.Tools.Compiler.Bootstrap.Tests.Unit.Emit.C")]
| 32 | 85 | 0.804688 | [
"MIT"
] | adamant/adamant.tools.compiler.bootstrap | Emit.C/InternalsVisibleTo.cs | 128 | C# |
using System;
namespace LearnInterfaces
{
class Truck : IAutomobile
{
public string LicensePlate
{ get; }
public double Speed
{ get; private set; }
//only can be set when initial the object by construtor. then can't be changed any more.
public int Wheels
{ get; }
public double Weight
{ get; }
public Truck(double speed, double weight)
{
Speed = speed;
LicensePlate = Tools.GenerateLicensePlate();
Weight = weight;
if (weight < 400)
{
Wheels = 8;
}
else
{
Wheels = 12;
}
}
public void Honk()
{
Console.WriteLine("HONK!");
}
public void SpeedUp()
{
Speed += 5;
}
public void SlowDown()
{
Speed -= 5;
}
}
} | 18.673077 | 96 | 0.436663 | [
"Apache-2.0"
] | SpAiNiOr/mystudy | learning/csharp/Interface/Truck.cs | 971 | C# |
using System.Collections.Generic;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace LeeWay.Ensure.ControllerAttributes.Tests.Fakes.Controllers
{
[Route("api/[controller]")]
[ApiController]
[AllowAnonymous]
public class PublicController : ControllerBase
{
// GET: api/Public
[HttpGet]
[Authorize("MyPolicy")]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET: api/Public/5
[HttpGet("{id}", Name = "Get")]
[Authorize("MyPolicy")]
public string GetById(int id)
{
return "value";
}
// POST: api/Public
[HttpPost]
public void Post([FromBody] string value)
{
}
// PUT: api/Public/5
[HttpPut("{id}")]
public void Put(int id, [FromBody] string value)
{
}
// DELETE: api/ApiWithActions/5
[HttpDelete("{id}")]
[Authorize("DeletePolicy")]
public void Delete(int id)
{
}
}
}
| 22.3 | 68 | 0.53991 | [
"MIT"
] | JimiSweden/LeeWay | LeeWay.Ensure.ControllerAttributes.Tests/Fakes/Controllers/PublicController.cs | 1,117 | C# |
using MaxiPago.Gateway;
using MaxiPago.DataContract;
using MaxiPago.DataContract.Transactional;
namespace MaxiPagoExample
{
class Program
{
static void Main(string[] args)
{
Transaction transaction = new Transaction();
transaction.Environment = "TEST";
ResponseBase response = transaction.Sale(
"100", // 'merchantId' - REQUIRED: Merchant ID assigned by maxiPago! //
"merchant-key", // 'merchantKey' - REQUIRED: Merchant Key assigned by maxiPago! //
"ORD4828381B", // 'referenceNum' - REQUIRED: Merchant internal order number //
432.31, // 'chargeTotal' - REQUIRED: Transaction amount in US format //
"1", // 'processorId' - REQUIRED: Acquirer code for routing transactions. Use '1' for testing. //
"eBUv/SIBJv0=", // 'token' - REQUIRED: Credit card token assigned by maxiPago! //
"999", // 'customerId' - REQUIRED: Customer ID created by maxiPago! //
null, // 'numberOfInstallments' - Optional: Number of installments for credit card purchases ("parcelas") //
// Send 'null' if no installments are used //
null, // 'chargeInterest' - Optional: Charge interest flag (Y/N) for installment purchase ("com" e "sem" juros) //
"127.0.01", // 'ipAddress' - Optional //
null, // 'customerIdExt' - Optional: Merchant internal customer number //
"John Smith", // 'billingName' - RECOMMENDED: Customer name //
"Rua de Teste, 123", // 'billingAddress' - Optional: Customer address //
null, // 'billingAddress2' - Optional: Customer address //
"Rio de Janeiro", // 'billingCity' - Optional: Customer city //
"RJ", // 'billingState' - Optional: Customer state with 2 characters //
"20030000", // 'billingPostalCode' - Optional: Customer zip code //
"BR", // 'billingCountry' - Optional: Customer country per ISO 3166-2 //
"551140634666", // 'billingPhone' - Optional: Customer phone number //
"example@example.com", // 'billingEmail' - Optional: Customer email addres //
"Jane Doe", // 'shippingName' - Optional: Shipping name //
null, // 'shippingAddress' - Optional: Shipping address //
null, // 'shippingAddress2' - Optional: Shipping address //
null, // 'shippingCity' - Optional: Shipping city //
null, // 'shippingState' - Optional: Shipping state with 2 characters //
null, // 'shippingPostalCode' - Optional: Shipping zip code //
null, // 'shippingCountry' - Optional: Shipping country per ISO 3166-2 //
null, // 'shippingPhone' - Optional: Shipping phone number //
null, // 'shippingEmail' - Optional: Shipping email address //
"BRL", // 'currencyCode' - Optional: Currency code. Valid only for ChasePaymentech. Please see full documentation for more info //
null, // 'softDescriptor' - Optional
null // 'iataFee' - Optional
);
if (response.IsTransactionResponse) {
TransactionResponse result = response as TransactionResponse;
if (result.ResponseCode == "0") {
// Success
}
else {
// Declined
}
}
else if (response.IsErrorResponse) {
ErrorResponse result = response as ErrorResponse;
// Fail
}
}
}
} | 50.552239 | 139 | 0.613227 | [
"Apache-2.0"
] | danilobenedetti/sdk-dotnet-maxipago | test/sale-with-token.cs | 3,387 | C# |
using Csla;
using Csla.Core;
using System;
using System.Threading.Tasks;
[Serializable]
public class ExpressionBodiedMember
: BusinessBase<ExpressionBodiedMember>
{
public static readonly PropertyInfo<int> ResourceIdProperty = RegisterProperty<int>(c => c.ResourceId);
public int ResourceId => ReadProperty(ResourceIdProperty);
}
public interface IBO
: IBusinessObject
{
void DataPortal_Create();
}
internal class x : IBO
{
internal void DataPortal_Create()
{
throw new NotImplementedException();
}
}
public class SomeCriteria
: CriteriaBase<SomeCriteria>
{ }
public class MyCommandBase
: CommandBase<MyCommandBase>
{
public MyCommandBase(int id) { }
public MyCommandBase()
{
}
}
// This should have an error because it's not serializable
public class ClassIsStereotypeAndIsNotSerializable
: BusinessBase<ClassIsStereotypeAndIsNotSerializable>
{ }
public class ClassIsNotStereotype { }
[Serializable]
public class ClassIsStereotypeAndIsSerializable
: BusinessBase<ClassIsStereotypeAndIsSerializable>
{ }
// This should have an error because it doesn't have a public constructor
// and a warning for the constructor with arguments.
[Serializable]
public class User
: BusinessBase<User>
{
private User(int x) { }
public void SaveItself()
{
Save();
}
public User SaveItselfAndReturn()
{
return Save();
}
public async Task SaveItselfAsync()
{
await SaveAsync();
}
public async Task<User> SaveItselfAndReturnAsync()
{
return await SaveAsync();
}
}
public class UserCaller
{
private User value;
public UserCaller Save() { return null; }
public async Task<UserCaller> SaveAsync() { return await Task.FromResult<UserCaller>(null); }
public async Task UserSaveAsync()
{
var x = DataPortal.Fetch<User>();
// This should have an error because it doesn't set the return value
await x.SaveAsync();
await this.SaveAsync();
// This should have an error because it doesn't set the return value
await x.SaveAsync(true).ConfigureAwait(false);
x = await x.SaveAsync();
var a = await x.SaveAsync();
this.value = await x.SaveAsync();
await DataPortal.Fetch<User>().SaveAsync();
}
public void UserSave()
{
var x = DataPortal.Fetch<User>();
// This should have an error because it doesn't set the return value
x.Save();
this.Save();
// This should have an error because it doesn't set the return value
x.Save(true);
x = x.Save();
var a = x.Save();
x.Save(true);
this.value = x.Save();
this.DoThis(() => { this.value = x.Save(); });
this.DoThis(() => this.value = x.Save());
// This should have an error because it doesn't set the return value
this.DoThis(() => { x.Save(); });
this.ReturnThis(() => x.Save());
this.ReturnThis(() => { return x.Save(); });
this.ReturnThis(() =>
{
var q = DataPortal.Fetch<User>();
// This should have an error because it doesn't set the return value
q.Save();
return null;
});
DataPortal.Fetch<User>().Save();
}
public User ReturnsUser()
{
var x = DataPortal.Fetch<User>();
return x.Save();
}
public async Task<User> ReturnsUserAsync()
{
var x = DataPortal.Fetch<User>();
return await x.SaveAsync();
}
private void DoThis(Action a)
{
a();
}
private User ReturnThis(Func<User> a)
{
return a();
}
} | 19.657143 | 105 | 0.66686 | [
"MIT"
] | angtianqiang/csla | Source/Csla.Analyzers/Csla.Analyzers.IntegrationTests/Csla.Analyzers.IntegrationTests/AnalyzerTests.cs | 3,442 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using Microsoft.Practices.Unity;
using System.Linq;
using Rebus.Configuration;
namespace Rebus.Unity
{
public class UnityContainerAdapter : IContainerAdapter
{
readonly IUnityContainer unityContainer;
public UnityContainerAdapter(IUnityContainer unityContainer)
{
this.unityContainer = unityContainer;
}
public IEnumerable<IHandleMessages> GetHandlerInstancesFor<T>()
{
IEnumerable<IHandleMessages> handlers = unityContainer.ResolveAll<IHandleMessages<T>>();
IEnumerable<IHandleMessages> asyncHandlers = unityContainer.ResolveAll<IHandleMessagesAsync<T>>();
return handlers.Union(asyncHandlers).ToArray();
}
public void Release(IEnumerable handlerInstances)
{
foreach (var disposable in handlerInstances.OfType<IDisposable>())
{
disposable.Dispose();
}
}
public void SaveBusInstances(IBus bus)
{
unityContainer.RegisterInstance(typeof(IBus), bus);
unityContainer.RegisterType<IMessageContext>(new InjectionFactory(c => MessageContext.GetCurrent()));
}
}
}
| 32.097561 | 114 | 0.645897 | [
"Apache-2.0"
] | jacobbonde/Rebus | src/Rebus.Unity/UnityContainerAdapter.cs | 1,318 | C# |
/*
* LIO - Order Management API
*
* API de gerenciamento de pedidos da LIO.
*
* OpenAPI spec version: 1.0.0
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.IO;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reflection;
using RestSharp;
using NUnit.Framework;
using IO.Swagger.Client;
using IO.Swagger.Api;
using IO.Swagger.Model;
namespace IO.Swagger.Test
{
/// <summary>
/// Class for testing OrderManagementApi
/// </summary>
/// <remarks>
/// This file is automatically generated by Swagger Codegen.
/// Please update the test case below to test the API endpoint.
/// </remarks>
[TestFixture]
public class OrderManagementApiTests
{
private OrderManagementApi instance;
/// <summary>
/// Setup before each unit test
/// </summary>
[SetUp]
public void Init()
{
instance = new OrderManagementApi();
}
/// <summary>
/// Clean up after each unit test
/// </summary>
[TearDown]
public void Cleanup()
{
}
/// <summary>
/// Test an instance of OrderManagementApi
/// </summary>
[Test]
public void InstanceTest()
{
// TODO uncomment below to test 'IsInstanceOfType' OrderManagementApi
//Assert.IsInstanceOfType(typeof(OrderManagementApi), instance, "instance is a OrderManagementApi");
}
/// <summary>
/// Test OrderAddItem
/// </summary>
[Test]
public void OrderAddItemTest()
{
// TODO uncomment below to test the method and replace null with proper value
//string clientId = null;
//string accessToken = null;
//string merchantId = null;
//string id = null;
//Body1 body = null;
//var response = instance.OrderAddItem(clientId, accessToken, merchantId, id, body);
//Assert.IsInstanceOf<InlineResponse201> (response, "response is InlineResponse201");
}
/// <summary>
/// Test OrderCreate
/// </summary>
[Test]
public void OrderCreateTest()
{
// TODO uncomment below to test the method and replace null with proper value
//string clientId = null;
//string accessToken = null;
//string merchantId = null;
//Body body = null;
//var response = instance.OrderCreate(clientId, accessToken, merchantId, body);
//Assert.IsInstanceOf<InlineResponse201> (response, "response is InlineResponse201");
}
/// <summary>
/// Test OrderDelete
/// </summary>
[Test]
public void OrderDeleteTest()
{
// TODO uncomment below to test the method and replace null with proper value
//string clientId = null;
//string accessToken = null;
//string merchantId = null;
//string id = null;
//instance.OrderDelete(clientId, accessToken, merchantId, id);
}
/// <summary>
/// Test OrderDeleteItem
/// </summary>
[Test]
public void OrderDeleteItemTest()
{
// TODO uncomment below to test the method and replace null with proper value
//string clientId = null;
//string accessToken = null;
//string merchantId = null;
//string id = null;
//string itemId = null;
//var response = instance.OrderDeleteItem(clientId, accessToken, merchantId, id, itemId);
//Assert.IsInstanceOf<InlineResponse201> (response, "response is InlineResponse201");
}
/// <summary>
/// Test OrderGet
/// </summary>
[Test]
public void OrderGetTest()
{
// TODO uncomment below to test the method and replace null with proper value
//string clientId = null;
//string accessToken = null;
//string merchantId = null;
//string id = null;
//var response = instance.OrderGet(clientId, accessToken, merchantId, id);
//Assert.IsInstanceOf<InlineResponse200> (response, "response is InlineResponse200");
}
/// <summary>
/// Test OrderGetByParameters
/// </summary>
[Test]
public void OrderGetByParametersTest()
{
// TODO uncomment below to test the method and replace null with proper value
//string clientId = null;
//string accessToken = null;
//string merchantId = null;
//string parameters = null;
//var response = instance.OrderGetByParameters(clientId, accessToken, merchantId, parameters);
//Assert.IsInstanceOf<List<InlineResponse200>> (response, "response is List<InlineResponse200>");
}
/// <summary>
/// Test OrderGetItem
/// </summary>
[Test]
public void OrderGetItemTest()
{
// TODO uncomment below to test the method and replace null with proper value
//string clientId = null;
//string accessToken = null;
//string merchantId = null;
//string id = null;
//var response = instance.OrderGetItem(clientId, accessToken, merchantId, id);
//Assert.IsInstanceOf<OrdersItems> (response, "response is OrdersItems");
}
/// <summary>
/// Test OrderGetTransactions
/// </summary>
[Test]
public void OrderGetTransactionsTest()
{
// TODO uncomment below to test the method and replace null with proper value
//string clientId = null;
//string accessToken = null;
//string merchantId = null;
//string id = null;
//var response = instance.OrderGetTransactions(clientId, accessToken, merchantId, id);
//Assert.IsInstanceOf<OrdersTransactions> (response, "response is OrdersTransactions");
}
/// <summary>
/// Test OrderUpdate
/// </summary>
[Test]
public void OrderUpdateTest()
{
// TODO uncomment below to test the method and replace null with proper value
//string clientId = null;
//string accessToken = null;
//string merchantId = null;
//string id = null;
//string operation = null;
//instance.OrderUpdate(clientId, accessToken, merchantId, id, operation);
}
/// <summary>
/// Test OrderUpdateItem
/// </summary>
[Test]
public void OrderUpdateItemTest()
{
// TODO uncomment below to test the method and replace null with proper value
//string clientId = null;
//string accessToken = null;
//string merchantId = null;
//string id = null;
//string itemId = null;
//Body2 body = null;
//var response = instance.OrderUpdateItem(clientId, accessToken, merchantId, id, itemId, body);
//Assert.IsInstanceOf<InlineResponse201> (response, "response is InlineResponse201");
}
}
}
| 33.511111 | 112 | 0.558621 | [
"Apache-2.0"
] | DeveloperCielo/LIO-SDK-API-Integracao-Remota-v1-CSHARP | src/IO.Swagger.Test/Api/OrderManagementApiTests.cs | 7,540 | C# |
//----------------------------------------------------------------------------
// <copyright file="Program.cs"
// company="Markus M. Egger">
// Copyright (C) 2018 Markus M. Egger. All rights reserved.
// </copyright>
// <author>Markus M. Egger</author>
// <description>
// The main program class of the "Arrays" console demos.
// </description>
// <version>v1.0.0 2018-06-02T23:34:54+02</version>
//
// This code is inspired by examples and exercises from the book
// "C# Data Structures and Algorithms" (C) 2018 by Marcin Jamro,
// Packt Publishing.
// https://www.packtpub.com/application-development/c-data-structures-and-algorithms-0
//
//----------------------------------------------------------------------------
namespace DataStructuresAndAlgos.Arrays
{
using System;
using System.Linq;
using System.Text;
using Util;
using static System.Console;
/// <summary>
/// The main program class of the "Arrays" console demos.
/// </summary>
internal static class Program
{
#region Fields
private static readonly Random _random = new Random();
private static readonly int[] _numbers =
{
-11, 12, -42,
0, 1, 90,
68, 6, -9
};
private static readonly string[] _names =
{
"Mary", "Marcin", "Ann",
"James", "George", "Nicole",
};
#endregion
/// <summary>
/// The main method of the program.
/// </summary>
/// <param name="args">
/// The program arguments supplied on the command-line.
/// </param>
private static void Main(string[] args)
{
if (args == null)
{
throw new ArgumentNullException(nameof(args));
}
WriteLine();
WriteLine("*** ARRAY DEMOS ***");
WriteLine();
// English month names demo
EnglishMonthNames();
WriteLine();
// Multi-dimensional arrays
MultiDimArrays();
WriteLine();
// Multiplication table
MulTable();
WriteLine();
// Console-based game map sample
GameMap();
WriteLine();
// Console-based transportation schedule sample
TransportationSchedule();
WriteLine();
// Sorting algorithms for arrays
SortNumbers();
WriteLine();
}
// A showcase of simple, single-dimension arrays.
private static void EnglishMonthNames()
{
// Retrieve array of English month names.
var months = DateTimeHelper.GetMonthNames();
WriteLine("English month names:");
WriteLine();
foreach (var monthName in months)
{
WriteLine(monthName);
}
WriteLine();
}
/// <summary>
/// A first showcase of multi-dimensional arrays
/// using a number table.
/// </summary>
private static void MultiDimArrays()
{
var numbers = new int[,]
{
{ 9, 5, -9 },
{ -11, 4, 0 },
{ 6, 115, 3 },
{ -12, -9, 71 },
{ 1, -6, -1 }
};
WriteLine($"The {nameof(numbers)} array is {numbers.GetLength(0)} by {numbers.GetLength(1)} in size.");
WriteLine();
WriteLine("The numbers are:");
WriteLine();
for (var y = 0; y < numbers.GetLength(0); ++y)
{
for (var x = 0; x < numbers.GetLength(1); ++x)
{
Write($"{numbers[y, x],4}");
}
// Put a linefeed after each row.
WriteLine();
}
WriteLine();
}
/// <summary>
/// A second showcase of multi-dimensional arrays using pre-computation.
/// </summary>
private static void MulTable()
{
// Multiplication table.
var mul10Table = new int[10, 10];
// Initialize table.
for (var y = 0; y < mul10Table.GetLength(0); ++y)
{
for (var x = 0; x < mul10Table.GetLength(1); ++x)
{
mul10Table[y, x] =
(x + 1) * (y + 1);
}
}
WriteLine("The multiplication table from 1 x 1 to 10 x 10 is:");
WriteLine();
// Print table
for (var y = 0; y < mul10Table.GetLength(0); ++y)
{
for (var x = 0; x < mul10Table.GetLength(1); ++x)
{
Write($"{mul10Table[y, x],4}");
}
// Put a linefeed after each row.
WriteLine();
}
WriteLine();
}
/// <summary>
/// A nice demo of how a console-based game map could be
/// realized using multi-dimensional arrays and extension methods.
/// </summary>
private static void GameMap()
{
TerrainType[,] gameMap =
{
{
TerrainType.Sand, TerrainType.Sand, TerrainType.Sand,
TerrainType.Sand, TerrainType.Grass, TerrainType.Grass,
TerrainType.Grass, TerrainType.Grass, TerrainType.Grass,
TerrainType.Grass
},
{
TerrainType.Sand, TerrainType.Sand, TerrainType.Sand,
TerrainType.Sand, TerrainType.Grass, TerrainType.Grass,
TerrainType.Grass, TerrainType.Grass, TerrainType.Grass,
TerrainType.Grass
},
{
TerrainType.Sand, TerrainType.Sand, TerrainType.Sand,
TerrainType.Sand, TerrainType.Grass, TerrainType.Grass,
TerrainType.Grass, TerrainType.Grass, TerrainType.Grass,
TerrainType.Grass
},
{
TerrainType.Sand, TerrainType.Sand, TerrainType.Sand,
TerrainType.Sand, TerrainType.Grass, TerrainType.Grass,
TerrainType.Grass, TerrainType.Grass, TerrainType.Grass,
TerrainType.Grass
},
{
TerrainType.Sand, TerrainType.Sand, TerrainType.Sand,
TerrainType.Sand, TerrainType.Sand, TerrainType.Sand,
TerrainType.Sand, TerrainType.Wall, TerrainType.Wall,
TerrainType.Wall
},
{
TerrainType.Sand, TerrainType.Sand, TerrainType.Sand,
TerrainType.Sand, TerrainType.Sand, TerrainType.Sand,
TerrainType.Sand, TerrainType.Wall, TerrainType.Sand,
TerrainType.Sand
},
{
TerrainType.Sand, TerrainType.Sand, TerrainType.Sand,
TerrainType.Sand, TerrainType.Sand, TerrainType.Sand,
TerrainType.Sand, TerrainType.Wall, TerrainType.Sand,
TerrainType.Sand
},
{
TerrainType.Water, TerrainType.Water, TerrainType.Water,
TerrainType.Water, TerrainType.Water, TerrainType.Water,
TerrainType.Water, TerrainType.Wall, TerrainType.Sand,
TerrainType.Sand
},
{
TerrainType.Water, TerrainType.Water, TerrainType.Water,
TerrainType.Water, TerrainType.Water, TerrainType.Water,
TerrainType.Water, TerrainType.Wall, TerrainType.Sand,
TerrainType.Sand
},
{
TerrainType.Water, TerrainType.Water, TerrainType.Water,
TerrainType.Water, TerrainType.Water, TerrainType.Water,
TerrainType.Water, TerrainType.Wall, TerrainType.Water,
TerrainType.Water
},
{
TerrainType.Water, TerrainType.Water, TerrainType.Water,
TerrainType.Water, TerrainType.Water, TerrainType.Water,
TerrainType.Water, TerrainType.Wall, TerrainType.Water,
TerrainType.Water
},
};
// Set the console to a proper encoding.
Console.OutputEncoding = Encoding.UTF8;
// Save console colors.
var foregroundColor = Console.ForegroundColor;
WriteLine("A simple game map:");
WriteLine();
// Print the game map.
for (var y = 0; y < gameMap.GetLength(0); ++y)
{
for (var x = 0; x < gameMap.GetLength(1); ++x)
{
Console.ForegroundColor =
gameMap[y, x].GetColor();
Write(gameMap[y, x].GetChar());
}
WriteLine();
}
// Restore console colors.
Console.ForegroundColor = foregroundColor;
WriteLine();
}
/// <summary>
/// Demo of a daily transportation schedule for different
/// transportation types. Showcases jagged arrays.
/// </summary>
private static void TransportationSchedule()
{
// Get the transportation types as an array to aid
// random schedule generation.
var transportationTypes =
Enum.GetNames(typeof(TransportationType));
// Compute the number of transportation types defined.
// This will also help in random schedule generation.
var transportationTypeCount =
transportationTypes.Length;
// The daily schedule (jagged array) with the first dimension
// representing the month.
var dailySchedule = new TransportationType[12][];
// Get the number of days in each month.
var monthDays = DateTimeHelper.GetMonthDays();
// We will also need the names of the months for a nice output.
var monthNames = DateTimeHelper.GetMonthNames();
// Iterate over the months
for (var monthIndex = 0; monthIndex < 12; ++monthIndex)
{
// First we need the correct number of slots (days) for
// each month.
dailySchedule[monthIndex] =
new TransportationType[monthDays[monthIndex]];
for (var dayIndex = 0; dayIndex < monthDays[monthIndex]; ++dayIndex)
{
// Generate random transportation for each day.
var randomIndex =
_random.Next(transportationTypeCount);
var transportationType = (TransportationType)
Enum.Parse(typeof(TransportationType), transportationTypes[randomIndex]);
dailySchedule[monthIndex][dayIndex] =
transportationType;
}
}
// Schedule title
WriteLine("DAILY TRANSPORTATION SCHEDULE");
WriteLine();
// For a nice output we need to know the longest month name.
var maxMonthNameLength =
monthNames.Max(m => m.Length) + 2;
// The hard part is done, now display the schedule.
for (var monthIndex = 0; monthIndex < 12; ++monthIndex)
{
var monthName = monthNames[monthIndex];
monthName =
monthName.PadRight(maxMonthNameLength);
Write(monthName);
for (var dayIndex = 0; dayIndex < dailySchedule[monthIndex].GetLength(0); ++dayIndex)
{
var transportation = dailySchedule[monthIndex][dayIndex];
transportation.Write();
// Extra space for better readability.
//Write(' ');
}
WriteLine();
}
WriteLine();
}
/// <summary>
/// Showcase of the implementation of various sorting algorithms.
/// </summary>
private static void SortNumbers()
{
// Header
WriteLine("SORTING ALGORITHMS");
WriteLine();
// Numbers
Write("Numbers: ");
WriteLine(String.Join(", ", _numbers));
WriteLine();
Write("Sorted by Selection Sort: ");
WriteLine(String.Join(", ", _numbers.SelectionSort()));
Write("Sorted by Insertion Sort: ");
WriteLine(String.Join(", ", _numbers.InsertionSort()));
Write("Sorted by Bubble Sort: ");
WriteLine(String.Join(", ", _numbers.BubbleSort()));
Write("Sorted by Quick Sort: ");
WriteLine(String.Join(", ", _numbers.QuickSort()));
WriteLine();
// Names
WriteLine($"Names: {String.Join(", ", _names)}");
WriteLine();
Write("Sorted by Selection Sort: ");
WriteLine(String.Join(", ", _names.SelectionSort()));
Write("Sorted by Insertion Sort: ");
WriteLine(String.Join(", ", _names.InsertionSort()));
Write("Sorted by Bubble Sort: ");
WriteLine(String.Join(", ", _names.BubbleSort()));
Write("Sorted by Quick Sort: ");
WriteLine(String.Join(", ", _names.QuickSort()));
WriteLine();
}
}
}
| 32.893868 | 115 | 0.490787 | [
"MIT"
] | prof79/PPCSDSA | Arrays/Program.cs | 13,949 | C# |
using Dna;
using Dna.AspNet;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
namespace ChatWpf.Web.Server
{
public class Program
{
public static void Main(string[] args)
{
CreateBuildWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateBuildWebHostBuilder(string[] args)
{
return WebHost.CreateDefaultBuilder()
.UseDnaFramework(construct =>
{
construct.AddFileLogger();
})
.UseStartup<Startup>();
}
}
}
| 23.5 | 78 | 0.564648 | [
"Unlicense"
] | lego963/ChatWpf | ChatWpf.Web.Server/Program.cs | 613 | C# |
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
namespace Sample.Domain.Managers
{
public class SampleManager : IManager
{
private IDbConnection Connection;
public SampleManager(IDbConnection connection)
{
Connection = connection;
}
public string Get()
{
var contents = new StringBuilder();
contents.AppendLine($"Resolved Correctly: { this.ToString() }");
contents.AppendLine($"Resolved Correctly: { Connection.ToString() }");
return contents.ToString();
}
}
}
| 20.576923 | 73 | 0.723364 | [
"MIT"
] | cfryerdev/composition-root-example | Sample.Domain/Managers/SampleManager.cs | 537 | C# |
namespace ClearHl7.Codes.V280
{
/// <summary>
/// HL7 Version 2 Table 0618 - Protection Code.
/// </summary>
/// <remarks>https://www.hl7.org/fhir/v2/0618</remarks>
public enum CodeProtectionCode
{
/// <summary>
/// LI - Listed.
/// </summary>
Listed,
/// <summary>
/// UL - Unlisted (Should not appear in directories).
/// </summary>
UnlistedShouldNotAppearInDirectories,
/// <summary>
/// UP - Unpublished.
/// </summary>
Unpublished
}
} | 24.25 | 61 | 0.505155 | [
"MIT"
] | davebronson/clear-hl7-net | src/ClearHl7.Codes/V280/CodeProtectionCode.cs | 584 | C# |
using System;
using Moq;
using NUnit.Framework;
using Umbraco.Core.Composing;
using Umbraco.Core.Configuration;
using Umbraco.Core.Models;
using Umbraco.Tests.TestHelpers;
using Umbraco.Tests.Testing;
using Umbraco.Web.PublishedCache.XmlPublishedCache;
namespace Umbraco.Tests.Routing
{
// purpose: test the values returned by PublishedContentCache.GetRouteById
// and .GetByRoute (no caching at all, just routing nice urls) including all
// the quirks due to hideTopLevelFromPath and backward compatibility.
[UmbracoTest(Database = UmbracoTestOptions.Database.NewSchemaPerFixture)]
public class UrlRoutesTests : TestWithDatabaseBase
{
#region Test Setup
protected override string GetXmlContent(int templateId)
{
return @"<?xml version=""1.0"" encoding=""utf-8""?>
<!DOCTYPE root[
<!ELEMENT Doc ANY>
<!ATTLIST Doc id ID #REQUIRED>
]>
<root id=""-1"">
<Doc id=""1000"" parentID=""-1"" level=""1"" path=""-1,1000"" nodeName=""A"" urlName=""a"" sortOrder=""1"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""" + templateId + @""" createDate=""2012-06-12T14:13:17"" updateDate=""2012-07-20T18:50:43"" writerName=""admin"" creatorName=""admin"" isDoc="""">
<Doc id=""1001"" parentID=""1000"" level=""2"" path=""-1,1000,1001"" nodeName=""B"" urlName=""b"" sortOrder=""1"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""" + templateId + @""" createDate=""2012-07-20T18:06:45"" updateDate=""2012-07-20T19:07:31"" writerName=""admin"" creatorName=""admin"" isDoc="""">
<Doc id=""1002"" parentID=""1001"" level=""3"" path=""-1,1000,1001,1002"" nodeName=""C"" urlName=""c"" sortOrder=""1"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""" + templateId + @""" createDate=""2012-07-20T18:06:45"" updateDate=""2012-07-20T19:07:31"" writerName=""admin"" creatorName=""admin"" isDoc="""">
<Doc id=""1003"" parentID=""1002"" level=""4"" path=""-1,1000,1001,1002,1003"" nodeName=""D"" urlName=""d"" sortOrder=""1"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""" + templateId + @""" createDate=""2012-07-20T18:06:45"" updateDate=""2012-07-20T19:07:31"" writerName=""admin"" creatorName=""admin"" isDoc="""">
</Doc>
</Doc>
</Doc>
</Doc>
<Doc id=""2000"" parentID=""-1"" level=""1"" path=""-1,2000"" nodeName=""X"" urlName=""x"" sortOrder=""1"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""" + templateId + @""" createDate=""2012-06-12T14:13:17"" updateDate=""2012-07-20T18:50:43"" writerName=""admin"" creatorName=""admin"" isDoc="""">
<Doc id=""2001"" parentID=""2000"" level=""2"" path=""-1,2000,2001"" nodeName=""Y"" urlName=""y"" sortOrder=""1"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""" + templateId + @""" createDate=""2012-06-12T14:13:17"" updateDate=""2012-07-20T18:50:43"" writerName=""admin"" creatorName=""admin"" isDoc="""">
<Doc id=""2002"" parentID=""2001"" level=""3"" path=""-1,2000,2001,2002"" nodeName=""Z"" urlName=""z"" sortOrder=""1"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""" + templateId + @""" createDate=""2012-06-12T14:13:17"" updateDate=""2012-07-20T18:50:43"" writerName=""admin"" creatorName=""admin"" isDoc="""">
</Doc>
</Doc>
<Doc id=""2003"" parentID=""2000"" level=""2"" path=""-1,2000,2003"" nodeName=""A"" urlName=""a"" sortOrder=""2"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""" + templateId + @""" createDate=""2012-06-12T14:13:17"" updateDate=""2012-07-20T18:50:43"" writerName=""admin"" creatorName=""admin"" isDoc="""">
</Doc>
<Doc id=""2004"" parentID=""2000"" level=""2"" path=""-1,2000,2004"" nodeName=""B"" urlName=""b"" sortOrder=""3"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""" + templateId + @""" createDate=""2012-06-12T14:13:17"" updateDate=""2012-07-20T18:50:43"" writerName=""admin"" creatorName=""admin"" isDoc="""">
<Doc id=""2005"" parentID=""2004"" level=""3"" path=""-1,2000,2004,2005"" nodeName=""C"" urlName=""c"" sortOrder=""1"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""" + templateId + @""" createDate=""2012-06-12T14:13:17"" updateDate=""2012-07-20T18:50:43"" writerName=""admin"" creatorName=""admin"" isDoc="""">
</Doc>
<Doc id=""2006"" parentID=""2004"" level=""3"" path=""-1,2000,2004,2006"" nodeName=""E"" urlName=""e"" sortOrder=""1"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""" + templateId + @""" createDate=""2012-06-12T14:13:17"" updateDate=""2012-07-20T18:50:43"" writerName=""admin"" creatorName=""admin"" isDoc="""">
</Doc>
</Doc>
</Doc>
</root>";
}
protected override void Initialize()
{
base.Initialize();
if (FirstTestInFixture)
ServiceContext.ContentTypeService.Save(new ContentType(-1) { Alias = "Doc", Name = "name" });
}
#endregion
/*
* Just so it's documented somewhere, as of jan. 2017, routes obey the following pseudo-code:
GetByRoute(route, hide = null):
route is "[id]/[path]"
hide = hide ?? global.hide
root = id ? node(id) : document
content = cached(route) ?? DetermineIdByRoute(route, hide)
# route is "1234/path/to/content", finds "content"
# but if there is domain 5678 on "to", the *true* route of "content" is "5678/content"
# so although the route does match, we don't cache it
# there are not other reason not to cache it
if content and no domain between root and content:
cache route (as trusted)
return content
DetermineIdByRoute(route, hide):
route is "[id]/[path]"
try return NavigateRoute(id ?? 0, path, hide:hide)
return null
NavigateRoute(id, path, hide):
if path:
if id:
start = node(id)
else:
start = document
# 'navigate ... from ...' uses lowest sortOrder in case of collision
if hide and ![id]:
# if hiding, then for "/foo" we want to look for "/[any]/foo"
for each child of start:
try return navigate path from child
# but if it fails, we also want to try "/foo"
# fail now if more than one part eg "/foo/bar"
if path is "/[any]/...":
fail
try return navigate path from start
else:
if id:
return node(id)
else:
return root node with lowest sortOrder
GetRouteById(id):
route = cached(id)
if route:
return route
# never cache the route, it may be colliding
route = DetermineRouteById(id)
if route:
cache route (as not trusted)
return route
DetermineRouteById(id):
node = node(id)
walk up from node to domain or root, assemble parts = url segments
if !domain and global.hide:
if id.parent:
# got /top/[path]content, can remove /top
remove top part
else:
# got /content, should remove only if it is the
# node with lowest sort order
root = root node with lowest sortOrder
if root == node:
remove top part
compose path from parts
route = assemble "[domain.id]/[path]"
return route
*/
/*
* The Xml structure for the following tests is:
*
* root
* A 1000
* B 1001
* C 1002
* D 1003
* X 2000
* Y 2001
* Z 2002
* A 2003
* B 2004
* C 2005
* E 2006
*
*/
[TestCase(1000, false, "/a")]
[TestCase(1001, false, "/a/b")]
[TestCase(1002, false, "/a/b/c")]
[TestCase(1003, false, "/a/b/c/d")]
[TestCase(2000, false, "/x")]
[TestCase(2001, false, "/x/y")]
[TestCase(2002, false, "/x/y/z")]
[TestCase(2003, false, "/x/a")]
[TestCase(2004, false, "/x/b")]
[TestCase(2005, false, "/x/b/c")]
[TestCase(2006, false, "/x/b/e")]
public void GetRouteByIdNoHide(int id, bool hide, string expected)
{
var globalSettings = Mock.Get(Factory.GetInstance<IGlobalSettings>()); //this will modify the IGlobalSettings instance stored in the container
globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(hide);
var umbracoContext = GetUmbracoContext("/test", 0, globalSettings: globalSettings.Object);
var cache = umbracoContext.ContentCache as PublishedContentCache;
if (cache == null) throw new Exception("Unsupported IPublishedContentCache, only the Xml one is supported.");
var route = cache.GetRouteById(false, id);
Assert.AreEqual(expected, route);
}
[TestCase(1000, true, "/")]
[TestCase(1001, true, "/b")]
[TestCase(1002, true, "/b/c")]
[TestCase(1003, true, "/b/c/d")]
[TestCase(2000, true, "/x")]
[TestCase(2001, true, "/y")]
[TestCase(2002, true, "/y/z")]
[TestCase(2003, true, "/a")]
[TestCase(2004, true, "/b")] // collision!
[TestCase(2005, true, "/b/c")] // collision!
[TestCase(2006, true, "/b/e")] // risky!
public void GetRouteByIdHide(int id, bool hide, string expected)
{
var globalSettings = Mock.Get(Factory.GetInstance<IGlobalSettings>()); //this will modify the IGlobalSettings instance stored in the container
globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(hide);
var umbracoContext = GetUmbracoContext("/test", 0, globalSettings: globalSettings.Object);
var cache = umbracoContext.ContentCache as PublishedContentCache;
if (cache == null) throw new Exception("Unsupported IPublishedContentCache, only the Xml one is supported.");
var route = cache.GetRouteById(false, id);
Assert.AreEqual(expected, route);
}
[Test]
public void GetRouteByIdCache()
{
var globalSettings = Mock.Get(Factory.GetInstance<IGlobalSettings>()); //this will modify the IGlobalSettings instance stored in the container
globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false);
var umbracoContext = GetUmbracoContext("/test", 0, globalSettings:globalSettings.Object);
var cache = umbracoContext.ContentCache as PublishedContentCache;
if (cache == null) throw new Exception("Unsupported IPublishedContentCache, only the Xml one is supported.");
var route = cache.GetRouteById(false, 1000);
Assert.AreEqual("/a", route);
// GetRouteById registers a non-trusted route, which is cached for
// id -> route queries (fast GetUrl) but *not* for route -> id
// queries (safe inbound routing)
var cachedRoutes = cache.RoutesCache.GetCachedRoutes();
Assert.AreEqual(1, cachedRoutes.Count);
Assert.IsTrue(cachedRoutes.ContainsKey(1000));
Assert.AreEqual("/a", cachedRoutes[1000]);
var cachedIds = cache.RoutesCache.GetCachedIds();
Assert.AreEqual(0, cachedIds.Count);
}
[TestCase("/", false, 1000)]
[TestCase("/a", false, 1000)] // yes!
[TestCase("/a/b", false, 1001)]
[TestCase("/a/b/c", false, 1002)]
[TestCase("/a/b/c/d", false, 1003)]
[TestCase("/x", false, 2000)]
public void GetByRouteNoHide(string route, bool hide, int expected)
{
var globalSettings = Mock.Get(Factory.GetInstance<IGlobalSettings>()); //this will modify the IGlobalSettings instance stored in the container
globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(hide);
var umbracoContext = GetUmbracoContext("/test", 0, globalSettings:globalSettings.Object);
var cache = umbracoContext.ContentCache as PublishedContentCache;
if (cache == null) throw new Exception("Unsupported IPublishedContentCache, only the Xml one is supported.");
const bool preview = false; // make sure we don't cache - but HOW? should be some sort of switch?!
var content = cache.GetByRoute(preview, route);
if (expected < 0)
{
Assert.IsNull(content);
}
else
{
Assert.IsNotNull(content);
Assert.AreEqual(expected, content.Id);
}
}
[TestCase("/", true, 1000)]
[TestCase("/a", true, 2003)]
[TestCase("/a/b", true, -1)]
[TestCase("/x", true, 2000)] // oops!
[TestCase("/x/y", true, -1)] // yes!
[TestCase("/y", true, 2001)]
[TestCase("/y/z", true, 2002)]
[TestCase("/b", true, 1001)] // (hence the 2004 collision)
[TestCase("/b/c", true, 1002)] // (hence the 2005 collision)
public void GetByRouteHide(string route, bool hide, int expected)
{
var globalSettings = Mock.Get(Factory.GetInstance<IGlobalSettings>()); //this will modify the IGlobalSettings instance stored in the container
globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(hide);
var umbracoContext = GetUmbracoContext("/test", 0, globalSettings:globalSettings.Object);
var cache = umbracoContext.ContentCache as PublishedContentCache;
if (cache == null) throw new Exception("Unsupported IPublishedContentCache, only the Xml one is supported.");
const bool preview = false; // make sure we don't cache - but HOW? should be some sort of switch?!
var content = cache.GetByRoute(preview, route);
if (expected < 0)
{
Assert.IsNull(content);
}
else
{
Assert.IsNotNull(content);
Assert.AreEqual(expected, content.Id);
}
}
[Test]
public void GetByRouteCache()
{
var globalSettings = Mock.Get(Factory.GetInstance<IGlobalSettings>()); //this will modify the IGlobalSettings instance stored in the container
globalSettings.Setup(x => x.HideTopLevelNodeFromPath).Returns(false);
var umbracoContext = GetUmbracoContext("/test", 0, globalSettings:globalSettings.Object);
var cache = umbracoContext.ContentCache as PublishedContentCache;
if (cache == null) throw new Exception("Unsupported IPublishedContentCache, only the Xml one is supported.");
var content = cache.GetByRoute(false, "/a/b/c");
Assert.IsNotNull(content);
Assert.AreEqual(1002, content.Id);
// GetByRoute registers a trusted route, which is cached both for
// id -> route queries (fast GetUrl) and for route -> id queries
// (fast inbound routing)
var cachedRoutes = cache.RoutesCache.GetCachedRoutes();
Assert.AreEqual(1, cachedRoutes.Count);
Assert.IsTrue(cachedRoutes.ContainsKey(1002));
Assert.AreEqual("/a/b/c", cachedRoutes[1002]);
var cachedIds = cache.RoutesCache.GetCachedIds();
Assert.AreEqual(1, cachedIds.Count);
Assert.IsTrue(cachedIds.ContainsKey("/a/b/c"));
Assert.AreEqual(1002, cachedIds["/a/b/c"]);
}
}
}
| 44.827586 | 346 | 0.594231 | [
"MIT"
] | bharanijayasuri/umbraco8 | src/Umbraco.Tests/Routing/UrlRoutesTests.cs | 15,602 | C# |
/*
Copyright (C) 2020 Jean-Camille Tournier (mail@tournierjc.fr)
This file is part of QLCore Project https://github.com/OpenDerivatives/QLCore
QLCore is free software: you can redistribute it and/or modify it
under the terms of the QLCore and QLNet license. You should have received a
copy of the license along with this program; if not, license is
available at https://github.com/OpenDerivatives/QLCore/LICENSE.
QLCore is a forked of QLNet which is a based on QuantLib, a free-software/open-source
library for financial quantitative analysts and developers - http://quantlib.org/
The QuantLib license is available online at http://quantlib.org/license.shtml and the
QLNet license is available online at https://github.com/amaggiulli/QLNet/blob/develop/LICENSE.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICAR PURPOSE. See the license for more details.
*/
using System;
namespace QLCore
{
//! Local volatility surface derived from a Black vol surface
/*! For details about this implementation refer to
"Stochastic Volatility and Local Volatility," in
"Case Studies and Financial Modelling Course Notes," by
Jim Gatheral, Fall Term, 2003
see www.math.nyu.edu/fellows_fin_math/gatheral/Lecture1_Fall02.pdf
\bug this class is untested, probably unreliable.
*/
public class LocalVolSurface : LocalVolTermStructure
{
Handle<BlackVolTermStructure> blackTS_;
Handle<YieldTermStructure> riskFreeTS_, dividendTS_;
Handle<Quote> underlying_;
public LocalVolSurface(Handle<BlackVolTermStructure> blackTS, Handle<YieldTermStructure> riskFreeTS,
Handle<YieldTermStructure> dividendTS, Handle<Quote> underlying)
: base(blackTS.link.businessDayConvention(), blackTS.link.dayCounter())
{
blackTS_ = blackTS;
riskFreeTS_ = riskFreeTS;
dividendTS_ = dividendTS;
underlying_ = underlying;
}
public LocalVolSurface(Handle<BlackVolTermStructure> blackTS, Handle<YieldTermStructure> riskFreeTS,
Handle<YieldTermStructure> dividendTS, double underlying)
: base(blackTS.link.businessDayConvention(), blackTS.link.dayCounter())
{
blackTS_ = blackTS;
riskFreeTS_ = riskFreeTS;
dividendTS_ = dividendTS;
underlying_ = new Handle<Quote>(new SimpleQuote(underlying));
}
// TermStructure interface
public override Date referenceDate() { return blackTS_.link.referenceDate(); }
public override DayCounter dayCounter() { return blackTS_.link.dayCounter(); }
public override Date maxDate() { return blackTS_.link.maxDate(); }
// VolatilityTermStructure interface
public override double minStrike() { return blackTS_.link.minStrike(); }
public override double maxStrike() { return blackTS_.link.maxStrike(); }
protected override double localVolImpl(double t, double underlyingLevel)
{
double dr = riskFreeTS_.currentLink().discount(t, true);
double dq = dividendTS_.currentLink().discount(t, true);
double forwardValue = underlying_.currentLink().value() * dq / dr;
// strike derivatives
double strike, y, dy, strikep, strikem;
double w, wp, wm, dwdy, d2wdy2;
strike = underlyingLevel;
y = Math.Log(strike / forwardValue);
dy = ((Math.Abs(y) > 0.001) ? y * 0.0001 : 0.000001);
strikep = strike * Math.Exp(dy);
strikem = strike / Math.Exp(dy);
w = blackTS_.link.blackVariance(t, strike, true);
wp = blackTS_.link.blackVariance(t, strikep, true);
wm = blackTS_.link.blackVariance(t, strikem, true);
dwdy = (wp - wm) / (2.0 * dy);
d2wdy2 = (wp - 2.0 * w + wm) / (dy * dy);
// time derivative
double dt, wpt, wmt, dwdt;
if (t.IsEqual(0.0))
{
dt = 0.0001;
double drpt = riskFreeTS_.currentLink().discount(t + dt, true);
double dqpt = dividendTS_.currentLink().discount(t + dt, true);
double strikept = strike * dr * dqpt / (drpt * dq);
wpt = blackTS_.link.blackVariance(t + dt, strikept, true);
Utils.QL_REQUIRE(wpt >= w, () =>
"decreasing variance at strike " + strike + " between time " + t + " and time " + (t + dt));
dwdt = (wpt - w) / dt;
}
else
{
dt = Math.Min(0.0001, t / 2.0);
double drpt = riskFreeTS_.currentLink().discount(t + dt, true);
double drmt = riskFreeTS_.currentLink().discount(t - dt, true);
double dqpt = dividendTS_.currentLink().discount(t + dt, true);
double dqmt = dividendTS_.currentLink().discount(t - dt, true);
double strikept = strike * dr * dqpt / (drpt * dq);
double strikemt = strike * dr * dqmt / (drmt * dq);
wpt = blackTS_.link.blackVariance(t + dt, strikept, true);
wmt = blackTS_.link.blackVariance(t - dt, strikemt, true);
Utils.QL_REQUIRE(wpt >= w, () =>
"decreasing variance at strike " + strike + " between time " + t + " and time " + (t + dt));
Utils.QL_REQUIRE(w >= wmt, () =>
"decreasing variance at strike " + strike + " between time " + (t - dt) + " and time " + t);
dwdt = (wpt - wmt) / (2.0 * dt);
}
if (dwdy.IsEqual(0.0) && d2wdy2.IsEqual(0.0)) // avoid /w where w might be 0.0
{
return Math.Sqrt(dwdt);
}
else
{
double den1 = 1.0 - y / w * dwdy;
double den2 = 0.25 * (-0.25 - 1.0 / w + y * y / w / w) * dwdy * dwdy;
double den3 = 0.5 * d2wdy2;
double den = den1 + den2 + den3;
double result = dwdt / den;
Utils.QL_REQUIRE(result >= 0.0, () =>
"negative local vol^2 at strike " + strike + " and time " + t + "; the black vol surface is not smooth enough");
return Math.Sqrt(result);
}
}
}
}
| 43.666667 | 141 | 0.608142 | [
"BSD-3-Clause"
] | tournierjc/QLCore | QLCore/TermStructures/Volatility/EquityFx/LocalVolSurface.cs | 6,290 | C# |
using System;
namespace Xbox_360_Guide_Button_Remapper
{
[Serializable()]
public class Key
{
public string KeyCode { get; set; }
public int KeyValue { get; set; }
public Key()
{
KeyCode = string.Empty;
KeyValue = 0;
}
public Key(int val, string code)
{
KeyCode = code;
KeyValue = val;
}
}
}
| 17.28 | 43 | 0.479167 | [
"MIT"
] | pinumbernumber/Xbox-360-Guide-Button-Remapper | Source/Xbox 360 Guide Button Remapper/Key.cs | 434 | C# |
// ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschraenkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
using System.Collections.Generic;
using System.Threading.Tasks;
using NodaTime;
using Squidex.Domain.Apps.Entities.Apps;
using Squidex.Infrastructure;
namespace Squidex.Domain.Apps.Entities.Schemas
{
public interface ISchemasHash
{
Task<(Instant Create, string Hash)> GetCurrentHashAsync(DomainId appId);
ValueTask<string> ComputeHashAsync(IAppEntity app, IEnumerable<ISchemaEntity> schemas);
}
}
| 34.608696 | 95 | 0.537688 | [
"MIT"
] | EdoardoTona/squidex | backend/src/Squidex.Domain.Apps.Entities/Schemas/ISchemasHash.cs | 798 | C# |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Management.Automation;
using Microsoft.Azure.Commands.CosmosDB.Models;
using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters;
using Microsoft.Azure.Management.CosmosDB.Models;
using Microsoft.Azure.Management.Internal.Resources.Utilities.Models;
using Microsoft.Azure.Commands.CosmosDB.Helpers;
using Microsoft.Azure.Commands.CosmosDB.Exceptions;
using Microsoft.Rest.Azure;
using Microsoft.Azure.PowerShell.Cmdlets.CosmosDB.Exceptions;
using Microsoft.Azure.Management.CosmosDB;
namespace Microsoft.Azure.Commands.CosmosDB
{
[Cmdlet("Update", ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "CosmosDBSqlDatabase", DefaultParameterSetName = NameParameterSet, SupportsShouldProcess = true), OutputType(typeof(PSSqlDatabaseGetResults), typeof(ResourceNotFoundException))]
public class UpdateAzCosmosDBSqlDatabase : AzureCosmosDBCmdletBase
{
[Parameter(Mandatory = true, ParameterSetName = NameParameterSet, HelpMessage = Constants.ResourceGroupNameHelpMessage)]
[ResourceGroupCompleter]
[ValidateNotNullOrEmpty]
public string ResourceGroupName { get; set; }
[Parameter(Mandatory = true, ParameterSetName = NameParameterSet, HelpMessage = Constants.AccountNameHelpMessage)]
[ValidateNotNullOrEmpty]
public string AccountName { get; set; }
[Parameter(Mandatory = false, HelpMessage = Constants.DatabaseNameHelpMessage)]
[ValidateNotNullOrEmpty]
public string Name { get; set; }
[Parameter(Mandatory = false, HelpMessage = Constants.SqlDatabaseThroughputHelpMessage)]
public int? Throughput { get; set; }
[Parameter(Mandatory = false, HelpMessage = Constants.AutoscaleMaxThroughputHelpMessage)]
public int? AutoscaleMaxThroughput { get; set; }
[Parameter(Mandatory = true, ValueFromPipeline = true, ParameterSetName = ParentObjectParameterSet, HelpMessage = Constants.AccountObjectHelpMessage)]
[ValidateNotNull]
public PSDatabaseAccountGetResults ParentObject { get; set; }
[Parameter(Mandatory = true, ValueFromPipeline = true, ParameterSetName = ObjectParameterSet, HelpMessage = Constants.SqlDatabaseObjectHelpMessage)]
[ValidateNotNull]
public PSSqlDatabaseGetResults InputObject { get; set; }
public override void ExecuteCmdlet()
{
if (ParameterSetName.Equals(ParentObjectParameterSet, StringComparison.Ordinal))
{
ResourceIdentifier resourceIdentifier = new ResourceIdentifier(ParentObject.Id);
ResourceGroupName = resourceIdentifier.ResourceGroupName;
AccountName = resourceIdentifier.ResourceName;
}
else if (ParameterSetName.Equals(ObjectParameterSet, StringComparison.Ordinal))
{
ResourceIdentifier resourceIdentifier = new ResourceIdentifier(InputObject.Id);
ResourceGroupName = resourceIdentifier.ResourceGroupName;
Name = resourceIdentifier.ResourceName;
AccountName = ResourceIdentifierExtensions.GetDatabaseAccountName(resourceIdentifier);
}
SqlDatabaseGetResults readSqlDatabaseGetResults = null;
try
{
readSqlDatabaseGetResults = CosmosDBManagementClient.SqlResources.GetSqlDatabase(ResourceGroupName, AccountName, Name);
}
catch (CloudException e)
{
if (e.Response.StatusCode == System.Net.HttpStatusCode.NotFound)
{
throw new ResourceNotFoundException(message: string.Format(ExceptionMessage.NotFound, Name), innerException: e);
}
}
CreateUpdateOptions options = ThroughputHelper.PopulateCreateUpdateOptions(Throughput, AutoscaleMaxThroughput);
SqlDatabaseCreateUpdateParameters sqlDatabaseCreateUpdateParameters = new SqlDatabaseCreateUpdateParameters
{
Resource = new SqlDatabaseResource
{
Id = Name
},
Options = options
};
if (ShouldProcess(Name, "Updating an existing CosmosDB Sql Database"))
{
SqlDatabaseGetResults sqlDatabaseGetResults = CosmosDBManagementClient.SqlResources.CreateUpdateSqlDatabaseWithHttpMessagesAsync(ResourceGroupName, AccountName, Name, sqlDatabaseCreateUpdateParameters).GetAwaiter().GetResult().Body;
WriteObject(new PSSqlDatabaseGetResults(sqlDatabaseGetResults));
}
return;
}
}
}
| 50.536364 | 256 | 0.675121 | [
"MIT"
] | 3quanfeng/azure-powershell | src/CosmosDB/CosmosDB/SQL/UpdateAzCosmosDBSqlDatabase.cs | 5,452 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using CharlieBackend.Business.Services.Interfaces;
using CharlieBackend.Core.DTO.Schedule;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using CharlieBackend.Core;
using CharlieBackend.Core.Models.ResultModel;
using Swashbuckle.AspNetCore.Annotations;
namespace CharlieBackend.Api.Controllers
{
/// <summary>
/// Controller to manage schedules data
/// </summary>
[Route("api/schedules")]
[ApiController]
public class SchedulesController : ControllerBase
{
private readonly IScheduleService _scheduleService;
/// <summary>
/// Schedules cocontroller constructor
/// </summary>
/// <param name="scheduleService"></param>
public SchedulesController(IScheduleService scheduleService)
{
_scheduleService = scheduleService;
}
/// <summary>
/// Add new schedule
/// </summary>
/// <response code="200">Successful add of schedule</response>
/// <response code="HTTP: 400, API: 0">Can not create schedule due to wrong request data</response>
/// <response code="HTTP: 404, API: 3">Can not create schedule due to missing request data</response>
[SwaggerResponse(200, type: typeof(ScheduleDto))]
[Authorize(Roles = "Secretary, Admin")]
[HttpPost]
public async Task<ActionResult<ScheduleDto>> PostSchedule([FromBody]CreateScheduleDto scheduleDTO)
{
var resSchedule = await _scheduleService
.CreateScheduleAsync(scheduleDTO);
return resSchedule.ToActionResult();
}
/// <summary>
/// Gets all schedules
/// </summary>
/// <response code="200">Successful return of schedules list</response>
[SwaggerResponse(200, type: typeof(List<ScheduleDto>))]
[Authorize(Roles = "Secretary, Admin")]
[HttpGet]
public async Task<ActionResult<List<ScheduleDto>>> GetAllSchedules()
{
var resSchedule = await _scheduleService.GetAllSchedulesAsync();
return resSchedule.ToActionResult();
}
/// <summary>
/// Returns schedules of exact student group
/// </summary>
/// <response code="200">Successful return of schedules list</response>
/// <response code="HTTP: 404, API: 3">Error, student group not found</response>
[SwaggerResponse(200, type: typeof(IList<ScheduleDto>))]
[Authorize(Roles = "Secretary, Admin")]
[HttpGet("{studentGroupId}/groupSchedule")]
public async Task<ActionResult<List<ScheduleDto>>> GetSchedulesByStudentGroupIdAsync(long studentGroupId)
{
var foundSchedules = await _scheduleService.GetSchedulesByStudentGroupIdAsync(studentGroupId);
return foundSchedules.ToActionResult();
}
/// <summary>
/// Updates shedule
/// </summary>
/// <response code="200">Successful update of schedule</response>
/// <response code="HTTP: 404, API: 3">Error, update data is missing</response>
/// <response code="HTTP: 400, API: 0">Error, update data is wrong</response>
[SwaggerResponse(200, type: typeof(ScheduleDto))]
[Authorize(Roles = "Secretary, Admin")]
[HttpPut("{scheduleId}")]
public async Task<ActionResult<ScheduleDto>> PutSchedule(long scheduleId, [FromBody]UpdateScheduleDto updateScheduleDto)
{
var foundSchedules = await _scheduleService.UpdateStudentGroupAsync(scheduleId, updateScheduleDto);
return foundSchedules.ToActionResult();
}
/// <summary>
/// Deletes exact schedule
/// </summary>
/// <response code = "200" > Successful delete of schedule</response>
/// <response code="HTTP: 404, API: 3">Error, given schedule not found</response>
[Authorize(Roles = "Secretary, Admin")]
[HttpDelete("{scheduleId}")]
public async Task<ActionResult<ScheduleDto>> DeleteSchedule(long scheduleId)
{
var foundSchedules = await _scheduleService.DeleteScheduleByIdAsync(scheduleId);
return foundSchedules.ToActionResult();
}
}
}
| 38.769912 | 128 | 0.645971 | [
"MIT"
] | BobinMathew/WhatBackend | CharlieBackend.Api/Controllers/SchedulesController.cs | 4,383 | C# |
#nullable disable
namespace EFCore6WebAPI;
public partial class Employee
{
public long Idemployee { get; set; }
public string Name { get; set; }
public long Iddepartment { get; set; }
public virtual Department IddepartmentNavigation { get; set; }
}
| 20.692308 | 66 | 0.70632 | [
"MIT"
] | ignatandrei/Presentations | 2021/WhatsNewNet6/code/EFCore6/EFCore6WebAPI/Employee.cs | 271 | C# |
using System;
namespace Cortside.DomainEvent.EntityFramework.IntegrationTests.Events {
public class WidgetStateChangedEvent {
public int WidgetId { get; set; }
public DateTime Timestamp { get; set; }
}
}
| 25.444444 | 72 | 0.707424 | [
"MIT"
] | SubjectiveReality/cortside.domainevent | src/Cortside.DomainEvent.EntityFramework.IntegrationTests/Events/WidgetStateChangedEvent.cs | 229 | C# |
using System.Reflection;
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("AWSSDK.Comprehend")]
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - Amazon Comprehend. Amazon Comprehend is an AWS service for gaining insight into the content of text and documents. It can be used to determine the topics contained in your documents, the topics they discuss, the predominant sentiment expressed in them, the predominant language used, and more. For more information, go to the Amazon Comprehend product page. To get started, see the Amazon Comprehend Developer Guide.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("Amazon Web Services SDK for .NET")]
[assembly: AssemblyCompany("Amazon.com, Inc")]
[assembly: AssemblyCopyright("Copyright 2009-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("3.3")]
[assembly: AssemblyFileVersion("3.3.107.8")] | 55.375 | 497 | 0.760722 | [
"Apache-2.0"
] | gnurg/aws-sdk-net | sdk/code-analysis/ServiceAnalysis/Comprehend/Properties/AssemblyInfo.cs | 1,772 | C# |
using Kentico.Kontent.Delivery.Abstractions;
using Kentico.Kontent.Delivery.Urls.QueryParameters;
using PetrSvihlik.Com.Models.ContentTypes;
using Kontent.Statiq;
using Statiq.Common;
using Statiq.Core;
using Statiq.Razor;
using System.Linq;
using PetrSvihlik.Com.Models.ViewModels;
namespace PetrSvihlik.Com.Pipelines
{
public class PostsPipeline : Pipeline
{
public PostsPipeline(IDeliveryClient deliveryClient)
{
Dependencies.AddRange(nameof(SiteMetadataPipeline));
InputModules = new ModuleList{
new Kontent<Article>(deliveryClient)
.WithQuery(new DepthParameter(1), new IncludeTotalCountParameter(), new OrderParameter($"elements.{Article.PublishDateCodename}", SortOrder.Descending)),
new SetMetadata(nameof(Category), Config.FromDocument((doc, ctx) =>
{
// Add category (useful for grouping)
return doc.AsKontent<Article>().SelectedCategory.System.Codename;
})),
new SetMetadata(nameof(Article.SelectedCategory), Config.FromDocument((doc, ctx) =>
{
// Add some extra metadata to be used later for creating filenames
return doc.AsKontent<Article>().SelectedCategory;
})),
new SetMetadata(nameof(Tag), Config.FromDocument((doc, ctx) =>
{
// Add tag (useful for grouping)
return doc.AsKontent<Article>().TagObjects.Select(t=>t.System.Codename);
})),
new SetMetadata(nameof(Article.TagObjects), Config.FromDocument((doc, ctx) =>
{
// Add some extra metadata to be used later for creating filenames
return doc.AsKontent<Article>().TagObjects;
})),
new SetDestination(Config.FromDocument((doc, ctx) => new NormalizedPath($"posts/{doc.AsKontent<Article>().Slug}.html" ))),
};
ProcessModules = new ModuleList {
new MergeContent(new ReadFiles(patterns: "Post.cshtml") ),
new RenderRazor()
.WithModel(Config.FromDocument((document, context) =>
new PostViewModel(document.AsKontent<Article>(),
context.Outputs.FromPipeline(nameof(SiteMetadataPipeline)).Select(x => x.AsKontent<SiteMetadata>()).FirstOrDefault()))),
new KontentImageProcessor()
};
OutputModules = new ModuleList {
new WriteFiles(),
};
}
}
} | 45.827586 | 173 | 0.589165 | [
"MIT"
] | petrsvihlik/petrsvihlik.com | Pipelines/PostsPipeline.cs | 2,658 | C# |
using System;
using System.Threading.Tasks;
using Microsoft.Bot.Schema;
namespace Microsoft.Bot.Builder.Skills
{
public interface ISkillTransport
{
Task<bool> ForwardToSkillAsync(ITurnContext dialogContext, Activity activity, Action<Activity> tokenRequestHandler = null);
Task CancelRemoteDialogsAsync(ITurnContext turnContext);
void Disconnect();
}
} | 26.066667 | 131 | 0.749361 | [
"MIT"
] | 3ve4me/botframework-solutions | lib/csharp/microsoft.bot.builder.skills/Microsoft.Bot.Builder.Skills/ISkillTransport.cs | 393 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the macie2-2020-01-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.Macie2.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.Macie2.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for AdminAccount Object
/// </summary>
public class AdminAccountUnmarshaller : IUnmarshaller<AdminAccount, XmlUnmarshallerContext>, IUnmarshaller<AdminAccount, JsonUnmarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
AdminAccount IUnmarshaller<AdminAccount, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context)
{
throw new NotImplementedException();
}
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public AdminAccount Unmarshall(JsonUnmarshallerContext context)
{
context.Read();
if (context.CurrentTokenType == JsonToken.Null)
return null;
AdminAccount unmarshalledObject = new AdminAccount();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("accountId", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.AccountId = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("status", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.Status = unmarshaller.Unmarshall(context);
continue;
}
}
return unmarshalledObject;
}
private static AdminAccountUnmarshaller _instance = new AdminAccountUnmarshaller();
/// <summary>
/// Gets the singleton.
/// </summary>
public static AdminAccountUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 33.94898 | 149 | 0.624887 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/Macie2/Generated/Model/Internal/MarshallTransformations/AdminAccountUnmarshaller.cs | 3,327 | C# |
namespace TraktNet.Objects.Post.Comments
{
using Get.Shows;
using Objects.Json;
using System.Threading;
using System.Threading.Tasks;
/// <summary>A show comment post.</summary>
public class TraktShowCommentPost : TraktCommentPost, ITraktShowCommentPost
{
/// <summary>
/// Gets or sets the required Trakt show for the show comment post.
/// See also <seealso cref="ITraktShow" />.
/// </summary>
public ITraktShow Show { get; set; }
public override Task<string> ToJson(CancellationToken cancellationToken = default)
{
IObjectJsonWriter<ITraktShowCommentPost> objectJsonWriter = JsonFactoryContainer.CreateObjectWriter<ITraktShowCommentPost>();
return objectJsonWriter.WriteObjectAsync(this, cancellationToken);
}
public override void Validate()
{
// TODO
}
}
}
| 31.793103 | 137 | 0.650759 | [
"MIT"
] | henrikfroehling/Trakt.NET | Source/Lib/Trakt.NET/Objects/Post/Comments/Implementations/TraktShowCommentPost.cs | 924 | C# |
using Game.Engine.Interactions.Built_In;
using Game.Engine.Items;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Game.Engine.Monsters;
using Game.Engine.Monsters.MonsterFactories;
namespace Game.Engine.Interactions.Built_In
{
class WhiteDragonNormalStrategy : IWhiteDragonStrategy
{
public void Execute(GameSession parentSession, PrincessEncounter princess)
{
int GetListBoxChoice(List<string> choices)
{
return parentSession.ListBoxInteractionChoice(choices);
}
parentSession.SendText("\nWhat do you want?");
DragonEvolved whiteDragonFight = new DragonEvolved(parentSession.currentPlayer.Level);
// get player choice
int choice = GetListBoxChoice(new List<string>() { "I'm looking for a key. Do you have one?", "I've heard you have a lot of gold. Let's fight!", "N-n-n-nothing, bye!" });
switch (choice)
{
case 0:
parentSession.SendText("\nMaybe I have...or maybe I don't. How about a little exchange? I really want a golden sword. Bring it to me and I'll give you a key.");
int choice2 = GetListBoxChoice(new List<string>() { "Ok", "No way! I won't give you anything!" });
if (choice2 == 0)
{
if (parentSession.TestForItem("item0011"))
{
parentSession.SendText("\nThanks human. A key? Hahahaha, I don't have it! One cheeky princess took it from me long time ago. Find her if you want a key.");
princess.Strategy = new PrincessNormalStrategy();
}
else
{
return;
}
}
else
{
parentSession.SendText("Then I won't let you go!");
parentSession.FightThisMonster(whiteDragonFight);
parentSession.SendText("\nYou defeated White Dragon! But...there's no key.");
princess.Strategy = new PrincessGratefulStrategy();
}
break;
case 1:
parentSession.SendText("You'll regret it!");
parentSession.FightThisMonster(whiteDragonFight);
parentSession.SendText("\nYou defeated White Dragon! You take all the gold but...there's no key.");
princess.Strategy = new PrincessGratefulStrategy();
parentSession.UpdateStat(8, 100);
break;
default:
parentSession.SendText("What a weird human.");
break;
}
}
}
} | 46.96875 | 184 | 0.525283 | [
"MIT"
] | doworek/rpg-game | Engine/Interactions/Built-In/WhiteDragonNormalStrategy.cs | 3,008 | 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 Microsoft.Data.Entity.FunctionalTests;
namespace Microsoft.Data.Entity.InMemory.FunctionalTests
{
public class AsyncQueryInMemoryTest : AsyncQueryTestBase<NorthwindQueryInMemoryFixture>
{
public AsyncQueryInMemoryTest(NorthwindQueryInMemoryFixture fixture)
: base(fixture)
{
}
}
}
| 31.5 | 111 | 0.740079 | [
"Apache-2.0"
] | suryasnath/csharp | test/EntityFramework.InMemory.FunctionalTests/AsyncQueryInMemoryTest.cs | 504 | C# |
/* Copyright (c) 2019 Samsung Electronics Co., 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.
.*
.*/
using System;
using System.ComponentModel;
using Tizen.NUI.BaseComponents;
using Tizen.NUI.Binding;
namespace Tizen.NUI
{
/// <summary>
/// GridLayout is a 2D grid pattern layout that consists of a set of rows and columns.
/// </summary>
public partial class GridLayout : LayoutGroup
{
/// <summary>
/// ColumnProperty
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public static readonly BindableProperty ColumnProperty = BindableProperty.CreateAttached("Column", typeof(int), typeof(GridLayout), CellUndefined, validateValue: (bindable, value) => (int)value >= 0, propertyChanged: OnChildPropertyChanged);
/// <summary>
/// ColumnSpanProperty
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public static readonly BindableProperty ColumnSpanProperty = BindableProperty.CreateAttached("ColumnSpan", typeof(int), typeof(GridLayout), 1, validateValue: (bindable, value) => (int)value >= 1, propertyChanged: OnChildPropertyChanged);
/// <summary>
/// RowProperty
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public static readonly BindableProperty RowProperty = BindableProperty.CreateAttached("Row", typeof(int), typeof(GridLayout), CellUndefined, validateValue: (bindable, value) => (int)value >= 0, propertyChanged: OnChildPropertyChanged);
/// <summary>
/// RowSpanProperty
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public static readonly BindableProperty RowSpanProperty = BindableProperty.CreateAttached("RowSpan", typeof(int), typeof(GridLayout), 1, validateValue: (bindable, value) => (int)value >= 1, propertyChanged: OnChildPropertyChanged);
/// <summary>
/// HorizontalStretchProperty
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public static readonly BindableProperty HorizontalStretchProperty = BindableProperty.CreateAttached("HorizontalStretch", typeof(StretchFlags), typeof(GridLayout), default(StretchFlags), validateValue: ValidateEnum((int)StretchFlags.None, (int)StretchFlags.ExpandAndFill), propertyChanged: OnChildPropertyChanged);
/// <summary>
/// VerticalStretchProperty
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public static readonly BindableProperty VerticalStretchProperty = BindableProperty.CreateAttached("VerticalStretch", typeof(StretchFlags), typeof(GridLayout), default(StretchFlags), validateValue: ValidateEnum((int)StretchFlags.None, (int)StretchFlags.ExpandAndFill), propertyChanged: OnChildPropertyChanged);
/// <summary>
/// HorizontalAlignmentProperty
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public static readonly BindableProperty HorizontalAlignmentProperty = BindableProperty.CreateAttached("HorizontalAlignment", typeof(Alignment), typeof(GridLayout), Alignment.Start, validateValue: ValidateEnum((int)Alignment.Start, (int)Alignment.End), propertyChanged: OnChildPropertyChanged);
/// <summary>
/// VerticalAlignmentProperty
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public static readonly BindableProperty VerticalAlignmentProperty = BindableProperty.CreateAttached("VerticalAlignment", typeof(Alignment), typeof(GridLayout), Alignment.Start, validateValue: ValidateEnum((int)Alignment.Start, (int)Alignment.End), propertyChanged: OnChildPropertyChanged);
private const int CellUndefined = int.MinValue;
private Orientation gridOrientation = Orientation.Horizontal;
private int columns = 1;
private int rows = 1;
private float columnSpacing = 0;
private float rowSpacing = 0;
/// <summary>
/// Enumeration for the direction in which the content is laid out
/// </summary>
/// <since_tizen> 8 </since_tizen>
public enum Orientation
{
/// <summary>
/// Horizontal (row)
/// </summary>
Horizontal,
/// <summary>
/// Vertical (column)
/// </summary>
Vertical
}
/// <summary>
/// Get the column index.
/// </summary>
/// <since_tizen> 8 </since_tizen>
public static int GetColumn(View view) => GetAttachedValue<int>(view, ColumnProperty);
/// <summary>
/// Get the column span.
/// </summary>
/// <since_tizen> 8 </since_tizen>
public static int GetColumnSpan(View view) => GetAttachedValue<int>(view, ColumnSpanProperty);
/// <summary>
/// Get the row index.
/// </summary>
/// <since_tizen> 8 </since_tizen>
public static int GetRow(View view) => GetAttachedValue<int>(view, RowProperty);
/// <summary>
/// Get the row span.
/// </summary>
/// <since_tizen> 8 </since_tizen>
public static int GetRowSpan(View view) => GetAttachedValue<int>(view, RowSpanProperty);
/// <summary>
/// Get the value how child is resized within its horizontal space.
/// </summary>
/// <since_tizen> 8 </since_tizen>
public static StretchFlags GetHorizontalStretch(View view) => GetAttachedValue<StretchFlags>(view, HorizontalStretchProperty);
/// <summary>
/// Get the value how child is resized within its vertical space.
/// </summary>
/// <since_tizen> 8 </since_tizen>
public static StretchFlags GetVerticalStretch(View view) => GetAttachedValue<StretchFlags>(view, VerticalStretchProperty);
/// <summary>
/// Get the horizontal alignment of this child.
/// </summary>
/// <since_tizen> 8 </since_tizen>
public static Alignment GetHorizontalAlignment(View view) => GetAttachedValue<Alignment>(view, HorizontalAlignmentProperty);
/// <summary>
/// Get the vertical alignment of this child.
/// </summary>
/// <since_tizen> 8 </since_tizen>
public static Alignment GetVerticalAlignment(View view) => GetAttachedValue<Alignment>(view, VerticalAlignmentProperty);
/// <summary>
/// Set the column index.
/// </summary>
/// <since_tizen> 8 </since_tizen>
public static void SetColumn(View view, int value) => SetAttachedValue(view, ColumnProperty, value);
/// <summary>
/// Set the column span.
/// </summary>
/// <since_tizen> 8 </since_tizen>
public static void SetColumnSpan(View view, int value) => SetAttachedValue(view, ColumnSpanProperty, value);
/// <summary>
/// Set the row index.
/// </summary>
/// <since_tizen> 8 </since_tizen>
public static void SetRow(View view, int value) => SetAttachedValue(view, RowProperty, value);
/// <summary>
/// Set the row span.
/// </summary>
/// <since_tizen> 8 </since_tizen>
public static void SetRowSpan(View view, int value) => SetAttachedValue(view, RowSpanProperty, value);
/// <summary>
/// Set the value how child is resized within its horizontal space. <see cref="StretchFlags.Fill"/> by default.
/// </summary>
/// <since_tizen> 8 </since_tizen>
public static void SetHorizontalStretch(View view, StretchFlags value) => SetAttachedValue(view, HorizontalStretchProperty, value);
/// <summary>
/// Set the value how child is resized within its vertical space. <see cref="StretchFlags.Fill"/> by default.
/// </summary>
/// <since_tizen> 8 </since_tizen>
public static void SetVerticalStretch(View view, StretchFlags value) => SetAttachedValue(view, VerticalStretchProperty, value);
/// <summary>
/// Set the horizontal alignment of this child inside the cells.
/// </summary>
/// <since_tizen> 8 </since_tizen>
public static void SetHorizontalAlignment(View view, Alignment value) => SetAttachedValue(view, HorizontalAlignmentProperty, value);
/// <summary>
/// Set the vertical alignment of this child inside the cells.
/// </summary>
/// <since_tizen> 8 </since_tizen>
public static void SetVerticalAlignment(View view, Alignment value) => SetAttachedValue(view, VerticalAlignmentProperty, value);
/// <summary>
/// The distance between columns.
/// </summary>
/// <since_tizen> 8 </since_tizen>
public float ColumnSpacing
{
get => columnSpacing;
set
{
if (columnSpacing == value) return;
columnSpacing = value > 0 ? value : 0;
RequestLayout();
}
}
/// <summary>
/// The distance between rows.
/// </summary>
/// <since_tizen> 8 </since_tizen>
public float RowSpacing
{
get => rowSpacing;
set
{
if (rowSpacing == value) return;
rowSpacing = value > 0 ? value : 0;
RequestLayout();
}
}
/// <summary>
/// Get/Set the orientation in the layout
/// </summary>
/// <exception cref="InvalidEnumArgumentException">Thrown when using invalid arguments that are enumerators.</exception>
/// <since_tizen> 8 </since_tizen>
public Orientation GridOrientation
{
get => gridOrientation;
set
{
if (gridOrientation == value) return;
if (value != Orientation.Horizontal && value != Orientation.Vertical)
throw new InvalidEnumArgumentException(nameof(GridOrientation));
gridOrientation = value;
RequestLayout();
}
}
/// <summary>
/// GridLayout Constructor.
/// </summary>
/// <returns> New Grid object.</returns>
/// <since_tizen> 6 </since_tizen>
public GridLayout()
{
}
/// <summary>
/// Gets or Sets the number of columns in the grid.
/// </summary>
/// <since_tizen> 6 </since_tizen>
public int Columns
{
get => columns;
set
{
if (value == columns) return;
if (value < 1) value = 1;
columns = value;
RequestLayout();
}
}
/// <summary>
/// Gets or Sets the number of rows in the grid.
/// </summary>
/// <since_tizen> 8 </since_tizen>
public int Rows
{
get => rows;
set
{
if (value == rows) return;
if (value < 1) value = 1;
rows = value;
RequestLayout();
}
}
/// <summary>
/// Measure the layout and its content to determine the measured width and the measured height.<br />
/// </summary>
/// <param name="widthMeasureSpec">horizontal space requirements as imposed by the parent.</param>
/// <param name="heightMeasureSpec">vertical space requirements as imposed by the parent.</param>
/// <since_tizen> 6 </since_tizen>
protected override void OnMeasure(MeasureSpecification widthMeasureSpec, MeasureSpecification heightMeasureSpec)
{
int widthSize;
int heightSize;
var widthMode = widthMeasureSpec.Mode;
var heightMode = heightMeasureSpec.Mode;
InitChildren(widthMeasureSpec, heightMeasureSpec);
if (widthMode == MeasureSpecification.ModeType.Exactly)
widthSize = (int)widthMeasureSpec.Size.AsRoundedValue();
else
widthSize = (int)(hLocations[maxColumnConut] - hLocations[0] - columnSpacing);
if (heightMode == MeasureSpecification.ModeType.Exactly)
heightSize = (int)heightMeasureSpec.Size.AsRoundedValue();
else
heightSize = (int)(vLocations[maxRowCount] - vLocations[0] - rowSpacing);
LayoutLength widthLength = new LayoutLength(widthSize + Padding.Start + Padding.End);
LayoutLength heightLenght = new LayoutLength(heightSize + Padding.Top + Padding.Bottom);
MeasuredSize widthMeasuredSize = ResolveSizeAndState(widthLength, widthMeasureSpec, MeasuredSize.StateType.MeasuredSizeOK);
MeasuredSize heightMeasuredSize = ResolveSizeAndState(heightLenght, heightMeasureSpec, MeasuredSize.StateType.MeasuredSizeOK);
SetMeasuredDimensions(widthMeasuredSize, heightMeasuredSize);
}
/// <summary>
/// Assign a size and position to each of its children.<br />
/// </summary>
/// <param name="changed">This is a new size or position for this layout.</param>
/// <param name="left">Left position, relative to parent.</param>
/// <param name="top"> Top position, relative to parent.</param>
/// <param name="right">Right position, relative to parent.</param>
/// <param name="bottom">Bottom position, relative to parent.</param>
/// <since_tizen> 6 </since_tizen>
protected override void OnLayout(bool changed, LayoutLength left, LayoutLength top, LayoutLength right, LayoutLength bottom)
{
InitChildrenWithExpand(MeasuredWidth.Size - Padding.Start - Padding.End, MeasuredHeight.Size - Padding.Top - Padding.Bottom);
for (int i = 0; i < gridChildren.Length; i++)
{
GridChild child = gridChildren[i];
View view = child.LayoutItem?.Owner;
if (view == null) continue;
Alignment halign = GetHorizontalAlignment(view);
Alignment valign = GetVerticalAlignment(view);
int column = child.Column.Start;
int row = child.Row.Start;
int columnEnd = child.Column.End;
int rowEnd = child.Row.End;
float l = hLocations[column] + Padding.Start + view.Margin.Start;
float t = vLocations[row] + Padding.Top + view.Margin.Top;
float width = hLocations[columnEnd] - hLocations[column] - ColumnSpacing - view.Margin.Start - view.Margin.End;
float height = vLocations[rowEnd] - vLocations[row] - RowSpacing - view.Margin.Top - view.Margin.Bottom;
if (!child.Column.Stretch.HasFlag(StretchFlags.Fill))
{
l += (width - child.LayoutItem.MeasuredWidth.Size.AsDecimal()) * halign.ToFloat();
width = child.LayoutItem.MeasuredWidth.Size.AsDecimal();
}
if (!child.Row.Stretch.HasFlag(StretchFlags.Fill))
{
t += (height - child.LayoutItem.MeasuredHeight.Size.AsDecimal()) * valign.ToFloat();
height = child.LayoutItem.MeasuredHeight.Size.AsDecimal();
}
child.LayoutItem.Layout(new LayoutLength(l), new LayoutLength(t), new LayoutLength(l + width), new LayoutLength(t + height));
}
}
/// <summary>
/// The value how child is resized within its space.
/// </summary>
/// <since_tizen> 8 </since_tizen>
[Flags]
public enum StretchFlags
{
/// <summary>
/// Respect mesured size of the child.
/// </summary>
/// <since_tizen> 8 </since_tizen>
None = 0,
/// <summary>
/// Resize to completely fill the space.
/// </summary>
/// <since_tizen> 8 </since_tizen>
Fill = 1,
/// <summary>
/// Expand to share available space in GridLayout.
/// </summary>
/// <since_tizen> 8 </since_tizen>
Expand = 2,
/// <summary>
/// Expand to share available space in GridLayout and fill the space.
/// </summary>
/// <since_tizen> 8 </since_tizen>
ExpandAndFill = Fill + Expand,
}
/// <summary>
/// The alignment of the grid layout child.
/// </summary>
/// <since_tizen> 8 </since_tizen>
public enum Alignment
{
/// <summary>
/// At the start of the container.
/// </summary>
/// <since_tizen> 8 </since_tizen>
Start = 0,
/// <summary>
/// At the center of the container
/// </summary>
/// <since_tizen> 8 </since_tizen>
Center = 1,
/// <summary>
/// At the end of the container.
/// </summary>
/// <since_tizen> 8 </since_tizen>
End = 2,
}
}
// Extension Method of GridLayout.Alignment.
internal static class AlignmentExtension
{
public static float ToFloat(this GridLayout.Alignment align)
{
return 0.5f * (float)align;
}
}
}
| 41.391705 | 321 | 0.596805 | [
"Apache-2.0",
"MIT"
] | Coquinho/TizenFX | src/Tizen.NUI/src/public/Layouting/GridLayout.cs | 17,966 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ExemploWindows
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
| 22.304348 | 65 | 0.614035 | [
"MIT"
] | carloscds/Palestras | VSSummit2019/WindowsForms/ExemploWindows/ExemploWindows/Program.cs | 515 | C# |
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices.ComTypes;
using System.Text;
using NUnit.Framework;
using RoseByte.SharpFiles.Extensions;
namespace RoseByte.SharpFiles.Tests
{
[TestFixture]
public class FileTests
{
private static FsFolder AppFsFolder =>
(FsFolder)Directory.GetParent(Assembly.GetExecutingAssembly().Location).FullName.ToPath();
private readonly FsFolder _folder = AppFsFolder.CombineFolder("FileTests");
[OneTimeSetUp]
public void Setup()
{
_folder.Create();
}
[OneTimeTearDown]
public void TearDown()
{
_folder.Remove();
}
[Test]
public void ShouldCreateInstance()
{
var path = "C:\\test.txt";
var sut = path.ToFile();
Assert.That(sut.Path, Is.EqualTo(path));
}
[Test]
public void ShouldReturnEncoding()
{
var sut = _folder.CombineFile(nameof(ShouldReturnEncoding));
sut.Write("A");
Assert.That(sut.Encoding, Is.EqualTo(Encoding.UTF8));
File.WriteAllText(sut, "AV", Encoding.ASCII);
Assert.That(sut.Encoding, Is.EqualTo(Encoding.ASCII));
}
[Test]
public void ShouldTestEncoding()
{
var sut = _folder.CombineFile(nameof(ShouldTestEncoding));
sut.Write("A");
Assert.That(sut.HasEncoding(Encoding.UTF8), Is.True);
Assert.That(sut.HasEncoding(Encoding.ASCII), Is.False);
File.WriteAllText(sut, "AV", Encoding.ASCII);
Assert.That(sut.HasEncoding(Encoding.ASCII), Is.True);
Assert.That(sut.HasEncoding(Encoding.UTF8), Is.False);
}
[Test]
public void ShouldTestIfFileExists()
{
var sut = "C:\\test_not_here.txt".ToFile();
Assert.That(sut.Exists, Is.False);
sut = Path.GetFullPath(Assembly.GetExecutingAssembly().Location).ToFile();
Assert.That(sut.Exists, Is.True);
}
[Test]
public void ShouldReturnFalseToIsFolder()
{
var sut = "C:\\test.txt".ToFile();
Assert.That(sut.IsFile, Is.True);
Assert.That(sut.IsFolder, Is.False);
}
[Test]
public void ShouldReturnFileName()
{
var fileName = Path.GetFileName(Assembly.GetExecutingAssembly().Location);
var sut = Path.GetFullPath(Assembly.GetExecutingAssembly().Location).ToFile();
Assert.That(sut.Name, Is.EqualTo(fileName));
}
[Test]
public void ShouldReturnFileNameWithoutExtension()
{
var fileName = Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().Location);
var sut = Path.GetFullPath(Assembly.GetExecutingAssembly().Location).ToFile();
Assert.That(sut.NameWithoutExtension, Is.EqualTo(fileName));
}
[Test]
public void ShouldGetParentDirectory()
{
var file = Directory.GetParent(Assembly.GetExecutingAssembly().Location).FullName;
var parentDir = Directory.GetParent(file).FullName;
var sut = Path.Combine(file).ToFile();
var parent = sut.Parent;
Assert.That(parent.ToString(), Is.EqualTo(parentDir));
}
[Test]
public void ShouldCopySmallFileWithoutProgress()
{
var sut = _folder.CombineFile("ShouldCopySmallFileWithoutProgress_1.txt");
File.WriteAllText(sut, "ABCD");
var file = _folder.CombineFile("ShouldCopySmallFileWithoutProgress_2.txt");
Assert.That(File.Exists(sut));
sut.Copy(file);
Assert.That(File.Exists(file));
Assert.That(sut.Content, Is.EqualTo(file.Content));
}
[Test]
public void ShouldCopySmallFileWithProgress()
{
var sut = _folder.CombineFile("ShouldCopySmallFileWithoutProgress_1.txt");
File.WriteAllText(sut, "ABCD");
var file = _folder.CombineFile("ShouldCopySmallFileWithoutProgress_2.txt");
Assert.That(File.Exists(sut));
var progresses = new List<int>();
sut.Copy(file, i => progresses.Add(i));
Assert.That(File.Exists(file));
Assert.That(sut.Content, Is.EqualTo(file.Content));
Assert.That(progresses.SingleOrDefault(), Is.EqualTo(100));
}
[Test]
public void ShouldRemoveFile()
{
var sut = _folder.CombineFile("ShouldRemoveFile_1.txt");
File.WriteAllText(sut, "ABCD");
Assert.That(File.Exists(sut));
sut.Remove();
Assert.That(!File.Exists(sut));
}
[Test]
public void ShouldGetFilesContent()
{
var folder = AppFsFolder.CombineFolder("CopyTest");
folder.Create();
File.WriteAllText(folder.CombineFile("test1.txt"), "ABCD");
var sut = folder.CombineFile("test1.txt");
Assert.That(sut.Content, Is.EqualTo("ABCD"));
folder.Remove();
}
[Test]
public void ShouldWriteFilesContent()
{
var sut = _folder.CombineFile("ShouldWriteFilesContent.txt");
File.WriteAllText(sut, "");
Assert.That(File.ReadAllText(sut).Length, Is.EqualTo(0));
sut.Write("AAAA");
Assert.That(File.ReadAllText(sut), Is.EqualTo("AAAA"));
}
[Test]
public void ShouldCalculateHash()
{
var sut = _folder.CombineFile("ShouldCalculateHash.txt");
sut.Write("1");
Assert.That(sut.Hash, Is.EqualTo(new []
{
90, 189, 182, 23, 95, 130, 15, 10, 195, 216,
100, 127, 187, 31, 122, 11, 204, 145, 117, 122,
120, 42, 138, 20, 85, 112, 148, 76, 166, 160,
12, 150
}));
}
[Test]
public void ShouldCalculateSize()
{
var message = "111";
var folder = AppFsFolder.CombineFolder("CopyTest");
folder.Create();
var sut = folder.CombineFile("test5.txt");
sut.Write(message);
Assert.That(sut.Size, Is.EqualTo(message.Length * 2));
folder.Remove();
}
[Test]
public void ShouldRecalculateSize()
{
var message = "111";
var sut = _folder.CombineFile(nameof(ShouldRecalculateSize));
sut.Write(message);
Assert.That(sut.Size, Is.EqualTo(message.Length * 2));
sut.Write(message + message);
sut.RefreshSize();
Assert.That(sut.Size, Is.EqualTo(message.Length * 3));
}
[Test]
public void ShouldWriteFilesContentWhenFileDoesNotExist()
{
var folder = AppFsFolder.CombineFolder("CopyTest");
folder.Create();
var sut = folder.CombineFile("test3.txt");
sut.Write("AAAA");
Assert.That(File.ReadAllText(sut), Is.EqualTo("AAAA"));
folder.Remove();
}
[Test]
public void ShouldRemoveReadOnlyFile()
{
var sut = _folder.CombineFile(nameof(ShouldRemoveReadOnlyFile));
File.WriteAllText(sut, "ABCD");
File.SetAttributes(sut, FileAttributes.ReadOnly);
Assert.That(File.Exists(sut));
sut.Remove();
Assert.That(!File.Exists(sut));
}
[Test]
public void ShouldThrowWhenCantRemoveFile()
{
var target = AppFsFolder.CombineFile("RoseByte.SharpFiles.Tests.dll");
Assert.That(
() => target.Remove(),
Throws.Exception.With.Message.Contains(
$"is locked by: "));
}
[Test]
public void ShouldThrowOnCopyingWithoutProgressOverLockedFile()
{
var sut = AppFsFolder.CombineFile("TestFiles\\nuget.exe");
var target = AppFsFolder.CombineFile("RoseByte.SharpFiles.Tests.dll");
Assert.That(
() => sut.Copy(target),
Throws.Exception.With.Message.StartsWith($"File '{sut}' could not be copied to '{target}': "));
}
}
} | 32.084806 | 111 | 0.525771 | [
"MIT"
] | mgottvald/SharpFilePath | SharpFilepath.Tests/Internal/FileTests.cs | 9,082 | C# |
using CryptoExchange.Net.ExchangeInterfaces;
using FTX.Net.Converters;
using FTX.Net.Enums;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;
namespace FTX.Net.Objects.Spot
{
/// <summary>
/// User trade info
/// </summary>
public class FTXUserTrade: ICommonTrade
{
/// <summary>
/// Fill id
/// </summary>
public long Id { get; set; }
/// <summary>
/// Symbol
/// </summary>
[JsonProperty("market")]
public string Symbol { get; set; } = string.Empty;
/// <summary>
/// Fee paid
/// </summary>
public decimal Fee { get; set; }
/// <summary>
/// Fee rate
/// </summary>
public decimal FeeRate { get; set; }
/// <summary>
/// Fee currency
/// </summary>
public string FeeCurrency { get; set; } = string.Empty;
/// <summary>
/// Future
/// </summary>
public string Future { get; set; } = string.Empty;
/// <summary>
/// Liquidity
/// </summary>
[JsonConverter(typeof(LiquidityTypeConverter))]
public LiquidityType Liquidity { get; set; }
/// <summary>
/// Base currency
/// </summary>
public string? BaseCurrency { get; set; }
/// <summary>
/// Quote currency
/// </summary>
public string? QuoteCurrency { get; set; }
/// <summary>
/// Order id
/// </summary>
public long OrderId { get; set; }
/// <summary>
/// Trade id
/// </summary>
public long TradeId { get; set; }
/// <summary>
/// Order price
/// </summary>
public decimal Price { get; set; }
/// <summary>
/// Order quantity
/// </summary>
[JsonProperty("size")]
public decimal Quantity { get; set; }
/// <summary>
/// Order side
/// </summary>
[JsonConverter(typeof(OrderSideConverter))]
public OrderSide Side { get; set; }
/// <summary>
/// Timestamp
/// </summary>
public DateTime Time { get; set; }
/// <summary>
/// Type
/// </summary>
public string Type { get; set; } = string.Empty;
string ICommonTrade.CommonId => Id.ToString();
decimal ICommonTrade.CommonPrice => Price;
decimal ICommonTrade.CommonQuantity => Quantity;
decimal ICommonTrade.CommonFee => Fee;
string? ICommonTrade.CommonFeeAsset => FeeCurrency;
DateTime ICommonTrade.CommonTradeTime => Time;
}
}
| 27.44898 | 63 | 0.515242 | [
"MIT"
] | wclark17/FTX.Net | FTX.Net/Objects/Spot/FTXUserTrade.cs | 2,692 | C# |
using Samples.Application;
using StoryTeller;
using StoryTeller.Grammars.Tables;
namespace Samples.Fixtures
{
public class CalculatorFixture : Fixture
{
private readonly Calculator _calculator = new Calculator();
// SAMPLE: start-with-sentence
[FormatAs("Start with {value}")]
public void StartWith(double value)
{
_calculator.Value = value;
}
// ENDSAMPLE
[FormatAs("Add {value}")]
public void Add(double value)
{
_calculator.Add(value);
}
[FormatAs("Subtract {value}")]
public void Subtract(double value)
{
_calculator.Subtract(value);
}
[FormatAs("Multiply by {value}")]
public void MultiplyBy(double value)
{
_calculator.MultiplyBy(value);
}
[FormatAs("Divide by {value}")]
public void DivideBy(double value)
{
_calculator.DivideBy(value);
}
// SAMPLE: the-value-should-be-sentence
[FormatAs("The value should be {value}")]
public double TheValueShouldBe()
{
return _calculator.Value;
}
// ENDSAMPLE
// SAMPLE: multiple-inputs-sentence
[FormatAs("Adding {x} to {y} should equal {returnValue}")]
public double AddingNumbersTogether(double x, double y)
{
_calculator.Value = x;
_calculator.Add(y);
return _calculator.Value;
}
// ENDSAMPLE
[ExposeAsTable("The sum of two columns should be")]
[return: AliasAs("sum")]
public double AddingNumbersTogetherAsTable(double x, double y)
{
_calculator.Value = x;
_calculator.Add(y);
return _calculator.Value;
}
// SAMPLE: sentence-with-output-parameters
[FormatAs("For X={X} and Y={Y}, the Sum should be {Sum} and the Product should be {Product}")]
public void SumAndProduct(int X, int Y, out int Sum, out int Product)
{
Sum = X + Y;
Product = X * Y;
}
// ENDSAMPLE
// SAMPLE: decision-tree-with-multiple-outputs
[ExposeAsTable("Sum and Product Operations")]
public void Operations(int X, int Y, out int Sum, out int Product)
{
Sum = X + Y;
Product = X*Y;
}
// ENDSAMPLE
}
/*
// SAMPLE: CalculatorFixture
public class CalculatorFixture : Fixture
{
private readonly Calculator _calculator = new Calculator();
[FormatAs("Start with {value}")]
public void StartWith(double value)
{
_calculator.Value = value;
}
[FormatAs("Add {value}")]
public void Add(double value)
{
_calculator.Add(value);
}
[FormatAs("Subtract {value}")]
public void Subtract(double value)
{
_calculator.Subtract(value);
}
[FormatAs("Multiply by {value}")]
public void MultiplyBy(double value)
{
_calculator.MultiplyBy(value);
}
[FormatAs("Divide by {value}")]
public void DivideBy(double value)
{
_calculator.DivideBy(value);
}
[FormatAs("The value should be {value}")]
public double TheValueShouldBe()
{
return _calculator.Value;
}
}
// ENDSAMPLE
*/
} | 25.028369 | 103 | 0.538963 | [
"Apache-2.0"
] | SeanKilleen/Storyteller | src/Samples/Fixtures/CalculatorFixture.cs | 3,529 | C# |
using System.Configuration;
using System.Net.Http;
using System.Threading.Tasks;
using AzureFunctionsForSharePoint.Functions;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Azure.WebJobs.Host;
namespace AzureFunctionsForSharePoint.Host
{
/// <summary>
/// Entry point to the actual functionality for an Azure function host
/// This class passes the input from the trigger to the function and logs notification events
/// There are two assemblies to allow hosting the function code in another container without a dependency of the
/// WebJobs SDK
/// </summary>
/// <remarks>
/// If you want to test a locally hosted version, follow the instructions here:
/// https://github.com/lindydonna/FunctionsAsWebProject
/// </remarks>
public static class GetACSAccessTokensFunctionHandler
{
[FunctionName("GetACSAccessTokensFunctionHandler")]
public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "get", Route = "GetACSAccessTokens")] HttpRequestMessage req, TraceWriter log)
{
Log(log, $"C# HTTP trigger function processed a request! RequestUri={req.RequestUri}");
var func = new GetACSAccessTokensHandler(req);
func.FunctionNotify += (sender, args) => Log(log, args.Message);
var getAcsAccessTokensFunctionArgs = new GetACSAccessTokensArgs
{
StorageAccount = ConfigurationManager.AppSettings["ConfigurationStorageAccount"],
StorageAccountKey = ConfigurationManager.AppSettings["ConfigurationStorageAccountKey"]
};
return await Task.Run(() => func.Execute(getAcsAccessTokensFunctionArgs));
}
private static void Log(TraceWriter log, string message)
{
log.Info(message);
}
}
} | 43.545455 | 178 | 0.690501 | [
"MIT"
] | InstantQuick/AzureFunctionsForSharePoint | AzureFunctionsForSharePoint.Host/GetACSAccessTokensFunctionHandler.cs | 1,916 | C# |
using Synuit.Toolkit.Models.Metadata;
//
namespace Synuit.Toolkit.Test.Plugins
{
public class PluginAMetadata : ExplicitModel
{
public string Name { get; set; } = "";
public int Value { get; set; } = 0;
public string SpecificToPluginA { get; set; } = "";
}
}
| 22.153846 | 57 | 0.631944 | [
"MIT"
] | Synuit-Platform/Synuit.Toolkit | tests/Synuit.Toolkit.Tests.Plugin.A/PluginAMetadata.cs | 290 | C# |
using PaySharp.Wechatpay.Domain;
using PaySharp.Wechatpay.Response;
namespace PaySharp.Wechatpay.Request
{
public class TransferQueryRequest : BaseRequest<TransferQueryModel, TransferQueryResponse>
{
public TransferQueryRequest()
{
RequestUrl = "/mmpaymkttransfers/gettransferinfo";
IsUseCert = true;
}
internal override void Execute(Merchant merchant)
{
GatewayData.Remove("notify_url");
GatewayData.Remove("sign_type");
}
}
}
| 25.666667 | 94 | 0.647495 | [
"MIT"
] | Abbotton/PaySharp | src/PaySharp.Wechatpay/Request/TransferQueryRequest.cs | 541 | C# |
using System;
namespace DirectedGraphLesson.Clients
{
public class DepthFirstSearch
{
private DirectedGraph _graph;
private bool[] _marked;
private int _count;
public DepthFirstSearch(DirectedGraph graph, int source)
{
if (graph == null || graph.Vertices == 0)
throw new ArgumentException();
graph.ValidateVertex(source);
_graph = graph;
_marked = new bool[graph.Vertices];
_count = 0;
Search(source);
}
public bool Marked(int vertex)
{
_graph.ValidateVertex(vertex);
return _marked[vertex];
}
public int Count()
{
return _count;
}
private void Search(int vertex)
{
_count++;
_marked[vertex] = true;
foreach (var adjVertex in _graph.VertexAdjacency(vertex))
{
if (!_marked[adjVertex])
Search(adjVertex);
}
}
}
}
| 21.692308 | 70 | 0.478723 | [
"MIT"
] | mainframebot/csharp-datastructures-graphs | DirectedGraphLesson/Clients/DepthFirstSearch.cs | 1,130 | C# |
// <copyright file="ProviderExtensions.cs" company="OpenTelemetry Authors">
// Copyright The OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using OpenTelemetry.Logs;
using OpenTelemetry.Metrics;
using OpenTelemetry.Resources;
using OpenTelemetry.Trace;
namespace OpenTelemetry
{
/// <summary>
/// Contains provider extension methods.
/// </summary>
public static class ProviderExtensions
{
/// <summary>
/// Gets the <see cref="Resource"/> associated with the <see cref="BaseProvider"/>.
/// </summary>
/// <param name="baseProvider"><see cref="BaseProvider"/>.</param>
/// <returns><see cref="Resource"/>if found otherwise <see cref="Resource.Empty"/>.</returns>
public static Resource GetResource(this BaseProvider baseProvider)
{
if (baseProvider is TracerProviderSdk tracerProviderSdk)
{
return tracerProviderSdk.Resource;
}
else if (baseProvider is OpenTelemetryLoggerProvider otelLoggerProvider)
{
return otelLoggerProvider.Resource;
}
else if (baseProvider is MeterProviderSdk meterProviderSdk)
{
return meterProviderSdk.Resource;
}
return Resource.Empty;
}
/// <summary>
/// Gets the <see cref="Resource"/> associated with the <see cref="BaseProvider"/>.
/// </summary>
/// <param name="baseProvider"><see cref="BaseProvider"/>.</param>
/// <returns><see cref="Resource"/>if found otherwise <see cref="Resource.Empty"/>.</returns>
public static Resource GetDefaultResource(this BaseProvider baseProvider)
{
return ResourceBuilder.CreateDefault().Build();
}
}
}
| 37.365079 | 101 | 0.647409 | [
"Apache-2.0"
] | Fresa/opentelemetry-dotnet | src/OpenTelemetry/ProviderExtensions.cs | 2,354 | C# |
// <copyright file="AnalyzeResponses.ascx.cs" company="Engage Software">
// Engage: Survey
// Copyright (c) 2004-2015
// by Engage Software ( http://www.engagesoftware.com )
// </copyright>
// 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.
namespace Engage.Dnn.Survey
{
using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Users;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.Localization;
using Engage.Survey.Entities;
using Telerik.Charting;
using Telerik.Web.UI;
/// <summary>
/// Displays a view of responses to a particular survey
/// </summary>
public partial class AnalyzeResponses : ModuleBase
{
/// <summary>
/// The skin to use for Telerik controls
/// </summary>
private const string TelerikControlsSkin = "Simple";
/// <summary>
/// The skin to use for Telerik charts
/// </summary>
private const string TelerikChartsSkin = "Telerik";
/// <summary>
/// A regular expression to match (one or more) invalid filename characters or an underscore (to be used to replace the invalid characters with underscores, without having multiple underscores in a row)
/// </summary>
private static readonly Regex InvalidFilenameCharactersExpression = new Regex("[" + Regex.Escape(new string(Path.GetInvalidFileNameChars())) + "_]+", RegexOptions.Compiled);
/// <summary>
/// Backing field for <see cref="Responses"/>
/// </summary>
private IQueryable<IGrouping<ResponseHeader, Response>> responses;
/// <summary>
/// Backing field for <see cref="Survey"/>
/// </summary>
private Survey survey;
/// <summary>
/// Backing field for <see cref="SurveyId"/>
/// </summary>
private int? surveyId;
/// <summary>
/// Gets the survey for which to display responses.
/// </summary>
/// <value>The survey.</value>
protected Survey Survey
{
get
{
if (this.survey == null)
{
this.survey = new SurveyRepository().LoadSurvey(this.SurveyId, this.ModuleId);
}
return this.survey;
}
}
/// <summary>
/// Gets or sets the grid control in which responses are listed.
/// </summary>
private RadGrid ResponseGrid { get; set; }
/// <summary>
/// Gets the list of responses (a list of response header, grouped with their related responses).
/// </summary>
/// <value>A queryable sequence of <see cref="ResponseHeader"/> instances, grouped with the header's corresponding <see cref="Response"/>s.</value>
private IQueryable<IGrouping<ResponseHeader, Response>> Responses
{
get
{
if (this.responses == null)
{
this.responses = new SurveyRepository().LoadResponses(this.SurveyId);
}
return this.responses;
}
}
/// <summary>
/// Gets the ID of the survey for which to display responses.
/// </summary>
/// <value>The survey ID.</value>
private int SurveyId
{
get
{
if (!this.surveyId.HasValue)
{
int value;
if (!int.TryParse(this.Request.QueryString["SurveyId"], NumberStyles.Integer, CultureInfo.InvariantCulture, out value))
{
throw new InvalidOperationException("Survey ID was not available");
}
this.surveyId = value;
}
return this.surveyId.Value;
}
}
/// <summary>
/// Raises the <see cref="Control.Init"/> event.
/// </summary>
/// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
protected override void OnInit(EventArgs e)
{
if (this.Survey == null)
{
// set this.survey to a valid survey, so that calls from markup don't fail
this.survey = new Survey(this.UserId);
return;
}
this.CreateGraphs();
this.CreateGrid();
this.Load += this.Page_Load;
this.ResponseGrid.NeedDataSource += this.ResponseGrid_NeedDataSource;
this.ResponseGrid.ItemCreated += this.ResponseGrid_ItemCreated;
base.OnInit(e);
}
/// <summary>
/// Gets the name of the column for the question text.
/// </summary>
/// <param name="questionId">The ID of the question.</param>
/// <returns>
/// The name of the column containing the text of the responser to the question
/// </returns>
private static string GetQuestionTextColumnName(int questionId)
{
return "Question-Text-" + questionId.ToString(CultureInfo.InvariantCulture);
}
/// <summary>
/// Gets the name of the column for the question's order.
/// </summary>
/// <param name="questionId">The ID of the question.</param>
/// <returns>
/// The name of the column containing the order of the responses to the question
/// </returns>
private static string GetRelativeOrderColumnName(int questionId)
{
return "Question-Order-" + questionId.ToString(CultureInfo.InvariantCulture);
}
/// <summary>
/// Replaces characters in the given <paramref name="filename"/> which are invalid for filenames.
/// </summary>
/// <param name="filename">The filename to fix.</param>
/// <returns>The filename with all invalid characters replaced with an underscore</returns>
private static string RemoveInvalidCharacters(string filename)
{
return InvalidFilenameCharactersExpression.Replace(filename, "_");
}
/// <summary>
/// Creates the graphs for each question.
/// </summary>
private void CreateGraphs()
{
var questions = new SurveyRepository().LoadAnswerResponseCounts(this.SurveyId);
foreach (var questionPair in questions)
{
var question = questionPair.First;
var answers = questionPair.Second.ToArray();
const int TitleHeight = 25;
const int AnswerHeight = 16;
const int HeaderFooterHeight = 70;
var linesOfTitleText = (int)Math.Ceiling(question.Text.Length / (double)35);
var chart = new RadChart
{
ChartTitle = { TextBlock = { Text = this.GetQuestionLabel(question.RelativeOrder, question.Text, false) } },
SeriesOrientation = ChartSeriesOrientation.Horizontal,
Skin = TelerikChartsSkin,
Height = Unit.Pixel((linesOfTitleText * TitleHeight) + (AnswerHeight * answers.Length) + HeaderFooterHeight),
Legend = { Visible = false },
AutoTextWrap = true,
AutoLayout = true,
HttpHandlerUrl = this.ResolveUrl("~/ChartImage.axd"),
EnableHandlerDetection = false,
PlotArea =
{
XAxis = { Appearance = { TextAppearance = { Visible = false } } },
YAxis = { AxisLabel = { TextBlock = { Text = this.Localize("Axis Label.Text") }, Visible = true } }
},
};
var chartSeries = new ChartSeries();
foreach (var answerPair in answers)
{
var answer = answerPair.First;
var answerCount = answerPair.Second;
chartSeries.Items.Insert(0, new ChartSeriesItem(answerCount, this.GetAnswerLabel(answer.RelativeOrder, answer.Text, false)));
}
chart.Series.Add(chartSeries);
this.ChartsPanel.Controls.Add(chart);
}
var charts = this.ChartsPanel.Controls.OfType<RadChart>();
if (!charts.Any())
{
return;
}
var maxHeight = charts.Select(c => (int)c.Height.Value).Max();
foreach (var chart in charts)
{
chart.Height = Unit.Pixel(maxHeight);
}
}
/// <summary>
/// Creates the <see cref="ResponseGrid"/>.
/// </summary>
/// <remarks>Because we're creating the question columns dynamically, it's easier to just create the whole grid dynamically</remarks>
private void CreateGrid()
{
this.ResponseGrid = new RadGrid
{
ID = "ResponseGrid",
Skin = TelerikControlsSkin,
CssClass = "sa-grid",
AutoGenerateColumns = false,
GridLines = GridLines.None,
AllowSorting = true,
AllowPaging = true,
AllowCustomPaging = true,
PageSize = 25,
ExportSettings =
{
ExportOnlyData = true,
IgnorePaging = true,
OpenInNewWindow = true,
FileName = this.GetExportFilename()
},
SortingSettings =
{
SortedAscToolTip = this.Localize("Sorted Ascending.ToolTip"),
SortedDescToolTip = this.Localize("Sorted Descending.ToolTip"),
SortToolTip = this.Localize("Sort.ToolTip")
},
MasterTableView =
{
AllowNaturalSort = false,
SortExpressions = { new GridSortExpression { FieldName = @"CreationDate", SortOrder = GridSortOrder.Descending } },
CommandItemDisplay = GridCommandItemDisplay.TopAndBottom,
PagerStyle =
{
Mode = GridPagerMode.NextPrevNumericAndAdvanced,
AlwaysVisible = true,
FirstPageToolTip = this.Localize("First Page.ToolTip"),
PrevPageToolTip = this.Localize("Previous Page.ToolTip"),
NextPageToolTip = this.Localize("Next Page.ToolTip"),
LastPageToolTip = this.Localize("Last Page.ToolTip"),
FirstPageText = this.Localize("First Page.Text"),
PrevPageText = this.Localize("Previous Page.Text"),
NextPageText = this.Localize("Next Page.Text"),
LastPageText = this.Localize("Last Page.Text"),
PagerTextFormat = this.Localize("Pager.Format")
},
CommandItemSettings =
{
ShowExportToWordButton = true,
ShowExportToExcelButton = true,
ShowExportToCsvButton = true,
ShowExportToPdfButton = true,
ExportToWordText = this.Localize("Export To Word.ToolTip"),
ExportToExcelText = this.Localize("Export To Excel.ToolTip"),
ExportToCsvText = this.Localize("Export To CSV.ToolTip"),
ExportToPdfText = this.Localize("Export To PDF.ToolTip")
},
NoRecordsTemplate = new NoRecordsTemplate(this.LocalResourceFile)
}
};
// add column for each question
foreach (var question in new SurveyRepository().LoadQuestions(this.SurveyId))
{
var questionCssClass = string.Format(
CultureInfo.InvariantCulture,
"sa-question sa-question-{0} sa-question-id-{1}",
question.RelativeOrder,
question.QuestionId);
this.ResponseGrid.MasterTableView.Columns.Add(
new GridBoundColumn
{
DataField = GetQuestionTextColumnName(question.QuestionId),
SortExpression = GetRelativeOrderColumnName(question.QuestionId),
HeaderText = this.GetQuestionLabel(question.RelativeOrder, question.Text, true),
HeaderStyle = { CssClass = questionCssClass + " rgHeader" },
ItemStyle = { CssClass = questionCssClass },
});
}
this.ResponseGrid.MasterTableView.Columns.Add(
new GridBoundColumn
{
DataField = "CreationDate",
HeaderText = this.Localize("Date.Header"),
HeaderStyle = { CssClass = "sa-date rgHeader" },
ItemStyle = { CssClass = "sa-date" }
});
this.ResponseGrid.MasterTableView.Columns.Add(
new GridBoundColumn
{
DataField = "User",
HeaderText = this.Localize("User.Header"),
HeaderStyle = { CssClass = "sa-user rgHeader" },
ItemStyle = { CssClass = "sa-user" },
HtmlEncode = true
});
////this.ResponseGrid.MasterTableView.Columns.Add(
//// new GridBoundColumn
//// {
//// DataField = "ResponseHeaderId",
//// HeaderText = this.Localize("Response ID.Header"),
//// HeaderStyle = { CssClass = "sa-id rgHeader" },
//// ItemStyle = { CssClass = "sa-id" }
//// });
var returnUrlParameter = "returnUrl=" +
HttpUtility.UrlEncode(
this.BuildLinkUrl(
this.ModuleId,
this.GetCurrentControlKey(),
"surveyId=" + this.SurveyId.ToString(CultureInfo.InvariantCulture)));
this.ResponseGrid.MasterTableView.Columns.Add(
new GridHyperLinkColumn
{
DataNavigateUrlFields = new[] { "ResponseHeaderId" },
HeaderText = this.Localize("View.Header"),
Text = this.Localize("View.Text"),
HeaderStyle = { CssClass = "sa-view rgHeader" },
ItemStyle = { CssClass = "sa-view sa-action-btn" },
DataNavigateUrlFormatString = this.BuildLinkUrl(this.ModuleId, ControlKey.ViewSurvey, "responseHeaderId={0}", returnUrlParameter)
});
this.ResponseGridPlaceholder.Controls.Add(this.ResponseGrid);
}
/// <summary>
/// Gets the text label for an answer.
/// </summary>
/// <param name="relativeOrder">The relative order, or <c>null</c> if an answer to an open-ended question.</param>
/// <param name="answerText">The answer text.</param>
/// <param name="asHtml">Whether the text should be HTML or plain text</param>
/// <returns>The text to label an answer</returns>
private string GetAnswerLabel(int? relativeOrder, string answerText, bool asHtml)
{
const int MaxAnswerLength = 75;
var answerLabel = relativeOrder.HasValue
? string.Format(CultureInfo.CurrentCulture, this.Localize("Answer.Format"), relativeOrder, answerText)
: answerText.Length < MaxAnswerLength ? HttpUtility.HtmlEncode(answerText)
: string.Format("<span class=\"sa-long-answer\">{0}</a>", HttpUtility.HtmlEncode(answerText));
return asHtml ? answerLabel : HtmlUtils.StripTags(answerLabel, false);
}
/// <summary>
/// Gets the name of the file when exporting data
/// </summary>
/// <returns>The filename (without extension) for the generated export file</returns>
private string GetExportFilename()
{
var filename = string.Format(
CultureInfo.CurrentCulture,
this.Localize("FileName.Format"),
DateTime.Now,
this.Survey.Text,
this.Survey.SurveyId);
return RemoveInvalidCharacters(filename);
}
/// <summary>
/// Gets the text label for a question.
/// </summary>
/// <param name="relativeOrder">The relative order.</param>
/// <param name="questionText">The question text.</param>
/// <param name="asHtml">Whether the text should be HTML or plain text</param>
/// <returns>The text to label a question</returns>
private string GetQuestionLabel(int relativeOrder, string questionText, bool asHtml)
{
var questionLabel = string.Format(CultureInfo.CurrentCulture, this.Localize("Question.Format"), relativeOrder, questionText);
return asHtml ? questionLabel : HtmlUtils.StripTags(questionLabel, false);
}
/// <summary>
/// Gets the name of the user.
/// </summary>
/// <param name="userId">The user ID, or <c>null</c> for anonymous users.</param>
/// <returns>The user's name</returns>
private string GetUser(int? userId)
{
var user = new UserController().GetUser(this.PortalId, userId ?? Null.NullInteger);
if (user == null)
{
return this.Localize("AnonymousUser.Text");
}
return string.Format(
CultureInfo.CurrentCulture,
this.Localize("UserLabel.Format"),
user.DisplayName,
user.FirstName,
user.LastName);
}
/// <summary>
/// Pivots the questions into columns.
/// </summary>
/// <param name="responsesByHeader">A collection of <see cref="ResponseHeader"/>s, grouped with each header's <see cref="Response"/>s.</param>
/// <returns>A <see cref="DataTable"/> with columns for header information and for each question, and a row for each header</returns>
private DataTable PivotQuestions(IQueryable<IGrouping<ResponseHeader, Response>> responsesByHeader)
{
var table = new DataTable { Locale = CultureInfo.CurrentCulture };
if (!responsesByHeader.Any())
{
return table;
}
var questionTextColumnMap = new Dictionary<int, DataColumn>();
var relativeOrderColumnMap = new Dictionary<int, DataColumn>();
foreach (var response in new SurveyRepository().LoadQuestions(this.SurveyId))
{
var questionTextcolumn = table.Columns.Add(GetQuestionTextColumnName(response.QuestionId), typeof(string));
questionTextColumnMap.Add(response.QuestionId, questionTextcolumn);
var relativeOrdercolumn = table.Columns.Add(GetRelativeOrderColumnName(response.QuestionId), typeof(int));
relativeOrderColumnMap.Add(response.QuestionId, relativeOrdercolumn);
}
// add header columns
var responseHeaderIdColumn = table.Columns.Add("ResponseHeaderId", typeof(int));
var creationDateColumn = table.Columns.Add("CreationDate", typeof(DateTime));
var userColumn = table.Columns.Add("User", typeof(string));
// create rows for each header
foreach (var headerWithResponses in responsesByHeader)
{
var row = table.NewRow();
table.Rows.Add(row);
var surveyResponses = from response in headerWithResponses
where questionTextColumnMap.ContainsKey(response.QuestionId)
group response by response.QuestionId
into responsesByQuestion
select new
{
QuestionId = responsesByQuestion.Key,
Responses = from response in responsesByQuestion
orderby response.AnswerRelativeOrder
select new { response.AnswerRelativeOrder, response.UserResponse, response.AnswerText }
};
foreach (var response in surveyResponses)
{
var firstResponse = response.Responses.First();
if (response.Responses.Count() == 1)
{
row[questionTextColumnMap[response.QuestionId]] = this.GetAnswerLabel(firstResponse.AnswerRelativeOrder, firstResponse.UserResponse, true);
}
else
{
var answerLabels = from answer in response.Responses
where bool.Parse(answer.UserResponse)
select this.GetAnswerLabel(answer.AnswerRelativeOrder, answer.AnswerText, true);
row[questionTextColumnMap[response.QuestionId]] = string.Join(", ", answerLabels.ToArray());
}
row[relativeOrderColumnMap[response.QuestionId]] = firstResponse.AnswerRelativeOrder ?? (object)DBNull.Value;
}
row[responseHeaderIdColumn] = headerWithResponses.Key.ResponseHeaderId;
row[creationDateColumn] = headerWithResponses.Key.CreationDate;
row[userColumn] = HttpUtility.HtmlEncode(this.GetUser(headerWithResponses.Key.UserId));
}
return table;
}
/// <summary>
/// Handles the <see cref="Control.Load"/> event of this control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
private void Page_Load(object sender, EventArgs e)
{
try
{
if (string.IsNullOrEmpty(this.Request.QueryString["SurveyId"]))
{
this.Response.Redirect(this.BuildLinkUrl(this.ModuleId, ControlKey.SurveyListing));
}
}
catch (Exception exc)
{
Exceptions.ProcessModuleLoadException(this, exc);
}
}
/// <summary>
/// Handles the <see cref="RadGrid.NeedDataSource"/> event of the <see cref="ResponseGrid"/> control.
/// </summary>
/// <param name="source">The source of the event.</param>
/// <param name="e">The <see cref="GridNeedDataSourceEventArgs"/> instance containing the event data.</param>
private void ResponseGrid_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
{
var pagedResponsesByHeader = this.Responses.Skip(this.ResponseGrid.CurrentPageIndex * this.ResponseGrid.PageSize).Take(this.ResponseGrid.PageSize);
this.ResponseGrid.DataSource = this.PivotQuestions(pagedResponsesByHeader);
this.ResponseGrid.MasterTableView.VirtualItemCount = this.Responses.Count();
}
/// <summary>
/// Handles the <see cref="RadGrid.ItemCreated"/> event of the <see cref="ResponseGrid"/> control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="GridItemEventArgs"/> instance containing the event data.</param>
private void ResponseGrid_ItemCreated(object sender, GridItemEventArgs e)
{
var commandItem = e.Item as GridCommandItem;
if (commandItem != null)
{
// control information from http://www.telerik.com/help/aspnet-ajax/grddefaultbehavior.html
commandItem.FindControl("AddNewRecordButton").Visible = false;
commandItem.FindControl("InitInsertButton").Visible = false;
commandItem.FindControl("RefreshButton").Visible = false;
commandItem.FindControl("RebindGridButton").Visible = false;
}
else
{
// control information from http://www.telerik.com/help/aspnet-ajax/grdaccessingdefaultpagerbuttons.html
var pagerItem = e.Item as GridPagerItem;
if (pagerItem != null)
{
((Label)pagerItem.FindControl("GoToPageLabel")).Text = this.Localize("Go to Page Label.Text");
((Button)pagerItem.FindControl("GoToPageLinkButton")).Text = this.Localize("Go to Page Button.Text");
((Label)pagerItem.FindControl("PageOfLabel")).Text = string.Format(CultureInfo.CurrentCulture, this.Localize("Page of.Format"), pagerItem.Paging.PageCount);
((Label)pagerItem.FindControl("ChangePageSizeLabel")).Text = this.Localize("Change Page Size Label.Text");
((Button)pagerItem.FindControl("ChangePageSizeLinkButton")).Text = this.Localize("Change Page Size Button.Text");
}
}
}
/// <summary>
/// The template instantiated by the <see cref="AnalyzeResponses.ResponseGrid"/> when there are no responses to display
/// </summary>
private class NoRecordsTemplate : ITemplate
{
/// <summary>
/// Initializes a new instance of the <see cref="Engage.Dnn.Survey.AnalyzeResponses.NoRecordsTemplate"/> class.
/// </summary>
/// <param name="resourceFile">The resource file.</param>
public NoRecordsTemplate(string resourceFile)
{
this.ResourceFile = resourceFile;
}
/// <summary>
/// Gets or sets he resource file.
/// </summary>
/// <value>The resource file.</value>
private string ResourceFile { get; set; }
/// <summary>
/// Defines the <see cref="Control"/> object that child controls and templates belong to. These child controls are in turn defined within an inline template.
/// </summary>
/// <param name="container">The <see cref="Control"/> object to contain the instances of controls from the inline template.</param>
public void InstantiateIn(Control container)
{
// ReSharper disable LocalizableElement
container.Controls.Add(new Literal { Text = "<h3 class='no-responses'>" + Localization.GetString("No Responses.Text", this.ResourceFile) + "</h3>" });
// ReSharper restore LocalizableElement
}
}
}
} | 48.011419 | 211 | 0.527131 | [
"MIT"
] | bdukes/Engage-Survey | Source/AnalyzeResponses.ascx.cs | 29,431 | C# |
using System.Runtime.Serialization;
namespace Service.ServerKeyValue.Grpc.Models
{
[DataContract]
public class KeysGrpcResponse
{
[DataMember(Order = 1)]
public string[] Keys { get; set; }
}
} | 18.272727 | 44 | 0.736318 | [
"MIT"
] | MyJetEducation/Service.ServerKeyValue | src/Service.ServerKeyValue.Grpc/Models/KeysGrpcResponse.cs | 201 | C# |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
//using System;
//using System.Collections;
//using System.Collections.Generic;
//using System.Reflection;
//using System.Text;
//using System.Threading;
//using log4net;
//namespace OpenSim.GridLaunch
//{
// internal class AppExecutor2
// {
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
// private static readonly int consoleReadIntervalMilliseconds = 50;
// //private static readonly Timer readTimer = new Timer(readConsole, null, Timeout.Infinite, Timeout.Infinite);
// private static Thread timerThread;
// private static object timerThreadLock = new object();
// #region Start / Stop timer thread
// private static void timer_Start()
// {
// //readTimer.Change(0, consoleReadIntervalMilliseconds);
// lock (timerThreadLock)
// {
// if (timerThread == null)
// {
// m_log.Debug("Starting timer thread.");
// timerThread = new Thread(timerThreadLoop);
// timerThread.Name = "StdOutputStdErrorReadThread";
// timerThread.IsBackground = true;
// timerThread.Start();
// }
// }
// }
// private static void timer_Stop()
// {
// //readTimer.Change(Timeout.Infinite, Timeout.Infinite);
// lock (timerThreadLock)
// {
// if (timerThread != null)
// {
// m_log.Debug("Stopping timer thread.");
// try
// {
// if (timerThread.IsAlive)
// timerThread.Abort();
// timerThread.Join(2000);
// timerThread = null;
// }
// catch (Exception ex)
// {
// m_log.Error("Exception stopping timer thread: " + ex.ToString());
// }
// }
// }
// }
// #endregion
// #region Timer read from consoles and fire event
// private static void timerThreadLoop()
// {
// try
// {
// while (true)
// {
// readConsole();
// Thread.Sleep(consoleReadIntervalMilliseconds);
// }
// }
// catch (ThreadAbortException) { } // Expected on thread shutdown
// }
// private static void readConsole()
// {
// try
// {
// // Lock so we don't collide with any startup or shutdown
// lock (Program.AppList)
// {
// foreach (AppExecutor app in new ArrayList(Program.AppList.Values))
// {
// try
// {
// string txt = app.GetStdOutput();
// // Fire event with received text
// if (!string.IsNullOrEmpty(txt))
// Program.FireAppConsoleOutput(app.File, txt);
// }
// catch (Exception ex)
// {
// m_log.ErrorFormat("Exception reading standard output from \"{0}\": {1}", app.File, ex.ToString());
// }
// try
// {
// string txt = app.GetStdError();
// // Fire event with received text
// if (!string.IsNullOrEmpty(txt))
// Program.FireAppConsoleOutput(app.File, txt);
// }
// catch (Exception ex)
// {
// m_log.ErrorFormat("Exception reading standard error from \"{0}\": {1}", app.File, ex.ToString());
// }
// }
// }
// }
// finally
// {
// }
// }
// #endregion
// #region Read stdOutput and stdError
// public string GetStdOutput()
// {
// return GetStreamData(Output);
// }
// public string GetStdError()
// {
// return GetStreamData(Error);
// }
// private static int num = 0;
// // Gets any data from StreamReader object, non-blocking
// private static string GetStreamData(StreamReader sr)
// {
// // Can't read?
// if (!sr.BaseStream.CanRead)
// return "";
// // Read a chunk
// //sr.BaseStream.ReadTimeout = 100;
// byte[] buffer = new byte[4096];
// num++;
// Trace.WriteLine("Start read " + num);
// int len = sr.BaseStream.Read(buffer, 0, buffer.Length);
// Trace.WriteLine("End read " + num + ": " + len);
// // Nothing?
// if (len <= 0)
// return "";
// // Return data
// StringBuilder sb = new StringBuilder();
// sb.Append(System.Text.Encoding.ASCII.GetString(buffer, 0, len));
// //while (sr.Peek() >= 0)
// //{
// // sb.Append(Convert.ToChar(sr.Read()));
// //}
// return sb.ToString();
// }
// #endregion
// }
//}
| 38.164894 | 128 | 0.503833 | [
"BSD-3-Clause"
] | Ana-Green/halcyon-1 | OpenSim/Tools/OpenSim.GridLaunch/AppExecutor_Thread.cs | 7,175 | C# |
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using SurviveOnSotka.Db;
namespace SurviveOnSotka.Db.Migrations
{
[DbContext(typeof(AppDbContext))]
[Migration("20190531050021_11")]
partial class _11
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "2.2.4-servicing-10062")
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<System.Guid>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<Guid>("RoleId");
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<System.Guid>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<Guid>("UserId");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<System.Guid>", b =>
{
b.Property<string>("LoginProvider");
b.Property<string>("ProviderKey");
b.Property<string>("ProviderDisplayName");
b.Property<Guid>("UserId");
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<System.Guid>", b =>
{
b.Property<Guid>("UserId");
b.Property<Guid>("RoleId");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.ToTable("AspNetUserRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<System.Guid>", b =>
{
b.Property<Guid>("UserId");
b.Property<string>("LoginProvider");
b.Property<string>("Name");
b.Property<string>("Value");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens");
});
modelBuilder.Entity("SurviveOnSotka.Entities.Category", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Descriptrion")
.HasMaxLength(64);
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(40);
b.Property<Guid?>("ParentCategoryId");
b.Property<string>("PathToIcon");
b.HasKey("Id");
b.HasIndex("ParentCategoryId");
b.ToTable("Categories");
});
modelBuilder.Entity("SurviveOnSotka.Entities.Ingredient", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(100);
b.Property<string>("PathToIcon");
b.Property<Guid>("TypeFoodId");
b.HasKey("Id");
b.HasIndex("TypeFoodId");
b.ToTable("Ingredients");
});
modelBuilder.Entity("SurviveOnSotka.Entities.IngredientToRecipe", b =>
{
b.Property<Guid>("RecipeId");
b.Property<Guid>("IngredientId");
b.Property<int>("Amount");
b.Property<int>("Price");
b.Property<int>("Weight");
b.HasKey("RecipeId", "IngredientId");
b.HasIndex("IngredientId");
b.ToTable("IngredientToRecipe");
});
modelBuilder.Entity("SurviveOnSotka.Entities.RateReview", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd();
b.Property<bool>("IsCool");
b.Property<Guid>("ReviewId");
b.Property<Guid>("UserId");
b.HasKey("Id");
b.HasIndex("UserId");
b.HasIndex("ReviewId", "UserId")
.IsUnique();
b.ToTable("RateReviews");
});
modelBuilder.Entity("SurviveOnSotka.Entities.Recipe", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd();
b.Property<Guid?>("CategoryId");
b.Property<DateTime>("DateCreated");
b.Property<string>("Description")
.IsRequired()
.HasMaxLength(1000);
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(100);
b.Property<string>("PathToPhotos");
b.Property<TimeSpan?>("TimeForCooking");
b.Property<TimeSpan?>("TimeForPreparetion");
b.Property<Guid?>("UserId");
b.HasKey("Id");
b.HasIndex("CategoryId");
b.HasIndex("UserId");
b.ToTable("Recipes");
});
modelBuilder.Entity("SurviveOnSotka.Entities.Review", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("DateCreated");
b.Property<string>("PathToPhotos");
b.Property<int>("Rate");
b.Property<Guid>("RecipeId");
b.Property<string>("Text")
.IsRequired()
.HasMaxLength(2000);
b.Property<Guid?>("UserId");
b.HasKey("Id");
b.HasIndex("RecipeId");
b.HasIndex("UserId");
b.ToTable("Reviews");
});
modelBuilder.Entity("SurviveOnSotka.Entities.Role", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Name")
.HasMaxLength(256);
b.Property<string>("NormalizedName")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("NormalizedName")
.IsUnique()
.HasName("RoleNameIndex")
.HasFilter("[NormalizedName] IS NOT NULL");
b.ToTable("AspNetRoles");
});
modelBuilder.Entity("SurviveOnSotka.Entities.Step", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Description")
.IsRequired()
.HasMaxLength(1000);
b.Property<int>("NumberStep");
b.Property<Guid>("RecipeId");
b.HasKey("Id");
b.HasIndex("RecipeId");
b.ToTable("Step");
});
modelBuilder.Entity("SurviveOnSotka.Entities.Tag", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(40);
b.HasKey("Id");
b.ToTable("Tags");
});
modelBuilder.Entity("SurviveOnSotka.Entities.TagsInRecipe", b =>
{
b.Property<Guid>("TagId");
b.Property<Guid>("RecipeId");
b.HasKey("TagId", "RecipeId");
b.HasIndex("RecipeId");
b.ToTable("TagsInRecipies");
});
modelBuilder.Entity("SurviveOnSotka.Entities.TypeFood", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(40);
b.Property<string>("PathToIcon");
b.HasKey("Id");
b.ToTable("TypeFoods");
});
modelBuilder.Entity("SurviveOnSotka.Entities.User", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("AboutYourself")
.HasMaxLength(1000);
b.Property<int>("AccessFailedCount");
b.Property<string>("Avatar");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Email")
.HasMaxLength(256);
b.Property<bool>("EmailConfirmed");
b.Property<string>("FirstName")
.HasMaxLength(40);
b.Property<bool>("Gender");
b.Property<string>("LastName")
.HasMaxLength(40);
b.Property<bool>("LockoutEnabled");
b.Property<DateTimeOffset?>("LockoutEnd");
b.Property<string>("NormalizedEmail")
.HasMaxLength(256);
b.Property<string>("NormalizedUserName")
.HasMaxLength(256);
b.Property<string>("PasswordHash");
b.Property<string>("PhoneNumber");
b.Property<bool>("PhoneNumberConfirmed");
b.Property<string>("SecurityStamp");
b.Property<bool>("TwoFactorEnabled");
b.Property<string>("UserName")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasName("UserNameIndex")
.HasFilter("[NormalizedUserName] IS NOT NULL");
b.ToTable("AspNetUsers");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<System.Guid>", b =>
{
b.HasOne("SurviveOnSotka.Entities.Role")
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<System.Guid>", b =>
{
b.HasOne("SurviveOnSotka.Entities.User")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<System.Guid>", b =>
{
b.HasOne("SurviveOnSotka.Entities.User")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<System.Guid>", b =>
{
b.HasOne("SurviveOnSotka.Entities.Role")
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("SurviveOnSotka.Entities.User")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<System.Guid>", b =>
{
b.HasOne("SurviveOnSotka.Entities.User")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("SurviveOnSotka.Entities.Category", b =>
{
b.HasOne("SurviveOnSotka.Entities.Category", "ParentCategory")
.WithMany("Categories")
.HasForeignKey("ParentCategoryId");
});
modelBuilder.Entity("SurviveOnSotka.Entities.Ingredient", b =>
{
b.HasOne("SurviveOnSotka.Entities.TypeFood", "TypeFood")
.WithMany("Ingredients")
.HasForeignKey("TypeFoodId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("SurviveOnSotka.Entities.IngredientToRecipe", b =>
{
b.HasOne("SurviveOnSotka.Entities.Ingredient", "Ingredient")
.WithMany("Recipies")
.HasForeignKey("IngredientId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("SurviveOnSotka.Entities.Recipe", "Recipe")
.WithMany("Ingredients")
.HasForeignKey("RecipeId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("SurviveOnSotka.Entities.RateReview", b =>
{
b.HasOne("SurviveOnSotka.Entities.Review", "Review")
.WithMany("RateReviews")
.HasForeignKey("ReviewId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("SurviveOnSotka.Entities.User", "User")
.WithMany("RateReviews")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("SurviveOnSotka.Entities.Recipe", b =>
{
b.HasOne("SurviveOnSotka.Entities.Category", "Category")
.WithMany("Recipies")
.HasForeignKey("CategoryId");
b.HasOne("SurviveOnSotka.Entities.User", "User")
.WithMany("Recipies")
.HasForeignKey("UserId");
});
modelBuilder.Entity("SurviveOnSotka.Entities.Review", b =>
{
b.HasOne("SurviveOnSotka.Entities.Recipe", "Recipe")
.WithMany("Reviews")
.HasForeignKey("RecipeId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("SurviveOnSotka.Entities.User", "User")
.WithMany("Reviews")
.HasForeignKey("UserId");
});
modelBuilder.Entity("SurviveOnSotka.Entities.Step", b =>
{
b.HasOne("SurviveOnSotka.Entities.Recipe", "Recipe")
.WithMany("Steps")
.HasForeignKey("RecipeId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("SurviveOnSotka.Entities.TagsInRecipe", b =>
{
b.HasOne("SurviveOnSotka.Entities.Recipe", "Recipe")
.WithMany("Tags")
.HasForeignKey("RecipeId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("SurviveOnSotka.Entities.Tag", "Tag")
.WithMany("Recipies")
.HasForeignKey("TagId")
.OnDelete(DeleteBehavior.Cascade);
});
#pragma warning restore 612, 618
}
}
}
| 33.369403 | 125 | 0.449066 | [
"MIT"
] | vladisa385/SurviveOnSotka | Db/Migrations/20190531050021_11.Designer.cs | 17,888 | 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.
namespace Microsoft.AspNetCore.Components
{
[System.AttributeUsageAttribute(System.AttributeTargets.Class, AllowMultiple=true, Inherited=true)]
public sealed partial class BindInputElementAttribute : System.Attribute
{
public BindInputElementAttribute(string type, string suffix, string valueAttribute, string changeAttribute, bool isInvariantCulture, string format) { }
public string ChangeAttribute { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } }
public string Format { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } }
public bool IsInvariantCulture { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } }
public string Suffix { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } }
public string Type { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } }
public string ValueAttribute { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } }
}
}
namespace Microsoft.AspNetCore.Components.Forms
{
public static partial class EditContextFieldClassExtensions
{
public static string FieldCssClass(this Microsoft.AspNetCore.Components.Forms.EditContext editContext, in Microsoft.AspNetCore.Components.Forms.FieldIdentifier fieldIdentifier) { throw null; }
public static string FieldCssClass<TField>(this Microsoft.AspNetCore.Components.Forms.EditContext editContext, System.Linq.Expressions.Expression<System.Func<TField>> accessor) { throw null; }
}
public partial class EditForm : Microsoft.AspNetCore.Components.ComponentBase
{
public EditForm() { }
[Microsoft.AspNetCore.Components.ParameterAttribute(CaptureUnmatchedValues=true)]
public System.Collections.Generic.IReadOnlyDictionary<string, object> AdditionalAttributes { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
[Microsoft.AspNetCore.Components.ParameterAttribute]
public Microsoft.AspNetCore.Components.RenderFragment<Microsoft.AspNetCore.Components.Forms.EditContext> ChildContent { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
[Microsoft.AspNetCore.Components.ParameterAttribute]
public Microsoft.AspNetCore.Components.Forms.EditContext EditContext { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
[Microsoft.AspNetCore.Components.ParameterAttribute]
public object Model { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
[Microsoft.AspNetCore.Components.ParameterAttribute]
public Microsoft.AspNetCore.Components.EventCallback<Microsoft.AspNetCore.Components.Forms.EditContext> OnInvalidSubmit { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
[Microsoft.AspNetCore.Components.ParameterAttribute]
public Microsoft.AspNetCore.Components.EventCallback<Microsoft.AspNetCore.Components.Forms.EditContext> OnSubmit { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
[Microsoft.AspNetCore.Components.ParameterAttribute]
public Microsoft.AspNetCore.Components.EventCallback<Microsoft.AspNetCore.Components.Forms.EditContext> OnValidSubmit { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
protected override void BuildRenderTree(Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder builder) { }
protected override void OnParametersSet() { }
}
public abstract partial class InputBase<TValue> : Microsoft.AspNetCore.Components.ComponentBase, System.IDisposable
{
protected InputBase() { }
[Microsoft.AspNetCore.Components.ParameterAttribute(CaptureUnmatchedValues=true)]
public System.Collections.Generic.IReadOnlyDictionary<string, object> AdditionalAttributes { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
protected string CssClass { get { throw null; } }
protected TValue CurrentValue { get { throw null; } set { } }
protected string CurrentValueAsString { get { throw null; } set { } }
protected Microsoft.AspNetCore.Components.Forms.EditContext EditContext { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
protected Microsoft.AspNetCore.Components.Forms.FieldIdentifier FieldIdentifier { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
[Microsoft.AspNetCore.Components.ParameterAttribute]
public TValue Value { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
[Microsoft.AspNetCore.Components.ParameterAttribute]
public Microsoft.AspNetCore.Components.EventCallback<TValue> ValueChanged { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
[Microsoft.AspNetCore.Components.ParameterAttribute]
public System.Linq.Expressions.Expression<System.Func<TValue>> ValueExpression { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
protected virtual void Dispose(bool disposing) { }
protected virtual string FormatValueAsString(TValue value) { throw null; }
public override System.Threading.Tasks.Task SetParametersAsync(Microsoft.AspNetCore.Components.ParameterView parameters) { throw null; }
void System.IDisposable.Dispose() { }
protected abstract bool TryParseValueFromString(string value, out TValue result, out string validationErrorMessage);
}
public partial class InputCheckbox : Microsoft.AspNetCore.Components.Forms.InputBase<bool>
{
public InputCheckbox() { }
protected override void BuildRenderTree(Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder builder) { }
protected override bool TryParseValueFromString(string value, out bool result, out string validationErrorMessage) { throw null; }
}
public partial class InputDate<TValue> : Microsoft.AspNetCore.Components.Forms.InputBase<TValue>
{
public InputDate() { }
[Microsoft.AspNetCore.Components.ParameterAttribute]
public string ParsingErrorMessage { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
protected override void BuildRenderTree(Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder builder) { }
protected override string FormatValueAsString(TValue value) { throw null; }
protected override bool TryParseValueFromString(string value, out TValue result, out string validationErrorMessage) { throw null; }
}
public partial class InputNumber<TValue> : Microsoft.AspNetCore.Components.Forms.InputBase<TValue>
{
public InputNumber() { }
[Microsoft.AspNetCore.Components.ParameterAttribute]
public string ParsingErrorMessage { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
protected override void BuildRenderTree(Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder builder) { }
protected override string FormatValueAsString(TValue value) { throw null; }
protected override bool TryParseValueFromString(string value, out TValue result, out string validationErrorMessage) { throw null; }
}
public partial class InputSelect<TValue> : Microsoft.AspNetCore.Components.Forms.InputBase<TValue>
{
public InputSelect() { }
[Microsoft.AspNetCore.Components.ParameterAttribute]
public Microsoft.AspNetCore.Components.RenderFragment ChildContent { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
protected override void BuildRenderTree(Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder builder) { }
protected override bool TryParseValueFromString(string value, out TValue result, out string validationErrorMessage) { throw null; }
}
public partial class InputText : Microsoft.AspNetCore.Components.Forms.InputBase<string>
{
public InputText() { }
protected override void BuildRenderTree(Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder builder) { }
protected override bool TryParseValueFromString(string value, out string result, out string validationErrorMessage) { throw null; }
}
public partial class InputTextArea : Microsoft.AspNetCore.Components.Forms.InputBase<string>
{
public InputTextArea() { }
protected override void BuildRenderTree(Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder builder) { }
protected override bool TryParseValueFromString(string value, out string result, out string validationErrorMessage) { throw null; }
}
public partial class ValidationMessage<TValue> : Microsoft.AspNetCore.Components.ComponentBase, System.IDisposable
{
public ValidationMessage() { }
[Microsoft.AspNetCore.Components.ParameterAttribute(CaptureUnmatchedValues=true)]
public System.Collections.Generic.IReadOnlyDictionary<string, object> AdditionalAttributes { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
[Microsoft.AspNetCore.Components.ParameterAttribute]
public System.Linq.Expressions.Expression<System.Func<TValue>> For { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
protected override void BuildRenderTree(Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder builder) { }
protected virtual void Dispose(bool disposing) { }
protected override void OnParametersSet() { }
void System.IDisposable.Dispose() { }
}
public partial class ValidationSummary : Microsoft.AspNetCore.Components.ComponentBase, System.IDisposable
{
public ValidationSummary() { }
[Microsoft.AspNetCore.Components.ParameterAttribute(CaptureUnmatchedValues=true)]
public System.Collections.Generic.IReadOnlyDictionary<string, object> AdditionalAttributes { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
[Microsoft.AspNetCore.Components.ParameterAttribute]
public object Model { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
protected override void BuildRenderTree(Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder builder) { }
protected virtual void Dispose(bool disposing) { }
protected override void OnParametersSet() { }
void System.IDisposable.Dispose() { }
}
}
namespace Microsoft.AspNetCore.Components.RenderTree
{
public sealed partial class WebEventDescriptor
{
public WebEventDescriptor() { }
public int BrowserRendererId { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
public string EventArgsType { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
public Microsoft.AspNetCore.Components.RenderTree.EventFieldInfo EventFieldInfo { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
public ulong EventHandlerId { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
}
}
namespace Microsoft.AspNetCore.Components.Routing
{
public partial class NavLink : Microsoft.AspNetCore.Components.ComponentBase, System.IDisposable
{
public NavLink() { }
[Microsoft.AspNetCore.Components.ParameterAttribute]
public string ActiveClass { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
[Microsoft.AspNetCore.Components.ParameterAttribute(CaptureUnmatchedValues=true)]
public System.Collections.Generic.IReadOnlyDictionary<string, object> AdditionalAttributes { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
[Microsoft.AspNetCore.Components.ParameterAttribute]
public Microsoft.AspNetCore.Components.RenderFragment ChildContent { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
protected string CssClass { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
[Microsoft.AspNetCore.Components.ParameterAttribute]
public Microsoft.AspNetCore.Components.Routing.NavLinkMatch Match { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
protected override void BuildRenderTree(Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder builder) { }
public void Dispose() { }
protected override void OnInitialized() { }
protected override void OnParametersSet() { }
}
public enum NavLinkMatch
{
Prefix = 0,
All = 1,
}
}
namespace Microsoft.AspNetCore.Components.Web
{
[Microsoft.AspNetCore.Components.BindElementAttribute("select", null, "value", "onchange")]
[Microsoft.AspNetCore.Components.BindElementAttribute("textarea", null, "value", "onchange")]
[Microsoft.AspNetCore.Components.BindInputElementAttribute("checkbox", null, "checked", "onchange", false, null)]
[Microsoft.AspNetCore.Components.BindInputElementAttribute("date", "value", "value", "onchange", true, "yyyy-MM-dd")]
[Microsoft.AspNetCore.Components.BindInputElementAttribute("date", null, "value", "onchange", true, "yyyy-MM-dd")]
[Microsoft.AspNetCore.Components.BindInputElementAttribute("datetime-local", "value", "value", "onchange", true, "yyyy-MM-ddTHH:mm:ss")]
[Microsoft.AspNetCore.Components.BindInputElementAttribute("datetime-local", null, "value", "onchange", true, "yyyy-MM-ddTHH:mm:ss")]
[Microsoft.AspNetCore.Components.BindInputElementAttribute("month", "value", "value", "onchange", true, "yyyy-MM")]
[Microsoft.AspNetCore.Components.BindInputElementAttribute("month", null, "value", "onchange", true, "yyyy-MM")]
[Microsoft.AspNetCore.Components.BindInputElementAttribute("number", "value", "value", "onchange", true, null)]
[Microsoft.AspNetCore.Components.BindInputElementAttribute("number", null, "value", "onchange", true, null)]
[Microsoft.AspNetCore.Components.BindInputElementAttribute("text", null, "value", "onchange", false, null)]
[Microsoft.AspNetCore.Components.BindInputElementAttribute("time", "value", "value", "onchange", true, "HH:mm:ss")]
[Microsoft.AspNetCore.Components.BindInputElementAttribute("time", null, "value", "onchange", true, "HH:mm:ss")]
[Microsoft.AspNetCore.Components.BindInputElementAttribute(null, "value", "value", "onchange", false, null)]
[Microsoft.AspNetCore.Components.BindInputElementAttribute(null, null, "value", "onchange", false, null)]
public static partial class BindAttributes
{
}
public partial class ClipboardEventArgs : System.EventArgs
{
public ClipboardEventArgs() { }
public string Type { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
}
public partial class DataTransfer
{
public DataTransfer() { }
public string DropEffect { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
public string EffectAllowed { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
public string[] Files { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
public Microsoft.AspNetCore.Components.Web.DataTransferItem[] Items { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
public string[] Types { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
}
public partial class DataTransferItem
{
public DataTransferItem() { }
public string Kind { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
public string Type { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
}
public partial class DragEventArgs : Microsoft.AspNetCore.Components.Web.MouseEventArgs
{
public DragEventArgs() { }
public Microsoft.AspNetCore.Components.Web.DataTransfer DataTransfer { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
}
public partial class ErrorEventArgs : System.EventArgs
{
public ErrorEventArgs() { }
public int Colno { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
public string Filename { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
public int Lineno { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
public string Message { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
public string Type { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
}
[Microsoft.AspNetCore.Components.EventHandlerAttribute("onabort", typeof(Microsoft.AspNetCore.Components.Web.ProgressEventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("onactivate", typeof(System.EventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("onbeforeactivate", typeof(System.EventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("onbeforecopy", typeof(System.EventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("onbeforecut", typeof(System.EventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("onbeforedeactivate", typeof(System.EventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("onbeforepaste", typeof(System.EventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("onblur", typeof(Microsoft.AspNetCore.Components.Web.FocusEventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("oncanplay", typeof(System.EventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("oncanplaythrough", typeof(System.EventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("onchange", typeof(Microsoft.AspNetCore.Components.ChangeEventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("onclick", typeof(Microsoft.AspNetCore.Components.Web.MouseEventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("oncontextmenu", typeof(Microsoft.AspNetCore.Components.Web.MouseEventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("oncopy", typeof(Microsoft.AspNetCore.Components.Web.ClipboardEventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("oncuechange", typeof(System.EventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("oncut", typeof(Microsoft.AspNetCore.Components.Web.ClipboardEventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("ondblclick", typeof(Microsoft.AspNetCore.Components.Web.MouseEventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("ondeactivate", typeof(System.EventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("ondrag", typeof(Microsoft.AspNetCore.Components.Web.DragEventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("ondragend", typeof(Microsoft.AspNetCore.Components.Web.DragEventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("ondragenter", typeof(Microsoft.AspNetCore.Components.Web.DragEventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("ondragleave", typeof(Microsoft.AspNetCore.Components.Web.DragEventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("ondragover", typeof(Microsoft.AspNetCore.Components.Web.DragEventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("ondragstart", typeof(Microsoft.AspNetCore.Components.Web.DragEventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("ondrop", typeof(Microsoft.AspNetCore.Components.Web.DragEventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("ondurationchange", typeof(System.EventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("onemptied", typeof(System.EventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("onended", typeof(System.EventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("onerror", typeof(Microsoft.AspNetCore.Components.Web.ErrorEventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("onfocus", typeof(Microsoft.AspNetCore.Components.Web.FocusEventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("onfocusin", typeof(Microsoft.AspNetCore.Components.Web.FocusEventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("onfocusout", typeof(Microsoft.AspNetCore.Components.Web.FocusEventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("onfullscreenchange", typeof(System.EventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("onfullscreenerror", typeof(System.EventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("ongotpointercapture", typeof(Microsoft.AspNetCore.Components.Web.PointerEventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("oninput", typeof(Microsoft.AspNetCore.Components.ChangeEventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("oninvalid", typeof(System.EventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("onkeydown", typeof(Microsoft.AspNetCore.Components.Web.KeyboardEventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("onkeypress", typeof(Microsoft.AspNetCore.Components.Web.KeyboardEventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("onkeyup", typeof(Microsoft.AspNetCore.Components.Web.KeyboardEventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("onload", typeof(Microsoft.AspNetCore.Components.Web.ProgressEventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("onloadeddata", typeof(System.EventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("onloadedmetadata", typeof(System.EventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("onloadend", typeof(Microsoft.AspNetCore.Components.Web.ProgressEventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("onloadstart", typeof(Microsoft.AspNetCore.Components.Web.ProgressEventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("onlostpointercapture", typeof(Microsoft.AspNetCore.Components.Web.PointerEventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("onmousedown", typeof(Microsoft.AspNetCore.Components.Web.MouseEventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("onmousemove", typeof(Microsoft.AspNetCore.Components.Web.MouseEventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("onmouseout", typeof(Microsoft.AspNetCore.Components.Web.MouseEventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("onmouseover", typeof(Microsoft.AspNetCore.Components.Web.MouseEventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("onmouseup", typeof(Microsoft.AspNetCore.Components.Web.MouseEventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("onmousewheel", typeof(Microsoft.AspNetCore.Components.Web.WheelEventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("onpaste", typeof(Microsoft.AspNetCore.Components.Web.ClipboardEventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("onpause", typeof(System.EventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("onplay", typeof(System.EventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("onplaying", typeof(System.EventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("onpointercancel", typeof(Microsoft.AspNetCore.Components.Web.PointerEventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("onpointerdown", typeof(Microsoft.AspNetCore.Components.Web.PointerEventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("onpointerenter", typeof(Microsoft.AspNetCore.Components.Web.PointerEventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("onpointerleave", typeof(Microsoft.AspNetCore.Components.Web.PointerEventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("onpointerlockchange", typeof(System.EventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("onpointerlockerror", typeof(System.EventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("onpointermove", typeof(Microsoft.AspNetCore.Components.Web.PointerEventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("onpointerout", typeof(Microsoft.AspNetCore.Components.Web.PointerEventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("onpointerover", typeof(Microsoft.AspNetCore.Components.Web.PointerEventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("onpointerup", typeof(Microsoft.AspNetCore.Components.Web.PointerEventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("onprogress", typeof(Microsoft.AspNetCore.Components.Web.ProgressEventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("onratechange", typeof(System.EventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("onreadystatechange", typeof(System.EventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("onreset", typeof(System.EventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("onscroll", typeof(System.EventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("onseeked", typeof(System.EventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("onseeking", typeof(System.EventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("onselect", typeof(System.EventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("onselectionchange", typeof(System.EventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("onselectstart", typeof(System.EventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("onstalled", typeof(System.EventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("onstop", typeof(System.EventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("onsubmit", typeof(System.EventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("onsuspend", typeof(System.EventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("ontimeout", typeof(Microsoft.AspNetCore.Components.Web.ProgressEventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("ontimeupdate", typeof(System.EventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("ontouchcancel", typeof(Microsoft.AspNetCore.Components.Web.TouchEventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("ontouchend", typeof(Microsoft.AspNetCore.Components.Web.TouchEventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("ontouchenter", typeof(Microsoft.AspNetCore.Components.Web.TouchEventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("ontouchleave", typeof(Microsoft.AspNetCore.Components.Web.TouchEventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("ontouchmove", typeof(Microsoft.AspNetCore.Components.Web.TouchEventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("ontouchstart", typeof(Microsoft.AspNetCore.Components.Web.TouchEventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("onvolumechange", typeof(System.EventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("onwaiting", typeof(System.EventArgs), true, true)]
[Microsoft.AspNetCore.Components.EventHandlerAttribute("onwheel", typeof(Microsoft.AspNetCore.Components.Web.WheelEventArgs), true, true)]
public static partial class EventHandlers
{
}
public partial class FocusEventArgs : System.EventArgs
{
public FocusEventArgs() { }
public string Type { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
}
public partial class KeyboardEventArgs : System.EventArgs
{
public KeyboardEventArgs() { }
public bool AltKey { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
public string Code { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
public bool CtrlKey { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
public string Key { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
public float Location { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
public bool MetaKey { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
public bool Repeat { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
public bool ShiftKey { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
public string Type { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
}
public partial class MouseEventArgs : System.EventArgs
{
public MouseEventArgs() { }
public bool AltKey { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
public long Button { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
public long Buttons { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
public double ClientX { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
public double ClientY { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
public bool CtrlKey { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
public long Detail { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
public bool MetaKey { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
public double ScreenX { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
public double ScreenY { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
public bool ShiftKey { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
public string Type { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
}
public partial class PointerEventArgs : Microsoft.AspNetCore.Components.Web.MouseEventArgs
{
public PointerEventArgs() { }
public float Height { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
public bool IsPrimary { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
public long PointerId { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
public string PointerType { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
public float Pressure { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
public float TiltX { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
public float TiltY { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
public float Width { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
}
public partial class ProgressEventArgs : System.EventArgs
{
public ProgressEventArgs() { }
public bool LengthComputable { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
public long Loaded { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
public long Total { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
public string Type { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
}
public partial class TouchEventArgs : System.EventArgs
{
public TouchEventArgs() { }
public bool AltKey { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
public Microsoft.AspNetCore.Components.Web.TouchPoint[] ChangedTouches { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
public bool CtrlKey { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
public long Detail { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
public bool MetaKey { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
public bool ShiftKey { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
public Microsoft.AspNetCore.Components.Web.TouchPoint[] TargetTouches { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
public Microsoft.AspNetCore.Components.Web.TouchPoint[] Touches { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
public string Type { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
}
public partial class TouchPoint
{
public TouchPoint() { }
public double ClientX { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
public double ClientY { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
public long Identifier { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
public double PageX { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
public double PageY { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
public double ScreenX { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
public double ScreenY { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
}
public static partial class WebEventCallbackFactoryEventArgsExtensions
{
public static Microsoft.AspNetCore.Components.EventCallback<Microsoft.AspNetCore.Components.Web.ClipboardEventArgs> Create(this Microsoft.AspNetCore.Components.EventCallbackFactory factory, object receiver, System.Action<Microsoft.AspNetCore.Components.Web.ClipboardEventArgs> callback) { throw null; }
public static Microsoft.AspNetCore.Components.EventCallback<Microsoft.AspNetCore.Components.Web.DragEventArgs> Create(this Microsoft.AspNetCore.Components.EventCallbackFactory factory, object receiver, System.Action<Microsoft.AspNetCore.Components.Web.DragEventArgs> callback) { throw null; }
public static Microsoft.AspNetCore.Components.EventCallback<Microsoft.AspNetCore.Components.Web.ErrorEventArgs> Create(this Microsoft.AspNetCore.Components.EventCallbackFactory factory, object receiver, System.Action<Microsoft.AspNetCore.Components.Web.ErrorEventArgs> callback) { throw null; }
public static Microsoft.AspNetCore.Components.EventCallback<Microsoft.AspNetCore.Components.Web.FocusEventArgs> Create(this Microsoft.AspNetCore.Components.EventCallbackFactory factory, object receiver, System.Action<Microsoft.AspNetCore.Components.Web.FocusEventArgs> callback) { throw null; }
public static Microsoft.AspNetCore.Components.EventCallback<Microsoft.AspNetCore.Components.Web.KeyboardEventArgs> Create(this Microsoft.AspNetCore.Components.EventCallbackFactory factory, object receiver, System.Action<Microsoft.AspNetCore.Components.Web.KeyboardEventArgs> callback) { throw null; }
public static Microsoft.AspNetCore.Components.EventCallback<Microsoft.AspNetCore.Components.Web.MouseEventArgs> Create(this Microsoft.AspNetCore.Components.EventCallbackFactory factory, object receiver, System.Action<Microsoft.AspNetCore.Components.Web.MouseEventArgs> callback) { throw null; }
public static Microsoft.AspNetCore.Components.EventCallback<Microsoft.AspNetCore.Components.Web.PointerEventArgs> Create(this Microsoft.AspNetCore.Components.EventCallbackFactory factory, object receiver, System.Action<Microsoft.AspNetCore.Components.Web.PointerEventArgs> callback) { throw null; }
public static Microsoft.AspNetCore.Components.EventCallback<Microsoft.AspNetCore.Components.Web.ProgressEventArgs> Create(this Microsoft.AspNetCore.Components.EventCallbackFactory factory, object receiver, System.Action<Microsoft.AspNetCore.Components.Web.ProgressEventArgs> callback) { throw null; }
public static Microsoft.AspNetCore.Components.EventCallback<Microsoft.AspNetCore.Components.Web.TouchEventArgs> Create(this Microsoft.AspNetCore.Components.EventCallbackFactory factory, object receiver, System.Action<Microsoft.AspNetCore.Components.Web.TouchEventArgs> callback) { throw null; }
public static Microsoft.AspNetCore.Components.EventCallback<Microsoft.AspNetCore.Components.Web.WheelEventArgs> Create(this Microsoft.AspNetCore.Components.EventCallbackFactory factory, object receiver, System.Action<Microsoft.AspNetCore.Components.Web.WheelEventArgs> callback) { throw null; }
public static Microsoft.AspNetCore.Components.EventCallback<Microsoft.AspNetCore.Components.Web.ClipboardEventArgs> Create(this Microsoft.AspNetCore.Components.EventCallbackFactory factory, object receiver, System.Func<Microsoft.AspNetCore.Components.Web.ClipboardEventArgs, System.Threading.Tasks.Task> callback) { throw null; }
public static Microsoft.AspNetCore.Components.EventCallback<Microsoft.AspNetCore.Components.Web.DragEventArgs> Create(this Microsoft.AspNetCore.Components.EventCallbackFactory factory, object receiver, System.Func<Microsoft.AspNetCore.Components.Web.DragEventArgs, System.Threading.Tasks.Task> callback) { throw null; }
public static Microsoft.AspNetCore.Components.EventCallback<Microsoft.AspNetCore.Components.Web.ErrorEventArgs> Create(this Microsoft.AspNetCore.Components.EventCallbackFactory factory, object receiver, System.Func<Microsoft.AspNetCore.Components.Web.ErrorEventArgs, System.Threading.Tasks.Task> callback) { throw null; }
public static Microsoft.AspNetCore.Components.EventCallback<Microsoft.AspNetCore.Components.Web.FocusEventArgs> Create(this Microsoft.AspNetCore.Components.EventCallbackFactory factory, object receiver, System.Func<Microsoft.AspNetCore.Components.Web.FocusEventArgs, System.Threading.Tasks.Task> callback) { throw null; }
public static Microsoft.AspNetCore.Components.EventCallback<Microsoft.AspNetCore.Components.Web.KeyboardEventArgs> Create(this Microsoft.AspNetCore.Components.EventCallbackFactory factory, object receiver, System.Func<Microsoft.AspNetCore.Components.Web.KeyboardEventArgs, System.Threading.Tasks.Task> callback) { throw null; }
public static Microsoft.AspNetCore.Components.EventCallback<Microsoft.AspNetCore.Components.Web.MouseEventArgs> Create(this Microsoft.AspNetCore.Components.EventCallbackFactory factory, object receiver, System.Func<Microsoft.AspNetCore.Components.Web.MouseEventArgs, System.Threading.Tasks.Task> callback) { throw null; }
public static Microsoft.AspNetCore.Components.EventCallback<Microsoft.AspNetCore.Components.Web.PointerEventArgs> Create(this Microsoft.AspNetCore.Components.EventCallbackFactory factory, object receiver, System.Func<Microsoft.AspNetCore.Components.Web.PointerEventArgs, System.Threading.Tasks.Task> callback) { throw null; }
public static Microsoft.AspNetCore.Components.EventCallback<Microsoft.AspNetCore.Components.Web.ProgressEventArgs> Create(this Microsoft.AspNetCore.Components.EventCallbackFactory factory, object receiver, System.Func<Microsoft.AspNetCore.Components.Web.ProgressEventArgs, System.Threading.Tasks.Task> callback) { throw null; }
public static Microsoft.AspNetCore.Components.EventCallback<Microsoft.AspNetCore.Components.Web.TouchEventArgs> Create(this Microsoft.AspNetCore.Components.EventCallbackFactory factory, object receiver, System.Func<Microsoft.AspNetCore.Components.Web.TouchEventArgs, System.Threading.Tasks.Task> callback) { throw null; }
public static Microsoft.AspNetCore.Components.EventCallback<Microsoft.AspNetCore.Components.Web.WheelEventArgs> Create(this Microsoft.AspNetCore.Components.EventCallbackFactory factory, object receiver, System.Func<Microsoft.AspNetCore.Components.Web.WheelEventArgs, System.Threading.Tasks.Task> callback) { throw null; }
}
public static partial class WebRenderTreeBuilderExtensions
{
public static void AddEventPreventDefaultAttribute(this Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder builder, int sequence, string eventName, bool value) { }
public static void AddEventStopPropagationAttribute(this Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder builder, int sequence, string eventName, bool value) { }
}
public partial class WheelEventArgs : Microsoft.AspNetCore.Components.Web.MouseEventArgs
{
public WheelEventArgs() { }
public long DeltaMode { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
public double DeltaX { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
public double DeltaY { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
public double DeltaZ { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } }
}
}
| 115 | 337 | 0.792581 | [
"Apache-2.0"
] | MuhortovAA/AspNetCore | src/Components/Web/ref/Microsoft.AspNetCore.Components.Web.netcoreapp.cs | 50,140 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was automatically generated.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace FoxKit.Modules.DataSet.Fox
{
using System;
using System.Collections.Generic;
using FoxKit.Modules.DataSet.Fox.FoxCore;
using FoxKit.Modules.Lua;
using FoxLib;
using static KopiLua.Lua;
using OdinSerializer;
using UnityEngine;
using DataSetFile2 = DataSetFile2;
using TppGameKit = FoxKit.Modules.DataSet.Fox.TppGameKit;
[SerializableAttribute, ExposeClassToLuaAttribute]
public partial class TppWaterDropsOnCameraLens : Data
{
[OdinSerializeAttribute, NonSerializedAttribute, PropertyInfoAttribute(Core.PropertyInfoType.Path, 120, 1, Core.ContainerType.StaticArray, PropertyExport.EditorAndGame, PropertyExport.EditorAndGame, null, null)]
private UnityEngine.Object diffulseTexture;
[OdinSerializeAttribute, NonSerializedAttribute, PropertyInfoAttribute(Core.PropertyInfoType.Path, 128, 1, Core.ContainerType.StaticArray, PropertyExport.EditorAndGame, PropertyExport.EditorAndGame, null, null)]
private UnityEngine.Object normalTexture;
[OdinSerializeAttribute, NonSerializedAttribute, PropertyInfoAttribute(Core.PropertyInfoType.Float, 136, 1, Core.ContainerType.StaticArray, PropertyExport.EditorAndGame, PropertyExport.EditorAndGame, null, null)]
private System.Single sizeMin;
[OdinSerializeAttribute, NonSerializedAttribute, PropertyInfoAttribute(Core.PropertyInfoType.Float, 140, 1, Core.ContainerType.StaticArray, PropertyExport.EditorAndGame, PropertyExport.EditorAndGame, null, null)]
private System.Single sizeMax;
[OdinSerializeAttribute, NonSerializedAttribute, PropertyInfoAttribute(Core.PropertyInfoType.Float, 144, 1, Core.ContainerType.StaticArray, PropertyExport.EditorAndGame, PropertyExport.EditorAndGame, null, null)]
private System.Single lifeMin;
[OdinSerializeAttribute, NonSerializedAttribute, PropertyInfoAttribute(Core.PropertyInfoType.Float, 148, 1, Core.ContainerType.StaticArray, PropertyExport.EditorAndGame, PropertyExport.EditorAndGame, null, null)]
private System.Single lifeMax;
[OdinSerializeAttribute, NonSerializedAttribute, PropertyInfoAttribute(Core.PropertyInfoType.Float, 152, 1, Core.ContainerType.StaticArray, PropertyExport.EditorAndGame, PropertyExport.EditorAndGame, null, null)]
private System.Single angleAppear;
[OdinSerializeAttribute, NonSerializedAttribute, PropertyInfoAttribute(Core.PropertyInfoType.Float, 156, 1, Core.ContainerType.StaticArray, PropertyExport.EditorAndGame, PropertyExport.EditorAndGame, null, null)]
private System.Single angleMax;
[OdinSerializeAttribute, NonSerializedAttribute, PropertyInfoAttribute(Core.PropertyInfoType.Float, 160, 1, Core.ContainerType.StaticArray, PropertyExport.EditorAndGame, PropertyExport.EditorAndGame, null, null)]
private System.Single waitMin;
[OdinSerializeAttribute, NonSerializedAttribute, PropertyInfoAttribute(Core.PropertyInfoType.Float, 164, 1, Core.ContainerType.StaticArray, PropertyExport.EditorAndGame, PropertyExport.EditorAndGame, null, null)]
private System.Single waitMax;
public override short ClassId => 112;
public override ushort Version => 1;
public override string Category => "";
}
}
| 60.145161 | 220 | 0.727541 | [
"MIT"
] | Joey35233/FoxKit | FoxKit/Assets/FoxKit/Modules/DataSet/Fox/TppWaterDropsOnCameraLens.Generated.cs | 3,729 | C# |
namespace Daves.WordamentSolver.Tries
{
public class TrieSearchResult
{
// Provided to make beginning a prefix search chain more convenient (result.TerminalNode vs result?.TerminalNode)
public TrieSearchResult()
{ }
public TrieSearchResult(Trie.Node terminalNode, bool containsPrefix, bool containsWord)
{
TerminalNode = terminalNode;
ContainsPrefix = containsPrefix;
ContainsWord = containsWord;
}
public Trie.Node TerminalNode { get; }
public bool ContainsPrefix { get; }
public bool ContainsWord { get; }
}
}
| 30.238095 | 121 | 0.644094 | [
"MIT"
] | JTOne123/Daves.WordamentSolver | Daves.WordamentSolver/Tries/TrieSearchResult.cs | 637 | 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/codecapi.h in the Windows SDK for Windows 10.0.20348.0
// Original source is Copyright © Microsoft. All rights reserved.
using NUnit.Framework;
using System;
using System.Runtime.InteropServices;
using static TerraFX.Interop.Windows;
namespace TerraFX.Interop.UnitTests
{
/// <summary>Provides validation of the <see cref="CODECAPI_AVEncDDRFPreEmphasisFilter" /> struct.</summary>
public static unsafe class CODECAPI_AVEncDDRFPreEmphasisFilterTests
{
/// <summary>Validates that the <see cref="Guid" /> of the <see cref="CODECAPI_AVEncDDRFPreEmphasisFilter" /> struct is correct.</summary>
[Test]
public static void GuidOfTest()
{
Assert.That(typeof(CODECAPI_AVEncDDRFPreEmphasisFilter).GUID, Is.EqualTo(STATIC_CODECAPI_AVEncDDRFPreEmphasisFilter));
}
/// <summary>Validates that the <see cref="CODECAPI_AVEncDDRFPreEmphasisFilter" /> struct is blittable.</summary>
[Test]
public static void IsBlittableTest()
{
Assert.That(Marshal.SizeOf<CODECAPI_AVEncDDRFPreEmphasisFilter>(), Is.EqualTo(sizeof(CODECAPI_AVEncDDRFPreEmphasisFilter)));
}
/// <summary>Validates that the <see cref="CODECAPI_AVEncDDRFPreEmphasisFilter" /> struct has the right <see cref="LayoutKind" />.</summary>
[Test]
public static void IsLayoutSequentialTest()
{
Assert.That(typeof(CODECAPI_AVEncDDRFPreEmphasisFilter).IsLayoutSequential, Is.True);
}
/// <summary>Validates that the <see cref="CODECAPI_AVEncDDRFPreEmphasisFilter" /> struct has the correct size.</summary>
[Test]
public static void SizeOfTest()
{
Assert.That(sizeof(CODECAPI_AVEncDDRFPreEmphasisFilter), Is.EqualTo(1));
}
}
}
| 43.488889 | 148 | 0.703117 | [
"MIT"
] | phizch/terrafx.interop.windows | tests/Interop/Windows/um/codecapi/CODECAPI_AVEncDDRFPreEmphasisFilterTests.cs | 1,959 | C# |
namespace Models
{
public static class SignedInUser
{
// store info about signed-in user
public static string User_id { get; set; }
public static string Email { get; set; }
public static string Fname { get; set; }
public static string Lname { get; set; }
public static bool isSignedIn { get; set; }
}
} | 30.25 | 51 | 0.606061 | [
"MIT"
] | Zenithcoder/SCORM-LearningManagementSystem | OpenSourceSCORMLMS/Areas/Models/SignedInUser.cs | 365 | C# |
using Terraria;
using Terraria.ID;
using static Terraria.ID.ItemUseStyleID;
public class ItemUseStyleIDTest
{
public void SetUseStyle(Item item) {
item.useStyle = ItemUseStyleID.HoldUp;
item.useStyle = ItemUseStyleID.Shoot;
item.useStyle = ItemUseStyleID.Swing;
item.useStyle = ItemUseStyleID.EatFood;
item.useStyle = ItemUseStyleID.Thrust;
item.useStyle = HoldUp;
item.useStyle = Shoot;
item.useStyle = Swing;
item.useStyle = EatFood;
item.useStyle = Thrust;
}
} | 23.238095 | 41 | 0.756148 | [
"MIT"
] | blushiemagic/tModLoader | tModPorter/tModPorter.Tests/TestData/ItemUseStyleIDTest.Expected.cs | 488 | C# |
using iBank.Operator.Desktop.ViewModels;
using OfficeOpenXml;
using Ookii.Dialogs.Wpf;
using System;
using System.Drawing;
using System.IO;
using System.Windows;
using System.Windows.Controls;
namespace iBank.Operator.Desktop.Views
{
/// <summary>
/// Interaction logic for Bank.xaml
/// </summary>
public partial class DactyloscopyView : UserControl
{
public DactyloscopyViewModel ViewModel => DataContext as DactyloscopyViewModel ?? throw new Exception("Шо блэт");
public DactyloscopyView()
{
DataContext = new CardsViewModel();
InitializeComponent();
}
private void Button_Today_DB_Click(object sender, RoutedEventArgs e)
{
using (var p = new ExcelPackage())
using (var sqlcmd = new SqlCommandExecutor("EXEC pr_GetDactyloscopyReport"))
using (var sqlReader = sqlcmd.ExecuteReader())
{
var ws = p.Workbook.Worksheets.Add("BANK");
int count = sqlReader.FieldCount;
for (var i = 1; sqlReader.Read(); i++)
for (int j = 1; j <= count; j++)
{
ws.Cells[i, j].Value = sqlReader.GetValue(j - 1);
ws.Cells[i, j].Style.Font.SetFromFont(new Font("Times New Roman", 12));
}
var dlg = new VistaSaveFileDialog()
{
Filter = "Open XML Spreadsheet |*.xlsx",
FileName = "Отчет для дактилоскопии",
DefaultExt = ".xlsx",
OverwritePrompt = true,
CreatePrompt = false,
};
if (dlg.ShowDialog() == true)
{
using (var fs = File.Create(dlg.FileName))
p.SaveAs(fs);
}
}
}
}
} | 32.508475 | 121 | 0.519812 | [
"MIT"
] | mcap-ibank/iBank.Desktop | iBank.Operator.Desktop/Views/DactyloscopyView.xaml.cs | 1,947 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using EventCatalogApi.Data;
using EventCatalogApi.Domain;
using EventCatalogApi.ViewModels;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
namespace EventCatalogApi.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class EventController : ControllerBase
{
private readonly EventCatalogContext _context;
private readonly IConfiguration _config;
public EventController(EventCatalogContext context, IConfiguration config)
{
_context = context;
_config = config;
}
[HttpGet("[action]")]
public async Task<IActionResult> EventPlaces()
{
var places = await _context.EventPlace.ToListAsync();
return Ok(places);
}
[HttpGet("[action]")]
public async Task<IActionResult> EventCategories()
{
var categories = await _context.EventCategory.ToListAsync();
return Ok(categories);
}
[HttpGet("[action]")]
public async Task<IActionResult> Events(
[FromQuery] int pageIndex = 0,
[FromQuery] int pageSize = 6)
{
var itemsCount = _context.EventCatalogTable.LongCountAsync();
var items = await _context.EventCatalogTable
.OrderBy(c => c.Name)
.Skip(pageIndex * pageSize)
.Take(pageSize)
.ToListAsync();
items = ChangePictureUrl(items);
var model = new PaginatedItemsViewModel
{
PageIndex = pageIndex,
PageSize = items.Count,
Count = itemsCount.Result,
Data = items
};
return Ok(model);
}
[HttpGet("[action]/filter")]
public async Task<IActionResult> Events(
[FromQuery] int? eventTypeId,
[FromQuery] int? eventPlaceId,
[FromQuery] int pageIndex = 0,
[FromQuery] int pageSize = 6)
{
var query = (IQueryable<Event>)_context.EventCatalogTable;
if (eventTypeId.HasValue)
{
query = query.Where(c => c.EventCategoryId == eventTypeId);
}
if (eventPlaceId.HasValue)
{
query = query.Where(c => c.EventPlaceId== eventPlaceId);
}
var itemsCount = _context.EventCatalogTable.LongCountAsync();
var items = await query
.OrderBy(c => c.Name)
.Skip(pageIndex * pageSize)
.Take(pageSize)
.ToListAsync();
items = ChangePictureUrl(items);
var model = new PaginatedItemsViewModel
{
PageIndex = pageIndex,
PageSize = items.Count,
Count = itemsCount.Result,
Data = items
};
return Ok(model);
}
private List<Event> ChangePictureUrl(List<Event> events)
{
events.ForEach(ev =>
ev.PictureURL = ev.PictureURL.Replace("http://externalcatalogbaseurltobereplaced",
_config["Externalbaseurl"]));
return events;
}
}
}
| 33.055556 | 98 | 0.538375 | [
"MIT"
] | zewditu/MicroServicesPartOne | Eventbriteassignment/EventCatalogApi/Controllers/EventController.cs | 3,572 | C# |
namespace Nacos
{
using Microsoft.Extensions.Logging;
using Nacos.V2.Utils;
using System;
using System.Collections.Concurrent;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
public class FailoverReactor : IDisposable
{
public static string FAILOVER_MODE_NAME = "failover-mode";
public static string FAILOVER_PATH = "failover";
private readonly ILogger _logger;
private string _failoverDir;
private HostReactor _hostReactor;
private DiskCache _diskCache;
private Timer _switchRefresher;
private Timer _diskFileWriter;
private ConcurrentDictionary<string, ServiceInfo> _serviceMap = new ConcurrentDictionary<string, ServiceInfo>();
private ConcurrentDictionary<string, string> _switchParams = new ConcurrentDictionary<string, string>();
public FailoverReactor(ILoggerFactory loggerFactory, HostReactor hostReactor, DiskCache diskCache, string cacheDir)
{
_logger = loggerFactory.CreateLogger<FailoverReactor>();
_hostReactor = hostReactor;
_diskCache = diskCache;
_failoverDir = Path.Combine(cacheDir, FAILOVER_PATH);
Init();
}
public void Init()
{
SwitchRefresher();
DiskFileWriter();
}
private void SwitchRefresher()
{
long lastModifiedMillis = 0;
_switchRefresher = new Timer(
async x =>
{
try
{
string filePath = Path.Combine(_failoverDir, ConstValue.FAILOVER_SWITCH);
if (!File.Exists(filePath))
{
_switchParams.AddOrUpdate(FAILOVER_MODE_NAME, "false", (k, v) => "false");
_logger?.LogDebug("failover switch is not found, {0}", filePath);
return;
}
long modified = _diskCache.GetFileLastModifiedTime(filePath);
if (lastModifiedMillis < modified)
{
lastModifiedMillis = modified;
string failover = await _diskCache.ReadFile(filePath).ConfigureAwait(false);
if (!string.IsNullOrEmpty(failover))
{
var lines = failover.SplitByString(_diskCache.GetLineSeparator());
foreach (var line in lines)
{
if ("1".Equals(line.Trim()))
{
_switchParams.AddOrUpdate(FAILOVER_MODE_NAME, "true", (k, v) => "true");
_logger?.LogInformation($"{FAILOVER_MODE_NAME} is on");
await FailoverFileReader().ConfigureAwait(false);
}
else if ("0".Equals(line.Trim()))
{
_switchParams.AddOrUpdate(FAILOVER_MODE_NAME, "false", (k, v) => "false");
_logger?.LogInformation($"{FAILOVER_MODE_NAME} is off");
}
}
}
else
{
_switchParams.AddOrUpdate(FAILOVER_MODE_NAME, "false", (k, v) => "false");
}
}
}
catch (Exception ex)
{
_logger?.LogError(ex, "[NA] failed to read failover switch.");
}
}, null, TimeSpan.Zero, TimeSpan.FromMilliseconds(5000));
}
private void DiskFileWriter()
{
_diskFileWriter = new Timer(
async x =>
{
var map = _hostReactor.GetServiceInfoMap();
foreach (var entry in map)
{
ServiceInfo serviceInfo = entry.Value;
if (serviceInfo.GetKey().Equals(ConstValue.ALL_IPS)
|| serviceInfo.name.Equals(ConstValue.ENV_LIST_KEY)
|| serviceInfo.name.Equals(ConstValue.ENV_CONFIGS)
|| serviceInfo.name.Equals(ConstValue.VIPCLIENT_CONFIG)
|| serviceInfo.name.Equals(ConstValue.ALL_HOSTS))
{
continue;
}
await _diskCache.WriteServiceInfoAsync(_failoverDir, serviceInfo).ConfigureAwait(false);
}
}, null, TimeSpan.FromMinutes(30), TimeSpan.FromMinutes(24 * 60));
}
private async Task FailoverFileReader()
{
var domMap = new ConcurrentDictionary<string, ServiceInfo>();
try
{
var files = _diskCache.MakeSureCacheDirExists(_failoverDir);
foreach (var filePath in files)
{
var fi = new FileInfo(filePath);
if (fi.Name.Equals(ConstValue.FAILOVER_SWITCH)) continue;
string content = await _diskCache.ReadFile(filePath).ConfigureAwait(false);
ServiceInfo serviceInfo = content.ToObj<ServiceInfo>();
if (serviceInfo.Hosts != null && serviceInfo.Hosts.Count > 0)
{
domMap.AddOrUpdate(serviceInfo.GetKey(), serviceInfo, (k, v) => serviceInfo);
}
}
}
catch (Exception ex)
{
_logger?.LogError(ex, "[NA] failed to read cache files");
}
if (domMap.Count > 0)
{
_serviceMap = domMap;
}
}
public bool IsFailoverSwitch()
{
if (_switchParams.TryGetValue(FAILOVER_MODE_NAME, out string failover))
{
return !failover.Equals("false");
}
return false;
}
public ServiceInfo GetService(string key)
{
if (!_serviceMap.TryGetValue(key, out ServiceInfo serviceInfo))
{
serviceInfo = new ServiceInfo
{
name = key
};
}
return serviceInfo;
}
public void Dispose()
{
_diskFileWriter?.Dispose();
_switchRefresher?.Dispose();
}
}
} | 36.918478 | 123 | 0.477403 | [
"Apache-2.0"
] | SwingZhang/nacos-sdk-csharp | src/Nacos/Naming/Cache/FailoverReactor.cs | 6,795 | C# |
// ********************************************************************************************************
// Product Name: DotSpatial.Symbology.Forms.dll
// Description: The Windows Forms user interface layer for the DotSpatial.Projections library.
//
// ********************************************************************************************************
// The contents of this file are subject to the MIT License (MIT)
// you may not use this file except in compliance with the License. You may obtain a copy of the License at
// http://dotspatial.codeplex.com/license
//
// Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF
// ANY KIND, either expressed or implied. See the License for the specific language governing rights and
// limitations under the License.
//
// The Original Code is DotSpatial.dll for the DotSpatial project
//
// The Initial Developer of this Original Code is Ted Dunsford. Created in September, 2007.
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************
using System.Windows.Forms;
using DotSpatial.Data;
namespace DotSpatial.Symbology.Forms
{
/// <summary>
/// Actions that occur on an image layer in the legend.
/// </summary>
public class ImageLayerActions : LegendItemActionsBase, IImageLayerActions
{
/// <summary>
/// Show the properties of an image layer in the legend.
/// </summary>
/// <param name="e"></param>
public void ShowProperties(IImageLayer e)
{
using (var dlg = new LayerDialog(e,new ImageCategoryControl()))
{
ShowDialog(dlg);
}
}
/// <summary>
/// Export data from an image layer.
/// </summary>
/// <param name="e"></param>
public void ExportData(IImageData e)
{
using (var sfd = new SaveFileDialog
{
Filter = DataManager.DefaultDataManager.RasterWriteFilter
})
{
if (ShowDialog(sfd) == DialogResult.OK)
{
e.SaveAs(sfd.FileName);
}
}
}
}
} | 38.935484 | 109 | 0.517813 | [
"MIT"
] | sdrmaps/dotspatial | Source/DotSpatial.Symbology.Forms/ImageLayerActions.cs | 2,416 | C# |
using System;
namespace Man.Dapr.Sidekick.Security
{
public class RandomStringApiTokenProvider : IDaprApiTokenProvider
{
public string GetAppApiToken() => Guid.NewGuid().ToString();
public string GetDaprApiToken() => Guid.NewGuid().ToString();
}
}
| 23.25 | 69 | 0.695341 | [
"Apache-2.0"
] | Benknightdark/dapr-sidekick-dotnet | src/Man.Dapr.Sidekick/Security/RandomStringApiTokenProvider.cs | 281 | C# |
using System;
using UnityEngine;
/// <summary>
/// 满足特定条件时才显示,为UnityEvent类型量身定制
/// </summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true)]
public class ConditionalShow4UEventAttribute : PropertyAttribute
{
//条件字段,枚举或整型
public string ConditionalIntField = "";
//预期值
public int[] ExpectedValues;
public ConditionalShow4UEventAttribute(string conditionalIntField, object expectedValue)
{
this.ConditionalIntField = conditionalIntField;
this.ExpectedValues = new int[] { (int)expectedValue };
}
public ConditionalShow4UEventAttribute(string conditionalIntField, params object[] expectedValues)
{
this.ConditionalIntField = conditionalIntField;
this.ExpectedValues = new int[expectedValues.Length];
for (int i = 0; i < expectedValues.Length; i++) this.ExpectedValues[i] = (int)expectedValues[i];
}
} | 35.538462 | 104 | 0.728355 | [
"Apache-2.0"
] | Minstreams/Hometopia | Assets/Scripts/Library/ConditionalShow4UEvent/ConditionalShow4UEventAttribute.cs | 988 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
namespace DynamicStyles.UWP
{
/// <summary>
/// Provides application-specific behavior to supplement the default Application class.
/// </summary>
sealed partial class App : Application
{
/// <summary>
/// Initializes the singleton application object. This is the first line of authored code
/// executed, and as such is the logical equivalent of main() or WinMain().
/// </summary>
public App()
{
Microsoft.ApplicationInsights.WindowsAppInitializer.InitializeAsync(
Microsoft.ApplicationInsights.WindowsCollectors.Metadata |
Microsoft.ApplicationInsights.WindowsCollectors.Session);
this.InitializeComponent();
this.Suspending += OnSuspending;
}
/// <summary>
/// Invoked when the application is launched normally by the end user. Other entry points
/// will be used such as when the application is launched to open a specific file.
/// </summary>
/// <param name="e">Details about the launch request and process.</param>
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
#if DEBUG
if (System.Diagnostics.Debugger.IsAttached)
{
this.DebugSettings.EnableFrameRateCounter = true;
}
#endif
Frame rootFrame = Window.Current.Content as Frame;
// Do not repeat app initialization when the Window already has content,
// just ensure that the window is active
if (rootFrame == null)
{
// Create a Frame to act as the navigation context and navigate to the first page
rootFrame = new Frame();
rootFrame.NavigationFailed += OnNavigationFailed;
Xamarin.Forms.Forms.Init(e);
if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
{
//TODO: Load state from previously suspended application
}
// Place the frame in the current Window
Window.Current.Content = rootFrame;
}
if (rootFrame.Content == null)
{
// When the navigation stack isn't restored navigate to the first page,
// configuring the new page by passing required information as a navigation
// parameter
rootFrame.Navigate(typeof(MainPage), e.Arguments);
}
// Ensure the current window is active
Window.Current.Activate();
}
/// <summary>
/// Invoked when Navigation to a certain page fails
/// </summary>
/// <param name="sender">The Frame which failed navigation</param>
/// <param name="e">Details about the navigation failure</param>
void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
{
throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
}
/// <summary>
/// Invoked when application execution is being suspended. Application state is saved
/// without knowing whether the application will be terminated or resumed with the contents
/// of memory still intact.
/// </summary>
/// <param name="sender">The source of the suspend request.</param>
/// <param name="e">Details about the suspend request.</param>
private void OnSuspending(object sender, SuspendingEventArgs e)
{
var deferral = e.SuspendingOperation.GetDeferral();
//TODO: Save application state and stop any background activity
deferral.Complete();
}
}
}
| 38.405405 | 99 | 0.626789 | [
"Apache-2.0"
] | NoleHealth/xamarin-forms-book-preview-2 | Chapter12/DynamicStyles/DynamicStyles/DynamicStyles.UWP/App.xaml.cs | 4,265 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
//
// This source code was auto-generated by Microsoft.VSDesigner, Version 4.0.30319.42000.
//
#pragma warning disable 1591
namespace AgenceGUI.ReferenceServiceDisponibilte {
using System;
using System.Web.Services;
using System.Diagnostics;
using System.Web.Services.Protocols;
using System.Xml.Serialization;
using System.ComponentModel;
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.8.4084.0")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Web.Services.WebServiceBindingAttribute(Name="ConsulterDisponibiliteSoap", Namespace="http://tempuri.org/")]
public partial class ConsulterDisponibilite : System.Web.Services.Protocols.SoapHttpClientProtocol {
private System.Threading.SendOrPostCallback chercherDisponibiliteOperationCompleted;
private bool useDefaultCredentialsSetExplicitly;
/// <remarks/>
public ConsulterDisponibilite() {
this.Url = global::AgenceGUI.Properties.Settings.Default.AgenceGUI_ReferenceServiceDisponibilte_ConsulterDisponibilite;
if ((this.IsLocalFileSystemWebService(this.Url) == true)) {
this.UseDefaultCredentials = true;
this.useDefaultCredentialsSetExplicitly = false;
}
else {
this.useDefaultCredentialsSetExplicitly = true;
}
}
public new string Url {
get {
return base.Url;
}
set {
if ((((this.IsLocalFileSystemWebService(base.Url) == true)
&& (this.useDefaultCredentialsSetExplicitly == false))
&& (this.IsLocalFileSystemWebService(value) == false))) {
base.UseDefaultCredentials = false;
}
base.Url = value;
}
}
public new bool UseDefaultCredentials {
get {
return base.UseDefaultCredentials;
}
set {
base.UseDefaultCredentials = value;
this.useDefaultCredentialsSetExplicitly = true;
}
}
/// <remarks/>
public event chercherDisponibiliteCompletedEventHandler chercherDisponibiliteCompleted;
/// <remarks/>
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/chercherDisponibilite", RequestNamespace="http://tempuri.org/", ResponseNamespace="http://tempuri.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public Offre[] chercherDisponibilite(string login, string mdp, string dateDebut, string dateFin, int nbPersonne) {
object[] results = this.Invoke("chercherDisponibilite", new object[] {
login,
mdp,
dateDebut,
dateFin,
nbPersonne});
return ((Offre[])(results[0]));
}
/// <remarks/>
public void chercherDisponibiliteAsync(string login, string mdp, string dateDebut, string dateFin, int nbPersonne) {
this.chercherDisponibiliteAsync(login, mdp, dateDebut, dateFin, nbPersonne, null);
}
/// <remarks/>
public void chercherDisponibiliteAsync(string login, string mdp, string dateDebut, string dateFin, int nbPersonne, object userState) {
if ((this.chercherDisponibiliteOperationCompleted == null)) {
this.chercherDisponibiliteOperationCompleted = new System.Threading.SendOrPostCallback(this.OnchercherDisponibiliteOperationCompleted);
}
this.InvokeAsync("chercherDisponibilite", new object[] {
login,
mdp,
dateDebut,
dateFin,
nbPersonne}, this.chercherDisponibiliteOperationCompleted, userState);
}
private void OnchercherDisponibiliteOperationCompleted(object arg) {
if ((this.chercherDisponibiliteCompleted != null)) {
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.chercherDisponibiliteCompleted(this, new chercherDisponibiliteCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
/// <remarks/>
public new void CancelAsync(object userState) {
base.CancelAsync(userState);
}
private bool IsLocalFileSystemWebService(string url) {
if (((url == null)
|| (url == string.Empty))) {
return false;
}
System.Uri wsUri = new System.Uri(url);
if (((wsUri.Port >= 1024)
&& (string.Compare(wsUri.Host, "localHost", System.StringComparison.OrdinalIgnoreCase) == 0))) {
return true;
}
return false;
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.8.4084.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://tempuri.org/")]
public partial class Offre {
private string identifiantField;
private TypeChambre typeChambreField;
private string dateDisponibiliteField;
private double prixField;
private byte[] imageField;
/// <remarks/>
public string Identifiant {
get {
return this.identifiantField;
}
set {
this.identifiantField = value;
}
}
/// <remarks/>
public TypeChambre TypeChambre {
get {
return this.typeChambreField;
}
set {
this.typeChambreField = value;
}
}
/// <remarks/>
public string DateDisponibilite {
get {
return this.dateDisponibiliteField;
}
set {
this.dateDisponibiliteField = value;
}
}
/// <remarks/>
public double Prix {
get {
return this.prixField;
}
set {
this.prixField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(DataType="base64Binary")]
public byte[] Image {
get {
return this.imageField;
}
set {
this.imageField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.8.4084.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://tempuri.org/")]
public partial class TypeChambre {
private int nbLitsField;
/// <remarks/>
public int NbLits {
get {
return this.nbLitsField;
}
set {
this.nbLitsField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.8.4084.0")]
public delegate void chercherDisponibiliteCompletedEventHandler(object sender, chercherDisponibiliteCompletedEventArgs e);
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.8.4084.0")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class chercherDisponibiliteCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {
private object[] results;
internal chercherDisponibiliteCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
base(exception, cancelled, userState) {
this.results = results;
}
/// <remarks/>
public Offre[] Result {
get {
this.RaiseExceptionIfNecessary();
return ((Offre[])(this.results[0]));
}
}
}
}
#pragma warning restore 1591 | 37.706827 | 325 | 0.571733 | [
"CC0-1.0"
] | ahmedBylka/Gestion_hotel_distribuee | AgenceGUI/AgenceGUI/Web References/ReferenceServiceDisponibilte/Reference.cs | 9,391 | C# |
using System.Windows;
namespace Tracker.Views
{
/// <summary>
/// Interaction logic for AboutWindow.xaml
/// </summary>
public partial class AboutWindow : Window
{
public AboutWindow()
{
InitializeComponent();
}
}
}
| 17.375 | 46 | 0.568345 | [
"MIT"
] | vjkrammes/Tracker | Tracker/Views/AboutWindow.xaml.cs | 280 | 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("MyEmailer")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MyEmailer")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[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("876e73b5-dfa7-4028-93fa-8eaf9f95b3ca")]
// 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.459459 | 84 | 0.746753 | [
"MIT"
] | pilacst/MyEmailer | MyEmailer/Properties/AssemblyInfo.cs | 1,389 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the codebuild-2016-10-06.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.CodeBuild.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.CodeBuild.Model.Internal.MarshallTransformations
{
/// <summary>
/// S3ReportExportConfig Marshaller
/// </summary>
public class S3ReportExportConfigMarshaller : IRequestMarshaller<S3ReportExportConfig, JsonMarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="requestObject"></param>
/// <param name="context"></param>
/// <returns></returns>
public void Marshall(S3ReportExportConfig requestObject, JsonMarshallerContext context)
{
if(requestObject.IsSetBucket())
{
context.Writer.WritePropertyName("bucket");
context.Writer.Write(requestObject.Bucket);
}
if(requestObject.IsSetEncryptionDisabled())
{
context.Writer.WritePropertyName("encryptionDisabled");
context.Writer.Write(requestObject.EncryptionDisabled);
}
if(requestObject.IsSetEncryptionKey())
{
context.Writer.WritePropertyName("encryptionKey");
context.Writer.Write(requestObject.EncryptionKey);
}
if(requestObject.IsSetPackaging())
{
context.Writer.WritePropertyName("packaging");
context.Writer.Write(requestObject.Packaging);
}
if(requestObject.IsSetPath())
{
context.Writer.WritePropertyName("path");
context.Writer.Write(requestObject.Path);
}
}
/// <summary>
/// Singleton Marshaller.
/// </summary>
public readonly static S3ReportExportConfigMarshaller Instance = new S3ReportExportConfigMarshaller();
}
} | 33.662791 | 114 | 0.648359 | [
"Apache-2.0"
] | PureKrome/aws-sdk-net | sdk/src/Services/CodeBuild/Generated/Model/Internal/MarshallTransformations/S3ReportExportConfigMarshaller.cs | 2,895 | C# |
using System.Runtime.InteropServices;
namespace RFReborn.Windows.Native.Structs
{
/// <summary>
/// The RECT structure defines a rectangle by the coordinates of its upper-left and lower-right corners.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
/// <summary>
/// Specifies the x-coordinate of the upper-left corner of the rectangle.
/// </summary>
public int left;
/// <summary>
/// Specifies the y-coordinate of the upper-left corner of the rectangle.
/// </summary>
public int top;
/// <summary>
/// Specifies the x-coordinate of the lower-right corner of the rectangle.
/// </summary>
public int right;
/// <summary>
/// Specifies the y-coordinate of the lower-right corner of the rectangle.
/// </summary>
public int bottom;
}
}
| 28.875 | 108 | 0.600649 | [
"MIT"
] | mztikk/RFReborn.Windows | RFReborn.Windows/Native/Structs/RECT.cs | 926 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.