text stringlengths 13 6.01M |
|---|
using log4net;
using System;
using System.IO;
namespace filter.framework.utility
{
/// <summary>
/// 日志管理
/// </summary>
public sealed class LogHelper
{
private ILog mLog;
public void SetLog(string loggerName = "", bool forceSet = false)
{
if (forceSet || mLog == null)
{
if (string.IsNullOrWhiteSpace(loggerName))
{
mLog = LogManager.GetLogger("Default");
}
else
{
mLog = LogManager.GetLogger(loggerName);
}
}
}
public void Warn(string message)
{
SetLog();
mLog.Warn(message);
}
public void Debug(string message)
{
SetLog();
mLog.Debug(message);
}
public void Info(string message)
{
SetLog();
mLog.Info(message);
}
public void Fatal(string message, Exception ex = null)
{
SetLog();
mLog.Fatal(message, ex);
}
public void Error(string message, Exception ex = null)
{
SetLog();
mLog.Error(message, ex);
}
public void InitLog4Net()
{
var logCfg = new FileInfo(AppDomain.CurrentDomain.BaseDirectory + "log4net.config");
log4net.Config.XmlConfigurator.ConfigureAndWatch(logCfg);
}
}
}
|
using BookStore.Models;
using System.Threading.Tasks;
namespace BookStore.Services
{
public interface IEmailService
{
Task SendTestEmail(UserEmailOptions userEmailOptions);
Task SendEmailForEmailConfirmation(UserEmailOptions userEmailOptions);
Task SendEmailForForgotPassword(UserEmailOptions userEmailOptions);
}
} |
namespace Computers.Logic.ComputerType
{
using HardDrives;
public class Server : Computer
{
public Server(
Cpu cpu,
Ram ram,
HardDrive hardDrives,
VideoCard videoCard)
: base(cpu, ram, hardDrives, videoCard)
{
}
public void Process(int data)
{
this.Ram.SaveValue(data);
this.Cpu.SquareNumber();
}
}
}
|
using System;
//For MethodImpl
using System.Runtime.CompilerServices;
namespace Unicorn
{
public class Light
{
public enum Type
{
DIRECTIONAL = 0,
POINT,
SPOT,
INVALID_TYPE
};
// Native handle for this component
private IntPtr native_handle = IntPtr.Zero;
public bool isActive
{
get { return get_isActive_Internal(this.native_handle); }
set { set_isActive_Internal(this.native_handle, value); }
}
public float intensity
{
get { return get_Intensity_Internal(this.native_handle); }
set { set_Intensity_Internal(this.native_handle, value); }
}
public float inCutOff
{
get { return get_inCutOff_Internal(this.native_handle); }
set { set_inCutOff_Internal(this.native_handle, value); }
}
public float outCutOff
{
get { return get_outCutOff_Internal(this.native_handle); }
set { set_outCutOff_Internal(this.native_handle, value); }
}
public float radius
{
get { return get_Radius_Internal(this.native_handle); }
set { set_Radius_Internal(this.native_handle, value); }
}
public Vector3 GetColor()
{
return get_Color_Internal(native_handle);
}
public void SetColor(Vector3 val)
{
set_Color_Internal(native_handle, val);
}
public Vector3 GetDiffuse()
{
return get_Diffuse_Internal(native_handle);
}
public void SetDiffuse(Vector3 val)
{
//Console.WriteLine("Set diffuse!");
set_Diffuse_Internal(native_handle, val);
}
public Vector3 GetSpecular()
{
return get_Specular_Internal(native_handle);
}
public void SetSpecular(Vector3 val)
{
set_Specular_Internal(native_handle, val);
}
public void ChangeLightType(Type val)
{
ChangeLightType_Internal(native_handle, val);
}
// Getter/Setter for name
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static bool get_isActive_Internal(IntPtr native_handle);
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static void set_isActive_Internal(IntPtr native_handle, bool val);
// Getter/Setter for Intensity
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static float get_Intensity_Internal(IntPtr native_handle);
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static void set_Intensity_Internal(IntPtr native_handle, float val);
// Getter/Setter for InnerCutoff
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static float get_inCutOff_Internal(IntPtr native_handle);
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static void set_inCutOff_Internal(IntPtr native_handle, float val);
// Getter/Setter for OuterCutoff
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static float get_outCutOff_Internal(IntPtr native_handle);
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static void set_outCutOff_Internal(IntPtr native_handle, float val);
// Getter/Setter for OuterCutoff
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static float get_Radius_Internal(IntPtr native_handle);
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static void set_Radius_Internal(IntPtr native_handle, float val);
// Getter/Setter for Ambient
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static Vector3 get_Color_Internal(IntPtr native_handle);
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static void set_Color_Internal(IntPtr native_handle, Vector3 val);
// Getter/Setter for Diffuse
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static Vector3 get_Diffuse_Internal(IntPtr native_handle);
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static void set_Diffuse_Internal(IntPtr native_handle, Vector3 val);
// Getter/Setter for Specular
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static Vector3 get_Specular_Internal(IntPtr native_handle);
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static void set_Specular_Internal(IntPtr native_handle, Vector3 val);
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static void ChangeLightType_Internal(IntPtr native_handle, Type val);
}
}
|
// -----------------------------------------------------------------------
// <copyright file="AssemblyInitializer.cs" company="Microsoft Corporation">
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root
// for license information.
// </copyright>
// -----------------------------------------------------------------------
using Mlos.Core;
using MlosCoreProxy = Proxy.Mlos.Core;
using MlosUnitTestProxy = Proxy.Mlos.UnitTest;
namespace Mlos.UnitTest
{
public static class AssemblyInitializer
{
static AssemblyInitializer()
{
MlosUnitTestProxy.WideStringViewArray.Callback = RunA;
MlosUnitTestProxy.Line.Callback = RunB;
MlosUnitTestProxy.UpdateConfigTestMessage.Callback = UpdateConfigTestMessage;
}
internal static void RunA(MlosUnitTestProxy.WideStringViewArray wideStringArrayProxy)
{
var a = wideStringArrayProxy.Id;
var b = wideStringArrayProxy.Strings[0].Value;
var c = wideStringArrayProxy.Strings[1].Value;
var d = wideStringArrayProxy.Strings[2].Value;
var e = wideStringArrayProxy.Strings[3].Value;
var f = wideStringArrayProxy.Strings[4].Value;
}
internal static void RunB(MlosUnitTestProxy.Line line)
{
var a = line.Colors[0];
var b = line.Colors[0];
var c = line.Points[0];
}
internal static void UpdateConfigTestMessage(MlosUnitTestProxy.UpdateConfigTestMessage msg)
{
// Update config.
//
var channelReaderStats = MlosContext.Instance.SharedConfigManager.Lookup<MlosCoreProxy.ChannelReaderStats>().Config;
channelReaderStats.SpinCount++;
}
}
}
|
using System.Collections;
using System.Runtime.CompilerServices;
using System.Threading;
namespace SCII
{
/*
internal class Keyboard
{
private static readonly Keyboard ThisInstance = new Keyboard();
private readonly VirtialKey[] _keyboardBuffer = new VirtialKey[32];
private int _getPointer;
private int _storePointer;
private Keyboard()
{
}
public int InBufCount { get; private set; }
public static Keyboard Instance
{
get { return ThisInstance; }
}
public void AddKey(VirtialKey virtialKey)
{
if (InBufCount == _keyboardBuffer.Length - 1)
return;
lock (this)
{
_keyboardBuffer[_storePointer] = virtialKey;
_storePointer++;
if (_storePointer == _keyboardBuffer.Length)
_storePointer = 0;
InBufCount++;
}
}
public VirtialKey GetKey()
{
while (InBufCount == 0)
{
Thread.Sleep(25);
}
VirtialKey virtialKey = _keyboardBuffer[_getPointer];
lock (this)
{
if (++_getPointer == _keyboardBuffer.Length)
_getPointer = 0;
InBufCount--;
}
return virtialKey;
}
[method: MethodImpl(MethodImplOptions.Synchronized)]
public void Clear()
{
InBufCount = _storePointer = _getPointer = 0;
}
}
*/
static class Keyboard2
{
private static readonly Queue Queue = new Queue();
public static int InBufCount
{
get { return Queue.Count; }
}
public static void AddKey(VirtialKey virtialKey)
{
Queue.Enqueue(virtialKey);
}
public static VirtialKey GetKey()
{
while (Queue.Count == 0)
{
Thread.Sleep(25);
}
return (VirtialKey)Queue.Dequeue();
}
public static void Clear()
{
Queue.Clear();
}
}
} |
using FluentAssertions;
using NUnit.Framework;
using PSPatcher.Core.Storage;
namespace PSPatcher.Tests.AstExtensionsTests.PSTests
{
[TestFixture]
public class DisplayExtensions_Tests
{
private IStorage storage;
[SetUp]
public void SetUp()
{
storage = new StringStorage();
}
[Test]
public void GetText_should_return_source_code()
{
var script = "Set-Variable foo_arg -value 99";
var ast = storage.Open(script);
var text = ast.GetText();
text.Should().Be(script);
}
}
} |
namespace RokasLog
{
public class LogHelper
{
private static LogBase logger = null;
public void Log(LogTarget target, string message)
{
switch(target)
{
case LogTarget.File:
logger = new FileLogger();
logger.Log(message);
break;
case LogTarget.Database:
logger = new DBLogger();
logger.Log(message);
break;
case LogTarget.EventLog:
logger = new EventLogger();
logger.Log(message);
break;
case LogTarget.RabbitMq:
logger = new RabbitMqLogger();
logger.Log(message);
break;
default:
return;
}
}
public void Log(string message)
{
// Could use a for loop, but that would be slower and use more memory.
logger = new FileLogger();
logger.Log(message);
logger = new DBLogger();
logger.Log(message);
logger = new EventLogger();
logger.Log(message);
logger = new RabbitMqLogger();
logger.Log(message);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using doob.Reflectensions;
using doob.Reflectensions.Common;
using doob.Scripter;
using doob.Scripter.Engine.Javascript;
using doob.Scripter.Engine.Powershell;
using doob.Scripter.Engine.TypeScript;
using doob.Scripter.Module.Common;
using doob.Scripter.Module.ConsoleWriter;
using doob.Scripter.Shared;
using Jint;
using Jint.Native;
using Microsoft.Extensions.DependencyInjection;
using NamedServices.Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json.Linq;
namespace ScripterTestCmd
{
class Program
{
private static IServiceProvider ServiceProvider { get; set; }
static async Task Main(string[] args)
{
var sc = new ServiceCollection();
sc.AddScripter(options => options
.AddJavaScriptEngine()
.AddTypeScriptEngine()
.AddPowerShellCoreEngine()
.AddScripterModule<ConsoleWriterModule>()
.AddScripterModule<CommonModule>()
.AddScripterModule<GlobalVariablesModule>()
);
sc.AddSingleton<IVariablesRepository, VariableRepository>();
sc.AddScoped<Options>(provider =>
{
var opts = new Options();
opts.AddExtensionMethods(typeof(StringExtensions));
return opts;
});
ServiceProvider = sc.BuildServiceProvider();
await ExecutePowershell();
}
private static async Task Execute()
{
var tsEngine = ServiceProvider.GetRequiredNamedService<IScriptEngine>("TypeScript");
var reg =ServiceProvider.GetService<IScripterModuleRegistry>();
var regModules = reg.GetRegisteredModuleDefinitions();
var variable = Json.Converter.ToJToken("{\r\n \"VKZ\": \"BMI\",\r\n \"BereichsKennung\": \"urn:publicid:gv.at:cdid+ZP\"\r\n}");
tsEngine.AddTaggedModules("VARiableS");
var tsScript = @"
//import * as variables from 'GlobalVariables';
//var methods = variables.GetType().GetMethods();
//let data = variables.GetAny(""BPK/DefaultRequestValues"");
//let d = {
// a: 123,
// ...data
//}
//variables.Test = ""Das ist ein TEst""
//let z = JSON.stringify(d)
//let y = d.VKZ.ToNullableInt();
//exit();
//let z = new System.Collections.Generic.Dictionary$2<string, System.Collections.Generic.List$1<Date>>();
//var l = new System.Collections.Generic.List$1<Date>();
//l.Add(new Date())
//z[""LLL""] = l;
//z[""qwert""] = new System.Collections.Generic.List$1<Date>();//ignore
//z[""qwert""].Add(new Date());
function ExecuteRequest(value) {
return value + '-123';
}
var z = '123';
";
var jsScript = tsEngine.CompileScript(tsScript);
await tsEngine.ExecuteAsync(jsScript);
var f = tsEngine.GetFunction("ExecuteRequest");
if (f != null)
{
var n = tsEngine.InvokeFunction("ExecuteRequest", "Bernhard");
}
var m = tsEngine.GetModuleState<GlobalVariablesModule>();
//var z = tsEngine.GetValue<string>("z");
//var y = tsEngine.GetValue("y");
var obj = tsEngine.GetValue("z");
//var methods = tsEngine.GetValue("methods");
//Console.WriteLine(z);
}
private static async Task ExecutePowershell()
{
var tsEngine = ServiceProvider.GetRequiredNamedService<IScriptEngine>("PowerShellCore");
var tsScript = @"
$d = Get-Date
function ExecuteRequest($name) {
return ""$($name)-123 - $($d)"";
}
";
await tsEngine.ExecuteAsync(tsScript);
var ret = tsEngine.GetFunction("ExecuteRequest");
if (ret != null)
{
var n = tsEngine.InvokeFunction("ExecuteRequest", "Bernhard");
}
}
}
}
|
using System.Collections.Generic;
using UnityEngine;
namespace AID
{
/// <summary>
/// Binds and routes Console requirements to DevConsoleUI Gameobjects, UI, and user input.
/// </summary>
[RequireComponent(typeof(DevConsoleUI))]
public class DevConsoleBinding : MonoBehaviour
{
private DevConsoleUI devConsole;
private List<string> bindingErrors = new List<string>();
public void Awake()
{
devConsole = GetComponent<DevConsoleUI>();
ConsoleBindingHelper.OnErrorLogDelegate = BindingLog;
ConsoleBindingHelper.RegisterAttributes();
if (bindingErrors.Count > 0)
UnityEngine.Debug.LogWarning(bindingErrors.Count.ToString() + " errors during RegisterAttributes");
ConsoleBindingHelper.OnErrorLogDelegate = UnityEngine.Debug.LogError;
bindingErrors.Clear();
}
private void BindingLog(string obj)
{
bindingErrors.Add(obj);
}
public void OnEnable()
{
Console.OnOutputUpdated += devConsole.AddToMainOutput;
devConsole.OnConsoleCommandInput += RunConsoleCommand;
devConsole.OnConsoleCompleteRequested += Console.Complete;
Console.RegisterCommand("clear", "clears the output text of the console", (s) => devConsole.ClearMainOutput());
}
public void OnDisable()
{
Console.OnOutputUpdated -= devConsole.AddToMainOutput;
devConsole.OnConsoleCommandInput -= RunConsoleCommand;
devConsole.OnConsoleCompleteRequested -= Console.Complete;
Console.DeregisterCommand("clear");
}
private void RunConsoleCommand(string input)
{
Console.Run(input);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace GetAllParens
{
class Program
{
static void Main(string[] args)
{
foreach (string paren in GetAllParens(3, 3))
{
Console.WriteLine(paren);
}
Console.Read();
}
/// <summary>
/// Get all valid parenthesis combinations with L open- and R- closing- parenthesis
/// </summary>
/// <param name="L">How many left parenthesis left</param>
/// <param name="R">How many right parenthesis left</param>
/// <remarks>
/// Cases:
/// 0. L==R==0:
/// can only break return ""
/// 1. L==R!=0:
/// can only open a parenthesis. And continue with L-1, R
/// 2. L<R, L!=0:
/// start with a "(", continue with L-1, R
/// ...and...
/// start with a ")", continue with L, R-1
/// 3. L==0, L<R (left parenthesis is used out):
/// start with ")", continue with L, R-1
///
/// Merging the four cases, we have:
/// if (case0):
/// break return ""
/// if (L<=R, L!=0): // merging case 1 and 2
/// start with "(", continue with L-1,R
/// if (R!=0): //merging case 2 and 3
/// start with ")", continue with L, R-1
///
/// Note we need (R!=0) to guard. If not, we will have a case where L!=0, so take ")"
/// and R-1, then R eventually got below 0 and stack overflow.
///
/// Note that this recursive will have repetitive computing. DP can solve that (TODO).
/// </remarks>
static public IEnumerable<string> GetAllParens(int L, int R)
{
if (L == R && L == 0)
{
yield return "";
yield break;
}
if (L <= R && L > 0)
{
foreach (string s in GetAllParens(L-1,R))
{
yield return "(" + s;
}
}
if (L < R)
{
foreach (string s in GetAllParens(L, R-1))
{
yield return ")" + s;
}
}
}
}
}
|
namespace WebMarkupMin.Core.Configuration
{
using System.Configuration;
/// <summary>
/// Configuration settings of code minification
/// </summary>
public abstract class CodeMinificationConfigurationBase : ConfigurationElement
{
/// <summary>
/// Gets a name of default code minifier
/// </summary>
public abstract string DefaultMinifier
{
get;
set;
}
/// <summary>
/// Gets a list of registered code minifiers
/// </summary>
[ConfigurationProperty("minifiers", IsRequired = true)]
public CodeMinifierRegistrationList Minifiers
{
get { return (CodeMinifierRegistrationList)this["minifiers"]; }
}
}
} |
using System;
namespace MZcms.Core
{
/// <summary>
/// 平台不支持异常
/// </summary>
public class PlatformNotSupportedException : MZcmsException
{
public PlatformNotSupportedException(PlatformType platformType)
: base("不支持" + platformType.ToDescription() + "平台")
{
Log.Info(this.Message, this);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DriveMgr.IDAL;
using System.Data.SqlClient;
using System.Data;
namespace DriveMgr.SQLServerDAL
{
public class VehiclMaintenanceDAL:IVehiclMaintenanceDAL
{
/// <summary>
/// 增加一条数据
/// </summary>
public bool AddVehiclMaintenance(Model.VehiclMaintenanceModel model)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("insert into tb_VehiclMaintenance(");
strSql.Append("VehicleId,MaintenanceType,MaintenCosts,MaintenPerson,MaintenDate,Remark,CreatePerson,CreateDate,UpdatePerson,UpdateDate,DeleteMark)");
strSql.Append(" values (");
strSql.Append("@VehicleId,@MaintenanceType,@MaintenCosts,@MaintenPerson,@MaintenDate,@Remark,@CreatePerson,@CreateDate,@UpdatePerson,@UpdateDate,@DeleteMark)");
SqlParameter[] parameters = {
new SqlParameter("@VehicleId", SqlDbType.Int,4),
new SqlParameter("@MaintenanceType", SqlDbType.Int,4),
new SqlParameter("@MaintenCosts", SqlDbType.Money,8),
new SqlParameter("@MaintenPerson", SqlDbType.VarChar,50),
new SqlParameter("@Remark", SqlDbType.VarChar,100),
new SqlParameter("@CreatePerson", SqlDbType.VarChar,50),
new SqlParameter("@CreateDate", SqlDbType.DateTime),
new SqlParameter("@UpdatePerson", SqlDbType.VarChar,50),
new SqlParameter("@UpdateDate", SqlDbType.DateTime),
new SqlParameter("@DeleteMark", SqlDbType.Bit,1),
new SqlParameter("@MaintenDate", SqlDbType.DateTime)};
parameters[0].Value = model.VehicleId;
parameters[1].Value = model.MaintenanceType;
parameters[2].Value = model.MaintenCosts;
parameters[3].Value = model.MaintenPerson;
parameters[4].Value = model.Remark;
parameters[5].Value = model.CreatePerson;
parameters[6].Value = model.CreateDate;
parameters[7].Value = model.UpdatePerson;
parameters[8].Value = model.UpdateDate;
parameters[9].Value = model.DeleteMark;
parameters[10].Value = model.MaintenDate;
int rows = DriveMgr.Common.SqlHelper.ExecuteNonQuery(DriveMgr.Common.SqlHelper.financialMgrConn, CommandType.Text, strSql.ToString(), parameters);
if (rows > 0)
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// 更新一条数据
/// </summary>
public bool UpdateVehiclMaintenance(Model.VehiclMaintenanceModel model)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("update tb_VehiclMaintenance set ");
strSql.Append("VehicleId=@VehicleId,");
strSql.Append("MaintenanceType=@MaintenanceType,");
strSql.Append("MaintenCosts=@MaintenCosts,");
strSql.Append("MaintenPerson=@MaintenPerson,");
strSql.Append("Remark=@Remark,");
strSql.Append("CreatePerson=@CreatePerson,");
strSql.Append("CreateDate=@CreateDate,");
strSql.Append("UpdatePerson=@UpdatePerson,");
strSql.Append("UpdateDate=@UpdateDate,");
strSql.Append("DeleteMark=@DeleteMark, ");
strSql.Append("MaintenDate=@MaintenDate ");
strSql.Append(" where Id=@Id");
SqlParameter[] parameters = {
new SqlParameter("@VehicleId", SqlDbType.Int,4),
new SqlParameter("@MaintenanceType", SqlDbType.Int,4),
new SqlParameter("@MaintenCosts", SqlDbType.Money,8),
new SqlParameter("@MaintenPerson", SqlDbType.VarChar,50),
new SqlParameter("@Remark", SqlDbType.VarChar,100),
new SqlParameter("@CreatePerson", SqlDbType.VarChar,50),
new SqlParameter("@CreateDate", SqlDbType.DateTime),
new SqlParameter("@UpdatePerson", SqlDbType.VarChar,50),
new SqlParameter("@UpdateDate", SqlDbType.DateTime),
new SqlParameter("@DeleteMark", SqlDbType.Bit,1),
new SqlParameter("@MaintenDate", SqlDbType.DateTime),
new SqlParameter("@Id", SqlDbType.Int,4)};
parameters[0].Value = model.VehicleId;
parameters[1].Value = model.MaintenanceType;
parameters[2].Value = model.MaintenCosts;
parameters[3].Value = model.MaintenPerson;
parameters[4].Value = model.Remark;
parameters[5].Value = model.CreatePerson;
parameters[6].Value = model.CreateDate;
parameters[7].Value = model.UpdatePerson;
parameters[8].Value = model.UpdateDate;
parameters[9].Value = model.DeleteMark;
parameters[10].Value = model.MaintenDate;
parameters[11].Value = model.Id;
object obj = DriveMgr.Common.SqlHelper.ExecuteNonQuery(DriveMgr.Common.SqlHelper.financialMgrConn, CommandType.Text, strSql.ToString(), parameters);
if (Convert.ToInt32(obj) > 0)
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// 删除一条数据
/// </summary>
public bool DeleteVehiclMaintenance(int id)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("Update tb_VehiclMaintenance Set DeleteMark = 1 ");
strSql.Append(" where Id=@Id");
SqlParameter[] parameters = {
new SqlParameter("@Id", SqlDbType.Int,4)
};
parameters[0].Value = id;
object obj = DriveMgr.Common.SqlHelper.ExecuteNonQuery(DriveMgr.Common.SqlHelper.financialMgrConn, CommandType.Text, strSql.ToString(), parameters);
if (Convert.ToInt32(obj) > 0)
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// 批量删除数据
/// </summary>
public bool DeleteVehiclMaintenanceList(string idlist)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("Update tb_VehiclMaintenance Set DeleteMark = 1 ");
strSql.Append(" where Id in (" + idlist + ") ");
try
{
DriveMgr.Common.SqlHelper.ExecuteNonQuery(DriveMgr.Common.SqlHelper.financialMgrConn, CommandType.Text, strSql.ToString());
return true;
}
catch (Exception ex)
{
return false;
}
}
/// <summary>
/// 得到一个对象实体
/// </summary>
public Model.VehiclMaintenanceModel GetVehiclMaintenanceModel(int id)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("select top 1 Id,VehicleId,MaintenanceType,MaintenCosts,MaintenDate,MaintenPerson,Remark,CreatePerson,CreateDate,UpdatePerson,UpdateDate,DeleteMark from tb_VehiclMaintenance ");
strSql.Append(" where Id=@Id");
SqlParameter[] parameters = {
new SqlParameter("@Id", SqlDbType.Int,4)
};
parameters[0].Value = id;
Model.VehiclMaintenanceModel model = new Model.VehiclMaintenanceModel();
DataSet ds = DriveMgr.Common.SqlHelper.GetDataset(DriveMgr.Common.SqlHelper.financialMgrConn, CommandType.Text, strSql.ToString(), parameters);
if (ds.Tables[0].Rows.Count > 0)
{
return DataRowToModel(ds.Tables[0].Rows[0]);
}
else
{
return null;
}
}
/// <summary>
/// 得到一个对象实体
/// </summary>
private Model.VehiclMaintenanceModel DataRowToModel(DataRow row)
{
Model.VehiclMaintenanceModel model = new Model.VehiclMaintenanceModel();
if (row != null)
{
if (row["Id"] != null && row["Id"].ToString() != "")
{
model.Id = int.Parse(row["Id"].ToString());
}
if (row["VehicleId"] != null && row["VehicleId"].ToString() != "")
{
model.VehicleId = int.Parse(row["VehicleId"].ToString());
}
if (row["MaintenanceType"] != null && row["MaintenanceType"].ToString() != "")
{
model.MaintenanceType = int.Parse(row["MaintenanceType"].ToString());
}
if (row["MaintenCosts"] != null && row["MaintenCosts"].ToString() != "")
{
model.MaintenCosts = decimal.Parse(row["MaintenCosts"].ToString());
}
if (row["MaintenPerson"] != null)
{
model.MaintenPerson = row["MaintenPerson"].ToString();
}
if (row["Remark"] != null)
{
model.Remark = row["Remark"].ToString();
}
if (row["CreatePerson"] != null)
{
model.CreatePerson = row["CreatePerson"].ToString();
}
if (row["CreateDate"] != null && row["CreateDate"].ToString() != "")
{
model.CreateDate = DateTime.Parse(row["CreateDate"].ToString());
}
if (row["UpdatePerson"] != null)
{
model.UpdatePerson = row["UpdatePerson"].ToString();
}
if (row["UpdateDate"] != null && row["UpdateDate"].ToString() != "")
{
model.UpdateDate = DateTime.Parse(row["UpdateDate"].ToString());
}
if (row["MaintenDate"] != null && row["MaintenDate"].ToString() != "")
{
model.MaintenDate = DateTime.Parse(row["MaintenDate"].ToString());
}
if (row["DeleteMark"] != null && row["DeleteMark"].ToString() != "")
{
if ((row["DeleteMark"].ToString() == "1") || (row["DeleteMark"].ToString().ToLower() == "true"))
{
model.DeleteMark = true;
}
else
{
model.DeleteMark = false;
}
}
}
return model;
}
/// <summary>
/// 获取分页数据
/// </summary>
/// <param name="tableName">表名</param>
/// <param name="columns">要取的列名(逗号分开)</param>
/// <param name="order">排序</param>
/// <param name="pageSize">每页大小</param>
/// <param name="pageIndex">当前页</param>
/// <param name="where">查询条件</param>
/// <param name="totalCount">总记录数</param>
public string GetPagerData(string tableName, string columns, string order, int pageSize, int pageIndex, string where, out int totalCount)
{
DataTable dt = DriveMgr.Common.SqlPagerHelper.GetPagerData(DriveMgr.Common.SqlHelper.financialMgrConn, tableName, columns, order, pageSize, pageIndex, where, out totalCount);
return DriveMgr.Common.JsonHelper.ToJson(dt);
}
}
}
|
using System;
using System.Dynamic;
using System.Net;
using System.Net.Http;
using doob.Scripter.Module.Http.ExtensionMethods;
namespace doob.Scripter.Module.Http
{
public class HttpResponse : IDisposable
{
private readonly HttpResponseMessage _httpResponseMessage;
public Version Version => _httpResponseMessage.Version;
private GenericHttpContent? _content;
public GenericHttpContent Content => _content ??= new GenericHttpContent(_httpResponseMessage.Content);
private ExpandoObject? _contentHeaders;
public ExpandoObject? ContentHeaders => _contentHeaders ??= _httpResponseMessage.Content.Headers.ToExpandoObject();
public HttpStatusCode StatusCode => _httpResponseMessage.StatusCode;
public string? ReasonPhrase => _httpResponseMessage.ReasonPhrase;
private ExpandoObject? _headers;
public ExpandoObject? Headers => _headers ??= _httpResponseMessage.Headers.ToExpandoObject();
private ExpandoObject? _trailingheaders;
public ExpandoObject? TrailingHeaders => _trailingheaders ??= _httpResponseMessage.TrailingHeaders.ToExpandoObject();
public bool IsSuccessStatusCode => _httpResponseMessage.IsSuccessStatusCode;
public HttpResponse EnsureSuccessStatusCode()
{
_httpResponseMessage.EnsureSuccessStatusCode();
return this;
}
public override string ToString() => _httpResponseMessage.ToString();
internal HttpResponse(HttpResponseMessage httpResponseMessage)
{
_httpResponseMessage = httpResponseMessage;
//Content = new GenericHttpContent(_httpResponseMessage.Content);
}
public void Dispose()
{
_httpResponseMessage?.Dispose();
}
}
} |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DataAccess;
namespace BusinessLogic
{
public class Business
{
static InterfaceForAdoEntity DB;
public void getData(int id, string name, string accType, int balance)
{
GetReferenceForObj();
try
{
DB.insert(id, name, accType, balance);
}
catch (Exception ex)
{
Console.WriteLine("Account Already Exists");
}
}
public void GetReferenceForObj()
{
string databaseCOnnectivity = ConfigurationManager.AppSettings["DatabaseConnectivity"].ToString();
int option; //currently set to 2 in appconfig file. change it to 1 to access ado.net file
Int32.TryParse(databaseCOnnectivity, out option);
if (option == 1)
{
Console.WriteLine("Working through ADO.net");
DB = new DataConnectUsingAdo();
}
else if (option == 2)
{
Console.WriteLine("Working through Entity Framework");
DB = new DataConnectEntityFW();
}
}
public void ShowDetails(int id)
{
GetReferenceForObj();
DB.View(id);
}
public void withdraw(int id, int amount)
{
int balance = DB.getBalance(id);
string type = DB.getType(id).Trim();
Console.WriteLine(balance + " " + type);
if (type.Equals("S") && (balance - amount) > 1000)
{
balance = balance - amount;
DB.update(id, balance);
}
else if (type == "C" && balance - amount >= 0)
{
balance = balance - amount;
DB.update(id, balance);
}
else if (type == "D" && balance - amount >= -10000)
{
balance = balance - amount;
DB.update(id, balance);
}
else
{
Console.WriteLine("Balance Insufficient");
}
}
public void deposit(int id, int amount)
{
int balance = DB.getBalance(id);
balance = balance + amount;
DB.update(id, balance);
}
public float interest(int id)
{
int balance = DB.getBalance(id);
string type = DB.getType(id).Trim();
if (type == "S")
{
return balance * 4 / 100;
}
else if (type == "C")
{
return balance * 1 / 100;
}
else
{
return 0;
}
}
/* public int checkIfExists(int id)
{
if(DB.IdExists(id))
{
return false;
}
return true;
}*/
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ws_seta.Models;
namespace ws_seta.Controllers
{
public class VariacaoResource
{
public List<Variacao> variacoes { get; set; }
}
} |
using iQuest.VendingMachine.PresentationLayer.Views.Interfaces;
using iQuest.VendingMachine.Payment.Interfaces;
namespace iQuest.VendingMachine.Payment.Services
{
internal class CardPayment : IPaymentAlgorithm
{
public ICardPaymentView cardView { get; set; }
public string Name { get => "CREDIT CARD"; }
public CardPayment(ICardPaymentView cardView)
{
this.cardView = cardView;
}
public void Run(float price, string name)
{
cardView.AskForCardNumber(price, name);
}
}
}
|
using System;
using System.Collections.Generic;
namespace RestApiEcom.Models
{
public partial class TIaIndicateurAssocie
{
public int IaIndId { get; set; }
public int? IaIndIaId { get; set; }
public string IaIndIndCode { get; set; }
public virtual TIaIndicateur IaIndIa { get; set; }
public virtual TIndicateur IaIndIndCodeNavigation { get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Shoot : MonoBehaviour {
public float attackRange = 2;
public int damage = 0;
public GameObject arrowPrefab;
public Transform shootPoint;
Vector3 mousePositionOnScreen;
Vector3 screenPosition;
Vector3 mousePositionInWorld;
private GameObject arrow;
[SerializeField]
private float shootSpeed = 0.12f;
private Player player;
float dis = 0;
public bool hasTarget = false;
public GameObject enemys = null;
private float timer = 2;
public List<AudioClip> clips;
// Use this for initialization
void Start () {
player = GetComponent<Player>();
damage = PlayerMes.getInstance().Attack;
}
// Update is called once per frame
void Update () {
shootTo();
startAttack();
}
private void OnDrawGizmos()
{
//Gizmos.color = Color.red;
//Gizmos.DrawWireSphere(this.transform.position, attackRange);
}
void ShootTo()
{
if (enemys == null) return;
arrow = Instantiate(arrowPrefab, shootPoint.position, transform.rotation) as GameObject;
if (clips.Count!= 0)
{
MusicManager.Instance.PlayMusic(clips[Random.Range(0, clips.Count)]);
}
Self se = arrow.gameObject.GetComponent<Self>();
Weapon weapon = arrow.gameObject.GetComponent<Weapon>();
weapon.damage = damage + (int)Random.Range(-damage * 0.1f, damage * 0.1f);
se.point = enemys.transform.parent.parent.position;
se.point.y += (enemys.gameObject.GetComponent<Collider>().bounds.size.y)/2.0f;
se.shootSpeed = this.shootSpeed;
}
void shootTo()
{
if (hasTarget)
{
transform.LookAt(new Vector3(enemys.transform.parent.parent.position.x,transform.position.y, enemys.transform.parent.parent.position.z));
}
else
{
enemys = null;
Animator animator = transform.GetComponent<Animator>();
animator.SetBool("isAttacking", false);
}
}
void startAttack()
{
if (enemys == null) return;
dis = (gameObject.transform.position - enemys.transform.position).magnitude;
Animator animator = transform.GetComponent<Animator>();
if (dis <= attackRange && hasTarget)
{
animator.SetBool("isAttacking", true);
player.target = this.transform.position;
}
else if (dis > attackRange)
{
player.target = new Vector3(enemys.transform.position.x, player.transform.position.y, enemys.transform.position.z);
animator.SetBool("isAttacking", false);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Battleships
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
public int[,] buttonListPlayer1 = new int[10, 10]
{
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } ,
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } ,
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } ,
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } ,
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } ,
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } ,
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } ,
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } ,
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } ,
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } ,
};
public void MyGrid_Loaded(object sender, RoutedEventArgs e)
{
for(int i = 0; i < 10; i++)
{
var row = new RowDefinition();
row.Height = new GridLength(45);
BattleGround.RowDefinitions.Add(row);
var col = new ColumnDefinition();
col.Width = new GridLength(50);
BattleGround.ColumnDefinitions.Add(col);
for (int j = 0; j < 10; j++)
{
var button = new Button();
int[,] buttonListPlayer1 = new int[10, 10];
button.Click += new RoutedEventHandler((x, y) => {
var Row = Grid.GetRow(button);
var Column = Grid.GetColumn(button);
buttonListPlayer1[Row, Column] = 1;
if (buttonListPlayer1 = 1)
{
button.Content = 1;
}
});
Grid.SetRow(button, i);
Grid.SetColumn(button, j);
BattleGround.Children.Add(button);
}
}
}
private void MyGrid_Loaded2(object sender, RoutedEventArgs e)
{
for (int i = 0; i < 10; i++)
{
var row = new RowDefinition();
row.Height = new GridLength(45);
BattleGround2.RowDefinitions.Add(row);
var col = new ColumnDefinition();
col.Width = new GridLength(50);
BattleGround2.ColumnDefinitions.Add(col);
for (int j = 0; j < 10; j++)
{
var button = new Button();
Grid.SetRow(button, i);
Grid.SetColumn(button, j);
BattleGround2.Children.Add(button);
}
}
}
public void Game()
{
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BossWin : MonoBehaviour
{
[SerializeField] private GameObject boss;
[SerializeField] private GameObject winText;
[SerializeField] private GameObject reward;
[SerializeField] private GameObject ground;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if(boss == null)
{
AudioManager.PlaySound("levelUp", 1f);
reward.SetActive(true);
ground.SetActive(true);
winText.SetActive(true);
Destroy(gameObject);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CharacterSelectInputController : MenuInputController {
private bool[] m_submitTriggerList = new bool[4];
private bool[] m_previousTriggerList = new bool[4];
private bool[] m_pauseTriggerList = new bool[4];
private bool[] m_changeColorTriggerList = new bool[4];
private bool[] m_upTriggerList = new bool[4];
private bool[] m_downTriggerList = new bool[4];
private bool[] m_leftTriggerList = new bool[4];
private bool[] m_rightTriggerList = new bool[4];
void Start(){
for(int i = 0; i < 4; i++){
m_submitTriggerList[i] = false;
m_previousTriggerList[i] = false;
m_pauseTriggerList[i] = false;
m_changeColorTriggerList[i] = false;
m_upTriggerList[i] = false;
m_downTriggerList[i] = false;
m_leftTriggerList[i] = false;
m_rightTriggerList[i] = false;
}
}
public override void Update()
{
for(int i = 0; i < 4; i++){
// reset triggers when button released
m_submitTriggerList[i] = !InputMgr.GetMenuButton(i + 1, InputMgr.eMenuButton.SUBMIT) || m_submitTriggerList[i];
m_previousTriggerList[i] = !InputMgr.GetMenuButton(i + 1, InputMgr.eMenuButton.PREVIOUS) || m_previousTriggerList[i];
m_pauseTriggerList[i] = !InputMgr.GetMenuButton(i + 1, InputMgr.eMenuButton.PAUSE) || m_pauseTriggerList[i];
m_changeColorTriggerList[i] = !InputMgr.GetMenuButton(i + 1, InputMgr.eMenuButton.CHANGE_COLOR) || m_changeColorTriggerList[i];
m_upTriggerList[i] = !InputMgr.GetMenuButton(i + 1, InputMgr.eMenuButton.UP) || m_upTriggerList[i];
m_downTriggerList[i] = !InputMgr.GetMenuButton(i + 1, InputMgr.eMenuButton.DOWN) || m_downTriggerList[i];
m_leftTriggerList[i] = !InputMgr.GetMenuButton(i + 1, InputMgr.eMenuButton.LEFT) || m_leftTriggerList[i];
m_rightTriggerList[i] = !InputMgr.GetMenuButton(i + 1, InputMgr.eMenuButton.RIGHT) || m_rightTriggerList[i];
}
}
public bool GetSubmit(int player)
{
if (m_submitTriggerList[player] && InputMgr.GetMenuButton(player + 1, InputMgr.eMenuButton.SUBMIT))
{
m_submitTriggerList[player] = false;
return true;
}
return false;
}
public bool GetPrevious(int player)
{
if (m_previousTriggerList[player] && InputMgr.GetMenuButton(player + 1, InputMgr.eMenuButton.PREVIOUS))
{
m_previousTriggerList[player] = false;
return true;
}
return false;
}
public bool GetPause(int player)
{
if (m_pauseTriggerList[player] && InputMgr.GetMenuButton(player + 1, InputMgr.eMenuButton.PAUSE))
{
m_pauseTriggerList[player] = false;
return true;
}
return false;
}
public bool GetChangeColor(int player)
{
if (m_changeColorTriggerList[player] && InputMgr.GetMenuButton(player + 1, InputMgr.eMenuButton.CHANGE_COLOR))
{
m_changeColorTriggerList[player] = false;
return true;
}
return false;
}
// ======================================================================================
public bool GetUp(int player)
{
if (m_upTriggerList[player] && InputMgr.GetMenuButton(player + 1, InputMgr.eMenuButton.UP))
{
m_upTriggerList[player] = false;
return true;
}
return false;
}
// ======================================================================================
public bool GetDown(int player)
{
if (m_downTriggerList[player] && InputMgr.GetMenuButton(player + 1, InputMgr.eMenuButton.DOWN))
{
m_downTriggerList[player] = false;
return true;
}
return false;
}
// ======================================================================================
public bool GetLeft(int player)
{
if (m_leftTriggerList[player] && InputMgr.GetMenuButton(player + 1, InputMgr.eMenuButton.LEFT))
{
m_leftTriggerList[player] = false;
return true;
}
return false;
}
// ======================================================================================
public bool GetRight(int player)
{
if (m_rightTriggerList[player] && InputMgr.GetMenuButton(player + 1, InputMgr.eMenuButton.RIGHT))
{
m_rightTriggerList[player] = false;
return true;
}
return false;
}
}
|
namespace OCP.Group.Backend
{
/**
* @since 17.0.0
*/
public interface IGetDisplayNameBackend:IBackend
{
/**
* @since 17.0.0
*/
string getDisplayName(string gid);
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace Models
{
public class tb_Reserve
{
public tb_Reserve()
{ }
#region Models
private int _id;
private string _ReserveType;
private string _ReserveInfo;
public int id
{
set { _id = value; }
get { return _id; }
}
public string ReserveType
{
set { _ReserveType = value; }//当给userName赋值时:userName=ss;则先执行set
get { return _ReserveType; }//当是从userName读取时,XX=userName则先执行get
}
public string ReserveInfo
{
set { _ReserveInfo = value; }
get { return _ReserveInfo; }
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using NHibernate;
using Soko.Exceptions;
using Soko.Domain;
using Soko;
namespace Bilten.Dao.NHibernate
{
/// <summary>
/// NHibernate-specific implementation of <see cref="MesecnaClanarinaDAO"/>.
/// </summary>
public class MesecnaClanarinaDAOImpl : GenericNHibernateDAO<MesecnaClanarina, int>, MesecnaClanarinaDAO
{
#region MesecnaClanarinaDAO Members
public virtual bool existsClanarinaGrupa(Grupa g)
{
try
{
IQuery q = Session.CreateQuery("select count(*) from MesecnaClanarina mc where mc.Grupa = :grupa");
q.SetEntity("grupa", g);
return (long)q.UniqueResult() > 0;
}
catch (HibernateException ex)
{
string message = String.Format(
"{0} \n\n{1}", Strings.DatabaseAccessExceptionMessage, ex.Message);
throw new InfrastructureException(message, ex);
}
}
public virtual IList<MesecnaClanarina> getCenovnik()
{
// NOTE: Correlated subqueries don't work in SQL Server Compact
try
{
IQuery q = Session.CreateQuery(@"from MesecnaClanarina mc
left join fetch mc.Grupa
order by mc.Grupa.Id asc, mc.VaziOd desc");
IList<MesecnaClanarina> result = q.List<MesecnaClanarina>();
List<MesecnaClanarina> result2 = new List<MesecnaClanarina>();
int prevId = -1;
foreach (MesecnaClanarina mc in result)
{
if (mc.Grupa.Id != prevId)
{
result2.Add(mc);
prevId = mc.Grupa.Id;
}
}
return result2;
}
catch (HibernateException ex)
{
string message = String.Format(
"{0} \n\n{1}", Strings.DatabaseAccessExceptionMessage, ex.Message);
throw new InfrastructureException(message, ex);
}
}
public virtual IList<MesecnaClanarina> findForGrupa(Grupa g)
{
try
{
IQuery q = Session.CreateQuery(@"from MesecnaClanarina mc left join fetch mc.Grupa g where g = :grupa");
q.SetEntity("grupa", g);
return q.List<MesecnaClanarina>();
}
catch (HibernateException ex)
{
string message = String.Format(
"{0} \n\n{1}", Strings.DatabaseAccessExceptionMessage, ex.Message);
throw new InfrastructureException(message, ex);
}
}
public virtual MesecnaClanarina getVazecaClanarinaForGrupa(Grupa g)
{
try
{
IQuery q = Session.CreateQuery(@"from MesecnaClanarina mc
left join fetch mc.Grupa g
where g = :grupa
order by mc.VaziOd desc");
q.SetEntity("grupa", g);
IList<MesecnaClanarina> result = q.List<MesecnaClanarina>();
if (result.Count > 0)
return result[0];
else
return null;
}
catch (HibernateException ex)
{
string message = String.Format(
"{0} \n\n{1}", Strings.DatabaseAccessExceptionMessage, ex.Message);
throw new InfrastructureException(message, ex);
}
}
public virtual MesecnaClanarina findForGrupaVaziOd(Grupa g, DateTime vaziOd)
{
try
{
IQuery q = Session.CreateQuery(@"from MesecnaClanarina mc
left join fetch mc.Grupa g
where g = :grupa and mc.VaziOd = :vaziOd");
q.SetEntity("grupa", g);
q.SetDateTime("vaziOd", vaziOd);
IList<MesecnaClanarina> result = q.List<MesecnaClanarina>();
if (result.Count > 0)
return result[0];
else
return null;
}
catch (HibernateException ex)
{
string message = String.Format(
"{0} \n\n{1}", Strings.DatabaseAccessExceptionMessage, ex.Message);
throw new InfrastructureException(message, ex);
}
}
// TODO2: Izbaciti sort_order kolonu iz table grupe
public virtual List<object[]> getCenovnikReportItems()
{
try
{
IQuery q = Session.CreateQuery(@"from MesecnaClanarina mc
left join fetch mc.Grupa
order by mc.Grupa.Sifra.BrojGrupe asc, mc.Grupa.Sifra.Podgrupa asc, mc.VaziOd desc");
IList<MesecnaClanarina> result = q.List<MesecnaClanarina>();
List<object[]> result2 = new List<object[]>();
int prevId = -1;
foreach (MesecnaClanarina mc in result)
{
if (mc.Grupa.Id != prevId)
{
result2.Add(new object[] { mc.Grupa.Sifra.Value, mc.Grupa.Naziv, mc.Iznos, mc.VaziOd });
prevId = mc.Grupa.Id;
}
}
return result2;
}
catch (HibernateException ex)
{
string message = String.Format(
"{0} \n\n{1}", Strings.DatabaseAccessExceptionMessage, ex.Message);
throw new InfrastructureException(message, ex);
}
}
#endregion
public override IList<MesecnaClanarina> FindAll()
{
try
{
IQuery q = Session.CreateQuery(@"from MesecnaClanarina");
return q.List<MesecnaClanarina>();
}
catch (HibernateException ex)
{
string message = String.Format(
"{0} \n\n{1}", Strings.DatabaseAccessExceptionMessage, ex.Message);
throw new InfrastructureException(message, ex);
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mime;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using QI.WikiScraping.Api.Application.Services;
namespace QI.WikiScraping.Api.Controllers.V1
{
[ApiVersion("1.0")]
[Route("api/V{version:apiVersion}/[controller]")]
[ApiController]
[Produces(MediaTypeNames.Application.Json)]
[Consumes(MediaTypeNames.Application.Json)]
public class WikiArticleController : ControllerBase
{
private readonly ILogger<WikiArticleController> _logger;
private readonly IWikiScraperService _wikiScraperService;
public WikiArticleController(ILogger<WikiArticleController> logger,
IWikiScraperService wikiScraperService)
{
_logger = logger;
_wikiScraperService = wikiScraperService;
}
/// <summary>
///
/// </summary>
/// <param name="productType"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
[Route(nameof(DifferentWords))]
[HttpGet]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task<ActionResult> DifferentWords(string wikiArticleUrl, CancellationToken cancellationToken)
{
_logger.LogInformation($"Ini--{nameof(WikiArticleController)}.{nameof(DifferentWords)} for Url: '{wikiArticleUrl}'");
//Validate the Url from Wikipedia at this point
var response = await _wikiScraperService.GetContentFromArticle(wikiArticleUrl, cancellationToken);
_logger.LogInformation($"End--{nameof(WikiArticleController)}.{nameof(DifferentWords)} for Url: '{wikiArticleUrl}'");
return Ok($"The article has the number of different words: '{response}'");
}
}
}
|
using System;
using System.Globalization;
using System.IO;
using System.Text;
using Newtonsoft.Json;
using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities;
using OmniSharp.Extensions.LanguageServer.Protocol.Serialization;
using ISerializer = OmniSharp.Extensions.JsonRpc.ISerializer;
namespace Lsp.Tests
{
internal static class Fixture
{
public static string SerializeObject(object value, ClientVersion version = ClientVersion.Lsp3) => SerializeObject(value, null, null, version);
public static string SerializeObject(object value, Type? type, JsonSerializerSettings? settings, ClientVersion version = ClientVersion.Lsp3)
{
var jsonSerializer = new LspSerializer(version);
return SerializeObjectInternal(value, type, jsonSerializer);
}
private static string SerializeObjectInternal(object value, Type? type, ISerializer serializer)
{
var sb = new StringBuilder(256);
var sw = new StringWriter(sb, CultureInfo.InvariantCulture);
using (var jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.Formatting = Formatting.Indented;
jsonWriter.Indentation = 4;
serializer.JsonSerializer.Serialize(jsonWriter, value, type);
}
return sw.ToString().Replace("\r\n", "\n").TrimEnd(); //?.Replace("\n", "\r\n");
}
}
}
|
using System;
namespace RO
{
[CustomLuaClass]
public class LuaGameObjectClickable : LuaGameObject
{
public int clickPriority = 999;
}
}
|
namespace AthleteBuilder.Model
{
public class Athlete
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int BirthYear { get; set; }
public string Club { get; set; }
public string Sexe { get; set; }
public bool Malus { get; set; }
public ChampVsIndoor ChampVsIndoor { get; } = new ChampVsIndoor();
public TourneeCross TourneeCross { get; } = new TourneeCross();
public FinaleGruyere FinaleGruyere { get; } = new FinaleGruyere();
public FinaleSprint FinaleSprint { get; } = new FinaleSprint();
public ChampVsOutdoor ChampVsOutdoor { get; } = new ChampVsOutdoor();
public ChampVsMultiple ChampVsMultiple { get; } = new ChampVsMultiple();
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ClassSpecDescription : MonoBehaviour {
public Text classOrSpecText;
public Image icon;
public Text _name;
public Text description;
public static Transform tr;
public static Vector3 initPos;
private void OnEnable()
{
ItemInGrid.onItemClicked += ChangeDescription;
}
private void OnDisable()
{
ItemInGrid.onItemClicked -= ChangeDescription;
}
private void Awake()
{
tr = transform;
initPos = transform.position;
}
void ChangeDescription(ItemInGrid.DescriptionStruct desc)
{
HeroDescription.tr.position = new Vector3(10000, HeroDescription.initPos.y, HeroDescription.initPos.z);
tr.position = initPos;
//classOrSpecText.text = desc.classOrSpec;
icon.sprite = desc.icon;
_name.text = desc.classOrSpec + ": " + "\n" + desc._name;
description.text = desc.description;
}
}
|
using System;
namespace Objects
{
public sealed class Snake : Animal
{
public Snake() : base(nameof(Snake))
{
}
public override void Move()
{
Console.WriteLine("Crawling");
}
public override void Sound()
{
Console.WriteLine("Hiss");
}
}
}
|
using NUnit.Framework;
using System.Collections.Generic;
namespace Logs.Models.Tests.LogEntryTests
{
[TestFixture]
public class PropertiesTests
{
[TestCase(1)]
[TestCase(12)]
[TestCase(431)]
[TestCase(21311)]
[TestCase(1209731)]
[TestCase(5665)]
[TestCase(123)]
[TestCase(11)]
public void TestLogEntryId_ShouldInitializeCorrectly(int logEntryId)
{
// Arrange
var logEntry = new LogEntry();
// Act
logEntry.LogEntryId = logEntryId;
// Assert
Assert.AreEqual(logEntryId, logEntry.LogEntryId);
}
[Test]
public void TestLog_ShouldInitializeCorrectly()
{
// Arrange
var log = new TrainingLog();
var logEntry = new LogEntry();
// Act
logEntry.TrainingLog = log;
// Assert
Assert.AreSame(log, logEntry.TrainingLog);
}
[Test]
public void TestUser_ShouldInitializeCorrectly()
{
// Arrange
var user = new User();
var logEntry = new LogEntry();
// Act
logEntry.User = user;
// Assert
Assert.AreSame(user, logEntry.User);
}
[Test]
public void TestTrainingLogs_ShouldInitializeCorrectly()
{
// Arrange
var logs = new List<TrainingLog>();
var logEntry = new LogEntry();
// Act
logEntry.TrainingLogs = logs;
// Assert
CollectionAssert.AreEqual(logs, logEntry.TrainingLogs);
}
[TestCase("d547a40d-c45f-4c43-99de-0bfe9199ff95")]
[TestCase("99ae8dd3-1067-4141-9675-62e94bb6caaa")]
public void TestUserId_ShouldInitializeCorrectly(string userId)
{
// Arrange
var logEntry = new LogEntry();
// Act
logEntry.UserId = userId;
// Assert
Assert.AreEqual(userId, logEntry.UserId);
}
}
}
|
using System.Text;
namespace ZeroFormatter.Internal
{
internal static class StringEncoding
{
public static Encoding UTF8 = new UTF8Encoding(false);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Faculty
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
// Application.Run(new ReceivedRequest());
// Application.Run(new SendRequest());
// Application.Run(new FacultyProfile());
//Application.Run(new FacultyHomeAfterLogin());
Application.Run(new MainHomePage());
//Application.Run(new LoginStudent());
//Application.Run(new AllDeptInfo());
//Application.Run(new StudentProfile());
// Application.Run(new FacultyResponse());
// Application.Run(new StudentHomeAfterLogin());
//Application.Run(new AllFacultylist());
// Application.Run(new SendRequest());
//Application.Run(new Form1());
}
}
}
|
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Messaging;
using System;
using System.Threading;
using Tai_Shi_Xuan_Ji_Yi.Classes;
using Tai_Shi_Xuan_Ji_Yi.Classes.StepAreaAndLineChart.PresetSequence;
namespace Tai_Shi_Xuan_Ji_Yi.ViewModel
{
public class ViewModelNewCureSetup : ViewModelBase
{
string strPatientName;
/// <summary>
/// Set or get the patient name
/// </summary>
public string PatientName
{
set
{
strPatientName = value;
RaisePropertyChanged("PatientName");
}
get
{
return strPatientName;
}
}
public string CureSN { get; private set; }
public string[] SequenceNames { get; private set; }
string strSelectedSeqName;
public string SelectedSeqName
{
get
{
return strSelectedSeqName;
}
private set
{
strSelectedSeqName = value;
RaisePropertyChanged("SelectedSeqName");
}
}
CTemperatureSequence seq;
public CTemperatureSequence Sequence
{
private set
{
seq = value;
RaisePropertyChanged("Sequence");
}
get
{
return seq;
}
}
public bool Result { get; set; }
public ViewModelNewCureSetup()
{
//LoadParameters();
}
/// <summary>
/// 启动一个加载SequenceNames和生成CureSN的线程
/// </summary>
/// <param name="param"></param>
public void LoadParameters()
{
string[] seq_names = null;
string cure_sn = string.Empty;
new Thread(() =>
{
using (CDatabase db = new CDatabase())
{
// 从数据库获取温度预设曲线名称列表
if (!db.GetSequenceNames(out seq_names))
{
// 如果错误,通知View弹出错误对话框
Messenger.Default.Send<GenericMessage<string>>(new GenericMessage<string>(db.LastError), "DBError");
return;
}
else
{
this.SequenceNames = seq_names;
RaisePropertyChanged("SequenceNames");
}
if (!db.GetNewCureSN(ref cure_sn))
{
// 如果错误,通知View弹出错误对话框
Messenger.Default.Send<GenericMessage<string>>(new GenericMessage<string>(db.LastError), "DBError");
}
else
{
this.CureSN = cure_sn;
RaisePropertyChanged("CureSN");
return;
}
}
}).Start();
this.SelectedSeqName = null;
this.Sequence = null;
this.PatientName = "";
this.Result = false;
}
/// <summary>
/// Load sequence with name
/// </summary>
/// <param name="SeqName"></param>
/// <returns></returns>
public void LoadSequence(string SequenceName)
{
using (CDatabase db = new CDatabase())
{
CTemperatureSequence _Sequence;
if (db.GetTemperatureSequence(SequenceName, out _Sequence))
{
this.Sequence = _Sequence;
if (_Sequence == null)
this.SelectedSeqName = "";
else
this.SelectedSeqName = _Sequence.SequenceName;
}
else
{
}
}
}
public RelayCommand<string> SequenceSelectionChanged
{
get
{
return new RelayCommand<string>(new Action<string>(LoadSequence));
}
}
public RelayCommand ApplySetting
{
get
{
return new RelayCommand(() =>
{
if (PatientName == "")
{
Messenger.Default.Send<NotificationMessage<string>>(new NotificationMessage<string>("患者姓名不能为空", "ApplyError"));
}
else if (Sequence == null)
{
Messenger.Default.Send<NotificationMessage<string>>(new NotificationMessage<string>("请选择预设温度曲线", "ApplyError"));
}
else
{
Messenger.Default.Send<NotificationMessage<string>>(new NotificationMessage<string>("成功", "ApplySucceed"));
Result = true;
}
});
}
}
}
}
|
using System;
using System.Collections.Generic;
namespace RestApiEcom.Models
{
public partial class TempZone
{
public int Id { get; set; }
public string CodGeo { get; set; }
public string Quartier { get; set; }
public string Ilot { get; set; }
public string Lot { get; set; }
public string Cntig { get; set; }
}
}
|
// -----------------------------------------------------------------------
// <copyright file="TsMediaStreamSource.cs" company="Henric Jungheim">
// Copyright (c) 2012-2014.
// <author>Henric Jungheim</author>
// </copyright>
// -----------------------------------------------------------------------
// Copyright (c) 2012-2014 Henric Jungheim <software@henric.org>
//
// 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.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Media;
using SM.Media.Configuration;
using SM.Media.MediaParser;
using SM.Media.Pes;
using SM.Media.Utility;
namespace SM.Media
{
public sealed class TsMediaStreamSource : MediaStreamSource, IMediaStreamSource
{
static readonly Dictionary<MediaSampleAttributeKeys, string> NoMediaSampleAttributes = new Dictionary<MediaSampleAttributeKeys, string>();
TaskCompletionSource<object> _closeCompleted;
#if DEBUG
MediaStreamFsm _mediaStreamFsm = new MediaStreamFsm();
#endif
readonly object _stateLock = new object();
readonly object _streamConfigurationLock = new object();
readonly SingleThreadSignalTaskScheduler _taskScheduler;
readonly PesStream _pesStream = new PesStream();
MediaStreamDescription _audioStreamDescription;
IStreamSource _audioStreamSource;
float _bufferingProgress;
bool _isClosed = true;
int _isDisposed;
volatile int _pendingOperations;
TimeSpan _pendingSeekTarget;
TimeSpan? _seekTarget;
SourceState _state;
int _streamClosedFlags;
int _streamOpenFlags;
MediaStreamDescription _videoStreamDescription;
IStreamSource _videoStreamSource;
public TsMediaStreamSource()
{
//AudioBufferLength = 150; // 150ms of internal buffering, instead of 1s.
#if DEBUG
_mediaStreamFsm.Reset();
#endif
_taskScheduler = new SingleThreadSignalTaskScheduler("TsMediaStreamSource", SignalHandler);
}
bool IsDisposed
{
get { return 0 != _isDisposed; }
}
SourceState State
{
get { lock (_stateLock) return _state; }
set
{
lock (_stateLock)
{
if (_state == value)
return;
_state = value;
}
CheckPending();
}
}
#region IMediaStreamSource Members
public IMediaManager MediaManager { get; set; }
public TimeSpan? SeekTarget
{
get { lock (_stateLock) return _seekTarget; }
set { lock (_stateLock) _seekTarget = value; }
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
if (0 != Interlocked.Exchange(ref _isDisposed, 1))
return;
Debug.WriteLine("TsMediaStreamSource.Dispose()");
ValidateEvent(MediaStreamFsm.MediaEvent.DisposeCalled);
TaskCompletionSource<object> closeCompleted;
lock (_stateLock)
{
_isClosed = true;
closeCompleted = _closeCompleted;
_closeCompleted = null;
}
if (null != closeCompleted)
closeCompleted.TrySetResult(string.Empty);
if (null != _taskScheduler)
_taskScheduler.Dispose();
ForceClose();
_audioStreamSource = null;
_audioStreamDescription = null;
_videoStreamSource = null;
_videoStreamDescription = null;
}
void ForceClose()
{
var operations = HandleOperation(Operation.Video | Operation.Audio | Operation.Seek);
//Debug.WriteLine("TsMediastreamSource.ForceClose() " + operations);
if (0 != (operations & Operation.Seek))
{
ValidateEvent(MediaStreamFsm.MediaEvent.CallingReportSeekCompleted);
ReportSeekCompleted(0);
}
if (0 != (operations & Operation.Video) && null != _videoStreamDescription)
SendLastStreamSample(_videoStreamDescription);
if (0 != (operations & Operation.Audio) && null != _audioStreamDescription)
SendLastStreamSample(_audioStreamDescription);
}
public void Configure(IMediaConfiguration configuration)
{
if (null != configuration.Audio)
ConfigureAudioStream(configuration.Audio);
if (null != configuration.Video)
ConfigureVideoStream(configuration.Video);
lock (_streamConfigurationLock)
{
CompleteConfigure(configuration.Duration);
}
}
public void ReportError(string message)
{
var task = Task.Factory.StartNew(() => ErrorOccurred(message), CancellationToken.None, TaskCreationOptions.None, _taskScheduler);
TaskCollector.Default.Add(task, "TsMediaStreamSource ReportError");
}
public Task CloseAsync()
{
Debug.WriteLine("TsMediaStreamSource.CloseAsync(): open {0} close {1}",
_streamOpenFlags, null == _closeCompleted ? "<none>" : _closeCompleted.Task.Status.ToString());
TaskCompletionSource<object> closeCompleted;
bool closedState;
lock (_stateLock)
{
_isClosed = true;
closedState = SourceState.Closed == _state;
if (!closedState)
_state = SourceState.WaitForClose;
closeCompleted = _closeCompleted;
if (null != closeCompleted && closeCompleted.Task.IsCompleted)
{
closeCompleted = null;
_closeCompleted = null;
}
}
if (0 == _streamOpenFlags || closedState)
{
if (null != closeCompleted)
closeCompleted.TrySetResult(string.Empty);
return TplTaskExtensions.CompletedTask;
}
if (null == _closeCompleted)
return TplTaskExtensions.CompletedTask;
CheckPending();
return _closeCompleted.Task;
}
public void ValidateEvent(MediaStreamFsm.MediaEvent mediaEvent)
{
#if DEBUG
_mediaStreamFsm.ValidateEvent(mediaEvent);
#endif
}
public void CheckForSamples()
{
//Debug.WriteLine("TsMediaStreamSource.CheckForSamples(): " + (Operation)_pendingOperations);
if (0 == (_pendingOperations & (int)(Operation.Audio | Operation.Video)))
return;
_taskScheduler.Signal();
}
#endregion
void CheckPending()
{
if (0 == _pendingOperations)
return;
_taskScheduler.Signal();
}
async Task SeekHandler()
{
TimeSpan seekTimestamp;
_taskScheduler.ThrowIfNotOnThread();
var mediaManager = MediaManager;
if (null == mediaManager)
throw new InvalidOperationException("MediaManager has not been initialized");
lock (_stateLock)
{
if (_isClosed)
return;
seekTimestamp = _pendingSeekTarget;
}
try
{
var position = await mediaManager.SeekMediaAsync(seekTimestamp).ConfigureAwait(true);
_taskScheduler.ThrowIfNotOnThread();
if (_isClosed)
return;
ValidateEvent(MediaStreamFsm.MediaEvent.CallingReportSeekCompleted);
ReportSeekCompleted(position.Ticks);
Debug.WriteLine("TsMediaStreamSource.SeekHandler({0}) completed, actual: {1}", seekTimestamp, position);
State = SourceState.Play;
_bufferingProgress = -1;
}
catch (Exception ex)
{
Debug.WriteLine("TsMediaStreamSource.SeekHandler({0}) failed: {1}", seekTimestamp, ex.Message);
ErrorOccurred("Seek failed: " + ex.Message);
_taskScheduler.ThrowIfNotOnThread();
}
CheckPending();
}
void SignalHandler()
{
//Debug.WriteLine("TsMediaStreamSource.SignalHandler() pending {0}", _pendingOperations);
_taskScheduler.ThrowIfNotOnThread();
if (_isClosed)
{
ForceClose();
return;
}
var previousOperations = Operation.None;
var requestedOperations = Operation.None;
try
{
for (; ; )
{
if (0 != HandleOperation(Operation.Seek))
{
// Request the previous operation(s) again if we
// detect a possible Seek/GetSample race.
if (Operation.None != previousOperations)
requestedOperations |= previousOperations;
var task = SeekHandler();
TaskCollector.Default.Add(task, "TsMediaStreamSource.SignalHandler SeekHandler()");
return;
}
if (SourceState.Play != State)
return;
previousOperations = HandleOperation(Operation.Video | Operation.Audio);
requestedOperations |= previousOperations;
if (0 == requestedOperations)
return;
var reportBufferingMask = (Operation)_streamOpenFlags;
var canCallReportBufferingProgress = reportBufferingMask == (requestedOperations & reportBufferingMask);
var gotPackets = false;
if (0 != (requestedOperations & Operation.Video))
{
if (null != _videoStreamSource)
{
if (SendStreamSample(_videoStreamSource, _videoStreamDescription, canCallReportBufferingProgress))
{
requestedOperations &= ~Operation.Video;
gotPackets = true;
}
}
}
if (0 != (requestedOperations & Operation.Audio))
{
if (null != _audioStreamSource)
{
if (SendStreamSample(_audioStreamSource, _audioStreamDescription, canCallReportBufferingProgress))
{
requestedOperations &= ~Operation.Audio;
gotPackets = true;
}
}
}
if (!gotPackets)
return;
}
}
finally
{
if (0 != requestedOperations)
{
Debug.WriteLine("TsMediaStreamSource.SignalHandler() re-requesting " + requestedOperations);
RequestOperation(requestedOperations);
}
}
}
void ThrowIfDisposed()
{
if (0 == _isDisposed)
return;
throw new ObjectDisposedException(GetType().Name);
}
bool SendStreamSample(IStreamSource source, MediaStreamDescription mediaStreamDescription, bool canCallReportBufferingProgress)
{
_taskScheduler.ThrowIfNotOnThread();
var packet = source.GetNextSample();
if (null == packet)
{
if (source.IsEof)
return SendLastStreamSample(mediaStreamDescription);
if (canCallReportBufferingProgress)
{
var progress = source.BufferingProgress;
if (progress.HasValue)
{
if (Math.Abs(_bufferingProgress - progress.Value) < 0.05)
return false;
Debug.WriteLine("Sample {0} buffering {1:F2}%", mediaStreamDescription.Type, progress * 100);
_bufferingProgress = progress.Value;
ValidateEvent(MediaStreamFsm.MediaEvent.CallingReportSampleCompleted);
ReportGetSampleProgress(progress.Value);
}
else
{
Debug.WriteLine("Sample {0} not buffering", mediaStreamDescription.Type);
// Try again, data might have arrived between the last call to GetNextSample() and
// when we checked the buffering progress.
packet = source.GetNextSample();
}
}
if (null == packet)
return false;
}
_bufferingProgress = -1;
try
{
_pesStream.Packet = packet;
var sample = new MediaStreamSample(mediaStreamDescription, _pesStream, 0, packet.Length,
packet.PresentationTimestamp.Ticks, NoMediaSampleAttributes);
//Debug.WriteLine("Sample {0} at {1}", sample.MediaStreamDescription.Type, TimeSpan.FromTicks(sample.Timestamp));
ValidateEvent(MediaStreamFsm.MediaEvent.CallingReportSampleCompleted);
ReportGetSampleCompleted(sample);
}
finally
{
_pesStream.Packet = null;
source.FreeSample(packet);
}
return true;
}
bool SendLastStreamSample(MediaStreamDescription mediaStreamDescription)
{
_taskScheduler.ThrowIfNotOnThread();
ReportGetSampleProgress(1);
var sample = new MediaStreamSample(mediaStreamDescription, null, 0, 0, 0, NoMediaSampleAttributes);
Debug.WriteLine("Sample {0} is null", mediaStreamDescription.Type);
var allClosed = CloseStream(mediaStreamDescription.Type);
if (allClosed)
{
Debug.WriteLine("TsMediaStreamSource.SendLastStreamSample() All streams closed");
lock (_stateLock)
{
_isClosed = true;
if (SourceState.Closed != _state)
_state = SourceState.WaitForClose;
}
}
ValidateEvent(MediaStreamFsm.MediaEvent.CallingReportSampleCompleted);
ReportGetSampleCompleted(sample);
if (allClosed)
ValidateEvent(MediaStreamFsm.MediaEvent.StreamsClosed);
return true;
}
void ConfigureVideoStream(IMediaParserMediaStream video)
{
var configurationSource = (IVideoConfigurationSource)video.ConfigurationSource;
var msa = new Dictionary<MediaStreamAttributeKeys, string>();
msa[MediaStreamAttributeKeys.VideoFourCC] = configurationSource.VideoFourCc;
var cpd = configurationSource.CodecPrivateData;
Debug.WriteLine("TsMediaStreamSource.ConfigureVideoStream(): CodecPrivateData: " + cpd);
if (!string.IsNullOrWhiteSpace(cpd))
msa[MediaStreamAttributeKeys.CodecPrivateData] = cpd;
msa[MediaStreamAttributeKeys.Height] = configurationSource.Height.ToString();
msa[MediaStreamAttributeKeys.Width] = configurationSource.Width.ToString();
var videoStreamDescription = new MediaStreamDescription(MediaStreamType.Video, msa);
lock (_streamConfigurationLock)
{
_videoStreamSource = video.StreamSource;
_videoStreamDescription = videoStreamDescription;
}
}
void ConfigureAudioStream(IMediaParserMediaStream audio)
{
var configurationSource = (IAudioConfigurationSource)audio.ConfigurationSource;
var msa = new Dictionary<MediaStreamAttributeKeys, string>();
var cpd = configurationSource.CodecPrivateData;
Debug.WriteLine("TsMediaStreamSource.ConfigureAudioStream(): CodecPrivateData: " + cpd);
if (!string.IsNullOrWhiteSpace(cpd))
msa[MediaStreamAttributeKeys.CodecPrivateData] = cpd;
var audioStreamDescription = new MediaStreamDescription(MediaStreamType.Audio, msa);
lock (_streamConfigurationLock)
{
_audioStreamSource = audio.StreamSource;
_audioStreamDescription = audioStreamDescription;
}
}
void OpenStream(MediaStreamType type)
{
var operation = GetOperationFromType(type);
var flag = (int)operation;
var oldFlags = _streamOpenFlags;
for (; ; )
{
var newFlags = oldFlags | flag;
var flags = Interlocked.CompareExchange(ref _streamOpenFlags, newFlags, oldFlags);
if (flags == oldFlags)
return;
oldFlags = flags;
}
}
bool CloseStream(MediaStreamType type)
{
var operation = GetOperationFromType(type);
var flag = (int)operation;
var oldFlags = _streamClosedFlags;
for (; ; )
{
var newFlags = oldFlags | flag;
if (newFlags == oldFlags)
return false;
var flags = Interlocked.CompareExchange(ref _streamClosedFlags, newFlags, oldFlags);
if (flags == oldFlags)
return newFlags == _streamOpenFlags;
oldFlags = flags;
}
}
static Operation GetOperationFromType(MediaStreamType type)
{
switch (type)
{
case MediaStreamType.Audio:
return Operation.Audio;
case MediaStreamType.Video:
return Operation.Video;
default:
throw new ArgumentException("Only audio and video types are supported", "type");
}
}
void CompleteConfigure(TimeSpan? duration)
{
var msd = new List<MediaStreamDescription>();
if (null != _videoStreamSource && null != _videoStreamDescription)
{
msd.Add(_videoStreamDescription);
OpenStream(_videoStreamDescription.Type);
}
if (null != _audioStreamSource && null != _audioStreamSource)
{
msd.Add(_audioStreamDescription);
OpenStream(_audioStreamDescription.Type);
}
var mediaSourceAttributes = new Dictionary<MediaSourceAttributesKeys, string>();
if (duration.HasValue)
mediaSourceAttributes[MediaSourceAttributesKeys.Duration] = duration.Value.Ticks.ToString(CultureInfo.InvariantCulture);
var canSeek = duration.HasValue;
mediaSourceAttributes[MediaSourceAttributesKeys.CanSeek] = canSeek.ToString();
var task = Task.Factory.StartNew(() =>
{
Debug.WriteLine("TsMediaStreamSource: ReportOpenMediaCompleted ({0} streams)", msd.Count);
_taskScheduler.ThrowIfNotOnThread();
foreach (var kv in mediaSourceAttributes)
Debug.WriteLine("TsMediaStreamSource: ReportOpenMediaCompleted {0} = {1}", kv.Key, kv.Value);
ValidateEvent(canSeek
? MediaStreamFsm.MediaEvent.CallingReportOpenMediaCompleted
: MediaStreamFsm.MediaEvent.CallingReportOpenMediaCompletedLive);
ReportOpenMediaCompleted(mediaSourceAttributes, msd);
State = canSeek ? SourceState.Seek : SourceState.Play;
}, CancellationToken.None, TaskCreationOptions.None, _taskScheduler);
TaskCollector.Default.Add(task, "TsMediaStreamSource CompleteConfigure");
//ReportGetSampleProgress(0);
}
/// <summary>
/// The <see cref="T:System.Windows.Controls.MediaElement" /> calls this method to ask the
/// <see
/// cref="T:System.Windows.Media.MediaStreamSource" />
/// to open the media.
/// </summary>
protected override void OpenMediaAsync()
{
Debug.WriteLine("TsMediaStreamSource.OpenMediaAsync()");
ValidateEvent(MediaStreamFsm.MediaEvent.OpenMediaAsyncCalled);
ThrowIfDisposed();
var mediaManager = MediaManager;
if (null == mediaManager)
throw new InvalidOperationException("MediaManager has not been initialized");
lock (_stateLock)
{
_isClosed = false;
_state = SourceState.Open;
Debug.Assert(null == _closeCompleted, "TsMediaStreamSource.OpenMediaAsync() stream is already playing");
_closeCompleted = new TaskCompletionSource<object>();
}
_bufferingProgress = -1;
mediaManager.OpenMedia();
}
/// <summary>
/// The <see cref="T:System.Windows.Controls.MediaElement" /> calls this method to ask the
/// <see
/// cref="T:System.Windows.Media.MediaStreamSource" />
/// to seek to the nearest randomly accessible point before the specified time. Developers respond to this method by
/// calling
/// <see
/// cref="M:System.Windows.Media.MediaStreamSource.ReportSeekCompleted(System.Int64)" />
/// and by ensuring future calls to
/// <see
/// cref="M:System.Windows.Media.MediaStreamSource.ReportGetSampleCompleted(System.Windows.Media.MediaStreamSample)" />
/// will return samples from that point in the media.
/// </summary>
/// <param name="seekToTime">
/// The time as represented by 100 nanosecond increments to seek to. This is typically measured
/// from the beginning of the media file.
/// </param>
protected override void SeekAsync(long seekToTime)
{
var seekTimestamp = TimeSpan.FromTicks(seekToTime);
Debug.WriteLine("TsMediaStreamSource.SeekAsync({0})", seekTimestamp);
ValidateEvent(MediaStreamFsm.MediaEvent.SeekAsyncCalled);
StartSeek(seekTimestamp);
}
void StartSeek(TimeSpan seekTimestamp)
{
lock (_stateLock)
{
if (_isClosed)
return;
_state = SourceState.Seek;
_pendingSeekTarget = _seekTarget ?? seekTimestamp;
}
RequestOperationAndSignal(Operation.Seek);
}
/// <summary>
/// The <see cref="T:System.Windows.Controls.MediaElement" /> calls this method to ask the
/// <see
/// cref="T:System.Windows.Media.MediaStreamSource" />
/// to prepare the next
/// <see
/// cref="T:System.Windows.Media.MediaStreamSample" />
/// of the requested stream type for the media pipeline. Developers can respond to this method by calling either
/// <see
/// cref="M:System.Windows.Media.MediaStreamSource.ReportGetSampleCompleted(System.Windows.Media.MediaStreamSample)" />
/// or
/// <see
/// cref="M:System.Windows.Media.MediaStreamSource.ReportGetSampleProgress(System.Double)" />
/// .
/// </summary>
/// <param name="mediaStreamType">
/// The description of the stream that the next sample should come from which will be either
/// <see
/// cref="F:System.Windows.Media.MediaStreamType.Audio" />
/// or <see cref="F:System.Windows.Media.MediaStreamType.Video" /> .
/// </param>
protected override void GetSampleAsync(MediaStreamType mediaStreamType)
{
//Debug.WriteLine("TsMediaStreamSource.GetSampleAsync({0})", mediaStreamType);
var op = LookupOperation(mediaStreamType);
RequestOperationAndSignal(op);
}
/// <summary>
/// Called when a stream switch is requested on the <see cref="T:System.Windows.Controls.MediaElement" />.
/// </summary>
/// <param name="mediaStreamDescription"> The stream switched to. </param>
protected override void SwitchMediaStreamAsync(MediaStreamDescription mediaStreamDescription)
{
Debug.WriteLine("TsMediaStreamSource.SwitchMediaStreamAsync()");
throw new NotImplementedException();
}
/// <summary>
/// The <see cref="T:System.Windows.Controls.MediaElement" /> can call this method to request information about the
/// <see
/// cref="T:System.Windows.Media.MediaStreamSource" />
/// . Developers respond to this method by calling
/// <see
/// cref="M:System.Windows.Media.MediaStreamSource.ReportGetDiagnosticCompleted(System.Windows.Media.MediaStreamSourceDiagnosticKind,System.Int64)" />
/// .
/// </summary>
/// <param name="diagnosticKind">
/// A member of the <see cref="T:System.Windows.Media.MediaStreamSourceDiagnosticKind" /> enumeration describing what
/// type of information is desired.
/// </param>
protected override void GetDiagnosticAsync(MediaStreamSourceDiagnosticKind diagnosticKind)
{
Debug.WriteLine("TsMediaStreamSource.GetDiagnosticAsync({0})", diagnosticKind);
throw new NotImplementedException();
}
/// <summary>
/// The <see cref="T:System.Windows.Controls.MediaElement" /> can call this method when going through normal shutdown
/// or as a result of an error. This lets the developer perform any needed cleanup of the
/// <see
/// cref="T:System.Windows.Media.MediaStreamSource" />
/// .
/// </summary>
protected override void CloseMedia()
{
Debug.WriteLine("TsMediaStreamSource.CloseMedia()");
ValidateEvent(MediaStreamFsm.MediaEvent.CloseMediaCalled);
lock (_stateLock)
{
_isClosed = true;
_state = SourceState.Closed;
}
var task = Task.Factory.StartNew(CloseMediaHandler, CancellationToken.None, TaskCreationOptions.None, _taskScheduler);
TaskCollector.Default.Add(task, "TsMediaStreamSource CloseMedia");
}
void CloseMediaHandler()
{
Debug.WriteLine("TsMediaStreamSource.CloseMediaHandler()");
_taskScheduler.ThrowIfNotOnThread();
TaskCompletionSource<object> closeCompleted;
lock (_stateLock)
{
closeCompleted = _closeCompleted;
}
if (null != closeCompleted)
closeCompleted.TrySetResult(string.Empty);
var mediaManager = MediaManager;
if (null == mediaManager)
{
Debug.WriteLine("TsMediaStreamSource.CloseMediaHandler() null media manager");
return;
}
mediaManager.CloseMedia();
}
Operation LookupOperation(MediaStreamType mediaStreamType)
{
switch (mediaStreamType)
{
case MediaStreamType.Audio:
return Operation.Audio;
case MediaStreamType.Video:
return Operation.Video;
}
Debug.Assert(false);
return 0;
}
void RequestOperationAndSignal(Operation operation)
{
if (RequestOperation(operation))
_taskScheduler.Signal();
}
bool RequestOperation(Operation operation)
{
//Debug.WriteLine("TsMediaStreamSource.RequestOperation({0}) pending {1}", operation, _pendingOperations);
var op = (int)operation;
var current = _pendingOperations;
for (; ; )
{
var value = current | op;
if (value == current)
return false;
#pragma warning disable 0420
var existing = Interlocked.CompareExchange(ref _pendingOperations, value, current);
#pragma warning restore 0420
if (existing == current)
return true;
current = existing;
}
}
Operation HandleOperation(Operation operation)
{
var op = (int)operation;
var current = _pendingOperations;
for (; ; )
{
var value = current & ~op;
if (value == current)
return Operation.None;
#pragma warning disable 0420
var existing = Interlocked.CompareExchange(ref _pendingOperations, value, current);
#pragma warning restore 0420
if (existing == current)
return (Operation)(current & op);
current = existing;
}
}
#region Nested type: Operation
[Flags]
enum Operation
{
None = 0,
Audio = 1,
Video = 2,
Seek = 4
}
#endregion
#region Nested type: SourceState
enum SourceState
{
Idle,
Open,
Seek,
Play,
Closed,
WaitForClose
}
#endregion
}
}
|
using ManyConsole;
using Microsoft.Win32.TaskScheduler;
using System;
namespace DailyDscovrConsoleApp.Commands
{
public class ScheduleCommand : ConsoleCommand
{
private static bool Install = true;
private static short RunInterval = 1;
public ScheduleCommand()
{
IsCommand("DailyDscovr", "Schedules the UpdateWallpaper command to automatically run");
HasLongDescription("This either sets or removes the Set wallpaper command from the daily schedule.");
HasOption("r|remove", "Removes the DSCOVR wallpaper task", _ => Install = false);
HasOption("i|interval", "Sets the interval in days between wallpaper updates", i => RunInterval = Convert.ToInt16(i));
}
private static string GetCurrentDir()
{
var path = System.Reflection.Assembly.GetExecutingAssembly().CodeBase;
return System.IO.Path.GetDirectoryName(path);
}
public override int Run(string[] remainingArguments)
{
using (TaskService ts = new TaskService())
{
if (Install)
{
Console.WriteLine("Installing task....");
var td = ts.NewTask();
td.RegistrationInfo.Description = "Updates wallpaper, with latest from Dscovr for the users current location";
td.Settings.RunOnlyIfIdle = true;
td.Settings.RunOnlyIfNetworkAvailable = true;
td.Settings.DisallowStartIfOnBatteries = true;
td.Settings.StartWhenAvailable = true;
// set it retry every 20 mins for an hour
td.Settings.RestartCount = 3;
td.Settings.RestartInterval = new TimeSpan(0, 20, 0);
td.Triggers.Add(new DailyTrigger { DaysInterval = RunInterval });
// todo remove hardcoded paths
td.Actions.Add(new ExecAction("DscovrWallpaperizer.exe", "UpdateWallpaper", AppDomain.CurrentDomain.BaseDirectory));
ts.RootFolder.RegisterTaskDefinition(@"DailyDscovr", td);
}
else
{
Console.WriteLine("Removing task....");
ts.RootFolder.DeleteTask("DailyDscovr");
}
Console.WriteLine("Success!");
}
return 1;
}
}
}
|
using JekossTest.Dal.Common;
using JekossTest.Dal.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace JekossTest.Dal.Configurations
{
public class UserConfiguration : DbEntityConfiguration<User>
{
public override void Configure(EntityTypeBuilder<User> entity)
{
entity.ToTable("User");
entity.HasIndex(x => x.Id);
entity.HasOne(x => x.Role).WithMany(x => x.Users).HasForeignKey(x => x.RoleId);
entity.HasOne(x => x.AccountRefreshToken).WithOne(x => x.User).HasForeignKey<AccountRefreshToken>(x=>x.UserId);
}
}
} |
using AutoMapper;
using iCopy.Model.Request;
using iCopy.SERVICES.Attributes;
using iCopy.SERVICES.IServices;
using iCopy.Web.Controllers;
using iCopy.Web.Helper;
using iCopy.Web.Resources;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using System;
using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
namespace iCopy.Web.Areas.Administration.Controllers
{
[Area(Strings.Area.Administration), AllowAnonymous()]
[Authorize(Roles = Strings.Roles.AdministratorCompany)]
public class CopierController : BaseDataTableCRUDController<Model.Request.Copier, Model.Request.Copier, Model.Response.Copier, Model.Request.CopierSearch, int>
{
private new readonly ICopierService crudService;
private Model.Request.ProfilePhoto PhotoSession => HttpContext.Session.Get<Model.Request.ProfilePhoto>(Session.Keys.Upload.ProfileImage);
public CopierController(ICopierService CrudService, SharedResource _localizer, IMapper mapper) : base(CrudService, _localizer, mapper)
{
this.crudService = CrudService;
}
[HttpPost, Transaction, AutoValidateModelState, Authorize(Roles = Strings.Roles.Administrator)]
public override async Task<IActionResult> Insert(Copier model)
{
try
{
model.ProfilePhoto = PhotoSession;
await crudService.InsertAsync(model);
TempData["success"] = _localizer.SuccAdd;
return Ok();
}
catch (Exception e)
{
return StatusCode((int)HttpStatusCode.InternalServerError);
}
}
[HttpGet]
public override Task<IActionResult> Update(int id)
{
if (HttpContext.Session.Get(Session.Keys.Upload.ProfileImage) != null)
HttpContext.Session.Remove(Session.Keys.Upload.ProfileImage);
return base.Update(id);
}
[HttpPost, Transaction]
public override async Task<IActionResult> Update(int id, [FromForm]Copier model)
{
if (ModelState.IsValid)
{
try
{
model.ProfilePhoto = PhotoSession;
await crudService.UpdateAsync(id, model);
TempData["success"] = _localizer.SuccUpdate;
return RedirectToAction(nameof(Update));
}
catch
{
TempData["error"] = _localizer.ErrUpdate;
}
}
return View(await crudService.GetByIdAsync(id));
}
[HttpGet, Transaction, Authorize(Roles = Strings.Roles.Administrator)]
public override Task<IActionResult> Delete(int id)
{
return base.Delete(id);
}
[HttpPost, IgnoreAntiforgeryToken, Authorize(Roles = Strings.Roles.Administrator)]
public override Task<IActionResult> ChangeActiveStatus(int id)
{
return base.ChangeActiveStatus(id);
}
}
}
|
using MediatR;
using System;
namespace JCFruit.WeebChat.Server.Models
{
public class MessageEnvelope<T> : INotification
{
public string SourceId { get; set; }
public DateTimeOffset Timestamp { get; set; }
public T Body { get; set; }
}
}
|
using System.Collections.Generic;
namespace PDV.DAO.Entidades.MDFe.Tipos
{
public class TipoEmitente
{
public decimal IDTipoEmitente { get; set; }
public string Descricao { get; set; }
public static List<TipoEmitente> GetTipos()
{
List<TipoEmitente> Tipos = new List<TipoEmitente>();
//Tipos.Add(new TipoEmitente { IDTipoEmitente = 1, Descricao = "Prestador de Serviço de Transporte" });
Tipos.Add(new TipoEmitente { IDTipoEmitente = 2, Descricao = "Transportador de Carga Própria" });
return Tipos;
}
}
}
|
public class NameFactory : INameFactory
{
public IName Make(string firstName, string lastName)
{
return
new Name
{
FirstName = firstName,
LastName = lastName,
};
}
}
|
using FakeItEasy;
using FatCat.Nes.OpCodes.AddressingModes;
using FluentAssertions;
using Xunit;
namespace FatCat.Nes.Tests.OpCodes.AddressModes
{
public class IndirectYModeTests : AddressModeTests
{
private const byte HighAddressValue = 0x19;
private const byte InitialReadValue = 0xe2;
private const byte LowAddressValue = 0x09;
private const byte YRegister = 0x02;
private readonly ushort HighLocation = (InitialReadValue + 1) & 0x00ff;
private readonly ushort LowLocation = InitialReadValue & 0x00ff;
protected override int ExpectedCycles => 0;
protected override string ExpectedName => "(Indirect),Y";
public IndirectYModeTests()
{
addressMode = new IndirectYMode(cpu);
cpu.YRegister = YRegister;
A.CallTo(() => cpu.Read(ProgramCounter)).Returns(InitialReadValue);
A.CallTo(() => cpu.Read(HighLocation)).Returns(HighAddressValue);
A.CallTo(() => cpu.Read(LowLocation)).Returns(LowAddressValue);
}
[Fact]
public void IfThePageChangesAnExtraClockCycleIsRequired()
{
cpu.YRegister = 0xff;
var cycles = addressMode.Run();
cycles.Should().Be(1);
}
[Fact]
public void WillIncrementTheProgramCounter()
{
addressMode.Run();
cpu.ProgramCounter.Should().Be(ProgramCounter + 1);
}
[Fact]
public void WillReadFromHighLocation()
{
addressMode.Run();
A.CallTo(() => cpu.Read(HighLocation)).MustHaveHappened();
}
[Fact]
public void WillReadFromTheLowLocation()
{
addressMode.Run();
A.CallTo(() => cpu.Read(LowLocation)).MustHaveHappened();
}
[Fact]
public void WillReadFromTheProgramCounter()
{
addressMode.Run();
A.CallTo(() => cpu.Read(ProgramCounter)).MustHaveHappened();
}
[Fact]
public void WillSetTheAbsoluteAddressToValuesPlusTheYRegister()
{
addressMode.Run();
ushort expectedAddress = (HighAddressValue << 8) | LowAddressValue;
expectedAddress += YRegister;
cpu.AbsoluteAddress.Should().Be(expectedAddress);
}
}
} |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlockChain
{
public class TraceingManager
{
public static void InitializeTraceing()
{
string path = Directory.GetCurrentDirectory() + "\\TraceInfo.txt";
Trace.Listeners.Add(new TextWriterTraceListener( path, "BlockChainTraceingListener"));
}
public static void Message(string message)
{
Trace.TraceInformation(DateTime.Now.ToString() + " :: " + message);
Trace.Flush();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace unidad_3.modelo.championshift
{
class cancha
{
//propiedad de la clase
protected int id;
protected string nombre;
protected string tipo;
protected string ubicacion;
//metodo getter´s y setter´s
public int _Id { get; set; }
public string Nombre { get; set; }
public string Tipo { get; set; }
public string Ubicacion { get; set; }
}
}
|
/* 02. Write a program to traverse the directory C:\WINDOWS and all its subdirectories recursively
* and to display all files matching the mask *.exe. Use the class System.IO.Directory. */
using System;
using System.Collections.Generic;
using System.IO;
class FindAllExeFiles
{
static void Main()
{
string originalPath = "C:\\Windows";
List<string> allExeFiles = new List<string>();
Stack<string> allSubDirectories = new Stack<string>();
allSubDirectories.Push(originalPath);
while (allSubDirectories.Count > 0)
{
var currentDir = allSubDirectories.Pop();
IEnumerable<string> subDirectories = new List<string>();
try
{
allExeFiles.AddRange(Directory.EnumerateFiles(currentDir, "*.exe", SearchOption.TopDirectoryOnly));
subDirectories = Directory.EnumerateDirectories(currentDir);
}
catch (UnauthorizedAccessException ex)
{
Console.WriteLine(ex.Message);
}
foreach (var dir in subDirectories)
{
allSubDirectories.Push(dir);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace UsingStructs
{
// STRUCTS are similar to classes. But, there are some differences:
//
// 1) Structs don't support inheritance
//
// 2) Structs are VALUE TYPES not refference types like classes
//
// 3) Cannot initialize the fields of a struct within the definition
public struct Point
{
private int _xCoord;
private int _yCoord;
public Point(int x, int y)
{
_xCoord = x;
_yCoord = y;
}
public int x
{
get { return _xCoord; }
set { _xCoord = value; }
}
public int y
{
get { return _xCoord; }
set { _xCoord = value; }
}
}
}
|
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GlobalDevelopment.SocialNetworks.LinkedIn.Models
{
public class PositionValues
{
public string ID { get; set; }
public bool IsCurrent { get; set; }
public string Location { get; set; }
public string Title { get; set; }
public Company Company { get; set; }
public PositionValues(JToken token)
{
ID = (token["id"] ?? "NA").ToString();
IsCurrent = bool.Parse((token["isCurrent"] ?? "false").ToString());
Location = (token["location"] ?? "NA").ToString();
Title = (token["title"] ?? "NA").ToString();
Company = new Company(token["company"]);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using SubSonic.Extensions;
namespace Pes.Core
{
public partial class VLessionGroup
{
public static List<VLessionGroup> GetListLessionGroups()
{
return All().ToList();
}
public static VLessionGroup GetLessionGroupByID(int id)
{
try
{
return VLessionGroup.Single(id);
}
catch
{
return null;
}
}
public static VLessionGroup GetLessionGroupByName(string name)
{
try
{
VLessionGroup lgBO = (from lg in All()
where lg.LessionGroupName == name
select lg).Single();
return lgBO;
}
catch
{
return null;
}
}
public static VLessionGroup GetLessionGroupByView(int view)
{
try
{
VLessionGroup lgBO = (from lg in All()
where lg.LessionGroupView == view
select lg).Single();
return lgBO;
}
catch
{
return null;
}
}
public static bool CheckLessionGroupByName(string name)
{
foreach (VLessionGroup lesGroup in All().ToList())
if (lesGroup.LessionGroupName.CompareTo(name) == 0)
return true;
return false;
}
/// <summary>
/// Lấy tất cả các LessionGroup có trạng thái View=1
/// </summary>
/// <returns>List</returns>
//public static List<LessionGroup> GetAllLessionGroupView()
//{
// try
// {
// List<LessionGroup> lesView = (from les in GetLessionGroups()
// where les.LessionGroupView == 1
// select les).ToList<LessionGroup>();
// return lesView;
// }
// catch
// {
// return null;
// }
//}
public static List<VLessionGroup> GetAllLessionGroupByPriority()
{
try
{
List<VLessionGroup> lesView = (from les in All()
where les.LessionGroupPriority >= 1
orderby les.LessionGroupPriority
select les).ToList();
return lesView;
}
catch
{
return null;
}
}
//public static bool CheckFullLessionGroupView()
//{
// List<LessionGroup> list = GetAllLessionGroupView();
// if (list.Count >= 6)
// return true;
// return false;
//}
public static void InsertLessionGroup(VLessionGroup lessionGrBO)
{
Add(lessionGrBO);
}
public static void DeleteLessionGroup(VLessionGroup moBO)
{
Delete(moBO);
}
public static void UpdateLessionGroup(VLessionGroup moBo)
{
Update(moBo);
}
public static List<VLessionGroup> GetItemsFromTo(IQueryable<VLessionGroup> table, int start, int end)
{
if (start <= 0)
start = 1;
List<VLessionGroup> listGet = table.Skip(start - 1).Take(end - start + 1).ToList();
return listGet;
}
public static List<VLessionGroup> GetListLessionGroupFromTo(int start, int end)
{
return GetItemsFromTo(All(), start, end);
}
public static int CountAllLessionGroup()
{
return All().Count();
}
public static string ToStringView(object view)
{
int temp = CoreSupport.ConvertToInt(view, 0);
if (temp == 0)
return "Không";
return "Có";
}
}
} |
using Mosa.External.x86;
using Mosa.External.x86.FileSystem;
using Mosa.Kernel.x86;
using System;
using System.Collections.Generic;
namespace Mosa.External.x86.FileSystem
{
public struct PartitionInfo
{
public bool IsBootable;
public uint LBA;
public uint Size;
}
public unsafe class MBR
{
public static List<PartitionInfo> PartitionInfos;
public static MemoryBlock memoryBlock;
public static void Initialize(IDisk disk)
{
byte[] mbrData = new byte[512];
disk.ReadBlock(0, 1, mbrData);
memoryBlock = new MemoryBlock(mbrData);
PartitionInfos = new List<PartitionInfo>();
LoadPartitionInfo();
}
public static void LoadPartitionInfo()
{
for(int i = 0x1BE;i< 0x1FE; i += 16)
{
bool _IsBootable = memoryBlock.Read8((uint)(i + 0)) == 0x80;
uint _LBA = memoryBlock.Read32((uint)(i + 8));
uint _Size = memoryBlock.Read32((uint)(i + 12));
if(_Size == 0 || _LBA == 0)
{
continue;
}
PartitionInfos.Add(new PartitionInfo()
{
IsBootable = _IsBootable,
LBA = _LBA,
Size = _Size,
});
}
for (int i = 0; i < PartitionInfos.Count; i++)
{
PartitionInfo v = PartitionInfos[i];
//Console.WriteLine("Partition:" + i + " Bootable:" + (v.IsBootable ? "True" : "False") + " LBA:" + v.LBA + " Size:" + v.Size);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GenericImplementation
{
class Mystack<T>
{
int top = -1; T[] stack = new T[100];
public void push(T x)
{
if (top == 99)
Console.WriteLine("STACK OVERFLOW");
else
stack[++top] = x;
}
public T pop()
{
if (top == -1)
{
Console.WriteLine("STACK UNDERFLOW");
return default(T);
}
else
{
return stack[top--];
}
}
public void showstack()
{
if (top == -1)
Console.WriteLine("STACK UNDERFLOW");
else
{
Console.WriteLine("Current elements in the stack are:");
for (int i = top; i >= 0; i--)
{
Console.WriteLine(stack[i]);
}
}
}
}
class Program
{
static void Main(string[] args)
{
Mystack<string> obj = new Mystack<string>();
obj.pop();
obj.push("Subham");
obj.push("Virat");
obj.push("Messi");
obj.push("Ronaldo");
obj.push("Sunil");
obj.showstack();
Console.WriteLine("Popped element is " + obj.pop());
Console.WriteLine("Popped element is " + obj.pop());
obj.showstack();
obj.push("Smriti");
obj.push("Mahi");
obj.showstack();
Console.ReadKey();
Mystack<int> obj1 = new Mystack<int>();
obj1.pop();
obj1.push(10);
obj1.push(20);
obj1.push(30);
obj1.push(40);
obj1.push(50);
obj1.showstack();
Console.WriteLine("Popped element is " + obj1.pop());
Console.WriteLine("Popped element is " + obj1.pop());
obj1.showstack();
obj1.push(60);
obj1.push(70);
obj1.showstack();
Console.ReadKey();
}
}
}
|
using LibraryAssetsAPI.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace LibraryAssetsAPI.Data
{
public class LibraryAssetContexSeed
{
public static async Task SeedAsync(LibraryAssetContex context)
{
if (!context.Status.Any())
{
context.Status.AddRange(GetPreconfiguredStatus());
await context.SaveChangesAsync();
}
if (!context.Video.Any())
{
context.Video.AddRange(GetPreconfiguredVideo());
await context.SaveChangesAsync();
}
if (!context.Book.Any())
{
context.Book.AddRange(GetPreconfiguredBook());
await context.SaveChangesAsync();
}
}
static IEnumerable<Video> GetPreconfiguredVideo()
{
return new List<Video>()
{
new Video() { Id= 1, Title = "Addidas",Year = 2017, Cost = 80, ImageUrl= "Unkown", NumberOfCopies = 10, StatusId = 1, Director="Chow"},
new Video() { Id= 2, Title = "Nike",Year = 2017, Cost = 10, ImageUrl= "Unkown", NumberOfCopies = 5, StatusId = 2, Director="Mohan"},
new Video() { Id= 3, Title = "Puma",Year = 2017, Cost = 40, ImageUrl= "Unkown", NumberOfCopies = 10, StatusId = 3, Director="Martinus"}
};
}
static IEnumerable<Status> GetPreconfiguredStatus()
{
return new List<Status>()
{
new Status() { Id =1, Name= "Healthy", Description="Just Do It!"},
new Status() { Id =2, Name= "FastFood", Description="Wife!"},
new Status() { Id =3, Name= "Restaurant", Description="Money!"}
};
}
static IEnumerable<Book> GetPreconfiguredBook()
{
return new List<Book>()
{
new Book() { Id = 1, Title = "WonderWoman", Year = 2010, Cost = 80, ImageUrl = "Unkown", NumberOfCopies = 10, StatusId = 1, Author="Stanley", ISBN="123", DeweyIndex="hello"},
new Book() { Id = 2, Title = "SuperMan", Year = 2010, Cost = 80, ImageUrl = "Unkown", NumberOfCopies = 10, StatusId = 2, Author="Stanley", ISBN="1234", DeweyIndex="helloMe"},
new Book() { Id = 3, Title = "BatMan", Year = 2011, Cost = 80, ImageUrl = "Unkown", NumberOfCopies = 10, StatusId = 3, Author="Stanley", ISBN="1235", DeweyIndex="helloYou"},
new Book() { Id = 4, Title = "Joker", Year = 2012, Cost = 80, ImageUrl = "Unkown", NumberOfCopies = 10, StatusId = 2, Author="Stanley", ISBN="1236", DeweyIndex="helloUs"},
new Book() { Id = 5, Title = "GreenLantern", Year = 2013, Cost = 80, ImageUrl = "Unkown", NumberOfCopies = 10, StatusId = 2, Author="Stanley", ISBN="1237", DeweyIndex="helloWorld"},
};
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
namespace qmaster
{
public partial class add_qus : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = "<b><font color=Brown>" + "WELLCOME STAFF:: " + "</font>" + "<b><font color=red>" + Session["staff_id"] + "</font>";
if (!IsPostBack)
{
SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=qus;User ID=sa;Password=admin123");
con.Open();
string id = Session["staff_id"].ToString();
string com = "Select tbl_sub.sub_id,tbl_sub.sub_name,tbl_sub_allot.allot_id from tbl_sub,tbl_sub_allot where tbl_sub.sub_name=tbl_sub_allot.sub_id and tbl_sub_allot.staff_id='" + id+"'";
SqlDataAdapter adpt = new SqlDataAdapter(com, con);
DataTable dt = new DataTable();
adpt.Fill(dt);
ddlsub.DataSource = dt;
ddlsub.DataBind();
ddlsub.DataTextField = "sub_name";
ddlsub.DataValueField = "sub_name";
ddlsub.DataBind();
con.Close();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=qus;User ID=sa;Password=admin123");
con.Open();
string sql = "insert into tbl_qus (sub_id,module,topic,question,mark,complexity,lvl) values('" + ddlsub.SelectedValue + "','" + ddlmodule.SelectedValue + "','" + txttopic.Text.Trim() + "',N'" + txtqus.Text.Trim() + "','" + ddlmark.SelectedValue + "','" + ddlcom.SelectedValue + "','" + ddllvl.SelectedValue + "')";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.ExecuteNonQuery();
}
protected void Button2_Click(object sender, EventArgs e)
{
Response.Redirect("staff_home.aspx");
}
}
} |
using System;
using Newtonsoft.Json;
namespace SnakeEyesGame.Models {
[JsonObject(MemberSerialization.OptIn)]
public class SnakeEyes {
#region fields
[JsonProperty]
private Dice _eye1;
[JsonProperty]
private Dice _eye2;
#endregion
#region properties
public int Eye1 { get; }
public int Eye2 { get; }
public bool HasSnakeEyes { get; }
[JsonProperty]
public int Total { get; set; }
#endregion
#region methods
public void Play()
{
_eye1.roll();
_eye2.roll();
if (Eye1 == 1 && Eye2 == 1)
Total = 0;
else
Total += Eye1 + Eye2;
}
#endregion
#region constructors
public SnakeEyes() {
_eye1 = new Dice();
_eye2 = new Dice();
}
#endregion
}
} |
using System;
using Xamarin.Forms;
using City_Center.PopUp;
using City_Center.Clases;
using Acr.UserDialogs;
using City_Center.Helper;
using System.Text.RegularExpressions;
using City_Center.ViewModels;
namespace City_Center.Page
{
public partial class InicioContent : ContentPage
{
public WebViewHotel _webHotel;
public AlertaConfirmacion _AlertaConfirmacion;
InicioViewModel Inicito = new InicioViewModel();
private WebViewTienda pageweb = new WebViewTienda();
public InicioContent()
{
InitializeComponent();
_webHotel = new WebViewHotel();
_AlertaConfirmacion = new AlertaConfirmacion();
FechaInicio.Text = String.Format("{0:dd/MM/yyyy}", DateTime.Today);
FechaFinal.Text = String.Format("{0:dd/MM/yyyy}", DateTime.Today.AddDays(1));
}
protected override void OnDisappearing()
{
base.OnDisappearing();
GC.Collect();
}
protected override void OnAppearing()
{
base.OnAppearing();
}
async void Handle_Clicked(object sender, System.EventArgs e)
{
// Navigation.PushPopupAsync(new MensajeCarga());
//Mensajes.Cargando("Iniciando Sesion");
try
{
if (FechaInicio.Text == "00/00/0000")
{
await Mensajes.Alerta("Fecha inicial requerida.");
return;
}
if (FechaFinal.Text == "00/00/0000")
{
await Mensajes.Alerta("Fecha inicial requerida.");
return;
}
//DateTime fecha1 = Convert.ToDateTime(Application.Current.Properties["FechaNacimiento"].ToString());
string Dia = FechaInicio.Text.Substring(0, 2);
string Mes = FechaInicio.Text.Substring(3, 2);
string Año = FechaInicio.Text.Substring(6, 4);
string Dia2 = FechaFinal.Text.Substring(0, 2);
string Mes2 = FechaFinal.Text.Substring(3, 2);
string Año2 = FechaFinal.Text.Substring(6, 4);
DateTime Fecha1 = Convert.ToDateTime(Año + "-" + Mes + "-" + Dia);
DateTime Fecha2 = Convert.ToDateTime(Año2 + "-" + Mes2 + "-" + Dia2);
if (Fecha2.Date < Fecha1.Date)
{
await Mensajes.Alerta("La fecha final no puede ser menor a la fecha inicial");
}
else
{
VariablesGlobales.FechaInicio = Fecha1.Date;
VariablesGlobales.FechaFin = Fecha2.Date;
VariablesGlobales.NumeroHuespedes = Convert.ToInt32(NoPersona.Text);
//await Navigation.PushPopupAsync(_webHotel);
// #if __ANDROID__
await ((MasterPage)Application.Current.MainPage).Detail.Navigation.PushAsync(_webHotel);
// #endif
}
}
catch (Exception)
{
//await DisplayAlert("oj", ex.ToString(), "ok");
await Mensajes.Alerta("No se pudo acceder a las reservaciones, intente mas tarde.");
}
}
private void Btn1_Clicked(object sender, EventArgs e)
{
SL1.IsVisible = true;
SL2.IsVisible = false;
SL3.IsVisible = false;
SL4.IsVisible = false;
reservarHotel.Source = "RESERVAHOTEL_S";
tickets.Source = "TICKETSHOWS";
reservarMesa.Source = "RESERVATUMESA";
tienda.Source = "TIENDAONLINE";
}
private void Btn2_Clicked(object sender, System.EventArgs e)
{
SL1.IsVisible = false;
SL2.IsVisible = true;
SL3.IsVisible = false;
SL4.IsVisible = false;
reservarHotel.Source = "RESERVAHOTEL";
tickets.Source = "TICKETSHOWS_S";
reservarMesa.Source = "RESERVATUMESA";
tienda.Source = "TIENDAONLINE";
}
private void Btn3_Clicked(object sender, System.EventArgs e)
{
SL1.IsVisible = false;
SL2.IsVisible = false;
SL3.IsVisible = true;
SL4.IsVisible = false;
reservarHotel.Source = "RESERVAHOTEL";
tickets.Source = "TICKETSHOWS";
reservarMesa.Source = "RESERVATUMESA_S";
tienda.Source = "TIENDAONLINE";
}
private async void Btn4_Clicked(object sender, System.EventArgs e)
{
//SL1.IsVisible = false;
//SL2.IsVisible = false;
//SL3.IsVisible = false;
//SL4.IsVisible = true;
//reservarHotel.Source = "RESERVAHOTEL";
//tickets.Source = "TICKETSHOWS";
//reservarMesa.Source = "RESERVATUMESA";
//tienda.Source = "TIENDAONLINE_S";
await((MasterPage)Application.Current.MainPage).Detail.Navigation.PushAsync(new WebViewTienda());
}
void CambiaIcono(object sender, System.EventArgs e)
{
try
{
bool isLoggedIn = Application.Current.Properties.ContainsKey("IsLoggedIn") ?
(bool)Application.Current.Properties["IsLoggedIn"] : false;
if (isLoggedIn)
{
Image image = sender as Image;
if (image.BackgroundColor != Color.Transparent)
{
image.BackgroundColor = Color.Transparent;
image.Source = "Fav";
}
else
{
image.BackgroundColor = Color.White;
image.Source = "Favorito";
}
}
}
catch (Exception)
{
}
}
void CambiaIcono2(object sender, System.EventArgs e)
{
try
{
bool isLoggedIn = Application.Current.Properties.ContainsKey("IsLoggedIn") ?
(bool)Application.Current.Properties["IsLoggedIn"] : false;
if (isLoggedIn)
{
Image image = sender as Image;
if (image.BackgroundColor != Color.Transparent)
{
image.BackgroundColor = Color.Transparent;
image.Source = "Favorito";
}
else
{
image.BackgroundColor = Color.White;
image.Source = "Fav";
}
}
}
catch (Exception)
{
}
}
async void FechaFin_Focused(object sender, Xamarin.Forms.FocusEventArgs e)
{
#if __IOS__
DependencyService.Get<IForceKeyboardDismissalService>().DismissKeyboard();
#endif
var result = await UserDialogs.Instance.DatePromptAsync(new DatePromptConfig
{
IsCancellable = true,
CancelText = "CANCELAR",
MinimumDate = DateTime.Now.AddDays(0),
Title = "Salida"
});
if (result.Ok)
{
FechaFinal.Text = String.Format("{0:dd/MM/yyyy}", result.SelectedDate);
FechaFinal.Unfocus();
DependencyService.Get<IForceKeyboardDismissalService>().DismissKeyboard();
}
else
{
FechaFinal.Unfocus();
DependencyService.Get<IForceKeyboardDismissalService>().DismissKeyboard();
}
//String.Format("{0:dd MMMM yyyy}"
}
async void FechaRango1_Focused(object sender, Xamarin.Forms.FocusEventArgs e)
{
#if __IOS__
DependencyService.Get<IForceKeyboardDismissalService>().DismissKeyboard();
#endif
var result = await UserDialogs.Instance.DatePromptAsync(new DatePromptConfig
{
IsCancellable = true,
CancelText = "CANCELAR",
MinimumDate = DateTime.Now.AddDays(0)
});
if (result.Ok)
{
FechaRango1.Text = String.Format("{0:dd/MM/yyyy}", result.SelectedDate);
FechaRango1.Unfocus();
DependencyService.Get<IForceKeyboardDismissalService>().DismissKeyboard();
}
else
{
FechaRango1.Unfocus();
DependencyService.Get<IForceKeyboardDismissalService>().DismissKeyboard();
}
//String.Format("{0:dd MMMM yyyy}"
}
async void FechaRango2_Focused(object sender, Xamarin.Forms.FocusEventArgs e)
{
#if __IOS__
DependencyService.Get<IForceKeyboardDismissalService>().DismissKeyboard();
#endif
var result = await UserDialogs.Instance.DatePromptAsync(new DatePromptConfig
{
IsCancellable = true,
CancelText = "CANCELAR",
MinimumDate = DateTime.Now.AddDays(0)
});
if (result.Ok)
{
FechaRango2.Text = String.Format("{0:dd/MM/yyyy}", result.SelectedDate);
FechaRango2.Unfocus();
DependencyService.Get<IForceKeyboardDismissalService>().DismissKeyboard();
}
else
{
FechaRango2.Unfocus();
DependencyService.Get<IForceKeyboardDismissalService>().DismissKeyboard();
}
//String.Format("{0:dd MMMM yyyy}"
}
void Handle_TextChanged(object sender, Xamarin.Forms.TextChangedEventArgs e)
{
try
{
Entry entry = sender as Entry;
String val = entry.Text; //Get Current Text
if (val.Length > 0)//If it is more than your character restriction
{
Match match = Regex.Match(val, @"([0-9\-]+)$",
RegexOptions.IgnoreCase);
if (!match.Success)
{
val = val.Remove(val.Length - 1);
entry.Text = val;
return;
}
//Set the Old value
}
}
catch (Exception)
{
}
}
// void PositionSelected_CT(object sender, CarouselView.FormsPlugin.Abstractions.PositionSelectedEventArgs e)
// {
// VariablesGlobales.indice = e.NewValue;
//#if __IOS__
// try
// {
// if (VariablesGlobales.validacionIOS == 1)
// {
// if (e.NewValue != 0)
// {
// CarruselTorneos.Position = 0;
// VariablesGlobales.indice = 1;
// }
// }
// else if (VariablesGlobales.validacionIOS == 2)
// {
// //if (e.NewValue == 0)
// //{
// CarruselTorneos.Position = VariablesGlobales.RegistrosTorneo + 1;
// VariablesGlobales.indice = VariablesGlobales.RegistrosTorneo;
// //}
// }
// }
// catch (Exception)
// {
// }
//#endif
// }
// void Scrolled_CT(object sender, CarouselView.FormsPlugin.Abstractions.ScrolledEventArgs e)
// {
//#if __IOS__
// try
// {
// string Direccion = Convert.ToString(e.Direction);
// if (VariablesGlobales.indice == VariablesGlobales.RegistrosTorneo && Direccion == "Right")
// {
// //CarruselTorneos.ItemsSource = Inicito.TorneoDetalle;
// VariablesGlobales.validacionIOS = 1;
// CarruselTorneos.Position = 0;
// CarruselTorneos.AnimateTransition = false;
// }
// else if (VariablesGlobales.indice == 1 && Direccion == "Left")
// {
// CarruselTorneos.AnimateTransition = false;
// VariablesGlobales.validacionIOS = 2;
// CarruselTorneos.Position = VariablesGlobales.RegistrosTorneo + 1;
// }
// else
// {
// VariablesGlobales.validacionIOS = 0;
// }
// }
// catch (Exception ex)
// {
// DisplayAlert("Error", ex.ToString(), "OK");
// }
//#endif
//#if __ANDROID__
// try
// {
// string Direccion = Convert.ToString(e.Direction);
// if (VariablesGlobales.indice == VariablesGlobales.RegistrosTorneo && Direccion == "Right")
// {
// CarruselTorneos.AnimateTransition = false;
// CarruselTorneos.Position = 1;
// }
// else if (VariablesGlobales.indice == 1 && Direccion == "Left")
// {
// CarruselTorneos.AnimateTransition = false;
// CarruselTorneos.Position = VariablesGlobales.RegistrosTorneo + 1;
// }
// }
// catch (Exception ex)
// {
// DisplayAlert("Error", ex.ToString(), "OK");
// }
//#endif
//}
// void Scrolled_HP(object sender, CarouselView.FormsPlugin.Abstractions.ScrolledEventArgs e)
// {
//#if __IOS__
// try
// {
// string Direccion = Convert.ToString(e.Direction);
// if (VariablesGlobales.IndicePromociones == VariablesGlobales.RegistrosPromociones && Direccion == "Right")
// {
// VariablesGlobales.validacionIOSPromociones = 1;
// CarruselPromociones.Position = 0;
// CarruselPromociones.AnimateTransition = false;
// }
// else if (VariablesGlobales.IndicePromociones == 1 && Direccion == "Left")
// {
// CarruselPromociones.AnimateTransition = false;
// VariablesGlobales.validacionIOSPromociones = 2;
// CarruselPromociones.Position = VariablesGlobales.RegistrosPromociones + 1;
// }
// else
// {
// VariablesGlobales.validacionIOSPromociones = 0;
// }
// }
// catch (Exception ex)
// {
// DisplayAlert("Error", ex.ToString(), "OK");
// }
//#endif
//#if __ANDROID__
// try
// {
// string Direccion = Convert.ToString(e.Direction);
// if (VariablesGlobales.IndicePromociones >= VariablesGlobales.RegistrosPromociones && Direccion == "Right")
// {
// CarruselPromociones.AnimateTransition = false;
// CarruselPromociones.Position = 0;
// }
// else if (VariablesGlobales.IndicePromociones <= 1 && Direccion == "Left")
// {
// CarruselPromociones.AnimateTransition = false;
// CarruselPromociones.Position = VariablesGlobales.RegistrosPromociones + 1;
// }
// }
// catch (Exception ex)
// {
// }
//#endif
// }
// void PositionSelected_HP(object sender, CarouselView.FormsPlugin.Abstractions.PositionSelectedEventArgs e)
// {
// VariablesGlobales.IndicePromociones = e.NewValue;
//#if __IOS__
// try
// {
// if (VariablesGlobales.validacionIOSPromociones == 1)
// {
// if (e.NewValue != 0)
// {
// CarruselPromociones.Position = 0;
// VariablesGlobales.IndicePromociones = 1;
// // e.NewValue =1;
// }
// }
// else if (VariablesGlobales.validacionIOSPromociones == 2)
// {
// //if (e.NewValue == 0)
// //{
// CarruselPromociones.Position = VariablesGlobales.RegistrosPromociones + 1;
// VariablesGlobales.IndicePromociones = VariablesGlobales.RegistrosPromociones;
// //}
// }
// }
// catch (Exception)
// {
// }
//#endif
//}
async void Fecha_Tapped(object sender, System.EventArgs e)
{
#if __IOS__
DependencyService.Get<IForceKeyboardDismissalService>().DismissKeyboard();
#endif
var result = await UserDialogs.Instance.DatePromptAsync(new DatePromptConfig
{
Title = "Llegada",
CancelText = "CANCELAR",
IsCancellable = true,
MinimumDate = DateTime.Now.AddDays(0)
});
if (result.Ok)
{
FechaInicio.Text = String.Format("{0:dd/MM/yyyy}", result.SelectedDate);
FechaInicio.Unfocus();
DependencyService.Get<IForceKeyboardDismissalService>().DismissKeyboard();
}
else
{
FechaInicio.Unfocus();
DependencyService.Get<IForceKeyboardDismissalService>().DismissKeyboard();
}
}
async void Fecha2_Tapped(object sender, System.EventArgs e)
{
#if __IOS__
DependencyService.Get<IForceKeyboardDismissalService>().DismissKeyboard();
#endif
var result = await UserDialogs.Instance.DatePromptAsync(new DatePromptConfig
{
IsCancellable = true,
CancelText = "CANCELAR",
MinimumDate = DateTime.Now.AddDays(0),
Title = "Salida"
});
if (result.Ok)
{
FechaFinal.Text = String.Format("{0:dd/MM/yyyy}", result.SelectedDate);
FechaFinal.Unfocus();
DependencyService.Get<IForceKeyboardDismissalService>().DismissKeyboard();
}
else
{
FechaFinal.Unfocus();
DependencyService.Get<IForceKeyboardDismissalService>().DismissKeyboard();
}
}
async void Hora_Tapped(object sender, System.EventArgs e)
{
#if __IOS__
DependencyService.Get<IForceKeyboardDismissalService>().DismissKeyboard();
#endif
if (Restaurante.Text.Contains("PIÚ"))
{
var result = await UserDialogs.Instance.ActionSheetAsync("Horario", "CANCELAR", null, null, "12:30", "20:30", "21:00", "23:00");
if (result != "CANCELAR")
{
HoraR1.Text = result.ToString();
HoraR1.Unfocus();
DependencyService.Get<IForceKeyboardDismissalService>().DismissKeyboard();
}
else
{
HoraR1.Text = "12:30";
HoraR1.Unfocus();
DependencyService.Get<IForceKeyboardDismissalService>().DismissKeyboard();
}
}
else if (Restaurante.Text.Contains("LE GULÁ"))
{
var result = await UserDialogs.Instance.ActionSheetAsync("Horario", "CANCELAR", null, null, "21:00", "23:00");
if (result != "CANCELAR")
{
HoraR1.Text = result.ToString();
HoraR1.Unfocus();
DependencyService.Get<IForceKeyboardDismissalService>().DismissKeyboard();
}
else
{
HoraR1.Text = "21:00";
HoraR1.Unfocus();
DependencyService.Get<IForceKeyboardDismissalService>().DismissKeyboard();
}
}
else if (Restaurante.Text.Contains("CITY ROCK"))
{
var result = await UserDialogs.Instance.ActionSheetAsync("Horario", "CANCELAR", null, null, "20:30");
if (result != "CANCELAR")
{
HoraR1.Text = result.ToString();
HoraR1.Unfocus();
DependencyService.Get<IForceKeyboardDismissalService>().DismissKeyboard();
}
else
{
HoraR1.Text = "20:30";
HoraR1.Unfocus();
DependencyService.Get<IForceKeyboardDismissalService>().DismissKeyboard();
}
}
else
{
var result = await UserDialogs.Instance.TimePromptAsync(new TimePromptConfig
{
IsCancellable = true,
CancelText="CANCELAR"
});
if (result.Ok)
{
HoraR1.Text = FechaRango1.Text = (Convert.ToString(result.SelectedTime).Substring(0, 5));
HoraR1.Unfocus();
DependencyService.Get<IForceKeyboardDismissalService>().DismissKeyboard();
}
else
{
HoraR1.Unfocus();
DependencyService.Get<IForceKeyboardDismissalService>().DismissKeyboard();
}
}
}
async void FechaR1_Tapped(object sender, System.EventArgs e)
{
#if __IOS__
DependencyService.Get<IForceKeyboardDismissalService>().DismissKeyboard();
#endif
var result = await UserDialogs.Instance.DatePromptAsync(new DatePromptConfig
{
IsCancellable = true,
CancelText = "CANCELAR",
MinimumDate = DateTime.Now.AddDays(0)
});
if (result.Ok)
{
FechaR1.Text = String.Format("{0:dd/MM/yyyy}", result.SelectedDate);
FechaR1.Unfocus();
DependencyService.Get<IForceKeyboardDismissalService>().DismissKeyboard();
}
else
{
FechaR1.Unfocus();
DependencyService.Get<IForceKeyboardDismissalService>().DismissKeyboard();
}
//String.Format("{0:dd MMMM yyyy}"
}
async void Silla_Tapped(object sender, System.EventArgs e)
{
#if __IOS__
DependencyService.Get<IForceKeyboardDismissalService>().DismissKeyboard();
#endif
var result = await UserDialogs.Instance.ActionSheetAsync("Sillas niños", "CANCELAR", null, null, "No", "Si");
if (result != "CANCELAR")
{
SillaNiño.Text = result.ToString();
SillaNiño.Unfocus();
DependencyService.Get<IForceKeyboardDismissalService>().DismissKeyboard();
}
else
{
SillaNiño.Unfocus();
DependencyService.Get<IForceKeyboardDismissalService>().DismissKeyboard();
}
}
async void Restaurante_Tapped(object sender, System.EventArgs e)
{
#if __IOS__
DependencyService.Get<IForceKeyboardDismissalService>().DismissKeyboard();
#endif
// "LE GULÁ", "PIÚ! EXPRESS"
string result= "";
switch (VariablesGlobales.NumeroArreglo)
{
case 0:
result = await UserDialogs.Instance.ActionSheetAsync("Restaurant", "CANCELAR", null, null, VariablesGlobales.ArregloRestaurantes[0], VariablesGlobales.ArregloRestaurantes[1]);
break;
case 1:
result = await UserDialogs.Instance.ActionSheetAsync("Restaurant",
"CANCELAR",
null,
null,
VariablesGlobales.ArregloRestaurantes[0],
VariablesGlobales.ArregloRestaurantes[1]);
break;
case 2:
result = await UserDialogs.Instance.ActionSheetAsync("Restaurant",
"CANCELAR",
null,
null,
VariablesGlobales.ArregloRestaurantes[0],
VariablesGlobales.ArregloRestaurantes[1],
VariablesGlobales.ArregloRestaurantes[2]);
break;
case 3:
result = await UserDialogs.Instance.ActionSheetAsync("Restaurant",
"CANCELAR",
null,
null,
VariablesGlobales.ArregloRestaurantes[0],
VariablesGlobales.ArregloRestaurantes[1],
VariablesGlobales.ArregloRestaurantes[2],
VariablesGlobales.ArregloRestaurantes[3]);
break;
case 4:
result = await UserDialogs.Instance.ActionSheetAsync("Restaurant",
"CANCELAR",
null,
null,
VariablesGlobales.ArregloRestaurantes[0],
VariablesGlobales.ArregloRestaurantes[1],
VariablesGlobales.ArregloRestaurantes[2],
VariablesGlobales.ArregloRestaurantes[3],
VariablesGlobales.ArregloRestaurantes[4]);
break;
case 5:
result = await UserDialogs.Instance.ActionSheetAsync("Restaurant",
"CANCELAR",
null,
null,
VariablesGlobales.ArregloRestaurantes[0],
VariablesGlobales.ArregloRestaurantes[1],
VariablesGlobales.ArregloRestaurantes[2],
VariablesGlobales.ArregloRestaurantes[3],
VariablesGlobales.ArregloRestaurantes[4],
VariablesGlobales.ArregloRestaurantes[5]);
break;
}
if (result != "CANCELAR")
{
Restaurante.Text = result.ToString();
if (Restaurante.Text.Contains("PIÚ"))
{
HoraR1.Text = "12:30";
}
else if (Restaurante.Text.Contains("LE GULÁ"))
{
HoraR1.Text = "21:00";
}
else if (Restaurante.Text.Contains("CITY ROCK"))
{
HoraR1.Text = "20:30";
}
Restaurante.Unfocus();
DependencyService.Get<IForceKeyboardDismissalService>().DismissKeyboard();
}
else
{
HoraR1.Text = "00:00";
Restaurante.Unfocus();
DependencyService.Get<IForceKeyboardDismissalService>().DismissKeyboard();
}
}
void Promociones_PositionSelected(object sender, Xamarin.Forms.SelectedPositionChangedEventArgs e)
{
int Position = Convert.ToInt32(e.SelectedPosition);
if (Position == VariablesGlobales.RegistrosPromociones)
{
CarruselPromociones.Position = 1;
}
else if (Position == 0)
{
CarruselPromociones.Position = VariablesGlobales.RegistrosPromociones-1;
}
}
void Torneo_PositionSelected(object sender, Xamarin.Forms.SelectedPositionChangedEventArgs e)
{
int Position = Convert.ToInt32(e.SelectedPosition);
if (Position == VariablesGlobales.RegistrosTorneo)
{
CarruselTorneos.Position = 1;
}
else if (Position == 0)
{
CarruselTorneos.Position = VariablesGlobales.RegistrosTorneo - 1;
}
}
}
} |
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.Internal;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Serilog;
using SSW.DataOnion.Interfaces;
using System.Linq;
namespace SSW.DataOnion.Core
{
/// <summary>
/// Factory for creating new instance of DbContext. Uses initializer and connection string to create new
/// database instance
/// </summary>
public class DbContextFactory : IDbContextFactory
{
private readonly ILogger logger = Log.ForContext<DbContextFactory>();
private readonly DbContextConfig[] dbContextConfigs;
private static bool hasSetInitializer;
/// <summary>
/// Initializes a new instance of the <see cref="DbContextFactory"/> class.
/// </summary>
/// <param name="dbContextConfigs">The database context configurations.</param>
public DbContextFactory(params DbContextConfig[] dbContextConfigs)
{
Guard.AgainstNull(dbContextConfigs, nameof(dbContextConfigs));
Guard.Against(
() => this.InvalidConfigurations(dbContextConfigs),
"At least one db context configuration must be specified for DbContextFactory");
this.dbContextConfigs = dbContextConfigs;
}
/// <summary>
/// Creates new instance of DbContext using specified initializer.
/// </summary>
/// <returns></returns>
public virtual TDbContext Create<TDbContext>() where TDbContext : DbContext
{
var config = this.dbContextConfigs.FirstOrDefault(c => c.DbContextType == typeof(TDbContext));
if (config == null)
{
throw new DataOnionException($"Could not find any configurations for DbContext of type {typeof(TDbContext)}");
}
this.logger.Debug(
"Creating new dbContext with connection string {connectionString}", config.ConnectionString);
// create serviceProvider
var serviceProvider =
new ServiceCollection()
.AddDbContext<TDbContext>(
options =>
{
options.UseSqlServer(config.ConnectionString);
})
.BuildServiceProvider();
var dbContext = serviceProvider.GetService<TDbContext>();
if (hasSetInitializer)
{
return dbContext;
}
config.DatabaseInitializer.Initialize(dbContext);
hasSetInitializer = true;
return dbContext;
}
private IEnumerable<string> InvalidConfigurations(DbContextConfig[] dbContextConfigurations)
{
if (!dbContextConfigurations.Any())
{
yield return "At least one db context configuration must be specified for DbContextFactory";
}
}
}
}
|
using System.Threading.Tasks;
using Psibr.Platform.Logging;
using Psibr.Platform.Serialization;
using RabbitMQ.Client;
using REstate.Services;
namespace REstate.Connectors.RabbitMq
{
public class RabbitMqConnectorFactory
: IConnectorFactory
{
private readonly ConnectionFactory _connectionFactory;
private readonly IStringSerializer _stringSerializer;
private readonly IPlatformLogger _logger;
public RabbitMqConnectorFactory(ConnectionFactory connectionFactory,
IStringSerializer stringSerializer, IPlatformLogger logger)
{
_connectionFactory = connectionFactory;
_stringSerializer = stringSerializer;
_logger = logger;
}
public Task<IConnector> BuildConnector(string apiKey)
{
return Task.FromResult<IConnector>(new RabbitMqConnector(_connectionFactory, _stringSerializer, _logger));
}
string IConnectorFactory.ConnectorKey => ConnectorKey;
public bool IsActionConnector { get; } = true;
public bool IsGuardConnector { get; } = false;
public string ConnectorSchema { get; set; } = "{ }";
public static string ConnectorKey => "REstate.Connectors.RabbitMq";
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
using System.Collections;
/// <summary>
/// Summary description for MailClass
/// </summary>
public class MailClass
{
string connStr = ConfigurationManager.ConnectionStrings["BizCon"].ConnectionString;
string connJun = ConfigurationManager.ConnectionStrings["SCMCon"].ConnectionString;
string GSTConnStr = ConfigurationManager.ConnectionStrings["GST"].ConnectionString;
SqlConnection obj_BizConn = new SqlConnection();
SqlConnection obj_SCMConn = new SqlConnection();
SqlConnection obj_GSTConn = new SqlConnection();
public MailClass()
{
//
// TODO: Add constructor logic here
//
string BizConnStr = ConfigurationManager.ConnectionStrings["BizCon"].ConnectionString;
string SCMConnStr = ConfigurationManager.ConnectionStrings["SCMCon"].ConnectionString;
string GSTConnStr = ConfigurationManager.ConnectionStrings["GST"].ConnectionString;
obj_BizConn.ConnectionString = BizConnStr;
obj_SCMConn.ConnectionString = SCMConnStr;
obj_GSTConn.ConnectionString = GSTConnStr;
}
public DataSet MailForReBidPriceToTransporter()
{
DataSet ds = new DataSet();
ds.Clear();
obj_BizConn.Open();
using (SqlCommand cmd = new SqlCommand("MailForReBidPriceToTransporter", obj_BizConn))
{
try
{
SqlDataAdapter ada = new SqlDataAdapter(cmd);
ada.SelectCommand.CommandType = CommandType.StoredProcedure;
ada.Fill(ds, "RebidMail");
}
catch (Exception ex)
{
}
finally
{
obj_BizConn.Close();
}
}
return ds;
}
//Mail to Transporter for RoutePrice Status
public DataSet Transporter_RoutePricestatus()
{
DataSet ds = new DataSet();
ds.Clear();
obj_BizConn.Open();
using (SqlCommand cmd = new SqlCommand("Transporter_RoutePricestatus", obj_BizConn))
{
try
{
SqlDataAdapter ada = new SqlDataAdapter(cmd);
ada.SelectCommand.CommandType = CommandType.StoredProcedure;
ada.Fill(ds, "RebidMail");
}
catch (Exception ex)
{
}
finally
{
obj_BizConn.Close();
}
}
return ds;
}
} |
namespace Triton.Game.Mapping
{
using ns26;
using System;
using Triton.Game;
using Triton.Game.Mono;
[Attribute38("SpecialEventManager")]
public class SpecialEventManager : MonoClass
{
public SpecialEventManager(IntPtr address) : this(address, "SpecialEventManager")
{
}
public SpecialEventManager(IntPtr address, string className) : base(address, className)
{
}
public bool ForceEventActive(SpecialEventType eventType)
{
object[] objArray1 = new object[] { eventType };
return base.method_11<bool>("ForceEventActive", objArray1);
}
public static SpecialEventManager Get()
{
return MonoClass.smethod_15<SpecialEventManager>(TritonHs.MainAssemblyPath, "", "SpecialEventManager", "Get", Array.Empty<object>());
}
public bool HasEventEnded(SpecialEventType eventType)
{
object[] objArray1 = new object[] { eventType };
return base.method_11<bool>("HasEventEnded", objArray1);
}
public bool HasEventStarted(SpecialEventType eventType)
{
object[] objArray1 = new object[] { eventType };
return base.method_11<bool>("HasEventStarted", objArray1);
}
public bool IsEventActive(string eventName, bool activeIfDoesNotExist)
{
Class272.Enum20[] enumArray1 = new Class272.Enum20[] { Class272.Enum20.String, Class272.Enum20.Boolean };
object[] objArray1 = new object[] { eventName, activeIfDoesNotExist };
return base.method_10<bool>("IsEventActive", enumArray1, objArray1);
}
public bool IsEventActive(SpecialEventType eventType, bool activeIfDoesNotExist)
{
Class272.Enum20[] enumArray1 = new Class272.Enum20[] { Class272.Enum20.ValueType, Class272.Enum20.Boolean };
object[] objArray1 = new object[] { eventType, activeIfDoesNotExist };
return base.method_10<bool>("IsEventActive", enumArray1, objArray1);
}
public void OnReset()
{
base.method_8("OnReset", Array.Empty<object>());
}
[Attribute38("SpecialEventManager.EventTiming")]
public class EventTiming : MonoClass
{
public EventTiming(IntPtr address) : this(address, "EventTiming")
{
}
public EventTiming(IntPtr address, string className) : base(address, className)
{
}
public bool HasEnded()
{
return base.method_11<bool>("HasEnded", Array.Empty<object>());
}
public bool HasStarted()
{
return base.method_11<bool>("HasStarted", Array.Empty<object>());
}
public bool IsActiveNow()
{
return base.method_11<bool>("IsActiveNow", Array.Empty<object>());
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
/// <summary>
/// Summary description for WebServiceFacadeHelper
/// </summary>
public class WebServiceFacadeHelper
{
public WebServiceFacadeHelper()
{
//
// TODO: Add constructor logic here
//
}
public PersonService.PersonService GetPersonService()
{
PersonService.PersonService personService = new PersonService.PersonService();
personService.PTJSoapHeaderValue = new PersonService.PTJSoapHeader()
{
TimeView = DateTime.Now,
CurrentUser = System.Security.Principal.WindowsIdentity.GetCurrent().Name,
CurrentRowLevelSecurity = "N/D",
CurrentDataRole = "SomeRole",
};
return personService;
}
public AdressTypService.AdressTypService GetAdressTypService()
{
AdressTypService.AdressTypService adressTypService = new AdressTypService.AdressTypService();
adressTypService.PTJSoapHeaderValue = new AdressTypService.PTJSoapHeader()
{
TimeView = DateTime.Now,
CurrentUser = System.Security.Principal.WindowsIdentity.GetCurrent().Name,
CurrentRowLevelSecurity = "N/D",
CurrentDataRole = "SomeRole",
};
return adressTypService;
}
public AdressVariantService.AdressVariantService GetAdressVariantService()
{
AdressVariantService.AdressVariantService adressVariantService = new AdressVariantService.AdressVariantService();
adressVariantService.PTJSoapHeaderValue = new AdressVariantService.PTJSoapHeader()
{
TimeView = DateTime.Now,
CurrentUser = System.Security.Principal.WindowsIdentity.GetCurrent().Name,
CurrentRowLevelSecurity = "N/D",
CurrentDataRole = "SomeRole",
};
return adressVariantService;
}
public GatuAdressService.GatuAdressService GetGatuAdressService()
{
GatuAdressService.GatuAdressService gatuAdressService = new GatuAdressService.GatuAdressService();
gatuAdressService.PTJSoapHeaderValue = new GatuAdressService.PTJSoapHeader()
{
TimeView = DateTime.Now,
CurrentUser = System.Security.Principal.WindowsIdentity.GetCurrent().Name,
CurrentRowLevelSecurity = "N/D",
CurrentDataRole = "SomeRole",
};
return gatuAdressService;
}
public MailService.MailService GetMailService()
{
MailService.MailService mailService = new MailService.MailService();
mailService.PTJSoapHeaderValue = new MailService.PTJSoapHeader()
{
TimeView = DateTime.Now,
CurrentUser = System.Security.Principal.WindowsIdentity.GetCurrent().Name,
CurrentRowLevelSecurity = "N/D",
CurrentDataRole = "SomeRole",
};
return mailService;
}
public TelefonService.TelefonService GetTelefonService()
{
TelefonService.TelefonService telefonService = new TelefonService.TelefonService();
telefonService.PTJSoapHeaderValue = new TelefonService.PTJSoapHeader()
{
TimeView = DateTime.Now,
CurrentUser = System.Security.Principal.WindowsIdentity.GetCurrent().Name,
CurrentRowLevelSecurity = "N/D",
CurrentDataRole = "SomeRole",
};
return telefonService;
}
public AdressService.AdressService GetAdressService()
{
AdressService.AdressService adressService = new AdressService.AdressService();
adressService.PTJSoapHeaderValue = new AdressService.PTJSoapHeader()
{
TimeView = DateTime.Now,
CurrentUser = System.Security.Principal.WindowsIdentity.GetCurrent().Name,
CurrentRowLevelSecurity = "N/D",
CurrentDataRole = "SomeRole",
};
return adressService;
}
public PersonService.TransportMessageOfArrayOfKeyValueOfPersonSchemaAdressSchema GetTransportArrPerson_Adress()
{
return new PersonService.TransportMessageOfArrayOfKeyValueOfPersonSchemaAdressSchema();
}
public PersonService.TransportMessageOfArrayOfPersonSchema GetTransportArrPerson()
{
return new PersonService.TransportMessageOfArrayOfPersonSchema();
}
public PersonService.TransportMessageOfPersonSchema GetTransportPerson()
{
return new PersonService.TransportMessageOfPersonSchema();
}
public AdressService.TransportMessageOfAdressSchema GetTransportAdress()
{
return new AdressService.TransportMessageOfAdressSchema();
}
public AdressService.TransportMessageOfArrayOfAdressSchema GetTransportArrAdress()
{
return new AdressService.TransportMessageOfArrayOfAdressSchema();
}
public AdressService.TransportMessageOfArrayOfKeyValueOfAdressSchemaAdressTypSchema GetTransportArrAdress_AdressTyp()
{
return new AdressService.TransportMessageOfArrayOfKeyValueOfAdressSchemaAdressTypSchema();
}
public AdressService.TransportMessageOfArrayOfKeyValueOfAdressSchemaAdressVariantSchema GetTransportArrAdress_AdressVariant()
{
return new AdressService.TransportMessageOfArrayOfKeyValueOfAdressSchemaAdressVariantSchema();
}
public AdressService.TransportMessageOfArrayOfKeyValueOfAdressSchemaGatuAdressSchema GetTransportArrAdress_GatuAdress()
{
return new AdressService.TransportMessageOfArrayOfKeyValueOfAdressSchemaGatuAdressSchema();
}
public AdressService.TransportMessageOfArrayOfKeyValueOfAdressSchemaMailSchema GetTransportArrAdress_Mail()
{
return new AdressService.TransportMessageOfArrayOfKeyValueOfAdressSchemaMailSchema();
}
public AdressService.TransportMessageOfArrayOfKeyValueOfAdressSchemaPersonSchema GetTransportArrAdress_Person()
{
return new AdressService.TransportMessageOfArrayOfKeyValueOfAdressSchemaPersonSchema();
}
public AdressService.TransportMessageOfArrayOfKeyValueOfAdressSchemaTelefonSchema GetTransportArrAdress_Telefon()
{
return new AdressService.TransportMessageOfArrayOfKeyValueOfAdressSchemaTelefonSchema();
}
public AdressVariantService.TransportMessageOfAdressVariantSchema GetTransportAdressVariant()
{
return new AdressVariantService.TransportMessageOfAdressVariantSchema();
}
public AdressVariantService.TransportMessageOfArrayOfAdressVariantSchema GetTransportArrAdressVariant()
{
return new AdressVariantService.TransportMessageOfArrayOfAdressVariantSchema();
}
public AdressVariantService.TransportMessageOfArrayOfKeyValueOfAdressVariantSchemaAdressSchema GetTransportArrAdressVariant_Adress()
{
return new AdressVariantService.TransportMessageOfArrayOfKeyValueOfAdressVariantSchemaAdressSchema();
}
public AdressVariantService.TransportMessageOfArrayOfKeyValueOfAdressVariantSchemaAdressTypSchema GetTransportArrAdressVariant_AdressTyp()
{
return new AdressVariantService.TransportMessageOfArrayOfKeyValueOfAdressVariantSchemaAdressTypSchema();
}
public GatuAdressService.TransportMessageOfArrayOfGatuAdressSchema GetTransportArrGatuAdress()
{
return new GatuAdressService.TransportMessageOfArrayOfGatuAdressSchema();
}
public GatuAdressService.TransportMessageOfArrayOfKeyValueOfGatuAdressSchemaAdressSchema GetTransportArrGatuAdress_Adress()
{
return new GatuAdressService.TransportMessageOfArrayOfKeyValueOfGatuAdressSchemaAdressSchema();
}
public GatuAdressService.TransportMessageOfGatuAdressSchema GetTransportGatuAdress()
{
return new GatuAdressService.TransportMessageOfGatuAdressSchema();
}
public MailService.TransportMessageOfMailSchema GetTransportMail()
{
return new MailService.TransportMessageOfMailSchema();
}
public MailService.TransportMessageOfArrayOfMailSchema GetTransportArrMail()
{
return new MailService.TransportMessageOfArrayOfMailSchema();
}
public MailService.TransportMessageOfArrayOfKeyValueOfMailSchemaAdressSchema GetTransportArrMail_Adress()
{
return new MailService.TransportMessageOfArrayOfKeyValueOfMailSchemaAdressSchema();
}
public TelefonService.TransportMessageOfTelefonSchema GetTransportTelefon()
{
return new TelefonService.TransportMessageOfTelefonSchema();
}
public TelefonService.TransportMessageOfArrayOfTelefonSchema GetTransportArrTelefon()
{
return new TelefonService.TransportMessageOfArrayOfTelefonSchema();
}
public TelefonService.TransportMessageOfArrayOfKeyValueOfTelefonSchemaAdressSchema GetTransportArrTelefon_Adress()
{
return new TelefonService.TransportMessageOfArrayOfKeyValueOfTelefonSchemaAdressSchema();
}
public bool HasMessages(PersonService.TransportMessageOfArrayOfKeyValueOfPersonSchemaAdressSchema transportItem)
{
return transportItem.lstMessages.Count() > 0;
}
public bool HasMessages(PersonService.TransportMessageOfArrayOfPersonSchema transportItem)
{
return transportItem.lstMessages.Count() > 0;
}
public bool HasMessages(PersonService.TransportMessageOfPersonSchema transportItem)
{
return transportItem.lstMessages.Count() > 0;
}
public bool HasMessages(AdressService.TransportMessageOfAdressSchema transportItem)
{
return transportItem.lstMessages.Count() > 0;
}
public bool HasMessages(AdressService.TransportMessageOfArrayOfAdressSchema transportItem)
{
return transportItem.lstMessages.Count() > 0;
}
public bool HasMessages(AdressService.TransportMessageOfArrayOfKeyValueOfAdressSchemaAdressTypSchema transportItem)
{
return transportItem.lstMessages.Count() > 0;
}
public bool HasMessages(AdressService.TransportMessageOfArrayOfKeyValueOfAdressSchemaAdressVariantSchema transportItem)
{
return transportItem.lstMessages.Count() > 0;
}
public bool HasMessages(AdressService.TransportMessageOfArrayOfKeyValueOfAdressSchemaGatuAdressSchema transportItem)
{
return transportItem.lstMessages.Count() > 0;
}
public bool HasMessages(AdressService.TransportMessageOfArrayOfKeyValueOfAdressSchemaMailSchema transportItem)
{
return transportItem.lstMessages.Count() > 0;
}
public bool HasMessages(AdressService.TransportMessageOfArrayOfKeyValueOfAdressSchemaPersonSchema transportItem)
{
return transportItem.lstMessages.Count() > 0;
}
public bool HasMessages(AdressService.TransportMessageOfArrayOfKeyValueOfAdressSchemaTelefonSchema transportItem)
{
return transportItem.lstMessages.Count() > 0;
}
public bool HasMessages(AdressVariantService.TransportMessageOfAdressVariantSchema transportItem)
{
return transportItem.lstMessages.Count() > 0;
}
public bool HasMessages(AdressVariantService.TransportMessageOfArrayOfAdressVariantSchema transportItem)
{
return transportItem.lstMessages.Count() > 0;
}
public bool HasMessages(AdressVariantService.TransportMessageOfArrayOfKeyValueOfAdressVariantSchemaAdressSchema transportItem)
{
return transportItem.lstMessages.Count() > 0;
}
public bool HasMessages(AdressVariantService.TransportMessageOfArrayOfKeyValueOfAdressVariantSchemaAdressTypSchema transportItem)
{
return transportItem.lstMessages.Count() > 0;
}
public bool HasMessages(GatuAdressService.TransportMessageOfArrayOfGatuAdressSchema transportItem)
{
return transportItem.lstMessages.Count() > 0;
}
public bool HasMessages(GatuAdressService.TransportMessageOfArrayOfKeyValueOfGatuAdressSchemaAdressSchema transportItem)
{
return transportItem.lstMessages.Count() > 0;
}
public bool HasMessages(GatuAdressService.TransportMessageOfGatuAdressSchema transportItem)
{
return transportItem.lstMessages.Count() > 0;
}
public bool HasMessages(MailService.TransportMessageOfMailSchema transportItem)
{
return transportItem.lstMessages.Count() > 0;
}
public bool HasMessages(MailService.TransportMessageOfArrayOfMailSchema transportItem)
{
return transportItem.lstMessages.Count() > 0;
}
public bool HasMessages(MailService.TransportMessageOfArrayOfKeyValueOfMailSchemaAdressSchema transportItem)
{
return transportItem.lstMessages.Count() > 0;
}
public bool HasMessages(TelefonService.TransportMessageOfTelefonSchema transportItem)
{
return transportItem.lstMessages.Count() > 0;
}
public bool HasMessages(TelefonService.TransportMessageOfArrayOfTelefonSchema transportItem)
{
return transportItem.lstMessages.Count() > 0;
}
public bool HasMessages(TelefonService.TransportMessageOfArrayOfKeyValueOfTelefonSchemaAdressSchema transportItem)
{
return transportItem.lstMessages.Count() > 0;
}
public List<PersonService.Message> GetMessages(PersonService.TransportMessageOfArrayOfKeyValueOfPersonSchemaAdressSchema transportItem)
{
return transportItem.lstMessages.ToList();
}
public List<PersonService.Message> GetMessages(PersonService.TransportMessageOfArrayOfPersonSchema transportItem)
{
return transportItem.lstMessages.ToList();
}
public List<PersonService.Message> GetMessages(PersonService.TransportMessageOfPersonSchema transportItem)
{
return transportItem.lstMessages.ToList();
}
public List<AdressService.Message> GetMessages(AdressService.TransportMessageOfAdressSchema transportItem)
{
return transportItem.lstMessages.ToList();
}
public List<AdressService.Message> GetMessages(AdressService.TransportMessageOfArrayOfAdressSchema transportItem)
{
return transportItem.lstMessages.ToList();
}
public List<AdressService.Message> GetMessages(AdressService.TransportMessageOfArrayOfKeyValueOfAdressSchemaAdressTypSchema transportItem)
{
return transportItem.lstMessages.ToList();
}
public List<AdressService.Message> GetMessages(AdressService.TransportMessageOfArrayOfKeyValueOfAdressSchemaAdressVariantSchema transportItem)
{
return transportItem.lstMessages.ToList();
}
public List<AdressService.Message> GetMessages(AdressService.TransportMessageOfArrayOfKeyValueOfAdressSchemaGatuAdressSchema transportItem)
{
return transportItem.lstMessages.ToList();
}
public List<AdressService.Message> GetMessages(AdressService.TransportMessageOfArrayOfKeyValueOfAdressSchemaMailSchema transportItem)
{
return transportItem.lstMessages.ToList();
}
public List<AdressService.Message> GetMessages(AdressService.TransportMessageOfArrayOfKeyValueOfAdressSchemaPersonSchema transportItem)
{
return transportItem.lstMessages.ToList();
}
public List<AdressService.Message> GetMessages(AdressService.TransportMessageOfArrayOfKeyValueOfAdressSchemaTelefonSchema transportItem)
{
return transportItem.lstMessages.ToList();
}
public List<AdressVariantService.Message> GetMessages(AdressVariantService.TransportMessageOfAdressVariantSchema transportItem)
{
return transportItem.lstMessages.ToList();
}
public List<AdressVariantService.Message> GetMessages(AdressVariantService.TransportMessageOfArrayOfAdressVariantSchema transportItem)
{
return transportItem.lstMessages.ToList();
}
public List<AdressVariantService.Message> GetMessages(AdressVariantService.TransportMessageOfArrayOfKeyValueOfAdressVariantSchemaAdressSchema transportItem)
{
return transportItem.lstMessages.ToList();
}
public List<AdressVariantService.Message> GetMessages(AdressVariantService.TransportMessageOfArrayOfKeyValueOfAdressVariantSchemaAdressTypSchema transportItem)
{
return transportItem.lstMessages.ToList();
}
public List<GatuAdressService.Message> GetMessages(GatuAdressService.TransportMessageOfArrayOfGatuAdressSchema transportItem)
{
return transportItem.lstMessages.ToList();
}
public List<GatuAdressService.Message> GetMessages(GatuAdressService.TransportMessageOfArrayOfKeyValueOfGatuAdressSchemaAdressSchema transportItem)
{
return transportItem.lstMessages.ToList();
}
public List<GatuAdressService.Message> GetMessages(GatuAdressService.TransportMessageOfGatuAdressSchema transportItem)
{
return transportItem.lstMessages.ToList();
}
public List<MailService.Message> GetMessages(MailService.TransportMessageOfMailSchema transportItem)
{
return transportItem.lstMessages.ToList();
}
public List<MailService.Message> GetMessages(MailService.TransportMessageOfArrayOfMailSchema transportItem)
{
return transportItem.lstMessages.ToList();
}
public List<MailService.Message> GetMessages(MailService.TransportMessageOfArrayOfKeyValueOfMailSchemaAdressSchema transportItem)
{
return transportItem.lstMessages.ToList();
}
public List<TelefonService.Message> GetMessages(TelefonService.TransportMessageOfTelefonSchema transportItem)
{
return transportItem.lstMessages.ToList();
}
public List<TelefonService.Message> GetMessages(TelefonService.TransportMessageOfArrayOfTelefonSchema transportItem)
{
return transportItem.lstMessages.ToList();
}
public List<TelefonService.Message> GetMessages(TelefonService.TransportMessageOfArrayOfKeyValueOfTelefonSchemaAdressSchema transportItem)
{
return transportItem.lstMessages.ToList();
}
public List<PersonService.KeyValueOfPersonSchemaAdressSchema> GetData(PersonService.TransportMessageOfArrayOfKeyValueOfPersonSchemaAdressSchema transportItem)
{
return transportItem.Data.ToList();
}
public List<PersonService.PersonSchema> GetData(PersonService.TransportMessageOfArrayOfPersonSchema transportItem)
{
return transportItem.Data.ToList();
}
public PersonService.PersonSchema GetData(PersonService.TransportMessageOfPersonSchema transportItem)
{
return transportItem.Data;
}
public AdressService.AdressSchema GetData(AdressService.TransportMessageOfAdressSchema transportItem)
{
return transportItem.Data;
}
public List<AdressService.AdressSchema> GetData(AdressService.TransportMessageOfArrayOfAdressSchema transportItem)
{
return transportItem.Data.ToList();
}
public List<AdressService.KeyValueOfAdressSchemaAdressTypSchema> GetData(AdressService.TransportMessageOfArrayOfKeyValueOfAdressSchemaAdressTypSchema transportItem)
{
return transportItem.Data.ToList();
}
public List<AdressService.KeyValueOfAdressSchemaAdressVariantSchema> GetData(AdressService.TransportMessageOfArrayOfKeyValueOfAdressSchemaAdressVariantSchema transportItem)
{
return transportItem.Data.ToList();
}
public List<AdressService.KeyValueOfAdressSchemaGatuAdressSchema> GetData(AdressService.TransportMessageOfArrayOfKeyValueOfAdressSchemaGatuAdressSchema transportItem)
{
return transportItem.Data.ToList();
}
public List<AdressService.KeyValueOfAdressSchemaMailSchema> GetData(AdressService.TransportMessageOfArrayOfKeyValueOfAdressSchemaMailSchema transportItem)
{
return transportItem.Data.ToList();
}
public List<AdressService.KeyValueOfAdressSchemaPersonSchema> GetData(AdressService.TransportMessageOfArrayOfKeyValueOfAdressSchemaPersonSchema transportItem)
{
return transportItem.Data.ToList();
}
public List<AdressService.KeyValueOfAdressSchemaTelefonSchema> GetData(AdressService.TransportMessageOfArrayOfKeyValueOfAdressSchemaTelefonSchema transportItem)
{
return transportItem.Data.ToList();
}
public AdressVariantService.AdressVariantSchema GetData(AdressVariantService.TransportMessageOfAdressVariantSchema transportItem)
{
return transportItem.Data;
}
public List<AdressVariantService.AdressVariantSchema> GetData(AdressVariantService.TransportMessageOfArrayOfAdressVariantSchema transportItem)
{
return transportItem.Data.ToList();
}
public List<AdressVariantService.KeyValueOfAdressVariantSchemaAdressSchema> GetData(AdressVariantService.TransportMessageOfArrayOfKeyValueOfAdressVariantSchemaAdressSchema transportItem)
{
return transportItem.Data.ToList();
}
public List<AdressVariantService.KeyValueOfAdressVariantSchemaAdressTypSchema> GetData(AdressVariantService.TransportMessageOfArrayOfKeyValueOfAdressVariantSchemaAdressTypSchema transportItem)
{
return transportItem.Data.ToList();
}
public List<GatuAdressService.GatuAdressSchema> GetData(GatuAdressService.TransportMessageOfArrayOfGatuAdressSchema transportItem)
{
return transportItem.Data.ToList();
}
public List<GatuAdressService.KeyValueOfGatuAdressSchemaAdressSchema> GetData(GatuAdressService.TransportMessageOfArrayOfKeyValueOfGatuAdressSchemaAdressSchema transportItem)
{
return transportItem.Data.ToList();
}
public GatuAdressService.GatuAdressSchema GetData(GatuAdressService.TransportMessageOfGatuAdressSchema transportItem)
{
return transportItem.Data;
}
public MailService.MailSchema GetData(MailService.TransportMessageOfMailSchema transportItem)
{
return transportItem.Data;
}
public List<MailService.MailSchema> GetData(MailService.TransportMessageOfArrayOfMailSchema transportItem)
{
return transportItem.Data.ToList();
}
public List<MailService.KeyValueOfMailSchemaAdressSchema> GetData(MailService.TransportMessageOfArrayOfKeyValueOfMailSchemaAdressSchema transportItem)
{
return transportItem.Data.ToList();
}
public TelefonService.TelefonSchema GetData(TelefonService.TransportMessageOfTelefonSchema transportItem)
{
return transportItem.Data;
}
public List<TelefonService.TelefonSchema> GetData(TelefonService.TransportMessageOfArrayOfTelefonSchema transportItem)
{
return transportItem.Data.ToList();
}
public List<TelefonService.KeyValueOfTelefonSchemaAdressSchema> GetData(TelefonService.TransportMessageOfArrayOfKeyValueOfTelefonSchemaAdressSchema transportItem)
{
return transportItem.Data.ToList();
}
} |
using System.Text;
using System;
using System.Collections.Generic;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json;
using System.Net.Http;
using System.Drawing;
using System.Collections.ObjectModel;
using System.Xml;
using System.ComponentModel;
using System.Reflection;
namespace LinnworksAPI
{
public class OrderSummary
{
public Guid OrderId;
public Int32 NumOrderId;
public DateTime ReceivedDate;
public DateTime ProcessDate;
public String Source;
public String CustomerName;
public Int32 NumProducts;
public Guid FulfillmentLocationId;
}
} |
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace FindSelf.Application.Queries.Users
{
public interface IUserTranscationQueryService
{
Task<bool> IsExistTranscationAsync(Guid requestId);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RPGGame;
namespace RPGgame
{
class Floor : Tile
{
bool isOccupied;
public Floor(int posX, int posY)
{
this.posX = posX;
this.posY = posY;
path = @"../../Assets/floor.png";
isOccupied = false;
isAvailable = true;
}
}
}
|
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
namespace KataJeuDeLaVie
{
[TestFixture]
public class GrilleTest
{
private Grille _grille;
[SetUp]
public void SetUp()
{
_grille = new Grille();
}
[Test]
public void Une_grille_vide_ne_contient_que_des_cellules_mortes()
{
var suivantes = _grille.Suivantes(new List<Position>());
Assert.That(suivantes, Is.Empty);
}
[Test]
public void Une_grille_peut_rester_en_vie()
{
var cellules = new List<Position>
{
new Position(0, 0),
new Position(0, 1),
new Position(1, 0),
new Position(1, 1)
};
var suivantes = _grille.Suivantes(cellules);
Assert.That(suivantes, Has.Count.EqualTo(4));
Assert.That(suivantes, Has.Member(new Position(0, 0)));
Assert.That(suivantes, Has.Member(new Position(0, 1)));
Assert.That(suivantes, Has.Member(new Position(1, 0)));
Assert.That(suivantes, Has.Member(new Position(1, 1)));
}
[Test]
public void Une_grille_peut_mourir()
{
var cellules = new List<Position> {new Position(0, 0)};
var suivantes = _grille.Suivantes(cellules);
Assert.That(suivantes, Is.Empty);
}
[Test]
public void Une_grille_peut_evoluer()
{
var cellules = new List<Position>
{
new Position(0, 0),
new Position(1, 0),
new Position(2, 0)
};
var suivantes = _grille.Suivantes(cellules);
Assert.That(suivantes, Has.Count.EqualTo(3));
Assert.That(suivantes, Has.Member(new Position(1, 1)));
Assert.That(suivantes, Has.Member(new Position(1, 0)));
Assert.That(suivantes, Has.Member(new Position(1, -1)));
}
}
} |
using System;
using System.Collections.Generic;
using System.Drawing;
using Cloo;
using KelpNet.Common;
using KelpNet.Common.Functions;
using KelpNet.Common.Tools;
namespace KelpNet.Functions.Connections
{
[Serializable]
public class Deconvolution2D : CompressibleFunction
{
const string FUNCTION_NAME = "Deconvolution2D";
private const string PARAM_NAME = "/*ForwardActivate*/";
private const string PARAM_VALUE = "result = ForwardActivate(result);";
public NdArray Weight;
public NdArray Bias;
public readonly bool NoBias;
private readonly int _kWidth;
private readonly int _kHeight;
private readonly int _subSampleX;
private readonly int _subSampleY;
private readonly int _trimX;
private readonly int _trimY;
public readonly int InputCount;
public readonly int OutputCount;
public Deconvolution2D(int inputChannels, int outputChannels, int kSize, int subSample = 1, int trim = 0, bool noBias = false, Array initialW = null, Array initialb = null, CompressibleActivation activation = null, string name = FUNCTION_NAME, string[] inputNames = null, string[] outputNames = null, bool gpuEnable = false) : base(FUNCTION_NAME, activation, new []{new KeyValuePair<string, string>(PARAM_NAME, PARAM_VALUE)}, name, inputNames, outputNames, gpuEnable)
{
this._kWidth = kSize;
this._kHeight = kSize;
this._trimX = trim;
this._trimY = trim;
this._subSampleX = subSample;
this._subSampleY = subSample;
this.NoBias = noBias;
this.Parameters = new NdArray[noBias ? 1 : 2];
this.OutputCount = outputChannels;
this.InputCount = inputChannels;
this.Initialize(initialW, initialb);
}
public Deconvolution2D(int inputChannels, int outputChannels, Size kSize, Size subSample = new Size(), Size trim = new Size(), bool noBias = false, Array initialW = null, Array initialb = null, CompressibleActivation activation = null, string name = FUNCTION_NAME, string[] inputNames = null, string[] outputNames = null, bool gpuEnable = false) : base(FUNCTION_NAME, activation, new []{new KeyValuePair<string, string>(PARAM_NAME, PARAM_VALUE)}, name, inputNames, outputNames, gpuEnable)
{
if (subSample == Size.Empty)
subSample = new Size(1, 1);
if (trim == Size.Empty)
trim = new Size(0, 0);
this._kWidth = kSize.Width;
this._kHeight = kSize.Height;
this._trimX = trim.Width;
this._trimY = trim.Height;
this.NoBias = noBias;
this._subSampleX = subSample.Width;
this._subSampleY = subSample.Height;
this.Parameters = new NdArray[noBias ? 1 : 2];
this.OutputCount = outputChannels;
this.InputCount = inputChannels;
this.Initialize(initialW, initialb);
}
void Initialize(Array initialW = null, Array initialb = null)
{
this.Weight = new NdArray(OutputCount, InputCount, this._kHeight, this._kWidth);
this.Weight.Name = this.Name + " Weight";
if (initialW == null)
{
Initializer.InitWeight(this.Weight);
}
else
{
this.Weight.Data = Real.GetArray(initialW);
}
this.Parameters[0] = this.Weight;
if (!NoBias)
{
this.Bias = new NdArray(OutputCount);
this.Bias.Name = this.Name + " Bias";
if (initialb != null)
{
this.Bias.Data = Real.GetArray(initialb);
}
this.Parameters[1] = this.Bias;
}
}
protected override NdArray NeedPreviousForwardCpu(NdArray input)
{
int outputHeight = (input.Shape[1] - 1) * this._subSampleY + this._kHeight - this._trimY * 2;
int outputWidth = (input.Shape[2] - 1) * this._subSampleX + this._kWidth - this._trimX * 2;
Real[] result = new Real[input.BatchCount * this.OutputCount * outputWidth * outputHeight];
int outSizeOffset = outputWidth * outputHeight;
int inputSizeOffset = input.Shape[1] * input.Shape[2];
int kSizeOffset = this.Weight.Shape[2] * this.Weight.Shape[3];
for (int batchCount = 0; batchCount < input.BatchCount; batchCount++)
{
for (int och = 0; och < this.OutputCount; och++)
{
for (int oy = this._trimY; oy < outputHeight + this._trimY; oy++)
{
int iyLimit = oy / this._subSampleY + 1 < input.Shape[1] ? oy / this._subSampleY + 1 : input.Shape[1];
int iyStart = oy - this.Weight.Shape[2] < 0 ? 0 : (oy - this.Weight.Shape[2]) / this._subSampleY + 1;
for (int ox = this._trimX; ox < outputWidth + this._trimX; ox++)
{
int ixLimit = ox / this._subSampleX + 1 < input.Shape[2] ? ox / this._subSampleX + 1 : input.Shape[2];
int ixStart = ox - this.Weight.Shape[3] < 0 ? 0 : (ox - this.Weight.Shape[3]) / this._subSampleX + 1;
int outputIndex = batchCount * this.OutputCount * outSizeOffset + och * outSizeOffset + (oy - this._trimY) * outputWidth + ox - this._trimX;
for (int ich = 0; ich < input.Shape[0]; ich++)
{
int inputIndexOffset = batchCount * input.Length + ich * inputSizeOffset;
int kernelIndexOffset = och * this.Weight.Shape[1] * kSizeOffset + ich * kSizeOffset;
for (int iy = iyStart; iy < iyLimit; iy++)
{
for (int ix = ixStart; ix < ixLimit; ix++)
{
int inputIndex = inputIndexOffset + iy * input.Shape[2] + ix;
int kernelIndex = kernelIndexOffset + (oy - iy * this._subSampleY) * this.Weight.Shape[3] + (ox - ix * this._subSampleX);
result[outputIndex] += input.Data[inputIndex] * this.Weight.Data[kernelIndex];
}
}
}
}
}
}
}
if (this.Activator != null && !NoBias)
{
for (int batchCount = 0; batchCount < input.BatchCount; batchCount++)
{
for (int och = 0; och < this.OutputCount; och++)
{
for (int oy = this._trimY; oy < outputHeight + this._trimY; oy++)
{
for (int ox = this._trimX; ox < outputWidth + this._trimX; ox++)
{
int outputIndex = batchCount * this.OutputCount * outSizeOffset + och * outSizeOffset + (oy - this._trimY) * outputWidth + ox - this._trimX;
result[outputIndex] += this.Bias.Data[och];
result[outputIndex] = this.Activator.ForwardActivate(result[outputIndex]);
}
}
}
}
}
else if (!NoBias)
{
for (int batchCount = 0; batchCount < input.BatchCount; batchCount++)
{
for (int och = 0; och < this.OutputCount; och++)
{
for (int oy = this._trimY; oy < outputHeight + this._trimY; oy++)
{
for (int ox = this._trimX; ox < outputWidth + this._trimX; ox++)
{
int outputIndex = batchCount * this.OutputCount * outSizeOffset + och * outSizeOffset + (oy - this._trimY) * outputWidth + ox - this._trimX;
result[outputIndex] += this.Bias.Data[och];
}
}
}
}
}
else if (this.Activator != null)
{
for (int batchCount = 0; batchCount < input.BatchCount; batchCount++)
{
for (int och = 0; och < this.OutputCount; och++)
{
for (int oy = this._trimY; oy < outputHeight + this._trimY; oy++)
{
for (int ox = this._trimX; ox < outputWidth + this._trimX; ox++)
{
int outputIndex = batchCount * this.OutputCount * outSizeOffset + och * outSizeOffset + (oy - this._trimY) * outputWidth + ox - this._trimX;
result[outputIndex] = this.Activator.ForwardActivate(result[outputIndex]);
}
}
}
}
}
return NdArray.Convert(result, new[] { this.OutputCount, outputHeight, outputWidth }, input.BatchCount, this);
}
protected override NdArray NeedPreviousForwardGpu(NdArray input)
{
int outputHeight = (input.Shape[1] - 1) * this._subSampleY + this._kHeight - this._trimY * 2;
int outputWidth = (input.Shape[2] - 1) * this._subSampleX + this._kWidth - this._trimX * 2;
Real[] result = new Real[input.BatchCount * this.OutputCount * outputWidth * outputHeight];
using (ComputeBuffer<Real> gpuX = new ComputeBuffer<Real>(Weaver.Context, ComputeMemoryFlags.ReadOnly | ComputeMemoryFlags.CopyHostPointer, input.Data))
using (ComputeBuffer<Real> gpuW = new ComputeBuffer<Real>(Weaver.Context, ComputeMemoryFlags.ReadOnly | ComputeMemoryFlags.CopyHostPointer, this.Weight.Data))
using (ComputeBuffer<Real> gpub = new ComputeBuffer<Real>(Weaver.Context, ComputeMemoryFlags.ReadOnly | ComputeMemoryFlags.CopyHostPointer, this.NoBias ? new Real[OutputCount] : this.Bias.Data))
using (ComputeBuffer<Real> gpuY = new ComputeBuffer<Real>(Weaver.Context, ComputeMemoryFlags.WriteOnly | ComputeMemoryFlags.AllocateHostPointer, result.Length))
{
ForwardKernel.SetMemoryArgument(0, gpuX);
ForwardKernel.SetMemoryArgument(1, gpuW);
ForwardKernel.SetMemoryArgument(2, gpub);
ForwardKernel.SetMemoryArgument(3, gpuY);
ForwardKernel.SetValueArgument(4, input.Shape[1]);
ForwardKernel.SetValueArgument(5, input.Shape[2]);
ForwardKernel.SetValueArgument(6, input.Length);
ForwardKernel.SetValueArgument(7, outputWidth);
ForwardKernel.SetValueArgument(8, outputHeight);
ForwardKernel.SetValueArgument(9, this._subSampleX);
ForwardKernel.SetValueArgument(10, this._subSampleY);
ForwardKernel.SetValueArgument(11, this._trimX);
ForwardKernel.SetValueArgument(12, this._trimY);
ForwardKernel.SetValueArgument(13, this._kHeight);
ForwardKernel.SetValueArgument(14, this._kWidth);
ForwardKernel.SetValueArgument(15, this.OutputCount);
ForwardKernel.SetValueArgument(16, this.InputCount);
Weaver.CommandQueue.Execute
(
ForwardKernel,
null,
new long[] { input.BatchCount * OutputCount, outputHeight, outputWidth },
null,
null
);
Weaver.CommandQueue.Finish();
Weaver.CommandQueue.ReadFromBuffer(gpuY, ref result, true, null);
}
return NdArray.Convert(result, new[] { this.OutputCount, outputHeight, outputWidth }, input.BatchCount, this);
}
Real[] GetActivatedgy(NdArray y)
{
int gyIndex = 0;
Real[] activatedgy = new Real[y.Grad.Length];
for (int batchCounter = 0; batchCounter < y.BatchCount; batchCounter++)
{
for (int och = 0; och < y.Shape[0]; och++)
{
for (int olocation = 0; olocation < y.Shape[1] * y.Shape[2]; olocation++)
{
activatedgy[gyIndex] = this.Activator.BackwardActivate(y.Grad[gyIndex], y.Data[gyIndex]);
gyIndex++;
}
}
}
return activatedgy;
}
void CalcBiasGrad(Real[] gy, int[] gyShape, int batchCount)
{
int gyIndex = 0;
for (int batchCounter = 0; batchCounter < batchCount; batchCounter++)
{
for (int och = 0; och < gyShape[0]; och++)
{
for (int olocation = 0; olocation < gyShape[1] * gyShape[2]; olocation++)
{
this.Bias.Grad[och] += gy[gyIndex];
gyIndex++;
}
}
}
}
protected override void NeedPreviousBackwardCpu(NdArray y, NdArray x)
{
//Real [] gx = new Real [x.Data.Length];
Real[] activatedgy = this.Activator != null ? GetActivatedgy(y) : y.Grad;
if (!NoBias) CalcBiasGrad(activatedgy, y.Shape, y.BatchCount);
//Original logic
for (int batchCount = 0; batchCount < y.BatchCount; batchCount++)
{
for (int och = 0; och < OutputCount; och++)
{
int outChOffset = och * this.Weight.Shape[1] * this.Weight.Shape[2] * this.Weight.Shape[3];
int inputOffset = och * y.Shape[1] * y.Shape[2];
for (int oy = this._trimY; oy < y.Shape[1] + this._trimY; oy++)
{
int iyLimit = oy / this._subSampleY + 1 < x.Shape[1] ? oy / this._subSampleY + 1 : x.Shape[1];
int iyStart = oy - this.Weight.Shape[2] < 0 ? 0 : (oy - this.Weight.Shape[2]) / this._subSampleY + 1;
for (int ox = this._trimX; ox < y.Shape[2] + this._trimX; ox++)
{
int ixLimit = ox / this._subSampleX + 1 < x.Shape[2] ? ox / this._subSampleX + 1 : x.Shape[2];
int ixStart = ox - this.Weight.Shape[3] < 0 ? 0 : (ox - this.Weight.Shape[3]) / this._subSampleX + 1;
int gyIndex = batchCount * y.Length + inputOffset + (oy - this._trimY) * y.Shape[2] + ox - this._trimX;
Real gyData = activatedgy[gyIndex];
for (int ich = 0; ich < InputCount; ich++)
{
int inChOffset = outChOffset + ich * this.Weight.Shape[2] * this.Weight.Shape[3];
int pinputOffset = batchCount * x.Length + ich * x.Shape[1] * x.Shape[2];
for (int iy = iyStart; iy < iyLimit; iy++)
{
for (int ix = ixStart; ix < ixLimit; ix++)
{
int pInIndex = pinputOffset + iy * x.Shape[2] + ix;
int gwIndex = inChOffset + (oy - iy * this._subSampleY) * this.Weight.Shape[3] + (ox - ix * this._subSampleX);
this.Weight.Grad[gwIndex] += x.Data[pInIndex] * gyData;
x.Grad[pInIndex] += this.Weight.Data[gwIndex] * gyData;
}
}
}
}
}
}
}
}
protected override void NeedPreviousBackwardGpu(NdArray y, NdArray x)
{
Real[] gx = new Real[x.Data.Length];
Real[] activatedgy = this.Activator != null ? GetActivatedgy(y) : y.Grad;
if (!NoBias) CalcBiasGrad(activatedgy, y.Shape, y.BatchCount);
//gy is commonly used
using (ComputeBuffer<Real> gpugY = new ComputeBuffer<Real>(Weaver.Context, ComputeMemoryFlags.ReadOnly | ComputeMemoryFlags.CopyHostPointer, activatedgy))
{
using (ComputeBuffer<Real> gpugW = new ComputeBuffer<Real>(Weaver.Context, ComputeMemoryFlags.ReadWrite | ComputeMemoryFlags.CopyHostPointer, this.Weight.Grad))
using (ComputeBuffer<Real> gpuX = new ComputeBuffer<Real>(Weaver.Context, ComputeMemoryFlags.ReadOnly | ComputeMemoryFlags.CopyHostPointer, x.Data))
{
this.BackwardgWKernel.SetMemoryArgument(0, gpugY);
this.BackwardgWKernel.SetMemoryArgument(1, gpuX);
this.BackwardgWKernel.SetMemoryArgument(2, gpugW);
this.BackwardgWKernel.SetValueArgument(3, y.BatchCount);
this.BackwardgWKernel.SetValueArgument(4, this.InputCount);
this.BackwardgWKernel.SetValueArgument(5, y.Length);
this.BackwardgWKernel.SetValueArgument(6, y.Shape[1]);
this.BackwardgWKernel.SetValueArgument(7, y.Shape[2]);
this.BackwardgWKernel.SetValueArgument(8, x.Shape[1]);
this.BackwardgWKernel.SetValueArgument(9, x.Shape[2]);
this.BackwardgWKernel.SetValueArgument(10, x.Length);
this.BackwardgWKernel.SetValueArgument(11, this._subSampleX);
this.BackwardgWKernel.SetValueArgument(12, this._subSampleY);
this.BackwardgWKernel.SetValueArgument(13, this._trimX);
this.BackwardgWKernel.SetValueArgument(14, this._trimY);
this.BackwardgWKernel.SetValueArgument(15, this._kHeight);
this.BackwardgWKernel.SetValueArgument(16, this._kWidth);
Weaver.CommandQueue.Execute
(
this.BackwardgWKernel,
null,
new long[] { OutputCount * InputCount, this._kHeight, this._kWidth },
null,
null
);
Weaver.CommandQueue.Finish();
Weaver.CommandQueue.ReadFromBuffer(gpugW, ref this.Weight.Grad, true, null);
}
using (ComputeBuffer<Real> gpugX = new ComputeBuffer<Real>(Weaver.Context, ComputeMemoryFlags.WriteOnly | ComputeMemoryFlags.AllocateHostPointer, gx.Length))
using (ComputeBuffer<Real> gpuW = new ComputeBuffer<Real>(Weaver.Context, ComputeMemoryFlags.ReadOnly | ComputeMemoryFlags.CopyHostPointer, this.Weight.Data))
{
this.BackwardgXKernel.SetMemoryArgument(0, gpugY);
this.BackwardgXKernel.SetMemoryArgument(1, gpuW);
this.BackwardgXKernel.SetMemoryArgument(2, gpugX);
this.BackwardgXKernel.SetValueArgument(3, this.OutputCount);
this.BackwardgXKernel.SetValueArgument(4, this.InputCount);
this.BackwardgXKernel.SetValueArgument(5, y.Length);
this.BackwardgXKernel.SetValueArgument(6, y.Shape[1]);
this.BackwardgXKernel.SetValueArgument(7, y.Shape[2]);
this.BackwardgXKernel.SetValueArgument(8, x.Shape[1]);
this.BackwardgXKernel.SetValueArgument(9, x.Shape[2]);
this.BackwardgXKernel.SetValueArgument(10, x.Length);
this.BackwardgXKernel.SetValueArgument(11, this._subSampleX);
this.BackwardgXKernel.SetValueArgument(12, this._subSampleY);
this.BackwardgXKernel.SetValueArgument(13, this._trimX);
this.BackwardgXKernel.SetValueArgument(14, this._trimY);
this.BackwardgXKernel.SetValueArgument(15, this._kHeight);
this.BackwardgXKernel.SetValueArgument(16, this._kWidth);
Weaver.CommandQueue.Execute
(
this.BackwardgXKernel,
null,
new long[] { y.BatchCount * x.Shape[0], x.Shape[1], x.Shape[2] },
null,
null
);
Weaver.CommandQueue.Finish();
Weaver.CommandQueue.ReadFromBuffer(gpugX, ref gx, true, null);
}
}
for (int i = 0; i < x.Grad.Length; i++)
{
x.Grad[i] += gx[i];
}
}
}
}
|
using System;
namespace ImmedisHCM.Services.Models.Core
{
public class SalaryServiceModel
{
public Guid Id { get; set; }
public decimal Amount { get; set; }
public EmployeeServiceModel Employee { get; set; }
public SalaryTypeServiceModel SalaryType { get; set; }
public CurrencyServiceModel Currency { get; set; }
}
} |
using System;
using Micro.Net.Abstractions;
namespace Micro.Net.Receive
{
public interface IReceiveContext<TRequest, TResponse> : IContextBase
{
Uri Source { get; set; }
Uri Destination { get; set; }
IRequestContext<TRequest> Request { get; set; }
IResponseContext<TResponse> Response { get; set; }
}
} |
using System;
using Xunit;
namespace NMoSql.Test
{
public class JoinsTests
{
IQueryBuilder builder;
public JoinsTests()
{
builder = TestNMoSqlFactory.CreateQueryBuilder();
}
[Fact(DisplayName = "Joins should build joins from single joins query helper")]
public void JoinsShouldBuildJoinsFromSingleJoinsQueryHelper()
{
var query = @"{
type: 'select',
table: 'users',
joins: {
books: {
type: 'left',
on: {
userId: '$users.id$'
}
}
}
}";
var result = builder.Build(query);
Assert.Equal("select \"users\".* from \"users\" left join \"books\" \"books\" on \"books\".\"userId\" = \"users\".\"id\"", result.ToString());
}
[Fact(DisplayName = "Joins should allow object syntax to override alias and provide a target")]
public void JoinsShouldAllowObjectSyntaxToOverrideAliasAndProvideTarget()
{
var query = @"{
type: 'select',
table: 'users',
joins: {
booksJoin: {
type: 'left',
alias: 'b',
target: 'books',
on: {
userId: '$users.id$'
}
}
}
}";
var result = builder.Build(query);
Assert.Equal("select \"users\".* from \"users\" " +
"left join \"books\" \"b\" on \"b\".\"userId\" = \"users\".\"id\"",
result.ToString());
}
[Fact(DisplayName = "Joins should allow sub-queries on targets")]
public void JoinsShouldAllowSubQueriesOnTargets()
{
var query = @"{
type: 'select',
table: 'users',
joins: {
books: {
type: 'left',
target: {
type: 'select',
table: 'books'
},
on: {
userId: '$users.id$'
}
}
}
}";
var result = builder.Build(query);
Assert.Equal("select \"users\".* from \"users\" " +
"left join (select \"books\".* from \"books\") \"books\" on \"books\".\"userId\" = \"users\".\"id\"",
result.ToString());
}
[Fact(DisplayName = "Joins should build joins using array syntax")]
public void JoinsShouldBuildJoinsUsingArraySyntax()
{
var query = @"{
type: 'select',
table: 'users',
joins: [
{
type: 'left',
target: ""books"",
on: {
userId: '$users.id$'
}
}
]
}";
var result = builder.Build(query);
Assert.Equal("select \"users\".* from \"users\" " +
"left join \"books\" on \"books\".\"userId\" = \"users\".\"id\"",
result.ToString());
}
[Fact(DisplayName = "Joins should build joins using array syntax with conditionals in a sub-select")]
public void JoinsShouldBuildJoinsUsingArraySyntaxWithConditionalsInSubSelect()
{
var query = @"{
type: 'select',
table: 'users',
joins: [
{
type: 'left',
target: ""books"",
on: {
userId: '$users.id$'
}
},
{
type: 'left',
alias: 'addresses',
on: {
'userId': '$users.id$'
},
target: {
type: 'select',
table: 'addresses',
columns: ['userId'],
where: {
id: {
$gt: 7
}
}
}
}
]
}";
var result = builder.Build(query);
Assert.Equal("select \"users\".* from \"users\" " +
"left join \"books\" on \"books\".\"userId\" = \"users\".\"id\" " +
"left join (select \"addresses\".\"userId\" from \"addresses\" where \"addresses\".\"id\" > @0) \"addresses\" on \"addresses\".\"userId\" = \"users\".\"id\"",
result.ToString());
Assert.True(result.Values.Count == 1 && (int)result.Values[0] == 7);
}
[Fact(DisplayName = "Joins should build multiple joins from single joins query helper")]
public void JoinsShouldBuildMultipleJoinsFromSingleJoinsQueryHelper()
{
var query = @"{
type: 'select',
table: 'users',
joins: {
books: {
type: 'left',
on: {
userId: '$users.id$'
}
},
things: {
type: 'left',
on: {
userId: '$users.id$'
}
}
}
}";
var result = builder.Build(query);
Assert.Equal("select \"users\".* from \"users\" " +
"left join \"books\" \"books\" on \"books\".\"userId\" = \"users\".\"id\" " +
"left join \"things\" \"things\" on \"things\".\"userId\" = \"users\".\"id\"",
result.ToString());
}
[Fact(DisplayName = "Joins should build multiple joins using array syntax")]
public void JoinsShouldBuildMultipleJoinsUsingArraySyntax()
{
var query = @"{
type: 'select',
table: 'users',
joins: [
{
type: 'left',
target: ""books"",
on: {
userId: '$users.id$'
}
},
{
type: 'left',
target: ""things"",
on: {
userId: '$users.id$'
}
}
]
}";
var result = builder.Build(query);
Assert.Equal("select \"users\".* from \"users\" " +
"left join \"books\" on \"books\".\"userId\" = \"users\".\"id\" " +
"left join \"things\" on \"things\".\"userId\" = \"users\".\"id\"",
result.ToString());
}
[Fact(DisplayName = "Joins invalid join throws exception")]
public void JoinsInvalidJoinThrowsException()
{
var query = @"{
type: 'select',
table: 'users',
joins: 1
}";
Assert.Throws<InvalidOperationException>(() => builder.Build(query));
}
[Fact(DisplayName = "Joins missing target throws exception")]
public void JoinsMissingTargetThrowsException()
{
var query = @"{
type: 'select',
table: 'users',
joins: [
{
alias: 'c',
on: {
id: '$users.id$'
}
}
]
}";
Assert.Throws<InvalidOperationException>(() => builder.Build(query));
}
[Fact(DisplayName = "Joins should join with array syntax")]
public void JoinsShouldJoinWithArraySyntax()
{
var query = @"{
type: 'select',
table: 'users',
joins: [
{
type: 'left',
target: 'books',
alias: 'books',
on: {
userId: '$users.id$'
}
},
{
type: 'left',
target: 'things',
on: {
userId: '$users.id$'
}
}
]
}";
var result = builder.Build(query);
Assert.Equal("select \"users\".* from \"users\" " +
"left join \"books\" \"books\" on \"books\".\"userId\" = \"users\".\"id\" " +
"left join \"things\" on \"things\".\"userId\" = \"users\".\"id\"",
result.ToString());
}
[Fact(DisplayName = "Joins should join with schema specified in target")]
public void JoinsShouldJoinWithSchemaSpecifiedInTarget()
{
var query = @"{
type: 'select',
table: 'users',
joins: [
{
type: 'left',
target: 'my_schema.books',
alias: 'books',
on: {
userId: '$users.id$'
}
}
]
}";
var result = builder.Build(query);
Assert.Equal("select \"users\".* from \"users\" " +
"left join \"my_schema\".\"books\" \"books\" on \"books\".\"userId\" = \"users\".\"id\"",
result.ToString());
}
[Fact(DisplayName = "Joins should join with schema specified as a separate field")]
public void JoinsShouldJoinWithSchemaSpecifiedAsSeparateField()
{
var query = @"{
type: 'select',
table: 'users',
joins: [
{
type: 'left',
target: 'books',
schema: 'my_schema',
alias: 'books',
on: {
userId: '$users.id$'
}
}
]
}";
var result = builder.Build(query);
Assert.Equal("select \"users\".* from \"users\" " +
"left join \"my_schema\".\"books\" \"books\" on \"books\".\"userId\" = \"users\".\"id\"",
result.ToString());
}
[Fact(DisplayName = "Joins should join with schema and database specified in target")]
public void JoinsShouldJoinWithSchemaAndDatabaseSpecifiedInTarget()
{
var query = @"{
type: 'select',
table: 'users',
joins: [
{
type: 'left',
target: 'my_database.my_schema.books',
alias: 'books',
on: {
userId: '$users.id$'
}
}
]
}";
var result = builder.Build(query);
Assert.Equal("select \"users\".* from \"users\" " +
"left join \"my_database\".\"my_schema\".\"books\" \"books\" on \"books\".\"userId\" = \"users\".\"id\"",
result.ToString());
}
[Fact(DisplayName = "Joins should join with schema and database specified in separate fields")]
public void JoinsShouldJoinWithSchemaAndDatabaseSpecifiedInSeparateFields()
{
var query = @"{
type: 'select',
table: 'users',
joins: [
{
type: 'left',
target: 'books',
schema: 'my_schema',
database: 'my_database',
alias: 'books',
on: {
userId: '$users.id$'
}
}
]
}";
var result = builder.Build(query);
Assert.Equal("select \"users\".* from \"users\" " +
"left join \"my_database\".\"my_schema\".\"books\" \"books\" on \"books\".\"userId\" = \"users\".\"id\"",
result.ToString());
}
[Theory(DisplayName = "Joins should join on boolean")]
[InlineData(true)]
[InlineData(false)]
public void JoinsShouldJoinOnBoolean(bool value)
{
var query = @"{
type: 'select',
table: 'users',
joins: [
{
type: 'lateral',
target: {
type: 'select',
table: 'books'
},
on: " + value.ToString().ToLower() + @"
}
]
}";
var result = builder.Build(query);
Assert.Equal("select \"users\".* from \"users\" " +
"join lateral (select \"books\".* from \"books\") on " + value.ToString().ToLower(),
result.ToString());
}
[Theory(DisplayName = "Joins should build lateral joins")]
[InlineData("lateral", "join lateral")]
[InlineData("cross lateral", "cross join lateral")]
[InlineData("left lateral", "left join lateral")]
public void JoinsShouldBuildLateralJoin(string type, string expected)
{
var query = @"{
type: 'select',
table: 'users',
joins: [
{
type: '" + type + @"',
target: {
type: 'select',
table: 'books',
where: {
userId: {
$equalsEx: {
table: 'users',
name: 'id'
}
}
}
},
on: true
}
]
}";
var result = builder.Build(query);
Assert.Equal("select \"users\".* from \"users\" " +
expected + " (select \"books\".* from \"books\" where \"books\".\"userId\" = \"users\".\"id\") on true",
result.ToString());
}
}
}
|
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using SprintFour.Utilities;
namespace SprintFour.HUD
{
/// <summary>
/// Handles the overlay drawn over the gameplay as well as elements concerning time
/// </summary>
public class Overlay : DrawableGameComponent
{
public static SpriteFont Font { get; set; }
private static Vector2 TextHeight { get { return Font.LineSpacing*Vector2.UnitY; } }
public static int Score { get; set; }
public static int CoinCount { get; set; }
public static TimeSpan Time { get; private set; }
public static int Lives = Utility.INITIAL_LIVES;
private SpriteBatch SpriteBatch { get { return ((SprintFourGame)Game).SpriteBatch; } }
private static Texture2D coinTexture;
private static Rectangle coinSrc;
private static Texture2D marioTexture;
private static Texture2D bulletTex;
private static int ammo;
public Overlay(): base(SprintFourGame.GetInstance()) { }
public override void Initialize()
{
if (SprintFourGame.GetInstance().LevelIsInfinite) Time = Utility.LargeGameTimeSpan;
else Time = Utility.GameTimeSpan;
coinSrc = Utility.CoinSourceRectangle;
DrawOrder = Utility.OVERLAY_DRAW_ORDER;
ammo = Utility.ZERO;
base.Initialize();
}
protected override void LoadContent()
{
bulletTex = Game.Content.Load<Texture2D>(Utility.BULLET);
coinTexture = Game.Content.Load<Texture2D>(Utility.ITEMS);
marioTexture = Game.Content.Load<Texture2D>(Utility.MARIO);
base.LoadContent();
}
public override void Draw(GameTime gameTime)
{
//Game over
if (SprintFourGame.GetInstance().CurrentGameState == SprintFourGame.GameState.Lost) {
SpriteBatch.DrawString(Font, "Game Over", Utility.GameOverPosition, Color.White);
return;
}
Vector2 offset = Background.Camera.Position/Utility.CAMERA_SCALE;
if (SprintFourGame.GetInstance().CurrentGameState == SprintFourGame.GameState.LevelSelect)
{
DrawLevelSelectOverlay(gameTime, offset);
return;
}
if (!SprintFourGame.GetInstance().Paused) {
Time -= TimeSpan.FromTicks(gameTime.ElapsedGameTime.Ticks * Utility.TICK_RATE);
}
//time logic
if (!SoundManager.Hurried && Time.TotalSeconds < Utility.HURRIED_TIME_LIMIT)
{
SoundManager.Hurried = true;
SoundManager.State = BGMusicState.Transition;
}
if (Time.TotalSeconds <= Utility.ZERO)
{
SprintFourGame.GetInstance().Mario.Kill();
}
DrawHeaders(offset);
if (ammo > Utility.ZERO)
{
DrawClipStatus(offset);
}
if (SprintFourGame.GetInstance().CurrentGameState == SprintFourGame.GameState.Loading)
{
DrawLoadingOverlay();
}
else if (SprintFourGame.GetInstance().CurrentGameState == SprintFourGame.GameState.HighScore)
{
DrawHighScoreOverlay(gameTime, offset);
}
else if (SprintFourGame.GetInstance().CurrentGameState == SprintFourGame.GameState.LevelSelect)
{
DrawLevelSelectOverlay(gameTime, offset);
}
}
private void DrawLoadingOverlay()
{
SpriteBatch.Draw(marioTexture, Utility.LoadingPosition, Utility.MarioSourceRectangle, Color.White);
SpriteBatch.DrawString(Font, "x " + Lives, Utility.Loading2Position, Color.White);
}
private void DrawHighScoreOverlay(GameTime gameTime,Vector2 offset)
{
Time += TimeSpan.FromTicks(gameTime.ElapsedGameTime.Ticks * Utility.TICK_RATE);
SpriteBatch.DrawString(Font, "Name", new Vector2(100, 100) + offset, Color.White);
SpriteBatch.DrawString(Font, "Score", new Vector2(200, 100) + offset, Color.White);
for (int i = Utility.ZERO; i < Utility.THREE; ++i)
{
if (i == HighScore.NewScoreIndex)
{
SpriteBatch.DrawString(Font, HighScore.GetNewName(),
new Vector2(100, 100) + offset + Vector2.UnitY * 30 * (i + 1), Color.LightYellow);
SpriteBatch.DrawString(Font, String.Format("{0:00000}", Score),
new Vector2(200, 100) + offset + Vector2.UnitY * 30 * (i + 1), Color.LightYellow);
}
else
{
SpriteBatch.DrawString(Font, HighScore.TopScores[i].Name,
new Vector2(100, 100) + offset + Vector2.UnitY * 30 * (i + 1), Color.White);
SpriteBatch.DrawString(Font, String.Format("{0:00000}", HighScore.TopScores[i].Score),
new Vector2(200, 100) + offset + Vector2.UnitY * 30 * (i + 1), Color.White);
}
}
}
/// <summary>
/// Formats a number string to be a certain number of digits
/// </summary>
/// <param name="value">Value to be formatted</param>
/// <param name="digits">Desired length of the string</param>
/// <returns></returns>
private static string AddZeroes(int value, int digits)
{
int len = value == Utility.ZERO ? Utility.ONE : (int) Math.Log10(value);
String result = string.Empty;
for (int i = len; i < digits; ++i)
{
result += Utility.ZERO.ToString();
}
return result + value;
}
private void DrawClipStatus(Vector2 offset)
{
offset += Utility.ClipLeftPosition;
SpriteBatch.DrawString(Font, ammo.ToString(), offset, Color.Black);
offset += Vector2.UnitY * Font.MeasureString(ammo.ToString());
offset += Vector2.UnitY * bulletTex.Width;
for (int i = Utility.ZERO; i < ammo; i++)
{
SpriteBatch.Draw(
bulletTex,
offset,
null,
Color.White,
-MathHelper.PiOver2,
Vector2.Zero,
Utility.ONE,
SpriteEffects.None,
Utility.ZERO
);
offset += Vector2.UnitX * bulletTex.Height;
}
}
private void DrawHeaders(Vector2 offset)
{
SpriteBatch.DrawString(Font, Utility.NAME.ToUpper(), offset + Utility.MarioPosition, Color.White);
SpriteBatch.DrawString(Font, AddZeroes(Score, Utility.NUM_ZEROS), offset + Utility.MarioPosition + TextHeight, Color.White);
SpriteBatch.Draw(coinTexture, offset + Utility.CoinPosition + TextHeight, coinSrc, Color.White, Utility.ZERO, Vector2.Zero, Utility.DRAW_SCALE, SpriteEffects.None, Utility.ZERO);
SpriteBatch.DrawString(Font, Utility.COIN_COUNT + CoinCount, offset + Utility.CoinPosition + TextHeight, Color.White);
SpriteBatch.DrawString(Font, Utility.WORLD, offset + Utility.WorldPosition, Color.White);
SpriteBatch.DrawString(Font, Utility.TIME + (Time.Ticks / Utility.TIME_DENOMINATOR), offset + Utility.TimePosition, Color.White);
SpriteBatch.DrawString(Font, Utility.LIVES + Lives, offset + Utility.LifePosition, Color.White);
}
public static void SetAmmo(int clip)
{
ammo = clip;
}
private void DrawLevelSelectOverlay(GameTime gameTime, Vector2 offset)
{
Time += TimeSpan.FromTicks(gameTime.ElapsedGameTime.Ticks * Utility.TICK_RATE);
SpriteBatch.DrawString(Font, "Level 1-1", new Vector2(Utility.LEVEL_SELECT_CHOICES_X_VALUE, Utility.ORIGINAL_CHOICE_Y_VALUE) + offset, Color.White);
SpriteBatch.DrawString(Font, "Infinite Level", new Vector2(Utility.LEVEL_SELECT_CHOICES_X_VALUE, Utility.INFINITE_CHOICE_Y_VALUE) + offset, Color.White);
}
public void Reset()
{
Score = Utility.ZERO;
CoinCount = Utility.ZERO;
Lives = Utility.INITIAL_LIVES;
}
}
}
|
/*
AGE
Copyright (C) 2019 Cups
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
using AGE.GPU;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Security;
using System.Text;
using System.Windows.Forms;
using static AGE.UTILS.Utils;
using static AGE.Shared;
using AGERunner;
namespace AGE
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
private void loadCartridgeToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFileDialog OpenCartridgeFileDialog = new OpenFileDialog()
{
FileName = "",
Filter = "Gameboy ROM File|*.gb",
Title = "AGE - Load ROM File",
Multiselect = false,
CheckFileExists = true
};
if (OpenCartridgeFileDialog.ShowDialog() == DialogResult.OK)
{
Gameboy.InsertCartridge(OpenCartridgeFileDialog.FileName);
}
}
private void togglePowerToolStripMenuItem_Click(object sender, EventArgs e)
{
Gameboy.TurnGameBoyOn();
Shared.Gamerunner.Run(Microsoft.Xna.Framework.GameRunBehavior.Synchronous);
this.Text = "AGE - " + Gameboy.Cartridge.Title + "(Running)";
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if(!object.Equals(Gameboy.Cpu, null) || !object.Equals(Gameboy.Cpu.CpuThread, null))
Gameboy.Cpu.CpuThread.Abort();
// We wait until the CPU thread is done
while (Gameboy.Cpu.CpuThread.IsAlive)
{
// This is to prevent CPU intensive usage.
System.Threading.Thread.Sleep(10);
}
}
private void debugButtonToolStripMenuItem_Click(object sender, EventArgs e)
{
LcdController lcdController = new LcdController(ScreenPanel);
}
}
}
|
using UnityEngine;
namespace VavilichevGD.GameServices.Purchasing.Example {
[CreateAssetMenu(fileName = "ProductInfoExample", menuName = "Monetization/Products/New ProductInfoExample")]
public class ProductInfoExample : ProductInfo {
[SerializeField] private int price;
public override object GetPrice() {
return this.price;
}
public override string GetPriceString() {
return this.price.ToString();
}
}
} |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using MediatR;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json.Linq;
using OmniSharp.Extensions.LanguageServer.Client.Configuration;
using OmniSharp.Extensions.LanguageServer.Protocol;
using OmniSharp.Extensions.LanguageServer.Protocol.Client;
using OmniSharp.Extensions.LanguageServer.Protocol.Models;
using OmniSharp.Extensions.LanguageServer.Protocol.Workspace;
namespace OmniSharp.Extensions.LanguageProtocol.Testing
{
public class TestConfigurationProvider : IConfigurationHandler
{
private readonly IWorkspaceLanguageClient _workspaceLanguageClient;
private readonly ConcurrentDictionary<(string section, DocumentUri? scope), IConfiguration> _scopedConfigurations =
new ConcurrentDictionary<(string section, DocumentUri? scope), IConfiguration>();
public TestConfigurationProvider(IWorkspaceLanguageClient workspaceLanguageClient) => _workspaceLanguageClient = workspaceLanguageClient;
public void Update(string section, IDictionary<string, string>? configuration)
{
if (configuration == null) return;
Update(section, new ConfigurationBuilder().AddInMemoryCollection(configuration).Build());
}
public void Update(string section, IConfiguration? configuration)
{
if (configuration == null) return;
Update(section, null, configuration);
}
public void Update(string section, DocumentUri documentUri, IDictionary<string, string>? configuration)
{
if (configuration == null) return;
Update(section, documentUri, new ConfigurationBuilder().AddInMemoryCollection(configuration).Build());
}
public void Update(string section, DocumentUri? documentUri, IConfiguration? configuration)
{
if (configuration == null) return;
_scopedConfigurations.AddOrUpdate(( section, documentUri ), configuration, (_, _) => configuration);
TriggerChange();
}
public void Reset(string section) => Reset(section, null);
public void Reset(string section, DocumentUri? documentUri)
{
_scopedConfigurations.TryRemove(( section, documentUri ), out _);
_workspaceLanguageClient.DidChangeConfiguration(new DidChangeConfigurationParams());
TriggerChange();
}
private IConfiguration Get(ConfigurationItem configurationItem)
{
if (_scopedConfigurations.TryGetValue(
( configurationItem.Section!, configurationItem.ScopeUri ),
out var configuration
)
)
{
return new ConfigurationBuilder()
.CustomAddConfiguration(configuration, false)
.Build();
}
return new ConfigurationBuilder().Build();
}
private void TriggerChange() => _workspaceLanguageClient.DidChangeConfiguration(new DidChangeConfigurationParams());
Task<Container<JToken>> IRequestHandler<ConfigurationParams, Container<JToken>>.Handle(ConfigurationParams request, CancellationToken cancellationToken)
{
var results = new List<JToken>();
foreach (var item in request.Items)
{
var config = Get(item);
results.Add(Parse(config.AsEnumerable(true).Where(x => x.Value != null)));
}
return Task.FromResult<Container<JToken>>(results);
}
private JObject Parse(IEnumerable<KeyValuePair<string, string>> values)
{
if (values == null)
{
throw new ArgumentNullException(nameof(values));
}
var result = new JObject();
foreach (var item in values)
{
var keys = item.Key.Split(new[] { ":" }, StringSplitOptions.RemoveEmptyEntries);
var prop = keys.Last();
JToken root = result;
// This produces a simple look ahead
var zippedKeys = keys
.Zip(keys.Skip(1), (prev, current) => ( prev, current ));
foreach (var (key, next) in zippedKeys)
{
if (int.TryParse(next, out _))
{
root = SetValueToToken(root, key, new JArray());
}
else
{
root = SetValueToToken(root, key, new JObject());
}
}
SetValueToToken(root, prop, new JValue(item.Value));
}
return result;
}
private T SetValueToToken<T>(JToken root, string key, T value)
where T : JToken
{
var currentValue = GetValueFromToken(root, key);
if (currentValue == null || currentValue.Type == JTokenType.Null)
{
if (root is JArray arr)
{
if (int.TryParse(key, out var index))
{
if (arr.Count <= index)
{
while (arr.Count < index)
arr.Add(null!);
arr.Add(value);
}
else
{
arr[index] = value;
}
return value;
}
}
else
{
root[key] = value;
return value;
}
}
if (root is JArray arr2 && int.TryParse(key, out var i))
{
return (T) arr2[i];
}
return ( root[key] as T )!;
}
private static JToken? GetValueFromToken(JToken root, string key)
{
if (root is JArray arr)
{
if (int.TryParse(key, out var index))
{
if (arr.Count <= index) return null;
return arr[index];
}
throw new IndexOutOfRangeException(key);
}
return root[key];
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Roger
{
public partial class DeviceListBox : UserControl
{
private List<DeviceListItem> existingDeviceListItems = new List<DeviceListItem>();
public DeviceListBox()
{
InitializeComponent();
}
private void deviceBox_MouseClick(object sender, MouseEventArgs e)
{
removeHighlighting();
}
private void removeHighlighting()
{
foreach (var i in existingDeviceListItems)
{
i.BackColor = Color.FromArgb(255, 111, 94, 201);
}
}
private void deviceBox_SizeChanged(object sender, EventArgs e)
{
adjustListItems();
}
private void adjustListItems()
{
var offset = needScrollBarOffset() ? SystemInformation.VerticalScrollBarWidth : 0;
foreach (var item in existingDeviceListItems)
{
// modify width of list items to account for scrollbar
item.Width = this.Width - calculateScrollBarOffset(offset, item);
}
}
private bool needScrollBarOffset()
{
if (existingDeviceListItems.Count() > 0)
{
var controlHeights = (from item in existingDeviceListItems
select (item.Margin.Top + item.Margin.Bottom + item.Height));
if (controlHeights.Sum() > this.Height)
{
return true;
}
return false;
}
return false;
}
private int calculateScrollBarOffset(int offset, Control control)
{
const int BORDER_THICKNESS = 1;
return offset + control.Margin.Left + control.Margin.Right + (BORDER_THICKNESS * 2);
}
public void clearListItems()
{
existingDeviceListItems.Clear();
this.deviceBox.Controls.Clear();
}
public void Add(Device device)
{
DeviceListItem item = new DeviceListItem(device);
if (existingDeviceListItems.Contains(item))
{
return;
}
// keep space between DeviceListItems constant
correctListItemMargins(item);
deviceBox.Controls.Add(item);
existingDeviceListItems.Add(item);
adjustListItems();
}
private void correctListItemMargins(DeviceListItem item)
{
if (existingDeviceListItems.Count() == 0)
{
item.Margin += new Padding(0, 5, 0, 0);
}
else
{
DeviceListItem previousItem = existingDeviceListItems.Last();
previousItem.Margin -= new Padding(0, 0, 0, 5);
}
item.Margin += new Padding(0, 0, 0, 5);
}
}
}
|
using LuaInterface;
using RO;
using SLua;
using System;
public class Lua_RO_CustomTouchUpCall : LuaObject
{
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int constructor(IntPtr l)
{
int result;
try
{
CustomTouchUpCall o = new CustomTouchUpCall();
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, o);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_call(IntPtr l)
{
int result;
try
{
CustomTouchUpCall customTouchUpCall = (CustomTouchUpCall)LuaObject.checkSelf(l);
Action action;
int num = LuaDelegation.checkDelegate(l, 2, out action);
if (num == 0)
{
customTouchUpCall.call = action;
}
else if (num == 1)
{
CustomTouchUpCall expr_30 = customTouchUpCall;
expr_30.call = (Action)Delegate.Combine(expr_30.call, action);
}
else if (num == 2)
{
CustomTouchUpCall expr_53 = customTouchUpCall;
expr_53.call = (Action)Delegate.Remove(expr_53.call, action);
}
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_check(IntPtr l)
{
int result;
try
{
CustomTouchUpCall customTouchUpCall = (CustomTouchUpCall)LuaObject.checkSelf(l);
Func<bool> func;
int num = LuaDelegation.checkDelegate(l, 2, out func);
if (num == 0)
{
customTouchUpCall.check = func;
}
else if (num == 1)
{
CustomTouchUpCall expr_30 = customTouchUpCall;
expr_30.check = (Func<bool>)Delegate.Combine(expr_30.check, func);
}
else if (num == 2)
{
CustomTouchUpCall expr_53 = customTouchUpCall;
expr_53.check = (Func<bool>)Delegate.Remove(expr_53.check, func);
}
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
public static void reg(IntPtr l)
{
LuaObject.getTypeTable(l, "RO.CustomTouchUpCall");
LuaObject.addMember(l, "call", null, new LuaCSFunction(Lua_RO_CustomTouchUpCall.set_call), true);
LuaObject.addMember(l, "check", null, new LuaCSFunction(Lua_RO_CustomTouchUpCall.set_check), true);
LuaObject.createTypeMetatable(l, new LuaCSFunction(Lua_RO_CustomTouchUpCall.constructor), typeof(CustomTouchUpCall), typeof(CallBackWhenClickOtherPlace));
}
}
|
using Moq;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Text;
namespace NunitMoq.UnitTest
{
[TestFixture]
public class MockingMethodsExceptionsAndReturnValues
{
[Test]
public void MockingMethodsExceptionsAndReturnValues1()
{
var mock = new Mock<IFoo>();
mock.Setup(foo => foo.ProcessString(It.IsAny<string>()))
.Returns((string s) => s.ToLower());
Assert.Multiple(() =>
{
Assert.That(mock.Object.ProcessString("ABC"), Is.EqualTo("abc"));
});
}
[Test]
public void MockingMethodsExceptionsAndReturnValues2()
{
var mock = new Mock<IFoo>();
var calls = 0;
mock.Setup(foo => foo.GetCount())
.Returns(() => calls)
.Callback(() => ++calls);
mock.Object.GetCount();
mock.Object.GetCount();
Assert.Multiple(() =>
{
Assert.That(mock.Object.GetCount(), Is.EqualTo(2));
});
}
[Test]
public void MockingMethodsExceptionsAndReturnValues3()
{
var mock = new Mock<IFoo>();
mock.Setup(foo => foo.DoSomething("Kill"))
.Throws<InvalidOperationException>();
Assert.Throws<InvalidOperationException>(()=> mock.Object.DoSomething("Kill"));
}
[Test]
public void MockingMethodsExceptionsAndReturnValues4()
{
var mock = new Mock<IFoo>();
mock.Setup(foo => foo.DoSomething(null))
.Throws(new ArgumentException("cmd"));
Assert.Throws<ArgumentException>(() => { mock.Object.DoSomething(null); },"cmd");
}
}
}
|
using FastSQL.App.Interfaces;
using FastSQL.Core.Events;
using Prism.Events;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace FastSQL.App.UserControls.OutputView
{
public class UCOutputViewViewModel: BaseViewModel
{
private bool _hasChannels;
private string _selectedChannel;
private ObservableCollection<string> _messages;
private ObservableCollection<string> _channels;
private Dictionary<string, List<string>> _channelMessages;
public bool HasChannels
{
get => _hasChannels;
set
{
_hasChannels = value;
OnPropertyChanged(nameof(HasChannels));
}
}
public ObservableCollection<string> Channels
{
get => _channels;
set
{
_channels = value;
OnPropertyChanged(nameof(Channels));
}
}
public string SelectedChannel
{
get => _selectedChannel;
set
{
_selectedChannel = value;
Messages = _channelMessages.ContainsKey(value) && _channelMessages[value].Count > 0
? new ObservableCollection<string>(_channelMessages[value])
: new ObservableCollection<string>();
OnPropertyChanged(nameof(SelectedChannel));
}
}
public ObservableCollection<string> Messages
{
get => _messages;
set
{
_messages = value;
OnPropertyChanged(nameof(Messages));
}
}
public UCOutputViewViewModel(IEventAggregator eventAggregator)
{
Messages = new ObservableCollection<string>();
eventAggregator.GetEvent<ApplicationOutputEvent>().Subscribe(OnApplicationOutput);
_channelMessages = new Dictionary<string, List<string>>();
Channels = new ObservableCollection<string>();
}
private void OnApplicationOutput(ApplicationOutputEventArgument obj)
{
if (!HasChannels || string.IsNullOrWhiteSpace(obj.Channel))
{
App.Current.Dispatcher.Invoke(delegate
{
if (Messages.Count >= 500)
{
Messages.RemoveAt(0);
}
Messages.Add(obj.Message);
});
return;
}
App.Current.Dispatcher.Invoke(delegate
{
if (!_channelMessages.ContainsKey(obj.Channel))
{
_channelMessages.Add(obj.Channel, new List<string>());
Channels.Add(obj.Channel);
}
if (obj.Channel != SelectedChannel)
{
SelectedChannel = obj.Channel;
}
if (Messages.Count >= 500)
{
Messages.RemoveAt(0);
_channelMessages[obj.Channel].RemoveAt(0);
}
Messages.Add(obj.Message);
_channelMessages[obj.Channel].Add(obj.Message);
});
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using CentralitaHerencia;
namespace Formulario
{
public partial class frmMostrar : Form
{
private Centralita cMostrar;
private Local.TipoLlamada tipo;
public Local.TipoLlamada Tipo
{
set
{
this.tipo = value;
}
}
private frmMostrar(Centralita c)
{
InitializeComponent();
this.cMostrar = c;
}
public frmMostrar(Centralita c, Local.TipoLlamada tipo)
:this(c)
{
this.Tipo = tipo;
}
private void frmMostrar_Load(object sender, EventArgs e)
{
rtbMostrar.Text = this.cMostrar.ToString();
}
private void rtbMostrar_TextChanged(object sender, EventArgs e)
{
}
}
}
|
namespace TLBOT.Optimizator {
public interface IOptimizator {
string GetName();
void BeforeTranslate(ref string Line, uint ID);
void AfterTranslate(ref string Line, uint ID);
void AfterOpen(ref string Line, uint ID);
void BeforeSave(ref string Line, uint ID);
}
}
|
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using lianda.Component;
namespace lianda.LD30
{
/// <summary>
/// LD3070 的摘要说明。
/// </summary>
public class LD3070 : BasePage
{
protected System.Web.UI.WebControls.Button Button3;
protected Infragistics.WebUI.WebSchedule.WebDateChooser dcsWTRQ;
protected Infragistics.WebUI.WebSchedule.WebDateChooser dcsWTRQ2;
protected System.Web.UI.WebControls.DropDownList ddlYWZT;
protected System.Web.UI.WebControls.TextBox WTDWMC;
protected System.Web.UI.WebControls.TextBox WTDW;
protected System.Web.UI.HtmlControls.HtmlImage IMG1;
protected DataDynamics.ActiveReports.Web.WebViewer WebViewer1;
private void Page_Load(object sender, System.EventArgs e)
{
// 在此处放置用户代码以初始化页面
if (!this.IsPostBack)
{
this.dcsWTRQ.Value = DateTime.Today.AddDays(-1);
this.dcsWTRQ2.Value = DateTime.Today;
}
}
#region Web 窗体设计器生成的代码
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.Button3.Click += new System.EventHandler(this.Button3_Click);
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
#region 报表数据源
/// <summary>
/// 报表数据源
/// </summary>
/// <returns>报表数据源</returns>
private SqlDataReader rptData()
{
string strSql = "";
strSql = "SELECT a.TZXH, a.TZRQ, a.WTDW, a.WTDWMC, a.SHDW, a.SHDWMC, b.JC, a.ZYGC, ";
strSql += " a.PM, a.CCH, a.RKDW, a.RKJS, a.CKDW, a.CKJS, a.ZYSJ, a.BWDC, a.DJ, ";
strSql += " a.JE, a.BZ, a.ZT, a.SKPZH, a.SKSJ, a.SKR, a.FPH, a.KPR, a.KPSJ, ";
strSql += "JSFS = case a.JSFS when '10' then '月结' when '20' then '现付' when '30' then '公司转帐' else '' end ";
strSql += " FROM C_CCTZ a LEFT OUTER JOIN J_KH b ON a.SHDW = b.BM ";
strSql += " WHERE (a.SC = 'N') and (a.JE <> 0) ";
// 委托单位
if (this.WTDW.Text != "")
strSql += " and a.WTDW='"+ this.WTDW.Text +"'";
// 台帐时间
if (this.dcsWTRQ.Value != null && this.dcsWTRQ.Value != System.DBNull.Value)
strSql += " and CONVERT(char(8),a.TZRQ,112) >= '"+ Convert.ToDateTime(this.dcsWTRQ.Value).ToString("yyyyMMdd") +"'";
if (this.dcsWTRQ2.Value != null && this.dcsWTRQ2.Value != System.DBNull.Value)
strSql += " and CONVERT(char(8),a.TZRQ,112) <= '"+ Convert.ToDateTime(this.dcsWTRQ2.Value).ToString("yyyyMMdd") +"'";
// 收款状态
if (this.ddlYWZT.SelectedValue != "")
{
if (this.ddlYWZT.SelectedValue == "20")
strSql += " and a.ZT = '20'";
else
strSql += " and a.ZT <> '20'";
}
strSql += " ORDER BY a.WTDW, a.TZXH";
SqlDataReader dr;
dr = SqlHelper.ExecuteReader(SqlHelper.CONN_STRING,CommandType.Text,strSql,null);
return dr;
}
#endregion
private void Button3_Click(object sender, System.EventArgs e)
{
if(this.dcsWTRQ.Value == null || this.dcsWTRQ2.Value == null || this.dcsWTRQ.Value == DBNull.Value || this.dcsWTRQ2.Value == DBNull.Value)
{
this.msgbox("请先选择日期!");
return;
}
this.WebViewer1.ClearCachedReport();
DataDynamics.ActiveReports.ActiveReport ar;
ar = new LD307010RP(Session["UserName"].ToString(),this.WTDW.Text,this.dcsWTRQ.Value.ToString(),this.dcsWTRQ2.Value.ToString());
ar.DataSource = rptData();
ar.Run(false);
this.WebViewer1.Report = ar;
}
}
}
|
using Business.Abstract;
using Business.Constant;
using Core.Utilities;
using DataAccess.Abstract;
using Entities.Concrete;
using Entities.DTOs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Business.Concrete
{
public class RentalManager : IRentalService
{
IRentalDal _rentalDal;
public RentalManager(IRentalDal rentalDal )
{
_rentalDal = rentalDal;
}
public IResult Add(Rental rental)
{
List<Rental> returnedCars = _rentalDal.GetAll(p => p.CarId == rental.CarId).ToList();
if(returnedCars.Count!=0)
{
foreach (var car in returnedCars)
{
if (car.ReturnDate == null)
{
return new ErrorResult(Messages.RentalNotAvailable);
}
}
}
rental.RentDate = DateTime.Now;
rental.ReturnDate = null;
_rentalDal.Add(rental);
return new SuccessResult(Messages.RentalAdded);
}
public IResult Completed(Rental rental)
{
var completeRental = _rentalDal.GetAll(p => p.Id == rental.Id);
if(completeRental.Any(p=>p.ReturnDate==null) && (completeRental.Count!=0))
{
rental.ReturnDate = DateTime.Now;
_rentalDal.Update(rental);
return new SuccessResult(Messages.RentalCompleted);
}
else
return new SuccessResult(Messages.RentalNotCompleted);
}
public IResult Delete(Rental rental)
{
_rentalDal.Delete(rental);
return new SuccessResult(Messages.RentalDeleted);
}
public IDataResult<List<Rental>> GetAll()
{
return new SuccessDataResult<List<Rental>>(_rentalDal.GetAll());
}
public IDataResult<Rental> GetById(int id)
{
return new SuccessDataResult<Rental>(_rentalDal.Get(p => p.Id == id));
}
public IDataResult<List<RentalDetailDto>> GetRentalDetails()
{
var sonuc = (_rentalDal.GetRentalDetails()).Count;
if(sonuc>0)
return new SuccessDataResult<List<RentalDetailDto>>(_rentalDal.GetRentalDetails());
else
return new ErrorDataResult<List<RentalDetailDto>>(Messages.RentalNoData);
}
public IResult Update(Rental rental)
{
_rentalDal.Update(rental);
return new SuccessResult(Messages.RentalUpdated);
}
}
}
|
using System;
using System.Collections.Generic;
namespace Logs.Models
{
public class Nutrition
{
public Nutrition()
{
}
public Nutrition(int calories, int protein, int carbs, int fats, double water, int fiber, int sugar, string notes,
string userId, DateTime date)
: this()
{
this.Calories = calories;
this.Protein = protein;
this.Carbs = carbs;
this.Fats = fats;
this.WaterInLitres = water;
this.Fiber = fiber;
this.Sugar = sugar;
this.Notes = notes;
this.UserId = userId;
this.Date = date;
}
public int NutritionId { get; set; }
public string Notes { get; set; }
public int Calories { get; set; }
public int Protein { get; set; }
public int Carbs { get; set; }
public int Fats { get; set; }
public double WaterInLitres { get; set; }
public int Fiber { get; set; }
public int Sugar { get; set; }
public DateTime Date { get; set; }
public string UserId { get; set; }
public virtual User User { get; set; }
}
}
|
namespace Microsoft.DataStudio.Services.Data.Models.Solutions
{
public class Solution
{
public string ID { get; set; }
//[Key]
public string Name { get; set; }
public string GraphUrl { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Zelo.Common.CustomAttributes;
namespace Zelo.DBModel
{
[Table(Name = "tconfinfo")]
public class Tconfinfo
{
[Id(Name = "cinfo_id", Strategy = GenerationType.INDENTITY)]
public int CinfoId{ get; set; }
[Column(Name = "cinfo_CGID")]
public string CinfoCGID{ get; set; }
[Column(Name = "cinfo_userGid")]
public string CinfoUserGid{ get; set; }
[Column(Name = "cinfo_CreateTime")]
public DateTime? CinfoCreateTime{ get; set; }
[Column(Name = "cinfo_UpdateTime")]
public DateTime? CinfoUpdateTime{ get; set; }
[Column(Name = "cinfo_isdel")]
public int? CinfoIsdel{ get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProtobufExample
{
public class Config
{
public const string SERVER_ADDR = "127.0.0.1";
public const int SERVER_PORT = 13423;
private Config() { }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using ERP_Palmeiras_RH.Models.Facade;
using ERP_Palmeiras_RH.Models;
using ERP_Palmeiras_RH.Core;
namespace ERP_Palmeiras_RH.WebServices
{
/// <summary>
/// Summary description for UsuariosWS
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class UsuariosWS : System.Web.Services.WebService
{
RecursosHumanos facade = RecursosHumanos.GetInstance();
[WebMethod]
public Boolean InserirUsuario(String login, String senha)
{
// Caso o usuario seja criado em outro modulo,
// é necessário criá-lo neste módulo, também.
// Esta função cria um Funcionário Externo,
// com dados stubs, com o login e senha fornecidos,
// de forma que se mantenha a consistência de existência
// dos logins nos módulos.
// No entanto, as informações deste usuário devem ser editadas no módulo de RH.
// Para isto, cria-se uma pendência de cadastro. Há uma tela de monitoramento de pendências.
try
{
Funcionario f = CriarFuncionarioExterno(login, senha);
facade.InserirFuncionario(f, false);
Pendencia p = new Pendencia();
p.Funcionario = f;
facade.InserirPendencia(p);
return true;
}
catch (ERPException)
{
// ja existe uma pendencia para esse funcionario ou ele ja existe neste modulo.
return true;
}
catch (Exception)
{
return false;
}
}
[WebMethod]
public Boolean AlterarUsuario(String loginNovo, String loginAntigo, String senhaNova)
{
try
{
Funcionario f = facade.BuscarFuncionario(loginAntigo);
f.Credencial.Usuario = loginNovo;
f.Credencial.Senha = senhaNova;
facade.AtualizarFuncionario(f);
return true;
}
catch (Exception)
{
return false;
}
}
private Funcionario CriarFuncionarioExterno(String login, String senha)
{
Funcionario func;
func = new Funcionario();
func.Ramal = 12;
func.Salario = 2000;
Admissao adm = new Admissao();
DateTime DataAdmissao = new DateTime(1967, 9, 12);
adm.DataAdmissao = DataAdmissao.Ticks;
adm.DataDesligamento = null;
adm.MotivoDesligamento = null;
adm.UltimoSalario = null;
func.Admissao = adm;
IEnumerable<Beneficio> beneficios = facade.BuscarBeneficios();
foreach (Beneficio b in beneficios)
{
func.Beneficios.Add(b);
}
Cargo cg = facade.BuscarCargos().First<Cargo>();
func.Cargo = cg;
Random rd = new Random();
DadoPessoal dp = new DadoPessoal();
int sulfixNome = rd.Next();
dp.Nome = "Funcionario" + sulfixNome;
dp.RG = rd.Next();
dp.Sexo = "Masculino";
dp.Sobrenome = "Externo";
dp.CPF = rd.Next();
DateTime DataNascimento = new DateTime(1967, 9, 12);
dp.DataNascimento = DataNascimento.Ticks;
dp.Email = "funcionario.externo" + sulfixNome.ToString() + "@xxx.com";
dp.CLT = rd.Next().ToString();
Endereco end = new Endereco();
end.Rua = "??";
end.Pais = "??";
end.Numero = rd.Next();
end.Estado = "??";
end.CEP = "00000-000";
end.Complemento = "";
end.Cidade = "??";
end.Bairro = "??";
Telefone tel = new Telefone();
String ddd = "11";
String telStr = "11111111";
tel.DDD = int.Parse(ddd);
tel.Numero = int.Parse(telStr);
dp.Telefones.Add(tel);
dp.Endereco = end;
func.DadosPessoais = dp;
Curriculum curriculum = new Curriculum();
byte[] cv = new byte[1000];
curriculum.Arquivo = cv;
curriculum.Formacao = "??";
func.Curriculum = curriculum;
Credencial c = new Credencial();
c.Senha = senha;
c.Usuario = login;
func.Credencial = c;
Permissao p = facade.BuscarPermissoes().First<Permissao>();
func.Permissao = p;
DadoBancario db = new DadoBancario();
db.Agencia = rd.Next().ToString().ToLower() + "-0";
db.Banco = 231;
db.ContaCorrente = rd.Next().ToString().ToLower() + "-00";
func.DadosBancarios = db;
func.Status = 1;
func.CartaoPonto = new CartaoPonto();
return func;
}
}
}
|
using FindSelf.Domain.SeedWork;
using System;
using System.Collections.Generic;
using System.Text;
namespace FindSelf.Infrastructure.Idempotent
{
public class IdempotentRequest
{
public Guid Id { get; }
public string CommandType { get; }
public IdempotentRequest(Guid id, string commandType)
{
Id = id;
CommandType = commandType ?? throw new ArgumentNullException(nameof(commandType));
}
}
}
|
using Amesc.Dominio.Contas;
using Microsoft.AspNetCore.Identity;
using System.Threading.Tasks;
namespace Amesc.Data.Identity
{
public class Autenticacao : IAutenticacao
{
private readonly SignInManager<ApplicationUser> _signInManager;
public Autenticacao(SignInManager<ApplicationUser> signInManager)
{
_signInManager = signInManager;
}
public async Task<bool> Autenticar(string email, string password)
{
var result = await _signInManager.PasswordSignInAsync(email, password, false, lockoutOnFailure: false);
return result.Succeeded;
}
public async Task Deslogar()
{
await _signInManager.SignOutAsync();
}
}
}
|
namespace HandyControlDemo.UserControl
{
/// <summary>
/// ImageBrowserDemoCtl.xaml 的交互逻辑
/// </summary>
public partial class ImageBrowserDemoCtl
{
public ImageBrowserDemoCtl()
{
InitializeComponent();
}
}
}
|
using UnityEngine;
using System.Collections;
public class PlayerProperties {
public static readonly string team = "Team";
public static readonly string experience = "Experience";
public static readonly string gameResult = "Result";
public static readonly string skin = "Skin";
public static readonly string score = "score";
public enum GameResult
{
None,
Lose,
Win,
Tie
}
}
|
using System;
using UnityEngine;
//using YoukiaUnity.App;
namespace YoukiaUnity.Graphics
{
/// <summary>
/// 基于2DSprites的布告板系统
/// </summary>
public class PanoramicSprite : MonoBehaviour
{
/// <summary>
/// Sprites
/// </summary>
public Sprite[] Sprites;
/// <summary>
/// InitialAngle
/// </summary>
public float InitialAngle = 0;
private Camera _viewCam;
/// <summary>
/// ViewCam
/// </summary>
public Camera ViewCam
{
set { _viewCam = value; }
get { return _viewCam ?? Camera.main; }
}
private SpriteRenderer _sprite;
private GraphicsManager _graphicsManager;
void Awake() {
if (_graphicsManager == null) {
_graphicsManager = GameObject.Find("GraphicsManager").GetComponent<GraphicsManager>();
}
}
// Use this for initialization
void Start() {
// _viewCam = YKApplication.Instance.GetManager<GraphicsManager>().MainCamera;
_viewCam = _graphicsManager.MainCamera;
// YKApplication.Instance.GetManager<GraphicsManager>().CameraFarClip = 50;
_graphicsManager.CameraFarClip = 50;
_sprite = GetComponent<SpriteRenderer>();
}
// Update is called once per frame
void Update()
{
int count = Sprites.Length;
Vector2 worldDir = new Vector2(transform.forward.x, transform.forward.z).normalized;
Vector3 camVec = transform.position - ViewCam.transform.position;
Vector2 camDir = new Vector2(camVec.x, camVec.z).normalized;
float degCam = Mathf.Acos(camDir.x);
degCam = ((degCam * Mathf.Sign(camDir.y) / Mathf.PI) + 1) / 2f;
float degObj = Mathf.PI - (float)Math.Acos(worldDir.x);
degObj = ((degObj * Mathf.Sign(worldDir.y) / Mathf.PI) + 1) / 2f;
degCam += degObj;
degCam -= (InitialAngle / 180f);
degCam += 0.5f / count;
degCam -= (float)Math.Floor(degCam);
// UiLog.Error(degree.ToString());
_sprite.sprite = Sprites[(int)Mathf.Floor(degCam * count)];
// _mat.SetTexture("_MainTex", TexArray[(int)Mathf.Floor(degCam * count)]);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace ZinsAct360
{
/// <summary>
/// Interaktionslogik für MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private int InterestDays(DateTime start, DateTime end)
{
return (end - start).Days;
}
private void btnCalculate_Click(object sender, RoutedEventArgs e)
{
DateTime start, end;
int iDays;
double k, z, p;
try
{
k = Convert.ToDouble(txtCapital.Text.Replace(".",","));
p = Convert.ToDouble(txtInterestRate.Text.Replace(".",","));
start = Convert.ToDateTime(dtpStart.Text);
end = Convert.ToDateTime(dtpEnd.Text);
if (start > end)
throw new Exception("Einzahlungsdatum muss vor Auszahlungsdatum liegen.");
iDays = (end - start).Days;
z = k * (p / 100.0) * (iDays / 360.0);
txtIDays.Text = iDays.ToString();
txtInterest.Text = z.ToString("f2");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Hinweis");
}
}
}
}
|
using System;
namespace CalculatorApp {
class NullableAtShow {
static void Main (string[] args) {
int? num1 = null;
int? num2 = 45;
double? num3 = new double?();
double? num4 = 3.1415926;
bool? boolval = new bool?();
Console.WriteLine ("显示可空类型的值:{0},{1},{2},{3}", num1, num2, num3, num4);
Console.WriteLine ("一个可空的布尔值:{0}", boolval);
nullablesFun ();
}
static void nullablesFun () {
double? num1 = null;
double? num2 = 3.14157;
double num3;
num3 = num1 ?? 5.34;
Console.WriteLine ("num3 的值:{0}", num3);
num3 = num2 ?? 5.34;
Console.WriteLine ("num3 的值:{0}", num3);
}
}
} |
namespace CarsDb.XmlQueries
{
public enum QueryType
{
Equals,
GreaterThan,
LessThan,
Contains
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DCDC_Manager
{
/// <summary>
/// Class providing auto update maintenence
/// </summary>
abstract public class WatchDog
{
private System.Timers.Timer _timer;
private bool _autoUpdate;
private System.IO.Ports.SerialPort _port;
private bool _readyToUpdate;
public bool IsAutoUpdate
{
get
{
throw new System.NotImplementedException();
}
set
{
}
}
/// <summary>
/// Update period in milliseconds
/// </summary>
public int UpdatePeriod
{
get
{
throw new System.NotImplementedException();
}
set
{
}
}
public System.IO.Ports.SerialPort Port
{
get
{
throw new System.NotImplementedException();
}
set
{
}
}
/// <summary>
/// Indicates if its possible to update value
/// </summary>
public bool ReadyToUpdate
{
get
{
throw new System.NotImplementedException();
}
set
{
}
}
abstract public void read();
abstract public void write();
public abstract string getReadQuery();
public abstract string getWriteQuery();
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace Problems.Burrows_Wheeler
{
public class BW_Encoding
{
public string Encoding(string _string)
{
string result = "";
List<string> permutations = new List<string>();
string aux = _string;
permutations.Add(aux);
for (int index=0; index < _string.Length-1; index++)
{
aux = aux.Substring(1, aux.Length-1) + aux[0];
permutations.Add(aux);
}
permutations.Sort();
for(int index=0;index<permutations.Count;index++)
{
result += permutations[index][permutations[index].Length-1];
}
return result;
}
}
}
|
using System;
using Pchp.Core;
namespace OC.Authentication.Token
{
public interface IToken : JsonSerializable
{
// const int TEMPORARY_TOKEN = 0;
// const int PERMANENT_TOKEN = 1;
// const int DO_NOT_REMEMBER = 0;
// const int REMEMBER = 1;
/**
* Get the token ID
*
* @return int
*/
int getId();
/**
* Get the user UID
*
* @return string
*/
string getUID() ;
/**
* Get the login name used when generating the token
*
* @return string
*/
string getLoginName() ;
/**
* Get the (encrypted) login password
*
* @return string|null
*/
string getPassword();
/**
* Get the timestamp of the last password check
*
* @return int
*/
int getLastCheck() ;
/**
* Set the timestamp of the last password check
*
* @param int $time
*/
void setLastCheck(int time);
/**
* Get the authentication scope for this token
*
* @return string
*/
string getScope() ;
/**
* Get the authentication scope for this token
*
* @return array
*/
PhpArray getScopeAsArray();
/**
* Set the authentication scope for this token
*
* @param array $scope
*/
void setScope(PhpArray scope);
/**
* Get the name of the token
* @return string
*/
string getName();
/**
* Get the remember state of the token
*
* @return int
*/
int getRemember();
/**
* Set the token
*
* @param string $token
*/
void setToken(string token);
/**
* Set the password
*
* @param string $password
*/
void setPassword(string password);
/**
* Set the expiration time of the token
*
* @param int|null $expires
*/
void setExpires(int? expires);
}
}
|
//
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
using System;
using System.Data;
using DotNetNuke.Entities.Modules;
namespace DotNetNuke.Tests.Integration.Executers.Dto
{
public class CopyModuleItem : IHydratable
{
public int Id { get; set; }
public string Title { get; set; }
public int KeyID
{
get { return Id; }
set { Id = value; }
}
public void Fill(IDataReader dr)
{
Id = Convert.ToInt32(dr["ModuleId"]);
Title = Convert.ToString(dr["ModuleTitle"]);
}
}
}
|
using System;
using System.Net.Http;
using System.Threading.Tasks;
namespace ZeroIssuesBot
{
class Program
{
private static HttpClient Client = new HttpClient();
static async Task Main(string[] args)
{
// get a new access token from discord api
DiscordBotAuthorizer authorizer = new DiscordBotAuthorizer();
DiscordToken Token = DiscordToken.GetTokenFromResponse(await authorizer.GetTokenResponse(Client));
Console.WriteLine(Token.access_token);
// Get list of slash commands from commands.json
var listOfCommands = CommandRegistrar.GetSlashCommands();
// Register each command from the list
foreach (var command in listOfCommands)
{
var res = await CommandRegistrar.AddApplicationCommand(Client, Token, command);
Console.WriteLine(res);
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.