content stringlengths 23 1.05M |
|---|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
namespace CoreWebAppExample
{
[DataContract]
public class ResourceAuthority : CredentialObject
{
private string _title = "";
private List<ResourcePath> _paths = null;
[DataMember]
public string Title
{
get { return _title; }
set { _title = value ?? ""; }
}
[DataMember]
public List<ResourcePath> Paths
{
get
{
List<ResourcePath> paths = _paths;
if (paths == null)
{
paths = new List<ResourcePath>();
_paths = paths;
}
return paths;
}
set { _paths = value; }
}
public override void Normalize() { CredentialDataStore.NormalizeIDs<ResourcePath>(_paths); }
public ResourceAuthorityInfo AsServiceObject()
{
Normalize();
return new ResourceAuthorityInfo(this);
}
}
} |
using Newtonsoft.Json;
namespace MLFlow.NET.Lib.Model.Responses.Run
{
public class RunInfo
{
[JsonProperty("run_uuid")]
public string RunUuid { get; set; }
[JsonProperty("experiment_id")]
public string ExperimentId { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("source_type")]
public string SourceType { get; set; }
[JsonProperty("source_name")]
public string SourceName { get; set; }
[JsonProperty("user_id")]
public string UserId { get; set; }
[JsonProperty("status")]
public string Status { get; set; }
[JsonProperty("start_time")]
public string StartTime { get; set; }
[JsonProperty("artifact_uri")]
public string ArtifactUri { get; set; }
[JsonProperty("lifecycle_stage")]
public string LifecycleStage { get; set; }
}
} |
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
namespace Blogger
{
/// <summary>
/// Summary description for addentry.
/// </summary>
public class addentry : System.Windows.Forms.Form
{
private System.Windows.Forms.TextBox EntryText;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.TextBox EntryTitleBox;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public addentry()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
}
public string Entry
{
get
{
return this.EntryText.Text;
}
}
public string EntryTitle
{
get
{
return this.EntryTitleBox.Text;
}
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.EntryText = new System.Windows.Forms.TextBox();
this.button1 = new System.Windows.Forms.Button();
this.EntryTitleBox = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// EntryText
//
this.EntryText.Location = new System.Drawing.Point(32, 64);
this.EntryText.Multiline = true;
this.EntryText.Name = "EntryText";
this.EntryText.Size = new System.Drawing.Size(536, 136);
this.EntryText.TabIndex = 3;
this.EntryText.Text = "";
this.EntryText.TextChanged += new System.EventHandler(this.EntryText_TextChanged);
//
// button1
//
this.button1.DialogResult = System.Windows.Forms.DialogResult.OK;
this.button1.Enabled = false;
this.button1.Location = new System.Drawing.Point(472, 24);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(96, 24);
this.button1.TabIndex = 4;
this.button1.Text = "&Ok";
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// EntryTitleBox
//
this.EntryTitleBox.Location = new System.Drawing.Point(112, 16);
this.EntryTitleBox.Name = "EntryTitleBox";
this.EntryTitleBox.Size = new System.Drawing.Size(248, 20);
this.EntryTitleBox.TabIndex = 2;
this.EntryTitleBox.Text = "";
this.EntryTitleBox.TextChanged += new System.EventHandler(this.EntryTitleBox_TextChanged);
//
// label2
//
this.label2.Location = new System.Drawing.Point(32, 16);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(48, 16);
this.label2.TabIndex = 4;
this.label2.Text = "Title";
//
// addentry
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(592, 214);
this.Controls.Add(this.EntryTitleBox);
this.Controls.Add(this.label2);
this.Controls.Add(this.button1);
this.Controls.Add(this.EntryText);
this.Name = "addentry";
this.Text = "addentry";
this.ResumeLayout(false);
}
#endregion
private void EntryText_TextChanged(object sender, System.EventArgs e)
{
Verify();
}
private void button1_Click(object sender, System.EventArgs e)
{
this.Close();
}
private void Verify()
{
if (this.Name.Length > 0 &&
this.Entry.Length > 0 &&
this.EntryTitle.Length > 0)
{
this.button1.Enabled = true;
}
else
{
this.button1.Enabled = false;
}
}
private void EntryTitleBox_TextChanged(object sender, System.EventArgs e)
{
Verify();
}
}
}
|
using Xunit;
using Xunit.Extensions.Ordering;
using Xunit.Extensions.Ordering.Tests;
using Xunit.Extensions.Ordering.Tests.Fixtures;
[assembly: CollectionBehavior(DisableTestParallelization = true)]
[assembly: TestFramework("Xunit.Extensions.Ordering.TestFramework", "Xunit.Extensions.Ordering")]
[assembly: TestCaseOrderer("Xunit.Extensions.Ordering.TestCaseOrderer", "Xunit.Extensions.Ordering")]
[assembly: TestCollectionOrderer("Xunit.Extensions.Ordering.CollectionOrderer", "Xunit.Extensions.Ordering")]
[assembly: AssemblyFixture(typeof(AssemblyFixture4))]
[assembly: AssemblyFixture(typeof(AssemblyFixture5), typeof(AssemblyFixture6))] |
/// ---------------------------------------------
/// Ultimate Character Controller
/// Copyright (c) Opsive. All Rights Reserved.
/// https://www.opsive.com
/// ---------------------------------------------
using UnityEditor;
using UnityEngine;
namespace Opsive.UltimateCharacterController.Inventory
{
/// <summary>
/// The ItemCollection ScriptableObject is a container for the static item data.
/// </summary>
public class AnimationStateCollection : ScriptableObject {
private const string c_ItemIdsName = "Item Ids";
private const string c_ItemStateIndexesName = "Item State Indexes";
private const string c_AbilityIndexesName = "Ability Indexes";
[SerializeField] protected AnimationStateSet m_ItemIds;
[SerializeField] protected AnimationStateSet m_ItemStateIndexes;
[SerializeField] protected AnimationStateSet m_AbilityIndexes;
private AnimationStateSet CreateStateSet(string name) {
AnimationStateSet set = new AnimationStateSet();
set.name = name;
AssetDatabase.AddObjectToAsset(set, this);
AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(this));
EditorUtility.SetDirty(this);
AssetDatabase.SaveAssets();
return set;
}
private void Deserialize() {
Debug.Log("Loading assets in " + AssetDatabase.GetAssetPath(this));
Object[] assets = AssetDatabase.LoadAllAssetsAtPath(
AssetDatabase.GetAssetPath(this));
if (null != assets) {
foreach (Object asset in assets) {
if (null != asset && !string.IsNullOrEmpty(asset.name)) {
switch (asset.name) {
case c_ItemIdsName:
m_ItemIds = m_ItemIds ?? asset as AnimationStateSet;
break;
case c_ItemStateIndexesName:
m_ItemStateIndexes = m_ItemStateIndexes ?? asset as AnimationStateSet;
break;
case c_AbilityIndexesName:
m_AbilityIndexes = m_AbilityIndexes ?? asset as AnimationStateSet;
break;
}
}
}
}
if (m_ItemIds == null) {
m_ItemIds = CreateStateSet(c_ItemIdsName);
}
if (m_ItemStateIndexes == null) {
m_ItemStateIndexes = CreateStateSet(c_ItemStateIndexesName);
}
if (m_AbilityIndexes == null) {
m_AbilityIndexes = CreateStateSet(c_AbilityIndexesName);
}
Debug.Log("Item id count: " + m_ItemIds.AnimationStates.Length);
}
public AnimationStateSet ItemIds {
get {
if(m_ItemIds == null) {
Deserialize();
}
return m_ItemIds;
}
set { m_ItemIds = value; }
}
public AnimationStateSet ItemStateIndexes {
get {
if (m_ItemStateIndexes == null) {
Deserialize();
}
return m_ItemStateIndexes;
}
set { m_ItemStateIndexes = value; }
}
public AnimationStateSet AbilityIndexes {
get {
if (m_AbilityIndexes == null) {
Deserialize();
}
return m_AbilityIndexes;
}
set { m_AbilityIndexes = value; }
}
}
} |
using lids.library.Enums;
namespace lids.library.DAL.Transports
{
public class QueueItem
{
public DAL_TRANSACTION_TYPES TransactionType { get; set; }
public dynamic QueueObject { get; set; }
}
} |
/* TwoFactor
*
* This program is free software. It comes without any warranty, to
* the extent permitted by applicable law. You can redistribute it
* and/or modify it under the terms of the Do What The Fuck You Want
* To Public License, Version 2.
*/
using System;
using System.Linq;
using System.Security.Cryptography;
namespace TwoFactorAuthentication
{
public class TwoFactor
{
/// <summary>
/// Used to Generate 2FA code,
/// it is the key used to generate the code.
/// Is set by the constructor and given as base32 encoded string.
/// </summary>
public readonly byte[] Secret;
public TwoFactor(string secret)=>
Secret = Base32.ToArray(secret);
/// <summary>
/// Generate a 2FA code
/// </summary>
/// <returns>6 digit 2FA code</returns>
/// See: https://tools.ietf.org/html/rfc6238
public string GenerateCode()
{
//Get timestamp.
DateTime EPOCH = new DateTime(1970, 1, 1, 0, 0, 0);
long timestamp = Convert.ToInt64(
Math.Round((DateTime.UtcNow - EPOCH).TotalSeconds)) / 30;
using (var HMAC = new HMACSHA1(Secret))
{
//Generate hash with secret as key and the current time.
//See: https://docs.microsoft.com/en-us/dotnet/api/system.security.cryptography.hmacsha1
byte[] h = HMAC.ComputeHash(
BitConverter.GetBytes(timestamp).Reverse().ToArray());
//Generate 6 digit number from hash.
int offset = h.Last() & 0x0F;
int number = (
((h[offset + 0] & 0x7f) << 24) |
((h[offset + 1] & 0xff) << 16) |
((h[offset + 2] & 0xff) << 8) |
(h[offset + 3] & 0xff)) % 1000000;
//Create a string from the number.
//Padleft to add zero's if needed.
return number.ToString().PadLeft(6, '0');
}
}
/// <summary>
/// Validate a passed code.
/// </summary>
/// <param name="twoFactorCode">6 digit 2FA code</param>
public bool ValidateCode(string twoFactorCode)=>
GenerateCode().Equals(twoFactorCode);
/// <summary>
/// Generate a new secret
/// </summary>
/// <returns>Generated a secret</returns>
public static string GenerateRandomSecret()
{
byte[] randomBytes = new byte[32];
using (var rng = new RNGCryptoServiceProvider())
rng.GetBytes(randomBytes);
return string.Concat(randomBytes.Select(v => "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"[v & 31]));
}
/// <summary>
/// Generates the string that is needed to generate a qr code.
/// Create a qr code of this string to scan with authy/Google Authenticator
/// </summary>
public static string GenerateQRCodeString(string secret, string label, string issuer)
=> $"otpauth://totp/{label}?secret={secret}&issuer={issuer}";
}
} |
using JetBrains.Annotations;
using UVACanvasAccess.Model.Analytics;
using UVACanvasAccess.Util;
namespace UVACanvasAccess.Structures.Analytics
{
[PublicAPI]
public class Tardiness : IPrettyPrint
{
internal Tardiness(TardinessModel model)
{
Missing = model.Missing;
Late = model.Late;
OnTime = model.OnTime;
Floating = model.Floating;
Total = model.Total;
}
public decimal Floating { get; }
public decimal Late { get; }
public decimal Missing { get; }
public decimal OnTime { get; }
public decimal Total { get; }
public string ToPrettyString() => "Tardiness {" +
($"\n{nameof(Missing)}: {Missing}," +
$"\n{nameof(Late)}: {Late}," +
$"\n{nameof(OnTime)}: {OnTime}," +
$"\n{nameof(Floating)}: {Floating}," +
$"\n{nameof(Total)}: {Total}").Indent(4) +
"\n}";
}
} |
@model Demo.Web.ViewModels.CreateEmployeeViewModel
@{
ViewBag.Title = "Create Employee";
}
@{
Html.EnableClientValidation();
Html.EnableUnobtrusiveJavaScript();
}
@section styles
{
<style type="text/css">
.groupheaderLevel1 {
position: relative;
left: 50% !important;
transform: translateX(-50%);
}
</style>
}
<div class="row justify-content-center">
<div class="col-xl-6 col-lg-6 col-md-6 col-12">
<div class="card shadow-lg border-0 rounded-lg mt-5">
<div class="card-header">
<h3 class="text-center font-weight-light my-4">@ViewBag.Title</h3>
</div>
<div class="card-body">
@Html.Partial("_CreateEmployeeFormLayoutPartial", Model)
</div>
</div>
<hr/>
<div class="text-center">
@Html.ActionLink("Go back to Index", "Index", "Home")
</div>
</div>
</div>
@section scripts
{
<script type="text/javascript">
const toastType = '@TempData["ToastType"]', toastMessage = '@TempData["ToastMessage"]';
DisplayToastMessage(toastType, toastMessage);
</script>
}
|
using System.Threading.Tasks;
using System.Web.Mvc;
using BackOffice.Areas.Users.Models;
using BackOffice.Controllers;
using BackOffice.Translates;
using Core;
namespace BackOffice.Areas.Users.Controllers
{
[Authorize]
public class ChangeMyPasswordController : Controller
{
private readonly IBackOfficeUsersRepository _backOfficeUsersRepository;
public ChangeMyPasswordController(IBackOfficeUsersRepository backOfficeUsersRepository)
{
_backOfficeUsersRepository = backOfficeUsersRepository;
}
public ActionResult Index()
{
return View();
}
[HttpPost]
public async Task<ActionResult> ChangeMyPassword(ChangeMyPasswordModel model)
{
if (string.IsNullOrEmpty(model.NewPassword))
return this.JsonFailResult(Phrases.FieldShouldNotBeEmpty, "#newPassword");
if (string.IsNullOrEmpty(model.PasswordConfirmation))
return this.JsonFailResult(Phrases.FieldShouldNotBeEmpty, "#passwordConfirmation");
if (model.NewPassword != model.PasswordConfirmation)
return this.JsonFailResult(Phrases.PasswordsDoNotMatch, "#passwordConfirmation");
var id = this.GetUserId();
await _backOfficeUsersRepository.ChangePasswordAsync(id, model.NewPassword);
return this.JsonFailResult(Phrases.PasswordIsNowChanged, "#btnChangePassword");
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public enum MissionType
{
None,
Daily = 1,
Week,
Month,
}
public class Mission
{
public int mId;
public MissionType mType;
public DateTime mDateTime;
public string mTextureName;
private Texture mTexture;
public string mDesc;
public int mCount;
public int mFinished;
/// temp var
public MissionLog mLog = null;
///
public Texture texture
{
get
{
if(mTexture == null)
{
// todo load texture
mTexture = AssetHelper.LoadTableMissionPic(mTextureName);
if(mTexture == null)
{
mTexture = AssetHelper.LoadMissionPic(mTextureName);
}
return mTexture;
}
return mTexture;
}
set
{
mTexture = value;
}
}
public bool IsOld()
{
if(mDateTime == null) return false;
int day1 = TimeConvert.GetDays(mDateTime);
int day2 = TimeConvert.NowDay();
if(day2 != day1) return true;
return false;
}
public bool IsFinished()
{
int day1 = TimeConvert.NowDay();
if(day1 != mFinished) return false;
return true;
}
public Dictionary<string,object> ToDic()
{
Dictionary<string,object> dic = new Dictionary<string,object>();
dic.Add("id",mId);
dic.Add("type",(int)mType);
dic.Add("time",mDateTime.Ticks);
dic.Add("tex_name",mTextureName);
dic.Add("desc",mDesc);
dic.Add("count",mCount);
dic.Add("finished",mFinished);
return dic;
}
public void ToModel(Dictionary<string, object> _dic)
{
mId = Convert.ToInt32(_dic["id"]);
mType = (MissionType)Convert.ToInt32(_dic["type"]);
mDateTime = new DateTime(Convert.ToInt64(_dic["time"]));
mTextureName = _dic["tex_name"].ToString();
mDesc = _dic["desc"].ToString();
mCount = Convert.ToInt32(_dic["count"]);
mFinished = Convert.ToInt32(_dic["finished"]);
}
}
|
using DotNetNote.Models;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace DotNetNote.ViewComponents
{
public class DataListViewComponent : ViewComponent
{
public async Task<IViewComponentResult> InvokeAsync(string name)
{
var data = await GetByNameAsync(name);
return View(data);
}
private Task<IEnumerable<DataModel>> GetByNameAsync(string name)
{
return Task.FromResult(GetByName(name));
}
private IEnumerable<DataModel> GetByName(string name)
{
DataService service = new DataService();
return service.GetDataByName(name);
}
}
}
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System.Collections.Generic;
using Azure.Core;
namespace Azure.ResourceManager.MachineLearningServices.Models
{
/// <summary> The RegistryListCredentialsResult. </summary>
public partial class RegistryListCredentialsResult
{
/// <summary> Initializes a new instance of RegistryListCredentialsResult. </summary>
internal RegistryListCredentialsResult()
{
Passwords = new ChangeTrackingList<Password>();
}
/// <summary> Initializes a new instance of RegistryListCredentialsResult. </summary>
/// <param name="location"> . </param>
/// <param name="username"> . </param>
/// <param name="passwords"> . </param>
internal RegistryListCredentialsResult(string location, string username, IReadOnlyList<Password> passwords)
{
Location = location;
Username = username;
Passwords = passwords;
}
public string Location { get; }
public string Username { get; }
public IReadOnlyList<Password> Passwords { get; }
}
}
|
//[Obsolete]
[Obsolete("Use Test2")]
public class Test
{
public Test()
{
WriteLine("Version 1");
}
}
[Data("Implemented by César")]
public class Test2
{
public Test2()
{
WriteLine("Version 2");
}
}
[AttributeUsage(AttributeTargets.All, AllowMultiple = false)]
public sealed class DataAttribute : System.Attribute
{
public string Data { get; }
public DataAttribute() { }
public DataAttribute(string data)
{
Data = data;
}
}
|
using LLVMSharp.API;
using LLVMSharp.API.Types;
using LLVMSharp.API.Types.Composite.SequentialTypes;
using LLVMSharp.API.Values.Constants;
using LLVMSharp.API.Values.Constants.ConstantDataSequentials;
using LLVMSharp.API.Values.Constants.GlobalValues.GlobalObjects;
using System;
using System.Reflection;
using System.Reflection.Emit;
namespace CLILL
{
partial class Compiler
{
private static void CompileGlobals(CompilationContext context)
{
var constructor = context.TypeBuilder.DefineTypeInitializer();
var ilGenerator = constructor.GetILGenerator();
var global = (GlobalVariable)context.LLVMModule.GetFirstGlobal();
while (global != null)
{
// TODO
var fieldType = GetMsilType(global.Type);
var globalField = context.TypeBuilder.DefineField(
global.Name.Replace(".", string.Empty),
fieldType,
FieldAttributes.Private | FieldAttributes.Static);
switch (global.Operands[0])
{
case ConstantDataArray v:
var arrayType = (ArrayType)v.Type;
ilGenerator.Emit(OpCodes.Ldc_I4, (int) arrayType.Length);
ilGenerator.Emit(OpCodes.Newarr, GetMsilType(arrayType.ElementType));
for (var i = 0u; i < arrayType.Length; i++)
{
ilGenerator.Emit(OpCodes.Dup);
ilGenerator.Emit(OpCodes.Ldc_I4, i);
EmitLoadConstantAndStoreElement(ilGenerator, v.GetElementAsConstant(i));
}
break;
}
ilGenerator.Emit(OpCodes.Stsfld, globalField);
ilGenerator.Emit(OpCodes.Ret);
context.Globals.Add(global, globalField);
global = global.NextGlobal;
}
}
private static void EmitLoadConstantAndStoreElement(ILGenerator ilGenerator, Value value)
{
switch (value)
{
case ConstantInt c:
var integerType = (IntegerType)c.Type;
switch (integerType.BitWidth)
{
case 8:
ilGenerator.Emit(OpCodes.Ldc_I4, (int)c.SExtValue);
ilGenerator.Emit(OpCodes.Stelem_I1);
break;
default:
throw new NotImplementedException();
}
break;
default:
throw new NotImplementedException();
}
}
}
}
|
using System;
using Tomino;
public static class GameExtension
{
public static void WaitUntilPieceFallsAutomatically(this Game game)
{
var pieceFinishedFalling = false;
Game.GameEventHandler eventHandler = delegate { pieceFinishedFalling = true; };
game.PieceFinishedFallingEvent += eventHandler;
while (!pieceFinishedFalling) game.Update(1.0f);
game.PieceFinishedFallingEvent -= eventHandler;
}
} |
using VRC.SDK3.Avatars.Components;
namespace Mochizuki.VRChat.ParticleLiveToolkit.Internal
{
// ReSharper disable once InconsistentNaming
internal static class VRCAnimatorLocomotionControlExtensions
{
public static void ApplyTo(this VRCAnimatorLocomotionControl source, VRCAnimatorLocomotionControl dest)
{
dest.ApplySettings = source.ApplySettings;
dest.debugString = source.debugString;
dest.disableLocomotion = source.disableLocomotion;
dest.hideFlags = source.hideFlags;
dest.name = source.name;
}
}
} |
using RuriLib.Functions.Http;
using RuriLib.Legacy.LS;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RuriLib.Blocks.Requests.Http;
using System.Threading.Tasks;
using RuriLib.Legacy.Models;
using RuriLib.Functions.Http.Options;
using RuriLib.Functions.Conversion;
using RuriLib.Models.Blocks.Custom.HttpRequest.Multipart;
using RuriLib.Logging;
using System.IO;
namespace RuriLib.Legacy.Blocks
{
/// <summary>
/// A block that can perform HTTP requests.
/// </summary>
public class BlockRequest : BlockBase
{
#region Variables
/// <summary>The URL to call, including additional GET query parameters.</summary>
public string Url { get; set; } = "https://google.com";
/// <summary>The request type.</summary>
public RequestType RequestType { get; set; } = RequestType.Standard;
// Basic Auth
/// <summary>The username for basic auth requests.</summary>
public string AuthUser { get; set; } = "";
/// <summary>The password for basic auth requests.</summary>
public string AuthPass { get; set; } = "";
// Standard
/// <summary>The content of the request, sent after the headers. Use '\n' to input a linebreak.</summary>
public string PostData { get; set; } = "";
// Raw
/// <summary>The content of the request as a raw HEX string that will be sent as a bytestream.</summary>
public string RawData { get; set; } = "";
/// <summary>The method of the HTTP request.</summary>
public HttpMethod Method { get; set; } = HttpMethod.GET;
/// <summary>The security protocol(s) to use for the HTTPS request.</summary>
public SecurityProtocol SecurityProtocol { get; set; } = SecurityProtocol.SystemDefault;
/// <summary>The custom headers that are sent in the HTTP request.</summary>
public Dictionary<string, string> CustomHeaders { get; set; } = new Dictionary<string, string>() {
{ "User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36" },
{ "Pragma", "no-cache" },
{ "Accept", "*/*" }
};
/// <summary>The custom cookies that are sent in the HTTP request.</summary>
public Dictionary<string, string> CustomCookies { get; set; } = new();
/// <summary>The type of content the server should expect.</summary>
public string ContentType { get; set; } = "application/x-www-form-urlencoded";
/// <summary>Whether to perform automatic redirection in the case of 3xx headers.</summary>
public bool AutoRedirect { get; set; } = true;
/// <summary>Whether to read the stream of data from the HTTP response. Set to false if only the headers are needed, in order to speed up the process.</summary>
public bool ReadResponseSource { get; set; } = true;
/// <summary>Whether to URL encode the content before sending it.</summary>
public bool EncodeContent { get; set; } = false;
/// <summary>Whether to automatically generate an Accept-Encoding header.</summary>
public bool AcceptEncoding { get; set; } = true;
// Multipart
/// <summary>The boundary that separates multipart contents.</summary>
public string MultipartBoundary { get; set; } = "";
/// <summary>The list of contents to send in a multipart request.</summary>
public List<MultipartContent> MultipartContents { get; set; } = new();
/// <summary>The type of response expected from the server.</summary>
public ResponseType ResponseType { get; set; } = ResponseType.String;
/// <summary>The path of the file where a FILE response needs to be stored.</summary>
public string DownloadPath { get; set; } = "";
/// <summary>The variable name for Base64String response.</summary>
public string OutputVariable { get; set; } = "";
/// <summary>Whether to add the downloaded image to the default screenshot path.</summary>
public bool SaveAsScreenshot { get; set; } = false;
#endregion
/// <summary>
/// Creates a Request block.
/// </summary>
public BlockRequest()
{
Label = "REQUEST";
}
/// <inheritdoc />
public override BlockBase FromLS(string line)
{
// Trim the line
var input = line.Trim();
// Parse the label
if (input.StartsWith("#"))
Label = LineParser.ParseLabel(ref input);
Method = (HttpMethod)LineParser.ParseEnum(ref input, "METHOD", typeof(HttpMethod));
Url = LineParser.ParseLiteral(ref input, "URL");
while (LineParser.Lookahead(ref input) == TokenType.Boolean)
LineParser.SetBool(ref input, this);
CustomHeaders.Clear(); // Remove the default headers
while (input != string.Empty && !input.StartsWith("->"))
{
var parsed = LineParser.ParseToken(ref input, TokenType.Parameter, true).ToUpper();
switch (parsed)
{
case "MULTIPART":
RequestType = RequestType.Multipart;
break;
case "BASICAUTH":
RequestType = RequestType.BasicAuth;
break;
case "STANDARD":
RequestType = RequestType.Standard;
break;
case "RAW":
RequestType = RequestType.Raw;
break;
case "CONTENT":
PostData = LineParser.ParseLiteral(ref input, "POST DATA");
break;
case "RAWDATA":
RawData = LineParser.ParseLiteral(ref input, "RAW DATA");
break;
case "STRINGCONTENT":
var stringContentPair = ParseString(LineParser.ParseLiteral(ref input, "STRING CONTENT"), ':', 2);
MultipartContents.Add(new MultipartContent() { Type = MultipartContentType.String, Name = stringContentPair[0], Value = stringContentPair[1] });
break;
case "FILECONTENT":
var fileContentTriplet = ParseString(LineParser.ParseLiteral(ref input, "FILE CONTENT"), ':', 3);
MultipartContents.Add(new MultipartContent() { Type = MultipartContentType.File, Name = fileContentTriplet[0], Value = fileContentTriplet[1], ContentType = fileContentTriplet[2] });
break;
case "COOKIE":
var cookiePair = ParseString(LineParser.ParseLiteral(ref input, "COOKIE VALUE"), ':', 2);
CustomCookies[cookiePair[0]] = cookiePair[1];
break;
case "HEADER":
var headerPair = ParseString(LineParser.ParseLiteral(ref input, "HEADER VALUE"), ':', 2);
CustomHeaders[headerPair[0]] = headerPair[1];
break;
case "CONTENTTYPE":
ContentType = LineParser.ParseLiteral(ref input, "CONTENT TYPE");
break;
case "USERNAME":
AuthUser = LineParser.ParseLiteral(ref input, "USERNAME");
break;
case "PASSWORD":
AuthPass = LineParser.ParseLiteral(ref input, "PASSWORD");
break;
case "BOUNDARY":
MultipartBoundary = LineParser.ParseLiteral(ref input, "BOUNDARY");
break;
case "SECPROTO":
SecurityProtocol = LineParser.ParseEnum(ref input, "Security Protocol", typeof(SecurityProtocol));
break;
default:
break;
}
}
if (input.StartsWith("->"))
{
LineParser.EnsureIdentifier(ref input, "->");
var outType = LineParser.ParseToken(ref input, TokenType.Parameter, true);
if (outType.ToUpper() == "STRING") ResponseType = ResponseType.String;
else if (outType.ToUpper() == "FILE")
{
ResponseType = ResponseType.File;
DownloadPath = LineParser.ParseLiteral(ref input, "DOWNLOAD PATH");
while (LineParser.Lookahead(ref input) == TokenType.Boolean)
{
LineParser.SetBool(ref input, this);
}
}
else if (outType.ToUpper() == "BASE64")
{
ResponseType = ResponseType.Base64String;
OutputVariable = LineParser.ParseLiteral(ref input, "OUTPUT VARIABLE");
}
}
return this;
}
/// <summary>
/// Parses values from a string.
/// </summary>
/// <param name="input">The string to parse</param>
/// <param name="separator">The character that separates the elements</param>
/// <param name="count">The number of elements to return</param>
/// <returns>The array of the parsed elements.</returns>
public static string[] ParseString(string input, char separator, int count)
=> input.Split(new[] { separator }, count).Select(s => s.Trim()).ToArray();
/// <inheritdoc />
public override string ToLS(bool indent = true)
{
var writer = new BlockWriter(GetType(), indent, Disabled);
writer
.Label(Label)
.Token("REQUEST")
.Token(Method)
.Literal(Url)
.Boolean(AcceptEncoding, "AcceptEncoding")
.Boolean(AutoRedirect, "AutoRedirect")
.Boolean(ReadResponseSource, "ReadResponseSource")
.Boolean(EncodeContent, "EncodeContent")
.Token(RequestType, "RequestType")
.Indent();
switch (RequestType)
{
case RequestType.BasicAuth:
writer
.Token("USERNAME")
.Literal(AuthUser)
.Token("PASSWORD")
.Literal(AuthPass)
.Indent();
break;
case RequestType.Standard:
writer
.Token("CONTENT")
.Literal(PostData)
.Indent()
.Token("CONTENTTYPE")
.Literal(ContentType);
break;
case RequestType.Multipart:
foreach(var c in MultipartContents)
{
writer
.Indent()
.Token($"{c.Type.ToString().ToUpper()}CONTENT");
if (c.Type == MultipartContentType.String)
{
writer.Literal($"{c.Name}: {c.Value}");
}
else if (c.Type == MultipartContentType.File)
{
writer.Literal($"{c.Name}: {c.Value}: {c.ContentType}");
}
}
if (!writer.CheckDefault(MultipartBoundary, "MultipartBoundary"))
{
writer
.Indent()
.Token("BOUNDARY")
.Literal(MultipartBoundary);
}
break;
case RequestType.Raw:
writer
.Token("RAWDATA")
.Literal(RawData)
.Indent()
.Token("CONTENTTYPE")
.Literal(ContentType);
break;
}
if (SecurityProtocol != SecurityProtocol.SystemDefault)
{
writer
.Indent()
.Token("SECPROTO")
.Token(SecurityProtocol, "SecurityProtocol");
}
foreach (var c in CustomCookies)
{
writer
.Indent()
.Token("COOKIE")
.Literal($"{c.Key}: {c.Value}");
}
foreach (var h in CustomHeaders)
{
writer
.Indent()
.Token("HEADER")
.Literal($"{h.Key}: {h.Value}");
}
if (ResponseType == ResponseType.File)
{
writer
.Indent()
.Arrow()
.Token("FILE")
.Literal(DownloadPath)
.Boolean(SaveAsScreenshot, "SaveAsScreenshot");
}
else if (ResponseType == ResponseType.Base64String)
{
writer
.Indent()
.Arrow()
.Token("BASE64")
.Literal(OutputVariable);
}
return writer.ToString();
}
/// <inheritdoc />
public override async Task Process(LSGlobals ls)
{
var data = ls.BotData;
await base.Process(ls);
var headers = ReplaceValues(CustomHeaders, ls);
// If no Connection header was specified, add keep-alive by default
if (!headers.Keys.Any(k => k.Equals("connection", StringComparison.OrdinalIgnoreCase)))
{
headers.Add("Connection", "keep-alive");
}
// Override the default for Accept-Encoding (default behaviour in OB1)
foreach (var key in headers.Keys.Where(k => k.Equals("accept-encoding", StringComparison.OrdinalIgnoreCase)).ToArray())
{
headers.Remove(key);
}
headers["Accept-Encoding"] = "gzip,deflate";
// Remove Content-Length because it was disregarded in OB1
var contentLengthHeader = headers.Keys.FirstOrDefault(k => k.Equals("Content-Length", StringComparison.OrdinalIgnoreCase));
if (contentLengthHeader != null)
{
headers.Remove(contentLengthHeader);
}
switch (RequestType)
{
case RequestType.Standard:
var standardOptions = new StandardHttpRequestOptions
{
AutoRedirect = AutoRedirect,
MaxNumberOfRedirects = 8,
ReadResponseContent = ReadResponseSource,
SecurityProtocol = SecurityProtocol,
Content = ReplaceValues(PostData, ls),
ContentType = ReplaceValues(ContentType, ls),
CustomCookies = ReplaceValues(CustomCookies, ls),
CustomHeaders = headers,
Method = Method,
Url = ReplaceValues(Url, ls),
TimeoutMilliseconds = 10000,
UrlEncodeContent = EncodeContent
};
await Methods.HttpRequestStandard(data, standardOptions);
break;
case RequestType.Raw:
var rawOptions = new RawHttpRequestOptions
{
AutoRedirect = AutoRedirect,
MaxNumberOfRedirects = 8,
ReadResponseContent = ReadResponseSource,
SecurityProtocol = SecurityProtocol,
Content = HexConverter.ToByteArray(ReplaceValues(RawData, ls)),
ContentType = ReplaceValues(ContentType, ls),
CustomCookies = ReplaceValues(CustomCookies, ls),
CustomHeaders = headers,
Method = Method,
Url = ReplaceValues(Url, ls),
TimeoutMilliseconds = 10000
};
await Methods.HttpRequestRaw(data, rawOptions);
break;
case RequestType.BasicAuth:
var basicAuthOptions = new BasicAuthHttpRequestOptions
{
AutoRedirect = AutoRedirect,
MaxNumberOfRedirects = 8,
ReadResponseContent = ReadResponseSource,
SecurityProtocol = SecurityProtocol,
Username = ReplaceValues(AuthUser, ls),
Password = ReplaceValues(AuthPass, ls),
CustomCookies = ReplaceValues(CustomCookies, ls),
CustomHeaders = headers,
Method = Method,
Url = ReplaceValues(Url, ls),
TimeoutMilliseconds = 10000
};
await Methods.HttpRequestBasicAuth(data, basicAuthOptions);
break;
case RequestType.Multipart:
var multipartOptions = new MultipartHttpRequestOptions
{
AutoRedirect = AutoRedirect,
MaxNumberOfRedirects = 8,
ReadResponseContent = ReadResponseSource,
SecurityProtocol = SecurityProtocol,
Boundary = ReplaceValues(MultipartBoundary, ls),
Contents = MultipartContents.Select(mpc => MapMultipartContent(mpc, ls)).ToList(),
CustomCookies = ReplaceValues(CustomCookies, ls),
CustomHeaders = headers,
Method = Method,
Url = ReplaceValues(Url, ls),
TimeoutMilliseconds = 10000
};
await Methods.HttpRequestMultipart(data, multipartOptions);
break;
}
// Save the response content
switch (ResponseType)
{
case ResponseType.File:
if (SaveAsScreenshot)
{
Utils.SaveScreenshot(data.RAWSOURCE, data);
data.Logger.Log("File saved as screenshot", LogColors.Green);
}
else
{
File.WriteAllBytes(ReplaceValues(DownloadPath, ls), data.RAWSOURCE);
}
break;
case ResponseType.Base64String:
var base64 = Convert.ToBase64String(data.RAWSOURCE);
InsertVariable(ls, false, base64, OutputVariable);
break;
default:
break;
}
}
#region Custom Cookies, Headers and Multipart Contents
/// <summary>
/// Builds a string containing custom cookies.
/// </summary>
/// <returns>One cookie per line, with name and value separated by a colon</returns>
public string GetCustomCookies()
{
var sb = new StringBuilder();
foreach (var pair in CustomCookies)
{
sb.Append($"{pair.Key}: {pair.Value}");
if (!pair.Equals(CustomCookies.Last())) sb.Append(Environment.NewLine);
}
return sb.ToString();
}
/// <summary>
/// Sets custom cookies from an array of lines.
/// </summary>
/// <param name="lines">The lines containing the colon-separated name and value of the cookies</param>
public void SetCustomCookies(string[] lines)
{
CustomCookies.Clear();
foreach (var line in lines)
{
if (line.Contains(':'))
{
var split = line.Split(new[] { ':' }, 2);
CustomCookies[split[0].Trim()] = split[1].Trim();
}
}
}
/// <summary>
/// Builds a string containing custom headers.
/// </summary>
/// <returns>One header per line, with name and value separated by a colon</returns>
public string GetCustomHeaders()
{
var sb = new StringBuilder();
foreach (var pair in CustomHeaders)
{
sb.Append($"{pair.Key}: {pair.Value}");
if (!pair.Equals(CustomHeaders.Last())) sb.Append(Environment.NewLine);
}
return sb.ToString();
}
/// <summary>
/// Sets custom headers from an array of lines.
/// </summary>
/// <param name="lines">The lines containing the colon-separated name and value of the headers</param>
public void SetCustomHeaders(string[] lines)
{
CustomHeaders.Clear();
foreach (var line in lines)
{
if (line.Contains(':'))
{
var split = line.Split(new[] { ':' }, 2);
CustomHeaders[split[0].Trim()] = split[1].Trim();
}
}
}
/// <summary>
/// Builds a string containing multipart content.
/// </summary>
/// <returns>One content per line, with type, name and value separated by a colon</returns>
public string GetMultipartContents()
{
var sb = new StringBuilder();
foreach (var c in MultipartContents)
{
sb.Append($"{c.Type.ToString().ToUpper()}: {c.Name}: {c.Value}");
if (!c.Equals(MultipartContents.Last())) sb.Append(Environment.NewLine);
}
return sb.ToString();
}
/// <summary>
/// Sets multipart contents from an array of lines.
/// </summary>
/// <param name="lines">The lines containing the colon-separated type, name and value of the multipart contents</param>
public void SetMultipartContents(string[] lines)
{
MultipartContents.Clear();
foreach(var line in lines)
{
try
{
var split = line.Split(new[] { ':' }, 3);
MultipartContents.Add(new MultipartContent() {
Type = (MultipartContentType)Enum.Parse(typeof(MultipartContentType), split[0].Trim(), true),
Name = split[1].Trim(),
Value = split[2].Trim()
});
}
catch { }
}
}
#endregion
private MyHttpContent MapMultipartContent(MultipartContent mpc, LSGlobals ls)
{
switch (mpc.Type)
{
case MultipartContentType.String:
return new StringHttpContent(
ReplaceValues(mpc.Name, ls),
ReplaceValues(mpc.Value, ls),
string.IsNullOrEmpty(mpc.ContentType) ? "text/plain" : ReplaceValues(mpc.ContentType, ls));
case MultipartContentType.File:
return new FileHttpContent(
ReplaceValues(mpc.Name, ls),
ReplaceValues(mpc.Value, ls),
string.IsNullOrEmpty(mpc.ContentType) ? "text/plain" : ReplaceValues(mpc.ContentType, ls));
}
throw new NotSupportedException();
}
}
/// <summary>
/// The types of request that can be performed.
/// </summary>
public enum RequestType
{
Standard,
BasicAuth,
Multipart,
Raw
}
/// <summary>
/// The available types of multipart contents.
/// </summary>
public enum MultipartContentType
{
String,
File
}
/// <summary>
/// The type of data expected inside the HTTP response.
/// </summary>
public enum ResponseType
{
String,
File,
Base64String
}
/// <summary>
/// Represents a Multipart Content
/// </summary>
public struct MultipartContent
{
public MultipartContentType Type { get; set; }
public string Name { get; set; }
public string Value { get; set; }
public string ContentType { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using BlazorFourInARow.Common.Models;
namespace BlazorFourInARow.BusinessLogic
{
public interface ICurrentGameStateProvider
{
Task<GameState> GetCurrentGameStateAsync();
}
}
|
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using OneFitnessVue.Common;
using OneFitnessVue.Common.Notification;
using OneFitnessVue.Data.GeneralSetting.Queries;
using OneFitnessVue.Data.Reporting.Command;
using OneFitnessVue.Data.Reporting.Queries;
using OneFitnessVue.Model.Reporting;
using OneFitnessVue.ViewModel.MemberRegistration;
using OneFitnessVue.Web.Filters;
namespace OneFitnessVue.Web.Areas.Service.Controllers
{
[Area("Service")]
[AuthorizeUser]
public class ReceiptController : Controller
{
private readonly IGeneralSettingQueries _generalSettingQueries;
private readonly IReportingQueries _reportingQueries;
private readonly IReportingCommand _reportingCommand;
private readonly INotificationService _notificationService;
public ReceiptController(IGeneralSettingQueries generalSettingQueries,
IReportingQueries reportingQueries,
IReportingCommand reportingCommand,
INotificationService notificationService
)
{
_generalSettingQueries = generalSettingQueries;
_reportingQueries = reportingQueries;
_reportingCommand = reportingCommand;
_notificationService = notificationService;
}
[HttpGet]
public IActionResult Generate(string memberId, string paymentId)
{
if (!Regex.IsMatch(paymentId, "^[0-9]*$"))
{
_notificationService.DangerNotification("Message", "Some Thing Went Wrong !");
return RedirectToAction("Dashboard", "Dashboard");
}
if (!Regex.IsMatch(memberId, "^[0-9]*$"))
{
_notificationService.DangerNotification("Message", "Some Thing Went Wrong !");
return RedirectToAction("Dashboard", "Dashboard");
}
var recepitDetails = _generalSettingQueries.GetRecepitDetails(memberId, paymentId);
var userid = HttpContext.Session.GetInt32(AllSessionKeys.UserId);
var receiptViewModel = new ReceiptViewModel()
{
GeneralSettings = _generalSettingQueries.GetActiveGeneralSettings(),
RecepitDetails = recepitDetails,
InvoiceNo = recepitDetails.InvoiceNo,
InvoiceDate = DateTime.Now.ToString("dd/MM/yyyy")
};
var receiptHistoryModel = new ReceiptHistoryModel()
{
InvoiceNo = recepitDetails.InvoiceNo,
CreatedOn = DateTime.Now,
MemberNo = recepitDetails.MemberNo,
CreatedBy = userid,
ReceiptHistoryId = 0
};
_reportingCommand.SaveReceiptHistory(receiptHistoryModel);
return View(receiptViewModel);
}
}
}
|
using AutoMapper;
using MediatR;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using VoipProjectEntities.Application.Contracts.Persistence;
using VoipProjectEntities.Application.Exceptions;
using VoipProjectEntities.Application.Responses;
using VoipProjectEntities.Domain.Entities;
namespace VoipProjectEntities.Application.Features.DeviceAgents.Commands.UpdateDeviceAgent
{
public class UpdateDeviceAgentCommandHandler : IRequestHandler<UpdateDeviceAgentCommand, Response<Guid>>
{
private readonly IDeviceAgentRepository _deviceAgentRepository;
private readonly IMapper _mapper;
public UpdateDeviceAgentCommandHandler(IMapper mapper, IDeviceAgentRepository deviceAgentRepository)
{
_mapper = mapper;
_deviceAgentRepository = deviceAgentRepository;
}
public async Task<Response<Guid>> Handle(UpdateDeviceAgentCommand request, CancellationToken cancellationToken)
{
var deviceAgentToUpdate = await _deviceAgentRepository.GetByIdAsync(request.DeviceAgentId);
if (deviceAgentToUpdate == null)
{
throw new NotFoundException(nameof(DeviceAgent), request.DeviceAgentId);
}
var validator = new UpdateDeviceAgentCommandValidator();
var validationResult = await validator.ValidateAsync(request);
if (validationResult.Errors.Count > 0)
throw new ValidationException(validationResult);
_mapper.Map(request, deviceAgentToUpdate, typeof(UpdateDeviceAgentCommand), typeof(DeviceAgent));
await _deviceAgentRepository.UpdateAsync(deviceAgentToUpdate);
return new Response<Guid>(request.DeviceAgentId, "Updated successfully ");
}
}
}
|
//MIT, 2016-present, WinterDev
using System;
using System.Collections.Generic;
namespace PixelFarm.Drawing.WinGdi
{
class BufferBitmapStore
{
Stack<System.Drawing.Bitmap> _bmpStack = new Stack<System.Drawing.Bitmap>();
public BufferBitmapStore(int w, int h)
{
this.Width = w;
this.Height = h;
}
public int Width { get; private set; }
public int Height { get; private set; }
public System.Drawing.Bitmap GetFreeBmp()
{
if (_bmpStack.Count > 0)
{
return _bmpStack.Pop();
}
else
{
return new System.Drawing.Bitmap(Width, Height);
}
}
public void RelaseBmp(System.Drawing.Bitmap bmp)
{
_bmpStack.Push(bmp);
}
}
} |
using System;
using System.Collections.Generic;
namespace ECS
{
public class EntityBuilder
{
public static EntityBuilder Default = new EntityBuilder();
public EntityBuilder AddComponent<T>(T t) where T: struct
{
return this;
}
public void Build(World world)
{
}
}
} |
namespace AmbientSounds.Constants
{
public class IapConstants
{
public const string MsStoreAmbiePlusId = "ambieplus";
}
}
|
using System;
namespace Mocoding.Ofx.Client.Exceptions
{
class OfxResponseException : Exception
{
public OfxResponseException(string message)
: base(message)
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Google.Apis.Drive.v3;
using Google.Apis.Drive.v3.Data;
using DropNet;
public class Navigation
{
private DriveService service;
private DropNetClient dropClient;
public Navigation(DriveService service)
{
this.service = service;
}
public Navigation(DropNetClient dropClient)
{
this.dropClient = dropClient;
}
public IList<File> DriveNavigate(string parent)
{
string search, s1 = "'", s2 = "' in parents and trashed = false";
search = s1 + parent + s2;
return GetDriveFiles(search);
}
private IList<File> GetDriveFiles(string search)
{
FilesResource.ListRequest listRequest = service.Files.List();
if (search != null)
{
listRequest.Q = search;
}
else
{
listRequest.Q = "'root' in parents and trashed = false";
}
listRequest.Fields = "files(id,mimeType,modifiedTime,name,size),kind,nextPageToken";
IList<File> files = listRequest.Execute().Files;
return files;
}
public DropNet.Models.MetaData DropNavigate()
{
return GetDropFiles();
}
private DropNet.Models.MetaData GetDropFiles()
{
return dropClient.GetMetaData(null, true);
}
}
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
// the core npc script. implements a number of states for an npc actor
public class npcScript : MonoBehaviour {
public enum npcState
{
invalid = -1,
none = 0,
idle = 1,
patrol = 2,
turnToPlayer = 3,
InteractWithPlayer = 4,
Celebrate = 5,
Disappointed = 6,
startPatrol = 7,
pause = 8
};
private npcState state;
public bool showPath;
public npcDecisionMgr decisionMgr;
public splineMgr path;
// Use this for initialization
void Start () {
SetState (npcState.idle);
if (path != null)
path.computeDebugPath();
if (decisionMgr != null)
decisionMgr.init();
SetState(npcState.startPatrol);
}
public void SetState(npcState newState)
{
// things to do when leaving state and entering s
switch(newState)
{
case(npcState.idle):
{
break;
}
case(npcState.Celebrate):
{
break;
}
case(npcState.Disappointed):
{
path.SetPlaybackMode(splineMgr.ePlaybackMode.paused);
break;
}
case(npcState.InteractWithPlayer):
{
break;
}
case(npcState.startPatrol):
{
if (path != null)
{
path.HeadObj = this.gameObject;
path.SetPlaybackMode(splineMgr.ePlaybackMode.paused);
path.reset();
}
break;
}
case(npcState.patrol):
{
path.HeadObj = this.gameObject;
path.SetPlaybackMode(splineMgr.ePlaybackMode.loop);
break;
}
case(npcState.pause):
{
path.HeadObj = this.gameObject;
path.SetPlaybackMode(splineMgr.ePlaybackMode.paused);
break;
}
case(npcState.turnToPlayer):
{
path.SetPlaybackMode (splineMgr.ePlaybackMode.none);
break;
}
case(npcState.none):
{
break;
}
case(npcState.invalid):
{
break;
}
}
state = newState;
}
// Update is called once per frame
void Update ()
{
float distanceToHero = 999.0f;
GameObject player = GameObject.Find ("Player");
if (player)
{
Vector3 v = player.transform.position - this.transform.position;
distanceToHero = v.magnitude;
}
// things to do each tick of state
switch(state)
{
case(npcState.idle):
{
break;
}
case(npcState.Celebrate):
{
break;
}
case(npcState.Disappointed):
{
break;
}
case(npcState.InteractWithPlayer):
{
break;
}
case(npcState.patrol):
{
this.transform.LookAt(path.TargetObj.transform.position);
break;
}
case(npcState.turnToPlayer):
{
this.transform.LookAt (player.transform.position);
break;
}
}
//DispatchInteractions();
if (decisionMgr != null)
decisionMgr.eval ();
// enable or disable lineRenderer for path
this.GetComponent<LineRenderer>().enabled = showPath;
}
}
|
// <copyright file="TextureConverterService.cs" company="natsnudasoft">
// Copyright (c) Adrian John Dunstan. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
namespace Natsnudasoft.EgamiFlowScreensaver
{
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Microsoft.Xna.Framework.Graphics;
using Natsnudasoft.NatsnudaLibrary;
using ImageLockMode = System.Drawing.Imaging.ImageLockMode;
using PixelFormat = System.Drawing.Imaging.PixelFormat;
using SystemBitmap = System.Drawing.Bitmap;
using SystemPoint = System.Drawing.Point;
using SystemRectangle = System.Drawing.Rectangle;
/// <summary>
/// Provides methods for converting to and from textures.
/// </summary>
/// <seealso cref="ITextureConverterService" />
public class TextureConverterService : ITextureConverterService
{
private const int DefaultImageSize = 2048;
private readonly IGraphicsDeviceService graphicsDeviceService;
private readonly int maxWidth;
private readonly int maxHeight;
/// <summary>
/// Initializes a new instance of the <see cref="TextureConverterService"/> class.
/// </summary>
/// <param name="graphicsDeviceService">The graphics device service to use to help create
/// instances of <see cref="Texture2D"/>.</param>
/// <exception cref="ArgumentNullException"><paramref name="graphicsDeviceService"/> is
/// <see langword="null"/>.</exception>
public TextureConverterService(IGraphicsDeviceService graphicsDeviceService)
: this(graphicsDeviceService, DefaultImageSize, DefaultImageSize)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="TextureConverterService"/> class.
/// </summary>
/// <param name="graphicsDeviceService">The graphics device service to use to help create
/// instances of <see cref="Texture2D"/>.</param>
/// <param name="maxWidth">The maximum width that a single texture converted by this
/// service can be. Images larger than this will be tiled to multiple textures.</param>
/// <param name="maxHeight">The maximum height that a single texture converted by this
/// service can be. Images larger than this will be tiled to multiple textures.</param>
/// <exception cref="ArgumentNullException"><paramref name="graphicsDeviceService"/> is
/// <see langword="null"/>.</exception>
public TextureConverterService(
IGraphicsDeviceService graphicsDeviceService,
int maxWidth,
int maxHeight)
{
ParameterValidation.IsNotNull(graphicsDeviceService, nameof(graphicsDeviceService));
this.graphicsDeviceService = graphicsDeviceService;
this.maxWidth = maxWidth;
this.maxHeight = maxHeight;
}
/// <inheritdoc/>
/// <exception cref="ArgumentNullException"><paramref name="bitmap"/> is
/// <see langword="null"/>.</exception>
/// <exception cref="Exception">The operation failed for an unknown reason.</exception>
/// <exception cref="InvalidOperationException">The specified bitmap is too large. Use
/// <see cref="FromLargeBitmap"/> instead.
/// </exception>
public Texture2D FromBitmap(SystemBitmap bitmap)
{
ParameterValidation.IsNotNull(bitmap, nameof(bitmap));
if (bitmap.Width > this.maxWidth || bitmap.Height > this.maxHeight)
{
throw new InvalidOperationException("The specified bitmap is too large.");
}
return this.FromBitmapArea(bitmap, new SystemRectangle(SystemPoint.Empty, bitmap.Size));
}
/// <inheritdoc/>
/// <exception cref="ArgumentNullException"><paramref name="bitmap"/> is
/// <see langword="null"/>.</exception>
/// <exception cref="Exception">The operation failed for an unknown reason.</exception>
public TiledTexture2D FromLargeBitmap(SystemBitmap bitmap)
{
ParameterValidation.IsNotNull(bitmap, nameof(bitmap));
var x = 0;
var y = 0;
var width = bitmap.Width;
var height = bitmap.Height;
var tiledTextureSegments = new List<TiledTexture2DSegment>();
while (y < height)
{
while (x < width)
{
var segmentWidth = Math.Min(this.maxWidth, width - x);
var segmentHeight = Math.Min(this.maxHeight, height - y);
var segmentArea = new SystemRectangle(x, y, segmentWidth, segmentHeight);
var segmentTexture = this.FromBitmapArea(bitmap, segmentArea);
#pragma warning disable CC0022 // Should dispose object
tiledTextureSegments.Add(new TiledTexture2DSegment(
segmentTexture,
segmentArea.ToGameRectangle()));
#pragma warning restore CC0022 // Should dispose object
x += this.maxWidth;
}
x = 0;
y += this.maxWidth;
}
return new TiledTexture2D(tiledTextureSegments, width, height);
}
private Texture2D FromBitmapArea(SystemBitmap bitmap, SystemRectangle area)
{
var texture = new Texture2D(
this.graphicsDeviceService.GraphicsDevice,
area.Width,
area.Height,
false,
SurfaceFormat.Bgra32);
try
{
var data = bitmap.LockBits(
area,
ImageLockMode.ReadOnly,
PixelFormat.Format32bppPArgb);
var bytes = new byte[data.Height * data.Stride];
Marshal.Copy(data.Scan0, bytes, 0, bytes.Length);
texture.SetData(bytes);
bitmap.UnlockBits(data);
}
catch
{
texture.Dispose();
throw;
}
return texture;
}
}
} |
using Domain.Helpers;
using Domain.Model;
using Domain.Serializer;
using Plugin;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace Domain.Services
{
[Serializable]
public class ModelService
{
public List<Drink> Drinks { get; private set; }
public List<SerializerHelper> Serializers { get; set; }
public ISerializer LastSerializer { get; set; }
public string LastFile { get; set; }
public ModelService()
{
Drinks = new List<Drink>();
Serializers = new List<SerializerHelper>()
{
new SerializerHelper("Binary file (*.bin)|*.bin", new BinarySerializer()),
new SerializerHelper("JSON file (*.json)|*.json", new JsonSerializer()),
new SerializerHelper("CSER file (*.cser)|*.cser", new CustomSerializer())
};
var serializersWithPlugins = LoadSerializerWithPlugins(Serializers.Select(f => f.Serializator));
Serializers.Add(new SerializerHelper("File processed by the plugin (*.fpbp)|*.fpbp",
serializersWithPlugins));
}
public void AddDrink(Drink drink)
{
Drinks.Add(drink);
}
public void AddDrinks(List<Drink> drinks)
{
Drinks.Clear();
foreach (var drink in drinks)
{
Drinks.Add(drink);
}
}
private SerializerWithPlugins LoadSerializerWithPlugins(IEnumerable<ISerializer> serializers)
{
const string DirectoryWithPlugins = "Plugins";
var pathToPlugins = Path.Combine(Environment.CurrentDirectory, DirectoryWithPlugins);
var plugins = new List<IPlugin>(PluginLoader.LoadPlugins(pathToPlugins))
{
new EmptyPlugin()
};
return new SerializerWithPlugins(serializers, plugins);
}
}
}
|
namespace Patterns.Domain
{
public class Receipt
{
public decimal Price { get; }
public decimal DiscountPrice { get; }
public Receipt(decimal price, decimal discountPrice)
{
Price = price;
DiscountPrice = discountPrice;
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace Chic.Core.Modules
{
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public class ModuleEntryAttribute : Attribute
{
private Type _type { get; set; }
public ModuleEntryAttribute(Type type)
{
_type = type;
}
public Type GetModule()
{
return _type;
}
}
}
|
using UnityEngine;
using System.Collections;
public class Raycasting : MonoBehaviour {
Camera camera;
// Use this for initialization
void Start () {
camera = GetComponent<Camera> ();
}
// Update is called once per frame
void Update () {
Ray ray = camera.ViewportPointToRay (new Vector3 (0.5F, 0.5F, 0));
RaycastHit hit;
if (Physics.Raycast (ray, out hit))
print ("im looking at" + hit.transform.name);
else
print ("im looking at nothing");
}
} |
namespace RealbizGames.Shopping
{
public enum BuyItemStatus
{
None = 0,
Processing = 1,
Fail = 2
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.IO;
namespace WindowsFormsApplication_GetTemperature
{
class GetTemMethod
{
public string GetTemMethodtemp(string city)
{
string sURL,sURL1,sURL2;
sURL1 = "https://weather.cit.api.here.com/weather/1.0/report.json?product=observation&name=";
sURL2 = "&app_id=DemoAppId01082013GAL&app_code=AJKnXv84fjrb0KIHawS0Tg";
sURL = sURL1 + city + sURL2;
WebRequest wrGETURL;
wrGETURL = WebRequest.Create(sURL);
WebProxy myProxy = new WebProxy("myproxy", 80);
myProxy.BypassProxyOnLocal = true;
wrGETURL.Proxy = WebProxy.GetDefaultProxy();
Stream objStream;
objStream = wrGETURL.GetResponse().GetResponseStream();
StreamReader objReader = new StreamReader(objStream);
string sLine = "";
int start = 0;
int end = 0;
//int i = 0;
sLine = objReader.ReadToEnd();
start = sLine.LastIndexOf(",\"temperature\":\""); // ,"temperature":" ,\"temperature\":\"
sLine = sLine.Substring(start + 16);
end = sLine.LastIndexOf("\",\"tem");
sLine = sLine.Substring(0, end); // \",\"tem
return sLine;
}
}
}
|
namespace DockerSdk.Registries.Dto
{
internal class AuthResponse
{
public string? IdentityToken { get; set; }
public string Status { get; set; } = null!;
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using SoulsFormats;
public class MSB2MapPiecePart : MSB2Part
{
[AddComponentMenu("Dark Souls 2/Parts/Map Piece")]
/// <summary>
/// Unknown.
/// </summary>
public short UnkT00;
/// <summary>
/// Unknown.
/// </summary>
public short UnkT02;
public override void SetPart(MSB2.Part bpart)
{
var part = (MSB2.Part.MapPiece)bpart;
setBasePart(part);
UnkT00 = part.UnkT00;
UnkT02 = part.UnkT02;
}
public override MSB2.Part Serialize(GameObject parent)
{
var part = new MSB2.Part.MapPiece();
_Serialize(part, parent);
part.UnkT00 = UnkT00;
part.UnkT02 = UnkT02;
return part;
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.Json.Serialization;
using Newtonsoft.Json;
namespace ImooseApiClient.Models
{
public class ServerTime
{
[JsonProperty("unix_time")]
public long UnixTime { get; set; }
[JsonProperty("unix_time_ms")]
public long UnixTimeMs { get; set; }
[JsonProperty("rfc1123")]
public string Rfc1123 { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RequestService;
namespace RequestServiceTest
{
public class RequestServiceHost : ServiceBaseCustom
{
public void Start(string[] args)
{
base.OnStart(args);
}
public new void Stop()
{
base.OnStop();
}
public RequestServiceHost()
{
this.ServiceName = "RequestService";
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Newtonsoft.Json.Linq;
namespace BMap.NET.WindowsForm
{
/// <summary>
/// 导航路线起点/终点位置建议项
/// </summary>
partial class BPlacesSuggestionItem : UserControl
{
public event EndPointSelectedEventHandler EndPointSelected;
private JObject _dataSource;
/// <summary>
/// 位置数据源
/// </summary>
public JObject DataSource
{
get
{
return _dataSource;
}
set
{
_dataSource = value;
if (_dataSource != null) //解析 具体json格式参见api文档
{
lblName.Text = (string)_dataSource["name"];
lblAddress.Text = (string)_dataSource["address"];
if (Type == PointType.RouteEnd)
{
lblSelect.Text = "设为终点";
}
else
{
lblSelect.Text = "设为起点";
}
lblIndex.Text = Index.ToString();
}
}
}
/// <summary>
/// 序号
/// </summary>
public int Index
{
get;
set;
}
/// <summary>
/// 位置类型
/// </summary>
public PointType Type
{
get;
set;
}
/// <summary>
/// 构造方法
/// </summary>
public BPlacesSuggestionItem()
{
InitializeComponent();
}
/// <summary>
/// 鼠标进入
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void label1_MouseEnter(object sender, EventArgs e)
{
BackColor = Color.FromArgb(235, 241, 251);
}
/// <summary>
/// 鼠标离开
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void label1_MouseLeave(object sender, EventArgs e)
{
BackColor = Color.White;
}
/// <summary>
/// 选择
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void lblSelect_Click(object sender, EventArgs e)
{
if (EndPointSelected != null)
{
EndPointSelected(lblName.Text, Type);
}
}
/// <summary>
/// 重绘
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void BPlacesSuggestionItem_Paint(object sender, PaintEventArgs e)
{
}
}
}
|
using System;
using System.Threading.Tasks;
namespace ModularMonolith.Shared.Infrastructure.Modules
{
public sealed class ModuleBroadcastRegistration
{
public Type TargetType { get; }
public Func<object, Task> Handle { get; }
public string Key => TargetType.Name;
public ModuleBroadcastRegistration(Type targetType, Func<object, Task> handle)
{
TargetType = targetType;
Handle = handle;
}
}
} |
namespace ShpToSql.SqlConnectionControl
{
public partial class LoadingCircle
{
public LoadingCircle()
{
InitializeComponent();
}
}
} |
using System;
using ProtoBuf;
namespace BO4E.ENUM
{
/// <summary>Unterscheidung für hoch- und niedrig-kalorisches Gas.</summary>
public enum Gasqualitaet
{
[Obsolete("This value is only a workaround for the proto3 syntax generation. You shouldn't actually use it")]
#pragma warning disable CS0618 // Type or member is obsolete
[ProtoEnum(Name = nameof(Gasqualitaet) + "_" + nameof(ZERO))]
#pragma warning restore CS0618 // Type or member is obsolete
[Newtonsoft.Json.JsonIgnore]
[System.Text.Json.Serialization.JsonIgnore]
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
ZERO = 0,
#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member
/// <summary>High Caloric Gas</summary>
H_GAS = 1,
/// <summary>Low Caloric Gas</summary>
L_GAS = 2,
/// <inheritdoc cref="H_GAS" />
[Newtonsoft.Json.JsonIgnore]
[System.Text.Json.Serialization.JsonIgnore]
HGAS = 1, // do not remove, they're needed as workaround for bad sap values
/// <inheritdoc cref="L_GAS" />
[Newtonsoft.Json.JsonIgnore]
[System.Text.Json.Serialization.JsonIgnore]
LGAS = 2 // do not remove, they're needed as workaround for bad sap values
}
} |
using UnityEditor;
using UnityEngine;
namespace Baum2.Editor {
public class BaumSpriteProcess : AssetPostprocessor {
private void OnPostprocessTexture(Texture2D texture) {
if( !assetPath.Contains("Assets/Art/UI/Sprites") ) {
return;
}
var importer = assetImporter as TextureImporter;
importer.textureType = TextureImporterType.Sprite;
importer.mipmapEnabled = false;
}
}
} |
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
using System;
using ICSharpCode.PythonBinding;
using ICSharpCode.SharpDevelop;
using ICSharpCode.SharpDevelop.Dom;
using IronPython.Compiler.Ast;
namespace PythonBinding.Tests.Utils
{
public static class PythonParserHelper
{
/// <summary>
/// Parses the code and returns the first statement as an assignment statement.
/// </summary>
public static AssignmentStatement GetAssignmentStatement(string code)
{
return GetFirstStatement(code) as AssignmentStatement;
}
/// <summary>
/// Parses the code and returns the first statement's expression as call expression.
/// </summary>
public static CallExpression GetCallExpression(string code)
{
ExpressionStatement expressionStatement = GetFirstStatement(code) as ExpressionStatement;
return expressionStatement.Expression as CallExpression;
}
static Statement GetFirstStatement(string code)
{
PythonParser parser = new PythonParser();
PythonAst ast = parser.CreateAst(@"snippet.py", new StringTextBuffer(code));
SuiteStatement suiteStatement = (SuiteStatement)ast.Body;
return suiteStatement.Statements[0];
}
public static ParseInformation CreateParseInfo(string code)
{
DefaultProjectContent projectContent = new DefaultProjectContent();
PythonParser parser = new PythonParser();
ICompilationUnit compilationUnit = parser.Parse(projectContent, @"C:\test.py", code);
return new ParseInformation(compilationUnit);
}
}
}
|
using Tridion.ContentManager.ContentManagement;
using Tridion.ContentManager.ContentManagement.Fields;
using Tridion.ContentManager.Templating;
using Tridion.ContentManager.Templating.Assembly;
namespace TridionTemplates
{
[TcmTemplateTitle("Render Code")]
public class RenderCode : ITemplate
{
public void Transform(Engine engine, Package package)
{
Component component = (Component)engine.GetObject(package.GetByName(Package.ComponentName));
ItemFields fields = new ItemFields(component.Content, component.Schema);
TextField code = (TextField)fields["Code"];
package.PushItem(Package.OutputName, package.CreateStringItem(ContentType.Html, code.Value));
}
}
}
|
using System.Threading.Tasks;
using PuppeteerSharp.Tests.Attributes;
using PuppeteerSharp.Xunit;
using Xunit;
using Xunit.Abstractions;
namespace PuppeteerSharp.Tests.ChromiumSpecificTests
{
[Collection(TestConstants.TestFixtureCollectionName)]
public class BrowserUrlOptionTests : PuppeteerPageBaseTest
{
public BrowserUrlOptionTests(ITestOutputHelper output) : base(output)
{
}
[PuppeteerTest("chromiumonly.spec.ts", "Puppeteer.launch |browserURL| option", "should be able to connect using browserUrl, with and without trailing slash")]
[SkipBrowserFact(skipFirefox: true)]
public async Task ShouldBeAbleToConnectUsingBrowserURLWithAndWithoutTrailingSlash()
{
var options = TestConstants.DefaultBrowserOptions();
options.Args = new string[] { "--remote-debugging-port=21222" };
var originalBrowser = await Puppeteer.LaunchAsync(options);
var browserURL = "http://127.0.0.1:21222";
var browser1 = await Puppeteer.ConnectAsync(new ConnectOptions { BrowserURL = browserURL });
var page1 = await browser1.NewPageAsync();
Assert.Equal(56, await page1.EvaluateExpressionAsync<int>("7 * 8"));
browser1.Disconnect();
var browser2 = await Puppeteer.ConnectAsync(new ConnectOptions { BrowserURL = browserURL + "/" });
var page2 = await browser2.NewPageAsync();
Assert.Equal(56, await page2.EvaluateExpressionAsync<int>("7 * 8"));
browser2.Disconnect();
await originalBrowser.CloseAsync();
}
[PuppeteerTest("chromiumonly.spec.ts", "Puppeteer.launch |browserURL| option", "should throw when using both browserWSEndpoint and browserURL")]
[SkipBrowserFact(skipFirefox: true)]
public async Task ShouldThrowWhenUsingBothBrowserWSEndpointAndBrowserURL()
{
var options = TestConstants.DefaultBrowserOptions();
options.Args = new string[] { "--remote-debugging-port=21222" };
var originalBrowser = await Puppeteer.LaunchAsync(options);
var browserURL = "http://127.0.0.1:21222";
await Assert.ThrowsAsync<PuppeteerException>(() => Puppeteer.ConnectAsync(new ConnectOptions
{
BrowserURL = browserURL,
BrowserWSEndpoint = originalBrowser.WebSocketEndpoint
}));
await originalBrowser.CloseAsync();
}
[PuppeteerTest("chromiumonly.spec.ts", "Puppeteer.launch |browserURL| option", "should throw when trying to connect to non-existing browser")]
[SkipBrowserFact(skipFirefox: true)]
public async Task ShouldThrowWhenTryingToConnectToNonExistingBrowser()
{
var options = TestConstants.DefaultBrowserOptions();
options.Args = new string[] { "--remote-debugging-port=21222" };
var originalBrowser = await Puppeteer.LaunchAsync(options);
var browserURL = "http://127.0.0.1:2122";
await Assert.ThrowsAsync<ProcessException>(() => Puppeteer.ConnectAsync(new ConnectOptions
{
BrowserURL = browserURL
}));
await originalBrowser.CloseAsync();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Build.Utilities;
using WebGAC.Core;
namespace WebGAC.MSBuild {
public class SupplyCreds : Task {
public override bool Execute() {
Core.WebGAC gac = WebGACFactory.WebGAC;
gac.CredRequestHandler = new CredentialsHelper().HandleCredentialsRequest;
gac.Resolve("Dummy.Binary.For.ForcingResolution", new Version("2.0.0.0"), null, null, "Debug",
new string[] {"Debug"});
return true;
}
}
}
|
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using Bright.Serialization;
using System.Collections.Generic;
namespace cfg.item
{
/// <summary>
/// 道具
/// </summary>
public sealed class Item : Bright.Config.BeanBase
{
public Item(ByteBuf _buf)
{
Id = _buf.ReadInt();
Name = _buf.ReadString();
MajorType = (item.EMajorType)_buf.ReadInt();
MinorType = (item.EMinorType)_buf.ReadInt();
MaxPileNum = _buf.ReadInt();
Quality = (item.EItemQuality)_buf.ReadInt();
Icon = _buf.ReadString();
IconBackgroud = _buf.ReadString();
IconMask = _buf.ReadString();
Desc = _buf.ReadString();
ShowOrder = _buf.ReadInt();
Quantifier = _buf.ReadString();
ShowInBag = _buf.ReadBool();
MinShowLevel = _buf.ReadInt();
BatchUsable = _buf.ReadBool();
ProgressTimeWhenUse = _buf.ReadFloat();
ShowHintWhenUse = _buf.ReadBool();
Droppable = _buf.ReadBool();
if(_buf.ReadBool()){ Price = _buf.ReadInt(); } else { Price = null; }
UseType = (item.EUseType)_buf.ReadInt();
if(_buf.ReadBool()){ LevelUpId = _buf.ReadInt(); } else { LevelUpId = null; }
}
public static Item DeserializeItem(ByteBuf _buf)
{
return new item.Item(_buf);
}
/// <summary>
/// 道具id
/// </summary>
public int Id { get; private set; }
public string Name { get; private set; }
public item.EMajorType MajorType { get; private set; }
public item.EMinorType MinorType { get; private set; }
public int MaxPileNum { get; private set; }
public item.EItemQuality Quality { get; private set; }
public string Icon { get; private set; }
public string IconBackgroud { get; private set; }
public string IconMask { get; private set; }
public string Desc { get; private set; }
public int ShowOrder { get; private set; }
public string Quantifier { get; private set; }
public bool ShowInBag { get; private set; }
public int MinShowLevel { get; private set; }
public bool BatchUsable { get; private set; }
public float ProgressTimeWhenUse { get; private set; }
public bool ShowHintWhenUse { get; private set; }
public bool Droppable { get; private set; }
public int? Price { get; private set; }
public item.EUseType UseType { get; private set; }
public int? LevelUpId { get; private set; }
public const int __ID__ = 2107285806;
public override int GetTypeId() => __ID__;
public void Resolve(Dictionary<string, object> _tables)
{
}
public void TranslateText(System.Func<string, string, string> translator)
{
}
public override string ToString()
{
return "{ "
+ "Id:" + Id + ","
+ "Name:" + Name + ","
+ "MajorType:" + MajorType + ","
+ "MinorType:" + MinorType + ","
+ "MaxPileNum:" + MaxPileNum + ","
+ "Quality:" + Quality + ","
+ "Icon:" + Icon + ","
+ "IconBackgroud:" + IconBackgroud + ","
+ "IconMask:" + IconMask + ","
+ "Desc:" + Desc + ","
+ "ShowOrder:" + ShowOrder + ","
+ "Quantifier:" + Quantifier + ","
+ "ShowInBag:" + ShowInBag + ","
+ "MinShowLevel:" + MinShowLevel + ","
+ "BatchUsable:" + BatchUsable + ","
+ "ProgressTimeWhenUse:" + ProgressTimeWhenUse + ","
+ "ShowHintWhenUse:" + ShowHintWhenUse + ","
+ "Droppable:" + Droppable + ","
+ "Price:" + Price + ","
+ "UseType:" + UseType + ","
+ "LevelUpId:" + LevelUpId + ","
+ "}";
}
}
}
|
namespace MS.GTA.BOTService.BusinessLibrary.Interfaces
{
using MS.GTA.BOTService.Common.Models;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
public interface IJobApplicationManager
{
Task<IList<UpcomingInterviews>> GetUpcomingInterviews(string userOid, DateTime startDateTime);
}
} |
//------------------------------------------------------------------------------
// <auto-generated />
// This file was automatically generated by the UpdateVendors tool.
//------------------------------------------------------------------------------
// dnlib: See LICENSE.txt for more info
namespace Datadog.Trace.Vendors.dnlib.PE {
/// <summary>
/// Represents an RVA (relative virtual address)
/// </summary>
internal enum RVA : uint {
}
partial class PEExtensions {
/// <summary>
/// Align up
/// </summary>
/// <param name="rva">this</param>
/// <param name="alignment">Alignment</param>
public static RVA AlignUp(this RVA rva, uint alignment) => (RVA)(((uint)rva + alignment - 1) & ~(alignment - 1));
/// <summary>
/// Align up
/// </summary>
/// <param name="rva">this</param>
/// <param name="alignment">Alignment</param>
public static RVA AlignUp(this RVA rva, int alignment) => (RVA)(((uint)rva + alignment - 1) & ~(alignment - 1));
}
}
|
using Neon.HomeControl.Components.EventsDb;
using Newtonsoft.Json;
namespace Neon.HomeControl.Components.Data
{
public class SunsetDataResultWrap
{
[JsonProperty("results")] public SunsetDataResults Results { get; set; }
}
} |
using System;
using System.ComponentModel;
namespace Chapter09
{
[Description("Listing 9.01")]
class SimpleAnonymousMethod
{
static void Main()
{
Func<string, int> returnLength;
returnLength = delegate(string text) { return text.Length; };
Console.WriteLine(returnLength("Hello"));
}
}
}
|
using System;
using System.Threading.Tasks;
using Caliburn.Micro.Xamarin.Forms;
using Xamarin.Forms;
// ReSharper disable once CheckNamespace
namespace LogoFX.Client.Mvvm.Navigation
{
/// <summary>
/// A <see cref="NavigationPageAdapter"/> decorator allowing navigation to view model by type.
/// </summary>
public class LogoFXNavigationPageAdapter : NavigationPageAdapter, ILogoFXNavigationService
{
private readonly NavigationPage _navigationPage;
/// <summary>
/// Initializes an instance of <see cref="LogoFXNavigationPageAdapter"/>
/// </summary>
/// <param name="navigationPage"></param>
public LogoFXNavigationPageAdapter(NavigationPage navigationPage)
: base(navigationPage)
{
_navigationPage = navigationPage;
}
/// <inheritdoc />
public Task NavigateToViewModelInstanceAsync<TViewModel>(TViewModel viewModel, bool animated = true)
{
Element element;
try
{
element = ViewLocator.LocateForModelType(typeof(TViewModel), null, null);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
throw;
}
var page = element as Page;
if (page == null && !(element is ContentView))
throw new NotSupportedException(
$"{element.GetType()} does not inherit from either {typeof(Page)} or {typeof(ContentView)}.");
try
{
ViewModelBinder.Bind(viewModel, element, null);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
throw;
}
if (element is ContentView view)
page = CreateContentPage(view, viewModel);
return _navigationPage.PushAsync(page, animated);
}
/// <inheritdoc />
public bool CanNavigateBack()
{
return _navigationPage.Navigation.NavigationStack.Count > 1;
}
}
} |
namespace MediatR.BackgroundService.SampleApi.BusinessLogic.Handlers.LongOperation;
/// <summary>
/// A request for the long operation. This will be ideally executed in the background
/// </summary>
public record LongOperationRequest(string Source) : IRequest<Unit>;
|
using System.Collections.Generic;
using System.IO;
using System.Linq;
using IronBlock.Blocks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace IronBlock.Tests
{
[TestClass]
public class ListsTests
{
[TestMethod]
public void Test_List_Create_With()
{
const string xml = @"
<xml xmlns=""http://www.w3.org/1999/xhtml"">
<block type=""lists_create_with"">
<mutation items=""3""></mutation>
<value name=""ADD0"">
<block type=""text"">
<field name=""TEXT"">x</field>
</block>
</value>
<value name=""ADD1"">
<block type=""text"">
<field name=""TEXT"">y</field>
</block>
</value>
<value name=""ADD2"">
<block type=""text"">
<field name=""TEXT"">z</field>
</block>
</value>
</block>
</xml>
";
var output = new Parser()
.AddStandardBlocks()
.Parse(xml)
.Evaluate();
Assert.AreEqual("x,y,z", string.Join(",", (output as IEnumerable<object>).Select(x => x.ToString())));
}
[TestMethod]
public void Test_List_Split()
{
const string xml = @"
<xml xmlns=""http://www.w3.org/1999/xhtml"">
<block type=""lists_split"">
<mutation mode=""SPLIT""></mutation>
<field name=""MODE"">SPLIT</field>
<value name=""INPUT"">
<block type=""text"">
<field name=""TEXT"">x,y,z</field>
</block>
</value>
<value name=""DELIM"">
<shadow type=""text"">
<field name=""TEXT"">,</field>
</shadow>
</value>
</block>
</xml>
";
var output = new Parser()
.AddStandardBlocks()
.Parse(xml)
.Evaluate();
Assert.AreEqual("x,y,z", string.Join(",", output as IEnumerable<object>));
}
[TestMethod]
public void Test_Lists_Join()
{
const string xml = @"
<xml xmlns=""http://www.w3.org/1999/xhtml"">
<block type=""lists_split"">
<mutation mode=""JOIN""></mutation>
<field name=""MODE"">JOIN</field>
<value name=""INPUT"">
<block type=""lists_create_with"">
<mutation items=""3""></mutation>
<value name=""ADD0"">
<block type=""text"">
<field name=""TEXT"">x</field>
</block>
</value>
<value name=""ADD1"">
<block type=""text"">
<field name=""TEXT"">y</field>
</block>
</value>
<value name=""ADD2"">
<block type=""text"">
<field name=""TEXT"">z</field>
</block>
</value>
</block>
</value>
<value name=""DELIM"">
<shadow type=""text"">
<field name=""TEXT"">,</field>
</shadow>
</value>
</block>
</xml>
";
var output = new Parser()
.AddStandardBlocks()
.Parse(xml)
.Evaluate();
Assert.AreEqual("x,y,z", output);
}
[TestMethod]
public void Test_Lists_Length()
{
const string xml = @"
<xml xmlns=""http://www.w3.org/1999/xhtml"">
<block type=""lists_length"">
<value name=""VALUE"">
<block type=""lists_split"">
<mutation mode=""SPLIT""></mutation>
<field name=""MODE"">SPLIT</field>
<value name=""INPUT"">
<block type=""text"">
<field name=""TEXT"">a,b,c</field>
</block>
</value>
<value name=""DELIM"">
<shadow type=""text"">
<field name=""TEXT"">,</field>
</shadow>
</value>
</block>
</value>
</block>
</xml>
";
var output = new Parser()
.AddStandardBlocks()
.Parse(xml)
.Evaluate();
Assert.AreEqual(3, (double)output);
}
[TestMethod]
public void Test_Lists_Repeat()
{
const string xml = @"
<xml xmlns=""http://www.w3.org/1999/xhtml"">
<block type=""lists_repeat"">
<value name=""ITEM"">
<block type=""text"">
<field name=""TEXT"">hello</field>
</block>
</value>
<value name=""NUM"">
<shadow type=""math_number"">
<field name=""NUM"">3</field>
</shadow>
</value>
</block>
</xml>
";
var output = new Parser()
.AddStandardBlocks()
.Parse(xml)
.Evaluate();
Assert.AreEqual("hello,hello,hello", string.Join(",", (output as IEnumerable<object>).Select(x => x.ToString())));
}
[TestMethod]
public void Test_Lists_IsEmpty()
{
const string xml = @"
<xml xmlns=""http://www.w3.org/1999/xhtml"">
<block type=""lists_isEmpty"">
<value name=""VALUE"">
<block type=""lists_create_with"">
<mutation items=""0""></mutation>
</block>
</value>
</block>
</xml>
";
var output = new Parser()
.AddStandardBlocks()
.Parse(xml)
.Evaluate();
Assert.IsTrue((bool)output);
}
[TestMethod]
public void Test_Lists_IndexOf()
{
const string xml = @"
<xml xmlns=""http://www.w3.org/1999/xhtml"">
<variables></variables>
<block type=""lists_indexOf"">
<field name=""END"">FIRST</field>
<value name=""VALUE"">
<block type=""lists_split"">
<mutation mode=""SPLIT""></mutation>
<field name=""MODE"">SPLIT</field>
<value name=""INPUT"">
<block type=""text"">
<field name=""TEXT"">foo,bar,baz</field>
</block>
</value>
<value name=""DELIM"">
<shadow type=""text"">
<field name=""TEXT"">,</field>
</shadow>
</value>
</block>
</value>
<value name=""FIND"">
<block type=""text"">
<field name=""TEXT"">bar</field>
</block>
</value>
</block>
</xml>
";
var output = new Parser()
.AddStandardBlocks()
.Parse(xml)
.Evaluate();
Assert.AreEqual(2, (int)output);
}
[TestMethod]
public void Test_Lists_GetIndex()
{
const string xml = @"
<xml xmlns=""http://www.w3.org/1999/xhtml"">
<block type=""lists_getIndex"">
<mutation statement=""false"" at=""true""></mutation>
<field name=""MODE"">GET</field>
<field name=""WHERE"">FROM_START</field>
<value name=""VALUE"">
<block type=""lists_split"">
<mutation mode=""SPLIT""></mutation>
<field name=""MODE"">SPLIT</field>
<value name=""INPUT"">
<block type=""text"">
<field name=""TEXT"">foo,bar,baz</field>
</block>
</value>
<value name=""DELIM"">
<shadow type=""text"">
<field name=""TEXT"">,</field>
</shadow>
</value>
</block>
</value>
<value name=""AT"">
<block type=""math_number"">
<field name=""NUM"">2</field>
</block>
</value>
</block>
</xml>
";
var output = new Parser()
.AddStandardBlocks()
.Parse(xml)
.Evaluate();
Assert.AreEqual("bar", (string)output);
}
}
}
|
// Copyright(c) 2017 Google 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.
using CommandLine;
using Google.Cloud.Firestore;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Threading;
using System.Linq;
namespace GoogleCloudSamples
{
public class DataModel
{
public static string Usage = @"Usage:
C:\> dotnet run command YOUR_PROJECT_ID
Where command is one of
document-ref
collection-ref
document-path-ref
subcollection-ref
";
private static void DocumentRef(string project)
{
FirestoreDb db = FirestoreDb.Create(project);
// [START fs_document_ref]
DocumentReference documentRef = db.Collection("users").Document("alovelace");
// [END fs_document_ref]
}
private static void CollectionRef(string project)
{
FirestoreDb db = FirestoreDb.Create(project);
// [START fs_collection_ref]
CollectionReference collectionRef = db.Collection("users");
// [END fs_collection_ref]
}
private static void DocumentPathRef(string project)
{
FirestoreDb db = FirestoreDb.Create(project);
// [START fs_document_path_ref]
DocumentReference documentRef = db.Document("users/alovelace");
// [END fs_document_path_ref]
}
private static void SubcollectionRef(string project)
{
FirestoreDb db = FirestoreDb.Create(project);
// [START fs_subcollection_ref]
DocumentReference documentRef = db
.Collection("Rooms").Document("RoomA")
.Collection("Messages").Document("Message1");
// [END fs_subcollection_ref]
}
public static void Main(string[] args)
{
if (args.Length < 2)
{
Console.Write(Usage);
return;
}
string command = args[0].ToLower();
string project = string.Join(" ",
new ArraySegment<string>(args, 1, args.Length - 1));
switch (command)
{
case "document-ref":
DocumentRef(project);
break;
case "collection-ref":
CollectionRef(project);
break;
case "document-path-ref":
DocumentPathRef(project);
break;
case "subcollection-ref":
SubcollectionRef(project);
break;
default:
Console.Write(Usage);
return;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data.Entity.ModelConfiguration;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations.Schema;
namespace H1.Model.Entity.Configuration
{
public class PacienteConfiguration : EntityTypeConfiguration<Paciente>
{
public PacienteConfiguration()
{
ToTable("[@FLAGCADPAC]")
.HasKey(t => t.Code);
//Property(u => u.Code).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
}
}
}
|
using System.Collections.Generic;
namespace TxTraktor.Extension
{
public interface IExtension
{
string Name { get; }
IEnumerable<Dictionary<string, string>> Process(string query);
}
} |
/*
* Destroy gameobject when its renderer is no longer visible
* @ Max Perraut '20
*/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace WSoft.Camera
{
public class DestroyOutOfSight : MonoBehaviour
{
[Tooltip("A renderer that displays the object.")]
public Renderer view;
[Tooltip("How long after becoming invisible should this be destroyed?")]
public float delay = 0;
private float lastTimeVisible = 0;
/// <summary>
/// Gets all of the renderers on the object again, in the event that they change.
/// </summary>
public void ResetRenderers()
{
//default view to first one found on object
view = GetComponentInChildren<Renderer>();
}
public void Update()
{
if (view != null && view.isVisible)
{
lastTimeVisible = Time.time;
}
else if (Time.time > lastTimeVisible + delay)
{
Destroy(gameObject);
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataProcessor.DataModels
{
public class ClassOccupanyDetails
{
public int IsClassOccupied { get; set; }//0 for false and 1 for true
public int ClassTotalCapacity { get; set; }
public int ClassOccupiedValue { get; set; }
public int ClassOccupanyRemaining
{
get
{
return ClassTotalCapacity - ClassOccupiedValue;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using MarketingBox.Redistribution.Service.Domain.Models;
using MarketingBox.Redistribution.Service.Grpc;
using MarketingBox.Redistribution.Service.Grpc.Models;
using MarketingBox.Redistribution.Service.Storage;
using MarketingBox.Sdk.Common.Extensions;
using MarketingBox.Sdk.Common.Models.Grpc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
namespace MarketingBox.Redistribution.Service.Services
{
public class RegistrationImporter : IRegistrationImporter
{
private readonly ILogger<RegistrationImporter> _logger;
private readonly FileStorage _fileStorage;
public RegistrationImporter(ILogger<RegistrationImporter> logger, FileStorage fileStorage)
{
_logger = logger;
_fileStorage = fileStorage;
}
public async Task<Response<ImportResponse>> ImportAsync(ImportRequest request)
{
try
{
_logger.LogInformation(
$"RegistrationImporter.ImportAsync receive request {JsonConvert.SerializeObject(request)}");
var registrationsFile = new RegistrationsFile()
{
CreatedAt = DateTime.UtcNow,
CreatedBy = request.UserId,
File = request.RegistrationsFile,
TenantId = request.TenantId
};
await _fileStorage.Save(registrationsFile);
return new Response<ImportResponse>()
{
Status = ResponseStatus.Ok,
Data = new ImportResponse()
{
FileId = registrationsFile.Id
}
};
}
catch (Exception ex)
{
_logger.LogError(ex, ex.Message);
return ex.FailedResponse<ImportResponse>();
}
}
public async Task<Response<IReadOnlyCollection<RegistrationsFile>>> GetRegistrationFilesAsync(
GetFilesRequest request)
{
try
{
var (files, total) = await _fileStorage.Search(request);
return new Response<IReadOnlyCollection<RegistrationsFile>>()
{
Status = ResponseStatus.Ok,
Data = files,
Total = total
};
}
catch (Exception ex)
{
_logger.LogError(ex, ex.Message);
return ex.FailedResponse<IReadOnlyCollection<RegistrationsFile>>();
}
}
public async Task<Response<IReadOnlyCollection<RegistrationFromFile>>> GetRegistrationsFromFileAsync(
GetRegistrationsFromFileRequest request)
{
try
{
var (registrationsFiles,total) = await _fileStorage.ParseFile(request);
return new Response<IReadOnlyCollection<RegistrationFromFile>>()
{
Status = ResponseStatus.Ok,
Data = registrationsFiles,
Total = total
};
}
catch (Exception ex)
{
_logger.LogError(ex, ex.Message);
return ex.FailedResponse<IReadOnlyCollection<RegistrationFromFile>>();
}
}
}
} |
using UnityEngine;
using System.Collections;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Xml;
using System.IO;
using ProtoBuf;
using update_protocol_v3;
namespace Holojam
{
public class MasterStream : Singleton<MasterStream>
{
private class OtherMarker
{
public Vector3 pos;
}
private class LiveObjectStorage
{
public Vector3 pos;
public Quaternion rot;
public int button_bits;
public List<Vector2> axis_buttons;
// TODO: Handle extra data
}
private const int BLACK_BOX_CLIENT_PORT = 1611;
private Vector3 DEFAULT_POS_VEC;
private Quaternion DEFAULT_ROT_QUAT;
private int nBytesReceived;
private bool stopReceive;
private IPEndPoint ipEndPoint;
private System.Threading.Thread thread = null;
private Socket socket;
private byte[] b1;
private byte[] b2;
private byte[] b3;
private MemoryStream b1ms;
private MemoryStream b2ms;
private float accum;
private int nPackets;
private int nFrames;
private UnityEngine.Object lock_object;
private long lastLoadedFrame;
private byte[] lastLoadedBuffer;
private MemoryStream lastLoadedBufferMS;
private Dictionary<string, LiveObjectStorage> labelToLiveObject;
public void Start() {
lock_object = new UnityEngine.Object();
Application.runInBackground = true;
Application.targetFrameRate = -1;
DEFAULT_POS_VEC = new Vector3 (0, 0, 0);
DEFAULT_ROT_QUAT = new Quaternion (0, 0, 0, 0);
labelToLiveObject = new Dictionary<string, LiveObjectStorage>();
accum = 0;
nPackets = 0;
nFrames = 0;
// ~65KB buffer sizes
b1 = new byte[65507];
b2 = new byte[65507];
b1ms = new MemoryStream(b1);
b2ms = new MemoryStream(b2);
thread = new System.Threading.Thread(ThreadRun);
thread.Start();
}
// Handle new thread data / invoke Unity routines outside of the socket thread.
public void Update() {
accum += Time.deltaTime;
float round_accum = (float)Math.Floor(accum);
if (round_accum > 0) {
accum -= round_accum;
// print ("FPS: " + ((float)nFrames / round_accum).ToString());
print ("packets per second: " + ((float)nPackets / round_accum).ToString());
nPackets = 0;
nFrames = 0;
}
nFrames++;
}
public Vector3 getLiveObjectPosition(string name) {
LiveObjectStorage o;
lock (lock_object) {
if (!labelToLiveObject.TryGetValue (name, out o)) {
//print ("Body not found: " + name);
return DEFAULT_POS_VEC;
}
}
return o.pos;
}
public Quaternion getLiveObjectRotation(string name) {
LiveObjectStorage o;
lock (lock_object) {
if (!labelToLiveObject.TryGetValue (name, out o)) {
//print ("Body not found: " + name);
return DEFAULT_ROT_QUAT;
}
}
return o.rot;
}
public int getLiveObjectButtonBits(string name) {
LiveObjectStorage o;
lock (lock_object) {
if (!labelToLiveObject.TryGetValue (name, out o)) {
//print ("Body not found: " + name);
return 0;
}
}
return o.button_bits;
}
public Vector2 getLiveObjectAxisButton(string name, int index) {
LiveObjectStorage o;
lock (lock_object) {
if (!labelToLiveObject.TryGetValue (name, out o)) {
//print ("Body not found: " + name);
return Vector2.zero;
}
}
return o.axis_buttons[index];
}
// This thread handles incoming NatNet packets.
private void ThreadRun ()
{
stopReceive = false;
Socket socket =new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
ipEndPoint = new IPEndPoint (IPAddress.Any, BLACK_BOX_CLIENT_PORT);
//Debug.Log("prebind");
socket.Bind (ipEndPoint);
//Debug.Log("bind");
MulticastOption mo = new MulticastOption (IPAddress.Parse ("224.1.1.1"));
socket.SetSocketOption (SocketOptionLevel.IP, SocketOptionName.AddMembership, mo);
nBytesReceived = 0;
lastLoadedBuffer = b1;
lastLoadedBufferMS = b1ms;
lastLoadedFrame = 0;
byte[] newPacketBuffer = b2;
MemoryStream newPacketBufferMS = b2ms;
long newPacketFrame = 0;
byte[] tempBuffer;
MemoryStream tempBufferMS;
while (true) {
//Debug.Log("preRECV");
nBytesReceived = socket.Receive(newPacketBuffer);
//Debug.Log("RECV");
nPackets++;
newPacketBufferMS.Position = 0;
//Debug.Log ("Deserializing data...");
update_protocol_v3.Update update = Serializer.Deserialize<update_protocol_v3.Update>(new MemoryStream(newPacketBuffer, 0, nBytesReceived));
//Debug.Log ("Data deserialized. Received update of type " + update.label);
newPacketFrame = update.mod_version;
if(newPacketFrame > lastLoadedFrame) {
// Swap the buffers and reset the positions.
lastLoadedBufferMS.Position = 0;
newPacketBufferMS.Position = 0;
tempBuffer = lastLoadedBuffer;
tempBufferMS = lastLoadedBufferMS;
lastLoadedBuffer = newPacketBuffer;
lastLoadedBufferMS = newPacketBufferMS;
newPacketBuffer = tempBuffer;
newPacketBufferMS = tempBufferMS;
lastLoadedFrame = newPacketFrame;
for (int j = 0; j < update.live_objects.Count; j++) {
LiveObject or = update.live_objects[j];
string label = or.label;
if (label == "marker") {
Debug.Log ("marker at " + or.x + ", " + or.y + ", " + or.z);
}
LiveObjectStorage ow;
lock (lock_object) {
if (!labelToLiveObject.TryGetValue(label, out ow)) {
ow = new LiveObjectStorage();
labelToLiveObject[label] = ow;
} else {
ow = labelToLiveObject[label];
}
if (update.lhs_frame) {
ow.pos = new Vector3(-(float)or.x, (float)or.y, (float)or.z);
ow.rot = new Quaternion(-(float)or.qx, (float)or.qy, (float)or.qz, -(float)or.qw);
} else {
ow.pos = new Vector3((float)or.x, (float)or.y, (float)or.z);
ow.rot = new Quaternion((float)or.qx, (float)or.qy, (float)or.qz, (float)or.qw);
}
ow.button_bits = or.button_bits;
}
}
}
if (stopReceive) {
break;
}
}
}
private void OnDestroy ()
{
stopReceive = true;
}
}
} |
// -----------------------------------------------------------------------
// <copyright file="IPaymentProcessor.cs" company="Rare Crowds Inc">
// Copyright 2012-2013 Rare Crowds, 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.
// </copyright>
// -----------------------------------------------------------------------
namespace PaymentProcessor
{
/// <summary>Interface to encapsulate payment processing implementations.</summary>
public interface IPaymentProcessor
{
/// <summary>Gets the name of the PaymentProcessor.</summary>
string ProcessorName { get; }
/// <summary>Create a customer on the billing service.</summary>
/// <param name="billingInformationToken">A token representing the customers billing information.</param>
/// <param name="companyName">The internal name of the customer (company name).</param>
/// <returns>A customer billing id.</returns>
string CreateCustomer(string billingInformationToken, string companyName);
/// <summary>Create a customer on the billing service.</summary>
/// <param name="billingInformationToken">A token representing the customers billing information.</param>
/// <param name="customerBillingId">The billing id of the customer.</param>
/// <param name="companyName">The internal name of the customer (company name).</param>
/// <returns>A customer billing id.</returns>
string UpdateCustomer(string billingInformationToken, string customerBillingId, string companyName);
/// <summary>Charge a customer on the billing service.</summary>
/// <param name="customerBillingId">The billing id of the customer.</param>
/// <param name="chargeAmount">Amount of charge in U.S. dollars.</param>
/// <param name="chargeDescription">Description of charge.</param>
/// <returns>A charge id.</returns>
string ChargeCustomer(string customerBillingId, decimal chargeAmount, string chargeDescription);
/// <summary>Refund a customer on the billing service.</summary>
/// <param name="customerBillingId">The billing id of the customer.</param>
/// <param name="chargeId">Id of charge to refund against.</param>
/// <param name="refundAmount">Amount of refund in U.S. dollars.</param>
/// <returns>A charge id.</returns>
string RefundCustomer(string customerBillingId, string chargeId, decimal refundAmount);
/// <summary>Perform a charge check (but not an actual charge) on the billing service.</summary>
/// <param name="customerBillingId">The billing id of the customer.</param>
/// <param name="chargeAmount">Amount of charge in U.S. dollars.</param>
/// <param name="chargeDescription">Description of charge.</param>
/// <returns>A charge id.</returns>
string PerformChargeCheck(string customerBillingId, decimal chargeAmount, string chargeDescription);
}
}
|
using System.Threading.Tasks;
using FeedbackService.Contracts;
using FeedbackService.Database.Repositories.Interfaces;
using MassTransit;
using Microsoft.Extensions.Logging;
namespace FeedbackService.Consumers
{
public class GetOrderFeedbackConsumer : IConsumer<GetOrderFeedback>
{
private readonly ILogger<GetOrderFeedbackConsumer> _logger;
private readonly IFeedbackRepository _feedbackRepository;
public GetOrderFeedbackConsumer(ILogger<GetOrderFeedbackConsumer> logger,
IFeedbackRepository feedbackRepository)
{
_logger = logger;
_feedbackRepository = feedbackRepository;
}
public async Task Consume(ConsumeContext<GetOrderFeedback> context)
{
var feedback = await _feedbackRepository.FindFeedbackAsync(context.Message.OrderId);
await context.RespondAsync<GetOrderFeedbackResponse>(new
{
OrderId = context.Message.OrderId,
Text = feedback?.Text,
StarsAmount = feedback?.StarsAmount
});
}
}
} |
using System.Net.Sockets;
namespace MyNatsClient.Internals
{
internal class SocketFactory : ISocketFactory
{
public Socket Create(SocketOptions options)
{
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
if (options.UseNagleAlgorithm.HasValue)
socket.NoDelay = !options.UseNagleAlgorithm.Value;
if (options.ReceiveBufferSize.HasValue)
socket.ReceiveBufferSize = options.ReceiveBufferSize.Value;
if (options.SendBufferSize.HasValue)
socket.SendBufferSize = options.SendBufferSize.Value;
if (options.ReceiveTimeoutMs.HasValue)
socket.ReceiveTimeout = options.ReceiveTimeoutMs.Value;
if (options.SendTimeoutMs.HasValue)
socket.SendTimeout = options.SendTimeoutMs.Value;
return socket;
}
}
} |
using System;
namespace ZaraEngine.StateManaging
{
[Serializable]
public class HealthStateStateContract
{
public float BloodPressureTop;
public float BloodPressureBottom;
public float HeartRate;
public float BloodPercentage;
public float FoodPercentage;
public float WaterPercentage;
public float OxygenPercentage;
public float StaminaPercentage;
public float FatiguePercentage;
public float BodyTemperature;
public DateTimeContract LastSleepTime;
public DateTimeContract CheckTime;
public bool IsBloodLoss;
public bool IsActiveInjury;
public bool IsActiveDisease;
public bool IsFoodDisgust;
public bool IsSleepDisorder;
public bool CannotRun;
public bool IsLegFracture;
public int ActiveDiseasesWorstLevel;
public string WorstDiseaseId;
public ActiveDiseasesAndInjuriesContract ActiveDiseasesAndInjuries;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace P9YS.Web.Controllers
{
public class AccountController : Controller
{
public IActionResult Index()
{
return Redirect("http://ht.p9ys.com");
}
}
} |
using System.Text.Json.Serialization;
namespace Essensoft.Paylink.Alipay.Response
{
/// <summary>
/// ZhimaCreditEpDossierQrcodeApplyResponse.
/// </summary>
public class ZhimaCreditEpDossierQrcodeApplyResponse : AlipayResponse
{
/// <summary>
/// 档案直跳地址,默认不返回
/// </summary>
[JsonPropertyName("dossier_path")]
public string DossierPath { get; set; }
/// <summary>
/// 二维码到期时间, 标准时间格式:yyyy-MM-dd HH:mm:ss
/// </summary>
[JsonPropertyName("expiration_time")]
public string ExpirationTime { get; set; }
/// <summary>
/// 企业档案页二维码图片地址
/// </summary>
[JsonPropertyName("qr_code")]
public string QrCode { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using LeakBlocker.Libraries.Common;
using LeakBlocker.Libraries.Common.Cryptography;
using LeakBlocker.Libraries.Common.Entities.Security;
namespace LeakBlocker.Server.Service.InternalTools.AdminUsersStorage
{
[DataContract(IsReference = true)]
internal sealed class AdminUserData : BaseReadOnlyObject
{
public AdminUserData(AccountSecurityIdentifier userIdentifier, SymmetricEncryptionKey key)
{
Check.ObjectIsNotNull(userIdentifier, "userIdentifier");
Check.ObjectIsNotNull(key, "key");
UserIdentifier = userIdentifier;
Key = key;
}
[DataMember]
public AccountSecurityIdentifier UserIdentifier
{
get;
private set;
}
[DataMember]
public SymmetricEncryptionKey Key
{
get;
private set;
}
protected override IEnumerable<object> GetInnerObjects()
{
yield return UserIdentifier;
yield return Key;
}
}
}
|
using System;
public static class Heap<T> where T : IComparable<T>
{
public static void Sort(T[] arr)
{
int length = arr.Length;
for (int i = length / 2; i >= 0; i--)
{
HeapifyDown(arr, i, length);
}
for (int i = length - 1; i > 0; i--)
{
Swap(arr, 0, i);
HeapifyDown(arr, 0, i);
}
}
private static void HeapifyDown(T[] arr, int current, int border)
{
while (current < border / 2)
{
int greaterChild = Child(arr, current, border);
if (IsGreater(arr, current, greaterChild))
{
break;
}
Swap(arr, current, greaterChild);
current = greaterChild;
}
}
private static void Swap(T[] arr, int current, int greaterChild)
{
T oldElement = arr[current];
arr[current] = arr[greaterChild];
arr[greaterChild] = oldElement;
}
private static int Child(T[] arr, int current, int border)
{
int leftIndex = current * 2 + 1;
int childIndex = leftIndex;
if (leftIndex + 1 < border)
{
int rightIndex = current * 2 + 2;
if (IsLess(arr,leftIndex,rightIndex))
{
childIndex = rightIndex;
}
}
return childIndex;
}
private static bool IsGreater(T[] arr, int leftIndex, int rightIndex)
{
return arr[leftIndex].CompareTo(arr[rightIndex]) > 0;
}
private static bool IsLess(T[] arr, int leftIndex, int rightIndex)
{
return arr[leftIndex].CompareTo(arr[rightIndex]) < 0;
}
}
|
using NUnit.Framework;
namespace Wikiled.Text.Analysis.Tests.NLP
{
[TestFixture]
public class RawWordExtractorTests
{
[TestCase("program's", "program")]
[TestCase("ringtones", "ringtone")]
[TestCase("smallest", "small")]
[TestCase("best", "best")]
[TestCase("prettier", "pretty")]
[TestCase("noblest", "noble")]
[TestCase("browser", "browser")]
[TestCase("browsers", "browser")]
[TestCase("browsing", "browse")]
[TestCase("uses", "us")]
[TestCase("using", "use")]
[TestCase("dyeing", "dye")]
[TestCase("miss", "miss")]
[TestCase("seeing", "see")]
[TestCase("frustrating", "frustrate")]
[TestCase("fanned", "fan")]
[TestCase("liked", "like")]
[TestCase("missed", "miss")]
[TestCase("helped", "help")]
[TestCase("button", "button")]
[TestCase("Itunes", "itune")]
[TestCase("years", "year")]
[TestCase("productive", "productive")]
[TestCase("potatoes", "potato")]
[TestCase("Cars", "car")]
[TestCase("was", "was")]
[TestCase("wasnt", "wasnt")]
[TestCase("cannt", "cannt")]
[TestCase("wouldnt", "wouldnt")]
[TestCase("wouldn't", "wouldn't")]
[TestCase("anti-virus", "anti-virus")]
public void GetSpecialSymbols(string word, string extected)
{
var result = Global.Raw.GetWord(word);
Assert.AreEqual(extected, result);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace WYZTracker
{
public class ScaleManager
{
private static Dictionary<Scales, int[]> offsetsByScale;
public static Dictionary<Scales, int[]> OffsetsByScale
{
get
{
return offsetsByScale;
}
}
static ScaleManager()
{
initializeOffsetsByScale();
}
private static void initializeOffsetsByScale()
{
offsetsByScale = new Dictionary<Scales, int[]>();
offsetsByScale.Add(Scales.MajorTriad, new int[] { 0, 4, 7 });
offsetsByScale.Add(Scales.MinorTriad, new int[] { 0, 3, 7 });
offsetsByScale.Add(Scales.DiminishedTriad, new int[] { 0, 3, 6 });
offsetsByScale.Add(Scales.AugmentedTriad, new int[] { 0, 4, 8 });
offsetsByScale.Add(Scales.Major, new int[] { 0, 2, 4, 5, 7, 9, 11, 12 });
offsetsByScale.Add(Scales.NaturalMinor, new int[] { 0, 2, 3, 5, 7, 8, 10, 12 });
offsetsByScale.Add(Scales.MelodicMinor, new int[] { 0, 2, 3, 5, 7, 9, 11, 12 });
offsetsByScale.Add(Scales.HarmonicMinor, new int[] { 0, 2, 3, 5, 7, 8, 11, 12 });
offsetsByScale.Add(Scales.Chromatic, new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 });
offsetsByScale.Add(Scales.WholeTone, new int[] { 0, 2, 4, 6, 8, 10, 12 });
offsetsByScale.Add(Scales.PentatonicMajor1, new int[] { 0, 2, 5, 7, 9, 12 });
offsetsByScale.Add(Scales.PentatonicMajor2, new int[] { 0, 2, 4, 7, 9, 12 });
offsetsByScale.Add(Scales.PentatonicMinor, new int[] { 0, 3, 5, 7, 10, 12 });
offsetsByScale.Add(Scales.Mixolydian, new int[] { 0, 2, 4, 5, 7, 9, 10, 12 });
offsetsByScale.Add(Scales.Lydian, new int[] { 0, 2, 4, 6, 7, 9, 11, 12 });
offsetsByScale.Add(Scales.Phrygian, new int[] { 0, 1, 3, 5, 7, 8, 10, 12 });
offsetsByScale.Add(Scales.Dorian, new int[] { 0, 2, 3, 5, 7, 9, 10, 12 });
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Tests.Helpers;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace System.Linq.Tests
{
public class ToDictionaryTests
{
private class CustomComparer<T> : IEqualityComparer<T>
{
public bool Equals(T x, T y) { return EqualityComparer<T>.Default.Equals(x, y); }
public int GetHashCode(T obj) { return EqualityComparer<T>.Default.GetHashCode(obj); }
}
// =====================
[Fact]
public void ToDictionary_AlwaysCreateACopy()
{
Dictionary<int, int> source = new Dictionary<int, int>() { { 1, 1 }, { 2, 2 }, { 3, 3 } };
Dictionary<int, int> result = source.ToDictionary(key => key.Key, val => val.Value);
Assert.NotSame(source, result);
Assert.Equal(source, result);
}
private void RunToDictionaryOnAllCollectionTypes<T>(T[] items, Action<Dictionary<T, T>> validation)
{
validation(Enumerable.ToDictionary(items, key => key));
validation(Enumerable.ToDictionary(items, key => key, value => value));
validation(Enumerable.ToDictionary(new List<T>(items), key => key));
validation(Enumerable.ToDictionary(new List<T>(items), key => key, value => value));
validation(new TestEnumerable<T>(items).ToDictionary(key => key));
validation(new TestEnumerable<T>(items).ToDictionary(key => key, value => value));
validation(new TestReadOnlyCollection<T>(items).ToDictionary(key => key));
validation(new TestReadOnlyCollection<T>(items).ToDictionary(key => key, value => value));
validation(new TestCollection<T>(items).ToDictionary(key => key));
validation(new TestCollection<T>(items).ToDictionary(key => key, value => value));
}
[Fact]
public void ToDictionary_WorkWithEmptyCollection()
{
RunToDictionaryOnAllCollectionTypes(new int[0],
resultDictionary =>
{
Assert.NotNull(resultDictionary);
Assert.Equal(0, resultDictionary.Count);
});
}
[Fact]
public void ToDictionary_ProduceCorrectDictionary()
{
int[] sourceArray = new int[] { 1, 2, 3, 4, 5, 6, 7 };
RunToDictionaryOnAllCollectionTypes(sourceArray,
resultDictionary =>
{
Assert.Equal(sourceArray.Length, resultDictionary.Count);
Assert.Equal(sourceArray, resultDictionary.Keys);
Assert.Equal(sourceArray, resultDictionary.Values);
});
string[] sourceStringArray = new string[] { "1", "2", "3", "4", "5", "6", "7", "8" };
RunToDictionaryOnAllCollectionTypes(sourceStringArray,
resultDictionary =>
{
Assert.Equal(sourceStringArray.Length, resultDictionary.Count);
for (int i = 0; i < sourceStringArray.Length; i++)
Assert.Same(sourceStringArray[i], resultDictionary[sourceStringArray[i]]);
});
}
[Fact]
public void ToDictionary_PassCustomComparer()
{
CustomComparer<int> comparer = new CustomComparer<int>();
TestCollection<int> collection = new TestCollection<int>(new int[] { 1, 2, 3, 4, 5, 6 });
Dictionary<int, int> result1 = collection.ToDictionary(key => key, comparer);
Assert.Same(comparer, result1.Comparer);
Dictionary<int, int> result2 = collection.ToDictionary(key => key, val => val, comparer);
Assert.Same(comparer, result2.Comparer);
}
[Fact]
public void ToDictionary_UseDefaultComparerOnNull()
{
CustomComparer<int> comparer = null;
TestCollection<int> collection = new TestCollection<int>(new int[] { 1, 2, 3, 4, 5, 6 });
Dictionary<int, int> result1 = collection.ToDictionary(key => key, comparer);
Assert.Same(EqualityComparer<int>.Default, result1.Comparer);
Dictionary<int, int> result2 = collection.ToDictionary(key => key, val => val, comparer);
Assert.Same(EqualityComparer<int>.Default, result2.Comparer);
}
[Fact]
public void ToDictionary_KeyValueSelectorsWork()
{
TestCollection<int> collection = new TestCollection<int>(new int[] { 1, 2, 3, 4, 5, 6 });
Dictionary<int, int> result = collection.ToDictionary(key => key + 10, val => val + 100);
Assert.Equal(collection.Items.Select(o => o + 10), result.Keys);
Assert.Equal(collection.Items.Select(o => o + 100), result.Values);
}
[Fact]
public void ToDictionary_ThrowArgumentNullExceptionWhenSourceIsNull()
{
int[] source = null;
Assert.Throws<ArgumentNullException>(() => source.ToDictionary(key => key));
}
[Fact]
public void ToDictionary_ThrowArgumentNullExceptionWhenKeySelectorIsNull()
{
int[] source = new int[0];
Func<int, int> keySelector = null;
Assert.Throws<ArgumentNullException>(() => source.ToDictionary(keySelector));
}
[Fact]
public void ToDictionary_ThrowArgumentNullExceptionWhenValueSelectorIsNull()
{
int[] source = new int[0];
Func<int, int> keySelector = key => key;
Func<int, int> valueSelector = null;
Assert.Throws<ArgumentNullException>(() => source.ToDictionary(keySelector, valueSelector));
}
[Fact]
public void ToDictionary_KeySelectorThrowException()
{
int[] source = new int[] { 1, 2, 3 };
Func<int, int> keySelector = key =>
{
if (key == 1)
throw new InvalidOperationException();
return key;
};
Assert.Throws<InvalidOperationException>(() => source.ToDictionary(keySelector));
}
[Fact]
public void ToDictionary_ThrowWhenKeySelectorReturnNull()
{
int[] source = new int[] { 1, 2, 3 };
Func<int, string> keySelector = key => null;
Assert.Throws<ArgumentNullException>(() => source.ToDictionary(keySelector));
}
[Fact]
public void ToDictionary_ThrowWhenKeySelectorReturnSameValueTwice()
{
int[] source = new int[] { 1, 2, 3 };
Func<int, int> keySelector = key => 1;
Assert.Throws<ArgumentException>(() => source.ToDictionary(keySelector));
}
[Fact]
public void ToDictionary_ValueSelectorThrowException()
{
int[] source = new int[] { 1, 2, 3 };
Func<int, int> keySelector = key => key;
Func<int, int> valueSelector = value =>
{
if (value == 1)
throw new InvalidOperationException();
return value;
};
Assert.Throws<InvalidOperationException>(() => source.ToDictionary(keySelector, valueSelector));
}
}
}
|
using System;
using System.ComponentModel;
using System.Diagnostics;
using Roslyn.Scripting;
namespace Microsoft.CSharp.RuntimeHelpers
{
[DebuggerStepThrough]
[EditorBrowsable(EditorBrowsableState.Never)]
public static class SessionHelpers
{
// this method is only run in Submission constructor that doesn't need to be thread-safe
[Obsolete("do not use this method", true), EditorBrowsable(EditorBrowsableState.Never)]
public static object GetSubmission(Session session, int id)
{
// A call to this helper is not emitted when there are no previous submissions in the session.
// There are obviously no previous submissions if there is no session at all.
Debug.Assert(session != null);
return session.submissions[id];
}
// this method is only run in Submission constructor that doesn't need to be thread-safe
[Obsolete("do not use this method", true), EditorBrowsable(EditorBrowsableState.Never)]
public static object SetSubmission(Session session, int slotIndex, object submission)
{
if (session == null)
{
return null;
}
if (slotIndex >= session.submissions.Length)
{
Array.Resize(ref session.submissions, Math.Max(slotIndex + 1, session.submissions.Length * 2));
}
if (slotIndex > 0 && session.submissions[slotIndex - 1] == null)
{
ThrowPreviousSubmissionNotExecuted();
}
session.submissions[slotIndex] = submission;
return session.hostObject;
}
internal static void RequirePreviousSubmissionExecuted(Session session, int slotIndex)
{
if (slotIndex > 0 && session.submissions[slotIndex - 1] == null)
{
ThrowPreviousSubmissionNotExecuted();
}
}
private static void ThrowPreviousSubmissionNotExecuted()
{
throw new InvalidOperationException("Previous submission must execute before this submission.");
}
}
}
|
using System.Collections.Generic;
using ShaderTools.CodeAnalysis.Hlsl.Symbols;
namespace ShaderTools.CodeAnalysis.Hlsl.Binding.Signatures
{
internal abstract class Signature
{
public abstract TypeSymbol ReturnType { get; }
public abstract ParameterDirection GetParameterDirection(int index);
public abstract bool ParameterHasDefaultValue(int index);
public abstract TypeSymbol GetParameterType(int index);
public abstract int ParameterCount { get; }
public abstract bool HasVariadicParameter { get; }
public IEnumerable<TypeSymbol> GetParameterTypes()
{
for (var i = 0; i < ParameterCount; i++)
yield return GetParameterType(i);
}
}
} |
using JobSchedule.Entities.Models;
using JobSchedule.Service.BaseService;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace JobSchedule.Service.MemberGoalService
{
public interface IMemberGoalService : IService<MemberGoal>
{
Task<IEnumerable<MemberGoal>> GetAllGoalMembersAsync();
Task<MemberGoal> GetGoalMembersAsync(int id);
Task<MemberGoal> GetGoalMemberByGoalIdAsync(int id);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace lm.Comol.Modules.Standard.ProjectManagement.Domain
{
[Serializable]
public class dtoReorderAction
{
public ReorderAction Action{get;set;}
public Boolean Selected { get; set; }
public dtoReorderAction() { }
public dtoReorderAction(ReorderAction action, Boolean selected =false) {
Action = action;
Selected = selected;
}
}
}
|
@using System.Web.Optimization
@using MyWalletz.Helpers
@model MyWalletz.Models.Home
@section Navigation {
@Html.Partial("Navigation")
}
<div class="container-fluid">
<div class="row-fluid">
<div id="container" class="span12" role="main">
<div class="page" ng-view></div>
@{ Html.IncludeClientViews(); }
</div>
</div>
</div>
@section Scripts {
<script>
options = {
userSignedIn: @Html.Raw(@Request.IsAuthenticated.ToString().ToLowerInvariant()),
categories: @Html.Raw(Model.Accounts.ToJson()),
accounts: @Html.Raw(Model.Accounts.ToJson())
};
</script>
@Scripts.Render("~/bundles/angular", "~/bundles/application")
} |
// This source file is covered by the LICENSE.TXT file in the root folder of the SDK.
namespace Ptv.XServer.Controls.Map.Gadgets
{
/// <summary> Control showing a watermark text over the map. </summary>
public partial class WatermarkControl
{
#region constructor
/// <summary> Initializes a new instance of the <see cref="WatermarkControl"/> class. </summary>
public WatermarkControl()
{
InitializeComponent();
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using EasyLife.Domain.Models;
using EasyLife.Domain.ViewModels;
namespace EasyLife.Application.Services.Interfaces
{
public interface IOfficeManager
{
Task<List<Office>> GetOfficesAsync();
Task AddOfficeAsync(Office office);
Task<Office> GetOfficeAsync(int id);
void UpdateOffice(Office office);
void DeleteOffice(Office office);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace projetoTriangulo
{
class Triangulo
{
public double lado1;
public double lado2;
public double lado3;
public string classificacao;
public double perimetro;
public double area;
public Triangulo()
{
lado1 = 0;
lado2 = 0;
lado3 = 0;
classificacao = "";
perimetro = 0;
area = 0;
}
public Triangulo(double Lado1, double Lado2, double Lado3, string Classificacao, double Perimetro, double Area)
{
lado1= Lado1;
lado2 = Lado2;
lado3 = Lado3;
classificacao = Classificacao;
perimetro = Perimetro;
area = Area;
}
public Triangulo(double lado1, double lado2, double lado3)
{
this.lado1 = lado1;
this.lado2 = lado2;
this.lado3 = lado3;
}
public bool IsTriangle()
{
if (lado1 < lado2 + lado3 && lado2 < lado1+lado3 && lado3 < lado1+lado2)
{
Classificar();
CalcularArea();
return true;
}
return false;
}
public void CalcularPerimetro()
{
perimetro = lado1 + lado2 + lado3;
}
public void Classificar()
{
if (lado1 == lado2 && lado1 == lado3 && lado2 == lado3)
{
classificacao = "Triangulo equilatero";
}
else if (lado1 != lado2 && lado1 != lado3 && lado2 != lado3)
{
classificacao = "Triangulo Escaleno";
}
else
{
classificacao = "Triangulo isósceles";
}
}
public void CalcularArea()
{
CalcularPerimetro();
double sp = perimetro / 2;
area = Math.Sqrt(sp * (sp - lado1) * (sp - lado2) * (sp - lado3));
}
}
}
|
using Scrabble_Score_Tool_Library;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Scrabble_Score_Tool_UI
{
/// <summary>
/// Interaction logic for Score_Finder.xaml
/// </summary>
public partial class ScoreFinder : Page
{
public ScoreFinder()
{
InitializeComponent();
TxtBoxWord.MaxLength = 7;
}
private void BtnCalculate_Click(object sender, RoutedEventArgs e)
{
ScrabbleTool tool = new ScrabbleTool();
tool.SetWord(TxtBoxWord.Text);
int score = tool.ScoreFinderRunProgram();
TxtBoxScore.Background = Brushes.DarkGreen;
TxtBoxScore.Opacity = 1;
TxtBoxScore.MinWidth = 30;
TxtBoxScore.Text = score.ToString();
}
private void BtnRtnToMain_OnClick(object sender, RoutedEventArgs e)
{
MainMenu mainMenu = new MainMenu();
this.NavigationService.Navigate(mainMenu);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Charlotte.Commons;
using Charlotte.GameCommons;
namespace Charlotte.Games.Enemies
{
/// <summary>
/// 敵
/// </summary>
public abstract class Enemy
{
// Game.I.ReloadEnemies() からロードされた場合、初期位置として「配置されたマップセルの中心座標」が与えられる。
// this.X, this.Y はマップの座標(マップの左上を0,0とする)
// -- 描画する際は DDGround.ICamera.X, DDGround.ICamera.Y をそれぞれ減じること。
// リスポーンによる敵再現のため、E_Draw は実装しない。
public double X;
public double Y;
public Enemy(double x, double y)
{
this.X = x;
this.Y = y;
}
public Enemy(D2Point pos)
: this(pos.X, pos.Y)
{ }
/// <summary>
/// この敵を消滅させるか
/// 撃破された場合などこの敵を消滅させたい場合 true をセットすること。
/// これにより「フレームの最後に」敵リストから除去される。
/// </summary>
public bool DeadFlag = false;
/// <summary>
/// 現在のフレームにおける当たり判定を保持する。
/// -- Draw によって設定される。
/// </summary>
public DDCrash Crash = DDCrashUtils.None();
// リスポーンによる敵再現のため、E_Draw は実装しない。
/// <summary>
/// 描画と動作
/// リスポーンによる敵再現のため、E_Draw は実装しない。
/// するべきこと:
/// -- 行動
/// -- 描画
/// -- 必要に応じて Crash 設定
/// </summary>
public abstract void Draw();
/// <summary>
/// この敵のコピーを生成する。
/// リスポーン時に、この戻り値と置き換わる。
/// </summary>
/// <returns>この敵のコピー</returns>
public abstract Enemy GetClone();
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WellControl
{
/// <summary>
/// 用来传递已知数据
/// </summary>
public class WellDataInput
{
public double YLSD = 3200;//溢流深度(m)
public double YLCS = 3200;//溢流测深(m)
public double JYZJ = 215.9;//井眼直径(mm)
public double JSTGXS = 2400;//技术套管下深(m)
public double JSTGNJ = 224.4;//技术套管内径(mm)
public double GXPLYL = 40.58;//套管鞋处地层破裂压力(MPa)
public double ZJYMD = 1.25;//钻井液密度(g/cm^3)
public double ZJYZL = 2.5;//钻井液增量(m^3)
public double ZTWJ = 177.8;//钻铤外径(mm)
public double ZTNJ = 71.44;//钻铤内径(mm)
public double ZTCD = 100;//钻铤长度(m)
public double ZGWJ = 127;//钻杆外径(mm)
public double ZGNJ = 108.6;//钻杆内径(mm)
public double GJTY = 6.5;//关井套压(MPa)
public double GJLY = 5;//关井立压(MPa)
public double XHYL = 3.8;//循环压力(MPa)
public double YJBPL = 10;//压井泵排量(L/s)
public double CS = 70;//钻井液泵冲数(冲/分)
public double FJMD = 0.1;//附加密度(g/cm^3)
}
}
|
using Fan.Blog.Models.View;
using Fan.Plugins;
using Fan.Web.Events;
using MediatR;
using Shortcodes.Services;
using System.Threading;
using System.Threading.Tasks;
namespace Shortcodes
{
/// <summary>
/// Handler for parsing shortcodes in Page or Post body content.
/// </summary>
public class ShortcodesHandler : INotificationHandler<ModelPreRender<PageVM>>,
INotificationHandler<ModelPreRender<BlogPostVM>>,
INotificationHandler<ModelPreRender<BlogPostListVM>>
{
private readonly IShortcodeService shortcodeService;
private readonly IPluginService pluginService;
public ShortcodesHandler(IShortcodeService shortcodeService, IPluginService pluginService)
{
this.shortcodeService = shortcodeService;
this.pluginService = pluginService;
}
/// <summary>
/// Handles <see cref="PageVM"/> by parsing shortcodes then nav links.
/// </summary>
/// <param name="notification"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public Task Handle(ModelPreRender<PageVM> notification, CancellationToken cancellationToken)
{
if (!(notification.Model is PageVM)) return Task.CompletedTask;
var pageVM = (PageVM)notification.Model;
((PageVM)notification.Model).Body = shortcodeService.Parse(pageVM.Body);
return Task.CompletedTask;
}
/// <summary>
/// Handles <see cref="BlogPostVM"/> by parsing any shortcodes in its body.
/// </summary>
/// <param name="notification"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public Task Handle(ModelPreRender<BlogPostVM> notification, CancellationToken cancellationToken)
{
if (!(notification.Model is BlogPostVM)) return Task.CompletedTask;
var body = ((BlogPostVM)notification.Model).Body;
((BlogPostVM)notification.Model).Body = shortcodeService.Parse(body);
return Task.CompletedTask;
}
/// <summary>
/// Handles <see cref="BlogPostListVM"/> by parsing any shortcodes in the body of the list of posts.
/// </summary>
/// <param name="notification"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public Task Handle(ModelPreRender<BlogPostListVM> notification, CancellationToken cancellationToken)
{
if (!(notification.Model is BlogPostListVM)) return Task.CompletedTask;
foreach (var postViewModel in ((BlogPostListVM)notification.Model).BlogPostViewModels)
{
postViewModel.Body = shortcodeService.Parse(postViewModel.Body);
}
return Task.CompletedTask;
}
}
}
|
using Clarity.Common.CodingUtilities.Tuples;
namespace Clarity.Common.Infra.TreeReadWrite.Serialization.Handlers
{
public class PairTrwHandler<T> : TrwSerializationHandlerBase<Pair<T>>
{
public override bool ContentIsProperties => false;
public override void SaveContent(ITrwSerializationWriteContext context, Pair<T> value)
{
context.Writer.StartArray(TrwValueType.Undefined);
context.Write(value.First);
context.Write(value.Second);
context.Writer.EndArray();
}
public override Pair<T> LoadContent(ITrwSerializationReadContext context)
{
context.Reader.Check(TrwTokenType.StartArray);
context.Reader.MoveNext();
var first = context.Read<T>();
var second = context.Read<T>();
context.Reader.Check(TrwTokenType.EndArray);
context.Reader.MoveNext();
return new Pair<T>(first, second);
}
}
} |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="TagsAttribute.cs" company="OxyPlot">
// Copyright (c) 2014 OxyPlot contributors
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace ExampleLibrary
{
using System;
/// <summary>
/// Specifies tags.
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
public class TagsAttribute : Attribute
{
/// <summary>
/// Initializes a new instance of the <see cref="TagsAttribute" /> class.
/// </summary>
/// <param name="tags">The tags.</param>
public TagsAttribute(params string[] tags)
{
this.Tags = tags;
}
/// <summary>
/// Gets the tags.
/// </summary>
/// <value>
/// The tags.
/// </value>
public string[] Tags { get; private set; }
}
} |
namespace ConformityCheck.Services
{
using System.Linq;
using ConformityCheck.Data.Common.Repositories;
using ConformityCheck.Data.Models;
public class ContentCheckService : IContentCheckService
{
private readonly IDeletableEntityRepository<Article> articlesRepository;
private readonly IDeletableEntityRepository<Supplier> suppliersRepository;
private readonly IDeletableEntityRepository<Product> productsRepository;
private readonly IDeletableEntityRepository<Substance> substancesRepository;
private readonly IDeletableEntityRepository<ConformityType> conformityTypesRepository;
private readonly IDeletableEntityRepository<Conformity> conformitiesRepository;
private readonly IRepository<ArticleSupplier> articleSuppliersRepository;
private readonly IRepository<ArticleConformityType> articleConformityTypesRepository;
private readonly IRepository<ArticleProduct> articleProductsRepository;
private readonly IRepository<ArticleSubstance> articleSubstancesRepository;
private readonly IRepository<ProductConformityType> productConformityTypesRepository;
public ContentCheckService(
IDeletableEntityRepository<Article> articlesRepository,
IDeletableEntityRepository<Supplier> suppliersRepository,
IDeletableEntityRepository<Product> productsRepository,
IDeletableEntityRepository<Substance> substancesRepository,
IDeletableEntityRepository<ConformityType> conformityTypesRepository,
IDeletableEntityRepository<Conformity> conformitiesRepository,
IRepository<ArticleSupplier> articleSuppliersRepository,
IRepository<ArticleConformityType> articleConformityTypesRepository,
IRepository<ArticleProduct> articleProductsRepository,
IRepository<ArticleSubstance> articleSubstancesRepository,
IRepository<ProductConformityType> productConformityTypesRepository)
{
this.articlesRepository = articlesRepository;
this.suppliersRepository = suppliersRepository;
this.productsRepository = productsRepository;
this.substancesRepository = substancesRepository;
this.conformityTypesRepository = conformityTypesRepository;
this.conformitiesRepository = conformitiesRepository;
this.articleSuppliersRepository = articleSuppliersRepository;
this.articleConformityTypesRepository = articleConformityTypesRepository;
this.articleProductsRepository = articleProductsRepository;
this.articleSubstancesRepository = articleSubstancesRepository;
this.productConformityTypesRepository = productConformityTypesRepository;
}
public bool ArticleEntityIdCheck(string id)
{
var a = this.articlesRepository.AllAsNoTracking().Any(x => x.Id == id);
return a;
}
public bool ArticleSupplierEntityIdCheck(string articleId, string supplierId)
{
return this.articleSuppliersRepository
.AllAsNoTracking()
.Any(x => x.ArticleId == articleId &&
x.SupplierId == supplierId);
}
public bool ArticleConformityTypeEntityIdCheck(string articleId, int conformityTypeId)
{
return this.articleConformityTypesRepository
.AllAsNoTracking()
.Any(x => x.ArticleId == articleId &&
x.ConformityTypeId == conformityTypeId);
}
public bool ArticleEntityNumberCheck(string input)
{
return this.articlesRepository
.AllAsNoTrackingWithDeleted()
.Any(x => x.Number == input.Trim().ToUpper());
}
public bool ConformityTypeEntityIdCheck(int id)
{
return this.conformityTypesRepository.AllAsNoTracking().Any(x => x.Id == id);
}
public bool ConformityTypeEntityDescriptionCheck(string input)
{
return this.conformityTypesRepository
.AllAsNoTracking()
.Any(x => x.Description.ToUpper() == input.ToUpper());
}
public bool ConformityTypeArticlesCheck(int id)
{
return this.articleConformityTypesRepository
.AllAsNoTracking()
.Any(x => x.ConformityTypeId == id);
}
public bool ConformityTypeProductsCheck(int id)
{
return this.productConformityTypesRepository
.AllAsNoTracking()
.Any(x => x.ConformityTypeId == id);
}
public bool ConformityTypeConformitiesCheck(int id)
{
return this.conformitiesRepository
.AllAsNoTracking()
.Any(x => x.ConformityTypeId == id);
}
public bool ConformityEntityIdCheck(string id)
{
return this.conformitiesRepository.AllAsNoTracking().Any(x => x.Id == id);
}
public bool ProductEntityIdCheck(string id)
{
return this.productsRepository.AllAsNoTracking().Any(x => x.Id == id);
}
public bool SubstanceEntityIdCheck(int id)
{
return this.substancesRepository.AllAsNoTracking().Any(x => x.Id == id);
}
public bool SupplierEntityIdCheck(string id)
{
return this.suppliersRepository.AllAsNoTracking().Any(x => x.Id == id);
}
public bool SupplierEntityNameCheck(string input)
{
return this.suppliersRepository
.AllAsNoTracking()
.Any(x => x.Name == input.Trim().ToUpper());
}
public bool SupplierEntityNumberCheck(string input)
{
return this.suppliersRepository
.AllAsNoTrackingWithDeleted()
.Any(x => x.Number == input.Trim().ToUpper());
}
}
}
|
using IdentityModel;
using System;
using System.Collections.Generic;
namespace Plus.IdentityModel
{
public class IdentityClientConfiguration : Dictionary<string, string>
{
/// <summary>
/// Possible values: "client_credentials" or "password".
/// Default value: "client_credentials".
/// </summary>
public string GrantType
{
get => this.GetOrDefault(nameof(GrantType));
set => this[nameof(GrantType)] = value;
}
/// <summary>
/// Client Id.
/// </summary>
public string ClientId
{
get => this.GetOrDefault(nameof(ClientId));
set => this[nameof(ClientId)] = value;
}
/// <summary>
/// Client secret (as plain text - without hashed).
/// </summary>
public string ClientSecret
{
get => this.GetOrDefault(nameof(ClientSecret));
set => this[nameof(ClientSecret)] = value;
}
/// <summary>
/// User name.
/// Valid only if <see cref="GrantType"/> is "password".
/// </summary>
public string UserName
{
get => this.GetOrDefault(nameof(UserName));
set => this[nameof(UserName)] = value;
}
/// <summary>
/// Password of the <see cref="UserName"/>.
/// Valid only if <see cref="GrantType"/> is "password".
/// </summary>
public string UserPassword
{
get => this.GetOrDefault(nameof(UserPassword));
set => this[nameof(UserPassword)] = value;
}
/// <summary>
/// Authority.
/// </summary>
public string Authority
{
get => this.GetOrDefault(nameof(Authority));
set => this[nameof(Authority)] = value;
}
/// <summary>
/// Scope.
/// </summary>
public string Scope
{
get => this.GetOrDefault(nameof(Scope));
set => this[nameof(Scope)] = value;
}
/// <summary>
/// RequireHttps.
/// Default: true.
/// </summary>
public bool RequireHttps
{
get => this.GetOrDefault(nameof(RequireHttps))?.To<bool>() ?? true;
set => this[nameof(RequireHttps)] = value.ToString().ToLowerInvariant();
}
public IdentityClientConfiguration()
{
}
public IdentityClientConfiguration(
string authority,
string scope,
string clientId,
string clientSecret,
string grantType = OidcConstants.GrantTypes.ClientCredentials,
string userName = null,
string userPassword = null,
bool requireHttps = true)
{
this[nameof(Authority)] = authority;
this[nameof(Scope)] = scope;
this[nameof(ClientId)] = clientId;
this[nameof(ClientSecret)] = clientSecret;
this[nameof(GrantType)] = grantType;
this[nameof(UserName)] = userName;
this[nameof(UserPassword)] = userPassword;
this[nameof(RequireHttps)] = requireHttps.ToString().ToLowerInvariant();
}
}
} |
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text.RegularExpressions;
namespace ReaperCore.Nodes
{
public class ReaperNode
{
/// <summary>
/// The parent ReaperNode. If null, this node is the main ReaperSession Node.
/// </summary>
public ReaperNode? Parent { get; }
/// <summary>
/// The type of this Node as a string.
/// </summary>
public string? Type { get; protected set; }
/// <summary>
/// All Children of this ReaperNode as a instances of ReaperNode.
/// A child can be a
/// - TRACK
/// - ITEM (a region on a track)
/// - POSITION (which might be the position of an item on a track),
/// - FADEIN (which might be an array of numbers) or
/// - PT (which is a point of an envelope)
/// - etc.
/// There are many other properties and values. Have a look into
/// the .rpp file (open in any text editor).
/// </summary>
/// <value>The child nodes of this node.</value>
public List<ReaperNode> Children { get; }
/// <summary>
/// The values of this Node.
/// </summary>
public List<string> Values { get; }
/// <summary>
/// Gets the first value of this nodes values.
/// </summary>
/// <value>The first value of this nodes values.</value>
public string Value => Values.Count > 0 ? Values.First() : "";
/// <summary>
/// Initializes a new instance of the <see cref="T:ReaperNode"/> class.
/// </summary>
/// <param name="text">The current line as a string from the reaper file.</param>
/// <param name="parent">The parent node. Pass null if there is no parent.</param>
public ReaperNode(
string text,
ReaperNode? parent
) {
Children = new List<ReaperNode>();
Values = new List<string>();
Parent = parent;
text = text.Trim();
var matchList = new List<string>();
var matches = Regex.Matches(text, "(\"[^\"]*\"|[\\S]+)"); // split the values
foreach (Match match in matches)
{
matchList.Add(match.Value);
}
matchList = matchList.Select(s => s.Trim(' ', '\"', '<', '>')).ToList();
/*
* Try to parse the first element of matches as a float. If it is a
* number, the node has no type but only values. if it is not a
* number, the first element is the type of the node.
*/
try
{
Type = "";
Values = matchList;
}
catch
{
if (matchList.Count > 0)
{
Type = matchList[0];
matchList.RemoveAt(0);
Values = matchList;
}
}
}
/// <summary>
/// Adds a child.
/// </summary>
/// <param name="o">O.</param>
public void AddChild(ReaperNode o) => Children.Add(o);
/// <summary>
/// Gets all children of the given type with the given name
/// </summary>
/// <returns>All children of given type with the given name.</returns>
/// <param name="type">Type.</param>
/// <param name="name">Name.</param>
/// <param name="recursive">Search child nodes too. False by default.</param>
public List<ReaperNode> GetNodesByTypeAndName(string type, string name, bool recursive = false) =>
GetNodes(type, recursive)
.Where(node => node.GetNode("NAME").Value == name)
.ToList();
/// <summary>
/// Find a node by it's type and name.
/// </summary>
/// <returns>The node by type and name.</returns>
/// <param name="type">Type.</param>
/// <param name="name">Name.</param>
public ReaperNode GetNodeByTypeAndName(string type, string name) =>
GetDescendantNodes(type).FirstOrDefault(
node => node.GetNode("NAME").Value == name
);
/// <summary>
/// Find a node by it's type.
/// </summary>
/// <returns>The first child node with type type.</returns>
/// <param name="type">Type.</param>
public ReaperNode GetNode(string type) =>
Children.Find(x => x.Type == type);
public string GetValue(string key) =>
Children
.Find(x => x.Value == key).Values
.ElementAt(1);
/// <summary>
/// Gets the last child node with type type.
/// </summary>
/// <returns>The last child node with type type.</returns>
/// <param name="type">Type.</param>
public ReaperNode GetLastNode(string type) =>
Children.FindLast(x => x.Type == type);
/// <summary>
/// Gets all child nodes with type type.
/// </summary>
/// <returns>The child nodes with type type.</returns>
/// <param name="type">Type.</param>
/// <param name="includeDescendants">If true search child nodes too. False by default.</param>
public List<ReaperNode> GetNodes(string type, bool includeDescendants = false) =>
!includeDescendants
? Children.FindAll(x => x.Type == type)
: GetDescendantNodes(type);
/// <summary>
/// Search all children recursively. Finds children in children too and so on...
/// </summary>
/// <returns>All children of type type.</returns>
/// <param name="type">Type.</param>
private List<ReaperNode> GetDescendantNodes(string type)
{
var found = new List<ReaperNode>();
GetAllDescendants(ref found, type);
return found;
}
private void GetAllDescendants(ref List<ReaperNode> found, string type)
{
var children = GetNodes(type);
found.AddRange(children);
foreach (var child in children)
{
child.GetAllDescendants(ref found, type);
}
}
}
}
|
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#if BINARY_REWRITE
using System.Threading.Tasks;
#else
using Microsoft.Coyote.Tasks;
#endif
using Microsoft.Coyote.Tests.Common;
using Xunit.Abstractions;
#if BINARY_REWRITE
namespace Microsoft.Coyote.BinaryRewriting.Tests
#else
namespace Microsoft.Coyote.Production.Tests
#endif
{
public abstract class BaseProductionTest : BaseTest
{
public BaseProductionTest(ITestOutputHelper output)
: base(output)
{
}
#if BINARY_REWRITE
public override bool SystematicTest => true;
#endif
public class SharedEntry
{
public volatile int Value = 0;
public async Task<int> GetWriteResultAsync(int value)
{
this.Value = value;
await Task.CompletedTask;
return this.Value;
}
public async Task<int> GetWriteResultWithDelayAsync(int value)
{
this.Value = value;
await Task.Delay(1);
return this.Value;
}
}
/// <summary>
/// Unwrap the Coyote controlled Task.
/// </summary>
internal static System.Threading.Tasks.Task<T> GetUncontrolledTask<T>(Task<T> task)
{
#if BINARY_REWRITE
return task;
#else
return task.UncontrolledTask;
#endif
}
/// <summary>
/// For tests expecting uncontrolled task assertions, use these as the expectedErrors array.
/// </summary>
public static string[] GetUncontrolledTaskErrorMessages()
{
return new string[]
{
"Controlled task '' is trying to wait for an uncontrolled task or awaiter to complete. Please " +
"make sure to avoid using concurrency APIs () inside actor handlers. If you are using external " +
"libraries that are executing concurrently, you will need to mock them during testing.",
"Uncontrolled task '' invoked a runtime method. Please make sure to avoid using concurrency APIs () " +
"inside actor handlers or controlled tasks. If you are using external libraries that are executing " +
"concurrently, you will need to mock them during testing.",
"Controlled task '' is trying to wait for an uncontrolled task or awaiter to complete. " +
"Please make sure to use Coyote APIs to express concurrency ()."
};
}
}
}
|
// -----------------------------------------------------------------------
// <copyright file="ConsoleLogger.cs" company="bartosz.jarmuz@gmail.com">
// Copyright (c) Bartosz Jarmuż. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
using System;
using RepoCat.Transmission.Contracts;
namespace RepoCat.Transmission
{
public class ConsoleLogger : LoggerDecorator
{
public ConsoleLogger(ILogger logger) : base(logger)
{
}
public override void Debug(string message)
{
base.Debug(message);
Console.WriteLine("Debug - " + message);
}
public override void Info(string message)
{
base.Info(message);
Console.WriteLine("Info - " + message);
}
public override void Error(string message, Exception exception)
{
base.Error(message, exception);
Console.WriteLine("Error - " + message + exception);
}
public override void Error(string message)
{
base.Error(message);
Console.WriteLine("Error - " + message);
}
public override void Warn(string message)
{
base.Warn(message);
Console.WriteLine("Warn - " + message);
}
public override void Fatal(Exception exception)
{
base.Fatal(exception);
Console.WriteLine("Fatal - " + exception);
}
public override void Fatal(string message, Exception exception)
{
base.Fatal(message, exception);
Console.WriteLine("Fatal - " + message + exception);
}
}
} |
using System;
namespace Heirloom
{
/// <summary>
/// Contains information about a glyph (ie, the horizontal metrics).
/// </summary>
/// <category>Text</category>
public readonly struct GlyphMetrics
{
private readonly IntRectangle _box;
/// <summary>
/// The advance width of the glyph.
/// This is the spacing between the glyph's left edge and the next glyph.
/// </summary>
public readonly float AdvanceWidth;
/// <summary>
/// The bearing of this glyph.
/// </summary>
public readonly float Bearing;
#region Constructors
internal GlyphMetrics(float advanceWidth, float bearing, IntRectangle box)
{
AdvanceWidth = advanceWidth;
Bearing = bearing;
_box = box;
}
#endregion
#region Properties
/// <summary>
/// The glyph offset from the pen position.
/// </summary>
public IntVector Offset => _box.Position;
/// <summary>
/// The glyph bounds size.
/// </summary>
public IntSize Size => _box.Size;
#endregion
#region Equality
/// <summary>
/// Compares this <see cref="GlyphMetrics"/> for equality with another object.
/// </summary>
public override bool Equals(object obj)
{
if (obj is GlyphMetrics metrics)
{
return (metrics.AdvanceWidth == AdvanceWidth)
&& (metrics.Bearing == Bearing)
&& (metrics._box == _box);
}
return false;
}
/// <summary>
/// Returns the hash code this <see cref="GlyphMetrics"/>.
/// </summary>
public override int GetHashCode()
{
return HashCode.Combine(AdvanceWidth, Bearing, _box);
}
/// <summary>
/// Compares two instances of <see cref="GlyphMetrics"/> for equality.
/// </summary>
public static bool operator ==(GlyphMetrics left, GlyphMetrics right)
{
return left.Equals(right);
}
/// <summary>
/// Compares two instances of <see cref="GlyphMetrics"/> for inequality.
/// </summary>
public static bool operator !=(GlyphMetrics left, GlyphMetrics right)
{
return !(left == right);
}
#endregion
}
}
|
using System;
using System.Net;
namespace ExtraLife
{
public class ApiResponseException : Exception
{
public ApiResponseException()
{
}
public ApiResponseException(string message) : base(message)
{
}
public ApiResponseException(string message, Exception innerException) : base(message, innerException)
{
}
public HttpStatusCode HttpResponseCode { get; set; }
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RunComponentOutputNode : RunComponent, INeuralNetworkOutputNode{
public void Activation(float activationValue)
{
m_MoveSpeed += activationValue * m_AccelerationMultiplier;
if (m_MoveSpeed < minimumSpeed)
m_MoveSpeed = minimumSpeed;
}
}
|
using System;
using Microsoft.Data.Entity;
using Microsoft.Data.Entity.Infrastructure;
using Microsoft.Data.Entity.Metadata;
using Microsoft.Data.Entity.Migrations;
using UnicornClicker.UWP.Models;
namespace UnicornClicker.UWP.Migrations
{
[DbContext(typeof(UnicornClickerContext))]
partial class UnicornClickerContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
modelBuilder
.HasAnnotation("ProductVersion", "7.0.0-rc1-16348");
modelBuilder.Entity("UnicornClicker.UWP.Models.GameScore", b =>
{
b.Property<int>("GameScoreId")
.ValueGeneratedOnAdd();
b.Property<int>("Clicks");
b.Property<double>("ClicksPerSecond");
b.Property<int>("Duration");
b.Property<DateTime>("Played");
b.HasKey("GameScoreId");
});
}
}
}
|
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Wsu.DairyCafo.DataAccess.Tests.Helpers;
namespace Wsu.DairyCafo.DataAccess.Tests
{
[TestClass]
public class ScenarioTest
{
[TestMethod]
public void GetCountManureSeparator_ComplexScenario_ReturnsCorrectNum()
{
// Arrange
var injector = new Injector();
var sut = injector.GetComplexScenario();
// Act
int seps = sut.GetCountManureSeparator();
// Assert
Assert.AreEqual(injector.NumberSeparatorsComplex, seps);
}
[TestMethod]
public void GetCountManureSeparator_SimpleScenario_ReturnsCorrectNum()
{
// Arrange
var injector = new Injector();
var sut = injector.GetSimpleScenario();
// Act
int seps = sut.GetCountManureSeparator();
// Assert
Assert.AreEqual(injector.NumberSeparatorsSimple, seps);
}
[TestMethod]
public void GetCountManureStorage_ComplexScenario_ReturnsCorrectNum()
{
// Arrange
var injector = new Injector();
var sut = injector.GetComplexScenario();
// Act
int storage = sut.GetCountManureStorage();
// Assert
Assert.AreEqual(injector.NumberStorageComplex, storage);
}
[TestMethod]
public void GetCountManureStorage_SimpleScenario_ReturnsCorrectNum()
{
// Arrange
var injector = new Injector();
var sut = injector.GetSimpleScenario();
// Act
int storage = sut.GetCountManureStorage();
// Assert
Assert.AreEqual(injector.NumberStorageSimple, storage);
}
}
}
|
using System.Transactions;
using FlexibleSqlConnectionResolver.ConnectionResolution;
using FlexibleSqlConnectionResolver.UseCases.SampleApplication;
namespace FlexibleSqlConnectionResolver.UseCases
{
public class Transaction : UseCase
{
public Transaction(string connectionString)
: base(connectionString)
{
}
public override void Right()
{
// Create and dispose single connection per transaction (e.g. web request)
using (var connectionResolver = new SingletonSqlConnectionResolver(_connectionString))
{
TryCreateOrder(connectionResolver, "Order1");
}
using (var connectionResolver = new SingletonSqlConnectionResolver(_connectionString))
{
TryCreateOrder(connectionResolver, "Order2");
}
}
public override void Wrong1()
{
// Create multiple connections per transaction
using (var connectionResolver = new PerResolveSqlConnectionResolver(_connectionString))
{
TryCreateOrder(connectionResolver, "Order1");
TryCreateOrder(connectionResolver, "Order2");
}
}
public override void Wrong2()
{
// Create too-long-living connection, possibly used by different threads
using (var connectionResolver = new SingletonSqlConnectionResolver(_connectionString))
{
TryCreateOrder(connectionResolver, "Order1");
TryCreateOrder(connectionResolver, "Order2");
}
}
private void TryCreateOrder(ISqlConnectionResolver sqlConnectionResolver, string orderName)
{
var orderCreator = new OrderCreator(sqlConnectionResolver);
var orderItemCreator = new OrderItemCreator(sqlConnectionResolver);
using (var transaction = new TransactionScope())
{
var order = orderCreator.Create(new OrderCreatorInput
{
Name = orderName
});
orderItemCreator.Create(new OrderItemCreatorInput
{
OrderId = order.OrderId,
Name = "Item"
});
transaction.Complete();
}
}
}
}
|
using System.ComponentModel;
// ReSharper disable CSharpWarnings::CS1591
namespace Nutritionix
{
/// <summary>
/// Types of food allergens
/// </summary>
public enum Allergen
{
/// <summary>
/// Contains milk
/// </summary>
[Description("allergen_contains_milk")]
Milk,
/// <summary>
/// Contains eggs
/// </summary>
[Description("allergen_contains_eggs")]
Eggs,
/// <summary>
/// Contains fish
/// </summary>
[Description("allergen_contains_fish")]
Fish,
/// <summary>
/// Contains shellfish
/// </summary>
[Description("allergen_contains_shellfish")]
Shellfish,
/// <summary>
/// Contains tree nuts
/// </summary>
[Description("allergen_contains_tree_nuts")]
TreeNuts,
/// <summary>
/// Contains peanuts
/// </summary>
[Description("allergen_contains_peanuts")]
Peanuts,
/// <summary>
/// Contains wheat
/// </summary>
[Description("allergen_contains_wheat")]
Wheat,
/// <summary>
/// Contains soy
/// </summary>
[Description("allergen_contains_soybeans")]
Soybeans,
/// <summary>
/// Contains gluten
/// </summary>
[Description("allergen_contains_gluten")]
Gluten
}
} |
using Busybody.Events;
namespace Busybody
{
public interface IHandle<T> where T : BusybodyEvent
{
void Handle(T @event);
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.