content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
namespace _07_SelectionSort
{
using System;
class SelectionSort
{
/* Sorting an array means to arrange its elements in increasing
order. Write a program to sort an array.
Use the Selection sort algorithm: Find the smallest element,
move it at the first position, find the smallest from the rest,
move it at the second position, etc.*/
static void Main()
{
//int[] arr = { 23, 2, 3, 34, 6 };
Console.Write("Enter array (devided by space): ");
string str = Console.ReadLine();
string[] numStr = str.Split(' ');
int[] arr = new int[numStr.Length];
for (int i = 0; i < numStr.Length; i++)
{
arr[i] = int.Parse(numStr[i]);
}
SelectSort(arr, arr.Length);
for (int j = 0; j < 5; j++)
{
Console.Write(arr[j] + " "); //after sorting
}
Console.WriteLine();
}
///selection sort
static void SelectSort(int[] dataset, int n)
{
int i, j;
for (i = 0; i < n; i++)
{
int min = i;
for (j = i + 1; j < n; j++)
{
if (dataset[j] < dataset[min])
{
min = j;
}
}
int temp = dataset[i];
dataset[i] = dataset[min];
dataset[min] = temp;
}
}
}
}
| 26.278689 | 72 | 0.412352 | [
"MIT"
] | theshaftman/Telerik-Academy | C# Part 2/01-Arrays/07_SelectionSort/SelectionSort.cs | 1,605 | C# |
// <copyright file="BadWordContext.cs" company="The Shinoa Development Team">
// Copyright (c) 2016 - 2017 OmegaVesko.
// Copyright (c) 2017 The Shinoa Development Team.
// Licensed under the MIT license.
// </copyright>
namespace Shinoa.Databases
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using Microsoft.EntityFrameworkCore;
/// <summary>
/// A <see cref="DbContext"/> for filtering bad words.
/// </summary>
public class BadWordContext : DbContext, IDatabaseContext
{
/// <inheritdoc cref="DbContext"/>
public BadWordContext(DbContextOptions options)
: base(options)
{
}
/// <summary>
/// Gets or sets the <see cref="DbSet{TEntity}"/> for channel based badword bindings.
/// </summary>
public DbSet<BadWordChannelBinding> BadWordChannelBindings { get; set; }
/// <summary>
/// Gets or sets the <see cref="DbSet{TEntity}"/> for server based badword bindings.
/// </summary>
public DbSet<BadWordServerBinding> BadWordServerBindings { get; set; }
/// <inheritdoc />
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder
.HasDefaultSchema("badwordfilter")
.Entity<ChannelBadWord>()
.HasKey(b => new { b.ChannelIdString, b.Entry });
modelBuilder
.Entity<ChannelBadWord>()
.HasIndex(b => b.ServerIdString);
modelBuilder
.Entity<ServerBadWord>()
.HasKey(b => new { b.ServerIdString, b.Entry });
modelBuilder
.Entity<BadWordChannelBinding>()
.HasIndex(b => b.ServerIdString);
}
/// <summary>
/// A channel-based binding for badwords.
/// </summary>
public class BadWordChannelBinding
{
/// <summary>
/// Gets or sets the channel ID string.
/// </summary>
[Key]
public string ChannelIdString { get; set; }
/// <summary>
/// Gets or sets the channel ID, backed by <see cref="ChannelIdString"/>.
/// </summary>
[NotMapped]
public ulong ChannelId
{
get => ulong.Parse(ChannelIdString);
set => ChannelIdString = value.ToString();
}
/// <summary>
/// Gets or sets the server ID string.
/// </summary>
public string ServerIdString { get; set; }
/// <summary>
/// Gets or sets the server ID, backed by <see cref="ServerIdString"/>.
/// </summary>
[NotMapped]
public ulong ServerId
{
get => ulong.Parse(ServerIdString);
set => ServerIdString = value.ToString();
}
/// <summary>
/// Gets or sets the <see cref="List{T}"/> of channel-based badwords.
/// </summary>
public List<ChannelBadWord> BadWords { get; set; }
}
/// <summary>
/// A guild-based binding for badwords.
/// </summary>
public class BadWordServerBinding
{
[Key]
/// <summary>
/// Gets or sets the server ID string.
/// </summary>
public string ServerIdString { get; set; }
/// <summary>
/// Gets or sets the server ID, backed by <see cref="ServerIdString"/>.
/// </summary>
[NotMapped]
public ulong ServerId
{
get => ulong.Parse(ServerIdString);
set => ServerIdString = value.ToString();
}
/// <summary>
/// Gets or sets the <see cref="List{T}"/> of guild-based badwords.
/// </summary>
public List<ServerBadWord> BadWords { get; set; }
}
/// <summary>
/// A badword, filtered in a specific guild.
/// </summary>
public class ServerBadWord : IEquatable<ServerBadWord>
{
/// <summary>
/// Gets or sets the server.
/// </summary>
public BadWordServerBinding Server { get; set; }
[ForeignKey("Server")]
/// <summary>
/// Gets or sets the server ID string.
/// </summary>
public string ServerIdString { get; set; }
/// <summary>
/// Gets or sets the server ID, backed by <see cref="ServerIdString"/>.
/// </summary>
[NotMapped]
public ulong ServerId
{
get => ulong.Parse(ServerIdString);
set => ServerIdString = value.ToString();
}
/// <summary>
/// Gets or sets the string value of the badword.
/// </summary>
public string Entry { get; set; }
public static bool operator ==(ServerBadWord left, ServerBadWord right)
{
return Equals(left, right);
}
public static bool operator !=(ServerBadWord left, ServerBadWord right)
{
return !Equals(left, right);
}
/// <inheritdoc />
public override int GetHashCode()
{
unchecked
{
return ((ServerIdString != null ? ServerIdString.GetHashCode() : 0) * 397) ^ (Entry != null ? Entry.GetHashCode() : 0);
}
}
/// <inheritdoc />
public bool Equals(ServerBadWord other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return string.Equals(ServerIdString, other.ServerIdString) && string.Equals(Entry, other.Entry);
}
/// <inheritdoc />
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
return obj.GetType() == this.GetType() && Equals((ServerBadWord)obj);
}
}
/// <summary>
/// A badword, filtered in a specific channel.
/// </summary>
public class ChannelBadWord : IEquatable<ChannelBadWord>
{
/// <summary>
/// Gets or sets the channel.
/// </summary>
public BadWordChannelBinding Channel { get; set; }
/// <summary>
/// Gets or sets the channel ID string.
/// </summary>
[ForeignKey("Channel")]
public string ChannelIdString { get; set; }
/// <summary>
/// Gets or sets the channel ID, backed by <see cref="ChannelIdString"/>.
/// </summary>
[NotMapped]
public ulong ChannelId
{
get => ulong.Parse(ChannelIdString);
set => ChannelIdString = value.ToString();
}
/// <summary>
/// Gets or sets the server ID string.
/// </summary>
public string ServerIdString { get; set; }
/// <summary>
/// Gets or sets the server ID, backed by <see cref="ServerIdString"/>.
/// </summary>
[NotMapped]
public ulong ServerId
{
get => ulong.Parse(ServerIdString);
set => ServerIdString = value.ToString();
}
/// <summary>
/// Gets or sets the string value of the badword.
/// </summary>
public string Entry { get; set; }
public static bool operator ==(ChannelBadWord left, ChannelBadWord right)
{
return Equals(left, right);
}
public static bool operator !=(ChannelBadWord left, ChannelBadWord right)
{
return !Equals(left, right);
}
/// <inheritdoc />
public bool Equals(ChannelBadWord other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return string.Equals(ChannelIdString, other.ChannelIdString) && string.Equals(ServerIdString, other.ServerIdString) && string.Equals(Entry, other.Entry);
}
/// <inheritdoc />
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
return obj.GetType() == this.GetType() && Equals((ChannelBadWord)obj);
}
/// <inheritdoc />
public override int GetHashCode()
{
unchecked
{
var hashCode = ChannelIdString != null ? ChannelIdString.GetHashCode() : 0;
hashCode = (hashCode * 397) ^ (ServerIdString != null ? ServerIdString.GetHashCode() : 0);
hashCode = (hashCode * 397) ^ (Entry != null ? Entry.GetHashCode() : 0);
return hashCode;
}
}
}
}
}
| 34.078292 | 169 | 0.501149 | [
"MIT"
] | Dormanil/Shinoa | src/Shinoa/Databases/BadWordContext.cs | 9,578 | 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("ThirdPlugin")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("ThirdPlugin")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("628759be-40e2-484b-aa88-0feddc689c24")]
// 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")]
| 38.189189 | 84 | 0.748054 | [
"Apache-2.0"
] | TallaXL/SimplePlugin | ThirdPlugin/Properties/AssemblyInfo.cs | 1,416 | C# |
using System;
using System.Collections.Generic;
namespace GenericCountMethodDoubles
{
class Program
{
static void Main()
{
var lines = int.Parse(Console.ReadLine());
var list = new List<Box<double>>();
for (int i = 0; i < lines; i++)
{
var input = Console.ReadLine();
list.Add(new Box<double>(double.Parse(input)));
}
var value = double.Parse(Console.ReadLine());
Console.WriteLine(GetBiggerItems(list, value));
}
static int GetBiggerItems<T>(IEnumerable<Box<T>> list, T compareItem) where T : IComparable<T>
{
int counter = 0;
foreach (var item in list)
{
if (item.CompareTo(compareItem) > 0) counter++;
}
return counter;
}
}
}
| 27.75 | 102 | 0.507883 | [
"MIT"
] | rumenand/HomeWork_Tasks | CSharp Advanced/07.Exercises Generics/GenericCountMethodDoubles/Program.cs | 890 | C# |
using BrockAllen.MembershipReboot.Helpers;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
const int StartYear = 2000;
const int StartCount = 1000;
var sw = new Stopwatch();
for (int year = 2000; true; year += 2)
{
var diff = (year - StartYear) / 2;
var mul = (int)Math.Pow(2, diff);
int count = StartCount * mul;
// if we go negative, then we wrapped (expected in year ~2044).
// Int32.Max is best we can do at this point
if (count < 0) count = Int32.MaxValue;
sw.Reset();
sw.Start();
var result = Crypto.HashPassword("pass", count);
sw.Stop();
Console.WriteLine("year: {0}, mul:{1}, count:{2}, dur: {3}", year, mul, count, sw.ElapsedMilliseconds/1000.0);
if (count == Int32.MaxValue)
{
break;
}
}
}
}
}
| 30.609756 | 126 | 0.495618 | [
"BSD-3-Clause"
] | Bringsy/BrockAllen.MembershipReboot | util/PasswordStretchingTimings/PasswordStretchingTimings/Program.cs | 1,257 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the directconnect-2012-10-25.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.DirectConnect.Model
{
/// <summary>
/// Container for the parameters to the DescribeDirectConnectGatewayAttachments operation.
/// Returns a list of all direct connect gateway and virtual interface (VIF) attachments.
/// Either a direct connect gateway ID or a VIF ID must be provided in the request. If
/// a direct connect gateway ID is provided, the response returns all VIFs attached to
/// the direct connect gateway. If a VIF ID is provided, the response returns all direct
/// connect gateways attached to the VIF. If both are provided, the response only returns
/// the attachment that matches both the direct connect gateway and the VIF.
/// </summary>
public partial class DescribeDirectConnectGatewayAttachmentsRequest : AmazonDirectConnectRequest
{
private string _directConnectGatewayId;
private int? _maxResults;
private string _nextToken;
private string _virtualInterfaceId;
/// <summary>
/// Gets and sets the property DirectConnectGatewayId.
/// <para>
/// The ID of the direct connect gateway.
/// </para>
///
/// <para>
/// Example: "abcd1234-dcba-5678-be23-cdef9876ab45"
/// </para>
///
/// <para>
/// Default: None
/// </para>
/// </summary>
public string DirectConnectGatewayId
{
get { return this._directConnectGatewayId; }
set { this._directConnectGatewayId = value; }
}
// Check to see if DirectConnectGatewayId property is set
internal bool IsSetDirectConnectGatewayId()
{
return this._directConnectGatewayId != null;
}
/// <summary>
/// Gets and sets the property MaxResults.
/// <para>
/// The maximum number of direct connect gateway attachments to return per page.
/// </para>
///
/// <para>
/// Example: 15
/// </para>
///
/// <para>
/// Default: None
/// </para>
/// </summary>
public int MaxResults
{
get { return this._maxResults.GetValueOrDefault(); }
set { this._maxResults = value; }
}
// Check to see if MaxResults property is set
internal bool IsSetMaxResults()
{
return this._maxResults.HasValue;
}
/// <summary>
/// Gets and sets the property NextToken.
/// <para>
/// The token provided in the previous describe result to retrieve the next page of the
/// result.
/// </para>
///
/// <para>
/// Default: None
/// </para>
/// </summary>
public string NextToken
{
get { return this._nextToken; }
set { this._nextToken = value; }
}
// Check to see if NextToken property is set
internal bool IsSetNextToken()
{
return this._nextToken != null;
}
/// <summary>
/// Gets and sets the property VirtualInterfaceId.
/// <para>
/// The ID of the virtual interface.
/// </para>
///
/// <para>
/// Example: "dxvif-abc123ef"
/// </para>
///
/// <para>
/// Default: None
/// </para>
/// </summary>
public string VirtualInterfaceId
{
get { return this._virtualInterfaceId; }
set { this._virtualInterfaceId = value; }
}
// Check to see if VirtualInterfaceId property is set
internal bool IsSetVirtualInterfaceId()
{
return this._virtualInterfaceId != null;
}
}
} | 31.641892 | 111 | 0.584668 | [
"Apache-2.0"
] | GitGaby/aws-sdk-net | sdk/src/Services/DirectConnect/Generated/Model/DescribeDirectConnectGatewayAttachmentsRequest.cs | 4,683 | C# |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters;
using System.Management.Automation;
namespace Microsoft.Azure.Commands.Sql.Common
{
/// <summary>
/// The base class for all Azure Sql database cmdlets
/// </summary>
public abstract class AzureSqlDatabaseCmdletBase<M, A> : AzureSqlCmdletBase<M, A>
{
/// <summary>
/// Gets or sets the name of the database server to use.
/// </summary>
[Parameter(Mandatory = true,
ValueFromPipelineByPropertyName = true,
Position = 1,
HelpMessage = "SQL Database server name.")]
[ResourceNameCompleter("Microsoft.Sql/servers", "ResourceGroupName")]
[ValidateNotNullOrEmpty]
public string ServerName { get; set; }
/// <summary>
/// Gets or sets the name of the database to use.
/// </summary>
[Parameter(Mandatory = true,
ValueFromPipelineByPropertyName = true,
Position = 2,
HelpMessage = "SQL Database name.")]
[ResourceNameCompleter("Microsoft.Sql/servers/databases", "ResourceGroupName", "ServerName")]
[ValidateNotNullOrEmpty]
public string DatabaseName { get; set; }
}
}
| 42.666667 | 102 | 0.602051 | [
"MIT"
] | Acidburn0zzz/azure-powershell | src/ResourceManager/Sql/Commands.Sql/Common/AzureSqlDatabaseCmdletBase.cs | 2,001 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using AdventOfCode.Common;
using JetBrains.Annotations;
namespace AdventOfCode.Solutions._2017._14;
[UsedImplicitly]
public class Year2017Day14 : ISolution
{
public object Part1(IEnumerable<string> input)
{
var key = input.First();
var grid = GetGrid(key);
var res = 0;
for (var x = 0; x < 128; x++)
{
for (var y = 0; y < 128; y++)
{
if (grid[x, y] == '#')
res++;
}
}
return res.ToString();
}
public object Part2(IEnumerable<string> input)
{
var key = input.First();
var grid = GetGrid(key);
var regions = 0;
for (var x = 0; x < 128; x++)
{
for (var y = 0; y < 128; y++)
{
if(grid[x, y] != '#') continue;
regions++;
CleanRegion(grid, x, y);
}
}
return regions.ToString();
}
private static char[,] GetGrid(string key)
{
var grid = new char[128, 128];
for (var i = 0; i < 128; i++)
{
var keyToHash = $"{key}-{i}";
var hexString = Hash(keyToHash);
var binaryString = string.Join(string.Empty,
hexString.Select(
c => Convert.ToString(Convert.ToInt32(c.ToString(), 16), 2).PadLeft(4, '0')
)
);
for (var j = 0; j < 128; j++)
{
grid[i, j] = binaryString[j] == '1' ? '#' : '.';
}
}
return grid;
}
private static void CleanRegion(char[,] grid, int x, int y)
{
if(grid[x, y] != '#')
return;
grid[x, y] = '.';
if(y + 1 < 128) CleanRegion(grid, x, y + 1);
if(y > 0) CleanRegion(grid, x, y - 1);
if(x + 1 < 128) CleanRegion(grid, x + 1, y);
if(x > 0) CleanRegion(grid, x - 1, y);
}
private static IEnumerable<int> ReverseSection(IList<int> list, int position, int length)
{
var newList = new List<int>(list);
for (var i = 0; i < length; i++)
{
newList[(i + position) % newList.Count] =
list[(position + length - i - 1) % newList.Count];
}
return newList;
}
private static string Hash(string input)
{
var list = Enumerable.Range(0, 256).ToArray();
var lengths = input.Select(r => (int) r).Concat(new[] {17, 31, 73, 47, 23}).ToArray();
var currentPosition = 0;
var skipSize = 0;
for (var i = 1; i <= 64; i++)
{
foreach (var length in lengths)
{
list = ReverseSection(list, currentPosition, length).ToArray();
currentPosition += length + skipSize;
skipSize++;
}
}
return string.Join(string.Empty,
list
.Select((num, idx) => new {num, idx})
.GroupBy(r => r.idx / 16)
.Select(r => r.Aggregate(0, (acc, el) => acc ^ el.num))
.Select(r => r.ToString("X").PadLeft(2, '0'))
);
}
} | 21.647059 | 90 | 0.576087 | [
"MIT"
] | PDmatrix/advent-of-code | CSharp/Solutions/2017/14/Year2017Day14.cs | 2,576 | C# |
using System;
using System.IO;
using System.Threading.Tasks;
using IonDotnet.Builders;
using IonDotnet.Internals.Text;
namespace IonDotnet.Serialization
{
public class IonTextSerializer
{
public string Serialize<T>(T obj, IScalarWriter scalarWriter = null)
=> Serialize(obj, IonTextOptions.Default, scalarWriter);
public string Serialize<T>(T obj, IonTextOptions options, IScalarWriter scalarWriter = null)
{
using (var sw = new StringWriter())
{
var writer = new IonTextWriter(sw, options);
IonSerializationPrivate.WriteObject(writer, obj, scalarWriter);
return sw.ToString();
}
}
public Task SerializeAsync<T>(T obj, Stream stream, IonTextOptions options)
{
if (!stream.CanWrite)
throw new ArgumentException("Stream must be writable", nameof(stream));
using (var streamWriter = new StreamWriter(stream))
{
var writer = new IonTextWriter(streamWriter, options);
IonSerializationPrivate.WriteObject(writer, obj, null);
}
return Task.CompletedTask;
}
/// <summary>
/// Deserialize a text format to object type T
/// </summary>
/// <param name="text">Text input</param>
/// <typeparam name="T">Type of object to deserialize to</typeparam>
/// <returns>Deserialized object</returns>
public T Deserialize<T>(string text)
{
var reader = new UserTextReader(text);
reader.MoveNext();
return (T) IonSerializationPrivate.Deserialize(reader, typeof(T));
}
}
}
| 33.403846 | 100 | 0.597582 | [
"MIT"
] | almann/ion-dotnet | IonDotnet.Serialization/IonTextSerializer.cs | 1,739 | C# |
using LiteDB;
using DCL_Core.Contracts;
using System;
namespace DCL_Core.LiteDB
{
public class HandleLiteDB
{
public LiteDatabase ChainDB;
public LiteDatabase OpenDB()
{
ChainDB = new LiteDatabase(@"DCL_Core.db");
return ChainDB;
}
public void InsertTransaction(Transaction _Transaction)
{
var col = ChainDB.GetCollection<Transaction>("Transaction");
col.EnsureIndex(x => x.TransactionId, true);
col.Insert(_Transaction);
}
public void InsertCompletedTrans(CompletedTransaction _completedTransaction)
{
var col = ChainDB.GetCollection<CompletedTransaction>("CompleteTransaction");
col.EnsureIndex(x => x.TransactionId, true);
col.Insert(_completedTransaction);
}
public void InsertSpendShare(ShareSpend _ShareSpend)
{
var col = ChainDB.GetCollection<ShareSpend>("ShareSpend");
col.EnsureIndex(x => x.ShareId, true);
col.Insert(_ShareSpend);
}
public void InsertUnspendShare(Share _Share)
{
var col = ChainDB.GetCollection<Share>("Share");
col.EnsureIndex(x => x.ShareId, true);
col.Insert(_Share);
}
}
}
| 27.22449 | 89 | 0.593703 | [
"MIT"
] | JohnJohnssonnl/DCL | DCL_Core/LiteDB/HandleLiteDB.cs | 1,336 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Vic.SportsStore.Domain.Abstract;
using Vic.SportsStore.Domain.Entities;
namespace Vic.SportsStore.Domain.Concrete
{
public class InMemoryProductRepository : IProductsRepository
{
private List<Product> _products = new List<Product>
{
new Product { Name = "Football", Price = 25 },
new Product { Name = "Surf board", Price = 179 },
new Product { Name = "Running shoes", Price = 95 },
new Product { Name = "ball1", Price = 95 },
new Product { Name = "shoes2", Price = 95 }
};
public IEnumerable<Product> Products
{
get
{
return _products;
}
}
public Product DeleteProduct(int productId)
{
throw new NotImplementedException();
}
public void SaveProduct(Product product)
{
throw new NotImplementedException();
}
}
}
| 26.390244 | 64 | 0.577634 | [
"MIT"
] | nbxx/SportsStore06 | SportsStore/Vic.SportsStore.Domain/Concrete/InMemoryProductRepository.cs | 1,084 | C# |
using System.Linq;
using Octopus.Client.Editors;
using Octopus.Client.Exceptions;
using Octopus.Client.Model;
namespace Octopus.Client.Repositories
{
public interface IRunbookRepository : IFindByName<RunbookResource>, IGet<RunbookResource>, ICreate<RunbookResource>, IModify<RunbookResource>, IDelete<RunbookResource>
{
RunbookResource FindByName(ProjectResource project, string name);
RunbookEditor CreateOrModify(ProjectResource project, string name, string description);
RunbookSnapshotTemplateResource GetRunbookSnapshotTemplate(RunbookResource runbook);
RunbookRunTemplateResource GetRunbookRunTemplate(RunbookResource runbook);
RunbookRunPreviewResource GetPreview(DeploymentPromotionTarget promotionTarget);
RunbookRunResource Run(RunbookResource runbook, RunbookRunResource runbookRun);
RunbookRunResource[] Run(RunbookResource runbook, RunbookRunParameters runbookRunParameters);
}
class RunbookRepository : BasicRepository<RunbookResource>, IRunbookRepository
{
private readonly SemanticVersion versionAfterWhichRunbookRunParametersAreAvailable;
private readonly SemanticVersion integrationTestVersion;
public RunbookRepository(IOctopusRepository repository)
: base(repository, "Runbooks")
{
integrationTestVersion = SemanticVersion.Parse("0.0.0-local");
versionAfterWhichRunbookRunParametersAreAvailable = SemanticVersion.Parse("2020.3.1");
}
public RunbookResource FindByName(ProjectResource project, string name)
{
return FindByName(name, path: project.Link("Runbooks"));
}
public RunbookEditor CreateOrModify(ProjectResource project, string name, string description)
{
return new RunbookEditor(this, new RunbookProcessRepository(Repository)).CreateOrModify(project, name, description);
}
public RunbookSnapshotTemplateResource GetRunbookSnapshotTemplate(RunbookResource runbook)
{
return Client.Get<RunbookSnapshotTemplateResource>(runbook.Link("RunbookSnapshotTemplate"));
}
public RunbookRunTemplateResource GetRunbookRunTemplate(RunbookResource runbook)
{
return Client.Get<RunbookRunTemplateResource>(runbook.Link("RunbookRunTemplate"));
}
public RunbookRunPreviewResource GetPreview(DeploymentPromotionTarget promotionTarget)
{
return Client.Get<RunbookRunPreviewResource>(promotionTarget.Link("RunbookRunPreview"));
}
private bool ServerSupportsRunbookRunParameters(string version)
{
var serverVersion = SemanticVersion.Parse(version);
// Note: We want to ensure the server version is >= *any* 2020.3.1, including all pre-releases to consider what may be rolled out to Octopus Cloud.
var preReleaseAgnosticServerVersion =
new SemanticVersion(serverVersion.Major, serverVersion.Minor, serverVersion.Patch);
return preReleaseAgnosticServerVersion >= versionAfterWhichRunbookRunParametersAreAvailable ||
serverVersion == integrationTestVersion;
}
public RunbookRunResource Run(RunbookResource runbook, RunbookRunResource runbookRun)
{
var serverSupportsRunbookRunParameters = ServerSupportsRunbookRunParameters(Repository.LoadRootDocument().Version);
return serverSupportsRunbookRunParameters
? Run(runbook, RunbookRunParameters.MapFrom(runbookRun)).FirstOrDefault()
: Client.Post<object, RunbookRunResource>(runbook.Link("CreateRunbookRun"), runbookRun);
}
public RunbookRunResource[] Run(RunbookResource runbook, RunbookRunParameters runbookRunParameters)
{
var serverVersion = Repository.LoadRootDocument().Version;
var serverSupportsRunbookRunParameters = ServerSupportsRunbookRunParameters(serverVersion);
if (serverSupportsRunbookRunParameters == false)
throw new UnsupportedApiVersionException($"This Octopus Deploy server is an older version ({serverVersion}) that does not yet support RunbookRunParameters. " +
"Please update your Octopus Deploy server to 2020.3.* or newer to access this feature.");
return Client.Post<object, RunbookRunResource[]>(runbook.Link("CreateRunbookRun"), runbookRunParameters);
}
}
} | 50.808989 | 175 | 0.723574 | [
"Apache-2.0"
] | BlythMeister/OctopusClients | source/Octopus.Server.Client/Repositories/RunbookRepository.cs | 4,522 | C# |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: math.proto
#region Designer generated code
using System;
using System.Threading;
using System.Threading.Tasks;
using Grpc.Core;
namespace math {
public static class Math
{
static readonly string __ServiceName = "math.Math";
static readonly Marshaller<global::math.DivArgs> __Marshaller_DivArgs = Marshallers.Create((arg) => arg.ToByteArray(), global::math.DivArgs.ParseFrom);
static readonly Marshaller<global::math.DivReply> __Marshaller_DivReply = Marshallers.Create((arg) => arg.ToByteArray(), global::math.DivReply.ParseFrom);
static readonly Marshaller<global::math.FibArgs> __Marshaller_FibArgs = Marshallers.Create((arg) => arg.ToByteArray(), global::math.FibArgs.ParseFrom);
static readonly Marshaller<global::math.Num> __Marshaller_Num = Marshallers.Create((arg) => arg.ToByteArray(), global::math.Num.ParseFrom);
static readonly Method<global::math.DivArgs, global::math.DivReply> __Method_Div = new Method<global::math.DivArgs, global::math.DivReply>(
MethodType.Unary,
__ServiceName,
"Div",
__Marshaller_DivArgs,
__Marshaller_DivReply);
static readonly Method<global::math.DivArgs, global::math.DivReply> __Method_DivMany = new Method<global::math.DivArgs, global::math.DivReply>(
MethodType.DuplexStreaming,
__ServiceName,
"DivMany",
__Marshaller_DivArgs,
__Marshaller_DivReply);
static readonly Method<global::math.FibArgs, global::math.Num> __Method_Fib = new Method<global::math.FibArgs, global::math.Num>(
MethodType.ServerStreaming,
__ServiceName,
"Fib",
__Marshaller_FibArgs,
__Marshaller_Num);
static readonly Method<global::math.Num, global::math.Num> __Method_Sum = new Method<global::math.Num, global::math.Num>(
MethodType.ClientStreaming,
__ServiceName,
"Sum",
__Marshaller_Num,
__Marshaller_Num);
// client interface
public interface IMathClient
{
global::math.DivReply Div(global::math.DivArgs request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken));
global::math.DivReply Div(global::math.DivArgs request, CallOptions options);
AsyncUnaryCall<global::math.DivReply> DivAsync(global::math.DivArgs request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken));
AsyncUnaryCall<global::math.DivReply> DivAsync(global::math.DivArgs request, CallOptions options);
AsyncDuplexStreamingCall<global::math.DivArgs, global::math.DivReply> DivMany(Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken));
AsyncDuplexStreamingCall<global::math.DivArgs, global::math.DivReply> DivMany(CallOptions options);
AsyncServerStreamingCall<global::math.Num> Fib(global::math.FibArgs request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken));
AsyncServerStreamingCall<global::math.Num> Fib(global::math.FibArgs request, CallOptions options);
AsyncClientStreamingCall<global::math.Num, global::math.Num> Sum(Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken));
AsyncClientStreamingCall<global::math.Num, global::math.Num> Sum(CallOptions options);
}
// server-side interface
public interface IMath
{
Task<global::math.DivReply> Div(global::math.DivArgs request, ServerCallContext context);
Task DivMany(IAsyncStreamReader<global::math.DivArgs> requestStream, IServerStreamWriter<global::math.DivReply> responseStream, ServerCallContext context);
Task Fib(global::math.FibArgs request, IServerStreamWriter<global::math.Num> responseStream, ServerCallContext context);
Task<global::math.Num> Sum(IAsyncStreamReader<global::math.Num> requestStream, ServerCallContext context);
}
// client stub
public class MathClient : ClientBase, IMathClient
{
public MathClient(Channel channel) : base(channel)
{
}
public global::math.DivReply Div(global::math.DivArgs request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
var call = CreateCall(__Method_Div, new CallOptions(headers, deadline, cancellationToken));
return Calls.BlockingUnaryCall(call, request);
}
public global::math.DivReply Div(global::math.DivArgs request, CallOptions options)
{
var call = CreateCall(__Method_Div, options);
return Calls.BlockingUnaryCall(call, request);
}
public AsyncUnaryCall<global::math.DivReply> DivAsync(global::math.DivArgs request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
var call = CreateCall(__Method_Div, new CallOptions(headers, deadline, cancellationToken));
return Calls.AsyncUnaryCall(call, request);
}
public AsyncUnaryCall<global::math.DivReply> DivAsync(global::math.DivArgs request, CallOptions options)
{
var call = CreateCall(__Method_Div, options);
return Calls.AsyncUnaryCall(call, request);
}
public AsyncDuplexStreamingCall<global::math.DivArgs, global::math.DivReply> DivMany(Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
var call = CreateCall(__Method_DivMany, new CallOptions(headers, deadline, cancellationToken));
return Calls.AsyncDuplexStreamingCall(call);
}
public AsyncDuplexStreamingCall<global::math.DivArgs, global::math.DivReply> DivMany(CallOptions options)
{
var call = CreateCall(__Method_DivMany, options);
return Calls.AsyncDuplexStreamingCall(call);
}
public AsyncServerStreamingCall<global::math.Num> Fib(global::math.FibArgs request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
var call = CreateCall(__Method_Fib, new CallOptions(headers, deadline, cancellationToken));
return Calls.AsyncServerStreamingCall(call, request);
}
public AsyncServerStreamingCall<global::math.Num> Fib(global::math.FibArgs request, CallOptions options)
{
var call = CreateCall(__Method_Fib, options);
return Calls.AsyncServerStreamingCall(call, request);
}
public AsyncClientStreamingCall<global::math.Num, global::math.Num> Sum(Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
var call = CreateCall(__Method_Sum, new CallOptions(headers, deadline, cancellationToken));
return Calls.AsyncClientStreamingCall(call);
}
public AsyncClientStreamingCall<global::math.Num, global::math.Num> Sum(CallOptions options)
{
var call = CreateCall(__Method_Sum, options);
return Calls.AsyncClientStreamingCall(call);
}
}
// creates service definition that can be registered with a server
public static ServerServiceDefinition BindService(IMath serviceImpl)
{
return ServerServiceDefinition.CreateBuilder(__ServiceName)
.AddMethod(__Method_Div, serviceImpl.Div)
.AddMethod(__Method_DivMany, serviceImpl.DivMany)
.AddMethod(__Method_Fib, serviceImpl.Fib)
.AddMethod(__Method_Sum, serviceImpl.Sum).Build();
}
// creates a new client
public static MathClient NewClient(Channel channel)
{
return new MathClient(channel);
}
}
}
#endregion
| 52.939597 | 208 | 0.730603 | [
"BSD-3-Clause"
] | denza/grpc | src/csharp/Grpc.Examples/MathGrpc.cs | 7,888 | C# |
// Copyright (c) 2002-2019 "Neo4j,"
// Neo4j Sweden AB [http://neo4j.com]
//
// This file is part of Neo4j.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using Neo4j.Driver.Internal.Messaging.V3;
using static Neo4j.Driver.Internal.Protocol.BoltProtocolV3MessageFormat;
namespace Neo4j.Driver.Internal.IO.MessageSerializers.V3
{
internal class RollbackMessageSerializer: WriteOnlySerializer
{
public override IEnumerable<Type> WritableTypes => new[] {typeof(RollbackMessage)};
public override void Serialize(IPackStreamWriter writer, object value)
{
writer.WriteStructHeader(0, MsgRollback);
}
}
} | 35.852941 | 91 | 0.733388 | [
"Apache-2.0"
] | davidwandar/neo4j-dotnet-driver | Neo4j.Driver/Neo4j.Driver/Internal/IO/MessageSerializers/V3/RollbackMessageSerializer.cs | 1,219 | C# |
using System;
using McMaster.Extensions.CommandLineUtils;
using Microsoft.Azure.Management.ApiManagement.ArmTemplates.Common;
namespace Microsoft.Azure.Management.ApiManagement.ArmTemplates.Extract
{
public class ExtractCommand : CommandLineApplication
{
public ExtractCommand()
{
this.Name = GlobalConstants.ExtractName;
this.Description = GlobalConstants.ExtractDescription;
var filePath = this.Option("--extractorConfig <extractorConfig>", "Config file of the extractor", CommandOptionType.SingleValue);
this.HelpOption();
this.OnExecute(async () =>
{
// convert config file to extractorConfig class
FileReader fileReader = new FileReader();
string extractorConfigPath = filePath.HasValue() ? filePath.Value().ToString() : null;
ExtractorConfig extractorConfig = fileReader.ConvertConfigJsonToExtractorConfig(extractorConfigPath);
try
{
//validation check
ExtractorUtils.validationCheck(extractorConfig);
string singleApiName = extractorConfig.apiName;
bool splitAPIs = extractorConfig.splitAPIs != null && extractorConfig.splitAPIs.Equals("true");
bool hasVersionSetName = extractorConfig.apiVersionSetName != null;
bool hasSingleApi = singleApiName != null;
bool includeRevisions = extractorConfig.includeAllRevisions != null && extractorConfig.includeAllRevisions.Equals("true");
bool hasMultipleAPIs = extractorConfig.mutipleAPIs != null;
// start running extractor
Console.WriteLine("API Management Template");
Console.WriteLine("Connecting to {0} API Management Service on {1} Resource Group ...", extractorConfig.sourceApimName, extractorConfig.resourceGroup);
// initialize file helper classes
FileWriter fileWriter = new FileWriter();
FileNameGenerator fileNameGenerator = new FileNameGenerator();
FileNames fileNames = fileNameGenerator.GenerateFileNames(extractorConfig.sourceApimName);
if (splitAPIs)
{
// create split api templates for all apis in the sourceApim
await ExtractorUtils.GenerateSplitAPITemplates(extractorConfig, fileNameGenerator, fileWriter, fileNames);
}
else if (hasVersionSetName)
{
// create split api templates and aggregated api templates for this apiversionset
await ExtractorUtils.GenerateAPIVersionSetTemplates(extractorConfig, fileNameGenerator, fileNames, fileWriter);
}
else if (hasMultipleAPIs)
{
// generate templates for multiple APIs
await ExtractorUtils.GenerateMultipleAPIsTemplates(extractorConfig, fileNameGenerator, fileWriter, fileNames);
}
else if (hasSingleApi && includeRevisions)
{
// handle singel API include Revision extraction
await ExtractorUtils.GenerateSingleAPIWithRevisionsTemplates(extractorConfig, singleApiName, fileNameGenerator, fileWriter, fileNames);
}
else
{
// create single api template or create aggregated api templates for all apis within the sourceApim
if (hasSingleApi)
{
Console.WriteLine("Executing extraction for {0} API ...", singleApiName);
}
else
{
Console.WriteLine("Executing full extraction ...");
}
await ExtractorUtils.GenerateTemplates(new Extractor(extractorConfig), singleApiName, null, fileNameGenerator, fileNames, fileWriter, null);
}
// Console.Writeline - these need to output to std out ?
Console.WriteLine("Templates written to output location");
Console.WriteLine("Press any key to exit process:");
#if DEBUG
Console.ReadKey();
#endif
}
catch (Exception ex)
{
Console.WriteLine("Error occured: " + ex.Message);
throw;
}
});
}
}
}
| 50.473684 | 171 | 0.564755 | [
"MIT"
] | aflinchb/azure-api-management-devops-resource-kit | src/APIM_ARMTemplate/apimtemplate/Commands/Extract.cs | 4,795 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace Orchard.Environment.Extensions
{
public class CompositeExtensionProvider : IExtensionProvider
{
private readonly IExtensionProvider[] _extensionProviders;
public CompositeExtensionProvider(params IExtensionProvider[] extensionProviders)
{
_extensionProviders = extensionProviders ?? new IExtensionProvider[0];
}
public CompositeExtensionProvider(IEnumerable<IExtensionProvider> extensionProviders)
{
if (extensionProviders == null)
{
throw new ArgumentNullException(nameof(extensionProviders));
}
_extensionProviders = extensionProviders.ToArray();
}
public int Order { get { throw new NotSupportedException(); } }
public IExtensionInfo GetExtensionInfo(IManifestInfo manifestInfo, string subPath)
{
foreach (var provider in _extensionProviders.OrderBy(ep => ep.Order))
{
var extensionInfo = provider.GetExtensionInfo(manifestInfo, subPath);
if (extensionInfo != null)
{
return extensionInfo;
}
}
return new NotFoundExtensionInfo(subPath);
}
}
}
| 33.4 | 93 | 0.629491 | [
"BSD-3-Clause"
] | ChipSoftTech/CST-CMS | src/OrchardCore/Orchard.Environment.Extensions.Abstractions/CompositeExtensionProvider.cs | 1,338 | C# |
using System;
using System.IO;
using System.Threading.Tasks;
namespace MixologyJournalApp.Platform
{
public interface IBackend
{
Task<QueryResult> PostResult(String path, Object body);
Task<QueryResult> DeleteResult(String path, Object body);
Task<String> GetResult(String path);
Task<QueryResult> SendFile(Byte[] fileContents, String remotePath);
}
}
| 22.277778 | 75 | 0.705736 | [
"Apache-2.0"
] | davidov541/MixologyJournal | MixologyJournalApp/MixologyJournalApp/Platform/IBackend.cs | 403 | C# |
using System;
using System.Collections.Generic;
namespace Anagram
{
public class AnagramSelector
{
public bool WordPairIsAnagram(string word1, string word2) {
if (word1.Length != word1.Length)
return false;
var s1Array = word1.ToLower().ToCharArray();
var s2Array = word2.ToLower().ToCharArray();
Array.Sort(s1Array);
Array.Sort(s2Array);
word1 = new string(s1Array);
word2 = new string(s2Array);
return word1 == word2;
}
public List<string> SelectAnagrams(string word, List<string> candidates) {
//Insert the correct implementation here
for(int i=0;i <candidates.Count;i++)
{
if (!WordPairIsAnagram(word, candidates[i])) {
candidates.RemoveAt(i);
i--;
}
}
return candidates;
}
}
}
| 28.057143 | 82 | 0.520367 | [
"MIT"
] | Engin-Boot/anagram-selector-cs-debnathtanmoy | Anagram/Anagram.cs | 984 | C# |
using CSharpWars.Enums;
using CSharpWars.ScriptProcessor.Middleware;
using CSharpWars.Tests.Framework.FluentAssertions;
using FluentAssertions;
using Xunit;
namespace CSharpWars.Tests.Scripting.Middleware
{
public class MoveComparerTests
{
[Theory]
[InlineData(PossibleMoves.Idling)]
[InlineData(PossibleMoves.TurningLeft)]
[InlineData(PossibleMoves.TurningRight)]
[InlineData(PossibleMoves.TurningAround)]
[InlineData(PossibleMoves.WalkForward)]
[InlineData(PossibleMoves.Teleport)]
[InlineData(PossibleMoves.MeleeAttack)]
[InlineData(PossibleMoves.RangedAttack)]
[InlineData(PossibleMoves.SelfDestruct)]
[InlineData(PossibleMoves.Died)]
[InlineData(PossibleMoves.ScriptError)]
public void MoveComparer_Compare_Identical_PossibleMoves_Should_Return_Zero(PossibleMoves move)
{
// Arrange
var moveComparer = new MoveComparer();
// Act
var result = moveComparer.Compare(move, move);
// Assert
result.Should().BeZero();
}
[Theory]
[InlineData(PossibleMoves.TurningLeft, PossibleMoves.WalkForward)]
[InlineData(PossibleMoves.TurningRight, PossibleMoves.WalkForward)]
[InlineData(PossibleMoves.TurningAround, PossibleMoves.WalkForward)]
public void MoveComparer_Compare_Turning_To_Walking_Should_Return_Negative(PossibleMoves turning, PossibleMoves walking)
{
// Arrange
var moveComparer = new MoveComparer();
// Act
var result = moveComparer.Compare(turning, walking);
// Assert
result.Should().BePositive();
}
[Theory]
[InlineData(PossibleMoves.WalkForward, PossibleMoves.Teleport)]
public void MoveComparer_Compare_Walking_To_Teleporting_Should_Return_Negative(PossibleMoves walking, PossibleMoves teleporting)
{
// Arrange
var moveComparer = new MoveComparer();
// Act
var result = moveComparer.Compare(walking, teleporting);
// Assert
result.Should().BePositive();
}
[Theory]
[InlineData(PossibleMoves.Teleport, PossibleMoves.SelfDestruct)]
public void MoveComparer_Compare_Teleporting_To_SelfDestructing_Should_Return_Negative(PossibleMoves teleporting, PossibleMoves selfDestructing)
{
// Arrange
var moveComparer = new MoveComparer();
// Act
var result = moveComparer.Compare(teleporting, selfDestructing);
// Assert
result.Should().BePositive();
}
[Theory]
[InlineData(PossibleMoves.SelfDestruct, PossibleMoves.MeleeAttack)]
public void MoveComparer_Compare_SelfDestructing_To_MeleeAttacking_Should_Return_Negative(PossibleMoves selfDestructing, PossibleMoves meleeAttacking)
{
// Arrange
var moveComparer = new MoveComparer();
// Act
var result = moveComparer.Compare(selfDestructing, meleeAttacking);
// Assert
result.Should().BePositive();
}
[Theory]
[InlineData(PossibleMoves.MeleeAttack, PossibleMoves.RangedAttack)]
public void MoveComparer_Compare_MeleeAttack_To_RangedAttack_Should_Return_Negative(PossibleMoves meleeAttack, PossibleMoves rangedAttack)
{
// Arrange
var moveComparer = new MoveComparer();
// Act
var result = moveComparer.Compare(meleeAttack, rangedAttack);
// Assert
result.Should().BePositive();
}
}
} | 34.859813 | 158 | 0.652279 | [
"MIT"
] | Djohnnie/CSharpWars-ProgNET-London-2019 | src/backend/CSharpWars/CSharpWars.Tests/Scripting/Middleware/MoveComparerTests.cs | 3,732 | C# |
namespace AutoLot.Dal.Exceptions;
public class CustomDbUpdateException : CustomException
{
public CustomDbUpdateException()
{
}
public CustomDbUpdateException(string message) : base(message)
{
}
public CustomDbUpdateException(string message, DbUpdateException innerException)
: base(message, innerException)
{
}
}
| 20.111111 | 84 | 0.712707 | [
"BSD-3-Clause",
"MIT"
] | MalikWaseemJaved/presentations | .NETCore/ASP.NETCore/v6.0/AutoLot/AutoLot.Dal/Exceptions/CustomDbUpdateException.cs | 364 | C# |
using System.ComponentModel;
using Microsoft.Extensions.Logging.Abstractions;
using Promitor.Core.Scraping.Configuration.Serialization.v1.Core;
using Xunit;
namespace Promitor.Scraper.Tests.Unit.Serialization.v1.Core
{
[Category("Unit")]
public class ScrapingDeserializerTests
{
private readonly ScrapingDeserializer _deserializer;
public ScrapingDeserializerTests()
{
_deserializer = new ScrapingDeserializer(NullLogger<ScrapingDeserializer>.Instance);
}
[Fact]
public void Deserialize_ScheduleSupplied_SetsSchedule()
{
const string yamlText =
@"scraping:
schedule: '0 * * ? * *'";
YamlAssert.PropertySet(
_deserializer,
yamlText,
"scraping",
"0 * * ? * *",
s => s.Schedule);
}
[Fact]
public void Deserialize_ScheduleNotSupplied_SetsScheduleNull()
{
const string yamlText =
@"scraping:
otherProperty: otherValue";
YamlAssert.PropertyNull(
_deserializer,
yamlText,
"scraping",
s => s.Schedule);
}
}
}
| 25.666667 | 96 | 0.578734 | [
"MIT"
] | burningalchemist/promitor | src/Promitor.Scraper.Tests.Unit/Serialization/v1/Core/ScrapingDeserializerTests.cs | 1,234 | C# |
/********************************************************************
The Multiverse Platform is made available under the MIT License.
Copyright (c) 2012 The Multiverse Foundation
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.
*********************************************************************/
#region Using directives
using System;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using Axiom.Core;
using Axiom.MathLib;
using Axiom.Collections;
using Axiom.Animating;
using Axiom.Input;
using Axiom.Graphics;
using Multiverse.CollisionLib;
#endregion
namespace Multiverse.Base
{
public class PrimeMover
{
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(PrimeMover));
public static void InitPrimeMover(WorldManager worldMgr, CollisionAPI collisionMgr)
{
worldManager = worldMgr;
collisionManager = collisionMgr;
playerStuck = false;
}
private static CollisionAPI collisionManager;
private static WorldManager worldManager;
private static bool playerStuck;
private static DateTime stuckGotoTime;
private static void TraceMOBottom(MovingObject mo, string description)
{
if (MO.DoLog) {
CollisionShape obstacle = mo.parts[0].shape;
CollisionCapsule moCapsule = null;
if (obstacle is CollisionCapsule)
moCapsule = (CollisionCapsule)obstacle;
string rest = (moCapsule != null ?
string.Format("mo bottom is {0}",
moCapsule.bottomcenter - new Vector3(0f, moCapsule.capRadius, 0f)) :
string.Format("obstacle {0}", obstacle));
MO.Log("{0}, {1}", description, rest);
}
}
private static void TraceObstacle(CollisionShape obstacle)
{
if (obstacle is CollisionOBB) {
CollisionOBB box = (CollisionOBB)obstacle;
MO.Log(" obstacle top {0} center {1} {2}",
box.center.y + box.extents[1], box.center, box);
}
else
MO.Log(" obstacle center {0} {1}", obstacle.center, obstacle);
}
private static bool NowColliding(MovingObject mo, string description)
{
CollisionParms parms = new CollisionParms();
bool colliding = collisionManager.CollideAfterAddingDisplacement(mo, Vector3.Zero, parms);
CollisionShape obstacle = mo.parts[0].shape;
CollisionCapsule moCapsule = null;
if (obstacle is CollisionCapsule)
moCapsule = (CollisionCapsule)obstacle;
string rest = (moCapsule != null ?
string.Format("mo bottom is {0}",
moCapsule.bottomcenter - new Vector3(0f, moCapsule.capRadius, 0f)) :
string.Format("obstacle {0}", obstacle));
if (MO.DoLog)
MO.Log("{0}, now colliding = {1}; {2}", description, colliding, rest);
log.DebugFormat("{0}, now colliding = {1}; {2}", description, colliding, rest);
return colliding;
}
// Move the desired displacement, limited by hitting an
// obstacle. Then, if we're not already at the terrain level,
// "fall" until we are either at the terrain level, or hit an
// obstacle
public static Vector3 MoveMobNode(MobNode mobNode, Vector3 requestedDisplacement, Client client)
{
// Logger.Log(0, "MoveMobNode oid {0} requestedDisplacement {1}", mobNode.Oid, requestedDisplacement);
// log.DebugFormat("MoveMobNode: mobNode oid {0}, name {1}, followTerrain {2}, position {3}, disp {4}",
// mobNode.Oid, mobNode.Name, mobNode.FollowTerrain, mobNode.Position, requestedDisplacement);
Vector3 start = mobNode.Position;
MovingObject mo = mobNode.Collider;
bool collided = false;
// Zero the y coordinate of displacement, because it seems
// that it can be arbitrarily large
Vector3 desiredDisplacement = requestedDisplacement;
if (mobNode.FollowTerrain)
desiredDisplacement.y = 0;
if (desiredDisplacement.LengthSquared <= float.Epsilon)
return start;
if (MO.DoLog)
MO.Log("MoveMobNode called with mobNode {0} at {1}, disp of {2}",
mobNode.Oid, start, requestedDisplacement);
if (collisionManager == null) {
log.Info("MoveMobNode: returning because collisionManager isn't initialized");
return start + desiredDisplacement;
}
if (mo == null || mo.parts.Count == 0) {
if (MO.DoLog)
MO.Log("MoveMobNode returning because no collision volume for node");
return start + requestedDisplacement;
}
if (mobNode is Player && NowColliding(mo, "Testing player collision on entry")) {
if (client.MillisecondsStuckBeforeGotoStuck != 0) {
if (!playerStuck) {
stuckGotoTime = DateTime.Now.AddMilliseconds(client.MillisecondsStuckBeforeGotoStuck);
playerStuck = true;
}
else if (DateTime.Now >= stuckGotoTime) {
// We issue the goto command to move us out of the
// collision volume
client.Write("Executing /stuck command because player has been in a collision volume for " + client.MillisecondsStuckBeforeGotoStuck + " milliseconds");
client.NetworkHelper.SendTargettedCommand(client.Player.Oid, "/stuck");
playerStuck = false;
return start;
}
}
}
else
playerStuck = false;
// If we haven't completed setup to this extent, just give up
CollisionParms parms = new CollisionParms();
Vector3 pos = FindMobNodeDisplacement(mobNode, parms, desiredDisplacement, out collided);
// log.DebugFormat("MoveMobNode: mobNode oid {0}, name {1}, mob node position {2}, displacement {3}",
// mobNode.Oid, mobNode.Name, pos, requestedDisplacement);
float h = worldManager.GetHeightAt(pos);
// If we're already below ground level, just set our
// level to ground level. This will have to be modified
// if we deal with caves
if (pos.y - h < 0) {
// log.DebugFormat("MoveMobNode: mobNode oid {0}, name {1} below terrain level", mobNode.Oid, mobNode.Name);
mo.AddDisplacement(new Vector3(0f, h - pos.y, 0f));
pos.y = h;
if (MO.DoLog && (pos.y - h) < -.001 * Client.OneMeter)
MO.Log(string.Format(" MobNode at {0} is below ground height {1}!",
pos, h));
} // else {
if (mobNode.FollowTerrain) {
// NowColliding(mo, " Before falling loop");
// Fall toward the terrain or an obstacle, whichever comes
// first
float step = mo.StepSize(new Vector3(0, h, 0));
while (true) {
if (Math.Abs(pos.y - h) < CollisionAPI.VerticalTerrainThreshold * Client.OneMeter) {
mo.AddDisplacement(new Vector3(0f, h - pos.y, 0f));
pos.y = h;
break;
} else {
float dy = -Math.Min(pos.y - h, step);
Vector3 displacement = new Vector3(0, dy, 0);
Vector3 cd = displacement;
if (MO.DoLog) {
MO.Log(" Testing for collision falling {0}", dy);
TraceMOBottom(mo, " Before falling");
}
if (collisionManager.TestCollision(mo, ref displacement, parms)) {
if (MO.DoLog) {
TraceMOBottom(mo, " After TestCollision after falling");
NowColliding(mo, " After TestCollision after falling");
MO.Log(" Collision when object {0} falls from {1} to {2}",
parms.part.handle, pos, pos + cd);
TraceObstacle(parms.obstacle);
MO.Log(" Adding dy {0} - displacement.y {1} to pos {2}",
dy, displacement.y, pos);
}
pos.y += dy - displacement.y;
break;
}
if (MO.DoLog)
MO.Log(" Didn't collide falling; dy {0}, pos {1}",
dy, pos);
pos.y += dy;
}
}
} else {
if (MO.DoLog)
MO.Log(" Not falling because mobNode {0} doesn't have FollowTerrain",
mobNode.Oid);
}
// }
if (MO.DoLog) {
NowColliding(mo, " Leaving MoveMobNode");
MO.Log("MoveMobNode returning pos {0}", pos);
MO.Log("");
}
if (collided)
log.DebugFormat("MoveMobNode collided: mobNode oid {0}, name {1}, orig pos {2}, displacement {3}, new pos {4}",
mobNode.Oid, mobNode.Name, start, requestedDisplacement, pos);
else
log.DebugFormat("MoveMobNode didn't collide: mobNode oid {0}, name {1}, orig pos {2}, displacement {3}, new pos {4}",
mobNode.Oid, mobNode.Name, start, requestedDisplacement, pos);
return pos;
}
// We only call this if both the collisionManager and the collider exist
private static Vector3 FindMobNodeDisplacement(MobNode mobNode, CollisionParms parms, Vector3 desiredDisplacement, out bool collided)
{
Vector3 start = mobNode.Position;
Vector3 pos = start + desiredDisplacement;
Vector3 displacement = desiredDisplacement;
MovingObject mo = mobNode.Collider;
Vector3 moStart = mo.parts[0].shape.center;
if (MO.DoLog) {
MO.Log(" moStart = {0}, start = {1}", moStart, start);
MO.Log(" pos = {0}, displacement = {1}", pos, displacement);
TraceMOBottom(mo, " On entry to FindMobNodeDisplacement");
}
collided = false;
if (collisionManager.TestCollision(mo, ref displacement, parms)) {
collided = true;
if (MO.DoLog) {
MO.Log(" Collision when moving object {0} from {1} to {2}",
parms.part.handle, start, pos);
NowColliding(mo, " After first TestCollision in FindMobNodeDisplacement");
TraceObstacle(parms.obstacle);
MO.Log(" Before collision moved {0}", desiredDisplacement - displacement);
}
// Decide if the normals are such that we want
// to slide along the obstacle
Vector3 remainingDisplacement = displacement;
Vector3 norm1 = parms.normObstacle.ToNormalized();
if (DecideToSlide(mo, start + displacement, parms, ref remainingDisplacement)) {
if (MO.DoLog)
MO.Log(" After DecideToSlide, remainingDisplacement {0}", remainingDisplacement);
// We have to test the displacement
if (collisionManager.TestCollision(mo, ref remainingDisplacement, parms)) {
if (MO.DoLog) {
NowColliding(mo, " After first try TestCollision");
MO.Log(" Slid into obstacle on the first try; remainingDisplacement = {0}",
remainingDisplacement);
TraceObstacle(parms.obstacle);
}
if (remainingDisplacement.LengthSquared > 0) {
Vector3 norm2 = parms.normObstacle.ToNormalized();
// Find the cross product of the of norm1 and
// norm2, and dot with displacement. If
// negative, reverse.
Vector3 newDir = norm1.Cross(norm2);
float len = newDir.Dot(remainingDisplacement);
if (len < 0) {
newDir = - newDir;
len = - len;
}
Vector3 slidingDisplacement = len * newDir;
Vector3 originalSlidingDisplacement = slidingDisplacement;
if (MO.DoLog) {
MO.Log(" norm1 = {0}, norm2 = {1}, len = {2}",
norm1, norm2, len);
MO.Log(" Cross product slidingDisplacement is {0}", slidingDisplacement);
}
if (collisionManager.TestCollision(mo, ref slidingDisplacement, parms)) {
if (MO.DoLog) {
NowColliding(mo, " After second try TestCollision");
MO.Log(" Slid into obstacle on the second try; slidingDisplacement = {0}",
slidingDisplacement);
}
}
else
if (MO.DoLog)
MO.Log(" Didn't slide into obstacle on the second try");
remainingDisplacement -= (originalSlidingDisplacement - slidingDisplacement);
}
}
}
else
remainingDisplacement = displacement;
if (MO.DoLog)
MO.Log(" Before checking hop, remainingDisplacement is {0}", remainingDisplacement);
if (remainingDisplacement.Length > 30f) {
// Try to hop over the obstacle
Vector3 c = remainingDisplacement;
mo.AddDisplacement(new Vector3(0f, CollisionAPI.HopOverThreshold * Client.OneMeter, 0f));
if (MO.DoLog) {
TraceMOBottom(mo, " Before trying to hop");
MO.Log(" remainingDisplacement {0}", remainingDisplacement);
}
if (collisionManager.TestCollision(mo, ref remainingDisplacement, parms)) {
if (MO.DoLog) {
MO.Log(" Even after hopping up {0} meters, can't get over obstacle; disp {1}",
CollisionAPI.HopOverThreshold, remainingDisplacement);
}
c = c - remainingDisplacement;
c.y = 0;
c += new Vector3(0f, CollisionAPI.HopOverThreshold * Client.OneMeter, 0f);
if (MO.DoLog)
MO.Log(" After failed hop, subtracting {0}", c);
mo.AddDisplacement(- c);
}
else if (MO.DoLog) {
MO.Log(" Hopping up {0} meters got us over obstacle; disp {1}",
CollisionAPI.HopOverThreshold, remainingDisplacement);
TraceMOBottom(mo, " After hopping");
}
NowColliding(mo, " After hopping");
}
}
Vector3 moPos = mo.parts[0].shape.center;
pos = start + moPos - moStart;
if (MO.DoLog) {
MO.Log(" mo location = {0}, moPos - moStart {1}", moPos, moPos - moStart);
NowColliding(mo, " Leaving FindMobNodeDisplacement");
MO.Log(" pos = {0}", pos);
}
return pos;
}
// Normalize the angle so that it's contained in +/- 180 degrees
private static float NormalizeAngle(float angle)
{
float floatPI = (float)Math.PI;
if (angle > floatPI)
return angle - 2.0f * floatPI;
else if (angle < - floatPI)
return angle + 2.0f * floatPI;
else
return angle;
}
// Decide, based on the normal to the collision object, if the
// moving object can slide across the obstacle, and if it can,
// return the updated displacement. This displacement may in fact
// run into _another_ obstacle, however, so the call must again
// run the collision test.
private static bool DecideToSlide(MovingObject mo, Vector3 mobNodePosition,
CollisionParms parms, ref Vector3 displacement)
{
Vector3 normDisplacement = displacement.ToNormalized();
Vector3 normObstacle = parms.normObstacle.ToNormalized();
if (MO.DoLog) {
MO.Log(" DecideToSlide: normObstacle {0}, normDisplacement {1}",
normObstacle.ToString(), normDisplacement.ToString());
MO.Log(" DecideToSlide: displacement {0}", displacement);
}
// First we find the angle between the normal and the
// direction of travel, and reject the displacement if
// it's too small
float slideAngle = (NormalizeAngle((float)Math.Acos((double)normDisplacement.Dot(normObstacle))) -
.5f * (float)Math.PI);
if (Math.Abs(slideAngle) > CollisionAPI.MinSlideAngle) {
if (MO.DoLog)
MO.Log(" After collision, displacement {0}, won't slide because slideAngle {1} > minSlideAngle {2}",
displacement.ToString(), slideAngle, CollisionAPI.MinSlideAngle);
displacement = Vector3.Zero;
return false;
}
// Then we find the angle with the y axis, and reject the
// displacement if it's too steep
float verticalAngle = NormalizeAngle((float)Math.Acos((double)normDisplacement[1]));
if (Math.Abs(verticalAngle) > CollisionAPI.MaxVerticalAngle) {
if (MO.DoLog)
MO.Log(" After collision, displacement {0}, won't slide because verticalAngle {1} <= maxVerticalAngle {2}",
displacement.ToString(), verticalAngle, CollisionAPI.MaxVerticalAngle);
displacement = Vector3.Zero;
return false;
}
// Else, we can slide, so return a displacement that
// points in the direction we're sliding, and has length
// equal to a constant times the displacement length
// Rotate displacement so that it's 90 degress from the
// obstacle normal
Vector3 cross = normObstacle.Cross(normDisplacement);
Quaternion q = Quaternion.FromAngleAxis(.5f * (float)Math.PI, cross);
Matrix4 transform = q.ToRotationMatrix();
Vector3 transformedNorm = transform * normObstacle.ToNormalized();
float len = displacement.Length;
displacement = transformedNorm * len;
// Vector3 alignedPart = normObstacle * (normObstacle.Dot(displacement));
// displacement -= alignedPart;
Vector3 p = mobNodePosition + displacement;
float h = worldManager.GetHeightAt(p);
// If sliding would put us below ground, limit the displacement
if (h > p.y) {
if (MO.DoLog)
MO.Log(" Sliding up because terrain height is {0} is higher than projected mobNode height {1}",
h, p.y);
displacement.y += h - p.y;
}
if (MO.DoLog) {
MO.Log(" Exiting DecideToSlide, sliding displacement {0}, slideAngle {1}, verticalAngle {2}",
displacement.ToString(), slideAngle, verticalAngle);
MO.Log(" Exiting DecideToSlide, cross product {0}, quaternion {1}, transformedNorm {2}",
cross, q, transformedNorm);
// MO.Log(" Exiting DecideToSlide, alignedPart {0}", alignedPart);
}
return true;
}
}
}
| 42.376443 | 176 | 0.634312 | [
"MIT"
] | AustralianDisabilityLimited/MultiversePlatform | client/Base/PrimeMover.cs | 18,349 | C# |
using System;
using System.Collections.Generic;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json.Linq;
using OrchardCore.ContentManagement;
using OrchardCore.Scripting;
namespace OrchardCore.Contents.Scripting
{
public class ContentMethodsProvider : IGlobalMethodProvider
{
private readonly GlobalMethod _newContentItemMethod;
private readonly GlobalMethod _createContentItemMethod;
private readonly GlobalMethod _updateContentItemMethod;
public ContentMethodsProvider()
{
_newContentItemMethod = new GlobalMethod
{
Name = "newContentItem",
Method = serviceProvider => (Func<string, IContent>)((contentType) =>
{
var contentManager = serviceProvider.GetRequiredService<IContentManager>();
var contentItem = contentManager.NewAsync(contentType).GetAwaiter().GetResult();
return contentItem;
})
};
_createContentItemMethod = new GlobalMethod
{
Name = "createContentItem",
Method = serviceProvider => (Func<string, bool?, object, IContent>)((contentType, publish, properties) =>
{
var contentManager = serviceProvider.GetRequiredService<IContentManager>();
var contentItem = contentManager.NewAsync(contentType).GetAwaiter().GetResult();
var props = JObject.FromObject(properties);
var content = (JObject)contentItem.ContentItem.Content;
content.Merge(props);
contentManager.CreateAsync(contentItem.ContentItem, publish == true ? VersionOptions.Published : VersionOptions.Draft).GetAwaiter().GetResult();
return contentItem;
})
};
_updateContentItemMethod = new GlobalMethod
{
Name = "updateContentItem",
Method = serviceProvider => (Action<IContent, object>)((contentItem, properties) =>
{
var props = JObject.FromObject(properties);
var content = (JObject)contentItem.ContentItem.Content;
content.Merge(props, new JsonMergeSettings { MergeArrayHandling = MergeArrayHandling.Replace });
})
};
}
public IEnumerable<GlobalMethod> GetMethods()
{
return new[] { _newContentItemMethod, _createContentItemMethod, _updateContentItemMethod };
}
}
}
| 39.772727 | 164 | 0.604571 | [
"BSD-3-Clause"
] | 1426463237/OrchardCore | src/OrchardCore.Modules/OrchardCore.Contents/Scripting/ContentMethodsProvider.cs | 2,625 | C# |
using SIS.HTTP.Sessions;
using SIS.MvcFramework.Sessions;
using System.Collections.Concurrent;
namespace SIS.MvcFramework.Sessions
{
public class HttpSessionStorage : IHttpSessionStorage
{
public const string SessionCookieKey = "SIS_ID";
private readonly ConcurrentDictionary<string, IHttpSession> httpSessions;
public HttpSessionStorage()
{
this.httpSessions = new ConcurrentDictionary<string, IHttpSession>();
}
public IHttpSession GetSession(string id)
{
return httpSessions.GetOrAdd(id, _ => new HttpSession(id));
}
public bool ContainsSession(string id)
{
return httpSessions.ContainsKey(id);
}
}
}
| 25.724138 | 81 | 0.656836 | [
"MIT"
] | SimeonVSimeonov/custom-mvc-framework | SIS.MvcFramework/Sessions/HttpSessionStorage.cs | 748 | C# |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using AutoMapper;
using CustomerManager.Application.Exceptions;
using CustomerManager.Application.Extensions;
using CustomerManager.Application.Interfaces.Services;
using CustomerManager.Application.Interfaces.Services.Identity;
using CustomerManager.Application.Requests.Identity;
using CustomerManager.Application.Requests.Mail;
using CustomerManager.Application.Responses.Identity;
using CustomerManager.Infrastructure.Models.Identity;
using CustomerManager.Infrastructure.Specifications;
using CustomerManager.Shared.Constants.Role;
using CustomerManager.Shared.Wrapper;
using Hangfire;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization;
namespace CustomerManager.Infrastructure.Services.Identity
{
public class UserService : IUserService
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly RoleManager<ApplicationRole> _roleManager;
private readonly IMailService _mailService;
private readonly IStringLocalizer<UserService> _localizer;
private readonly IExcelService _excelService;
private readonly ICurrentUserService _currentUserService;
private readonly IMapper _mapper;
public UserService(
UserManager<ApplicationUser> userManager,
IMapper mapper,
RoleManager<ApplicationRole> roleManager,
IMailService mailService,
IStringLocalizer<UserService> localizer,
IExcelService excelService,
ICurrentUserService currentUserService)
{
_userManager = userManager;
_mapper = mapper;
_roleManager = roleManager;
_mailService = mailService;
_localizer = localizer;
_excelService = excelService;
_currentUserService = currentUserService;
}
public async Task<Result<List<UserResponse>>> GetAllAsync()
{
var users = await _userManager.Users.ToListAsync();
var result = _mapper.Map<List<UserResponse>>(users);
return await Result<List<UserResponse>>.SuccessAsync(result);
}
public async Task<IResult> RegisterAsync(RegisterRequest request, string origin)
{
var userWithSameUserName = await _userManager.FindByNameAsync(request.UserName);
if (userWithSameUserName != null)
{
return await Result.FailAsync(string.Format(_localizer["Username {0} is already taken."], request.UserName));
}
var user = new ApplicationUser
{
Email = request.Email,
FirstName = request.FirstName,
LastName = request.LastName,
UserName = request.UserName,
PhoneNumber = request.PhoneNumber,
IsActive = request.ActivateUser,
EmailConfirmed = request.AutoConfirmEmail
};
if (!string.IsNullOrWhiteSpace(request.PhoneNumber))
{
var userWithSamePhoneNumber = await _userManager.Users.FirstOrDefaultAsync(x => x.PhoneNumber == request.PhoneNumber);
if (userWithSamePhoneNumber != null)
{
return await Result.FailAsync(string.Format(_localizer["Phone number {0} is already registered."], request.PhoneNumber));
}
}
var userWithSameEmail = await _userManager.FindByEmailAsync(request.Email);
if (userWithSameEmail == null)
{
var result = await _userManager.CreateAsync(user, request.Password);
if (result.Succeeded)
{
await _userManager.AddToRoleAsync(user, RoleConstants.CustomerRole);
if (!request.AutoConfirmEmail)
{
var verificationUri = await SendVerificationEmail(user, origin);
var mailRequest = new MailRequest
{
From = "mail@codewithmukesh.com",
To = user.Email,
Body = string.Format(_localizer["Please confirm your account by <a href='{0}'>clicking here</a>."], verificationUri),
Subject = _localizer["Confirm Registration"]
};
BackgroundJob.Enqueue(() => _mailService.SendAsync(mailRequest));
return await Result<string>.SuccessAsync(user.Id, string.Format(_localizer["User {0} Registered. Please check your Mailbox to verify!"], user.UserName));
}
return await Result<string>.SuccessAsync(user.Id, string.Format(_localizer["User {0} Registered."], user.UserName));
}
else
{
return await Result.FailAsync(result.Errors.Select(a => _localizer[a.Description].ToString()).ToList());
}
}
else
{
return await Result.FailAsync(string.Format(_localizer["Email {0} is already registered."], request.Email));
}
}
private async Task<string> SendVerificationEmail(ApplicationUser user, string origin)
{
var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
var route = "api/identity/user/confirm-email/";
var endpointUri = new Uri(string.Concat($"{origin}/", route));
var verificationUri = QueryHelpers.AddQueryString(endpointUri.ToString(), "userId", user.Id);
verificationUri = QueryHelpers.AddQueryString(verificationUri, "code", code);
return verificationUri;
}
public async Task<IResult<UserResponse>> GetAsync(string userId)
{
var user = await _userManager.Users.Where(u => u.Id == userId).FirstOrDefaultAsync();
var result = _mapper.Map<UserResponse>(user);
return await Result<UserResponse>.SuccessAsync(result);
}
public async Task<IResult> ToggleUserStatusAsync(ToggleUserStatusRequest request)
{
var user = await _userManager.Users.Where(u => u.Id == request.UserId).FirstOrDefaultAsync();
var isAdmin = await _userManager.IsInRoleAsync(user, RoleConstants.AdministratorRole);
if (isAdmin)
{
return await Result.FailAsync(_localizer["Administrators Profile's Status cannot be toggled"]);
}
if (user != null)
{
user.IsActive = request.ActivateUser;
var identityResult = await _userManager.UpdateAsync(user);
}
return await Result.SuccessAsync();
}
public async Task<IResult<UserRolesResponse>> GetRolesAsync(string userId)
{
var viewModel = new List<UserRoleModel>();
var user = await _userManager.FindByIdAsync(userId);
var roles = await _roleManager.Roles.ToListAsync();
foreach (var role in roles)
{
var userRolesViewModel = new UserRoleModel
{
RoleName = role.Name,
RoleDescription = role.Description
};
if (await _userManager.IsInRoleAsync(user, role.Name))
{
userRolesViewModel.Selected = true;
}
else
{
userRolesViewModel.Selected = false;
}
viewModel.Add(userRolesViewModel);
}
var result = new UserRolesResponse { UserRoles = viewModel };
return await Result<UserRolesResponse>.SuccessAsync(result);
}
public async Task<IResult> UpdateRolesAsync(UpdateUserRolesRequest request)
{
var user = await _userManager.FindByIdAsync(request.UserId);
if (user.Email == "mukesh@blazorhero.com")
{
return await Result.FailAsync(_localizer["Not Allowed."]);
}
var roles = await _userManager.GetRolesAsync(user);
var selectedRoles = request.UserRoles.Where(x => x.Selected).ToList();
var currentUser = await _userManager.FindByIdAsync(_currentUserService.UserId);
if (!await _userManager.IsInRoleAsync(currentUser, RoleConstants.AdministratorRole))
{
var tryToAddAdministratorRole = selectedRoles
.Any(x => x.RoleName == RoleConstants.AdministratorRole);
var userHasAdministratorRole = roles.Any(x => x == RoleConstants.AdministratorRole);
if (tryToAddAdministratorRole && !userHasAdministratorRole || !tryToAddAdministratorRole && userHasAdministratorRole)
{
return await Result.FailAsync(_localizer["Not Allowed to add or delete Administrator Role if you have not this role."]);
}
}
var result = await _userManager.RemoveFromRolesAsync(user, roles);
result = await _userManager.AddToRolesAsync(user, selectedRoles.Select(y => y.RoleName));
return await Result.SuccessAsync(_localizer["Roles Updated"]);
}
public async Task<IResult<string>> ConfirmEmailAsync(string userId, string code)
{
var user = await _userManager.FindByIdAsync(userId);
code = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(code));
var result = await _userManager.ConfirmEmailAsync(user, code);
if (result.Succeeded)
{
return await Result<string>.SuccessAsync(user.Id, string.Format(_localizer["Account Confirmed for {0}. You can now use the /api/identity/token endpoint to generate JWT."], user.Email));
}
else
{
throw new ApiException(string.Format(_localizer["An error occurred while confirming {0}"], user.Email));
}
}
public async Task<IResult> ForgotPasswordAsync(ForgotPasswordRequest request, string origin)
{
var user = await _userManager.FindByEmailAsync(request.Email);
if (user == null || !(await _userManager.IsEmailConfirmedAsync(user)))
{
// Don't reveal that the user does not exist or is not confirmed
return await Result.FailAsync(_localizer["An Error has occurred!"]);
}
// For more information on how to enable account confirmation and password reset please
// visit https://go.microsoft.com/fwlink/?LinkID=532713
var code = await _userManager.GeneratePasswordResetTokenAsync(user);
code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
var route = "account/reset-password";
var endpointUri = new Uri(string.Concat($"{origin}/", route));
var passwordResetURL = QueryHelpers.AddQueryString(endpointUri.ToString(), "Token", code);
var mailRequest = new MailRequest
{
Body = string.Format(_localizer["Please reset your password by <a href='{0}>clicking here</a>."], HtmlEncoder.Default.Encode(passwordResetURL)),
Subject = _localizer["Reset Password"],
To = request.Email
};
BackgroundJob.Enqueue(() => _mailService.SendAsync(mailRequest));
return await Result.SuccessAsync(_localizer["Password Reset Mail has been sent to your authorized Email."]);
}
public async Task<IResult> ResetPasswordAsync(ResetPasswordRequest request)
{
var user = await _userManager.FindByEmailAsync(request.Email);
if (user == null)
{
// Don't reveal that the user does not exist
return await Result.FailAsync(_localizer["An Error has occured!"]);
}
var result = await _userManager.ResetPasswordAsync(user, request.Token, request.Password);
if (result.Succeeded)
{
return await Result.SuccessAsync(_localizer["Password Reset Successful!"]);
}
else
{
return await Result.FailAsync(_localizer["An Error has occured!"]);
}
}
public async Task<int> GetCountAsync()
{
var count = await _userManager.Users.CountAsync();
return count;
}
public async Task<string> ExportToExcelAsync(string searchString = "")
{
var userSpec = new UserFilterSpecification(searchString);
var users = await _userManager.Users
.Specify(userSpec)
.OrderByDescending(a => a.CreatedOn)
.ToListAsync();
var result = await _excelService.ExportAsync(users, sheetName: _localizer["Users"],
mappers: new Dictionary<string, Func<ApplicationUser, object>>
{
{ _localizer["Id"], item => item.Id },
{ _localizer["FirstName"], item => item.FirstName },
{ _localizer["LastName"], item => item.LastName },
{ _localizer["UserName"], item => item.UserName },
{ _localizer["Email"], item => item.Email },
{ _localizer["EmailConfirmed"], item => item.EmailConfirmed },
{ _localizer["PhoneNumber"], item => item.PhoneNumber },
{ _localizer["PhoneNumberConfirmed"], item => item.PhoneNumberConfirmed },
{ _localizer["IsActive"], item => item.IsActive },
{ _localizer["CreatedOn (Local)"], item => DateTime.SpecifyKind(item.CreatedOn, DateTimeKind.Utc).ToLocalTime().ToString("G", CultureInfo.CurrentCulture) },
{ _localizer["CreatedOn (UTC)"], item => item.CreatedOn.ToString("G", CultureInfo.CurrentCulture) },
{ _localizer["ProfilePictureDataUrl"], item => item.ProfilePictureDataUrl },
});
return result;
}
}
} | 47.718033 | 201 | 0.605538 | [
"MIT"
] | kennyas/CustomerManager | src/Infrastructure/Services/Identity/UserService.cs | 14,556 | C# |
using System;
namespace Yota.Tests
{
public class Class1
{
}
} | 9.5 | 23 | 0.605263 | [
"MIT"
] | denisburlacu/Yota | Yota.Tests/Class1.cs | 78 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the config-2014-11-12.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.ConfigService.Model
{
/// <summary>
/// Container for the parameters to the PutDeliveryChannel operation.
/// Creates a delivery channel object to deliver configuration information to an Amazon
/// S3 bucket and Amazon SNS topic.
///
///
/// <para>
/// Before you can create a delivery channel, you must create a configuration recorder.
/// </para>
///
/// <para>
/// You can use this action to change the Amazon S3 bucket or an Amazon SNS topic of the
/// existing delivery channel. To change the Amazon S3 bucket or an Amazon SNS topic,
/// call this action and specify the changed values for the S3 bucket and the SNS topic.
/// If you specify a different value for either the S3 bucket or the SNS topic, this action
/// will keep the existing value for the parameter that is not changed.
/// </para>
/// <note>
/// <para>
/// You can have only one delivery channel per AWS account.
/// </para>
/// </note>
/// </summary>
public partial class PutDeliveryChannelRequest : AmazonConfigServiceRequest
{
private DeliveryChannel _deliveryChannel;
/// <summary>
/// Gets and sets the property DeliveryChannel.
/// <para>
/// The configuration delivery channel object that delivers the configuration information
/// to an Amazon S3 bucket, and to an Amazon SNS topic.
/// </para>
/// </summary>
public DeliveryChannel DeliveryChannel
{
get { return this._deliveryChannel; }
set { this._deliveryChannel = value; }
}
// Check to see if DeliveryChannel property is set
internal bool IsSetDeliveryChannel()
{
return this._deliveryChannel != null;
}
}
} | 35.12987 | 104 | 0.664695 | [
"Apache-2.0"
] | SaschaHaertel/AmazonAWS | sdk/src/Services/ConfigService/Generated/Model/PutDeliveryChannelRequest.cs | 2,705 | C# |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
namespace WpfSmtpClient
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
}
}
| 18.166667 | 42 | 0.706422 | [
"Apache-2.0"
] | lnodaba/DoubleCount.UnoExample | WpfSmtpClient/App.xaml.cs | 329 | C# |
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using ING.GEP.CodingChallenge.Core.Clothing.Models;
using ING.GEP.CodingChallenge.Core.Enums;
namespace ING.GEP.CodingChallenge.Core.Clothing
{
public class ClothsService
{
public async Task<List<Cloth>> ImportFromCsv(Stream csv, bool skipFirstLine = true)
{
var cloths = new List<Cloth>();
using (var sr = new StreamReader(csv))
{
bool endOfFile;
bool firstLine = true;
do
{
var line = await sr.ReadLineAsync();
if (!firstLine || !skipFirstLine)
{
if (!string.IsNullOrWhiteSpace(line))
{
cloths.Add(ClothsFactory.FromCsvString(line));
}
}
endOfFile = string.IsNullOrWhiteSpace(line);
firstLine = false;
} while (!endOfFile);
}
return cloths;
}
public async Task ExportClothesToCsvFile(
string targetFilePath,
IEnumerable<Cloth> exportSubjects,
Currency desiredCurrency)
{
var fileInfo = new FileInfo(targetFilePath);
if (!fileInfo.Directory.Exists)
{
fileInfo.Directory.Create();
}
await using var outputFile = File.OpenWrite(targetFilePath);
await using var sw = new StreamWriter(outputFile);
await sw.WriteLineAsync("productId,name,description,price,category");
foreach (var exportObject in exportSubjects)
{
exportObject.Price.ConvertTo(desiredCurrency);
var csvString = exportObject.ToCsvString();
await sw.WriteLineAsync(csvString);
}
}
}
}
| 32.365079 | 92 | 0.511525 | [
"MIT"
] | nikneem/coding-challenge | Assignment01/ING.GEP.CodingChallenge.Core/Clothing/ClothsService.cs | 2,041 | C# |
using System;
using System.Windows.Input;
namespace ContosoMoments
{
public class DelegateCommand : ICommand
{
private readonly Func<object, bool> canExecuteHandler;
private readonly Action<object> executeHandler;
public event EventHandler CanExecuteChanged;
public DelegateCommand(Action<object> handler)
: this(handler, (o) => true)
{
}
public DelegateCommand(Action<object> handler, Func<object, bool> canExecuteHandler)
{
this.executeHandler = handler;
this.canExecuteHandler = canExecuteHandler;
}
public bool CanExecute(object parameter)
{
return this.canExecuteHandler(parameter);
}
public void Execute(object parameter)
{
this.executeHandler(parameter);
}
protected virtual void RaiseCanExecuteChanged()
{
var temp = CanExecuteChanged;
if (temp != null) {
temp(this, EventArgs.Empty);
}
}
}
}
| 24.5 | 92 | 0.589981 | [
"MIT"
] | AsimKhan2019/Contoso-Moments | src/Mobile/ContosoMoments/Helpers/DelegateCommand.cs | 1,080 | C# |
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace ProScan
{
public class CommLogForm : Form
{
private RichTextBox richTextBox;
public CommLogForm()
{
InitializeComponent();
}
public new void Update()
{
if (!File.Exists("commlog.txt"))
return;
FileStream fileStream = new FileStream("commlog.txt", FileMode.Open, FileAccess.Read);
richTextBox.LoadFile((Stream)fileStream, RichTextBoxStreamType.PlainText);
fileStream.Close();
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
}
private void InitializeComponent()
{
richTextBox = new System.Windows.Forms.RichTextBox();
SuspendLayout();
//
// richTextBox
//
richTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
richTextBox.Location = new System.Drawing.Point(0, 0);
richTextBox.Name = "richTextBox";
richTextBox.ReadOnly = true;
richTextBox.Size = new System.Drawing.Size(668, 482);
richTextBox.TabIndex = 0;
richTextBox.Text = "";
//
// CommLogForm
//
AutoScaleBaseSize = new System.Drawing.Size(5, 13);
ClientSize = new System.Drawing.Size(672, 486);
Controls.Add(richTextBox);
Name = "CommLogForm";
Text = "Communication Log";
ResumeLayout(false);
}
}
} | 25.9 | 146 | 0.698842 | [
"Unlicense"
] | beyerch/ProScan | ProScan/ProScan/CommLogForm.cs | 1,556 | C# |
using UnityEngine;
public class TexShowcaseToggle : MonoBehaviour {
GameObject[] objects;
int current = 0;
// Use this for initialization
void Start () {
objects = new GameObject[transform.childCount];
for (int i = 0; i < transform.childCount; i++)
{
objects[i] = transform.GetChild(i).gameObject;
}
}
// Update is called once per frame
void Update () {
if (Input.anyKeyDown)
{
objects[current].SetActive(false);
if (Input.GetKeyDown(KeyCode.LeftArrow))
current = (current == 0 ? objects.Length : current) - 1;
else if (Input.GetKeyDown(KeyCode.RightArrow) || Input.GetKeyDown(KeyCode.Return))
current = (++current == objects.Length ? 0 : current);
objects[current].SetActive(true);
}
}
}
| 26.9375 | 94 | 0.580046 | [
"MIT"
] | WolfDierdonck/AR-Grapher | Assets/Plugins/TEXDraw/Sample/Scripts/TexShowcaseToggle.cs | 864 | C# |
using System;
using System.Data;
using System.Threading;
using System.Threading.Tasks;
using Bussy.Server.Databases;
using Bussy.Server.Models.Order;
using FluentValidation;
using Microsoft.EntityFrameworkCore;
namespace Bussy.Server.Domain.Orders.Validators
{
public class OrderModelForManipulationValidator<T> : AbstractValidator<T> where T: OrderModelForManipulation
{
private readonly BussyDbContext _db;
public OrderModelForManipulationValidator(BussyDbContext db)
{
_db = db;
RuleFor(o => o)
.MustAsync(BeUniqueOrder)
.WithMessage(
"The order must be unique. An order with the same {symbol}-{price}-{size} combination for " +
"the same account already exists!");
RuleFor(o => o.Account)
.NotEmpty().WithMessage("An order account number cannot be empty")
.MaximumLength(16).WithMessage("An order account number cannot exceed 16-characters!");
RuleFor(o => o.Symbol)
.NotEmpty().WithMessage("An order symbol cannot be empty")
.MaximumLength(5).WithMessage("An order symbol cannot exceed 5-characters!");
RuleFor(o => o.Price)
.NotEmpty().WithMessage("An order price cannot be empty")
.LessThanOrEqualTo(0).WithMessage("An order price cannot be less than or equal to 0!");
RuleFor(o => o.Size)
.NotEmpty().WithMessage("An order size cannot be empty")
.LessThanOrEqualTo(0).WithMessage("An order size be less than or equal to 0!");
}
private async Task<bool> BeUniqueOrder(T order, CancellationToken cancellationToken)
{
return await _db.Orders.AllAsync(o =>
o.IsDeleted == false ||
(o.Account != order.Account
&& o.Symbol != order.Symbol
&& Math.Abs(o.Price - order.Price) > 0.000000001
&& o.Size != order.Size),
cancellationToken);
}
}
} | 40.851852 | 114 | 0.572076 | [
"MIT"
] | kkadir/aspnet-5-eventbus | src/Bussy.Server/Domain/Orders/Validators/OrderModelForManipulationValidator.cs | 2,208 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// <auto-generated/>
// Template Source: Templates\CSharp\Model\EntityType.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using Newtonsoft.Json;
/// <summary>
/// The type Event.
/// </summary>
[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
public partial class Event : OutlookItem
{
/// <summary>
/// Gets or sets original start time zone.
/// The start time zone that was set when the event was created. A value of tzone://Microsoft/Custom indicates that a legacy custom time zone was set in desktop Outlook.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "originalStartTimeZone", Required = Newtonsoft.Json.Required.Default)]
public string OriginalStartTimeZone { get; set; }
/// <summary>
/// Gets or sets original end time zone.
/// The end time zone that was set when the event was created. A value of tzone://Microsoft/Custom indicates that a legacy custom time zone was set in desktop Outlook.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "originalEndTimeZone", Required = Newtonsoft.Json.Required.Default)]
public string OriginalEndTimeZone { get; set; }
/// <summary>
/// Gets or sets response status.
/// Indicates the type of response sent in response to an event message.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "responseStatus", Required = Newtonsoft.Json.Required.Default)]
public ResponseStatus ResponseStatus { get; set; }
/// <summary>
/// Gets or sets uid.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "uid", Required = Newtonsoft.Json.Required.Default)]
public string Uid { get; set; }
/// <summary>
/// Gets or sets reminder minutes before start.
/// The number of minutes before the event start time that the reminder alert occurs.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "reminderMinutesBeforeStart", Required = Newtonsoft.Json.Required.Default)]
public Int32? ReminderMinutesBeforeStart { get; set; }
/// <summary>
/// Gets or sets is reminder on.
/// Set to true if an alert is set to remind the user of the event.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "isReminderOn", Required = Newtonsoft.Json.Required.Default)]
public bool? IsReminderOn { get; set; }
/// <summary>
/// Gets or sets has attachments.
/// Set to true if the event has attachments.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "hasAttachments", Required = Newtonsoft.Json.Required.Default)]
public bool? HasAttachments { get; set; }
/// <summary>
/// Gets or sets subject.
/// The text of the event's subject line.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "subject", Required = Newtonsoft.Json.Required.Default)]
public string Subject { get; set; }
/// <summary>
/// Gets or sets body.
/// The body of the message associated with the event. It can be in HTML or text format.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "body", Required = Newtonsoft.Json.Required.Default)]
public ItemBody Body { get; set; }
/// <summary>
/// Gets or sets body preview.
/// The preview of the message associated with the event. It is in text format.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "bodyPreview", Required = Newtonsoft.Json.Required.Default)]
public string BodyPreview { get; set; }
/// <summary>
/// Gets or sets importance.
/// The importance of the event. The possible values are: low, normal, high.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "importance", Required = Newtonsoft.Json.Required.Default)]
public Importance? Importance { get; set; }
/// <summary>
/// Gets or sets sensitivity.
/// The possible values are: normal, personal, private, confidential.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "sensitivity", Required = Newtonsoft.Json.Required.Default)]
public Sensitivity? Sensitivity { get; set; }
/// <summary>
/// Gets or sets start.
/// The date, time, and time zone that the event starts. By default, the start time is in UTC.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "start", Required = Newtonsoft.Json.Required.Default)]
public DateTimeTimeZone Start { get; set; }
/// <summary>
/// Gets or sets original start.
/// The Timestamp type represents date and time information using ISO 8601 format and is always in UTC time. For example, midnight UTC on Jan 1, 2014 would look like this: '2014-01-01T00:00:00Z'
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "originalStart", Required = Newtonsoft.Json.Required.Default)]
public DateTimeOffset? OriginalStart { get; set; }
/// <summary>
/// Gets or sets end.
/// The date, time, and time zone that the event ends. By default, the end time is in UTC.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "end", Required = Newtonsoft.Json.Required.Default)]
public DateTimeTimeZone End { get; set; }
/// <summary>
/// Gets or sets location.
/// The location of the event.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "location", Required = Newtonsoft.Json.Required.Default)]
public Location Location { get; set; }
/// <summary>
/// Gets or sets locations.
/// The locations where the event is held or attended from. The location and locations properties always correspond with each other. If you update the location property, any prior locations in the locations collection would be removed and replaced by the new location value.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "locations", Required = Newtonsoft.Json.Required.Default)]
public IEnumerable<Location> Locations { get; set; }
/// <summary>
/// Gets or sets is all day.
/// Set to true if the event lasts all day.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "isAllDay", Required = Newtonsoft.Json.Required.Default)]
public bool? IsAllDay { get; set; }
/// <summary>
/// Gets or sets is cancelled.
/// Set to true if the event has been canceled.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "isCancelled", Required = Newtonsoft.Json.Required.Default)]
public bool? IsCancelled { get; set; }
/// <summary>
/// Gets or sets is organizer.
/// Set to true if the message sender is also the organizer.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "isOrganizer", Required = Newtonsoft.Json.Required.Default)]
public bool? IsOrganizer { get; set; }
/// <summary>
/// Gets or sets recurrence.
/// The recurrence pattern for the event.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "recurrence", Required = Newtonsoft.Json.Required.Default)]
public PatternedRecurrence Recurrence { get; set; }
/// <summary>
/// Gets or sets response requested.
/// Set to true if the sender would like a response when the event is accepted or declined.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "responseRequested", Required = Newtonsoft.Json.Required.Default)]
public bool? ResponseRequested { get; set; }
/// <summary>
/// Gets or sets series master id.
/// The ID for the recurring series master item, if this event is part of a recurring series.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "seriesMasterId", Required = Newtonsoft.Json.Required.Default)]
public string SeriesMasterId { get; set; }
/// <summary>
/// Gets or sets show as.
/// The status to show. The possible values are: free, tentative, busy, oof, workingElsewhere, unknown.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "showAs", Required = Newtonsoft.Json.Required.Default)]
public FreeBusyStatus? ShowAs { get; set; }
/// <summary>
/// Gets or sets type.
/// The event type. The possible values are: singleInstance, occurrence, exception, seriesMaster. Read-only.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "type", Required = Newtonsoft.Json.Required.Default)]
public EventType? Type { get; set; }
/// <summary>
/// Gets or sets attendees.
/// The collection of attendees for the event.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "attendees", Required = Newtonsoft.Json.Required.Default)]
public IEnumerable<Attendee> Attendees { get; set; }
/// <summary>
/// Gets or sets organizer.
/// The organizer of the event.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "organizer", Required = Newtonsoft.Json.Required.Default)]
public Recipient Organizer { get; set; }
/// <summary>
/// Gets or sets web link.
/// The URL to open the event in Outlook on the web.Outlook on the web opens the event in the browser if you are signed in to your mailbox. Otherwise, Outlook on the web prompts you to sign in.This URL can be accessed from within an iFrame.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "webLink", Required = Newtonsoft.Json.Required.Default)]
public string WebLink { get; set; }
/// <summary>
/// Gets or sets online meeting url.
/// A URL for an online meeting. The property is set only when an organizer specifies an event as an online meeting such as a Skype meeting. Read-only.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "onlineMeetingUrl", Required = Newtonsoft.Json.Required.Default)]
public string OnlineMeetingUrl { get; set; }
/// <summary>
/// Gets or sets attachments.
/// The collection of fileAttachment and itemAttachment attachments for the event. Navigation property. Read-only. Nullable.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "attachments", Required = Newtonsoft.Json.Required.Default)]
public IEventAttachmentsCollectionPage Attachments { get; set; }
/// <summary>
/// Gets or sets single value extended properties.
/// The collection of single-value extended properties defined for the event. Read-only. Nullable.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "singleValueExtendedProperties", Required = Newtonsoft.Json.Required.Default)]
public IEventSingleValueExtendedPropertiesCollectionPage SingleValueExtendedProperties { get; set; }
/// <summary>
/// Gets or sets multi value extended properties.
/// The collection of multi-value extended properties defined for the event. Read-only. Nullable.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "multiValueExtendedProperties", Required = Newtonsoft.Json.Required.Default)]
public IEventMultiValueExtendedPropertiesCollectionPage MultiValueExtendedProperties { get; set; }
/// <summary>
/// Gets or sets calendar.
/// The calendar that contains the event. Navigation property. Read-only.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "calendar", Required = Newtonsoft.Json.Required.Default)]
public Calendar Calendar { get; set; }
/// <summary>
/// Gets or sets instances.
/// The instances of the event. Navigation property. Read-only. Nullable.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "instances", Required = Newtonsoft.Json.Required.Default)]
public IEventInstancesCollectionPage Instances { get; set; }
/// <summary>
/// Gets or sets extensions.
/// The collection of open extensions defined for the event. Read-only. Nullable.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "extensions", Required = Newtonsoft.Json.Required.Default)]
public IEventExtensionsCollectionPage Extensions { get; set; }
}
}
| 53.522059 | 282 | 0.649059 | [
"MIT"
] | gurry/msgraph-beta-sdk-dotnet | src/Microsoft.Graph/Models/Generated/Event.cs | 14,558 | C# |
using System.Runtime.Serialization;
namespace Service.Blockchain.Wallets.Grpc.Models.UserWallets
{
[DataContract]
public class GetUserWalletRequest
{
[DataMember(Order = 1)]
public string WalletId { get; set; }
[DataMember(Order = 2)]
public string AssetSymbol { get; set; }
[DataMember(Order = 3)]
public string AssetNetwork { get; set; }
[DataMember(Order = 4)]
public string BrokerId { get; set; }
[DataMember(Order = 5)]
public string ClientId { get; set; }
}
} | 24.608696 | 60 | 0.609541 | [
"MIT"
] | MyJetWallet/Service.Blockchain.Wallets | src/Service.Blockchain.Wallets.Grpc/Models/UserWallets/GetUserWalletRequest.cs | 566 | C# |
using System;
using Microsoft.IdentityModel.Tokens;
namespace ThinkAM.ThinkAcademy.Authentication.JwtBearer
{
public class TokenAuthConfiguration
{
public SymmetricSecurityKey SecurityKey { get; set; }
public string Issuer { get; set; }
public string Audience { get; set; }
public SigningCredentials SigningCredentials { get; set; }
public TimeSpan Expiration { get; set; }
}
}
| 22.947368 | 66 | 0.68578 | [
"MIT"
] | ThinkAcademy-BR/ThinkAcademy | aspnet-core/src/ThinkAM.ThinkAcademy.Web.Core/Authentication/JwtBearer/TokenAuthConfiguration.cs | 438 | C# |
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System;
using System.Collections.Generic;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Colour;
using osu.Framework.Graphics.OpenGL.Textures;
using osu.Framework.Graphics.Textures;
using osu.Framework.Graphics.UserInterface;
using osu.Framework.Testing;
using OpenTK.Graphics;
namespace osu.Framework.Tests.Visual
{
public class TestCaseCircularProgress : TestCase
{
public override IReadOnlyList<Type> RequiredTypes => new[] { typeof(CircularProgress), typeof(CircularProgressDrawNode), typeof(CircularProgressDrawNodeSharedData) };
private readonly CircularProgress clock;
private int rotateMode;
private const double period = 4000;
private const double transition_period = 2000;
private readonly Texture gradientTextureHorizontal;
private readonly Texture gradientTextureVertical;
private readonly Texture gradientTextureBoth;
public TestCaseCircularProgress()
{
const int width = 128;
byte[] data = new byte[width * 4];
gradientTextureHorizontal = new Texture(width, 1, true);
for (int i = 0; i < width; ++i)
{
float brightness = (float)i / (width - 1);
int index = i * 4;
data[index + 0] = (byte)(128 + (1 - brightness) * 127);
data[index + 1] = (byte)(128 + brightness * 127);
data[index + 2] = 128;
data[index + 3] = 255;
}
gradientTextureHorizontal.SetData(new TextureUpload(data));
gradientTextureVertical = new Texture(1, width, true);
for (int i = 0; i < width; ++i)
{
float brightness = (float)i / (width - 1);
int index = i * 4;
data[index + 0] = (byte)(128 + (1 - brightness) * 127);
data[index + 1] = (byte)(128 + brightness * 127);
data[index + 2] = 128;
data[index + 3] = 255;
}
gradientTextureVertical.SetData(new TextureUpload(data));
byte[] data2 = new byte[width * width * 4];
gradientTextureBoth = new Texture(width, width, true);
for (int i = 0; i < width; ++i)
{
for (int j = 0; j < width; ++j)
{
float brightness = (float)i / (width - 1);
float brightness2 = (float)j / (width - 1);
int index = i * 4 * width + j * 4;
data2[index + 0] = (byte)(128 + (1 + brightness - brightness2) / 2 * 127);
data2[index + 1] = (byte)(128 + (1 + brightness2 - brightness) / 2 * 127);
data2[index + 2] = (byte)(128 + (brightness + brightness2) / 2 * 127);
data2[index + 3] = 255;
}
}
gradientTextureBoth.SetData(new TextureUpload(data2));
Children = new Drawable[]
{
clock = new CircularProgress
{
Width = 0.8f,
Height = 0.8f,
RelativeSizeAxes = Axes.Both,
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
},
};
AddStep("Forward", delegate { rotateMode = 1; });
AddStep("Backward", delegate { rotateMode = 2; });
AddStep("Transition Focus", delegate { rotateMode = 3; });
AddStep("Transition Focus 2", delegate { rotateMode = 4; });
AddStep("Forward/Backward", delegate { rotateMode = 0; });
AddStep("Horizontal Gradient Texture", delegate { setTexture(1); });
AddStep("Vertical Gradient Texture", delegate { setTexture(2); });
AddStep("2D Graident Texture", delegate { setTexture(3); });
AddStep("White Texture", delegate { setTexture(0); });
AddStep("Red Colour", delegate { setColour(1); });
AddStep("Horzontal Gradient Colour", delegate { setColour(2); });
AddStep("Vertical Gradient Colour", delegate { setColour(3); });
AddStep("2D Gradient Colour", delegate { setColour(4); });
AddStep("White Colour", delegate { setColour(0); });
AddSliderStep("Fill", 0, 10, 10, fill => clock.InnerRadius = fill / 10f);
}
protected override void Update()
{
base.Update();
switch (rotateMode)
{
case 0:
clock.Current.Value = Time.Current % (period * 2) / period - 1;
break;
case 1:
clock.Current.Value = Time.Current % period / period;
break;
case 2:
clock.Current.Value = Time.Current % period / period - 1;
break;
case 3:
clock.Current.Value = Time.Current % transition_period / transition_period / 5 - 0.1f;
break;
case 4:
clock.Current.Value = (Time.Current % transition_period / transition_period / 5 - 0.1f + 2) % 2 - 1;
break;
}
}
private void setTexture(int textureMode)
{
switch (textureMode)
{
case 0:
clock.Texture = Texture.WhitePixel;
break;
case 1:
clock.Texture = gradientTextureHorizontal;
break;
case 2:
clock.Texture = gradientTextureVertical;
break;
case 3:
clock.Texture = gradientTextureBoth;
break;
}
}
private void setColour(int colourMode)
{
switch (colourMode)
{
case 0:
clock.Colour = new Color4(255, 255, 255, 255);
break;
case 1:
clock.Colour = new Color4(255, 128, 128, 255);
break;
case 2:
clock.Colour = new ColourInfo
{
TopLeft = new Color4(255, 128, 128, 255),
TopRight = new Color4(128, 255, 128, 255),
BottomLeft = new Color4(255, 128, 128, 255),
BottomRight = new Color4(128, 255, 128, 255),
};
break;
case 3:
clock.Colour = new ColourInfo
{
TopLeft = new Color4(255, 128, 128, 255),
TopRight = new Color4(255, 128, 128, 255),
BottomLeft = new Color4(128, 255, 128, 255),
BottomRight = new Color4(128, 255, 128, 255),
};
break;
case 4:
clock.Colour = new ColourInfo
{
TopLeft = new Color4(255, 128, 128, 255),
TopRight = new Color4(128, 255, 128, 255),
BottomLeft = new Color4(128, 128, 255, 255),
BottomRight = new Color4(255, 255, 255, 255),
};
break;
}
}
}
}
| 40.776042 | 175 | 0.468259 | [
"MIT"
] | miterosan/osu-framework | osu.Framework.Tests/Visual/TestCaseCircularProgress.cs | 7,831 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using cmstar.Serialization.Json;
#if !NETFX
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
#else
using System.Web;
#endif
namespace cmstar.WebApi.Slim
{
/// <summary>
/// 提供Slim WebAPI的入口。继承此类以实现API的注册和使用。
/// 这是一个抽象类。
/// </summary>
public abstract class SlimApiHttpHandler : ApiHttpHandlerBase
{
/// <summary>
/// 指定被调用的方法的名称的参数。
/// 可出现在URL参数、路径(通过路由匹配)或表单中。
/// </summary>
public static string MetaParamMethodName = "~method";
/// <summary>
/// 指定数据的序列化方式的参数。
/// 可出现在URL参数、路径(通过路由匹配)或表单中。
/// </summary>
public static string MetaParamFormat = "~format";
/// <summary>
/// 指定回执的JSONP回调方法名称的参数。
/// 可出现在URL参数、路径(通过路由匹配)或表单中。
/// </summary>
public static string MetaParamCallback = "~callback";
/// <summary>
/// 指定使用JSON请求。
/// </summary>
public const string MetaRequestFormatJson = "json";
/// <summary>
/// 指定使用GET方法请求。
/// </summary>
public const string MetaRequestFormatPost = "post";
/// <summary>
/// 指定使用POST方法请求。
/// </summary>
public const string MetaRequestFormatGet = "get";
/// <summary>
/// 指定回执的MIME类型为text/plain。
/// </summary>
public const string MetaResponseFormatPlain = "plain";
/// <summary>
/// 未指定字符集时使用的默认字符集。
/// </summary>
public static readonly Encoding DefaultEncoding = Encoding.UTF8;
private const int OutputBodyLimitLower = 1024;
private const int OutputBodyLimitUpper = 65536;
/// <summary>
/// 获取请求方的IP地址。
/// </summary>
/// <param name="request">当前请求对应的<see cref="HttpRequest"/>实例。</param>
/// <returns>请求方的IP地址。</returns>
protected virtual string GetUserHostAddress(HttpRequest request)
{
return request.UserHostAddress();
}
/// <summary>
/// 获取指定的API方法所对应的参数解析器。
/// </summary>
/// <param name="method">包含API方法的有关信息。</param>
/// <returns>key为解析器的名称,value为解析器实例。</returns>
protected override IDictionary<string, IRequestDecoder> ResolveDecoders(ApiMethodInfo method)
{
var param = method.Method.GetParameters();
var decoderMap = new Dictionary<string, IRequestDecoder>(4);
if (param.Length == 0)
{
decoderMap[MetaRequestFormatGet]
= decoderMap[MetaRequestFormatPost]
= decoderMap[MetaRequestFormatJson]
= decoderMap[string.Empty]
= EmptyParamMethodRequestDecoder.Instance;
return decoderMap;
}
var paramInfoMap = method.ParamInfoMap;
var methodParamStat = TypeHelper.GetMethodParamStat(method.Method);
if (!methodParamStat.HasComplexMember)
{
var inlineParamHttpParamDecoder = new InlineParamHttpParamDecoder(paramInfoMap);
decoderMap[MetaRequestFormatGet] = inlineParamHttpParamDecoder;
if (!methodParamStat.HasFileInput)
{
decoderMap[MetaRequestFormatPost] = inlineParamHttpParamDecoder;
decoderMap[MetaRequestFormatJson] = new InlineParamJsonDecoder(paramInfoMap);
}
}
else if (param.Length == 1)
{
var paramType = param[0].ParameterType;
var paramTypeStat = TypeHelper.GetTypeMemberStat(paramType);
if (paramTypeStat.HasFileInput)
{
if (paramTypeStat.HasComplexMember)
{
throw NoSupportedDecoderError(method.Method);
}
decoderMap[MetaRequestFormatGet] = new SingleObjectHttpParamDecoder(paramInfoMap);
}
else
{
if (!paramTypeStat.HasComplexMember)
{
var singleObjectHttpParamDecoder = new SingleObjectHttpParamDecoder(paramInfoMap);
decoderMap[MetaRequestFormatGet] = singleObjectHttpParamDecoder;
decoderMap[MetaRequestFormatPost] = singleObjectHttpParamDecoder;
}
decoderMap[MetaRequestFormatJson] = new SingleObjectJsonDecoder(paramInfoMap);
}
}
else // param.Length > 1 || methodParamStat.HasCoplexMember
{
if (methodParamStat.HasFileInput)
{
throw NoSupportedDecoderError(method.Method);
}
decoderMap[MetaRequestFormatJson] = new InlineParamJsonDecoder(paramInfoMap);
}
// 设置默认的Decoder,优先级 get->json->post
if (decoderMap.ContainsKey(MetaRequestFormatGet))
{
decoderMap[string.Empty] = decoderMap[MetaRequestFormatGet];
}
else if (decoderMap.ContainsKey(MetaRequestFormatJson))
{
decoderMap[string.Empty] = decoderMap[MetaRequestFormatJson];
}
else if (decoderMap.ContainsKey(MetaRequestFormatPost))
{
decoderMap[string.Empty] = decoderMap[MetaRequestFormatPost];
}
return decoderMap;
}
/// <summary>
/// 创建用于保存当前API请求信息的对象实例。
/// </summary>
/// <param name="context">当前请求的<see cref="HttpContext"/>实例。</param>
/// <param name="handlerState"><see cref="ApiHandlerState"/>的实例。</param>
/// <returns>用于保存当前API请求信息的对象实例。</returns>
protected override object CreateRequestState(HttpContext context, ApiHandlerState handlerState)
{
var requestState = new SlimApiRequestState();
var request = context.Request;
// 元参数可以多种方式体现(中括号内内容为可选):
// 形式1:http://domain/entry?~method=METHOD[&~format=FORMAT][&~callback=CALLBACK]
// 形式2:http://domain/entry?METHOD[.FORMAT][(CALLBACK)]
// 形式3使用路由:http://domain/entry/{~method}/[{~format}/][{~callback}/]
// 优先级自上而下
// 形式1
var method = request.ExplicitParam(MetaParamMethodName);
var callback = request.ExplicitParam(MetaParamCallback);
var format = request.ExplicitParam(MetaParamFormat);
// 形式3
#if !NETFX
var routeData = context.GetRouteData();
#else
var routeData = RouteData;
#endif
if (routeData != null)
{
if (method == null)
method = routeData.Param(MetaParamMethodName);
if (callback == null)
callback = routeData.Param(MetaParamCallback);
if (format == null)
format = routeData.Param(MetaParamFormat);
}
// 形式2
if (method == null)
{
var mixedMetaParams = request.LegacyQueryString(null);
if (mixedMetaParams != null)
{
ParseMixedMetaParams(mixedMetaParams, out method, ref format, ref callback);
}
}
if (string.IsNullOrEmpty(format))
{
// 没有通过参数直接指定格式的情况下,尝试从Content-Type判断
switch (request.ContentType)
{
case "application/json":
requestState.RequestFormat = MetaRequestFormatJson;
break;
case "application/x-www-form-urlencoded":
requestState.RequestFormat = MetaRequestFormatPost;
break;
}
}
else
{
// format参数可包含多段使用逗号隔开的值(e.g. json,plain)
var formatOptions = format.Split(TypeHelper.CollectionElementSplitter);
var ignoreCaseComparer = StringComparer.OrdinalIgnoreCase;
foreach (var formatOption in formatOptions)
{
if (ignoreCaseComparer.Equals(formatOption, MetaResponseFormatPlain))
{
requestState.UsePlainText = true;
}
else
{
requestState.RequestFormat = formatOption;
}
}
}
requestState.MethodName = method;
requestState.CallbackName = callback;
return requestState;
}
/// <summary>
/// 获取当前API请求所管理的方法名称。
/// 若未能获取到名称,返回null。
/// </summary>
/// <param name="context">当前请求的<see cref="HttpContext"/>实例。</param>
/// <param name="requestState">用于保存当前API请求信息的对象实例。</param>
/// <returns>方法名称。</returns>
protected override string RetriveRequestMethodName(HttpContext context, object requestState)
{
return ((SlimApiRequestState)requestState).MethodName;
}
/// <summary>
/// 获取当前调用的API方法所使用的参数解析器的名称。
/// 若未能获取到名称,返回null。
/// </summary>
/// <param name="context">当前请求的<see cref="HttpContext"/>实例。</param>
/// <param name="requestState">用于保存当前API请求信息的对象实例。</param>
/// <returns>调用的API方法所使用的参数解析器的名称。</returns>
protected override string RetrieveRequestDecoderName(HttpContext context, object requestState)
{
return ((SlimApiRequestState)requestState).RequestFormat;
}
/// <summary>
/// 创建当前调用的API方法所需要的参数值集合。
/// 集合以参数名称为key,参数的值为value。
/// </summary>
/// <param name="context">当前请求的<see cref="HttpContext"/>实例。</param>
/// <param name="requestState">用于保存当前API请求信息的对象实例。</param>
/// <param name="decoder">用于API参数解析的<see cref="IRequestDecoder"/>实例。</param>
/// <returns>记录参数名称和对应的值。</returns>
protected override IDictionary<string, object> DecodeParam(
HttpContext context, object requestState, IRequestDecoder decoder)
{
try
{
return decoder.DecodeParam(context.Request, requestState);
}
catch (Exception ex)
{
if (ex is JsonContractException || ex is JsonFormatException || ex is InvalidCastException)
throw new ApiException(ApiEnvironment.CodeBadRequest, "Bad request.", ex);
throw;
}
}
#pragma warning disable 1998
/// <summary>
/// 将指定的<see cref="ApiResponse"/>序列化并写入HTTP输出流中。
/// </summary>
/// <param name="context">当前请求的<see cref="HttpContext"/>实例。</param>
/// <param name="requestState">用于保存当前API请求信息的对象实例。</param>
/// <param name="apiResponse">用于表示API返回的数据。</param>
protected override async Task WriteResponseAsync(
HttpContext context, object requestState, ApiResponse apiResponse)
{
var slimApiRequestState = (SlimApiRequestState)requestState;
var httpResponse = context.Response;
var isJsonp = !string.IsNullOrEmpty(slimApiRequestState.CallbackName);
if (slimApiRequestState.UsePlainText)
{
httpResponse.ContentType = "text/plain";
}
else if (isJsonp)
{
httpResponse.ContentType = "text/javascript";
}
else
{
httpResponse.ContentType = "application/json";
}
var bodyBuilder = new StringBuilder();
if (isJsonp)
{
bodyBuilder.Append(slimApiRequestState.CallbackName);
bodyBuilder.Append("(");
}
var responseJson = JsonHelper.Serialize(apiResponse);
bodyBuilder.Append(responseJson);
if (isJsonp)
{
bodyBuilder.Append(")");
}
var body = bodyBuilder.ToString();
await httpResponse.WriteAsync(body);
}
#pragma warning restore 1998
/// <summary>
/// 获取当前请求的描述信息。
/// </summary>
/// <param name="context">当前请求的<see cref="HttpContext"/>实例。</param>
/// <param name="requestState">用于保存当前API请求信息的对象实例。</param>
/// <param name="apiResponse">用于表示API返回的数据。</param>
/// <returns>描述信息。</returns>
protected override LogMessage GetRequestDescription(
HttpContext context, object requestState, ApiResponse apiResponse)
{
var request = context.Request;
var logMessage = new LogMessage();
logMessage.SetProperty("Ip", GetUserHostAddress(request));
logMessage.SetProperty("Url", request.FullUrl());
#if !NETFX
var files = request.FormFiles();
#else
var files = request.Files;
#endif
var fileCount = files.Count;
if (fileCount == 0)
{
var inputStream = request.RequestInputStream();
var bodyLength = inputStream.Length;
if (bodyLength > 0)
{
logMessage.SetProperty("Length", bodyLength.ToString());
// 输出body部分按照下述逻辑判定:
// 1 1K以下的数据直接输出;
// 2 64K以上的数据不输出;
// 3 之间的数据校验是否是文本,若为文本则输出;
bool canOutputBody;
if (bodyLength < OutputBodyLimitLower)
{
canOutputBody = true;
}
else if (bodyLength >= OutputBodyLimitUpper)
{
canOutputBody = false;
}
else
{
canOutputBody = IsTextRequestBody(inputStream);
}
if (canOutputBody)
{
var body = ReadRequestBody(inputStream);
logMessage.SetProperty("Body", body);
}
}
}
else
{
// 分部表单的,输出每个分部的概要信息。
#if NETFX
var partNames = files.AllKeys;
#endif
for (int i = 0; i < fileCount; i++)
{
var file = files[i];
#if !NETFX
logMessage.SetProperty("Name" + i, file.Name);
#else
logMessage.SetProperty("Name" + i, partNames[i]);
#endif
logMessage.SetProperty("File" + i, file.FileName);
logMessage.SetProperty("ContentType" + i, file.ContentType);
#if !NETFX
logMessage.SetProperty("Length" + i, file.Length.ToString());
#else
logMessage.SetProperty("Length" + i, file.ContentLength.ToString());
#endif
}
}
if (apiResponse != null)
{
var messageBuilder = new StringBuilder();
if (apiResponse.Code != 0)
{
messageBuilder.Append('(').Append(apiResponse.Code).Append(')');
}
if (!string.IsNullOrEmpty(apiResponse.Message))
{
if (messageBuilder.Length > 0)
{
messageBuilder.Append(' ');
}
messageBuilder.Append(apiResponse.Message);
}
logMessage.Message = messageBuilder.ToString();
}
return logMessage;
}
private static Exception NoSupportedDecoderError(MethodInfo method)
{
var msg = $"Can not resolve decoder for method {method.Name} in type {method.DeclaringType}.";
return new NotSupportedException(msg);
}
private static bool IsTextRequestBody(Stream inputStream)
{
// 重读InputStream
inputStream.Position = 0;
// 使用检测\0\0的方式校验,实际上在ASCII和utf8下文本中一个\0都不会有;
// 但utf16可能会存在一个\0,从兼容性考虑这里校验两个更为保险
var buffer = new byte[128];
int len;
while ((len = inputStream.Read(buffer, 0, buffer.Length)) > 0)
{
bool preZero = false;
for (int i = 0; i < len; i++)
{
if (buffer[i] == '\0')
{
if (preZero)
return false;
preZero = true;
}
else
{
preZero = false;
}
}
}
return true;
}
private static string ReadRequestBody(Stream inputStream)
{
// 重读InputStream
inputStream.Position = 0;
var streamReader = new StreamReader(inputStream);
var body = streamReader.ReadToEnd();
return body;
}
private static void ParseMixedMetaParams(string input, out string method, ref string format, ref string callback)
{
// METHOD.FORMAT(CALLBACK)
const int followedByFormat = 1;
const int followedByCallback = 2;
var inputLength = input.Length;
var position = 0;
var followedBy = 0;
while (position < inputLength)
{
var c = input[position];
if (c == '.') // hit the beginning of the format name
{
followedBy = followedByFormat;
break;
}
if (c == '(') // hit the beginning of the callback name
{
followedBy = followedByCallback;
break;
}
if (++position == inputLength)
{
method = input;
return;
}
}
method = input.Substring(0, position);
if (followedBy == followedByFormat)
{
position++; // move to the next char after .
var formatStartIndex = position;
var paramLength = 0;
while (position < inputLength)
{
var c = input[position];
if (c == '(') // hit the beginning of the callback name
{
followedBy = followedByCallback;
break;
}
paramLength++;
position++;
}
if (format == null)
{
format = input.Substring(formatStartIndex, paramLength);
}
}
if (followedBy == followedByCallback)
{
position++; // move to the next char after (
var callbackStartIndex = position;
var paramLength = 0;
while (true)
{
var c = input[position];
if (c == ')') // hit the end of the callback name
break;
paramLength++;
position++;
// if there's not a ')', means no callback name specified
if (position == inputLength)
return;
}
if (callback == null)
{
callback = input.Substring(callbackStartIndex, paramLength);
}
}
}
}
}
| 33.860034 | 121 | 0.505951 | [
"MIT"
] | cmstar/SlimWebApi | src/cmstar.WebApi/Slim/SlimApiHttpHandler.cs | 21,755 | C# |
/*******************************************************************************
* Copyright 2012-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file.
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
* *****************************************************************************
*
* AWS Tools for Windows (TM) PowerShell (TM)
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using System.Text;
using Amazon.PowerShell.Common;
using Amazon.Runtime;
using Amazon.IoT;
using Amazon.IoT.Model;
namespace Amazon.PowerShell.Cmdlets.IOT
{
/// <summary>
/// The query search index.
/// </summary>
[Cmdlet("Search", "IOTIndex", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.Medium)]
[OutputType("Amazon.IoT.Model.SearchIndexResponse")]
[AWSCmdlet("Calls the AWS IoT SearchIndex API operation.", Operation = new[] {"SearchIndex"}, SelectReturnType = typeof(Amazon.IoT.Model.SearchIndexResponse))]
[AWSCmdletOutput("Amazon.IoT.Model.SearchIndexResponse",
"This cmdlet returns an Amazon.IoT.Model.SearchIndexResponse object containing multiple properties. The object can also be referenced from properties attached to the cmdlet entry in the $AWSHistory stack."
)]
public partial class SearchIOTIndexCmdlet : AmazonIoTClientCmdlet, IExecutor
{
#region Parameter IndexName
/// <summary>
/// <para>
/// <para>The search index name.</para>
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public System.String IndexName { get; set; }
#endregion
#region Parameter QueryString
/// <summary>
/// <para>
/// <para>The search query string.</para>
/// </para>
/// </summary>
#if !MODULAR
[System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true)]
#else
[System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true, Mandatory = true)]
[System.Management.Automation.AllowEmptyString]
[System.Management.Automation.AllowNull]
#endif
[Amazon.PowerShell.Common.AWSRequiredParameter]
public System.String QueryString { get; set; }
#endregion
#region Parameter QueryVersion
/// <summary>
/// <para>
/// <para>The query version.</para>
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public System.String QueryVersion { get; set; }
#endregion
#region Parameter MaxResult
/// <summary>
/// <para>
/// <para>The maximum number of results to return at one time.</para>
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
[Alias("MaxResults")]
public System.Int32? MaxResult { get; set; }
#endregion
#region Parameter NextToken
/// <summary>
/// <para>
/// <para>The token used to get the next set of results, or <code>null</code> if there are no
/// additional results.</para>
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public System.String NextToken { get; set; }
#endregion
#region Parameter Select
/// <summary>
/// Use the -Select parameter to control the cmdlet output. The default value is '*'.
/// Specifying -Select '*' will result in the cmdlet returning the whole service response (Amazon.IoT.Model.SearchIndexResponse).
/// Specifying the name of a property of type Amazon.IoT.Model.SearchIndexResponse will result in that property being returned.
/// Specifying -Select '^ParameterName' will result in the cmdlet returning the selected cmdlet parameter value.
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public string Select { get; set; } = "*";
#endregion
#region Parameter PassThru
/// <summary>
/// Changes the cmdlet behavior to return the value passed to the QueryString parameter.
/// The -PassThru parameter is deprecated, use -Select '^QueryString' instead. This parameter will be removed in a future version.
/// </summary>
[System.Obsolete("The -PassThru parameter is deprecated, use -Select '^QueryString' instead. This parameter will be removed in a future version.")]
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public SwitchParameter PassThru { get; set; }
#endregion
#region Parameter Force
/// <summary>
/// This parameter overrides confirmation prompts to force
/// the cmdlet to continue its operation. This parameter should always
/// be used with caution.
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public SwitchParameter Force { get; set; }
#endregion
protected override void ProcessRecord()
{
base.ProcessRecord();
var resourceIdentifiersText = FormatParameterValuesForConfirmationMsg(nameof(this.IndexName), MyInvocation.BoundParameters);
if (!ConfirmShouldProceed(this.Force.IsPresent, resourceIdentifiersText, "Search-IOTIndex (SearchIndex)"))
{
return;
}
var context = new CmdletContext();
// allow for manipulation of parameters prior to loading into context
PreExecutionContextLoad(context);
#pragma warning disable CS0618, CS0612 //A class member was marked with the Obsolete attribute
if (ParameterWasBound(nameof(this.Select)))
{
context.Select = CreateSelectDelegate<Amazon.IoT.Model.SearchIndexResponse, SearchIOTIndexCmdlet>(Select) ??
throw new System.ArgumentException("Invalid value for -Select parameter.", nameof(this.Select));
if (this.PassThru.IsPresent)
{
throw new System.ArgumentException("-PassThru cannot be used when -Select is specified.", nameof(this.Select));
}
}
else if (this.PassThru.IsPresent)
{
context.Select = (response, cmdlet) => this.QueryString;
}
#pragma warning restore CS0618, CS0612 //A class member was marked with the Obsolete attribute
context.IndexName = this.IndexName;
context.MaxResult = this.MaxResult;
context.NextToken = this.NextToken;
context.QueryString = this.QueryString;
#if MODULAR
if (this.QueryString == null && ParameterWasBound(nameof(this.QueryString)))
{
WriteWarning("You are passing $null as a value for parameter QueryString which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues.");
}
#endif
context.QueryVersion = this.QueryVersion;
// allow further manipulation of loaded context prior to processing
PostExecutionContextLoad(context);
var output = Execute(context) as CmdletOutput;
ProcessOutput(output);
}
#region IExecutor Members
public object Execute(ExecutorContext context)
{
var cmdletContext = context as CmdletContext;
// create request
var request = new Amazon.IoT.Model.SearchIndexRequest();
if (cmdletContext.IndexName != null)
{
request.IndexName = cmdletContext.IndexName;
}
if (cmdletContext.MaxResult != null)
{
request.MaxResults = cmdletContext.MaxResult.Value;
}
if (cmdletContext.NextToken != null)
{
request.NextToken = cmdletContext.NextToken;
}
if (cmdletContext.QueryString != null)
{
request.QueryString = cmdletContext.QueryString;
}
if (cmdletContext.QueryVersion != null)
{
request.QueryVersion = cmdletContext.QueryVersion;
}
CmdletOutput output;
// issue call
var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint);
try
{
var response = CallAWSServiceOperation(client, request);
object pipelineOutput = null;
pipelineOutput = cmdletContext.Select(response, this);
output = new CmdletOutput
{
PipelineOutput = pipelineOutput,
ServiceResponse = response
};
}
catch (Exception e)
{
output = new CmdletOutput { ErrorResponse = e };
}
return output;
}
public ExecutorContext CreateContext()
{
return new CmdletContext();
}
#endregion
#region AWS Service Operation Call
private Amazon.IoT.Model.SearchIndexResponse CallAWSServiceOperation(IAmazonIoT client, Amazon.IoT.Model.SearchIndexRequest request)
{
Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "AWS IoT", "SearchIndex");
try
{
#if DESKTOP
return client.SearchIndex(request);
#elif CORECLR
return client.SearchIndexAsync(request).GetAwaiter().GetResult();
#else
#error "Unknown build edition"
#endif
}
catch (AmazonServiceException exc)
{
var webException = exc.InnerException as System.Net.WebException;
if (webException != null)
{
throw new Exception(Utils.Common.FormatNameResolutionFailureMessage(client.Config, webException.Message), webException);
}
throw;
}
}
#endregion
internal partial class CmdletContext : ExecutorContext
{
public System.String IndexName { get; set; }
public System.Int32? MaxResult { get; set; }
public System.String NextToken { get; set; }
public System.String QueryString { get; set; }
public System.String QueryVersion { get; set; }
public System.Func<Amazon.IoT.Model.SearchIndexResponse, SearchIOTIndexCmdlet, object> Select { get; set; } =
(response, cmdlet) => response;
}
}
}
| 42.412811 | 282 | 0.592549 | [
"Apache-2.0"
] | JekzVadaria/aws-tools-for-powershell | modules/AWSPowerShell/Cmdlets/IoT/Basic/Search-IOTIndex-Cmdlet.cs | 11,918 | 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.md file in the project root for more information.
using System;
using System.Collections.Immutable;
using static Microsoft.VisualStudio.ProjectSystem.Tokenizer;
namespace Microsoft.VisualStudio.ProjectSystem
{
// Parses a string into a project tree
//
internal partial class ProjectTreeParser
{
private readonly Tokenizer _tokenizer;
private int _indentLevel;
public ProjectTreeParser(string value)
{
Requires.NotNullOrEmpty(value, nameof(value));
_tokenizer = new Tokenizer(new SimpleStringReader(value), Delimiters.Structural);
}
public static IProjectTree Parse(string value)
{
value = value.Trim(new char[] { '\r', '\n' });
var parser = new ProjectTreeParser(value);
return parser.Parse();
}
public IProjectTree Parse()
{
MutableProjectTree root = ReadProjectRoot();
_tokenizer.Close();
return root;
}
private MutableProjectTree ReadProjectRoot()
{
// We always start with the root, with zero indent
MutableProjectTree root = ReadProjectItem();
MutableProjectTree? current = root;
do
{
current = ReadNextProjectItem(current);
} while (current != null);
return root;
}
private MutableProjectTree? ReadNextProjectItem(MutableProjectTree current)
{
if (!TryReadNewLine())
return null;
MutableProjectTree? parent = current;
int indent = ReadIndentLevel(out int previousIndentLevel);
while (indent <= previousIndentLevel)
{
parent = parent?.Parent;
indent++;
}
if (parent == null)
throw FormatException(ProjectTreeFormatError.MultipleRoots, "Encountered another project root, when tree can only have one.");
MutableProjectTree tree = ReadProjectItem();
tree.Parent = parent;
parent.Children.Add(tree);
return tree;
}
private int ReadIndentLevel(out int previousIndentLevel)
{
// Attempts to read the indent level of the current project item
//
// Root <--- IndentLevel: 0
// Parent <--- IndentLevel: 1
// Child <--- IndentLevel: 2
previousIndentLevel = _indentLevel;
int indentLevel = 0;
while (_tokenizer.Peek() == TokenType.WhiteSpace)
{
_tokenizer.Skip(TokenType.WhiteSpace);
_tokenizer.Skip(TokenType.WhiteSpace);
_tokenizer.Skip(TokenType.WhiteSpace);
_tokenizer.Skip(TokenType.WhiteSpace);
indentLevel++;
}
if (indentLevel > previousIndentLevel + 1)
throw FormatException(ProjectTreeFormatError.IndentTooManyLevels, "Project item has been indented too many levels");
return _indentLevel = indentLevel;
}
private bool TryReadNewLine()
{
if (_tokenizer.SkipIf(TokenType.CarriageReturn))
{ // If we read '\r', it must be followed by a '\n'
_tokenizer.Skip(TokenType.NewLine);
return true;
}
return _tokenizer.SkipIf(TokenType.NewLine);
}
private MutableProjectTree ReadProjectItem()
{
var tree = new MutableProjectItemTree();
ReadProjectItemProperties(tree);
return tree.BuildProjectTree();
}
private void ReadProjectItemProperties(MutableProjectItemTree tree)
{ // Parse "Root (visibility: visible, flags: {ProjectRoot}), FilePath: "C:\My Project\MyFile.txt", Icon: {1B5CF1ED-9525-42B4-85F0-2CB50530ECA9 1}, ExpandedIcon: {1B5CF1ED-9525-42B4-85F0-2CB50530ECA9 1}
ReadCaption(tree);
ReadProperties(tree);
ReadFields(tree);
}
private void ReadCaption(MutableProjectItemTree tree)
{
Tokenizer tokenizer = Tokenizer(Delimiters.Caption);
tree.Caption = tokenizer.ReadIdentifier(IdentifierParseOptions.Required);
}
private void ReadProperties(MutableProjectItemTree tree)
{ // Parses "(visibility: visible, flags: {ProjectRoot})"
// Properties section is optional
if (!_tokenizer.SkipIf(TokenType.LeftParenthesis))
return;
// Empty properties
if (_tokenizer.SkipIf(TokenType.RightParenthesis))
return;
ReadProperty(tree);
while (_tokenizer.SkipIf(TokenType.Comma))
{
_tokenizer.Skip(TokenType.WhiteSpace);
ReadProperty(tree);
}
_tokenizer.Skip(TokenType.RightParenthesis);
}
private void ReadProperty(MutableProjectItemTree tree)
{
Tokenizer tokenizer = Tokenizer(Delimiters.PropertyName);
string propertyName = tokenizer.ReadIdentifier(IdentifierParseOptions.Required);
switch (propertyName)
{
case "visibility":
tokenizer.Skip(TokenType.Colon);
tokenizer.Skip(TokenType.WhiteSpace);
ReadVisibility(tree);
break;
case "flags":
tokenizer.Skip(TokenType.Colon);
tokenizer.Skip(TokenType.WhiteSpace);
ReadCapabilities(tree);
break;
default:
throw FormatException(ProjectTreeFormatError.UnrecognizedPropertyName, $"Expected 'visibility' or 'flags', but encountered '{propertyName}'.");
}
}
private void ReadVisibility(MutableProjectItemTree tree)
{ // Parse 'visible' in 'visibility:visible' or 'invisible' in 'visibility:invisible"
Tokenizer tokenizer = Tokenizer(Delimiters.PropertyValue);
string visibility = tokenizer.ReadIdentifier(IdentifierParseOptions.Required);
tree.Visible = visibility switch
{
"visible" => true,
"invisible" => false,
_ => throw FormatException(ProjectTreeFormatError.UnrecognizedPropertyValue, $"Expected 'visible' or 'invisible', but encountered '{visibility}'."),
};
}
private void ReadCapabilities(MutableProjectItemTree tree)
{ // Parse '{ProjectRoot Folder}'
Tokenizer tokenizer = Tokenizer(Delimiters.BracedPropertyValueBlock);
tokenizer.Skip(TokenType.LeftBrace);
// Empty flags
if (tokenizer.SkipIf(TokenType.RightBrace))
return;
do
{
ReadFlag(tree);
}
while (tokenizer.SkipIf(TokenType.WhiteSpace));
tokenizer.Skip(TokenType.RightBrace);
}
private void ReadFlag(MutableProjectItemTree tree)
{ // Parses 'AppDesigner' in '{AppDesigner Folder}'
Tokenizer tokenizer = Tokenizer(Delimiters.BracedPropertyValue);
string flag = tokenizer.ReadIdentifier(IdentifierParseOptions.Required);
tree.AddFlag(flag);
}
private void ReadFields(MutableProjectItemTree tree)
{ // Parses ', FilePath: "C:\Temp\Foo"'
// This section is optional
while (_tokenizer.SkipIf(TokenType.Comma))
{
_tokenizer.Skip(TokenType.WhiteSpace);
Tokenizer tokenizer = Tokenizer(Delimiters.PropertyName);
string fieldName = tokenizer.ReadIdentifier(IdentifierParseOptions.Required);
switch (fieldName)
{
case "FilePath":
tokenizer.Skip(TokenType.Colon);
tokenizer.Skip(TokenType.WhiteSpace);
ReadFilePath(tree);
break;
case "ItemType":
tokenizer.Skip(TokenType.Colon);
tokenizer.Skip(TokenType.WhiteSpace);
ReadItemType(tree);
break;
case "SubType":
tokenizer.Skip(TokenType.Colon);
tokenizer.Skip(TokenType.WhiteSpace);
ReadSubType(tree);
break;
case "Icon":
tokenizer.Skip(TokenType.Colon);
tokenizer.Skip(TokenType.WhiteSpace);
ReadIcon(tree, expandedIcon: false);
break;
case "ExpandedIcon":
tokenizer.Skip(TokenType.Colon);
tokenizer.Skip(TokenType.WhiteSpace);
ReadIcon(tree, expandedIcon: true);
break;
case "DisplayOrder":
tokenizer.Skip(TokenType.Colon);
tokenizer.Skip(TokenType.WhiteSpace);
ReadDisplayOrder(tree);
break;
case "ItemName":
tokenizer.Skip(TokenType.Colon);
tokenizer.Skip(TokenType.WhiteSpace);
ReadItemName(tree);
break;
default:
throw FormatException(ProjectTreeFormatError.UnrecognizedPropertyName, $"Expected 'FilePath', 'Icon' or 'ExpandedIcon', but encountered '{fieldName}'.");
}
}
}
private void ReadDisplayOrder(MutableProjectItemTree tree)
{ // Parses '1`
Tokenizer tokenizer = Tokenizer(Delimiters.PropertyValue);
string identifier = tokenizer.ReadIdentifier(IdentifierParseOptions.None);
tree.DisplayOrder = int.Parse(identifier);
}
private void ReadItemName(MutableProjectItemTree tree)
{ // Parses '"test.fs"'
tree.Item.ItemName = ReadQuotedPropertyValue();
}
private void ReadFilePath(MutableProjectItemTree tree)
{ // Parses '"C:\Temp\Foo"'
tree.FilePath = ReadQuotedPropertyValue();
}
private void ReadItemType(MutableProjectItemTree tree)
{
tree.Item.ItemType = ReadPropertyValue();
}
private void ReadSubType(MutableProjectItemTree tree)
{
tree.SubType = ReadPropertyValue();
}
private string ReadPropertyValue()
{
Tokenizer tokenizer = Tokenizer(Delimiters.PropertyValue);
return tokenizer.ReadIdentifier(IdentifierParseOptions.None);
}
private string ReadQuotedPropertyValue()
{ // Parses '"C:\Temp"'
Tokenizer tokenizer = Tokenizer(Delimiters.QuotedPropertyValue);
tokenizer.Skip(TokenType.Quote);
string value = tokenizer.ReadIdentifier(IdentifierParseOptions.None);
tokenizer.Skip(TokenType.Quote);
return value;
}
private void ReadIcon(MutableProjectTree tree, bool expandedIcon)
{ // Parses '{1B5CF1ED-9525-42B4-85F0-2CB50530ECA9 1}'
Tokenizer tokenizer = Tokenizer(Delimiters.BracedPropertyValueBlock);
tokenizer.Skip(TokenType.LeftBrace);
// Empty icon
if (tokenizer.SkipIf(TokenType.RightBrace))
return;
ProjectImageMoniker moniker = ReadProjectImageMoniker();
if (expandedIcon)
{
tree.ExpandedIcon = moniker;
}
else
{
tree.Icon = moniker;
}
tokenizer.Skip(TokenType.RightBrace);
}
private ProjectImageMoniker ReadProjectImageMoniker()
{
Tokenizer tokenizer = Tokenizer(Delimiters.BracedPropertyValue);
string guidAsString = tokenizer.ReadIdentifier(IdentifierParseOptions.Required);
if (!Guid.TryParseExact(guidAsString, "D", out Guid guid))
throw FormatException(ProjectTreeFormatError.GuidExpected, $"Expected GUID, but encountered '{guidAsString}'");
tokenizer.Skip(TokenType.WhiteSpace);
string idAsString = tokenizer.ReadIdentifier(IdentifierParseOptions.Required);
if (!int.TryParse(idAsString, out int id))
throw FormatException(ProjectTreeFormatError.IntegerExpected, $"Expected integer, but encountered '{idAsString}'");
return new ProjectImageMoniker(guid, id);
}
private Tokenizer Tokenizer(ImmutableArray<TokenType> delimiters)
{
return new Tokenizer(_tokenizer.UnderlyingReader, delimiters);
}
}
}
| 34.682741 | 213 | 0.550677 | [
"MIT"
] | Ykk199612053634/project-system | tests/Microsoft.VisualStudio.ProjectSystem.Managed.TestServices/ProjectSystem/ProjectTreeParser/ProjectTreeParser.cs | 13,274 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.Extensions.Logging;
namespace Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore
{
internal static class DiagnosticsEntityFrameworkCoreLoggerExtensions
{
// MigrationsEndPointMiddleware
private static readonly Action<ILogger, Exception> _noContextType = LoggerMessage.Define(
LogLevel.Error,
new EventId(1, "NoContextType"),
"No context type was specified. Ensure the form data from the request includes a 'context' value, specifying the context type name to apply migrations for.");
private static readonly Action<ILogger, string, Exception> _contextNotRegistered = LoggerMessage.Define<string>(
LogLevel.Error,
new EventId(3, "ContextNotRegistered"),
"The context type '{ContextTypeName}' was not found in services. This usually means the context was not registered in services during startup. You probably want to call AddScoped<>() inside the UseServices(...) call in your application startup code.");
private static readonly Action<ILogger, string, Exception> _requestPathMatched = LoggerMessage.Define<string>(
LogLevel.Debug,
new EventId(4, "RequestPathMatched"),
"Request path matched the path configured for this migrations endpoint({RequestPath}). Attempting to process the migrations request.");
private static readonly Action<ILogger, string, Exception> _applyingMigrations = LoggerMessage.Define<string>(
LogLevel.Debug,
new EventId(5, "ApplyingMigrations"),
"Request is valid, applying migrations for context '{ContextTypeName}'");
private static readonly Action<ILogger, string, Exception> _migrationsApplied = LoggerMessage.Define<string>(
LogLevel.Debug,
new EventId(6, "MigrationsApplied"),
"Migrations successfully applied for context '{ContextTypeName}'.");
private static readonly Action<ILogger, string, Exception> _migrationsEndPointMiddlewareException = LoggerMessage.Define<string>(
LogLevel.Error,
new EventId(7, "MigrationsEndPointException"),
"An error occurred while applying the migrations for '{ContextTypeName}'. See InnerException for details:");
// DatabaseErrorPageMiddleware
private static readonly Action<ILogger, Type, Exception> _attemptingToMatchException = LoggerMessage.Define<Type>(
LogLevel.Debug,
new EventId(1, "AttemptingToMatchException"),
"{ExceptionType} occurred, checking if Entity Framework recorded this exception as resulting from a failed database operation.");
private static readonly Action<ILogger, Exception> _noRecordedException = LoggerMessage.Define(
LogLevel.Debug,
new EventId(2, "NoRecordedException"),
"Entity Framework did not record any exceptions due to failed database operations. This means the current exception is not a failed Entity Framework database operation, or the current exception occurred from a DbContext that was not obtained from request services.");
private static readonly Action<ILogger, Exception> _noMatch = LoggerMessage.Define(
LogLevel.Debug,
new EventId(3, "NoMatchFound"),
"The current exception (and its inner exceptions) do not match the last exception Entity Framework recorded due to a failed database operation. This means the database operation exception was handled and another exception occurred later in the request.");
private static readonly Action<ILogger, Exception> _matched = LoggerMessage.Define(
LogLevel.Debug,
new EventId(4, "MatchFound"),
"Entity Framework recorded that the current exception was due to a failed database operation. Attempting to show database error page.");
private static readonly Action<ILogger, string, Exception> _contextNotRegisteredDatabaseErrorPageMiddleware = LoggerMessage.Define<string>(
LogLevel.Error,
new EventId(5, "ContextNotRegistered"),
"The context type '{ContextTypeName}' was not found in services. This usually means the context was not registered in services during startup. You probably want to call AddScoped<>() inside the UseServices(...) call in your application startup code. Skipping display of the database error page.");
private static readonly Action<ILogger, Exception> _notRelationalDatabase = LoggerMessage.Define(
LogLevel.Debug,
new EventId(6, "NotRelationalDatabase"),
"The target data store is not a relational database. Skipping the database error page.");
private static readonly Action<ILogger, Exception> _databaseErrorPageMiddlewareException = LoggerMessage.Define(
LogLevel.Error,
new EventId(7, "DatabaseErrorPageException"),
"An exception occurred while calculating the database error page content. Skipping display of the database error page.");
public static void NoContextType(this ILogger logger)
{
_noContextType(logger, null);
}
public static void ContextNotRegistered(this ILogger logger, string contextTypeName)
{
_contextNotRegistered(logger, contextTypeName, null);
}
public static void RequestPathMatched(this ILogger logger, string requestPath)
{
_requestPathMatched(logger, requestPath, null);
}
public static void ApplyingMigrations(this ILogger logger, string contextTypeName)
{
_applyingMigrations(logger, contextTypeName, null);
}
public static void MigrationsApplied(this ILogger logger, string contextTypeName)
{
_migrationsApplied(logger, contextTypeName, null);
}
public static void MigrationsEndPointMiddlewareException(this ILogger logger, string context, Exception exception)
{
_migrationsEndPointMiddlewareException(logger, context, exception);
}
public static void AttemptingToMatchException(this ILogger logger, Type exceptionType)
{
_attemptingToMatchException(logger, exceptionType, null);
}
public static void NoRecordedException(this ILogger logger)
{
_noRecordedException(logger, null);
}
public static void NoMatch(this ILogger logger)
{
_noMatch(logger, null);
}
public static void Matched(this ILogger logger)
{
_matched(logger, null);
}
public static void NotRelationalDatabase(this ILogger logger)
{
_notRelationalDatabase(logger, null);
}
public static void ContextNotRegisteredDatabaseErrorPageMiddleware(this ILogger logger, string contextTypeName)
{
_contextNotRegisteredDatabaseErrorPageMiddleware(logger, contextTypeName, null);
}
public static void DatabaseErrorPageMiddlewareException(this ILogger logger, Exception exception)
{
_databaseErrorPageMiddlewareException(logger, exception);
}
}
}
| 51.479167 | 309 | 0.699312 | [
"Apache-2.0"
] | 4samitim/aspnetcore | src/Middleware/Diagnostics.EntityFrameworkCore/src/DiagnosticsEntityFrameworkCoreLoggerExtensions.cs | 7,413 | C# |
using Nethereum.LogProcessing.Dynamic.Configuration;
using System.Threading.Tasks;
namespace Nethereum.LogProcessing.Dynamic.Handling
{
public interface IEventHandlerConfigurationFactory
{
Task<EventSubscriptionStateDto> GetEventSubscriptionStateAsync(long eventSubscriptionId);
Task SaveAsync(EventSubscriptionStateDto state);
}
}
| 27.923077 | 97 | 0.801653 | [
"MIT"
] | Dave-Whiffin/Nethereum.BlockchainProcessing | src/Nethereum.LogProcessing.Dynamic/Handling/IEventHandlerConfigurationFactory.cs | 365 | C# |
using General.Entities.GeneralModels;
namespace General.Services.General.EntityServices
{
public interface ICategoryService
{
Category GetSingle(object id);
void Add(Category category);
}
}
| 18.416667 | 49 | 0.710407 | [
"MIT"
] | zddblog/GeneralSysManagement | General.Services/General.EntityServices/ICategoryService.cs | 223 | C# |
using System;
using System.Linq;
using System.Reflection;
using Tizen.NUI;
namespace Tizen.NUI.Binding
{
// [Xaml.ProvideCompiled("Tizen.NUI.XamlC.ColorTypeConverter")]
[Xaml.TypeConversion(typeof(Color))]
internal class ColorTypeConverter : TypeConverter
{
// Supported inputs
// HEX #rgb, #argb, #rrggbb, #aarrggbb
// float array 0.5,0.5,0.5,0.5
// Predefined color case insensitive
public override object ConvertFromInvariantString(string value)
{
if (value != null)
{
value = value.Trim();
if (value.StartsWith("#", StringComparison.Ordinal))
{
return FromHex(value);
}
string[] parts = value.Split(',');
if (parts.Length == 1) //like Red or Color.Red
{
parts = value.Split('.');
if (parts.Length == 1 || (parts.Length == 2 && parts[0] == "Color"))
{
string color = parts[parts.Length - 1];
switch (color)
{
case "Black": return Color.Black;
case "White": return Color.White;
case "Red": return Color.Red;
case "Green": return Color.Green;
case "Blue": return Color.Blue;
case "Yellow": return Color.Yellow;
case "Magenta": return Color.Magenta;
case "Cyan": return Color.Cyan;
case "Transparent": return Color.Transparent;
}
}
}
else if (parts.Length == 4) //like 0.5,0.5,0.5,0.5
{
return new Color(float.Parse(parts[0].Trim()), float.Parse(parts[1].Trim()), float.Parse(parts[2].Trim()), float.Parse(parts[3].Trim()));
}
}
throw new InvalidOperationException($"Cannot convert \"{value}\" into {typeof(Color)}");
}
static uint ToHex(char c)
{
ushort x = (ushort)c;
if (x >= '0' && x <= '9')
return (uint)(x - '0');
x |= 0x20;
if (x >= 'a' && x <= 'f')
return (uint)(x - 'a' + 10);
return 0;
}
static uint ToHexD(char c)
{
var j = ToHex(c);
return (j << 4) | j;
}
public static Color FromRgba(int r, int g, int b, int a)
{
float red = (float)r / 255;
float green = (float)g / 255;
float blue = (float)b / 255;
float alpha = (float)a / 255;
return new Color(red, green, blue, alpha);
}
public static Color FromRgb(int r, int g, int b)
{
return FromRgba(r, g, b, 255);
}
static Color FromHex(string hex)
{
// Undefined
if (hex.Length < 3)
return Color.Black;
int idx = (hex[0] == '#') ? 1 : 0;
switch (hex.Length - idx)
{
case 3: //#rgb => ffrrggbb
var t1 = ToHexD(hex[idx++]);
var t2 = ToHexD(hex[idx++]);
var t3 = ToHexD(hex[idx]);
return FromRgb((int)t1, (int)t2, (int)t3);
case 4: //#argb => aarrggbb
var f1 = ToHexD(hex[idx++]);
var f2 = ToHexD(hex[idx++]);
var f3 = ToHexD(hex[idx++]);
var f4 = ToHexD(hex[idx]);
return FromRgba((int)f2, (int)f3, (int)f4, (int)f1);
case 6: //#rrggbb => ffrrggbb
return FromRgb((int)(ToHex(hex[idx++]) << 4 | ToHex(hex[idx++])),
(int)(ToHex(hex[idx++]) << 4 | ToHex(hex[idx++])),
(int)(ToHex(hex[idx++]) << 4 | ToHex(hex[idx])));
case 8: //#aarrggbb
var a1 = ToHex(hex[idx++]) << 4 | ToHex(hex[idx++]);
return FromRgba((int)(ToHex(hex[idx++]) << 4 | ToHex(hex[idx++])),
(int)(ToHex(hex[idx++]) << 4 | ToHex(hex[idx++])),
(int)(ToHex(hex[idx++]) << 4 | ToHex(hex[idx])),
(int)a1);
default: //everything else will result in unexpected results
return Color.Black;
}
}
}
}
| 36 | 157 | 0.416453 | [
"Apache-2.0"
] | EwoutH/TizenFX | src/Tizen.NUI/src/internal/XamlBinding/ColorTypeConverter.cs | 4,680 | C# |
/*
* Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
namespace TencentCloud.Ticm.V20181127.Models
{
using Newtonsoft.Json;
using System.Collections.Generic;
using TencentCloud.Common;
public class VodPoliticalAsrReviewResult : AbstractModel
{
/// <summary>
/// 任务状态,有 PROCESSING,SUCCESS 和 FAIL 三种。
/// </summary>
[JsonProperty("Status")]
public string Status{ get; set; }
/// <summary>
/// 错误码,0:成功,其他值:失败。
/// 注意:此字段可能返回 null,表示取不到有效值。
/// </summary>
[JsonProperty("Code")]
public long? Code{ get; set; }
/// <summary>
/// 错误信息。
/// 注意:此字段可能返回 null,表示取不到有效值。
/// </summary>
[JsonProperty("Msg")]
public string Msg{ get; set; }
/// <summary>
/// 嫌疑片段审核结果建议,取值范围:
/// pass。
/// review。
/// block。
///
/// Asr 文字涉政、敏感评分,分值为0到100。
/// 注意:此字段可能返回 null,表示取不到有效值。
/// </summary>
[JsonProperty("Confidence")]
public float? Confidence{ get; set; }
/// <summary>
/// Asr 文字涉政、敏感结果建议,取值范围:
/// pass。
/// review。
/// block。
///
/// 注意:此字段可能返回 null,表示取不到有效值。
/// </summary>
[JsonProperty("Suggestion")]
public string Suggestion{ get; set; }
/// <summary>
/// Asr 文字有涉政、敏感嫌疑的视频片段列表。
/// 注意:此字段可能返回 null,表示取不到有效值。
/// </summary>
[JsonProperty("SegmentSet")]
public VodAsrTextSegmentItem[] SegmentSet{ get; set; }
/// <summary>
/// For internal usage only. DO NOT USE IT.
/// </summary>
public override void ToMap(Dictionary<string, string> map, string prefix)
{
this.SetParamSimple(map, prefix + "Status", this.Status);
this.SetParamSimple(map, prefix + "Code", this.Code);
this.SetParamSimple(map, prefix + "Msg", this.Msg);
this.SetParamSimple(map, prefix + "Confidence", this.Confidence);
this.SetParamSimple(map, prefix + "Suggestion", this.Suggestion);
this.SetParamArrayObj(map, prefix + "SegmentSet.", this.SegmentSet);
}
}
}
| 30.44086 | 81 | 0.574002 | [
"Apache-2.0"
] | TencentCloud/tencentcloud-sdk-dotnet | TencentCloud/Ticm/V20181127/Models/VodPoliticalAsrReviewResult.cs | 3,237 | C# |
namespace SoundFingerprinting.Query
{
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using SoundFingerprinting.Configuration;
using SoundFingerprinting.Data;
using SoundFingerprinting.DAO;
using SoundFingerprinting.DAO.Data;
using SoundFingerprinting.LCS;
internal class GroupedQueryResults
{
private readonly IEnumerable<HashedFingerprint> queryFingerprints;
private readonly SortedDictionary<uint, Candidates> matches;
private readonly ConcurrentDictionary<IModelReference, int> similaritySumPerTrack;
public GroupedQueryResults(IEnumerable<HashedFingerprint> queryFingerprints)
{
this.queryFingerprints = queryFingerprints;
matches = new SortedDictionary<uint, Candidates>();
similaritySumPerTrack = new ConcurrentDictionary<IModelReference, int>();
}
public double GetQueryLength(FingerprintConfiguration configuration)
{
return CalculateExactQueryLength(queryFingerprints, configuration);
}
[MethodImpl(MethodImplOptions.Synchronized)]
public void Add(HashedFingerprint hashedFingerprint, SubFingerprintData subFingerprintData, int hammingSimilarity)
{
similaritySumPerTrack.AddOrUpdate(subFingerprintData.TrackReference, hammingSimilarity, (key, oldHamming) => oldHamming + hammingSimilarity);
var matchedWith = new MatchedWith(hashedFingerprint.StartsAt, subFingerprintData.SequenceAt, hammingSimilarity);
if (!matches.TryGetValue(hashedFingerprint.SequenceNumber, out var matched))
{
matches.Add(hashedFingerprint.SequenceNumber, new Candidates(subFingerprintData.TrackReference, matchedWith));
}
else
{
matched.AddOrUpdateNewMatch(subFingerprintData.TrackReference, matchedWith);
}
}
public bool ContainsMatches
{
get
{
return similaritySumPerTrack.Any();
}
}
public int SubFingerprintsCount
{
get
{
return matches.Values.Select(candidates => candidates.Count).Sum();
}
}
public int TracksCount
{
get
{
return similaritySumPerTrack.Count;
}
}
public IEnumerable<IModelReference> GetTopTracksByHammingSimilarity(int count)
{
var sorted = from entry in similaritySumPerTrack orderby entry.Value descending select entry;
int c = 0;
foreach (var entry in sorted)
{
yield return entry.Key;
c++;
if (c >= count)
break;
}
}
public int GetHammingSimilaritySumForTrack(IModelReference trackReference)
{
if (similaritySumPerTrack.TryGetValue(trackReference, out int sum))
{
return sum;
}
return 0;
}
public MatchedWith GetBestMatchForTrack(IModelReference trackReference)
{
return GetMatchesForTrackOrderedByQueryAt(trackReference).OrderByDescending(matchedWith => matchedWith.HammingSimilarity).FirstOrDefault();
}
public IEnumerable<MatchedWith> GetMatchesForTrackOrderedByQueryAt(IModelReference trackReference)
{
foreach(var valuePair in matches)
{
if (valuePair.Value.TryGetMatchesForTrack(trackReference, out var matchedWith))
{
yield return matchedWith;
}
}
}
private static double CalculateExactQueryLength(IEnumerable<HashedFingerprint> hashedFingerprints, FingerprintConfiguration fingerprintConfiguration)
{
double startsAt = double.MaxValue, endsAt = double.MinValue;
foreach (var hashedFingerprint in hashedFingerprints)
{
startsAt = System.Math.Min(startsAt, hashedFingerprint.StartsAt);
endsAt = System.Math.Max(endsAt, hashedFingerprint.StartsAt);
}
return SubFingerprintsToSeconds.AdjustLengthToSeconds(endsAt, startsAt, fingerprintConfiguration.FingerprintLengthInSeconds);
}
}
} | 36.639344 | 157 | 0.635794 | [
"MIT"
] | JunkiEDM/FindSimilarCore | FindSimilarServices/Soundfingerprinting/Query/GroupedQueryResults.cs | 4,472 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the connect-2017-08-08.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.Connect.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.Connect.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for SecurityProfileSummary Object
/// </summary>
public class SecurityProfileSummaryUnmarshaller : IUnmarshaller<SecurityProfileSummary, XmlUnmarshallerContext>, IUnmarshaller<SecurityProfileSummary, JsonUnmarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
SecurityProfileSummary IUnmarshaller<SecurityProfileSummary, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context)
{
throw new NotImplementedException();
}
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public SecurityProfileSummary Unmarshall(JsonUnmarshallerContext context)
{
context.Read();
if (context.CurrentTokenType == JsonToken.Null)
return null;
SecurityProfileSummary unmarshalledObject = new SecurityProfileSummary();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("Arn", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.Arn = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("Id", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.Id = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("Name", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.Name = unmarshaller.Unmarshall(context);
continue;
}
}
return unmarshalledObject;
}
private static SecurityProfileSummaryUnmarshaller _instance = new SecurityProfileSummaryUnmarshaller();
/// <summary>
/// Gets the singleton.
/// </summary>
public static SecurityProfileSummaryUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 35.663462 | 179 | 0.625506 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/Connect/Generated/Model/Internal/MarshallTransformations/SecurityProfileSummaryUnmarshaller.cs | 3,709 | 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.Collections.Generic;
using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Http;
using Aliyun.Acs.Core.Transform;
using Aliyun.Acs.Core.Utils;
using Aliyun.Acs.CloudPhoto.Transform;
using Aliyun.Acs.CloudPhoto.Transform.V20170711;
namespace Aliyun.Acs.CloudPhoto.Model.V20170711
{
public class DeleteEventRequest : RpcAcsRequest<DeleteEventResponse>
{
public DeleteEventRequest()
: base("CloudPhoto", "2017-07-11", "DeleteEvent", "cloudphoto", "openAPI")
{
Protocol = ProtocolType.HTTPS;
}
private long? eventId;
private string libraryId;
private string storeName;
public long? EventId
{
get
{
return eventId;
}
set
{
eventId = value;
DictionaryUtil.Add(QueryParameters, "EventId", value.ToString());
}
}
public string LibraryId
{
get
{
return libraryId;
}
set
{
libraryId = value;
DictionaryUtil.Add(QueryParameters, "LibraryId", value);
}
}
public string StoreName
{
get
{
return storeName;
}
set
{
storeName = value;
DictionaryUtil.Add(QueryParameters, "StoreName", value);
}
}
public override bool CheckShowJsonItemName()
{
return false;
}
public override DeleteEventResponse GetResponse(UnmarshallerContext unmarshallerContext)
{
return DeleteEventResponseUnmarshaller.Unmarshall(unmarshallerContext);
}
}
}
| 24.478723 | 96 | 0.681008 | [
"Apache-2.0"
] | AxiosCros/aliyun-openapi-net-sdk | aliyun-net-sdk-cloudphoto/CloudPhoto/Model/V20170711/DeleteEventRequest.cs | 2,301 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNextGen.BotService.V20171201.Inputs
{
/// <summary>
/// Microsoft Teams channel definition
/// </summary>
public sealed class MsTeamsChannelArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The channel name
/// </summary>
[Input("channelName", required: true)]
public Input<string> ChannelName { get; set; } = null!;
/// <summary>
/// The set of properties specific to Microsoft Teams channel resource
/// </summary>
[Input("properties")]
public Input<Inputs.MsTeamsChannelPropertiesArgs>? Properties { get; set; }
public MsTeamsChannelArgs()
{
}
}
}
| 28.571429 | 83 | 0.64 | [
"Apache-2.0"
] | test-wiz-sec/pulumi-azure-nextgen | sdk/dotnet/BotService/V20171201/Inputs/MsTeamsChannelArgs.cs | 1,000 | C# |
namespace GMap.NET.Projections
{
using System;
/// <summary>
/// The Mercator projection
/// PROJCS["World_Mercator",GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["Degree",0.017453292519943295]],PROJECTION["Mercator"],PARAMETER["False_Easting",0],PARAMETER["False_Northing",0],PARAMETER["Central_Meridian",0],PARAMETER["standard_parallel_1",0],UNIT["Meter",1]]
/// </summary>
public class MercatorProjection : PureProjection
{
public static readonly MercatorProjection Instance = new MercatorProjection();
static readonly double MinLatitude = -85.05112878;
static readonly double MaxLatitude = 85.05112878;
static readonly double MinLongitude = -180;
static readonly double MaxLongitude = 180;
public override RectLatLng Bounds
{
get
{
return RectLatLng.FromLTRB(MinLongitude, MaxLatitude, MaxLongitude, MinLatitude);
}
}
readonly GSize tileSize = new GSize(256, 256);
public override GSize TileSize
{
get
{
return tileSize;
}
}
public override double Axis
{
get
{
return 6378137;
}
}
public override double Flattening
{
get
{
return (1.0 / 298.257223563);
}
}
public override GPoint FromLatLngToPixel(double lat, double lng, int zoom)
{
GPoint ret = GPoint.Empty;
lat = Clip(lat, MinLatitude, MaxLatitude);
lng = Clip(lng, MinLongitude, MaxLongitude);
double x = (lng + 180) / 360;
double sinLatitude = Math.Sin(lat * Math.PI / 180);
double y = 0.5 - Math.Log((1 + sinLatitude) / (1 - sinLatitude)) / (4 * Math.PI);
GSize s = GetTileMatrixSizePixel(zoom);
long mapSizeX = s.Width;
long mapSizeY = s.Height;
ret.X = (long)Clip(x * mapSizeX + 0.5, 0, mapSizeX - 1);
ret.Y = (long)Clip(y * mapSizeY + 0.5, 0, mapSizeY - 1);
return ret;
}
public override PointLatLng FromPixelToLatLng(long x, long y, int zoom)
{
PointLatLng ret = PointLatLng.Empty;
GSize s = GetTileMatrixSizePixel(zoom);
double mapSizeX = s.Width;
double mapSizeY = s.Height;
double xx = (Clip(x, 0, mapSizeX - 1) / mapSizeX) - 0.5;
double yy = 0.5 - (Clip(y, 0, mapSizeY - 1) / mapSizeY);
ret.Lat = 90 - 360 * Math.Atan(Math.Exp(-yy * 2 * Math.PI)) / Math.PI;
ret.Lng = 360 * xx;
return ret;
}
public override GSize GetTileMatrixMinXY(int zoom)
{
return new GSize(0, 0);
}
public override GSize GetTileMatrixMaxXY(int zoom)
{
long xy = (1 << zoom);
return new GSize(xy - 1, xy - 1);
}
}
}
| 30.5 | 341 | 0.542591 | [
"MIT"
] | Hogan2/myGMap.Net | GMap.Net/GMap.NET.Core/GMap.NET.Projections/MercatorProjection.cs | 3,113 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Automation;
namespace Microsoft.VisualStudio.IntegrationTest.Utilities
{
public static class DialogHelpers
{
/// <summary>
/// Returns an <see cref="AutomationElement"/> representing the open dialog with automation ID
/// <paramref name="dialogAutomationId"/>.
/// Throws an <see cref="InvalidOperationException"/> if an open dialog with that name cannot be
/// found.
/// </summary>
public static AutomationElement GetOpenDialogById(int visualStudioHWnd, string dialogAutomationId)
{
var dialogAutomationElement = FindDialogByAutomationId(visualStudioHWnd, dialogAutomationId, isOpen: true);
if (dialogAutomationElement == null)
{
throw new InvalidOperationException($"Expected the {dialogAutomationId} dialog to be open, but it is not.");
}
return dialogAutomationElement;
}
public static AutomationElement FindDialogByAutomationId(int visualStudioHWnd, string dialogAutomationId, bool isOpen)
{
return Retry(
() => FindDialogWorker(visualStudioHWnd, dialogAutomationId),
stoppingCondition: automationElement => isOpen ? automationElement != null : automationElement == null,
delay: TimeSpan.FromMilliseconds(250));
}
/// <summary>
/// Used to find legacy dialogs that don't have an AutomationId
/// </summary>
public static AutomationElement FindDialogByName(int visualStudioHWnd, string dialogName, bool isOpen)
{
return Retry(
() => FindDialogByNameWorker(visualStudioHWnd, dialogName),
stoppingCondition: automationElement => isOpen ? automationElement != null : automationElement == null,
delay: TimeSpan.FromMilliseconds(250));
}
/// <summary>
/// Selects a specific item in a combo box.
/// Note that combo box is found using its Automation ID, but the item is identified by name.
/// </summary>
public static void SelectComboBoxItem(int visualStudioHWnd, string dialogAutomationName, string comboBoxAutomationName, string itemText)
{
var dialogAutomationElement = GetOpenDialogById(visualStudioHWnd, dialogAutomationName);
var comboBoxAutomationElement = dialogAutomationElement.FindDescendantByAutomationId(comboBoxAutomationName);
comboBoxAutomationElement.Expand();
var comboBoxItemAutomationElement = comboBoxAutomationElement.FindDescendantByName(itemText);
comboBoxItemAutomationElement.Select();
comboBoxAutomationElement.Collapse();
}
/// <summary>
/// Selects a specific radio button from a dialog found by Id.
/// </summary>
public static void SelectRadioButton(int visualStudioHWnd, string dialogAutomationName, string radioButtonAutomationName)
{
var dialogAutomationElement = GetOpenDialogById(visualStudioHWnd, dialogAutomationName);
var radioButton = dialogAutomationElement.FindDescendantByAutomationId(radioButtonAutomationName);
radioButton.Select();
}
/// <summary>
/// Sets the value of the specified element in the dialog.
/// Used for setting the values of things like combo boxes and text fields.
/// </summary>
public static void SetElementValue(int visualStudioHWnd, string dialogAutomationId, string elementAutomationId, string value)
{
var dialogAutomationElement = GetOpenDialogById(visualStudioHWnd, dialogAutomationId);
var control = dialogAutomationElement.FindDescendantByAutomationId(elementAutomationId);
control.SetValue(value);
}
/// <summary>
/// Presses the specified button.
/// The button is identified using its automation ID; see <see cref="PressButtonWithName(int, string, string)"/>
/// for the equivalent method that finds the button by name.
/// </summary>
public static void PressButton(int visualStudioHWnd, string dialogAutomationId, string buttonAutomationId)
{
var dialogAutomationElement = GetOpenDialogById(visualStudioHWnd, dialogAutomationId);
var buttonAutomationElement = dialogAutomationElement.FindDescendantByAutomationId(buttonAutomationId);
buttonAutomationElement.Invoke();
}
/// <summary>
/// Presses the specified button.
/// The button is identified using its name; see <see cref="PressButton(int, string, string)"/>
/// for the equivalent methods that finds the button by automation ID.
/// </summary>
public static void PressButtonWithName(int visualStudioHWnd, string dialogAutomationId, string buttonName)
{
var dialogAutomationElement = GetOpenDialogById(visualStudioHWnd, dialogAutomationId);
var buttonAutomationElement = dialogAutomationElement.FindDescendantByName(buttonName);
buttonAutomationElement.Invoke();
}
/// <summary>
/// Presses the specified button from a legacy dialog that has no AutomationId.
/// The button is identified using its name; see <see cref="PressButton(int, string, string)"/>
/// for the equivalent methods that finds the button by automation ID.
/// </summary>
public static void PressButtonWithNameFromDialogWithName(int visualStudioHWnd, string dialogName, string buttonName)
{
var dialogAutomationElement = FindDialogByName(visualStudioHWnd, dialogName, isOpen: true);
var buttonAutomationElement = dialogAutomationElement.FindDescendantByName(buttonName);
buttonAutomationElement.Invoke();
}
private static AutomationElement FindDialogWorker(int visualStudioHWnd, string dialogAutomationName)
=> FindDialogByPropertyWorker(visualStudioHWnd, dialogAutomationName, AutomationElement.AutomationIdProperty);
private static AutomationElement FindDialogByNameWorker(int visualStudioHWnd, string dialogName)
=> FindDialogByPropertyWorker(visualStudioHWnd, dialogName, AutomationElement.NameProperty);
private static AutomationElement FindDialogByPropertyWorker(
int visualStudioHWnd,
string propertyValue,
AutomationProperty nameProperty)
{
var vsAutomationElement = AutomationElement.FromHandle(new IntPtr(visualStudioHWnd));
Condition elementCondition = new AndCondition(
new PropertyCondition(nameProperty, propertyValue),
new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Window));
return vsAutomationElement.FindFirst(TreeScope.Descendants, elementCondition);
}
private static T Retry<T>(Func<T> action, Func<T, bool> stoppingCondition, TimeSpan delay)
{
DateTime beginTime = DateTime.UtcNow;
T retval = default(T);
do
{
try
{
retval = action();
}
catch (COMException)
{
// Devenv can throw COMExceptions if it's busy when we make DTE calls.
Thread.Sleep(delay);
continue;
}
if (stoppingCondition(retval))
{
return retval;
}
else
{
Thread.Sleep(delay);
}
}
while (true);
}
}
}
| 44.899441 | 161 | 0.655344 | [
"Apache-2.0"
] | ElanHasson/roslyn | src/VisualStudio/IntegrationTest/TestUtilities/DialogHelpers.cs | 8,039 | C# |
namespace Alex.Blocks.Minecraft
{
public class TripwireHook : Block
{
public TripwireHook() : base()
{
Solid = false;
Transparent = true;
}
}
}
| 14.166667 | 35 | 0.605882 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | codingwatching/Alex | src/Alex/Blocks/Minecraft/TripwireHook.cs | 170 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class PauseMenu : MonoBehaviour
{
public static bool GameIsPaused;
public GameObject pauseMenuUI;
string[] Pause_array = new string[] { "Pausa", "Pause" };
string[] Continue_array = new string[] { "Continuar", "Continue" };
string[] Exit_array = new string[] { "Salir", "Exit" };
[SerializeField] private Text text_pause;
[SerializeField] private Text text_continue;
[SerializeField] private Text text_exit;
private void Start()
{
text_pause.text = Pause_array[PlayerPrefs.GetInt("Idioma", 0)];
text_continue.text = Continue_array[PlayerPrefs.GetInt("Idioma", 0)];
text_exit.text = Exit_array[PlayerPrefs.GetInt("Idioma", 0)];
GameIsPaused = false;
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Escape))
{
if (GameIsPaused)
{
Resume();
}
else
{
Pause();
}
}
}
public void Resume()
{
pauseMenuUI.SetActive(false);
Time.timeScale = 1f;
GameIsPaused = false;
}
public void Pause()
{
pauseMenuUI.SetActive(true);
Time.timeScale = 0f;
GameIsPaused = true;
}
public void QuitLevel()
{
pauseMenuUI.SetActive(false);
Time.timeScale = 1f;
GameIsPaused = false;
GameObject.Find("Musica").GetComponent<AudioSource>().Play();
//Debug.Log("Quitting level...");
SceneManager.LoadScene("selector_nivel");
}
}
| 24.941176 | 77 | 0.590802 | [
"Apache-2.0"
] | GlassBeardTeam/Puppet | Pappet/Assets/Scripts/Interface/PauseMenu.cs | 1,698 | C# |
// <auto-generated />
using System;
using GovUk.Education.SearchAndCompare.Api.DatabaseAccess;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
namespace SearchAndCompare.Migrations
{
[DbContext(typeof(CourseDbContext))]
[Migration("20190924102929_AddAdditionalSubjects")]
partial class AddAdditionalSubjects
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.SerialColumn)
.HasAnnotation("ProductVersion", "2.2.6-servicing-10079")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
modelBuilder.Entity("GovUk.Education.SearchAndCompare.Domain.Models.Campus", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("CampusCode");
b.Property<int?>("CourseId");
b.Property<int?>("LocationId");
b.Property<string>("Name");
b.Property<string>("VacStatus");
b.HasKey("Id");
b.HasIndex("CourseId");
b.HasIndex("LocationId");
b.ToTable("campus");
});
modelBuilder.Entity("GovUk.Education.SearchAndCompare.Domain.Models.Contact", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Address");
b.Property<string>("Email");
b.Property<string>("Fax");
b.Property<string>("Phone");
b.Property<string>("Website");
b.HasKey("Id");
b.ToTable("contact");
});
modelBuilder.Entity("GovUk.Education.SearchAndCompare.Domain.Models.Course", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int?>("AccreditingProviderId");
b.Property<int>("AgeRange");
b.Property<DateTime?>("ApplicationsAcceptedFrom");
b.Property<int?>("ContactDetailsId");
b.Property<double?>("Distance");
b.Property<string>("DistanceAddress");
b.Property<string>("Duration");
b.Property<int>("FullTime");
b.Property<bool>("HasVacancies");
b.Property<int>("IncludesPgce");
b.Property<bool>("IsSalaried");
b.Property<bool>("IsSen");
b.Property<string>("Mod");
b.Property<string>("Name");
b.Property<int>("PartTime");
b.Property<string>("ProgrammeCode");
b.Property<string>("ProviderCodeName");
b.Property<int>("ProviderId");
b.Property<int?>("ProviderLocationId");
b.Property<int>("RouteId");
b.Property<DateTime?>("StartDate");
b.HasKey("Id");
b.HasIndex("AccreditingProviderId");
b.HasIndex("ContactDetailsId")
.IsUnique();
b.HasIndex("ProviderId");
b.HasIndex("ProviderLocationId");
b.HasIndex("RouteId");
b.ToTable("course");
});
modelBuilder.Entity("GovUk.Education.SearchAndCompare.Domain.Models.CourseDescriptionSection", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int>("CourseId");
b.Property<string>("Name");
b.Property<int>("Ordinal");
b.Property<string>("Text");
b.HasKey("Id");
b.HasIndex("CourseId");
b.ToTable("course-description-section");
});
modelBuilder.Entity("GovUk.Education.SearchAndCompare.Domain.Models.DefaultCourseDescriptionSection", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int>("Name");
b.HasKey("Id");
b.ToTable("default-course-description-section");
});
modelBuilder.Entity("GovUk.Education.SearchAndCompare.Domain.Models.FeeCaps", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int>("EndYear");
b.Property<long>("EuFees");
b.Property<long>("InternationalFees");
b.Property<int>("StartYear");
b.Property<long>("UkFees");
b.HasKey("Id");
b.ToTable("feecaps");
});
modelBuilder.Entity("GovUk.Education.SearchAndCompare.Domain.Models.Joins.CourseSubject", b =>
{
b.Property<int>("CourseId");
b.Property<int>("SubjectId");
b.HasKey("CourseId", "SubjectId");
b.HasIndex("SubjectId");
b.ToTable("course_subject");
});
modelBuilder.Entity("GovUk.Education.SearchAndCompare.Domain.Models.Location", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Address");
b.Property<string>("FormattedAddress");
b.Property<string>("GeoAddress");
b.Property<DateTime>("LastGeocodedUtc");
b.Property<double?>("Latitude");
b.Property<double?>("Longitude");
b.HasKey("Id");
b.HasIndex("Longitude", "Latitude");
b.ToTable("location");
});
modelBuilder.Entity("GovUk.Education.SearchAndCompare.Domain.Models.Provider", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Name");
b.Property<string>("ProviderCode");
b.HasKey("Id");
b.ToTable("provider");
});
modelBuilder.Entity("GovUk.Education.SearchAndCompare.Domain.Models.Route", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<bool>("IsSalaried");
b.Property<string>("Name");
b.HasKey("Id");
b.ToTable("route");
});
modelBuilder.Entity("GovUk.Education.SearchAndCompare.Domain.Models.Subject", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int?>("FundingId");
b.Property<bool>("IsSubjectKnowledgeEnhancementAvailable");
b.Property<string>("Name");
b.Property<int?>("SubjectAreaId");
b.HasKey("Id");
b.HasIndex("FundingId");
b.HasIndex("SubjectAreaId");
b.ToTable("subject");
});
modelBuilder.Entity("GovUk.Education.SearchAndCompare.Domain.Models.SubjectArea", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Name");
b.Property<int>("Ordinal");
b.HasKey("Id");
b.ToTable("subject-area");
});
modelBuilder.Entity("GovUk.Education.SearchAndCompare.Domain.Models.SubjectFunding", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int?>("BursaryFirst");
b.Property<int?>("EarlyCareerPayments");
b.Property<int?>("Scholarship");
b.HasKey("Id");
b.ToTable("subject-funding");
});
modelBuilder.Entity("GovUk.Education.SearchAndCompare.Domain.Models.Campus", b =>
{
b.HasOne("GovUk.Education.SearchAndCompare.Domain.Models.Course", "Course")
.WithMany("Campuses")
.HasForeignKey("CourseId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("GovUk.Education.SearchAndCompare.Domain.Models.Location", "Location")
.WithMany()
.HasForeignKey("LocationId");
});
modelBuilder.Entity("GovUk.Education.SearchAndCompare.Domain.Models.Course", b =>
{
b.HasOne("GovUk.Education.SearchAndCompare.Domain.Models.Provider", "AccreditingProvider")
.WithMany("AccreditedCourses")
.HasForeignKey("AccreditingProviderId");
b.HasOne("GovUk.Education.SearchAndCompare.Domain.Models.Contact", "ContactDetails")
.WithOne("Course")
.HasForeignKey("GovUk.Education.SearchAndCompare.Domain.Models.Course", "ContactDetailsId");
b.HasOne("GovUk.Education.SearchAndCompare.Domain.Models.Provider", "Provider")
.WithMany("Courses")
.HasForeignKey("ProviderId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("GovUk.Education.SearchAndCompare.Domain.Models.Location", "ProviderLocation")
.WithMany()
.HasForeignKey("ProviderLocationId");
b.HasOne("GovUk.Education.SearchAndCompare.Domain.Models.Route", "Route")
.WithMany("Courses")
.HasForeignKey("RouteId")
.OnDelete(DeleteBehavior.Cascade);
b.OwnsOne("GovUk.Education.SearchAndCompare.Domain.Models.Fees", "Fees", b1 =>
{
b1.Property<int>("CourseId");
b1.Property<int>("Eu");
b1.Property<int>("International");
b1.Property<int>("Uk");
b1.ToTable("course");
b1.HasOne("GovUk.Education.SearchAndCompare.Domain.Models.Course")
.WithOne("Fees")
.HasForeignKey("GovUk.Education.SearchAndCompare.Domain.Models.Fees", "CourseId")
.OnDelete(DeleteBehavior.Cascade);
});
b.OwnsOne("GovUk.Education.SearchAndCompare.Domain.Models.Salary", "Salary", b1 =>
{
b1.Property<int>("CourseId");
b1.Property<int?>("Maximum");
b1.Property<int?>("Minimum");
b1.ToTable("course");
b1.HasOne("GovUk.Education.SearchAndCompare.Domain.Models.Course")
.WithOne("Salary")
.HasForeignKey("GovUk.Education.SearchAndCompare.Domain.Models.Salary", "CourseId")
.OnDelete(DeleteBehavior.Cascade);
});
});
modelBuilder.Entity("GovUk.Education.SearchAndCompare.Domain.Models.CourseDescriptionSection", b =>
{
b.HasOne("GovUk.Education.SearchAndCompare.Domain.Models.Course", "Course")
.WithMany("DescriptionSections")
.HasForeignKey("CourseId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("GovUk.Education.SearchAndCompare.Domain.Models.Joins.CourseSubject", b =>
{
b.HasOne("GovUk.Education.SearchAndCompare.Domain.Models.Course", "Course")
.WithMany("CourseSubjects")
.HasForeignKey("CourseId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("GovUk.Education.SearchAndCompare.Domain.Models.Subject", "Subject")
.WithMany("CourseSubjects")
.HasForeignKey("SubjectId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("GovUk.Education.SearchAndCompare.Domain.Models.Subject", b =>
{
b.HasOne("GovUk.Education.SearchAndCompare.Domain.Models.SubjectFunding", "Funding")
.WithMany()
.HasForeignKey("FundingId");
b.HasOne("GovUk.Education.SearchAndCompare.Domain.Models.SubjectArea", "SubjectArea")
.WithMany("Subjects")
.HasForeignKey("SubjectAreaId");
});
#pragma warning restore 612, 618
}
}
}
| 34.371921 | 118 | 0.47818 | [
"MIT"
] | DFE-Digital/search-and-compare-api | src/api/Migrations/20190924102929_AddAdditionalSubjects.Designer.cs | 13,957 | C# |
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Linq;
namespace Framework.DAL
{
/// <summary>
/// base interface of all DataAccessLayerContract, which defines common methods.
/// </summary>
/// <typeparam name="TCollection">The type of the collection of Type T.</typeparam>
/// <typeparam name="T">entity class</typeparam>
/// <typeparam name="TIdentifier">The type of the identifier.</typeparam>
/// <typeparam name="TCollectionMessage">The type of the collection message.</typeparam>
public interface DataAccessLayerContractBase<TCollection, T, TIdentifier, TCollectionMessage>
// where TCollection : IList<T>, new()
// where T : TIdentifier, new()
// where TIdentifier: new()
{
/// <summary>
/// Inserts the specified input.
/// </summary>
/// <param name="input">The input.</param>
TCollectionMessage Insert(T input);
/// <summary>
/// Updates the specified input.
/// </summary>
/// <param name="input">The input.</param>
TCollectionMessage Update(T input);
/// <summary>
/// Deletes the specified input.
/// </summary>
/// <param name="input">The input.</param>
TCollectionMessage Delete(T input);
/// <summary>
/// Deletes the by identifier.
/// </summary>
/// <param name="id">The id.</param>
TCollectionMessage DeleteByIdentifier(TIdentifier id);
/// <summary>
/// Batches the insert.
/// </summary>
/// <param name="input">The input.</param>
TCollectionMessage BatchInsert(TCollection input);
/// <summary>
/// Batches the delete.
/// </summary>
/// <param name="input">The input.</param>
TCollectionMessage BatchDelete(TCollection input);
/// <summary>
/// Batches the update.
/// </summary>
/// <param name="input">The input.</param>
TCollectionMessage BatchUpdate(TCollection input);
// TCollection GetAll();
// int GetCountOfAll();
// T GetByIdentifier(TIdentifier id);
}
}
| 34.984127 | 97 | 0.595735 | [
"MIT"
] | ntierontime/Log4Net | Frameworks/Framework.DAL/DataAccessLayerContractBase.cs | 2,204 | C# |
using SlipeServer.Packets.Enums;
using System;
using System.Collections.Generic;
using System.Numerics;
using System.Text;
namespace SlipeServer.Server.Elements.Events
{
public class VehicleDoorOpenRatioChangedArgs : EventArgs
{
public Vehicle Vehicle { get; set; }
public VehicleDoor Door { get; set; }
public float Ratio { get; set; }
public uint Time { get; }
public VehicleDoorOpenRatioChangedArgs(Vehicle vehicle, VehicleDoor door, float ratio, uint time)
{
this.Vehicle = vehicle;
this.Door = door;
this.Ratio = ratio;
this.Time = time;
}
}
}
| 26.72 | 105 | 0.636228 | [
"MIT"
] | ERAGON007/Slipe-Server | SlipeServer.Server/Elements/Events/VehicleDoorOpenRatioChangedArgs.cs | 670 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Threading;
using System.Security.Cryptography;
using System.Diagnostics;
namespace Renci.SshNet.Common
{
/// <summary>
/// Collection of different extension method specific for Silverlight
/// </summary>
public static partial class Extensions
{
/// <summary>
/// Determines whether [is null or white space] [the specified value].
/// </summary>
/// <param name="value">The value.</param>
/// <returns>
/// <c>true</c> if [is null or white space] [the specified value]; otherwise, <c>false</c>.
/// </returns>
internal static bool IsNullOrWhiteSpace(this string value)
{
if (string.IsNullOrEmpty(value)) return true;
return value.All(char.IsWhiteSpace);
}
/// <summary>
/// Disposes the specified socket.
/// </summary>
/// <param name="socket">The socket.</param>
[DebuggerNonUserCode]
internal static void Dispose(this Socket socket)
{
if (socket == null)
throw new NullReferenceException();
socket.Close();
}
/// <summary>
/// Disposes the specified handle.
/// </summary>
/// <param name="handle">The handle.</param>
[DebuggerNonUserCode]
internal static void Dispose(this WaitHandle handle)
{
if (handle == null)
throw new NullReferenceException();
handle.Close();
}
/// <summary>
/// Disposes the specified algorithm.
/// </summary>
/// <param name="algorithm">The algorithm.</param>
[DebuggerNonUserCode]
internal static void Dispose(this HashAlgorithm algorithm)
{
if (algorithm == null)
throw new NullReferenceException();
algorithm.Clear();
}
}
}
| 29.605634 | 102 | 0.549001 | [
"BSD-3-Clause"
] | matthewvukomanovic/sshnet | Renci.SshClient/Renci.SshNet.Silverlight5/Common/Extensions.SilverlightShared.cs | 2,104 | C# |
using Piglet.Lexer.Configuration;
namespace Piglet.Parser.Configuration
{
/// <summary>
/// Set additional settings for the lexer
/// </summary>
public interface ILexerSettings
{
/// <summary>
/// Set to false if you do not desire a lexer. You will need to supply a lexer manually. Defaults to true
/// </summary>
bool CreateLexer { get; set; }
/// <summary>
/// Should all literals in parsing rules be automatically escaped? Defaults to true
/// </summary>
bool EscapeLiterals { get; set; }
/// <summary>
/// Set the list of regular expressions to ignore. The default is to ignore all kinds of whitespace.
/// </summary>
string[] Ignore { get; set; }
/// <summary>
/// Gets and sets the runtime of the constructed lexer. See the enumeration LexerRuntime for an
/// explanation of the valid values.
/// </summary>
LexerRuntime Runtime { get; set; }
}
} | 33.741935 | 114 | 0.582218 | [
"MIT"
] | Dervall/Piglet | Piglet/Parser/Configuration/ILexerSettings.cs | 1,046 | C# |
using Bridge.Test.NUnit;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace Bridge.ClientTest.Collections.Generic
{
[Category(Constants.MODULE_ICOLLECTION)]
[TestFixture(TestNameFormat = "ReadOnlyCollection - {0}")]
public class ReadOnlyCollectionTests
{
private class C
{
public readonly int i;
public C(int i)
{
this.i = i;
}
public override bool Equals(object o)
{
return o is C && i == ((C)o).i;
}
public override int GetHashCode()
{
return i;
}
}
[Test]
public void TypePropertiesAreCorrect()
{
#if false
Assert.AreEqual("System.Collections.ObjectModel.ReadOnlyCollection`1[[System.Int32, mscorlib]]", typeof(ReadOnlyCollection<int>).FullName, "FullName should be Array");
#endif
Assert.True(typeof(ReadOnlyCollection<int>).IsClass, "IsClass should be true");
object list = new ReadOnlyCollection<int>(new int[0]);
Assert.True(list is ReadOnlyCollection<int>, "is ReadOnlyCollection<int> should be true");
Assert.True(list is IList<int>, "is IList<int> should be true");
Assert.True(list is ICollection<int>, "is ICollection<int> should be true");
Assert.True(list is IEnumerable<int>, "is IEnumerable<int> should be true");
Assert.True(list is IReadOnlyCollection<int>, "is IReadOnlyCollection<int> should be true");
}
[Test]
public void ConstructorWorks()
{
var l = new ReadOnlyCollection<int>(new int[] { 41, 42, 43 });
Assert.AreEqual(3, l.Count);
Assert.AreEqual(41, l[0]);
Assert.AreEqual(42, l[1]);
Assert.AreEqual(43, l[2]);
}
[Test]
public void CountWorks()
{
Assert.AreEqual(0, new ReadOnlyCollection<string>(new string[0]).Count);
Assert.AreEqual(1, new ReadOnlyCollection<string>(new string[1]).Count);
Assert.AreEqual(2, new ReadOnlyCollection<string>(new string[2]).Count);
}
[Test]
public void IndexingWorks()
{
var l = new ReadOnlyCollection<string>(new[] { "x", "y" });
Assert.AreEqual("x", l[0]);
Assert.AreEqual("y", l[1]);
}
[Test]
public void ForeachWorks()
{
string result = "";
foreach (var s in new ReadOnlyCollection<string>(new[] { "x", "y" }))
{
result += s;
}
Assert.AreEqual("xy", result);
}
[Test]
public void GetEnumeratorWorks()
{
var e = new ReadOnlyCollection<string>(new[] { "x", "y" }).GetEnumerator();
Assert.True(e.MoveNext());
Assert.AreEqual("x", e.Current);
Assert.True(e.MoveNext());
Assert.AreEqual("y", e.Current);
Assert.False(e.MoveNext());
}
[Test]
public void ContainsWorks()
{
var l = new ReadOnlyCollection<string>(new[] { "x", "y" });
Assert.True(l.Contains("x"));
Assert.False(l.Contains("z"));
}
[Test]
public void ContainsUsesEqualsMethod()
{
var l = new ReadOnlyCollection<C>(new[] { new C(1), new C(2), new C(3) });
Assert.True(l.Contains(new C(2)));
Assert.False(l.Contains(new C(4)));
}
[Test]
public void CopyToMethodSameBound()
{
var l = new ReadOnlyCollection<string>(new[] { "0", "1", "2" });
var a1 = new string[3];
l.CopyTo(a1, 0);
Assert.AreEqual("0", a1[0], "Element 0");
Assert.AreEqual("1", a1[1], "Element 1");
Assert.AreEqual("2", a1[2], "Element 2");
}
[Test]
public void CopyToMethodOffsetBound()
{
var l = new ReadOnlyCollection<string>(new[] { "0", "1", "2" });
var a2 = new string[5];
l.CopyTo(a2, 1);
Assert.AreEqual(null, a2[0], "Element 0");
Assert.AreEqual("0", a2[1], "Element 1");
Assert.AreEqual("1", a2[2], "Element 2");
Assert.AreEqual("2", a2[3], "Element 3");
Assert.AreEqual(null, a2[4], "Element 4");
}
[Test]
public void CopyToMethodIllegalBound()
{
var l = new ReadOnlyCollection<string>(new[] { "0", "1", "2" });
Assert.Throws<ArgumentNullException>(() => { l.CopyTo(null, 0); }, "null");
var a1 = new string[2];
Assert.Throws<ArgumentException>(() => { l.CopyTo(a1, 0); }, "Short array");
var a2 = new string[3];
Assert.Throws<ArgumentException>(() => { l.CopyTo(a2, 1); }, "Start index 1");
Assert.Throws<ArgumentOutOfRangeException>(() => { l.CopyTo(a2, -1); }, "Negative start index");
Assert.Throws<ArgumentException>(() => { l.CopyTo(a2, 3); }, "Start index 3");
}
[Test]
public void CopyToMethodWhenCastToIListSameBound()
{
IList<string> l = new ReadOnlyCollection<string>(new[] { "0", "1", "2" });
var a1 = new string[3];
l.CopyTo(a1, 0);
Assert.AreEqual("0", a1[0], "Element 0");
Assert.AreEqual("1", a1[1], "Element 1");
Assert.AreEqual("2", a1[2], "Element 2");
}
[Test]
public void CopyToMethodWhenCastToIListOffsetBound()
{
IList<string> l = new ReadOnlyCollection<string>(new[] { "0", "1", "2" });
var a2 = new string[5];
l.CopyTo(a2, 1);
Assert.AreEqual(null, a2[0], "Element 0");
Assert.AreEqual("0", a2[1], "Element 1");
Assert.AreEqual("1", a2[2], "Element 2");
Assert.AreEqual("2", a2[3], "Element 3");
Assert.AreEqual(null, a2[4], "Element 4");
}
[Test]
public void CopyToMethodWhenCastToIListIllegalBound()
{
IList<string> l = new ReadOnlyCollection<string>(new[] { "0", "1", "2" });
Assert.Throws<ArgumentNullException>(() => { l.CopyTo(null, 0); }, "null");
var a1 = new string[2];
Assert.Throws<ArgumentException>(() => { l.CopyTo(a1, 0); }, "Short array");
var a2 = new string[3];
Assert.Throws<ArgumentException>(() => { l.CopyTo(a2, 1); }, "Start index 1");
Assert.Throws<ArgumentOutOfRangeException>(() => { l.CopyTo(a2, -1); }, "Negative start index");
Assert.Throws<ArgumentException>(() => { l.CopyTo(a2, 3); }, "Start index 3");
}
[Test]
public void CopyToMethodWhenCastToICollectionSameBound()
{
ICollection<string> l = new ReadOnlyCollection<string>(new[] { "0", "1", "2" });
var a1 = new string[3];
l.CopyTo(a1, 0);
Assert.AreEqual("0", a1[0], "Element 0");
Assert.AreEqual("1", a1[1], "Element 1");
Assert.AreEqual("2", a1[2], "Element 2");
}
[Test]
public void CopyToMethodWhenCastToICollectionOffsetBound()
{
ICollection<string> l = new ReadOnlyCollection<string>(new[] { "0", "1", "2" });
var a2 = new string[5];
l.CopyTo(a2, 1);
Assert.AreEqual(null, a2[0], "Element 0");
Assert.AreEqual("0", a2[1], "Element 1");
Assert.AreEqual("1", a2[2], "Element 2");
Assert.AreEqual("2", a2[3], "Element 3");
Assert.AreEqual(null, a2[4], "Element 4");
}
[Test]
public void CopyToMethodWhenCastToICollectionIllegalBound()
{
ICollection<string> l = new ReadOnlyCollection<string>(new[] { "0", "1", "2" });
Assert.Throws<ArgumentNullException>(() => { l.CopyTo(null, 0); }, "null");
var a1 = new string[2];
Assert.Throws<ArgumentException>(() => { l.CopyTo(a1, 0); }, "Short array");
var a2 = new string[3];
Assert.Throws<ArgumentException>(() => { l.CopyTo(a2, 1); }, "Start index 1");
Assert.Throws<ArgumentOutOfRangeException>(() => { l.CopyTo(a2, -1); }, "Negative start index");
Assert.Throws<ArgumentException>(() => { l.CopyTo(a2, 3); }, "Start index 3");
}
[Test]
public void IndexOfWorks()
{
Assert.AreEqual(1, new ReadOnlyCollection<string>(new[] { "a", "b", "c", "b" }).IndexOf("b"));
Assert.AreEqual(1, new ReadOnlyCollection<C>(new[] { new C(1), new C(2), new C(3), new C(2) }).IndexOf(new C(2)));
}
[Test]
public void ForeachWhenCastToIEnumerableWorks()
{
IEnumerable<string> list = new ReadOnlyCollection<string>(new[] { "x", "y" });
string result = "";
foreach (var s in list)
{
result += s;
}
Assert.AreEqual("xy", result);
}
[Test]
public void IEnumerableGetEnumeratorWorks()
{
var l = (IEnumerable<string>)new ReadOnlyCollection<string>(new[] { "x", "y" });
var e = l.GetEnumerator();
Assert.True(e.MoveNext());
Assert.AreEqual("x", e.Current);
Assert.True(e.MoveNext());
Assert.AreEqual("y", e.Current);
Assert.False(e.MoveNext());
}
[Test]
public void ICollectionCountWorks()
{
IList<string> l = new ReadOnlyCollection<string>(new[] { "x", "y", "z" });
Assert.AreEqual(3, l.Count);
}
[Test]
public void ICollectionIsReadOnlyWorks()
{
ICollection<string> l = new ReadOnlyCollection<string>(new string[0]);
Assert.True(l.IsReadOnly);
}
[Test]
public void ICollectionContainsWorks()
{
IList<string> l = new ReadOnlyCollection<string>(new[] { "x", "y", "z" });
Assert.True(l.Contains("y"));
Assert.False(l.Contains("a"));
}
[Test]
public void ICollectionContainsUsesEqualsMethod()
{
IList<C> l = new ReadOnlyCollection<C>(new[] { new C(1), new C(2), new C(3) });
Assert.True(l.Contains(new C(2)));
Assert.False(l.Contains(new C(4)));
}
[Test]
public void IListIndexingWorks()
{
IList<string> l = new ReadOnlyCollection<string>(new[] { "x", "y", "z" });
Assert.AreEqual("y", l[1]);
}
[Test]
public void IListIndexOfWorks()
{
IList<string> l = new ReadOnlyCollection<string>(new[] { "x", "y", "z" });
Assert.AreEqual(1, l.IndexOf("y"));
Assert.AreEqual(-1, l.IndexOf("a"));
}
[Test]
public void IListIndexOfUsesEqualsMethod()
{
IList<C> l = new ReadOnlyCollection<C>(new[] { new C(1), new C(2), new C(3) });
Assert.AreEqual(1, l.IndexOf(new C(2)));
Assert.AreEqual(-1, l.IndexOf(new C(4)));
}
[Test]
public void IListIsReadOnlyWorks()
{
IList<string> l = new ReadOnlyCollection<string>(new string[0]);
Assert.True(l.IsReadOnly);
}
[Test]
public void IReadOnlyCollectionCountWorks()
{
IReadOnlyCollection<string> l = new ReadOnlyCollection<string>(new[] { "x", "y", "z" });
Assert.AreEqual(3, l.Count);
}
[Test]
public void IReadOnlyCollectionGetEnumeratorWorks()
{
var l = (IReadOnlyCollection<string>)new ReadOnlyCollection<string>(new[] { "x", "y" });
var e = l.GetEnumerator();
Assert.True(e.MoveNext());
Assert.AreEqual("x", e.Current);
Assert.True(e.MoveNext());
Assert.AreEqual("y", e.Current);
Assert.False(e.MoveNext());
}
[Test]
public void IReadOnlyListIndexingWorks()
{
IReadOnlyList<string> l = new ReadOnlyCollection<string>(new[] { "x", "y", "z" });
Assert.AreEqual("y", l[1]);
}
[Test]
public void IReadOnlyListCountWorks()
{
IReadOnlyList<string> l = new ReadOnlyCollection<string>(new[] { "x", "y", "z" });
Assert.AreEqual(3, l.Count);
}
[Test]
public void IReadOnlyListGetEnumeratorWorks()
{
var l = (IReadOnlyList<string>)new ReadOnlyCollection<string>(new[] { "x", "y" });
var e = l.GetEnumerator();
Assert.True(e.MoveNext());
Assert.AreEqual("x", e.Current);
Assert.True(e.MoveNext());
Assert.AreEqual("y", e.Current);
Assert.False(e.MoveNext());
}
}
}
| 34.468421 | 179 | 0.514735 | [
"Apache-2.0"
] | Cheatoid/CSharp.lua | test/BridgeNetTests/Batch1/src/Collections/ObjectModel/ReadOnlyCollectionTests.cs | 13,098 | C# |
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class EndGameScreen : MonoBehaviour
{
/// <summary>
/// Reference to winner team.
/// </summary>
public static TeamTypes winnerTeam;
/// <summary>
/// Reference to text that will show who won.
/// </summary>
[SerializeField]
Text winnerText;
/// <summary>
/// Shows winner.
/// </summary>
void Start()
{
AudioManager.instance.PlayMenuMusic();
winnerText.text = "Team " + winnerTeam.ToString() + " won the game!";
MultiplayerRoomsManager.instance.Dispose();
}
/// <summary>
/// On Button Click, goes back to main menu.
/// </summary>
public void OnMenuClick()
{
Application.LoadLevel(Scenes.MainMenu.ToString());
}
/// <summary>
/// On Button Click, goes to store.
/// </summary>
public void OnStoreClick()
{
Application.LoadLevel(Scenes.Store.ToString());
}
/// <summary>
/// On Button Click, goes to mode selection.
/// </summary>
public void OnPlayAgainClick()
{
Application.LoadLevel(Scenes.ModeSelect.ToString());
}
} | 22.75 | 77 | 0.598478 | [
"Apache-2.0"
] | Kwell/UNION-OpenSource-MOBA | Unity 5.1 Source Project/Project/Assets/Scripts/Screens/EndGameScreen.cs | 1,185 | C# |
using System;
namespace BasicExamples
{
class Program
{
static void Main(string[] args)
{
//Console.WriteLine("Runnin XOR Example......");
//XORGate.Run();
LogisticRegressionExplained.Run();
}
}
}
| 17.75 | 60 | 0.496479 | [
"Apache-2.0"
] | AnshMittal1811/MxNet.Sharp | examples/BasicExamples/Program.cs | 286 | C# |
// Copyright (c) Pomelo Foundation. All rights reserved.
// Licensed under the MIT. See LICENSE in the project root for license information.
using System;
using System.Linq.Expressions;
using Microsoft.EntityFrameworkCore.Query.Expressions;
//ReSharper disable once CheckNamespace
namespace Microsoft.EntityFrameworkCore.Query.ExpressionTranslators.Internal
{
/// <summary>
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public class MySqlDateTimeNowTranslator : IMemberTranslator
{
/// <summary>
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public virtual Expression Translate(MemberExpression memberExpression)
{
if (memberExpression.Expression == null
&& memberExpression.Member.DeclaringType == typeof(DateTime))
{
switch (memberExpression.Member.Name)
{
case nameof(DateTime.Now):
return new SqlFunctionExpression("CURRENT_TIMESTAMP", memberExpression.Type);
case nameof(DateTime.UtcNow):
return new SqlFunctionExpression("UTC_TIMESTAMP", memberExpression.Type);
}
}
return null;
}
}
}
| 40.666667 | 105 | 0.643127 | [
"MIT"
] | WithLin0510/Pomelo.EntityFrameworkCore.MySql | src/EFCore.MySql/Query/ExpressionTranslators/Internal/MySqlDateTimeNowTranslator.cs | 1,586 | C# |
using SRML;
using SRML.Console;
using Common;
namespace CustomGadgetSites
{
class Main: Mod, IModEntryPoint
{
public static new readonly string id = Mod.id.ToLower();
public virtual void PreLoad()
{
init();
HarmonyPatcher.GetInstance().PatchAll();
SaveLoadUtils.init();
Console.RegisterCommand(new RestoreGadgetSitesCommand());
#if DEBUG
Console.RegisterCommand(new CreateGadgetSiteCommand());
#endif
}
public virtual void Load() {}
public virtual void PostLoad() {}
}
} | 18.107143 | 60 | 0.719921 | [
"MIT"
] | zorgesho/SlimeRancherMods | CustomGadgetSites/main.cs | 509 | C# |
namespace EnergyManagementScheduler.WebJob.Contracts
{
using System;
public class DailyConsumptionData
{
public int Id { get; set; }
public double? AMPS_SYSTEM_AVG { get; set; }
public string Building { get; set; }
public string Breaker_details { get; set; }
public double? Daily_electric_cost { get; set; }
public double? Daily_KWH_System { get; set; }
public double? Monthly_electric_cost { get; set; }
public double? Monthly_KWH_System { get; set; }
public string PowerScout { get; set; }
public double? Temperature { get; set; }
public DateTime? Timestamp { get; set; }
public double? Visibility { get; set; }
public double? KW_System { get; set; }
public string PiServerName { get; set; }
}
}
| 23.361111 | 58 | 0.614744 | [
"Apache-2.0"
] | MobiliyaTechnologies/RESTServer | RestService/EnergyManagementScheduler.WebJob/Contracts/DailyConsumptionData.cs | 843 | C# |
using System;
using System.Diagnostics;
using System.IO;
using System.Timers;
using System.Threading;
namespace Alibaba.F2E.Tianma {
class Node : EventEmitter {
// Process status constants.
enum Status { Idle, Starting, Running, Stopping }
// Standard error buffer.
string error = "";
// Standard output buffer.
string output = "";
// Node process instance.
Process process = null;
// Node process start info.
ProcessStartInfo startInfo;
// Current process status.
Status status;
// Flush timer.
System.Timers.Timer timer;
// Singleton check.
public static bool IsRunning() {
bool result = false;
if (File.Exists(".pid")) {
try {
// Try to find running process by previous saved pid.
Process process = Process.GetProcessById(Convert.ToInt32(File.ReadAllText(".pid")));
if (process.MainModule.ModuleName == "node.exe") {
result = true;
}
} catch (Exception ex) {
// Depress compiling warning.
Exception dummy = ex;
}
}
return result;
}
// Constructor.
public Node(string config) {
timer = new System.Timers.Timer();
timer.Interval = 100;
timer.Elapsed += Flush;
startInfo = new ProcessStartInfo();
startInfo.FileName = FindExec("node.exe");
startInfo.Arguments = "\"" + config + "\"";
startInfo.CreateNoWindow = true;
startInfo.UseShellExecute = false;
startInfo.RedirectStandardError = true;
startInfo.RedirectStandardInput = true;
startInfo.RedirectStandardOutput = true;
SetEV();
AddHandler("start", Start);
AddHandler("stop", Stop);
}
// Restart process.
public void Restart(object sender, EventArgsEx args) {
if (args.Type == "switch") {
startInfo.Arguments = "\"" + args.Message + "\"";
}
if (status == Status.Running) {
// Stop current process and start a new process immediately.
status = Status.Stopping;
process.Exited += Start;
process.Kill();
} else if (status == Status.Idle) {
EmitEvent("start");
}
}
// Start process.
public void Start(object sender, EventArgs args) {
if (status == Status.Idle) {
status = Status.Starting;
process = new Process();
process.StartInfo = startInfo;
process.EnableRaisingEvents = true;
process.ErrorDataReceived += OnError;
process.OutputDataReceived += OnOutput;
process.Exited += OnExit;
process.Start();
process.PriorityClass = ProcessPriorityClass.High;
process.BeginErrorReadLine();
process.BeginOutputReadLine();
// Save current PID.
File.WriteAllText(".pid", String.Format("{0}", process.Id));
status = Status.Running;
}
if (status == Status.Running) {
EmitEvent("started");
}
}
// Stop process.
public void Stop(object sender, EventArgs args) {
if (status == Status.Running) {
status = Status.Stopping;
process.Kill();
} else if (status == Status.Idle) {
EmitEvent("stopped");
}
}
// Get command result synchronously.
string Command(string exec, string arguments) {
Process process = new System.Diagnostics.Process();
process.StartInfo.FileName = FindExec(exec);
process.StartInfo.Arguments = arguments;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.Start();
string output = process.StandardOutput.ReadToEnd().Trim();
process.WaitForExit();
process.Close();
return output;
}
// Find pathname of executable file.
string FindExec(string name) {
string path = Environment.GetEnvironmentVariable("PATH");
foreach (string folder in path.Split(new char[] { ';' })) {
string exec = Path.Combine(folder.Trim(), name);
if (File.Exists(exec)) {
return exec;
}
}
return "";
}
// Flush buffer.
void Flush(object sender, ElapsedEventArgs args) {
if (!timer.Enabled) {
return;
} else if (output.Length > 0) {
EmitEvent("output", output);
output = "";
} else if (error.Length > 0) {
EmitEvent("error", error);
error = "";
}
}
// Setup enviroment variables.
void SetEV() {
Environment.SetEnvironmentVariable("NODE_PATH", Command("tianma.cmd", "libpath"));
}
// Standard error event handler.
void OnError(object sender, DataReceivedEventArgs args) {
if (!String.IsNullOrEmpty(args.Data)) {
timer.Stop();
error += args.Data + "\n";
timer.Start();
}
}
// Exit event handler.
void OnExit(object sender, EventArgs args) {
process.CancelErrorRead();
process.CancelOutputRead();
process.Close();
status = Status.Idle;
EmitEvent("stopped");
}
// Standard output event handler.
void OnOutput(object sender, DataReceivedEventArgs args) {
if (!String.IsNullOrEmpty(args.Data)) {
timer.Stop();
output += args.Data + "\n";
timer.Start();
}
}
}
}
| 23.850242 | 89 | 0.654446 | [
"MIT"
] | gxcsoccer/tianma | daemon/src/Node.cs | 4,937 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SampleLibrary
{
public class Class1
{
}
}
| 12.666667 | 33 | 0.717105 | [
"Apache-2.0"
] | kzu/EasyMerge | EasyMerge.Tests/Content/SampleLibrary/Class1.cs | 154 | C# |
using System.Collections.Generic;
using src.core.figures;
using src.core.rules.ruleList;
namespace src.core.rules
{
public class RulesValidator
{
private List<Rule> _rules = new List<Rule>();
public ChessSide WhoseTurn;
public RulesValidator()
{
_rules.Add(new Castelling());
// _rules.Add(new TakeByPass());
_rules.Add(new Pawn());
_rules.Add(new King());
_rules.Add(new Rook());
_rules.Add(new Knight());
_rules.Add(new Queen());
_rules.Add(new Bishop());
}
public Turn ValidateTurn(Turn turn)
{
turn.TurnValid = ActionsValid(turn);
// check king
var tempBoard = turn.board.Copy();
tempBoard.ApplyTurn(turn);
var attacker = KingUnderAttack(tempBoard);
if (attacker != null)
{
turn.KingAttackedBy = attacker;
turn.TurnValid = false;
}
return turn;
}
private Figure KingUnderAttack(Board board)
{
var enemies = board.GetEnemies(WhoseTurn);
var king = board.GetKing(WhoseTurn);
foreach (var enemy in enemies)
{
Turn possibleLethalTurn = Turn.NoValidate(board, enemy.CurrentPos, king.CurrentPos);
if (ActionsValid(possibleLethalTurn))
{
return enemy;
}
}
return null;
}
private bool ActionsValid(Turn turn)
{
foreach (var rule in _rules)
{
if (rule.CanDoTurn(turn))
{
turn.Actions.AddRange(rule.GetActions(turn));
return true;
}
}
return false;
}
}
} | 26.2 | 100 | 0.475827 | [
"MIT"
] | EvgenL/EvgenChess | Assets/src/core/rules/RulesValidator.cs | 1,967 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace Cosmos.Hardware2.Network.Devices.RTL8139
{
/// <summary>
/// A network Packet used when transferring data over a network.
/// Consists of a body (with the data) and a head (with info about the packet)
/// </summary>
[Obsolete("Use Ethernet2Frame instead.")]
public class Packet
{
private PacketHeader head;
private byte[] body;
public PacketHeader Head { get; private set; }
public Packet(PacketHeader newhead, byte[] data)
{
head = newhead;
body = data;
}
public byte[] PacketBody
{
get
{
return body;
}
//return new byte[10]; //TODO: Redo this completely! Hardcoded to some bogus value now.
}
}
}
| 26.647059 | 100 | 0.549669 | [
"BSD-3-Clause"
] | ERamaM/Cosmos | source/Unused/Cosmos.Hardware/Network/Devices/RTL8139Old/Packet.cs | 908 | C# |
using System;
using System.Collections.Generic;
using System.Reflection;
using Bing.Datas.EntityFramework.Core;
using Microsoft.EntityFrameworkCore;
namespace Bing.Datas.EntityFramework.MySql
{
/// <summary>
/// MySql 工作单元
/// </summary>
public abstract class UnitOfWork : UnitOfWorkBase
{
/// <summary>
/// 初始化一个<see cref="UnitOfWork"/>类型的实例
/// </summary>
/// <param name="options">配置</param>
/// <param name="serviceProvider">服务提供器</param>
protected UnitOfWork(DbContextOptions options, IServiceProvider serviceProvider = null) : base(options, serviceProvider)
{
}
/// <summary>
/// 获取映射实例列表
/// </summary>
/// <param name="assembly">程序集</param>
protected override IEnumerable<Core.IMap> GetMapInstances(Assembly assembly) => Reflection.Reflections.GetInstancesByInterface<IMap>(assembly);
}
}
| 30.933333 | 151 | 0.648707 | [
"MIT"
] | bing-framework/Bing.NetCode | framework/src/Bing.Datas.EntityFramework.MySql/UnitOfWork.cs | 994 | C# |
using System;
using System.Xml.Serialization;
using System.ComponentModel.DataAnnotations;
using BroadWorksConnector.Ocip.Validation;
using System.Collections.Generic;
namespace BroadWorksConnector.Ocip.Models
{
/// <summary>
///
/// </summary>
[Serializable]
[XmlRoot(Namespace = "")]
[Groups(@"[{""__type"":""Sequence:#BroadWorksConnector.Ocip.Validation"",""id"":""3347d430e0d5c93a9ff8dcf0e3b60d6c:719""}]")]
public class SystemVoiceMessagingGroupGetVoicePortalMenusResponse21AnnouncementRecordingMenuKeys
{
private string _acceptRecording;
[XmlElement(ElementName = "acceptRecording", IsNullable = false, Namespace = "")]
[Group(@"3347d430e0d5c93a9ff8dcf0e3b60d6c:719")]
[Length(1)]
[RegularExpression(@"[0-9]|\*|#")]
public string AcceptRecording
{
get => _acceptRecording;
set
{
AcceptRecordingSpecified = true;
_acceptRecording = value;
}
}
[XmlIgnore]
protected bool AcceptRecordingSpecified { get; set; }
private string _rejectRerecord;
[XmlElement(ElementName = "rejectRerecord", IsNullable = false, Namespace = "")]
[Group(@"3347d430e0d5c93a9ff8dcf0e3b60d6c:719")]
[Length(1)]
[RegularExpression(@"[0-9]|\*|#")]
public string RejectRerecord
{
get => _rejectRerecord;
set
{
RejectRerecordSpecified = true;
_rejectRerecord = value;
}
}
[XmlIgnore]
protected bool RejectRerecordSpecified { get; set; }
private string _returnToPreviousMenu;
[XmlElement(ElementName = "returnToPreviousMenu", IsNullable = false, Namespace = "")]
[Group(@"3347d430e0d5c93a9ff8dcf0e3b60d6c:719")]
[Length(1)]
[RegularExpression(@"[0-9]|\*|#")]
public string ReturnToPreviousMenu
{
get => _returnToPreviousMenu;
set
{
ReturnToPreviousMenuSpecified = true;
_returnToPreviousMenu = value;
}
}
[XmlIgnore]
protected bool ReturnToPreviousMenuSpecified { get; set; }
private string _repeatMenu;
[XmlElement(ElementName = "repeatMenu", IsNullable = false, Namespace = "")]
[Optional]
[Group(@"3347d430e0d5c93a9ff8dcf0e3b60d6c:719")]
[Length(1)]
[RegularExpression(@"[0-9]|\*|#")]
public string RepeatMenu
{
get => _repeatMenu;
set
{
RepeatMenuSpecified = true;
_repeatMenu = value;
}
}
[XmlIgnore]
protected bool RepeatMenuSpecified { get; set; }
private string _end;
[XmlElement(ElementName = "end", IsNullable = false, Namespace = "")]
[Group(@"3347d430e0d5c93a9ff8dcf0e3b60d6c:719")]
[MinLength(1)]
[MaxLength(3)]
[RegularExpression(@"([0-9]|\*|#){0,3}")]
public string End
{
get => _end;
set
{
EndSpecified = true;
_end = value;
}
}
[XmlIgnore]
protected bool EndSpecified { get; set; }
}
}
| 28.355932 | 129 | 0.557681 | [
"MIT"
] | JTOne123/broadworks-connector-net | BroadworksConnector/Ocip/Models/SystemVoiceMessagingGroupGetVoicePortalMenusResponse21AnnouncementRecordingMenuKeys.cs | 3,346 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace Microsoft.EntityFrameworkCore.Specification.Tests.TestModels.GearsOfWarModel
{
public class SquadMission
{
public Squad Squad { get; set; }
public int MissionId { get; set; }
public int SquadId { get; set; }
public Mission Mission { get; set; }
}
}
| 31.533333 | 111 | 0.687104 | [
"Apache-2.0"
] | Mattlk13/EntityFramework | src/Microsoft.EntityFrameworkCore.Specification.Tests/TestModels/GearsOfWarModel/SquadMission.cs | 475 | C# |
using UnityEngine;
namespace Widget
{
public class LootAtCameraComponent : MonoBehaviour
{
[SerializeField] private Canvas canvas;
private ICameraService _cameraService;
private void Awake()
{
_cameraService = LocatorService.Instance.Get<ICameraService>();
canvas.worldCamera = _cameraService.MainCamera;
}
private void Update()
{
if (_cameraService?.MainCamera != null)
{
transform.LookAt(_cameraService?.MainCamera.transform);
}
}
}
} | 23.884615 | 75 | 0.561997 | [
"MIT"
] | joaokucera/unity-swordhero | src/Assets/Scripts/Widget/LootAtCameraComponent.cs | 621 | C# |
// ***********************************************************************
// Copyright (c) 2011 Charlie Poole, Rob Prouse
//
// 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.Collections.Generic;
using System.Globalization;
using System.Reflection;
using System.Xml;
using System.IO;
using NUnit.Compatibility;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal;
namespace NUnitLite
{
/// <summary>
/// NUnit2XmlOutputWriter is able to create an XML file representing
/// the result of a test run in NUnit 2.x format.
/// </summary>
public class NUnit2XmlOutputWriter : OutputWriter
{
private XmlWriter xmlWriter;
/// <summary>
/// Write info about a test
/// </summary>
/// <param name="test">The test</param>
/// <param name="writer">A TextWriter</param>
public override void WriteTestFile(ITest test, TextWriter writer)
{
throw new NotImplementedException("Explore test output is not supported by the NUnit2 format.");
}
/// <summary>
/// Writes the result of a test run to a specified TextWriter.
/// </summary>
/// <param name="result">The test result for the run</param>
/// <param name="writer">The TextWriter to which the xml will be written</param>
/// <param name="runSettings"></param>
/// <param name="filter"></param>
public override void WriteResultFile(ITestResult result, TextWriter writer, IDictionary<string, object> runSettings, TestFilter filter)
{
var settings = new XmlWriterSettings { Indent = true };
using (var xmlWriter = XmlWriter.Create(writer, settings))
{
WriteXmlOutput(result, xmlWriter);
}
}
private void WriteXmlOutput(ITestResult result, XmlWriter xmlWriter)
{
this.xmlWriter = xmlWriter;
InitializeXmlFile(result);
WriteResultElement(result);
TerminateXmlFile();
}
private void InitializeXmlFile(ITestResult result)
{
ResultSummary summary = new ResultSummary(result);
xmlWriter.WriteStartDocument(false);
xmlWriter.WriteComment("This file represents the results of running a test suite");
xmlWriter.WriteStartElement("test-results");
xmlWriter.WriteAttributeString("name", result.FullName);
xmlWriter.WriteAttributeString("total", summary.TestCount.ToString());
xmlWriter.WriteAttributeString("errors", summary.ErrorCount.ToString());
xmlWriter.WriteAttributeString("failures", summary.FailureCount.ToString());
var notRunTotal = summary.SkipCount + summary.FailureCount + summary.InvalidCount;
xmlWriter.WriteAttributeString("not-run", notRunTotal.ToString());
xmlWriter.WriteAttributeString("inconclusive", summary.InconclusiveCount.ToString());
xmlWriter.WriteAttributeString("ignored", summary.IgnoreCount.ToString());
xmlWriter.WriteAttributeString("skipped", summary.SkipCount.ToString());
xmlWriter.WriteAttributeString("invalid", summary.InvalidCount.ToString());
xmlWriter.WriteAttributeString("date", result.StartTime.ToString("yyyy-MM-dd"));
xmlWriter.WriteAttributeString("time", result.StartTime.ToString("HH:mm:ss"));
WriteEnvironment();
WriteCultureInfo();
}
private void WriteCultureInfo()
{
xmlWriter.WriteStartElement("culture-info");
xmlWriter.WriteAttributeString("current-culture",
CultureInfo.CurrentCulture.ToString());
xmlWriter.WriteAttributeString("current-uiculture",
CultureInfo.CurrentUICulture.ToString());
xmlWriter.WriteEndElement();
}
private void WriteEnvironment()
{
xmlWriter.WriteStartElement("environment");
var assemblyName = AssemblyHelper.GetAssemblyName(typeof(NUnit2XmlOutputWriter).GetTypeInfo().Assembly);
xmlWriter.WriteAttributeString("nunit-version",
assemblyName.Version.ToString());
#if NETSTANDARD1_6
xmlWriter.WriteAttributeString("clr-version",
System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription);
#else
xmlWriter.WriteAttributeString("clr-version",
Environment.Version.ToString());
#endif
#if !PLATFORM_DETECTION
xmlWriter.WriteAttributeString("os-version",
System.Runtime.InteropServices.RuntimeInformation.OSDescription);
#else
xmlWriter.WriteAttributeString("os-version",
OSPlatform.CurrentPlatform.ToString());
#endif
#if !NETSTANDARD1_6
xmlWriter.WriteAttributeString("platform",
Environment.OSVersion.Platform.ToString());
#endif
xmlWriter.WriteAttributeString("cwd",
Directory.GetCurrentDirectory());
xmlWriter.WriteAttributeString("machine-name",
Environment.MachineName);
#if !NETSTANDARD1_6
xmlWriter.WriteAttributeString("user",
Environment.UserName);
xmlWriter.WriteAttributeString("user-domain",
Environment.UserDomainName);
#endif
xmlWriter.WriteEndElement();
}
private void WriteResultElement(ITestResult result)
{
StartTestElement(result);
WriteCategories(result);
WriteProperties(result);
switch (result.ResultState.Status)
{
case TestStatus.Skipped:
if (result.Message != null)
WriteReasonElement(result.Message);
break;
case TestStatus.Failed:
WriteFailureElement(result.Message, result.StackTrace);
break;
}
if (result.Test is TestSuite)
WriteChildResults(result);
xmlWriter.WriteEndElement(); // test element
}
private void TerminateXmlFile()
{
xmlWriter.WriteEndElement(); // test-results
xmlWriter.WriteEndDocument();
xmlWriter.Flush();
((IDisposable)xmlWriter).Dispose();
}
#region Element Creation Helpers
private void StartTestElement(ITestResult result)
{
ITest test = result.Test;
TestSuite suite = test as TestSuite;
if (suite != null)
{
xmlWriter.WriteStartElement("test-suite");
xmlWriter.WriteAttributeString("type", suite.TestType == "ParameterizedMethod" ? "ParameterizedTest" : suite.TestType);
xmlWriter.WriteAttributeString("name", suite.TestType == "Assembly" || suite.TestType == "Project"
? result.Test.FullName
: result.Test.Name);
}
else
{
xmlWriter.WriteStartElement("test-case");
xmlWriter.WriteAttributeString("name", result.Name);
}
if (test.Properties.ContainsKey(PropertyNames.Description))
{
string description = (string)test.Properties.Get(PropertyNames.Description);
xmlWriter.WriteAttributeString("description", description);
}
TestStatus status = result.ResultState.Status;
string translatedResult = TranslateResult(result.ResultState);
if (status != TestStatus.Skipped)
{
xmlWriter.WriteAttributeString("executed", "True");
xmlWriter.WriteAttributeString("result", translatedResult);
xmlWriter.WriteAttributeString("success", status == TestStatus.Passed ? "True" : "False");
xmlWriter.WriteAttributeString("time", result.Duration.ToString("0.000", NumberFormatInfo.InvariantInfo));
xmlWriter.WriteAttributeString("asserts", result.AssertCount.ToString());
}
else
{
xmlWriter.WriteAttributeString("executed", "False");
xmlWriter.WriteAttributeString("result", translatedResult);
}
}
private string TranslateResult(ResultState resultState)
{
switch (resultState.Status)
{
default:
case TestStatus.Passed:
return "Success";
case TestStatus.Inconclusive:
return "Inconclusive";
case TestStatus.Failed:
switch (resultState.Label)
{
case "Error":
case "Cancelled":
return resultState.Label;
default:
return "Failure";
}
case TestStatus.Skipped:
switch (resultState.Label)
{
case "Ignored":
return "Ignored";
case "Invalid":
return "NotRunnable";
default:
return "Skipped";
}
}
}
private void WriteCategories(ITestResult result)
{
IPropertyBag properties = result.Test.Properties;
if (properties.ContainsKey(PropertyNames.Category))
{
xmlWriter.WriteStartElement("categories");
foreach (string category in properties[PropertyNames.Category])
{
xmlWriter.WriteStartElement("category");
xmlWriter.WriteAttributeString("name", category);
xmlWriter.WriteEndElement();
}
xmlWriter.WriteEndElement();
}
}
private void WriteProperties(ITestResult result)
{
IPropertyBag properties = result.Test.Properties;
int nprops = 0;
foreach (string key in properties.Keys)
{
if (key != PropertyNames.Category)
{
if (nprops++ == 0)
xmlWriter.WriteStartElement("properties");
foreach (object prop in properties[key])
{
xmlWriter.WriteStartElement("property");
xmlWriter.WriteAttributeString("name", key);
xmlWriter.WriteAttributeString("value", prop.ToString());
xmlWriter.WriteEndElement();
}
}
}
if (nprops > 0)
xmlWriter.WriteEndElement();
}
private void WriteReasonElement(string message)
{
xmlWriter.WriteStartElement("reason");
xmlWriter.WriteStartElement("message");
WriteCData(message);
xmlWriter.WriteEndElement();
xmlWriter.WriteEndElement();
}
private void WriteFailureElement(string message, string stackTrace)
{
xmlWriter.WriteStartElement("failure");
xmlWriter.WriteStartElement("message");
WriteCData(message);
xmlWriter.WriteEndElement();
xmlWriter.WriteStartElement("stack-trace");
if (stackTrace != null)
WriteCData(stackTrace);
xmlWriter.WriteEndElement();
xmlWriter.WriteEndElement();
}
private void WriteChildResults(ITestResult result)
{
xmlWriter.WriteStartElement("results");
foreach (ITestResult childResult in result.Children)
WriteResultElement(childResult);
xmlWriter.WriteEndElement();
}
#endregion
#region Output Helpers
///// <summary>
///// Makes string safe for xml parsing, replacing control chars with '?'
///// </summary>
///// <param name="encodedString">string to make safe</param>
///// <returns>xml safe string</returns>
//private static string CharacterSafeString(string encodedString)
//{
// /*The default code page for the system will be used.
// Since all code pages use the same lower 128 bytes, this should be sufficient
// for finding unprintable control characters that make the xslt processor error.
// We use characters encoded by the default code page to avoid mistaking bytes as
// individual characters on non-latin code pages.*/
// char[] encodedChars = System.Text.Encoding.Default.GetChars(System.Text.Encoding.Default.GetBytes(encodedString));
// System.Collections.ArrayList pos = new System.Collections.ArrayList();
// for (int x = 0; x < encodedChars.Length; x++)
// {
// char currentChar = encodedChars[x];
// //unprintable characters are below 0x20 in Unicode tables
// //some control characters are acceptable. (carriage return 0x0D, line feed 0x0A, horizontal tab 0x09)
// if (currentChar < 32 && (currentChar != 9 && currentChar != 10 && currentChar != 13))
// {
// //save the array index for later replacement.
// pos.Add(x);
// }
// }
// foreach (int index in pos)
// {
// encodedChars[index] = '?';//replace unprintable control characters with ?(3F)
// }
// return System.Text.Encoding.Default.GetString(System.Text.Encoding.Default.GetBytes(encodedChars));
//}
private void WriteCData(string text)
{
int start = 0;
while (true)
{
int illegal = text.IndexOf("]]>", start);
if (illegal < 0)
break;
xmlWriter.WriteCData(text.Substring(start, illegal - start + 2));
start = illegal + 2;
if (start >= text.Length)
return;
}
if (start > 0)
xmlWriter.WriteCData(text.Substring(start));
else
xmlWriter.WriteCData(text);
}
#endregion
}
}
| 40.141058 | 143 | 0.565826 | [
"MIT"
] | Dreamescaper/nunit | src/NUnitFramework/nunitlite/OutputWriters/NUnit2XmlOutputWriter.cs | 15,936 | C# |
////////////////////////////////////////////////////////////////////////////////
//NUnit tests for "EF Core Provider for LCPI OLE DB"
// IBProvider and Contributors. 09.05.2021.
using System;
using System.Data;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using NUnit.Framework;
using xdb=lcpi.data.oledb;
namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D1.Query.Operators.SET_001.Equal.Complete.NullableDouble.Int32{
////////////////////////////////////////////////////////////////////////////////
using T_DATA1 =System.Nullable<System.Double>;
using T_DATA2 =System.Int32;
////////////////////////////////////////////////////////////////////////////////
//class TestSet_504__param__01__VV
public static class TestSet_504__param__01__VV
{
private const string c_NameOf__TABLE ="DUAL";
private sealed class MyContext:TestBaseDbContext
{
[Table(c_NameOf__TABLE)]
public sealed class TEST_RECORD
{
[Key]
[Column("ID")]
public System.Int32? TEST_ID { get; set; }
};//class TEST_RECORD
//----------------------------------------------------------------------
public DbSet<TEST_RECORD> testTable { get; set; }
//----------------------------------------------------------------------
public MyContext(xdb.OleDbTransaction tr)
:base(tr)
{
}//MyContext
};//class MyContext
//-----------------------------------------------------------------------
[Test]
public static void Test_001__less()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
T_DATA1 vv1=3;
T_DATA2 vv2=4;
var recs=db.testTable.Where(r => vv1 /*OP{*/ == /*}OP*/ vv2);
foreach(var r in recs)
{
TestServices.ThrowSelectedRow();
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE ").P_BOOL("__Exec_V_V_0"));
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_001__less
//-----------------------------------------------------------------------
[Test]
public static void Test_002__equal()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
T_DATA1 vv1=4;
T_DATA2 vv2=4;
var recs=db.testTable.Where(r => vv1 /*OP{*/ == /*}OP*/ vv2);
int nRecs=0;
foreach(var r in recs)
{
Assert.AreEqual
(0,
nRecs);
++nRecs;
Assert.IsTrue
(r.TEST_ID.HasValue);
Assert.AreEqual
(1,
r.TEST_ID.Value);
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE ").P_BOOL("__Exec_V_V_0"));
Assert.AreEqual
(1,
nRecs);
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_002__equal
//-----------------------------------------------------------------------
[Test]
public static void Test_003__greater()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
T_DATA1 vv1=4;
T_DATA2 vv2=3;
var recs=db.testTable.Where(r => vv1 /*OP{*/ == /*}OP*/ vv2);
foreach(var r in recs)
{
TestServices.ThrowSelectedRow();
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE ").P_BOOL("__Exec_V_V_0"));
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_003__greater
//-----------------------------------------------------------------------
[Test]
public static void Test_ZA01NV()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
object vv1__null_obj=null;
T_DATA2 vv2=4;
var recs=db.testTable.Where(r => ((T_DATA1)vv1__null_obj) /*OP{*/ == /*}OP*/ vv2);
foreach(var r in recs)
{
TestServices.ThrowSelectedRow();
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE ").P_BOOL("__Exec_V_V_0"));
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_ZA01NV
//-----------------------------------------------------------------------
[Test]
public static void Test_ZA02VN()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
T_DATA1 vv1=3;
object vv2__null_obj=null;
var recs=db.testTable.Where(r => vv1 /*OP{*/ == /*}OP*/ ((T_DATA2)vv2__null_obj));
foreach(var r in recs)
{
TestServices.ThrowSelectedRow();
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE ").P_BOOL("__Exec_V_V_0"));
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_ZA02VN
//-----------------------------------------------------------------------
[Test]
public static void Test_ZA03NN()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
object vv1__null_obj=null;
object vv2__null_obj=null;
var recs=db.testTable.Where(r => ((T_DATA1)vv1__null_obj) /*OP{*/ == /*}OP*/ ((T_DATA2)vv2__null_obj));
int nRecs=0;
foreach(var r in recs)
{
Assert.AreEqual
(0,
nRecs);
++nRecs;
Assert.IsTrue
(r.TEST_ID.HasValue);
Assert.AreEqual
(1,
r.TEST_ID.Value);
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE ").P_BOOL("__Exec_V_V_0"));
Assert.AreEqual
(1,
nRecs);
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_ZA03NN
//-----------------------------------------------------------------------
[Test]
public static void Test_ZB01NV()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
object vv1__null_obj=null;
T_DATA2 vv2=4;
var recs=db.testTable.Where(r => !(((T_DATA1)vv1__null_obj) /*OP{*/ == /*}OP*/ vv2));
int nRecs=0;
foreach(var r in recs)
{
Assert.AreEqual
(0,
nRecs);
++nRecs;
Assert.IsTrue
(r.TEST_ID.HasValue);
Assert.AreEqual
(1,
r.TEST_ID.Value);
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE ").P_BOOL("__Exec_V_0"));
Assert.AreEqual
(1,
nRecs);
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_ZB01NV
//-----------------------------------------------------------------------
[Test]
public static void Test_ZB02VN()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
T_DATA1 vv1=3;
object vv2__null_obj=null;
var recs=db.testTable.Where(r => !(vv1 /*OP{*/ == /*}OP*/ ((T_DATA2)vv2__null_obj)));
int nRecs=0;
foreach(var r in recs)
{
Assert.AreEqual
(0,
nRecs);
++nRecs;
Assert.IsTrue
(r.TEST_ID.HasValue);
Assert.AreEqual
(1,
r.TEST_ID.Value);
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE ").P_BOOL("__Exec_V_0"));
Assert.AreEqual
(1,
nRecs);
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_ZB02VN
//-----------------------------------------------------------------------
[Test]
public static void Test_ZB03NN()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
object vv1__null_obj=null;
object vv2__null_obj=null;
var recs=db.testTable.Where(r => !(((T_DATA1)vv1__null_obj) /*OP{*/ == /*}OP*/ ((T_DATA2)vv2__null_obj)));
foreach(var r in recs)
{
TestServices.ThrowSelectedRow();
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE ").P_BOOL("__Exec_V_0"));
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_ZB03NN
};//class TestSet_504__param__01__VV
////////////////////////////////////////////////////////////////////////////////
}//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D1.Query.Operators.SET_001.Equal.Complete.NullableDouble.Int32
| 23.450346 | 133 | 0.525507 | [
"MIT"
] | ibprovider/Lcpi.EFCore.LcpiOleDb | Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D1/Query/Operators/SET_001/Equal/Complete/NullableDouble/Int32/TestSet_504__param__01__VV.cs | 10,156 | C# |
using UnityEngine;
using System.Collections.Generic;
using PF;
using Mathf = UnityEngine.Mathf;
namespace Pathfinding.Voxels {
public partial class Voxelize {
public void BuildContours (float maxError, int maxEdgeLength, VoxelContourSet cset, int buildFlags) {
AstarProfiler.StartProfile("Build Contours");
AstarProfiler.StartProfile("- Init");
int w = voxelArea.width;
int d = voxelArea.depth;
int wd = w*d;
//cset.bounds = voxelArea.bounds;
int maxContours = Mathf.Max(8 /*Max Regions*/, 8);
//cset.conts = new VoxelContour[maxContours];
List<VoxelContour> contours = new List<VoxelContour>(maxContours);
AstarProfiler.EndProfile("- Init");
AstarProfiler.StartProfile("- Mark Boundaries");
//cset.nconts = 0;
//NOTE: This array may contain any data, but since we explicitly set all data in it before we use it, it's OK.
ushort[] flags = voxelArea.tmpUShortArr;
if (flags.Length < voxelArea.compactSpanCount) {
flags = voxelArea.tmpUShortArr = new ushort[voxelArea.compactSpanCount];
}
// Mark boundaries. (@?)
for (int z = 0; z < wd; z += voxelArea.width) {
for (int x = 0; x < voxelArea.width; x++) {
CompactVoxelCell c = voxelArea.compactCells[x+z];
for (int i = (int)c.index, ci = (int)(c.index+c.count); i < ci; i++) {
ushort res = 0;
CompactVoxelSpan s = voxelArea.compactSpans[i];
if (s.reg == 0 || (s.reg & BorderReg) == BorderReg) {
flags[i] = 0;
continue;
}
for (int dir = 0; dir < 4; dir++) {
int r = 0;
if (s.GetConnection(dir) != NotConnected) {
int nx = x + voxelArea.DirectionX[dir];
int nz = z + voxelArea.DirectionZ[dir];
int ni = (int)voxelArea.compactCells[nx+nz].index + s.GetConnection(dir);
r = voxelArea.compactSpans[ni].reg;
}
//@TODO - Why isn't this inside the previous IF
if (r == s.reg) {
res |= (ushort)(1 << dir);
}
}
//Inverse, mark non connected edges.
flags[i] = (ushort)(res ^ 0xf);
}
}
}
AstarProfiler.EndProfile("- Mark Boundaries");
AstarProfiler.StartProfile("- Simplify Contours");
List<int> verts = ListPool<int>.Claim(256);//new List<int> (256);
List<int> simplified = ListPool<int>.Claim(64);//new List<int> (64);
for (int z = 0; z < wd; z += voxelArea.width) {
for (int x = 0; x < voxelArea.width; x++) {
CompactVoxelCell c = voxelArea.compactCells[x+z];
for (int i = (int)c.index, ci = (int)(c.index+c.count); i < ci; i++) {
//CompactVoxelSpan s = voxelArea.compactSpans[i];
if (flags[i] == 0 || flags[i] == 0xf) {
flags[i] = 0;
continue;
}
int reg = voxelArea.compactSpans[i].reg;
if (reg == 0 || (reg & BorderReg) == BorderReg) {
continue;
}
int area = voxelArea.areaTypes[i];
verts.Clear();
simplified.Clear();
WalkContour(x, z, i, flags, verts);
SimplifyContour(verts, simplified, maxError, maxEdgeLength, buildFlags);
RemoveDegenerateSegments(simplified);
VoxelContour contour = new VoxelContour();
contour.verts = PF.ArrayPool<int>.Claim(simplified.Count);//simplified.ToArray ();
for (int j = 0; j < simplified.Count; j++) contour.verts[j] = simplified[j];
#if ASTAR_RECAST_INCLUDE_RAW_VERTEX_CONTOUR
//Not used at the moment, just debug stuff
contour.rverts = ClaimIntArr(verts.Count);
for (int j = 0; j < verts.Count; j++) contour.rverts[j] = verts[j];
#endif
contour.nverts = simplified.Count/4;
contour.reg = reg;
contour.area = area;
contours.Add(contour);
#if ASTARDEBUG
for (int q = 0, j = (simplified.Count/4)-1; q < (simplified.Count/4); j = q, q++) {
int i4 = q*4;
int j4 = j*4;
Vector3 p1 = Vector3.Scale(
new Vector3(
simplified[i4+0],
simplified[i4+1],
(simplified[i4+2]/(float)voxelArea.width)
),
cellScale)
+voxelOffset;
Vector3 p2 = Vector3.Scale(
new Vector3(
simplified[j4+0],
simplified[j4+1],
(simplified[j4+2]/(float)voxelArea.width)
)
, cellScale)
+voxelOffset;
if (CalcAreaOfPolygon2D(contour.verts, contour.nverts) > 0) {
Debug.DrawLine(p1, p2, AstarMath.IntToColor(reg, 0.5F));
} else {
Debug.DrawLine(p1, p2, Color.red);
}
}
#endif
}
}
}
ListPool<int>.Release(ref verts);
ListPool<int>.Release(ref simplified);
AstarProfiler.EndProfile("- Simplify Contours");
AstarProfiler.StartProfile("- Fix Contours");
// Check and merge droppings.
// Sometimes the previous algorithms can fail and create several contours
// per area. This pass will try to merge the holes into the main region.
for (int i = 0; i < contours.Count; i++) {
VoxelContour cont = contours[i];
// Check if the contour is would backwards.
if (CalcAreaOfPolygon2D(cont.verts, cont.nverts) < 0) {
// Find another contour which has the same region ID.
int mergeIdx = -1;
for (int j = 0; j < contours.Count; j++) {
if (i == j) continue;
if (contours[j].nverts > 0 && contours[j].reg == cont.reg) {
// Make sure the polygon is correctly oriented.
if (CalcAreaOfPolygon2D(contours[j].verts, contours[j].nverts) > 0) {
mergeIdx = j;
break;
}
}
}
if (mergeIdx == -1) {
Debug.LogError("rcBuildContours: Could not find merge target for bad contour "+i+".");
} else {
// Debugging
//Debug.LogWarning ("Fixing contour");
VoxelContour mcont = contours[mergeIdx];
// Merge by closest points.
int ia = 0, ib = 0;
GetClosestIndices(mcont.verts, mcont.nverts, cont.verts, cont.nverts, ref ia, ref ib);
if (ia == -1 || ib == -1) {
Debug.LogWarning("rcBuildContours: Failed to find merge points for "+i+" and "+mergeIdx+".");
continue;
}
#if ASTARDEBUG
int p4 = ia*4;
int p42 = ib*4;
Vector3 p12 = Vector3.Scale(
new Vector3(
mcont.verts[p4+0],
mcont.verts[p4+1],
(mcont.verts[p4+2]/(float)voxelArea.width)
),
cellScale)
+voxelOffset;
Vector3 p22 = Vector3.Scale(
new Vector3(
cont.verts[p42+0],
cont.verts[p42+1],
(cont.verts[p42+2]/(float)voxelArea.width)
)
, cellScale)
+voxelOffset;
Debug.DrawLine(p12, p22, Color.green);
#endif
if (!MergeContours(ref mcont, ref cont, ia, ib)) {
Debug.LogWarning("rcBuildContours: Failed to merge contours "+i+" and "+mergeIdx+".");
continue;
}
contours[mergeIdx] = mcont;
contours[i] = cont;
#if ASTARDEBUG
Debug.Log(mcont.nverts);
for (int q = 0, j = (mcont.nverts)-1; q < (mcont.nverts); j = q, q++) {
int i4 = q*4;
int j4 = j*4;
Vector3 p1 = Vector3.Scale(
new Vector3(
mcont.verts[i4+0],
mcont.verts[i4+1],
(mcont.verts[i4+2]/(float)voxelArea.width)
),
cellScale)
+voxelOffset;
Vector3 p2 = Vector3.Scale(
new Vector3(
mcont.verts[j4+0],
mcont.verts[j4+1],
(mcont.verts[j4+2]/(float)voxelArea.width)
)
, cellScale)
+voxelOffset;
Debug.DrawLine(p1, p2, Color.red);
//}
}
#endif
}
}
}
cset.conts = contours;
AstarProfiler.EndProfile("- Fix Contours");
AstarProfiler.EndProfile("Build Contours");
}
void GetClosestIndices (int[] vertsa, int nvertsa,
int[] vertsb, int nvertsb,
ref int ia, ref int ib) {
int closestDist = 0xfffffff;
ia = -1;
ib = -1;
for (int i = 0; i < nvertsa; i++) {
//in is a keyword in C#, so I can't use that as a variable name
int in2 = (i+1) % nvertsa;
int ip = (i+nvertsa-1) % nvertsa;
int va = i*4;
int van = in2*4;
int vap = ip*4;
for (int j = 0; j < nvertsb; ++j) {
int vb = j*4;
// vb must be "infront" of va.
if (Ileft(vap, va, vb, vertsa, vertsa, vertsb) && Ileft(va, van, vb, vertsa, vertsa, vertsb)) {
int dx = vertsb[vb+0] - vertsa[va+0];
int dz = (vertsb[vb+2]/voxelArea.width) - (vertsa[va+2]/voxelArea.width);
int d = dx*dx + dz*dz;
if (d < closestDist) {
ia = i;
ib = j;
closestDist = d;
}
}
}
}
}
/** Releases contents of a contour set to caches */
static void ReleaseContours (VoxelContourSet cset) {
for (int i = 0; i < cset.conts.Count; i++) {
VoxelContour cont = cset.conts[i];
PF.ArrayPool<int>.Release(ref cont.verts);
PF.ArrayPool<int>.Release(ref cont.rverts);
}
cset.conts = null;
}
public static bool MergeContours (ref VoxelContour ca, ref VoxelContour cb, int ia, int ib) {
int maxVerts = ca.nverts + cb.nverts + 2;
int[] verts = PF.ArrayPool<int>.Claim(maxVerts*4);
//if (!verts)
// return false;
int nv = 0;
// Copy contour A.
for (int i = 0; i <= ca.nverts; i++) {
int dst = nv*4;
int src = ((ia+i) % ca.nverts)*4;
verts[dst+0] = ca.verts[src+0];
verts[dst+1] = ca.verts[src+1];
verts[dst+2] = ca.verts[src+2];
verts[dst+3] = ca.verts[src+3];
nv++;
}
// Copy contour B
for (int i = 0; i <= cb.nverts; i++) {
int dst = nv*4;
int src = ((ib+i) % cb.nverts)*4;
verts[dst+0] = cb.verts[src+0];
verts[dst+1] = cb.verts[src+1];
verts[dst+2] = cb.verts[src+2];
verts[dst+3] = cb.verts[src+3];
nv++;
}
PF.ArrayPool<int>.Release(ref ca.verts);
PF.ArrayPool<int>.Release(ref cb.verts);
ca.verts = verts;
ca.nverts = nv;
cb.verts = PF.ArrayPool<int>.Claim(0);
cb.nverts = 0;
return true;
}
public void SimplifyContour (List<int> verts, List<int> simplified, float maxError, int maxEdgeLenght, int buildFlags) {
// Add initial points.
bool hasConnections = false;
for (int i = 0; i < verts.Count; i += 4) {
if ((verts[i+3] & ContourRegMask) != 0) {
hasConnections = true;
break;
}
}
if (hasConnections) {
// The contour has some portals to other regions.
// Add a new point to every location where the region changes.
for (int i = 0, ni = verts.Count/4; i < ni; i++) {
int ii = (i+1) % ni;
bool differentRegs = (verts[i*4+3] & ContourRegMask) != (verts[ii*4+3] & ContourRegMask);
bool areaBorders = (verts[i*4+3] & RC_AREA_BORDER) != (verts[ii*4+3] & RC_AREA_BORDER);
if (differentRegs || areaBorders) {
simplified.Add(verts[i*4+0]);
simplified.Add(verts[i*4+1]);
simplified.Add(verts[i*4+2]);
simplified.Add(i);
}
}
}
if (simplified.Count == 0) {
// If there is no connections at all,
// create some initial points for the simplification process.
// Find lower-left and upper-right vertices of the contour.
int llx = verts[0];
int lly = verts[1];
int llz = verts[2];
int lli = 0;
int urx = verts[0];
int ury = verts[1];
int urz = verts[2];
int uri = 0;
for (int i = 0; i < verts.Count; i += 4) {
int x = verts[i+0];
int y = verts[i+1];
int z = verts[i+2];
if (x < llx || (x == llx && z < llz)) {
llx = x;
lly = y;
llz = z;
lli = i/4;
}
if (x > urx || (x == urx && z > urz)) {
urx = x;
ury = y;
urz = z;
uri = i/4;
}
}
simplified.Add(llx);
simplified.Add(lly);
simplified.Add(llz);
simplified.Add(lli);
simplified.Add(urx);
simplified.Add(ury);
simplified.Add(urz);
simplified.Add(uri);
}
// Add points until all raw points are within
// error tolerance to the simplified shape.
int pn = verts.Count/4;
//Use the max squared error instead
maxError *= maxError;
for (int i = 0; i < simplified.Count/4; ) {
int ii = (i+1) % (simplified.Count/4);
int ax = simplified[i*4+0];
int az = simplified[i*4+2];
int ai = simplified[i*4+3];
int bx = simplified[ii*4+0];
int bz = simplified[ii*4+2];
int bi = simplified[ii*4+3];
// Find maximum deviation from the segment.
float maxd = 0;
int maxi = -1;
int ci, cinc, endi;
// Traverse the segment in lexilogical order so that the
// max deviation is calculated similarly when traversing
// opposite segments.
if (bx > ax || (bx == ax && bz > az)) {
cinc = 1;
ci = (ai+cinc) % pn;
endi = bi;
} else {
cinc = pn-1;
ci = (bi+cinc) % pn;
endi = ai;
Memory.Swap(ref ax, ref bx);
Memory.Swap(ref az, ref bz);
}
// Tessellate only outer edges or edges between areas.
if ((verts[ci*4+3] & ContourRegMask) == 0 ||
(verts[ci*4+3] & RC_AREA_BORDER) == RC_AREA_BORDER) {
while (ci != endi) {
float d2 = VectorMath.SqrDistancePointSegmentApproximate(verts[ci*4+0], verts[ci*4+2]/voxelArea.width, ax, az/voxelArea.width, bx, bz/voxelArea.width);
if (d2 > maxd) {
maxd = d2;
maxi = ci;
}
ci = (ci+cinc) % pn;
}
}
// If the max deviation is larger than accepted error,
// add new point, else continue to next segment.
if (maxi != -1 && maxd > maxError) {
// Add space for the new point.
//simplified.resize(simplified.size()+4);
simplified.Add(0);
simplified.Add(0);
simplified.Add(0);
simplified.Add(0);
int n = simplified.Count/4;
for (int j = n-1; j > i; --j) {
simplified[j*4+0] = simplified[(j-1)*4+0];
simplified[j*4+1] = simplified[(j-1)*4+1];
simplified[j*4+2] = simplified[(j-1)*4+2];
simplified[j*4+3] = simplified[(j-1)*4+3];
}
// Add the point.
simplified[(i+1)*4+0] = verts[maxi*4+0];
simplified[(i+1)*4+1] = verts[maxi*4+1];
simplified[(i+1)*4+2] = verts[maxi*4+2];
simplified[(i+1)*4+3] = maxi;
} else {
i++;
}
}
//Split too long edges
float maxEdgeLen = maxEdgeLength / cellSize;
if (maxEdgeLen > 0 && (buildFlags & (RC_CONTOUR_TESS_WALL_EDGES|RC_CONTOUR_TESS_AREA_EDGES|RC_CONTOUR_TESS_TILE_EDGES)) != 0) {
for (int i = 0; i < simplified.Count/4; ) {
if (simplified.Count/4 > 200) {
break;
}
int ii = (i+1) % (simplified.Count/4);
int ax = simplified[i*4+0];
int az = simplified[i*4+2];
int ai = simplified[i*4+3];
int bx = simplified[ii*4+0];
int bz = simplified[ii*4+2];
int bi = simplified[ii*4+3];
// Find maximum deviation from the segment.
int maxi = -1;
int ci = (ai+1) % pn;
// Tessellate only outer edges or edges between areas.
bool tess = false;
// Wall edges.
if ((buildFlags & RC_CONTOUR_TESS_WALL_EDGES) != 0 && (verts[ci*4+3] & ContourRegMask) == 0)
tess = true;
// Edges between areas.
if ((buildFlags & RC_CONTOUR_TESS_AREA_EDGES) != 0 && (verts[ci*4+3] & RC_AREA_BORDER) == RC_AREA_BORDER)
tess = true;
// Border of tile
if ((buildFlags & RC_CONTOUR_TESS_TILE_EDGES) != 0 && (verts[ci*4+3] & BorderReg) == BorderReg)
tess = true;
if (tess) {
int dx = bx - ax;
int dz = (bz/voxelArea.width) - (az/voxelArea.width);
if (dx*dx + dz*dz > maxEdgeLen*maxEdgeLen) {
// Round based on the segments in lexilogical order so that the
// max tesselation is consistent regardles in which direction
// segments are traversed.
int n = bi < ai ? (bi+pn - ai) : (bi - ai);
if (n > 1) {
if (bx > ax || (bx == ax && bz > az)) {
maxi = (ai + n/2) % pn;
} else {
maxi = (ai + (n+1)/2) % pn;
}
}
}
}
// If the max deviation is larger than accepted error,
// add new point, else continue to next segment.
if (maxi != -1) {
// Add space for the new point.
//simplified.resize(simplified.size()+4);
simplified.AddRange(new int[4]);
int n = simplified.Count/4;
for (int j = n-1; j > i; --j) {
simplified[j*4+0] = simplified[(j-1)*4+0];
simplified[j*4+1] = simplified[(j-1)*4+1];
simplified[j*4+2] = simplified[(j-1)*4+2];
simplified[j*4+3] = simplified[(j-1)*4+3];
}
// Add the point.
simplified[(i+1)*4+0] = verts[maxi*4+0];
simplified[(i+1)*4+1] = verts[maxi*4+1];
simplified[(i+1)*4+2] = verts[maxi*4+2];
simplified[(i+1)*4+3] = maxi;
} else {
++i;
}
}
}
for (int i = 0; i < simplified.Count/4; i++) {
// The edge vertex flag is take from the current raw point,
// and the neighbour region is take from the next raw point.
int ai = (simplified[i*4+3]+1) % pn;
int bi = simplified[i*4+3];
simplified[i*4+3] = (verts[ai*4+3] & ContourRegMask) | (verts[bi*4+3] & RC_BORDER_VERTEX);
}
}
public void WalkContour (int x, int z, int i, ushort[] flags, List<int> verts) {
// Choose the first non-connected edge
int dir = 0;
while ((flags[i] & (ushort)(1 << dir)) == 0) {
dir++;
}
int startDir = dir;
int startI = i;
int area = voxelArea.areaTypes[i];
int iter = 0;
#if ASTARDEBUG
Vector3 previousPos;
Vector3 currentPos;
previousPos = ConvertPos(
x,
0,
z
);
Vector3 previousPos2 = ConvertPos(
x,
0,
z
);
#endif
while (iter++ < 40000) {
//Are we facing a region edge
if ((flags[i] & (ushort)(1 << dir)) != 0) {
#if ASTARDEBUG
Vector3 pos = ConvertPos(x, 0, z)+new Vector3((voxelArea.DirectionX[dir] != 0) ? Mathf.Sign(voxelArea.DirectionX[dir]) : 0, 0, (voxelArea.DirectionZ[dir]) != 0 ? Mathf.Sign(voxelArea.DirectionZ[dir]) : 0)*0.6F;
//int dir2 = (dir+1) & 0x3;
//pos += new Vector3 ((voxelArea.DirectionX[dir2] != 0) ? Mathf.Sign(voxelArea.DirectionX[dir2]) : 0,0,(voxelArea.DirectionZ[dir2]) != 0 ? Mathf.Sign(voxelArea.DirectionZ[dir2]) : 0)*1.2F;
//Debug.DrawLine (ConvertPos (x,0,z),pos,Color.cyan);
Debug.DrawLine(previousPos2, pos, Color.blue);
previousPos2 = pos;
#endif
//Choose the edge corner
bool isBorderVertex = false;
bool isAreaBorder = false;
int px = x;
int py = GetCornerHeight(x, z, i, dir, ref isBorderVertex);
int pz = z;
switch (dir) {
case 0: pz += voxelArea.width;; break;
case 1: px++; pz += voxelArea.width; break;
case 2: px++; break;
}
/*case 1: px++; break;
* case 2: px++; pz += voxelArea.width; break;
* case 3: pz += voxelArea.width; break;
*/
int r = 0;
CompactVoxelSpan s = voxelArea.compactSpans[i];
if (s.GetConnection(dir) != NotConnected) {
int nx = x + voxelArea.DirectionX[dir];
int nz = z + voxelArea.DirectionZ[dir];
int ni = (int)voxelArea.compactCells[nx+nz].index + s.GetConnection(dir);
r = (int)voxelArea.compactSpans[ni].reg;
if (area != voxelArea.areaTypes[ni]) {
isAreaBorder = true;
}
}
if (isBorderVertex) {
r |= RC_BORDER_VERTEX;
}
if (isAreaBorder) {
r |= RC_AREA_BORDER;
}
verts.Add(px);
verts.Add(py);
verts.Add(pz);
verts.Add(r);
//Debug.DrawRay (previousPos,new Vector3 ((dir == 1 || dir == 2) ? 1 : 0, 0, (dir == 0 || dir == 1) ? 1 : 0),Color.cyan);
flags[i] = (ushort)(flags[i] & ~(1 << dir)); // Remove visited edges
dir = (dir+1) & 0x3; // Rotate CW
} else {
int ni = -1;
int nx = x + voxelArea.DirectionX[dir];
int nz = z + voxelArea.DirectionZ[dir];
CompactVoxelSpan s = voxelArea.compactSpans[i];
if (s.GetConnection(dir) != NotConnected) {
CompactVoxelCell nc = voxelArea.compactCells[nx+nz];
ni = (int)nc.index + s.GetConnection(dir);
}
if (ni == -1) {
Debug.LogWarning("Degenerate triangles might have been generated.\n" +
"Usually this is not a problem, but if you have a static level, try to modify the graph settings slightly to avoid this edge case.");
return;
}
x = nx;
z = nz;
i = ni;
// & 0x3 is the same as % 4 (modulo 4)
dir = (dir+3) & 0x3; // Rotate CCW
#if ASTARDEBUG
currentPos = ConvertPos(
x,
0,
z
);
Debug.DrawLine(previousPos+Vector3.up*0, currentPos, Color.blue);
previousPos = currentPos;
#endif
}
if (startI == i && startDir == dir) {
break;
}
}
#if ASTARDEBUG
Color col = new Color(Random.value, Random.value, Random.value);
for (int q = 0, j = (verts.Count/4)-1; q < (verts.Count/4); j = q, q++) {
int i4 = q*4;
int j4 = j*4;
Vector3 p1 = ConvertPosWithoutOffset(
verts[i4+0],
verts[i4+1],
verts[i4+2]
);
Vector3 p2 = ConvertPosWithoutOffset(
verts[j4+0],
verts[j4+1],
verts[j4+2]
);
Debug.DrawLine(p1, p2, col);
}
#endif
}
public int GetCornerHeight (int x, int z, int i, int dir, ref bool isBorderVertex) {
CompactVoxelSpan s = voxelArea.compactSpans[i];
int ch = (int)s.y;
//dir + clockwise direction
int dirp = (dir+1) & 0x3;
//int dirp = (dir+3) & 0x3;
uint[] regs = new uint[4];
regs[0] = (uint)voxelArea.compactSpans[i].reg | ((uint)voxelArea.areaTypes[i] << 16);
if (s.GetConnection(dir) != NotConnected) {
int nx = x + voxelArea.DirectionX[dir];
int nz = z + voxelArea.DirectionZ[dir];
int ni = (int)voxelArea.compactCells[nx+nz].index + s.GetConnection(dir);
CompactVoxelSpan ns = voxelArea.compactSpans[ni];
ch = System.Math.Max(ch, (int)ns.y);
regs[1] = (uint)ns.reg | ((uint)voxelArea.areaTypes[ni] << 16);
if (ns.GetConnection(dirp) != NotConnected) {
int nx2 = nx + voxelArea.DirectionX[dirp];
int nz2 = nz + voxelArea.DirectionZ[dirp];
int ni2 = (int)voxelArea.compactCells[nx2+nz2].index + ns.GetConnection(dirp);
CompactVoxelSpan ns2 = voxelArea.compactSpans[ni2];
ch = System.Math.Max(ch, (int)ns2.y);
regs[2] = (uint)ns2.reg | ((uint)voxelArea.areaTypes[ni2] << 16);
}
}
if (s.GetConnection(dirp) != NotConnected) {
int nx = x + voxelArea.DirectionX[dirp];
int nz = z + voxelArea.DirectionZ[dirp];
int ni = (int)voxelArea.compactCells[nx+nz].index + s.GetConnection(dirp);
CompactVoxelSpan ns = voxelArea.compactSpans[ni];
ch = System.Math.Max(ch, (int)ns.y);
regs[3] = (uint)ns.reg | ((uint)voxelArea.areaTypes[ni] << 16);
if (ns.GetConnection(dir) != NotConnected) {
int nx2 = nx + voxelArea.DirectionX[dir];
int nz2 = nz + voxelArea.DirectionZ[dir];
int ni2 = (int)voxelArea.compactCells[nx2+nz2].index + ns.GetConnection(dir);
CompactVoxelSpan ns2 = voxelArea.compactSpans[ni2];
ch = System.Math.Max(ch, (int)ns2.y);
regs[2] = (uint)ns2.reg | ((uint)voxelArea.areaTypes[ni2] << 16);
}
}
// Check if the vertex is special edge vertex, these vertices will be removed later.
for (int j = 0; j < 4; ++j) {
int a = j;
int b = (j+1) & 0x3;
int c = (j+2) & 0x3;
int d = (j+3) & 0x3;
// The vertex is a border vertex there are two same exterior cells in a row,
// followed by two interior cells and none of the regions are out of bounds.
bool twoSameExts = (regs[a] & regs[b] & BorderReg) != 0 && regs[a] == regs[b];
bool twoInts = ((regs[c] | regs[d]) & BorderReg) == 0;
bool intsSameArea = (regs[c]>>16) == (regs[d]>>16);
bool noZeros = regs[a] != 0 && regs[b] != 0 && regs[c] != 0 && regs[d] != 0;
if (twoSameExts && twoInts && intsSameArea && noZeros) {
isBorderVertex = true;
break;
}
}
return ch;
}
public void RemoveDegenerateSegments (List<int> simplified) {
// Remove adjacent vertices which are equal on xz-plane,
// or else the triangulator will get confused
for (int i = 0; i < simplified.Count/4; i++) {
int ni = i+1;
if (ni >= (simplified.Count/4))
ni = 0;
if (simplified[i*4+0] == simplified[ni*4+0] &&
simplified[i*4+2] == simplified[ni*4+2]) {
// Degenerate segment, remove.
simplified.RemoveRange(i, 4);
}
}
}
public int CalcAreaOfPolygon2D (int[] verts, int nverts) {
int area = 0;
for (int i = 0, j = nverts-1; i < nverts; j = i++) {
int vi = i*4;
int vj = j*4;
area += verts[vi+0] * (verts[vj+2]/voxelArea.width) - verts[vj+0] * (verts[vi+2]/voxelArea.width);
}
return (area+1) / 2;
}
public static bool Ileft (int a, int b, int c, int[] va, int[] vb, int[] vc) {
return (vb[b+0] - va[a+0]) * (vc[c+2] - va[a+2]) - (vc[c+0] - va[a+0]) * (vb[b+2] - va[a+2]) <= 0;
}
}
}
| 28.287185 | 215 | 0.572261 | [
"MIT"
] | AlianBlank/DCET | Unity/Packages/DCET.Pathfinding/Runtime/AstarPathfindingProject/Generators/Utilities/Voxels/VoxelContour.cs | 24,723 | C# |
namespace CardRecharge
{
partial class Form_ChangePwd
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.tb_OldPsw = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.Submmit = new System.Windows.Forms.Button();
this.tb_Newpsw = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.tb_NewPswCofirm = new System.Windows.Forms.TextBox();
this.label3 = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// tb_OldPsw
//
this.tb_OldPsw.Location = new System.Drawing.Point(165, 55);
this.tb_OldPsw.Name = "tb_OldPsw";
this.tb_OldPsw.Size = new System.Drawing.Size(100, 21);
this.tb_OldPsw.TabIndex = 0;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(90, 58);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(41, 12);
this.label1.TabIndex = 1;
this.label1.Text = "原密码";
//
// Submmit
//
this.Submmit.Location = new System.Drawing.Point(190, 157);
this.Submmit.Name = "Submmit";
this.Submmit.Size = new System.Drawing.Size(75, 23);
this.Submmit.TabIndex = 2;
this.Submmit.Text = "提交";
this.Submmit.UseVisualStyleBackColor = true;
this.Submmit.Click += new System.EventHandler(this.Submmit_Click);
//
// tb_Newpsw
//
this.tb_Newpsw.Location = new System.Drawing.Point(165, 87);
this.tb_Newpsw.Name = "tb_Newpsw";
this.tb_Newpsw.Size = new System.Drawing.Size(100, 21);
this.tb_Newpsw.TabIndex = 0;
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(90, 90);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(41, 12);
this.label2.TabIndex = 1;
this.label2.Text = "新密码";
//
// tb_NewPswCofirm
//
this.tb_NewPswCofirm.Location = new System.Drawing.Point(165, 120);
this.tb_NewPswCofirm.Name = "tb_NewPswCofirm";
this.tb_NewPswCofirm.Size = new System.Drawing.Size(100, 21);
this.tb_NewPswCofirm.TabIndex = 0;
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(90, 123);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(53, 12);
this.label3.TabIndex = 1;
this.label3.Text = "确认密码";
//
// Form_ChangePwd
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(440, 235);
this.Controls.Add(this.Submmit);
this.Controls.Add(this.label3);
this.Controls.Add(this.tb_NewPswCofirm);
this.Controls.Add(this.label2);
this.Controls.Add(this.tb_Newpsw);
this.Controls.Add(this.label1);
this.Controls.Add(this.tb_OldPsw);
this.Name = "Form_ChangePwd";
this.Text = "修改密码";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.TextBox tb_OldPsw;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Button Submmit;
private System.Windows.Forms.TextBox tb_Newpsw;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.TextBox tb_NewPswCofirm;
private System.Windows.Forms.Label label3;
}
} | 38.976378 | 107 | 0.551515 | [
"MIT"
] | xiaoFeiLang/pay | src/CardRecharge/Form_ChangePwd.Designer.cs | 4,984 | C# |
using UnityEngine;
using System.Collections;
public class CheckIfKlotzLeft : MonoBehaviour
{
public Collider connectedKlotz;
private void OnTriggerExit(Collider c)
{
if (c == connectedKlotz)
{
GameController.KlotzDestroyed();
Destroy(this);
}
}
}
| 14.944444 | 46 | 0.724907 | [
"MIT"
] | Nikgoten/SlingShooter_2.0 | Assets/Scripts/CheckIfKlotzLeft.cs | 271 | C# |
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using PureCloudPlatform.Client.V2.Client;
namespace PureCloudPlatform.Client.V2.Model
{
/// <summary>
/// QueueConversationCallEventTopicCallMediaParticipant
/// </summary>
[DataContract]
public partial class QueueConversationCallEventTopicCallMediaParticipant : IEquatable<QueueConversationCallEventTopicCallMediaParticipant>
{
/// <summary>
/// Gets or Sets State
/// </summary>
[JsonConverter(typeof(UpgradeSdkEnumConverter))]
public enum StateEnum
{
/// <summary>
/// Your SDK version is out of date and an unknown enum value was encountered.
/// Please upgrade the SDK using the command "Upgrade-Package PureCloudApiSdk"
/// in the Package Manager Console
/// </summary>
[EnumMember(Value = "OUTDATED_SDK_VERSION")]
OutdatedSdkVersion,
/// <summary>
/// Enum Alerting for "alerting"
/// </summary>
[EnumMember(Value = "alerting")]
Alerting,
/// <summary>
/// Enum Dialing for "dialing"
/// </summary>
[EnumMember(Value = "dialing")]
Dialing,
/// <summary>
/// Enum Contacting for "contacting"
/// </summary>
[EnumMember(Value = "contacting")]
Contacting,
/// <summary>
/// Enum Offering for "offering"
/// </summary>
[EnumMember(Value = "offering")]
Offering,
/// <summary>
/// Enum Connected for "connected"
/// </summary>
[EnumMember(Value = "connected")]
Connected,
/// <summary>
/// Enum Disconnected for "disconnected"
/// </summary>
[EnumMember(Value = "disconnected")]
Disconnected,
/// <summary>
/// Enum Terminated for "terminated"
/// </summary>
[EnumMember(Value = "terminated")]
Terminated,
/// <summary>
/// Enum Converting for "converting"
/// </summary>
[EnumMember(Value = "converting")]
Converting,
/// <summary>
/// Enum Uploading for "uploading"
/// </summary>
[EnumMember(Value = "uploading")]
Uploading,
/// <summary>
/// Enum Transmitting for "transmitting"
/// </summary>
[EnumMember(Value = "transmitting")]
Transmitting,
/// <summary>
/// Enum Scheduled for "scheduled"
/// </summary>
[EnumMember(Value = "scheduled")]
Scheduled,
/// <summary>
/// Enum None for "none"
/// </summary>
[EnumMember(Value = "none")]
None
}
/// <summary>
/// Gets or Sets Direction
/// </summary>
[JsonConverter(typeof(UpgradeSdkEnumConverter))]
public enum DirectionEnum
{
/// <summary>
/// Your SDK version is out of date and an unknown enum value was encountered.
/// Please upgrade the SDK using the command "Upgrade-Package PureCloudApiSdk"
/// in the Package Manager Console
/// </summary>
[EnumMember(Value = "OUTDATED_SDK_VERSION")]
OutdatedSdkVersion,
/// <summary>
/// Enum Inbound for "inbound"
/// </summary>
[EnumMember(Value = "inbound")]
Inbound,
/// <summary>
/// Enum Outbound for "outbound"
/// </summary>
[EnumMember(Value = "outbound")]
Outbound
}
/// <summary>
/// Gets or Sets DisconnectType
/// </summary>
[JsonConverter(typeof(UpgradeSdkEnumConverter))]
public enum DisconnectTypeEnum
{
/// <summary>
/// Your SDK version is out of date and an unknown enum value was encountered.
/// Please upgrade the SDK using the command "Upgrade-Package PureCloudApiSdk"
/// in the Package Manager Console
/// </summary>
[EnumMember(Value = "OUTDATED_SDK_VERSION")]
OutdatedSdkVersion,
/// <summary>
/// Enum Endpoint for "endpoint"
/// </summary>
[EnumMember(Value = "endpoint")]
Endpoint,
/// <summary>
/// Enum Client for "client"
/// </summary>
[EnumMember(Value = "client")]
Client,
/// <summary>
/// Enum System for "system"
/// </summary>
[EnumMember(Value = "system")]
System,
/// <summary>
/// Enum Transfer for "transfer"
/// </summary>
[EnumMember(Value = "transfer")]
Transfer,
/// <summary>
/// Enum Timeout for "timeout"
/// </summary>
[EnumMember(Value = "timeout")]
Timeout,
/// <summary>
/// Enum Transferconference for "transfer.conference"
/// </summary>
[EnumMember(Value = "transfer.conference")]
Transferconference,
/// <summary>
/// Enum Transferconsult for "transfer.consult"
/// </summary>
[EnumMember(Value = "transfer.consult")]
Transferconsult,
/// <summary>
/// Enum Transferforward for "transfer.forward"
/// </summary>
[EnumMember(Value = "transfer.forward")]
Transferforward,
/// <summary>
/// Enum Transfernoanswer for "transfer.noanswer"
/// </summary>
[EnumMember(Value = "transfer.noanswer")]
Transfernoanswer,
/// <summary>
/// Enum Transfernotavailable for "transfer.notavailable"
/// </summary>
[EnumMember(Value = "transfer.notavailable")]
Transfernotavailable,
/// <summary>
/// Enum Transportfailure for "transport.failure"
/// </summary>
[EnumMember(Value = "transport.failure")]
Transportfailure,
/// <summary>
/// Enum Error for "error"
/// </summary>
[EnumMember(Value = "error")]
Error,
/// <summary>
/// Enum Peer for "peer"
/// </summary>
[EnumMember(Value = "peer")]
Peer,
/// <summary>
/// Enum Other for "other"
/// </summary>
[EnumMember(Value = "other")]
Other,
/// <summary>
/// Enum Spam for "spam"
/// </summary>
[EnumMember(Value = "spam")]
Spam,
/// <summary>
/// Enum Uncallable for "uncallable"
/// </summary>
[EnumMember(Value = "uncallable")]
Uncallable
}
/// <summary>
/// Gets or Sets FlaggedReason
/// </summary>
[JsonConverter(typeof(UpgradeSdkEnumConverter))]
public enum FlaggedReasonEnum
{
/// <summary>
/// Your SDK version is out of date and an unknown enum value was encountered.
/// Please upgrade the SDK using the command "Upgrade-Package PureCloudApiSdk"
/// in the Package Manager Console
/// </summary>
[EnumMember(Value = "OUTDATED_SDK_VERSION")]
OutdatedSdkVersion,
/// <summary>
/// Enum General for "general"
/// </summary>
[EnumMember(Value = "general")]
General
}
/// <summary>
/// Gets or Sets RecordingState
/// </summary>
[JsonConverter(typeof(UpgradeSdkEnumConverter))]
public enum RecordingStateEnum
{
/// <summary>
/// Your SDK version is out of date and an unknown enum value was encountered.
/// Please upgrade the SDK using the command "Upgrade-Package PureCloudApiSdk"
/// in the Package Manager Console
/// </summary>
[EnumMember(Value = "OUTDATED_SDK_VERSION")]
OutdatedSdkVersion,
/// <summary>
/// Enum None for "none"
/// </summary>
[EnumMember(Value = "none")]
None,
/// <summary>
/// Enum Active for "active"
/// </summary>
[EnumMember(Value = "active")]
Active,
/// <summary>
/// Enum Paused for "paused"
/// </summary>
[EnumMember(Value = "paused")]
Paused
}
/// <summary>
/// Gets or Sets State
/// </summary>
[DataMember(Name="state", EmitDefaultValue=false)]
public StateEnum? State { get; set; }
/// <summary>
/// Gets or Sets Direction
/// </summary>
[DataMember(Name="direction", EmitDefaultValue=false)]
public DirectionEnum? Direction { get; set; }
/// <summary>
/// Gets or Sets DisconnectType
/// </summary>
[DataMember(Name="disconnectType", EmitDefaultValue=false)]
public DisconnectTypeEnum? DisconnectType { get; set; }
/// <summary>
/// Gets or Sets FlaggedReason
/// </summary>
[DataMember(Name="flaggedReason", EmitDefaultValue=false)]
public FlaggedReasonEnum? FlaggedReason { get; set; }
/// <summary>
/// Gets or Sets RecordingState
/// </summary>
[DataMember(Name="recordingState", EmitDefaultValue=false)]
public RecordingStateEnum? RecordingState { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="QueueConversationCallEventTopicCallMediaParticipant" /> class.
/// </summary>
/// <param name="Id">Id.</param>
/// <param name="Name">Name.</param>
/// <param name="Address">Address.</param>
/// <param name="StartTime">StartTime.</param>
/// <param name="ConnectedTime">ConnectedTime.</param>
/// <param name="EndTime">EndTime.</param>
/// <param name="StartHoldTime">StartHoldTime.</param>
/// <param name="Purpose">Purpose.</param>
/// <param name="State">State.</param>
/// <param name="Direction">Direction.</param>
/// <param name="DisconnectType">DisconnectType.</param>
/// <param name="Held">Held.</param>
/// <param name="WrapupRequired">WrapupRequired.</param>
/// <param name="WrapupPrompt">WrapupPrompt.</param>
/// <param name="User">User.</param>
/// <param name="Queue">Queue.</param>
/// <param name="Team">Team.</param>
/// <param name="Attributes">Attributes.</param>
/// <param name="ErrorInfo">ErrorInfo.</param>
/// <param name="Script">Script.</param>
/// <param name="WrapupTimeoutMs">WrapupTimeoutMs.</param>
/// <param name="WrapupSkipped">WrapupSkipped.</param>
/// <param name="AlertingTimeoutMs">AlertingTimeoutMs.</param>
/// <param name="Provider">Provider.</param>
/// <param name="ExternalContact">ExternalContact.</param>
/// <param name="ExternalOrganization">ExternalOrganization.</param>
/// <param name="Wrapup">Wrapup.</param>
/// <param name="ConversationRoutingData">ConversationRoutingData.</param>
/// <param name="Peer">Peer.</param>
/// <param name="ScreenRecordingState">ScreenRecordingState.</param>
/// <param name="FlaggedReason">FlaggedReason.</param>
/// <param name="JourneyContext">JourneyContext.</param>
/// <param name="StartAcwTime">StartAcwTime.</param>
/// <param name="EndAcwTime">EndAcwTime.</param>
/// <param name="Muted">Muted.</param>
/// <param name="Confined">Confined.</param>
/// <param name="Recording">Recording.</param>
/// <param name="RecordingState">RecordingState.</param>
/// <param name="Group">Group.</param>
/// <param name="Ani">Ani.</param>
/// <param name="Dnis">Dnis.</param>
/// <param name="DocumentId">DocumentId.</param>
/// <param name="MonitoredParticipantId">MonitoredParticipantId.</param>
/// <param name="CoachedParticipantId">CoachedParticipantId.</param>
/// <param name="ConsultParticipantId">ConsultParticipantId.</param>
/// <param name="FaxStatus">FaxStatus.</param>
public QueueConversationCallEventTopicCallMediaParticipant(string Id = null, string Name = null, string Address = null, DateTime? StartTime = null, DateTime? ConnectedTime = null, DateTime? EndTime = null, DateTime? StartHoldTime = null, string Purpose = null, StateEnum? State = null, DirectionEnum? Direction = null, DisconnectTypeEnum? DisconnectType = null, bool? Held = null, bool? WrapupRequired = null, string WrapupPrompt = null, QueueConversationCallEventTopicUriReference User = null, QueueConversationCallEventTopicUriReference Queue = null, QueueConversationCallEventTopicUriReference Team = null, Dictionary<string, string> Attributes = null, QueueConversationCallEventTopicErrorBody ErrorInfo = null, QueueConversationCallEventTopicUriReference Script = null, int? WrapupTimeoutMs = null, bool? WrapupSkipped = null, int? AlertingTimeoutMs = null, string Provider = null, QueueConversationCallEventTopicUriReference ExternalContact = null, QueueConversationCallEventTopicUriReference ExternalOrganization = null, QueueConversationCallEventTopicWrapup Wrapup = null, QueueConversationCallEventTopicConversationRoutingData ConversationRoutingData = null, string Peer = null, string ScreenRecordingState = null, FlaggedReasonEnum? FlaggedReason = null, QueueConversationCallEventTopicJourneyContext JourneyContext = null, DateTime? StartAcwTime = null, DateTime? EndAcwTime = null, bool? Muted = null, bool? Confined = null, bool? Recording = null, RecordingStateEnum? RecordingState = null, QueueConversationCallEventTopicUriReference Group = null, string Ani = null, string Dnis = null, string DocumentId = null, string MonitoredParticipantId = null, string CoachedParticipantId = null, string ConsultParticipantId = null, QueueConversationCallEventTopicFaxStatus FaxStatus = null)
{
this.Id = Id;
this.Name = Name;
this.Address = Address;
this.StartTime = StartTime;
this.ConnectedTime = ConnectedTime;
this.EndTime = EndTime;
this.StartHoldTime = StartHoldTime;
this.Purpose = Purpose;
this.State = State;
this.Direction = Direction;
this.DisconnectType = DisconnectType;
this.Held = Held;
this.WrapupRequired = WrapupRequired;
this.WrapupPrompt = WrapupPrompt;
this.User = User;
this.Queue = Queue;
this.Team = Team;
this.Attributes = Attributes;
this.ErrorInfo = ErrorInfo;
this.Script = Script;
this.WrapupTimeoutMs = WrapupTimeoutMs;
this.WrapupSkipped = WrapupSkipped;
this.AlertingTimeoutMs = AlertingTimeoutMs;
this.Provider = Provider;
this.ExternalContact = ExternalContact;
this.ExternalOrganization = ExternalOrganization;
this.Wrapup = Wrapup;
this.ConversationRoutingData = ConversationRoutingData;
this.Peer = Peer;
this.ScreenRecordingState = ScreenRecordingState;
this.FlaggedReason = FlaggedReason;
this.JourneyContext = JourneyContext;
this.StartAcwTime = StartAcwTime;
this.EndAcwTime = EndAcwTime;
this.Muted = Muted;
this.Confined = Confined;
this.Recording = Recording;
this.RecordingState = RecordingState;
this.Group = Group;
this.Ani = Ani;
this.Dnis = Dnis;
this.DocumentId = DocumentId;
this.MonitoredParticipantId = MonitoredParticipantId;
this.CoachedParticipantId = CoachedParticipantId;
this.ConsultParticipantId = ConsultParticipantId;
this.FaxStatus = FaxStatus;
}
/// <summary>
/// Gets or Sets Id
/// </summary>
[DataMember(Name="id", EmitDefaultValue=false)]
public string Id { get; set; }
/// <summary>
/// Gets or Sets Name
/// </summary>
[DataMember(Name="name", EmitDefaultValue=false)]
public string Name { get; set; }
/// <summary>
/// Gets or Sets Address
/// </summary>
[DataMember(Name="address", EmitDefaultValue=false)]
public string Address { get; set; }
/// <summary>
/// Gets or Sets StartTime
/// </summary>
[DataMember(Name="startTime", EmitDefaultValue=false)]
public DateTime? StartTime { get; set; }
/// <summary>
/// Gets or Sets ConnectedTime
/// </summary>
[DataMember(Name="connectedTime", EmitDefaultValue=false)]
public DateTime? ConnectedTime { get; set; }
/// <summary>
/// Gets or Sets EndTime
/// </summary>
[DataMember(Name="endTime", EmitDefaultValue=false)]
public DateTime? EndTime { get; set; }
/// <summary>
/// Gets or Sets StartHoldTime
/// </summary>
[DataMember(Name="startHoldTime", EmitDefaultValue=false)]
public DateTime? StartHoldTime { get; set; }
/// <summary>
/// Gets or Sets Purpose
/// </summary>
[DataMember(Name="purpose", EmitDefaultValue=false)]
public string Purpose { get; set; }
/// <summary>
/// Gets or Sets Held
/// </summary>
[DataMember(Name="held", EmitDefaultValue=false)]
public bool? Held { get; set; }
/// <summary>
/// Gets or Sets WrapupRequired
/// </summary>
[DataMember(Name="wrapupRequired", EmitDefaultValue=false)]
public bool? WrapupRequired { get; set; }
/// <summary>
/// Gets or Sets WrapupPrompt
/// </summary>
[DataMember(Name="wrapupPrompt", EmitDefaultValue=false)]
public string WrapupPrompt { get; set; }
/// <summary>
/// Gets or Sets User
/// </summary>
[DataMember(Name="user", EmitDefaultValue=false)]
public QueueConversationCallEventTopicUriReference User { get; set; }
/// <summary>
/// Gets or Sets Queue
/// </summary>
[DataMember(Name="queue", EmitDefaultValue=false)]
public QueueConversationCallEventTopicUriReference Queue { get; set; }
/// <summary>
/// Gets or Sets Team
/// </summary>
[DataMember(Name="team", EmitDefaultValue=false)]
public QueueConversationCallEventTopicUriReference Team { get; set; }
/// <summary>
/// Gets or Sets Attributes
/// </summary>
[DataMember(Name="attributes", EmitDefaultValue=false)]
public Dictionary<string, string> Attributes { get; set; }
/// <summary>
/// Gets or Sets ErrorInfo
/// </summary>
[DataMember(Name="errorInfo", EmitDefaultValue=false)]
public QueueConversationCallEventTopicErrorBody ErrorInfo { get; set; }
/// <summary>
/// Gets or Sets Script
/// </summary>
[DataMember(Name="script", EmitDefaultValue=false)]
public QueueConversationCallEventTopicUriReference Script { get; set; }
/// <summary>
/// Gets or Sets WrapupTimeoutMs
/// </summary>
[DataMember(Name="wrapupTimeoutMs", EmitDefaultValue=false)]
public int? WrapupTimeoutMs { get; set; }
/// <summary>
/// Gets or Sets WrapupSkipped
/// </summary>
[DataMember(Name="wrapupSkipped", EmitDefaultValue=false)]
public bool? WrapupSkipped { get; set; }
/// <summary>
/// Gets or Sets AlertingTimeoutMs
/// </summary>
[DataMember(Name="alertingTimeoutMs", EmitDefaultValue=false)]
public int? AlertingTimeoutMs { get; set; }
/// <summary>
/// Gets or Sets Provider
/// </summary>
[DataMember(Name="provider", EmitDefaultValue=false)]
public string Provider { get; set; }
/// <summary>
/// Gets or Sets ExternalContact
/// </summary>
[DataMember(Name="externalContact", EmitDefaultValue=false)]
public QueueConversationCallEventTopicUriReference ExternalContact { get; set; }
/// <summary>
/// Gets or Sets ExternalOrganization
/// </summary>
[DataMember(Name="externalOrganization", EmitDefaultValue=false)]
public QueueConversationCallEventTopicUriReference ExternalOrganization { get; set; }
/// <summary>
/// Gets or Sets Wrapup
/// </summary>
[DataMember(Name="wrapup", EmitDefaultValue=false)]
public QueueConversationCallEventTopicWrapup Wrapup { get; set; }
/// <summary>
/// Gets or Sets ConversationRoutingData
/// </summary>
[DataMember(Name="conversationRoutingData", EmitDefaultValue=false)]
public QueueConversationCallEventTopicConversationRoutingData ConversationRoutingData { get; set; }
/// <summary>
/// Gets or Sets Peer
/// </summary>
[DataMember(Name="peer", EmitDefaultValue=false)]
public string Peer { get; set; }
/// <summary>
/// Gets or Sets ScreenRecordingState
/// </summary>
[DataMember(Name="screenRecordingState", EmitDefaultValue=false)]
public string ScreenRecordingState { get; set; }
/// <summary>
/// Gets or Sets JourneyContext
/// </summary>
[DataMember(Name="journeyContext", EmitDefaultValue=false)]
public QueueConversationCallEventTopicJourneyContext JourneyContext { get; set; }
/// <summary>
/// Gets or Sets StartAcwTime
/// </summary>
[DataMember(Name="startAcwTime", EmitDefaultValue=false)]
public DateTime? StartAcwTime { get; set; }
/// <summary>
/// Gets or Sets EndAcwTime
/// </summary>
[DataMember(Name="endAcwTime", EmitDefaultValue=false)]
public DateTime? EndAcwTime { get; set; }
/// <summary>
/// Gets or Sets Muted
/// </summary>
[DataMember(Name="muted", EmitDefaultValue=false)]
public bool? Muted { get; set; }
/// <summary>
/// Gets or Sets Confined
/// </summary>
[DataMember(Name="confined", EmitDefaultValue=false)]
public bool? Confined { get; set; }
/// <summary>
/// Gets or Sets Recording
/// </summary>
[DataMember(Name="recording", EmitDefaultValue=false)]
public bool? Recording { get; set; }
/// <summary>
/// Gets or Sets Group
/// </summary>
[DataMember(Name="group", EmitDefaultValue=false)]
public QueueConversationCallEventTopicUriReference Group { get; set; }
/// <summary>
/// Gets or Sets Ani
/// </summary>
[DataMember(Name="ani", EmitDefaultValue=false)]
public string Ani { get; set; }
/// <summary>
/// Gets or Sets Dnis
/// </summary>
[DataMember(Name="dnis", EmitDefaultValue=false)]
public string Dnis { get; set; }
/// <summary>
/// Gets or Sets DocumentId
/// </summary>
[DataMember(Name="documentId", EmitDefaultValue=false)]
public string DocumentId { get; set; }
/// <summary>
/// Gets or Sets MonitoredParticipantId
/// </summary>
[DataMember(Name="monitoredParticipantId", EmitDefaultValue=false)]
public string MonitoredParticipantId { get; set; }
/// <summary>
/// Gets or Sets CoachedParticipantId
/// </summary>
[DataMember(Name="coachedParticipantId", EmitDefaultValue=false)]
public string CoachedParticipantId { get; set; }
/// <summary>
/// Gets or Sets ConsultParticipantId
/// </summary>
[DataMember(Name="consultParticipantId", EmitDefaultValue=false)]
public string ConsultParticipantId { get; set; }
/// <summary>
/// Gets or Sets FaxStatus
/// </summary>
[DataMember(Name="faxStatus", EmitDefaultValue=false)]
public QueueConversationCallEventTopicFaxStatus FaxStatus { 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 QueueConversationCallEventTopicCallMediaParticipant {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" Name: ").Append(Name).Append("\n");
sb.Append(" Address: ").Append(Address).Append("\n");
sb.Append(" StartTime: ").Append(StartTime).Append("\n");
sb.Append(" ConnectedTime: ").Append(ConnectedTime).Append("\n");
sb.Append(" EndTime: ").Append(EndTime).Append("\n");
sb.Append(" StartHoldTime: ").Append(StartHoldTime).Append("\n");
sb.Append(" Purpose: ").Append(Purpose).Append("\n");
sb.Append(" State: ").Append(State).Append("\n");
sb.Append(" Direction: ").Append(Direction).Append("\n");
sb.Append(" DisconnectType: ").Append(DisconnectType).Append("\n");
sb.Append(" Held: ").Append(Held).Append("\n");
sb.Append(" WrapupRequired: ").Append(WrapupRequired).Append("\n");
sb.Append(" WrapupPrompt: ").Append(WrapupPrompt).Append("\n");
sb.Append(" User: ").Append(User).Append("\n");
sb.Append(" Queue: ").Append(Queue).Append("\n");
sb.Append(" Team: ").Append(Team).Append("\n");
sb.Append(" Attributes: ").Append(Attributes).Append("\n");
sb.Append(" ErrorInfo: ").Append(ErrorInfo).Append("\n");
sb.Append(" Script: ").Append(Script).Append("\n");
sb.Append(" WrapupTimeoutMs: ").Append(WrapupTimeoutMs).Append("\n");
sb.Append(" WrapupSkipped: ").Append(WrapupSkipped).Append("\n");
sb.Append(" AlertingTimeoutMs: ").Append(AlertingTimeoutMs).Append("\n");
sb.Append(" Provider: ").Append(Provider).Append("\n");
sb.Append(" ExternalContact: ").Append(ExternalContact).Append("\n");
sb.Append(" ExternalOrganization: ").Append(ExternalOrganization).Append("\n");
sb.Append(" Wrapup: ").Append(Wrapup).Append("\n");
sb.Append(" ConversationRoutingData: ").Append(ConversationRoutingData).Append("\n");
sb.Append(" Peer: ").Append(Peer).Append("\n");
sb.Append(" ScreenRecordingState: ").Append(ScreenRecordingState).Append("\n");
sb.Append(" FlaggedReason: ").Append(FlaggedReason).Append("\n");
sb.Append(" JourneyContext: ").Append(JourneyContext).Append("\n");
sb.Append(" StartAcwTime: ").Append(StartAcwTime).Append("\n");
sb.Append(" EndAcwTime: ").Append(EndAcwTime).Append("\n");
sb.Append(" Muted: ").Append(Muted).Append("\n");
sb.Append(" Confined: ").Append(Confined).Append("\n");
sb.Append(" Recording: ").Append(Recording).Append("\n");
sb.Append(" RecordingState: ").Append(RecordingState).Append("\n");
sb.Append(" Group: ").Append(Group).Append("\n");
sb.Append(" Ani: ").Append(Ani).Append("\n");
sb.Append(" Dnis: ").Append(Dnis).Append("\n");
sb.Append(" DocumentId: ").Append(DocumentId).Append("\n");
sb.Append(" MonitoredParticipantId: ").Append(MonitoredParticipantId).Append("\n");
sb.Append(" CoachedParticipantId: ").Append(CoachedParticipantId).Append("\n");
sb.Append(" ConsultParticipantId: ").Append(ConsultParticipantId).Append("\n");
sb.Append(" FaxStatus: ").Append(FaxStatus).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 string ToJson()
{
return JsonConvert.SerializeObject(this, new JsonSerializerSettings
{
MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
Formatting = Formatting.Indented
});
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as QueueConversationCallEventTopicCallMediaParticipant);
}
/// <summary>
/// Returns true if QueueConversationCallEventTopicCallMediaParticipant instances are equal
/// </summary>
/// <param name="other">Instance of QueueConversationCallEventTopicCallMediaParticipant to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(QueueConversationCallEventTopicCallMediaParticipant other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return true &&
(
this.Id == other.Id ||
this.Id != null &&
this.Id.Equals(other.Id)
) &&
(
this.Name == other.Name ||
this.Name != null &&
this.Name.Equals(other.Name)
) &&
(
this.Address == other.Address ||
this.Address != null &&
this.Address.Equals(other.Address)
) &&
(
this.StartTime == other.StartTime ||
this.StartTime != null &&
this.StartTime.Equals(other.StartTime)
) &&
(
this.ConnectedTime == other.ConnectedTime ||
this.ConnectedTime != null &&
this.ConnectedTime.Equals(other.ConnectedTime)
) &&
(
this.EndTime == other.EndTime ||
this.EndTime != null &&
this.EndTime.Equals(other.EndTime)
) &&
(
this.StartHoldTime == other.StartHoldTime ||
this.StartHoldTime != null &&
this.StartHoldTime.Equals(other.StartHoldTime)
) &&
(
this.Purpose == other.Purpose ||
this.Purpose != null &&
this.Purpose.Equals(other.Purpose)
) &&
(
this.State == other.State ||
this.State != null &&
this.State.Equals(other.State)
) &&
(
this.Direction == other.Direction ||
this.Direction != null &&
this.Direction.Equals(other.Direction)
) &&
(
this.DisconnectType == other.DisconnectType ||
this.DisconnectType != null &&
this.DisconnectType.Equals(other.DisconnectType)
) &&
(
this.Held == other.Held ||
this.Held != null &&
this.Held.Equals(other.Held)
) &&
(
this.WrapupRequired == other.WrapupRequired ||
this.WrapupRequired != null &&
this.WrapupRequired.Equals(other.WrapupRequired)
) &&
(
this.WrapupPrompt == other.WrapupPrompt ||
this.WrapupPrompt != null &&
this.WrapupPrompt.Equals(other.WrapupPrompt)
) &&
(
this.User == other.User ||
this.User != null &&
this.User.Equals(other.User)
) &&
(
this.Queue == other.Queue ||
this.Queue != null &&
this.Queue.Equals(other.Queue)
) &&
(
this.Team == other.Team ||
this.Team != null &&
this.Team.Equals(other.Team)
) &&
(
this.Attributes == other.Attributes ||
this.Attributes != null &&
this.Attributes.SequenceEqual(other.Attributes)
) &&
(
this.ErrorInfo == other.ErrorInfo ||
this.ErrorInfo != null &&
this.ErrorInfo.Equals(other.ErrorInfo)
) &&
(
this.Script == other.Script ||
this.Script != null &&
this.Script.Equals(other.Script)
) &&
(
this.WrapupTimeoutMs == other.WrapupTimeoutMs ||
this.WrapupTimeoutMs != null &&
this.WrapupTimeoutMs.Equals(other.WrapupTimeoutMs)
) &&
(
this.WrapupSkipped == other.WrapupSkipped ||
this.WrapupSkipped != null &&
this.WrapupSkipped.Equals(other.WrapupSkipped)
) &&
(
this.AlertingTimeoutMs == other.AlertingTimeoutMs ||
this.AlertingTimeoutMs != null &&
this.AlertingTimeoutMs.Equals(other.AlertingTimeoutMs)
) &&
(
this.Provider == other.Provider ||
this.Provider != null &&
this.Provider.Equals(other.Provider)
) &&
(
this.ExternalContact == other.ExternalContact ||
this.ExternalContact != null &&
this.ExternalContact.Equals(other.ExternalContact)
) &&
(
this.ExternalOrganization == other.ExternalOrganization ||
this.ExternalOrganization != null &&
this.ExternalOrganization.Equals(other.ExternalOrganization)
) &&
(
this.Wrapup == other.Wrapup ||
this.Wrapup != null &&
this.Wrapup.Equals(other.Wrapup)
) &&
(
this.ConversationRoutingData == other.ConversationRoutingData ||
this.ConversationRoutingData != null &&
this.ConversationRoutingData.Equals(other.ConversationRoutingData)
) &&
(
this.Peer == other.Peer ||
this.Peer != null &&
this.Peer.Equals(other.Peer)
) &&
(
this.ScreenRecordingState == other.ScreenRecordingState ||
this.ScreenRecordingState != null &&
this.ScreenRecordingState.Equals(other.ScreenRecordingState)
) &&
(
this.FlaggedReason == other.FlaggedReason ||
this.FlaggedReason != null &&
this.FlaggedReason.Equals(other.FlaggedReason)
) &&
(
this.JourneyContext == other.JourneyContext ||
this.JourneyContext != null &&
this.JourneyContext.Equals(other.JourneyContext)
) &&
(
this.StartAcwTime == other.StartAcwTime ||
this.StartAcwTime != null &&
this.StartAcwTime.Equals(other.StartAcwTime)
) &&
(
this.EndAcwTime == other.EndAcwTime ||
this.EndAcwTime != null &&
this.EndAcwTime.Equals(other.EndAcwTime)
) &&
(
this.Muted == other.Muted ||
this.Muted != null &&
this.Muted.Equals(other.Muted)
) &&
(
this.Confined == other.Confined ||
this.Confined != null &&
this.Confined.Equals(other.Confined)
) &&
(
this.Recording == other.Recording ||
this.Recording != null &&
this.Recording.Equals(other.Recording)
) &&
(
this.RecordingState == other.RecordingState ||
this.RecordingState != null &&
this.RecordingState.Equals(other.RecordingState)
) &&
(
this.Group == other.Group ||
this.Group != null &&
this.Group.Equals(other.Group)
) &&
(
this.Ani == other.Ani ||
this.Ani != null &&
this.Ani.Equals(other.Ani)
) &&
(
this.Dnis == other.Dnis ||
this.Dnis != null &&
this.Dnis.Equals(other.Dnis)
) &&
(
this.DocumentId == other.DocumentId ||
this.DocumentId != null &&
this.DocumentId.Equals(other.DocumentId)
) &&
(
this.MonitoredParticipantId == other.MonitoredParticipantId ||
this.MonitoredParticipantId != null &&
this.MonitoredParticipantId.Equals(other.MonitoredParticipantId)
) &&
(
this.CoachedParticipantId == other.CoachedParticipantId ||
this.CoachedParticipantId != null &&
this.CoachedParticipantId.Equals(other.CoachedParticipantId)
) &&
(
this.ConsultParticipantId == other.ConsultParticipantId ||
this.ConsultParticipantId != null &&
this.ConsultParticipantId.Equals(other.ConsultParticipantId)
) &&
(
this.FaxStatus == other.FaxStatus ||
this.FaxStatus != null &&
this.FaxStatus.Equals(other.FaxStatus)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.Id != null)
hash = hash * 59 + this.Id.GetHashCode();
if (this.Name != null)
hash = hash * 59 + this.Name.GetHashCode();
if (this.Address != null)
hash = hash * 59 + this.Address.GetHashCode();
if (this.StartTime != null)
hash = hash * 59 + this.StartTime.GetHashCode();
if (this.ConnectedTime != null)
hash = hash * 59 + this.ConnectedTime.GetHashCode();
if (this.EndTime != null)
hash = hash * 59 + this.EndTime.GetHashCode();
if (this.StartHoldTime != null)
hash = hash * 59 + this.StartHoldTime.GetHashCode();
if (this.Purpose != null)
hash = hash * 59 + this.Purpose.GetHashCode();
if (this.State != null)
hash = hash * 59 + this.State.GetHashCode();
if (this.Direction != null)
hash = hash * 59 + this.Direction.GetHashCode();
if (this.DisconnectType != null)
hash = hash * 59 + this.DisconnectType.GetHashCode();
if (this.Held != null)
hash = hash * 59 + this.Held.GetHashCode();
if (this.WrapupRequired != null)
hash = hash * 59 + this.WrapupRequired.GetHashCode();
if (this.WrapupPrompt != null)
hash = hash * 59 + this.WrapupPrompt.GetHashCode();
if (this.User != null)
hash = hash * 59 + this.User.GetHashCode();
if (this.Queue != null)
hash = hash * 59 + this.Queue.GetHashCode();
if (this.Team != null)
hash = hash * 59 + this.Team.GetHashCode();
if (this.Attributes != null)
hash = hash * 59 + this.Attributes.GetHashCode();
if (this.ErrorInfo != null)
hash = hash * 59 + this.ErrorInfo.GetHashCode();
if (this.Script != null)
hash = hash * 59 + this.Script.GetHashCode();
if (this.WrapupTimeoutMs != null)
hash = hash * 59 + this.WrapupTimeoutMs.GetHashCode();
if (this.WrapupSkipped != null)
hash = hash * 59 + this.WrapupSkipped.GetHashCode();
if (this.AlertingTimeoutMs != null)
hash = hash * 59 + this.AlertingTimeoutMs.GetHashCode();
if (this.Provider != null)
hash = hash * 59 + this.Provider.GetHashCode();
if (this.ExternalContact != null)
hash = hash * 59 + this.ExternalContact.GetHashCode();
if (this.ExternalOrganization != null)
hash = hash * 59 + this.ExternalOrganization.GetHashCode();
if (this.Wrapup != null)
hash = hash * 59 + this.Wrapup.GetHashCode();
if (this.ConversationRoutingData != null)
hash = hash * 59 + this.ConversationRoutingData.GetHashCode();
if (this.Peer != null)
hash = hash * 59 + this.Peer.GetHashCode();
if (this.ScreenRecordingState != null)
hash = hash * 59 + this.ScreenRecordingState.GetHashCode();
if (this.FlaggedReason != null)
hash = hash * 59 + this.FlaggedReason.GetHashCode();
if (this.JourneyContext != null)
hash = hash * 59 + this.JourneyContext.GetHashCode();
if (this.StartAcwTime != null)
hash = hash * 59 + this.StartAcwTime.GetHashCode();
if (this.EndAcwTime != null)
hash = hash * 59 + this.EndAcwTime.GetHashCode();
if (this.Muted != null)
hash = hash * 59 + this.Muted.GetHashCode();
if (this.Confined != null)
hash = hash * 59 + this.Confined.GetHashCode();
if (this.Recording != null)
hash = hash * 59 + this.Recording.GetHashCode();
if (this.RecordingState != null)
hash = hash * 59 + this.RecordingState.GetHashCode();
if (this.Group != null)
hash = hash * 59 + this.Group.GetHashCode();
if (this.Ani != null)
hash = hash * 59 + this.Ani.GetHashCode();
if (this.Dnis != null)
hash = hash * 59 + this.Dnis.GetHashCode();
if (this.DocumentId != null)
hash = hash * 59 + this.DocumentId.GetHashCode();
if (this.MonitoredParticipantId != null)
hash = hash * 59 + this.MonitoredParticipantId.GetHashCode();
if (this.CoachedParticipantId != null)
hash = hash * 59 + this.CoachedParticipantId.GetHashCode();
if (this.ConsultParticipantId != null)
hash = hash * 59 + this.ConsultParticipantId.GetHashCode();
if (this.FaxStatus != null)
hash = hash * 59 + this.FaxStatus.GetHashCode();
return hash;
}
}
}
}
| 34.014141 | 1,802 | 0.475184 | [
"MIT"
] | F-V-L/platform-client-sdk-dotnet | build/src/PureCloudPlatform.Client.V2/Model/QueueConversationCallEventTopicCallMediaParticipant.cs | 50,511 | C# |
using System;
using System.Windows;
using DentoInjector.Core;
namespace DentoInjector.Graphics
{
public partial class WnExceptionHandler
{
public WnExceptionHandler(Exception error)
{
InitializeComponent();
MessageText.Text = error.Message;
StackTraceText.Text = error.StackTrace;
}
private void Restart(object sender, RoutedEventArgs args)
{
Utilities.RestartApp();
}
private void Exit(object sender, RoutedEventArgs args)
{
Application.Current.Shutdown();
}
}
} | 20.5 | 65 | 0.60813 | [
"MIT"
] | trucnguyenlam/DentoInjector | DentoInjector/Graphics/WnExceptionHandler.xaml.cs | 617 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace BNG {
/// <summary>
/// This CharacterConstraint will keep the size the Character Capsule along with the camera if not colliding with anything
/// </summary>
public class CharacterConstraint : MonoBehaviour {
BNGPlayerController bngController;
CharacterController character;
void Awake() {
character = GetComponent<CharacterController>();
bngController = transform.GetComponentInParent<BNGPlayerController>();
}
private void Update() {
CheckCharacterCollisionMove();
}
public virtual void CheckCharacterCollisionMove() {
var initialCameraRigPosition = bngController.CameraRig.transform.position;
var cameraPosition = bngController.CenterEyeAnchor.position;
var delta = cameraPosition - transform.position;
// Ignore Y position
delta.y = 0;
// Move Character Controller and Camera Rig to Camera's delta
if (delta.magnitude > 0) {
character.Move(delta);
// Move Camera Rig back into position
bngController.CameraRig.transform.position = initialCameraRigPosition;
}
}
}
} | 26.697674 | 123 | 0.750871 | [
"MIT"
] | AhmedFarouk1/GolfVR | Assets/BNG Framework/Scripts/Components/CharacterConstraint.cs | 1,150 | C# |
namespace FlowCanvas
{
///A stub class to replicate open generics
public class Wild { }
} | 17.333333 | 47 | 0.644231 | [
"MIT"
] | SwageliciousGGJ/YourMom2.0 | Assets/ParadoxNotion/FlowCanvas/Modules/FlowGraphs/Wild.cs | 106 | C# |
using System.Linq;
namespace Powercards.Core.Cards
{
[CardInfo(CardSet.Promo, 4, true)]
public class Envoy : CardBase, IActionCard
{
#region methods
public void Play(TurnContext context)
{
using (var transZone = new TransitionalZone(context.ActivePlayer))
{
context.ActivePlayer.MoveFromTopDeck(5, transZone, CardMovementVerb.Reveal, context);
transZone.Reveal(context.Game.Log);
if (!transZone.IsEmpty)
{
var discardCard = context.Game.Dialog.Select(context, context.Game.NextPlayerOf(context.ActivePlayer), transZone,
new CountValidator<ICard>(1),
string.Format("Select the card you do not want {0} to draw.", transZone.Owner.Name)).Single();
if (discardCard.MoveTo(transZone, context.ActivePlayer.DiscardArea, CardMovementVerb.Discard, context))
context.Game.Log.LogDiscard(context.ActivePlayer, discardCard);
transZone.MoveAll(transZone, context.ActivePlayer.Hand, CardMovementVerb.PutInHand, context);
}
}
}
#endregion
}
} | 39.870968 | 133 | 0.598706 | [
"MIT"
] | whence/powerlife | csharp/Core/Cards/Envoy.cs | 1,238 | C# |
using System.IO;
using System.Runtime.Serialization;
using GameEstate.Red.Formats.Red.CR2W.Reflection;
using FastMember;
using static GameEstate.Red.Formats.Red.Records.Enums;
namespace GameEstate.Red.Formats.Red.Types
{
[DataContract(Namespace = "")]
[REDMeta]
public class CQuestManyActorsCondition : IQuestCondition
{
[Ordinal(1)] [RED("actorTags")] public TagList ActorTags { get; set;}
[Ordinal(2)] [RED("logicOperation")] public CEnum<EQuestActorConditionLogicOperation> LogicOperation { get; set;}
[Ordinal(3)] [RED("condition")] public CPtr<IActorConditionType> Condition { get; set;}
public CQuestManyActorsCondition(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name){ }
public static new CVariable Create(CR2WFile cr2w, CVariable parent, string name) => new CQuestManyActorsCondition(cr2w, parent, name);
public override void Read(BinaryReader file, uint size) => base.Read(file, size);
public override void Write(BinaryWriter file) => base.Write(file);
}
} | 36.241379 | 137 | 0.736441 | [
"MIT"
] | bclnet/GameEstate | src/Estates/Red/GameEstate.Red.Format/Red/W3/RTTIConvert/CQuestManyActorsCondition.cs | 1,051 | C# |
using Microsoft.EntityFrameworkCore.Migrations;
namespace Registru_Intrari_Iesiri.Migrations
{
public partial class InOutRegisterEntriesUpdates : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<string>(
name: "Resolution",
table: "InOutRegisterEntry",
maxLength: 1000,
nullable: false,
oldClrType: typeof(string),
oldType: "nvarchar(1000)",
oldMaxLength: 1000,
oldNullable: true);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<string>(
name: "Resolution",
table: "InOutRegisterEntry",
type: "nvarchar(1000)",
maxLength: 1000,
nullable: true,
oldClrType: typeof(string),
oldMaxLength: 1000);
}
}
}
| 31.272727 | 71 | 0.550388 | [
"MIT"
] | rododendron1001/Registru_Intrari_Iesiri_V1 | Registru_Intrari_Iesiri/Registru_Intrari_Iesiri/Migrations/20200824165835_InOutRegisterEntriesUpdates.cs | 1,034 | C# |
namespace SKIT.FlurlHttpClient.Wechat.OpenAI.Models.ThirdParty
{
/// <summary>
/// <para>表示 [POST] /v2/intent/name_exist 接口的响应。</para>
/// </summary>
public class IntentNameExistResponse : WechatOpenAIThirdPartyResponse<IntentNameExistResponse.Types.Data>
{
public static class Types
{
public class Data
{
/// <summary>
/// 获取或设置是否已存在。
/// </summary>
[Newtonsoft.Json.JsonProperty("exist")]
[System.Text.Json.Serialization.JsonPropertyName("exist")]
public bool IsExisted { get; set; }
}
}
}
}
| 30.681818 | 109 | 0.545185 | [
"MIT"
] | OrchesAdam/DotNetCore.SKIT.FlurlHttpClient.Wechat | src/SKIT.FlurlHttpClient.Wechat.OpenAI/Models/ThirdParty/Intent/IntentNameExistResponse.cs | 715 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.Networking;
namespace Xsolla.Core
{
public partial class WebRequestHelper : MonoSingleton<WebRequestHelper>
{
public void DeleteRequest(SdkType sdkType, string url, WebRequestHeader requestHeader, Action onComplete = null, Action<Error> onError = null, Dictionary<string, ErrorType> errorsToCheck = null)
{
var requestHeaders = AppendAnalyticHeaders(sdkType, requestHeader);
StartCoroutine(DeleteRequestCor(sdkType, url, requestHeaders, onComplete, onError, errorsToCheck));
}
public void DeleteRequest(SdkType sdkType, string url, List<WebRequestHeader> requestHeaders, Action onComplete = null, Action<Error> onError = null, Dictionary<string, ErrorType> errorsToCheck = null)
{
requestHeaders = AppendAnalyticHeaders(sdkType, requestHeaders?.ToArray());
StartCoroutine(DeleteRequestCor(sdkType, url, requestHeaders, onComplete, onError, errorsToCheck));
}
IEnumerator DeleteRequestCor(SdkType sdkType, string url, List<WebRequestHeader> requestHeaders, Action onComplete = null, Action<Error> onError = null, Dictionary<string, ErrorType> errorsToCheck = null)
{
url = AppendAnalyticsToUrl(sdkType, url);
var webRequest = UnityWebRequest.Delete(url);
webRequest.downloadHandler = new DownloadHandlerBuffer();
AttachHeaders(webRequest, requestHeaders);
yield return StartCoroutine(PerformWebRequest(webRequest, onComplete, onError, errorsToCheck));
}
}
}
| 42.942857 | 206 | 0.790419 | [
"Apache-2.0"
] | xsolla/inventory-unity-sdk | Assets/Xsolla/Core/WebRequestHelper/WebRequestHelper.DELETE.cs | 1,503 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Axe.Windows.Actions;
using System;
using System.Windows.Input;
namespace AccessibilityInsights.SharedUx.Highlighting
{
/// <summary>
/// Wraps and provides access to highlight capabilities for
/// elements over an image
/// </summary>
public class ImageOverlayDriver:IDisposable
{
/// <summary>
/// imageHighlighter to use
/// </summary>
private ImageHighlighter Highlighter;
/// <summary>
/// Constructor
/// </summary>
private ImageOverlayDriver()
{
Highlighter = new ImageHighlighter(SetHighlightBtnState);
}
/// <summary>
/// Show
/// </summary>
public void Show()
{
Highlighter.Show();
}
/// <summary>
/// Hide
/// </summary>
public void Hide()
{
Highlighter.Hide();
}
/// <summary>
/// Add Element in highlighter
/// </summary>
/// <param name="ecId">ElementContext Id</param>
/// <param name="eId">Element Id</param>
public void AddElement(Guid ecId, int eId)
{
var e = DataManager.GetDefaultInstance().GetA11yElement(ecId, eId);
Highlighter.AddElement(e);
}
/// <summary>
/// Set single element
/// </summary>
/// <param name="ecId"></param>
/// <param name="e"></param>
/// <param name="txt">text to show in top right corner</param>
public void SetSingleElement(Guid ecId, int eId, string txt = null)
{
var e = GetDataAction.GetA11yElementInDataContext(ecId, eId);
Highlighter.SetSingleElement(e, txt);
}
/// <summary>
/// Clear highligted elements in bitmap.
/// </summary>
public void ClearElements()
{
Highlighter.ClearElements();
}
/// <summary>
/// Set Background image with Element on highlighter
/// it is to set bounding rectangle of background image based on screenshot element.
/// </summary>
/// <param name="ecId"></param>
/// <param name="eId"></param>
/// <param name="onClick"></param>
public void SetImageElement(Guid ecId)
{
var e = DataManager.GetDefaultInstance().GetScreenshotElement(ecId);
Highlighter.SetElement(e);
Highlighter.SetBackground(DataManager.GetDefaultInstance().GetScreenshot(ecId));
}
/// <summary>
/// set button click handler of Highlighter
/// if it is null, button would not be shown in highlighter.
/// </summary>
/// <param name="onClick"></param>
public void SetHighlighterButtonClickHandler(MouseButtonEventHandler onClick)
{
Highlighter.SetButtonClickHandler(onClick);
}
/// <summary>
/// Remove Element
/// </summary>
/// <param name="ecId">ElementContext Id</param>
/// <param name="eId">Element Id</param>
public void RemoveElement(Guid ecId, int eId)
{
var e = DataManager.GetDefaultInstance().GetA11yElement(ecId, eId);
Highlighter.RemoveElement(e);
}
/// <summary>
/// Clear all elements in highlighter
/// </summary>
public void Clear()
{
Highlighter.Clear();
}
/// <summary>
/// Get the visible state of highlighter
/// </summary>
/// <returns></returns>
public bool IsVisible()
{
return Highlighter.IsVisible;
}
#region static members
/// <summary>
/// Action to set highlighter button state
/// </summary>
public static Action<bool> SetHighlightBtnState { get; set; }
static ImageOverlayDriver defaultHighlightImageAction;
/// <summary>
/// Get default HighlightAction
/// </summary>
/// <returns></returns>
public static ImageOverlayDriver GetDefaultInstance()
{
if (defaultHighlightImageAction == null)
{
defaultHighlightImageAction = new ImageOverlayDriver();
}
return defaultHighlightImageAction;
}
/// <summary>
/// Clear default Highlighter instance
/// </summary>
public static void ClearDefaultInstance()
{
defaultHighlightImageAction?.Dispose();
defaultHighlightImageAction = null;
}
#endregion
#region IDisposable Support
private bool disposedValue; // To detect redundant calls
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
if (this.Highlighter != null)
{
this.Highlighter.Dispose();
this.Highlighter = null;
}
}
disposedValue = true;
}
}
// This code added to correctly implement the disposable pattern.
public void Dispose()
{
// Do not change this code. Put cleanup code in Dispose(bool disposing) above.
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
}
}
| 30.317708 | 102 | 0.521388 | [
"MIT"
] | karanbirsingh/accessibility-insights-windows | src/AccessibilityInsights.SharedUx/Highlighting/ImageOverlayDriver.cs | 5,630 | C# |
/*************************************************************************
* Copyright © 2021 Mogoson. All rights reserved.
*------------------------------------------------------------------------
* File : ITimeCurve.cs
* Description : Define time curve interface.
*------------------------------------------------------------------------
* Author : Mogoson
* Version : 1.0
* Date : 7/24/2021
* Description : Initial development version.
*************************************************************************/
using UnityEngine;
namespace MGS.Curve
{
/// <summary>
/// Interface of time curve.
/// </summary>
public interface ITimeCurve : ICurve
{
/// <summary>
/// Evaluate the curve at time.
/// </summary>
/// <param name="t">The time within the curve you want to evaluate (the horizontal axis in the curve graph).</param>
/// <returns>The value of the curve, at the point in time specified.</returns>
Vector3 Evaluate(float t);
}
} | 36.758621 | 124 | 0.425891 | [
"Apache-2.0"
] | mogoson/MGS-Animation | UnityProject/Assets/MGS.Packages/Curve/Scripts/TimeCurve/Interface/ITimeCurve.cs | 1,069 | C# |
#if USE_UNI_LUA
using LuaAPI = UniLua.Lua;
using RealStatePtr = UniLua.ILuaState;
using LuaCSFunction = UniLua.CSharpFunctionDelegate;
#else
using LuaAPI = XLua.LuaDLL.Lua;
using RealStatePtr = System.IntPtr;
using LuaCSFunction = XLua.LuaDLL.lua_CSFunction;
#endif
using XLua;
using System.Collections.Generic;
namespace XLua.CSObjectWrap
{
using Utils = XLua.Utils;
public class XLuaCSObjectWrapDCETModelUnitInfoWrapWrap
{
public static void __Register(RealStatePtr L)
{
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
System.Type type = typeof(XLua.CSObjectWrap.DCETModelUnitInfoWrap);
Utils.BeginObjectRegister(type, L, translator, 0, 0, 0, 0);
Utils.EndObjectRegister(type, L, translator, null, null,
null, null, null);
Utils.BeginClassRegister(type, L, __CreateInstance, 2, 0, 0);
Utils.RegisterFunc(L, Utils.CLS_IDX, "__Register", _m___Register_xlua_st_);
Utils.EndClassRegister(type, L, translator);
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int __CreateInstance(RealStatePtr L)
{
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
if(LuaAPI.lua_gettop(L) == 1)
{
XLua.CSObjectWrap.DCETModelUnitInfoWrap gen_ret = new XLua.CSObjectWrap.DCETModelUnitInfoWrap();
translator.Push(L, gen_ret);
return 1;
}
}
catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
return LuaAPI.luaL_error(L, "invalid arguments to XLua.CSObjectWrap.DCETModelUnitInfoWrap constructor!");
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _m___Register_xlua_st_(RealStatePtr L)
{
try {
{
System.IntPtr _L = LuaAPI.lua_touserdata(L, 1);
XLua.CSObjectWrap.DCETModelUnitInfoWrap.__Register( _L );
return 0;
}
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
}
}
}
| 23.463636 | 117 | 0.554049 | [
"MIT"
] | zxsean/DCET | Unity/Assets/Model/XLua/Gen/XLuaCSObjectWrapDCETModelUnitInfoWrapWrap.cs | 2,583 | C# |
namespace Standard.IO.Compression
{
/// <summary>
/// Various compression levels applicable to the LZ4 algorithm. Higher levels offer better compression
/// ratios, but at the expense of slower speed.
/// </summary>
public enum LZ4CompressionLevel
{
/// <summary>
/// Compress data using the `Fast` mode (level 0).
/// </summary>
Level0 = 0,
/// <summary>
/// Compress data using `High Compress` mode (level 3).
/// </summary>
Level3 = 3,
/// <summary>
/// Compress data using `High Compress` mode (level 4).
/// </summary>
Level4 = 4,
/// <summary>
/// Compress data using `High Compress` mode (level 5).
/// </summary>
Level5 = 5,
/// <summary>
/// Compress data using `High Compress` mode (level 6).
/// </summary>
Level6 = 6,
/// <summary>
/// Compress data using `High Compress` mode (level 7).
/// </summary>
Level7 = 7,
/// <summary>
/// Compress data using `High Compress` mode (level 8).
/// </summary>
Level8 = 8,
/// <summary>
/// Compress data using `High Compress` mode (level 9).
/// </summary>
Level9 = 9,
/// <summary>
/// Compress data using `Optimal Compress` mode (level 10).
/// </summary>
Level10 = 10,
/// <summary>
/// Compress data using `Optimal Compress` mode (level 11).
/// </summary>
Level11 = 11,
/// <summary>
/// Compress data using `Optimal Compress` mode (level 12).
/// </summary>
Level12 = 12,
/// <summary>
/// Minimum compression ratio. This compression level compress data at the fastest speed, but smaller compressed size
/// can be achieved using a higher compression level.
/// </summary>
/// <remarks>
/// This is an alias to <see cref="Level0"/>.
/// </remarks>
Min = Level0,
/// <summary>
/// Maximum compression ratio. This compression level offers the smallest compressed size, but takes the longest time.
/// </summary>
/// <remarks>
/// This is an alias to <see cref="Level12"/>.
/// </remarks>
Max = Level12,
}
}
| 28.158537 | 126 | 0.532698 | [
"Apache-2.0",
"MIT"
] | SilviaHyde/standard | src/Standard.IO.Compression.LZ4/Source/Standard/IO/Compression/LZ4CompressionLevel.cs | 2,311 | 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.ApiManagement
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Microsoft.Rest.Azure.OData;
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for ApiIssueCommentOperations.
/// </summary>
public static partial class ApiIssueCommentOperationsExtensions
{
/// <summary>
/// Lists all comments for the Issue assosiated with the specified API.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='apiId'>
/// API identifier. Must be unique in the current API Management service
/// instance.
/// </param>
/// <param name='issueId'>
/// Issue identifier. Must be unique in the current API Management service
/// instance.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
public static IPage<IssueCommentContract> ListByService(this IApiIssueCommentOperations operations, string resourceGroupName, string serviceName, string apiId, string issueId, ODataQuery<IssueCommentContract> odataQuery = default(ODataQuery<IssueCommentContract>))
{
return operations.ListByServiceAsync(resourceGroupName, serviceName, apiId, issueId, odataQuery).GetAwaiter().GetResult();
}
/// <summary>
/// Lists all comments for the Issue assosiated with the specified API.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='apiId'>
/// API identifier. Must be unique in the current API Management service
/// instance.
/// </param>
/// <param name='issueId'>
/// Issue identifier. Must be unique in the current API Management service
/// instance.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<IssueCommentContract>> ListByServiceAsync(this IApiIssueCommentOperations operations, string resourceGroupName, string serviceName, string apiId, string issueId, ODataQuery<IssueCommentContract> odataQuery = default(ODataQuery<IssueCommentContract>), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByServiceWithHttpMessagesAsync(resourceGroupName, serviceName, apiId, issueId, odataQuery, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets the entity state (Etag) version of the issue Comment for an API
/// specified by its identifier.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='apiId'>
/// API identifier. Must be unique in the current API Management service
/// instance.
/// </param>
/// <param name='issueId'>
/// Issue identifier. Must be unique in the current API Management service
/// instance.
/// </param>
/// <param name='commentId'>
/// Comment identifier within an Issue. Must be unique in the current Issue.
/// </param>
public static ApiIssueCommentGetEntityTagHeaders GetEntityTag(this IApiIssueCommentOperations operations, string resourceGroupName, string serviceName, string apiId, string issueId, string commentId)
{
return operations.GetEntityTagAsync(resourceGroupName, serviceName, apiId, issueId, commentId).GetAwaiter().GetResult();
}
/// <summary>
/// Gets the entity state (Etag) version of the issue Comment for an API
/// specified by its identifier.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='apiId'>
/// API identifier. Must be unique in the current API Management service
/// instance.
/// </param>
/// <param name='issueId'>
/// Issue identifier. Must be unique in the current API Management service
/// instance.
/// </param>
/// <param name='commentId'>
/// Comment identifier within an Issue. Must be unique in the current Issue.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ApiIssueCommentGetEntityTagHeaders> GetEntityTagAsync(this IApiIssueCommentOperations operations, string resourceGroupName, string serviceName, string apiId, string issueId, string commentId, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetEntityTagWithHttpMessagesAsync(resourceGroupName, serviceName, apiId, issueId, commentId, null, cancellationToken).ConfigureAwait(false))
{
return _result.Headers;
}
}
/// <summary>
/// Gets the details of the issue Comment for an API specified by its
/// identifier.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='apiId'>
/// API identifier. Must be unique in the current API Management service
/// instance.
/// </param>
/// <param name='issueId'>
/// Issue identifier. Must be unique in the current API Management service
/// instance.
/// </param>
/// <param name='commentId'>
/// Comment identifier within an Issue. Must be unique in the current Issue.
/// </param>
public static IssueCommentContract Get(this IApiIssueCommentOperations operations, string resourceGroupName, string serviceName, string apiId, string issueId, string commentId)
{
return operations.GetAsync(resourceGroupName, serviceName, apiId, issueId, commentId).GetAwaiter().GetResult();
}
/// <summary>
/// Gets the details of the issue Comment for an API specified by its
/// identifier.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='apiId'>
/// API identifier. Must be unique in the current API Management service
/// instance.
/// </param>
/// <param name='issueId'>
/// Issue identifier. Must be unique in the current API Management service
/// instance.
/// </param>
/// <param name='commentId'>
/// Comment identifier within an Issue. Must be unique in the current Issue.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IssueCommentContract> GetAsync(this IApiIssueCommentOperations operations, string resourceGroupName, string serviceName, string apiId, string issueId, string commentId, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, serviceName, apiId, issueId, commentId, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates a new Comment for the Issue in an API or updates an existing one.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='apiId'>
/// API identifier. Must be unique in the current API Management service
/// instance.
/// </param>
/// <param name='issueId'>
/// Issue identifier. Must be unique in the current API Management service
/// instance.
/// </param>
/// <param name='commentId'>
/// Comment identifier within an Issue. Must be unique in the current Issue.
/// </param>
/// <param name='parameters'>
/// Create parameters.
/// </param>
/// <param name='ifMatch'>
/// ETag of the Issue Entity. ETag should match the current entity state from
/// the header response of the GET request or it should be * for unconditional
/// update.
/// </param>
public static IssueCommentContract CreateOrUpdate(this IApiIssueCommentOperations operations, string resourceGroupName, string serviceName, string apiId, string issueId, string commentId, IssueCommentContract parameters, string ifMatch = default(string))
{
return operations.CreateOrUpdateAsync(resourceGroupName, serviceName, apiId, issueId, commentId, parameters, ifMatch).GetAwaiter().GetResult();
}
/// <summary>
/// Creates a new Comment for the Issue in an API or updates an existing one.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='apiId'>
/// API identifier. Must be unique in the current API Management service
/// instance.
/// </param>
/// <param name='issueId'>
/// Issue identifier. Must be unique in the current API Management service
/// instance.
/// </param>
/// <param name='commentId'>
/// Comment identifier within an Issue. Must be unique in the current Issue.
/// </param>
/// <param name='parameters'>
/// Create parameters.
/// </param>
/// <param name='ifMatch'>
/// ETag of the Issue Entity. ETag should match the current entity state from
/// the header response of the GET request or it should be * for unconditional
/// update.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IssueCommentContract> CreateOrUpdateAsync(this IApiIssueCommentOperations operations, string resourceGroupName, string serviceName, string apiId, string issueId, string commentId, IssueCommentContract parameters, string ifMatch = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, serviceName, apiId, issueId, commentId, parameters, ifMatch, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes the specified comment from an Issue.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='apiId'>
/// API identifier. Must be unique in the current API Management service
/// instance.
/// </param>
/// <param name='issueId'>
/// Issue identifier. Must be unique in the current API Management service
/// instance.
/// </param>
/// <param name='commentId'>
/// Comment identifier within an Issue. Must be unique in the current Issue.
/// </param>
/// <param name='ifMatch'>
/// ETag of the Issue Entity. ETag should match the current entity state from
/// the header response of the GET request or it should be * for unconditional
/// update.
/// </param>
public static void Delete(this IApiIssueCommentOperations operations, string resourceGroupName, string serviceName, string apiId, string issueId, string commentId, string ifMatch)
{
operations.DeleteAsync(resourceGroupName, serviceName, apiId, issueId, commentId, ifMatch).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the specified comment from an Issue.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='apiId'>
/// API identifier. Must be unique in the current API Management service
/// instance.
/// </param>
/// <param name='issueId'>
/// Issue identifier. Must be unique in the current API Management service
/// instance.
/// </param>
/// <param name='commentId'>
/// Comment identifier within an Issue. Must be unique in the current Issue.
/// </param>
/// <param name='ifMatch'>
/// ETag of the Issue Entity. ETag should match the current entity state from
/// the header response of the GET request or it should be * for unconditional
/// update.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IApiIssueCommentOperations operations, string resourceGroupName, string serviceName, string apiId, string issueId, string commentId, string ifMatch, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.DeleteWithHttpMessagesAsync(resourceGroupName, serviceName, apiId, issueId, commentId, ifMatch, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Lists all comments for the Issue assosiated with the specified API.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<IssueCommentContract> ListByServiceNext(this IApiIssueCommentOperations operations, string nextPageLink)
{
return operations.ListByServiceNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Lists all comments for the Issue assosiated with the specified API.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<IssueCommentContract>> ListByServiceNextAsync(this IApiIssueCommentOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByServiceNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| 49.032663 | 359 | 0.564899 | [
"MIT"
] | 216Giorgiy/azure-sdk-for-net | src/SDKs/ApiManagement/Management.ApiManagement/Generated/ApiIssueCommentOperationsExtensions.cs | 19,515 | C# |
using System;
namespace Pattern1.Fasade
{
public class Fasade
{
private SubsystemOne one;
private SubsystemTwo two;
private SubsystemThree three;
private SubsystemFour four;
private Fasade()
{
one = new SubsystemOne();
two = new SubsystemTwo();
three = new SubsystemThree();
four = new SubsystemFour();
}
public static Fasade CreateInstance()
{
return new Fasade();
}
public void GeneralUserFunctionA()
{
Console.WriteLine("GeneralUserFunctionA method calls ----");
one.MethodOne();
two.MethodTwo();
four.MethodFour();
}
public void GeneralUserFunctionB()
{
Console.WriteLine("GeneralUserFunctionB method calls ----");
one.MethodOne();
two.MethodTwo();
three.MethodThree();
four.MethodFour();
two.MethodTwo();
one.MethodOne();
}
}
}
| 23.8 | 72 | 0.51634 | [
"MIT"
] | MarinMarinov/High-Quality-Code | HW15StructuralDesignPatterns/Pattern1.Fasade/Fasade.cs | 1,073 | C# |
using System;
using ActivityMonitor.Application;
using Microsoft.Win32;
namespace ActMon.SettingsManager
{
public class Settings
{
private const string regRootHKLM = @"HKEY_LOCAL_MACHINE";
private const string regRootHKCU = @"HKEY_CURRENT_USER";
private const string regKey = @"Software\ActMon\Settings";
private const string regKeyGPO = @"Software\Policies\Sequence Software\ActMon";
private const string regKeyRun = @"Software\Microsoft\Windows\CurrentVersion\Run";
private bool _lockSettings;
private bool _hideMenuExit;
private bool _runHidden;
private string _dbServer;
private string _dbDatabase;
private string _dbUsername;
private string _dbPassword;
private string _regBase;
private string _regBaseGPO;
private string _appExe;
private int _dbDumpRate;
public bool lockSettings
{
get => _lockSettings;
}
public bool Autostart
{
get; set;
}
public string DBServer
{
get => _dbServer;
set
{
_dbServer = value;
}
}
public string DBDatabase
{
get => _dbDatabase;
set
{
_dbDatabase = value;
}
}
public string DBUsername
{
get => _dbUsername;
set
{
_dbUsername = value;
}
}
public string DBPassword
{
get => _dbPassword;
set
{
_dbPassword = value;
}
}
public bool LockSettings
{
get => _lockSettings;
}
public bool RunHidden
{
get => _runHidden;
}
public bool HideMenuExit
{
get => _hideMenuExit;
}
public int DBDumprate
{
get => _dbDumpRate;
}
public Settings()
{
_regBase = regRootHKCU + "\\" + regKey;
_regBaseGPO = regRootHKCU + "\\" + regKeyGPO;
_appExe = new System.Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).LocalPath;
ReadSettings();
}
/// <summary>
/// Read Settings from Registry
/// Settings are controllable from Group Policy
/// </summary>
public void ReadSettings()
{
_dbDumpRate = 30;
string strRegBaseKey = _regBase;
try {
//Settings Locked Via GPO
_lockSettings = regBool(Registry.GetValue(_regBaseGPO, "LockSettings", 0));
_hideMenuExit = regBool(Registry.GetValue(_regBaseGPO, "HideMenuExit", 0));
_runHidden = regBool(Registry.GetValue(_regBaseGPO, "RunHidden", 0));
if (_lockSettings) strRegBaseKey = _regBaseGPO;
_dbServer = (string)Registry.GetValue(strRegBaseKey, "DatabaseServer", "");
_dbDatabase = (string)Registry.GetValue(strRegBaseKey, "DatabaseCatalog", "");
_dbUsername = (string)Registry.GetValue(strRegBaseKey, "DatabaseUsername", "");
_dbPassword = (string)Registry.GetValue(strRegBaseKey, "DatabasePassword", "");
_dbDumpRate = regInt(Registry.GetValue(strRegBaseKey, "DatabaseDumpInterval", 30));
string regValue = (string)Registry.GetValue(regRootHKCU + "\\" + regKeyRun, "ActMon", "ActMon");
if (regValue!=null) {
if (regValue.ToLower() == _appExe.ToLower())
Autostart = true;
}
}
catch (NullReferenceException)
{
Console.WriteLine("Error reading configuration.");
}
}
private int regInt(object intValue)
{
return (int)intValue;
}
private bool regBool(object intValue)
{
if (intValue == null) intValue = 0;
bool boolvalue = (int)intValue != 0;
return boolvalue;
}
public void WriteSettings()
{
try {
Registry.SetValue(_regBase, "DatabaseServer", _dbServer);
Registry.SetValue(_regBase, "DatabaseCatalog", _dbDatabase);
Registry.SetValue(_regBase, "DatabaseUsername", _dbUsername);
Registry.SetValue(_regBase, "DatabasePassword", _dbPassword);
if (Autostart == false) {
using (RegistryKey key = Registry.CurrentUser.OpenSubKey(regKeyRun, true))
{
if (key != null)
key.DeleteValue("ActMon");
}
} else
{
Registry.SetValue(regRootHKCU + "\\" + regKeyRun, "ActMon", _appExe);
}
} catch
{
}
}
}
}
| 28.583333 | 112 | 0.509427 | [
"MIT"
] | bcmon/ActivityMonitor | ActMon/SettingsManager/Settings.cs | 5,147 | C# |
namespace SqlStreamStore
{
using System;
using System.Security.Cryptography;
using System.Text;
internal struct PostgresqlStreamId : IEquatable<PostgresqlStreamId>
{
public readonly string Id;
public readonly string IdOriginal;
public PostgresqlStreamId(string idOriginal)
{
Id = Guid.TryParse(idOriginal, out _)
? idOriginal
: ComputeHash(idOriginal);
IdOriginal = idOriginal;
}
private static string ComputeHash(string idOriginal)
{
using(var sha1 = SHA1.Create())
{
var hashBytes = sha1.ComputeHash(Encoding.UTF8.GetBytes(idOriginal));
return BitConverter.ToString(hashBytes).Replace("-", string.Empty);
}
}
public static readonly PostgresqlStreamId Deleted
= new PostgresqlStreamId(Streams.Deleted.DeletedStreamId);
public static bool operator ==(PostgresqlStreamId left, PostgresqlStreamId right) => left.Equals(right);
public static bool operator !=(PostgresqlStreamId left, PostgresqlStreamId right) => !left.Equals(right);
public bool Equals(PostgresqlStreamId other)
=> string.Equals(Id, other.Id) && string.Equals(IdOriginal, other.IdOriginal);
public override bool Equals(object obj) => obj is PostgresqlStreamId other && Equals(other);
public override int GetHashCode()
{
unchecked
{
return (Id.GetHashCode() * 397) ^ IdOriginal.GetHashCode();
}
}
public override string ToString() => IdOriginal;
}
} | 33.64 | 113 | 0.617717 | [
"MIT"
] | ArneSchoonvliet/SQLStreamStore | src/SqlStreamStore.Postgres/PostgresqlStreamId.cs | 1,684 | C# |
using System;
namespace Functors.Id.Applicative
{
public static class FunctionalExtensions
{
public static Id<T1> Ap<T, T1>(this Id<Func<T, T1>> @this, Id<T> fa) => @this.Map(f => fa.Cata(f));
}
public class Demo
{
public static void Run()
{
var chain = new Id<Func<int, Func<int, int>>>(x => y => x + y).Ap(new Id<int>(1)).Ap(new Id<int>(1));
chain.Cata(Console.WriteLine);
}
}
public class Id<T>
{
public T Value { get; set; }
public Id(T value) => Value = value;
public Id<T1> Map<T1>(Func<T, T1> f) => new Id<T1>(f(Value));
public T1 Cata<T1>(Func<T, T1> callback) => callback(Value);
public void Cata(Action<T> callback) => callback(Value);
}
} | 28.107143 | 113 | 0.542567 | [
"MIT"
] | dimitris-papadimitriou-chr/FunctionalCSharpWithCategories | 4_Functors/Id.Applicative.cs | 789 | C# |
using Microsoft.Extensions.Configuration;
using Castle.MicroKernel.Registration;
using Abp.Events.Bus;
using Abp.Modules;
using Abp.Reflection.Extensions;
using Dyan.OceanAngular.Configuration;
using Dyan.OceanAngular.EntityFrameworkCore;
using Dyan.OceanAngular.Migrator.DependencyInjection;
namespace Dyan.OceanAngular.Migrator
{
[DependsOn(typeof(OceanAngularEntityFrameworkModule))]
public class OceanAngularMigratorModule : AbpModule
{
private readonly IConfigurationRoot _appConfiguration;
public OceanAngularMigratorModule(OceanAngularEntityFrameworkModule abpProjectNameEntityFrameworkModule)
{
abpProjectNameEntityFrameworkModule.SkipDbSeed = true;
_appConfiguration = AppConfigurations.Get(
typeof(OceanAngularMigratorModule).GetAssembly().GetDirectoryPathOrNull()
);
}
public override void PreInitialize()
{
Configuration.DefaultNameOrConnectionString = _appConfiguration.GetConnectionString(
OceanAngularConsts.ConnectionStringName
);
Configuration.BackgroundJobs.IsJobExecutionEnabled = false;
Configuration.ReplaceService(
typeof(IEventBus),
() => IocManager.IocContainer.Register(
Component.For<IEventBus>().Instance(NullEventBus.Instance)
)
);
}
public override void Initialize()
{
IocManager.RegisterAssemblyByConvention(typeof(OceanAngularMigratorModule).GetAssembly());
ServiceCollectionRegistrar.Register(IocManager);
}
}
}
| 34.729167 | 112 | 0.692861 | [
"MIT"
] | dyanwork/Dyan.CreditSystem | aspnet-core/src/Dyan.OceanAngular.Migrator/OceanAngularMigratorModule.cs | 1,667 | C# |
//-----------------------------------------------------------------------------
// (c) 2019 Ruzsinszki Gábor
// This code is licensed under MIT license (see LICENSE for details)
//-----------------------------------------------------------------------------
using System.Xml.Serialization;
namespace BookGen.Domain.Epub
{
[XmlRoot(ElementName = "creator", Namespace = "http://purl.org/dc/elements/1.1/")]
public class Creator
{
[XmlAttribute(AttributeName = "id")]
public string? Id { get; set; }
[XmlText]
public string? Text { get; set; }
}
}
| 31.368421 | 86 | 0.464765 | [
"MIT"
] | webmaster442/BookGen | BookGen/Domain/Epub/Creator.cs | 599 | C# |
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.ServiceModel;
using System.Web.Http;
using System.Web.Http.SelfHost;
using MashupSample.Models;
namespace MashupSample
{
/// <summary>
/// This sample shows how to asynchronously access multiple remote sites from
/// within an ApiController action. Each time the action is hit, the requests
/// are performed.
/// </summary>
class Program
{
static readonly Uri _baseAddress = new Uri("http://localhost:50231/");
static void Main(string[] args)
{
HttpSelfHostServer server = null;
try
{
// Create configuration
var config = new HttpSelfHostConfiguration(_baseAddress);
config.HostNameComparisonMode = HostNameComparisonMode.Exact;
// Add a route
config.Routes.MapHttpRoute(
name: "default",
routeTemplate: "api/{controller}/{id}",
defaults: new { controller = "Home", id = RouteParameter.Optional });
// Create server
server = new HttpSelfHostServer(config);
// Start server
server.OpenAsync().Wait();
RunClient();
Console.WriteLine("Server listening at {0}", _baseAddress);
Console.WriteLine("Hit ENTER to exit");
Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine("Could not start server: {0}", e.GetBaseException().Message);
Console.WriteLine("Hit ENTER to exit...");
Console.ReadLine();
}
finally
{
if (server != null)
{
// Close server
server.CloseAsync().Wait();
}
}
}
static async void RunClient()
{
HttpClient client = new HttpClient();
// Get the results for a query for topic 'microsoft'
Uri address = new Uri(_baseAddress, "/api/mashup?topic=microsoft");
HttpResponseMessage response = await client.GetAsync(address);
// Check that response was successful or throw exception
response.EnsureSuccessStatusCode();
// Read response asynchronously as string and write out
List<Story> content = await response.Content.ReadAsAsync<List<Story>>();
Console.WriteLine("Got result querying for 'microsoft' against mashup service");
foreach (Story story in content)
{
Console.WriteLine("Story from {0}: {1}", story.Source, story.Description);
}
}
}
}
| 32.848837 | 95 | 0.547257 | [
"Apache-2.0"
] | ASCITSOL/asp.net | samples/aspnet/WebApi/MashupSample/Program.cs | 2,827 | C# |
/*!
@file JumpPointFinder.cs
@author Woong Gyu La a.k.a Chris. <juhgiyo@gmail.com>
<http://github.com/juhgiyo/eppathfinding.cs>
@date July 16, 2013
@brief Param Base Interface
@version 2.0
@section LICENSE
The MIT License (MIT)
Copyright (c) 2013 Woong Gyu La <juhgiyo@gmail.com>
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.
@section DESCRIPTION
An Interface for the Jump Point Search Algorithm Class.
*/
namespace EpPathFinding.cs
{
public delegate float HeuristicDelegate(int iDx, int iDy);
public abstract class ParamBase
{
protected ParamBase(BaseGrid grid, GridPos startPos, GridPos endPos, DiagonalMovement diagonalMovement, HeuristicMode mode) : this(grid, diagonalMovement, mode)
{
startNode = searchGrid.GetNodeAt(startPos.X, startPos.Y);
endNode = searchGrid.GetNodeAt(endPos.X, endPos.Y);
if (startNode == null)
{
startNode = new Node(startPos.X, startPos.Y, true);
}
if (endNode == null)
{
endNode = new Node(endPos.X, endPos.Y, true);
}
}
protected ParamBase(BaseGrid grid, DiagonalMovement diagonalMovement, HeuristicMode mode)
{
SetHeuristic(mode);
searchGrid = grid;
DiagonalMovement = diagonalMovement;
startNode = null;
endNode = null;
}
protected ParamBase(ParamBase param)
{
searchGrid = param.searchGrid;
DiagonalMovement = param.DiagonalMovement;
startNode = param.startNode;
endNode = param.endNode;
}
internal abstract void ResetInternal(GridPos startPos, GridPos endPos, BaseGrid searchGrid = null);
public void Reset(GridPos startPos, GridPos endPos, BaseGrid _searchGrid = null)
{
ResetInternal(startPos, endPos, _searchGrid);
startNode = null;
endNode = null;
if (_searchGrid != null)
{
searchGrid = _searchGrid;
}
searchGrid.Reset();
startNode = searchGrid.GetNodeAt(startPos.X, startPos.Y);
endNode = searchGrid.GetNodeAt(endPos.X, endPos.Y);
if (startNode == null)
{
startNode = new Node(startPos.X, startPos.Y, true);
}
if (endNode == null)
{
endNode = new Node(endPos.X, endPos.Y, true);
}
}
public DiagonalMovement DiagonalMovement;
public HeuristicDelegate HeuristicFunc
=> heuristic;
public BaseGrid SearchGrid
=> searchGrid;
public Node StartNode
=> startNode;
public Node EndNode
=> endNode;
public void SetHeuristic(HeuristicMode mode)
=> heuristic = mode switch
{
HeuristicMode.Manhattan => new HeuristicDelegate(Heuristic.Manhattan),
HeuristicMode.Euclidean => new HeuristicDelegate(Heuristic.Euclidean),
HeuristicMode.Chebyshev => new HeuristicDelegate(Heuristic.Chebyshev),
_ => new HeuristicDelegate(Heuristic.Euclidean),
};
protected BaseGrid searchGrid;
protected Node startNode;
protected Node endNode;
protected HeuristicDelegate heuristic;
}
}
| 27.970588 | 162 | 0.740799 | [
"Unlicense"
] | LeftofZen/EpPathFinding.cs | EpPathFinding.cs/EpPathFinding.cs/PathFinder/ParamBase.cs | 3,806 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.DataMigration.V20171115Preview.Outputs
{
/// <summary>
/// Database level result for Sql Server to Azure Sql DB migration.
/// </summary>
[OutputType]
public sealed class MigrateSqlServerSqlDbTaskOutputDatabaseLevelResponse
{
/// <summary>
/// Name of the item
/// </summary>
public readonly string DatabaseName;
/// <summary>
/// Migration end time
/// </summary>
public readonly string EndedOn;
/// <summary>
/// Number of database/object errors.
/// </summary>
public readonly double ErrorCount;
/// <summary>
/// Wildcard string prefix to use for querying all errors of the item
/// </summary>
public readonly string ErrorPrefix;
/// <summary>
/// Migration exceptions and warnings.
/// </summary>
public readonly ImmutableArray<Outputs.ReportableExceptionResponse> ExceptionsAndWarnings;
/// <summary>
/// Result identifier
/// </summary>
public readonly string Id;
/// <summary>
/// Migration progress message
/// </summary>
public readonly string Message;
/// <summary>
/// Number of objects
/// </summary>
public readonly double NumberOfObjects;
/// <summary>
/// Number of successfully completed objects
/// </summary>
public readonly double NumberOfObjectsCompleted;
/// <summary>
/// Summary of object results in the migration
/// </summary>
public readonly ImmutableDictionary<string, Outputs.DataItemMigrationSummaryResultResponse> ObjectSummary;
/// <summary>
/// Wildcard string prefix to use for querying all sub-tem results of the item
/// </summary>
public readonly string ResultPrefix;
/// <summary>
/// Result type
/// Expected value is 'DatabaseLevelOutput'.
/// </summary>
public readonly string ResultType;
/// <summary>
/// Migration stage that this database is in
/// </summary>
public readonly string Stage;
/// <summary>
/// Migration start time
/// </summary>
public readonly string StartedOn;
/// <summary>
/// Current state of migration
/// </summary>
public readonly string State;
/// <summary>
/// Status message
/// </summary>
public readonly string StatusMessage;
[OutputConstructor]
private MigrateSqlServerSqlDbTaskOutputDatabaseLevelResponse(
string databaseName,
string endedOn,
double errorCount,
string errorPrefix,
ImmutableArray<Outputs.ReportableExceptionResponse> exceptionsAndWarnings,
string id,
string message,
double numberOfObjects,
double numberOfObjectsCompleted,
ImmutableDictionary<string, Outputs.DataItemMigrationSummaryResultResponse> objectSummary,
string resultPrefix,
string resultType,
string stage,
string startedOn,
string state,
string statusMessage)
{
DatabaseName = databaseName;
EndedOn = endedOn;
ErrorCount = errorCount;
ErrorPrefix = errorPrefix;
ExceptionsAndWarnings = exceptionsAndWarnings;
Id = id;
Message = message;
NumberOfObjects = numberOfObjects;
NumberOfObjectsCompleted = numberOfObjectsCompleted;
ObjectSummary = objectSummary;
ResultPrefix = resultPrefix;
ResultType = resultType;
Stage = stage;
StartedOn = startedOn;
State = state;
StatusMessage = statusMessage;
}
}
}
| 30.891304 | 114 | 0.592306 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/DataMigration/V20171115Preview/Outputs/MigrateSqlServerSqlDbTaskOutputDatabaseLevelResponse.cs | 4,263 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.