text stringlengths 13 6.01M |
|---|
using UnityEngine;
using System.Collections;
public class bulletManager : MonoBehaviour {
public int bulletSpeed = 1000;
public int bulletDamage = 25;
public int bulletAliveTime = 8;
Rigidbody rigid;
Vector3 movement;
// Use this for initialization
void Start () {
rigid = this.gameObject.GetComponent<Rigidbody>();
Invoke("RemoveObject", bulletAliveTime);
}
void OnCollisionEnter (Collision col)
{
if (col.gameObject.tag == "Enemy")
{
// Insert damage logic
enemyController enemycontroller = col.gameObject.GetComponent<enemyController>();
enemycontroller.takeDamage(bulletDamage);
}
Destroy(this.gameObject);
}
// Update is called once per frame
void Update () {
Move();
}
void Move()
{
rigid.velocity = transform.right * bulletSpeed * Time.deltaTime;
}
void RemoveObject()
{
Destroy(this.gameObject);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DataAccess.NHibernateHelper;
using Domain.Entity;
using DataAccess.AbstractRepository;
using NHibernate;
namespace DataAccess.Repository
{
public class RefundRepository : NHibRepository<Refund>, IRefundRepository
{
public RefundRepository(NHibContext context)
: base(context)
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data;
using System.Xml;
namespace ServiceManager
{
public class XMLClass
{
/// <summary>
/// 读取服务列表
/// </summary>
/// <returns></returns>
public static DataSet GetServiceList()
{
string path = Application.StartupPath + "\\Service.xml";
DataSet ds = new DataSet();
ds.ReadXml(path);
return ds;
}
/// <summary>
/// 读取服务的配置文件
/// </summary>
/// <param name="pFileName">配置文件名称</param>
/// <returns></returns>
public static DataSet GetAppConfig(string pFileName)
{
string path = Application.StartupPath + "\\" + pFileName;
DataSet ds = new DataSet();
ds.ReadXml(path);
return ds;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Paypal_API.Models
{
public class TransactionModel
{
public string name { get; set; }
public string Street1 { get; set; }
public string Street2 { get; set; }
public string CityName { get; set; }
public string StateOrProvince { get; set; }
public string Country { get; set; }
public string PostalCode { get; set; }
public string Phone { get; set; }
public string ItemName { get; set; }
public string ItemQuentity { get; set; }
public string ItemDescription { get; set; }
public string PaymentAction { get; set; }
public string BillingAgreement { get; set; }
public string BillingType { get; set; }
public string ItemAmount { get; set; }
public decimal OrderTotal { get; set; }
public string InsurenceTotal { get; set; }
public string HandlingTotal { get; set; }
public string TaxTotal { get; set; }
public string ShippingTotalCost { get; set; }
public string OrderDescription { get; set; }
// public decimal ShippingTotal { get; set; }
public Int32? Quantity { get; set; }
public string ReturnURL { get; set; }
public string CancelURL { get; set; }
public string BuyerEmail { get; set; }
public string ReqConfirmShipping { get; set; }
public string ItemCategory { get; set; }
public string SalesTax { get; set; }
public string ipnNotificationUrl { get; set; }
public string CurrencyCode { get; set; }
public string ItemCost { get; set; }
public string PayerName { get; set; }
public string TransactionType { get; set; }
public string NetAmount { get; set; }
public string GrossAmount { get; set; }
public string TransactionId { get; set; }
public string TransactionStatus { get; set; }
public string Time { get; set; }
public string ProfileId { get; set; }
public string status { get; set; }
public string Paymentstatus { get; set; }
public string PayerId { get; set; }
}
} |
namespace FlWaspMigrator.Support
{
public interface IStaticData
{
byte[] GetWaspFlFst();
byte[] GetWaspVstFst();
}
} |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
namespace Microsoft.EntityFrameworkCore
{
/// <summary>
/// Marks a type as keyless entity.
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
public sealed class KeylessAttribute : Attribute
{
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace LoggerProxy.App.Controllers
{
[ApiController]
[Route("[controller]")]
public class FooController : ControllerBase
{
private readonly IFooService fooService;
public FooController(IFooService fooService)
{
this.fooService = fooService;
}
[HttpGet]
public string Foo()
{
return this.fooService.Foo();
}
}
}
|
namespace UserVoiceSystem.Web.ViewModels.Comments
{
using System;
using System.Web.Mvc;
using Data.Models;
using Infrastructure.Mapping;
public class CommentGetViewModel : IMapFrom<Comment>
{
[HiddenInput(DisplayValue = false)]
public int Id { get; set; }
public string Content { get; set; }
public string AuthorEmail { get; set; }
public int IdeaId { get; set; }
public DateTime CreatedOn { get; set; }
}
}
|
namespace Kraken.Services
{
using System;
using Microsoft.Extensions.OptionsModel;
using Octopus.Client;
using Octopus.Client.Model;
public class OctopusAuthenticationProxy : IOctopusAuthenticationProxy
{
public OctopusAuthenticationProxy(IOptions<AppSettings> settings)
{
if (settings == null) throw new ArgumentNullException(nameof(settings));
var endpoint = new OctopusServerEndpoint(settings.Value.OctopusServerAddress);
_repository = new OctopusRepository(endpoint);
}
public bool Login(string userName, string password)
{
var loginCommand = new LoginCommand()
{
Username = userName,
Password = password
};
try
{
_repository.Users.SignIn(loginCommand);
}
catch
{
return false;
}
return true;
}
public string CreateApiKey()
{
var apiKeyResource = _repository.Users.CreateApiKey(_repository.Users.GetCurrent(), "Kraken");
return apiKeyResource.ApiKey;
}
private readonly OctopusRepository _repository;
}
}
|
using System;
using Common;
using Common.Geometry;
using OcTreeLibrary;
using OpenTK;
using SimpleShooter.Graphics;
namespace SimpleShooter.Core
{
public class GameObject : IOctreeItem
{
public long Id { get; set; }
public SimpleModel Model { get; set; }
public ShadersNeeded ShaderKind { get; set; }
public GameObject(SimpleModel model, ShadersNeeded shadersNeeded)
{
Id = IdService.GetNext();
ShaderKind = shadersNeeded;
Model = model;
BoundingBox = BoundingVolume.InitBoundingBox(Model.Vertices);
}
public void CalcNormals()
{
Model.Normals = GetNormals(Model.Vertices);
}
private Vector3[] GetNormals(Vector3[] points)
{
var normals = new Vector3[points.Length];
var tempVertices = new Vector3[3];
for (int i = 0; i < points.Length; i += 6)
{
tempVertices[0] = points[i];
tempVertices[1] = points[i + 1];
tempVertices[2] = points[i + 2];
var norm = CalcNormal(tempVertices);
for (int j = i; j < i + 6; j++)
{
normals[j] = norm;
}
}
return normals;
}
public static Vector3 CalcNormal(Vector3[] vrt)
{
var n = Vector3.Cross(vrt[0] - vrt[2], vrt[0] - vrt[1]);
n.Normalize();
return n;
}
#region IOctreeItem
public BoundingVolume BoundingBox { get; set; }
public BoundingVolume TreeSegment { get; set; }
public bool ReInsertImmediately { get; set; }
public event EventHandler<ReinsertingEventArgs> NeedsRemoval;
public event EventHandler<ReinsertingEventArgs> NeedsInsert;
public void RaiseRemove()
{
NeedsRemoval?.Invoke(this, new ReinsertingEventArgs());
}
public void RaiseInsert()
{
NeedsInsert?.Invoke(this, new ReinsertingEventArgs());
}
#endregion
}
} |
namespace ServiceBase.Json
{
using Newtonsoft.Json.Serialization;
public class UnderscorePropertyNamesContractResolver :
DefaultContractResolver
{
public UnderscorePropertyNamesContractResolver() : base()
{
}
protected override string ResolvePropertyName(string propertyName)
{
return propertyName.Underscore();
}
}
} |
using System;
using LearningEnglishWeb.Areas.Training.Infrastructure.Facades.Abstractions;
using LearningEnglishWeb.Areas.Training.Infrastructure.Factories;
using LearningEnglishWeb.Areas.Training.Models.TranslateWord;
using LearningEnglishWeb.Areas.Training.Services;
using LearningEnglishWeb.Areas.Training.ViewModels.Abstractions;
using LearningEnglishWeb.Areas.Training.ViewModels.TranslateWord;
using LearningEnglishWeb.Services.Abstractions;
using Microsoft.AspNetCore.Http;
namespace LearningEnglishWeb.Areas.Training.Infrastructure.Facades
{
public class TranslateWordTrainingFacade : TrainingFacade<TranslateWordTraining, QuestionViewModel>
{
public TranslateWordTrainingFacade(TrainingFactory trainingFactory, IWordImageService wordImageService, ITrainingService trainingService) : base(trainingFactory, wordImageService, trainingService)
{
}
public TranslateWordAnswerViewModel GetCheckAnswerModel(HttpContext httpContext, Guid trainingId, string answer)
{
var training = GetTraining(httpContext, trainingId);
var isRight = training.CheckAnswer(answer);
SaveTraining(httpContext, training);
var question = training.GetCurrentQuestion();
var questionResult = new TranslateWordAnswerViewModel
{
Word = question.Word,
UserTranslation = answer,
RightTranslation = question.Translation
};
return questionResult;
}
}
}
|
using System;
using System.Diagnostics.CodeAnalysis;
using System.ServiceModel;
using EPiServer.Events.ServiceModel;
using HansKindberg.EPiServer.ServiceModel;
using log4net;
namespace HansKindberg.EPiServer.Events.Providers
{
public abstract class EventProvider<T> : global::EPiServer.Events.Providers.EventProvider where T : IEventReplication
{
// ReSharper disable StaticFieldInGenericType
#region Fields
private static readonly ILog _log = LogManager.GetLogger(typeof(EventProvider<>)); // ReSharper restore StaticFieldInGenericType
private readonly IServiceHostFactory _serviceHostFactory;
private string _serviceName;
#endregion
#region Constructors
protected EventProvider(IServiceHostFactory serviceHostFactory)
{
if(serviceHostFactory == null)
throw new ArgumentNullException("serviceHostFactory");
this._serviceHostFactory = serviceHostFactory;
}
#endregion
#region Properties
protected internal virtual IServiceHostFactory ServiceHostFactory
{
get { return this._serviceHostFactory; }
}
protected internal virtual string ServiceName
{
get { return this._serviceName ?? (this._serviceName = typeof(T).FullName); }
}
#endregion
#region Methods
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
protected internal virtual ICommunicationObject CreateServiceHost()
{
try
{
var serviceHost = this.ServiceHostFactory.Create<T>();
serviceHost.Open();
if(_log.IsInfoEnabled)
_log.Info("Successfully created service host for event replication class.");
return serviceHost;
}
catch(Exception exception)
{
if(_log.IsErrorEnabled)
_log.Error("Error creating/opening service host for event replication class.", exception);
return null;
}
}
#endregion
}
} |
using System.Collections.Generic;
using UnityEngine;
namespace FairyGUI
{
public class BitmapFont : BaseFont
{
public class BMGlyph
{
public int x;
public int y;
public int offsetX;
public int offsetY;
public int width;
public int height;
public int advance;
public int lineHeight;
public Rect uvRect;
public int channel;//0-n/a, 1-r,2-g,3-b,4-alpha
}
Dictionary<int, BMGlyph> _dict;
public int lineHeight;
static GlyphInfo glyhInfo = new GlyphInfo();
public BitmapFont(string name)
{
this.name = name;
this.canTint = true;
this.canLight = false;
this.canOutline = true;
this.hasChannel = false;
this.shader = ShaderConfig.bmFontShader;
_dict = new Dictionary<int, BMGlyph>();
}
public void AddChar(char ch, BMGlyph glyph)
{
_dict[ch] = glyph;
}
override public void SetFontStyle(TextFormat format)
{
}
override public void PrepareCharacters(string text)
{
}
override public bool GetGlyphSize(char ch, out int width, out int height)
{
BMGlyph bg;
if (ch == ' ')
{
width = Mathf.CeilToInt(size / 2 * scale);
height = Mathf.CeilToInt(size * scale);
return true;
}
else if (_dict.TryGetValue((int)ch, out bg))
{
width = Mathf.CeilToInt(bg.advance * scale);
height = Mathf.CeilToInt(bg.lineHeight * scale);
return true;
}
else
{
width = 0;
height = 0;
return false;
}
}
override public GlyphInfo GetGlyph(char ch)
{
BMGlyph bg;
if (ch == ' ')
{
glyhInfo.width = Mathf.CeilToInt(size / 2 * scale);
glyhInfo.height = Mathf.CeilToInt(size * scale);
glyhInfo.vert.xMin = 0;
glyhInfo.vert.xMax = glyhInfo.width;
glyhInfo.vert.yMin = glyhInfo.height;
glyhInfo.vert.yMax = 0;
glyhInfo.uv = new Rect(0, 0, 0, 0);
glyhInfo.channel = 0;
glyhInfo.flipped = false;
return glyhInfo;
}
else if (_dict.TryGetValue((int)ch, out bg))
{
glyhInfo.width = Mathf.CeilToInt(bg.advance * scale);
glyhInfo.height = Mathf.CeilToInt(bg.lineHeight * scale);
glyhInfo.vert.xMin = bg.offsetX;
glyhInfo.vert.xMax = bg.offsetX + bg.width * scale;
glyhInfo.vert.yMin = -Mathf.CeilToInt(bg.height * scale);
glyhInfo.vert.yMax = 0;
glyhInfo.uv = bg.uvRect;
glyhInfo.flipped = false;
glyhInfo.channel = bg.channel;
return glyhInfo;
}
else
return null;
}
}
}
|
namespace Sample.Domain.Shared
{
public enum Status { Initiated, InProgress, Completed, Canceled }
}
|
using System.Linq;
using System.Text;
namespace Service
{
/// <summary>
/// Provides extension methods for working with <see cref="IMessage" />
/// </summary>
public static class MessageExtensions
{
/// <summary>
/// Dumps the message and the values of it's public properties to a string, if possible.
/// </summary>
/// <param name="message">The message.</param>
/// <returns>
/// The name and contents of the message as a string. If an error occurs, just the name of the message.
/// </returns>
public static string Dump(this IMessage message)
{
if (message == null)
{
return "(null)";
}
try
{
var builder = new StringBuilder();
builder.AppendLine($"{message.GetType().Name}:");
builder.AppendLine("{");
var properties = message.GetType().GetProperties().OrderBy(x => x.Name);
foreach (var property in properties)
{
var value = property.GetValue(message);
var valueString = value == null ? "(null)" : value.ToString();
builder.AppendLine($"\t{property.Name}: {valueString}");
}
builder.Append("}");
return builder.ToString();
}
catch
{
return message.GetType().Name;
}
}
}
} |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Text.Json;
using System.Text.Json.Serialization;
using BuildXL.Cache.ContentStore.Interfaces.Logging;
using BuildXL.Cache.Monitor.App.Notifications;
namespace BuildXL.Cache.Monitor.App
{
internal class LogWriter<T> : INotifier<T>
{
private readonly ILogger _logger;
private readonly JsonSerializerOptions _jsonOptions;
public LogWriter(ILogger logger)
{
_logger = logger;
_jsonOptions = new JsonSerializerOptions() { WriteIndented = true };
_jsonOptions.Converters.Add(new JsonStringEnumConverter());
}
public void Emit(T notification) => _logger.Always(JsonSerializer.Serialize(notification, _jsonOptions));
}
}
|
using LuaInterface;
using SLua;
using System;
using UnityEngine;
public class Lua_UnityEngine_MaterialPropertyBlock : LuaObject
{
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int constructor(IntPtr l)
{
int result;
try
{
MaterialPropertyBlock o = new MaterialPropertyBlock();
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, o);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int SetFloat(IntPtr l)
{
int result;
try
{
int total = LuaDLL.lua_gettop(l);
if (LuaObject.matchType(l, total, 2, typeof(int), typeof(float)))
{
MaterialPropertyBlock materialPropertyBlock = (MaterialPropertyBlock)LuaObject.checkSelf(l);
int num;
LuaObject.checkType(l, 2, out num);
float num2;
LuaObject.checkType(l, 3, out num2);
materialPropertyBlock.SetFloat(num, num2);
LuaObject.pushValue(l, true);
result = 1;
}
else if (LuaObject.matchType(l, total, 2, typeof(string), typeof(float)))
{
MaterialPropertyBlock materialPropertyBlock2 = (MaterialPropertyBlock)LuaObject.checkSelf(l);
string text;
LuaObject.checkType(l, 2, out text);
float num3;
LuaObject.checkType(l, 3, out num3);
materialPropertyBlock2.SetFloat(text, num3);
LuaObject.pushValue(l, true);
result = 1;
}
else
{
LuaObject.pushValue(l, false);
LuaDLL.lua_pushstring(l, "No matched override function to call");
result = 2;
}
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int SetVector(IntPtr l)
{
int result;
try
{
int total = LuaDLL.lua_gettop(l);
if (LuaObject.matchType(l, total, 2, typeof(int), typeof(Vector4)))
{
MaterialPropertyBlock materialPropertyBlock = (MaterialPropertyBlock)LuaObject.checkSelf(l);
int num;
LuaObject.checkType(l, 2, out num);
Vector4 vector;
LuaObject.checkType(l, 3, out vector);
materialPropertyBlock.SetVector(num, vector);
LuaObject.pushValue(l, true);
result = 1;
}
else if (LuaObject.matchType(l, total, 2, typeof(string), typeof(Vector4)))
{
MaterialPropertyBlock materialPropertyBlock2 = (MaterialPropertyBlock)LuaObject.checkSelf(l);
string text;
LuaObject.checkType(l, 2, out text);
Vector4 vector2;
LuaObject.checkType(l, 3, out vector2);
materialPropertyBlock2.SetVector(text, vector2);
LuaObject.pushValue(l, true);
result = 1;
}
else
{
LuaObject.pushValue(l, false);
LuaDLL.lua_pushstring(l, "No matched override function to call");
result = 2;
}
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int SetColor(IntPtr l)
{
int result;
try
{
int total = LuaDLL.lua_gettop(l);
if (LuaObject.matchType(l, total, 2, typeof(int), typeof(Color)))
{
MaterialPropertyBlock materialPropertyBlock = (MaterialPropertyBlock)LuaObject.checkSelf(l);
int num;
LuaObject.checkType(l, 2, out num);
Color color;
LuaObject.checkType(l, 3, out color);
materialPropertyBlock.SetColor(num, color);
LuaObject.pushValue(l, true);
result = 1;
}
else if (LuaObject.matchType(l, total, 2, typeof(string), typeof(Color)))
{
MaterialPropertyBlock materialPropertyBlock2 = (MaterialPropertyBlock)LuaObject.checkSelf(l);
string text;
LuaObject.checkType(l, 2, out text);
Color color2;
LuaObject.checkType(l, 3, out color2);
materialPropertyBlock2.SetColor(text, color2);
LuaObject.pushValue(l, true);
result = 1;
}
else
{
LuaObject.pushValue(l, false);
LuaDLL.lua_pushstring(l, "No matched override function to call");
result = 2;
}
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int SetMatrix(IntPtr l)
{
int result;
try
{
int total = LuaDLL.lua_gettop(l);
if (LuaObject.matchType(l, total, 2, typeof(int), typeof(Matrix4x4)))
{
MaterialPropertyBlock materialPropertyBlock = (MaterialPropertyBlock)LuaObject.checkSelf(l);
int num;
LuaObject.checkType(l, 2, out num);
Matrix4x4 matrix4x;
LuaObject.checkValueType<Matrix4x4>(l, 3, out matrix4x);
materialPropertyBlock.SetMatrix(num, matrix4x);
LuaObject.pushValue(l, true);
result = 1;
}
else if (LuaObject.matchType(l, total, 2, typeof(string), typeof(Matrix4x4)))
{
MaterialPropertyBlock materialPropertyBlock2 = (MaterialPropertyBlock)LuaObject.checkSelf(l);
string text;
LuaObject.checkType(l, 2, out text);
Matrix4x4 matrix4x2;
LuaObject.checkValueType<Matrix4x4>(l, 3, out matrix4x2);
materialPropertyBlock2.SetMatrix(text, matrix4x2);
LuaObject.pushValue(l, true);
result = 1;
}
else
{
LuaObject.pushValue(l, false);
LuaDLL.lua_pushstring(l, "No matched override function to call");
result = 2;
}
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int SetTexture(IntPtr l)
{
int result;
try
{
int total = LuaDLL.lua_gettop(l);
if (LuaObject.matchType(l, total, 2, typeof(int), typeof(Texture)))
{
MaterialPropertyBlock materialPropertyBlock = (MaterialPropertyBlock)LuaObject.checkSelf(l);
int num;
LuaObject.checkType(l, 2, out num);
Texture texture;
LuaObject.checkType<Texture>(l, 3, out texture);
materialPropertyBlock.SetTexture(num, texture);
LuaObject.pushValue(l, true);
result = 1;
}
else if (LuaObject.matchType(l, total, 2, typeof(string), typeof(Texture)))
{
MaterialPropertyBlock materialPropertyBlock2 = (MaterialPropertyBlock)LuaObject.checkSelf(l);
string text;
LuaObject.checkType(l, 2, out text);
Texture texture2;
LuaObject.checkType<Texture>(l, 3, out texture2);
materialPropertyBlock2.SetTexture(text, texture2);
LuaObject.pushValue(l, true);
result = 1;
}
else
{
LuaObject.pushValue(l, false);
LuaDLL.lua_pushstring(l, "No matched override function to call");
result = 2;
}
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int AddFloat(IntPtr l)
{
int result;
try
{
int total = LuaDLL.lua_gettop(l);
if (LuaObject.matchType(l, total, 2, typeof(int), typeof(float)))
{
MaterialPropertyBlock materialPropertyBlock = (MaterialPropertyBlock)LuaObject.checkSelf(l);
int num;
LuaObject.checkType(l, 2, out num);
float num2;
LuaObject.checkType(l, 3, out num2);
materialPropertyBlock.AddFloat(num, num2);
LuaObject.pushValue(l, true);
result = 1;
}
else if (LuaObject.matchType(l, total, 2, typeof(string), typeof(float)))
{
MaterialPropertyBlock materialPropertyBlock2 = (MaterialPropertyBlock)LuaObject.checkSelf(l);
string text;
LuaObject.checkType(l, 2, out text);
float num3;
LuaObject.checkType(l, 3, out num3);
materialPropertyBlock2.AddFloat(text, num3);
LuaObject.pushValue(l, true);
result = 1;
}
else
{
LuaObject.pushValue(l, false);
LuaDLL.lua_pushstring(l, "No matched override function to call");
result = 2;
}
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int AddVector(IntPtr l)
{
int result;
try
{
int total = LuaDLL.lua_gettop(l);
if (LuaObject.matchType(l, total, 2, typeof(int), typeof(Vector4)))
{
MaterialPropertyBlock materialPropertyBlock = (MaterialPropertyBlock)LuaObject.checkSelf(l);
int num;
LuaObject.checkType(l, 2, out num);
Vector4 vector;
LuaObject.checkType(l, 3, out vector);
materialPropertyBlock.AddVector(num, vector);
LuaObject.pushValue(l, true);
result = 1;
}
else if (LuaObject.matchType(l, total, 2, typeof(string), typeof(Vector4)))
{
MaterialPropertyBlock materialPropertyBlock2 = (MaterialPropertyBlock)LuaObject.checkSelf(l);
string text;
LuaObject.checkType(l, 2, out text);
Vector4 vector2;
LuaObject.checkType(l, 3, out vector2);
materialPropertyBlock2.AddVector(text, vector2);
LuaObject.pushValue(l, true);
result = 1;
}
else
{
LuaObject.pushValue(l, false);
LuaDLL.lua_pushstring(l, "No matched override function to call");
result = 2;
}
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int AddColor(IntPtr l)
{
int result;
try
{
int total = LuaDLL.lua_gettop(l);
if (LuaObject.matchType(l, total, 2, typeof(int), typeof(Color)))
{
MaterialPropertyBlock materialPropertyBlock = (MaterialPropertyBlock)LuaObject.checkSelf(l);
int num;
LuaObject.checkType(l, 2, out num);
Color color;
LuaObject.checkType(l, 3, out color);
materialPropertyBlock.AddColor(num, color);
LuaObject.pushValue(l, true);
result = 1;
}
else if (LuaObject.matchType(l, total, 2, typeof(string), typeof(Color)))
{
MaterialPropertyBlock materialPropertyBlock2 = (MaterialPropertyBlock)LuaObject.checkSelf(l);
string text;
LuaObject.checkType(l, 2, out text);
Color color2;
LuaObject.checkType(l, 3, out color2);
materialPropertyBlock2.AddColor(text, color2);
LuaObject.pushValue(l, true);
result = 1;
}
else
{
LuaObject.pushValue(l, false);
LuaDLL.lua_pushstring(l, "No matched override function to call");
result = 2;
}
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int AddMatrix(IntPtr l)
{
int result;
try
{
int total = LuaDLL.lua_gettop(l);
if (LuaObject.matchType(l, total, 2, typeof(int), typeof(Matrix4x4)))
{
MaterialPropertyBlock materialPropertyBlock = (MaterialPropertyBlock)LuaObject.checkSelf(l);
int num;
LuaObject.checkType(l, 2, out num);
Matrix4x4 matrix4x;
LuaObject.checkValueType<Matrix4x4>(l, 3, out matrix4x);
materialPropertyBlock.AddMatrix(num, matrix4x);
LuaObject.pushValue(l, true);
result = 1;
}
else if (LuaObject.matchType(l, total, 2, typeof(string), typeof(Matrix4x4)))
{
MaterialPropertyBlock materialPropertyBlock2 = (MaterialPropertyBlock)LuaObject.checkSelf(l);
string text;
LuaObject.checkType(l, 2, out text);
Matrix4x4 matrix4x2;
LuaObject.checkValueType<Matrix4x4>(l, 3, out matrix4x2);
materialPropertyBlock2.AddMatrix(text, matrix4x2);
LuaObject.pushValue(l, true);
result = 1;
}
else
{
LuaObject.pushValue(l, false);
LuaDLL.lua_pushstring(l, "No matched override function to call");
result = 2;
}
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int AddTexture(IntPtr l)
{
int result;
try
{
int total = LuaDLL.lua_gettop(l);
if (LuaObject.matchType(l, total, 2, typeof(int), typeof(Texture)))
{
MaterialPropertyBlock materialPropertyBlock = (MaterialPropertyBlock)LuaObject.checkSelf(l);
int num;
LuaObject.checkType(l, 2, out num);
Texture texture;
LuaObject.checkType<Texture>(l, 3, out texture);
materialPropertyBlock.AddTexture(num, texture);
LuaObject.pushValue(l, true);
result = 1;
}
else if (LuaObject.matchType(l, total, 2, typeof(string), typeof(Texture)))
{
MaterialPropertyBlock materialPropertyBlock2 = (MaterialPropertyBlock)LuaObject.checkSelf(l);
string text;
LuaObject.checkType(l, 2, out text);
Texture texture2;
LuaObject.checkType<Texture>(l, 3, out texture2);
materialPropertyBlock2.AddTexture(text, texture2);
LuaObject.pushValue(l, true);
result = 1;
}
else
{
LuaObject.pushValue(l, false);
LuaDLL.lua_pushstring(l, "No matched override function to call");
result = 2;
}
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int GetFloat(IntPtr l)
{
int result;
try
{
int total = LuaDLL.lua_gettop(l);
if (LuaObject.matchType(l, total, 2, typeof(int)))
{
MaterialPropertyBlock materialPropertyBlock = (MaterialPropertyBlock)LuaObject.checkSelf(l);
int num;
LuaObject.checkType(l, 2, out num);
float @float = materialPropertyBlock.GetFloat(num);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, @float);
result = 2;
}
else if (LuaObject.matchType(l, total, 2, typeof(string)))
{
MaterialPropertyBlock materialPropertyBlock2 = (MaterialPropertyBlock)LuaObject.checkSelf(l);
string text;
LuaObject.checkType(l, 2, out text);
float float2 = materialPropertyBlock2.GetFloat(text);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, float2);
result = 2;
}
else
{
LuaObject.pushValue(l, false);
LuaDLL.lua_pushstring(l, "No matched override function to call");
result = 2;
}
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int GetVector(IntPtr l)
{
int result;
try
{
int total = LuaDLL.lua_gettop(l);
if (LuaObject.matchType(l, total, 2, typeof(int)))
{
MaterialPropertyBlock materialPropertyBlock = (MaterialPropertyBlock)LuaObject.checkSelf(l);
int num;
LuaObject.checkType(l, 2, out num);
Vector4 vector = materialPropertyBlock.GetVector(num);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, vector);
result = 2;
}
else if (LuaObject.matchType(l, total, 2, typeof(string)))
{
MaterialPropertyBlock materialPropertyBlock2 = (MaterialPropertyBlock)LuaObject.checkSelf(l);
string text;
LuaObject.checkType(l, 2, out text);
Vector4 vector2 = materialPropertyBlock2.GetVector(text);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, vector2);
result = 2;
}
else
{
LuaObject.pushValue(l, false);
LuaDLL.lua_pushstring(l, "No matched override function to call");
result = 2;
}
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int GetMatrix(IntPtr l)
{
int result;
try
{
int total = LuaDLL.lua_gettop(l);
if (LuaObject.matchType(l, total, 2, typeof(int)))
{
MaterialPropertyBlock materialPropertyBlock = (MaterialPropertyBlock)LuaObject.checkSelf(l);
int num;
LuaObject.checkType(l, 2, out num);
Matrix4x4 matrix = materialPropertyBlock.GetMatrix(num);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, matrix);
result = 2;
}
else if (LuaObject.matchType(l, total, 2, typeof(string)))
{
MaterialPropertyBlock materialPropertyBlock2 = (MaterialPropertyBlock)LuaObject.checkSelf(l);
string text;
LuaObject.checkType(l, 2, out text);
Matrix4x4 matrix2 = materialPropertyBlock2.GetMatrix(text);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, matrix2);
result = 2;
}
else
{
LuaObject.pushValue(l, false);
LuaDLL.lua_pushstring(l, "No matched override function to call");
result = 2;
}
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int GetTexture(IntPtr l)
{
int result;
try
{
int total = LuaDLL.lua_gettop(l);
if (LuaObject.matchType(l, total, 2, typeof(int)))
{
MaterialPropertyBlock materialPropertyBlock = (MaterialPropertyBlock)LuaObject.checkSelf(l);
int num;
LuaObject.checkType(l, 2, out num);
Texture texture = materialPropertyBlock.GetTexture(num);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, texture);
result = 2;
}
else if (LuaObject.matchType(l, total, 2, typeof(string)))
{
MaterialPropertyBlock materialPropertyBlock2 = (MaterialPropertyBlock)LuaObject.checkSelf(l);
string text;
LuaObject.checkType(l, 2, out text);
Texture texture2 = materialPropertyBlock2.GetTexture(text);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, texture2);
result = 2;
}
else
{
LuaObject.pushValue(l, false);
LuaDLL.lua_pushstring(l, "No matched override function to call");
result = 2;
}
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int Clear(IntPtr l)
{
int result;
try
{
MaterialPropertyBlock materialPropertyBlock = (MaterialPropertyBlock)LuaObject.checkSelf(l);
materialPropertyBlock.Clear();
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_isEmpty(IntPtr l)
{
int result;
try
{
MaterialPropertyBlock materialPropertyBlock = (MaterialPropertyBlock)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, materialPropertyBlock.get_isEmpty());
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
public static void reg(IntPtr l)
{
LuaObject.getTypeTable(l, "UnityEngine.MaterialPropertyBlock");
LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_MaterialPropertyBlock.SetFloat));
LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_MaterialPropertyBlock.SetVector));
LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_MaterialPropertyBlock.SetColor));
LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_MaterialPropertyBlock.SetMatrix));
LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_MaterialPropertyBlock.SetTexture));
LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_MaterialPropertyBlock.AddFloat));
LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_MaterialPropertyBlock.AddVector));
LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_MaterialPropertyBlock.AddColor));
LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_MaterialPropertyBlock.AddMatrix));
LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_MaterialPropertyBlock.AddTexture));
LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_MaterialPropertyBlock.GetFloat));
LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_MaterialPropertyBlock.GetVector));
LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_MaterialPropertyBlock.GetMatrix));
LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_MaterialPropertyBlock.GetTexture));
LuaObject.addMember(l, new LuaCSFunction(Lua_UnityEngine_MaterialPropertyBlock.Clear));
LuaObject.addMember(l, "isEmpty", new LuaCSFunction(Lua_UnityEngine_MaterialPropertyBlock.get_isEmpty), null, true);
LuaObject.createTypeMetatable(l, new LuaCSFunction(Lua_UnityEngine_MaterialPropertyBlock.constructor), typeof(MaterialPropertyBlock));
}
}
|
using System;
using System.Linq;
using System.Xml.Serialization;
namespace Swiddler.Security
{
/// <summary>
/// Wraps up the client SSL hello information.
/// </summary>
public class SslClientHello : SslHelloBase
{
public int[] Ciphers { get; set; }
[XmlIgnore] public byte[] CompressionData { get; set; }
[XmlElement(nameof(CompressionData))] public string CompressionDataEncoded { get => CompressionData == null ? null : Convert.ToBase64String(CompressionData); set => CompressionData = value == null ? null : Convert.FromBase64String(value); }
public string[] GetCipherSuites()
{
return Ciphers?.Select(x => SslCiphers.GetName(x)).ToArray();
}
public string GetServerNameIndication()
{
if (Extensions != null &&
Extensions.TryGetValue("server_name", out var sslExtension) &&
sslExtension?.GetExtensionData() is string[] data)
{
return data.FirstOrDefault();
}
return null;
}
}
}
|
using System;
public class Program
{
public static void Main()
{
var literLinesCount = int.Parse(Console.ReadLine());
var waterTankCapacity = 255;
var totalWater = 0m;
for (int i = 0; i < literLinesCount; i++)
{
var currentWaterLiters = int.Parse(Console.ReadLine());
totalWater += currentWaterLiters;
if (totalWater > waterTankCapacity)
{
Console.WriteLine("Insufficient capacity!");
totalWater -= currentWaterLiters;
}
}
Console.WriteLine(totalWater);
}
} |
using System;
using RestSharp.Deserializers;
namespace Jira.NET.Models
{
public class JiraSubTask
{
[DeserializeAs(Name = "id")]
public string Id { get; set; }
[DeserializeAs(Name = "type")]
public Type Type { get; set; }
[DeserializeAs(Name = "outwardIssue")]
public JiraWardIssue OutwardIssue { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Chpoi.SuitUp.Service
{
//图片服务
public interface ImageService
{
bool SendImage(string path);
bool SendNewImage(string path);
string GetServerMessage();
void SendRequest(string[] a,int size);
double[] TakeBodyMeasurements(string frontImageName, string sideImageName, double height);
byte[] GetPicture(string id);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
namespace Unity_Decoupler
{
public interface IUnityDecoupler
{
/*
Add an update frame event listsener
@param onUpdateFrame is a methode that is called each frame
and passes a parameter deltaTime as a float
*/
void AddUpdateTrigger(Action<float> onUpdateFrame);
/*
Remove an update frame event listsener
@param onUpdateFrame:
is the methode that needs to be removed. By calling this the methode is
no longer updated each frame if it was previously added.
*/
void RemoveUpdateTrigger(Action<float> onUpdateFrame);
/*
Link an existing object in the scene the the local spawn list
The scen might contain game object that are not spawned by this system,
but might have alllready been added to the scene. For example the Main Camara.
By using this methode the example camera is added to the local spawn list,
an can be extracted from this list. Using Get spawn.
@param gameObjectName:
is the name of the object in the scene that needs to be added to the spawn
list. NOTE: The name of this object will not be changed and there can be no
double names in the spawnlist!
@returns:
the game object from the scene for fast reference. It is quicker to use
the returned object and store its reference where you need it, than to call the
GetSpawn methode, which needs to itterate through all existing spawns in the local
spawn list.
@returns:
game object from spawn list if a game object with the given name allready
exists in the spawn list, instead of linking the scene object!
@returns:
NULL if there is no game object in the scene with the given name
*/
GameObject Link(string gameObjectName);
/*
Spawn a new instance of a prefab into the scene
This methode takes a gameobject from the local prefab list and instantiate's it
into the scene.
@param prefabName:
the name of the GameObject that is stored in the local prefap
list which you are trying to spawn into the scene.
@paran instanceName:
is the name of the spawn in the local spawn list
@returns:
the newly created instance of an existing prefab.
@returns:
a previously spawned game object if a spawn with the same instance name
allready exist. In this case no new instance is created.
@returns:
NULL if prefab does not exist.
*/
GameObject Spawn(string prefabName, string instanceName);
/*
Add a new object into the local prefab list
you can create your own game object (or use returned gameo bjects) and add them
to the local prefab list, so you can spawn instances of this prefab on the fly.
@param prefabObject:
the GameObject added to the local prefab list. The name of this
game object must be unique in order for this methode to work.
@returns:
true if the game object was succesfully added to the local prefab list.
@returns:
false if a game object with the same name allready exists within the
local prefab list.
*/
bool AddPrefab(GameObject prefabObject);
/*
Get a spawned object from the scene
@param instanceName:
name of the spawn, that has been stored within the local spawn list, you
are trying to get.
@returns:
the requested game object from the local spaw list.
@returns:
NULL if the spawn with the requested name was not found!
*/
GameObject GetSpawn(string instanceName);
/*
Get a prefab from the local prefab list
@param prefabName:
the name of the game object (gameobject.name), that has been stored within the
local prefab list, you are trying to get.
@returns:
the requested prefab game object from the local prefab list.
@returns:
NULL if the prefab with the requested name was not found!
*/
GameObject GetPrefab(string prefabName);
/*
Remove a prefab from the scene
@param instanceName:
the name of the previously spawned instance that needs to be removed.
if this instance does not exist in the local spawn list, nothing will happen.
*/
void Remove(string name);
/*
Load a prefab from recources into local prefab list
@param path:
path name within the resources folder see unity's documentation on
Resources.Load
@returns:
the newly loaded game object fetched from the resources folder.
@returns:
if a prefab allready exists within the local prefab list, this existing
game object will be returned and the load process will be skipped!
*/
GameObject LoadPrefab(string path);
}
public class UnityDecoupler : MonoBehaviour, IUnityDecoupler
{
private Action<float> updateTrigger;
public List<GameObject> prefabList;
private Dictionary<string, GameObject> spawnList;
void Start ()
{
spawnList = new Dictionary<string, GameObject>();
if (prefabList == null)
prefabList = new List<GameObject>();
Main main = new Main(this);
}
void Update ()
{
if (updateTrigger != null)
updateTrigger(Time.deltaTime);
}
public void AddUpdateTrigger(Action<float> onUpdateFrame)
{
updateTrigger += onUpdateFrame;
}
public void RemoveUpdateTrigger(Action<float> onUpdateFrame)
{
updateTrigger -= onUpdateFrame;
}
public GameObject Link(string gameObjectName)
{
GameObject go;
if (!spawnList.TryGetValue(gameObjectName, out go))
{
go = GameObject.Find(gameObjectName);
if (go != null)
spawnList.Add(gameObjectName, go);
}
return go;
}
public GameObject Spawn(string prefabName, string instanceName)
{
GameObject prefab = GetPrefab(prefabName);
GameObject go = GetSpawn(instanceName);
if (prefab != null && go == null)
{
go = Instantiate(prefab);
spawnList.Add(instanceName, go);
}
return go;
}
public GameObject GetSpawn(string instanceName)
{
GameObject go;
spawnList.TryGetValue(instanceName, out go);
return go;
}
public GameObject GetPrefab(string prefabName)
{
GameObject go = null;
foreach (GameObject prefab in prefabList)
if (prefab.name == name)
go = prefab;
return go;
}
public void Remove(string name)
{
GameObject go = GetSpawn(name);
if (go != null)
{
Destroy(go);
spawnList.Remove(name);
}
}
public GameObject LoadPrefab(string path)
{
GameObject prefab = GetPrefab(path);
if (prefab == null)
{
prefab = Resources.Load(path, typeof(GameObject)) as GameObject;
if (prefab != null)
AddPrefab(prefab);
}
return prefab;
}
public bool AddPrefab(GameObject prefabObject)
{
// check if prefab allready exists, if so return false;
foreach (GameObject prefab in prefabList)
if (prefab.name == prefabObject.name)
return false;
prefabList.Add(prefabObject);
return true;
}
}
}
|
using UnityEngine;
public class OpenDoorController : MonoBehaviour
{
#region Fields
[SerializeField] private GameObject _toggledGameObject;
#endregion
#region UnityMethods
private void OnTriggerEnter(Collider other)
{
var animator =_toggledGameObject.GetComponent<Animator>();
animator.SetTrigger("Open");
}
#endregion
}
|
using System;
namespace TeamElem.Security.Cryptography
{
[Serializable]
public abstract class PrivateKey
{
public PublicKey PublicKey => GetPublicKey();
public override string ToString() => GetPublicKey().ToString();
protected abstract PublicKey GetPublicKey();
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MenuShow
{
class MenuLeaf: MenuBase
{
protected MenuBase ParentLeaf { get; set; }
protected List<MenuBase> ChildLeafs { get; set; }
public string Name { get; set; }
public override MenuBase GetparentLeaf()
{
return ParentLeaf;
}
public override List<MenuBase> GetChildLeafs()
{
return ChildLeafs;
}
public string GetName()
{
return Name;
}
public override bool SetparentLeaf(MenuBase PLeaf)
{
if(PLeaf!=null)
{
ParentLeaf = PLeaf;
return true;
}
else
{
return false;
}
}
public bool SetChildLeafs(List<MenuBase> ChildNodes)
{
if (ChildNodes != null && ChildNodes.Count > 0)
{
ChildLeafs = ChildNodes;
return true;
}
else
{
return false;
}
}
public override bool SetChildLeafs(List<string> CName ,bool flag)
{
ChildLeafs = new List<MenuBase>();
if (CName!=null&&CName.Count>0)
{
if(flag)
{
CName.ForEach(o => ChildLeafs.Add(new MenuLeaf(this, null, o.ToString())));
}
else
{
CName.ForEach(o => ChildLeafs.Add(new MenuNode(this, o.ToString())));
}
return true;
}
else
{
return false;
}
}
public MenuLeaf(MenuBase PLeaf, List<MenuBase> CLeafs, string MyName):base()
{
ParentLeaf = PLeaf;
Name = MyName;
ChildLeafs = CLeafs;
}
}
}
|
using UnityEditor;
using UnityEngine;
using System.Collections;
using AorFramework.module;
using YoukiaUnity.CinemaSystem;
using YoukiaUnity.Graphics;
[CustomEditor(typeof(SubCameraInfo))]
public class SubCameraInfoEditor : Editor
{
public override void OnInspectorGUI()
{
// base.OnInspectorGUI();
SerializedObject m_Object = new SerializedObject(target);
EditorGUILayout.HelpBox("摄像机", MessageType.Warning);
GraphicsManager.eCameraOpenState state = (GraphicsManager.eCameraOpenState)EditorGUILayout.EnumPopup(new GUIContent("开机状态", " 开机状态"), (target as SubCameraInfo).OpenState);
(target as SubCameraInfo).OpenState = state;
EditorGUILayout.PropertyField(m_Object.FindProperty("_Level"), new GUIContent("优先级", "优先级高的摄像机优先渲染"));
EditorGUILayout.PropertyField(m_Object.FindProperty("OverrideGraphicSetting"), new GUIContent("覆盖图形参数", "覆盖一些参数利于表现"));
if (m_Object.FindProperty("OverrideGraphicSetting").boolValue)
{
EditorGUILayout.PropertyField(m_Object.FindProperty("OverrideNearClip"), new GUIContent("覆盖摄像机近裁面", "覆盖一些参数利于表现"));
EditorGUILayout.PropertyField(m_Object.FindProperty("OverrideFarClip"), new GUIContent("覆盖摄像机远裁面", "覆盖一些参数利于表现"));
EditorGUILayout.PropertyField(m_Object.FindProperty("OverrideFogDestance"), new GUIContent("覆盖大气雾距离", "覆盖一些参数利于表现"));
EditorGUILayout.PropertyField(m_Object.FindProperty("OverrideFogDestiy"), new GUIContent("覆盖大气雾浓度", "覆盖一些参数利于表现"));
}
SubCameraInfo cam = target as SubCameraInfo;
m_Object.ApplyModifiedProperties();
}
}
|
using RestSharp;
using Starwars.OAuth2Client.Entities;
using Starwars.OAuth2Client.Interfaces;
using System.Text.Json;
using System.Threading.Tasks;
namespace Starwars.OAuth2Client
{
public class OAuth2Client : IOAuth2Client
{
public async Task<Token> GetTokenAsync(string url, string clientId, string clientSecret)
{
var client = new RestClient(url);
var request = new RestRequest(Method.POST);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddParameter("application/x-www-form-urlencoded",
$"grant_type=client_credentials&client_id={clientId}&client_secret={clientSecret}",
ParameterType.RequestBody);
IRestResponse response = await client.ExecuteAsync(request);
if (response.IsSuccessful)
{
return JsonSerializer.Deserialize<Token>(response.Content);
}
return null;
}
}
}
|
using System.Collections.Generic;
using System.Data;
namespace PDTech.OA.BLL
{
/// <summary>
/// 公文类型定义字典表
/// </summary>
public partial class OA_ARCHIVE_TYPE
{
private readonly PDTech.OA.DAL.OA_ARCHIVE_TYPE dal = new PDTech.OA.DAL.OA_ARCHIVE_TYPE();
public OA_ARCHIVE_TYPE()
{ }
#region BasicMethod
/// <summary>
/// 获取类型信息---未分页
/// </summary>
/// <param name="where"></param>
/// <returns></returns>
public IList<Model.OA_ARCHIVE_TYPE> get_ArchiveTypeList(Model.OA_ARCHIVE_TYPE where)
{
return dal.get_ArchiveTypeList(where);
}
#endregion BasicMethod
/// <summary>
/// 查询公文类型
/// </summary>
/// <returns>返回公文类型</returns>
public DataTable GetArchiveType()
{
return dal.GetArchiveType();
}
/// <summary>
/// 查询公文类型
/// </summary>
/// <returns>返回公文类型</returns>
public IList<Model.ARCHIVE_TYPE_OPTION> GetArchiveTypeOption()
{
return dal.GetArchiveTypeOption();
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace p528___Secret_Ingredients
{
public partial class Form1 : Form
{
Amy amy;
Suzanne suzanne;
GetSecretIngredient del_ingredientMethod;
public Form1()
{
InitializeComponent();
amy = new Amy();
suzanne = new Suzanne();
del_ingredientMethod = null;
}
private void useIngredient_Click(object sender, EventArgs e)
{
if (del_ingredientMethod != null)
MessageBox.Show("I’ll add " + del_ingredientMethod( (int)amount.Value) );
else
MessageBox.Show("I don’t have a secret ingredient!");
}
private void getSuzanne_Click(object sender, EventArgs e)
{
del_ingredientMethod = new GetSecretIngredient(suzanne.MySecretIngredientMethod);
}
private void getAmy_Click(object sender, EventArgs e)
{
del_ingredientMethod = new GetSecretIngredient(amy.AmysSecretIngredientMethod);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
namespace Assets.Scripts.Entities {
[RequireComponent(typeof(Collider2D))]
public class Coin : Entity {
void OnTriggerEnter2D(Collider2D bumper) {
if ( objective == null )
return;
Player ply = objective.GetPlayer();
if ( ply != null && ply.gameObject != null && bumper.gameObject.Equals(ply.gameObject) ) {
Debug.Log("Collected coin...");
objective.RemoveEntity(this);
GameObject.Destroy(this.gameObject);
}
}
}
}
|
namespace AllSongsQueryLINQ
{
using System;
using System.Linq;
using System.Xml.Linq;
class ExtractAllSongs
{
static void Main()
{
XDocument document = XDocument.Load("../../../Lib/xml/catalogue.xml");
var songsTitlesCollection =
from song in document.Descendants("song")
select song.Element("title").Value;
Console.WriteLine("List of all songs from Catalogue: {0}{1}", Environment.NewLine, new string('-', 42));
foreach (var songName in songsTitlesCollection)
{
Console.WriteLine(songName);
}
}
}
}
|
// Accord Math Library
// The Accord.NET Framework
// http://accord-framework.net
//
// Copyright © César Souza, 2009-2015
// cesarsouza at gmail.com
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//
namespace Accord.Math.Decompositions
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Accord;
/// <summary>
/// Gram-Schmidt Orthogonalization.
/// </summary>
///
public class GramSchmidtOrthogonalization
{
private double[,] q;
private double[,] r;
/// <summary>
/// Initializes a new instance of the <see cref="GramSchmidtOrthogonalization"/> class.
/// </summary>
///
/// <param name="value">The matrix <c>A</c> to be decomposed.</param>
///
public GramSchmidtOrthogonalization(double[,] value)
: this(value, true)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="GramSchmidtOrthogonalization"/> class.
/// </summary>
///
/// <param name="value">The matrix <c>A</c> to be decomposed.</param>
/// <param name="modified">True to use modified Gram-Schmidt; false
/// otherwise. Default is true (and is the recommended setup).</param>
///
public GramSchmidtOrthogonalization(double[,] value, bool modified)
{
if (value.GetLength(0) != value.GetLength(1))
throw new DimensionMismatchException("value", "Matrix must be square.");
int size = value.GetLength(0);
q = new double[size, size];
r = new double[size, size];
if (modified)
{
for (int j = 0; j < size; j++)
{
double[] v = value.GetColumn(j);
for (int i = 0; i < j; i++)
{
r[i, j] = q.GetColumn(i).Dot(v);
var t = r[i, j].Multiply(q.GetColumn(i));
v.Subtract(t, result: v);
}
r[j, j] = Norm.Euclidean(v);
q.SetColumn(j, v.Divide(r[j, j]));
}
}
else
{
for (int j = 0; j < size; j++)
{
double[] v = value.GetColumn(j);
double[] a = value.GetColumn(j);
for (int i = 0; i < j; i++)
{
r[i, j] = q.GetColumn(j).Dot(a);
v = v.Subtract(r[i, j].Multiply(q.GetColumn(i)));
}
r[j, j] = Norm.Euclidean(v);
q.SetColumn(j, v.Divide(r[j, j]));
}
}
}
/// <summary>
/// Returns the orthogonal factor matrix <c>Q</c>.
/// </summary>
///
public double[,] OrthogonalFactor
{
get { return q; }
}
/// <summary>
/// Returns the upper triangular factor matrix <c>R</c>.
/// </summary>
///
public double[,] UpperTriangularFactor
{
get { return r; }
}
}
}
|
using FatCat.Nes.OpCodes.AddressingModes;
namespace FatCat.Nes.OpCodes.Transfers
{
public class TransferStackPointerToXRegister : TransferOpCode
{
public override string Name => "TSX";
protected override byte TransferFromItem => cpu.StackPointer;
protected override byte TransferTooItem
{
get => cpu.XRegister;
set => cpu.XRegister = value;
}
public TransferStackPointerToXRegister(ICpu cpu, IAddressMode addressMode) : base(cpu, addressMode) { }
}
} |
//#define CHECK
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
namespace GomokuEngine
{
class Sorting
{
BothPlayerEvaluation[] evaluation;
int[] scoreTable;
int score;
int[] firstItem;
int[] previousItem;
int[] nextItem;
VCT threats;
public Sorting(int boardSize, VCT threats)
{
//compute number of squares of board
int numberOfSquares = boardSize * boardSize;
evaluation = new BothPlayerEvaluation[numberOfSquares];
for (int square = 0; square < numberOfSquares; square++)
{
evaluation[square] = BothPlayerEvaluation.unknown;
}
score = 0;
#region initialize score table
scoreTable = new int[Enum.GetValues(typeof(BothPlayerEvaluation)).Length];
for (int index1 = 0; index1 < scoreTable.Length; index1++)
{
int opositeIndex = scoreTable.Length - index1 - 1;
int score1 = (int)Math.Pow(opositeIndex,1.5);
// int score1 = 10*opositeIndex;
//toggle score1 for defending moves
BothPlayerEvaluation eval = (BothPlayerEvaluation)index1;
string str1 = eval.ToString();
if (str1.Contains("defending"))
{
score1 = -score1;
}
scoreTable[index1] = score1;
}
#endregion
#region initialize sorting
previousItem = new int[numberOfSquares];
nextItem = new int[numberOfSquares];
for (int index = 0; index < numberOfSquares; index++)
{
previousItem[index] = index - 1;
nextItem[index] = index + 1;
}
//fix last item
nextItem[numberOfSquares - 1] = -1;
//initialize first item
firstItem = new int[Enum.GetValues(typeof(BothPlayerEvaluation)).Length];
for (int index = 0; index < Enum.GetValues(typeof(BothPlayerEvaluation)).Length; index++)
{
firstItem[index] = -1;
}
firstItem[(int)BothPlayerEvaluation.unknown] = 0;
#endregion
this.threats = threats;
}
void SortSquare(int square, BothPlayerEvaluation oldEvaluation, BothPlayerEvaluation newEvaluation)
{
//remove square from old position
int previous = previousItem[square];
if (previous == -1)
{
//fix forward pointer
int next = firstItem[(int)oldEvaluation] = nextItem[square];
//fix backward pointer
if (next != -1)
{
//this is the first item in the list
previousItem[next] = -1;
}
}
else
{
//fix forward pointer
int next = nextItem[previous] = nextItem[square];
//fix backward pointer
if (next != -1)
{
previousItem[next] = previousItem[square];
}
}
//place line to new position
int first = firstItem[(int)newEvaluation];
nextItem[square] = first;
//is something in list?
if (first != -1)
{
//fix backward pointer
previousItem[first] = square;
}
//fix pointers of line
previousItem[square] = -1;
firstItem[(int)newEvaluation] = square;
}
public void Modify(int square, BothPlayerEvaluation newEvaluation)
{
//get old evaluation
BothPlayerEvaluation oldEvaluation = evaluation[square];
//if (newEvaluation == oldEvaluation) return false;
SortSquare(square, oldEvaluation, newEvaluation);
//modify evaluation
score += scoreTable[(byte)newEvaluation] - scoreTable[(byte)oldEvaluation];
evaluation[square] = newEvaluation;
#if CHECK
int score1 = 0;
List<int> list1 = new List<int>();
for (BothPlayerEvaluation eval = BothPlayerEvaluation.four_attacking; eval < BothPlayerEvaluation.unknown; eval++)
{
int nbMoves = AddMovesToList(eval, list1);
int score2 = scoreTable[(byte)eval];
score1 += nbMoves * score2;
}
System.Diagnostics.Debug.Assert(score == score1,"Score value is wrong!");
#endif
//return true;
}
/* function adds moves to list */
public int AddMovesToList(BothPlayerEvaluation evaluation, List<int> moves, bool vctMoves)
{
//get first square
int square = firstItem[(int)evaluation];
int addedMoves = 0;
//loop through all squares
while (square != -1)
{
if (((vctMoves == true) && threats.CreatesVct(square))||(vctMoves == false))
{
moves.Add(square);
addedMoves++;
}
//get next square
square = nextItem[square];
}
return addedMoves;
}
public bool Exists(BothPlayerEvaluation evaluation)
{
if (firstItem[(int)evaluation] >= 0)
{
return true;
}
else
{
return false;
}
}
public int Score
{
get
{
return score;
}
}
public BothPlayerEvaluation GetEvaluation(int square)
{
return evaluation[square];
}
public bool IsWinningMove(int square)
{
if (evaluation[square] == BothPlayerEvaluation.four_attacking)
{
return true;
}
else
{
return false;
}
}
public int[] GetScoreEvaluation()
{
return scoreTable;
}
public void SetScoreEvaluation(int[] scoreEvaluation)
{
for (int index = 0; index < scoreEvaluation.Length; index++)
{
this.scoreTable[index] = scoreEvaluation[index];
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Media.Imaging;
using System.Windows.Media;
using System.Windows;
namespace ServerKinect.Video
{
public class RgbImageSourceFactory : IImageFactory
{
public RgbImageSourceFactory()
{ }
public unsafe void CreateImage(WriteableBitmap target, IntPtr pointer)
{
Int32Rect rectangle = default(Int32Rect);
target.Dispatcher.Invoke(new Action(() =>
{
rectangle = new Int32Rect(0, 0, target.PixelWidth, target.PixelHeight);
}));
byte* pImage = (byte*)pointer.ToPointer();
var pixelCount = rectangle.Width * rectangle.Height;
var buffer = new byte[pixelCount * 3];
for (int index = 0; index < pixelCount; index++)
{
buffer[index * 3] = pImage[2];
buffer[index * 3 + 1] = pImage[1];
buffer[index * 3 + 2] = pImage[0];
pImage += 3;
}
target.Dispatcher.Invoke(new Action(() =>
{
target.Lock();
target.WritePixels(rectangle, buffer, rectangle.Width * 3, 0);
target.Unlock();
}));
}
}
}
|
#region Copyright Syncfusion Inc. 2001-2015.
// Copyright Syncfusion Inc. 2001-2015. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using Syncfusion.SfChart.XForms;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace SampleBrowser
{
public partial class Trackball
{
public Trackball()
{
InitializeComponent();
labelDisplayMode.SelectedIndex = 0;
labelDisplayMode.SelectedIndexChanged += labelDisplayMode_SelectedIndexChanged;
}
void labelDisplayMode_SelectedIndexChanged(object sender, EventArgs e)
{
switch(labelDisplayMode.SelectedIndex)
{
case 0:
chartTrackball.LabelDisplayMode = TrackballLabelDisplayMode.FloatAllPoints;
break;
case 1:
chartTrackball.LabelDisplayMode = TrackballLabelDisplayMode.NearestPoint;
break;
}
}
}
}
|
using System;
namespace NoteTaker1.Converters
{
public class BooleanConverter : ValueConverterBase<object,bool>
{
protected override bool ConvertValue(object input, object parameter){
if (input.ToString().ToLower() == "true")
return true;
else
return false;
}
protected override object ConvertValueBack (bool output, object parameter)
{
return output.ToString ();
}
}
}
|
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using WMagic;
using WMaper.Base;
namespace WMaper.Misc.View.Core
{
public sealed partial class Tips : UserControl
{
#region 变量
private bool make;
private WMaper.Core.Tips tips;
#endregion
#region 构造函数
/// <summary>
/// 构造函数
/// </summary>
public Tips()
{
InitializeComponent();
}
/// <summary>
/// 构造函数
/// </summary>
/// <param name="tips"></param>
public Tips(WMaper.Core.Tips tips)
: this()
{
this.make = false;
{
(this.tips = tips).Facade = this.TipsLayer;
}
this.TipsGrid.LayoutUpdated += this.Paint;
}
#endregion
#region 函数方法
/// <summary>
/// 强制绘制
/// </summary>
/// <param name="obj"></param>
/// <param name="evt"></param>
private void Paint(object obj, EventArgs evt)
{
if (this.make)
{
this.make = false;
{
if (Visibility.Visible.Equals(this.Visibility))
{
Pixel pixel = this.tips.Target.Netmap.Crd2px(this.tips.Point);
try
{
pixel = this.tips.Target.Netmap.Crd2px(this.tips.Point);
}
catch (NullReferenceException)
{
pixel = null;
}
finally
{
if (MatchUtils.IsEmpty(pixel))
{
this.Visibility = Visibility.Collapsed;
}
else
{
double devX = !MatchUtils.IsEmpty(this.tips.Drift) ? this.tips.Drift.X : 0, devY = !MatchUtils.IsEmpty(this.tips.Drift) ? this.tips.Drift.Y : 0;
{
Canvas.SetTop(this, Math.Round(devY + pixel.Y - this.tips.Target.Netmap.Nature.Y - this.TipsGrid.ActualHeight));
Canvas.SetLeft(this, Math.Round(devX + pixel.X - this.tips.Target.Netmap.Nature.X - this.TipsGrid.ActualWidth * 0.5));
}
}
}
}
}
}
}
/// <summary>
/// 构建提示框
/// </summary>
public void Build()
{
if (!MatchUtils.IsEmpty(this.tips) && !MatchUtils.IsEmpty(this.tips.Target) && !MatchUtils.IsEmpty(this.tips.Target.Netmap) && this.tips.Target.Enable && this.tips.Enable)
{
// 提示光标
this.Cursor = this.tips.Mouse;
{
// 提示标题
this.TipsTitle.Content = this.tips.Title;
// 提示透明
this.tips.Facade.Opacity = this.tips.Alpha / 100.0;
// 提示色彩
this.TipsTitle.Foreground = new SolidColorBrush(this.tips.Color);
// 提示字体
if (MatchUtils.IsEmpty(this.tips.Fonts))
{
this.TipsTitle.FontSize = 14;
this.TipsTitle.FontStyle = FontStyles.Normal;
this.TipsTitle.FontWeight = FontWeights.Bold;
}
else
{
this.TipsTitle.FontSize = this.tips.Fonts.Size;
this.TipsTitle.FontStyle = this.tips.Fonts.Ital ? FontStyles.Italic : FontStyles.Normal;
this.TipsTitle.FontWeight = this.tips.Fonts.Bold ? FontWeights.Bold : FontWeights.Normal;
}
// 提示内容
this.TipsBody.Children.Clear();
{
FrameworkElement component = new FrameworkElement();
if (!MatchUtils.IsEmpty(this.tips.Quote))
{
if (this.tips.Quote is String)
{
string ctx = this.tips.Quote as String;
if (MatchUtils.IsUrl(ctx))
{
// 添加浏览器控件
WebBrowser webBrowser = new WebBrowser();
try
{
webBrowser.Source = new Uri(ctx, UriKind.RelativeOrAbsolute);
}
catch
{
webBrowser = null;
}
finally
{
if (webBrowser != null)
{
component = webBrowser;
}
}
}
else
{
// 添加文本内容
TextBox textBox = new TextBox();
try
{
textBox.Text = ctx;
textBox.FontSize = 12;
textBox.IsReadOnly = true;
textBox.IsHitTestVisible = false;
textBox.IsReadOnlyCaretVisible = false;
textBox.FontStyle = FontStyles.Normal;
textBox.FontWeight = FontWeights.Normal;
textBox.TextWrapping = TextWrapping.Wrap;
textBox.FontFamily = new FontFamily("SimSun");
textBox.BorderThickness = (
textBox.Padding = new Thickness(0, 0, 0, 0)
);
textBox.VerticalScrollBarVisibility = ScrollBarVisibility.Auto;
textBox.HorizontalScrollBarVisibility = ScrollBarVisibility.Auto;
}
catch
{
textBox = null;
}
finally
{
if (textBox != null)
{
component = textBox;
}
}
}
}
else
{
if (this.tips.Quote is FrameworkElement)
{
// 初始控件绑定
DependencyObject depend = (this.tips.Quote as FrameworkElement).Parent;
if (!MatchUtils.IsEmpty(depend))
{
depend.SetValue(ContentProperty, null);
{
depend = null;
}
}
// 添加控件内容
ScrollViewer scrollViewer = new ScrollViewer();
{
scrollViewer.VerticalScrollBarVisibility = ScrollBarVisibility.Auto;
scrollViewer.HorizontalScrollBarVisibility = ScrollBarVisibility.Auto;
}
try
{
scrollViewer.Content = this.tips.Quote as FrameworkElement;
}
catch
{
scrollViewer = null;
}
finally
{
if (scrollViewer != null)
{
component = scrollViewer;
}
}
}
}
}
// 设置尺寸
{
if (MatchUtils.IsEmpty(this.tips.Gauge))
{
component.Width = 135.0;
component.Height = 35.0;
}
else
{
component.Width = this.tips.Gauge.W;
component.Height = this.tips.Gauge.H;
}
component.Margin = new Thickness(8, 5, 8, 5);
}
this.TipsBody.Children.Add(component);
}
}
// 强制绘制
this.Adjust();
}
}
/// <summary>
/// 纠偏提示
/// </summary>
public void Adjust()
{
if (Visibility.Visible.Equals(this.Visibility))
{
this.make = true;
{
this.TipsGrid.InvalidateArrange();
}
}
}
/// <summary>
/// 关闭提示框
/// </summary>
/// <param name="obj"></param>
/// <param name="evt"></param>
private void TipsCtrl_MouseLeftButtonDown(object obj, MouseButtonEventArgs evt)
{
if (!MatchUtils.IsEmpty(this.tips) && !MatchUtils.IsEmpty(this.tips.Target) && this.tips.Target.Enable && (evt.Handled = this.tips.Enable) && evt.ClickCount == 1)
{
MouseButtonEventHandler stopHnd = null;
{
this.TipsCtrl.MouseLeftButtonUp += (stopHnd = new MouseButtonEventHandler((stopObj, stopEvt) =>
{
this.TipsCtrl.MouseLeftButtonUp -= stopHnd;
{
stopHnd = null;
}
this.tips.Remove();
}));
}
}
}
#endregion
}
} |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ExperianOfficeArrangement.Models
{
[TestClass]
public class ChairTests
{
[TestClass]
public class CtorTests
{
[TestMethod]
public void ShouldSetPropertyAfterInitialization()
{
Chair chair = new Chair("test");
Assert.AreEqual("test", chair.BrandName);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using CardinalInventoryWebApi.Data.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
namespace CardinalInventoryWebApi.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class TokenController : ControllerBase
{
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly ILogger _logger;
private readonly IConfiguration _configuration;
private readonly UserManager<ApplicationUser> _userManager;
public TokenController(
SignInManager<ApplicationUser> signInManager,
ILogger<TokenController> logger,
IConfiguration configuration,
UserManager<ApplicationUser> userManager)
{
_signInManager = signInManager;
_logger = logger;
_configuration = configuration;
_userManager = userManager;
}
//POST: api/Token
[HttpPost]
[AllowAnonymous]
public async Task<IActionResult> Create([FromForm]string username, [FromForm]string password, [FromForm]bool persistent)
{
bool foundemail = true;
var user = await _userManager.FindByEmailAsync(username);
if (user == null)
{
foundemail = false;
user = await _userManager.FindByNameAsync(username);
if (user == null)
{
return BadRequest();
}
}
var result = await _signInManager.PasswordSignInAsync(user, password, persistent, false);
if (result == Microsoft.AspNetCore.Identity.SignInResult.Success)
{
_logger.LogInformation(user.UserName + " logged in.");
string token = await GenerateToken(username, foundemail);
return new ObjectResult(token);
}
return BadRequest();
}
private async Task<string> GenerateToken(string username, bool foundemail)
{
ApplicationUser appUser;
if (foundemail)
{
appUser = await _userManager.FindByEmailAsync(username);
}
else
{
appUser = await _userManager.FindByNameAsync(username);
}
var claims = new Claim[]
{
//new Claim(ClaimTypes.Name, username),
//new Claim(ClaimTypes.NameIdentifier, appUser.Id),
new Claim(JwtRegisteredClaimNames.Jti, appUser.Id.ToString()),
new Claim(JwtRegisteredClaimNames.Nbf, new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds().ToString()),
new Claim(JwtRegisteredClaimNames.Exp, new DateTimeOffset(DateTime.Now.AddDays(1)).ToUnixTimeSeconds().ToString()),
};
var token = new JwtSecurityToken(
new JwtHeader(new SigningCredentials(
new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration[Constants.JwtSecretKey])),
SecurityAlgorithms.HmacSha256)),
new JwtPayload(claims));
return new JwtSecurityTokenHandler().WriteToken(token);
}
}
} |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Group : MonoBehaviour {
private List<Unit> unitsList = new List<Unit>();
private Unit commander;
private GameObject ghostHolder;
public GameObject unitGO, ghostGO;
private Transform centerGO; // TODO only serves debugging, remove
private Vector3 center;
public int number, width;
public float unitSpace = 3;
public int team;
public Color color;
public GameObject commanderIcon;
[HideInInspector] public Vector3[] precalculatedPositions;
private float pathRefreshTime = 0.5f;
// TODO stop pathfinding once destination reached
// Use this for initialization
void Start () {
Globals.group = gameObject;
precalculatedPositions = new Vector3[number];
// create invisible commander unit and disable all his renderers
commander = (Instantiate(unitGO, transform.position, Quaternion.identity) as GameObject).GetComponent<Unit>();
foreach ( var r in commander.GetComponentsInChildren<Renderer>() ) {
Destroy(r);
}
commander.transform.parent = transform;
Destroy(commander.GetComponent<LODManager>());
commander.name = "Commander";
commander.team = team;
commander.transform.localScale *= 0.001f;
Destroy(commander.collider);
Destroy(commander.rigidbody);
commander.GetComponent<NavMeshAgent>().obstacleAvoidanceType = ObstacleAvoidanceType.NoObstacleAvoidance;
// create ghost holder
ghostHolder = new GameObject("GhostHolder");
ghostHolder.transform.parent = commander.transform;
ghostHolder.transform.localPosition = new Vector3(0,0.4f,0);
createFormation();
// create icon above commander for debugging
var icon = Instantiate(commanderIcon, commander.transform.position, Quaternion.identity) as GameObject;
icon.transform.parent = commander.transform;
icon.transform.position += new Vector3(0, 6, 0);
//
StartCoroutine(updateGhosts());
centerGO = transform.FindChild("Center");
StartCoroutine(updateCenter());
}
void createFormation() {
// create units in formation and add them to list
GameObject newUnit, newGhost;
for (int i = 0; i<number; i++) {
precalculatedPositions[i] = idToPosition(i);
// create units
newUnit = Instantiate(unitGO, transform.position
+ precalculatedPositions[i], Quaternion.identity) as GameObject;
unitsList.Add(newUnit.GetComponent<Unit>());
newUnit.GetComponent<Unit>().id = i;
newUnit.GetComponent<Unit>().team = team;
newUnit.transform.parent = transform;
newUnit.GetComponent<Unit>().group = this;
newUnit.transform.GetChild(0).GetComponent<SpriteRenderer>().color = color;
// create ghosts around commander for reference
newGhost = Instantiate(ghostGO) as GameObject;
newGhost.transform.parent = ghostHolder.transform;
newGhost.transform.localPosition = precalculatedPositions[i];
}
}
// returns position in formation in coordinates relative to group center
Vector3 idToPosition(int id) {
return new Vector3(((id % width) < width/2 ? id % width : -(id % width) + width/2 -1) * unitSpace, 0,
id/width * -unitSpace);
// commander is in topleft corner
//return new Vector3(id / width * unitSpace, 0, id % width * unitSpace);
}
public Vector3 calculateCenter() {
Vector3 center = Vector3.zero;
foreach (Transform t in transform) {
center += t.localPosition;
}
center /= transform.childCount;
return center;
}
// set a new destination for the group
public void setDestination(Vector3 pos){
StopCoroutine("refreshPaths");
// create path for commander immediately
var path = new NavMeshPath();
var done = commander.navMeshAgent.CalculatePath(pos, path);
if (done){
commander.navMeshAgent.path = path;
}
StartCoroutine("refreshPaths");
}
IEnumerator updateGhosts( ){
var refreshTime = 0.5f;
// TODO may be super heavy; optimize
for (var i=0; i<ghostHolder.transform.childCount; i++) {
var dir = (precalculatedPositions[i] - ghostHolder.transform.GetChild(i).localPosition)*refreshTime;
ghostHolder.transform.GetChild(i).Translate(dir);
//ghostHolder.transform.GetChild(i).rigidbody.AddForce(-dir*100, ForceMode.VelocityChange);
}
// attract commander to center of group
if (commander.navMeshAgent.remainingDistance > 20f) {
var dir = (center - commander.transform.localPosition)*refreshTime/10f;
commander.transform.position += dir * dir.magnitude; // TODO bug probably local coords
}
yield return new WaitForSeconds(refreshTime);
StartCoroutine(updateGhosts());
}
IEnumerator updateCenter() {
center = calculateCenter();
centerGO.transform.localPosition = center;
yield return new WaitForSeconds(1f);
StartCoroutine(updateCenter());
}
// recalculate path to commander
IEnumerator refreshPaths() {
var hit = new NavMeshHit();
commander.navMeshAgent.SamplePathPosition(~0, 10, out hit);
for (int i=0; i<unitsList.Count; i++) {
// ahead of commander on path
unitsList[i].setDestination(ghostHolder.transform.GetChild(i).position);
}
yield return new WaitForSeconds(pathRefreshTime);
StartCoroutine("refreshPaths");
}
public void unitKilled(Unit unit) {
unitsList.Remove(unit);
}
}
|
using UnityEngine;
using System.Collections;
public class InstructionsMenu : MonoBehaviour {
// GUI style for the background
public GUIStyle backgroundStyle;
// GUI style for the back button
public GUIStyle backButtonStyle;
void OnGUI()
{
GUI.Box(new Rect(0, 0, Screen.width, Screen.height), "",
backgroundStyle);
if (GUI.Button(new Rect(
Screen.width - 80, Screen.height - 80, 64, 64), "",
backButtonStyle))
{
// Return to the title screen
Application.LoadLevel(0);
}
}
}
|
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
namespace CMS_Tools.Lib
{
/// <summary>
/// Google lib login
/// </summary>
public class GoogleLib
{
/// <summary>
/// Get Config google key authen
/// </summary>
/// <returns></returns>
public static dynamic GetConfigGoogle(string fileName)
{
try
{
string text = System.IO.File.ReadAllText(HttpContext.Current.Server.MapPath("~/" + fileName));
dynamic JSON = JObject.Parse(text);
return JSON;
}
catch (Exception ex)
{
Lib.Logs.SaveError("Error GetConfigGoogle: " + ex);
return null;
}
}
/// <summary>
/// GetAccessToken
/// </summary>
/// <param name="code"></param>
/// <returns></returns>
private static string GetAccessToken(string code) {
try
{
var JSON = Lib.GoogleLib.GetConfigGoogle(Constants.GG_JSON_FILE);
string d = "code=" + code +
"&client_id=" + JSON.web.client_id +
"&client_secret=" + JSON.web.client_secret +
"&redirect_uri=" + (Constants.SERVER_TYPE == "REAL" ? JSON.web.redirect_uris[1] : JSON.web.redirect_uris[0]) +
"&grant_type=authorization_code";
string url = JSON.web.token_uri + "";
Logs.SaveLog("GetAccessToken: " + url +
"\r\nPost Data: " + d);
string data = UtilClass.SendPost(d, url);
Logs.SaveLog("TokenGG: " + data);
//{ "access_token": "ya29.Glv2BYPsIns3p7MiUsvhz109tCR9zv3yOoZG_KZO3eynI_-ltDbnl43zqt6IAk17_KSkoVknBQwAakNe33m0CNvXznpW3pcC325vXKSc_i3Y93EoyEqDuPoYg1bj", "token_type": "Bearer", "expires_in": 3600, "refresh_token": "1/UxchQTnopGju7bDezDV-Djeye_bixXZETaHTpvhjAcc", "scope": "https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/plus.me", "id_token": "eyJhbGciOiJSUzI1NiIsImtpZCI6IjlhMzNiNWVkYjQ5ZDA4NjdhODY3MmQ5NTczYjFlMGQyMzc1ODg2ZTEifQ.eyJhenAiOiI5ODMzNzM3OTg3NzctNGc1MWk2ODBvcThncTBwajFvdG5mZXNqcXNlMXZzcDAuYXBwcy5nb29nbGV1c2VyY29udGVudC5jb20iLCJhdWQiOiI5ODMzNzM3OTg3NzctNGc1MWk2ODBvcThncTBwajFvdG5mZXNqcXNlMXZzcDAuYXBwcy5nb29nbGV1c2VyY29udGVudC5jb20iLCJzdWIiOiIxMDY1MzM3ODA3OTU5OTI1MTgwODgiLCJlbWFpbCI6ImRldnByb2R1Y3Rpb24udm5AZ21haWwuY29tIiwiZW1haWxfdmVyaWZpZWQiOnRydWUsImF0X2hhc2giOiJfbHNENkRnYXVmZTlIdkxwYWotLW93IiwiZXhwIjoxNTM0MDAxOTY0LCJpc3MiOiJhY2NvdW50cy5nb29nbGUuY29tIiwiaWF0IjoxNTMzOTk4MzY0fQ.udQXANtLAIzdY85Gn-KoSKUNBGVBnbwVKuEFeZTILJclzFPxoWcpiOvbvpD6KyCz0b8moQnZTSNZCeQ7uU-YZMWPy9Jr225Pqo5DbOIAfeVfpm8AhJxuKCw8euhxe3LRDxq37ABsx782ayXpV_07wgnoE5jBcNS_BjYGHA9e9yAMyJ5uWNmN5Y9WSbfl6fw03wDVenX--Qi4IDtj-3ClJ2s6nqZ9i1kcPKGJPXMLQvXKQRkkh3k335Z-k2Y-CG5kjtBHA7Mfdkf2H5cgvY-I6Ck_qPUR_O2AnZ3uTWzND7-E6cjoRAcY9OB1ye0vnAe1kovU3H2ojd2RcNViZfZm_w" }
dynamic Token = JObject.Parse(data);
string accessToken = Token.access_token + "";
return accessToken;
}
catch (Exception ex)
{
Logs.SaveError("Error AccessToken: " + ex);
throw new Exception(ex.Message);
}
}
/// <summary>
/// GetGoogleUserInfo
/// </summary>
/// <param name="accessToken"></param>
/// <returns></returns>
public static GoogleUserOutputData GetGoogleUserInfo(string code)
{
try
{
string accessToken = GetAccessToken(code);
using (WebClient client = new WebClient())
{
//client.Headers.Add("Authorization", "Bearer " + accessToken);
client.Encoding = System.Text.Encoding.UTF8;
string jsonData = client.DownloadString("https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + accessToken);
//string jsonData = client.DownloadString("https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=" + accessToken);
//{
//"id": "106533780795992518088",
// "email": "devproduction.vn@gmail.com",
// "verified_email": true,
// "name": "",
// "given_name": "",
// "family_name": "",
// "picture": "https://lh4.googleusercontent.com/-IRPnaUrro-g/AAAAAAAAAAI/AAAAAAAAAAc/wji_sJlfe8A/photo.jpg"
//}
Logs.SaveLog("Result Login GG: " + jsonData);
var d = JsonConvert.DeserializeObject<GoogleUserOutputData>(jsonData);
return d;
}
}
catch (Exception ex)
{
Logs.SaveError("Error GetGoogleUserInfo: " + ex);
throw new Exception(ex.Message);
}
}
}
public class GoogleUserOutputData
{
public GoogleUserOutputData() {
id = "";
name = "";
given_name = "";
email = "";
picture = "";
}
public string id { get; set; }
public string name { get; set; }
public string given_name { get; set; }
public string email { get; set; }
public string picture { get; set; }
}
} |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="BaseHierarchicalQueryOver.cs" company="CGI">
// Copyright (c) CGI. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CGI.Reflex.Core.Entities;
using NHibernate;
using NHibernate.Transform;
namespace CGI.Reflex.Core.Queries
{
public abstract class BaseHierarchicalQueryOver<T>
where T : BaseHierarchicalEntity<T>
{
protected BaseHierarchicalQueryOver(int defaultNumberOfEagerLoading = 3)
{
NumberOfEagerLoadingLevels = defaultNumberOfEagerLoading;
}
public int NumberOfEagerLoadingLevels { get; set; }
public virtual IQueryOver<T, T> Over()
{
return Over(References.NHSession);
}
public virtual IQueryOver<T, T> Over(ISession session)
{
if (NumberOfEagerLoadingLevels > 5)
throw new InvalidOperationException("It is not recommended to have a number of eager loading levels > 5. Override Over(ISession) to by pass the limit if you want.");
var queryOver = OverImpl(session);
if (NumberOfEagerLoadingLevels > 0)
queryOver = queryOver.Fetch(x => x.Children).Eager;
if (NumberOfEagerLoadingLevels > 1)
queryOver = queryOver.Fetch(x => x.Children.First().Children).Eager;
if (NumberOfEagerLoadingLevels > 2)
queryOver = queryOver.Fetch(x => x.Children.First().Children.First().Children).Eager;
if (NumberOfEagerLoadingLevels > 3)
queryOver = queryOver.Fetch(x => x.Children.First().Children.First().Children.First().Children).Eager;
if (NumberOfEagerLoadingLevels > 4)
queryOver = queryOver.Fetch(x => x.Children.First().Children.First().Children.First().Children.First().Children).Eager;
queryOver.TransformUsing(Transformers.DistinctRootEntity);
return queryOver;
}
public virtual IQueryOver<T, T> FetchParents()
{
return FetchParents(References.NHSession);
}
public virtual IQueryOver<T, T> FetchParents(ISession session)
{
if (NumberOfEagerLoadingLevels > 5)
throw new InvalidOperationException("It is not recommended to have a number of eager loading levels > 5. Override Over(ISession) to by pass the limit if you want.");
var queryOver = OverImpl(session);
if (NumberOfEagerLoadingLevels > 0)
queryOver = queryOver.Fetch(x => x.Parent).Eager;
if (NumberOfEagerLoadingLevels > 1)
queryOver = queryOver.Fetch(x => x.Parent.Parent).Eager;
if (NumberOfEagerLoadingLevels > 2)
queryOver = queryOver.Fetch(x => x.Parent.Parent.Parent).Eager;
if (NumberOfEagerLoadingLevels > 3)
queryOver = queryOver.Fetch(x => x.Parent.Parent.Parent.Parent).Eager;
if (NumberOfEagerLoadingLevels > 4)
queryOver = queryOver.Fetch(x => x.Parent.Parent.Parent.Parent.Parent).Eager;
queryOver.TransformUsing(Transformers.DistinctRootEntity);
return queryOver;
}
public virtual T SingleOrDefault()
{
return SingleOrDefault(References.NHSession);
}
public virtual T SingleOrDefault(ISession session)
{
return Over(session).SingleOrDefault();
}
public virtual IEnumerable<T> List()
{
return List(References.NHSession);
}
public virtual IEnumerable<T> List(ISession session)
{
return Over(session).List();
}
public virtual int Count()
{
return Count(References.NHSession);
}
public virtual int Count(ISession session)
{
var countQueryOver = Over(session);
countQueryOver.ClearOrders();
return countQueryOver.RowCount();
}
protected abstract IQueryOver<T, T> OverImpl(ISession session);
}
}
|
using System.Collections.Generic;
using Psub.DTO.Entities;
namespace Psub.DataService.Abstract
{
public interface ICatalogMainSectionService
{
PublicationMainSectionDTO GetCatalogSectionDTOById(int id);
PublicationMainSectionDTO GetCatalogSectionDTOByName(string name);
IEnumerable<PublicationMainSectionDTO> GetCatalogSectionDTOList();
int SaveOrUpdate(PublicationMainSectionDTO catalogMainSectionDTO);
void Delete(int id);
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SFP.Persistencia.Dao;
using SFP.Persistencia.Model;
using SFP.SIT.SERV.Model.RESP;
namespace SFP.SIT.SERV.Dao.RESP
{
public class SIT_RESP_TURNARDao : BaseDao
{
public SIT_RESP_TURNARDao(DbConnection cn, DbTransaction transaction, String dataAdapter) : base(cn, transaction, dataAdapter)
{
}
public Object dmlAgregar(SIT_RESP_TURNAR oDatos)
{
String sSQL = " INSERT INTO SIT_RESP_TURNAR( araclave, usrclave, turinstruccion, repclave) VALUES ( :P0, :P1, :P2, :P3) ";
return EjecutaDML ( sSQL, oDatos.araclave, oDatos.usrclave, oDatos.turinstruccion, oDatos.repclave );
}
public int dmlImportar( List<SIT_RESP_TURNAR> lstDatos)
{
int iTotReg = 0;
String sSQL = " INSERT INTO SIT_RESP_TURNAR( araclave, usrclave, turinstruccion, repclave) VALUES ( :P0, :P1, :P2, :P3) ";
foreach (SIT_RESP_TURNAR oDatos in lstDatos)
{
EjecutaDML ( sSQL, oDatos.araclave, oDatos.usrclave, oDatos.turinstruccion, oDatos.repclave );
iTotReg++;
}
return iTotReg;
}
public int dmlEditar(SIT_RESP_TURNAR oDatos)
{
String sSQL = " UPDATE SIT_RESP_TURNAR SET turinstruccion = :P0 WHERE araclave = :P1 AND repclave = :P2 AND usrclave = :P3 ";
return (int) EjecutaDML ( sSQL, oDatos.turinstruccion, oDatos.araclave, oDatos.repclave, oDatos.usrclave );
}
public int dmlBorrar(SIT_RESP_TURNAR oDatos)
{
String sSQL = " DELETE FROM SIT_RESP_TURNAR WHERE araclave = :P0 AND repclave = :P1 AND usrclave = :P2 ";
return (int) EjecutaDML ( sSQL, oDatos.araclave, oDatos.repclave, oDatos.usrclave );
}
public List<SIT_RESP_TURNAR> dmlSelectTabla( )
{
String sSQL = " SELECT * FROM SIT_RESP_TURNAR ";
return CrearListaMDL<SIT_RESP_TURNAR>(ConsultaDML(sSQL) as DataTable);
}
public List<ComboMdl> dmlSelectCombo( )
{
throw new NotImplementedException();
}
public Dictionary<int, string> dmlSelectDiccionario( )
{
throw new NotImplementedException();
}
public SIT_RESP_TURNAR dmlSelectID(SIT_RESP_TURNAR oDatos )
{
String sSQL = " SELECT * FROM SIT_RESP_TURNAR WHERE araclave = :P0 AND repclave = :P1 AND usrclave = :P2 ";
return CrearListaMDL<SIT_RESP_TURNAR>(ConsultaDML ( sSQL, oDatos.araclave, oDatos.repclave, oDatos.usrclave ) as DataTable)[0];
}
public object dmlCRUD( Dictionary<string, object> dicParam )
{
int iOper = (int)dicParam[CMD_OPERACION];
if (iOper == OPE_INSERTAR)
return dmlAgregar(dicParam[CMD_ENTIDAD] as SIT_RESP_TURNAR );
else if (iOper == OPE_EDITAR)
return dmlEditar(dicParam[CMD_ENTIDAD] as SIT_RESP_TURNAR );
else if (iOper == OPE_BORRAR)
return dmlBorrar(dicParam[CMD_ENTIDAD] as SIT_RESP_TURNAR );
else
return 0;
}
/*INICIO*/
public List<SIT_RESP_TURNAR> dmlSelectTurnarResp( long repClave)
{
String sSQL = " SELECT * FROM SIT_RESP_TURNAR WHERE repclave = :P0 ";
return CrearListaMDL<SIT_RESP_TURNAR>(ConsultaDML(sSQL, repClave) as DataTable);
}
/*FIN*/
}
}
|
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class dragDrop : MonoBehaviour {
public GameObject gameControl;
private bool dragging = false;
private float distance;
GameObject drag;
float shelf0x;
float shelf1x;
float shelf2x;
float shelf3x;
float shelf4x;
float shelf5x;
float shelf0y;
float shelf1y;
float shelf2y;
float shelf3y;
float shelf4y;
float shelf5y;
public float carb;
public float fat;
public float prot;
private int count;
void Start(){
GameObject.Find ("Errors").GetComponent<Text> ().text = "Select "+ (5 - gameControl.GetComponent<GameControl> ().count) +" more object(s)";
}
void OnMouseDown()
{
if (gameObject.name.Contains("drag")) {
Destroy (gameObject);
gameControl.GetComponent<GameControl> ().count -= 1;
gameControl.GetComponent<GameControl> ().RemoveCarb (carb);
gameControl.GetComponent<GameControl> ().RemoveFat (fat);
gameControl.GetComponent<GameControl> ().RemoveProt (prot);
GameObject.Find ("Errors").GetComponent<Text> ().text = "Select "+ (5 - gameControl.GetComponent<GameControl> ().count) +" more object(s)";
} else {
if (gameControl.GetComponent<GameControl>().count < 5) {
distance = Vector3.Distance (transform.position, Camera.main.transform.position);
dragging = true;
drag = Instantiate (gameObject);
drag.name = "drag"+gameObject.name;
} else {
GameObject.Find ("Errors").GetComponent<Text> ().text = "Too many objects,\ndelete some";
}
}
}
void OnMouseUp()
{
if (gameControl.GetComponent<GameControl> ().count < 5) {
dragging = false;
drag.transform.position = new Vector3 (drag.transform.position.x, drag.transform.position.y, 553);
if (drag.transform.position.x < 0) {
gameControl.GetComponent<GameControl> ().AddToCarb (carb);
gameControl.GetComponent<GameControl> ().AddToFat (fat);
gameControl.GetComponent<GameControl> ().AddToProt (prot);
gameControl.GetComponent<GameControl> ().count += 1;
GameObject.Find ("Errors").GetComponent<Text> ().text = "Select "+ (5 - gameControl.GetComponent<GameControl> ().count) +" more object(s)";
}
}
}
void Update()
{
if (dragging)
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
Vector3 rayPoint = ray.GetPoint(554.0f);
drag.transform.position = rayPoint;
}
}
}
|
using System.Collections.Generic;
using Microsoft.AspNetCore.Identity;
namespace HseClass.Data.Entities
{
public class User : IdentityUser<int>
{
public string Name { get; set; }
public List<UserClass> UserClasses { get; set; } = new List<UserClass>();
public List<SolutionLab> SolutionLabs { get; set; } = new List<SolutionLab>();
}
} |
// Copyright (c) 2011 - OJ Reeves & Jeremiah Peschka
//
// This file is provided to you under the Apache License,
// Version 2.0 (the "License"); you may not use this file
// except in compliance with the License. You may obtain
// a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
using System.Text;
using System.Collections.Generic;
namespace CorrugatedIron.Models.RiakSearch
{
public class Group : RiakSearchQueryPart
{
private List<RiakSearchQueryPart> _parts;
public Group()
{
_parts = new List<RiakSearchQueryPart>();
}
public Group AddItem(RiakSearchQueryPart item)
{
_parts.Add(item);
return this;
}
public override void ToSearchTerm(StringBuilder sb)
{
sb.Append("(");
foreach (var part in _parts)
{
part.ToSearchTerm(sb);
}
sb.Append(")");
}
}
}
|
namespace UserStorageServices.Notification
{
internal interface INotificationSerializer
{
string Serialize(NotificationContainer container);
NotificationContainer Deserialize(string container);
}
}
|
using MyCashFlow.Web.Infrastructure.Automapper;
using MyCashFlow.Web.ViewModels.Shared;
using Rsx = MyCashFlow.Resources.Localization.Views;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System;
namespace MyCashFlow.Web.ViewModels.Transaction
{
public class TransactionCreateViewModel :
CreatorBaseViewModel,
IMapTo<Domains.DataObject.Transaction>
{
public TransactionCreateViewModel()
: base(title: Rsx.Transaction._Shared.Title,
header: string.Format(Rsx.Shared.Create.Header, Rsx.Transaction._Shared.Title.ToLower()))
{ }
[DataType(DataType.Date)]
[Display(Name = nameof(Rsx.Transaction._Shared.Field_Date), ResourceType = typeof(Rsx.Transaction._Shared))]
public DateTime Date { get; set; }
[Display(Name = nameof(Rsx.Transaction._Shared.Field_Amount), ResourceType = typeof(Rsx.Transaction._Shared))]
public decimal Amount { get; set; }
[DataType(DataType.MultilineText)]
[Display(Name = nameof(Rsx.Transaction._Shared.Field_Note), ResourceType = typeof(Rsx.Transaction._Shared))]
public string Note { get; set; }
[Display(Name = nameof(Rsx.Transaction._Shared.Field_Income), ResourceType = typeof(Rsx.Transaction._Shared))]
public bool Income { get; set; }
[Display(Name = nameof(Rsx.Transaction._Shared.Field_Project), ResourceType = typeof(Rsx.Transaction._Shared))]
public int? ProjectID { get; set; }
public IList<Domains.DataObject.Project> Projects { get; set; }
[Display(Name = nameof(Rsx.Transaction._Shared.Field_TransactionType), ResourceType = typeof(Rsx.Transaction._Shared))]
public int TransactionTypeID { get; set; }
public IEnumerable<Domains.DataObject.TransactionType> TransactionTypes { get; set; }
[Display(Name = nameof(Rsx.Transaction._Shared.Field_PaymentMethod), ResourceType = typeof(Rsx.Transaction._Shared))]
public int? PaymentMethodID { get; set; }
public IEnumerable<Domains.DataObject.PaymentMethod> PaymentMethods { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.IO;
using ChesterDevs.Core.Aspnet.App.RemoteData;
namespace Tests
{
public class HttpWrapperFake : IHttpWrapper
{
private Stream _getDataSource;
public List<string> UrlRequests = new List<string>();
public void SetupGetData(Stream data)
{
_getDataSource = data;
}
public T GetData<T>(string url, Func<Stream, T> responseBuilder)
{
UrlRequests.Add(url);
return responseBuilder(_getDataSource);
}
}
} |
namespace WpfAppAbit2.Models
{
/// <summary>
/// уровень бюджета
/// </summary>
public class LevelBudget : SimpleClass
{
}
}
|
using System.ComponentModel.DataAnnotations;
namespace ToDoApp.Api.Dtos.List
{
public class ListPostDto
{
/// <summary>
/// Title of list
/// </summary>
[Required]
public string Title { get; set; }
/// <summary>
/// Background color of list
/// </summary>
[Required]
public string Color { get; set; }
}
}
|
using System;
using System.Windows.Forms;
namespace MH_Database
{
public partial class Language_Selection : Form
{
public string lang = "\0";
public bool closedByProgram = false;
public Language_Selection()
{
InitializeComponent();
}
private void French_language_Click(object sender, EventArgs e)
{
lang = "fr";
Hide();
Game_Selection_International game_Selection = new Game_Selection_International(lang);
game_Selection.ShowDialog();
Close();
}
private void English_language_Click(object sender, EventArgs e)
{
lang = "en";
Hide();
Game_Selection_International game_Selection = new Game_Selection_International(lang);
game_Selection.ShowDialog();
Close();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
/// <summary>
/// Response Staff
/// </summary>
public class Results
{
public string status { get; set; }
public string message { get; set; }
public string result { get; set; }
public string type { get; set; }
} |
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace WebApplication.Models
{
public class Category : PublicKeyEntity
{
[Required]
public string CategoryName { set; get; }
public virtual ICollection<Post> Posts { set; get; } = new HashSet<Post>();
}
} |
using System;
using System.Collections.Generic;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
namespace MCC.Utility.Net
{
public class WebSocketClient : ILogged
{
protected ClientWebSocket client;
/// <summary>
/// 接続しているかどうか
/// </summary>
public bool Connected { get; set; }
/// <summary>
/// 接続先URL
/// </summary>
public Uri URL { get; set; }
public event LoggedEventHandler OnLogged;
public async void Start(Dictionary<string, string> header = null) => Start(v => Process(v), header);
public async void Start(Action<ClientWebSocket> action, Dictionary<string, string> header = null)
{
if (client is null)
{
client = new();
}
if (!Connected)
{
try
{
if (header is not null)
{
foreach (var item in header)
{
client.Options.SetRequestHeader(item.Key, item.Value);
}
}
await client.ConnectAsync(URL, CancellationToken.None);
Connected = true;
Logged(LogLevel.Info, $"接続を開始しました。");
// 受信開始
action(client);
}
catch (Exception e)
{
Logged(LogLevel.Error, $"[{e.InnerException}] {e.Message.ToString()}");
}
}
}
public async void Send(string message) => Send(message, Encoding.UTF8);
public async void Send(string message, Encoding encoding)
{
var buffer = encoding.GetBytes(message);
var segment = new ArraySegment<byte>(buffer);
await client.SendAsync(segment, WebSocketMessageType.Text, true, CancellationToken.None);
}
protected virtual void Process(ClientWebSocket client) => throw new NotImplementedException();
public void Abort()
{
if (client is not null)
{
if (client.State == WebSocketState.Open)
{
client.CloseAsync(WebSocketCloseStatus.NormalClosure, "OK", CancellationToken.None);
}
client.Abort();
client.Dispose();
client = null;
URL = null;
Connected = false;
Logged(LogLevel.Info, $"接続を閉じました。");
}
}
public void Logged(LogLevel level, string message) => OnLogged?.Invoke(this, new(level, message));
}
}
|
/*
* Copyright (c) 2017 Samsung Electronics Co., Ltd. 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 Xamarin.Forms;
using ElmSharp;
using BasicCalculator.ViewModels;
namespace BasicCalculator.Tizen.Mobile.Views
{
/// <summary>
/// MainPage Xaml C# partial class code.
/// </summary>
public partial class MobileMainView
{
EcoreEvent<EcoreKeyEventArgs> _ecoreKeyUp;
/// <summary>
/// Class constructor.
/// Initializes component (Xaml partial).
/// </summary>
public MobileMainView()
{
InitializeComponent();
_ecoreKeyUp = new EcoreEvent<EcoreKeyEventArgs>(EcoreEventType.KeyUp, EcoreKeyEventArgs.Create);
_ecoreKeyUp.On += _ecoreKeyUp_On;
}
private void _ecoreKeyUp_On(object sender, EcoreKeyEventArgs e)
{
// e.KeyName, e.KeyCode
DependencyService.Get<IKeyboardService>().KeyEvent(sender, e);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using FastSQL.Sync.Core.Enums;
namespace FastSQL.Sync.Core.Processors
{
public class PromotionAttributeProcessor : IProcessor
{
public string Id => "promotion_attribute_VQXNPkddwQW7Ea419Py/lmPlA==";
public string Name => "Promotion Attribute Sync";
public string Description => "Promotion Attribute Sync";
public ProcessorType Type => ProcessorType.Attribute;
}
}
|
using System.Drawing;
using System.Collections.Generic;
namespace ZiZhuJY.ImageHandler
{
public class TextWatermarker : Watermarker
{
#region Properties
private string watermarkText;
public string WatermarkText
{
get
{
return watermarkText;
}
set
{
watermarkText = value;
}
}
// 自动计算最合适的水印文本字体大小
private bool autoSize = true;
public bool AutoSize
{
get
{
return autoSize;
}
set
{
autoSize = value;
}
}
private double fontSizePercent;
public double FontSizePercent
{
get { return fontSizePercent; }
set {
fontSizePercent = value > 1 ? 1 : (value <= 0.01 ? 0.01 : value);
}
}
private List<Font> fonts = new List<Font>();
public List<Font> Fonts
{
get
{
return fonts;
}
set
{
fonts = value;
}
}
private Font bestFont = new Font("Arial", 12, FontStyle.Regular, GraphicsUnit.Pixel);
public Font BestFont{
get{
return bestFont;
}
set
{
bestFont = value;
}
}
private StringFormat StringFormat
{
get
{
StringFormat format = new StringFormat();
if (this.ComputeX)
{
switch (this.HorizontalPosition)
{
case WatermarkHorizontalPostion.Left:
format.Alignment = StringAlignment.Near;
break;
case WatermarkHorizontalPostion.Center:
format.Alignment = StringAlignment.Center;
break;
case WatermarkHorizontalPostion.Right:
format.Alignment = StringAlignment.Far;
break;
}
}
else
{
format.Alignment = StringAlignment.Near;
}
return format;
}
}
#endregion
#region Constructor
public TextWatermarker(Image originImage, string watermarkText) : base(originImage)
{
this.WatermarkText = watermarkText;
// Default values
this.Fonts.Add(new Font("Arial", 18, FontStyle.Regular, GraphicsUnit.Pixel));
this.Fonts.Add(new Font("Arial", 16, FontStyle.Regular, GraphicsUnit.Pixel));
this.Fonts.Add(new Font("Arial", 14, FontStyle.Regular, GraphicsUnit.Pixel));
this.Fonts.Add(new Font("Arial", 12, FontStyle.Regular, GraphicsUnit.Pixel));
this.Fonts.Add(new Font("Arial", 10, FontStyle.Regular, GraphicsUnit.Pixel));
this.Fonts.Add(new Font("Arial", 8, FontStyle.Regular, GraphicsUnit.Pixel));
this.Fonts.Add(new Font("Arial", 6, FontStyle.Regular, GraphicsUnit.Pixel));
this.Fonts.Add(new Font("Arial", 4, FontStyle.Regular, GraphicsUnit.Pixel));
this.FontSizePercent = 30.00 / 480.00;
this.AutoSize = true;
}
#endregion
#region Methods
public void ChangeFont(string fontFamily, bool bold, bool italic, bool underline, bool strikeThrough)
{
FontStyle fontStyle = FontStyle.Regular;
if (bold) fontStyle = fontStyle | FontStyle.Bold;
if (italic) fontStyle = fontStyle | FontStyle.Italic;
if (underline) fontStyle = fontStyle | FontStyle.Underline;
if (strikeThrough) fontStyle = fontStyle | FontStyle.Strikeout;
ChangeFont(fontFamily, fontStyle);
}
public void ChangeFontFamily(string fontFamily)
{
FontFamily ff = new FontFamily(fontFamily);
ChangeFontFamily(ff);
}
public void ChangeFont(string fontFamily, FontStyle fontStyle)
{
for (int i = 0; i < this.Fonts.Count; i++)
{
this.Fonts[i] = new Font(fontFamily, this.Fonts[i].Size, fontStyle, this.Fonts[i].Unit, this.Fonts[i].GdiCharSet, this.Fonts[i].GdiVerticalFont);
}
this.BestFont = new Font(fontFamily, this.BestFont.Size, fontStyle, this.BestFont.Unit, this.BestFont.GdiCharSet, this.BestFont.GdiVerticalFont);
}
public void ChangeFont(FontFamily fontFamily, FontStyle fontStyle)
{
for (int i = 0; i < this.Fonts.Count; i++)
{
this.Fonts[i] = new Font(fontFamily, this.Fonts[i].Size, fontStyle, this.Fonts[i].Unit, this.Fonts[i].GdiCharSet, this.Fonts[i].GdiVerticalFont);
}
this.BestFont = new Font(fontFamily, this.BestFont.Size, fontStyle, this.BestFont.Unit, this.BestFont.GdiCharSet, this.BestFont.GdiVerticalFont);
}
public void ChangeFontFamily(Font font)
{
for (int i = 0; i < this.Fonts.Count; i++)
{
this.Fonts[i] = new Font(font.FontFamily, this.Fonts[i].Size, font.Style, this.Fonts[i].Unit, this.Fonts[i].GdiCharSet, this.Fonts[i].GdiVerticalFont);
}
this.BestFont = new Font(font.FontFamily, this.BestFont.Size, font.Style, this.BestFont.Unit, this.BestFont.GdiCharSet, this.BestFont.GdiVerticalFont);
}
public void ChangeFontFamily(FontFamily fontFamily)
{
for (int i = 0; i < this.Fonts.Count; i++)
{
this.Fonts[i] = new Font(fontFamily, this.Fonts[i].Size, this.Fonts[i].Style, this.Fonts[i].Unit, this.Fonts[i].GdiCharSet, this.Fonts[i].GdiVerticalFont);
}
this.BestFont = new Font(fontFamily, this.BestFont.Size, this.BestFont.Style, this.BestFont.Unit, this.BestFont.GdiCharSet, this.BestFont.GdiVerticalFont);
}
protected override SizeF ComputeWatermarkSize()
{
FindAvailableMaxSizedFont();
return this.WatermarkSize;
}
protected override void UpdateXY()
{
if (this.ComputeX)
{
switch (this.HorizontalPosition)
{
case WatermarkHorizontalPostion.Left:
this.X = this.HorizontalMarginPixel;
break;
case WatermarkHorizontalPostion.Center:
this.X = this.OriginImage.Width / 2;
break;
case WatermarkHorizontalPostion.Right:
this.X = (this.OriginImage.Width - this.HorizontalMarginPixel);
break;
default:
break;
}
}
if (this.ComputeY)
{
switch (this.VerticalPosition)
{
case WatermarkVerticalPostion.Top:
this.Y = this.VerticalMarginPixel;
break;
case WatermarkVerticalPostion.Middle:
this.Y = this.OriginImage.Height / 2 - this.WatermarkSize.Height / 2;
break;
case WatermarkVerticalPostion.Bottom:
this.Y = (this.OriginImage.Height - this.VerticalMarginPixel - this.WatermarkSize.Height);
break;
default:
break;
}
}
}
protected override Image AddWatermarkToOriginImage()
{
this.WatermarkedImage = this.OriginImage;
if (this.BestFont != null)
{
Graphics g = Graphics.FromImage(this.WatermarkedImage);
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
SolidBrush semiTransBrushShadow = new SolidBrush(this.ShadowColor);
StringFormat format = this.StringFormat;
g.DrawString(this.WatermarkText, this.BestFont, semiTransBrushShadow, new PointF(this.X + this.ShadowOffsetX, this.Y + this.ShadowOffsetY), format);
SolidBrush semiTransBrush = new SolidBrush(this.ForeColor);
g.DrawString(this.WatermarkText, this.BestFont, semiTransBrush, new PointF(this.X, this.Y), format);
g.Dispose();
}
return this.WatermarkedImage;
}
private Font FindAvailableMaxSizedFont()
{
if (this.AutoSize)
{
this.BestFont = FindAvailableMaxSizedFont(false);
if (this.BestFont != null)
{
if (this.BestFont.Size >= 16)
{
return this.BestFont;
}
else
{
return FindAvailableMaxSizedFont(true);
}
}
else
{
return null;
}
}
else
{
return FindAvailableMaxSizedFont(true);
}
}
private Font FindAvailableMaxSizedFont(bool byAbsoluteSizes)
{
if (byAbsoluteSizes)
{
this.Fonts.Sort(delegate(Font font1, Font font2) { return font2.Size.CompareTo(font1.Size); });
SizeF size = new SizeF();
Bitmap image = new Bitmap(1, 1);
Graphics g = Graphics.FromImage(image);
for (int i = 0; i < this.Fonts.Count; i++)
{
//size = MeasureSize(this.WatermarkText, this.Fonts[i]);
size = g.MeasureString(this.WatermarkText, this.Fonts[i]);
if ((ushort)(size.Width + this.HorizontalMarginPixel * 2) < (ushort)this.OriginImage.Width && (ushort)(size.Height + this.VerticalMarginPixel * 2) < (ushort)this.OriginImage.Height)
{
g.Dispose();
image.Dispose();
this.WatermarkSize = size;
this.BestFont = this.fonts[i];
return this.Fonts[i];
}
}
g.Dispose();
image.Dispose();
this.WatermarkSize = new SizeF(0, 0);
return null;
}
else
{
int fontSize = (int)(this.OriginImage.Height * this.FontSizePercent);
fontSize = fontSize >= 1 ? fontSize : 1;
this.BestFont = new Font(this.BestFont.FontFamily, fontSize, this.BestFont.Style, this.BestFont.Unit);
this.WatermarkSize = MeasureSize(this.WatermarkText, this.BestFont);
if ((ushort)(this.WatermarkSize.Width + this.HorizontalMarginPixel * 2) < (ushort)this.OriginImage.Width && (ushort)(this.WatermarkSize.Height + this.VerticalMarginPixel * 2) < (ushort)this.OriginImage.Height)
{
return this.BestFont;
}
else
{
this.WatermarkSize = new SizeF(0, 0);
return null;
}
}
}
private SizeF MeasureSize(string text, Font font)
{
// Use a test image to measure the text.
Bitmap image = new Bitmap(1, 1);
Graphics g = Graphics.FromImage(image);
SizeF size = g.MeasureString(text, font);
g.Dispose();
image.Dispose();
return size;
}
#endregion
}
}
|
namespace DpiConverter.Data
{
using System;
using System.Collections.Generic;
using Helpers;
internal class Observation
{
private string featureCode = string.Empty;
private string targetPoint;
private double targetHeight;
private double horizontalAngle;
private double slopeDistance;
private double zenithAngle;
private string pointDescription = string.Empty;
private double? verticalAngleMisclosure = null;
private double? horizontalAngleMisclosure = null;
private ObservationPurpose purpose = ObservationPurpose.Sideshot;
public Observation(string featureCode, string targetPoint, double targetHeight, double horizontalAngle, double slopeDistance, double zenithAngle, string pointDescription)
{
this.featureCode = featureCode;
this.targetPoint = targetPoint;
this.targetHeight = targetHeight;
this.horizontalAngle = horizontalAngle;
this.slopeDistance = slopeDistance;
this.zenithAngle = zenithAngle;
this.pointDescription = pointDescription;
}
public static ICollection<string> PredefinedCodes
{
get
{
return new List<string>() { "tt", "pt", "ot", "lt", "nr" };
}
}
public double? HorizontalAngleMisclosure
{
get
{
return this.horizontalAngleMisclosure;
}
set
{
this.horizontalAngleMisclosure = value;
}
}
public ObservationPurpose Purpose
{
get
{
return this.purpose;
}
set
{
this.purpose = value;
}
}
public double? VerticalAngleMisclosure
{
get
{
return this.verticalAngleMisclosure;
}
set
{
this.verticalAngleMisclosure = value;
}
}
public string PointDescription
{
get
{
return this.pointDescription;
}
set
{
this.pointDescription = value;
}
}
public string FullName
{
get
{
return string.Format("{0}{1}", this.featureCode, this.targetPoint);
}
set
{
if (string.IsNullOrWhiteSpace(value))
{
throw new ArgumentException("Невалиден номер на точка!");
}
string featureCode = StationHelper.ParseCode(value);
string pointNumber = StationHelper.ParseNumber(value);
this.FeatureCode = featureCode;
this.TargetPoint = pointNumber;
}
}
public string FeatureCode
{
get
{
return this.featureCode;
}
set
{
this.featureCode = value;
}
}
public string TargetPoint
{
get
{
return this.targetPoint;
}
set
{
if (string.IsNullOrWhiteSpace(value))
{
throw new ArgumentException("Невалиден номер на наблюдавана точка!");
}
this.targetPoint = value;
}
}
public double TargetHeight
{
get
{
return this.targetHeight;
}
set
{
this.targetHeight = value;
}
}
public double HorizontalAngle
{
get
{
return this.horizontalAngle;
}
set
{
if (value < 0)
{
throw new ArgumentOutOfRangeException("Хоризонталният ъгъл не може да бъде по-малък от 0 гради!");
}
if (value >= 400)
{
throw new ArgumentOutOfRangeException("Хоризонталният ъгъл не може да бъде по-голям или равен на 400 гради!");
}
this.horizontalAngle = value;
}
}
public double SlopeDistance
{
get
{
return this.slopeDistance;
}
set
{
this.slopeDistance = value;
}
}
public double ZenithAngle
{
get
{
return this.zenithAngle;
}
set
{
if (value < 0.0000)
{
throw new ArgumentOutOfRangeException("Зенитният ъгъл не може да бъде по-малък от 0 гради!");
}
if (value >= 400.0000)
{
throw new ArgumentOutOfRangeException("Зенитният ъгъл не може да бъде по-голям или равен на 400 гради!");
}
this.zenithAngle = value;
}
}
}
} |
using System;
using System.IO;
using cloudfiles.contract;
namespace cloudfiles.blockstore
{
internal class BlockStore
{
private const int DEFAULT_BLOCK_SIZE = 100*1024;
private readonly BlockGroup_operations _groupOps;
private readonly BlockGroupHead_operations _headOps;
private readonly int _blockSize;
public BlockStore(IKeyValueStore cache) : this(cache, DEFAULT_BLOCK_SIZE) {}
public BlockStore(IKeyValueStore cache, int blockSize)
{
_groupOps = new BlockGroup_operations(cache, blockSize);
_headOps = new BlockGroupHead_operations(cache);
_blockSize = blockSize;
}
public void Store_blocks(Stream source)
{
var blockGroupId = Guid.NewGuid();
var summary = new BlockUploadSummary {BlockGroupId = blockGroupId, BlockSize = _blockSize};
_groupOps.Stream_blocks(source, block0 =>
Store_block(blockGroupId, block0, block1 =>
summary.Aggregate(block1, _ =>
{
_headOps.Write_number_of_blocks(_.BlockGroupId, _.NumberOfBlocks);
On_blocks_stored(_);
})));
}
internal void Store_block(Guid blockGroupId, Tuple<byte[], int> block, Action<Tuple<byte[], int>> on_block)
{
var blockKey = blockGroupId.Build_block_key_for_index(block.Item2);
_groupOps.Upload_block(blockKey, block.Item1);
on_block(block);
}
public void Load_blocks(Guid blockGroupId, Stream destination)
{
var numberOfBlocks = _headOps.Read_number_of_blocks(blockGroupId);
_groupOps.Stream_block_keys(blockGroupId, numberOfBlocks, blockKey =>
{
var blockContent = _groupOps.Download_block(blockKey);
_groupOps.Write_content(blockContent, destination);
});
}
public event Action<BlockUploadSummary> On_blocks_stored;
}
}
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace Ai
{
public enum AiState
{
Unknown = -1, // 사용하면 안됨.
Sleep, // Ai가동되기 전 첫 상태
Move, // 의미없는 움직임
Chase, // 공격을 위해 적 쫓아가는 상태
Charge, // MP 부족해서 충전해야하는 상태
Launch,
Dodge, // 상대 공격을 피하는 상태
Escape, // 위험한 상태여서 target으로부터 도망치는 상태
Skill, // 스킬 사용중인 상태
}
public abstract class ICharacterAi : MonoBehaviour
{
public AiPlayer AiPlayer { get; protected set; }
public AiState AiState { get; protected set; }
public AiState PrevAiState { get; protected set; }
public CharacterState CharacterState { get { return AiPlayer.TargetCharacter.State; } }
public Vector3 CharacterPosition { get { return AiPlayer.TargetCharacter.transform.position; } }
public ICharacter Character { get { return AiPlayer.TargetCharacter; } }
public int FearPoint { get; private set; } = 0;
public bool IsEscaping { get; set; } = false;
public bool IsMoving { get; set; } = false;
// 지금은 공격 대상이 캐릭터일 때만 구현하지만,
// 나중에 장애물 혹은 NPC등을 공격 대상으로 삼을 수도 있으니 IObject Type으로.
public IObject AttackTarget { get; set; } = null;
public IObject EscapeTarget { get; set; } = null;
public IObject DodgeTarget { get; set; } = null;
public Dictionary<AiState, IAiBehaviour> Behaviours { get; protected set; } = new Dictionary<AiState, IAiBehaviour>();
private Data.FearPointData fearPointData;
protected virtual void CreateBehaviours()
{
Behaviours.Add(AiState.Sleep, new SleepBehaviour(this));
Behaviours.Add(AiState.Move, new MoveBehaviour(this));
Behaviours.Add(AiState.Chase, new ChaseBehaviour(this));
Behaviours.Add(AiState.Charge, new ChargeBehaviour(this));
Behaviours.Add(AiState.Launch, new LaunchBehaviour(this));
Behaviours.Add(AiState.Dodge, new DodgeBehaviour(this));
Behaviours.Add(AiState.Escape, new EscapeBehaviour(this));
Behaviours.Add(AiState.Skill, new SkillBehaviour(this));
}
public void Initialize(AiPlayer player)
{
this.AiPlayer = player;
AiState = AiState.Sleep;
PrevAiState = AiState.Sleep;
player.TargetCharacter.OnCollisionEnter += OnCharacterCollisionEnter;
player.TargetCharacter.OnHpChanged += OnCharacterHpChanged;
player.TargetCharacter.OnMpChanged += OnCharacterMpChanged;
fearPointData = Resources.Load<Data.FearPointData>("Data/Ai/FearPointData_" + Character.CharacterType.ToString());
Debug.Assert(fearPointData != null, "FearPointData is null, ChracterType : " + Character.CharacterType.ToString());
Behaviours.Clear();
CreateBehaviours();
StartCoroutine(TargetSettingProcess());
}
public void Process()
{
if(AttackTarget == null || AttackTarget as MonoBehaviour == null)
{
AttackTarget = null;
}
if(EscapeTarget == null || EscapeTarget as MonoBehaviour == null)
{
EscapeTarget = null;
}
if(DodgeTarget == null || DodgeTarget as MonoBehaviour == null)
{
DodgeTarget = null;
}
UpdateFearPoint();
ProcessDangerDetact();
// 캐릭터를 제어할 수 없는 상태에는 그냥 return 해버리기~
if(CanProcessAi(AiPlayer.TargetCharacter.State) == false)
{
return;
}
AiState = GetTopPriorityBehaviour();
if(AiState != PrevAiState)
{
Behaviours[PrevAiState].CancelBehaviour();
}
Behaviours[AiState].DoBehaviour();
PrevAiState = AiState;
}
// 캐릭터 마다 다를 수 있기 때문에 하위 클래스에서 알아서 구현해서 사용하도록 한다.
protected virtual bool CanProcessAi(CharacterState state)
{
switch (AiPlayer.TargetCharacter.State)
{
case CharacterState.Idle:
break;
case CharacterState.Flying:
return false;
case CharacterState.Dodge:
return false;
case CharacterState.Hitted:
return false;
case CharacterState.SkillActivated:
return false;
}
return true;
}
protected AiState GetTopPriorityBehaviour()
{
// 각각의 상태에 따른 우선순위 결정을 위해 정수형으로 표현.
var behaviourPoints = from behaviourPair in Behaviours
select System.Tuple.Create(behaviourPair.Key, behaviourPair.Value.GetBehaviourPoint());
return (from point in behaviourPoints
orderby point.Item2 descending
select point.Item1).First();
}
public void TryGetItem(ItemType itemType)
{
IItem item = ItemController.Instance.GetNearestItem(itemType, CharacterPosition);
if(item == null)
{
return;
}
Vector2 moveDir = (item.transform.position - CharacterPosition).normalized;
AiPlayer.TargetCharacter.DoMove(moveDir);
}
#region TargetSetting
Coroutine targetSettingCoroutine;
private void OnTargetDeath(IObject character)
{
AttackTarget.OnDestroyed -= OnTargetDeath;
if (targetSettingCoroutine != null)
StopCoroutine(targetSettingCoroutine);
targetSettingCoroutine = StartCoroutine(TargetSettingProcess());
}
private IEnumerator TargetSettingProcess()
{
while(true)
{
const float minDuration = 5f;
const float maxDuration = 15f;
float duration = Random.Range(minDuration, maxDuration);
if(AttackTarget != null)
{
AttackTarget.OnDestroyed -= OnTargetDeath;
}
// 일단 가장 많이 때린 적을 타겟으로
AttackTarget = AttackListener.Instance.GetHighestAttackEnemy(AiPlayer.TargetCharacter);
if(AttackTarget == null) // 아직 하나도 맞은 게 없을 경우,
{
// 가장 가까운 적으로 설정.
AttackTarget = CharacterManager.Instance.GetNearestEnemy(AiPlayer.TargetCharacter);
}
if(AttackTarget != null)
{
AttackTarget.OnDestroyed += OnTargetDeath;
}
yield return new WaitForSeconds(duration);
}
}
#endregion
#region DangerDetact
private ICharacter GetDodgeTargetEnemy()
{
ICharacter[] enemys = CharacterManager.Instance.GetEmemys(Character);
for (int i = 0; i < enemys.Length; ++i)
{
if (enemys[i].IsHighThreat == false)
{
continue;
}
if ((enemys[i].transform.position - CharacterPosition).magnitude < AiDifficultyController.Instance.GetStatusValue(AiConstants.DangerDetactDistance))
{
return enemys[i];
}
}
return null;
}
private float dangerDetactElapsedTime = 0f;
private void ProcessDangerDetact()
{
dangerDetactElapsedTime += Time.deltaTime;
if(dangerDetactElapsedTime < AiDifficultyController.Instance.GetStatusValue(AiConstants.DangerDetactInterval))
{
return;
}
// dodgeTarget이 없을 경우엔 시간초기화 하지 않는다.
DodgeTarget = GetDodgeTargetEnemy();
if(DodgeTarget == null)
{
return;
}
dangerDetactElapsedTime = 0f;
if(AiDifficultyController.Instance.IsRandomActivated(AiConstants.DangerDetactProbability) == false)
{
DodgeTarget = null;
return;
}
}
#endregion
#region
private float fearPointRecoverageTime = 0f;
private void UpdateFearPoint()
{
if(fearPointRecoverageTime + 1f < Time.time)
{
fearPointRecoverageTime = Time.time;
FearPoint -= fearPointData.DecreaseValueForSecond;
}
}
#endregion
#region Event listeners
// ICharacter의 OnCollisionEnter Event listener 함수.
private void OnCharacterCollisionEnter(Collision2D other)
{
if(IsMoving == true)
{
// 또 다른 처리할게 필요할까?
IsMoving = false;
}
}
private void OnCharacterHpChanged(int prevHp, int currHp)
{
if(prevHp == 1 && currHp > 1)
{
IsEscaping = false;
}
int deltaHp = currHp - prevHp;
FearPoint += fearPointData.HpStepChangeValue * deltaHp;
}
private void OnCharacterMpChanged(int prevMp, int currMp)
{
// 이거 조건이 애매하다.. 나중에 다시 확인 필요
if(currMp < fearPointData.MpCheckLimitValue)
{
}
}
#endregion
#region helpers
public void LogAi(string message)
{
//[Player + N][CharcterType] message
Debug.Log(string.Format("[Player{0}][{1}] {2}", AiPlayer.PlayerNumber, AiPlayer.TargetCharacter.CharacterType, message));
}
#endregion
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Shake : MonoBehaviour
{
public Animator _camAnimator;
public void AttackShake()
{
_camAnimator.SetTrigger("AttackShake");
}
}
|
using StockData.Contract;
using StockData.Data;
using System;
using System.Collections.Generic;
using System.Text;
namespace StockData.Repository
{
public static class Mapper
{
public static ProductDto Map(Product entity)
=> new ProductDto
{
Id = entity.ProductId,
Name = entity.ProductName
};
public static ProductQuantityDto Map(ProductQuantity entity)
=> new ProductQuantityDto
{
ProductId = entity.ProductId,
Quantity = entity.Quantity,
};
}
}
|
using System.Web;
using System.Web.Mvc;
using MooshakPP.Handlers;
namespace MooshakPP
{
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new CustomHandlerAttribute());
}
}
}
|
using System;
using System.Collections.Generic;
class DayFive {
public void Run(){
List<string> strList = Input.GetStrings("input_files/Day05.txt");
List<Pass> passList = GetPassList(strList);
List<int> openSeats = FindOpenSeats(passList);
openSeats.ForEach(Console.WriteLine);
}
List<Pass> GetPassList(List<string> strList){
List<Pass> passList = new List<Pass>();
foreach(string str in strList){
passList.Add(new Pass(str));
}
return passList;
}
int FindHighestPassID(List<Pass> passList){
int highestPassID = 0;
foreach(Pass pass in passList){
int passID = pass.GetSeatID();
if(passID > highestPassID) highestPassID = passID;
}
return highestPassID;
}
List<int> FindOpenSeats(List<Pass> passList){
List<int> openSeats = new List<int>();
for(int i = 0; i < 1024; i++){
openSeats.Add(i);
}
foreach(Pass pass in passList){
openSeats.Remove(pass.GetSeatID());
}
return openSeats;
}
}
class Pass{
int row;
int column;
public Pass(string str){
FindRow(str.Substring(0, 7));
FindColumn(str.Substring(7));
}
void FindRow(string rowString){
int lowest = 0;
int highest = 127;
int divider = 64;
foreach(char c in rowString){
if(c == 'F') highest -= divider;
if(c == 'B') lowest += divider;
divider /= 2;
}
row = lowest;
}
void FindColumn(string columnString){
int lowest = 0;
int highest = 7;
int divider = 4;
foreach(char c in columnString){
if(c == 'L') highest -= divider;
if(c == 'R') lowest += divider;
divider /= 2;
}
column = lowest;
}
public int GetSeatID(){
return (row * 8) + column;
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.OpenApi.Models;
using Microsoft.OpenApi.Readers;
using Swaggelot.Models;
namespace Swaggelot.OpenApiCollector
{
public class OpenApiCollector : IOpenApiCollector
{
private readonly HttpClient _client;
private readonly ILogger _logger;
private readonly IEnumerable<SwaggerEndPointOptions> _swaggerEndpoints;
public OpenApiCollector(
IOptions<SwaggerSettings> swaggerSettings,
HttpClient client,
ILogger<OpenApiCollector> logger)
{
_client = client;
_logger = logger;
_swaggerEndpoints = swaggerSettings?.Value?.Endpoints ?? new List<SwaggerEndPointOptions>();
if (swaggerSettings?.Value?.Endpoints == null)
{
_logger.LogWarning($"Swagger settings not found");
}
}
public async Task<Dictionary<SwaggerDescriptor, OpenApiDocument>> CollectDownstreamSwaggersAsync()
{
var loaded = await Task.WhenAll(
_swaggerEndpoints.SelectMany(
x => x.Versions,
(endpoint, config) => LoadSwaggerAsync(endpoint.Key, config)));
return loaded.ToDictionary(x => x.Item1, x => x.Item2);
}
private async Task<(SwaggerDescriptor, OpenApiDocument)> LoadSwaggerAsync(string key,
SwaggerEndPointConfig endpoint)
{
var descriptor = new SwaggerDescriptor(key, endpoint.Version);
try
{
var swaggerJson = await _client.GetStringAsync(endpoint.Url);
var openApi = new OpenApiStringReader().Read(swaggerJson, out _);
return (descriptor, openApi);
}
catch (Exception e)
{
_logger.LogWarning(e, $"Can't load downstream swagger {endpoint.Url}");
return (descriptor, null);
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
namespace Runpath.Common.HttpProcessor
{
public class HttpRequestBuilder
{
private HttpMethod _method = null;
private string _requestUri = "";
private readonly HttpContent _content = null;
private readonly string _acceptHeader = "application/json";
private readonly TimeSpan _timeout = new TimeSpan(0, 0, 15);
private readonly bool _allowAutoRedirect = false;
private readonly List<KeyValuePair<string, string>> _formContentValues = null;
public HttpRequestBuilder()
{
}
public HttpRequestBuilder AddMethod(HttpMethod method)
{
this._method = method;
return this;
}
public HttpRequestBuilder AddRequestUri(string requestUri)
{
this._requestUri = requestUri;
return this;
}
public async Task<HttpResponseMessage> SendAsync()
{
// Check required arguments
EnsureArguments();
// Set up request
var request = new HttpRequestMessage
{
Method = this._method,
RequestUri = new Uri(this._requestUri)
};
if (this._content != null)
request.Content = this._content;
request.Headers.Accept.Clear();
if (!string.IsNullOrEmpty(this._acceptHeader))
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(this._acceptHeader));
if (this._formContentValues != null && this._formContentValues.Count > 0)
request.Content = new FormUrlEncodedContent(this._formContentValues);
// Setup client
var handler = new HttpClientHandler { AllowAutoRedirect = this._allowAutoRedirect };
var client = new System.Net.Http.HttpClient(handler) { Timeout = this._timeout };
return await client.SendAsync(request);
}
#region " Private "
private void EnsureArguments()
{
if (this._method == null)
throw new ArgumentNullException($"Method");
if (string.IsNullOrEmpty(this._requestUri))
throw new ArgumentNullException($"Request Uri");
}
#endregion
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
namespace Audio.Tracks
{
public class musicController : MonoBehaviour
{
[SerializeField] private deviceMusicListing DeviceMusicListing;
[SerializeField] private serverMusicListing ServerMusicListing;
[SerializeField] private MusicManager MusicManager;
[SerializeField] private Button[] actions;
public static List<string> listedMusic;
public static int alreadyIndex = -1;
public static int position;
public static bool devicemode;
public static string trackName = "Empty test";
[SerializeField] private RectTransform rect;
public float height = 820;
public float basic;
public float currently;
private bool lerped, moving;
void Start ()
{
//DeviceMusicListing = gameObject.AddComponent<deviceMusicListing>();
currently = basic;
actions[0].onClick.AddListener(() => ServerLoad());
actions[1].onClick.AddListener(() => DeviceLoad());
actions[2].onClick.AddListener(() => List());
//rect = gameObject.GetComponent<RectTransform>();
}
void ServerLoad()
{
}
void DeviceLoad()
{
DeviceMusicListing.CallManager();
}
public void List()
{
if (!moving)
StartCoroutine(Lerp(lerped));
else
Debug.Log("can't lerp");
}
IEnumerator Lerp(bool status)
{
currently = basic;
status = lerped;
if (!lerped && !moving)
while (!status)
{
if (rect.rect.height < height)
{
var temp = Mathf.Lerp(currently, height, 3 * Time.fixedDeltaTime);
currently += temp - currently;
rect.sizeDelta = new Vector2(526, temp);
moving = true;
}
yield return new WaitForFixedUpdate();
if (rect.rect.height >= height - 10)
{
lerped = true;
moving = false;
yield break;
}
}
if (lerped && !moving)
while (status)
{
var temp = Mathf.Lerp(height, currently, 3 * Time.fixedDeltaTime);
currently = currently - temp;
rect.sizeDelta = new Vector2(526, temp);
moving = true;
yield return new WaitForFixedUpdate();
if (rect.rect.height <= basic)
{
lerped = false;
moving = false;
yield break;
}
}
else if(moving) Debug.Log("Again, wait a bit!");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Metrics;
namespace MetricsDemo
{
public class MetricsKey
{
public static Meter OrderCount
{
//建议MetricsKeyName命名规范:Solution名或应用名+MetricsName
get { return MetricsHelper.Meter("MetricsDemo.OrderCount", Unit.Custom("单")); }
}
public static Meter OrderMoneyCount
{
get { return MetricsHelper.Meter("MetricsDemo.OrderMoneyCount", Unit.Custom("元")); }
}
public static Meter OrderErrorCount
{
get { return MetricsHelper.Meter("MetricsDemo.OrderErrorCount", Unit.Custom("单")); }
}
}
}
|
using Ghost.Extensions;
using System;
using UnityEngine;
namespace RO
{
[CustomLuaClass]
public class AnimatorPlayer : MonoBehaviour
{
[CustomLuaClass]
public class Params
{
public string stateName;
public int layer;
public float normalizedTime;
public float speed = 1f;
}
public Animator[] animators;
public void Play(AnimatorPlayer.Params p)
{
if (this.animators.IsNullOrEmpty<Animator>())
{
return;
}
Animator[] array = this.animators;
for (int i = 0; i < array.Length; i++)
{
Animator animator = array[i];
string stateName = p.stateName;
int num = Animator.StringToHash(stateName);
if (!animator.HasState(p.layer, num))
{
num = animator.GetCurrentAnimatorStateInfo(p.layer).get_shortNameHash();
}
animator.set_speed(p.speed);
animator.Play(num, p.layer, p.normalizedTime);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Monogram.cs
{
class Program
{
static void Monogram(char a, char b, char c)
{
Console.WriteLine("** {0}.{1}.{2}. **", a, b, c);
}
static void Main(string[] args)
{
char f1 = 'B', m1 = 'C', l1 = 'R', f2 = 'M', m2 = 'M', l2 = 'O';
Monogram(f1, m1, l1);
Monogram(f2, m2, l2);
}
}
} |
// ----------------------------------------------------------------------------------------------------------------------------------------
// <copyright file="DequeueOnlyQueue.cs" company="David Eiwen">
// Copyright © 2016 by David Eiwen
// </copyright>
// <author>David Eiwen</author>
// <summary>
// This file contains the DequeueOnlyQueue<T> class.
// </summary>
// ----------------------------------------------------------------------------------------------------------------------------------------
namespace IndiePortable.Collections
{
using System;
using System.Collections;
using System.Collections.Generic;
/// <summary>
/// Represents a queue where items can only be dequeued.
/// </summary>
/// <typeparam name="T">
/// The type of the items in the <see cref="DequeqeOnlyQueue{T}" />.
/// </typeparam>
/// <seealso cref="IEnumerable{T}" />
/// <seealso cref="ICollection" />
/// <seealso cref="IEnumerable" />
public class DequeqeOnlyQueue<T>
: IEnumerable<T>, ICollection, IEnumerable
{
/// <summary>
/// The source <see cref="Queue{T}" />.
/// </summary>
private readonly Queue<T> source;
/// <summary>
/// Initializes a new instance of the <see cref="DequeqeOnlyQueue{T}" /> class.
/// </summary>
/// <param name="source">
/// The source <see cref="Queue{T}" />.
/// </param>
/// <exception cref="ArgumentNullException">
/// <para>Thrown if <paramref name="source" /> is <c>null</c>.</para>
/// </exception>
public DequeqeOnlyQueue(Queue<T> source)
{
if (object.ReferenceEquals(source, null))
{
throw new ArgumentNullException(nameof(source));
}
this.source = source;
}
/// <summary>
/// Gets the number of elements contained in the <see cref="DequeqeOnlyQueue{T}" />.
/// </summary>
/// <value>
/// Contains the number of elements contained in the <see cref="DequeqeOnlyQueue{T}" />.
/// </value>
/// <remarks>
/// <para>Implements <see cref="ICollection.Count" /> implicitly.</para>
/// </remarks>
public int Count => this.source.Count;
/// <summary>
/// Gets a value indicating whether access to the <see cref="DequeqeOnlyQueue{T}" /> is synchronized (thread safe).
/// </summary>
/// <value>
/// Contains a value indicating whether access to the <see cref="DequeqeOnlyQueue{T}" /> is synchronized (thread safe).
/// </value>
/// <remarks>
/// <para>Implements <see cref="ICollection.IsSynchronized" /> implicitly.</para>
/// </remarks>
public bool IsSynchronized => ((ICollection)source).IsSynchronized;
/// <summary>
/// Gets an object that can be used to synchronize access to the <see cref="DequeqeOnlyQueue{T}" />.
/// </summary>
/// <value>
/// Contains an object that can be used to synchronize access to the <see cref="DequeqeOnlyQueue{T}" />.
/// </value>
/// <remarks>
/// <para>Implements <see cref="ICollection.SyncRoot" /> implicitly.</para>
/// </remarks>
public object SyncRoot => ((ICollection)source).SyncRoot;
/// <summary>
/// Returns and removes the object at the beginning of the <see cref="DequeqeOnlyQueue{T}" />.
/// </summary>
/// <returns>
/// The object that is removed from the beginning of the <see cref="DequeqeOnlyQueue{T}" />.
/// </returns>
/// <exception cref="InvalidOperationException">
/// <para>Thrown if the <see cref="DequeqeOnlyQueue{T}" /> is empty.</para>
/// </exception>
public T Dequeue() => this.source.Dequeue();
/// <summary>
/// Returns the object at the beginning of the<see cref="DequeqeOnlyQueue{T}" /> without removing it.
/// </summary>
/// <returns>
/// The object at the beginning of the <see cref="DequeqeOnlyQueue{T}" />.
/// </returns>
/// <exception cref="InvalidOperationException">
/// <para>Thrown if the <see cref="DequeqeOnlyQueue{T}" /> is empty.</para>
/// </exception>
public T Peek() => this.source.Peek();
/// <summary>
/// Copies the elements of the <see cref="DequeqeOnlyQueue{T}" /> to an <see cref="Array" />,
/// starting at the specified <see cref="Array"/> index.
/// </summary>
/// <param name="array">
/// The one-dimensional <see cref="Array"/> that is the destination of the elements copied
/// from <see cref="DequeqeOnlyQueue{T}" />. The <see cref="Array" /> must have zero-based indexing.
/// </param>
/// <param name="arrayIndex">
/// The zero-based index in array at which copying begins.
/// </param>
/// <exception cref="ArgumentNullException">
/// <para>Thrown if <paramref name="array" /> is <c>null</c>.</para>
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <para>Thrown if <paramref name="arrayIndex" /> is less than <c>0</c>.</para>
/// </exception>
/// <exception cref="ArgumentException">
/// <para>
/// Thrown if the number of elements in the source <see cref="DequeqeOnlyQueue{T}" />
/// is greater than the available space from index to the end of the destination array.
/// </para>
/// </exception>
public void CopyTo(T[] array, int arrayIndex) => this.source.CopyTo(array, arrayIndex);
/// <summary>
/// Copies the elements of the <see cref="ICollection" /> to an <see cref="Array" />,
/// starting at a particular <see cref="Array"/> index.
/// </summary>
/// <param name="array">
/// The one-dimensional <see cref="Array"/> that is the destination of the elements copied
/// from <see cref="ICollection" />. The <see cref="Array" /> must have zero-based indexing.
/// </param>
/// <param name="index">
/// The zero-based index in array at which copying begins.
/// </param>
/// <exception cref="ArgumentNullException">
/// <para>Thrown if <paramref name="array" /> is <c>null</c>.</para>
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <para>Thrown if <paramref name="index" /> is less than <c>0</c>.</para>
/// </exception>
/// <exception cref="ArgumentException">
/// <para>Thrown if:</para>
/// <para>
/// - <paramref name="array" /> is multidimensional.
/// </para>
/// <para>
/// - the number of elements in the source <see cref="ICollection" />
/// is greater than the available space from index to the end of the destination array.
/// </para>
/// <para>
/// - The type of the source <see cref="ICollection" /> cannot
/// be cast automatically to the type of the destination array.
/// </para>
/// </exception>
/// <remarks>
/// <para>Implements <see cref="ICollection.CopyTo(Array, int)" /> explicitly.</para>
/// </remarks>
void ICollection.CopyTo(Array array, int index) => ((ICollection)this.source).CopyTo(array, index);
/// <summary>
/// Gets an enumerator that iterates through the <see cref="DequeqeOnlyQueue{T}" />.
/// </summary>
/// <returns>
/// Returns an enumerator that iterates through the <see cref="DequeqeOnlyQueue{T}" />.
/// </returns>
/// <remarks>
/// <para>Implements <see cref="IEnumerable{T}.GetEnumerator()" /> implicitly.</para>
/// </remarks>
public IEnumerator<T> GetEnumerator() => this.source.GetEnumerator();
/// <summary>
/// Gets an enumerator that iterates through the <see cref="DequeqeOnlyQueue{T}" />.
/// </summary>
/// <returns>
/// Returns an enumerator that iterates through the <see cref="DequeqeOnlyQueue{T}" />.
/// </returns>
/// <remarks>
/// <para>Implements <see cref="IEnumerable.GetEnumerator()" /> explicitly.</para>
/// </remarks>
IEnumerator IEnumerable.GetEnumerator() => this.GetEnumerator();
}
}
|
using System.Collections.Generic;
using ReadyGamerOne.Common;
namespace DialogSystem.ScriptObject
{
[ScriptableSingletonInfo("DialogCharacters")]
public class DialogCharacterAsset:ScriptableSingleton<DialogCharacterAsset>
{
public List<string> characterNames=new List<string>();
}
} |
using System;
using Newtonsoft.Json;
namespace Core.Internal.Newtsoft.Json.Converters
{
public class ArrayOrSinglePropertyConverter<TDto> : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return false;
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.StartArray)
{
return serializer.Deserialize(reader, objectType);
}
return new TDto[]
{
serializer.Deserialize<TDto>(reader)
};
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
}
|
using UnityEngine;
using System.Collections;
public class Water : Photon.MonoBehaviour {
[SerializeField]
float movementSpeed = 0;
public bool canMove = false;
Vector3 realPosition;
// Use this for initialization
void Awake()
{
realPosition = transform.position;
}
// Update is called once per frame
void Update ()
{
if(PhotonNetwork.isMasterClient)
{
if (canMove) transform.position += Vector3.up * movementSpeed * Time.deltaTime;
}
else
transform.position = Vector3.Lerp(transform.position, realPosition, 0.1f);
}
public void OnPhotonSerializeView (PhotonStream stream, PhotonMessageInfo info)
{
if (stream.isWriting)
{
stream.SendNext(transform.position);
}
else
{
realPosition = (Vector3)stream.ReceiveNext();
}
}
}
|
// ===== Enhanced Editor - https://github.com/LucasJoestar/EnhancedEditor ===== //
//
// Notes:
//
// ============================================================================ //
using System;
namespace EnhancedEditor {
/// <summary>
/// Multiple <see cref="Enum"/>-related extension methods.
/// </summary>
public static class EnumExtensions {
#region Flags
/// <summary>
/// Adds a flag to this enum.
/// </summary>
/// <typeparam name="T">This enum type.</typeparam>
/// <param name="_value">This enum value.</param>
/// <param name="_flag">The flag value to add.</param>
/// <returns>This enum new value.</returns>
public static T AddFlag<T>(this Enum _value, T _flag) where T : Enum {
return (T)(object)(_value.ToInt() | _flag.ToInt());
}
/// <summary>
/// Removes a flag to this enum.
/// </summary>
/// <typeparam name="T">This enum type.</typeparam>
/// <param name="_value">This enum value.</param>
/// <param name="_flag">The flag value to remove.</param>
/// <returns>This enum new value.</returns>
public static T RemoveFlag<T>(this Enum _value, T _flag) where T : Enum {
return (T)(object)(_value.ToInt() & ~_flag.ToInt());
}
#endregion
#region Conversion
/// <summary>
/// Get the integer value of a specific enum.
/// </summary>
/// <param name="_value">Enum value to convert.</param>
/// <returns>Int value of this enum.</returns>
public static int ToInt(this Enum _value) {
return Convert.ToInt32(_value);
}
#endregion
#region Name
/// <inheritdoc cref="EnumUtility.GetName(Enum)"/>
public static string GetName(this Enum _value) {
return EnumUtility.GetName(_value);
}
#endregion
}
}
|
using Opbot.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace Opbot.Tests
{
public class CmdTests
{
[Fact]
[Trait("Category", "Unit")]
public void Cmd_WhenRun_ShouldEcho()
{
var result = Cmd.Run(@"c:\windows\system32\cmdkey.exe");
Assert.Equal(0, result.ExitCode);
Assert.Equal("test", string.Join("",result.Output));
}
}
}
|
using System.Collections.Generic;
namespace Binocle.Processors
{
public class PassiveProcessor : EntityProcessor
{
public override void OnChange(Entity entity)
{
// We do not manage any notification of entities changing state and avoid polluting our list of entities as we want to keep it empty
}
public override void Process(List<Entity> entities)
{
// We replace the basic entity system with our own that doesn't take into account entities
Begin();
End();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Json;
using System.Threading.Tasks;
namespace BlazorApp.Services
{
public class BuildingAppService : IBuldingAppService
{
private readonly HttpClient httpClient;
public BuildingAppService(HttpClient httpClient)
{
this.httpClient = httpClient;
}
public string Message { get; set; }
public async Task<string> AddBina(Bina bina)
{
var result = await httpClient.PostAsJsonAsync<Bina>("api/bina/add", bina);
Message = await result.Content.ReadFromJsonAsync<string>();
return Message;
}
public async Task<string> AddDepo(Depo depo)
{
var result = await httpClient.PostAsJsonAsync<Depo>("api/depo/add", depo);
Message = await result.Content.ReadFromJsonAsync<string>();
return Message;
}
public async Task<string> AddOda(Oda oda)
{
var result = await httpClient.PostAsJsonAsync<Oda>("api/oda/add", oda);
Message = await result.Content.ReadFromJsonAsync<string>();
return Message;
}
public async Task<List<Bina>> BinalariGetir()
{
return await httpClient.GetFromJsonAsync<List<Bina>>("api/bina/getall");
}
public async Task<List<Depo>> DepolarıGetir()
{
return await httpClient.GetFromJsonAsync<List<Depo>>("api/depo/getall");
}
public async Task<List<Oda>> OdalariGetir()
{
return await httpClient.GetFromJsonAsync<List<Oda>>("api/oda/getall");
}
public async Task<Bina> BinayiGetir(int id)
{
return await httpClient.GetFromJsonAsync<Bina>($"api/bina/getbyid?id={id}");
}
public async Task<Depo> DepoyuGetir(int id)
{
return await httpClient.GetFromJsonAsync<Depo>($"api/depo/getbyid?id={id}");
}
public async Task<Oda> OdayiGetir(int id)
{
return await httpClient.GetFromJsonAsync<Oda>($"api/oda/getbyid?id={id}");
}
public async Task<string> DeleteBina(int id)
{
var result = await httpClient.PostAsJsonAsync<string>($"api/bina/delete?id={id}",null);
Message = await result.Content.ReadFromJsonAsync<string>();
return Message;
}
public async Task<string> DeleteOda(int id)
{
var result = await httpClient.PostAsJsonAsync<string>($"api/oda/delete?id={id}", null);
Message = await result.Content.ReadFromJsonAsync<string>();
return Message;
}
public async Task<string> DeleteDepo(int id)
{
var result = await httpClient.PostAsJsonAsync<string>($"api/depo/delete?id={id}", null);
Message = await result.Content.ReadFromJsonAsync<string>();
return Message;
}
}
}
|
namespace JqD.Common.Command.SystemManage
{
public class UpdateUserCommand
{
public int Id { get; set; }
public string Password { get; set; }
}
}
|
using LuaInterface;
using RO;
using SLua;
using System;
public class Lua_RO_CoreEvent : LuaObject
{
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_typeID(IntPtr l)
{
int result;
try
{
CoreEvent coreEvent = (CoreEvent)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, coreEvent.typeID);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
public static void reg(IntPtr l)
{
LuaObject.getTypeTable(l, "RO.CoreEvent");
LuaObject.addMember(l, "typeID", new LuaCSFunction(Lua_RO_CoreEvent.get_typeID), null, true);
LuaObject.createTypeMetatable(l, null, typeof(CoreEvent));
}
}
|
using System.Collections.Generic; using System;
using System.Text;
using BrainDuelsLib.threads;
namespace BrainDuelsLib.view
{
public interface GamesChallengesLobbyControl
{
void SetSelectUserCallback(Action<int> action);
void SetOnEnterGameAsPlayerCallback(Action<Game> action);
void SetOnEnterGameAsObserverCallback(Action<Game> action);
void SetOnLeaveGameCallback(Action<Game> action);
void Update(List<Game> games);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using log4net;
using Plus.Communication.Packets.Outgoing.Inventory.Achievements;
using Plus.Communication.Packets.Outgoing.Inventory.Purse;
using Plus.Database.Interfaces;
using Plus.HabboHotel.GameClients;
using Plus.HabboHotel.Users.Messenger;
namespace Plus.HabboHotel.Achievements
{
public class AchievementManager
{
private static readonly ILog Log = LogManager.GetLogger(typeof(AchievementManager));
public Dictionary<string, Achievement> Achievements;
public AchievementManager()
{
Achievements = new Dictionary<string, Achievement>();
}
public void Init()
{
AchievementLevelFactory.GetAchievementLevels(out Achievements);
}
public bool ProgressAchievement(GameClient session, string group, int progress, bool fromBeginning = false)
{
if (!Achievements.ContainsKey(group) || session == null)
return false;
Achievement data = Achievements[group];
if (data == null)
{
return false;
}
UserAchievement userData = session.GetHabbo().GetAchievementData(group);
if (userData == null)
{
userData = new UserAchievement(group, 0, 0);
session.GetHabbo().Achievements.TryAdd(group, userData);
}
int totalLevels = data.Levels.Count;
if (userData.Level == totalLevels)
return false; // done, no more.
int targetLevel = userData.Level + 1;
if (targetLevel > totalLevels)
targetLevel = totalLevels;
AchievementLevel level = data.Levels[targetLevel];
int newProgress;
if (fromBeginning)
newProgress = progress;
else
newProgress = userData.Progress + progress;
int newLevel = userData.Level;
int newTarget = newLevel + 1;
if (newTarget > totalLevels)
newTarget = totalLevels;
if (newProgress >= level.Requirement)
{
newLevel++;
newTarget++;
newProgress = 0;
if (targetLevel == 1)
session.GetHabbo().GetBadgeComponent().GiveBadge(group + targetLevel, true, session);
else
{
session.GetHabbo().GetBadgeComponent().RemoveBadge(Convert.ToString(group + (targetLevel - 1)));
session.GetHabbo().GetBadgeComponent().GiveBadge(group + targetLevel, true, session);
}
if (newTarget > totalLevels)
{
newTarget = totalLevels;
}
session.SendPacket(new AchievementUnlockedComposer(data, targetLevel, level.RewardPoints, level.RewardPixels));
session.GetHabbo().GetMessenger().BroadcastAchievement(session.GetHabbo().Id, MessengerEventTypes.AchievementUnlocked, group + targetLevel);
using (IQueryAdapter dbClient = PlusEnvironment.GetDatabaseManager().GetQueryReactor())
{
dbClient.SetQuery("REPLACE INTO `user_achievements` VALUES (@userId, @group, @newLevel, @newProgress)");
dbClient.AddParameter("userId", session.GetHabbo().Id);
dbClient.AddParameter("group", group);
dbClient.AddParameter("newLevel", newLevel);
dbClient.AddParameter("newProgress", newProgress);
dbClient.RunQuery();
}
userData.Level = newLevel;
userData.Progress = newProgress;
session.GetHabbo().Duckets += level.RewardPixels;
session.GetHabbo().GetStats().AchievementPoints += level.RewardPoints;
session.SendPacket(new HabboActivityPointNotificationComposer(session.GetHabbo().Duckets, level.RewardPixels));
session.SendPacket(new AchievementScoreComposer(session.GetHabbo().GetStats().AchievementPoints));
AchievementLevel newLevelData = data.Levels[newTarget];
session.SendPacket(new AchievementProgressedComposer(data, newTarget, newLevelData, totalLevels, session.GetHabbo().GetAchievementData(group)));
return true;
}
userData.Level = newLevel;
userData.Progress = newProgress;
using (IQueryAdapter dbClient = PlusEnvironment.GetDatabaseManager().GetQueryReactor())
{
dbClient.SetQuery("REPLACE INTO `user_achievements` VALUES (@userId, @group, @newLevel, @newProgress)");
dbClient.AddParameter("userId", session.GetHabbo().Id);
dbClient.AddParameter("group", group);
dbClient.AddParameter("newLevel", newLevel);
dbClient.AddParameter("newProgress", newProgress);
dbClient.RunQuery();
}
session.SendPacket(new AchievementProgressedComposer(data, targetLevel, level, totalLevels, session.GetHabbo().GetAchievementData(group)));
return false;
}
public ICollection<Achievement> GetGameAchievements(int gameId)
{
List<Achievement> achievements = new();
foreach (Achievement achievement in Achievements.Values.ToList())
{
if (achievement.Category == "games" && achievement.GameId == gameId)
achievements.Add(achievement);
}
return achievements;
}
}
} |
/********************************************************************
* FulcrumWeb RAD Framework - Fulcrum of your business *
* Copyright (c) 2002-2010 FulcrumWeb, ALL RIGHTS RESERVED *
* *
* THE SOURCE CODE CONTAINED WITHIN THIS FILE AND ALL RELATED *
* FILES OR ANY PORTION OF ITS CONTENTS SHALL AT NO TIME BE *
* COPIED, TRANSFERRED, SOLD, DISTRIBUTED, OR OTHERWISE MADE *
* AVAILABLE TO OTHER INDIVIDUALS WITHOUT EXPRESS WRITTEN CONSENT *
* AND PERMISSION FROM FULCRUMWEB. CONSULT THE END USER LICENSE *
* AGREEMENT FOR INFORMATION ON ADDITIONAL RESTRICTIONS. *
********************************************************************/
using System;
using System.Collections;
using System.Xml;
using Framework.Utils;
namespace Framework.Metadata
{
/// <summary>
/// Defines entity group.
/// </summary>
public class CxEntityGroup : CxMetadataObject
{
//-------------------------------------------------------------------------
protected CxEntityGroupCondition m_Condition = null;
//-------------------------------------------------------------------------
/// <summary>
/// Constructor.
/// </summary>
/// <param name="holder">parent metadata holder object</param>
/// <param name="element">XML element that holds metadata</param>
public CxEntityGroup(CxMetadataHolder holder, XmlElement element) : base(holder, element)
{
XmlElement conditionElement = (XmlElement) element.SelectSingleNode("condition");
if (conditionElement != null)
{
m_Condition = new CxEntityGroupCondition(Holder, conditionElement);
}
}
//-------------------------------------------------------------------------
/// <summary>
/// True if entity group is applicable to the given metadata object.
/// </summary>
/// <param name="metadataObject">metadata object to check</param>
public bool GetIsMatch(CxMetadataObject metadataObject)
{
if (m_Condition != null)
{
foreach (string propertyName in m_Condition.PropertyNames)
{
if (m_Condition[propertyName].ToLower() != metadataObject[propertyName].ToLower())
{
return false;
}
}
}
return true;
}
//-------------------------------------------------------------------------
}
} |
/**************************************************************************
*
* Filename: ShellShortcut.cs
* Author: Mattias Sjögren (mattias@mvps.org)
* http://www.msjogren.net/dotnet/
*
* Description: Defines a .NET friendly class, ShellShortcut, for reading
* and writing shortcuts.
* Define the conditional compilation symbol UNICODE to use
* IShellLinkW internally.
*
* Public types: class ShellShortcut
*
*
* Dependencies: ShellLinkNative.cs
*
*
* Copyright ©2001-2002, Mattias Sjögren
*
**************************************************************************/
using System;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
namespace Illallangi.ShellLink
{
using System.Diagnostics.CodeAnalysis;
/// <summary>.NET friendly wrapper for the ShellLink class</summary>
public class ShellShortcut : IDisposable
{
#region Fields
private const int Infotipsize = 1024;
private const int MaxPath = 260;
private const int SwShownormal = 1;
private const int SwShowminimized = 2;
private const int SwShowmaximized = 3;
private const int SwShowminnoactive = 7;
private IShellLinkA currentShellLink;
private readonly string currentShellPath;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="ShellShortcut"/> class.
/// </summary>
/// <param name="linkPath">
/// Path to new or existing shortcut file.
/// </param>
public ShellShortcut(string linkPath)
{
this.currentShellPath = linkPath;
this.currentShellLink = (IShellLinkA)new ShellLink();
if (!File.Exists(linkPath))
{
return;
}
((IPersistFile)this.currentShellLink).Load(linkPath, 0);
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the argument list of the shortcut.
/// </summary>
/// <value>
/// The argument list of the shortcut.
/// </value>
public string Arguments
{
get
{
var sb = new StringBuilder(Infotipsize);
this.currentShellLink.GetArguments(sb, sb.Capacity);
return sb.ToString();
}
set
{
this.currentShellLink.SetArguments(value);
}
}
/// <value>
/// Gets or sets a description of the shortcut.
/// </value>
public string Description
{
get
{
var sb = new StringBuilder(Infotipsize);
this.currentShellLink.GetDescription(sb, sb.Capacity);
return sb.ToString();
}
set
{
this.currentShellLink.SetDescription(value);
}
}
/// <summary>
/// Gets or sets the working directory (aka start in directory) of the shortcut.
/// </summary>
/// <value>
/// The working directory (aka start in directory) of the shortcut.
/// </value>
public string WorkingDirectory
{
get
{
var sb = new StringBuilder(MaxPath);
this.currentShellLink.GetWorkingDirectory(sb, sb.Capacity);
return sb.ToString();
}
set
{
this.currentShellLink.SetWorkingDirectory(value);
}
}
/// <summary>
/// Gets or sets the target path of the shortcut.
/// </summary>
/// <value>
/// The target path of the shortcut.
/// </value>
/// <comment>
/// If Path returns an empty string, the shortcut is associated with
/// a PIDL instead, which can be retrieved with IShellLink.GetIDList().
/// This is beyond the scope of this wrapper class.
/// </comment>
public string Path
{
get
{
WIN32_FIND_DATAA wfd;
var sb = new StringBuilder(MaxPath);
this.currentShellLink.GetPath(sb, sb.Capacity, out wfd, SLGP_FLAGS.SLGP_UNCPRIORITY);
return sb.ToString();
}
set
{
this.currentShellLink.SetPath(value);
}
}
/// <summary>
/// Gets or sets the path of the <see cref="Icon"/> assigned to the shortcut. <seealso cref="IconIndex"/>
/// </summary>
/// <value>
/// The path of the <see cref="Icon"/> assigned to the shortcut.
/// </value>
public string IconPath
{
get
{
var sb = new StringBuilder(MaxPath);
int iconIdx;
this.currentShellLink.GetIconLocation(sb, sb.Capacity, out iconIdx);
return sb.ToString();
}
set
{
this.currentShellLink.SetIconLocation(value, this.IconIndex);
}
}
/// <value>
/// The index of the <see cref="Icon"/> assigned to the shortcut.
/// </value>
/// <summary>
/// Gets or sets the index of the <see cref="Icon"/> assigned to the shortcut.
/// Set to zero when the <see cref="IconPath"/> property specifies a .ICO file.
/// <seealso cref="IconPath"/>
/// </summary>
public int IconIndex
{
get
{
var sb = new StringBuilder(MaxPath);
int iconIdx;
this.currentShellLink.GetIconLocation(sb, sb.Capacity, out iconIdx);
return iconIdx;
}
set
{
this.currentShellLink.SetIconLocation(this.IconPath, value);
}
}
/// <summary>
/// Gets the Icon of the shortcut as it will appear in Explorer.
/// Use the <see cref="IconPath"/> and <see cref="IconIndex"/>
/// properties to change it.
/// </summary>
/// <value>
/// The Icon of the shortcut as it will appear in Explorer.
/// </value>
public Icon Icon
{
get
{
var sb = new StringBuilder(MaxPath);
int iconIdx;
this.currentShellLink.GetIconLocation(sb, sb.Capacity, out iconIdx);
var inst = Marshal.GetHINSTANCE(this.GetType().Module);
var icon = Native.ExtractIcon(inst, sb.ToString(), iconIdx);
if (icon == IntPtr.Zero)
{
return null;
}
// Return a cloned Icon, because we have to free the original ourselves.
var ico = Icon.FromHandle(icon);
var clone = (Icon)ico.Clone();
ico.Dispose();
Native.DestroyIcon(icon);
return clone;
}
}
/// <summary>
/// Gets or sets the System.Diagnostics.ProcessWindowStyle value
/// that decides the initial show state of the shortcut target. Note that
/// ProcessWindowStyle.Hidden is not a valid property value.
/// </summary>
/// <value>
/// The System.Diagnostics.ProcessWindowStyle value
/// that decides the initial show state of the shortcut target.
/// </value>
public ProcessWindowStyle WindowStyle
{
get
{
int ws;
this.currentShellLink.GetShowCmd(out ws);
switch (ws)
{
case SwShowminimized:
case SwShowminnoactive:
return ProcessWindowStyle.Minimized;
case SwShowmaximized:
return ProcessWindowStyle.Maximized;
default:
return ProcessWindowStyle.Normal;
}
}
set
{
int ws;
switch (value)
{
case ProcessWindowStyle.Normal:
ws = SwShownormal;
break;
case ProcessWindowStyle.Minimized:
ws = SwShowminnoactive;
break;
case ProcessWindowStyle.Maximized:
ws = SwShowmaximized;
break;
default: // ProcessWindowStyle.Hidden
throw new ArgumentException("Unsupported ProcessWindowStyle value.");
}
this.currentShellLink.SetShowCmd(ws);
}
}
/// <summary>
/// Gets or sets the hotkey for the shortcut.
/// </summary>
/// <value>
/// The hotkey for the shortcut.
/// </value>
public Keys Hotkey
{
get
{
short hotkey;
this.currentShellLink.GetHotkey(out hotkey);
// Convert from IShellLink 16-bit format to Keys enumeration 32-bit value
// IShellLink: 0xMMVK
// Keys: 0x00MM00VK
// MM = Modifier (Alt, Control, Shift)
// VK = Virtual key code
return (Keys)(((hotkey & 0xFF00) << 8) | (hotkey & 0xFF));
}
set
{
if ((value & Keys.Modifiers) == 0)
{
throw new ArgumentException("Hotkey must include a modifier key.");
}
// Convert from Keys enumeration 32-bit value to IShellLink 16-bit format
// IShellLink: 0xMMVK
// Keys: 0x00MM00VK
// MM = Modifier (Alt, Control, Shift)
// VK = Virtual key code
this.currentShellLink.SetHotkey(unchecked((short)(((int)(value & Keys.Modifiers) >> 8) | (int)(value & Keys.KeyCode))));
}
}
#endregion
#region Methods
/// <summary>
/// Saves the shortcut to disk.
/// </summary>
public void Save()
{
var pf = (IPersistFile)this.currentShellLink;
pf.Save(this.currentShellPath, true);
}
/// <summary>
/// Implementation of the IDispose interface.
/// </summary>
public void Dispose()
{
if (this.currentShellLink == null)
{
return;
}
Marshal.ReleaseComObject(this.currentShellLink);
this.currentShellLink = null;
}
#endregion
#region Classes
/// <summary>
/// Native win32 operations.
/// </summary>
private static class Native
{
[SuppressMessage("StyleCop.CSharp.NamingRules", "SA1305:FieldNamesMustNotUseHungarianNotation", Justification = "Win32 Native operation.")]
[DllImport("shell32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr ExtractIcon(IntPtr hInst, string lpszExeFileName, int nIconIndex);
[SuppressMessage("StyleCop.CSharp.NamingRules", "SA1305:FieldNamesMustNotUseHungarianNotation", Justification = "Win32 Native operation.")]
[DllImport("user32.dll")]
public static extern bool DestroyIcon(IntPtr hIcon);
}
#endregion
}
}
|
using System.Data.Entity.ModelConfiguration;
using SSW.DataOnion.Sample.Entities;
namespace SSW.DataOnion.Sample.Data.Configurations
{
public class StudentConfigurations : EntityTypeConfiguration<Student>
{
public StudentConfigurations()
{
this.HasKey(m => m.Id);
this.Ignore(m => m.FullName);
}
}
}
|
using CandidateTesting.RicardoCastroMartin.Infra.Interfaces;
using System.Text;
namespace CandidateTesting.RicardoCastroMartin.Test
{
public class MockLogClient : ILogClient
{
public string GetString()
{
StringBuilder sb = new StringBuilder();
sb.Append("312|200|HIT|\"GET /robots.txt HTTP/1.1\"|100.2\n");
sb.Append("101|200|MISS|\"POST /myImages HTTP/1.1\"|319.4\n");
sb.Append("199|404|MISS|\"GET /not-found HTTP/1.1\"|142.9\n");
sb.Append("312|200|INVALIDATE|\"GET /robots.txt HTTP/1.1\"|245.1\n");
return sb.ToString();
}
}
}
|
using UnityEngine;
using System.Collections.Generic;
public class Targetting : MonoBehaviour
{
public static Targetting instance;
public List<Transform> allTargets;
public Transform currentTarget;
//[HideInInspector]
public bool hasTurned = false;
public float munchDuration = 1.0f;
public float range = 3.0f;
public float shottyRange = 20.0f;
[HideInInspector]
public float shottyDist = 0.0f;
[HideInInspector]
public bool hasTurnedBack = false;
private PlayerPhysics playerPhysics;
private float munchDur = 0.0f;
private float curDist;
void Awake()
{
instance = this;
playerPhysics = GetComponent<PlayerPhysics>();
}
// Use this for initialization
void Start()
{
munchDur = munchDuration;
allTargets = new List<Transform>();
currentTarget = null;
AddAllZombies();
}
public void AddAllHumans()
{
GameObject[] go = GameObject.FindGameObjectsWithTag("Human");
foreach (GameObject target in go)
{
AddTarget(target.transform);
}
}
public void AddAllZombies()
{
GameObject[] go = GameObject.FindGameObjectsWithTag("Zombie");
foreach (GameObject target in go)
{
AddTarget(target.transform);
}
}
void AddTarget(Transform target)
{
allTargets.Add(target);
}
// Update is called once per frame
void Update ()
{
MunchControl();
}
private void MunchControl()
{
curDist = range;
foreach (Transform target in allTargets)
{
if (allTargets.Count > 0)
{
float dist = Vector3.Distance(target.position, transform.position);
//calculate range for shotgun strength
if (dist < shottyRange)
{
shottyDist = (shottyDist / dist) + shottyRange;
}
//calculate distance to other targets
if (dist < curDist)
{
curDist = dist;
if (Input.GetMouseButton(1) && playerPhysics.zombieStates != PlayerPhysics.ZombieState.fullHuman)
{
munchDur -= Time.deltaTime;
}
}
}
}
if (munchDur <= 0)
{
playerPhysics.zombieStates--;
PlayerPhysics.killCount++;
munchDur = munchDuration;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AutoMapper;
using SaleShop.Model.Models;
using SaleShop.Service;
using SaleShop.Web.Models;
namespace SaleShop.Web.Controllers
{
public class PageController : Controller
{
private IPageService _pageService;
public PageController(IPageService pageService)
{
_pageService = pageService;
}
// GET: Page
public ActionResult Index(string alias)
{
var page = _pageService.GetPageByAlias(alias);
var model = Mapper.Map<Page, PageViewModel>(page);
return View(model);
}
}
} |
using System;
using ORMHandsOn;
namespace Test.ORM.Infrastructure
{
/// <summary>
/// Feeds the database with some initial data
/// </summary>
public class TestDataSeeder
{
public void SeedDatabaseWithStudentEnrolledInCourses(int id, string studentName, int numberOfCourses)
{
//very quick and dirty way to seed test data, this is NOT the ORM way :)
using (var context = new EntityContext())
{
context.Database.ExecuteSqlCommand(String.Format("INSERT INTO Students (Id, Name, Age) VALUES ({0}, '{1}', 23)", id, studentName));
const string insertCourseStatement = "INSERT INTO Courses (Name, Student_Id) VALUES ({0}, {1})";
for (int courseNumber = 1; courseNumber <= numberOfCourses; courseNumber++)
{
context.Database.ExecuteSqlCommand(insertCourseStatement, String.Format("Course number {0}", courseNumber), id);
}
}
}
}
}
|
// Copyright 2021 Google 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.Concurrent;
using System.Linq;
using System.Reflection;
namespace NtApiDotNet.Utilities.Reflection
{
/// <summary>
/// Utilities for reflection.
/// </summary>
public static class ReflectionUtils
{
private readonly static ConcurrentDictionary<Tuple<Type, string>, string> _sdk_name_cache
= new ConcurrentDictionary<Tuple<Type, string>, string>();
private static string GetSDKNameInternal(Type type, string member_name)
{
if (string.IsNullOrEmpty(member_name))
return type.GetCustomAttribute<SDKNameAttribute>()?.Name;
MemberInfo member = type.GetMember(member_name).FirstOrDefault();
if (member == null)
return null;
return member.GetCustomAttribute<SDKNameAttribute>()?.Name;
}
private static string GetSDKNameCached(Type type, string member_name)
{
var key = Tuple.Create(type, member_name);
return _sdk_name_cache.GetOrAdd(key, k => GetSDKNameInternal(k.Item1, k.Item2));
}
private static string GetSDKNameCached(Enum value)
{
return GetSDKNameCached(value.GetType(), value.ToString());
}
/// <summary>
/// Get the SDK name for a type, if available.
/// </summary>
/// <param name="type">The type to get the name for.</param>
/// <returns>The SDK name. Returns the name of the type if not available.</returns>
public static string GetSDKName(Type type)
{
if (type is null)
{
throw new ArgumentNullException(nameof(type));
}
return GetSDKNameCached(type, string.Empty) ?? type.Name;
}
/// <summary>
/// Get the SDK name for an enum, if available.
/// </summary>
/// <param name="value">The enum to get the name for.</param>
/// <returns>The SDK name. If the enum is a flags enum then will return the names joined with commas.</returns>
public static string GetSDKName(Enum value)
{
if (value is null)
{
throw new ArgumentNullException(nameof(value));
}
var sdk_name = GetSDKNameCached(value);
if (sdk_name != null)
return sdk_name;
Type type = value.GetType();
var parts = value.ToString().Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(s => s.Trim());
return string.Join(", ", parts.Select(s => GetSDKNameCached(type, s) ?? s));
}
/// <summary>
/// Get the SDK name an object.
/// </summary>
/// <param name="value">The object to get the name from. If this isn't an Enum or Type then the Type of the object is used.</param>
/// <returns>The SDK name.</returns>
public static string GetSDKName(object value)
{
if (value is null)
{
throw new ArgumentNullException(nameof(value));
}
if (value is Type type)
{
return GetSDKName(type);
}
else if (value is Enum en)
{
return GetSDKName(en);
}
return GetSDKName(value.GetType());
}
}
}
|
using Newtonsoft.Json;
/// <summary>
/// Scribble.rs ♯ data namespace
/// </summary>
namespace ScribblersSharp.Data
{
/// <summary>
/// A class that describes a sendable "clear-drawing-board" game message
/// </summary>
[JsonObject(MemberSerialization.OptIn)]
internal class ClearDrawingBoardSendGameMessageData : BaseGameMessageData, ISendGameMessageData
{
/// <summary>
/// Constructs a sendable "clear-drawing-board" game message
/// </summary>
public ClearDrawingBoardSendGameMessageData() : base(Naming.GetSendGameMessageDataNameInKebabCase<ClearDrawingBoardSendGameMessageData>())
{
// ...
}
}
}
|
using Common;
using Common.Graphics;
namespace OcTreeRevisited
{
class RenderEngine : AbstractRenderEngine
{
public RenderEngine(int width, int height, AbstractPlayer player)
: base(width, height, player, 900)
{
}
protected override void PreRender()
{
}
protected override void BindBuffers(SimpleModel model)
{
}
protected override void Draw(SimpleModel model)
{
}
protected override void PostRender()
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Problem02StudentsAndWorkers
{
class Worker : Human
{
public double WeekSalary { get; set; }
public int WorkHoursPerDay { get; set; }
public Worker() { }
public Worker(double weekSalary, int workHoursPerDay)
{
this.WeekSalary = weekSalary;
this.WorkHoursPerDay = workHoursPerDay;
}
public Worker(string firstName, string lastName, double weekSalary, int workHoursPerDay)
: base(firstName, lastName)
{
this.WeekSalary = weekSalary;
this.WorkHoursPerDay = workHoursPerDay;
}
public double MoneyPerHour()
{
return WeekSalary / 5 / WorkHoursPerDay;
}
public override string ToString()
{
return String.Format("Name: {0} {1}, Week Salary = {2}, Work hours per day: {3}", base.FirstName, base.LastName, WeekSalary, WorkHoursPerDay);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GoalManSettings
{
public class RequestResult
{
public string source { get; set; }
public string resolvedQuery { get; set; }
public string action { get; set; }
public string actionIncomplete { get; set; }
public RequestParameters parameters { get; set; }
public string[] contexts { get; set; }
public RequestMetaData metadata { get; set; }
public Fulfillment fulfillment { get; set; }
public double score { get; set; }
}
}
|
using System;
namespace Domain.Entities {
public class DetailOrder {
public Guid IdDetailOrder { get; set; }
public Guid IdOrder { get; set; }
public Guid IdProducts { get; set; }
public int TotalProducts { get; set; }
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.