content stringlengths 23 1.05M |
|---|
using System;
using Windows.Foundation;
using Windows.Networking;
using Windows.Networking.Sockets;
using Windows.Storage.Streams;
using System.Diagnostics;
namespace RobotApp
{
public static class NetworkCmd
{
// if no host, be client, otherwise be a host
private static String hostName = "";
private const String hostPort = "8027";
public static void NetworkInit(String host)
{
ClearPrevious();
hostName = host;
Debug.WriteLine("NetworkInit() host={0}, port={1}", hostName, hostPort);
if (hostName.Length > 0)
{
InitConnectionToHost();
}
else
{
if (listener == null) StartListener();
}
}
public static long msLastSendTime;
static String ctrlStringToSend;
public static void SendCommandToRobot(String stringToSend)
{
ctrlStringToSend = stringToSend + ".";
if (hostName.Length > 0) PostSocketWrite(ctrlStringToSend);
Debug.WriteLine("Sending: " + ctrlStringToSend);
}
#region ----- host connection ----
static StreamSocketListener listener;
public static async void StartListener()
{
try
{
listener = new StreamSocketListener();
listener.ConnectionReceived += OnConnection;
await listener.BindServiceNameAsync(hostPort);
Debug.WriteLine("Listening on {0}", hostPort);
}
catch (Exception e)
{
Debug.WriteLine("StartListener() - Unable to bind listener. " + e.Message);
}
}
static async void OnConnection(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
{
try
{
if (MainPage.isRobot)
{
DataReader reader = new DataReader(args.Socket.InputStream);
String str = "";
while (true)
{
uint len = await reader.LoadAsync(1);
if (len > 0)
{
byte b = reader.ReadByte();
str += Convert.ToChar(b);
if (b == '.')
{
Debug.WriteLine("Network Received: '{0}'", str);
Controllers.ParseCtrlMessage(str);
break;
}
}
}
}
else
{
String lastStringSent;
while (true)
{
DataWriter writer = new DataWriter(args.Socket.OutputStream);
lastStringSent = ctrlStringToSend;
writer.WriteString(lastStringSent);
await writer.StoreAsync();
msLastSendTime = MainPage.stopwatch.ElapsedMilliseconds;
// re-send periodically
long msStart = MainPage.stopwatch.ElapsedMilliseconds;
for (; ;)
{
long msCurrent = MainPage.stopwatch.ElapsedMilliseconds;
if ((msCurrent - msStart) > 3000) break;
if (lastStringSent.CompareTo(ctrlStringToSend) != 0) break;
}
}
}
}
catch (Exception e)
{
Debug.WriteLine("OnConnection() - " + e.Message);
}
}
#endregion
#region ----- client connection -----
static StreamSocket socket;
static bool socketIsConnected;
private static async void InitConnectionToHost()
{
try
{
ClearPrevious();
socket = new StreamSocket();
HostName hostNameObj = new HostName(hostName);
await socket.ConnectAsync(hostNameObj, hostPort);
Debug.WriteLine("Connected to {0}:{1}.", hostNameObj, hostPort);
socketIsConnected = true;
if (MainPage.isRobot) PostSocketRead(1024);
}
catch (Exception ex)
{
Debug.WriteLine("InitConnectionToHost() - " + ex.Message);
}
}
private static void ClearPrevious()
{
if (socket != null)
{
socket.Dispose();
socket = null;
socketIsConnected = false;
}
}
public static void OnDataReadCompletion(uint bytesRead, DataReader readPacket)
{
if (readPacket == null)
{
Debug.WriteLine("DataReader is null");
return;
}
uint buffLen = readPacket.UnconsumedBufferLength;
if (buffLen == 0)
{
// buflen==0 - assume server closed socket
Debug.WriteLine("Attempting to disconnect and reconnecting to the server");
InitConnectionToHost();
return;
}
string message = readPacket.ReadString(buffLen);
Debug.WriteLine("Network Received (b={0},l={1}): '{2}'", bytesRead, buffLen, message);
Controllers.ParseCtrlMessage(message);
PostSocketRead(1024);
}
static DataReader readPacket;
static void PostSocketRead(int length)
{
if (socket == null || !socketIsConnected)
{
Debug.WriteLine("Rd: Socket not connected yet.");
return;
}
try
{
var readBuf = new Windows.Storage.Streams.Buffer((uint)length);
var readOp = socket.InputStream.ReadAsync(readBuf, (uint)length, InputStreamOptions.Partial);
readOp.Completed = (IAsyncOperationWithProgress<IBuffer, uint> asyncAction, AsyncStatus asyncStatus) =>
{
switch (asyncStatus)
{
case AsyncStatus.Completed:
case AsyncStatus.Error:
try
{
IBuffer localBuf = asyncAction.GetResults();
uint bytesRead = localBuf.Length;
readPacket = DataReader.FromBuffer(localBuf);
OnDataReadCompletion(bytesRead, readPacket);
}
catch (Exception exp)
{
Debug.WriteLine("Read operation failed: " + exp.Message);
}
break;
case AsyncStatus.Canceled:
break;
}
};
}
catch (Exception exp)
{
Debug.WriteLine("Failed to post a Read - " + exp.Message);
}
}
static async void PostSocketWrite(string writeStr)
{
if (socket == null || !socketIsConnected)
{
Debug.WriteLine("Wr: Socket not connected yet.");
return;
}
try
{
DataWriter writer = new DataWriter(socket.OutputStream);
writer.WriteString(writeStr);
await writer.StoreAsync();
msLastSendTime = MainPage.stopwatch.ElapsedMilliseconds;
}
catch (Exception exp)
{
Debug.WriteLine("Failed to Write - " + exp.Message);
}
}
#endregion
}
}
|
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace ExchangeRates.Web.Pages
{
public class IndexModel : PageModel
{
private readonly CurrencySettings _settings;
private readonly ICurrencyConverter _converter;
public IndexModel(IOptions<CurrencySettings> settings, ICurrencyConverter converter)
{
_settings = settings.Value;
_converter = converter;
}
[DisplayName("Value in alternate currency")]
public decimal Result { get; set; }
[BindProperty]
public InputModel Input { get; set; }
public void OnGet()
{
Input = new InputModel()
{
Value = _settings.DefaultValue,
ExchangeRate = _settings.DefaultExchangeRate,
DecimalPlaces = _settings.DefaultDecimalPlaces,
};
}
public PageResult OnPost()
{
if (!ModelState.IsValid)
{
return Page();
}
Result = _converter.ConvertToGbp(
Input.Value,
Input.ExchangeRate,
Input.DecimalPlaces);
return Page();
}
public class InputModel
{
[DisplayName("Value in GBP")]
public decimal Value { get; set; } = 0;
[DisplayName("Exchange rate from GBP to alternate currency")]
[Range(0, double.MaxValue)]
public decimal ExchangeRate { get; set; }
[DisplayName("Round to decimal places")]
[Range(0, int.MaxValue)]
public int DecimalPlaces { get; set; }
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Fail : MonoBehaviour
{
public GameObject Player;
Animator animator;
public bool FailCheck;
public GameObject FailPanel;
CanvasGroup canvasGroup;
Vector3 startPos; //초기위치
Quaternion StartRot; //초기회전
// Start is called before the first frame update
void Start()
{
FailCheck = false;
canvasGroup = FailPanel.GetComponent<CanvasGroup>();
startPos = Player.transform.position;
StartRot = Player.transform.rotation;
animator = Player.GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
if(FailCheck)
{
animator.SetTrigger("Death");
FailCheck = false;
canvasGroup.alpha = 1;
canvasGroup.blocksRaycasts = true;
}
}
public void onClickFailButton()
{
Player.transform.position = startPos;
Player.transform.rotation = StartRot;
animator.Rebind(); //애니메이션 초기화
FailCheck = false;
canvasGroup.alpha = 0;
canvasGroup.blocksRaycasts = false;
}
}
|
using System;
using Timetable.Test.Data;
using Xunit;
namespace Timetable.Test
{
public class ResolvedAssociationStopTest
{
private ResolvedStop TestStop = new ResolvedStop(TestScheduleLocations.CreateStop(
TestLocations.Surbiton,
TestSchedules.Ten), DateTime.Today);
[Fact]
public void IsBrokenWhenNoStopInService()
{
var stop = new ResolvedAssociationStop(null, TestStop);
Assert.True(stop.IsBroken);
}
[Fact]
public void IsBrokenWhenNoStopInAssociatedService()
{
var stop = new ResolvedAssociationStop(TestStop, null);
Assert.True(stop.IsBroken);
}
[Fact]
public void NotBrokenWHenHasBothStops()
{
var stop = new ResolvedAssociationStop(TestStop, TestStop);
Assert.False(stop.IsBroken);
}
}
} |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
namespace Azure.ResourceManager.Dynatrace.Models
{
/// <summary> Dynatrace Account Information. </summary>
public partial class AccountInfo
{
/// <summary> Initializes a new instance of AccountInfo. </summary>
public AccountInfo()
{
}
/// <summary> Initializes a new instance of AccountInfo. </summary>
/// <param name="accountId"> Account Id of the account this environment is linked to. </param>
/// <param name="regionId"> Region in which the account is created. </param>
internal AccountInfo(string accountId, string regionId)
{
AccountId = accountId;
RegionId = regionId;
}
/// <summary> Account Id of the account this environment is linked to. </summary>
public string AccountId { get; set; }
/// <summary> Region in which the account is created. </summary>
public string RegionId { get; set; }
}
}
|
using System;
using System.IO;
using NerdyMishka.Security.Cryptography;
using NerdyMishka.Windows;
namespace Kryptos
{
public class Setup
{
}
} |
// Copyright (c) zhenlei520 All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
namespace EInfrastructure.Core.Tools
{
/// <summary>
/// 拷贝类
/// </summary>
[Serializable]
public class CloneableClass : ICloneable
{
#region ICloneable 成员
/// <summary>
/// 浅拷贝
/// </summary>
/// <returns></returns>
public object Clone()
{
return MemberwiseClone();
}
#endregion
#region 深拷贝
/// <summary>
/// 深拷贝
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
/// <returns></returns>
public T DeepClone<T>(T t)
{
using (Stream objectStream = new MemoryStream())
{
IFormatter formatter = new BinaryFormatter();
formatter.Serialize(objectStream, t);
objectStream.Seek(0, SeekOrigin.Begin);
return (T) formatter.Deserialize(objectStream);
}
}
#endregion
#region 浅拷贝
/// <summary>
/// 浅拷贝
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public T ShallowClone<T>()
{
return (T) Clone();
}
#endregion
}
}
|
using System.ComponentModel.DataAnnotations;
using Newtonsoft.Json;
namespace ECommerce.Monitoring.Abstractions
{
public class MonitoringRule
{
[Key]
public string Id { get; set; }
[JsonProperty("rule")]
public string Rule { get; set; }
[JsonProperty("isEnabled")]
public bool IsEnabled { get; set; } = true;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using Xunit;
namespace Amazon.Lambda.RuntimeSupport.UnitTests
{
public class LambdaExceptionHandlingTests
{
[Fact]
public void WriteJsonForUserCodeException()
{
Exception exception = null;
try
{
ThrowTest();
}
catch (Exception ex)
{
exception = ex;
}
var exceptionInfo = ExceptionInfo.GetExceptionInfo(exception);
var json = LambdaXRayExceptionWriter.WriteJson(exceptionInfo);
Assert.NotNull(json);
Assert.DoesNotMatch("\r\n", json);
Assert.DoesNotMatch("\n", json);
var jsonDocument = JsonDocument.Parse(json);
JsonElement jsonElement;
Assert.True(jsonDocument.RootElement.TryGetProperty("working_directory", out jsonElement));
Assert.Equal(JsonValueKind.String, jsonElement.ValueKind);
Assert.True(jsonElement.GetString().Length > 0);
Assert.True(jsonDocument.RootElement.TryGetProperty("exceptions", out jsonElement));
Assert.Equal(JsonValueKind.Array, jsonElement.ValueKind);
jsonElement = jsonElement.EnumerateArray().First();
Assert.Equal("ApplicationException", jsonElement.GetProperty("type").GetString());
Assert.Equal("This is a fake Exception", jsonElement.GetProperty("message").GetString());
jsonElement = jsonElement.GetProperty("stack").EnumerateArray().First();
Assert.True(jsonElement.GetProperty("path").GetString().Length > 0);
Assert.Equal("LambdaExceptionHandlingTests.ThrowTest", jsonElement.GetProperty("label").GetString());
Assert.True(jsonElement.GetProperty("line").GetInt32() > 0);
Assert.True(jsonDocument.RootElement.TryGetProperty("paths", out jsonElement));
Assert.Equal(JsonValueKind.Array, jsonElement.ValueKind);
var paths = jsonElement.EnumerateArray().ToArray();
Assert.Single(paths);
Assert.Contains("LambdaExceptionHandlingTests.cs", paths[0].GetString());
}
private void ThrowTest()
{
throw new ApplicationException("This is a fake Exception");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
namespace WebApi.Attributes
{
/// <summary>
/// 注意:对于所有 OPTIONS 请求,必须在 Action 上标记 HttpOptions ,否则根本不会进过滤器,而是先会被 asp.net webapi 内部拦截,因为没有支持此http方法的标记
/// 此方法失败:改用消息管道,先于 HttpMethod 注解之前
/// </summary>
public class WhiteListAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
IList<string> whiteList = new List<string>();
// TODO: WebApiWhiteList 白名单待查数据库
whiteList.Add("*");
actionContext.Response = new HttpResponseMessage();
actionContext.Response.Headers.Add("Access-Control-Allow-Origin", whiteList);
if (actionContext.Request.Method == HttpMethod.Options)
{
actionContext.Response.StatusCode = System.Net.HttpStatusCode.OK;
return;
}
else
{
base.OnActionExecuting(actionContext);
}
}
}
} |
namespace FastFoodWorkshop.Service
{
using AutoMapper;
using Contracts;
using Data;
using Common.WebConstants;
using Microsoft.Extensions.Logging;
using Models;
using ServiceModels.Manager;
using System.Collections.Generic;
using System.Threading.Tasks;
using System;
using System.Linq;
public class CategoryService : ICategoryService
{
private readonly IRepository<Category> categoryRepository;
private readonly IMapper mapper;
private readonly ILogger logger;
public CategoryService(
ILogger<CategoryService> logger,
IRepository<Category> categoryRepository,
IMapper mapper)
{
this.logger = logger;
this.mapper = mapper;
this.categoryRepository = categoryRepository;
}
public async Task AddCategoryAsync(CategoryViewModel model)
{
try
{
var category = this.mapper.Map<Category>(model);
await this.categoryRepository.AddAsync(category);
await this.categoryRepository.SaveChangesAsync();
this.logger.LogInformation(string.Format(LogMessages.CategoryAdded, category.Id));
}
catch (Exception e)
{
throw new ApplicationException(e.Message);
}
}
public async Task DeleteCategoryAsync(int id)
{
try
{
var category = this.categoryRepository.All().FirstOrDefault(e => e.Id == id);
if (category == null)
{
throw new ApplicationException(string.Format(ErrorMessages.CategoryDoesNotExist, id));
}
this.categoryRepository.Delete(category);
await this.categoryRepository.SaveChangesAsync();
this.logger.LogInformation(string.Format(LogMessages.CategoryDeleted, category.Id));
}
catch (Exception e)
{
throw new ApplicationException(e.Message);
}
}
public async Task EditCategoryAsync(int id, CategoryViewModel model)
{
try
{
var category = this.categoryRepository.All().FirstOrDefault(e => e.Id == id);
if (category == null)
{
throw new ApplicationException(string.Format(ErrorMessages.CategoryDoesNotExist, id));
}
category.Name = model.Name;
this.categoryRepository.Update(category);
await this.categoryRepository.SaveChangesAsync();
this.logger.LogInformation(string.Format(LogMessages.CategoryAdded, category.Id));
}
catch (Exception e)
{
throw new ApplicationException(e.Message);
}
}
public async Task<ICollection<Category>> GetCategoriesAsync()
{
var category = categoryRepository.All().ToList();
return await Task.FromResult<ICollection<Category>>(category);
}
public async Task<Category> GetCategoryAsync(int id)
{
var category = this.categoryRepository.All().FirstOrDefault(e => e.Id == id);
return await Task.FromResult<Category>(category);
}
public async Task<ICollection<CategoryViewModel>> MapCategoriesAsync(CategoriesViewModel model)
{
var category = this.categoryRepository.All().ToList();
model.Categories = this.mapper.Map<ICollection<CategoryViewModel>>(category);
return await Task.FromResult<ICollection<CategoryViewModel>>(model.Categories);
}
public async Task<CategoryViewModel> MapCategoryAsync(int id)
{
var category = this.categoryRepository.All().FirstOrDefault(e => e.Id == id);
if (category == null)
{
throw new ApplicationException(string.Format(ErrorMessages.CategoryDoesNotExist, id));
}
var model = this.mapper.Map<CategoryViewModel>(category);
return await Task.FromResult<CategoryViewModel>(model);
}
}
}
|
using Plus.Configuration;
namespace Plus.RedisCache
{
/// <summary>
/// DefaultRedisCacheSettings
/// </summary>
public class DefaultRedisCacheSettings : SettingsBase
{
public DefaultRedisCacheSettings()
{
}
/// <summary>
/// DatabaseId
/// </summary>
/// <returns></returns>
public int DefaultDatabaseId => Config.GetSection("RedisCache")["DatabaseId"].ToInt();
/// <summary>
/// ConnectionString
/// </summary>
/// <returns></returns>
public string DefaultConnectionString => Config.GetSection("RedisCache")["ConnectionString"].ToString();
}
} |
// Copyright (c) Peter Vrenken. All rights reserved. See the license on https://github.com/vrenken/EtAlii.Ubigia
namespace EtAlii.Ubigia.Api.Transport.Grpc
{
using global::Grpc.Core;
using System.Threading.Tasks;
using EtAlii.Ubigia.Api.Transport.Grpc.WireProtocol;
using Account = EtAlii.Ubigia.Account;
public partial class GrpcAuthenticationDataClient : GrpcClientBase, IAuthenticationDataClient<IGrpcSpaceTransport>
{
private AuthenticationGrpcService.AuthenticationGrpcServiceClient _client;
private StorageGrpcService.StorageGrpcServiceClient _storageClient;
private SpaceGrpcService.SpaceGrpcServiceClient _spaceClient;
private Account _account;
public GrpcAuthenticationDataClient()
{
_hostIdentifier = CreateHostIdentifier();
}
public override async Task Connect(ISpaceConnection<IGrpcSpaceTransport> spaceConnection)
{
await base.Connect(spaceConnection).ConfigureAwait(false);
SetClients(spaceConnection.Transport.CallInvoker);
}
public override async Task Disconnect()
{
await base.Disconnect().ConfigureAwait(false);
_storageClient = null;
_spaceClient = null;
}
private void SetClients(CallInvoker callInvoker)
{
_client = new AuthenticationGrpcService.AuthenticationGrpcServiceClient(callInvoker);
_storageClient = new StorageGrpcService.StorageGrpcServiceClient(callInvoker);
_spaceClient = new SpaceGrpcService.SpaceGrpcServiceClient(callInvoker);
}
}
}
|
using System;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using Avalonia.Platform.Interop;
namespace Avalonia.OpenGL
{
public class GlInterfaceBase : GlInterfaceBase<object>
{
public GlInterfaceBase(Func<string, IntPtr> getProcAddress) : base(getProcAddress, null)
{
}
public GlInterfaceBase(Func<Utf8Buffer, IntPtr> nativeGetProcAddress) : base(nativeGetProcAddress, null)
{
}
}
public class GlInterfaceBase<TContext>
{
private readonly Func<string, IntPtr> _getProcAddress;
public GlInterfaceBase(Func<string, IntPtr> getProcAddress, TContext context)
{
_getProcAddress = getProcAddress;
foreach (var prop in this.GetType().GetProperties())
{
var attrs = prop.GetCustomAttributes()
.Where(a =>
a is IGlEntryPointAttribute || a is IGlEntryPointAttribute<TContext>)
.ToList();
if(attrs.Count == 0)
continue;
var isOptional = prop.GetCustomAttribute<GlOptionalEntryPoint>() != null;
var fieldName = $"<{prop.Name}>k__BackingField";
var field = prop.DeclaringType.GetField(fieldName,
BindingFlags.Instance | BindingFlags.NonPublic);
if (field == null)
throw new InvalidProgramException($"Expected property {prop.Name} to have {fieldName}");
IntPtr proc = IntPtr.Zero;
foreach (var attr in attrs)
{
if (attr is IGlEntryPointAttribute<TContext> typed)
proc = typed.GetProcAddress(context, getProcAddress);
else if (attr is IGlEntryPointAttribute untyped)
proc = untyped.GetProcAddress(getProcAddress);
if (proc != IntPtr.Zero)
break;
}
if (proc != IntPtr.Zero)
field.SetValue(this, Marshal.GetDelegateForFunctionPointer(proc, prop.PropertyType));
else if (!isOptional)
throw new OpenGlException("Unable to find a suitable GL function for " + prop.Name);
}
}
protected static Func<string, IntPtr> ConvertNative(Func<Utf8Buffer, IntPtr> func) =>
(proc) =>
{
using (var u = new Utf8Buffer(proc))
{
var rv = func(u);
return rv;
}
};
public GlInterfaceBase(Func<Utf8Buffer, IntPtr> nativeGetProcAddress, TContext context) : this(ConvertNative(nativeGetProcAddress), context)
{
}
public IntPtr GetProcAddress(string proc) => _getProcAddress(proc);
}
}
|
using PseudoScript.Interpreter.Types;
using PseudoScript.Parser;
namespace PseudoScript.Interpreter.Operations
{
class Literal : Operation
{
public readonly new AstProvider.Literal item;
public CustomValue value;
public Literal(AstProvider.Literal item) : base(item) { }
public Literal(AstProvider.Literal item, string target) : base(null, target)
{
this.item = item;
}
public override Literal Build(CPSVisit visit)
{
value = item.type switch
{
AstProvider.Type.BooleanLiteral => new CustomBoolean((bool)item.value),
AstProvider.Type.StringLiteral => new CustomString((string)item.value),
AstProvider.Type.NumericLiteral => new CustomNumber((double)item.value),
AstProvider.Type.NilLiteral => Default.Void,
_ => throw new InterpreterException("Unexpected literal type."),
};
return this;
}
public override CustomValue Handle(Context ctx)
{
return value;
}
}
}
|
using System.ComponentModel.DataAnnotations;
namespace Netptune.Core.Requests
{
public class UpdateTagRequest
{
[Required]
[MinLength(2)]
[MaxLength(128)]
public string CurrentValue { get; set; }
[Required]
[MinLength(2)]
[MaxLength(128)]
public string NewValue { get; set; }
}
}
|
using Convience.Util.Helpers;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using System.Linq;
using System.Threading.Tasks;
namespace Convience.Util.Filters
{
public class SafeApiFilter : IAsyncActionFilter
{
private readonly ILogger<SafeApiFilter> _logger;
public SafeApiFilter(ILogger<SafeApiFilter> logger)
{
_logger = logger;
}
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
var headers = context.HttpContext.Request.Headers;
var timestamp = headers["TimeStamp"];
var nonce = headers["Nonce"];
var sign = headers["Sign"];
var md5 = EncryptionHelper.MD5Encrypt(timestamp.FirstOrDefault() + "-" + nonce.FirstOrDefault());
if (md5 == sign.FirstOrDefault())
{
_logger.LogDebug("签名验证成功!");
await next();
}
else
{
_logger.LogDebug("签名验证失败!");
context.Result = new StatusCodeResult(406);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Zoo.Classes
{
public abstract class Mammal : Animal
{
// backing stores
// redirect targets for unwanted property 'set' inputs
private string _garbageString = "";
// inherited properties overrides
public override string BodyCovering {
get { return "hair"; }
set { _garbageString = value; }
}
/// <summary>
/// Requires children to define how they travel
/// </summary>
public abstract string Travel();
/// <summary>
/// Allows children to hibernate and comment on it
/// </summary>
/// <param name="months"> number of months the hibernation lasts </param>
/// <returns> nap report </returns>
public virtual string Hibernate(int months)
{
string nap = $"What a great {months} month nap!";
return nap;
}
}
}
|
using ChatApp.Domain.Models;
namespace ChatApp.Consumer
{
public interface IChatConsumer
{
void ConsumeChat(Team team);
}
}
|
using System;
using System.Collections.Generic;
using System.Reflection.Emit;
using System.Text;
namespace Wodsoft.Protobuf
{
/// <summary>
/// Protobuf message field definition.
/// </summary>
public interface IMessageField
{
/// <summary>
/// Get field number.
/// </summary>
int FieldNumber { get; }
/// <summary>
/// Get field CLR type.
/// </summary>
Type FieldType { get; }
/// <summary>
/// Get field name.
/// </summary>
string FieldName { get; }
/// <summary>
/// Generate IL code that read field value of object.<br/>
/// The top of the stack is a reference of object.<br/>
/// There must be a value on the top of the stack. It can be null.
/// </summary>
/// <param name="ilGenerator">IL generator.</param>
void GenerateReadFieldCode(ILGenerator ilGenerator);
/// <summary>
/// Generate IL code that write field value of object.<br/>
/// The top of the stack is value that need to write to the field.<br/>
/// The second of the stack is a reference of object.<br/>
/// </summary>
/// <param name="ilGenerator">IL generator.</param>
void GenerateWriteFieldCode(ILGenerator ilGenerator);
}
}
|
namespace Lua4Net.Types
{
public abstract class LuaType
{
}
} |
/*
* [The "BSD licence"]
* Copyright (c) 2011 Terence Parr
* All rights reserved.
*
* Conversion to C#:
* Copyright (c) 2011 Sam Harwell, Pixel Mine, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
namespace AntlrUnitTests
{
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Console = System.Console;
using ErrorManager = Antlr3.Tool.ErrorManager;
using Path = System.IO.Path;
using Regex = System.Text.RegularExpressions.Regex;
[TestClass]
[TestCategory(TestCategories.SkipOnCI)]
public class TestSyntaxErrors : BaseTest
{
[TestMethod][TestCategory(TestCategories.Antlr3)]
public void TestLL2()
{
string grammar =
"grammar T;\n" +
"a : 'a' 'b'" +
" | 'a' 'c'" +
";\n" +
"q : 'e' ;\n";
string found = execParser("T.g", grammar, "TParser", "TLexer", "a", "ae", false);
string expecting = "line 1:1 no viable alternative at input 'e'" + NewLine;
string result = Regex.Replace(stderrDuringParse, ".*?/input ", "input ");
Assert.AreEqual(expecting, result);
}
[TestMethod][TestCategory(TestCategories.Antlr3)]
public void TestLL3()
{
string grammar =
"grammar T;\n" +
"a : 'a' 'b'* 'c'" +
" | 'a' 'b' 'd'" +
" ;\n" +
"q : 'e' ;\n";
Console.WriteLine(grammar);
string found = execParser("T.g", grammar, "TParser", "TLexer", "a", "abe", false);
string expecting = "line 1:2 no viable alternative at input 'e'" + NewLine;
string result = Regex.Replace(stderrDuringParse, ".*?/input ", "input ");
Assert.AreEqual(expecting, result);
}
[TestMethod][TestCategory(TestCategories.Antlr3)]
public void TestLLStar()
{
string grammar =
"grammar T;\n" +
"a : 'a'+ 'b'" +
" | 'a'+ 'c'" +
";\n" +
"q : 'e' ;\n";
string found = execParser("T.g", grammar, "TParser", "TLexer", "a", "aaae", false);
string expecting = "line 1:3 no viable alternative at input 'e'" + NewLine;
string result = Regex.Replace(stderrDuringParse, ".*?/input ", "input ");
Assert.AreEqual(expecting, result);
}
[TestMethod][TestCategory(TestCategories.Antlr3)]
public void TestSynPred()
{
string grammar =
"grammar T;\n" +
"a : (e '.')=> e '.'" +
" | (e ';')=> e ';'" +
" | 'z'" +
" ;\n" +
"e : '(' e ')'" +
" | 'i'" +
" ;\n";
Console.WriteLine(grammar);
string found = execParser("T.g", grammar, "TParser", "TLexer", "a", "((i))z", false);
string expecting = "line 1:1 no viable alternative at input '('" + NewLine;
string result = Regex.Replace(stderrDuringParse, ".*?/input ", "input ");
Assert.AreEqual(expecting, result);
}
[TestMethod][TestCategory(TestCategories.Antlr3)]
public void TestLL1ErrorInfo()
{
string grammar =
"grammar T;\n" +
"start : animal (AND acClass)? service EOF;\n" +
"animal : (DOG | CAT );\n" +
"service : (HARDWARE | SOFTWARE) ;\n" +
"AND : 'and';\n" +
"DOG : 'dog';\n" +
"CAT : 'cat';\n" +
"HARDWARE: 'hardware';\n" +
"SOFTWARE: 'software';\n" +
"WS : ' ' {skip();} ;" +
"acClass\n" +
"@init\n" +
"{ System.out.println(computeContextSensitiveRuleFOLLOW().toString(tokenNames)); }\n" +
" : ;\n";
string result = execParser("T.g", grammar, "TParser", "TLexer", "start", "dog and software", false);
string expecting = "{HARDWARE,SOFTWARE}" + NewLine;
Assert.AreEqual(expecting, result);
}
[TestMethod][TestCategory(TestCategories.Antlr3)]
public void TestStrayBracketRecovery()
{
string grammar =
"grammar T;\n" +
"options {output = AST;}\n" +
"tokens{NODE;}\n" +
"s : a=ID INT -> ^(NODE[$a]] INT);\n" +
"ID: 'a'..'z'+;\n" +
"INT: '0'..'9'+;\n";
ErrorQueue errorQueue = new ErrorQueue();
ErrorManager.SetErrorListener(errorQueue);
bool found =
rawGenerateAndBuildRecognizer(
"T.g", grammar, "TParser", "TLexer", false);
Assert.IsFalse(found);
Assert.AreEqual(
"[error(100): :4:27: syntax error: antlr: dangling ']'? make sure to escape with \\]]",
'[' + string.Join(", ", errorQueue.errors) + ']');
}
/**
* This is a regression test for antlr/antlr3#61.
* https://github.com/antlr/antlr3/issues/61
*/
[TestMethod][TestCategory(TestCategories.Antlr3)]
public void TestMissingAttributeAccessPreventsCodeGeneration()
{
string grammar =
"grammar T;\n" +
"options {\n" +
" backtrack = true; \n" +
"}\n" +
"// if b is rule ref, gens bad void x=null code\n" +
"a : x=b {Object o = $x; System.out.println(\"alt1\");}\n" +
" | y=b\n" +
" ;\n" +
"\n" +
"b : 'a' ;\n";
ErrorQueue errorQueue = new ErrorQueue();
ErrorManager.SetErrorListener(errorQueue);
bool success = rawGenerateAndBuildRecognizer("T.g", grammar, "TParser", "TLexer", false);
Assert.IsFalse(success);
Assert.AreEqual(
"[error(117): " + tmpdir.ToString() + Path.DirectorySeparatorChar + "T.g:6:9: missing attribute access on rule scope: x]",
'[' + string.Join(", ", errorQueue.errors) + ']');
}
}
}
|
using System;
using System.Collections;
using System.Windows;
using System.Windows.Input;
using System.Windows.Controls;
using System.Windows.Media;
namespace SDKSample
{
public partial class Window1 : Window
{
ArrayList hitResultsList = new ArrayList();
public Window1()
{
InitializeComponent();
}
private void WindowLoaded(object sender, EventArgs e)
{
}
// <Snippet100>
// Respond to the left mouse button down event by initiating the hit test.
private void OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
// Retrieve the coordinate of the mouse position.
Point pt = e.GetPosition((UIElement)sender);
// Perform the hit test against a given portion of the visual object tree.
HitTestResult result = VisualTreeHelper.HitTest(myCanvas, pt);
if (result != null)
{
// Perform action on hit visual object.
}
}
// </Snippet100>
// <Snippet101>
// Respond to the right mouse button down event by setting up a hit test results callback.
private void OnMouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
// Retrieve the coordinate of the mouse position.
Point pt = e.GetPosition((UIElement)sender);
// Clear the contents of the list used for hit test results.
hitResultsList.Clear();
// Set up a callback to receive the hit test result enumeration.
VisualTreeHelper.HitTest(myCanvas, null,
new HitTestResultCallback(MyHitTestResult),
new PointHitTestParameters(pt));
// Perform actions on the hit test results list.
if (hitResultsList.Count > 0)
{
Console.WriteLine("Number of Visuals Hit: " + hitResultsList.Count);
}
}
// </Snippet101>
// <Snippet102>
// Return the result of the hit test to the callback.
public HitTestResultBehavior MyHitTestResult(HitTestResult result)
{
// Add the hit test result to the list that will be processed after the enumeration.
hitResultsList.Add(result.VisualHit);
// Set the behavior to return visuals at all z-order levels.
return HitTestResultBehavior.Continue;
}
// </Snippet102>
// Dummy routine to hold snippet.
public HitTestResultBehavior MyDummyHitTestResult(HitTestResult result)
{
// <Snippet103>
// Set the behavior to stop enumerating visuals.
return HitTestResultBehavior.Stop;
// </Snippet103>
}
// <Snippet104>
// Respond to the mouse wheel event by setting up a hit test filter and results enumeration.
private void OnMouseWheel(object sender, MouseWheelEventArgs e)
{
// Retrieve the coordinate of the mouse position.
Point pt = e.GetPosition((UIElement)sender);
// Clear the contents of the list used for hit test results.
hitResultsList.Clear();
// Set up a callback to receive the hit test result enumeration.
VisualTreeHelper.HitTest(myCanvas,
new HitTestFilterCallback(MyHitTestFilter),
new HitTestResultCallback(MyHitTestResult),
new PointHitTestParameters(pt));
// Perform actions on the hit test results list.
if (hitResultsList.Count > 0)
{
ProcessHitTestResultsList();
}
}
// </Snippet104>
// Dummy routine to hold snippet.
private void OnDummyEvent01(object sender, MouseButtonEventArgs e)
{
// Retrieve the coordinate of the mouse position.
Point pt = e.GetPosition((UIElement)sender);
// Clear the contents of the list used for hit test results.
hitResultsList.Clear();
// <Snippet105>
// Set up a callback to receive the hit test result enumeration,
// but no hit test filter enumeration.
VisualTreeHelper.HitTest(myCanvas,
null, // No hit test filtering.
new HitTestResultCallback(MyHitTestResult),
new PointHitTestParameters(pt));
// </Snippet105>
// Perform actions on the hit test results list.
if (hitResultsList.Count > 0)
{
ProcessHitTestResultsList();
}
}
// <Snippet106>
// Filter the hit test values for each object in the enumeration.
public HitTestFilterBehavior MyHitTestFilter(DependencyObject o)
{
// Test for the object value you want to filter.
if (o.GetType() == typeof(Label))
{
// Visual object and descendants are NOT part of hit test results enumeration.
return HitTestFilterBehavior.ContinueSkipSelfAndChildren;
}
else
{
// Visual object is part of hit test results enumeration.
return HitTestFilterBehavior.Continue;
}
}
// </Snippet106>
public void ProcessHitTestResultsList() { }
}
// Dummy class to hold snippet.
public class MyDummyVisual : DrawingVisual
{
//<Snippet107>
// Override default hit test support in visual object.
protected override HitTestResult HitTestCore(PointHitTestParameters hitTestParameters)
{
Point pt = hitTestParameters.HitPoint;
// Perform custom actions during the hit test processing,
// which may include verifying that the point actually
// falls within the rendered content of the visual.
// Return hit on bounding rectangle of visual object.
return new PointHitTestResult(this, pt);
}
//</Snippet107>
}
// Dummy class to hold snippet.
public class MyDummyVisual2 : DrawingVisual
{
//<Snippet108>
// Override default hit test support in visual object.
protected override HitTestResult HitTestCore(PointHitTestParameters hitTestParameters)
{
// Perform actions based on hit test of bounding rectangle.
// ...
// Return results of base class hit testing,
// which only returns hit on the geometry of visual objects.
return base.HitTestCore(hitTestParameters);
}
//</Snippet108>
}
} |
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
namespace BlazeBin.Client.Pages;
public partial class ActionButtons : IDisposable
{
[Inject] private BlazeBinStateContainer? State { get; set; }
[Inject] private NavigationManager? Nav { get; set; }
private bool _saving;
protected override void OnAfterRender(bool firstRender)
{
if (firstRender)
{
State!.OnChange += HandleStateChange;
}
base.OnAfterRender(firstRender);
}
private Task HandleStateChange()
{
StateHasChanged();
return Task.CompletedTask;
}
private async Task CreateNewBundle(MouseEventArgs e)
{
await State!.Dispatch(() => State!.CreateUpload(true));
}
private async Task SaveFileBundle(MouseEventArgs e)
{
_saving = true;
StateHasChanged();
await State!.Dispatch(() => State!.SaveActiveUpload());
_saving = false;
}
private bool IsSavingDisabled()
{
if (_saving)
{
return true;
}
if (State!.ActiveUpload != null && State.ActiveUpload.LastServerId != null)
{
return true;
}
if (State!.ActiveFile == null)
{
return true;
}
return false;
}
private void RedirectToBasic()
{
if (State!.ActiveUpload?.LastServerId == null)
{
Nav!.NavigateTo("/basic", true);
}
else if (State.ActiveUpload != null && State.ActiveUpload.LastServerId != null)
{
Nav!.NavigateTo($"/basic/viewer/{State.ActiveUpload.LastServerId}/{State.ActiveFileIndex}", true);
}
}
public void Dispose()
{
State!.OnChange -= HandleStateChange;
GC.SuppressFinalize(this);
}
}
|
//############################################################
// https://github.com/yuzhengyang
// author:yuzhengyang
//############################################################
using System;
namespace Azylee.Core.ReflectionUtils.AttributeUtils
{
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Method, Inherited = false, AllowMultiple = true)]
public class ControlAttribute : Attribute
{
public string Widget { get; set; }
public string Click { get; set; }
public ControlAttributeEvent Event { get; set; }
//public static void Band(Form form)
//{
//string buttonName = "ShowMsg";
//Type type = form.GetType();
//FieldInfo fieldShowMsg = type.GetField(buttonName, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
//ControlAttribute controlAttribute = (ControlAttribute)fieldShowMsg.GetCustomAttribute(typeof(ControlAttribute));
//FieldInfo fieldButton1 = type.GetField(controlAttribute.Widget, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
//fieldShowMsg.SetValue(form, fieldButton1.GetValue(form));
//MethodInfo method = type.GetMethod(controlAttribute.Click, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public);
//EventInfo evt = fieldShowMsg.FieldType.GetEvent("Click", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public);
//evt.AddEventHandler(fieldShowMsg.GetValue(form), Delegate.CreateDelegate(typeof(EventHandler), form, method));
//int a = 0;
//}
}
}
|
using QQChannelFramework.Api.Base;
using QQChannelFramework.Api.Types;
namespace QQChannelFramework.Api;
/// <summary>
/// QQ频道机器人OpenApi
/// </summary>
public sealed partial class QQChannelApi {
private ApiBase apiBase {
get {
var ret = new ApiBase(OpenApiAccessInfo);
switch (Identity) {
case Identity.Bot: ret.UseBotIdentity(); break;
default:
throw new ArgumentOutOfRangeException();
}
switch (RequestMode) {
case RequestMode.Release: ret.UseReleaseMode(); break;
case RequestMode.SandBox: ret.UseSandBoxMode(); break;
default:
throw new ArgumentOutOfRangeException();
}
return ret;
}
}
public OpenApiAccessInfo OpenApiAccessInfo { get; private set; }
public QQChannelApi(OpenApiAccessInfo openApiAccessInfo) {
OpenApiAccessInfo = openApiAccessInfo;
}
/// <summary>
/// 正式/沙箱模式
/// </summary>
public RequestMode RequestMode { get; set; }
public Identity Identity { get; set; }
/// <summary>
/// 使用正式模式 (默认)
/// </summary>
/// <returns></returns>
public QQChannelApi UseReleaseMode() {
RequestMode = RequestMode.Release;
return this;
}
/// <summary>
/// 使用沙盒模式
/// </summary>
/// <returns></returns>
public QQChannelApi UseSandBoxMode() {
RequestMode = RequestMode.SandBox;
return this;
}
/// <summary>
/// 使用Bot身份
/// </summary>
/// <returns></returns>
public QQChannelApi UseBotIdentity() {
Identity = Identity.Bot;
return this;
}
} |
namespace AsmResolver.DotNet.TestCases.Types
{
public abstract class AbstractClass
{
public abstract void AbstractMethod();
}
} |
namespace Scheduler.Services.Interfaces
{
using System.Collections.Generic;
using System.Threading.Tasks;
using Scheduler.Data.Models;
using Scheduler.Web.ViewModels.EventViewModel;
public interface IEventService
{
public Task<Event> GetEvent(string eventId);
public Task<IEnumerable<Event>> GetAllEventsForUser(string userId);
public Task<IEnumerable<Event>> GetEventsFromTo(string start, string end, string userId);
public Task<bool> CreateEvent(EventAddViewModel eventAdd);
public Task<bool> AddUserToEvent(string userId, string eventId);
public Task DeleteEvent(string eventId, string userId);
public Task UpdateEvent(EventAddViewModel eventAddViewModel);
public Task UpdateParticipants(EventAddParticipantsViewModel eventParticipants);
}
}
|
using Nordlys.Game.Sessions;
using System.Threading.Tasks;
namespace Nordlys.Communication.Messages
{
public interface IMessageEvent
{
Task RunAsync(Session session, ClientMessage message);
}
}
|
using System;
using System.Linq;
using Sandbox;
using Sandbox.UI;
using Sandbox.UI.Construct;
namespace Facepunch.Minigolf.UI;
public partial class WaitingScreenClient : Panel
{
public Client Client { get; set; }
public Image Avatar { get; set; }
public bool Loaded { get; set; }
public WaitingScreenClient( Client cl )
{
Client = cl;
Avatar = Add.Image( $"avatarbig:{cl.PlayerId}" );
}
public override void Tick()
{
base.Tick();
if ( !Client.IsValid() )
return;
SetClass( "loaded", Loaded );
}
}
[UseTemplate]
public partial class WaitingScreen : Panel
{
Panel PlayersContainer { get; set; }
// Bindables for HTML:
public string StartingTimeLeft => $"{ Math.Max(0, Game.Current.StartTime - Time.Now ).CeilToInt() }";
public string PlayerCount => $"{Client.All.Count}";
public string MaxPlayers => $"{ Game.Current.LobbyCount }";
public override void Tick()
{
// Remove any invalid clients (disconnected)
foreach ( var panel in PlayersContainer.Children.OfType<WaitingScreenClient>() )
{
if ( panel.Client.IsValid() ) continue;
panel.Delete();
}
// Add any new clients that aren't already in the list
foreach ( var client in Client.All )
{
if ( PlayersContainer.Children.OfType<WaitingScreenClient>().Any( panel => panel.Client == client ) ) continue;
PlayersContainer.AddChild( new WaitingScreenClient( client ) );
}
}
} |
using Cool.Normalization.Permissions;
using System.Collections.Generic;
namespace Cool.Normalization.Permissions
{
public interface IPermissionRegister
{
void Register(string name, string displayName, IEnumerable<CoolPermission> permissions);
}
}
|
using Terraria;
using Terraria.ID;
using Terraria.ModLoader;
namespace DyeHard.Dyes.Flame
{
public class BrightCyanGradientDye : ModItem
{
public override void SetStaticDefaults()
{
DisplayName.SetDefault("Bright Cyan Gradient Dye");
}
public override void SetDefaults()
{
item.width = 20;
item.height = 20;
item.maxStack = 99;
item.value = Item.sellPrice(0, 0, 20, 0);
item.rare = 1;
item.dye = 71;
}
public override void AddRecipes()
{
ModRecipe recipe = new ModRecipe(mod);
recipe.AddTile(TileID.DyeVat);
recipe.AddIngredient(ItemID.CyanGradientDye);
recipe.AddIngredient(ItemID.SilverDye);
recipe.SetResult(this);
recipe.AddRecipe();
}
}
public class BrightVioletGradientDye : ModItem
{
public override void SetStaticDefaults()
{
DisplayName.SetDefault("Bright Violet Gradient Dye");
}
public override void SetDefaults()
{
item.width = 20;
item.height = 20;
item.maxStack = 99;
item.value = Item.sellPrice(0, 0, 20, 0);
item.rare = 1;
item.dye = 72;
}
public override void AddRecipes()
{
ModRecipe recipe = new ModRecipe(mod);
recipe.AddIngredient(ItemID.VioletGradientDye);
recipe.AddIngredient(ItemID.SilverDye);
recipe.AddTile(TileID.DyeVat);
recipe.SetResult(this);
recipe.AddRecipe();
}
}
public class BrightYellowGradientDye : ModItem
{
public override void SetStaticDefaults()
{
DisplayName.SetDefault("Bright Yellow Gradient Dye");
}
public override void SetDefaults()
{
item.width = 20;
item.height = 20;
item.maxStack = 99;
item.value = Item.sellPrice(0, 0, 20, 0);
item.rare = 1;
item.dye = 70;
}
public override void AddRecipes()
{
ModRecipe recipe = new ModRecipe(mod);
recipe.AddIngredient(ItemID.YellowGradientDye);
recipe.AddIngredient(ItemID.SilverDye);
recipe.AddTile(TileID.DyeVat);
recipe.SetResult(this);
recipe.AddRecipe();
}
}
public class DimCyanGradientDye : ModItem
{
public override void SetStaticDefaults()
{
DisplayName.SetDefault("Dim Cyan Gradient Dye");
}
public override void SetDefaults()
{
item.width = 20;
item.height = 20;
item.maxStack = 99;
item.value = Item.sellPrice(0, 0, 20, 0);
item.rare = 1;
item.dye = 71;
}
public override void AddRecipes()
{
ModRecipe recipe = new ModRecipe(mod);
recipe.AddIngredient(ItemID.CyanGradientDye);
recipe.AddIngredient(ItemID.BlackDye);
recipe.AddTile(TileID.DyeVat);
recipe.SetResult(this);
recipe.AddRecipe();
}
}
public class DimVioletGradientDye : ModItem
{
public override void SetStaticDefaults()
{
DisplayName.SetDefault("Dim Violet Gradient Dye");
}
public override void SetDefaults()
{
item.width = 20;
item.height = 20;
item.maxStack = 99;
item.value = Item.sellPrice(0, 0, 20, 0);
item.rare = 1;
item.dye = 72;
}
public override void AddRecipes()
{
ModRecipe recipe = new ModRecipe(mod);
recipe.AddIngredient(ItemID.VioletGradientDye);
recipe.AddIngredient(ItemID.BlackDye);
recipe.AddTile(TileID.DyeVat);
recipe.SetResult(this);
recipe.AddRecipe();
}
}
public class DimYellowGradientDye : ModItem
{
public override void SetStaticDefaults()
{
DisplayName.SetDefault("Dim Yellow Gradient Dye");
}
public override void SetDefaults()
{
item.width = 20;
item.height = 20;
item.maxStack = 99;
item.value = Item.sellPrice(0, 0, 20, 0);
item.rare = 1;
item.dye = 70;
}
public override void AddRecipes()
{
ModRecipe recipe = new ModRecipe(mod);
recipe.AddIngredient(ItemID.YellowGradientDye);
recipe.AddIngredient(ItemID.BlackDye);
recipe.AddTile(TileID.DyeVat);
recipe.SetResult(this);
recipe.AddRecipe();
}
}
public class BrightFlameDye : ModItem
{
public override void SetStaticDefaults()
{
DisplayName.SetDefault("Bright Flame Dye");
}
public override void SetDefaults()
{
item.width = 20;
item.height = 20;
item.maxStack = 99;
item.value = Item.sellPrice(0, 0, 20, 0);
item.rare = 1;
item.dye = 58;
}
public override void AddRecipes()
{
ModRecipe recipe = new ModRecipe(mod);
recipe.AddIngredient(ItemID.FlameDye);
recipe.AddIngredient(ItemID.SilverDye);
recipe.AddTile(TileID.DyeVat);
recipe.SetResult(this);
recipe.AddRecipe();
}
}
public class BrightBlueFlameDye : ModItem
{
public override void SetStaticDefaults()
{
DisplayName.SetDefault("Bright Blue Flame Dye");
}
public override void SetDefaults()
{
item.width = 20;
item.height = 20;
item.maxStack = 99;
item.value = Item.sellPrice(0, 0, 20, 0);
item.rare = 1;
item.dye = 62;
}
public override void AddRecipes()
{
ModRecipe recipe = new ModRecipe(mod);
recipe.AddIngredient(ItemID.BlueFlameDye);
recipe.AddIngredient(ItemID.SilverDye);
recipe.AddTile(TileID.DyeVat);
recipe.SetResult(this);
recipe.AddRecipe();
}
}
public class BrightGreenFlameDye : ModItem
{
public override void SetStaticDefaults()
{
DisplayName.SetDefault("Bright Green Flame Dye");
}
public override void SetDefaults()
{
item.width = 20;
item.height = 20;
item.maxStack = 99;
item.value = Item.sellPrice(0, 0, 20, 0);
item.rare = 1;
item.dye = 66;
}
public override void AddRecipes()
{
ModRecipe recipe = new ModRecipe(mod);
recipe.AddIngredient(ItemID.GreenFlameDye);
recipe.AddIngredient(ItemID.SilverDye);
recipe.AddTile(TileID.DyeVat);
recipe.SetResult(this);
recipe.AddRecipe();
}
}
public class DimFlameDye : ModItem
{
public override void SetStaticDefaults()
{
DisplayName.SetDefault("Dim Flame Dye");
}
public override void SetDefaults()
{
item.width = 20;
item.height = 20;
item.maxStack = 99;
item.value = Item.sellPrice(0, 0, 20, 0);
item.rare = 1;
item.dye = 58;
}
public override void AddRecipes()
{
ModRecipe recipe = new ModRecipe(mod);
recipe.AddIngredient(ItemID.FlameDye);
recipe.AddIngredient(ItemID.BlackDye);
recipe.AddTile(TileID.DyeVat);
recipe.SetResult(this);
recipe.AddRecipe();
}
}
public class DimBlueFlameDye : ModItem
{
public override void SetStaticDefaults()
{
DisplayName.SetDefault("Dim Blue Flame Dye");
}
public override void SetDefaults()
{
item.width = 20;
item.height = 20;
item.maxStack = 99;
item.value = Item.sellPrice(0, 0, 20, 0);
item.rare = 1;
item.dye = 62;
}
public override void AddRecipes()
{
ModRecipe recipe = new ModRecipe(mod);
recipe.AddIngredient(ItemID.BlueFlameDye);
recipe.AddIngredient(ItemID.BlackDye);
recipe.AddTile(TileID.DyeVat);
recipe.SetResult(this);
recipe.AddRecipe();
}
}
public class DimGreenFlameDye : ModItem
{
public override void SetStaticDefaults()
{
DisplayName.SetDefault("Dim Green Flame Dye");
}
public override void SetDefaults()
{
item.width = 20;
item.height = 20;
item.maxStack = 99;
item.value = Item.sellPrice(0, 0, 20, 0);
item.rare = 1;
item.dye = 66;
}
public override void AddRecipes()
{
ModRecipe recipe = new ModRecipe(mod);
recipe.AddIngredient(ItemID.GreenFlameDye);
recipe.AddIngredient(ItemID.BlackDye);
recipe.AddTile(TileID.DyeVat);
recipe.SetResult(this);
recipe.AddRecipe();
}
}
}
|
public class DualWorkSetup : MonoBehaviour // TypeDefIndex: 8329
{
// Fields
[SerializeField] // RVA: 0x16EDE0 Offset: 0x16EEE1 VA: 0x16EDE0
private ActorImporter MainActor; // 0x18
[SerializeField] // RVA: 0x16EDF0 Offset: 0x16EEF1 VA: 0x16EDF0
private ActorImporter SubActor; // 0x20
[CompilerGeneratedAttribute] // RVA: 0x16EE00 Offset: 0x16EF01 VA: 0x16EE00
private double <MiniGameEnd>k__BackingField; // 0x28
// Properties
public double MiniGameEnd { get; set; }
// Methods
[CompilerGeneratedAttribute] // RVA: 0x1A6E30 Offset: 0x1A6F31 VA: 0x1A6E30
// RVA: 0x200E360 Offset: 0x200E461 VA: 0x200E360
public double get_MiniGameEnd() { }
[CompilerGeneratedAttribute] // RVA: 0x1A6E40 Offset: 0x1A6F41 VA: 0x1A6E40
// RVA: 0x200E370 Offset: 0x200E471 VA: 0x200E370
public void set_MiniGameEnd(double value) { }
// RVA: 0x200E380 Offset: 0x200E481 VA: 0x200E380
public void SetUp() { }
// RVA: 0x200EB60 Offset: 0x200EC61 VA: 0x200EB60
public void UnSetup() { }
// RVA: 0x200EC40 Offset: 0x200ED41 VA: 0x200EC40
public void .ctor() { }
}
|
using PontoDigital_final.Models;
namespace PontoDigital_final.ViewModels
{
public class UsuarioViewModel
{
public Usuario Usuario {get;set;}
}
} |
namespace Autofac.Extensions.FluentBuilder.Tests.Generics
{
public class GenericClass : IGenericType
{
}
} |
public interface IUINavigationMediator {
IUIActiveReceiver SetNavigationReceiver {
set;
}
void NavigationActive();
void NavigationInactive();
}
|
@page
@model TroydonFitnessWebsite.Pages.Gallery.IndexModel
@{
ViewData["Title"] = "Gallery";
}
<h1>Gallery</h1>
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class DataObject {
//*** Properties
public List<float> speeds;
public float speedY;
}
|
// Copyright (c) Nate McMaster.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
namespace McMaster.Extensions.CommandLineUtils
{
internal class Constants
{
public static readonly object[] EmptyArray
#if NET45
= new object[0];
#elif (NETSTANDARD1_6 || NETSTANDARD2_0)
= Array.Empty<object>();
#else
#error Update target frameworks
#endif
}
}
|
using NetworkToolkit.Connections;
using System.Diagnostics;
using System.Net;
using System.Threading.Tasks;
namespace NetworkToolkit.Tests.Http.Servers
{
internal sealed class Http1TestServer : HttpTestServer
{
private readonly ConnectionListener _listener;
public override EndPoint? EndPoint => _listener.EndPoint;
public Http1TestServer(ConnectionListener connectionListener)
{
_listener = connectionListener;
}
public override async Task<HttpTestConnection> AcceptAsync()
{
Connection? connection = await _listener.AcceptConnectionAsync().ConfigureAwait(false);
Debug.Assert(connection != null);
return new Http1TestConnection(connection);
}
public override ValueTask DisposeAsync() =>
_listener.DisposeAsync();
}
}
|
//------------------------------------------------------------------------------
// <copyright file="ICodeGenerator.cs" company="Microsoft">
//
// Copyright (c) 2006 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
// </copyright>
//------------------------------------------------------------------------------
namespace System.CodeDom.Compiler {
using System.Diagnostics;
using System.IO;
using System.Security.Permissions;
/// <devdoc>
/// <para>
/// Provides an
/// interface for code generation.
/// </para>
/// </devdoc>
public interface ICodeGenerator {
/// <devdoc>
/// <para>
/// Gets a value indicating whether
/// the specified value is a valid identifier for this language.
/// </para>
/// </devdoc>
[PermissionSet(SecurityAction.LinkDemand, Name="FullTrust")]
[PermissionSet(SecurityAction.InheritanceDemand, Name="FullTrust")]
bool IsValidIdentifier(string value);
/// <devdoc>
/// <para>
/// Throws an exception if value is not a valid identifier.
/// </para>
/// </devdoc>
[PermissionSet(SecurityAction.LinkDemand, Name="FullTrust")]
[PermissionSet(SecurityAction.InheritanceDemand, Name="FullTrust")]
void ValidateIdentifier(string value);
[PermissionSet(SecurityAction.LinkDemand, Name="FullTrust")]
[PermissionSet(SecurityAction.InheritanceDemand, Name="FullTrust")]
string CreateEscapedIdentifier(string value);
[PermissionSet(SecurityAction.LinkDemand, Name="FullTrust")]
[PermissionSet(SecurityAction.InheritanceDemand, Name="FullTrust")]
string CreateValidIdentifier(string value);
[PermissionSet(SecurityAction.LinkDemand, Name="FullTrust")]
[PermissionSet(SecurityAction.InheritanceDemand, Name="FullTrust")]
string GetTypeOutput(CodeTypeReference type);
[PermissionSet(SecurityAction.LinkDemand, Name="FullTrust")]
[PermissionSet(SecurityAction.InheritanceDemand, Name="FullTrust")]
bool Supports(GeneratorSupport supports);
/// <devdoc>
/// <para>
/// Generates code from the specified expression and
/// outputs it to the specified textwriter.
/// </para>
/// </devdoc>
[PermissionSet(SecurityAction.LinkDemand, Name="FullTrust")]
[PermissionSet(SecurityAction.InheritanceDemand, Name="FullTrust")]
void GenerateCodeFromExpression(CodeExpression e, TextWriter w, CodeGeneratorOptions o);
/// <devdoc>
/// <para>
/// Outputs the language specific representaion of the CodeDom tree
/// refered to by e, into w.
/// </para>
/// </devdoc>
[PermissionSet(SecurityAction.LinkDemand, Name="FullTrust")]
[PermissionSet(SecurityAction.InheritanceDemand, Name="FullTrust")]
void GenerateCodeFromStatement(CodeStatement e, TextWriter w, CodeGeneratorOptions o);
/// <devdoc>
/// <para>
/// Outputs the language specific representaion of the CodeDom tree
/// refered to by e, into w.
/// </para>
/// </devdoc>
[PermissionSet(SecurityAction.LinkDemand, Name="FullTrust")]
[PermissionSet(SecurityAction.InheritanceDemand, Name="FullTrust")]
void GenerateCodeFromNamespace(CodeNamespace e, TextWriter w, CodeGeneratorOptions o);
/// <devdoc>
/// <para>
/// Outputs the language specific representaion of the CodeDom tree
/// refered to by e, into w.
/// </para>
/// </devdoc>
[PermissionSet(SecurityAction.LinkDemand, Name="FullTrust")]
[PermissionSet(SecurityAction.InheritanceDemand, Name="FullTrust")]
void GenerateCodeFromCompileUnit(CodeCompileUnit e, TextWriter w, CodeGeneratorOptions o);
/// <devdoc>
/// <para>
/// Outputs the language specific representaion of the CodeDom tree
/// refered to by e, into w.
/// </para>
/// </devdoc>
[PermissionSet(SecurityAction.LinkDemand, Name="FullTrust")]
[PermissionSet(SecurityAction.InheritanceDemand, Name="FullTrust")]
void GenerateCodeFromType(CodeTypeDeclaration e, TextWriter w, CodeGeneratorOptions o);
}
}
|
using JetBrains.Annotations;
namespace ITGlobal.CommandLine.Parsing
{
/// <summary>
/// Default value provider for command line options
/// </summary>
[PublicAPI]
public delegate bool DefaultValueProvider<T>(out T value);
} |
//===================================================================================
// Microsoft patterns & practices
// Guidance Automation Extensions
//===================================================================================
// Copyright (c) Microsoft Corporation. All rights reserved.
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE.
//===================================================================================
// License: MS-LPL
//===================================================================================
#region Using directives
using System;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
#endregion
namespace Microsoft.Practices.ComponentModel
{
[TestClass]
public class ServiceContainerTests
{
#region Simple service registration and retrieval
[TestMethod]
public void TestGetServiceGeneric()
{
IServiceContainer c = new ServiceContainer();
c.AddService(this.GetType(), this);
ServiceContainerTests st = (ServiceContainerTests)
c.GetService(typeof(ServiceContainerTests));
Assert.AreEqual("Hello", st.SayHello());
}
private string SayHello()
{
return "Hello";
}
#endregion Simple service registration and retrieval
#region Siting components
[TestMethod]
public void TestSitedComponent()
{
ServiceContainer c = new ServiceContainer();
c.AddService(typeof(HelloWorldService), new HelloWorldService());
c.Add(new MyComponent(), "MyTest");
MyComponent mc = c.Components["MyTest"] as MyComponent;
Assert.IsTrue(mc.Run());
}
private class MyComponent : SitedComponent
{
public bool Run()
{
return ((HelloWorldService)GetService(typeof(HelloWorldService))).SayHello() == "Hello";
}
}
private class HelloWorldService
{
public string SayHello()
{
return "Hello";
}
}
#endregion Siting components
#region Nested containers and services
[TestMethod]
public void DetectContainerOnSited()
{
ServiceContainer parent = new ServiceContainer();
DetectOnSitedChildContainer child = new DetectOnSitedChildContainer();
parent.Add(child);
Assert.IsTrue(child.HasDetected, "Child OnSited method not called or Site is null.");
}
[TestMethod]
public void NestedContainers()
{
IServiceContainer parent = new ServiceContainer();
IServiceContainer child = new ServiceContainer();
// Site into parent container.
((IContainer)parent).Add((IComponent)child);
IServiceContainer grandchild = new ServiceContainer();
// Site into parent container.
((IContainer)child).Add((IComponent)grandchild);
parent.AddService(typeof(TopMostService), new TopMostService());
child.AddService(typeof(FirstChildService), new FirstChildService());
grandchild.AddService(typeof(SecondChildService), new SecondChildService());
Assert.IsNotNull(grandchild.GetService(typeof(SecondChildService)));
Assert.IsNotNull(grandchild.GetService(typeof(FirstChildService)));
Assert.IsNotNull(grandchild.GetService(typeof(TopMostService)));
Assert.IsNull(child.GetService(typeof(SecondChildService)));
Assert.IsNull(parent.GetService(typeof(FirstChildService)));
Assert.IsNull(parent.GetService(typeof(SecondChildService)));
Assert.IsNotNull(child.GetService(typeof(FirstChildService)));
Assert.IsNotNull(child.GetService(typeof(TopMostService)));
}
private class TopMostService
{
}
private class FirstChildService
{
}
private class SecondChildService
{
}
private class DetectOnSitedChildContainer : ServiceContainer
{
public bool HasDetected = false;
protected override void OnSited()
{
base.OnSited();
HasDetected = this.Site != null;
}
}
#endregion Nested containers and services
#region Component publishes service
[TestMethod]
public void ComponentPublishesService()
{
ServiceContainer c = new ServiceContainer(true);
c.Add(new PublishingComponent());
c.Add(new ConsumingComponent());
}
private class PublishingComponent : SitedComponent
{
protected override void OnSited()
{
base.OnSited();
IServiceContainer c = (IServiceContainer)GetService(typeof(IServiceContainer));
Assert.IsNotNull(c, "IServiceContainer service not found!");
c.AddService(typeof(TopMostService), new TopMostService());
}
}
private class ConsumingComponent : SitedComponent
{
protected override void OnSited()
{
base.OnSited();
Assert.IsNotNull(GetService(typeof(TopMostService)), "Couldn't find published service!");
}
}
#endregion Component publishes service
#region Component publishes promoted service
[TestMethod]
public void ComponentPublishesPromotedService()
{
ServiceContainer parent = new ServiceContainer(true);
ServiceContainer child = new ServiceContainer(true);
parent.Add(child);
// Publishing component added to the child container.
child.Add(new PromotedPublishingComponent());
// Consuming component on the parent container should see the promoted service.
parent.Add(new ConsumingComponent());
}
private class PromotedPublishingComponent : SitedComponent
{
protected override void OnSited()
{
base.OnSited();
IServiceContainer c = (IServiceContainer)GetService(typeof(IServiceContainer));
Assert.IsNotNull(c, "IServiceContainer service not found!");
c.AddService(typeof(TopMostService), new TopMostService(), true);
}
}
#endregion Component publishes service
#region Service dependency checks
[TestMethod]
[ExpectedException(typeof(ServiceMissingException))]
public void CheckedDependenciesGenericException()
{
ServiceContainer c = new ServiceContainer();
c.Add(new GenericDependencyExceptionComponent());
}
[TestMethod]
[ExpectedException(typeof(CantWorkWithoutItException))]
public void CheckedDependenciesSpecificException()
{
ServiceContainer c = new ServiceContainer();
c.Add(new SpecificDependencyExceptionComponent());
}
[ServiceDependency(typeof(TopMostService))]
private class SpecificDependencyExceptionComponent : SitedComponent
{
protected override void OnMissingServiceDependency(Type missingService)
{
throw new CantWorkWithoutItException();
}
}
private class CantWorkWithoutItException : ApplicationException
{
}
[ServiceDependency(typeof(TopMostService))]
private class GenericDependencyExceptionComponent : IComponent
{
#region IComponent Members
event EventHandler IComponent.Disposed
{
add { throw new global::System.NotImplementedException(); }
remove { throw new global::System.NotImplementedException(); }
}
ISite IComponent.Site
{
get { return _site; }
set { _site = value; }
} ISite _site;
#endregion
#region IDisposable Members
void IDisposable.Dispose()
{
throw new NotImplementedException();
}
#endregion
}
#endregion Service dependency checks
}
} |
using System.Collections.Generic;
using System.Linq;
namespace Kifa.Markdown.Elements {
public class HeadingElement : MarkdownElement {
public int Level { get; set; }
public List<MarkdownElement> TitleElements { get; set; }
public override string ToText() =>
$"{new string('#', Level)} {TitleElements.Select(title => title.ToText()).JoinBy()}\n\n";
}
}
|
using System;
using System.Threading.Tasks;
using MediatR;
using Raven.Client;
using Shrew.Web.Models.Domain;
namespace Shrew.Web.Infrastructure.SuggestionsBox
{
public class DetailsCommandHandler : AsyncRequestHandler<DetailsCommand>
{
private readonly Func<IAsyncDocumentSession> session;
public DetailsCommandHandler(Func<IAsyncDocumentSession> session)
{
this.session = session;
}
protected override async Task HandleCore(DetailsCommand message)
{
var box = await session().LoadAsync<Box>(message.Details.Id);
box.AddSuggestion(message.Details.NewSuggestion);
}
}
} |
using System.Windows.Controls;
namespace Vulnerator.View.Validation
{
class BlankFieldValidationRule : ValidationRule
{
public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
{
string fieldText = value.ToString();
if (string.IsNullOrWhiteSpace(fieldText))
{
return new ValidationResult(false, null);
}
return new ValidationResult(true, null);
}
}
}
|
/*
* Copyright © 2012-2016 VMware, Inc. 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.
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.Serialization;
using System.Text;
namespace Vmware.Tools.RestSsoAdminSnapIn.Dto
{
[TypeConverter(typeof(ExpandableObjectConverter))][Serializable]
public class HttpTransportItem : IDataContext
{
[ReadOnlyAttribute(true), DescriptionAttribute("Unique identitfier for each message trace")]
public Guid Id { get; set; }
[ReadOnlyAttribute(true), DescriptionAttribute("Server that serviced the request")]
public string Server { get; set; }
[ReadOnlyAttribute(true), DescriptionAttribute("Total time taken from the client to the server and back")]
public string TimeTaken { get; set; }
[ReadOnlyAttribute(true), DescriptionAttribute("HTTP verb (GET, POST, PUT, DELETE, PATCH) used to make the request to the URI")]
public string Method { get; set; }
[ReadOnlyAttribute(true), DescriptionAttribute("The server endpoint corresponding to the requst")]
public string RequestUri { get; set; }
[ReadOnlyAttribute(true), DescriptionAttribute("HTTP Headers set with the request from client to the server")]
public HttpTransportRequestHeader RequestHeader { get; set; }
[ReadOnlyAttribute(true), DescriptionAttribute("Data sent from the client to the server")]
public string RequestData { get; set; }
[ReadOnlyAttribute(true), DescriptionAttribute("The timestamp corresponding to the request")]
public DateTime RequestTimestamp { get; set; }
[ReadOnlyAttribute(true), DescriptionAttribute("Data sent back from the server to the client")]
public string ResponseData { get; set; }
[ReadOnlyAttribute(true), DescriptionAttribute("HTTP Headers sent by the server to the client")]
public HttpTransportResponseHeader ResponseHeader { get; set; }
[ReadOnlyAttribute(true), DescriptionAttribute("Error returned when the request was processed")]
public string Error { get; set; }
public string RequestHeaderAsString { get { return GetRequestHeaderAsString(); } }
private string GetRequestHeaderAsString()
{
var builder = new StringBuilder();
if (RequestHeader != null)
{
builder.AppendFormat("User-Agent : {0}", RequestHeader.UserAgent);
builder.AppendLine();
builder.AppendFormat("ContentType : {0}", RequestHeader.ContentType);
builder.AppendLine();
builder.AppendFormat("ContentLength : {0}", RequestHeader.ContentLength);
builder.AppendLine();
builder.AppendFormat("Host : {0}", RequestHeader.Host);
builder.AppendLine();
builder.AppendFormat("Authorization : {0}", RequestHeader.Authorization);
builder.AppendLine();
}
return builder.ToString();
}
public string ResponseHeaderAsString { get { return GetResponseHeaderAsString(); } }
private string GetResponseHeaderAsString()
{
var builder = new StringBuilder();
if (ResponseHeader != null)
{
builder.AppendFormat("ContentType : {0}", ResponseHeader.ContentType);
builder.AppendLine();
builder.AppendFormat("ContentLength : {0}", ResponseHeader.ContentLength);
builder.AppendLine();
builder.AppendFormat("Server : {0}", ResponseHeader.Server);
builder.AppendLine();
}
return builder.ToString();
}
}
}
|
public interface IJeweller
{
IGem Cut(string[] gemInfo);
}
|
using AbhsChinese.Code.Common;
using AbhsChinese.Domain.Enum;
using AbhsChinese.Domain.JsonEntity.Answer;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AbhsChinese.Domain.Dto.Response.Student
{
public class DtoStudentWrongSubjectInfo
{
public string CourseName { get; set; }
public string CourseLessonName { get; set; }
public int Yws_StudentId { get; set; }
public int Yws_Id { get; set; }
public int Yws_CourseId { get; set; }
public int Yws_LessonId { get; set; }
public int Yws_WrongBookId { get; set; }
public int Yws_Source { get; set; }
public string SourceStr => CustomEnumHelper.Parse(typeof(StudyWrongSourceEnum), Yws_Source);
public int Yws_WrongSubjectId { get; set; }
public int Yws_SubjectType { get; set; }
public int Yws_KnowledgeId { get; set; }
public string Yws_StudentAnswer { get; set; }
public int Yws_RemoveTryCount { get; set; }
/// <summary>
/// <see cref="StudyWrongStatusEnum"/>
/// </summary>
public int Yws_Status { get; set; }
public DateTime Yws_CreateTime { get; set; }
public string CreateTimeStr => Yws_CreateTime.ToString("yyyy-MM-dd");
public DateTime BookCreateTime { get; set; }
public string BookCreateTimeStr => BookCreateTime.ToString("yyyy-MM-dd");
/// <summary>
/// 当前错题本下的所有错题
/// Yw_StudentWrongSubject 表主键Id
/// </summary>
public List<int> WrongSubjectIds { get; set; }
}
}
|
using System.Collections.Generic;
using Entitas;
[Game]
public class WeatherEffectComponent : IComponent{
public Weather Type;
public WeatherDisplayEffect Effect;
}
|
/*
Copyright © Bryan Apellanes 2015
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Bam.Net.ServiceProxy;
namespace Bam.Net.Server
{
public interface IRequestHandler
{
void HandleRequest(IHttpContext context);
}
}
|
using GM.FileDataRepositories;
using System;
using System.IO;
namespace GM.ProcessTranscript
{
public class TranscriptProcess
{
/* ProcessTranscript process new transcript files that arrive.
* It performs the following steps:
* 1. If PDF file, convert to plain text.
* 2. Make location specific fixes to convert it to a standard format.
* For example: fixes for Philadelphia, PA, USA
* 3. Convert the file to JSON format.
*/
const string WORK_FOLDER = "PreProcess";
string workFolder;
string location;
public bool Process(string filename, string meetingFolder, string language)
{
MeetingFolder mf = new MeetingFolder(filename);
//mf.SetFields(filename);
location = mf.location;
workFolder = meetingFolder + "\\" + WORK_FOLDER + "\\";
Directory.CreateDirectory(workFolder);
if (filename.ToLower().EndsWith(".pdf"))
{
return ProcessPdf(filename, language);
}
string workfile = workFolder + "2 plain-text.txt";
File.Copy(filename, workfile);
string text = File.ReadAllText(workfile);
return TextFixes(text);
}
private bool ProcessPdf(string filename, string language)
{
// Step 1 - Copy PDF to meeting workfolder
string outfile = workFolder + "1 original.pdf";
File.Copy(filename, outfile);
// Step 2 - Convert the PDF file to text
string text = ConvertPdfToText.Convert(outfile);
outfile = workFolder + "2 plain-text.txt";
File.WriteAllText(outfile, text);
return TextFixes(text);
}
private bool TextFixes(string text)
{
// Step 3 - Fix the transcript text: Put in common format
TranscriptFixes transcriptFixes = new TranscriptFixes();
string transcript = transcriptFixes.Fix(workFolder, text, location);
// Convert the fixed transcript to JSON
ConvertToJson.Convert(ref transcript);
string outfile = workFolder + "3 ToBeTagged.json";
File.WriteAllText(outfile, transcript);
return true;
}
//private void CreateWorkFolder(string meetingFolder)
//{
// workFolder = meetingFolder + "\\" + WORK_FOLDER + "\\";
// Directory.CreateDirectory(workFolder);
//}
}
}
|
// Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build darwin dragonfly freebsd netbsd openbsd
// package route -- go2cs converted at 2020 October 09 04:51:40 UTC
// import "golang.org/x/net/route" ==> using route = go.golang.org.x.net.route_package
// Original source: C:\Users\ritchie\go\src\golang.org\x\net\route\sys.go
using @unsafe = go.@unsafe_package;
using static go.builtin;
using System;
namespace go {
namespace golang.org {
namespace x {
namespace net
{
public static partial class route_package
{
private static binaryByteOrder nativeEndian = default; private static long kernelAlign = default; private static byte rtmVersion = default; private static map<long, ptr<wireFormat>> wireFormats = default;
private static void init()
{
ref var i = ref heap(uint32(1L), out ptr<var> _addr_i);
ptr<array<byte>> b = new ptr<ptr<array<byte>>>(@unsafe.Pointer(_addr_i));
if (b[0L] == 1L)
{
nativeEndian = littleEndian;
}
else
{
nativeEndian = bigEndian;
}
// might get overridden in probeRoutingStack
rtmVersion = sysRTM_VERSION;
kernelAlign, wireFormats = probeRoutingStack();
}
private static long roundup(long l)
{
if (l == 0L)
{
return kernelAlign;
}
return (l + kernelAlign - 1L) & ~(kernelAlign - 1L);
}
private partial struct wireFormat
{
public long extOff; // offset of header extension
public long bodyOff; // offset of message body
public Func<RIBType, slice<byte>, (Message, error)> parse;
}
}
}}}}
|
using System.Collections.Generic;
namespace LeadershipProfileAPI.Data.Models.ProfileSearchRequest
{
public class ProfileSearchYearsOfPriorExperience
{
public ICollection<Range> Values { get; set; }
public class Range
{
public Range() { }
public Range(int min, int max)
{
Min = min;
Max = max;
}
public int Min { get; set; }
public int Max { get; set; }
}
}
} |
using System;
namespace _9.PadawanEquipment
{
class Program
{
static void Main(string[] args)
{
double money = double.Parse(Console.ReadLine());
int studentCount = int.Parse(Console.ReadLine());
double saberPrice = double.Parse(Console.ReadLine());
double robePrice = double.Parse(Console.ReadLine());
double beltPrice = double.Parse(Console.ReadLine());
double allMoney = 0;
double saber = studentCount + Math.Ceiling(studentCount * 0.1);
double saberMoney = saber * saberPrice;
for (int i = 1; i <= studentCount; i++)
{
if (i % 6 == 0)
{
allMoney += robePrice;
}
else
{
allMoney += robePrice + beltPrice;
}
}
allMoney += saberMoney;
if (money >= allMoney)
{
Console.WriteLine($"The money is enough - it would cost {allMoney:F2}lv.");
}
else
{
Console.WriteLine($"Ivan Cho will need {allMoney-money:F2}lv more.");
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace ChristmasPi.Data.Exceptions {
class TypeMismatchException : Exception {
public TypeMismatchException() : base() { }
public TypeMismatchException(Type offendA, Type offendB) : base($"{offendA} != {offendB}") { }
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using Tensorflow;
using Tensorflow.Keras.Utils;
using Tensorflow.NumPy;
using static Tensorflow.Binding;
namespace TensorModel
{
public struct TensorFlowModelSettings
{
// input tensor name
public const string inputTensorName = "self";
// output tensor name
public const string outputTensorName = "sequential/prediction/Softmax";
}
class TensorFlowNet
{
string pbFile = @"E:\test\mobilenet_v2_140_224\frozen_graph.pb";
string labelFile = @"E:\test\mobilenet_v2_140_224\class_labels.txt";
public IEnumerable<string> Run(string img_file_name)
{
tf.compat.v1.disable_eager_execution();
var graph = new Graph();
//import GraphDef from pb file
graph.Import(pbFile);
var input_name = TensorFlowModelSettings.inputTensorName;
var output_name = TensorFlowModelSettings.outputTensorName;
var input_operation = graph.OperationByName(input_name);
var output_operation = graph.OperationByName(output_name);
var labels = File.ReadAllLines(labelFile);
var result_labels = new List<string>();
var sw = new Stopwatch();
var nd = ReadTensorFromImageFile(img_file_name);
using (var sess = tf.Session(graph))
{
// foreach (var nd in file_ndarrays)
// {
sw.Restart();
var results = sess.run(output_operation.outputs[0], (input_operation.outputs[0], nd));
var resultsSqueezed = np.squeeze(results);
//int idx = np.argmax(resultsSqueezed);
for (int idx = 0; idx < resultsSqueezed.Count(); idx++)
{
Console.WriteLine($"{labels[idx]} {resultsSqueezed[idx]}", Color.Tan);
}
Console.WriteLine($" in {sw.ElapsedMilliseconds}ms", Color.Tan);
//result_labels.Add(labels[idx]);
// }
}
return result_labels;
}
private NDArray ReadTensorFromImageFile(string file_name,
int input_height = 224,
int input_width = 224,
int input_mean = 117,
int input_std = 1)
{
var graph = tf.Graph().as_default();
var file_reader = tf.io.read_file(file_name, "file_reader");
var decodeJpeg = tf.image.decode_jpeg(file_reader, channels: 3, name: "DecodeJpeg");
var cast = tf.cast(decodeJpeg, tf.float32);
var dims_expander = tf.expand_dims(cast, 0);
var resize = tf.constant(new int[] { input_height, input_width });
var bilinear = tf.image.resize_bilinear(dims_expander, resize, true);
var sub = tf.subtract(bilinear, new float[] { input_mean });
var normalized = tf.divide(sub, new float[] { input_std });
using (var sess = tf.Session(graph))
return sess.run(normalized);
}
}
}
|
namespace System.Web.Mvc.Test {
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web.Mvc;
using System.Web.TestUtil;
using Microsoft.VisualStudio.TestTools.UnitTesting;
[TestClass]
public class ActionMethodSelectorTest {
[TestMethod]
public void AliasedMethodsProperty() {
// Arrange
Type controllerType = typeof(MethodLocatorController);
// Act
ActionMethodSelector selector = new ActionMethodSelector(controllerType);
// Assert
Assert.AreEqual(2, selector.AliasedMethods.Length);
List<MethodInfo> sortedAliasedMethods = selector.AliasedMethods.OrderBy(methodInfo => methodInfo.Name).ToList();
Assert.AreEqual("Bar", sortedAliasedMethods[0].Name);
Assert.AreEqual("FooRenamed", sortedAliasedMethods[1].Name);
}
[TestMethod]
public void ControllerTypeProperty() {
// Arrange
Type controllerType = typeof(MethodLocatorController);
ActionMethodSelector selector = new ActionMethodSelector(controllerType);
// Act & Assert
Assert.AreSame(controllerType, selector.ControllerType);
}
[TestMethod]
public void FindActionMethodReturnsMatchingMethodIfOneMethodMatches() {
// Arrange
Type controllerType = typeof(SelectionAttributeController);
ActionMethodSelector selector = new ActionMethodSelector(controllerType);
// Act
MethodInfo matchedMethod = selector.FindActionMethod(null, "OneMatch");
// Assert
Assert.AreEqual("OneMatch", matchedMethod.Name, "Method named OneMatch() should have matched.");
Assert.AreEqual(typeof(string), matchedMethod.GetParameters()[0].ParameterType, "Method overload OneMatch(string) should have matched.");
}
[TestMethod]
public void FindActionMethodReturnsMethodWithActionSelectionAttributeIfMultipleMethodsMatchRequest() {
// DevDiv Bugs 212062: If multiple action methods match a request, we should match only the methods with an
// [ActionMethod] attribute since we assume those methods are more specific.
// Arrange
Type controllerType = typeof(SelectionAttributeController);
ActionMethodSelector selector = new ActionMethodSelector(controllerType);
// Act
MethodInfo matchedMethod = selector.FindActionMethod(null, "ShouldMatchMethodWithSelectionAttribute");
// Assert
Assert.AreEqual("MethodHasSelectionAttribute1", matchedMethod.Name);
}
[TestMethod]
public void FindActionMethodReturnsNullIfNoMethodMatches() {
// Arrange
Type controllerType = typeof(SelectionAttributeController);
ActionMethodSelector selector = new ActionMethodSelector(controllerType);
// Act
MethodInfo matchedMethod = selector.FindActionMethod(null, "ZeroMatch");
// Assert
Assert.IsNull(matchedMethod, "No method should have matched.");
}
[TestMethod]
public void FindActionMethodThrowsIfMultipleMethodsMatch() {
// Arrange
Type controllerType = typeof(SelectionAttributeController);
ActionMethodSelector selector = new ActionMethodSelector(controllerType);
// Act & veriy
ExceptionHelper.ExpectException<AmbiguousMatchException>(
delegate {
selector.FindActionMethod(null, "TwoMatch");
},
@"The current request for action 'TwoMatch' on controller type 'SelectionAttributeController' is ambiguous between the following action methods:
Void TwoMatch2() on type System.Web.Mvc.Test.ActionMethodSelectorTest+SelectionAttributeController
Void TwoMatch() on type System.Web.Mvc.Test.ActionMethodSelectorTest+SelectionAttributeController");
}
[TestMethod]
public void NonAliasedMethodsProperty() {
// Arrange
Type controllerType = typeof(MethodLocatorController);
// Act
ActionMethodSelector selector = new ActionMethodSelector(controllerType);
// Assert
Assert.AreEqual(1, selector.NonAliasedMethods.Count);
List<MethodInfo> sortedMethods = selector.NonAliasedMethods["foo"].OrderBy(methodInfo => methodInfo.GetParameters().Length).ToList();
Assert.AreEqual("Foo", sortedMethods[0].Name);
Assert.AreEqual(0, sortedMethods[0].GetParameters().Length);
Assert.AreEqual("Foo", sortedMethods[1].Name);
Assert.AreEqual(typeof(string), sortedMethods[1].GetParameters()[0].ParameterType);
}
private class MethodLocatorController : Controller {
public void Foo() {
}
public void Foo(string s) {
}
[ActionName("Foo")]
public void FooRenamed() {
}
[ActionName("Bar")]
public void Bar() {
}
[ActionName("PrivateVoid")]
private void PrivateVoid() {
}
protected void ProtectedVoidAction() {
}
public static void StaticMethod() {
}
// ensure that methods inheriting from Controller or a base class are not matched
[ActionName("Blah")]
protected override void ExecuteCore() {
throw new NotImplementedException();
}
public string StringProperty {
get;
set;
}
#pragma warning disable 0067
public event EventHandler<EventArgs> SomeEvent;
#pragma warning restore 0067
}
private class SelectionAttributeController : Controller {
[Match(false)]
public void OneMatch() {
}
public void OneMatch(string s) {
}
public void TwoMatch() {
}
[ActionName("TwoMatch")]
public void TwoMatch2() {
}
[Match(true), ActionName("ShouldMatchMethodWithSelectionAttribute")]
public void MethodHasSelectionAttribute1() {
}
[ActionName("ShouldMatchMethodWithSelectionAttribute")]
public void MethodDoesNotHaveSelectionAttribute1() {
}
private class MatchAttribute : ActionMethodSelectorAttribute {
private bool _match;
public MatchAttribute(bool match) {
_match = match;
}
public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo) {
return _match;
}
}
}
}
}
|
using System;
using SeventhServices.Client.Common.Enums;
using SeventhServices.Client.Network.Models.Response.Shared;
using SeventhServices.Resource.Common.Abstractions;
namespace Seventh.Bot.Common
{
public class RobotStatus : ConfigureFile
{
public DateTime LastEventBorderDateTime { get; set; }
public OpenEventType OpenEventType { get; set; }
= OpenEventType.None;
public int SubRev { get; set; } = 3;
public Downloadconfig DownloadConfig { get; set; }
= new Downloadconfig();
}
} |
using JGL.Globals.Contracts.Validations;
using MealPlanner.Data.Auth.CustomValidations;
using MealPlanner.Data.Auth.Definitions;
using System.ComponentModel.DataAnnotations;
namespace JGL.Security.Auth.Data.Requests
{
/// <summary>
/// Recipe returns recipe model.
/// </summary>
public class CreateUserRequest
{
/// <summary>
/// email
/// </summary>
/// <example>
/// mail@examplle.com
/// </example>
[Required(ErrorMessage = MessagesValidation.ErrorRequiredMessage)]
public string Email { get; set; }
/// <summary>
/// Username
/// </summary>
/// <example>
/// jagel
/// </example>
[Required(ErrorMessage = MessagesValidation.ErrorRequiredMessage)]
public string Username { get; set; }
/// <summary>
/// Name
/// </summary>
/// <example>
/// Javier
/// </example>
[Required(ErrorMessage = MessagesValidation.ErrorRequiredMessage)]
public string Name { get; set; }
/// <summary>
/// Lastname
/// </summary>
/// <example>
/// Garcia
/// </example>
[Required(ErrorMessage = MessagesValidation.ErrorRequiredMessage)]
public string Lastname { get; set; }
/// <summary>
/// Password
/// </summary>
/// <example>
/// 12345678
/// </example>
[Required(ErrorMessage = MessagesValidation.ErrorRequiredMessage)]
public string Password { get; set; }
/// <summary>
/// Language
/// </summary>
/// <example>
/// es, en
/// </example>
[LanguageTypeValidation]
public string Language { get; set; }
}
}
|
/*
Copyright 2018 Esri
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ArcGIS.Desktop.Framework;
using ArcGIS.Desktop.Framework.Contracts;
//added references
using ArcGIS.Desktop.Core; //Project
using ArcGIS.Desktop.Layouts; //Layout class
using ArcGIS.Desktop.Framework.Threading.Tasks; //QueuedTask
using ArcGIS.Core.Geometry;
using ArcGIS.Desktop.Mapping;
using ArcGIS.Core.CIM;
namespace Layout_HelpExamples
{
// cref: MapSurroundExample;ArcGIS.Desktop.Layouts.MapSurround
#region MapSurroundExample
//Added references
using ArcGIS.Desktop.Core; //Project
using ArcGIS.Desktop.Layouts; //Layout class
using ArcGIS.Desktop.Framework.Threading.Tasks; //QueuedTask
public class MapSurroundExample
{
public static Task<bool> UpdateMapSurroundAsync(string LayoutName, string SBName, string MFName)
{
//Reference a layoutitem in a project by name
LayoutProjectItem layoutItem = Project.Current.GetItems<LayoutProjectItem>().FirstOrDefault(item => item.Name.Equals(LayoutName));
if (layoutItem == null)
return Task.FromResult(false);
return QueuedTask.Run<bool>(() =>
{
//Reference and load the layout associated with the layout item
Layout lyt = layoutItem.GetLayout();
//Reference a scale bar element by name
MapSurround scaleBar = lyt.FindElement(SBName) as MapSurround;
if (scaleBar == null)
return false;
//Reference a map frame element by name
MapFrame mf = lyt.FindElement(MFName) as MapFrame;
if (mf == null)
return false;
//Set the scale bar to the newly referenced map frame
scaleBar.SetMapFrame(mf);
return true;
});
}
}
#endregion MapSurroundExample
internal class MapSurroundClass : Button
{
async protected override void OnClick()
{
bool b = await MapSurroundExample.UpdateMapSurroundAsync("Layout Name", "Scale Bar", "Map2 Map Frame");
if (b == false)
System.Windows.MessageBox.Show("Object Not found");
}
}
}
public class TableFrameClassSamples
{
async public static void CreateNew()
{
// cref: TableFrame_CreateNew;ArcGIS.Desktop.Layouts.TableFrame
#region TableFrame_CreateNew
//Create a new table frame on the active layout.
Layout layout = LayoutView.Active.Layout;
//Perform on the worker thread
await QueuedTask.Run(() =>
{
//Build 2D envelope geometry
Coordinate2D rec_ll = new Coordinate2D(1.0, 3.5);
Coordinate2D rec_ur = new Coordinate2D(7.5, 4.5);
Envelope rec_env = EnvelopeBuilder.CreateEnvelope(rec_ll, rec_ur);
//Reference map frame
MapFrame mf = layout.FindElement("Map Frame") as MapFrame;
//Reference layer
Map m = mf.Map;
FeatureLayer lyr = m.FindLayers("GreatLakes").First() as FeatureLayer;
//Build fields list
var fields = new[] { "NAME", "Shape_Area", "Shape_Length" };
//Construct the table frame
TableFrame tabFrame = LayoutElementFactory.Instance.CreateTableFrame(layout, rec_env, mf, lyr, fields);
});
#endregion TableFrame_CreateNew
}
async public static void ModifyExisting()
{
#region TableFrame_ModifyExisting
//Modify an existing tableframe using CIM properties.
//Reference the active layout
Layout layout = LayoutView.Active.Layout;
//Perform on the worker thread
await QueuedTask.Run(() =>
{
//Reference table frame
TableFrame TF = layout.FindElement("Table Frame") as TableFrame;
//Modify CIM properties
CIMTableFrame cimTF = TF.GetDefinition() as CIMTableFrame;
cimTF.Alternate1RowBackgroundCount = 1;
cimTF.Alternate2RowBackgroundCount = 1;
//Apply the changes
TF.SetDefinition(cimTF);
});
#endregion TableFrame_ModifyExisting
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraControl : MonoBehaviour {
public List<Camera> Cameras;
public int CurrentCameraIndex = 0;
private void Start()
{
Cameras[CurrentCameraIndex].depth = 999;
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.C))
{
CurrentCameraIndex = (CurrentCameraIndex + 1) % Cameras.Count;
Cameras.ForEach(c =>
{
var index = Cameras.IndexOf(c);
if (index == CurrentCameraIndex)
{
c.depth = 999;
c.enabled = true;
// activate parent CameraHolder object
c.transform.parent.gameObject.SetActive(true);
c.GetComponentInChildren<AudioListener>().enabled = true;
}
else
{
c.depth = 0;
c.enabled = false;
// deactivate parent CameraHolder object
c.transform.parent.gameObject.SetActive(false);
c.GetComponentInChildren<AudioListener>().enabled = false;
}
});
}
}
}
|
// SPDX-License-Identifier: MIT
// Copyright © 2021 Oscar Björhn, Petter Löfgren and contributors
using System;
namespace Daf.Core.LanguageServer.Services
{
public class HoverRequest
{
public string? RootNodeName { get; set; }
public bool RootNodeSet { get { return RootNodeName != null; } }
public string? ParentNodeName { get; set; }
public bool ParentNodeSet { get { return ParentNodeName != null; } }
public string SearchText { get; set; }
public int SearchTextLine { get; set; }
public int SearchTextLineOffset { get; set; }
public HoverRequest(string searchText)
{
SearchText = searchText;
}
public HoverRequest(HoverRequest fromRequest)
{
if (fromRequest == null)
throw new ArgumentNullException(nameof(fromRequest));
SearchText = fromRequest.SearchText;
}
}
public class FieldValueHoverRequest : HoverRequest
{
public string FieldName { get; set; }
public FieldValueHoverRequest(string searchText, string fieldName) : base(searchText)
{
FieldName = fieldName;
}
public FieldValueHoverRequest(HoverRequest hoverRequest, string fieldName) : base(hoverRequest)
{
RootNodeName = hoverRequest.RootNodeName;
ParentNodeName = hoverRequest.ParentNodeName;
FieldName = fieldName;
}
}
}
|
namespace CloseTabs;
[Command(PackageIds.CloseAllTabsNotOfFileType)]
internal sealed class CloseAllTabsNotOfFileTypeCommand : BaseCommand<CloseAllTabsNotOfFileTypeCommand>
{
private IEnumerable<IVsWindowFrame> _framesToClose = Enumerable.Empty<IVsWindowFrame>();
protected override void Execute(object sender, EventArgs e)
{
ThreadHelper.ThrowIfNotOnUIThread();
_framesToClose.ToList().CloseAll();
}
protected override void BeforeQueryStatus(EventArgs e)
{
ThreadHelper.ThrowIfNotOnUIThread();
Command.Visible = false;
Command.Enabled = false;
_framesToClose = Enumerable.Empty<IVsWindowFrame>();
string? fileExtension = Services.VsMonitorSelection.GetSelectedFrame()?.GetFileExtension();
if (fileExtension is null)
{
return;
}
IEnumerable<IVsWindowFrame> documents = WindowFrameUtilities.GetAllDocumentsInActiveWindow();
_framesToClose = documents.Where(frame => frame.GetFileExtension() != fileExtension);
Command.Visible = true;
Command.Enabled = _framesToClose.Any();
Command.Text = $"Close all non-{fileExtension} Files";
}
} |
using LINQPad;
using System;
using System.Linq;
using Tessin.Bladerunner.Controls;
namespace Tessin.Bladerunner.Blades
{
public class SelectBlade : IBladeRenderer
{
private Option[] _options;
private Action<Option> _onSelect;
public SelectBlade(Option[] options, Action<Option> onSelect)
{
_options = options;
_onSelect = onSelect;
}
public object Render(Blade blade)
{
var searchBox = new SearchBox();
var refreshContainer = new RefreshPanel(new[] { searchBox }, () =>
{
return new Menu(
_options.Where(e => e.Label.StartsWith(searchBox.Text)).Select(e => new MenuButton(e.Label, (_) =>
{
_onSelect(e);
})).ToArray()
);
});
return new HeaderPanel(
Layout.Fill().Middle().Add(searchBox, "1fr").Horizontal(),
refreshContainer
);
}
}
}
|
@{
Layout = "_Layout";
}
@await Html.PartialAsync("_navbarRegister");
<div class="container mt-5">
<h3 class="text-secondary">Yetkisiz Alana Giriş Yapmaya Çalıştınız. Anasayfaya yönlendiriliyorsunuz...</h3>
</div>
@section Scripts{
<script>
window.setTimeout(function(){
window.location.href='/';
}, 3000);
</script>
} |
using Eto.Forms;
namespace Clarity.Ext.Gui.EtoForms
{
public static class FlagExtensions
{
public static bool HasFlagFast(this MouseButtons val, MouseButtons flag) { return (val & flag) != 0; }
}
} |
namespace WinLLDPService
{
using System.ComponentModel;
using System.Configuration.Install;
using System.ServiceProcess;
/// <summary>
/// The project installer.
/// </summary>
[RunInstaller(true)]
public class ProjectInstaller : Installer
{
/// <summary>
/// The service process installer.
/// </summary>
private ServiceProcessInstaller serviceProcessInstaller;
/// <summary>
/// The service installer.
/// </summary>
private ServiceInstaller serviceInstaller;
/// <summary>
/// Project installer
/// </summary>
public ProjectInstaller()
{
this.serviceProcessInstaller = new ServiceProcessInstaller();
this.serviceInstaller = new ServiceInstaller();
// Here you can set properties on serviceProcessInstaller or register event handlers
this.serviceProcessInstaller.Account = ServiceAccount.LocalService;
this.serviceInstaller.ServiceName = WinLLDPService.MyServiceName;
this.Installers.AddRange(new Installer[] { this.serviceProcessInstaller, this.serviceInstaller });
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Threading;
namespace PaintTouchBoardWindow
{
class Win32Api
{
[DllImport("user32.dll")]
public static extern bool SetCursorPos(int x, int y);
[DllImport("user32.dll", EntryPoint = "ShowWindow", SetLastError = true)]
public static extern bool ShowWindow(IntPtr hWnd, uint nCmdShow);
[DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll")]
public static extern UInt32 SendInput(UInt32 nInputs,Win32Struct.Input[] pInputs, int cbSize);
[DllImport("user32.dll")]
public static extern void mouse_event(
int dwFlags, int dx, int dy, int dwData, IntPtr dwExtraInfo);
[DllImport("user32.dll", EntryPoint = "SetForegroundWindow")]
public static extern bool SetForegroundWindow(IntPtr hWnd);//设置此窗体为活动窗体
[DllImport("user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto, ExactSpelling = true)]
public static extern IntPtr GetForegroundWindow(); //获得本窗体的句柄
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern int SetWindowPos(IntPtr hWnd, int hWndInsertAfter,
int x, int y, int Width, int Height, int flags);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern bool GetWindowRect(IntPtr hWnd, ref Win32Struct.RECT lpRect);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern bool ScreenToClient(IntPtr hWnd, ref Win32Struct.POINT lpPoint);
}
}
|
using Amica.Models;
using FluentValidation;
namespace Amica.Validation
{
public class PaymentMethodValidator : AbstractValidator<Models.PaymentMethod>
{
public PaymentMethodValidator()
{
RuleFor(method => method.Name).NotEmpty();
RuleFor(method => method.Code)
.NotEmpty()
.Must(BeValidPaymentMethod);
}
private static bool BeValidPaymentMethod(string challenge)
{
if (challenge == string.Empty) return true;
foreach (var method in PaymentHelpers.PaymentMethods)
{
if (method.Code == challenge) return true;
}
return false;
}
}
} |
using UnityEngine;
using UnityEngine.UI;
using Netherlands3D.LayerSystem;
using Netherlands3D.ObjectInteraction;
namespace Netherlands3D.Interface.SidePanel
{
public class SelectionOutliner : MonoBehaviour
{
private string id = "";
private string title = "";
[SerializeField]
private Text titleText;
private GameObject linkedGameObject;
public GameObject LinkedGameObject { get => linkedGameObject; set => linkedGameObject = value; }
public string Id { get => id; set => id = value; }
public string Title {
get => title;
set
{
title = value;
titleText.text = title;
}
}
private void Update()
{
if (!LinkedGameObject) Close();
}
public void Link(GameObject targetGameObject, string title, string id = "")
{
linkedGameObject = targetGameObject;
Title = title;
Id = id;
}
public void Select()
{
var selectByID = linkedGameObject.GetComponent<SelectByID>();
if (selectByID)
{
selectByID.ShowBAGDataForSelectedID(Id);
return;
}
}
public void Close()
{
//Did we close a SelectByID selection?
var selectByID = linkedGameObject.GetComponent<SelectByID>();
if (selectByID)
{
selectByID.DeselectSpecificID(Id);
return;
}
//Maybe another simple interactable?
var selectable = linkedGameObject.GetComponent<Interactable>();
if (selectable)
{
selectable.Deselect();
}
}
}
} |
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Nuuvify.CommonPack.Domain.Interfaces;
using Nuuvify.CommonPack.Extensions.Notificator;
namespace Nuuvify.CommonPack.Domain
{
public abstract class BaseValidation<TEntity, TValidation> : NotifiableR,
IValidation<TEntity, TValidation>
where TEntity : DomainEntity
where TValidation : class
{
public abstract Task Valid(TEntity entity);
public IList<NotificationR> ValidationResult()
{
return (IList<NotificationR>)Notifications.ToList();
}
}
}
|
using System.Text.RegularExpressions;
namespace SmartHomeWWW.Core.Utils
{
public static class RegexExtensions
{
public static bool TryMatch(this Regex regex, string text, out Match match)
{
match = regex.Match(text);
return match.Success;
}
public static bool TryMatch(this Regex regex, string text, string groupName, out string value)
{
var match = regex.Match(text);
if (match.Success)
{
value = match.Groups[groupName].Value;
return true;
}
value = string.Empty;
return false;
}
}
}
|
using System.Collections.Generic;
using UnityEngine;
public class HeroManager : MonoBehaviour
{
public float FOV;
public float attackRange;
[HideInInspector]
public static Dictionary<string, Color> fieldDebugColors;
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Timers;
namespace Website.Components.DataTable
{
public partial class DataTable<TItem>
{
public OrderByModel CurrentOrder { get; set; } = new OrderByModel();
public class OrderByModel
{
public DataTableColumn<TItem> Column { get; set; }
public bool Asc { get; set; }
}
public void OrderBy(DataTableColumn<TItem> column)
{
searchTimer.Stop();
isLoading = true;
if (CurrentOrder.Column == column)
{
CurrentOrder.Asc = !CurrentOrder.Asc;
} else
{
CurrentOrder.Column = column;
CurrentOrder.Asc = true;
}
StateHasChanged();
searchTimer.Start();
}
public void ApplyOrder(ref IEnumerable<TItem> data)
{
if (CurrentOrder.Column == null)
{
return;
}
if (CurrentOrder.Asc)
{
data = data.OrderBy(x => CurrentOrder.Column.GetValue(x));
return;
}
data = data.OrderByDescending(x => CurrentOrder.Column.GetValue(x));
}
}
}
|
@model Sporty.ViewModel.ExerciseDetailsView
@{
ViewBag.Title = "Neue Einheit";
}
<h2>Neue Einheit</h2>
@Html.Partial("_Edit") |
using System.Linq;
using System.Threading.Tasks;
using Marten.Testing.Documents;
using Marten.Testing.Harness;
using Shouldly;
using Weasel.Core;
using Weasel.Postgresql;
using Xunit;
namespace DocumentDbTests.Bugs
{
public class Bug_336_completely_remove_crosses_schema_lines : BugIntegrationContext
{
[Fact]
public async Task do_not_remove_items_out_of_the_main_schema()
{
var store1 = theStore;
await store1.BulkInsertAsync(Target.GenerateRandomData(5).ToArray());
await store1.BulkInsertAsync(new[] { new User() });
var database1 = store1.Tenancy.Default.Database;
(await database1.DocumentTables()).Any().ShouldBeTrue();
var store2 = SeparateStore(_ =>
{
_.AutoCreateSchemaObjects = AutoCreate.All;
_.DatabaseSchemaName = "other_bug";
});
await store2.BulkInsertAsync(Target.GenerateRandomData(5).ToArray());
await store2.BulkInsertAsync(new[] { new User() });
var database2 = store2.Tenancy.Default.Database;
(await database2.DocumentTables()).Any().ShouldBeTrue();
await store1.Advanced.Clean.CompletelyRemoveAllAsync();
(await database1.DocumentTables()).Any().ShouldBeFalse();
(await database2.DocumentTables()).Any().ShouldBeTrue();
}
}
}
|
//
// Encog(tm) Core v3.2 - .Net Version
// http://www.heatonresearch.com/encog/
//
// Copyright 2008-2014 Heaton Research, 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.
//
// For more information on Heaton Research copyrights, licenses
// and trademarks visit:
// http://www.heatonresearch.com/copyright
//
using System;
using System.Collections.Generic;
using Encog.App.Analyst.CSV.Basic;
namespace Encog.App.Quant.Indicators
{
/// <summary>
/// An indicator, used by Encog.
/// </summary>
public abstract class Indicator : BaseCachedColumn
{
/// <summary>
/// Construct the indicator.
/// </summary>
/// <param name="name">The indicator name.</param>
/// <param name="input">Is this indicator used to predict?</param>
/// <param name="output">Is this indicator what we are trying to predict.</param>
public Indicator(String name, bool input,
bool output) : base(name, input, output)
{
}
/// <value>the beginningIndex to set</value>
public int BeginningIndex { get; set; }
/// <value>the endingIndex to set.</value>
public int EndingIndex { get; set; }
/// <value>The number of periods this indicator is for.</value>
public abstract int Periods { get; }
/// <summary>
/// Calculate this indicator.
/// </summary>
/// <param name="data">The data available to this indicator.</param>
/// <param name="length">The length of data to use.</param>
public abstract void Calculate(IDictionary<String, BaseCachedColumn> data,
int length);
/// <summary>
/// Require a specific type of underlying data.
/// </summary>
/// <param name="theData">The data available.</param>
/// <param name="item">The type of data we are looking for.</param>
public void Require(IDictionary<String, BaseCachedColumn> theData,
String item)
{
if (!theData.ContainsKey(item))
{
throw new QuantError(
"To use this indicator, the underlying data must contain: "
+ item);
}
}
}
}
|
using System;
using Argotic.Common;
namespace Argotic.Syndication.Specialized
{
/// <summary>
/// Represents the permissible types of a web log post.
/// </summary>
[Serializable()]
public enum BlogMLPostType
{
/// <summary>
/// No post type specified.
/// </summary>
[EnumerationMetadata(DisplayName = "", AlternateValue = "")]
None = 0,
/// <summary>
/// Indicates that the post represents an article.
/// </summary>
[EnumerationMetadata(DisplayName = "Article", AlternateValue = "article")]
Article = 1,
/// <summary>
/// Indicates that the post represents web log entry.
/// </summary>
[EnumerationMetadata(DisplayName = "Normal", AlternateValue = "normal")]
Normal = 2
}
} |
using day_4_part_1;
List<string> input = File.ReadAllLines(args[0]).ToList();
var numbers = input[0].Split(',').Select(x => int.Parse(x));
List<BingoBoard> bingoBoards = new();
for(int i = 2; i + BingoBoard.BINGO_SIZE <= input.Count; i+= BingoBoard.BINGO_SIZE + 1)
{
var bingoLines = input.GetRange(i, BingoBoard.BINGO_SIZE);
bingoBoards.Add(Utils.ReadBingoBoard(bingoLines.ToArray()));
}
foreach(int number in numbers)
{
foreach(BingoBoard board in bingoBoards)
{
var unmarkedSum = board.MarkNumber(number);
if(unmarkedSum > 0)
{
Console.WriteLine(unmarkedSum * number);
return;
}
}
} |
namespace TasksEverywhere.DataLayer.Context.Abstract
{
public interface IConnection
{
T GetProperty<T>(string key);
}
} |
using System.Reflection;
namespace SocketFlow
{
public struct HandlerInfo
{
public MethodInfo Method;
public object Target;
public HandlerInfo(MethodInfo method, object target)
{
Method = method;
Target = target;
}
}
}
|
using GVFS.Common;
using GVFS.Tests.Should;
using GVFS.UnitTests.Category;
using GVFS.UnitTests.Mock.Common;
using GVFS.UnitTests.Windows.Mock.Upgrader;
using NUnit.Framework;
using System;
using System.Collections.Generic;
namespace GVFS.UnitTests.Windows.Upgrader
{
public abstract class UpgradeTests
{
protected const string OlderThanLocalVersion = "1.0.17000.1";
protected const string LocalGVFSVersion = "1.0.18115.1";
protected const string NewerThanLocalVersion = "1.1.18115.1";
protected MockTracer Tracer { get; private set; }
protected MockTextWriter Output { get; private set; }
protected MockInstallerPrerunChecker PrerunChecker { get; private set; }
protected MockProductUpgrader Upgrader { get; private set; }
public virtual void Setup()
{
this.Tracer = new MockTracer();
this.Output = new MockTextWriter();
this.PrerunChecker = new MockInstallerPrerunChecker(this.Tracer);
this.Upgrader = new MockProductUpgrader(LocalGVFSVersion, this.Tracer);
this.PrerunChecker.Reset();
this.Upgrader.PretendNewReleaseAvailableAtRemote(
upgradeVersion: NewerThanLocalVersion,
remoteRing: ProductUpgrader.RingType.Slow);
this.Upgrader.LocalRingConfig = ProductUpgrader.RingType.Slow;
}
[TestCase]
public virtual void NoneLocalRing()
{
string message = "Upgrade ring set to \"None\". No upgrade check was performed.";
this.ConfigureRunAndVerify(
configure: () =>
{
this.Upgrader.LocalRingConfig = ProductUpgrader.RingType.None;
},
expectedReturn: ReturnCode.Success,
expectedOutput: new List<string>
{
message
},
expectedErrors: new List<string>
{
});
}
[TestCase]
public virtual void InvalidUpgradeRing()
{
string errorString = "Invalid upgrade ring `Invalid` specified in gvfs config.";
this.ConfigureRunAndVerify(
configure: () =>
{
this.Upgrader.LocalRingConfig = GVFS.Common.ProductUpgrader.RingType.Invalid;
},
expectedReturn: ReturnCode.GenericError,
expectedOutput: new List<string>
{
errorString
},
expectedErrors: new List<string>
{
errorString
});
}
[TestCase]
[Category(CategoryConstants.ExceptionExpected)]
public virtual void FetchReleaseInfo()
{
string errorString = "Error fetching upgrade release info.";
this.ConfigureRunAndVerify(
configure: () =>
{
this.Upgrader.SetFailOnAction(MockProductUpgrader.ActionType.FetchReleaseInfo);
},
expectedReturn: ReturnCode.GenericError,
expectedOutput: new List<string>
{
errorString
},
expectedErrors: new List<string>
{
errorString
});
}
protected abstract ReturnCode RunUpgrade();
protected void ConfigureRunAndVerify(
Action configure,
ReturnCode expectedReturn,
List<string> expectedOutput,
List<string> expectedErrors)
{
configure();
this.RunUpgrade().ShouldEqual(expectedReturn);
if (expectedOutput != null)
{
this.Output.AllLines.ShouldContain(
expectedOutput,
(line, expectedLine) => { return line.Contains(expectedLine); });
}
if (expectedErrors != null)
{
this.Tracer.RelatedErrorEvents.ShouldContain(
expectedErrors,
(error, expectedError) => { return error.Contains(expectedError); });
}
}
}
}
|
using System.Collections.Generic;
using NCore.Demo.Domain;
using NCore.Demo.Utilities;
using NCore.Extensions;
using NCore.Web.Commands;
using NCore.Web.Utilities;
using NHibernate;
namespace NCore.Demo.Commands
{
public class OrderLineUpdater : BaseUpdater<OrderLine>
{
private readonly IPropertyHelper _propertyHelper;
public OrderLineUpdater(long id, IDictionary<string, object> dto)
: base(id)
{
_propertyHelper = new DictionaryHelper(dto);
}
protected override bool TrySetProperties(ISession session, OrderLine entity, out IEnumerable<string> errors)
{
var setter = new EntitySetter<OrderLine>(_propertyHelper, entity);
setter.UpdateSimpleProperty(e => e.Index, (o, n) =>
{
var otherLines = session.QueryOver<OrderLine>()
.Where(ol => ol.Order == entity.Order)
.And(ol => ol.Id != entity.Id)
.List();
new OrderLineIndexHandler().AdjustIndexes(entity, n, otherLines);
});
setter.UpdateSimpleProperty(e => e.Total);
setter.UpdateSimpleProperty(e => e.Description);
return this.Success(out errors);
}
}
} |
using FlightReportApp.API.Model;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace FlightReportApp.API.Controllers
{
[ApiController]
[Route("api/v1/[controller]")]
public class FlightController : ControllerBase
{
private readonly FlightReportAppDbContext _flightReportAppDbContext;
private readonly ILogger<FlightController> _logger;
public FlightController(ILogger<FlightController> logger, FlightReportAppDbContext flightReportAppDbContext)
{
_logger = logger;
_flightReportAppDbContext = flightReportAppDbContext;
}
[HttpGet]
public ActionResult<IEnumerable<Flight>> GetFlights()
{
return Ok(_flightReportAppDbContext.Flights.ToList());
}
[HttpGet("{id}")]
public ActionResult<Flight> GetFlightById(int id)
{
var flight = _flightReportAppDbContext.Flights.FirstOrDefault(x => x.Id == id);
if (flight != null)
{
return Ok(flight);
}
return NotFound();
}
[HttpPost]
public ActionResult<Flight> CreateAirport(Flight flight)
{
_flightReportAppDbContext.Flights.Add(flight);
if (_flightReportAppDbContext.SaveChanges() > 0)
{
return Ok(flight);
}
return BadRequest();
}
[HttpPut("{id}")]
public ActionResult<Flight> UpdateFlight(int id, Flight flight)
{
if (id != flight.Id)
{
return BadRequest();
}
var existingFlight = _flightReportAppDbContext.Flights.FirstOrDefault(x => x.Id == id);
if (existingFlight == null)
{
return NotFound();
}
_flightReportAppDbContext.Flights.Update(flight);
return Ok(flight);
}
[HttpDelete("{id}")]
public ActionResult DeleteFlight(int id)
{
var flight = _flightReportAppDbContext.Flights.FirstOrDefault(x => x.Id == id);
if (flight != null)
{
_flightReportAppDbContext.Flights.Remove(flight);
return Ok();
}
return NotFound();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Methods
{
class Program
{
static void Main(string[] args)
{
Add();
Add2(20, 30);
var result = Add3(20, 20);
Console.WriteLine("Add3: {0}", result);
var result2 = Add4(20);
Console.WriteLine("Add4: {0}", result2);
int number1 = 20;
int number2 = 100;
var result3 = Add5(ref number1, number2);
Console.WriteLine("Add5: {0}", result3);
Console.WriteLine("number1: {0}", number1);
int number3;
int number4 = 50;
var result4 = Add6(out number3, number4);
Console.WriteLine("Add5: {0}", result4);
Console.WriteLine("number1: {0}", number3);
Console.WriteLine(multiply(2, 4));
Console.WriteLine(multiply(2, 4, 5));
Console.WriteLine(add7(1, 2, 3, 4, 5, 6));
Console.ReadKey();
}
//void method
static void Add()
{
Console.WriteLine("Added!");
}
//void method with parameter
static void Add2(int number1, int number2)
{
Console.WriteLine("Result: {0}", number1 + number2);
}
//int method with parameter
static int Add3(int number1, int number2)
{
var result = number1 + number2;
return result;
}
//parameter with default value
static int Add4(int number1, int number2 = 40)
{
var result = number1 + number2;
return result;
}
//method with reference parameter
static int Add5(ref int number1, int number2)
{
number1 = 30;
return number1 + number2;
}
//method with out parameter
static int Add6(out int number1, int number2)
{
number1 = 30;
return number1 + number2;
}
//method overloading
static int multiply(int number1, int number2)
{
return number1 * number2;
}
//method overloading
static int multiply(int number1, int number2, int number3)
{
return number1 * number2 * number3;
}
//params
static int add7(params int[] numbers)
{
return numbers.Sum();
}
}
}
|
namespace Nodsoft.Wargaming.Api.Common.Data.Responses;
public record ResponseMeta
{
public int? Count { get; init; }
} |
using System;
using TrackMyWristAPI.Models;
namespace TrackMyWristAPI.Dtos.Watch
{
public class AddWatchDto
{
public string Manufacturer { get; set; }
public string ModelName { get; set; }
public string ModelNumber { get; set; }
public string Mechanism { get; set; }
public int Diameter { get; set; }
public int LugToLug { get; set; }
public int LugWidth { get; set; }
public int LiftAngle { get; set; }
public WatchType Type { get; set; }
}
} |
using MiniFac.Contract;
using MiniFac.Core.Lifetime;
using System;
using System.Linq;
namespace MiniFac.Core.Registration
{
public class ComponentRegistration : IComponentRegistration
{
public Guid Id { get; }
public IInstanceActivator Activator { get; }
public IComponentLifetime Lifetime { get; }
public InstanceSharing Sharing { get; }
public Service[] Services { get; }
public ComponentRegistration(IInstanceActivator activator, params Service[] services)
:this(Guid.NewGuid(), activator, new CurrentLifetimeScope(), InstanceSharing.None, services) { }
public ComponentRegistration(
Guid id,
IInstanceActivator activator,
IComponentLifetime lifetime,
InstanceSharing sharing,
params Service[] services)
{
Id = id;
Activator = activator;
Lifetime = lifetime;
Sharing = sharing;
Services = services.ToArray();
}
}
}
|
using CoderCMS.Alogrithm.Common;
namespace ReverserFullLinkedList206
{
/// <summary>
/// 206. Reverse Linked List: https://leetcode.com/problems/reverse-linked-list/
/// </summary>
public class Solution
{
/// <summary>
/// Solution #1: Recursive.
/// </summary>
/// <param name="head"></param>
/// <returns></returns>
public ListNode ReverseList(ListNode head)
{
if(head == null || head.next == null) return head;
ListNode last = ReverseList(head.next);
head.next.next = head;
head.next = null;
return last;
}
/// <summary>
/// Solution #2: iterative.
/// </summary>
/// <param name="head"></param>
/// <returns></returns>
public ListNode ReverseListTwo(ListNode head)
{
ListNode current = head;
ListNode prev = null;
while (current != null)
{
(current.next, prev, current) = (prev, current, current.next);
// var tmpCurrent = current;
// var tmpNext = current.next;
// current.next = prev;
// prev = tmpCurrent;
// current = tmpNext;
}
return prev;
}
}
} |
using System;
using System.Collections.Generic;
using Csla;
using Codisa.InterwayDocs.DataAccess;
namespace Codisa.InterwayDocs.Business
{
/// <summary>
/// EditOnDemandBase (base class).<br/>
/// This is a generated <see cref="EditOnDemandBase{T}"/> base classe.
/// </summary>
[Serializable]
public abstract partial class EditOnDemandBase<T> : BusinessBase<T>
where T : EditOnDemandBase<T>
{
#region Business Properties
#endregion
}
}
|
namespace DXPlus;
/// <summary>
/// Valid image content types which may be inserted into a
/// document.
/// </summary>
public static class ImageContentType
{
/// <summary>
/// Tiff
/// </summary>
public static string Tiff => "image/tif";
/// <summary>
/// PNG
/// </summary>
public static string Png => "image/png";
/// <summary>
/// GIF
/// </summary>
public static string Gif => "image/gif";
/// <summary>
/// JPG
/// </summary>
public static string Jpg => "image/jpg";
/// <summary>
/// JPEG
/// </summary>
public static string Jpeg => "image/jpeg";
/// <summary>
/// SVG
/// </summary>
public static string Svg => "image/svg";
} |
@model OperationDetails
@{
string colorClass = Model.Status == OperationStatus.Success ? "alert-success" : "alert-danger";
}
<div class="notification alert alert-dismissible fade in @colorClass">
<button class="close" type="button" data-dismiss="alert">
<span>×</span>
</button>
@Model.Message
</div>
|
/*
* Identity role repository interface.
*
* @author Michel Megens
* @email michel.megens@sonatolabs.com
*/
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using SensateIoT.API.Common.IdentityData.Models;
namespace SensateIoT.API.Common.Core.Infrastructure.Repositories
{
public interface IUserRoleRepository
{
void Create(SensateRole role);
Task CreateAsync(SensateRole role, CancellationToken ct = default);
void Create(string name, string description);
Task CreateAsync(string name, string description);
void Delete(string name);
Task DeleteAsync(string name);
Task UpdateAsync(string name, SensateRole role);
void Update(string name, SensateRole role);
Task<SensateRole> GetByNameAsync(string name);
SensateRole GetById(string id);
SensateRole GetByName(string name);
IEnumerable<SensateUser> GetUsers(string id);
IEnumerable<string> GetRolesFor(SensateUser user);
Task<IEnumerable<string>> GetRolesForAsync(SensateUser user);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace Totem
{
/// <summary>
/// Describes a context in which events occur on the same timeline
/// </summary>
public interface IClock : IClean
{
DateTime Now { get; }
}
} |
using UnityEngine;
using System.Collections;
public class Tile : MonoBehaviour {
//Types 1 : Straight, 2 : Right, 3 : Left, 4 Straight Right, 5 Straight Left, 6 Left Right, 7 All
public int Turns;
public int GetTurns () {
return Turns;
}
}
|
namespace SpaceEngineers.Core.DataAccess.Orm.Model
{
using AutoRegistration.Api.Abstractions;
/// <summary>
/// IModelValidator
/// </summary>
public interface IModelValidator : IResolvable
{
/// <summary>
/// Validates database model
/// </summary>
/// <param name="model">Model</param>
public void Validate(DatabaseNode model);
}
} |
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) 2006 Microsoft Corporation. All rights reserved.
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Xml;
using Microsoft.Feeds.Interop;
namespace Microsoft.Samples.RssPlatform.ScreenSaver.Rss
{
/// <summary>
/// Representation of an RSS element in a RSS 2.0 XML document
/// </summary>
public class RssFeed : UI.IItem
{
private readonly string title;
private readonly string link;
private readonly string description;
private readonly string path;
private readonly DateTime lastWriteTime;
private List<RssItem> items;
public string Title { get { return title; } }
public string Link { get { return link; } }
public string Description { get { return description; } }
public string Path { get { return path; } }
public DateTime LastWriteTime { get { return lastWriteTime; } }
public IList<RssItem> Items { get { return items.AsReadOnly(); } }
/// <summary>
/// Private constructor to be used with factory pattern.
/// </summary>
/// <exception cref="System.Xml.XmlException">Occurs when the XML is not well-formed.</exception>
/// <param name="xmlNode">An XML block containing the RSSFeed content.</param>
private RssFeed(XmlNode xmlNode)
{
XmlNode channelNode = xmlNode.SelectSingleNode("rss/channel");
items = new List<RssItem>();
title = channelNode.SelectSingleNode("title").InnerText;
link = channelNode.SelectSingleNode("link").InnerText;
description = channelNode.SelectSingleNode("description").InnerText;
XmlNodeList itemNodes = channelNode.SelectNodes("item");
foreach (XmlNode itemNode in itemNodes)
{
RssItem rssItem = new RssItem(itemNode);
// only add items that have enclosures
if (rssItem.Enclosure != null)
items.Add(rssItem);
}
}
private RssFeed(IFeed feed)
{
items = new List<RssItem>();
title = feed.Title;
link = feed.Link;
description = feed.Description;
path = feed.Path;
lastWriteTime = feed.LastWriteTime;
foreach (IFeedItem item in (IFeedsEnum)feed.Items)
{
RssItem rssItem = new RssItem(item);
// only add items that have enclosures
if (rssItem.Enclosure != null)
items.Add(rssItem);
}
}
/// <summary>
/// Factory that constructs RSSFeed objects from a uri pointing to a valid RSS 2.0 XML file.
/// </summary>
/// <exception cref="System.Net.WebException">Occurs when the uri cannot be located on the web.</exception>
/// <param name="uri">The URL to read the RSS feed from.</param>
/// <example>
/*
* try
{
Uri url = new Uri("http://localhost/feed.rss");
RssFeed.FromUri(url);
}
catch (UriFormatException ex)
{
MessageBox.Show(ex.Message, "Not a valid Url", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
catch (System.Net.WebException ex)
{
MessageBox.Show(ex.Message, "Failed to get Url", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
catch (System.Xml.XmlException ex)
{
MessageBox.Show(ex.Message, "Not a valid RSS feed.", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
MessageBox.Show("Valid RSS feed.", "Valid RSS feed.", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
*/
/// </example>
public static RssFeed FromUri(Uri uri)
{
XmlDocument xmlDoc;
WebClient webClient = new WebClient();
using (Stream rssStream = webClient.OpenRead(uri))
{
TextReader textReader = new StreamReader(rssStream);
XmlTextReader reader = new XmlTextReader(textReader);
xmlDoc = new XmlDocument();
xmlDoc.Load(reader);
}
return new RssFeed(xmlDoc);
}
/// <summary>
/// Factory to construct the RSSFeed object from the Windows RSS Platform API
/// </summary>
/// <param name="feed">The Common Feed List feed object</param>
/// <returns>An initialized RSSFeed object</returns>
internal static RssFeed FromApi(IFeed feed)
{
RssFeed rssFeed = null;
// Skip this feed if there are not items.
if (feed != null
&& ((IFeedsEnum)feed.Items).Count > 0)
rssFeed = new RssFeed(feed);
return rssFeed;
}
/// <summary>
/// Factory that constructs RssFeed objects from the text of an RSS 2.0 XML file.
/// </summary>
/// <param name="rssText">A string containing the XML for the RSS feed.</param>
public static RssFeed FromText(string rssText)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(rssText);
return new RssFeed(xmlDoc);
}
}
} |
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
namespace WeeklyXamarin.Core.Models
{
public record Index
{
public DateTime UpdatedTimeStamp { get; init; }
public List<Edition> Editions { get; init; }
public DateTime FetchedDate { get; set; }
[JsonIgnore]
public bool IsStale => FetchedDate < DateTime.UtcNow.AddMinutes(-5);
}
}
|
using System.IO.Abstractions;
namespace Ingestor.MacOS;
public class MacOsDriveAttachedNotifier : IDriveAttachedNotifier
{
public event EventHandler<DriveAttachedEventArgs>? DriveAttached;
public MacOsDriveAttachedNotifier(ILogger<MacOsDriveAttachedNotifier> logger, IFileSystem fileSystem)
{
var watcher = fileSystem.FileSystemWatcher.CreateNew("/Volumes/");
watcher.NotifyFilter = NotifyFilters.DirectoryName;
watcher.Deleted += (sender, e) =>
{
logger.LogInformation("Got filesystem delete notification: {name}", e.FullPath);
};
watcher.Renamed += (sender, e) =>
{
logger.LogInformation("Got filesystem rename notification: {name}", e.FullPath);
};
watcher.Changed += async (sender, e) =>
{
logger.LogInformation("Got filesystem changed notification: {name}", e.FullPath);
};
watcher.Error += (sender, e) =>
{
logger.LogError(e.GetException(), "Error from FileSystemWatcher");
};
watcher.Created += async (sender, e) =>
{
logger.LogInformation("Got filesystem created notification: {name}", e.FullPath);
if (string.IsNullOrEmpty(e.FullPath))
{
return;
}
IDriveInfo driveInfo;
try
{
driveInfo = new DriveInfoWrapper(fileSystem, new DriveInfo(e.FullPath));
}
catch (ArgumentException ex)
{
logger.LogWarning(ex, "Drive '{name}' does not seem to be valid", e.Name);
return;
}
if (DriveAttached != null)
{
await Task.Delay(100);
DriveAttached.Invoke(this, new DriveAttachedEventArgs(driveInfo));
}
};
watcher.EnableRaisingEvents = true;
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.