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 © 2021 Neuroglia SPRL. All rights reserved.
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
using Neuroglia.AsyncApi.Configuration;
using Neuroglia.AsyncApi.Models;
using Neuroglia.AsyncApi.Services.Generators;
using Neuroglia.AsyncApi.Services.IO;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Neuroglia.AsyncApi.Services
{
/// <summary>
/// Represents the default implementation of the <see cref="IAsyncApiDocumentProvider"/> interface
/// </summary>
public class AsyncApiDocumentProvider
: BackgroundService, IAsyncApiDocumentProvider
{
/// <summary>
/// Initializes a new <see cref="AsyncApiDocumentProvider"/>
/// </summary>
/// <param name="options">The service used to access the current <see cref="AsyncApiGenerationOptions"/></param>
/// <param name="generator">The service used to generate <see cref="AsyncApiDocument"/>s</param>
/// <param name="writer">The service used to write <see cref="AsyncApiDocument"/>s</param>
public AsyncApiDocumentProvider(IOptions<AsyncApiGenerationOptions> options, IAsyncApiDocumentGenerator generator, IAsyncApiDocumentWriter writer)
{
this.Options = options.Value;
this.Generator = generator;
this.Writer = writer;
}
/// <summary>
/// Gets the current <see cref="AsyncApiGenerationOptions"/>
/// </summary>
protected AsyncApiGenerationOptions Options { get; }
/// <summary>
/// Gets the service used to generate <see cref="AsyncApiDocument"/>s
/// </summary>
protected IAsyncApiDocumentGenerator Generator { get; }
/// <summary>
/// Gets the service used to write <see cref="AsyncApiDocument"/>s
/// </summary>
protected IAsyncApiDocumentWriter Writer { get; }
/// <summary>
/// Gets a <see cref="List{T}"/> containing all available <see cref="AsyncApiDocument"/>s
/// </summary>
protected virtual List<AsyncApiDocument> Documents { get; private set; }
/// <inheritdoc/>
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
this.Documents = (await this.Generator.GenerateAsync(this.Options.MarkupTypes, new AsyncApiDocumentGenerationOptions() { DefaultConfiguration = this.Options.DefaultDocumentConfiguration })).ToList();
}
/// <inheritdoc/>
public virtual async Task<byte[]> ReadDocumentContentsAsync(string name, string version, AsyncApiDocumentFormat format)
{
if (string.IsNullOrWhiteSpace(name))
throw new ArgumentNullException(nameof(name));
AsyncApiDocument document = this.Documents.FirstOrDefault(n =>
(n.Info.Title.Equals(name, StringComparison.OrdinalIgnoreCase) || n.Info.Title.Replace(" ", "").Equals(name, StringComparison.OrdinalIgnoreCase))
&& n.Info.Version.Equals(version, StringComparison.OrdinalIgnoreCase));
if (document == null)
throw new NullReferenceException($"Failed to find an AsyncAPI document with the specified title '{name}' and version '{version}'");
using MemoryStream stream = new();
await this.Writer.WriteAsync(document, stream, format);
await stream.FlushAsync();
return stream.ToArray();
}
/// <inheritdoc/>
public virtual IEnumerator<AsyncApiDocument> GetEnumerator()
{
return this.Documents.AsReadOnly().GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}
}
| 40.363636 | 211 | 0.668919 |
[
"Apache-2.0"
] |
neuroglia-io/AsyncApi
|
src/Neuroglia.AsyncApi.AspNetCore/Services/AsyncApiDocumentProvider.cs
| 4,443 |
C#
|
/*----------------------------------------------------------------
Copyright (C) 2021 Senparc
文件名:ScheduleApi.cs
文件功能描述:日程相关API
创建标识:lishewen - 20191226
----------------------------------------------------------------*/
using Senparc.NeuChar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Senparc.Weixin.Work.AdvancedAPIs.Schedule.ScheduleJson;
using Senparc.Weixin.Entities;
namespace Senparc.Weixin.Work.AdvancedAPIs.Schedule
{
/// <summary>
/// 日程相关API
/// </summary>
public static class ScheduleApi
{
#region 同步方法
/// <summary>
/// 创建日程(每个应用每天最多可创建1万个日程。)
/// </summary>
/// <param name="accessTokenOrAppKey">接口调用凭证</param>
/// <param name="schedule">日程信息</param>
/// <param name="timeOut"></param>
/// <returns></returns>
[NcApiBind(NeuChar.PlatformType.WeChat_Work, true)]
public static AddScheduleJsonResult Add(string accessTokenOrAppKey, ScheduleJson.Schedule schedule, int timeOut = Config.TIME_OUT)
{
return ApiHandlerWapper.TryCommonApi(accessToken =>
{
var url = Config.ApiWorkHost + "/cgi-bin/oa/schedule/add?access_token={0}";
var data = new
{
schedule
};
return Senparc.Weixin.CommonAPIs.CommonJsonSend.Send<AddScheduleJsonResult>(accessToken, url, data, CommonJsonSendType.POST, timeOut);
}, accessTokenOrAppKey);
}
/// <summary>
/// 更新日程(注意,更新日程,不可变更组织者)
/// </summary>
/// <param name="accessTokenOrAppKey">接口调用凭证</param>
/// <param name="schedule">日程信息</param>
/// <param name="timeOut"></param>
/// <returns></returns>
[NcApiBind(NeuChar.PlatformType.WeChat_Work, true)]
public static WorkJsonResult Update(string accessTokenOrAppKey, ScheduleUpdate schedule, int timeOut = Config.TIME_OUT)
{
return ApiHandlerWapper.TryCommonApi(accessToken =>
{
var url = Config.ApiWorkHost + "/cgi-bin/oa/schedule/update?access_token={0}";
var data = new
{
schedule
};
return Senparc.Weixin.CommonAPIs.CommonJsonSend.Send<WorkJsonResult>(accessToken, url, data, CommonJsonSendType.POST, timeOut);
}, accessTokenOrAppKey);
}
/// <summary>
/// 取消日程
/// </summary>
/// <param name="accessTokenOrAppKey">接口调用凭证</param>
/// <param name="schedule_id">日程ID</param>
/// <param name="timeOut"></param>
/// <returns></returns>
[NcApiBind(NeuChar.PlatformType.WeChat_Work, true)]
public static WorkJsonResult Del(string accessTokenOrAppKey, string schedule_id, int timeOut = Config.TIME_OUT)
{
return ApiHandlerWapper.TryCommonApi(accessToken =>
{
var url = Config.ApiWorkHost + "/cgi-bin/oa/schedule/del?access_token={0}";
var data = new
{
schedule_id
};
return Senparc.Weixin.CommonAPIs.CommonJsonSend.Send<WorkJsonResult>(accessToken, url, data, CommonJsonSendType.POST, timeOut);
}, accessTokenOrAppKey);
}
/// <summary>
/// 获取日程(注意,被取消的日程也可以拉取详情,调用者需要检查status)
/// </summary>
/// <param name="accessTokenOrAppKey">接口调用凭证</param>
/// <param name="schedule_id_list">日程ID列表。一次最多拉取1000条</param>
/// <param name="timeOut"></param>
/// <returns></returns>
[NcApiBind(NeuChar.PlatformType.WeChat_Work, true)]
public static GetScheduleJsonResult Get(string accessTokenOrAppKey, List<string> schedule_id_list, int timeOut = Config.TIME_OUT)
{
return ApiHandlerWapper.TryCommonApi(accessToken =>
{
var url = Config.ApiWorkHost + "/cgi-bin/oa/schedule/get?access_token={0}";
var data = new
{
schedule_id_list
};
return Senparc.Weixin.CommonAPIs.CommonJsonSend.Send<GetScheduleJsonResult>(accessToken, url, data, CommonJsonSendType.POST, timeOut);
}, accessTokenOrAppKey);
}
#endregion
#region 异步方法
/// <summary>
/// 创建日程(每个应用每天最多可创建1万个日程。)
/// </summary>
/// <param name="accessTokenOrAppKey">接口调用凭证</param>
/// <param name="schedule">日程信息</param>
/// <param name="timeOut"></param>
/// <returns></returns>
[NcApiBind(NeuChar.PlatformType.WeChat_Work, true)]
public static async Task<AddScheduleJsonResult> AddAsync(string accessTokenOrAppKey, ScheduleJson.Schedule schedule, int timeOut = Config.TIME_OUT)
{
return await ApiHandlerWapper.TryCommonApiAsync(async accessToken =>
{
var url = Config.ApiWorkHost + "/cgi-bin/oa/schedule/add?access_token={0}";
var data = new
{
schedule
};
return await Weixin.CommonAPIs.CommonJsonSend.SendAsync<AddScheduleJsonResult>(accessToken, url, data, CommonJsonSendType.POST, timeOut).ConfigureAwait(false);
}, accessTokenOrAppKey).ConfigureAwait(false);
}
/// <summary>
/// 更新日程(注意,更新日程,不可变更组织者)
/// </summary>
/// <param name="accessTokenOrAppKey">接口调用凭证</param>
/// <param name="schedule">日程信息</param>
/// <param name="timeOut"></param>
/// <returns></returns>
[NcApiBind(NeuChar.PlatformType.WeChat_Work, true)]
public static async Task<WorkJsonResult> UpdateAsync(string accessTokenOrAppKey, ScheduleUpdate schedule, int timeOut = Config.TIME_OUT)
{
return await ApiHandlerWapper.TryCommonApiAsync(async accessToken =>
{
var url = Config.ApiWorkHost + "/cgi-bin/oa/schedule/update?access_token={0}";
var data = new
{
schedule
};
return await Weixin.CommonAPIs.CommonJsonSend.SendAsync<WorkJsonResult>(accessToken, url, data, CommonJsonSendType.POST, timeOut).ConfigureAwait(false);
}, accessTokenOrAppKey).ConfigureAwait(false);
}
/// <summary>
/// 取消日程
/// </summary>
/// <param name="accessTokenOrAppKey">接口调用凭证</param>
/// <param name="schedule_id">日程ID</param>
/// <param name="timeOut"></param>
/// <returns></returns>
[NcApiBind(NeuChar.PlatformType.WeChat_Work, true)]
public static async Task<WorkJsonResult> DelAsync(string accessTokenOrAppKey, string schedule_id, int timeOut = Config.TIME_OUT)
{
return await ApiHandlerWapper.TryCommonApiAsync(async accessToken =>
{
var url = Config.ApiWorkHost + "/cgi-bin/oa/schedule/del?access_token={0}";
var data = new
{
schedule_id
};
return await Weixin.CommonAPIs.CommonJsonSend.SendAsync<WorkJsonResult>(accessToken, url, data, CommonJsonSendType.POST, timeOut).ConfigureAwait(false);
}, accessTokenOrAppKey).ConfigureAwait(false);
}
/// <summary>
/// 获取日程(注意,被取消的日程也可以拉取详情,调用者需要检查status)
/// </summary>
/// <param name="accessTokenOrAppKey">接口调用凭证</param>
/// <param name="schedule_id_list">日程ID列表。一次最多拉取1000条</param>
/// <param name="timeOut"></param>
/// <returns></returns>
[NcApiBind(NeuChar.PlatformType.WeChat_Work, true)]
public static async Task<GetScheduleJsonResult> GetAsync(string accessTokenOrAppKey, List<string> schedule_id_list, int timeOut = Config.TIME_OUT)
{
return await ApiHandlerWapper.TryCommonApiAsync(async accessToken =>
{
var url = Config.ApiWorkHost + "/cgi-bin/oa/schedule/get?access_token={0}";
var data = new
{
schedule_id_list
};
return await Weixin.CommonAPIs.CommonJsonSend.SendAsync<GetScheduleJsonResult>(accessToken, url, data, CommonJsonSendType.POST, timeOut).ConfigureAwait(false);
}, accessTokenOrAppKey).ConfigureAwait(false);
}
#endregion
}
}
| 40.535545 | 175 | 0.58307 |
[
"Apache-2.0"
] |
LonelyLancer/WeiXinMPSDK
|
src/Senparc.Weixin.Work/Senparc.Weixin.Work/AdvancedAPIs/Schedule/ScheduleApi.cs
| 9,103 |
C#
|
using Luis;
using ToDoSkill.Dialogs.Shared.Resources;
namespace ToDoSkillTest.Flow.Utterances
{
public class DeleteToDoFlowTestUtterances : ShowToDoFlowTestUtterances
{
public DeleteToDoFlowTestUtterances()
{
var number = new double[] { 1 };
this.Add(DeleteSpecificTask, GetBaseDeleteToDoIntent(
DeleteSpecificTask,
number: number));
var listType = new string[] { ToDoStrings.Shopping };
number = new double[] { 2 };
this.Add(DeleteSpecificTaskWithListType, GetBaseDeleteToDoIntent(
DeleteSpecificTaskWithListType,
listType: listType,
number: number));
var containsAll = new string[] { "all" };
this.Add(DeleteAllTasks, GetBaseDeleteToDoIntent(
DeleteAllTasks,
containsAll: containsAll));
}
public static string DeleteSpecificTask { get; } = "delete the first task";
public static string DeleteSpecificTaskWithListType { get; } = "delete the second task in my shopping list";
public static string DeleteAllTasks { get; } = "remove all my tasks";
private ToDo GetBaseDeleteToDoIntent(
string userInput,
ToDo.Intent intents = ToDo.Intent.DeleteToDo,
double[] ordinal = null,
double[] number = null,
string[] listType = null,
string[] containsAll = null)
{
return GetToDoIntent(
userInput,
intents,
ordinal: ordinal,
number: number,
listType: listType,
containsAll: containsAll);
}
}
}
| 33.673077 | 116 | 0.5751 |
[
"MIT"
] |
vinstce/AI
|
solutions/Virtual-Assistant/src/csharp/skills/tests/todoskilltest/Flow/Utterances/DeleteToDoFlowTestUtterances.cs
| 1,753 |
C#
|
using System;
using UnityEngine;
using UnityEngine.Events;
namespace DapperDino.GGJ2020.Movements
{
[Serializable]
public struct MovementData
{
public Vector3 Input { get; set; }
public Transform CharacterTransform { get; set; }
public Transform CameraTransform { get; set; }
}
[Serializable]
public class UnityMovemementDataEvent : UnityEvent<MovementData> { }
}
| 23.055556 | 72 | 0.693976 |
[
"MIT"
] |
DapperDino/GGJ-2020
|
Assets/Scripts/Items/MovementData.cs
| 417 |
C#
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
using System;
namespace Microsoft.Azure.PowerShell.Cmdlets.Purviewdata.Runtime.Json
{
internal static class TypeExtensions
{
internal static bool IsNullable(this Type type) =>
type.IsGenericType && type.GetGenericTypeDefinition().Equals(typeof(Nullable<>));
internal static Type GetOpenGenericInterface(this Type candidateType, Type openGenericInterfaceType)
{
if (candidateType.IsGenericType && candidateType.GetGenericTypeDefinition() == openGenericInterfaceType)
{
return candidateType;
}
// Check if it references it's own converter....
foreach (Type interfaceType in candidateType.GetInterfaces())
{
if (interfaceType.IsGenericType
&& interfaceType.GetGenericTypeDefinition().Equals(openGenericInterfaceType))
{
return interfaceType;
}
}
return null;
}
// Author: Sebastian Good
// http://stackoverflow.com/questions/503263/how-to-determine-if-a-type-implements-a-specific-generic-interface-type
internal static bool ImplementsOpenGenericInterface(this Type candidateType, Type openGenericInterfaceType)
{
if (candidateType.Equals(openGenericInterfaceType))
{
return true;
}
if (candidateType.IsGenericType && candidateType.GetGenericTypeDefinition().Equals(openGenericInterfaceType))
{
return true;
}
foreach (Type i in candidateType.GetInterfaces())
{
if (i.IsGenericType && i.ImplementsOpenGenericInterface(openGenericInterfaceType))
{
return true;
}
}
return false;
}
}
}
| 37.983607 | 125 | 0.537333 |
[
"MIT"
] |
Agazoth/azure-powershell
|
src/Purview/Purviewdata.Autorest/generated/runtime/Helpers/Extensions/TypeExtensions.cs
| 2,259 |
C#
|
// This file is auto-generated, don't edit it. Thanks.
using System;
using System.Collections.Generic;
using System.IO;
using Tea;
namespace AlibabaCloud.SDK.Dingtalkdoc_1_0.Models
{
public class CreateWorkspaceDocResponse : TeaModel {
[NameInMap("headers")]
[Validation(Required=true)]
public Dictionary<string, string> Headers { get; set; }
[NameInMap("body")]
[Validation(Required=true)]
public CreateWorkspaceDocResponseBody Body { get; set; }
}
}
| 22.347826 | 64 | 0.680934 |
[
"Apache-2.0"
] |
aliyun/dingtalk-sdk
|
dingtalk/csharp/core/doc_1_0/Models/CreateWorkspaceDocResponse.cs
| 514 |
C#
|
using System;
using System.Linq;
using uTinyRipper.Classes;
using uTinyRipper.Classes.GameObjects;
using uTinyRipper.Converters.GameObjects;
using uTinyRipper.Layout;
namespace uTinyRipper.Converters
{
public static class GameObjectConverter
{
public static GameObject Convert(IExportContainer container, GameObject origin)
{
GameObjectLayout layout = container.Layout.GameObject;
GameObjectLayout exlayout = container.ExportLayout.GameObject;
GameObject instance = new GameObject(container.ExportLayout);
EditorExtensionConverter.Convert(container, origin, instance);
if (exlayout.IsComponentTuple)
{
instance.ComponentTuple = origin.ComponentTuple.ToArray();
}
else
{
instance.Component = GetComponent(container, origin);
}
instance.IsActive = GetIsActive(container, origin);
instance.Layer = origin.Layer;
instance.Name = origin.Name;
if (exlayout.HasTag)
{
instance.Tag = GetTag(container, origin);
}
if (exlayout.HasTagString)
{
instance.TagString = GetTagString(container, origin);
}
#if UNIVERSAL
if (layout.HasIcon)
{
instance.Icon = origin.Icon;
}
if (layout.HasNavMeshLayer)
{
instance.NavMeshLayer = origin.NavMeshLayer;
instance.StaticEditorFlags = origin.StaticEditorFlags;
}
else if (exlayout.HasIsStatic && layout.HasIsStatic)
{
instance.IsStatic = origin.IsStatic;
}
#endif
return instance;
}
private static ComponentPair[] GetComponent(IExportContainer container, GameObject origin)
{
if (container.Layout.GameObject.IsComponentTuple)
{
Tuple<ClassIDType, PPtr<Component>>[] originComponent = origin.ComponentTuple;
ComponentPair[] pairs = new ComponentPair[originComponent.Length];
for (int i = 0; i < pairs.Length; i++)
{
ComponentPair pair = new ComponentPair();
pair.Component = originComponent[i].Item2;
pairs[i] = pair;
}
return pairs;
}
else
{
return origin.Component.Select(t => ComponentPairConverter.Convert(container, t)).ToArray();
}
}
private static bool GetIsActive(IExportContainer container, GameObject origin)
{
if (container.Layout.GameObject.IsActiveInherited)
{
return origin.File.Collection.IsScene(origin.File) ? origin.IsActive : true;
}
return origin.IsActive;
}
private static ushort GetTag(IExportContainer container, GameObject origin)
{
if (container.Layout.GameObject.HasTag)
{
return origin.Tag;
}
return container.TagNameToID(origin.TagString);
}
private static string GetTagString(IExportContainer container, GameObject origin)
{
if (container.Layout.GameObject.HasTagString)
{
return origin.TagString;
}
return container.TagIDToName(origin.Tag);
}
}
}
| 26.883495 | 96 | 0.723366 |
[
"MIT"
] |
Bluscream/UtinyRipper
|
uTinyRipperCore/Converters/Classes/GameObject/GameObjectConverter.cs
| 2,771 |
C#
|
#region License & Metadata
// The MIT License (MIT)
//
// 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.
//
//
// Created On: 2018/07/27 12:55
// Modified On: 2019/01/19 01:23
// Modified By: Alexis
#endregion
using System;
using System.Diagnostics;
using SuperMemoAssistant.Interop.SuperMemo.Content;
using SuperMemoAssistant.Interop.SuperMemo.Content.Components;
using SuperMemoAssistant.Interop.SuperMemo.Content.Models;
using SuperMemoAssistant.Interop.SuperMemo.Elements.Models;
using SuperMemoAssistant.Interop.SuperMemo.Elements.Types;
using SuperMemoAssistant.Interop.SuperMemo.Registry.Members;
namespace SuperMemoAssistant.Interop.SuperMemo.Core
{
/// <summary>Base event, contains a SM management instance</summary>
[Serializable]
public class SMEventArgs : EventArgs
{
#region Constructors
public SMEventArgs(ISuperMemo smMgmt)
{
SMMgmt = smMgmt;
}
#endregion
#region Properties & Fields - Public
public ISuperMemo SMMgmt { get; set; }
#endregion
}
/// <summary>SuperMemo App Process-related events, contains a definition of its Process</summary>
[Serializable]
public class SMProcessArgs : SMEventArgs
{
#region Constructors
public SMProcessArgs(ISuperMemo smMgmt,
Process process)
: base(smMgmt)
{
Process = process;
}
#endregion
#region Properties & Fields - Public
public Process Process { get; }
#endregion
}
/// <summary>Element-related events</summary>
[Serializable]
public class SMDisplayedElementChangedArgs : SMEventArgs
{
#region Constructors
public SMDisplayedElementChangedArgs(ISuperMemo smMgmt,
IElement newElement,
IElement oldElement)
: base(smMgmt)
{
NewElement = newElement;
OldElement = oldElement;
}
#endregion
#region Properties & Fields - Public
public IElement NewElement { get; }
public IElement OldElement { get; }
#endregion
}
/// <summary>Element-related events</summary>
[Serializable]
public class SMElementArgs : SMEventArgs
{
#region Constructors
public SMElementArgs(ISuperMemo smMgmt,
IElement element)
: base(smMgmt)
{
Element = element;
}
#endregion
#region Properties & Fields - Public
public IElement Element { get; }
#endregion
}
/// <summary>Element change-related events</summary>
[Serializable]
public class SMElementChangedArgs : SMEventArgs
{
#region Constructors
public SMElementChangedArgs(ISuperMemo smMgmt,
IElement element,
ElementFieldFlags changedFields)
: base(smMgmt)
{
Element = element;
ChangedFields = changedFields;
}
#endregion
#region Properties & Fields - Public
public IElement Element { get; }
public ElementFieldFlags ChangedFields { get; }
#endregion
}
/// <summary>Registry member-related events</summary>
[Serializable]
public class SMRegistryArgs<T> : SMEventArgs
where T : IRegistryMember
{
#region Constructors
public SMRegistryArgs(ISuperMemo smMgmt,
T member)
: base(smMgmt)
{
Member = member;
}
#endregion
#region Properties & Fields - Public
public T Member { get; }
#endregion
}
/// <summary>Component-related events</summary>
[Serializable]
public class SMComponentChangedArgs : SMEventArgs
{
#region Constructors
public SMComponentChangedArgs(ISuperMemo smMgmt,
IComponent component,
ComponentFieldFlags changedFields)
: base(smMgmt)
{
Component = component;
ChangedFields = changedFields;
}
#endregion
#region Properties & Fields - Public
public IComponent Component { get; }
public ComponentFieldFlags ChangedFields { get; }
#endregion
}
/// <summary>Component group-related events</summary>
[Serializable]
public class SMComponentGroupArgs : SMEventArgs
{
#region Constructors
public SMComponentGroupArgs(ISuperMemo smMgmt,
IComponentGroup componentGroup)
: base(smMgmt)
{
ComponentGroup = componentGroup;
}
#endregion
#region Properties & Fields - Public
public IComponentGroup ComponentGroup { get; }
#endregion
}
}
| 22.607143 | 99 | 0.654555 |
[
"MIT"
] |
KeepOnSurviving/SuperMemoAssistant
|
src/Core/SuperMemoAssistant.Interop/Interop/SuperMemo/Core/SMEventArgs.cs
| 5,699 |
C#
|
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Windows;
namespace Microsoft.VisualStudio.InteractiveWindow.UnitTests
{
internal sealed class TestClipboard : InteractiveWindowClipboard
{
DataObject _data = null;
internal void Clear() => _data = null;
internal override bool ContainsData(string format) => _data?.GetData(format) != null;
internal override object GetData(string format) => _data?.GetData(format);
internal override bool ContainsText() => _data != null ? _data.ContainsText() : false;
internal override string GetText() => _data?.GetText();
internal override void SetDataObject(object data, bool copy) => _data = (DataObject)data;
internal override IDataObject GetDataObject() => _data;
}
}
| 34.481481 | 161 | 0.704619 |
[
"Apache-2.0"
] |
0x53A/roslyn
|
src/InteractiveWindow/EditorTest/TestClipboard.cs
| 933 |
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("Test")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Test")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("a2d09a45-a4bd-440e-8c25-d55bd6b6a87e")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.189189 | 84 | 0.744913 |
[
"MIT"
] |
PhilipYordanov/Software-University-C-Fundamentals-track
|
CSharpAdvance/Sets and Dictionaries - Lab/Sets and Dictionaries - Lab/Test/Properties/AssemblyInfo.cs
| 1,379 |
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using LightInject;
using RestOfUs.Common.Services;
using RestOfUs.Services;
using RestOfUs.Web.Services;
namespace RestOfUs.Web {
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit http://go.microsoft.com/?LinkId=9394801
public class MvcApplication : System.Web.HttpApplication {
private static ServiceContainer container;
protected void Application_Start() {
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
container = new ServiceContainer();
container.RegisterControllers();
container.Register<IUserStore, FakeUserStore>();
container.Register<IAuthenticator, FormsAuthenticator>();
container.Register<IOAuth2DataStore, FakeIoAuth2DataStore>();
container.EnableMvc();
}
}
}
| 32.727273 | 73 | 0.711111 |
[
"MIT"
] |
dylanbeattie/RestOfUs
|
src/RestOfUs.Web/Global.asax.cs
| 1,082 |
C#
|
using FPP.Scripts.Enums;
using UnityEngine.Events;
using System.Collections.Generic;
namespace FPP.Scripts.Patterns
{
public class RaceEventBus
{
private static readonly IDictionary<RaceEventType, UnityEvent> Events =
new Dictionary<RaceEventType, UnityEvent>();
public static void Subscribe(RaceEventType eventType, UnityAction listener)
{
UnityEvent thisEvent;
if (Events.TryGetValue(eventType, out thisEvent))
{
thisEvent.AddListener(listener);
}
else
{
thisEvent = new UnityEvent();
thisEvent.AddListener(listener);
Events.Add(eventType, thisEvent);
}
}
public static void Unsubscribe(RaceEventType eventType, UnityAction listener)
{
UnityEvent thisEvent;
if (Events.TryGetValue(eventType, out thisEvent))
{
thisEvent.RemoveListener(listener);
}
}
public static void Publish(RaceEventType eventType)
{
UnityEvent thisEvent;
if (Events.TryGetValue(eventType, out thisEvent))
{
thisEvent.Invoke();
}
}
}
}
| 28.711111 | 85 | 0.564241 |
[
"MIT"
] |
PacktPublishing/Game-Development-Patterns-with-Unity-2021
|
Assets/FPP/Scripts/Patterns/RaceEventBus.cs
| 1,294 |
C#
|
using Sandbox;
[Library( "weapon_shotgun", Title = "Shotgun", Spawnable = true )]
partial class Shotgun : Weapon
{
public override string ViewModelPath => "weapons/rust_pumpshotgun/v_rust_pumpshotgun.vmdl";
public override float PrimaryRate => 1;
public override float SecondaryRate => 1;
public override float ReloadTime => 0.5f;
public override void Spawn()
{
base.Spawn();
SetModel( "weapons/rust_pumpshotgun/rust_pumpshotgun.vmdl" );
}
public override void AttackPrimary()
{
TimeSincePrimaryAttack = 0;
TimeSinceSecondaryAttack = 0;
(Owner as AnimEntity)?.SetAnimBool( "b_attack", true );
//
// Tell the clients to play the shoot effects
//
ShootEffects();
PlaySound( "rust_pumpshotgun.shoot" );
//
// Shoot the bullets
//
ShootBullets( 10, 0.1f, 10.0f, 9.0f, 3.0f );
}
public override void AttackSecondary()
{
TimeSincePrimaryAttack = -0.5f;
TimeSinceSecondaryAttack = -0.5f;
(Owner as AnimEntity)?.SetAnimBool( "b_attack", true );
//
// Tell the clients to play the shoot effects
//
DoubleShootEffects();
PlaySound( "rust_pumpshotgun.shootdouble" );
//
// Shoot the bullets
//
ShootBullets( 20, 0.4f, 20.0f, 8.0f, 3.0f );
}
[ClientRpc]
protected override void ShootEffects()
{
Host.AssertClient();
Particles.Create( "particles/toon_muzzleflash.vpcf", EffectEntity, "muzzle" );
Particles.Create( "particles/pistol_ejectbrass.vpcf", EffectEntity, "ejection_point" );
ViewModelEntity?.SetAnimBool( "fire", true );
if ( IsLocalPawn )
{
new Sandbox.ScreenShake.Perlin( 1.0f, 1.5f, 2.0f );
}
CrosshairPanel?.CreateEvent( "fire" );
}
[ClientRpc]
protected virtual void DoubleShootEffects()
{
Host.AssertClient();
Particles.Create( "particles/toon_muzzleflash.vpcf", EffectEntity, "muzzle" );
ViewModelEntity?.SetAnimBool( "fire_double", true );
CrosshairPanel?.CreateEvent( "fire" );
if ( IsLocalPawn )
{
new Sandbox.ScreenShake.Perlin( 3.0f, 3.0f, 3.0f );
}
}
public override void OnReloadFinish()
{
IsReloading = false;
TimeSincePrimaryAttack = 0;
TimeSinceSecondaryAttack = 0;
FinishReload();
}
[ClientRpc]
protected virtual void FinishReload()
{
ViewModelEntity?.SetAnimBool( "reload_finished", true );
}
public override void SimulateAnimator( PawnAnimator anim )
{
anim.SetParam( "holdtype", 3 ); // TODO this is shit
anim.SetParam( "aimat_weight", 1.0f );
}
}
| 21.642857 | 92 | 0.695957 |
[
"MIT"
] |
ImWill0w0/sandbox
|
code/weapons/Shotgun.cs
| 2,426 |
C#
|
/*
* Licensed to SharpSoftware under one or more contributor
* license agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*
* SharpSoftware licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using Itinero.Optimization.Abstract.Models;
using Itinero.Optimization.Abstract.Solvers.TSP;
using Itinero.Optimization.Models.Mapping;
using Itinero.Optimization.Abstract.Tours;
namespace Itinero.Optimization.Abstract.Solvers.TSP
{
/// <summary>
/// Hooks the TSP solver up to the solver registry by defining solver details.
/// </summary>
public static class TSPSolverDetails
{
/// <summary>
/// Gets the default solver details.
/// </summary>
/// <returns></returns>
public static SolverDetails Default = new SolverDetails()
{
Name = "TSP",
TrySolve = TrySolve
};
private static Result<IList<ITour>> TrySolve(MappedModel mappedModel, Action<IList<ITour>> intermediateResult)
{
var result = mappedModel.TryToTSP();
if (result.IsError)
{
return result.ConvertError<IList<ITour>>();
}
var solution = result.Value.Solve();
return new Result<IList<ITour>>(new List<ITour>(
new ITour[]
{
solution
}));
}
/// <summary>
/// Returns true if the given model is a TSP.
/// </summary>
/// <param name="model">The model.</param>
/// <returns></returns>
public static bool IsTSP(this AbstractModel model)
{
string reasonIfNot;
return model.IsTSP(out reasonIfNot);
}
/// <summary>
/// Returns true if the given model is a TSP.
/// </summary>
/// <param name="model">The model.</param>
/// <param name="reasonIfNot">The reason if it's not considered a TSP.</param>
/// <returns></returns>
public static bool IsTSP(this AbstractModel model, out string reasonIfNot)
{
if (!model.IsValid(out reasonIfNot))
{
reasonIfNot = "Model is invalid: " + reasonIfNot;
return false;
}
if (model.VehiclePool.Reusable ||
model.VehiclePool.Vehicles.Length > 1)
{
reasonIfNot = "More than one vehicle or vehicle reusable.";
return false;
}
var vehicle = model.VehiclePool.Vehicles[0];
if (vehicle.TurnPentalty != 0)
{
reasonIfNot = "Turning penalty, this is a directed problem.";
return false;
}
if (vehicle.CapacityConstraints != null &&
vehicle.CapacityConstraints.Length > 0)
{
reasonIfNot = "At least one capacity constraint was found.";
return false;
}
if (model.TimeWindows != null &&
model.TimeWindows.Length > 0)
{
// TODO: check if timewindows are there but are all set to max.
reasonIfNot = "Timewindows detected.";
return false;
}
return true;
}
/// <summary>
/// Converts the given abstract model to a TSP.
/// </summary>
public static Result<ITSProblem> TryToTSP(this MappedModel mappedModel)
{
var model = mappedModel.BuildAbstract();
string reasonWhenFailed;
if (!model.IsTSP(out reasonWhenFailed))
{
return new Result<ITSProblem>("Model is not a TSP: " +
reasonWhenFailed);
}
var vehicle = model.VehiclePool.Vehicles[0];
var metric = vehicle.Metric;
if (!model.TryGetTravelCostsForMetric(metric, out Models.Costs.TravelCostMatrix weights))
{
throw new Exception("Travel costs not found but model was declared valid.");
}
int first = 0;
var problem = new TSProblem(first, weights.Costs);
if (vehicle.Departure.HasValue)
{
problem.First = vehicle.Departure.Value;
}
if (vehicle.Arrival.HasValue)
{
problem.Last = vehicle.Arrival.Value;
}
return new Result<ITSProblem>(problem);
}
}
}
| 35.054054 | 118 | 0.561103 |
[
"Apache-2.0"
] |
msioen/optimization
|
src/Itinero.Optimization/Abstract/Solvers/TSP/TSPSolverDetails.cs
| 5,188 |
C#
|
// Copyright 2016-2017 Confluent Inc.
//
// 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.
//
// Refer to LICENSE for more information.
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Xunit;
namespace Confluent.Kafka.IntegrationTests
{
/// <summary>
/// Test every Producer.ProduceAsync method overload that provides
/// delivery reports via a Task
/// (null key/value case)
/// </summary>
public static partial class Tests
{
[Theory, MemberData(nameof(KafkaParameters))]
public static void Producer_ProduceAsync_Null_Task(string bootstrapServers, string topic, string partitionedTopic)
{
var producerConfig = new Dictionary<string, object>
{
{ "bootstrap.servers", bootstrapServers },
{ "api.version.request", true }
};
var drs = new List<Task<Message>>();
using (var producer = new Producer(producerConfig))
{
drs.Add(producer.ProduceAsync(partitionedTopic, null, 0, 0, null, 0, 0, 1, true));
drs.Add(producer.ProduceAsync(partitionedTopic, null, 0, 0, null, 0, 0, 1));
drs.Add(producer.ProduceAsync(partitionedTopic, null, 0, 0, null, 0, 0, true));
drs.Add(producer.ProduceAsync(partitionedTopic, null, 0, 0, null, 0, 0));
drs.Add(producer.ProduceAsync(partitionedTopic, null, null));
Assert.Throws<ArgumentException>(() => { producer.ProduceAsync(partitionedTopic, null, 8, 100, null, -33, int.MaxValue); });
producer.Flush(TimeSpan.FromSeconds(10));
}
for (int i=0; i<5; ++i)
{
var dr = drs[i].Result;
Assert.Equal(ErrorCode.NoError, dr.Error.Code);
Assert.Equal(partitionedTopic, dr.Topic);
Assert.True(dr.Offset >= 0);
Assert.True(dr.Partition == 0 || dr.Partition == 1);
Assert.Null(dr.Key);
Assert.Null(dr.Value);
Assert.Equal(TimestampType.CreateTime, dr.Timestamp.Type);
Assert.True(Math.Abs((DateTime.UtcNow - dr.Timestamp.UtcDateTime).TotalMinutes) < 1.0);
}
Assert.Equal(1, drs[0].Result.Partition);
Assert.Equal(1, drs[1].Result.Partition);
}
}
}
| 41.056338 | 140 | 0.613379 |
[
"Apache-2.0"
] |
sstaton/daxko-kafka-etl
|
test/Confluent.Kafka.IntegrationTests/Tests/Producer_ProduceAsync_Null_Task.cs
| 2,915 |
C#
|
using Nager.Date.Contract;
using Nager.Date.Model;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Nager.Date.PublicHolidays
{
/// <summary>
/// Switzerland
/// http://de.wikipedia.org/wiki/Feiertage_in_der_Schweiz
/// </summary>
public class SwitzerlandProvider : IPublicHolidayProvider
{
private readonly ICatholicProvider _catholicProvider;
/// <summary>
/// SwitzerlandProvider
/// </summary>
/// <param name="catholicProvider"></param>
public SwitzerlandProvider(ICatholicProvider catholicProvider)
{
this._catholicProvider = catholicProvider;
}
/// <summary>
/// Get
/// </summary>
/// <param name="year">The year</param>
/// <returns></returns>
public IEnumerable<PublicHoliday> Get(int year)
{
var countryCode = CountryCode.CH;
var easterSunday = this._catholicProvider.EasterSunday(year);
//In canton of Neuchâtel the following dates are considered official county holidays
//only if Christmas day and new year's day fall on a Sunday : 26.12 and 02.01
var christmasDate = new DateTime(year, 12, 25);
var newYearDate = new DateTime(year, 12, 31);
var isChristmasDateSunday = christmasDate.DayOfWeek == DayOfWeek.Sunday;
var isNewYearDateSunday = newYearDate.DayOfWeek == DayOfWeek.Sunday;
//Get Jeune fédéral holiday date for the given year (3rd monday of September)
var thirdMondayOfSeptember = DateSystem.FindDay(year, 9, DayOfWeek.Monday, 3);
var items = new List<PublicHoliday>();
items.Add(new PublicHoliday(year, 1, 1, "Neujahr", "New Year's Day", countryCode, 1967));
items.Add(new PublicHoliday(year, 1, 2, "Berchtoldstag", "St. Berchtold's Day", countryCode, null, new string[] { "CH-ZH", "CH-BE", "CH-LU", "CH-OW", "CH-GL", "CH-ZG", "CH-FR", "CH-SO", "CH-SH", "CH-TG", "CH-VD", "CH-NE", "CH-GE", "CH-JU" }));
items.Add(new PublicHoliday(year, 1, 6, "Heilige Drei Könige", "Epiphany", countryCode, null, new string[] { "CH-UR", "CH-SZ", "CH-GR", "CH-TI" }));
items.Add(new PublicHoliday(year, 3, 19, "Josefstag", "Saint Joseph's Day", countryCode, null, new string[] { "CH-LU", "CH-UR", "CH-SZ", "CH-NW", "CH-ZG", "CH-GR", "CH-TI", "CH-VS" }));
items.Add(new PublicHoliday(easterSunday.AddDays(-2), "Karfreitag", "Good Friday", countryCode, null, new string[] { "CH-ZH", "CH-BE", "CH-LU", "CH-UR", "CH-SZ", "CH-OW", "CH-NW", "CH-GL", "CH-ZG", "CH-FR", "CH-SO", "CH-BS", "CH-BL", "CH-SH", "CH-AR", "CH-AI", "CH-SG", "CH-GR", "CH-AG", "CH-TG", "CH-VD", "CH-NE", "CH-GE", "CH-JU" }));
items.Add(new PublicHoliday(easterSunday.AddDays(1), "Ostermontag", "Easter Monday", countryCode, 1642, new string[] { "CH-ZH", "CH-BE", "CH-LU", "CH-UR", "CH-SZ", "CH-OW", "CH-NW", "CH-GL", "CH-ZG", "CH-FR", "CH-SO", "CH-BS", "CH-BL", "CH-SH", "CH-AR", "CH-AI", "CH-SG", "CH-GR", "CH-AG", "CH-TG", "CH-TI", "CH-VD", "CH-NE", "CH-GE", "CH-JU" }));
items.Add(new PublicHoliday(year, 5, 1, "Tag der Arbeit", "Labour Day", countryCode, null, new string[] { "CH-ZH", "CH-FR", "CH-SO", "CH-BS", "CH-BL", "CH-SH", "CH-AG", "CH-TG", "CH-TI", "CH-NE", "CH-JU" }));
items.Add(new PublicHoliday(easterSunday.AddDays(39), "Auffahrt", "Ascension Day", countryCode));
items.Add(new PublicHoliday(easterSunday.AddDays(50), "Pfingstmontag", "Whit Monday", countryCode, null, new string[] { "CH-ZH", "CH-BE", "CH-LU", "CH-UR", "CH-SZ", "CH-OW", "CH-NW", "CH-GL", "CH-ZG", "CH-FR", "CH-SO", "CH-BS", "CH-BL", "CH-SH", "CH-AR", "CH-AI", "CH-SG", "CH-GR", "CH-AG", "CH-TG", "CH-TI", "CH-VD", "CH-NE", "CH-GE", "CH-JU" }));
items.Add(new PublicHoliday(easterSunday.AddDays(60), "Fronleichnam", "Corpus Christi", countryCode, null, new string[] { "CH-LU", "CH-UR", "CH-SZ", "CH-OW", "CH-NW", "CH-ZG", "CH-FR", "CH-SO", "CH-BL", "CH-AI", "CH-GR", "CH-AG", "CH-TI", "CH-VS", "CH-NE", "CH-JU" }));
items.Add(new PublicHoliday(year, 8, 1, "Bundesfeier", "Swiss National Day", countryCode));
items.Add(new PublicHoliday(year, 8, 15, "Maria Himmelfahrt", "Assumption of the Virgin Mary", countryCode, null, new string[] { "CH-LU", "CH-UR", "CH-SZ", "CH-OW", "CH-NW", "CH-ZG", "CH-FR", "CH-SO", "CH-BL", "CH-AI", "CH-GR", "CH-AG", "CH-TI", "CH-VS", "CH-JU" }));
items.Add(new PublicHoliday(thirdMondayOfSeptember, "Jeûne Fédéral", "Jeûne Fédéral", countryCode, null, new string[] { "CH-NE", "CH-VD" }));
items.Add(new PublicHoliday(year, 11, 1, "Allerheiligen", "All Saints' Day", countryCode, null, new string[] { "CH-LU", "CH-UR", "CH-SZ", "CH-OW", "CH-NW", "CH-GL", "CH-ZG", "CH-FR", "CH-SO", "CH-AI", "CH-SG", "CH-GR", "CH-AG", "CH-TI", "CH-VS", "CH-JU" }));
items.Add(new PublicHoliday(year, 12, 8, "Mariä Empfängnis", "Immaculate Conception", countryCode, null, new string[] { "CH-LU", "CH-UR", "CH-SZ", "CH-OW", "CH-NW", "CH-ZG", "CH-FR", "CH-SO", "CH-AI", "CH-GR", "CH-AG", "CH-TI", "CH-VS" }));
items.Add(new PublicHoliday(year, 12, 25, "Weihnachten", "Christmas Day", countryCode));
if (isChristmasDateSunday)
{
items.Add(new PublicHoliday(year, 12, 26, "Stephanstag", "St. Stephen's Day", countryCode, null, new string[] { "CH-ZH", "CH-BE", "CH-LU", "CH-UR", "CH-SZ", "CH-OW", "CH-NW", "CH-GL", "CH-ZG", "CH-FR", "CH-SO", "CH-BS", "CH-BL", "CH-SH", "CH-AR", "CH-AI", "CH-SG", "CH-GR", "CH-AG", "CH-TG" }));
}
if (isNewYearDateSunday)
{
items.Add(new PublicHoliday(year, 12, 31, "Silvester", "Silvester", countryCode, null, new string[] { "CH-NE" }));
}
return items.OrderBy(o => o.Date);
}
}
}
| 76.909091 | 360 | 0.57565 |
[
"MIT"
] |
Pulgovisk/Nager.Date
|
Src/Nager.Date/PublicHolidays/SwitzerlandProvider.cs
| 5,936 |
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace dw.common.util
{
public class CommandLineParser
{
protected static string usage = "etl <configfile>";
public static string Usage { get { return usage; } }
public static Arguments parse( string[] args )
{
Arguments arguments = new Arguments();
string module = string.Empty;
try
{
int i = 0;
while (i < args.Length)
{
string filename = args[i++];
arguments = loadConfig( filename );
}
}
catch (Exception x)
{
throw new EtlException("Usage: " + usage, x);
}
return arguments;
}
public static Arguments loadConfig( string filename )
{
return Arguments.loadConfig(filename);
}
}
}
| 22.12766 | 61 | 0.498077 |
[
"MIT"
] |
dataventure-io/dw
|
src/dw-common/util/CommandLineParser.cs
| 1,042 |
C#
|
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Juce.Core.Time
{
public interface ITimer
{
ITimeContext TimeContext { get; }
TimeSpan Time { get; }
void Start();
void Pause();
void Resume();
void Reset();
void Restart();
bool HasReached(TimeSpan time);
Task AwaitReach(TimeSpan time, CancellationToken cancellationToken);
Task AwaitTime(TimeSpan time, CancellationToken cancellationToken);
}
}
| 24.666667 | 76 | 0.640927 |
[
"MIT"
] |
Juce-Assets/Juce-Core
|
Runtime/Time/ITimer.cs
| 520 |
C#
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace XTool
{
public class TabDataProfiler
{
public DataProfileFieldCollection Fields { get; set; }
public int RecordCount { get; set; }
public int FieldCount { get; set; }
private ProfilerSettings _Settings;
private List<FieldFilter> _Filters;
private bool _IsAnd = false;
public TabDataProfiler(ProfilerSettings settings, List<FieldFilter> filters, bool isAnd)
{
_Settings = settings;
Fields = new DataProfileFieldCollection();
_Filters = filters;
_IsAnd = isAnd;
}
public TabDataProfiler(ProfilerSettings settings)
:this(settings, new List<FieldFilter>(),false){}
public void Execute(IDataReader reader)
{
SetupFields(reader);
ExecuteProfile(reader);
Calculate();
}
private bool PassFilters(IDataReader reader)
{
bool b = true;
if (_Filters.Count > 0)
{
if (!_IsAnd)
{
b = false;
for (int i = 0;!b && i < _Filters.Count; i++)
{
var filter = _Filters[i];
string fieldValue = reader[filter.ColumnIndex].ToString();
if (filter.FilterValues.Contains(fieldValue))
{
b = true;
}
}
}
else
{
for (int i = 0;b && i < _Filters.Count; i++)
{
var filter = _Filters[i];
string fieldValue = reader[filter.ColumnIndex].ToString();
if (!filter.FilterValues.Contains(fieldValue))
{
b = false;
}
}
}
}
return b;
}
private void ExecuteProfile(IDataReader reader)
{
while (reader.Read())
{
for (int i = 0; i < FieldCount; i++)
{
if (PassFilters(reader))
{
Fields[i].Execute(reader[i].ToString());
}
}
RecordCount++;
}
}
private void SetupFields(IDataReader reader)
{
DataTable dt = reader.GetSchemaTable();
foreach (DataRow dr in dt.Rows)
{
DataProfileField fld = new DataProfileField(dr) { Index = FieldCount, MaxDistinct = _Settings.MaxDistinct };
Fields.Add(fld);
FieldCount++;
var found = _Filters.FirstOrDefault(x => x.ColumnName.Equals(fld.Name));
if (found != null)
{
found.ColumnIndex = fld.Index;
found.FilterValues = new List<string>();
foreach (var item in found.Values)
{
found.FilterValues.Add(item.Key);
}
}
}
}
public void Execute<T>(IEnumerable<T> list, string[] fields) where T : class , new()
{
SetupFields(list, fields);
ExecuteProfile(list);
Calculate();
}
private void ExecuteProfile<T>(IEnumerable<T> list) where T : class, new()
{
foreach (var item in list)
{
foreach (var fld in Fields)
{
fld.Execute(item);
}
}
}
private void SetupFields<T>(IEnumerable<T> list, string[] fields) where T : class, new()
{
T t = Activator.CreateInstance<T>();
Type type = t.GetType();
PropertyInfo[] infos = type.GetProperties();
foreach (PropertyInfo info in infos)
{
if (fields.Contains(info.Name))
{
DataProfileField fld = new DataProfileField(info) { MaxDistinct = _Settings.MaxDistinct };
Fields.Add(fld);
FieldCount++;
}
}
}
internal void Calculate()
{
// ming rocks!
foreach (var field in Fields)
{
field.CharProfile.Summarize();
field.Calculate(field.HasData);
}
}
public bool CanGetFilters()
{
return Fields != null && Fields.Count > 0;
}
public List<FieldFilter> GetFilters()
{
return (from x in Fields where x.IsSelected == true
select x.GetFilter()).ToList();
}
}
}
| 29.942197 | 124 | 0.445946 |
[
"MIT"
] |
eXtensoft/xtool
|
XTool/code/profiler.tab/TabDataProfiler.cs
| 5,182 |
C#
|
using Patients.Core.Entities.Foundation;
using System;
using System.Data.Entity;
using System.Threading.Tasks;
namespace Patients.Data
{
public interface IDbContext : IDisposable
{
IDbSet<TEntity> Set<TEntity>() where TEntity : BaseEntity;
void SetAsAdded<TEntity>(TEntity entity) where TEntity : BaseEntity;
void SetAsModified<TEntity>(TEntity entity) where TEntity : BaseEntity;
void SetAsDeleted<TEntity>(TEntity entity) where TEntity : BaseEntity;
void BeginTransaction();
int Commit();
Task<int> CommitAsync();
void Rollback();
}
}
| 23.037037 | 79 | 0.684887 |
[
"MIT"
] |
amshekar/azure-iot-devops
|
iMinify-Innova/Patient.Data/IDbContext.cs
| 624 |
C#
|
using System.Net.Http;
namespace BitTorrentAnonymizer.Services
{
public class AnonymizerHttpClient
{
public readonly HttpClient Client;
public AnonymizerHttpClient(HttpClient client)
{
Client = client;
}
}
}
| 18.733333 | 55 | 0.604982 |
[
"MIT"
] |
magicxor/BitTorrentAnonymizer
|
BitTorrentAnonymizer/Services/AnonymizerHttpClient.cs
| 283 |
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using AutoMapper;
using Lykke.Service.Affiliate.Contracts;
using Lykke.Service.Affiliate.Core.Domain.Repositories.Mongo;
using Lykke.Service.Affiliate.Core.Services;
using Lykke.Service.Affiliate.Models;
using Lykke.Service.ClientAccount.Client.AutorestClient;
using Microsoft.AspNetCore.Mvc;
using Swashbuckle.AspNetCore.SwaggerGen;
namespace Lykke.Service.Affiliate.Controllers
{
[Route("api/[controller]")]
public class AffiliateController : Controller
{
private readonly ILinkService _linkService;
private readonly IReferralService _referralService;
private readonly IClientAccountService _clientAccountService;
private readonly IAccrualService _accrualService;
private readonly IAffiliateService _affiliateService;
private readonly IMapper _mapper;
public AffiliateController(
IReferralService referralService,
IMapper mapper,
ILinkService linkService,
IClientAccountService clientAccountService,
IAccrualService accrualService,
IAffiliateService affiliateService)
{
_referralService = referralService;
_mapper = mapper;
_linkService = linkService;
_clientAccountService = clientAccountService;
_accrualService = accrualService;
_affiliateService = affiliateService;
}
[HttpGet("count")]
[SwaggerOperation("GetAffiliatesCount")]
[ProducesResponseType(typeof(int), (int)HttpStatusCode.OK)]
public async Task<int> GetAffiliatesCount()
{
var count = (await _affiliateService.GetAllAffiliates()).Count();
return count;
}
[HttpGet("referrals")]
[SwaggerOperation("GetReferrals")]
[ProducesResponseType(typeof(IEnumerable<ReferralModel>), (int)HttpStatusCode.OK)]
public async Task<IEnumerable<ReferralModel>> GetReferrals([FromQuery]string clientId)
{
var referrals = await _referralService.GetReferralsAsync(clientId);
var result = _mapper.Map<IEnumerable<IReferral>, IEnumerable<ReferralModel>>(referrals);
return result;
}
[HttpGet("referrals/count")]
[SwaggerOperation("GetReferralsCount")]
[ProducesResponseType(typeof(int), (int)HttpStatusCode.OK)]
public async Task<int> GetReferralsCount()
{
var count = await _referralService.GetReferralsCountAsync();
return count;
}
[HttpGet("links")]
[SwaggerOperation("GetLinks")]
[ProducesResponseType(typeof(IEnumerable<LinkModel>), (int)HttpStatusCode.OK)]
public async Task<IEnumerable<LinkModel>> GetLinks([FromQuery]string clientId)
{
var links = await _linkService.GetLinks(clientId);
var result = _mapper.Map<IEnumerable<LinkResult>, IEnumerable<LinkModel>>(links);
return result;
}
[HttpPost("link")]
[SwaggerOperation("RegisterLink")]
[ProducesResponseType(typeof(LinkModel), (int)HttpStatusCode.OK)]
public async Task<LinkModel> RegisterLink([FromBody]RegisterLinkModel model)
{
if (string.IsNullOrWhiteSpace(model.ClientId))
throw new ApiException(HttpStatusCode.BadRequest, "Client id must be not empty string");
if (!await ValidateClientId(model.ClientId))
throw new ApiException(HttpStatusCode.BadRequest, "Client does not exist");
if (string.IsNullOrWhiteSpace(model.RedirectUrl) || !Uri.IsWellFormedUriString(model.RedirectUrl, UriKind.Absolute))
throw new ApiException(HttpStatusCode.BadRequest, "Redirect URL must be a valid URL string");
var link = await _linkService.CreateNewLink(model.ClientId, model.RedirectUrl);
var result = _mapper.Map<LinkResult, LinkModel>(link);
return result;
}
[HttpGet("stats")]
[SwaggerOperation("GetStats")]
[ProducesResponseType(typeof(IEnumerable<StatisticItemModel>), (int)HttpStatusCode.OK)]
public async Task<IEnumerable<StatisticItemModel>> GetStats([FromQuery] string clientId)
{
var stats = await _accrualService.GetStats(clientId);
var result = _mapper.Map<IEnumerable<StatisticsItem>, IEnumerable<StatisticItemModel>>(stats);
return result;
}
private async Task<bool> ValidateClientId(string clientId)
{
var client = await _clientAccountService.GetClientByIdAsync(clientId);
return client != null;
}
}
}
| 38.198413 | 128 | 0.669645 |
[
"MIT"
] |
LykkeCity/Lykke.Service.Affiliate
|
src/Lykke.Service.Affiliate/Controllers/AffiliateController.cs
| 4,815 |
C#
|
/*
* [The BSD 3-Clause License]
* Copyright (c) 2015, Samuel Suffos
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list
* of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*
*/
using Matlab.Info;
using System;
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(Information.MatlabNodes)]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct(Information.MatlabNodes)]
[assembly: AssemblyCopyright(Information.Copyright)]
[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("5b0abc50-d928-4141-9d06-cea80d8c48b6")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion(Information.Version)]
[assembly: AssemblyFileVersion(Information.Version)]
/* EXTRA ATTRIBUTES */
[assembly: CLSCompliant(true)]
| 42.72973 | 88 | 0.757116 |
[
"BSD-3-Clause"
] |
samuel-suffos/matlab-parser
|
Matlab.Nodes/Properties/AssemblyInfo.cs
| 3,164 |
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 backup-2018-11-15.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.Backup.Model
{
/// <summary>
/// Contains detailed information about all of the controls of a framework. Each framework
/// must contain at least one control.
/// </summary>
public partial class FrameworkControl
{
private List<ControlInputParameter> _controlInputParameters = new List<ControlInputParameter>();
private string _controlName;
private ControlScope _controlScope;
/// <summary>
/// Gets and sets the property ControlInputParameters.
/// <para>
/// A list of <code>ParameterName</code> and <code>ParameterValue</code> pairs.
/// </para>
/// </summary>
public List<ControlInputParameter> ControlInputParameters
{
get { return this._controlInputParameters; }
set { this._controlInputParameters = value; }
}
// Check to see if ControlInputParameters property is set
internal bool IsSetControlInputParameters()
{
return this._controlInputParameters != null && this._controlInputParameters.Count > 0;
}
/// <summary>
/// Gets and sets the property ControlName.
/// <para>
/// The name of a control. This name is between 1 and 256 characters.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public string ControlName
{
get { return this._controlName; }
set { this._controlName = value; }
}
// Check to see if ControlName property is set
internal bool IsSetControlName()
{
return this._controlName != null;
}
/// <summary>
/// Gets and sets the property ControlScope.
/// <para>
/// The scope of a control. The control scope defines what the control will evaluate.
/// Three examples of control scopes are: a specific backup plan, all backup plans with
/// a specific tag, or all backup plans. For more information, see <a href="aws-backup/latest/devguide/API_ControlScope.html">
/// <code>ControlScope</code>.</a>
/// </para>
/// </summary>
public ControlScope ControlScope
{
get { return this._controlScope; }
set { this._controlScope = value; }
}
// Check to see if ControlScope property is set
internal bool IsSetControlScope()
{
return this._controlScope != null;
}
}
}
| 33.99 | 134 | 0.631656 |
[
"Apache-2.0"
] |
Hazy87/aws-sdk-net
|
sdk/src/Services/Backup/Generated/Model/FrameworkControl.cs
| 3,399 |
C#
|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using Microsoft.Build.BackEnd;
using Microsoft.Build.Execution;
using Xunit;
namespace Microsoft.Build.UnitTests.BackEnd
{
public class FullyQualifiedBuildRequest_Tests
{
[Fact]
public void TestConstructorGood()
{
BuildRequestData data1 = new BuildRequestData("foo", new Dictionary<string, string>(), "tools", new string[0], null);
FullyQualifiedBuildRequest request = new FullyQualifiedBuildRequest(new BuildRequestConfiguration(data1, "2.0"), new string[1] { "foo" }, true);
request = new FullyQualifiedBuildRequest(new BuildRequestConfiguration(data1, "2.0"), new string[0] { }, true);
BuildRequestData data3 = new BuildRequestData("foo", new Dictionary<string, string>(), "tools", new string[0], null);
request = new FullyQualifiedBuildRequest(new BuildRequestConfiguration(data1, "2.0"), new string[0] { }, false);
}
[Fact]
public void TestConstructorBad1()
{
Assert.Throws<ArgumentNullException>(() =>
{
FullyQualifiedBuildRequest request = new FullyQualifiedBuildRequest(null, new string[1] { "foo" }, true);
}
);
}
[Fact]
public void TestConstructorBad2()
{
Assert.Throws<ArgumentNullException>(() =>
{
FullyQualifiedBuildRequest request = new FullyQualifiedBuildRequest(new BuildRequestConfiguration(new BuildRequestData("foo", new Dictionary<string, string>(), "tools", new string[0], null), "2.0"), null, true);
}
);
}
[Fact]
public void TestProperties()
{
BuildRequestData data = new BuildRequestData("foo", new Dictionary<string, string>(), "tools", new string[0], null);
BuildRequestConfiguration config = new BuildRequestConfiguration(data, "2.0");
FullyQualifiedBuildRequest request = new FullyQualifiedBuildRequest(config, new string[1] { "foo" }, true);
Assert.Equal(request.Config, config);
Assert.Single(request.Targets);
Assert.Equal("foo", request.Targets[0]);
Assert.True(request.ResultsNeeded);
}
}
}
| 42.789474 | 227 | 0.637556 |
[
"MIT"
] |
0xced/msbuild
|
src/Build.UnitTests/BackEnd/FullyQualifiedBuildRequest_Tests.cs
| 2,439 |
C#
|
// Copyright (c) Jeremy W. Kuhne. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace WInterop.Storage
{
/// <summary>
/// Named pipe configuration.
/// </summary>
/// <remarks>
/// <see cref="https://msdn.microsoft.com/en-us/library/windows/hardware/ff728846.aspx"/>
/// </remarks>
public enum PipeConfiguration : uint
{
/// <summary>
/// The flow of data in the pipe goes from client to server only.
/// [FILE_PIPE_INBOUND]
/// </summary>
Inbound = 0x0,
/// <summary>
/// The flow of data in the pipe goes from server to client only.
/// [FILE_PIPE_OUTBOUND]
/// </summary>
Outbound = 0x1,
/// <summary>
/// The pipe is bidirectional; both server and client processes can read from
/// and write to the pipe. [FILE_PIPE_FULL_DUPLEX]
/// </summary>
FullDuplex = 0x2
}
}
| 31.8125 | 101 | 0.586444 |
[
"MIT"
] |
JeremyKuhne/WInterop
|
src/WInterop.Desktop/Storage/PipeConfiguration.cs
| 1,020 |
C#
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using Azure.Core;
namespace Azure.ResourceManager.AppService.Models
{
/// <summary> Details about restoring a deleted app. </summary>
public partial class DeletedAppRestoreRequest : ProxyOnlyResource
{
/// <summary> Initializes a new instance of DeletedAppRestoreRequest. </summary>
public DeletedAppRestoreRequest()
{
}
/// <summary> Initializes a new instance of DeletedAppRestoreRequest. </summary>
/// <param name="id"> The id. </param>
/// <param name="name"> The name. </param>
/// <param name="type"> The type. </param>
/// <param name="kind"> Kind of resource. </param>
/// <param name="deletedSiteId">
/// ARM resource ID of the deleted app. Example:
/// /subscriptions/{subId}/providers/Microsoft.Web/deletedSites/{deletedSiteId}
/// </param>
/// <param name="recoverConfiguration"> If true, deleted site configuration, in addition to content, will be restored. </param>
/// <param name="snapshotTime">
/// Point in time to restore the deleted app from, formatted as a DateTime string.
/// If unspecified, default value is the time that the app was deleted.
/// </param>
/// <param name="useDRSecondary"> If true, the snapshot is retrieved from DRSecondary endpoint. </param>
internal DeletedAppRestoreRequest(ResourceIdentifier id, string name, ResourceType type, string kind, string deletedSiteId, bool? recoverConfiguration, string snapshotTime, bool? useDRSecondary) : base(id, name, type, kind)
{
DeletedSiteId = deletedSiteId;
RecoverConfiguration = recoverConfiguration;
SnapshotTime = snapshotTime;
UseDRSecondary = useDRSecondary;
}
/// <summary>
/// ARM resource ID of the deleted app. Example:
/// /subscriptions/{subId}/providers/Microsoft.Web/deletedSites/{deletedSiteId}
/// </summary>
public string DeletedSiteId { get; set; }
/// <summary> If true, deleted site configuration, in addition to content, will be restored. </summary>
public bool? RecoverConfiguration { get; set; }
/// <summary>
/// Point in time to restore the deleted app from, formatted as a DateTime string.
/// If unspecified, default value is the time that the app was deleted.
/// </summary>
public string SnapshotTime { get; set; }
/// <summary> If true, the snapshot is retrieved from DRSecondary endpoint. </summary>
public bool? UseDRSecondary { get; set; }
}
}
| 46.728814 | 231 | 0.647443 |
[
"MIT"
] |
AhmedLeithy/azure-sdk-for-net
|
sdk/websites/Azure.ResourceManager.AppService/src/Generated/Models/DeletedAppRestoreRequest.cs
| 2,757 |
C#
|
// Note: Adapted from https://github.com/ap0llo/changelog/blob/9c789d570199480801ea95d57f425b425b5f1964/src/ChangeLog.Test/EqualityTest.cs
using System;
using System.Collections.Generic;
using System.Reflection;
using NUnit.Framework;
namespace Grynwald.Extensions.Statiq.TestHelpers
{
public interface IEqualityTestDataProvider<TTestee>
{
IEnumerable<(TTestee left, TTestee right)> GetEqualTestCases();
IEnumerable<(TTestee left, TTestee right)> GetUnequalTestCases();
}
/// <summary>
/// Base class for tests of <see cref="IEquatable{T}"/> implementations.
/// </summary>
public abstract class EqualityTest<TTestee, TDataProvider>
where TTestee : IEquatable<TTestee>
where TDataProvider : IEqualityTestDataProvider<TTestee>, new()
{
public static IEnumerable<object[]> EqualityTestCases()
{
var dataProvider = (IEqualityTestDataProvider<TTestee>)Activator.CreateInstance(typeof(TDataProvider))!;
foreach (var (left, right) in dataProvider.GetEqualTestCases())
{
yield return new object[] { left, right };
}
}
public static IEnumerable<object[]> InequalityTestCases()
{
var dataProvider = (IEqualityTestDataProvider<TTestee>)Activator.CreateInstance(typeof(TDataProvider))!;
foreach (var (left, right) in dataProvider.GetUnequalTestCases())
{
yield return new object[] { left, right };
}
}
public static IEnumerable<object[]> SampleInstance()
{
var dataProvider = (IEqualityTestDataProvider<TTestee>)Activator.CreateInstance(typeof(TDataProvider))!;
foreach (var (left, _) in dataProvider.GetUnequalTestCases())
{
yield return new object[] { left };
yield break;
}
}
private static bool TesteeImplementsEqualitsOperators =>
typeof(TTestee).GetMethod("op_Equality", BindingFlags.Static | BindingFlags.Public) != null;
[Theory]
[TestCaseSource(nameof(EqualityTestCases))]
public void Comparision_of_two_equal_instances_yield_expected_result(TTestee left, TTestee right)
{
// instances must be equal to themselves
Assert.AreEqual(left, left);
Assert.AreEqual(right, right);
// hash code must be equal
Assert.AreEqual(left.GetHashCode(), right.GetHashCode());
Assert.AreEqual(left, right);
Assert.AreEqual(right, left);
Assert.True(left.Equals(right));
Assert.True(left.Equals((object)right));
Assert.True(right.Equals(left));
Assert.True(right.Equals((object)left));
if (TesteeImplementsEqualitsOperators)
{
var opEquality = typeof(TTestee).GetMethod("op_Equality", BindingFlags.Static | BindingFlags.Public);
var opInequality = typeof(TTestee).GetMethod("op_Inequality", BindingFlags.Static | BindingFlags.Public);
Assert.NotNull(opEquality);
Assert.NotNull(opInequality);
var isEqual1 = (bool)opEquality!.Invoke(null, new object[] { left, right })!;
var isEqual2 = (bool)opEquality!.Invoke(null, new object[] { right, left })!;
var isNotEqual1 = (bool)opInequality!.Invoke(null, new object[] { left, right })!;
var isNotEqual2 = (bool)opInequality!.Invoke(null, new object[] { right, left })!;
Assert.True(isEqual1);
Assert.True(isEqual2);
Assert.False(isNotEqual1);
Assert.False(isNotEqual2);
}
}
[Theory]
[TestCaseSource(nameof(InequalityTestCases))]
public void Comparision_of_two_unequal_instances_yield_expected_result(TTestee left, TTestee right)
{
Assert.AreNotEqual(left, right);
Assert.AreNotEqual(right, left);
Assert.False(left.Equals(right));
Assert.False(left.Equals((object)right));
Assert.False(right.Equals(left));
Assert.False(right.Equals((object)left));
if (TesteeImplementsEqualitsOperators)
{
var opEquality = typeof(TTestee).GetMethod("op_Equality", BindingFlags.Static | BindingFlags.Public);
var opInequality = typeof(TTestee).GetMethod("op_Inequality", BindingFlags.Static | BindingFlags.Public);
Assert.NotNull(opEquality);
Assert.NotNull(opInequality);
var isEqual1 = (bool)opEquality!.Invoke(null, new object[] { left, right })!;
var isEqual2 = (bool)opEquality!.Invoke(null, new object[] { right, left })!;
var isNotEqual1 = (bool)opInequality!.Invoke(null, new object[] { left, right })!;
var isNotEqual2 = (bool)opInequality!.Invoke(null, new object[] { right, left })!;
Assert.False(isEqual1);
Assert.False(isEqual2);
Assert.True(isNotEqual1);
Assert.True(isNotEqual2);
}
}
[Theory]
[TestCaseSource(nameof(SampleInstance))]
public void Equals_retuns_false_if_argument_is_of_a_different_type(TTestee sut)
{
Assert.False(sut.Equals(new object()));
}
}
}
| 39.927007 | 139 | 0.6117 |
[
"MIT"
] |
ap0llo/extensions-statiq
|
src/Extensions.Statiq.TestHelpers/EqualityTest.cs
| 5,472 |
C#
|
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using Google.Api.Ads.AdWords.Lib;
using Google.Api.Ads.AdWords.Util.BatchJob;
using Google.Api.Ads.AdWords.Util.BatchJob.v201809;
using Google.Api.Ads.AdWords.v201809;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
namespace Google.Api.Ads.AdWords.Tests.Util.BatchJob.v201809
{
/// <summary>
/// Tests for <see cref="BatchJobUtilities" /> class.
/// </summary>
public class BatchJobUtilitiesTest : BatchJobUtilities
{
/// <summary>
/// The test user for initializing purposes.
/// </summary>
private AdWordsUser TEST_USER = new AdWordsUser();
/// <summary>
/// The test data for upload purposes.
/// </summary>
private readonly byte[] TEST_DATA =
Encoding.UTF8.GetBytes(
string.Concat(Enumerable.Repeat("ABCDEFGHIJKLMNOPQRSTUVWXYZ", 1000000)));
/// <summary>
/// A random chunk size that is not multiple of 256K.
/// </summary>
private const int TEST_NON_MULTIPLE_CHUNK_SIZE = 10000;
/// <summary>
/// The upload progress for testing resumable uploads.
/// </summary>
private const int TESTDATA_UPLOAD_PROGRESS = 123456;
/// <summary>
/// A random chunk size for testing chunked uploads.
/// </summary>
private const int TEST_CHUNK_SIZE = CHUNK_SIZE_ALIGN * 12;
/// <summary>
/// The number of batches for streamed upload.
/// </summary>
private const int NUM_BATCHES_FOR_STREAMED_UPLOAD = 10;
/// <summary>
/// The number of keyword operations to generate for testing purposes.
/// </summary>
private const int NUM_KEYWORD_OPERATIONS = 100000;
/// <summary>
/// Class to keep track of parameters passed to a <see cref="UploadChunk"/> method.
/// </summary>
public class UploadChunkRecord
{
/// <summary>
/// Gets or sets the start of the chunk.
/// </summary>
public int Start { get; set; }
/// <summary>
/// Gets or sets the end of the chunk.
/// </summary>
public int End { get; set; }
/// <summary>
/// Gets or sets the start file offset on the server.
/// </summary>
public long StartOffset { get; set; }
/// <summary>
/// Gets or sets the total size of the upload.
/// </summary>
public long? TotalUploadSize { get; set; }
}
/// <summary>
/// An array to keep track of calls to the mocked <see cref="UploadChunk"/>
/// method.
/// </summary>
private List<UploadChunkRecord> uploadChunkRecords = new List<UploadChunkRecord>();
/// <summary>
/// Initializes this instance.
/// </summary>
[SetUp]
public void Init()
{
}
/// <summary>
/// Tests for streaming upload without chunking.
/// </summary>
[Test]
public void TestStreamedUploadNoChunking()
{
uploadChunkRecords.Clear();
// Initialize the uploader for chunked upload.
this.Init(TEST_USER, false, 0);
// Generate operations for upload.
Operation[] operations = GetKeywordOperations(123);
// Start the upload.
BatchUploadProgress progress = this.BeginStreamUpload("http://www.example.com");
// Split the upload into NUM_BATCHES_FOR_STREAMED_UPLOAD batches.
int[] batchSizes = new int[NUM_BATCHES_FOR_STREAMED_UPLOAD];
for (int i = 0; i < NUM_BATCHES_FOR_STREAMED_UPLOAD; i++)
{
Operation[] operationsToStream =
new Operation[NUM_KEYWORD_OPERATIONS / NUM_BATCHES_FOR_STREAMED_UPLOAD];
int dataLength = Encoding.UTF8.GetBytes(GetPostBody(operationsToStream)).Length;
int paddedLength = CHUNK_SIZE_ALIGN - (dataLength % CHUNK_SIZE_ALIGN);
batchSizes[i] = dataLength + paddedLength;
Array.Copy(operations, i * NUM_BATCHES_FOR_STREAMED_UPLOAD, operationsToStream, 0,
NUM_BATCHES_FOR_STREAMED_UPLOAD);
progress = this.StreamUpload(progress, operationsToStream);
}
this.EndStreamUpload(progress);
// There should be NUM_BATCHES_FOR_STREAMED_UPLOAD + 1 batches.
Assert.That(uploadChunkRecords.Count == NUM_BATCHES_FOR_STREAMED_UPLOAD + 1);
// StartOffset tests.
Assert.AreEqual(0, uploadChunkRecords[0].StartOffset);
for (int i = 1; i < NUM_BATCHES_FOR_STREAMED_UPLOAD + 1; i++)
{
Assert.AreEqual(uploadChunkRecords[i].StartOffset,
uploadChunkRecords[i - 1].StartOffset + (uploadChunkRecords[i - 1].End -
uploadChunkRecords[i - 1].Start) + 1);
}
// Start, End, totalUploadSize tests.
for (int i = 0; i < 10; i++)
{
Assert.AreEqual(0, uploadChunkRecords[i].Start);
Assert.AreEqual(batchSizes[i] - 1, uploadChunkRecords[i].End);
Assert.IsNull(uploadChunkRecords[i].TotalUploadSize);
}
// Start, End, totalUploadSize tests.
for (int i = 0; i < 10; i++)
{
Assert.AreEqual(0, uploadChunkRecords[i].Start);
Assert.AreEqual(batchSizes[i] - 1, uploadChunkRecords[i].End);
Assert.IsNull(uploadChunkRecords[i].TotalUploadSize);
}
// Last record.
Assert.AreEqual(0, uploadChunkRecords[10].Start);
Assert.AreEqual(POSTAMBLE.Length, uploadChunkRecords[10].End + 1);
Assert.AreEqual(uploadChunkRecords[10].StartOffset + POSTAMBLE.Length,
uploadChunkRecords[10].TotalUploadSize);
}
/// <summary>
/// Tests for streaming upload with chunking.
/// </summary>
[Test]
[Category("MissingMonoSupport")]
public void TestStreamedUploadWithChunking()
{
uploadChunkRecords.Clear();
// Initialize the uploader for chunked upload.
this.Init(TEST_USER, true, CHUNK_SIZE_ALIGN * 12);
// Generate operations for upload.
Operation[] operations = GetKeywordOperations(123);
// Start the upload.
BatchUploadProgress progress = this.BeginStreamUpload("http://www.example.com");
// Split the upload into NUM_BATCHES_FOR_STREAMED_UPLOAD batches.
int[] batchSizes = new int[NUM_BATCHES_FOR_STREAMED_UPLOAD];
const int NUM_OPERATIONS_TO_UPLOAD_PER_BATCH =
NUM_KEYWORD_OPERATIONS / NUM_BATCHES_FOR_STREAMED_UPLOAD;
long uploadRequestCount = 0;
for (int i = 0; i < NUM_BATCHES_FOR_STREAMED_UPLOAD; i++)
{
Operation[] operationsToStream = new Operation[NUM_OPERATIONS_TO_UPLOAD_PER_BATCH];
Array.Copy(operations, i * NUM_OPERATIONS_TO_UPLOAD_PER_BATCH, operationsToStream,
0, NUM_OPERATIONS_TO_UPLOAD_PER_BATCH);
long oldProgress = progress.BytesUploaded;
progress = this.StreamUpload(progress, operationsToStream);
long additionalDataCount = progress.BytesUploaded - oldProgress;
uploadRequestCount += (additionalDataCount) / CHUNK_SIZE;
if ((additionalDataCount % CHUNK_SIZE) != 0)
{
uploadRequestCount += 1;
}
}
this.EndStreamUpload(progress);
uploadRequestCount += 1;
// There should be uploadRequestCount entries in uploadChunkRecords.
Assert.That(uploadChunkRecords.Count == uploadRequestCount);
for (int i = 0; i < uploadRequestCount - 1; i++)
{
long start = uploadChunkRecords[i].StartOffset + uploadChunkRecords[i].Start;
long end = uploadChunkRecords[i].StartOffset + uploadChunkRecords[i].End;
long uploaded = end - start;
// uploaded size is always a multiple of 256K
if (end - start == CHUNK_SIZE - 1)
{
Assert.Pass(string.Format("Chunk {0} is aligned with CHUNK_SIZE.", i));
}
else
{
Assert.That((uploaded + 1) % (256 * 1024) == 0,
string.Format("Chunk {0} is not aligned with 256K.", i));
}
}
}
/// <summary>
/// Tests for the GetPayload() method.
/// </summary>
[Test]
public void TestGetPayload()
{
// Generate operations for upload.
Operation[] operations = GetKeywordOperations(123);
string postBody = GetPostBody(operations);
XmlDocument xDoc = new XmlDocument();
xDoc.LoadXml(postBody);
string operationsOnly = xDoc.DocumentElement.InnerXml;
string payload = GetPayload(0, postBody);
// Ensure that operations are not duplicated in the payload
// for the initial upload.
Assert.AreEqual(AllIndexesOf(operationsOnly, payload).Count(), 1);
// Ensure that the SOAP envelope is not part of the payload
// if we already have an upload in progress.
payload = GetPayload(1, postBody);
Assert.AreEqual(operationsOnly, payload);
}
/// <summary>
/// Gets alls the indexes of <paramref name="needle"/> in <paramref name="haystack"/>.
/// </summary>
/// <param name="needle">The substring to search for.</param>
/// <param name="haystack">The string to search for <paramref name="needle"/>.</param>
/// <returns>A list of all the indices where match was found.</returns>
private static List<int> AllIndexesOf(string needle, string haystack)
{
var indexes = new List<int>();
int index = 0;
do
{
index = haystack.IndexOf(needle, index);
if (index != -1)
{
indexes.Add(index);
index++;
}
} while (index != -1);
return indexes;
}
/// <summary>
/// Tests for <see cref="Init"/> method.
/// </summary>
[Test]
[Category("MissingMonoSupport")]
public void TestInit()
{
// Any chunk size that is not a multiple of 256K should throw an
// exception if chunking is turned on.
Assert.Throws(typeof(ArgumentException),
delegate() { this.Init(TEST_USER, true, TEST_NON_MULTIPLE_CHUNK_SIZE); });
// Any chunk size that is a multiple of 256K should not throw an
// exception if chunking is turned on.
Assert.DoesNotThrow(delegate() { this.Init(TEST_USER, true, CHUNK_SIZE_ALIGN * 12); });
// Chunk size ignored if chunking is false.
Assert.DoesNotThrow(delegate()
{
this.Init(TEST_USER, false, TEST_NON_MULTIPLE_CHUNK_SIZE);
});
}
/// <summary>
/// Tests for uploads without chunking.
/// </summary>
[Test]
public void TestUploadNoChunking()
{
uploadChunkRecords.Clear();
// Upload with chunking turned off.
this.Init(TEST_USER, false, TEST_NON_MULTIPLE_CHUNK_SIZE);
Upload("http://www.example.com", TEST_DATA, 0);
// There should be one chunk record that represents the whole data.
Assert.That(uploadChunkRecords.Count == 1);
Assert.That(uploadChunkRecords[0].Start == 0);
Assert.That(uploadChunkRecords[0].End == TEST_DATA.Length - 1);
}
/// <summary>
/// Tests for uploads with chunking.
/// </summary>
[Test]
[Category("MissingMonoSupport")]
public void TestUploadWithChunking()
{
uploadChunkRecords.Clear();
int numExpectedRecords = (int) (TEST_DATA.Length / TEST_CHUNK_SIZE) + 1;
// Upload with chunking turned off.
this.Init(TEST_USER, true, TEST_CHUNK_SIZE);
Upload("http://www.example.com", TEST_DATA, 0);
// There should be TESTDATA.Length % TEST_CHUNK_SIZE + 1 chunk records.
Assert.That(uploadChunkRecords.Count == numExpectedRecords);
UploadChunkRecord record;
// There should be NUM_EXPECTED_RECORDS - 1 records of size = TEST_CHUNK_SIZE
for (int i = 0; i < numExpectedRecords - 1; i++)
{
record = uploadChunkRecords[i];
Assert.That(record.Start == i * TEST_CHUNK_SIZE);
Assert.That(record.End == record.Start + TEST_CHUNK_SIZE - 1);
}
// The last record should be the leftover data.
record = uploadChunkRecords[numExpectedRecords - 1];
Assert.That(record.Start == (numExpectedRecords - 1) * TEST_CHUNK_SIZE);
Assert.That(record.End == TEST_DATA.Length - 1);
}
/// <summary>
/// Tests for uploads with chunking and resuming an interrupted upload.
/// </summary>
[Test]
[Category("MissingMonoSupport")]
public void TestUploadWithResumeAndChunking()
{
uploadChunkRecords.Clear();
Operation[] operations = GetKeywordOperations(1000);
string postBody = GetPostBody(operations);
byte[] data = Encoding.UTF8.GetBytes(postBody);
this.Init(TEST_USER, true, TEST_CHUNK_SIZE);
Upload("http://www.example.com", operations, true);
long numExpectedRecords =
1 + (data.Length - TESTDATA_UPLOAD_PROGRESS) / TEST_CHUNK_SIZE;
Assert.That(uploadChunkRecords.Count == numExpectedRecords);
for (int i = 0; i < numExpectedRecords; i++)
{
Assert.AreEqual(uploadChunkRecords[i].Start, TEST_CHUNK_SIZE * i);
if (i == numExpectedRecords - 1)
{
Assert.AreEqual(uploadChunkRecords[i].End,
data.Length - TESTDATA_UPLOAD_PROGRESS - 1);
}
else
{
Assert.AreEqual(uploadChunkRecords[i].End,
uploadChunkRecords[i].Start + TEST_CHUNK_SIZE - 1);
}
Assert.AreEqual(uploadChunkRecords[i].StartOffset, TESTDATA_UPLOAD_PROGRESS);
Assert.AreEqual(uploadChunkRecords[i].TotalUploadSize, data.Length);
}
}
/// <summary>
/// Tests for GetTextToLog method.
/// </summary>
[Test]
public void TestGetTextToLog()
{
// When using ASCII characters only, you should get the actual number of chars
// requested, since 1 byte == 1 char.
string textToLog = "ABCDE";
Assert.AreEqual("ABC", GetTextToLog(Encoding.UTF8.GetBytes(textToLog), 0, 3));
// If you pass indices out of range of the array, exception is thrown.
Assert.Throws<ArgumentOutOfRangeException>(delegate()
{
GetTextToLog(Encoding.UTF8.GetBytes(textToLog), 10, 20);
});
string utf8TextToLog = "こんにちは"; // Hello
// こ is // \u3053, and its UTF-8 representation is \xe3\x81\x93.
// So you get back 1 char.
Assert.AreEqual("こ", GetTextToLog(Encoding.UTF8.GetBytes(utf8TextToLog), 0, 3));
// When you request 4 bytes, the first 3 bytes are used to decode to こ, and the fourth
// byte is malformed. So unicode replacement character (\uFFFD) is used.
Assert.AreEqual("こ\uFFFD", GetTextToLog(Encoding.UTF8.GetBytes(utf8TextToLog), 0, 4));
// When you request 3 bytes, the stream is misaligned, so you get three unicode
// replacement characters (\uFFFD\uFFFD\uFFFD).
Assert.AreEqual("\uFFFD\uFFFD\uFFFD",
GetTextToLog(Encoding.UTF8.GetBytes(utf8TextToLog), 1, 3));
}
/// <summary>
/// Gets an array of keyword operations for testing upload.
/// </summary>
/// <param name="adGroupId">The ad group ID.</param>
/// <returns>An array of operations.</returns>
private Operation[] GetKeywordOperations(long adGroupId)
{
List<Operation> operations = new List<Operation>();
for (int i = 0; i < NUM_KEYWORD_OPERATIONS; i++)
{
// Create the keyword.
Keyword keyword = new Keyword();
keyword.text = "Test keyword " + i;
keyword.matchType = KeywordMatchType.BROAD;
// Create the biddable ad group criterion.
BiddableAdGroupCriterion keywordCriterion = new BiddableAdGroupCriterion();
keywordCriterion.adGroupId = adGroupId;
keywordCriterion.criterion = keyword;
// Optional: Set the user status.
keywordCriterion.userStatus = UserStatus.PAUSED;
// Create the operations.
AdGroupCriterionOperation operation = new AdGroupCriterionOperation();
operation.@operator = Operator.ADD;
operation.operand = keywordCriterion;
operations.Add(operation);
}
return operations.ToArray();
}
#region Mocked methods
/// <summary>
/// Initializes a new instance of the <see cref="BatchJobUtilitiesTest"/> class.
/// </summary>
public BatchJobUtilitiesTest() : base(new AdWordsUser())
{
}
/// <summary>
/// Uploads a chunk of data for the batch job.
/// </summary>
/// <param name="url">The resumable upload URL.</param>
/// <param name="postBody">The post body.</param>
/// <param name="start">The start of range of bytes to be uploaded.</param>
/// <param name="end">The end of range of bytes to be uploaded.</param>
/// <param name="startOffset">The start offset in the stream to upload to.</param>
/// <param name="totalUploadSize">If specified, this indicates the total
/// size of the upload. When doing a streamed upload, this value will be
/// null for all except the last chunk.</param>
protected override void UploadChunk(string url, byte[] postBody, int start, int end,
long startOffset, long? totalUploadSize)
{
uploadChunkRecords.Add(new UploadChunkRecord()
{
Start = start,
End = end,
StartOffset = startOffset,
TotalUploadSize = totalUploadSize
});
}
/// <summary>
/// Gets the upload progress.
/// </summary>
/// <param name="url">The resumable upload URL.</param>
/// <returns>
/// The number of bytes uploaded so far.
/// </returns>
protected override int GetUploadProgress(string url)
{
return TESTDATA_UPLOAD_PROGRESS;
}
#endregion Mocked methods
}
}
| 38.612903 | 99 | 0.571625 |
[
"Apache-2.0"
] |
CoryLiseno/googleads-dotnet-lib
|
tests/AdWords/Util/BatchJob/v201809/BatchJobUtilitiesTest.cs
| 20,369 |
C#
|
// --------------------------------------------------------------------------------------------------------------------
// <copyright company="Chocolatey" file="AdvancedInstallViewModel.cs">
// Copyright 2017 - Present Chocolatey Software, LLC
// Copyright 2014 - 2017 Rob Reynolds, the maintainers of Chocolatey, and RealDimensions Software, LLC
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Input;
using chocolatey;
using ChocolateyGui.Common.Base;
using ChocolateyGui.Common.Properties;
using ChocolateyGui.Common.Services;
using ChocolateyGui.Common.Windows.Commands;
using ChocolateyGui.Common.Windows.Controls.Dialogs;
using ChocolateyGui.Common.Windows.Utilities;
using NuGet;
namespace ChocolateyGui.Common.Windows.ViewModels
{
public class AdvancedInstallViewModel : ObservableBase, IClosableChildWindow<AdvancedInstallViewModel>
{
private readonly IChocolateyService _chocolateyService;
private readonly IPersistenceService _persistenceService;
private CancellationTokenSource _cts;
private string _selectedVersion;
private bool _includePreRelease;
private Utilities.NotifyTaskCompletion<ObservableCollection<string>> _availableVersions;
private string _packageParamaters;
private string _installArguments;
private int _executionTimeoutInSeconds;
private string _logFile;
private string _cacheLocation;
private bool _preRelease;
private bool _forcex86;
private bool _overrideArguments;
private bool _notSilent;
private bool _applyInstallArgumentsToDependencies;
private bool _applyPackageParametersToDependencies;
private bool _allowDowngrade;
private bool _allowMultipleVersions;
private bool _ignoreDependencies;
private bool _forceDependencies;
private bool _skipPowerShell;
private bool _ignoreChecksums;
private bool _allowEmptyChecksums;
private bool _allowEmptyChecksumsSecure;
private bool _requireChecksums;
private string _downloadChecksum;
private string _downloadChecksum64bit;
private string _downloadChecksumType;
private string _downloadChecksumType64bit;
private List<string> _availableChecksumTypes;
private string _packageVersion;
public AdvancedInstallViewModel(
IChocolateyService chocolateyService,
IPersistenceService persistenceService,
SemanticVersion packageVersion)
{
_chocolateyService = chocolateyService;
_persistenceService = persistenceService;
_cts = new CancellationTokenSource();
_packageVersion = packageVersion.ToString();
SelectedVersion = _packageVersion;
FetchAvailableVersions();
AvailableChecksumTypes = new List<string> { "md5", "sha1", "sha256", "sha512" };
InstallCommand = new RelayCommand(
o => { Close?.Invoke(this); },
o => string.IsNullOrEmpty(SelectedVersion) || SelectedVersion == Resources.AdvancedChocolateyDialog_LatestVersion || SemanticVersion.TryParse(SelectedVersion, out _));
CancelCommand = new RelayCommand(
o =>
{
_cts.Cancel();
Close?.Invoke(null);
},
o => true);
BrowseLogFileCommand = new RelayCommand(BrowseLogFile);
BrowseCacheLocationCommand = new RelayCommand(BrowseCacheLocation);
SetDefaults();
}
public string SelectedVersion
{
get
{
return _selectedVersion;
}
set
{
SetPropertyValue(ref _selectedVersion, value);
OnSelectedVersionChanged(value);
}
}
public bool IncludePreRelease
{
get
{
return _includePreRelease;
}
set
{
if (SetPropertyValue(ref _includePreRelease, value))
{
_cts.Cancel();
_cts.Dispose();
_cts = new CancellationTokenSource();
FetchAvailableVersions();
}
}
}
public Utilities.NotifyTaskCompletion<ObservableCollection<string>> AvailableVersions
{
get { return _availableVersions; }
set { SetPropertyValue(ref _availableVersions, value); }
}
public string PackageParameters
{
get { return _packageParamaters; }
set { SetPropertyValue(ref _packageParamaters, value); }
}
public string InstallArguments
{
get { return _installArguments; }
set { SetPropertyValue(ref _installArguments, value); }
}
public int ExecutionTimeoutInSeconds
{
get { return _executionTimeoutInSeconds; }
set { SetPropertyValue(ref _executionTimeoutInSeconds, value); }
}
public string LogFile
{
get { return _logFile; }
set { SetPropertyValue(ref _logFile, value); }
}
public string CacheLocation
{
get { return _cacheLocation; }
set { SetPropertyValue(ref _cacheLocation, value); }
}
public bool PreRelease
{
get { return _preRelease; }
set { SetPropertyValue(ref _preRelease, value); }
}
public bool Forcex86
{
get { return _forcex86; }
set { SetPropertyValue(ref _forcex86, value); }
}
public bool OverrideArguments
{
get
{
return _overrideArguments;
}
set
{
SetPropertyValue(ref _overrideArguments, value);
if (value)
{
NotSilent = false;
}
}
}
public bool NotSilent
{
get
{
return _notSilent;
}
set
{
SetPropertyValue(ref _notSilent, value);
if (value)
{
OverrideArguments = false;
}
}
}
public bool ApplyInstallArgumentsToDependencies
{
get { return _applyInstallArgumentsToDependencies; }
set { SetPropertyValue(ref _applyInstallArgumentsToDependencies, value); }
}
public bool ApplyPackageParametersToDependencies
{
get { return _applyPackageParametersToDependencies; }
set { SetPropertyValue(ref _applyPackageParametersToDependencies, value); }
}
public bool AllowDowngrade
{
get { return _allowDowngrade; }
set { SetPropertyValue(ref _allowDowngrade, value); }
}
public bool AllowMultipleVersions
{
get { return _allowMultipleVersions; }
set { SetPropertyValue(ref _allowMultipleVersions, value); }
}
public bool IgnoreDependencies
{
get
{
return _ignoreDependencies;
}
set
{
SetPropertyValue(ref _ignoreDependencies, value);
if (value)
{
ForceDependencies = false;
}
}
}
public bool ForceDependencies
{
get
{
return _forceDependencies;
}
set
{
SetPropertyValue(ref _forceDependencies, value);
if (value)
{
IgnoreDependencies = false;
}
}
}
public bool SkipPowerShell
{
get
{
return _skipPowerShell;
}
set
{
SetPropertyValue(ref _skipPowerShell, value);
if (value)
{
OverrideArguments = false;
NotSilent = false;
}
}
}
public bool IgnoreChecksums
{
get
{
return _ignoreChecksums;
}
set
{
SetPropertyValue(ref _ignoreChecksums, value);
if (value)
{
RequireChecksums = false;
}
}
}
public bool AllowEmptyChecksums
{
get
{
return _allowEmptyChecksums;
}
set
{
SetPropertyValue(ref _allowEmptyChecksums, value);
if (value)
{
RequireChecksums = false;
}
}
}
public bool AllowEmptyChecksumsSecure
{
get
{
return _allowEmptyChecksumsSecure;
}
set
{
SetPropertyValue(ref _allowEmptyChecksumsSecure, value);
if (value)
{
RequireChecksums = false;
}
}
}
public bool RequireChecksums
{
get
{
return _requireChecksums;
}
set
{
SetPropertyValue(ref _requireChecksums, value);
if (value)
{
IgnoreChecksums = false;
AllowEmptyChecksums = false;
AllowEmptyChecksumsSecure = false;
}
}
}
public string DownloadChecksum
{
get { return _downloadChecksum; }
set { SetPropertyValue(ref _downloadChecksum, value); }
}
public string DownloadChecksum64bit
{
get { return _downloadChecksum64bit; }
set { SetPropertyValue(ref _downloadChecksum64bit, value); }
}
public string DownloadChecksumType
{
get
{
return _downloadChecksumType;
}
set
{
SetPropertyValue(ref _downloadChecksumType, value);
DownloadChecksumType64bit = value;
}
}
public string DownloadChecksumType64bit
{
get { return _downloadChecksumType64bit; }
set { SetPropertyValue(ref _downloadChecksumType64bit, value); }
}
public List<string> AvailableChecksumTypes
{
get { return _availableChecksumTypes; }
set { SetPropertyValue(ref _availableChecksumTypes, value); }
}
public ICommand InstallCommand { get; }
public ICommand CancelCommand { get; }
public ICommand BrowseLogFileCommand { get; }
public ICommand BrowseCacheLocationCommand { get; }
/// <inheritdoc />
public Action<AdvancedInstallViewModel> Close { get; set; }
private void FetchAvailableVersions()
{
var availableVersions = new ObservableCollection<string>();
availableVersions.Add(Resources.AdvancedChocolateyDialog_LatestVersion);
if (!string.IsNullOrEmpty(_packageVersion))
{
availableVersions.Add(_packageVersion);
}
AvailableVersions =
new NotifyTaskCompletion<ObservableCollection<string>>(Task.FromResult(availableVersions));
}
private void SetDefaults()
{
var choco = Lets.GetChocolatey();
var config = choco.GetConfiguration();
DownloadChecksumType = "md5";
DownloadChecksumType64bit = "md5";
ExecutionTimeoutInSeconds = config.CommandExecutionTimeoutSeconds;
CacheLocation = config.CacheLocation;
LogFile = config.AdditionalLogFileLocation;
}
private void OnSelectedVersionChanged(string stringVersion)
{
SemanticVersion version;
if (SemanticVersion.TryParse(stringVersion, out version))
{
PreRelease = !string.IsNullOrEmpty(version.SpecialVersion);
}
}
private void BrowseLogFile(object value)
{
var filter = "{0}|{1}|{2}".format_with(
L(nameof(Resources.FilePicker_LogFiles)) + "|*.log;*.klg",
L(nameof(Resources.FilePicker_TextFiles)) + "|*.txt;*.text;*.plain",
L(nameof(Resources.FilePicker_AllFiles)) + "|*.*");
var logFile = _persistenceService.GetFilePath("log", filter);
if (!string.IsNullOrEmpty(logFile))
{
LogFile = logFile;
}
}
private void BrowseCacheLocation(object value)
{
var description = L(nameof(Resources.AdvancedChocolateyDialog_CacheLocation_BrowseDescription));
var cacheDirectory = _persistenceService.GetFolderPath(CacheLocation, description);
if (!string.IsNullOrEmpty(cacheDirectory))
{
CacheLocation = cacheDirectory;
}
}
}
}
| 30.181435 | 184 | 0.517056 |
[
"Apache-2.0"
] |
BearerPipelineTest/ChocolateyGUI
|
Source/ChocolateyGui.Common.Windows/ViewModels/AdvancedInstallViewModel.cs
| 14,308 |
C#
|
using System.Threading.Tasks;
using SalesOrder.Models;
namespace SalesOrder.ServiceBus.Helpers
{
public interface IStorageQueueHelper
{
Task SendToSalesOrderMessageQueue(SalesOrder.Models.SalesOrder salesOrderData);
Task<Models.SalesOrder?> GetNextOrderFromMessageQueue();
Task ConfirmSalesOrderToMessageQueue(Models.SalesOrder value);
}
}
| 29.692308 | 87 | 0.756477 |
[
"MIT"
] |
DickBaker/C-8-and-.NET-Core-3-Projects-Using-Azure-Second-Edition
|
Chapter08/SalesOrder.ServiceBus/ServiceBus/IStorageQueueHelper.cs
| 388 |
C#
|
// Copyright (c) SecretCollect B.V. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE file in the project root for license information.
//
// Based upon work by Michiel van Oudheusden
// https://github.com/mivano/EFIndexInclude
// Changes:
// - Moved SqlServer:IncludeIndex to constant
// - Changed namespace to accomodate easy usage
using Microsoft.EntityFrameworkCore.Internal;
using SecretCollect.EntityFramework;
using System;
using System.Linq.Expressions;
using System.Text;
namespace Microsoft.EntityFrameworkCore.Metadata.Builders
{
/// <summary>
/// Extentions class for <see cref="IndexBuilder"/>
/// </summary>
public static class IndexExtensions
{
/// <summary>
/// Include columns in the index
/// </summary>
/// <typeparam name="TEntity">The entity for which an index is being created</typeparam>
/// <param name="indexBuilder">The builder</param>
/// <param name="indexExpression">The expression that selects the columns</param>
/// <returns>The indexbuilder for chaining purposes</returns>
public static IndexBuilder Include<TEntity>(this IndexBuilder indexBuilder, Expression<Func<TEntity, object>> indexExpression)
{
var includeStatement = new StringBuilder();
foreach (var column in indexExpression.GetPropertyAccessList())
{
if (includeStatement.Length > 0)
includeStatement.Append(", ");
includeStatement.AppendFormat("[{0}]", column.Name);
}
indexBuilder.HasAnnotation(Constants.INCLUDE_INDEX, includeStatement.ToString());
return indexBuilder;
}
}
}
| 37.06383 | 134 | 0.669346 |
[
"Apache-2.0"
] |
SecretView/EntityFramework
|
src/SecretCollect.EntityFramework/Extensions/IndexExtensions.cs
| 1,742 |
C#
|
namespace PhotoShare.Client.Core.Commands
{
using System;
using Data;
using Models;
using Contracts;
using Services.Contracts;
public class ShareAlbumCommand : ICommand
{
private readonly IAlbumService albumService;
public ShareAlbumCommand(IAlbumService albumService)
{
this.albumService = albumService;
}
// ShareAlbum <albumId> <username> <permission>
// For example:
// ShareAlbum 4 dragon321 Owner
// ShareAlbum 4 dragon11 Viewer
public string Execute(params string[] data)
{
var albumId = int.Parse(data[0]);
var username = data[1];
var permission = data[2];
var isOwner = albumService.IsOwner(Session.User, albumId);
if (!isOwner)
{
throw new ArgumentException("Invalid credentials!");
}
albumService.ShareAlbum(albumId, username, permission);
var context = new PhotoShareContext();
Album album;
using (context)
{
album = context.Albums.Find(albumId);
}
return $"Username {username} added to album {album.Name} ({permission})";
}
}
}
| 25.431373 | 85 | 0.55744 |
[
"MIT"
] |
jackofdiamond5/Software-University
|
C# DB Fundamentals/DB Advanced - EF Core/PhotoShare/PhotoShare.Client/Core/Commands/ShareAlbumCommand.cs
| 1,299 |
C#
|
using System;
using System.CodeDom.Compiler;
using System.Xml.Serialization;
namespace Workday.Recruiting
{
[GeneratedCode("System.Xml", "4.6.1590.0"), XmlType(Namespace = "urn:com.workday/bsvc", IncludeInSchema = false)]
[Serializable]
public enum ItemChoiceType5
{
Social_Network_Account_URL,
Social_Network_Account_User_Name
}
}
| 22.8 | 114 | 0.780702 |
[
"MIT"
] |
matteofabbri/Workday.WebServices
|
Workday.Recruiting/ItemChoiceType5.cs
| 342 |
C#
|
#if UNITY_IOS && UNITY_EDITOR
using UnityEditor.iOS.Xcode;
namespace PostprocessCollection
{
/// <summary>
/// Writes properties to Info.plist file of XCode project
/// with given values.
/// For example:
/// ITSAppUsesNonExemptEncryption false - claims that your app doesn't use encryption
/// GADApplicationIdentifier - ca-app-pub-3940256099942544~1458002511 - set Google Ads Plugin app id
/// GADIsAdManagerApp true - another key, needed to make your app work with Google Ads Plugin
/// </summary>
public static class AddPropertiesPostprocess
{
public static void AddProperties(PlistDocument plist, PlistKeys keys)
{
if(keys == null) return;
if (keys.StringKeys != null)
{
foreach (var key in keys.StringKeys)
plist.root.SetString(key.Name, key.Value);
}
if (keys.IntKeys != null)
{
foreach (var key in keys.IntKeys)
plist.root.SetInteger(key.Name, key.Value);
}
if (keys.BoolKeys != null)
{
foreach (var key in keys.BoolKeys)
plist.root.SetBoolean(key.Name, key.Value);
}
if (keys.FloatKeys != null)
{
foreach (var key in keys.FloatKeys)
plist.root.SetReal(key.Name, key.Value);
}
}
}
}
#endif
| 30.86 | 105 | 0.533377 |
[
"MIT"
] |
vmchar/iOSPostprocessCollection
|
Postprocess Collection/Assets/PostprocessCollection/AddPropertiesPostprocess.cs
| 1,545 |
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StatureTool
{
public class OLV_MappingDetails
{
public int index { get; set; }
public string mrn { get; set; }
public string course { get; set; }
public string plan { get; set; }
//DateTime planDate { get; set; }
public string structureName { get; set; }
public double volume { get; set; }
public double d95 { get; set; }
public double dMean { get; set; }
public double dMedian { get; set; }
public string mappingStatus { get; set; }
public string templateName { get; set; }
public int tnMatchCount { get; set; }
public string group { get; set; }
//public OLV_MappingDetails(string mrn, string course, string plan, DateTime planDate, string structureName, double volume, double d95, string mappingStatus, string templateName, int tnMatchCount, string group)
public OLV_MappingDetails(int index, string mrn, string course, string plan, string structureName, double volume, double d95, double dMean, double dMedian, string mappingStatus, string templateName, int tnMatchCount, string group)
{
this.index = index;
this.mrn = mrn;
this.course = course;
this.plan = plan;
//this.planDate = planDate;
this.structureName = structureName;
this.volume = volume;
this.d95 = d95;
this.dMean = dMean;
this.dMedian = dMedian;
this.mappingStatus = mappingStatus;
this.templateName = templateName;
this.tnMatchCount = tnMatchCount;
this.group = group;
}
}
}
| 39.043478 | 238 | 0.619154 |
[
"Apache-2.0"
] |
tschuler/StatureTool
|
StatureTool/OLV_Models.cs
| 1,798 |
C#
|
using UniRx;
using UniRx.Triggers;
using UnityEngine;
namespace Samples.Section4.Filters
{
public class DistinctSample2 : MonoBehaviour
{
private void Start()
{
this.OnCollisionEnterAsObservable()
// 過去に衝突したことがあるGameObjectは無視
.Distinct(x => x.gameObject)
.Subscribe(x => Debug.Log(x.gameObject.name));
}
}
}
| 23.823529 | 62 | 0.592593 |
[
"Unlicense",
"CC0-1.0",
"MIT"
] |
TORISOUP/UniRx-UniTask_Samples
|
Assets/Samples/Section4/Filters/DistinctSample2.cs
| 437 |
C#
|
#pragma checksum "C:\Users\Michael Douglas\Documents\GitHub\FormacaoAspNetCoreExpertDesenvolvedorIO\DominandoAspNetMVCCore\PrimeiraAppMvcCore\AppModelo\src\DevIO.UI.Site\Views\_ViewStart.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "fb15a6fa2b9e89da8d14e27ff92faedafbbc5199"
// <auto-generated/>
#pragma warning disable 1591
[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views__ViewStart), @"mvc.1.0.view", @"/Views/_ViewStart.cshtml")]
namespace AspNetCore
{
#line hidden
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
#nullable restore
#line 1 "C:\Users\Michael Douglas\Documents\GitHub\FormacaoAspNetCoreExpertDesenvolvedorIO\DominandoAspNetMVCCore\PrimeiraAppMvcCore\AppModelo\src\DevIO.UI.Site\Views\_ViewImports.cshtml"
using DevIO.UI.Site;
#line default
#line hidden
#nullable disable
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"fb15a6fa2b9e89da8d14e27ff92faedafbbc5199", @"/Views/_ViewStart.cshtml")]
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"d422f58880ba81cb40380a31cef49b3445cddf72", @"/Views/_ViewImports.cshtml")]
public class Views__ViewStart : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<dynamic>
{
#pragma warning disable 1998
public async override global::System.Threading.Tasks.Task ExecuteAsync()
{
#nullable restore
#line 1 "C:\Users\Michael Douglas\Documents\GitHub\FormacaoAspNetCoreExpertDesenvolvedorIO\DominandoAspNetMVCCore\PrimeiraAppMvcCore\AppModelo\src\DevIO.UI.Site\Views\_ViewStart.cshtml"
Layout = "_Layout";
#line default
#line hidden
#nullable disable
}
#pragma warning restore 1998
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<dynamic> Html { get; private set; }
}
}
#pragma warning restore 1591
| 55.403846 | 278 | 0.781326 |
[
"MIT"
] |
MichaelDouglasGit/FormacaoAspNetCoreExpertDesenvolvedorIO
|
DominandoAspNetMVCCore/PrimeiraAppMvcCore/AppModelo/src/DevIO.UI.Site/obj/Debug/netcoreapp3.1/Razor/Views/_ViewStart.cshtml.g.cs
| 2,881 |
C#
|
/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using ReaderException = com.google.zxing.ReaderException;
using BitMatrix = com.google.zxing.common.BitMatrix;
using DecoderResult = com.google.zxing.common.DecoderResult;
using GF256 = com.google.zxing.common.reedsolomon.GF256;
using ReedSolomonDecoder = com.google.zxing.common.reedsolomon.ReedSolomonDecoder;
using ReedSolomonException = com.google.zxing.common.reedsolomon.ReedSolomonException;
namespace com.google.zxing.datamatrix.decoder
{
/// <summary> <p>The main class which implements Data Matrix Code decoding -- as opposed to locating and extracting
/// the Data Matrix Code from an image.</p>
///
/// </summary>
/// <author> [email protected] (Brian Brown)
/// </author>
/// <author>www.Redivivus.in ([email protected]) - Ported from ZXING Java Source
/// </author>
public sealed class Decoder
{
//UPGRADE_NOTE: Final was removed from the declaration of 'rsDecoder '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
private ReedSolomonDecoder rsDecoder;
public Decoder()
{
rsDecoder = new ReedSolomonDecoder(GF256.DATA_MATRIX_FIELD);
}
/// <summary> <p>Convenience method that can decode a Data Matrix Code represented as a 2D array of booleans.
/// "true" is taken to mean a black module.</p>
///
/// </summary>
/// <param name="image">booleans representing white/black Data Matrix Code modules
/// </param>
/// <returns> text and bytes encoded within the Data Matrix Code
/// </returns>
/// <throws> ReaderException if the Data Matrix Code cannot be decoded </throws>
public DecoderResult decode(bool[][] image)
{
int dimension = image.Length;
BitMatrix bits = new BitMatrix(dimension);
for (int i = 0; i < dimension; i++)
{
for (int j = 0; j < dimension; j++)
{
if (image[i][j])
{
bits.set_Renamed(j, i);
}
}
}
return decode(bits);
}
/// <summary> <p>Decodes a Data Matrix Code represented as a {@link BitMatrix}. A 1 or "true" is taken
/// to mean a black module.</p>
///
/// </summary>
/// <param name="bits">booleans representing white/black Data Matrix Code modules
/// </param>
/// <returns> text and bytes encoded within the Data Matrix Code
/// </returns>
/// <throws> ReaderException if the Data Matrix Code cannot be decoded </throws>
public DecoderResult decode(BitMatrix bits)
{
// Construct a parser and read version, error-correction level
BitMatrixParser parser = new BitMatrixParser(bits);
Version version = parser.readVersion(bits);
// Read codewords
sbyte[] codewords = parser.readCodewords();
// Separate into data blocks
DataBlock[] dataBlocks = DataBlock.getDataBlocks(codewords, version);
// Count total number of data bytes
int totalBytes = 0;
for (int i = 0; i < dataBlocks.Length; i++)
{
totalBytes += dataBlocks[i].NumDataCodewords;
}
sbyte[] resultBytes = new sbyte[totalBytes];
int resultOffset = 0;
// Error-correct and copy data blocks together into a stream of bytes
for (int j = 0; j < dataBlocks.Length; j++)
{
DataBlock dataBlock = dataBlocks[j];
sbyte[] codewordBytes = dataBlock.Codewords;
int numDataCodewords = dataBlock.NumDataCodewords;
correctErrors(codewordBytes, numDataCodewords);
for (int i = 0; i < numDataCodewords; i++)
{
resultBytes[resultOffset++] = codewordBytes[i];
}
}
// Decode the contents of that stream of bytes
return DecodedBitStreamParser.decode(resultBytes);
}
/// <summary> <p>Given data and error-correction codewords received, possibly corrupted by errors, attempts to
/// correct the errors in-place using Reed-Solomon error correction.</p>
///
/// </summary>
/// <param name="codewordBytes">data and error correction codewords
/// </param>
/// <param name="numDataCodewords">number of codewords that are data bytes
/// </param>
/// <throws> ReaderException if error correction fails </throws>
private void correctErrors(sbyte[] codewordBytes, int numDataCodewords)
{
int numCodewords = codewordBytes.Length;
// First read into an array of ints
int[] codewordsInts = new int[numCodewords];
for (int i = 0; i < numCodewords; i++)
{
codewordsInts[i] = codewordBytes[i] & 0xFF;
}
int numECCodewords = codewordBytes.Length - numDataCodewords;
try
{
rsDecoder.decode(codewordsInts, numECCodewords);
}
catch (ReedSolomonException rse)
{
throw ReaderException.Instance;
}
// Copy back into array of bytes -- only need to worry about the bytes that were data
// We don't care about errors in the error-correction codewords
for (int i = 0; i < numDataCodewords; i++)
{
codewordBytes[i] = (sbyte) codewordsInts[i];
}
}
}
}
| 36.431373 | 183 | 0.676175 |
[
"Apache-2.0"
] |
LeonidRulit/zxing1
|
csharp/datamatrix/decoder/Decoder.cs
| 5,574 |
C#
|
using System.Runtime.InteropServices;
namespace Ship_Game
{
public class PerfTimer
{
[DllImport("Kernel32.dll")]
private static extern bool QueryPerformanceCounter(out long perfcount);
[DllImport("Kernel32.dll")]
private static extern bool QueryPerformanceFrequency(out long freq);
private static readonly long Frequency;
private long Time;
public float AvgTime { get; private set; }
public float MaxTime { get; private set; }
public int NumSamples { get; private set; }
static PerfTimer()
{
QueryPerformanceFrequency(out Frequency);
}
public static PerfTimer StartNew()
{
var t = new PerfTimer();
t.Start();
return t;
}
// start perf timer
public void Start()
{
QueryPerformanceCounter(out Time);
}
// Get intermediate sampling value that isn't stored
// (in seconds)
public float Elapsed
{
get
{
QueryPerformanceCounter(out long end);
return (float)((double)(end - Time) / Frequency);
}
}
public float ElapsedMillis => Elapsed * 1000f;
// stop and gather performance sample
public void Stop()
{
QueryPerformanceCounter(out long end);
float elapsed = (float)((double)(end - Time) / Frequency);
AvgTime = (AvgTime*NumSamples + elapsed) / (NumSamples + 1);
// Well... this is kinda complicated to do without a list indeed
if (elapsed > MaxTime) MaxTime = elapsed;
else MaxTime *= 0.98f; // trickle down towards avg time
++NumSamples;
}
public override string ToString()
{
return $"{AvgTime*1000f:0.0,5}ms ({MaxTime*1000f:0.0,5}ms)";
}
}
}
| 28.774648 | 86 | 0.524719 |
[
"MIT"
] |
UnGaucho/StarDrive
|
Ship_Game/Utils/PerfTimer.cs
| 2,045 |
C#
|
using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Android.Support.Wearable.Views;
using Android.Support.V4.App;
using Android.Support.V4.View;
using Android.Support.Wearable.Activity;
using Java.Interop;
using Android.Views.Animations;
using System.Net;
using System.IO;
using Newtonsoft.Json;
using System.Threading.Tasks;
using System.Timers;
namespace App4
{
[Activity(Label = "@string/app_name", MainLauncher = true)]
public class MainActivity : WearableActivity
{
public void RefreshWeather()
{
string token = "d827fff2c3d14e37ebf57321e477e96f";
string url = "http://api.openweathermap.org/data/2.5/weather?q=Yakutsk&APPID=" + token;
try
{
// Создаем реквест
HttpWebRequest httpWebRequest = new HttpWebRequest(new Uri(url));
// Получаем респонз и из него получаемстрим
var jsonStream = new StreamReader(httpWebRequest.GetResponse().GetResponseStream());
// Считываем стрим до конца в строку
var json = jsonStream.ReadToEnd();
// Разбираем Json в класс
dynamic weatherClass = JsonConvert.DeserializeObject(json);
// Обновляем температуру
FindViewById<TextView>(Resource.Id.text).Text = ((int)weatherClass.main.temp - 273).ToString() + " C";
}
catch
{
// В случае ошибки
FindViewById<TextView>(Resource.Id.text).Text = "Ошибка загрузки данных с сервера";
}
}
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.activity_main);
SetAmbientEnabled();
// Добавлено
// Запускаем тред с обновлениемтемпературы
RunOnUiThread(async () =>
{
while (true)
{
// Функция обновления температуры
RefreshWeather();
// Ждем секунду
await Task.Delay(10000);
}
});
}
}
}
| 31.891892 | 119 | 0.561017 |
[
"MIT"
] |
PavlenkoDR/World-Skills-Juniors
|
Code/App4/App4/App4/MainActivity.cs
| 2,599 |
C#
|
using I18nMigrationTool.Services.Models;
using System.Collections.Generic;
using System.IO;
namespace I18nMigrationTool.Services
{
public class ReportService
{
public static void CreateReport(List<Translation> translations, string filepath, List<I18NFile> i18NTranslations)
{
using (StreamWriter writer = new StreamWriter(new FileStream(filepath, FileMode.Create, FileAccess.Write)))
{
writer.WriteLine("i18NKey;jsonKey;IsEligibleToMigrate;MigrationDone;Language;Tag");
foreach (var translation in translations)
{
foreach (var translationSingle in translation.TranslationSingles)
{
writer.WriteLine($"{translation.I18NKey};{translation.JsonKey};{translation.IsEligibleToMigrate};{translation.MigrationDone};{translationSingle.CultureInfo.Name};{translationSingle.Tag}");
}
}
}
}
}
}
| 38.692308 | 212 | 0.639165 |
[
"MIT"
] |
YounitedCredit/Younited.I18nMigrationTool
|
I18nMigrationTool.Services/ReportService.cs
| 1,008 |
C#
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Gw2.Models.Commerce
{
/// <summary>
/// GW2 commerce Item
/// </summary>
public class Item
{
/// <summary>
/// Id of the Item
/// </summary>
public int Id { get; set; }
/// <summary>
/// Count of the Items
/// </summary>
public int Count { get; set; }
}
}
| 18.434783 | 38 | 0.509434 |
[
"Apache-2.0"
] |
jjoaoclaro/Gw2Bacalhaus
|
Gw2/Models/Commerce/Item.cs
| 426 |
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 codestar-connections-2019-12-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.CodeStarconnections.Model
{
/// <summary>
/// This is the response object from the CreateHost operation.
/// </summary>
public partial class CreateHostResponse : AmazonWebServiceResponse
{
private string _hostArn;
private List<Tag> _tags = new List<Tag>();
/// <summary>
/// Gets and sets the property HostArn.
/// <para>
/// The Amazon Resource Name (ARN) of the host to be created.
/// </para>
/// </summary>
[AWSProperty(Min=0, Max=256)]
public string HostArn
{
get { return this._hostArn; }
set { this._hostArn = value; }
}
// Check to see if HostArn property is set
internal bool IsSetHostArn()
{
return this._hostArn != null;
}
/// <summary>
/// Gets and sets the property Tags.
/// </summary>
[AWSProperty(Min=0, Max=200)]
public List<Tag> Tags
{
get { return this._tags; }
set { this._tags = value; }
}
// Check to see if Tags property is set
internal bool IsSetTags()
{
return this._tags != null && this._tags.Count > 0;
}
}
}
| 28.866667 | 118 | 0.614781 |
[
"Apache-2.0"
] |
ChristopherButtars/aws-sdk-net
|
sdk/src/Services/CodeStarconnections/Generated/Model/CreateHostResponse.cs
| 2,165 |
C#
|
//-----------------------------------------------------------------------------
// Copyright : (c) Chris Moore, 2020
// License : MIT
//-----------------------------------------------------------------------------
namespace Z0
{
using System;
using System.Runtime.CompilerServices;
using System.Runtime.Intrinsics;
using static Root;
using static SFx;
partial struct CalcHosts
{
[Closures(AllNumeric), Nonz]
public readonly struct VNonZ128<T> : IUnaryPred128D<T>
where T : unmanaged
{
[MethodImpl(Inline)]
public bit Invoke(Vector128<T> x)
=> gcpu.vnonz(x);
[MethodImpl(Inline)]
public bit Invoke(T a)
=> gmath.nonz(a);
}
[Closures(AllNumeric), Nonz]
public readonly struct VNonZ256<T> : IUnaryPred256D<T>
where T : unmanaged
{
[MethodImpl(Inline)]
public bit Invoke(Vector256<T> x)
=> gcpu.vnonz(x);
[MethodImpl(Inline)]
public bit Invoke(T a)
=> gmath.nonz(a);
}
[Closures(AllNumeric), Nonz]
public readonly struct Nonz<T> : IFunc<T,bit>, IUnarySpanPred<T>
where T : unmanaged
{
[MethodImpl(Inline)]
public bit Invoke(T a)
=> gmath.nonz(a);
[MethodImpl(Inline)]
public Span<bit> Invoke(ReadOnlySpan<T> src, Span<bit> dst)
=> apply(this, src, dst);
}
[Closures(AllNumeric), Nonz]
public readonly struct NonZ128<T> : IBlockedUnaryPred128<T>
where T : unmanaged
{
[MethodImpl(Inline)]
public Span<bit> Invoke(in SpanBlock128<T> src, Span<bit> dst)
=> map(src, dst, Calcs.vnonz<T>(w128));
}
[Closures(AllNumeric), Nonz]
public readonly struct NonZ256<T> : IBlockedUnaryPred256<T>
where T : unmanaged
{
[MethodImpl(Inline)]
public Span<bit> Invoke(in SpanBlock256<T> src, Span<bit> dst)
=> map(src, dst, Calcs.vnonz<T>(w256));
}
}
}
| 30.383562 | 79 | 0.483318 |
[
"BSD-3-Clause"
] |
0xCM/z0
|
src/calc/src/hosts/Nonz.cs
| 2,218 |
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 firehose-2015-08-04.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.KinesisFirehose.Model
{
/// <summary>
/// A serializer to use for converting data to the Parquet format before storing it in
/// Amazon S3. For more information, see <a href="https://parquet.apache.org/documentation/latest/">Apache
/// Parquet</a>.
/// </summary>
public partial class ParquetSerDe
{
private int? _blockSizeBytes;
private ParquetCompression _compression;
private bool? _enableDictionaryCompression;
private int? _maxPaddingBytes;
private int? _pageSizeBytes;
private ParquetWriterVersion _writerVersion;
/// <summary>
/// Gets and sets the property BlockSizeBytes.
/// <para>
/// The Hadoop Distributed File System (HDFS) block size. This is useful if you intend
/// to copy the data from Amazon S3 to HDFS before querying. The default is 256 MiB and
/// the minimum is 64 MiB. Kinesis Data Firehose uses this value for padding calculations.
/// </para>
/// </summary>
public int BlockSizeBytes
{
get { return this._blockSizeBytes.GetValueOrDefault(); }
set { this._blockSizeBytes = value; }
}
// Check to see if BlockSizeBytes property is set
internal bool IsSetBlockSizeBytes()
{
return this._blockSizeBytes.HasValue;
}
/// <summary>
/// Gets and sets the property Compression.
/// <para>
/// The compression code to use over data blocks. The possible values are <code>UNCOMPRESSED</code>,
/// <code>SNAPPY</code>, and <code>GZIP</code>, with the default being <code>SNAPPY</code>.
/// Use <code>SNAPPY</code> for higher decompression speed. Use <code>GZIP</code> if the
/// compression ration is more important than speed.
/// </para>
/// </summary>
public ParquetCompression Compression
{
get { return this._compression; }
set { this._compression = value; }
}
// Check to see if Compression property is set
internal bool IsSetCompression()
{
return this._compression != null;
}
/// <summary>
/// Gets and sets the property EnableDictionaryCompression.
/// <para>
/// Indicates whether to enable dictionary compression.
/// </para>
/// </summary>
public bool EnableDictionaryCompression
{
get { return this._enableDictionaryCompression.GetValueOrDefault(); }
set { this._enableDictionaryCompression = value; }
}
// Check to see if EnableDictionaryCompression property is set
internal bool IsSetEnableDictionaryCompression()
{
return this._enableDictionaryCompression.HasValue;
}
/// <summary>
/// Gets and sets the property MaxPaddingBytes.
/// <para>
/// The maximum amount of padding to apply. This is useful if you intend to copy the data
/// from Amazon S3 to HDFS before querying. The default is 0.
/// </para>
/// </summary>
public int MaxPaddingBytes
{
get { return this._maxPaddingBytes.GetValueOrDefault(); }
set { this._maxPaddingBytes = value; }
}
// Check to see if MaxPaddingBytes property is set
internal bool IsSetMaxPaddingBytes()
{
return this._maxPaddingBytes.HasValue;
}
/// <summary>
/// Gets and sets the property PageSizeBytes.
/// <para>
/// The Parquet page size. Column chunks are divided into pages. A page is conceptually
/// an indivisible unit (in terms of compression and encoding). The minimum value is 64
/// KiB and the default is 1 MiB.
/// </para>
/// </summary>
public int PageSizeBytes
{
get { return this._pageSizeBytes.GetValueOrDefault(); }
set { this._pageSizeBytes = value; }
}
// Check to see if PageSizeBytes property is set
internal bool IsSetPageSizeBytes()
{
return this._pageSizeBytes.HasValue;
}
/// <summary>
/// Gets and sets the property WriterVersion.
/// <para>
/// Indicates the version of row format to output. The possible values are <code>V1</code>
/// and <code>V2</code>. The default is <code>V1</code>.
/// </para>
/// </summary>
public ParquetWriterVersion WriterVersion
{
get { return this._writerVersion; }
set { this._writerVersion = value; }
}
// Check to see if WriterVersion property is set
internal bool IsSetWriterVersion()
{
return this._writerVersion != null;
}
}
}
| 35.567901 | 110 | 0.613155 |
[
"Apache-2.0"
] |
Bio2hazard/aws-sdk-net
|
sdk/src/Services/KinesisFirehose/Generated/Model/ParquetSerDe.cs
| 5,762 |
C#
|
using System;
using System.Drawing;
using SummerGUI.DataGrid;
using SummerGUI.Charting.Graph2D;
namespace SummerGUI.Charting
{
public class PlotterContainer : SplitContainer
{
public Graph2DPlotter Plotter { get; private set; }
public DataGridView GRD { get; private set; }
public GraphList Graphs { get; private set; }
public PlotterContainer (string name)
: base(name, SplitOrientation.Vertical, -240f)
{
Plotter = new Graph2DPlotter ("plotter");
Panel1.AddChild(Plotter);
GRD = new DataGridView ("dgv");
GRD.RowHeaderWidth = 0;
GRD.AlternatingRowColor = Color.FromArgb (50, Theme.Colors.Cyan);
Panel2.AddChild(GRD);
Graphs = new GraphList ();
GraphBase GB = new GraphBase (null, GRD);
Graphs.Add (GB);
GRD.SetDataProvider(GB);
GB.OnDataLoaded ();
Plotter.Graphs = Graphs;
Plotter.Graph = GB;
GB.GraphColor = Theme.Colors.Orange;
}
public override void Focus ()
{
GRD.Focus ();
}
}
}
| 21.577778 | 68 | 0.68898 |
[
"MIT"
] |
kroll-software/SummerGUI.Charting
|
Forms/Graph2D/PlotterContainer.cs
| 973 |
C#
|
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.Tracing;
using System.Linq;
using Microsoft.Practices.EnterpriseLibrary.SemanticLogging;
using Microsoft.Practices.EnterpriseLibrary.SemanticLogging.Schema;
namespace FullScale180.SemanticLogging.Sinks.Tests.TestSupport
{
internal static class EventEntryTestHelper
{
public static EventEntry Create(
int eventId = 0,
Guid providerId = default(Guid),
string providerName = null,
EventLevel level = default(EventLevel),
EventTask task = default(EventTask),
string taskName = null,
EventOpcode opcode = default(EventOpcode),
string opcodeName = null,
EventKeywords keywords = default(EventKeywords),
string keywordsDescription = null,
int version = 0,
IEnumerable<string> payloadNames = null,
string formattedMessage = null,
IEnumerable<object> payload = null,
DateTimeOffset timestamp = default(DateTimeOffset),
Guid activityId = default(Guid),
Guid relatedActivityId = default(Guid),
int processId = 0,
int threadId = 0)
{
return
new EventEntry(
providerId,
eventId,
formattedMessage,
new ReadOnlyCollection<object>((payload ?? Enumerable.Empty<object>()).ToList()),
timestamp != default(DateTimeOffset) ? timestamp : DateTimeOffset.UtcNow,
processId,
threadId,
activityId,
relatedActivityId,
new EventSchema(
eventId,
providerId,
providerName,
level,
task,
taskName,
opcode,
opcodeName,
keywords,
keywordsDescription,
version,
(payloadNames ?? Enumerable.Empty<string>())));
}
}
}
| 38.206349 | 122 | 0.539676 |
[
"Apache-2.0"
] |
DSakura1987/slab-sinks
|
tests/SemanticLogging.Tests/TestSupport/EventEntryTestHelper.cs
| 2,409 |
C#
|
using System;
using System.IO;
namespace Picturepark.SDK.V1.Contract
{
/// <summary>
/// Specifies the location where to upload the file from and optional filename if it should be renamed on upload
/// </summary>
public class FileLocations
{
/// <summary>
/// Initializes a new instance of the <see cref="FileLocations"/> class.
/// </summary>
/// <param name="absoluteSourcePath">Physical (absolute) source file path</param>
/// <param name="fileNameOverride">
/// Specify if you want to upload the file under a different filename than the source name.
/// If a path is specified, only the filename will be used.
/// </param>
/// <param name="identifier">
/// The identifier of the file for internal book keeping. Usually this is auto-generated.
/// </param>
public FileLocations(string absoluteSourcePath, string fileNameOverride = null, string identifier = null)
{
AbsoluteSourcePath = absoluteSourcePath ?? throw new ArgumentNullException(nameof(absoluteSourcePath));
UploadAs = fileNameOverride ?? Path.GetFileName(absoluteSourcePath);
Identifier = identifier ?? $"{Guid.NewGuid():N}";
}
/// <summary>
/// Physical (absolute) source file path
/// </summary>
public string AbsoluteSourcePath { get; }
/// <summary>
/// The filename under which the file will be uploaded
/// </summary>
public string UploadAs { get; }
/// <summary>
/// The identifier of the file for internal book keeping
/// Usually this is auto-generated.
/// </summary>
public string Identifier { get; }
public static implicit operator FileLocations(string path)
{
return new FileLocations(path);
}
public override string ToString()
=> $"{AbsoluteSourcePath} => {UploadAs}";
}
}
| 37.54717 | 116 | 0.610553 |
[
"MIT"
] |
Picturepark/Picturepark.SDK.DotNet
|
src/Picturepark.SDK.V1.Contract/Contract/FileLocations.cs
| 1,992 |
C#
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace AdditionalBoneSliders.Debug
{
internal class Logger
{
private const string timeStampFormat = "yyyy-mm-dd HH:mm:ss";
private const string defaultLogPath = "log.txt";
private static readonly Dictionary<string, object> _fileLockObjects = new Dictionary<string, object>();
private static string _defaultPath = defaultLogPath;
public static string Path
{
get { return _defaultPath; }
set
{
if (string.IsNullOrEmpty(value))
throw new InvalidOperationException();
_defaultPath = value;
}
}
private string _path;
private string _context;
protected Logger(Type typeContext, string path)
{
_context = typeContext.Name;
_path = path;
Initialize(path);
}
private void Initialize(string path)
{
if (string.IsNullOrEmpty(path))
path = Path;
lock (GetFileLock(path))
{
if (!File.Exists(path))
{
using (var stream = File.Create(path))
{
stream.Close();
}
}
}
}
private StreamWriter GetStreamWriter()
{
var streamWriter = new StreamWriter(_path, true);
streamWriter.AutoFlush = true;
return streamWriter;
}
private static object GetFileLock(string path)
{
if (!_fileLockObjects.TryGetValue(path, out object value))
{
value = new object();
_fileLockObjects.Add(path, value);
}
return value;
}
public static Logger GetLogger(Type typeContext)
{
return GetLogger(typeContext, Path);
}
public static Logger GetLogger(Type typeContext, string path)
{
return new Logger(typeContext, path);
}
public void Info(string entry)
{
Log("Info", entry);
}
public void Warning(string entry)
{
Log("Warning", entry);
}
public void Error(string entry)
{
Log("Error", entry);
}
protected void Log(string level, string entry)
{
lock (GetFileLock(_path))
{
using (var streamWriter = GetStreamWriter())
{
streamWriter.WriteLine($"{DateTime.Now.ToString(timeStampFormat)} [{level}][{_context}] {entry ?? "null"}");
}
}
}
}
internal class GameObjectLogger : Logger
{
protected GameObjectLogger(Type typeContext, string path) : base(typeContext, path)
{
}
public new static GameObjectLogger GetLogger(Type typeContext, string path)
{
return new GameObjectLogger(typeContext, path);
}
public void GameObjectHierarchy(UnityEngine.GameObject gameObject)
{
if (gameObject.transform != null)
{
if (gameObject.transform.parent != null)
{
var parent = gameObject.transform.parent.gameObject;
if (parent != null)
GameObjectHierarchy(parent);
}
}
Info(" + " + gameObject.name);
foreach (var component in gameObject.GetComponents<UnityEngine.Component>())
{
Info(" " + component.GetType());
}
}
public void GameObjectChildren(UnityEngine.GameObject gameObject)
{
GameObjectChildren(gameObject, 0);
}
private void GameObjectChildren(UnityEngine.GameObject gameObject, int indent)
{
var indentation = new string(' ', indent * 4);
Info(indentation + " + " + gameObject.name);
foreach (var component in gameObject.GetComponents<UnityEngine.Component>())
Info(indentation + " | - - " + component.GetType());
foreach (UnityEngine.Transform transform in gameObject.transform)
GameObjectChildren(transform.gameObject, indent + 1);
}
}
}
| 27.339394 | 128 | 0.522057 |
[
"MIT"
] |
whoaabird/AdditionalBoneSliders
|
src/AdditionalBoneSliders/AdditionalBoneSliders/Logger.cs
| 4,513 |
C#
|
// 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.
//
// Copyright (c) 2008 Novell, Inc. (http://www.novell.com)
//
// Authors:
// Mike Gorse <[email protected]>
//
using System;
using System.Windows.Automation;
using System.Windows.Automation.Provider;
namespace UiaAtkBridge
{
public class ListGroup: ComponentParentAdapter, Atk.ISelectionImplementor, Atk.ITableImplementor
{
private ISelectionProvider selectionProvider;
private SelectionProviderUserHelper selectionHelper;
private TableImplementorHelper tableExpert = null;
public ListGroup (IRawElementProviderFragment provider): base (provider)
{
tableExpert = new TableImplementorHelper (this);
IRawElementProviderFragment listProvider = provider.Navigate (NavigateDirection.Parent);
selectionProvider = (ISelectionProvider)listProvider.GetPatternProvider(SelectionPatternIdentifiers.Pattern.Id);
if (selectionProvider == null)
throw new ArgumentException ("List should always implement ISelectionProvider");
selectionHelper = new SelectionProviderUserHelper (provider, selectionProvider);
Role = Atk.Role.LayeredPane;
}
public override void RaiseStructureChangedEvent (object childProvider, StructureChangedEventArgs e)
{
// TODO
}
public int SelectionCount
{
get { return selectionHelper.SelectionCount; }
}
public bool AddSelection (int i)
{
selectionHelper.AddSelection (i);
//FIXME: currently unit-tests force this to always true, we may be interested in changing them when we report the gail bug about this (see ComboBox.cs)
return true;
}
public bool ClearSelection ()
{
return selectionHelper.ClearSelection ();
}
public bool IsChildSelected (int i)
{
return selectionHelper.IsChildSelected (i);
}
public Atk.Object RefSelection (int i)
{
return selectionHelper.RefSelection (i);
}
public bool RemoveSelection (int i)
{
return selectionHelper.RemoveSelection (i);
}
public bool SelectAllSelection ()
{
return selectionHelper.SelectAllSelection ();
}
public Atk.Object RefAt (int row, int column)
{
return tableExpert.RefAt (row, column);
}
public int GetIndexAt (int row, int column)
{
return tableExpert.GetIndexAt (row, column);
}
public int GetColumnAtIndex (int index)
{
return tableExpert.GetColumnAtIndex (index);
}
public int GetRowAtIndex (int index)
{
return tableExpert.GetRowAtIndex (index);
}
public int NColumns { get { return tableExpert.NColumns; } }
public int NRows { get { return tableExpert.NRows; } }
public int GetColumnExtentAt (int row, int column)
{
return tableExpert.GetColumnExtentAt (row, column);
}
public int GetRowExtentAt (int row, int column)
{
return tableExpert.GetRowExtentAt (row, column);
}
public Atk.Object Caption
{
get { return tableExpert.Caption; } set { tableExpert.Caption = value; }
}
public string GetColumnDescription (int column)
{
return string.Empty;
}
public Atk.Object GetColumnHeader (int column)
{
return null;
}
public string GetRowDescription (int row)
{
return String.Empty;
}
public Atk.Object GetRowHeader (int row)
{
return null;
}
public Atk.Object Summary
{
get { return tableExpert.Summary; }
set { tableExpert.Summary = value; }
}
public void SetColumnDescription (int column, string description)
{
tableExpert.SetColumnDescription (column, description);
}
public void SetColumnHeader (int column, Atk.Object header)
{
tableExpert.SetColumnHeader (column, header);
}
public void SetRowDescription (int row, string description)
{
tableExpert.SetRowDescription (row, description);
}
public void SetRowHeader (int row, Atk.Object header)
{
tableExpert.SetRowHeader (row, header);
}
public int [] SelectedColumns {
get { return tableExpert.SelectedColumns; }
}
public int [] SelectedRows {
get { return tableExpert.SelectedRows; }
}
// TODO: Remove next methods when atk-sharp is fixed (BNC#512477)
public int GetSelectedColumns (out int selected)
{
return tableExpert.GetSelectedColumns (out selected);
}
public int GetSelectedRows (out int selected)
{
return tableExpert.GetSelectedRows (out selected);
}
public int GetSelectedColumns (out int [] selected)
{
return tableExpert.GetSelectedColumns (out selected);
}
public int GetSelectedRows (out int [] selected)
{
return tableExpert.GetSelectedRows (out selected);
}
public bool IsColumnSelected (int column)
{
return tableExpert.IsColumnSelected (column);
}
public bool IsRowSelected (int row)
{
return tableExpert.IsRowSelected (row);
}
public bool IsSelected (int row, int column)
{
return tableExpert.IsSelected (row, column);
}
public bool AddRowSelection (int row)
{
return tableExpert.AddRowSelection (row);
}
public bool RemoveRowSelection (int row)
{
return tableExpert.RemoveRowSelection (row);
}
public bool AddColumnSelection (int column)
{
return tableExpert.AddColumnSelection (column);
}
public bool RemoveColumnSelection (int column)
{
return tableExpert.RemoveColumnSelection (column);
}
}
}
| 26.154167 | 155 | 0.727895 |
[
"MIT"
] |
ABEMBARKA/monoUI
|
UiaAtkBridge/UiaAtkBridge/ListGroup.cs
| 6,277 |
C#
|
// Amplify Shader Editor - Visual Shader Editing Tool
// Copyright (c) Amplify Creations, Lda <[email protected]>
//
// Custom Node TAU
// Donated by The Four Headed Cat - @fourheadedcat
using UnityEngine;
using System;
namespace AmplifyShaderEditor
{
[Serializable]
[NodeAttributes( "Tau", "Constants And Properties", "Tau constant (2*PI): 6.28318530718", null, KeyCode.None, true, false, null,null, "The Four Headed Cat - @fourheadedcat" )]
public sealed class TauNode : ParentNode
{
private readonly string Tau = ( 2.0 * Mathf.PI ).ToString();
public TauNode() : base() { }
public TauNode( int uniqueId, float x, float y, float width, float height ) : base( uniqueId, x, y, width, height ) { }
protected override void CommonInit( int uniqueId )
{
base.CommonInit( uniqueId );
AddOutputPort( WirePortDataType.FLOAT, Constants.EmptyPortValue );
m_previewShaderGUID = "701bc295c0d75d8429eabcf45e8e008d";
}
public override string GenerateShaderForOutput( int outputId, ref MasterNodeDataCollector dataCollector, bool ignoreLocalvar )
{
return dataCollector.IsSRP? "TWO_PI": Tau;
}
}
}
| 33.969697 | 176 | 0.729706 |
[
"MIT"
] |
142333lzg/jynew
|
jyx2/Assets/3rd/AmplifyShaderEditor/Plugins/Editor/Nodes/Constants/TauNode.cs
| 1,121 |
C#
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System.Collections.Generic;
using System.Text.Json;
using Azure.Core;
namespace Azure.Analytics.Synapse.Artifacts.Models
{
public partial class NetezzaLinkedService : IUtf8JsonSerializable
{
void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
{
writer.WriteStartObject();
writer.WritePropertyName("type");
writer.WriteStringValue(Type);
if (Optional.IsDefined(ConnectVia))
{
writer.WritePropertyName("connectVia");
writer.WriteObjectValue(ConnectVia);
}
if (Optional.IsDefined(Description))
{
writer.WritePropertyName("description");
writer.WriteStringValue(Description);
}
if (Optional.IsCollectionDefined(Parameters))
{
writer.WritePropertyName("parameters");
writer.WriteStartObject();
foreach (var item in Parameters)
{
writer.WritePropertyName(item.Key);
writer.WriteObjectValue(item.Value);
}
writer.WriteEndObject();
}
if (Optional.IsCollectionDefined(Annotations))
{
writer.WritePropertyName("annotations");
writer.WriteStartArray();
foreach (var item in Annotations)
{
writer.WriteObjectValue(item);
}
writer.WriteEndArray();
}
writer.WritePropertyName("typeProperties");
writer.WriteStartObject();
if (Optional.IsDefined(ConnectionString))
{
writer.WritePropertyName("connectionString");
writer.WriteObjectValue(ConnectionString);
}
if (Optional.IsDefined(Pwd))
{
writer.WritePropertyName("pwd");
writer.WriteObjectValue(Pwd);
}
if (Optional.IsDefined(EncryptedCredential))
{
writer.WritePropertyName("encryptedCredential");
writer.WriteObjectValue(EncryptedCredential);
}
writer.WriteEndObject();
foreach (var item in AdditionalProperties)
{
writer.WritePropertyName(item.Key);
writer.WriteObjectValue(item.Value);
}
writer.WriteEndObject();
}
internal static NetezzaLinkedService DeserializeNetezzaLinkedService(JsonElement element)
{
string type = default;
Optional<IntegrationRuntimeReference> connectVia = default;
Optional<string> description = default;
Optional<IDictionary<string, ParameterSpecification>> parameters = default;
Optional<IList<object>> annotations = default;
Optional<object> connectionString = default;
Optional<AzureKeyVaultSecretReference> pwd = default;
Optional<object> encryptedCredential = default;
IDictionary<string, object> additionalProperties = default;
Dictionary<string, object> additionalPropertiesDictionary = default;
foreach (var property in element.EnumerateObject())
{
if (property.NameEquals("type"))
{
type = property.Value.GetString();
continue;
}
if (property.NameEquals("connectVia"))
{
connectVia = IntegrationRuntimeReference.DeserializeIntegrationRuntimeReference(property.Value);
continue;
}
if (property.NameEquals("description"))
{
description = property.Value.GetString();
continue;
}
if (property.NameEquals("parameters"))
{
Dictionary<string, ParameterSpecification> dictionary = new Dictionary<string, ParameterSpecification>();
foreach (var property0 in property.Value.EnumerateObject())
{
dictionary.Add(property0.Name, ParameterSpecification.DeserializeParameterSpecification(property0.Value));
}
parameters = dictionary;
continue;
}
if (property.NameEquals("annotations"))
{
List<object> array = new List<object>();
foreach (var item in property.Value.EnumerateArray())
{
array.Add(item.GetObject());
}
annotations = array;
continue;
}
if (property.NameEquals("typeProperties"))
{
foreach (var property0 in property.Value.EnumerateObject())
{
if (property0.NameEquals("connectionString"))
{
connectionString = property0.Value.GetObject();
continue;
}
if (property0.NameEquals("pwd"))
{
pwd = AzureKeyVaultSecretReference.DeserializeAzureKeyVaultSecretReference(property0.Value);
continue;
}
if (property0.NameEquals("encryptedCredential"))
{
encryptedCredential = property0.Value.GetObject();
continue;
}
}
continue;
}
additionalPropertiesDictionary ??= new Dictionary<string, object>();
additionalPropertiesDictionary.Add(property.Name, property.Value.GetObject());
}
additionalProperties = additionalPropertiesDictionary;
return new NetezzaLinkedService(type, connectVia.Value, description.Value, Optional.ToDictionary(parameters), Optional.ToList(annotations), additionalProperties, connectionString.Value, pwd.Value, encryptedCredential.Value);
}
}
}
| 41.566879 | 236 | 0.528808 |
[
"MIT"
] |
amolagar5/azure-sdk-for-net
|
sdk/synapse/Azure.Analytics.Synapse.Artifacts/src/Generated/Models/NetezzaLinkedService.Serialization.cs
| 6,526 |
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace EasyWrapper
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Main());
}
}
}
| 21.772727 | 65 | 0.597077 |
[
"MIT"
] |
SkillsFundingAgency/DC-Alpha-EasyWrapperPaaS
|
EasyWrapper/Program.cs
| 481 |
C#
|
using Entitas.Generics;
using Entitas.MatchLine;
using Performance.ViewModels;
using System.Threading;
using UnityEngine;
using Random = UnityEngine.Random;
public sealed partial class TestElementService : Service, IElementService
{
private int _entityCounter;
private IGenericContext<GameEntity> _game;
public TestElementService(Contexts contexts, MainViewModel viewModel, IFactories factories) : base(contexts, viewModel, factories)
{
_entityCounter = 0;
_game = contexts.Game;
}
private static readonly ThreadLocal<System.Random> Random
= new ThreadLocal<System.Random>(() => new System.Random());
public void CreateRandomElement(GridPosition position)
{
var typeCount = _contexts.Config.GetUnique<TypeCountComponent>().Value;
int maxType = typeCount;
if (typeCount - 1 < 1)
maxType = 1;
else if (typeCount >= 100)
maxType = 100;
// Unity's Random class can't be used outside of the Unity environment.
//var maxType = Mathf.Clamp(typeCount - 1, 1, 100);
//var randomType = Random.Range(0, maxType + 1);
var randomType = Random.Value.Next(0, maxType + 1);
var normalizedType = Mathf.InverseLerp(0, maxType, randomType);
var entity = _game.CreateEntity();
_game.SetFlag<ElementComponent>(entity, true);
_game.SetFlag<MovableComponent>(entity, true);
_game.Set(entity, new IdComponent { value = _entityCounter });
_game.Set(entity, new ElementTypeComponent { value = randomType });
_game.Set(entity, new AssetComponent {
value = "Element",
id = (int)ActorType.Element
});
_game.Set(entity, new ColorComponent { value = new Color(normalizedType, normalizedType, normalizedType) });
entity.Set<PositionComponent>(c => c.value = position);
_entityCounter++;
}
public void CreateMovableBlock(GridPosition position)
{
var entity = _game.CreateEntity();
_game.SetFlag<ElementComponent>(entity, true);
_game.SetFlag<MovableComponent>(entity, true);
_game.SetFlag<BlockComponent>(entity, true);
_game.Set(entity, new IdComponent { value = _entityCounter });
_game.Set(entity, new AssetComponent {
value = "Block",
id = (int)ActorType.Block
});
_game.Set<PositionComponent>(entity, c => c.value = position);
_entityCounter++;
}
public void CreateNotMovableBlock(GridPosition position)
{
var entity = _game.CreateEntity();
_game.SetFlag<ElementComponent>(entity, true);
_game.SetFlag<BlockComponent>(entity, true);
_game.Set(entity, new IdComponent { value = _entityCounter });
_game.Set(entity, new AssetComponent
{
value = "NotMovableBlock",
id = (int)ActorType.NotMovableBlock
});
_game.Set<PositionComponent>(entity, c => c.value = position);
_entityCounter++;
}
public void CreateExsplosiveBlock(GridPosition position)
{
var entity = _game.CreateEntity();
_game.SetFlag<ElementComponent>(entity, true);
_game.SetFlag<ExplosiveComponent>(entity, true);
_game.SetFlag<BlockComponent>(entity, true);
_game.Set(entity, new IdComponent { value = _entityCounter });
_game.Set(entity, new AssetComponent {
value = "ExsplosiveBlock",
id = (int)ActorType.ExplosiveBlock
});
_game.Set<PositionComponent>(entity, c => c.value = position);
_entityCounter++;
}
public override void DropState()
{
_entityCounter = 0;
}
}
| 35.836538 | 134 | 0.641803 |
[
"MIT"
] |
jeffvella/EntitasGenerics
|
Assets/Sources/WpfRenderer/cvs/Performance.Game/Services/TestElementService.cs
| 3,729 |
C#
|
using AutoMapper;
using PendAdvisor.API.DTOs;
using PendAdvisorModel;
using System.Linq;
namespace PendAdvisor.API
{
public class MappingProfile : Profile
{
public MappingProfile()
{
CreateMap<ClaimData, ModelInput>();
CreateMap<ModelOutputEx, AdviceData>()
.ForMember(ad => ad.AdvisedAction, o => o.MapFrom(mo => mo.Action))
.ForMember(ad => ad.AdviceScore, o => o.MapFrom(ml => ml.ActionsAndScores[0].Score)) // ActionsAndScores is ordered by score
.ForMember(ad => ad.ActionsAndScores, o => o.MapFrom(ml => ml.ActionsAndScores.Select(t => new { t.Action, t.Score }))); // ActionsAndScores in ModelOutputEx are tuples, which do not serialize well
}
}
}
| 37 | 210 | 0.660811 |
[
"Apache-2.0"
] |
mavidian/PendAdvisor
|
PendAdvisor.API/MappingProfile.cs
| 742 |
C#
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace FeatureA.Contracts
{
public interface IWorker
{
Task Work(CancellationToken cancellationToken = default);
}
}
| 18.785714 | 65 | 0.749049 |
[
"MIT"
] |
bnayae/autofac-module-sample
|
AutofacModuleSamples/FeatureA/FeatureA.Contracts/IWorker.cs
| 265 |
C#
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace MinerByAlexForms
{
public partial class Template : Form
{
private static Template _instance;
public static Template GetInstance
{
get
{
if (_instance == null) _instance = new Template();
return _instance;
}
}
public void SetUnmarkedButtonView(MineButton btn)
{
btn.Size = GetButtonSize();
btn.FlatStyle = Mine.FlatStyle;
btn.Text = "";
btn.BackColor = Mine.BackColor;
btn.Margin = new Padding(0);
btn.Padding = new Padding(0);
}
public void SetMarkedAsMineButtonView(MineButton btn)
{
btn.Size = GetButtonSize();
btn.FlatStyle = MineMarkAsMine.FlatStyle;
btn.Text = MineMarkAsMine.Text;
btn.BackColor = MineMarkAsMine.BackColor;
btn.Margin = new Padding(0);
btn.Padding = new Padding(0);
}
public Size GetButtonSize()
{
return Mine.Size;
}
private Template()
{
InitializeComponent();
}
public void SetDeactivatedButtonView(MineButton btn)
{
btn.Size = GetButtonSize();
btn.FlatStyle = btn_deactivated.FlatStyle;
btn.Font = btn_deactivated.Font;
btn.FlatAppearance.BorderColor = Color.FromArgb(255, 235, 204, 172);
btn.FlatAppearance.BorderSize = 1;
if (btn.NearMinesCount == 0)
{
btn.Text = "";
btn.ForeColor = Color.Black;
}
else
{
btn.Text = btn.NearMinesCount.ToString();
switch (btn.NearMinesCount)
{
case 1: btn.ForeColor = Color.Blue; break;
case 2: btn.ForeColor = Color.ForestGreen; break;
case 3: btn.ForeColor = Color.Red; break;
case 4: btn.ForeColor = Color.DarkBlue; break;
case 5: btn.ForeColor = Color.DarkRed; break;
case 6: btn.ForeColor = Color.Cyan; break;
case 7: btn.ForeColor = Color.Magenta; break;
case 8: btn.ForeColor = Color.Black; break;
}
}
btn.BackColor = btn_deactivated.BackColor;
btn.Margin = new Padding(0);
btn.Padding = new Padding(0);
}
internal void SetSuspiciousButtonView(MineButton btn)
{
btn.Size = GetButtonSize();
btn.FlatStyle = btn_suspicious.FlatStyle;
btn.Text = btn_suspicious.Text;
btn.BackColor = btn_suspicious.BackColor;
btn.Margin = new Padding(0);
btn.Padding = new Padding(0);
}
internal void SetExplodedButtonView(MineButton btn)
{
btn.Size = GetButtonSize();
btn.FlatStyle = btn_exploded.FlatStyle;
btn.Text = btn_exploded.Text;
btn.BackColor = btn_exploded.BackColor;
btn.Margin = new Padding(0);
btn.Padding = new Padding(0);
}
internal void SetExplodedPressedButtonView(MineButton btn)
{
btn.Size = GetButtonSize();
btn.FlatStyle = btn_exploded_pressed.FlatStyle;
btn.Text = btn_exploded_pressed.Text;
btn.BackColor = btn_exploded_pressed.BackColor;
btn.Margin = new Padding(0);
btn.Padding = new Padding(0);
}
private void Template_Load(object sender, EventArgs e)
{
}
}
}
| 31.516129 | 80 | 0.541198 |
[
"MIT"
] |
Trissstar/MineSweeper
|
MineSweeperForms/Template.cs
| 3,910 |
C#
|
// ==============================================================================================================
// Microsoft patterns & practices
// CQRS Journey project
// ==============================================================================================================
// ©2012 Microsoft. All rights reserved. Certain content used with permission from contributors
// http://go.microsoft.com/fwlink/p/?LinkID=258575
// 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 Infrastructure.Azure.Messaging
{
using System;
using Microsoft.ServiceBus.Messaging;
/// <summary>
/// Abstracts the behavior of a receiving component that raises
/// an event for every received event.
/// </summary>
public interface IMessageReceiver
{
/// <summary>
/// Starts the listener.
/// </summary>
/// <param name="messageHandler">Handler for incoming messages. The return value indicates how to release the message lock.</param>
void Start(Func<BrokeredMessage, MessageReleaseAction> messageHandler);
/// <summary>
/// Stops the listener.
/// </summary>
void Stop();
}
}
| 49.27027 | 140 | 0.556226 |
[
"Apache-2.0"
] |
BenakTomas/cqrs-journey
|
source/Infrastructure/Azure/Infrastructure.Azure/Messaging/IMessageReceiver.cs
| 1,826 |
C#
|
#if WITH_GAME
#if PLATFORM_32BITS
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace UnrealEngine
{
public partial class UStaticMesh
{
static readonly int MinLOD__Offset;
public int MinLOD
{
get{ CheckIsValid();return (int)Marshal.PtrToStructure(_this.Get()+MinLOD__Offset, typeof(int));}
}
static readonly int Materials__Offset;
public TObjectArray<UMaterialInterface> Materials
{
get{ CheckIsValid();return new TObjectArray<UMaterialInterface>((FScriptArray)Marshal.PtrToStructure(_this.Get()+Materials__Offset, typeof(FScriptArray)));}
set{ CheckIsValid();Marshal.StructureToPtr(value.InterArray, _this.Get()+Materials__Offset, false);}
}
static readonly int StaticMaterials__Offset;
public TStructArray<FStaticMaterial> StaticMaterials
{
get{ CheckIsValid();return new TStructArray<FStaticMaterial>((FScriptArray)Marshal.PtrToStructure(_this.Get()+StaticMaterials__Offset, typeof(FScriptArray)));}
set{ CheckIsValid();Marshal.StructureToPtr(value.InterArray, _this.Get()+StaticMaterials__Offset, false);}
}
static readonly int LightmapUVDensity__Offset;
public float LightmapUVDensity
{
get{ CheckIsValid();return (float)Marshal.PtrToStructure(_this.Get()+LightmapUVDensity__Offset, typeof(float));}
}
static readonly int LightMapResolution__Offset;
public int LightMapResolution
{
get{ CheckIsValid();return (int)Marshal.PtrToStructure(_this.Get()+LightMapResolution__Offset, typeof(int));}
set{ CheckIsValid();Marshal.StructureToPtr(value, _this.Get()+LightMapResolution__Offset, false);}
}
static readonly int LightMapCoordinateIndex__Offset;
public int LightMapCoordinateIndex
{
get{ CheckIsValid();return (int)Marshal.PtrToStructure(_this.Get()+LightMapCoordinateIndex__Offset, typeof(int));}
set{ CheckIsValid();Marshal.StructureToPtr(value, _this.Get()+LightMapCoordinateIndex__Offset, false);}
}
static readonly int bGenerateMeshDistanceField__Offset;
public bool bGenerateMeshDistanceField
{
get{ CheckIsValid();return BoolWrap.Get(_this.Get(), bGenerateMeshDistanceField__Offset, 1, 0, 1, 1);}
set{ CheckIsValid();BoolWrap.Set(value,_this.Get(), bGenerateMeshDistanceField__Offset, 1,0,1,1);}
}
static readonly int BodySetup__Offset;
public UBodySetup BodySetup
{
get{ CheckIsValid(); IntPtr v = Marshal.ReadIntPtr(_this.Get() + BodySetup__Offset); if (v == IntPtr.Zero)return null; UBodySetup retValue = new UBodySetup(); retValue._this = v; return retValue; }
set{ CheckIsValid(); if (value == null)Marshal.WriteIntPtr(_this.Get() + BodySetup__Offset, IntPtr.Zero);else Marshal.WriteIntPtr(_this.Get() + BodySetup__Offset, value._this.Get()); }
}
static readonly int LODForCollision__Offset;
public int LODForCollision
{
get{ CheckIsValid();return (int)Marshal.PtrToStructure(_this.Get()+LODForCollision__Offset, typeof(int));}
set{ CheckIsValid();Marshal.StructureToPtr(value, _this.Get()+LODForCollision__Offset, false);}
}
static readonly int bStripComplexCollisionForConsole__Offset;
public bool bStripComplexCollisionForConsole
{
get{ CheckIsValid();return BoolWrap.Get(_this.Get(), bStripComplexCollisionForConsole__Offset, 1, 0, 1, 1);}
}
static readonly int bHasNavigationData__Offset;
public bool bHasNavigationData
{
get{ CheckIsValid();return BoolWrap.Get(_this.Get(), bHasNavigationData__Offset, 1, 0, 2, 2);}
set{ CheckIsValid();BoolWrap.Set(value,_this.Get(), bHasNavigationData__Offset, 1,0,2,2);}
}
static readonly int LpvBiasMultiplier__Offset;
public float LpvBiasMultiplier
{
get{ CheckIsValid();return (float)Marshal.PtrToStructure(_this.Get()+LpvBiasMultiplier__Offset, typeof(float));}
set{ CheckIsValid();Marshal.StructureToPtr(value, _this.Get()+LpvBiasMultiplier__Offset, false);}
}
static readonly int bAllowCPUAccess__Offset;
public bool bAllowCPUAccess
{
get{ CheckIsValid();return BoolWrap.Get(_this.Get(), bAllowCPUAccess__Offset, 1, 0, 1, 255);}
set{ CheckIsValid();BoolWrap.Set(value,_this.Get(), bAllowCPUAccess__Offset, 1,0,1,255);}
}
static readonly int Sockets__Offset;
public TObjectArray<UStaticMeshSocket> Sockets
{
get{ CheckIsValid();return new TObjectArray<UStaticMeshSocket>((FScriptArray)Marshal.PtrToStructure(_this.Get()+Sockets__Offset, typeof(FScriptArray)));}
set{ CheckIsValid();Marshal.StructureToPtr(value.InterArray, _this.Get()+Sockets__Offset, false);}
}
static readonly int PositiveBoundsExtension__Offset;
public FVector PositiveBoundsExtension
{
get{ CheckIsValid();return (FVector)Marshal.PtrToStructure(_this.Get()+PositiveBoundsExtension__Offset, typeof(FVector));}
set{ CheckIsValid();Marshal.StructureToPtr(value, _this.Get()+PositiveBoundsExtension__Offset, false);}
}
static readonly int NegativeBoundsExtension__Offset;
public FVector NegativeBoundsExtension
{
get{ CheckIsValid();return (FVector)Marshal.PtrToStructure(_this.Get()+NegativeBoundsExtension__Offset, typeof(FVector));}
set{ CheckIsValid();Marshal.StructureToPtr(value, _this.Get()+NegativeBoundsExtension__Offset, false);}
}
static readonly int ExtendedBounds__Offset;
public FBoxSphereBounds ExtendedBounds
{
get{ CheckIsValid();return (FBoxSphereBounds)Marshal.PtrToStructure(_this.Get()+ExtendedBounds__Offset, typeof(FBoxSphereBounds));}
}
static readonly int ElementToIgnoreForTexFactor__Offset;
public int ElementToIgnoreForTexFactor
{
get{ CheckIsValid();return (int)Marshal.PtrToStructure(_this.Get()+ElementToIgnoreForTexFactor__Offset, typeof(int));}
}
static readonly int AssetUserData__Offset;
public TObjectArray<UAssetUserData> AssetUserData
{
get{ CheckIsValid();return new TObjectArray<UAssetUserData>((FScriptArray)Marshal.PtrToStructure(_this.Get()+AssetUserData__Offset, typeof(FScriptArray)));}
set{ CheckIsValid();Marshal.StructureToPtr(value.InterArray, _this.Get()+AssetUserData__Offset, false);}
}
static readonly int NavCollision__Offset;
public UNavCollision NavCollision
{
get{ CheckIsValid(); IntPtr v = Marshal.ReadIntPtr(_this.Get() + NavCollision__Offset); if (v == IntPtr.Zero)return null; UNavCollision retValue = new UNavCollision(); retValue._this = v; return retValue; }
set{ CheckIsValid(); if (value == null)Marshal.WriteIntPtr(_this.Get() + NavCollision__Offset, IntPtr.Zero);else Marshal.WriteIntPtr(_this.Get() + NavCollision__Offset, value._this.Get()); }
}
static UStaticMesh()
{
IntPtr NativeClassPtr=GetNativeClassFromName("StaticMesh");
MinLOD__Offset=GetPropertyOffset(NativeClassPtr,"MinLOD");
Materials__Offset=GetPropertyOffset(NativeClassPtr,"Materials");
StaticMaterials__Offset=GetPropertyOffset(NativeClassPtr,"StaticMaterials");
LightmapUVDensity__Offset=GetPropertyOffset(NativeClassPtr,"LightmapUVDensity");
LightMapResolution__Offset=GetPropertyOffset(NativeClassPtr,"LightMapResolution");
LightMapCoordinateIndex__Offset=GetPropertyOffset(NativeClassPtr,"LightMapCoordinateIndex");
bGenerateMeshDistanceField__Offset=GetPropertyOffset(NativeClassPtr,"bGenerateMeshDistanceField");
BodySetup__Offset=GetPropertyOffset(NativeClassPtr,"BodySetup");
LODForCollision__Offset=GetPropertyOffset(NativeClassPtr,"LODForCollision");
bStripComplexCollisionForConsole__Offset=GetPropertyOffset(NativeClassPtr,"bStripComplexCollisionForConsole");
bHasNavigationData__Offset=GetPropertyOffset(NativeClassPtr,"bHasNavigationData");
LpvBiasMultiplier__Offset=GetPropertyOffset(NativeClassPtr,"LpvBiasMultiplier");
bAllowCPUAccess__Offset=GetPropertyOffset(NativeClassPtr,"bAllowCPUAccess");
Sockets__Offset=GetPropertyOffset(NativeClassPtr,"Sockets");
PositiveBoundsExtension__Offset=GetPropertyOffset(NativeClassPtr,"PositiveBoundsExtension");
NegativeBoundsExtension__Offset=GetPropertyOffset(NativeClassPtr,"NegativeBoundsExtension");
ExtendedBounds__Offset=GetPropertyOffset(NativeClassPtr,"ExtendedBounds");
ElementToIgnoreForTexFactor__Offset=GetPropertyOffset(NativeClassPtr,"ElementToIgnoreForTexFactor");
AssetUserData__Offset=GetPropertyOffset(NativeClassPtr,"AssetUserData");
NavCollision__Offset=GetPropertyOffset(NativeClassPtr,"NavCollision");
}
}
}
#endif
#endif
| 42.964286 | 209 | 0.780549 |
[
"MIT"
] |
RobertAcksel/UnrealCS
|
Engine/Plugins/UnrealCS/UECSharpDomain/UnrealEngine/GeneratedScriptFile_Game_32bits/UStaticMesh_FixSize.cs
| 8,421 |
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Text;
namespace LeetCode.Naive.Problems
{
/// <summary>
/// Problem: https://leetcode.com/problems/score-of-parentheses/
/// Submission: https://leetcode.com/submissions/detail/239976930/
/// </summary>
internal class P0856
{
public class Solution
{
public int ScoreOfParentheses(string S)
{
// (()(()))
var stack = new Stack<int>();
var score = 0;
for (int i = 0; i < S.Length; i++)
{
var ch = S[i];
if (ch == '(')
{
stack.Push(score);
score = 0;
}
if (ch == ')')
{
var popScore = stack.Pop();
score = popScore + (score == 0 ? 1 : score * 2);
}
}
return score;
}
}
}
}
| 20.608696 | 72 | 0.46519 |
[
"MIT"
] |
viacheslave/leetcode-naive
|
c#/Problems/P0856.cs
| 948 |
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Xml.Xsl;
using System.Diagnostics;
using System.Globalization;
using System.IO;
namespace Arebis.Caching
{
/// <summary>
/// A cache for XSLT document files.
/// </summary>
public class XsltFileCache : FileCache<XslCompiledTransform>
{
/// <summary>
/// Instantiates a file cache to hold compiled XSLT documents.
/// </summary>
public XsltFileCache()
{ }
/// <summary>
/// Instantiates a file cache to hold compiled XSLT documents.
/// </summary>
public XsltFileCache(string appSettingsBaseKey)
:base(appSettingsBaseKey)
{ }
/// <summary>
/// Instantiates a file cache to hold compiled XSLT documents up to the given number or
/// file size rules.
/// </summary>
public XsltFileCache(string appSettingsBaseKey, int defaultMaxFileCount, long defaultMaxFileLengthToCache, long defaultMaxFileLengthSum, bool defaultInvalidateOnSoftRecycle)
: base(appSettingsBaseKey, defaultMaxFileCount, defaultMaxFileLengthToCache, defaultMaxFileLengthSum, defaultInvalidateOnSoftRecycle)
{ }
/// <summary>
/// Instantiates a file cache to hold compiled XSLT documents up to the given number or
/// file size rules.
/// </summary>
public XsltFileCache(int maxFileCount, long maxFileLengthToCache, long maxFileLengthSum, bool invalidateOnSoftRecycle)
: base(maxFileCount, maxFileLengthToCache, maxFileLengthSum, invalidateOnSoftRecycle)
{ }
protected override XslCompiledTransform Load(string filePath)
{
XslCompiledTransform document = new XslCompiledTransform();
document.Load(filePath);
return document;
}
}
/// <summary>
/// A cache for XSLT document files.
/// </summary>
[Obsolete("Use XsltFileCache instead.")]
public class XsltCache2
{
private const int _lockTimeout = 10000;
private Dictionary<string, XsltCacheSlot> _xsltCache = new Dictionary<string, XsltCacheSlot>();
private ReaderWriterLock _lock = new ReaderWriterLock();
/// <summary>
/// Returns the requested XSLT document.
/// </summary>
/// <param name="filePath">The filename of the XSLT document.</param>
/// <returns>The requested XSLT document from cache.</returns>
public XslCompiledTransform Get(string filePath)
{
// Validate arguments:
if (string.IsNullOrEmpty(filePath))
{
throw new ArgumentException("The specified key cannot be an empty string or null");
}
// Acquire a reader lock:
_lock.AcquireReaderLock(_lockTimeout);
try
{
// Retrieve actual file timestamp:
var actualTicks = File.GetLastWriteTime(filePath).Ticks; // If files does not exist, returns 01/01/1601 01:00:00, so anyway, does not throw an exception...
// Try to retrieve the document from cache:
XsltCacheSlot slot;
if (_xsltCache.TryGetValue(filePath, out slot))
{
// If found, verify it's timestamp, and if current, return the document:
if (slot.FileLastWriteTimeTicks == actualTicks)
{
return slot.Document;
}
}
// Upgrade to a writer lock:
_lock.UpgradeToWriterLock(_lockTimeout);
// Create a new cache slot by loading the document from disk:
slot = _xsltCache[filePath] = new XsltCacheSlot() {
FilePath = filePath,
Document = this.Load(filePath),
FileLastWriteTimeTicks = actualTicks
};
// Return the document:
return slot.Document;
}
finally
{
// Release reader and/or writer lock:
_lock.ReleaseLock();
}
}
/// <summary>
/// Removes a xlscompileTransform from the cache
/// </summary>
/// <param name="filePath">The filename of the XSLT template.</param>
public void Invalidate(string filePath)
{
try
{
_lock.AcquireWriterLock(_lockTimeout);
_xsltCache[filePath] = null;
}
finally
{
_lock.ReleaseWriterLock();
}
}
/// <summary>
/// Loads an XSLT document and returns the document
/// as compiled XSLT.
/// </summary>
/// <param name="filePath">The filename of the XSLT template.</param>
private XslCompiledTransform Load(string filePath)
{
XslCompiledTransform myTransformer = new XslCompiledTransform();
myTransformer.Load(filePath);
return myTransformer;
}
class XsltCacheSlot {
public string FilePath { get; set; }
public long FileLastWriteTimeTicks { get; set; }
public XslCompiledTransform Document { get; set; }
public override bool Equals(object obj)
{
var other = obj as XsltCacheSlot;
if (other == null)
return false;
else
return String.Equals(this.FilePath, other.FilePath);
}
public override int GetHashCode()
{
return this.FilePath.GetHashCode();
}
}
}
}
| 35 | 182 | 0.551827 |
[
"MIT"
] |
FingersCrossed/Arebis.Common
|
Arebis.Common/Arebis/Caching/XsltFileCache.cs
| 6,022 |
C#
|
using System;
using System.Globalization;
using System.Threading.Tasks;
using System.Xml;
using XRoadLib.Extensions;
using XRoadLib.Schema;
using XRoadLib.Serialization.Template;
namespace XRoadLib.Serialization.Mapping
{
public class DateTypeMap : TypeMap
{
private static readonly string[] DateFormats =
{
"yyyy-MM-dd",
"'+'yyyy-MM-dd",
"'-'yyyy-MM-dd",
"yyyy-MM-ddzzz",
"'+'yyyy-MM-ddzzz",
"'-'yyyy-MM-ddzzz",
"yyyy-MM-dd'Z'",
"'+'yyyy-MM-dd'Z'",
"'-'yyyy-MM-dd'Z'"
};
public DateTypeMap(TypeDefinition typeDefinition) : base(typeDefinition) { }
public override async Task<object> DeserializeAsync(XmlReader reader, IXmlTemplateNode templateNode, ContentDefinition content, XRoadMessage message)
{
if (reader.IsEmptyElement)
return await reader.MoveNextAndReturnAsync(HandleEmptyElement(content, message)).ConfigureAwait(false);
var value = await reader.ReadElementContentAsStringAsync().ConfigureAwait(false);
if (string.IsNullOrEmpty(value))
return HandleEmptyElement(content, message);
var date = DateTime.ParseExact(value, DateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None);
if (value[value.Length - 1] == 'Z')
date = date.ToLocalTime();
return date;
}
public override async Task SerializeAsync(XmlWriter writer, IXmlTemplateNode templateNode, object value, ContentDefinition content, XRoadMessage message)
{
await message.Style.WriteTypeAsync(writer, Definition, content).ConfigureAwait(false);
await writer.WriteStringAsync(XmlConvert.ToString((DateTime)value, "yyyy-MM-dd")).ConfigureAwait(false);
}
private static DateTime? HandleEmptyElement(ContentDefinition content, XRoadMessage message)
{
return message.HandleEmptyElementOfValueType<DateTime>(content, () => throw new InvalidQueryException("'' is not a valid value for 'date'"));
}
}
}
| 38.482143 | 161 | 0.647332 |
[
"MIT"
] |
janno-p/XRoadLib
|
src/XRoadLib/Serialization/Mapping/DateTypeMap.cs
| 2,157 |
C#
|
using Assets.scripts.DataModel;
using Assets.scripts.Location;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using UnityEngine;
public class DataModel : MonoBehaviour
{
public static DataModel instance;
[Header("Server info")]
// Server Connection Info
public string localServerName;
public string remoteServerName;
private string serverName;
public int localHostPort;
public int remoteHostPort;
private int hostPort;
public bool useRemoteServer;
public NetworkConnection connection;
private void SetServer(bool remote)
{
serverName = remote ? remoteServerName : localServerName;
hostPort = remote ? remoteHostPort : localHostPort;
}
private void AbandonConnection()
{
Debug.Log("Abandon Connection");
if (connection != null)
{
connection.DropConnectionUsingTCPClient();
connection = null;
}
}
private bool UpdateNetworkData(NetworkData data)
{
bool res = false;
try
{
// data.GetData() is an object of the Type stored in "JSONType" field
// according to the type of the object, you can compute whatever you want
Debug.Log("UpdateNetworkData() : " + data.ToJSON());
Debug.LogWarning("TO BE IMPLEMENTED");
res = true;
}
catch (System.Exception ex)
{
Debug.LogError("UpdateNetworkData() got an exception : " + ex.Message);
}
return res;
}
private Thread readLinesThread;
private void ReadLinesInfinite()
{
while (true)
{
Thread.Sleep(100);
if (connection != null)
{
connection.CheckTCPClientReceiveSignals();
}
}
}
private NetworkConnection createNetworkConnectionWithDelegates(SendRequest methodToSendRequestOnceConnectionIsEstablished, ComputeNetworkData methodToComputeDataOnceTheyAreReceived)
{
NetworkConnection connection = new NetworkConnection(serverName, hostPort);
connection.methodToSendRequest = methodToSendRequestOnceConnectionIsEstablished;
connection.methodToComputeData = methodToComputeDataOnceTheyAreReceived;
connection.methodToAbandonConnection = AbandonConnection;
if (!readLinesThread.IsAlive)
{
readLinesThread = new Thread(() => ReadLinesInfinite());
readLinesThread.Start();
Debug.Log("Start new readLine thread");
}
return connection;
}
private void SendRequest(float lat, float lon)
{
}
private void SendRequest()
{
if (MyLocationService.instance.locationServiceIsRunning)
{
Debug.Log("Location service is running : SendRequest");
SendRequest(MyLocationService.instance.playerLocation.lat_d, MyLocationService.instance.playerLocation.lon_d);
}
else
{
Debug.LogError("Impossible to send Request : location service is not working");
}
}
public void ConnectAndSendMapEncRequest()
{
connection = createNetworkConnectionWithDelegates(SendRequest, UpdateNetworkData);
connection.StartConnectionUsingTCPClient();
}
[Header("Data Model")]
public string currentPlayerIDConnection;
#region Location
public IEnumerator StartLocationService()
{
yield return StartCoroutine(MyLocationService.instance.StartLocationService());
StartCoroutine(MyLocationService.instance.RunLocationService());
}
public IEnumerator InitializeLocationService()
{
MyLocationService.instance = new MyLocationService();
yield return StartCoroutine(StartLocationService());
}
#endregion
#region MonoBehaviour methods
/// <summary>
/// Awake will initialize the connection.
/// RunAsyncInit is just for show. You can do the normal SQLiteInit to ensure that it is
/// initialized during the Awake() phase and everything is ready during the Start() phase
/// </summary>
void Awake()
{
instance = this;
/*
firstConnectionSucceeded = false;
firstConnectionErrorMessage = null;*/
DontDestroyOnLoad(this.gameObject);
}
// Use this for initialization
void Start()
{
connection = null;
readLinesThread = new Thread(() => ReadLinesInfinite());
readLinesThread.Start();
}
/// <summary>
/// Called when DataModel is destroyed, aka: when application is closed.
/// </summary>
void OnDestroy()
{
if (connection != null)
{
connection.DropConnectionUsingTCPClient();
}
if (readLinesThread.IsAlive)
{
readLinesThread.Abort();
}
}
#endregion
}
| 28.55814 | 185 | 0.642101 |
[
"MIT"
] |
RemiFusade2/KorokGO
|
Korok GO/Assets/scripts/datamodel/DataModel.cs
| 4,914 |
C#
|
using System;
using System.Linq;
using Alea;
using Alea.Parallel.Device;
namespace AleaTK.ML {
public class Batcher: IDisposable {
[GpuParam]
private readonly int cols_, rows_, outputs_;
private readonly bool doReset_;
public long Index { get; private set; }
public int Rows => rows_;
public int Cols => cols_;
public int Outputs => outputs_;
public Batcher(Context context, float[,] data, float[,] labels, bool doReset=true) {
doReset_ = doReset;
Context = context;
Random = new Random(0);
rows_ = data.GetLength(0);
cols_ = data.GetLength(1);
outputs_ = labels.GetLength(1);
Indices = Enumerable.Range(0, Rows).ToArray();
Data = data;
Labels = labels;
IndicesTensor = context.Allocate(Indices);
DataTensor1 = context.Allocate(data);
LabelsTensor1 = context.Allocate(labels);
DataTensor2 = context.Device.Allocate<float>(Shape.Create(Rows, Cols));
LabelsTensor2 = context.Device.Allocate<float>(Shape.Create(Rows, Outputs));
DataTensor = DataTensor1;
LabelsTensor = LabelsTensor1;
if (!doReset_) return;
Index = -1;
Reset();
}
#region props
public Context Context { get; }
public Random Random { get; }
public int[] Indices { get; }
public float[,] Data { get; }
public float[,] Labels { get; }
public Tensor<int> IndicesTensor { get; }
public Tensor<float> DataTensor { get; private set; }
public Tensor<float> DataTensor1 { get; }
public Tensor<float> DataTensor2 { get; }
public Tensor<float> LabelsTensor { get; private set; }
public Tensor<float> LabelsTensor1 { get; }
public Tensor<float> LabelsTensor2 { get; }
#endregion
private void ShuffleIndices() {
var rng = Random;
var array = Indices;
var n = array.Length;
while (n > 1) {
var k = rng.Next(n--);
var temp = array[n];
array[n] = array[k];
array[k] = temp;
}
}
public void Reset() {
if (!doReset_ || Index == 0L || Context.Type != ContextType.Gpu) return;
Index = 0L;
ShuffleIndices();
Context.Copy(IndicesTensor, Indices.AsTensor());
var stream = Context.ToGpuContext().Stream;
var srcData = DataTensor == DataTensor1 ? DataTensor1.Buffer.Ptr : DataTensor2.Buffer.Ptr;
var dstData = DataTensor == DataTensor1 ? DataTensor2.Buffer.Ptr : DataTensor1.Buffer.Ptr;
var srcLabels = LabelsTensor == LabelsTensor1 ? LabelsTensor1.Buffer.Ptr : LabelsTensor2.Buffer.Ptr;
var dstLabels = LabelsTensor == LabelsTensor1 ? LabelsTensor2.Buffer.Ptr : LabelsTensor1.Buffer.Ptr;
var idx = IndicesTensor.Buffer.Ptr;
DeviceFor.For(stream, 0, Rows, i => {
var j = idx[i];
var srcDataOffset = srcData + i*cols_;
var dstDataOffset = dstData + j* cols_;
for (var k = 0; k < cols_; ++k) dstDataOffset[k] = srcDataOffset[k];
var srcLabelsOffset = srcLabels + i*outputs_;
var dstLabelsOffset = dstLabels + j* outputs_;
for (var k = 0; k < outputs_; ++k) dstLabelsOffset[k] = srcLabelsOffset[k];
});
DataTensor = DataTensor == DataTensor1 ? DataTensor2 : DataTensor1;
LabelsTensor = LabelsTensor == LabelsTensor1 ? LabelsTensor2 : LabelsTensor1;
}
public static Buffer<T> CreateBuffer<T>(Tensor<T> t, long rows, int cols, long idx) {
return new Buffer<T>(t.Device, t.Memory, new Layout(Shape.Create(rows, cols)), t.Buffer.Ptr.LongPtr(idx * cols));
}
public bool Next(long batchSize, Executor executor, Variable<float> dataVar, Variable<float> labelsVar) {
if (Index >= Rows) {
Reset();
return false;
}
var size = Index + batchSize >= Rows ? Rows - Index : batchSize;
var dataBuffer = CreateBuffer(DataTensor, size, Cols, Index);
var labelsBuffer = CreateBuffer(LabelsTensor, size, Outputs, Index);
Index += batchSize;
executor.SetTensor(dataVar, new Tensor<float>(dataBuffer));
executor.SetTensor(labelsVar, new Tensor<float>(labelsBuffer));
return true;
}
public void Dispose() {
foreach (var t in new[] {DataTensor, DataTensor1, DataTensor2, LabelsTensor1, LabelsTensor2}) t.Buffer.Dispose();
IndicesTensor.Buffer.Dispose();
}
}
}
| 40.566667 | 125 | 0.570049 |
[
"Apache-2.0"
] |
fastai/AleaTK
|
src/AleaTK/ML/Batcher.cs
| 4,870 |
C#
|
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.AspNetCore.Testing;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Logging.Testing;
namespace Microsoft.AspNetCore.SignalR.Tests
{
public class VerifiableLoggedTest : LoggedTest
{
public VerifiableLoggedTest()
{
// Ensures this isn't null in case the logged test framework
// doesn't initialize it correctly.
LoggerFactory = NullLoggerFactory.Instance;
}
public virtual IDisposable StartVerifiableLog(Func<WriteContext, bool> expectedErrorsFilter = null)
{
return CreateScope(expectedErrorsFilter);
}
private VerifyNoErrorsScope CreateScope(Func<WriteContext, bool> expectedErrorsFilter = null)
{
return new VerifyNoErrorsScope(LoggerFactory, wrappedDisposable: null, expectedErrorsFilter);
}
}
}
| 34.548387 | 111 | 0.705882 |
[
"Apache-2.0"
] |
1175169074/aspnetcore
|
src/SignalR/common/testassets/Tests.Utils/VerifiableLoggedTest.cs
| 1,071 |
C#
|
using Autobot.Models.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace Autobot.Data.Configurations
{
public class PromoCodeBatchConfiguration : IEntityTypeConfiguration<PromoCodeBatch>
{
public void Configure(EntityTypeBuilder<PromoCodeBatch> builder)
{
builder.Property(e => e.BatchId).IsRequired();
builder.Property(e => e.BatchName).IsRequired().HasMaxLength(50);
builder.Property(e => e.BrandId).IsRequired();
builder.Property(e => e.ExpirationDateTime).IsRequired();
builder.Property(e => e.NoOfPromoCodes).IsRequired();
builder.Property(e => e.LoyaltyPoints).IsRequired();
builder.Property(t => t.LastUpdatedOn)
.IsRequired()
.HasDefaultValueSql("GetDate()");
builder.Property(e => e.LastUpdatedBy).IsRequired();
builder.HasKey(e => new { e.BatchId });
builder.HasCheckConstraint("ck_NoOfPromoCodes", "NoOfPromoCodes > 0");
builder.HasMany<PromoCode>(s => s.PromoCodes)
.WithOne(c => c.PromoCodeBatch)
.HasForeignKey(b => b.BatchId);
}
}
}
| 40.129032 | 87 | 0.631833 |
[
"MIT"
] |
JaspreetSinghChahal/dotnetcore-entityframework-webapi
|
Autobot.Data/Configurations/PromoCodeBatchConfiguration.cs
| 1,246 |
C#
|
namespace RotatingWalkInMatrix
{
using System;
public class MatrixDemo
{
public static void Main()
{
//Console.WriteLine("Enter a positive number ");
//string input = Console.ReadLine();
//int n;
//while (!int.TryParse(input, out n) || n < 0 || n > 100)
//{
// Console.WriteLine("You haven't entered a correct positive number");
// input = Console.ReadLine();
//}
int n = 6;
Matrix matrix = new Matrix(n);
Console.WriteLine(matrix);
}
}
}
| 24.84 | 85 | 0.484702 |
[
"MIT"
] |
NikitoG/TelerikAcademyHomeworks
|
Hight-Quality-Code/Refactoring/RotatingWalkInMatrix/MatrixDemo.cs
| 623 |
C#
|
namespace HouseRules.Configuration.UI
{
using System;
using System.Collections.Generic;
using System.Linq;
using Common.UI;
using HouseRules.Types;
using TMPro;
using UnityEngine;
internal class RulesetSelectionPanel
{
private const int MaxRulesetsPerPage = 7;
private readonly Rulebook _rulebook;
private readonly UiHelper _uiHelper;
private readonly PageStack _pageStack;
private TextMeshPro _selectedText;
internal GameObject Panel { get; }
internal static RulesetSelectionPanel NewInstance(Rulebook rulebook, UiHelper uiHelper)
{
return new RulesetSelectionPanel(
rulebook,
uiHelper,
new GameObject("RulesetSelectionPanel"),
PageStack.NewInstance(uiHelper));
}
private RulesetSelectionPanel(Rulebook rulebook, UiHelper uiHelper, GameObject panel, PageStack pageStack)
{
this._rulebook = rulebook;
this._uiHelper = uiHelper;
this._pageStack = pageStack;
this.Panel = panel;
Render();
}
private void Render()
{
var header = CreateHeader();
header.transform.SetParent(Panel.transform, worldPositionStays: false);
header.transform.localPosition = new Vector3(0, 1f, 0);
var rulesetPartitions = PartitionRulesets();
var rulesetPages = rulesetPartitions.Select(CreateRulesetPage).ToList();
rulesetPages.ForEach(_pageStack.AddPage);
var pageNavigation = _pageStack.NavigationPanel;
pageNavigation.transform.SetParent(Panel.transform, worldPositionStays: false);
pageNavigation.transform.localPosition = new Vector3(0, -17f, 0);
}
private GameObject CreateHeader()
{
var headerContainer = new GameObject("Header");
var infoText = _uiHelper.CreateLabelText("Select a ruleset for your next private multiplayer game or skirmish.");
var rectTransform = (RectTransform)infoText.transform;
rectTransform.SetParent(headerContainer.transform, worldPositionStays: false);
rectTransform.sizeDelta = new Vector2(10, 2);
rectTransform.localPosition = new Vector3(0, 0, UiHelper.DefaultTextZShift);
var selectedText = _uiHelper.CreateLabelText("Selected ruleset: ");
rectTransform = (RectTransform)selectedText.transform;
rectTransform.SetParent(headerContainer.transform, worldPositionStays: false);
rectTransform.sizeDelta = new Vector2(10, 2);
rectTransform.localPosition = new Vector3(0, -1.5f, UiHelper.DefaultTextZShift);
_selectedText = selectedText.GetComponentInChildren<TextMeshPro>();
UpdateSelectedText();
return headerContainer;
}
private IEnumerable<List<Ruleset>> PartitionRulesets()
{
return _rulebook.Rulesets
.Select((value, index) => new { group = index / MaxRulesetsPerPage, value })
.GroupBy(pair => pair.group)
.Select(group => group.Select(g => g.value).ToList());
}
private GameObject CreateRulesetPage(List<Ruleset> rulesets)
{
var container = new GameObject("Rulesets");
container.transform.SetParent(Panel.transform, worldPositionStays: false);
container.transform.localPosition = new Vector3(0, -2.5f, 0);
for (var i = 0; i < rulesets.Count; i++)
{
var yOffset = i * -2f;
var rulesetRow = CreateRulesetRow(rulesets.ElementAt(i));
rulesetRow.transform.SetParent(container.transform, worldPositionStays: false);
rulesetRow.transform.localPosition = new Vector3(0, yOffset, 0);
}
return container;
}
private GameObject CreateRulesetRow(Ruleset ruleset)
{
var roomRowContainer = new GameObject(ruleset.Name);
var button = _uiHelper.CreateButton(SelectRulesetAction(ruleset.Name));
button.transform.SetParent(roomRowContainer.transform, worldPositionStays: false);
button.transform.localScale = new Vector3(1f, 0.6f, 1f);
button.transform.localPosition = new Vector3(-4.5f, 0, UiHelper.DefaultButtonZShift);
var buttonText = _uiHelper.CreateText(ruleset.Name, Color.white, UiHelper.DefaultLabelFontSize);
buttonText.transform.SetParent(roomRowContainer.transform, worldPositionStays: false);
buttonText.transform.localPosition = new Vector3(-4.5f, 0, UiHelper.DefaultButtonZShift + UiHelper.DefaultTextZShift);
var description = _uiHelper.CreateLabelText(ruleset.Description);
var rectTransform = (RectTransform)description.transform;
rectTransform.SetParent(roomRowContainer.transform, worldPositionStays: false);
rectTransform.pivot = Vector2.left;
rectTransform.sizeDelta = new Vector2(9, 1);
rectTransform.localPosition = new Vector3(-9.7f, -0.5f, UiHelper.DefaultTextZShift);
return roomRowContainer;
}
private Action SelectRulesetAction(string rulesetName)
{
return () =>
{
HR.SelectRuleset(rulesetName);
UpdateSelectedText();
};
}
private void UpdateSelectedText()
{
_selectedText.text = $"Selected ruleset: {HR.SelectedRuleset.Name}";
}
}
}
| 39.901408 | 130 | 0.634663 |
[
"MIT"
] |
orendain/DemeoMods
|
HouseRules_Configuration/UI/RulesetSelectionPanel.cs
| 5,668 |
C#
|
// <copyright file="ClockLibrary.cs" company="MIT License">
// Licensed under the MIT License. See LICENSE file in the project root for license information.
// </copyright>
namespace SmallBasic.Editor.Libraries
{
using System;
using System.Globalization;
using SmallBasic.Compiler.Runtime;
internal sealed class ClockLibrary : IClockLibrary
{
public string Get_Date() => DateTime.Now.ToString(DateTimeFormatInfo.GetInstance(CultureInfo.CurrentCulture).ShortDatePattern, CultureInfo.CurrentCulture);
public decimal Get_Day() => DateTime.Now.Day;
public decimal Get_ElapsedMilliseconds() => (decimal)(DateTime.Now - new DateTime(1900, 1, 1)).TotalMilliseconds;
public decimal Get_Hour() => DateTime.Now.Hour;
public decimal Get_Millisecond() => DateTime.Now.Millisecond;
public decimal Get_Minute() => DateTime.Now.Minute;
public decimal Get_Month() => DateTime.Now.Month;
public decimal Get_Second() => DateTime.Now.Second;
public string Get_Time() => DateTime.Now.ToString(DateTimeFormatInfo.GetInstance(CultureInfo.CurrentCulture).LongTimePattern, CultureInfo.CurrentCulture);
public string Get_WeekDay() => DateTime.Now.ToString("dddd", CultureInfo.CurrentCulture);
public decimal Get_Year() => DateTime.Now.Year;
}
}
| 37.361111 | 163 | 0.72342 |
[
"MIT"
] |
AndrewCook/smallbasic-editor
|
Source/SmallBasic.Editor/Libraries/ClockLibrary.cs
| 1,347 |
C#
|
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace UnitTests.EF6.Model
{
public class CompositeKeyEntity
{
[Column(Order = 0), Key]
public int FirstKeyEntityId { get; set; }
[Column(Order = 1), Key]
public int SecondKeyEntityId { get; set; }
public virtual FirstKeyEntity FirstKeyEntity { get; set; }
public virtual SecondKeyEntity SecondKeyEntity { get; set; }
public string Name { get; set; }
}
}
| 29.166667 | 68 | 0.670476 |
[
"MIT"
] |
NathanNZ/BulkExtensions
|
UnitTests.EF6/Model/CompositeKeyEntity.cs
| 525 |
C#
|
namespace Fonet.DataTypes
{
internal class ToBeImplemented
{
public ToBeImplemented(string value)
{
}
}
}
| 15.666667 | 44 | 0.588652 |
[
"Apache-2.0"
] |
DaveDezinski/Fo.Net
|
src/DataTypes/ToBeImplemented.cs
| 141 |
C#
|
// This file is auto-generated, don't edit it. Thanks.
using System;
using System.Collections.Generic;
using System.IO;
using Tea;
namespace AlibabaCloud.SDK.Ecs20140526.Models
{
public class ModifySecurityGroupRuleResponse : TeaModel {
[NameInMap("RequestId")]
[Validation(Required=true)]
public string RequestId { get; set; }
}
}
| 19.421053 | 61 | 0.699187 |
[
"Apache-2.0"
] |
alibabacloud-sdk-swift/alibabacloud-sdk
|
ecs-20140526/csharp/core/Models/ModifySecurityGroupRuleResponse.cs
| 369 |
C#
|
namespace _000_DataAccess
{
public static class Connection
{
public const string Default = @"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=TitanCamp_Expressions_BloggingDB;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False;Pooling=true";
}
}
| 51 | 279 | 0.806723 |
[
"Apache-2.0"
] |
arttonoyan/dotnet-courses
|
Lesson_Expressions/Part2/000_DataAccess/Connection.cs
| 359 |
C#
|
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information.
using System.Collections.Generic;
namespace Analyzer.Utilities.Extensions
{
internal static class KeyValuePairExtensions
{
public static void Deconstruct<TKey, TValue>(this KeyValuePair<TKey, TValue> pair, out TKey key, out TValue value)
{
key = pair.Key;
value = pair.Value;
}
public static KeyValuePair<TKey?, TValue?> AsNullable<TKey, TValue>(this KeyValuePair<TKey, TValue> pair)
{
// This conversion is safe
return pair!;
}
}
}
| 31.363636 | 145 | 0.647826 |
[
"MIT"
] |
AndreasVolkmann/roslyn-analyzers
|
src/Utilities/Compiler/Extensions/KeyValuePairExtensions.cs
| 692 |
C#
|
// -----------------------------------------------------------------------------
// 让 .NET 开发更简单,更通用,更流行。
// Copyright © 2020-2021 Furion, 百小僧, Baiqian Co.,Ltd.
//
// 框架名称:Furion
// 框架作者:百小僧
// 框架版本:2.8.6
// 源码地址:Gitee: https://gitee.com/dotnetchina/Furion
// Github:https://github.com/monksoul/Furion
// 开源协议:Apache-2.0(https://gitee.com/dotnetchina/Furion/blob/master/LICENSE)
// -----------------------------------------------------------------------------
using Furion.ConfigurableOptions;
namespace Furion.FriendlyException
{
/// <summary>
/// 异常配置选项,最优的方式是采用后期配置,也就是所有异常状态码先不设置(推荐)
/// </summary>
public sealed class ErrorCodeMessageSettingsOptions : IConfigurableOptions
{
/// <summary>
/// 异常状态码配置列表
/// </summary>
public object[][] Definitions { get; set; }
}
}
| 31.037037 | 81 | 0.523866 |
[
"Apache-2.0"
] |
staoran/Furion
|
framework/Furion.Pure/FriendlyException/Options/ErrorCodeMessageSettingsOptions.cs
| 1,035 |
C#
|
using System;
using System.IO;
using System.Linq;
using BizHawk.Client.Common;
using BizHawk.Common;
using BizHawk.Emulation.Common;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace BizHawk.Tests.Client.Common.Movie
{
[TestClass]
public class ZwinderStateManagerTests
{
private ZwinderStateManager CreateSmallZwinder(IStatable ss)
{
var zw = new ZwinderStateManager(new ZwinderStateManagerSettings
{
CurrentBufferSize = 1,
CurrentTargetFrameLength = 10000,
RecentBufferSize = 1,
RecentTargetFrameLength = 100000,
AncientStateInterval = 50000
}, f => false);
var ms = new MemoryStream();
ss.SaveStateBinary(new BinaryWriter(ms));
zw.Engage(ms.ToArray());
return zw;
}
private IStatable CreateStateSource() => new StateSource {PaddingData = new byte[1000]};
[TestMethod]
public void SaveCreateRoundTrip()
{
var ms = new MemoryStream();
var zw = new ZwinderStateManager(new ZwinderStateManagerSettings
{
CurrentBufferSize = 16,
CurrentTargetFrameLength = 10000,
RecentBufferSize = 16,
RecentTargetFrameLength = 100000,
AncientStateInterval = 50000
}, f => false);
zw.SaveStateHistory(new BinaryWriter(ms));
var buff = ms.ToArray();
var rms = new MemoryStream(buff, false);
var zw2 = ZwinderStateManager.Create(new BinaryReader(rms), zw.Settings, f => false);
// TODO: we could assert more things here to be thorough
Assert.IsNotNull(zw2);
Assert.AreEqual(zw.Settings.CurrentBufferSize, zw2.Settings.CurrentBufferSize);
Assert.AreEqual(zw.Settings.RecentBufferSize, zw2.Settings.RecentBufferSize);
}
[TestMethod]
public void CountEvictWorks()
{
using var zb = new ZwinderBuffer(new RewindConfig
{
BufferSize = 1,
TargetFrameLength = 1
});
var ss = new StateSource
{
PaddingData = new byte[10]
};
var stateCount = 0;
for (int i = 0; i < 1000000; i++)
{
zb.Capture(i, s => ss.SaveStateBinary(new BinaryWriter(s)), j => stateCount--, true);
stateCount++;
}
Assert.AreEqual(zb.Count, stateCount);
}
[TestMethod]
public void SaveCreateBufferRoundTrip()
{
RewindConfig config = new RewindConfig
{
BufferSize = 1,
TargetFrameLength = 10
};
var buff = new ZwinderBuffer(config);
var ss = new StateSource { PaddingData = new byte[500] };
for (var frame = 0; frame < 2090; frame++)
{
ss.Frame = frame;
buff.Capture(frame, (s) => ss.SaveStateBinary(new BinaryWriter(s)));
}
// states are 504 bytes large, buffer is 1048576 bytes large
Assert.AreEqual(buff.Count, 2080);
Assert.AreEqual(buff.GetState(0).Frame, 10);
Assert.AreEqual(buff.GetState(2079).Frame, 2089);
Assert.AreEqual(StateSource.GetFrameNumberInState(buff.GetState(0).GetReadStream()), 10);
Assert.AreEqual(StateSource.GetFrameNumberInState(buff.GetState(2079).GetReadStream()), 2089);
var ms = new MemoryStream();
buff.SaveStateBinary(new BinaryWriter(ms));
ms.Position = 0;
var buff2 = ZwinderBuffer.Create(new BinaryReader(ms), config);
Assert.AreEqual(buff.Size, buff2.Size);
Assert.AreEqual(buff.Used, buff2.Used);
Assert.AreEqual(buff2.Count, 2080);
Assert.AreEqual(buff2.GetState(0).Frame, 10);
Assert.AreEqual(buff2.GetState(2079).Frame, 2089);
Assert.AreEqual(StateSource.GetFrameNumberInState(buff2.GetState(0).GetReadStream()), 10);
Assert.AreEqual(StateSource.GetFrameNumberInState(buff2.GetState(2079).GetReadStream()), 2089);
}
[TestMethod]
public void StateBeforeFrame()
{
var ss = new StateSource { PaddingData = new byte[1000] };
var zw = new ZwinderStateManager(new ZwinderStateManagerSettings
{
CurrentBufferSize = 1,
CurrentTargetFrameLength = 10000,
RecentBufferSize = 1,
RecentTargetFrameLength = 100000,
AncientStateInterval = 50000
}, f => false);
{
var ms = new MemoryStream();
ss.SaveStateBinary(new BinaryWriter(ms));
zw.Engage(ms.ToArray());
}
for (int frame = 0; frame <= 10440; frame++)
{
ss.Frame = frame;
zw.Capture(frame, ss);
}
var (f, data) = zw.GetStateClosestToFrame(10440);
var actual = StateSource.GetFrameNumberInState(data);
Assert.AreEqual(f, actual);
Assert.IsTrue(actual <= 10440);
}
[TestMethod]
public void Last_Correct_WhenReservedGreaterThanCurrent()
{
// Arrange
const int futureReservedFrame = 1000;
var ss = CreateStateSource();
using var zw = CreateSmallZwinder(ss);
zw.CaptureReserved(futureReservedFrame, ss);
for (int i = 1; i < 20; i++)
{
zw.Capture(i, ss);
}
// Act
var actual = zw.Last;
// Assert
Assert.AreEqual(futureReservedFrame, actual);
}
[TestMethod]
public void Last_Correct_WhenCurrentIsLast()
{
// Arrange
const int totalCurrentFrames = 20;
const int expectedFrameGap = 9;
var ss = CreateStateSource();
using var zw = CreateSmallZwinder(ss);
for (int i = 1; i < totalCurrentFrames; i++)
{
zw.Capture(i, ss);
}
// Act
var actual = zw.Last;
// Assert
Assert.AreEqual(totalCurrentFrames - expectedFrameGap, actual);
}
[TestMethod]
public void HasState_Correct_WhenReservedGreaterThanCurrent()
{
// Arrange
const int futureReservedFrame = 1000;
var ss = CreateStateSource();
using var zw = CreateSmallZwinder(ss);
zw.CaptureReserved(futureReservedFrame, ss);
for (int i = 1; i < 20; i++)
{
zw.Capture(i, ss);
}
// Act
var actual = zw.HasState(futureReservedFrame);
// Assert
Assert.IsTrue(actual);
}
[TestMethod]
public void HasState_Correct_WhenCurrentIsLast()
{
// Arrange
const int totalCurrentFrames = 20;
const int expectedFrameGap = 9;
var ss = CreateStateSource();
using var zw = CreateSmallZwinder(ss);
for (int i = 1; i < totalCurrentFrames; i++)
{
zw.Capture(i, ss);
}
// Act
var actual = zw.HasState(totalCurrentFrames - expectedFrameGap);
// Assert
Assert.IsTrue(actual);
}
[TestMethod]
public void GetStateClosestToFrame_Correct_WhenReservedGreaterThanCurrent()
{
// Arrange
const int futureReservedFrame = 1000;
var ss = CreateStateSource();
using var zw = CreateSmallZwinder(ss);
zw.CaptureReserved(futureReservedFrame, ss);
for (int i = 1; i < 10; i++)
{
zw.Capture(i, ss);
}
// Act
var actual = zw.GetStateClosestToFrame(futureReservedFrame + 1);
// Assert
Assert.IsNotNull(actual);
Assert.AreEqual(futureReservedFrame, actual.Key);
}
[TestMethod]
public void GetStateClosestToFrame_Correct_WhenCurrentIsLast()
{
// Arrange
const int totalCurrentFrames = 20;
const int expectedFrameGap = 9;
var ss = CreateStateSource();
using var zw = CreateSmallZwinder(ss);
for (int i = 1; i < totalCurrentFrames; i++)
{
zw.Capture(i, ss);
}
// Act
var actual = zw.GetStateClosestToFrame(totalCurrentFrames);
// Assert
Assert.AreEqual(totalCurrentFrames - expectedFrameGap, actual.Key);
}
[TestMethod]
public void InvalidateAfter_Correct_WhenReservedGreaterThanCurrent()
{
// Arrange
const int futureReservedFrame = 1000;
var ss = CreateStateSource();
using var zw = CreateSmallZwinder(ss);
zw.CaptureReserved(futureReservedFrame, ss);
for (int i = 1; i < 10; i++)
{
zw.Capture(i, ss);
}
// Act
zw.InvalidateAfter(futureReservedFrame - 1);
// Assert
Assert.IsFalse(zw.HasState(futureReservedFrame));
}
[TestMethod]
public void InvalidateAfter_Correct_WhenCurrentIsLast()
{
// Arrange
const int totalCurrentFrames = 10;
var ss = CreateStateSource();
using var zw = CreateSmallZwinder(ss);
for (int i = 1; i < totalCurrentFrames; i++)
{
zw.Capture(i, ss);
}
// Act
zw.InvalidateAfter(totalCurrentFrames - 1);
// Assert
Assert.IsFalse(zw.HasState(totalCurrentFrames));
}
[TestMethod]
public void Count_NoReserved()
{
// Arrange
const int totalCurrentFrames = 20;
const int expectedFrameGap = 10;
var ss = CreateStateSource();
using var zw = CreateSmallZwinder(ss);
for (int i = 1; i < totalCurrentFrames; i++)
{
zw.Capture(i, ss);
}
// Act
var actual = zw.Count;
// Assert
var expected = (totalCurrentFrames / expectedFrameGap) + 1;
Assert.AreEqual(expected, actual);
}
[TestMethod]
public void Count_WithReserved()
{
// Arrange
const int totalCurrentFrames = 20;
const int expectedFrameGap = 10;
var ss = CreateStateSource();
using var zw = CreateSmallZwinder(ss);
zw.CaptureReserved(1000, ss);
for (int i = 1; i < totalCurrentFrames; i++)
{
zw.Capture(i, ss);
}
// Act
var actual = zw.Count;
// Assert
var expected = (totalCurrentFrames / expectedFrameGap) + 2;
Assert.AreEqual(expected, actual);
}
[TestMethod]
public void StateCache()
{
var ss = CreateStateSource();
var zw = new ZwinderStateManager(new ZwinderStateManagerSettings
{
CurrentBufferSize = 2,
CurrentTargetFrameLength = 1000,
RecentBufferSize = 2,
RecentTargetFrameLength = 1000,
AncientStateInterval = 100
}, f => false);
for (int i = 0; i < 1000; i += 200)
{
zw.CaptureReserved(i, ss);
}
for (int i = 400; i < 1000; i += 400)
{
zw.EvictReserved(i);
}
for (int i = 0; i < 10000; i++)
{
zw.Capture(i, ss);
}
zw.Capture(101, ss);
var allStates = zw.AllStates()
.Select(s => s.Frame)
.ToList();
for (int i = 0; i < 10000; i++)
{
var actual = zw.HasState(i);
var expected = allStates.Contains(i);
Assert.AreEqual(expected, actual);
}
}
[TestMethod]
public void Clear_KeepsZeroState()
{
// Arrange
var ss = CreateStateSource();
using var zw = CreateSmallZwinder(ss);
zw.CaptureReserved(1000, ss);
for (int i = 1; i < 10; i++)
{
zw.Capture(i, ss);
}
// Act
zw.Clear();
// Assert
Assert.AreEqual(1, zw.AllStates().Count());
Assert.AreEqual(0, zw.AllStates().Single().Frame);
}
[TestMethod]
public void WhatIfTheHeadStateWrapsAround()
{
var ss = new StateSource
{
PaddingData = new byte[400 * 1000]
};
using var zw = new ZwinderBuffer(new RewindConfig
{
BufferSize = 1,
TargetFrameLength = 1
});
// Need to get data in the zwinderbuffer so that the last state, and the last state in particular, wraps around
ss.Frame = 1;
zw.Capture(1, s => ss.SaveStateBinary(new BinaryWriter(s)), null, true);
ss.Frame = 2;
zw.Capture(2, s => ss.SaveStateBinary(new BinaryWriter(s)), null, true);
ss.Frame = 3;
zw.Capture(3, s => ss.SaveStateBinary(new BinaryWriter(s)), null, true);
zw.SaveStateBinary(new BinaryWriter(new MemoryStream()));
}
[TestMethod]
public void TestReadByteCorruption()
{
using var zw = new ZwinderBuffer(new RewindConfig
{
BufferSize = 1,
TargetFrameLength = 1
});
zw.Capture(0, s =>
{
s.Write(new byte[] { 1, 2, 3, 4 });
});
zw.Capture(1, s =>
{
s.Write(new byte[] { 5, 6, 7, 8 });
});
var state = zw.GetState(0);
Assert.AreEqual(0, state.Frame);
Assert.AreEqual(4, state.Size);
Assert.AreEqual(1, state.GetReadStream().ReadByte());
}
[TestMethod]
public void TestReadBytesCorruption()
{
using var zw = new ZwinderBuffer(new RewindConfig
{
BufferSize = 1,
TargetFrameLength = 1
});
zw.Capture(0, s =>
{
s.Write(new byte[] { 1, 2, 3, 4 });
});
zw.Capture(1, s =>
{
s.Write(new byte[] { 5, 6, 7, 8 });
});
var state = zw.GetState(0);
Assert.AreEqual(0, state.Frame);
Assert.AreEqual(4, state.Size);
var bb = new byte[2];
state.GetReadStream().Read(bb, 0, 2);
Assert.AreEqual(1, bb[0]);
Assert.AreEqual(2, bb[1]);
}
[TestMethod]
public void TestWriteByteCorruption()
{
using var zw = new ZwinderBuffer(new RewindConfig
{
BufferSize = 1,
TargetFrameLength = 1
});
zw.Capture(0, s =>
{
s.WriteByte(1);
s.WriteByte(2);
s.WriteByte(3);
s.WriteByte(4);
});
zw.Capture(1, s =>
{
s.WriteByte(5);
s.WriteByte(6);
s.WriteByte(7);
s.WriteByte(8);
});
zw.GetState(0).GetReadStream(); // Rewinds the backing store
zw.Capture(2, s =>
{
s.WriteByte(9);
s.WriteByte(10);
s.WriteByte(11);
s.WriteByte(12);
});
var state = zw.GetState(0);
Assert.AreEqual(0, state.Frame);
Assert.AreEqual(4, state.Size);
Assert.AreEqual(1, state.GetReadStream().ReadByte());
}
[TestMethod]
public void BufferStressTest()
{
var r = new Random(8675309);
using var zw = new ZwinderBuffer(new RewindConfig
{
BufferSize = 1,
TargetFrameLength = 1
});
var buff = new byte[40000];
for (int round = 0; round < 10; round++)
{
for (int i = 0; i < 500; i++)
{
zw.Capture(i, s =>
{
var length = r.Next(40000);
var bw = new BinaryWriter(s);
var bytes = buff.AsSpan(0, length);
r.NextBytes(bytes);
bw.Write(length);
bw.Write(bytes);
bw.Write(CRC32.Calculate(bytes));
});
}
for (int i = 0; i < zw.Count; i++)
{
var info = zw.GetState(i);
var s = info.GetReadStream();
var br = new BinaryReader(s);
var length = info.Size;
if (length != br.ReadInt32() + 8)
throw new Exception("Length field corrupted");
var bytes = buff.AsSpan(0, length - 8);
br.Read(bytes);
if (br.ReadUInt32() != CRC32.Calculate(bytes))
throw new Exception("Data or CRC field corrupted");
}
}
}
private class StateSource : IStatable
{
public int Frame { get; set; }
public byte[] PaddingData { get; set; } = Array.Empty<byte>();
public void LoadStateBinary(BinaryReader reader)
{
Frame = reader.ReadInt32();
reader.Read(PaddingData, 0, PaddingData.Length);
}
public void SaveStateBinary(BinaryWriter writer)
{
writer.Write(Frame);
writer.Write(PaddingData);
}
public static int GetFrameNumberInState(Stream stream)
{
var ss = new StateSource();
ss.LoadStateBinary(new BinaryReader(stream));
return ss.Frame;
}
}
}
}
| 24.672788 | 115 | 0.621828 |
[
"MIT"
] |
Ortheore/BizHawk
|
src/BizHawk.Tests/Client.Common/Movie/ZwinderStateManagerTests.cs
| 14,779 |
C#
|
#pragma checksum "C:\Revature\042020-dotnet-uta-RevRepo\kingsleyOnonachi_repo1\Proj1\Views\Customer\Create.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "ea5bc8a4d87fa1b91583df3ae771e0095b6cc714"
// <auto-generated/>
#pragma warning disable 1591
[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_Customer_Create), @"mvc.1.0.view", @"/Views/Customer/Create.cshtml")]
namespace AspNetCore
{
#line hidden
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
#nullable restore
#line 1 "C:\Revature\042020-dotnet-uta-RevRepo\kingsleyOnonachi_repo1\Proj1\Views\_ViewImports.cshtml"
using Proj1;
#line default
#line hidden
#nullable disable
#nullable restore
#line 2 "C:\Revature\042020-dotnet-uta-RevRepo\kingsleyOnonachi_repo1\Proj1\Views\_ViewImports.cshtml"
using Proj1.Models;
#line default
#line hidden
#nullable disable
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"ea5bc8a4d87fa1b91583df3ae771e0095b6cc714", @"/Views/Customer/Create.cshtml")]
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"b2de7b03f38fb002db0cffff48521a57eb336a78", @"/Views/_ViewImports.cshtml")]
public class Views_Customer_Create : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<Proj1.Models.CustomerViewModel>
{
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("text-danger"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_1 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("control-label"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_2 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("form-control"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_3 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-action", "Create", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_4 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-action", "Index", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
#line hidden
#pragma warning disable 0649
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext __tagHelperExecutionContext;
#pragma warning restore 0649
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner __tagHelperRunner = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner();
#pragma warning disable 0169
private string __tagHelperStringValueBuffer;
#pragma warning restore 0169
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __backed__tagHelperScopeManager = null;
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __tagHelperScopeManager
{
get
{
if (__backed__tagHelperScopeManager == null)
{
__backed__tagHelperScopeManager = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope);
}
return __backed__tagHelperScopeManager;
}
}
private global::Microsoft.AspNetCore.Mvc.TagHelpers.FormTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper;
private global::Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper;
private global::Microsoft.AspNetCore.Mvc.TagHelpers.ValidationSummaryTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationSummaryTagHelper;
private global::Microsoft.AspNetCore.Mvc.TagHelpers.LabelTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper;
private global::Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper;
private global::Microsoft.AspNetCore.Mvc.TagHelpers.ValidationMessageTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper;
private global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper;
#pragma warning disable 1998
public async override global::System.Threading.Tasks.Task ExecuteAsync()
{
WriteLiteral("\r\n");
#nullable restore
#line 3 "C:\Revature\042020-dotnet-uta-RevRepo\kingsleyOnonachi_repo1\Proj1\Views\Customer\Create.cshtml"
ViewData["Title"] = "Create";
#line default
#line hidden
#nullable disable
WriteLiteral("\r\n<h1>Create</h1>\r\n\r\n<h4>CustomerViewModel</h4>\r\n<hr />\r\n<div class=\"row\">\r\n <div class=\"col-md-4\">\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("form", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "ea5bc8a4d87fa1b91583df3ae771e0095b6cc7146021", async() => {
WriteLiteral("\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("div", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "ea5bc8a4d87fa1b91583df3ae771e0095b6cc7146291", async() => {
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationSummaryTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.ValidationSummaryTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationSummaryTagHelper);
#nullable restore
#line 14 "C:\Revature\042020-dotnet-uta-RevRepo\kingsleyOnonachi_repo1\Proj1\Views\Customer\Create.cshtml"
__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationSummaryTagHelper.ValidationSummary = global::Microsoft.AspNetCore.Mvc.Rendering.ValidationSummary.ModelOnly;
#line default
#line hidden
#nullable disable
__tagHelperExecutionContext.AddTagHelperAttribute("asp-validation-summary", __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationSummaryTagHelper.ValidationSummary, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n <div class=\"form-group\">\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("label", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "ea5bc8a4d87fa1b91583df3ae771e0095b6cc7148032", async() => {
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.LabelTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper);
#nullable restore
#line 16 "C:\Revature\042020-dotnet-uta-RevRepo\kingsleyOnonachi_repo1\Proj1\Views\Customer\Create.cshtml"
__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.FirstName);
#line default
#line hidden
#nullable disable
__tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "ea5bc8a4d87fa1b91583df3ae771e0095b6cc7149645", async() => {
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper);
#nullable restore
#line 17 "C:\Revature\042020-dotnet-uta-RevRepo\kingsleyOnonachi_repo1\Proj1\Views\Customer\Create.cshtml"
__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.FirstName);
#line default
#line hidden
#nullable disable
__tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("span", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "ea5bc8a4d87fa1b91583df3ae771e0095b6cc71411252", async() => {
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.ValidationMessageTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper);
#nullable restore
#line 18 "C:\Revature\042020-dotnet-uta-RevRepo\kingsleyOnonachi_repo1\Proj1\Views\Customer\Create.cshtml"
__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.FirstName);
#line default
#line hidden
#nullable disable
__tagHelperExecutionContext.AddTagHelperAttribute("asp-validation-for", __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n </div>\r\n <div class=\"form-group\">\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("label", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "ea5bc8a4d87fa1b91583df3ae771e0095b6cc71413000", async() => {
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.LabelTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper);
#nullable restore
#line 21 "C:\Revature\042020-dotnet-uta-RevRepo\kingsleyOnonachi_repo1\Proj1\Views\Customer\Create.cshtml"
__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.LastName);
#line default
#line hidden
#nullable disable
__tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "ea5bc8a4d87fa1b91583df3ae771e0095b6cc71414613", async() => {
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper);
#nullable restore
#line 22 "C:\Revature\042020-dotnet-uta-RevRepo\kingsleyOnonachi_repo1\Proj1\Views\Customer\Create.cshtml"
__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.LastName);
#line default
#line hidden
#nullable disable
__tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("span", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "ea5bc8a4d87fa1b91583df3ae771e0095b6cc71416220", async() => {
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.ValidationMessageTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper);
#nullable restore
#line 23 "C:\Revature\042020-dotnet-uta-RevRepo\kingsleyOnonachi_repo1\Proj1\Views\Customer\Create.cshtml"
__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.LastName);
#line default
#line hidden
#nullable disable
__tagHelperExecutionContext.AddTagHelperAttribute("asp-validation-for", __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n </div>\r\n <div class=\"form-group\">\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("label", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "ea5bc8a4d87fa1b91583df3ae771e0095b6cc71417967", async() => {
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.LabelTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper);
#nullable restore
#line 26 "C:\Revature\042020-dotnet-uta-RevRepo\kingsleyOnonachi_repo1\Proj1\Views\Customer\Create.cshtml"
__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.StreetAddress);
#line default
#line hidden
#nullable disable
__tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "ea5bc8a4d87fa1b91583df3ae771e0095b6cc71419585", async() => {
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper);
#nullable restore
#line 27 "C:\Revature\042020-dotnet-uta-RevRepo\kingsleyOnonachi_repo1\Proj1\Views\Customer\Create.cshtml"
__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.StreetAddress);
#line default
#line hidden
#nullable disable
__tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("span", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "ea5bc8a4d87fa1b91583df3ae771e0095b6cc71421197", async() => {
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.ValidationMessageTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper);
#nullable restore
#line 28 "C:\Revature\042020-dotnet-uta-RevRepo\kingsleyOnonachi_repo1\Proj1\Views\Customer\Create.cshtml"
__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.StreetAddress);
#line default
#line hidden
#nullable disable
__tagHelperExecutionContext.AddTagHelperAttribute("asp-validation-for", __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n </div>\r\n <div class=\"form-group\">\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("label", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "ea5bc8a4d87fa1b91583df3ae771e0095b6cc71422949", async() => {
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.LabelTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper);
#nullable restore
#line 31 "C:\Revature\042020-dotnet-uta-RevRepo\kingsleyOnonachi_repo1\Proj1\Views\Customer\Create.cshtml"
__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.CityAddress);
#line default
#line hidden
#nullable disable
__tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "ea5bc8a4d87fa1b91583df3ae771e0095b6cc71424565", async() => {
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper);
#nullable restore
#line 32 "C:\Revature\042020-dotnet-uta-RevRepo\kingsleyOnonachi_repo1\Proj1\Views\Customer\Create.cshtml"
__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.CityAddress);
#line default
#line hidden
#nullable disable
__tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("span", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "ea5bc8a4d87fa1b91583df3ae771e0095b6cc71426175", async() => {
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.ValidationMessageTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper);
#nullable restore
#line 33 "C:\Revature\042020-dotnet-uta-RevRepo\kingsleyOnonachi_repo1\Proj1\Views\Customer\Create.cshtml"
__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.CityAddress);
#line default
#line hidden
#nullable disable
__tagHelperExecutionContext.AddTagHelperAttribute("asp-validation-for", __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n </div>\r\n <div class=\"form-group\">\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("label", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "ea5bc8a4d87fa1b91583df3ae771e0095b6cc71427925", async() => {
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.LabelTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper);
#nullable restore
#line 36 "C:\Revature\042020-dotnet-uta-RevRepo\kingsleyOnonachi_repo1\Proj1\Views\Customer\Create.cshtml"
__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.StateAddress);
#line default
#line hidden
#nullable disable
__tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "ea5bc8a4d87fa1b91583df3ae771e0095b6cc71429542", async() => {
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper);
#nullable restore
#line 37 "C:\Revature\042020-dotnet-uta-RevRepo\kingsleyOnonachi_repo1\Proj1\Views\Customer\Create.cshtml"
__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.StateAddress);
#line default
#line hidden
#nullable disable
__tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("span", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "ea5bc8a4d87fa1b91583df3ae771e0095b6cc71431153", async() => {
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.ValidationMessageTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper);
#nullable restore
#line 38 "C:\Revature\042020-dotnet-uta-RevRepo\kingsleyOnonachi_repo1\Proj1\Views\Customer\Create.cshtml"
__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.StateAddress);
#line default
#line hidden
#nullable disable
__tagHelperExecutionContext.AddTagHelperAttribute("asp-validation-for", __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n </div>\r\n <div class=\"form-group\">\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("label", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "ea5bc8a4d87fa1b91583df3ae771e0095b6cc71432904", async() => {
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.LabelTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper);
#nullable restore
#line 41 "C:\Revature\042020-dotnet-uta-RevRepo\kingsleyOnonachi_repo1\Proj1\Views\Customer\Create.cshtml"
__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.CountryAddress);
#line default
#line hidden
#nullable disable
__tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "ea5bc8a4d87fa1b91583df3ae771e0095b6cc71434523", async() => {
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper);
#nullable restore
#line 42 "C:\Revature\042020-dotnet-uta-RevRepo\kingsleyOnonachi_repo1\Proj1\Views\Customer\Create.cshtml"
__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.CountryAddress);
#line default
#line hidden
#nullable disable
__tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("span", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "ea5bc8a4d87fa1b91583df3ae771e0095b6cc71436136", async() => {
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.ValidationMessageTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper);
#nullable restore
#line 43 "C:\Revature\042020-dotnet-uta-RevRepo\kingsleyOnonachi_repo1\Proj1\Views\Customer\Create.cshtml"
__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.CountryAddress);
#line default
#line hidden
#nullable disable
__tagHelperExecutionContext.AddTagHelperAttribute("asp-validation-for", __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n </div>\r\n <div class=\"form-group\">\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("label", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "ea5bc8a4d87fa1b91583df3ae771e0095b6cc71437889", async() => {
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.LabelTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper);
#nullable restore
#line 46 "C:\Revature\042020-dotnet-uta-RevRepo\kingsleyOnonachi_repo1\Proj1\Views\Customer\Create.cshtml"
__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.UserName);
#line default
#line hidden
#nullable disable
__tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "ea5bc8a4d87fa1b91583df3ae771e0095b6cc71439502", async() => {
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper);
#nullable restore
#line 47 "C:\Revature\042020-dotnet-uta-RevRepo\kingsleyOnonachi_repo1\Proj1\Views\Customer\Create.cshtml"
__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.UserName);
#line default
#line hidden
#nullable disable
__tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("span", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "ea5bc8a4d87fa1b91583df3ae771e0095b6cc71441109", async() => {
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.ValidationMessageTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper);
#nullable restore
#line 48 "C:\Revature\042020-dotnet-uta-RevRepo\kingsleyOnonachi_repo1\Proj1\Views\Customer\Create.cshtml"
__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.UserName);
#line default
#line hidden
#nullable disable
__tagHelperExecutionContext.AddTagHelperAttribute("asp-validation-for", __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n </div>\r\n <div class=\"form-group\">\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("label", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "ea5bc8a4d87fa1b91583df3ae771e0095b6cc71442856", async() => {
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.LabelTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper);
#nullable restore
#line 51 "C:\Revature\042020-dotnet-uta-RevRepo\kingsleyOnonachi_repo1\Proj1\Views\Customer\Create.cshtml"
__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Email);
#line default
#line hidden
#nullable disable
__tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "ea5bc8a4d87fa1b91583df3ae771e0095b6cc71444466", async() => {
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper);
#nullable restore
#line 52 "C:\Revature\042020-dotnet-uta-RevRepo\kingsleyOnonachi_repo1\Proj1\Views\Customer\Create.cshtml"
__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Email);
#line default
#line hidden
#nullable disable
__tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("span", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "ea5bc8a4d87fa1b91583df3ae771e0095b6cc71446070", async() => {
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.ValidationMessageTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper);
#nullable restore
#line 53 "C:\Revature\042020-dotnet-uta-RevRepo\kingsleyOnonachi_repo1\Proj1\Views\Customer\Create.cshtml"
__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Email);
#line default
#line hidden
#nullable disable
__tagHelperExecutionContext.AddTagHelperAttribute("asp-validation-for", __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n </div>\r\n <div class=\"form-group\">\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("label", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "ea5bc8a4d87fa1b91583df3ae771e0095b6cc71447814", async() => {
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.LabelTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper);
#nullable restore
#line 56 "C:\Revature\042020-dotnet-uta-RevRepo\kingsleyOnonachi_repo1\Proj1\Views\Customer\Create.cshtml"
__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.PassWord);
#line default
#line hidden
#nullable disable
__tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "ea5bc8a4d87fa1b91583df3ae771e0095b6cc71449427", async() => {
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper);
#nullable restore
#line 57 "C:\Revature\042020-dotnet-uta-RevRepo\kingsleyOnonachi_repo1\Proj1\Views\Customer\Create.cshtml"
__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.PassWord);
#line default
#line hidden
#nullable disable
__tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("span", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "ea5bc8a4d87fa1b91583df3ae771e0095b6cc71451034", async() => {
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.ValidationMessageTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper);
#nullable restore
#line 58 "C:\Revature\042020-dotnet-uta-RevRepo\kingsleyOnonachi_repo1\Proj1\Views\Customer\Create.cshtml"
__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.PassWord);
#line default
#line hidden
#nullable disable
__tagHelperExecutionContext.AddTagHelperAttribute("asp-validation-for", __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n </div>\r\n <div class=\"form-group\">\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("label", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "ea5bc8a4d87fa1b91583df3ae771e0095b6cc71452781", async() => {
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.LabelTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper);
#nullable restore
#line 61 "C:\Revature\042020-dotnet-uta-RevRepo\kingsleyOnonachi_repo1\Proj1\Views\Customer\Create.cshtml"
__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.RegDate);
#line default
#line hidden
#nullable disable
__tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "ea5bc8a4d87fa1b91583df3ae771e0095b6cc71454393", async() => {
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper);
#nullable restore
#line 62 "C:\Revature\042020-dotnet-uta-RevRepo\kingsleyOnonachi_repo1\Proj1\Views\Customer\Create.cshtml"
__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.RegDate);
#line default
#line hidden
#nullable disable
__tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("span", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "ea5bc8a4d87fa1b91583df3ae771e0095b6cc71455999", async() => {
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.ValidationMessageTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper);
#nullable restore
#line 63 "C:\Revature\042020-dotnet-uta-RevRepo\kingsleyOnonachi_repo1\Proj1\Views\Customer\Create.cshtml"
__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.RegDate);
#line default
#line hidden
#nullable disable
__tagHelperExecutionContext.AddTagHelperAttribute("asp-validation-for", __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n </div>\r\n <div class=\"form-group\">\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("label", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "ea5bc8a4d87fa1b91583df3ae771e0095b6cc71457741", async() => {
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.LabelTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper);
#nullable restore
#line 66 "C:\Revature\042020-dotnet-uta-RevRepo\kingsleyOnonachi_repo1\Proj1\Views\Customer\Create.cshtml"
__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.StoreID);
#line default
#line hidden
#nullable disable
__tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "ea5bc8a4d87fa1b91583df3ae771e0095b6cc71459349", async() => {
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper);
#nullable restore
#line 67 "C:\Revature\042020-dotnet-uta-RevRepo\kingsleyOnonachi_repo1\Proj1\Views\Customer\Create.cshtml"
__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.StoreID);
#line default
#line hidden
#nullable disable
__tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("span", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "ea5bc8a4d87fa1b91583df3ae771e0095b6cc71460951", async() => {
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.ValidationMessageTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper);
#nullable restore
#line 68 "C:\Revature\042020-dotnet-uta-RevRepo\kingsleyOnonachi_repo1\Proj1\Views\Customer\Create.cshtml"
__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.StoreID);
#line default
#line hidden
#nullable disable
__tagHelperExecutionContext.AddTagHelperAttribute("asp-validation-for", __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n </div>\r\n <div class=\"form-group\">\r\n <input type=\"submit\" value=\"Create\" class=\"btn btn-primary\" />\r\n </div>\r\n ");
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.FormTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Action = (string)__tagHelperAttribute_3.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_3);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n</div>\r\n</div>\r\n\r\n<div>\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "ea5bc8a4d87fa1b91583df3ae771e0095b6cc71463973", async() => {
WriteLiteral("Back to List");
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Action = (string)__tagHelperAttribute_4.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_4);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n</div>\r\n\r\n");
DefineSection("Scripts", async() => {
WriteLiteral("\r\n");
#nullable restore
#line 82 "C:\Revature\042020-dotnet-uta-RevRepo\kingsleyOnonachi_repo1\Proj1\Views\Customer\Create.cshtml"
await Html.RenderPartialAsync("_ValidationScriptsPartial");
#line default
#line hidden
#nullable disable
}
);
}
#pragma warning restore 1998
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<Proj1.Models.CustomerViewModel> Html { get; private set; }
}
}
#pragma warning restore 1591
| 74.034989 | 351 | 0.733806 |
[
"MIT"
] |
042020-dotnet-uta/kingsleyOnonachi_repo1
|
Proj1/obj/Debug/netcoreapp3.1/Razor/Views/Customer/Create.cshtml.g.cs
| 65,595 |
C#
|
using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("AWSSDK.CloudFront")]
#if BCL35
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - Amazon CloudFront. Amazon CloudFront is a content delivery web service. It integrates with other Amazon Web Services products to give developers and businesses an easy way to distribute content to end users with low latency, high data transfer speeds, and no minimum usage commitments.")]
#elif BCL45
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (4.5) - Amazon CloudFront. Amazon CloudFront is a content delivery web service. It integrates with other Amazon Web Services products to give developers and businesses an easy way to distribute content to end users with low latency, high data transfer speeds, and no minimum usage commitments.")]
#elif NETSTANDARD13
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 1.3) - Amazon CloudFront. Amazon CloudFront is a content delivery web service. It integrates with other Amazon Web Services products to give developers and businesses an easy way to distribute content to end users with low latency, high data transfer speeds, and no minimum usage commitments.")]
#elif NETSTANDARD20
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 2.0) - Amazon CloudFront. Amazon CloudFront is a content delivery web service. It integrates with other Amazon Web Services products to give developers and businesses an easy way to distribute content to end users with low latency, high data transfer speeds, and no minimum usage commitments.")]
#elif NETCOREAPP3_1
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (.NET Core 3.1) - Amazon CloudFront. Amazon CloudFront is a content delivery web service. It integrates with other Amazon Web Services products to give developers and businesses an easy way to distribute content to end users with low latency, high data transfer speeds, and no minimum usage commitments.")]
#else
#error Unknown platform constant - unable to set correct AssemblyDescription
#endif
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("Amazon Web Services SDK for .NET")]
[assembly: AssemblyCompany("Amazon.com, Inc")]
[assembly: AssemblyCopyright("Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("3.3.4.0")]
[assembly: AssemblyFileVersion("3.5.2.2")]
[assembly: System.CLSCompliant(true)]
#if BCL
[assembly: System.Security.AllowPartiallyTrustedCallers]
#endif
| 65.433962 | 377 | 0.784602 |
[
"Apache-2.0"
] |
orinem/aws-sdk-net
|
sdk/src/Services/CloudFront/Properties/AssemblyInfo.cs
| 3,468 |
C#
|
/**
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine;
using UnityEngine.Serialization;
using System.Collections;
namespace Fungus
{
[CommandInfo("iTween",
"Punch Rotation",
"Applies a jolt of force to a GameObject's rotation and wobbles it back to its initial rotation.")]
[AddComponentMenu("")]
[ExecuteInEditMode]
public class PunchRotation : iTweenCommand
{
[Tooltip("A rotation offset in space the GameObject will animate to")]
public Vector3Data _amount;
[Tooltip("Apply the transformation in either the world coordinate or local cordinate system")]
public Space space = Space.Self;
public override void DoTween()
{
Hashtable tweenParams = new Hashtable();
tweenParams.Add("name", _tweenName.Value);
tweenParams.Add("amount", _amount.Value);
tweenParams.Add("space", space);
tweenParams.Add("time", _duration.Value);
tweenParams.Add("easetype", easeType);
tweenParams.Add("looptype", loopType);
tweenParams.Add("oncomplete", "OniTweenComplete");
tweenParams.Add("oncompletetarget", gameObject);
tweenParams.Add("oncompleteparams", this);
iTween.PunchRotation(_targetObject.Value, tweenParams);
}
#region Backwards compatibility
[HideInInspector] [FormerlySerializedAs("amount")] public Vector3 amountOLD;
protected override void OnEnable()
{
base.OnEnable();
if (amountOLD != default(Vector3))
{
_amount.Value = amountOLD;
amountOLD = default(Vector3);
}
}
#endregion
}
}
| 34.103448 | 125 | 0.624874 |
[
"MIT"
] |
worthingtonjg/laugh-kingdom
|
Assets/Fungus/iTween/Scripts/Commands/PunchRotation.cs
| 1,978 |
C#
|
using System.Collections.Generic;
namespace ceenq.com.AssetImport.ViewModels
{
public class ImportViewModel {
public string Subdirectory { get; set; }
public bool OverwriteExisting { get; set; }
public string ImportUrl { get; set; }
}
}
| 21 | 51 | 0.67033 |
[
"BSD-3-Clause"
] |
bill-cooper/catc-cms
|
src/Orchard.Web/Modules/ceenq.com.AssetImport/ViewModels/ImportViewModel.cs
| 275 |
C#
|
/*
*************************************************************************
** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
** C#-SQLite is an independent reimplementation of the SQLite software library
**
** SQLITE_SOURCE_ID: 2010-08-23 18:52:01 42537b60566f288167f1b5864a5435986838e3a3
**
*************************************************************************
*/
namespace Community.CsharpSqlite
{
public partial class Globals
{
/* Automatically generated. Do not edit */
/* See the mkopcodec.awk script for details. */
#if !SQLITE_OMIT_EXPLAIN || !NDEBUG || VDBE_PROFILE || SQLITE_DEBUG
static string sqlite3OpcodeName( int i )
{
string[] azName = { "?",
/* 1 */ "Goto",
/* 2 */ "Gosub",
/* 3 */ "Return",
/* 4 */ "Yield",
/* 5 */ "HaltIfNull",
/* 6 */ "Halt",
/* 7 */ "Integer",
/* 8 */ "Int64",
/* 9 */ "String",
/* 10 */ "Null",
/* 11 */ "Blob",
/* 12 */ "Variable",
/* 13 */ "Move",
/* 14 */ "Copy",
/* 15 */ "SCopy",
/* 16 */ "ResultRow",
/* 17 */ "CollSeq",
/* 18 */ "Function",
/* 19 */ "Not",
/* 20 */ "AddImm",
/* 21 */ "MustBeInt",
/* 22 */ "RealAffinity",
/* 23 */ "Permutation",
/* 24 */ "Compare",
/* 25 */ "Jump",
/* 26 */ "If",
/* 27 */ "IfNot",
/* 28 */ "Column",
/* 29 */ "Affinity",
/* 30 */ "MakeRecord",
/* 31 */ "Count",
/* 32 */ "Savepoint",
/* 33 */ "AutoCommit",
/* 34 */ "Transaction",
/* 35 */ "ReadCookie",
/* 36 */ "SetCookie",
/* 37 */ "VerifyCookie",
/* 38 */ "OpenRead",
/* 39 */ "OpenWrite",
/* 40 */ "OpenAutoindex",
/* 41 */ "OpenEphemeral",
/* 42 */ "OpenPseudo",
/* 43 */ "Close",
/* 44 */ "SeekLt",
/* 45 */ "SeekLe",
/* 46 */ "SeekGe",
/* 47 */ "SeekGt",
/* 48 */ "Seek",
/* 49 */ "NotFound",
/* 50 */ "Found",
/* 51 */ "IsUnique",
/* 52 */ "NotExists",
/* 53 */ "Sequence",
/* 54 */ "NewRowid",
/* 55 */ "Insert",
/* 56 */ "InsertInt",
/* 57 */ "Delete",
/* 58 */ "ResetCount",
/* 59 */ "RowKey",
/* 60 */ "RowData",
/* 61 */ "Rowid",
/* 62 */ "NullRow",
/* 63 */ "Last",
/* 64 */ "Sort",
/* 65 */ "Rewind",
/* 66 */ "Prev",
/* 67 */ "Next",
/* 68 */ "Or",
/* 69 */ "And",
/* 70 */ "IdxInsert",
/* 71 */ "IdxDelete",
/* 72 */ "IdxRowid",
/* 73 */ "IsNull",
/* 74 */ "NotNull",
/* 75 */ "Ne",
/* 76 */ "Eq",
/* 77 */ "Gt",
/* 78 */ "Le",
/* 79 */ "Lt",
/* 80 */ "Ge",
/* 81 */ "IdxLT",
/* 82 */ "BitAnd",
/* 83 */ "BitOr",
/* 84 */ "ShiftLeft",
/* 85 */ "ShiftRight",
/* 86 */ "Add",
/* 87 */ "Subtract",
/* 88 */ "Multiply",
/* 89 */ "Divide",
/* 90 */ "Remainder",
/* 91 */ "Concat",
/* 92 */ "IdxGE",
/* 93 */ "BitNot",
/* 94 */ "String8",
/* 95 */ "Destroy",
/* 96 */ "Clear",
/* 97 */ "CreateIndex",
/* 98 */ "CreateTable",
/* 99 */ "ParseSchema",
/* 100 */ "LoadAnalysis",
/* 101 */ "DropTable",
/* 102 */ "DropIndex",
/* 103 */ "DropTrigger",
/* 104 */ "IntegrityCk",
/* 105 */ "RowSetAdd",
/* 106 */ "RowSetRead",
/* 107 */ "RowSetTest",
/* 108 */ "Program",
/* 109 */ "Param",
/* 110 */ "FkCounter",
/* 111 */ "FkIfZero",
/* 112 */ "MemMax",
/* 113 */ "IfPos",
/* 114 */ "IfNeg",
/* 115 */ "IfZero",
/* 116 */ "AggStep",
/* 117 */ "AggFinal",
/* 118 */ "Checkpoint",
/* 119 */ "JournalMode",
/* 120 */ "Vacuum",
/* 121 */ "IncrVacuum",
/* 122 */ "Expire",
/* 123 */ "TableLock",
/* 124 */ "VBegin",
/* 125 */ "VCreate",
/* 126 */ "VDestroy",
/* 127 */ "VOpen",
/* 128 */ "VFilter",
/* 129 */ "VColumn",
/* 130 */ "Real",
/* 131 */ "VNext",
/* 132 */ "VRename",
/* 133 */ "VUpdate",
/* 134 */ "Pagecount",
/* 135 */ "MaxPgcnt",
/* 136 */ "Trace",
/* 137 */ "Noop",
/* 138 */ "Explain",
/* 139 */ "NotUsed_139",
/* 140 */ "NotUsed_140",
/* 141 */ "ToText",
/* 142 */ "ToBlob",
/* 143 */ "ToNumeric",
/* 144 */ "ToInt",
/* 145 */ "ToReal",
};
return azName[i];
}
#endif
}
}
| 27.385965 | 83 | 0.372624 |
[
"MIT"
] |
ArsenShnurkov/csharp-sqlite
|
Community.CsharpSqlite/src/engine_vdbe/opcodes_c.cs
| 4,683 |
C#
|
namespace SharedTrip.Data
{
public class UserTrip
{
public string UserId { get; set; }
public virtual User User { get; set; }
public string TripId { get; set; }
public virtual Trip Trip { get; set; }
}
}
| 18 | 46 | 0.571429 |
[
"MIT"
] |
Avanguarde/csharp-web
|
2020-Sept-Season/SUS/Apps/SharedTrip/Data/UserTrip.cs
| 254 |
C#
|
using Github_Recent_Explorer_Test.Components;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Media;
namespace Github_Recent_Explorer_Test.Models
{
class RepositoriesViewModel : INotifyPropertyChanged
{
private Label _languageFilter;
private string _dateFilter;
private string _customFilter;
private bool _isDropSideHidden;
public bool IsLoading
{
get
{
return this.repositoriesModel.IsRequestInProcess;
}
}
public bool IsDropSideHidden
{
get
{
return _isDropSideHidden;
}
set
{
_isDropSideHidden = value;
RaisePropertyChanged("IsDropSideHidden");
}
}
public string DateFilter
{
get
{
return _dateFilter;
}
set
{
_dateFilter = value;
repositoriesModel.DateFilter = this._dateFilter;
}
}
public string CustomFilter
{
get
{
return _customFilter;
}
set
{
_customFilter = value;
repositoriesModel.CustomFilter = this._customFilter;
}
}
public Label LanguageFilter
{
get
{
return _languageFilter;
}
set
{
_languageFilter = value;
repositoriesModel.LanguageFilter = (this._languageFilter?.Content as string);
}
}
public GitRepositoryControl[] Repositories
{
get
{
return this.repositoriesModel.Repositories
.Select((each) =>
new GitRepositoryControl()
{
Url = each.url, Title = each.title, Description = each.description,
Stars = each.stars, Language = each.language, License = each.license,
LastUpdate = each.representupdatedate
})
.ToArray();
}
}
public string[] AvailableDateFilters
{
get => this.repositoriesModel.AvailableDateFilters;
}
public string[] AvailableCustomFilters
{
get => this.repositoriesModel.AvailableCustomFilters;
}
public Label[] AvailableLanguageFilters
{
get => this.repositoriesModel.AvailableLanguageFilters
.Select((each) => new Label() { Content = each, Foreground = Brushes.White }).ToArray();
}
private RepositoriesModel repositoriesModel;
public event PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
private void ModelPropertyChange(object sender, PropertyChangedEventArgs e)
{
RaisePropertyChanged(e.PropertyName);
}
public RepositoriesViewModel()
{
this.IsDropSideHidden = false;
this.repositoriesModel = new RepositoriesModel();
this.repositoriesModel.PropertyChanged += ModelPropertyChange;
}
}
}
| 29.112 | 103 | 0.535312 |
[
"MIT"
] |
Embarcadero/ComparisonResearch
|
github-recent-explorer/wpf/Refrence/Github Recent Explorer Test/Models/RepositoriesViewModel.cs
| 3,641 |
C#
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GoalHolderBlue : MonoBehaviour
{
public AudioSource crowd_audio;
public static int mavitakimgol;
private void OnTriggerEnter(Collider other)
{
if (other.tag == "Ball")
{
BallPosition.isGoal = true;
mavitakimgol++;
crowd_audio.Play();
}
}
}
| 19.454545 | 47 | 0.609813 |
[
"Apache-2.0"
] |
MarsalekDesmotes/-FpsSoccerGame
|
ChampionsSoccer/Assets/MainMenu/GoalHolderBlue.cs
| 428 |
C#
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Craft.Net;
namespace SMProxy
{
public class Log
{
public StreamWriter Stream { get; set; }
private MemoryStream MemoryStream { get; set; } // Used for getting raw packet data
private MinecraftStream MinecraftStream { get; set; } // Used for getting raw packet data
private ProxySettings Settings { get; set; }
public Log(StreamWriter stream, ProxySettings settings)
{
Stream = stream;
MemoryStream = new MemoryStream();
MinecraftStream = new MinecraftStream(MemoryStream);
Settings = settings;
}
public virtual void LogPacket(IPacket packet, bool clientToServer)
{
if (clientToServer && !Settings.LogClient) return;
if (!clientToServer && !Settings.LogServer) return;
if (!Settings.PacketFilter.Contains(packet.Id)) return;
var type = packet.GetType();
var fields = type.GetFields();
// Log time, direction, name
Stream.Write(DateTime.Now.ToString("{hh:mm:ss.fff} "));
if (clientToServer)
Stream.Write("[CLIENT->SERVER] ");
else
Stream.Write("[SERVER->CLIENT] ");
Stream.Write(FormatPacketName(type.Name));
Stream.Write(" (0x"); Stream.Write(packet.Id.ToString("X2")); Stream.Write(")");
Stream.WriteLine();
// Log raw data
MemoryStream.Seek(0, SeekOrigin.Begin);
MemoryStream.SetLength(0);
packet.WritePacket(MinecraftStream);
Stream.Write(DumpArrayPretty(MemoryStream.GetBuffer().Take((int)MemoryStream.Length).ToArray()));
// Log fields
foreach (var field in fields)
{
var name = field.Name;
name = AddSpaces(name);
var fValue = field.GetValue(packet);
if (!(fValue is Array))
Stream.Write(string.Format(" {0} ({1})", name, field.FieldType.Name));
else
{
var array = fValue as Array;
Stream.Write(string.Format(" {0} ({1}[{2}])", name,
array.GetType().GetElementType().Name, array.Length));
}
if (fValue is byte[])
Stream.Write(": " + DumpArray(fValue as byte[]) + "\n");
else if (fValue is Array)
{
Stream.Write(": ");
var array = fValue as Array;
foreach (var item in array)
Stream.Write(string.Format("{0}, ", item.ToString()));
Stream.WriteLine();
}
else
Stream.Write(": " + fValue + "\n");
}
Stream.WriteLine();
Stream.Flush();
}
private string FormatPacketName(string name)
{
if (name.EndsWith("Packet"))
name = name.Remove(name.Length - "Packet".Length);
// TODO: Consider adding spaces before capital letters
return name;
}
public static string DumpArray(byte[] array)
{
if (array.Length == 0)
return "[]";
var sb = new StringBuilder((array.Length * 2) + 2);
foreach (byte b in array)
sb.AppendFormat("{0} ", b.ToString("X2"));
return "[" + sb.ToString().Remove(sb.Length - 1) + "]";
}
public static string DumpArrayPretty(byte[] array)
{
if (array.Length == 0)
return "[Empty arry]";
int length = 5 * array.Length + (4 * (array.Length / 16)) + 2; // rough estimate of final length
var sb = new StringBuilder(length);
sb.AppendLine("[");
for (int i = 0; i < array.Length; i += 16)
{
sb.Append(" ");
// Hex dump
int hexCount = 16;
for (int j = i; j < array.Length && j < i + 16; j++, hexCount--)
sb.AppendFormat("{0} ", array[j].ToString("X2"));
sb.Append(" ");
for (; hexCount > 0; hexCount--)
sb.Append(" ");
for (int j = i; j < array.Length && j < i + 16; j++)
{
char value = Encoding.ASCII.GetString(new byte[] { array[j] })[0];
if (char.IsLetterOrDigit(value))
sb.AppendFormat("{0} ", value);
else
sb.Append(". ");
}
sb.AppendLine();
}
sb.AppendLine("]");
string result = " " + sb.ToString().Replace("\n", "\n ");
return result.Remove(result.Length - 2);
}
public static string AddSpaces(string value)
{
string newValue = "";
foreach (char c in value)
{
if (char.IsLower(c))
newValue += c;
else
newValue += " " + c;
}
return newValue.Substring(1);
}
public virtual void Write(string p)
{
Stream.Write(DateTime.Now.ToString("{hh:mm:ss.fff} "));
Stream.WriteLine(p);
}
}
}
| 36.688742 | 109 | 0.47509 |
[
"MIT"
] |
libraryaddict/SMProxy
|
SMProxy/Log.cs
| 5,542 |
C#
|
using SpiceSharpParser.ModelReaders.Netlist.Spice.Context;
using SpiceSharpParser.ModelReaders.Netlist.Spice.Exceptions;
using SpiceSharpParser.ModelReaders.Netlist.Spice.Mappings;
using SpiceSharpParser.ModelReaders.Netlist.Spice.Readers;
using SpiceSharpParser.ModelReaders.Netlist.Spice.Readers.Controls;
using SpiceSharpParser.ModelReaders.Netlist.Spice.Readers.EntityGenerators;
using SpiceSharpParser.Models.Netlist.Spice.Objects;
using System;
using System.Collections.Generic;
namespace SpiceSharpParser.ModelReaders.Netlist.Spice
{
public class SpiceStatementsReader : ISpiceStatementsReader
{
public SpiceStatementsReader(
IMapper<BaseControl> controlMapper,
IMapper<IModelGenerator> modelMapper,
IMapper<IComponentGenerator> entityMapper)
{
var modelReader = new ModelReader(modelMapper, new StochasticModelsGenerator());
var componentReader = new ComponentReader(entityMapper);
var controlReader = new ControlReader(controlMapper);
var subcircuitDefinitionReader = new SubcircuitDefinitionReader();
var commentReader = new CommentReader();
Readers[typeof(Component)] = componentReader;
Readers[typeof(Model)] = modelReader;
Readers[typeof(Control)] = controlReader;
Readers[typeof(SubCircuit)] = subcircuitDefinitionReader;
Readers[typeof(CommentLine)] = commentReader;
}
/// <summary>
/// Gets the readers.
/// </summary>
protected Dictionary<Type, IStatementReader> Readers { get; } = new Dictionary<Type, IStatementReader>();
/// <summary>
/// Reads a statement.
/// </summary>
/// <param name="statement">A statement.</param>
/// <param name="circuitContext">A reading context.</param>
public void Read(Statement statement, ICircuitContext circuitContext)
{
if (statement == null)
{
throw new ArgumentNullException(nameof(statement));
}
if (circuitContext == null)
{
throw new ArgumentNullException(nameof(circuitContext));
}
if (Readers.ContainsKey(statement.GetType()))
{
Readers[statement.GetType()].Read(statement, circuitContext);
}
else
{
throw new ReadingException($"There is no reader for the statement of type: {statement.GetType()}", statement.LineInfo);
}
}
}
}
| 39.861538 | 135 | 0.648398 |
[
"MIT"
] |
fossabot/SpiceSharpParser
|
src/SpiceSharpParser/ModelReaders/Netlist/Spice/SpiceStatementsReader.cs
| 2,593 |
C#
|
using Chalmers.ILL.Models;
using Newtonsoft.Json;
using System;
using System.Data.Entity;
using Umbraco.Core.Logging;
using System.Linq;
using Chalmers.ILL.OrderItems;
using System.Collections.Generic;
using System.Data.Entity.Validation;
namespace Chalmers.ILL.Database
{
public class OrderItemsDbContext : DbContext
{
private static readonly string _connectionStringName = "chillinOrderItemsDb";
private IOrderItemSearcher _orderItemSearcher;
public DbSet<OrderItemModel> OrderItems { get; set; }
public OrderItemsDbContext() : base(_connectionStringName) { }
public OrderItemsDbContext(IOrderItemSearcher orderItemSearcher) : base(_connectionStringName)
{
_orderItemSearcher = orderItemSearcher;
}
public override int SaveChanges()
{
var orderItemChanges = from e in ChangeTracker.Entries<OrderItemModel>()
where e.State != EntityState.Unchanged
select e;
var addedItems = new List<OrderItemModel>();
var modifiedItems = new List<OrderItemModel>();
var removedItems = new List<OrderItemModel>();
foreach (var change in orderItemChanges)
{
if (change.State == EntityState.Added)
{
if (change.Entity.CreateDate == DateTime.MinValue)
{
change.Entity.CreateDate = DateTime.Now;
}
if (change.Entity.UpdateDate == DateTime.MinValue)
{
change.Entity.UpdateDate = DateTime.Now;
}
addedItems.Add(change.Entity);
}
else if (change.State == EntityState.Deleted)
{
removedItems.Add(change.Entity);
}
else if (change.State == EntityState.Modified)
{
change.Entity.UpdateDate = DateTime.Now;
modifiedItems.Add(change.Entity);
}
}
int res = 0;
try
{
res = base.SaveChanges();
foreach (var item in addedItems)
{
_orderItemSearcher.Added(item);
}
foreach (var item in modifiedItems)
{
_orderItemSearcher.Modified(item);
}
foreach (var item in removedItems)
{
_orderItemSearcher.Deleted(item);
}
}
catch (DbEntityValidationException e)
{
LogHelper.Error<OrderItemsDbContext>("An entity validation exception occured during saving.", e);
throw e;
}
catch (Exception e)
{
LogHelper.Error<OrderItemsDbContext>("An error occured during a save to database.", e);
throw e;
}
return res;
}
}
}
| 32.57732 | 113 | 0.514557 |
[
"MIT"
] |
ChalmersLibrary/Chillin
|
Chalmers.ILL/Database/OrderItemsDbContext.cs
| 3,162 |
C#
|
// --------------------------------------------------------------------------------------------
// Version: MPL 1.1/GPL 2.0/LGPL 2.1
//
// The contents of this file are subject to the Mozilla Public License Version
// 1.1 (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.mozilla.org/MPL/
//
// Software distributed under the License is distributed on an "AS IS" basis,
// WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
// for the specific language governing rights and limitations under the
// License.
//
// <remarks>
// Generated by IDLImporter from file mozIStorageConnection.idl
//
// You should use these interfaces when you access the COM objects defined in the mentioned
// IDL/IDH file.
// </remarks>
// --------------------------------------------------------------------------------------------
namespace Gecko
{
using System;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using System.Runtime.CompilerServices;
/// <summary>
/// mozIStorageConnection represents a database connection attached to
/// a specific file or to the in-memory data storage. It is the
/// primary interface for interacting with a database, including
/// creating prepared statements, executing SQL, and examining database
/// errors.
///
/// @note From the main thread, you should rather use mozIStorageAsyncConnection.
///
/// @threadsafe
/// </summary>
[ComImport()]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("4aa2ac47-8d24-4004-9b31-ec0bd85f0cc3")]
internal interface mozIStorageConnection : mozIStorageAsyncConnection
{
/// <summary>
/// Close this database connection, allowing all pending statements
/// to complete first.
///
/// @param aCallback [optional]
/// A callback that will be notified when the close is completed,
/// with the following arguments:
/// - status: the status of the call
/// - value: |null|
///
/// @throws NS_ERROR_NOT_SAME_THREAD
/// If is called on a thread other than the one that opened it.
/// </summary>
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
new void AsyncClose(mozIStorageCompletionCallback aCallback);
/// <summary>
/// Clone a database and make the clone read only if needed.
///
/// @param aReadOnly
/// If true, the returned database should be put into read-only mode.
///
/// @param aCallback
/// A callback that will be notified when the operation is complete,
/// with the following arguments:
/// - status: the status of the operation
/// - value: in case of success, an intance of
/// mozIStorageAsyncConnection cloned from this one.
///
/// @throws NS_ERROR_NOT_SAME_THREAD
/// If is called on a thread other than the one that opened it.
/// @throws NS_ERROR_UNEXPECTED
/// If this connection is a memory database.
///
/// @note If your connection is already read-only, you will get a read-only
/// clone.
/// @note Due to a bug in SQLite, if you use the shared cache
/// (see mozIStorageService), you end up with the same privileges as the
/// first connection opened regardless of what is specified in aReadOnly.
/// @note The following pragmas are copied over to a read-only clone:
/// - cache_size
/// - temp_store
/// The following pragmas are copied over to a writeable clone:
/// - cache_size
/// - temp_store
/// - foreign_keys
/// - journal_size_limit
/// - synchronous
/// - wal_autocheckpoint
/// </summary>
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
new void AsyncClone([MarshalAs(UnmanagedType.U1)] bool aReadOnly, mozIStorageCompletionCallback aCallback);
/// <summary>
/// The current database nsIFile. Null if the database
/// connection refers to an in-memory database.
/// </summary>
[return: MarshalAs(UnmanagedType.Interface)]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
new nsIFile GetDatabaseFileAttribute();
/// <summary>
/// Create an asynchronous statement for the given SQL. An
/// asynchronous statement can only be used to dispatch asynchronous
/// requests to the asynchronous execution thread and cannot be used
/// to take any synchronous actions on the database.
///
/// The expression may use ? to indicate sequential numbered arguments,
/// ?1, ?2 etc. to indicate specific numbered arguments or :name and
/// $var to indicate named arguments.
///
/// @param aSQLStatement
/// The SQL statement to execute.
/// @return a new mozIStorageAsyncStatement
/// @note The statement is created lazily on first execution.
/// </summary>
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
new mozIStorageAsyncStatement CreateAsyncStatement([MarshalAs(UnmanagedType.LPStruct)] nsAUTF8StringBase aSQLStatement);
/// <summary>
/// Execute an array of statements created with this connection using
/// any currently bound parameters. When the array contains multiple
/// statements, the execution is wrapped in a single
/// transaction. These statements can be reused immediately, and
/// reset does not need to be called.
///
/// @param aStatements
/// The array of statements to execute asynchronously, in the order they
/// are given in the array.
/// @param aNumStatements
/// The number of statements in aStatements.
/// @param aCallback [optional]
/// The callback object that will be notified of progress, errors, and
/// completion.
/// @return an object that can be used to cancel the statements execution.
///
/// @note If you have any custom defined functions, they must be
/// re-entrant since they can be called on multiple threads.
/// </summary>
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
new mozIStoragePendingStatement ExecuteAsync([MarshalAs(UnmanagedType.LPArray, SizeParamIndex=1)] mozIStorageBaseStatement[] aStatements, uint aNumStatements, mozIStorageStatementCallback aCallback);
/// <summary>
/// Execute asynchronously an SQL expression, expecting no arguments.
///
/// @param aSQLStatement
/// The SQL statement to execute
/// @param aCallback [optional]
/// The callback object that will be notified of progress, errors, and
/// completion.
/// @return an object that can be used to cancel the statement execution.
/// </summary>
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
new mozIStoragePendingStatement ExecuteSimpleSQLAsync([MarshalAs(UnmanagedType.LPStruct)] nsAUTF8StringBase aSQLStatement, mozIStorageStatementCallback aCallback);
/// <summary>
/// Create a new SQL function. If you use your connection on multiple threads,
/// your function needs to be threadsafe, or it should only be called on one
/// thread.
///
/// @param aFunctionName
/// The name of function to create, as seen in SQL.
/// @param aNumArguments
/// The number of arguments the function takes. Pass -1 for
/// variable-argument functions.
/// @param aFunction
/// The instance of mozIStorageFunction, which implements the function
/// in question.
/// </summary>
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
new void CreateFunction([MarshalAs(UnmanagedType.LPStruct)] nsAUTF8StringBase aFunctionName, int aNumArguments, mozIStorageFunction aFunction);
/// <summary>
/// Create a new SQL aggregate function. If you use your connection on
/// multiple threads, your function needs to be threadsafe, or it should only
/// be called on one thread.
///
/// @param aFunctionName
/// The name of aggregate function to create, as seen in SQL.
/// @param aNumArguments
/// The number of arguments the function takes. Pass -1 for
/// variable-argument functions.
/// @param aFunction
/// The instance of mozIStorageAggreagteFunction, which implements the
/// function in question.
/// </summary>
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
new void CreateAggregateFunction([MarshalAs(UnmanagedType.LPStruct)] nsAUTF8StringBase aFunctionName, int aNumArguments, mozIStorageAggregateFunction aFunction);
/// <summary>
/// Delete custom SQL function (simple or aggregate one).
///
/// @param aFunctionName
/// The name of function to remove.
/// </summary>
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
new void RemoveFunction([MarshalAs(UnmanagedType.LPStruct)] nsAUTF8StringBase aFunctionName);
/// <summary>
/// Sets a progress handler. Only one handler can be registered at a time.
/// If you need more than one, you need to chain them yourself. This progress
/// handler should be threadsafe if you use this connection object on more than
/// one thread.
///
/// @param aGranularity
/// The number of SQL virtual machine steps between progress handler
/// callbacks.
/// @param aHandler
/// The instance of mozIStorageProgressHandler.
/// @return previous registered handler.
/// </summary>
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
new mozIStorageProgressHandler SetProgressHandler(int aGranularity, mozIStorageProgressHandler aHandler);
/// <summary>
/// Remove a progress handler.
///
/// @return previous registered handler.
/// </summary>
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
new mozIStorageProgressHandler RemoveProgressHandler();
/// <summary>
/// Closes a database connection. Callers must finalize all statements created
/// for this connection prior to calling this method. It is illegal to use
/// call this method if any asynchronous statements have been executed on this
/// connection.
///
/// @throws NS_ERROR_UNEXPECTED
/// If any statement has been executed asynchronously on this object.
/// @throws NS_ERROR_UNEXPECTED
/// If is called on a thread other than the one that opened it.
/// </summary>
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void Close();
/// <summary>
/// Clones a database connection and makes the clone read only if needed.
///
/// @param aReadOnly
/// If true, the returned database should be put into read-only mode.
/// Defaults to false.
/// @return the cloned database connection.
///
/// @throws NS_ERROR_UNEXPECTED
/// If this connection is a memory database.
/// @note If your connection is already read-only, you will get a read-only
/// clone.
/// @note Due to a bug in SQLite, if you use the shared cache (openDatabase),
/// you end up with the same privileges as the first connection opened
/// regardless of what is specified in aReadOnly.
/// @note The following pragmas are copied over to a read-only clone:
/// - cache_size
/// - temp_store
/// The following pragmas are copied over to a writeable clone:
/// - cache_size
/// - temp_store
/// - foreign_keys
/// - journal_size_limit
/// - synchronous
/// - wal_autocheckpoint
///
/// </summary>
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
mozIStorageConnection Clone([MarshalAs(UnmanagedType.U1)] bool aReadOnly);
/// <summary>
/// The default size for SQLite database pages used by mozStorage for new
/// databases.
/// </summary>
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
int GetDefaultPageSizeAttribute();
/// <summary>
/// Indicates if the connection is open and ready to use. This will be false
/// if the connection failed to open, or it has been closed.
/// </summary>
[return: MarshalAs(UnmanagedType.U1)]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
bool GetConnectionReadyAttribute();
/// <summary>
/// lastInsertRowID returns the row ID from the last INSERT
/// operation.
/// </summary>
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
long GetLastInsertRowIDAttribute();
/// <summary>
/// affectedRows returns the number of database rows that were changed or
/// inserted or deleted by last operation.
/// </summary>
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
int GetAffectedRowsAttribute();
/// <summary>
/// The last error SQLite error code.
/// </summary>
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
int GetLastErrorAttribute();
/// <summary>
/// The last SQLite error as a string (in english, straight from the
/// sqlite library).
/// </summary>
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void GetLastErrorStringAttribute([MarshalAs(UnmanagedType.LPStruct)] nsAUTF8StringBase aLastErrorString);
/// <summary>
/// The schema version of the database. This should not be used until the
/// database is ready. The schema will be reported as zero if it is not set.
/// </summary>
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
int GetSchemaVersionAttribute();
/// <summary>
/// The schema version of the database. This should not be used until the
/// database is ready. The schema will be reported as zero if it is not set.
/// </summary>
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void SetSchemaVersionAttribute(int aSchemaVersion);
/// <summary>
/// Create a mozIStorageStatement for the given SQL expression. The
/// expression may use ? to indicate sequential numbered arguments,
/// ?1, ?2 etc. to indicate specific numbered arguments or :name and
/// $var to indicate named arguments.
///
/// @param aSQLStatement
/// The SQL statement to execute.
/// @return a new mozIStorageStatement
/// </summary>
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
mozIStorageStatement CreateStatement([MarshalAs(UnmanagedType.LPStruct)] nsAUTF8StringBase aSQLStatement);
/// <summary>
/// Execute a SQL expression, expecting no arguments.
///
/// @param aSQLStatement The SQL statement to execute
/// </summary>
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void ExecuteSimpleSQL([MarshalAs(UnmanagedType.LPStruct)] nsAUTF8StringBase aSQLStatement);
/// <summary>
/// Check if the given table exists.
///
/// @param aTableName
/// The table to check
/// @return TRUE if table exists, FALSE otherwise.
/// </summary>
[return: MarshalAs(UnmanagedType.U1)]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
bool TableExists([MarshalAs(UnmanagedType.LPStruct)] nsAUTF8StringBase aTableName);
/// <summary>
/// Check if the given index exists.
///
/// @param aIndexName The index to check
/// @return TRUE if the index exists, FALSE otherwise.
/// </summary>
[return: MarshalAs(UnmanagedType.U1)]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
bool IndexExists([MarshalAs(UnmanagedType.LPStruct)] nsAUTF8StringBase aIndexName);
/// <summary>
/// Returns true if a transaction is active on this connection.
/// </summary>
[return: MarshalAs(UnmanagedType.U1)]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
bool GetTransactionInProgressAttribute();
/// <summary>
/// Begin a new transaction. sqlite default transactions are deferred.
/// If a transaction is active, throws an error.
/// </summary>
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void BeginTransaction();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void BeginTransactionAs(int transactionType);
/// <summary>
/// Commits the current transaction. If no transaction is active,
/// @throws NS_ERROR_UNEXPECTED.
/// @throws NS_ERROR_NOT_INITIALIZED.
/// </summary>
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void CommitTransaction();
/// <summary>
/// Rolls back the current transaction. If no transaction is active,
/// @throws NS_ERROR_UNEXPECTED.
/// @throws NS_ERROR_NOT_INITIALIZED.
/// </summary>
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void RollbackTransaction();
/// <summary>
/// Create the table with the given name and schema.
///
/// If the table already exists, NS_ERROR_FAILURE is thrown.
/// (XXX at some point in the future it will check if the schema is
/// the same as what is specified, but that doesn't happen currently.)
///
/// @param aTableName
/// The table name to be created, consisting of [A-Za-z0-9_], and
/// beginning with a letter.
/// @param aTableSchema
/// The schema of the table; what would normally go between the parens
/// in a CREATE TABLE statement: e.g., "foo INTEGER, bar STRING".
///
/// @throws NS_ERROR_FAILURE
/// If the table already exists or could not be created for any other
/// reason.
/// </summary>
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void CreateTable([MarshalAs(UnmanagedType.LPStr)] string aTableName, [MarshalAs(UnmanagedType.LPStr)] string aTableSchema);
/// <summary>
/// Controls SQLITE_FCNTL_CHUNK_SIZE setting in sqlite. This helps avoid fragmentation
/// by growing/shrinking the database file in SQLITE_FCNTL_CHUNK_SIZE increments. To
/// conserve memory on systems short on storage space, this function will have no effect
/// on mobile devices or if less than 500MiB of space is left available.
///
/// @param aIncrement
/// The database file will grow in multiples of chunkSize.
/// @param aDatabaseName
/// Sqlite database name. "" means pass NULL for zDbName to sqlite3_file_control.
/// See http://sqlite.org/c3ref/file_control.html for more details.
/// @throws NS_ERROR_FILE_TOO_BIG
/// If the system is short on storage space.
/// </summary>
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void SetGrowthIncrement(int aIncrement, [MarshalAs(UnmanagedType.LPStruct)] nsAUTF8StringBase aDatabaseName);
/// <summary>
/// Enable a predefined virtual table implementation.
///
/// @param aModuleName
/// The module to enable. Only "filesystem" is currently supported.
///
/// @throws NS_ERROR_FAILURE
/// For unknown module names.
/// </summary>
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
void EnableModule([MarshalAs(UnmanagedType.LPStruct)] nsACStringBase aModuleName);
}
/// <summary>mozIStorageConnectionConsts </summary>
internal class mozIStorageConnectionConsts
{
// <summary>
// Begins a new transaction with the given type.
// </summary>
public const long TRANSACTION_DEFERRED = 0;
//
public const long TRANSACTION_IMMEDIATE = 1;
//
public const long TRANSACTION_EXCLUSIVE = 2;
}
}
| 44.814894 | 201 | 0.66472 |
[
"MIT"
] |
haga-rak/Freezer
|
Freezer/GeckoFX/__Core/Generated/mozIStorageConnection.cs
| 21,063 |
C#
|
namespace ns0
{
using BoomBang.Communication;
using BoomBang.Communication.Incoming;
using BoomBang.Config;
using BoomBang.Game.Sessions;
using System;
using System.Security.Cryptography;
internal class Class1
{
public static void smethod_0()
{
DataRouter.RegisterHandler(FlagcodesIn.USER, ItemcodesIn.LANDING_LOGIN, new ProcessRequestCallback(Class1.smethod_1), true);
}
private static void smethod_1(Session session_0, ClientMessage clientMessage_0)
{
string username = clientMessage_0.ReadString();
string s = clientMessage_0.ReadString();
string password = string.Empty;
password = Convert.ToBase64String(SHA1.Create().ComputeHash(Constants.DefaultEncoding.GetBytes(s)));
session_0.TryAuthenticate(username, password, session_0.RemoteAddress, false);
}
}
}
| 32.892857 | 136 | 0.679696 |
[
"MIT"
] |
DaLoE99/Servidores-DaLoE
|
BB Server/BoomBang/ns0/Class1.cs
| 923 |
C#
|
namespace SFA.Apprenticeships.Infrastructure.Communication.Email
{
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.Mail;
using Application.Interfaces.Communications;
using Configuration;
using Domain.Entities.Exceptions;
using EmailFromResolvers;
using Exceptions;
using SendGrid;
using SFA.Apprenticeships.Application.Interfaces;
using ErrorCodes = Application.Interfaces.Communications.ErrorCodes;
public class SendGridEmailDispatcher : IEmailDispatcher
{
private readonly ILogService _logger;
private readonly string _userName;
private readonly string _password;
private readonly EmailTemplate[] _templates;
private readonly IEnumerable<KeyValuePair<MessageTypes, EmailMessageFormatter>> _messageFormatters;
private readonly IEnumerable<IEmailFromResolver> _emailFromResolvers;
public SendGridEmailDispatcher(
IConfigurationService configuration,
IEnumerable<KeyValuePair<MessageTypes, EmailMessageFormatter>> messageFormatters,
ILogService logger,
IEnumerable<IEmailFromResolver> emailFromResolvers)
{
_messageFormatters = messageFormatters;
_logger = logger;
_emailFromResolvers = emailFromResolvers;
var config = configuration.Get<EmailConfiguration>();
_userName = config.Username;
_password = config.Password;
_templates = config.Templates.ToArray();
}
public void SendEmail(EmailRequest request)
{
_logger.Debug("Dispatching email To:{0}, Template:{1}", request.ToEmail, request.MessageType);
var message = ComposeMessage(request);
DispatchMessage(request, message);
}
private SendGridMessage ComposeMessage(EmailRequest request)
{
var message = CreateMessage(request);
AttachTemplate(request, message);
PopulateTemplate(request, message);
return message;
}
private static SendGridMessage CreateMessage(EmailRequest request)
{
const string emptyHtml = "<span></span>";
const string emptyText = "";
const string subject = " ";
// NOTE: https://github.com/sendgrid/sendgrid-csharp.
var message = new SendGridMessage
{
Subject = subject,
To = new[]
{
//TODO: Support multiple to addresses
new MailAddress(request.ToEmail)
},
Text = emptyText,
Html = emptyHtml
};
return message;
}
private void PopulateTemplate(EmailRequest request, SendGridMessage message)
{
// NOTE: https://sendgrid.com/docs/API_Reference/SMTP_API/substitution_tags.html.
if (_messageFormatters.All(mf => mf.Key != request.MessageType))
{
var errorMessage = string.Format("Populate template: No message formatter exists for MessageType name: {0}", request.MessageType);
_logger.Error(errorMessage);
throw new ConfigurationErrorsException(errorMessage);
}
_messageFormatters.First(mf => mf.Key == request.MessageType).Value.PopulateMessage(request, message);
}
private void AttachTemplate(EmailRequest request, SendGridMessage message)
{
var templateName = GetTemplateName(request.MessageType);
var template = GetTemplateConfiguration(templateName);
var fromEmail = _emailFromResolvers.First(er => er.CanResolve(request.MessageType)).Resolve(request, template.FromEmail);
message.From = new MailAddress(fromEmail);
message.EnableTemplateEngine(template.Id.ToString());
}
private string GetTemplateName(Enum messageType)
{
var enumType = messageType.GetType();
var templateName = string.Format("{0}.{1}", enumType.Name, Enum.GetName(enumType, messageType));
_logger.Debug("Determined email template: EnumType={0} Name={1} TemplateName={2} MessageType={3}", enumType,
enumType.Name, templateName, messageType);
return templateName;
}
private EmailTemplate GetTemplateConfiguration(string templateName)
{
var template = _templates.FirstOrDefault(each => each.Name == templateName);
if (template != null)
{
return template;
}
var errorMessage = string.Format("GetTemplateConfiguration : Invalid email template name: {0}", templateName);
_logger.Error(errorMessage);
throw new ConfigurationErrorsException(errorMessage);
}
private void DispatchMessage(EmailRequest request, SendGridMessage message)
{
var logMessage = GetEmailLogMessage(request, message);
try
{
_logger.Debug("Dispatching email: {0}", logMessage);
var credentials = new NetworkCredential(_userName, _password);
var web = new Web(credentials);
web.Deliver(message);
_logger.Info("Dispatched email: {0}", logMessage);
}
catch (InvalidApiRequestException e)
{
var errorMessage = string.Format("Failed to dispatch email: {0}. Errors: {1}", logMessage, string.Join(", ", e.Errors));
_logger.Error(errorMessage, e, logMessage);
throw new CustomException(errorMessage, e, ErrorCodes.EmailApiError);
}
catch (ArgumentNullException e)
{
var errorMessage = string.Format("Failed to dispatch email due to formatting errors: {0}", logMessage);
_logger.Error(errorMessage, e, logMessage);
throw new CustomException(errorMessage, e, ErrorCodes.EmailFormatError);
}
catch (Exception e)
{
var errorMessage = string.Format("Failed to dispatch email: {0}", logMessage);
_logger.Error(errorMessage, e, logMessage);
throw new CustomException(errorMessage, e, ErrorCodes.EmailError);
}
}
private static string GetEmailLogMessage(EmailRequest request, SendGridMessage message)
{
var subject = string.IsNullOrWhiteSpace(message.Subject) ? "<from template>" : message.Subject;
var recipients = string.Join(", ", message.To.Select(address => address.Address));
var tokens = string.Join(", ", request.Tokens.Select(token => string.Format("'{0}'='{1}'", token.Key, token.Value)));
return string.Format("type='{0}', subject='{1}', from='{2}', to='{3}', tokens='{4}'",
request.MessageType, subject, message.From.Address, recipients, tokens);
}
}
}
| 38.691892 | 146 | 0.615395 |
[
"MIT"
] |
BugsUK/FindApprenticeship
|
src/SFA.Apprenticeships.Infrastructure.Communication/Email/SendGridEmailDispatcher.cs
| 7,160 |
C#
|
using System;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using FluentValidation;
using LineNotifySample.Models;
using LineNotifySDK;
using LineNotifySDK.Model;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace LineNotifySample.Controllers
{
public class HomeController : Controller
{
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly ILineNotifyServices _lineNotifyServices;
private const string TokenKey = "token";
public HomeController(
IHttpContextAccessor httpContextAccessor,
ILineNotifyServices lineNotifyServices)
{
_httpContextAccessor = httpContextAccessor;
_lineNotifyServices = lineNotifyServices;
}
public IActionResult Index()
{
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
public IActionResult LineAuthorize()
{
return Redirect(_lineNotifyServices.GetAuthorizeUri().AbsoluteUri);
}
public async Task<IActionResult> BindCallback(string code, string state)
{
if (code == null)
{
ViewBag.Message = "Binding Failed";
return View("Index");
}
var token = await _lineNotifyServices.GetTokenAsync(code).ConfigureAwait(false);
_httpContextAccessor.HttpContext?.Session.SetString(TokenKey, token);
ViewBag.Token = token;
if (!string.IsNullOrWhiteSpace(ViewBag.Token))
{
ViewBag.Message = "Binding Success";
}
return View("Index");
}
public async Task<IActionResult> LineRevoke()
{
var token = _httpContextAccessor.HttpContext?.Session.GetString(TokenKey);
if (!string.IsNullOrWhiteSpace(token))
{
await _lineNotifyServices.RevokeAsync(token).ConfigureAwait(false);
_httpContextAccessor.HttpContext.Session.SetString(TokenKey, string.Empty);
ViewBag.Message = "Unbind Success";
}
return View("Index");
}
public async Task<IActionResult> SentMessage(NewLineNotifyMessage lineNotifyMessage)
{
var token = _httpContextAccessor.HttpContext?.Session.GetString(TokenKey);
if (!string.IsNullOrWhiteSpace(token))
{
if (lineNotifyMessage.ImageFormFile != null
&& (lineNotifyMessage.ImageFormFile.ContentType.Equals("image/png")
|| lineNotifyMessage.ImageFormFile.ContentType.Equals("image/jpeg")))
{
lineNotifyMessage.ImageFile = lineNotifyMessage.ImageFormFile.OpenReadStream();
}
try
{
await _lineNotifyServices.SentAsync(token, lineNotifyMessage);
ViewBag.Message = "Send Message Success";
}
catch (ValidationException e)
{
ViewBag.Message = string.Join(',', e.Errors.Select(x => x.ErrorMessage)).ToString();
}
}
else
{
ViewBag.Message = "You need to bind first";
}
return View("Index");
}
}
public class NewLineNotifyMessage : LineNotifyMessage
{
public IFormFile ImageFormFile { get; set; }
}
}
| 33.81982 | 112 | 0.592701 |
[
"MIT"
] |
a26007565/LineNotifySDK
|
LineNotifySample/Controllers/HomeController.cs
| 3,754 |
C#
|
// ReSharper disable MemberCanBePrivate.Global
namespace Modulos.Testing
{
using System;
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)]
public sealed class ScriptFileAttribute : ScriptAttribute
{
public ScriptFileAttribute()
: this("")
{
}
public ScriptFileAttribute(string splitter) : base(splitter)
{
}
}
}
| 21.789474 | 72 | 0.637681 |
[
"MIT"
] |
adobrzyc/modulos.testing.db
|
src/Modulos.Testing.Db/Attributes/ScriptFileAttribute.cs
| 416 |
C#
|
using System.Text;
using CoreHelper;
using CoreHelper.Ioc;
using Loogn.OrmLite;
using project.dao;
using project.dao.Models;
namespace project.backsite.Services
{
[AppService]
public class AnnouncementService
{
[Autowired] private AnnouncementDao announcementDao;
public AnnouncementService(AutowiredService autowiredService)
{
autowiredService.Autowired(this);
}
public ResultObject Edit(Announcement m)
{
var flag = 0L;
if (m.Id > 0)
{
flag = announcementDao.Update(m);
}
else
{
flag = announcementDao.Insert(m);
}
return new ResultObject(flag > 0);
}
public OrmLitePageResult<Announcement> SelectList(string title, int pageIndex, int pageSize)
{
StringBuilder sb = new StringBuilder();
var ps = DictBuilder.New();
sb.Append("1=1");
var orderBy = "id desc";
title = SqlInjection.Filter(title);
if (!string.IsNullOrEmpty(title))
{
sb.AppendFormat(" and Title like '%{0}%'", title);
}
var factor = new OrmLitePageFactor
{
Conditions = sb.ToString(),
PageIndex = pageIndex,
PageSize = pageSize,
OrderBy = orderBy,
Params = ps
};
return announcementDao.SelectPage(factor);
}
public Announcement SingleById(long id)
{
return announcementDao.SingleById(id);
}
public ResultObject Del(long id)
{
announcementDao.DeleteById(id);
return new ResultObject(true);
}
}
}
| 26.4 | 100 | 0.522727 |
[
"MIT"
] |
loogn/NetApiStarter
|
src/project.backsite/Services/AnnouncementService.cs
| 1,848 |
C#
|
namespace DCET.Model
{
public static class EventIdType
{
public const string RecvHotfixMessage = "RecvHotfixMessage";
public const string BehaviorTreeRunTreeEvent = "BehaviorTreeRunTreeEvent";
public const string BehaviorTreeOpenEditor = "BehaviorTreeOpenEditor";
public const string BehaviorTreeClickNode = "BehaviorTreeClickNode";
public const string BehaviorTreeAfterChangeNodeType = "BehaviorTreeAfterChangeNodeType";
public const string BehaviorTreeCreateNode = "BehaviorTreeCreateNode";
public const string BehaviorTreePropertyDesignerNewCreateClick = "BehaviorTreePropertyDesignerNewCreateClick";
public const string BehaviorTreeMouseInNode = "BehaviorTreeMouseInNode";
public const string BehaviorTreeConnectState = "BehaviorTreeConnectState";
public const string BehaviorTreeReplaceClick = "BehaviorTreeReplaceClick";
public const string BehaviorTreeRightDesignerDrag = "BehaviorTreeRightDesignerDrag";
public const string SessionRecvMessage = "SessionRecvMessage";
public const string NumbericChange = "NumbericChange";
public const string MessageDeserializeFinish = "MessageDeserializeFinish";
public const string SceneChange = "SceneChange";
public const string FrameUpdate = "FrameUpdate";
public const string LoadingBegin = "LoadingBegin";
public const string LoadingFinish = "LoadingFinish";
public const string TestHotfixSubscribMonoEvent = "TestHotfixSubscribMonoEvent";
public const string MaxModelEvent = "MaxModelEvent";
}
}
| 57.230769 | 112 | 0.826613 |
[
"MIT"
] |
zxsean/DCET
|
Unity/Packages/DCET/Core/Runtime/Base/Event/EventIdType.cs
| 1,490 |
C#
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace Iot.Device.Ws28xx.Esp32
{
/// <summary>
/// Represents the SK6812 Driver.
/// </summary>
/// <seealso cref="Iot.Device.Ws28xx.Ws28xx" />
public class Sk6812 : Ws28xx
{
/// <summary>
/// Initializes a new instance of the <see cref="Sk6812"/> class.
/// </summary>
/// <param name="gpioPin">The GPIO pin used for communication with the LED driver</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
public Sk6812(int gpioPin, int width, int height = 1)
: base(gpioPin, new BitmapImageWs2808Grb(width, height))
{
ClockDivider = 4;
OnePulse = new(14, true, 12, false);
ZeroPulse = new(7, true, 16, false);
ResetCommand = new(500, false, 520, false);
}
}
}
| 35.892857 | 97 | 0.585075 |
[
"MIT"
] |
josesimoes/nanoFramework.IoT.Device
|
devices/Ws28xx.Esp32/Sk6812.cs
| 1,007 |
C#
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
namespace BizHawk.Emulation.DiscSystem
{
public class FFMpeg
{
public static string FFMpegPath;
public class AudioQueryResult
{
public bool IsAudio;
}
private static string[] Escape(IEnumerable<string> args)
{
return args.Select(s => s.Contains(" ") ? $"\"{s}\"" : s).ToArray();
}
//note: accepts . or : in the stream stream/substream separator in the stream ID format, since that changed at some point in FFMPEG history
//if someone has a better idea how to make the determination of whether an audio stream is available, I'm all ears
static readonly Regex rxHasAudio = new Regex(@"Stream \#(\d*(\.|\:)\d*)\: Audio", RegexOptions.Compiled);
public AudioQueryResult QueryAudio(string path)
{
var ret = new AudioQueryResult();
string stdout = Run("-i", path).Text;
ret.IsAudio = rxHasAudio.Matches(stdout).Count > 0;
return ret;
}
/// <summary>
/// queries whether this service is available. if ffmpeg is broken or missing, then you can handle it gracefully
/// </summary>
public bool QueryServiceAvailable()
{
try
{
string stdout = Run("-version").Text;
if (stdout.Contains("ffmpeg version")) return true;
}
catch
{
}
return false;
}
public struct RunResults
{
public string Text;
public int ExitCode;
}
public RunResults Run(params string[] args)
{
args = Escape(args);
StringBuilder sbCmdline = new StringBuilder();
for (int i = 0; i < args.Length; i++)
{
sbCmdline.Append(args[i]);
if (i != args.Length - 1) sbCmdline.Append(' ');
}
ProcessStartInfo oInfo = new ProcessStartInfo(FFMpegPath, sbCmdline.ToString())
{
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardOutput = true,
RedirectStandardError = true
};
Process proc = Process.Start(oInfo);
string result = proc.StandardOutput.ReadToEnd();
result += proc.StandardError.ReadToEnd();
proc.WaitForExit();
return new RunResults
{
ExitCode = proc.ExitCode,
Text = result
};
}
public byte[] DecodeAudio(string path)
{
string tempfile = Path.GetTempFileName();
try
{
var runResults = Run("-i", path, "-xerror", "-f", "wav", "-ar", "44100", "-ac", "2", "-acodec", "pcm_s16le", "-y", tempfile);
if(runResults.ExitCode != 0)
throw new InvalidOperationException($"Failure running ffmpeg for audio decode. here was its output:\r\n{runResults.Text}");
byte[] ret = File.ReadAllBytes(tempfile);
if (ret.Length == 0)
throw new InvalidOperationException($"Failure running ffmpeg for audio decode. here was its output:\r\n{runResults.Text}");
return ret;
}
finally
{
File.Delete(tempfile);
}
}
}
class AudioDecoder
{
[Serializable]
public class AudioDecoder_Exception : Exception
{
public AudioDecoder_Exception(string message)
: base(message)
{
}
}
public AudioDecoder()
{
}
bool CheckForAudio(string path)
{
FFMpeg ffmpeg = new FFMpeg();
var qa = ffmpeg.QueryAudio(path);
return qa.IsAudio;
}
/// <summary>
/// finds audio at a path similar to the provided path (i.e. finds Track01.mp3 for Track01.wav)
/// TODO - isnt this redundant with CueFileResolver?
/// </summary>
string FindAudio(string audioPath)
{
string basePath = Path.GetFileNameWithoutExtension(audioPath);
//look for potential candidates
var di = new DirectoryInfo(Path.GetDirectoryName(audioPath));
var fis = di.GetFiles();
//first, look for the file type we actually asked for
foreach (var fi in fis)
{
if (fi.FullName.ToUpper() == audioPath.ToUpper())
if (CheckForAudio(fi.FullName))
return fi.FullName;
}
//then look for any other type
foreach (var fi in fis)
{
if (Path.GetFileNameWithoutExtension(fi.FullName).ToUpper() == basePath.ToUpper())
{
if (CheckForAudio(fi.FullName))
{
return fi.FullName;
}
}
}
return null;
}
public byte[] AcquireWaveData(string audioPath)
{
string path = FindAudio(audioPath);
if (path == null)
{
throw new AudioDecoder_Exception($"Could not find source audio for: {Path.GetFileName(audioPath)}");
}
return new FFMpeg().DecodeAudio(path);
}
}
}
| 26.633721 | 142 | 0.64069 |
[
"MIT"
] |
Gikkman/BizHawk
|
BizHawk.Emulation.DiscSystem/DiscDecoding.cs
| 4,583 |
C#
|
public class Enemy: Entity{
public EnemyType type;
public float movespeed;
public int damage;
public int moneyDrop;
public int expDrop;
public int health;
public bool isDead;
public float spawntime;
public static int ids = 0;
public Enemy(EnemyData enemyData) {
type = enemyData.type;
this.id = ids++;
movespeed = enemyData.movementSpeed;
moneyDrop = enemyData.moneyValue;
expDrop = enemyData.xpValue;
damage = enemyData.damage;
health = enemyData.health;
isDead = false;
spawntime = enemyData.spawntime;
}
public Enemy() {
// unit test
}
public void getDamaged(int damage) {
health -= damage;
if(health <= 0) {
isDead = true;
}
}
}
| 23.970588 | 44 | 0.584049 |
[
"MIT"
] |
bende24/TowerDefense
|
TowerDefense/Assets/Scripts/Entity/Enemy/Enemy.cs
| 815 |
C#
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Specialized;
using Xunit;
namespace System.ComponentModel.Design.Tests
{
public class DesignerActionTextItemTests : IClassFixture<ThreadExceptionFixture>
{
[Theory]
[InlineData("displayName", "category", "displayName")]
[InlineData("displa(&a)yName", "cate(&a)gory", "displayName")]
[InlineData("", "", "")]
[InlineData(null, null, null)]
public void DesignerActionItem_Ctor_String_String(string displayName, string category, string expectedDisplayName)
{
var item = new DesignerActionTextItem(displayName, category);
Assert.Equal(expectedDisplayName, item.DisplayName);
Assert.Equal(category, item.Category);
Assert.Null(item.Description);
Assert.False(item.AllowAssociate);
Assert.Empty(item.Properties);
Assert.Same(item.Properties, item.Properties);
Assert.IsType<HybridDictionary>(item.Properties);
Assert.True(item.ShowInSourceView);
}
}
}
| 40.645161 | 122 | 0.675397 |
[
"MIT"
] |
Amy-Li03/winforms
|
src/System.Windows.Forms.Design/tests/UnitTests/System/ComponentModel/Design/DesignerActionTextItemTests.cs
| 1,260 |
C#
|
namespace Nest
{
[MapsApi("xpack.rollup.stop_job.json")]
public partial interface IStopRollupJobRequest { }
public partial class StopRollupJobRequest { }
public partial class StopRollupJobDescriptor { }
}
| 21.2 | 51 | 0.778302 |
[
"Apache-2.0"
] |
Henr1k80/elasticsearch-net
|
src/Nest/XPack/RollUp/StopRollupJob/StopRollupJobRequest.cs
| 214 |
C#
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.