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
sequence | repository_name
stringlengths 7
92
| path
stringlengths 3
249
| size
int64 5
1.04M
| lang
stringclasses 2
values |
---|---|---|---|---|---|---|---|---|
using Xunit;
namespace Oqtane.Database.Sqlite.Tests
{
public class SqliteDatabaseTests
{
[Fact()]
public void VerifyDatabaseTypeName()
{
// Arrange & Act
var database = new SqliteDatabase();
// Assert
Assert.Equal("Oqtane.Database.Sqlite.SqliteDatabase, Oqtane.Database.Sqlite", database.TypeName);
}
}
}
| 22.166667 | 109 | 0.588972 | [
"MIT"
] | 2sic-forks/oqtane.framework | Oqtane.Test/Oqtane.Database.Sqlite/SqliteDatabaseTests.cs | 399 | C# |
using UdonSharp;
using UnityEngine;
using VRC.SDKBase;
using VRC.Udon;
namespace StepmaniaVRC
{
/// <summary>
/// Simple class representing an arrow on the gamescreen
/// </summary>
public class ArrowVisualizer : UdonSharpBehaviour
{
public Renderer[] myRenderers;//Renderers associated to the visualizer, should be passed to the prefab in the scene. Multiple in case we have sub elements
void Start()
{
}
/// <summary>
/// Material/Color of the arrow should change depending on whatever we want, change it for each renderer associated to this ArrowVisualizer
/// </summary>
/// <param name="mat">Material/Color to change this arrow to</param>
public void changeMat(Material mat)
{
foreach (var renderer in myRenderers)
renderer.material = mat;
}
}
} | 29.833333 | 162 | 0.639106 | [
"MIT"
] | jiray-yay/Stepmania-VRC | Scripts/ArrowVisualizer.cs | 897 | C# |
using System.Linq;
using SnippetBuilder.Models;
namespace SnippetBuilder.Extensions
{
public static class RecipeExtensions
{
public static bool Validate(this Recipe recipe)
{
if (string.IsNullOrEmpty(recipe.Name)) return false;
if (string.IsNullOrEmpty(recipe.Output)) return false;
return recipe.Input is { } && !recipe.Input.Any(string.IsNullOrEmpty);
}
}
} | 28.8 | 82 | 0.657407 | [
"MIT"
] | AconCavy/SnippetBuilder | src/SnippetBuilder/Extensions/RecipeExtensions.cs | 432 | C# |
using UnityEngine;
namespace UniVRM10
{
public static class TransformExtensions
{
public static Quaternion ParentRotation(this Transform transform)
{
return transform.parent == null ? Quaternion.identity : transform.parent.rotation;
}
}
}
| 23.076923 | 95 | 0.643333 | [
"MIT"
] | ousttrue/UniVRM_1_0 | Assets/Vrm10/UniVRM10/Components/Constraint/TransformExtensions.cs | 300 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LexShop.Core.Models;
using LexShop.Core.ViewModels;
namespace LexShop.Core.Contracts
{
//5. Create the interface
public interface IOrderService
{
void CreateOrder(Order baseOrder, List<BasketItemViewModel> basketItems);
List<Order> GetOrderList();
Order GetOrder(string Id);
void UpdateOrder(Order updatedOrder);
}
}
| 24.45 | 81 | 0.728016 | [
"MIT"
] | rghalayini/LexShop | LexShop/LexShop.Core/Contracts/IOrderService.cs | 491 | C# |
// Copyright (c) E5R Development Team. All rights reserved.
// This file is a part of E5R.Architecture.
// Licensed under the Apache version 2.0: https://github.com/e5r/manifest/blob/master/license/APACHE-2.0.txt
using E5R.Architecture.Core;
namespace E5R.Architecture.Data.Abstractions.Alias
{
public interface IStoreBulkWriter<TUowProperty, TDataModel> : IStoreBulkWriter<TDataModel>
where TDataModel : IIdentifiable
{ }
public interface IStoreBulkWriter<TDataModel> : IStorageBulkWriter<TDataModel>
where TDataModel : IIdentifiable
{ }
}
| 33.941176 | 108 | 0.752166 | [
"Apache-2.0"
] | e5r/E5R.Architecture | src/E5R.Architecture.Data/Abstractions/Alias/IStoreBulkWriter`2.cs | 579 | C# |
using System;
using ProjectManager.Framework.Core.Common.Contracts;
namespace ProjectManager.Framework.Core.Common.Providers
{
public class ConsoleWriter : IWriter
{
public void Write(object value)
{
Console.Write(value);
}
public void WriteLine(object value)
{
Console.WriteLine(value);
}
}
}
| 20.052632 | 56 | 0.614173 | [
"MIT"
] | SimeonGerginov/Telerik-Academy | 06. C# Design Patterns/Exams/2017-06-15/ProjectManager.Framework/Core/Common/Providers/ConsoleWriter.cs | 383 | C# |
/*********************************************
作者:曹旭升
QQ:279060597
访问博客了解详细介绍及更多内容:
http://blog.shengxunwei.com
**********************************************/
using System;
using System.Data.Common;
using System.Data.SqlServerCe;
using Microsoft.Practices.EnterpriseLibrary.Data.SqlCe;
using Microsoft.Practices.EnterpriseLibrary.Data.Tests;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Data.SqlCe.Tests.VSTS
{
[TestClass]
public class SqlCeExecuteScalarFixture
{
TestConnectionString testConnection;
SqlCeDatabase db;
ExecuteScalarFixture baseFixture;
[TestInitialize]
public void SetUp()
{
testConnection = new TestConnectionString();
testConnection.CopyFile();
db = new SqlCeDatabase(testConnection.ConnectionString);
DbCommand command = db.GetSqlStringCommand("Select count(*) from region");
baseFixture = new ExecuteScalarFixture(db, command);
}
[TestCleanup]
public void DeleteDb()
{
SqlCeConnectionPool.CloseSharedConnections();
testConnection.DeleteFile();
}
[TestMethod]
public void CanOpenDatabase()
{
Assert.IsNotNull(db);
}
[TestMethod]
public void ExecuteScalarWithIDbCommand()
{
baseFixture.ExecuteScalarWithIDbCommand();
}
[TestMethod]
public void ExecuteScalarWithCommandTextAndTypeInTransaction()
{
baseFixture.ExecuteScalarWithCommandTextAndTypeInTransaction();
}
[TestMethod]
[ExpectedException(typeof(NotImplementedException))]
public void CannotExecuteReaderWithStoredProcInTransaction()
{
using (DbConnection connection = db.CreateConnection())
{
connection.Open();
using (DbTransaction trans = connection.BeginTransaction())
{
db.ExecuteScalar(trans, "Ten Most Expensive Products");
trans.Rollback();
}
}
}
[TestMethod]
[ExpectedException(typeof(SqlCeException))]
public void ExecuteSqlWithBadCommandThrows()
{
DbCommand badCommand = db.GetSqlStringCommand("select * from foobar");
db.ExecuteScalar(badCommand);
}
[TestMethod]
public void ExecuteScalarWithIDbTransaction()
{
baseFixture.ExecuteScalarWithIDbTransaction();
}
[TestMethod]
public void CanExecuteScalarDoAnInsertion()
{
baseFixture.CanExecuteScalarDoAnInsertion();
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void ExecuteScalarWithNullIDbCommand()
{
baseFixture.ExecuteScalarWithNullIDbCommand();
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void ExecuteScalarWithNullIDbTransaction()
{
baseFixture.ExecuteScalarWithNullIDbTransaction();
}
[TestMethod]
[ExpectedException(typeof(NotImplementedException))]
public void ExecuteScalarWithNullIDbCommandAndNullTransaction()
{
baseFixture.ExecuteScalarWithNullIDbCommandAndNullTransaction();
}
}
}
| 34.696078 | 87 | 0.589432 | [
"MIT"
] | ckalvin-hub/Sheng.Winform.IDE | SourceCode/Source/EnterpriseLibrary/Data/Tests/SqlCe.Tests/SqlCeExecuteScalarFixture.cs | 3,587 | C# |
namespace CyclopsEnhancedSonar
{
using System;
using Common;
using Harmony;
using MoreCyclopsUpgrades.API;
using SMLHelper.V2.Handlers;
public static class QPatch
{
public static void Patch()
{
QuickLogger.Info($"Started patching. Version {QuickLogger.GetAssemblyVersion()}");
try
{
var harmony = HarmonyInstance.Create("com.CyclopsEnhancedSonar.psmod");
harmony.Patch( // Create a postfix patch on the SubControl Start method to add the CySonarComponent
original: AccessTools.Method(typeof(SubControl), nameof(SubControl.Start)),
postfix: new HarmonyMethod(typeof(QPatch), nameof(QPatch.SubControlStartPostfix)));
// Register a custom upgrade handler for the CyclopsSonarModule
MCUServices.Register.CyclopsUpgradeHandler((SubRoot s) => new SonarUpgradeHandler(s));
// Register a PDA Icon Overlay for the CyclopsSonarModule
MCUServices.Register.PdaIconOverlay(TechType.CyclopsSonarModule,
(uGUI_ItemIcon i, InventoryItem u) => new SonarPdaDisplay(i, u));
// Add a language line for the text in the SonarPdaDisplay to allow it to be easily overridden
LanguageHandler.SetLanguageLine(SonarPdaDisplay.SpeedUpKey, SonarPdaDisplay.SpeedUpText);
QuickLogger.Info($"Finished patching.");
}
catch (Exception ex)
{
QuickLogger.Error(ex);
}
}
internal static void SubControlStartPostfix(SubControl __instance)
{
if (__instance.gameObject.name.StartsWith("Cyclops-MainPrefab"))
__instance.gameObject.AddComponent<CySonarComponent>();
}
}
}
| 40.06383 | 117 | 0.614976 | [
"MIT"
] | Denkkar/PrimeSonicSubnauticaMods | CyclopsEnhancedSonar/QPatch.cs | 1,885 | C# |
namespace ViewModels.Client
{
using ViewModels.Address;
public class ClientViewModel
{
public string FirstName { get; init; }
public string LastName { get; init; }
public string PhoneNumber { get; init; }
public AddressViewModel Address { get; init; }
}
}
| 19.3125 | 54 | 0.627832 | [
"MIT"
] | AchoVasilev/BgAirsoft | serverAPI/AirsoftServer/ViewModels/Client/ClientViewModel.cs | 311 | C# |
using System.Collections;
using System.Collections.Generic;
using System.Threading.Tasks;
using DualPantoFramework;
using SpeechIO;
using UnityEngine;
public class LabyrinthGameManager : MonoBehaviour
{
GameObject[] forceFields;
public GameObject forceFieldPrefab;
GameObject upper;
GameObject lower;
private SpeechOut speech;
bool isRunning = false;
public int currentLevel = 0;
private int maxLevel = 3;
Vector3 startPos = new Vector3(0, 0, -4);
PantoHandle handle;
// level configs
// TODO: load from JSON
Dictionary<int, List<(Vector3, int)>> forceFieldPositions = new Dictionary<int, List<(Vector3, int)>>{
{
0, new List<(Vector3, int)>
{
{ (new Vector3(2.8f, 0, -5.6f),5) },
{ (new Vector3(-0.5f, 0, -9.2f),5) },
{ (new Vector3(-2.9f, 0, -15.0f),3) },
{ (new Vector3(-5.9f, 0, -10.0f),5) },
{ (new Vector3(3.4f, 0, -13.0f),5) },
}
},
{
1, new List<(Vector3, int)>
{
{ (new Vector3(2.8f, 0, -5.6f),5) },
{ (new Vector3(-0.5f, 0, -9.2f),5) },
{ (new Vector3(-2.9f, 0, -15.0f),3) },
{ (new Vector3(-5.9f, 0, -10.0f),5) },
{ (new Vector3(3.4f, 0, -13.0f),5) },
{ (new Vector3(0.9f, 0, -7.0f),3) },
{ (new Vector3(2.9f, 0, -9.0f),3) },
{ (new Vector3(-5.2f, 0, -13.0f),4) },
{ (new Vector3(6.4f, 0, -7.2f),3) },
}
},
{
2, new List<(Vector3, int)>
{
{ (new Vector3(2.8f, 0, -5.6f),5) },
{ (new Vector3(-0.5f, 0, -9.2f),5) },
{ (new Vector3(-2.9f, 0, -15.0f),3) },
{ (new Vector3(-5.9f, 0, -10.0f),5) },
{ (new Vector3(3.4f, 0, -13.0f),5) },
{ (new Vector3(0.9f, 0, -14.0f),3) },
{ (new Vector3(2.9f, 0, -9.0f),3) },
{ (new Vector3(-5.2f, 0, -13.0f),4) },
{ (new Vector3(6.4f, 0, -7.2f),3) },
{ (new Vector3(-0.4f, 0, -13.2f),3) },
{ (new Vector3(-6.4f, 0, -4.2f),3) },
{ (new Vector3(7.4f, 0, -7.2f),3) },
}
},
{
3, new List<(Vector3, int)>
{
{ (new Vector3(2.8f, 0, -5.6f),5) },
{ (new Vector3(-0.5f, 0, -9.2f),5) },
{ (new Vector3(-2.9f, 0, -15.0f),3) },
{ (new Vector3(-5.9f, 0, -10.0f),5) },
{ (new Vector3(3.4f, 0, -13.0f),5) },
{ (new Vector3(0.9f, 0, -14.0f),3) },
{ (new Vector3(2.9f, 0, -9.0f),3) },
{ (new Vector3(-5.2f, 0, -13.0f),4) },
{ (new Vector3(6.4f, 0, -7.2f),3) },
{ (new Vector3(-0.4f, 0, -13.2f),3) },
{ (new Vector3(-6.4f, 0, -4.2f),3) },
{ (new Vector3(7.4f, 0, -7.2f),3) },
{ (new Vector3(3.4f, 0, -14.2f),2) },
{ (new Vector3(-2.4f, 0, -13.7f),2) },
{ (new Vector3(5.4f, 0, -12.2f),2) },
}
},
};
async void Start()
{
// get forcefields
forceFields = GameObject.FindGameObjectsWithTag("ForceField");
forceFieldPrefab.SetActive(false);
upper = GameObject.FindGameObjectWithTag("MeHandle");
lower = GameObject.FindGameObjectWithTag("ItHandle");
isRunning = true;
speech = new SpeechOut();
Debug.Log("Starting game");
await speech.Speak("Reach the bottom without getting pulled into the forcefields.");
StartLevel();
}
private void SpawnForceFields()
{
List<(Vector3, int)> currentForceFields = forceFieldPositions[currentLevel];
List<GameObject> ffs = new List<GameObject>();
for (int i = 0; i < currentForceFields.Count; i++)
{
GameObject ff = Instantiate(forceFieldPrefab);
ff.transform.position = currentForceFields[i].Item1;
int scale = currentForceFields[i].Item2;
ff.transform.localScale = new Vector3(scale, scale, scale);
ff.SetActive(true);
ffs.Add(ff);
}
forceFields = ffs.ToArray();
}
private void DisableForceFields()
{
foreach (GameObject ff in forceFields)
{
Destroy(ff);
}
}
async private void StartLevel()
{
isRunning = false;
DisableForceFields();
await Task.Delay(100);
handle = GameObject.Find("Panto").GetComponent<UpperHandle>();
await handle.MoveToPosition(startPos, 1f, true);
await speech.Speak("Level: " + currentLevel, 1);
SpawnForceFields();
isRunning = true;
}
async public void LevelCompleted()
{
if (isRunning)
{
isRunning = false;
if (currentLevel == maxLevel)
{
await speech.Speak("Congratulations: You've finished all levels", 1);
return;
}
await speech.Speak("Level " + currentLevel + " completed", 1);
currentLevel++;
StartLevel();
}
}
async void RestartLevel()
{
isRunning = false;
await speech.Speak("You lost. Restarting Level");
StartLevel();
}
void Update()
{
// if player position distance to center of any force field is too short -> lose
foreach (GameObject ff in forceFields)
{
if (isRunning && (Vector3.Distance(ff.transform.position, upper.transform.position) < 0.4 || Vector3.Distance(ff.transform.position, lower.transform.position) < 0.4))
{
RestartLevel();
}
}
}
}
| 34.302326 | 178 | 0.479153 | [
"Apache-2.0"
] | Max784/BIS_BeatSaber | Assets/unity-dualpanto-framework/Assets/ExampleScripts/ForcefieldLabyrinth/LabyrinthGameManager.cs | 5,902 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
// Colors: provides color properties //
public static class Colors
{
#region provided by Unity's Color class
public static Color cyan => Color.cyan;
public static Color green => Color.green;
public static Color red => Color.red;
public static Color black => Color.black;
public static Color yellow => Color.yellow;
public static Color blue => Color.blue;
public static Color magenta => Color.magenta;
public static Color gray => Color.gray;
public static Color white => Color.white;
public static Color clear => Color.clear;
public static Color grey => Color.grey;
#endregion provided by Unity's Color class
#region provided here
public static Color purple => new Color(143f, 0f, 254f);
#endregion provided here
} | 32.44 | 57 | 0.754624 | [
"MIT"
] | MartianDust/MartianDust-Project | Assets/Plugins/Mars Motion Toolkit/Utilities/Explicit/Colors.cs | 813 | C# |
#region license
// Copyright (c) HatTrick Labs, LLC. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// The latest version of this file can be found at https://github.com/HatTrickLabs/db-ex
#endregion
using System;
using System.Threading;
using System.Threading.Tasks;
namespace HatTrick.DbEx.Sql.Pipeline
{
public class BeforeSelectPipelineEventActions : PipelineEventActions<Func<BeforeSelectPipelineExecutionContext, CancellationToken, Task>, Action<BeforeSelectPipelineExecutionContext>, BeforeSelectPipelineExecutionContext>
{
protected override Func<BeforeSelectPipelineExecutionContext, CancellationToken, Task> MakeAsync(Action<BeforeSelectPipelineExecutionContext> action)
=> new Func<BeforeSelectPipelineExecutionContext, CancellationToken, Task>((ctx, ct) =>
{
action.Invoke(ctx);
return Task.FromResult<object>(null);
});
protected override Action<BeforeSelectPipelineExecutionContext> MakeSync(Func<BeforeSelectPipelineExecutionContext, CancellationToken, Task> action)
=> new Action<BeforeSelectPipelineExecutionContext>(ctx => action.Invoke(ctx, CancellationToken.None).GetAwaiter().GetResult());
}
} | 47.486486 | 225 | 0.753557 | [
"Apache-2.0"
] | HatTrickLabs/dbExpression | src/HatTrick.DbEx.Sql/Pipeline/_PipelineEvents/BeforeSelectPipelineEventActions.cs | 1,759 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System;
using System.Collections.Generic;
using Aliyun.Acs.Core.Transform;
using Aliyun.Acs.CCC.Model.V20170705;
namespace Aliyun.Acs.CCC.Transform.V20170705
{
public class CreateInstanceResponseUnmarshaller
{
public static CreateInstanceResponse Unmarshall(UnmarshallerContext context)
{
CreateInstanceResponse createInstanceResponse = new CreateInstanceResponse();
createInstanceResponse.HttpResponse = context.HttpResponse;
createInstanceResponse.RequestId = context.StringValue("CreateInstance.RequestId");
createInstanceResponse.Success = context.BooleanValue("CreateInstance.Success");
createInstanceResponse.Code = context.StringValue("CreateInstance.Code");
createInstanceResponse.Message = context.StringValue("CreateInstance.Message");
createInstanceResponse.HttpStatusCode = context.IntegerValue("CreateInstance.HttpStatusCode");
CreateInstanceResponse.CreateInstance_Instance instance = new CreateInstanceResponse.CreateInstance_Instance();
instance.InstanceId = context.StringValue("CreateInstance.Instance.InstanceId");
instance.InstanceName = context.StringValue("CreateInstance.Instance.InstanceName");
instance.InstanceDescription = context.StringValue("CreateInstance.Instance.InstanceDescription");
instance.DomainName = context.StringValue("CreateInstance.Instance.DomainName");
instance.ConsoleUrl = context.StringValue("CreateInstance.Instance.ConsoleUrl");
instance.StorageBucket = context.StringValue("CreateInstance.Instance.StorageBucket");
instance.StorageMaxDays = context.IntegerValue("CreateInstance.Instance.StorageMaxDays");
instance.StorageMaxSize = context.IntegerValue("CreateInstance.Instance.StorageMaxSize");
instance.MaxOnlineAgents = context.IntegerValue("CreateInstance.Instance.MaxOnlineAgents");
instance.TenantId = context.StringValue("CreateInstance.Instance.TenantId");
instance.Status = context.StringValue("CreateInstance.Instance.Status");
instance.DirectoryId = context.StringValue("CreateInstance.Instance.DirectoryId");
instance.CreatedTime = context.LongValue("CreateInstance.Instance.CreatedTime");
instance.Owner = context.StringValue("CreateInstance.Instance.Owner");
List<string> instance_successPhoneNumbers = new List<string>();
for (int i = 0; i < context.Length("CreateInstance.Instance.SuccessPhoneNumbers.Length"); i++) {
instance_successPhoneNumbers.Add(context.StringValue("CreateInstance.Instance.SuccessPhoneNumbers["+ i +"]"));
}
instance.SuccessPhoneNumbers = instance_successPhoneNumbers;
List<string> instance_failPhoneNumbers = new List<string>();
for (int i = 0; i < context.Length("CreateInstance.Instance.FailPhoneNumbers.Length"); i++) {
instance_failPhoneNumbers.Add(context.StringValue("CreateInstance.Instance.FailPhoneNumbers["+ i +"]"));
}
instance.FailPhoneNumbers = instance_failPhoneNumbers;
List<string> instance_successLoginNames = new List<string>();
for (int i = 0; i < context.Length("CreateInstance.Instance.SuccessLoginNames.Length"); i++) {
instance_successLoginNames.Add(context.StringValue("CreateInstance.Instance.SuccessLoginNames["+ i +"]"));
}
instance.SuccessLoginNames = instance_successLoginNames;
List<string> instance_failLoginNames = new List<string>();
for (int i = 0; i < context.Length("CreateInstance.Instance.FailLoginNames.Length"); i++) {
instance_failLoginNames.Add(context.StringValue("CreateInstance.Instance.FailLoginNames["+ i +"]"));
}
instance.FailLoginNames = instance_failLoginNames;
List<CreateInstanceResponse.CreateInstance_Instance.CreateInstance_User> instance_admin = new List<CreateInstanceResponse.CreateInstance_Instance.CreateInstance_User>();
for (int i = 0; i < context.Length("CreateInstance.Instance.Admin.Length"); i++) {
CreateInstanceResponse.CreateInstance_Instance.CreateInstance_User user = new CreateInstanceResponse.CreateInstance_Instance.CreateInstance_User();
user.UserId = context.StringValue("CreateInstance.Instance.Admin["+ i +"].UserId");
user.RamId = context.StringValue("CreateInstance.Instance.Admin["+ i +"].RamId");
user.InstanceId = context.StringValue("CreateInstance.Instance.Admin["+ i +"].InstanceId");
CreateInstanceResponse.CreateInstance_Instance.CreateInstance_User.CreateInstance_Detail detail = new CreateInstanceResponse.CreateInstance_Instance.CreateInstance_User.CreateInstance_Detail();
detail.LoginName = context.StringValue("CreateInstance.Instance.Admin["+ i +"].Detail.LoginName");
detail.DisplayName = context.StringValue("CreateInstance.Instance.Admin["+ i +"].Detail.DisplayName");
detail.Phone = context.StringValue("CreateInstance.Instance.Admin["+ i +"].Detail.Phone");
detail.Email = context.StringValue("CreateInstance.Instance.Admin["+ i +"].Detail.Email");
detail.Department = context.StringValue("CreateInstance.Instance.Admin["+ i +"].Detail.Department");
user.Detail = detail;
instance_admin.Add(user);
}
instance.Admin = instance_admin;
List<CreateInstanceResponse.CreateInstance_Instance.CreateInstance_PhoneNumber> instance_phoneNumbers = new List<CreateInstanceResponse.CreateInstance_Instance.CreateInstance_PhoneNumber>();
for (int i = 0; i < context.Length("CreateInstance.Instance.PhoneNumbers.Length"); i++) {
CreateInstanceResponse.CreateInstance_Instance.CreateInstance_PhoneNumber phoneNumber = new CreateInstanceResponse.CreateInstance_Instance.CreateInstance_PhoneNumber();
phoneNumber.PhoneNumberId = context.StringValue("CreateInstance.Instance.PhoneNumbers["+ i +"].PhoneNumberId");
phoneNumber.InstanceId = context.StringValue("CreateInstance.Instance.PhoneNumbers["+ i +"].InstanceId");
phoneNumber.Number = context.StringValue("CreateInstance.Instance.PhoneNumbers["+ i +"].Number");
phoneNumber.PhoneNumberDescription = context.StringValue("CreateInstance.Instance.PhoneNumbers["+ i +"].PhoneNumberDescription");
phoneNumber.TestOnly = context.BooleanValue("CreateInstance.Instance.PhoneNumbers["+ i +"].TestOnly");
phoneNumber.RemainingTime = context.IntegerValue("CreateInstance.Instance.PhoneNumbers["+ i +"].RemainingTime");
phoneNumber.AllowOutbound = context.BooleanValue("CreateInstance.Instance.PhoneNumbers["+ i +"].AllowOutbound");
phoneNumber.Usage = context.StringValue("CreateInstance.Instance.PhoneNumbers["+ i +"].Usage");
phoneNumber.Trunks = context.IntegerValue("CreateInstance.Instance.PhoneNumbers["+ i +"].Trunks");
instance_phoneNumbers.Add(phoneNumber);
}
instance.PhoneNumbers = instance_phoneNumbers;
createInstanceResponse.Instance = instance;
return createInstanceResponse;
}
}
}
| 63.024793 | 198 | 0.772227 | [
"Apache-2.0"
] | bbs168/aliyun-openapi-net-sdk | aliyun-net-sdk-ccc/CCC/Transform/V20170705/CreateInstanceResponseUnmarshaller.cs | 7,626 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DAL;
namespace BOL
{
public class UserBol
{
//Instanciamos nuestra clase UserDal para poder utilizar sus miembros
private UserDal _userDal = new UserDal();
//
//El uso de la clase StringBuilder nos ayudara a devolver los mensajes de las validaciones
public readonly StringBuilder stringBuilder = new StringBuilder();
//
//Creamos nuestro método para Insertar un nuevo usuario, observe como este método tampoco valida los el contenido
//de las propiedades, sino que manda a llamar a una Función que tiene como tarea única hacer esta validación
//
public void Registrar(EUser user)
{
if (ValidarUsuario(user))
{
if (_userDal.GetByUser(user.User)==null)
_userDal.Insert(user);
else
_userDal.Update(user);
}
}
public List<EUser> Todos()
{
return _userDal.GetAll();
}
public EUser TraerPorId(int idUser)
{
stringBuilder.Clear();
if (idUser == 0) stringBuilder.Append("Por favor proporcione un valor de Id valido");
if (stringBuilder.Length == 0)
{
return _userDal.GetById(idUser);
}
return null;
}
public void Eliminar(int idProduct)
{
stringBuilder.Clear();
if (idProduct == 0) stringBuilder.Append("Por favor proporcione un valor de Id valido");
if (stringBuilder.Length == 0)
{
_userDal.Delete(idProduct);
}
}
public bool ValidarUsuario(EUser user)
{
stringBuilder.Clear();
if (string.IsNullOrEmpty(user.User)) stringBuilder.Append("El campo Usuario es obligatorio");
if (string.IsNullOrEmpty(user.Password)) stringBuilder.Append(Environment.NewLine + "El campo Contraseña es obligatorio");
return stringBuilder.Length == 0;
}
public bool LoginUsuario(String name, String password)
{
bool bLogin = false;
EUser user =_userDal.GetByUser(name);
if (user== null)
{
bLogin = false;
}
else
{
if (user.Password.Equals(password))
{
bLogin = true;
}
}
return bLogin;
}
}
}
| 29.945652 | 135 | 0.523775 | [
"MIT",
"Unlicense"
] | Bengis/remoteanywhere | BOL/UserBol.cs | 2,763 | C# |
using System;
using System.Windows;
using Waves.Core.Services.Interfaces;
using Waves.UI.WPF.Controls.Drawing.Behavior;
using Microsoft.Xaml.Behaviors;
using SkiaSharp.Views.Desktop;
using SkiaSharp.Views.WPF;
namespace Waves.UI.WPF.Drawing.Engine.Skia.Behavior
{
/// <summary>
/// Paint surface command behavior.
/// </summary>
public class SkiaPaintBehavior : PaintBehavior<SKElement>
{
/// <inheritdoc />
public SkiaPaintBehavior(IInputService inputService) : base(inputService)
{
}
/// <inheritdoc />
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.PaintSurface += OnPaintSurface;
}
/// <inheritdoc />
protected override void OnDetaching()
{
base.OnDetaching();
AssociatedObject.PaintSurface -= OnPaintSurface;
}
/// <summary>
/// Actions when paint requested.
/// </summary>
/// <param name="sender">Sender.</param>
/// <param name="e">Arguments.</param>
private void OnPaintSurface(object sender, SKPaintSurfaceEventArgs e)
{
DataContext?.Draw(e.Surface);
}
}
} | 26.659574 | 81 | 0.60016 | [
"MIT"
] | ambertape/waves.ui.wpf | sources/Waves.UI.WPF.Drawing.Engine.Skia/Behavior/SkiaPaintBehavior.cs | 1,255 | C# |
using JetBrains.Annotations;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
namespace DragonSpark.Application.Hosting.Server.Environment.Development;
public sealed class ApplicationConfiguration : IApplicationConfiguration
{
[UsedImplicitly]
public static ApplicationConfiguration Default { get; } = new ApplicationConfiguration();
ApplicationConfiguration() {}
public void Execute(IApplicationBuilder parameter)
{
var service = parameter.ApplicationServices.GetRequiredService<IHostEnvironment>();
if (service.IsDevelopment())
{
parameter.UseDeveloperExceptionPage();
}
else
{
throw new
InvalidOperationException("A call was made into an assembly component designed for development purposes, but IApplicationBuilder.IsDevelopment states that it is not.");
}
}
} | 30.482759 | 172 | 0.804299 | [
"MIT"
] | DragonSpark/Framework | DragonSpark.Application.Hosting.Server.Environment.Development/ApplicationConfiguration.cs | 886 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Pty.Net
{
using System;
/// <summary>
/// Event arguments that encapsulate data about the pty process exit.
/// </summary>
public class PtyExitedEventArgs : EventArgs
{
/// <summary>
/// Initializes a new instance of the <see cref="PtyExitedEventArgs"/> class.
/// </summary>
/// <param name="exitCode">Exit code of the pty process.</param>
internal PtyExitedEventArgs(int exitCode)
{
this.ExitCode = exitCode;
}
/// <summary>
/// Gets or sets the exit code of the pty process.
/// </summary>
public int ExitCode { get; set; }
}
}
| 29.857143 | 101 | 0.607656 | [
"MIT"
] | MypowerHD/vs-pty.net | src/Pty.Net/PtyExitedEventArgs.cs | 838 | C# |
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Situator.Data;
using Situator.Models;
namespace Situator
{
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
services.AddMvc().AddJsonOptions(options =>
{
options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
});
services.AddDbContext<SituatorContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("SituatorContext")));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, SituatorContext context)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseFileServer();
using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
serviceScope.ServiceProvider.GetService<SituatorContext>().Database.EnsureDeleted();
serviceScope.ServiceProvider.GetService<SituatorContext>().Database.Migrate();
serviceScope.ServiceProvider.GetService<SituatorContext>().EnsureSeedData();
}
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
} | 36.824324 | 134 | 0.622752 | [
"MIT"
] | dominikfoldi/Situator_HackTM2017 | Situator/Startup.cs | 2,727 | C# |
using System;
using System.Collections.Generic;
using System.Reactive.Linq;
using System.Reactive.Threading.Tasks;
using MS.Core;
namespace System.Reflection
{
public static class __TargetParameterCountException
{
}
} | 19.166667 | 55 | 0.782609 | [
"MIT"
] | RixianOpenTech/RxWrappers | Source/Wrappers/mscorlib/System.Reflection.TargetParameterCountException.cs | 230 | C# |
using System.Linq;
using System.Runtime.InteropServices.ComTypes;
using RendleLabs.Diagnostics;
using Xunit;
namespace SplitWatch.UnitTests
{
public class SplitTests
{
[Fact]
public void DoesChildren()
{
var a = new SplitTimer("a", false, "", "", 0);
var b = a.Split("b");
var c = a.Split("c");
b.Dispose();
c.Dispose();
Assert.Equal(2, a.Children().Count());
}
}
}
| 22.521739 | 59 | 0.492278 | [
"MIT"
] | RendleLabs/SplitWatch | test/SplitWatch.UnitTests/SplitTests.cs | 518 | C# |
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.Management.RecoveryServices.SiteRecovery.Models
{
using Newtonsoft.Json;
using System.Linq;
/// <summary>
/// A2A protected managed disk details.
/// </summary>
public partial class A2AProtectedManagedDiskDetails
{
/// <summary>
/// Initializes a new instance of the A2AProtectedManagedDiskDetails
/// class.
/// </summary>
public A2AProtectedManagedDiskDetails()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the A2AProtectedManagedDiskDetails
/// class.
/// </summary>
/// <param name="diskId">The managed disk Arm id.</param>
/// <param name="recoveryResourceGroupId">The recovery disk resource
/// group Arm Id.</param>
/// <param name="recoveryTargetDiskId">Recovery target disk Arm
/// Id.</param>
/// <param name="recoveryReplicaDiskId">Recovery replica disk Arm
/// Id.</param>
/// <param name="recoveryReplicaDiskAccountType">The replica disk type.
/// Its an optional value and will be same as source disk type if not
/// user provided.</param>
/// <param name="recoveryTargetDiskAccountType">The target disk type
/// after failover. Its an optional value and will be same as source
/// disk type if not user provided.</param>
/// <param name="diskName">The disk name.</param>
/// <param name="diskCapacityInBytes">The disk capacity in
/// bytes.</param>
/// <param name="primaryStagingAzureStorageAccountId">The primary
/// staging storage account.</param>
/// <param name="diskType">The type of disk.</param>
/// <param name="resyncRequired">A value indicating whether resync is
/// required for this disk.</param>
/// <param name="monitoringPercentageCompletion">The percentage of the
/// monitoring job. The type of the monitoring job is defined by
/// MonitoringJobType property.</param>
/// <param name="monitoringJobType">The type of the monitoring job. The
/// progress is contained in MonitoringPercentageCompletion
/// property.</param>
/// <param name="dataPendingInStagingStorageAccountInMB">The data
/// pending for replication in MB at staging account.</param>
/// <param name="dataPendingAtSourceAgentInMB">The data pending at
/// source virtual machine in MB.</param>
/// <param name="isDiskEncrypted">A value indicating whether vm has
/// encrypted os disk or not.</param>
/// <param name="secretIdentifier">The secret URL / identifier
/// (BEK).</param>
/// <param name="dekKeyVaultArmId">The KeyVault resource id for secret
/// (BEK).</param>
/// <param name="isDiskKeyEncrypted">A value indicating whether disk
/// key got encrypted or not.</param>
/// <param name="keyIdentifier">The key URL / identifier (KEK).</param>
/// <param name="kekKeyVaultArmId">The KeyVault resource id for key
/// (KEK).</param>
public A2AProtectedManagedDiskDetails(string diskId = default(string), string recoveryResourceGroupId = default(string), string recoveryTargetDiskId = default(string), string recoveryReplicaDiskId = default(string), string recoveryReplicaDiskAccountType = default(string), string recoveryTargetDiskAccountType = default(string), string diskName = default(string), long? diskCapacityInBytes = default(long?), string primaryStagingAzureStorageAccountId = default(string), string diskType = default(string), bool? resyncRequired = default(bool?), int? monitoringPercentageCompletion = default(int?), string monitoringJobType = default(string), double? dataPendingInStagingStorageAccountInMB = default(double?), double? dataPendingAtSourceAgentInMB = default(double?), bool? isDiskEncrypted = default(bool?), string secretIdentifier = default(string), string dekKeyVaultArmId = default(string), bool? isDiskKeyEncrypted = default(bool?), string keyIdentifier = default(string), string kekKeyVaultArmId = default(string))
{
DiskId = diskId;
RecoveryResourceGroupId = recoveryResourceGroupId;
RecoveryTargetDiskId = recoveryTargetDiskId;
RecoveryReplicaDiskId = recoveryReplicaDiskId;
RecoveryReplicaDiskAccountType = recoveryReplicaDiskAccountType;
RecoveryTargetDiskAccountType = recoveryTargetDiskAccountType;
DiskName = diskName;
DiskCapacityInBytes = diskCapacityInBytes;
PrimaryStagingAzureStorageAccountId = primaryStagingAzureStorageAccountId;
DiskType = diskType;
ResyncRequired = resyncRequired;
MonitoringPercentageCompletion = monitoringPercentageCompletion;
MonitoringJobType = monitoringJobType;
DataPendingInStagingStorageAccountInMB = dataPendingInStagingStorageAccountInMB;
DataPendingAtSourceAgentInMB = dataPendingAtSourceAgentInMB;
IsDiskEncrypted = isDiskEncrypted;
SecretIdentifier = secretIdentifier;
DekKeyVaultArmId = dekKeyVaultArmId;
IsDiskKeyEncrypted = isDiskKeyEncrypted;
KeyIdentifier = keyIdentifier;
KekKeyVaultArmId = kekKeyVaultArmId;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets the managed disk Arm id.
/// </summary>
[JsonProperty(PropertyName = "diskId")]
public string DiskId { get; set; }
/// <summary>
/// Gets or sets the recovery disk resource group Arm Id.
/// </summary>
[JsonProperty(PropertyName = "recoveryResourceGroupId")]
public string RecoveryResourceGroupId { get; set; }
/// <summary>
/// Gets or sets recovery target disk Arm Id.
/// </summary>
[JsonProperty(PropertyName = "recoveryTargetDiskId")]
public string RecoveryTargetDiskId { get; set; }
/// <summary>
/// Gets or sets recovery replica disk Arm Id.
/// </summary>
[JsonProperty(PropertyName = "recoveryReplicaDiskId")]
public string RecoveryReplicaDiskId { get; set; }
/// <summary>
/// Gets or sets the replica disk type. Its an optional value and will
/// be same as source disk type if not user provided.
/// </summary>
[JsonProperty(PropertyName = "recoveryReplicaDiskAccountType")]
public string RecoveryReplicaDiskAccountType { get; set; }
/// <summary>
/// Gets or sets the target disk type after failover. Its an optional
/// value and will be same as source disk type if not user provided.
/// </summary>
[JsonProperty(PropertyName = "recoveryTargetDiskAccountType")]
public string RecoveryTargetDiskAccountType { get; set; }
/// <summary>
/// Gets or sets the disk name.
/// </summary>
[JsonProperty(PropertyName = "diskName")]
public string DiskName { get; set; }
/// <summary>
/// Gets or sets the disk capacity in bytes.
/// </summary>
[JsonProperty(PropertyName = "diskCapacityInBytes")]
public long? DiskCapacityInBytes { get; set; }
/// <summary>
/// Gets or sets the primary staging storage account.
/// </summary>
[JsonProperty(PropertyName = "primaryStagingAzureStorageAccountId")]
public string PrimaryStagingAzureStorageAccountId { get; set; }
/// <summary>
/// Gets or sets the type of disk.
/// </summary>
[JsonProperty(PropertyName = "diskType")]
public string DiskType { get; set; }
/// <summary>
/// Gets or sets a value indicating whether resync is required for this
/// disk.
/// </summary>
[JsonProperty(PropertyName = "resyncRequired")]
public bool? ResyncRequired { get; set; }
/// <summary>
/// Gets or sets the percentage of the monitoring job. The type of the
/// monitoring job is defined by MonitoringJobType property.
/// </summary>
[JsonProperty(PropertyName = "monitoringPercentageCompletion")]
public int? MonitoringPercentageCompletion { get; set; }
/// <summary>
/// Gets or sets the type of the monitoring job. The progress is
/// contained in MonitoringPercentageCompletion property.
/// </summary>
[JsonProperty(PropertyName = "monitoringJobType")]
public string MonitoringJobType { get; set; }
/// <summary>
/// Gets or sets the data pending for replication in MB at staging
/// account.
/// </summary>
[JsonProperty(PropertyName = "dataPendingInStagingStorageAccountInMB")]
public double? DataPendingInStagingStorageAccountInMB { get; set; }
/// <summary>
/// Gets or sets the data pending at source virtual machine in MB.
/// </summary>
[JsonProperty(PropertyName = "dataPendingAtSourceAgentInMB")]
public double? DataPendingAtSourceAgentInMB { get; set; }
/// <summary>
/// Gets or sets a value indicating whether vm has encrypted os disk or
/// not.
/// </summary>
[JsonProperty(PropertyName = "isDiskEncrypted")]
public bool? IsDiskEncrypted { get; set; }
/// <summary>
/// Gets or sets the secret URL / identifier (BEK).
/// </summary>
[JsonProperty(PropertyName = "secretIdentifier")]
public string SecretIdentifier { get; set; }
/// <summary>
/// Gets or sets the KeyVault resource id for secret (BEK).
/// </summary>
[JsonProperty(PropertyName = "dekKeyVaultArmId")]
public string DekKeyVaultArmId { get; set; }
/// <summary>
/// Gets or sets a value indicating whether disk key got encrypted or
/// not.
/// </summary>
[JsonProperty(PropertyName = "isDiskKeyEncrypted")]
public bool? IsDiskKeyEncrypted { get; set; }
/// <summary>
/// Gets or sets the key URL / identifier (KEK).
/// </summary>
[JsonProperty(PropertyName = "keyIdentifier")]
public string KeyIdentifier { get; set; }
/// <summary>
/// Gets or sets the KeyVault resource id for key (KEK).
/// </summary>
[JsonProperty(PropertyName = "kekKeyVaultArmId")]
public string KekKeyVaultArmId { get; set; }
}
}
| 45.802469 | 1,024 | 0.639623 | [
"MIT"
] | Am018/azure-sdk-for-net | src/SDKs/RecoveryServices.SiteRecovery/Management.RecoveryServices.SiteRecovery/Generated/Models/A2AProtectedManagedDiskDetails.cs | 11,130 | C# |
#region Copyright
//
<<<<<<< HEAD
<<<<<<< HEAD
=======
=======
>>>>>>> update form orginal repo
// DotNetNuke® - https://www.dnnsoftware.com
// Copyright (c) 2002-2018
// by DotNetNuke Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#endregion
<<<<<<< HEAD
>>>>>>> Merges latest changes from release/9.4.x into development (#3178)
=======
>>>>>>> update form orginal repo
using System;
namespace Dnn.PersonaBar.Library
{
public static class Constants
{
public const string LocalResourcesFile = "~/DesktopModules/admin/Dnn.PersonaBar/Modules/Dnn.Prompt/App_LocalResources/Prompt.resx";
public const string PersonaBarRelativePath = "~/DesktopModules/admin/Dnn.PersonaBar/";
public const string PersonaBarModulesPath = PersonaBarRelativePath + "Modules/";
public const string SharedResources = PersonaBarRelativePath + "/App_LocalResources/SharedResources.resx";
public const int AvatarWidth = 64;
public const int AvatarHeight = 64;
public static readonly TimeSpan ThreeSeconds = TimeSpan.FromSeconds(3);
public static readonly TimeSpan ThirtySeconds = TimeSpan.FromSeconds(30);
public static readonly TimeSpan OneMinute = TimeSpan.FromMinutes(1);
public static readonly TimeSpan FiveMinutes = TimeSpan.FromMinutes(5);
public static readonly TimeSpan TenMinutes = TimeSpan.FromMinutes(10);
public static readonly TimeSpan HalfHour = TimeSpan.FromMinutes(30);
public static readonly TimeSpan OneHour = TimeSpan.FromHours(1);
public static readonly TimeSpan FourHours = TimeSpan.FromHours(1);
public static readonly TimeSpan TwelveHours = TimeSpan.FromHours(12);
public static readonly TimeSpan OneDay = TimeSpan.FromDays(1);
public static readonly TimeSpan OneWeek = TimeSpan.FromDays(7);
public const string AdminsRoleName = "Administrators";
}
}
| 48.442623 | 139 | 0.730288 | [
"MIT"
] | DnnSoftwarePersian/Dnn.Platform | Dnn.AdminExperience/Library/Dnn.PersonaBar.Library/Constants.cs | 2,958 | C# |
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;
namespace BASE.Core.Avuxi.Respones
{
public class Rank
{
public int sights { get; set; }
public int beachpark { get; set; }
public int historical { get; set; }
public int eating { get; set; }
public int eating_vegetarian { get; set; }
public int shopping { get; set; }
public int shopping_luxury { get; set; }
public int nightlife { get; set; }
}
public class Venue
{
public string name { get; set; }
public int dis_min { get; set; }
public double dis_km { get; set; }
public string category { get; set; }
public int rank { get; set; }
}
public class Value
{
public string id { get; set; }
public Rank rank { get; set; }
public int signals { get; set; }
public List<Venue> venues { get; set; }
}
public class GetNearbyInfoResponse
{
public List<Value> values { get; set; }
public int state { get; set; }
public object note { get; set; }
}
}
| 26 | 50 | 0.571678 | [
"MIT"
] | jmserrano-dev/hackathon-travel.wallet | src/BASE.Core/Avuxi/Respones/GetNearbyInfoResponse.cs | 1,146 | C# |
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.WindowsAzure.Storage.Table;
using SignalFunc.Models;
namespace SignalFunc
{
public static class DetectsCheck
{
[FunctionName("DetectsCheck")]
public static async Task<HttpResponseMessage> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "DetectsCheck/{imageName}")]HttpRequestMessage req,
string imageName,
[Table("detects", " ", "{imageName}", Connection = "AzureWebJobsStorage")] DetectEntity detect,
TraceWriter log)
{
if (detect == null)
return req.CreateResponse(HttpStatusCode.OK, DetectEntity.DetectState.NotProcessed);
return req.CreateResponse(HttpStatusCode.OK, detect.Faces);
}
}
}
| 31.354839 | 122 | 0.682099 | [
"MIT"
] | msimecek/Signal-Faces | SignalFunc/SignalFunc/Functions/DetectsCheck.cs | 972 | C# |
using TickTrader.Algo.Api;
using TickTrader.Algo.Api.Indicators;
using TickTrader.Algo.Indicators.Utility;
namespace TickTrader.Algo.Indicators.Oscillators.BullsPower
{
[Indicator(Category = "Oscillators", DisplayName = "Bulls Power", Version = "1.0")]
public class BullsPower : Indicator, IBullsPower
{
private IMovingAverage _ema;
[Parameter(DefaultValue = 13, DisplayName = "Period")]
public int Period { get; set; }
[Parameter(DefaultValue = AppliedPrice.Close, DisplayName = "Apply To")]
public AppliedPrice TargetPrice { get; set; }
[Input]
public new BarSeries Bars { get; set; }
[Output(DisplayName = "Bulls", Target = OutputTargets.Window1, DefaultColor = Colors.Silver, PlotType = PlotType.Histogram)]
public DataSeries Bulls { get; set; }
public int LastPositionChanged { get { return _ema.LastPositionChanged; } }
public BullsPower() { }
public BullsPower(BarSeries bars, int period, AppliedPrice targetPrice = AppliedPrice.Close)
{
Bars = bars;
Period = period;
TargetPrice = targetPrice;
InitializeIndicator();
}
protected void InitializeIndicator()
{
_ema = Indicators.MovingAverage(AppliedPriceHelper.GetDataSeries(Bars, TargetPrice), Period, 0, MovingAverageMethod.Exponential);
}
protected override void Init()
{
InitializeIndicator();
}
protected override void Calculate(bool isNewBar)
{
var pos = LastPositionChanged;
Bulls[pos] = Bars.High[pos] - _ema.Average[pos];
}
}
}
| 31.518519 | 141 | 0.633373 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | SoftFx/TTAlgo | src/csharp/api/TickTrader.Algo.Indicators/Oscillators/BullsPower/BullsPower.cs | 1,704 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WSIP.RMS;
namespace WSIP
{
public partial class Recipe
{
public bool RecipeGet(RecipeEntity recipe)
{
throw new NotImplementedException();
}
}
}
| 18.555556 | 51 | 0.634731 | [
"MIT"
] | miracleshih/SmartIoTPlatform | WSIP/WSIP/RMS/RecipeGet.cs | 336 | C# |
using System.Security.Principal;
namespace Microsoft.Extensions.DependencyInjection
{
public static class ServiceCollectionExtensions
{
public static IServiceCollection AddIdentityServices(this IServiceCollection services)
{
//Temporary
return services.AddScoped<IPrincipal>(sp =>
{
var identity = new GenericIdentity("unknown");
return new GenericPrincipal(identity, new string[] { });
});
}
}
}
| 27.157895 | 94 | 0.620155 | [
"MIT"
] | sweepator/next | src/abstractions/Next.Abstractions.Security/Extensions/ServiceCollectionExtensions.cs | 518 | C# |
using System;
using System.Collections.Generic;
namespace Microsoft.ML.Samples.Dynamic
{
public static class FastTreeRegression
{
// This example requires installation of additional nuget package <a href="https://www.nuget.org/packages/Microsoft.ML.FastTree/">Microsoft.ML.FastTree</a>.
public static void Example()
{
// Create a new ML context, for ML.NET operations. It can be used for exception tracking and logging,
// as well as the source of randomness.
var ml = new MLContext();
// Get a small dataset as an IEnumerable and convert it to an IDataView.
var data = SamplesUtils.DatasetUtils.GetInfertData();
var trainData = ml.Data.LoadFromEnumerable(data);
// Preview of the data.
//
// Age Case Education Induced Parity PooledStratum RowNum ...
// 26 1 0-5yrs 1 6 3 1 ...
// 42 1 0-5yrs 1 1 1 2 ...
// 39 1 0-5yrs 2 6 4 3 ...
// 34 1 0-5yrs 2 4 2 4 ...
// 35 1 6-11yrs 1 3 32 5 ...
// A pipeline for concatenating the Parity and Induced columns together in the Features column.
// We will train a FastTreeRegression model with 1 tree on these two columns to predict Age.
string outputColumnName = "Features";
var pipeline = ml.Transforms.Concatenate(outputColumnName, new[] { "Parity", "Induced" })
.Append(ml.Regression.Trainers.FastTree(labelColumnName: "Age", featureColumnName: outputColumnName, numberOfTrees: 1, numberOfLeaves: 2, minimumExampleCountPerLeaf: 1));
var model = pipeline.Fit(trainData);
// Get the trained model parameters.
var modelParams = model.LastTransformer.Model;
}
}
}
| 49.804878 | 186 | 0.5524 | [
"MIT"
] | calcbench/machinelearning | docs/samples/Microsoft.ML.Samples/Dynamic/FastTreeRegression.cs | 2,044 | 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.Linq;
using System.Threading;
using System.Threading.Tasks;
using Roslyn.Test.Utilities;
using Xunit;
using LSP = Microsoft.VisualStudio.LanguageServer.Protocol;
namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.References
{
public class FindAllReferencesHandlerTests : AbstractLanguageServerProtocolTests
{
[WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/43063")]
public async Task TestFindAllReferencesAsync()
{
var markup =
@"class A
{
public int {|reference:someInt|} = 1;
void M()
{
var i = {|reference:someInt|} + 1;
}
}
class B
{
int someInt = A.{|reference:someInt|} + 1;
void M2()
{
var j = someInt + A.{|caret:|}{|reference:someInt|};
}
}";
using var workspace = CreateTestWorkspace(markup, out var locations);
var results = await RunFindAllReferencesAsync(workspace.CurrentSolution, locations["caret"].First());
AssertLocationsEqual(locations["reference"], results.Select(result => result.Location));
Assert.Equal("A", results[0].ContainingType);
Assert.Equal("B", results[2].ContainingType);
Assert.Equal("M", results[1].ContainingMember);
Assert.Equal("M2", results[3].ContainingMember);
AssertValidDefinitionProperties(results, 0);
}
[WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/43063")]
public async Task TestFindAllReferencesAsync_MultipleDocuments()
{
var markups = new string[] {
@"class A
{
public int {|reference:someInt|} = 1;
void M()
{
var i = {|reference:someInt|} + 1;
}
}",
@"class B
{
int someInt = A.{|reference:someInt|} + 1;
void M2()
{
var j = someInt + A.{|caret:|}{|reference:someInt|};
}
}"
};
using var workspace = CreateTestWorkspace(markups, out var locations);
var results = await RunFindAllReferencesAsync(workspace.CurrentSolution, locations["caret"].First());
AssertLocationsEqual(locations["reference"], results.Select(result => result.Location));
Assert.Equal("A", results[0].ContainingType);
Assert.Equal("B", results[2].ContainingType);
Assert.Equal("M", results[1].ContainingMember);
Assert.Equal("M2", results[3].ContainingMember);
AssertValidDefinitionProperties(results, 0);
}
[WpfFact]
public async Task TestFindAllReferencesAsync_InvalidLocation()
{
var markup =
@"class A
{
{|caret:|}
}";
using var workspace = CreateTestWorkspace(markup, out var locations);
var results = await RunFindAllReferencesAsync(workspace.CurrentSolution, locations["caret"].First());
Assert.Empty(results);
}
[WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/43063")]
public async Task TestFindAllReferencesMetadataDefinitionAsync()
{
var markup =
@"using System;
class A
{
void M()
{
Console.{|caret:|}{|reference:WriteLine|}(""text"");
}
}";
using var workspace = CreateTestWorkspace(markup, out var locations);
var results = await RunFindAllReferencesAsync(workspace.CurrentSolution, locations["caret"].First());
Assert.NotNull(results[0].Location.Uri);
}
private static LSP.ReferenceParams CreateReferenceParams(LSP.Location caret) =>
new LSP.ReferenceParams()
{
TextDocument = CreateTextDocumentIdentifier(caret.Uri),
Position = caret.Range.Start,
Context = new LSP.ReferenceContext(),
};
private static async Task<LSP.VSReferenceItem[]> RunFindAllReferencesAsync(Solution solution, LSP.Location caret)
{
var vsClientCapabilities = new LSP.VSClientCapabilities
{
SupportsVisualStudioExtensions = true
};
return await GetLanguageServer(solution).ExecuteRequestAsync<LSP.ReferenceParams, LSP.VSReferenceItem[]>(LSP.Methods.TextDocumentReferencesName,
CreateReferenceParams(caret), vsClientCapabilities, null, CancellationToken.None);
}
private static void AssertValidDefinitionProperties(LSP.ReferenceItem[] referenceItems, int definitionIndex)
{
var definition = referenceItems[definitionIndex];
var definitionId = definition.DefinitionId;
Assert.NotNull(definition.DefinitionText);
for (var i = 0; i < referenceItems.Length; i++)
{
if (i == definitionIndex)
{
continue;
}
Assert.Null(referenceItems[i].DefinitionText);
Assert.Equal(definitionId, referenceItems[i].DefinitionId);
Assert.NotEqual(definitionId, referenceItems[i].Id);
}
}
}
}
| 33.589744 | 156 | 0.622328 | [
"MIT"
] | 06needhamt/roslyn | src/Features/LanguageServer/ProtocolUnitTests/References/FindAllReferencesHandlerTests.cs | 5,242 | C# |
using System.Collections.Generic;
using UnityEngine;
using FairyGUI.Utils;
namespace FairyGUI
{
class GearLookValue
{
public float alpha;
public float rotation;
public bool grayed;
public bool touchable;
public GearLookValue(float alpha, float rotation, bool grayed, bool touchable)
{
this.alpha = alpha;
this.rotation = rotation;
this.grayed = grayed;
this.touchable = touchable;
}
}
/// <summary>
/// Gear is a connection between object and controller.
/// </summary>
public class GearLook : GearBase, ITweenListener
{
Dictionary<string, GearLookValue> _storage;
GearLookValue _default;
public GearLook(GObject owner)
: base(owner)
{
}
protected override void Init()
{
_default = new GearLookValue(_owner.alpha, _owner.rotation, _owner.grayed, _owner.touchable);
_storage = new Dictionary<string, GearLookValue>();
}
override protected void AddStatus(string pageId, ByteBuffer buffer)
{
GearLookValue gv;
if (pageId == null)
gv = _default;
else
{
gv = new GearLookValue(0, 0, false, false);
_storage[pageId] = gv;
}
gv.alpha = buffer.ReadFloat();
gv.rotation = buffer.ReadFloat();
gv.grayed = buffer.ReadBool();
gv.touchable = buffer.ReadBool();
}
override public void Apply()
{
GearLookValue gv;
if (!_storage.TryGetValue(_controller.selectedPageId, out gv))
gv = _default;
if (_tweenConfig != null && _tweenConfig.tween && UIPackage._constructing == 0 && !disableAllTweenEffect)
{
_owner._gearLocked = true;
_owner.grayed = gv.grayed;
_owner.touchable = gv.touchable;
_owner._gearLocked = false;
if (_tweenConfig._tweener != null)
{
if (_tweenConfig._tweener.endValue.x != gv.alpha || _tweenConfig._tweener.endValue.y != gv.rotation)
{
_tweenConfig._tweener.Kill(true);
_tweenConfig._tweener = null;
}
else
return;
}
bool a = gv.alpha != _owner.alpha;
bool b = gv.rotation != _owner.rotation;
if (a || b)
{
if (_owner.CheckGearController(0, _controller))
_tweenConfig._displayLockToken = _owner.AddDisplayLock();
_tweenConfig._tweener = GTween.To(new Vector2(_owner.alpha, _owner.rotation), new Vector2(gv.alpha, gv.rotation), _tweenConfig.duration)
.SetDelay(_tweenConfig.delay)
.SetEase(_tweenConfig.easeType, _tweenConfig.customEase)
.SetUserData((a ? 1 : 0) + (b ? 2 : 0))
.SetTarget(this)
.SetListener(this);
}
}
else
{
_owner._gearLocked = true;
_owner.alpha = gv.alpha;
_owner.rotation = gv.rotation;
_owner.grayed = gv.grayed;
_owner.touchable = gv.touchable;
_owner._gearLocked = false;
}
}
public void OnTweenStart(GTweener tweener)
{
}
public void OnTweenUpdate(GTweener tweener)
{
int flag = (int)tweener.userData;
_owner._gearLocked = true;
if ((flag & 1) != 0)
_owner.alpha = tweener.value.x;
if ((flag & 2) != 0)
{
_owner.rotation = tweener.value.y;
_owner.InvalidateBatchingState();
}
_owner._gearLocked = false;
}
public void OnTweenComplete(GTweener tweener)
{
_tweenConfig._tweener = null;
if (_tweenConfig._displayLockToken != 0)
{
_owner.ReleaseDisplayLock(_tweenConfig._displayLockToken);
_tweenConfig._displayLockToken = 0;
}
_owner.DispatchEvent("onGearStop", this);
}
override public void UpdateState()
{
GearLookValue gv;
if (!_storage.TryGetValue(_controller.selectedPageId, out gv))
_storage[_controller.selectedPageId] = new GearLookValue(_owner.alpha, _owner.rotation, _owner.grayed, _owner.touchable);
else
{
gv.alpha = _owner.alpha;
gv.rotation = _owner.rotation;
gv.grayed = _owner.grayed;
gv.touchable = _owner.touchable;
}
}
}
}
| 33.836601 | 157 | 0.493529 | [
"MIT"
] | 1901/FairyGUI-unity | Assets/Scripts/UI/Gears/GearLook.cs | 5,179 | C# |
using DAL.Models;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace DAL.Core.Interfaces
{
public interface IExamManager : IManager<Exam>
{
Task<List<Exam>> GetAllExamsAsync();
Task<List<Exam>> GetExamsForCategoryAsync(int categoryId);
Task<Exam> GetFullExam(int examId);
}
}
| 21.823529 | 66 | 0.71159 | [
"MIT"
] | michalfalat/skillPortal | src/DAL/Core/Interfaces/IExamManager.cs | 373 | C# |
using AspNetCore.Identity.Mongo.Model;
namespace Ianitor.Osp.Backend.Persistence.SystemEntities
{
[CollectionName("IdentityRoles")]
public class OspRole : MongoRole
{
}
}
| 16.454545 | 56 | 0.762431 | [
"MIT"
] | ianitor/ObjectServicePlatform | Osp/Backend/Ianitor.Osp.Backend.Persistence/SystemEntities/OspRole.cs | 181 | C# |
// Decompiled with JetBrains decompiler
// Type: Functal.FnFunction_Max_Double
// Assembly: Functal, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
// MVID: 47DC2DAE-D56F-4FC5-A0C3-CC69F2DF9A1F
// Assembly location: \\WSE\Folder Redirection\JP\Downloads\Functal-1_0_0\Functal.dll
using System;
namespace Functal
{
internal class FnFunction_Max_Double : FnFunction<double>
{
[FnArg]
protected FnObject<double> A;
[FnArg]
protected FnObject<double> B;
public override double GetValue()
{
return Math.Max(this.A.GetValue(), this.B.GetValue());
}
}
}
| 24.916667 | 85 | 0.719064 | [
"MIT"
] | jpdillingham/Functal | src/FnFunction_Max_Double.cs | 600 | C# |
using OpenBots.Core.Attributes.PropertyAttributes;
using OpenBots.Core.Command;
using OpenBots.Core.Interfaces;
using OpenBots.Core.Properties;
using OpenBots.Core.User32;
using OpenBots.Core.Utilities.CommonUtilities;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Windows.Forms;
using Tasks = System.Threading.Tasks;
namespace OpenBots.Commands.Misc
{
[Serializable]
[Category("Misc Commands")]
[Description("This command gets text from the user's clipboard.")]
public class GetClipboardTextCommand : ScriptCommand
{
[Required]
[Editable(false)]
[DisplayName("Output Clipboard Text Variable")]
[Description("Create a new variable or select a variable from the list.")]
[SampleUsage("vUserVariable")]
[Remarks("New variables/arguments may be instantiated by utilizing the Ctrl+K/Ctrl+J shortcuts.")]
[CompatibleTypes(new Type[] { typeof(string) })]
public string v_OutputUserVariableName { get; set; }
public GetClipboardTextCommand()
{
CommandName = "GetClipboardTextCommand";
SelectionName = "Get Clipboard Text";
CommandEnabled = true;
CommandIcon = Resources.command_files;
}
public async override Tasks.Task RunCommand(object sender)
{
var engine = (IAutomationEngineInstance)sender;
User32Functions.GetClipboardText().SetVariableValue(engine, v_OutputUserVariableName);
}
public override List<Control> Render(IfrmCommandEditor editor, ICommandControls commandControls)
{
base.Render(editor, commandControls);
RenderedControls.AddRange(commandControls.CreateDefaultOutputGroupFor("v_OutputUserVariableName", this, editor));
return RenderedControls;
}
public override string GetDisplayValue()
{
return base.GetDisplayValue() + $" [Store Clipboard Text in '{v_OutputUserVariableName}']";
}
}
}
| 33.887097 | 125 | 0.690148 | [
"MIT"
] | OpenBotsAI/OpenBots.Studio | OpenBots.Commands/OpenBots.Commands.Core/OpenBots.Commands.Misc/GetClipboardTextCommand.cs | 2,103 | C# |
namespace SmartHomeWWW.Server.Config
{
public record TelegramConfig
{
public string ApiKey { get; set; } = string.Empty;
public long OwnerId { get; set; }
}
}
| 20.888889 | 58 | 0.62234 | [
"MIT"
] | GreenOlvi/smart-home-www | Server/Config/TelegramConfig.cs | 190 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using HuaweiCloud.SDK.Core;
namespace HuaweiCloud.SDK.Dds.V3.Model
{
/// <summary>
/// Response Object
/// </summary>
public class ResizeInstanceVolumeResponse : SdkResponse
{
/// <summary>
/// 工作流ID。
/// </summary>
[JsonProperty("job_id", NullValueHandling = NullValueHandling.Ignore)]
public string JobId { get; set; }
/// <summary>
/// Get the string
/// </summary>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class ResizeInstanceVolumeResponse {\n");
sb.Append(" jobId: ").Append(JobId).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
public override bool Equals(object input)
{
return this.Equals(input as ResizeInstanceVolumeResponse);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
public bool Equals(ResizeInstanceVolumeResponse input)
{
if (input == null)
return false;
return
(
this.JobId == input.JobId ||
(this.JobId != null &&
this.JobId.Equals(input.JobId))
);
}
/// <summary>
/// Get hash code
/// </summary>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.JobId != null)
hashCode = hashCode * 59 + this.JobId.GetHashCode();
return hashCode;
}
}
}
}
| 26.407895 | 78 | 0.510214 | [
"Apache-2.0"
] | Huaweicloud-SDK/huaweicloud-sdk-net-v3 | Services/Dds/V3/Model/ResizeInstanceVolumeResponse.cs | 2,015 | C# |
using System.Collections.Generic;
using System.Text.Json.Serialization;
using Essensoft.Paylink.Alipay.Domain;
namespace Essensoft.Paylink.Alipay.Response
{
/// <summary>
/// AlipayCommerceCityfacilitatorVoucherBatchqueryResponse.
/// </summary>
public class AlipayCommerceCityfacilitatorVoucherBatchqueryResponse : AlipayResponse
{
/// <summary>
/// 查询到的订单信息列表
/// </summary>
[JsonPropertyName("tickets")]
public List<TicketDetailInfo> Tickets { get; set; }
}
}
| 27.842105 | 88 | 0.691871 | [
"MIT"
] | Frunck8206/payment | src/Essensoft.Paylink.Alipay/Response/AlipayCommerceCityfacilitatorVoucherBatchqueryResponse.cs | 551 | C# |
using System;
using XLogger.Configuration;
using XLogger.Configuration.MethodsConfiguration;
namespace XLogger.LogMethods {
public class ConsoleLogMethod : ILogMethod {
protected static readonly object Sync = new object();
public ConsoleLogMethodConfiguration Config { get; set; }
public ConsoleLogMethod() : this(null) {
}
public ConsoleLogMethod(ConsoleLogMethodConfiguration config) {
Config = config ?? LoggerConfiguration.GetConfiguration<ConsoleLogMethodConfiguration>() ?? new ConsoleLogMethodConfiguration();
}
protected ConsoleColor GetTextHightlighting(FormattedLogMessage formattedLog) {
if (Config.TextHighlighting == null) {
return Console.ForegroundColor;
}
if (Config.TextHighlighting.ContainsKey(formattedLog.Level)) {
return Config.TextHighlighting[formattedLog.Level];
} else {
return Config.DefaultConsoleColor;
}
}
public void Write(FormattedLogMessage formattedLog) {
ConsoleColor previousConsoleColor = Console.ForegroundColor;
Console.ForegroundColor = GetTextHightlighting(formattedLog);
Console.WriteLine(formattedLog.FormattedMessage);
Console.ForegroundColor = previousConsoleColor;
}
}
}
| 30.487179 | 131 | 0.780488 | [
"MIT"
] | JaleChaki/XLogger | Src/XLogger/LogMethods/ConsoleLogMethod.cs | 1,191 | C# |
/******************************************************************************
* Spine Runtimes License Agreement
* Last updated January 1, 2020. Replaces all prior versions.
*
* Copyright (c) 2013-2020, Esoteric Software LLC
*
* Integration of the Spine Runtimes into software or otherwise creating
* derivative works of the Spine Runtimes is permitted under the terms and
* conditions of Section 2 of the Spine Editor License Agreement:
* http://esotericsoftware.com/spine-editor-license
*
* Otherwise, it is permitted to integrate the Spine Runtimes into software
* or otherwise create derivative works of the Spine Runtimes (collectively,
* "Products"), provided that each user of the Products must obtain their own
* Spine Editor license and redistribution of the Products in any form must
* include this license and copyright notice.
*
* THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "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 ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES,
* BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) 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
* THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*****************************************************************************/
using System;
using UnityEngine;
using UnityEngine.Playables;
using UnityEngine.Timeline;
using Spine;
using Spine.Unity;
using System.Collections.Generic;
namespace Spine.Unity.Playables {
using Animation = Spine.Animation;
[Serializable]
public class SpineAnimationStateBehaviour : PlayableBehaviour {
public AnimationReferenceAsset animationReference;
public bool loop;
// Mix Properties
public bool customDuration = false;
public bool useBlendDuration = true;
[SerializeField]
#pragma warning disable 414
private bool isInitialized = false; // required to read preferences values from editor side.
#pragma warning restore 414
public float mixDuration = 0.1f;
public bool holdPrevious = false;
[Range(0, 1f)]
public float attachmentThreshold = 0.5f;
[Range(0, 1f)]
public float eventThreshold = 0.5f;
[Range(0, 1f)]
public float drawOrderThreshold = 0.5f;
}
}
| 39.426471 | 95 | 0.704961 | [
"MIT"
] | exAntares/GameJam280521 | Assets/Plugins/com.esotericsoftware.spine.timeline-3.8 2/Runtime/SpineAnimationState/SpineAnimationStateBehaviour.cs | 2,681 | C# |
// Copyright © 2017 SOFTINUX. All rights reserved.
// Licensed under the MIT License, Version 2.0. See LICENSE file in the project root for license information.
using Infrastructure.Interfaces;
namespace Infrastructure.Extensions
{
public static class TypeExtensions
{
/// <summary>
/// Return the string used for the "scope".
/// </summary>
/// <param name="extensionMetadata_"></param>
/// <returns>The scope, equal to assembly name, given by Assembly.GetName().Name</returns>
public static string GetScope(this IExtensionMetadata extensionMetadata_)
{
return extensionMetadata_.GetType().Assembly.GetName().Name;
}
}
} | 33.904762 | 109 | 0.668539 | [
"MIT"
] | YodasMyDad/Base | Infrastructure/Extensions/TypeExtensions.cs | 713 | C# |
namespace Blauhaus.TestHelpers.MockBuilders
{
public class MockBuilder<TMock> : BaseMockBuilder<MockBuilder<TMock>, TMock> where TMock : class
{
}
} | 24.285714 | 100 | 0.694118 | [
"MIT"
] | BlauhausTechnology/Blauhaus.TestHelpers | src/Blauhaus.TestHelpers/MockBuilders/MockBuilder.cs | 172 | 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.Collections.Generic;
using System.Linq;
using Mono.Cecil;
using Mono.Linker.Tests.Extensions;
using Mono.Linker.Tests.TestCases;
using Mono.Linker.Tests.TestCasesRunner;
using NUnit.Framework;
namespace Mono.Linker.Tests.Tests
{
[TestFixture]
public class TestFrameworkRulesAndConventions
{
[Test]
public void OnlyAttributeTypesInExpectations ()
{
foreach (var expectationsAssemblyPath in ExpectationAssemblies ()) {
using (var assembly = AssemblyDefinition.ReadAssembly (expectationsAssemblyPath)) {
var nonAttributeTypes = assembly.MainModule.AllDefinedTypes ().Where (t => !IsAcceptableExpectationsAssemblyType (t)).ToArray ();
Assert.That (nonAttributeTypes, Is.Empty);
}
}
}
[Test]
public void CanFindATypeForAllCsFiles ()
{
var collector = CreateCollector ();
var missing = collector.AllSourceFiles ().Where (path => {
return collector.Collect (path) == null;
})
.ToArray ();
Assert.That (missing, Is.Empty, $"Could not locate a type for the following files. Verify the type name and file name match and that the type is not excluded by a #if");
}
/// <summary>
/// Virtual to allow a derived test suite to setup the test case collector differently
/// </summary>
/// <returns></returns>
protected virtual TestCaseCollector CreateCollector ()
{
return TestDatabase.CreateCollector ();
}
/// <summary>
/// Virtual to allow creation of a derived test suite for a different expectations assembly, or multiple
/// </summary>
/// <returns></returns>
protected virtual IEnumerable<NPath> ExpectationAssemblies ()
{
yield return PathUtilities.GetTestAssemblyPath ("Mono.Linker.Tests.Cases.Expectations").ToNPath ();
}
static bool IsAcceptableExpectationsAssemblyType (TypeDefinition type)
{
if (type.Name == "<Module>")
return true;
// A static class with a const string field helper. This file is OK.
if (type.Name == "PlatformAssemblies")
return true;
// Simple types like enums are OK and needed for certain attributes
if (type.IsEnum)
return true;
// Attributes are OK because that is the purpose of the Expectations assembly, to provide attributes for annotating test cases
if (IsAttributeType (type))
return true;
// Anything else is not OK and should probably be defined in Mono.Linker.Tests.Cases and use SandboxDependency in order to be included
// with the tests that need it
return false;
}
static bool IsAttributeType (TypeDefinition type)
{
if (type.Namespace == "System" && type.Name == "Attribute")
return true;
if (type.BaseType == null)
return false;
return IsAttributeType (type.BaseType.Resolve ());
}
}
} | 31.159574 | 173 | 0.720382 | [
"MIT"
] | Youssef1313/linker | test/Mono.Linker.Tests/Tests/TestFrameworkRulesAndConventions.cs | 2,929 | C# |
using System.Collections.Generic;
using Appysights.Enums;
using Appysights.Models;
using Appysights.Services;
using Caliburn.Micro;
namespace Appysights.ViewModels
{
public class SettingsViewModel : PropertyChangedBase
{
#region Fields
private ThemeService _themeService;
private ConfigurationManager _configurationManager;
private Scheme _selectedScheme;
private Theme _selectedTheme;
private IEventAggregator _eventAggregator;
#endregion
#region Constructors
public SettingsViewModel(ThemeService themeService, ConfigurationManager configurationManager, IEventAggregator eventAggregator)
{
_themeService = themeService;
_configurationManager = configurationManager;
_selectedScheme = themeService.Scheme;
_selectedTheme = themeService.Theme;
_eventAggregator = eventAggregator;
PropertyChanged += SettingsViewModel_PropertyChanged;
}
#endregion
#region Properties
public IEnumerable<Theme> Themes => _themeService.GetThemes();
public IEnumerable<Scheme> Schemes => _themeService.GetSchemes();
public Scheme SelectedScheme
{
get
{
return _selectedScheme;
}
set
{
_selectedScheme = value;
NotifyOfPropertyChange();
}
}
public Theme SelectedTheme
{
get
{
return _selectedTheme;
}
set
{
_selectedTheme = value;
NotifyOfPropertyChange();
}
}
#endregion
#region Methods
public void EditConfigurations()
{
}
public void Random()
{
var result = _themeService.Random();
SelectedScheme = result.Scheme;
SelectedTheme = result.Theme;
}
private void SettingsViewModel_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
_themeService.Change(SelectedTheme, SelectedScheme);
}
#endregion
}
}
| 24.641304 | 136 | 0.59109 | [
"MIT"
] | C1rdec/App-Lurker | src/Appysights/ViewModels/SettingsViewModel.cs | 2,269 | C# |
using CommonUtils;
using System;
using System.Data;
namespace BusinessLogic
{
public class BASE_MOULDINFODto
{
public long? MouldCode { get; set; }
public string ProjectName { get; set; }
public string LeftPartCode { get; set; }
public string LeftPartName { get; set; }
public string RightPartCode { get; set; }
public string RightPartName { get; set; }
public enum DtoEnum
{
MouldCode
,ProjectName
,LeftPartCode
,LeftPartName
,RightPartCode
,RightPartName
}
}
}
| 23.037037 | 49 | 0.57074 | [
"MIT"
] | muzeyc/MuzeyWebForNetCore | src/MuzeyAngular.Application/BusinessLogic/Dto/BASE_MOULDINFODto.cs | 624 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Kunukn.XmlVisual.Core.Extensions;
using Kunukn.XmlVisual.Core.SvgBuilder;
namespace Kunukn.XmlVisual.Core.Entities
{
public class Element : IComparable
{
// Metadata
public int Id { get; private set; }
public int Level { get; set; } // depth in tree
public string Label { get; set; } //used by File System view
public int TotalChilds { get; set; } //used by File System view
// SVG related
public SvgData Svg { get; set; }
// Properties
public XmlType Type { get; set; }
public string Name { get; set; }
private string _value;
public string Value
{
get { return _value; }
private set
{
_value = value;
}
}
public string ValueShort { get; private set; } // shortened version for truncated display
//restrict, else very slow in browser due to js tspan loop create/delete
private const int MessageMaxLength = 800;
private const int MessageMaxAttributes = 400;
private const string Truncated = " (TRUNCATED...)";
public string Message // full info storage
{
get
{
var sb = new StringBuilder();
if (!string.IsNullOrEmpty(Name))
{
string str = SvgTool.TruncateText(Name, MessageMaxLength, Truncated);
sb.Append(string.Concat("Name=", str));
if (Attributes.Count > 0 || !string.IsNullOrEmpty(Value))
sb.Append(" ");
}
if (Attributes.Count > 0)
{
var sbAttr = new StringBuilder();
sbAttr.Append(string.Concat("Attributes: "));
foreach (var a in Attributes)
{
sbAttr.Append(string.Concat(a.ToString(), " "));
if (sbAttr.ToString().Length > MessageMaxAttributes)
{
sbAttr.Append(string.Concat(Truncated));
break;
}
}
sb.Append(sbAttr.ToString() );
}
if (!string.IsNullOrEmpty(Value))
{
string str = SvgTool.TruncateText(Value, MessageMaxLength, Truncated);
sb.Append(string.Concat("Value=", str));
}
return sb.ToString();
}
}
public ListElement Childs { get; private set; }
public List<Attribute> Attributes { get; private set; }
public Element Parent { get; private set; }
public Element(Element parent, XmlType type, int level, int elementId)
{
Id = elementId;
Childs = new ListElement();
Attributes = new List<Attribute>();
Parent = parent;
Type = type;
Level = level;
Svg = new SvgData();
Name = string.Empty;
}
public void SetValue(string s, UserConfig userConfig)
{
Value = s;
ValueShort = SvgTool.TruncateText(s, userConfig);
}
public bool IsLeaf()
{
return Childs == null || Childs.Count == 0;
}
public bool HasChildren()
{
return !IsLeaf();
}
public bool IsSingleChild()
{
return this.Parent.Childs.Count == 1;
}
public override string ToString()
{
switch (Type)
{
case XmlType.Node:
return "Node=" + Name; //XmlType.Node.GetString()
case XmlType.Cdata:
return "[CDATA]";
case XmlType.Comment:
return "[Comment]";
case XmlType.Text:
return "Text=" + Value;
case XmlType.DocType:
return "DocType=" + Value;
case XmlType.ProcessingInstruction:
return "PI=" + Value;
default:
throw new Exception("Node invalid id=" + Id);
}
}
#region IComparable Members
public int CompareTo(object obj)
{
var other = obj as Element;
if (other == null)
return -1;
return this.Id.CompareTo(other.Id);
}
public override int GetHashCode()
{
return Id;
}
public override bool Equals(Object o)
{
var other = o as Element;
if (other == null)
return false;
return this.Id == other.Id;
}
#endregion
}
}
| 32.123457 | 128 | 0.456764 | [
"BSD-3-Clause"
] | kunukn/xml-visual | src/webforms/Core/Entities/Element.cs | 5,206 | C# |
// ███╗ ██╗ ██████╗ ████████╗██╗ ██████╗███████╗
// ████╗ ██║██╔═══██╗╚══██╔══╝██║██╔════╝██╔════╝
// ██╔██╗ ██║██║ ██║ ██║ ██║██║ █████╗
// ██║╚██╗██║██║ ██║ ██║ ██║██║ ██╔══╝
// ██║ ╚████║╚██████╔╝ ██║ ██║╚██████╗███████╗
// ╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝╚══════╝
// -----------------------------------------------
//
// This file is automatically generated
// Please do not edit these files manually
// Run the following in the root of the repos:
//
// *NIX : ./build.sh codegen
// Windows : build.bat codegen
//
// -----------------------------------------------
// ReSharper disable RedundantUsingDirective
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using Elastic.Transport;
// ReSharper disable once CheckNamespace
namespace Elasticsearch.Net.Specification.CatApi
{
///<summary>Request options for Aliases <para>https://www.elastic.co/guide/en/elasticsearch/reference/master/cat-alias.html</para></summary>
public class CatAliasesRequestParameters : RequestParameters<CatAliasesRequestParameters>
{
///<summary>Whether to expand wildcard expression to concrete indices that are open, closed or both.</summary>
public ExpandWildcards? ExpandWildcards
{
get => Q<ExpandWildcards? >("expand_wildcards");
set => Q("expand_wildcards", value);
}
///<summary>a short version of the Accept header, e.g. json, yaml</summary>
public string Format
{
get => Q<string>("format");
set
{
Q("format", value);
SetAcceptHeader(value);
}
}
///<summary>Comma-separated list of column names to display</summary>
public string[] Headers
{
get => Q<string[]>("h");
set => Q("h", value);
}
///<summary>Return help information</summary>
public bool? Help
{
get => Q<bool? >("help");
set => Q("help", value);
}
///<summary>Return local information, do not retrieve the state from master node (default: false)</summary>
public bool? Local
{
get => Q<bool? >("local");
set => Q("local", value);
}
///<summary>Comma-separated list of column names or column aliases to sort by</summary>
public string[] SortByColumns
{
get => Q<string[]>("s");
set => Q("s", value);
}
///<summary>Verbose mode. Display column headers</summary>
public bool? Verbose
{
get => Q<bool? >("v");
set => Q("v", value);
}
}
///<summary>Request options for Allocation <para>https://www.elastic.co/guide/en/elasticsearch/reference/master/cat-allocation.html</para></summary>
public class CatAllocationRequestParameters : RequestParameters<CatAllocationRequestParameters>
{
///<summary>The unit in which to display byte values</summary>
public Bytes? Bytes
{
get => Q<Bytes? >("bytes");
set => Q("bytes", value);
}
///<summary>a short version of the Accept header, e.g. json, yaml</summary>
public string Format
{
get => Q<string>("format");
set
{
Q("format", value);
SetAcceptHeader(value);
}
}
///<summary>Comma-separated list of column names to display</summary>
public string[] Headers
{
get => Q<string[]>("h");
set => Q("h", value);
}
///<summary>Return help information</summary>
public bool? Help
{
get => Q<bool? >("help");
set => Q("help", value);
}
///<summary>Return local information, do not retrieve the state from master node (default: false)</summary>
public bool? Local
{
get => Q<bool? >("local");
set => Q("local", value);
}
///<summary>Explicit operation timeout for connection to master node</summary>
public TimeSpan MasterTimeout
{
get => Q<TimeSpan>("master_timeout");
set => Q("master_timeout", value);
}
///<summary>Comma-separated list of column names or column aliases to sort by</summary>
public string[] SortByColumns
{
get => Q<string[]>("s");
set => Q("s", value);
}
///<summary>Verbose mode. Display column headers</summary>
public bool? Verbose
{
get => Q<bool? >("v");
set => Q("v", value);
}
}
///<summary>Request options for Count <para>https://www.elastic.co/guide/en/elasticsearch/reference/master/cat-count.html</para></summary>
public class CatCountRequestParameters : RequestParameters<CatCountRequestParameters>
{
///<summary>a short version of the Accept header, e.g. json, yaml</summary>
public string Format
{
get => Q<string>("format");
set
{
Q("format", value);
SetAcceptHeader(value);
}
}
///<summary>Comma-separated list of column names to display</summary>
public string[] Headers
{
get => Q<string[]>("h");
set => Q("h", value);
}
///<summary>Return help information</summary>
public bool? Help
{
get => Q<bool? >("help");
set => Q("help", value);
}
///<summary>Comma-separated list of column names or column aliases to sort by</summary>
public string[] SortByColumns
{
get => Q<string[]>("s");
set => Q("s", value);
}
///<summary>Verbose mode. Display column headers</summary>
public bool? Verbose
{
get => Q<bool? >("v");
set => Q("v", value);
}
}
///<summary>Request options for Fielddata <para>https://www.elastic.co/guide/en/elasticsearch/reference/master/cat-fielddata.html</para></summary>
public class CatFielddataRequestParameters : RequestParameters<CatFielddataRequestParameters>
{
///<summary>The unit in which to display byte values</summary>
public Bytes? Bytes
{
get => Q<Bytes? >("bytes");
set => Q("bytes", value);
}
///<summary>A comma-separated list of fields to return in the output</summary>
public string[] Fields
{
get => Q<string[]>("fields");
set => Q("fields", value);
}
///<summary>a short version of the Accept header, e.g. json, yaml</summary>
public string Format
{
get => Q<string>("format");
set
{
Q("format", value);
SetAcceptHeader(value);
}
}
///<summary>Comma-separated list of column names to display</summary>
public string[] Headers
{
get => Q<string[]>("h");
set => Q("h", value);
}
///<summary>Return help information</summary>
public bool? Help
{
get => Q<bool? >("help");
set => Q("help", value);
}
///<summary>Comma-separated list of column names or column aliases to sort by</summary>
public string[] SortByColumns
{
get => Q<string[]>("s");
set => Q("s", value);
}
///<summary>Verbose mode. Display column headers</summary>
public bool? Verbose
{
get => Q<bool? >("v");
set => Q("v", value);
}
}
///<summary>Request options for Health <para>https://www.elastic.co/guide/en/elasticsearch/reference/master/cat-health.html</para></summary>
public class CatHealthRequestParameters : RequestParameters<CatHealthRequestParameters>
{
///<summary>a short version of the Accept header, e.g. json, yaml</summary>
public string Format
{
get => Q<string>("format");
set
{
Q("format", value);
SetAcceptHeader(value);
}
}
///<summary>Comma-separated list of column names to display</summary>
public string[] Headers
{
get => Q<string[]>("h");
set => Q("h", value);
}
///<summary>Return help information</summary>
public bool? Help
{
get => Q<bool? >("help");
set => Q("help", value);
}
///<summary>Set to false to disable timestamping</summary>
public bool? IncludeTimestamp
{
get => Q<bool? >("ts");
set => Q("ts", value);
}
///<summary>Comma-separated list of column names or column aliases to sort by</summary>
public string[] SortByColumns
{
get => Q<string[]>("s");
set => Q("s", value);
}
///<summary>Verbose mode. Display column headers</summary>
public bool? Verbose
{
get => Q<bool? >("v");
set => Q("v", value);
}
}
///<summary>Request options for Help <para>https://www.elastic.co/guide/en/elasticsearch/reference/master/cat.html</para></summary>
public class CatHelpRequestParameters : RequestParameters<CatHelpRequestParameters>
{
///<summary>Return help information</summary>
public bool? Help
{
get => Q<bool? >("help");
set => Q("help", value);
}
///<summary>Comma-separated list of column names or column aliases to sort by</summary>
public string[] SortByColumns
{
get => Q<string[]>("s");
set => Q("s", value);
}
}
///<summary>Request options for Indices <para>https://www.elastic.co/guide/en/elasticsearch/reference/master/cat-indices.html</para></summary>
public class CatIndicesRequestParameters : RequestParameters<CatIndicesRequestParameters>
{
///<summary>The unit in which to display byte values</summary>
public Bytes? Bytes
{
get => Q<Bytes? >("bytes");
set => Q("bytes", value);
}
///<summary>Whether to expand wildcard expression to concrete indices that are open, closed or both.</summary>
public ExpandWildcards? ExpandWildcards
{
get => Q<ExpandWildcards? >("expand_wildcards");
set => Q("expand_wildcards", value);
}
///<summary>a short version of the Accept header, e.g. json, yaml</summary>
public string Format
{
get => Q<string>("format");
set
{
Q("format", value);
SetAcceptHeader(value);
}
}
///<summary>Comma-separated list of column names to display</summary>
public string[] Headers
{
get => Q<string[]>("h");
set => Q("h", value);
}
///<summary>A health status ("green", "yellow", or "red" to filter only indices matching the specified health status</summary>
public Health? Health
{
get => Q<Health? >("health");
set => Q("health", value);
}
///<summary>Return help information</summary>
public bool? Help
{
get => Q<bool? >("help");
set => Q("help", value);
}
///<summary>If set to true segment stats will include stats for segments that are not currently loaded into memory</summary>
public bool? IncludeUnloadedSegments
{
get => Q<bool? >("include_unloaded_segments");
set => Q("include_unloaded_segments", value);
}
///<summary>Explicit operation timeout for connection to master node</summary>
public TimeSpan MasterTimeout
{
get => Q<TimeSpan>("master_timeout");
set => Q("master_timeout", value);
}
///<summary>Set to true to return stats only for primary shards</summary>
public bool? Pri
{
get => Q<bool? >("pri");
set => Q("pri", value);
}
///<summary>Comma-separated list of column names or column aliases to sort by</summary>
public string[] SortByColumns
{
get => Q<string[]>("s");
set => Q("s", value);
}
///<summary>Verbose mode. Display column headers</summary>
public bool? Verbose
{
get => Q<bool? >("v");
set => Q("v", value);
}
}
///<summary>Request options for Master <para>https://www.elastic.co/guide/en/elasticsearch/reference/master/cat-master.html</para></summary>
public class CatMasterRequestParameters : RequestParameters<CatMasterRequestParameters>
{
///<summary>a short version of the Accept header, e.g. json, yaml</summary>
public string Format
{
get => Q<string>("format");
set
{
Q("format", value);
SetAcceptHeader(value);
}
}
///<summary>Comma-separated list of column names to display</summary>
public string[] Headers
{
get => Q<string[]>("h");
set => Q("h", value);
}
///<summary>Return help information</summary>
public bool? Help
{
get => Q<bool? >("help");
set => Q("help", value);
}
///<summary>Return local information, do not retrieve the state from master node (default: false)</summary>
public bool? Local
{
get => Q<bool? >("local");
set => Q("local", value);
}
///<summary>Explicit operation timeout for connection to master node</summary>
public TimeSpan MasterTimeout
{
get => Q<TimeSpan>("master_timeout");
set => Q("master_timeout", value);
}
///<summary>Comma-separated list of column names or column aliases to sort by</summary>
public string[] SortByColumns
{
get => Q<string[]>("s");
set => Q("s", value);
}
///<summary>Verbose mode. Display column headers</summary>
public bool? Verbose
{
get => Q<bool? >("v");
set => Q("v", value);
}
}
///<summary>Request options for DataFrameAnalytics <para>https://www.elastic.co/guide/en/elasticsearch/reference/current/cat-dfanalytics.html</para></summary>
public class CatDataFrameAnalyticsRequestParameters : RequestParameters<CatDataFrameAnalyticsRequestParameters>
{
///<summary>Whether to ignore if a wildcard expression matches no configs. (This includes `_all` string or when no configs have been specified)</summary>
public bool? AllowNoMatch
{
get => Q<bool? >("allow_no_match");
set => Q("allow_no_match", value);
}
///<summary>The unit in which to display byte values</summary>
public Bytes? Bytes
{
get => Q<Bytes? >("bytes");
set => Q("bytes", value);
}
///<summary>a short version of the Accept header, e.g. json, yaml</summary>
public string Format
{
get => Q<string>("format");
set
{
Q("format", value);
SetAcceptHeader(value);
}
}
///<summary>Comma-separated list of column names to display</summary>
public string[] Headers
{
get => Q<string[]>("h");
set => Q("h", value);
}
///<summary>Return help information</summary>
public bool? Help
{
get => Q<bool? >("help");
set => Q("help", value);
}
///<summary>Comma-separated list of column names or column aliases to sort by</summary>
public string[] SortByColumns
{
get => Q<string[]>("s");
set => Q("s", value);
}
///<summary>Verbose mode. Display column headers</summary>
public bool? Verbose
{
get => Q<bool? >("v");
set => Q("v", value);
}
}
///<summary>Request options for Datafeeds <para>https://www.elastic.co/guide/en/elasticsearch/reference/current/cat-datafeeds.html</para></summary>
public class CatDatafeedsRequestParameters : RequestParameters<CatDatafeedsRequestParameters>
{
///<summary>Whether to ignore if a wildcard expression matches no datafeeds. (This includes `_all` string or when no datafeeds have been specified)</summary>
[Obsolete("Scheduled to be removed in 8.0, deprecated")]
public bool? AllowNoDatafeeds
{
get => Q<bool? >("allow_no_datafeeds");
set => Q("allow_no_datafeeds", value);
}
///<summary>Whether to ignore if a wildcard expression matches no datafeeds. (This includes `_all` string or when no datafeeds have been specified)</summary>
public bool? AllowNoMatch
{
get => Q<bool? >("allow_no_match");
set => Q("allow_no_match", value);
}
///<summary>a short version of the Accept header, e.g. json, yaml</summary>
public string Format
{
get => Q<string>("format");
set
{
Q("format", value);
SetAcceptHeader(value);
}
}
///<summary>Comma-separated list of column names to display</summary>
public string[] Headers
{
get => Q<string[]>("h");
set => Q("h", value);
}
///<summary>Return help information</summary>
public bool? Help
{
get => Q<bool? >("help");
set => Q("help", value);
}
///<summary>Comma-separated list of column names or column aliases to sort by</summary>
public string[] SortByColumns
{
get => Q<string[]>("s");
set => Q("s", value);
}
///<summary>Verbose mode. Display column headers</summary>
public bool? Verbose
{
get => Q<bool? >("v");
set => Q("v", value);
}
}
///<summary>Request options for Jobs <para>https://www.elastic.co/guide/en/elasticsearch/reference/current/cat-anomaly-detectors.html</para></summary>
public class CatJobsRequestParameters : RequestParameters<CatJobsRequestParameters>
{
///<summary>Whether to ignore if a wildcard expression matches no jobs. (This includes `_all` string or when no jobs have been specified)</summary>
[Obsolete("Scheduled to be removed in 8.0, deprecated")]
public bool? AllowNoJobs
{
get => Q<bool? >("allow_no_jobs");
set => Q("allow_no_jobs", value);
}
///<summary>Whether to ignore if a wildcard expression matches no jobs. (This includes `_all` string or when no jobs have been specified)</summary>
public bool? AllowNoMatch
{
get => Q<bool? >("allow_no_match");
set => Q("allow_no_match", value);
}
///<summary>The unit in which to display byte values</summary>
public Bytes? Bytes
{
get => Q<Bytes? >("bytes");
set => Q("bytes", value);
}
///<summary>a short version of the Accept header, e.g. json, yaml</summary>
public string Format
{
get => Q<string>("format");
set
{
Q("format", value);
SetAcceptHeader(value);
}
}
///<summary>Comma-separated list of column names to display</summary>
public string[] Headers
{
get => Q<string[]>("h");
set => Q("h", value);
}
///<summary>Return help information</summary>
public bool? Help
{
get => Q<bool? >("help");
set => Q("help", value);
}
///<summary>Comma-separated list of column names or column aliases to sort by</summary>
public string[] SortByColumns
{
get => Q<string[]>("s");
set => Q("s", value);
}
///<summary>Verbose mode. Display column headers</summary>
public bool? Verbose
{
get => Q<bool? >("v");
set => Q("v", value);
}
}
///<summary>Request options for TrainedModels <para>https://www.elastic.co/guide/en/elasticsearch/reference/current/cat-trained-model.html</para></summary>
public class CatTrainedModelsRequestParameters : RequestParameters<CatTrainedModelsRequestParameters>
{
///<summary>
/// Whether to ignore if a wildcard expression matches no trained models. (This includes `_all` string or when no trained models have been
/// specified)
///</summary>
public bool? AllowNoMatch
{
get => Q<bool? >("allow_no_match");
set => Q("allow_no_match", value);
}
///<summary>The unit in which to display byte values</summary>
public Bytes? Bytes
{
get => Q<Bytes? >("bytes");
set => Q("bytes", value);
}
///<summary>a short version of the Accept header, e.g. json, yaml</summary>
public string Format
{
get => Q<string>("format");
set
{
Q("format", value);
SetAcceptHeader(value);
}
}
///<summary>skips a number of trained models</summary>
public int? From
{
get => Q<int? >("from");
set => Q("from", value);
}
///<summary>Comma-separated list of column names to display</summary>
public string[] Headers
{
get => Q<string[]>("h");
set => Q("h", value);
}
///<summary>Return help information</summary>
public bool? Help
{
get => Q<bool? >("help");
set => Q("help", value);
}
///<summary>specifies a max number of trained models to get</summary>
public int? Size
{
get => Q<int? >("size");
set => Q("size", value);
}
///<summary>Comma-separated list of column names or column aliases to sort by</summary>
public string[] SortByColumns
{
get => Q<string[]>("s");
set => Q("s", value);
}
///<summary>Verbose mode. Display column headers</summary>
public bool? Verbose
{
get => Q<bool? >("v");
set => Q("v", value);
}
}
///<summary>Request options for NodeAttributes <para>https://www.elastic.co/guide/en/elasticsearch/reference/master/cat-nodeattrs.html</para></summary>
public class CatNodeAttributesRequestParameters : RequestParameters<CatNodeAttributesRequestParameters>
{
///<summary>a short version of the Accept header, e.g. json, yaml</summary>
public string Format
{
get => Q<string>("format");
set
{
Q("format", value);
SetAcceptHeader(value);
}
}
///<summary>Comma-separated list of column names to display</summary>
public string[] Headers
{
get => Q<string[]>("h");
set => Q("h", value);
}
///<summary>Return help information</summary>
public bool? Help
{
get => Q<bool? >("help");
set => Q("help", value);
}
///<summary>Return local information, do not retrieve the state from master node (default: false)</summary>
public bool? Local
{
get => Q<bool? >("local");
set => Q("local", value);
}
///<summary>Explicit operation timeout for connection to master node</summary>
public TimeSpan MasterTimeout
{
get => Q<TimeSpan>("master_timeout");
set => Q("master_timeout", value);
}
///<summary>Comma-separated list of column names or column aliases to sort by</summary>
public string[] SortByColumns
{
get => Q<string[]>("s");
set => Q("s", value);
}
///<summary>Verbose mode. Display column headers</summary>
public bool? Verbose
{
get => Q<bool? >("v");
set => Q("v", value);
}
}
///<summary>Request options for Nodes <para>https://www.elastic.co/guide/en/elasticsearch/reference/master/cat-nodes.html</para></summary>
public class CatNodesRequestParameters : RequestParameters<CatNodesRequestParameters>
{
///<summary>The unit in which to display byte values</summary>
public Bytes? Bytes
{
get => Q<Bytes? >("bytes");
set => Q("bytes", value);
}
///<summary>a short version of the Accept header, e.g. json, yaml</summary>
public string Format
{
get => Q<string>("format");
set
{
Q("format", value);
SetAcceptHeader(value);
}
}
///<summary>Return the full node ID instead of the shortened version (default: false)</summary>
public bool? FullId
{
get => Q<bool? >("full_id");
set => Q("full_id", value);
}
///<summary>Comma-separated list of column names to display</summary>
public string[] Headers
{
get => Q<string[]>("h");
set => Q("h", value);
}
///<summary>Return help information</summary>
public bool? Help
{
get => Q<bool? >("help");
set => Q("help", value);
}
///<summary>If set to true segment stats will include stats for segments that are not currently loaded into memory</summary>
public bool? IncludeUnloadedSegments
{
get => Q<bool? >("include_unloaded_segments");
set => Q("include_unloaded_segments", value);
}
///<summary>Explicit operation timeout for connection to master node</summary>
public TimeSpan MasterTimeout
{
get => Q<TimeSpan>("master_timeout");
set => Q("master_timeout", value);
}
///<summary>Comma-separated list of column names or column aliases to sort by</summary>
public string[] SortByColumns
{
get => Q<string[]>("s");
set => Q("s", value);
}
///<summary>Verbose mode. Display column headers</summary>
public bool? Verbose
{
get => Q<bool? >("v");
set => Q("v", value);
}
}
///<summary>Request options for PendingTasks <para>https://www.elastic.co/guide/en/elasticsearch/reference/master/cat-pending-tasks.html</para></summary>
public class CatPendingTasksRequestParameters : RequestParameters<CatPendingTasksRequestParameters>
{
///<summary>a short version of the Accept header, e.g. json, yaml</summary>
public string Format
{
get => Q<string>("format");
set
{
Q("format", value);
SetAcceptHeader(value);
}
}
///<summary>Comma-separated list of column names to display</summary>
public string[] Headers
{
get => Q<string[]>("h");
set => Q("h", value);
}
///<summary>Return help information</summary>
public bool? Help
{
get => Q<bool? >("help");
set => Q("help", value);
}
///<summary>Return local information, do not retrieve the state from master node (default: false)</summary>
public bool? Local
{
get => Q<bool? >("local");
set => Q("local", value);
}
///<summary>Explicit operation timeout for connection to master node</summary>
public TimeSpan MasterTimeout
{
get => Q<TimeSpan>("master_timeout");
set => Q("master_timeout", value);
}
///<summary>Comma-separated list of column names or column aliases to sort by</summary>
public string[] SortByColumns
{
get => Q<string[]>("s");
set => Q("s", value);
}
///<summary>Verbose mode. Display column headers</summary>
public bool? Verbose
{
get => Q<bool? >("v");
set => Q("v", value);
}
}
///<summary>Request options for Plugins <para>https://www.elastic.co/guide/en/elasticsearch/reference/master/cat-plugins.html</para></summary>
public class CatPluginsRequestParameters : RequestParameters<CatPluginsRequestParameters>
{
///<summary>a short version of the Accept header, e.g. json, yaml</summary>
public string Format
{
get => Q<string>("format");
set
{
Q("format", value);
SetAcceptHeader(value);
}
}
///<summary>Comma-separated list of column names to display</summary>
public string[] Headers
{
get => Q<string[]>("h");
set => Q("h", value);
}
///<summary>Return help information</summary>
public bool? Help
{
get => Q<bool? >("help");
set => Q("help", value);
}
///<summary>Include bootstrap plugins in the response</summary>
public bool? IncludeBootstrap
{
get => Q<bool? >("include_bootstrap");
set => Q("include_bootstrap", value);
}
///<summary>Return local information, do not retrieve the state from master node (default: false)</summary>
public bool? Local
{
get => Q<bool? >("local");
set => Q("local", value);
}
///<summary>Explicit operation timeout for connection to master node</summary>
public TimeSpan MasterTimeout
{
get => Q<TimeSpan>("master_timeout");
set => Q("master_timeout", value);
}
///<summary>Comma-separated list of column names or column aliases to sort by</summary>
public string[] SortByColumns
{
get => Q<string[]>("s");
set => Q("s", value);
}
///<summary>Verbose mode. Display column headers</summary>
public bool? Verbose
{
get => Q<bool? >("v");
set => Q("v", value);
}
}
///<summary>Request options for Recovery <para>https://www.elastic.co/guide/en/elasticsearch/reference/master/cat-recovery.html</para></summary>
public class CatRecoveryRequestParameters : RequestParameters<CatRecoveryRequestParameters>
{
///<summary>If `true`, the response only includes ongoing shard recoveries</summary>
public bool? ActiveOnly
{
get => Q<bool? >("active_only");
set => Q("active_only", value);
}
///<summary>The unit in which to display byte values</summary>
public Bytes? Bytes
{
get => Q<Bytes? >("bytes");
set => Q("bytes", value);
}
///<summary>If `true`, the response includes detailed information about shard recoveries</summary>
public bool? Detailed
{
get => Q<bool? >("detailed");
set => Q("detailed", value);
}
///<summary>a short version of the Accept header, e.g. json, yaml</summary>
public string Format
{
get => Q<string>("format");
set
{
Q("format", value);
SetAcceptHeader(value);
}
}
///<summary>Comma-separated list of column names to display</summary>
public string[] Headers
{
get => Q<string[]>("h");
set => Q("h", value);
}
///<summary>Return help information</summary>
public bool? Help
{
get => Q<bool? >("help");
set => Q("help", value);
}
///<summary>Comma-separated list or wildcard expression of index names to limit the returned information</summary>
public string[] IndexQueryString
{
get => Q<string[]>("index");
set => Q("index", value);
}
///<summary>Comma-separated list of column names or column aliases to sort by</summary>
public string[] SortByColumns
{
get => Q<string[]>("s");
set => Q("s", value);
}
///<summary>Verbose mode. Display column headers</summary>
public bool? Verbose
{
get => Q<bool? >("v");
set => Q("v", value);
}
}
///<summary>Request options for Repositories <para>https://www.elastic.co/guide/en/elasticsearch/reference/master/cat-repositories.html</para></summary>
public class CatRepositoriesRequestParameters : RequestParameters<CatRepositoriesRequestParameters>
{
///<summary>a short version of the Accept header, e.g. json, yaml</summary>
public string Format
{
get => Q<string>("format");
set
{
Q("format", value);
SetAcceptHeader(value);
}
}
///<summary>Comma-separated list of column names to display</summary>
public string[] Headers
{
get => Q<string[]>("h");
set => Q("h", value);
}
///<summary>Return help information</summary>
public bool? Help
{
get => Q<bool? >("help");
set => Q("help", value);
}
///<summary>Return local information, do not retrieve the state from master node</summary>
public bool? Local
{
get => Q<bool? >("local");
set => Q("local", value);
}
///<summary>Explicit operation timeout for connection to master node</summary>
public TimeSpan MasterTimeout
{
get => Q<TimeSpan>("master_timeout");
set => Q("master_timeout", value);
}
///<summary>Comma-separated list of column names or column aliases to sort by</summary>
public string[] SortByColumns
{
get => Q<string[]>("s");
set => Q("s", value);
}
///<summary>Verbose mode. Display column headers</summary>
public bool? Verbose
{
get => Q<bool? >("v");
set => Q("v", value);
}
}
///<summary>Request options for Segments <para>https://www.elastic.co/guide/en/elasticsearch/reference/master/cat-segments.html</para></summary>
public class CatSegmentsRequestParameters : RequestParameters<CatSegmentsRequestParameters>
{
///<summary>The unit in which to display byte values</summary>
public Bytes? Bytes
{
get => Q<Bytes? >("bytes");
set => Q("bytes", value);
}
///<summary>a short version of the Accept header, e.g. json, yaml</summary>
public string Format
{
get => Q<string>("format");
set
{
Q("format", value);
SetAcceptHeader(value);
}
}
///<summary>Comma-separated list of column names to display</summary>
public string[] Headers
{
get => Q<string[]>("h");
set => Q("h", value);
}
///<summary>Return help information</summary>
public bool? Help
{
get => Q<bool? >("help");
set => Q("help", value);
}
///<summary>Comma-separated list of column names or column aliases to sort by</summary>
public string[] SortByColumns
{
get => Q<string[]>("s");
set => Q("s", value);
}
///<summary>Verbose mode. Display column headers</summary>
public bool? Verbose
{
get => Q<bool? >("v");
set => Q("v", value);
}
}
///<summary>Request options for Shards <para>https://www.elastic.co/guide/en/elasticsearch/reference/master/cat-shards.html</para></summary>
public class CatShardsRequestParameters : RequestParameters<CatShardsRequestParameters>
{
///<summary>The unit in which to display byte values</summary>
public Bytes? Bytes
{
get => Q<Bytes? >("bytes");
set => Q("bytes", value);
}
///<summary>a short version of the Accept header, e.g. json, yaml</summary>
public string Format
{
get => Q<string>("format");
set
{
Q("format", value);
SetAcceptHeader(value);
}
}
///<summary>Comma-separated list of column names to display</summary>
public string[] Headers
{
get => Q<string[]>("h");
set => Q("h", value);
}
///<summary>Return help information</summary>
public bool? Help
{
get => Q<bool? >("help");
set => Q("help", value);
}
///<summary>Explicit operation timeout for connection to master node</summary>
public TimeSpan MasterTimeout
{
get => Q<TimeSpan>("master_timeout");
set => Q("master_timeout", value);
}
///<summary>Comma-separated list of column names or column aliases to sort by</summary>
public string[] SortByColumns
{
get => Q<string[]>("s");
set => Q("s", value);
}
///<summary>Verbose mode. Display column headers</summary>
public bool? Verbose
{
get => Q<bool? >("v");
set => Q("v", value);
}
}
///<summary>Request options for Snapshots <para>https://www.elastic.co/guide/en/elasticsearch/reference/master/cat-snapshots.html</para></summary>
public class CatSnapshotsRequestParameters : RequestParameters<CatSnapshotsRequestParameters>
{
///<summary>a short version of the Accept header, e.g. json, yaml</summary>
public string Format
{
get => Q<string>("format");
set
{
Q("format", value);
SetAcceptHeader(value);
}
}
///<summary>Comma-separated list of column names to display</summary>
public string[] Headers
{
get => Q<string[]>("h");
set => Q("h", value);
}
///<summary>Return help information</summary>
public bool? Help
{
get => Q<bool? >("help");
set => Q("help", value);
}
///<summary>Set to true to ignore unavailable snapshots</summary>
public bool? IgnoreUnavailable
{
get => Q<bool? >("ignore_unavailable");
set => Q("ignore_unavailable", value);
}
///<summary>Explicit operation timeout for connection to master node</summary>
public TimeSpan MasterTimeout
{
get => Q<TimeSpan>("master_timeout");
set => Q("master_timeout", value);
}
///<summary>Comma-separated list of column names or column aliases to sort by</summary>
public string[] SortByColumns
{
get => Q<string[]>("s");
set => Q("s", value);
}
///<summary>Verbose mode. Display column headers</summary>
public bool? Verbose
{
get => Q<bool? >("v");
set => Q("v", value);
}
}
///<summary>Request options for Tasks <para>https://www.elastic.co/guide/en/elasticsearch/reference/master/tasks.html</para></summary>
public class CatTasksRequestParameters : RequestParameters<CatTasksRequestParameters>
{
///<summary>A comma-separated list of actions that should be returned. Leave empty to return all.</summary>
public string[] Actions
{
get => Q<string[]>("actions");
set => Q("actions", value);
}
///<summary>Return detailed task information (default: false)</summary>
public bool? Detailed
{
get => Q<bool? >("detailed");
set => Q("detailed", value);
}
///<summary>a short version of the Accept header, e.g. json, yaml</summary>
public string Format
{
get => Q<string>("format");
set
{
Q("format", value);
SetAcceptHeader(value);
}
}
///<summary>Comma-separated list of column names to display</summary>
public string[] Headers
{
get => Q<string[]>("h");
set => Q("h", value);
}
///<summary>Return help information</summary>
public bool? Help
{
get => Q<bool? >("help");
set => Q("help", value);
}
///<summary>
/// A comma-separated list of node IDs or names to limit the returned information; use `_local` to return information from the node you're
/// connecting to, leave empty to get information from all nodes
///</summary>
public string[] Nodes
{
get => Q<string[]>("nodes");
set => Q("nodes", value);
}
///<summary>Return tasks with specified parent task id (node_id:task_number). Set to -1 to return all.</summary>
public string ParentTaskId
{
get => Q<string>("parent_task_id");
set => Q("parent_task_id", value);
}
///<summary>Comma-separated list of column names or column aliases to sort by</summary>
public string[] SortByColumns
{
get => Q<string[]>("s");
set => Q("s", value);
}
///<summary>Verbose mode. Display column headers</summary>
public bool? Verbose
{
get => Q<bool? >("v");
set => Q("v", value);
}
}
///<summary>Request options for Templates <para>https://www.elastic.co/guide/en/elasticsearch/reference/master/cat-templates.html</para></summary>
public class CatTemplatesRequestParameters : RequestParameters<CatTemplatesRequestParameters>
{
///<summary>a short version of the Accept header, e.g. json, yaml</summary>
public string Format
{
get => Q<string>("format");
set
{
Q("format", value);
SetAcceptHeader(value);
}
}
///<summary>Comma-separated list of column names to display</summary>
public string[] Headers
{
get => Q<string[]>("h");
set => Q("h", value);
}
///<summary>Return help information</summary>
public bool? Help
{
get => Q<bool? >("help");
set => Q("help", value);
}
///<summary>Return local information, do not retrieve the state from master node (default: false)</summary>
public bool? Local
{
get => Q<bool? >("local");
set => Q("local", value);
}
///<summary>Explicit operation timeout for connection to master node</summary>
public TimeSpan MasterTimeout
{
get => Q<TimeSpan>("master_timeout");
set => Q("master_timeout", value);
}
///<summary>Comma-separated list of column names or column aliases to sort by</summary>
public string[] SortByColumns
{
get => Q<string[]>("s");
set => Q("s", value);
}
///<summary>Verbose mode. Display column headers</summary>
public bool? Verbose
{
get => Q<bool? >("v");
set => Q("v", value);
}
}
///<summary>Request options for ThreadPool <para>https://www.elastic.co/guide/en/elasticsearch/reference/master/cat-thread-pool.html</para></summary>
public class CatThreadPoolRequestParameters : RequestParameters<CatThreadPoolRequestParameters>
{
///<summary>a short version of the Accept header, e.g. json, yaml</summary>
public string Format
{
get => Q<string>("format");
set
{
Q("format", value);
SetAcceptHeader(value);
}
}
///<summary>Comma-separated list of column names to display</summary>
public string[] Headers
{
get => Q<string[]>("h");
set => Q("h", value);
}
///<summary>Return help information</summary>
public bool? Help
{
get => Q<bool? >("help");
set => Q("help", value);
}
///<summary>Return local information, do not retrieve the state from master node (default: false)</summary>
public bool? Local
{
get => Q<bool? >("local");
set => Q("local", value);
}
///<summary>Explicit operation timeout for connection to master node</summary>
public TimeSpan MasterTimeout
{
get => Q<TimeSpan>("master_timeout");
set => Q("master_timeout", value);
}
///<summary>Comma-separated list of column names or column aliases to sort by</summary>
public string[] SortByColumns
{
get => Q<string[]>("s");
set => Q("s", value);
}
///<summary>Verbose mode. Display column headers</summary>
public bool? Verbose
{
get => Q<bool? >("v");
set => Q("v", value);
}
}
///<summary>Request options for Transforms <para>https://www.elastic.co/guide/en/elasticsearch/reference/current/cat-transforms.html</para></summary>
public class CatTransformsRequestParameters : RequestParameters<CatTransformsRequestParameters>
{
///<summary>Whether to ignore if a wildcard expression matches no transforms. (This includes `_all` string or when no transforms have been specified)</summary>
public bool? AllowNoMatch
{
get => Q<bool? >("allow_no_match");
set => Q("allow_no_match", value);
}
///<summary>a short version of the Accept header, e.g. json, yaml</summary>
public string Format
{
get => Q<string>("format");
set
{
Q("format", value);
SetAcceptHeader(value);
}
}
///<summary>skips a number of transform configs, defaults to 0</summary>
public int? From
{
get => Q<int? >("from");
set => Q("from", value);
}
///<summary>Comma-separated list of column names to display</summary>
public string[] Headers
{
get => Q<string[]>("h");
set => Q("h", value);
}
///<summary>Return help information</summary>
public bool? Help
{
get => Q<bool? >("help");
set => Q("help", value);
}
///<summary>specifies a max number of transforms to get, defaults to 100</summary>
public int? Size
{
get => Q<int? >("size");
set => Q("size", value);
}
///<summary>Comma-separated list of column names or column aliases to sort by</summary>
public string[] SortByColumns
{
get => Q<string[]>("s");
set => Q("s", value);
}
///<summary>Verbose mode. Display column headers</summary>
public bool? Verbose
{
get => Q<bool? >("v");
set => Q("v", value);
}
}
} | 26.374086 | 161 | 0.636989 | [
"Apache-2.0"
] | bdchris/elasticsearch-net | src/Elasticsearch.Net/Api/RequestParameters/RequestParameters.Cat.cs | 40,139 | C# |
using System;
using System.Collections;
using System.Data;
using System.Text.RegularExpressions;
using CMS.Base;
using CMS.DocumentEngine;
using CMS.FormEngine;
using CMS.FormEngine.Web.UI;
using CMS.Helpers;
using CMS.Localization;
using CMS.Membership;
using CMS.PortalEngine;
using CMS.PortalEngine.Web.UI;
using CMS.SiteProvider;
using CMS.UIControls;
public partial class CMSModules_PortalEngine_Controls_WebParts_WebPartZoneProperties : CMSUserControl
{
#region "Variables"
/// <summary>
/// Current page info.
/// </summary>
private PageInfo pi = null;
/// <summary>
/// Page template info.
/// </summary>
private PageTemplateInfo pti = null;
/// <summary>
/// Current web part zone.
/// </summary>
private WebPartZoneInstance webPartZone = null;
private bool mIsNewVariant = false;
private int mZoneVariantID = 0;
private VariantModeEnum variantMode = VariantModeEnum.None;
#endregion
#region "Public properties"
/// <summary>
/// Indicates whether this instance is a new variant.
/// </summary>
public bool IsNewVariant
{
get
{
return mIsNewVariant;
}
}
/// <summary>
/// Gets the web part zone instance.
/// </summary>
public WebPartZoneInstance WebPartZoneInstance
{
get
{
return webPartZone;
}
}
/// <summary>
/// Gets the zone variant ID.
/// </summary>
public int ZoneVariantID
{
get
{
return mZoneVariantID;
}
}
#endregion
#region "Page methods"
/// <summary>
/// OnInit event (BasicForm initialization).
/// </summary>
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
string zoneId = QueryHelper.GetString("zoneid", "");
string aliasPath = QueryHelper.GetString("aliaspath", "");
int templateId = QueryHelper.GetInteger("templateid", 0);
string culture = QueryHelper.GetString("culture", LocalizationContext.PreferredCultureCode);
mZoneVariantID = QueryHelper.GetInteger("variantid", 0);
mIsNewVariant = QueryHelper.GetBoolean("isnewvariant", false);
variantMode = VariantModeFunctions.GetVariantModeEnum(QueryHelper.GetString("variantmode", string.Empty));
// When displaying an existing variant of a web part, get the variant mode for its original web part
if (ZoneVariantID > 0)
{
PageTemplateInfo pti = PageTemplateInfoProvider.GetPageTemplateInfo(templateId);
if ((pti != null) && ((pti.TemplateInstance != null)))
{
// Get the original webpart and retrieve its variant mode
WebPartZoneInstance zoneInstance = pti.TemplateInstance.GetZone(zoneId);
if ((zoneInstance != null) && (zoneInstance.VariantMode != VariantModeEnum.None))
{
variantMode = zoneInstance.VariantMode;
}
}
}
// Try to find the zone variant in the database and set its VariantID
if (IsNewVariant)
{
Hashtable properties = WindowHelper.GetItem("variantProperties") as Hashtable;
if (properties != null)
{
// Get the variant code name from the WindowHelper
string variantName = ValidationHelper.GetString(properties["codename"], string.Empty);
// Check if the variant exists in the database
int variantIdFromDB = VariantHelper.GetVariantID(variantMode, templateId, variantName, true);
// Set the variant id from the database
if (variantIdFromDB > 0)
{
mZoneVariantID = variantIdFromDB;
mIsNewVariant = false;
}
}
}
if (!String.IsNullOrEmpty(zoneId))
{
// Get page info
pi = CMSWebPartPropertiesPage.GetPageInfo(aliasPath, templateId, culture);
if (pi == null)
{
ShowInformation(GetString("webpartzone.notfound"));
pnlFormArea.Visible = false;
return;
}
// Get template
pti = pi.UsedPageTemplateInfo;
if (pti != null)
{
// Get web part zone
pti.TemplateInstance.EnsureZone(zoneId);
webPartZone = pti.TemplateInstance.GetZone(zoneId);
if ((ZoneVariantID > 0) && (webPartZone != null) && (webPartZone.ZoneInstanceVariants != null))
{
// Check OnlineMarketing permissions
if (CheckPermissions("Read"))
{
webPartZone = webPartZone.ZoneInstanceVariants.Find(v => v.VariantID.Equals(ZoneVariantID));
}
else
{
// Not authorized for OnlineMarketing - Manage.
RedirectToInformation(String.Format(GetString("general.permissionresource"), "Read", (variantMode == VariantModeEnum.ContentPersonalization) ? "CMS.ContentPersonalization" : "CMS.MVTest"));
}
}
if (webPartZone == null)
{
ShowInformation(GetString("webpartzone.notfound"));
pnlFormArea.Visible = false;
return;
}
FormInfo fi = BuildFormInfo(webPartZone);
// Get the DataRow and fill the data row with values
DataRow dr = fi.GetDataRow();
foreach (DataColumn column in dr.Table.Columns)
{
try
{
DataHelper.SetDataRowValue(dr, column.ColumnName, webPartZone.GetValue(column.ColumnName));
}
catch
{
}
}
// Initialize Form
formElem.DataRow = dr;
formElem.MacroTable = webPartZone.MacroTable;
formElem.SubmitButton.Visible = false;
formElem.SiteName = SiteContext.CurrentSiteName;
formElem.FormInformation = fi;
formElem.ShowPrivateFields = true;
formElem.OnAfterDataLoad += formElem_OnAfterDataLoad;
// HTML editor toolbar
if (fi.UsesHtmlArea())
{
plcToolbarPadding.Visible = true;
plcToolbar.Visible = true;
pnlFormArea.Height = 285;
}
}
}
}
/// <summary>
/// Checks permissions (depends on variant mode)
/// </summary>
/// <param name="permissionName">Name of permission to test</param>
private bool CheckPermissions(string permissionName)
{
var cui = MembershipContext.AuthenticatedUser;
switch (variantMode)
{
case VariantModeEnum.MVT:
return cui.IsAuthorizedPerResource("cms.mvtest", permissionName);
case VariantModeEnum.ContentPersonalization:
return cui.IsAuthorizedPerResource("cms.contentpersonalization", permissionName);
case VariantModeEnum.Conflicted:
case VariantModeEnum.None:
return cui.IsAuthorizedPerResource("cms.mvtest", permissionName) || cui.IsAuthorizedPerResource("cms.contentpersonalization", permissionName);
}
return true;
}
/// <summary>
/// Handles the OnAfterDataLoad event of the formElem control.
/// </summary>
private void formElem_OnAfterDataLoad(object sender, EventArgs e)
{
if ((pti != null) && (pti.PageTemplateType == PageTemplateTypeEnum.Dashboard))
{
FormEngineUserControl typeCtrl = formElem.FieldControls["WidgetZoneType"];
if (typeCtrl != null)
{
typeCtrl.SetValue("IsDashboard", true);
}
}
else
{
// Disable WidgetZoneType if the zone is a zone variant or has variants
if ((ZoneVariantID > 0)
|| IsNewVariant
|| ((webPartZone != null) && (webPartZone.HasVariants)))
{
EditingFormControl editingCtrl = formElem.FieldEditingControls["WidgetZoneType"];
if (editingCtrl != null)
{
editingCtrl.Enabled = false;
}
}
}
}
#endregion
#region "Public methods"
/// <summary>
/// Saves web part zone properties.
/// </summary>
public bool Save()
{
if (ZoneVariantID > 0)
{
// Check OnlineMarketing permissions
if (!CheckPermissions("Manage"))
{
ShowInformation(GetString("general.modifynotallowed"));
return false;
}
}
// Save the data
if (formElem.SaveData(""))
{
DataRow dr = formElem.DataRow;
// Get basicform's datarow and update the fields
if ((webPartZone != null) && (dr != null) && (pti != null))
{
webPartZone.XMLVersion = 1;
// New variant
if (IsNewVariant)
{
webPartZone = pti.TemplateInstance.EnsureZone(webPartZone.ZoneID);
// Ensure that all the zones which are not saved in the template already will be saved now
// This is a case for new layout zones
if (!webPartZone.HasVariants)
{
TreeProvider tree = new TreeProvider(MembershipContext.AuthenticatedUser);
CMSPortalManager.SaveTemplateChanges(pi, pti.TemplateInstance, WidgetZoneTypeEnum.None, ViewModeEnum.Design, tree);
}
webPartZone = webPartZone.Clone();
string webPartControlId = string.Empty;
// Re-generate web part unique IDs
foreach (WebPartInstance wpi in webPartZone.WebParts)
{
bool webPartIdExists = false;
int offset = 0;
// Set new web part unique ID
string baseId = Regex.Replace(wpi.ControlID, "\\d+$", "");
do
{
webPartControlId = WebPartZoneInstance.GetUniqueWebPartId(baseId, pti.TemplateInstance, offset);
// Check if the returned web part control id is already used in the new zone variant
webPartIdExists = (webPartZone.GetWebPart(webPartControlId) != null);
offset++;
} while (webPartIdExists);
wpi.ControlID = webPartControlId;
wpi.InstanceGUID = new Guid();
}
}
// If zone type changed, delete all webparts in the zone
if (dr.Table.Columns.Contains("WidgetZoneType") &&
ValidationHelper.GetString(webPartZone.GetValue("WidgetZoneType"), "") != ValidationHelper.GetString(dr["WidgetZoneType"], ""))
{
webPartZone.RemoveAllWebParts();
}
foreach (DataColumn column in dr.Table.Columns)
{
webPartZone.MacroTable[column.ColumnName.ToLowerCSafe()] = formElem.MacroTable[column.ColumnName.ToLowerCSafe()];
webPartZone.SetValue(column.ColumnName, dr[column]);
}
// Ensure the layout zone flag
webPartZone.LayoutZone = QueryHelper.GetBoolean("layoutzone", false);
// Save standard zone
if ((ZoneVariantID == 0) && (!IsNewVariant))
{
// Update page template
PageTemplateInfoProvider.SetPageTemplateInfo(pti);
}
else
{
// Save zone variant
if ((webPartZone != null)
&& (webPartZone.ParentTemplateInstance != null)
&& (webPartZone.ParentTemplateInstance.ParentPageTemplate != null)
&& (!webPartZone.WebPartsContainVariants)) // Save only if any of the child web parts does not have variants
{
// Save the variant properties
VariantSettings variant = new VariantSettings()
{
ID = ZoneVariantID,
ZoneID = webPartZone.ZoneID,
PageTemplateID = webPartZone.ParentTemplateInstance.ParentPageTemplate.PageTemplateId,
};
// Get variant description properties
Hashtable properties = WindowHelper.GetItem("variantProperties") as Hashtable;
if (properties != null)
{
variant.Name = ValidationHelper.GetString(properties["codename"], string.Empty);
variant.DisplayName = ValidationHelper.GetString(properties["displayname"], string.Empty);
variant.Description = ValidationHelper.GetString(properties["description"], string.Empty);
variant.Enabled = ValidationHelper.GetBoolean(properties["enabled"], true);
if (PortalContext.ContentPersonalizationEnabled)
{
variant.Condition = ValidationHelper.GetString(properties["condition"], string.Empty);
}
}
mZoneVariantID = VariantHelper.SetVariant(variantMode, variant, webPartZone.GetXmlNode());
// The variants are cached -> Reload
pti.TemplateInstance.LoadVariants(true, VariantModeEnum.None);
}
}
// Reload the form (because of macro values set only by JS)
formElem.LoadData(dr);
ShowChangesSaved();
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
#endregion
#region "Private methods"
/// <summary>
/// Returns the form definition for the web part zone properties.
/// </summary>
private FormInfo BuildFormInfo(WebPartZoneInstance webPartZone)
{
FormInfo fi = null;
string formDefinition = String.Empty;
// Dashboard zone properties
if ((pti != null) && (pti.PageTemplateType == PageTemplateTypeEnum.Dashboard))
{
formDefinition = PortalFormHelper.LoadProperties("WebPartZone", "Dashboard.xml");
}
// UI page template properties
else if ((pti != null) && (pti.PageTemplateType == PageTemplateTypeEnum.UI))
{
formDefinition = PortalFormHelper.LoadProperties("WebPartZone", "UI.xml");
}
// Classic web part/widget properties
else
{
formDefinition = PortalFormHelper.LoadProperties("WebPartZone", "Standard.xml");
}
if (!String.IsNullOrEmpty(formDefinition))
{
// Load properties
fi = new FormInfo(formDefinition);
fi.UpdateExistingFields(fi);
DataRow dr = fi.GetDataRow();
LoadDataRowFromWebPartZone(dr, webPartZone);
}
return fi;
}
/// <summary>
/// Loads the data row data from given web part zone instance.
/// </summary>
/// <param name="dr">DataRow to fill</param>
/// <param name="webPart">Source web part zone</param>
private void LoadDataRowFromWebPartZone(DataRow dr, WebPartZoneInstance webPartZone)
{
foreach (DataColumn column in dr.Table.Columns)
{
try
{
object value = webPartZone.GetValue(column.ColumnName);
if (column.DataType == typeof(decimal))
{
value = ValidationHelper.GetDouble(value, 0, "en-us");
}
DataHelper.SetDataRowValue(dr, column.ColumnName, value);
}
catch
{
}
}
}
#endregion
} | 36 | 214 | 0.518845 | [
"MIT"
] | CMeeg/kentico-contrib | src/CMS/CMSModules/PortalEngine/Controls/WebParts/WebPartZoneProperties.ascx.cs | 17,354 | C# |
using RV32_Register;
using RV32_Register.Constants;
using System;
namespace RV32_Alu {
/// <summary>32bit長バイナリ形式</summary>
using Binary32 = UInt32;
/// <summary>
/// Risc-V RV32I 単精度浮動小数点命令セット 算術論理演算命令を実行するFPU
/// </summary>
public class RV32_SingleFpu : RV32_AbstractCalculator {
internal const Binary32 NaN = 0x7fc0_0000U;
internal const Binary32 Zero = 0x0000_0000U;
internal const Binary32 Infinity = 0x7f80_0000U;
internal const Binary32 NegativeSign = 0x8000_0000U;
internal const Binary32 SignMask = 0x8000_0000U;
internal const Binary32 ExpMask = 0x7f80_0000U;
internal const Binary32 MantMask = 0x007f_ffffU;
/// <summary>
/// Risc-V 単精度浮動小数算術論理演算 FPU
/// </summary>
/// <param name="registerSet">入出力用レジスタ</param>
public RV32_SingleFpu(RV32_RegisterSet reg) : base(reg) {
}
#region Risc-V CPU, Single-Precision命令
#region Risv-V CPU 浮動小数点演算命令
/// <summary>
/// Floating-Point Fused Multiply-Add, Single-Precision命令
/// 浮動小数点レジスタrs1とrs2の積にrs3を足した値を浮動小数点レジスタrdに書き込む
/// </summary>
/// <param name="rd">結果を格納するレジスタ番号</param>
/// <param name="rs1">レジスタ番号</param>
/// <param name="rs2">レジスタ番号</param>
/// <param name="rs3">レジスタ番号</param>
/// <returns>処理の成否</returns>
public bool FmaddS(FPRegister rd, FPRegister rs1, FPRegister rs2, FPRegister rs3, FloatRoundingMode frm, UInt32 insLength = 4U) {
Binary32 binary1 = (Binary32)reg.GetValue(rs1);
Binary32 binary2 = (Binary32)reg.GetValue(rs2);
Binary32 binary3 = (Binary32)reg.GetValue(rs3);
Binary32 result;
FloatCSR fcsr = 0;
result = ToBinary((ToSingle(binary1) * ToSingle(binary2)) + ToSingle(binary3));
result = IsNaN(result) ? NaN : result;
if ((IsInfinity(binary1) || IsInfinity(binary2)) && IsInfinity(binary3) &&
((IsNegative(binary1) ^ IsPositive(binary2)) ^ IsNegative(binary3))) {
// ∞ + -∞ もしくは -∞ + ∞の場合
result = NaN;
fcsr.NV = true;
} else if (IsSigNaN(binary1) || IsSigNaN(binary2) || IsSigNaN(binary3)) {
// いずれかの数値がシグナリングNaNの場合
fcsr.NV = true;
} else if (ToSingle(result) != (ToSingle(binary1) * ToSingle(binary2)) + ToSingle(binary3)) {
// 結果が一致しない場合
fcsr.NX = true;
} else if (IsRounded(result, binary1) || IsRounded(result, binary2) || IsRounded(result, binary3)) {
// 桁丸めが発生している場合
fcsr.NX = true;
}
reg.SetValue(rd, result);
reg.SetFflagsCSR(fcsr);
reg.IncrementPc(insLength);
return true;
}
/// <summary>
/// Floating-Point Fused Multiply-Subtract, Single-Precision命令
/// 浮動小数点レジスタrs1とrs2の積からrs3を引いた値を浮動小数点レジスタrdに書き込む
/// </summary>
/// <param name="rd">結果を格納するレジスタ番号</param>
/// <param name="rs1">レジスタ番号</param>
/// <param name="rs2">レジスタ番号</param>
/// <param name="rs3">レジスタ番号</param>
/// <returns>処理の成否</returns>
public bool FmsubS(FPRegister rd, FPRegister rs1, FPRegister rs2, FPRegister rs3, FloatRoundingMode frm, UInt32 insLength = 4U) {
Binary32 binary1 = (Binary32)reg.GetValue(rs1);
Binary32 binary2 = (Binary32)reg.GetValue(rs2);
Binary32 binary3 = (Binary32)reg.GetValue(rs3);
Binary32 result;
FloatCSR fcsr = 0;
result = ToBinary((ToSingle(binary1) * ToSingle(binary2)) - ToSingle(binary3));
result = IsNaN(result) ? NaN : result;
if ((IsInfinity(binary1) || IsInfinity(binary2)) && IsInfinity(binary3) &&
((IsNegative(binary1) ^ IsPositive(binary2)) ^ IsPositive(binary3))) {
// ∞ + -∞ もしくは -∞ + ∞の場合
result = NaN;
fcsr.NV = true;
} else if (IsSigNaN(binary1) || IsSigNaN(binary2) || IsSigNaN(binary3)) {
// いずれかの数値がシグナリングNaNの場合
fcsr.NV = true;
} else if (ToSingle(result) != (ToSingle(binary1) * ToSingle(binary2)) - ToSingle(binary3)) {
// 結果が一致しない場合
fcsr.NX = true;
} else if (IsRounded(result, binary1) || IsRounded(result, binary2) || IsRounded(result, binary3)) {
// 桁丸めが発生している場合
fcsr.NX = true;
}
reg.SetValue(rd, result);
reg.SetFflagsCSR(fcsr);
reg.IncrementPc(insLength);
return true;
}
/// <summary>
/// Floating-Point Fused Negative Multiply-Add, Single-Precision命令
/// 浮動小数点レジスタrs1に-1掛けた値とrs2の積にrs3を足した値を浮動小数点レジスタrdに書き込む
/// </summary>
/// <param name="rd">結果を格納するレジスタ番号</param>
/// <param name="rs1">レジスタ番号</param>
/// <param name="rs2">レジスタ番号</param>
/// <param name="rs3">レジスタ番号</param>
/// <returns>処理の成否</returns>
public bool FnmaddS(FPRegister rd, FPRegister rs1, FPRegister rs2, FPRegister rs3, FloatRoundingMode frm, UInt32 insLength = 4U) {
Binary32 binary1 = (Binary32)reg.GetValue(rs1);
Binary32 binary2 = (Binary32)reg.GetValue(rs2);
Binary32 binary3 = (Binary32)reg.GetValue(rs3);
Binary32 result;
FloatCSR fcsr = 0;
result = ToBinary((-ToSingle(binary1) * ToSingle(binary2)) - ToSingle(binary3));
result = IsNaN(result) ? NaN : result;
if ((IsInfinity(binary1) || IsInfinity(binary2)) && IsInfinity(binary3) &&
((IsPositive(binary1) ^ IsPositive(binary2)) ^ IsNegative(binary3))) {
// ∞ + -∞ もしくは -∞ + ∞の場合
result = NaN;
fcsr.NV = true;
} else if (IsSigNaN(binary1) || IsSigNaN(binary2) || IsSigNaN(binary3)) {
// いずれかの数値がシグナリングNaNの場合
fcsr.NV = true;
} else if (ToSingle(result) != (-ToSingle(binary1) * ToSingle(binary2)) - ToSingle(binary3)) {
// 結果が一致しない場合
fcsr.NX = true;
} else if (IsRounded(result, binary1) || IsRounded(result, binary2) || IsRounded(result, binary3)) {
// 桁丸めが発生している場合
fcsr.NX = true;
}
reg.SetValue(rd, result);
reg.SetFflagsCSR(fcsr);
reg.IncrementPc(insLength);
return true;
}
/// <summary>
/// Floating-Point Fused Negative Multiply-Subtract, Single-Precision命令
/// 浮動小数点レジスタrs1に-1掛けた値とrs2の積からrs3を引いた値を浮動小数点レジスタrdに書き込む
/// </summary>
/// <param name="rd">結果を格納するレジスタ番号</param>
/// <param name="rs1">レジスタ番号</param>
/// <param name="rs2">レジスタ番号</param>
/// <param name="rs3">レジスタ番号</param>
/// <returns>処理の成否</returns>
public bool FnmsubS(FPRegister rd, FPRegister rs1, FPRegister rs2, FPRegister rs3, FloatRoundingMode frm, UInt32 insLength = 4U) {
Binary32 binary1 = (Binary32)reg.GetValue(rs1);
Binary32 binary2 = (Binary32)reg.GetValue(rs2);
Binary32 binary3 = (Binary32)reg.GetValue(rs3);
Binary32 result;
FloatCSR fcsr = 0;
result = ToBinary((-ToSingle(binary1) * ToSingle(binary2)) + ToSingle(binary3));
result = IsNaN(result) ? NaN : result;
if ((IsInfinity(binary1) || IsInfinity(binary2)) && IsInfinity(binary3) &&
((IsPositive(binary1) ^ IsPositive(binary2)) ^ IsPositive(binary3))) {
// ∞ + -∞ もしくは -∞ + ∞の場合
result = NaN;
fcsr.NV = true;
} else if (IsSigNaN(binary1) || IsSigNaN(binary2) || IsSigNaN(binary3)) {
// いずれかの数値がシグナリングNaNの場合
fcsr.NV = true;
} else if (ToSingle(result) != (-ToSingle(binary1) * ToSingle(binary2)) + ToSingle(binary3)) {
// 結果が一致しない場合
fcsr.NX = true;
} else if (IsRounded(result, binary1) || IsRounded(result, binary2) || IsRounded(result, binary3)) {
// 桁丸めが発生している場合
fcsr.NX = true;
}
reg.SetValue(rd, result);
reg.SetFflagsCSR(fcsr);
reg.IncrementPc(insLength);
return true;
}
/// <summary>
/// Floating-Point Add, Single-Precision命令
/// 浮動小数点レジスタrs1とrs2の和を浮動小数点レジスタrdに書き込む
/// </summary>
/// <param name="rd">結果を格納するレジスタ番号</param>
/// <param name="rs1">レジスタ番号</param>
/// <param name="rs2">レジスタ番号</param>
/// <returns>処理の成否</returns>
public bool FaddS(FPRegister rd, FPRegister rs1, FPRegister rs2, FloatRoundingMode frm, UInt32 insLength = 4U) {
Binary32 binary1 = (Binary32)reg.GetValue(rs1);
Binary32 binary2 = (Binary32)reg.GetValue(rs2);
Binary32 result;
FloatCSR fcsr = 0;
result = ToBinary(ToSingle(binary1) + ToSingle(binary2));
result = IsNaN(result) ? NaN : result;
if (IsInfinity(binary1) && IsInfinity(binary2) && (IsNegative(binary1) ^ IsNegative(binary2))) {
// ∞ + -∞ もしくは -∞ + ∞の場合
result = NaN;
fcsr.NV = true;
} else if (IsSigNaN(binary1) || IsSigNaN(binary2)) {
// いずれかの数値がシグナリングNaNの場合
fcsr.NV = true;
} else if (ToSingle(result) != ToSingle(binary1) + ToSingle(binary2)) {
// 結果が一致しない場合
fcsr.NX = true;
} else if (IsRounded(result, binary1) || IsRounded(result, binary2)) {
// 桁丸めが発生している場合
fcsr.NX = true;
}
reg.SetValue(rd, result);
reg.SetFflagsCSR(fcsr);
reg.IncrementPc(insLength);
return true;
}
/// <summary>
/// Floating-Point Subtract, Single-Precision命令
/// 浮動小数点レジスタrs1とrs2の差を浮動小数点レジスタrdに書き込む
/// </summary>
/// <param name="rd">結果を格納するレジスタ番号</param>
/// <param name="rs1">レジスタ番号</param>
/// <param name="rs2">レジスタ番号</param>
/// <returns>処理の成否</returns>
public bool FsubS(FPRegister rd, FPRegister rs1, FPRegister rs2, FloatRoundingMode frm, UInt32 insLength = 4U) {
Binary32 binary1 = (Binary32)reg.GetValue(rs1);
Binary32 binary2 = (Binary32)reg.GetValue(rs2);
Binary32 result;
FloatCSR fcsr = 0;
result = ToBinary(ToSingle(binary1) - ToSingle(binary2));
result = IsNaN(result) ? NaN : result;
if (IsInfinity(binary1) && IsInfinity(binary2) && (IsNegative(binary1) ^ IsPositive(binary2))) {
// ∞ - ∞ もしくは -∞ - -∞の場合
result = NaN;
fcsr.NV = true;
} else if (IsSigNaN(binary1) || IsSigNaN(binary2)) {
// いずれかの数値がシグナリングNaNの場合
fcsr.NV = true;
} else if (ToSingle(result) != ToSingle(binary1) - ToSingle(binary2)) {
// 結果が一致しない場合
fcsr.NX = true;
} else if (IsRounded(result, binary1) || IsRounded(result, binary2)) {
// 桁丸めが発生している場合
fcsr.NX = true;
}
reg.SetValue(rd, result);
reg.SetFflagsCSR(fcsr);
reg.IncrementPc(insLength);
return true;
}
/// <summary>
/// Floating-Point Multiply, Single-Precision命令
/// 浮動小数点レジスタrs1とrs2の積を浮動小数点レジスタrdに書き込む
/// </summary>
/// <param name="rd">結果を格納するレジスタ番号</param>
/// <param name="rs1">レジスタ番号</param>
/// <param name="rs2">レジスタ番号</param>
/// <returns>処理の成否</returns>
public bool FmulS(FPRegister rd, FPRegister rs1, FPRegister rs2, FloatRoundingMode frm, UInt32 insLength = 4U) {
Binary32 binary1 = (Binary32)reg.GetValue(rs1);
Binary32 binary2 = (Binary32)reg.GetValue(rs2);
Binary32 result;
FloatCSR fcsr = 0;
result = ToBinary(ToSingle(binary1) * ToSingle(binary2));
result = IsNaN(result) ? NaN : result;
if (IsSigNaN(binary1) || IsSigNaN(binary2)) {
// いずれかの数値がシグナリングNaNの場合
fcsr.NV = true;
} else if (ToSingle(result) != ToSingle(binary1) * ToSingle(binary2)) {
// 結果が一致しない場合
fcsr.NX = true;
} else if (IsRounded(result, binary1) || IsRounded(result, binary2)) {
// 桁丸めが発生している場合
fcsr.NX = true;
}
reg.SetValue(rd, result);
reg.SetFflagsCSR(fcsr);
reg.IncrementPc(insLength);
return true;
}
/// <summary>
/// Floating-Point Divide, Single-Precision命令
/// 浮動小数点レジスタrs1とrs2の商を浮動小数点レジスタrdに書き込む
/// </summary>
/// <param name="rd">結果を格納するレジスタ番号</param>
/// <param name="rs1">レジスタ番号</param>
/// <param name="rs2">レジスタ番号</param>
/// <returns>処理の成否</returns>
public bool FdivS(FPRegister rd, FPRegister rs1, FPRegister rs2, FloatRoundingMode frm, UInt32 insLength = 4U) {
Binary32 binary1 = (Binary32)reg.GetValue(rs1);
Binary32 binary2 = (Binary32)reg.GetValue(rs2);
Binary32 result;
FloatCSR fcsr = 0;
if (binary1 == 0f && binary2 == 0f) {
// 被除数、除数ともに0の場合
result = NaN;
fcsr.DZ = true;
} else if (IsZero(binary2)) {
// ゼロ除算の場合
result = Infinity | ((binary1 & SignMask) ^ (binary2 & SignMask));
fcsr.DZ = true;
} else {
result = ToBinary(ToSingle(binary1) / ToSingle(binary2));
result = IsNaN(result) ? NaN : result;
if (IsSigNaN(binary1) || IsSigNaN(binary2)) {
// いずれかの数値がシグナリングNaNの場合
fcsr.NV = true;
} else if (ToSingle(result) != ToSingle(binary1) / ToSingle(binary2)) {
// 結果が一致しない場合
fcsr.NX = true;
} else if (IsRounded(result, binary1) || IsRounded(result, binary2)) {
// 桁丸めが発生している場合
fcsr.NX = true;
}
}
reg.SetValue(rd, result);
reg.SetFflagsCSR(fcsr);
reg.IncrementPc(insLength);
return true;
}
/// <summary>
/// Floating-Point Square Root, Single-Precision命令
/// 浮動小数点レジスタrs1の平方根を浮動小数点レジスタrdに書き込む
/// </summary>
/// <param name="rd">結果を格納するレジスタ番号</param>
/// <param name="rs1">レジスタ番号</param>
/// <param name="rs2">レジスタ番号</param>
/// <returns>処理の成否</returns>
public bool FsqrtS(FPRegister rd, FPRegister rs1, FloatRoundingMode frm, UInt32 insLength = 4U) {
Binary32 binary1 = (Binary32)reg.GetValue(rs1);
Binary32 result;
FloatCSR fcsr = 0;
result = ToBinary((Single)Math.Sqrt(ToSingle(binary1)));
result = IsNaN(result) ? NaN : result;
if (IsSigNaN(binary1)) {
// いずれかの数値がシグナリングNaNの場合
fcsr.NV = true;
} else if (IsNegative(binary1)) {
// 負数の平方根を求めようとした場合
fcsr.NV = true;
} else if (ToSingle(result) * ToSingle(result) != ToSingle(binary1)) {
// 結果が一致しない場合
fcsr.NX = true;
} else if (IsRounded(binary1, result)) {
// 桁丸めが発生している場合
fcsr.NX = true;
}
reg.SetValue(rd, result);
reg.SetFflagsCSR(fcsr);
reg.IncrementPc(insLength);
return true;
}
/// <summary>
/// Floating-Point Sign Inject, Single-Precision命令
/// 浮動小数点レジスタrs1の指数と仮数と、rs2の符号を組み立てて
/// 浮動小数点レジスタrdに書き込む
/// </summary>
/// <param name="rd">結果を格納するレジスタ番号</param>
/// <param name="rs1">レジスタ番号</param>
/// <param name="rs2">レジスタ番号</param>
/// <returns>処理の成否</returns>
public bool FsgnjS(FPRegister rd, FPRegister rs1, FPRegister rs2, UInt32 insLength = 4U) {
Binary32 binary1 = (Binary32)reg.GetValue(rs1);
Binary32 binary2 = (Binary32)reg.GetValue(rs2);
Binary32 result;
result = binary1 & 0x7fff_ffffU | binary2 & 0x8000_0000U;
reg.SetValue(rd, result);
reg.IncrementPc(insLength);
return true;
}
/// <summary>
/// Floating-Point Sign Inject, Single-Precision命令
/// 浮動小数点レジスタrs1の指数と仮数と、rs2の符号反転したものを組み立てて
/// 浮動小数点レジスタrdに書き込む
/// </summary>
/// <param name="rd">結果を格納するレジスタ番号</param>
/// <param name="rs1">レジスタ番号</param>
/// <param name="rs2">レジスタ番号</param>
/// <returns>処理の成否</returns>
public bool FsgnjnS(FPRegister rd, FPRegister rs1, FPRegister rs2, UInt32 insLength = 4U) {
Binary32 binary1 = (Binary32)reg.GetValue(rs1);
Binary32 binary2 = (Binary32)reg.GetValue(rs2);
Binary32 result;
FloatCSR fcsr = 0;
result = binary1 & 0x7fff_ffffU | ~binary2 & 0x8000_0000U;
reg.SetValue(rd, result);
reg.SetFflagsCSR(fcsr);
reg.IncrementPc(insLength);
return true;
}
/// <summary>
/// Floating-Point Sign Inject, Single-Precision命令
/// 浮動小数点レジスタrs1の指数と仮数と、rs1の符号とrs2の符号の排他的論理和を組み立てて
/// 浮動小数点レジスタrdに書き込む
/// </summary>
/// <param name="rd">結果を格納するレジスタ番号</param>
/// <param name="rs1">レジスタ番号</param>
/// <param name="rs2">レジスタ番号</param>
/// <returns>処理の成否</returns>
public bool FsgnjxS(FPRegister rd, FPRegister rs1, FPRegister rs2, UInt32 insLength = 4U) {
Binary32 binary1 = (Binary32)reg.GetValue(rs1);
Binary32 binary2 = (Binary32)reg.GetValue(rs2);
Binary32 result;
FloatCSR fcsr = 0;
result = binary1 & 0x7fff_ffffU | (binary1 ^ binary2) & 0x8000_0000U;
reg.SetValue(rd, result);
reg.SetFflagsCSR(fcsr);
reg.IncrementPc(insLength);
return true;
}
/// <summary>
/// Floating-Point Minimum, Single-Precision命令
/// 浮動小数点レジスタrs1とrs2の小さい方を浮動小数点レジスタrdに書き込む
/// </summary>
/// <param name="rd">結果を格納するレジスタ番号</param>
/// <param name="rs1">レジスタ番号</param>
/// <param name="rs2">レジスタ番号</param>
/// <returns>処理の成否</returns>
public bool FminS(FPRegister rd, FPRegister rs1, FPRegister rs2, UInt32 insLength = 4U) {
Binary32 binary1 = (Binary32)reg.GetValue(rs1);
Binary32 binary2 = (Binary32)reg.GetValue(rs2);
Binary32 result;
FloatCSR fcsr = 0;
result = ToSingle(binary1) < ToSingle(binary2) ? binary1 : (IsNegative(binary1) && IsZero(binary1) ? binary1 : binary2);
result = IsNaN(result) ? NaN : result;
if (IsSigNaN(binary1) || IsSigNaN(binary2)) {
fcsr.NV = true;
}
reg.SetValue(rd, result);
reg.SetFflagsCSR(fcsr);
reg.IncrementPc(insLength);
return true;
}
/// <summary>
/// Floating-Point Maximum, Single-Precision命令
/// 浮動小数点レジスタrs1とrs2の大きい方を浮動小数点レジスタrdに書き込む
/// </summary>
/// <param name="rd">結果を格納するレジスタ番号</param>
/// <param name="rs1">レジスタ番号</param>
/// <param name="rs2">レジスタ番号</param>
/// <returns>処理の成否</returns>
public bool FmaxS(FPRegister rd, FPRegister rs1, FPRegister rs2, UInt32 insLength = 4U) {
Binary32 binary1 = (Binary32)reg.GetValue(rs1);
Binary32 binary2 = (Binary32)reg.GetValue(rs2);
Binary32 result;
FloatCSR fcsr = 0;
result = ToSingle(binary1) > ToSingle(binary2) ? binary1 : (IsPositive(binary1) && IsZero(binary1) ? binary1 : binary2);
result = IsNaN(result) ? NaN : result;
if (IsSigNaN(binary1) || IsSigNaN(binary2)) {
fcsr.NV = true;
}
reg.SetValue(rd, result);
reg.SetFflagsCSR(fcsr);
reg.IncrementPc(insLength);
return true;
}
/// <summary>
/// Floating-Point Equals, Single-Precision命令
/// 浮動小数点レジスタrs1とrs2が等しければ 1 を、そうでなければ 0 を
/// 整数レジスタrdに書き込む
/// </summary>
/// <param name="rd">結果を格納するレジスタ番号</param>
/// <param name="rs1">レジスタ番号</param>
/// <returns>処理の成否</returns>
public bool FeqS(Register rd, FPRegister rs1, FPRegister rs2, UInt32 insLength = 4U) {
Binary32 binary1 = (Binary32)reg.GetValue(rs1);
Binary32 binary2 = (Binary32)reg.GetValue(rs2);
UInt32 result;
FloatCSR fcsr = 0;
result = ToSingle(binary1) == ToSingle(binary2) ? 1U : 0U;
if (IsSigNaN(binary1) || IsSigNaN(binary2)) {
fcsr.NV = true;
}
reg.SetValue(rd, result);
reg.SetFflagsCSR(fcsr);
reg.IncrementPc(insLength);
return true;
}
/// <summary>
/// Floating-Point Less Then, Single-Precision命令
/// 浮動小数点レジスタrs1がrs2より小さければ 1 を、そうでなければ 0 を
/// 整数レジスタrdに書き込む
/// </summary>
/// <param name="rd">結果を格納するレジスタ番号</param>
/// <param name="rs1">レジスタ番号</param>
/// <returns>処理の成否</returns>
public bool FltS(Register rd, FPRegister rs1, FPRegister rs2, UInt32 insLength = 4U) {
Binary32 binary1 = (Binary32)reg.GetValue(rs1);
Binary32 binary2 = (Binary32)reg.GetValue(rs2);
UInt32 result;
FloatCSR fcsr = 0;
result = ToSingle(binary1) < ToSingle(binary2) ? 1U : 0U;
if (IsNaN(binary1) || IsNaN(binary2)) {
fcsr.NV = true;
}
reg.SetValue(rd, result);
reg.SetFflagsCSR(fcsr);
reg.IncrementPc(insLength);
return true;
}
/// <summary>
/// Floating-Point Less Then or Equal, Single-Precision命令
/// 浮動小数点レジスタrs1がrs2以下であれば 1 を、そうでなければ 0 を
/// 整数レジスタrdに書き込む
/// </summary>
/// <param name="rd">結果を格納するレジスタ番号</param>
/// <param name="rs1">レジスタ番号</param>
/// <returns>処理の成否</returns>
public bool FleS(Register rd, FPRegister rs1, FPRegister rs2, UInt32 insLength = 4U) {
Binary32 binary1 = (Binary32)reg.GetValue(rs1);
Binary32 binary2 = (Binary32)reg.GetValue(rs2);
UInt32 result;
FloatCSR fcsr = 0;
result = ToSingle(binary1) <= ToSingle(binary2) ? 1U : 0U;
if (IsNaN(binary1) || IsNaN(binary2)) {
fcsr.NV = true;
}
reg.SetValue(rd, result);
reg.SetFflagsCSR(fcsr);
reg.IncrementPc(insLength);
return true;
}
/// <summary>
/// Floating-Point Convert to Word from Single命令
/// 浮動小数点レジスタrs1の単精度浮動小数を整数(符号付き)に変換して、整数レジスタrdに書き込む
/// </summary>
/// <param name="rd">結果を格納するレジスタ番号</param>
/// <param name="rs1">レジスタ番号</param>
/// <returns>処理の成否</returns>
public bool FcvtWS(Register rd, FPRegister rs1, FloatRoundingMode frm, UInt32 insLength = 4U) {
Binary32 binary1 = (Binary32)reg.GetValue(rs1);
Single value1 = ToSingle(binary1);
Single rvalue1 = ToSingle(RoundNum(binary1, 0, frm));
Int32 result;
FloatCSR fcsr = 0;
result = (Int32)rvalue1;
if ((IsPositive(binary1) && IsInfinity(binary1)) || IsNaN(binary1)) {
fcsr.NV = true;
result = Int32.MaxValue;
} else if (IsNegative(binary1) && IsInfinity(binary1)) {
fcsr.NV = true;
result = Int32.MinValue;
} else if (Int32.MaxValue < rvalue1) {
fcsr.NV = true;
result = Int32.MaxValue;
} else if (Int32.MinValue > rvalue1) {
fcsr.NV = true;
result = Int32.MinValue;
} else if (result != value1) {
fcsr.NX = true;
}
reg.SetValue(rd, (UInt32)result);
reg.SetFflagsCSR(fcsr);
reg.IncrementPc(insLength);
return true;
}
/// <summary>
/// Floating-Point Convert to Unsigned Word from Single命令
/// 浮動小数点レジスタrs1の単精度浮動小数を整数(符号なし)に変換して、整数レジスタrdに書き込む
/// </summary>
/// <param name="rd">結果を格納するレジスタ番号</param>
/// <param name="rs1">レジスタ番号</param>
/// <returns>処理の成否</returns>
public bool FcvtWUS(Register rd, FPRegister rs1, FloatRoundingMode frm, UInt32 insLength = 4U) {
Binary32 binary1 = (Binary32)reg.GetValue(rs1);
Single value1 = ToSingle(binary1);
Single rvalue1 = ToSingle(RoundNum(binary1, 0, frm));
UInt32 result;
FloatCSR fcsr = 0;
result = (UInt32)rvalue1;
if ((IsPositive(binary1) && IsInfinity(binary1)) || IsNaN(binary1)) {
fcsr.NV = true;
result = UInt32.MaxValue;
} else if (IsNegative(binary1) && IsInfinity(binary1)) {
fcsr.NV = true;
result = UInt32.MinValue;
} else if(UInt32.MaxValue < rvalue1) {
fcsr.NV = true;
result = UInt32.MaxValue;
} else if (UInt32.MinValue > rvalue1) {
fcsr.NV = true;
result = UInt32.MinValue;
} else if (result != value1) {
fcsr.NX = true;
}
reg.SetValue(rd, result);
reg.SetFflagsCSR(fcsr);
reg.IncrementPc(insLength);
return true;
}
/// <summary>
/// Floating-Point Convert to Single from Word命令
/// 整数レジスタrs1(符号付き)の整数を単精度浮動小数に変換して、浮動小数点レジスタrdに書き込む
/// </summary>
/// <param name="rd">結果を格納するレジスタ番号</param>
/// <param name="rs1">レジスタ番号</param>
/// <returns>処理の成否</returns>
public bool FcvtSW(FPRegister rd, Register rs1, FloatRoundingMode frm, UInt32 insLength = 4U) {
Int32 value1 = (Int32)reg.GetValue(rs1);
Binary32 result;
FloatCSR fcsr = 0;
result = ToBinary((Single)value1);
if ((Int32)ToSingle(result) != value1) {
fcsr.NX = true;
}
reg.SetValue(rd, result);
reg.SetFflagsCSR(fcsr);
reg.IncrementPc(insLength);
return true;
}
/// <summary>
/// Floating-Point Convert to Single from Unsigned Word命令
/// 整数レジスタrs1(符号なし)の整数を単精度浮動小数に変換して、浮動小数点レジスタrdに書き込む
/// </summary>
/// <param name="rd">結果を格納するレジスタ番号</param>
/// <param name="rs1">レジスタ番号</param>
/// <returns>処理の成否</returns>
public bool FcvtSWU(FPRegister rd, Register rs1, FloatRoundingMode frm, UInt32 insLength = 4U) {
UInt32 value1 = reg.GetValue(rs1);
Binary32 result;
FloatCSR fcsr = 0;
result = ToBinary((Single)value1);
if ((UInt32)ToSingle(result) != value1) {
fcsr.NX = true;
}
reg.SetValue(rd, result);
reg.SetFflagsCSR(fcsr);
reg.IncrementPc(insLength);
return true;
}
/// <summary>
/// Floating-Point Move to Integer from Word命令
/// 浮動小数点レジスタrs1を整数レジスタrd(符号付き)に書き込む
/// </summary>
/// <param name="rd">結果を格納するレジスタ番号</param>
/// <param name="rs1">レジスタ番号</param>
/// <returns>処理の成否</returns>
public bool FmvXW(Register rd, FPRegister rs1, UInt32 insLength = 4U) {
Binary32 binary1 = (Binary32)reg.GetValue(rs1);
UInt32 result;
result = binary1;
reg.SetValue(rd, result);
reg.IncrementPc(insLength);
return true;
}
/// <summary>
/// Floating-Point Move to Word from Integer命令
/// 整数レジスタrs1(符号付き)を浮動小数点レジスタrdに書き込む
/// </summary>
/// <param name="rd">結果を格納するレジスタ番号</param>
/// <param name="rs1">レジスタ番号</param>
/// <returns>処理の成否</returns>
public bool FmvWX(FPRegister rd, Register rs1, UInt32 insLength = 4U) {
UInt32 value1 = reg.GetValue(rs1);
Binary32 result;
result = value1;
reg.SetValue(rd, result);
reg.IncrementPc(insLength);
return true;
}
/// <summary>
/// Floating-Point Classigy, Single-Precision命令
/// 浮動小数点レジスタrs1のクラスを示すマスクを整数レジスタrdに書き込む
/// </summary>
/// <param name="rd">結果を格納するレジスタ番号</param>
/// <param name="rs1">レジスタ番号</param>
/// <returns>処理の成否</returns>
public bool FclassS(Register rd, FPRegister rs1, UInt32 insLength = 4U) {
Binary32 binary1 = (Binary32)reg.GetValue(rs1);
UInt32 result = 0U;
if (IsNegative(binary1) && IsInfinity(binary1)) {
// rs1が-∞の場合
result |= 0b00_0000_0001;
} else if (IsNegative(binary1) && IsNormalNum(binary1)) {
// rs1が負の正規数の場合
result |= 0b00_0000_0010;
} else if (IsNegative(binary1) && IsDenormalNum(binary1)) {
// rs1が負の非正規数の場合
result |= 0b00_0000_0100;
} else if (IsNegative(binary1) && IsZero(binary1)) {
// rs1が-0の場合
result |= 0b00_0000_1000;
} else if (IsPositive(binary1) && IsZero(binary1)) {
// rs1が+0の場合
result |= 0b00_0001_0000;
} else if (IsPositive(binary1) && IsDenormalNum(binary1)) {
// rs1が正の非正規数の場合
result |= 0b00_0010_0000;
} else if (IsPositive(binary1) && IsNormalNum(binary1)) {
// rs1が正の正規数の場合
result |= 0b00_0100_0000;
} else if (IsPositive(binary1) && IsInfinity(binary1)) {
// rs1が+∞の場合
result |= 0b00_1000_0000;
} else if (IsSigNaN(binary1)) {
// rs1がシグナル型非数の場合
result |= 0b01_0000_0000;
} else if (IsQuietNaN(binary1)) {
// rs1がクワイエット型非数の場合
result |= 0b10_0000_0000;
}
reg.SetValue(rd, result);
reg.IncrementPc(insLength);
return true;
}
#endregion
#endregion
internal static bool IsZero(Binary32 binary) => (binary & (ExpMask | MantMask)) == Zero;
internal static bool IsDenormalNum(Binary32 binary) => (binary & ExpMask) == 0U && !IsZero(binary);
internal static bool IsNormalNum(Binary32 binary) => (binary & ExpMask) > 0U && (binary & ExpMask) < 0x7f80_0000U;
internal static bool IsNaN(Binary32 binary) => (binary & ExpMask) == 0x7f80_0000U && (binary & MantMask) > 0U;
internal static bool IsSigNaN(Binary32 binary) => IsNaN(binary) && (binary & 0x0040_0000U) == 0x0000_0000U;
internal static bool IsQuietNaN(Binary32 binary) => IsNaN(binary) && (binary & 0x0040_0000U) == 0x0040_0000U;
internal static bool IsInfinity(Binary32 binary) => (binary & (ExpMask | MantMask)) == Infinity;
internal static bool IsNegative(Binary32 binary) => (binary & SignMask) == NegativeSign;
internal static bool IsPositive(Binary32 binary) => !IsNegative(binary);
internal static bool IsRounded(Binary32 base_binary, Binary32 binary) {
bool result = true;
// binary1とbinary2の指数の差を求める
int exp_sa = (int)((base_binary & ExpMask) >> 23) - (int)((binary & ExpMask) >> 23) ;
// 差が+の場合は仮数が右シフト、-の場合は左シフトされるので、シフトして消える部分に数値がある場合は誤差ありとする
//Binary32 mask = (exp_sa > 0 ? ((1u << exp_sa) - 1) : (uint)(-0xff80_0000 >> -exp_sa));
// -0x80_0000 = 0xff80_0000
Binary32 mask = (exp_sa > 0 ? ((1u << exp_sa) - 1) : (uint)(-0x80_0000 >> -exp_sa));
result = ((binary & MantMask) & mask) > 0;
return result;
}
/// <summary>
/// 32bit長バイナリ形式から単精度浮動小数点数に変換する
/// </summary>
/// <param name="binary">バイナリ形式の値</param>
/// <returns>変換した単精度浮動小数点数</returns>
internal static Single ToSingle(Binary32 binary) => BitConverter.ToSingle(BitConverter.GetBytes(binary), 0);
/// <summary>
/// 単精度浮動小数点数を32bit長バイナリ形式に変換する
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
internal static Binary32 ToBinary(Single value) => BitConverter.ToUInt32(BitConverter.GetBytes(value), 0);
/// <summary>
/// 値を指定した桁数、丸めモードで丸める
/// </summary>
/// <param name="binary">丸めるバイナリ形式の値</param>
/// <param name="digits">桁数</param>
/// <param name="frm">丸めモード</param>
/// <returns>丸めたバイナリ形式の値</returns>
private static Binary32 RoundNum(Binary32 binary, int digits, FloatRoundingMode frm) {
Binary32 result;
Single coef;
switch (frm) {
case FloatRoundingMode.RNE: // 最近接丸め(偶数)
result = ToBinary((Single)Math.Round(ToSingle(binary), digits, MidpointRounding.ToEven));
break;
case FloatRoundingMode.RTZ: // 0への丸め
coef = (Single)Math.Pow(10, digits);
Single sign = IsNegative(binary) ? -1f : 1f;
result = ToBinary(sign * (Single)(Math.Floor(sign * ToSingle(binary) * coef) / coef));
break;
case FloatRoundingMode.RDN: // 切り下げ
coef = (Single)Math.Pow(10, digits);
result = ToBinary((Single)(Math.Ceiling(ToSingle(binary) * coef) / coef));
break;
case FloatRoundingMode.RUP: // 切り上げ
coef = (Single)Math.Pow(10, digits);
result = ToBinary((Single)(Math.Floor(ToSingle(binary) * coef) / coef));
break;
case FloatRoundingMode.RMM: // 最近接丸め(0から遠くへの丸め)
result = ToBinary((Single)Math.Round(ToSingle(binary), digits, MidpointRounding.AwayFromZero));
break;
default:
result = 0U;
break;
}
return result;
}
}
}
| 37.785177 | 138 | 0.538035 | [
"BSD-3-Clause"
] | roy-n-roy/rv32Emulator | RV32_Alu/RV32_SingleFpu.cs | 39,924 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace DesignPatterns.Command
{
public class Client : MonoBehaviour
{
private RemoteControlDevice m_RadioReceiver;
private RemoteControlDevice m_TelevisionReceiver;
private RemoteControlDevice[] m_Devices = new RemoteControlDevice[2];
void Start()
{
m_RadioReceiver = new RadioReceiver();
m_TelevisionReceiver = new TelevisionReceiver();
m_Devices[0] = m_RadioReceiver;
m_Devices[1] = m_TelevisionReceiver;
}
void Update()
{
if (Input.GetKeyDown(KeyCode.O))
{
Command commandTV = new TurnOnCommand(m_Devices[0]);
Command commandRadio = new TurnOnCommand(m_Devices[1]);
Invoker invoker = new Invoker();
invoker.SetCommand(commandTV);
invoker.ExecuteCommand();
invoker.SetCommand(commandRadio);
invoker.ExecuteCommand();
}
if (Input.GetKeyDown(KeyCode.K))
{
Command commandKill = new KillSwitchCommand(m_Devices);
Invoker invoker = new Invoker();
invoker.SetCommand(commandKill);
invoker.ExecuteCommand();
}
}
}
} | 21.755102 | 70 | 0.746717 | [
"Apache-2.0"
] | japerales/codelearnstuff | Assets/Design Patterns/Structurals/Command/Client.cs | 1,068 | C# |
namespace VaporStore.DataProcessor
{
using System;
using System.Globalization;
using System.Linq;
using Data;
using Newtonsoft.Json;
using SoftJail.DataProcessor;
using VaporStore.DataProcessor.Dto.Export;
public static class Serializer
{
public static string ExportGamesByGenres(VaporStoreDbContext context, string[] genreNames)
{
var genres = context.Genres.ToList()
.Where(x => genreNames.Contains(x.Name))
.Select(x => new
{
Id = x.Id,
Genre = x.Name,
Games = x.Games
.Where(y => y.Purchases.Count > 0)
.Select(y => new
{
Id = y.Id,
Title = y.Name,
Developer = y.Developer.Name,
Tags = string.Join(", ", y.GameTags.Select(z => z.Tag.Name)),
Players = y.Purchases.Count
})
.OrderByDescending(y => y.Players)
.ThenBy(y => y.Id)
.ToList(),
TotalPlayers = x.Games.Sum(y => y.Purchases.Count)
})
.OrderByDescending(x => x.TotalPlayers)
.ThenBy(x => x.Id)
.ToList();
var result = JsonConvert.SerializeObject(genres, Formatting.Indented);
return result;
}
public static string ExportUserPurchasesByType(VaporStoreDbContext context, string storeType)
{
var users = context.Users.ToList()
.Where(x => x.Cards.Any(y => y.Purchases.Any(z => z.Type.ToString() == storeType)))
.Select(x => new UserXmlOutputModel
{
Username = x.Username,
Purchases = x.Cards.SelectMany(y => y.Purchases)
.Where(y => y.Type.ToString() == storeType)
.Select(y => new PurchaseXmlOutputModel
{
Card = y.Card.Number,
Cvc = y.Card.Cvc,
Date = y.Date.ToString("yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture),
Game = new GameXmlOutputModel
{
Title = y.Game.Name,
Genre = y.Game.Genre.Name,
Price = y.Game.Price,
}
})
.OrderBy(y => y.Date)
.ToArray(),
TotalSpent = x.Cards
.Sum(c => c.Purchases
.Where(p => p.Type.ToString() == storeType)
.Sum(p => p.Game.Price)),
})
.OrderByDescending(x => x.TotalSpent)
.ThenBy(x => x.Username)
.ToList();
var result = XmlConverter.Serialize(users, "Users");
return result;
}
}
} | 38.304878 | 101 | 0.430436 | [
"MIT"
] | HNochev/SoftUni-CSharp-Software-Engineering | MS SQL and Entity Framework/Entity Framework Core/Exam - Preparation/2020.08.14/VaporStore/DataProcessor/Serializer.cs | 3,143 | C# |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using GIPC;
using log4net.Config;
using TestRunner;
using Xappy.Common;
namespace Xappy
{
public class TestRunnerMarshal: LogCapableObject, IDisposable
{
private static GIPCServer _server;
private Action<string> _onBusy;
private Action<string> _onCompleted;
public string Host { get; protected set; }
public int Port { get; protected set; }
public int TimeoutInSeconds { get; protected set; }
public TestRunnerMarshal(Action<string> onBusy, Action<string> onCompleted)
{
_onBusy = onBusy;
_onCompleted = onCompleted;
}
public bool Start()
{
GetGIPCServerConfigValues();
SetupGIPCServerWith(Host, Port, TimeoutInSeconds);
try
{
_server.Start();
return true;
}
catch (Exception ex)
{
MessageBox.Show(String.Join("\n", new[]
{
"Unable to start GIPC server to listen for incoming requests:", ex.Message, ex.StackTrace
}));
return false;
}
}
private void SetupGIPCServerWith(string host, int port, int timeout)
{
_server = new GIPCServer(GIPCBase.Protocols.NetTcp, "xappy")
{
HostName = host,
Port = port,
MaxMessageSizeInMB = 25,
CommunicationTimeoutInSeconds = timeout
};
_server.OnMessageReceived += OnServerMessageReceived;
}
private void GetGIPCServerConfigValues()
{
var appSettings = ConfigurationManager.AppSettings;
GetServerHostAndPort(appSettings);
GetTimeoutValue(appSettings);
}
private void GetTimeoutValue(NameValueCollection appSettings)
{
TimeoutInSeconds = 600;
var timeout = appSettings["timeout"];
if (!String.IsNullOrEmpty(timeout))
{
int timeoutValue;
if (int.TryParse(timeout, out timeoutValue))
{
if (timeoutValue > 1)
TimeoutInSeconds = timeoutValue;
}
}
}
private void GetServerHostAndPort(NameValueCollection appSettings)
{
var listen = appSettings["listen"] ?? String.Join(":", new[] {Dns.GetHostName(), "5555"});
var parts = listen.Split(':');
var host = Dns.GetHostName();
var port = 5555;
var portFound = false;
var hostnameFound = false;
foreach (var item in parts)
{
if (!portFound && int.TryParse(item, out port))
{
portFound = true;
continue;
}
if (!hostnameFound)
{
host = item;
hostnameFound = true;
}
}
this.Host = host;
this.Port = port;
LogDebug(String.Format("Listening on {0}:{1}", Host, Port));
}
public void Stop()
{
lock (this)
{
LogDebug("Stopping GIPC server");
if (_server != null)
_server.Dispose();
_server = null;
LogDebug("GIPC server stopped");
}
}
private string OnServerMessageReceived(string message)
{
if (IsVersionInfoRequest(message))
return VersionInfo.GetVersion();
var testRunner = new TestRunner(ConfigurationManager.AppSettings["vstest"]);
var parts = message.Split('\n');
var buildName = parts[0];
_onBusy("Starting run for: " + buildName);
LogInfo(String.Format("Test run request received for: {0}", buildName));
var tempFile = Path.GetTempFileName() + ".xap";
var base64Data = String.Join("\n", parts.Skip(1));
var blob = new Base64Blob(base64Data);
var xapBytes = blob.ToBinary();
LogDebug(String.Format("Creating temporary XAP at: {0} ({1}k)", tempFile, (xapBytes.Length / 1024)));
File.WriteAllBytes(tempFile, xapBytes);
LogDebug(" => temporary file created");
try
{
var result = testRunner.ProcessBuild(tempFile);
_onCompleted(GetLastRunMessage());
return result;
}
catch (Exception ex)
{
LogError("Error running test:");
LogError(ex.Message + "\n\n" + ex.StackTrace);
_onCompleted(GetLastFailedMessage());
return "Unable to run tests: " + ex.Message;
}
finally
{
try {
LogDebug("Removing temporary XAP file");
File.Delete(tempFile);
LogDebug(" => done");
}
catch { }
}
}
private bool IsVersionInfoRequest(string message)
{
return message == "?version";
}
private string GetLastFailedMessage()
{
return GetLastMessageFor("failure");
}
private string GetLastMessageFor(string operation)
{
return String.Format("Last {0} was at: {1}", operation, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
}
private string GetLastRunMessage()
{
return GetLastMessageFor("successful run");
}
public void Dispose()
{
Stop();
}
}
}
| 32.768421 | 143 | 0.498554 | [
"BSD-2-Clause"
] | fluffynuts/xappy | source/Xappy/TestRunnerMarshal.cs | 6,228 | 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("4.PeshoCode")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("4.PeshoCode")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("b8c77911-e523-4f36-84ea-87e4bc26e5f5")]
// 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.567568 | 84 | 0.746043 | [
"MIT"
] | shopOFF/Telerik-Academy-Courses | CSharpPractice/4.PeshoCode/Properties/AssemblyInfo.cs | 1,393 | C# |
namespace keepnotes_api.Models.Db
{
public interface IKeepNotesDatabaseSettings
{
string UsersCollectionName { get; set; }
string NotesCollectionName { get; set; }
string ConnectionString { get; set; }
string DatabaseName { get; set; }
}
} | 28.7 | 49 | 0.644599 | [
"MIT"
] | josedr120/keepnotes-api | Models/Db/IKeepNotesDatabaseSettings.cs | 287 | C# |
// Copyright (c) Microsoft. All rights reserved.
namespace Microsoft.Azure.Devices.Edge.Hub.Core.Test.Storage
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Devices.Edge.Hub.Core.Storage;
using Microsoft.Azure.Devices.Edge.Storage;
using Microsoft.Azure.Devices.Edge.Util.Test.Common;
using Microsoft.Azure.Devices.Routing.Core;
using Microsoft.Azure.Devices.Routing.Core.Checkpointers;
using Microsoft.Azure.Devices.Routing.Core.MessageSources;
using Xunit;
using SystemProperties = Microsoft.Azure.Devices.Edge.Hub.Core.SystemProperties;
[Integration]
public class MessageStoreTest
{
[Theory]
[InlineData(0)]
[InlineData(10150)]
[InlineData(-1)]
public async Task BasicTest(long initialCheckpointOffset)
{
(IMessageStore messageStore, ICheckpointStore checkpointStore) result = await this.GetMessageStore(initialCheckpointOffset);
using (IMessageStore messageStore = result.messageStore)
{
for (int i = 0; i < 10000; i++)
{
if (i % 2 == 0)
{
long offset = await messageStore.Add("module1", this.GetMessage(i));
Assert.Equal(initialCheckpointOffset + 1 + i / 2, offset);
}
else
{
long offset = await messageStore.Add("module2", this.GetMessage(i));
Assert.Equal(initialCheckpointOffset + 1 + i / 2, offset);
}
}
IMessageIterator module1Iterator = messageStore.GetMessageIterator("module1");
Assert.NotNull(module1Iterator);
IMessageIterator module2Iterator = messageStore.GetMessageIterator("module2");
Assert.NotNull(module2Iterator);
for (int i = 0; i < 5; i++)
{
IEnumerable<IMessage> batch = await module1Iterator.GetNext(1000);
IEnumerable<IMessage> batchItemsAsList = batch as IList<IMessage> ?? batch.ToList();
Assert.Equal(1000, batchItemsAsList.Count());
for (int j = 0; j < 1000; j++)
{
Assert.Equal((((i * 1000) + j) * 2).ToString(), batchItemsAsList.ElementAt(j).SystemProperties[SystemProperties.MessageId]);
}
}
for (int i = 0; i < 5; i++)
{
IEnumerable<IMessage> batch = await module2Iterator.GetNext(1000);
IEnumerable<IMessage> batchItemsAsList2 = batch as IList<IMessage> ?? batch.ToList();
Assert.Equal(1000, batchItemsAsList2.Count());
for (int j = 0; j < 1000; j++)
{
Assert.Equal((((i * 1000) + j) * 2 + 1).ToString(), batchItemsAsList2.ElementAt(j).SystemProperties[SystemProperties.MessageId]);
}
}
}
}
[Fact]
public async Task CleanupTestTimeout()
{
(IMessageStore messageStore, ICheckpointStore checkpointStore) result = await this.GetMessageStore(20);
using (IMessageStore messageStore = result.messageStore)
{
for (int i = 0; i < 200; i++)
{
if (i % 2 == 0)
{
long offset = await messageStore.Add("module1", this.GetMessage(i));
Assert.Equal(i / 2, offset);
}
else
{
long offset = await messageStore.Add("module2", this.GetMessage(i));
Assert.Equal(i / 2, offset);
}
}
IMessageIterator module1Iterator = messageStore.GetMessageIterator("module1");
IEnumerable<IMessage> batch = await module1Iterator.GetNext(100);
Assert.Equal(100, batch.Count());
IMessageIterator module2Iterator = messageStore.GetMessageIterator("module2");
batch = await module2Iterator.GetNext(100);
Assert.Equal(100, batch.Count());
await Task.Delay(TimeSpan.FromSeconds(100));
module1Iterator = messageStore.GetMessageIterator("module1");
batch = await module1Iterator.GetNext(100);
Assert.Empty(batch);
module2Iterator = messageStore.GetMessageIterator("module2");
batch = await module2Iterator.GetNext(100);
Assert.Empty(batch);
}
}
[Fact]
public async Task CleanupTestTimeoutWithReadd()
{
(IMessageStore messageStore, ICheckpointStore checkpointStore) result = await this.GetMessageStore(20);
using (IMessageStore messageStore = result.messageStore)
{
for (int i = 0; i < 200; i++)
{
if (i % 2 == 0)
{
long offset = await messageStore.Add("module1", this.GetMessage(i));
Assert.Equal(i / 2, offset);
}
else
{
long offset = await messageStore.Add("module2", this.GetMessage(i));
Assert.Equal(i / 2, offset);
}
}
IMessageIterator module1Iterator = messageStore.GetMessageIterator("module1");
IEnumerable<IMessage> batch = await module1Iterator.GetNext(100);
Assert.Equal(100, batch.Count());
IMessageIterator module2Iterator = messageStore.GetMessageIterator("module2");
batch = await module2Iterator.GetNext(100);
Assert.Equal(100, batch.Count());
await Task.Delay(TimeSpan.FromSeconds(100));
for (int i = 200; i < 250; i++)
{
if (i % 2 == 0)
{
long offset = await messageStore.Add("module1", this.GetMessage(i));
Assert.Equal(i / 2, offset);
}
else
{
long offset = await messageStore.Add("module2", this.GetMessage(i));
Assert.Equal(i / 2, offset);
}
}
module1Iterator = messageStore.GetMessageIterator("module1");
batch = await module1Iterator.GetNext(100);
Assert.Equal(25, batch.Count());
module2Iterator = messageStore.GetMessageIterator("module2");
batch = await module2Iterator.GetNext(100);
Assert.Equal(25, batch.Count());
}
}
[Fact]
public async Task CleanupTestCheckpointed()
{
(IMessageStore messageStore, ICheckpointStore checkpointStore) result = await this.GetMessageStore(20);
ICheckpointStore checkpointStore = result.checkpointStore;
using (IMessageStore messageStore = result.messageStore)
{
for (int i = 0; i < 200; i++)
{
if (i % 2 == 0)
{
long offset = await messageStore.Add("module1", this.GetMessage(i));
Assert.Equal(i / 2, offset);
}
else
{
long offset = await messageStore.Add("module2", this.GetMessage(i));
Assert.Equal(i / 2, offset);
}
}
IMessageIterator module1Iterator = messageStore.GetMessageIterator("module1");
IEnumerable<IMessage> batch = await module1Iterator.GetNext(100);
Assert.Equal(100, batch.Count());
IMessageIterator module2Iterator = messageStore.GetMessageIterator("module2");
batch = await module2Iterator.GetNext(100);
Assert.Equal(100, batch.Count());
await checkpointStore.SetCheckpointDataAsync("module1", new CheckpointData(198), CancellationToken.None);
await checkpointStore.SetCheckpointDataAsync("module2", new CheckpointData(199), CancellationToken.None);
await Task.Delay(TimeSpan.FromSeconds(100));
module2Iterator = messageStore.GetMessageIterator("module2");
batch = await module2Iterator.GetNext(100);
Assert.Empty(batch);
module1Iterator = messageStore.GetMessageIterator("module1");
batch = await module1Iterator.GetNext(100);
Assert.Empty(batch);
}
}
[Fact]
public async Task MessageStoreAddRemoveEndpointTest()
{
// Arrange
var dbStoreProvider = new InMemoryDbStoreProvider();
IStoreProvider storeProvider = new StoreProvider(dbStoreProvider);
ICheckpointStore checkpointStore = CheckpointStore.Create(storeProvider);
IMessageStore messageStore = new MessageStore(storeProvider, checkpointStore, TimeSpan.FromHours(1));
// Act
await messageStore.AddEndpoint("module1");
for (int i = 0; i < 10; i++)
{
await messageStore.Add("module1", this.GetMessage(i));
}
// Assert
IMessageIterator module1Iterator = messageStore.GetMessageIterator("module1");
Assert.NotNull(module1Iterator);
IEnumerable<IMessage> batch = await module1Iterator.GetNext(1000);
List<IMessage> batchItemsAsList = batch.ToList();
Assert.Equal(10, batchItemsAsList.Count);
for (int i = 0; i < 10; i++)
{
Assert.Equal($"{i}", batchItemsAsList.ElementAt(i).SystemProperties[SystemProperties.MessageId]);
}
// Remove
await messageStore.RemoveEndpoint("module1");
// Assert
await Assert.ThrowsAsync<InvalidOperationException>(() => messageStore.Add("module1", this.GetMessage(0)));
Assert.Throws<InvalidOperationException>(() => messageStore.GetMessageIterator("module1"));
// Act
await messageStore.AddEndpoint("module1");
for (int i = 20; i < 30; i++)
{
await messageStore.Add("module1", this.GetMessage(i));
}
// Assert
module1Iterator = messageStore.GetMessageIterator("module1");
Assert.NotNull(module1Iterator);
batch = await module1Iterator.GetNext(1000);
batchItemsAsList = batch.ToList();
Assert.Equal(10, batchItemsAsList.Count);
for (int i = 20; i < 30; i++)
{
Assert.Equal($"{i}", batchItemsAsList.ElementAt(i - 20).SystemProperties[SystemProperties.MessageId]);
}
}
[Fact]
public void MessageWrapperRoundtripTest()
{
var properties = new Dictionary<string, string>
{
["Prop1"] = "PropVal1",
["Prop2"] = "PropVal2"
};
var systemProperties = new Dictionary<string, string>
{
[Devices.Routing.Core.SystemProperties.CorrelationId] = Guid.NewGuid().ToString(),
[Devices.Routing.Core.SystemProperties.DeviceId] = "device1",
[Devices.Routing.Core.SystemProperties.MessageId] = Guid.NewGuid().ToString()
};
byte[] body = "Test Message Body".ToBody();
var enqueueTime = new DateTime(2017, 11, 20, 01, 02, 03);
var dequeueTime = new DateTime(2017, 11, 20, 02, 03, 04);
IMessage message = new Message(
TelemetryMessageSource.Instance,
body,
properties,
systemProperties,
100,
enqueueTime,
dequeueTime);
var messageWrapper = new MessageStore.MessageWrapper(message, DateTime.UtcNow, 3);
byte[] messageWrapperBytes = messageWrapper.ToBytes();
var retrievedMesssageWrapper = messageWrapperBytes.FromBytes<MessageStore.MessageWrapper>();
Assert.NotNull(retrievedMesssageWrapper);
Assert.Equal(messageWrapper.TimeStamp, retrievedMesssageWrapper.TimeStamp);
Assert.Equal(messageWrapper.RefCount, retrievedMesssageWrapper.RefCount);
Assert.Equal(messageWrapper.Message, retrievedMesssageWrapper.Message);
}
IMessage GetMessage(int i)
{
return new Message(
TelemetryMessageSource.Instance,
$"Test Message {i} Body".ToBody(),
new Dictionary<string, string>(),
new Dictionary<string, string>
{
[SystemProperties.EdgeMessageId] = Guid.NewGuid().ToString(),
[SystemProperties.MessageId] = i.ToString()
});
}
async Task<(IMessageStore, ICheckpointStore)> GetMessageStore(int ttlSecs = 300)
{
var dbStoreProvider = new InMemoryDbStoreProvider();
IStoreProvider storeProvider = new StoreProvider(dbStoreProvider);
ICheckpointStore checkpointStore = CheckpointStore.Create(storeProvider);
IMessageStore messageStore = new MessageStore(storeProvider, checkpointStore, TimeSpan.FromSeconds(ttlSecs));
await messageStore.AddEndpoint("module1");
await messageStore.AddEndpoint("module2");
return (messageStore, checkpointStore);
}
async Task<(IMessageStore, ICheckpointStore)> GetMessageStore(long initialCheckpointOffset, int ttlSecs = 300)
{
var dbStoreProvider = new InMemoryDbStoreProvider();
IStoreProvider storeProvider = new StoreProvider(dbStoreProvider);
IEntityStore<string, CheckpointStore.CheckpointEntity> checkpointUnderlyingStore = storeProvider.GetEntityStore<string, CheckpointStore.CheckpointEntity>($"Checkpoint{Guid.NewGuid().ToString()}");
if (initialCheckpointOffset >= 0)
{
await checkpointUnderlyingStore.Put("module1", new CheckpointStore.CheckpointEntity(initialCheckpointOffset, null, null));
await checkpointUnderlyingStore.Put("module2", new CheckpointStore.CheckpointEntity(initialCheckpointOffset, null, null));
}
ICheckpointStore checkpointStore = new CheckpointStore(checkpointUnderlyingStore);
IMessageStore messageStore = new MessageStore(storeProvider, checkpointStore, TimeSpan.FromSeconds(ttlSecs));
await messageStore.AddEndpoint("module1");
await messageStore.AddEndpoint("module2");
return (messageStore, checkpointStore);
}
}
}
| 43.551136 | 208 | 0.557926 | [
"MIT"
] | CIPop/iotedge | edge-hub/test/Microsoft.Azure.Devices.Edge.Hub.Core.Test/storage/MessageStoreTest.cs | 15,330 | C# |
using System.Collections.Generic;
using System.Text.Json.Serialization;
namespace CarbonSDK.Rest.Responses
{
public class AllValidatorsResponse : List<AllValidatorsResponse.ValidatorItem>
{
public class ValidatorItem
{
public string OperatorAddress { get; set; }
public string ConsPubKey { get; set; }
public bool Jailed { get; set; }
public int Status { get; set; }
public string Tokens { get; set; }
public string DelegatorShares { get; set; }
public DescriptionItem Description { get; set; }
public int UnbondingHeight { get; set; }
public object UnbondingCompletionTime { get; set; }
public CommissionItem Commission { get; set; }
public string MinSelfDelegation { get; set; }
public string ConsAddress { get; set; }
public string ConsAddressByte { get; set; }
public string WalletAddress { get; set; }
public string BondStatus { get; set; }
}
public class DescriptionItem
{
public string Moniker { get; set; }
public string Identity { get; set; }
public string Website { get; set; }
[JsonPropertyName("security_contact")]
public string SecurityContact { get; set; }
public string Details { get; set; }
}
public class CommissionItem
{
[JsonPropertyName("commission_rates")]
public CommissionRateItem CommissionRates { get; set; }
[JsonPropertyName("update_time")]
public string UpdateTime { get; set; }
}
public class CommissionRateItem
{
public string Rate { get; set; }
[JsonPropertyName("max_rate")]
public string MaxRate { get; set; }
[JsonPropertyName("max_change_rate")]
public string MaxChangeRate { get; set; }
}
}
}
| 33.45 | 82 | 0.577479 | [
"Apache-2.0"
] | blocksentinel/carbon-dotnet-sdk | src/Rest/Responses/AllValidatorsResponse.cs | 2,009 | C# |
#region S# License
/******************************************************************************************
NOTICE!!! This program and source code is owned and licensed by
StockSharp, LLC, www.stocksharp.com
Viewing or use of this code requires your acceptance of the license
agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE
Removal of this comment is a violation of the license agreement.
Project: StockSharp.Messages.Messages
File: PositionChangeMessage.cs
Created: 2015, 11, 11, 2:32 PM
Copyright 2010 by StockSharp, LLC
*******************************************************************************************/
#endregion S# License
namespace StockSharp.Messages
{
using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Runtime.Serialization;
using Ecng.Common;
using Ecng.Collections;
using Ecng.Serialization;
using StockSharp.Localization;
/// <summary>
/// Type of the changes in <see cref="PositionChangeMessage"/>.
/// </summary>
[System.Runtime.Serialization.DataContract]
[Serializable]
public enum PositionChangeTypes
{
/// <summary>
/// Initial value.
/// </summary>
[EnumMember]
[Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Str253Key)]
BeginValue,
/// <summary>
/// Current value.
/// </summary>
[EnumMember]
[Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Str254Key)]
CurrentValue,
/// <summary>
/// Blocked.
/// </summary>
[EnumMember]
[Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Str255Key)]
BlockedValue,
/// <summary>
/// Position price.
/// </summary>
[EnumMember]
[Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Str256Key)]
CurrentPrice,
/// <summary>
/// Average price.
/// </summary>
[EnumMember]
[Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Str257Key)]
AveragePrice,
/// <summary>
/// Unrealized profit.
/// </summary>
[EnumMember]
[Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Str258Key)]
UnrealizedPnL,
/// <summary>
/// Realized profit.
/// </summary>
[EnumMember]
[Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Str259Key)]
RealizedPnL,
/// <summary>
/// Variation margin.
/// </summary>
[EnumMember]
[Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Str260Key)]
VariationMargin,
/// <summary>
/// Currency.
/// </summary>
[EnumMember]
[Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.CurrencyKey)]
Currency,
/// <summary>
/// Extended information.
/// </summary>
[EnumMember]
[Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.ExtendedInfoKey)]
[Obsolete]
ExtensionInfo,
/// <summary>
/// Margin leverage.
/// </summary>
[EnumMember]
[Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Str261Key)]
Leverage,
/// <summary>
/// Total commission.
/// </summary>
[EnumMember]
[Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Str262Key)]
Commission,
/// <summary>
/// Current value (in lots).
/// </summary>
[EnumMember]
[Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Str263Key)]
CurrentValueInLots,
/// <summary>
/// The depositary where the physical security.
/// </summary>
[EnumMember]
[Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Str264Key)]
[Obsolete]
DepoName,
/// <summary>
/// Portfolio state.
/// </summary>
[EnumMember]
[Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Str265Key)]
State,
/// <summary>
/// Expiration date.
/// </summary>
[EnumMember]
[Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.ExpiryDateKey)]
ExpirationDate,
}
/// <summary>
/// The message contains information about the position changes.
/// </summary>
[System.Runtime.Serialization.DataContract]
[Serializable]
[DisplayNameLoc(LocalizedStrings.Str862Key)]
[DescriptionLoc(LocalizedStrings.PositionDescKey)]
public sealed class PositionChangeMessage : BaseChangeMessage<PositionChangeTypes>
{
/// <summary>
/// Security ID.
/// </summary>
[DataMember]
[DisplayNameLoc(LocalizedStrings.SecurityIdKey)]
[DescriptionLoc(LocalizedStrings.SecurityIdKey, true)]
[MainCategory]
public SecurityId SecurityId { get; set; }
/// <summary>
/// Portfolio name.
/// </summary>
[DataMember]
[DisplayNameLoc(LocalizedStrings.PortfolioKey)]
[DescriptionLoc(LocalizedStrings.PortfolioNameKey)]
[MainCategory]
[ReadOnly(true)]
public string PortfolioName { get; set; }
/// <summary>
/// Client code assigned by the broker.
/// </summary>
[DataMember]
[MainCategory]
[DisplayNameLoc(LocalizedStrings.ClientCodeKey)]
[DescriptionLoc(LocalizedStrings.ClientCodeDescKey)]
public string ClientCode { get; set; }
/// <summary>
/// The depositary where the physical security.
/// </summary>
[DisplayNameLoc(LocalizedStrings.Str264Key)]
[DescriptionLoc(LocalizedStrings.DepoNameKey)]
[MainCategory]
public string DepoName { get; set; }
/// <summary>
/// User id.
/// </summary>
[DataMember]
[DisplayNameLoc(LocalizedStrings.Str3725Key)]
[DescriptionLoc(LocalizedStrings.UserIdKey)]
[MainCategory]
public string User { get; set; }
/// <summary>
/// Limit type for Т+ market.
/// </summary>
[DisplayNameLoc(LocalizedStrings.Str266Key)]
[DescriptionLoc(LocalizedStrings.Str267Key)]
[MainCategory]
[Nullable]
public TPlusLimits? LimitType { get; set; }
/// <summary>
/// Text position description.
/// </summary>
[DataMember]
[DisplayNameLoc(LocalizedStrings.DescriptionKey)]
[DescriptionLoc(LocalizedStrings.Str269Key)]
[MainCategory]
public string Description { get; set; }
/// <summary>
/// ID of the original message <see cref="PortfolioMessage.TransactionId"/> for which this message is a response.
/// </summary>
[DataMember]
public long OriginalTransactionId { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="PositionChangeMessage"/>.
/// </summary>
public PositionChangeMessage()
: base(MessageTypes.PositionChange)
{
}
/// <summary>
/// Create a copy of <see cref="PositionChangeMessage"/>.
/// </summary>
/// <returns>Copy.</returns>
public override Message Clone()
{
var msg = new PositionChangeMessage
{
LocalTime = LocalTime,
PortfolioName = PortfolioName,
SecurityId = SecurityId,
DepoName = DepoName,
ServerTime = ServerTime,
LimitType = LimitType,
Description = Description,
OriginalTransactionId = OriginalTransactionId,
ClientCode = ClientCode,
User = User,
};
msg.Changes.AddRange(Changes);
this.CopyExtensionInfo(msg);
return msg;
}
/// <summary>
/// Returns a string that represents the current object.
/// </summary>
/// <returns>A string that represents the current object.</returns>
public override string ToString()
{
return base.ToString() + $",Sec={SecurityId},P={PortfolioName},CL={ClientCode},Changes={Changes.Select(c => c.ToString()).Join(",")}";
}
}
} | 27.076923 | 137 | 0.686012 | [
"Apache-2.0"
] | 1M15M3/StockSharp | Messages/PositionChangeMessage.cs | 7,393 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using Plang.Compiler.Backend.ASTExt;
using Plang.Compiler.TypeChecker;
using Plang.Compiler.TypeChecker.AST;
using Plang.Compiler.TypeChecker.AST.Declarations;
using Plang.Compiler.TypeChecker.AST.Expressions;
using Plang.Compiler.TypeChecker.AST.Statements;
using Plang.Compiler.TypeChecker.AST.States;
using Plang.Compiler.TypeChecker.Types;
using Antlr4.Runtime;
namespace Plang.Compiler.Backend.Symbolic
{
class TransformASTPass
{
static private int continuationNumber = 0;
static private int whileNumber = 0;
static private int callNum = 0;
static public List<IPDecl> GetTransformedDecls(Scope globalScope)
{
continuationNumber = 0;
callNum = 0;
List<IPDecl> decls = new List<IPDecl>();
foreach (var decl in globalScope.AllDecls)
{
IPDecl result = TransformDecl(decl);
if (result != null)
decls.Add(result);
}
continuationNumber = 0;
callNum = 0;
return decls;
}
static private IPDecl TransformDecl(IPDecl decl)
{
switch (decl)
{
case Function function:
if (function.IsForeign)
return function;
else
return null;
case Machine machine:
if (machine.Receives.Events.GetEnumerator().MoveNext())
return TransformMachine(machine);
else return machine;
default:
return decl;
}
}
static private Machine TransformMachine(Machine machine)
{
Machine transformedMachine = new Machine(machine.Name, machine.SourceLocation);
transformedMachine.Assume = machine.Assume;
transformedMachine.Assert = machine.Assert;
transformedMachine.Receives = machine.Receives;
transformedMachine.Sends = machine.Sends;
transformedMachine.Creates = machine.Creates;
foreach (var field in machine.Fields) transformedMachine.AddField(field);
Dictionary<Function, Function> functionMap = new Dictionary<Function, Function>();
foreach (var method in machine.Methods)
{
InlineInFunction(method);
}
foreach (var method in machine.Methods)
{
Function transformedFunction = TransformFunction(method, transformedMachine);
functionMap.Add(method, transformedFunction);
transformedMachine.AddMethod(transformedFunction);
}
transformedMachine.StartState = machine.StartState;
transformedMachine.Observes = machine.Observes;
transformedMachine.PayloadType = machine.PayloadType;
transformedMachine.Scope = machine.Scope;
foreach (var state in machine.States)
{
transformedMachine.AddState(TransformState(state, functionMap));
}
foreach (var method in machine.Methods)
{
foreach (var callee in method.Callees)
{
if (functionMap.ContainsKey(callee))
functionMap[method].AddCallee(functionMap[callee]);
else functionMap[method].AddCallee(callee);
}
}
return transformedMachine;
}
static private State TransformState(State state, IDictionary<Function, Function> functionMap)
{
State transformedState = new State(state.SourceLocation, state.Name);
transformedState.Temperature = state.Temperature;
transformedState.IsStart = state.IsStart;
if (state.Entry != null)
transformedState.Entry = functionMap[state.Entry];
if (state.Exit != null)
transformedState.Exit = functionMap[state.Exit];
transformedState.OwningMachine = state.OwningMachine;
transformedState.Container = state.Container;
foreach (var handler in state.AllEventHandlers)
{
transformedState[handler.Key] = TransformAction(handler.Value, functionMap);
}
return transformedState;
}
static private IStateAction TransformAction(IStateAction action, IDictionary<Function, Function> functionMap)
{
switch (action)
{
case EventDoAction doAction:
return new EventDoAction(doAction.SourceLocation, doAction.Trigger, functionMap[doAction.Target]);
case EventGotoState gotoState:
Function transition = null;
if(gotoState.TransitionFunction != null) transition = functionMap[gotoState.TransitionFunction];
return new EventGotoState(gotoState.SourceLocation, gotoState.Trigger, gotoState.Target, transition);
default:
return action;
}
}
static private void GenerateInline(Function caller, Function callee, IReadOnlyList<IPExpr> argsList, List<IPStmt> body, ParserRuleContext sourceLocation)
{
Dictionary<Variable,Variable> newVarMap = new Dictionary<Variable,Variable>();
for (int i = 0; i < callee.Signature.Parameters.Count; i++)
{
IPExpr expr = argsList[i];
Variable newVar = new Variable($"inline_{callNum}_{callee.Signature.Parameters[i].Name}", sourceLocation, VariableRole.Temp);
newVar.Type = expr.Type;
body.Add(new AssignStmt(sourceLocation, new VariableAccessExpr(sourceLocation, newVar), expr));
newVarMap.Add(callee.Signature.Parameters[i], newVar);
caller.AddLocalVariable(newVar);
}
foreach(var local in callee.LocalVariables)
{
Variable newVar = new Variable($"local_{callNum}_{local.Name}", sourceLocation, VariableRole.Temp);
newVar.Type = local.Type;
newVarMap.Add(local, newVar);
caller.AddLocalVariable(newVar);
}
foreach(var funStmt in callee.Body.Statements)
body.Add(ReplaceVars(funStmt, newVarMap));
callNum++;
}
static private List<IPStmt> ReplaceReturn(IReadOnlyList<IPStmt> body, IPExpr location)
{
List<IPStmt> newBody = new List<IPStmt>();
foreach (IPStmt stmt in body)
{
switch (stmt)
{
case ReturnStmt returnStmt:
newBody.Add(new AssignStmt(returnStmt.SourceLocation, location, returnStmt.ReturnValue));
break;
case CompoundStmt compoundStmt:
List<IPStmt> replace = ReplaceReturn(compoundStmt.Statements, location);
foreach (var statement in replace) newBody.Add(statement);
break;
case IfStmt ifStmt:
IPStmt thenStmt = null;
if (ifStmt.ThenBranch != null)
{
List<IPStmt> replaceThen = ReplaceReturn(ifStmt.ThenBranch.Statements, location);
thenStmt = new CompoundStmt(ifStmt.ThenBranch.SourceLocation, replaceThen);
}
IPStmt elseStmt = null;
if (ifStmt.ElseBranch != null)
{
List<IPStmt> replaceElse = ReplaceReturn(ifStmt.ElseBranch.Statements, location);
elseStmt = new CompoundStmt(ifStmt.ElseBranch.SourceLocation, replaceElse);
}
newBody.Add(new IfStmt(ifStmt.SourceLocation, ifStmt.Condition, thenStmt, elseStmt));
break;
case ReceiveStmt receiveStmt:
foreach(KeyValuePair<PEvent, Function> entry in receiveStmt.Cases)
{
entry.Value.Body = new CompoundStmt(entry.Value.Body.SourceLocation, ReplaceReturn(entry.Value.Body.Statements, location));
entry.Value.Signature.ReturnType = null;
}
break;
case WhileStmt whileStmt:
List<IPStmt> bodyList = new List<IPStmt>();
bodyList.Add(whileStmt.Body);
List<IPStmt> replaceWhile = ReplaceReturn(bodyList, location);
newBody.Add(new WhileStmt(whileStmt.SourceLocation, whileStmt.Condition, new CompoundStmt(whileStmt.Body.SourceLocation, replaceWhile)));
break;
default:
newBody.Add(stmt);
break;
}
}
return newBody;
}
static private void InlineStmt(Function function, IPStmt stmt, List<IPStmt> body)
{
switch (stmt)
{
case AssignStmt assign:
if (assign.Value is FunCallExpr)
{
InlineInFunction(((FunCallExpr) assign.Value).Function);
List<IPStmt> appendToBody = new List<IPStmt>();
GenerateInline(function, ((FunCallExpr) assign.Value).Function, ((FunCallExpr) assign.Value).Arguments, appendToBody, assign.SourceLocation);
appendToBody = ReplaceReturn(appendToBody, assign.Location);
foreach (var statement in appendToBody) body.Add(statement);
}
else
{
body.Add(assign);
}
break;
case CompoundStmt compound:
foreach (var statement in compound.Statements) InlineStmt(function, statement, body);
break;
case FunCallStmt call:
if (call.Function.CanReceive ?? true)
{
InlineInFunction(call.Function);
GenerateInline(function, call.Function, call.ArgsList, body, call.SourceLocation);
}
else
{
body.Add(call);
}
break;
case IfStmt ifStmt:
IPStmt thenStmt = null;
if (ifStmt.ThenBranch != null)
{
List<IPStmt> thenBranch = new List<IPStmt>();
InlineStmt(function, ifStmt.ThenBranch, thenBranch);
thenStmt = new CompoundStmt(ifStmt.ThenBranch.SourceLocation, thenBranch);
}
IPStmt elseStmt = null;
if (ifStmt.ElseBranch != null)
{
List<IPStmt> elseBranch = new List<IPStmt>();
InlineStmt(function, ifStmt.ElseBranch, elseBranch);
elseStmt = new CompoundStmt(ifStmt.ElseBranch.SourceLocation, elseBranch);
}
body.Add(new IfStmt(ifStmt.SourceLocation, ifStmt.Condition, thenStmt, elseStmt));
break;
case WhileStmt whileStmt:
List<IPStmt> bodyList = new List<IPStmt>();
InlineStmt(function, whileStmt.Body, bodyList);
body.Add(new WhileStmt(whileStmt.SourceLocation, whileStmt.Condition, new CompoundStmt(whileStmt.Body.SourceLocation, bodyList)));
break;
default:
body.Add(stmt);
break;
}
}
static private void InlineInFunction(Function function)
{
List<IPStmt> body = new List<IPStmt>();
foreach (var stmt in function.Body.Statements)
{
InlineStmt(function, stmt, body);
}
function.Body = new CompoundStmt(function.Body.SourceLocation, body);
return;
}
static private IPStmt ReplaceVars(IPStmt stmt, Dictionary<Variable,Variable> varMap)
{
if (stmt == null) return null;
switch(stmt)
{
case AddStmt addStmt:
return new AddStmt(addStmt.SourceLocation, ReplaceVars(addStmt.Variable, varMap), ReplaceVars(addStmt.Value, varMap));
case AnnounceStmt announceStmt:
return new AnnounceStmt(announceStmt.SourceLocation, ReplaceVars(announceStmt.PEvent, varMap), ReplaceVars(announceStmt.Payload, varMap));
case AssertStmt assertStmt:
return new AssertStmt(assertStmt.SourceLocation, ReplaceVars(assertStmt.Assertion, varMap), ReplaceVars(assertStmt.Message, varMap));
case AssignStmt assignStmt:
return new AssignStmt(assignStmt.SourceLocation, ReplaceVars(assignStmt.Location, varMap), ReplaceVars(assignStmt.Value, varMap));
case CompoundStmt compoundStmt:
List<IPStmt> statements = new List<IPStmt>();
foreach (var inner in compoundStmt.Statements) statements.Add(ReplaceVars(inner, varMap));
return new CompoundStmt(compoundStmt.SourceLocation, statements);
case CtorStmt ctorStmt:
List<IPExpr> arguments = new List<IPExpr>();
foreach (var arg in ctorStmt.Arguments) arguments.Add(ReplaceVars(arg, varMap));
return new CtorStmt(ctorStmt.SourceLocation, ctorStmt.Interface, arguments);
case FunCallStmt funCallStmt:
List<IPExpr> newArgs = new List<IPExpr>();
foreach (var arg in funCallStmt.ArgsList) newArgs.Add(ReplaceVars(arg, varMap));
return new FunCallStmt(funCallStmt.SourceLocation, funCallStmt.Function, new List<IPExpr>(newArgs));
case GotoStmt gotoStmt:
return new GotoStmt(gotoStmt.SourceLocation, gotoStmt.State, ReplaceVars(gotoStmt.Payload, varMap));
case IfStmt ifStmt:
return new IfStmt(ifStmt.SourceLocation, ReplaceVars(ifStmt.Condition, varMap), ReplaceVars(ifStmt.ThenBranch, varMap), ReplaceVars(ifStmt.ElseBranch, varMap));
case InsertStmt insertStmt:
return new InsertStmt(insertStmt.SourceLocation, ReplaceVars(insertStmt.Variable, varMap), ReplaceVars(insertStmt.Index, varMap), ReplaceVars(insertStmt.Value, varMap));
case MoveAssignStmt moveAssignStmt:
Variable fromVar = moveAssignStmt.FromVariable;
if (varMap.ContainsKey(moveAssignStmt.FromVariable)) fromVar = varMap[moveAssignStmt.FromVariable];
return new MoveAssignStmt(moveAssignStmt.SourceLocation, ReplaceVars(moveAssignStmt.ToLocation, varMap), fromVar);
case PrintStmt printStmt:
return new PrintStmt(printStmt.SourceLocation, ReplaceVars(printStmt.Message, varMap));
case RaiseStmt raiseStmt:
List<IPExpr> payload = new List<IPExpr>();
foreach(var p in raiseStmt.Payload) payload.Add(ReplaceVars(p, varMap));
return new RaiseStmt(raiseStmt.SourceLocation, raiseStmt.PEvent, payload);
case ReceiveStmt receiveStmt:
Dictionary<PEvent, Function> cases = new Dictionary<PEvent, Function>();
foreach(KeyValuePair<PEvent, Function> entry in receiveStmt.Cases)
{
Function replacement = new Function(entry.Value.Name, entry.Value.SourceLocation);
replacement.Owner = entry.Value.Owner;
replacement.ParentFunction = entry.Value.ParentFunction;
replacement.CanReceive = entry.Value.CanReceive;
replacement.Role = entry.Value.Role;
replacement.Scope = entry.Value.Scope;
foreach (var local in entry.Value.LocalVariables) replacement.AddLocalVariable(local);
foreach (var i in entry.Value.CreatesInterfaces) replacement.AddCreatesInterface(i);
foreach (var param in entry.Value.Signature.Parameters) replacement.Signature.Parameters.Add(param);
replacement.Signature.ReturnType = entry.Value.Signature.ReturnType;
foreach (var callee in entry.Value.Callees) replacement.AddCallee(callee);
replacement.Body = (CompoundStmt) ReplaceVars(entry.Value.Body, varMap);
cases.Add(entry.Key, replacement);
}
return new ReceiveStmt(receiveStmt.SourceLocation, cases);
case RemoveStmt removeStmt:
return new RemoveStmt(removeStmt.SourceLocation, ReplaceVars(removeStmt.Variable, varMap), ReplaceVars(removeStmt.Value, varMap));
case ReturnStmt returnStmt:
return new ReturnStmt(returnStmt.SourceLocation, ReplaceVars(returnStmt.ReturnValue, varMap));
case SendStmt sendStmt:
List<IPExpr> sendArgs = new List<IPExpr>();
foreach (var arg in sendStmt.Arguments) sendArgs.Add(ReplaceVars(arg, varMap));
return new SendStmt(sendStmt.SourceLocation, ReplaceVars(sendStmt.MachineExpr, varMap), ReplaceVars(sendStmt.Evt, varMap), sendArgs);
case WhileStmt whileStmt:
return new WhileStmt(whileStmt.SourceLocation, ReplaceVars(whileStmt.Condition, varMap), ReplaceVars(whileStmt.Body, varMap));
default:
return stmt;
}
}
static private IPExpr ReplaceVars(IPExpr expr, Dictionary<Variable,Variable> varMap)
{
switch(expr)
{
case BinOpExpr binOpExpr:
return new BinOpExpr(binOpExpr.SourceLocation, binOpExpr.Operation, ReplaceVars(binOpExpr.Lhs, varMap), ReplaceVars(binOpExpr.Rhs, varMap));
case CastExpr castExpr:
return new CastExpr(castExpr.SourceLocation, ReplaceVars(castExpr.SubExpr, varMap), castExpr.Type);
case ChooseExpr chooseExpr:
return new ChooseExpr(chooseExpr.SourceLocation, ReplaceVars(chooseExpr.SubExpr, varMap), chooseExpr.Type);
case CloneExpr cloneExpr:
return ReplaceVars(cloneExpr.Term, varMap);
case CoerceExpr coerceExpr:
return new CoerceExpr(coerceExpr.SourceLocation, ReplaceVars(coerceExpr.SubExpr, varMap), coerceExpr.NewType);
case ContainsExpr containsExpr:
return new ContainsExpr(containsExpr.SourceLocation, ReplaceVars(containsExpr.Item, varMap), ReplaceVars(containsExpr.Collection, varMap));
case CtorExpr ctorExpr:
List<IPExpr> newArguments = new List<IPExpr>();
foreach (var arg in ctorExpr.Arguments) newArguments.Add(ReplaceVars(arg, varMap));
return new CtorExpr(ctorExpr.SourceLocation, ctorExpr.Interface, new List<IPExpr>(newArguments));
case FunCallExpr funCallExpr:
List<IPExpr> newArgs = new List<IPExpr>();
foreach (var arg in funCallExpr.Arguments) newArgs.Add(ReplaceVars(arg, varMap));
return new FunCallExpr(funCallExpr.SourceLocation, funCallExpr.Function, new List<IPExpr>(newArgs));
case KeysExpr keysExpr:
return new KeysExpr(keysExpr.SourceLocation, ReplaceVars(keysExpr.Expr, varMap), keysExpr.Type);
case MapAccessExpr mapAccessExpr:
return new MapAccessExpr(mapAccessExpr.SourceLocation, ReplaceVars(mapAccessExpr.MapExpr, varMap), ReplaceVars(mapAccessExpr.IndexExpr, varMap), mapAccessExpr.Type);
case NamedTupleAccessExpr namedTupleAccessExpr:
return new NamedTupleAccessExpr(namedTupleAccessExpr.SourceLocation, ReplaceVars(namedTupleAccessExpr.SubExpr, varMap), namedTupleAccessExpr.Entry);
case NamedTupleExpr namedTupleExpr:
List<IPExpr> newFields = new List<IPExpr>();
foreach (var field in namedTupleExpr.TupleFields) newFields.Add(ReplaceVars(field, varMap));
return new NamedTupleExpr(namedTupleExpr.SourceLocation, new List<IPExpr>(newFields), namedTupleExpr.Type);
case SeqAccessExpr seqAccessExpr:
return new SeqAccessExpr(seqAccessExpr.SourceLocation, ReplaceVars(seqAccessExpr.SeqExpr, varMap), ReplaceVars(seqAccessExpr.IndexExpr, varMap), seqAccessExpr.Type);
case SetAccessExpr setAccessExpr:
return new SetAccessExpr(setAccessExpr.SourceLocation, ReplaceVars(setAccessExpr.SetExpr, varMap), ReplaceVars(setAccessExpr.IndexExpr, varMap), setAccessExpr.Type);
case SizeofExpr sizeofExpr:
return new SizeofExpr(sizeofExpr.SourceLocation, ReplaceVars(sizeofExpr.Expr, varMap));
case StringExpr stringExpr:
List<IPExpr> newListArgs = new List<IPExpr>();
foreach (var arg in stringExpr.Args) newListArgs.Add(ReplaceVars(arg, varMap));
return new StringExpr(stringExpr.SourceLocation, stringExpr.BaseString, newListArgs);
case TupleAccessExpr tupleAccessExpr:
return new TupleAccessExpr(tupleAccessExpr.SourceLocation, ReplaceVars(tupleAccessExpr.SubExpr, varMap), tupleAccessExpr.FieldNo, tupleAccessExpr.Type);
case UnaryOpExpr unaryOpExpr:
return new UnaryOpExpr(unaryOpExpr.SourceLocation, unaryOpExpr.Operation, ReplaceVars(unaryOpExpr.SubExpr, varMap));
case UnnamedTupleExpr unnamedTupleExpr:
List<IPExpr> newUnnamedFields = new List<IPExpr>();
foreach (var field in unnamedTupleExpr.TupleFields) newUnnamedFields.Add(ReplaceVars(field, varMap));
return new UnnamedTupleExpr(unnamedTupleExpr.SourceLocation, new List<IPExpr>(newUnnamedFields));
case ValuesExpr valuesExpr:
return new ValuesExpr(valuesExpr.SourceLocation, ReplaceVars(valuesExpr.Expr, varMap), valuesExpr.Type);
case VariableAccessExpr variableAccessExpr:
if (varMap.ContainsKey(variableAccessExpr.Variable))
return new VariableAccessExpr(variableAccessExpr.SourceLocation, varMap[variableAccessExpr.Variable]);
else return variableAccessExpr;
default:
return expr;
}
}
static private Function TransformFunction(Function function, Machine machine)
{
if (function.CanReceive != true) {
return function;
}
if (machine == null)
throw new NotImplementedException($"Async functions {function.Name} are not supported");
Function transformedFunction = new Function(function.Name, function.SourceLocation);
transformedFunction.Owner = function.Owner;
transformedFunction.ParentFunction = function.ParentFunction;
foreach (var local in function.LocalVariables) transformedFunction.AddLocalVariable(local);
foreach (var i in function.CreatesInterfaces) transformedFunction.AddCreatesInterface(i);
transformedFunction.Role = function.Role;
transformedFunction.Body = (CompoundStmt) HandleReceives(function.Body, function, machine);
transformedFunction.Scope = function.Scope;
transformedFunction.CanChangeState = function.CanChangeState;
transformedFunction.CanRaiseEvent = function.CanRaiseEvent;
transformedFunction.CanReceive = function.CanReceive;
transformedFunction.IsNondeterministic = function.IsNondeterministic;
foreach (var param in function.Signature.Parameters) transformedFunction.Signature.Parameters.Add(param);
transformedFunction.Signature.ReturnType = function.Signature.ReturnType;
return transformedFunction;
}
static private IPStmt ReplaceBreaks(IPStmt stmt)
{
if (stmt == null) return null;
switch(stmt)
{
case CompoundStmt compoundStmt:
List<IPStmt> statements = new List<IPStmt>();
foreach (var inner in compoundStmt.Statements)
{
statements.Add(ReplaceBreaks(inner));
}
return new CompoundStmt(compoundStmt.SourceLocation, statements);
case IfStmt ifStmt:
return new IfStmt(ifStmt.SourceLocation, ifStmt.Condition, ReplaceBreaks(ifStmt.ThenBranch), ReplaceBreaks(ifStmt.ElseBranch));
case ReceiveStmt receiveStmt:
Dictionary<PEvent, Function> cases = new Dictionary<PEvent, Function>();
foreach(KeyValuePair<PEvent, Function> entry in receiveStmt.Cases)
{
Function replacement = new Function(entry.Value.Name, entry.Value.SourceLocation);
replacement.Owner = entry.Value.Owner;
replacement.ParentFunction = entry.Value.ParentFunction;
replacement.CanReceive = entry.Value.CanReceive;
replacement.Role = entry.Value.Role;
replacement.Scope = entry.Value.Scope;
foreach (var local in entry.Value.LocalVariables) replacement.AddLocalVariable(local);
foreach (var i in entry.Value.CreatesInterfaces) replacement.AddCreatesInterface(i);
foreach (var param in entry.Value.Signature.Parameters) replacement.Signature.Parameters.Add(param);
replacement.Signature.ReturnType = entry.Value.Signature.ReturnType;
foreach (var callee in entry.Value.Callees) replacement.AddCallee(callee);
replacement.Body = (CompoundStmt) ReplaceBreaks(entry.Value.Body);
cases.Add(entry.Key, replacement);
}
return new ReceiveStmt(receiveStmt.SourceLocation, cases);
case BreakStmt _:
return new ReturnStmt(stmt.SourceLocation, null);
default:
return stmt;
}
}
static private IPStmt HandleReceives(IPStmt statement, Function function, Machine machine)
{
switch (statement)
{
case CompoundStmt compound:
IEnumerator<IPStmt> enumerator = compound.Statements.GetEnumerator();
if (enumerator.MoveNext())
{
IPStmt first = enumerator.Current;
List<IPStmt> afterStmts = new List<IPStmt>();
while (enumerator.MoveNext())
{
afterStmts.Add(enumerator.Current);
}
CompoundStmt after = null;
if (afterStmts.Count > 0)
{
after = new CompoundStmt(afterStmts[0].SourceLocation, afterStmts);
after = (CompoundStmt) HandleReceives(after, function, machine);
}
List<IPStmt> result = new List<IPStmt>();
switch (first)
{
case CompoundStmt nestedCompound:
List<IPStmt> compoundStmts = new List<IPStmt>(nestedCompound.Statements);
foreach (var stmt in afterStmts)
{
compoundStmts.Add(stmt);
}
result.Add(HandleReceives(new CompoundStmt(nestedCompound.SourceLocation, compoundStmts), function, machine));
break;
case IfStmt cond:
List<IPStmt> thenStmts = new List<IPStmt>();
List<IPStmt> elseStmts = new List<IPStmt>();
if (cond.ThenBranch != null)
thenStmts = new List<IPStmt>(cond.ThenBranch.Statements);
if (cond.ElseBranch != null)
elseStmts = new List<IPStmt>(cond.ElseBranch.Statements);
foreach (var stmt in afterStmts)
{
thenStmts.Add(stmt);
elseStmts.Add(stmt);
}
CompoundStmt thenBody = new CompoundStmt(cond.SourceLocation, thenStmts);
CompoundStmt elseBody = new CompoundStmt(cond.SourceLocation, elseStmts);
result.Add(new IfStmt(cond.SourceLocation, cond.Condition, HandleReceives(thenBody, function, machine), HandleReceives(elseBody, function, machine)));
break;
case ReceiveStmt recv:
IDictionary<PEvent, Function> cases = new Dictionary<PEvent, Function>();
foreach (KeyValuePair<PEvent, Function> c in recv.Cases)
{
c.Value.AddLocalVariables(function.Signature.Parameters);
c.Value.AddLocalVariables(function.LocalVariables);
cases.Add(c.Key, TransformFunction(c.Value, machine));
}
Continuation continuation = GetContinuation(function, cases, after, recv.SourceLocation);
if (machine != null) machine.AddMethod(continuation);
foreach (Variable v in continuation.StoreParameters)
{
machine.AddField(v);
}
foreach (AssignStmt store in continuation.StoreStmts)
{
result.Add(store);
}
ReceiveSplitStmt split = new ReceiveSplitStmt(compound.SourceLocation, continuation);
result.Add(split);
break;
case WhileStmt loop:
// turn the while statement into a recursive function
WhileFunction rec = new WhileFunction(loop.SourceLocation);
rec.Owner = function.Owner;
rec.ParentFunction = function;
foreach (var param in function.Signature.Parameters) rec.AddParameter(param);
Dictionary<Variable,Variable> newVarMap = new Dictionary<Variable,Variable>();
foreach (var local in function.LocalVariables)
{
Variable machineVar = new Variable($"while_{whileNumber}_{local.Name}", local.SourceLocation, local.Role);
machineVar.Type = local.Type;
machine.AddField(machineVar);
newVarMap.Add(local, machineVar);
}
foreach (var i in function.CreatesInterfaces) rec.AddCreatesInterface(i);
rec.CanChangeState = function.CanChangeState;
rec.CanRaiseEvent = function.CanRaiseEvent;
rec.CanReceive = function.CanReceive;
rec.IsNondeterministic = function.IsNondeterministic;
// make while loop body
List<IPStmt> loopBody = new List<IPStmt>();
IEnumerator<IPStmt> bodyEnumerator = loop.Body.Statements.GetEnumerator();
while (bodyEnumerator.MoveNext())
{
IPStmt stmt = bodyEnumerator.Current;
IPStmt replaceBreak = ReplaceBreaks(stmt);
if (replaceBreak != null) {
loopBody.Add(ReplaceVars(replaceBreak, newVarMap));
}
}
List<VariableAccessExpr> recArgs = new List<VariableAccessExpr>();
foreach (var param in rec.Signature.Parameters)
{
recArgs.Add(new VariableAccessExpr(rec.SourceLocation, param));
}
// call the function
FunCallStmt recCall = new FunCallStmt(loop.SourceLocation, rec, recArgs);
loopBody = new List<IPStmt>(((CompoundStmt) HandleReceives(new CompoundStmt(rec.SourceLocation, loopBody), rec, machine)).Statements);
rec.Body = new CompoundStmt(rec.SourceLocation, loopBody);
if (machine != null) machine.AddMethod(rec);
// assign local variables
foreach (var local in function.LocalVariables)
{
result.Add(new AssignStmt(local.SourceLocation, new VariableAccessExpr(local.SourceLocation, newVarMap[local]), new VariableAccessExpr(local.SourceLocation, local)));
}
// replace the while statement with a function call
result.Add(recCall);
if (after != null)
{
foreach (var stmt in after.Statements)
{
result.Add(ReplaceVars(stmt, newVarMap));
}
}
whileNumber++;
break;
default:
if (after == null) return compound;
result.Add(first);
foreach (IPStmt stmt in after.Statements) result.Add(HandleReceives(stmt, function, machine));
break;
}
return new CompoundStmt(compound.SourceLocation, result);
}
return compound;
/*
case FunCallStmt call:
Function callee = TransformFunction(callee, machine);
FunCallStmt newCall = new FunCallStmt(SourceLocation, callee, call.ArgsList);
function.AddCallee(callee);
return newCall;
*/
default:
return statement;
}
}
static private Continuation GetContinuation(Function function, IDictionary<PEvent, Function> cases, IPStmt after, ParserRuleContext location)
{
Continuation continuation = new Continuation(new Dictionary<PEvent, Function>(cases), after, location);
continuation.ParentFunction = function;
function.AddCallee(continuation);
function.Role = FunctionRole.Method;
foreach (var v in function.Signature.Parameters) {
Variable local = new Variable(v.Name, v.SourceLocation, v.Role);
Variable store = new Variable($"continuation_{continuationNumber}_{v.Name}", v.SourceLocation, v.Role);
local.Type = v.Type;
store.Type = v.Type;
continuation.AddParameter(local, store);
}
foreach (var v in function.LocalVariables)
{
Variable local = new Variable(v.Name, v.SourceLocation, v.Role);
Variable store = new Variable($"continuation_{continuationNumber}_{v.Name}", v.SourceLocation, v.Role);
local.Type = v.Type;
store.Type = v.Type;
continuation.AddParameter(local, store);
}
continuation.CanChangeState = function.CanChangeState;
continuation.CanRaiseEvent = function.CanRaiseEvent;
continuation.Signature.ReturnType = function.Signature.ReturnType;
continuationNumber++;
return continuation;
}
}
}
| 58.825493 | 203 | 0.54393 | [
"MIT"
] | aman-goel/P | Src/PCompiler/CompilerCore/Backend/Symbolic/TransformASTPass.cs | 38,766 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using OrchardCore.ContentManagement.Display.ContentDisplay;
using OrchardCore.ContentManagement.Display.Models;
using OrchardCore.ContentManagement.Metadata.Models;
using OrchardCore.DisplayManagement.ModelBinding;
using OrchardCore.DisplayManagement.Views;
using OrchardCore.Media.Fields;
using OrchardCore.Media.Services;
using OrchardCore.Media.Settings;
using OrchardCore.Media.ViewModels;
using OrchardCore.Mvc.ModelBinding;
namespace OrchardCore.Media.Drivers
{
public class MediaFieldDisplayDriver : ContentFieldDisplayDriver<MediaField>
{
private static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
private readonly AttachedMediaFieldFileService _attachedMediaFieldFileService;
private readonly IStringLocalizer S;
private readonly ILogger _logger;
public MediaFieldDisplayDriver(AttachedMediaFieldFileService attachedMediaFieldFileService,
IStringLocalizer<MediaFieldDisplayDriver> localizer,
ILogger<MediaFieldDisplayDriver> logger)
{
_attachedMediaFieldFileService = attachedMediaFieldFileService;
S = localizer;
_logger = logger;
}
public override IDisplayResult Display(MediaField field, BuildFieldDisplayContext context)
{
return Initialize<DisplayMediaFieldViewModel>(GetDisplayShapeType(context), model =>
{
model.Field = field;
model.Part = context.ContentPart;
model.PartFieldDefinition = context.PartFieldDefinition;
})
.Location("Detail", "Content")
.Location("Summary", "Content");
}
public override IDisplayResult Edit(MediaField field, BuildFieldEditorContext context)
{
var itemPaths = field.Paths?.ToList().Select(p => new EditMediaFieldItemInfo { Path = p }).ToArray() ?? Array.Empty<EditMediaFieldItemInfo>();
return Initialize<EditMediaFieldViewModel>(GetEditorShapeType(context), model =>
{
var settings = context.PartFieldDefinition.GetSettings<MediaFieldSettings>();
if (settings.AllowMediaText)
{
if (field.MediaTexts != null)
{
for (var i = 0; i < itemPaths.Count(); i++)
{
if (i >= 0 && i < field.MediaTexts.Length)
{
itemPaths[i].MediaText = field.MediaTexts[i];
}
}
}
}
if (settings.AllowAnchors)
{
var anchors = field.GetAnchors();
if (anchors != null)
{
for (var i = 0; i < itemPaths.Count(); i++)
{
if (i >= 0 && i < anchors.Length)
{
itemPaths[i].Anchor = anchors[i];
}
}
}
}
model.Paths = JsonConvert.SerializeObject(itemPaths, Settings);
model.TempUploadFolder = _attachedMediaFieldFileService.MediaFieldsTempSubFolder;
model.Field = field;
model.Part = context.ContentPart;
model.PartFieldDefinition = context.PartFieldDefinition;
model.AllowMediaText = settings.AllowMediaText;
});
}
public override async Task<IDisplayResult> UpdateAsync(MediaField field, IUpdateModel updater, UpdateFieldEditorContext context)
{
var model = new EditMediaFieldViewModel();
if (await updater.TryUpdateModelAsync(model, Prefix, f => f.Paths))
{
// Deserializing an empty string doesn't return an array
var items = string.IsNullOrWhiteSpace(model.Paths)
? new List<EditMediaFieldItemInfo>()
: JsonConvert.DeserializeObject<EditMediaFieldItemInfo[]>(model.Paths, Settings).ToList();
// If it's an attached media field editor the files are automatically handled by _attachedMediaFieldFileService
if (string.Equals(context.PartFieldDefinition.Editor(), "Attached", StringComparison.OrdinalIgnoreCase))
{
try
{
await _attachedMediaFieldFileService.HandleFilesOnFieldUpdateAsync(items, context.ContentPart.ContentItem);
}
catch (Exception e)
{
updater.ModelState.AddModelError(Prefix, nameof(model.Paths), S["{0}: There was an error handling the files.", context.PartFieldDefinition.DisplayName()]);
_logger.LogError(e, "Error handling attached media files for field '{Field}'", context.PartFieldDefinition.DisplayName());
}
}
field.Paths = items.Where(p => !p.IsRemoved).Select(p => p.Path).ToArray() ?? new string[] { };
var settings = context.PartFieldDefinition.GetSettings<MediaFieldSettings>();
if (settings.Required && field.Paths.Length < 1)
{
updater.ModelState.AddModelError(Prefix, nameof(model.Paths), S["{0}: A media is required.", context.PartFieldDefinition.DisplayName()]);
}
if (field.Paths.Length > 1 && !settings.Multiple)
{
updater.ModelState.AddModelError(Prefix, nameof(model.Paths), S["{0}: Selecting multiple media is forbidden.", context.PartFieldDefinition.DisplayName()]);
}
if (settings.AllowMediaText)
{
field.MediaTexts = items.Select(t => t.MediaText).ToArray();
}
else
{
field.MediaTexts = Array.Empty<string>();
}
if (settings.AllowAnchors)
{
field.SetAnchors(items.Select(t => t.Anchor).ToArray());
}
else if (field.Content.ContainsKey("Anchors")) // Less well known properties should be self healing.
{
field.Content.Remove("Anchors");
}
}
return Edit(field, context);
}
}
}
| 42.679012 | 179 | 0.569858 | [
"BSD-3-Clause"
] | CityofSantaMonica/OrchardCore | src/OrchardCore.Modules/OrchardCore.Media/Drivers/MediaFieldDriver.cs | 6,914 | C# |
using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.Linq;
namespace UF.Profiling {
public static class Profiler {
static profiler() {
Stopwatch = new Stopwatch();
EnabledBuckets = new List<string>();
ActiveTimers = new Stack<ActiveTimer>();
LogLag = false;
Stopwatch.Start();
}
private static Stopwatch Stopwatch { get; set; }
private static List<string> EnabledBuckets { get; set; }
private static Stack<ActiveTimer> ActiveTimers { get; set; }
private static object Lock = new object();
public static bool LogLag { get; set; }
private struct ActiveTimer {
public long Started, Finished;
public string Bucket;
}
[Conditional("DEBUG")]
public static void EnableBucket(string bucket) {
EnabledBuckets.Add(bucket);
}
[Conditional("DEBUG")]
public static void DisableBucket(string bucket) {
EnabledBuckets.Remove(bucket);
}
[Conditional("DEBUG")]
public static void Start(string bucket) {
lock (Lock) {
ActiveTimers.Push(new ActiveTimer {
Started = Stopwatch.ElapsedTicks,
Finished = -1,
bucket = bucket
});
}
}
[Conditional("DEBUG")]
public static void Done(long lag = -1) {
lock (Lock) {
if (ActiveTimers.Count > 0) {
var timer = ActiveTimers.Pop();
timer.Finished = Stopwatch.ElapsedTicks;
double elapsed = (timer.Finished - timer.Started) / 10000.0;
for (int i = 0; i < EnabledBuckets.Count; i++) {
if (Match(EnabledBuckets[i], timer.Bucket)) {
Console.WriteLine("{0} took {1}ms", timer.Bucket, elapsed);
break;
}
}
if (LogLag && lag != -1 && elapsed > lag)
Console.WriteLine("{0} is lagging by {1}ms", timer.Bucket, elapsed);
}
}
}
private static bool Match(string mask, string value) {
if (value == null)
value = string.Empty;
int i = 0;
int j = 0;
for (; j < value.Length && i < mask.Length; j++) {
if (mask[i] == "?")
i++;
else if (mask[i] == "*") {
i++;
if (i >= mask.Length)
return true;
while (++j < value.Length && value[j] != mask[i]);
if (j-- == value.Length) {
return false;
}
}
else {
if (char.ToUpper(mask[i]) != char.ToUpper(value[j]))
return false;
i++;
}
}
return i == mask.Length && j == value.Length;
}
}
} | 31.772277 | 92 | 0.444998 | [
"MIT"
] | InternalRBLX/UltimateFootball | UF.Profiling/Profiler.cs | 3,209 | C# |
using Omu.ValueInjecter;
using System.Web.Profile;
namespace Lightweight.Web.Mappings
{
public class ProfileBaseInjection : KnownTargetValueInjection<ProfileBase>
{
protected override void Inject(object source, ref ProfileBase target)
{
foreach (var prop in source.GetInfos())
target.SetPropertyValue(prop.Name, prop.GetValue(source));
}
}
} | 29.071429 | 78 | 0.68059 | [
"MIT"
] | noir2501/lightweight | src/Lightweight.Web/Mappings/UserProfileInjections.cs | 409 | C# |
using UnityEngine;
using System;
using System.Collections;
[Serializable]
public struct CellInfo
{
public Sprite sprite;
}
| 13.8 | 26 | 0.717391 | [
"MIT"
] | TannerPR/LPGJ4 | Alexandria Is Burning/Assets/Scripts/CellInfo.cs | 140 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.IO;
using System.Runtime.Serialization;
using System.Text;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using System.ComponentModel.DataAnnotations;
using OpenAPIDateConverter = Cloud.Governance.Client.Client.OpenAPIDateConverter;
namespace Cloud.Governance.Client.Model
{
/// <summary>
/// GuestUserPropertyModel
/// </summary>
[DataContract(Name = "GuestUserPropertyModel")]
public partial class GuestUserPropertyModel : IEquatable<GuestUserPropertyModel>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="GuestUserPropertyModel" /> class.
/// </summary>
/// <param name="displayName">displayName.</param>
/// <param name="firstName">firstName.</param>
/// <param name="lastName">lastName.</param>
/// <param name="userName">userName.</param>
/// <param name="usageLocation">usageLocation.</param>
/// <param name="usageLocationDisplayName">usageLocationDisplayName.</param>
/// <param name="jobTitle">jobTitle.</param>
/// <param name="jobDepartment">jobDepartment.</param>
/// <param name="manager">ApiUser model.</param>
/// <param name="companyName">companyName.</param>
public GuestUserPropertyModel(string displayName = default(string), string firstName = default(string), string lastName = default(string), string userName = default(string), string usageLocation = default(string), string usageLocationDisplayName = default(string), string jobTitle = default(string), string jobDepartment = default(string), ApiUser manager = default(ApiUser), string companyName = default(string))
{
this.DisplayName = displayName;
this.FirstName = firstName;
this.LastName = lastName;
this.UserName = userName;
this.UsageLocation = usageLocation;
this.UsageLocationDisplayName = usageLocationDisplayName;
this.JobTitle = jobTitle;
this.JobDepartment = jobDepartment;
this.Manager = manager;
this.CompanyName = companyName;
}
/// <summary>
/// Gets or Sets DisplayName
/// </summary>
[DataMember(Name = "displayName", EmitDefaultValue = true)]
public string DisplayName { get; set; }
/// <summary>
/// Gets or Sets FirstName
/// </summary>
[DataMember(Name = "firstName", EmitDefaultValue = true)]
public string FirstName { get; set; }
/// <summary>
/// Gets or Sets LastName
/// </summary>
[DataMember(Name = "lastName", EmitDefaultValue = true)]
public string LastName { get; set; }
/// <summary>
/// Gets or Sets UserName
/// </summary>
[DataMember(Name = "userName", EmitDefaultValue = true)]
public string UserName { get; set; }
/// <summary>
/// Gets or Sets UsageLocation
/// </summary>
[DataMember(Name = "usageLocation", EmitDefaultValue = true)]
public string UsageLocation { get; set; }
/// <summary>
/// Gets or Sets UsageLocationDisplayName
/// </summary>
[DataMember(Name = "usageLocationDisplayName", EmitDefaultValue = true)]
public string UsageLocationDisplayName { get; set; }
/// <summary>
/// Gets or Sets JobTitle
/// </summary>
[DataMember(Name = "jobTitle", EmitDefaultValue = true)]
public string JobTitle { get; set; }
/// <summary>
/// Gets or Sets JobDepartment
/// </summary>
[DataMember(Name = "jobDepartment", EmitDefaultValue = true)]
public string JobDepartment { get; set; }
/// <summary>
/// ApiUser model
/// </summary>
/// <value>ApiUser model</value>
[DataMember(Name = "manager", EmitDefaultValue = true)]
public ApiUser Manager { get; set; }
/// <summary>
/// Gets or Sets CompanyName
/// </summary>
[DataMember(Name = "companyName", EmitDefaultValue = true)]
public string CompanyName { 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 GuestUserPropertyModel {\n");
sb.Append(" DisplayName: ").Append(DisplayName).Append("\n");
sb.Append(" FirstName: ").Append(FirstName).Append("\n");
sb.Append(" LastName: ").Append(LastName).Append("\n");
sb.Append(" UserName: ").Append(UserName).Append("\n");
sb.Append(" UsageLocation: ").Append(UsageLocation).Append("\n");
sb.Append(" UsageLocationDisplayName: ").Append(UsageLocationDisplayName).Append("\n");
sb.Append(" JobTitle: ").Append(JobTitle).Append("\n");
sb.Append(" JobDepartment: ").Append(JobDepartment).Append("\n");
sb.Append(" Manager: ").Append(Manager).Append("\n");
sb.Append(" CompanyName: ").Append(CompanyName).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as GuestUserPropertyModel);
}
/// <summary>
/// Returns true if GuestUserPropertyModel instances are equal
/// </summary>
/// <param name="input">Instance of GuestUserPropertyModel to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(GuestUserPropertyModel input)
{
if (input == null)
return false;
return
(
this.DisplayName == input.DisplayName ||
(this.DisplayName != null &&
this.DisplayName.Equals(input.DisplayName))
) &&
(
this.FirstName == input.FirstName ||
(this.FirstName != null &&
this.FirstName.Equals(input.FirstName))
) &&
(
this.LastName == input.LastName ||
(this.LastName != null &&
this.LastName.Equals(input.LastName))
) &&
(
this.UserName == input.UserName ||
(this.UserName != null &&
this.UserName.Equals(input.UserName))
) &&
(
this.UsageLocation == input.UsageLocation ||
(this.UsageLocation != null &&
this.UsageLocation.Equals(input.UsageLocation))
) &&
(
this.UsageLocationDisplayName == input.UsageLocationDisplayName ||
(this.UsageLocationDisplayName != null &&
this.UsageLocationDisplayName.Equals(input.UsageLocationDisplayName))
) &&
(
this.JobTitle == input.JobTitle ||
(this.JobTitle != null &&
this.JobTitle.Equals(input.JobTitle))
) &&
(
this.JobDepartment == input.JobDepartment ||
(this.JobDepartment != null &&
this.JobDepartment.Equals(input.JobDepartment))
) &&
(
this.Manager == input.Manager ||
(this.Manager != null &&
this.Manager.Equals(input.Manager))
) &&
(
this.CompanyName == input.CompanyName ||
(this.CompanyName != null &&
this.CompanyName.Equals(input.CompanyName))
);
}
/// <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.DisplayName != null)
hashCode = hashCode * 59 + this.DisplayName.GetHashCode();
if (this.FirstName != null)
hashCode = hashCode * 59 + this.FirstName.GetHashCode();
if (this.LastName != null)
hashCode = hashCode * 59 + this.LastName.GetHashCode();
if (this.UserName != null)
hashCode = hashCode * 59 + this.UserName.GetHashCode();
if (this.UsageLocation != null)
hashCode = hashCode * 59 + this.UsageLocation.GetHashCode();
if (this.UsageLocationDisplayName != null)
hashCode = hashCode * 59 + this.UsageLocationDisplayName.GetHashCode();
if (this.JobTitle != null)
hashCode = hashCode * 59 + this.JobTitle.GetHashCode();
if (this.JobDepartment != null)
hashCode = hashCode * 59 + this.JobDepartment.GetHashCode();
if (this.Manager != null)
hashCode = hashCode * 59 + this.Manager.GetHashCode();
if (this.CompanyName != null)
hashCode = hashCode * 59 + this.CompanyName.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| 40.775665 | 421 | 0.549608 | [
"Apache-2.0"
] | AvePoint/cloud-governance-client | csharp-netstandard/src/Cloud.Governance.Client/Model/GuestUserPropertyModel.cs | 10,724 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// Food motion - rotates the object around the Y axis.
/// </summary>
public class FoodMotion : MonoBehaviour
{
float speed = 20f;
void Update()
{
transform.Rotate(Vector3.down, Time.deltaTime * speed * 5);
}
}
| 19.529412 | 67 | 0.671687 | [
"Apache-2.0"
] | TejusWadbudhe/Snake-Game---VAM-Club | Assets/Codelab/Scripts/FoodMotion.cs | 334 | C# |
using Blitz.RabbitMq.Library.Libs;
using Blitz.RabbitMq.Library.Models;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System;
using System.Collections.Generic;
using System.Text;
namespace Blitz.RabbitMq.Library
{
/// <summary>
/// Client: RabbitMQ Blitzkrieg Style
/// </summary>
public class RabbitMQClient : IQueueEngine
{
private readonly ILogger _logger;
private readonly IConfigurationRoot _config;
private readonly RabbitMqEngineConfiguration _engineConfiguration;
// Default CTOR not allowed
private RabbitMQClient() { }
/// <summary>
/// CTOR
/// </summary>
/// <param name="logger">ILogger</param>
/// <param name="config">IConfigurationRoot</param>
public RabbitMQClient(ILogger logger, IConfigurationRoot config)
{
this._logger = logger;
this._config = config;
this._engineConfiguration = RabbitMqEngineConfiguration.CreateDefault();
foreach (var c in this._config.AsEnumerable())
{
this._engineConfiguration.SetProperty(c.Key, c.Value);
}
this._logger.LogDebug(this._engineConfiguration.ToString());
}
/// <summary>
/// Keep Listening
/// </summary>
public bool KeepListening { get; set; } = true;
/// <summary>
/// Dequeue a message
/// </summary>
/// <param name="queueConfiguration">(sic)</param>
/// <param name="handler">QueueMessageHandler</param>
public void SetupDequeueEvent(Models.RabbitMqInstanceConfiguration queueConfiguration, QueueMessageHandler handler)
{
var factory = RabbitMqUtility.RabbitMQMakeConnectionFactory(this._engineConfiguration.Host, this._engineConfiguration.Port, this._engineConfiguration.Username, this._engineConfiguration.Password);
using (var connection = factory.CreateConnection())
{
using (var model = connection.CreateModel())
{
RabbitMqUtility.SetupDurableQueue(model, this._engineConfiguration, queueConfiguration);
var consumer = new EventingBasicConsumer(model);
consumer.Received += (_, ea) =>
{
handler(this, this._logger, model, ea);
};
model.BasicConsume(queue: queueConfiguration.QueueName,
autoAck: false,
consumer: consumer);
while (this.KeepListening) { }
}
}
}
/// <summary>
/// Enqueue message
/// </summary>
/// <typeparam name="T">T</typeparam>
/// <param name="message">Message of T</param>
/// <param name="queueConfiguration">RabbitMqInstanceConfiguration</param>
/// <param name="delayMilliseconds">Milliseconds to delay, default zero</param>
public void Enqueue<T>(T message, Models.RabbitMqInstanceConfiguration queueConfiguration, int delayMilliseconds = 0)
{
var factory = RabbitMqUtility.RabbitMQMakeConnectionFactory(this._engineConfiguration.Host, this._engineConfiguration.Port, this._engineConfiguration.Username, this._engineConfiguration.Password);
using (var connection = factory.CreateConnection())
{
using (IModel model = connection.CreateModel())
{
RabbitMqUtility.SetupDurableQueue(model, this._engineConfiguration, queueConfiguration);
var messageProperties = RabbitMqUtility.MessageBasicPropertiesPersistant(model, this._engineConfiguration.MessageDeliveryMode, this._engineConfiguration.MessagePersistent, this._engineConfiguration.MessageExpiration);
messageProperties.Headers = new Dictionary<string, object>();
// Deliver in the future
if(delayMilliseconds > 0)
{
messageProperties.Headers.Add("x-delay", delayMilliseconds);
}
// Make message
var json = JsonConvert.SerializeObject(message);
var body = Encoding.UTF8.GetBytes(json);
// Send message
RabbitMqUtility.Publish(model, queueConfiguration.ExchangeName, queueConfiguration.RoutingKey, messageProperties, body);
this._logger.LogInformation("Published: {0}", json);
}
}
}
/// <summary>
/// Ack/Nack/Reject Message (must be called by the <c>QueueMessageHandler</c>
/// </summary>
/// <param name="model">IModel</param>
/// <param name="ea">BasicDeliverEventArgs</param>
/// <param name="state">ReceivedMessageState</param>
public void SendResponse(IModel model, BasicDeliverEventArgs ea, ReceivedMessageState state)
{
if (model == null) throw new ArgumentNullException(nameof(model));
if (ea == null) throw new ArgumentNullException(nameof(ea));
switch (state)
{
case ReceivedMessageState.SuccessfullyProcessed:
// Success remove from queue
model.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false);
break;
case ReceivedMessageState.UnsuccessfulProcessing:
// Unsuccessful, requeue and retry
model.BasicNack(deliveryTag: ea.DeliveryTag, multiple: false, requeue: true);
break;
default:
// Bad Message, Reject and Delete
model.BasicReject(deliveryTag: ea.DeliveryTag, requeue: false);
break;
}
}
/// <summary>
/// Delete all message in a queue (Purge)
/// </summary>
/// <param name="queueConfiguration">QueueInstanceConfiguration</param>
public void PurgeQueue(Models.RabbitMqInstanceConfiguration queueConfiguration)
{
if (queueConfiguration == null) throw new ArgumentNullException(nameof(queueConfiguration));
var factory = Libs.RabbitMqUtility.RabbitMQMakeConnectionFactory(this._engineConfiguration.Host, this._engineConfiguration.Port, this._engineConfiguration.Username, this._engineConfiguration.Password);
using (var connection = factory.CreateConnection())
{
using (IModel model = connection.CreateModel())
{
try
{
model.QueuePurge(queueConfiguration.QueueName);
}
catch { }
}
}
}
}
}
| 40.5 | 237 | 0.590322 | [
"MIT"
] | BlitzkriegSoftware/queues-reliability | Blitz.RabbitMq.Library/RabbitMQClient.cs | 7,049 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public enum ResampleType
{
Linear,
Lanczos,
FSRLanczos,
};
public class SignalCommonDef : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}
| 14.269231 | 52 | 0.630728 | [
"MIT"
] | ouerkakaChango/UnityRayTraceGitee | TestRayTrace/Assets/Scripts/Signal/SignalCommonDef.cs | 371 | C# |
/*
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. See License.txt in the project root for license information.
*/
using System.Web.Mvc;
namespace Site.Areas.Forums
{
public class ForumsAreaRegistration : AreaRegistration
{
public override string AreaName
{
get { return "Forums"; }
}
public override void RegisterArea(AreaRegistrationContext context)
{
}
}
}
| 19.409091 | 94 | 0.740047 | [
"MIT"
] | Adoxio/xRM-Portals-Community-Edition | Samples/MasterPortal/Areas/Forums/ForumsAreaRegistration.cs | 427 | C# |
namespace Weather.Common.Models;
public readonly record struct TemperatureDetails(
Temperature Temperature,
Temperature? FeelsLike,
Temperature? TemperatureLow,
Temperature? TemperatureHigh,
double Pressure,
double Humidity); | 27.777778 | 49 | 0.772 | [
"MIT"
] | JerrettDavis/weather-cli | src/Weather/Common/Models/TemperatureDetails.cs | 250 | C# |
// /*
// Copyright 2008-2011 Alex Robson
//
// 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 Symbiote.Core.Extensions;
using Symbiote.Redis.Impl.Connection;
namespace Symbiote.Redis.Impl.Command
{
public class GetCommand<TValue>
: RedisCommand<TValue>
{
protected const string GET = "GET {0}\r\n";
protected string Key { get; set; }
public TValue Get( IConnection connection )
{
var data = connection.SendExpectData( null, GET.AsFormat( Key ) );
return Deserialize<TValue>( data );
}
public GetCommand( string key )
{
Key = key;
Command = Get;
}
}
} | 30.923077 | 78 | 0.651741 | [
"Apache-2.0"
] | code-attic/Symbiote | src/Symbiote.Redis/Impl/Command/GetCommand.cs | 1,208 | 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("Dropio.Core")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Dropio.Core")]
[assembly: AssemblyCopyright("Copyright © 2008")]
[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("75ba5aee-52fa-47db-95d4-08b2c35bce53")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.702703 | 84 | 0.743369 | [
"MIT"
] | AliSharafi/dropio_api_csharp | Dropio.Core/Properties/AssemblyInfo.cs | 1,398 | C# |
using System.Reflection;
using System.Security;
[assembly: AssemblyProduct("Common Logging Framework Event Tracing for Windows Logger Adapter")]
[assembly: SecurityTransparent]
| 29.833333 | 96 | 0.821229 | [
"Apache-2.0"
] | Defee/common-logging | src/Common.Logging.ETWLogger/AssemblyInfo.cs | 181 | C# |
using System.Collections.Generic;
using XiaoLin.VNADS.Roles.Dto;
namespace XiaoLin.VNADS.Web.Models.Common
{
public interface IPermissionsEditViewModel
{
List<FlatPermissionDto> Permissions { get; set; }
}
} | 22.9 | 57 | 0.733624 | [
"MIT"
] | hunghv/Xiaolin.VNADS | aspnet-core/src/XiaoLin.VNADS.Web.Mvc/Models/Common/IPermissionsEditViewModel.cs | 231 | C# |
using Microsoft.Practices.Unity;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
namespace BlogBackendService.App_Start
{
public class WebApiUnityActionFilterProvider : ActionDescriptorFilterProvider, IFilterProvider
{
private readonly IUnityContainer _container;
public WebApiUnityActionFilterProvider(IUnityContainer container)
{
_container = container;
}
public new IEnumerable<FilterInfo> GetFilters(HttpConfiguration configuration, HttpActionDescriptor actionDescriptor)
{
var filters = base.GetFilters(configuration, actionDescriptor);
var filterInfoList = new List<FilterInfo>();
foreach (var filter in filters)
{
_container.BuildUp(filter.Instance.GetType(), filter.Instance);
}
return filters;
}
public static void RegisterFilterProviders(HttpConfiguration config)
{
var providers = config.Services.GetFilterProviders().ToList();
config.Services.Add(typeof(System.Web.Http.Filters.IFilterProvider), new WebApiUnityActionFilterProvider(UnityConfiguration.GetContainer()));
var defaultprovider = providers.First(p => p is ActionDescriptorFilterProvider);
config.Services.Remove(typeof(System.Web.Http.Filters.IFilterProvider), defaultprovider);
}
}
}
| 36.536585 | 153 | 0.698264 | [
"MIT"
] | QuinntyneBrown/blog-backend-service | BlogBackendService/App_Start/WebApiUnityActionFilterProvider.cs | 1,498 | C# |
namespace mdoc.Test.SampleClasses
{
public struct SomeStruct
{
public int IntMember;
public static int StaticMember;
public TestClass TestClassMember;
}
} | 21.222222 | 41 | 0.664921 | [
"MIT"
] | JeffABC/api-doc-tools | mdoc/mdoc.Test/SampleClasses/SomeStruct.cs | 193 | C# |
namespace _10.Tuple
{
public class Tuple<T, U, V>
{
private T item1;
private U item2;
private V item3;
public Tuple(T item1, U item2, V item3)
{
this.Item1 = item1;
this.Item2 = item2;
this.Item3 = item3;
}
public T Item1 { get { return this.item1; } set { this.item1 = value; } }
public U Item2 { get { return this.item2; } set { this.item2 = value; } }
public V Item3 { get { return this.item3; } set { this.item3 = value; } }
public override string ToString()
{
return $"{this.Item1} -> {this.Item2} -> {this.Item3}";
}
}
}
| 24.892857 | 81 | 0.499283 | [
"MIT"
] | nikolaydechev/CSharp-OOP-Advanced | 02 Generics/10. Tuple/Tuple.cs | 699 | C# |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using vdo.trias;
using DateTime = System.DateTime;
namespace DerMistkaefer.DvbLive.TriasCommunication.Data
{
/// <summary>
/// Response Structure for an Stop Event Request
/// </summary>
public class StopEventResponse
{
/// <summary>
/// Id of the requested stop point.
/// </summary>
public string IdStopPoint { get; }
/// <summary>
/// Stop Events that are on the stop point.
/// </summary>
public IReadOnlyList<StopEventResult> StopEvents { get; }
internal StopEventResponse(string idStopPoint, IReadOnlyList<StopEventResult> stopEvents)
{
IdStopPoint = idStopPoint;
StopEvents = stopEvents;
}
internal StopEventResponse(StopEventResponseStructure response, string idStopPoint)
{
IdStopPoint = idStopPoint;
StopEvents = response.StopEventResult.Select(x => new StopEventResult(x)).ToList();
}
}
/// <summary>
/// One stop event in a <see cref="StopEventResponse"/>
/// </summary>
public class StopEventResult
{
/// <summary>
/// Refernece for the Operating Day of the journey.
/// </summary>
public DateTime OperatingDayRef { get; }
/// <summary>
/// Reference for the journey.
/// </summary>
public string JourneyRef { get; }
/// <summary>
/// Reference for the line.
/// </summary>
public string LineRef { get; }
/// <summary>
/// Name of the mode of the vehicle.
/// </summary>
public string ModeName { get; }
/// <summary>
/// Name of the Line.
/// </summary>
public string LineName { get; }
/// <summary>
/// Reference of the operator.
/// </summary>
public string OperatorRef { get; }
/// <summary>
/// Description of the Route.
/// </summary>
public string RouteDescription { get; }
/// <summary>
/// Reference of the Origin StopPoint from the Line/Route.
/// </summary>
public string OriginStopPointRef { get; }
/// <summary>
/// Reference of the Destination StopPoint from the Line/Route.
/// </summary>
public string DestinationStopPointRef { get; }
/// <summary>
/// Calls of the Stop Event.
/// </summary>
public IReadOnlyList<StopEventCall> Stops { get; }
internal StopEventResult(DateTime operatingDayRef, string journeyRef, string lineRef, string modeName,
string lineName, string operatorRef, string routeDescription,
string originStopPointRef, string destinationStopPointRef,
IReadOnlyList<StopEventCall> stops)
{
OperatingDayRef = operatingDayRef;
JourneyRef = journeyRef;
LineRef = lineRef;
ModeName = modeName;
LineName = lineName;
OperatorRef = operatorRef;
RouteDescription = routeDescription;
OriginStopPointRef = originStopPointRef;
DestinationStopPointRef = destinationStopPointRef;
Stops = stops;
}
internal StopEventResult(StopEventResultStructure stopEventResult)
{
var stopEvent = stopEventResult.StopEvent;
var stops = new List<StopEventCall>();
if (stopEvent.PreviousCall != null)
{
stops.AddRange(stopEvent.PreviousCall.Select(call => new StopEventCall(call, CallType.Previous)));
}
stops.Add(new StopEventCall(stopEvent.ThisCall, CallType.This));
if (stopEvent.OnwardCall != null)
{
stops.AddRange(stopEvent.OnwardCall.Select(call => new StopEventCall(call, CallType.Onward)));
}
Stops = stops;
OperatingDayRef = stopEvent.Service.OperatingDayRef.Value != null ? Convert.ToDateTime(stopEvent.Service.OperatingDayRef.Value.Replace("T", "", StringComparison.CurrentCultureIgnoreCase), CultureInfo.InvariantCulture) : DateTime.Today;
JourneyRef = stopEvent.Service.JourneyRef.Value;
var serviceSection = stopEvent.Service.ServiceSection.First();
LineRef = serviceSection.LineRef.Value;
ModeName = serviceSection.Mode.Name.GetBestText();
LineName = serviceSection.PublishedLineName.GetBestText();
OperatorRef = serviceSection.OperatorRef.Value;
RouteDescription = serviceSection.RouteDescription.GetBestText();
OriginStopPointRef = stopEvent.Service.OriginStopPointRef.Value;
DestinationStopPointRef = stopEvent.Service.DestinationStopPointRef.Value;
}
}
/// <summary>
/// One stop call in a <see cref="StopEventResult"/>
/// </summary>
public class StopEventCall
{
/// <summary>
/// Reference for the stop point in the track.
/// </summary>
public string StopPointRef { get; }
/// <summary>
/// Name of the stop point.
/// </summary>
public string StopPointName { get; }
/// <summary>
/// Sequence number of the stop point in the track.
/// </summary>
public int StopSeqNumber { get; }
/// <summary>
/// Planned Bay
/// </summary>
public string PlannedBay { get; }
/// <summary>
/// Arrival TimeTable Time
/// </summary>
public DateTime? ArrivalTimeTableTime { get; }
/// <summary>
/// Arrival Estimated Time
/// </summary>
public DateTime? ArrivalEstimatedTime { get; }
/// <summary>
/// Departure TimeTable Time
/// </summary>
public DateTime? DepartureTimeTableTime { get; }
/// <summary>
/// Departure Estimated Time
/// </summary>
public DateTime? DepartureEstimatedTime { get; }
/// <summary>
/// Typ of this call in the request.
/// </summary>
public CallType Type { get; }
internal StopEventCall(string stopPointRef, string stopPointName, int stopSeqNumber, string plannedBay,
DateTime? arrivalTimeTableTime, DateTime? arrivalEstimatedTime, DateTime? departureTimeTableTime, DateTime? departureEstimatedTime,
CallType callType)
{
StopPointRef = stopPointRef;
StopPointName = stopPointName;
StopSeqNumber = stopSeqNumber;
PlannedBay = plannedBay;
ArrivalTimeTableTime = arrivalTimeTableTime;
ArrivalEstimatedTime = arrivalEstimatedTime;
DepartureTimeTableTime = departureTimeTableTime;
DepartureEstimatedTime = departureEstimatedTime;
Type = callType;
}
internal StopEventCall(CallAtNearStopStructure call, CallType callType)
{
var callStop = call.CallAtStop;
StopPointRef = callStop.StopPointRef.Value;
StopSeqNumber = Convert.ToInt32(callStop.StopSeqNumber, CultureInfo.CurrentCulture);
StopPointName = callStop.StopPointName.GetBestText();
PlannedBay = callStop.PlannedBay.GetBestText();
ArrivalTimeTableTime = DateTimeIsDefaultThenNull(callStop.ServiceArrival?.TimetabledTime);
ArrivalEstimatedTime = DateTimeIsDefaultThenNull(callStop.ServiceArrival?.EstimatedTime);
DepartureTimeTableTime = DateTimeIsDefaultThenNull(callStop.ServiceDeparture?.TimetabledTime);
DepartureEstimatedTime = DateTimeIsDefaultThenNull(callStop.ServiceDeparture?.EstimatedTime);
Type = callType;
}
private static DateTime? DateTimeIsDefaultThenNull(DateTime? dateTime)
{
return dateTime.HasValue ? dateTime.Value == default ? null : dateTime : null;
}
}
/// <summary>
/// Typ of this call in the request.
/// </summary>
public enum CallType
{
/// <summary>
/// Previous call.
/// </summary>
Previous,
/// <summary>
/// Call of this Request.
/// </summary>
This,
/// <summary>
/// Onward call.
/// </summary>
Onward
}
}
| 34.594262 | 247 | 0.600047 | [
"MIT"
] | DerMistkaefer/dvb-live | backend/TriasCommunication/Data/StopEventResponse.cs | 8,443 | C# |
using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Metadata;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Tooling.Connector;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PowerApps.Samples
{
public partial class SampleProgram
{
private static Guid _publisherId;
private const string _primarySolutionName = "PrimarySolution";
private static Guid _primarySolutionId;
private static Guid _secondarySolutionId;
private const String _prefix = "test";
private const String _globalOptionSetName = _prefix + "_exampleoptionset";
private static Guid? _globalOptionSetId;
private const String _picklistName = _prefix + "_examplepicklist";
private const int _languageCode = 1033;
private static bool prompt = true;
/// <summary>
/// Function to set up the sample.
/// </summary>
/// <param name="service">Specifies the service to connect to.</param>
///
private static void SetUpSample(CrmServiceClient service)
{
// Check that the current version is greater than the minimum version
if (!SampleHelpers.CheckVersion(service, new Version("7.1.0.0")))
{
//The environment version is lower than version 7.1.0.0
return;
}
CreateRequiredRecords(service);
}
private static void CleanUpSample(CrmServiceClient service)
{
DeleteRequiredRecords(service, prompt);
}
/// <summary>
/// This method creates any entity records that this sample requires.
/// Create a publisher
/// Create a new solution, "Primary"
/// Create a Global Option Set in solution "Primary"
/// Export the "Primary" solution, setting it to Protected
/// Delete the option set and solution
/// Import the "Primary" solution, creating a managed solution in CRM.
/// Create a new solution, "Secondary"
/// Create an attribute in "Secondary" that references the Global Option Set
/// </summary>
public static void CreateRequiredRecords(CrmServiceClient service)
{
//Create the publisher that will "own" the two solutions
Publisher publisher = new Publisher
{
UniqueName = "samplepublisher",
FriendlyName = "An Example Publisher",
Description = "This is an example publisher",
CustomizationPrefix = _prefix
};
_publisherId = service.Create(publisher);
//Create the primary solution - note that we are not creating it
//as a managed solution as that can only be done when exporting the solution.
Solution primarySolution = new Solution
{
Version = "1.0",
FriendlyName = "Primary Solution",
PublisherId = new EntityReference(Publisher.EntityLogicalName, _publisherId),
UniqueName = _primarySolutionName
};
_primarySolutionId = service.Create(primarySolution);
//Now, create the Global Option Set and associate it to the solution.
OptionSetMetadata optionSetMetadata = new OptionSetMetadata()
{
Name = _globalOptionSetName,
DisplayName = new Label("Example Option Set", _languageCode),
IsGlobal = true,
OptionSetType = OptionSetType.Picklist,
Options =
{
new OptionMetadata(new Label("Option 1", _languageCode), 1),
new OptionMetadata(new Label("Option 2", _languageCode), 2)
}
};
CreateOptionSetRequest createOptionSetRequest = new CreateOptionSetRequest
{
OptionSet = optionSetMetadata
};
createOptionSetRequest.SolutionUniqueName = "PrimarySolution";
service.Execute(createOptionSetRequest);
//Export the solution as managed so that we can later import it.
ExportSolutionRequest exportRequest = new ExportSolutionRequest
{
Managed = true,
SolutionName = "PrimarySolution"
};
ExportSolutionResponse exportResponse =
(ExportSolutionResponse)service.Execute(exportRequest);
// Delete the option set previous created, so it can be imported under the
// managed solution.
DeleteOptionSetRequest deleteOptionSetRequest = new DeleteOptionSetRequest
{
Name = _globalOptionSetName
};
service.Execute(deleteOptionSetRequest);
// Delete the previous primary solution, so it can be imported as managed.
service.Delete(Solution.EntityLogicalName, _primarySolutionId);
_primarySolutionId = Guid.Empty;
// Re-import the solution as managed.
ImportSolutionRequest importRequest = new ImportSolutionRequest
{
CustomizationFile = exportResponse.ExportSolutionFile
};
service.Execute(importRequest);
// Retrieve the solution from CRM in order to get the new id.
QueryByAttribute primarySolutionQuery = new QueryByAttribute
{
EntityName = Solution.EntityLogicalName,
ColumnSet = new ColumnSet("solutionid"),
Attributes = { "uniquename" },
Values = { "PrimarySolution" }
};
_primarySolutionId = service.RetrieveMultiple(primarySolutionQuery).Entities
.Cast<Solution>().FirstOrDefault().SolutionId.GetValueOrDefault();
// Create a secondary solution.
Solution secondarySolution = new Solution
{
Version = "1.0",
FriendlyName = "Secondary Solution",
PublisherId = new EntityReference(Publisher.EntityLogicalName, _publisherId),
UniqueName = "SecondarySolution"
};
_secondarySolutionId = service.Create(secondarySolution);
// Create a Picklist attribute in the secondary solution linked to the option set in the
// primary - see WorkWithOptionSets.cs for more on option sets.
PicklistAttributeMetadata picklistMetadata = new PicklistAttributeMetadata
{
SchemaName = _picklistName,
LogicalName = _picklistName,
DisplayName = new Label("Example Picklist", _languageCode),
RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),
OptionSet = new OptionSetMetadata
{
IsGlobal = true,
Name = _globalOptionSetName
}
};
CreateAttributeRequest createAttributeRequest = new CreateAttributeRequest
{
EntityName = Contact.EntityLogicalName,
Attribute = picklistMetadata
};
createAttributeRequest["SolutionUniqueName"] = secondarySolution.UniqueName;
service.Execute(createAttributeRequest);
}
/// <summary>
/// Deletes any entity records that were created for this sample.
/// <param name="prompt">Indicates whether to prompt the user to delete the records created in this sample.</param>
/// </summary>
public static void DeleteRequiredRecords(CrmServiceClient service,bool prompt)
{
bool deleteRecords = true;
if (prompt)
{
Console.WriteLine("\nDo you want these entity records deleted? (y/n)");
String answer = Console.ReadLine();
deleteRecords = (answer.StartsWith("y") || answer.StartsWith("Y"));
}
if (deleteRecords)
{
DeleteAttributeRequest deleteAttributeRequest = new DeleteAttributeRequest
{
EntityLogicalName = Contact.EntityLogicalName,
LogicalName = "sample" + "_examplepicklist"
};
service.Execute(deleteAttributeRequest);
service.Delete(Solution.EntityLogicalName, _primarySolutionId);
service.Delete(Solution.EntityLogicalName, _secondarySolutionId);
service.Delete(Publisher.EntityLogicalName, _publisherId);
Console.WriteLine("Entity records have been deleted.");
}
}
/// <summary>
/// Shows how to get a more friendly message based on information within the dependency
/// <param name="dependency">A Dependency returned from the RetrieveDependentComponents message</param>
/// </summary>
public static void DependencyReport(CrmServiceClient service, Dependency dependency)
{
//These strings represent parameters for the message.
String dependentComponentName = "";
String dependentComponentTypeName = "";
String dependentComponentSolutionName = "";
String requiredComponentName = "";
String requiredComponentTypeName = "";
String requiredComponentSolutionName = "";
//The ComponentType global Option Set contains options for each possible component.
RetrieveOptionSetRequest componentTypeRequest = new RetrieveOptionSetRequest
{
Name = "componenttype"
};
RetrieveOptionSetResponse componentTypeResponse = (RetrieveOptionSetResponse)service.Execute(componentTypeRequest);
OptionSetMetadata componentTypeOptionSet = (OptionSetMetadata)componentTypeResponse.OptionSetMetadata;
// Match the Component type with the option value and get the label value of the option.
foreach (OptionMetadata opt in componentTypeOptionSet.Options)
{
if (dependency.DependentComponentType.Value == opt.Value)
{
dependentComponentTypeName = opt.Label.UserLocalizedLabel.Label;
}
if (dependency.RequiredComponentType.Value == opt.Value)
{
requiredComponentTypeName = opt.Label.UserLocalizedLabel.Label;
}
}
//The name or display name of the compoent is retrieved in different ways depending on the component type
dependentComponentName = getComponentName(service, dependency.DependentComponentType.Value, (Guid)dependency.DependentComponentObjectId);
requiredComponentName = getComponentName(service, dependency.RequiredComponentType.Value, (Guid)dependency.RequiredComponentObjectId);
// Retrieve the friendly name for the dependent solution.
Solution dependentSolution = (Solution)service.Retrieve
(
Solution.EntityLogicalName,
(Guid)dependency.DependentComponentBaseSolutionId,
new ColumnSet("friendlyname")
);
dependentComponentSolutionName = dependentSolution.FriendlyName;
// Retrieve the friendly name for the required solution.
Solution requiredSolution = (Solution)service.Retrieve
(
Solution.EntityLogicalName,
(Guid)dependency.RequiredComponentBaseSolutionId,
new ColumnSet("friendlyname")
);
requiredComponentSolutionName = requiredSolution.FriendlyName;
//Display the message
Console.WriteLine("The {0} {1} in the {2} depends on the {3} {4} in the {5} solution.",
dependentComponentName,
dependentComponentTypeName,
dependentComponentSolutionName,
requiredComponentName,
requiredComponentTypeName,
requiredComponentSolutionName);
}
// The name or display name of the component depends on the type of component.
public static String getComponentName(CrmServiceClient service, int ComponentType, Guid ComponentId)
{
String name = "";
switch (ComponentType)
{
// A separate method is required for each type of component
case (int)componenttype.Attribute:
name = getAttributeInformation(service,ComponentId);
break;
case (int)componenttype.OptionSet:
name = getGlobalOptionSetName(service, ComponentId);
break;
default:
name = "not implemented";
break;
}
return name;
}
// Retrieve the display name and parent entity information about an attribute solution component.
public static string getAttributeInformation(CrmServiceClient service,Guid id)
{
String attributeInformation = "";
RetrieveAttributeRequest req = new RetrieveAttributeRequest
{
MetadataId = id
};
RetrieveAttributeResponse resp = (RetrieveAttributeResponse)service.Execute(req);
AttributeMetadata attmet = resp.AttributeMetadata;
attributeInformation = attmet.EntityLogicalName + " : " + attmet.DisplayName.UserLocalizedLabel.Label;
return attributeInformation;
}
//Retrieve the name of a global Option set
public static String getGlobalOptionSetName(CrmServiceClient service, Guid id)
{
String name = "";
RetrieveOptionSetRequest req = new RetrieveOptionSetRequest
{
MetadataId = id
};
RetrieveOptionSetResponse resp = (RetrieveOptionSetResponse)service.Execute(req);
OptionSetMetadataBase os = (OptionSetMetadataBase)resp.OptionSetMetadata;
name = os.DisplayName.UserLocalizedLabel.Label;
return name;
}
}
}
| 43.376506 | 149 | 0.611208 | [
"MIT"
] | Antrodfr/PowerApps-Samples | cds/orgsvc/C#/SolutionDependencies/SolutionDependencies/SampleMethods.cs | 14,403 | C# |
using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("AWSSDK.AccessAnalyzer")]
#if BCL35
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - Access Analyzer. Introducing AWS IAM Access Analyzer, an IAM feature that makes it easy for AWS customers to ensure that their resource-based policies provide only the intended access to resources outside their AWS accounts.")]
#elif BCL45
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (4.5) - Access Analyzer. Introducing AWS IAM Access Analyzer, an IAM feature that makes it easy for AWS customers to ensure that their resource-based policies provide only the intended access to resources outside their AWS accounts.")]
#elif PCL
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (PCL) - Access Analyzer. Introducing AWS IAM Access Analyzer, an IAM feature that makes it easy for AWS customers to ensure that their resource-based policies provide only the intended access to resources outside their AWS accounts.")]
#elif UNITY
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (Unity) - Access Analyzer. Introducing AWS IAM Access Analyzer, an IAM feature that makes it easy for AWS customers to ensure that their resource-based policies provide only the intended access to resources outside their AWS accounts.")]
#elif NETSTANDARD13
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 1.3)- Access Analyzer. Introducing AWS IAM Access Analyzer, an IAM feature that makes it easy for AWS customers to ensure that their resource-based policies provide only the intended access to resources outside their AWS accounts.")]
#elif NETSTANDARD20
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 2.0)- Access Analyzer. Introducing AWS IAM Access Analyzer, an IAM feature that makes it easy for AWS customers to ensure that their resource-based policies provide only the intended access to resources outside their AWS accounts.")]
#else
#error Unknown platform constant - unable to set correct AssemblyDescription
#endif
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("Amazon Web Services SDK for .NET")]
[assembly: AssemblyCompany("Amazon.com, Inc")]
[assembly: AssemblyCopyright("Copyright 2009-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.3.103.6")]
#if WINDOWS_PHONE || UNITY
[assembly: System.CLSCompliant(false)]
# else
[assembly: System.CLSCompliant(true)]
#endif
#if BCL
[assembly: System.Security.AllowPartiallyTrustedCallers]
#endif | 60.220339 | 315 | 0.783563 | [
"Apache-2.0"
] | playstudios/aws-sdk-net | sdk/src/Services/AccessAnalyzer/Properties/AssemblyInfo.cs | 3,553 | C# |
using MediatR;
using OctopusSubscriptionHandler.Core.Models.Octopus;
namespace OctopusSubscriptionHandler.Core.Messages
{
public class NewOctopusSubscriptionEventReceived : INotification
{
public OctopusSubscriptionEvent SubscriptionEventEvent { get; }
public NewOctopusSubscriptionEventReceived(OctopusSubscriptionEvent subscriptionEventEvent)
{
SubscriptionEventEvent = subscriptionEventEvent;
}
}
} | 30.6 | 99 | 0.766885 | [
"MIT"
] | pmcilreavy/OctopusSubscriptionHandlerAzureFunction | OctopusSubscriptionHandler.Core/Messages/NewOctopusSubscriptionEventReceived.cs | 459 | C# |
using System.Collections.Generic;
namespace Eon.Collections {
public static class QueueUtilities {
public static IReadOnlyList<T> TryDequeueAll<T>(this Queue<T> queue) {
queue.EnsureNotNull(nameof(queue));
//
if (queue.Count > 0) {
var array = new T[ queue.Count ];
queue.CopyTo(array: array, arrayIndex: 0);
var result = new ListReadOnlyWrap<T>(list: array);
queue.Clear();
return result;
}
else
return ListReadOnlyWrap<T>.Empty;
}
public static IReadOnlyList<T> TryDequeue<T>(this Queue<T> queue, int maxCount) {
queue.EnsureNotNull(nameof(queue));
maxCount.Arg(nameof(maxCount)).EnsureNotLessThanZero();
//
if (queue.Count > 0 && maxCount > 0) {
if (maxCount > queue.Count)
return TryDequeueAll(queue: queue);
else {
var result = new List<T>();
while (result.Count < maxCount && queue.Count > 0)
result.Add(queue.Dequeue());
return new ListReadOnlyWrap<T>(collection: result);
}
}
else
return ListReadOnlyWrap<T>.Empty;
}
}
} | 25.463415 | 83 | 0.657088 | [
"MIT"
] | vitalik-mironov/eon-lib | src/eon-lib.core.level-1/Collections/QueueUtilities.cs | 1,046 | C# |
using System;
using System.Text;
namespace Tiandao.ComponentModel
{
/// <summary>
/// 指定属性 (Property) 或事件的说明。
/// </summary>
[AttributeUsage(AttributeTargets.All)]
public class DescriptionAttribute : Attribute
{
#region 静态常量
public static readonly DescriptionAttribute Default = new DescriptionAttribute();
#endregion
#region 私有字段
private string _description;
#endregion
#region 公共属性
public virtual string Description
{
get
{
return this.DescriptionValue;
}
}
#endregion
#region 保护属性
protected string DescriptionValue
{
get
{
return this._description;
}
set
{
this._description = value;
}
}
#endregion
#region 构造方法
public DescriptionAttribute() : this(string.Empty)
{
}
public DescriptionAttribute(string description)
{
this._description = description;
}
#endregion
#region 重写方法
public override bool Equals(object obj)
{
if(obj == this)
return true;
DescriptionAttribute attribute = obj as DescriptionAttribute;
return ((attribute != null) && (attribute.Description == this.Description));
}
public override int GetHashCode()
{
return this.Description.GetHashCode();
}
#endregion
}
}
| 14.529412 | 83 | 0.680162 | [
"MIT"
] | jonfee/Tiandao.CoreLibrary | src/Tiandao.CoreLibrary/ComponentModel/DescriptionAttribute.cs | 1,307 | C# |
using System.Collections.Generic;
namespace Aska.Core.EntityStorage.Abstractions
{
public interface IPagedEnumerable<out T> : IEnumerable<T>
{
long TotalCount { get; }
}
} | 21.444444 | 61 | 0.699482 | [
"MIT"
] | felements/aska.core | src/Aska.Core.EntityStorage.Abstractions/src/IPagedEnumerable.cs | 195 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace _2020052801HGCS_1_HelloWorld.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}
| 34.935484 | 151 | 0.588181 | [
"MIT"
] | AungWinnHtut/POL | C#/2020052801HGCS-1 HelloWorld/Properties/Settings.Designer.cs | 1,085 | 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("silkveil.net.Flow.StreamMerger.Contracts")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("silkveil.net.Flow.StreamMerger.Contracts")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2010")]
[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("5d33143d-6c8c-4f3f-8e7c-f5a14279260c")]
// 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")]
| 40.72973 | 85 | 0.734572 | [
"Unlicense",
"MIT"
] | peterbucher/silkveil | silkveil.net EBC Prototype by Golo/silkveil.net.Flow.StreamMerger.Contracts/Properties/AssemblyInfo.cs | 1,510 | C# |
using System;
using System.Collections.Generic;
namespace Karoterra.AupDotNet.ExEdit.Effects
{
/// <summary>
/// シーンチェンジ
/// </summary>
/// <remarks>
/// <list type="table">
/// <listheader>
/// <term>シーンチェンジの種類</term>
/// <description>説明</description>
/// </listheader>
/// <item>
/// <term>組み込みシーンチェンジ</term>
/// <description>
/// <see cref="ScriptFileEffect.Name"/> は空、
/// <see cref="ScriptFileEffect.ScriptId"/> にインデックスが入り、
/// <see cref="ScriptFileEffect.Params"/> は<c>null</c>。
/// </description>
/// </item>
/// <item>
/// <term>exedit.scnのスクリプト</term>
/// <description>
/// <see cref="ScriptFileEffect.Name"/> にスクリプト名、
/// <see cref="ScriptFileEffect.ScriptId"/> に1が入る。
/// </description>
/// </item>
/// <item>
/// <term>ユーザ定義スクリプト</term>
/// <description>
/// <see cref="ScriptFileEffect.Name"/> にスクリプト名、
/// <see cref="ScriptFileEffect.ScriptId"/> に2が入る。
/// </description>
/// </item>
/// <item>
/// <term>transition画像</term>
/// <description>
/// <see cref="ScriptFileEffect.Name"/> に画像ファイル名(拡張子無し)、
/// <see cref="ScriptFileEffect.ScriptId"/> に0が入り、
/// <see cref="ScriptFileEffect.Params"/> は<c>null</c>。
/// </description>
/// </item>
/// </list>
/// </remarks>
public class SceneChangeEffect : ScriptFileEffect
{
/// <summary>
/// シーンチェンジのフィルタ効果定義。
/// </summary>
public static EffectType EffectType { get; }
/// <summary>
/// 組み込みシーンチェンジ名の一覧。
/// Nameが空の時にはこれのインデックスがScriptIdに入る。
/// </summary>
public static readonly IReadOnlyList<string> Defaults;
/// <summary>
/// exedit.scnで定義されているスクリプト。
/// スクリプト名がNameに入り、ScriptIdは1になる。
/// </summary>
public static readonly IReadOnlyList<string> DefaultScripts;
/// <summary>
/// 「反転」チェックボックス
/// </summary>
public bool Reverse
{
get => Checkboxes[0] != 0;
set => Checkboxes[0] = value ? 1 : 0;
}
/// <summary>
/// <see cref="SceneChangeEffect"/> のインスタンスを初期化します。
/// </summary>
public SceneChangeEffect()
: base(EffectType)
{
}
/// <summary>
/// トラックバーとチェックボックスの値を指定して <see cref="SceneChangeEffect"/> のインスタンスを初期化します。
/// </summary>
/// <param name="trackbars">トラックバー</param>
/// <param name="checkboxes">チェックボックス</param>
public SceneChangeEffect(Trackbar[] trackbars, int[] checkboxes)
: base(EffectType, trackbars, checkboxes)
{
}
/// <summary>
/// トラックバーとチェックボックス、拡張データを指定して <see cref="SceneChangeEffect"/> のインスタンスを初期化します。
/// </summary>
/// <param name="trackbars">トラックバー</param>
/// <param name="checkboxes">チェックボックス</param>
/// <param name="data">拡張データ</param>
public SceneChangeEffect(Trackbar[] trackbars, int[] checkboxes, ReadOnlySpan<byte> data)
: base(EffectType, trackbars, checkboxes, data)
{
}
static SceneChangeEffect()
{
EffectType = new EffectType(
14, 0x04000400, 2, 3, 516, "シーンチェンジ",
new TrackbarDefinition[]
{
new TrackbarDefinition("調整", 100, 0, 0, 0),
new TrackbarDefinition("track1", 100, 0, 0, 0),
},
new CheckboxDefinition[]
{
new CheckboxDefinition("反転", true, 0),
new CheckboxDefinition("check0", true, 0),
new CheckboxDefinition("クロスフェード", false, 0),
}
);
Defaults = new List<string>()
{
"クロスフェード",
"ワイプ(円)",
"ワイプ(四角)",
"ワイプ(時計)",
"スライス",
"スワップ",
"スライド",
"縮小回転",
"押し出し(横)",
"押し出し(縦)",
"回転(横)",
"回転(縦)",
"キューブ回転(横)",
"キューブ回転(縦)",
"フェードアウトイン",
"放射ブラー",
"ぼかし",
"ワイプ(横)",
"ワイプ(縦)",
"ロール(横)",
"ロール(縦)",
"ランダムライン",
};
DefaultScripts = new List<string>()
{
"発光",
"レンズブラー",
"ドア",
"起き上がる",
"リール回転",
"図形ワイプ",
"図形で隠す",
"図形で隠す(放射)",
"砕け散る",
"ページめくり",
};
}
}
}
| 31.310559 | 97 | 0.438802 | [
"MIT"
] | karoterra/AupDotNet | src/AupDotNet/ExEdit/Effects/SceneChangeEffect.cs | 6,049 | C# |
#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Uno.Extensions;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml.Markup;
using Windows.UI.Xaml.Controls.Primitives;
using Uno.Logging;
using Uno.UI.Controls;
using Uno.Disposables;
#if __IOS__
using UIKit;
#elif __ANDROID__
using Uno.UI;
#endif
namespace Windows.UI.Xaml.Controls
{
[ContentProperty(Name = nameof(PrimaryCommands))]
[TemplatePart(Name = MoreButton, Type = typeof(Button))]
[TemplatePart(Name = OverflowPopup, Type = typeof(Popup))]
[TemplatePart(Name = PrimaryItemsControl, Type = typeof(ItemsControl))]
[TemplatePart(Name = SecondaryItemsControl, Type = typeof(ItemsControl))]
public partial class CommandBar : AppBar
{
private const string MoreButton = "MoreButton";
private const string OverflowPopup = "OverflowPopup";
private const string PrimaryItemsControl = "PrimaryItemsControl";
private const string SecondaryItemsControl = "SecondaryItemsControl";
private readonly SerialDisposable _eventSubscriptions = new SerialDisposable();
private Button? _moreButton;
private Popup? _overflowPopup;
private ItemsControl? _primaryItemsControl;
private ItemsControl? _secondaryItemsControl;
private double _contentHeight;
public CommandBar()
{
PrimaryCommands = new ObservableVector<ICommandBarElement>();
SecondaryCommands = new ObservableVector<ICommandBarElement>();
PrimaryCommands.VectorChanged += (s, e) => UpdateCommands();
SecondaryCommands.VectorChanged += (s, e) => UpdateCommands();
CommandBarTemplateSettings = new CommandBarTemplateSettings(this);
Loaded += (s, e) => RegisterEvents();
Unloaded += (s, e) => UnregisterEvents();
SizeChanged += (s, e) => _contentHeight = e.NewSize.Height;
this.RegisterPropertyChangedCallback(IsEnabledProperty, (s, e) => UpdateCommonState());
this.RegisterPropertyChangedCallback(ClosedDisplayModeProperty, (s, e) => UpdateDisplayModeState());
this.RegisterPropertyChangedCallback(IsOpenProperty, (s, e) =>
{
// TODO: Consider the content of _secondaryItemsControl when IsDynamicOverflowEnabled is supported.
var hasSecondaryItems = SecondaryCommands.Any();
if (hasSecondaryItems)
{
if (_overflowPopup is {} popup)
{
popup.IsOpen = true;
}
}
UpdateDisplayModeState();
UpdateButtonsIsCompact();
});
DefaultStyleKey = typeof(CommandBar);
}
#if __ANDROID__ || __IOS__
internal NativeCommandBarPresenter? Presenter { get; set; }
#endif
protected override void OnApplyTemplate()
{
base.OnApplyTemplate();
_moreButton = GetTemplateChild(MoreButton) as Button;
_overflowPopup = GetTemplateChild(OverflowPopup) as Popup;
_primaryItemsControl = GetTemplateChild(PrimaryItemsControl) as ItemsControl;
_secondaryItemsControl = GetTemplateChild(SecondaryItemsControl) as ItemsControl;
#if __ANDROID__ || __IOS__
Presenter = this.FindFirstChild<NativeCommandBarPresenter>();
#endif
RegisterEvents();
UpdateCommands();
UpdateTemplateSettings();
UpdateCommonState();
UpdateDisplayModeState();
UpdateButtonsIsCompact();
}
private void UpdateTemplateSettings()
{
CommandBarTemplateSettings.ContentHeight = _contentHeight;
CommandBarTemplateSettings.OverflowContentMinWidth = RenderSize.Width;
CommandBarTemplateSettings.OverflowContentMaxWidth = RenderSize.Width;
}
private void RegisterEvents()
{
UnregisterEvents();
var disposables = new CompositeDisposable(2);
if (_moreButton is {} moreButton)
{
moreButton.Click += OnMoreButtonClicked;
disposables.Add(() => moreButton.Click -= OnMoreButtonClicked);
}
if (_overflowPopup is {} overflowPopup)
{
overflowPopup.Closed += OnOverflowPopupClosed;
disposables.Add(() => overflowPopup.Closed -= OnOverflowPopupClosed);
}
_eventSubscriptions.Disposable = disposables;
}
private void UnregisterEvents() => _eventSubscriptions.Disposable = null;
private void OnOverflowPopupClosed(object sender, object e)
=> IsOpen = false;
private void OnMoreButtonClicked(object sender, RoutedEventArgs e)
=> IsOpen = !IsOpen;
private void UpdateButtonsIsCompact()
{
var allCommands = Enumerable.Concat(PrimaryCommands, SecondaryCommands).OfType<ICommandBarElement>();
foreach (var command in allCommands)
{
command.IsCompact = !IsOpen;
};
}
public event TypedEventHandler<CommandBar, DynamicOverflowItemsChangingEventArgs?>? DynamicOverflowItemsChanging;
#region PrimaryCommands
public IObservableVector<ICommandBarElement> PrimaryCommands
{
get => (IObservableVector<ICommandBarElement>)this.GetValue(PrimaryCommandsProperty);
private set => this.SetValue(PrimaryCommandsProperty, value);
}
public static DependencyProperty PrimaryCommandsProperty { get; } =
DependencyProperty.Register(
"PrimaryCommands",
typeof(IObservableVector<ICommandBarElement>),
typeof(CommandBar),
new FrameworkPropertyMetadata(
default(IObservableVector<ICommandBarElement>),
FrameworkPropertyMetadataOptions.ValueInheritsDataContext
)
);
#endregion
#region SecondaryCommands
public IObservableVector<ICommandBarElement> SecondaryCommands
{
get => (IObservableVector<ICommandBarElement>)this.GetValue(SecondaryCommandsProperty);
private set => this.SetValue(SecondaryCommandsProperty, value);
}
public static DependencyProperty SecondaryCommandsProperty { get; } =
DependencyProperty.Register(
"SecondaryCommands",
typeof(IObservableVector<ICommandBarElement>),
typeof(CommandBar),
new FrameworkPropertyMetadata(
default(IObservableVector<ICommandBarElement>),
FrameworkPropertyMetadataOptions.ValueInheritsDataContext
)
);
#endregion
#region CommandBarOverflowPresenterStyle
public Style CommandBarOverflowPresenterStyle
{
get => (Style)GetValue(CommandBarOverflowPresenterStyleProperty);
set => SetValue(CommandBarOverflowPresenterStyleProperty, value);
}
[Uno.NotImplemented]
public static DependencyProperty CommandBarOverflowPresenterStyleProperty { get; } =
DependencyProperty.Register(
"CommandBarOverflowPresenterStyle",
typeof(Style),
typeof(CommandBar),
new FrameworkPropertyMetadata(default(Style), FrameworkPropertyMetadataOptions.ValueDoesNotInheritDataContext)
);
#endregion
#region OverflowButtonVisibility
public CommandBarOverflowButtonVisibility OverflowButtonVisibility
{
get => (CommandBarOverflowButtonVisibility)this.GetValue(OverflowButtonVisibilityProperty);
set => SetValue(OverflowButtonVisibilityProperty, value);
}
public static DependencyProperty OverflowButtonVisibilityProperty { get; } =
DependencyProperty.Register(
"OverflowButtonVisibility",
typeof(CommandBarOverflowButtonVisibility),
typeof(CommandBar),
new FrameworkPropertyMetadata(default(CommandBarOverflowButtonVisibility))
);
#endregion
#region IsDynamicOverflowEnabled
public bool IsDynamicOverflowEnabled
{
get => (bool)this.GetValue(IsDynamicOverflowEnabledProperty);
set => SetValue(IsDynamicOverflowEnabledProperty, value);
}
public static DependencyProperty IsDynamicOverflowEnabledProperty { get; } =
DependencyProperty.Register(
"IsDynamicOverflowEnabled",
typeof(bool),
typeof(CommandBar),
new FrameworkPropertyMetadata(default(bool))
);
#endregion
#region DefaultLabelPosition
public CommandBarDefaultLabelPosition DefaultLabelPosition
{
get => (CommandBarDefaultLabelPosition)this.GetValue(DefaultLabelPositionProperty);
set => SetValue(DefaultLabelPositionProperty, value);
}
public static DependencyProperty DefaultLabelPositionProperty { get; } =
DependencyProperty.Register(
"DefaultLabelPosition",
typeof(CommandBarDefaultLabelPosition),
typeof(CommandBar),
new FrameworkPropertyMetadata(default(CommandBarDefaultLabelPosition))
);
#endregion
public CommandBarTemplateSettings CommandBarTemplateSettings { get; }
private void UpdateCommands()
{
DynamicOverflowItemsChanging?.Invoke(this, null);
// TODO: Remove/Add delta, to preserve state of existing buttons
if (_primaryItemsControl != null)
{
_primaryItemsControl.ItemsSource = PrimaryCommands;
}
if (_secondaryItemsControl != null)
{
_secondaryItemsControl.ItemsSource = SecondaryCommands;
}
PrimaryCommands.OfType<ICommandBarElement3>().ForEach(command => command.IsInOverflow = false);
SecondaryCommands.OfType<ICommandBarElement3>().ForEach(command => command.IsInOverflow = true);
UpdateAvailableCommandsState();
UpdateButtonsIsCompact();
}
private void UpdateCommonState()
{
var commonState = IsEnabled
? "Normal"
: "Disabled";
VisualStateManager.GoToState(this, commonState, true);
}
private void UpdateDisplayModeState()
{
string? GetDisplayMode()
{
switch (ClosedDisplayMode)
{
case AppBarClosedDisplayMode.Compact: return "Compact";
case AppBarClosedDisplayMode.Minimal: return "Minimal";
case AppBarClosedDisplayMode.Hidden: return "Hidden";
default: return null;
}
}
string GetState()
{
// OpenUp is not supported yet.
return IsOpen ? "OpenDown" : "Closed";
}
var displayModeState = GetDisplayMode() + GetState();
VisualStateManager.GoToState(this, displayModeState, true);
}
private void UpdateAvailableCommandsState()
{
string availableCommandsState;
if (PrimaryCommands.Any() && SecondaryCommands.None())
{
availableCommandsState = "PrimaryCommandsOnly";
}
else if (PrimaryCommands.None() && SecondaryCommands.Any())
{
availableCommandsState = "SecondaryCommandsOnly";
}
else
{
availableCommandsState = "BothCommands";
}
VisualStateManager.GoToState(this, availableCommandsState, true);
}
}
}
| 28.895652 | 115 | 0.756746 | [
"Apache-2.0"
] | AnshSSonkhia/uno | src/Uno.UI/UI/Xaml/Controls/CommandBar/CommandBar.cs | 9,971 | C# |
namespace LogViewer
{
using System;
using System.Windows;
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
private void AppStartup(object sender, StartupEventArgs e)
{
var mw = new MainWindow();
var args = Environment.GetCommandLineArgs();
if (args.GetLength(0) > 1 && args[1].EndsWith(".log"))
mw.CarregarArquivo(args[1]);
mw.Show();
}
}
}
| 23.636364 | 66 | 0.546154 | [
"CC0-1.0"
] | aforesti/ncr-LogViewer | LogViewer/Source/App.xaml.cs | 522 | C# |
// =================================================================================================================================
// Copyright (c) RapidField LLC. Licensed under the MIT License. See LICENSE.txt in the project root for license information.
// =================================================================================================================================
using Autofac;
using Microsoft.Azure.ServiceBus;
using Microsoft.Extensions.Configuration;
using RapidField.SolidInstruments.Core;
using RapidField.SolidInstruments.Core.ArgumentValidation;
using RapidField.SolidInstruments.Core.Extensions;
using RapidField.SolidInstruments.InversionOfControl;
using RapidField.SolidInstruments.InversionOfControl.Autofac.Extensions;
using RapidField.SolidInstruments.Messaging.AzureServiceBus;
using RapidField.SolidInstruments.Messaging.TransportPrimitives;
using System;
namespace RapidField.SolidInstruments.Messaging.Autofac.Asb.Extensions
{
/// <summary>
/// Extends the <see cref="ContainerBuilder" /> class with inversion of control features to support Azure Service Bus messaging.
/// </summary>
public static class ContainerBuilderExtensions
{
/// <summary>
/// Registers a collection of types that establish support for in-memory service bus functionality.
/// </summary>
/// <param name="target">
/// The current <see cref="ContainerBuilder" />.
/// </param>
/// <param name="applicationConfiguration">
/// Configuration information for the application.
/// </param>
/// <param name="connectionStringConfigurationKeyName">
/// The configuration connection string key name for the Azure Service Bus connection.
/// </param>
/// <exception cref="ArgumentEmptyException">
/// <paramref name="connectionStringConfigurationKeyName" /> is empty.
/// </exception>
/// <exception cref="ArgumentNullException">
/// <paramref name="applicationConfiguration" /> is <see langword="null" /> -or-
/// <paramref name="connectionStringConfigurationKeyName" /> is <see langword="null" />.
/// </exception>
public static void RegisterSupportingTypesForAzureServiceBusMessaging(this ContainerBuilder target, IConfiguration applicationConfiguration, String connectionStringConfigurationKeyName)
{
target.RegisterApplicationConfiguration(applicationConfiguration);
_ = connectionStringConfigurationKeyName.RejectIf().IsNullOrEmpty(nameof(connectionStringConfigurationKeyName));
target.Register(context =>
{
var configuration = context.Resolve<IConfiguration>();
var serviceBusConnectionString = configuration.GetConnectionString(connectionStringConfigurationKeyName);
if (serviceBusConnectionString.IsNullOrWhiteSpace())
{
throw new DependencyResolutionException("The service bus connection string was not found in configuration.");
}
return new ServiceBusConnection(serviceBusConnectionString);
}).IfNotRegistered(typeof(ServiceBusConnection)).AsSelf().InstancePerLifetimeScope();
target.RegisterType<AzureServiceBusMessageAdapter>().IfNotRegistered(typeof(AzureServiceBusMessageAdapter)).As<IMessageAdapter<PrimitiveMessage>>().AsSelf().InstancePerLifetimeScope();
target.RegisterType<AzureServiceBusClientFactory>().IfNotRegistered(typeof(AzureServiceBusClientFactory)).As<IMessagingClientFactory<IMessagingEntitySendClient, IMessagingEntityReceiveClient, PrimitiveMessage>>().AsSelf().InstancePerLifetimeScope();
target.RegisterType<AzureServiceBusTransmittingFacade>().IfNotRegistered(typeof(AzureServiceBusTransmittingFacade)).As<IMessageTransmittingFacade>().AsSelf().InstancePerLifetimeScope();
target.RegisterType<AzureServiceBusListeningFacade>().IfNotRegistered(typeof(AzureServiceBusListeningFacade)).As<IMessageListeningFacade>().AsSelf().SingleInstance();
target.RegisterType<AzureServiceBusRequestingFacade>().IfNotRegistered(typeof(AzureServiceBusRequestingFacade)).As<IMessageRequestingFacade>().AsSelf().SingleInstance();
}
}
} | 63.308824 | 261 | 0.691289 | [
"MIT"
] | RapidField/solid-instruments | src/RapidField.SolidInstruments.Messaging.Autofac.Asb/Extensions/ContainerBuilderExtensions.cs | 4,307 | C# |
using System;
using System.Collections.Generic;
using System.Windows;
using SharpEssentials.Controls.Selectors;
using Xunit;
namespace SharpEssentials.Tests.Unit.SharpEssentials.Controls.Selectors
{
public class TypeMapDataTemplateSelectorTests
{
[Fact]
public void Test_ExactMatch()
{
// Arrange.
var template = new DataTemplate { DataType = typeof(string) };
var selector = new TypeMapDataTemplateSelector(new List<DataTemplate>
{
new DataTemplate { DataType = typeof(int) },
template
});
// Act.
var actual = selector.SelectTemplate("test", null);
// Assert.
Assert.Equal(template, actual);
}
[Fact]
public void Test_NoMatch()
{
// Arrange.
var selector = new TypeMapDataTemplateSelector(new List<DataTemplate>
{
new DataTemplate { DataType = typeof(int) },
new DataTemplate { DataType = typeof(string) }
});
// Act.
var actual = selector.SelectTemplate(new object(), null);
// Assert.
Assert.Null(actual);
}
[Fact]
public void Test_NonExactMatch()
{
// Arrange.
var broadTemplate = new DataTemplate { DataType = typeof(IComparable<string>) };
var moreBroadTemplate = new DataTemplate { DataType = typeof(IConvertible) };
var selector = new TypeMapDataTemplateSelector(new List<DataTemplate>
{
moreBroadTemplate,
broadTemplate
});
// Act.
var actual = selector.SelectTemplate("test", null);
// Assert.
Assert.Equal(moreBroadTemplate, actual);
}
[Fact]
public void Test_NonExactMatch_OrderMatters()
{
// Arrange.
var broadTemplate = new DataTemplate { DataType = typeof(IComparable<string>) };
var moreBroadTemplate = new DataTemplate { DataType = typeof(IConvertible) };
var selector = new TypeMapDataTemplateSelector(new List<DataTemplate>
{
broadTemplate,
moreBroadTemplate
});
// Act.
var actual = selector.SelectTemplate("test", null);
// Assert.
Assert.Equal(broadTemplate, actual);
}
}
} | 22.885057 | 83 | 0.690105 | [
"Apache-2.0"
] | mthamil/SharpEssentials.Controls | SharpEssentials.Tests.Unit/SharpEssentials.Controls/Selectors/TypeMapDataTemplateSelectorTests.cs | 1,993 | C# |
using Microsoft.Extensions.Hosting;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Aragas.QServer.Hosting
{
public class QServerHost : IHost, IEnvironmentSetup
{
public static QServerHost Default => new QServerHost();
public static IHostBuilder CreateDefaultBuilder(string[]? args = null, Guid? uid = null)
{
var host = Host.CreateDefaultBuilder(args ?? Array.Empty<string>())
.UseLogging()
.UseNATSNetworkBus()
.UseMetricsWithDefault()
.UseHealthChecks();
if (uid != null)
host.UseServiceOptions(uid.Value);
return host;
}
private readonly IHost _host;
public IServiceProvider Services => _host.Services;
public Guid Uid { get; } = Guid.NewGuid();
public QServerHost()
{
IEnvironmentSetup.SetEnvironment();
var builder = CreateDefaultBuilder(uid: Uid);
_host = builder.Build();
}
public QServerHost(IHostBuilder builder)
{
IEnvironmentSetup.SetEnvironment();
builder = builder
.UseLogging()
.UseNATSNetworkBus()
.UseMetricsWithDefault()
.UseHealthChecks()
.UseServiceOptions(Uid);
_host = builder.Build();
}
public Task StartAsync(CancellationToken cancellationToken = default)
{
return _host.StartAsync(cancellationToken);
}
public Task StopAsync(CancellationToken cancellationToken = default)
{
return _host.StopAsync(cancellationToken);
}
public void Dispose()
{
_host.Dispose();
}
}
} | 26.492754 | 96 | 0.567287 | [
"MIT"
] | Aragas/Aragas.QServer.Hosting | QServerHost.cs | 1,830 | C# |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Turbo.Cache;
using Turbo.Cache.Info;
using Turbo.Construction;
using Turbo.DI;
using Turbo.Metadata;
using Turbo.Metadata.Yaml;
using Turbo.UnitTests.Stubs.WebDriver.Null;
namespace Turbo.UnitTests.Construction.Test.Pages
{
[TestClass]
public class PageTestBase
{
private IMetadataLoader _loader;
[TestInitialize]
public void InitBase()
{
_loader = new YamlMetadataLoader();
WebDriver = new NullDriver();
var factory = new SimpleObjectFactory();
TurboInitializer.RegisterBuiltInTypes(factory);
factory.Instance(_loader);
PageBuilder = factory.GetInstance<IPageFactory>();
}
public IPageFactory PageBuilder { get; private set; }
public NullDriver WebDriver { get; private set; }
protected AppInfo RegisterApp<TApp>()
{
AppInfo appInfo;
if (!TurboSync.TryGetApp(typeof(TApp), out appInfo))
{
var appMeta = _loader.GetAppMeta<TApp>();
appInfo = TurboSync.AddApp(appMeta);
}
return appInfo;
}
protected PageInfo RegisterPage<TPage>(AppInfo appInfo)
{
PageInfo pageInfo;
if (!TurboSync.TryGetPage(typeof(TPage), out pageInfo))
{
var page = _loader.GetPageMeta<TPage>();
pageInfo = TurboSync.AddPage(appInfo.App, page);
}
return pageInfo;
}
protected T GetPage<T>()
{
return PageBuilder.BuildPage<T>(WebDriver);
}
protected T GetPart<T>()
{
return PageBuilder.BuildPart<T>(WebDriver);
}
}
} | 27.5 | 68 | 0.562032 | [
"Unlicense"
] | mikalai-kardash/Turbo | src/Turbo.UnitTests/Construction/Test/Pages/PageTestBase.cs | 1,872 | C# |
using System.Collections.Generic;
using System.Linq;
using Cake.Core.IO;
using Newtonsoft.Json;
using Rocket.Surgery.Cake.Internal;
namespace Rocket.Surgery.Cake.TfsTasks
{
/// <summary>
/// ReportCodeCoverageOptions.
/// </summary>
public class ReportCodeCoverageOptions
{
/// <summary>
/// Gets the type of the code coverage.
/// </summary>
/// <value>The type of the code coverage.</value>
[JsonProperty("codecoveragetool")]
public CodeCoverageType CodeCoverageType { get; } = CodeCoverageType.Cobertura;
/// <summary>
/// Gets or sets the summary file.
/// </summary>
/// <value>The summary file.</value>
[JsonProperty("summaryfile")]
public FilePath SummaryFile { get; set; }
/// <summary>
/// Gets or sets the report directory.
/// </summary>
/// <value>The report directory.</value>
[JsonProperty("reportdirectory")]
public DirectoryPath ReportDirectory { get; set; }
/// <summary>
/// Gets or sets the additional code coverage files.
/// </summary>
/// <value>The additional code coverage files.</value>
[JsonProperty("additionalcodecoveragefiles")]
public IEnumerable<FilePath> AdditionalCodeCoverageFiles { get; set; }
}
}
| 31.465116 | 87 | 0.614191 | [
"MIT"
] | RocketSurgeonsGuild/Cake | src/Cake/TfsTasks/ReportCodeCoverageOptions.cs | 1,353 | C# |
/*
MIT License
Copyright(c) 2014-2018 Infragistics, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using System;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using BreakingChangesDetector.MetadataItems;
using BreakingChangesDetector.BreakingChanges;
namespace BreakingChangesDetector.UnitTests.BreakingChangesTests
{
[TestClass]
public class ChangedClassToStaticTests
{
#region NestedTypeTests
[TestMethod]
public void NestedTypeTests()
{
var assembly = AssemblyData.FromAssembly(typeof(ChangedClassToStaticTests).Assembly);
var NestedClass = TypeDefinitionData.FromType(typeof(NestedClass));
var NestedClassWithInternalConstructor = TypeDefinitionData.FromType(typeof(NestedClassWithInternalConstructor));
var NestedClassWithProtectedConstructor = TypeDefinitionData.FromType(typeof(NestedClassWithProtectedConstructor));
var NestedStaticClass = TypeDefinitionData.FromType(typeof(NestedStaticClass));
var breakingChanges = MetadataComparer.CompareTypes(NestedClass, NestedStaticClass).Where(b => b.BreakingChangeKind == BreakingChangeKind.ChangedClassToStatic).ToList();
Assert.AreEqual(1, breakingChanges.Count, "There should be one breaking change when a class is made static.");
Assert.AreEqual(BreakingChangeKind.ChangedClassToStatic, breakingChanges[0].BreakingChangeKind, "The BreakingChangeKind is incorrect.");
Assert.AreEqual(NestedClass.GetMember("Class"), breakingChanges[0].OldItem, "The OldItem is incorrect.");
Assert.AreEqual(NestedStaticClass.GetMember("Class"), breakingChanges[0].NewItem, "The NewItem is incorrect.");
Assert.IsNull(breakingChanges[0].AssociatedData, "The AssociatedData is incorrect.");
breakingChanges = MetadataComparer.CompareTypes(NestedClassWithInternalConstructor, NestedStaticClass);
Assert.AreEqual(0, breakingChanges.Count, "There should be no breaking changes when a class with no public constructors is made abstract.");
breakingChanges = MetadataComparer.CompareTypes(NestedClassWithProtectedConstructor, NestedStaticClass).Where(b => b.BreakingChangeKind == BreakingChangeKind.ChangedClassToStatic).ToList();
Assert.AreEqual(1, breakingChanges.Count, "There should be one breaking change when a class is made static.");
Assert.AreEqual(BreakingChangeKind.ChangedClassToStatic, breakingChanges[0].BreakingChangeKind, "The BreakingChangeKind is incorrect.");
Assert.AreEqual(NestedClassWithProtectedConstructor.GetMember("Class"), breakingChanges[0].OldItem, "The OldItem is incorrect.");
Assert.AreEqual(NestedStaticClass.GetMember("Class"), breakingChanges[0].NewItem, "The NewItem is incorrect.");
Assert.IsNull(breakingChanges[0].AssociatedData, "The AssociatedData is incorrect.");
}
#endregion // NestedTypeTests
#region TypeTests
[TestMethod]
public void TypeTests()
{
var assembly = AssemblyData.FromAssembly(typeof(ChangedClassToStaticTests).Assembly);
var Class = TypeDefinitionData.FromType(typeof(Class));
var ClassWithInternalConstructor = TypeDefinitionData.FromType(typeof(ClassWithInternalConstructor));
var ClassWithProtectedConstructor = TypeDefinitionData.FromType(typeof(ClassWithProtectedConstructor));
var StaticClass = TypeDefinitionData.FromType(typeof(StaticClass));
var breakingChanges = MetadataComparer.CompareTypes(Class, StaticClass).Where(b => b.BreakingChangeKind == BreakingChangeKind.ChangedClassToStatic).ToList();
Assert.AreEqual(1, breakingChanges.Count, "There should be one breaking change when a class is made static.");
Assert.AreEqual(BreakingChangeKind.ChangedClassToStatic, breakingChanges[0].BreakingChangeKind, "The BreakingChangeKind is incorrect.");
Assert.AreEqual(Class, breakingChanges[0].OldItem, "The OldItem is incorrect.");
Assert.AreEqual(StaticClass, breakingChanges[0].NewItem, "The NewItem is incorrect.");
Assert.IsNull(breakingChanges[0].AssociatedData, "The AssociatedData is incorrect.");
breakingChanges = MetadataComparer.CompareTypes(ClassWithInternalConstructor, StaticClass);
Assert.AreEqual(0, breakingChanges.Count, "There should be no breaking changes when a class with no public constructors is made abstract.");
breakingChanges = MetadataComparer.CompareTypes(ClassWithProtectedConstructor, StaticClass).Where(b => b.BreakingChangeKind == BreakingChangeKind.ChangedClassToStatic).ToList();
Assert.AreEqual(1, breakingChanges.Count, "There should be one breaking change when a class is made static.");
Assert.AreEqual(BreakingChangeKind.ChangedClassToStatic, breakingChanges[0].BreakingChangeKind, "The BreakingChangeKind is incorrect.");
Assert.AreEqual(ClassWithProtectedConstructor, breakingChanges[0].OldItem, "The OldItem is incorrect.");
Assert.AreEqual(StaticClass, breakingChanges[0].NewItem, "The NewItem is incorrect.");
Assert.IsNull(breakingChanges[0].AssociatedData, "The AssociatedData is incorrect.");
}
#endregion // TypeTests
public class NestedClass { public class Class { } }
public class NestedClassWithInternalConstructor { public class Class { internal Class() { } } }
public class NestedClassWithProtectedConstructor { public class Class { protected Class() { } } }
public class NestedStaticClass { public static class Class { } }
public class Class { }
public class ClassWithInternalConstructor { internal ClassWithInternalConstructor() { } }
public class ClassWithProtectedConstructor { protected ClassWithProtectedConstructor() { } }
public static class StaticClass { }
}
}
| 60.376147 | 192 | 0.7938 | [
"MIT"
] | IG-JM/BreakingChangesDetector | BreakingChangesDetector.UnitTests/BreakingChangesTests/ChangedClassToStaticTests.cs | 6,583 | C# |
#region Copyright & License
/*
Copyright (c) 2022, Integrated Solutions, Inc.
All rights reserved.
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 Integrated Solutions, Inc. 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT OWNER OR 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.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ISI.Extensions.Documents
{
public interface IDocumentDataSourceRoot
{
IDocumentDataValue GetValue(string fieldName);
IDocumentDataSource GetChildDataSource(string tableName);
}
}
| 62.233333 | 754 | 0.810927 | [
"BSD-3-Clause"
] | ISI-Extensions/ISI.Extensions | src/ISI.Extensions/Documents/IDocumentDataSourceRoot.cs | 1,867 | C# |
using System;
using System.Web.UI.WebControls;
using CMS.Base.Web.UI;
using CMS.Helpers;
using CMS.UIControls;
public partial class CMSModules_Content_Controls_Dialogs_YouTube_YouTubeSizes : CMSUserControl
{
#region "Variables"
private int mMaxSideSize = 60;
private string mOnSelectedItemClick = "";
#endregion
#region "Public properties"
/// <summary>
/// Gets or sets the maximal size of the rectangle in preview.
/// </summary>
public int MaxSideSize
{
get
{
return mMaxSideSize;
}
set
{
mMaxSideSize = value;
}
}
/// <summary>
/// Gets or sets the JavaScript code which is prcessed when some size is clicked.
/// </summary>
public string OnSelectedItemClick
{
get
{
return mOnSelectedItemClick;
}
set
{
mOnSelectedItemClick = value;
}
}
/// <summary>
/// Gets or sets the width.
/// </summary>
public int SelectedWidth
{
get
{
return ValidationHelper.GetInteger(hdnWidth.Value, 0);
}
set
{
hdnWidth.Value = value.ToString();
}
}
/// <summary>
/// Gets or sets the height.
/// </summary>
public int SelectedHeight
{
get
{
return ValidationHelper.GetInteger(hdnHeight.Value, 0);
}
set
{
hdnHeight.Value = value.ToString();
}
}
#endregion
protected void Page_Load(object sender, EventArgs e)
{
// Register scripts
ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "YouTubeSizes", ScriptHelper.GetScript(
"function setSizes(width, height) { \n" +
" var widthElem = document.getElementById('" + hdnWidth.ClientID + "'); \n" +
" var heightElem = document.getElementById('" + hdnHeight.ClientID + "'); \n" +
" if ((widthElem != null) && (heightElem != null)) { \n" +
" widthElem.value = width; \n" +
" heightElem.value = height; \n" + OnSelectedItemClick + "; \n" +
" } \n" +
"} \n"));
}
#region "Public methods"
/// <summary>
/// Loads the sizes previews.
/// </summary>
/// <param name="sizes">Array with sizes (two items per box)</param>
public void LoadSizes(int[] sizes)
{
plcSizes.Controls.Clear();
if (sizes.Length > 1)
{
int max = sizes[0];
foreach (int size in sizes)
{
if (size > max)
{
max = size;
}
}
var radioList = new Panel
{
CssClass = "radio-list-vertical"
};
plcSizes.Controls.Add(radioList);
for (int i = 0; i < sizes.Length; i += 2)
{
var radio = new CMSRadioButton();
radio.Text = sizes[i] + " x " + sizes[i + 1];
radio.Attributes.Add("onclick", "setSizes('" + sizes[i] + "', '" + sizes[i + 1] + "');");
radio.GroupName = "size";
if ((sizes[i] == SelectedWidth) && (sizes[i + 1] == SelectedHeight))
{
radio.InputAttributes.Add("checked", "checked");
}
radioList.Controls.Add(radio);
}
}
}
#endregion
}
| 24.027211 | 108 | 0.494337 | [
"MIT"
] | BryanSoltis/KenticoMVCWidgetShowcase | CMS/CMSModules/Content/Controls/Dialogs/YouTube/YouTubeSizes.ascx.cs | 3,534 | C# |
using SFA.DAS.Payments.AcceptanceTests.Assertions.DataLockRules;
using SFA.DAS.Payments.AcceptanceTests.Contexts;
using SFA.DAS.Payments.AcceptanceTests.ResultsDataModels;
namespace SFA.DAS.Payments.AcceptanceTests.Assertions
{
public static class DataLockAssertions
{
private static readonly DataLockRuleBase[] Rules =
{
new DataLockEventsRule(),
new DataLockErrorsRule(),
new DataLockPeriodsRule(),
new DataLockCommitmentVersionRule(),
};
public static void AssertDataLockOutput(DataLockContext context, LearnerResults[] results)
{
if (TestEnvironment.ValidateSpecsOnly)
{
return;
}
foreach (var rule in Rules)
{
rule.AssertDataLockEvents(context, results);
}
}
}
}
| 29.483871 | 99 | 0.600656 | [
"MIT"
] | SkillsFundingAgency/das-paymentsacceptancetesting | src/SFA.DAS.Payments.AcceptanceTests/Assertions/DataLockAssertions.cs | 916 | 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.
// ----------------------------------------------------------------------------------
namespace Microsoft.WindowsAzure.Commands.Storage.File.Cmdlet
{
using Microsoft.Azure.Commands.Common.Authentication.Abstractions;
using Microsoft.Azure.Storage;
using Microsoft.Azure.Storage.File;
using Microsoft.WindowsAzure.Commands.Storage.Model.ResourceModel;
using System.Globalization;
using System.Management.Automation;
using System.Net;
[Cmdlet("Close", Azure.Commands.ResourceManager.Common.AzureRMConstants.AzurePrefix + "StorageFileHandle", SupportsShouldProcess = true, DefaultParameterSetName = ShareNameCloseAllParameterSetName)]
[OutputType(typeof(int))]
public class CloseAzureStorageFileHandle : AzureStorageFileCmdletBase
{
/// <summary>
/// Parameter set name for ShareName.
/// </summary>
public const string ShareNameCloseAllParameterSetName = "ShareNameCloseAll";
/// <summary>
/// Parameter set name for directory.
/// </summary>
public const string DirectoryCloseAllParameterSetName = "DirectoryCloseAll";
/// <summary>
/// Parameter set name for Share CloseAll.
/// </summary>
public const string ShareCloseAllParameterSetName = "ShareCloseAll";
/// <summary>
/// Parameter set name for File CloseAll.
/// </summary>
public const string FileCloseAllParameterSetName = "FileCloseAll";
/// <summary>
/// Parameter set name for ShareName.
/// </summary>
public const string ShareNameCloseSingleParameterSetName = "ShareNameCloseSingle";
///// <summary>
///// Parameter set name for directory.
///// </summary>
//public const string DirectoryCloseSingleParameterSetName = "DirectoryCloseSingle";
/// <summary>
/// Parameter set name for Share CloseAll.
/// </summary>
public const string ShareCloseSingleParameterSetName = "ShareCloseSingle";
///// <summary>
///// Parameter set name for File CloseAll.
///// </summary>
//public const string FileCloseSingleParameterSetName = "FileCloseSingle";
[Parameter(
Position = 0,
Mandatory = true,
ParameterSetName = ShareNameCloseAllParameterSetName,
HelpMessage = "Name of the file share which contains the files/directories to closed handle.")]
[Parameter(
Position = 0,
Mandatory = true,
ParameterSetName = ShareNameCloseSingleParameterSetName,
HelpMessage = "Name of the file share which contains the files/directories to closed handle.")]
[ValidateNotNullOrEmpty]
public string ShareName { get; set; }
[Parameter(
Position = 0,
Mandatory = true,
ValueFromPipeline = true,
ParameterSetName = ShareCloseAllParameterSetName,
HelpMessage = "CloudFileShare object indicated the share which contains the files/directories to closed handle.")]
[Parameter(
Position = 0,
Mandatory = true,
ValueFromPipeline = true,
ParameterSetName = ShareCloseSingleParameterSetName,
HelpMessage = "CloudFileShare object indicated the share which contains the files/directories to closed handle.")]
[ValidateNotNull]
public CloudFileShare Share { get; set; }
[Parameter(
Position = 0,
Mandatory = true,
ValueFromPipeline = true,
ParameterSetName = DirectoryCloseAllParameterSetName,
HelpMessage = "CloudFileDirectory object indicated the base folder which contains the files/directories to closed handle.")]
[ValidateNotNull]
public CloudFileDirectory Directory { get; set; }
[Parameter(
Position = 0,
Mandatory = true,
ValueFromPipeline = true,
ParameterSetName = FileCloseAllParameterSetName,
HelpMessage = "CloudFile object indicated the file to close handle.")]
[ValidateNotNull]
public CloudFile File { get; set; }
[Parameter(
Position = 1,
Mandatory = false,
ParameterSetName = ShareNameCloseAllParameterSetName,
HelpMessage = "Path to an existing file/directory.")]
[Parameter(
Position = 1,
Mandatory = false,
ParameterSetName = ShareCloseAllParameterSetName,
HelpMessage = "Path to an existing file/directory.")]
[Parameter(
Position = 1,
Mandatory = false,
ParameterSetName = DirectoryCloseAllParameterSetName,
HelpMessage = "Path to an existing file/directory.")]
public string Path { get; set; }
[Parameter(Mandatory = true, ParameterSetName = ShareNameCloseSingleParameterSetName, ValueFromPipeline = true, HelpMessage = "The File Handle to close.")]
[Parameter(Mandatory = true, ParameterSetName = ShareCloseSingleParameterSetName, ValueFromPipeline = true, HelpMessage = "The File Handle to close.")]
[ValidateNotNull]
public PSFileHandle FileHandle { get; set; }
[Parameter(Mandatory = false, ParameterSetName = ShareNameCloseAllParameterSetName, HelpMessage = "Closed handles Recursively. Only works on File Directory.")]
[Parameter(Mandatory = false, ParameterSetName = ShareCloseAllParameterSetName, HelpMessage = "Closed handles Recursively. Only works on File Directory.")]
[Parameter(Mandatory = false, ParameterSetName = DirectoryCloseAllParameterSetName, HelpMessage = "Closed handles Recursively. Only works on File Directory.")]
public SwitchParameter Recursive { get; set; }
[Parameter(Mandatory = true, ParameterSetName = ShareNameCloseAllParameterSetName, HelpMessage = "Force close all File handles.")]
[Parameter(Mandatory = true, ParameterSetName = ShareCloseAllParameterSetName, HelpMessage = "Force close all File handles.")]
[Parameter(Mandatory = true, ParameterSetName = DirectoryCloseAllParameterSetName, HelpMessage = "Force close all File handles.")]
[Parameter(Mandatory = true, ParameterSetName = FileCloseAllParameterSetName, HelpMessage = "Force close all File handles.")]
public SwitchParameter CloseAll { get; set; }
[Parameter(
ValueFromPipeline = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = ShareNameCloseSingleParameterSetName,
HelpMessage = "Azure Storage Context Object")]
[Parameter(
ValueFromPipeline = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = ShareNameCloseAllParameterSetName,
HelpMessage = "Azure Storage Context Object")]
public override IStorageContext Context { get; set; }
[Parameter(Mandatory = false, HelpMessage = "Return whether the specified blob is successfully removed")]
public SwitchParameter PassThru { get; set; }
[Parameter(Mandatory = false, HelpMessage = "Run cmdlet in the background")]
public virtual SwitchParameter AsJob { get; set; }
public override void ExecuteCmdlet()
{
if (this.ShouldProcess(string.Format("Close File Handles for File or FileDirectory on Path: {0}", this.Path != null? this.Path : (this.FileHandle != null? this.FileHandle.Path: null) ), "This operation will force the provided file handle(s) closed, which may cause data loss or corruption for active applications/users.", null))
{
CloudFileDirectory baseDirectory = null;
switch (this.ParameterSetName)
{
case DirectoryCloseAllParameterSetName:
baseDirectory = this.Directory;
break;
case ShareNameCloseSingleParameterSetName:
case ShareNameCloseAllParameterSetName:
baseDirectory = this.BuildFileShareObjectFromName(this.ShareName).GetRootDirectoryReference();
break;
case ShareCloseSingleParameterSetName:
case ShareCloseAllParameterSetName:
baseDirectory = this.Share.GetRootDirectoryReference();
break;
case FileCloseAllParameterSetName:
// Don't need to set baseDirectory when input is a CloudFile
break;
default:
throw new PSArgumentException(string.Format(CultureInfo.InvariantCulture, "Invalid parameter set name: {0}", this.ParameterSetName));
}
if(ParameterSetName == ShareNameCloseSingleParameterSetName || ParameterSetName == ShareCloseSingleParameterSetName)
{
this.Path = FileHandle.Path;
}
// When not input path/File, the list handle target must be a Dir
bool foundAFolder = true;
CloudFileDirectory targetDir = baseDirectory;
CloudFile targetFile = null;
if (this.File != null)
{
targetFile = this.File;
foundAFolder = false;
}
else
{
if (!string.IsNullOrEmpty(this.Path))
{
string[] subfolders = NamingUtil.ValidatePath(this.Path);
targetDir = baseDirectory.GetDirectoryReferenceByPath(subfolders);
if (!targetDir.Exists())
{
foundAFolder = false;
}
if (!foundAFolder)
{
//Get file
string[] filePath = NamingUtil.ValidatePath(this.Path, true);
targetFile = baseDirectory.GetFileReferenceByPath(filePath);
this.Channel.FetchFileAttributesAsync(
targetFile,
null,
this.RequestOptions,
this.OperationContext,
this.CmdletCancellationToken).ConfigureAwait(false);
}
}
}
// Recursive only take effect on File Dir
if (!foundAFolder && Recursive.IsPresent)
{
WriteVerbose("The target object of the 'Path' is an Azure File, the parameter '-Recursive' won't take effect.");
}
//Close handle
CloseFileHandleResultSegment closeResult = null;
FileContinuationToken continuationToken = null;
int numHandlesClosed = 0;
do
{
if (foundAFolder)
{
if (FileHandle != null)
{
// close single handle on fileDir
if (this.FileHandle.HandleId == null)
{
throw new System.ArgumentException(string.Format("The HandleId of the FileHandle on path {0} should not be null.", this.FileHandle.Path), "FileHandle");
}
closeResult = targetDir.CloseHandleSegmented(this.FileHandle.HandleId.ToString(), continuationToken, Recursive, null, this.RequestOptions, this.OperationContext);
}
else
{
// close all handle on fileDir
closeResult = targetDir.CloseAllHandlesSegmented(continuationToken, Recursive, null, this.RequestOptions, this.OperationContext);
}
}
else
{
if (FileHandle != null)
{
// close single handle on file
if (this.FileHandle.HandleId == null)
{
throw new System.ArgumentException(string.Format("The HandleId of the FileHandle on path {0} should not be null.", this.FileHandle.Path), "FileHandle");
}
closeResult = targetFile.CloseHandleSegmented(this.FileHandle.HandleId.ToString(), continuationToken, null, this.RequestOptions, this.OperationContext);
}
else
{
// close all handle on file
closeResult = targetFile.CloseAllHandlesSegmented(continuationToken, null, this.RequestOptions, this.OperationContext);
}
}
numHandlesClosed += closeResult.NumHandlesClosed;
continuationToken = closeResult.ContinuationToken;
} while (continuationToken != null && continuationToken.NextMarker != null);
if (PassThru)
{
WriteObject(numHandlesClosed);
}
}
}
}
}
| 49.237288 | 341 | 0.566609 | [
"MIT"
] | AzureMentor/azure-powershell | src/Storage/Storage/File/Cmdlet/CloseAzureStorageFileHandle.cs | 14,233 | C# |
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Leger;
namespace HyperGraph.VsTests
{
[TestClass]
public class GraphCoreTests
{
[TestMethod]
public void RemoveVertexSimpleGraph()
{
GraphObjectTypeInfo vertexType = new GraphObjectTypeInfo("33ca7d63-78e0-44b2-90b2-279f20f48856", "Test Vertex Type", GraphObjectType.Vertex);
GraphObjectTypeInfo edgeType = new GraphObjectTypeInfo("9eaa1218-14d9-46cd-9678-c2a29128982f", "Test Edge Type", GraphObjectType.Edge);
Graph g = new Graph();
IVertex origin = VertexExtensions.CreateTextVertex(vertexType, "v1");
IVertex target = VertexExtensions.CreateTextVertex(vertexType, "v2");
g.AddVertex(origin);
g.AddVertex(target);
g.CreateEdge(edgeType, origin, target);
Assert.AreEqual<int>(1, origin.Links.Count);
Assert.AreEqual<int>(1, target.Links.Count);
g.RemoveVertex(target);
List<IVertex> results = g.SearchNode("", "v2");
Assert.IsNull(results);
Assert.AreEqual<int>(0, origin.Links.Count);
// not in the graph anymore but should have the reference to the edge deleted
Assert.AreEqual<int>(0, target.Links.Count);
}
[TestMethod]
public void RemoveEdgeSimpleGraph()
{
GraphObjectTypeInfo vertexType = new GraphObjectTypeInfo("33ca7d63-78e0-44b2-90b2-279f20f48856", "Test Vertex Type", GraphObjectType.Vertex);
GraphObjectTypeInfo edgeType = new GraphObjectTypeInfo("9eaa1218-14d9-46cd-9678-c2a29128982f", "Test Edge Type", GraphObjectType.Edge);
Graph g = new Graph();
IVertex origin = VertexExtensions.CreateTextVertex(vertexType, "v1");
IVertex target = VertexExtensions.CreateTextVertex(vertexType, "v2");
g.AddVertex(origin);
g.AddVertex(target);
IEdge edge = g.CreateEdge(edgeType, origin, target);
Assert.AreEqual<int>(1, origin.Links.Count);
Assert.AreEqual<int>(1, target.Links.Count);
Assert.AreEqual<int>(1, g.EdgesNumber);
g.RemoveEdge(edge);
Assert.AreEqual<int>(0, origin.Links.Count);
Assert.AreEqual<int>(0, target.Links.Count);
Assert.AreEqual<int>(0, g.EdgesNumber);
}
}
} | 40.370968 | 154 | 0.622054 | [
"BSD-3-Clause"
] | titanix/HyperGraph_Public | HyperGraph.VsTests/GraphCoreTests.cs | 2,505 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Oci.Functions
{
public static class GetApplications
{
/// <summary>
/// This data source provides the list of Applications in Oracle Cloud Infrastructure Functions service.
///
/// Lists applications for a compartment.
///
/// {{% examples %}}
/// ## Example Usage
/// {{% example %}}
///
/// ```csharp
/// using Pulumi;
/// using Oci = Pulumi.Oci;
///
/// class MyStack : Stack
/// {
/// public MyStack()
/// {
/// var testApplications = Output.Create(Oci.Functions.GetApplications.InvokeAsync(new Oci.Functions.GetApplicationsArgs
/// {
/// CompartmentId = @var.Compartment_id,
/// DisplayName = @var.Application_display_name,
/// Id = @var.Application_id,
/// State = @var.Application_state,
/// }));
/// }
///
/// }
/// ```
/// {{% /example %}}
/// {{% /examples %}}
/// </summary>
public static Task<GetApplicationsResult> InvokeAsync(GetApplicationsArgs args, InvokeOptions? options = null)
=> Pulumi.Deployment.Instance.InvokeAsync<GetApplicationsResult>("oci:functions/getApplications:getApplications", args ?? new GetApplicationsArgs(), options.WithVersion());
}
public sealed class GetApplicationsArgs : Pulumi.InvokeArgs
{
/// <summary>
/// The [OCID](https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm) of the compartment to which this resource belongs.
/// </summary>
[Input("compartmentId", required: true)]
public string CompartmentId { get; set; } = null!;
/// <summary>
/// A filter to return only applications with display names that match the display name string. Matching is exact.
/// </summary>
[Input("displayName")]
public string? DisplayName { get; set; }
[Input("filters")]
private List<Inputs.GetApplicationsFilterArgs>? _filters;
public List<Inputs.GetApplicationsFilterArgs> Filters
{
get => _filters ?? (_filters = new List<Inputs.GetApplicationsFilterArgs>());
set => _filters = value;
}
/// <summary>
/// A filter to return only applications with the specified OCID.
/// </summary>
[Input("id")]
public string? Id { get; set; }
/// <summary>
/// A filter to return only applications that match the lifecycle state in this parameter. Example: `Creating`
/// </summary>
[Input("state")]
public string? State { get; set; }
public GetApplicationsArgs()
{
}
}
[OutputType]
public sealed class GetApplicationsResult
{
/// <summary>
/// The list of applications.
/// </summary>
public readonly ImmutableArray<Outputs.GetApplicationsApplicationResult> Applications;
/// <summary>
/// The OCID of the compartment that contains the application.
/// </summary>
public readonly string CompartmentId;
/// <summary>
/// The display name of the application. The display name is unique within the compartment containing the application.
/// </summary>
public readonly string? DisplayName;
public readonly ImmutableArray<Outputs.GetApplicationsFilterResult> Filters;
/// <summary>
/// The [OCID](https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm) of the application.
/// </summary>
public readonly string? Id;
/// <summary>
/// The current state of the application.
/// </summary>
public readonly string? State;
[OutputConstructor]
private GetApplicationsResult(
ImmutableArray<Outputs.GetApplicationsApplicationResult> applications,
string compartmentId,
string? displayName,
ImmutableArray<Outputs.GetApplicationsFilterResult> filters,
string? id,
string? state)
{
Applications = applications;
CompartmentId = compartmentId;
DisplayName = displayName;
Filters = filters;
Id = id;
State = state;
}
}
}
| 34.818841 | 184 | 0.58127 | [
"ECL-2.0",
"Apache-2.0"
] | EladGabay/pulumi-oci | sdk/dotnet/Functions/GetApplications.cs | 4,805 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.18444
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System.CodeDom.Compiler;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Drawing;
using System.Globalization;
using System.Resources;
using System.Runtime.CompilerServices;
namespace DotSpatial.Plugins.SimpleLegend.Properties {
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[GeneratedCode("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[DebuggerNonUserCode()]
[CompilerGenerated()]
internal class Resources {
private static ResourceManager resourceMan;
private static CultureInfo resourceCulture;
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
internal static ResourceManager ResourceManager {
get {
if (ReferenceEquals(resourceMan, null)) {
ResourceManager temp = new ResourceManager("DotSpatial.Plugins.SimpleLegend.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
internal static CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized string similar to Legend.
/// </summary>
internal static string Legend {
get {
return ResourceManager.GetString("Legend", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static Bitmap legend_16x16 {
get {
object obj = ResourceManager.GetObject("legend_16x16", resourceCulture);
return ((Bitmap)(obj));
}
}
}
}
| 36.696629 | 148 | 0.558481 | [
"MIT"
] | sdrmaps/dotspatial | Source/DotSpatial.Plugins.Legend/Properties/Resources.Designer.cs | 3,268 | C# |
Subsets and Splits