content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2 values |
|---|---|---|---|---|---|---|---|---|
using System.ComponentModel.DataAnnotations;
using todoCore3.Api.Models.Auth.Entities;
namespace todoCore3.Api.Models.Auth
{
public class UpdateAccountRequest
{
private string _password;
private string _confirmPassword;
private string _role;
private string _email;
public string Gender { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
[EnumDataType(typeof(Role))]
public string Role
{
get => _role;
set => _role = replaceEmptyWithNull(value);
}
[EmailAddress]
public string Email
{
get => _email;
set => _email = replaceEmptyWithNull(value);
}
[MinLength(6)]
public string Password
{
get => _password;
set => _password = replaceEmptyWithNull(value);
}
[Compare("Password")]
public string ConfirmPassword
{
get => _confirmPassword;
set => _confirmPassword = replaceEmptyWithNull(value);
}
private string replaceEmptyWithNull(string value)
{
// replace empty string with null to make field optional
return string.IsNullOrEmpty(value) ? null : value;
}
}
}
| 22.519231 | 62 | 0.653288 | [
"MIT"
] | shockzinfinity/todo-app-complicated | todoCore3.Api/Models/Auth/UpdateAccountRequest.cs | 1,171 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Unlocks : MonoBehaviour
{
#region Singleton
public static Unlocks instance;
private void Awake()
{
instance = this;
}
#endregion
public List<Reward> rewards;
public Item armyDefeatItem;
public Item castleDefeatItem;
public Item wizardItem;
public bool armyDefeat;
public bool castleDefeat;
public Item armyItem;
public Item castleItem;
public Item enemiesTriggerItem01;
public Item enemiesTriggerItem02;
public Item enemiesTriggerItem03;
public Item enemiesTriggerItem04;
private bool wizardAdded = false;
private bool enemiesAdded = false;
private Inventory inventory;
private void Start()
{
inventory = Inventory.instance;
rewards = new List<Reward>(Resources.LoadAll<Reward>("Rewards"));
}
private void Update()
{
Reward[] rewardsArray = rewards.ToArray();
foreach (Reward reward in rewardsArray)
{
if (reward.itemsRequired == inventory.GetAmount() && reward.itemsRequired != 0)
{
Unlock(reward);
rewards.Remove(reward);
}
}
}
void Unlock (Reward reward)
{
foreach (Item item in reward.items)
{
Debug.Log(item.name + " UNLOCKED!!!");
Discoveries.instance.Discover(item);
Inventory.instance.AddItem(item, false);
}
}
public void OnItemAdded (Item item)
{
if (!wizardAdded)
{
if (item == castleDefeatItem)
castleDefeat = true;
if (item == armyDefeatItem)
armyDefeat = true;
if (castleDefeat && armyDefeat)
{
wizardAdded = true;
Discoveries.instance.Discover(wizardItem);
Inventory.instance.AddItem(wizardItem, false);
}
}
if (!enemiesAdded)
{
if( item == enemiesTriggerItem01 || item == enemiesTriggerItem02 ||
item == enemiesTriggerItem03 || item == enemiesTriggerItem04)
{
enemiesAdded = true;
Discoveries.instance.Discover(castleItem);
Inventory.instance.AddItem(castleItem, false);
Discoveries.instance.Discover(armyItem);
Inventory.instance.AddItem(armyItem, false);
}
}
}
}
| 20.376238 | 82 | 0.707483 | [
"MIT"
] | cortexarts/Otter-Space-Prototype | Prototype/Assets/Scripts/UI/Unlocks.cs | 2,058 | C# |
using Content.Server.Administration;
using Content.Server.GameTicking.Presets;
using Content.Shared.Administration;
using Content.Shared.CCVar;
using Robust.Shared.Configuration;
using Robust.Shared.Console;
namespace Content.Server.GameTicking.Commands
{
[AdminCommand(AdminFlags.Round)]
public sealed class GoLobbyCommand : IConsoleCommand
{
public string Command => "golobby";
public string Description => "Enables the lobby and restarts the round.";
public string Help => $"Usage: {Command} / {Command} <preset>";
public void Execute(IConsoleShell shell, string argStr, string[] args)
{
GamePresetPrototype? preset = null;
var presetName = string.Join(" ", args);
var ticker = EntitySystem.Get<GameTicker>();
if (args.Length > 0)
{
if (!ticker.TryFindGamePreset(presetName, out preset))
{
shell.WriteLine($"No preset found with name {presetName}");
return;
}
}
var config = IoCManager.Resolve<IConfigurationManager>();
config.SetCVar(CCVars.GameLobbyEnabled, true);
ticker.RestartRound();
if (preset != null)
{
ticker.SetGamePreset(preset);
}
shell.WriteLine($"Enabling the lobby and restarting the round.{(preset == null ? "" : $"\nPreset set to {presetName}")}");
}
}
}
| 32.782609 | 134 | 0.592838 | [
"MIT"
] | 14th-Batallion-Marine-Corps/14-Marine-Corps | Content.Server/GameTicking/Commands/GoLobbyCommand.cs | 1,510 | C# |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Auth0.Core.Collections;
using Auth0.ManagementApi.Models;
namespace Auth0.ManagementApi.Clients
{
/// <summary>
/// Contains all the methods to call the /users endpoints.
/// </summary>
public interface IUsersClient
{
/// <summary>
/// Creates a new user.
/// </summary>
/// <param name="request">The <see cref="UserCreateRequest" /> containing the properties of the user to create.</param>
/// <returns></returns>
Task<User> CreateAsync(UserCreateRequest request);
/// <summary>
/// Deletes all users. Use with caution!
/// </summary>
/// <returns></returns>
Task DeleteAllAsync();
/// <summary>
/// Deletes a user.
/// </summary>
/// <param name="id">The id of the user to delete.</param>
Task DeleteAsync(string id);
/// <summary>
/// Deletes a user's multifactor provider.
/// </summary>
/// <param name="id">The id of the user who multi factor provider to delete.</param>
/// <param name="provider">The type of the multifactor provider. Supported values 'duo' or 'google-authenticator'</param>
/// <returns></returns>
Task DeleteMultifactorProviderAsync(string id, string provider);
/// <summary>
/// Lists or search for users based on criteria.
/// </summary>
/// <param name="page">The page number. Zero based.</param>
/// <param name="perPage">The amount of entries per page.</param>
/// <param name="includeTotals">True if a query summary must be included in the result.</param>
/// <param name="sort">The field to use for sorting. 1 == ascending and -1 == descending</param>
/// <param name="connection">Connection filter.</param>
/// <param name="fields">
/// A comma separated list of fields to include or exclude (depending on
/// <paramref name="includeFields" />) from the result, empty to retrieve all fields.
/// </param>
/// <param name="includeFields">
/// True if the fields specified are to be included in the result, false otherwise. Defaults to
/// true.
/// </param>
/// <param name="q">
/// Query in Lucene query string syntax.
/// </param>
/// <param name="searchEngine">
/// The version of the search engine to use.
/// Will default to v2 if no value is passed. Default will change to v3 on 2018/11/13.
/// For more info <a href="https://auth0.com/docs/users/search/v3#migrate-from-search-engine-v2-to-v3">see the online documentation</a>.
/// </param>
/// <returns></returns>
[Obsolete("Use GetAllAsync(GetUsersRequest) or GetAllAsync(GetUsersRequest, PaginationInfo) instead")]
Task<IPagedList<User>> GetAllAsync(int? page = null, int? perPage = null, bool? includeTotals = null, string sort = null, string connection = null, string fields = null,
bool? includeFields = null, string q = null, string searchEngine = null);
/// <summary>
/// Lists or search for users based on criteria.
/// </summary>
/// <param name="request">Specifies criteria to use when querying users.</param>
/// <returns>An <see cref="IPagedList{GetUsersRequest}"/> containing the list of users.</returns>
Task<IPagedList<User>> GetAllAsync(GetUsersRequest request);
/// <summary>
/// Lists or search for users based on criteria.
/// </summary>
/// <param name="request">Specifies criteria to use when querying users.</param>
/// <param name="pagination">Specifies pagination info to use when requesting paged results.</param>
/// <returns>An <see cref="IPagedList{GetUsersRequest}"/> containing the list of users.</returns>
Task<IPagedList<User>> GetAllAsync(GetUsersRequest request, PaginationInfo pagination);
/// <summary>
/// Gets a user.
/// </summary>
/// <param name="id">The id of the user to retrieve.</param>
/// <param name="fields">
/// A comma separated list of fields to include or exclude (depending on includeFields) from the
/// result, empty to retrieve all fields
/// </param>
/// <param name="includeFields">
/// true if the fields specified are to be included in the result, false otherwise (defaults to
/// true)
/// </param>
/// <returns>The <see cref="User" />.</returns>
Task<User> GetAsync(string id, string fields = null, bool includeFields = true);
/// <summary>
/// Retrieve every log event for a specific user id
/// </summary>
/// <param name="userId">The user id of the logs to retrieve</param>
/// <param name="page">The zero-based page number</param>
/// <param name="perPage">The amount of entries per page. Default: 50. Max value: 100</param>
/// <param name="sort">The field to use for sorting. Use field:order where order is 1 for ascending and -1 for descending. For example date:-1</param>
/// <param name="includeTotals">True if a query summary must be included in the result, false otherwise. Default false.</param>
/// <returns></returns>
[Obsolete("Use GetLogsAsync(GetUserLogsRequest) or GetLogsAsync(GetUserLogsRequest, PaginationInfo) instead")]
Task<IPagedList<LogEntry>> GetLogsAsync(string userId, int? page = null, int? perPage = null, string sort = null,
bool? includeTotals = null);
/// <summary>
/// Retrieve every log event for a specific user.
/// </summary>
/// <param name="request">Specifies criteria to use when querying logs for a user.</param>
/// <returns>An <see cref="IPagedList{LogEntry}"/> containing the log entries for the user.</returns>
Task<IPagedList<LogEntry>> GetLogsAsync(GetUserLogsRequest request);
/// <summary>
/// Retrieve every log event for a specific user.
/// </summary>
/// <param name="request">Specifies criteria to use when querying logs for a user.</param>
/// <param name="pagination">Specifies pagination info to use when requesting paged results.</param>
/// <returns>An <see cref="IPagedList{LogEntry}"/> containing the log entries for the user.</returns>
Task<IPagedList<LogEntry>> GetLogsAsync(GetUserLogsRequest request, PaginationInfo pagination);
/// <summary>
/// Gets all users by email address.
/// </summary>
/// <param name="email">The email address to search for</param>
/// <param name="fields"> A comma separated list of fields to include or exclude (depending on <see cref="includeFields"/>) from the result, null to retrieve all fields</param>
/// <param name="includeFields">true if the fields specified are to be included in the result, false otherwise. Defaults to true</param>
/// <returns></returns>
Task<IList<User>> GetUsersByEmailAsync(string email, string fields = null,
bool? includeFields = null);
/// <summary>
/// Links a secondary account to a primary account.
/// </summary>
/// <param name="id">The ID of the primary account.</param>
/// <param name="request">The <see cref="UserAccountLinkRequest" /> containing details of the secondary account to link.</param>
/// <returns></returns>
Task<IList<AccountLinkResponse>> LinkAccountAsync(string id, UserAccountLinkRequest request);
/// <summary>
/// Links a secondary account to a primary account.
/// </summary>
/// <param name="id">The ID of the primary account.</param>
/// <param name="primaryJwtToken">The JWT of the primary account.</param>
/// <param name="secondaryJwtToken">The JWT for the secondary account you wish to link.</param>
/// <returns></returns>
Task<IList<AccountLinkResponse>> LinkAccountAsync(string id, string primaryJwtToken, string secondaryJwtToken);
/// <summary>
/// Unlinks user accounts
/// </summary>
/// <param name="primaryUserId">The ID of the primary account.</param>
/// <param name="provider">The type of the identity provider.</param>
/// <param name="secondaryUserId">The ID for the secondary account</param>
/// <returns></returns>
Task<IList<AccountLinkResponse>> UnlinkAccountAsync(string primaryUserId, string provider, string secondaryUserId);
/// <summary>
/// Updates a user.
/// </summary>
/// <param name="id">The id of the user to update.</param>
/// <param name="request">The <see cref="UserUpdateRequest" /> containing the information you wish to update.</param>
/// <returns></returns>
Task<User> UpdateAsync(string id, UserUpdateRequest request);
}
} | 53.098837 | 184 | 0.621702 | [
"MIT"
] | Vaskinn/auth0.net | src/Auth0.ManagementApi/Clients/IUsersClient.cs | 9,135 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Web;
namespace AdminApp.Libraries
{
/// <summary>
/// 常用Http操作类集合
/// </summary>
public class HttpHelper
{
/// <summary>
/// Get方式获取远程资源
/// </summary>
/// <param name="url">请求地址</param>
/// <param name="headers">自定义Header集合</param>
/// <returns></returns>
public static string Get(string url, Dictionary<string, string> headers = default)
{
using HttpClientHandler handler = new();
using HttpClient client = new(handler);
client.DefaultRequestVersion = new Version("2.0");
if (headers != default)
{
foreach (var header in headers)
{
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
}
using var httpResponse = client.GetStringAsync(url);
return httpResponse.Result;
}
/// <summary>
/// Model对象转换为Uri网址参数形式
/// </summary>
/// <param name="obj">Model对象</param>
/// <param name="url">前部分网址</param>
/// <returns></returns>
public static string ModelToUriParam(object obj, string url = "")
{
PropertyInfo[] propertis = obj.GetType().GetProperties();
StringBuilder sb = new();
sb.Append(url);
sb.Append('?');
foreach (var p in propertis)
{
var v = p.GetValue(obj, null);
if (v == null)
continue;
sb.Append(p.Name);
sb.Append('=');
sb.Append(HttpUtility.UrlEncode(v.ToString()));
sb.Append('&');
}
sb.Remove(sb.Length - 1, 1);
return sb.ToString();
}
/// <summary>
/// Post数据到指定url
/// </summary>
/// <param name="url">Url</param>
/// <param name="data">数据</param>
/// <param name="type">form,data,json,xml</param>
/// <param name="headers">自定义Header集合</param>
/// <returns></returns>
public static string Post(string url, string data, string type, Dictionary<string, string> headers = default)
{
using HttpClientHandler handler = new();
using HttpClient client = new(handler);
client.DefaultRequestVersion = new Version("2.0");
if (headers != default)
{
foreach (var header in headers)
{
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
}
using Stream dataStream = new MemoryStream(Encoding.UTF8.GetBytes(data));
using HttpContent content = new StreamContent(dataStream);
if (type == "form")
{
content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
}
else if (type == "data")
{
content.Headers.ContentType = new MediaTypeHeaderValue("multipart/form-data");
}
else if (type == "json")
{
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
}
else if (type == "xml")
{
content.Headers.ContentType = new MediaTypeHeaderValue("text/xml");
}
content.Headers.ContentType.CharSet = "utf-8";
using var httpResponse = client.PostAsync(url, content);
return httpResponse.Result.Content.ReadAsStringAsync().Result;
}
/// <summary>
/// Post数据到指定url,异步执行
/// </summary>
/// <param name="url">Url</param>
/// <param name="data">数据</param>
/// <param name="type">form,data,json,xml</param>
/// <param name="headers">自定义Header集合</param>
/// <returns></returns>
public async static void PostAsync(string url, string data, string type, Dictionary<string, string> headers = default)
{
await Task.Run(() =>
{
Post(url, data, type, headers);
});
}
/// <summary>
/// Post文件和数据到指定url
/// </summary>
/// <param name="url"></param>
/// <param name="formItems">Post表单内容</param>
/// <param name="headers">自定义Header集合</param>
/// <returns></returns>
public static string PostForm(string url, List<PostFormItem> formItems, Dictionary<string, string> headers = default)
{
using HttpClientHandler handler = new();
using HttpClient client = new(handler);
client.DefaultRequestVersion = new Version("2.0");
if (headers != default)
{
foreach (var header in headers)
{
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
}
string boundary = "----" + DateTime.UtcNow.Ticks.ToString("x");
using MultipartFormDataContent formDataContent = new(boundary);
foreach (var item in formItems)
{
if (item.IsFile)
{
//上传文件
formDataContent.Add(new StreamContent(item.FileContent), item.Key, item.FileName);
}
else
{
//上传文本
formDataContent.Add(new StringContent(item.Value), item.Key);
}
}
using var httpResponse = client.PostAsync(url, formDataContent);
return httpResponse.Result.Content.ReadAsStringAsync().Result;
}
/// <summary>
/// Post 提交 From 表单数据模型结构
/// </summary>
public class PostFormItem
{
/// <summary>
/// 表单键,request["key"]
/// </summary>
public string Key { set; get; }
/// <summary>
/// 表单值,上传文件时忽略,request["key"].value
/// </summary>
public string Value { set; get; }
/// <summary>
/// 是否是文件
/// </summary>
public bool IsFile
{
get
{
if (FileContent == null || FileContent.Length == 0)
return false;
if (FileContent != null && FileContent.Length > 0 && string.IsNullOrWhiteSpace(FileName))
throw new Exception("上传文件时 FileName 属性值不能为空");
return true;
}
}
/// <summary>
/// 上传的文件名
/// </summary>
public string FileName { set; get; }
/// <summary>
/// 上传的文件内容
/// </summary>
public Stream FileContent { set; get; }
}
}
}
| 28.613546 | 126 | 0.493317 | [
"MIT"
] | berkerdong/NetEngine | AdminApp/Libraries/HttpHelper.cs | 7,484 | 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.AwsNative.FraudDetector.Outputs
{
[OutputType]
public sealed class EntityTypeTag
{
public readonly string Key;
public readonly string Value;
[OutputConstructor]
private EntityTypeTag(
string key,
string value)
{
Key = key;
Value = value;
}
}
}
| 22.5 | 81 | 0.637037 | [
"Apache-2.0"
] | AaronFriel/pulumi-aws-native | sdk/dotnet/FraudDetector/Outputs/EntityTypeTag.cs | 675 | C# |
using Verse;
namespace WaterworksMod
{
public abstract class CompWater : ThingComp
{
public CompProperties_Water Props => this.props as CompProperties_Water;
}
} | 20.333333 | 80 | 0.715847 | [
"Apache-2.0"
] | coder2000/WaterworksMod | Source/WaterworksMod/WaterworksMod/CompWater.cs | 185 | C# |
using FactFactory.TestsCommon;
using FactFactory.VersionedTests.CommonFacts;
using FactFactory.VersionedTests.VersionedFactRuleCollection.Env;
using GetcuReone.FactFactory.Entities;
using GetcuReone.GetcuTestAdapter;
using GetcuReone.GwtTestFramework.Helpers;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Linq;
using Collection = GetcuReone.FactFactory.Entities.FactRuleCollection;
namespace FactFactory.VersionedTests.VersionedFactRuleCollection
{
[TestClass]
public sealed class VersionedFactRuleCollectionTests : VersionedFactRuleCollectionTestBase
{
[TestMethod]
[TestCategory(TC.Projects.Versioned), TestCategory(TC.Objects.RuleCollection), TestCategory(GetcuReoneTC.Unit)]
[Description("Add rule.")]
[Timeout(Timeouts.Millisecond.FiveHundred)]
public void AddRuleTestCase()
{
GivenCreateCollection()
.When("Add rule.", collection =>
collection.Add((Fact1 fact) => new FactResult(fact.Value)))
.ThenIsTrue(colletion => colletion.Count == 1)
.Run();
}
[TestMethod]
[TestCategory(TC.Objects.RuleCollection), TestCategory(GetcuReoneTC.Unit)]
[Description("Get copied collection.")]
[Timeout(Timeouts.Millisecond.FiveHundred)]
public void Versioned_GetCopiedCollectionTestCase()
{
Collection originalsCollection = null;
FactRule factRule = null;
Given("Create collection.", () => originalsCollection = new Collection())
.And("Create rule", () =>
factRule = GetFactRule(() => new Fact1(default)))
.And("Add rule.", _ =>
originalsCollection.Add(factRule))
.When("Get copied.", _ =>
originalsCollection.Copy())
.ThenIsNotNull()
.AndAreNotEqual(originalsCollection)
.And("Check result.", copyCollection =>
{
Assert.AreEqual(originalsCollection.Count(), copyCollection.Count(), "Collections should have the same amount of rules");
Assert.AreEqual(factRule, copyCollection[0], "The collection contains another rule.");
})
.Run();
}
}
}
| 41.192982 | 141 | 0.629046 | [
"Apache-2.0"
] | GetcuReone/FactFactory | FactFactory/VersionedFactFactory/FactFactory.VersionedTests/VersionedFactRuleCollection/VersionedFactRuleCollectionTests.cs | 2,350 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Axe.Windows.Desktop.ColorContrastAnalyzer
{
public class Pixel
{
public int Row { get; private set; }
public int Column { get; private set; }
public Color Color { get; private set; }
public Pixel(Color color, int row, int column)
{
this.Row = row;
this.Column = column;
this.Color = color;
}
}
}
| 28.75 | 102 | 0.587826 | [
"MIT"
] | AdrianaDJ/axe-windows | src/Desktop/ColorContrastAnalyzer/Pixel.cs | 558 | C# |
using Autofac;
using JetBrains.Annotations;
using Lykke.Common;
using Lykke.Job.Staking.Settings;
using Lykke.Job.Staking.Settings.JobSettings;
using Lykke.RabbitMqBroker.Publisher;
using MAVN.Service.NotificationSystem.SubscriberContract;
using MAVN.Service.Staking.Contract.Events;
using MAVN.Service.Staking.DomainServices.RabbitMq.Subscribers;
using Lykke.SettingsReader;
namespace Lykke.Job.Staking.Modules
{
[UsedImplicitly]
public class RabbitMqModule : Module
{
private const string DefaultQueueName = "staking";
private const string NotificationSystemPushNotificationsExchangeName = "notificationsystem.command.pushnotification";
private const string TransactionFailedExchange = "lykke.wallet.transactionfailed";
private const string ReferralStakeReservedExchange = "lykke.wallet.referralstakereserved";
private const string ReferralStakeReleasedExchange = "lykke.wallet.referralstakereleased";
private const string ReferralStakeBurntExchange = "lykke.wallet.referralstakeburnt";
private const string ReferralStakeStatusUpdatedExchange = "lykke.wallet.referralstakestatusupdated";
private readonly RabbitMqSettings _settings;
public RabbitMqModule(IReloadingManager<AppSettings> appSettings)
{
_settings = appSettings.CurrentValue.StakingJob.RabbitMq;
}
protected override void Load(ContainerBuilder builder)
{
var rabbitMqConnString = _settings.RabbitMqConnectionString;
builder.RegisterJsonRabbitPublisher<ReferralStakeReservedEvent>(
rabbitMqConnString,
ReferralStakeReservedExchange);
builder.RegisterJsonRabbitPublisher<ReferralStakeReleasedEvent>(
rabbitMqConnString,
ReferralStakeReleasedExchange);
builder.RegisterJsonRabbitPublisher<ReferralStakeBurntEvent>(
rabbitMqConnString,
ReferralStakeBurntExchange);
builder.RegisterJsonRabbitPublisher<ReferralStakeStatusUpdatedEvent>(
rabbitMqConnString,
ReferralStakeStatusUpdatedExchange);
var notificationRabbitMqConnString = _settings.NotificationRabbitMqConnectionString;
builder.RegisterJsonRabbitPublisher<PushNotificationEvent>(
notificationRabbitMqConnString,
NotificationSystemPushNotificationsExchangeName);
builder.RegisterType<TransactionFailedSubscriber>()
.As<IStartStop>()
.WithParameter("connectionString", rabbitMqConnString)
.WithParameter("exchangeName", TransactionFailedExchange)
.WithParameter("queueName", DefaultQueueName)
.SingleInstance();
builder.RegisterType<TransactionSucceededSubscriber>()
.As<IStartStop>()
.WithParameter("connectionString", rabbitMqConnString)
.WithParameter("exchangeName", TransactionFailedExchange)
.WithParameter("queueName", DefaultQueueName)
.SingleInstance();
}
}
}
| 42.783784 | 125 | 0.709413 | [
"MIT"
] | HannaAndreevna/MAVN.Service.Staking | src/MAVN.Job.Staking/Modules/RabbitMqModule.cs | 3,168 | C# |
using System.Runtime.InteropServices;
using Microsoft.Git.CredentialManager.Interop.Posix.Native;
namespace Microsoft.Git.CredentialManager.Interop.MacOS.Native
{
public static class Termios_MacOS
{
[DllImport("libc", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
public static extern int tcgetattr(int fd, out termios_MacOS termios);
[DllImport("libc", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
public static extern int tcsetattr(int fd, SetActionFlags optActions, ref termios_MacOS termios);
}
[StructLayout(LayoutKind.Explicit)]
public struct termios_MacOS
{
// macOS has an array of 20 elements
private const int NCCS = 20;
// macOS uses unsigned 64-bit sized flags
[FieldOffset(0)] public InputFlags c_iflag;
[FieldOffset(8)] public OutputFlags c_oflag;
[FieldOffset(16)] public ControlFlags c_cflag;
[FieldOffset(24)] public LocalFlags c_lflag;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = NCCS)]
[FieldOffset(32)] public byte[] c_cc;
[FieldOffset(32 + NCCS)] public ulong c_ispeed;
[FieldOffset(32 + NCCS + 8)] public ulong c_ospeed;
}
}
| 37.235294 | 105 | 0.691943 | [
"MIT"
] | Shegox/Git-Credential-Manager-Core | src/shared/Microsoft.Git.CredentialManager/Interop/MacOS/Native/termios_MacOS.cs | 1,266 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reactive.Linq;
using System.Threading;
using System.Threading.Tasks;
using HttpMachine;
using ISimpleHttpListener.Rx.Enum;
using ISimpleHttpListener.Rx.Model;
using SimpleHttpListener.Rx.Helper;
using SimpleHttpListener.Rx.Model;
namespace SimpleHttpListener.Rx.Parser
{
internal class HttpStreamParser : IDisposable
{
private readonly HttpCombinedParser _parser;
private readonly HttpParserDelegate _parserDelegate;
private readonly ErrorCorrection[] _errorCorrections;
private readonly byte[] _correctLast4BytesReversed = {0x0a, 0x0d, 0x0a, 0x0d};
private readonly CircularBuffer<byte> _last4BytesCircularBuffer;
private IDisposable _disposableParserCompletion;
private bool IsDone { get; set; }
internal bool HasParsingError { get; private set; }
internal HttpStreamParser(HttpParserDelegate parserDelegate, params ErrorCorrection[] errorCorrections)
{
_errorCorrections = errorCorrections;
_parserDelegate = parserDelegate;
_parser = new HttpCombinedParser(parserDelegate);
_last4BytesCircularBuffer = new CircularBuffer<byte>(4);
}
internal async Task<IHttpRequestResponse> ParseAsync(Stream stream, CancellationToken ct)
{
_disposableParserCompletion = _parserDelegate.ParserCompletionObservable
.Subscribe(parserState =>
{
switch (parserState)
{
case ParserState.Start:
break;
case ParserState.Parsing:
break;
case ParserState.Completed:
break;
case ParserState.Failed:
HasParsingError = true;
break;
default:
throw new ArgumentOutOfRangeException(nameof(parserState), parserState, null);
}
},
ex => throw ex,
() =>
{
IsDone = true;
});
await Observable.While(
() => !HasParsingError && !IsDone,
Observable.FromAsync(() => ReadBytesAsync(stream, ct)))
.Catch<byte[], SimpleHttpListenerException>(ex =>
{
HasParsingError = true;
return Observable.Return(Enumerable.Empty<byte>().ToArray());
})
.Where(b => b != Enumerable.Empty<byte>().ToArray())
.Where(bSegment => bSegment.Length > 0)
.Select(b => new ArraySegment<byte>(b, 0, b.Length))
.Select(bSegment => _parser.Execute(bSegment));
_parser.Execute(default);
_parserDelegate.RequestResponse.MajorVersion = _parser.MajorVersion;
_parserDelegate.RequestResponse.MinorVersion = _parser.MinorVersion;
_parserDelegate.RequestResponse.ShouldKeepAlive = _parser.ShouldKeepAlive;
return _parserDelegate.RequestResponse;
}
private async Task<byte[]> ReadBytesAsync(Stream stream, CancellationToken ct)
{
if (_parserDelegate.RequestResponse.IsEndOfRequest || HasParsingError)
{
IsDone = true;
return Enumerable.Empty<byte>().ToArray();
}
if (ct.IsCancellationRequested)
{
return Enumerable.Empty<byte>().ToArray();
}
var b = new byte[1];
if (stream == null)
{
throw new Exception("Read stream cannot be null.");
}
if (!stream.CanRead)
{
throw new Exception("Stream connection have been closed.");
}
var bytesRead = 0;
try
{
//Debug.WriteLine("Reading byte.");
bytesRead = await stream.ReadAsync(b, 0, 1, ct).ConfigureAwait(false);
//Debug.WriteLine("Done reading byte.");
}
catch (Exception ex)
{
HasParsingError = true;
throw new SimpleHttpListenerException("Unable to read network stream.", ex);
}
if (bytesRead < b.Length)
{
IsDone = true;
}
return _errorCorrections.Contains(ErrorCorrection.HeaderCompletionError)
? ResilientHeader(b)
: b;
}
// Sometimes the HTTP does not end with \r\n\r\n, in which case it is added here.
private byte[] ResilientHeader(byte[] b)
{
if (!IsDone)
{
_last4BytesCircularBuffer.Enqueue(b[0]);
}
else
{
if (!_parserDelegate.IsHeaderDone)
{
var last4Byte = _last4BytesCircularBuffer.ToArray();
if (last4Byte != _correctLast4BytesReversed)
{
byte[] returnNewLine = { 0x0d, 0x0a };
var correctionList = new List<byte>();
if (last4Byte[0] != _correctLast4BytesReversed[0] || last4Byte[1] != _correctLast4BytesReversed[1])
{
correctionList.Add(returnNewLine[0]);
correctionList.Add(returnNewLine[1]);
}
if (last4Byte[2] != _correctLast4BytesReversed[2] || last4Byte[3] != _correctLast4BytesReversed[3])
{
correctionList.Add(returnNewLine[0]);
correctionList.Add(returnNewLine[1]);
}
if (correctionList.Any())
{
return correctionList.Concat(correctionList.Select(x => x)).ToArray();
}
}
}
}
return b;
}
public void Dispose()
{
_disposableParserCompletion?.Dispose();
_parser?.Dispose();
}
}
}
| 34.718085 | 123 | 0.512946 | [
"MIT"
] | 1iveowl/SimpleHttpListener.Rx | src/main/SimpleHttpListener.Rx/Parser/HttpStreamParser.cs | 6,529 | C# |
// <auto-generated>
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/datacatalog/v1/policytagmanagerserialization.proto
// </auto-generated>
// Original file comments:
// Copyright 2022 Google LLC
//
// 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.
//
#pragma warning disable 0414, 1591
#region Designer generated code
using grpc = global::Grpc.Core;
namespace Google.Cloud.DataCatalog.V1 {
/// <summary>
/// Policy Tag Manager Serialization API service allows you to manipulate
/// your policy tags and taxonomies in a serialized format.
///
/// Taxonomy is a hierarchical group of policy tags.
/// </summary>
public static partial class PolicyTagManagerSerialization
{
static readonly string __ServiceName = "google.cloud.datacatalog.v1.PolicyTagManagerSerialization";
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
static void __Helper_SerializeMessage(global::Google.Protobuf.IMessage message, grpc::SerializationContext context)
{
#if !GRPC_DISABLE_PROTOBUF_BUFFER_SERIALIZATION
if (message is global::Google.Protobuf.IBufferMessage)
{
context.SetPayloadLength(message.CalculateSize());
global::Google.Protobuf.MessageExtensions.WriteTo(message, context.GetBufferWriter());
context.Complete();
return;
}
#endif
context.Complete(global::Google.Protobuf.MessageExtensions.ToByteArray(message));
}
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
static class __Helper_MessageCache<T>
{
public static readonly bool IsBufferMessage = global::System.Reflection.IntrospectionExtensions.GetTypeInfo(typeof(global::Google.Protobuf.IBufferMessage)).IsAssignableFrom(typeof(T));
}
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
static T __Helper_DeserializeMessage<T>(grpc::DeserializationContext context, global::Google.Protobuf.MessageParser<T> parser) where T : global::Google.Protobuf.IMessage<T>
{
#if !GRPC_DISABLE_PROTOBUF_BUFFER_SERIALIZATION
if (__Helper_MessageCache<T>.IsBufferMessage)
{
return parser.ParseFrom(context.PayloadAsReadOnlySequence());
}
#endif
return parser.ParseFrom(context.PayloadAsNewBuffer());
}
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
static readonly grpc::Marshaller<global::Google.Cloud.DataCatalog.V1.ReplaceTaxonomyRequest> __Marshaller_google_cloud_datacatalog_v1_ReplaceTaxonomyRequest = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Google.Cloud.DataCatalog.V1.ReplaceTaxonomyRequest.Parser));
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
static readonly grpc::Marshaller<global::Google.Cloud.DataCatalog.V1.Taxonomy> __Marshaller_google_cloud_datacatalog_v1_Taxonomy = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Google.Cloud.DataCatalog.V1.Taxonomy.Parser));
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
static readonly grpc::Marshaller<global::Google.Cloud.DataCatalog.V1.ImportTaxonomiesRequest> __Marshaller_google_cloud_datacatalog_v1_ImportTaxonomiesRequest = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Google.Cloud.DataCatalog.V1.ImportTaxonomiesRequest.Parser));
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
static readonly grpc::Marshaller<global::Google.Cloud.DataCatalog.V1.ImportTaxonomiesResponse> __Marshaller_google_cloud_datacatalog_v1_ImportTaxonomiesResponse = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Google.Cloud.DataCatalog.V1.ImportTaxonomiesResponse.Parser));
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
static readonly grpc::Marshaller<global::Google.Cloud.DataCatalog.V1.ExportTaxonomiesRequest> __Marshaller_google_cloud_datacatalog_v1_ExportTaxonomiesRequest = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Google.Cloud.DataCatalog.V1.ExportTaxonomiesRequest.Parser));
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
static readonly grpc::Marshaller<global::Google.Cloud.DataCatalog.V1.ExportTaxonomiesResponse> __Marshaller_google_cloud_datacatalog_v1_ExportTaxonomiesResponse = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Google.Cloud.DataCatalog.V1.ExportTaxonomiesResponse.Parser));
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
static readonly grpc::Method<global::Google.Cloud.DataCatalog.V1.ReplaceTaxonomyRequest, global::Google.Cloud.DataCatalog.V1.Taxonomy> __Method_ReplaceTaxonomy = new grpc::Method<global::Google.Cloud.DataCatalog.V1.ReplaceTaxonomyRequest, global::Google.Cloud.DataCatalog.V1.Taxonomy>(
grpc::MethodType.Unary,
__ServiceName,
"ReplaceTaxonomy",
__Marshaller_google_cloud_datacatalog_v1_ReplaceTaxonomyRequest,
__Marshaller_google_cloud_datacatalog_v1_Taxonomy);
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
static readonly grpc::Method<global::Google.Cloud.DataCatalog.V1.ImportTaxonomiesRequest, global::Google.Cloud.DataCatalog.V1.ImportTaxonomiesResponse> __Method_ImportTaxonomies = new grpc::Method<global::Google.Cloud.DataCatalog.V1.ImportTaxonomiesRequest, global::Google.Cloud.DataCatalog.V1.ImportTaxonomiesResponse>(
grpc::MethodType.Unary,
__ServiceName,
"ImportTaxonomies",
__Marshaller_google_cloud_datacatalog_v1_ImportTaxonomiesRequest,
__Marshaller_google_cloud_datacatalog_v1_ImportTaxonomiesResponse);
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
static readonly grpc::Method<global::Google.Cloud.DataCatalog.V1.ExportTaxonomiesRequest, global::Google.Cloud.DataCatalog.V1.ExportTaxonomiesResponse> __Method_ExportTaxonomies = new grpc::Method<global::Google.Cloud.DataCatalog.V1.ExportTaxonomiesRequest, global::Google.Cloud.DataCatalog.V1.ExportTaxonomiesResponse>(
grpc::MethodType.Unary,
__ServiceName,
"ExportTaxonomies",
__Marshaller_google_cloud_datacatalog_v1_ExportTaxonomiesRequest,
__Marshaller_google_cloud_datacatalog_v1_ExportTaxonomiesResponse);
/// <summary>Service descriptor</summary>
public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor
{
get { return global::Google.Cloud.DataCatalog.V1.PolicytagmanagerserializationReflection.Descriptor.Services[0]; }
}
/// <summary>Base class for server-side implementations of PolicyTagManagerSerialization</summary>
[grpc::BindServiceMethod(typeof(PolicyTagManagerSerialization), "BindService")]
public abstract partial class PolicyTagManagerSerializationBase
{
/// <summary>
/// Replaces (updates) a taxonomy and all its policy tags.
///
/// The taxonomy and its entire hierarchy of policy tags must be
/// represented literally by `SerializedTaxonomy` and the nested
/// `SerializedPolicyTag` messages.
///
/// This operation automatically does the following:
///
/// - Deletes the existing policy tags that are missing from the
/// `SerializedPolicyTag`.
/// - Creates policy tags that don't have resource names. They are considered
/// new.
/// - Updates policy tags with valid resources names accordingly.
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.DataCatalog.V1.Taxonomy> ReplaceTaxonomy(global::Google.Cloud.DataCatalog.V1.ReplaceTaxonomyRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
/// <summary>
/// Creates new taxonomies (including their policy tags) in a given project
/// by importing from inlined or cross-regional sources.
///
/// For a cross-regional source, new taxonomies are created by copying
/// from a source in another region.
///
/// For an inlined source, taxonomies and policy tags are created in bulk using
/// nested protocol buffer structures.
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.DataCatalog.V1.ImportTaxonomiesResponse> ImportTaxonomies(global::Google.Cloud.DataCatalog.V1.ImportTaxonomiesRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
/// <summary>
/// Exports taxonomies in the requested type and returns them,
/// including their policy tags. The requested taxonomies must belong to the
/// same project.
///
/// This method generates `SerializedTaxonomy` protocol buffers with nested
/// policy tags that can be used as input for `ImportTaxonomies` calls.
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.DataCatalog.V1.ExportTaxonomiesResponse> ExportTaxonomies(global::Google.Cloud.DataCatalog.V1.ExportTaxonomiesRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
}
/// <summary>Client for PolicyTagManagerSerialization</summary>
public partial class PolicyTagManagerSerializationClient : grpc::ClientBase<PolicyTagManagerSerializationClient>
{
/// <summary>Creates a new client for PolicyTagManagerSerialization</summary>
/// <param name="channel">The channel to use to make remote calls.</param>
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
public PolicyTagManagerSerializationClient(grpc::ChannelBase channel) : base(channel)
{
}
/// <summary>Creates a new client for PolicyTagManagerSerialization that uses a custom <c>CallInvoker</c>.</summary>
/// <param name="callInvoker">The callInvoker to use to make remote calls.</param>
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
public PolicyTagManagerSerializationClient(grpc::CallInvoker callInvoker) : base(callInvoker)
{
}
/// <summary>Protected parameterless constructor to allow creation of test doubles.</summary>
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
protected PolicyTagManagerSerializationClient() : base()
{
}
/// <summary>Protected constructor to allow creation of configured clients.</summary>
/// <param name="configuration">The client configuration.</param>
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
protected PolicyTagManagerSerializationClient(ClientBaseConfiguration configuration) : base(configuration)
{
}
/// <summary>
/// Replaces (updates) a taxonomy and all its policy tags.
///
/// The taxonomy and its entire hierarchy of policy tags must be
/// represented literally by `SerializedTaxonomy` and the nested
/// `SerializedPolicyTag` messages.
///
/// This operation automatically does the following:
///
/// - Deletes the existing policy tags that are missing from the
/// `SerializedPolicyTag`.
/// - Creates policy tags that don't have resource names. They are considered
/// new.
/// - Updates policy tags with valid resources names accordingly.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
public virtual global::Google.Cloud.DataCatalog.V1.Taxonomy ReplaceTaxonomy(global::Google.Cloud.DataCatalog.V1.ReplaceTaxonomyRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken))
{
return ReplaceTaxonomy(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Replaces (updates) a taxonomy and all its policy tags.
///
/// The taxonomy and its entire hierarchy of policy tags must be
/// represented literally by `SerializedTaxonomy` and the nested
/// `SerializedPolicyTag` messages.
///
/// This operation automatically does the following:
///
/// - Deletes the existing policy tags that are missing from the
/// `SerializedPolicyTag`.
/// - Creates policy tags that don't have resource names. They are considered
/// new.
/// - Updates policy tags with valid resources names accordingly.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
public virtual global::Google.Cloud.DataCatalog.V1.Taxonomy ReplaceTaxonomy(global::Google.Cloud.DataCatalog.V1.ReplaceTaxonomyRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_ReplaceTaxonomy, null, options, request);
}
/// <summary>
/// Replaces (updates) a taxonomy and all its policy tags.
///
/// The taxonomy and its entire hierarchy of policy tags must be
/// represented literally by `SerializedTaxonomy` and the nested
/// `SerializedPolicyTag` messages.
///
/// This operation automatically does the following:
///
/// - Deletes the existing policy tags that are missing from the
/// `SerializedPolicyTag`.
/// - Creates policy tags that don't have resource names. They are considered
/// new.
/// - Updates policy tags with valid resources names accordingly.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
public virtual grpc::AsyncUnaryCall<global::Google.Cloud.DataCatalog.V1.Taxonomy> ReplaceTaxonomyAsync(global::Google.Cloud.DataCatalog.V1.ReplaceTaxonomyRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken))
{
return ReplaceTaxonomyAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Replaces (updates) a taxonomy and all its policy tags.
///
/// The taxonomy and its entire hierarchy of policy tags must be
/// represented literally by `SerializedTaxonomy` and the nested
/// `SerializedPolicyTag` messages.
///
/// This operation automatically does the following:
///
/// - Deletes the existing policy tags that are missing from the
/// `SerializedPolicyTag`.
/// - Creates policy tags that don't have resource names. They are considered
/// new.
/// - Updates policy tags with valid resources names accordingly.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
public virtual grpc::AsyncUnaryCall<global::Google.Cloud.DataCatalog.V1.Taxonomy> ReplaceTaxonomyAsync(global::Google.Cloud.DataCatalog.V1.ReplaceTaxonomyRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_ReplaceTaxonomy, null, options, request);
}
/// <summary>
/// Creates new taxonomies (including their policy tags) in a given project
/// by importing from inlined or cross-regional sources.
///
/// For a cross-regional source, new taxonomies are created by copying
/// from a source in another region.
///
/// For an inlined source, taxonomies and policy tags are created in bulk using
/// nested protocol buffer structures.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
public virtual global::Google.Cloud.DataCatalog.V1.ImportTaxonomiesResponse ImportTaxonomies(global::Google.Cloud.DataCatalog.V1.ImportTaxonomiesRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken))
{
return ImportTaxonomies(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Creates new taxonomies (including their policy tags) in a given project
/// by importing from inlined or cross-regional sources.
///
/// For a cross-regional source, new taxonomies are created by copying
/// from a source in another region.
///
/// For an inlined source, taxonomies and policy tags are created in bulk using
/// nested protocol buffer structures.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
public virtual global::Google.Cloud.DataCatalog.V1.ImportTaxonomiesResponse ImportTaxonomies(global::Google.Cloud.DataCatalog.V1.ImportTaxonomiesRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_ImportTaxonomies, null, options, request);
}
/// <summary>
/// Creates new taxonomies (including their policy tags) in a given project
/// by importing from inlined or cross-regional sources.
///
/// For a cross-regional source, new taxonomies are created by copying
/// from a source in another region.
///
/// For an inlined source, taxonomies and policy tags are created in bulk using
/// nested protocol buffer structures.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
public virtual grpc::AsyncUnaryCall<global::Google.Cloud.DataCatalog.V1.ImportTaxonomiesResponse> ImportTaxonomiesAsync(global::Google.Cloud.DataCatalog.V1.ImportTaxonomiesRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken))
{
return ImportTaxonomiesAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Creates new taxonomies (including their policy tags) in a given project
/// by importing from inlined or cross-regional sources.
///
/// For a cross-regional source, new taxonomies are created by copying
/// from a source in another region.
///
/// For an inlined source, taxonomies and policy tags are created in bulk using
/// nested protocol buffer structures.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
public virtual grpc::AsyncUnaryCall<global::Google.Cloud.DataCatalog.V1.ImportTaxonomiesResponse> ImportTaxonomiesAsync(global::Google.Cloud.DataCatalog.V1.ImportTaxonomiesRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_ImportTaxonomies, null, options, request);
}
/// <summary>
/// Exports taxonomies in the requested type and returns them,
/// including their policy tags. The requested taxonomies must belong to the
/// same project.
///
/// This method generates `SerializedTaxonomy` protocol buffers with nested
/// policy tags that can be used as input for `ImportTaxonomies` calls.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
public virtual global::Google.Cloud.DataCatalog.V1.ExportTaxonomiesResponse ExportTaxonomies(global::Google.Cloud.DataCatalog.V1.ExportTaxonomiesRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken))
{
return ExportTaxonomies(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Exports taxonomies in the requested type and returns them,
/// including their policy tags. The requested taxonomies must belong to the
/// same project.
///
/// This method generates `SerializedTaxonomy` protocol buffers with nested
/// policy tags that can be used as input for `ImportTaxonomies` calls.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
public virtual global::Google.Cloud.DataCatalog.V1.ExportTaxonomiesResponse ExportTaxonomies(global::Google.Cloud.DataCatalog.V1.ExportTaxonomiesRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_ExportTaxonomies, null, options, request);
}
/// <summary>
/// Exports taxonomies in the requested type and returns them,
/// including their policy tags. The requested taxonomies must belong to the
/// same project.
///
/// This method generates `SerializedTaxonomy` protocol buffers with nested
/// policy tags that can be used as input for `ImportTaxonomies` calls.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
public virtual grpc::AsyncUnaryCall<global::Google.Cloud.DataCatalog.V1.ExportTaxonomiesResponse> ExportTaxonomiesAsync(global::Google.Cloud.DataCatalog.V1.ExportTaxonomiesRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken))
{
return ExportTaxonomiesAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Exports taxonomies in the requested type and returns them,
/// including their policy tags. The requested taxonomies must belong to the
/// same project.
///
/// This method generates `SerializedTaxonomy` protocol buffers with nested
/// policy tags that can be used as input for `ImportTaxonomies` calls.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
public virtual grpc::AsyncUnaryCall<global::Google.Cloud.DataCatalog.V1.ExportTaxonomiesResponse> ExportTaxonomiesAsync(global::Google.Cloud.DataCatalog.V1.ExportTaxonomiesRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_ExportTaxonomies, null, options, request);
}
/// <summary>Creates a new instance of client from given <c>ClientBaseConfiguration</c>.</summary>
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
protected override PolicyTagManagerSerializationClient NewInstance(ClientBaseConfiguration configuration)
{
return new PolicyTagManagerSerializationClient(configuration);
}
}
/// <summary>Creates service definition that can be registered with a server</summary>
/// <param name="serviceImpl">An object implementing the server-side handling logic.</param>
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
public static grpc::ServerServiceDefinition BindService(PolicyTagManagerSerializationBase serviceImpl)
{
return grpc::ServerServiceDefinition.CreateBuilder()
.AddMethod(__Method_ReplaceTaxonomy, serviceImpl.ReplaceTaxonomy)
.AddMethod(__Method_ImportTaxonomies, serviceImpl.ImportTaxonomies)
.AddMethod(__Method_ExportTaxonomies, serviceImpl.ExportTaxonomies).Build();
}
/// <summary>Register service method with a service binder with or without implementation. Useful when customizing the service binding logic.
/// Note: this method is part of an experimental API that can change or be removed without any prior notice.</summary>
/// <param name="serviceBinder">Service methods will be bound by calling <c>AddMethod</c> on this object.</param>
/// <param name="serviceImpl">An object implementing the server-side handling logic.</param>
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
public static void BindService(grpc::ServiceBinderBase serviceBinder, PolicyTagManagerSerializationBase serviceImpl)
{
serviceBinder.AddMethod(__Method_ReplaceTaxonomy, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Google.Cloud.DataCatalog.V1.ReplaceTaxonomyRequest, global::Google.Cloud.DataCatalog.V1.Taxonomy>(serviceImpl.ReplaceTaxonomy));
serviceBinder.AddMethod(__Method_ImportTaxonomies, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Google.Cloud.DataCatalog.V1.ImportTaxonomiesRequest, global::Google.Cloud.DataCatalog.V1.ImportTaxonomiesResponse>(serviceImpl.ImportTaxonomies));
serviceBinder.AddMethod(__Method_ExportTaxonomies, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Google.Cloud.DataCatalog.V1.ExportTaxonomiesRequest, global::Google.Cloud.DataCatalog.V1.ExportTaxonomiesResponse>(serviceImpl.ExportTaxonomies));
}
}
}
#endregion
| 65.075157 | 383 | 0.727824 | [
"Apache-2.0"
] | AlexandrTrf/google-cloud-dotnet | apis/Google.Cloud.DataCatalog.V1/Google.Cloud.DataCatalog.V1/PolicytagmanagerserializationGrpc.g.cs | 31,171 | C# |
using System.Threading;
using Vapula;
using Vapula.Runtime;
namespace sample_lib_x
{
public class Sample
{
public void Math()
{
Stack stack = Stack.Instance;
Dataset dataset = stack.Dataset;
Record record = dataset[1];
Pointer pointer = new Pointer();
pointer.Capture(record.Read(), record.Size);
int[] data = pointer.ReadArray<int>();
int result = 0;
foreach (int v in data)
result += v;
pointer.Release();
pointer.WriteValue(result);
dataset[2].Write(pointer.Data, pointer.Size);
stack.Context.ReturnCode = ReturnCode.Normal;
}
public void Out()
{
Stack stack = Stack.Instance;
Dataset dataset = stack.Dataset;
string data = "中文English日本語テスト";
Pointer pointer = new Pointer();
pointer.WriteArray(data.ToCharArray());
dataset[1].Write(pointer.Data, pointer.Size);
stack.Context.ReturnCode = ReturnCode.Normal;
}
public void Context()
{
Stack stack = Stack.Instance;
Context ctx = stack.Context;
for (int i = 0; i < 1000; i++)
{
ControlCode ctrl = ctx.ControlCode;
if (ctrl == ControlCode.Cancel)
ctx.ReturnCode = ReturnCode.Cancel;
if (ctrl == ControlCode.Pause)
{
ctx.SwitchHold();
while (true)
{
ctrl = ctx.ControlCode;
if (ctrl == ControlCode.Resume)
{
ctx.SwitchHold();
break;
}
Thread.Sleep(25);
}
}
ctx.Progress = i / 10.0f;
Thread.Sleep(25);
}
ctx.ReturnCode = ReturnCode.Normal;
}
}
}
| 31.134328 | 57 | 0.45302 | [
"Apache-2.0"
] | sartrey/vapula | Core/Sample/sample_library_x/Program.cs | 2,104 | C# |
using Microsoft.eShopWeb.ApplicationCore.Interfaces;
using System.Collections.Generic;
using System.Linq;
namespace Microsoft.eShopWeb.ApplicationCore.Entities.BasketAggregate
{
public class Basket : BaseEntity, IAggregateRoot
{
public string BuyerId { get; private set; }
private readonly List<BasketItem> _items = new List<BasketItem>();
public IReadOnlyCollection<BasketItem> Items => _items.AsReadOnly();
public Basket(string buyerId)
{
BuyerId = buyerId;
}
public void AddItem(int catalogItemId, decimal unitPrice, int quantity = 1)
{
if (!Items.Any(i => i.CatalogItemId == catalogItemId))
{
_items.Add(new BasketItem(catalogItemId, quantity, unitPrice));
return;
}
var existingItem = Items.FirstOrDefault(i => i.CatalogItemId == catalogItemId);
existingItem.AddQuantity(quantity);
}
public void RemoveItem(int catalogItemId)
{
_items.RemoveAll(i => i.CatalogItemId == catalogItemId);
}
public void RemoveEmptyItems()
{
_items.RemoveAll(i => i.Quantity == 0);
}
public void SetNewBuyerId(string buyerId)
{
BuyerId = buyerId;
}
}
}
| 26.340909 | 83 | 0.695427 | [
"MIT"
] | jesse-moore/eShopOnWeb | src/ApplicationCore/Entities/BasketAggregate/Basket.cs | 1,161 | 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 apigateway-2015-07-09.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.APIGateway.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.APIGateway.Model.Internal.MarshallTransformations
{
/// <summary>
/// UpdateIntegrationResponse Request Marshaller
/// </summary>
public class UpdateIntegrationResponseRequestMarshaller : IMarshaller<IRequest, UpdateIntegrationResponseRequest> , IMarshaller<IRequest,AmazonWebServiceRequest>
{
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public IRequest Marshall(AmazonWebServiceRequest input)
{
return this.Marshall((UpdateIntegrationResponseRequest)input);
}
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="publicRequest"></param>
/// <returns></returns>
public IRequest Marshall(UpdateIntegrationResponseRequest publicRequest)
{
IRequest request = new DefaultRequest(publicRequest, "Amazon.APIGateway");
request.Headers["Content-Type"] = "application/json";
request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2015-07-09";
request.HttpMethod = "PATCH";
if (!publicRequest.IsSetHttpMethod())
throw new AmazonAPIGatewayException("Request object does not have required field HttpMethod set");
request.AddPathResource("{http_method}", StringUtils.FromString(publicRequest.HttpMethod));
if (!publicRequest.IsSetResourceId())
throw new AmazonAPIGatewayException("Request object does not have required field ResourceId set");
request.AddPathResource("{resource_id}", StringUtils.FromString(publicRequest.ResourceId));
if (!publicRequest.IsSetRestApiId())
throw new AmazonAPIGatewayException("Request object does not have required field RestApiId set");
request.AddPathResource("{restapi_id}", StringUtils.FromString(publicRequest.RestApiId));
if (!publicRequest.IsSetStatusCode())
throw new AmazonAPIGatewayException("Request object does not have required field StatusCode set");
request.AddPathResource("{status_code}", StringUtils.FromString(publicRequest.StatusCode));
request.ResourcePath = "/restapis/{restapi_id}/resources/{resource_id}/methods/{http_method}/integration/responses/{status_code}";
using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture))
{
JsonWriter writer = new JsonWriter(stringWriter);
writer.WriteObjectStart();
var context = new JsonMarshallerContext(request, writer);
if(publicRequest.IsSetPatchOperations())
{
context.Writer.WritePropertyName("patchOperations");
context.Writer.WriteArrayStart();
foreach(var publicRequestPatchOperationsListValue in publicRequest.PatchOperations)
{
context.Writer.WriteObjectStart();
var marshaller = PatchOperationMarshaller.Instance;
marshaller.Marshall(publicRequestPatchOperationsListValue, context);
context.Writer.WriteObjectEnd();
}
context.Writer.WriteArrayEnd();
}
writer.WriteObjectEnd();
string snippet = stringWriter.ToString();
request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
}
return request;
}
private static UpdateIntegrationResponseRequestMarshaller _instance = new UpdateIntegrationResponseRequestMarshaller();
internal static UpdateIntegrationResponseRequestMarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static UpdateIntegrationResponseRequestMarshaller Instance
{
get
{
return _instance;
}
}
}
} | 42.682927 | 165 | 0.651619 | [
"Apache-2.0"
] | Hazy87/aws-sdk-net | sdk/src/Services/APIGateway/Generated/Model/Internal/MarshallTransformations/UpdateIntegrationResponseRequestMarshaller.cs | 5,250 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:2.0.50727.3603
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace TestXmlizedAttribute.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "9.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}
| 34.612903 | 150 | 0.584343 | [
"Apache-2.0"
] | haowenbiao/His6C- | Test/TestXmlizedAttribute/TestXmlizedAttribute/Properties/Settings.Designer.cs | 1,075 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime;
namespace System.ServiceModel.Channels
{
public abstract class BufferManager
{
public abstract byte[] TakeBuffer(int bufferSize);
public abstract void ReturnBuffer(byte[] buffer);
public abstract void Clear();
public static BufferManager CreateBufferManager(long maxBufferPoolSize, int maxBufferSize)
{
if (maxBufferPoolSize < 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("maxBufferPoolSize",
maxBufferPoolSize, SR.ValueMustBeNonNegative));
}
if (maxBufferSize < 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("maxBufferSize",
maxBufferSize, SR.ValueMustBeNonNegative));
}
return new WrappingBufferManager(InternalBufferManager.Create(maxBufferPoolSize, maxBufferSize));
}
internal static InternalBufferManager GetInternalBufferManager(BufferManager bufferManager)
{
if (bufferManager is WrappingBufferManager)
{
return ((WrappingBufferManager)bufferManager).InternalBufferManager;
}
else
{
return new WrappingInternalBufferManager(bufferManager);
}
}
internal class WrappingBufferManager : BufferManager
{
private InternalBufferManager _innerBufferManager;
public WrappingBufferManager(InternalBufferManager innerBufferManager)
{
_innerBufferManager = innerBufferManager;
}
public InternalBufferManager InternalBufferManager
{
get { return _innerBufferManager; }
}
public override byte[] TakeBuffer(int bufferSize)
{
if (bufferSize < 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("bufferSize", bufferSize,
SR.ValueMustBeNonNegative));
}
return _innerBufferManager.TakeBuffer(bufferSize);
}
public override void ReturnBuffer(byte[] buffer)
{
if (buffer == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("buffer");
}
_innerBufferManager.ReturnBuffer(buffer);
}
public override void Clear()
{
_innerBufferManager.Clear();
}
}
internal class WrappingInternalBufferManager : InternalBufferManager
{
private BufferManager _innerBufferManager;
public WrappingInternalBufferManager(BufferManager innerBufferManager)
{
_innerBufferManager = innerBufferManager;
}
public override void Clear()
{
_innerBufferManager.Clear();
}
public override void ReturnBuffer(byte[] buffer)
{
_innerBufferManager.ReturnBuffer(buffer);
}
public override byte[] TakeBuffer(int bufferSize)
{
return _innerBufferManager.TakeBuffer(bufferSize);
}
}
}
}
| 32.901786 | 135 | 0.59213 | [
"MIT"
] | OceanYan/dotnet-wcf | src/System.Private.ServiceModel/src/System/ServiceModel/Channels/BufferManager.cs | 3,685 | C# |
using System;
namespace Xample.DeadCode.CSharp
{
static class Program
{
static void Main(params object[] args)
{
var x = new SimpleClass();
Console.Write(x.Method(8));
}
}
}
| 13.642857 | 40 | 0.659686 | [
"MIT"
] | Corniel/DeadCode | xample/Xample.DeadCode.CSharp/Program.cs | 193 | C# |
using AutoMapper;
using Discount.Grpc.Entities;
using Discount.Grpc.Protos;
using Discount.Grpc.Repositories;
using Grpc.Core;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Discount.Grpc.Services
{
public class DiscountService : DiscountProtoService.DiscountProtoServiceBase
{
private readonly IDiscountRepository repository;
private readonly IMapper mapper;
private readonly ILogger<DiscountService> logger;
public DiscountService(IDiscountRepository repository, IMapper mapper, ILogger<DiscountService> logger)
{
this.repository = repository ?? throw new ArgumentNullException(nameof(repository));
this.logger = logger ?? throw new ArgumentNullException(nameof(logger));
this.mapper = mapper ?? throw new ArgumentNullException(nameof(mapper));
}
public override async Task<CouponModel> GetDiscount(GetDiscountRequest request, ServerCallContext context)
{
var coupon = await repository.GetDiscount(request.ProductName);
if (coupon == null)
{
throw new RpcException(new Status(StatusCode.NotFound, $"Discount with ProductName={request.ProductName} not found."));
}
logger.LogInformation($"Discount is retrieved for ProductName: {coupon.ProductName}, Amount: {coupon.Amount}, Description: {coupon.Description}");
var couponModel = mapper.Map<CouponModel>(coupon);
return couponModel;
}
public override async Task<CouponModel> CreateDiscount(CreateDiscountRequest request, ServerCallContext context)
{
var coupon = mapper.Map<Coupon>(request.Coupon);
await repository.CreateDiscount(coupon);
logger.LogInformation($"Discount is successfully created. ProductName: {coupon.ProductName}");
var couponModel = mapper.Map<CouponModel>(coupon);
return couponModel;
}
public override async Task<CouponModel> UpdateDiscount(UpdateDiscountRequest request, ServerCallContext context)
{
var coupon = mapper.Map<Coupon>(request.Coupon);
await repository.UpdateDiscount(coupon);
logger.LogInformation($"Discount is seccussfully updated. ProductName: {coupon.ProductName}");
var couponModel = mapper.Map<CouponModel>(coupon);
return couponModel;
}
public override async Task<DeleteDiscountResponse> DeleteDiscount(DeleteDiscountRequest request, ServerCallContext context)
{
var deleted = await repository.DeleteDiscount(request.ProductName);
var response = new DeleteDiscountResponse
{
Success = deleted
};
return response;
}
}
}
| 39.337838 | 158 | 0.678805 | [
"MIT"
] | Mental-NV/AspnetMicroservices | src/Services/Discount/Discount.Grpc/Services/DiscountService.cs | 2,913 | C# |
using NUnit.Framework;
using static Yoga.Net.YGGlobal;
namespace Yoga.Net.Tests
{
[TestFixture]
public class YGDirtyMarkingTest
{
[Test] public void dirty_propagation() {
YGNode root = YGNodeNew();
YGNodeStyleSetAlignItems(root, YGAlign.FlexStart);
YGNodeStyleSetWidth(root, 100);
YGNodeStyleSetHeight(root, 100);
YGNode root_child0 = YGNodeNew();
YGNodeStyleSetWidth(root_child0, 50);
YGNodeStyleSetHeight(root_child0, 20);
YGNodeInsertChild(root, root_child0, 0);
YGNode root_child1 = YGNodeNew();
YGNodeStyleSetWidth(root_child1, 50);
YGNodeStyleSetHeight(root_child1, 20);
YGNodeInsertChild(root, root_child1, 1);
YGNodeCalculateLayout(root, YGValue.YGUndefined, YGValue.YGUndefined, YGDirection.LTR);
YGNodeStyleSetWidth(root_child0, 20);
Assert.IsTrue(root_child0.isDirty());
Assert.IsFalse(root_child1.isDirty());
Assert.IsTrue(root.isDirty());
YGNodeCalculateLayout(root, YGValue.YGUndefined, YGValue.YGUndefined, YGDirection.LTR);
Assert.IsFalse(root_child0.isDirty());
Assert.IsFalse(root_child1.isDirty());
Assert.IsFalse(root.isDirty());
}
[Test] public void dirty_propagation_only_if_prop_changed() {
YGNode root = YGNodeNew();
YGNodeStyleSetAlignItems(root, YGAlign.FlexStart);
YGNodeStyleSetWidth(root, 100);
YGNodeStyleSetHeight(root, 100);
YGNode root_child0 = YGNodeNew();
YGNodeStyleSetWidth(root_child0, 50);
YGNodeStyleSetHeight(root_child0, 20);
YGNodeInsertChild(root, root_child0, 0);
YGNode root_child1 = YGNodeNew();
YGNodeStyleSetWidth(root_child1, 50);
YGNodeStyleSetHeight(root_child1, 20);
YGNodeInsertChild(root, root_child1, 1);
YGNodeCalculateLayout(root, YGValue.YGUndefined, YGValue.YGUndefined, YGDirection.LTR);
YGNodeStyleSetWidth(root_child0, 50);
Assert.IsFalse(root_child0.isDirty());
Assert.IsFalse(root_child1.isDirty());
Assert.IsFalse(root.isDirty());
}
[Test] public void dirty_mark_all_children_as_dirty_when_display_changes() {
YGNode root = YGNodeNew();
YGNodeStyleSetFlexDirection(root, YGFlexDirection.Row);
YGNodeStyleSetHeight(root, 100);
YGNode child0 = YGNodeNew();
YGNodeStyleSetFlexGrow(child0, 1);
YGNode child1 = YGNodeNew();
YGNodeStyleSetFlexGrow(child1, 1);
YGNode child1_child0 = YGNodeNew();
YGNode child1_child0_child0 = YGNodeNew();
YGNodeStyleSetWidth(child1_child0_child0, 8);
YGNodeStyleSetHeight(child1_child0_child0, 16);
YGNodeInsertChild(child1_child0, child1_child0_child0, 0);
YGNodeInsertChild(child1, child1_child0, 0);
YGNodeInsertChild(root, child0, 0);
YGNodeInsertChild(root, child1, 0);
YGNodeStyleSetDisplay(child0, YGDisplay.Flex);
YGNodeStyleSetDisplay(child1, YGDisplay.None);
YGNodeCalculateLayout(root, YGValue.YGUndefined, YGValue.YGUndefined, YGDirection.LTR);
Assert.AreEqual(0, YGNodeLayoutGetWidth(child1_child0_child0));
Assert.AreEqual(0, YGNodeLayoutGetHeight(child1_child0_child0));
YGNodeStyleSetDisplay(child0, YGDisplay.None);
YGNodeStyleSetDisplay(child1, YGDisplay.Flex);
YGNodeCalculateLayout(root, YGValue.YGUndefined, YGValue.YGUndefined, YGDirection.LTR);
Assert.AreEqual(8, YGNodeLayoutGetWidth(child1_child0_child0));
Assert.AreEqual(16, YGNodeLayoutGetHeight(child1_child0_child0));
YGNodeStyleSetDisplay(child0, YGDisplay.Flex);
YGNodeStyleSetDisplay(child1, YGDisplay.None);
YGNodeCalculateLayout(root, YGValue.YGUndefined, YGValue.YGUndefined, YGDirection.LTR);
Assert.AreEqual(0, YGNodeLayoutGetWidth(child1_child0_child0));
Assert.AreEqual(0, YGNodeLayoutGetHeight(child1_child0_child0));
YGNodeStyleSetDisplay(child0, YGDisplay.None);
YGNodeStyleSetDisplay(child1, YGDisplay.Flex);
YGNodeCalculateLayout(root, YGValue.YGUndefined, YGValue.YGUndefined, YGDirection.LTR);
Assert.AreEqual(8, YGNodeLayoutGetWidth(child1_child0_child0));
Assert.AreEqual(16, YGNodeLayoutGetHeight(child1_child0_child0));
}
[Test] public void dirty_node_only_if_children_are_actually_removed() {
YGNode root = YGNodeNew();
YGNodeStyleSetAlignItems(root, YGAlign.FlexStart);
YGNodeStyleSetWidth(root, 50);
YGNodeStyleSetHeight(root, 50);
YGNode child0 = YGNodeNew();
YGNodeStyleSetWidth(child0, 50);
YGNodeStyleSetHeight(child0, 25);
YGNodeInsertChild(root, child0, 0);
YGNodeCalculateLayout(root, YGValue.YGUndefined, YGValue.YGUndefined, YGDirection.LTR);
YGNode child1 = YGNodeNew();
YGNodeRemoveChild(root, child1);
Assert.IsFalse(root.isDirty());
YGNodeRemoveChild(root, child0);
Assert.IsTrue(root.isDirty());
}
[Test] public void dirty_node_only_if_undefined_values_gets_set_to_undefined() {
YGNode root = YGNodeNew();
YGNodeStyleSetWidth(root, 50);
YGNodeStyleSetHeight(root, 50);
YGNodeStyleSetMinWidth(root, YGValue.YGUndefined);
YGNodeCalculateLayout(root, YGValue.YGUndefined, YGValue.YGUndefined, YGDirection.LTR);
Assert.IsFalse(root.isDirty());
YGNodeStyleSetMinWidth(root, YGValue.YGUndefined);
Assert.IsFalse(root.isDirty());
}
}
}
| 37.703704 | 99 | 0.639817 | [
"MIT"
] | brainzdev/Yoga.Net | Yoga.Net.Tests/YGDirtyMarkingTest.cs | 6,108 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using Zoo.Interfaces;
namespace Zoo.Classes
{
public class Nautilus : Cephalopod
{
public override int NumberOfTentacles { get; set; } = 90;
public override string Habitat { get; set; } = "Tropical Indo-Pacific";
public override string Diet { get; set; } = "Shrimps, crabs, and small fishes";
public override bool HasShell { get; set; } = true;
/// <summary>
/// Nautilus crawls sometimes.
/// </summary>
/// <returns></returns>
public override string Crawl()
{
return "Is it really crawling? Oh yes, it's moving real slow";
}
/// <summary>
/// Nautilus' typically lay 10 eggs.
/// </summary>
/// <returns></returns>
public override string GiveBirth()
{
return "How cute, it just laid 10 eggs!";
}
/// <summary>
/// They probably do make sounds, but it's just too quiet.
/// </summary>
/// <returns></returns>
public override string MakeSound()
{
return "It made a sound, but it's too quiet for you to hear.";
}
/// <summary>
/// Turns into fossil
/// </summary>
/// <returns>The process of turning into a fossil</returns>
public string BeAFossil()
{
return "It's not moving... Is it..- Oh, it's a fossil now.";
}
public override string Swim()
{
return "It floats along, ignoring you.";
}
}
}
| 28.403509 | 87 | 0.536751 | [
"MIT"
] | Inkh/Zoo | Zoo/Classes/Nautilus.cs | 1,621 | C# |
namespace InControl
{
// @cond nodoc
[AutoDiscover]
public class MogaHeroPowerAndroidProfile : UnityInputDeviceProfile
{
public MogaHeroPowerAndroidProfile()
{
Name = "Moga Hero Power";
Meta = "Moga Hero Power on Android";
DeviceClass = InputDeviceClass.Controller;
IncludePlatforms = new[] {
"Android"
};
JoystickNames = new[] {
"Moga 2 HID"
};
ButtonMappings = new[] {
new InputControlMapping {
Handle = "A",
Target = InputControlType.Action1,
Source = Button0
},
new InputControlMapping {
Handle = "B",
Target = InputControlType.Action2,
Source = Button1
},
new InputControlMapping {
Handle = "X",
Target = InputControlType.Action3,
Source = Button2
},
new InputControlMapping {
Handle = "Y",
Target = InputControlType.Action4,
Source = Button3
},
new InputControlMapping {
Handle = "Start",
Target = InputControlType.Start,
Source = Button10
},
new InputControlMapping {
Handle = "L1",
Target = InputControlType.LeftBumper,
Source = Button4
},
new InputControlMapping {
Handle = "R1",
Target = InputControlType.RightBumper,
Source = Button5
},
new InputControlMapping {
Handle = "Left Stick Button",
Target = InputControlType.LeftStickButton,
Source = Button8
},
new InputControlMapping {
Handle = "Right Stick Button",
Target = InputControlType.RightStickButton,
Source = Button9
},
};
AnalogMappings = new[] {
LeftTriggerMapping( Analog12 ),
RightTriggerMapping( Analog11 ),
LeftStickLeftMapping( Analog0 ),
LeftStickRightMapping( Analog0 ),
LeftStickUpMapping( Analog1 ),
LeftStickDownMapping( Analog1 ),
RightStickLeftMapping( Analog2 ),
RightStickRightMapping( Analog2 ),
RightStickUpMapping( Analog3 ),
RightStickDownMapping( Analog3 ),
DPadLeftMapping( Analog4 ),
DPadRightMapping( Analog4 ),
DPadUpMapping( Analog5 ),
DPadDownMapping( Analog5 )
};
AnalogMappings[0].SourceRange = InputRange.ZeroToOne;
AnalogMappings[1].SourceRange = InputRange.ZeroToOne;
}
}
// @endcond
}
| 23.09375 | 67 | 0.653586 | [
"MIT"
] | BattlerockStudios/GGJ2019 | Assets/InControl/Source/Unity/DeviceProfiles/MogaHeroPowerAndroidProfile.cs | 2,217 | 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.IO;
using System.Linq;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
using Microsoft.CodeAnalysis.Shared.Utilities;
using System;
using CS = Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.UnitTests
{
public partial class AdhocWorkspaceTests : WorkspaceTestBase
{
[Fact, Trait(Traits.Feature, Traits.Features.Workspace)]
public void TestAddProject_ProjectInfo()
{
var info = ProjectInfo.Create(
ProjectId.CreateNewId(),
version: VersionStamp.Default,
name: "TestProject",
assemblyName: "TestProject.dll",
language: LanguageNames.CSharp);
using (var ws = new AdhocWorkspace())
{
var project = ws.AddProject(info);
Assert.Equal(project, ws.CurrentSolution.Projects.FirstOrDefault());
Assert.Equal(info.Name, project.Name);
Assert.Equal(info.Id, project.Id);
Assert.Equal(info.AssemblyName, project.AssemblyName);
Assert.Equal(info.Language, project.Language);
}
}
[Fact, Trait(Traits.Feature, Traits.Features.Workspace)]
public void TestAddProject_NameAndLanguage()
{
using (var ws = new AdhocWorkspace())
{
var project = ws.AddProject("TestProject", LanguageNames.CSharp);
Assert.Same(project, ws.CurrentSolution.Projects.FirstOrDefault());
Assert.Equal("TestProject", project.Name);
Assert.Equal(LanguageNames.CSharp, project.Language);
}
}
[Fact, Trait(Traits.Feature, Traits.Features.Workspace)]
public void TestAddDocument_DocumentInfo()
{
using (var ws = new AdhocWorkspace())
{
var project = ws.AddProject("TestProject", LanguageNames.CSharp);
var info = DocumentInfo.Create(DocumentId.CreateNewId(project.Id), "code.cs");
var doc = ws.AddDocument(info);
Assert.Equal(ws.CurrentSolution.GetDocument(info.Id), doc);
Assert.Equal(info.Name, doc.Name);
}
}
[Fact, Trait(Traits.Feature, Traits.Features.Workspace)]
public async Task TestAddDocument_NameAndTextAsync()
{
using (var ws = new AdhocWorkspace())
{
var project = ws.AddProject("TestProject", LanguageNames.CSharp);
var name = "code.cs";
var source = "class C {}";
var doc = ws.AddDocument(project.Id, name, SourceText.From(source));
Assert.Equal(name, doc.Name);
Assert.Equal(source, (await doc.GetTextAsync()).ToString());
}
}
[Fact, Trait(Traits.Feature, Traits.Features.Workspace)]
public void TestAddSolution_SolutionInfo()
{
using (var ws = new AdhocWorkspace())
{
var pinfo = ProjectInfo.Create(
ProjectId.CreateNewId(),
version: VersionStamp.Default,
name: "TestProject",
assemblyName: "TestProject.dll",
language: LanguageNames.CSharp);
var sinfo = SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Default, projects: new ProjectInfo[] { pinfo });
var solution = ws.AddSolution(sinfo);
Assert.Same(ws.CurrentSolution, solution);
Assert.Equal(solution.Id, sinfo.Id);
Assert.Equal(sinfo.Projects.Count, solution.ProjectIds.Count);
var project = solution.Projects.FirstOrDefault();
Assert.NotNull(project);
Assert.Equal(pinfo.Name, project.Name);
Assert.Equal(pinfo.Id, project.Id);
Assert.Equal(pinfo.AssemblyName, project.AssemblyName);
Assert.Equal(pinfo.Language, project.Language);
}
}
[Fact, Trait(Traits.Feature, Traits.Features.Workspace)]
public void TestAddProjects()
{
var id1 = ProjectId.CreateNewId();
var info1 = ProjectInfo.Create(
id1,
version: VersionStamp.Default,
name: "TestProject1",
assemblyName: "TestProject1.dll",
language: LanguageNames.CSharp);
var id2 = ProjectId.CreateNewId();
var info2 = ProjectInfo.Create(
id2,
version: VersionStamp.Default,
name: "TestProject2",
assemblyName: "TestProject2.dll",
language: LanguageNames.VisualBasic,
projectReferences: new[] { new ProjectReference(id1) });
using (var ws = new AdhocWorkspace())
{
ws.AddProjects(new[] { info1, info2 });
var solution = ws.CurrentSolution;
Assert.Equal(2, solution.ProjectIds.Count);
var project1 = solution.GetProject(id1);
Assert.Equal(info1.Name, project1.Name);
Assert.Equal(info1.Id, project1.Id);
Assert.Equal(info1.AssemblyName, project1.AssemblyName);
Assert.Equal(info1.Language, project1.Language);
var project2 = solution.GetProject(id2);
Assert.Equal(info2.Name, project2.Name);
Assert.Equal(info2.Id, project2.Id);
Assert.Equal(info2.AssemblyName, project2.AssemblyName);
Assert.Equal(info2.Language, project2.Language);
Assert.Equal(1, project2.ProjectReferences.Count());
Assert.Equal(id1, project2.ProjectReferences.First().ProjectId);
}
}
[Fact, Trait(Traits.Feature, Traits.Features.Workspace)]
public void TestAddProject_TryApplyChanges()
{
using (var ws = new AdhocWorkspace())
{
ProjectId pid = ProjectId.CreateNewId();
var docInfo = DocumentInfo.Create(
DocumentId.CreateNewId(pid),
"MyDoc.cs",
loader: TextLoader.From(TextAndVersion.Create(SourceText.From(""), VersionStamp.Create())));
var projInfo = ProjectInfo.Create(
pid,
VersionStamp.Create(),
"NewProject",
"NewProject.dll",
LanguageNames.CSharp,
documents: new[] { docInfo });
var newSolution = ws.CurrentSolution.AddProject(projInfo);
Assert.Equal(0, ws.CurrentSolution.Projects.Count());
var result = ws.TryApplyChanges(newSolution);
Assert.Equal(result, true);
Assert.Equal(1, ws.CurrentSolution.Projects.Count());
var proj = ws.CurrentSolution.Projects.First();
Assert.Equal("NewProject", proj.Name);
Assert.Equal("NewProject.dll", proj.AssemblyName);
Assert.Equal(LanguageNames.CSharp, proj.Language);
Assert.Equal(1, proj.Documents.Count());
var doc = proj.Documents.First();
Assert.Equal("MyDoc.cs", doc.Name);
}
}
[Fact, Trait(Traits.Feature, Traits.Features.Workspace)]
public void TestRemoveProject_TryApplyChanges()
{
var pid = ProjectId.CreateNewId();
var info = ProjectInfo.Create(
pid,
version: VersionStamp.Default,
name: "TestProject",
assemblyName: "TestProject.dll",
language: LanguageNames.CSharp);
using (var ws = new AdhocWorkspace())
{
ws.AddProject(info);
Assert.Equal(1, ws.CurrentSolution.Projects.Count());
var newSolution = ws.CurrentSolution.RemoveProject(pid);
Assert.Equal(0, newSolution.Projects.Count());
var result = ws.TryApplyChanges(newSolution);
Assert.Equal(true, result);
Assert.Equal(0, ws.CurrentSolution.Projects.Count());
}
}
[Fact]
public void TestOpenCloseDocument()
{
var pid = ProjectId.CreateNewId();
var text = SourceText.From("public class C { }");
var version = VersionStamp.Create();
var docInfo = DocumentInfo.Create(DocumentId.CreateNewId(pid), "c.cs", loader: TextLoader.From(TextAndVersion.Create(text, version)));
var projInfo = ProjectInfo.Create(
pid,
version: VersionStamp.Default,
name: "TestProject",
assemblyName: "TestProject.dll",
language: LanguageNames.CSharp,
documents: new[] { docInfo });
using (var ws = new AdhocWorkspace())
{
ws.AddProject(projInfo);
var doc = ws.CurrentSolution.GetDocument(docInfo.Id);
Assert.Equal(false, doc.TryGetText(out var currentText));
ws.OpenDocument(docInfo.Id);
doc = ws.CurrentSolution.GetDocument(docInfo.Id);
Assert.Equal(true, doc.TryGetText(out currentText));
Assert.Equal(true, doc.TryGetTextVersion(out var currentVersion));
Assert.Same(text, currentText);
Assert.Equal(version, currentVersion);
ws.CloseDocument(docInfo.Id);
doc = ws.CurrentSolution.GetDocument(docInfo.Id);
Assert.Equal(false, doc.TryGetText(out currentText));
}
}
[Fact]
public void TestOpenCloseAdditionalDocument()
{
var pid = ProjectId.CreateNewId();
var text = SourceText.From("public class C { }");
var version = VersionStamp.Create();
var docInfo = DocumentInfo.Create(DocumentId.CreateNewId(pid), "c.cs", loader: TextLoader.From(TextAndVersion.Create(text, version)));
var projInfo = ProjectInfo.Create(
pid,
version: VersionStamp.Default,
name: "TestProject",
assemblyName: "TestProject.dll",
language: LanguageNames.CSharp,
additionalDocuments: new[] { docInfo });
using (var ws = new AdhocWorkspace())
{
ws.AddProject(projInfo);
var doc = ws.CurrentSolution.GetAdditionalDocument(docInfo.Id);
Assert.Equal(false, doc.TryGetText(out var currentText));
ws.OpenAdditionalDocument(docInfo.Id);
doc = ws.CurrentSolution.GetAdditionalDocument(docInfo.Id);
Assert.Equal(true, doc.TryGetText(out currentText));
Assert.Equal(true, doc.TryGetTextVersion(out var currentVersion));
Assert.Same(text, currentText);
Assert.Equal(version, currentVersion);
ws.CloseAdditionalDocument(docInfo.Id);
doc = ws.CurrentSolution.GetAdditionalDocument(docInfo.Id);
Assert.Equal(false, doc.TryGetText(out currentText));
}
}
[Fact]
public void TestGenerateUniqueName()
{
var a = NameGenerator.GenerateUniqueName("ABC", "txt", _ => true);
Assert.True(a.StartsWith("ABC", StringComparison.Ordinal));
Assert.True(a.EndsWith(".txt", StringComparison.Ordinal));
Assert.False(a.EndsWith("..txt", StringComparison.Ordinal));
var b = NameGenerator.GenerateUniqueName("ABC", ".txt", _ => true);
Assert.True(b.StartsWith("ABC", StringComparison.Ordinal));
Assert.True(b.EndsWith(".txt", StringComparison.Ordinal));
Assert.False(b.EndsWith("..txt", StringComparison.Ordinal));
var c = NameGenerator.GenerateUniqueName("ABC", "\u0640.txt", _ => true);
Assert.True(c.StartsWith("ABC", StringComparison.Ordinal));
Assert.True(c.EndsWith(".\u0640.txt", StringComparison.Ordinal));
Assert.False(c.EndsWith("..txt", StringComparison.Ordinal));
}
[Fact]
public async Task TestUpdatedDocumentHasTextVersionAsync()
{
var pid = ProjectId.CreateNewId();
var text = SourceText.From("public class C { }");
var version = VersionStamp.Create();
var docInfo = DocumentInfo.Create(DocumentId.CreateNewId(pid), "c.cs", loader: TextLoader.From(TextAndVersion.Create(text, version)));
var projInfo = ProjectInfo.Create(
pid,
version: VersionStamp.Default,
name: "TestProject",
assemblyName: "TestProject.dll",
language: LanguageNames.CSharp,
documents: new[] { docInfo });
using (var ws = new AdhocWorkspace())
{
ws.AddProject(projInfo);
var doc = ws.CurrentSolution.GetDocument(docInfo.Id);
Assert.Equal(false, doc.TryGetText(out var currentText));
Assert.Equal(false, doc.TryGetTextVersion(out var currentVersion));
// cause text to load and show that TryGet now works for text and version
currentText = await doc.GetTextAsync();
Assert.Equal(true, doc.TryGetText(out currentText));
Assert.Equal(true, doc.TryGetTextVersion(out currentVersion));
Assert.Equal(version, currentVersion);
// change document
var root = await doc.GetSyntaxRootAsync();
var newRoot = root.WithAdditionalAnnotations(new SyntaxAnnotation());
Assert.NotSame(root, newRoot);
var newDoc = doc.WithSyntaxRoot(newRoot);
Assert.NotSame(doc, newDoc);
// text is now unavailable since it must be constructed from tree
Assert.Equal(false, newDoc.TryGetText(out currentText));
// version is available because it is cached
Assert.Equal(true, newDoc.TryGetTextVersion(out currentVersion));
// access it the hard way
var actualVersion = await newDoc.GetTextVersionAsync();
// version is the same
Assert.Equal(currentVersion, actualVersion);
// accessing text version did not cause text to be constructed.
Assert.Equal(false, newDoc.TryGetText(out currentText));
// now access text directly (force it to be constructed)
var actualText = await newDoc.GetTextAsync();
actualVersion = await newDoc.GetTextVersionAsync();
// prove constructing text did not introduce a new version
Assert.Equal(currentVersion, actualVersion);
}
}
private AdhocWorkspace CreateWorkspaceWithRecoverableTrees(HostServices hostServices)
{
var ws = new AdhocWorkspace(hostServices, workspaceKind: "NotKeptAlive");
ws.Options = ws.Options.WithChangedOption(Host.CacheOptions.RecoverableTreeLengthThreshold, 0);
return ws;
}
[Fact]
public async Task TestUpdatedDocumentTextIsObservablyConstantAsync()
{
var hostServices = MefHostServices.Create(TestHost.Assemblies);
await CheckUpdatedDocumentTextIsObservablyConstantAsync(new AdhocWorkspace(hostServices));
await CheckUpdatedDocumentTextIsObservablyConstantAsync(CreateWorkspaceWithRecoverableTrees(hostServices));
}
private async Task CheckUpdatedDocumentTextIsObservablyConstantAsync(AdhocWorkspace ws)
{
var pid = ProjectId.CreateNewId();
var text = SourceText.From("public class C { }");
var version = VersionStamp.Create();
var docInfo = DocumentInfo.Create(DocumentId.CreateNewId(pid), "c.cs", loader: TextLoader.From(TextAndVersion.Create(text, version)));
var projInfo = ProjectInfo.Create(
pid,
version: VersionStamp.Default,
name: "TestProject",
assemblyName: "TestProject.dll",
language: LanguageNames.CSharp,
documents: new[] { docInfo });
ws.AddProject(projInfo);
var doc = ws.CurrentSolution.GetDocument(docInfo.Id);
// change document
var root = await doc.GetSyntaxRootAsync();
var newRoot = root.WithAdditionalAnnotations(new SyntaxAnnotation());
Assert.NotSame(root, newRoot);
var newDoc = doc.Project.Solution.WithDocumentSyntaxRoot(doc.Id, newRoot).GetDocument(doc.Id);
Assert.NotSame(doc, newDoc);
var newDocText = await newDoc.GetTextAsync();
var sameText = await newDoc.GetTextAsync();
Assert.Same(newDocText, sameText);
var newDocTree = await newDoc.GetSyntaxTreeAsync();
var treeText = newDocTree.GetText();
Assert.Same(newDocText, treeText);
}
[WorkItem(1174396, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1174396")]
[Fact]
public async Task TestUpdateCSharpLanguageVersionAsync()
{
using (var ws = new AdhocWorkspace())
{
var projid = ws.AddProject("TestProject", LanguageNames.CSharp).Id;
var docid1 = ws.AddDocument(projid, "A.cs", SourceText.From("public class A { }")).Id;
var docid2 = ws.AddDocument(projid, "B.cs", SourceText.From("public class B { }")).Id;
var pws = new WorkspaceWithPartialSemantics(ws.CurrentSolution);
var proj = pws.CurrentSolution.GetProject(projid);
var comp = await proj.GetCompilationAsync();
// change language version
var parseOptions = proj.ParseOptions as CS.CSharpParseOptions;
pws.SetParseOptions(projid, parseOptions.WithLanguageVersion(CS.LanguageVersion.CSharp3));
// get partial semantics doc
var frozen = pws.CurrentSolution.GetDocument(docid1).WithFrozenPartialSemantics(CancellationToken.None);
}
}
public class WorkspaceWithPartialSemantics : Workspace
{
public WorkspaceWithPartialSemantics(Solution solution)
: base(solution.Workspace.Services.HostServices, solution.Workspace.Kind)
{
this.SetCurrentSolution(solution);
}
protected internal override bool PartialSemanticsEnabled
{
get { return true; }
}
public void SetParseOptions(ProjectId id, ParseOptions options)
{
base.OnParseOptionsChanged(id, options);
}
}
[Fact, Trait(Traits.Feature, Traits.Features.Workspace)]
public async Task TestChangeDocumentName_TryApplyChanges()
{
using (var ws = new AdhocWorkspace())
{
var projectId = ws.AddProject("TestProject", LanguageNames.CSharp).Id;
var originalDoc = ws.AddDocument(projectId, "TestDocument", SourceText.From(""));
Assert.Equal(originalDoc.Name, "TestDocument");
var newName = "ChangedName";
var changedDoc = originalDoc.WithName(newName);
Assert.Equal(newName, changedDoc.Name);
var tcs = new TaskCompletionSource<bool>();
ws.WorkspaceChanged += (s, args) =>
{
if (args.Kind == WorkspaceChangeKind.DocumentInfoChanged
&& args.DocumentId == originalDoc.Id)
{
tcs.SetResult(true);
}
};
Assert.True(ws.TryApplyChanges(changedDoc.Project.Solution));
var appliedDoc = ws.CurrentSolution.GetDocument(originalDoc.Id);
Assert.Equal(newName, appliedDoc.Name);
await Task.WhenAny(tcs.Task, Task.Delay(1000));
Assert.True(tcs.Task.IsCompleted && tcs.Task.Result);
}
}
[Fact, Trait(Traits.Feature, Traits.Features.Workspace)]
public async Task TestChangeDocumentFolders_TryApplyChanges()
{
using (var ws = new AdhocWorkspace())
{
var projectId = ws.AddProject("TestProject", LanguageNames.CSharp).Id;
var originalDoc = ws.AddDocument(projectId, "TestDocument", SourceText.From(""));
Assert.Equal(0, originalDoc.Folders.Count);
var changedDoc = originalDoc.WithFolders(new[] { "A", "B" });
Assert.Equal(2, changedDoc.Folders.Count);
Assert.Equal("A", changedDoc.Folders[0]);
Assert.Equal("B", changedDoc.Folders[1]);
var tcs = new TaskCompletionSource<bool>();
ws.WorkspaceChanged += (s, args) =>
{
if (args.Kind == WorkspaceChangeKind.DocumentInfoChanged
&& args.DocumentId == originalDoc.Id)
{
tcs.SetResult(true);
}
};
Assert.True(ws.TryApplyChanges(changedDoc.Project.Solution));
var appliedDoc = ws.CurrentSolution.GetDocument(originalDoc.Id);
Assert.Equal(2, appliedDoc.Folders.Count);
Assert.Equal("A", appliedDoc.Folders[0]);
Assert.Equal("B", appliedDoc.Folders[1]);
await Task.WhenAny(tcs.Task, Task.Delay(1000));
Assert.True(tcs.Task.IsCompleted && tcs.Task.Result);
}
}
[Fact, Trait(Traits.Feature, Traits.Features.Workspace)]
public async Task TestChangeDocumentFilePath_TryApplyChanges()
{
using (var ws = new AdhocWorkspace())
{
var projectId = ws.AddProject("TestProject", LanguageNames.CSharp).Id;
var originalDoc = ws.AddDocument(projectId, "TestDocument", SourceText.From(""));
Assert.Null(originalDoc.FilePath);
var newPath = @"\goo\TestDocument.cs";
var changedDoc = originalDoc.WithFilePath(newPath);
Assert.Equal(newPath, changedDoc.FilePath);
var tcs = new TaskCompletionSource<bool>();
ws.WorkspaceChanged += (s, args) =>
{
if (args.Kind == WorkspaceChangeKind.DocumentInfoChanged
&& args.DocumentId == originalDoc.Id)
{
tcs.SetResult(true);
}
};
Assert.True(ws.TryApplyChanges(changedDoc.Project.Solution));
var appliedDoc = ws.CurrentSolution.GetDocument(originalDoc.Id);
Assert.Equal(newPath, appliedDoc.FilePath);
await Task.WhenAny(tcs.Task, Task.Delay(1000));
Assert.True(tcs.Task.IsCompleted && tcs.Task.Result);
}
}
[Fact, Trait(Traits.Feature, Traits.Features.Workspace)]
public async Task TestChangeDocumentSourceCodeKind_TryApplyChanges()
{
using (var ws = new AdhocWorkspace())
{
var projectId = ws.AddProject("TestProject", LanguageNames.CSharp).Id;
var originalDoc = ws.AddDocument(projectId, "TestDocument", SourceText.From(""));
Assert.Equal(SourceCodeKind.Regular, originalDoc.SourceCodeKind);
var changedDoc = originalDoc.WithSourceCodeKind(SourceCodeKind.Script);
Assert.Equal(SourceCodeKind.Script, changedDoc.SourceCodeKind);
var tcs = new TaskCompletionSource<bool>();
ws.WorkspaceChanged += (s, args) =>
{
if (args.Kind == WorkspaceChangeKind.DocumentInfoChanged
&& args.DocumentId == originalDoc.Id)
{
tcs.SetResult(true);
}
};
Assert.True(ws.TryApplyChanges(changedDoc.Project.Solution));
var appliedDoc = ws.CurrentSolution.GetDocument(originalDoc.Id);
Assert.Equal(SourceCodeKind.Script, appliedDoc.SourceCodeKind);
await Task.WhenAny(tcs.Task, Task.Delay(1000));
Assert.True(tcs.Task.IsCompleted && tcs.Task.Result);
}
}
[Fact, Trait(Traits.Feature, Traits.Features.Workspace)]
public void TestChangeDocumentInfo_TryApplyChanges()
{
using (var ws = new AdhocWorkspace())
{
var projectId = ws.AddProject("TestProject", LanguageNames.CSharp).Id;
var originalDoc = ws.AddDocument(projectId, "TestDocument", SourceText.From(""));
Assert.Equal(originalDoc.Name, "TestDocument");
Assert.Equal(0, originalDoc.Folders.Count);
Assert.Null(originalDoc.FilePath);
var newName = "ChangedName";
var newPath = @"\A\B\ChangedName.cs";
var changedDoc = originalDoc.WithName(newName).WithFolders(new[] { "A", "B" }).WithFilePath(newPath);
Assert.Equal(newName, changedDoc.Name);
Assert.Equal(2, changedDoc.Folders.Count);
Assert.Equal("A", changedDoc.Folders[0]);
Assert.Equal("B", changedDoc.Folders[1]);
Assert.Equal(newPath, changedDoc.FilePath);
Assert.True(ws.TryApplyChanges(changedDoc.Project.Solution));
var appliedDoc = ws.CurrentSolution.GetDocument(originalDoc.Id);
Assert.Equal(newName, appliedDoc.Name);
Assert.Equal(2, appliedDoc.Folders.Count);
Assert.Equal("A", appliedDoc.Folders[0]);
Assert.Equal("B", appliedDoc.Folders[1]);
Assert.Equal(newPath, appliedDoc.FilePath);
}
}
[Fact, Trait(Traits.Feature, Traits.Features.Workspace)]
public void TestDefaultDocumentTextDifferencingService()
{
using (var ws = new AdhocWorkspace())
{
var service = ws.Services.GetService<IDocumentTextDifferencingService>();
Assert.NotNull(service);
Assert.Equal(service.GetType(), typeof(DefaultDocumentTextDifferencingService));
}
}
}
}
| 42.627329 | 161 | 0.57107 | [
"Apache-2.0"
] | Ashera138/roslyn | src/Workspaces/CoreTest/WorkspaceTests/AdhocWorkspaceTests.cs | 27,454 | C# |
using System;
using System.Collections;
using System.Data;
using System.Data.Common;
using System.Collections.Generic;
using Hades.Pager.Entity;
using Hades.Framework.ControlUtil;
using Hades.HR.Entity;
namespace Hades.HR.IDAL
{
/// <summary>
/// LaborLeaveWorkload
/// </summary>
public interface ILaborLeaveWorkload : IBaseDAL<LaborLeaveWorkloadInfo>
{
}
} | 19.947368 | 72 | 0.746702 | [
"Apache-2.0"
] | robertzml/Hades.HR | Hades.HR.Core/IDAL/Attendance/ILaborLeaveWorkload.cs | 381 | C# |
namespace HackF5.UnitySpy.HearthstoneLib.Tests
{
using JetBrains.Annotations;
using Microsoft.VisualStudio.TestTools.UnitTesting;
// This needs to be run while Hearthstone is running
[TestClass]
public class TestHearthstoneLibApi
{
[PublicAPI]
public TestContext TestContext { get; set; }
[TestMethod]
public void TestRetrieveCollection()
{
var collection = new MindVision().GetCollectionCards();
Assert.IsNotNull(collection);
Assert.IsTrue(collection.Count > 0, "Collection should not be empty.");
this.TestContext.WriteLine($"Collection has {collection.Count} cards.");
}
// You need to have a game running for this
[TestMethod]
public void TestRetrieveMatchInfo()
{
var matchInfo = new MindVision().GetMatchInfo();
Assert.IsNotNull(matchInfo);
this.TestContext.WriteLine($"Local player's standard rank is {matchInfo.LocalPlayer.StandardRank}.");
}
// You need to have a solo run (Dungeon Run, Monster Hunt, Rumble Run, Dalaran Heist, Tombs of Terror) ongoing
[TestMethod]
public void TestRetrieveFullDungeonInfo()
{
var dungeonInfo = new MindVision().GetDungeonInfoCollection();
Assert.IsNotNull(dungeonInfo);
}
}
} | 35.538462 | 118 | 0.637085 | [
"MIT"
] | Manuel-777/unityspy | src/HackF5.UnitySpy.Tests/TestHearthstoneLibApi.cs | 1,386 | C# |
public static partial class ToonLibrary
{
public static partial class Animations
{
public static class Walk
{
public const string Name = "Walk";
public const string ParentName = Idle.Name;
public static class Events
{
public static readonly float[] AnyStep = new float[2] { Step1, Step2 };
public const float Step1 = 0f;
public const float Step2 = 0.5f;
}
}
}
}
| 24.238095 | 87 | 0.532417 | [
"MIT"
] | NatPlane/unity3d-little-heroes-script-addon | src/Little Heroes Script Addon/Animations/Walk.cs | 509 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
namespace Microsoft.CodeAnalysis.CSharp
{
internal partial class LocalRewriter
{
/// <summary>
/// A common base class for lowering the pattern switch statement and the pattern switch expression.
/// </summary>
private abstract class BaseSwitchLocalRewriter : DecisionDagRewriter
{
/// <summary>
/// Map from when clause's syntax to the lowered code for the matched pattern. The code for a section
/// includes the code to assign to the pattern variables and evaluate the when clause. Since a
/// when clause can yield a false value, it can jump back to a label in the lowered decision dag.
/// </summary>
private readonly PooledDictionary<
SyntaxNode,
ArrayBuilder<BoundStatement>
> _switchArms = PooledDictionary<
SyntaxNode,
ArrayBuilder<BoundStatement>
>.GetInstance();
protected override ArrayBuilder<BoundStatement> BuilderForSection(
SyntaxNode whenClauseSyntax
)
{
// We need the section syntax to get the section builder from the map. Unfortunately this is a bit awkward
SyntaxNode? sectionSyntax = whenClauseSyntax is SwitchLabelSyntax l
? l.Parent
: whenClauseSyntax;
Debug.Assert(sectionSyntax is { });
bool found = _switchArms.TryGetValue(
sectionSyntax,
out ArrayBuilder<BoundStatement>? result
);
if (!found || result == null)
throw new InvalidOperationException();
return result;
}
protected BaseSwitchLocalRewriter(
SyntaxNode node,
LocalRewriter localRewriter,
ImmutableArray<SyntaxNode> arms,
bool generateInstrumentation
) : base(node, localRewriter, generateInstrumentation)
{
foreach (var arm in arms)
{
var armBuilder = ArrayBuilder<BoundStatement>.GetInstance();
// We start each switch block of a switch statement with a hidden sequence point so that
// we do not appear to be in the previous switch block when we begin.
if (GenerateInstrumentation)
armBuilder.Add(_factory.HiddenSequencePoint());
_switchArms.Add(arm, armBuilder);
}
}
protected new void Free()
{
_switchArms.Free();
base.Free();
}
/// <summary>
/// Lower the given nodes into _loweredDecisionDag. Should only be called once per instance of this.
/// </summary>
protected (ImmutableArray<BoundStatement> loweredDag, ImmutableDictionary<
SyntaxNode,
ImmutableArray<BoundStatement>
> switchSections) LowerDecisionDag(BoundDecisionDag decisionDag)
{
var loweredDag = LowerDecisionDagCore(decisionDag);
var switchSections = _switchArms.ToImmutableDictionary(
kv => kv.Key,
kv => kv.Value.ToImmutableAndFree()
);
_switchArms.Clear();
return (loweredDag, switchSections);
}
}
}
}
| 40.484536 | 122 | 0.572193 | [
"MIT"
] | belav/roslyn | src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_BasePatternSwitchLocalRewriter.cs | 3,929 | 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;
namespace Aliyun.Acs.companyreg.Model.V20200306
{
public class PutMeasureDataResponse : AcsResponse
{
private string requestId;
private bool? data;
public string RequestId
{
get
{
return requestId;
}
set
{
requestId = value;
}
}
public bool? Data
{
get
{
return data;
}
set
{
data = value;
}
}
}
}
| 22.350877 | 63 | 0.684458 | [
"Apache-2.0"
] | aliyun/aliyun-openapi-net-sdk | aliyun-net-sdk-companyreg/Companyreg/Model/V20200306/PutMeasureDataResponse.cs | 1,274 | C# |
/*
__ __ _ __ __ _ _ _ _
| \/ | | | | \/ (_) | | | (_)
| \ / | __ _ _ __| | __ | \ / |_ ___| |__ __ _ ___| |_ ___
| |\/| |/ _` | '__| |/ / | |\/| | |/ __| '_ \ / _` |/ _ \ | / __|
| | | | (_| | | | < | | | | | (__| | | | (_| | __/ | \__ \
|_| |_|\__,_|_| |_|\_\ |_| |_|_|\___|_| |_|\__,_|\___|_|_|___/
_ __ _ ____ _
| |/ / (_) | _ \ | |
| ' / _____ ___ _ __ | |_) | ___ ___| |_
| < / _ \ \ / / | '_ \ | _ < / _ \/ __| __|
| . \ __/\ V /| | | | | | |_) | (_) \__ \ |_
|_|\_\___| \_/ |_|_| |_| |____/ \___/|___/\__|
_____ _ _ ___
/ ____|| || |_ / _ \
| | |_ __ _| | (_) |
| | _| || |_ \__, |
| |___|_ __ _| / /
\_____||_||_| /_/
FinglePrint because FingerPrint is hard to spell
*/ | 40.772727 | 65 | 0.259755 | [
"MIT"
] | BenjaminMichaelis/SpokaneNETUserGroupSamples | 2020.11.10-CShap9/CSharp9/00-Intro.cs | 897 | C# |
using UnityEngine;
public class DebugMode : MonoBehaviour
{
int index = 0;
float lastTime;
public KeyCode[] phrase;
public bool debugEnabled;
void Update ()
{
if (Input.GetKeyUp(phrase[index]))
{
print(phrase[index]);
lastTime = Time.realtimeSinceStartup;
index++;
if (index == phrase.Length)
{
debugEnabled = !debugEnabled;
index = 0;
}
}
if (Time.realtimeSinceStartup > lastTime + 0.5f)
{
index = 0;
}
}
}
| 17.257143 | 56 | 0.485099 | [
"MIT"
] | sloan-gamedev-tutorials/manic-miner | Assets/Scripts/Debug/DebugMode.cs | 606 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace SmallTalks.Core.Models
{
public class MatchData
{
public string SmallTalk { get; internal set; }
public string Value { get; internal set; }
public int? Index { get; internal set; }
public int? Lenght { get; internal set; }
}
}
| 23.333333 | 54 | 0.648571 | [
"MIT"
] | mregisd/smalltalks | SmallTalks/SmallTalks.Core/Models/MatchData.cs | 352 | C# |
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
namespace IdentityServerHost
{
public class ScopeViewModel
{
public string Name { get; set; }
public string DisplayName { get; set; }
public string Description { get; set; }
public bool Emphasize { get; set; }
public bool Required { get; set; }
public bool Checked { get; set; }
}
}
| 30.705882 | 107 | 0.649425 | [
"MIT"
] | ardalis/TestSecureApiSample | IdentityServerHost/Quickstart/Consent/ScopeViewModel.cs | 524 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft;
using NuGet.ProjectManagement;
using NuGet.ProjectManagement.Projects;
using NuGet.ProjectModel;
namespace NuGet.VisualStudio.Internal.Contracts
{
public sealed class ProjectContextInfo : IProjectContextInfo
{
public ProjectContextInfo(string projectId, ProjectStyle projectStyle, NuGetProjectKind projectKind)
{
ProjectId = projectId;
ProjectStyle = projectStyle;
ProjectKind = projectKind;
}
public string ProjectId { get; }
public NuGetProjectKind ProjectKind { get; }
public ProjectStyle ProjectStyle { get; }
public static ValueTask<IProjectContextInfo> CreateAsync(NuGetProject nugetProject, CancellationToken cancellationToken)
{
Assumes.NotNull(nugetProject);
if (!nugetProject.TryGetMetadata(NuGetProjectMetadataKeys.ProjectId, out string projectId))
{
throw new InvalidOperationException();
}
NuGetProjectKind projectKind = GetProjectKind(nugetProject);
ProjectStyle projectStyle = nugetProject.ProjectStyle;
return new ValueTask<IProjectContextInfo>(new ProjectContextInfo(projectId, projectStyle, projectKind));
}
private static NuGetProjectKind GetProjectKind(NuGetProject nugetProject)
{
// Order matters
NuGetProjectKind projectKind = NuGetProjectKind.Unknown;
if (nugetProject is BuildIntegratedNuGetProject)
{
projectKind = NuGetProjectKind.PackageReference;
}
else if (nugetProject is MSBuildNuGetProject)
{
projectKind = NuGetProjectKind.PackagesConfig;
}
return projectKind;
}
}
}
| 34.677966 | 128 | 0.672532 | [
"Apache-2.0"
] | 0xced/NuGet.Client | src/NuGet.Clients/NuGet.VisualStudio.Internal.Contracts/ProjectContextInfo.cs | 2,046 | C# |
/**
* Copyright(c) Live2D Inc. All rights reserved.
*
* Use of this source code is governed by the Live2D Open Software license
* that can be found at https://www.live2d.com/eula/live2d-open-software-license-agreement_en.html.
*/
using Live2D.Cubism.Core;
using Live2D.Cubism.Rendering;
using UnityEngine;
namespace Live2D.Cubism.Framework.Json
{
/// <summary>
/// Default pickers.
/// </summary>
public static class CubismBuiltinPickers
{
/// <summary>
/// Builtin <see cref="Material"/> picker.
/// </summary>
/// <param name="sender">Event source.</param>
/// <param name="drawable">Drawable to map to.</param>
/// <returns>Mapped texture.</returns>
public static Material MaterialPicker(CubismModel3Json sender, CubismDrawable drawable)
{
if (drawable.BlendAdditive)
{
return (drawable.IsMasked)
? (drawable.IsInverted) ? CubismBuiltinMaterials.UnlitAdditiveMaskedInverted : CubismBuiltinMaterials.UnlitAdditiveMasked
: CubismBuiltinMaterials.UnlitAdditive;
}
if (drawable.MultiplyBlend)
{
return (drawable.IsMasked)
? (drawable.IsInverted) ? CubismBuiltinMaterials.UnlitMultiplyMaskedInverted : CubismBuiltinMaterials.UnlitMultiplyMasked
: CubismBuiltinMaterials.UnlitMultiply;
}
return (drawable.IsMasked)
? (drawable.IsInverted) ? CubismBuiltinMaterials.UnlitMaskedInverted : CubismBuiltinMaterials.UnlitMasked
: CubismBuiltinMaterials.Unlit;
}
/// <summary>
/// Builtin <see cref="Texture2D"/> picker.
/// </summary>
/// <param name="sender">Event source.</param>
/// <param name="drawable">Drawable to map to.</param>
/// <returns>Mapped texture.</returns>
public static Texture2D TexturePicker(CubismModel3Json sender, CubismDrawable drawable)
{
return sender.Textures[drawable.TextureIndex];
}
}
}
| 33.857143 | 141 | 0.620253 | [
"MIT"
] | NAJA5152/TouhouMachineLearning2022 | Assets/Plugins/Live2D/Cubism/Framework/Json/CubismBuiltinPickers.cs | 2,135 | C# |
using System;
using System.Collections.Generic;
namespace P4_ListasYNumeros
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(" ");
//Inicialización del array
string[] numeros = new string[5] {"1", "2", "3", "4", "5"};
//Modificaciones del array
numeros[1] = "6";
numeros[4] = "7";
numeros[0] = null;
//Reasignación de valores del array
for (int i = 0; i < 4; i++)
{
numeros[i] = numeros[i+1];
}
numeros[4] = "8";
//Mostrar los valores del array
for (int i = 0; i < numeros.Length; i++)
{
Console.Write(numeros[i] + " ");
}
//Creación de la lista de numeros
List<int> listaNumeros = new List<int>();
Console.WriteLine(" ");
Console.WriteLine(" ");
//Asignacion de valores a la lista del 1 al 5
for (int i = 0; i < 5; i++)
{
listaNumeros.Add(i + 1);
}
listaNumeros[1] = 6;
listaNumeros[4] = 7;
//Remover el primer número
listaNumeros.RemoveAt(0);
//Añadir el 8 al final
listaNumeros.Add(8);
//Añadir el 9 al final
listaNumeros.Add(9);
//Multiplicar los números de la lista *3
for (int i = 0; i < listaNumeros.Count; i++)
{
listaNumeros[i] = listaNumeros[i] * 3;
}
// Eliminar los numeros de la lista que sean mayores a 20
for (int i = 0; i < listaNumeros.Count; i++)
{
if (listaNumeros[i] > 20)
{
listaNumeros.RemoveAt(i);
i--;
}
}
//Mostrar los valores de la lista
for (int i = 0; i < listaNumeros.Count; i++)
{
Console.Write(listaNumeros[i] + " ");
}
// Crear una lista de números enteros
List<int> listaNumeros1 = new List<int>();
// Asignarle los numeros: 2, 6, 19, 34, 65, 12, 42, 33, 40, 15
listaNumeros1.Add(2);
listaNumeros1.Add(6);
listaNumeros1.Add(19);
listaNumeros1.Add(34);
listaNumeros1.Add(65);
listaNumeros1.Add(12);
listaNumeros1.Add(42);
listaNumeros1.Add(33);
listaNumeros1.Add(40);
listaNumeros1.Add(15);
int NumeroMayor1 = 0;
Console.WriteLine(" ");
//Verificar el número mayor de la primer lista
for(int i = 0; i < listaNumeros1.Count; i++)
{
if(listaNumeros1[i] > NumeroMayor1)
{
NumeroMayor1 = listaNumeros1[i];
}
}
Console.WriteLine(" ");
for(int i = 0; i < listaNumeros1.Count; i++)
{
Console.Write(listaNumeros1[i] + " ");
}
Console.WriteLine(" ");
Console.WriteLine("El numero mayor de la lista es: " + NumeroMayor1);
}
}
}
| 23.306122 | 81 | 0.429947 | [
"MIT"
] | RAMZ-66/P4_ListasYNumeros | Program.cs | 3,437 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using SeoSchema;
using SeoSchema.Enumerations;
using SuperStructs;
namespace SeoSchema.Entities
{
/// <summary>
/// An airline flight.
/// <see cref="https://schema.org/Flight"/>
/// </summary>
public class Flight : IEntity
{
/// The kind of aircraft (e.g., "Boeing 747").
public Or<string, Vehicle>? Aircraft { get; set; }
/// The airport where the flight terminates.
public Or<Airport>? ArrivalAirport { get; set; }
/// Identifier of the flight's arrival gate.
public Or<string>? ArrivalGate { get; set; }
/// Identifier of the flight's arrival terminal.
public Or<string>? ArrivalTerminal { get; set; }
/// The type of boarding policy used by the airline (e.g. zone-based or group-based).
public Or<BoardingPolicyType>? BoardingPolicy { get; set; }
/// The airport where the flight originates.
public Or<Airport>? DepartureAirport { get; set; }
/// Identifier of the flight's departure gate.
public Or<string>? DepartureGate { get; set; }
/// Identifier of the flight's departure terminal.
public Or<string>? DepartureTerminal { get; set; }
/// The estimated time the flight will take.
public Or<Duration, string>? EstimatedFlightDuration { get; set; }
/// The distance of the flight.
public Or<Distance, string>? FlightDistance { get; set; }
/// The unique identifier for a flight including the airline IATA code. For example, if describing United flight 110, where the IATA code for United is 'UA', the flightNumber is 'UA110'.
public Or<string>? FlightNumber { get; set; }
/// Description of the meals that will be provided or available for purchase.
public Or<string>? MealService { get; set; }
/// An entity which offers (sells / leases / lends / loans) the services / goods. A seller may also be a provider. Supersedes merchant, vendor.
public Or<Organization, Person>? Seller { get; set; }
/// The time when a passenger can check into the flight online.
public Or<DateTime>? WebCheckinTime { get; set; }
/// The expected arrival time.
public Or<DateTime>? ArrivalTime { get; set; }
/// The expected departure time.
public Or<DateTime>? DepartureTime { get; set; }
/// Indicates an item or CreativeWork that is part of this item, or CreativeWork (in some sense). Inverse property: isPartOf.
public Or<CreativeWork, Trip>? HasPart { get; set; }
/// Indicates an item or CreativeWork that this item, or CreativeWork (in some sense), is part of. Inverse property: hasPart.
public Or<CreativeWork, Trip>? IsPartOf { get; set; }
/// Destination(s) ( Place ) that make up a trip. For a trip where destination order is important use ItemList to specify that order (see examples).
public Or<ItemList, Place>? Itinerary { get; set; }
/// An offer to provide this item—for example, an offer to sell a product, rent the DVD of a movie, perform a service, or give away tickets to an event.
public Or<Offer>? Offers { get; set; }
/// The service provider, service operator, or service performer; the goods producer. Another party (a seller) may offer those services or goods on behalf of the provider. A provider may also serve as the seller. Supersedes carrier.
public Or<Organization, Person>? Provider { get; set; }
/// An additional type for the item, typically used for adding more specific types from external vocabularies in microdata syntax. This is a relationship between something and a class that the thing is in. In RDFa syntax, it is better to use the native RDFa syntax - the 'typeof' attribute - for multiple types. Schema.org tools may have only weaker understanding of extra types, in particular those defined externally.
public Or<Uri>? AdditionalType { get; set; }
/// An alias for the item.
public Or<string>? AlternateName { get; set; }
/// A description of the item.
public Or<string>? Description { get; set; }
/// A sub property of description. A short description of the item used to disambiguate from other, similar items. Information from other properties (in particular, name) may be necessary for the description to be useful for disambiguation.
public Or<string>? DisambiguatingDescription { get; set; }
/// The identifier property represents any kind of identifier for any kind of Thing, such as ISBNs, GTIN codes, UUIDs etc. Schema.org provides dedicated properties for representing many of these, either as textual strings or as URL (URI) links. See background notes for more details.
public Or<PropertyValue, string, Uri>? Identifier { get; set; }
/// An image of the item. This can be a URL or a fully described ImageObject.
public Or<ImageObject, Uri>? Image { get; set; }
/// Indicates a page (or other CreativeWork) for which this thing is the main entity being described. See background notes for details. Inverse property: mainEntity.
public Or<CreativeWork, Uri>? MainEntityOfPage { get; set; }
/// The name of the item.
public Or<string>? Name { get; set; }
/// Indicates a potential Action, which describes an idealized action in which this thing would play an 'object' role.
public Or<Action>? PotentialAction { get; set; }
/// URL of a reference Web page that unambiguously indicates the item's identity. E.g. the URL of the item's Wikipedia page, Wikidata entry, or official website.
public Or<Uri>? SameAs { get; set; }
/// A CreativeWork or Event about this Thing.. Inverse property: about.
public Or<CreativeWork, Event>? SubjectOf { get; set; }
/// URL of the item.
public Or<Uri>? Url { get; set; }
}
}
| 51.504274 | 427 | 0.671922 | [
"MIT"
] | jefersonsv/SeoSchema | src/SeoSchema/Entities/Flight.cs | 6,028 | C# |
// Copyright 2019 Maintainers of NUKE.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE
using System;
using System.IO;
using System.Linq;
using Nuke.Common.IO;
namespace Nuke.Common.Utilities
{
public class CustomFileWriter : IDisposable
{
private readonly FileStream _fileStream;
private readonly StreamWriter _streamWriter;
private readonly int _indentationFactor;
private int _indentation;
public CustomFileWriter(string filename, int indentationFactor, FileMode fileMode = FileMode.Create)
{
FileSystemTasks.EnsureExistingParentDirectory(filename);
_fileStream = File.Open(filename, fileMode);
_streamWriter = new StreamWriter(_fileStream);
_indentationFactor = indentationFactor;
}
public void Dispose()
{
_streamWriter.Dispose();
_fileStream.Dispose();
}
public void WriteLine(string text = null)
{
_streamWriter.WriteLine(
text != null
? $"{new string(c: ' ', _indentation * _indentationFactor)}{text}"
: string.Empty);
}
public IDisposable Indent()
{
return DelegateDisposable.CreateBracket(
() => _indentation++,
() => _indentation--);
}
}
}
| 28.58 | 108 | 0.603919 | [
"MIT"
] | robsonj/common | source/Nuke.Common/Utilities/CustomFileWriter.cs | 1,429 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public static class WinController
{
public static bool Win = false;
public static bool Game1Done = false;
}
| 18.909091 | 42 | 0.725962 | [
"MIT"
] | Jiawen-Zhang/GGJ-W2020 | Coronavania/Assets/Scripts/WinController.cs | 210 | C# |
using UnityEngine;
namespace RockVR.Common
{
/// <summary>
/// Be aware this will not prevent a non singleton constructor
/// such as `T myT = new T();`
/// To prevent that, add `protected T () {}` to your singleton class.
///
/// As a note, this is made as MonoBehaviour because we need Coroutines.
/// Modified from: http://wiki.unity3d.com/index.php/Singleton
/// </summary>
public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
private static T _instance;
private static object _lock = new object();
public static T instance
{
get
{
if (applicationIsQuitting)
{
Debug.LogWarning("[Singleton] Instance '" + typeof(T) +
"' already destroyed on application quit." +
" Won't create again - returning null.");
return null;
}
lock (_lock)
{
if (_instance == null)
{
_instance = (T)FindObjectOfType(typeof(T));
if (FindObjectsOfType(typeof(T)).Length > 1)
{
Debug.LogError("[Singleton] Something went really wrong " +
" - there should never be more than 1 singleton!" +
" Reopening the scene might fix it.");
return _instance;
}
if (_instance == null)
{
GameObject singleton = new GameObject();
_instance = singleton.AddComponent<T>();
singleton.name = typeof(T).Name;
DontDestroyOnLoad(singleton);
Debug.Log("[Singleton] An instance of " + typeof(T) +
" is needed in the scene, so '" + singleton +
"' was created with DontDestroyOnLoad.");
}
else
{
Debug.Log("[Singleton] Using instance already created: " +
_instance.gameObject.name);
}
}
return _instance;
}
}
}
/// <summary>
/// If this script is placed on game objec in the scene, make sure to
/// keep only instance.
/// </summary>
protected virtual void Awake()
{
if (_instance == null)
{
_instance = this as T;
DontDestroyOnLoad(gameObject);
}
else if (_instance != this)
{
Destroy(gameObject);
}
}
private static bool applicationIsQuitting = false;
/// <summary>
/// When Unity quits, it destroys objects in a random order.
/// In principle, a Singleton is only destroyed when application quits.
/// If any script calls Instance after it have been destroyed,
/// it will create a buggy ghost object that will stay on the Editor scene
/// even after stopping playing the Application. Really bad!
/// So, this was made to be sure we're not creating that buggy ghost object.
/// </summary>
protected virtual void OnApplicationQuit()
{
applicationIsQuitting = true;
}
}
} | 38.142857 | 88 | 0.449438 | [
"MIT"
] | adarshmelethil/TankTourney | Assets/RockVR/Common/Scripts/Singleton.cs | 3,740 | C# |
using System;
using CMS.UIControls;
public partial class CMSFormControls_LiveSelectors_InsertImageOrMedia_Default : CMSLiveModalPage
{
protected string mBlankUrl = null;
protected void Page_Load(object sender, EventArgs e)
{
mBlankUrl = ResolveUrl("~/CMSPages/blank.htm");
}
} | 23 | 97 | 0.701863 | [
"MIT"
] | CMeeg/kentico-contrib | src/CMS/CMSFormControls/LiveSelectors/InsertImageOrMedia/Default.aspx.cs | 324 | C# |
// *****************************************************************************
// BSD 3-Clause License (https://github.com/ComponentFactory/Krypton/blob/master/LICENSE)
// © Component Factory Pty Ltd, 2006-2019, All rights reserved.
// The software and associated documentation supplied hereunder are the
// proprietary information of Component Factory Pty Ltd, 13 Swallows Close,
// Mornington, Vic 3931, Australia and are supplied subject to license terms.
//
// Modifications by Peter Wagner(aka Wagnerp) & Simon Coghlan(aka Smurf-IV) 2017 - 2019. All rights reserved. (https://github.com/Wagnerp/Krypton-NET-5.480)
// Version 5.480.0.0 www.ComponentFactory.com
// *****************************************************************************
using System.Drawing;
using System.Windows.Forms;
namespace ComponentFactory.Krypton.Toolkit
{
/// <summary>
/// Encapsulates context for view layout operations.
/// </summary>
public class ViewLayoutContext : ViewContext
{
#region Instance Fields
#endregion
#region Identity
/// <summary>
/// Initialize a new instance of the ViewContext class.
/// </summary>
/// <param name="control">Control associated with rendering.</param>
/// <param name="renderer">Rendering provider.</param>
public ViewLayoutContext(Control control,
IRenderer renderer)
: this(null, control, control, null, renderer, control.Size)
{
}
/// <summary>
/// Initialize a new instance of the ViewContext class.
/// </summary>
/// <param name="manager">Reference to the view manager.</param>
/// <param name="control">Control associated with rendering.</param>
/// <param name="alignControl">Control used for aligning elements.</param>
/// <param name="renderer">Rendering provider.</param>
public ViewLayoutContext(ViewManager manager,
Control control,
Control alignControl,
IRenderer renderer)
: this(manager, control, alignControl, null, renderer, control.Size)
{
}
/// <summary>
/// Initialize a new instance of the ViewContext class.
/// </summary>
/// <param name="manager">Reference to the view manager.</param>
/// <param name="control">Control associated with rendering.</param>
/// <param name="alignControl">Control used for aligning elements.</param>
/// <param name="renderer">Rendering provider.</param>
/// <param name="displaySize">Display size.</param>
public ViewLayoutContext(ViewManager manager,
Control control,
Control alignControl,
IRenderer renderer,
Size displaySize)
: this(manager, control, alignControl, null, renderer, displaySize)
{
}
/// <summary>
/// Initialize a new instance of the ViewContext class.
/// </summary>
/// <param name="manager">Reference to the view manager.</param>
/// <param name="form">Form associated with rendering.</param>
/// <param name="formRect">Window rectangle for the Form.</param>
/// <param name="renderer">Rendering provider.</param>
public ViewLayoutContext(ViewManager manager,
Form form,
Rectangle formRect,
IRenderer renderer)
: base(manager, form, form, null, renderer)
{
// The initial display rectangle is the provided size
DisplayRectangle = new Rectangle(Point.Empty, formRect.Size);
}
/// <summary>
/// Initialize a new instance of the ViewContext class.
/// </summary>
/// <param name="manager">Reference to the view manager.</param>
/// <param name="control">Control associated with rendering.</param>
/// <param name="alignControl">Control used for aligning elements.</param>
/// <param name="graphics">Graphics instance for drawing.</param>
/// <param name="renderer">Rendering provider.</param>
/// <param name="displaySize">Display size.</param>
public ViewLayoutContext(ViewManager manager,
Control control,
Control alignControl,
Graphics graphics,
IRenderer renderer,
Size displaySize)
: base(manager, control, alignControl, graphics, renderer)
{
// The initial display rectangle is the provided size
DisplayRectangle = new Rectangle(Point.Empty, displaySize);
}
#endregion
#region Public Properties
/// <summary>
/// Gets and sets the available display area.
/// </summary>
public Rectangle DisplayRectangle { get; set; }
#endregion
}
}
| 42.579832 | 157 | 0.574896 | [
"BSD-3-Clause"
] | MarketingInternetOnlines/Krypton-NET-5.480 | Source/Krypton Components/ComponentFactory.Krypton.Toolkit/View Layout/ViewLayoutContext.cs | 5,070 | C# |
// -----------------------------------------------------------------------------
// 让 .NET 开发更简单,更通用,更流行。
// Copyright © 2020-2021 Furion, 百小僧, Baiqian Co.,Ltd.
//
// 框架名称:Furion
// 框架作者:百小僧
// 框架版本:2.8.9
// 源码地址:Gitee: https://gitee.com/dotnetchina/Furion
// Github:https://github.com/monksoul/Furion
// 开源协议:Apache-2.0(https://gitee.com/dotnetchina/Furion/blob/master/LICENSE)
// -----------------------------------------------------------------------------
namespace System.Running
{
/// <summary>
/// 默认日志分类名
/// </summary>
internal sealed class Logging
{
}
} | 28.571429 | 81 | 0.463333 | [
"Apache-2.0"
] | jakinchan/Furion | framework/Furion.Pure/Logging/Internal/Logging.cs | 717 | C# |
namespace WaterAddition.UI.Pages.Main
{
public partial class MainPage : BasePage
{
public MainPage ()
{
InitializeComponent ();
}
}
}
| 13.272727 | 41 | 0.684932 | [
"MIT"
] | Porodin/WaterAddition | WaterAddition/UI/Pages/Main/MainPage.xaml.cs | 146 | C# |
#region Header
/**
* JsonWriter.cs
* Stream-like facility to output JSON text.
*
* The authors disclaim copyright to this source code. For more details, see
* the COPYING file included with this distribution.
**/
#endregion
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
namespace LitJson
{
internal enum Condition
{
InArray,
InObject,
NotAProperty,
Property,
Value
}
internal class WriterContext
{
public int Count;
public bool InArray;
public bool InObject;
public bool ExpectingValue;
public int Padding;
}
public class JsonWriter
{
#region Fields
private static readonly NumberFormatInfo number_format;
private WriterContext context;
private Stack<WriterContext> ctx_stack;
private bool has_reached_end;
private char[] hex_seq;
private int indentation;
private int indent_value;
private StringBuilder inst_string_builder;
private bool pretty_print;
private bool validate;
private bool lower_case_properties;
private TextWriter writer;
#endregion
#region Properties
public int IndentValue {
get { return indent_value; }
set {
indentation = (indentation / indent_value) * value;
indent_value = value;
}
}
public bool PrettyPrint {
get { return pretty_print; }
set { pretty_print = value; }
}
public TextWriter TextWriter {
get { return writer; }
}
public bool Validate {
get { return validate; }
set { validate = value; }
}
public bool LowerCaseProperties {
get { return lower_case_properties; }
set { lower_case_properties = value; }
}
#endregion
#region Constructors
static JsonWriter ()
{
number_format = NumberFormatInfo.InvariantInfo;
}
public JsonWriter ()
{
inst_string_builder = new StringBuilder ();
writer = new StringWriter (inst_string_builder);
Init ();
}
public JsonWriter (StringBuilder sb) :
this (new StringWriter (sb))
{
}
public JsonWriter (TextWriter writer)
{
if (writer == null)
throw new ArgumentNullException ("writer");
this.writer = writer;
Init ();
}
#endregion
#region Private Methods
private void DoValidation (Condition cond)
{
if (! context.ExpectingValue)
context.Count++;
if (! validate)
return;
if (has_reached_end)
throw new JsonException (
"A complete JSON symbol has already been written");
switch (cond) {
case Condition.InArray:
if (! context.InArray)
throw new JsonException (
"Can't close an array here");
break;
case Condition.InObject:
if (! context.InObject || context.ExpectingValue)
throw new JsonException (
"Can't close an object here");
break;
case Condition.NotAProperty:
if (context.InObject && ! context.ExpectingValue)
throw new JsonException (
"Expected a property");
break;
case Condition.Property:
if (! context.InObject || context.ExpectingValue)
throw new JsonException (
"Can't add a property here");
break;
case Condition.Value:
if (! context.InArray &&
(! context.InObject || ! context.ExpectingValue))
throw new JsonException (
"Can't add a value here");
break;
}
}
private void Init ()
{
has_reached_end = false;
hex_seq = new char[4];
indentation = 0;
indent_value = 4;
pretty_print = false;
validate = true;
lower_case_properties = false;
ctx_stack = new Stack<WriterContext> ();
context = new WriterContext ();
ctx_stack.Push (context);
}
private static void IntToHex (int n, char[] hex)
{
int num;
for (int i = 0; i < 4; i++) {
num = n % 16;
if (num < 10)
hex[3 - i] = (char) ('0' + num);
else
hex[3 - i] = (char) ('A' + (num - 10));
n >>= 4;
}
}
private void Indent ()
{
if (pretty_print)
indentation += indent_value;
}
private void Put (string str)
{
if (pretty_print && ! context.ExpectingValue)
for (int i = 0; i < indentation; i++)
writer.Write (' ');
writer.Write (str);
}
private void PutNewline ()
{
PutNewline (true);
}
private void PutNewline (bool add_comma)
{
if (add_comma && ! context.ExpectingValue &&
context.Count > 1)
writer.Write (',');
if (pretty_print && ! context.ExpectingValue)
writer.Write (Environment.NewLine);
}
private void PutString (string str)
{
Put (String.Empty);
writer.Write ('"');
int n = str.Length;
for (int i = 0; i < n; i++) {
switch (str[i]) {
case '\n':
writer.Write ("\\n");
continue;
case '\r':
writer.Write ("\\r");
continue;
case '\t':
writer.Write ("\\t");
continue;
case '"':
case '\\':
writer.Write ('\\');
writer.Write (str[i]);
continue;
case '\f':
writer.Write ("\\f");
continue;
case '\b':
writer.Write ("\\b");
continue;
}
if ((int) str[i] >= 32 && (int) str[i] <= 126) {
writer.Write (str[i]);
continue;
}
// Default, turn into a \uXXXX sequence
IntToHex ((int) str[i], hex_seq);
writer.Write ("\\u");
writer.Write (hex_seq);
}
writer.Write ('"');
}
private void Unindent ()
{
if (pretty_print)
indentation -= indent_value;
}
#endregion
public override string ToString ()
{
if (inst_string_builder == null)
return String.Empty;
return inst_string_builder.ToString ();
}
public void Reset ()
{
has_reached_end = false;
ctx_stack.Clear ();
context = new WriterContext ();
ctx_stack.Push (context);
if (inst_string_builder != null)
inst_string_builder.Remove (0, inst_string_builder.Length);
}
public void Write (bool boolean)
{
DoValidation (Condition.Value);
PutNewline ();
Put (boolean ? "true" : "false");
context.ExpectingValue = false;
}
public void Write (decimal number)
{
DoValidation (Condition.Value);
PutNewline ();
Put (Convert.ToString (number, number_format));
context.ExpectingValue = false;
}
public void Write (double number)
{
DoValidation (Condition.Value);
PutNewline ();
string str = Convert.ToString (number, number_format);
Put (str);
if (str.IndexOf ('.') == -1 &&
str.IndexOf ('E') == -1)
writer.Write (".0");
context.ExpectingValue = false;
}
public void Write (int number)
{
DoValidation (Condition.Value);
PutNewline ();
Put (Convert.ToString (number, number_format));
context.ExpectingValue = false;
}
public void Write (long number)
{
DoValidation (Condition.Value);
PutNewline ();
Put (Convert.ToString (number, number_format));
context.ExpectingValue = false;
}
public void Write (string str)
{
DoValidation (Condition.Value);
PutNewline ();
if (str == null)
Put ("null");
else
PutString (str);
context.ExpectingValue = false;
}
// [XtraLife] Disable compiler warning...
#pragma warning disable 3021
[CLSCompliant(false)]
public void Write (ulong number)
{
DoValidation (Condition.Value);
PutNewline ();
Put (Convert.ToString (number, number_format));
context.ExpectingValue = false;
}
#pragma warning restore 3021
public void WriteArrayEnd ()
{
DoValidation (Condition.InArray);
PutNewline (false);
ctx_stack.Pop ();
if (ctx_stack.Count == 1)
has_reached_end = true;
else {
context = ctx_stack.Peek ();
context.ExpectingValue = false;
}
Unindent ();
Put ("]");
}
public void WriteArrayStart ()
{
DoValidation (Condition.NotAProperty);
PutNewline ();
Put ("[");
context = new WriterContext ();
context.InArray = true;
ctx_stack.Push (context);
Indent ();
}
public void WriteObjectEnd ()
{
DoValidation (Condition.InObject);
PutNewline (false);
ctx_stack.Pop ();
if (ctx_stack.Count == 1)
has_reached_end = true;
else {
context = ctx_stack.Peek ();
context.ExpectingValue = false;
}
Unindent ();
Put ("}");
}
public void WriteObjectStart ()
{
DoValidation (Condition.NotAProperty);
PutNewline ();
Put ("{");
context = new WriterContext ();
context.InObject = true;
ctx_stack.Push (context);
Indent ();
}
public void WritePropertyName (string property_name)
{
DoValidation (Condition.Property);
PutNewline ();
string propertyName = (property_name == null || !lower_case_properties)
? property_name
: property_name.ToLowerInvariant();
PutString (propertyName);
if (pretty_print) {
if (propertyName.Length > context.Padding)
context.Padding = propertyName.Length;
for (int i = context.Padding - propertyName.Length;
i >= 0; i--)
writer.Write (' ');
writer.Write (": ");
} else
writer.Write (':');
context.ExpectingValue = true;
}
}
}
| 25.595388 | 83 | 0.460562 | [
"MIT"
] | AndrewMSHowe/unity-sdk | CotcSdk/Libs/LitJson/JsonWriter.cs | 12,209 | C# |
#region BSD License
/*
*
* Original BSD 3-Clause License (https://github.com/ComponentFactory/Krypton/blob/master/LICENSE)
* © Component Factory Pty Ltd, 2006 - 2016, (Version 4.5.0.0) All rights reserved.
*
* New BSD 3-Clause License (https://github.com/Krypton-Suite/Standard-Toolkit/blob/master/LICENSE)
* Modifications by Peter Wagner(aka Wagnerp) & Simon Coghlan(aka Smurf-IV), et al. 2017 - 2021. All rights reserved.
*
*/
#endregion
namespace Krypton.Toolkit
{
/// <summary>
/// View element that can draw a separator
/// </summary>
public class ViewDrawSeparator : ViewLeaf
{
#region Instance Fields
internal IPaletteDouble _paletteDisabled;
internal IPaletteDouble _paletteNormal;
internal IPaletteDouble _paletteTracking;
internal IPaletteDouble _palettePressed;
internal IPaletteMetric _metricDisabled;
internal IPaletteMetric _metricNormal;
internal IPaletteMetric _metricTracking;
internal IPaletteMetric _metricPressed;
internal IPaletteDouble _palette;
internal IPaletteMetric _metric;
#endregion
#region Identity
/// <summary>
/// Initialize a new instance of the ViewDrawSeparator class.
/// </summary>
/// <param name="paletteDisabled">Palette source for the disabled state.</param>
/// <param name="paletteNormal">Palette source for the normal state.</param>
/// <param name="paletteTracking">Palette source for the tracking state.</param>
/// <param name="palettePressed">Palette source for the pressed state.</param>
/// <param name="metricDisabled">Palette source for disabled metric values.</param>
/// <param name="metricNormal">Palette source for normal metric values.</param>
/// <param name="metricTracking">Palette source for tracking metric values.</param>
/// <param name="metricPressed">Palette source for pressed metric values.</param>
/// <param name="metricPadding">Metric used to get padding values.</param>
/// <param name="orientation">Visual orientation of the content.</param>
public ViewDrawSeparator(IPaletteDouble paletteDisabled, IPaletteDouble paletteNormal,
IPaletteDouble paletteTracking, IPaletteDouble palettePressed,
IPaletteMetric metricDisabled, IPaletteMetric metricNormal,
IPaletteMetric metricTracking, IPaletteMetric metricPressed,
PaletteMetricPadding metricPadding,
Orientation orientation)
{
Debug.Assert(paletteDisabled != null);
Debug.Assert(paletteNormal != null);
Debug.Assert(paletteTracking != null);
Debug.Assert(palettePressed != null);
Debug.Assert(metricDisabled != null);
Debug.Assert(metricNormal != null);
Debug.Assert(metricTracking != null);
Debug.Assert(metricPressed != null);
// Remember the source information
_paletteDisabled = paletteDisabled;
_paletteNormal = paletteNormal;
_paletteTracking = paletteTracking;
_palettePressed = palettePressed;
_metricDisabled = metricDisabled;
_metricNormal = metricNormal;
_metricTracking = metricTracking;
_metricPressed = metricPressed;
MetricPadding = metricPadding;
Orientation = orientation;
// Default other state
Length = 0;
}
/// <summary>
/// Obtains the String representation of this instance.
/// </summary>
/// <returns>User readable name of the instance.</returns>
public override string ToString()
{
// Return the class name and instance identifier
return "ViewDrawSeparator:" + Id;
}
#endregion
#region MetricPadding
/// <summary>
/// Gets and sets the metric used to calculate the padding.
/// </summary>
public PaletteMetricPadding MetricPadding { get; set; }
#endregion
#region Source
/// <summary>
/// Gets and sets the associated separator source.
/// </summary>
public ISeparatorSource Source { get; set; }
#endregion
#region Orientation
/// <summary>
/// Gets and sets the visual orientation.
/// </summary>
public Orientation Orientation { get; set; }
#endregion
#region Length
/// <summary>
/// Gets and sets the length of the separator.
/// </summary>
public int Length { get; set; }
#endregion
#region SetPalettes
/// <summary>
/// Update the source palettes for drawing.
/// </summary>
/// <param name="paletteDisabled">Palette source for the disabled state.</param>
/// <param name="paletteNormal">Palette source for the normal state.</param>
/// <param name="paletteTracking">Palette source for the tracking state.</param>
/// <param name="palettePressed">Palette source for the pressed state.</param>
/// <param name="metricDisabled">Palette source for disabled metric values.</param>
/// <param name="metricNormal">Palette source for normal metric values.</param>
/// <param name="metricTracking">Palette source for tracking metric values.</param>
/// <param name="metricPressed">Palette source for pressed metric values.</param>
public void SetPalettes(IPaletteDouble paletteDisabled,
IPaletteDouble paletteNormal,
IPaletteDouble paletteTracking,
IPaletteDouble palettePressed,
IPaletteMetric metricDisabled,
IPaletteMetric metricNormal,
IPaletteMetric metricTracking,
IPaletteMetric metricPressed)
{
Debug.Assert(paletteDisabled != null);
Debug.Assert(paletteNormal != null);
Debug.Assert(paletteTracking != null);
Debug.Assert(palettePressed != null);
Debug.Assert(metricDisabled != null);
Debug.Assert(metricNormal != null);
Debug.Assert(metricTracking != null);
Debug.Assert(metricPressed != null);
// Use newly provided palettes
_paletteDisabled = paletteDisabled;
_paletteNormal = paletteNormal;
_paletteTracking = paletteTracking;
_palettePressed = palettePressed;
_metricDisabled = metricDisabled;
_metricNormal = metricNormal;
_metricTracking = metricTracking;
_metricPressed = metricPressed;
}
#endregion
#region Layout
/// <summary>
/// Discover the preferred size of the element.
/// </summary>
/// <param name="context">Layout context.</param>
public override Size GetPreferredSize(ViewLayoutContext context)
{
Debug.Assert(context != null);
return new Size(Length, Length);
}
/// <summary>
/// Perform a layout of the elements.
/// </summary>
/// <param name="context">Layout context.</param>
public override void Layout(ViewLayoutContext context)
{
Debug.Assert(context != null);
ClientRectangle = context.DisplayRectangle;
}
#endregion
#region Paint
/// <summary>
/// Perform rendering before child elements are rendered.
/// </summary>
/// <param name="context">Rendering context.</param>
/// <exception cref="ArgumentNullException"></exception>
public override void RenderBefore(RenderContext context)
{
Debug.Assert(context != null);
// Validate reference parameter
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
// Ensure we are using the correct palette
CheckPaletteState();
// Apply padding needed outside the border of the separator
Rectangle rect = CommonHelper.ApplyPadding(Orientation, ClientRectangle,
_metric.GetMetricPadding(ElementState, MetricPadding));
// Ask the renderer to perform drawing of the separator glyph
context.Renderer.RenderGlyph.DrawSeparator(context, rect, _palette.PaletteBack, _palette.PaletteBorder,
Orientation, State, ((Source == null) || Source.SeparatorCanMove));
}
#endregion
#region Implementation
private void CheckPaletteState()
{
PaletteState state = (IsFixed ? FixedState : State);
// Set the current palette based on the element state
switch (state)
{
case PaletteState.Disabled:
_palette = _paletteDisabled;
_metric = _metricDisabled;
break;
case PaletteState.Normal:
_palette = _paletteNormal;
_metric = _metricNormal;
break;
case PaletteState.Pressed:
_palette = _palettePressed;
_metric = _metricPressed;
break;
case PaletteState.Tracking:
_palette = _paletteTracking;
_metric = _metricTracking;
break;
default:
// Should never happen!
Debug.Assert(false);
break;
}
}
#endregion
}
}
| 40.139442 | 122 | 0.581241 | [
"BSD-3-Clause"
] | cuteofdragon/Standard-Toolkit | Source/Krypton Components/Krypton.Toolkit/View Draw/ViewDrawSeparator.cs | 10,078 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class HighScores : MonoBehaviour
{
public Text[] scores = new Text[10];
// Start is called before the first frame update
void Start()
{
for (int i = 1; i <= 10; i++)
{
if (PlayerPrefs.GetInt(i + ".Score") != -1)
{
scores[i - 1].text = i + " - " + PlayerPrefs.GetInt(i + ".Score").ToString();
}
else
break;
}
}
}
| 21.92 | 93 | 0.514599 | [
"MIT"
] | yunus-topal/unityBabySteps | BasicMath/Assets/Scripts/HighScores.cs | 550 | 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("08 CoffeeShop.DA")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("08 CoffeeShop.DA")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("51cf50e7-6414-451b-ba77-1be41a0e6192")]
// 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.810811 | 85 | 0.727716 | [
"MIT"
] | giuliobosco/CsharpSAMT | 01-LearnMVVM/08 CoffeeShop.DA/Properties/AssemblyInfo.cs | 1,439 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Windows.Media;
using System.Windows.Media.Imaging;
namespace ThinkGeo.MapSuite.GisEditor.Plugins
{
[Serializable]
public class ImageSourceToImageBrushConverter : ValueConverter
{
public override object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
BitmapImage imageValue = value as BitmapImage;
if (imageValue != null)
{
ImageBrush imageBrush = new ImageBrush(imageValue);
imageBrush.TileMode = TileMode.None;
imageBrush.Stretch = Stretch.UniformToFill;
return imageBrush;
}
return null;
}
}
}
| 35.55814 | 129 | 0.703728 | [
"Apache-2.0"
] | ThinkGeo/GIS-Editor | MapSuiteGisEditor/GisEditorPluginCore/Shares/Converters/ImageSourceToImageBrushConverter.cs | 1,529 | C# |
using System;
using System.Threading.Tasks;
using AutoMapper;
using EMS.Events;
using HotChocolate;
using HotChocolate.Execution;
using Microsoft.EntityFrameworkCore;
using EMS.EventVerification_Services.API.Context;
using EMS.EventVerification_Services.API.Controllers.Request;
using EMS.TemplateWebHost.Customization.EventService;
using EMS.EventVerification_Services.API.Context.Model;
using EMS.TemplateWebHost.Customization.StartUp;
using Microsoft.AspNetCore.Authorization;
namespace EMS.EventVerification_Services.API.GraphQlQueries
{
public class EventVerificationMutations : BaseMutations
{
private readonly EventVerificationContext _context;
private readonly IMapper _mapper;
private readonly IEventService _eventService;
public EventVerificationMutations(EventVerificationContext context, IEventService template1EventService, IMapper mapper, IAuthorizationService authorizationService) : base(authorizationService)
{
_context = context ?? throw new ArgumentNullException(nameof(context)); ;
_eventService = template1EventService ?? throw new ArgumentNullException(nameof(template1EventService));
_mapper = mapper;
}
public async Task<EventVerification> VerifyCodeAsync(VerifyCodeRequest request)
{
var codeInt = int.Parse(request.Code, System.Globalization.NumberStyles.HexNumber);
var item = await _context.EventVerifications
.SingleOrDefaultAsync(ci => ci.EventId == request.EventId
&& ci.EventVerificationId == codeInt);
if (item == null)
{
throw new QueryException(
ErrorBuilder.New()
.SetMessage("Invalid code or eventId")
.SetCode("ID_UNKNOWN")
.Build());
}
if (item.Status != PresenceStatusEnum.SignedUp)
{
throw new QueryException(
ErrorBuilder.New()
.SetMessage("EventVerificationId have already been used")
.SetCode("ID_UNKNOWN")
.Build());
}
item.Status = PresenceStatusEnum.Attend;
_context.EventVerifications.Update(item);
await _context.SaveChangesAsync();
return item;
}
}
}
| 39.467742 | 201 | 0.644871 | [
"MIT"
] | EventMS/EMS | src/Services/EventVerification/EventVerification.API/GraphQlQueries/EventVerificationMutations.cs | 2,447 | C# |
// Copyright (c) 2014-2018 The Khronos Group Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and/or associated documentation files (the "Materials"),
// to deal in the Materials without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Materials, and to permit persons to whom the
// Materials are 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 Materials.
//
// MODIFICATIONS TO THIS FILE MAY MEAN IT NO LONGER ACCURATELY REFLECTS KHRONOS
// STANDARDS. THE UNMODIFIED, NORMATIVE VERSIONS OF KHRONOS SPECIFICATIONS AND
// HEADER INFORMATION ARE LOCATED AT https://www.khronos.org/registry/
//
// THE MATERIALS ARE 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 MATERIALS OR THE USE OR OTHER DEALINGS
// IN THE MATERIALS.
// This header is automatically generated by the same tool that creates
// the Binary Section of the SPIR-V specification.
// Enumeration tokens for SPIR-V, in various styles:
// C, C++, C++11, JSON, Lua, Python, C#
//
// - C will have tokens with a "Spv" prefix, e.g.: SpvSourceLanguageGLSL
// - C++ will have tokens in the "spv" name space, e.g.: spv::SourceLanguageGLSL
// - C++11 will use enum classes in the spv namespace, e.g.: spv::SourceLanguage::GLSL
// - Lua will use tables, e.g.: spv.SourceLanguage.GLSL
// - Python will use dictionaries, e.g.: spv['SourceLanguage']['GLSL']
// - C# will use enum classes in the Specification class located in the "Spv" namespace, e.g.: Spv.Specification.SourceLanguage.GLSL
//
// Some tokens act like mask values, which can be OR'd together,
// while others are mutually exclusive. The mask-like ones have
// "Mask" in their name, and a parallel enum that has the shift
// amount (1 << x) for each corresponding enumerant.
namespace Spv
{
public static class Specification
{
public const uint MagicNumber = 0x07230203;
public const uint Version = 0x00010200;
public const uint Revision = 2;
public const uint OpCodeMask = 0xffff;
public const uint WordCountShift = 16;
public enum SourceLanguage
{
Unknown = 0,
ESSL = 1,
GLSL = 2,
OpenCL_C = 3,
OpenCL_CPP = 4,
HLSL = 5,
}
public enum ExecutionModel
{
Vertex = 0,
TessellationControl = 1,
TessellationEvaluation = 2,
Geometry = 3,
Fragment = 4,
GLCompute = 5,
Kernel = 6,
}
public enum AddressingModel
{
Logical = 0,
Physical32 = 1,
Physical64 = 2,
}
public enum MemoryModel
{
Simple = 0,
GLSL450 = 1,
OpenCL = 2,
}
public enum ExecutionMode
{
Invocations = 0,
SpacingEqual = 1,
SpacingFractionalEven = 2,
SpacingFractionalOdd = 3,
VertexOrderCw = 4,
VertexOrderCcw = 5,
PixelCenterInteger = 6,
OriginUpperLeft = 7,
OriginLowerLeft = 8,
EarlyFragmentTests = 9,
PointMode = 10,
Xfb = 11,
DepthReplacing = 12,
DepthGreater = 14,
DepthLess = 15,
DepthUnchanged = 16,
LocalSize = 17,
LocalSizeHint = 18,
InputPoints = 19,
InputLines = 20,
InputLinesAdjacency = 21,
Triangles = 22,
InputTrianglesAdjacency = 23,
Quads = 24,
Isolines = 25,
OutputVertices = 26,
OutputPoints = 27,
OutputLineStrip = 28,
OutputTriangleStrip = 29,
VecTypeHint = 30,
ContractionOff = 31,
Initializer = 33,
Finalizer = 34,
SubgroupSize = 35,
SubgroupsPerWorkgroup = 36,
SubgroupsPerWorkgroupId = 37,
LocalSizeId = 38,
LocalSizeHintId = 39,
PostDepthCoverage = 4446,
StencilRefReplacingEXT = 5027,
}
public enum StorageClass
{
UniformConstant = 0,
Input = 1,
Uniform = 2,
Output = 3,
Workgroup = 4,
CrossWorkgroup = 5,
Private = 6,
Function = 7,
Generic = 8,
PushConstant = 9,
AtomicCounter = 10,
Image = 11,
StorageBuffer = 12,
}
public enum Dim
{
Dim1D = 0,
Dim2D = 1,
Dim3D = 2,
Cube = 3,
Rect = 4,
Buffer = 5,
SubpassData = 6,
}
public enum SamplerAddressingMode
{
None = 0,
ClampToEdge = 1,
Clamp = 2,
Repeat = 3,
RepeatMirrored = 4,
}
public enum SamplerFilterMode
{
Nearest = 0,
Linear = 1,
}
public enum ImageFormat
{
Unknown = 0,
Rgba32f = 1,
Rgba16f = 2,
R32f = 3,
Rgba8 = 4,
Rgba8Snorm = 5,
Rg32f = 6,
Rg16f = 7,
R11fG11fB10f = 8,
R16f = 9,
Rgba16 = 10,
Rgb10A2 = 11,
Rg16 = 12,
Rg8 = 13,
R16 = 14,
R8 = 15,
Rgba16Snorm = 16,
Rg16Snorm = 17,
Rg8Snorm = 18,
R16Snorm = 19,
R8Snorm = 20,
Rgba32i = 21,
Rgba16i = 22,
Rgba8i = 23,
R32i = 24,
Rg32i = 25,
Rg16i = 26,
Rg8i = 27,
R16i = 28,
R8i = 29,
Rgba32ui = 30,
Rgba16ui = 31,
Rgba8ui = 32,
R32ui = 33,
Rgb10a2ui = 34,
Rg32ui = 35,
Rg16ui = 36,
Rg8ui = 37,
R16ui = 38,
R8ui = 39,
}
public enum ImageChannelOrder
{
R = 0,
A = 1,
RG = 2,
RA = 3,
RGB = 4,
RGBA = 5,
BGRA = 6,
ARGB = 7,
Intensity = 8,
Luminance = 9,
Rx = 10,
RGx = 11,
RGBx = 12,
Depth = 13,
DepthStencil = 14,
sRGB = 15,
sRGBx = 16,
sRGBA = 17,
sBGRA = 18,
ABGR = 19,
}
public enum ImageChannelDataType
{
SnormInt8 = 0,
SnormInt16 = 1,
UnormInt8 = 2,
UnormInt16 = 3,
UnormShort565 = 4,
UnormShort555 = 5,
UnormInt101010 = 6,
SignedInt8 = 7,
SignedInt16 = 8,
SignedInt32 = 9,
UnsignedInt8 = 10,
UnsignedInt16 = 11,
UnsignedInt32 = 12,
HalfFloat = 13,
Float = 14,
UnormInt24 = 15,
UnormInt101010_2 = 16,
}
public enum ImageOperandsShift
{
Bias = 0,
Lod = 1,
Grad = 2,
ConstOffset = 3,
Offset = 4,
ConstOffsets = 5,
Sample = 6,
MinLod = 7,
}
public enum ImageOperandsMask
{
MaskNone = 0,
Bias = 0x00000001,
Lod = 0x00000002,
Grad = 0x00000004,
ConstOffset = 0x00000008,
Offset = 0x00000010,
ConstOffsets = 0x00000020,
Sample = 0x00000040,
MinLod = 0x00000080,
}
public enum FPFastMathModeShift
{
NotNaN = 0,
NotInf = 1,
NSZ = 2,
AllowRecip = 3,
Fast = 4,
}
public enum FPFastMathModeMask
{
MaskNone = 0,
NotNaN = 0x00000001,
NotInf = 0x00000002,
NSZ = 0x00000004,
AllowRecip = 0x00000008,
Fast = 0x00000010,
}
public enum FPRoundingMode
{
RTE = 0,
RTZ = 1,
RTP = 2,
RTN = 3,
}
public enum LinkageType
{
Export = 0,
Import = 1,
}
public enum AccessQualifier
{
ReadOnly = 0,
WriteOnly = 1,
ReadWrite = 2,
}
public enum FunctionParameterAttribute
{
Zext = 0,
Sext = 1,
ByVal = 2,
Sret = 3,
NoAlias = 4,
NoCapture = 5,
NoWrite = 6,
NoReadWrite = 7,
}
public enum Decoration
{
RelaxedPrecision = 0,
SpecId = 1,
Block = 2,
BufferBlock = 3,
RowMajor = 4,
ColMajor = 5,
ArrayStride = 6,
MatrixStride = 7,
GLSLShared = 8,
GLSLPacked = 9,
CPacked = 10,
BuiltIn = 11,
NoPerspective = 13,
Flat = 14,
Patch = 15,
Centroid = 16,
Sample = 17,
Invariant = 18,
Restrict = 19,
Aliased = 20,
Volatile = 21,
Constant = 22,
Coherent = 23,
NonWritable = 24,
NonReadable = 25,
Uniform = 26,
SaturatedConversion = 28,
Stream = 29,
Location = 30,
Component = 31,
Index = 32,
Binding = 33,
DescriptorSet = 34,
Offset = 35,
XfbBuffer = 36,
XfbStride = 37,
FuncParamAttr = 38,
FPRoundingMode = 39,
FPFastMathMode = 40,
LinkageAttributes = 41,
NoContraction = 42,
InputAttachmentIndex = 43,
Alignment = 44,
MaxByteOffset = 45,
AlignmentId = 46,
MaxByteOffsetId = 47,
ExplicitInterpAMD = 4999,
OverrideCoverageNV = 5248,
PassthroughNV = 5250,
ViewportRelativeNV = 5252,
SecondaryViewportRelativeNV = 5256,
HlslCounterBufferGOOGLE = 5634,
HlslSemanticGOOGLE = 5635,
}
public enum BuiltIn
{
Position = 0,
PointSize = 1,
ClipDistance = 3,
CullDistance = 4,
VertexId = 5,
InstanceId = 6,
PrimitiveId = 7,
InvocationId = 8,
Layer = 9,
ViewportIndex = 10,
TessLevelOuter = 11,
TessLevelInner = 12,
TessCoord = 13,
PatchVertices = 14,
FragCoord = 15,
PointCoord = 16,
FrontFacing = 17,
SampleId = 18,
SamplePosition = 19,
SampleMask = 20,
FragDepth = 22,
HelperInvocation = 23,
NumWorkgroups = 24,
WorkgroupSize = 25,
WorkgroupId = 26,
LocalInvocationId = 27,
GlobalInvocationId = 28,
LocalInvocationIndex = 29,
WorkDim = 30,
GlobalSize = 31,
EnqueuedWorkgroupSize = 32,
GlobalOffset = 33,
GlobalLinearId = 34,
SubgroupSize = 36,
SubgroupMaxSize = 37,
NumSubgroups = 38,
NumEnqueuedSubgroups = 39,
SubgroupId = 40,
SubgroupLocalInvocationId = 41,
VertexIndex = 42,
InstanceIndex = 43,
SubgroupEqMaskKHR = 4416,
SubgroupGeMaskKHR = 4417,
SubgroupGtMaskKHR = 4418,
SubgroupLeMaskKHR = 4419,
SubgroupLtMaskKHR = 4420,
BaseVertex = 4424,
BaseInstance = 4425,
DrawIndex = 4426,
DeviceIndex = 4438,
ViewIndex = 4440,
BaryCoordNoPerspAMD = 4992,
BaryCoordNoPerspCentroidAMD = 4993,
BaryCoordNoPerspSampleAMD = 4994,
BaryCoordSmoothAMD = 4995,
BaryCoordSmoothCentroidAMD = 4996,
BaryCoordSmoothSampleAMD = 4997,
BaryCoordPullModelAMD = 4998,
FragStencilRefEXT = 5014,
ViewportMaskNV = 5253,
SecondaryPositionNV = 5257,
SecondaryViewportMaskNV = 5258,
PositionPerViewNV = 5261,
ViewportMaskPerViewNV = 5262,
}
public enum SelectionControlShift
{
Flatten = 0,
DontFlatten = 1,
}
public enum SelectionControlMask
{
MaskNone = 0,
Flatten = 0x00000001,
DontFlatten = 0x00000002,
}
public enum LoopControlShift
{
Unroll = 0,
DontUnroll = 1,
DependencyInfinite = 2,
DependencyLength = 3,
}
public enum LoopControlMask
{
MaskNone = 0,
Unroll = 0x00000001,
DontUnroll = 0x00000002,
DependencyInfinite = 0x00000004,
DependencyLength = 0x00000008,
}
public enum FunctionControlShift
{
Inline = 0,
DontInline = 1,
Pure = 2,
Const = 3,
}
public enum FunctionControlMask
{
MaskNone = 0,
Inline = 0x00000001,
DontInline = 0x00000002,
Pure = 0x00000004,
Const = 0x00000008,
}
public enum MemorySemanticsShift
{
Acquire = 1,
Release = 2,
AcquireRelease = 3,
SequentiallyConsistent = 4,
UniformMemory = 6,
SubgroupMemory = 7,
WorkgroupMemory = 8,
CrossWorkgroupMemory = 9,
AtomicCounterMemory = 10,
ImageMemory = 11,
}
public enum MemorySemanticsMask
{
MaskNone = 0,
Acquire = 0x00000002,
Release = 0x00000004,
AcquireRelease = 0x00000008,
SequentiallyConsistent = 0x00000010,
UniformMemory = 0x00000040,
SubgroupMemory = 0x00000080,
WorkgroupMemory = 0x00000100,
CrossWorkgroupMemory = 0x00000200,
AtomicCounterMemory = 0x00000400,
ImageMemory = 0x00000800,
}
public enum MemoryAccessShift
{
Volatile = 0,
Aligned = 1,
Nontemporal = 2,
}
public enum MemoryAccessMask
{
MaskNone = 0,
Volatile = 0x00000001,
Aligned = 0x00000002,
Nontemporal = 0x00000004,
}
public enum Scope
{
CrossDevice = 0,
Device = 1,
Workgroup = 2,
Subgroup = 3,
Invocation = 4,
}
public enum GroupOperation
{
Reduce = 0,
InclusiveScan = 1,
ExclusiveScan = 2,
}
public enum KernelEnqueueFlags
{
NoWait = 0,
WaitKernel = 1,
WaitWorkGroup = 2,
}
public enum KernelProfilingInfoShift
{
CmdExecTime = 0,
}
public enum KernelProfilingInfoMask
{
MaskNone = 0,
CmdExecTime = 0x00000001,
}
public enum Capability
{
Matrix = 0,
Shader = 1,
Geometry = 2,
Tessellation = 3,
Addresses = 4,
Linkage = 5,
Kernel = 6,
Vector16 = 7,
Float16Buffer = 8,
Float16 = 9,
Float64 = 10,
Int64 = 11,
Int64Atomics = 12,
ImageBasic = 13,
ImageReadWrite = 14,
ImageMipmap = 15,
Pipes = 17,
Groups = 18,
DeviceEnqueue = 19,
LiteralSampler = 20,
AtomicStorage = 21,
Int16 = 22,
TessellationPointSize = 23,
GeometryPointSize = 24,
ImageGatherExtended = 25,
StorageImageMultisample = 27,
UniformBufferArrayDynamicIndexing = 28,
SampledImageArrayDynamicIndexing = 29,
StorageBufferArrayDynamicIndexing = 30,
StorageImageArrayDynamicIndexing = 31,
ClipDistance = 32,
CullDistance = 33,
ImageCubeArray = 34,
SampleRateShading = 35,
ImageRect = 36,
SampledRect = 37,
GenericPointer = 38,
Int8 = 39,
InputAttachment = 40,
SparseResidency = 41,
MinLod = 42,
Sampled1D = 43,
Image1D = 44,
SampledCubeArray = 45,
SampledBuffer = 46,
ImageBuffer = 47,
ImageMSArray = 48,
StorageImageExtendedFormats = 49,
ImageQuery = 50,
DerivativeControl = 51,
InterpolationFunction = 52,
TransformFeedback = 53,
GeometryStreams = 54,
StorageImageReadWithoutFormat = 55,
StorageImageWriteWithoutFormat = 56,
MultiViewport = 57,
SubgroupDispatch = 58,
NamedBarrier = 59,
PipeStorage = 60,
SubgroupBallotKHR = 4423,
DrawParameters = 4427,
SubgroupVoteKHR = 4431,
StorageBuffer16BitAccess = 4433,
StorageUniformBufferBlock16 = 4433,
StorageUniform16 = 4434,
UniformAndStorageBuffer16BitAccess = 4434,
StoragePushConstant16 = 4435,
StorageInputOutput16 = 4436,
DeviceGroup = 4437,
MultiView = 4439,
VariablePointersStorageBuffer = 4441,
VariablePointers = 4442,
AtomicStorageOps = 4445,
SampleMaskPostDepthCoverage = 4447,
ImageGatherBiasLodAMD = 5009,
FragmentMaskAMD = 5010,
StencilExportEXT = 5013,
ImageReadWriteLodAMD = 5015,
SampleMaskOverrideCoverageNV = 5249,
GeometryShaderPassthroughNV = 5251,
ShaderViewportIndexLayerEXT = 5254,
ShaderViewportIndexLayerNV = 5254,
ShaderViewportMaskNV = 5255,
ShaderStereoViewNV = 5259,
PerViewAttributesNV = 5260,
SubgroupShuffleINTEL = 5568,
SubgroupBufferBlockIOINTEL = 5569,
SubgroupImageBlockIOINTEL = 5570,
}
public enum Op
{
OpNop = 0,
OpUndef = 1,
OpSourceContinued = 2,
OpSource = 3,
OpSourceExtension = 4,
OpName = 5,
OpMemberName = 6,
OpString = 7,
OpLine = 8,
OpExtension = 10,
OpExtInstImport = 11,
OpExtInst = 12,
OpMemoryModel = 14,
OpEntryPoint = 15,
OpExecutionMode = 16,
OpCapability = 17,
OpTypeVoid = 19,
OpTypeBool = 20,
OpTypeInt = 21,
OpTypeFloat = 22,
OpTypeVector = 23,
OpTypeMatrix = 24,
OpTypeImage = 25,
OpTypeSampler = 26,
OpTypeSampledImage = 27,
OpTypeArray = 28,
OpTypeRuntimeArray = 29,
OpTypeStruct = 30,
OpTypeOpaque = 31,
OpTypePointer = 32,
OpTypeFunction = 33,
OpTypeEvent = 34,
OpTypeDeviceEvent = 35,
OpTypeReserveId = 36,
OpTypeQueue = 37,
OpTypePipe = 38,
OpTypeForwardPointer = 39,
OpConstantTrue = 41,
OpConstantFalse = 42,
OpConstant = 43,
OpConstantComposite = 44,
OpConstantSampler = 45,
OpConstantNull = 46,
OpSpecConstantTrue = 48,
OpSpecConstantFalse = 49,
OpSpecConstant = 50,
OpSpecConstantComposite = 51,
OpSpecConstantOp = 52,
OpFunction = 54,
OpFunctionParameter = 55,
OpFunctionEnd = 56,
OpFunctionCall = 57,
OpVariable = 59,
OpImageTexelPointer = 60,
OpLoad = 61,
OpStore = 62,
OpCopyMemory = 63,
OpCopyMemorySized = 64,
OpAccessChain = 65,
OpInBoundsAccessChain = 66,
OpPtrAccessChain = 67,
OpArrayLength = 68,
OpGenericPtrMemSemantics = 69,
OpInBoundsPtrAccessChain = 70,
OpDecorate = 71,
OpMemberDecorate = 72,
OpDecorationGroup = 73,
OpGroupDecorate = 74,
OpGroupMemberDecorate = 75,
OpVectorExtractDynamic = 77,
OpVectorInsertDynamic = 78,
OpVectorShuffle = 79,
OpCompositeConstruct = 80,
OpCompositeExtract = 81,
OpCompositeInsert = 82,
OpCopyObject = 83,
OpTranspose = 84,
OpSampledImage = 86,
OpImageSampleImplicitLod = 87,
OpImageSampleExplicitLod = 88,
OpImageSampleDrefImplicitLod = 89,
OpImageSampleDrefExplicitLod = 90,
OpImageSampleProjImplicitLod = 91,
OpImageSampleProjExplicitLod = 92,
OpImageSampleProjDrefImplicitLod = 93,
OpImageSampleProjDrefExplicitLod = 94,
OpImageFetch = 95,
OpImageGather = 96,
OpImageDrefGather = 97,
OpImageRead = 98,
OpImageWrite = 99,
OpImage = 100,
OpImageQueryFormat = 101,
OpImageQueryOrder = 102,
OpImageQuerySizeLod = 103,
OpImageQuerySize = 104,
OpImageQueryLod = 105,
OpImageQueryLevels = 106,
OpImageQuerySamples = 107,
OpConvertFToU = 109,
OpConvertFToS = 110,
OpConvertSToF = 111,
OpConvertUToF = 112,
OpUConvert = 113,
OpSConvert = 114,
OpFConvert = 115,
OpQuantizeToF16 = 116,
OpConvertPtrToU = 117,
OpSatConvertSToU = 118,
OpSatConvertUToS = 119,
OpConvertUToPtr = 120,
OpPtrCastToGeneric = 121,
OpGenericCastToPtr = 122,
OpGenericCastToPtrExplicit = 123,
OpBitcast = 124,
OpSNegate = 126,
OpFNegate = 127,
OpIAdd = 128,
OpFAdd = 129,
OpISub = 130,
OpFSub = 131,
OpIMul = 132,
OpFMul = 133,
OpUDiv = 134,
OpSDiv = 135,
OpFDiv = 136,
OpUMod = 137,
OpSRem = 138,
OpSMod = 139,
OpFRem = 140,
OpFMod = 141,
OpVectorTimesScalar = 142,
OpMatrixTimesScalar = 143,
OpVectorTimesMatrix = 144,
OpMatrixTimesVector = 145,
OpMatrixTimesMatrix = 146,
OpOuterProduct = 147,
OpDot = 148,
OpIAddCarry = 149,
OpISubBorrow = 150,
OpUMulExtended = 151,
OpSMulExtended = 152,
OpAny = 154,
OpAll = 155,
OpIsNan = 156,
OpIsInf = 157,
OpIsFinite = 158,
OpIsNormal = 159,
OpSignBitSet = 160,
OpLessOrGreater = 161,
OpOrdered = 162,
OpUnordered = 163,
OpLogicalEqual = 164,
OpLogicalNotEqual = 165,
OpLogicalOr = 166,
OpLogicalAnd = 167,
OpLogicalNot = 168,
OpSelect = 169,
OpIEqual = 170,
OpINotEqual = 171,
OpUGreaterThan = 172,
OpSGreaterThan = 173,
OpUGreaterThanEqual = 174,
OpSGreaterThanEqual = 175,
OpULessThan = 176,
OpSLessThan = 177,
OpULessThanEqual = 178,
OpSLessThanEqual = 179,
OpFOrdEqual = 180,
OpFUnordEqual = 181,
OpFOrdNotEqual = 182,
OpFUnordNotEqual = 183,
OpFOrdLessThan = 184,
OpFUnordLessThan = 185,
OpFOrdGreaterThan = 186,
OpFUnordGreaterThan = 187,
OpFOrdLessThanEqual = 188,
OpFUnordLessThanEqual = 189,
OpFOrdGreaterThanEqual = 190,
OpFUnordGreaterThanEqual = 191,
OpShiftRightLogical = 194,
OpShiftRightArithmetic = 195,
OpShiftLeftLogical = 196,
OpBitwiseOr = 197,
OpBitwiseXor = 198,
OpBitwiseAnd = 199,
OpNot = 200,
OpBitFieldInsert = 201,
OpBitFieldSExtract = 202,
OpBitFieldUExtract = 203,
OpBitReverse = 204,
OpBitCount = 205,
OpDPdx = 207,
OpDPdy = 208,
OpFwidth = 209,
OpDPdxFine = 210,
OpDPdyFine = 211,
OpFwidthFine = 212,
OpDPdxCoarse = 213,
OpDPdyCoarse = 214,
OpFwidthCoarse = 215,
OpEmitVertex = 218,
OpEndPrimitive = 219,
OpEmitStreamVertex = 220,
OpEndStreamPrimitive = 221,
OpControlBarrier = 224,
OpMemoryBarrier = 225,
OpAtomicLoad = 227,
OpAtomicStore = 228,
OpAtomicExchange = 229,
OpAtomicCompareExchange = 230,
OpAtomicCompareExchangeWeak = 231,
OpAtomicIIncrement = 232,
OpAtomicIDecrement = 233,
OpAtomicIAdd = 234,
OpAtomicISub = 235,
OpAtomicSMin = 236,
OpAtomicUMin = 237,
OpAtomicSMax = 238,
OpAtomicUMax = 239,
OpAtomicAnd = 240,
OpAtomicOr = 241,
OpAtomicXor = 242,
OpPhi = 245,
OpLoopMerge = 246,
OpSelectionMerge = 247,
OpLabel = 248,
OpBranch = 249,
OpBranchConditional = 250,
OpSwitch = 251,
OpKill = 252,
OpReturn = 253,
OpReturnValue = 254,
OpUnreachable = 255,
OpLifetimeStart = 256,
OpLifetimeStop = 257,
OpGroupAsyncCopy = 259,
OpGroupWaitEvents = 260,
OpGroupAll = 261,
OpGroupAny = 262,
OpGroupBroadcast = 263,
OpGroupIAdd = 264,
OpGroupFAdd = 265,
OpGroupFMin = 266,
OpGroupUMin = 267,
OpGroupSMin = 268,
OpGroupFMax = 269,
OpGroupUMax = 270,
OpGroupSMax = 271,
OpReadPipe = 274,
OpWritePipe = 275,
OpReservedReadPipe = 276,
OpReservedWritePipe = 277,
OpReserveReadPipePackets = 278,
OpReserveWritePipePackets = 279,
OpCommitReadPipe = 280,
OpCommitWritePipe = 281,
OpIsValidReserveId = 282,
OpGetNumPipePackets = 283,
OpGetMaxPipePackets = 284,
OpGroupReserveReadPipePackets = 285,
OpGroupReserveWritePipePackets = 286,
OpGroupCommitReadPipe = 287,
OpGroupCommitWritePipe = 288,
OpEnqueueMarker = 291,
OpEnqueueKernel = 292,
OpGetKernelNDrangeSubGroupCount = 293,
OpGetKernelNDrangeMaxSubGroupSize = 294,
OpGetKernelWorkGroupSize = 295,
OpGetKernelPreferredWorkGroupSizeMultiple = 296,
OpRetainEvent = 297,
OpReleaseEvent = 298,
OpCreateUserEvent = 299,
OpIsValidEvent = 300,
OpSetUserEventStatus = 301,
OpCaptureEventProfilingInfo = 302,
OpGetDefaultQueue = 303,
OpBuildNDRange = 304,
OpImageSparseSampleImplicitLod = 305,
OpImageSparseSampleExplicitLod = 306,
OpImageSparseSampleDrefImplicitLod = 307,
OpImageSparseSampleDrefExplicitLod = 308,
OpImageSparseSampleProjImplicitLod = 309,
OpImageSparseSampleProjExplicitLod = 310,
OpImageSparseSampleProjDrefImplicitLod = 311,
OpImageSparseSampleProjDrefExplicitLod = 312,
OpImageSparseFetch = 313,
OpImageSparseGather = 314,
OpImageSparseDrefGather = 315,
OpImageSparseTexelsResident = 316,
OpNoLine = 317,
OpAtomicFlagTestAndSet = 318,
OpAtomicFlagClear = 319,
OpImageSparseRead = 320,
OpSizeOf = 321,
OpTypePipeStorage = 322,
OpConstantPipeStorage = 323,
OpCreatePipeFromPipeStorage = 324,
OpGetKernelLocalSizeForSubgroupCount = 325,
OpGetKernelMaxNumSubgroups = 326,
OpTypeNamedBarrier = 327,
OpNamedBarrierInitialize = 328,
OpMemoryNamedBarrier = 329,
OpModuleProcessed = 330,
OpExecutionModeId = 331,
OpDecorateId = 332,
OpSubgroupBallotKHR = 4421,
OpSubgroupFirstInvocationKHR = 4422,
OpSubgroupAllKHR = 4428,
OpSubgroupAnyKHR = 4429,
OpSubgroupAllEqualKHR = 4430,
OpSubgroupReadInvocationKHR = 4432,
OpGroupIAddNonUniformAMD = 5000,
OpGroupFAddNonUniformAMD = 5001,
OpGroupFMinNonUniformAMD = 5002,
OpGroupUMinNonUniformAMD = 5003,
OpGroupSMinNonUniformAMD = 5004,
OpGroupFMaxNonUniformAMD = 5005,
OpGroupUMaxNonUniformAMD = 5006,
OpGroupSMaxNonUniformAMD = 5007,
OpFragmentMaskFetchAMD = 5011,
OpFragmentFetchAMD = 5012,
OpSubgroupShuffleINTEL = 5571,
OpSubgroupShuffleDownINTEL = 5572,
OpSubgroupShuffleUpINTEL = 5573,
OpSubgroupShuffleXorINTEL = 5574,
OpSubgroupBlockReadINTEL = 5575,
OpSubgroupBlockWriteINTEL = 5576,
OpSubgroupImageBlockReadINTEL = 5577,
OpSubgroupImageBlockWriteINTEL = 5578,
OpDecorateStringGOOGLE = 5632,
OpMemberDecorateStringGOOGLE = 5633,
}
}
}
| 30.73092 | 132 | 0.499315 | [
"Apache-2.0"
] | 10088/filament | third_party/spirv-tools/external/spirv-headers/include/spirv/1.2/spirv.cs | 31,407 | 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 sns-2010-03-31.normal.json service model.
*/
using System;
using Amazon.Runtime;
using Amazon.Util.Internal;
namespace Amazon.SimpleNotificationService
{
/// <summary>
/// Configuration for accessing Amazon SimpleNotificationService service
/// </summary>
public partial class AmazonSimpleNotificationServiceConfig : ClientConfig
{
private static readonly string UserAgentString =
InternalSDKUtils.BuildUserAgentString("3.5.0.8");
private string _userAgent = UserAgentString;
/// <summary>
/// Default constructor
/// </summary>
public AmazonSimpleNotificationServiceConfig()
{
this.AuthenticationServiceName = "sns";
}
/// <summary>
/// The constant used to lookup in the region hash the endpoint.
/// </summary>
public override string RegionEndpointServiceName
{
get
{
return "sns";
}
}
/// <summary>
/// Gets the ServiceVersion property.
/// </summary>
public override string ServiceVersion
{
get
{
return "2010-03-31";
}
}
/// <summary>
/// Gets the value of UserAgent property.
/// </summary>
public override string UserAgent
{
get
{
return _userAgent;
}
}
}
} | 26.625 | 101 | 0.595775 | [
"Apache-2.0"
] | orinem/aws-sdk-net | sdk/src/Services/SimpleNotificationService/Generated/AmazonSimpleNotificationServiceConfig.cs | 2,130 | 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("07. Reverse number")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("07. Reverse number")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("ca39d0d0-747c-44bc-90f8-0fa0a1aa428f")]
// 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.081081 | 84 | 0.74308 | [
"MIT"
] | VelislavLeonov/Telerik-Akademy | HomeworkMethods/07. Reverse number/Properties/AssemblyInfo.cs | 1,412 | C# |
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace LeetCode.Test
{
[TestClass]
public class _0452_MinimumNumberOfArrowsToBurstBalloons_Test
{
[TestMethod]
public void FindMinArrowShots_1()
{
var solution = new _0452_MinimumNumberOfArrowsToBurstBalloons();
var result = solution.FindMinArrowShots(new int[][] {
new int[] { 10, 16 },
new int[] { 2, 8 },
new int[] { 1, 6 },
new int[] { 7, 12 },
});
Assert.AreEqual(2, result);
}
[TestMethod]
public void FindMinArrowShots_2()
{
var solution = new _0452_MinimumNumberOfArrowsToBurstBalloons();
var result = solution.FindMinArrowShots(new int[][] {
new int[] { 1, 2 },
new int[] { 3, 4 },
new int[] { 5, 6 },
new int[] { 7, 8 },
});
Assert.AreEqual(4, result);
}
[TestMethod]
public void FindMinArrowShots_3()
{
var solution = new _0452_MinimumNumberOfArrowsToBurstBalloons();
var result = solution.FindMinArrowShots(new int[][] {
new int[] { 1, 2 },
new int[] { 2, 3 },
new int[] { 3, 4 },
new int[] { 4, 5 },
});
Assert.AreEqual(2, result);
}
[TestMethod]
public void FindMinArrowShots_4()
{
var solution = new _0452_MinimumNumberOfArrowsToBurstBalloons();
var result = solution.FindMinArrowShots(new int[][] {
new int[] { 1, 2 },
});
Assert.AreEqual(1, result);
}
[TestMethod]
public void FindMinArrowShots_5()
{
var solution = new _0452_MinimumNumberOfArrowsToBurstBalloons();
var result = solution.FindMinArrowShots(new int[][] {
new int[] { 2, 3 },
new int[] { 2, 3 },
});
Assert.AreEqual(1, result);
}
}
}
| 30.884058 | 76 | 0.486626 | [
"MIT"
] | BigEggStudy/LeetCode-CS | LeetCode.Test/0451-0500/0452-MinimumNumberOfArrowsToBurstBalloons-Test.cs | 2,131 | C# |
namespace NServiceKit.Common.Tests.Models
{
/// <summary>A model with long identifier and string fields.</summary>
public class ModelWithLongIdAndStringFields
{
/// <summary>Gets or sets the identifier.</summary>
/// <value>The identifier.</value>
public long Id { get; set; }
/// <summary>Gets or sets the name.</summary>
/// <value>The name.</value>
public string Name { get; set; }
/// <summary>Gets or sets the identifier of the album.</summary>
/// <value>The identifier of the album.</value>
public string AlbumId { get; set; }
/// <summary>Gets or sets the name of the album.</summary>
/// <value>The name of the album.</value>
public string AlbumName { get; set; }
}
} | 34.454545 | 74 | 0.631926 | [
"BSD-3-Clause"
] | azraelrabbit/NServiceKit.OrmLite | tests/NServiceKit.OrmLite.Tests/Shared/ModelWithLongIdAndStringFields.cs | 758 | C# |
using System.Collections.Generic;
using System.Threading.Tasks;
using Abp.Application.Features;
using Abp.Application.Navigation;
using Abp.Authorization;
using Abp.Configuration;
using Abp.Configuration.Startup;
using Abp.Localization;
using Abp.Runtime.Session;
using Abp.Timing;
using Abp.Timing.Timezone;
using Abp.Web.Models.AbpUserConfiguration;
using Abp.Web.Security.AntiForgery;
using System.Linq;
using Abp.Dependency;
using Abp.Extensions;
using System.Globalization;
namespace Abp.Web.Configuration
{
public class AbpUserConfigurationBuilder : ITransientDependency
{
private readonly IAbpStartupConfiguration _startupConfiguration;
protected IMultiTenancyConfig MultiTenancyConfig { get; }
protected ILanguageManager LanguageManager { get; }
protected ILocalizationManager LocalizationManager { get; }
protected IFeatureManager FeatureManager { get; }
protected IFeatureChecker FeatureChecker { get; }
protected IPermissionManager PermissionManager { get; }
protected IUserNavigationManager UserNavigationManager { get; }
protected ISettingDefinitionManager SettingDefinitionManager { get; }
protected ISettingManager SettingManager { get; }
protected IAbpAntiForgeryConfiguration AbpAntiForgeryConfiguration { get; }
protected IAbpSession AbpSession { get; }
protected IPermissionChecker PermissionChecker { get; }
protected Dictionary<string, object> CustomDataConfig { get; }
private readonly IIocResolver _iocResolver;
public AbpUserConfigurationBuilder(
IMultiTenancyConfig multiTenancyConfig,
ILanguageManager languageManager,
ILocalizationManager localizationManager,
IFeatureManager featureManager,
IFeatureChecker featureChecker,
IPermissionManager permissionManager,
IUserNavigationManager userNavigationManager,
ISettingDefinitionManager settingDefinitionManager,
ISettingManager settingManager,
IAbpAntiForgeryConfiguration abpAntiForgeryConfiguration,
IAbpSession abpSession,
IPermissionChecker permissionChecker,
IIocResolver iocResolver,
IAbpStartupConfiguration startupConfiguration)
{
MultiTenancyConfig = multiTenancyConfig;
LanguageManager = languageManager;
LocalizationManager = localizationManager;
FeatureManager = featureManager;
FeatureChecker = featureChecker;
PermissionManager = permissionManager;
UserNavigationManager = userNavigationManager;
SettingDefinitionManager = settingDefinitionManager;
SettingManager = settingManager;
AbpAntiForgeryConfiguration = abpAntiForgeryConfiguration;
AbpSession = abpSession;
PermissionChecker = permissionChecker;
_iocResolver = iocResolver;
_startupConfiguration = startupConfiguration;
CustomDataConfig = new Dictionary<string, object>();
}
public virtual async Task<AbpUserConfigurationDto> GetAll()
{
return new AbpUserConfigurationDto
{
MultiTenancy = GetUserMultiTenancyConfig(),
Session = GetUserSessionConfig(),
Localization = GetUserLocalizationConfig(),
Features = await GetUserFeaturesConfig(),
Auth = await GetUserAuthConfig(),
Nav = await GetUserNavConfig(),
Setting = await GetUserSettingConfig(),
Clock = GetUserClockConfig(),
Timing = await GetUserTimingConfig(),
Security = GetUserSecurityConfig(),
Custom = _startupConfiguration.GetCustomConfig()
};
}
protected virtual AbpMultiTenancyConfigDto GetUserMultiTenancyConfig()
{
return new AbpMultiTenancyConfigDto
{
IsEnabled = MultiTenancyConfig.IsEnabled,
IgnoreFeatureCheckForHostUsers = MultiTenancyConfig.IgnoreFeatureCheckForHostUsers
};
}
protected virtual AbpUserSessionConfigDto GetUserSessionConfig()
{
return new AbpUserSessionConfigDto
{
UserId = AbpSession.UserId,
TenantId = AbpSession.TenantId,
ImpersonatorUserId = AbpSession.ImpersonatorUserId,
ImpersonatorTenantId = AbpSession.ImpersonatorTenantId,
MultiTenancySide = AbpSession.MultiTenancySide
};
}
protected virtual AbpUserLocalizationConfigDto GetUserLocalizationConfig()
{
var currentCulture = CultureInfo.CurrentUICulture;
var languages = LanguageManager.GetActiveLanguages();
var config = new AbpUserLocalizationConfigDto
{
CurrentCulture = new AbpUserCurrentCultureConfigDto
{
Name = currentCulture.Name,
DisplayName = currentCulture.DisplayName
},
Languages = languages.ToList()
};
if (languages.Count > 0)
{
config.CurrentLanguage = LanguageManager.CurrentLanguage;
}
var sources = LocalizationManager.GetAllSources().OrderBy(s => s.Name).ToArray();
config.Sources = sources.Select(s => new AbpLocalizationSourceDto
{
Name = s.Name,
Type = s.GetType().Name
}).ToList();
config.Values = new Dictionary<string, Dictionary<string, string>>();
foreach (var source in sources)
{
var stringValues = source.GetAllStrings(currentCulture).OrderBy(s => s.Name).ToList();
var stringDictionary = stringValues
.ToDictionary(_ => _.Name, _ => _.Value);
config.Values.Add(source.Name, stringDictionary);
}
return config;
}
protected virtual async Task<AbpUserFeatureConfigDto> GetUserFeaturesConfig()
{
var config = new AbpUserFeatureConfigDto()
{
AllFeatures = new Dictionary<string, AbpStringValueDto>()
};
var allFeatures = FeatureManager.GetAll().ToList();
if (AbpSession.TenantId.HasValue)
{
var currentTenantId = AbpSession.GetTenantId();
foreach (var feature in allFeatures)
{
var value = await FeatureChecker.GetValueAsync(currentTenantId, feature.Name);
config.AllFeatures.Add(feature.Name, new AbpStringValueDto
{
Value = value
});
}
}
else
{
foreach (var feature in allFeatures)
{
config.AllFeatures.Add(feature.Name, new AbpStringValueDto
{
Value = feature.DefaultValue
});
}
}
return config;
}
protected virtual async Task<AbpUserAuthConfigDto> GetUserAuthConfig()
{
var config = new AbpUserAuthConfigDto();
var allPermissionNames = PermissionManager.GetAllPermissions(false).Select(p => p.Name).ToList();
var grantedPermissionNames = new List<string>();
if (AbpSession.UserId.HasValue)
{
foreach (var permissionName in allPermissionNames)
{
if (await PermissionChecker.IsGrantedAsync(permissionName))
{
grantedPermissionNames.Add(permissionName);
}
}
}
config.AllPermissions = allPermissionNames.ToDictionary(permissionName => permissionName, permissionName => "true");
config.GrantedPermissions = grantedPermissionNames.ToDictionary(permissionName => permissionName, permissionName => "true");
return config;
}
protected virtual async Task<AbpUserNavConfigDto> GetUserNavConfig()
{
var userMenus = await UserNavigationManager.GetMenusAsync(AbpSession.ToUserIdentifier());
return new AbpUserNavConfigDto
{
Menus = userMenus.ToDictionary(userMenu => userMenu.Name, userMenu => userMenu)
};
}
protected virtual async Task<AbpUserSettingConfigDto> GetUserSettingConfig()
{
var config = new AbpUserSettingConfigDto
{
Values = new Dictionary<string, string>()
};
var settingDefinitions = SettingDefinitionManager
.GetAllSettingDefinitions();
using (var scope = _iocResolver.CreateScope())
{
foreach (var settingDefinition in settingDefinitions)
{
if (!await settingDefinition.ClientVisibilityProvider.CheckVisible(scope))
{
continue;
}
var settingValue = await SettingManager.GetSettingValueAsync(settingDefinition.Name);
config.Values.Add(settingDefinition.Name, settingValue);
}
}
return config;
}
protected virtual AbpUserClockConfigDto GetUserClockConfig()
{
return new AbpUserClockConfigDto
{
Provider = Clock.Provider.GetType().Name.ToCamelCase()
};
}
protected virtual async Task<AbpUserTimingConfigDto> GetUserTimingConfig()
{
var timezoneId = await SettingManager.GetSettingValueAsync(TimingSettingNames.TimeZone);
var timezone = TimezoneHelper.FindTimeZoneInfo(timezoneId);
return new AbpUserTimingConfigDto
{
TimeZoneInfo = new AbpUserTimeZoneConfigDto
{
Windows = new AbpUserWindowsTimeZoneConfigDto
{
TimeZoneId = timezoneId,
BaseUtcOffsetInMilliseconds = timezone.BaseUtcOffset.TotalMilliseconds,
CurrentUtcOffsetInMilliseconds = timezone.GetUtcOffset(Clock.Now).TotalMilliseconds,
IsDaylightSavingTimeNow = timezone.IsDaylightSavingTime(Clock.Now)
},
Iana = new AbpUserIanaTimeZoneConfigDto
{
TimeZoneId = TimezoneHelper.WindowsToIana(timezoneId)
}
}
};
}
protected virtual AbpUserSecurityConfigDto GetUserSecurityConfig()
{
return new AbpUserSecurityConfigDto
{
AntiForgery = new AbpUserAntiForgeryConfigDto
{
TokenCookieName = AbpAntiForgeryConfiguration.TokenCookieName,
TokenHeaderName = AbpAntiForgeryConfiguration.TokenHeaderName
}
};
}
}
}
| 38.829352 | 136 | 0.597785 | [
"MIT"
] | Aytekin/aspnetboilerplate | src/Abp.Web.Common/Web/Configuration/AbpUserConfigurationBuilder.cs | 11,377 | C# |
// Copyright 2018 by JCoder58. See License.txt for license
// Auto-generated --- Do not modify.
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using UE4.Core;
using UE4.CoreUObject;
using UE4.CoreUObject.Native;
using UE4.InputCore;
using UE4.Native;
#pragma warning disable CS0108
using UE4.BlueprintGraph.Native;
namespace UE4.BlueprintGraph {
///<summary>K2Node Load Asset Class</summary>
public unsafe partial class K2Node_LoadAssetClass : K2Node_LoadAsset {
static K2Node_LoadAssetClass() {
StaticClass = Main.GetClass("K2Node_LoadAssetClass");
}
internal unsafe K2Node_LoadAssetClass_fields* K2Node_LoadAssetClass_ptr => (K2Node_LoadAssetClass_fields*) ObjPointer.ToPointer();
///<summary>Convert from IntPtr to UObject</summary>
public static implicit operator K2Node_LoadAssetClass(IntPtr p) => UObject.Make<K2Node_LoadAssetClass>(p);
///<summary>Get UE4 Class</summary>
public static Class StaticClass {get; private set;}
///<summary>Get UE4 Default Object for this Class</summary>
public static K2Node_LoadAssetClass DefaultObject => Main.GetDefaultObject(StaticClass);
///<summary>Spawn an object of this class</summary>
public static K2Node_LoadAssetClass New(UObject obj = null, Name name = new Name()) => Main.NewObject(StaticClass, obj, name);
}
}
| 43 | 138 | 0.733615 | [
"MIT"
] | UE4DotNet/Plugin | DotNet/DotNet/UE4/Generated/BlueprintGraph/K2Node_LoadAssetClass.cs | 1,419 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using HuaweiCloud.SDK.Core;
namespace HuaweiCloud.SDK.Swr.V2.Model
{
/// <summary>
/// Request Object
/// </summary>
public class ListRetentionHistoriesRequest
{
/// <summary>
/// 组织名称。小写字母开头,后面跟小写字母、数字、小数点、下划线或中划线(其中下划线最多允许连续两个,小数点、下划线、中划线不能直接相连),小写字母或数字结尾,1-64个字符。
/// </summary>
[SDKProperty("namespace", IsPath = true)]
[JsonProperty("namespace", NullValueHandling = NullValueHandling.Ignore)]
public string Namespace { get; set; }
/// <summary>
/// 镜像仓库名称
/// </summary>
[SDKProperty("repository", IsPath = true)]
[JsonProperty("repository", NullValueHandling = NullValueHandling.Ignore)]
public string Repository { get; set; }
/// <summary>
/// 起始索引。**注意:offset和limit参数需要配套使用**
/// </summary>
[SDKProperty("offset", IsQuery = true)]
[JsonProperty("offset", NullValueHandling = NullValueHandling.Ignore)]
public string Offset { get; set; }
/// <summary>
/// 返回条数。**注意:offset和limit参数需要配套使用**
/// </summary>
[SDKProperty("limit", IsQuery = true)]
[JsonProperty("limit", NullValueHandling = NullValueHandling.Ignore)]
public string Limit { get; set; }
/// <summary>
/// Get the string
/// </summary>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class ListRetentionHistoriesRequest {\n");
sb.Append(" Namespace: ").Append(Namespace).Append("\n");
sb.Append(" repository: ").Append(Repository).Append("\n");
sb.Append(" offset: ").Append(Offset).Append("\n");
sb.Append(" limit: ").Append(Limit).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
public override bool Equals(object input)
{
return this.Equals(input as ListRetentionHistoriesRequest);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
public bool Equals(ListRetentionHistoriesRequest input)
{
if (input == null)
return false;
return
(
this.Namespace == input.Namespace ||
(this.Namespace != null &&
this.Namespace.Equals(input.Namespace))
) &&
(
this.Repository == input.Repository ||
(this.Repository != null &&
this.Repository.Equals(input.Repository))
) &&
(
this.Offset == input.Offset ||
(this.Offset != null &&
this.Offset.Equals(input.Offset))
) &&
(
this.Limit == input.Limit ||
(this.Limit != null &&
this.Limit.Equals(input.Limit))
);
}
/// <summary>
/// Get hash code
/// </summary>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.Namespace != null)
hashCode = hashCode * 59 + this.Namespace.GetHashCode();
if (this.Repository != null)
hashCode = hashCode * 59 + this.Repository.GetHashCode();
if (this.Offset != null)
hashCode = hashCode * 59 + this.Offset.GetHashCode();
if (this.Limit != null)
hashCode = hashCode * 59 + this.Limit.GetHashCode();
return hashCode;
}
}
}
}
| 33.368852 | 98 | 0.50872 | [
"Apache-2.0"
] | cnblogs/huaweicloud-sdk-net-v3 | Services/Swr/V2/Model/ListRetentionHistoriesRequest.cs | 4,315 | C# |
// This file is subject to the MIT License as seen in the root of this folder structure (LICENSE)
using UnityEngine;
namespace Crest
{
[CreateAssetMenu(fileName = "SimSettingsFoam", menuName = "Crest/Foam Sim Settings", order = 10000)]
public class SimSettingsFoam : SimSettingsBase
{
[Range(0f, 5f), Tooltip("Speed at which foam fades/dissipates.")]
public float _foamFadeRate = 0.8f;
[Range(0f, 5f), Tooltip("Scales intensity of foam generated from Gerstner waves.")]
public float _waveFoamStrength = 1.25f;
[Range(0f, 1f), Tooltip("How much of the Gerstner waves generate foam.")]
public float _waveFoamCoverage = 0.8f;
[Range(0f, 3f), Tooltip("Foam will be generated in water shallower than this depth.")]
public float _shorelineFoamMaxDepth = 0.65f;
[Range(0f, 1f), Tooltip("Scales intensity of foam generated in shallow water.")]
public float _shorelineFoamStrength = 0.313f;
}
}
| 44.772727 | 104 | 0.684264 | [
"MIT"
] | Rbn3D/crest-oceanrender | src/unity/Assets/Crest/Scripts/Simulation/Settings/SimSettingsFoam.cs | 987 | C# |
/**
* $File: JCS_ButtonSoundEffect.cs $
* $Date: $
* $Revision: $
* $Creator: Jen-Chieh Shen $
* $Notice: See LICENSE.txt for modification and distribution information
* Copyright (c) 2016 by Shen, Jen-Chieh $
*/
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
namespace JCSUnity
{
/// <summary>
/// Customize your own button sound base on different
/// circumstance.
///
/// Please use this class with Unity's "Event Trigger (Script)"!!!
/// </summary>
[RequireComponent(typeof(RectTransform))]
[RequireComponent(typeof(EventTrigger))]
public class JCS_ButtonSoundEffect
: MonoBehaviour
{
/* Variables */
private RectTransform mRectTransform = null;
private EventTrigger mEventTrigger = null;
[Header("** Optional Variables (JCS_ButtonSoundEffect) **")]
[Tooltip(@"Sound Player for this button, if this transform dose not
have the 'JCS_Soundplayer' then it will grab the global sound player.")]
[SerializeField]
private JCS_SoundPlayer mSoundPlayer = null;
[Header("Auto add to Unity's \"Event Trigger(Script)\" or not?")]
[Tooltip("is true u dont have to add manully!")]
[SerializeField]
private bool mAutoAddEvent = true;
[Header("*USAGE: Please use this component with Unity's \"Event Trigger(Script)\"!!!")]
[SerializeField]
private AudioClip mOnMouseOverSound = null;
[SerializeField]
private AudioClip mOnMouseExitSound = null;
[SerializeField]
private AudioClip mOnMouseDownSound = null;
[SerializeField]
private AudioClip mOnMouseUpSound = null;
[SerializeField]
private AudioClip mOnMouseClickSound = null;
[SerializeField]
private AudioClip mOnMouseDoubleClickSound = null;
private bool mIsOver = false;
[SerializeField]
private JCS_SoundMethod mOnMouseOverSoundMethod = JCS_SoundMethod.PLAY_SOUND;
[SerializeField]
private JCS_SoundMethod mOnMouseExitSoundMethod = JCS_SoundMethod.PLAY_SOUND;
[SerializeField]
private JCS_SoundMethod mOnMouseDownSoundMethod = JCS_SoundMethod.PLAY_SOUND;
[SerializeField]
private JCS_SoundMethod mOnMouseUpSoundMethod = JCS_SoundMethod.PLAY_SOUND;
[SerializeField]
private JCS_SoundMethod mOnMouseClickSoundMethod = JCS_SoundMethod.PLAY_SOUND;
[SerializeField]
private JCS_SoundMethod mOnMouseDoubleClickSoundMethod = JCS_SoundMethod.PLAY_SOUND;
[Header("** Optional Settings (JCS_ButtonSoundEffect) **")]
[Tooltip("Use to detect to see if the button is interactable or not.")]
[SerializeField]
private JCS_Button mJCSButton = null;
[Tooltip(@"When button is not interactable will active these when
on mouse down.")]
[SerializeField]
private AudioClip mOnMouseOverRefuseSound = null;
[SerializeField]
private AudioClip mOnMouseExitRefuseSound = null;
[SerializeField]
private AudioClip mOnMouseDownRefuseSound = null;
[SerializeField]
private AudioClip mOnMouseUpRefuseSound = null;
[SerializeField]
private AudioClip mOnMouseClickRefuseSound = null;
[SerializeField]
private AudioClip mOnMouseDoubleClickRefuseSound = null;
[SerializeField]
private JCS_SoundMethod mOnMouseOverRefuseSoundMethod = JCS_SoundMethod.PLAY_SOUND;
[SerializeField]
private JCS_SoundMethod mOnMouseExitRefuseSoundMethod = JCS_SoundMethod.PLAY_SOUND;
[SerializeField]
private JCS_SoundMethod mOnMouseDownRefuseSoundMethod = JCS_SoundMethod.PLAY_SOUND;
[SerializeField]
private JCS_SoundMethod mOnMouseUpRefuseSoundMethod = JCS_SoundMethod.PLAY_SOUND;
[SerializeField]
private JCS_SoundMethod mOnMouseClickRefuseSoundMethod = JCS_SoundMethod.PLAY_SOUND;
[SerializeField]
private JCS_SoundMethod mOnMouseDoubleClickRefuseSoundMethod = JCS_SoundMethod.PLAY_SOUND;
/* Setter & Getter */
public bool AutoAddEvent { get { return this.mAutoAddEvent; } set { this.mAutoAddEvent = value; } }
public AudioClip OnMouseOverSound { get { return this.mOnMouseOverSound; } set { this.mOnMouseOverSound = value; } }
public AudioClip OnMouseExitSound { get { return this.mOnMouseExitSound; } set { this.mOnMouseExitSound = value; } }
public AudioClip OnMouseDownSound { get { return this.mOnMouseDownSound; } set { this.mOnMouseDownSound = value; } }
public AudioClip OnMouseUpSound { get { return this.mOnMouseUpSound; } set { this.mOnMouseUpSound = value; } }
public AudioClip OnMouseClickSound { get { return this.mOnMouseClickSound; } set { this.mOnMouseClickSound = value; } }
public AudioClip OnMouseDoubleClickSound { get { return this.mOnMouseDoubleClickSound; } set { this.mOnMouseDoubleClickSound = value; } }
public JCS_SoundMethod OnMouseOverSoundMethod { get { return this.mOnMouseOverSoundMethod; } set { this.mOnMouseOverSoundMethod = value; } }
public JCS_SoundMethod OnMouseExitSoundMethod { get { return this.mOnMouseExitSoundMethod; } set { this.mOnMouseExitSoundMethod = value; } }
public JCS_SoundMethod OnMouseDownSoundMethod { get { return this.mOnMouseDownSoundMethod; } set { this.mOnMouseDownSoundMethod = value; } }
public JCS_SoundMethod OnMouseUpSoundMethod { get { return this.mOnMouseUpSoundMethod; } set { this.mOnMouseUpSoundMethod = value; } }
public JCS_SoundMethod OnMouseClickSoundMethod { get { return this.mOnMouseClickSoundMethod; } set { this.mOnMouseClickSoundMethod = value; } }
public JCS_SoundMethod OnMouseDoubleClickSoundMethod { get { return this.mOnMouseDoubleClickSoundMethod; } set { this.mOnMouseDoubleClickSoundMethod = value; } }
public AudioClip OnMouseOverRefuseSound { get { return this.mOnMouseOverRefuseSound; } set { this.mOnMouseOverRefuseSound = value; } }
public AudioClip OnMouseExitRefuseSound { get { return this.mOnMouseExitRefuseSound; } set { this.mOnMouseExitRefuseSound = value; } }
public AudioClip OnMouseDownRefuseSound { get { return this.mOnMouseDownRefuseSound; } set { this.mOnMouseDownRefuseSound = value; } }
public AudioClip OnMouseUpRefuseSound { get { return this.mOnMouseUpRefuseSound; } set { this.mOnMouseUpRefuseSound = value; } }
public AudioClip OnMouseClickRefuseSound { get { return this.mOnMouseClickRefuseSound; } set { this.mOnMouseClickRefuseSound = value; } }
public AudioClip OnMouseDoubleClickRefuseSound { get { return this.mOnMouseDoubleClickRefuseSound; } set { this.mOnMouseDoubleClickRefuseSound = value; } }
public JCS_SoundMethod OnMouseOverRefuseSoundMethod { get { return this.mOnMouseOverRefuseSoundMethod; } set { this.mOnMouseOverRefuseSoundMethod = value; } }
public JCS_SoundMethod OnMouseExitRefuseSoundMethod { get { return this.mOnMouseExitRefuseSoundMethod; } set { this.mOnMouseExitRefuseSoundMethod = value; } }
public JCS_SoundMethod OnMouseDownRefuseSoundMethod { get { return this.mOnMouseDownRefuseSoundMethod; } set { this.mOnMouseDownRefuseSoundMethod = value; } }
public JCS_SoundMethod OnMouseUpRefuseSoundMethod { get { return this.mOnMouseUpRefuseSoundMethod; } set { this.mOnMouseUpRefuseSoundMethod = value; } }
public JCS_SoundMethod OnMouseClickRefuseSoundMethod { get { return this.mOnMouseClickRefuseSoundMethod; } set { this.mOnMouseClickRefuseSoundMethod = value; } }
public JCS_SoundMethod OnMouseDoubleClickRefuseSoundMethod { get { return this.mOnMouseDoubleClickRefuseSoundMethod; } set { this.mOnMouseDoubleClickRefuseSoundMethod = value; } }
/* Functions */
private void Awake()
{
if (mSoundPlayer == null)
mSoundPlayer = this.GetComponent<JCS_SoundPlayer>();
mRectTransform = this.GetComponent<RectTransform>();
mEventTrigger = this.GetComponent<EventTrigger>();
if (mJCSButton == null)
mJCSButton = this.GetComponent<JCS_Button>();
}
private void Start()
{
/*
* NOTE(jenchieh): First get the sound player from its own
* transform, if it still missing then grab the global sound
* player.
*/
if (mSoundPlayer == null)
mSoundPlayer = JCS_SoundManager.instance.GetGlobalSoundPlayer();
if (mAutoAddEvent)
{
JCS_Utility.AddEventTriggerEvent(mEventTrigger, EventTriggerType.PointerEnter, JCS_OnMouseOver);
JCS_Utility.AddEventTriggerEvent(mEventTrigger, EventTriggerType.PointerEnter, JCS_OnMouseDoubleClick);
JCS_Utility.AddEventTriggerEvent(mEventTrigger, EventTriggerType.PointerExit, JCS_OnMouseExit);
JCS_Utility.AddEventTriggerEvent(mEventTrigger, EventTriggerType.PointerDown, JCS_OnMouseDown);
JCS_Utility.AddEventTriggerEvent(mEventTrigger, EventTriggerType.PointerUp, JCS_OnMouseUp);
JCS_Utility.AddEventTriggerEvent(mEventTrigger, EventTriggerType.PointerClick, JCS_OnMouseClick);
}
}
private void Update()
{
// IMPORTANT(JenChieh): only double click need update
if (mIsOver)
{
if (JCS_Input.OnMouseDoubleClick(0))
{
// either time is out or double click,
// both are all over the "double click event".
mIsOver = false;
if (mJCSButton != null)
{
if (!mJCSButton.Interactable)
{
// play not ineractable sound
mSoundPlayer.PlayOneShotByMethod(
mOnMouseDoubleClickRefuseSound,
mOnMouseDoubleClickRefuseSoundMethod);
return;
}
else
{
// play normal double click sound
mSoundPlayer.PlayOneShotByMethod(
mOnMouseDoubleClickSound,
mOnMouseDoubleClickSoundMethod);
}
}
}
// check if the mouse still over or not
if (!JCS_Utility.MouseOverGUI(this.mRectTransform))
mIsOver = false;
}
}
public void JCS_OnMouseOver(PointerEventData data)
{
JCS_OnMouseOver();
}
public void JCS_OnMouseOver()
{
if (mJCSButton != null)
{
if (!mJCSButton.Interactable)
{
// play not ineractable sound
mSoundPlayer.PlayOneShotByMethod(
mOnMouseOverRefuseSound,
mOnMouseOverRefuseSoundMethod);
return;
}
}
mSoundPlayer.PlayOneShotByMethod(
mOnMouseOverSound,
mOnMouseOverSoundMethod);
}
public void JCS_OnMouseExit(PointerEventData data)
{
JCS_OnMouseExit();
}
public void JCS_OnMouseExit()
{
if (mJCSButton == null)
return;
if (!mJCSButton.Interactable)
{
// play not ineractable sound
mSoundPlayer.PlayOneShotByMethod(
mOnMouseExitRefuseSound,
mOnMouseExitRefuseSoundMethod);
}
else
{
mSoundPlayer.PlayOneShotByMethod(
mOnMouseExitSound,
mOnMouseExitSoundMethod);
}
}
public void JCS_OnMouseDown(PointerEventData data)
{
JCS_OnMouseDown();
}
public void JCS_OnMouseDown()
{
if (mJCSButton == null)
return;
if (!mJCSButton.Interactable)
{
// play not ineractable sound
mSoundPlayer.PlayOneShotByMethod(
mOnMouseDownRefuseSound,
mOnMouseDownRefuseSoundMethod);
}
else
{
// play normal sound
mSoundPlayer.PlayOneShotByMethod(
mOnMouseDownSound,
mOnMouseDownSoundMethod);
}
}
public void JCS_OnMouseUp(PointerEventData data)
{
JCS_OnMouseUp();
}
public void JCS_OnMouseUp()
{
if (mJCSButton == null)
return;
if (!mJCSButton.Interactable)
{
// play not ineractable sound
mSoundPlayer.PlayOneShotByMethod(
mOnMouseUpRefuseSound,
mOnMouseUpRefuseSoundMethod);
}
else
{
mSoundPlayer.PlayOneShotByMethod(
mOnMouseUpSound,
mOnMouseUpSoundMethod);
}
}
public void JCS_OnMouseClick(PointerEventData data)
{
JCS_OnMouseClick();
}
public void JCS_OnMouseClick()
{
if (mJCSButton == null)
return;
if (!mJCSButton.Interactable)
{
// play not ineractable sound
mSoundPlayer.PlayOneShotByMethod(
mOnMouseClickRefuseSound,
mOnMouseClickRefuseSoundMethod);
}
else
{
mSoundPlayer.PlayOneShotByMethod(
mOnMouseClickSound,
mOnMouseClickSoundMethod);
}
}
// plz put this in Pointer Enter event
public void JCS_OnMouseDoubleClick(PointerEventData data)
{
JCS_OnMouseDoubleClick();
}
public void JCS_OnMouseDoubleClick()
{
mIsOver = true;
}
}
}
| 41.748555 | 187 | 0.615022 | [
"MIT"
] | edwin-channel/JCSUnity | Assets/JCSUnity/Scripts/Effects/JCS_ButtonSoundEffect.cs | 14,447 | 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.Network.V20200301
{
/// <summary>
/// Application gateway resource.
/// </summary>
[AzureNativeResourceType("azure-native:network/v20200301:ApplicationGateway")]
public partial class ApplicationGateway : Pulumi.CustomResource
{
/// <summary>
/// Authentication certificates of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits).
/// </summary>
[Output("authenticationCertificates")]
public Output<ImmutableArray<Outputs.ApplicationGatewayAuthenticationCertificateResponse>> AuthenticationCertificates { get; private set; } = null!;
/// <summary>
/// Autoscale Configuration.
/// </summary>
[Output("autoscaleConfiguration")]
public Output<Outputs.ApplicationGatewayAutoscaleConfigurationResponse?> AutoscaleConfiguration { get; private set; } = null!;
/// <summary>
/// Backend address pool of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits).
/// </summary>
[Output("backendAddressPools")]
public Output<ImmutableArray<Outputs.ApplicationGatewayBackendAddressPoolResponse>> BackendAddressPools { get; private set; } = null!;
/// <summary>
/// Backend http settings of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits).
/// </summary>
[Output("backendHttpSettingsCollection")]
public Output<ImmutableArray<Outputs.ApplicationGatewayBackendHttpSettingsResponse>> BackendHttpSettingsCollection { get; private set; } = null!;
/// <summary>
/// Custom error configurations of the application gateway resource.
/// </summary>
[Output("customErrorConfigurations")]
public Output<ImmutableArray<Outputs.ApplicationGatewayCustomErrorResponse>> CustomErrorConfigurations { get; private set; } = null!;
/// <summary>
/// Whether FIPS is enabled on the application gateway resource.
/// </summary>
[Output("enableFips")]
public Output<bool?> EnableFips { get; private set; } = null!;
/// <summary>
/// Whether HTTP2 is enabled on the application gateway resource.
/// </summary>
[Output("enableHttp2")]
public Output<bool?> EnableHttp2 { get; private set; } = null!;
/// <summary>
/// A unique read-only string that changes whenever the resource is updated.
/// </summary>
[Output("etag")]
public Output<string> Etag { get; private set; } = null!;
/// <summary>
/// Reference to the FirewallPolicy resource.
/// </summary>
[Output("firewallPolicy")]
public Output<Outputs.SubResourceResponse?> FirewallPolicy { get; private set; } = null!;
/// <summary>
/// If true, associates a firewall policy with an application gateway regardless whether the policy differs from the WAF Config.
/// </summary>
[Output("forceFirewallPolicyAssociation")]
public Output<bool?> ForceFirewallPolicyAssociation { get; private set; } = null!;
/// <summary>
/// Frontend IP addresses of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits).
/// </summary>
[Output("frontendIPConfigurations")]
public Output<ImmutableArray<Outputs.ApplicationGatewayFrontendIPConfigurationResponse>> FrontendIPConfigurations { get; private set; } = null!;
/// <summary>
/// Frontend ports of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits).
/// </summary>
[Output("frontendPorts")]
public Output<ImmutableArray<Outputs.ApplicationGatewayFrontendPortResponse>> FrontendPorts { get; private set; } = null!;
/// <summary>
/// Subnets of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits).
/// </summary>
[Output("gatewayIPConfigurations")]
public Output<ImmutableArray<Outputs.ApplicationGatewayIPConfigurationResponse>> GatewayIPConfigurations { get; private set; } = null!;
/// <summary>
/// Http listeners of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits).
/// </summary>
[Output("httpListeners")]
public Output<ImmutableArray<Outputs.ApplicationGatewayHttpListenerResponse>> HttpListeners { get; private set; } = null!;
/// <summary>
/// The identity of the application gateway, if configured.
/// </summary>
[Output("identity")]
public Output<Outputs.ManagedServiceIdentityResponse?> Identity { get; private set; } = null!;
/// <summary>
/// Resource location.
/// </summary>
[Output("location")]
public Output<string?> Location { get; private set; } = null!;
/// <summary>
/// Resource name.
/// </summary>
[Output("name")]
public Output<string> Name { get; private set; } = null!;
/// <summary>
/// Operational state of the application gateway resource.
/// </summary>
[Output("operationalState")]
public Output<string> OperationalState { get; private set; } = null!;
/// <summary>
/// Probes of the application gateway resource.
/// </summary>
[Output("probes")]
public Output<ImmutableArray<Outputs.ApplicationGatewayProbeResponse>> Probes { get; private set; } = null!;
/// <summary>
/// The provisioning state of the application gateway resource.
/// </summary>
[Output("provisioningState")]
public Output<string> ProvisioningState { get; private set; } = null!;
/// <summary>
/// Redirect configurations of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits).
/// </summary>
[Output("redirectConfigurations")]
public Output<ImmutableArray<Outputs.ApplicationGatewayRedirectConfigurationResponse>> RedirectConfigurations { get; private set; } = null!;
/// <summary>
/// Request routing rules of the application gateway resource.
/// </summary>
[Output("requestRoutingRules")]
public Output<ImmutableArray<Outputs.ApplicationGatewayRequestRoutingRuleResponse>> RequestRoutingRules { get; private set; } = null!;
/// <summary>
/// The resource GUID property of the application gateway resource.
/// </summary>
[Output("resourceGuid")]
public Output<string> ResourceGuid { get; private set; } = null!;
/// <summary>
/// Rewrite rules for the application gateway resource.
/// </summary>
[Output("rewriteRuleSets")]
public Output<ImmutableArray<Outputs.ApplicationGatewayRewriteRuleSetResponse>> RewriteRuleSets { get; private set; } = null!;
/// <summary>
/// SKU of the application gateway resource.
/// </summary>
[Output("sku")]
public Output<Outputs.ApplicationGatewaySkuResponse?> Sku { get; private set; } = null!;
/// <summary>
/// SSL certificates of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits).
/// </summary>
[Output("sslCertificates")]
public Output<ImmutableArray<Outputs.ApplicationGatewaySslCertificateResponse>> SslCertificates { get; private set; } = null!;
/// <summary>
/// SSL policy of the application gateway resource.
/// </summary>
[Output("sslPolicy")]
public Output<Outputs.ApplicationGatewaySslPolicyResponse?> SslPolicy { get; private set; } = null!;
/// <summary>
/// Resource tags.
/// </summary>
[Output("tags")]
public Output<ImmutableDictionary<string, string>?> Tags { get; private set; } = null!;
/// <summary>
/// Trusted Root certificates of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits).
/// </summary>
[Output("trustedRootCertificates")]
public Output<ImmutableArray<Outputs.ApplicationGatewayTrustedRootCertificateResponse>> TrustedRootCertificates { get; private set; } = null!;
/// <summary>
/// Resource type.
/// </summary>
[Output("type")]
public Output<string> Type { get; private set; } = null!;
/// <summary>
/// URL path map of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits).
/// </summary>
[Output("urlPathMaps")]
public Output<ImmutableArray<Outputs.ApplicationGatewayUrlPathMapResponse>> UrlPathMaps { get; private set; } = null!;
/// <summary>
/// Web application firewall configuration.
/// </summary>
[Output("webApplicationFirewallConfiguration")]
public Output<Outputs.ApplicationGatewayWebApplicationFirewallConfigurationResponse?> WebApplicationFirewallConfiguration { get; private set; } = null!;
/// <summary>
/// A list of availability zones denoting where the resource needs to come from.
/// </summary>
[Output("zones")]
public Output<ImmutableArray<string>> Zones { get; private set; } = null!;
/// <summary>
/// Create a ApplicationGateway resource with the given unique name, arguments, and options.
/// </summary>
///
/// <param name="name">The unique name of the resource</param>
/// <param name="args">The arguments used to populate this resource's properties</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public ApplicationGateway(string name, ApplicationGatewayArgs args, CustomResourceOptions? options = null)
: base("azure-native:network/v20200301:ApplicationGateway", name, args ?? new ApplicationGatewayArgs(), MakeResourceOptions(options, ""))
{
}
private ApplicationGateway(string name, Input<string> id, CustomResourceOptions? options = null)
: base("azure-native:network/v20200301:ApplicationGateway", name, null, MakeResourceOptions(options, id))
{
}
private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id)
{
var defaultOptions = new CustomResourceOptions
{
Version = Utilities.Version,
Aliases =
{
new Pulumi.Alias { Type = "azure-nextgen:network/v20200301:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-native:network:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-native:network/latest:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/latest:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20150501preview:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20150501preview:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20150615:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20150615:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20160330:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20160330:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20160601:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20160601:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20160901:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20160901:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20161201:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20161201:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20170301:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20170301:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20170601:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20170601:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20170801:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20170801:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20170901:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20170901:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20171001:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20171001:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20171101:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20171101:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20180101:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20180101:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20180201:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20180201:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20180401:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20180401:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20180601:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20180601:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20180701:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20180701:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20180801:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20180801:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20181001:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20181001:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20181101:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20181101:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20181201:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20181201:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20190201:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190201:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20190401:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190401:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20190601:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190601:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20190701:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190701:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20190801:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190801:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20190901:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190901:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20191101:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20191101:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20191201:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20191201:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20200401:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200401:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20200501:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200501:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20200601:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200601:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20200701:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200701:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20200801:ApplicationGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200801:ApplicationGateway"},
},
};
var merged = CustomResourceOptions.Merge(defaultOptions, options);
// Override the ID if one was specified for consistency with other language SDKs.
merged.Id = id ?? merged.Id;
return merged;
}
/// <summary>
/// Get an existing ApplicationGateway resource's state with the given name, ID, and optional extra
/// properties used to qualify the lookup.
/// </summary>
///
/// <param name="name">The unique name of the resulting resource.</param>
/// <param name="id">The unique provider ID of the resource to lookup.</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public static ApplicationGateway Get(string name, Input<string> id, CustomResourceOptions? options = null)
{
return new ApplicationGateway(name, id, options);
}
}
public sealed class ApplicationGatewayArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The name of the application gateway.
/// </summary>
[Input("applicationGatewayName")]
public Input<string>? ApplicationGatewayName { get; set; }
[Input("authenticationCertificates")]
private InputList<Inputs.ApplicationGatewayAuthenticationCertificateArgs>? _authenticationCertificates;
/// <summary>
/// Authentication certificates of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits).
/// </summary>
public InputList<Inputs.ApplicationGatewayAuthenticationCertificateArgs> AuthenticationCertificates
{
get => _authenticationCertificates ?? (_authenticationCertificates = new InputList<Inputs.ApplicationGatewayAuthenticationCertificateArgs>());
set => _authenticationCertificates = value;
}
/// <summary>
/// Autoscale Configuration.
/// </summary>
[Input("autoscaleConfiguration")]
public Input<Inputs.ApplicationGatewayAutoscaleConfigurationArgs>? AutoscaleConfiguration { get; set; }
[Input("backendAddressPools")]
private InputList<Inputs.ApplicationGatewayBackendAddressPoolArgs>? _backendAddressPools;
/// <summary>
/// Backend address pool of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits).
/// </summary>
public InputList<Inputs.ApplicationGatewayBackendAddressPoolArgs> BackendAddressPools
{
get => _backendAddressPools ?? (_backendAddressPools = new InputList<Inputs.ApplicationGatewayBackendAddressPoolArgs>());
set => _backendAddressPools = value;
}
[Input("backendHttpSettingsCollection")]
private InputList<Inputs.ApplicationGatewayBackendHttpSettingsArgs>? _backendHttpSettingsCollection;
/// <summary>
/// Backend http settings of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits).
/// </summary>
public InputList<Inputs.ApplicationGatewayBackendHttpSettingsArgs> BackendHttpSettingsCollection
{
get => _backendHttpSettingsCollection ?? (_backendHttpSettingsCollection = new InputList<Inputs.ApplicationGatewayBackendHttpSettingsArgs>());
set => _backendHttpSettingsCollection = value;
}
[Input("customErrorConfigurations")]
private InputList<Inputs.ApplicationGatewayCustomErrorArgs>? _customErrorConfigurations;
/// <summary>
/// Custom error configurations of the application gateway resource.
/// </summary>
public InputList<Inputs.ApplicationGatewayCustomErrorArgs> CustomErrorConfigurations
{
get => _customErrorConfigurations ?? (_customErrorConfigurations = new InputList<Inputs.ApplicationGatewayCustomErrorArgs>());
set => _customErrorConfigurations = value;
}
/// <summary>
/// Whether FIPS is enabled on the application gateway resource.
/// </summary>
[Input("enableFips")]
public Input<bool>? EnableFips { get; set; }
/// <summary>
/// Whether HTTP2 is enabled on the application gateway resource.
/// </summary>
[Input("enableHttp2")]
public Input<bool>? EnableHttp2 { get; set; }
/// <summary>
/// Reference to the FirewallPolicy resource.
/// </summary>
[Input("firewallPolicy")]
public Input<Inputs.SubResourceArgs>? FirewallPolicy { get; set; }
/// <summary>
/// If true, associates a firewall policy with an application gateway regardless whether the policy differs from the WAF Config.
/// </summary>
[Input("forceFirewallPolicyAssociation")]
public Input<bool>? ForceFirewallPolicyAssociation { get; set; }
[Input("frontendIPConfigurations")]
private InputList<Inputs.ApplicationGatewayFrontendIPConfigurationArgs>? _frontendIPConfigurations;
/// <summary>
/// Frontend IP addresses of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits).
/// </summary>
public InputList<Inputs.ApplicationGatewayFrontendIPConfigurationArgs> FrontendIPConfigurations
{
get => _frontendIPConfigurations ?? (_frontendIPConfigurations = new InputList<Inputs.ApplicationGatewayFrontendIPConfigurationArgs>());
set => _frontendIPConfigurations = value;
}
[Input("frontendPorts")]
private InputList<Inputs.ApplicationGatewayFrontendPortArgs>? _frontendPorts;
/// <summary>
/// Frontend ports of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits).
/// </summary>
public InputList<Inputs.ApplicationGatewayFrontendPortArgs> FrontendPorts
{
get => _frontendPorts ?? (_frontendPorts = new InputList<Inputs.ApplicationGatewayFrontendPortArgs>());
set => _frontendPorts = value;
}
[Input("gatewayIPConfigurations")]
private InputList<Inputs.ApplicationGatewayIPConfigurationArgs>? _gatewayIPConfigurations;
/// <summary>
/// Subnets of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits).
/// </summary>
public InputList<Inputs.ApplicationGatewayIPConfigurationArgs> GatewayIPConfigurations
{
get => _gatewayIPConfigurations ?? (_gatewayIPConfigurations = new InputList<Inputs.ApplicationGatewayIPConfigurationArgs>());
set => _gatewayIPConfigurations = value;
}
[Input("httpListeners")]
private InputList<Inputs.ApplicationGatewayHttpListenerArgs>? _httpListeners;
/// <summary>
/// Http listeners of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits).
/// </summary>
public InputList<Inputs.ApplicationGatewayHttpListenerArgs> HttpListeners
{
get => _httpListeners ?? (_httpListeners = new InputList<Inputs.ApplicationGatewayHttpListenerArgs>());
set => _httpListeners = value;
}
/// <summary>
/// Resource ID.
/// </summary>
[Input("id")]
public Input<string>? Id { get; set; }
/// <summary>
/// The identity of the application gateway, if configured.
/// </summary>
[Input("identity")]
public Input<Inputs.ManagedServiceIdentityArgs>? Identity { get; set; }
/// <summary>
/// Resource location.
/// </summary>
[Input("location")]
public Input<string>? Location { get; set; }
[Input("probes")]
private InputList<Inputs.ApplicationGatewayProbeArgs>? _probes;
/// <summary>
/// Probes of the application gateway resource.
/// </summary>
public InputList<Inputs.ApplicationGatewayProbeArgs> Probes
{
get => _probes ?? (_probes = new InputList<Inputs.ApplicationGatewayProbeArgs>());
set => _probes = value;
}
[Input("redirectConfigurations")]
private InputList<Inputs.ApplicationGatewayRedirectConfigurationArgs>? _redirectConfigurations;
/// <summary>
/// Redirect configurations of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits).
/// </summary>
public InputList<Inputs.ApplicationGatewayRedirectConfigurationArgs> RedirectConfigurations
{
get => _redirectConfigurations ?? (_redirectConfigurations = new InputList<Inputs.ApplicationGatewayRedirectConfigurationArgs>());
set => _redirectConfigurations = value;
}
[Input("requestRoutingRules")]
private InputList<Inputs.ApplicationGatewayRequestRoutingRuleArgs>? _requestRoutingRules;
/// <summary>
/// Request routing rules of the application gateway resource.
/// </summary>
public InputList<Inputs.ApplicationGatewayRequestRoutingRuleArgs> RequestRoutingRules
{
get => _requestRoutingRules ?? (_requestRoutingRules = new InputList<Inputs.ApplicationGatewayRequestRoutingRuleArgs>());
set => _requestRoutingRules = value;
}
/// <summary>
/// The name of the resource group.
/// </summary>
[Input("resourceGroupName", required: true)]
public Input<string> ResourceGroupName { get; set; } = null!;
[Input("rewriteRuleSets")]
private InputList<Inputs.ApplicationGatewayRewriteRuleSetArgs>? _rewriteRuleSets;
/// <summary>
/// Rewrite rules for the application gateway resource.
/// </summary>
public InputList<Inputs.ApplicationGatewayRewriteRuleSetArgs> RewriteRuleSets
{
get => _rewriteRuleSets ?? (_rewriteRuleSets = new InputList<Inputs.ApplicationGatewayRewriteRuleSetArgs>());
set => _rewriteRuleSets = value;
}
/// <summary>
/// SKU of the application gateway resource.
/// </summary>
[Input("sku")]
public Input<Inputs.ApplicationGatewaySkuArgs>? Sku { get; set; }
[Input("sslCertificates")]
private InputList<Inputs.ApplicationGatewaySslCertificateArgs>? _sslCertificates;
/// <summary>
/// SSL certificates of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits).
/// </summary>
public InputList<Inputs.ApplicationGatewaySslCertificateArgs> SslCertificates
{
get => _sslCertificates ?? (_sslCertificates = new InputList<Inputs.ApplicationGatewaySslCertificateArgs>());
set => _sslCertificates = value;
}
/// <summary>
/// SSL policy of the application gateway resource.
/// </summary>
[Input("sslPolicy")]
public Input<Inputs.ApplicationGatewaySslPolicyArgs>? SslPolicy { get; set; }
[Input("tags")]
private InputMap<string>? _tags;
/// <summary>
/// Resource tags.
/// </summary>
public InputMap<string> Tags
{
get => _tags ?? (_tags = new InputMap<string>());
set => _tags = value;
}
[Input("trustedRootCertificates")]
private InputList<Inputs.ApplicationGatewayTrustedRootCertificateArgs>? _trustedRootCertificates;
/// <summary>
/// Trusted Root certificates of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits).
/// </summary>
public InputList<Inputs.ApplicationGatewayTrustedRootCertificateArgs> TrustedRootCertificates
{
get => _trustedRootCertificates ?? (_trustedRootCertificates = new InputList<Inputs.ApplicationGatewayTrustedRootCertificateArgs>());
set => _trustedRootCertificates = value;
}
[Input("urlPathMaps")]
private InputList<Inputs.ApplicationGatewayUrlPathMapArgs>? _urlPathMaps;
/// <summary>
/// URL path map of the application gateway resource. For default limits, see [Application Gateway limits](https://docs.microsoft.com/azure/azure-subscription-service-limits#application-gateway-limits).
/// </summary>
public InputList<Inputs.ApplicationGatewayUrlPathMapArgs> UrlPathMaps
{
get => _urlPathMaps ?? (_urlPathMaps = new InputList<Inputs.ApplicationGatewayUrlPathMapArgs>());
set => _urlPathMaps = value;
}
/// <summary>
/// Web application firewall configuration.
/// </summary>
[Input("webApplicationFirewallConfiguration")]
public Input<Inputs.ApplicationGatewayWebApplicationFirewallConfigurationArgs>? WebApplicationFirewallConfiguration { get; set; }
[Input("zones")]
private InputList<string>? _zones;
/// <summary>
/// A list of availability zones denoting where the resource needs to come from.
/// </summary>
public InputList<string> Zones
{
get => _zones ?? (_zones = new InputList<string>());
set => _zones = value;
}
public ApplicationGatewayArgs()
{
}
}
}
| 53.991987 | 225 | 0.65614 | [
"Apache-2.0"
] | pulumi-bot/pulumi-azure-native | sdk/dotnet/Network/V20200301/ApplicationGateway.cs | 33,691 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
[assembly: System.Reflection.AssemblyCompanyAttribute("CoodenadasDeUmPonto")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")]
[assembly: System.Reflection.AssemblyProductAttribute("CoodenadasDeUmPonto")]
[assembly: System.Reflection.AssemblyTitleAttribute("CoodenadasDeUmPonto")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
// Generated by the MSBuild WriteCodeFragment class.
| 41.958333 | 80 | 0.656405 | [
"MIT"
] | g-aleprojetos/DIO | Bootcamps/Everis New Talents - dotnet/DesafiosAvancadosEmCSharp/CoodenadasDeUmPonto/obj/Debug/net5.0/CoodenadasDeUmPonto.AssemblyInfo.cs | 1,007 | C# |
using System;
namespace FizzyBuzz
{
public class Program
{
static void Main(string[] args)
{
for (Number number = new Number(1); number <= 100; number++)
{
if (number.IsMod3() && number.IsMod5())
{
Console.WriteLine("FizzBuzz");
}
else if (number.IsMod3())
{
Console.WriteLine("Fizz");
}
else if (number.IsMod5())
{
Console.WriteLine("Buzz");
}
else
{
Console.WriteLine((int)number);
}
}
Console.Read();
}
}
}
| 15.212121 | 63 | 0.551793 | [
"MIT"
] | gilbertgeorge/fizzybuzz | FizzyBuzz/FizzyBuzz/Program.cs | 504 | C# |
namespace FactoryPattern
{
public abstract class PizzaFactory
{
public abstract Pizza CreatePizza();
}
}
| 15.75 | 44 | 0.666667 | [
"MIT"
] | PhilShishov/Design-Patterns | CreationalDesignPatterns/FactoryPattern/PizzaFactory.cs | 128 | C# |
using System;
namespace PuertsStaticWrap
{
public static class UnityEngine_LightProbes_Wrap
{
[Puerts.MonoPInvokeCallback(typeof(Puerts.V8ConstructorCallback))]
private static IntPtr Constructor(IntPtr isolate, IntPtr info, int paramLen, long data)
{
try
{
Puerts.PuertsDLL.ThrowException(isolate, "invalid arguments to UnityEngine.LightProbes constructor");
}
catch (Exception e)
{
Puerts.PuertsDLL.ThrowException(isolate, "c# exception:" + e.Message + ",stack:" + e.StackTrace);
}
return IntPtr.Zero;
}
[Puerts.MonoPInvokeCallback(typeof(Puerts.V8FunctionCallback))]
private static void F_Tetrahedralize(IntPtr isolate, IntPtr info, IntPtr self, int paramLen, long data)
{
try
{
{
{
UnityEngine.LightProbes.Tetrahedralize();
}
}
}
catch (Exception e)
{
Puerts.PuertsDLL.ThrowException(isolate, "c# exception:" + e.Message + ",stack:" + e.StackTrace);
}
}
[Puerts.MonoPInvokeCallback(typeof(Puerts.V8FunctionCallback))]
private static void F_TetrahedralizeAsync(IntPtr isolate, IntPtr info, IntPtr self, int paramLen, long data)
{
try
{
{
{
UnityEngine.LightProbes.TetrahedralizeAsync();
}
}
}
catch (Exception e)
{
Puerts.PuertsDLL.ThrowException(isolate, "c# exception:" + e.Message + ",stack:" + e.StackTrace);
}
}
[Puerts.MonoPInvokeCallback(typeof(Puerts.V8FunctionCallback))]
private static void F_GetInterpolatedProbe(IntPtr isolate, IntPtr info, IntPtr self, int paramLen, long data)
{
try
{
{
var argHelper0 = new Puerts.ArgumentHelper((int)data, isolate, info, 0);
var argHelper1 = new Puerts.ArgumentHelper((int)data, isolate, info, 1);
var argHelper2 = new Puerts.ArgumentHelper((int)data, isolate, info, 2);
{
var Arg0 = argHelper0.Get<UnityEngine.Vector3>(false);
var Arg1 = argHelper1.Get<UnityEngine.Renderer>(false);
var Arg2 = argHelper2.Get<UnityEngine.Rendering.SphericalHarmonicsL2>(true);
UnityEngine.LightProbes.GetInterpolatedProbe(Arg0,Arg1,out Arg2);
argHelper2.SetByRefValue(Arg2);
}
}
}
catch (Exception e)
{
Puerts.PuertsDLL.ThrowException(isolate, "c# exception:" + e.Message + ",stack:" + e.StackTrace);
}
}
[Puerts.MonoPInvokeCallback(typeof(Puerts.V8FunctionCallback))]
private static void F_CalculateInterpolatedLightAndOcclusionProbes(IntPtr isolate, IntPtr info, IntPtr self, int paramLen, long data)
{
try
{
if (paramLen == 3)
{
var argHelper0 = new Puerts.ArgumentHelper((int)data, isolate, info, 0);
var argHelper1 = new Puerts.ArgumentHelper((int)data, isolate, info, 1);
var argHelper2 = new Puerts.ArgumentHelper((int)data, isolate, info, 2);
if (argHelper0.IsMatch(Puerts.JsValueType.NullOrUndefined | Puerts.JsValueType.NativeObject, typeof(UnityEngine.Vector3[]), false, false)
&& argHelper1.IsMatch(Puerts.JsValueType.NullOrUndefined | Puerts.JsValueType.NativeObject, typeof(UnityEngine.Rendering.SphericalHarmonicsL2[]), false, false)
&& argHelper2.IsMatch(Puerts.JsValueType.NullOrUndefined | Puerts.JsValueType.NativeObject, typeof(UnityEngine.Vector4[]), false, false))
{
var Arg0 = argHelper0.Get<UnityEngine.Vector3[]>(false);
var Arg1 = argHelper1.Get<UnityEngine.Rendering.SphericalHarmonicsL2[]>(false);
var Arg2 = argHelper2.Get<UnityEngine.Vector4[]>(false);
UnityEngine.LightProbes.CalculateInterpolatedLightAndOcclusionProbes(Arg0,Arg1,Arg2);
return;
}
if (argHelper0.IsMatch(Puerts.JsValueType.NullOrUndefined | Puerts.JsValueType.NativeObject, typeof(System.Collections.Generic.List<UnityEngine.Vector3>), false, false)
&& argHelper1.IsMatch(Puerts.JsValueType.NullOrUndefined | Puerts.JsValueType.NativeObject, typeof(System.Collections.Generic.List<UnityEngine.Rendering.SphericalHarmonicsL2>), false, false)
&& argHelper2.IsMatch(Puerts.JsValueType.NullOrUndefined | Puerts.JsValueType.NativeObject, typeof(System.Collections.Generic.List<UnityEngine.Vector4>), false, false))
{
var Arg0 = argHelper0.Get<System.Collections.Generic.List<UnityEngine.Vector3>>(false);
var Arg1 = argHelper1.Get<System.Collections.Generic.List<UnityEngine.Rendering.SphericalHarmonicsL2>>(false);
var Arg2 = argHelper2.Get<System.Collections.Generic.List<UnityEngine.Vector4>>(false);
UnityEngine.LightProbes.CalculateInterpolatedLightAndOcclusionProbes(Arg0,Arg1,Arg2);
return;
}
}
Puerts.PuertsDLL.ThrowException(isolate, "invalid arguments to CalculateInterpolatedLightAndOcclusionProbes");
}
catch (Exception e)
{
Puerts.PuertsDLL.ThrowException(isolate, "c# exception:" + e.Message + ",stack:" + e.StackTrace);
}
}
[Puerts.MonoPInvokeCallback(typeof(Puerts.V8FunctionCallback))]
private static void G_positions(IntPtr isolate, IntPtr info, IntPtr self, int paramLen, long data)
{
try
{
var obj = Puerts.Utils.GetSelf((int)data, self) as UnityEngine.LightProbes;
var result = obj.positions;
Puerts.ResultHelper.Set((int)data, isolate, info, result);
}
catch (Exception e)
{
Puerts.PuertsDLL.ThrowException(isolate, "c# exception:" + e.Message + ",stack:" + e.StackTrace);
}
}
[Puerts.MonoPInvokeCallback(typeof(Puerts.V8FunctionCallback))]
private static void G_bakedProbes(IntPtr isolate, IntPtr info, IntPtr self, int paramLen, long data)
{
try
{
var obj = Puerts.Utils.GetSelf((int)data, self) as UnityEngine.LightProbes;
var result = obj.bakedProbes;
Puerts.ResultHelper.Set((int)data, isolate, info, result);
}
catch (Exception e)
{
Puerts.PuertsDLL.ThrowException(isolate, "c# exception:" + e.Message + ",stack:" + e.StackTrace);
}
}
[Puerts.MonoPInvokeCallback(typeof(Puerts.V8FunctionCallback))]
private static void S_bakedProbes(IntPtr isolate, IntPtr info, IntPtr self, int paramLen, long data)
{
try
{
var obj = Puerts.Utils.GetSelf((int)data, self) as UnityEngine.LightProbes;
var argHelper = new Puerts.ArgumentHelper((int)data, isolate, info, 0);
obj.bakedProbes = argHelper.Get<UnityEngine.Rendering.SphericalHarmonicsL2[]>(false);
}
catch (Exception e)
{
Puerts.PuertsDLL.ThrowException(isolate, "c# exception:" + e.Message + ",stack:" + e.StackTrace);
}
}
[Puerts.MonoPInvokeCallback(typeof(Puerts.V8FunctionCallback))]
private static void G_count(IntPtr isolate, IntPtr info, IntPtr self, int paramLen, long data)
{
try
{
var obj = Puerts.Utils.GetSelf((int)data, self) as UnityEngine.LightProbes;
var result = obj.count;
Puerts.PuertsDLL.ReturnNumber(isolate, info, result);
}
catch (Exception e)
{
Puerts.PuertsDLL.ThrowException(isolate, "c# exception:" + e.Message + ",stack:" + e.StackTrace);
}
}
[Puerts.MonoPInvokeCallback(typeof(Puerts.V8FunctionCallback))]
private static void G_cellCount(IntPtr isolate, IntPtr info, IntPtr self, int paramLen, long data)
{
try
{
var obj = Puerts.Utils.GetSelf((int)data, self) as UnityEngine.LightProbes;
var result = obj.cellCount;
Puerts.PuertsDLL.ReturnNumber(isolate, info, result);
}
catch (Exception e)
{
Puerts.PuertsDLL.ThrowException(isolate, "c# exception:" + e.Message + ",stack:" + e.StackTrace);
}
}
[Puerts.MonoPInvokeCallback(typeof(Puerts.V8FunctionCallback))]
private static void A_tetrahedralizationCompleted(IntPtr isolate, IntPtr info, IntPtr self, int paramLen, long data)
{
try
{
var argHelper = new Puerts.ArgumentHelper((int)data, isolate, info, 0);
UnityEngine.LightProbes.tetrahedralizationCompleted += argHelper.Get<System.Action>(false);
}
catch (Exception e)
{
Puerts.PuertsDLL.ThrowException(isolate, "c# exception:" + e.Message + ",stack:" + e.StackTrace);
}
}
[Puerts.MonoPInvokeCallback(typeof(Puerts.V8FunctionCallback))]
private static void R_tetrahedralizationCompleted(IntPtr isolate, IntPtr info, IntPtr self, int paramLen, long data)
{
try
{
var argHelper = new Puerts.ArgumentHelper((int)data, isolate, info, 0);
UnityEngine.LightProbes.tetrahedralizationCompleted -= argHelper.Get<System.Action>(false);
}
catch (Exception e)
{
Puerts.PuertsDLL.ThrowException(isolate, "c# exception:" + e.Message + ",stack:" + e.StackTrace);
}
}
[Puerts.MonoPInvokeCallback(typeof(Puerts.V8FunctionCallback))]
private static void A_needsRetetrahedralization(IntPtr isolate, IntPtr info, IntPtr self, int paramLen, long data)
{
try
{
var argHelper = new Puerts.ArgumentHelper((int)data, isolate, info, 0);
UnityEngine.LightProbes.needsRetetrahedralization += argHelper.Get<System.Action>(false);
}
catch (Exception e)
{
Puerts.PuertsDLL.ThrowException(isolate, "c# exception:" + e.Message + ",stack:" + e.StackTrace);
}
}
[Puerts.MonoPInvokeCallback(typeof(Puerts.V8FunctionCallback))]
private static void R_needsRetetrahedralization(IntPtr isolate, IntPtr info, IntPtr self, int paramLen, long data)
{
try
{
var argHelper = new Puerts.ArgumentHelper((int)data, isolate, info, 0);
UnityEngine.LightProbes.needsRetetrahedralization -= argHelper.Get<System.Action>(false);
}
catch (Exception e)
{
Puerts.PuertsDLL.ThrowException(isolate, "c# exception:" + e.Message + ",stack:" + e.StackTrace);
}
}
public static Puerts.TypeRegisterInfo GetRegisterInfo()
{
return new Puerts.TypeRegisterInfo()
{
BlittableCopy = false,
Constructor = Constructor,
Methods = new System.Collections.Generic.Dictionary<Puerts.MethodKey, Puerts.V8FunctionCallback>()
{
{ new Puerts.MethodKey {Name = "Tetrahedralize", IsStatic = true}, F_Tetrahedralize },
{ new Puerts.MethodKey {Name = "TetrahedralizeAsync", IsStatic = true}, F_TetrahedralizeAsync },
{ new Puerts.MethodKey {Name = "GetInterpolatedProbe", IsStatic = true}, F_GetInterpolatedProbe },
{ new Puerts.MethodKey {Name = "CalculateInterpolatedLightAndOcclusionProbes", IsStatic = true}, F_CalculateInterpolatedLightAndOcclusionProbes },
{ new Puerts.MethodKey {Name = "add_tetrahedralizationCompleted", IsStatic = true}, A_tetrahedralizationCompleted},
{ new Puerts.MethodKey {Name = "remove_tetrahedralizationCompleted", IsStatic = true}, R_tetrahedralizationCompleted},
{ new Puerts.MethodKey {Name = "add_needsRetetrahedralization", IsStatic = true}, A_needsRetetrahedralization},
{ new Puerts.MethodKey {Name = "remove_needsRetetrahedralization", IsStatic = true}, R_needsRetetrahedralization},
},
Properties = new System.Collections.Generic.Dictionary<string, Puerts.PropertyRegisterInfo>()
{
{"positions", new Puerts.PropertyRegisterInfo(){ IsStatic = false, Getter = G_positions, Setter = null} },
{"bakedProbes", new Puerts.PropertyRegisterInfo(){ IsStatic = false, Getter = G_bakedProbes, Setter = S_bakedProbes} },
{"count", new Puerts.PropertyRegisterInfo(){ IsStatic = false, Getter = G_count, Setter = null} },
{"cellCount", new Puerts.PropertyRegisterInfo(){ IsStatic = false, Getter = G_cellCount, Setter = null} },
}
};
}
}
} | 43.557746 | 214 | 0.520856 | [
"MIT"
] | HFX-93/luban_examples | Projects/TypeScript_Unity_Puerts_Bin/Assets/Gen/UnityEngine_LightProbes_Wrap.cs | 15,465 | C# |
#if !NETSTANDARD13
/*
* 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 iot-2015-05-28.normal.json service model.
*/
using Amazon.Runtime;
namespace Amazon.IoT.Model
{
/// <summary>
/// Paginator for the ListPolicyPrincipals operation
///</summary>
public interface IListPolicyPrincipalsPaginator
{
/// <summary>
/// Enumerable containing all full responses for the operation
/// </summary>
IPaginatedEnumerable<ListPolicyPrincipalsResponse> Responses { get; }
/// <summary>
/// Enumerable containing all of the Principals
/// </summary>
IPaginatedEnumerable<string> Principals { get; }
}
}
#endif | 32.9 | 102 | 0.667933 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/IoT/Generated/Model/_bcl45+netstandard/IListPolicyPrincipalsPaginator.cs | 1,316 | C# |
// This file is part of Silk.NET.
//
// You may modify and distribute Silk.NET under the terms
// of the MIT license. See the LICENSE file for details.
using System;
using System.Runtime.InteropServices;
using System.Text;
using Silk.NET.Core.Native;
using Ultz.SuperInvoke;
#pragma warning disable 1591
namespace Silk.NET.Vulkan
{
public unsafe struct SubpassDescriptionDepthStencilResolve
{
public SubpassDescriptionDepthStencilResolve
(
StructureType sType = StructureType.SubpassDescriptionDepthStencilResolve,
void* pNext = default,
ResolveModeFlags depthResolveMode = default,
ResolveModeFlags stencilResolveMode = default,
AttachmentReference2* pDepthStencilResolveAttachment = default
)
{
SType = sType;
PNext = pNext;
DepthResolveMode = depthResolveMode;
StencilResolveMode = stencilResolveMode;
PDepthStencilResolveAttachment = pDepthStencilResolveAttachment;
}
/// <summary></summary>
public StructureType SType;
/// <summary></summary>
public void* PNext;
/// <summary></summary>
public ResolveModeFlags DepthResolveMode;
/// <summary></summary>
public ResolveModeFlags StencilResolveMode;
/// <summary></summary>
public AttachmentReference2* PDepthStencilResolveAttachment;
}
}
| 29.87234 | 86 | 0.688746 | [
"MIT"
] | AzyIsCool/Silk.NET | src/Vulkan/Silk.NET.Vulkan/Structs/SubpassDescriptionDepthStencilResolve.gen.cs | 1,404 | C# |
namespace Shopping_cart.Authorization.Accounts.Dto
{
public class IsTenantAvailableOutput
{
public TenantAvailabilityState State { get; set; }
public int? TenantId { get; set; }
public IsTenantAvailableOutput()
{
}
public IsTenantAvailableOutput(TenantAvailabilityState state, int? tenantId = null)
{
State = state;
TenantId = tenantId;
}
}
}
| 22.3 | 91 | 0.605381 | [
"MIT"
] | vishnupriya55/Shopping_cart | aspnet-core/src/Shopping_cart.Application/Authorization/Accounts/Dto/IsTenantAvailableOutput.cs | 446 | C# |
#region PDFsharp - A .NET library for processing PDF
//
// Authors:
// Stefan Lange
//
// Copyright (c) 2005-2019 empira Software GmbH, Cologne Area (Germany)
//
// http://www.pdfsharp.com
// http://sourceforge.net/projects/pdfsharp
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#endregion
namespace PdfSharp.Pdf.IO
{
/// <summary>
/// Determines the type of the password.
/// </summary>
public enum PasswordValidity
{
/// <summary>
/// Password is neither user nor owner password.
/// </summary>
Invalid,
/// <summary>
/// Password is user password.
/// </summary>
UserPassword,
/// <summary>
/// Password is owner password.
/// </summary>
OwnerPassword,
}
}
| 34.245283 | 77 | 0.687603 | [
"MIT"
] | 0xced/PDFsharp | src/PdfSharp/Pdf.IO/enums/PasswordValidity.cs | 1,815 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cosmos
{
/// <summary>
/// 网络模块定义的常量;
/// </summary>
public class NetworkConstant
{
/// <summary>
/// 秒级别;
/// 1代表1秒;
/// </summary>
public const byte HeartbeatMaxRto = 3;
/// <summary>
/// 最大失效次数
/// </summary>
public const uint HeartbeatInterval = 5;
/// <summary>
/// 重传次数;
/// </summary>
public const int RTO_DEF = 200;
/// <summary>
/// 解析间隔
/// </summary>// default RTO
public const int Interval = 100;
}
}
| 21.242424 | 48 | 0.513552 | [
"MIT"
] | DonHitYep/CosmosFramework | Assets/CosmosFramework/Runtime/Modules/Network/Base/NetworkConstant.cs | 769 | C# |
/**
* Copyright 2017-2020 Plexus Interop Deutsche Bank AG
* SPDX-License-Identifier: Apache-2.0
*
* 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 Plexus
{
using System.Threading;
internal sealed class Latch
{
private volatile int _entered;
public bool TryEnter()
{
return Interlocked.Exchange(ref _entered, 1) == 0;
}
public bool IsEntered => _entered == 1;
public void Reset()
{
_entered = 0;
}
}
}
| 27.157895 | 75 | 0.660853 | [
"ECL-2.0",
"Apache-2.0"
] | brntbeer/plexus-interop | desktop/src/Plexus.Utils/Latch.cs | 1,032 | C# |
namespace soen390_team01.Data.Exceptions
{
public class NotFoundException : DataAccessException
{
public NotFoundException(string entity, string identifier, string value)
: base("Non existent entity", BuildMessage(entity, identifier, value))
{}
private static string BuildMessage(string entity, string identifier, string value)
{
return entity + " with " + identifier + "=" + value + " was not found.";
}
}
}
| 34.785714 | 90 | 0.640657 | [
"MIT"
] | jshoyos/soen390-team01 | soen390-team01/soen390-team01/Data/Exceptions/NotFoundException.cs | 489 | C# |
// Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.0.6365, generator: {generator})
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
namespace Commvault.Powershell.Models
{
using Commvault.Powershell.Runtime.PowerShell;
/// <summary>
/// A PowerShell PSTypeConverter to support converting to an instance of <see cref="PlanBackupDestinationResp" />
/// </summary>
public partial class PlanBackupDestinationRespTypeConverter : global::System.Management.Automation.PSTypeConverter
{
/// <summary>
/// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" />
/// parameter.
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <returns>
/// <c>true</c> if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" />
/// parameter, otherwise <c>false</c>.
/// </returns>
public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue);
/// <summary>
/// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" />
/// parameter.
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object" /> instance to check if it can be converted to the <see cref="PlanBackupDestinationResp"
/// /> type.</param>
/// <returns>
/// <c>true</c> if the instance could be converted to a <see cref="PlanBackupDestinationResp" /> type, otherwise <c>false</c>
/// </returns>
public static bool CanConvertFrom(dynamic sourceValue)
{
if (null == sourceValue)
{
return true;
}
global::System.Type type = sourceValue.GetType();
if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type))
{
// we say yest to PSObjects
return true;
}
if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type))
{
// we say yest to Hashtables/dictionaries
return true;
}
try
{
if (null != sourceValue.ToJsonString())
{
return true;
}
}
catch
{
// Not one of our objects
}
try
{
string text = sourceValue.ToString()?.Trim();
return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Commvault.Powershell.Runtime.Json.JsonNode.Parse(text).Type == Commvault.Powershell.Runtime.Json.JsonType.Object;
}
catch
{
// Doesn't look like it can be treated as JSON
}
return false;
}
/// <summary>
/// Determines if the <see cref="sourceValue" /> parameter can be converted to the <see cref="destinationType" /> parameter
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <returns>
/// <c>true</c> if the converter can convert the <see cref="sourceValue" /> parameter to the <see cref="destinationType" />
/// parameter, otherwise <c>false</c>
/// </returns>
public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false;
/// <summary>
/// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider"
/// /> and <see cref="ignoreCase" />
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <param name="formatProvider">not used by this TypeConverter.</param>
/// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param>
/// <returns>
/// an instance of <see cref="PlanBackupDestinationResp" />, or <c>null</c> if there is no suitable conversion.
/// </returns>
public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue);
/// <summary>
/// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider"
/// /> and <see cref="ignoreCase" />
/// </summary>
/// <param name="sourceValue">the value to convert into an instance of <see cref="PlanBackupDestinationResp" />.</param>
/// <returns>
/// an instance of <see cref="PlanBackupDestinationResp" />, or <c>null</c> if there is no suitable conversion.
/// </returns>
public static Commvault.Powershell.Models.IPlanBackupDestinationResp ConvertFrom(dynamic sourceValue)
{
if (null == sourceValue)
{
return null;
}
global::System.Type type = sourceValue.GetType();
if (typeof(Commvault.Powershell.Models.IPlanBackupDestinationResp).IsAssignableFrom(type))
{
return sourceValue;
}
try
{
return PlanBackupDestinationResp.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());;
}
catch
{
// Unable to use JSON pattern
}
if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type))
{
return PlanBackupDestinationResp.DeserializeFromPSObject(sourceValue);
}
if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type))
{
return PlanBackupDestinationResp.DeserializeFromDictionary(sourceValue);
}
return null;
}
/// <summary>NotImplemented -- this will return <c>null</c></summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <param name="formatProvider">not used by this TypeConverter.</param>
/// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param>
/// <returns>will always return <c>null</c>.</returns>
public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null;
}
} | 50.186207 | 200 | 0.597087 | [
"MIT"
] | Commvault/CVPowershellSDKV2 | generated/api/Models/PlanBackupDestinationResp.TypeConverter.cs | 7,277 | C# |
//C6#CPE001
//C5#43121
//Description: Adds the ISSN to the periodical name or replaces the periodical name for the ISSN
//Version: 2.1
//Version 2.1 changed options to that component can also be suppressed altogether if there is no ISSN for a given Journal
// therefore we now have the options (output modes) AppendISSNToJournalName, ShowISSNOnlyOrJournalName or ShowISSNOnlyOrSuppressJournalName
//Version 2.0 added option to append ISSN or replace periodical name with ISSN
//Version 1.1 added options to set parentheses around the ISSN as well as prefix and font styles for all elements, e.g.: , (ISSN)
using System.Linq;
using System.Collections.Generic;
using SwissAcademic.Citavi;
using SwissAcademic.Citavi.Metadata;
using SwissAcademic.Collections;
using SwissAcademic.Drawing;
namespace SwissAcademic.Citavi.Citations
{
public class ComponentPartFilter
:
IComponentPartFilter
{
public IEnumerable<ITextUnit> GetTextUnits(ComponentPart componentPart, Template template, Citation citation, out bool handled)
{
//-------- START OPTIONS ----------------
var outputMode = OutputMode.ShowISSNOnlyOrSuppressJournalName; //append ISSN to journal name or replace the journal name with the ISSN or suppress it when there is no ISSN
var prefix = "ISSN "; //add a space e.g., or " ISSN: "
var prefixFontStyle = FontStyle.Neutral; //this is how you assign several styles at once: = FontStyle.Bold | FontStyle.Italic;
var useBrackets = BracketType.None; //replace None with either of the following: Parentheses, Brackes, CurlyBraces, Slashes, AngleBracktes
var bracketsFontStyle = FontStyle.Neutral;
var issnFontStyle = FontStyle.Neutral;
//-------- END OPTIONS ----------------
handled = false;
if (componentPart == null) return null;
if (template == null) return null;
if (citation == null || citation.Reference == null) return null;
var periodical = citation.Reference.Periodical;
if (periodical == null) return null;
var issnString = periodical.Issn;
bool hasISSN = !string.IsNullOrWhiteSpace(issnString);
var periodicalFieldElement = componentPart.GetFieldElements().FirstOrDefault<FieldElement>(item => item.PropertyId == ReferencePropertyId.Periodical);
if (periodicalFieldElement == null) return null;
if (!hasISSN && outputMode == OutputMode.ShowISSNOnlyOrSuppressJournalName)
{
handled = true;
return null; //suppresses the component altogether
}
List<LiteralElement> issnElements = new List<LiteralElement>();
#region Prefix
if (!string.IsNullOrEmpty(prefix))
{
var prefixLiteralElement = new LiteralElement(componentPart, prefix);
prefixLiteralElement.FontStyle = prefixFontStyle;
issnElements.Add(prefixLiteralElement);
}
#endregion Prefix
#region Opening Bracket
string openingBracket = string.Empty;
switch(useBrackets)
{
case BracketType.AngleBrackets:
openingBracket = "<";
break;
case BracketType.Brackets:
openingBracket = "[";
break;
case BracketType.CurlyBraces:
openingBracket = "{";
break;
case BracketType.Parentheses:
openingBracket = "(";
break;
case BracketType.Slashes:
openingBracket = "/";
break;
default:
break;
}
if (hasISSN && !string.IsNullOrEmpty(openingBracket))
{
var openingBracketLiteralElement = new LiteralElement(componentPart, openingBracket);
openingBracketLiteralElement.FontStyle = bracketsFontStyle;
issnElements.Add(openingBracketLiteralElement);
}
#endregion Opening Bracket
#region ISSN
if (hasISSN)
{
var issnLiteralElement = new LiteralElement(componentPart, issnString);
issnLiteralElement.FontStyle = issnFontStyle;
issnElements.Add(issnLiteralElement);
}
#endregion ISSN
#region Closing Bracket
string closingBracket = string.Empty;
switch(useBrackets)
{
case BracketType.AngleBrackets:
closingBracket = ">";
break;
case BracketType.Brackets:
closingBracket = "]";
break;
case BracketType.CurlyBraces:
closingBracket = "}";
break;
case BracketType.Parentheses:
closingBracket = ")";
break;
case BracketType.Slashes:
closingBracket = "/";
break;
default:
break;
}
if (hasISSN && !string.IsNullOrEmpty(closingBracket))
{
var closingBracketLiteralElement = new LiteralElement(componentPart, closingBracket);
closingBracketLiteralElement.FontStyle = bracketsFontStyle;
issnElements.Add(closingBracketLiteralElement);
}
#endregion Closing Bracket
if (hasISSN)
{
int index = componentPart.Elements.IndexOf(periodicalFieldElement);
if (outputMode == OutputMode.AppendISSNToJournalName)
{
if (index == -1) index = componentPart.Elements.Count - 1; //default: add at the end
componentPart.Elements.InsertElements(index + 1, issnElements);
}
else
{
if (index != -1)
{
componentPart.Elements.ReplaceItem(index, issnElements);
//always show LiteralElements
var literalElements = componentPart.Elements.OfType<LiteralElement>();
foreach (LiteralElement literalElement in literalElements)
{
literalElement.ApplyCondition = ElementApplyCondition.Always;
}
}
}
}
handled = false;
return null;
}
enum BracketType
{
None,
Parentheses,
Brackets,
CurlyBraces,
Slashes,
AngleBrackets
}
enum OutputMode
{
AppendISSNToJournalName,
ShowISSNOnlyOrJournalName,
ShowISSNOnlyOrSuppressJournalName
}
}
} | 27.864078 | 174 | 0.693206 | [
"MIT"
] | Citavi/C6-Citation-Style-Scripts | Components/CPE Periodical/CPE001 Add ISSN to journal name or replace with ISSN/CPE001_Add_ISSN_to_journal_name_or_replace_with_ISSN.cs | 5,740 | C# |
//
// Author: B4rtik (@b4rtik)
// Project: RedPeanut (https://github.com/b4rtik/RedPeanut)
// License: BSD 3-Clause
//
using System;
using System.Net;
using static RedPeanut.Models;
using static RedPeanut.Utility;
namespace RedPeanut
{
public static class Replacer
{
public static string ReplaceAgentProfile(string src, string serverkey, int targetframework, ListenerConfig config, bool sandboxcheck = false)
{
string source = src
.Replace("#SANDBOXCHECK#", sandboxcheck.ToString())
.Replace("#HOST#", config.GetHost())
.Replace("#PORT#", config.GetPort().ToString())
.Replace("#PARAM#", config.GetProfile().HttpPost.Param)
.Replace("#SERVERKEY#", RedPeanut.Program.GetServerKey())
.Replace("#PAGEGET#", ParseUri(config.GetProfile().HttpGet.ApiPath))
.Replace("#PAGEPOST#", ParseUri(config.GetProfile().HttpPost.ApiPath))
.Replace("#USERAGENT#", config.GetProfile().UserAgent)
.Replace("#PIPENAME#", "")
.Replace("#COVERED#", config.GetProfile().HtmlCovered.ToString().ToLower())
.Replace("#TARGETCLASS#", config.GetProfile().TargetClass)
.Replace("#SPAWN#", config.GetProfile().Spawn)
.Replace("#FRAMEWORK#", targetframework.ToString())
.Replace("#MANAGED#", config.GetProfile().InjectionManaged.ToString());
string headers = "";
foreach (HttpHeader h in config.GetProfile().HttpGet.Client.Headers)
{
try
{
if(!h.Name.Equals("Connection"))
{
int t = (int)Enum.Parse(typeof(HttpRequestHeader), h.Name.Replace("-", ""), true);
headers += string.Format("webHeaderCollection.Add(HttpRequestHeader.{0}, \"{1}\");" + Environment.NewLine, h.Name.Replace("-", ""), h.Value);
}
}
catch(Exception)
{
Console.WriteLine("[x] Error parsing header {0}", h.Name);
}
}
source = source
.Replace("#HEADERS#", headers);
return source;
}
public static string ReplaceAgentProfile(string src, string serverkey, int targetframework, ListenerPivotConfig config, bool sandboxcheck = false)
{
string source = src
.Replace("#SANDBOXCHECK#", sandboxcheck.ToString())
.Replace("#HOST#", config.GetHost())
.Replace("#PORT#", "0")
.Replace("#PARAM#", "")
.Replace("#SERVERKEY#", RedPeanut.Program.GetServerKey())
.Replace("#PAGEGET#", "")
.Replace("#PAGEPOST#", "")
.Replace("#USERAGENT#", "")
.Replace("#PIPENAME#", config.GetPipename())
.Replace("#COVERED#", "false")
.Replace("#TARGETCLASS#", "")
.Replace("#SPAWN#", config.GetProfile().Spawn)
.Replace("#FRAMEWORK#", targetframework.ToString())
.Replace("#MANAGED#", config.GetProfile().InjectionManaged.ToString());
source = source
.Replace("#HEADERS#", "");
return source;
}
public static string ReplaceAgentShooter(string src, string resourceurl, ListenerConfig config)
{
string source = src
.Replace("#HOST#", config.GetHost())
.Replace("#PORT#", config.GetPort().ToString())
.Replace("#RESURLCEURL#", resourceurl);
return source;
}
public static string ReplacePersAutorun(string src, string reghive, string url, string keyname, bool encoded)
{
string source = src
.Replace("#REGHIVE#", reghive)
.Replace("#URL#", url)
.Replace("#NAME#", keyname)
.Replace("#ENCODED#", encoded.ToString());
return source;
}
public static string ReplacePersWMI(string src, string eventname, string url, string processname, bool encoded)
{
string source = src
.Replace("#EVENTNAME#", eventname)
.Replace("#URL#", url)
.Replace("#PROCESSNAME#", processname)
.Replace("#ENCODED#", encoded.ToString());
return source;
}
public static string ReplacePersStartup(string src, string payload, string filename, bool encoded)
{
string source = src
.Replace("#URL#", payload)
.Replace("#FILENAME#", filename)
.Replace("#ENCODED#", encoded.ToString());
return source;
}
public static string ReplaceFileUpLoad(string src, string filesrc, string destpath, string destfilename, string username, string password, string domain)
{
string source = src
.Replace("#FILEBASE64#", filesrc)
.Replace("#FILENAME#", destfilename)
.Replace("#PATHDEST#", destpath)
.Replace("#USERNAME#", username)
.Replace("#PASSWORD#", password)
.Replace("#DOMAIN#", domain);
return source;
}
public static string ReplaceFileDownLoad(string src, string filesrc, string username, string password, string domain)
{
string source = src
.Replace("#FILESRC#", filesrc)
.Replace("#USERNAME#", username)
.Replace("#PASSWORD#", password)
.Replace("#DOMAIN#", domain);
return source;
}
public static string ReplaceHtmlProfile(string src, string targetclass, int payloadlen, string urlimg, int elements, int payloadindex, string[] images)
{
Random random = new Random();
string page = src;
string uripath = "/images/";
for(int i = 1; i <= elements; i++)
{
string pTargetclass = "#{targetclass" + i + "}";
string pRandomid = "#{randomid" + i + "}";
string pImagepath = "#{imagepath" + i + "}";
//Replace with random value except for payload index
if (i == payloadindex)
{
page = page.Replace(pTargetclass, targetclass)
.Replace(pRandomid, payloadlen.ToString())
.Replace(pImagepath, uripath + urlimg);
}
else
{
page = page.Replace(pTargetclass, "img-responsive")
.Replace(pRandomid, random.Next(1,payloadlen).ToString())
.Replace(pImagepath, uripath + images[i - 1]);
}
}
return page;
}
public static string ReplaceMigrate(string src, string shellcode, int pid)
{
string source = src
.Replace("#NUTCLR#", shellcode)
.Replace("#PID#", pid.ToString());
return source;
}
public static string ReplaceDonutLoader(string src, string compassembly, string type, string method)
{
string source = src
.Replace("#COMPRESSEDASSEMBLY#", compassembly)
.Replace("#TYPE#", type)
.Replace("#METHOD#", method);
return source;
}
private static string ParseUri(string[] apipath)
{
string s = "";
foreach (string str in apipath)
s = string.Format("\"{0}\",", str.TrimStart('/'));
return s.TrimEnd(',');
}
}
}
| 39.639024 | 165 | 0.503323 | [
"BSD-3-Clause"
] | FDlucifer/RedPeanut | Modules/Launchers/Replacer.cs | 8,128 | C# |
#if CSHARP_7_OR_LATER
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
using UniRx.Async.Internal;
using UnityEngine;
using UnityEngine.EventSystems;
namespace UniRx.Async.Triggers
{
[DisallowMultipleComponent]
public class AsyncUpdateSelectedTrigger : MonoBehaviour, IEventSystemHandler, IUpdateSelectedHandler
{
ReusablePromise<BaseEventData> onUpdateSelected;
void IUpdateSelectedHandler.OnUpdateSelected(BaseEventData eventData)
{
onUpdateSelected?.TryInvokeContinuation(eventData);
}
public UniTask<BaseEventData> OnUpdateSelectedAsync()
{
return new UniTask<BaseEventData>(onUpdateSelected ?? (onUpdateSelected = new ReusablePromise<BaseEventData>()));
}
}
}
#endif | 29.107143 | 125 | 0.736196 | [
"MIT"
] | ryo0ka/MinAR | Assets/Plugins/UniRx/Scripts/Async/Triggers/AsyncUpdateSelectedTrigger.cs | 817 | C# |
using System;
using System.Collections.Generic;
namespace AdventOfCode._6
{
public class Vertex : IEquatable<Vertex>
{
private readonly ISet<Vertex> _outEdges = new HashSet<Vertex>();
public Vertex(string id)
{
Id = id;
}
public string Id { get; }
public int Weight { get; private set; } = -1;
public bool IsWeighted() => Weight != -1;
public void AddOutEdge(Vertex v)
{
_outEdges.Add(v);
if (v.InEdge != null)
{
throw new InvalidOperationException("vertex already has a inEdge");
}
v.InEdge = this;
}
public IEnumerable<Vertex> GetOutEdges()
{
return _outEdges;
}
public Vertex InEdge { get; private set; } = null;
public void SetWeight(int weight)
{
if (weight < 0)
{
throw new ArgumentException("weight can't be negative: " + weight);
}
Weight = weight;
}
public bool Equals(Vertex other)
{
return string.Equals(Id, other.Id);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((Vertex)obj);
}
public override int GetHashCode()
{
return (Id != null ? Id.GetHashCode() : 0);
}
}
} | 23.573529 | 83 | 0.50655 | [
"MIT"
] | joao-r-reis/advent-of-code | csharp/AdventOfCode/6/Vertex.cs | 1,605 | C# |
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Text;
using System.Linq;
using System.Collections.Generic;
using Bioinformatics;
using Bioinformatics.Algorithms;
namespace BioTest
{
[TestClass]
public class MotifMediumTests
{
[TestMethod]
public void MotifMedium_Simple()
{
List<DnaStrand> strands = new List<DnaStrand>();
strands.Add(new DnaStrand("AAATTGACGCAT"));
strands.Add(new DnaStrand("GACGACCACGTT"));
strands.Add(new DnaStrand("CGTCAGCGCCTG"));
strands.Add(new DnaStrand("GCTGAGCACCGG"));
strands.Add(new DnaStrand("AGTTCGGGACAG"));
DnaStrand pattern = Motif.MedianString(strands, 3);
Assert.AreEqual("GAC", pattern.Dna);
}
[TestMethod]
public void MotifMedium_Test1()
{
List<DnaStrand> strands = new List<DnaStrand>();
strands.Add(new DnaStrand("ACGT"));
strands.Add(new DnaStrand("ACGT"));
strands.Add(new DnaStrand("ACGT"));
DnaStrand pattern = Motif.MedianString(strands, 3);
Assert.AreEqual("ACG", pattern.Dna);
}
[TestMethod]
public void MotifMedium_Test2()
{
List<DnaStrand> strands = new List<DnaStrand>();
strands.Add(new DnaStrand("ATA"));
strands.Add(new DnaStrand("ACA"));
strands.Add(new DnaStrand("AGA"));
strands.Add(new DnaStrand("AAT"));
strands.Add(new DnaStrand("AAC"));
DnaStrand pattern = Motif.MedianString(strands, 3);
Assert.AreEqual("AAA", pattern.Dna);
}
[TestMethod]
public void MotifMedium_Test3()
{
List<DnaStrand> strands = new List<DnaStrand>();
strands.Add(new DnaStrand("AAG"));
strands.Add(new DnaStrand("AAT"));
DnaStrand pattern = Motif.MedianString(strands, 3);
Assert.AreEqual("AAT", pattern.Dna);
}
[TestMethod]
public void MotifMedium_Test4()
{
List<DnaStrand> strands = new List<DnaStrand>();
strands.Add(new DnaStrand("TGATGATAACGTGACGGGACTCAGCGGCGATGAAGGATGAGT"));
strands.Add(new DnaStrand("CAGCGACAGACAATTTCAATAATATCCGCGGTAAGCGGCGTA"));
strands.Add(new DnaStrand("TGCAGAGGTTGGTAACGCCGGCGACTCGGAGAGCTTTTCGCT"));
strands.Add(new DnaStrand("TTTGTCATGAACTCAGATACCATAGAGCACCGGCGAGACTCA"));
strands.Add(new DnaStrand("ACTGGGACTTCACATTAGGTTGAACCGCGAGCCAGGTGGGTG"));
strands.Add(new DnaStrand("TTGCGGACGGGATACTCAATAACTAAGGTAGTTCAGCTGCGA"));
strands.Add(new DnaStrand("TGGGAGGACACACATTTTCTTACCTCTTCCCAGCGAGATGGC"));
strands.Add(new DnaStrand("GAAAAAACCTATAAAGTCCACTCTTTGCGGCGGCGAGCCATA"));
strands.Add(new DnaStrand("CCACGTCCGTTACTCCGTCGCCGTCAGCGATAATGGGATGAG"));
strands.Add(new DnaStrand("CCAAAGCTGCGAAATAACCATACTCTGCTCAGGAGCCCGATG"));
DnaStrand pattern = Motif.MedianString(strands, 6);
Assert.AreEqual("CGGCGA", pattern.Dna);
}
[TestMethod]
public void MotifMedium_Test5()
{
List<DnaStrand> strands = new List<DnaStrand>();
strands.Add(new DnaStrand("TAAGCGTTTGTGCGTAGCGTATAAGTCTAACCAACTTGTTGA"));
strands.Add(new DnaStrand("AGGTTCACGACTTATCTGTACGCGGACCGTCGCTGAATCACA"));
strands.Add(new DnaStrand("CTAAATATACTTTCAGTCCGGGTATATGCGCAGTGTTCGAAA"));
strands.Add(new DnaStrand("CTTATCAGAGAGGGCTTGCTAGTCCCTCAATGTTGATATGCG"));
strands.Add(new DnaStrand("TACGCGTTTCAGCTGCACTCAAATAGATTGATAAACGCGTTA"));
strands.Add(new DnaStrand("AGTGCGGTACCGATACATTTCGCTCTTTTGCGGGCTTACGCG"));
strands.Add(new DnaStrand("TACCTTATGGCATACGCGTGGCGTACAAGCTCCTTCGCCGTC"));
strands.Add(new DnaStrand("CATAAGGATCTAGGCTGGTAGGCGTTTTTAGACCCCTGTTAT"));
strands.Add(new DnaStrand("ATGGGAGCCCTCCATCGTGCAGCCTACGCGCGGTTATTCCCT"));
strands.Add(new DnaStrand("TATGCGTGTCCGGGTCGTCTAACGGGTTCGTCTCTCGTCCGT"));
DnaStrand pattern = Motif.MedianString(strands, 6);
Assert.AreEqual("TACGCG", pattern.Dna);
}
}
}
| 37.172414 | 85 | 0.642857 | [
"Unlicense",
"MIT"
] | andweller/bioinformatics | BioTest/Motif/MotifMediumTests.cs | 4,314 | C# |
using BinarySerializer;
namespace R1Engine
{
public class LUDI_Video : LUDI_BaseBlock {
public uint Width { get; set; }
public uint Height { get; set; }
public uint Speed { get; set; }
public uint FrameCount { get; set; }
public uint[] FrameOffsets { get; set; }
public BGR565Color[][] FrameDataPPC { get; set; }
public override void SerializeBlock(SerializerObject s) {
Width = s.Serialize<uint>(Width, name: nameof(Width));
Height = s.Serialize<uint>(Height, name: nameof(Height));
Speed = s.Serialize<uint>(Speed, name: nameof(Speed));
FrameCount = s.Serialize<uint>(FrameCount, name: nameof(FrameCount));
FrameOffsets = s.SerializeArray<uint>(FrameOffsets, FrameCount, name: nameof(FrameOffsets));
if (s.GetR1Settings().EngineVersion == EngineVersion.GBC_R1_PocketPC) {
if (FrameDataPPC == null) FrameDataPPC = new BGR565Color[FrameCount][];
for (int i = 0; i < FrameDataPPC.Length; i++) {
uint decompressedSize = Width * Height * 2;
long nextOff = i < FrameDataPPC.Length - 1 ? FrameOffsets[i + 1] : BlockSize;
long compressedSize = nextOff - FrameOffsets[i];
s.DoAt(BlockStartPointer + FrameOffsets[i], () => {
s.DoEncoded(new Lzo1xEncoder((uint)compressedSize, decompressedSize), () => {
FrameDataPPC[i] = s.SerializeObjectArray<BGR565Color>(FrameDataPPC[i], Width * Height, name: $"{nameof(FrameDataPPC)}[{i}]");
});
});
}
}
}
}
} | 50.617647 | 153 | 0.565369 | [
"MIT"
] | Adsolution/Ray1Map | Assets/Scripts/DataTypes/GBC/LUDI/LUDI_Video.cs | 1,723 | C# |
using Obsidian.Domain;
using Obsidian.Domain.Repositories;
using Obsidian.Persistence.Repositories;
using System;
using System.Threading.Tasks;
using Xunit;
namespace Obsidian.Persistence.Test.Repositories
{
public class UserMongoRepositoryTest : MongoRepositoryTest<User>
{
protected override User CreateAggregateWithEmptyId() => new User();
protected override IRepository<User> CreateRepository() => new UserMongoRepository(Database);
protected override User CreateAggregate() => User.Create(Guid.NewGuid(), Guid.NewGuid().ToString());
private IUserRepository UserRepo => _repository as IUserRepository;
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData(" ")]
public async Task FindByUserName_Fail_When_UserNameIsNullOrWhiteSpace(string value)
{
await Assert.ThrowsAsync<ArgumentNullException>("userName", async () => await UserRepo.FindByUserNameAsync(value));
}
[Fact]
public async Task FindByUserName_Test()
{
var user = CreateAggregate();
var userName = user.UserName;
await UserRepo.AddAsync(user);
var found = await UserRepo.FindByUserNameAsync(userName);
Assert.Equal(user.Id, found.Id);
}
[Fact]
public async override Task Save_Test() => await Save_PasswordHash();
[Fact]
public async Task Save_PasswordHash()
{
var user = CreateAggregate();
var id = user.Id;
const string password = "test";
user.SetPassword(password);
await _repository.AddAsync(user);
var found = await _repository.FindByIdAsync(id);
Assert.True(found.VaildatePassword(password));
}
}
} | 33.072727 | 127 | 0.642111 | [
"Apache-2.0"
] | TheCashiers/Obsidian | test/Obsidian.Persistence.Test/Repositories/UserMongoRepositoryTest.cs | 1,821 | C# |
using System;
namespace AkkaPrismUnityDemo.Modules.Stocks.ActorModels.Messages {
internal sealed class RemoveChartSeriesMessage {
/// <summary>
/// The constructor.
/// </summary>
/// <param name="stockSymbol"></param>
public RemoveChartSeriesMessage( string stockSymbol ) {
this.StockSymbol = stockSymbol;
}
/// <summary>
/// The stock symbol.
/// </summary>
public string StockSymbol { get; }
}
}
| 18.73913 | 66 | 0.679814 | [
"Apache-2.0"
] | forki/AkkaPrismUnityDemo | AkkaPrismUnityDemo.Modules.Stocks/ActorModels/Messages/RemoveChartSeriesMessage.cs | 433 | C# |
using System.Diagnostics.CodeAnalysis;
using System.Web.Mvc.Async;
namespace System.Web.Mvc
{
[SuppressMessage("Microsoft.Performance", "CA1813:AvoidUnsealedAttributes", Justification = "Unsealed so that subclassed types can set properties in the default constructor.")]
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public class AsyncTimeoutAttribute : ActionFilterAttribute
{
// duration is specified in milliseconds
public AsyncTimeoutAttribute(int duration)
{
if (duration < -1)
{
throw Error.AsyncCommon_InvalidTimeout("duration");
}
Duration = duration;
}
public int Duration { get; private set; }
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext == null)
{
throw new ArgumentNullException("filterContext");
}
IAsyncManagerContainer container = filterContext.Controller as IAsyncManagerContainer;
if (container == null)
{
throw Error.AsyncCommon_ControllerMustImplementIAsyncManagerContainer(filterContext.Controller.GetType());
}
container.AsyncManager.Timeout = Duration;
base.OnActionExecuting(filterContext);
}
}
}
| 34.071429 | 180 | 0.6471 | [
"Apache-2.0"
] | douchedetector/mvc-razor | src/System.Web.Mvc/AsyncTimeoutAttribute.cs | 1,433 | C# |
using System;
using System.Diagnostics;
using System.IO;
using System.Numerics;
namespace _18_CornellBoxHittableLight
{
public class Program
{
public static Diffuse_light lightMaterial;
public static Hitable_List Cornell_box(out Camera cam, float aspect)
{
Hitable_List objects = new Hitable_List();
var red = new Lambertian(new Solid_Color(.65f, .05f, .05f));
var white = new Lambertian(new Solid_Color(.73f, .73f, .73f));
var green = new Lambertian(new Solid_Color(.12f, .45f, .15f));
lightMaterial = new Diffuse_light(new Solid_Color(15, 15, 15));
objects.Add(new Flip_face(new YZ_rect(0, 555, 0, 555, 555, green)));
objects.Add(new YZ_rect(0, 555, 0, 555, 0, red));
objects.Add(new Flip_face(new XZ_rect(213, 343, 227, 332, 554, lightMaterial)));
objects.Add(new Flip_face(new XZ_rect(0, 555, 0, 555, 0, white)));
objects.Add(new XZ_rect(0, 555, 0, 555, 555, white));
objects.Add(new Flip_face(new XY_rect(0, 555, 0, 555, 555, white)));
HitTable box1 = new Box(new Vector3(0, 0, 0), new Vector3(165, 330, 165), white);
box1 = new Rotate_y(box1, 15);
box1 = new Translate(box1, new Vector3(265, 0, 295));
objects.Add(box1);
HitTable box2 = new Box(new Vector3(0, 0, 0), new Vector3(165, 165, 165), white);
box2 = new Rotate_y(box2, -18);
box2 = new Translate(box2, new Vector3(130, 0, 65));
objects.Add(box2);
Vector3 lookfrom = new Vector3(278, 278, -800);
Vector3 lookat = new Vector3(278, 278, 0);
Vector3 vup = new Vector3(0, 1, 0);
float dist_to_focus = 10.0f;
float aperture = 0.0f;
float vfov = 40.0f;
float t0 = 0.0f;
float t1 = 1.0f;
cam = new Camera(lookfrom, lookat, vup, vfov, aspect, aperture, dist_to_focus, t0, t1);
return objects;
}
static Vector3 Ray_color(Ray r, Vector3 background, HitTable world, int depth)
{
Hit_Record rec = default;
// If we've exceeded the ray bounce limit, no more light is gathered.
if (depth <= 0)
return Vector3.Zero;
// If the ray hits nothing, return the background color.
if (!world.Hit(r, 0.001f, Helpers.Infinity, ref rec))
return background;
Ray scattered;
Vector3 emitted = rec.Mat_ptr.Emitted(r, rec, rec.U, rec.V, rec.P);
float pdf_val;
Vector3 albedo;
if (!rec.Mat_ptr.Scatter(r, rec, out albedo, out scattered, out pdf_val))
return emitted;
HitTable light_shape = new XZ_rect(213, 343, 227, 332, 554, lightMaterial);
Hittable_pdf p = new Hittable_pdf(light_shape, rec.P);
scattered = new Ray(rec.P, p.Generate(), r.Time);
pdf_val = p.Value(scattered.Direction);
return emitted + albedo * rec.Mat_ptr.Scattering_pdf(r, rec, scattered) * Ray_color(scattered, background, world, depth - 1) / pdf_val;
}
static void Write_color(StreamWriter file, Vector3 pixel_color, int samples_per_pixel)
{
var r = pixel_color.X;
var g = pixel_color.Y;
var b = pixel_color.Z;
// Divide the color total by the number of samples.
float scale = 1.0f / samples_per_pixel;
r = (float)Math.Sqrt(scale * r);
g = (float)Math.Sqrt(scale * g);
b = (float)Math.Sqrt(scale * b);
// Write the translated [0,255] value of each color component.
file.WriteLine($"{(int)(256 * Math.Clamp(r, 0.0, 0.999))} {(int)(256 * Math.Clamp(g, 0.0, 0.999))} {(int)(256 * Math.Clamp(b, 0.0, 0.999))}");
}
static void Main(string[] args)
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
int image_width = 500;
int image_height = image_width;
float aspect_ratio = (float)image_width / image_height;
int samples_per_pixel = 10;
int max_depth = 50;
string filePath = "image.ppm";
using (var file = new StreamWriter(filePath))
{
file.WriteLine($"P3\n{image_width} {image_height}\n255");
float viewport_height = 2.0f;
float viewport_width = aspect_ratio * viewport_height;
float focal_length = 1.0f;
var origin = Vector3.Zero;
var horizontal = new Vector3(viewport_width, 0, 0);
var vertical = new Vector3(0, viewport_height, 0);
var lower_left_corner = origin - horizontal / 2 - vertical / 2 - new Vector3(0, 0, focal_length);
Hitable_List world = Cornell_box(out Camera cam, aspect_ratio);
Vector3 background = new Vector3(0.0f, 0.0f, 0.0f);
for (int j = image_height - 1; j >= 0; --j)
{
Console.WriteLine($"\rScanlines remaining: {j}");
for (int i = 0; i < image_width; ++i)
{
Vector3 pixel_color = Vector3.Zero;
for (int s = 0; s < samples_per_pixel; ++s)
{
float u = (float)(i + Helpers.random.NextDouble()) / (image_width - 1);
float v = (float)(j + Helpers.random.NextDouble()) / (image_height - 1);
Ray r = cam.Get_Ray(u, v);
pixel_color += Ray_color(r, background, world, max_depth);
}
Write_color(file, pixel_color, samples_per_pixel);
}
}
Console.WriteLine("Done.");
}
stopwatch.Stop();
TimeSpan ts = stopwatch.Elapsed;
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
ts.Hours, ts.Minutes, ts.Seconds,
ts.Milliseconds);
Console.WriteLine($"Time: {elapsedTime} hh:mm:ss:fff");
}
}
} | 42.388158 | 154 | 0.525842 | [
"MIT"
] | Jorgemagic/RaytracingTheRestOfYourLife | 18-CornellBoxHittableLight/Program.cs | 6,445 | C# |
using System;
using System.Diagnostics;
using System.Threading.Tasks;
namespace syp.biz.Core.Extensions
{
/// <summary>
/// A collection of diagnostics extension methods
/// </summary>
public static class DiagnosticsExtensions
{
/// <summary>
/// Measures the duration it takes to perform <paramref name="action"/>.
/// </summary>
/// <param name="stopwatch">The <see cref="Stopwatch"/> to use.</param>
/// <param name="action">The <see cref="Action"/> to measure the duration of.</param>
/// <returns>A <see cref="TimeSpan"/> representing the duration the action took.</returns>
public static TimeSpan Measure(this Stopwatch stopwatch, Action action)
{
try
{
stopwatch.Start();
action();
}
finally
{
stopwatch.Stop();
}
return stopwatch.Elapsed;
}
/// <summary>
/// Asynchronously measures the duration it takes to perform <paramref name="asyncAction"/>.
/// </summary>
/// <param name="stopwatch">The <see cref="Stopwatch"/> to use.</param>
/// <param name="asyncAction">The asynchronous task to measure the duration of.</param>
/// <returns>A <see cref="TimeSpan"/> representing the duration the action took.</returns>
public static async Task<TimeSpan> Measure(this Stopwatch stopwatch, Func<Task> asyncAction)
{
try
{
stopwatch.Start();
await asyncAction();
}
finally
{
stopwatch.Stop();
}
return stopwatch.Elapsed;
}
/// <summary>
/// Measures the duration it takes to perform <paramref name="action"/>.
/// </summary>
/// <param name="stopwatch">The <see cref="Stopwatch"/> to use.</param>
/// <param name="action">The <see cref="Action"/> to measure the duration of.</param>
/// <param name="duration">A <see cref="TimeSpan"/> representing the duration the action took.</param>
public static void Measure(this Stopwatch stopwatch, Action action, out TimeSpan duration)
{
try
{
stopwatch.Start();
action();
stopwatch.Stop();
duration = stopwatch.Elapsed;
}
catch
{
stopwatch.Stop();
duration = stopwatch.Elapsed;
throw;
}
}
/// <summary>
/// Measures the duration it takes to perform <paramref name="action"/>.
/// </summary>
/// <param name="stopwatch">The <see cref="Stopwatch"/> to use.</param>
/// <param name="action">The <see cref="Action"/> to measure the duration of.</param>
/// <param name="onDone">A callback delegate to call with the <see cref="TimeSpan"/> duration the action took.</param>
public static void Measure(this Stopwatch stopwatch, Action action, Action<TimeSpan> onDone)
{
stopwatch.Measure(action, out var duration);
onDone(duration);
}
/// <summary>
/// Measures the duration it takes to perform <paramref name="func"/>.
/// </summary>
/// <typeparam name="T">The return type of <paramref name="func"/>.</typeparam>
/// <param name="stopwatch">The <see cref="Stopwatch"/> to use.</param>
/// <param name="func">The <see cref="Func{T}"/> to measure the duration of.</param>
/// <param name="duration">A <see cref="TimeSpan"/> representing the duration the action took.</param>
/// <returns>The result of <paramref name="func"/>.</returns>
public static T Measure<T>(this Stopwatch stopwatch, Func<T> func, out TimeSpan duration)
{
try
{
stopwatch.Start();
var rslt = func();
stopwatch.Stop();
duration = stopwatch.Elapsed;
return rslt;
}
catch
{
stopwatch.Stop();
duration = stopwatch.Elapsed;
throw;
}
}
/// <summary>
/// Measures the duration it takes to perform <paramref name="func"/>.
/// </summary>
/// <typeparam name="T">The return type of <paramref name="func"/>.</typeparam>
/// <param name="stopwatch">The <see cref="Stopwatch"/> to use.</param>
/// <param name="func">The <see cref="Func{T}"/> to measure the duration of.</param>
/// <param name="onDone">A callback delegate to call with the <see cref="TimeSpan"/> duration the action took.</param>
/// <returns>The result of <paramref name="func"/>.</returns>
public static T Measure<T>(this Stopwatch stopwatch, Func<T> func, Action<TimeSpan> onDone)
{
var rslt = stopwatch.Measure(func, out var duration);
onDone(duration);
return rslt;
}
}
}
| 39.282443 | 126 | 0.54178 | [
"Apache-2.0"
] | sypbiz/core | syp.biz.Core/Extensions/DiagnosticsExtensions.cs | 5,148 | 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.sgw.Transform;
using Aliyun.Acs.sgw.Transform.V20180511;
namespace Aliyun.Acs.sgw.Model.V20180511
{
public class OperateGatewayRequest : RpcAcsRequest<OperateGatewayResponse>
{
public OperateGatewayRequest()
: base("sgw", "2018-05-11", "OperateGateway", "hcs_sgw", "openAPI")
{
if (this.GetType().GetProperty("ProductEndpointMap") != null && this.GetType().GetProperty("ProductEndpointType") != null)
{
this.GetType().GetProperty("ProductEndpointMap").SetValue(this, Endpoint.endpointMap, null);
this.GetType().GetProperty("ProductEndpointType").SetValue(this, Endpoint.endpointRegionalType, null);
}
Method = MethodType.POST;
}
private string operateAction;
private string _params;
private string securityToken;
private string gatewayId;
public string OperateAction
{
get
{
return operateAction;
}
set
{
operateAction = value;
DictionaryUtil.Add(QueryParameters, "OperateAction", value);
}
}
public string _Params
{
get
{
return _params;
}
set
{
_params = value;
DictionaryUtil.Add(QueryParameters, "Params", value);
}
}
public string SecurityToken
{
get
{
return securityToken;
}
set
{
securityToken = value;
DictionaryUtil.Add(QueryParameters, "SecurityToken", value);
}
}
public string GatewayId
{
get
{
return gatewayId;
}
set
{
gatewayId = value;
DictionaryUtil.Add(QueryParameters, "GatewayId", value);
}
}
public override OperateGatewayResponse GetResponse(UnmarshallerContext unmarshallerContext)
{
return OperateGatewayResponseUnmarshaller.Unmarshall(unmarshallerContext);
}
}
}
| 26.110092 | 134 | 0.670766 | [
"Apache-2.0"
] | AxiosCros/aliyun-openapi-net-sdk | aliyun-net-sdk-sgw/Sgw/Model/V20180511/OperateGatewayRequest.cs | 2,846 | C# |
using Agathas.Storefront.Controllers.ActionArguments;
using Agathas.Storefront.Infrastructure.Authentication;
using Agathas.Storefront.Infrastructure.CookieStorage;
using Agathas.Storefront.Infrastructure.Domain.Events;
using Agathas.Storefront.Infrastructure.Logging;
using Agathas.Storefront.Infrastructure.Payments;
using Agathas.Storefront.Infrastructure.UnitOfWork;
using Agathas.Storefront.Infrastructure.Configuration;
using Agathas.Storefront.Model.Basket;
using Agathas.Storefront.Model.Categories;
using Agathas.Storefront.Model.Customers;
using Agathas.Storefront.Model.Orders;
using Agathas.Storefront.Model.Orders.Events;
using Agathas.Storefront.Model.Products;
using Agathas.Storefront.Model.Shipping;
using Agathas.Storefront.Services.DomainEventHandlers;
using Agathas.Storefront.Services.Implementations;
using Agathas.Storefront.Services.Interfaces;
using StructureMap;
using StructureMap.Configuration.DSL;
using Agathas.Storefront.Infrastructure.Email;
namespace Agathas.Storefront.UI.Web.MVC
{
public class BootStrapper
{
public static void ConfigureDependencies()
{
ObjectFactory.Initialize(x =>
{
x.AddRegistry<ControllerRegistry>();
});
}
public class ControllerRegistry : Registry
{
public ControllerRegistry()
{
// Repositories
ForRequestedType<IOrderRepository>().TheDefault.Is.OfConcreteType
<Repository.NHibernate.Repositories.OrderRepository>();
ForRequestedType<ICustomerRepository>().TheDefault.Is.OfConcreteType
<Repository.NHibernate.Repositories.CustomerRepository>();
ForRequestedType<IBasketRepository>().TheDefault.Is.OfConcreteType
<Repository.NHibernate.Repositories.BasketRepository>();
ForRequestedType<IDeliveryOptionRepository>().TheDefault.Is.OfConcreteType
<Repository.NHibernate.Repositories.DeliveryOptionRepository>();
ForRequestedType<ICategoryRepository>().TheDefault.Is.OfConcreteType
<Repository.NHibernate.Repositories.CategoryRepository>();
ForRequestedType<IProductTitleRepository>().TheDefault.Is.OfConcreteType
<Repository.NHibernate.Repositories.ProductTitleRepository>();
ForRequestedType<IProductRepository>().TheDefault.Is.OfConcreteType
<Repository.NHibernate.Repositories.ProductRepository>();
ForRequestedType<IUnitOfWork>().TheDefault.Is.OfConcreteType
<Repository.NHibernate.NHUnitOfWork>();
// Order Service
ForRequestedType<IOrderService>().TheDefault.Is.OfConcreteType
<OrderService>();
// Payment
ForRequestedType<IPaymentService>().TheDefault.Is.OfConcreteType
<PayPalPaymentService>();
// Handlers for Domain Events
ForRequestedType<IDomainEventHandlerFactory>().TheDefault
.Is.OfConcreteType<StructureMapDomainEventHandlerFactory>();
ForRequestedType<IDomainEventHandler<OrderSubmittedEvent>>()
.AddConcreteType<OrderSubmittedHandler>();
// Product Catalogue
ForRequestedType<IProductCatalogService>().TheDefault.Is.OfConcreteType
<ProductCatalogService>();
// Product Catalogue & Category Service with Caching Layer Registration
this.InstanceOf<IProductCatalogService>().Is.OfConcreteType<ProductCatalogService>()
.WithName("RealProductCatalogueService");
// Uncomment the line below to use the product service caching layer
//ForRequestedType<IProductCatalogueService>().TheDefault.Is.OfConcreteType<CachedProductCatalogueService>()
// .CtorDependency<IProductCatalogueService>().Is(x => x.TheInstanceNamed("RealProductCatalogueService"));
ForRequestedType<IBasketService>().TheDefault.Is.OfConcreteType
<BasketService>();
ForRequestedType<ICookieStorageService>().TheDefault.Is.OfConcreteType
<CookieStorageService>();
// Application Settings
ForRequestedType<IApplicationSettings>().TheDefault.Is.OfConcreteType
<WebConfigApplicationSettings>();
// Logger
ForRequestedType<ILogger>().TheDefault.Is.OfConcreteType
<Log4NetAdapter>();
// Email Service
ForRequestedType<IEmailService>().TheDefault.Is.OfConcreteType
<TextLoggingEmailService>();
ForRequestedType<ICustomerService>().TheDefault.Is.OfConcreteType
<CustomerService>();
// Authentication
ForRequestedType<IExternalAuthenticationService>().TheDefault.Is
.OfConcreteType<JanrainAuthenticationService>();
ForRequestedType<IFormsAuthentication>().TheDefault.Is
.OfConcreteType<AspFormsAuthentication>();
ForRequestedType<ILocalAuthenticationService>().TheDefault.Is
.OfConcreteType<AspMembershipAuthentication>();
// Controller Helpers
ForRequestedType<IActionArguments>().TheDefault.Is.OfConcreteType
<HttpRequestActionArguments>();
}
}
}
}
| 48.414634 | 126 | 0.62351 | [
"MIT"
] | codeyu/ASPNETCore-Design-Patterns | ASPPatterns.allcode/ASPPatterns14/Agathas.Storefront - VS 2010/Agathas.Storefront.UI.Web.MVC/BootStrapper.cs | 5,957 | C# |
using Lucene.Net.Store;
using Lucene.Net.Util;
using System;
using System.Diagnostics;
using System.IO;
namespace Lucene.Net.Codecs.Bloom
{
/*
* 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.
*/
/// <summary>
/// A class used to represent a set of many, potentially large, values (e.g. many
/// long strings such as URLs), using a significantly smaller amount of memory.
/// <para/>
/// The set is "lossy" in that it cannot definitively state that is does contain
/// a value but it <em>can</em> definitively say if a value is <em>not</em> in
/// the set. It can therefore be used as a Bloom Filter.
/// <para/>
/// Another application of the set is that it can be used to perform fuzzy counting because
/// it can estimate reasonably accurately how many unique values are contained in the set.
/// <para/>
/// This class is NOT threadsafe.
/// <para/>
/// Internally a Bitset is used to record values and once a client has finished recording
/// a stream of values the <see cref="Downsize(float)"/> method can be used to create a suitably smaller set that
/// is sized appropriately for the number of values recorded and desired saturation levels.
/// <para/>
/// @lucene.experimental
/// </summary>
public class FuzzySet
{
public static readonly int VERSION_SPI = 1; // HashFunction used to be loaded through a SPI
public static readonly int VERSION_START = VERSION_SPI;
public static readonly int VERSION_CURRENT = 2;
public static HashFunction HashFunctionForVersion(int version)
{
if (version < VERSION_START)
throw new ArgumentException("Version " + version + " is too old, expected at least " +
VERSION_START);
if (version > VERSION_CURRENT)
throw new ArgumentException("Version " + version + " is too new, expected at most " +
VERSION_CURRENT);
return MurmurHash2.INSTANCE;
}
/// <remarks>
/// Result from <see cref="FuzzySet.Contains(BytesRef)"/>:
/// can never return definitively YES (always MAYBE),
/// but can sometimes definitely return NO.
/// </remarks>
public enum ContainsResult
{
MAYBE,
NO
};
private readonly HashFunction _hashFunction;
private readonly FixedBitSet _filter;
private readonly int _bloomSize;
//The sizes of BitSet used are all numbers that, when expressed in binary form,
//are all ones. This is to enable fast downsizing from one bitset to another
//by simply ANDing each set index in one bitset with the size of the target bitset
// - this provides a fast modulo of the number. Values previously accumulated in
// a large bitset and then mapped to a smaller set can be looked up using a single
// AND operation of the query term's hash rather than needing to perform a 2-step
// translation of the query term that mirrors the stored content's reprojections.
private static int[] _usableBitSetSizes = LoadUsableBitSetSizes();
private static int[] LoadUsableBitSetSizes() // LUCENENET: Avoid static constructors (see https://github.com/apache/lucenenet/pull/224#issuecomment-469284006)
{
var usableBitSetSizes = new int[30];
const int mask = 1;
var size = mask;
for (var i = 0; i < usableBitSetSizes.Length; i++)
{
size = (size << 1) | mask;
usableBitSetSizes[i] = size;
}
return usableBitSetSizes;
}
/// <summary>
/// Rounds down required <paramref name="maxNumberOfBits"/> to the nearest number that is made up
/// of all ones as a binary number.
/// Use this method where controlling memory use is paramount.
/// </summary>
public static int GetNearestSetSize(int maxNumberOfBits)
{
int result = _usableBitSetSizes[0];
for (int i = 0; i < _usableBitSetSizes.Length; i++)
{
if (_usableBitSetSizes[i] <= maxNumberOfBits)
{
result = _usableBitSetSizes[i];
}
}
return result;
}
/// <summary>
/// Use this method to choose a set size where accuracy (low content saturation) is more important
/// than deciding how much memory to throw at the problem.
/// </summary>
/// <param name="maxNumberOfValuesExpected"></param>
/// <param name="desiredSaturation">A number between 0 and 1 expressing the % of bits set once all values have been recorded.</param>
/// <returns>The size of the set nearest to the required size.</returns>
public static int GetNearestSetSize(int maxNumberOfValuesExpected,
float desiredSaturation)
{
// Iterate around the various scales of bitset from smallest to largest looking for the first that
// satisfies value volumes at the chosen saturation level
for (int i = 0; i < _usableBitSetSizes.Length; i++)
{
int numSetBitsAtDesiredSaturation = (int)(_usableBitSetSizes[i] * desiredSaturation);
int estimatedNumUniqueValues = GetEstimatedNumberUniqueValuesAllowingForCollisions(
_usableBitSetSizes[i], numSetBitsAtDesiredSaturation);
if (estimatedNumUniqueValues > maxNumberOfValuesExpected)
{
return _usableBitSetSizes[i];
}
}
return -1;
}
public static FuzzySet CreateSetBasedOnMaxMemory(int maxNumBytes)
{
var setSize = GetNearestSetSize(maxNumBytes);
return new FuzzySet(new FixedBitSet(setSize + 1), setSize, HashFunctionForVersion(VERSION_CURRENT));
}
public static FuzzySet CreateSetBasedOnQuality(int maxNumUniqueValues, float desiredMaxSaturation)
{
var setSize = GetNearestSetSize(maxNumUniqueValues, desiredMaxSaturation);
return new FuzzySet(new FixedBitSet(setSize + 1), setSize, HashFunctionForVersion(VERSION_CURRENT));
}
private FuzzySet(FixedBitSet filter, int bloomSize, HashFunction hashFunction)
{
_filter = filter;
_bloomSize = bloomSize;
_hashFunction = hashFunction;
}
/// <summary>
/// The main method required for a Bloom filter which, given a value determines set membership.
/// Unlike a conventional set, the fuzzy set returns <see cref="ContainsResult.NO"/> or
/// <see cref="ContainsResult.MAYBE"/> rather than <c>true</c> or <c>false</c>.
/// </summary>
/// <returns><see cref="ContainsResult.NO"/> or <see cref="ContainsResult.MAYBE"/></returns>
public virtual ContainsResult Contains(BytesRef value)
{
var hash = _hashFunction.Hash(value);
if (hash < 0)
{
hash = hash*-1;
}
return MayContainValue(hash);
}
/// <summary>
/// Serializes the data set to file using the following format:
/// <list type="bullet">
/// <item><description>FuzzySet -->FuzzySetVersion,HashFunctionName,BloomSize,
/// NumBitSetWords,BitSetWord<sup>NumBitSetWords</sup></description></item>
/// <item><description>HashFunctionName --> String (<see cref="DataOutput.WriteString(string)"/>) The
/// name of a ServiceProvider registered <see cref="HashFunction"/></description></item>
/// <item><description>FuzzySetVersion --> Uint32 (<see cref="DataOutput.WriteInt32(int)"/>) The version number of the <see cref="FuzzySet"/> class</description></item>
/// <item><description>BloomSize --> Uint32 (<see cref="DataOutput.WriteInt32(int)"/>) The modulo value used
/// to project hashes into the field's Bitset</description></item>
/// <item><description>NumBitSetWords --> Uint32 (<see cref="DataOutput.WriteInt32(int)"/>) The number of
/// longs (as returned from <see cref="FixedBitSet.GetBits()"/>)</description></item>
/// <item><description>BitSetWord --> Long (<see cref="DataOutput.WriteInt64(long)"/>) A long from the array
/// returned by <see cref="FixedBitSet.GetBits()"/></description></item>
/// </list>
/// </summary>
/// <param name="output">Data output stream.</param>
/// <exception cref="IOException">If there is a low-level I/O error.</exception>
public virtual void Serialize(DataOutput output)
{
output.WriteInt32(VERSION_CURRENT);
output.WriteInt32(_bloomSize);
var bits = _filter.GetBits();
output.WriteInt32(bits.Length);
foreach (var t in bits)
{
// Can't used VLong encoding because cant cope with negative numbers
// output by FixedBitSet
output.WriteInt64(t);
}
}
public static FuzzySet Deserialize(DataInput input)
{
var version = input.ReadInt32();
if (version == VERSION_SPI)
input.ReadString();
var hashFunction = HashFunctionForVersion(version);
var bloomSize = input.ReadInt32();
var numLongs = input.ReadInt32();
var longs = new long[numLongs];
for (var i = 0; i < numLongs; i++)
{
longs[i] = input.ReadInt64();
}
var bits = new FixedBitSet(longs, bloomSize + 1);
return new FuzzySet(bits, bloomSize, hashFunction);
}
private ContainsResult MayContainValue(int positiveHash)
{
Debug.Assert((positiveHash >= 0));
// Bloom sizes are always base 2 and so can be ANDed for a fast modulo
var pos = positiveHash & _bloomSize;
return _filter.Get(pos) ? ContainsResult.MAYBE : ContainsResult.NO;
}
/// <summary>
/// Records a value in the set. The referenced bytes are hashed and then modulo n'd where n is the
/// chosen size of the internal bitset.
/// </summary>
/// <param name="value">The Key value to be hashed.</param>
/// <exception cref="IOException">If there is a low-level I/O error.</exception>
public virtual void AddValue(BytesRef value)
{
var hash = _hashFunction.Hash(value);
if (hash < 0)
{
hash = hash*-1;
}
// Bitmasking using bloomSize is effectively a modulo operation.
var bloomPos = hash & _bloomSize;
_filter.Set(bloomPos);
}
/// <param name="targetMaxSaturation">
/// A number between 0 and 1 describing the % of bits that would ideally be set in the result.
/// Lower values have better accuracy but require more space.
/// </param>
/// <return>A smaller <see cref="FuzzySet"/> or <c>null</c> if the current set is already over-saturated.</return>
public virtual FuzzySet Downsize(float targetMaxSaturation)
{
var numBitsSet = _filter.Cardinality();
FixedBitSet rightSizedBitSet;
var rightSizedBitSetSize = _bloomSize;
//Hopefully find a smaller size bitset into which we can project accumulated values while maintaining desired saturation level
for (int i = 0; i < _usableBitSetSizes.Length; i++)
{
int candidateBitsetSize = _usableBitSetSizes[i];
float candidateSaturation = (float)numBitsSet
/ (float)candidateBitsetSize;
if (candidateSaturation <= targetMaxSaturation)
{
rightSizedBitSetSize = candidateBitsetSize;
break;
}
}
// Re-project the numbers to a smaller space if necessary
if (rightSizedBitSetSize < _bloomSize)
{
// Reset the choice of bitset to the smaller version
rightSizedBitSet = new FixedBitSet(rightSizedBitSetSize + 1);
// Map across the bits from the large set to the smaller one
var bitIndex = 0;
do
{
bitIndex = _filter.NextSetBit(bitIndex);
if (bitIndex < 0) continue;
// Project the larger number into a smaller one effectively
// modulo-ing by using the target bitset size as a mask
var downSizedBitIndex = bitIndex & rightSizedBitSetSize;
rightSizedBitSet.Set(downSizedBitIndex);
bitIndex++;
} while ((bitIndex >= 0) && (bitIndex <= _bloomSize));
}
else
{
return null;
}
return new FuzzySet(rightSizedBitSet, rightSizedBitSetSize, _hashFunction);
}
public virtual int GetEstimatedUniqueValues()
{
return GetEstimatedNumberUniqueValuesAllowingForCollisions(_bloomSize, _filter.Cardinality());
}
/// <summary>
/// Given a <paramref name="setSize"/> and a the number of set bits, produces an estimate of the number of unique values recorded.
/// </summary>
public static int GetEstimatedNumberUniqueValuesAllowingForCollisions(
int setSize, int numRecordedBits)
{
double setSizeAsDouble = setSize;
double numRecordedBitsAsDouble = numRecordedBits;
var saturation = numRecordedBitsAsDouble/setSizeAsDouble;
var logInverseSaturation = Math.Log(1 - saturation)*-1;
return (int) (setSizeAsDouble*logInverseSaturation);
}
public virtual float GetSaturation()
{
var numBitsSet = _filter.Cardinality();
return numBitsSet/(float) _bloomSize;
}
public virtual long RamBytesUsed()
{
return RamUsageEstimator.SizeOf(_filter.GetBits());
}
}
}
| 46.12012 | 183 | 0.598581 | [
"Apache-2.0"
] | Ref12/lucenenet | src/Lucene.Net.Codecs/Bloom/FuzzySet.cs | 15,358 | C# |
using Chameleon.Domain;
using Chameleon.Entity;
using Chameleon.Repository;
using Chameleon.ValueObject;
using MongoDB.Bson;
using MongoDB.Driver;
using Newtonsoft.Json.Linq;
using SevenTiny.Bantina;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Chameleon.Application
{
public interface IDataAccessApp
{
/// <summary>
/// 翻译BsonDocument为CloudData模式
/// </summary>
/// <param name="bsonDocuments"></param>
/// <param name="formatInterfaceFieldsDic">如有必要使用接口返回设置过滤返回值数量,则传递该参数</param>
/// <returns></returns>
List<Dictionary<string, CloudData>> TranslatorBsonToCloudData(List<BsonDocument> bsonDocuments, Dictionary<string, InterfaceFields> formatInterfaceFieldsDic = null);
/// <summary>
/// 翻译BsonDocument为CloudData模式
/// </summary>
/// <param name="bsonDocument"></param>
/// <param name="formatInterfaceFieldsDic">如有必要使用接口返回设置过滤返回值数量,则传递该参数</param>
/// <returns></returns>
Dictionary<string, CloudData> TranslatorBsonToCloudData(BsonDocument bsonDocument, Dictionary<string, InterfaceFields> formatInterfaceFieldsDic = null);
/// <summary>
/// 批量添加
/// </summary>
/// <param name="interfaceSetting"></param>
/// <param name="bsonsList"></param>
/// <returns></returns>
Result BatchAdd(InterfaceSetting interfaceSetting, IEnumerable<BsonDocument> bsonsList);
/// <summary>
/// 批量修改
/// </summary>
/// <param name="interfaceSetting"></param>
/// <param name="condition"></param>
/// <param name="bsonDocument"></param>
/// <returns></returns>
Result BatchUpdate(InterfaceSetting interfaceSetting, FilterDefinition<BsonDocument> filter, BsonDocument bsonDocument);
/// <summary>
/// 批量删除
/// </summary>
/// <param name="interfaceSetting"></param>
/// <param name="condition"></param>
/// <returns></returns>
Result Delete(InterfaceSetting interfaceSetting, FilterDefinition<BsonDocument> filter);
/// <summary>
/// 获取单条,内部走的获取列表
/// </summary>
/// <param name="interfaceSetting"></param>
/// <param name="condition"></param>
/// <param name="columns"></param>
/// <returns></returns>
Result<Dictionary<string, CloudData>> Get(InterfaceSetting interfaceSetting, FilterDefinition<BsonDocument> filter);
/// <summary>
/// 获取列表
/// </summary>
/// <param name="interfaceSetting"></param>
/// <param name="condition"></param>
/// <param name="pageIndex"></param>
/// <param name="pageSize"></param>
/// <param name="sortSetting"></param>
/// <param name="columns"></param>
/// <returns></returns>
Result<List<Dictionary<string, CloudData>>> GetList(InterfaceSetting interfaceSetting, FilterDefinition<BsonDocument> filter, int pageIndex = 0);
/// <summary>
/// 查询数量
/// </summary>
/// <param name="interfaceSetting"></param>
/// <param name="condition"></param>
/// <returns></returns>
Result<int> GetCount(InterfaceSetting interfaceSetting, FilterDefinition<BsonDocument> filter);
/// <summary>
/// 获取动态脚本执行结果
/// </summary>
/// <param name="interfaceSetting"></param>
/// <param name="argumentsUpperKeyDic"></param>
/// <returns></returns>
object GetDynamicScriptDataSourceResult(InterfaceSetting interfaceSetting, Dictionary<string, string> argumentsUpperKeyDic);
/// <summary>
/// 获取json数据源的json脚本
/// </summary>
/// <param name="interfaceSetting"></param>
/// <returns></returns>
object GetJsonDataSourceResult(InterfaceSetting interfaceSetting);
}
public class DataAccessApp : IDataAccessApp
{
IInterfaceConditionService _interfaceConditionService;
IInterfaceFieldsService _interfaceFieldsService;
IMetaFieldService _metaFieldService;
IInterfaceSettingService _interfaceSettingService;
ChameleonDataDbContext _chameleonDataDbContext;
IMetaFieldRepository _metaFieldRepository;
IInterfaceVerificationRepository _interfaceVerificationRepository;
IInterfaceVerificationService _interfaceVerificationService;
IInterfaceFieldsRepository _interfaceFieldsRepository;
IInterfaceSortRepository _interfaceSortRepository;
ITriggerScriptRepository _triggerScriptRepository;
ITriggerScriptService _triggerScriptService;
public DataAccessApp(ITriggerScriptService triggerScriptService, ITriggerScriptRepository triggerScriptRepository, IInterfaceSortRepository interfaceSortRepository, IInterfaceFieldsRepository interfaceFieldsRepository, IInterfaceVerificationRepository interfaceVerificationRepository, IInterfaceVerificationService interfaceVerificationService, IMetaFieldRepository metaFieldRepository, ChameleonDataDbContext chameleonDataDbContext, IInterfaceSettingService interfaceSettingService, IInterfaceConditionService interfaceConditionService, IInterfaceFieldsService interfaceFieldsService, IMetaFieldService metaFieldService)
{
_triggerScriptService = triggerScriptService;
_triggerScriptRepository = triggerScriptRepository;
_interfaceSortRepository = interfaceSortRepository;
_interfaceFieldsRepository = interfaceFieldsRepository;
_interfaceVerificationRepository = interfaceVerificationRepository;
_interfaceVerificationService = interfaceVerificationService;
_metaFieldRepository = metaFieldRepository;
_chameleonDataDbContext = chameleonDataDbContext;
_interfaceSettingService = interfaceSettingService;
_metaFieldService = metaFieldService;
_interfaceFieldsService = interfaceFieldsService;
_interfaceConditionService = interfaceConditionService;
}
/// <summary>
/// 构造排序
/// </summary>
/// <param name="interfaceSortId"></param>
/// <returns></returns>
private SortDefinition<BsonDocument> StructureSortDefinition(Guid interfaceSortId)
{
var builder = new SortDefinitionBuilder<BsonDocument>();
SortDefinition<BsonDocument> sort = null;
if (interfaceSortId == Guid.Empty)
return builder.Ascending("_id");
var sorts = _interfaceSortRepository.GetInterfaceSortByParentId(interfaceSortId) ?? new List<InterfaceSort>(0);
foreach (var item in sorts)
{
switch (item.GetSortType())
{
case SortTypeEnum.DESC:
sort = sort?.Descending(item.MetaFieldShortCode) ?? builder.Descending(item.MetaFieldShortCode);
break;
case SortTypeEnum.ASC:
sort = sort?.Ascending(item.MetaFieldShortCode) ?? builder.Ascending(item.MetaFieldShortCode);
break;
default:
break;
}
}
return sort;
}
public List<Dictionary<string, CloudData>> TranslatorBsonToCloudData(List<BsonDocument> bsonDocuments, Dictionary<string, InterfaceFields> formatInterfaceFieldsDic = null)
{
if (bsonDocuments == null || !bsonDocuments.Any())
return new List<Dictionary<string, CloudData>>(0);
return bsonDocuments.Select(t => TranslatorBsonToCloudData(t, formatInterfaceFieldsDic)).ToList();
}
public Dictionary<string, CloudData> TranslatorBsonToCloudData(BsonDocument bsonDocument, Dictionary<string, InterfaceFields> formatInterfaceFieldsDic = null)
{
if (bsonDocument == null || !bsonDocument.Any())
return new Dictionary<string, CloudData>(0);
Dictionary<string, CloudData> result = new Dictionary<string, CloudData>(formatInterfaceFieldsDic?.Count ?? bsonDocument.ElementCount);
foreach (var element in bsonDocument)
{
CloudData cloudData = null;
//如果有自定义返回设置
if (formatInterfaceFieldsDic != null)
{
var upperKey = element.Name.ToUpperInvariant();
//如果自定义返回设置里没有该字段,则不返回
if (!formatInterfaceFieldsDic.ContainsKey(upperKey))
continue;
cloudData = new CloudData
{
Name = formatInterfaceFieldsDic[upperKey].MetaFieldCustomViewName
};
}
if (cloudData == null)
cloudData = new CloudData();
cloudData.Code = element.Name;
cloudData.Value = element.Value?.ToString();
//如果后续需要翻译,则处理该字段
cloudData.Text = cloudData.Value;
result.TryAdd(element.Name, cloudData);
}
return result;
}
public Result BatchAdd(InterfaceSetting interfaceSetting, IEnumerable<BsonDocument> bsonsList)
{
if (interfaceSetting == null)
return Result.Error("接口设置参数不能为空");
if (bsonsList == null || !bsonsList.Any())
return Result.Success($"没有任何数据需要插入");
//获取全部接口校验
var verificationDic = _interfaceVerificationRepository.GetMetaFieldUpperKeyDicByInterfaceVerificationId(interfaceSetting.InterfaceVerificationId);
//获取到字段列表以编码为Key大写的字典
var metaFields = _metaFieldRepository.GetMetaFieldShortCodeUpperDicByMetaObjectId(interfaceSetting.MetaObjectId);
List<BsonDocument> insertBsonsList = new List<BsonDocument>(bsonsList.Count());
foreach (var bsonDocument in bsonsList)
{
if (bsonDocument == null)
return Result.Error("数据为空,插入终止");
BsonDocument bsonElementsToAdd = new BsonDocument();
foreach (var bsonElement in bsonDocument)
{
string upperKey = bsonElement.Name.ToUpperInvariant();
if (!metaFields.ContainsKey(upperKey))
continue;
//校验值是否符合接口校验设置
if (verificationDic.ContainsKey(upperKey))
{
var verification = verificationDic[upperKey];
if (!_interfaceVerificationService.IsMatch(verification, Convert.ToString(bsonElement.Value)))
return Result.Error(!string.IsNullOrEmpty(verification.VerificationTips) ? verification.VerificationTips : $"字段[{bsonElement.Name}]传递的值[{bsonElement.Value}]格式不正确");
}
//检查字段的值是否符合字段类型
var checkResult = _metaFieldService.CheckAndGetFieldValueByFieldType(metaFields[upperKey], bsonElement.Value);
if (checkResult.IsSuccess)
bsonElementsToAdd.Add(new BsonElement(metaFields[upperKey].ShortCode, BsonValue.Create(checkResult.Data)));
else
return Result.Error($"字段[{bsonElement.Name}]传递的值[{bsonElement.Value}]不符合字段定义的类型");
}
//获取系统内置的bson元素
var systemBsonDocument = _metaFieldService.GetSystemFieldBsonDocument();
//设置系统字段及其默认值
foreach (var presetBsonElement in systemBsonDocument)
{
//如果传入的字段已经有了,那么这里就不预置了
if (!bsonElementsToAdd.Contains(presetBsonElement.Name))
bsonElementsToAdd.Add(presetBsonElement);
}
//补充字段
bsonElementsToAdd.SetElement(new BsonElement("MetaObject", interfaceSetting.MetaObjectCode));
if (bsonElementsToAdd.Any())
insertBsonsList.Add(bsonElementsToAdd);
}
if (insertBsonsList.Any())
_chameleonDataDbContext.GetCollectionBson(interfaceSetting.MetaObjectCode).InsertMany(insertBsonsList);
return Result.Success($"插入成功! 成功{insertBsonsList.Count}条,失败{bsonsList.Count() - insertBsonsList.Count}条.");
}
public Result BatchUpdate(InterfaceSetting interfaceSetting, FilterDefinition<BsonDocument> filter, BsonDocument bsonDocument)
{
if (interfaceSetting == null)
return Result.Error("接口设置参数不能为空");
if (bsonDocument == null)
return Result.Error("数据为空,更新终止");
//获取全部接口校验
var verificationDic = _interfaceVerificationRepository.GetMetaFieldUpperKeyDicByInterfaceVerificationId(interfaceSetting.InterfaceVerificationId);
//获取到字段列表以编码为Key大写的字典
var metaFields = _metaFieldRepository.GetMetaFieldShortCodeUpperDicByMetaObjectId(interfaceSetting.MetaObjectId);
BsonDocument bsonElementsToModify = new BsonDocument();
foreach (var bsonElement in bsonDocument)
{
string upperKey = bsonElement.Name.ToUpperInvariant();
if (!metaFields.ContainsKey(upperKey))
continue;
//校验值是否符合接口校验设置
if (verificationDic.ContainsKey(upperKey))
{
var verification = verificationDic[upperKey];
if (!_interfaceVerificationService.IsMatch(verification, Convert.ToString(bsonElement.Value)))
return Result.Error(!string.IsNullOrEmpty(verification.VerificationTips) ? verification.VerificationTips : $"字段[{bsonElement.Name}]传递的值[{bsonElement.Value}]格式不正确");
}
//检查字段的值是否符合字段类型
var checkResult = _metaFieldService.CheckAndGetFieldValueByFieldType(metaFields[upperKey], bsonElement.Value);
if (checkResult.IsSuccess)
bsonElementsToModify.Add(new BsonElement(metaFields[upperKey].ShortCode, BsonValue.Create(checkResult.Data)));
else
return Result.Error($"字段[{bsonElement.Name}]传递的值[{bsonElement.Value}]不符合字段定义的类型");
}
//设置更新并执行更新操作
var updateDefinitions = bsonElementsToModify.Select(item => Builders<BsonDocument>.Update.Set(item.Name, item.Value)).ToArray();
_chameleonDataDbContext.GetCollectionBson(interfaceSetting.MetaObjectCode).UpdateMany(filter, Builders<BsonDocument>.Update.Combine(updateDefinitions));
return Result.Success($"修改成功");
}
public Result Delete(InterfaceSetting interfaceSetting, FilterDefinition<BsonDocument> filter)
{
_chameleonDataDbContext.GetCollectionBson(interfaceSetting.MetaObjectCode).DeleteMany(filter);
return Result.Success($"删除成功");
}
public Result<Dictionary<string, CloudData>> Get(InterfaceSetting interfaceSetting, FilterDefinition<BsonDocument> filter)
{
var listResult = GetList(interfaceSetting, filter, 0);
if (listResult.IsSuccess)
return Result<Dictionary<string, CloudData>>.Success("查询成功", listResult.Data.FirstOrDefault());
return Result<Dictionary<string, CloudData>>.Error(listResult.Message);
}
public Result<List<Dictionary<string, CloudData>>> GetList(InterfaceSetting interfaceSetting, FilterDefinition<BsonDocument> filter, int pageIndex = 0)
{
//自定义查询列表
var interfaceFields = _interfaceFieldsRepository.GetInterfaceFieldMetaFieldUpperKeyDicByInterfaceFieldsId(interfaceSetting.InterfaceFieldsId);
//处理查询列
var projection = Builders<BsonDocument>.Projection.Include("_id");
foreach (var item in interfaceFields.Values)
projection = projection.Include(item.MetaFieldShortCode);
int skipSize = (pageIndex - 1) > 0 ? ((pageIndex - 1) * interfaceSetting.PageSize) : 0;
var datas = TranslatorBsonToCloudData(_chameleonDataDbContext.GetCollectionBson(interfaceSetting.MetaObjectCode).Find(filter).Skip(skipSize).Limit(interfaceSetting.PageSize).Sort(StructureSortDefinition(interfaceSetting.InterfaceSortId)).Project(projection).ToList() ?? new List<BsonDocument>(0), interfaceFields);
var result = Result<List<Dictionary<string, CloudData>>>.Success($"查询成功,共{datas.Count}条记录", datas);
result.MoreMessage = new List<string> { datas.Count.ToString() };
return result;
}
public Result<int> GetCount(InterfaceSetting interfaceSetting, FilterDefinition<BsonDocument> filter)
{
return Result<int>.Success("查询成功", Convert.ToInt32(_chameleonDataDbContext.GetCollectionBson(interfaceSetting.MetaObjectCode).CountDocuments(filter)));
}
public object GetDynamicScriptDataSourceResult(InterfaceSetting interfaceSetting, Dictionary<string, string> argumentsUpperKeyDic)
{
var script = _triggerScriptRepository.GetById(interfaceSetting.DataSousrceId);
var result = _triggerScriptService.ExecuteTriggerScript<object>(script, new object[] { argumentsUpperKeyDic });
return result.IsSuccess ? result.Data : throw new InvalidOperationException(result.Message);
}
public object GetJsonDataSourceResult(InterfaceSetting interfaceSetting)
{
var entity = _triggerScriptRepository.GetById(interfaceSetting.DataSousrceId);
try
{
return JObject.Parse(entity.Script);
}
catch
{
try
{
return JArray.Parse(entity.Script);
}
catch (Exception ex)
{
return string.Empty;
}
}
}
}
}
| 45.167082 | 629 | 0.636042 | [
"MIT"
] | sevenTiny/Chameleon | Code/Chameleon.Application/DataAccessApp.cs | 19,054 | C# |
using BlazorInputFile;
namespace Frontend.Models
{
public class Image
{
public int Id { get; set; }
public string ImageDataURL { get; set; }
public IFileListEntry ImageFile { get; set; }
public string ImageURL { get; set; }
public bool IsDefault { get; set; }
public int ProductId { get; set; }
}
} | 25.714286 | 53 | 0.6 | [
"MIT"
] | PGBSNH19/project-grupp-5-1 | Frontend/Models/Image.cs | 362 | C# |
using BusinessAccessLayer;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace E_Commerce_Site.UI
{
public partial class Index : System.Web.UI.MasterPage
{
public int flag = 1;
protected void Page_Load(object sender, EventArgs e)
{
if (Session["User"] == null)
{
flag = 0;
}
if (Session["User"] != null)
{
if (!IsPostBack)
{
UserName.Text = Session["User"].ToString();
lblUserName.Text = Session["User"].ToString();
if (!string.IsNullOrEmpty(Session["UserImage"].ToString()))
{
userImage.ImageUrl = Session["UserImage"].ToString();
userImage2.ImageUrl = Session["UserImage"].ToString();
}
}
DataTable dt = (DataTable)Session["UserWholeRecord"];
int userID = Convert.ToInt32(dt.Rows[0]["user_id"].ToString());
ECommerceBusiness ecb = new ECommerceBusiness();
dt = ecb.SelectAllCartedProduct(userID);
string noOfCartedProduct = dt.Rows.Count.ToString();
if (Convert.ToInt32(noOfCartedProduct) > 0)
{
cartBadge.InnerText = noOfCartedProduct;
cartBadge.Style.Add("visibility", "visible");
}
}
}
protected void btnLogin_Click(object sender, EventArgs e)
{
if (Request.UrlReferrer != null)
{
Session["PageName"] = System.IO.Path.GetFileName(Request.UrlReferrer.AbsolutePath);
}
Response.Redirect("UserLogin.aspx");
}
protected void btnProfile_Click(object sender, EventArgs e)
{
Response.Redirect("Profile.aspx");
}
protected void btnLogout_Click(object sender, EventArgs e)
{
Session.Abandon();
Response.Redirect("HomePage.aspx");
}
}
} | 31.493151 | 100 | 0.508047 | [
"MIT"
] | 78526Nasir/E-Commerce-Site | E-Commerce Site/UI/Index.Master.cs | 2,301 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.Storage.Blobs.Models;
using Metadata = System.Collections.Generic.IDictionary<string, string>;
#pragma warning disable SA1402 // File may only contain a single type
namespace Azure.Storage.Blobs.Specialized
{
/// <summary>
/// The <see cref="AppendBlobClient"/> allows you to manipulate Azure
/// Storage append blobs.
///
/// An append blob is comprised of blocks and is optimized for append
/// operations. When you modify an append blob, blocks are added to the
/// end of the blob only, via the <see cref="AppendBlockAsync"/>
/// operation. Updating or deleting of existing blocks is not supported.
/// Unlike a block blob, an append blob does not expose its block IDs.
///
/// Each block in an append blob can be a different size, up to a maximum
/// of 4 MB, and an append blob can include up to 50,000 blocks. The
/// maximum size of an append blob is therefore slightly more than 195 GB
/// (4 MB X 50,000 blocks).
/// </summary>
public class AppendBlobClient : BlobBaseClient
{
/// <summary>
/// Gets the maximum number of bytes that can be sent in a call
/// to AppendBlock.
/// </summary>
public virtual int AppendBlobMaxAppendBlockBytes => Constants.Blob.Append.MaxAppendBlockBytes;
/// <summary>
/// Gets the maximum number of blocks allowed in an append blob.
/// </summary>
public virtual int AppendBlobMaxBlocks => Constants.Blob.Append.MaxBlocks;
#region ctors
/// <summary>
/// Initializes a new instance of the <see cref="AppendBlobClient"/>
/// class for mocking.
/// </summary>
protected AppendBlobClient()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="AppendBlobClient"/>
/// class.
/// </summary>
/// <param name="connectionString">
/// A connection string includes the authentication information
/// required for your application to access data in an Azure Storage
/// account at runtime.
///
/// For more information, <see href="https://docs.microsoft.com/en-us/azure/storage/common/storage-configure-connection-string"/>.
/// </param>
/// <param name="blobContainerName">
/// The name of the container containing this append blob.
/// </param>
/// <param name="blobName">
/// The name of this append blob.
/// </param>
public AppendBlobClient(string connectionString, string blobContainerName, string blobName)
: base(connectionString, blobContainerName, blobName)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="AppendBlobClient"/>
/// class.
/// </summary>
/// <param name="connectionString">
/// A connection string includes the authentication information
/// required for your application to access data in an Azure Storage
/// account at runtime.
///
/// For more information, <see href="https://docs.microsoft.com/en-us/azure/storage/common/storage-configure-connection-string"/>.
/// </param>
/// <param name="blobContainerName">
/// The name of the container containing this append blob.
/// </param>
/// <param name="blobName">
/// The name of this append blob.
/// </param>
/// <param name="options">
/// Optional client options that define the transport pipeline
/// policies for authentication, retries, etc., that are applied to
/// every request.
/// </param>
public AppendBlobClient(string connectionString, string blobContainerName, string blobName, BlobClientOptions options)
: base(connectionString, blobContainerName, blobName, options)
{
AssertNoClientSideEncryption(options);
}
/// <summary>
/// Initializes a new instance of the <see cref="AppendBlobClient"/>
/// class.
/// </summary>
/// <param name="blobUri">
/// A <see cref="Uri"/> referencing the append blob that includes the
/// name of the account, the name of the container, and the name of
/// the blob.
/// This is likely to be similar to "https://{account_name}.blob.core.windows.net/{container_name}/{blob_name}".
/// </param>
/// <param name="options">
/// Optional client options that define the transport pipeline
/// policies for authentication, retries, etc., that are applied to
/// every request.
/// </param>
public AppendBlobClient(Uri blobUri, BlobClientOptions options = default)
: base(blobUri, options)
{
AssertNoClientSideEncryption(options);
}
/// <summary>
/// Initializes a new instance of the <see cref="AppendBlobClient"/>
/// class.
/// </summary>
/// <param name="blobUri">
/// A <see cref="Uri"/> referencing the append blob that includes the
/// name of the account, the name of the container, and the name of
/// the blob.
/// This is likely to be similar to "https://{account_name}.blob.core.windows.net/{container_name}/{blob_name}".
/// </param>
/// <param name="credential">
/// The shared key credential used to sign requests.
/// </param>
/// <param name="options">
/// Optional client options that define the transport pipeline
/// policies for authentication, retries, etc., that are applied to
/// every request.
/// </param>
public AppendBlobClient(Uri blobUri, StorageSharedKeyCredential credential, BlobClientOptions options = default)
: base(blobUri, credential, options)
{
AssertNoClientSideEncryption(options);
}
/// <summary>
/// Initializes a new instance of the <see cref="AppendBlobClient"/>
/// class.
/// </summary>
/// <param name="blobUri">
/// A <see cref="Uri"/> referencing the append blob that includes the
/// name of the account, the name of the container, and the name of
/// the blob.
/// This is likely to be similar to "https://{account_name}.blob.core.windows.net/{container_name}/{blob_name}".
/// </param>
/// <param name="credential">
/// The token credential used to sign requests.
/// </param>
/// <param name="options">
/// Optional client options that define the transport pipeline
/// policies for authentication, retries, etc., that are applied to
/// every request.
/// </param>
public AppendBlobClient(Uri blobUri, TokenCredential credential, BlobClientOptions options = default)
: base(blobUri, credential, options)
{
AssertNoClientSideEncryption(options);
}
/// <summary>
/// Initializes a new instance of the <see cref="AppendBlobClient"/>
/// class.
/// </summary>
/// <param name="blobUri">
/// A <see cref="Uri"/> referencing the append blob that includes the
/// name of the account, the name of the container, and the name of
/// the blob.
/// This is likely to be similar to "https://{account_name}.blob.core.windows.net/{container_name}/{blob_name}".
/// </param>
/// <param name="pipeline">
/// The transport pipeline used to send every request.
/// </param>
/// <param name="version">
/// The version of the service to use when sending requests.
/// </param>
/// <param name="clientDiagnostics">Client diagnostics.</param>
/// <param name="customerProvidedKey">Customer provided key.</param>
/// <param name="encryptionScope">Encryption scope.</param>
internal AppendBlobClient(
Uri blobUri,
HttpPipeline pipeline,
BlobClientOptions.ServiceVersion version,
ClientDiagnostics clientDiagnostics,
CustomerProvidedKey? customerProvidedKey,
string encryptionScope)
: base(
blobUri,
pipeline,
version,
clientDiagnostics,
customerProvidedKey,
clientSideEncryption: default,
encryptionScope)
{
}
private static void AssertNoClientSideEncryption(BlobClientOptions options)
{
if (options?._clientSideEncryptionOptions != default)
{
throw Errors.ClientSideEncryption.TypeNotSupported(typeof(AppendBlobClient));
}
}
#endregion ctors
/// <summary>
/// Initializes a new instance of the <see cref="AppendBlobClient"/>
/// class with an identical <see cref="Uri"/> source but the specified
/// <paramref name="snapshot"/> timestamp.
///
/// For more information, see <see href="https://docs.microsoft.com/en-us/rest/api/storageservices/creating-a-snapshot-of-a-blob" />.
/// </summary>
/// <param name="snapshot">The snapshot identifier.</param>
/// <returns>A new <see cref="AppendBlobClient"/> instance.</returns>
/// <remarks>
/// Pass null or empty string to remove the snapshot returning a URL
/// to the base blob.
/// </remarks>
public new AppendBlobClient WithSnapshot(string snapshot)
{
var builder = new BlobUriBuilder(Uri) { Snapshot = snapshot };
return new AppendBlobClient(builder.ToUri(), Pipeline, Version, ClientDiagnostics, CustomerProvidedKey, EncryptionScope);
}
#region Create
/// <summary>
/// The <see cref="Create"/> operation creates a new 0-length
/// append blob. The content of any existing blob is overwritten with
/// the newly initialized append blob. To add content to the append
/// blob, call the <see cref="AppendBlock"/> operation.
///
/// For more information, see <see href="https://docs.microsoft.com/rest/api/storageservices/put-blob" />.
/// </summary>
/// <param name="httpHeaders">
/// Optional standard HTTP header properties that can be set for the
/// new append blob.
/// </param>
/// <param name="metadata">
/// Optional custom metadata to set for this append blob.
/// </param>
/// <param name="conditions">
/// Optional <see cref="AppendBlobRequestConditions"/> to add
/// conditions on the creation of this new append blob.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response{BlobContentInfo}"/> describing the
/// newly created append blob.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
public virtual Response<BlobContentInfo> Create(
BlobHttpHeaders httpHeaders = default,
Metadata metadata = default,
AppendBlobRequestConditions conditions = default,
CancellationToken cancellationToken = default) =>
CreateInternal(
httpHeaders,
metadata,
conditions,
false, // async
cancellationToken)
.EnsureCompleted();
/// <summary>
/// The <see cref="CreateAsync"/> operation creates a new 0-length
/// append blob. The content of any existing blob is overwritten with
/// the newly initialized append blob. To add content to the append
/// blob, call the <see cref="AppendBlockAsync"/> operation.
///
/// For more information, see <see href="https://docs.microsoft.com/rest/api/storageservices/put-blob" />.
/// </summary>
/// <param name="httpHeaders">
/// Optional standard HTTP header properties that can be set for the
/// new append blob.
/// </param>
/// <param name="metadata">
/// Optional custom metadata to set for this append blob.
/// </param>
/// <param name="conditions">
/// Optional <see cref="AppendBlobRequestConditions"/> to add
/// conditions on the creation of this new append blob.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response{BlobContentInfo}"/> describing the
/// newly created append blob.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
public virtual async Task<Response<BlobContentInfo>> CreateAsync(
BlobHttpHeaders httpHeaders = default,
Metadata metadata = default,
AppendBlobRequestConditions conditions = default,
CancellationToken cancellationToken = default) =>
await CreateInternal(
httpHeaders,
metadata,
conditions,
true, // async
cancellationToken)
.ConfigureAwait(false);
/// <summary>
/// The <see cref="CreateIfNotExists"/> operation creates a new 0-length
/// append blob. If the append blob already exists, the content of
/// the existing append blob will remain unchanged. To add content to the append
/// blob, call the <see cref="AppendBlockAsync"/> operation.
///
/// For more information, see <see href="https://docs.microsoft.com/rest/api/storageservices/put-blob" />.
/// </summary>
/// <param name="httpHeaders">
/// Optional standard HTTP header properties that can be set for the
/// new append blob.
/// </param>
/// <param name="metadata">
/// Optional custom metadata to set for this append blob.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// If the append blob does not already exist, a <see cref="Response{BlobContentInfo}"/>
/// describing the newly created append blob. Otherwise, <c>null</c>.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
public virtual Response<BlobContentInfo> CreateIfNotExists(
BlobHttpHeaders httpHeaders = default,
Metadata metadata = default,
CancellationToken cancellationToken = default) =>
CreateIfNotExistsInternal(
httpHeaders,
metadata,
false, // async
cancellationToken)
.EnsureCompleted();
/// <summary>
/// The <see cref="CreateIfNotExistsAsync"/> operation creates a new 0-length
/// append blob. If the append blob already exists, the content of
/// the existing append blob will remain unchanged. To add content to the append
/// blob, call the <see cref="AppendBlockAsync"/> operation.
///
/// For more information, see <see href="https://docs.microsoft.com/rest/api/storageservices/put-blob" />.
/// </summary>
/// <param name="httpHeaders">
/// Optional standard HTTP header properties that can be set for the
/// new append blob.
/// </param>
/// <param name="metadata">
/// Optional custom metadata to set for this append blob.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// If the append blob does not already exist, a <see cref="Response{BlobContentInfo}"/>
/// describing the newly created append blob. Otherwise, <c>null</c>.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
public virtual async Task<Response<BlobContentInfo>> CreateIfNotExistsAsync(
BlobHttpHeaders httpHeaders = default,
Metadata metadata = default,
CancellationToken cancellationToken = default) =>
await CreateIfNotExistsInternal(
httpHeaders,
metadata,
true, // async
cancellationToken)
.ConfigureAwait(false);
/// <summary>
/// The <see cref="CreateIfNotExistsInternal"/> operation creates a new 0-length
/// append blob. If the append blob already exists, the content of
/// the existing append blob will remain unchanged. To add content to the append
/// blob, call the <see cref="AppendBlockAsync"/> operation.
///
/// For more information, see <see href="https://docs.microsoft.com/rest/api/storageservices/put-blob" />.
/// </summary>
/// <param name="httpHeaders">
/// Optional standard HTTP header properties that can be set for the
/// new append blob.
/// </param>
/// <param name="metadata">
/// Optional custom metadata to set for this append blob.
/// </param>
/// <param name="async">
/// Whether to invoke the operation asynchronously.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// If the append blob does not already exist, a <see cref="Response{BlobContentInfo}"/>
/// describing the newly created append blob. Otherwise, <c>null</c>.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
private async Task<Response<BlobContentInfo>> CreateIfNotExistsInternal(
BlobHttpHeaders httpHeaders,
Metadata metadata,
bool async,
CancellationToken cancellationToken)
{
using (Pipeline.BeginLoggingScope(nameof(AppendBlobClient)))
{
Pipeline.LogMethodEnter(
nameof(AppendBlobClient),
message:
$"{nameof(Uri)}: {Uri}\n" +
$"{nameof(httpHeaders)}: {httpHeaders}");
var conditions = new AppendBlobRequestConditions { IfNoneMatch = new ETag(Constants.Wildcard) };
try
{
Response<BlobContentInfo> response = await CreateInternal(
httpHeaders,
metadata,
conditions,
async,
cancellationToken,
$"{nameof(AppendBlobClient)}.{nameof(CreateIfNotExists)}")
.ConfigureAwait(false);
return response;
}
catch (RequestFailedException storageRequestFailedException)
when (storageRequestFailedException.ErrorCode == BlobErrorCode.BlobAlreadyExists)
{
return default;
}
catch (Exception ex)
{
Pipeline.LogException(ex);
throw;
}
finally
{
Pipeline.LogMethodExit(nameof(AppendBlobClient));
}
}
}
/// <summary>
/// The <see cref="CreateInternal"/> operation creates a new 0-length
/// append blob. The content of any existing blob is overwritten with
/// the newly initialized append blob. To add content to the append
/// blob, call the <see cref="AppendBlockAsync"/> operation.
///
/// For more information, see <see href="https://docs.microsoft.com/rest/api/storageservices/put-blob" />.
/// </summary>
/// <param name="httpHeaders">
/// Optional standard HTTP header properties that can be set for the
/// new append blob.
/// </param>
/// <param name="metadata">
/// Optional custom metadata to set for this append blob.
/// </param>
/// <param name="conditions">
/// Optional <see cref="AppendBlobRequestConditions"/> to add
/// conditions on the creation of this new append blob.
/// </param>
/// <param name="async">
/// Whether to invoke the operation asynchronously.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <param name="operationName">
/// Optional. To indicate if the name of the operation.
/// </param>
/// <returns>
/// A <see cref="Response{BlobContentInfo}"/> describing the
/// newly created append blob.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
private async Task<Response<BlobContentInfo>> CreateInternal(
BlobHttpHeaders httpHeaders,
Metadata metadata,
AppendBlobRequestConditions conditions,
bool async,
CancellationToken cancellationToken,
string operationName = null)
{
using (Pipeline.BeginLoggingScope(nameof(AppendBlobClient)))
{
Pipeline.LogMethodEnter(
nameof(AppendBlobClient),
message:
$"{nameof(Uri)}: {Uri}\n" +
$"{nameof(httpHeaders)}: {httpHeaders}\n" +
$"{nameof(conditions)}: {conditions}");
try
{
return await BlobRestClient.AppendBlob.CreateAsync(
ClientDiagnostics,
Pipeline,
Uri,
contentLength: default,
version: Version.ToVersionString(),
blobContentType: httpHeaders?.ContentType,
blobContentEncoding: httpHeaders?.ContentEncoding,
blobContentLanguage: httpHeaders?.ContentLanguage,
blobContentHash: httpHeaders?.ContentHash,
blobCacheControl: httpHeaders?.CacheControl,
metadata: metadata,
leaseId: conditions?.LeaseId,
blobContentDisposition: httpHeaders?.ContentDisposition,
encryptionKey: CustomerProvidedKey?.EncryptionKey,
encryptionKeySha256: CustomerProvidedKey?.EncryptionKeyHash,
encryptionAlgorithm: CustomerProvidedKey?.EncryptionAlgorithm,
encryptionScope: EncryptionScope,
ifModifiedSince: conditions?.IfModifiedSince,
ifUnmodifiedSince: conditions?.IfUnmodifiedSince,
ifMatch: conditions?.IfMatch,
ifNoneMatch: conditions?.IfNoneMatch,
async: async,
operationName: operationName ?? $"{nameof(AppendBlobClient)}.{nameof(Create)}",
cancellationToken: cancellationToken)
.ConfigureAwait(false);
}
catch (Exception ex)
{
Pipeline.LogException(ex);
throw;
}
finally
{
Pipeline.LogMethodExit(nameof(AppendBlobClient));
}
}
}
#endregion Create
#region AppendBlock
/// <summary>
/// The <see cref="AppendBlock"/> operation commits a new block
/// of data, represented by the <paramref name="content"/> <see cref="Stream"/>,
/// to the end of the existing append blob. The <see cref="AppendBlock"/>
/// operation is only permitted if the blob was created as an append
/// blob.
///
/// For more information, see <see href="https://docs.microsoft.com/rest/api/storageservices/append-block" />.
/// </summary>
/// <param name="content">
/// A <see cref="Stream"/> containing the content of the block to
/// append.
/// </param>
/// <param name="transactionalContentHash">
/// Optional MD5 hash of the block content. This hash is used to
/// verify the integrity of the block during transport. When this hash
/// is specified, the storage service compares the hash of the content
/// that has arrived with this value. Note that this MD5 hash is not
/// stored with the blob. If the two hashes do not match, the
/// operation will fail with a <see cref="RequestFailedException"/>.
/// </param>
/// <param name="conditions">
/// Optional <see cref="AppendBlobRequestConditions"/> to add
/// conditions on appending content to this append blob.
/// </param>
/// <param name="progressHandler">
/// Optional <see cref="IProgress{Long}"/> to provide
/// progress updates about data transfers.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response{BlobAppendInfo}"/> describing the
/// state of the updated append blob.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
public virtual Response<BlobAppendInfo> AppendBlock(
Stream content,
byte[] transactionalContentHash = default,
AppendBlobRequestConditions conditions = default,
IProgress<long> progressHandler = default,
CancellationToken cancellationToken = default) =>
AppendBlockInternal(
content,
transactionalContentHash,
conditions,
progressHandler,
false, // async
cancellationToken)
.EnsureCompleted();
/// <summary>
/// The <see cref="AppendBlockAsync"/> operation commits a new block
/// of data, represented by the <paramref name="content"/> <see cref="Stream"/>,
/// to the end of the existing append blob. The <see cref="AppendBlockAsync"/>
/// operation is only permitted if the blob was created as an append
/// blob.
///
/// For more information, see <see href="https://docs.microsoft.com/rest/api/storageservices/append-block" />.
/// </summary>
/// <param name="content">
/// A <see cref="Stream"/> containing the content of the block to
/// append.
/// </param>
/// <param name="transactionalContentHash">
/// Optional MD5 hash of the block content. This hash is used to
/// verify the integrity of the block during transport. When this hash
/// is specified, the storage service compares the hash of the content
/// that has arrived with this value. Note that this MD5 hash is not
/// stored with the blob. If the two hashes do not match, the
/// operation will fail with a <see cref="RequestFailedException"/>.
/// </param>
/// <param name="conditions">
/// Optional <see cref="AppendBlobRequestConditions"/> to add
/// conditions on appending content to this append blob.
/// </param>
/// <param name="progressHandler">
/// Optional <see cref="IProgress{Long}"/> to provide
/// progress updates about data transfers.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response{BlobAppendInfo}"/> describing the
/// state of the updated append blob.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
public virtual async Task<Response<BlobAppendInfo>> AppendBlockAsync(
Stream content,
byte[] transactionalContentHash = default,
AppendBlobRequestConditions conditions = default,
IProgress<long> progressHandler = default,
CancellationToken cancellationToken = default) =>
await AppendBlockInternal(
content,
transactionalContentHash,
conditions,
progressHandler,
true, // async
cancellationToken)
.ConfigureAwait(false);
/// <summary>
/// The <see cref="AppendBlockInternal"/> operation commits a new block
/// of data, represented by the <paramref name="content"/> <see cref="Stream"/>,
/// to the end of the existing append blob. The <see cref="AppendBlockInternal"/>
/// operation is only permitted if the blob was created as an append
/// blob.
///
/// For more information, see <see href="https://docs.microsoft.com/rest/api/storageservices/append-block" />.
/// </summary>
/// <param name="content">
/// A <see cref="Stream"/> containing the content of the block to
/// append.
/// </param>
/// <param name="transactionalContentHash">
/// Optional MD5 hash of the block content. This hash is used to
/// verify the integrity of the block during transport. When this hash
/// is specified, the storage service compares the hash of the content
/// that has arrived with this value. Note that this MD5 hash is not
/// stored with the blob. If the two hashes do not match, the
/// operation will fail with a <see cref="RequestFailedException"/>.
/// </param>
/// <param name="conditions">
/// Optional <see cref="AppendBlobRequestConditions"/> to add
/// conditions on appending content to this append blob.
/// </param>
/// <param name="progressHandler">
/// Optional <see cref="IProgress{Long}"/> to provide
/// progress updates about data transfers.
/// </param>
/// <param name="async">
/// Whether to invoke the operation asynchronously.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response{BlobAppendInfo}"/> describing the
/// state of the updated append blob.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
private async Task<Response<BlobAppendInfo>> AppendBlockInternal(
Stream content,
byte[] transactionalContentHash,
AppendBlobRequestConditions conditions,
IProgress<long> progressHandler,
bool async,
CancellationToken cancellationToken)
{
using (Pipeline.BeginLoggingScope(nameof(AppendBlobClient)))
{
Pipeline.LogMethodEnter(
nameof(AppendBlobClient),
message:
$"{nameof(Uri)}: {Uri}\n" +
$"{nameof(conditions)}: {conditions}");
try
{
BlobErrors.VerifyHttpsCustomerProvidedKey(Uri, CustomerProvidedKey);
content = content?.WithNoDispose().WithProgress(progressHandler);
return await BlobRestClient.AppendBlob.AppendBlockAsync(
ClientDiagnostics,
Pipeline,
Uri,
body: content,
contentLength: content?.Length ?? 0,
version: Version.ToVersionString(),
transactionalContentHash: transactionalContentHash,
leaseId: conditions?.LeaseId,
maxSize: conditions?.IfMaxSizeLessThanOrEqual,
encryptionKey: CustomerProvidedKey?.EncryptionKey,
encryptionKeySha256: CustomerProvidedKey?.EncryptionKeyHash,
encryptionAlgorithm: CustomerProvidedKey?.EncryptionAlgorithm,
encryptionScope: EncryptionScope,
appendPosition: conditions?.IfAppendPositionEqual,
ifModifiedSince: conditions?.IfModifiedSince,
ifUnmodifiedSince: conditions?.IfUnmodifiedSince,
ifMatch: conditions?.IfMatch,
ifNoneMatch: conditions?.IfNoneMatch,
async: async,
operationName: "AppendBlobClient.AppendBlock",
cancellationToken: cancellationToken).ConfigureAwait(false);
}
catch (Exception ex)
{
Pipeline.LogException(ex);
throw;
}
finally
{
Pipeline.LogMethodExit(nameof(AppendBlobClient));
}
}
}
#endregion AppendBlock
#region AppendBlockFromUri
/// <summary>
/// The <see cref="AppendBlockFromUri"/> operation commits a new
/// block of data, represented by the <paramref name="sourceUri"/>,
/// to the end of the existing append blob. The
/// <see cref="AppendBlockFromUri"/> operation is only permitted
/// if the blob was created as an append blob.
///
/// For more information, see <see href="https://docs.microsoft.com/en-us/rest/api/storageservices/append-block-from-url" />.
/// </summary>
/// <param name="sourceUri">
/// Specifies the <see cref="Uri"/> of the source blob. The value may
/// be a <see cref="Uri"/> of up to 2 KB in length that specifies a
/// blob. The source blob must either be public or must be
/// authenticated via a shared access signature. If the source blob
/// is public, no authentication is required to perform the operation.
/// </param>
/// <param name="sourceRange">
/// Optionally only upload the bytes of the blob in the
/// <paramref name="sourceUri"/> in the specified range. If this is
/// not specified, the entire source blob contents are uploaded as a
/// single append block.
/// </param>
/// <param name="sourceContentHash">
/// Optional MD5 hash of the append block content from the
/// <paramref name="sourceUri"/>. This hash is used to verify the
/// integrity of the block during transport of the data from the Uri.
/// When this hash is specified, the storage service compares the hash
/// of the content that has arrived from the <paramref name="sourceUri"/>
/// with this value. Note that this md5 hash is not stored with the
/// blob. If the two hashes do not match, the operation will fail
/// with a <see cref="RequestFailedException"/>.
/// </param>
/// <param name="conditions">
/// Optional <see cref="AppendBlobRequestConditions"/> to add
/// conditions on the copying of data to this append blob.
/// </param>
/// <param name="sourceConditions">
/// Optional <see cref="AppendBlobRequestConditions"/> to add
/// conditions on the copying of data from this source blob.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response{BlobAppendInfo}"/> describing the
/// state of the updated append blob.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
public virtual Response<BlobAppendInfo> AppendBlockFromUri(
Uri sourceUri,
HttpRange sourceRange = default,
byte[] sourceContentHash = default,
AppendBlobRequestConditions conditions = default,
AppendBlobRequestConditions sourceConditions = default,
CancellationToken cancellationToken = default) =>
AppendBlockFromUriInternal(
sourceUri,
sourceRange,
sourceContentHash,
conditions,
sourceConditions,
false, // async
cancellationToken)
.EnsureCompleted();
/// <summary>
/// The <see cref="AppendBlockFromUriAsync"/> operation commits a new
/// block of data, represented by the <paramref name="sourceUri"/>,
/// to the end of the existing append blob. The
/// <see cref="AppendBlockFromUriAsync"/> operation is only permitted
/// if the blob was created as an append blob.
///
/// For more information, see <see href="https://docs.microsoft.com/en-us/rest/api/storageservices/append-block-from-url" />.
/// </summary>
/// <param name="sourceUri">
/// Specifies the <see cref="Uri"/> of the source blob. The value may
/// be a <see cref="Uri"/> of up to 2 KB in length that specifies a
/// blob. The source blob must either be public or must be
/// authenticated via a shared access signature. If the source blob
/// is public, no authentication is required to perform the operation.
/// </param>
/// <param name="sourceRange">
/// Optionally only upload the bytes of the blob in the
/// <paramref name="sourceUri"/> in the specified range. If this is
/// not specified, the entire source blob contents are uploaded as a
/// single append block.
/// </param>
/// <param name="sourceContentHash">
/// Optional MD5 hash of the append block content from the
/// <paramref name="sourceUri"/>. This hash is used to verify the
/// integrity of the block during transport of the data from the Uri.
/// When this hash is specified, the storage service compares the hash
/// of the content that has arrived from the <paramref name="sourceUri"/>
/// with this value. Note that this md5 hash is not stored with the
/// blob. If the two hashes do not match, the operation will fail
/// with a <see cref="RequestFailedException"/>.
/// </param>
/// <param name="conditions">
/// Optional <see cref="AppendBlobRequestConditions"/> to add
/// conditions on the copying of data to this append blob.
/// </param>
/// <param name="sourceConditions">
/// Optional <see cref="AppendBlobRequestConditions"/> to add
/// conditions on the copying of data from this source blob.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response{BlobAppendInfo}"/> describing the
/// state of the updated append blob.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
public virtual async Task<Response<BlobAppendInfo>> AppendBlockFromUriAsync(
Uri sourceUri,
HttpRange sourceRange = default,
byte[] sourceContentHash = default,
AppendBlobRequestConditions conditions = default,
AppendBlobRequestConditions sourceConditions = default,
CancellationToken cancellationToken = default) =>
await AppendBlockFromUriInternal(
sourceUri,
sourceRange,
sourceContentHash,
conditions,
sourceConditions,
true, // async
cancellationToken)
.ConfigureAwait(false);
/// <summary>
/// The <see cref="AppendBlockFromUriInternal"/> operation commits a new
/// block of data, represented by the <paramref name="sourceUri"/>,
/// to the end of the existing append blob. The
/// <see cref="AppendBlockFromUriInternal"/> operation is only permitted
/// if the blob was created as an append blob.
///
/// For more information, see <see href="https://docs.microsoft.com/en-us/rest/api/storageservices/append-block-from-url" />.
/// </summary>
/// <param name="sourceUri">
/// Specifies the <see cref="Uri"/> of the source blob. The value may
/// be a <see cref="Uri"/> of up to 2 KB in length that specifies a
/// blob. The source blob must either be public or must be
/// authenticated via a shared access signature. If the source blob
/// is public, no authentication is required to perform the operation.
/// </param>
/// <param name="sourceRange">
/// Optionally only upload the bytes of the blob in the
/// <paramref name="sourceUri"/> in the specified range. If this is
/// not specified, the entire source blob contents are uploaded as a
/// single append block.
/// </param>
/// <param name="sourceContentHash">
/// Optional MD5 hash of the append block content from the
/// <paramref name="sourceUri"/>. This hash is used to verify the
/// integrity of the block during transport of the data from the Uri.
/// When this hash is specified, the storage service compares the hash
/// of the content that has arrived from the <paramref name="sourceUri"/>
/// with this value. Note that this md5 hash is not stored with the
/// blob. If the two hashes do not match, the operation will fail
/// with a <see cref="RequestFailedException"/>.
/// </param>
/// <param name="conditions">
/// Optional <see cref="AppendBlobRequestConditions"/> to add
/// conditions on the copying of data to this append blob.
/// </param>
/// <param name="sourceConditions">
/// Optional <see cref="AppendBlobRequestConditions"/> to add
/// conditions on the copying of data from this source blob.
/// </param>
/// <param name="async">
/// Whether to invoke the operation asynchronously.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be cancelled.
/// </param>
/// <returns>
/// A <see cref="Response{BlobAppendInfo}"/> describing the
/// state of the updated append blob.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
private async Task<Response<BlobAppendInfo>> AppendBlockFromUriInternal(
Uri sourceUri,
HttpRange sourceRange,
byte[] sourceContentHash,
AppendBlobRequestConditions conditions,
AppendBlobRequestConditions sourceConditions,
bool async,
CancellationToken cancellationToken = default)
{
using (Pipeline.BeginLoggingScope(nameof(AppendBlobClient)))
{
Pipeline.LogMethodEnter(
nameof(AppendBlobClient),
message:
$"{nameof(Uri)}: {Uri}\n" +
$"{nameof(sourceUri)}: {sourceUri}\n" +
$"{nameof(conditions)}: {conditions}");
try
{
return await BlobRestClient.AppendBlob.AppendBlockFromUriAsync(
ClientDiagnostics,
Pipeline,
Uri,
sourceUri: sourceUri,
sourceRange: sourceRange.ToString(),
sourceContentHash: sourceContentHash,
contentLength: default,
version: Version.ToVersionString(),
encryptionKey: CustomerProvidedKey?.EncryptionKey,
encryptionKeySha256: CustomerProvidedKey?.EncryptionKeyHash,
encryptionAlgorithm: CustomerProvidedKey?.EncryptionAlgorithm,
encryptionScope: EncryptionScope,
leaseId: conditions?.LeaseId,
maxSize: conditions?.IfMaxSizeLessThanOrEqual,
appendPosition: conditions?.IfAppendPositionEqual,
ifModifiedSince: conditions?.IfModifiedSince,
ifUnmodifiedSince: conditions?.IfUnmodifiedSince,
ifMatch: conditions?.IfMatch,
ifNoneMatch: conditions?.IfNoneMatch,
sourceIfModifiedSince: sourceConditions?.IfModifiedSince,
sourceIfUnmodifiedSince: sourceConditions?.IfUnmodifiedSince,
sourceIfMatch: sourceConditions?.IfMatch,
sourceIfNoneMatch: sourceConditions?.IfNoneMatch,
async: async,
operationName: "AppendBlobClient.AppendBlockFromUri",
cancellationToken: cancellationToken)
.ConfigureAwait(false);
}
catch (Exception ex)
{
Pipeline.LogException(ex);
throw;
}
finally
{
Pipeline.LogMethodExit(nameof(AppendBlobClient));
}
}
}
#endregion AppendBlockFromUri
}
/// <summary>
/// Add easy to discover methods to <see cref="BlobContainerClient"/> for
/// creating <see cref="AppendBlobClient"/> instances.
/// </summary>
public static partial class SpecializedBlobExtensions
{
/// <summary>
/// Create a new <see cref="AppendBlobClient"/> object by
/// concatenating <paramref name="blobName"/> to
/// the end of the <paramref name="client"/>'s
/// <see cref="BlobContainerClient.Uri"/>. The new
/// <see cref="AppendBlobClient"/>
/// uses the same request policy pipeline as the
/// <see cref="BlobContainerClient"/>.
/// </summary>
/// <param name="client">The <see cref="BlobContainerClient"/>.</param>
/// <param name="blobName">The name of the append blob.</param>
/// <returns>A new <see cref="AppendBlobClient"/> instance.</returns>
public static AppendBlobClient GetAppendBlobClient(
this BlobContainerClient client,
string blobName)
{
if (client.ClientSideEncryption != default)
{
throw Errors.ClientSideEncryption.TypeNotSupported(typeof(AppendBlobClient));
}
return new AppendBlobClient(
client.Uri.AppendToPath(blobName),
client.Pipeline,
client.Version,
client.ClientDiagnostics,
client.CustomerProvidedKey,
client.EncryptionScope);
}
}
}
| 46.197588 | 141 | 0.571334 | [
"MIT"
] | AzureDataBox/azure-sdk-for-net | sdk/storage/Azure.Storage.Blobs/src/AppendBlobClient.cs | 49,803 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Aws.WafV2.Outputs
{
[OutputType]
public sealed class WebAclRuleStatementOrStatementStatementNotStatementStatementNotStatementStatementXssMatchStatementFieldToMatch
{
/// <summary>
/// Inspect all query arguments.
/// </summary>
public readonly Outputs.WebAclRuleStatementOrStatementStatementNotStatementStatementNotStatementStatementXssMatchStatementFieldToMatchAllQueryArguments? AllQueryArguments;
/// <summary>
/// Inspect the request body, which immediately follows the request headers.
/// </summary>
public readonly Outputs.WebAclRuleStatementOrStatementStatementNotStatementStatementNotStatementStatementXssMatchStatementFieldToMatchBody? Body;
/// <summary>
/// Inspect the HTTP method. The method indicates the type of operation that the request is asking the origin to perform.
/// </summary>
public readonly Outputs.WebAclRuleStatementOrStatementStatementNotStatementStatementNotStatementStatementXssMatchStatementFieldToMatchMethod? Method;
/// <summary>
/// Inspect the query string. This is the part of a URL that appears after a `?` character, if any.
/// </summary>
public readonly Outputs.WebAclRuleStatementOrStatementStatementNotStatementStatementNotStatementStatementXssMatchStatementFieldToMatchQueryString? QueryString;
/// <summary>
/// Inspect a single header. See Single Header below for details.
/// </summary>
public readonly Outputs.WebAclRuleStatementOrStatementStatementNotStatementStatementNotStatementStatementXssMatchStatementFieldToMatchSingleHeader? SingleHeader;
/// <summary>
/// Inspect a single query argument. See Single Query Argument below for details.
/// </summary>
public readonly Outputs.WebAclRuleStatementOrStatementStatementNotStatementStatementNotStatementStatementXssMatchStatementFieldToMatchSingleQueryArgument? SingleQueryArgument;
/// <summary>
/// Inspect the request URI path. This is the part of a web request that identifies a resource, for example, `/images/daily-ad.jpg`.
/// </summary>
public readonly Outputs.WebAclRuleStatementOrStatementStatementNotStatementStatementNotStatementStatementXssMatchStatementFieldToMatchUriPath? UriPath;
[OutputConstructor]
private WebAclRuleStatementOrStatementStatementNotStatementStatementNotStatementStatementXssMatchStatementFieldToMatch(
Outputs.WebAclRuleStatementOrStatementStatementNotStatementStatementNotStatementStatementXssMatchStatementFieldToMatchAllQueryArguments? allQueryArguments,
Outputs.WebAclRuleStatementOrStatementStatementNotStatementStatementNotStatementStatementXssMatchStatementFieldToMatchBody? body,
Outputs.WebAclRuleStatementOrStatementStatementNotStatementStatementNotStatementStatementXssMatchStatementFieldToMatchMethod? method,
Outputs.WebAclRuleStatementOrStatementStatementNotStatementStatementNotStatementStatementXssMatchStatementFieldToMatchQueryString? queryString,
Outputs.WebAclRuleStatementOrStatementStatementNotStatementStatementNotStatementStatementXssMatchStatementFieldToMatchSingleHeader? singleHeader,
Outputs.WebAclRuleStatementOrStatementStatementNotStatementStatementNotStatementStatementXssMatchStatementFieldToMatchSingleQueryArgument? singleQueryArgument,
Outputs.WebAclRuleStatementOrStatementStatementNotStatementStatementNotStatementStatementXssMatchStatementFieldToMatchUriPath? uriPath)
{
AllQueryArguments = allQueryArguments;
Body = body;
Method = method;
QueryString = queryString;
SingleHeader = singleHeader;
SingleQueryArgument = singleQueryArgument;
UriPath = uriPath;
}
}
}
| 59.450704 | 183 | 0.780147 | [
"ECL-2.0",
"Apache-2.0"
] | Otanikotani/pulumi-aws | sdk/dotnet/WafV2/Outputs/WebAclRuleStatementOrStatementStatementNotStatementStatementNotStatementStatementXssMatchStatementFieldToMatch.cs | 4,221 | C# |
/*
Copyright(c) 2009, Stefan Simek
Copyright(c) 2016, Vladyslav Taranov
MIT License
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#if !PHONE8
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
#if FEAT_IKVM
using IKVM.Reflection;
using IKVM.Reflection.Emit;
using Type = IKVM.Reflection.Type;
using MissingMethodException = System.MissingMethodException;
using MissingMemberException = System.MissingMemberException;
using DefaultMemberAttribute = System.Reflection.DefaultMemberAttribute;
using Attribute = IKVM.Reflection.CustomAttributeData;
using BindingFlags = IKVM.Reflection.BindingFlags;
#else
using System.Reflection;
using System.Reflection.Emit;
#endif
namespace TriAxis.RunSharp
{
public sealed class FieldGen : Operand, IMemberInfo, IDelayedCompletion
{
readonly TypeGen _owner;
readonly FieldAttributes _attrs;
readonly Type _type;
readonly FieldBuilder _fb;
List<AttributeGen> _customAttributes = new List<AttributeGen>();
public ITypeMapper TypeMapper => _owner.TypeMapper;
internal FieldGen(TypeGen owner, string name, Type type, FieldAttributes attrs)
{
_owner = owner;
_attrs = attrs;
Name = name;
_type = type;
_fb = owner.TypeBuilder.DefineField(name, type, attrs);
owner.RegisterForCompletion(this);
}
public override Type GetReturnType(ITypeMapper typeMapper) => _type;
public string Name { get; }
public bool IsStatic => (_attrs & FieldAttributes.Static) != 0;
#region Custom Attributes
#if FEAT_IKVM
public FieldGen Attribute(System.Type attributeType)
{
return Attribute(TypeMapper.MapType(attributeType));
}
#endif
public FieldGen Attribute(AttributeType type)
{
BeginAttribute(type);
return this;
}
#if FEAT_IKVM
public FieldGen Attribute(System.Type attributeType, params object[] args)
{
return Attribute(TypeMapper.MapType(attributeType), args);
}
#endif
public FieldGen Attribute(AttributeType type, params object[] args)
{
BeginAttribute(type, args);
return this;
}
#if FEAT_IKVM
public AttributeGen<FieldGen> BeginAttribute(System.Type attributeType)
{
return BeginAttribute(TypeMapper.MapType(attributeType));
}
#endif
public AttributeGen<FieldGen> BeginAttribute(AttributeType type)
{
return BeginAttribute(type, EmptyArray<object>.Instance);
}
#if FEAT_IKVM
public AttributeGen<FieldGen> BeginAttribute(System.Type attributeType, params object[] args)
{
return BeginAttribute(TypeMapper.MapType(attributeType), args);
}
#endif
public AttributeGen<FieldGen> BeginAttribute(AttributeType type, params object[] args)
{
return AttributeGen<FieldGen>.CreateAndAdd(this, ref _customAttributes, AttributeTargets.Field, type, args, _owner.TypeMapper);
}
#endregion
protected internal override void EmitGet(CodeGen g)
{
OperandExtensions.SetLeakedState(this, false);
if (!IsStatic)
{
if (g.Context.IsStatic || g.Context.OwnerType != _owner.TypeBuilder)
throw new InvalidOperationException(Properties.Messages.ErrInvalidFieldContext);
g.IL.Emit(OpCodes.Ldarg_0);
g.IL.Emit(OpCodes.Ldfld, _fb);
}
else
g.IL.Emit(OpCodes.Ldsfld, _fb);
}
protected internal override void EmitSet(CodeGen g, Operand value, bool allowExplicitConversion)
{
OperandExtensions.SetLeakedState(this, false);
if (!IsStatic)
{
if (g.Context.IsStatic || g.Context.OwnerType != _owner.TypeBuilder)
throw new InvalidOperationException(Properties.Messages.ErrInvalidFieldContext);
g.IL.Emit(OpCodes.Ldarg_0);
}
g.EmitGetHelper(value, _type, allowExplicitConversion);
g.IL.Emit(IsStatic ? OpCodes.Stsfld : OpCodes.Stfld, _fb);
}
protected internal override void EmitAddressOf(CodeGen g)
{
OperandExtensions.SetLeakedState(this, false);
if (!IsStatic)
{
if (g.Context.IsStatic || g.Context.OwnerType != _owner.TypeBuilder)
throw new InvalidOperationException(Properties.Messages.ErrInvalidFieldContext);
g.IL.Emit(OpCodes.Ldarg_0);
g.IL.Emit(OpCodes.Ldflda, _fb);
}
else
g.IL.Emit(OpCodes.Ldsflda, _fb);
}
protected internal override bool TrivialAccess => true;
#region IMemberInfo Members
MemberInfo IMemberInfo.Member => _fb;
Type IMemberInfo.ReturnType => _type;
Type[] IMemberInfo.ParameterTypes => Type.EmptyTypes;
bool IMemberInfo.IsParameterArray => false;
bool IMemberInfo.IsOverride => false;
#endregion
#region IDelayedCompletion Members
void IDelayedCompletion.Complete()
{
AttributeGen.ApplyList(ref _customAttributes, _fb.SetCustomAttribute);
}
#endregion
}
}
#endif
| 27.638095 | 130 | 0.7357 | [
"MIT"
] | AqlaSolutions/runsharp | RunSharpShared/FieldGen.cs | 5,804 | C# |
using Microsoft.Xna.Framework;
using System.ComponentModel;
using Terraria.ModLoader.Config;
// This file defines custom data type that represents Gradient data type that can be used in ModConfig classes.
namespace ExampleMod.Common.Configs.CustomDataTypes
{
public class Gradient
{
[Tooltip("The color the gradient starts at")]
[DefaultValue(typeof(Color), "0, 0, 255, 255")]
public Color start = Color.Blue; // For sub-objects, you'll want to make sure to set defaults in constructor or field initializer.
[Tooltip("The color the gradient ends at")]
[DefaultValue(typeof(Color), "255, 0, 0, 255")]
public Color end = Color.Red;
public override bool Equals(object obj) {
if (obj is Gradient other)
return start == other.start && end == other.end;
return base.Equals(obj);
}
public override int GetHashCode() {
return new { start, end }.GetHashCode();
}
}
}
| 32.071429 | 132 | 0.719376 | [
"MIT"
] | blushiemagic/tModLoader | ExampleMod/Common/Configs/CustomDataTypes/Gradient.cs | 900 | C# |
using MySocketServerTool.RequestInfo;
using MySocketServerTool.Session;
using SuperSocket.SocketBase.Command;
using SuperSocket.SocketBase.Protocol;
namespace MySocketServerTool.Command
{
public class FinsRWData : CommandBase<FinsSession, FinsTcpRequestInfo>
{
public override void ExecuteCommand(FinsSession session, FinsTcpRequestInfo requestInfo)
{
//session.Send($"Hello {session.RemoteEndPoint.Address} {session.RemoteEndPoint.Port} {requestInfo.Body}");
//session.Send(requestInfo.Body, 0, requestInfo.Body.Length);
session.Send(requestInfo.Data, 0, requestInfo.Data.Length);
}
}
}
| 36.777778 | 119 | 0.732628 | [
"Apache-2.0"
] | YAOZZJ/LTSProject | LTSProject/MySocketServerTool/Command/FinsRWData.cs | 664 | C# |
// Copyright 2021 Google LLC
//
// 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
//
// https://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.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Iam.Admin.V1.Snippets
{
using Google.Api.Gax;
using Google.Cloud.Iam.Admin.V1;
using System;
public sealed partial class GeneratedIAMClientStandaloneSnippets
{
/// <summary>Snippet for QueryTestablePermissions</summary>
/// <remarks>
/// This snippet has been automatically generated for illustrative purposes only.
/// It may require modifications to work in your environment.
/// </remarks>
public void QueryTestablePermissionsRequestObject()
{
// Create client
IAMClient iAMClient = IAMClient.Create();
// Initialize request argument(s)
QueryTestablePermissionsRequest request = new QueryTestablePermissionsRequest
{
FullResourceName = "",
};
// Make the request
PagedEnumerable<QueryTestablePermissionsResponse, Permission> response = iAMClient.QueryTestablePermissions(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (Permission item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (QueryTestablePermissionsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Permission item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Permission> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Permission item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
}
}
}
| 40.263158 | 129 | 0.620261 | [
"Apache-2.0"
] | googleapis/googleapis-gen | google/iam/admin/v1/google-cloud-iam-admin-v1-csharp/Google.Cloud.Iam.Admin.V1.StandaloneSnippets/IAMClient.QueryTestablePermissionsRequestObjectSnippet.g.cs | 3,060 | C# |
using System;
using System.Collections.Generic;
using UnityEditor.Animations;
using UnityEngine;
using VRC.SDK3.Avatars.Components;
using VRC.SDKBase;
namespace Hai.ComboGesture.Scripts.Editor.Internal.Reused
{
internal class Machinist
{
private readonly AnimatorStateMachine _machine;
private readonly AnimationClip _emptyClip;
internal Machinist(AnimatorStateMachine machine, AnimationClip emptyClip)
{
_machine = machine;
_emptyClip = emptyClip;
}
internal Machinist WithEntryPosition(int x, int y)
{
_machine.entryPosition = AnimatorGenerator.GridPosition(x, y);
return this;
}
internal Machinist WithExitPosition(int x, int y)
{
_machine.exitPosition = AnimatorGenerator.GridPosition(x, y);
return this;
}
internal Machinist WithAnyStatePosition(int x, int y)
{
_machine.anyStatePosition = AnimatorGenerator.GridPosition(x, y);
return this;
}
internal Statist NewState(string name, int x, int y)
{
var state = _machine.AddState(name, AnimatorGenerator.GridPosition(x, y));
state.motion = _emptyClip;
state.writeDefaultValues = false;
return new Statist(state);
}
public Transitionist AnyTransitionsTo(Statist destination)
{
return new Transitionist(Statist.NewDefaultTransition(_machine.AddAnyStateTransition(destination.State)));
}
public AnimatorStateMachine ExposeMachine()
{
return _machine;
}
}
internal class Statist
{
internal readonly AnimatorState State;
private VRCAvatarParameterDriver _driver;
private VRCAnimatorTrackingControl _tracking;
internal Statist(AnimatorState state)
{
State = state;
}
internal Statist WithAnimation(Motion clip)
{
State.motion = clip;
return this;
}
internal Transitionist TransitionsTo(Statist destination)
{
return new Transitionist(NewDefaultTransition(State.AddTransition(destination.State)));
}
internal Statist AutomaticallyMovesTo(Statist destination)
{
var transition = NewDefaultTransition(State.AddTransition(destination.State));
transition.hasExitTime = true;
return this;
}
internal Transitionist Exits()
{
return new Transitionist(NewDefaultTransition(State.AddExitTransition()));
}
internal static AnimatorStateTransition NewDefaultTransition(AnimatorStateTransition transition)
{
transition.duration = 0;
transition.hasExitTime = false;
transition.exitTime = 0;
transition.hasFixedDuration = true;
transition.offset = 0;
transition.interruptionSource = TransitionInterruptionSource.None;
transition.orderedInterruption = true;
transition.canTransitionToSelf = true;
return transition;
}
internal Statist Drives(IntParameterist parameterist, int value)
{
CreateDriverBehaviorIfNotExists();
_driver.parameters.Add(new VRC_AvatarParameterDriver.Parameter
{
type = VRC_AvatarParameterDriver.ChangeType.Set,
name = parameterist.Name, value = value
});
return this;
}
internal Statist Drives(FloatParameterist parameterist, float value)
{
CreateDriverBehaviorIfNotExists();
_driver.parameters.Add(new VRC_AvatarParameterDriver.Parameter
{
type = VRC_AvatarParameterDriver.ChangeType.Set,
name = parameterist.Name, value = value
});
return this;
}
internal Statist DrivingIncreases(FloatParameterist parameterist, float additiveValue)
{
CreateDriverBehaviorIfNotExists();
_driver.parameters.Add(new VRC_AvatarParameterDriver.Parameter
{
type = VRC_AvatarParameterDriver.ChangeType.Add,
name = parameterist.Name, value = additiveValue
});
return this;
}
internal Statist DrivingDecreases(FloatParameterist parameterist, float positiveValueToDecreaseBy)
{
CreateDriverBehaviorIfNotExists();
_driver.parameters.Add(new VRC_AvatarParameterDriver.Parameter
{
type = VRC_AvatarParameterDriver.ChangeType.Add,
name = parameterist.Name, value = -positiveValueToDecreaseBy
});
return this;
}
internal Statist Drives(BoolParameterist parameterist, bool value)
{
CreateDriverBehaviorIfNotExists();
_driver.parameters.Add(new VRC_AvatarParameterDriver.Parameter
{
name = parameterist.Name, value = value ? 1 : 0
});
return this;
}
private void CreateDriverBehaviorIfNotExists()
{
if (_driver != null) return;
_driver = State.AddStateMachineBehaviour<VRCAvatarParameterDriver>();
_driver.parameters = new List<VRC_AvatarParameterDriver.Parameter>();
}
public Statist WithWriteDefaultsSetTo(bool shouldWriteDefaults)
{
State.writeDefaultValues = shouldWriteDefaults;
return this;
}
public Statist TrackingTracks(TrackingElement element)
{
CreateTrackingBehaviorIfNotExists();
SettingElementTo(element, VRC_AnimatorTrackingControl.TrackingType.Tracking);
return this;
}
public Statist TrackingAnimates(TrackingElement element)
{
CreateTrackingBehaviorIfNotExists();
SettingElementTo(element, VRC_AnimatorTrackingControl.TrackingType.Animation);
return this;
}
private void SettingElementTo(TrackingElement element, VRC_AnimatorTrackingControl.TrackingType target)
{
switch (element)
{
case TrackingElement.Head:
_tracking.trackingHead = target;
break;
case TrackingElement.LeftHand:
_tracking.trackingLeftHand = target;
break;
case TrackingElement.RightHand:
_tracking.trackingRightHand = target;
break;
case TrackingElement.Hip:
_tracking.trackingHip = target;
break;
case TrackingElement.LeftFoot:
_tracking.trackingLeftFoot = target;
break;
case TrackingElement.RightFoot:
_tracking.trackingRightFoot = target;
break;
case TrackingElement.LeftFingers:
_tracking.trackingLeftFingers = target;
break;
case TrackingElement.RightFingers:
_tracking.trackingRightFingers = target;
break;
case TrackingElement.Eyes:
_tracking.trackingEyes = target;
break;
case TrackingElement.Mouth:
_tracking.trackingMouth = target;
break;
default:
throw new ArgumentOutOfRangeException(nameof(element), element, null);
}
}
private void CreateTrackingBehaviorIfNotExists()
{
if (_tracking != null) return;
_tracking = State.AddStateMachineBehaviour<VRCAnimatorTrackingControl>();
}
internal enum TrackingElement
{
Head,
LeftHand,
RightHand,
Hip,
LeftFoot,
RightFoot,
LeftFingers,
RightFingers,
Eyes,
Mouth
}
}
public class Transitionist
{
private readonly AnimatorStateTransition _transition;
internal Transitionist(AnimatorStateTransition transition)
{
_transition = transition;
}
internal BuildingIntTransitionist When(IntParameterist parameter)
{
return new BuildingIntTransitionist(new TransitionContinuationist(_transition), _transition, parameter);
}
internal BuildingFloatTransitionist When(FloatParameterist parameter)
{
return new BuildingFloatTransitionist(new TransitionContinuationist(_transition), _transition, parameter);
}
internal BuildingBoolTransitionist When(BoolParameterist parameter)
{
return new BuildingBoolTransitionist(new TransitionContinuationist(_transition), _transition, parameter);
}
internal TransitionContinuationist Whenever(Action<TransitionContinuationist> action)
{
var transitionContinuationist = new TransitionContinuationist(_transition);
action(transitionContinuationist);
return transitionContinuationist;
}
internal TransitionContinuationist Whenever()
{
return new TransitionContinuationist(_transition);
}
public class TransitionContinuationist
{
private readonly AnimatorStateTransition _transition;
internal TransitionContinuationist(AnimatorStateTransition transition)
{
_transition = transition;
}
internal BuildingIntTransitionist And(IntParameterist parameter)
{
return new BuildingIntTransitionist(this, _transition, parameter);
}
internal BuildingFloatTransitionist And(FloatParameterist parameter)
{
return new BuildingFloatTransitionist(this, _transition, parameter);
}
internal BuildingBoolTransitionist And(BoolParameterist parameter)
{
return new BuildingBoolTransitionist(this, _transition, parameter);
}
internal TransitionContinuationist AndWhenever(Action<TransitionContinuationist> action)
{
action(this);
return this;
}
}
internal class BuildingIntTransitionist
{
private readonly TransitionContinuationist _transitionist;
private readonly AnimatorStateTransition _transition;
private readonly IntParameterist _parameterist;
internal BuildingIntTransitionist(TransitionContinuationist transitionist, AnimatorStateTransition transition, IntParameterist parameterist)
{
_transitionist = transitionist;
_transition = transition;
_parameterist = parameterist;
}
internal TransitionContinuationist IsEqualTo(int value)
{
_transition.AddCondition(AnimatorConditionMode.Equals, value, _parameterist.Name);
return _transitionist;
}
internal TransitionContinuationist IsNotEqualTo(int value)
{
_transition.AddCondition(AnimatorConditionMode.NotEqual, value, _parameterist.Name);
return _transitionist;
}
internal TransitionContinuationist IsLesserThan(int value)
{
_transition.AddCondition(AnimatorConditionMode.Less, value, _parameterist.Name);
return _transitionist;
}
internal TransitionContinuationist IsGreaterThan(int value)
{
_transition.AddCondition(AnimatorConditionMode.Greater, value, _parameterist.Name);
return _transitionist;
}
}
internal class BuildingFloatTransitionist
{
private readonly TransitionContinuationist _transitionist;
private readonly AnimatorStateTransition _transition;
private readonly FloatParameterist _parameterist;
internal BuildingFloatTransitionist(TransitionContinuationist transitionist, AnimatorStateTransition transition, FloatParameterist parameterist)
{
_transitionist = transitionist;
_transition = transition;
_parameterist = parameterist;
}
internal TransitionContinuationist IsLesserThan(float value)
{
_transition.AddCondition(AnimatorConditionMode.Less, value, _parameterist.Name);
return _transitionist;
}
internal TransitionContinuationist IsGreaterThan(float value)
{
_transition.AddCondition(AnimatorConditionMode.Greater, value, _parameterist.Name);
return _transitionist;
}
}
internal class BuildingBoolTransitionist
{
private readonly TransitionContinuationist _transitionist;
private readonly AnimatorStateTransition _transition;
private readonly BoolParameterist _parameterist;
internal BuildingBoolTransitionist(TransitionContinuationist transitionist, AnimatorStateTransition transition, BoolParameterist parameterist)
{
_transitionist = transitionist;
_transition = transition;
_parameterist = parameterist;
}
internal TransitionContinuationist IsTrue()
{
_transition.AddCondition(AnimatorConditionMode.If, 0, _parameterist.Name);
return _transitionist;
}
internal TransitionContinuationist IsFalse()
{
_transition.AddCondition(AnimatorConditionMode.IfNot, 0, _parameterist.Name);
return _transitionist;
}
internal TransitionContinuationist Is(bool value)
{
return value ? IsTrue() : IsFalse();
}
}
public Transitionist WithSourceInterruption()
{
_transition.interruptionSource = TransitionInterruptionSource.Source;
return this;
}
public Transitionist WithTransitionDuration(float transitionDuration)
{
_transition.duration = transitionDuration;
return this;
}
public Transitionist WithNoOrderedInterruption()
{
_transition.orderedInterruption = false;
return this;
}
public Transitionist WithNoTransitionToSelf()
{
_transition.canTransitionToSelf = false;
return this;
}
}
}
| 34.536697 | 156 | 0.606521 | [
"MIT"
] | SpiralP/combo-gesture-expressions-av3 | Assets/Hai/ComboGesture/Scripts/Editor/Internal/Reused/HaiMachinist.cs | 15,060 | C# |
using System;
using UnityEngine;
using UnityEngine.Experimental.PlayerLoop;
namespace Components {
public class Spinning : MonoBehaviour {
public Vector3 Speed;
private void Update() {
transform.Rotate(Speed * Time.deltaTime);
}
}
}
| 18.625 | 53 | 0.61745 | [
"MIT"
] | MouradZzz/TankArena | Assets/Scripts/Components/Spinning.cs | 300 | C# |
// <auto-generated> This file has been auto generated by EF Core Power Tools. </auto-generated>
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace WebApplication.API.Models.Northwind;
[Table("order_details", Schema = "public")]
public partial class OrderDetail
{
[Key]
[Column("order_id")]
public int OrderId { get; set; }
[Key]
[Column("product_id")]
public int ProductId { get; set; }
[Column("unit_price")]
public float UnitPrice { get; set; }
[Column("quantity")]
public short Quantity { get; set; }
[Column("discount")]
public float Discount { get; set; }
[ForeignKey(nameof(OrderId))]
[InverseProperty("OrderDetails")]
public virtual Order Order { get; set; }
[ForeignKey(nameof(ProductId))]
[InverseProperty("OrderDetails")]
public virtual Product Product { get; set; }
}
| 29.96875 | 96 | 0.692388 | [
"MIT"
] | mehmetuken/AutoFilterer | sandbox/WebApplication.API/Models/Northwind/OrderDetail.cs | 961 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Resources {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class TestFiles {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal TestFiles() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("SevenZipExtractor.Tests.TestFiles", typeof(TestFiles).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized resource of type System.Byte[].
/// </summary>
internal static byte[] ansimate_arj {
get {
object obj = ResourceManager.GetObject("ansimate_arj", resourceCulture);
return ((byte[])(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Byte[].
/// </summary>
internal static byte[] lzh {
get {
object obj = ResourceManager.GetObject("lzh", resourceCulture);
return ((byte[])(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Byte[].
/// </summary>
internal static byte[] rar {
get {
object obj = ResourceManager.GetObject("rar", resourceCulture);
return ((byte[])(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Byte[].
/// </summary>
internal static byte[] SevenZip {
get {
object obj = ResourceManager.GetObject("SevenZip", resourceCulture);
return ((byte[])(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Byte[].
/// </summary>
internal static byte[] zip {
get {
object obj = ResourceManager.GetObject("zip", resourceCulture);
return ((byte[])(obj));
}
}
}
}
| 38.614035 | 178 | 0.554521 | [
"MIT"
] | Mattlk13/SevenZipExtractor | SevenZipExtractor.Tests/TestFiles.Designer.cs | 4,404 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.