text stringlengths 13 6.01M |
|---|
using QLSV.BD_layer;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace QLSV.BS_layer
{
class BLThongKe
{
DataProvider db = null;
public BLThongKe()
{
db = new DataProvider();
}
public DataTable GetTC(string MaSV)
{
string sqlString =
string.Format("select a.maSV,a.stcHoc,a.hocKi,b.stcDau "+
"from(select maSV, Sum(soTinChi) as stcHoc, hocKi from KetQua, Mon where ketQua.maMon = Mon.maMon and maSV = N'{0}' group by maSV, hocKi) a,"
+" (select maSV, Sum(soTinChi) as stcDau, hocKi from KetQua, Mon where ketQua.maMon = Mon.maMon and KetQua.ketQua = 1 and maSV = N'{0}' group by maSV, hocKi) b"
+" where a.hocKi = b.hocKi", MaSV);
return db.MyExecuteQuery(sqlString);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyCentrip : EnemyMovement {
// Use this for initialization
void Start () {
bulletType = "EnemyBullet4";
}
// Update is called once per frame
//void Update () {
//if ((Input.GetMouseButtonDown (1))) {
//GameObject bulletProj = (GameObject)Instantiate (Resources.Load ("EnemyBullet3"));
//bulletProj.transform.position = rigBod.position;
//}
//}
}
|
namespace CloneDeploy_Entities.DTOs.ClientImaging
{
public class ModelTaskDTO
{
public string imageProfileId { get; set; }
public string imageName { get; set; }
public string imageProfileName { get; set; }
}
} |
using System.Collections.Generic;
using System.Threading.Tasks;
using Contact.API.Dtos;
namespace Contact.API.Repository
{
public interface IContactRepository
{
/// <summary>
/// 更新好友基本信息
/// </summary>
/// <param name="info"></param>
/// <returns></returns>
Task UpdateContactInfoAsync(BaseUserInfo info);
Task AddContactFriendAsync(int userId, Data.Contact contact);
Task DeleteFriendAsync(int userId, int friendUserId);
Task<IEnumerable<Data.Contact>> GetAllFriendListAsync(int userId);
Task ContactTagsAsync(int userId, int friendUserId, string[] tags);
}
} |
using LuaInterface;
using SLua;
using System;
public class Lua_UnityEngine_ImagePosition : LuaObject
{
public static void reg(IntPtr l)
{
LuaObject.getEnumTable(l, "UnityEngine.ImagePosition");
LuaObject.addMember(l, 0, "ImageLeft");
LuaObject.addMember(l, 1, "ImageAbove");
LuaObject.addMember(l, 2, "ImageOnly");
LuaObject.addMember(l, 3, "TextOnly");
LuaDLL.lua_pop(l, 1);
}
}
|
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
namespace Sunny.HttpReqeustServer
{
public class MyHttpModule : IHttpModule
{
private bool? hiJacking;
protected bool HiJacking
{
get
{
if (!hiJacking.HasValue)
{
bool flag = false;
if (bool.TryParse(ConfigurationSettings.AppSettings["IsHiJacking"].ToString(), out flag))
{
hiJacking = flag;
}
else
{
hiJacking = false;
}
}
return hiJacking.Value;
}
}
public void Dispose()
{
}
public void Init(HttpApplication context)
{
CommonHelper.WriteLog(string.Format("*******{0}.Init*****************", this.GetType().Name), context.GetHashCode().ToString());
context.Disposed += new EventHandler(context_Disposed);
context.Error += new EventHandler(context_Error);
context.BeginRequest += new EventHandler(context_BeginRequest);
context.AuthenticateRequest += new EventHandler(context_AuthenticateRequest);
context.PostAuthenticateRequest += new EventHandler(context_PostAuthenticateRequest);
context.AuthorizeRequest += new EventHandler(context_AuthorizeRequest);
context.PostAuthorizeRequest += new EventHandler(context_PostAuthorizeRequest);
context.ResolveRequestCache += new EventHandler(context_ResolveRequestCache);
context.PostResolveRequestCache += new EventHandler(context_PostResolveRequestCache);
context.MapRequestHandler += new EventHandler(context_MapRequestHandler);
context.PostMapRequestHandler += new EventHandler(context_PostMapRequestHandler);
context.AcquireRequestState += new EventHandler(context_AcquireRequestState);
context.PostAcquireRequestState += new EventHandler(context_PostAcquireRequestState);
context.PreRequestHandlerExecute += new EventHandler(context_PreRequestHandlerExecute);
context.PostRequestHandlerExecute += new EventHandler(context_PostRequestHandlerExecute);
context.ReleaseRequestState += new EventHandler(context_ReleaseRequestState);
context.PostReleaseRequestState += new EventHandler(context_PostReleaseRequestState);
context.UpdateRequestCache += new EventHandler(context_UpdateRequestCache);
context.PostUpdateRequestCache += new EventHandler(context_PostUpdateRequestCache);
context.LogRequest += new EventHandler(LogRequest);
context.PostLogRequest += new EventHandler(context_PostLogRequest);
context.EndRequest += new EventHandler(context_EndRequest);
context.PreSendRequestContent += new EventHandler(context_PreSendRequestContent);
context.PreSendRequestHeaders += new EventHandler(context_PreSendRequestHeaders);
context.RequestCompleted += new EventHandler(context_RequestCompleted);
}
#region Event methods
void context_BeginRequest(object sender, EventArgs e)
{
HttpApplication app = sender as HttpApplication;
//CommonHelper.WriteLog(app.Context.Request.Path + Environment.NewLine);
CommonHelper.WriteLog(string.Format("{0}.BeginRequest", this.GetType().Name), app.GetHashCode().ToString());
//HttpContext.Current.Response.Write("BeginRequest<br />");
}
void context_AuthenticateRequest(object sender, EventArgs e)
{
HttpApplication app = sender as HttpApplication;
CommonHelper.WriteLog(string.Format("{0}.AuthenticateRequest", this.GetType().Name), app.GetHashCode().ToString());
//HttpContext.Current.Response.Write("AuthenticateRequest<br />");
}
void context_PostAuthenticateRequest(object sender, EventArgs e)
{
HttpApplication app = sender as HttpApplication;
CommonHelper.WriteLog(string.Format("{0}.PostAuthenticateRequest", this.GetType().Name), app.GetHashCode().ToString());
//HttpContext.Current.Response.Write("PostAuthenticateRequest<br />");
}
void context_AuthorizeRequest(object sender, EventArgs e)
{
HttpApplication app = sender as HttpApplication;
CommonHelper.WriteLog(string.Format("{0}.AuthorizeRequest", this.GetType().Name), app.GetHashCode().ToString());
//HttpContext.Current.Response.Write("AuthorizeRequest<br />");
}
void context_PostAuthorizeRequest(object sender, EventArgs e)
{
HttpApplication app = sender as HttpApplication;
CommonHelper.WriteLog(string.Format("{0}.PostAuthorizeRequest", this.GetType().Name), app.GetHashCode().ToString());
//HttpContext.Current.Response.Write("PostAuthorizeRequest<br />");
}
void context_ResolveRequestCache(object sender, EventArgs e)
{
HttpApplication app = sender as HttpApplication;
CommonHelper.WriteLog(string.Format("{0}.ResolveRequestCache", this.GetType().Name), app.GetHashCode().ToString());
// HttpContext.Current.Response.Write("ResolveRequestCache<br />");
}
void context_PostResolveRequestCache(object sender, EventArgs e)
{
HttpApplication app = sender as HttpApplication;
CommonHelper.WriteLog(string.Format("{0}.PostResolveRequestCache", this.GetType().Name), app.GetHashCode().ToString());
if (HiJacking)
{
IHttpHandler handler = new HiJackingHandler();
app.Context.RemapHandler(handler);
}
//HttpContext.Current.Response.Write("PostResolveRequestCache<br />");
}
void context_MapRequestHandler(object sender, EventArgs e)
{
HttpApplication app = sender as HttpApplication;
CommonHelper.WriteLog(string.Format("{0}.MapRequestHandler", this.GetType().Name), app.GetHashCode().ToString());
//HttpContext.Current.Response.Write("MapRequestHandler<br />");
}
void context_PostMapRequestHandler(object sender, EventArgs e)
{
HttpApplication app = sender as HttpApplication;
CommonHelper.WriteLog(string.Format("{0}.PostMapRequestHandler", this.GetType().Name), app.GetHashCode().ToString());
try
{
if (HiJacking)
{
IHttpHandler handler = new HttpRequestHandler();
app.Context.RemapHandler(handler);
}
}
catch (Exception ex)
{
string tt = "sdfsd";
}
//HttpContext.Current.Response.Write("PostMapRequestHandler<br />");
}
void context_AcquireRequestState(object sender, EventArgs e)
{
HttpApplication app = sender as HttpApplication;
CommonHelper.WriteLog(string.Format("{0}.AcquireRequestState", this.GetType().Name), app.GetHashCode().ToString());
//HttpContext.Current.Response.Write("AcquireRequestState<br />");
}
void context_PostAcquireRequestState(object sender, EventArgs e)
{
HttpApplication app = sender as HttpApplication;
CommonHelper.WriteLog(string.Format("{0}.PostAcquireRequestState", this.GetType().Name), app.GetHashCode().ToString());
//HttpContext.Current.Response.Write("PostAcquireRequestState<br />");
}
void context_PreRequestHandlerExecute(object sender, EventArgs e)
{
HttpApplication app = sender as HttpApplication;
CommonHelper.WriteLog(string.Format("{0}.PreRequestHandlerExecute", this.GetType().Name), app.GetHashCode().ToString());
//HttpContext.Current.Response.Write("PreRequestHandlerExecute<br />");
}
void context_PostRequestHandlerExecute(object sender, EventArgs e)
{
HttpApplication app = sender as HttpApplication;
CommonHelper.WriteLog(string.Format("{0}.PostRequestHandlerExecute", this.GetType().Name), app.GetHashCode().ToString());
//HttpContext.Current.Response.Write("PostRequestHandlerExecute<br />");
}
void context_ReleaseRequestState(object sender, EventArgs e)
{
HttpApplication app = sender as HttpApplication;
CommonHelper.WriteLog(string.Format("{0}.ReleaseRequestState", this.GetType().Name), app.GetHashCode().ToString());
//HttpContext.Current.Response.Write("ReleaseRequestState<br />");
}
void context_PostReleaseRequestState(object sender, EventArgs e)
{
HttpApplication app = sender as HttpApplication;
CommonHelper.WriteLog(string.Format("{0}.PostReleaseRequestState", this.GetType().Name), app.GetHashCode().ToString());
//HttpContext.Current.Response.Write("PostReleaseRequestState<br />");
}
void context_UpdateRequestCache(object sender, EventArgs e)
{
HttpApplication app = sender as HttpApplication;
CommonHelper.WriteLog(string.Format("{0}.UpdateRequestCache", this.GetType().Name), app.GetHashCode().ToString());
//HttpContext.Current.Response.Write("UpdateRequestCache<br />");
}
void context_PostUpdateRequestCache(object sender, EventArgs e)
{
HttpApplication app = sender as HttpApplication;
CommonHelper.WriteLog(string.Format("{0}.PostUpdateRequestCache", this.GetType().Name), app.GetHashCode().ToString());
//HttpContext.Current.Response.Write("PostUpdateRequestCache<br />");
}
void LogRequest(Object source, EventArgs e)
{
//可以在此处放置自定义日志记录逻辑
HttpApplication app = source as HttpApplication;
CommonHelper.WriteLog(string.Format("{0}.LogRequest", this.GetType().Name), app.GetHashCode().ToString());
//HttpContext.Current.Response.Write("OnLogRequest<br />");
}
void context_PostLogRequest(object sender, EventArgs e)
{
HttpApplication app = sender as HttpApplication;
CommonHelper.WriteLog(string.Format("{0}.PostLogRequest", this.GetType().Name), app.GetHashCode().ToString());
//HttpContext.Current.Response.Write("PostLogRequest<br />");
}
void context_EndRequest(object sender, EventArgs e)
{
HttpApplication app = sender as HttpApplication;
CommonHelper.WriteLog(string.Format("{0}.EndRequest", this.GetType().Name), app.GetHashCode().ToString());
//HttpContext.Current.Response.Write("EndRequest<br />");
}
void context_PreSendRequestContent(object sender, EventArgs e)
{
HttpApplication app = sender as HttpApplication;
CommonHelper.WriteLog(string.Format("{0}.PreSendRequestContent", this.GetType().Name), app.GetHashCode().ToString());
//HttpContext.Current.Response.Write("PreSendRequestContent<br />");
}
void context_PreSendRequestHeaders(object sender, EventArgs e)
{
HttpApplication app = sender as HttpApplication;
CommonHelper.WriteLog(string.Format("{0}.PreSendRequestHeaders", this.GetType().Name), app.GetHashCode().ToString());
//HttpContext.Current.Response.Write("PreSendRequestHeaders<br />");
}
void context_RequestCompleted(object sender, EventArgs e)
{
HttpApplication app = sender as HttpApplication;
CommonHelper.WriteLog(string.Format("{0}.RequestCompleted{1}", this.GetType().Name, Environment.NewLine), app.GetHashCode().ToString());
// HttpContext.Current.Response.Write("RequestCompleted<br />");
}
void context_Error(object sender, EventArgs e)
{
HttpApplication app = sender as HttpApplication;
CommonHelper.WriteLog("Error", app.GetHashCode().ToString());
//HttpContext.Current.Response.Write("Error<br />");
}
void context_Disposed(object sender, EventArgs e)
{
HttpApplication app = sender as HttpApplication;
CommonHelper.WriteLog(string.Format("*******{0}.Disposed*****************", this.GetType().Name), app.GetHashCode().ToString());
//HttpContext.Current.Response.Write("Disposed<br />");
}
#endregion
}
}
|
using System;
using System.Collections;
namespace SharpPcap.Util
{
public class IPAddressRange : NumberRange, IEnumerator, IEnumerable
{
virtual public System.String FisrtIPAddress
{
get
{
return IPUtil.IpToString(Min);
}
set
{
Min = (IPUtil.IpToLong(value));
}
}
virtual public System.String LastIPAddress
{
get
{
return IPUtil.IpToString(Max);
}
set
{
Max = (IPUtil.IpToLong(value));
}
}
virtual public System.String CurrentIPAddress
{
get
{
return IPUtil.IpToString(CurrentNumber);
}
set
{
CurrentNumber = IPUtil.IpToLong(value);
}
}
private const long MIN_IP = 0;
private const long MAX_IP = 0xFFFFFFFFL;
public IPAddressRange()
: this(MIN_IP, MAX_IP)
{
}
public IPAddressRange(long min, long max)
: this(min, max, true)
{
}
public IPAddressRange(long min, long max, bool isRandom)
: this(min, max, isRandom, MIN_IP, MAX_IP)
{
}
public IPAddressRange(long min, long max, long step)
: this(min, max, step, MIN_IP, MAX_IP)
{
}
protected internal IPAddressRange(long min, long max, long step, long totalMin, long totalMax)
: base(min, max, step, totalMin, totalMax)
{
}
protected internal IPAddressRange(long min, long max, bool isRandom, long totalMin, long totalMax)
: base(min, max, isRandom, totalMin, totalMax)
{
}
// String
public IPAddressRange(System.String min, System.String max)
: this(min, max, true)
{
}
public IPAddressRange(System.String min, System.String max, bool isRandom)
: this(min, max, isRandom, MIN_IP, MAX_IP)
{
}
public IPAddressRange(System.String min, System.String max, long step)
: this(min, max, step, MIN_IP, MAX_IP)
{
}
protected internal IPAddressRange(System.String min, System.String max, long step, long totalMin, long totalMax)
: this(IPUtil.IpToLong(min), IPUtil.IpToLong(max), step, totalMin, totalMax)
{
}
protected internal IPAddressRange(System.String min, System.String max, bool isRandom, long totalMin, long totalMax)
: this(IPUtil.IpToLong(min), IPUtil.IpToLong(max), isRandom, totalMin, totalMax)
{
}
public static IPAddressRange fromString(System.String range)
{
if (IPUtil.IsRange(range))
{
try
{
return new IPSubnet(IPUtil.ExtractIp(range), IPUtil.ExtractMaskBits(range));
}
catch (System.Exception e)
{
Console.Error.WriteLine(e.StackTrace);
}
}
return new IPAddressRange(range, range);
}
// </Constructors>
public override long size()
{
return base.size();
}
public virtual System.String nextIPAddress()
{
return IPUtil.IpToString(nextNumber());
}
#region IEnumerator Members
public void Reset()
{
throw new Exception("Reset(): Not implemented");
}
public object Current
{
get
{
return CurrentIPAddress;
}
}
public bool MoveNext()
{
this.nextIPAddress();
return true;
}
#endregion
#region IEnumerable Members
public IEnumerator GetEnumerator()
{
return this;
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Listas
{
class Program
{
private static readonly string[] colors = { "MAGENTA", "RED", "WHITE", "BLUE", "CYAN" };
private static readonly string[] removeColors = { "RED", "WHITE", "BLUE" };
static void Main(string[] args)
{
List<string> colors = new List<string>();
colors.Add("MAGENTA");
colors.Add("RED");
colors.Add("WHITE");
colors.Add("BLUE");
colors.Add("CYAN");
List<string> removecolors = new List<string>();
removecolors.Add("RED");
removecolors.Add("WHITE");
removecolors.Add("BLUE");
foreach (string color in colors)
Console.WriteLine(color);
colors.Remove("RED");
colors.Remove("WHITE");
colors.Remove("BLUE");
foreach (string colores in colors)
Console.WriteLine(colores);
Console.ReadLine();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace UDM
{
public abstract class Aggregation
{
protected List<Cell> cells;
public abstract Object GetAggregatedValue(List<Cell> cells);
}
}
|
using System.Collections.Generic;
using UIKit;
namespace App1
{
public class SimpleViewController : UIViewController
{
private SimpleView m_simpleView;
public override void LoadView()
{
m_simpleView = new SimpleView();
m_simpleView.BuildView();
View = m_simpleView;
}
public override void ViewDidLoad()
{
m_simpleView.TableSource.Data = new List<string>
{
"Chathurika",
"Chandu",
"Lakmal",
"Mariss",
"Morten",
"Prasad",
"Rizan",
"Sandun",
"Sudantha",
"Tharika",
"Runar",
"Peter",
"Lars",
"Jonas",
"Karoline",
"Phuong",
"Malin"
};
View.LayoutSubviews();
}
}
} |
namespace OmniSharp.Extensions.JsonRpc
{
public class SerialRequestProcessIdentifier : IRequestProcessIdentifier
{
public RequestProcessType Identify(IHandlerDescriptor descriptor) => descriptor.RequestProcessType ?? RequestProcessType.Serial;
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/**
* Copyright (c) blueback
* Released under the MIT License
* https://github.com/bluebackblue/fee/blob/master/LICENSE.txt
* http://bbbproject.sakura.ne.jp/wordpress/mitlicense
* @brief フェード。スプライト。
*/
/** NFade
*/
namespace NFade
{
/** Fade_Sprite2D
*/
public class Fade_Sprite2D : NRender2D.Sprite2D
{
/** constructor。
*/
public Fade_Sprite2D(NDeleter.Deleter a_deleter,NRender2D.State2D a_state,long a_drawpriority)
:
base(a_deleter,a_state,a_drawpriority)
{
}
/** マテリアルを更新する。
return = true : 変更あり。直後にSetPassの呼び出しが行われます。
*/
public override bool UpdateMaterial(ref Material a_material)
{
//テクスチャ設定。
a_material.mainTexture = Texture2D.whiteTexture;
//SetPass要求。
return true;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1.VmWare
{
/// <summary>
/// Find the number of times the most-common substring occurs in a given string
/// </summary>
public class Interview
{
static void MaxOccurrencesOfSubstrings()
{
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int N = int.Parse(Console.ReadLine());
int[] ln = (Console.ReadLine().Split(new string[] { " " }, StringSplitOptions.None)).Select<string, int>(u => int.Parse(u)).ToArray();
int K = ln[0];
int L = ln[1];
int M = ln[2];
string str = Console.ReadLine();
int maxOccur = 0;
Dictionary<string, int> substringsDictionary = new Dictionary<string, int>();
for (int i = 0; i < N; i++)
{
for (int j = K; j <= L && i + j <= N; ++j)
{
string current = str.Substring(i, j);
//if(current.Distinct().Count() > M)
//continue;
//if(DistinctCountByArray(current) > M)
//continue;
if (DistinctCountByHashset(current) > M)
continue;
int currentOccur = 0;
if (substringsDictionary.ContainsKey(current))
{
currentOccur = substringsDictionary[current];
substringsDictionary[current] = ++currentOccur;
}
else
{
currentOccur++;
substringsDictionary.Add(current, currentOccur);
}
if (currentOccur > maxOccur)
maxOccur = currentOccur;
}
}
Console.WriteLine(maxOccur.ToString());
}
static int DistinctCountByHashset(string str)
{
HashSet<char> chars = new HashSet<char>();
foreach (var item in str)
{
chars.Add(item);
}
return chars.Count();
}
static int DistinctCountByArray(string str)
{
int distinctCount = 0;
int[] chars = new int[26];
foreach (char item in str)
{
int index = (int)item - 97;
int charCount = chars[index];
chars[index] = ++charCount;
}
for (int i = 0; i < 26; i++)
if (chars[i] == 1)
distinctCount++;
return distinctCount;
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace Soko.UI
{
public partial class BiracDana : Form
{
public BiracDana(string caption)
{
InitializeComponent();
this.Text = caption;
this.dtpDatum.CustomFormat = "dd.MM.yyyy";
this.dtpDatum.Format = DateTimePickerFormat.Custom;
Font = Options.Instance.Font;
}
public DateTime Datum
{
get
{
return dtpDatum.Value.Date;
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using HealthLink.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace HealthLink.Controllers
{
public class HospitalsController : Controller
{
private readonly ApplicationDBContext _db;
public HospitalsController(ApplicationDBContext db)
{
_db = db;
}
public IActionResult Index()
{
return View();
}
public async Task <IActionResult> Donors()
{
//var allDonors = await _db.Donors.ToListAsync();
return View(await _db.Donors.ToListAsync());
}
public async Task<IActionResult> Recievers()
{
return View(await _db.Recievers.ToListAsync());
}
public IActionResult PostBlog()
{
return View();
}
public IActionResult Info()
{
return View();
}
}
} |
namespace Triton.Game.Mapping
{
using ns25;
using ns26;
using System;
using System.Collections.Generic;
using Triton.Game;
using Triton.Game.Mono;
[Attribute38("SpecialEventVisualMgr")]
public class SpecialEventVisualMgr : MonoBehaviour
{
public SpecialEventVisualMgr(IntPtr address) : this(address, "SpecialEventVisualMgr")
{
}
public SpecialEventVisualMgr(IntPtr address, string className) : base(address, className)
{
}
public void Awake()
{
base.method_8("Awake", Array.Empty<object>());
}
public static SpecialEventVisualMgr Get()
{
return MonoClass.smethod_15<SpecialEventVisualMgr>(TritonHs.MainAssemblyPath, "", "SpecialEventVisualMgr", "Get", Array.Empty<object>());
}
public static SpecialEventType GetActiveEventType()
{
return MonoClass.smethod_14<SpecialEventType>(TritonHs.MainAssemblyPath, "", "SpecialEventVisualMgr", "GetActiveEventType", Array.Empty<object>());
}
public bool LoadEvent(SpecialEventType eventType)
{
object[] objArray1 = new object[] { eventType };
return base.method_11<bool>("LoadEvent", objArray1);
}
public void OnDestroy()
{
base.method_8("OnDestroy", Array.Empty<object>());
}
public void OnEventFinished(Spell spell, object userData)
{
object[] objArray1 = new object[] { spell, userData };
base.method_8("OnEventFinished", objArray1);
}
public bool UnloadEvent(SpecialEventType eventType)
{
object[] objArray1 = new object[] { eventType };
return base.method_11<bool>("UnloadEvent", objArray1);
}
public List<SpecialEventVisualDef> m_EventDefs
{
get
{
Class267<SpecialEventVisualDef> class2 = base.method_3<Class267<SpecialEventVisualDef>>("m_EventDefs");
if (class2 != null)
{
return class2.method_25();
}
return null;
}
}
}
}
|
using Application.Contract.RepositoryInterfaces;
using Application.Contract.Responses;
using Application.CQRS.Queries;
using Application.Maping;
using MediatR;
using System.Threading;
using System.Threading.Tasks;
namespace Application.CQRS.Handlers.Queries
{
public class GetCryptoCurrencyRawDataHandler : IRequestHandler<GetCryptoCurrencyRawDataQuery, CryptoCurrencyRawResponse>
{
private readonly ICryptoCurrencyRepository _cryptoCurrencyRepository;
private readonly IMapper _mapper;
public GetCryptoCurrencyRawDataHandler(ICryptoCurrencyRepository cryptoCurrencyRepository,
IMapper mapper)
{
_cryptoCurrencyRepository = cryptoCurrencyRepository;
_mapper = mapper;
}
public async Task<CryptoCurrencyRawResponse> Handle(GetCryptoCurrencyRawDataQuery request, CancellationToken cancellationToken)
{
var result = await _cryptoCurrencyRepository.GetCryptoCurrencyAsync(request.Id, cancellationToken);
return _mapper.MapCryptoCurrencyToCryptoCurrencyRawResponse(result);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WF.SDK.Common;
namespace WF.SDK.Models
{
[Serializable]
public class Product : ICacheControl
{
//Cache Control properties - these do not go to the client.
[Newtonsoft.Json.JsonIgnore]
public HydrationFlag HydrationFlag { get; set; }
[Newtonsoft.Json.JsonIgnore]
public DateTime HydrationUTC { get; set; }
[Newtonsoft.Json.JsonIgnore]
public bool RequiresTimeExpiration { get; set; }
//End Cache Control
public Guid Id { get; set; }
public String Name { get; set; }
public String Detail { get; set; }
public ProductType ProductType { get; set; }
public string InboundCSID { get; set; }
public string InboundNumber { get; set; }
public string OutboundCSID { get; set; }
public string OutboundANI { get; set; }
public string FaxHeader { get; set; }
public TimeZoneName TimeZone { get; set; }
public ProductState ProductState { get; set; }
public DateTime CurrentBillingPeriodStart;
public DateTime CurrentBillingPeriodEnd;
public DateTime FreeTrialEnd;
public int PeriodicQuantity;
public int QuantityInbound;
public int QuantityOutbound;
public Product()
{
this.HydrationUTC = DateTime.MinValue;
this.RequiresTimeExpiration = false;
}
public Product(Guid id, string name, ProductType type, string inboundNumber = "") : this()
{
this.Id = id;
this.Name = name;
this.ProductType = type;
this.InboundNumber = "";
}
public Product(Internal.F2EProductItem item)
: this()
{
this.Id = item.Id;
this.Name = item.Name;
//Workaround for legacy product name.
this.ProductType = EnumExtensionMethods.ConvertToSdkProdType(item.ProductType);
//Convert Enums
try { this.ProductState = (ProductState)Enum.Parse(typeof(ProductState), item.ProductState); }
catch { this.ProductState = ProductState.OK; }
this.InboundNumber = item.InboundNumber;
try { this.TimeZone = (TimeZoneName)Enum.Parse(typeof(TimeZoneName), item.TimeZone); }
catch { }
this.CurrentBillingPeriodStart = item.CurrentBillingPeriodStart;
this.CurrentBillingPeriodEnd = item.CurrentBillingPeriodEnd;
this.PeriodicQuantity = item.PeriodicQuantity;
this.QuantityInbound = item.QuantityInbound;
this.QuantityOutbound = item.QuantityOutbound;
this.FreeTrialEnd = item.FreeTrialEnd;
}
internal Product(Internal.ProductItem item) : this()
{
this.Id = item.Id;
this.Name = item.Name;
//Workaround for legacy product name.
this.ProductType = EnumExtensionMethods.ConvertToSdkProdType(item.ProductType);
this.Detail = item.Detail;
this.InboundCSID = item.InboundCSID;
this.InboundNumber = item.InboundNumber;
this.OutboundCSID = item.OutboundCSID;
this.OutboundANI = item.OutboundANI;
this.FaxHeader = item.FaxHeader;
try { this.ProductState = (ProductState)Enum.Parse(typeof(ProductState), item.ProductState); }
catch { this.ProductState = ProductState.OK; }
try { this.TimeZone = (TimeZoneName)Enum.Parse(typeof(TimeZoneName), item.TimeZone); }
catch { }
}
public string BillingDateLabel
{
get
{
if (this.FreeTrialEnd < DateTime.Now) { return "Billing Date"; }
else { return "Free Trial Ends"; }
}
}
public string BillingDateData
{
get
{
if (this.FreeTrialEnd < DateTime.Now) { return this.CurrentBillingPeriodEnd.ToShortDateString(); }
else { return this.FreeTrialEnd.ToShortDateString(); }
}
}
}
public static class ProductInfoExtensions
{
public static Product ToProduct(this Internal.ProductItem obj)
{
if (obj == null) { return null; }
var ret = new Product(obj);
return ret;
}
public static Internal.ProductItem ToProductItem(this Product obj)
{
if (obj == null) { return null; }
var ret = new Internal.ProductItem();
ret.Id = obj.Id;
ret.Detail = obj.Detail;
ret.FaxHeader = obj.FaxHeader;
ret.InboundCSID = obj.InboundCSID;
ret.InboundNumber = obj.InboundNumber;
ret.Name = obj.Name;
ret.OutboundANI = obj.OutboundANI;
ret.OutboundCSID = obj.OutboundCSID;
ret.ProductState = obj.ProductState.ToString();
ret.ProductType = obj.ProductType.ConvertToPolkaProdString();
ret.TimeZone = obj.TimeZone.ToString();
return ret;
}
}
}
|
using System;
using Microsoft.EntityFrameworkCore.Migrations;
namespace VehiculosSanJoaquinMVC.Migrations
{
public partial class CreacionDB : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "NS_tblClientes",
columns: table => new
{
ClId = table.Column<int>(maxLength: 30, nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
ClNombre1 = table.Column<string>(maxLength: 30, nullable: false),
ClNombre2 = table.Column<string>(nullable: true),
ClApellido1 = table.Column<string>(maxLength: 30, nullable: false),
ClApellido2 = table.Column<string>(nullable: true),
ClCedula = table.Column<int>(nullable: false),
ClCorreo = table.Column<string>(nullable: false),
ClTelefono1 = table.Column<string>(nullable: true),
ClTelefono2 = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_NS_tblClientes", x => x.ClId);
});
migrationBuilder.CreateTable(
name: "NS_tblListas",
columns: table => new
{
LiCodigo = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
LiNombre = table.Column<string>(maxLength: 30, nullable: false),
LiActivo = table.Column<string>(maxLength: 10, nullable: false),
LiCodigoPadre = table.Column<string>(maxLength: 10, nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_NS_tblListas", x => x.LiCodigo);
});
migrationBuilder.CreateTable(
name: "NS_tblListasDetalle",
columns: table => new
{
LdClave = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
LdDescripcion1 = table.Column<string>(maxLength: 60, nullable: false),
LdDescripcion2 = table.Column<string>(nullable: true),
LdActivoV1 = table.Column<int>(nullable: false),
LdUsuario = table.Column<int>(nullable: false),
LdFecha = table.Column<DateTime>(nullable: false),
LdusuarioCambio = table.Column<int>(nullable: false),
LdFechaCambio = table.Column<DateTime>(nullable: false),
LdAplicacion = table.Column<string>(nullable: true),
LiCodigo = table.Column<int>(nullable: false),
ListasLiCodigo = table.Column<int>(nullable: true),
ClId = table.Column<int>(nullable: false),
ClienteClId = table.Column<int>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_NS_tblListasDetalle", x => x.LdClave);
table.ForeignKey(
name: "FK_NS_tblListasDetalle_NS_tblClientes_ClienteClId",
column: x => x.ClienteClId,
principalTable: "NS_tblClientes",
principalColumn: "ClId",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_NS_tblListasDetalle_NS_tblListas_ListasLiCodigo",
column: x => x.ListasLiCodigo,
principalTable: "NS_tblListas",
principalColumn: "LiCodigo",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateIndex(
name: "IX_NS_tblListasDetalle_ClienteClId",
table: "NS_tblListasDetalle",
column: "ClienteClId");
migrationBuilder.CreateIndex(
name: "IX_NS_tblListasDetalle_ListasLiCodigo",
table: "NS_tblListasDetalle",
column: "ListasLiCodigo");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "NS_tblListasDetalle");
migrationBuilder.DropTable(
name: "NS_tblClientes");
migrationBuilder.DropTable(
name: "NS_tblListas");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using async_inn.Data;
using async_inn.Models;
using async_inn.Models.Interfaces;
using async_inn.Models.DTOs;
using Microsoft.AspNetCore.Authorization;
namespace async_inn.Controllers
{
[Authorize]
[Route("api/[controller]")]
[ApiController]
// our constructor is bringing in a reference to our db
public class RoomsController : ControllerBase
{
private readonly IRoom _room;
public RoomsController(IRoom room)
{
_room = room;
}
// GET: api/Rooms
[HttpGet]
[AllowAnonymous]
public async Task<ActionResult<IEnumerable<RoomDTO>>> GetRooms()
{
return await _room.GetRooms();
}
// GET: api/Rooms/5
[HttpGet("{id}")]
[AllowAnonymous]
public async Task<ActionResult<RoomDTO>> GetRoom(int id)
{
RoomDTO roomdto = await _room.GetRoom(id);
return roomdto;
}
// PUT: api/Rooms/5
// To protect from overposting attacks, enable the specific properties you want to bind to, for
// more details, see https://go.microsoft.com/fwlink/?linkid=2123754.
[HttpPut("{id}")]
[Authorize(Policy = "MediumPrivileges")]
public async Task<IActionResult> PutRoom(int id, RoomDTO roomdto)
{
if (id != roomdto.Id)
{
return BadRequest();
}
var updatedRoom = await _room.Update(roomdto);
return Ok(updatedRoom);
}
// POST: api/Rooms
// To protect from overposting attacks, enable the specific properties you want to bind to, for
// more details, see https://go.microsoft.com/fwlink/?linkid=2123754.
[HttpPost]
[Authorize(Policy = "HighPrivileges")]
public async Task<ActionResult<Room>> PostRoom(RoomDTO roomdto)
{
await _room.Create(roomdto);
return CreatedAtAction("GetRoom", new { id = roomdto.Id }, roomdto);
}
//Post
[HttpPost]
[Route("{roomId}/{amenityId}")]
// Mode Binding
[Authorize(Policy = "NormalPrivileges")]
public async Task<IActionResult> AddAmenityToRoom(int roomId, int amenityId)
{
await _room.AddAmenityToRoom(roomId, amenityId);
return Ok();
}
[HttpDelete]
[Route("{roomId}/{amenityId}")]
[Authorize(Policy = "NormalPrivileges")]
public async Task<IActionResult> RemoveAmenityFromRome(int roomId, int amenityId)
{
await _room.RemoveAmenityFromRoom(roomId, amenityId);
return Ok();
}
// DELETE: api/Rooms/5
[HttpDelete("{id}")]
[Authorize(Policy = "HighPrivileges")]
public async Task<ActionResult<Room>> DeleteRoom(int id)
{
await _room.Delete(id);
return NoContent();
}
}
}
|
using System;
/// <summary> This is the class object </summary>
class VectorMath
{
/// <summary> >This method gets either a 2D or 3D vector and returns its magnitude,
///if the vector is not 2D or 3D it returns -1</summary>
public static double Magnitude(double[] vector)
{
if (vector.Length < 2 || vector.Length > 3)
return -1;
double r = 0;
foreach (double i in vector)
{
r += (i * i);
}
r = Math.Round(Math.Sqrt(r), 2);
return r;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace console
{
public class _017_InsertInterval
{
/// <summary>
/// Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).
/// You may assume that the intervals were initially sorted according to their start times.
/// Example 1:
/// Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9].
/// Example 2:
/// Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] in as [1,2],[3,10],[12,16].
/// This is because the new interval [4,9] overlaps with [3,5],[6,7],[8,10].
/// </summary>
/// <param name="intervals"></param>
/// <param name="newInterval"></param>
/// <returns></returns>
public Interval[] InsertInterval(Interval[] intervals, Interval newInterval)
{
if (intervals.Length == 0)
{
return new Interval[] { newInterval };
}
List<Interval> res = new List<Interval>();
int startIndex =-1;
int endIndex = -1;
int newStart =0;
int newEnd =0;
int overlappedIndex=-1;
for(int i = 0; i< intervals.Length; i ++)
{
if(newInterval.Start >= intervals[i].Start && newInterval.Start<= intervals[i].End)
startIndex = i;
if(newInterval.Start <= intervals[i].Start && newInterval.End >= intervals[i].End)
{
intervals[i] = null;
overlappedIndex = i;
continue;
}
if(newInterval.End>= intervals[i].Start && newInterval.End <= intervals[i].End)
endIndex = i;
}
// if startindex and end index are same, then newInterval fall within one interval.
if (startIndex == endIndex && overlappedIndex == -1)
{
int insertIndex = -1;
if (startIndex != -1)
{
return intervals;
}
else
{
if (newInterval.End < intervals[0].Start)
{
insertIndex = -1;
}
else if (newInterval.Start > intervals[intervals.Length - 1].End)
{
insertIndex = intervals.Length;
}
else
{
for (int i = 0; i < intervals.Length - 1; i++)
{
if (newInterval.Start > intervals[i].End && newInterval.End < intervals[i + 1].Start)
insertIndex = i;
}
}
}
if (insertIndex == -1)
{
res.Add(newInterval);
res.AddRange(intervals);
}
else if (insertIndex == intervals.Length)
{
res.AddRange(intervals);
res.Add(newInterval);
}
else
{
for (int i = 0; i <= intervals.Length; i++)
{
res.Add(intervals[i]);
if (i == insertIndex)
{
res.Add(newInterval);
}
}
}
}
else
{
if (startIndex != -1)
{
newStart = intervals[startIndex].Start;
intervals[startIndex] = null;
}
else
{
newStart = newInterval.Start;
}
if (endIndex != -1)
{
newEnd = intervals[endIndex].End;
intervals[endIndex] = null;
}
else
{
newEnd = newInterval.End;
}
Interval tmp = new Interval(newStart, newEnd);
bool newIntervalInserted = false;
if (startIndex != -1)
{
intervals[startIndex] = tmp;
newIntervalInserted = true;
}
else if (endIndex != -1)
{
intervals[endIndex] = tmp;
newIntervalInserted = true;
}
else
{
intervals[overlappedIndex] = tmp;
newIntervalInserted = true;
}
for (int i = 0; i < intervals.Length; i++)
{
if (intervals[i] != null)
{
res.Add(intervals[i]);
}
}
}
return res.ToArray();
}
/// <summary>
/// Same as last method.
/// </summary>
/// <param name="intervals"></param>
/// <param name="newInterval"></param>
/// <returns></returns>
public List<Interval> InsertInterval(List<Interval> intervals, Interval newInterval)
{
int newS = -1;
int newE = -1;
List<Interval> ret = new List<Interval>();
// case 1: empty lsit.
if (intervals.Count == 0)
{
ret.Add(newInterval);
return ret;
}
// case 2: new interval before any other interval.
if (newInterval.End < intervals[0].Start)
{
ret.Add(newInterval);
foreach (var item in intervals)
{
ret.Add(item);
}
return ret;
}
// case 3: new interval after any other interval.
if (newInterval.Start > intervals[intervals.Count - 1].End)
{
foreach (var item in intervals)
{
ret.Add(item);
}
ret.Add(newInterval);
return ret;
}
// case 4: new interval covered all other intervals.
if (newInterval.Start <= intervals[0].Start && newInterval.End >= intervals[intervals.Count - 1].End)
{
ret.Add(newInterval);
return ret;
}
// case 5: new interval stick out to the left side.
if (newInterval.Start <= intervals[0].Start)
{
newS = newInterval.Start;
foreach (var item in intervals)
{
if (newInterval.End > item.End)
{
continue;
}
if (newE == -1 && newInterval.End >= item.Start && newInterval.End <= item.End)
{
newE = item.End;
ret.Add(new Interval(newS, newE));
continue;
}
if (newE == -1 && newInterval.End < item.Start)
{
newE = newInterval.End;
ret.Add(new Interval(newS, newE));
ret.Add(item);
continue;
}
ret.Add(item);
}
return ret;
}
// case 6: new interval stick out to the right of the all intervals.
if (newInterval.End >= intervals[intervals.Count - 1].End)
{
newE = newInterval.End;
foreach (var item in intervals)
{
if (newInterval.Start > item.End)
{
ret.Add(item);
continue;
}
if (newS == -1 && newInterval.Start >= item.Start && newInterval.Start <= item.End)
{
newS = item.Start;
ret.Add(new Interval(newS, newE));
return ret;
}
if (newS == -1 && newInterval.Start < item.Start)
{
newS = newInterval.Start;
ret.Add(new Interval(newS, newE));
return ret;
}
}
return ret;
}
// case 8: new interval overlaps old intervals.
foreach (var item in intervals)
{
// ??? should it be new Interval.Start > itme.Start?
if (newS == -1 && newInterval.Start < item.Start)
{
newS = newInterval.Start;
continue;
}
// new interval totally merged into 1 old interval.
if (newS == -1 && newInterval.Start >= item.Start && newInterval.Start <= item.End)
{
newS = item.Start;
continue;
}
// new interval after one old interval.
if (newS == -1 && newInterval.Start > item.End)
{
ret.Add(item);
}
// new inverval stick out right to one old interval.
if (newInterval.End > item.End)
{
continue;
}
// End > start and End < End, new interval end landed inside one interval.
if (newE == -1 && newInterval.End >= item.Start && newInterval.End <= item.End)
{
newE = item.End;
ret.Add(new Interval(newS, newE));
continue;
}
// new interval before one interval.
if (newE == -1 && newInterval.End < item.Start)
{
newE = newInterval.End;
ret.Add(new Interval(newS, newE));
ret.Add(item);
continue;
}
ret.Add(item);
}
return ret;
}
}
public class Interval
{
public int Start;
public int End;
public Interval()
{
Start = 0;
End = 0;
}
public Interval(int start, int end)
{
Start = start;
End = end;
}
}
}
|
namespace Tolley.Data.Sql
{
/// <summary>
/// Defines a the encryption requirements for a sql connection
/// </summary>
public class SqlSecurityContext
{
/// <summary>
/// Sql Connections should be encrypted
/// </summary>
public bool IsEncrypted { get; set; }
/// <summary>
/// Symmetric key name
/// </summary>
public string KeyName { get; set; }
/// <summary>
/// Decryption certificate
/// </summary>
public string Certificate { get; set; }
}
}
|
using Airfield_Simulator.Core.Models;
using Airfield_Simulator.Core.Simulation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Airfield_Simulator.Core.FlightRoutes
{
public class Router : IRouter
{
private readonly IWeatherController _weatherController;
public Router(IWeatherController weathercontroller)
{
_weatherController = weathercontroller;
}
public IRoute GetRoute(RouteDestination destination, GeoPoint currentlocation)
{
return GetArrivalRoute(currentlocation);
}
private IRoute GetArrivalRoute(GeoPoint currentlocation)
{
return _weatherController.WindDegrees < 180 ? GetArrivalRoute09(currentlocation) : GetArrivalRoute27(currentlocation);
}
private static IRoute GetArrivalRoute27(GeoPoint currentlocation)
{
var returnroute = new Route();
if(currentlocation.Y > 0)
{
returnroute.Add(AirspaceWaypoints.DownwindNorth);
returnroute.Add(AirspaceWaypoints.TurnPointNorth27);
}
else
{
returnroute.Add(AirspaceWaypoints.DownwindSouth);
returnroute.Add(AirspaceWaypoints.TurnPointSouth27);
}
returnroute.Add(AirspaceWaypoints.Final27);
returnroute.Add(AirspaceWaypoints.TouchDown27);
return returnroute;
}
private static IRoute GetArrivalRoute09(GeoPoint currentlocation)
{
var returnroute = new Route();
if (currentlocation.Y > 0)
{
returnroute.Add(AirspaceWaypoints.DownwindNorth);
returnroute.Add(AirspaceWaypoints.TurnPointNorth09);
}
else
{
returnroute.Add(AirspaceWaypoints.DownwindSouth);
returnroute.Add(AirspaceWaypoints.TurnPointSouth09);
}
returnroute.Add(AirspaceWaypoints.Final09);
returnroute.Add(AirspaceWaypoints.TouchDown09);
return returnroute;
}
}
}
|
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Sbidu.Data;
using Sbidu.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Sbidu.Helper
{
public static class AddFavorites
{
public async static Task<bool> AddFavorite(int Id, ApplicationDbContext _context, AppUser user)
{
var auction = _context.AuctionProducts.Include(x => x.UserAuctionProducts).FirstOrDefault(x => x.Id == Id);
var isFavorite = auction.UserAuctionProducts.Where(x => x.IsFavorit == true).FirstOrDefault(x => x.AppUserId == user.Id);
if (auction.UserAuctionProducts.Any(x => x.IsFavorit == false))
{
auction.UserAuctionProducts.Where(x => x.IsFavorit == false)
.OrderBy(x => x.Bid)
.FirstOrDefault().IsFavorit = true;
_context.SaveChanges();
}
else if (isFavorite == null)
{
UserAuctionProduct userAuction = new UserAuctionProduct
{
AppUserId = user.Id,
Bid = 0,
AuctionProductId = Id,
IsFavorit = true,
AddDate = DateTime.Now
};
_context.UserAuctionProducts.Add(userAuction);
await _context.SaveChangesAsync();
}
else
{
isFavorite.IsFavorit = false;
await _context.SaveChangesAsync();
}
return true;
}
}
}
|
using PDV.DAO.Custom;
using PDV.DAO.DB.Controller;
using PDV.DAO.Entidades;
using System.Collections.Generic;
namespace PDV.CONTROLER.Funcoes
{
public class FuncoesCst
{
public static CSTIcms GetCSTIcmsPorID(decimal IDCSTIcms)
{
using (SQLQuery oSQL = new SQLQuery())
{
oSQL.SQL = string.Format("SELECT * FROM CSTICMS WHERE IDCSTICMS = @IDCSTICMS");
oSQL.ParamByName["IDCSTICMS"] = IDCSTIcms;
oSQL.Open();
return EntityUtil<CSTIcms>.ParseDataRow(oSQL.dtDados.Rows[0]);
}
}
public static CSTIcms GetCSTIcmsPorCodigo(decimal Codigo)
{
using (SQLQuery oSQL = new SQLQuery())
{
oSQL.SQL = string.Format("SELECT * FROM CSTICMS WHERE CSTCSOSN = @CSTCSOSN");
oSQL.ParamByName["CSTCSOSN"] = Codigo;
oSQL.Open();
return EntityUtil<CSTIcms>.ParseDataRow(oSQL.dtDados.Rows[0]);
}
}
public static List<CSTIcms> GetCSTIcms(decimal CRT)
{
using (SQLQuery oSQL = new SQLQuery())
{
oSQL.SQL = string.Format("SELECT * FROM CSTICMS WHERE {0}", CRT == 1 ? "CSTCSOSN BETWEEN 101 AND 900" : "CSTCSOSN BETWEEN 0 AND 90");
oSQL.Open();
return new DataTableParser<CSTIcms>().ParseDataTable(oSQL.dtDados);
}
}
public static List<CSTIpi> GetCSTIpi()
{
using (SQLQuery oSQL = new SQLQuery())
{
oSQL.SQL = "SELECT * FROM CSTIPI ORDER BY IDCSTIPI";
oSQL.Open();
return new DataTableParser<CSTIpi>().ParseDataTable(oSQL.dtDados);
}
}
public static CSTIpi GetCSTIpi(decimal IDCSTIpi)
{
using (SQLQuery oSQL = new SQLQuery())
{
oSQL.SQL = "SELECT * FROM CSTIPI WHERE IDCSTIPI = @IDCSTIPI";
oSQL.ParamByName["IDCSTIPI"] = IDCSTIpi;
oSQL.Open();
return EntityUtil<CSTIpi>.ParseDataRow(oSQL.dtDados.Rows[0]);
}
}
public static List<CSTPis> GetCSTPis()
{
using (SQLQuery oSQL = new SQLQuery())
{
oSQL.SQL = "SELECT * FROM CSTPIS ORDER BY IDCSTPIS";
oSQL.Open();
return new DataTableParser<CSTPis>().ParseDataTable(oSQL.dtDados);
}
}
public static CSTPis GetCSTPis(decimal IDCSTPis)
{
using (SQLQuery oSQL = new SQLQuery())
{
oSQL.SQL = "SELECT * FROM CSTPIS WHERE IDCSTPIS = @IDCSTPIS";
oSQL.ParamByName["IDCSTPIS"] = IDCSTPis;
oSQL.Open();
return EntityUtil<CSTPis>.ParseDataRow(oSQL.dtDados.Rows[0]);
}
}
public static CSTPis GetCSTPisPorCST(decimal CST)
{
using (SQLQuery oSQL = new SQLQuery())
{
oSQL.SQL = "SELECT * FROM CSTPIS WHERE CST = @CST";
oSQL.ParamByName["CST"] = CST;
oSQL.Open();
return EntityUtil<CSTPis>.ParseDataRow(oSQL.dtDados.Rows[0]);
}
}
public static CSTCofins GetCSTCofinsPorCST(decimal CST)
{
using (SQLQuery oSQL = new SQLQuery())
{
oSQL.SQL = "SELECT * FROM CSTCOFINS WHERE CST = @CST";
oSQL.ParamByName["CST"] = CST;
oSQL.Open();
return EntityUtil<CSTCofins>.ParseDataRow(oSQL.dtDados.Rows[0]);
}
}
public static List<CSTCofins> GetCSTCofins()
{
using (SQLQuery oSQL = new SQLQuery())
{
oSQL.SQL = "SELECT * FROM CSTCOFINS ORDER BY IDCSTCOFINS";
oSQL.Open();
return new DataTableParser<CSTCofins>().ParseDataTable(oSQL.dtDados);
}
}
public static CSTCofins GetCSTCofins(decimal IDCSTCofins)
{
using (SQLQuery oSQL = new SQLQuery())
{
oSQL.SQL = "SELECT * FROM CSTCOFINS WHERE IDCSTCOFINS = @IDCSTCOFINS";
oSQL.ParamByName["IDCSTCOFINS"] = IDCSTCofins;
oSQL.Open();
return EntityUtil<CSTCofins>.ParseDataRow(oSQL.dtDados.Rows[0]);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using DBManager.DBASES;
using System.Net;
namespace DBManager
{
public partial class frmSQLServerTunnelServerConnection : BlueForm
{
private bool importSchema;
private List<string> tbls;
SQLServerTunnel c = null;
public frmSQLServerTunnelServerConnection()
{
InitializeComponent();
}
public frmSQLServerTunnelServerConnection(bool importSchema, List<string> tbls)
{
InitializeComponent();
this.importSchema = importSchema;
this.tbls = tbls;
}
private void button2_Click(object sender, EventArgs e)
{
this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
}
private void button1_Click(object sender, EventArgs e)
{
if (txtURL.Text.Trim().Length == 0 || txtPassword.Text.Trim().Length == 0)
{
MessageBox.Show("Please fill all infos!", General.apTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return;
}
else
{
if (txtPassword.Text.Contains("$"))
{
MessageBox.Show("The symbol '$' forbidden!", General.apTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return;
}
if (!txtURL.Text.ToLower().StartsWith("https"))
{
if (MessageBox.Show("Server must be https enabled, are you sure you want to continue ?", General.apTitle, MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == System.Windows.Forms.DialogResult.No)
return;
}
}
if (txtURL.Text.ToLower().StartsWith("https"))
ServicePointManager.SecurityProtocol = (SecurityProtocolType)(0xc0 | 0x300 | 0xc00);
else
ServicePointManager.SecurityProtocol = (SecurityProtocolType)(48 | 192);
Cursor = System.Windows.Forms.Cursors.WaitCursor;
c = new SQLServerTunnel();
c.isConnected += new SQLServerTunnel.IsConnected(c_isConnected);
try
{
Cursor = System.Windows.Forms.Cursors.WaitCursor;
c.testConnection(txtURL.Text.Trim(), txtPassword.Text.Trim());
}
catch (Exception ex)
{
General.Mes(ex.Message);
}
finally
{
}
}
delegate void c_isConnectedCallback(string isSuccess);
void c_isConnected(string isSuccess)
{
if (txtURL.InvokeRequired)
{
txtURL.BeginInvoke(new c_isConnectedCallback(this.c_isConnected), new object[] { isSuccess });
return;
}
Cursor = System.Windows.Forms.Cursors.Default;
if (isSuccess == "ok")
{
General.Connections.Add(new dbConnection
{
dbaseName = "",
filename = "",
password = txtPassword.Text,
port = "",
serverName = txtURL.Text,
TYPE = (int)General.dbTypes.SQLSERVERtunnel,
user = ""
});
this.DialogResult = System.Windows.Forms.DialogResult.OK;
}
else
General.Mes("Could not connect! due : " + isSuccess);
}
private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
frmInformation i = new frmInformation(DBManager.Properties.Resources.tunnelPHP_PDO_SQLServer);
i.ShowDialog();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyGauge : MonoBehaviour
{
const float SCALE_CHANGE_SPEED = 0.8f;
AudioSource audioSource;
BossBase bossScript;
RectTransform rt;
float maxHP;
float hp;
bool appeared;
bool appearing;
bool isSubGauge;
// Start is called before the first frame update
void Start()
{
transform.parent.transform.localScale = new Vector2(0, 0);
GameObject bossWoodObj = GameObject.Find("BossWood");
if (bossWoodObj != null)
{
bossScript = bossWoodObj.GetComponent<BossWood>();
maxHP = bossWoodObj.GetComponentInChildren<Object>().GetMaxHp();
}
GameObject kiritanObj = GameObject.Find("Kiritan");
if (kiritanObj != null)
{
bossScript = kiritanObj.GetComponent<Kiritan>();
maxHP = kiritanObj.GetComponentInChildren<Object>().GetMaxHp();
}
GameObject makiObj = GameObject.Find("Maki");
if (makiObj != null)
{
bossScript = makiObj.GetComponent<Maki>();
maxHP = makiObj.GetComponentInChildren<Object>().GetMaxHp();
}
GameObject kireturnObj = GameObject.Find("KiReturn");
if (kireturnObj != null)
{
bossScript = kireturnObj.GetComponent<KiReturn>();
maxHP = kireturnObj.GetComponentInChildren<Object>().GetMaxHp();
}
GameObject zunkoObj = GameObject.Find("Zunko");
if (zunkoObj != null)
{
bossScript = zunkoObj.GetComponent<Zunko>();
maxHP = zunkoObj.GetComponentInChildren<Object>().GetMaxHp();
}
GameObject yukariObj = GameObject.Find("Yukari");
if (yukariObj != null)
{
bossScript = yukariObj.GetComponent<Yukari>();
maxHP = yukariObj.GetComponentInChildren<Object>().GetMaxHp();
}
appeared = false;
hp = maxHP;
rt = this.GetComponent<RectTransform>();
rt.localScale = new Vector2(0, 1.0f);
}
// Update is called once per frame
void Update()
{
float step = SCALE_CHANGE_SPEED * Time.deltaTime;
if (appeared)
{
rt.localScale = Vector2.MoveTowards(rt.localScale, new Vector2(hp / maxHP, 1.0f), step);
}
else if (appearing)
{
if (rt.localScale.x >= 1.0f)
{
StaticValues.isPause = false;
if (bossScript != null)
bossScript.SetActive();
appeared = true;
AudioManager.Instance.StopSE();
}
rt.localScale = Vector2.MoveTowards(rt.localScale, new Vector2(1.0f, 1.0f), step);
}
}
public void SetMaxHP(float hp)
{
this.maxHP = hp;
}
public void SetHP(float hp)
{
this.hp = hp;
this.hp = Mathf.Max(0, this.hp);
this.hp = Mathf.Min(maxHP, this.hp);
}
public void Damage(float damage)
{
this.hp -= damage;
this.hp = Mathf.Max(0, this.hp);
}
public void Heal(float heal)
{
this.hp += heal;
this.hp = Mathf.Min(maxHP, this.hp);
}
public void PlayGaugeAppear()
{
if (!appearing && !appeared)
{
transform.parent.transform.localScale = new Vector2(1, isSubGauge ? 0.5f : 1);
StaticValues.isPause = true;
appearing = true;
AudioManager.Instance.PlaySE("Pi");
}
}
public void PlayGaugeReAppear(float reviveHp)
{
appeared = false;
transform.parent.transform.localScale = new Vector2(1, isSubGauge ? 0.5f : 1);
StaticValues.isPause = true;
appearing = true;
AudioManager.Instance.PlaySE("Pi");
hp = reviveHp;
maxHP = reviveHp;
}
public bool IsGaugeAppearPlaying()
{
return (appearing && !appeared);
}
public void SetSubGauge(bool f)
{
isSubGauge = f;
}
}
|
using HangoutsDbLibrary.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WebAPI.Services
{
public interface IServiceLocation
{
void AddLocation(Location location);
List<Location> GetAllLocations();
Location GetLocationById(int id);
void UpdateLocation(Location location);
void DeleteLocation(Location location);
}
}
|
using System;
using System.IO;
using System.Linq;
using System.Web;
using System.Text;
using System.Security.Cryptography;
using System.Collections.Generic;
using System.Configuration;
namespace ReqOneUI
{
public class AspUtil
{
#region public methods
public static string GetRoot()
{
HttpRequest req = HttpContext.Current.Request;
string result = String.Concat(req.Url.Scheme, "://", req.Url.Authority,
req.ApplicationPath.TrimEnd('/'));
return result;
}
public static void RedirectToError(string message)
{
HttpContext.Current.Response.Redirect("~/res/Error.aspx?error=" + message);
}
#endregion public methods
}
} |
namespace Banks.Library.Customers
{
using System;
using System.Collections.Generic;
using System.Text;
using Banks.Library.Accounts;
/// <summary>
/// Abstract customer
/// </summary>
public abstract class Customer
{
protected List<Account> accounts = new List<Account>();
public List<Account> Accounts
{
get
{
return this.accounts;
}
}
/// <summary>
/// Adds a new bank account
/// </summary>
/// <param name="account"></param>
public void AddAccount(Account account)
{
this.accounts.Add(account);
}
/// <summary>
/// Removes a bank account
/// </summary>
/// <param name="account"></param>
public void RemoveAccount(Account account)
{
this.accounts.Remove(account);
}
/// <summary>
/// Deposit money
/// </summary>
/// <param name="account"></param>
/// <param name="amount"></param>
/// <returns></returns>
public IDepositable DepositMoney(IDepositable account, decimal amount)
{
return account.DepositMoney(amount);
}
/// <summary>
/// Withdraw money
/// </summary>
/// <param name="account"></param>
/// <param name="amount"></param>
/// <returns></returns>
public IWithdrawable WithdrawMoney(IWithdrawable account, decimal amount)
{
return account.WithdrawMoney(amount);
}
/// <summary>
/// Customer information
/// </summary>
/// <returns></returns>
public override string ToString()
{
StringBuilder info = new StringBuilder();
info.Append("Type: ").AppendLine(this.GetType().ToString());
return info.ToString();
}
}
}
|
#region License
// Copyright (c) 2011 Nano Taboada, http://openid.nanotaboada.com.ar
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#endregion
namespace Dotnet.Samples.Entity
{
#region References
using System;
using System.Linq;
using System.Text;
#endregion
class Program
{
static void Main()
{
try
{
using (var catalog = new Catalog())
{
var books = from book in catalog.Books
where book.InStock == true
orderby book.Published
select book;
var txt = new StringBuilder();
txt.AppendLine(String.Format("{0,-37} {1,-23} {2,10} {3,5}", "-".Repeat(37), "-".Repeat(23), "-".Repeat(10), "-".Repeat(5)));
txt.AppendLine(String.Format("{0,-37} {1,-23} {2,-10} {3,-5}", "Title", "Author", "Published", "Pages"));
txt.AppendLine(String.Format("{0,-37} {1,-23} {2,10} {3,5}", "-".Repeat(37), "-".Repeat(23), "-".Repeat(10), "-".Repeat(5)));
foreach (var book in books)
{
txt.AppendLine(String.Format("{0,-37} {1,-23} {2,10} {3,5}", book.Title, book.Author, book.Published.ToShortDateString(), book.Pages));
}
txt.AppendLine(String.Format("{0,-37} {1,-23} {2,10} {3,5}", "-".Repeat(37), "-".Repeat(23), "-".Repeat(10), "-".Repeat(5)));
Console.WriteLine(txt.ToString());
}
}
catch (Exception err)
{
Console.Write(Environment.NewLine);
Console.WriteLine(String.Format("Exception: {0}", err.Message));
}
finally
{
Console.Write(Environment.NewLine);
Console.Write("Press any key to continue . . .");
Console.ReadKey(true);
}
}
}
}
|
using System;
using System.Collections.Generic;
using Akka.Actor;
using DownloadExtractLib.Messages;
namespace DownloadExtractLib
{
public class DramaActor : ReceiveActor
{
readonly Dictionary<string, string> Url2FileDict = new Dictionary<string, string>();
readonly string OutFolder;
readonly IActorRef DownloadCoordinator;
public DramaActor(IActorRef downloadCoordinatorActor, string outFolder)
{
DownloadCoordinator = downloadCoordinatorActor ?? throw new InvalidOperationException("Must specify DownloadCoordinatorActor on DramaActor ctor");
outFolder = outFolder?.Trim();
if (outFolder == null)
{
throw new InvalidOperationException("Must specify target directory on creation");
}
OutFolder = (outFolder[outFolder.Length - 1] == '\\') ? outFolder : outFolder + '\\';
Receive<AddMessage>(AddHandler);
}
bool AddHandler(AddMessage addmsg)
{
string fileName;
if (!Url2FileDict.ContainsKey(addmsg.Url))
{
fileName = addmsg.FileName;
if (!Url2FileDict.ContainsValue(fileName)) // name clash (different Url already claimed same name) ?
{
fileName = (new Guid()).ToString(); // yes, so invent alias fiilename instead
}
Url2FileDict.Add(addmsg.Url, fileName); // record this mapping
}
else
{
fileName = Url2FileDict[addmsg.Url]; // this file already registered [avoid multiple downloads]
}
return true;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FinalliziedProject.Databases
{
class DataProcess
{
// Object orianted katili class :))))))
public List<LibraryPasage> getAll()
{
using (var dataContext = new SampleDBContext("ceit436DB"))
{
var ptx = (from r in dataContext.Categories select r);
return ptx.ToList();
}
}
public LibraryPasage getLibraryData(int id)
{
using (var dataContext = new SampleDBContext("ceit436DB"))
{
LibraryPasage ptx = dataContext.Categories.Where(x => x.id == id).First();
return ptx;
}
}
public void save(LibraryPasage passage)
{
using (var dataContext = new SampleDBContext("ceit436DB"))
{
dataContext.Categories.Add(passage);
dataContext.SaveChanges();
}
}
public void update(LibraryPasage passage)
{
using (var dataContext = new SampleDBContext("ceit436DB"))
{
dataContext.Categories.Update(passage);
dataContext.SaveChanges();
}
}
public void remove(LibraryPasage passage)
{
using (var dataContext = new SampleDBContext("ceit436DB"))
{
dataContext.Categories.Remove(passage);
dataContext.SaveChanges();
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace UltronCloud
{
class GDriveIntegration : Integration
{
public GDriveIntegration() : base("Google Drive")
{
}
}
}
|
using System;
using System;
using System.Collections;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine;
namespace Architecture.ViewModel
{
public interface ICommand
{
void Execute();
}
public interface ICommand<T> : ICommand
{
T Param { get; set; }
}
public interface ICommand<T1, T2> : ICommand<T1>
{
T2 Param2 { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using TemporaryEmploymentCorp.Helpers.ReportViewer;
using TemporaryEmploymentCorp.Models.Company;
using TemporaryEmploymentCorp.Models.Opening;
using TemporaryEmploymentCorp.Modules;
using TemporaryEmploymentCorp.Reports.Company;
namespace TemporaryEmploymentCorp.Reports.Opening
{
/// <summary>
/// Interaction logic for AllOpeningsReportWindow.xaml
/// </summary>
public partial class AllOpeningsReportWindow : Window
{
private ReportViewBuilder _reportView;
private string _titleFilter = string.Empty;
private readonly List<DataSetValuePair> _sources = new List<DataSetValuePair>();
public AllOpeningsReportWindow()
{
InitializeComponent();
_reportView = new ReportViewBuilder("TemporaryEmploymentCorp.Reports.Opening.AllOpeningsReport.rdlc", UpdateDatasetSource());
_reportView.RefreshDataSourceCallback = UpdateDatasetSource;
ReportContainer.Content = _reportView.ReportContent;
DataContext = this;
}
public ObservableCollection<DataAccess.EF.Company> Comps { get; } = new ObservableCollection<DataAccess.EF.Company>();
private IReadOnlyCollection<DataSetValuePair> UpdateDatasetSource()
{
_sources.Clear();
var openings = ViewModelLocatorStatic.Locator.OpeningModule.PrintOpenings.Select(c => c.Model);
_sources.Add(new DataSetValuePair("CompanyOpeningDataset", openings.Select(c => new CompanyOpening(c.Company, c, c.Qualification))));
// foreach (var opening in openings)
// {
// var company = opening.Company;
// Comps.Add(company);
// _sources.Add(new DataSetValuePair("CompanyDataset", Comps));
// }
return _sources;
}
public string TitleFilter
{
get { return _titleFilter; }
set
{
_titleFilter = value;
_reportView.ReportContent.UpdateDataSource(UpdateDatasetSource());
}
}
}
}
|
using NUnit.Framework;
using System;
namespace Logs.Models.Tests.NutritionTests
{
[TestFixture]
public class ConstructorTests
{
[Test]
public void TestConstructor_ShouldInitializeCorrectly()
{
// Arrange, Act
var nutrition = new Nutrition();
// Assert
Assert.IsNotNull(nutrition);
}
[TestCase(2222, 222, 111, 99, 3.17, 22, 7, "good", "d547a40d-c45f-4c43-99de-0bfe9199ff95")]
[TestCase(3333, 231, 771, 44, 5, 33, 6, "no notes", "99ae8dd3-1067-4141-9675-62e94bb6caaa")]
public void TestConstructor_ShouldSetCaloriesCorrectly(int calories, int protein, int carbs, int fats,
double water, int fiber, int sugar, string notes, string userId)
{
// Arrange,
var date = new DateTime(2, 3, 4);
// Act
var nutrition = new Nutrition(calories, protein, carbs, fats, water, fiber, sugar, notes, userId, date);
// Assert
Assert.AreEqual(calories, nutrition.Calories);
}
[TestCase(2222, 222, 111, 99, 3.17, 22, 7, "good", "d547a40d-c45f-4c43-99de-0bfe9199ff95")]
[TestCase(3333, 231, 771, 44, 5, 33, 6, "no notes", "99ae8dd3-1067-4141-9675-62e94bb6caaa")]
public void TestConstructor_ShouldSetProteinCorrectly(int calories, int protein, int carbs, int fats,
double water, int fiber, int sugar, string notes, string userId)
{
// Arrange,
var date = new DateTime(2, 3, 4);
// Act
var nutrition = new Nutrition(calories, protein, carbs, fats, water, fiber, sugar, notes, userId, date);
// Assert
Assert.AreEqual(protein, nutrition.Protein);
}
[TestCase(2222, 222, 111, 99, 3.17, 22, 7, "good", "d547a40d-c45f-4c43-99de-0bfe9199ff95")]
[TestCase(3333, 231, 771, 44, 5, 33, 6, "no notes", "99ae8dd3-1067-4141-9675-62e94bb6caaa")]
public void TestConstructor_ShouldSetCarbsCorrectly(int calories, int protein, int carbs, int fats,
double water, int fiber, int sugar, string notes, string userId)
{
// Arrange,
var date = new DateTime(2, 3, 4);
// Act
var nutrition = new Nutrition(calories, protein, carbs, fats, water, fiber, sugar, notes, userId, date);
// Assert
Assert.AreEqual(carbs, nutrition.Carbs);
}
[TestCase(2222, 222, 111, 99, 3.17, 22, 7, "good", "d547a40d-c45f-4c43-99de-0bfe9199ff95")]
[TestCase(3333, 231, 771, 44, 5, 33, 6, "no notes", "99ae8dd3-1067-4141-9675-62e94bb6caaa")]
public void TestConstructor_ShouldSetFatsCorrectly(int calories, int protein, int carbs, int fats,
double water, int fiber, int sugar, string notes, string userId)
{
// Arrange,
var date = new DateTime(2, 3, 4);
// Act
var nutrition = new Nutrition(calories, protein, carbs, fats, water, fiber, sugar, notes, userId, date);
// Assert
Assert.AreEqual(fats, nutrition.Fats);
}
[TestCase(2222, 222, 111, 99, 3.17, 22, 7, "good", "d547a40d-c45f-4c43-99de-0bfe9199ff95")]
[TestCase(3333, 231, 771, 44, 5, 33, 6, "no notes", "99ae8dd3-1067-4141-9675-62e94bb6caaa")]
public void TestConstructor_ShouldSetWaterCorrectly(int calories, int protein, int carbs, int fats,
double water, int fiber, int sugar, string notes, string userId)
{
// Arrange,
var date = new DateTime(2, 3, 4);
// Act
var nutrition = new Nutrition(calories, protein, carbs, fats, water, fiber, sugar, notes, userId, date);
// Assert
Assert.AreEqual(water, nutrition.WaterInLitres);
}
[TestCase(2222, 222, 111, 99, 3.17, 22, 7, "good", "d547a40d-c45f-4c43-99de-0bfe9199ff95")]
[TestCase(3333, 231, 771, 44, 5, 33, 6, "no notes", "99ae8dd3-1067-4141-9675-62e94bb6caaa")]
public void TestConstructor_ShouldSetFiberCorrectly(int calories, int protein, int carbs, int fats,
double water, int fiber, int sugar, string notes, string userId)
{
// Arrange,
var date = new DateTime(2, 3, 4);
// Act
var nutrition = new Nutrition(calories, protein, carbs, fats, water, fiber, sugar, notes, userId, date);
// Assert
Assert.AreEqual(fiber, nutrition.Fiber);
}
[TestCase(2222, 222, 111, 99, 3.17, 22, 7, "good", "d547a40d-c45f-4c43-99de-0bfe9199ff95")]
[TestCase(3333, 231, 771, 44, 5, 33, 6, "no notes", "99ae8dd3-1067-4141-9675-62e94bb6caaa")]
public void TestConstructor_ShouldSetSugarCorrectly(int calories, int protein, int carbs, int fats,
double water, int fiber, int sugar, string notes, string userId)
{
// Arrange,
var date = new DateTime(2, 3, 4);
// Act
var nutrition = new Nutrition(calories, protein, carbs, fats, water, fiber, sugar, notes, userId, date);
// Assert
Assert.AreEqual(sugar, nutrition.Sugar);
}
[TestCase(2222, 222, 111, 99, 3.17, 22, 7, "good", "d547a40d-c45f-4c43-99de-0bfe9199ff95")]
[TestCase(3333, 231, 771, 44, 5, 33, 6, "no notes", "99ae8dd3-1067-4141-9675-62e94bb6caaa")]
public void TestConstructor_ShouldSetNotesCorrectly(int calories, int protein, int carbs, int fats,
double water, int fiber, int sugar, string notes, string userId)
{
// Arrange,
var date = new DateTime(2, 3, 4);
// Act
var nutrition = new Nutrition(calories, protein, carbs, fats, water, fiber, sugar, notes, userId, date);
// Assert
Assert.AreEqual(notes, nutrition.Notes);
}
[TestCase(2222, 222, 111, 99, 3.17, 22, 7, "good", "d547a40d-c45f-4c43-99de-0bfe9199ff95")]
[TestCase(3333, 231, 771, 44, 5, 33, 6, "no notes", "99ae8dd3-1067-4141-9675-62e94bb6caaa")]
public void TestConstructor_ShouldSetUserIdCorrectly(int calories, int protein, int carbs, int fats,
double water, int fiber, int sugar, string notes, string userId)
{
// Arrange,
var date = new DateTime(2, 3, 4);
// Act
var nutrition = new Nutrition(calories, protein, carbs, fats, water, fiber, sugar, notes, userId, date);
// Assert
Assert.AreEqual(userId, nutrition.UserId);
}
[TestCase(2222, 222, 111, 99, 3.17, 22, 7, "good", "d547a40d-c45f-4c43-99de-0bfe9199ff95")]
[TestCase(3333, 231, 771, 44, 5, 33, 6, "no notes", "99ae8dd3-1067-4141-9675-62e94bb6caaa")]
public void TestConstructor_ShouldSetDateCorrectly(int calories, int protein, int carbs, int fats,
double water, int fiber, int sugar, string notes, string userId)
{
// Arrange,
var date = new DateTime(2, 3, 4);
// Act
var nutrition = new Nutrition(calories, protein, carbs, fats, water, fiber, sugar, notes, userId, date);
// Assert
Assert.AreEqual(date, nutrition.Date);
}
}
}
|
using AgeBaseTemplate.Core.ContentTypes;
namespace AgeBaseTemplate.UnitTests.ContentTypes
{
public class MockLanguagePage : MockBasePage<LanguagePage>
{
public MockHomePage HomePage { get; }
public MockConfigPage ConfigPage { get; }
public MockLanguagePage(bool includeHomePage = false, bool includeConfigPage = false)
: this(string.Empty, includeHomePage, includeConfigPage)
{
}
public MockLanguagePage(string name, bool includeHomePage = false, bool includeConfigPage = false)
: base(name)
{
SetProperty(l => l.LanguageName, name);
if (includeHomePage)
{
HomePage = new MockHomePage();
AddChild(HomePage.Object);
}
if (!includeConfigPage)
{
return;
}
ConfigPage = new MockConfigPage();
AddChild(ConfigPage.Object);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using CTCT.Util;
namespace CTCT.Components.EventSpot
{
/// <summary>
/// Order class
/// </summary>
[DataContract]
[Serializable]
public class Order : Component
{
/// <summary>
/// Constructor
/// </summary>
public Order()
{
this.Fees = new List<Fee>();
}
/// <summary>
/// Total
/// </summary>
[DataMember(Name = "total", EmitDefaultValue = true)]
public double Total { get; set; }
/// <summary>
/// Fees list
/// </summary>
[DataMember(Name = "fees", EmitDefaultValue = false)]
public IList<Fee> Fees { get; set; }
/// <summary>
/// Order id
/// </summary>
[DataMember(Name = "order_id", EmitDefaultValue = false)]
public string OrderId { get; set; }
/// <summary>
/// Currency type
/// </summary>
[DataMember(Name = "currency_type", EmitDefaultValue = false)]
public string CurrencyType { get; set; }
/// <summary>
/// String representation Order date
/// </summary>
[DataMember(Name = "order_date", EmitDefaultValue = false)]
private string OrderDateString { get; set; }
/// <summary>
/// Order date
/// </summary>
public DateTime? OrderDate
{
get { return this.OrderDateString.FromISO8601String(); }
set { this.OrderDateString = value.ToISO8601String(); }
}
}
}
|
using Assets.blackwhite_side_scroller.Scripts;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
public enum EndSlidingCondition
{
Fall,
Jump
}
public class SlidingCharacterController2D : MonoBehaviour
{
public float SlideSpeed = 1f;
public Transform ParticlesSpawnPoint;
public float ParticlesSpawnInterval;
private float _lastParticleSpawnTime;
public GameObject SlidingParticles;
private AudioSource _audio;
public AudioClip Sliding;
private void Awake()
{
_audio = GetComponent<AudioSource>();
}
void Update()
{
transform.position = Vector2.MoveTowards(transform.position, ((Vector2)transform.position + new Vector2(10, -10)), SlideSpeed * Time.deltaTime);
if (Time.time > _lastParticleSpawnTime + ParticlesSpawnInterval)
{
var particle = Instantiate(SlidingParticles, ParticlesSpawnPoint.position, Quaternion.Euler(new Vector3(0, 0, Random.Range(0, 360))));
}
GetComponent<Rigidbody2D>().velocity = Vector2.zero;
}
public void SlideReachedEnd()
{
GetComponent<CharacterController2D>().EndSliding(EndSlidingCondition.Fall);
}
void OnDisable()
{
Constants.MainCamera.GetComponent<SmoothFollow2D>().SetCameraConfiguration(CameraConfiguration.Default);
_audio.loop = false;
_audio.Stop();
}
void OnEnable()
{
Constants.MainCamera.GetComponent<SmoothFollow2D>().SetCameraConfiguration(CameraConfiguration.SlideSteep);
_audio.loop = true;
_audio.clip = Sliding;
_audio.Play();
}
public void Jump()
{
GetComponent<CharacterController2D>().EndSliding(EndSlidingCondition.Jump);
}
}
|
using System;
using System.IO;
using NUnit.Framework;
using Paralect.Schematra.Definitions;
namespace Paralect.Schematra.Test.Tests
{
[TestFixture]
public class ParserTest
{
[Test]
public void First()
{
}
public void DynamicTypeCreation()
{
}
}
} |
using Ninject;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.ModelBinding;
using System.Web.UI;
using System.Web.UI.WebControls;
using YouTubePlaylistsSystem.Data.Models;
using YouTubePlaylistsSystem.Data.Services.Contracts;
namespace YouTubePlaylistsSystem.Web
{
public partial class Categories : System.Web.UI.Page
{
[Inject]
public ICategoriesServices CategoriesServices { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
}
public Category lvCategories_GetData([QueryString]string id)
{
if (id == null)
{
return null;
}
return this.CategoriesServices.GetById(int.Parse(id)); ;
}
}
} |
using Avalonia.Controls;
using Avalonia.Markup.Xaml;
using Avalonia.Interactivity;
using Windore.Settings.Base;
using System;
namespace Windore.Settings.GUI
{
public class BoolSettingControl : UserControl
{
private CheckBox settingCheckBox;
private TextBlock settingCheckBoxName;
private ISettingsManager manager;
private string category;
private string name;
public BoolSettingControl()
{
throw new NotImplementedException("This constructor exists because AvaloniaUI requires it to exist. It's not supposed to be used");
}
public BoolSettingControl(string category, string name, ISettingsManager manager)
{
this.category = category;
this.name = name;
this.manager = manager;
InitializeComponent();
settingCheckBox.IsChecked = (bool)manager.GetSettingValue(category, name);
settingCheckBoxName.Text = name;
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
settingCheckBox = this.FindControl<CheckBox>("settingCheckBox");
settingCheckBoxName = this.FindControl<TextBlock>("settingCheckBoxName");
}
private void OnClick(object sender, RoutedEventArgs e)
{
manager.SetSettingValue(category, name, (bool)settingCheckBox.IsChecked);
}
}
} |
using System;
using System.Globalization;
using Xamarin.Forms;
namespace Kit.Forms.Converters
{
public class IsOfTypeConverter : IValueConverter
{
public bool IsReversed { get; set; }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is null)
{
return false;
}
if (parameter is not Type type)
{
return false;
}
if (IsReversed)
{
return value.GetType() != type;
}
return value.GetType() == type;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
} |
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;
namespace SchoolTest
{
[TestClass]
public class SchoolTest
{
[TestMethod]
public void SchoolConstructorTestName()
{
string schoolName = "Ivan Vazov";
School testSchools = new School(schoolName);
Assert.AreEqual(schoolName, testSchools.Name);
}
[TestMethod]
public void SchoolConstructorTestNameWithList()
{
string schoolName = "Ivan Vazov";
var courseList = new List<Course>();
School testSchools = new School(schoolName, courseList);
Assert.AreEqual(schoolName, testSchools.Name);
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void SchoolConstructorTestNullName()
{
new School(null);
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void SchoolConstrucotrTestEmptyName()
{
new School(string.Empty);
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void SchoolConstrucotrTestWhiteSpaceName()
{
new School(" ");
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void SchoolConstructorTestNullList()
{
string schoolName = "Math";
List<Course> courseList = null;
School testCourse = new School(schoolName, courseList);
}
[TestMethod]
public void SchoolAddCourseTest()
{
Course course = new Course("Math");
School testSchool = new School("Ivan Vazov");
testSchool.AddCourse(course);
Assert.IsTrue(testSchool.Courses.Count == 1);
Assert.AreEqual(course, testSchool.Courses[0]);
}
[TestMethod]
public void SchoolRemoveCourseTest()
{
Course course = new Course("Math");
School testSchool = new School("Ivan Vazov");
testSchool.AddCourse(course);
Assert.IsTrue(testSchool.Courses.Count == 1);
testSchool.RemoveCourse(course);
Assert.IsTrue(testSchool.Courses.Count == 0);
}
}
}
|
using APIEcommerce.Models;
using APIEcommerce.Requests;
using APIEcommerce.Responses;
namespace APIEcommerce.Mapper
{
public static class PedidoItemMapper
{
public static PedidoItem Mapper(PedidoItemRequest pedidoItem)
{
return new PedidoItem()
{
IdPedidoItem = pedidoItem.IdPedidoItem,
IdPedido = pedidoItem.IdPedido,
Produto = ProdutoMapper.Mapper(pedidoItem.Produto),
Quantidade = pedidoItem.Quantidade,
Valor = pedidoItem.Valor
};
}
public static PedidoItemResponse Mapper(PedidoItem pedidoItem)
{
return new PedidoItemResponse()
{
IdPedidoItem = pedidoItem.IdPedidoItem.ToString(),
IidPedido = pedidoItem.IdPedido.ToString(),
Produto = ProdutoMapper.Mapper(pedidoItem.Produto),
Quantidade = pedidoItem.Quantidade.ToString(),
Valor = pedidoItem.Valor.ToString()
};
}
}
}
|
using System.Collections.Generic;
using System.Threading.Tasks;
using Entities;
using MySql.Data.MySqlClient;
using Dapper;
using System.Linq;
namespace DataAccess
{
public class CitaDAL:Conexion
{
// CITAS
public async Task<List<Cita>> GetCitasAsync()
{
MySqlConnection MiConexion = AbrirConexionSql();
string sql = "select * from citas";
try
{
List<Cita> ListaCitas = null;
if (MiConexion != null)
{
ListaCitas = (await MiConexion.QueryAsync<Cita>(sql)).ToList();
}
return ListaCitas;
}
catch
{
return null;
}
finally
{
if (MiConexion.State == System.Data.ConnectionState.Open)
{
MiConexion.Close();
}
}
}
public async Task<int> GenerarCitaAsync(Cita cita)
{
MySqlConnection conexion = AbrirConexionSql();
string sql = "INSERT into citas (IdCita, Dni, Nombre, Apellido, CodEspecialidad, CMP, TipoCita, EstadoCita) values (@IdCita, @Dni, @Nombre, @Apellido, @CodEspecialidad, @CMP, @TipoCita, @EstadoCita)";
int FilasAfectadas = 0;
try
{
if (conexion != null)
{
FilasAfectadas = await conexion.ExecuteAsync(sql, new {IdCita = cita.IdCita, Dni = cita.Dni, Nombre = cita.Nombre, Apellido = cita.Apellido, CodEspecialidad = cita.CodEspecialidad, CMP = cita.CMP, TipoCita = cita.TipoCita, EstadoCita = cita.EstadoCita });
}
return FilasAfectadas;
}
catch
{
return FilasAfectadas;
}
finally
{
if (conexion.State == System.Data.ConnectionState.Open) { conexion.Close(); }
}
}
public async Task<int> EliminarCitaAsync(string IdCita)
{
MySqlConnection conexion = AbrirConexionSql();
string sql = "Delete from citas where IdCita = @IdCita";
int FilasAfectadas = 0;
try
{
if (conexion != null)
{
FilasAfectadas = await conexion.ExecuteAsync(sql, new { IdCita = IdCita });
}
return FilasAfectadas;
}
catch
{
return FilasAfectadas;
}
finally
{
if (conexion.State == System.Data.ConnectionState.Open) { conexion.Close(); }
}
}
}
}
|
using AutoMapper;
namespace MertricAgentServices.Mapper
{
public interface IMetricMapper
{
/// <summary>
/// Провайдер конфигурации для Mapper
/// </summary>
IConfigurationProvider ConfigurationProvider { get; }
/// <summary>
/// Конвертирует объекб в объект типа <typeparamref name="T"/>
/// </summary>
/// <typeparam name="T">Тип, в который конвертируется объект</typeparam>
/// <param name="source">Исходный объект</param>
/// <returns>Результирующий объект</returns>
T Map<T>(object source);
/// <summary>
/// Конвертирует объект в объект типа <typeparamref name="TDestination"/>
/// </summary>
/// <typeparam name="TSource">Исходный тип</typeparam>
/// <typeparam name="TDestination">Тип, в который конвертируется объект</typeparam>
/// <param name="source">Исходный объект</param>
/// <param name="destination">Целевой объект</param>
void Map<TSource, TDestination>(TSource source, TDestination destination);
}
}
|
using UnityEngine;
using System.Collections;
public class TeleportPipeEntrance : MonoBehaviour {
[SerializeField]
TeleportPipeExit teleportPipeExit;
void OnTriggerEnter(Collider other)
{
if (other.tag == "Player")
{
teleportPipeExit.TeleportObject(other.gameObject);
}
}
}
|
using BSEWalletClient.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BSEWalletClient.BAL.Interface
{
public interface ICustomerRepository
{
List<Customer> Get();
void Add(Customer card);
}
}
|
#nullable disable
namespace SPDataRepository.Data.Entities
{
public record Product : EntityBase
{
public string Name { get; set; }
public virtual Brand Brand { get; set; }
}
}
|
using UnityEngine;
using UnityEngine.UI;
public class UpdateEnergyBarText : MonoBehaviour
{
#region Fields
private Text text;
[SerializeField]
private EEntityCategory entityCategory;
#endregion
#region Unity Methods
void Awake()
{
this.text = GetComponent<Text>();
if (EEntityCategory.Player == this.entityCategory)
ServiceContainer.Instance.EventManagerParamsFloatAndFloat.SubcribeToEvent(EEventParamsFloatAndFloat.PlayerEnergyIsUpdate, this.UpdateEnergyBar);
else
ServiceContainer.Instance.EventManagerParamsFloatAndFloat.SubcribeToEvent(EEventParamsFloatAndFloat.EnemyLifeIsUpdate, this.UpdateEnergyBar);
}
#endregion
#region Behaviour Methods
private void UpdateEnergyBar(float currentEnergy, float maximumEnergy)
{
this.text.text = string.Format("{0}%", Mathf.CeilToInt(((currentEnergy / maximumEnergy) * 100.0f)).ToString());
}
#endregion
} |
public interface IList<T> where T : new()
{
bool Get(int x, out T y);
bool Set(int x, T elemento);
void Push(T elemento);
int Length();
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Threading.Tasks;
namespace ProjectEuler
{
public class FactorialDigitSum : ISolution
{
public void Run()
{
checked
{
var factorial = Enumerable.Range(1, 100).Select(x => new BigInteger(x)).Aggregate(new BigInteger(1), (x, y) => x * y);
var sumOfDigits = MathHelper.Digits(factorial).Sum();
Result = String.Format("{0} {1}", factorial, sumOfDigits);
}
}
public object Result { get; private set; }
}
}
|
using System;
using Relocation.Base;
using Relocation.Base.UI;
using Relocation.Com;
using Relocation.Com.Tools;
using Relocation.Data;
namespace Relocation
{
public partial class PwdModify : BaseForm
{
public PwdModify()
: base()
{
Initialize();
}
public PwdModify(Session s)
: base(s)
{
Initialize();
}
private void Initialize()
{
InitializeComponent();
this.password.Tag = new ControlTag(null, new ValidatorInfo(true));
this.confirmPassword.Tag = new ControlTag(null, new ValidatorInfo(true));
this.newPassword.Tag = new ControlTag(null, new ValidatorInfo(true));
}
private void submit_Click(object sender, EventArgs e)
{
if (!this.ValidatorAllControls())
return;
User u = this.Session.DataModel.getUserByNameAndPassword(Session.User.name, this.password.Text);
if (u == null)
{
MyMessagebox.Show("旧密码输入错误!");
this.password.Text = "";
this.password.Focus();
return;
} else if (!Validator.length(this.newPassword.Text, 6, 12))
{
MyMessagebox.Show("密码长度为6-12位!");
this.newPassword.Text = "";
this.newPassword.Focus();
return;
}
if (!this.confirmPassword.Text.Equals(this.newPassword.Text))
{
MyMessagebox.Show("两次密码输入不一致!");
this.confirmPassword.Text = "";
this.confirmPassword.Focus();
return;
}
u.password = this.newPassword.Text;
if (this.Session.DataModel.Save(u) < 1)
{
MyMessagebox.Show("密码修改失败!");
return;
} else
{
MyMessagebox.Show("密码修改成功!");
}
this.Close();
}
}
}
|
using System;
using System.Configuration;
using System.Linq;
using System.ServiceModel;
using ServiceConfiguration = ServiceConfigurationSection.ServiceConfigurationSection;
namespace UserStorageApp
{
// In case of AddressAccessDeniedException run the command below as an administrator:
// netsh http add urlacl url=<endpoint> user=<username>
public class Program
{
public static void Main(string[] args)
{
var serviceConfiguration = (ServiceConfiguration)ConfigurationManager.GetSection("serviceConfiguration");
using (var host = new ServiceHost(MyDiagnostics.Create(serviceConfiguration)))
{
host.SmartOpen();
var clientDomain = AppDomain.CreateDomain("ClientDomain");
var clientType = typeof(ClientDomainAction);
var clientAction = (ClientDomainAction)clientDomain.CreateInstanceAndUnwrap(
clientType.Assembly.FullName,
clientType.FullName);
clientAction.Run();
var client = clientAction.Client;
client.Run();
Console.WriteLine("Service \"{0}\" that is implemented by \"{1}\" class is available on \"{2}\" endpoint.", host.Description.Name, host.Description.ServiceType.FullName, host.BaseAddresses.First());
Console.WriteLine("Press <Enter> to stop the service.");
Console.ReadLine();
host.Close();
}
}
}
}
|
using UnityEngine.EventSystems;
using UnityEngine.UI;
namespace HT.Framework
{
/// <summary>
/// 可绑定的Float类型
/// </summary>
public sealed class BindableFloat : BindableType<float>
{
public static implicit operator float(BindableFloat bFloat)
{
return bFloat.Value;
}
public static implicit operator string(BindableFloat bFloat)
{
return bFloat.Value.ToString("F4");
}
/// <summary>
/// 数据值
/// </summary>
public override float Value
{
get
{
return base.Value;
}
set
{
if (_value.Approximately(value))
return;
_value = value;
_onValueChanged?.Invoke(_value);
}
}
public BindableFloat()
{
Value = 0f;
}
public BindableFloat(float value)
{
Value = value;
}
/// <summary>
/// 绑定控件
/// </summary>
/// <param name="control">绑定的目标控件</param>
protected override void Binding(UIBehaviour control)
{
base.Binding(control);
if (control is InputField)
{
InputField inputField = control as InputField;
inputField.text = Value.ToString();
inputField.onValueChanged.AddListener((value) =>
{
float newValue;
if (float.TryParse(value, out newValue))
{
Value = newValue;
}
});
_onValueChanged += (value) => { if (inputField) inputField.text = value.ToString(); };
}
else if (control is Text)
{
Text text = control as Text;
text.text = Value.ToString();
_onValueChanged += (value) => { if (text) text.text = value.ToString(); };
}
else if (control is Slider)
{
Slider slider = control as Slider;
slider.value = Value;
slider.onValueChanged.AddListener((value) => { Value = value; });
_onValueChanged += (value) => { if (slider) slider.value = value; };
}
else if (control is Scrollbar)
{
Scrollbar scrollbar = control as Scrollbar;
scrollbar.value = Value;
scrollbar.onValueChanged.AddListener((value) => { Value = value; });
_onValueChanged += (value) => { if (scrollbar) scrollbar.value = value; };
}
else
{
Log.Warning(string.Format("数据驱动器:数据绑定失败,当前不支持控件 {0} 与 BindableFloat 类型的数据绑定!", control.GetType().FullName));
}
}
}
} |
using UnityEngine;
using UnityEditor;
using System;
using System.IO;
using System.Text;
using System.Reflection;
using UnityEditor.Callbacks;
public static class AutoCreateViewClass
{
static string tempFilePath = "Temp/__AutoCreateViewClass__";
[MenuItem("Tools/Auto Create View Class from Seleced GameObject/MonoBehaviour")]
private static void Fabulous ()
{
Create("MonoBehaviour");
}
[MenuItem("Tools/Auto Create View Class from Seleced GameObject/Interaction View")]
private static void Marvelous ()
{
Create("InteractionView");
}
private static void Create (string base_class_name)
{
if (null == Selection.gameObjects) {
return;
}
if (1 != Selection.gameObjects.Length) {
return;
}
GameObject target = Selection.gameObjects[0];
string class_name = target.gameObject.name + "View";
StringBuilder sb = new StringBuilder();
sb.AppendLine("using UnityEngine;");
sb.AppendLine("using System.Collections;");
sb.AppendLine("using System.Collections.Generic;");
sb.AppendLine("");
sb.AppendLine("using Engine.Platforms.Unity.NGUI;");
sb.AppendLine("");
sb.AppendLine("namespace Game");
sb.AppendLine("{");
sb.AppendLine("\tpublic class " + class_name + " : " + base_class_name);
sb.AppendLine("\t{");
sb.AppendLine("\t\t");
UIWidget[] wi = target.GetComponentsInChildren<UIWidget>(true);
for (int i = 0; i < wi.Length; i++) {
sb.AppendLine("\t\t[SerializeField] " + wi[i].GetType() + " _" + wi[i].gameObject.name + ";");
}
UIPanel[] pa = target.GetComponentsInChildren<UIPanel>(true);
for (int i = 0; i < pa.Length; i++) {
sb.AppendLine("\t\t[SerializeField] " + pa[i].GetType() + " _" + pa[i].gameObject.name + ";");
}
sb.AppendLine("\t\t");
sb.AppendLine("\t\tvoid Awake() {");
sb.AppendLine("\t\t}");
sb.AppendLine("\t\t");
sb.AppendLine("\t\tvoid Start() {");
sb.AppendLine("\t\t}");
sb.AppendLine("\t\t");
sb.AppendLine("\t\tvoid Update() {");
sb.AppendLine("\t\t}");
sb.AppendLine("\t\t");
sb.AppendLine("\t\tvoid OnDestroy() {");
sb.AppendLine("\t\t}");
sb.AppendLine("\t\t");
sb.AppendLine("\t}");
sb.AppendLine("}");
File.WriteAllText(tempFilePath, class_name, Encoding.UTF8);
File.WriteAllText("Assets/" + class_name + ".cs", sb.ToString(), Encoding.UTF8);
AssetDatabase.ImportAsset("Assets/" + class_name + ".cs");
AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate);
}
public static GameObject FindDeep (GameObject self, string name)
{
var children = self.GetComponentsInChildren<Transform>(false);
foreach (var transform in children) {
if (transform.name == name) {
return transform.gameObject;
}
}
return null;
}
[DidReloadScripts]
private static void Log ()
{
if (File.Exists(tempFilePath)) {
StreamReader reader = new StreamReader(tempFilePath, Encoding.UTF8);
string scriptName = reader.ReadLine();
reader.Close();
Type type = GetTypeByClassName(scriptName);
Component component = Selection.gameObjects[0].AddComponent(type);
File.Delete(tempFilePath);
FieldInfo[] fi = type.GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly);
for (int i = 0; i < fi.Length; i++) {
string field_name = fi[i].Name.TrimStart('_');
fi[i].SetValue(component, FindDeep(component.gameObject, field_name).GetComponent(fi[i].FieldType));
}
}
}
public static Type GetTypeByClassName (string class_name)
{
foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()) {
foreach (Type type in assembly.GetTypes()) {
if (type.Name == class_name) {
return type;
}
}
}
return null;
}
}
|
using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
public class AtCoderValidator : NormalValidator
{
public AtCoderValidator(string ans) : base(ans) { }
public override bool Equal(string a, string b)
{
var sharpedA = string.Join("\n", a.Trim((char)0x0d, (char)0x0a).Split('\n').Select(x => x.Trim()).Where(x => x.Length != 0));
var sharpedB = string.Join("\n", b.Trim((char)0x0d, (char)0x0a).Split('\n').Select(x => x.Trim()).Where(x => x.Length != 0));
return sharpedA == sharpedB;
}
}
|
// --------------------------------
// <copyright file="SearchCarModel.cs" >
// © 2013 KarzPlus Inc.
// </copyright>
// <author>JDuverge</author>
// <summary>
// SearchCarModel Search Entity Object.
// </summary>
// ---------------------------------
using System;
namespace KarzPlus.Entities
{
/// <summary>
/// SearchCarModel search entity object.
/// </summary>
[Serializable]
public class SearchCarModel
{
/// <summary>
/// Gets or sets ModelId.
/// </summary>
public int? ModelId { get; set; }
/// <summary>
/// Gets or sets MakeId.
/// </summary>
public int? MakeId { get; set; }
/// <summary>
/// Gets or sets Name.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Gets or sets CarImage.
/// </summary>
public byte[] CarImage { get; set; }
/// <summary>
/// Gets or sets Deleted.
/// </summary>
public bool? Deleted { get; set; }
/// <summary>
/// Initializes a new instance of the SearchCarModel class.
/// </summary>
public SearchCarModel()
{
ModelId = null;
MakeId = null;
Name = null;
CarImage = null;
Deleted = false;
}
}
}
|
namespace Eventos.IO.Services.Api.ViewModels
{
public class EstadoViewModel
{
public string UF { get; set; }
public string Nome { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using JsonData;
using NUnit.Framework;
namespace JsonData.Elements.Tests
{
[TestFixture]
public class JsonObjectTests
{
#region Base JsonObject
internal static List<string> keys = new List<string>() { "oneKey", "nested.key", "two.nested.keys" } ;
internal static List<object> values = new List<object>() { "value", 1, new List<object>() { 1,2,3} };
internal static JsonObject json= JsonObject.ByKeysAndValues(keys, values, false, JsonOption.None);
internal static JsonObject jsonNested = JsonObject.ByKeysAndValues(keys, values, true, JsonOption.None);
#endregion
[Test]
[Category("UnitTests")]
public static void ByKeysAndValuesTest()
{
Assert.AreEqual(new List<string>() { "oneKey", "nested", "two"}, jsonNested.Keys);
Assert.AreEqual(keys, json.Keys);
Assert.AreEqual(values, json.Values);
Assert.AreEqual(3, jsonNested.Size);
}
[Test]
[Category("UnitTests")]
public static void GetValueByKeyTest()
{
Assert.AreEqual("value", JsonObject.GetValueByKey(jsonNested,"oneKey"));
Assert.AreEqual(1, JsonObject.GetValueByKey(json,"nested.key", false));
Assert.AreEqual(1, JsonObject.GetValueByKey(jsonNested,"nested.key"));
Assert.AreEqual(new List<object>() { 1, 2, 3 }, JsonObject.GetValueByKey(jsonNested,"two.nested.keys"));
}
[Test]
[Category("UnitTests")]
public static void NestedTest()
{
List<string> k = new List<string>() { "nested.one", "nested.two" };
List<object> v = new List<object>() { 1, 2 };
JsonObject jsonNested = JsonObject.ByKeysAndValues(k, v, true, JsonOption.None);
Assert.IsInstanceOf(typeof(JsonObject), JsonObject.GetValueByKey(jsonNested,"nested"));
}
[Test]
[Category("UnitTests")]
public static void FilterByKeyAndValueTest()
{
List<string> keys = new List<string>() { "one", "two", "three" };
List<JsonObject> jsonObjects = new List<JsonObject>()
{
JsonObject.ByKeysAndValues(keys, new List<object>(){ 1, "dos", "tres" }, false, JsonOption.None),
JsonObject.ByKeysAndValues(keys, new List<object>(){ 2, "uno", 3}, false, JsonOption.None),
JsonObject.ByKeysAndValues(new List<string>(){"uno", "dos"}, new List<object>(){ 1, 2}, false, JsonOption.None)
};
var noKeyFound = JsonObject.FilterByKeyAndValue(jsonObjects, "eins", 1);
Assert.AreEqual(0, noKeyFound["in"].Count);
Assert.AreEqual(3, noKeyFound["out"].Count);
var oneMatch = JsonObject.FilterByKeyAndValue(jsonObjects, "one", 1);
Assert.AreEqual(1, oneMatch["in"].Count);
Assert.AreEqual(2, oneMatch["out"].Count);
var stringPartialMatch = JsonObject.FilterByKeyAndValue(jsonObjects, "two", "o");
Assert.AreEqual(2, stringPartialMatch["in"].Count);
Assert.AreEqual(1, stringPartialMatch["out"].Count);
var stringCaseMatch = JsonObject.FilterByKeyAndValue(jsonObjects, "three", "TRES");
Assert.AreEqual(1, stringCaseMatch["in"].Count);
Assert.AreEqual(2, stringCaseMatch["out"].Count);
}
[Test]
[Category("UnitTests")]
public static void AddCombineTest()
{
var keys = new List<string>() { "string", "string", "int", "int", "list", "list" };
var values = new List<object>() { "first", "second", 1, 2, new List<object>() { "start" }, 99 };
JsonObject json = JsonObject.ByKeysAndValues(keys, values, false, JsonOption.Combine);
Assert.AreEqual(3, json.Size);
//json.Values.ForEach(v => Assert.IsTrue(v is IList<object>));
Assert.Pass("All values are lists");
}
[Test]
[Category("UnitTests")]
public static void RemoveTest()
{
var keys = new List<string>() { "first", "second", "nested.first", "nested.second" };
var values = new List<object>() { 1, 2, 3.1, 3.2 };
JsonObject json = JsonObject.ByKeysAndValues(keys, values, true, JsonOption.None);
JsonObject removeAll = JsonObject.Remove(json,keys, true);
Assert.AreEqual(0, removeAll.Size);
Assert.AreEqual(3, json.Size);
JsonObject removeSingle = JsonObject.Remove(json, new List<string>() { "first", "second" }, true);
Assert.AreEqual(1, removeSingle.Size);
Assert.AreEqual(3, json.Size);
JsonObject removeNested = JsonObject.Remove(json, new List<string>() { "nested.first" }, true);
Assert.AreEqual(3, removeNested.Size);
Assert.IsInstanceOf(typeof(int), removeNested.Values[0]);
Assert.IsInstanceOf(typeof(JsonObject), removeNested.Values[2]);
}
}
} |
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using WeatherWeb.Models;
using WeatherWeb.Service;
namespace WeatherWeb.ApiControllers
{
[Route("api/[controller]")]
public class WeatherController : Controller
{
private IOptions<AppSettings> _settings;
public WeatherController(IOptions<AppSettings> settings)
{
_settings = settings;
}
[HttpGet]
public async Task<IActionResult> Get()
{
var service = new AzureService(_settings);
List<Weather> history = await service.ReceiveMessagesAsync();
return new ObjectResult(history);
}
}
}
|
using AutoMapper;
using Umbraco.Core.Models;
using Umbraco.Web.Models.ContentEditing;
namespace Umbraco.Web.Models.Mapping
{
internal class TemplateMapperProfile : Profile
{
public TemplateMapperProfile()
{
CreateMap<ITemplate, TemplateDisplay>()
.ForMember(dest => dest.Notifications, opt => opt.Ignore());
CreateMap<TemplateDisplay, Template>()
.IgnoreEntityCommonProperties()
.ForMember(dest => dest.Path, opt => opt.Ignore())
.ForMember(dest => dest.VirtualPath, opt => opt.Ignore())
.ForMember(dest => dest.Path, opt => opt.Ignore())
.ForMember(dest => dest.MasterTemplateId, opt => opt.Ignore()) // ok, assigned when creating the template
.ForMember(dest => dest.IsMasterTemplate, opt => opt.Ignore())
.ForMember(dest => dest.HasIdentity, opt => opt.Ignore());
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Entidades
{
public class Clientes : Personas
{
[Key]
public int IdCliente { get; set; }
public decimal LimiteCredito { get; set; }
public decimal LimiteVenta { get; set; }
public decimal Balance { get; set; }
public Clientes()
{
IdCliente = 0;
LimiteCredito = 0;
LimiteVenta = 0;
Balance = 0;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BusinessEntity
{
public class eSinhVien
{
private int MaSV;
private string Ten;
private string Khoa;
private string Lop;
private string ChuyenNganh;
public int MaSV1 { get => MaSV; set => MaSV = value; }
public string Ten1 { get => Ten; set => Ten = value; }
public string Khoa1 { get => Khoa; set => Khoa = value; }
public string Lop1 { get => Lop; set => Lop = value; }
public string ChuyenNganh1 { get => ChuyenNganh; set => ChuyenNganh = value; }
public eSinhVien(int maSV, string ten, string khoa, string lop, string chuyenNganh)
{
MaSV = maSV;
Ten = ten;
Khoa = khoa;
Lop = lop;
ChuyenNganh = chuyenNganh;
}
public eSinhVien()
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
namespace WebService.MVC4.Controllers
{
public class ToUpperController : ApiController
{
public string Get(string input)
{
return input.ToUpper();
}
}
}
|
using System;
namespace Singleton
{
public class UsageExamples
{
public void UsingReadonlySingleton()
{
var proxyUri = $"{MyAppConfiguration.Instance.ProxyHost}:{MyAppConfiguration.Instance.ProxyPort}";
Console.Write($"Proxy address: {proxyUri}");
}
public void UsingPubSub()
{
// Subscribing to Loading event
PubSubAsSingleton.Instance.LoadingEvent += (sender, args) =>
{
if (args.LoadedProgress >= 1)
{
Console.WriteLine($"Loaded!");
}
else
{
Console.WriteLine($"Loading... {args.LoadedProgress * 100}%");
}
};
// Publishing Loading events
for (var i = 0; i <= 100; i++)
{
PubSubAsSingleton.Instance.RaiseLoadingEvent(this, i / 100.0);
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace Herencia
{
public class Coche : Vehiculo
{
public string Traccion { get; set; }
public Coche(string marca, string modelo, string traccion) : base(marca, modelo)
{
Traccion = traccion;
}
public override void Arrancar()
{
Console.WriteLine("Arrancar coche");
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
namespace TAiO.Subgraphs.Models
{
public class Graph<T>
{
public Dictionary<T, HashSet<T>> Neighbors { get; } = new Dictionary<T, HashSet<T>>();
public HashSet<T> Vertices { get; private set; }
public Graph(IEnumerable<T> vertices, IEnumerable<Tuple<T, T>> edges)
{
Vertices = new HashSet<T>(vertices);
foreach(var vertex in vertices)
AddVertex(vertex);
foreach(var edge in edges)
AddEdge(edge);
}
public void AddVertex(T vertex)
{
Neighbors[vertex] = new HashSet<T>();
}
public void AddEdge(Tuple<T, T> edge)
{
if (Neighbors.ContainsKey(edge.Item1) && Neighbors.ContainsKey(edge.Item2))
{
Neighbors[edge.Item1].Add(edge.Item2);
Neighbors[edge.Item2].Add(edge.Item1);
}
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SniperBullet : MonoBehaviour
{
private int damage;
private Vector3 direction;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
}
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.name == "Rifle" || collision.gameObject.name == "Sniper")
{
}
else
{
Destroy(gameObject);
}
}
public void setDamage(int dmg)
{
damage = dmg;
}
public int getDamage()
{
return damage;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
namespace Gensokyo.Components.Colors
{
public abstract partial class ColorBar : Control, IColorBar
{
public const string PART_Item1Name = "PART_Item1";
public const string PART_Item2Name = "PART_Item2";
public const string PART_Item3Name = "PART_Item3";
public const string PART_ItemValue1Name = "PART_ItemValue1";
public const string PART_ItemValue2Name = "PART_ItemValue2";
public const string PART_ItemValue3Name = "PART_ItemValue3";
static ColorBar()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(ColorBar), new FrameworkPropertyMetadata(typeof(ColorBar)));
BrushPropertyKey = DependencyProperty.RegisterReadOnly("Brush", typeof(Brush), typeof(ColorBar), new PropertyMetadata(new SolidColorBrush(System.Windows.Media.Colors.Red)));
ColorPropertyKey = DependencyProperty.RegisterReadOnly("Color", typeof(Color), typeof(ColorBar), new PropertyMetadata(System.Windows.Media.Colors.Red));
BrushProperty = BrushPropertyKey.DependencyProperty;
ColorProperty = ColorPropertyKey.DependencyProperty;
}
private Slider PART_Item1;
private Slider PART_Item2;
private Slider PART_Item3;
private TextBox PART_ItemValue1;
private TextBox PART_ItemValue2;
private TextBox PART_ItemValue3;
private readonly DispatcherTimer _Timer;
private bool _isColorChanged;
public ColorBar()
{
_Timer = new DispatcherTimer(TimeSpan.FromMilliseconds(16), DispatcherPriority.Normal, (o, e) =>
{
if (_isColorChanged)
{
_isColorChanged = false;
OnColorChanged(PART_Item1?.Value ?? 0,
PART_Item2?.Value ?? 100,
PART_Item3?.Value ?? 100);
}
}, Dispatcher);
_Timer.Start();
this.Unloaded += (o, e) => {
_Timer.Stop();
PART_Item1.ValueChanged -= OnFireColorChanged;
PART_Item2.ValueChanged -= OnFireColorChanged;
PART_Item3.ValueChanged -= OnFireColorChanged;
PART_ItemValue1.TextChanged -= OnValueChanged;
PART_ItemValue2.TextChanged -= OnValueChanged;
PART_ItemValue3.TextChanged -= OnValueChanged;
};
}
protected void OnFireColorChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
_isColorChanged = true;
}
protected virtual void OnColorChanged(double item1Val,double item2Value,double item3Value)
{
}
protected void OnValueChanged(object sender, TextChangedEventArgs e)
{
bool b1 = false,b2 = false,b3 = false;
if (double.TryParse(PART_ItemValue1.Text, out var val1))
{
PART_Item1.Value = val1;
b1 = true;
}
if (double.TryParse(PART_ItemValue2.Text, out val1))
{
PART_Item2.Value = val1;
b2 = true;
}
if (double.TryParse(PART_ItemValue3.Text, out val1))
{
PART_Item3.Value = val1;
b3 = true;
}
_isColorChanged = b1 || b2 || b3;
}
public override void OnApplyTemplate()
{
PART_Item1 = GetTemplateChild(PART_Item1Name) as Slider;
PART_Item2 = GetTemplateChild(PART_Item2Name) as Slider;
PART_Item3 = GetTemplateChild(PART_Item3Name) as Slider;
PART_ItemValue1 = GetTemplateChild(PART_ItemValue1Name) as TextBox;
PART_ItemValue2 = GetTemplateChild(PART_ItemValue2Name) as TextBox;
PART_ItemValue3 = GetTemplateChild(PART_ItemValue3Name) as TextBox;
PART_Item1.ValueChanged += OnFireColorChanged;
PART_Item2.ValueChanged += OnFireColorChanged;
PART_Item3.ValueChanged += OnFireColorChanged;
PART_ItemValue1.TextChanged += OnValueChanged;
PART_ItemValue2.TextChanged += OnValueChanged;
PART_ItemValue3.TextChanged += OnValueChanged;
}
}
}
|
using System;
namespace Lab3
{
public class Point
{
int x;
int y;
public void SetX(int x)
{
this.x = x;
}
public int GetX()
{
return x;
}
public void SetY(int y)
{
this.y = y;
}
public int GetY()
{
return y;
}
public Point() { }
public Point(int x, int y)
{
this.x = x;
this.y = y;
}
public double GetDistanceTo(Point comparisonPoint)
{
double xDistance = comparisonPoint.x - x;
double yDistance = comparisonPoint.y - y;
return Math.Sqrt(xDistance * xDistance + yDistance * yDistance);
}
}
}
|
using PointOfSalesV2.Entities;
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
namespace PointOfSalesV2.Repository
{
public class InvoiceDetailRepository : Repository<InvoiceDetail>, IInvoiceDetailRepository
{
public InvoiceDetailRepository(MainDataContext context) : base(context)
{
}
public IEnumerable<InvoiceDetail> GetByInvoiceId(long invoiceId)
{
return _Context.InvoicesDetails.Where(x => x.Active == true && x.InvoiceId == invoiceId);
}
public IEnumerable<InvoiceDetail> GetByProductId(long productId)
{
return _Context.InvoicesDetails.Where(x => x.Active == true && x.ProductId == productId);
}
public IEnumerable<InvoiceDetail> GetChildren(long parentId)
{
return _Context.InvoicesDetails.Where(x => x.Active == true && x.ParentId==parentId);
}
public IEnumerable<InvoiceDetail> GetInvoiceParentsDetails(long invoiceId)
{
return _Context.InvoicesDetails.Where(x => x.Active == true && x.InvoiceId == invoiceId && x.ParentId==null);
}
}
}
|
using System.Threading.Tasks;
using Remora.Discord.API.Abstractions.Objects;
using Remora.Discord.API.Abstractions.Rest;
using Remora.Discord.Core;
namespace DingleTheBotReboot.Services;
public class CommonMethodsService : ICommonMethodsService
{
public async Task<ulong> NukeChannelAsync(IDiscordRestGuildAPI guildApi,
IDiscordRestChannelAPI channelApi,
Snowflake channelId,
Snowflake guildId,
IUser user)
{
var getChannelReply = await channelApi.GetChannelAsync(channelId);
if (!getChannelReply.IsSuccess) return 0;
var channel = getChannelReply.Entity;
var channelCreateReply = await guildApi.CreateGuildChannelAsync(
guildId,
channel.Name.Value,
ChannelType.GuildText,
channel.Topic,
position: channel.Position,
permissionOverwrites: channel.PermissionOverwrites,
parentID: channel.ParentID.HasValue ? channel.ParentID.Value.Value : default,
isNsfw: channel.IsNsfw,
reason: "From nuke");
await channelApi.DeleteChannelAsync(channelId,
$"Nuked by {user.Username}#{user.Discriminator}");
return channelCreateReply.IsSuccess ? channelCreateReply.Entity.ID.Value : 0;
}
} |
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using Asset.Models.Library.EntityModels.OrganizationModels;
namespace Asset.Models.Library.EntityModels.HrModels
{
public class Employee
{
[Required]
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public int OrganizationId { get; set; }
[ForeignKey("OrganizationId")]
public virtual Organization Organization { get; set; }
public int BranchId { get; set; }
[ForeignKey("BranchId")]
public virtual Branch Branch { get; set; }
public int DepartmentId { get; set; }
[ForeignKey("DepartmentId")]
public virtual Department Department { get; set; }
public int DesignationId { get; set; }
[ForeignKey("DesignationId")]
public virtual Designation Designation { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string ContactNo { get; set; }
public string Email { get; set; }
public string Address { get; set; }
public byte[] Image { get; set; }
public string Code { get; set; }
}
}
|
namespace ServiceBase.Events
{
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
/// <summary>
/// Default implementation of the event service.
/// Write events raised to the log.
/// </summary>
public class DefaultEventService : IEventService
{
/// <summary>
/// The options
/// </summary>
private readonly EventOptions eventOptions;
/// <summary>
/// The <see cref="IHttpContextAccessor"/>
/// </summary>
private readonly IHttpContextAccessor httpContextAccessor;
/// <summary>
/// The <see cref="IDateTimeAccessor"/>
/// </summary>
private readonly IDateTimeAccessor dateTimeAccessor;
/// <summary>
/// The sink
/// </summary>
private readonly IEventSink eventSink;
/// <summary>
/// Initializes a new instance of the
/// <see cref="DefaultEventService"/> class.
/// </summary>
/// <param name="options">The options.</param>
/// <param name="context">The context.</param>
/// <param name="sink">The sink.</param>
public DefaultEventService(
EventOptions eventOptions,
IHttpContextAccessor httpContextAccessor,
IDateTimeAccessor dateTimeAccessor,
IEventSink eventSink)
{
this.eventOptions = eventOptions;
this.httpContextAccessor = httpContextAccessor;
this.dateTimeAccessor = dateTimeAccessor;
this.eventSink = eventSink;
}
/// <summary>
/// Raises the specified event.
/// </summary>
/// <param name="evt">The event.</param>
/// <returns></returns>
/// <exception cref="System.ArgumentNullException">evt</exception>
public async Task RaiseAsync(Event evt)
{
if (evt == null) throw new ArgumentNullException("evt");
if (this.CanRaiseEvent(evt))
{
await this.PrepareEventAsync(evt);
await this.eventSink.PersistAsync(evt);
}
}
/// <summary>
/// Indicates if the type of event will be persisted.
/// </summary>
/// <param name="evtType"></param>
/// <returns></returns>
/// <exception cref="System.ArgumentOutOfRangeException"></exception>
public bool CanRaiseEventType(EventTypes evtType)
{
switch (evtType)
{
case EventTypes.Failure:
return this.eventOptions.RaiseFailureEvents;
case EventTypes.Information:
return this.eventOptions.RaiseInformationEvents;
case EventTypes.Success:
return this.eventOptions.RaiseSuccessEvents;
case EventTypes.Error:
return this.eventOptions.RaiseErrorEvents;
default:
throw new ArgumentOutOfRangeException();
}
}
/// <summary>
/// Determines whether this event would be persisted.
/// </summary>
/// <param name="evt">The evt.</param>
/// <returns>
/// <c>true</c> if this event would be persisted; otherwise,
/// <c>false</c>.
/// </returns>
protected virtual bool CanRaiseEvent(Event evt)
{
return this.CanRaiseEventType(evt.EventType);
}
/// <summary>
/// Prepares the event.
/// </summary>
/// <param name="evt">The evt.</param>
/// <returns></returns>
protected virtual async Task PrepareEventAsync(Event evt)
{
HttpContext httpContext = this.httpContextAccessor.HttpContext;
evt.ActivityId = httpContext.TraceIdentifier;
evt.TimeStamp = this.dateTimeAccessor.UtcNow;
evt.ProcessId = Process.GetCurrentProcess().Id;
if (httpContext.Connection.LocalIpAddress != null)
{
evt.LocalIpAddress = httpContext.Connection
.LocalIpAddress.ToString() + ":" +
httpContext.Connection.LocalPort;
}
else
{
evt.LocalIpAddress = "unknown";
}
if (httpContext.Connection.RemoteIpAddress != null)
{
evt.RemoteIpAddress = httpContext.Connection
.RemoteIpAddress.ToString();
}
else
{
evt.RemoteIpAddress = "unknown";
}
await evt.PrepareAsync();
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DCDC_Manager
{
public abstract class PSValue<T> : WatchDog
{
private T _value;
private double _timeStamp;
public T Value
{
get
{
throw new System.NotImplementedException();
}
set
{
}
}
public double TimeStamp
{
get
{
throw new System.NotImplementedException();
}
set
{
}
}
public override void read()
{
throw new System.NotImplementedException();
}
public override void write()
{
throw new System.NotImplementedException();
}
public override string getReadQuery()
{
throw new System.NotImplementedException();
}
public override string getWriteQuery()
{
throw new System.NotImplementedException();
}
}
} |
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using Microsoft.CSharp.RuntimeBinder;
using System;
using System.Management.Automation.Runspaces;
using System.Collections.Generic;
using Microsoft.Extensions.Logging;
using Microsoft.PowerShell.EditorServices.Utility;
namespace Microsoft.PowerShell.EditorServices.Services.PowerShellContext
{
/// <summary>
/// Specifies the possible types of a runspace.
/// </summary>
public enum RunspaceLocation
{
/// <summary>
/// A runspace on the local machine.
/// </summary>
Local,
/// <summary>
/// A runspace on a different machine.
/// </summary>
Remote
}
/// <summary>
/// Specifies the context in which the runspace was encountered.
/// </summary>
public enum RunspaceContext
{
/// <summary>
/// The original runspace in a local or remote session.
/// </summary>
Original,
/// <summary>
/// A runspace in a process that was entered with Enter-PSHostProcess.
/// </summary>
EnteredProcess,
/// <summary>
/// A runspace that is being debugged with Debug-Runspace.
/// </summary>
DebuggedRunspace
}
/// <summary>
/// Provides details about a runspace being used in the current
/// editing session.
/// </summary>
public class RunspaceDetails
{
#region Private Fields
private Dictionary<Type, IRunspaceCapability> capabilities =
new Dictionary<Type, IRunspaceCapability>();
#endregion
#region Properties
/// <summary>
/// Gets the Runspace instance for which this class contains details.
/// </summary>
internal Runspace Runspace { get; private set; }
/// <summary>
/// Gets the PowerShell version of the new runspace.
/// </summary>
public PowerShellVersionDetails PowerShellVersion { get; private set; }
/// <summary>
/// Gets the runspace location, either Local or Remote.
/// </summary>
public RunspaceLocation Location { get; private set; }
/// <summary>
/// Gets the context in which the runspace was encountered.
/// </summary>
public RunspaceContext Context { get; private set; }
/// <summary>
/// Gets the "connection string" for the runspace, generally the
/// ComputerName for a remote runspace or the ProcessId of an
/// "Attach" runspace.
/// </summary>
public string ConnectionString { get; private set; }
/// <summary>
/// Gets the details of the runspace's session at the time this
/// RunspaceDetails object was created.
/// </summary>
public SessionDetails SessionDetails { get; private set; }
#endregion
#region Constructors
/// <summary>
/// Creates a new instance of the RunspaceDetails class.
/// </summary>
/// <param name="runspace">
/// The runspace for which this instance contains details.
/// </param>
/// <param name="sessionDetails">
/// The SessionDetails for the runspace.
/// </param>
/// <param name="powerShellVersion">
/// The PowerShellVersionDetails of the runspace.
/// </param>
/// <param name="runspaceLocation">
/// The RunspaceLocation of the runspace.
/// </param>
/// <param name="runspaceContext">
/// The RunspaceContext of the runspace.
/// </param>
/// <param name="connectionString">
/// The connection string of the runspace.
/// </param>
public RunspaceDetails(
Runspace runspace,
SessionDetails sessionDetails,
PowerShellVersionDetails powerShellVersion,
RunspaceLocation runspaceLocation,
RunspaceContext runspaceContext,
string connectionString)
{
this.Runspace = runspace;
this.SessionDetails = sessionDetails;
this.PowerShellVersion = powerShellVersion;
this.Location = runspaceLocation;
this.Context = runspaceContext;
this.ConnectionString = connectionString;
}
#endregion
#region Public Methods
internal void AddCapability<TCapability>(TCapability capability)
where TCapability : IRunspaceCapability
{
this.capabilities.Add(typeof(TCapability), capability);
}
internal TCapability GetCapability<TCapability>()
where TCapability : IRunspaceCapability
{
TCapability capability = default(TCapability);
this.TryGetCapability<TCapability>(out capability);
return capability;
}
internal bool TryGetCapability<TCapability>(out TCapability capability)
where TCapability : IRunspaceCapability
{
IRunspaceCapability capabilityAsInterface = default(TCapability);
if (this.capabilities.TryGetValue(typeof(TCapability), out capabilityAsInterface))
{
capability = (TCapability)capabilityAsInterface;
return true;
}
capability = default(TCapability);
return false;
}
internal bool HasCapability<TCapability>()
{
return this.capabilities.ContainsKey(typeof(TCapability));
}
/// <summary>
/// Creates and populates a new RunspaceDetails instance for the given runspace.
/// </summary>
/// <param name="runspace">
/// The runspace for which details will be gathered.
/// </param>
/// <param name="sessionDetails">
/// The SessionDetails for the runspace.
/// </param>
/// <param name="logger">An ILogger implementation used for writing log messages.</param>
/// <returns>A new RunspaceDetails instance.</returns>
internal static RunspaceDetails CreateFromRunspace(
Runspace runspace,
SessionDetails sessionDetails,
ILogger logger)
{
Validate.IsNotNull(nameof(runspace), runspace);
Validate.IsNotNull(nameof(sessionDetails), sessionDetails);
var runspaceLocation = RunspaceLocation.Local;
var runspaceContext = RunspaceContext.Original;
var versionDetails = PowerShellVersionDetails.GetVersionDetails(runspace, logger);
string connectionString = null;
if (runspace.ConnectionInfo != null)
{
// Use 'dynamic' to avoid missing NamedPipeRunspaceConnectionInfo
// on PS v3 and v4
try
{
dynamic connectionInfo = runspace.ConnectionInfo;
if (connectionInfo.ProcessId != null)
{
connectionString = connectionInfo.ProcessId.ToString();
runspaceContext = RunspaceContext.EnteredProcess;
}
}
catch (RuntimeBinderException)
{
// ProcessId property isn't on the object, move on.
}
// Grab the $host.name which will tell us if we're in a PSRP session or not
string hostName =
PowerShellContextService.ExecuteScriptAndGetItem<string>(
"$Host.Name",
runspace,
defaultValue: string.Empty);
// hostname is 'ServerRemoteHost' when the user enters a session.
// ex. Enter-PSSession
// Attaching to process currently needs to be marked as a local session
// so we skip this if block if the runspace is from Enter-PSHostProcess
if (hostName.Equals("ServerRemoteHost", StringComparison.Ordinal)
&& runspace.OriginalConnectionInfo?.GetType().ToString() != "System.Management.Automation.Runspaces.NamedPipeConnectionInfo")
{
runspaceLocation = RunspaceLocation.Remote;
connectionString =
runspace.ConnectionInfo.ComputerName +
(connectionString != null ? $"-{connectionString}" : string.Empty);
}
}
return
new RunspaceDetails(
runspace,
sessionDetails,
versionDetails,
runspaceLocation,
runspaceContext,
connectionString);
}
/// <summary>
/// Creates a clone of the given runspace through which another
/// runspace was attached. Sets the IsAttached property of the
/// resulting RunspaceDetails object to true.
/// </summary>
/// <param name="runspaceDetails">
/// The RunspaceDetails object which the new object based.
/// </param>
/// <param name="runspaceContext">
/// The RunspaceContext of the runspace.
/// </param>
/// <param name="sessionDetails">
/// The SessionDetails for the runspace.
/// </param>
/// <returns>
/// A new RunspaceDetails instance for the attached runspace.
/// </returns>
public static RunspaceDetails CreateFromContext(
RunspaceDetails runspaceDetails,
RunspaceContext runspaceContext,
SessionDetails sessionDetails)
{
return
new RunspaceDetails(
runspaceDetails.Runspace,
sessionDetails,
runspaceDetails.PowerShellVersion,
runspaceDetails.Location,
runspaceContext,
runspaceDetails.ConnectionString);
}
/// <summary>
/// Creates a new RunspaceDetails object from a remote
/// debugging session.
/// </summary>
/// <param name="runspaceDetails">
/// The RunspaceDetails object which the new object based.
/// </param>
/// <param name="runspaceLocation">
/// The RunspaceLocation of the runspace.
/// </param>
/// <param name="runspaceContext">
/// The RunspaceContext of the runspace.
/// </param>
/// <param name="sessionDetails">
/// The SessionDetails for the runspace.
/// </param>
/// <returns>
/// A new RunspaceDetails instance for the attached runspace.
/// </returns>
public static RunspaceDetails CreateFromDebugger(
RunspaceDetails runspaceDetails,
RunspaceLocation runspaceLocation,
RunspaceContext runspaceContext,
SessionDetails sessionDetails)
{
// TODO: Get the PowerShellVersion correctly!
return
new RunspaceDetails(
runspaceDetails.Runspace,
sessionDetails,
runspaceDetails.PowerShellVersion,
runspaceLocation,
runspaceContext,
runspaceDetails.ConnectionString);
}
#endregion
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerTurnState : State
{
public PlayerTurnState(StateMachine stateMachine) : base(stateMachine)
{
}
public override void Enter()
{
//start player turn
GameManager.instance.LevelManager.StartPlayerTurn();
}
}
|
using System.ComponentModel.DataAnnotations;
namespace TxtUploader.Models
{
public class TxtModel
{
public int Id { get; set; }
[MinLength(1)]
[MaxLength(100)]
public string FileName { get; set; }
public byte[] FileContent { get; set; }
}
} |
using Diligent.BOL;
namespace Diligent.DAL.Core
{
public interface IUserRepository : IRepository<User>
{
User GetUserWithProjects(int id);
}
}
|
using UnityEngine;
using System.Collections;
public class Level2 : MonoBehaviour {
GameObject boss1;
// Use this for initialization
void Start () {
boss1 = GameObject.Find("GIANT_WORM");
}
// Update is called once per frame
void Update () {
}
void OnTriggerEnter(Collider hit) {
if (boss1.GetComponent<HitPointManager> ().isDead ()) {
Application.LoadLevel ("Scene2");
}
}
} |
using System.Linq.Expressions;
using Bindable.Linq.Dependencies.Definitions;
namespace Bindable.Linq.Dependencies.ExpressionAnalysis.Extractors
{
/// <summary>
/// Extracts dependencies placed on child items within a query by looking for uses of <see cref="ParameterExpression"/>.
/// </summary>
internal sealed class ItemDependencyExtractor : DependencyExtractor
{
/// <summary>
/// When overridden in a derived class, extracts the appropriate dependency from the root of the expression.
/// </summary>
/// <param name="rootExpression">The root expression.</param>
/// <param name="propertyPath">The property path.</param>
/// <returns></returns>
protected override IDependencyDefinition ExtractFromRoot(Expression rootExpression, string propertyPath)
{
IDependencyDefinition result = null;
if (rootExpression is ParameterExpression)
{
var parameterExpression = (ParameterExpression) rootExpression;
result = new ItemDependencyDefinition(propertyPath, parameterExpression.Name);
}
return result;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
namespace buildings
{
public class ConstructController : MonoBehaviour
{
public Construct construct = null;
public Building building = null;
public List<ResourceCost> resourceCost;
[Serializable]
public struct ResourceCost
{
public string type;
public int num;
}
/// <summary>
/// Prepare for BuildMark
/// </summary>
public void SetBuildState()
{
construct.gameObject.SetActive(true);
construct.stages.ForEach(stage => stage.SetActive(false));
building.gameObject.SetActive(false);
construct.buildMark.gameObject.SetActive(true);
}
public void SetCompleteState()
{
GameManager.Instance.BuildingManager.UpdateBuildingsList();
}
public void Init()
{
construct.stages.ForEach(stage => stage.SetActive(false));
if (construct.isConstructed)
{
building.gameObject.SetActive(true);
GameManager.Instance.WorkManager.ReAssignByWorkplace(construct);
construct.gameObject.SetActive(false);
}
else
{
building.gameObject.SetActive(false);
construct.gameObject.SetActive(true);
construct.stages.First().SetActive(true);
//Set resource cost from editor to construct
foreach (var cost in resourceCost)
{
construct.resourcesCost[cost.type] = cost.num;
}
}
}
void Awake()
{
Init();
}
}
}
|
using System;
namespace DipDemo.Cataloguer.Infrastructure.Presentation
{
public class AbstractPresenter<TView> : IPresenter
where TView : IView
{
protected TView View;
public event Action Disposed = delegate { };
IView IPresenter.View
{
get { return View; }
}
public AbstractPresenter(TView view)
{
View = view;
View.Closed += (o, e) => Dispose();
}
public virtual void Close()
{
View.CloseView();
}
public virtual void Dispose()
{
Disposed();
}
}
}
|
#region Usings
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
#endregion
namespace Zengo.WP8.FAS.Controls
{
public partial class SearchBoxControl : UserControl
{
public class DoSearchEventArgs : EventArgs
{
public string searchTerm { get; set; }
}
#region Events
public event EventHandler<DoSearchEventArgs> DoSearch;
public event EventHandler<EventArgs> SearchCancelled;
#endregion
#region Constructors
public SearchBoxControl()
{
InitializeComponent();
}
#endregion
#region Properties
public string Text
{
get
{
return TextBoxSearchFind.Text;
}
set
{
TextBoxSearchFind.Text = value;
}
}
#endregion
internal void SelectAll()
{
TextBoxSearchFind.Focus();
}
internal bool IsSearchEnabled()
{
return BorderSearch.Visibility == System.Windows.Visibility.Visible ? true : false;
}
internal void EnableSearch( bool enable)
{
if (enable)
{
BorderSearch.Visibility = System.Windows.Visibility.Visible;
TextBoxSearchFind.Focus();
}
else
{
BorderSearch.Visibility = System.Windows.Visibility.Collapsed;
}
}
/// <summary>
/// The user clicks on the search textbox (giving it focus)
/// </summary>
private void TextBoxSearch_GotFocus(object sender, RoutedEventArgs e)
{
App.AppConstants.SetTextBoxFocusColours(sender as TextBox);
SelectAll();
}
/// <summary>
/// If return key is pressed, remove the search textbox and do the search
/// </summary>
private void TextBoxSearch_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
if (Text.Length >= 2)
{
if (DoSearch != null)
{
DoSearch(this, new DoSearchEventArgs() { searchTerm = TextBoxSearchFind.Text });
}
}
}
}
/// <summary>
/// Lost focus - let the container know so they can do what they need to do
/// </summary>
private void TextBoxSearch_LostFocus(object sender, System.Windows.RoutedEventArgs e)
{
EnableSearch(false);
if (SearchCancelled != null)
{
SearchCancelled(this, new EventArgs());
}
}
}
}
|
namespace Bb.Expressions.CsharpGenerators
{
internal sealed class Indentation
{
private readonly ExposedTabStringIndentedTextWriter _writer;
private readonly int _indent;
private string _s;
internal Indentation(ExposedTabStringIndentedTextWriter writer, int indent)
{
_writer = writer;
_indent = indent;
}
internal string IndentationString
{
get
{
if (_s == null)
{
string tabString = _writer.TabString;
switch (_indent)
{
case 1: _s = tabString; break;
case 2: _s = tabString + tabString; break;
case 3: _s = tabString + tabString + tabString; break;
case 4: _s = tabString + tabString + tabString + tabString; break;
default:
var args = new string[_indent];
for (int i = 0; i < args.Length; i++)
{
args[i] = tabString;
}
return string.Concat(args);
}
}
return _s;
}
}
}
} |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Tcgv.QuantumSim.Data;
namespace Tcgv.QuantumSim.Operations
{
[TestClass()]
public class CXGateTest
{
[TestMethod()]
public void ControlFalse_InputFalse_Test()
{
var c = new Qubit(false);
var q = new Qubit(false);
new CXGate().Apply(c, q);
Assert.IsFalse(c.Measure());
Assert.IsFalse(q.Measure());
}
[TestMethod()]
public void ControlFalse_InputTrue_Test()
{
var c = new Qubit(false);
var q = new Qubit(true);
new CXGate().Apply(c, q);
Assert.IsFalse(c.Measure());
Assert.IsTrue(q.Measure());
}
[TestMethod()]
public void ControlTrue_InputFalse_Test()
{
var c = new Qubit(true);
var q = new Qubit(false);
new CXGate().Apply(c, q);
Assert.IsTrue(c.Measure());
Assert.IsTrue(q.Measure());
}
[TestMethod()]
public void ControlTrue_InputTrue_Test()
{
var c = new Qubit(true);
var q = new Qubit(true);
new CXGate().Apply(c, q);
Assert.IsTrue(c.Measure());
Assert.IsFalse(q.Measure());
}
[TestMethod()]
public void ThreeQubitSystem_ControlFalse_InputFalse_Test()
{
var c = new Qubit(false);
var q = new Qubit(false);
var x = new Qubit(true);
Qubit.Combine(q, x);
Qubit.Combine(c, q);
new CXGate().Apply(c, q);
Assert.IsFalse(c.Measure());
Assert.IsFalse(q.Measure());
Assert.IsTrue(x.Measure());
}
[TestMethod()]
public void ThreeQubitSystem_ControlFalse_InputTrue_Test()
{
var c = new Qubit(false);
var q = new Qubit(true);
var x = new Qubit(true);
Qubit.Combine(q, x);
Qubit.Combine(c, q);
new CXGate().Apply(c, q);
Assert.IsFalse(c.Measure());
Assert.IsTrue(q.Measure());
Assert.IsTrue(x.Measure());
}
[TestMethod()]
public void ThreeQubitSystem_ControlTrue_InputFalse_Test()
{
var c = new Qubit(true);
var q = new Qubit(false);
var x = new Qubit(true);
Qubit.Combine(c, q);
Qubit.Combine(q, x);
new CXGate().Apply(c, q);
Assert.IsTrue(c.Measure());
Assert.IsTrue(q.Measure());
Assert.IsTrue(x.Measure());
}
[TestMethod()]
public void ThreeQubitSystem_ControlTrue_InputTrue_Test()
{
var c = new Qubit(true);
var q = new Qubit(true);
var x = new Qubit(false);
Qubit.Combine(c, q);
Qubit.Combine(q, x);
new CXGate().Apply(c, q);
Assert.IsTrue(c.Measure());
Assert.IsFalse(q.Measure());
Assert.IsFalse(x.Measure());
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Shooter
{
class Pistol : Gun
{
int _delay;
public Pistol()
: base()
{
_bullets = 7;
_delay = 40;
this.Cost = 1000;
this.Image = new string[] {
@" _____________",
@" \-------------'",
@" / /( /",
@" / /---",
@"/__/" };
}
public Pistol(int ammo)
: this()
{
_bullets = ammo;
}
public override void Shoot()
{
if (_delay >= 40)
{
_delay = 0;
base.Shoot(new SimpleShot(this, GetBulletIcon(_owner.Direction), 15, _owner.X, _owner.Y, _owner.Direction));
}
}
public override Gun Clone()
{
Pistol p = new Pistol();
SetValues(p);
return p;
}
protected override string GetBulletIcon(Direction direction)
{
switch (direction)
{
case Direction.Left:
case Direction.Right:
return "-";
case Direction.Up:
case Direction.Down:
return "|";
}
return this.Icon;
}
public override void Draw(int x, int y)
{
if (_delay < 40)
_delay++;
base.DoDraw(x, y);
}
public override string Name
{
get { return "Pistol"; }
}
public override string Icon
{
get { return "p"; }
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ENTITY;
using OpenMiracle.DAL;
using System.Windows.Forms;
using System.Data;
namespace OpenMiracle.BLL
{
public class DailySalaryVoucherBll
{
DailySalaryVoucherDetailsInfo infoDailySalaryVoucherDetails = new DailySalaryVoucherDetailsInfo();
DailySalaryVoucherDetailsSP SpDailySalaryVoucherDetails = new DailySalaryVoucherDetailsSP();
DailySalaryVoucherMasterInfo infoDailySalaryVoucherMaster = new DailySalaryVoucherMasterInfo();
DailySalaryVoucherMasterSP SpDailySalaryVoucherMaster = new DailySalaryVoucherMasterSP();
public string CheckWhetherDailySalaryAlreadyPaid(decimal decEmployeeId, DateTime SalaryDate)
{
string strName = string.Empty;
try
{
strName = SpDailySalaryVoucherDetails.CheckWhetherDailySalaryAlreadyPaid(decEmployeeId, SalaryDate);
}
catch (Exception ex)
{
MessageBox.Show("DSV1:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
return strName;
}
public void DailySalaryVoucherDetailsAdd(DailySalaryVoucherDetailsInfo dailysalaryvoucherdetailsinfo)
{
try
{
SpDailySalaryVoucherDetails.DailySalaryVoucherDetailsAdd(dailysalaryvoucherdetailsinfo);
}
catch (Exception ex)
{
MessageBox.Show("DSV2:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
public void DailySalaryVoucherDetailsDelete(decimal DailySalaryVoucherDetailsId)
{
try
{
SpDailySalaryVoucherDetails.DailySalaryVoucherDetailsDelete(DailySalaryVoucherDetailsId);
}
catch (Exception ex)
{
MessageBox.Show("DSV3:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
public int DailySalaryVoucherDetailsCount(decimal decMasterId)
{
int max = 0;
try
{
max = SpDailySalaryVoucherDetails.DailySalaryVoucherDetailsCount(decMasterId);
}
catch (Exception ex)
{
MessageBox.Show("DSV4:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
return max;
}
public void DailySalaryVoucherDetailsDeleteUsingMasterId(decimal DailySalaryVoucherDetailsMasterId)
{
try
{
SpDailySalaryVoucherDetails.DailySalaryVoucherDetailsDeleteUsingMasterId(DailySalaryVoucherDetailsMasterId);
}
catch (Exception ex)
{
MessageBox.Show("DSV5:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
public List<DataTable> DailySalaryVoucherDetailsGridViewAll(string strSalaryDate, bool isEditMode, string strVoucherNumber)
{
List<DataTable> listDailySalaryVoucherDetailsGridViewAll = new List<DataTable>();
try
{
listDailySalaryVoucherDetailsGridViewAll = SpDailySalaryVoucherDetails.DailySalaryVoucherDetailsGridViewAll(strSalaryDate, isEditMode, strVoucherNumber);
}
catch (Exception ex)
{
MessageBox.Show("DSV6:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
return listDailySalaryVoucherDetailsGridViewAll;
}
public List<DataTable> DailySalaryRegisterSearch(DateTime dtVoucherDateFrom, DateTime dtVoucherDateTo, DateTime dtSalaryDateFrom, DateTime dtSalaryDateTo, string strInvoiceNo)
{
List<DataTable> listObj = new List<DataTable>();
try
{
listObj = SpDailySalaryVoucherMaster.DailySalaryRegisterSearch(dtVoucherDateFrom, dtVoucherDateTo, dtSalaryDateFrom, dtSalaryDateTo, strInvoiceNo);
}
catch (Exception ex)
{
MessageBox.Show("DSV7:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
return listObj;
}
public List<DataTable> DailySalaryVoucherCashOrBankLedgersComboFill()
{
List<DataTable> listObj = new List<DataTable>();
try
{
listObj = SpDailySalaryVoucherMaster.DailySalaryVoucherCashOrBankLedgersComboFill();
}
catch (Exception ex)
{
MessageBox.Show("DSV8:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
return listObj;
}
public DailySalaryVoucherMasterInfo DailySalaryVoucherViewFromRegister(decimal decDailySalaryVoucehrMasterId)
{
DailySalaryVoucherMasterInfo infoDailySalaryVoucherMaster = new DailySalaryVoucherMasterInfo();
try
{
infoDailySalaryVoucherMaster = SpDailySalaryVoucherMaster.DailySalaryVoucherViewFromRegister(decDailySalaryVoucehrMasterId);
}
catch (Exception ex)
{
MessageBox.Show("DSV9:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
return infoDailySalaryVoucherMaster;
}
public bool DailySalaryVoucherCheckExistence(string voucherNumber, decimal voucherTypeId, decimal masterId)
{
bool trueOrfalse = false;
try
{
trueOrfalse = SpDailySalaryVoucherMaster.DailySalaryVoucherCheckExistence(voucherNumber, voucherTypeId, masterId);
}
catch (Exception ex)
{
MessageBox.Show("DSV10:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
return trueOrfalse;
}
public List<DataTable> DailySalaryVoucherMasterAddWithIdentity(DailySalaryVoucherMasterInfo dailysalaryvouchermasterinfo, bool IsAutomatic)
{
List<DataTable> listObj = new List<DataTable>();
try
{
listObj = SpDailySalaryVoucherMaster.DailySalaryVoucherMasterAddWithIdentity(dailysalaryvouchermasterinfo, IsAutomatic);
}
catch (Exception ex)
{
MessageBox.Show("DSV11:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
return listObj;
}
public string DailySalaryVoucherMasterGetMax(decimal voucherTypeId)
{
string max = "0";
try
{
max = SpDailySalaryVoucherMaster.DailySalaryVoucherMasterGetMax(voucherTypeId);
}
catch (Exception ex)
{
MessageBox.Show("DSV12:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
return max;
}
public void DailySalaryVoucherMasterEdit(DailySalaryVoucherMasterInfo dailysalaryvouchermasterinfo)
{
try
{
SpDailySalaryVoucherMaster.DailySalaryVoucherMasterEdit(dailysalaryvouchermasterinfo);
}
catch (Exception ex)
{
MessageBox.Show("DSV13:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
public void DailySalaryVoucherMasterDelete(decimal DailySalaryVoucehrMasterId)
{
try
{
SpDailySalaryVoucherMaster.DailySalaryVoucherMasterDelete(DailySalaryVoucehrMasterId);
}
catch (Exception ex)
{
MessageBox.Show("DSV14:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
public decimal SalaryVoucherMasterGetMaxPlusOne(decimal decVoucherTypeId)
{
decimal max = 0;
try
{
max = SpDailySalaryVoucherMaster.SalaryVoucherMasterGetMaxPlusOne(decVoucherTypeId);
}
catch (Exception ex)
{
MessageBox.Show("DSV15:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
return max;
}
}
}
|
using MedicalStoreWebApi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
namespace MedicalStoreWebApi.Controllers
{
[Authorize]
public class ConsumeController : Controller
{
// GET: Consume
HttpClient hc = new HttpClient();
MedicineDBContext db = new MedicineDBContext();
[HttpGet]
public ActionResult Index()
{
Auth.auth = true;
List<Medicine> list = new List<Medicine>();
hc.BaseAddress = new Uri("https://localhost:44398/api/");
var consume = hc.GetAsync("Medicine");
consume.Wait();
var test = consume.Result;
if (test.IsSuccessStatusCode)
{
var display = test.Content.ReadAsAsync<List<Medicine>>();
list = display.Result;
}
return View(list);
}
[HttpGet]
public ActionResult Details(int id)
{
hc.BaseAddress = new Uri("https://localhost:44398/api/Medicine/");
Medicine m = new Medicine();
var consume = hc.GetAsync("Get?id=" + id.ToString());
consume.Wait();
var test = consume.Result;
if (test.IsSuccessStatusCode)
{
var display = test.Content.ReadAsAsync<Medicine>();
display.Wait();
m = display.Result;
}
return View(m);
}
[HttpGet]
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(Medicine m)
{
hc.BaseAddress = new Uri("https://localhost:44398/api/Medicine/");
var consume = hc.PostAsJsonAsync("Post", m);
consume.Wait();
var test = consume.Result;
if (test.IsSuccessStatusCode)
{
return RedirectToAction("Index");
}
else
{
return HttpNotFound();
}
}
[HttpGet]
public ActionResult Edit(int id)
{
hc.BaseAddress = new Uri("https://localhost:44398/api/Medicine/");
Medicine m = new Medicine();
var consume = hc.GetAsync("Get?id=" + id.ToString());
consume.Wait();
var test = consume.Result;
if (test.IsSuccessStatusCode)
{
var display = test.Content.ReadAsAsync<Medicine>();
display.Wait();
m = display.Result;
}
return View(m);
}
[HttpPost]
public ActionResult Edit(Medicine m)
{
hc.BaseAddress = new Uri("https://localhost:44398/api/Medicine/");
var consume = hc.PutAsJsonAsync("Put", m);
consume.Wait();
var test = consume.Result;
if (test.IsSuccessStatusCode)
{
return RedirectToAction("Index");
}
return View();
}
public ActionResult Delete(int id)
{
hc.BaseAddress = new Uri("https://localhost:44398/api/Medicine/");
var consume = hc.DeleteAsync("Delete?id=" + id.ToString());
consume.Wait();
var test = consume.Result;
if (test.IsSuccessStatusCode)
{
return RedirectToAction("Index");
}
else
{
return HttpNotFound();
}
}
public ActionResult History()
{
List<Purchase> list = new List<Purchase>();
hc.BaseAddress = new Uri("https://localhost:44398/api/");
var consume = hc.GetAsync("Purchases");
consume.Wait();
var test = consume.Result;
if (test.IsSuccessStatusCode)
{
var display = test.Content.ReadAsAsync<List<Purchase>>();
list = display.Result;
}
return View(list);
}
[HttpGet]
public ActionResult Buy()
{
string[] medicine = db.Medicines.Select(e => e.MedicineName).ToArray();
ViewBag.mname = medicine;
return View();
}
[HttpPost]
public ActionResult Buy(Purchase p)
{
ApplicationDbContext dbContext = new ApplicationDbContext();
int amount = 0, total = 0, qty = 0;
qty = p.Quantity;
p.UserId = 0;
p.Date = DateTime.Now;
amount = db.Medicines.Where(e => e.MedicineName == p.MedicineName).Select(e => e.Price).FirstOrDefault();
total = p.Quantity * amount;
p.Amount = total;
Medicine data = db.Medicines.Where(e => e.MedicineName == p.MedicineName).FirstOrDefault();
if(data != null)
{
data.Stock = data.Stock - qty;
db.SaveChanges();
}
hc.BaseAddress = new Uri("https://localhost:44398/api/Purchases/");
var consume = hc.PostAsJsonAsync("PostPurchase", p);
consume.Wait();
var test = consume.Result;
if (test.IsSuccessStatusCode)
{
return RedirectToAction("Index");
}
else
{
return HttpNotFound();
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
namespace AdminSchool.DataAccesslayer
{
public class SutdentRegisterContext : DbContext
{
public SutdentRegisterContext(): base ("School") {} //my database name
public DbSet<Models.StudentData> StudentDatas { get; set; }
public DbSet<Models.SchoolTeacher> Schoolteachers { get; set; }
public DbSet<Models.Sport> Sports { get; set; }
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class Char : MonoBehaviour
{
NavMeshAgent agent;
void Start()
{
//UpAnim();
}
//float Speed = .02f;
void Update()
{
if (agent.isOnOffMeshLink)
{
//agent.updateRotation = false;
//agent.link
}
//Debug.Log(agent.desiredVelocity);
//transform.Translate(Vector3.up * agent.desiredVelocity.y * Speed);
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using Scintilla;
using Scintilla.Forms;
using Scintilla.Configuration;
using Scintilla.Configuration.SciTE;
using WeifenLuo.WinFormsUI.Docking;
namespace MyGeneration
{
public interface IMyGenerationMDI
{
FindForm FindDialog { get; }
ReplaceForm ReplaceDialog { get; }
ScintillaConfigureDelegate ConfigureDelegate { get; }
DockPanel DockPanel { get; }
}
} |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Reflection;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.EntityFrameworkCore.Migrations.Design;
using Microsoft.EntityFrameworkCore.Scaffolding;
using Microsoft.EntityFrameworkCore.TestUtilities;
using Microsoft.Extensions.DependencyInjection;
using Xunit;
namespace Microsoft.EntityFrameworkCore
{
public abstract class DesignTimeTestBase<TFixture> : IClassFixture<TFixture>
where TFixture : DesignTimeTestBase<TFixture>.DesignTimeFixtureBase
{
protected TFixture Fixture { get; }
protected DesignTimeTestBase(TFixture fixture)
=> Fixture = fixture;
protected abstract Assembly ProviderAssembly { get; }
[ConditionalFact]
public void Can_get_reverse_engineering_services()
{
using var context = Fixture.CreateContext();
var serviceCollection = new ServiceCollection()
.AddEntityFrameworkDesignTimeServices();
((IDesignTimeServices)Activator.CreateInstance(
ProviderAssembly.GetType(
ProviderAssembly.GetCustomAttribute<DesignTimeProviderServicesAttribute>().TypeName,
throwOnError: true))!)
.ConfigureDesignTimeServices(serviceCollection);
using var services = serviceCollection.BuildServiceProvider();
var reverseEngineerScaffolder = services.GetService<IReverseEngineerScaffolder>();
Assert.NotNull(reverseEngineerScaffolder);
}
[ConditionalFact]
public void Can_get_migrations_services()
{
using var context = Fixture.CreateContext();
var serviceCollection = new ServiceCollection()
.AddEntityFrameworkDesignTimeServices()
.AddDbContextDesignTimeServices(context);
((IDesignTimeServices)Activator.CreateInstance(
ProviderAssembly.GetType(
ProviderAssembly.GetCustomAttribute<DesignTimeProviderServicesAttribute>().TypeName,
throwOnError: true))!)
.ConfigureDesignTimeServices(serviceCollection);
using var services = serviceCollection.BuildServiceProvider();
var migrationsScaffolder = services.GetService<IMigrationsScaffolder>();
Assert.NotNull(migrationsScaffolder);
}
public abstract class DesignTimeFixtureBase : SharedStoreFixtureBase<PoolableDbContext>
{
protected override string StoreName
=> "DesignTimeTest";
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http.Filters;
namespace Shop.Attributes
{
public class HendlerArgumentExceptionAttribute : Attribute, IExceptionFilter
{
public bool AllowMultiple
{
get
{
return false;
}
}
public Task ExecuteExceptionFilterAsync(HttpActionExecutedContext actionExecutedContext,
CancellationToken cancellationToken)
{
if (actionExecutedContext != null && actionExecutedContext.Exception is ArgumentException)
{
actionExecutedContext.Response = actionExecutedContext.Request.CreateErrorResponse(
HttpStatusCode.BadRequest, "Check you argument");
}
return Task.FromResult<object>(null);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GenericLabs
{
class Box<T>
{
private List<T> start = new List<T>();
public int Count { get { return start.Count; } }
public void Add(T i)
{
start.Add(i);
}
public T Remove()
{
T temp = start[start.Count - 1];
start.RemoveAt(start.Count - 1);
return temp;
}
}
}
|
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace VetOnTrack.Controllers
{
public class AgendaController : Controller
{
public IActionResult AuthSchedule(string input_agenda)
{
return RedirectToAction("Agenda", "Home", new { data_consulta = input_agenda });
}
public IActionResult DeleteAgenda(int id_agenda)
{
return RedirectToAction("Agenda", "Home");
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.