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
/* * Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ namespace TencentCloud.Tat.V20201028 { using Newtonsoft.Json; using System.Threading.Tasks; using TencentCloud.Common; using TencentCloud.Common.Profile; using TencentCloud.Tat.V20201028.Models; public class TatClient : AbstractClient{ private const string endpoint = "tat.tencentcloudapi.com"; private const string version = "2020-10-28"; /// <summary> /// Client constructor. /// </summary> /// <param name="credential">Credentials.</param> /// <param name="region">Region name, such as "ap-guangzhou".</param> public TatClient(Credential credential, string region) : this(credential, region, new ClientProfile()) { } /// <summary> /// Client Constructor. /// </summary> /// <param name="credential">Credentials.</param> /// <param name="region">Region name, such as "ap-guangzhou".</param> /// <param name="profile">Client profiles.</param> public TatClient(Credential credential, string region, ClientProfile profile) : base(endpoint, version, credential, region, profile) { } /// <summary> /// 取消一台或多台CVM实例执行的命令 /// /// * 如果命令还未下发到agent,任务状态处于处于PENDING、DELIVERING、DELIVER_DELAYED,取消后任务状态是CANCELLED /// * 如果命令已下发到agent,任务状态处于RUNNING, 取消后任务状态是TERMINATED /// </summary> /// <param name="req"><see cref="CancelInvocationRequest"/></param> /// <returns><see cref="CancelInvocationResponse"/></returns> public async Task<CancelInvocationResponse> CancelInvocation(CancelInvocationRequest req) { JsonResponseModel<CancelInvocationResponse> rsp = null; try { var strResp = await this.InternalRequest(req, "CancelInvocation"); rsp = JsonConvert.DeserializeObject<JsonResponseModel<CancelInvocationResponse>>(strResp); } catch (JsonSerializationException e) { throw new TencentCloudSDKException(e.Message); } return rsp.Response; } /// <summary> /// 取消一台或多台CVM实例执行的命令 /// /// * 如果命令还未下发到agent,任务状态处于处于PENDING、DELIVERING、DELIVER_DELAYED,取消后任务状态是CANCELLED /// * 如果命令已下发到agent,任务状态处于RUNNING, 取消后任务状态是TERMINATED /// </summary> /// <param name="req"><see cref="CancelInvocationRequest"/></param> /// <returns><see cref="CancelInvocationResponse"/></returns> public CancelInvocationResponse CancelInvocationSync(CancelInvocationRequest req) { JsonResponseModel<CancelInvocationResponse> rsp = null; try { var strResp = this.InternalRequestSync(req, "CancelInvocation"); rsp = JsonConvert.DeserializeObject<JsonResponseModel<CancelInvocationResponse>>(strResp); } catch (JsonSerializationException e) { throw new TencentCloudSDKException(e.Message); } return rsp.Response; } /// <summary> /// 此接口用于创建命令。 /// </summary> /// <param name="req"><see cref="CreateCommandRequest"/></param> /// <returns><see cref="CreateCommandResponse"/></returns> public async Task<CreateCommandResponse> CreateCommand(CreateCommandRequest req) { JsonResponseModel<CreateCommandResponse> rsp = null; try { var strResp = await this.InternalRequest(req, "CreateCommand"); rsp = JsonConvert.DeserializeObject<JsonResponseModel<CreateCommandResponse>>(strResp); } catch (JsonSerializationException e) { throw new TencentCloudSDKException(e.Message); } return rsp.Response; } /// <summary> /// 此接口用于创建命令。 /// </summary> /// <param name="req"><see cref="CreateCommandRequest"/></param> /// <returns><see cref="CreateCommandResponse"/></returns> public CreateCommandResponse CreateCommandSync(CreateCommandRequest req) { JsonResponseModel<CreateCommandResponse> rsp = null; try { var strResp = this.InternalRequestSync(req, "CreateCommand"); rsp = JsonConvert.DeserializeObject<JsonResponseModel<CreateCommandResponse>>(strResp); } catch (JsonSerializationException e) { throw new TencentCloudSDKException(e.Message); } return rsp.Response; } /// <summary> /// 此接口用于创建执行器。 /// </summary> /// <param name="req"><see cref="CreateInvokerRequest"/></param> /// <returns><see cref="CreateInvokerResponse"/></returns> public async Task<CreateInvokerResponse> CreateInvoker(CreateInvokerRequest req) { JsonResponseModel<CreateInvokerResponse> rsp = null; try { var strResp = await this.InternalRequest(req, "CreateInvoker"); rsp = JsonConvert.DeserializeObject<JsonResponseModel<CreateInvokerResponse>>(strResp); } catch (JsonSerializationException e) { throw new TencentCloudSDKException(e.Message); } return rsp.Response; } /// <summary> /// 此接口用于创建执行器。 /// </summary> /// <param name="req"><see cref="CreateInvokerRequest"/></param> /// <returns><see cref="CreateInvokerResponse"/></returns> public CreateInvokerResponse CreateInvokerSync(CreateInvokerRequest req) { JsonResponseModel<CreateInvokerResponse> rsp = null; try { var strResp = this.InternalRequestSync(req, "CreateInvoker"); rsp = JsonConvert.DeserializeObject<JsonResponseModel<CreateInvokerResponse>>(strResp); } catch (JsonSerializationException e) { throw new TencentCloudSDKException(e.Message); } return rsp.Response; } /// <summary> /// 此接口用于删除命令。 /// 如果命令与执行器关联,则无法被删除。 /// </summary> /// <param name="req"><see cref="DeleteCommandRequest"/></param> /// <returns><see cref="DeleteCommandResponse"/></returns> public async Task<DeleteCommandResponse> DeleteCommand(DeleteCommandRequest req) { JsonResponseModel<DeleteCommandResponse> rsp = null; try { var strResp = await this.InternalRequest(req, "DeleteCommand"); rsp = JsonConvert.DeserializeObject<JsonResponseModel<DeleteCommandResponse>>(strResp); } catch (JsonSerializationException e) { throw new TencentCloudSDKException(e.Message); } return rsp.Response; } /// <summary> /// 此接口用于删除命令。 /// 如果命令与执行器关联,则无法被删除。 /// </summary> /// <param name="req"><see cref="DeleteCommandRequest"/></param> /// <returns><see cref="DeleteCommandResponse"/></returns> public DeleteCommandResponse DeleteCommandSync(DeleteCommandRequest req) { JsonResponseModel<DeleteCommandResponse> rsp = null; try { var strResp = this.InternalRequestSync(req, "DeleteCommand"); rsp = JsonConvert.DeserializeObject<JsonResponseModel<DeleteCommandResponse>>(strResp); } catch (JsonSerializationException e) { throw new TencentCloudSDKException(e.Message); } return rsp.Response; } /// <summary> /// 此接口用于删除执行器。 /// </summary> /// <param name="req"><see cref="DeleteInvokerRequest"/></param> /// <returns><see cref="DeleteInvokerResponse"/></returns> public async Task<DeleteInvokerResponse> DeleteInvoker(DeleteInvokerRequest req) { JsonResponseModel<DeleteInvokerResponse> rsp = null; try { var strResp = await this.InternalRequest(req, "DeleteInvoker"); rsp = JsonConvert.DeserializeObject<JsonResponseModel<DeleteInvokerResponse>>(strResp); } catch (JsonSerializationException e) { throw new TencentCloudSDKException(e.Message); } return rsp.Response; } /// <summary> /// 此接口用于删除执行器。 /// </summary> /// <param name="req"><see cref="DeleteInvokerRequest"/></param> /// <returns><see cref="DeleteInvokerResponse"/></returns> public DeleteInvokerResponse DeleteInvokerSync(DeleteInvokerRequest req) { JsonResponseModel<DeleteInvokerResponse> rsp = null; try { var strResp = this.InternalRequestSync(req, "DeleteInvoker"); rsp = JsonConvert.DeserializeObject<JsonResponseModel<DeleteInvokerResponse>>(strResp); } catch (JsonSerializationException e) { throw new TencentCloudSDKException(e.Message); } return rsp.Response; } /// <summary> /// 此接口用于查询自动化助手客户端的状态。 /// </summary> /// <param name="req"><see cref="DescribeAutomationAgentStatusRequest"/></param> /// <returns><see cref="DescribeAutomationAgentStatusResponse"/></returns> public async Task<DescribeAutomationAgentStatusResponse> DescribeAutomationAgentStatus(DescribeAutomationAgentStatusRequest req) { JsonResponseModel<DescribeAutomationAgentStatusResponse> rsp = null; try { var strResp = await this.InternalRequest(req, "DescribeAutomationAgentStatus"); rsp = JsonConvert.DeserializeObject<JsonResponseModel<DescribeAutomationAgentStatusResponse>>(strResp); } catch (JsonSerializationException e) { throw new TencentCloudSDKException(e.Message); } return rsp.Response; } /// <summary> /// 此接口用于查询自动化助手客户端的状态。 /// </summary> /// <param name="req"><see cref="DescribeAutomationAgentStatusRequest"/></param> /// <returns><see cref="DescribeAutomationAgentStatusResponse"/></returns> public DescribeAutomationAgentStatusResponse DescribeAutomationAgentStatusSync(DescribeAutomationAgentStatusRequest req) { JsonResponseModel<DescribeAutomationAgentStatusResponse> rsp = null; try { var strResp = this.InternalRequestSync(req, "DescribeAutomationAgentStatus"); rsp = JsonConvert.DeserializeObject<JsonResponseModel<DescribeAutomationAgentStatusResponse>>(strResp); } catch (JsonSerializationException e) { throw new TencentCloudSDKException(e.Message); } return rsp.Response; } /// <summary> /// 此接口用于查询命令详情。 /// </summary> /// <param name="req"><see cref="DescribeCommandsRequest"/></param> /// <returns><see cref="DescribeCommandsResponse"/></returns> public async Task<DescribeCommandsResponse> DescribeCommands(DescribeCommandsRequest req) { JsonResponseModel<DescribeCommandsResponse> rsp = null; try { var strResp = await this.InternalRequest(req, "DescribeCommands"); rsp = JsonConvert.DeserializeObject<JsonResponseModel<DescribeCommandsResponse>>(strResp); } catch (JsonSerializationException e) { throw new TencentCloudSDKException(e.Message); } return rsp.Response; } /// <summary> /// 此接口用于查询命令详情。 /// </summary> /// <param name="req"><see cref="DescribeCommandsRequest"/></param> /// <returns><see cref="DescribeCommandsResponse"/></returns> public DescribeCommandsResponse DescribeCommandsSync(DescribeCommandsRequest req) { JsonResponseModel<DescribeCommandsResponse> rsp = null; try { var strResp = this.InternalRequestSync(req, "DescribeCommands"); rsp = JsonConvert.DeserializeObject<JsonResponseModel<DescribeCommandsResponse>>(strResp); } catch (JsonSerializationException e) { throw new TencentCloudSDKException(e.Message); } return rsp.Response; } /// <summary> /// 此接口用于查询执行任务详情。 /// </summary> /// <param name="req"><see cref="DescribeInvocationTasksRequest"/></param> /// <returns><see cref="DescribeInvocationTasksResponse"/></returns> public async Task<DescribeInvocationTasksResponse> DescribeInvocationTasks(DescribeInvocationTasksRequest req) { JsonResponseModel<DescribeInvocationTasksResponse> rsp = null; try { var strResp = await this.InternalRequest(req, "DescribeInvocationTasks"); rsp = JsonConvert.DeserializeObject<JsonResponseModel<DescribeInvocationTasksResponse>>(strResp); } catch (JsonSerializationException e) { throw new TencentCloudSDKException(e.Message); } return rsp.Response; } /// <summary> /// 此接口用于查询执行任务详情。 /// </summary> /// <param name="req"><see cref="DescribeInvocationTasksRequest"/></param> /// <returns><see cref="DescribeInvocationTasksResponse"/></returns> public DescribeInvocationTasksResponse DescribeInvocationTasksSync(DescribeInvocationTasksRequest req) { JsonResponseModel<DescribeInvocationTasksResponse> rsp = null; try { var strResp = this.InternalRequestSync(req, "DescribeInvocationTasks"); rsp = JsonConvert.DeserializeObject<JsonResponseModel<DescribeInvocationTasksResponse>>(strResp); } catch (JsonSerializationException e) { throw new TencentCloudSDKException(e.Message); } return rsp.Response; } /// <summary> /// 此接口用于查询执行活动详情。 /// </summary> /// <param name="req"><see cref="DescribeInvocationsRequest"/></param> /// <returns><see cref="DescribeInvocationsResponse"/></returns> public async Task<DescribeInvocationsResponse> DescribeInvocations(DescribeInvocationsRequest req) { JsonResponseModel<DescribeInvocationsResponse> rsp = null; try { var strResp = await this.InternalRequest(req, "DescribeInvocations"); rsp = JsonConvert.DeserializeObject<JsonResponseModel<DescribeInvocationsResponse>>(strResp); } catch (JsonSerializationException e) { throw new TencentCloudSDKException(e.Message); } return rsp.Response; } /// <summary> /// 此接口用于查询执行活动详情。 /// </summary> /// <param name="req"><see cref="DescribeInvocationsRequest"/></param> /// <returns><see cref="DescribeInvocationsResponse"/></returns> public DescribeInvocationsResponse DescribeInvocationsSync(DescribeInvocationsRequest req) { JsonResponseModel<DescribeInvocationsResponse> rsp = null; try { var strResp = this.InternalRequestSync(req, "DescribeInvocations"); rsp = JsonConvert.DeserializeObject<JsonResponseModel<DescribeInvocationsResponse>>(strResp); } catch (JsonSerializationException e) { throw new TencentCloudSDKException(e.Message); } return rsp.Response; } /// <summary> /// 此接口用于查询执行器的执行记录。 /// </summary> /// <param name="req"><see cref="DescribeInvokerRecordsRequest"/></param> /// <returns><see cref="DescribeInvokerRecordsResponse"/></returns> public async Task<DescribeInvokerRecordsResponse> DescribeInvokerRecords(DescribeInvokerRecordsRequest req) { JsonResponseModel<DescribeInvokerRecordsResponse> rsp = null; try { var strResp = await this.InternalRequest(req, "DescribeInvokerRecords"); rsp = JsonConvert.DeserializeObject<JsonResponseModel<DescribeInvokerRecordsResponse>>(strResp); } catch (JsonSerializationException e) { throw new TencentCloudSDKException(e.Message); } return rsp.Response; } /// <summary> /// 此接口用于查询执行器的执行记录。 /// </summary> /// <param name="req"><see cref="DescribeInvokerRecordsRequest"/></param> /// <returns><see cref="DescribeInvokerRecordsResponse"/></returns> public DescribeInvokerRecordsResponse DescribeInvokerRecordsSync(DescribeInvokerRecordsRequest req) { JsonResponseModel<DescribeInvokerRecordsResponse> rsp = null; try { var strResp = this.InternalRequestSync(req, "DescribeInvokerRecords"); rsp = JsonConvert.DeserializeObject<JsonResponseModel<DescribeInvokerRecordsResponse>>(strResp); } catch (JsonSerializationException e) { throw new TencentCloudSDKException(e.Message); } return rsp.Response; } /// <summary> /// 此接口用于查询执行器信息。 /// </summary> /// <param name="req"><see cref="DescribeInvokersRequest"/></param> /// <returns><see cref="DescribeInvokersResponse"/></returns> public async Task<DescribeInvokersResponse> DescribeInvokers(DescribeInvokersRequest req) { JsonResponseModel<DescribeInvokersResponse> rsp = null; try { var strResp = await this.InternalRequest(req, "DescribeInvokers"); rsp = JsonConvert.DeserializeObject<JsonResponseModel<DescribeInvokersResponse>>(strResp); } catch (JsonSerializationException e) { throw new TencentCloudSDKException(e.Message); } return rsp.Response; } /// <summary> /// 此接口用于查询执行器信息。 /// </summary> /// <param name="req"><see cref="DescribeInvokersRequest"/></param> /// <returns><see cref="DescribeInvokersResponse"/></returns> public DescribeInvokersResponse DescribeInvokersSync(DescribeInvokersRequest req) { JsonResponseModel<DescribeInvokersResponse> rsp = null; try { var strResp = this.InternalRequestSync(req, "DescribeInvokers"); rsp = JsonConvert.DeserializeObject<JsonResponseModel<DescribeInvokersResponse>>(strResp); } catch (JsonSerializationException e) { throw new TencentCloudSDKException(e.Message); } return rsp.Response; } /// <summary> /// 此接口用于查询 TAT 产品后台地域列表。 /// RegionState 为 AVAILABLE,代表该地域的 TAT 后台服务已经可用;未返回,代表该地域的 TAT 后台服务尚不可用。 /// </summary> /// <param name="req"><see cref="DescribeRegionsRequest"/></param> /// <returns><see cref="DescribeRegionsResponse"/></returns> public async Task<DescribeRegionsResponse> DescribeRegions(DescribeRegionsRequest req) { JsonResponseModel<DescribeRegionsResponse> rsp = null; try { var strResp = await this.InternalRequest(req, "DescribeRegions"); rsp = JsonConvert.DeserializeObject<JsonResponseModel<DescribeRegionsResponse>>(strResp); } catch (JsonSerializationException e) { throw new TencentCloudSDKException(e.Message); } return rsp.Response; } /// <summary> /// 此接口用于查询 TAT 产品后台地域列表。 /// RegionState 为 AVAILABLE,代表该地域的 TAT 后台服务已经可用;未返回,代表该地域的 TAT 后台服务尚不可用。 /// </summary> /// <param name="req"><see cref="DescribeRegionsRequest"/></param> /// <returns><see cref="DescribeRegionsResponse"/></returns> public DescribeRegionsResponse DescribeRegionsSync(DescribeRegionsRequest req) { JsonResponseModel<DescribeRegionsResponse> rsp = null; try { var strResp = this.InternalRequestSync(req, "DescribeRegions"); rsp = JsonConvert.DeserializeObject<JsonResponseModel<DescribeRegionsResponse>>(strResp); } catch (JsonSerializationException e) { throw new TencentCloudSDKException(e.Message); } return rsp.Response; } /// <summary> /// 此接口用于停止执行器。 /// </summary> /// <param name="req"><see cref="DisableInvokerRequest"/></param> /// <returns><see cref="DisableInvokerResponse"/></returns> public async Task<DisableInvokerResponse> DisableInvoker(DisableInvokerRequest req) { JsonResponseModel<DisableInvokerResponse> rsp = null; try { var strResp = await this.InternalRequest(req, "DisableInvoker"); rsp = JsonConvert.DeserializeObject<JsonResponseModel<DisableInvokerResponse>>(strResp); } catch (JsonSerializationException e) { throw new TencentCloudSDKException(e.Message); } return rsp.Response; } /// <summary> /// 此接口用于停止执行器。 /// </summary> /// <param name="req"><see cref="DisableInvokerRequest"/></param> /// <returns><see cref="DisableInvokerResponse"/></returns> public DisableInvokerResponse DisableInvokerSync(DisableInvokerRequest req) { JsonResponseModel<DisableInvokerResponse> rsp = null; try { var strResp = this.InternalRequestSync(req, "DisableInvoker"); rsp = JsonConvert.DeserializeObject<JsonResponseModel<DisableInvokerResponse>>(strResp); } catch (JsonSerializationException e) { throw new TencentCloudSDKException(e.Message); } return rsp.Response; } /// <summary> /// 此接口用于启用执行器。 /// </summary> /// <param name="req"><see cref="EnableInvokerRequest"/></param> /// <returns><see cref="EnableInvokerResponse"/></returns> public async Task<EnableInvokerResponse> EnableInvoker(EnableInvokerRequest req) { JsonResponseModel<EnableInvokerResponse> rsp = null; try { var strResp = await this.InternalRequest(req, "EnableInvoker"); rsp = JsonConvert.DeserializeObject<JsonResponseModel<EnableInvokerResponse>>(strResp); } catch (JsonSerializationException e) { throw new TencentCloudSDKException(e.Message); } return rsp.Response; } /// <summary> /// 此接口用于启用执行器。 /// </summary> /// <param name="req"><see cref="EnableInvokerRequest"/></param> /// <returns><see cref="EnableInvokerResponse"/></returns> public EnableInvokerResponse EnableInvokerSync(EnableInvokerRequest req) { JsonResponseModel<EnableInvokerResponse> rsp = null; try { var strResp = this.InternalRequestSync(req, "EnableInvoker"); rsp = JsonConvert.DeserializeObject<JsonResponseModel<EnableInvokerResponse>>(strResp); } catch (JsonSerializationException e) { throw new TencentCloudSDKException(e.Message); } return rsp.Response; } /// <summary> /// 在指定的实例上触发命令,调用成功返回执行活动ID(inv-xxxxxxxx),每个执行活动内部有一个或多个执行任务(invt-xxxxxxxx),每个执行任务代表命令在一台 CVM 或一台 Lighthouse 上的执行记录。 /// /// * 如果指定实例未安装 agent,或 agent 不在线,返回失败 /// * 如果命令类型与 agent 运行环境不符,返回失败 /// * 指定的实例需要处于 VPC 网络 /// * 指定的实例需要处于 RUNNING 状态 /// * 不可同时指定 CVM 和 Lighthouse /// </summary> /// <param name="req"><see cref="InvokeCommandRequest"/></param> /// <returns><see cref="InvokeCommandResponse"/></returns> public async Task<InvokeCommandResponse> InvokeCommand(InvokeCommandRequest req) { JsonResponseModel<InvokeCommandResponse> rsp = null; try { var strResp = await this.InternalRequest(req, "InvokeCommand"); rsp = JsonConvert.DeserializeObject<JsonResponseModel<InvokeCommandResponse>>(strResp); } catch (JsonSerializationException e) { throw new TencentCloudSDKException(e.Message); } return rsp.Response; } /// <summary> /// 在指定的实例上触发命令,调用成功返回执行活动ID(inv-xxxxxxxx),每个执行活动内部有一个或多个执行任务(invt-xxxxxxxx),每个执行任务代表命令在一台 CVM 或一台 Lighthouse 上的执行记录。 /// /// * 如果指定实例未安装 agent,或 agent 不在线,返回失败 /// * 如果命令类型与 agent 运行环境不符,返回失败 /// * 指定的实例需要处于 VPC 网络 /// * 指定的实例需要处于 RUNNING 状态 /// * 不可同时指定 CVM 和 Lighthouse /// </summary> /// <param name="req"><see cref="InvokeCommandRequest"/></param> /// <returns><see cref="InvokeCommandResponse"/></returns> public InvokeCommandResponse InvokeCommandSync(InvokeCommandRequest req) { JsonResponseModel<InvokeCommandResponse> rsp = null; try { var strResp = this.InternalRequestSync(req, "InvokeCommand"); rsp = JsonConvert.DeserializeObject<JsonResponseModel<InvokeCommandResponse>>(strResp); } catch (JsonSerializationException e) { throw new TencentCloudSDKException(e.Message); } return rsp.Response; } /// <summary> /// 此接口用于修改命令。 /// </summary> /// <param name="req"><see cref="ModifyCommandRequest"/></param> /// <returns><see cref="ModifyCommandResponse"/></returns> public async Task<ModifyCommandResponse> ModifyCommand(ModifyCommandRequest req) { JsonResponseModel<ModifyCommandResponse> rsp = null; try { var strResp = await this.InternalRequest(req, "ModifyCommand"); rsp = JsonConvert.DeserializeObject<JsonResponseModel<ModifyCommandResponse>>(strResp); } catch (JsonSerializationException e) { throw new TencentCloudSDKException(e.Message); } return rsp.Response; } /// <summary> /// 此接口用于修改命令。 /// </summary> /// <param name="req"><see cref="ModifyCommandRequest"/></param> /// <returns><see cref="ModifyCommandResponse"/></returns> public ModifyCommandResponse ModifyCommandSync(ModifyCommandRequest req) { JsonResponseModel<ModifyCommandResponse> rsp = null; try { var strResp = this.InternalRequestSync(req, "ModifyCommand"); rsp = JsonConvert.DeserializeObject<JsonResponseModel<ModifyCommandResponse>>(strResp); } catch (JsonSerializationException e) { throw new TencentCloudSDKException(e.Message); } return rsp.Response; } /// <summary> /// 此接口用于修改执行器。 /// </summary> /// <param name="req"><see cref="ModifyInvokerRequest"/></param> /// <returns><see cref="ModifyInvokerResponse"/></returns> public async Task<ModifyInvokerResponse> ModifyInvoker(ModifyInvokerRequest req) { JsonResponseModel<ModifyInvokerResponse> rsp = null; try { var strResp = await this.InternalRequest(req, "ModifyInvoker"); rsp = JsonConvert.DeserializeObject<JsonResponseModel<ModifyInvokerResponse>>(strResp); } catch (JsonSerializationException e) { throw new TencentCloudSDKException(e.Message); } return rsp.Response; } /// <summary> /// 此接口用于修改执行器。 /// </summary> /// <param name="req"><see cref="ModifyInvokerRequest"/></param> /// <returns><see cref="ModifyInvokerResponse"/></returns> public ModifyInvokerResponse ModifyInvokerSync(ModifyInvokerRequest req) { JsonResponseModel<ModifyInvokerResponse> rsp = null; try { var strResp = this.InternalRequestSync(req, "ModifyInvoker"); rsp = JsonConvert.DeserializeObject<JsonResponseModel<ModifyInvokerResponse>>(strResp); } catch (JsonSerializationException e) { throw new TencentCloudSDKException(e.Message); } return rsp.Response; } /// <summary> /// 此接口用于预览自定义参数替换后的命令内容。不会触发真实执行。 /// </summary> /// <param name="req"><see cref="PreviewReplacedCommandContentRequest"/></param> /// <returns><see cref="PreviewReplacedCommandContentResponse"/></returns> public async Task<PreviewReplacedCommandContentResponse> PreviewReplacedCommandContent(PreviewReplacedCommandContentRequest req) { JsonResponseModel<PreviewReplacedCommandContentResponse> rsp = null; try { var strResp = await this.InternalRequest(req, "PreviewReplacedCommandContent"); rsp = JsonConvert.DeserializeObject<JsonResponseModel<PreviewReplacedCommandContentResponse>>(strResp); } catch (JsonSerializationException e) { throw new TencentCloudSDKException(e.Message); } return rsp.Response; } /// <summary> /// 此接口用于预览自定义参数替换后的命令内容。不会触发真实执行。 /// </summary> /// <param name="req"><see cref="PreviewReplacedCommandContentRequest"/></param> /// <returns><see cref="PreviewReplacedCommandContentResponse"/></returns> public PreviewReplacedCommandContentResponse PreviewReplacedCommandContentSync(PreviewReplacedCommandContentRequest req) { JsonResponseModel<PreviewReplacedCommandContentResponse> rsp = null; try { var strResp = this.InternalRequestSync(req, "PreviewReplacedCommandContent"); rsp = JsonConvert.DeserializeObject<JsonResponseModel<PreviewReplacedCommandContentResponse>>(strResp); } catch (JsonSerializationException e) { throw new TencentCloudSDKException(e.Message); } return rsp.Response; } /// <summary> /// 执行命令,调用成功返回执行活动ID(inv-xxxxxxxx),每个执行活动内部有一个或多个执行任务(invt-xxxxxxxx),每个执行任务代表命令在一台 CVM 或一台 Lighthouse 上的执行记录。 /// /// * 如果指定实例未安装 agent,或 agent 不在线,返回失败 /// * 如果命令类型与 agent 运行环境不符,返回失败 /// * 指定的实例需要处于 VPC 网络 /// * 指定的实例需要处于 `RUNNING` 状态 /// * 不可同时指定 CVM 和 Lighthouse /// </summary> /// <param name="req"><see cref="RunCommandRequest"/></param> /// <returns><see cref="RunCommandResponse"/></returns> public async Task<RunCommandResponse> RunCommand(RunCommandRequest req) { JsonResponseModel<RunCommandResponse> rsp = null; try { var strResp = await this.InternalRequest(req, "RunCommand"); rsp = JsonConvert.DeserializeObject<JsonResponseModel<RunCommandResponse>>(strResp); } catch (JsonSerializationException e) { throw new TencentCloudSDKException(e.Message); } return rsp.Response; } /// <summary> /// 执行命令,调用成功返回执行活动ID(inv-xxxxxxxx),每个执行活动内部有一个或多个执行任务(invt-xxxxxxxx),每个执行任务代表命令在一台 CVM 或一台 Lighthouse 上的执行记录。 /// /// * 如果指定实例未安装 agent,或 agent 不在线,返回失败 /// * 如果命令类型与 agent 运行环境不符,返回失败 /// * 指定的实例需要处于 VPC 网络 /// * 指定的实例需要处于 `RUNNING` 状态 /// * 不可同时指定 CVM 和 Lighthouse /// </summary> /// <param name="req"><see cref="RunCommandRequest"/></param> /// <returns><see cref="RunCommandResponse"/></returns> public RunCommandResponse RunCommandSync(RunCommandRequest req) { JsonResponseModel<RunCommandResponse> rsp = null; try { var strResp = this.InternalRequestSync(req, "RunCommand"); rsp = JsonConvert.DeserializeObject<JsonResponseModel<RunCommandResponse>>(strResp); } catch (JsonSerializationException e) { throw new TencentCloudSDKException(e.Message); } return rsp.Response; } } }
40.925969
136
0.582491
[ "Apache-2.0" ]
TencentCloud/tencentcloud-sdk-dotnet
TencentCloud/Tat/V20201028/TatClient.cs
37,240
C#
// -------------------------------------------------------------------------------------------------- // <copyright file="PropertyImagesController.cs" company="InmoIT"> // Copyright (c) InmoIT. All rights reserved. // Developer: Vladimir P. CHibás (vladperchi). // Licensed under the MIT license. See LICENSE file in the project root for full license information. // </copyright> // -------------------------------------------------------------------------------------------------- using System; using System.Threading.Tasks; using InmoIT.Modules.Inmo.Core.Entities; using InmoIT.Modules.Inmo.Core.Features.Images.Commands; using InmoIT.Modules.Inmo.Core.Features.Images.Queries; using InmoIT.Shared.Core.Constants; using InmoIT.Shared.Core.Features.Filters; using InmoIT.Shared.Dtos.Inmo.Images; using InmoIT.Shared.Infrastructure.Permissions; using Microsoft.AspNetCore.Mvc; using Swashbuckle.AspNetCore.Annotations; namespace InmoIT.Modules.Inmo.Api.Controllers { [ApiVersion("1")] internal sealed class PropertyImagesController : BaseController { [HttpGet] [HavePermission(PermissionsConstant.Images.ViewAll)] [SwaggerOperation( Summary = "Get Property Image List.", Description = "List all property images in the database. This can only be done by the registered user", OperationId = "GetAllAsync")] [SwaggerResponse(200, "Return property image list.")] [SwaggerResponse(204, "Property image list not content.")] [SwaggerResponse(401, "No authorization to access.")] [SwaggerResponse(403, "No permission to access.")] public async Task<IActionResult> GetAllAsync([FromQuery] PaginatedPropertyImageFilter filter) { var request = Mapper.Map<GetAllImagesQuery>(filter); var response = await Mediator.Send(request); return Ok(response); } [HttpGet("{id:guid}")] [HavePermission(PermissionsConstant.Images.View)] [SwaggerOperation( Summary = "Get Property Image By Id.", Description = "We get the detail property image by Id. This can only be done by the registered user", OperationId = "GetByIdAsync")] [SwaggerResponse(200, "Return property image by id.")] [SwaggerResponse(404, "Property Image was not found.")] [SwaggerResponse(401, "No authorization to access.")] [SwaggerResponse(403, "No permission to access.")] public async Task<IActionResult> GetByIdAsync([FromQuery] GetByIdCacheableFilter<Guid, PropertyImage> filter) { var request = Mapper.Map<GetImageByPropertyIdQuery>(filter); var response = await Mediator.Send(request); return Ok(response); } [HttpPost] [HavePermission(PermissionsConstant.Images.Add)] [SwaggerOperation( Summary = "Added Property Image List.", Description = "Added a property image list with all its values set. This can only be done by the registered user", OperationId = "AddAsync")] [SwaggerResponse(201, "Return added property image list.")] [SwaggerResponse(404, "Property was not found.")] [SwaggerResponse(400, "Property Image already exists.")] [SwaggerResponse(500, "Property Image Internal Server Error.")] [SwaggerResponse(401, "No authorization to access.")] [SwaggerResponse(403, "No permission to access.")] public async Task<IActionResult> AddAsync(AddImageCommand command) { var response = await Mediator.Send(command); return Ok(response); } [HttpPut] [HavePermission(PermissionsConstant.Images.Edit)] [SwaggerOperation( Summary = "Edit Property Image.", Description = "We get the property image with its modified values. This can only be done by the registered user", OperationId = "UpdateAsync")] [SwaggerResponse(200, "Return updated property image.")] [SwaggerResponse(404, "Property Image was not found.")] [SwaggerResponse(500, "Property Image Internal Server Error.")] [SwaggerResponse(401, "No authorization to access.")] [SwaggerResponse(403, "No permission to access.")] public async Task<IActionResult> EditAsync(UpdateImageCommand command) { var response = await Mediator.Send(command); return Ok(response); } [HttpDelete("{id:guid}")] [HavePermission(PermissionsConstant.Images.Remove)] [SwaggerOperation( Summary = "Remove Property Image.", Description = "We get the removed property image by Id. This can only be done by the registered user", OperationId = "RemoveAsync")] [SwaggerResponse(200, "Return removed property image.")] [SwaggerResponse(404, "Property Image was not found.")] [SwaggerResponse(500, "Property Image Internal Server Error.")] [SwaggerResponse(401, "No authorization to access.")] [SwaggerResponse(403, "No permission to access.")] public async Task<IActionResult> RemoveAsync(Guid id) { var response = await Mediator.Send(new RemoveImageCommand(id)); return Ok(response); } } }
47.75
126
0.637435
[ "MIT" ]
DevCrafts/InmoIT
src/server/Modules/Inmo/Modules.Inmo.Api/Controllers/PropertyImagesController.cs
5,351
C#
// // EndpointAddressMessageFilter.cs // // Author: // Atsushi Enomoto <atsushi@ximian.com> // // Copyright (C) 2005 Novell, Inc. http://www.novell.com // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.ServiceModel.Channels; using System.ServiceModel; namespace System.ServiceModel.Dispatcher { public class EndpointAddressMessageFilter : MessageFilter { EndpointAddress address; bool cmp_host; public EndpointAddressMessageFilter (EndpointAddress address) : this (address, false) { } public EndpointAddressMessageFilter (EndpointAddress address, bool includeHostNameInComparison) { this.address = address; cmp_host = includeHostNameInComparison; } public EndpointAddress Address { get { return address; } } public bool IncludeHostNameInComparison { get { return cmp_host; } } [MonoTODO] protected internal override IMessageFilterTable<FilterData> CreateFilterTable<FilterData> () { throw new NotImplementedException (); } [MonoTODO] public override bool Match (Message message) { Uri to = message.Headers.To; bool path = ((String.CompareOrdinal (to.AbsolutePath, address.Uri.AbsolutePath) == 0) && (to.Port == address.Uri.Port)); bool host = IncludeHostNameInComparison ? (String.CompareOrdinal (to.Host, address.Uri.Host) == 0) : true; return path && host; } public override bool Match (MessageBuffer messageBuffer) { if (messageBuffer == null) throw new ArgumentNullException ("messageBuffer"); return Match (messageBuffer.CreateMessage ()); } } }
30.252874
92
0.737462
[ "MIT" ]
zlxy/Genesis-3D
Engine/extlibs/IosLibs/mono-2.6.7/mcs/class/System.ServiceModel/System.ServiceModel.Dispatcher/EndpointAddressMessageFilter.cs
2,632
C#
using System; using System.IO; using System.Threading.Tasks; using Elasticsearch.Net; namespace Nest { using IndexExistConverter = Func<IElasticsearchResponse, Stream, IndexExistsResponse>; public partial class ElasticClient { /// <inheritdoc /> public IIndexExistsResponse IndexExists(Func<IndexExistsDescriptor, IndexExistsDescriptor> selector) { return this.Dispatch<IndexExistsDescriptor, IndexExistsRequestParameters, IndexExistsResponse>( selector, (p, d) => this.RawDispatch.IndicesExistsDispatch<IndexExistsResponse>( p.DeserializationState(new IndexExistConverter(DeserializeExistsResponse)) ), allow404: true ); } /// <inheritdoc /> public Task<IIndexExistsResponse> IndexExistsAsync(Func<IndexExistsDescriptor, IndexExistsDescriptor> selector) { return this.DispatchAsync<IndexExistsDescriptor, IndexExistsRequestParameters, IndexExistsResponse, IIndexExistsResponse>( selector, (p, d) => this.RawDispatch.IndicesExistsDispatchAsync<IndexExistsResponse>( p.DeserializationState(new IndexExistConverter(DeserializeExistsResponse)) ), allow404: true ); } private IndexExistsResponse DeserializeExistsResponse(IElasticsearchResponse response, Stream stream) { return new IndexExistsResponse(response); } } }
31.804878
125
0.782975
[ "MIT" ]
amitstefen/elasticsearch-net
src/Nest/ElasticClient-IndexExists.cs
1,306
C#
namespace Handlebars.Core.Compiler.Lexer.Tokens { internal class PartialToken : Token { public override TokenType Type => TokenType.Partial; public override string Value => ">"; public override string ToString() { return Value; } } }
21.428571
60
0.596667
[ "MIT" ]
esskar/Handlebars
source/Handlebars.Core/Compiler/Lexer/Tokens/PartialToken.cs
302
C#
using System.Threading.Tasks; namespace NetModular.Lib.Cache.Abstractions { /// <summary> /// 缓存处理器 /// </summary> public interface ICacheHandler { /// <summary> /// 获取 /// </summary> /// <param name="key">键</param> /// <returns></returns> string Get(string key); /// <summary> /// 获取 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key">键</param> /// <returns></returns> T Get<T>(string key); /// <summary> /// 获取 /// </summary> /// <param name="key">键</param> /// <returns></returns> Task<string> GetAsync(string key); /// <summary> /// 获取 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key">键</param> /// <returns></returns> Task<T> GetAsync<T>(string key); /// <summary> /// 尝试获取 /// </summary> /// <param name="key">键</param> /// <param name="value">返回值</param> /// <returns></returns> bool TryGetValue(string key, out string value); /// <summary> /// 尝试获取 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key">键</param> /// <param name="value">返回值</param> /// <returns></returns> bool TryGetValue<T>(string key, out T value); /// <summary> /// 设置 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key">键</param> /// <param name="value">值</param> bool Set<T>(string key, T value); /// <summary> /// 设置 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key">键</param> /// <param name="value">值</param> /// <param name="expires">有效期(分钟)</param> bool Set<T>(string key, T value, int expires); /// <summary> /// 设置 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key">键</param> /// <param name="value">值</param> /// <returns></returns> Task<bool> SetAsync<T>(string key, T value); /// <summary> /// 设置 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key">键</param> /// <param name="value">值</param> /// <param name="expires">有效期(分钟)</param> /// <returns></returns> Task<bool> SetAsync<T>(string key, T value, int expires); /// <summary> /// 删除 /// </summary> /// <param name="key"></param> bool Remove(string key); /// <summary> /// 删除 /// </summary> /// <param name="key"></param> /// <returns></returns> Task<bool> RemoveAsync(string key); /// <summary> /// 指定键是否存在 /// </summary> /// <param name="key"></param> /// <returns></returns> bool Exists(string key); /// <summary> /// 指定键是否存在 /// </summary> /// <param name="key"></param> /// <returns></returns> Task<bool> ExistsAsync(string key); /// <summary> /// 删除指定前缀的缓存 /// </summary> /// <param name="prefix"></param> /// <returns></returns> Task RemoveByPrefixAsync(string prefix); } }
26.882813
65
0.452775
[ "MIT" ]
380138129/NetModular
src/Framework/Cache/Cache.Abstractions/ICacheHandler.cs
3,615
C#
// ReSharper disable BuiltInTypeReferenceStyle // ReSharper disable RedundantNameQualifier // ReSharper disable ArrangeObjectCreationWhenTypeEvident // ReSharper disable UnusedType.Global // ReSharper disable PartialTypeWithSinglePart // ReSharper disable UnusedMethodReturnValue.Local // ReSharper disable ConvertToAutoProperty // ReSharper disable UnusedMember.Global // ReSharper disable SuggestVarOrType_SimpleTypes // ReSharper disable InconsistentNaming // StarWarsGetHeroClient // <auto-generated/> #nullable enable namespace Microsoft.Extensions.DependencyInjection { // StrawberryShake.CodeGeneration.CSharp.Generators.DependencyInjectionGenerator [global::System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "11.0.0")] public static partial class StarWarsGetHeroClientServiceCollectionExtensions { public static global::StrawberryShake.IClientBuilder<global::StrawberryShake.CodeGeneration.CSharp.Integration.StarWarsGetHero.State.StarWarsGetHeroClientStoreAccessor> AddStarWarsGetHeroClient(this global::Microsoft.Extensions.DependencyInjection.IServiceCollection services, global::StrawberryShake.ExecutionStrategy strategy = global::StrawberryShake.ExecutionStrategy.NetworkOnly) { global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton(services, sp => { var serviceCollection = ConfigureClientDefault(sp, strategy); return new ClientServiceProvider(global::Microsoft.Extensions.DependencyInjection.ServiceCollectionContainerBuilderExtensions.BuildServiceProvider(serviceCollection)); }); global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton(services, sp => new global::StrawberryShake.CodeGeneration.CSharp.Integration.StarWarsGetHero.State.StarWarsGetHeroClientStoreAccessor(global::Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService<global::StrawberryShake.IOperationStore>(global::Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService<ClientServiceProvider>(sp)), global::Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService<global::StrawberryShake.IEntityStore>(global::Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService<ClientServiceProvider>(sp)), global::Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService<global::StrawberryShake.IEntityIdSerializer>(global::Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService<ClientServiceProvider>(sp)), global::Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService<global::System.Collections.Generic.IEnumerable<global::StrawberryShake.IOperationRequestFactory>>(global::Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService<ClientServiceProvider>(sp)), global::Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService<global::System.Collections.Generic.IEnumerable<global::StrawberryShake.IOperationResultDataFactory>>(global::Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService<ClientServiceProvider>(sp)))); global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton(services, sp => global::Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService<global::StrawberryShake.CodeGeneration.CSharp.Integration.StarWarsGetHero.GetHeroQuery>(global::Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService<ClientServiceProvider>(sp))); global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton(services, sp => global::Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService<global::StrawberryShake.CodeGeneration.CSharp.Integration.StarWarsGetHero.StarWarsGetHeroClient>(global::Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService<ClientServiceProvider>(sp))); global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton(services, sp => global::Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService<global::StrawberryShake.CodeGeneration.CSharp.Integration.StarWarsGetHero.IStarWarsGetHeroClient>(global::Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService<ClientServiceProvider>(sp))); return new global::StrawberryShake.ClientBuilder<global::StrawberryShake.CodeGeneration.CSharp.Integration.StarWarsGetHero.State.StarWarsGetHeroClientStoreAccessor>("StarWarsGetHeroClient", services); } private static global::Microsoft.Extensions.DependencyInjection.IServiceCollection ConfigureClientDefault(global::System.IServiceProvider parentServices, global::StrawberryShake.ExecutionStrategy strategy = global::StrawberryShake.ExecutionStrategy.NetworkOnly) { var services = new global::Microsoft.Extensions.DependencyInjection.ServiceCollection(); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton<global::StrawberryShake.IEntityStore, global::StrawberryShake.EntityStore>(services); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton<global::StrawberryShake.IOperationStore>(services, sp => new global::StrawberryShake.OperationStore(global::Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService<global::StrawberryShake.IEntityStore>(sp))); global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton(services, sp => { var clientFactory = global::Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService<global::System.Net.Http.IHttpClientFactory>(parentServices); return new global::StrawberryShake.Transport.Http.HttpConnection(() => clientFactory.CreateClient("StarWarsGetHeroClient")); }); global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton<global::StrawberryShake.IEntityMapper<global::StrawberryShake.CodeGeneration.CSharp.Integration.StarWarsGetHero.State.DroidEntity, global::StrawberryShake.CodeGeneration.CSharp.Integration.StarWarsGetHero.GetHero_Hero_Droid>, global::StrawberryShake.CodeGeneration.CSharp.Integration.StarWarsGetHero.State.GetHero_Hero_DroidFromDroidEntityMapper>(services); global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton<global::StrawberryShake.IEntityMapper<global::StrawberryShake.CodeGeneration.CSharp.Integration.StarWarsGetHero.State.HumanEntity, global::StrawberryShake.CodeGeneration.CSharp.Integration.StarWarsGetHero.GetHero_Hero_Human>, global::StrawberryShake.CodeGeneration.CSharp.Integration.StarWarsGetHero.State.GetHero_Hero_HumanFromHumanEntityMapper>(services); global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton<global::StrawberryShake.Serialization.ISerializer, global::StrawberryShake.Serialization.StringSerializer>(services); global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton<global::StrawberryShake.Serialization.ISerializer, global::StrawberryShake.Serialization.BooleanSerializer>(services); global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton<global::StrawberryShake.Serialization.ISerializer, global::StrawberryShake.Serialization.ByteSerializer>(services); global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton<global::StrawberryShake.Serialization.ISerializer, global::StrawberryShake.Serialization.ShortSerializer>(services); global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton<global::StrawberryShake.Serialization.ISerializer, global::StrawberryShake.Serialization.IntSerializer>(services); global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton<global::StrawberryShake.Serialization.ISerializer, global::StrawberryShake.Serialization.LongSerializer>(services); global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton<global::StrawberryShake.Serialization.ISerializer, global::StrawberryShake.Serialization.FloatSerializer>(services); global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton<global::StrawberryShake.Serialization.ISerializer, global::StrawberryShake.Serialization.DecimalSerializer>(services); global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton<global::StrawberryShake.Serialization.ISerializer, global::StrawberryShake.Serialization.UrlSerializer>(services); global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton<global::StrawberryShake.Serialization.ISerializer, global::StrawberryShake.Serialization.UuidSerializer>(services); global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton<global::StrawberryShake.Serialization.ISerializer, global::StrawberryShake.Serialization.IdSerializer>(services); global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton<global::StrawberryShake.Serialization.ISerializer, global::StrawberryShake.Serialization.DateTimeSerializer>(services); global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton<global::StrawberryShake.Serialization.ISerializer, global::StrawberryShake.Serialization.DateSerializer>(services); global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton<global::StrawberryShake.Serialization.ISerializer, global::StrawberryShake.Serialization.ByteArraySerializer>(services); global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton<global::StrawberryShake.Serialization.ISerializer, global::StrawberryShake.Serialization.TimeSpanSerializer>(services); global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton<global::StrawberryShake.Serialization.ISerializerResolver>(services, sp => new global::StrawberryShake.Serialization.SerializerResolver(global::System.Linq.Enumerable.Concat(global::Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService<global::System.Collections.Generic.IEnumerable<global::StrawberryShake.Serialization.ISerializer>>(parentServices), global::Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService<global::System.Collections.Generic.IEnumerable<global::StrawberryShake.Serialization.ISerializer>>(sp)))); global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton<global::StrawberryShake.IOperationResultDataFactory<global::StrawberryShake.CodeGeneration.CSharp.Integration.StarWarsGetHero.IGetHeroResult>, global::StrawberryShake.CodeGeneration.CSharp.Integration.StarWarsGetHero.State.GetHeroResultFactory>(services); global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton<global::StrawberryShake.IOperationResultDataFactory>(services, sp => global::Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService<global::StrawberryShake.IOperationResultDataFactory<global::StrawberryShake.CodeGeneration.CSharp.Integration.StarWarsGetHero.IGetHeroResult>>(sp)); global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton<global::StrawberryShake.IOperationRequestFactory>(services, sp => global::Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService<global::StrawberryShake.CodeGeneration.CSharp.Integration.StarWarsGetHero.IGetHeroQuery>(sp)); global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton<global::StrawberryShake.IOperationResultBuilder<global::System.Text.Json.JsonDocument, global::StrawberryShake.CodeGeneration.CSharp.Integration.StarWarsGetHero.IGetHeroResult>, global::StrawberryShake.CodeGeneration.CSharp.Integration.StarWarsGetHero.State.GetHeroBuilder>(services); global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton<global::StrawberryShake.IOperationExecutor<global::StrawberryShake.CodeGeneration.CSharp.Integration.StarWarsGetHero.IGetHeroResult>>(services, sp => new global::StrawberryShake.OperationExecutor<global::System.Text.Json.JsonDocument, global::StrawberryShake.CodeGeneration.CSharp.Integration.StarWarsGetHero.IGetHeroResult>(global::Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService<global::StrawberryShake.Transport.Http.HttpConnection>(sp), () => global::Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService<global::StrawberryShake.IOperationResultBuilder<global::System.Text.Json.JsonDocument, global::StrawberryShake.CodeGeneration.CSharp.Integration.StarWarsGetHero.IGetHeroResult>>(sp), global::Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService<global::StrawberryShake.IOperationStore>(sp), strategy)); global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton<global::StrawberryShake.CodeGeneration.CSharp.Integration.StarWarsGetHero.GetHeroQuery>(services); global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton<global::StrawberryShake.CodeGeneration.CSharp.Integration.StarWarsGetHero.IGetHeroQuery>(services, sp => global::Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService<global::StrawberryShake.CodeGeneration.CSharp.Integration.StarWarsGetHero.GetHeroQuery>(sp)); global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton<global::StrawberryShake.IEntityIdSerializer, global::StrawberryShake.CodeGeneration.CSharp.Integration.StarWarsGetHero.State.StarWarsGetHeroClientEntityIdFactory>(services); global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton<global::StrawberryShake.CodeGeneration.CSharp.Integration.StarWarsGetHero.StarWarsGetHeroClient>(services); global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton<global::StrawberryShake.CodeGeneration.CSharp.Integration.StarWarsGetHero.IStarWarsGetHeroClient>(services, sp => global::Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService<global::StrawberryShake.CodeGeneration.CSharp.Integration.StarWarsGetHero.StarWarsGetHeroClient>(sp)); return services; } private class ClientServiceProvider : System.IServiceProvider, System.IDisposable { private readonly System.IServiceProvider _provider; public ClientServiceProvider(System.IServiceProvider provider) { _provider = provider; } public object? GetService(System.Type serviceType) { return _provider.GetService(serviceType); } public void Dispose() { if (_provider is System.IDisposable d) { d.Dispose(); } } } } } namespace StrawberryShake.CodeGeneration.CSharp.Integration.StarWarsGetHero { // StrawberryShake.CodeGeneration.CSharp.Generators.ResultTypeGenerator [global::System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "11.0.0")] public partial class GetHeroResult : global::System.IEquatable<GetHeroResult>, IGetHeroResult { public GetHeroResult(global::StrawberryShake.CodeGeneration.CSharp.Integration.StarWarsGetHero.IGetHero_Hero? hero) { Hero = hero; } public global::StrawberryShake.CodeGeneration.CSharp.Integration.StarWarsGetHero.IGetHero_Hero? Hero { get; } public override global::System.Boolean Equals(global::System.Object? obj) { if (ReferenceEquals(null, obj)) { return false; } if (ReferenceEquals(this, obj)) { return true; } if (obj.GetType() != GetType()) { return false; } return Equals((GetHeroResult)obj); } public global::System.Boolean Equals(GetHeroResult? other) { if (ReferenceEquals(null, other)) { return false; } if (ReferenceEquals(this, other)) { return true; } if (other.GetType() != GetType()) { return false; } return (((Hero is null && other.Hero is null) || Hero != null && Hero.Equals(other.Hero))); } public override global::System.Int32 GetHashCode() { unchecked { int hash = 5; if (!(Hero is null)) { hash ^= 397 * Hero.GetHashCode(); } return hash; } } } // StrawberryShake.CodeGeneration.CSharp.Generators.ResultTypeGenerator [global::System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "11.0.0")] public partial class GetHero_Hero_Droid : global::System.IEquatable<GetHero_Hero_Droid>, IGetHero_Hero_Droid { public GetHero_Hero_Droid(global::System.String name) { Name = name; } public global::System.String Name { get; } public override global::System.Boolean Equals(global::System.Object? obj) { if (ReferenceEquals(null, obj)) { return false; } if (ReferenceEquals(this, obj)) { return true; } if (obj.GetType() != GetType()) { return false; } return Equals((GetHero_Hero_Droid)obj); } public global::System.Boolean Equals(GetHero_Hero_Droid? other) { if (ReferenceEquals(null, other)) { return false; } if (ReferenceEquals(this, other)) { return true; } if (other.GetType() != GetType()) { return false; } return (Name.Equals(other.Name)); } public override global::System.Int32 GetHashCode() { unchecked { int hash = 5; hash ^= 397 * Name.GetHashCode(); return hash; } } } // StrawberryShake.CodeGeneration.CSharp.Generators.ResultTypeGenerator [global::System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "11.0.0")] public partial class GetHero_Hero_Human : global::System.IEquatable<GetHero_Hero_Human>, IGetHero_Hero_Human { public GetHero_Hero_Human(global::System.String name) { Name = name; } public global::System.String Name { get; } public override global::System.Boolean Equals(global::System.Object? obj) { if (ReferenceEquals(null, obj)) { return false; } if (ReferenceEquals(this, obj)) { return true; } if (obj.GetType() != GetType()) { return false; } return Equals((GetHero_Hero_Human)obj); } public global::System.Boolean Equals(GetHero_Hero_Human? other) { if (ReferenceEquals(null, other)) { return false; } if (ReferenceEquals(this, other)) { return true; } if (other.GetType() != GetType()) { return false; } return (Name.Equals(other.Name)); } public override global::System.Int32 GetHashCode() { unchecked { int hash = 5; hash ^= 397 * Name.GetHashCode(); return hash; } } } // StrawberryShake.CodeGeneration.CSharp.Generators.ResultInterfaceGenerator [global::System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "11.0.0")] public interface IGetHeroResult { public global::StrawberryShake.CodeGeneration.CSharp.Integration.StarWarsGetHero.IGetHero_Hero? Hero { get; } } // StrawberryShake.CodeGeneration.CSharp.Generators.ResultInterfaceGenerator [global::System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "11.0.0")] public interface IGetHero_Hero { public global::System.String Name { get; } } // StrawberryShake.CodeGeneration.CSharp.Generators.ResultInterfaceGenerator [global::System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "11.0.0")] public interface IGetHero_Hero_Droid : IGetHero_Hero { } // StrawberryShake.CodeGeneration.CSharp.Generators.ResultInterfaceGenerator [global::System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "11.0.0")] public interface IGetHero_Hero_Human : IGetHero_Hero { } // StrawberryShake.CodeGeneration.CSharp.Generators.OperationDocumentGenerator /// <summary> /// Represents the operation service of the GetHero GraphQL operation /// <code> /// query GetHero { /// hero(episode: NEW_HOPE) { /// __typename /// name /// ... on Droid { /// id /// } /// ... on Human { /// id /// } /// } /// } /// </code> /// </summary> [global::System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "11.0.0")] public partial class GetHeroQueryDocument : global::StrawberryShake.IDocument { private GetHeroQueryDocument() { } public static GetHeroQueryDocument Instance { get; } = new GetHeroQueryDocument(); public global::StrawberryShake.OperationKind Kind => global::StrawberryShake.OperationKind.Query; public global::System.ReadOnlySpan<global::System.Byte> Body => new global::System.Byte[]{0x71, 0x75, 0x65, 0x72, 0x79, 0x20, 0x47, 0x65, 0x74, 0x48, 0x65, 0x72, 0x6f, 0x20, 0x7b, 0x20, 0x68, 0x65, 0x72, 0x6f, 0x28, 0x65, 0x70, 0x69, 0x73, 0x6f, 0x64, 0x65, 0x3a, 0x20, 0x4e, 0x45, 0x57, 0x5f, 0x48, 0x4f, 0x50, 0x45, 0x29, 0x20, 0x7b, 0x20, 0x5f, 0x5f, 0x74, 0x79, 0x70, 0x65, 0x6e, 0x61, 0x6d, 0x65, 0x20, 0x6e, 0x61, 0x6d, 0x65, 0x20, 0x2e, 0x2e, 0x2e, 0x20, 0x6f, 0x6e, 0x20, 0x44, 0x72, 0x6f, 0x69, 0x64, 0x20, 0x7b, 0x20, 0x69, 0x64, 0x20, 0x7d, 0x20, 0x2e, 0x2e, 0x2e, 0x20, 0x6f, 0x6e, 0x20, 0x48, 0x75, 0x6d, 0x61, 0x6e, 0x20, 0x7b, 0x20, 0x69, 0x64, 0x20, 0x7d, 0x20, 0x7d, 0x20, 0x7d}; public global::StrawberryShake.DocumentHash Hash { get; } = new global::StrawberryShake.DocumentHash("sha1Hash", "95ca68547e3a55b9ff81efe79b33a417b2f0690b"); public override global::System.String ToString() { #if NETSTANDARD2_0 return global::System.Text.Encoding.UTF8.GetString(Body.ToArray()); #else return global::System.Text.Encoding.UTF8.GetString(Body); #endif } } // StrawberryShake.CodeGeneration.CSharp.Generators.OperationServiceGenerator /// <summary> /// Represents the operation service of the GetHero GraphQL operation /// <code> /// query GetHero { /// hero(episode: NEW_HOPE) { /// __typename /// name /// ... on Droid { /// id /// } /// ... on Human { /// id /// } /// } /// } /// </code> /// </summary> [global::System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "11.0.0")] public partial class GetHeroQuery : global::StrawberryShake.CodeGeneration.CSharp.Integration.StarWarsGetHero.IGetHeroQuery { private readonly global::StrawberryShake.IOperationExecutor<IGetHeroResult> _operationExecutor; public GetHeroQuery(global::StrawberryShake.IOperationExecutor<IGetHeroResult> operationExecutor) { _operationExecutor = operationExecutor ?? throw new global::System.ArgumentNullException(nameof(operationExecutor)); } global::System.Type global::StrawberryShake.IOperationRequestFactory.ResultType => typeof(IGetHeroResult); public async global::System.Threading.Tasks.Task<global::StrawberryShake.IOperationResult<IGetHeroResult>> ExecuteAsync(global::System.Threading.CancellationToken cancellationToken = default) { var request = CreateRequest(); return await _operationExecutor.ExecuteAsync(request, cancellationToken).ConfigureAwait(false); } public global::System.IObservable<global::StrawberryShake.IOperationResult<IGetHeroResult>> Watch(global::StrawberryShake.ExecutionStrategy? strategy = null) { var request = CreateRequest(); return _operationExecutor.Watch(request, strategy); } private global::StrawberryShake.OperationRequest CreateRequest() { return CreateRequest(null); } private global::StrawberryShake.OperationRequest CreateRequest(global::System.Collections.Generic.IReadOnlyDictionary<global::System.String, global::System.Object?>? variables) { return new global::StrawberryShake.OperationRequest(id: GetHeroQueryDocument.Instance.Hash.Value, name: "GetHero", document: GetHeroQueryDocument.Instance, strategy: global::StrawberryShake.RequestStrategy.Default); } global::StrawberryShake.OperationRequest global::StrawberryShake.IOperationRequestFactory.Create(global::System.Collections.Generic.IReadOnlyDictionary<global::System.String, global::System.Object?>? variables) { return CreateRequest(); } } // StrawberryShake.CodeGeneration.CSharp.Generators.OperationServiceInterfaceGenerator /// <summary> /// Represents the operation service of the GetHero GraphQL operation /// <code> /// query GetHero { /// hero(episode: NEW_HOPE) { /// __typename /// name /// ... on Droid { /// id /// } /// ... on Human { /// id /// } /// } /// } /// </code> /// </summary> [global::System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "11.0.0")] public interface IGetHeroQuery : global::StrawberryShake.IOperationRequestFactory { global::System.Threading.Tasks.Task<global::StrawberryShake.IOperationResult<IGetHeroResult>> ExecuteAsync(global::System.Threading.CancellationToken cancellationToken = default); global::System.IObservable<global::StrawberryShake.IOperationResult<IGetHeroResult>> Watch(global::StrawberryShake.ExecutionStrategy? strategy = null); } // StrawberryShake.CodeGeneration.CSharp.Generators.ClientGenerator /// <summary> /// Represents the StarWarsGetHeroClient GraphQL client /// </summary> [global::System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "11.0.0")] public partial class StarWarsGetHeroClient : global::StrawberryShake.CodeGeneration.CSharp.Integration.StarWarsGetHero.IStarWarsGetHeroClient { private readonly global::StrawberryShake.CodeGeneration.CSharp.Integration.StarWarsGetHero.IGetHeroQuery _getHero; public StarWarsGetHeroClient(global::StrawberryShake.CodeGeneration.CSharp.Integration.StarWarsGetHero.IGetHeroQuery getHero) { _getHero = getHero ?? throw new global::System.ArgumentNullException(nameof(getHero)); } public static global::System.String ClientName => "StarWarsGetHeroClient"; public global::StrawberryShake.CodeGeneration.CSharp.Integration.StarWarsGetHero.IGetHeroQuery GetHero => _getHero; } // StrawberryShake.CodeGeneration.CSharp.Generators.ClientInterfaceGenerator /// <summary> /// Represents the StarWarsGetHeroClient GraphQL client /// </summary> [global::System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "11.0.0")] public interface IStarWarsGetHeroClient { global::StrawberryShake.CodeGeneration.CSharp.Integration.StarWarsGetHero.IGetHeroQuery GetHero { get; } } } namespace StrawberryShake.CodeGeneration.CSharp.Integration.StarWarsGetHero.State { // StrawberryShake.CodeGeneration.CSharp.Generators.EntityTypeGenerator [global::System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "0.0.0.0")] public partial class DroidEntity { public DroidEntity(global::System.String name = default !) { Name = name; } public global::System.String Name { get; } } // StrawberryShake.CodeGeneration.CSharp.Generators.EntityTypeGenerator [global::System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "0.0.0.0")] public partial class HumanEntity { public HumanEntity(global::System.String name = default !) { Name = name; } public global::System.String Name { get; } } // StrawberryShake.CodeGeneration.CSharp.Generators.ResultDataFactoryGenerator [global::System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "11.0.0")] public partial class GetHeroResultFactory : global::StrawberryShake.IOperationResultDataFactory<global::StrawberryShake.CodeGeneration.CSharp.Integration.StarWarsGetHero.GetHeroResult> { private readonly global::StrawberryShake.IEntityStore _entityStore; private readonly global::StrawberryShake.IEntityMapper<global::StrawberryShake.CodeGeneration.CSharp.Integration.StarWarsGetHero.State.DroidEntity, GetHero_Hero_Droid> _getHero_Hero_DroidFromDroidEntityMapper; private readonly global::StrawberryShake.IEntityMapper<global::StrawberryShake.CodeGeneration.CSharp.Integration.StarWarsGetHero.State.HumanEntity, GetHero_Hero_Human> _getHero_Hero_HumanFromHumanEntityMapper; public GetHeroResultFactory(global::StrawberryShake.IEntityStore entityStore, global::StrawberryShake.IEntityMapper<global::StrawberryShake.CodeGeneration.CSharp.Integration.StarWarsGetHero.State.DroidEntity, GetHero_Hero_Droid> getHero_Hero_DroidFromDroidEntityMapper, global::StrawberryShake.IEntityMapper<global::StrawberryShake.CodeGeneration.CSharp.Integration.StarWarsGetHero.State.HumanEntity, GetHero_Hero_Human> getHero_Hero_HumanFromHumanEntityMapper) { _entityStore = entityStore ?? throw new global::System.ArgumentNullException(nameof(entityStore)); _getHero_Hero_DroidFromDroidEntityMapper = getHero_Hero_DroidFromDroidEntityMapper ?? throw new global::System.ArgumentNullException(nameof(getHero_Hero_DroidFromDroidEntityMapper)); _getHero_Hero_HumanFromHumanEntityMapper = getHero_Hero_HumanFromHumanEntityMapper ?? throw new global::System.ArgumentNullException(nameof(getHero_Hero_HumanFromHumanEntityMapper)); } global::System.Type global::StrawberryShake.IOperationResultDataFactory.ResultType => typeof(global::StrawberryShake.CodeGeneration.CSharp.Integration.StarWarsGetHero.IGetHeroResult); public GetHeroResult Create(global::StrawberryShake.IOperationResultDataInfo dataInfo, global::StrawberryShake.IEntityStoreSnapshot? snapshot = null) { if (snapshot is null) { snapshot = _entityStore.CurrentSnapshot; } if (dataInfo is GetHeroResultInfo info) { return new GetHeroResult(MapIGetHero_Hero(info.Hero, snapshot)); } throw new global::System.ArgumentException("GetHeroResultInfo expected."); } private global::StrawberryShake.CodeGeneration.CSharp.Integration.StarWarsGetHero.IGetHero_Hero? MapIGetHero_Hero(global::StrawberryShake.EntityId? entityId, global::StrawberryShake.IEntityStoreSnapshot snapshot) { if (entityId is null) { return null; } if (entityId.Value.Name.Equals("Droid", global::System.StringComparison.Ordinal)) { return _getHero_Hero_DroidFromDroidEntityMapper.Map(snapshot.GetEntity<global::StrawberryShake.CodeGeneration.CSharp.Integration.StarWarsGetHero.State.DroidEntity>(entityId.Value) ?? throw new global::StrawberryShake.GraphQLClientException()); } if (entityId.Value.Name.Equals("Human", global::System.StringComparison.Ordinal)) { return _getHero_Hero_HumanFromHumanEntityMapper.Map(snapshot.GetEntity<global::StrawberryShake.CodeGeneration.CSharp.Integration.StarWarsGetHero.State.HumanEntity>(entityId.Value) ?? throw new global::StrawberryShake.GraphQLClientException()); } throw new global::System.NotSupportedException(); } global::System.Object global::StrawberryShake.IOperationResultDataFactory.Create(global::StrawberryShake.IOperationResultDataInfo dataInfo, global::StrawberryShake.IEntityStoreSnapshot? snapshot) { return Create(dataInfo, snapshot); } } // StrawberryShake.CodeGeneration.CSharp.Generators.ResultInfoGenerator [global::System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "11.0.0")] public partial class GetHeroResultInfo : global::StrawberryShake.IOperationResultDataInfo { private readonly global::System.Collections.Generic.IReadOnlyCollection<global::StrawberryShake.EntityId> _entityIds; private readonly global::System.UInt64 _version; public GetHeroResultInfo(global::StrawberryShake.EntityId? hero, global::System.Collections.Generic.IReadOnlyCollection<global::StrawberryShake.EntityId> entityIds, global::System.UInt64 version) { Hero = hero; _entityIds = entityIds ?? throw new global::System.ArgumentNullException(nameof(entityIds)); _version = version; } public global::StrawberryShake.EntityId? Hero { get; } public global::System.Collections.Generic.IReadOnlyCollection<global::StrawberryShake.EntityId> EntityIds => _entityIds; public global::System.UInt64 Version => _version; public global::StrawberryShake.IOperationResultDataInfo WithVersion(global::System.UInt64 version) { return new GetHeroResultInfo(Hero, _entityIds, version); } } // StrawberryShake.CodeGeneration.CSharp.Generators.ResultFromEntityTypeMapperGenerator [global::System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "11.0.0")] public partial class GetHero_Hero_DroidFromDroidEntityMapper : global::StrawberryShake.IEntityMapper<global::StrawberryShake.CodeGeneration.CSharp.Integration.StarWarsGetHero.State.DroidEntity, GetHero_Hero_Droid> { private readonly global::StrawberryShake.IEntityStore _entityStore; public GetHero_Hero_DroidFromDroidEntityMapper(global::StrawberryShake.IEntityStore entityStore) { _entityStore = entityStore ?? throw new global::System.ArgumentNullException(nameof(entityStore)); } public GetHero_Hero_Droid Map(global::StrawberryShake.CodeGeneration.CSharp.Integration.StarWarsGetHero.State.DroidEntity entity, global::StrawberryShake.IEntityStoreSnapshot? snapshot = null) { if (snapshot is null) { snapshot = _entityStore.CurrentSnapshot; } return new GetHero_Hero_Droid(entity.Name); } } // StrawberryShake.CodeGeneration.CSharp.Generators.ResultFromEntityTypeMapperGenerator [global::System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "11.0.0")] public partial class GetHero_Hero_HumanFromHumanEntityMapper : global::StrawberryShake.IEntityMapper<global::StrawberryShake.CodeGeneration.CSharp.Integration.StarWarsGetHero.State.HumanEntity, GetHero_Hero_Human> { private readonly global::StrawberryShake.IEntityStore _entityStore; public GetHero_Hero_HumanFromHumanEntityMapper(global::StrawberryShake.IEntityStore entityStore) { _entityStore = entityStore ?? throw new global::System.ArgumentNullException(nameof(entityStore)); } public GetHero_Hero_Human Map(global::StrawberryShake.CodeGeneration.CSharp.Integration.StarWarsGetHero.State.HumanEntity entity, global::StrawberryShake.IEntityStoreSnapshot? snapshot = null) { if (snapshot is null) { snapshot = _entityStore.CurrentSnapshot; } return new GetHero_Hero_Human(entity.Name); } } // StrawberryShake.CodeGeneration.CSharp.Generators.JsonResultBuilderGenerator [global::System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "11.0.0")] public partial class GetHeroBuilder : global::StrawberryShake.IOperationResultBuilder<global::System.Text.Json.JsonDocument, global::StrawberryShake.CodeGeneration.CSharp.Integration.StarWarsGetHero.IGetHeroResult> { private readonly global::StrawberryShake.IEntityStore _entityStore; private readonly global::StrawberryShake.IEntityIdSerializer _idSerializer; private readonly global::StrawberryShake.IOperationResultDataFactory<global::StrawberryShake.CodeGeneration.CSharp.Integration.StarWarsGetHero.IGetHeroResult> _resultDataFactory; private readonly global::StrawberryShake.Serialization.ILeafValueParser<global::System.String, global::System.String> _stringParser; public GetHeroBuilder(global::StrawberryShake.IEntityStore entityStore, global::StrawberryShake.IEntityIdSerializer idSerializer, global::StrawberryShake.IOperationResultDataFactory<global::StrawberryShake.CodeGeneration.CSharp.Integration.StarWarsGetHero.IGetHeroResult> resultDataFactory, global::StrawberryShake.Serialization.ISerializerResolver serializerResolver) { _entityStore = entityStore ?? throw new global::System.ArgumentNullException(nameof(entityStore)); _idSerializer = idSerializer ?? throw new global::System.ArgumentNullException(nameof(idSerializer)); _resultDataFactory = resultDataFactory ?? throw new global::System.ArgumentNullException(nameof(resultDataFactory)); _stringParser = serializerResolver.GetLeafValueParser<global::System.String, global::System.String>("String") ?? throw new global::System.ArgumentException("No serializer for type `String` found."); } public global::StrawberryShake.IOperationResult<IGetHeroResult> Build(global::StrawberryShake.Response<global::System.Text.Json.JsonDocument> response) { (IGetHeroResult Result, GetHeroResultInfo Info)? data = null; global::System.Collections.Generic.IReadOnlyList<global::StrawberryShake.IClientError>? errors = null; try { if (response.Body != null) { if (response.Body.RootElement.TryGetProperty("data", out global::System.Text.Json.JsonElement dataElement) && dataElement.ValueKind == global::System.Text.Json.JsonValueKind.Object) { data = BuildData(dataElement); } if (response.Body.RootElement.TryGetProperty("errors", out global::System.Text.Json.JsonElement errorsElement)) { errors = global::StrawberryShake.Json.JsonErrorParser.ParseErrors(errorsElement); } } } catch (global::System.Exception ex) { errors = new global::StrawberryShake.IClientError[]{new global::StrawberryShake.ClientError(ex.Message, exception: ex)}; } return new global::StrawberryShake.OperationResult<IGetHeroResult>(data?.Result, data?.Info, _resultDataFactory, errors); } private (IGetHeroResult, GetHeroResultInfo) BuildData(global::System.Text.Json.JsonElement obj) { var entityIds = new global::System.Collections.Generic.HashSet<global::StrawberryShake.EntityId>(); global::StrawberryShake.IEntityStoreSnapshot snapshot = default !; global::StrawberryShake.EntityId? heroId = default !; _entityStore.Update(session => { heroId = UpdateIGetHero_HeroEntity(session, global::StrawberryShake.Json.JsonElementExtensions.GetPropertyOrNull(obj, "hero"), entityIds); snapshot = session.CurrentSnapshot; }); var resultInfo = new GetHeroResultInfo(heroId, entityIds, snapshot.Version); return (_resultDataFactory.Create(resultInfo), resultInfo); } private global::StrawberryShake.EntityId? UpdateIGetHero_HeroEntity(global::StrawberryShake.IEntityStoreUpdateSession session, global::System.Text.Json.JsonElement? obj, global::System.Collections.Generic.ISet<global::StrawberryShake.EntityId> entityIds) { if (!obj.HasValue) { return null; } global::StrawberryShake.EntityId entityId = _idSerializer.Parse(obj.Value); entityIds.Add(entityId); if (entityId.Name.Equals("Droid", global::System.StringComparison.Ordinal)) { if (session.CurrentSnapshot.TryGetEntity(entityId, out global::StrawberryShake.CodeGeneration.CSharp.Integration.StarWarsGetHero.State.DroidEntity? entity)) { session.SetEntity(entityId, new global::StrawberryShake.CodeGeneration.CSharp.Integration.StarWarsGetHero.State.DroidEntity(DeserializeNonNullableString(global::StrawberryShake.Json.JsonElementExtensions.GetPropertyOrNull(obj, "name")))); } else { session.SetEntity(entityId, new global::StrawberryShake.CodeGeneration.CSharp.Integration.StarWarsGetHero.State.DroidEntity(DeserializeNonNullableString(global::StrawberryShake.Json.JsonElementExtensions.GetPropertyOrNull(obj, "name")))); } return entityId; } if (entityId.Name.Equals("Human", global::System.StringComparison.Ordinal)) { if (session.CurrentSnapshot.TryGetEntity(entityId, out global::StrawberryShake.CodeGeneration.CSharp.Integration.StarWarsGetHero.State.HumanEntity? entity)) { session.SetEntity(entityId, new global::StrawberryShake.CodeGeneration.CSharp.Integration.StarWarsGetHero.State.HumanEntity(DeserializeNonNullableString(global::StrawberryShake.Json.JsonElementExtensions.GetPropertyOrNull(obj, "name")))); } else { session.SetEntity(entityId, new global::StrawberryShake.CodeGeneration.CSharp.Integration.StarWarsGetHero.State.HumanEntity(DeserializeNonNullableString(global::StrawberryShake.Json.JsonElementExtensions.GetPropertyOrNull(obj, "name")))); } return entityId; } throw new global::System.NotSupportedException(); } private global::System.String DeserializeNonNullableString(global::System.Text.Json.JsonElement? obj) { if (!obj.HasValue) { throw new global::System.ArgumentNullException(); } return _stringParser.Parse(obj.Value.GetString()!); } } // StrawberryShake.CodeGeneration.CSharp.Generators.EntityIdFactoryGenerator [global::System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "11.0.0")] public partial class StarWarsGetHeroClientEntityIdFactory : global::StrawberryShake.IEntityIdSerializer { private static readonly global::System.Text.Json.JsonWriterOptions _options = new global::System.Text.Json.JsonWriterOptions() {Indented = false}; public global::StrawberryShake.EntityId Parse(global::System.Text.Json.JsonElement obj) { global::System.String __typename = obj.GetProperty("__typename").GetString()!; return __typename switch { "Droid" => ParseDroidEntityId(obj, __typename), "Human" => ParseHumanEntityId(obj, __typename), _ => throw new global::System.NotSupportedException()} ; } public global::System.String Format(global::StrawberryShake.EntityId entityId) { return entityId.Name switch { "Droid" => FormatDroidEntityId(entityId), "Human" => FormatHumanEntityId(entityId), _ => throw new global::System.NotSupportedException()} ; } private global::StrawberryShake.EntityId ParseDroidEntityId(global::System.Text.Json.JsonElement obj, global::System.String type) { return new global::StrawberryShake.EntityId(type, obj.GetProperty("id").GetString()!); } private global::System.String FormatDroidEntityId(global::StrawberryShake.EntityId entityId) { using var writer = new global::StrawberryShake.Internal.ArrayWriter(); using var jsonWriter = new global::System.Text.Json.Utf8JsonWriter(writer, _options); jsonWriter.WriteStartObject(); jsonWriter.WriteString("__typename", entityId.Name); jsonWriter.WriteString("id", (global::System.String)entityId.Value); jsonWriter.WriteEndObject(); jsonWriter.Flush(); return global::System.Text.Encoding.UTF8.GetString(writer.GetInternalBuffer(), 0, writer.Length); } private global::StrawberryShake.EntityId ParseHumanEntityId(global::System.Text.Json.JsonElement obj, global::System.String type) { return new global::StrawberryShake.EntityId(type, obj.GetProperty("id").GetString()!); } private global::System.String FormatHumanEntityId(global::StrawberryShake.EntityId entityId) { using var writer = new global::StrawberryShake.Internal.ArrayWriter(); using var jsonWriter = new global::System.Text.Json.Utf8JsonWriter(writer, _options); jsonWriter.WriteStartObject(); jsonWriter.WriteString("__typename", entityId.Name); jsonWriter.WriteString("id", (global::System.String)entityId.Value); jsonWriter.WriteEndObject(); jsonWriter.Flush(); return global::System.Text.Encoding.UTF8.GetString(writer.GetInternalBuffer(), 0, writer.Length); } } // StrawberryShake.CodeGeneration.CSharp.Generators.StoreAccessorGenerator [global::System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "11.0.0")] public partial class StarWarsGetHeroClientStoreAccessor : global::StrawberryShake.StoreAccessor { public StarWarsGetHeroClientStoreAccessor(global::StrawberryShake.IOperationStore operationStore, global::StrawberryShake.IEntityStore entityStore, global::StrawberryShake.IEntityIdSerializer entityIdSerializer, global::System.Collections.Generic.IEnumerable<global::StrawberryShake.IOperationRequestFactory> requestFactories, global::System.Collections.Generic.IEnumerable<global::StrawberryShake.IOperationResultDataFactory> resultDataFactories): base(operationStore, entityStore, entityIdSerializer, requestFactories, resultDataFactories) { } } }
59.020457
1,723
0.722872
[ "MIT" ]
petli/hotchocolate
src/StrawberryShake/CodeGeneration/test/CodeGeneration.CSharp.Tests/Integration/StarWarsGetHeroTest.Client.cs
49,048
C#
// <auto-generated> // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v10/errors/audience_error.proto // </auto-generated> #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Google.Ads.GoogleAds.V10.Errors { /// <summary>Holder for reflection information generated from google/ads/googleads/v10/errors/audience_error.proto</summary> public static partial class AudienceErrorReflection { #region Descriptor /// <summary>File descriptor for google/ads/googleads/v10/errors/audience_error.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static AudienceErrorReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CjRnb29nbGUvYWRzL2dvb2dsZWFkcy92MTAvZXJyb3JzL2F1ZGllbmNlX2Vy", "cm9yLnByb3RvEh9nb29nbGUuYWRzLmdvb2dsZWFkcy52MTAuZXJyb3JzGhxn", "b29nbGUvYXBpL2Fubm90YXRpb25zLnByb3RvInIKEUF1ZGllbmNlRXJyb3JF", "bnVtIl0KDUF1ZGllbmNlRXJyb3ISDwoLVU5TUEVDSUZJRUQQABILCgdVTktO", "T1dOEAESFwoTTkFNRV9BTFJFQURZX0lOX1VTRRACEhUKEURJTUVOU0lPTl9J", "TlZBTElEEANC8gEKI2NvbS5nb29nbGUuYWRzLmdvb2dsZWFkcy52MTAuZXJy", "b3JzQhJBdWRpZW5jZUVycm9yUHJvdG9QAVpFZ29vZ2xlLmdvbGFuZy5vcmcv", "Z2VucHJvdG8vZ29vZ2xlYXBpcy9hZHMvZ29vZ2xlYWRzL3YxMC9lcnJvcnM7", "ZXJyb3JzogIDR0FBqgIfR29vZ2xlLkFkcy5Hb29nbGVBZHMuVjEwLkVycm9y", "c8oCH0dvb2dsZVxBZHNcR29vZ2xlQWRzXFYxMFxFcnJvcnPqAiNHb29nbGU6", "OkFkczo6R29vZ2xlQWRzOjpWMTA6OkVycm9yc2IGcHJvdG8z")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::Google.Api.AnnotationsReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Ads.GoogleAds.V10.Errors.AudienceErrorEnum), global::Google.Ads.GoogleAds.V10.Errors.AudienceErrorEnum.Parser, null, null, new[]{ typeof(global::Google.Ads.GoogleAds.V10.Errors.AudienceErrorEnum.Types.AudienceError) }, null, null) })); } #endregion } #region Messages /// <summary> /// Container for enum describing possible audience errors. /// </summary> public sealed partial class AudienceErrorEnum : pb::IMessage<AudienceErrorEnum> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<AudienceErrorEnum> _parser = new pb::MessageParser<AudienceErrorEnum>(() => new AudienceErrorEnum()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<AudienceErrorEnum> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Ads.GoogleAds.V10.Errors.AudienceErrorReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public AudienceErrorEnum() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public AudienceErrorEnum(AudienceErrorEnum other) : this() { _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public AudienceErrorEnum Clone() { return new AudienceErrorEnum(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as AudienceErrorEnum); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(AudienceErrorEnum other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(AudienceErrorEnum other) { if (other == null) { return; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; } } } #endif #region Nested types /// <summary>Container for nested types declared in the AudienceErrorEnum message type.</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static partial class Types { /// <summary> /// Enum describing possible audience errors. /// </summary> public enum AudienceError { /// <summary> /// Enum unspecified. /// </summary> [pbr::OriginalName("UNSPECIFIED")] Unspecified = 0, /// <summary> /// The received error code is not known in this version. /// </summary> [pbr::OriginalName("UNKNOWN")] Unknown = 1, /// <summary> /// An audience with this name already exists. /// </summary> [pbr::OriginalName("NAME_ALREADY_IN_USE")] NameAlreadyInUse = 2, /// <summary> /// A dimension within the audience definition is not valid. /// </summary> [pbr::OriginalName("DIMENSION_INVALID")] DimensionInvalid = 3, } } #endregion } #endregion } #endregion Designer generated code
38.579832
294
0.701154
[ "Apache-2.0" ]
friedenberg/google-ads-dotnet
src/V10/Services/AudienceError.g.cs
9,182
C#
using NUnit.Framework; using System; using System.Drawing; using System.Text; namespace ScottPlotTests { [TestFixture] public class Cookbook { readonly int width = 600; readonly int height = 400; public readonly string outputPath; public Cookbook() { outputPath = System.IO.Path.GetFullPath("cookbook"); SetUp(); } [OneTimeSetUp] public void SetUp() { if (System.IO.Directory.Exists(outputPath)) System.IO.Directory.Delete(outputPath, true); System.IO.Directory.CreateDirectory(outputPath); System.IO.Directory.CreateDirectory(outputPath + "/images/"); } [TearDown] public void TearDown() { Report.GenerateHTML(outputPath); } [Test] public void Figure_01a_Quickstart() { string name = System.Reflection.MethodBase.GetCurrentMethod().Name.Replace("Figure_", ""); string fileName = System.IO.Path.GetFullPath($"{outputPath}/images/{name}.png"); int pointCount = 50; double[] dataXs = ScottPlot.DataGen.Consecutive(pointCount); double[] dataSin = ScottPlot.DataGen.Sin(pointCount); double[] dataCos = ScottPlot.DataGen.Cos(pointCount); var plt = new ScottPlot.Plot(width, height); plt.PlotScatter(dataXs, dataSin); plt.PlotScatter(dataXs, dataCos); plt.Title("ScottPlot Quickstart"); plt.XLabel("Time (seconds)"); plt.YLabel("Potential (V)"); if (outputPath != null) plt.SaveFig(fileName); else Console.WriteLine(plt.GetHashCode()); Console.WriteLine($"Saved: {fileName}"); } [Test] public void Figure_01b_Automatic_Margins() { string name = System.Reflection.MethodBase.GetCurrentMethod().Name.Replace("Figure_", ""); string fileName = System.IO.Path.GetFullPath($"{outputPath}/images/{name}.png"); int pointCount = 50; double[] dataXs = ScottPlot.DataGen.Consecutive(pointCount); double[] dataSin = ScottPlot.DataGen.Sin(pointCount); double[] dataCos = ScottPlot.DataGen.Cos(pointCount); var plt = new ScottPlot.Plot(width, height); plt.PlotScatter(dataXs, dataSin); plt.PlotScatter(dataXs, dataCos); plt.AxisAuto(0, .5); // no horizontal padding, 50% vertical padding if (outputPath != null) plt.SaveFig(fileName); else Console.WriteLine(plt.GetHashCode()); Console.WriteLine($"Saved: {fileName}"); } [Test] public void Figure_01c_Defined_Axis_Limits() { string name = System.Reflection.MethodBase.GetCurrentMethod().Name.Replace("Figure_", ""); string fileName = System.IO.Path.GetFullPath($"{outputPath}/images/{name}.png"); int pointCount = 50; double[] dataXs = ScottPlot.DataGen.Consecutive(pointCount); double[] dataSin = ScottPlot.DataGen.Sin(pointCount); double[] dataCos = ScottPlot.DataGen.Cos(pointCount); var plt = new ScottPlot.Plot(width, height); plt.PlotScatter(dataXs, dataSin); plt.PlotScatter(dataXs, dataCos); plt.Axis(2, 8, .2, 1.1); // x1, x2, y1, y2 if (outputPath != null) plt.SaveFig(fileName); else Console.WriteLine(plt.GetHashCode()); Console.WriteLine($"Saved: {fileName}"); } [Test] public void Figure_01d_Zoom_and_Pan() { string name = System.Reflection.MethodBase.GetCurrentMethod().Name.Replace("Figure_", ""); string fileName = System.IO.Path.GetFullPath($"{outputPath}/images/{name}.png"); int pointCount = 50; double[] dataXs = ScottPlot.DataGen.Consecutive(pointCount); double[] dataSin = ScottPlot.DataGen.Sin(pointCount); double[] dataCos = ScottPlot.DataGen.Cos(pointCount); var plt = new ScottPlot.Plot(width, height); plt.PlotScatter(dataXs, dataSin); plt.PlotScatter(dataXs, dataCos); plt.AxisZoom(2, 2); plt.AxisPan(-10, .5); if (outputPath != null) plt.SaveFig(fileName); else Console.WriteLine(plt.GetHashCode()); Console.WriteLine($"Saved: {fileName}"); } [Test] public void Figure_01e_Legend() { string name = System.Reflection.MethodBase.GetCurrentMethod().Name.Replace("Figure_", ""); string fileName = System.IO.Path.GetFullPath($"{outputPath}/images/{name}.png"); int pointCount = 50; double[] dataXs = ScottPlot.DataGen.Consecutive(pointCount); double[] dataSin = ScottPlot.DataGen.Sin(pointCount); double[] dataCos = ScottPlot.DataGen.Cos(pointCount); var plt = new ScottPlot.Plot(width, height); plt.PlotScatter(dataXs, dataSin, label: "first"); plt.PlotScatter(dataXs, dataCos, label: "second"); plt.Legend(location: ScottPlot.legendLocation.lowerLeft); if (outputPath != null) plt.SaveFig(fileName); else Console.WriteLine(plt.GetHashCode()); Console.WriteLine($"Saved: {fileName}"); } [Test] public void Figure_01f_Custom_Marker_Shapes() { string name = System.Reflection.MethodBase.GetCurrentMethod().Name.Replace("Figure_", ""); string fileName = System.IO.Path.GetFullPath($"{outputPath}/images/{name}.png"); int pointCount = 50; double[] dataXs = ScottPlot.DataGen.Consecutive(pointCount); double[] dataSin = ScottPlot.DataGen.Sin(pointCount); double[] dataCos = ScottPlot.DataGen.Cos(pointCount); var plt = new ScottPlot.Plot(width, height); plt.PlotScatter(dataXs, dataSin, label: "sin", markerShape: ScottPlot.MarkerShape.openCircle); plt.PlotScatter(dataXs, dataCos, label: "cos", markerShape: ScottPlot.MarkerShape.filledSquare); plt.Legend(); if (outputPath != null) plt.SaveFig(fileName); else Console.WriteLine(plt.GetHashCode()); Console.WriteLine($"Saved: {fileName}"); } [Test] public void Figure_01g_All_Marker_Shapes() { string name = System.Reflection.MethodBase.GetCurrentMethod().Name.Replace("Figure_", ""); string fileName = System.IO.Path.GetFullPath($"{outputPath}/images/{name}.png"); int pointCount = 50; double[] dataXs = ScottPlot.DataGen.Consecutive(pointCount); double[] dataSin = ScottPlot.DataGen.Sin(pointCount); double[] dataCos = ScottPlot.DataGen.Cos(pointCount); var plt = new ScottPlot.Plot(width, height); plt.Title("ScottPlot Marker Shapes"); plt.Grid(false); // plot a sine wave for every marker available string[] markerShapeNames = Enum.GetNames(typeof(ScottPlot.MarkerShape)); for (int i = 0; i < markerShapeNames.Length; i++) { string markerShapeName = markerShapeNames[i]; var markerShape = (ScottPlot.MarkerShape)Enum.Parse(typeof(ScottPlot.MarkerShape), markerShapeName); double[] stackedSin = ScottPlot.DataGen.Sin(dataXs.Length, 2, -i); plt.PlotScatter(dataXs, stackedSin, label: markerShapeName, markerShape: markerShape); } plt.Legend(fontSize: 10); if (outputPath != null) plt.SaveFig(fileName); else Console.WriteLine(plt.GetHashCode()); Console.WriteLine($"Saved: {fileName}"); } [Test] public void Figure_02_Styling_Scatter_Plots() { string name = System.Reflection.MethodBase.GetCurrentMethod().Name.Replace("Figure_", ""); string fileName = System.IO.Path.GetFullPath($"{outputPath}/images/{name}.png"); int pointCount = 50; double[] dataXs = ScottPlot.DataGen.Consecutive(pointCount); double[] dataSin = ScottPlot.DataGen.Sin(pointCount); double[] dataCos = ScottPlot.DataGen.Cos(pointCount); var plt = new ScottPlot.Plot(width, height); plt.PlotScatter(dataXs, dataSin, color: Color.Magenta, lineWidth: 0, markerSize: 10, label: "sin"); plt.PlotScatter(dataXs, dataCos, color: Color.Green, lineWidth: 5, markerSize: 0, label: "cos"); plt.Legend(fixedLineWidth: false); if (outputPath != null) plt.SaveFig(fileName); else Console.WriteLine(plt.GetHashCode()); Console.WriteLine($"Saved: {fileName}"); } [Test] public void Figure_03_Plot_XY_Data() { string name = System.Reflection.MethodBase.GetCurrentMethod().Name.Replace("Figure_", ""); string fileName = System.IO.Path.GetFullPath($"{outputPath}/images/{name}.png"); Random rand = new Random(0); int pointCount = 50; double[] dataRandom1 = ScottPlot.DataGen.RandomNormal(rand, pointCount); double[] dataRandom2 = ScottPlot.DataGen.RandomNormal(rand, pointCount); var plt = new ScottPlot.Plot(width, height); plt.PlotScatter(dataRandom1, dataRandom2); if (outputPath != null) plt.SaveFig(fileName); else Console.WriteLine(plt.GetHashCode()); Console.WriteLine($"Saved: {fileName}"); } [Test] public void Figure_04_Plot_Lines_Only() { string name = System.Reflection.MethodBase.GetCurrentMethod().Name.Replace("Figure_", ""); string fileName = System.IO.Path.GetFullPath($"{outputPath}/images/{name}.png"); Random rand = new Random(0); int pointCount = 50; double[] dataRandom1 = ScottPlot.DataGen.RandomNormal(rand, pointCount, 1); double[] dataRandom2 = ScottPlot.DataGen.RandomNormal(rand, pointCount, 2); double[] dataRandom3 = ScottPlot.DataGen.RandomNormal(rand, pointCount, 3); double[] dataRandom4 = ScottPlot.DataGen.RandomNormal(rand, pointCount, 4); var plt = new ScottPlot.Plot(width, height); plt.PlotScatter(dataRandom1, dataRandom2, markerSize: 0); plt.PlotScatter(dataRandom3, dataRandom4, markerSize: 0); if (outputPath != null) plt.SaveFig(fileName); else Console.WriteLine(plt.GetHashCode()); Console.WriteLine($"Saved: {fileName}"); } [Test] public void Figure_05_Plot_Points_Only() { string name = System.Reflection.MethodBase.GetCurrentMethod().Name.Replace("Figure_", ""); string fileName = System.IO.Path.GetFullPath($"{outputPath}/images/{name}.png"); Random rand = new Random(0); int pointCount = 50; double[] dataRandom1 = ScottPlot.DataGen.RandomNormal(rand, pointCount, 1); double[] dataRandom2 = ScottPlot.DataGen.RandomNormal(rand, pointCount, 2); double[] dataRandom3 = ScottPlot.DataGen.RandomNormal(rand, pointCount, 3); double[] dataRandom4 = ScottPlot.DataGen.RandomNormal(rand, pointCount, 4); var plt = new ScottPlot.Plot(width, height); plt.PlotScatter(dataRandom1, dataRandom2, lineWidth: 0); plt.PlotScatter(dataRandom3, dataRandom4, lineWidth: 0); if (outputPath != null) plt.SaveFig(fileName); else Console.WriteLine(plt.GetHashCode()); Console.WriteLine($"Saved: {fileName}"); } [Test] public void Figure_06_Styling_XY_Plots() { string name = System.Reflection.MethodBase.GetCurrentMethod().Name.Replace("Figure_", ""); string fileName = System.IO.Path.GetFullPath($"{outputPath}/images/{name}.png"); Random rand = new Random(0); int pointCount = 50; double[] dataRandom1 = ScottPlot.DataGen.RandomNormal(rand, pointCount, 1); double[] dataRandom2 = ScottPlot.DataGen.RandomNormal(rand, pointCount, 2); double[] dataRandom3 = ScottPlot.DataGen.RandomNormal(rand, pointCount, 3); double[] dataRandom4 = ScottPlot.DataGen.RandomNormal(rand, pointCount, 4); var plt = new ScottPlot.Plot(width, height); plt.PlotScatter(dataRandom1, dataRandom2, color: Color.Magenta, lineWidth: 3, markerSize: 15); plt.PlotScatter(dataRandom3, dataRandom4, color: Color.Green, lineWidth: 3, markerSize: 15); if (outputPath != null) plt.SaveFig(fileName); else Console.WriteLine(plt.GetHashCode()); Console.WriteLine($"Saved: {fileName}"); } [Test] public void Figure_06b_Custom_LineStyles() { string name = System.Reflection.MethodBase.GetCurrentMethod().Name.Replace("Figure_", ""); string fileName = System.IO.Path.GetFullPath($"{outputPath}/images/{name}.png"); Random rand = new Random(0); int pointCount = 50; double[] dataRandom1 = ScottPlot.DataGen.RandomNormal(rand, pointCount, 1); double[] dataRandom2 = ScottPlot.DataGen.RandomNormal(rand, pointCount, 2); double[] dataRandom3 = ScottPlot.DataGen.RandomNormal(rand, pointCount, 3); double[] dataRandom4 = ScottPlot.DataGen.RandomNormal(rand, pointCount, 4); var plt = new ScottPlot.Plot(width, height); plt.PlotScatter(dataRandom1, dataRandom2, label: "dash", lineStyle: ScottPlot.LineStyle.Dash); plt.PlotScatter(dataRandom3, dataRandom4, label: "dash dot dot", lineStyle: ScottPlot.LineStyle.DashDotDot); plt.Legend(); if (outputPath != null) plt.SaveFig(fileName); else Console.WriteLine(plt.GetHashCode()); Console.WriteLine($"Saved: {fileName}"); } [Test] public void Figure_07_Plotting_Points() { string name = System.Reflection.MethodBase.GetCurrentMethod().Name.Replace("Figure_", ""); string fileName = System.IO.Path.GetFullPath($"{outputPath}/images/{name}.png"); int pointCount = 50; double[] dataXs = ScottPlot.DataGen.Consecutive(pointCount); double[] dataSin = ScottPlot.DataGen.Sin(pointCount); double[] dataCos = ScottPlot.DataGen.Cos(pointCount); var plt = new ScottPlot.Plot(width, height); plt.PlotScatter(dataXs, dataSin); plt.PlotScatter(dataXs, dataCos); plt.PlotPoint(25, 0.8); plt.PlotPoint(30, 0.3, color: Color.Magenta, markerSize: 15); if (outputPath != null) plt.SaveFig(fileName); else Console.WriteLine(plt.GetHashCode()); Console.WriteLine($"Saved: {fileName}"); } [Test] public void Figure_08_Plotting_Text() { string name = System.Reflection.MethodBase.GetCurrentMethod().Name.Replace("Figure_", ""); string fileName = System.IO.Path.GetFullPath($"{outputPath}/images/{name}.png"); int pointCount = 50; double[] dataXs = ScottPlot.DataGen.Consecutive(pointCount); double[] dataSin = ScottPlot.DataGen.Sin(pointCount); double[] dataCos = ScottPlot.DataGen.Cos(pointCount); var plt = new ScottPlot.Plot(width, height); plt.PlotScatter(dataXs, dataSin); plt.PlotScatter(dataXs, dataCos); plt.PlotPoint(25, 0.8, color: Color.Green); plt.PlotText(" important point", 25, 0.8, color: Color.Green); plt.PlotPoint(30, 0.3, color: Color.Black, markerSize: 15); plt.PlotText(" default alignment", 30, 0.3, fontSize: 16, bold: true, color: Color.Magenta); plt.PlotPoint(30, 0, color: Color.Black, markerSize: 15); plt.PlotText("middle center", 30, 0, fontSize: 16, bold: true, color: Color.Magenta, alignment: ScottPlot.TextAlignment.middleCenter); plt.PlotPoint(30, -0.3, color: Color.Black, markerSize: 15); plt.PlotText("upper left", 30, -0.3, fontSize: 16, bold: true, color: Color.Magenta, alignment: ScottPlot.TextAlignment.upperLeft); plt.PlotPoint(5, -.5, color: Color.Blue, markerSize: 15); plt.PlotText(" Rotated Text", 5, -.5, fontSize: 16, color: Color.Blue, bold: true, rotation: -30); plt.PlotText("Framed Text", 15, -.6, fontSize: 16, color: Color.White, bold: true, frame: true, frameColor: Color.DarkRed); if (outputPath != null) plt.SaveFig(fileName); else Console.WriteLine(plt.GetHashCode()); Console.WriteLine($"Saved: {fileName}"); } [Test] public void Figure_09_Clearing_Plots() { string name = System.Reflection.MethodBase.GetCurrentMethod().Name.Replace("Figure_", ""); string fileName = System.IO.Path.GetFullPath($"{outputPath}/images/{name}.png"); int pointCount = 50; double[] dataXs = ScottPlot.DataGen.Consecutive(pointCount); double[] dataSin = ScottPlot.DataGen.Sin(pointCount); double[] dataCos = ScottPlot.DataGen.Cos(pointCount); Random rand = new Random(0); double[] dataRandom1 = ScottPlot.DataGen.RandomNormal(rand, pointCount, 1); double[] dataRandom2 = ScottPlot.DataGen.RandomNormal(rand, pointCount, 2); var plt = new ScottPlot.Plot(width, height); plt.PlotScatter(dataXs, dataSin); plt.PlotScatter(dataXs, dataCos); plt.Clear(); plt.PlotScatter(dataRandom1, dataRandom2); if (outputPath != null) plt.SaveFig(fileName); else Console.WriteLine(plt.GetHashCode()); Console.WriteLine($"Saved: {fileName}"); } [Test] public void Figure_10_Modifying_Plotted_Data() { string name = System.Reflection.MethodBase.GetCurrentMethod().Name.Replace("Figure_", ""); string fileName = System.IO.Path.GetFullPath($"{outputPath}/images/{name}.png"); int pointCount = 50; double[] dataXs = ScottPlot.DataGen.Consecutive(pointCount); double[] dataSin = ScottPlot.DataGen.Sin(pointCount); double[] dataCos = ScottPlot.DataGen.Cos(pointCount); var plt = new ScottPlot.Plot(width, height); plt.PlotScatter(dataXs, dataSin); plt.PlotScatter(dataXs, dataCos); // After an array is plotted with PlotSignal() or PlotScatter() its contents // can be updated (by changing values in the array) and they will be displayed // at the next render. This makes it easy to create live displays. for (int i = 10; i < 20; i++) { dataSin[i] = i / 10.0; dataCos[i] = 2 * i / 10.0; } if (outputPath != null) plt.SaveFig(fileName); else Console.WriteLine(plt.GetHashCode()); Console.WriteLine($"Saved: {fileName}"); } [Test] public void Figure_11_Modify_Styles_After_Plotting() { string name = System.Reflection.MethodBase.GetCurrentMethod().Name.Replace("Figure_", ""); string fileName = System.IO.Path.GetFullPath($"{outputPath}/images/{name}.png"); int pointCount = 50; double[] dataXs = ScottPlot.DataGen.Consecutive(pointCount); double[] dataSin = ScottPlot.DataGen.Sin(pointCount); double[] dataCos = ScottPlot.DataGen.Cos(pointCount); var plt = new ScottPlot.Plot(width, height); // All Plot functions return the object that was just created. var scatter1 = plt.PlotScatter(dataXs, dataSin); var scatter2 = plt.PlotScatter(dataXs, dataCos); var horizontalLine = plt.PlotHLine(0, lineWidth: 3); // This allows you to modify the object's properties later. scatter1.color = Color.Pink; scatter2.markerShape = ScottPlot.MarkerShape.openCircle; horizontalLine.position = 0.7654; if (outputPath != null) plt.SaveFig(fileName); else Console.WriteLine(plt.GetHashCode()); Console.WriteLine($"Saved: {fileName}"); } [Test] public void Figure_12_Date_Axis() { string name = System.Reflection.MethodBase.GetCurrentMethod().Name.Replace("Figure_", ""); string fileName = System.IO.Path.GetFullPath($"{outputPath}/images/{name}.png"); Random rand = new Random(0); double[] price = ScottPlot.DataGen.RandomWalk(rand, 60 * 8); DateTime start = new DateTime(2019, 08, 25, 8, 30, 00); double pointsPerDay = 24 * 60; // one point per minute var plt = new ScottPlot.Plot(width, height); plt.PlotSignal(price, sampleRate: pointsPerDay, xOffset: start.ToOADate()); plt.Ticks(dateTimeX: true); plt.YLabel("Price"); plt.XLabel("Date and Time"); if (outputPath != null) plt.SaveFig(fileName); else Console.WriteLine(plt.GetHashCode()); Console.WriteLine($"Saved: {fileName}"); } [Test] public void Figure_13_Ruler_Mode() { string name = System.Reflection.MethodBase.GetCurrentMethod().Name.Replace("Figure_", ""); string fileName = System.IO.Path.GetFullPath($"{outputPath}/images/{name}.png"); int pointCount = 50; double[] dataXs = ScottPlot.DataGen.Consecutive(pointCount); double[] dataSin = ScottPlot.DataGen.Sin(pointCount); double[] dataCos = ScottPlot.DataGen.Cos(pointCount); var plt = new ScottPlot.Plot(width, height); plt.PlotScatter(dataXs, dataSin); plt.PlotScatter(dataXs, dataCos); plt.Frame(right: false, top: false); plt.Ticks(rulerModeX: true, rulerModeY: true); // enable ruler mode like this plt.AxisAuto(0, 0); if (outputPath != null) plt.SaveFig(fileName); else Console.WriteLine(plt.GetHashCode()); Console.WriteLine($"Saved: {fileName}"); } [Test] public void Figure_14_Custom_Tick_Labels() { string name = System.Reflection.MethodBase.GetCurrentMethod().Name.Replace("Figure_", ""); string fileName = System.IO.Path.GetFullPath($"{outputPath}/images/{name}.png"); var plt = new ScottPlot.Plot(width, height); plt.Title("Custom Tick Positions and Labels"); plt.PlotSignal(ScottPlot.DataGen.Sin(50)); double[] xPositions = { 7, 21, 37, 46 }; string[] xLabels = { "VII", "XXI", "XXXVII", "XLVI" }; plt.XTicks(xPositions, xLabels); double[] yPositions = { -1, 0, .5, 1 }; string[] yPabels = { "bottom", "center", "half", "top" }; plt.YTicks(yPositions, yPabels); if (outputPath != null) plt.SaveFig(fileName); else Console.WriteLine(plt.GetHashCode()); Console.WriteLine($"Saved: {fileName}"); } [Test] public void Figure_15_Descending_Ticks() { string name = System.Reflection.MethodBase.GetCurrentMethod().Name.Replace("Figure_", ""); string fileName = System.IO.Path.GetFullPath($"{outputPath}/images/{name}.png"); var plt = new ScottPlot.Plot(width, height); // to simulate an inverted (descending) horizontal axis, plot in the negative space plt.PlotSignal(ScottPlot.DataGen.Sin(50), xOffset: -50); // then invert the sign of the horizontal axis labels plt.Ticks(invertSignX: true); plt.Ticks(invertSignY: true); if (outputPath != null) plt.SaveFig(fileName); else Console.WriteLine(plt.GetHashCode()); Console.WriteLine($"Saved: {fileName}"); } [Test] public void Figure_20_Small_Plot() { string name = System.Reflection.MethodBase.GetCurrentMethod().Name.Replace("Figure_", ""); string fileName = System.IO.Path.GetFullPath($"{outputPath}/images/{name}.png"); int pointCount = 50; double[] dataXs = ScottPlot.DataGen.Consecutive(pointCount); double[] dataSin = ScottPlot.DataGen.Sin(pointCount); double[] dataCos = ScottPlot.DataGen.Cos(pointCount); var plt = new ScottPlot.Plot(200, 150); plt.PlotScatter(dataXs, dataSin); plt.PlotScatter(dataXs, dataCos); if (outputPath != null) plt.SaveFig(fileName); else Console.WriteLine(plt.GetHashCode()); Console.WriteLine($"Saved: {fileName}"); } [Test] public void Figure_21a_Title_and_Axis_Labels() { string name = System.Reflection.MethodBase.GetCurrentMethod().Name.Replace("Figure_", ""); string fileName = System.IO.Path.GetFullPath($"{outputPath}/images/{name}.png"); int pointCount = 50; double[] dataXs = ScottPlot.DataGen.Consecutive(pointCount); double[] dataSin = ScottPlot.DataGen.Sin(pointCount); double[] dataCos = ScottPlot.DataGen.Cos(pointCount); var plt = new ScottPlot.Plot(width, height); plt.PlotScatter(dataXs, dataSin); plt.PlotScatter(dataXs, dataCos); plt.Title("Very Complicated Data"); plt.XLabel("Experiment Duration"); plt.YLabel("Productivity"); if (outputPath != null) plt.SaveFig(fileName); else Console.WriteLine(plt.GetHashCode()); Console.WriteLine($"Saved: {fileName}"); } [Test] public void Figure_21b_Custom_Padding() { string name = System.Reflection.MethodBase.GetCurrentMethod().Name.Replace("Figure_", ""); string fileName = System.IO.Path.GetFullPath($"{outputPath}/images/{name}.png"); int pointCount = 50; double[] dataXs = ScottPlot.DataGen.Consecutive(pointCount); double[] dataSin = ScottPlot.DataGen.Sin(pointCount); double[] dataCos = ScottPlot.DataGen.Cos(pointCount); var plt = new ScottPlot.Plot(width, height); plt.PlotScatter(dataXs, dataSin); plt.PlotScatter(dataXs, dataCos); plt.Style(figBg: Color.LightBlue); // Layout component sizes are typically auto-calculated by TightenLayout() // Plots without title or axis labels typically extend right to the edge of the image // You can call Layout() to manually define the sizes of plot components plt.Layout(yScaleWidth: 80, titleHeight: 50, xLabelHeight: 20, y2LabelWidth: 20); if (outputPath != null) plt.SaveFig(fileName); else Console.WriteLine(plt.GetHashCode()); Console.WriteLine($"Saved: {fileName}"); } [Test] public void Figure_21c_Automatic_Left_Padding() { string name = System.Reflection.MethodBase.GetCurrentMethod().Name.Replace("Figure_", ""); string fileName = System.IO.Path.GetFullPath($"{outputPath}/images/{name}.png"); var plt = new ScottPlot.Plot(width, height); Random rand = new Random(0); double[] xs = ScottPlot.DataGen.Consecutive(100); double[] ys = ScottPlot.DataGen.RandomWalk(rand, 100, 1e2, 1e15); plt.PlotScatter(xs, ys); plt.YLabel("vertical units"); plt.XLabel("horizontal units"); // this can be problematic because Y labels get very large plt.Ticks(useOffsetNotation: false, useMultiplierNotation: false); // tightening with a render is the best way to get the axes right plt.TightenLayout(render: true); if (outputPath != null) plt.SaveFig(fileName); else Console.WriteLine(plt.GetHashCode()); Console.WriteLine($"Saved: {fileName}"); } [Test] public void Figure_21d_Single_Axis_With_No_Padding() { string name = System.Reflection.MethodBase.GetCurrentMethod().Name.Replace("Figure_", ""); string fileName = System.IO.Path.GetFullPath($"{outputPath}/images/{name}.png"); var plt = new ScottPlot.Plot(width, height); Random rand = new Random(0); double[] xs = ScottPlot.DataGen.Consecutive(100); double[] ys = ScottPlot.DataGen.RandomWalk(rand, 100, 1e2, 1e15); plt.PlotScatter(xs, ys); plt.Style(figBg: Color.LightBlue); // customize your tick and frame style then tighten the layout plt.Ticks(rulerModeX: true, displayTicksY: false); plt.Frame(left: false, right: false, top: false); plt.TightenLayout(padding: 0, render: true); if (outputPath != null) plt.SaveFig(fileName); else Console.WriteLine(plt.GetHashCode()); Console.WriteLine($"Saved: {fileName}"); } [Test] public void Figure_22_Custom_Colors() { string name = System.Reflection.MethodBase.GetCurrentMethod().Name.Replace("Figure_", ""); string fileName = System.IO.Path.GetFullPath($"{outputPath}/images/{name}.png"); int pointCount = 50; double[] dataXs = ScottPlot.DataGen.Consecutive(pointCount); double[] dataSin = ScottPlot.DataGen.Sin(pointCount); double[] dataCos = ScottPlot.DataGen.Cos(pointCount); var plt = new ScottPlot.Plot(width, height); Color figureBgColor = ColorTranslator.FromHtml("#001021"); Color dataBgColor = ColorTranslator.FromHtml("#021d38"); plt.Style(figBg: figureBgColor, dataBg: dataBgColor); plt.Grid(color: ColorTranslator.FromHtml("#273c51")); plt.Ticks(color: Color.LightGray); plt.PlotScatter(dataXs, dataSin); plt.PlotScatter(dataXs, dataCos); plt.Title("Very Complicated Data", color: Color.White); plt.XLabel("Experiment Duration", color: Color.LightGray); plt.YLabel("Productivity", color: Color.LightGray); if (outputPath != null) plt.SaveFig(fileName); else Console.WriteLine(plt.GetHashCode()); Console.WriteLine($"Saved: {fileName}"); } [Test] public void Figure_23_Frameless_Plot() { string name = System.Reflection.MethodBase.GetCurrentMethod().Name.Replace("Figure_", ""); string fileName = System.IO.Path.GetFullPath($"{outputPath}/images/{name}.png"); int pointCount = 50; double[] dataXs = ScottPlot.DataGen.Consecutive(pointCount); double[] dataSin = ScottPlot.DataGen.Sin(pointCount); double[] dataCos = ScottPlot.DataGen.Cos(pointCount); var plt = new ScottPlot.Plot(width, height); Color figureBgColor = ColorTranslator.FromHtml("#001021"); Color dataBgColor = ColorTranslator.FromHtml("#021d38"); plt.Style(figBg: figureBgColor, dataBg: dataBgColor); plt.Grid(color: ColorTranslator.FromHtml("#273c51")); plt.Ticks(displayTicksX: false, displayTicksY: false); plt.Frame(drawFrame: false); // dont draw a square around the plot plt.TightenLayout(padding: 0); // dont pad the data area at all plt.PlotScatter(dataXs, dataSin); plt.PlotScatter(dataXs, dataCos); if (outputPath != null) plt.SaveFig(fileName); else Console.WriteLine(plt.GetHashCode()); Console.WriteLine($"Saved: {fileName}"); } [Test] public void Figure_24_Disable_the_Grid() { string name = System.Reflection.MethodBase.GetCurrentMethod().Name.Replace("Figure_", ""); string fileName = System.IO.Path.GetFullPath($"{outputPath}/images/{name}.png"); int pointCount = 50; double[] dataXs = ScottPlot.DataGen.Consecutive(pointCount); double[] dataSin = ScottPlot.DataGen.Sin(pointCount); double[] dataCos = ScottPlot.DataGen.Cos(pointCount); var plt = new ScottPlot.Plot(width, height); plt.PlotScatter(dataXs, dataSin); plt.PlotScatter(dataXs, dataCos); plt.Grid(false); if (outputPath != null) plt.SaveFig(fileName); else Console.WriteLine(plt.GetHashCode()); Console.WriteLine($"Saved: {fileName}"); } [Test] public void Figure_25_Corner_Axis_Frame() { string name = System.Reflection.MethodBase.GetCurrentMethod().Name.Replace("Figure_", ""); string fileName = System.IO.Path.GetFullPath($"{outputPath}/images/{name}.png"); int pointCount = 50; double[] dataXs = ScottPlot.DataGen.Consecutive(pointCount); double[] dataSin = ScottPlot.DataGen.Sin(pointCount); double[] dataCos = ScottPlot.DataGen.Cos(pointCount); var plt = new ScottPlot.Plot(width, height); plt.PlotScatter(dataXs, dataSin); plt.PlotScatter(dataXs, dataCos); plt.Grid(false); plt.Frame(right: false, top: false); if (outputPath != null) plt.SaveFig(fileName); else Console.WriteLine(plt.GetHashCode()); Console.WriteLine($"Saved: {fileName}"); } [Test] public void Figure_26_Horizontal_Ticks_Only() { string name = System.Reflection.MethodBase.GetCurrentMethod().Name.Replace("Figure_", ""); string fileName = System.IO.Path.GetFullPath($"{outputPath}/images/{name}.png"); int pointCount = 50; double[] dataXs = ScottPlot.DataGen.Consecutive(pointCount); double[] dataSin = ScottPlot.DataGen.Sin(pointCount); double[] dataCos = ScottPlot.DataGen.Cos(pointCount); var plt = new ScottPlot.Plot(width, height); plt.PlotScatter(dataXs, dataSin); plt.PlotScatter(dataXs, dataCos); plt.Grid(false); plt.Ticks(displayTicksY: false); plt.Frame(left: false, right: false, top: false); if (outputPath != null) plt.SaveFig(fileName); else Console.WriteLine(plt.GetHashCode()); Console.WriteLine($"Saved: {fileName}"); } [Test] public void Figure_27_Very_Large_Numbers() { string name = System.Reflection.MethodBase.GetCurrentMethod().Name.Replace("Figure_", ""); string fileName = System.IO.Path.GetFullPath($"{outputPath}/images/{name}.png"); Random rand = new Random(0); int pointCount = 100; double[] largeXs = ScottPlot.DataGen.Consecutive(pointCount, 1e17); double[] largeYs = ScottPlot.DataGen.Random(rand, pointCount, 1e21); var plt = new ScottPlot.Plot(width, height); plt.PlotScatter(largeXs, largeYs); if (outputPath != null) plt.SaveFig(fileName); else Console.WriteLine(plt.GetHashCode()); Console.WriteLine($"Saved: {fileName}"); } [Test] public void Figure_28_Axis_Exponent_And_Offset() { string name = System.Reflection.MethodBase.GetCurrentMethod().Name.Replace("Figure_", ""); string fileName = System.IO.Path.GetFullPath($"{outputPath}/images/{name}.png"); double bigNumber = 9876; var plt = new ScottPlot.Plot(width, height); plt.Title("panned far and really zoomed in"); plt.Axis(bigNumber, bigNumber + .00001, bigNumber, bigNumber + .00001); if (outputPath != null) plt.SaveFig(fileName); else Console.WriteLine(plt.GetHashCode()); Console.WriteLine($"Saved: {fileName}"); } [Test] public void Figure_28b_Multiplier_Notation_Default() { string name = System.Reflection.MethodBase.GetCurrentMethod().Name.Replace("Figure_", ""); string fileName = System.IO.Path.GetFullPath($"{outputPath}/images/{name}.png"); double[] tenMillionPoints = ScottPlot.DataGen.SinSweep(10_000_000, 8); var plt = new ScottPlot.Plot(width, height); plt.PlotSignal(tenMillionPoints); if (outputPath != null) plt.SaveFig(fileName); else Console.WriteLine(plt.GetHashCode()); Console.WriteLine($"Saved: {fileName}"); } public void Figure_28c_Multiplier_Notation_Disabled() { string name = System.Reflection.MethodBase.GetCurrentMethod().Name.Replace("Figure_", ""); string fileName = System.IO.Path.GetFullPath($"{outputPath}/images/{name}.png"); double[] tenMillionPoints = ScottPlot.DataGen.SinSweep(10_000_000, 8); var plt = new ScottPlot.Plot(width, height); plt.PlotSignal(tenMillionPoints); plt.Ticks(useMultiplierNotation: false); // <-- THIS if (outputPath != null) plt.SaveFig(fileName); else Console.WriteLine(plt.GetHashCode()); Console.WriteLine($"Saved: {fileName}"); } [Test] public void Figure_29_Very_Large_Images() { string name = System.Reflection.MethodBase.GetCurrentMethod().Name.Replace("Figure_", ""); string fileName = System.IO.Path.GetFullPath($"{outputPath}/images/{name}.png"); int pointCount = 50; double[] dataXs = ScottPlot.DataGen.Consecutive(pointCount); double[] dataSin = ScottPlot.DataGen.Sin(pointCount); double[] dataCos = ScottPlot.DataGen.Cos(pointCount); var plt = new ScottPlot.Plot(2000, 1000); plt.PlotScatter(dataXs, dataSin); plt.PlotScatter(dataXs, dataCos); if (outputPath != null) plt.SaveFig(fileName); else Console.WriteLine(plt.GetHashCode()); Console.WriteLine($"Saved: {fileName}"); } [Test] public void Figure_30a_Signal() { string name = System.Reflection.MethodBase.GetCurrentMethod().Name.Replace("Figure_", ""); string fileName = System.IO.Path.GetFullPath($"{outputPath}/images/{name}.png"); double[] tenMillionPoints = ScottPlot.DataGen.SinSweep(10_000_000, 8); // PlotSignal() is much faster than PlotScatter() for large arrays of evenly-spaed data. // To plot more than 2GB of data, enable "gcAllowVeryLargeObjects" in App.config (Google it) var plt = new ScottPlot.Plot(width, height); plt.Title("Displaying 10 million points with PlotSignal()"); plt.Benchmark(); plt.PlotSignal(tenMillionPoints, sampleRate: 20_000); if (outputPath != null) plt.SaveFig(fileName); else Console.WriteLine(plt.GetHashCode()); Console.WriteLine($"Saved: {fileName}"); } [Test] public void Figure_30c_SignalConst() { string name = System.Reflection.MethodBase.GetCurrentMethod().Name.Replace("Figure_", ""); string fileName = System.IO.Path.GetFullPath($"{outputPath}/images/{name}.png"); double[] tenMillionPoints = ScottPlot.DataGen.SinSweep(10_000_000, 8); // SignalConst() is faster than PlotSignal() for very large data plots // - its data cannot be modified after it is loaded // - here threading was turned off so it renders properly in a console application // - in GUI applications threading allows it to initially render faster but here it is turned off var plt = new ScottPlot.Plot(width, height); plt.Title("Displaying 10 million points with PlotSignalConst()"); plt.Benchmark(); plt.PlotSignalConst(tenMillionPoints, sampleRate: 20_000); if (outputPath != null) plt.SaveFig(fileName); else Console.WriteLine(plt.GetHashCode()); Console.WriteLine($"Saved: {fileName}"); } //[Test] public void Figure_30d_SignalConst_One_Billion_Points() { string name = System.Reflection.MethodBase.GetCurrentMethod().Name.Replace("Figure_", ""); string fileName = System.IO.Path.GetFullPath($"{outputPath}/images/{name}.png"); // SignalConst() accepts generic data types (here a byte array with a billion points) byte[] oneBillionPoints = ScottPlot.DataGen.SinSweepByte(1_000_000_000, 8); var plt = new ScottPlot.Plot(width, height); plt.Title("Display One Billion points with PlotSignalConst()"); plt.Benchmark(); plt.PlotSignalConst(oneBillionPoints, sampleRate: 20_000_000); if (outputPath != null) plt.SaveFig(fileName); else Console.WriteLine(plt.GetHashCode()); Console.WriteLine($"Saved: {fileName}"); } [Test] public void Figure_32_Signal_Styling() { string name = System.Reflection.MethodBase.GetCurrentMethod().Name.Replace("Figure_", ""); string fileName = System.IO.Path.GetFullPath($"{outputPath}/images/{name}.png"); double[] tenMillionPoints = ScottPlot.DataGen.SinSweep(10_000_000, 8); var plt = new ScottPlot.Plot(width, height); plt.PlotSignal(tenMillionPoints, 20000, lineWidth: 3, color: Color.Red); if (outputPath != null) plt.SaveFig(fileName); else Console.WriteLine(plt.GetHashCode()); Console.WriteLine($"Saved: {fileName}"); } [Test] public void Figure_40_Vertical_and_Horizontal_Lines() { string name = System.Reflection.MethodBase.GetCurrentMethod().Name.Replace("Figure_", ""); string fileName = System.IO.Path.GetFullPath($"{outputPath}/images/{name}.png"); int pointCount = 50; double[] dataXs = ScottPlot.DataGen.Consecutive(pointCount); double[] dataSin = ScottPlot.DataGen.Sin(pointCount); double[] dataCos = ScottPlot.DataGen.Cos(pointCount); var plt = new ScottPlot.Plot(width, height); plt.PlotScatter(dataXs, dataSin); plt.PlotScatter(dataXs, dataCos); plt.PlotVLine(17); plt.PlotHLine(-.25, color: Color.Red, lineWidth: 3); if (outputPath != null) plt.SaveFig(fileName); else Console.WriteLine(plt.GetHashCode()); Console.WriteLine($"Saved: {fileName}"); } [Test] public void Figure_41_Axis_Spans() { string name = System.Reflection.MethodBase.GetCurrentMethod().Name.Replace("Figure_", ""); string fileName = System.IO.Path.GetFullPath($"{outputPath}/images/{name}.png"); int pointCount = 50; double[] dataXs = ScottPlot.DataGen.Consecutive(pointCount); double[] dataSin = ScottPlot.DataGen.Sin(pointCount); double[] dataCos = ScottPlot.DataGen.Cos(pointCount); var plt = new ScottPlot.Plot(width, height); // things plotted after before spans are covered by them plt.PlotScatter(dataXs, dataSin, label: "below", color: Color.Red, markerShape: ScottPlot.MarkerShape.filledCircle); // vertical lines and horizontal spans both take X-axis positions plt.PlotVLine(17, label: "vertical line"); plt.PlotVSpan(19, 27, label: "horizontal span", color: Color.Blue); // horizontal lines and vertical spans both take Y-axis positions plt.PlotHLine(-.6, label: "horizontal line"); plt.PlotHSpan(-.25, 0.33, label: "vertical span", color: Color.Green); // things plotted after are displayed on top of the spans plt.PlotScatter(dataXs, dataCos, label: "above", color: Color.Red, markerShape: ScottPlot.MarkerShape.filledSquare); plt.Legend(); if (outputPath != null) plt.SaveFig(fileName); else Console.WriteLine(plt.GetHashCode()); Console.WriteLine($"Saved: {fileName}"); } [Test] public void Figure_50_StyleBlue1() { string name = System.Reflection.MethodBase.GetCurrentMethod().Name.Replace("Figure_", ""); string fileName = System.IO.Path.GetFullPath($"{outputPath}/images/{name}.png"); int pointCount = 50; double[] dataXs = ScottPlot.DataGen.Consecutive(pointCount); double[] dataSin = ScottPlot.DataGen.Sin(pointCount); double[] dataCos = ScottPlot.DataGen.Cos(pointCount); var plt = new ScottPlot.Plot(width, height); plt.PlotScatter(dataXs, dataSin, label: "sin"); plt.PlotScatter(dataXs, dataCos, label: "cos"); plt.Title("Very Complicated Data"); plt.XLabel("Experiment Duration"); plt.YLabel("Productivity"); plt.Legend(); plt.Style(ScottPlot.Style.Blue1); if (outputPath != null) plt.SaveFig(fileName); else Console.WriteLine(plt.GetHashCode()); Console.WriteLine($"Saved: {fileName}"); } [Test] public void Figure_51_StyleBlue2() { string name = System.Reflection.MethodBase.GetCurrentMethod().Name.Replace("Figure_", ""); string fileName = System.IO.Path.GetFullPath($"{outputPath}/images/{name}.png"); int pointCount = 50; double[] dataXs = ScottPlot.DataGen.Consecutive(pointCount); double[] dataSin = ScottPlot.DataGen.Sin(pointCount); double[] dataCos = ScottPlot.DataGen.Cos(pointCount); var plt = new ScottPlot.Plot(width, height); plt.PlotScatter(dataXs, dataSin, label: "sin"); plt.PlotScatter(dataXs, dataCos, label: "cos"); plt.Title("Very Complicated Data"); plt.XLabel("Experiment Duration"); plt.YLabel("Productivity"); plt.Legend(); plt.Style(ScottPlot.Style.Blue2); if (outputPath != null) plt.SaveFig(fileName); else Console.WriteLine(plt.GetHashCode()); Console.WriteLine($"Saved: {fileName}"); } [Test] public void Figure_52_StyleBlue3() { string name = System.Reflection.MethodBase.GetCurrentMethod().Name.Replace("Figure_", ""); string fileName = System.IO.Path.GetFullPath($"{outputPath}/images/{name}.png"); int pointCount = 50; double[] dataXs = ScottPlot.DataGen.Consecutive(pointCount); double[] dataSin = ScottPlot.DataGen.Sin(pointCount); double[] dataCos = ScottPlot.DataGen.Cos(pointCount); var plt = new ScottPlot.Plot(width, height); plt.PlotScatter(dataXs, dataSin, label: "sin"); plt.PlotScatter(dataXs, dataCos, label: "cos"); plt.Title("Very Complicated Data"); plt.XLabel("Experiment Duration"); plt.YLabel("Productivity"); plt.Legend(); plt.Style(ScottPlot.Style.Blue3); if (outputPath != null) plt.SaveFig(fileName); else Console.WriteLine(plt.GetHashCode()); Console.WriteLine($"Saved: {fileName}"); } [Test] public void Figure_53_StyleLight1() { string name = System.Reflection.MethodBase.GetCurrentMethod().Name.Replace("Figure_", ""); string fileName = System.IO.Path.GetFullPath($"{outputPath}/images/{name}.png"); int pointCount = 50; double[] dataXs = ScottPlot.DataGen.Consecutive(pointCount); double[] dataSin = ScottPlot.DataGen.Sin(pointCount); double[] dataCos = ScottPlot.DataGen.Cos(pointCount); var plt = new ScottPlot.Plot(width, height); plt.PlotScatter(dataXs, dataSin, label: "sin"); plt.PlotScatter(dataXs, dataCos, label: "cos"); plt.Title("Very Complicated Data"); plt.XLabel("Experiment Duration"); plt.YLabel("Productivity"); plt.Legend(); plt.Style(ScottPlot.Style.Light1); if (outputPath != null) plt.SaveFig(fileName); else Console.WriteLine(plt.GetHashCode()); Console.WriteLine($"Saved: {fileName}"); } [Test] public void Figure_54_StyleLight2() { string name = System.Reflection.MethodBase.GetCurrentMethod().Name.Replace("Figure_", ""); string fileName = System.IO.Path.GetFullPath($"{outputPath}/images/{name}.png"); int pointCount = 50; double[] dataXs = ScottPlot.DataGen.Consecutive(pointCount); double[] dataSin = ScottPlot.DataGen.Sin(pointCount); double[] dataCos = ScottPlot.DataGen.Cos(pointCount); var plt = new ScottPlot.Plot(width, height); plt.PlotScatter(dataXs, dataSin, label: "sin"); plt.PlotScatter(dataXs, dataCos, label: "cos"); plt.Title("Very Complicated Data"); plt.XLabel("Experiment Duration"); plt.YLabel("Productivity"); plt.Legend(); plt.Style(ScottPlot.Style.Light2); if (outputPath != null) plt.SaveFig(fileName); else Console.WriteLine(plt.GetHashCode()); Console.WriteLine($"Saved: {fileName}"); } [Test] public void Figure_55_StyleGray1() { string name = System.Reflection.MethodBase.GetCurrentMethod().Name.Replace("Figure_", ""); string fileName = System.IO.Path.GetFullPath($"{outputPath}/images/{name}.png"); int pointCount = 50; double[] dataXs = ScottPlot.DataGen.Consecutive(pointCount); double[] dataSin = ScottPlot.DataGen.Sin(pointCount); double[] dataCos = ScottPlot.DataGen.Cos(pointCount); var plt = new ScottPlot.Plot(width, height); plt.PlotScatter(dataXs, dataSin, label: "sin"); plt.PlotScatter(dataXs, dataCos, label: "cos"); plt.Title("Very Complicated Data"); plt.XLabel("Experiment Duration"); plt.YLabel("Productivity"); plt.Legend(); plt.Style(ScottPlot.Style.Gray1); if (outputPath != null) plt.SaveFig(fileName); else Console.WriteLine(plt.GetHashCode()); Console.WriteLine($"Saved: {fileName}"); } [Test] public void Figure_56_StyleGray2() { string name = System.Reflection.MethodBase.GetCurrentMethod().Name.Replace("Figure_", ""); string fileName = System.IO.Path.GetFullPath($"{outputPath}/images/{name}.png"); int pointCount = 50; double[] dataXs = ScottPlot.DataGen.Consecutive(pointCount); double[] dataSin = ScottPlot.DataGen.Sin(pointCount); double[] dataCos = ScottPlot.DataGen.Cos(pointCount); var plt = new ScottPlot.Plot(width, height); plt.PlotScatter(dataXs, dataSin, label: "sin"); plt.PlotScatter(dataXs, dataCos, label: "cos"); plt.Title("Very Complicated Data"); plt.XLabel("Experiment Duration"); plt.YLabel("Productivity"); plt.Legend(); plt.Style(ScottPlot.Style.Gray2); if (outputPath != null) plt.SaveFig(fileName); else Console.WriteLine(plt.GetHashCode()); Console.WriteLine($"Saved: {fileName}"); } [Test] public void Figure_57_StyleBlack() { string name = System.Reflection.MethodBase.GetCurrentMethod().Name.Replace("Figure_", ""); string fileName = System.IO.Path.GetFullPath($"{outputPath}/images/{name}.png"); int pointCount = 50; double[] dataXs = ScottPlot.DataGen.Consecutive(pointCount); double[] dataSin = ScottPlot.DataGen.Sin(pointCount); double[] dataCos = ScottPlot.DataGen.Cos(pointCount); var plt = new ScottPlot.Plot(width, height); plt.PlotScatter(dataXs, dataSin, label: "sin"); plt.PlotScatter(dataXs, dataCos, label: "cos"); plt.Title("Very Complicated Data"); plt.XLabel("Experiment Duration"); plt.YLabel("Productivity"); plt.Legend(); plt.Style(ScottPlot.Style.Black); if (outputPath != null) plt.SaveFig(fileName); else Console.WriteLine(plt.GetHashCode()); Console.WriteLine($"Saved: {fileName}"); } [Test] public void Figure_58_StyleDefault() { string name = System.Reflection.MethodBase.GetCurrentMethod().Name.Replace("Figure_", ""); string fileName = System.IO.Path.GetFullPath($"{outputPath}/images/{name}.png"); int pointCount = 50; double[] dataXs = ScottPlot.DataGen.Consecutive(pointCount); double[] dataSin = ScottPlot.DataGen.Sin(pointCount); double[] dataCos = ScottPlot.DataGen.Cos(pointCount); var plt = new ScottPlot.Plot(width, height); plt.PlotScatter(dataXs, dataSin, label: "sin"); plt.PlotScatter(dataXs, dataCos, label: "cos"); plt.Title("Very Complicated Data"); plt.XLabel("Experiment Duration"); plt.YLabel("Productivity"); plt.Legend(); plt.Style(ScottPlot.Style.Default); if (outputPath != null) plt.SaveFig(fileName); else Console.WriteLine(plt.GetHashCode()); Console.WriteLine($"Saved: {fileName}"); } [Test] public void Figure_59_StyleControl() { string name = System.Reflection.MethodBase.GetCurrentMethod().Name.Replace("Figure_", ""); string fileName = System.IO.Path.GetFullPath($"{outputPath}/images/{name}.png"); int pointCount = 50; double[] dataXs = ScottPlot.DataGen.Consecutive(pointCount); double[] dataSin = ScottPlot.DataGen.Sin(pointCount); double[] dataCos = ScottPlot.DataGen.Cos(pointCount); var plt = new ScottPlot.Plot(width, height); plt.PlotScatter(dataXs, dataSin, label: "sin"); plt.PlotScatter(dataXs, dataCos, label: "cos"); plt.Title("Very Complicated Data"); plt.XLabel("Experiment Duration"); plt.YLabel("Productivity"); plt.Legend(); plt.Style(ScottPlot.Style.Control); if (outputPath != null) plt.SaveFig(fileName); else Console.WriteLine(plt.GetHashCode()); Console.WriteLine($"Saved: {fileName}"); } [Test] public void Figure_60_Plotting_With_Errorbars() { string name = System.Reflection.MethodBase.GetCurrentMethod().Name.Replace("Figure_", ""); string fileName = System.IO.Path.GetFullPath($"{outputPath}/images/{name}.png"); var plt = new ScottPlot.Plot(width, height); plt.Grid(false); for (int plotNumber = 0; plotNumber < 3; plotNumber++) { // create random data to plot Random rand = new Random(plotNumber); int pointCount = 20; double[] dataX = new double[pointCount]; double[] dataY = new double[pointCount]; double[] errorY = new double[pointCount]; double[] errorX = new double[pointCount]; for (int i = 0; i < pointCount; i++) { dataX[i] = i + rand.NextDouble(); dataY[i] = rand.NextDouble() * 100 + 100 * plotNumber; errorX[i] = rand.NextDouble(); errorY[i] = rand.NextDouble() * 10; } // demonstrate different ways to plot errorbars if (plotNumber == 0) plt.PlotScatter(dataX, dataY, lineWidth: 0, errorY: errorY, errorX: errorX, label: $"X and Y errors"); else if (plotNumber == 1) plt.PlotScatter(dataX, dataY, lineWidth: 0, errorY: errorY, label: $"Y errors only"); else plt.PlotScatter(dataX, dataY, errorY: errorY, errorX: errorX, label: $"Connected Errors"); } plt.Title("Scatter Plot with Errorbars"); plt.Legend(); if (outputPath != null) plt.SaveFig(fileName); else Console.WriteLine(plt.GetHashCode()); Console.WriteLine($"Saved: {fileName}"); } [Test] public void Figure_61_Plot_Bar_Data() { string name = System.Reflection.MethodBase.GetCurrentMethod().Name.Replace("Figure_", ""); string fileName = System.IO.Path.GetFullPath($"{outputPath}/images/{name}.png"); int pointCount = 50; double[] dataXs = ScottPlot.DataGen.Consecutive(pointCount); double[] dataSin = ScottPlot.DataGen.Sin(pointCount); double[] dataCos = ScottPlot.DataGen.Cos(pointCount); // create demo data to use for errorbars double[] yErr = new double[dataSin.Length]; for (int i = 0; i < yErr.Length; i++) yErr[i] = dataSin[i] / 5 + .025; var plt = new ScottPlot.Plot(width, height); plt.Title("Bar Plot With Error Bars"); plt.PlotBar(dataXs, dataSin, barWidth: .5, errorY: yErr, errorCapSize: 2); if (outputPath != null) plt.SaveFig(fileName); else Console.WriteLine(plt.GetHashCode()); Console.WriteLine($"Saved: {fileName}"); } [Test] public void Figure_62_Plot_Bar_Data_Fancy() { string name = System.Reflection.MethodBase.GetCurrentMethod().Name.Replace("Figure_", ""); string fileName = System.IO.Path.GetFullPath($"{outputPath}/images/{name}.png"); // generate some more complex data Random rand = new Random(0); int pointCount = 10; double[] Xs = new double[pointCount]; double[] dataA = new double[pointCount]; double[] errorA = new double[pointCount]; double[] dataB = new double[pointCount]; double[] errorB = new double[pointCount]; for (int i = 0; i < pointCount; i++) { Xs[i] = i * 10; dataA[i] = rand.NextDouble() * 100; dataB[i] = rand.NextDouble() * 100; errorA[i] = rand.NextDouble() * 10; errorB[i] = rand.NextDouble() * 10; } var plt = new ScottPlot.Plot(width, height); plt.Title("Multiple Bar Plots"); plt.Grid(false); // customize barWidth and xOffset to squeeze grouped bars together plt.PlotBar(Xs, dataA, errorY: errorA, label: "data A", barWidth: 3.2, xOffset: -2); plt.PlotBar(Xs, dataB, errorY: errorB, label: "data B", barWidth: 3.2, xOffset: 2); plt.Axis(null, null, 0, null); plt.Legend(); string[] labels = { "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten" }; plt.XTicks(Xs, labels); if (outputPath != null) plt.SaveFig(fileName); else Console.WriteLine(plt.GetHashCode()); Console.WriteLine($"Saved: {fileName}"); } [Test] public void Figure_63_Step_Plot() { string name = System.Reflection.MethodBase.GetCurrentMethod().Name.Replace("Figure_", ""); string fileName = System.IO.Path.GetFullPath($"{outputPath}/images/{name}.png"); int pointCount = 50; double[] dataXs = ScottPlot.DataGen.Consecutive(pointCount); double[] dataSin = ScottPlot.DataGen.Sin(pointCount); double[] dataCos = ScottPlot.DataGen.Cos(pointCount); var plt = new ScottPlot.Plot(width, height); plt.PlotStep(dataXs, dataSin); plt.PlotStep(dataXs, dataCos); if (outputPath != null) plt.SaveFig(fileName); else Console.WriteLine(plt.GetHashCode()); Console.WriteLine($"Saved: {fileName}"); } [Test] public void Figure_64_Manual_Grid_Spacing() { string name = System.Reflection.MethodBase.GetCurrentMethod().Name.Replace("Figure_", ""); string fileName = System.IO.Path.GetFullPath($"{outputPath}/images/{name}.png"); int pointCount = 50; double[] dataXs = ScottPlot.DataGen.Consecutive(pointCount); double[] dataSin = ScottPlot.DataGen.Sin(pointCount); double[] dataCos = ScottPlot.DataGen.Cos(pointCount); var plt = new ScottPlot.Plot(width, height); plt.PlotScatter(dataXs, dataSin); plt.PlotScatter(dataXs, dataCos); plt.Grid(xSpacing: 2, ySpacing: .1); if (outputPath != null) plt.SaveFig(fileName); else Console.WriteLine(plt.GetHashCode()); Console.WriteLine($"Saved: {fileName}"); } public void Figure_65_Histogram() { string name = System.Reflection.MethodBase.GetCurrentMethod().Name.Replace("Figure_", ""); string fileName = System.IO.Path.GetFullPath($"{outputPath}/images/{name}.png"); Random rand = new Random(0); double[] values1 = ScottPlot.DataGen.RandomNormal(rand, pointCount: 1000, mean: 50, stdDev: 20); var hist1 = new ScottPlot.Histogram(values1, min: 0, max: 100); var plt = new ScottPlot.Plot(width, height); plt.Title("Histogram"); plt.YLabel("Count (#)"); plt.XLabel("Value (units)"); plt.PlotBar(hist1.bins, hist1.counts, barWidth: 1); plt.Axis(null, null, 0, null); if (outputPath != null) plt.SaveFig(fileName); else Console.WriteLine(plt.GetHashCode()); Console.WriteLine($"Saved: {fileName}"); } [Test] public void Figure_66_CPH() { string name = System.Reflection.MethodBase.GetCurrentMethod().Name.Replace("Figure_", ""); string fileName = System.IO.Path.GetFullPath($"{outputPath}/images/{name}.png"); Random rand = new Random(0); double[] values1 = ScottPlot.DataGen.RandomNormal(rand, pointCount: 1000, mean: 50, stdDev: 20); double[] values2 = ScottPlot.DataGen.RandomNormal(rand, pointCount: 1000, mean: 45, stdDev: 25); var hist1 = new ScottPlot.Histogram(values1, min: 0, max: 100); var hist2 = new ScottPlot.Histogram(values2, min: 0, max: 100); var plt = new ScottPlot.Plot(width, height); plt.Title("Cumulative Probability Histogram"); plt.YLabel("Probability (fraction)"); plt.XLabel("Value (units)"); plt.PlotStep(hist1.bins, hist1.cumulativeFrac, lineWidth: 1.5, label: "sample A"); plt.PlotStep(hist2.bins, hist2.cumulativeFrac, lineWidth: 1.5, label: "sample B"); plt.Legend(); plt.Axis(null, null, 0, 1); if (outputPath != null) plt.SaveFig(fileName); else Console.WriteLine(plt.GetHashCode()); Console.WriteLine($"Saved: {fileName}"); } [Test] public void Figure_67_Candlestick() { string name = System.Reflection.MethodBase.GetCurrentMethod().Name.Replace("Figure_", ""); string fileName = System.IO.Path.GetFullPath($"{outputPath}/images/{name}.png"); ScottPlot.OHLC[] ohlcs = ScottPlot.DataGen.RandomStockPrices(rand: null, pointCount: 35, deltaMinutes: 10); var plt = new ScottPlot.Plot(width: 800, height: 400); plt.Title("Ten Minute Candlestick Chart"); plt.YLabel("Stock Price (USD)"); plt.PlotCandlestick(ohlcs); plt.Ticks(dateTimeX: true); if (outputPath != null) plt.SaveFig(fileName); else Console.WriteLine(plt.GetHashCode()); Console.WriteLine($"Saved: {fileName}"); } [Test] public void Figure_67a_Candlestick_Days() { string name = System.Reflection.MethodBase.GetCurrentMethod().Name.Replace("Figure_", ""); string fileName = System.IO.Path.GetFullPath($"{outputPath}/images/{name}.png"); ScottPlot.OHLC[] ohlcs = ScottPlot.DataGen.RandomStockPrices(rand: null, pointCount: 30, deltaDays: 1); var plt = new ScottPlot.Plot(width: 800, height: 400); plt.Title("Daily Candlestick Chart (weekends skipped)"); plt.YLabel("Stock Price (USD)"); plt.PlotCandlestick(ohlcs); plt.Ticks(dateTimeX: true); if (outputPath != null) plt.SaveFig(fileName); else Console.WriteLine(plt.GetHashCode()); Console.WriteLine($"Saved: {fileName}"); } [Test] public void Figure_67b_Candlestick_Days_Evenly_Spaced() { string name = System.Reflection.MethodBase.GetCurrentMethod().Name.Replace("Figure_", ""); string fileName = System.IO.Path.GetFullPath($"{outputPath}/images/{name}.png"); // start with stock prices which have unevenly spaced time points (weekends are skipped) ScottPlot.OHLC[] ohlcs = ScottPlot.DataGen.RandomStockPrices(rand: null, pointCount: 30); // replace timestamps with a series of numbers starting at 0 for (int i = 0; i < ohlcs.Length; i++) ohlcs[i].time = i; // plot the candlesticks (the horizontal axis will start at 0) var plt = new ScottPlot.Plot(width: 800, height: 400); plt.Title("Daily Candlestick Chart (evenly spaced)"); plt.YLabel("Stock Price (USD)"); plt.PlotCandlestick(ohlcs); // create ticks manually double[] tickPositions = { 0, 6, 13, 20, 27 }; string[] tickLabels = { "Sep 23", "Sep 30", "Oct 7", "Oct 14", "Oct 21" }; plt.XTicks(tickPositions, tickLabels); if (outputPath != null) plt.SaveFig(fileName); else Console.WriteLine(plt.GetHashCode()); Console.WriteLine($"Saved: {fileName}"); } [Test] public void Figure_68_OHLC() { string name = System.Reflection.MethodBase.GetCurrentMethod().Name.Replace("Figure_", ""); string fileName = System.IO.Path.GetFullPath($"{outputPath}/images/{name}.png"); ScottPlot.OHLC[] ohlcs = ScottPlot.DataGen.RandomStockPrices(rand: null, pointCount: 60, deltaMinutes: 10); var plt = new ScottPlot.Plot(width, height); plt.Title("Open/High/Low/Close (OHLC) Chart"); plt.YLabel("Stock Price (USD)"); plt.PlotOHLC(ohlcs); plt.Ticks(dateTimeX: true); if (outputPath != null) plt.SaveFig(fileName); else Console.WriteLine(plt.GetHashCode()); Console.WriteLine($"Saved: {fileName}"); } [Test] public void Figure_70_Save_Scatter_Data() { string name = System.Reflection.MethodBase.GetCurrentMethod().Name.Replace("Figure_", ""); string fileName = System.IO.Path.GetFullPath($"{outputPath}/images/{name}.png"); int pointCount = 50; double[] dataXs = ScottPlot.DataGen.Consecutive(pointCount); double[] dataSin = ScottPlot.DataGen.Sin(pointCount); var plt = new ScottPlot.Plot(width, height); plt.PlotScatter(dataXs, dataSin); plt.GetPlottables()[0].SaveCSV("scatter.csv"); if (outputPath != null) plt.SaveFig(fileName); else Console.WriteLine(plt.GetHashCode()); Console.WriteLine($"Saved: {fileName}"); } [Test] public void Figure_71_Save_Signal_Data() { string name = System.Reflection.MethodBase.GetCurrentMethod().Name.Replace("Figure_", ""); string fileName = System.IO.Path.GetFullPath($"{outputPath}/images/{name}.png"); int pointCount = 50; double[] dataCos = ScottPlot.DataGen.Cos(pointCount); var plt = new ScottPlot.Plot(width, height); plt.PlotSignal(dataCos, sampleRate: 20_000); plt.GetPlottables()[0].SaveCSV("signal.csv"); if (outputPath != null) plt.SaveFig(fileName); else Console.WriteLine(plt.GetHashCode()); Console.WriteLine($"Saved: {fileName}"); } [Test] public void Figure_72_Custom_Fonts() { string name = System.Reflection.MethodBase.GetCurrentMethod().Name.Replace("Figure_", ""); string fileName = System.IO.Path.GetFullPath($"{outputPath}/images/{name}.png"); int pointCount = 50; double[] dataXs = ScottPlot.DataGen.Consecutive(pointCount); double[] dataSin = ScottPlot.DataGen.Sin(pointCount); double[] dataCos = ScottPlot.DataGen.Cos(pointCount); var plt = new ScottPlot.Plot(width, height); plt.Title("Impressive Graph", fontName: "courier new", fontSize: 24, color: Color.Purple, bold: true); plt.YLabel("vertical units", fontName: "impact", fontSize: 24, color: Color.Red, bold: true); plt.XLabel("horizontal units", fontName: "georgia", fontSize: 24, color: Color.Blue, bold: true); plt.PlotScatter(dataXs, dataSin, label: "sin"); plt.PlotScatter(dataXs, dataCos, label: "cos"); plt.PlotText("very graph", 25, .8, fontName: "comic sans ms", fontSize: 24, color: Color.Blue, bold: true); plt.PlotText("so data", 0, 0, fontName: "comic sans ms", fontSize: 42, color: Color.Magenta, bold: true); plt.PlotText("many documentation", 3, -.6, fontName: "comic sans ms", fontSize: 18, color: Color.DarkCyan, bold: true); plt.PlotText("wow.", 10, .6, fontName: "comic sans ms", fontSize: 36, color: Color.Green, bold: true); plt.PlotText("NuGet", 32, 0, fontName: "comic sans ms", fontSize: 24, color: Color.Gold, bold: true); plt.Legend(fontName: "comic sans ms", fontSize: 16, bold: true, fontColor: Color.DarkBlue); if (outputPath != null) plt.SaveFig(fileName); else Console.WriteLine(plt.GetHashCode()); Console.WriteLine($"Saved: {fileName}"); } [Test] public void Figure_73_Multiplot() { string name = System.Reflection.MethodBase.GetCurrentMethod().Name.Replace("Figure_", ""); string fileName = System.IO.Path.GetFullPath($"{outputPath}/images/{name}.png"); Random rand = new Random(09241985); var plt = new ScottPlot.MultiPlot(width: 800, height: 600, rows: 2, cols: 2); plt.subplots[0].Title("Sine"); plt.subplots[0].PlotSignal(ScottPlot.DataGen.Sin(50)); plt.subplots[1].Title("Cosine"); plt.subplots[1].PlotSignal(ScottPlot.DataGen.Cos(50)); plt.subplots[2].Title("Random Points"); plt.subplots[2].PlotSignal(ScottPlot.DataGen.Random(rand, 50)); plt.subplots[3].Title("Random Walk"); plt.subplots[3].PlotSignal(ScottPlot.DataGen.RandomWalk(rand, 50)); // apply axes and layout from one plot to another one plt.subplots[2].MatchAxis(plt.subplots[3]); plt.subplots[2].MatchLayout(plt.subplots[3]); if (outputPath != null) plt.SaveFig(fileName); else Console.WriteLine(plt.GetHashCode()); Console.WriteLine($"Saved: {fileName}"); } [Test] public void Figure_74_Set_Visibility() { string name = System.Reflection.MethodBase.GetCurrentMethod().Name.Replace("Figure_", ""); string fileName = System.IO.Path.GetFullPath($"{outputPath}/images/{name}.png"); int pointCount = 50; double[] dataXs = ScottPlot.DataGen.Consecutive(pointCount); double[] dataSin = ScottPlot.DataGen.Sin(pointCount); double[] dataCos = ScottPlot.DataGen.Cos(pointCount); var plt = new ScottPlot.Plot(width, height); var plottable1 = plt.PlotScatter(dataXs, dataSin, label: "sin"); var plottable2 = plt.PlotScatter(dataXs, dataCos, label: "cos"); plt.Legend(); // after something is plotted you can toggle its visibility plottable1.visible = true; plottable2.visible = false; if (outputPath != null) plt.SaveFig(fileName); else Console.WriteLine(plt.GetHashCode()); Console.WriteLine($"Saved: {fileName}"); } } }
46.546379
131
0.599954
[ "MIT" ]
PracplayLLC/ScottPlot
tests/Cookbook.cs
73,266
C#
using DomainFramework.Core; using System; using System.Collections.Generic; using Utilities.Validation; namespace SimpleEntityWithAutoGeneratedKey.SimpleEntityWithAutoGeneratedKeyBoundedContext { public class SaveTestEntityInputDto : IInputDataTransferObject { public int TestEntityId { get; set; } public string Text { get; set; } public TestEntity.EnumerationType1 Enumeration1 { get; set; } public TypeValueInputDto TypeValue1 { get; set; } public UrlInputDto Url { get; set; } public SelectionCriteriaInputDto Distance { get; set; } public SelectionCriteriaInputDto Traffic { get; set; } public SelectionCriteriaInputDto Time { get; set; } public virtual void Validate(ValidationResult result) { Text.ValidateRequired(result, nameof(Text)); Text.ValidateMaxLength(result, nameof(Text), 50); Enumeration1.ValidateRequired(result, nameof(Enumeration1)); TypeValue1.Validate(result); Url.Validate(result); Distance?.Validate(result); Traffic?.Validate(result); Time?.Validate(result); } } }
26.173913
89
0.666113
[ "MIT" ]
jgonte/DomainFramework
DomainFramework.Tests/SimpleEntityWithAutoGeneratedKey/SimpleEntityWithAutoGeneratedKeyBoundedContext/InputDataTransferObjects/SaveTestEntityInputDto.cs
1,204
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the glacier-2012-06-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.Glacier.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.Glacier.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for UploadMultipartPart operation /// </summary> public class UploadMultipartPartResponseUnmarshaller : JsonResponseUnmarshaller { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context) { UploadMultipartPartResponse response = new UploadMultipartPartResponse(); if (context.ResponseData.IsHeaderPresent("x-amz-sha256-tree-hash")) response.Checksum = context.ResponseData.GetHeaderValue("x-amz-sha256-tree-hash"); return response; } /// <summary> /// Unmarshaller error response to exception. /// </summary> /// <param name="context"></param> /// <param name="innerException"></param> /// <param name="statusCode"></param> /// <returns></returns> public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode) { var errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context); errorResponse.InnerException = innerException; errorResponse.StatusCode = statusCode; var responseBodyBytes = context.GetResponseBodyBytes(); using (var streamCopy = new MemoryStream(responseBodyBytes)) using (var contextCopy = new JsonUnmarshallerContext(streamCopy, false, null)) { if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidParameterValueException")) { return InvalidParameterValueExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("MissingParameterValueException")) { return MissingParameterValueExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("RequestTimeoutException")) { return RequestTimeoutExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("ResourceNotFoundException")) { return ResourceNotFoundExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("ServiceUnavailableException")) { return ServiceUnavailableExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } } return new AmazonGlacierException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode); } private static UploadMultipartPartResponseUnmarshaller _instance = new UploadMultipartPartResponseUnmarshaller(); internal static UploadMultipartPartResponseUnmarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static UploadMultipartPartResponseUnmarshaller Instance { get { return _instance; } } } }
41.418803
190
0.661164
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/Glacier/Generated/Model/Internal/MarshallTransformations/UploadMultipartPartResponseUnmarshaller.cs
4,846
C#
using System; using System.Threading.Tasks; using Melville.IOC.IocContainers; using Melville.IOC.TypeResolutionPolicy; using Xunit; namespace Melville.IOC.Test.TypeResolutionPolicy { public class FunctionFactoryBindingTest { private readonly IocContainer sut = new IocContainer(); public class Simple { } [Fact] public void NoArguments() { var f = sut.Get<Func<Simple>>(); Assert.NotNull(f()); } [Fact] public void OneArgument() { var f = sut.Get<Func<int, Simple>>(); Assert.NotNull(f(1)); } [Fact] public void ManyArguments() { var f = sut.Get<Func<int, string, int, int, int, int, int, int, int, int, int, int, int, int, int, int, Simple>>(); Assert.NotNull(f(1, "2", 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 15, 16)); } public class HasThreeArguments { public int Int { get; } public int Int2 { get; } public Simple Simple { get; } public HasThreeArguments(int i, int int2, Simple simple) { Int = i; Int2 = int2; Simple = simple; } } [Fact] public void InitializeWithParameters() { var fact = sut.Get<Func<int, int, HasThreeArguments>>(); var item = fact(1, 2); Assert.Equal(1, item.Int); Assert.Equal(2, item.Int2); Assert.NotNull(item.Simple); } [Fact] public void BindWithParameters() { sut.Bind<HasThreeArguments>().To<HasThreeArguments>().WithParameters(1, 2); var item = sut.Get<HasThreeArguments>(); Assert.Equal(1, item.Int); Assert.Equal(2, item.Int2); Assert.NotNull(item.Simple); var item2 = sut.Get<HasThreeArguments>(); Assert.Equal(1, item2.Int); Assert.Equal(2, item2.Int2); Assert.NotNull(item2.Simple); } [Fact] public void SpecifyParametersToGet() { var item = sut.Get<HasThreeArguments>(1,2); Assert.Equal(1, item.Int); Assert.Equal(2, item.Int2); Assert.NotNull(item.Simple); } [Fact] public void CanGetWithArguments() { Assert.False(sut.CanGet<HasThreeArguments>()); Assert.True(sut.CanGet<HasThreeArguments>(1,2)); } public class AsyncCreatable { public AsyncCreatable(int a) { A = a; } public string B { get; set; } public int A { get; } private Task Create(string b) { B = b; return Task.CompletedTask; } } [Fact] public async Task CreateAsyncFactory() { var fact = sut.Get<Func<int, Func<string, Task<AsyncCreatable>>>>(); var ret = await fact(1)("Hello World"); Assert.Equal(1, ret.A); Assert.Equal("Hello World", ret.B); } [Fact] public async Task CreayAsyncUniqueObjects() { var fact = sut.Get<Func<int, Func<string, Task<AsyncCreatable>>>>(); var ret = await fact(1)("Hello World"); var ret2 = await fact(1)("Hello World"); Assert.NotEqual(ret,ret2); } [Fact] public async Task CreateAndClearAsyncCachedObjects() { sut.BindAsyncFactory<AsyncCreatable>().AsSingleton(); var (clear,fact) = sut.Get<(Action,Func<int, Func<string, Task<AsyncCreatable>>>)>(); var ret = await fact(1)("Hello World"); var ret2 = await fact(10)("aaa"); Assert.Equal(1, ret2.A); Assert.Equal("Hello World", ret2.B); Assert.Equal(ret,ret2); clear(); var ret3 = await fact(200)("new"); Assert.NotEqual(ret, ret3); Assert.Equal(200, ret3.A); Assert.Equal("new", ret3.B); } public class ClassWithAsyncFactoryMethod { public int Id { get; set;} public static Task<ClassWithAsyncFactoryMethod> Create(int id) { return Task.FromResult(new ClassWithAsyncFactoryMethod {Id = id}); } } [Fact] public async Task CreateFrpmAsyncStaticFactory() { var output = await sut.Get <Func<int, Task<ClassWithAsyncFactoryMethod>>>()(121); Assert.Equal(121, output.Id); } } }
29.930818
105
0.50851
[ "MIT" ]
DrJohnMelville/Melville
src/Melville.IOC.Test/TypeResolutionPolicy/FunctionFactoryBindingTest.cs
4,761
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ // // This source code was auto-generated by Microsoft.VSDesigner, Version 4.0.30319.42000. // #pragma warning disable 1591 namespace Sultanlar.UI.getcustomersC { using System; using System.Web.Services; using System.Diagnostics; using System.Web.Services.Protocols; using System.Xml.Serialization; using System.ComponentModel; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.8.3761.0")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Web.Services.WebServiceBindingAttribute(Name="ZwebGetCustomersBinding", Namespace="urn:sap-com:document:sap:soap:functions:mc-style")] [System.Xml.Serialization.XmlIncludeAttribute(typeof(Zwebt002[]))] public partial class ZwebGetCustomersService : System.Web.Services.Protocols.SoapHttpClientProtocol { private System.Threading.SendOrPostCallback ZwebGetCustomersOperationCompleted; private bool useDefaultCredentialsSetExplicitly; /// <remarks/> public ZwebGetCustomersService() { this.Url = global::Sultanlar.UI.Properties.Settings.Default.Sultanlar_getcustomersC_ZwebGetCustomersService; if ((this.IsLocalFileSystemWebService(this.Url) == true)) { this.UseDefaultCredentials = true; this.useDefaultCredentialsSetExplicitly = false; } else { this.useDefaultCredentialsSetExplicitly = true; } } public new string Url { get { return base.Url; } set { if ((((this.IsLocalFileSystemWebService(base.Url) == true) && (this.useDefaultCredentialsSetExplicitly == false)) && (this.IsLocalFileSystemWebService(value) == false))) { base.UseDefaultCredentials = false; } base.Url = value; } } public new bool UseDefaultCredentials { get { return base.UseDefaultCredentials; } set { base.UseDefaultCredentials = value; this.useDefaultCredentialsSetExplicitly = true; } } /// <remarks/> public event ZwebGetCustomersCompletedEventHandler ZwebGetCustomersCompleted; /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://www.sap.com/ZwebGetCustomers", RequestNamespace="urn:sap-com:document:sap:soap:functions:mc-style", ResponseElementName="ZwebGetCustomersResult", ResponseNamespace="urn:sap-com:document:sap:soap:functions:mc-style", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] [return: System.Xml.Serialization.XmlArrayAttribute("EtCustomers", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)] [return: System.Xml.Serialization.XmlArrayItemAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=false)] public Zwebt002[] ZwebGetCustomers() { object[] results = this.Invoke("ZwebGetCustomers", new object[0]); return ((Zwebt002[])(results[0])); } /// <remarks/> public void ZwebGetCustomersAsync() { this.ZwebGetCustomersAsync(null); } /// <remarks/> public void ZwebGetCustomersAsync(object userState) { if ((this.ZwebGetCustomersOperationCompleted == null)) { this.ZwebGetCustomersOperationCompleted = new System.Threading.SendOrPostCallback(this.OnZwebGetCustomersOperationCompleted); } this.InvokeAsync("ZwebGetCustomers", new object[0], this.ZwebGetCustomersOperationCompleted, userState); } private void OnZwebGetCustomersOperationCompleted(object arg) { if ((this.ZwebGetCustomersCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.ZwebGetCustomersCompleted(this, new ZwebGetCustomersCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> public new void CancelAsync(object userState) { base.CancelAsync(userState); } private bool IsLocalFileSystemWebService(string url) { if (((url == null) || (url == string.Empty))) { return false; } System.Uri wsUri = new System.Uri(url); if (((wsUri.Port >= 1024) && (string.Compare(wsUri.Host, "localHost", System.StringComparison.OrdinalIgnoreCase) == 0))) { return true; } return false; } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.8.3761.0")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(Namespace="urn:sap-com:document:sap:soap:functions:mc-style")] public partial class Zwebt002 { private string mandtField; private string parvwField; private string pernrField; private string kunweField; private string kunagField; private string kdgrpField; private string kdgtxField; private string regioField; private string bezeiField; private string namagField; private string namweField; private string adresField; private string stcd1Field; private string stcd2Field; private string telnoField; private string faxnoField; private string mobnoField; private string emailField; private decimal klimkField; private bool klimkFieldSpecified; private string pernoField; private string aedatField; private string aezetField; private string aufsdField; private string name3Field; private string defltCommField; private string commTextField; private string city1Field; private string postCode1Field; private string altknField; private string bzirkField; private string bztxtField; /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)] public string Mandt { get { return this.mandtField; } set { this.mandtField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)] public string Parvw { get { return this.parvwField; } set { this.parvwField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)] public string Pernr { get { return this.pernrField; } set { this.pernrField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)] public string Kunwe { get { return this.kunweField; } set { this.kunweField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)] public string Kunag { get { return this.kunagField; } set { this.kunagField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)] public string Kdgrp { get { return this.kdgrpField; } set { this.kdgrpField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)] public string Kdgtx { get { return this.kdgtxField; } set { this.kdgtxField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)] public string Regio { get { return this.regioField; } set { this.regioField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)] public string Bezei { get { return this.bezeiField; } set { this.bezeiField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)] public string Namag { get { return this.namagField; } set { this.namagField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)] public string Namwe { get { return this.namweField; } set { this.namweField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)] public string Adres { get { return this.adresField; } set { this.adresField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)] public string Stcd1 { get { return this.stcd1Field; } set { this.stcd1Field = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)] public string Stcd2 { get { return this.stcd2Field; } set { this.stcd2Field = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)] public string Telno { get { return this.telnoField; } set { this.telnoField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)] public string Faxno { get { return this.faxnoField; } set { this.faxnoField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)] public string Mobno { get { return this.mobnoField; } set { this.mobnoField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)] public string Email { get { return this.emailField; } set { this.emailField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)] public decimal Klimk { get { return this.klimkField; } set { this.klimkField = value; } } /// <remarks/> [System.Xml.Serialization.XmlIgnoreAttribute()] public bool KlimkSpecified { get { return this.klimkFieldSpecified; } set { this.klimkFieldSpecified = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)] public string Perno { get { return this.pernoField; } set { this.pernoField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)] public string Aedat { get { return this.aedatField; } set { this.aedatField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)] public string Aezet { get { return this.aezetField; } set { this.aezetField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)] public string Aufsd { get { return this.aufsdField; } set { this.aufsdField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)] public string Name3 { get { return this.name3Field; } set { this.name3Field = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)] public string DefltComm { get { return this.defltCommField; } set { this.defltCommField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)] public string CommText { get { return this.commTextField; } set { this.commTextField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)] public string City1 { get { return this.city1Field; } set { this.city1Field = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)] public string PostCode1 { get { return this.postCode1Field; } set { this.postCode1Field = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)] public string Altkn { get { return this.altknField; } set { this.altknField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)] public string Bzirk { get { return this.bzirkField; } set { this.bzirkField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)] public string Bztxt { get { return this.bztxtField; } set { this.bztxtField = value; } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.8.3761.0")] public delegate void ZwebGetCustomersCompletedEventHandler(object sender, ZwebGetCustomersCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.8.3761.0")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class ZwebGetCustomersCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal ZwebGetCustomersCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public Zwebt002[] Result { get { this.RaiseExceptionIfNecessary(); return ((Zwebt002[])(this.results[0])); } } } } #pragma warning restore 1591
32.592014
424
0.53529
[ "MIT" ]
dogukanalan/Sultanlar
Sultanlar/Sultanlar.UI/Web References/getcustomersC/Reference.cs
18,775
C#
/* Yet Another Forum.NET * Copyright (C) 2003-2005 Bjørnar Henden * Copyright (C) 2006-2013 Jaben Cargman * Copyright (C) 2014-2015 Ingo Herbote * http://www.yetanotherforum.net/ * * 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 YAF.Providers.Utils; namespace YAF.Providers.Membership { #region Using using System; using System.Data; using System.Data.SqlClient; using System.Web.Security; using YAF.Classes.Pattern; using YAF.Classes.Data; using YAF.Types; using YAF.Types.Extensions; using YAF.Types.Interfaces.Data; #endregion /// <summary> /// The db. /// </summary> public class DB : BaseProviderDb { #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref = "DB" /> class. /// </summary> public DB() : base(YafMembershipProvider.ConnStrAppKeyName) { } #endregion #region Properties /// <summary> /// Gets Current. /// </summary> public static DB Current { get { return PageSingleton<DB>.Instance; } } #endregion #region Public Methods /// <summary> /// The change password. /// </summary> /// <param name="appName"> /// The app name. /// </param> /// <param name="username"> /// The username. /// </param> /// <param name="newPassword"> /// The new password. /// </param> /// <param name="newSalt"> /// The new salt. /// </param> /// <param name="passwordFormat"> /// The password format. /// </param> /// <param name="newPasswordAnswer"> /// The new password answer. /// </param> public void ChangePassword([NotNull] string appName, [NotNull] string username, [NotNull] string newPassword, [NotNull] string newSalt, int passwordFormat, [NotNull] string newPasswordAnswer) { using (var cmd = new SqlCommand(DbHelpers.GetObjectName("prov_changepassword"))) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@ApplicationName", appName); // Nonstandard args cmd.Parameters.AddWithValue("@Username", username); cmd.Parameters.AddWithValue("@Password", newPassword); cmd.Parameters.AddWithValue("@PasswordSalt", newSalt); cmd.Parameters.AddWithValue("@PasswordFormat", passwordFormat); cmd.Parameters.AddWithValue("@PasswordAnswer", newPasswordAnswer); this.DbAccess.ExecuteNonQuery(cmd); } } /// <summary> /// The change password question and answer. /// </summary> /// <param name="appName"> /// The app name. /// </param> /// <param name="username"> /// The username. /// </param> /// <param name="passwordQuestion"> /// The password question. /// </param> /// <param name="passwordAnswer"> /// The password answer. /// </param> public void ChangePasswordQuestionAndAnswer([NotNull] string appName, [NotNull] string username, [NotNull] string passwordQuestion, [NotNull] string passwordAnswer) { using (var cmd = new SqlCommand(DbHelpers.GetObjectName("prov_changepasswordquestionandanswer"))) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@ApplicationName", appName); // Nonstandard args cmd.Parameters.AddWithValue("@Username", username); cmd.Parameters.AddWithValue("@PasswordQuestion", passwordQuestion); cmd.Parameters.AddWithValue("@PasswordAnswer", passwordAnswer); this.DbAccess.ExecuteNonQuery(cmd); } } /// <summary> /// The create user. /// </summary> /// <param name="appName"> /// The app name. /// </param> /// <param name="username"> /// The username. /// </param> /// <param name="password"> /// The password. /// </param> /// <param name="passwordSalt"> /// The password salt. /// </param> /// <param name="passwordFormat"> /// The password format. /// </param> /// <param name="email"> /// The email. /// </param> /// <param name="passwordQuestion"> /// The password question. /// </param> /// <param name="passwordAnswer"> /// The password answer. /// </param> /// <param name="isApproved"> /// The is approved. /// </param> /// <param name="providerUserKey"> /// The provider user key. /// </param> public void CreateUser([NotNull] string appName, [NotNull] string username, [NotNull] string password, [NotNull] string passwordSalt, int passwordFormat, [NotNull] string email, [NotNull] string passwordQuestion, [NotNull] string passwordAnswer, bool isApproved, [NotNull] object providerUserKey) { using (var cmd = new SqlCommand(DbHelpers.GetObjectName("prov_createuser"))) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@ApplicationName", appName); // Input Parameters cmd.Parameters.AddWithValue("Username", username); cmd.Parameters.AddWithValue("Password", password); cmd.Parameters.AddWithValue("PasswordSalt", passwordSalt); cmd.Parameters.AddWithValue("PasswordFormat", passwordFormat); cmd.Parameters.AddWithValue("Email", email); cmd.Parameters.AddWithValue("PasswordQuestion", passwordQuestion); cmd.Parameters.AddWithValue("PasswordAnswer", passwordAnswer); cmd.Parameters.AddWithValue("IsApproved", isApproved); cmd.Parameters.AddWithValue("@UTCTIMESTAMP", DateTime.UtcNow); // Input Output Parameters var paramUserKey = new SqlParameter("UserKey", SqlDbType.UniqueIdentifier); paramUserKey.Direction = ParameterDirection.InputOutput; paramUserKey.Value = providerUserKey; cmd.Parameters.Add(paramUserKey); // Execute this.DbAccess.ExecuteNonQuery(cmd); // Retrieve Output Parameters providerUserKey = paramUserKey.Value; } } /// <summary> /// The delete user. /// </summary> /// <param name="appName"> /// The app name. /// </param> /// <param name="username"> /// The username. /// </param> /// <param name="deleteAllRelatedData"> /// The delete all related data. /// </param> public void DeleteUser([NotNull] string appName, [NotNull] string username, bool deleteAllRelatedData) { using (var cmd = new SqlCommand(DbHelpers.GetObjectName("prov_deleteuser"))) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@ApplicationName", appName); // Nonstandard args cmd.Parameters.AddWithValue("@Username", username); cmd.Parameters.AddWithValue("@DeleteAllRelated", deleteAllRelatedData); this.DbAccess.ExecuteNonQuery(cmd); } } /// <summary> /// The find users by email. /// </summary> /// <param name="appName"> /// The app name. /// </param> /// <param name="emailToMatch"> /// The email to match. /// </param> /// <param name="pageIndex"> /// The page index. /// </param> /// <param name="pageSize"> /// The page size. /// </param> /// <returns> /// </returns> public DataTable FindUsersByEmail([NotNull] string appName, [NotNull] string emailToMatch, int pageIndex, int pageSize) { using (var cmd = new SqlCommand(DbHelpers.GetObjectName("prov_findusersbyemail"))) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@ApplicationName", appName); // Nonstandard args cmd.Parameters.AddWithValue("@EmailAddress", emailToMatch); cmd.Parameters.AddWithValue("@PageIndex", pageIndex); cmd.Parameters.AddWithValue("@PageSize", pageSize); return this.DbAccess.GetData(cmd); } } /// <summary> /// The find users by name. /// </summary> /// <param name="appName"> /// The app name. /// </param> /// <param name="usernameToMatch"> /// The username to match. /// </param> /// <param name="pageIndex"> /// The page index. /// </param> /// <param name="pageSize"> /// The page size. /// </param> /// <returns> /// </returns> public DataTable FindUsersByName([NotNull] string appName, [NotNull] string usernameToMatch, int pageIndex, int pageSize) { using (var cmd = new SqlCommand(DbHelpers.GetObjectName("prov_findusersbyname"))) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@ApplicationName", appName); // Nonstandard args cmd.Parameters.AddWithValue("@Username", usernameToMatch); cmd.Parameters.AddWithValue("@PageIndex", pageIndex); cmd.Parameters.AddWithValue("@PageSize", pageSize); return this.DbAccess.GetData(cmd); } } /// <summary> /// The get all users. /// </summary> /// <param name="appName"> /// The app name. /// </param> /// <param name="pageIndex"> /// The page index. /// </param> /// <param name="pageSize"> /// The page size. /// </param> /// <returns> /// </returns> public DataTable GetAllUsers([NotNull] string appName, int pageIndex, int pageSize) { using (var cmd = new SqlCommand(DbHelpers.GetObjectName("prov_getallusers"))) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@ApplicationName", appName); // Nonstandard args cmd.Parameters.AddWithValue("@PageIndex", pageIndex); cmd.Parameters.AddWithValue("@PageSize", pageSize); return this.DbAccess.GetData(cmd); } } /// <summary> /// The get number of users online. /// </summary> /// <param name="appName"> /// The app name. /// </param> /// <param name="timeWindow"> /// The time window. /// </param> /// <returns> /// The get number of users online. /// </returns> public int GetNumberOfUsersOnline([NotNull] string appName, int timeWindow) { using (var cmd = new SqlCommand(DbHelpers.GetObjectName("prov_getnumberofusersonline"))) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@ApplicationName", appName); // Nonstandard args cmd.Parameters.AddWithValue("@TimeWindow", timeWindow); cmd.Parameters.AddWithValue("@CurrentTimeUtc", DateTime.UtcNow); var p = new SqlParameter("ReturnValue", SqlDbType.Int); p.Direction = ParameterDirection.ReturnValue; cmd.Parameters.Add(p); this.DbAccess.ExecuteNonQuery(cmd); return Convert.ToInt32(cmd.Parameters["ReturnValue"].Value); } } /// <summary> /// The get user. /// </summary> /// <param name="appName"> /// The app name. /// </param> /// <param name="providerUserKey"> /// The provider user key. /// </param> /// <param name="userName"> /// The user name. /// </param> /// <param name="userIsOnline"> /// The user is online. /// </param> /// <returns> /// </returns> public DataRow GetUser([NotNull] string appName, [NotNull] object providerUserKey, [NotNull] string userName, bool userIsOnline) { using (var cmd = new SqlCommand(DbHelpers.GetObjectName("prov_getuser"))) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@ApplicationName", appName); // Nonstandard args cmd.Parameters.AddWithValue("@UserName", userName); cmd.Parameters.AddWithValue("@UserKey", providerUserKey); cmd.Parameters.AddWithValue("@UserIsOnline", userIsOnline); cmd.Parameters.AddWithValue("@UTCTIMESTAMP", DateTime.UtcNow); using (DataTable dt = this.DbAccess.GetData(cmd)) { return dt.HasRows() ? dt.Rows[0] : null; } } } /// <summary> /// The get user name by email. /// </summary> /// <param name="appName"> /// The app name. /// </param> /// <param name="email"> /// The email. /// </param> /// <returns> /// </returns> public DataTable GetUserNameByEmail([NotNull] string appName, [NotNull] string email) { using (var cmd = new SqlCommand(DbHelpers.GetObjectName("prov_getusernamebyemail"))) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@ApplicationName", appName); // Nonstandard args cmd.Parameters.AddWithValue("@Email", email); return this.DbAccess.GetData(cmd); } } /// <summary> /// The get user password info. /// </summary> /// <param name="appName"> /// The app name. /// </param> /// <param name="username"> /// The username. /// </param> /// <param name="updateUser"> /// The update user. /// </param> /// <returns> /// </returns> public DataTable GetUserPasswordInfo([NotNull] string appName, [NotNull] string username, bool updateUser) { using (var cmd = new SqlCommand(DbHelpers.GetObjectName("prov_getuser"))) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@ApplicationName", appName); // Nonstandard args cmd.Parameters.AddWithValue("@Username", username); cmd.Parameters.AddWithValue("@UserIsOnline", updateUser); cmd.Parameters.AddWithValue("@UTCTIMESTAMP", DateTime.UtcNow); return this.DbAccess.GetData(cmd); } } /// <summary> /// The reset password. /// </summary> /// <param name="appName"> /// The app name. /// </param> /// <param name="userName"> /// The user name. /// </param> /// <param name="password"> /// The password. /// </param> /// <param name="passwordSalt"> /// The password salt. /// </param> /// <param name="passwordFormat"> /// The password format. /// </param> /// <param name="maxInvalidPasswordAttempts"> /// The max invalid password attempts. /// </param> /// <param name="passwordAttemptWindow"> /// The password attempt window. /// </param> public void ResetPassword([NotNull] string appName, [NotNull] string userName, [NotNull] string password, [NotNull] string passwordSalt, int passwordFormat, int maxInvalidPasswordAttempts, int passwordAttemptWindow) { using (var cmd = new SqlCommand(DbHelpers.GetObjectName("prov_resetpassword"))) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@ApplicationName", appName); // Nonstandard args cmd.Parameters.AddWithValue("@UserName", userName); cmd.Parameters.AddWithValue("@Password", password); cmd.Parameters.AddWithValue("@PasswordSalt", passwordSalt); cmd.Parameters.AddWithValue("@PasswordFormat", passwordFormat); cmd.Parameters.AddWithValue("@MaxInvalidAttempts", maxInvalidPasswordAttempts); cmd.Parameters.AddWithValue("@PasswordAttemptWindow", passwordAttemptWindow); cmd.Parameters.AddWithValue("@CurrentTimeUtc", DateTime.UtcNow); this.DbAccess.ExecuteNonQuery(cmd); } } /// <summary> /// The unlock user. /// </summary> /// <param name="appName"> /// The app name. /// </param> /// <param name="userName"> /// The user name. /// </param> public void UnlockUser([NotNull] string appName, [NotNull] string userName) { using (var cmd = new SqlCommand(DbHelpers.GetObjectName("prov_unlockuser"))) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@ApplicationName", appName); // Nonstandard args cmd.Parameters.AddWithValue("@UserName", userName); this.DbAccess.ExecuteNonQuery(cmd); } } /// <summary> /// The update user. /// </summary> /// <param name="appName"> /// The app name. /// </param> /// <param name="user"> /// The user. /// </param> /// <param name="requiresUniqueEmail"> /// The requires unique email. /// </param> /// <returns> /// The update user. /// </returns> public int UpdateUser([NotNull] object appName, [NotNull] MembershipUser user, bool requiresUniqueEmail) { using (var cmd = new SqlCommand(DbHelpers.GetObjectName("prov_updateuser"))) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("ApplicationName", appName); // Nonstandard args cmd.Parameters.AddWithValue("UserKey", user.ProviderUserKey); cmd.Parameters.AddWithValue("UserName", user.UserName); cmd.Parameters.AddWithValue("Email", user.Email); cmd.Parameters.AddWithValue("Comment", user.Comment); cmd.Parameters.AddWithValue("IsApproved", user.IsApproved); cmd.Parameters.AddWithValue("LastLogin", user.LastLoginDate); cmd.Parameters.AddWithValue("LastActivity", user.LastActivityDate.ToUniversalTime()); cmd.Parameters.AddWithValue("UniqueEmail", requiresUniqueEmail); // Add Return Value var p = new SqlParameter("ReturnValue", SqlDbType.Int); p.Direction = ParameterDirection.ReturnValue; cmd.Parameters.Add(p); this.DbAccess.ExecuteNonQuery(cmd); // Execute Non SQL Query return Convert.ToInt32(p.Value); // Return } } /// <summary> /// The upgrade membership. /// </summary> /// <param name="previousVersion"> /// The previous version. /// </param> /// <param name="newVersion"> /// The new version. /// </param> public void UpgradeMembership(int previousVersion, int newVersion) { using (var cmd = new SqlCommand(DbHelpers.GetObjectName("prov_upgrade"))) { cmd.CommandType = CommandType.StoredProcedure; // Nonstandard args cmd.Parameters.AddWithValue("@PreviousVersion", previousVersion); cmd.Parameters.AddWithValue("@NewVersion", newVersion); cmd.Parameters.AddWithValue("@UTCTIMESTAMP", DateTime.UtcNow); this.DbAccess.ExecuteNonQuery(cmd); } } #endregion } }
37.962775
118
0.532983
[ "Apache-2.0" ]
TristanTong/bbsWirelessTag
yafsrc/YAF.Providers/Membership/DB.cs
21,847
C#
using System.Collections; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UI; namespace Tenlastic { public class DefaultSelectable : MonoBehaviour { public Selectable selectable; private void OnEnable() { StartCoroutine(Select()); } private IEnumerator Select() { yield return new WaitForEndOfFrame(); EventSystem.current.SetSelectedGameObject(selectable.gameObject); } } }
22.045455
77
0.663918
[ "MIT" ]
tenlastic/open-platform
projects/unity/Tenlastic SDK/Assets/Tenlastic/Scripts/UI/DefaultSelectable.cs
487
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.Aiven.Inputs { public sealed class ServiceGrafanaUserConfigAuthGitlabArgs : Pulumi.ResourceArgs { [Input("allowSignUp")] public Input<string>? AllowSignUp { get; set; } [Input("allowedGroups")] private InputList<string>? _allowedGroups; public InputList<string> AllowedGroups { get => _allowedGroups ?? (_allowedGroups = new InputList<string>()); set => _allowedGroups = value; } [Input("apiUrl")] public Input<string>? ApiUrl { get; set; } [Input("authUrl")] public Input<string>? AuthUrl { get; set; } [Input("clientId")] public Input<string>? ClientId { get; set; } [Input("clientSecret")] public Input<string>? ClientSecret { get; set; } [Input("tokenUrl")] public Input<string>? TokenUrl { get; set; } public ServiceGrafanaUserConfigAuthGitlabArgs() { } } }
28.23913
88
0.624326
[ "ECL-2.0", "Apache-2.0" ]
pulumi/pulumi-aiven
sdk/dotnet/Inputs/ServiceGrafanaUserConfigAuthGitlabArgs.cs
1,299
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Data.DataView; using Microsoft.ML; using Microsoft.ML.CommandLine; using Microsoft.ML.Data; using Microsoft.ML.EntryPoints; using Microsoft.ML.Runtime; using Microsoft.ML.Transforms; [assembly: LoadableClass(typeof(void), typeof(TrainTestSplit), null, typeof(SignatureEntryPointModule), "TrainTestSplit")] namespace Microsoft.ML.EntryPoints { internal static class TrainTestSplit { public sealed class Input { [Argument(ArgumentType.Required, HelpText = "Input dataset", SortOrder = 1)] public IDataView Data; [Argument(ArgumentType.AtMostOnce, HelpText = "Fraction of training data", SortOrder = 2)] public float Fraction = 0.8f; [Argument(ArgumentType.AtMostOnce, ShortName = "strat", HelpText = "Stratification column", SortOrder = 3)] public string StratificationColumn = null; } public sealed class Output { [TlcModule.Output(Desc = "Training data", SortOrder = 1)] public IDataView TrainData; [TlcModule.Output(Desc = "Testing data", SortOrder = 2)] public IDataView TestData; } public const string ModuleName = "TrainTestSplit"; public const string UserName = "Dataset Train-Test Split"; [TlcModule.EntryPoint(Name = "Transforms.TrainTestDatasetSplitter", Desc = "Split the dataset into train and test sets", UserName = UserName)] public static Output Split(IHostEnvironment env, Input input) { Contracts.CheckValue(env, nameof(env)); var host = env.Register(ModuleName); host.CheckValue(input, nameof(input)); host.Check(0 < input.Fraction && input.Fraction < 1, "The fraction must be in the interval (0,1)."); EntryPointUtils.CheckInputArgs(host, input); var data = input.Data; var stratCol = SplitUtils.CreateStratificationColumn(host, ref data, input.StratificationColumn); IDataView trainData = new RangeFilter(host, new RangeFilter.Options { Column = stratCol, Min = 0, Max = input.Fraction, Complement = false }, data); trainData = ColumnSelectingTransformer.CreateDrop(host, trainData, stratCol); IDataView testData = new RangeFilter(host, new RangeFilter.Options { Column = stratCol, Min = 0, Max = input.Fraction, Complement = true }, data); testData = ColumnSelectingTransformer.CreateDrop(host, testData, stratCol); return new Output() { TrainData = trainData, TestData = testData }; } } internal static class SplitUtils { public static string CreateStratificationColumn(IHost host, ref IDataView data, string stratificationColumn = null) { host.CheckValue(data, nameof(data)); host.CheckValueOrNull(stratificationColumn); // Pick a unique name for the stratificationColumn. const string stratColName = "StratificationKey"; string stratCol = stratColName; int col; int j = 0; while (data.Schema.TryGetColumnIndex(stratCol, out col)) stratCol = string.Format("{0}_{1:000}", stratColName, j++); // Construct the stratification column. If user-provided stratification column exists, use HashJoin // of it to construct the strat column, otherwise generate a random number and use it. if (stratificationColumn == null) { data = new GenerateNumberTransform(host, new GenerateNumberTransform.Options { Columns = new[] { new GenerateNumberTransform.Column { Name = stratCol } } }, data); } else { data = new HashJoiningTransform(host, new HashJoiningTransform.Arguments { Columns = new[] { new HashJoiningTransform.Column { Name = stratCol, Source = stratificationColumn } }, Join = true, NumberOfBits = 30 }, data); } return stratCol; } } }
42.028037
150
0.616411
[ "MIT" ]
taleebanwar/machinelearning
src/Microsoft.ML.EntryPoints/TrainTestSplit.cs
4,497
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Azure; using Azure.Core; using Azure.Core.Pipeline; using Azure.Graph.Rbac.Models; namespace Azure.Graph.Rbac { internal partial class SignedInUserRestOperations { private string tenantID; private Uri endpoint; private string apiVersion; private ClientDiagnostics _clientDiagnostics; private HttpPipeline _pipeline; /// <summary> Initializes a new instance of SignedInUserRestOperations. </summary> /// <param name="clientDiagnostics"> The handler for diagnostic messaging in the client. </param> /// <param name="pipeline"> The HTTP pipeline for sending and receiving REST requests and responses. </param> /// <param name="tenantID"> The tenant ID. </param> /// <param name="endpoint"> server parameter. </param> /// <param name="apiVersion"> Api Version. </param> /// <exception cref="ArgumentNullException"> <paramref name="tenantID"/> or <paramref name="apiVersion"/> is null. </exception> public SignedInUserRestOperations(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, string tenantID, Uri endpoint = null, string apiVersion = "1.6") { if (tenantID == null) { throw new ArgumentNullException(nameof(tenantID)); } endpoint ??= new Uri("https://graph.windows.net"); if (apiVersion == null) { throw new ArgumentNullException(nameof(apiVersion)); } this.tenantID = tenantID; this.endpoint = endpoint; this.apiVersion = apiVersion; _clientDiagnostics = clientDiagnostics; _pipeline = pipeline; } internal HttpMessage CreateGetRequest() { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); uri.Reset(endpoint); uri.AppendPath("/", false); uri.AppendPath(tenantID, true); uri.AppendPath("/me", false); uri.AppendQuery("api-version", apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json, text/json"); return message; } /// <summary> Gets the details for the currently logged-in user. </summary> /// <param name="cancellationToken"> The cancellation token to use. </param> public async Task<Response<User>> GetAsync(CancellationToken cancellationToken = default) { using var message = CreateGetRequest(); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { User value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = User.DeserializeUser(document.RootElement); return Response.FromValue(value, message.Response); } default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Gets the details for the currently logged-in user. </summary> /// <param name="cancellationToken"> The cancellation token to use. </param> public Response<User> Get(CancellationToken cancellationToken = default) { using var message = CreateGetRequest(); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { User value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = User.DeserializeUser(document.RootElement); return Response.FromValue(value, message.Response); } default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreateListOwnedObjectsRequest() { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); uri.Reset(endpoint); uri.AppendPath("/", false); uri.AppendPath(tenantID, true); uri.AppendPath("/me/ownedObjects", false); uri.AppendQuery("api-version", apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json, text/json"); return message; } /// <summary> Get the list of directory objects that are owned by the user. </summary> /// <param name="cancellationToken"> The cancellation token to use. </param> public async Task<Response<DirectoryObjectListResult>> ListOwnedObjectsAsync(CancellationToken cancellationToken = default) { using var message = CreateListOwnedObjectsRequest(); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { DirectoryObjectListResult value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = DirectoryObjectListResult.DeserializeDirectoryObjectListResult(document.RootElement); return Response.FromValue(value, message.Response); } default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Get the list of directory objects that are owned by the user. </summary> /// <param name="cancellationToken"> The cancellation token to use. </param> public Response<DirectoryObjectListResult> ListOwnedObjects(CancellationToken cancellationToken = default) { using var message = CreateListOwnedObjectsRequest(); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { DirectoryObjectListResult value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = DirectoryObjectListResult.DeserializeDirectoryObjectListResult(document.RootElement); return Response.FromValue(value, message.Response); } default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreateListOwnedObjectsNextRequest(string nextLink) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); uri.Reset(endpoint); uri.AppendPath("/", false); uri.AppendPath(tenantID, true); uri.AppendPath("/", false); uri.AppendRawNextLink(nextLink, false); uri.AppendQuery("api-version", apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json, text/json"); return message; } /// <summary> Get the list of directory objects that are owned by the user. </summary> /// <param name="nextLink"> Next link for the list operation. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="nextLink"/> is null. </exception> public async Task<Response<DirectoryObjectListResult>> ListOwnedObjectsNextAsync(string nextLink, CancellationToken cancellationToken = default) { if (nextLink == null) { throw new ArgumentNullException(nameof(nextLink)); } using var message = CreateListOwnedObjectsNextRequest(nextLink); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { DirectoryObjectListResult value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = DirectoryObjectListResult.DeserializeDirectoryObjectListResult(document.RootElement); return Response.FromValue(value, message.Response); } default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Get the list of directory objects that are owned by the user. </summary> /// <param name="nextLink"> Next link for the list operation. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="nextLink"/> is null. </exception> public Response<DirectoryObjectListResult> ListOwnedObjectsNext(string nextLink, CancellationToken cancellationToken = default) { if (nextLink == null) { throw new ArgumentNullException(nameof(nextLink)); } using var message = CreateListOwnedObjectsNextRequest(nextLink); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { DirectoryObjectListResult value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = DirectoryObjectListResult.DeserializeDirectoryObjectListResult(document.RootElement); return Response.FromValue(value, message.Response); } default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreateListOwnedObjectsNextNextPageRequest(string nextLink) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); uri.Reset(endpoint); uri.AppendRawNextLink(nextLink, false); request.Uri = uri; request.Headers.Add("Accept", "application/json, text/json"); return message; } /// <summary> Get the list of directory objects that are owned by the user. </summary> /// <param name="nextLink"> The URL to the next page of results. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="nextLink"/> is null. </exception> public async Task<Response<DirectoryObjectListResult>> ListOwnedObjectsNextNextPageAsync(string nextLink, CancellationToken cancellationToken = default) { if (nextLink == null) { throw new ArgumentNullException(nameof(nextLink)); } using var message = CreateListOwnedObjectsNextNextPageRequest(nextLink); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { DirectoryObjectListResult value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = DirectoryObjectListResult.DeserializeDirectoryObjectListResult(document.RootElement); return Response.FromValue(value, message.Response); } default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Get the list of directory objects that are owned by the user. </summary> /// <param name="nextLink"> The URL to the next page of results. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="nextLink"/> is null. </exception> public Response<DirectoryObjectListResult> ListOwnedObjectsNextNextPage(string nextLink, CancellationToken cancellationToken = default) { if (nextLink == null) { throw new ArgumentNullException(nameof(nextLink)); } using var message = CreateListOwnedObjectsNextNextPageRequest(nextLink); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { DirectoryObjectListResult value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = DirectoryObjectListResult.DeserializeDirectoryObjectListResult(document.RootElement); return Response.FromValue(value, message.Response); } default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } } }
48.161184
166
0.602964
[ "MIT" ]
0rland0Wats0n/azure-sdk-for-net
sdk/testcommon/Azure.Graph.Rbac/src/Generated/SignedInUserRestOperations.cs
14,641
C#
 using ETModel; using UnityEngine.UI; using UnityEngine; namespace ETHotfix { public class InputBtnItem : InitBaseItem { public Text mInpuText; public Button mInputBtn; public override void Init(GameObject go) { base.Init(go); mInpuText = gameObject.FindChild("Text").GetComponent<Text>(); mInputBtn = gameObject.GetComponent<Button>(); mInputBtn.Add(InputBtnEvent); } public void InputBtnEvent() { UIComponent.GetUiView<JoinRoomPanelComponent>().InputNum(_InputNum); } private int _InputNum; public void InitBtn(int num) { if (num == -2) { UIComponent.GetUiView<JoinRoomPanelComponent>().mChongChuGo.transform.SetParent(gameObject.transform); UIComponent.GetUiView<JoinRoomPanelComponent>().mChongChuGo.transform.localPosition=Vector3.zero; } else if (num == -1) { UIComponent.GetUiView<JoinRoomPanelComponent>().mShuanChuGo.transform.SetParent(gameObject.transform); UIComponent.GetUiView<JoinRoomPanelComponent>().mShuanChuGo.transform.localPosition = Vector3.zero; } _InputNum = num; if (num >= 0) { mInpuText.text = num.ToString(); } else { mInpuText.text = string.Empty; } } } }
30.5
118
0.56
[ "MIT" ]
594270461/fivestar
Unity/Assets/Hotfix/GameGather/Common/FiveStarUI/JoinRoomPanel/InputBtnItem.cs
1,527
C#
#region << 版 本 注 释 >> /*---------------------------------------------------------------- * 项目名称 :QueryPage * 项目描述 : * 类 名 称 :CacheEntity * 类 描 述 : * 命名空间 :QueryPage * CLR 版本 :4.0.30319.42000 * 作 者 :jinyu * 创建时间 :2018 * 更新时间 :2018 * 版 本 号 :v1.0.0.0 ******************************************************************* * Copyright @ jinyu 2018. All rights reserved. ******************************************************************* //----------------------------------------------------------------*/ #endregion using System; using System.Collections.Generic; using System.Data; using System.Text; namespace QueryPage { /* ============================================================================== * 功能描述:CacheEntity 缓存实体 * 创 建 者:jinyu * 修 改 者:jinyu * 创建日期:2018 * 修改日期:2018 * ==============================================================================*/ /// <summary> /// 缓存实体 /// </summary> public class CacheEntity { /// <summary> /// MODEL /// </summary> public List<object> Model { get; set; } /// <summary> /// DataTable /// </summary> public DataTable DataTable { get; set; } /// <summary> /// 创建时间 /// </summary> public DateTime DateTime { get; set; } /// <summary> /// 对应的页码 /// </summary> public int PageNum { get; set; } public CacheEntity(List<object> list,int pageNum) { DateTime = DateTime.Now; Model = list; this.PageNum = pageNum; } public CacheEntity(DataTable dt,int pageNum) { DateTime = DateTime.Now; DataTable = dt; this.PageNum = pageNum; } } }
23.671053
86
0.381879
[ "MIT" ]
jinyuttt/DBAcessSrv
QueryPage/CacheEntity.cs
1,975
C#
using System; using System.Collections.Generic; using System.Text; using System.Text.RegularExpressions; namespace SharpSvn.MSBuild.FileParsers { sealed class CSharpParser : LanguageParser { public override void WriteComment(System.IO.StreamWriter sw, string text) { sw.Write("// "); sw.WriteLine(text); } public override bool FilterLine(string line) { string trimmed = line.Trim(); if (!trimmed.StartsWith("[")) return false; foreach (AttributeRegex ar in AttrMap.Values) { if (ar.Matches(line)) return true; } return false; } protected override void AddAttribute(Type attributeType) { AttrMap[attributeType] = new AttributeRegex(attributeType, ConstructRegex(attributeType), RegexOptions.None); } private string ConstructRegex(Type attributeType) { return @"^\s*\[\s*assembly\s*:\s*" +ConstructNameRegex(attributeType) + @"\s*(" + ArgumentsRegex + @"\s*)?\]"; } private string ConstructNameRegex(Type attributeType) { StringBuilder sb = new StringBuilder(); string[] parts = attributeType.FullName.Split('.'); sb.Append('(', parts.Length-1); sb.Append(@"(global\s*::\s*)?"); for (int i = 0; i < parts.Length-1; i++) { sb.Append(Regex.Escape(parts[i])); sb.Append(@"\s*\.\s*)?"); } string name = parts[parts.Length-1]; if (name.EndsWith("Attribute")) { sb.Append(Regex.Escape(name.Substring(0, name.Length - 9))); sb.Append("(Attribute)?"); } else sb.Append(Regex.Escape(name)); return sb.ToString(); } private string ArgumentsRegex { get { return @"\(([^""@)]|""([^\\""]|\\.)*""|@""([^""]|"""")*"")*\)"; } } protected override void StartAttribute(System.IO.StreamWriter sw, Type attributeType) { sw.Write("[assembly: global::"); sw.Write(attributeType.FullName); sw.Write("("); } protected override void EndAttribute(System.IO.StreamWriter sw) { sw.WriteLine(")]"); } protected override void WriteAttribute(System.IO.StreamWriter sw, Type attributeType, string value) { StartAttribute(sw, attributeType); sw.Write("@\""); sw.Write(value.Replace("\"", "\"\"")); sw.Write('\"'); EndAttribute(sw); } protected override void WriteAttribute(System.IO.StreamWriter sw, Type attributeType, bool value) { StartAttribute(sw, attributeType); sw.Write(value ? "true" : "false"); EndAttribute(sw); } public override string CopyrightEscape(string from) { return (from ?? "").Replace("(c)", "©"); } } }
29.560748
122
0.513753
[ "Apache-2.0" ]
AmpScm/SharpSvn
src/SharpSvn.MSBuild/FileParsers/CSharpParser.cs
3,166
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 is1 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 TestCases.HSSF.Model { using System; using Npoi.Core.DDF; using Npoi.Core.HSSF.Model; using NUnit.Framework; [TestFixture] public class TestDrawingManager2 { private DrawingManager2 drawingManager2; private EscherDggRecord dgg; [SetUp] public void SetUp() { dgg = new EscherDggRecord(); dgg.FileIdClusters = (new EscherDggRecord.FileIdCluster[0]); drawingManager2 = new DrawingManager2(dgg); } [Test] public void TestCreateDgRecord() { EscherDgRecord dgRecord1 = drawingManager2.CreateDgRecord(); Assert.AreEqual(1, dgRecord1.DrawingGroupId); Assert.AreEqual(-1, dgRecord1.LastMSOSPID); EscherDgRecord dgRecord2 = drawingManager2.CreateDgRecord(); Assert.AreEqual(2, dgRecord2.DrawingGroupId); Assert.AreEqual(-1, dgRecord2.LastMSOSPID); Assert.AreEqual(2, dgg.DrawingsSaved); Assert.AreEqual(2, dgg.FileIdClusters.Length); Assert.AreEqual(3, dgg.NumIdClusters); Assert.AreEqual(0, dgg.NumShapesSaved); } [Test] public void TestAllocateShapeId() { EscherDgRecord dgRecord1 = drawingManager2.CreateDgRecord(); EscherDgRecord dgRecord2 = drawingManager2.CreateDgRecord(); Assert.AreEqual(1024, drawingManager2.AllocateShapeId((short)1)); Assert.AreEqual(1024, dgRecord1.LastMSOSPID); Assert.AreEqual(1025, dgg.ShapeIdMax); Assert.AreEqual(1025, drawingManager2.AllocateShapeId((short)1)); Assert.AreEqual(1025, dgRecord1.LastMSOSPID); Assert.AreEqual(1026, dgg.ShapeIdMax); Assert.AreEqual(1026, drawingManager2.AllocateShapeId((short)1)); Assert.AreEqual(1026, dgRecord1.LastMSOSPID); Assert.AreEqual(1027, dgg.ShapeIdMax); Assert.AreEqual(2048, drawingManager2.AllocateShapeId((short)2)); Assert.AreEqual(2048, dgRecord2.LastMSOSPID); Assert.AreEqual(2049, dgg.ShapeIdMax); for (int i = 0; i < 1021; i++) { drawingManager2.AllocateShapeId((short)1); Assert.AreEqual(2049, dgg.ShapeIdMax); } Assert.AreEqual(3072, drawingManager2.AllocateShapeId((short)1)); Assert.AreEqual(3073, dgg.ShapeIdMax); Assert.AreEqual(2, dgg.DrawingsSaved); Assert.AreEqual(4, dgg.NumIdClusters); Assert.AreEqual(1026, dgg.NumShapesSaved); } } }
40.270588
77
0.653812
[ "Apache-2.0" ]
Arch/Npoi.Core
test/Npoi.Core.TestCases/HSSF/Model/TestDrawingManager2.cs
3,423
C#
/* * Copyright 2018 JDCLOUD.COM * * 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. * * Transcode Template * 转码模板管理相关接口 * * OpenAPI spec version: v1 * Contact: * * NOTE: This class is auto generated by the jdcloud code generator program. */ using System; using System.Collections.Generic; using System.Text; using JDCloudSDK.Core.Service; using JDCloudSDK.Mps.Model; using JDCloudSDK.Core.Annotation; namespace JDCloudSDK.Mps.Apis { /// <summary> /// 完整更新转码模板 /// </summary> public class UpdateTranscodeTemplateRequest : JdcloudRequest { ///<summary> /// 模板标题。长度不超过 128 个字符,最少 2 个字符。UTF-8 编码。 /// ///</summary> public string Title{ get; set; } ///<summary> /// 视频参数配置 ///</summary> public VideoStreamSettings Video{ get; set; } ///<summary> /// 音频参数配置 ///</summary> public AudioStreamSettings Audio{ get; set; } ///<summary> /// 封装容器配置 ///</summary> public ContainerSettings Container{ get; set; } ///<summary> /// 加密配置 ///</summary> public EncryptionSettings Encryption{ get; set; } ///<summary> /// 清晰度规格标记。取值范围: /// SD - 标清 /// HD - 高清 /// FHD - 超清 /// 2K /// 4K /// ///</summary> public string Definition{ get; set; } ///<summary> /// 转码方式。取值范围: /// normal - 普通转码 /// jdchd - 京享超清 /// jdchs - 极速转码 /// ///</summary> public string TranscodeType{ get; set; } ///<summary> /// 模板ID ///Required:true ///</summary> [Required] public long TemplateId{ get; set; } } }
26.193182
76
0.562256
[ "Apache-2.0" ]
jdcloud-api/jdcloud-sdk-net
sdk/src/Service/Mps/Apis/UpdateTranscodeTemplateRequest.cs
2,517
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MachineBox.Core.Models { public class ApiResponse<T> : ApiResponse { public T Data { get; set; } } public class ApiResponse { public string Message { get; set; } public int Status { get; set; } } }
18.95
45
0.641161
[ "MIT" ]
vkural/machinebox
MachineBox.Core/Models/ApiResponse.cs
381
C#
using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using CompanyName.MyMeetings.BuildingBlocks.Application; using CompanyName.MyMeetings.Modules.Payments.Application.Configuration.Commands; using CompanyName.MyMeetings.Modules.Payments.Application.Contracts; using FluentValidation; namespace CompanyName.MyMeetings.Modules.Payments.Infrastructure.Configuration.Processing { internal class ValidationCommandHandlerWithResultDecorator<T, TResult> : ICommandHandler<T, TResult> where T : ICommand<TResult> { private readonly IList<IValidator<T>> _validators; private readonly ICommandHandler<T, TResult> _decorated; public ValidationCommandHandlerWithResultDecorator( IList<IValidator<T>> validators, ICommandHandler<T, TResult> decorated) { this._validators = validators; _decorated = decorated; } public Task<TResult> Handle(T command, CancellationToken cancellationToken) { var errors = _validators .Select(v => v.Validate(command)) .SelectMany(result => result.Errors) .Where(error => error != null) .ToList(); if (errors.Any()) { throw new InvalidCommandException(errors.Select(x => x.ErrorMessage).ToList()); } return _decorated.Handle(command, cancellationToken); } } }
35.511628
104
0.669286
[ "MIT" ]
Ahmetcanb/modular-monolith-with-ddd
src/Modules/Payments/Infrastructure/Configuration/Processing/ValidationCommandHandlerWithResultDecorator.cs
1,529
C#
#if WITH_GAME #if PLATFORM_64BITS using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace UnrealEngine { public partial class ACameraActor { static readonly int AutoActivateForPlayer__Offset; public EAutoReceiveInput AutoActivateForPlayer { get{ CheckIsValid();return (EAutoReceiveInput)Marshal.PtrToStructure(_this.Get()+AutoActivateForPlayer__Offset, typeof(EAutoReceiveInput));} set{ CheckIsValid();Marshal.StructureToPtr(value, _this.Get()+AutoActivateForPlayer__Offset, false);} } static readonly int CameraComponent__Offset; public UCameraComponent CameraComponent { get{ CheckIsValid(); IntPtr v = Marshal.ReadIntPtr(_this.Get() + CameraComponent__Offset); if (v == IntPtr.Zero)return null; UCameraComponent retValue = new UCameraComponent(); retValue._this = v; return retValue; } set{ CheckIsValid(); if (value == null)Marshal.WriteIntPtr(_this.Get() + CameraComponent__Offset, IntPtr.Zero);else Marshal.WriteIntPtr(_this.Get() + CameraComponent__Offset, value._this.Get()); } } static readonly int SceneComponent__Offset; public USceneComponent SceneComponent { get{ CheckIsValid(); IntPtr v = Marshal.ReadIntPtr(_this.Get() + SceneComponent__Offset); if (v == IntPtr.Zero)return null; USceneComponent retValue = new USceneComponent(); retValue._this = v; return retValue; } set{ CheckIsValid(); if (value == null)Marshal.WriteIntPtr(_this.Get() + SceneComponent__Offset, IntPtr.Zero);else Marshal.WriteIntPtr(_this.Get() + SceneComponent__Offset, value._this.Get()); } } static readonly int bConstrainAspectRatio__Offset; public bool bConstrainAspectRatio { get{ CheckIsValid();return BoolWrap.Get(_this.Get(), bConstrainAspectRatio__Offset, 1, 0, 1, 1);} } static readonly int AspectRatio__Offset; public float AspectRatio { get{ CheckIsValid();return (float)Marshal.PtrToStructure(_this.Get()+AspectRatio__Offset, typeof(float));} } static readonly int FOVAngle__Offset; public float FOVAngle { get{ CheckIsValid();return (float)Marshal.PtrToStructure(_this.Get()+FOVAngle__Offset, typeof(float));} } static readonly int PostProcessBlendWeight__Offset; public float PostProcessBlendWeight { get{ CheckIsValid();return (float)Marshal.PtrToStructure(_this.Get()+PostProcessBlendWeight__Offset, typeof(float));} } static readonly int PostProcessSettings__Offset; public FPostProcessSettings PostProcessSettings { get{ CheckIsValid();return (FPostProcessSettings)Marshal.PtrToStructure(_this.Get()+PostProcessSettings__Offset, typeof(FPostProcessSettings));} } static ACameraActor() { IntPtr NativeClassPtr=GetNativeClassFromName("CameraActor"); AutoActivateForPlayer__Offset=GetPropertyOffset(NativeClassPtr,"AutoActivateForPlayer"); CameraComponent__Offset=GetPropertyOffset(NativeClassPtr,"CameraComponent"); SceneComponent__Offset=GetPropertyOffset(NativeClassPtr,"SceneComponent"); bConstrainAspectRatio__Offset=GetPropertyOffset(NativeClassPtr,"bConstrainAspectRatio"); AspectRatio__Offset=GetPropertyOffset(NativeClassPtr,"AspectRatio"); FOVAngle__Offset=GetPropertyOffset(NativeClassPtr,"FOVAngle"); PostProcessBlendWeight__Offset=GetPropertyOffset(NativeClassPtr,"PostProcessBlendWeight"); PostProcessSettings__Offset=GetPropertyOffset(NativeClassPtr,"PostProcessSettings"); } } } #endif #endif
39.272727
218
0.779803
[ "MIT" ]
RobertAcksel/UnrealCS
Engine/Plugins/UnrealCS/UECSharpDomain/UnrealEngine/GeneratedScriptFile_Game_64bits/ACameraActor_FixSize.cs
3,456
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 directconnect-2012-10-25.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.DirectConnect.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.DirectConnect.Model.Internal.MarshallTransformations { /// <summary> /// CreateLag Request Marshaller /// </summary> public class CreateLagRequestMarshaller : IMarshaller<IRequest, CreateLagRequest> , 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((CreateLagRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(CreateLagRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.DirectConnect"); string target = "OvertureService.CreateLag"; request.Headers["X-Amz-Target"] = target; request.Headers["Content-Type"] = "application/x-amz-json-1.1"; request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2012-10-25"; request.HttpMethod = "POST"; request.ResourcePath = "/"; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); var context = new JsonMarshallerContext(request, writer); if(publicRequest.IsSetChildConnectionTags()) { context.Writer.WritePropertyName("childConnectionTags"); context.Writer.WriteArrayStart(); foreach(var publicRequestChildConnectionTagsListValue in publicRequest.ChildConnectionTags) { context.Writer.WriteObjectStart(); var marshaller = TagMarshaller.Instance; marshaller.Marshall(publicRequestChildConnectionTagsListValue, context); context.Writer.WriteObjectEnd(); } context.Writer.WriteArrayEnd(); } if(publicRequest.IsSetConnectionId()) { context.Writer.WritePropertyName("connectionId"); context.Writer.Write(publicRequest.ConnectionId); } if(publicRequest.IsSetConnectionsBandwidth()) { context.Writer.WritePropertyName("connectionsBandwidth"); context.Writer.Write(publicRequest.ConnectionsBandwidth); } if(publicRequest.IsSetLagName()) { context.Writer.WritePropertyName("lagName"); context.Writer.Write(publicRequest.LagName); } if(publicRequest.IsSetLocation()) { context.Writer.WritePropertyName("location"); context.Writer.Write(publicRequest.Location); } if(publicRequest.IsSetNumberOfConnections()) { context.Writer.WritePropertyName("numberOfConnections"); context.Writer.Write(publicRequest.NumberOfConnections); } if(publicRequest.IsSetProviderName()) { context.Writer.WritePropertyName("providerName"); context.Writer.Write(publicRequest.ProviderName); } if(publicRequest.IsSetRequestMACSec()) { context.Writer.WritePropertyName("requestMACSec"); context.Writer.Write(publicRequest.RequestMACSec); } if(publicRequest.IsSetTags()) { context.Writer.WritePropertyName("tags"); context.Writer.WriteArrayStart(); foreach(var publicRequestTagsListValue in publicRequest.Tags) { context.Writer.WriteObjectStart(); var marshaller = TagMarshaller.Instance; marshaller.Marshall(publicRequestTagsListValue, 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 CreateLagRequestMarshaller _instance = new CreateLagRequestMarshaller(); internal static CreateLagRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static CreateLagRequestMarshaller Instance { get { return _instance; } } } }
37.146199
133
0.578401
[ "Apache-2.0" ]
Hazy87/aws-sdk-net
sdk/src/Services/DirectConnect/Generated/Model/Internal/MarshallTransformations/CreateLagRequestMarshaller.cs
6,352
C#
namespace MODEXngine.lib.Common { public static class Constants { public const string NAME_APP = "MODEXngine"; public const string ASSEMBLY_MASK_GAME_LIBS = "MODEXngine.lib.*.dll"; public const string ASSEMBLY_MASK_RENDER_LIBS = "MODEXngine.renderlib.*.dll"; public const string FILE_NAME_SETTINGS = "settings.json"; public const string SETTINGS_GAME_DATA_PATH = "GAME_DATA_PATH"; } }
29.4
85
0.702948
[ "MIT" ]
jcapellman/MODEXngine
src/MODEXngine.lib/Common/Constants.cs
443
C#
using System.Collections.Generic; using Essensoft.Paylink.Alipay.Response; namespace Essensoft.Paylink.Alipay.Request { /// <summary> /// alipay.commerce.transport.offlinepay.record.verify /// </summary> public class AlipayCommerceTransportOfflinepayRecordVerifyRequest : IAlipayRequest<AlipayCommerceTransportOfflinepayRecordVerifyResponse> { /// <summary> /// 支付宝脱机操作信息验证 /// </summary> public string BizContent { get; set; } #region IAlipayRequest Members private bool needEncrypt = false; private string apiVersion = "1.0"; private string terminalType; private string terminalInfo; private string prodCode; private string notifyUrl; private string returnUrl; private AlipayObject bizModel; public void SetNeedEncrypt(bool needEncrypt) { this.needEncrypt = needEncrypt; } public bool GetNeedEncrypt() { return needEncrypt; } public void SetNotifyUrl(string notifyUrl) { this.notifyUrl = notifyUrl; } public string GetNotifyUrl() { return notifyUrl; } public void SetReturnUrl(string returnUrl) { this.returnUrl = returnUrl; } public string GetReturnUrl() { return returnUrl; } public void SetTerminalType(string terminalType) { this.terminalType = terminalType; } public string GetTerminalType() { return terminalType; } public void SetTerminalInfo(string terminalInfo) { this.terminalInfo = terminalInfo; } public string GetTerminalInfo() { return terminalInfo; } public void SetProdCode(string prodCode) { this.prodCode = prodCode; } public string GetProdCode() { return prodCode; } public string GetApiName() { return "alipay.commerce.transport.offlinepay.record.verify"; } public void SetApiVersion(string apiVersion) { this.apiVersion = apiVersion; } public string GetApiVersion() { return apiVersion; } public IDictionary<string, string> GetParameters() { var parameters = new AlipayDictionary { { "biz_content", BizContent } }; return parameters; } public AlipayObject GetBizModel() { return bizModel; } public void SetBizModel(AlipayObject bizModel) { this.bizModel = bizModel; } #endregion } }
23.104839
141
0.555672
[ "MIT" ]
fory77/paylink
src/Essensoft.Paylink.Alipay/Request/AlipayCommerceTransportOfflinepayRecordVerifyRequest.cs
2,889
C#
// <auto-generated> // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace k8s.Models { using Microsoft.Rest; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; /// <summary> /// PodSpec is a description of a pod. /// </summary> public partial class V1PodSpec { /// <summary> /// Initializes a new instance of the V1PodSpec class. /// </summary> public V1PodSpec() { CustomInit(); } /// <summary> /// Initializes a new instance of the V1PodSpec class. /// </summary> /// <param name="containers">List of containers belonging to the pod. /// Containers cannot currently be added or removed. There must be at /// least one container in a Pod. Cannot be updated.</param> /// <param name="activeDeadlineSeconds">Optional duration in seconds /// the pod may be active on the node relative to StartTime before the /// system will actively try to mark it failed and kill associated /// containers. Value must be a positive integer.</param> /// <param name="affinity">If specified, the pod's scheduling /// constraints</param> /// <param /// name="automountServiceAccountToken">AutomountServiceAccountToken /// indicates whether a service account token should be automatically /// mounted.</param> /// <param name="dnsConfig">Specifies the DNS parameters of a pod. /// Parameters specified here will be merged to the generated DNS /// configuration based on DNSPolicy.</param> /// <param name="dnsPolicy">Set DNS policy for the pod. Defaults to /// "ClusterFirst". Valid values are 'ClusterFirstWithHostNet', /// 'ClusterFirst', 'Default' or 'None'. DNS parameters given in /// DNSConfig will be merged with the policy selected with DNSPolicy. /// To have DNS options set along with hostNetwork, you have to specify /// DNS policy explicitly to 'ClusterFirstWithHostNet'.</param> /// <param name="enableServiceLinks">EnableServiceLinks indicates /// whether information about services should be injected into pod's /// environment variables, matching the syntax of Docker links. /// Optional: Defaults to true.</param> /// <param name="hostAliases">HostAliases is an optional list of hosts /// and IPs that will be injected into the pod's hosts file if /// specified. This is only valid for non-hostNetwork pods.</param> /// <param name="hostIPC">Use the host's ipc namespace. Optional: /// Default to false.</param> /// <param name="hostNetwork">Host networking requested for this pod. /// Use the host's network namespace. If this option is set, the ports /// that will be used must be specified. Default to false.</param> /// <param name="hostPID">Use the host's pid namespace. Optional: /// Default to false.</param> /// <param name="hostname">Specifies the hostname of the Pod If not /// specified, the pod's hostname will be set to a system-defined /// value.</param> /// <param name="imagePullSecrets">ImagePullSecrets is an optional list /// of references to secrets in the same namespace to use for pulling /// any of the images used by this PodSpec. If specified, these secrets /// will be passed to individual puller implementations for them to /// use. For example, in the case of docker, only DockerConfig type /// secrets are honored. More info: /// https://kubernetes.io/docs/concepts/containers/images#specifying-imagepullsecrets-on-a-pod</param> /// <param name="initContainers">List of initialization containers /// belonging to the pod. Init containers are executed in order prior /// to containers being started. If any init container fails, the pod /// is considered to have failed and is handled according to its /// restartPolicy. The name for an init container or normal container /// must be unique among all containers. Init containers may not have /// Lifecycle actions, Readiness probes, or Liveness probes. The /// resourceRequirements of an init container are taken into account /// during scheduling by finding the highest request/limit for each /// resource type, and then using the max of of that value or the sum /// of the normal containers. Limits are applied to init containers in /// a similar fashion. Init containers cannot currently be added or /// removed. Cannot be updated. More info: /// https://kubernetes.io/docs/concepts/workloads/pods/init-containers/</param> /// <param name="nodeName">NodeName is a request to schedule this pod /// onto a specific node. If it is non-empty, the scheduler simply /// schedules this pod onto that node, assuming that it fits resource /// requirements.</param> /// <param name="nodeSelector">NodeSelector is a selector which must be /// true for the pod to fit on a node. Selector which must match a /// node's labels for the pod to be scheduled on that node. More info: /// https://kubernetes.io/docs/concepts/configuration/assign-pod-node/</param> /// <param name="priority">The priority value. Various system /// components use this field to find the priority of the pod. When /// Priority Admission Controller is enabled, it prevents users from /// setting this field. The admission controller populates this field /// from PriorityClassName. The higher the value, the higher the /// priority.</param> /// <param name="priorityClassName">If specified, indicates the pod's /// priority. "system-node-critical" and "system-cluster-critical" are /// two special keywords which indicate the highest priorities with the /// former being the highest priority. Any other name must be defined /// by creating a PriorityClass object with that name. If not /// specified, the pod priority will be default or zero if there is no /// default.</param> /// <param name="readinessGates">If specified, all readiness gates will /// be evaluated for pod readiness. A pod is ready when all its /// containers are ready AND all conditions specified in the readiness /// gates have status equal to "True" More info: /// https://git.k8s.io/enhancements/keps/sig-network/0007-pod-ready%2B%2B.md</param> /// <param name="restartPolicy">Restart policy for all containers /// within the pod. One of Always, OnFailure, Never. Default to Always. /// More info: /// https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#restart-policy</param> /// <param name="runtimeClassName">RuntimeClassName refers to a /// RuntimeClass object in the node.k8s.io group, which should be used /// to run this pod. If no RuntimeClass resource matches the named /// class, the pod will not be run. If unset or empty, the "legacy" /// RuntimeClass will be used, which is an implicit class with an empty /// definition that uses the default runtime handler. More info: /// https://git.k8s.io/enhancements/keps/sig-node/runtime-class.md This /// is an alpha feature and may change in the future.</param> /// <param name="schedulerName">If specified, the pod will be /// dispatched by specified scheduler. If not specified, the pod will /// be dispatched by default scheduler.</param> /// <param name="securityContext">SecurityContext holds pod-level /// security attributes and common container settings. Optional: /// Defaults to empty. See type description for default values of each /// field.</param> /// <param name="serviceAccount">DeprecatedServiceAccount is a /// depreciated alias for ServiceAccountName. Deprecated: Use /// serviceAccountName instead.</param> /// <param name="serviceAccountName">ServiceAccountName is the name of /// the ServiceAccount to use to run this pod. More info: /// https://kubernetes.io/docs/tasks/configure-pod-container/configure-service-account/</param> /// <param name="shareProcessNamespace">Share a single process /// namespace between all of the containers in a pod. When this is set /// containers will be able to view and signal processes from other /// containers in the same pod, and the first process in each container /// will not be assigned PID 1. HostPID and ShareProcessNamespace /// cannot both be set. Optional: Default to false. This field is /// beta-level and may be disabled with the PodShareProcessNamespace /// feature.</param> /// <param name="subdomain">If specified, the fully qualified Pod /// hostname will be "&lt;hostname&gt;.&lt;subdomain&gt;.&lt;pod /// namespace&gt;.svc.&lt;cluster domain&gt;". If not specified, the /// pod will not have a domainname at all.</param> /// <param name="terminationGracePeriodSeconds">Optional duration in /// seconds the pod needs to terminate gracefully. May be decreased in /// delete request. Value must be non-negative integer. The value zero /// indicates delete immediately. If this value is nil, the default /// grace period will be used instead. The grace period is the duration /// in seconds after the processes running in the pod are sent a /// termination signal and the time when the processes are forcibly /// halted with a kill signal. Set this value longer than the expected /// cleanup time for your process. Defaults to 30 seconds.</param> /// <param name="tolerations">If specified, the pod's /// tolerations.</param> /// <param name="volumes">List of volumes that can be mounted by /// containers belonging to the pod. More info: /// https://kubernetes.io/docs/concepts/storage/volumes</param> public V1PodSpec(IList<V1Container> containers, long? activeDeadlineSeconds = default(long?), V1Affinity affinity = default(V1Affinity), bool? automountServiceAccountToken = default(bool?), V1PodDNSConfig dnsConfig = default(V1PodDNSConfig), string dnsPolicy = default(string), bool? enableServiceLinks = default(bool?), IList<V1HostAlias> hostAliases = default(IList<V1HostAlias>), bool? hostIPC = default(bool?), bool? hostNetwork = default(bool?), bool? hostPID = default(bool?), string hostname = default(string), IList<V1LocalObjectReference> imagePullSecrets = default(IList<V1LocalObjectReference>), IList<V1Container> initContainers = default(IList<V1Container>), string nodeName = default(string), IDictionary<string, string> nodeSelector = default(IDictionary<string, string>), int? priority = default(int?), string priorityClassName = default(string), IList<V1PodReadinessGate> readinessGates = default(IList<V1PodReadinessGate>), string restartPolicy = default(string), string runtimeClassName = default(string), string schedulerName = default(string), V1PodSecurityContext securityContext = default(V1PodSecurityContext), string serviceAccount = default(string), string serviceAccountName = default(string), bool? shareProcessNamespace = default(bool?), string subdomain = default(string), long? terminationGracePeriodSeconds = default(long?), IList<V1Toleration> tolerations = default(IList<V1Toleration>), IList<V1Volume> volumes = default(IList<V1Volume>)) { ActiveDeadlineSeconds = activeDeadlineSeconds; Affinity = affinity; AutomountServiceAccountToken = automountServiceAccountToken; Containers = containers; DnsConfig = dnsConfig; DnsPolicy = dnsPolicy; EnableServiceLinks = enableServiceLinks; HostAliases = hostAliases; HostIPC = hostIPC; HostNetwork = hostNetwork; HostPID = hostPID; Hostname = hostname; ImagePullSecrets = imagePullSecrets; InitContainers = initContainers; NodeName = nodeName; NodeSelector = nodeSelector; Priority = priority; PriorityClassName = priorityClassName; ReadinessGates = readinessGates; RestartPolicy = restartPolicy; RuntimeClassName = runtimeClassName; SchedulerName = schedulerName; SecurityContext = securityContext; ServiceAccount = serviceAccount; ServiceAccountName = serviceAccountName; ShareProcessNamespace = shareProcessNamespace; Subdomain = subdomain; TerminationGracePeriodSeconds = terminationGracePeriodSeconds; Tolerations = tolerations; Volumes = volumes; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets optional duration in seconds the pod may be active on /// the node relative to StartTime before the system will actively try /// to mark it failed and kill associated containers. Value must be a /// positive integer. /// </summary> [JsonProperty(PropertyName = "activeDeadlineSeconds")] public long? ActiveDeadlineSeconds { get; set; } /// <summary> /// Gets or sets if specified, the pod's scheduling constraints /// </summary> [JsonProperty(PropertyName = "affinity")] public V1Affinity Affinity { get; set; } /// <summary> /// Gets or sets automountServiceAccountToken indicates whether a /// service account token should be automatically mounted. /// </summary> [JsonProperty(PropertyName = "automountServiceAccountToken")] public bool? AutomountServiceAccountToken { get; set; } /// <summary> /// Gets or sets list of containers belonging to the pod. Containers /// cannot currently be added or removed. There must be at least one /// container in a Pod. Cannot be updated. /// </summary> [JsonProperty(PropertyName = "containers")] public IList<V1Container> Containers { get; set; } /// <summary> /// Gets or sets specifies the DNS parameters of a pod. Parameters /// specified here will be merged to the generated DNS configuration /// based on DNSPolicy. /// </summary> [JsonProperty(PropertyName = "dnsConfig")] public V1PodDNSConfig DnsConfig { get; set; } /// <summary> /// Gets or sets set DNS policy for the pod. Defaults to /// "ClusterFirst". Valid values are 'ClusterFirstWithHostNet', /// 'ClusterFirst', 'Default' or 'None'. DNS parameters given in /// DNSConfig will be merged with the policy selected with DNSPolicy. /// To have DNS options set along with hostNetwork, you have to specify /// DNS policy explicitly to 'ClusterFirstWithHostNet'. /// </summary> [JsonProperty(PropertyName = "dnsPolicy")] public string DnsPolicy { get; set; } /// <summary> /// Gets or sets enableServiceLinks indicates whether information about /// services should be injected into pod's environment variables, /// matching the syntax of Docker links. Optional: Defaults to true. /// </summary> [JsonProperty(PropertyName = "enableServiceLinks")] public bool? EnableServiceLinks { get; set; } /// <summary> /// Gets or sets hostAliases is an optional list of hosts and IPs that /// will be injected into the pod's hosts file if specified. This is /// only valid for non-hostNetwork pods. /// </summary> [JsonProperty(PropertyName = "hostAliases")] public IList<V1HostAlias> HostAliases { get; set; } /// <summary> /// Gets or sets use the host's ipc namespace. Optional: Default to /// false. /// </summary> [JsonProperty(PropertyName = "hostIPC")] public bool? HostIPC { get; set; } /// <summary> /// Gets or sets host networking requested for this pod. Use the host's /// network namespace. If this option is set, the ports that will be /// used must be specified. Default to false. /// </summary> [JsonProperty(PropertyName = "hostNetwork")] public bool? HostNetwork { get; set; } /// <summary> /// Gets or sets use the host's pid namespace. Optional: Default to /// false. /// </summary> [JsonProperty(PropertyName = "hostPID")] public bool? HostPID { get; set; } /// <summary> /// Gets or sets specifies the hostname of the Pod If not specified, /// the pod's hostname will be set to a system-defined value. /// </summary> [JsonProperty(PropertyName = "hostname")] public string Hostname { get; set; } /// <summary> /// Gets or sets imagePullSecrets is an optional list of references to /// secrets in the same namespace to use for pulling any of the images /// used by this PodSpec. If specified, these secrets will be passed to /// individual puller implementations for them to use. For example, in /// the case of docker, only DockerConfig type secrets are honored. /// More info: /// https://kubernetes.io/docs/concepts/containers/images#specifying-imagepullsecrets-on-a-pod /// </summary> [JsonProperty(PropertyName = "imagePullSecrets")] public IList<V1LocalObjectReference> ImagePullSecrets { get; set; } /// <summary> /// Gets or sets list of initialization containers belonging to the /// pod. Init containers are executed in order prior to containers /// being started. If any init container fails, the pod is considered /// to have failed and is handled according to its restartPolicy. The /// name for an init container or normal container must be unique among /// all containers. Init containers may not have Lifecycle actions, /// Readiness probes, or Liveness probes. The resourceRequirements of /// an init container are taken into account during scheduling by /// finding the highest request/limit for each resource type, and then /// using the max of of that value or the sum of the normal containers. /// Limits are applied to init containers in a similar fashion. Init /// containers cannot currently be added or removed. Cannot be updated. /// More info: /// https://kubernetes.io/docs/concepts/workloads/pods/init-containers/ /// </summary> [JsonProperty(PropertyName = "initContainers")] public IList<V1Container> InitContainers { get; set; } /// <summary> /// Gets or sets nodeName is a request to schedule this pod onto a /// specific node. If it is non-empty, the scheduler simply schedules /// this pod onto that node, assuming that it fits resource /// requirements. /// </summary> [JsonProperty(PropertyName = "nodeName")] public string NodeName { get; set; } /// <summary> /// Gets or sets nodeSelector is a selector which must be true for the /// pod to fit on a node. Selector which must match a node's labels for /// the pod to be scheduled on that node. More info: /// https://kubernetes.io/docs/concepts/configuration/assign-pod-node/ /// </summary> [JsonProperty(PropertyName = "nodeSelector")] public IDictionary<string, string> NodeSelector { get; set; } /// <summary> /// Gets or sets the priority value. Various system components use this /// field to find the priority of the pod. When Priority Admission /// Controller is enabled, it prevents users from setting this field. /// The admission controller populates this field from /// PriorityClassName. The higher the value, the higher the priority. /// </summary> [JsonProperty(PropertyName = "priority")] public int? Priority { get; set; } /// <summary> /// Gets or sets if specified, indicates the pod's priority. /// "system-node-critical" and "system-cluster-critical" are two /// special keywords which indicate the highest priorities with the /// former being the highest priority. Any other name must be defined /// by creating a PriorityClass object with that name. If not /// specified, the pod priority will be default or zero if there is no /// default. /// </summary> [JsonProperty(PropertyName = "priorityClassName")] public string PriorityClassName { get; set; } /// <summary> /// Gets or sets if specified, all readiness gates will be evaluated /// for pod readiness. A pod is ready when all its containers are ready /// AND all conditions specified in the readiness gates have status /// equal to "True" More info: /// https://git.k8s.io/enhancements/keps/sig-network/0007-pod-ready%2B%2B.md /// </summary> [JsonProperty(PropertyName = "readinessGates")] public IList<V1PodReadinessGate> ReadinessGates { get; set; } /// <summary> /// Gets or sets restart policy for all containers within the pod. One /// of Always, OnFailure, Never. Default to Always. More info: /// https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#restart-policy /// </summary> [JsonProperty(PropertyName = "restartPolicy")] public string RestartPolicy { get; set; } /// <summary> /// Gets or sets runtimeClassName refers to a RuntimeClass object in /// the node.k8s.io group, which should be used to run this pod. If no /// RuntimeClass resource matches the named class, the pod will not be /// run. If unset or empty, the "legacy" RuntimeClass will be used, /// which is an implicit class with an empty definition that uses the /// default runtime handler. More info: /// https://git.k8s.io/enhancements/keps/sig-node/runtime-class.md This /// is an alpha feature and may change in the future. /// </summary> [JsonProperty(PropertyName = "runtimeClassName")] public string RuntimeClassName { get; set; } /// <summary> /// Gets or sets if specified, the pod will be dispatched by specified /// scheduler. If not specified, the pod will be dispatched by default /// scheduler. /// </summary> [JsonProperty(PropertyName = "schedulerName")] public string SchedulerName { get; set; } /// <summary> /// Gets or sets securityContext holds pod-level security attributes /// and common container settings. Optional: Defaults to empty. See /// type description for default values of each field. /// </summary> [JsonProperty(PropertyName = "securityContext")] public V1PodSecurityContext SecurityContext { get; set; } /// <summary> /// Gets or sets deprecatedServiceAccount is a depreciated alias for /// ServiceAccountName. Deprecated: Use serviceAccountName instead. /// </summary> [JsonProperty(PropertyName = "serviceAccount")] public string ServiceAccount { get; set; } /// <summary> /// Gets or sets serviceAccountName is the name of the ServiceAccount /// to use to run this pod. More info: /// https://kubernetes.io/docs/tasks/configure-pod-container/configure-service-account/ /// </summary> [JsonProperty(PropertyName = "serviceAccountName")] public string ServiceAccountName { get; set; } /// <summary> /// Gets or sets share a single process namespace between all of the /// containers in a pod. When this is set containers will be able to /// view and signal processes from other containers in the same pod, /// and the first process in each container will not be assigned PID 1. /// HostPID and ShareProcessNamespace cannot both be set. Optional: /// Default to false. This field is beta-level and may be disabled with /// the PodShareProcessNamespace feature. /// </summary> [JsonProperty(PropertyName = "shareProcessNamespace")] public bool? ShareProcessNamespace { get; set; } /// <summary> /// Gets or sets if specified, the fully qualified Pod hostname will be /// "&amp;lt;hostname&amp;gt;.&amp;lt;subdomain&amp;gt;.&amp;lt;pod /// namespace&amp;gt;.svc.&amp;lt;cluster domain&amp;gt;". If not /// specified, the pod will not have a domainname at all. /// </summary> [JsonProperty(PropertyName = "subdomain")] public string Subdomain { get; set; } /// <summary> /// Gets or sets optional duration in seconds the pod needs to /// terminate gracefully. May be decreased in delete request. Value /// must be non-negative integer. The value zero indicates delete /// immediately. If this value is nil, the default grace period will be /// used instead. The grace period is the duration in seconds after the /// processes running in the pod are sent a termination signal and the /// time when the processes are forcibly halted with a kill signal. Set /// this value longer than the expected cleanup time for your process. /// Defaults to 30 seconds. /// </summary> [JsonProperty(PropertyName = "terminationGracePeriodSeconds")] public long? TerminationGracePeriodSeconds { get; set; } /// <summary> /// Gets or sets if specified, the pod's tolerations. /// </summary> [JsonProperty(PropertyName = "tolerations")] public IList<V1Toleration> Tolerations { get; set; } /// <summary> /// Gets or sets list of volumes that can be mounted by containers /// belonging to the pod. More info: /// https://kubernetes.io/docs/concepts/storage/volumes /// </summary> [JsonProperty(PropertyName = "volumes")] public IList<V1Volume> Volumes { get; set; } /// <summary> /// Validate the object. /// </summary> /// <exception cref="ValidationException"> /// Thrown if validation fails /// </exception> public virtual void Validate() { if (Containers == null) { throw new ValidationException(ValidationRules.CannotBeNull, "Containers"); } if (Affinity != null) { Affinity.Validate(); } if (Containers != null) { foreach (var element in Containers) { if (element != null) { element.Validate(); } } } if (InitContainers != null) { foreach (var element1 in InitContainers) { if (element1 != null) { element1.Validate(); } } } if (ReadinessGates != null) { foreach (var element2 in ReadinessGates) { if (element2 != null) { element2.Validate(); } } } if (Volumes != null) { foreach (var element3 in Volumes) { if (element3 != null) { element3.Validate(); } } } } } }
53.872928
1,481
0.620244
[ "Apache-2.0" ]
xinyanmsft/csharp
src/KubernetesClient/generated/Models/V1PodSpec.cs
29,253
C#
// Disable warnings about XML documentation #pragma warning disable 1591 using lua_Integer = System.Int32; namespace MoonSharp.Interpreter.Interop.LuaStateInterop { public partial class LuaBase { protected static int memcmp(CharPtr ptr1, CharPtr ptr2, uint size) { return memcmp(ptr1, ptr2, (int) size); } protected static int memcmp(CharPtr ptr1, CharPtr ptr2, int size) { for (int i = 0; i < size; i++) { if (ptr1[i] != ptr2[i]) { if (ptr1[i] < ptr2[i]) { return -1; } return 1; } } return 0; } protected static CharPtr memchr(CharPtr ptr, char c, uint count) { for (uint i = 0; i < count; i++) { if (ptr[i] == c) { return new CharPtr(ptr.chars, (int) (ptr.index + i)); } } return null; } protected static CharPtr strpbrk(CharPtr str, CharPtr charset) { for (int i = 0; str[i] != '\0'; i++) for (int j = 0; charset[j] != '\0'; j++) { if (str[i] == charset[j]) { return new CharPtr(str.chars, str.index + i); } } return null; } protected static bool isalpha(char c) { return char.IsLetter(c); } protected static bool iscntrl(char c) { return char.IsControl(c); } protected static bool isdigit(char c) { return char.IsDigit(c); } protected static bool islower(char c) { return char.IsLower(c); } protected static bool ispunct(char c) { return char.IsPunctuation(c); } protected static bool isspace(char c) { return (c == ' ') || (c >= (char) 0x09 && c <= (char) 0x0D); } protected static bool isupper(char c) { return char.IsUpper(c); } protected static bool isalnum(char c) { return char.IsLetterOrDigit(c); } protected static bool isxdigit(char c) { return "0123456789ABCDEFabcdef".IndexOf(c) >= 0; } protected static bool isgraph(char c) { return !char.IsControl(c) && !char.IsWhiteSpace(c); } protected static bool isalpha(int c) { return char.IsLetter((char) c); } protected static bool iscntrl(int c) { return char.IsControl((char) c); } protected static bool isdigit(int c) { return char.IsDigit((char) c); } protected static bool islower(int c) { return char.IsLower((char) c); } protected static bool ispunct(int c) { return ((char) c != ' ') && !isalnum((char) c); } // *not* the same as Char.IsPunctuation protected static bool isspace(int c) { return ((char) c == ' ') || ((char) c >= (char) 0x09 && (char) c <= (char) 0x0D); } protected static bool isupper(int c) { return char.IsUpper((char) c); } protected static bool isalnum(int c) { return char.IsLetterOrDigit((char) c); } protected static bool isgraph(int c) { return !char.IsControl((char) c) && !char.IsWhiteSpace((char) c); } protected static char tolower(char c) { return char.ToLower(c); } protected static char toupper(char c) { return char.ToUpper(c); } protected static char tolower(int c) { return char.ToLower((char) c); } protected static char toupper(int c) { return char.ToUpper((char) c); } // find c in str protected static CharPtr strchr(CharPtr str, char c) { for (int index = str.index; str.chars[index] != 0; index++) { if (str.chars[index] == c) { return new CharPtr(str.chars, index); } } return null; } protected static CharPtr strcpy(CharPtr dst, CharPtr src) { int i; for (i = 0; src[i] != '\0'; i++) { dst[i] = src[i]; } dst[i] = '\0'; return dst; } protected static CharPtr strncpy(CharPtr dst, CharPtr src, int length) { int index = 0; while ((src[index] != '\0') && (index < length)) { dst[index] = src[index]; index++; } while (index < length) { dst[index++] = '\0'; } return dst; } protected static int strlen(CharPtr str) { int index = 0; while (str[index] != '\0') { index++; } return index; } public static void sprintf(CharPtr buffer, CharPtr str, params object[] argv) { string temp = Tools.sprintf(str.ToString(), argv); strcpy(buffer, temp); } } }
23.911392
93
0.438857
[ "MIT" ]
blakepell/AvalonMudClient
src/Avalon.MoonSharp/Interop/LuaStateInterop/LuaBase_CLib.cs
5,669
C#
using UnityEngine; using System.Collections.Generic; namespace UMA { /// <summary> /// Utility class for aligning meshes with the same rig but different binds. /// </summary> public static class SkinnedMeshAligner { public static void AlignBindPose(SkinnedMeshRenderer template, SkinnedMeshRenderer data) { var dataBones = data.bones; var templateBones = template.bones; Dictionary<Transform, Transform> boneMap = new Dictionary<Transform, Transform>(dataBones.Length); Dictionary<Transform, int> templateIndex = new Dictionary<Transform, int>(dataBones.Length); Dictionary<int, Matrix4x4> boneTransforms = new Dictionary<int, Matrix4x4>(dataBones.Length); int index = 0; foreach (var boneT in templateBones) { templateIndex.Add(boneT, index++); } var templateMesh = template.sharedMesh; var templateBindPoses = templateMesh.bindposes; var dataMesh = data.sharedMesh; var dataBindPoses = dataMesh.bindposes; var destDataBindPoses = dataMesh.bindposes; int sourceIndex = 0; foreach (var bone in dataBones) { var destIndex = FindBoneIndexInHierarchy(bone, template.rootBone, boneMap, templateIndex); if (destIndex == -1) { if (Debug.isDebugBuild) Debug.Log(bone.name, bone); sourceIndex++; continue; } var dataup = dataBindPoses[sourceIndex].MultiplyVector(Vector3.up); var dataright = dataBindPoses[sourceIndex].MultiplyVector(Vector3.right); var templateup = templateBindPoses[destIndex].MultiplyVector(Vector3.up); var templateright = templateBindPoses[destIndex].MultiplyVector(Vector3.right); if (Mathf.Abs(Vector3.Angle(dataup, templateup)) > 1 || Mathf.Abs(Vector3.Angle(dataright, templateright)) > 1) { // rotation differs significantly Matrix4x4 convertMatrix = templateBindPoses[destIndex].inverse * dataBindPoses[sourceIndex]; boneTransforms.Add(sourceIndex, convertMatrix); destDataBindPoses[sourceIndex] = templateBindPoses[destIndex]; } sourceIndex++; } dataMesh.bindposes = destDataBindPoses; var dataWeights = dataMesh.GetAllBoneWeights(); var dataVertices = dataMesh.vertices; var dataNormals = dataMesh.normals; // Get the number of bone weights per vertex var bonesPerVertex = dataMesh.GetBonesPerVertex(); sourceIndex = 0; // Vector3 oldPos = Vector3.zero; // Vector3 oldPosT = Vector3.zero; // Iterate over the vertices int bonesIndex = 0; for (var vertIndex = 0; vertIndex < dataMesh.vertexCount; vertIndex++) { Vector3 oldV = dataVertices[sourceIndex]; Vector3 newV = Vector3.zero; Vector3 oldN = dataNormals[sourceIndex]; Vector3 newN = Vector3.zero; var numberOfBonesForThisVertex = bonesPerVertex[vertIndex]; Matrix4x4 temp; // For each vertex, iterate over the array of bones the correct number of times for (var i = 0; i < numberOfBonesForThisVertex; i++) { BoneWeight1 boneweight = dataWeights[bonesIndex]; if (boneTransforms.TryGetValue(boneweight.boneIndex, out temp)) { newV += temp.MultiplyPoint(oldV) * boneweight.weight; newN += temp.MultiplyVector(oldN) * boneweight.weight; } else { newV += oldV * boneweight.weight; newN += oldN * boneweight.weight; } bonesIndex++; } dataVertices[sourceIndex] = newV; dataNormals[sourceIndex] = newN; sourceIndex++; } dataMesh.vertices = dataVertices; dataMesh.normals = dataNormals; } private static int FindBoneIndexInHierarchy(Transform bone, Transform hierarchyRoot, Dictionary<Transform, Transform> boneMap, Dictionary<Transform, int> boneIndexes) { var res = RecursiveFindBoneInHierarchy(bone, hierarchyRoot, boneMap); int idx; if (res != null && boneIndexes.TryGetValue(res, out idx)) { return idx; } return -1; } private static Transform RecursiveFindBoneInHierarchy(Transform bone, Transform hierarchyRoot, Dictionary<Transform, Transform> boneMap) { if (bone == null) { return null; } Transform res; if (boneMap.TryGetValue(bone, out res)) { return res; } if (string.Compare(hierarchyRoot.name, bone.name) == 0) { boneMap.Add(bone, hierarchyRoot); return hierarchyRoot; } else { res = null; var parent = RecursiveFindBoneInHierarchy(bone.parent, hierarchyRoot, boneMap); if (parent != null) { res = parent.Find(bone.name); if (res != null) { boneMap.Add(bone, res); } } return res; } } } }
34.993151
171
0.620082
[ "MIT" ]
Arlorean/UMA
UMAProject/Assets/UMA/Core/StandardAssets/UMA/Scripts/SkinnedMeshAligner.cs
5,109
C#
using System; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Akka.Actor; using Akka.Cluster; using Akka.Cluster.Management; using Akka.Cluster.Sharding; using Akka.Configuration; using Akka.Util.Internal; using Microsoft.Extensions.Hosting; namespace HostCore { public class Startup : IHostedService { private ActorSystem actorSystem; public Task StartAsync(CancellationToken cancellationToken) { var actorSystemName = "akka-cluster"; var hoconConfig = ConfigurationFactory.ParseString(File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + "application.conf")); var config = hoconConfig.GetConfig("cluster-management"); if (config != null) { actorSystemName = config.GetString("actorsystem", actorSystemName); } actorSystem = ActorSystem.Create(actorSystemName, hoconConfig); // Akka Management hosts the HTTP routes used by bootstrap ClusterHttpManagement.Get(actorSystem).Start(); Cluster.Get(actorSystem).RegisterOnMemberUp(() => { var shardRegion = ClusterSharding.Get(actorSystem).Start( typeName: "my-actor", entityProps: Props.Create<MyActor>(), settings: ClusterShardingSettings.Create(actorSystem), messageExtractor: new MessageExtractor()); Enumerable.Range(1, 100).ForEach(i => shardRegion.Tell(new ShardingEnvelope(Guid.NewGuid().ToString(), "hello!"))); }); return Task.CompletedTask; } public Task StopAsync(CancellationToken cancellationToken) { ClusterHttpManagement.Get(actorSystem).Stop(); return CoordinatedShutdown.Get(actorSystem).Run(CoordinatedShutdown.ClrExitReason.Instance); } } internal sealed class MessageExtractor : HashCodeMessageExtractor { public MessageExtractor() : base(maxNumberOfShards: 10) { } public override string EntityId(object message) => message switch { ShardingEnvelope e => e.EntityId, ShardRegion.StartEntity start => start.EntityId, _ => null }; public new object EntityMessage(object message) => (message as ShardingEnvelope)?.Message ?? message; } internal class MyActor : UntypedActor { protected override void OnReceive(object message) { switch (message) { default: /* ignore */ break; } } } }
31.701149
141
0.607324
[ "Apache-2.0" ]
ismaelhamed/akka-cluster-management
src/examples/HostCore/Startup.cs
2,758
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Naveego.DataQuality { public class RunTrend { public string Type { get; set; } public Decimal[] Data { get; set; } public string[] Categories { get; set; } public Decimal zScore { get; set; } public Guid[] RunIds { get; set; } } }
19.818182
49
0.598624
[ "Apache-2.0" ]
Naveego/naveego-net
src/Naveego/DataQuality/RunTrend.cs
438
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Laser.Orchard.CommunicationGateway.ViewModels { public enum SearchFieldEnum { Name, Mail, Phone } }
19
57
0.692982
[ "Apache-2.0" ]
INVA-Spa/Laser.Orchard.Platform
src/Modules/Laser.Orchard.CommunicationGateway/ViewModels/SearchFieldEnum.cs
230
C#
using System; using System.Collections.Generic; using System.Text; //http://ee-api.lrussell.net/online namespace EEApi.JSONWrapper { /// <summary> /// A class for the online players, retreivable by /online. /// </summary> public class Online : Wrapper { internal Online() { } /// <summary> /// A dictionary<string, string> representing each player UserID, and then their EE name. /// </summary> public OnlinePlayer[] PlayersOnline { get; set; } } }
22.333333
91
0.686567
[ "MIT" ]
SirJosh3917/EEApi
src/EEApi/Public/JSONWrapper/Online.cs
471
C#
#region --- License --- /* Copyright (c) 2006 - 2008 The Open Toolkit library. 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 using System; using System.Runtime.InteropServices; using System.Xml.Serialization; namespace Picodex.Render.Unity { /// <summary>Represents a 2D vector using two double-precision floating-point numbers.</summary> [Serializable] [StructLayout(LayoutKind.Sequential)] public struct Vector2d : IEquatable<Vector2d> { #region Fields /// <summary>The X coordinate of this instance.</summary> public double X; /// <summary>The Y coordinate of this instance.</summary> public double Y; /// <summary> /// Defines a unit-length Vector2d that points towards the X-axis. /// </summary> public static readonly Vector2d UnitX = new Vector2d(1, 0); /// <summary> /// Defines a unit-length Vector2d that points towards the Y-axis. /// </summary> public static readonly Vector2d UnitY = new Vector2d(0, 1); /// <summary> /// Defines a zero-length Vector2d. /// </summary> public static readonly Vector2d Zero = new Vector2d(0, 0); /// <summary> /// Defines an instance with all components set to 1. /// </summary> public static readonly Vector2d One = new Vector2d(1, 1); /// <summary> /// Defines the size of the Vector2d struct in bytes. /// </summary> public static readonly int SizeInBytes = Marshal.SizeOf(new Vector2d()); #endregion #region Constructors /// <summary> /// Constructs a new instance. /// </summary> /// <param name="value">The value that will initialize this instance.</param> public Vector2d(double value) { X = value; Y = value; } /// <summary>Constructs left vector with the given coordinates.</summary> /// <param name="x">The X coordinate.</param> /// <param name="y">The Y coordinate.</param> public Vector2d(double x, double y) { this.X = x; this.Y = y; } #endregion #region Public Members /// <summary> /// Gets or sets the value at the index of the Vector. /// </summary> public double this[int index] { get{ if(index == 0) return X; else if(index == 1) return Y; throw new IndexOutOfRangeException("You tried to access this vector at index: " + index); } set{ if(index == 0) X = value; else if(index == 1) Y = value; else throw new IndexOutOfRangeException("You tried to set this vector at index: " + index); } } #region Instance #region public void Add() /// <summary>Add the Vector passed as parameter to this instance.</summary> /// <param name="right">Right operand. This parameter is only read from.</param> [CLSCompliant(false)] [Obsolete("Use static Add() method instead.")] public void Add(Vector2d right) { this.X += right.X; this.Y += right.Y; } /// <summary>Add the Vector passed as parameter to this instance.</summary> /// <param name="right">Right operand. This parameter is only read from.</param> [CLSCompliant(false)] [Obsolete("Use static Add() method instead.")] public void Add(ref Vector2d right) { this.X += right.X; this.Y += right.Y; } #endregion public void Add() #region public void Sub() /// <summary>Subtract the Vector passed as parameter from this instance.</summary> /// <param name="right">Right operand. This parameter is only read from.</param> [CLSCompliant(false)] [Obsolete("Use static Subtract() method instead.")] public void Sub(Vector2d right) { this.X -= right.X; this.Y -= right.Y; } /// <summary>Subtract the Vector passed as parameter from this instance.</summary> /// <param name="right">Right operand. This parameter is only read from.</param> [CLSCompliant(false)] [Obsolete("Use static Subtract() method instead.")] public void Sub(ref Vector2d right) { this.X -= right.X; this.Y -= right.Y; } #endregion public void Sub() #region public void Mult() /// <summary>Multiply this instance by a scalar.</summary> /// <param name="f">Scalar operand.</param> [Obsolete("Use static Multiply() method instead.")] public void Mult(double f) { this.X *= f; this.Y *= f; } #endregion public void Mult() #region public void Div() /// <summary>Divide this instance by a scalar.</summary> /// <param name="f">Scalar operand.</param> [Obsolete("Use static Divide() method instead.")] public void Div(double f) { double mult = 1.0 / f; this.X *= mult; this.Y *= mult; } #endregion public void Div() #region public double Length /// <summary> /// Gets the length (magnitude) of the vector. /// </summary> /// <seealso cref="LengthSquared"/> public double Length { get { return System.Math.Sqrt(X * X + Y * Y); } } #endregion #region public double LengthSquared /// <summary> /// Gets the square of the vector length (magnitude). /// </summary> /// <remarks> /// This property avoids the costly square root operation required by the Length property. This makes it more suitable /// for comparisons. /// </remarks> /// <see cref="Length"/> public double LengthSquared { get { return X * X + Y * Y; } } #endregion #region public Vector2d PerpendicularRight /// <summary> /// Gets the perpendicular vector on the right side of this vector. /// </summary> public Vector2d PerpendicularRight { get { return new Vector2d(Y, -X); } } #endregion #region public Vector2d PerpendicularLeft /// <summary> /// Gets the perpendicular vector on the left side of this vector. /// </summary> public Vector2d PerpendicularLeft { get { return new Vector2d(-Y, X); } } #endregion /// <summary> /// Returns a copy of the Vector2d scaled to unit length. /// </summary> /// <returns></returns> public Vector2d Normalized() { Vector2d v = this; v.Normalize(); return v; } #region public void Normalize() /// <summary> /// Scales the Vector2 to unit length. /// </summary> public void Normalize() { double scale = 1.0 / Length; X *= scale; Y *= scale; } #endregion #region public void Scale() /// <summary> /// Scales the current Vector2 by the given amounts. /// </summary> /// <param name="sx">The scale of the X component.</param> /// <param name="sy">The scale of the Y component.</param> [Obsolete("Use static Multiply() method instead.")] public void Scale(double sx, double sy) { X *= sx; Y *= sy; } /// <summary>Scales this instance by the given parameter.</summary> /// <param name="scale">The scaling of the individual components.</param> [CLSCompliant(false)] [Obsolete("Use static Multiply() method instead.")] public void Scale(Vector2d scale) { this.X *= scale.X; this.Y *= scale.Y; } /// <summary>Scales this instance by the given parameter.</summary> /// <param name="scale">The scaling of the individual components.</param> [CLSCompliant(false)] [Obsolete("Use static Multiply() method instead.")] public void Scale(ref Vector2d scale) { this.X *= scale.X; this.Y *= scale.Y; } #endregion public void Scale() #endregion #region Static #region Obsolete #region Sub /// <summary> /// Subtract one Vector from another /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <returns>Result of subtraction</returns> [Obsolete("Use static Subtract() method instead.")] public static Vector2d Sub(Vector2d a, Vector2d b) { a.X -= b.X; a.Y -= b.Y; return a; } /// <summary> /// Subtract one Vector from another /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <param name="result">Result of subtraction</param> [Obsolete("Use static Subtract() method instead.")] public static void Sub(ref Vector2d a, ref Vector2d b, out Vector2d result) { result.X = a.X - b.X; result.Y = a.Y - b.Y; } #endregion #region Mult /// <summary> /// Multiply a vector and a scalar /// </summary> /// <param name="a">Vector operand</param> /// <param name="d">Scalar operand</param> /// <returns>Result of the multiplication</returns> [Obsolete("Use static Multiply() method instead.")] public static Vector2d Mult(Vector2d a, double d) { a.X *= d; a.Y *= d; return a; } /// <summary> /// Multiply a vector and a scalar /// </summary> /// <param name="a">Vector operand</param> /// <param name="d">Scalar operand</param> /// <param name="result">Result of the multiplication</param> [Obsolete("Use static Multiply() method instead.")] public static void Mult(ref Vector2d a, double d, out Vector2d result) { result.X = a.X * d; result.Y = a.Y * d; } #endregion #region Div /// <summary> /// Divide a vector by a scalar /// </summary> /// <param name="a">Vector operand</param> /// <param name="d">Scalar operand</param> /// <returns>Result of the division</returns> [Obsolete("Use static Divide() method instead.")] public static Vector2d Div(Vector2d a, double d) { double mult = 1.0 / d; a.X *= mult; a.Y *= mult; return a; } /// <summary> /// Divide a vector by a scalar /// </summary> /// <param name="a">Vector operand</param> /// <param name="d">Scalar operand</param> /// <param name="result">Result of the division</param> [Obsolete("Use static Divide() method instead.")] public static void Div(ref Vector2d a, double d, out Vector2d result) { double mult = 1.0 / d; result.X = a.X * mult; result.Y = a.Y * mult; } #endregion #endregion #region Add /// <summary> /// Adds two vectors. /// </summary> /// <param name="a">Left operand.</param> /// <param name="b">Right operand.</param> /// <returns>Result of operation.</returns> public static Vector2d Add(Vector2d a, Vector2d b) { Add(ref a, ref b, out a); return a; } /// <summary> /// Adds two vectors. /// </summary> /// <param name="a">Left operand.</param> /// <param name="b">Right operand.</param> /// <param name="result">Result of operation.</param> public static void Add(ref Vector2d a, ref Vector2d b, out Vector2d result) { result = new Vector2d(a.X + b.X, a.Y + b.Y); } #endregion #region Subtract /// <summary> /// Subtract one Vector from another /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <returns>Result of subtraction</returns> public static Vector2d Subtract(Vector2d a, Vector2d b) { Subtract(ref a, ref b, out a); return a; } /// <summary> /// Subtract one Vector from another /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <param name="result">Result of subtraction</param> public static void Subtract(ref Vector2d a, ref Vector2d b, out Vector2d result) { result = new Vector2d(a.X - b.X, a.Y - b.Y); } #endregion #region Multiply /// <summary> /// Multiplies a vector by a scalar. /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <returns>Result of the operation.</returns> public static Vector2d Multiply(Vector2d vector, double scale) { Multiply(ref vector, scale, out vector); return vector; } /// <summary> /// Multiplies a vector by a scalar. /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <param name="result">Result of the operation.</param> public static void Multiply(ref Vector2d vector, double scale, out Vector2d result) { result = new Vector2d(vector.X * scale, vector.Y * scale); } /// <summary> /// Multiplies a vector by the components a vector (scale). /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <returns>Result of the operation.</returns> public static Vector2d Multiply(Vector2d vector, Vector2d scale) { Multiply(ref vector, ref scale, out vector); return vector; } /// <summary> /// Multiplies a vector by the components of a vector (scale). /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <param name="result">Result of the operation.</param> public static void Multiply(ref Vector2d vector, ref Vector2d scale, out Vector2d result) { result = new Vector2d(vector.X * scale.X, vector.Y * scale.Y); } #endregion #region Divide /// <summary> /// Divides a vector by a scalar. /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <returns>Result of the operation.</returns> public static Vector2d Divide(Vector2d vector, double scale) { Divide(ref vector, scale, out vector); return vector; } /// <summary> /// Divides a vector by a scalar. /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <param name="result">Result of the operation.</param> public static void Divide(ref Vector2d vector, double scale, out Vector2d result) { Multiply(ref vector, 1 / scale, out result); } /// <summary> /// Divides a vector by the components of a vector (scale). /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <returns>Result of the operation.</returns> public static Vector2d Divide(Vector2d vector, Vector2d scale) { Divide(ref vector, ref scale, out vector); return vector; } /// <summary> /// Divide a vector by the components of a vector (scale). /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <param name="result">Result of the operation.</param> public static void Divide(ref Vector2d vector, ref Vector2d scale, out Vector2d result) { result = new Vector2d(vector.X / scale.X, vector.Y / scale.Y); } #endregion #region Min /// <summary> /// Calculate the component-wise minimum of two vectors /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <returns>The component-wise minimum</returns> public static Vector2d Min(Vector2d a, Vector2d b) { a.X = a.X < b.X ? a.X : b.X; a.Y = a.Y < b.Y ? a.Y : b.Y; return a; } /// <summary> /// Calculate the component-wise minimum of two vectors /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <param name="result">The component-wise minimum</param> public static void Min(ref Vector2d a, ref Vector2d b, out Vector2d result) { result.X = a.X < b.X ? a.X : b.X; result.Y = a.Y < b.Y ? a.Y : b.Y; } #endregion #region Max /// <summary> /// Calculate the component-wise maximum of two vectors /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <returns>The component-wise maximum</returns> public static Vector2d Max(Vector2d a, Vector2d b) { a.X = a.X > b.X ? a.X : b.X; a.Y = a.Y > b.Y ? a.Y : b.Y; return a; } /// <summary> /// Calculate the component-wise maximum of two vectors /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <param name="result">The component-wise maximum</param> public static void Max(ref Vector2d a, ref Vector2d b, out Vector2d result) { result.X = a.X > b.X ? a.X : b.X; result.Y = a.Y > b.Y ? a.Y : b.Y; } #endregion #region Clamp /// <summary> /// Clamp a vector to the given minimum and maximum vectors /// </summary> /// <param name="vec">Input vector</param> /// <param name="min">Minimum vector</param> /// <param name="max">Maximum vector</param> /// <returns>The clamped vector</returns> public static Vector2d Clamp(Vector2d vec, Vector2d min, Vector2d max) { vec.X = vec.X < min.X ? min.X : vec.X > max.X ? max.X : vec.X; vec.Y = vec.Y < min.Y ? min.Y : vec.Y > max.Y ? max.Y : vec.Y; return vec; } /// <summary> /// Clamp a vector to the given minimum and maximum vectors /// </summary> /// <param name="vec">Input vector</param> /// <param name="min">Minimum vector</param> /// <param name="max">Maximum vector</param> /// <param name="result">The clamped vector</param> public static void Clamp(ref Vector2d vec, ref Vector2d min, ref Vector2d max, out Vector2d result) { result.X = vec.X < min.X ? min.X : vec.X > max.X ? max.X : vec.X; result.Y = vec.Y < min.Y ? min.Y : vec.Y > max.Y ? max.Y : vec.Y; } #endregion #region Normalize /// <summary> /// Scale a vector to unit length /// </summary> /// <param name="vec">The input vector</param> /// <returns>The normalized vector</returns> public static Vector2d Normalize(Vector2d vec) { double scale = 1.0 / vec.Length; vec.X *= scale; vec.Y *= scale; return vec; } /// <summary> /// Scale a vector to unit length /// </summary> /// <param name="vec">The input vector</param> /// <param name="result">The normalized vector</param> public static void Normalize(ref Vector2d vec, out Vector2d result) { double scale = 1.0 / vec.Length; result.X = vec.X * scale; result.Y = vec.Y * scale; } #endregion #region NormalizeFast /// <summary> /// Scale a vector to approximately unit length /// </summary> /// <param name="vec">The input vector</param> /// <returns>The normalized vector</returns> public static Vector2d NormalizeFast(Vector2d vec) { double scale = Mathf.InverseSqrtFast(vec.X * vec.X + vec.Y * vec.Y); vec.X *= scale; vec.Y *= scale; return vec; } /// <summary> /// Scale a vector to approximately unit length /// </summary> /// <param name="vec">The input vector</param> /// <param name="result">The normalized vector</param> public static void NormalizeFast(ref Vector2d vec, out Vector2d result) { double scale = Mathf.InverseSqrtFast(vec.X * vec.X + vec.Y * vec.Y); result.X = vec.X * scale; result.Y = vec.Y * scale; } #endregion #region Dot /// <summary> /// Calculate the dot (scalar) product of two vectors /// </summary> /// <param name="left">First operand</param> /// <param name="right">Second operand</param> /// <returns>The dot product of the two inputs</returns> public static double Dot(Vector2d left, Vector2d right) { return left.X * right.X + left.Y * right.Y; } /// <summary> /// Calculate the dot (scalar) product of two vectors /// </summary> /// <param name="left">First operand</param> /// <param name="right">Second operand</param> /// <param name="result">The dot product of the two inputs</param> public static void Dot(ref Vector2d left, ref Vector2d right, out double result) { result = left.X * right.X + left.Y * right.Y; } #endregion #region Lerp /// <summary> /// Returns a new Vector that is the linear blend of the 2 given Vectors /// </summary> /// <param name="a">First input vector</param> /// <param name="b">Second input vector</param> /// <param name="blend">The blend factor. a when blend=0, b when blend=1.</param> /// <returns>a when blend=0, b when blend=1, and a linear combination otherwise</returns> public static Vector2d Lerp(Vector2d a, Vector2d b, double blend) { a.X = blend * (b.X - a.X) + a.X; a.Y = blend * (b.Y - a.Y) + a.Y; return a; } /// <summary> /// Returns a new Vector that is the linear blend of the 2 given Vectors /// </summary> /// <param name="a">First input vector</param> /// <param name="b">Second input vector</param> /// <param name="blend">The blend factor. a when blend=0, b when blend=1.</param> /// <param name="result">a when blend=0, b when blend=1, and a linear combination otherwise</param> public static void Lerp(ref Vector2d a, ref Vector2d b, double blend, out Vector2d result) { result.X = blend * (b.X - a.X) + a.X; result.Y = blend * (b.Y - a.Y) + a.Y; } #endregion #region Barycentric /// <summary> /// Interpolate 3 Vectors using Barycentric coordinates /// </summary> /// <param name="a">First input Vector</param> /// <param name="b">Second input Vector</param> /// <param name="c">Third input Vector</param> /// <param name="u">First Barycentric Coordinate</param> /// <param name="v">Second Barycentric Coordinate</param> /// <returns>a when u=v=0, b when u=1,v=0, c when u=0,v=1, and a linear combination of a,b,c otherwise</returns> public static Vector2d BaryCentric(Vector2d a, Vector2d b, Vector2d c, double u, double v) { return a + u * (b - a) + v * (c - a); } /// <summary>Interpolate 3 Vectors using Barycentric coordinates</summary> /// <param name="a">First input Vector.</param> /// <param name="b">Second input Vector.</param> /// <param name="c">Third input Vector.</param> /// <param name="u">First Barycentric Coordinate.</param> /// <param name="v">Second Barycentric Coordinate.</param> /// <param name="result">Output Vector. a when u=v=0, b when u=1,v=0, c when u=0,v=1, and a linear combination of a,b,c otherwise</param> public static void BaryCentric(ref Vector2d a, ref Vector2d b, ref Vector2d c, double u, double v, out Vector2d result) { result = a; // copy Vector2d temp = b; // copy Subtract(ref temp, ref a, out temp); Multiply(ref temp, u, out temp); Add(ref result, ref temp, out result); temp = c; // copy Subtract(ref temp, ref a, out temp); Multiply(ref temp, v, out temp); Add(ref result, ref temp, out result); } #endregion #region Transform /// <summary> /// Transforms a vector by a quaternion rotation. /// </summary> /// <param name="vec">The vector to transform.</param> /// <param name="quat">The quaternion to rotate the vector by.</param> /// <returns>The result of the operation.</returns> public static Vector2d Transform(Vector2d vec, Quaterniond quat) { Vector2d result; Transform(ref vec, ref quat, out result); return result; } /// <summary> /// Transforms a vector by a quaternion rotation. /// </summary> /// <param name="vec">The vector to transform.</param> /// <param name="quat">The quaternion to rotate the vector by.</param> /// <param name="result">The result of the operation.</param> public static void Transform(ref Vector2d vec, ref Quaterniond quat, out Vector2d result) { Quaterniond v = new Quaterniond(vec.X, vec.Y, 0, 0), i, t; Quaterniond.Invert(ref quat, out i); Quaterniond.Multiply(ref quat, ref v, out t); Quaterniond.Multiply(ref t, ref i, out v); result = new Vector2d(v.X, v.Y); } #endregion #endregion #region Swizzle /// <summary> /// Gets or sets an OpenTK.Vector2d with the Y and X components of this instance. /// </summary> [XmlIgnore] public Vector2d Yx { get { return new Vector2d(Y, X); } set { Y = value.X; X = value.Y; } } #endregion #region Operators /// <summary> /// Adds two instances. /// </summary> /// <param name="left">The left instance.</param> /// <param name="right">The right instance.</param> /// <returns>The result of the operation.</returns> public static Vector2d operator +(Vector2d left, Vector2d right) { left.X += right.X; left.Y += right.Y; return left; } /// <summary> /// Subtracts two instances. /// </summary> /// <param name="left">The left instance.</param> /// <param name="right">The right instance.</param> /// <returns>The result of the operation.</returns> public static Vector2d operator -(Vector2d left, Vector2d right) { left.X -= right.X; left.Y -= right.Y; return left; } /// <summary> /// Negates an instance. /// </summary> /// <param name="vec">The instance.</param> /// <returns>The result of the operation.</returns> public static Vector2d operator -(Vector2d vec) { vec.X = -vec.X; vec.Y = -vec.Y; return vec; } /// <summary> /// Multiplies an instance by a scalar. /// </summary> /// <param name="vec">The instance.</param> /// <param name="f">The scalar.</param> /// <returns>The result of the operation.</returns> public static Vector2d operator *(Vector2d vec, double f) { vec.X *= f; vec.Y *= f; return vec; } /// <summary> /// Multiply an instance by a scalar. /// </summary> /// <param name="f">The scalar.</param> /// <param name="vec">The instance.</param> /// <returns>The result of the operation.</returns> public static Vector2d operator *(double f, Vector2d vec) { vec.X *= f; vec.Y *= f; return vec; } /// <summary> /// Component-wise multiplication between the specified instance by a scale vector. /// </summary> /// <param name="scale">Left operand.</param> /// <param name="vec">Right operand.</param> /// <returns>Result of multiplication.</returns> public static Vector2d operator *(Vector2d vec, Vector2d scale) { vec.X *= scale.X; vec.Y *= scale.Y; return vec; } /// <summary> /// Divides an instance by a scalar. /// </summary> /// <param name="vec">The instance.</param> /// <param name="f">The scalar.</param> /// <returns>The result of the operation.</returns> public static Vector2d operator /(Vector2d vec, double f) { double mult = 1.0 / f; vec.X *= mult; vec.Y *= mult; return vec; } /// <summary> /// Compares two instances for equality. /// </summary> /// <param name="left">The left instance.</param> /// <param name="right">The right instance.</param> /// <returns>True, if both instances are equal; false otherwise.</returns> public static bool operator ==(Vector2d left, Vector2d right) { return left.Equals(right); } /// <summary> /// Compares two instances for ienquality. /// </summary> /// <param name="left">The left instance.</param> /// <param name="right">The right instance.</param> /// <returns>True, if the instances are not equal; false otherwise.</returns> public static bool operator !=(Vector2d left, Vector2d right) { return !left.Equals(right); } /// <summary>Converts OpenTK.Vector2 to OpenTK.Vector2d.</summary> /// <param name="v2">The Vector2 to convert.</param> /// <returns>The resulting Vector2d.</returns> public static explicit operator Vector2d(Vector2 v2) { return new Vector2d(v2.X, v2.Y); } /// <summary>Converts OpenTK.Vector2d to OpenTK.Vector2.</summary> /// <param name="v2d">The Vector2d to convert.</param> /// <returns>The resulting Vector2.</returns> public static explicit operator Vector2(Vector2d v2d) { return new Vector2((float)v2d.X, (float)v2d.Y); } #endregion #region Overrides #region public override string ToString() private static string listSeparator = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ListSeparator; /// <summary> /// Returns a System.String that represents the current instance. /// </summary> /// <returns></returns> public override string ToString() { return String.Format("({0}{2} {1})", X, Y, listSeparator); } #endregion #region public override int GetHashCode() /// <summary> /// Returns the hashcode for this instance. /// </summary> /// <returns>A System.Int32 containing the unique hashcode for this instance.</returns> public override int GetHashCode() { return X.GetHashCode() ^ Y.GetHashCode(); } #endregion #region public override bool Equals(object obj) /// <summary> /// Indicates whether this instance and a specified object are equal. /// </summary> /// <param name="obj">The object to compare to.</param> /// <returns>True if the instances are equal; false otherwise.</returns> public override bool Equals(object obj) { if (!(obj is Vector2d)) return false; return this.Equals((Vector2d)obj); } #endregion #endregion #endregion #region IEquatable<Vector2d> Members /// <summary>Indicates whether the current vector is equal to another vector.</summary> /// <param name="other">A vector to compare with this vector.</param> /// <returns>true if the current vector is equal to the vector parameter; otherwise, false.</returns> public bool Equals(Vector2d other) { return X == other.X && Y == other.Y; } #endregion } }
33.411153
145
0.54044
[ "Apache-2.0" ]
objuan/picodex
old/picodex.unity/UnityEngine/Math1/Vector2d.cs
35,349
C#
#region Imports... using System; using System.Data; using System.Collections; using System.Collections.Specialized; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; #endregion namespace Nettiers.AdventureWorks.Web.UI { /// <summary> /// Provides a mechanism for combining multiple IBindableTemplate definitions /// into a single instance. /// </summary> /// <remarks> /// Adapted from an article written by James Crowley, which can be found at: /// http://www.developerfusion.co.uk/show/4721/ /// </remarks> public class MultiBindableTemplate : IBindableTemplate { private IBindableTemplate[] _templates; /// <summary> /// Initializes a new instance of the MultiBindableTemplate class. /// </summary> /// <param name="templates"></param> public MultiBindableTemplate(params IBindableTemplate[] templates) { _templates = templates; } /// <summary> /// Initializes a new instance of the MultiBindableTemplate class. /// </summary> /// <param name="control"></param> /// <param name="paths"></param> public MultiBindableTemplate(TemplateControl control, params String[] paths) { _templates = new IBindableTemplate[paths.Length]; for ( int i=0; i<paths.Length; i++ ) { _templates[i] = FormUtil.LoadBindableTemplate(control, paths[i]); } } /// <summary> /// Retrieves a set of name/value pairs for values bound using /// two-way ASP.NET data-binding syntax within the templated content. /// </summary> /// <param name="container"> /// The System.Web.UI.Control from which to extract name/value pairs, which are /// passed by the data-bound control to an associated data source control in /// two-way data-binding scenarios. /// </param> /// <returns> /// An System.Collections.Specialized.IOrderedDictionary of name/value pairs. /// The name represents the name of a control within templated content, and the /// value is the current value of a property value bound using two-way ASP.NET /// data-binding syntax. /// </returns> public IOrderedDictionary ExtractValues(Control container) { IOrderedDictionary multi = null; IOrderedDictionary temp; if ( HasTemplates ) { multi = _templates[0].ExtractValues(container); // extract the values for each of the templates for ( int i = 1; i < _templates.Length; i++ ) { temp = _templates[i].ExtractValues(container); // copy over to the first collection foreach ( Object key in temp.Keys ) { multi.Add(key, temp[key]); } } } // return the combined collection return multi; } /// <summary> /// When implemented by a class, defines the System.Web.UI.Control object that /// child controls and templates belong to. These child controls are in turn /// defined within an inline template. /// </summary> /// <param name="container"> /// The System.Web.UI.Control object to contain the instances of controls from /// the inline template. /// </param> public void InstantiateIn(Control container) { // create a container control Control c = new Control(); if ( HasTemplates ) { // instantiate the templates into this control for ( int i = 0; i < _templates.Length; i++ ) { _templates[i].InstantiateIn(c); } } // add our control to the container we were passed container.Controls.Add(c); } /// <summary> /// Gets a value that indicates whether there are any templates specified. /// </summary> public bool HasTemplates { get { return (_templates != null && _templates.Length > 0); } } } }
29.746154
82
0.66227
[ "MIT" ]
aqua88hn/netTiers
Samples/AdventureWorks/Generated/Nettiers.AdventureWorks.Web/UI/MultiBindableTemplate.cs
3,869
C#
using System.Collections.Generic; namespace NeoBus.Abstraction { public interface IConsumer<T> { IEnumerable<T> Consume(bool autoCommit = true); void Commit(); T ConsumeOne(bool autoCommit); } }
16.785714
55
0.646809
[ "MIT" ]
omid-ahmadpour/NeoBus
NeoBus/Abstraction/IConsumer.cs
237
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class SolarSystemSpawner : MonoBehaviour { public CelestialBodyGenerator.ResolutionSettings resolutionSettings; void Awake () { Spawn (0); } public void Spawn (int seed) { var sw = System.Diagnostics.Stopwatch.StartNew (); PRNG prng = new PRNG (seed); CelestialBody[] bodies = FindObjectsOfType<CelestialBody> (); foreach (var body in bodies) { if (body.bodyType == CelestialBody.BodyType.Sun) { continue; } BodyPlaceholder placeholder = body.gameObject.GetComponentInChildren<BodyPlaceholder> (); var template = placeholder.bodySettings; Destroy (placeholder.gameObject); GameObject holder = new GameObject ("Body Generator"); var generator = holder.AddComponent<CelestialBodyGenerator> (); generator.transform.parent = body.transform; generator.gameObject.layer = body.gameObject.layer; generator.transform.localRotation = Quaternion.identity; generator.transform.localPosition = Vector3.zero; generator.transform.localScale = Vector3.one * body.radius; generator.resolutionSettings = resolutionSettings; generator.body = template; } Debug.Log ("Generation time: " + sw.ElapsedMilliseconds + " ms."); } }
27.652174
92
0.745283
[ "MIT" ]
12090113/Solar-System
Assets/Scripts/Game/SolarSystemSpawner.cs
1,274
C#
public enum DisplayStyle // TypeDefIndex: 4130 { // Fields public int value__; // 0x0 public const DisplayStyle Flex = 0; public const DisplayStyle None = 1; }
18.333333
46
0.721212
[ "MIT" ]
SinsofSloth/RF5-global-metadata
UnityEngine/UIElements/DisplayStyle.cs
165
C#
namespace NxBRE.FlowEngine.Rules { using System; using System.Collections; using NxBRE.FlowEngine; /// <summary> This rule will always return true. /// </summary> /// <author> Sloan Seaman /// </author> public sealed class True : IBRERuleFactory { /// <summary> Always returns true /// * /// </summary> /// <param name="aBrc">- The BRERuleContext object /// </param> /// <param name="aMap">- The IDictionary of parameters from the XML /// </param> /// <param name="aStep">- The step that it is on /// </param> /// <returns> Boolean.TRUE /// /// </returns> public object ExecuteRule(IBRERuleContext aBrc, IDictionary aMap, object aStep) { return true; } } }
22.454545
82
0.604588
[ "MIT" ]
Peidyen/NxBRE
NxBRE3/Source/FlowEngine/Rules/True.cs
741
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 workdocs-2016-05-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.WorkDocs.Model { /// <summary> /// Describes the metadata of the user. /// </summary> public partial class UserMetadata { private string _emailAddress; private string _givenName; private string _id; private string _surname; private string _username; /// <summary> /// Gets and sets the property EmailAddress. /// <para> /// The email address of the user. /// </para> /// </summary> [AWSProperty(Min=1, Max=256)] public string EmailAddress { get { return this._emailAddress; } set { this._emailAddress = value; } } // Check to see if EmailAddress property is set internal bool IsSetEmailAddress() { return this._emailAddress != null; } /// <summary> /// Gets and sets the property GivenName. /// <para> /// The given name of the user before a rename operation. /// </para> /// </summary> [AWSProperty(Min=1, Max=64)] public string GivenName { get { return this._givenName; } set { this._givenName = value; } } // Check to see if GivenName property is set internal bool IsSetGivenName() { return this._givenName != null; } /// <summary> /// Gets and sets the property Id. /// <para> /// The ID of the user. /// </para> /// </summary> [AWSProperty(Min=1, Max=256)] public string Id { get { return this._id; } set { this._id = value; } } // Check to see if Id property is set internal bool IsSetId() { return this._id != null; } /// <summary> /// Gets and sets the property Surname. /// <para> /// The surname of the user. /// </para> /// </summary> [AWSProperty(Min=1, Max=64)] public string Surname { get { return this._surname; } set { this._surname = value; } } // Check to see if Surname property is set internal bool IsSetSurname() { return this._surname != null; } /// <summary> /// Gets and sets the property Username. /// <para> /// The name of the user. /// </para> /// </summary> [AWSProperty(Min=1, Max=256)] public string Username { get { return this._username; } set { this._username = value; } } // Check to see if Username property is set internal bool IsSetUsername() { return this._username != null; } } }
28.07971
107
0.52929
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/WorkDocs/Generated/Model/UserMetadata.cs
3,875
C#
using Kxnrl; using System; using System.IO; namespace DNF_Utils { class Settings { private static readonly string configFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Kxnrl", "DNF", "dnf.conf"); public static string lastRunningVersion { get { return Win32Api.IniGet(configFile, "Settings", "lastRunning"); } set { Win32Api.IniSet(configFile, "Settings", "lastRunning", value); } } public static string lastRunningDate { get { return Win32Api.IniGet(configFile, "Settings", "lastDate"); } set { Win32Api.IniSet(configFile, "Settings", "lastDate", value); } } public static string lastGamePath { get { return Win32Api.IniGet(configFile, "Settings", "lastGamePath"); } set { Win32Api.IniSet(configFile, "Settings", "lastGamePath", value); } } } }
31.064516
168
0.623053
[ "MIT" ]
Kxnrl/DNF-Utils
DNF-Utils/Settings.cs
965
C#
using System; using System.Threading.Tasks; using ProtoBuf.Grpc.Client; using Service.BonusRewards.Client; using Service.BonusRewards.Grpc.Models; namespace TestApp { class Program { static async Task Main(string[] args) { GrpcClientFactory.AllowUnencryptedHttp2 = true; Console.Write("Press enter to start"); Console.ReadLine(); // // var factory = new BonusRewardsClientFactory("http://localhost:5001"); // var client = factory.GetHelloService(); // // var resp = await client.SayHelloAsync(new HelloRequest(){Name = "Alex"}); // Console.WriteLine(resp?.Message); Console.WriteLine("End"); Console.ReadLine(); } } }
26.4
89
0.589646
[ "MIT" ]
MyJetWallet/Service.Bonus.PaidProcess
test/TestApp/Program.cs
794
C#
using Comet.Skia.WPF; namespace Comet.Skia { public static class UI { static bool _hasInitialized; public static void Init() { if (_hasInitialized) return; _hasInitialized = true; Comet.WPF.UI.Init(); // Controls Registrar.Handlers.Register<DrawableControl, DrawableControlHandler>(); Registrar.Handlers.Register<SkiaView, SkiaViewHandler>(); var generic = typeof(SkiaControlHandler<>); Skia.Internal.Registration.RegisterDefaultViews(generic); } } }
21.304348
74
0.730612
[ "MIT" ]
Clancey/Comet
src/Comet.Skia.WPF/UI.cs
492
C#
using Microsoft.AspNetCore.Mvc.ViewFeatures; using Microsoft.AspNetCore.Razor.TagHelpers; using Util.Ui.Angular.Base; using Util.Ui.Configs; using Util.Ui.Renders; using Util.Ui.TagHelpers; using Util.Ui.Zorro.Forms.Renders; namespace Util.Ui.Zorro.Forms { /// <summary> /// 开关 /// </summary> [HtmlTargetElement( "util-switch" )] public class SwitchTagHelper : AngularTagHelperBase { /// <summary> /// 属性表达式 /// </summary> public ModelExpression For { get; set; } /// <summary> /// [(ngModel)],模型绑定 /// </summary> public string NgModel { get; set; } /// <summary> /// 是否显示标签,默认值:false /// </summary> public bool ShowLabel { get; set; } /// <summary> /// 标签文本 /// </summary> public string LabelText { get; set; } /// <summary> /// 标签的栅格占位格数 /// </summary> public int LabelSpan { get; set; } /// <summary> /// name,控件名称 /// </summary> public string Name { get; set; } /// <summary> /// [name],控件名称 /// </summary> public string BindName { get; set; } /// <summary> /// nzDisabled,禁用 /// </summary> public bool Disabled { get; set; } /// <summary> /// [nzDisabled],禁用 /// </summary> public string BindDisabled { get; set; } /// <summary> /// nzSpan,24栅格占位格数,可选值: 0 - 24, 为 0 时隐藏 /// </summary> public int Span { get; set; } /// <summary> /// (ngModelChange),变更事件处理函数 /// </summary> public string OnChange { get; set; } /// <summary> /// 获取渲染器 /// </summary> /// <param name="context">上下文</param> protected override IRender GetRender( Context context ) { return new SwitchRender( new Config( context ) ); } } }
28.188406
65
0.507455
[ "MIT" ]
xljiulang/Util
src/Util.Ui.Angular.AntDesign/Zorro/Forms/SwitchTagHelper.cs
2,101
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Beta3_WS_PROYECTO_FINAL.GUI.MainAdmin; namespace Beta3_WS_PROYECTO_FINAL.GUI.UC { public partial class UC_cuenta_administrador : UserControl { public UC_cuenta_administrador() { InitializeComponent(); } private void btn_addDT_Admin_Click(object sender, EventArgs e) { frm_verDT_admin objVerDT = new frm_verDT_admin(); objVerDT.ShowDialog(); } private void btn_addAdmin_Admin_Click(object sender, EventArgs e) { frm_verAdmin_admin objverAdmin = new frm_verAdmin_admin(); objverAdmin.ShowDialog(); } private void btn_addORG_Admin_Click(object sender, EventArgs e) { frm_verOrg_admin objVerOrg = new frm_verOrg_admin(); objVerOrg.ShowDialog(); } } }
26.6
73
0.669173
[ "MIT" ]
SnakeCorporationTecno/papa
Beta3_WS_PROYECTO_FINAL/GUI/MainAdmin/UC_cuenta_administrador.cs
1,066
C#
// ************************************************************************** // Copyright 2020 VMware, Inc. // SPDX-License-Identifier: Apache-2.0 // ************************************************************************** using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace VMware.ScriptRuntimeService.APIGateway.Runspace.Impl.RetentionPolicy { public class RemoveExpiredActiveRunspaceRuleFactory : IRemoveExpiredActiveRunspaceRuleFactory { public IRunspaceRetentionRule Create(int maxActiveTimeoutMinutes) { return new RemoveExpiredActiveRunspaceRule(maxActiveTimeoutMinutes); } } }
35.526316
98
0.613333
[ "Apache-2.0" ]
dmilov/script-runtime-service-for-vsphere
src/Endpoint/VMware.ScriptRuntimeService.APIGateway/Runspace/Impl/RetentionPolicy/RemoveExpiredActiveRunspaceRuleFactory.cs
677
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Security.Permissions { #if NETCOREAPP [Obsolete(Obsoletions.CodeAccessSecurityMessage, DiagnosticId = Obsoletions.CodeAccessSecurityDiagId, UrlFormat = Obsoletions.SharedUrlFormat)] #endif [AttributeUsage((AttributeTargets)(109), AllowMultiple = true, Inherited = false)] public sealed partial class UrlIdentityPermissionAttribute : CodeAccessSecurityAttribute { public UrlIdentityPermissionAttribute(SecurityAction action) : base(default(SecurityAction)) { } public string Url { get; set; } public override IPermission CreatePermission() { return default(IPermission); } } }
45.588235
147
0.766452
[ "MIT" ]
AUTOMATE-2001/runtime
src/libraries/System.Security.Permissions/src/System/Security/Permissions/UrlIdentityPermissionAttribute.cs
775
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using UnityEngine; /// <summary> /// A collection of helper functions for Texture2D /// </summary> public static class Texture2DExtensions { /// <summary> /// Fills the pixels. You will need to call Apply on the texture in order for changes to take place. /// </summary> /// <param name="texture2D">The Texture2D.</param> /// <param name="row">The row to start filling at.</param> /// <param name="col">The column to start filling at.</param> /// <param name="width">The width to fill.</param> /// <param name="height">The height to fill.</param> /// <param name="fillColor">Color of the fill.</param> /// <remarks>This function considers row 0 to be left and col 0 to be top.</remarks> public static void FillPixels(this Texture2D texture2D, int row, int col, int width, int height, Color fillColor) { if (col + width > texture2D.width || row + height > texture2D.height) { throw new IndexOutOfRangeException(); } Color32 toColor = fillColor; // Implicit cast var colors = new Color32[width * height]; for (var i = 0; i < colors.Length; i++) { colors[i] = toColor; } texture2D.SetPixels32(col, (texture2D.height - row) - height, width, height, colors); } /// <summary> /// Fills the texture with a single color. /// </summary> /// <param name="texture2D">The Texture2D.</param> /// <param name="fillColor">Color of the fill.</param> public static void FillPixels(this Texture2D texture2D, Color fillColor) { texture2D.FillPixels(0, 0, texture2D.width, texture2D.height, fillColor); } /// <summary> /// Captures a region of the screen and returns it as a texture. /// </summary> /// <param name="x">x position of the screen to capture from (bottom-left)</param> /// <param name="y">y position of the screen to capture from (bottom-left)</param> /// <param name="width">width of the screen area to capture</param> /// <param name="height">height of the screen area to capture</param> /// <returns>A Texture2D containing pixels from the region of the screen specified</returns> /// <remarks>You should call this in OnPostRender.</remarks> public static Texture2D CaptureScreenRegion(int x, int y, int width, int height) { var tex = new Texture2D(width, height); tex.ReadPixels(new Rect(x, y, Screen.width, Screen.height), 0, 0); tex.Apply(); return tex; } /// <summary> /// Creates a texture from a defined region. /// </summary> /// <param name="texture2D">The Texture2D.</param> /// <param name="x">x position of this texture to get the texture from</param> /// <param name="y">y position of this texture to get the texture from</param> /// <param name="width">width of the region to capture</param> /// <param name="height">height of the region to capture</param> public static Texture2D CreateTextureFromRegion(this Texture2D texture2D, int x, int y, int width, int height) { var pixels = texture2D.GetPixels(x, y, width, height); var destTex = new Texture2D(width, height); destTex.SetPixels(pixels); destTex.Apply(); return destTex; } }
40.369048
117
0.63875
[ "MIT" ]
Alliance-DJ/project-adj-client
Assets/Scripts/Core/Microsoft/Extensions/Texture2DExtensions.cs
3,393
C#
/******************************************************************************* * Copyright 2009-2017 Amazon Services. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * * You may not use this file except in compliance with the License. * You may obtain a copy of the License at: http://aws.amazon.com/apache2.0 * 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. ******************************************************************************* * Marketplace Web Service Products * API Version: 2011-10-01 * Library Version: 2017-03-22 * Generated: Wed Mar 22 23:24:36 UTC 2017 */ using System; using AmazonAPI.MWSClientRuntime; using AmazonAPI.Products.MarketplaceWebServiceProducts.Model; namespace AmazonAPI.Products.MarketplaceWebServiceProducts { /// <summary> /// MarketplaceWebServiceProductsClient is an implementation of MarketplaceWebServiceProducts /// </summary> public class MarketplaceWebServiceProductsClient : MarketplaceWebServiceProducts { private const string libraryVersion = "2017-03-22"; private string servicePath; private MwsConnection connection; /// <summary> /// Create client. /// </summary> /// <param name="accessKey">Access Key</param> /// <param name="secretKey">Secret Key</param> /// <param name="applicationName">Application Name</param> /// <param name="applicationVersion">Application Version</param> /// <param name="config">configuration</param> public MarketplaceWebServiceProductsClient( String applicationName, String applicationVersion, String accessKey, String secretKey, MarketplaceWebServiceProductsConfig config) { connection = config.CopyConnection(); connection.AwsAccessKeyId = accessKey; connection.AwsSecretKeyId = secretKey; connection.ApplicationName = applicationName; connection.ApplicationVersion = applicationVersion; connection.LibraryVersion = libraryVersion; servicePath = config.ServicePath; } /// <summary> /// Create client. /// </summary> /// <param name="accessKey">Access Key</param> /// <param name="secretKey">Secret Key</param> /// <param name="config">configuration</param> public MarketplaceWebServiceProductsClient(String accessKey, String secretKey, MarketplaceWebServiceProductsConfig config) { connection = config.CopyConnection(); connection.AwsAccessKeyId = accessKey; connection.AwsSecretKeyId = secretKey; connection.LibraryVersion = libraryVersion; servicePath = config.ServicePath; } /// <summary> /// Create client. /// </summary> /// <param name="accessKey">Access Key</param> /// <param name="secretKey">Secret Key</param> public MarketplaceWebServiceProductsClient(String accessKey, String secretKey) : this(accessKey, secretKey, new MarketplaceWebServiceProductsConfig()) { } /// <summary> /// Create client. /// </summary> /// <param name="accessKey">Access Key</param> /// <param name="secretKey">Secret Key</param> /// <param name="applicationName">Application Name</param> /// <param name="applicationVersion">Application Version</param> public MarketplaceWebServiceProductsClient( String accessKey, String secretKey, String applicationName, String applicationVersion ) : this(accessKey, secretKey, applicationName, applicationVersion, new MarketplaceWebServiceProductsConfig()) { } public GetCompetitivePricingForASINResponse GetCompetitivePricingForASIN(GetCompetitivePricingForASINRequest request) { return connection.Call( new MarketplaceWebServiceProductsClient.Request<GetCompetitivePricingForASINResponse>("GetCompetitivePricingForASIN", typeof(GetCompetitivePricingForASINResponse), servicePath), request); } public GetCompetitivePricingForSKUResponse GetCompetitivePricingForSKU(GetCompetitivePricingForSKURequest request) { return connection.Call( new MarketplaceWebServiceProductsClient.Request<GetCompetitivePricingForSKUResponse>("GetCompetitivePricingForSKU", typeof(GetCompetitivePricingForSKUResponse), servicePath), request); } public GetLowestOfferListingsForASINResponse GetLowestOfferListingsForASIN(GetLowestOfferListingsForASINRequest request) { return connection.Call( new MarketplaceWebServiceProductsClient.Request<GetLowestOfferListingsForASINResponse>("GetLowestOfferListingsForASIN", typeof(GetLowestOfferListingsForASINResponse), servicePath), request); } public GetLowestOfferListingsForSKUResponse GetLowestOfferListingsForSKU(GetLowestOfferListingsForSKURequest request) { return connection.Call( new MarketplaceWebServiceProductsClient.Request<GetLowestOfferListingsForSKUResponse>("GetLowestOfferListingsForSKU", typeof(GetLowestOfferListingsForSKUResponse), servicePath), request); } public GetLowestPricedOffersForASINResponse GetLowestPricedOffersForASIN(GetLowestPricedOffersForASINRequest request) { return connection.Call( new MarketplaceWebServiceProductsClient.Request<GetLowestPricedOffersForASINResponse>("GetLowestPricedOffersForASIN", typeof(GetLowestPricedOffersForASINResponse), servicePath), request); } public GetLowestPricedOffersForSKUResponse GetLowestPricedOffersForSKU(GetLowestPricedOffersForSKURequest request) { return connection.Call( new MarketplaceWebServiceProductsClient.Request<GetLowestPricedOffersForSKUResponse>("GetLowestPricedOffersForSKU", typeof(GetLowestPricedOffersForSKUResponse), servicePath), request); } public GetMatchingProductResponse GetMatchingProduct(GetMatchingProductRequest request) { return connection.Call( new MarketplaceWebServiceProductsClient.Request<GetMatchingProductResponse>("GetMatchingProduct", typeof(GetMatchingProductResponse), servicePath), request); } public GetMatchingProductForIdResponse GetMatchingProductForId(GetMatchingProductForIdRequest request) { return connection.Call( new MarketplaceWebServiceProductsClient.Request<GetMatchingProductForIdResponse>("GetMatchingProductForId", typeof(GetMatchingProductForIdResponse), servicePath), request); } public GetMyFeesEstimateResponse GetMyFeesEstimate(GetMyFeesEstimateRequest request) { return connection.Call( new MarketplaceWebServiceProductsClient.Request<GetMyFeesEstimateResponse>("GetMyFeesEstimate", typeof(GetMyFeesEstimateResponse), servicePath), request); } public GetMyPriceForASINResponse GetMyPriceForASIN(GetMyPriceForASINRequest request) { return connection.Call( new MarketplaceWebServiceProductsClient.Request<GetMyPriceForASINResponse>("GetMyPriceForASIN", typeof(GetMyPriceForASINResponse), servicePath), request); } public GetMyPriceForSKUResponse GetMyPriceForSKU(GetMyPriceForSKURequest request) { return connection.Call( new MarketplaceWebServiceProductsClient.Request<GetMyPriceForSKUResponse>("GetMyPriceForSKU", typeof(GetMyPriceForSKUResponse), servicePath), request); } public GetProductCategoriesForASINResponse GetProductCategoriesForASIN(GetProductCategoriesForASINRequest request) { return connection.Call( new MarketplaceWebServiceProductsClient.Request<GetProductCategoriesForASINResponse>("GetProductCategoriesForASIN", typeof(GetProductCategoriesForASINResponse), servicePath), request); } public GetProductCategoriesForSKUResponse GetProductCategoriesForSKU(GetProductCategoriesForSKURequest request) { return connection.Call( new MarketplaceWebServiceProductsClient.Request<GetProductCategoriesForSKUResponse>("GetProductCategoriesForSKU", typeof(GetProductCategoriesForSKUResponse), servicePath), request); } public GetServiceStatusResponse GetServiceStatus(GetServiceStatusRequest request) { return connection.Call( new MarketplaceWebServiceProductsClient.Request<GetServiceStatusResponse>("GetServiceStatus", typeof(GetServiceStatusResponse), servicePath), request); } public ListMatchingProductsResponse ListMatchingProducts(ListMatchingProductsRequest request) { return connection.Call( new MarketplaceWebServiceProductsClient.Request<ListMatchingProductsResponse>("ListMatchingProducts", typeof(ListMatchingProductsResponse), servicePath), request); } private class Request<R> : IMwsRequestType<R> where R : IMwsObject { private string operationName; private Type responseClass; private string servicePath; public Request(string operationName, Type responseClass, string servicePath) { this.operationName = operationName; this.responseClass = responseClass; this.servicePath = servicePath; } public string ServicePath { get { return servicePath; } } public string OperationName { get { return operationName; } } public Type ResponseClass { get { return responseClass; } } public MwsException WrapException(Exception cause) { return new MarketplaceWebServiceProductsException(cause); } public void SetResponseHeaderMetadata(IMwsObject response, MwsResponseHeaderMetadata rhmd) { ((IMWSResponse)response).ResponseHeaderMetadata = new ResponseHeaderMetadata(rhmd); } } } }
44.727273
196
0.67184
[ "MIT" ]
ECourant/AmazonAPI
Products/MarketplaceWebServiceProductsClient.cs
10,824
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using Mono.Cecil; namespace BuildTool { public static class Publicizer { public static IEnumerable<string> Execute(IEnumerable<string> files, string outputSuffix = "", string outputPath = null) { // Ensure target directory exists. if (string.IsNullOrWhiteSpace(outputPath)) { outputPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); } if (!string.IsNullOrWhiteSpace(outputPath)) { Directory.CreateDirectory(outputPath); } // Create dependency resolve for cecil (needed to write dlls that have other dependencies). var resolver = new DefaultAssemblyResolver(); foreach (var file in files) { if (!File.Exists(file)) { throw new FileNotFoundException("Dll to publicize not found ", file); } resolver.AddSearchDirectory(Path.GetDirectoryName(file)); var outputName = $"{Path.GetFileNameWithoutExtension(file)}{outputSuffix}{Path.GetExtension(file)}"; var outputFile = Path.Combine(outputPath, outputName); Publicize(file, resolver).Write(outputFile); yield return outputFile; } } private static AssemblyDefinition Publicize(string file, BaseAssemblyResolver dllResolver) { var assembly = AssemblyDefinition.ReadAssembly(file, new ReaderParameters { AssemblyResolver = dllResolver }); var allTypes = GetAllTypes(assembly.MainModule).ToList(); var allMethods = allTypes.SelectMany(t => t.Methods); var allFields = FilterBackingEventFields(allTypes); foreach (var type in allTypes) { if (type == null) continue; if (type.IsPublic && type.IsNestedPublic) continue; if (type.IsNested) type.IsNestedPublic = true; else type.IsPublic = true; } foreach (var method in allMethods) { if (!method?.IsPublic ?? false) { method.IsPublic = true; } } foreach (var field in allFields) { if (!field?.IsPublic ?? false) { field.IsPublic = true; } } return assembly; } public static IEnumerable<FieldDefinition> FilterBackingEventFields(IEnumerable<TypeDefinition> allTypes) { var eventNames = allTypes.SelectMany(t => t.Events) .Select(eventDefinition => eventDefinition.Name) .ToList(); return allTypes.SelectMany(x => x.Fields) .Where(fieldDefinition => !eventNames.Contains(fieldDefinition.Name)); } /// <summary> /// Method which returns all Types of the given module, including nested ones (recursively) /// </summary> /// <param name="moduleDefinition"></param> /// <returns></returns> public static IEnumerable<TypeDefinition> GetAllTypes(ModuleDefinition moduleDefinition) => _GetAllNestedTypes(moduleDefinition.Types); //.Reverse(); /// <summary> /// Recursive method to get all nested types. Use <see cref="GetAllTypes(ModuleDefinition)" /> /// </summary> /// <param name="typeDefinitions"></param> /// <returns></returns> private static IEnumerable<TypeDefinition> _GetAllNestedTypes(IEnumerable<TypeDefinition> typeDefinitions) { if (typeDefinitions?.Count() == 0) return new List<TypeDefinition>(); var result = typeDefinitions.Concat(_GetAllNestedTypes(typeDefinitions.SelectMany(t => t.NestedTypes))); return result; } } }
36.669565
128
0.558928
[ "MIT" ]
Measurity/MethodCallCommand-Valheim
BuildTool/Publicizer.cs
4,219
C#
using System; using System.Threading.Tasks; using dev.codingWombat.Vombatidae.business; using dev.codingWombat.Vombatidae.store; using Microsoft.Extensions.Logging; namespace dev.codingWombat.Vombatidae.core { public interface IBurrowUpdater { Task<Burrow> Update(Guid guid, Burrow burrow); } public class BurrowUpdater : IBurrowUpdater { private readonly ILogger<BurrowUpdater> _logger; private readonly ICacheRepository _repository; public BurrowUpdater(ILogger<BurrowUpdater> logger, ICacheRepository repository) { _logger = logger; _repository = repository; } public async Task<Burrow> Update(Guid guid, Burrow burrow) { var existing = await _repository.ReadBurrowAsync(guid); if (existing.Modified != burrow.Modified) { throw new Exception("burrow was already modified"); } burrow.Modified = DateTime.UtcNow; await _repository.WriteBurrowAsync(burrow); _logger.LogDebug("Burrow {} updated with new config.", guid.ToString()); return burrow; } } }
29.738095
89
0.614091
[ "MIT" ]
codingWombat/Vombatidae
dev.codingWombat.Vombatidae.core/BurrowUpdater.cs
1,251
C#
using LeetCode.Attributes; using System; using System.Collections.Generic; using System.Linq; namespace LeetCode.Exercises { [Exercise] public class WordBreakII { public static void Run() { var ex = new WordBreakII(); do { Console.WriteLine("Enter text"); var line = Console.ReadLine(); if (string.IsNullOrEmpty(line)) break; Console.WriteLine("Enter words"); var words = Console.ReadLine(); if (string.IsNullOrEmpty(words)) break; var sentences = ex.WordBreak(line, words.Split(' ')); Console.WriteLine(); foreach (var sentence in sentences) { Console.WriteLine(sentence); } Console.WriteLine(); Console.WriteLine(); } while (true); } public IList<string> WordBreak(string s, IList<string> wordDict) { if (s == null) { throw new ArgumentNullException(); } if (wordDict == null || wordDict.Count == 0) return new String[0]; var words = new HashSet<string>(wordDict); return WordBreak( s, words, new Dictionary<int, IList<string>>(), minLength: words.Select(o => o.Length).Min(), maxLength: words.Select(o => o.Length).Max()); } private IList<string> WordBreak( string s, HashSet<string> words, IDictionary<int, IList<string>> memory, int minLength, int maxLength) { if (s == null) { throw new ArgumentNullException(); } if (s.Length < minLength) { return new String[0]; } if (memory.ContainsKey(s.Length)) { return memory[s.Length]; } var results = new List<string>(); var length = Math.Min(s.Length, maxLength); for (int i = 1; i <= length; i++) { var word = s.Substring(0, i); if (words.Contains(word) == false) { continue; } if (i == s.Length) { results.Add(word); } var sentences = WordBreak(s.Substring(i), words, memory, minLength, maxLength); foreach (var sentence in sentences) { results.Add($"{word} {sentence}"); } } memory.Add(s.Length, results); return results; } } }
24.466667
95
0.43188
[ "MIT" ]
sergioescalera/LeetCode-Exercises
src/LeetCode-Exercises/Exercises/140-WordBreakII.cs
2,938
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace AddressBook.Helpers { class GuiTools { public static void ClearControls(Control ctrl) { if (ctrl is TextBox && ctrl.Text!=string.Empty) { ctrl.Text = String.Empty; } foreach (Control ctrlChild in ctrl.Controls) { ClearControls(ctrlChild); } } public static bool HasBlankControls(Control ctrl,Type type) { if (ctrl is TextBox && ctrl.Text == string.Empty) { return true; } foreach (Control ctrlChild in ctrl.Controls) { if (HasBlankControls(ctrlChild,type)) return true; } return false; } } }
20.891304
67
0.514048
[ "MIT" ]
rcdosado/addressbook
AddressBook/Helpers/GuiTools.cs
963
C#
using System.Windows; using MyMediaRenamer.Gui.ViewModels; using MyMediaRenamer.Gui.Views; namespace MyMediaRenamer.Gui { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { private void App_OnStartup(object sender, StartupEventArgs e) { CommonWindow mainWindow = new CommonWindow { Title = "MyMediaRenamer", Height = 800, MinHeight = 400, Width = 450, MinWidth = 300, DataContext = new MainViewModel() }; mainWindow.Show(); } } }
25.111111
69
0.538348
[ "MIT" ]
alisterpineda/MyMediaRenamer
MyMediaRenamer.Gui/App.xaml.cs
680
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.ServiceModel.Channels; using System.Xml; using System.Xml.Serialization; using BizWTF.Core.Utilities; using BizWTF.Core; using BizWTF.Core.Entities; using BizWTF.Core.Entities.Mocking; namespace BizWTF.Core.Tests.ActionSteps.Messaging { public class SubmitMockMessage2WayStep : ActionStep { protected string _sourceFile; protected string _destURI; protected string _targetContextProperty; public string SourceFile { get { return this._sourceFile; } set { this._sourceFile = value; } } public string SourceResource { get; set; } public string SourceResourceAssembly { get; set; } public string DestURI { get { return this._destURI; } set { this._destURI = value; } } public string TargetContextProperty { get { return this._targetContextProperty; } set { this._targetContextProperty = value; } } public SubmitMockMessage2WayStep() : base() {} public SubmitMockMessage2WayStep(string stepName) : base(stepName) { } public override bool ExecuteStep() { MultipartMessageDefinition tempMsg = null; XmlTextReader xmlBodyReader = null; this.AppendResultDescription(0, "Executing step {0} ({1}):", this.StepName, this.StepType); if (!File.Exists(this.SourceFile) && String.IsNullOrEmpty(this.SourceResource)) { this.AppendResultDescription(1, "File {0} does not exist.", this.SourceFile); this.Result = StepResult.Error; } else if (File.Exists(this.SourceFile)) { //xmlBodyReader = new XmlTextReader(this.SourceFile); tempMsg = MultipartMessageSerializer.RetrieveDocument(this.SourceFile); } else { Assembly asmb = Assembly.Load(this.SourceResourceAssembly); //xmlBodyReader = new XmlTextReader(asmb.GetManifestResourceStream(this.SourceResource)); tempMsg = MultipartMessageSerializer.RetrieveDocument(this.SourceResource, asmb); } if(this.Result != StepResult.Error) { if (!string.IsNullOrEmpty(this.TestID)) { List<ContextProperty> props = tempMsg.PropertyBag.ToList<ContextProperty>(); props.Add(new ContextProperty { Name = BTSProperties.testID.Name.Name, Namespace = BTSProperties.testID.Name.Namespace, Promoted = false, Value = this.TestID }); tempMsg.PropertyBag = props.ToArray(); } XmlDocument doc = MultipartMessageSerializer.Serialize(tempMsg); xmlBodyReader = new XmlTextReader(new StringReader(doc.OuterXml)); BizTalk2WayReference.TwoWayAsyncClient client = new BizTalk2WayReference.TwoWayAsyncClient(); try { client.Endpoint.Address = new System.ServiceModel.EndpointAddress(this.DestURI); client.Open(); Message request = Message.CreateMessage(MessageVersion.Soap11, "Get2WayMultipartMessage", xmlBodyReader); Message response = client.BizTalkSubmit(request); this.AppendResultDescription(1, "[OK] Send file {0}, received response from {1}", this.SourceFile, DestURI); HttpResponseMessageProperty httpResponse = (HttpResponseMessageProperty) response.Properties["httpResponse"]; if (httpResponse.StatusCode != System.Net.HttpStatusCode.InternalServerError) { MemoryStream ms = new MemoryStream(); XmlWriter xw = XmlWriter.Create(ms, new XmlWriterSettings { Indent = true, IndentChars = " ", OmitXmlDeclaration = true }); XmlDictionaryReader bodyReader = response.GetReaderAtBodyContents(); while (bodyReader.NodeType != XmlNodeType.EndElement && bodyReader.LocalName != "Body" && bodyReader.NamespaceURI != "http://schemas.xmlsoap.org/soap/envelope/") { if (bodyReader.NodeType != XmlNodeType.Whitespace) { xw.WriteNode(bodyReader, true); } else { bodyReader.Read(); // ignore whitespace; maintain if you want } } xw.Flush(); XmlSerializer serializer = new XmlSerializer(typeof(MultipartMessageDefinition)); ms.Seek(0, SeekOrigin.Begin); BTSTestContext.AddParam(this.TargetContextProperty, serializer.Deserialize(ms)); } else { MessageFault fault = MessageFault.CreateFault(response, 10000000); string faultString = fault.Reason.ToString(); //XmlDocument faultDoc = new XmlDocument(); //faultDoc.Load(bodyReader); this.AppendResultDescription(1, "[KO] Error when sending file {0} to {1} : {2}", this.SourceFile, DestURI, faultString); this.Result = StepResult.Error; } } catch (Exception exc) { this.AppendResultDescription(1, "[KO] Error when sending file {0} to {1} : {2}", this.SourceFile, DestURI, exc.Message); this.Result = StepResult.Error; } finally { if (client != null) { if (client.State == System.ServiceModel.CommunicationState.Opened) client.Close(); } } } if (this.Result == StepResult.Working) this.Result = StepResult.OK; return (this.Result != StepResult.Error); } protected string processFileName(string sourceFile, string destPattern) { string destFileName = String.Empty; FileInfo fi = new FileInfo(sourceFile); destFileName = destPattern.Replace("%SourceFileName%", fi.Name.Replace(fi.Extension, "")) .Replace("%ShortDate%", DateTime.Now.ToString("yyyyMMdd")) .Replace("%LongDate%", DateTime.Now.ToString("yyyyMMddHHmmss")) .Replace("%Guid%", Guid.NewGuid().ToString()) .Replace("%SourceFileExtension%", fi.Extension); return destFileName; } } }
41.329609
185
0.530684
[ "MIT" ]
MiddleWayGroup/BizWTF
BizWTF.Core/Tests/ActionSteps/Messaging/SubmitMockMessage2WayStep.cs
7,400
C#
using System; using System.Windows; using System.Windows.Data; using System.Windows.Media.Imaging; namespace SIGame.Converters { public sealed class MainBackgroundConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { try { var image = new BitmapImage(); image.BeginInit(); image.CreateOptions = BitmapCreateOptions.IgnoreColorProfile; image.CacheOption = BitmapCacheOption.OnLoad; if (value is string uriString && Uri.TryCreate(uriString, UriKind.Absolute, out Uri uri)) image.UriSource = uri; else image.StreamSource = Application.GetResourceStream(new Uri("/SIGame;component/Theme/main_background.png", UriKind.Relative)).Stream; image.EndInit(); return image; } catch (Exception) { return DependencyProperty.UnsetValue; } } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } }
32.073171
152
0.602281
[ "MIT" ]
wurunduk/SI
src/SIGame/SIGame/Converters/MainBackgroundConverter.cs
1,317
C#
// ============================================================================ // FileName: RecordA.cs // // Description: // // // Author(s): // Alphons van der Heijden // // History: // 28 Mar 2008 Aaron Clauson Added to sipswitch code base based on http://www.codeproject.com/KB/library/DNS.NET_Resolver.aspx. // 14 Oct 2019 Aaron Clauson Synchronised with latest version of source from at https://www.codeproject.com/Articles/23673/DNS-NET-Resolver-C. // // License: // The Code Project Open License (CPOL) https://www.codeproject.com/info/cpol10.aspx // ============================================================================ using System.Net; /* 3.4.1. A RDATA format +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ADDRESS | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ where: ADDRESS A 32 bit Internet address. Hosts that have multiple Internet addresses will have multiple A records. * */ namespace Heijden.DNS { public class RecordA : Record { public System.Net.IPAddress Address; public RecordA(RecordReader rr) { Address = new System.Net.IPAddress(rr.ReadBytes(4)); } public RecordA(IPAddress address) { Address = address; } public override string ToString() { return Address.ToString(); } } }
25.568966
146
0.480782
[ "BSD-3-Clause" ]
SubportBE/sipsorcery
src/net/DNS/Records/RecordA.cs
1,483
C#
using System.Collections.Generic; using System.Threading.Tasks; using Duber.Infrastructure.Repository.Abstractions; namespace Duber.Domain.User.Repository { public interface IUserRepository : IRepository<Model.User> { Model.User GetUser(int userId); Task<IList<Model.User>> GetUsersAsync(); Task<Model.User> GetUserAsync(int userId); void Update(Model.User user); } }
23.166667
62
0.71223
[ "MIT" ]
ahmadezzeir/microservices-dotnetcore-docker-servicefabric
src/Domain/User/Duber.Domain.User/Repository/IUserRepository.cs
419
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics.CodeAnalysis; namespace System.Drawing { using System.Collections.Generic; using System.Diagnostics; using System.Drawing.Imaging; using System.Threading; /// <summary> /// Animates one or more images that have time-based frames. /// See the ImageInfo.cs file for the helper nested ImageInfo class. /// /// A common pattern for using this class is as follows (See PictureBox control): /// 1. The winform app (user's code) calls ImageAnimator.Animate() from the main thread. /// 2. Animate() spawns the animating (worker) thread in the background, which will update the image /// frames and raise the OnFrameChanged event, which handler will be executed in the main thread. /// 3. The main thread triggers a paint event (Invalidate()) from the OnFrameChanged handler. /// 4. From the OnPaint event, the main thread calls ImageAnimator.UpdateFrames() and then paints the /// image (updated frame). /// 5. The main thread calls ImageAnimator.StopAnimate() when needed. This does not kill the worker thread. /// /// Comment on locking the image ref: /// We need to synchronize access to sections of code that modify the image(s), but we don't want to block /// animation of one image when modifying a different one; for this, we use the image ref for locking the /// critical section (lock(image)). /// /// This class is safe for multi-threading but Image is not; multithreaded applications must use a critical /// section lock using the image ref the image access is not from the same thread that executes ImageAnimator /// code. If the user code locks on the image ref forever a deadlock will happen preventing the animation /// from occurring. /// </summary> public sealed partial class ImageAnimator { /// <summary> /// A list of images to be animated. /// </summary> private static List<ImageInfo>? s_imageInfoList; /// <summary> /// A variable to flag when an image or images need to be updated due to the selection of a new frame /// in an image. We don't need to synchronize access to this variable, in the case it is true we don't /// do anything, otherwise the worse case is where a thread attempts to update the image's frame after /// another one did which is harmless. /// </summary> private static bool s_anyFrameDirty; /// <summary> /// The thread used for animating the images. /// </summary> private static Thread? s_animationThread; /// <summary> /// Lock that allows either concurrent read-access to the images list for multiple threads, or write- /// access to it for a single thread. Observe that synchronization access to image objects are done /// with critical sections (lock). /// </summary> private static readonly ReaderWriterLock s_rwImgListLock = new ReaderWriterLock(); /// <summary> /// Flag to avoid a deadlock when waiting on a write-lock and an attempt to acquire a read-lock is /// made in the same thread. If RWLock is currently owned by another thread, the current thread is going to wait on an /// event using CoWaitForMultipleHandles while pumps message. /// The comment above refers to the COM STA message pump, not to be confused with the UI message pump. /// However, the effect is the same, the COM message pump will pump messages and dispatch them to the /// window while waiting on the writer lock; this has the potential of creating a re-entrancy situation /// that if during the message processing a wait on a reader lock is originated the thread will be block /// on itself. /// While processing STA message, the thread may call back into managed code. We do this because /// we can not block finalizer thread. Finalizer thread may need to release STA objects on this thread. If /// the current thread does not pump message, finalizer thread is blocked, and AD unload is blocked while /// waiting for finalizer thread. RWLock is a fair lock. If a thread waits for a writer lock, then it needs /// a reader lock while pumping message, the thread is blocked forever. /// This TLS variable is used to flag the above situation and avoid the deadlock, it is ThreadStatic so each /// thread calling into ImageAnimator is guarded against this problem. /// </summary> [ThreadStatic] private static int t_threadWriterLockWaitCount; /// <summary> /// Prevent instantiation of this class. /// </summary> private ImageAnimator() { } /// <summary> /// Advances the frame in the specified image. The new frame is drawn the next time the image is rendered. /// </summary> public static void UpdateFrames(Image image) { if (image == null || s_imageInfoList == null) { return; } if (t_threadWriterLockWaitCount > 0) { // Cannot acquire reader lock - frame update will be missed. return; } // If the current thread already has the writer lock, no reader lock is acquired. Instead, the lock count on // the writer lock is incremented. It already has a reader lock, the locks ref count will be incremented // w/o placing the request at the end of the reader queue. s_rwImgListLock.AcquireReaderLock(Timeout.Infinite); try { bool foundDirty = false; bool foundImage = false; foreach (ImageInfo imageInfo in s_imageInfoList) { if (imageInfo.Image == image) { if (imageInfo.FrameDirty) { // See comment in the class header about locking the image ref. lock (imageInfo.Image) { imageInfo.UpdateFrame(); } } foundImage = true; } else if (imageInfo.FrameDirty) { foundDirty = true; } if (foundDirty && foundImage) { break; } } s_anyFrameDirty = foundDirty; } finally { s_rwImgListLock.ReleaseReaderLock(); } } /// <summary> /// Advances the frame in all images currently being animated. The new frame is drawn the next time the image is rendered. /// </summary> public static void UpdateFrames() { if (!s_anyFrameDirty || s_imageInfoList == null) { return; } if (t_threadWriterLockWaitCount > 0) { // Cannot acquire reader lock at this time, frames update will be missed. return; } s_rwImgListLock.AcquireReaderLock(Timeout.Infinite); try { foreach (ImageInfo imageInfo in s_imageInfoList) { // See comment in the class header about locking the image ref. lock (imageInfo.Image) { imageInfo.UpdateFrame(); } } s_anyFrameDirty = false; } finally { s_rwImgListLock.ReleaseReaderLock(); } } /// <summary> /// Adds an image to the image manager. If the image does not support animation this method does nothing. /// This method creates the image list and spawns the animation thread the first time it is called. /// </summary> public static void Animate(Image image, EventHandler onFrameChangedHandler) { if (image == null) { return; } ImageInfo? imageInfo = null; // See comment in the class header about locking the image ref. lock (image) { // could we avoid creating an ImageInfo object if FrameCount == 1 ? imageInfo = new ImageInfo(image); } // If the image is already animating, stop animating it StopAnimate(image, onFrameChangedHandler); // Acquire a writer lock to modify the image info list. If the thread has a reader lock we need to upgrade // it to a writer lock; acquiring a reader lock in this case would block the thread on itself. // If the thread already has a writer lock its ref count will be incremented w/o placing the request in the // writer queue. See ReaderWriterLock.AcquireWriterLock method in the MSDN. bool readerLockHeld = s_rwImgListLock.IsReaderLockHeld; LockCookie lockDowngradeCookie = default; t_threadWriterLockWaitCount++; try { if (readerLockHeld) { lockDowngradeCookie = s_rwImgListLock.UpgradeToWriterLock(Timeout.Infinite); } else { s_rwImgListLock.AcquireWriterLock(Timeout.Infinite); } } finally { t_threadWriterLockWaitCount--; Debug.Assert(t_threadWriterLockWaitCount >= 0, "threadWriterLockWaitCount less than zero."); } try { if (imageInfo.Animated) { // Construct the image array // if (s_imageInfoList == null) { s_imageInfoList = new List<ImageInfo>(); } // Add the new image // imageInfo.FrameChangedHandler = onFrameChangedHandler; s_imageInfoList.Add(imageInfo); // Construct a new timer thread if we haven't already // if (s_animationThread == null) { s_animationThread = new Thread(new ThreadStart(AnimateImages)); s_animationThread.Name = nameof(ImageAnimator); s_animationThread.IsBackground = true; s_animationThread.Start(); } } } finally { if (readerLockHeld) { s_rwImgListLock.DowngradeFromWriterLock(ref lockDowngradeCookie); } else { s_rwImgListLock.ReleaseWriterLock(); } } } /// <summary> /// Whether or not the image has multiple time-based frames. /// </summary> public static bool CanAnimate([NotNullWhen(true)] Image? image) { if (image == null) { return false; } // See comment in the class header about locking the image ref. lock (image) { Guid[] dimensions = image.FrameDimensionsList; foreach (Guid guid in dimensions) { FrameDimension dimension = new FrameDimension(guid); if (dimension.Equals(FrameDimension.Time)) { return image.GetFrameCount(FrameDimension.Time) > 1; } } } return false; } /// <summary> /// Removes an image from the image manager so it is no longer animated. /// </summary> public static void StopAnimate(Image image, EventHandler onFrameChangedHandler) { // Make sure we have a list of images if (image == null || s_imageInfoList == null) { return; } // Acquire a writer lock to modify the image info list - See comments on Animate() about this locking. bool readerLockHeld = s_rwImgListLock.IsReaderLockHeld; LockCookie lockDowngradeCookie = default; t_threadWriterLockWaitCount++; try { if (readerLockHeld) { lockDowngradeCookie = s_rwImgListLock.UpgradeToWriterLock(Timeout.Infinite); } else { s_rwImgListLock.AcquireWriterLock(Timeout.Infinite); } } finally { t_threadWriterLockWaitCount--; Debug.Assert(t_threadWriterLockWaitCount >= 0, "threadWriterLockWaitCount less than zero."); } try { // Find the corresponding reference and remove it for (int i = 0; i < s_imageInfoList.Count; i++) { ImageInfo imageInfo = s_imageInfoList[i]; if (image == imageInfo.Image) { if ((onFrameChangedHandler == imageInfo.FrameChangedHandler) || (onFrameChangedHandler != null && onFrameChangedHandler.Equals(imageInfo.FrameChangedHandler))) { s_imageInfoList.Remove(imageInfo); } break; } } } finally { if (readerLockHeld) { s_rwImgListLock.DowngradeFromWriterLock(ref lockDowngradeCookie); } else { s_rwImgListLock.ReleaseWriterLock(); } } } /// <summary> /// Worker thread procedure which implements the main animation loop. /// NOTE: This is the ONLY code the worker thread executes, keeping it in one method helps better understand /// any synchronization issues. /// WARNING: Also, this is the only place where ImageInfo objects (not the contained image object) are modified, /// so no access synchronization is required to modify them. /// </summary> private static void AnimateImages() { Debug.Assert(s_imageInfoList != null, "Null images list"); Stopwatch stopwatch = Stopwatch.StartNew(); while (true) { Thread.Sleep(40); // Because Thread.Sleep is not accurate, capture how much time has actually elapsed during the animation long timeElapsed = stopwatch.ElapsedMilliseconds; stopwatch.Restart(); // Acquire reader-lock to access imageInfoList, elements in the list can be modified w/o needing a writer-lock. // Observe that we don't need to check if the thread is waiting or a writer lock here since the thread this // method runs in never acquires a writer lock. s_rwImgListLock.AcquireReaderLock(Timeout.Infinite); try { for (int i = 0; i < s_imageInfoList.Count; i++) { ImageInfo imageInfo = s_imageInfoList[i]; if (imageInfo.Animated) { imageInfo.AdvanceAnimationBy(timeElapsed); if (imageInfo.FrameDirty) { s_anyFrameDirty = true; } } } } finally { s_rwImgListLock.ReleaseReaderLock(); } } } } }
39.632941
183
0.527606
[ "MIT" ]
Alex-ABPerson/runtime
src/libraries/System.Drawing.Common/src/System/Drawing/ImageAnimator.cs
16,844
C#
// ========================================================================== // Notifo.io // ========================================================================== // Copyright (c) Sebastian Stehle // All rights reserved. Licensed under the MIT license. // ========================================================================== using System.Text.Json.Serialization; using Notifo.Domain.UserNotifications; using Notifo.Infrastructure.Reflection; namespace Notifo.Domain.Channels.WebPush { public sealed class WebPushPayload { [JsonPropertyName("id")] public Guid Id { get; set; } [JsonPropertyName("cu")] public string? ConfirmUrl { get; set; } [JsonPropertyName("ct")] public string? ConfirmText { get; set; } [JsonPropertyName("is")] public string? ImageSmall { get; set; } [JsonPropertyName("il")] public string? ImageLarge { get; set; } [JsonPropertyName("lt")] public string? LinkText { get; set; } [JsonPropertyName("lu")] public string? LinkUrl { get; set; } [JsonPropertyName("td")] public string? TrackDeliveredUrl { get; set; } [JsonPropertyName("ts")] public string? TrackSeenUrl { get; set; } [JsonPropertyName("ci")] public bool IsConfirmed { get; set; } [JsonPropertyName("ns")] public string Subject { get; set; } [JsonPropertyName("nb")] public string? Body { get; set; } public static WebPushPayload Create(UserNotification notification, string endpoint) { var result = new WebPushPayload(); SimpleMapper.Map(notification, result); SimpleMapper.Map(notification.Formatting, result); result.IsConfirmed = notification.FirstConfirmed != null; result.ConfirmText = notification.Formatting.ConfirmText; result.ConfirmUrl = notification.ComputeConfirmUrl(Providers.WebPush, endpoint); result.TrackDeliveredUrl = notification.ComputeTrackDeliveredUrl(Providers.WebPush, endpoint); result.TrackSeenUrl = notification.ComputeTrackSeenUrl(Providers.WebPush, endpoint); return result; } } }
31.901408
106
0.569978
[ "MIT" ]
anhgeeky/notifo
backend/src/Notifo.Domain/Channels/WebPush/WebPushPayload.cs
2,267
C#
using System.Collections.Generic; using System.IO.Abstractions; using Raven.Abstractions.Data; using Raven.Abstractions.FileSystem; using Raven.Assure.ResourceDocument; using Xunit; namespace Raven.Assure.Test.ResourceDocument { public class FileSystemDocumentServiceTests { public class TryRemoveEncryptionKey { public class WhenGivenAValidDocument { public class ThatHasAnEncryptionKey { [Fact] public void ShouldRemoveEncryptionKey() { var resourceDocumentService = new FileSystemDocumentService(new FileSystem()); var encryptedDatabaseDocument = new FileSystemDocument { Id = "WestOfWesteros", SecuredSettings = new Dictionary<string, string>() { { "Raven/Encryption/Key", "asdf" }, { "Raven/Encryption/EncryptIndexes", "True" } } }; var documentUpdate = resourceDocumentService.TryRemoveEncryptionKey(encryptedDatabaseDocument); Assert.True(documentUpdate.Updated, "It should have set the status to updated."); Assert.Equal(encryptedDatabaseDocument.Id, documentUpdate.Document.Id); Assert.Null(documentUpdate.Document.SecuredSettings["Raven/Encryption/Key"]); } } public class WithoutAnEncryptionKey { [Fact] public void ShouldReturnSameDocument() { var resourceDocumentService = new FileSystemDocumentService(new FileSystem()); var originalDatabaseDocument = new FileSystemDocument { Id = "TheValeOfArryn" }; var documentUpdate = resourceDocumentService.TryRemoveEncryptionKey(originalDatabaseDocument); Assert.False(documentUpdate.Updated, "It should not have set the status to updated."); Assert.Equal(originalDatabaseDocument, documentUpdate.Document); } } } } } }
36.322581
113
0.573712
[ "MIT" ]
absynce/Raven.Assure
test/Raven.Assure.Test/ResourceDocument/FileSystemDocumentServiceTests.cs
2,254
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NnCase.Designer.Modules.MainMenu.Models; namespace NnCase.Designer.Modules.MainMenu.ViewModels { public class MainMenuViewModel : MenuModel { private readonly IMenuBuilder _menuBuilder; public MainMenuViewModel(IMenuBuilder menuBuilder) { _menuBuilder = menuBuilder; _menuBuilder.BuildMenuBar(MenuDefinictions.MainMenuBar, this); } } }
25.190476
74
0.724008
[ "Apache-2.0" ]
svija/nncase
src/NnCase.Designer.Shell/Modules/MainMenu/ViewModels/MainMenuViewModel.cs
531
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information.  namespace System.Windows.Shell { using System; using System.Diagnostics; using System.Windows; using System.Windows.Input; using System.Windows.Media; public sealed class ThumbButtonInfo : Freezable, ICommandSource { protected override Freezable CreateInstanceCore() { return new ThumbButtonInfo(); } #region Dependency Properties and support methods public static readonly DependencyProperty VisibilityProperty = DependencyProperty.Register( "Visibility", typeof(Visibility), typeof(ThumbButtonInfo), new PropertyMetadata(Visibility.Visible)); /// <summary> /// Gets or sets the whether this should be visible in the UI. /// </summary> public Visibility Visibility { get { return (Visibility)GetValue(VisibilityProperty); } set { SetValue(VisibilityProperty, value); } } public static readonly DependencyProperty DismissWhenClickedProperty = DependencyProperty.Register( "DismissWhenClicked", typeof(bool), typeof(ThumbButtonInfo), new PropertyMetadata(false)); /// <summary> /// Gets or sets the DismissWhenClicked property. This dependency property /// indicates whether the thumbnail window should disappear as a result /// of the user clicking this button. /// </summary> public bool DismissWhenClicked { get { return (bool)GetValue(DismissWhenClickedProperty); } set { SetValue(DismissWhenClickedProperty, value); } } public static readonly DependencyProperty ImageSourceProperty = DependencyProperty.Register( "ImageSource", typeof(ImageSource), typeof(ThumbButtonInfo), new PropertyMetadata(null)); /// <summary> /// Gets or sets the ImageSource property. This dependency property /// indicates the ImageSource to use for this button's display. /// </summary> public ImageSource ImageSource { get { return (ImageSource)GetValue(ImageSourceProperty); } set { SetValue(ImageSourceProperty, value); } } public static readonly DependencyProperty IsBackgroundVisibleProperty = DependencyProperty.Register( "IsBackgroundVisible", typeof(bool), typeof(ThumbButtonInfo), new PropertyMetadata(true)); /// <summary> /// Gets or sets the IsBackgroundVisible property. This dependency property /// indicates whether the default background should be shown. /// </summary> public bool IsBackgroundVisible { get { return (bool)GetValue(IsBackgroundVisibleProperty); } set { SetValue(IsBackgroundVisibleProperty, value); } } public static readonly DependencyProperty DescriptionProperty = DependencyProperty.Register( "Description", typeof(string), typeof(ThumbButtonInfo), new PropertyMetadata( string.Empty, null, CoerceDescription)); /// <summary> /// Gets or sets the Description property. This dependency property /// indicates the text to display in the tooltip for this button. /// </summary> public string Description { get { return (string)GetValue(DescriptionProperty); } set { SetValue(DescriptionProperty, value); } } // The THUMBBUTTON struct has a hard-coded length for this field of 260. private static object CoerceDescription(DependencyObject d, object value) { var text = (string)value; if (text != null && text.Length >= 260) { // Account for the NULL in native LPWSTRs text = text.Substring(0, 259); } return text; } public static readonly DependencyProperty IsEnabledProperty = DependencyProperty.Register( "IsEnabled", typeof(bool), typeof(ThumbButtonInfo), new PropertyMetadata( true, null, (d, e) => ((ThumbButtonInfo)d).CoerceIsEnabledValue(e))); private object CoerceIsEnabledValue(object value) { var enabled = (bool)value; return enabled && CanExecute; } /// <summary> /// Gets or sets the IsEnabled property. /// </summary> /// <remarks> /// This dependency property /// indicates whether the button is receptive to user interaction and /// should appear as such. The button will not raise click events from /// the user when this property is false. /// See also IsInteractive. /// </remarks> public bool IsEnabled { get { return (bool)GetValue(IsEnabledProperty); } set { SetValue(IsEnabledProperty, value); } } public static readonly DependencyProperty IsInteractiveProperty = DependencyProperty.Register( "IsInteractive", typeof(bool), typeof(ThumbButtonInfo), new PropertyMetadata(true)); /// <summary> /// Gets or sets the IsInteractive property. /// </summary> /// <remarks> /// This dependency property allows an enabled button, as determined /// by the IsEnabled property, to not raise click events. Buttons that /// have IsInteractive=false can be used to indicate status. /// IsEnabled=false takes precedence over IsInteractive=false. /// </remarks> public bool IsInteractive { get { return (bool)GetValue(IsInteractiveProperty); } set { SetValue(IsInteractiveProperty, value); } } public static readonly DependencyProperty CommandProperty = DependencyProperty.Register( "Command", typeof(ICommand), typeof(ThumbButtonInfo), new PropertyMetadata( null, (d, e) => ((ThumbButtonInfo)d).OnCommandChanged(e))); private void OnCommandChanged(DependencyPropertyChangedEventArgs e) { var oldCommand = (ICommand)e.OldValue; var newCommand = (ICommand)e.NewValue; if (oldCommand == newCommand) { return; } if (oldCommand != null) { UnhookCommand(oldCommand); } if (newCommand != null) { HookCommand(newCommand); } } /// <summary> /// CommandParameter Dependency Property /// </summary> public static readonly DependencyProperty CommandParameterProperty = DependencyProperty.Register( "CommandParameter", typeof(object), typeof(ThumbButtonInfo), new PropertyMetadata( null, (d, e) => ((ThumbButtonInfo)d).UpdateCanExecute())); // .Net property deferred to ICommandSource region. /// <summary> /// CommandTarget Dependency Property /// </summary> public static readonly DependencyProperty CommandTargetProperty = DependencyProperty.Register( "CommandTarget", typeof(IInputElement), typeof(ThumbButtonInfo), new PropertyMetadata( null, (d, e) => ((ThumbButtonInfo)d).UpdateCanExecute())); // .Net property deferred to ICommandSource region. private static readonly DependencyProperty _CanExecuteProperty = DependencyProperty.Register( "_CanExecute", typeof(bool), typeof(ThumbButtonInfo), new PropertyMetadata( true, (d, e) => d.CoerceValue(IsEnabledProperty))); private bool CanExecute { get { return (bool)GetValue(_CanExecuteProperty); } set { SetValue(_CanExecuteProperty, value); } } #endregion public event EventHandler Click; internal void InvokeClick() { EventHandler local = Click; if (local != null) { local(this, EventArgs.Empty); } _InvokeCommand(); } private void _InvokeCommand() { ICommand command = Command; if (command != null) { object parameter = CommandParameter; IInputElement target = CommandTarget; RoutedCommand routedCommand = command as RoutedCommand; if (routedCommand != null) { if (routedCommand.CanExecute(parameter, target)) { routedCommand.Execute(parameter, target); } } else if (command.CanExecute(parameter)) { command.Execute(parameter); } } } private void UnhookCommand(ICommand command) { Debug.Assert(command != null); CanExecuteChangedEventManager.RemoveHandler(command, OnCanExecuteChanged); UpdateCanExecute(); } private void HookCommand(ICommand command) { CanExecuteChangedEventManager.AddHandler(command, OnCanExecuteChanged); UpdateCanExecute(); } private void OnCanExecuteChanged(object sender, EventArgs e) { UpdateCanExecute(); } private void UpdateCanExecute() { if (Command != null) { object parameter = CommandParameter; IInputElement target = CommandTarget; RoutedCommand routed = Command as RoutedCommand; if (routed != null) { CanExecute = routed.CanExecute(parameter, target); } else { CanExecute = Command.CanExecute(parameter); } } else { CanExecute = true; } } #region ICommandSource Members public ICommand Command { get { return (ICommand)GetValue(CommandProperty); } set { SetValue(CommandProperty, value); } } public object CommandParameter { get { return (object)GetValue(CommandParameterProperty); } set { SetValue(CommandParameterProperty, value); } } public IInputElement CommandTarget { get { return (IInputElement)GetValue(CommandTargetProperty); } set { SetValue(CommandTargetProperty, value); } } #endregion } }
33.087464
108
0.563662
[ "MIT" ]
00mjk/wpf
src/Microsoft.DotNet.Wpf/src/PresentationFramework/System/Windows/Shell/ThumbButtonInfo.cs
11,351
C#
using System.Collections.Generic; namespace ScrabbleScorer.Models { public class ScrabbleChecker { public string Word { get;set; } public static Dictionary<char, int> ScoreDictionary = new Dictionary<char, int>() { {'A', 1}, {'E', 1}, {'I', 1}, {'O', 1}, {'U', 1}, {'L', 1}, {'N', 1}, {'R', 1}, {'S', 1}, {'T', 1}, {'D', 2}, {'G', 2}, {'B', 3}, {'C', 3}, {'M', 3}, {'P', 3}, {'F', 4}, {'H', 4}, {'V', 4}, {'W', 4}, {'Y', 4}, {'K', 5}, {'J', 8}, {'X', 8}, {'Q', 10}, {'Z', 10} }; public ScrabbleChecker(string word) { Word = word; } public int CalculateScore() { string temp = Word.ToUpper(); int score = 0; foreach (char c in temp) { score += ScoreDictionary[c]; } return score; } } }
18.294118
87
0.392283
[ "MIT" ]
Patrick-Dolan/scrabble-scorer
ScrabbleScorer.Solution/ScrabbleScorer/Models/ScrabbleChecker.cs
933
C#
#region using System.Data.Entity; using System.Diagnostics; using Iam.Common; using Iam.Common.Contracts; using Iam.Identity; using Iam.Web.Migrations.Clients; using Iam.Web.Migrations.Scopes; using Iam.Web.Migrations.TenantMappings; using IdentityServer3.Core.Configuration; using IdentityServer3.Core.Services; using IdentityServer3.EntityFramework; using JetBrains.Annotations; using Owin; #endregion namespace Iam.Web.Services { [UsedImplicitly] public static class Configurations { private static bool _debug; static Configurations() { SetDebugFlag(); } [Conditional("DEBUG")] private static void SetDebugFlag() { _debug = true; } /// <summary> /// Enable migrations. /// </summary> /// <param name="app"></param> /// <param name="connectionString"></param> /// <returns></returns> public static IAppBuilder UseMigrations(this IAppBuilder app, string connectionString) { Database.SetInitializer( new MigrateDatabaseToLatestVersion<ScopeConfigurationDbContext, ScopeMigration>(connectionString)); Database.SetInitializer( new MigrateDatabaseToLatestVersion<ClientConfigurationDbContext, ClientMigration>(connectionString)); Database.SetInitializer( new MigrateDatabaseToLatestVersion<AdminContext, TenantMappingMigration>(connectionString)); return app; } /// <summary> /// Configure ID Server to use a custom view service, EF and ASP.NET Identity. /// </summary> /// <param name="factory"></param> /// <returns></returns> public static IdentityServerServiceFactory Configure( this IdentityServerServiceFactory factory) { if (_debug) { factory.Register(new Registration<ICache, NoCache>()); } else { factory.Register(new Registration<ICache, HttpCache>()); } factory.Register(new Registration<IBundle, Bundle>()); factory.Register(new Registration<IAdminContext, AdminContext>()); factory.Register(new Registration<TenantService>()); factory.CustomRequestValidator = new Registration<ICustomRequestValidator, CustomRequestValidator>(); factory.ViewService = new Registration<IViewService, CustomViewService>(); return factory.RegisterIdentityServices().RegisterUserServices(); } private static IdentityServerServiceFactory RegisterIdentityServices( this IdentityServerServiceFactory factory) { var option = new EntityFrameworkServiceOptions {ConnectionString = AppSettings.IdsConnectionString}; factory.RegisterOperationalServices(option); factory.RegisterConfigurationServices(option); return factory; } private static IdentityServerServiceFactory RegisterUserServices( this IdentityServerServiceFactory factory) { factory.UserService = new Registration<IUserService, UserService>(); factory.Register(new Registration<IamContext>()); factory.Register(new Registration<IamUserStore>()); factory.Register(new Registration<IamUserManager>()); return factory; } } }
32.803738
117
0.641026
[ "Apache-2.0" ]
HTT323/IAM
source/Iam/Iam.Web/Services/Configurations.cs
3,512
C#
using System; using System.Runtime.InteropServices; namespace Vlc.DotNet.Core.Interops.Signatures { /// <summary> /// Get id name of device. /// </summary> [LibVlcFunction("libvlc_audio_output_device_id")] [UnmanagedFunctionPointer(CallingConvention.Cdecl)] [Obsolete("Use GetAudioOutputDeviceList instead")] internal delegate IntPtr GetAudioOutputDeviceName(IntPtr instance, Utf8StringHandle audioOutputName, int deviceIndex); }
32.928571
122
0.761388
[ "MIT" ]
CrookedFingerGuy/Vlc.DotNet
src/Vlc.DotNet.Core.Interops/Signatures/libvlc_media_player.h/libvlc_audio_output_device_id.cs
463
C#
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.IO; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Input; using JetBrains.Annotations; using Newtonsoft.Json.Linq; using Ookii.Dialogs.Wpf; using Syncfusion.UI.Xaml.Grid; namespace SeriLogViewer { public sealed class MainWindowModel : INotifyPropertyChanged { private readonly SfDataGrid _grid; private ObservableCollection<dynamic> _entrys = new(); private int _isLoading; public MainWindowModel(SfDataGrid grid) { _grid = grid; OpenCommand = new SimpleCommand(() => _isLoading == 0, TryLoad); } public ICommand OpenCommand { get; } public ObservableCollection<dynamic> Entrys { get => _entrys; set { if (Equals(value, _entrys)) return; _entrys = value; OnPropertyChanged(); } } public event PropertyChangedEventHandler? PropertyChanged; private void TryLoad() { var diag = new VistaOpenFileDialog(); if (diag.ShowDialog(Application.Current.MainWindow) != true) return; #pragma warning disable EPC13 Task.Run(() => Load(diag.FileName)); #pragma warning restore EPC13 } private void Load(string file) { try { Application.Current.Dispatcher.Invoke(() => Entrys.Clear()); List<dynamic> entrys = new(); Interlocked.Exchange(ref _isLoading, 1); using var reader = new StreamReader(file); string? line; while ((line = reader.ReadLine()) != null) { dynamic target = JToken.Parse(line); ReconstructMessage(target); entrys.Add(target); } Application.Current.Dispatcher.Invoke( () => { foreach (dynamic entry in entrys) Entrys.Add(entry); _grid.GridColumnSizer.ResetAutoCalculationforAllColumns(); _grid.GridColumnSizer.Refresh(); }); } catch (Exception e) { MessageBox.Show(e.ToString()); } finally { Interlocked.Exchange(ref _isLoading, 0); } } private static void ReconstructMessage(JToken obj) { try { string msg = obj["@mt"]?.Value<string>() ?? string.Empty; var prov = obj; foreach (var match in FindComponent(msg)) msg = msg.Replace(match, prov[match[1..^1]]?.ToString() ?? string.Empty); obj["@mt"] = JToken.FromObject(msg); } catch { // ignored #pragma warning disable ERP022 } #pragma warning restore ERP022 } private static IEnumerable<string> FindComponent(string msg) { var target = msg; var isIn = false; var start = 0; for (var i = 0; i < msg.Length; i++) if (isIn && target[i] == '}') { isIn = false; yield return target[start..(i + 1)]; } else if (!isIn && msg[i] == '{') { isIn = true; start = i; } } [NotifyPropertyChangedInvocator] private void OnPropertyChanged([CallerMemberName] string propertyName = null!) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } }
28.716312
93
0.504075
[ "MIT" ]
Tauron1990/Project-Manager-Akka
Src/Apps/DevTools/SeriLogViewer/MainWindowModel.cs
4,051
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; public class CarManager { private Dictionary<int, Car> cars; private Dictionary<int, Race> races; private Garage garage; private List<int> closedRaces; public CarManager() { this.cars = new Dictionary<int, Car>(); this.races = new Dictionary<int, Race>(); this.garage = new Garage(); this.closedRaces = new List<int>(); } public void Register(int id, string type, string brand, string model, int yearOfProduction, int horsepower, int acceleration, int suspension, int durability) { if (type == "Performance") { this.cars.Add(id, new PerformanceCar(brand, model,yearOfProduction,horsepower,acceleration,suspension,durability)); } else { this.cars.Add(id, new ShowCar(brand, model, yearOfProduction, horsepower, acceleration, suspension,durability)); } } public string Check(int id) { return cars[id].ToString(); } public void Open(int id, string type, int length, string route, int prizePool) { switch (type) { case "Casual": this.races.Add(id, new CasualRace(length,route,prizePool)); break; case "Drag": this.races.Add(id, new DragRace(length, route, prizePool)); break; case "Drift": this.races.Add(id, new DriftRace(length, route, prizePool)); break; } } public void Participate(int carId, int raceId) { if (!garage.ParkedCars.Contains(carId)) { if (!closedRaces.Contains(raceId)) { this.races[raceId].Participants.Add(carId, cars[carId]); } } } public string Start(int id) { if (races[id].Participants.Count == 0) { return "Cannot start the race with zero participants."; } var result = races[id].StartRace(); closedRaces.Add(id); return result; } public void Park(int id) { foreach (var race in races.Where(r => !closedRaces.Contains(r.Key))) { if (race.Value.Participants.ContainsKey(id)) { return; } } this.garage.AddCar(id); } public void Unpark(int id) { this.garage.RemoveCar(id); } public void Tune(int tuneIndex, string addOn) { foreach (var id in garage.ParkedCars) { cars[id].Tune(tuneIndex, addOn); } } }
25.771429
161
0.558389
[ "MIT" ]
vasilchavdarov/SoftUniHomework
Exam Preparation OOPBasic/Exam Preparation OOPBasic/Cors/CarManager.cs
2,708
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Diagnostics; namespace Microsoft.CodeAnalysis.CodeActions { #pragma warning disable CA1200 // Avoid using cref tags with a prefix internal enum CodeActionRequestPriority { /// <summary> /// No priority specified, all refactoring, code fixes, and analyzers should be run. This is equivalent /// to <see cref="Normal"/> and <see cref="High"/> combined. /// </summary> None = 0, /// <summary> /// Only normal priority refactoring, code fix providers should be run. Specifically, /// providers will be run when <see cref="T:CodeRefactoringProvider.RequestPriority"/> or /// <see cref="T:CodeFixProvider.RequestPriority"/> is <see cref="Normal"/>. <see cref="DiagnosticAnalyzer"/>s /// will be run except for <see cref="DiagnosticAnalyzerExtensions.IsCompilerAnalyzer"/>. /// </summary> Normal = 1, /// <summary> /// Only high priority refactoring, code fix providers should be run. Specifically, /// providers will be run when <see cref="T:CodeRefactoringProvider.RequestPriority"/> or /// <see cref="T:CodeFixProvider.RequestPriority"/> is <see cref="Normal"/>. /// The <see cref="DiagnosticAnalyzerExtensions.IsCompilerAnalyzer"/> <see cref="DiagnosticAnalyzer"/> /// will be run. /// </summary> High = 2, } }
46.285714
119
0.660494
[ "MIT" ]
AlFasGD/roslyn
src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/CodeActions/CodeActionRequestPriority.cs
1,622
C#
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; using FeatureFlags.APIs.Controllers.Base; using FeatureFlags.APIs.Models; using FeatureFlags.APIs.Services; using FeatureFlags.APIs.ViewModels.Project; using Microsoft.AspNetCore.Mvc; namespace FeatureFlags.APIs.Controllers { [ApiVersion("2.0")] [Route("api/v{version:apiVersion}/envs/{envId:int}/settings")] public class EnvironmentSettingV2Controller : ApiControllerBase { private readonly EnvironmentSettingV2Service _service; public EnvironmentSettingV2Controller(EnvironmentSettingV2Service service) { _service = service; } [HttpGet] public async Task<IEnumerable<EnvironmentSettingV2>> GetSettingAsync( int envId, [Required(AllowEmptyStrings = false)] string type) { var settings = await _service.GetAsync(envId, type); return settings; } [HttpPost] public async Task<IEnumerable<EnvironmentSettingV2>> UpsertSettingAsync( int envId, IEnumerable<UpsertEnvironmentSetting> payload) { var settings = payload.Select(x => x.NewSetting()); var updatedSettings = await _service.UpsertAsync(envId, settings); return updatedSettings; } [HttpDelete] public async Task<IEnumerable<EnvironmentSettingV2>> DeleteSettingAsync( int envId, [Required(AllowEmptyStrings = false)] string settingId) { var updatedSettings = await _service.DeleteAsync(envId, settingId); return updatedSettings; } } }
33.339623
82
0.657612
[ "Apache-2.0" ]
thunderstroke325/feature-flags-co
FeatureFlagsCo.APIs/FeatureFlags.APIs/Controllers/EnvironmentSettingV2Controller.cs
1,767
C#
using System; using System.Collections.Generic; using System.Linq; namespace BirthdayCelebration { class Program { static List<IBirthable> birthed = new List<IBirthable>(); static void Main(string[] args) { while (true) { var input = Console.ReadLine().Split(' ').ToArray(); string prior = input[0]; if (prior == "End") { break; } switch (prior) { case "Citizen": CreateCitizen(input); break; case "Robot": CreateRobot(input); break; case "Pet": CreatePet(input); break; } } string dateToSearch = Console.ReadLine(); foreach (var item in birthed) { string year = item.BirthDate.ToString().Split('/')[2]; if (year == dateToSearch) { Console.WriteLine(item.BirthDate); } } } private static void CreatePet(string[] input) { string name = input[1]; string birthDate = input[2]; Pet pet = new Pet(name, birthDate); birthed.Add(pet); } private static void CreateRobot(string[] input) { string name = input[1]; string id = input[2]; Robot robot = new Robot(id, name); } private static void CreateCitizen(string[] input) { string name = input[1]; int age = int.Parse(input[2]); string id = input[3]; string birthDate = input[4]; Citizen citizen = new Citizen(id, birthDate, name, age); birthed.Add(citizen); } } }
26.773333
70
0.426295
[ "MIT" ]
grekssi/Softuni-Courses
SoftUni/01. .NET Courses/04. C# OOP/04. Interfaces and Abstraction/Exercise/06. Birthday Celebrations/Program.cs
2,010
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. namespace Microsoft.Bot.Schema { using System; using Newtonsoft.Json; /// <summary> /// An update to a payment request. /// </summary> [Obsolete("Bot Framework no longer supports payments.")] public partial class PaymentRequestUpdate { /// <summary> /// Initializes a new instance of the <see cref="PaymentRequestUpdate"/> class. /// </summary> public PaymentRequestUpdate() { CustomInit(); } /// <summary> /// Initializes a new instance of the <see cref="PaymentRequestUpdate"/> class. /// </summary> /// <param name="id">ID for the payment request to update.</param> /// <param name="details">Update payment details.</param> /// <param name="shippingAddress">Updated shipping address.</param> /// <param name="shippingOption">Updated shipping options.</param> public PaymentRequestUpdate(string id = default, PaymentDetails details = default, PaymentAddress shippingAddress = default, string shippingOption = default) { Id = id; Details = details; ShippingAddress = shippingAddress; ShippingOption = shippingOption; CustomInit(); } /// <summary> /// Gets or sets ID for the payment request to update. /// </summary> /// <value>The ID for the payment request to update.</value> [JsonProperty(PropertyName = "id")] public string Id { get; set; } /// <summary> /// Gets or sets update payment details. /// </summary> /// <value>The update payment details.</value> [JsonProperty(PropertyName = "details")] public PaymentDetails Details { get; set; } /// <summary> /// Gets or sets updated shipping address. /// </summary> /// <value>The updated shipping address.</value> [JsonProperty(PropertyName = "shippingAddress")] public PaymentAddress ShippingAddress { get; set; } /// <summary> /// Gets or sets updated shipping options. /// </summary> /// <value>The updated shipping options.</value> [JsonProperty(PropertyName = "shippingOption")] public string ShippingOption { get; set; } /// <summary> /// An initialization method that performs custom operations like setting defaults. /// </summary> partial void CustomInit(); } }
35.493151
165
0.594751
[ "MIT" ]
Arsh-Kashyap/botbuilder-dotnet
libraries/Microsoft.Bot.Schema/PaymentRequestUpdate.cs
2,593
C#
using System.Linq; using System.Threading.Tasks; using AElf.Contracts.TestKit; using AElf.CSharp.Core.Extension; using AElf.Kernel; using AElf.Sdk.CSharp; using AElf.Types; using Shouldly; using Xunit; namespace AElf.Contracts.Vote { public partial class VoteTests { [Fact] public async Task VoteContract_Register_Again_Test() { var votingItem = await RegisterVotingItemAsync(10, 4, true, DefaultSender, 10); var transactionResult = (await VoteContractStub.Register.SendWithExceptionAsync(new VotingRegisterInput { // Basically same as previous one. TotalSnapshotNumber = votingItem.TotalSnapshotNumber, StartTimestamp = votingItem.StartTimestamp, EndTimestamp = votingItem.EndTimestamp, Options = {votingItem.Options}, AcceptedCurrency = votingItem.AcceptedCurrency, IsLockToken = votingItem.IsLockToken })).TransactionResult; transactionResult.Status.ShouldBe(TransactionResultStatus.Failed); transactionResult.Error.ShouldContain("Voting item already exists"); } [Fact] public async Task VoteContract_Register_CurrencyNotSupportVoting_Test() { var startTime = TimestampHelper.GetUtcNow(); var input = new VotingRegisterInput { TotalSnapshotNumber = 5, EndTimestamp = startTime.AddDays(100), StartTimestamp = startTime, Options = { GenerateOptions(3) }, AcceptedCurrency = "USDT", IsLockToken = true }; var transactionResult = (await VoteContractStub.Register.SendWithExceptionAsync(input)).TransactionResult; transactionResult.Status.ShouldBe(TransactionResultStatus.Failed); transactionResult.Error.Contains("Claimed accepted token is not available for voting").ShouldBeTrue(); } [Fact] public async Task VoteContract_Vote_NotSuccess_Test() { //did not find related vote event { var input = new VoteInput { VotingItemId = HashHelper.ComputeFromString("hash") }; var transactionResult = (await VoteContractStub.Vote.SendWithExceptionAsync(input)).TransactionResult; transactionResult.Status.ShouldBe(TransactionResultStatus.Failed); transactionResult.Error.Contains("Voting item not found").ShouldBeTrue(); } //without such option { var votingItem = await RegisterVotingItemAsync(100, 4, true, DefaultSender, 2); var input = new VoteInput { VotingItemId = votingItem.VotingItemId, Option = "Somebody" }; var otherKeyPair = SampleECKeyPairs.KeyPairs[1]; var otherVoteStub = GetVoteContractTester(otherKeyPair); var transactionResult = (await otherVoteStub.Vote.SendWithExceptionAsync(input)).TransactionResult; transactionResult.Status.ShouldBe(TransactionResultStatus.Failed); transactionResult.Error.ShouldContain($"Option {input.Option} not found"); } //not enough token { var votingItemId = await RegisterVotingItemAsync(100, 4, true, DefaultSender, 2); var input = new VoteInput { VotingItemId = votingItemId.VotingItemId, Option = votingItemId.Options.First(), Amount = 2000_000_000_00000000L }; var otherKeyPair = SampleECKeyPairs.KeyPairs[1]; var otherVoteStub = GetVoteContractTester(otherKeyPair); var transactionResult = (await otherVoteStub.Vote.SendWithExceptionAsync(input)).TransactionResult; transactionResult.Status.ShouldBe(TransactionResultStatus.Failed); transactionResult.Error.ShouldContain("Insufficient balance"); } } } }
40.752294
118
0.581495
[ "MIT" ]
ezaruba/AElf
test/AElf.Contracts.Vote.Tests/GQL/BasicTests.cs
4,442
C#
using System.Linq; using Microsoft.EntityFrameworkCore; using Abp.MultiTenancy; using DA.ProjectManagement.Editions; using DA.ProjectManagement.MultiTenancy; namespace DA.ProjectManagement.EntityFrameworkCore.Seed.Tenants { public class DefaultTenantBuilder { private readonly ProjectManagementDbContext _context; public DefaultTenantBuilder(ProjectManagementDbContext context) { _context = context; } public void Create() { CreateDefaultTenant(); } private void CreateDefaultTenant() { // Default tenant var defaultTenant = _context.Tenants.IgnoreQueryFilters().FirstOrDefault(t => t.TenancyName == AbpTenantBase.DefaultTenantName); if (defaultTenant == null) { defaultTenant = new Tenant(AbpTenantBase.DefaultTenantName, AbpTenantBase.DefaultTenantName); var defaultEdition = _context.Editions.IgnoreQueryFilters().FirstOrDefault(e => e.Name == EditionManager.DefaultEditionName); if (defaultEdition != null) { defaultTenant.EditionId = defaultEdition.Id; } _context.Tenants.Add(defaultTenant); _context.SaveChanges(); } } } }
30.568182
141
0.627509
[ "MIT" ]
anthonynguyen92/DoAn
aspnet-core/src/DA.ProjectManagement.EntityFrameworkCore/EntityFrameworkCore/Seed/Tenants/DefaultTenantBuilder.cs
1,347
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("OpenSim.Region.ClientStack")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("http://opensimulator.org")] [assembly: AssemblyProduct("OpenSim")] [assembly: AssemblyCopyright("OpenSimulator developers")] [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("02ced54a-a802-4474-9e94-f03a44fde922")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // [assembly: AssemblyVersion("0.47.11.*")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.588235
84
0.755869
[ "BSD-3-Clause" ]
Michelle-Argus/ArribasimExtract
OpenSim/Region/ClientStack/Properties/AssemblyInfo.cs
1,280
C#
using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; using System.Collections; public class MainMenu : MonoBehaviour { // public Canvas mainMenuCanvas; public RectTransform creditPanel; // Use this for initialization void Start() { creditPanel.gameObject.SetActive(false); } // Update is called once per frame void Update() { } public void PlaySinleButton() { SceneManager.LoadScene(1); } public void Play2Player() { SceneManager.LoadScene(2); } public void CreditsButton() { creditPanel.gameObject.SetActive(true); // mainMenuCanvas.gameObject.SetActive(false); } public void BackButton() { creditPanel.gameObject.SetActive(false); // mainMenuCanvas.gameObject.SetActive(true); } public void QuitButton() { Application.Quit(); } }
17.528302
53
0.636168
[ "Apache-2.0" ]
DaffyNinja/Experimental-Game
Experimental Game/Assets/Music Flow Game/Scripts/MainMenu.cs
931
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Kujikatsu022.Algorithms; using Kujikatsu022.Collections; using Kujikatsu022.Extensions; using Kujikatsu022.Numerics; using Kujikatsu022.Questions; namespace Kujikatsu022.Questions { /// <summary> /// https://atcoder.jp/contests/agc034/tasks/agc034_a /// </summary> public class QuestionC : AtCoderQuestionBase { public override IEnumerable<object> Solve(TextReader inputStream) { var (_, snukeStart, fnukeStart, snukeGoal, fnukeGoal) = inputStream.ReadValue<int, int, int, int, int>(); snukeStart--; fnukeStart--; snukeGoal--; fnukeGoal--; var s = inputStream.ReadLine() + "#####"; var ok = true; for (int i = Math.Min(snukeStart, fnukeStart); i < Math.Max(snukeGoal, fnukeGoal); i++) { if (s[i] == '#' && s[i + 1] == '#') { ok = false; break; } } if ((long)(snukeStart - fnukeStart) * (snukeGoal - fnukeGoal) < 0) { var localOk = false; for (int i = Math.Max(snukeStart, fnukeStart); i <= Math.Min(snukeGoal, fnukeGoal); i++) { if (s[i - 1] == '.' && s[i] == '.' && s[i + 1] == '.') { localOk = true; break; } } ok &= localOk; } yield return ok ? "Yes" : "No"; } } }
29.694915
117
0.493721
[ "MIT" ]
terry-u16/AtCoder
Kujikatsu022/Kujikatsu022/Kujikatsu022/Questions/QuestionC.cs
1,754
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DFBSimulatorWrapper.GraphViz { public enum Shape { // Polygon box, polygon, ellipse, oval, circle, point, egg, triangle, plaintext, plain, diamond, trapezium, parallelogram, house, pentagon, hexagon, septagon, octagon, doublecircle, doubleoctagon, tripleoctagon, invtriangle, invtrapezium, invhouse, Mdiamond, Msquare, Mcircle, rect, rectangle, square, star, none, underline, cylinder, note, tab, folder, box3d, component, promoter, cds, terminator, utr, primersite, restrictionsite, fivepoverhang, threepoverhang, noverhang, assembly, signature, insulator, ribosite, rnastab, proteasesite, proteinstab, rpromoter, rarrow, larrow, lpromoter, // Record record, Mrecord, } }
12.090909
38
0.680988
[ "MIT" ]
paphillips/DFB
DFBSimulatorWrapper/GraphViz/Shape.cs
933
C#
/* * Selling Partner API for Merchant Fulfillment * * The Selling Partner API for Merchant Fulfillment helps you build applications that let sellers purchase shipping for non-Prime and Prime orders using Amazon’s Buy Shipping Services. * * OpenAPI spec version: v0 * * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using Newtonsoft.Json; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Runtime.Serialization; using System.Text; namespace AmazonSpApiSDK.Models.MerchantFulfillment { /// <summary> /// The state or province code. /// </summary> [DataContract] public partial class StateOrProvinceCode : IEquatable<StateOrProvinceCode>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="StateOrProvinceCode" /> class. /// </summary> [JsonConstructorAttribute] public StateOrProvinceCode() { } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class StateOrProvinceCode {\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as StateOrProvinceCode); } /// <summary> /// Returns true if StateOrProvinceCode instances are equal /// </summary> /// <param name="input">Instance of StateOrProvinceCode to be compared</param> /// <returns>Boolean</returns> public bool Equals(StateOrProvinceCode input) { if (input == null) return false; return false; } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
30.737864
184
0.594125
[ "MIT" ]
KristopherMackowiak/Amazon-SP-API-CSharp
Source/AmazonSpApiSDK/Models/MerchantFulfillment/StateOrProvinceCode.cs
3,168
C#
using System.Threading.Tasks; using EDziekanat.Application.Permissions; using Microsoft.AspNetCore.Authorization; namespace EDziekanat.Web.Core.Authentication { public class PermissionHandler : AuthorizationHandler<PermissionRequirement> { private readonly IPermissionAppService _permissionApp; public PermissionHandler(IPermissionAppService permissionApp) { _permissionApp = permissionApp; } protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionRequirement requirement) { if (context.User == null || !context.User.Identity.IsAuthenticated) { context.Fail(); return; } var hasPermission = await _permissionApp.IsUserGrantedToPermissionAsync(context.User.Identity.Name, requirement.Permission.Name); if (hasPermission) { context.Succeed(requirement); } } } }
31.9375
141
0.662427
[ "MIT" ]
jendruss/EDziekanatAPI
src/EDziekanat.Web.Core/Authentication/PermissionHandler.cs
1,024
C#
// <copyright file="WebServices.asmx.cs" company="Engage Software"> // Engage: Locator - http://www.engagemodules.com // Copyright (c) 2004-2009 // by Engage Software ( http://www.engagesoftware.com ) // </copyright> // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED // TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF // CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. namespace Engage.Dnn.Locator.Services { using System.ComponentModel; using System.Data; using System.Web.Services; using Maps; [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [ToolboxItem(false)] public class WebServices : WebService { [WebMethod] public LocationCollection GetLocationsByZip(string mapProviderTypeName, string apiKey, int radius, string postalCode, int locationTypeId, int portalId) { int[] locationTypeIds = { locationTypeId }; return SearchLocationsByZip(mapProviderTypeName, apiKey, radius, postalCode, locationTypeIds, portalId); } public LocationCollection GetLocationsByZip(string mapProviderTypeName, string apiKey, int radius, string postalCode, int[] locationTypeIds, int portalId) { return SearchLocationsByZip(mapProviderTypeName, apiKey, radius, postalCode, locationTypeIds, portalId); } private static LocationCollection SearchLocationsByZip(string mapProviderTypeName, string apiKey, int radius, string postalCode, int[] locationTypeIds, int portalId) { MapProviderType providerType = MapProviderType.GetFromName(mapProviderTypeName, typeof(MapProviderType)); GeocodeResult result = MapProvider.CreateInstance(providerType, apiKey).GeocodeLocation(string.Empty, string.Empty, null, postalCode, null); LocationCollection matches = Location.GetAllLocationsByDistance(result.Latitude, result.Longitude, radius, portalId, locationTypeIds, null, null); return matches; } [WebMethod] public Location GetLocation(int locationId) { return Location.GetLocation(locationId); } [WebMethod] public DataTable GetLocationTypes() { return Data.DataProvider.Instance().GetLocationTypes(); } [WebMethod] public DataTable GetLocations(int locationTypeId, int portalId) { return Data.DataProvider.Instance().GetLocations(locationTypeId, portalId); } } }
44.5
174
0.692203
[ "MIT" ]
mattekelly/Engage-Locator
Services/WebServices.asmx.cs
2,939
C#
/************************************************************************************* Extended WPF Toolkit Copyright (C) 2007-2013 Xceed Software Inc. This program is provided to you under the terms of the Microsoft Public License (Ms-PL) as published at http://wpftoolkit.codeplex.com/license For more features, controls, and fast professional support, pick up the Plus Edition at http://xceed.com/wpf_toolkit Stay informed: follow @datagrid on Twitter or Like http://facebook.com/datagrids ***********************************************************************************/ using System; using System.Windows; using System.Windows.Controls; namespace Xceed.Wpf.DataGrid { public delegate void RowValidationErrorRoutedEventHandler( object sender, RowValidationErrorRoutedEventArgs e ); public class RowValidationErrorRoutedEventArgs : RoutedEventArgs { public RowValidationErrorRoutedEventArgs( RowValidationError rowValidationError ) : base() { if( rowValidationError == null ) throw new ArgumentNullException( "rowValidationError" ); m_rowValidationError = rowValidationError; } public RowValidationErrorRoutedEventArgs( RoutedEvent routedEvent, RowValidationError rowValidationError ) : base( routedEvent ) { if( rowValidationError == null ) throw new ArgumentNullException( "rowValidationError" ); m_rowValidationError = rowValidationError; } public RowValidationErrorRoutedEventArgs( RoutedEvent routedEvent, object source, RowValidationError rowValidationError ) : base( routedEvent, source ) { if( rowValidationError == null ) throw new ArgumentNullException( "rowValidationError" ); m_rowValidationError = rowValidationError; } #region ValidationError PROPERTY public RowValidationError RowValidationError { get { return m_rowValidationError; } } private RowValidationError m_rowValidationError; #endregion ValidationError PROPERTY } }
30.869565
126
0.652582
[ "MIT" ]
BenInCOSprings/WpfDockingWindowsApplicationTemplate
wpftoolkit-110921/Main/Source/ExtendedWPFToolkitSolution/Src/Xceed.Wpf.DataGrid/RowValidationErrorRoutedEvent.cs
2,132
C#
namespace DarnTheLuck.Models { public class UserGroup { public string UserId { get; set; } public string UserEmail { get; set; } public string GrantId { get; set; } public string GrantEmail { get; set; } public bool Authorized { get; set; } public UserGroup() { Authorized = false; } } }
23.625
46
0.544974
[ "MIT" ]
git-gd/DarnTheLuck
Models/UserGroup.cs
380
C#
namespace JenkinsClient.Net.Models { public class Job : HasClass { public string Name { get; set; } public string Url { get; set; } public string Color { get; set; } } }
19.888889
35
0.664804
[ "MIT" ]
lvermeulen/JenkinsClient.Net
src/JenkinsClient.Net/Models/Job.cs
181
C#
/* * Sector conversion code borrowed from bizhawk: http://code.google.com/p/bizhawk/ * */ using System; using System.Linq; using System.Text; using System.Collections.Generic; namespace GDImageBuilder.DiscUtils.Raw { /// <summary> /// Used for converting sectors from 2048 byte size to 2352 /// </summary> public class SectorConversion { private static byte BCD_Byte(byte val) { byte ret = (byte)(val % 10); ret += (byte)(16 * (val / 10)); return ret; } /// <summary> /// Convert sector from 2048 bytes to 2352 /// </summary> /// <param name="data">A 2048 byte sector</param> /// <param name="lba">The LBA offset of the sector we're converting</param> /// <returns>The sector data</returns> public static byte[] ConvertSectorToRawMode1(byte[] data, int lba) { byte[] buffer = new byte[2352]; Array.Copy(data, 0, buffer, 16, 2048); int aba = lba + 150; byte bcd_aba_min = BCD_Byte((byte)(aba / 60 / 75)); byte bcd_aba_sec = BCD_Byte((byte)((aba / 75) % 60)); byte bcd_aba_frac = BCD_Byte((byte)(aba % 75)); //sync buffer[0] = 0x00; buffer[1] = 0xFF; buffer[2] = 0xFF; buffer[3] = 0xFF; buffer[4] = 0xFF; buffer[5] = 0xFF; buffer[6] = 0xFF; buffer[7] = 0xFF; buffer[8] = 0xFF; buffer[9] = 0xFF; buffer[10] = 0xFF; buffer[11] = 0x00; //sector address buffer[12] = bcd_aba_min; buffer[13] = bcd_aba_sec; buffer[14] = bcd_aba_frac; //mode 1 buffer[15] = 1; //calculate EDC and poke into the sector uint edc = ECM.EDC_Calc(buffer, 2064); ECM.PokeUint(buffer, 2064, edc); //intermediate for (int i = 0; i < 8; i++) buffer[2068 + i] = 0; //ECC ECM.ECC_Populate(buffer, 0, buffer, 0); return buffer; } } }
32.555556
85
0.529498
[ "MIT" ]
sizious/gdi-builder
GDImageBuilder/DiscUtils/Raw/SectorConversion.cs
2,053
C#
using System; using System.Diagnostics; using Lucene.Net.Randomized.Generators; using NUnit.Framework; namespace Lucene.Net.Facet { /* * 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 MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer; using MockTokenizer = Lucene.Net.Analysis.MockTokenizer; using Document = Lucene.Net.Documents.Document; using Field = Lucene.Net.Documents.Field; using TextField = Lucene.Net.Documents.TextField; using TaxonomyWriter = Lucene.Net.Facet.Taxonomy.TaxonomyWriter; using DirectoryTaxonomyReader = Lucene.Net.Facet.Taxonomy.Directory.DirectoryTaxonomyReader; using DirectoryTaxonomyWriter = Lucene.Net.Facet.Taxonomy.Directory.DirectoryTaxonomyWriter; using IndexReader = Lucene.Net.Index.IndexReader; using RandomIndexWriter = Lucene.Net.Index.RandomIndexWriter; using Term = Lucene.Net.Index.Term; using IndexSearcher = Lucene.Net.Search.IndexSearcher; using MatchAllDocsQuery = Lucene.Net.Search.MatchAllDocsQuery; using Query = Lucene.Net.Search.Query; using QueryUtils = Lucene.Net.Search.QueryUtils; using ScoreDoc = Lucene.Net.Search.ScoreDoc; using TermQuery = Lucene.Net.Search.TermQuery; using TopDocs = Lucene.Net.Search.TopDocs; using Directory = Lucene.Net.Store.Directory; using IOUtils = Lucene.Net.Util.IOUtils; [TestFixture] public class TestDrillDownQuery : FacetTestCase { private static IndexReader reader; private static DirectoryTaxonomyReader taxo; private static Directory dir; private static Directory taxoDir; private static FacetsConfig config; [TestFixtureTearDown] public static void AfterClassDrillDownQueryTest() { IOUtils.Close(reader, taxo, dir, taxoDir); reader = null; taxo = null; dir = null; taxoDir = null; config = null; } [TestFixtureSetUp] public static void BeforeClassDrillDownQueryTest() { dir = NewDirectory(); Random r = Random(); RandomIndexWriter writer = new RandomIndexWriter(r, dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(r, MockTokenizer.KEYWORD, false))); taxoDir = NewDirectory(); TaxonomyWriter taxoWriter = new DirectoryTaxonomyWriter(taxoDir); config = new FacetsConfig(); // Randomize the per-dim config: config.SetHierarchical("a", Random().NextBoolean()); config.SetMultiValued("a", Random().NextBoolean()); if (Random().NextBoolean()) { config.SetIndexFieldName("a", "$a"); } config.SetRequireDimCount("a", true); config.SetHierarchical("b", Random().NextBoolean()); config.SetMultiValued("b", Random().NextBoolean()); if (Random().NextBoolean()) { config.SetIndexFieldName("b", "$b"); } config.SetRequireDimCount("b", true); for (int i = 0; i < 100; i++) { Document doc = new Document(); if (i % 2 == 0) // 50 { doc.Add(new TextField("content", "foo", Field.Store.NO)); } if (i % 3 == 0) // 33 { doc.Add(new TextField("content", "bar", Field.Store.NO)); } if (i % 4 == 0) // 25 { if (r.NextBoolean()) { doc.Add(new FacetField("a", "1")); } else { doc.Add(new FacetField("a", "2")); } } if (i % 5 == 0) // 20 { doc.Add(new FacetField("b", "1")); } writer.AddDocument(config.Build(taxoWriter, doc)); } taxoWriter.Dispose(); reader = writer.Reader; writer.Dispose(); taxo = new DirectoryTaxonomyReader(taxoDir); } [Test] public virtual void TestAndOrs() { IndexSearcher searcher = NewSearcher(reader); // test (a/1 OR a/2) AND b/1 DrillDownQuery q = new DrillDownQuery(config); q.Add("a", "1"); q.Add("a", "2"); q.Add("b", "1"); TopDocs docs = searcher.Search(q, 100); Assert.AreEqual(5, docs.TotalHits); } [Test] public virtual void TestQuery() { IndexSearcher searcher = NewSearcher(reader); // Making sure the query yields 25 documents with the facet "a" DrillDownQuery q = new DrillDownQuery(config); q.Add("a"); QueryUtils.Check(q); TopDocs docs = searcher.Search(q, 100); Assert.AreEqual(25, docs.TotalHits); // Making sure the query yields 5 documents with the facet "b" and the // previous (facet "a") query as a base query DrillDownQuery q2 = new DrillDownQuery(config, q); q2.Add("b"); docs = searcher.Search(q2, 100); Assert.AreEqual(5, docs.TotalHits); // Making sure that a query of both facet "a" and facet "b" yields 5 results DrillDownQuery q3 = new DrillDownQuery(config); q3.Add("a"); q3.Add("b"); docs = searcher.Search(q3, 100); Assert.AreEqual(5, docs.TotalHits); // Check that content:foo (which yields 50% results) and facet/b (which yields 20%) // would gather together 10 results (10%..) Query fooQuery = new TermQuery(new Term("content", "foo")); DrillDownQuery q4 = new DrillDownQuery(config, fooQuery); q4.Add("b"); docs = searcher.Search(q4, 100); Assert.AreEqual(10, docs.TotalHits); } [Test] public virtual void TestQueryImplicitDefaultParams() { IndexSearcher searcher = NewSearcher(reader); // Create the base query to start with DrillDownQuery q = new DrillDownQuery(config); q.Add("a"); // Making sure the query yields 5 documents with the facet "b" and the // previous (facet "a") query as a base query DrillDownQuery q2 = new DrillDownQuery(config, q); q2.Add("b"); TopDocs docs = searcher.Search(q2, 100); Assert.AreEqual(5, docs.TotalHits); // Check that content:foo (which yields 50% results) and facet/b (which yields 20%) // would gather together 10 results (10%..) Query fooQuery = new TermQuery(new Term("content", "foo")); DrillDownQuery q4 = new DrillDownQuery(config, fooQuery); q4.Add("b"); docs = searcher.Search(q4, 100); Assert.AreEqual(10, docs.TotalHits); } [Test] public virtual void TestScoring() { // verify that drill-down queries do not modify scores IndexSearcher searcher = NewSearcher(reader); float[] scores = new float[reader.MaxDoc]; Query q = new TermQuery(new Term("content", "foo")); TopDocs docs = searcher.Search(q, reader.MaxDoc); // fetch all available docs to this query foreach (ScoreDoc sd in docs.ScoreDocs) { scores[sd.Doc] = sd.Score; } // create a drill-down query with category "a", scores should not change DrillDownQuery q2 = new DrillDownQuery(config, q); q2.Add("a"); docs = searcher.Search(q2, reader.MaxDoc); // fetch all available docs to this query foreach (ScoreDoc sd in docs.ScoreDocs) { Assert.AreEqual(scores[sd.Doc], sd.Score, 0f, "score of doc=" + sd.Doc + " modified"); } } [Test] public virtual void TestScoringNoBaseQuery() { // verify that drill-down queries (with no base query) returns 0.0 score IndexSearcher searcher = NewSearcher(reader); DrillDownQuery q = new DrillDownQuery(config); q.Add("a"); TopDocs docs = searcher.Search(q, reader.MaxDoc); // fetch all available docs to this query foreach (ScoreDoc sd in docs.ScoreDocs) { Assert.AreEqual(0f, sd.Score, 0f); } } [Test] public virtual void TestTermNonDefault() { string aField = config.GetDimConfig("a").IndexFieldName; Term termA = DrillDownQuery.Term(aField, "a"); Assert.AreEqual(new Term(aField, "a"), termA); string bField = config.GetDimConfig("b").IndexFieldName; Term termB = DrillDownQuery.Term(bField, "b"); Assert.AreEqual(new Term(bField, "b"), termB); } [Test] public virtual void TestClone() { var q = new DrillDownQuery(config, new MatchAllDocsQuery()); q.Add("a"); var clone = q.Clone() as DrillDownQuery; Assert.NotNull(clone); clone.Add("b"); Assert.False(q.ToString().Equals(clone.ToString()), "query wasn't cloned: source=" + q + " clone=" + clone); } [Test] public virtual void TestNoDrillDown() { Query @base = new MatchAllDocsQuery(); DrillDownQuery q = new DrillDownQuery(config, @base); Query rewrite = q.Rewrite(reader).Rewrite(reader); Assert.AreSame(@base, rewrite); } } }
37.904255
164
0.565348
[ "Apache-2.0" ]
CerebralMischief/lucenenet
src/Lucene.Net.Tests.Facet/TestDrillDownQuery.cs
10,691
C#
using Membrane = membrane; namespace Bulb { public class RigidBodyComponentViewModel : ComponentViewModel { public string Mass { get => mass; set { mass = value; massNum = EditorPropertyHelper.InputStringToFloat(mass); OnRigidBodyChanged?.Invoke(massNum); OnPropertyChanged(nameof(Mass)); } } private string mass; private float massNum; public delegate void RigdBodyChangedHandler(float mass); public RigdBodyChangedHandler OnRigidBodyChanged; public RigidBodyComponentViewModel(Membrane.RigidBodyComponentInitData initData) : base($"{Membrane.ComponentType.RigidBody}", Membrane.ComponentType.RigidBody) { Update(initData.mass); } public void Update(float mass) { massNum = mass; this.mass = massNum.ToString(); OnPropertyChanged(nameof(Mass)); } public void RefreshValues() { Update(massNum); } } }
30.083333
93
0.592798
[ "MIT" ]
AGarlicMonkey/Clove
bulb/source/ViewModels/Components/RigidBodyComponentViewModel.cs
1,083
C#
using System; namespace Promitor.Core.Infrastructure { public class FeatureFlag { /// <summary> /// Determine if a feature flag is active or not /// </summary> /// <param name="toggleName">Name of the feature flag</param> /// <param name="defaultFlagState">Default state of the feature flag if it's not configured</param> public static bool IsActive(string toggleName, bool defaultFlagState = true) { var environmentVariableName = $"PROMITOR_FEATURE_{toggleName}"; var rawFlag = Environment.GetEnvironmentVariable(environmentVariableName); if (bool.TryParse(rawFlag, out var isActive)) { return isActive; } return defaultFlagState; } } }
32.36
107
0.608158
[ "MIT" ]
brandonh-msft/promitor
src/Promitor.Core/Infrastructure/FeatureFlag.cs
811
C#
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using GPMDP.Release.Services; using EmbeddedBlazorContent; namespace GPMDP.Release { public class Startup { private IWebHostEnvironment _env; public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddRazorPages(); services.AddServerSideBlazor().AddCircuitOptions(o => { if (_env.IsDevelopment()) //only add details when debugging { o.DetailedErrors = true; } }); // services.AddSingleton<ITimerService, TimerService>(); services.AddSingleton<CircleCIService>(); services.AddSingleton<AppVeyorService>(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { _env = env; if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseEmbeddedBlazorContent(typeof(MatBlazor.BaseMatComponent).Assembly); app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapBlazorHub(); endpoints.MapFallbackToPage("/_Host"); }); } } }
33.75
143
0.60305
[ "MIT" ]
agc93/gpmdp-release
src/GPMDP.Release/Startup.cs
2,295
C#
//#define USE_ARFOUNDATION using System; using System.Collections; using System.Collections.Generic; using UnityEngine; #if USE_ARFOUNDATION using UnityEngine.XR.ARFoundation; using UnityEngine.XR.ARSubsystems; #endif namespace GarageKit.ARFoundationExtention { [Serializable] public class ARImageAnchorOriginData { public string imageName = ""; public GameObject imageAnchorPrefab = null; } [DisallowMultipleComponent] #if USE_ARFOUNDATION [RequireComponent(typeof(ARTrackedImageManager))] [RequireComponent(typeof(ARAnchorManager))] #endif public class ARTrackedImageAnchorManager : MonoBehaviour { #if USE_ARFOUNDATION // Origins public List<ARImageAnchorOriginData> imageAnchorOrigins; // アンカーの画面外判定でDestroyを行う public bool destroyOnInvisibleAnchor = false; // トラッキングされるイメージアンカー数の制限 public int numberOfTrackingImageAnchor = 1; private ARTrackedImageManager trackedImageManager; private ARAnchorManager anchorManager; private Camera arCamera; // トラッキング中のアンカー private Dictionary<string, ARAnchor> trackedImageAnchors; public Dictionary<string, ARAnchor> TrackedImageAnchors { get{ return trackedImageAnchors; } } // 画像マーカーの認識時イベント public Action<string> OnFoundImageAnchor; // 画像マーカーの削除時イベント public Action<string> OnRemoveImageAnchor; void Awake() { trackedImageManager = this.gameObject.GetComponent<ARTrackedImageManager>(); anchorManager = this.gameObject.GetComponent<ARAnchorManager>(); arCamera = FindObjectOfType<ARCameraManager>().GetComponent<Camera>(); } void Start() { trackedImageAnchors = new Dictionary<string, ARAnchor>(); } void OnEnable() { trackedImageManager.trackedImagesChanged += OnTrackedImagesChanged; } void OnDisable() { trackedImageManager.trackedImagesChanged -= OnTrackedImagesChanged; } void Update() { // アンカーの画面外削除 if(destroyOnInvisibleAnchor) { List<string> removeReserved = new List<string>(); foreach(KeyValuePair<string, ARAnchor> kvp in trackedImageAnchors) { string imageName = kvp.Key; ARAnchor anchor = kvp.Value; if(IsOutOfView(anchor.gameObject.transform.position)) removeReserved.Add(imageName); } foreach(string name in removeReserved) RemoveImageAnchorFromImageName(name); } } void OnTrackedImagesChanged(ARTrackedImagesChangedEventArgs e) { // 新規マーカーの認識 foreach(ARTrackedImage trackedImage in e.added) { if(trackedImage.trackingState != TrackingState.None) AddImageAnchor(trackedImage); } // マーカー認識の継続更新 foreach(ARTrackedImage trackedImage in e.updated) { if(trackedImage.trackingState != TrackingState.None) { // 検出後 削除済みの場合に再度追加 if(!trackedImageAnchors.ContainsKey(trackedImage.referenceImage.name)) AddImageAnchor(trackedImage); } } // マーカー認識のロスト foreach(ARTrackedImage trackedImage in e.removed) RemoveImageAnchorFromImageName(trackedImage.referenceImage.name); } private void AddImageAnchor(ARTrackedImage trackedImage) { if(trackedImageAnchors.Count >= numberOfTrackingImageAnchor) { // トラッキングされるイメージアンカー数の制限 Debug.LogWarning("ARTrackedImageAnchorManager :: Limit of number recognized."); return; } if(trackedImageAnchors.ContainsKey(trackedImage.referenceImage.name)) { // 同一マーカーの複数認識を拒否 Debug.LogWarning("ARTrackedImageAnchorManager :: Multiple identical markers have been recognized."); return; } // 画面外判定 if(IsOutOfView(trackedImage.transform.position)) return; Debug.LogFormat("ARTrackedImageAnchorManager :: ImageAnchor added [{0}].", trackedImage.referenceImage.name); // マーカー画像検出位置にアンカーを設定 ARAnchor anchor = anchorManager.AddAnchor(new Pose(trackedImage.transform.position, trackedImage.transform.rotation)); anchor.destroyOnRemoval = true; float scale = trackedImage.size.x / trackedImage.referenceImage.size.x; anchor.gameObject.transform.localScale = Vector3.one * scale; // アンカーの子供にオブジェクトを生成 ARImageAnchorOriginData org = imageAnchorOrigins.Find(o => o.imageName == trackedImage.referenceImage.name); if(org != null && org.imageAnchorPrefab != null) { GameObject go = Instantiate(org.imageAnchorPrefab) as GameObject; go.name += string.Format(" [{0}]", org.imageName); go.transform.SetParent(anchor.gameObject.transform); go.transform.localPosition = Vector3.zero; go.transform.localRotation = Quaternion.identity; go.transform.localScale = Vector3.one; } trackedImageAnchors.Add(trackedImage.referenceImage.name, anchor); // マーカー検出イベント this.OnFoundImageAnchor?.Invoke(trackedImage.referenceImage.name); } public void RemoveImageAnchorFromImageName(string imageName) { if(trackedImageAnchors.ContainsKey(imageName)) { Debug.LogFormat("ARTrackedImageAnchorManager :: ImageAnchor removed [{0}].", imageName); // マーカー削除イベント this.OnRemoveImageAnchor?.Invoke(imageName); anchorManager.RemoveAnchor(trackedImageAnchors[imageName]); trackedImageAnchors.Remove(imageName); } } public void ResetImageAnchors() { foreach(ARImageAnchorOriginData org in imageAnchorOrigins) RemoveImageAnchorFromImageName(org.imageName); } private bool IsOutOfView(Vector3 worldPosition) { Vector3 vp = arCamera.WorldToViewportPoint(worldPosition); return (vp.x < 0.0f || vp.x > 1.0f || vp.y < 0.0f || vp.y > 1.0f); } #endif } }
34.010204
130
0.608011
[ "MIT" ]
sharkattack51/GarageKit_for_Unity
UnityProject/Assets/__ProjectName__/Scripts/Utils/ARFoundationExtention/ARTrackedImageAnchorManager.cs
7,118
C#
using Abp.Application.Services.Dto; using AppFramework.Common; using AppFramework.Common.Models; using AppFramework.Organizations; using AppFramework.Organizations.Dto; using Prism.Commands; using Prism.Services.Dialogs; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using Prism.Ioc; using System.Threading.Tasks; namespace AppFramework.ViewModels { public class OrganizationsViewModel : NavigationCurdViewModel { public OrganizationsViewModel(IOrganizationUnitAppService userAppService) { this.appService = userAppService; SelectedCommand = new DelegateCommand<OrganizationListModel>(Selected); AddRootUnitCommand = new DelegateCommand<OrganizationListModel>(AddOrganizationUnit); ChangeCommand = new DelegateCommand<OrganizationListModel>(EditOrganizationUnit); RemoveCommand = new DelegateCommand<OrganizationListModel>(DeleteOrganizationUnit); DeleteRoleCommand = new DelegateCommand<OrganizationUnitRoleListDto>(DeleteRole); DeleteMemberCommand = new DelegateCommand<OrganizationUnitUserListDto>(DeleteMember); usersInput = new GetOrganizationUnitUsersInput(); rolesInput = new GetOrganizationUnitRolesInput(); roledataPager = ContainerLocator.Container.Resolve<IDataPagerService>(); roledataPager.OnPageIndexChangedEventhandler += RoleOnPageIndexChangedEventhandler; memberdataPager = ContainerLocator.Container.Resolve<IDataPagerService>(); memberdataPager.OnPageIndexChangedEventhandler += MemberdataPager_OnPageIndexChangedEventhandler; ExecuteItemCommand = new DelegateCommand<string>(ExecuteItem); } private async void MemberdataPager_OnPageIndexChangedEventhandler(object sender, PageIndexChangedEventArgs e) { if (usersInput.Id == 0) return; usersInput.SkipCount = e.SkipCount; usersInput.MaxResultCount = e.PageSize; await SetBusyAsync(async () => { await GetOrganizationUnitUsers(usersInput); }); } private async void RoleOnPageIndexChangedEventhandler(object sender, PageIndexChangedEventArgs e) { if (rolesInput.Id == 0) return; rolesInput.SkipCount = e.SkipCount; rolesInput.MaxResultCount = e.PageSize; await SetBusyAsync(async () => { await GetOrganizationUnitRoles(rolesInput); }); } #region 字段/属性 private OrganizationListModel SelectedOrganizationUnit; private readonly IOrganizationUnitAppService appService; public IDataPagerService roledataPager { get; private set; } public IDataPagerService memberdataPager { get; private set; } private GetOrganizationUnitUsersInput usersInput; private GetOrganizationUnitRolesInput rolesInput; //选中组织、添加跟组织、修改、删除组织 public DelegateCommand<OrganizationListModel> SelectedCommand { get; } public DelegateCommand<OrganizationListModel> AddRootUnitCommand { get; private set; } public DelegateCommand<OrganizationListModel> ChangeCommand { get; private set; } public DelegateCommand<OrganizationListModel> RemoveCommand { get; private set; } public DelegateCommand<string> ExecuteItemCommand { get; private set; } //删除成员、角色 public DelegateCommand<OrganizationUnitUserListDto> DeleteMemberCommand { get; private set; } public DelegateCommand<OrganizationUnitRoleListDto> DeleteRoleCommand { get; private set; } #endregion #region 组织机构 /// <summary> /// 选中组织机构-更新成员和角色信息 /// </summary> /// <param name="organizationUnit"></param> private async void Selected(OrganizationListModel organizationUnit) { if (organizationUnit == null) return; SelectedOrganizationUnit = organizationUnit; rolesInput.Id = SelectedOrganizationUnit.Id; usersInput.Id = SelectedOrganizationUnit.Id; await GetOrganizationUnitUsers(usersInput); await GetOrganizationUnitRoles(rolesInput); } /// <summary> /// UI的按钮命令 /// 说明: 添加组织、添加成员、添加角色、刷新组织机构树 /// </summary> /// <param name="arg"></param> public async void ExecuteItem(string arg) { switch (arg) { case "AddOrganizationUnit": AddOrganizationUnit(); break; case "AddMember": await AddMember(SelectedOrganizationUnit); break; case "AddRole": await AddRole(SelectedOrganizationUnit); break; case "Refresh": await RefreshAsync(); break; } } /// <summary> /// 刷新组织结构树 /// </summary> /// <returns></returns> public override async Task RefreshAsync() { await SetBusyAsync(async () => { await WebRequest.Execute( () => appService.GetOrganizationUnits(), async result => { dataPager.GridModelList.Clear(); var items = BuildOrganizationTree(Map<List<OrganizationListModel>>(result.Items)); foreach (var item in items) dataPager.GridModelList.Add(item); await Task.CompletedTask; }); }); } /// <summary> /// 删除组织机构 /// </summary> /// <param name="organization"></param> public async void DeleteOrganizationUnit(OrganizationListModel organization) { if (await dialog.Question(Local.Localize("OrganizationUnitDeleteWarningMessage", organization.DisplayName))) { await WebRequest.Execute(() => appService.DeleteOrganizationUnit(new EntityDto<long>() { Id = organization.Id }), RefreshAsync); } } /// <summary> /// 编辑组织机构 /// </summary> /// <param name="organization"></param> public async void EditOrganizationUnit(OrganizationListModel organization) { DialogParameters param = new DialogParameters(); param.Add("Value", organization); var dialogResult = await dialog.ShowDialogAsync("OrganizationsAddView", param); if (dialogResult.Result == ButtonResult.OK) await RefreshAsync(); } /// <summary> /// 新增组织机构 /// </summary> /// <param name="organization"></param> public async void AddOrganizationUnit(OrganizationListModel organization = null) { DialogParameters param = new DialogParameters(); if (organization != null) param.Add("ParentId", organization.Id); var dialogResult = await dialog.ShowDialogAsync("OrganizationsAddView", param); if (dialogResult.Result == ButtonResult.OK) await RefreshAsync(); } /// <summary> /// 更新组织机构显示信息 /// </summary> /// <param name="id"></param> private void UpdateOrganizationUnit(long id) { var organizationUnit = dataPager.GridModelList .FirstOrDefault(t => t is OrganizationListModel q && q.Id.Equals(id)) as OrganizationListModel; if (organizationUnit != null) { organizationUnit.MemberCount = memberdataPager.GridModelList.Count; organizationUnit.RoleCount = roledataPager.GridModelList.Count; } } public ObservableCollection<object> BuildOrganizationTree( List<OrganizationListModel> organizationUnits, long? parentId = null) { var masters = organizationUnits .Where(x => x.ParentId == parentId).ToList(); var childs = organizationUnits .Where(x => x.ParentId != parentId).ToList(); foreach (OrganizationListModel dpt in masters) dpt.Items = BuildOrganizationTree(childs, dpt.Id); return new ObservableCollection<object>(masters); } #endregion #region 角色 /// <summary> /// 添加角色 /// </summary> /// <param name="organizationUnit"></param> /// <returns></returns> private async Task AddRole(OrganizationListModel organizationUnit) { if (organizationUnit == null) return; long Id = organizationUnit.Id; await WebRequest.Execute(() => appService.FindRoles(new FindOrganizationUnitRolesInput() { OrganizationUnitId = Id }), async result => { DialogParameters param = new DialogParameters(); param.Add("Id", Id); param.Add("Value", result); var dialogResult = await dialog.ShowDialogAsync(AppViewManager.AddRoles, param); if (dialogResult.Result == ButtonResult.OK) { rolesInput.Id = Id; await GetOrganizationUnitRoles(rolesInput); } }); } /// <summary> /// 刷新角色 /// </summary> /// <param name="Id"></param> /// <returns></returns> private async Task GetOrganizationUnitRoles(GetOrganizationUnitRolesInput input) { await SetBusyAsync(async () => { var pagedResult = await appService.GetOrganizationUnitRoles(input); if (pagedResult != null) roledataPager.SetList(pagedResult); UpdateOrganizationUnit(input.Id); }); } /// <summary> /// 删除角色 /// </summary> /// <param name="obj"></param> private async void DeleteRole(OrganizationUnitRoleListDto obj) { if (await dialog.Question(Local.Localize("RemoveRoleFromOuWarningMessage", SelectedOrganizationUnit.DisplayName, obj.DisplayName))) { await SetBusyAsync(async () => { await WebRequest.Execute(() => appService.RemoveRoleFromOrganizationUnit(new RoleToOrganizationUnitInput() { RoleId = (int)obj.Id, OrganizationUnitId = SelectedOrganizationUnit.Id, }), async () => { rolesInput.Id = SelectedOrganizationUnit.Id; await GetOrganizationUnitRoles(rolesInput); }); }); } } #endregion #region 成员 /// <summary> /// 添加成员 /// </summary> /// <param name="organizationUnit"></param> /// <returns></returns> private async Task AddMember(OrganizationListModel organizationUnit) { if (organizationUnit == null) return; long Id = organizationUnit.Id; await WebRequest.Execute(() => appService.FindUsers(new FindOrganizationUnitUsersInput() { OrganizationUnitId = Id }), async result => { DialogParameters param = new DialogParameters(); param.Add("Id", Id); param.Add("Value", result); var dialogResult = await dialog.ShowDialogAsync(AppViewManager.AddUsers, param); if (dialogResult.Result == ButtonResult.OK) await GetOrganizationUnitUsers(usersInput); }); } /// <summary> /// 刷新成员 /// </summary> /// <param name="Id"></param> /// <returns></returns> private async Task GetOrganizationUnitUsers(GetOrganizationUnitUsersInput input) { await SetBusyAsync(async () => { var pagedResult = await appService.GetOrganizationUnitUsers(input); if (pagedResult != null) memberdataPager.SetList(pagedResult); UpdateOrganizationUnit(input.Id); }); } /// <summary> /// 删除成员 /// </summary> /// <param name="obj"></param> private async void DeleteMember(OrganizationUnitUserListDto obj) { if (await dialog.Question(Local.Localize("RemoveUserFromOuWarningMessage", SelectedOrganizationUnit.DisplayName, obj.UserName))) { await SetBusyAsync(async () => { await WebRequest.Execute(() => appService.RemoveUserFromOrganizationUnit(new UserToOrganizationUnitInput() { OrganizationUnitId = SelectedOrganizationUnit.Id, UserId = obj.Id }), async () => { await GetOrganizationUnitUsers(usersInput); }); }); } } #endregion } }
36.690411
130
0.574074
[ "MIT" ]
Muzsor/WPF-Examples
src/AppFramework/ViewModels/Organizations/OrganizationsViewModel.cs
13,674
C#
using FastMember; using GameEstate.Formats.Red.CR2W; using System.IO; using System.Linq; namespace GameEstate.Formats.Red.Types.Complex { public partial class CBitmapTexture : ITexture, IByteSource { [Ordinal(1000), REDBuffer] public CUInt32 unk { get; set; } [Ordinal(1001), REDBuffer(true)] public CUInt32 MipsCount { get; set; } [Ordinal(1002), REDBuffer(true)] public CCompressedBuffer<SMipData> Mipdata { get; set; } [Ordinal(1003), REDBuffer(true)] public CUInt16 unk1 { get; set; } [Ordinal(1003), REDBuffer(true)] public CUInt16 unk2 { get; set; } // Uncooked Textures // Cooked Textures [Ordinal(1005), REDBuffer(true)] public CUInt32 ResidentmipSize { get; set; } [Ordinal(1006), REDBuffer(true)] public CBytes Residentmip { get; set; } public CBitmapTexture(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name) { MipsCount = new CUInt32(cr2w, this, nameof(MipsCount)) { IsSerialized = true }; Mipdata = new CCompressedBuffer<SMipData>(cr2w, this, nameof(Mipdata)) { IsSerialized = true }; unk1 = new CUInt16(cr2w, this, nameof(unk1)) { IsSerialized = true }; unk2 = new CUInt16(cr2w, this, nameof(unk2)) { IsSerialized = true }; ResidentmipSize = new CUInt32(cr2w, this, nameof(ResidentmipSize)) { IsSerialized = true }; Residentmip = new CBytes(cr2w, this, nameof(Residentmip)) { IsSerialized = true }; } public byte[] GetBytes() { var isUncooked = REDFlags == 0; byte[] bytesource; if (isUncooked) { if (Mipdata.Count <= 0) return null; bytesource = Mipdata.First().Mip.Bytes; for (var index = 1; index < Mipdata.Count; index++) { var byteArray = Mipdata[index].Mip; bytesource = bytesource.Concat(byteArray.Bytes).ToArray(); } } else bytesource = Residentmip.Bytes; return bytesource; } public override void Read(BinaryReader r, uint size) { base.Read(r, size); //TODO: readd for tw3 //MipsCount.Read(r, 4); //Mipdata.Read(r, size, (int)MipsCount.val); //ResidentmipSize.Read(r, 4); //unk1.Read(r, 2); //unk2.Read(r, 2); //Residentmip.Read(r, ResidentmipSize.val); } public override void Write(BinaryWriter w) { base.Write(w); MipsCount.val = (uint)Mipdata.Count; MipsCount.Write(w); Mipdata.Write(w); ResidentmipSize.Write(w); unk1.Write(w); unk2.Write(w); Residentmip.Write(w); } } }
40.356164
108
0.549898
[ "MIT" ]
smorey2/GameEstate
src/GameEstate.Formats.Red/Formats/Red/Types/Complex/CBitmapTexture.cs
2,948
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; using EventDemo; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EventDemo.Tests { [TestClass()] public class RoomTests { [TestMethod()] public void 게임을_시작하고_정답_카드를_뽑는_이벤트_테스트() { Game game = new Game(); game.StartGame(); foreach (var item in game.AnswerCards) { Console.WriteLine(item); } Console.WriteLine(); } [TestMethod()] public void 게임을_시작하고_카드를_배포하는_이벤트_테스트() { Game game = new Game(); game.StartGame(); game.DistributeCards(); for (int i = 0; i < game._players.Length; i++) { foreach (var item in game._players[i].GameCard) { Console.WriteLine(item); } Console.WriteLine(); } } [TestMethod()] public void 방의_추리_아이템을_얻는_이벤트_테스트() { Room room = new Room(Place.Courtyard); foreach (var item in room.roomObjects) { Console.WriteLine(item.Key); } Console.WriteLine(); } } }
22.5
63
0.504444
[ "MIT" ]
smingscript/4Way_Path_Finding_Test
EventDemo/EventDemoTests/ClassCase/RoomTests.cs
1,464
C#
using System; using System.Threading; namespace kwd.ConsoleAssist.BasicConsole { /// <summary> /// Standard console input stream. /// </summary> public interface IConsoleRead { /// <summary> /// A cancellable ReadKey. /// </summary> ConsoleKeyInfo ReadKey(CancellationToken cancel, bool intercept = false); /// <summary> /// Read secret data (echo a placeholder) /// </summary> string PromptSecret(string prompt, CancellationToken cancel); /// <summary> /// Read a line of text. /// </summary> string PromptString(string prompt, CancellationToken cancel); } }
26.269231
81
0.598829
[ "MIT" ]
Dkowald/kwd.ConsoleAssist
src/kwd.ConsoleAssist/BasicConsole/IConsoleRead.cs
685
C#
#region License // Copyright (c) Amos Voron. All rights reserved. // Licensed under the Apache 2.0 License. See LICENSE in the project root for license information. #endregion namespace QueryTalk.Wall { /// <summary> /// This interface is not intended for public use. /// </summary> public interface IRankingOrderBy { } }
24.571429
98
0.697674
[ "MIT" ]
amosvoron/QueryTalk
lib/Wall/interfaces/ranking/IRankingOrderBy.cs
346
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ITextViewNavigator.cs" company="Hukano"> // Copyright (c) Hukano. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Sundew.TextView.ApplicationFramework.Navigation { using System; using System.Collections.Generic; using System.Threading.Tasks; using Sundew.TextView.ApplicationFramework.TextViewRendering; /// <summary> /// Interface for implementing a text view navigator. /// </summary> public interface ITextViewNavigator : IDisposable { /// <summary> /// Gets the current view. /// </summary> /// <value> /// The current view. /// </value> ITextView CurrentView { get; } /// <summary> /// Shows the asynchronous. /// </summary> /// <param name="textView">The text view.</param> /// <returns>An async task with a value indicating whether the navigation was successful.</returns> Task<bool> ShowAsync(ITextView textView); /// <summary> /// Shows the modal asynchronous. /// </summary> /// <param name="textView">The text view.</param> /// <returns>An async task with a value indicating whether the navigation was successful.</returns> Task<bool> ShowModalAsync(ITextView textView); /// <summary> /// Shows the asynchronous. /// </summary> /// <param name="textView">The text view.</param> /// <param name="onNavigatingAction">The on navigating action.</param> /// <returns> /// An async task with a value indicating whether the navigation was successful. /// </returns> Task<bool> ShowAsync(ITextView textView, Action<ITextView>? onNavigatingAction); /// <summary> /// Shows the modal asynchronous. /// </summary> /// <param name="textView">The text view.</param> /// <param name="onNavigatingAction">The on navigating action.</param> /// <returns> /// An async task with a value indicating whether the navigation was successful. /// </returns> Task<bool> ShowModalAsync(ITextView textView, Action<ITextView>? onNavigatingAction); /// <summary> /// Shows the modal asynchronous. /// </summary> /// <param name="textView">The text view.</param> /// <param name="additionalInputTargets">The additional input targets.</param> /// <returns>An async task with a value indicating whether the navigation was successful.</returns> Task<bool> ShowModalAsync(ITextView textView, params object[] additionalInputTargets); /// <summary> /// Shows the modal asynchronous. /// </summary> /// <param name="textView">The text view.</param> /// <param name="additionalInputTargets">The additional input targets.</param> /// <returns>An async task with a value indicating whether the navigation was successful.</returns> Task<bool> ShowModalAsync(ITextView textView, IEnumerable<object> additionalInputTargets); /// <summary> /// Shows the modal asynchronous. /// </summary> /// <param name="textView">The text view.</param> /// <param name="onNavigatingAction">The on navigating action.</param> /// <param name="additionalInputTargets">The additional input targets.</param> /// <returns> /// An async task with a value indicating whether the navigation was successful. /// </returns> Task<bool> ShowModalAsync(ITextView textView, Action<ITextView>? onNavigatingAction, params object[] additionalInputTargets); /// <summary> /// Shows the modal asynchronous. /// </summary> /// <param name="textView">The text view.</param> /// <param name="onNavigatingAction">The on navigating action.</param> /// <param name="additionalInputTargets">The additional input targets.</param> /// <returns> /// An async task with a value indicating whether the navigation was successful. /// </returns> Task<bool> ShowModalAsync(ITextView textView, Action<ITextView>? onNavigatingAction, IEnumerable<object> additionalInputTargets); /// <summary> /// Navigates to asynchronous. /// </summary> /// <param name="textView">The text view.</param> /// <returns>An async task with a value indicating whether the navigation was successful.</returns> Task<bool> NavigateToAsync(ITextView textView); /// <summary> /// Navigates to asynchronous. /// </summary> /// <param name="textView">The text view.</param> /// <param name="onNavigatingAction">The on navigating action.</param> /// <returns> /// An async task with a value indicating whether the navigation was successful. /// </returns> Task<bool> NavigateToAsync(ITextView textView, Action<ITextView>? onNavigatingAction); /// <summary> /// Navigates to modal asynchronous. /// </summary> /// <param name="textView">The text view.</param> /// <returns>An async task with a value indicating whether the navigation was successful.</returns> Task<bool> NavigateToModalAsync(ITextView textView); /// <summary> /// Navigates to modal asynchronous. /// </summary> /// <param name="textView">The text view.</param> /// <param name="onNavigatingAction">The on navigating action.</param> /// <returns> /// An async task with a value indicating whether the navigation was successful. /// </returns> Task<bool> NavigateToModalAsync(ITextView textView, Action<ITextView>? onNavigatingAction); /// <summary> /// Navigates to modal asynchronous. /// </summary> /// <param name="textView">The text view.</param> /// <param name="additionalInputTargets">The additional input targets.</param> /// <returns> /// An async task with a value indicating whether the navigation was successful. /// </returns> Task<bool> NavigateToModalAsync(ITextView textView, params object[] additionalInputTargets); /// <summary> /// Navigates to modal asynchronous. /// </summary> /// <param name="textView">The text view.</param> /// <param name="additionalInputTargets">The additional input targets.</param> /// <returns> /// An async task with a value indicating whether the navigation was successful. /// </returns> Task<bool> NavigateToModalAsync(ITextView textView, IEnumerable<object> additionalInputTargets); /// <summary> /// Navigates to modal asynchronous. /// </summary> /// <param name="textView">The text view.</param> /// <param name="onNavigatingAction">The on navigating action.</param> /// <param name="additionalInputTargets">The additional input targets.</param> /// <returns> /// An async task with a value indicating whether the navigation was successful. /// </returns> Task<bool> NavigateToModalAsync(ITextView textView, Action<ITextView>? onNavigatingAction, params object[] additionalInputTargets); /// <summary> /// Navigates to modal asynchronous. /// </summary> /// <param name="textView">The text view.</param> /// <param name="onNavigatingAction">The on navigating action.</param> /// <param name="additionalInputTargets">The additional input targets.</param> /// <returns> /// An async task with a value indicating whether the navigation was successful. /// </returns> Task<bool> NavigateToModalAsync(ITextView textView, Action<ITextView>? onNavigatingAction, IEnumerable<object> additionalInputTargets); /// <summary> /// Navigates the back asynchronous. /// </summary> /// <returns>An async task with a value indicating whether the navigation was successful.</returns> Task<bool> NavigateBackAsync(); /// <summary> /// Goes the back. /// </summary> /// <param name="onNavigatingAction">The on navigating action.</param> /// <returns>An async task with a value indicating whether the navigation was successful.</returns> Task<bool> NavigateBackAsync(Action<ITextView>? onNavigatingAction); } }
46.666667
143
0.612812
[ "MIT" ]
hugener/Sundew.TextView.ApplicationFramework
Source/Sundew.TextView.ApplicationFramework/Navigation/ITextViewNavigator.cs
8,822
C#
using System; using backend.v2.Models; using Microsoft.VisualStudio.TestTools.UnitTesting; using Type = backend.v2.Models.Type; namespace backend.v2.tests.Models { [TestClass] public class BookTests { private Book model; [TestInitialize] public void BeforeEach() { this.model = new Book(); } [TestMethod] public void ShouldCreate() { Assert.IsNotNull(model); } [TestMethod] public void ShouldSetAllProperties() { var guid = Guid.NewGuid(); var name = "name"; var authors = new string[] { }; var status = Status.ToRead; var tags = new string[] { }; var done = (short)0; var total = (short)100; var collectionGuid = Guid.NewGuid(); var order = (short)1; var genre = "genre"; var startYear = (short)2019; var startMonth = (short)3; var startDay = (short)1; var endYear = (short)2021; var endMonth = (short)3; var endDay = (short)2; var year = (short)1998; var modifyDate = new DateTime(2021, 3, 1, 17, 33, 0); var createDate = new DateTime(2021, 3, 1, 17, 34, 0); var deleteDate = new DateTime(2021, 3, 1, 17, 35, 0); var progressType = "done"; var type = Type.Audio; var note = "note"; var userId = 1; var rereadingGuid = Guid.NewGuid(); var rereadingBook = new Book() { Guid = rereadingGuid, }; var book = new Book() { Guid = guid, Name = name, Authors = authors, Status = status, Tags = tags, DoneUnits = done, TotalUnits = total, CollectionGuid = collectionGuid, CollectionOrder = order, Genre = genre, StartDateYear = startYear, StartDateMonth = startMonth, StartDateDay = startDay, EndDateYear = endYear, EndDateMonth = endMonth, EndDateDay = endDay, Year = year, ModifyDate = modifyDate, CreateDate = createDate, DeleteDate = deleteDate, ProgressType = progressType, Type = type, Note = note, UserId = userId, RereadingBookGuid = rereadingBook.Guid.Value, RereadingBook = rereadingBook, }; Assert.AreEqual(book.Guid, guid); Assert.AreEqual(book.Name, name); Assert.AreSame(book.Authors, authors); Assert.AreEqual(book.Status, status); Assert.AreSame(book.Tags, tags); Assert.AreEqual(book.DoneUnits, done); Assert.AreEqual(book.TotalUnits, total); Assert.AreEqual(book.CollectionGuid, collectionGuid); Assert.AreEqual(book.CollectionOrder, order); Assert.AreEqual(book.Genre, genre); Assert.AreEqual(book.StartDateYear, startYear); Assert.AreEqual(book.StartDateMonth, startMonth); Assert.AreEqual(book.StartDateDay, startDay); Assert.AreEqual(book.EndDateYear, endYear); Assert.AreEqual(book.EndDateMonth, endMonth); Assert.AreEqual(book.EndDateDay, endDay); Assert.AreEqual(book.Year, year); Assert.AreEqual(book.ModifyDate, modifyDate); Assert.AreEqual(book.CreateDate, createDate); Assert.AreEqual(book.DeleteDate, deleteDate); Assert.AreEqual(book.ProgressType, progressType); Assert.AreEqual(book.Type, type); Assert.AreEqual(book.Note, note); Assert.AreEqual(book.UserId, userId); Assert.AreEqual(book.StartDate, new DateTime(2019, 3, 1)); Assert.AreEqual(book.EndDate, new DateTime(2021, 3, 2)); Assert.AreEqual(book.Deleted, true); Assert.AreEqual(book.RereadingBookGuid, rereadingGuid); Assert.AreEqual(book.RereadingBook, rereadingBook); } [TestMethod] public void ShouldReturnNullableDates() { var book = new Book(); Assert.AreEqual(book.EndDate, null); Assert.AreEqual(book.StartDate, null); Assert.AreEqual(book.Deleted, false); } } }
36.193798
70
0.527094
[ "MIT" ]
afferenslucem/bookolog
backend.v2/backend.v2.tests/Models/BookTests.cs
4,671
C#