text stringlengths 13 6.01M |
|---|
using System;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Application.Common.Dtos;
using Application.Common.Exceptions;
using Application.Common.Interface;
using Application.Common.Models;
using AutoMapper;
using Domain.Entities;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace Application.Product.Commands.UpdateProductCommands {
public class UpdateProductCommand : IRequest<string> {
public ProductRequestUpdateDto Product { get; set; }
public IFormFile Image { get; set; }
}
public class UpdateProductCommandHandler : BaseCommandHandler<UpdateProductCommandHandler>, IRequestHandler<UpdateProductCommand, string> {
public UpdateProductCommandHandler (IAppDbContext context, IMapper mapper, ILogger<UpdateProductCommandHandler> logger) : base (context, mapper, logger) { }
public async Task<string> Handle (UpdateProductCommand request, CancellationToken cancellationToken) {
Random rnd = new Random ();
var entity = Context.Products.Where (x => x.IdProduct == request.Product.IdProduct).FirstOrDefault ();
if (entity == null) throw new NotFoundException ("Product", "Not found!");
entity.IsAvailable = request.Product.IsAvailable;
entity.ProductName = request.Product.ProductName;
entity.Stock = request.Product.Stock;
entity.VariantName = request.Product.VariantName;
entity.BaseColor = request.Product.BaseColor;
entity.CategoryName = request.Product.CategoryName;
entity.Cost = request.Product.Cost;
entity.Description = request.Product.Description;
if (request.Image != null) {
try {
File.Delete (Path.Combine ("./Resources/Products", entity.ImageUrl));
} catch (Exception e) {
Logger.LogError ($"Error when delete file : {e}");
}
try {
string productName = request.Product.ProductName.Replace (" ", String.Empty);
var fileName = $"{productName}{rnd.Next(1,999)}{Path.GetExtension(request.Image.FileName)}";
var path = Path.Combine ("./Resources/Products", fileName);
using (var stream = System.IO.File.Create (path)) {
await request.Image.CopyToAsync (stream);
}
entity.ImageUrl = fileName;
} catch (Exception e) {
Logger.LogError ($"Error when moving file : {e}");
}
}
await Context.SaveChangesAsync (true, cancellationToken);
return "Sukses";
}
}
} |
using System.Diagnostics.CodeAnalysis;
using System.Runtime.Serialization;
using MediatR;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using OmniSharp.Extensions.JsonRpc;
using OmniSharp.Extensions.JsonRpc.Generation;
using OmniSharp.Extensions.LanguageServer.Protocol.Client;
using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities;
using OmniSharp.Extensions.LanguageServer.Protocol.Serialization;
using OmniSharp.Extensions.LanguageServer.Protocol.Server;
using OmniSharp.Extensions.LanguageServer.Protocol.Server.Capabilities;
// ReSharper disable once CheckNamespace
namespace OmniSharp.Extensions.LanguageServer.Protocol
{
namespace Models
{
public partial interface IInitializeParams<TClientCapabilities> : IWorkDoneProgressParams, IRequest<InitializeResult>
{
/// <summary>
/// The process Id of the parent process that started
/// the server. Is null if the process has not been started by another process.
/// If the parent process is not alive then the server should exit (see exit notification) its process.
/// </summary>
long? ProcessId { get; init; }
/// <summary>
/// Information about the client
///
/// @since 3.15.0
/// </summary>
[DisallowNull]
ClientInfo? ClientInfo { get; init; }
/// <summary>
/// The rootPath of the workspace. Is null
/// if no folder is open.
///
/// @deprecated in favour of rootUri.
/// </summary>
[DisallowNull]
string? RootPath { get; init; }
/// <summary>
/// The rootUri of the workspace. Is null if no
/// folder is open. If both `rootPath` and `rootUri` are set
/// `rootUri` wins.
/// </summary>
[DisallowNull]
DocumentUri? RootUri { get; init; }
/// <summary>
/// User provided initialization options.
/// </summary>
[DisallowNull]
object? InitializationOptions { get; init; }
/// <summary>
/// The capabilities provided by the client (editor or tool)
/// </summary>
[MaybeNull]
TClientCapabilities Capabilities { get; init; }
/// <summary>
/// The initial trace setting. If omitted trace is disabled ('off').
/// </summary>
InitializeTrace Trace { get; init; }
/// <summary>
/// The workspace folders configured in the client when the server starts.
/// This property is only available if the client supports workspace folders.
/// It can be `null` if the client supports workspace folders but none are
/// configured.
///
/// Since 3.6.0
/// </summary>
[DisallowNull]
Container<WorkspaceFolder>? WorkspaceFolders { get; init; }
}
[Method(GeneralNames.Initialize, Direction.ClientToServer)]
public record InitializeParams : IInitializeParams<ClientCapabilities>
{
/// <summary>
/// The process Id of the parent process that started
/// the server. Is null if the process has not been started by another process.
/// If the parent process is not alive then the server should exit (see exit notification) its process.
/// </summary>
public long? ProcessId { get; init; }
/// <summary>
/// Information about the client
///
/// @since 3.15.0
/// </summary>
[Optional]
[DisallowNull]
public ClientInfo? ClientInfo { get; init; }
/// <summary>
/// The rootPath of the workspace. Is null
/// if no folder is open.
///
/// @deprecated in favour of rootUri.
/// </summary>
[Optional]
[DisallowNull]
public string? RootPath
{
get => RootUri?.GetFileSystemPath();
init
{
if (!string.IsNullOrEmpty(value))
{
RootUri = DocumentUri.FromFileSystemPath(value);
}
}
}
/// <summary>
/// The rootUri of the workspace. Is null if no
/// folder is open. If both `rootPath` and `rootUri` are set
/// `rootUri` wins.
/// </summary>
[DisallowNull]
public DocumentUri? RootUri { get; init; }
/// <summary>
/// User provided initialization options.
/// </summary>
[DisallowNull]
public object? InitializationOptions { get; init; }
/// <summary>
/// The capabilities provided by the client (editor or tool)
/// </summary>
[MaybeNull]
public ClientCapabilities Capabilities { get; init; }
/// <summary>
/// The initial trace setting. If omitted trace is disabled ('off').
/// </summary>
[Optional]
public InitializeTrace Trace { get; init; } = InitializeTrace.Off;
/// <summary>
/// The workspace folders configured in the client when the server starts.
/// This property is only available if the client supports workspace folders.
/// It can be `null` if the client supports workspace folders but none are
/// configured.
///
/// Since 3.6.0
/// </summary>
[MaybeNull]
public Container<WorkspaceFolder>? WorkspaceFolders { get; init; }
/// <inheritdoc />
[Optional]
[MaybeNull]
public ProgressToken? WorkDoneToken { get; init; }
/// <summary>
/// The locale the client is currently showing the user interface
/// in. This must not necessarily be the locale of the operating
/// system.
///
/// Uses IETF language tags as the value's syntax
/// (See https://en.wikipedia.org/wiki/IETF_language_tag)
///
/// @since 3.16.0
/// </summary>
[Optional]
public string? Locale { get; init; }
public InitializeParams()
{
}
internal InitializeParams(IInitializeParams<JObject> @params, ClientCapabilities clientCapabilities)
{
ProcessId = @params.ProcessId;
Trace = @params.Trace;
Capabilities = clientCapabilities;
ClientInfo = @params.ClientInfo!;
InitializationOptions = @params.InitializationOptions!;
RootUri = @params.RootUri!;
WorkspaceFolders = @params.WorkspaceFolders!;
WorkDoneToken = @params.WorkDoneToken!;
}
}
[Serial]
[Method(GeneralNames.Initialize, Direction.ClientToServer)]
[GenerateHandler("OmniSharp.Extensions.LanguageServer.Protocol.General", Name = "LanguageProtocolInitialize")]
[GenerateHandlerMethods(typeof(ILanguageServerRegistry))]
[GenerateRequestMethods(typeof(ILanguageClient))]
internal partial record
InternalInitializeParams : IInitializeParams<JObject>, IRequest<InitializeResult> // This is required for generation to work correctly.
{
/// <summary>
/// The process Id of the parent process that started
/// the server. Is null if the process has not been started by another process.
/// If the parent process is not alive then the server should exit (see exit notification) its process.
/// </summary>
public long? ProcessId { get; init; }
/// <summary>
/// Information about the client
///
/// @since 3.15.0
/// </summary>
[Optional]
public ClientInfo? ClientInfo { get; init; }
/// <summary>
/// The rootPath of the workspace. Is null
/// if no folder is open.
///
/// @deprecated in favour of rootUri.
/// </summary>
[Optional]
public string? RootPath
{
get => RootUri.GetFileSystemPath();
init => RootUri = ( value == null ? null : DocumentUri.FromFileSystemPath(value) )!;
}
/// <summary>
/// The rootUri of the workspace. Is null if no
/// folder is open. If both `rootPath` and `rootUri` are set
/// `rootUri` wins.
/// </summary>
public DocumentUri RootUri { get; init; } = null!;
/// <summary>
/// User provided initialization options.
/// </summary>
public object? InitializationOptions { get; init; }
/// <summary>
/// The capabilities provided by the client (editor or tool)
/// </summary>
public JObject Capabilities { get; init; } = null!;
/// <summary>
/// The initial trace setting. If omitted trace is disabled ('off').
/// </summary>
[Optional]
public InitializeTrace Trace { get; init; } = InitializeTrace.Off;
/// <summary>
/// The workspace folders configured in the client when the server starts.
/// This property is only available if the client supports workspace folders.
/// It can be `null` if the client supports workspace folders but none are
/// configured.
///
/// Since 3.6.0
/// </summary>
public Container<WorkspaceFolder>? WorkspaceFolders { get; init; }
/// <inheritdoc />
[Optional]
public ProgressToken? WorkDoneToken { get; init; }
}
public partial record InitializeResult
{
/// <summary>
/// The capabilities the language server provides.
/// </summary>
public ServerCapabilities Capabilities { get; init; }
/// <summary>
/// Information about the server.
///
/// @since 3.15.0
/// </summary>
[Optional]
public ServerInfo? ServerInfo { get; init; }
}
public record InitializeError
{
/// <summary>
/// Indicates whether the client should retry to send the
/// initialize request after showing the message provided
/// in the ResponseError.
/// </summary>
public bool Retry { get; init; }
}
[JsonConverter(typeof(StringEnumConverter))]
public enum InitializeTrace
{
[EnumMember(Value = "off")] Off,
[EnumMember(Value = "messages")] Messages,
[EnumMember(Value = "verbose")] Verbose
}
}
}
|
using LuaInterface;
using RO;
using RO.Net;
using SLua;
using System;
using System.Collections;
using System.Net.Sockets;
public class Lua_RO_Net_NetConnectionManager : LuaObject
{
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int constructor(IntPtr l)
{
int result;
try
{
NetConnectionManager o = new NetConnectionManager();
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 Restart(IntPtr l)
{
int result;
try
{
NetConnectionManager netConnectionManager = (NetConnectionManager)LuaObject.checkSelf(l);
netConnectionManager.Restart();
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int ConnLoginServer(IntPtr l)
{
int result;
try
{
NetConnectionManager netConnectionManager = (NetConnectionManager)LuaObject.checkSelf(l);
string ip;
LuaObject.checkType(l, 2, out ip);
int port;
LuaObject.checkType(l, 3, out port);
Action<int, int> handle;
LuaDelegation.checkDelegate(l, 4, out handle);
netConnectionManager.ConnLoginServer(ip, port, handle);
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int ConnGameServer(IntPtr l)
{
int result;
try
{
NetConnectionManager netConnectionManager = (NetConnectionManager)LuaObject.checkSelf(l);
string ip;
LuaObject.checkType(l, 2, out ip);
int port;
LuaObject.checkType(l, 3, out port);
Action<int, int> handle;
LuaDelegation.checkDelegate(l, 4, out handle);
netConnectionManager.ConnGameServer(ip, port, handle);
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int GetIPCallback(IntPtr l)
{
int result;
try
{
NetConnectionManager netConnectionManager = (NetConnectionManager)LuaObject.checkSelf(l);
NetConnectionManager.QueryIpWraper wraper;
LuaObject.checkType<NetConnectionManager.QueryIpWraper>(l, 2, out wraper);
Action<string> callback;
LuaDelegation.checkDelegate(l, 3, out callback);
IEnumerator iPCallback = netConnectionManager.GetIPCallback(wraper, callback);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, iPCallback);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int StartGetIP(IntPtr l)
{
int result;
try
{
NetConnectionManager netConnectionManager = (NetConnectionManager)LuaObject.checkSelf(l);
object obj;
LuaObject.checkType<object>(l, 2, out obj);
netConnectionManager.StartGetIP(obj);
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int ConnCallback(IntPtr l)
{
int result;
try
{
NetConnectionManager netConnectionManager = (NetConnectionManager)LuaObject.checkSelf(l);
NetConnection connect;
LuaObject.checkType<NetConnection>(l, 2, out connect);
Action<int> callback;
LuaDelegation.checkDelegate(l, 3, out callback);
IEnumerator o = netConnectionManager.ConnCallback(connect, callback);
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 GameClose(IntPtr l)
{
int result;
try
{
NetConnectionManager netConnectionManager = (NetConnectionManager)LuaObject.checkSelf(l);
netConnectionManager.GameClose();
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int DisConnect(IntPtr l)
{
int result;
try
{
NetConnectionManager netConnectionManager = (NetConnectionManager)LuaObject.checkSelf(l);
netConnectionManager.DisConnect();
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int setSocket(IntPtr l)
{
int result;
try
{
NetConnectionManager netConnectionManager = (NetConnectionManager)LuaObject.checkSelf(l);
Socket socket;
LuaObject.checkType<Socket>(l, 2, out socket);
netConnectionManager.setSocket(socket);
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int IsConnected(IntPtr l)
{
int result;
try
{
NetConnectionManager netConnectionManager = (NetConnectionManager)LuaObject.checkSelf(l);
bool b = netConnectionManager.IsConnected();
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, b);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int SetSendCallBack(IntPtr l)
{
int result;
try
{
NetConnectionManager netConnectionManager = (NetConnectionManager)LuaObject.checkSelf(l);
Action<NetProtocolID> sendCallBack;
LuaDelegation.checkDelegate(l, 2, out sendCallBack);
netConnectionManager.SetSendCallBack(sendCallBack);
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int AddSendCallBackProtocolID(IntPtr l)
{
int result;
try
{
NetConnectionManager netConnectionManager = (NetConnectionManager)LuaObject.checkSelf(l);
uint id;
LuaObject.checkType(l, 2, out id);
uint id2;
LuaObject.checkType(l, 3, out id2);
netConnectionManager.AddSendCallBackProtocolID(id, id2);
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int DoGameSend(IntPtr l)
{
int result;
try
{
NetConnectionManager netConnectionManager = (NetConnectionManager)LuaObject.checkSelf(l);
uint id;
LuaObject.checkType(l, 2, out id);
uint id2;
LuaObject.checkType(l, 3, out id2);
byte[] bytes;
LuaObject.checkArray<byte>(l, 4, out bytes);
netConnectionManager.DoGameSend(id, id2, bytes);
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int GameHandleReceive(IntPtr l)
{
int result;
try
{
NetConnectionManager netConnectionManager = (NetConnectionManager)LuaObject.checkSelf(l);
byte[] bytes;
LuaObject.checkArray<byte>(l, 2, out bytes);
int length;
LuaObject.checkType(l, 3, out length);
netConnectionManager.GameHandleReceive(bytes, length);
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_EnableLog(IntPtr l)
{
int result;
try
{
NetConnectionManager netConnectionManager = (NetConnectionManager)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, netConnectionManager.EnableLog);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_EnableLog(IntPtr l)
{
int result;
try
{
NetConnectionManager netConnectionManager = (NetConnectionManager)LuaObject.checkSelf(l);
bool enableLog;
LuaObject.checkType(l, 2, out enableLog);
netConnectionManager.EnableLog = enableLog;
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_EnableEncrypt(IntPtr l)
{
int result;
try
{
NetConnectionManager netConnectionManager = (NetConnectionManager)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, netConnectionManager.EnableEncrypt);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_EnableEncrypt(IntPtr l)
{
int result;
try
{
NetConnectionManager netConnectionManager = (NetConnectionManager)LuaObject.checkSelf(l);
bool enableEncrypt;
LuaObject.checkType(l, 2, out enableEncrypt);
netConnectionManager.EnableEncrypt = enableEncrypt;
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_EnableNonce(IntPtr l)
{
int result;
try
{
NetConnectionManager netConnectionManager = (NetConnectionManager)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, netConnectionManager.EnableNonce);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_EnableNonce(IntPtr l)
{
int result;
try
{
NetConnectionManager netConnectionManager = (NetConnectionManager)LuaObject.checkSelf(l);
bool enableNonce;
LuaObject.checkType(l, 2, out enableNonce);
netConnectionManager.EnableNonce = enableNonce;
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_EnableSelfResolve(IntPtr l)
{
int result;
try
{
NetConnectionManager netConnectionManager = (NetConnectionManager)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, netConnectionManager.EnableSelfResolve);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_EnableSelfResolve(IntPtr l)
{
int result;
try
{
NetConnectionManager netConnectionManager = (NetConnectionManager)LuaObject.checkSelf(l);
bool enableSelfResolve;
LuaObject.checkType(l, 2, out enableSelfResolve);
netConnectionManager.EnableSelfResolve = enableSelfResolve;
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_maxZibNum(IntPtr l)
{
int result;
try
{
NetConnectionManager netConnectionManager = (NetConnectionManager)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, netConnectionManager.maxZibNum);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_maxZibNum(IntPtr l)
{
int result;
try
{
NetConnectionManager netConnectionManager = (NetConnectionManager)LuaObject.checkSelf(l);
int maxZibNum;
LuaObject.checkType(l, 2, out maxZibNum);
netConnectionManager.maxZibNum = maxZibNum;
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_compressLevel(IntPtr l)
{
int result;
try
{
NetConnectionManager netConnectionManager = (NetConnectionManager)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, netConnectionManager.compressLevel);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_compressLevel(IntPtr l)
{
int result;
try
{
NetConnectionManager netConnectionManager = (NetConnectionManager)LuaObject.checkSelf(l);
int compressLevel;
LuaObject.checkType(l, 2, out compressLevel);
netConnectionManager.compressLevel = compressLevel;
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_connectTimeOut(IntPtr l)
{
int result;
try
{
NetConnectionManager netConnectionManager = (NetConnectionManager)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, netConnectionManager.connectTimeOut);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_connectTimeOut(IntPtr l)
{
int result;
try
{
NetConnectionManager netConnectionManager = (NetConnectionManager)LuaObject.checkSelf(l);
int connectTimeOut;
LuaObject.checkType(l, 2, out connectTimeOut);
netConnectionManager.connectTimeOut = connectTimeOut;
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_recvMaxLen(IntPtr l)
{
int result;
try
{
NetConnectionManager netConnectionManager = (NetConnectionManager)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, netConnectionManager.recvMaxLen);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_recvMaxLen(IntPtr l)
{
int result;
try
{
NetConnectionManager netConnectionManager = (NetConnectionManager)LuaObject.checkSelf(l);
int recvMaxLen;
LuaObject.checkType(l, 2, out recvMaxLen);
netConnectionManager.recvMaxLen = recvMaxLen;
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_uploadByteLength(IntPtr l)
{
int result;
try
{
NetConnectionManager netConnectionManager = (NetConnectionManager)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, netConnectionManager.uploadByteLength);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_uploadByteLength(IntPtr l)
{
int result;
try
{
NetConnectionManager netConnectionManager = (NetConnectionManager)LuaObject.checkSelf(l);
double uploadByteLength;
LuaObject.checkType(l, 2, out uploadByteLength);
netConnectionManager.uploadByteLength = uploadByteLength;
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_downloadbyteLength(IntPtr l)
{
int result;
try
{
NetConnectionManager netConnectionManager = (NetConnectionManager)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, netConnectionManager.downloadbyteLength);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_downloadbyteLength(IntPtr l)
{
int result;
try
{
NetConnectionManager netConnectionManager = (NetConnectionManager)LuaObject.checkSelf(l);
double downloadbyteLength;
LuaObject.checkType(l, 2, out downloadbyteLength);
netConnectionManager.downloadbyteLength = downloadbyteLength;
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_updateIntervalMillis(IntPtr l)
{
int result;
try
{
NetConnectionManager netConnectionManager = (NetConnectionManager)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, netConnectionManager.updateIntervalMillis);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_updateIntervalMillis(IntPtr l)
{
int result;
try
{
NetConnectionManager netConnectionManager = (NetConnectionManager)LuaObject.checkSelf(l);
int updateIntervalMillis;
LuaObject.checkType(l, 2, out updateIntervalMillis);
netConnectionManager.updateIntervalMillis = updateIntervalMillis;
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_updateIntervalLimitMillis(IntPtr l)
{
int result;
try
{
NetConnectionManager netConnectionManager = (NetConnectionManager)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, netConnectionManager.updateIntervalLimitMillis);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_updateIntervalLimitMillis(IntPtr l)
{
int result;
try
{
NetConnectionManager netConnectionManager = (NetConnectionManager)LuaObject.checkSelf(l);
int updateIntervalLimitMillis;
LuaObject.checkType(l, 2, out updateIntervalLimitMillis);
netConnectionManager.updateIntervalLimitMillis = updateIntervalLimitMillis;
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_Instance(IntPtr l)
{
int result;
try
{
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, NetConnectionManager.Instance);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_GameIsReceiving(IntPtr l)
{
int result;
try
{
NetConnectionManager netConnectionManager = (NetConnectionManager)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, netConnectionManager.GameIsReceiving);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_GameUpdate(IntPtr l)
{
int result;
try
{
NetConnectionManager netConnectionManager = (NetConnectionManager)LuaObject.checkSelf(l);
Action action;
int num = LuaDelegation.checkDelegate(l, 2, out action);
if (num == 0)
{
netConnectionManager.GameUpdate = action;
}
else if (num == 1)
{
NetConnectionManager expr_30 = netConnectionManager;
expr_30.GameUpdate = (Action)Delegate.Combine(expr_30.GameUpdate, action);
}
else if (num == 2)
{
NetConnectionManager expr_53 = netConnectionManager;
expr_53.GameUpdate = (Action)Delegate.Remove(expr_53.GameUpdate, action);
}
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.Net.NetConnectionManager");
LuaObject.addMember(l, new LuaCSFunction(Lua_RO_Net_NetConnectionManager.Restart));
LuaObject.addMember(l, new LuaCSFunction(Lua_RO_Net_NetConnectionManager.ConnLoginServer));
LuaObject.addMember(l, new LuaCSFunction(Lua_RO_Net_NetConnectionManager.ConnGameServer));
LuaObject.addMember(l, new LuaCSFunction(Lua_RO_Net_NetConnectionManager.GetIPCallback));
LuaObject.addMember(l, new LuaCSFunction(Lua_RO_Net_NetConnectionManager.StartGetIP));
LuaObject.addMember(l, new LuaCSFunction(Lua_RO_Net_NetConnectionManager.ConnCallback));
LuaObject.addMember(l, new LuaCSFunction(Lua_RO_Net_NetConnectionManager.GameClose));
LuaObject.addMember(l, new LuaCSFunction(Lua_RO_Net_NetConnectionManager.DisConnect));
LuaObject.addMember(l, new LuaCSFunction(Lua_RO_Net_NetConnectionManager.setSocket));
LuaObject.addMember(l, new LuaCSFunction(Lua_RO_Net_NetConnectionManager.IsConnected));
LuaObject.addMember(l, new LuaCSFunction(Lua_RO_Net_NetConnectionManager.SetSendCallBack));
LuaObject.addMember(l, new LuaCSFunction(Lua_RO_Net_NetConnectionManager.AddSendCallBackProtocolID));
LuaObject.addMember(l, new LuaCSFunction(Lua_RO_Net_NetConnectionManager.DoGameSend));
LuaObject.addMember(l, new LuaCSFunction(Lua_RO_Net_NetConnectionManager.GameHandleReceive));
LuaObject.addMember(l, "EnableLog", new LuaCSFunction(Lua_RO_Net_NetConnectionManager.get_EnableLog), new LuaCSFunction(Lua_RO_Net_NetConnectionManager.set_EnableLog), true);
LuaObject.addMember(l, "EnableEncrypt", new LuaCSFunction(Lua_RO_Net_NetConnectionManager.get_EnableEncrypt), new LuaCSFunction(Lua_RO_Net_NetConnectionManager.set_EnableEncrypt), true);
LuaObject.addMember(l, "EnableNonce", new LuaCSFunction(Lua_RO_Net_NetConnectionManager.get_EnableNonce), new LuaCSFunction(Lua_RO_Net_NetConnectionManager.set_EnableNonce), true);
LuaObject.addMember(l, "EnableSelfResolve", new LuaCSFunction(Lua_RO_Net_NetConnectionManager.get_EnableSelfResolve), new LuaCSFunction(Lua_RO_Net_NetConnectionManager.set_EnableSelfResolve), true);
LuaObject.addMember(l, "maxZibNum", new LuaCSFunction(Lua_RO_Net_NetConnectionManager.get_maxZibNum), new LuaCSFunction(Lua_RO_Net_NetConnectionManager.set_maxZibNum), true);
LuaObject.addMember(l, "compressLevel", new LuaCSFunction(Lua_RO_Net_NetConnectionManager.get_compressLevel), new LuaCSFunction(Lua_RO_Net_NetConnectionManager.set_compressLevel), true);
LuaObject.addMember(l, "connectTimeOut", new LuaCSFunction(Lua_RO_Net_NetConnectionManager.get_connectTimeOut), new LuaCSFunction(Lua_RO_Net_NetConnectionManager.set_connectTimeOut), true);
LuaObject.addMember(l, "recvMaxLen", new LuaCSFunction(Lua_RO_Net_NetConnectionManager.get_recvMaxLen), new LuaCSFunction(Lua_RO_Net_NetConnectionManager.set_recvMaxLen), true);
LuaObject.addMember(l, "uploadByteLength", new LuaCSFunction(Lua_RO_Net_NetConnectionManager.get_uploadByteLength), new LuaCSFunction(Lua_RO_Net_NetConnectionManager.set_uploadByteLength), true);
LuaObject.addMember(l, "downloadbyteLength", new LuaCSFunction(Lua_RO_Net_NetConnectionManager.get_downloadbyteLength), new LuaCSFunction(Lua_RO_Net_NetConnectionManager.set_downloadbyteLength), true);
LuaObject.addMember(l, "updateIntervalMillis", new LuaCSFunction(Lua_RO_Net_NetConnectionManager.get_updateIntervalMillis), new LuaCSFunction(Lua_RO_Net_NetConnectionManager.set_updateIntervalMillis), true);
LuaObject.addMember(l, "updateIntervalLimitMillis", new LuaCSFunction(Lua_RO_Net_NetConnectionManager.get_updateIntervalLimitMillis), new LuaCSFunction(Lua_RO_Net_NetConnectionManager.set_updateIntervalLimitMillis), true);
LuaObject.addMember(l, "Instance", new LuaCSFunction(Lua_RO_Net_NetConnectionManager.get_Instance), null, false);
LuaObject.addMember(l, "GameIsReceiving", new LuaCSFunction(Lua_RO_Net_NetConnectionManager.get_GameIsReceiving), null, true);
LuaObject.addMember(l, "GameUpdate", null, new LuaCSFunction(Lua_RO_Net_NetConnectionManager.set_GameUpdate), true);
LuaObject.createTypeMetatable(l, new LuaCSFunction(Lua_RO_Net_NetConnectionManager.constructor), typeof(NetConnectionManager), typeof(SingleTonGO<NetConnectionManager>));
}
}
|
using Infrastructure;
using Models.DDD.TimeSheets.Entries;
using Prism.Commands;
using Prism.Mvvm;
using Prism.Regions;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.Composition;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TimeKeep.Services;
namespace TimeKeep.ViewModels
{
[Export]
public class EntryEditViewModel : BindableBase, INavigationAware
{
private IRegionManager _regionManager;
private EntryService _entryService;
private Guid _timeSheetId;
private Guid _entryId;
[ImportingConstructor]
public EntryEditViewModel(IRegionManager regionManager,EntryService entryService)
{
_regionManager = regionManager;
_entryService = entryService;
this.SubmitCommand = new DelegateCommand(Submit);
}
private int _projectNumber;
public int ProjectNumber
{
get { return _projectNumber; }
set { SetProperty(ref _projectNumber, value); }
}
private DateTime _start;
public DateTime Start
{
get { return _start; }
set { SetProperty(ref _start, value); }
}
private DateTime _end;
public DateTime End
{
get { return _end; }
set { SetProperty(ref _end, value); }
}
private double _hours;
public double Hours
{
get { return _hours; }
set { SetProperty(ref _hours, value); }
}
private string _comment;
public string Comment
{
get { return _comment; }
set { SetProperty(ref _comment, value); }
}
public DelegateCommand SubmitCommand { get; private set; }
public void Submit()
{
_entryService.EnterHours(this.ProjectNumber, this.Hours, 0, this.Comment);
_regionManager.RequestNavigate(RegionNames.ContentRegion, ViewNames.TimeKeepView);
}
public bool IsNavigationTarget(NavigationContext navigationContext)
{
return true;
}
public void OnNavigatedFrom(NavigationContext navigationContext)
{
}
public void OnNavigatedTo(NavigationContext navigationContext)
{
//not needed
_timeSheetId =(Guid)navigationContext.Parameters["TimeSheetId"];
}
}
}
|
// Copyright (c) 2019 SceneGate
// 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.
namespace Clypo
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using Clypo.Layout;
using Yarhl.FileFormat;
using Yarhl.IO;
/// <summary>
/// CLYT layout format to binary (BCLYT).
/// </summary>
/// <remarks>
/// <p>Based on assembly research and information from:
/// https://www.3dbrew.org/wiki/CLYT_format</p>
/// </remarks>
public class Clyt2Binary : IConverter<Clyt, BinaryFormat>
{
const string Id = "CLYT";
const ushort Endianness = 0xFEFF;
const ushort HeaderSize = 0x14;
const uint Version = 0x02020000; // 2.2.0.0
DataWriter writer;
int sections;
public BinaryFormat Convert(Clyt source)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
var binary = new BinaryFormat();
writer = new DataWriter(binary.Stream);
WriteHeader(source);
WriteSections(source);
FinishHeader();
return binary;
}
void WriteHeader(Clyt source)
{
writer.Write(Id, nullTerminator: false);
writer.Write(Endianness);
writer.Write(HeaderSize);
writer.Write(Version);
writer.Write(0x00); // placeholder for size
writer.Write(0x00); // placeholder for number of sections
}
void FinishHeader()
{
writer.Stream.Position = 0x0C;
writer.Write((uint)writer.Stream.Length);
writer.Write(sections);
}
void WriteSections(Clyt source)
{
WriteSection("lyt1", () => WriteLayout(source.Layout));
if (source.Textures.Count > 0) {
WriteSection("txl1", () => WriteTextures(source.Textures));
}
if (source.Fonts.Count > 0) {
WriteSection("fnl1", () => WriteFonts(source.Fonts));
}
if (source.Materials.Count > 0) {
WriteSection("mat1", () => WriteMaterials(source.Materials));
}
WritePanelGroup(source.RootPanel);
WriteGroups(source.RootGroup);
}
void WritePanelGroup(Panel panel)
{
if (panel is TextSection text) {
WriteSection("txt1", () => WriteTextInfo(text));
} else if (panel is Picture picture) {
WriteSection("pic1", () => WritePictureInfo(picture));
} else if (panel is Window window) {
WriteSection("wnd1", () => WriteWindow(window));
} else if (panel is Boundary boundary) {
WriteSection("bnd1", () => WriteBoundary(boundary));
} else {
WriteSection("pan1", () => WritePanel(panel));
}
if (panel.UserData != null) {
WriteSection("usd1", () => WriteUserData(panel.UserData));
}
if (panel.Children.Any()) {
WriteSection("pas1", () => {});
foreach (var child in panel.Children) {
WritePanelGroup(child);
}
WriteSection("pae1", () => {});
}
}
void WriteGroups(Group group)
{
WriteSection("grp1", () => WriteGroup(group));
if (group.Children.Any()) {
WriteSection("grs1", () => { });
foreach (var child in group.Children) {
WriteGroups(child);
}
WriteSection("gre1", () => { });
}
}
void WriteSection(string id, Action writeFnc)
{
long initialSize = writer.Stream.Length;
long initialPos = writer.Stream.Position;
writer.Write(id, nullTerminator: false);
writer.Write(0x00); // place holder for size
writeFnc();
writer.WritePadding(0x00, 4);
// Update size
uint sectionSize = (uint)(writer.Stream.Length - initialSize);
writer.Stream.Position = initialPos + 0x04;
writer.Write(sectionSize);
writer.Stream.Position = initialPos + sectionSize;
sections++;
}
void WriteLayout(LayoutDefinition layout)
{
writer.Write((uint)layout.Origin);
writer.Write(layout.Size.Width);
writer.Write(layout.Size.Height);
}
void WriteTextures(Collection<string> textures)
{
writer.Write(textures.Count);
// Pre-initialize offset table so we can write names at the same time
long tablePos = writer.Stream.Position;
writer.WriteTimes(0x00, 4 * textures.Count);
for (int i = 0; i < textures.Count; i++) {
writer.Stream.RunInPosition(
() => writer.Write((uint)(writer.Stream.Length - tablePos)),
tablePos + (i * 4));
writer.Write(textures[i]);
}
}
void WriteFonts(Collection<string> fonts)
{
writer.Write(fonts.Count);
// Pre-initialize offset table so we can write names at the same time
long tablePos = writer.Stream.Position;
writer.WriteTimes(0x00, 4 * fonts.Count);
for (int i = 0; i < fonts.Count; i++) {
writer.Stream.RunInPosition(
() => writer.Write((uint)(writer.Stream.Length - tablePos)),
tablePos + (i * 4));
writer.Write(fonts[i]);
}
}
void WriteMaterials(Collection<Material> materials)
{
long sectionStart = writer.Stream.Position - 8;
writer.Write(materials.Count);
// Pre-initialize offset table so we can write names at the same time
long tablePos = writer.Stream.Position;
writer.WriteTimes(0x00, 4 * materials.Count);
for (int idx = 0; idx < materials.Count; idx++) {
writer.Stream.RunInPosition(
() => writer.Write((uint)(writer.Stream.Length - sectionStart)),
tablePos + (idx * 4));
Material mat = materials[idx];
writer.Write(mat.Name, 0x14);
for (int j = 0; j < mat.TevConstantColors.Length; j++) {
writer.Write(mat.TevConstantColors[j]);
}
int flag = 0x00;
flag |= mat.TexMapEntries.Count;
flag |= mat.TexMatrixEntries.Count << 2;
flag |= mat.TextureCoordGen.Count << 4;
flag |= mat.TevStages.Count << 6;
flag |= ((mat.AlphaCompare != null) ? 1 : 0) << 9;
flag |= ((mat.ColorBlendMode != null) ? 1 : 0) << 10;
flag |= (mat.UseTextureOnly ? 1 : 0) << 11;
flag |= ((mat.AlphaBlendMode != null) ? 1 : 0) << 12;
// TODO: Find a bclyt with the rest of sections
writer.Write(flag);
foreach (var entry in mat.TexMapEntries) {
writer.Write((ushort)entry.Index);
int flag1 = (byte)(entry.WrapS);
int flag2 = (byte)(entry.WrapT);
flag1 |= (byte)(entry.MinFilter) << 2;
flag2 |= (byte)(entry.MagFilter) << 2;
writer.Write((byte)flag1);
writer.Write((byte)flag2);
}
foreach (var entry in mat.TexMatrixEntries) {
writer.Write(entry.Translation.X);
writer.Write(entry.Translation.Y);
writer.Write(entry.Rotation);
writer.Write(entry.Scale.X);
writer.Write(entry.Scale.Y);
}
foreach (var coord in mat.TextureCoordGen) {
writer.Write(coord);
}
foreach (var tev in mat.TevStages) {
writer.Write(tev.Param1);
writer.Write(tev.Param2);
writer.Write(tev.Param3);
}
if (mat.AlphaCompare != null) {
writer.Write(mat.AlphaCompare.Function);
writer.Write(mat.AlphaCompare.Reference);
}
if (mat.ColorBlendMode != null) {
writer.Write(mat.ColorBlendMode.BlendOperator);
writer.Write(mat.ColorBlendMode.SourceFactor);
writer.Write(mat.ColorBlendMode.DestinationFactor);
writer.Write(mat.ColorBlendMode.LogicOperator);
}
if (mat.AlphaBlendMode != null) {
writer.Write(mat.AlphaBlendMode.BlendOperator);
writer.Write(mat.AlphaBlendMode.SourceFactor);
writer.Write(mat.AlphaBlendMode.DestinationFactor);
writer.Write(mat.AlphaBlendMode.LogicOperator);
}
}
}
void WriteGroup(Group group)
{
writer.Write(group.Name, 0x10);
writer.Write((uint)group.Panels.Count);
foreach (var panel in group.Panels) {
writer.Write(panel, 0x10, false);
}
}
void WritePanel(Panel panel)
{
writer.Write((byte)panel.Flags);
writer.Write(panel.Origin);
writer.Write(panel.Alpha);
writer.Write((byte)panel.MagnificationFlags);
writer.Write(panel.Name, 0x18);
writer.Write(panel.Translation.X);
writer.Write(panel.Translation.Y);
writer.Write(panel.Translation.Z);
writer.Write(panel.Rotation.X);
writer.Write(panel.Rotation.Y);
writer.Write(panel.Rotation.Z);
writer.Write(panel.Scale.X);
writer.Write(panel.Scale.Y);
writer.Write(panel.Size.Width);
writer.Write(panel.Size.Height);
}
void WriteUserData(UserData data)
{
writer.Write(data.Data);
}
void WriteTextInfo(TextSection textInfo)
{
string text = string.IsNullOrEmpty(textInfo.Text) ?
string.Empty :
textInfo.Text + "\0";
byte[] utf16Text = Encoding.Unicode.GetBytes(text);
WritePanel(textInfo);
int additionalSize = textInfo.AdditionalChars * 2; // multiplied by UTF-16 code-point size
writer.Write((ushort)(utf16Text.Length + additionalSize));
writer.Write((ushort)utf16Text.Length);
writer.Write(textInfo.MaterialIndex);
writer.Write(textInfo.FontIndex);
writer.Write(textInfo.Unknown54);
writer.Write(textInfo.Unknown55);
writer.Write((ushort)0x00); // reserved
// start text address is always 0x74 because previous fields
// have a constant size always.
writer.Write(0x74);
writer.Write(textInfo.Unknown5C[0]);
writer.Write(textInfo.Unknown5C[1]);
writer.Write(textInfo.Unknown64.X);
writer.Write(textInfo.Unknown64.Y);
writer.Write(textInfo.Unknown6C);
writer.Write(textInfo.Unknown70);
writer.Write(utf16Text);
}
void WritePictureInfo(Picture picInfo)
{
WritePanel(picInfo);
writer.Write(picInfo.TopLeftVertexColor);
writer.Write(picInfo.TopRightVertexColor);
writer.Write(picInfo.BottomLeftVertexColor);
writer.Write(picInfo.BottomRightVertexColor);
writer.Write((ushort)picInfo.MaterialIndex);
int count = picInfo.TopLeftVertexCoords.Length;
writer.Write((ushort)count);
for (int i = 0; i < count; i++) {
writer.Write(picInfo.TopLeftVertexCoords[i].X);
writer.Write(picInfo.TopLeftVertexCoords[i].Y);
writer.Write(picInfo.TopRightVertexCoords[i].X);
writer.Write(picInfo.TopRightVertexCoords[i].Y);
writer.Write(picInfo.BottomLeftVertexCoords[i].X);
writer.Write(picInfo.BottomLeftVertexCoords[i].Y);
writer.Write(picInfo.BottomRightVertexCoords[i].X);
writer.Write(picInfo.BottomRightVertexCoords[i].Y);
}
}
void WriteWindow(Window window)
{
WritePanel(window);
writer.Write(window.Unknown);
}
void WriteBoundary(Boundary boundary)
{
WritePanel(boundary);
}
}
}
|
using Hayalpc.Fatura.Data.Models;
using Hayalpc.Library.Repository;
using Hayalpc.Library.Repository.Interfaces;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
namespace Hayalpc.Fatura.Data
{
public class Repository<Tentity> : HpRepository<Tentity, HpDbContext>, IRepository<Tentity>
where Tentity : class, IHpModel
{
public Repository(HpDbContext context) : base(context)
{
}
public TOEntity ExecSqlFirst<TOEntity>(string sql) where TOEntity : class, IHpModel
{
return context.Set<TOEntity>().FromSqlRaw(sql).FirstOrDefault();
}
public List<Tentity> ExecSql(string sql)
{
return context.Set<Tentity>().FromSqlRaw(sql).ToList();
}
public List<TQuery> ExecSqlQuery<TQuery>(string sql, params object[] parameters) where TQuery : class
{
return context.Set<TQuery>().FromSqlRaw(sql, parameters).ToList();
}
}
}
|
// -----------------------------------------------------------------------
// <copyright file="StringTypes.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 System;
using System.Globalization;
using System.Runtime.CompilerServices;
using Mlos.Core;
using Mlos.Core.Collections;
using MlosStdTypes = global::Mlos.SettingsSystem.StdTypes;
namespace Proxy.Mlos.SettingsSystem.StdTypes
{
/// <summary>
/// Codegen proxy for StringPtr.
/// </summary>
public struct StringPtr : ICodegenProxy<MlosStdTypes.StringPtr, StringPtr>, IEquatable<StringPtr>, IEquatable<MlosStdTypes.StringPtr>
{
/// <summary>
/// Operator ==.
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static bool operator ==(StringPtr left, StringPtr right) => left.Equals(right);
/// <summary>
/// Operator !=.
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static bool operator !=(StringPtr left, StringPtr right) => !(left == right);
/// <summary>
/// Operator ==.
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static bool operator ==(StringPtr left, MlosStdTypes.StringPtr right) => left.Equals(right);
/// <summary>
/// Operator !=.
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static bool operator !=(StringPtr left, MlosStdTypes.StringPtr right) => !(left == right);
/// <summary>
/// Gets value stored in the buffer as a string.
/// </summary>
public string Value
{
get
{
unsafe
{
ulong offset = *(ulong*)Buffer;
ulong dataSize = *(ulong*)(Buffer + sizeof(ulong));
if (dataSize == 0)
{
return null;
}
sbyte* dataPtr = (sbyte*)(Buffer + (int)offset);
return new string(dataPtr, startIndex: 0, length: ((int)dataSize / sizeof(sbyte)) - 1);
}
}
}
/// <inheritdoc />
public override bool Equals(object obj)
{
if (obj is StringPtr stringPtr)
{
return Equals(stringPtr);
}
else if (obj is MlosStdTypes.StringPtr stdStringPtr)
{
return Equals(stdStringPtr);
}
return false;
}
/// <inheritdoc />
public bool Equals(StringPtr other) => Buffer == other.Buffer;
/// <inheritdoc />
public bool Equals(MlosStdTypes.StringPtr other) => string.Compare(Value, other.Value, ignoreCase: false, culture: CultureInfo.InvariantCulture) == 0;
/// <inheritdoc />
public override int GetHashCode() => Buffer.GetHashCode();
/// <inheritdoc />
uint ICodegenKey.CodegenTypeIndex() => throw new NotImplementedException();
/// <inheritdoc />
ulong ICodegenKey.CodegenTypeHash() => throw new NotImplementedException();
/// <inheritdoc />
public ulong CodegenTypeSize() => 16;
/// <inheritdoc />
public uint GetKeyHashValue<THash>()
where THash : IHash<uint> => default(THash).GetHashValue(Buffer);
/// <inheritdoc />
public bool CompareKey(ICodegenProxy proxy) => this == (StringPtr)proxy;
/// <inheritdoc/>
bool ICodegenProxy.VerifyVariableData(ulong objectOffset, ulong totalDataSize, ref ulong expectedDataOffset)
{
unsafe
{
ulong dataSize = *(ulong*)(Buffer + sizeof(ulong));
if (dataSize > totalDataSize)
{
return false;
}
ulong offset = *(ulong*)Buffer;
offset += objectOffset;
if (expectedDataOffset != offset)
{
return false;
}
expectedDataOffset += dataSize;
return true;
}
}
/// <inheritdoc />
public IntPtr Buffer { get; set; }
}
/// <summary>
/// Codegen proxy for WideStringPtr.
/// </summary>
public struct WideStringPtr : ICodegenProxy<MlosStdTypes.WideStringPtr, WideStringPtr>, IEquatable<WideStringPtr>, IEquatable<MlosStdTypes.WideStringPtr>
{
/// <summary>
/// Operator ==.
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static bool operator ==(WideStringPtr left, WideStringPtr right) => left.Equals(right);
/// <summary>
/// Operator !=.
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static bool operator !=(WideStringPtr left, WideStringPtr right) => !(left == right);
/// <summary>
/// Operator ==.
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static bool operator ==(WideStringPtr left, MlosStdTypes.WideStringPtr right) => left.Equals(right);
/// <summary>
/// Operator !=.
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static bool operator !=(WideStringPtr left, MlosStdTypes.WideStringPtr right) => !(left == right);
/// <summary>
/// Gets a string stored in the buffer.
/// </summary>
public string Value
{
get
{
unsafe
{
ulong offset = *(ulong*)Buffer;
ulong dataSize = *(ulong*)(Buffer + sizeof(ulong));
if (dataSize == 0)
{
return null;
}
char* dataPtr = (char*)(Buffer + (int)offset);
return new string(dataPtr, startIndex: 0, length: ((int)dataSize / sizeof(char)) - 1);
}
}
}
/// <inheritdoc />
public override bool Equals(object obj)
{
if (obj is WideStringPtr wideStringPtr)
{
return Equals(wideStringPtr);
}
else if (obj is MlosStdTypes.WideStringPtr stdWideStringPtr)
{
return Equals(stdWideStringPtr);
}
return false;
}
/// <inheritdoc />
public bool Equals(WideStringPtr other) => Buffer == other.Buffer;
/// <inheritdoc />
public bool Equals(MlosStdTypes.WideStringPtr other) => string.Compare(Value, other.Value, ignoreCase: false, culture: CultureInfo.InvariantCulture) == 0;
/// <inheritdoc />
public override int GetHashCode() => Buffer.GetHashCode();
/// <inheritdoc />
uint ICodegenKey.CodegenTypeIndex() => throw new NotImplementedException();
/// <inheritdoc />
ulong ICodegenKey.CodegenTypeHash() => throw new NotImplementedException();
/// <inheritdoc />
public ulong CodegenTypeSize() => 16;
/// <inheritdoc />
public uint GetKeyHashValue<THash>()
where THash : IHash<uint> => default(THash).GetHashValue(Buffer);
/// <inheritdoc />
public bool CompareKey(ICodegenProxy proxy) => this == (WideStringPtr)proxy;
/// <inheritdoc/>
bool ICodegenProxy.VerifyVariableData(ulong objectOffset, ulong totalDataSize, ref ulong expectedDataOffset)
{
unsafe
{
ulong dataSize = *(ulong*)(Buffer + sizeof(ulong));
if (dataSize > totalDataSize)
{
return false;
}
ulong offset = *(ulong*)Buffer;
offset += objectOffset;
if (expectedDataOffset != offset)
{
return false;
}
expectedDataOffset += dataSize;
return true;
}
}
/// <inheritdoc />
public IntPtr Buffer { get; set; }
}
/// <summary>
/// Codegen proxy for std::string_view.
/// </summary>
public struct StringView : ICodegenProxy<MlosStdTypes.StringView, StringView>, IEquatable<StringView>, IEquatable<MlosStdTypes.StringView>
{
/// <summary>
/// Operator ==.
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static bool operator ==(StringView left, StringView right) => left.Equals(right);
/// <summary>
/// Operator !=.
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static bool operator !=(StringView left, StringView right) => !(left == right);
/// <summary>
/// Operator ==.
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static bool operator ==(StringView left, MlosStdTypes.StringView right) => left.Equals(right);
/// <summary>
/// Operator !=.
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static bool operator !=(StringView left, MlosStdTypes.StringView right) => !(left == right);
/// <summary>
/// Gets a string stored in the buffer.
/// </summary>
public string Value
{
get
{
unsafe
{
ulong offset = *(ulong*)Buffer;
ulong dataSize = *(ulong*)(Buffer + sizeof(ulong));
if (dataSize == 0)
{
return null;
}
sbyte* dataPtr = (sbyte*)(Buffer + (int)offset);
return new string(dataPtr, startIndex: 0, length: (int)dataSize / sizeof(sbyte));
}
}
}
/// <inheritdoc />
public override bool Equals(object obj)
{
if (obj is StringView stringView)
{
return Equals(stringView);
}
else if (obj is MlosStdTypes.StringView stdStringView)
{
return Equals(stdStringView);
}
return false;
}
/// <inheritdoc />
public bool Equals(StringView other) => Buffer == other.Buffer;
/// <inheritdoc />
public bool Equals(MlosStdTypes.StringView other) => string.Compare(Value, other.Value, ignoreCase: false, culture: CultureInfo.InvariantCulture) == 0;
/// <inheritdoc />
public override int GetHashCode() => Buffer.GetHashCode();
/// <inheritdoc />
uint ICodegenKey.CodegenTypeIndex() => throw new NotImplementedException();
/// <inheritdoc />
ulong ICodegenKey.CodegenTypeHash() => throw new NotImplementedException();
/// <inheritdoc />
public ulong CodegenTypeSize() => 16;
/// <inheritdoc />
public uint GetKeyHashValue<THash>()
where THash : IHash<uint> => default(THash).GetHashValue(Buffer);
/// <inheritdoc />
public bool CompareKey(ICodegenProxy proxy) => this == (StringView)proxy;
/// <inheritdoc/>
bool ICodegenProxy.VerifyVariableData(ulong objectOffset, ulong totalDataSize, ref ulong expectedDataOffset)
{
unsafe
{
ulong dataSize = *(ulong*)(Buffer + sizeof(ulong));
if (dataSize > totalDataSize)
{
return false;
}
ulong offset = *(ulong*)Buffer;
offset += objectOffset;
if (expectedDataOffset != offset)
{
return false;
}
expectedDataOffset += dataSize;
return true;
}
}
/// <inheritdoc />
public IntPtr Buffer { get; set; }
}
/// <summary>
/// Codegen proxy for std::wstring_view.
/// </summary>
public struct WideStringView : ICodegenProxy<MlosStdTypes.WideStringView, WideStringView>, IEquatable<WideStringView>, IEquatable<MlosStdTypes.WideStringView>
{
/// <summary>
/// Operator ==.
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static bool operator ==(WideStringView left, WideStringView right) => left.Equals(right);
/// <summary>
/// Operator !=.
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static bool operator !=(WideStringView left, WideStringView right) => !(left == right);
/// <summary>
/// Operator ==.
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static bool operator ==(WideStringView left, MlosStdTypes.WideStringView right) => left.Equals(right);
/// <summary>
/// Operator !=.
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static bool operator !=(WideStringView left, MlosStdTypes.WideStringView right) => !(left == right);
/// <summary>
/// Gets a string stored in the buffer.
/// </summary>
public string Value
{
get
{
unsafe
{
ulong offset = *(ulong*)Buffer;
ulong dataSize = *(ulong*)(Buffer + sizeof(ulong));
if (dataSize == 0)
{
return null;
}
char* dataPtr = (char*)(Buffer + (int)offset);
return new string(dataPtr, startIndex: 0, length: (int)dataSize / sizeof(char));
}
}
}
/// <summary>
/// Gets a string stored in the buffer as read only span.
/// </summary>
/// <returns></returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlySpan<char> ValueAsSpan()
{
unsafe
{
ulong offset = *(ulong*)Buffer;
ulong size = *(ulong*)(Buffer + sizeof(ulong));
char* dataPtr = (char*)(Buffer + (int)offset);
ReadOnlySpan<char> valueSpan = new ReadOnlySpan<char>(dataPtr, length: (int)size / sizeof(char));
return valueSpan;
}
}
/// <inheritdoc />
public override bool Equals(object obj)
{
if (obj is WideStringView wideStringView)
{
return Equals(wideStringView);
}
else if (obj is MlosStdTypes.WideStringView stdWideStringView)
{
return Equals(stdWideStringView);
}
return false;
}
/// <inheritdoc />
public bool Equals(WideStringView other) => Buffer == other.Buffer;
/// <inheritdoc />
public bool Equals(MlosStdTypes.WideStringView other) => string.Compare(Value, other.Value, ignoreCase: false, culture: CultureInfo.InvariantCulture) == 0;
/// <inheritdoc />
public override int GetHashCode() => Buffer.GetHashCode();
/// <inheritdoc />
uint ICodegenKey.CodegenTypeIndex() => throw new NotImplementedException();
/// <inheritdoc />
ulong ICodegenKey.CodegenTypeHash() => throw new NotImplementedException();
/// <inheritdoc />
public ulong CodegenTypeSize() => 16;
/// <inheritdoc />
public uint GetKeyHashValue<THash>()
where THash : IHash<uint> => default(THash).GetHashValue(Buffer);
/// <inheritdoc />
public bool CompareKey(ICodegenProxy proxy) => this == (WideStringView)proxy;
/// <inheritdoc/>
bool ICodegenProxy.VerifyVariableData(ulong objectOffset, ulong totalDataSize, ref ulong expectedDataOffset)
{
unsafe
{
ulong dataSize = *(ulong*)(Buffer + sizeof(ulong));
if (dataSize > totalDataSize)
{
return false;
}
ulong offset = *(ulong*)Buffer;
offset += objectOffset;
if (expectedDataOffset != offset)
{
return false;
}
expectedDataOffset += dataSize;
return true;
}
}
/// <inheritdoc />
public IntPtr Buffer { get; set; }
}
}
|
using UnityEngine;
using UnityEngine.AI;
using BehaviorDesigner.Runtime;
public class MovJugadorMesh : MonoBehaviour
{
// Notificacion pulsar F
[SerializeField]
private GameObject texto;
// Christine
[SerializeField]
private Christine christine;
private NavMeshAgent navMeshAgent;
private Rigidbody rb;
private Vector3 vel;
// Booleano para saber si esta usando la barca
private bool usingBoat = false;
// Booleanos para el control de la situaci�n de Christine
private bool animable = false;
private bool llevando = false;
private bool al_alcance = false;
void Awake() {
navMeshAgent = GetComponent<NavMeshAgent>();
rb = GetComponent<Rigidbody>();
}
// Movimiento de Raoul
void Update() {
// Animar y liberar Christine
if (animable && Input.GetKeyDown(KeyCode.F))
{
christine.SetGrabbed(false);
christine.SetLlevando(false);
}
if (al_alcance && llevando) {
christine.SetLlevando(false);
christine.SetGrabbed(false);
}
// Para que pueda viajar por links hay que capar las direcciones manualmente
// Puente OESTE
if (transform.position.x > -20 && transform.position.x < -18 && transform.position.z > 24 && transform.position.z < 51) {
// Si estas abajo
if (!usingBoat && transform.position.z > 24 && transform.position.z < 26) {
navMeshAgent.destination = new Vector3 (-19, transform.position.y, 53);
usingBoat = true;
}
// Si estas arriba
if (!usingBoat && transform.position.z > 49 && transform.position.z < 51) {
navMeshAgent.destination = new Vector3 (-19, transform.position.y, 22);
usingBoat = true;
}
}
// Puente CENTRAL
else if (transform.position.x > 12 && transform.position.x < 14 && transform.position.z > 24 && transform.position.z < 42) {
// Si estas abajo
if (!usingBoat && transform.position.z > 24 && transform.position.z < 26) {
navMeshAgent.destination = new Vector3 (11, transform.position.y, 44);
usingBoat = true;
}
// Si estas arriba
if (!usingBoat && transform.position.z > 40 && transform.position.z < 42) {
navMeshAgent.destination = new Vector3 (11, transform.position.y, 22);
usingBoat = true;
}
}
// Puente ESTE
else if (transform.position.x > 21 && transform.position.x < 23 && transform.position.z > 24 && transform.position.z < 51) {
// Si estas abajo
if (!usingBoat && transform.position.z > 24 && transform.position.z < 26) {
navMeshAgent.destination = new Vector3 (22, transform.position.y, 53);
usingBoat = true;
}
// Si estas arriba
if (!usingBoat && transform.position.z > 49 && transform.position.z < 51) {
navMeshAgent.destination = new Vector3 (22, transform.position.y, 22);
usingBoat = true;
}
}
// Trampilla
else if (!usingBoat && transform.position.x > -10 && transform.position.x < -7.5 && transform.position.z > 14.5 && transform.position.z < 16.5) {
navMeshAgent.destination = new Vector3 (-12.5f, -5, 15.5f);
usingBoat = true;
}
// Rampa
else if (!usingBoat && transform.position.x > 9 && transform.position.x < 10 && transform.position.z > 22 && transform.position.z < 23) {
navMeshAgent.destination = new Vector3 (15, -5, 22.5f);
usingBoat = true;
}
// Pero si no, dejar que se mueva libremente por el mapa
else {
// El barco no se esta usando
usingBoat = false;
// Coger el input de los cursores
vel.x = Input.GetAxis("Horizontal");
vel.z = Input.GetAxis("Vertical");
// "Normalizar" manualmente la velocidad
if (vel.x > 0) vel.x = 1f;
if (vel.x < 0) vel.x = -1f;
if (vel.z > 0) vel.z = 1f;
if (vel.z < 0) vel.z = -1f;
// Destino al que queremos ir
navMeshAgent.destination = transform.position + vel;
}
}
// Mirar hacia donde estas yendo
private void LateUpdate() {
transform.LookAt(transform.position + vel);
}
void OnTriggerEnter(Collider other) {
if (other.CompareTag("Christine")) {
var grabbed_ = GlobalVariables.Instance.GetVariable("Grabbed_global");
if ((bool)grabbed_.GetValue()) {
animable = true;
texto.SetActive(true);
}
}
else if (other.CompareTag("Enemy")) {
var llevando_ = GlobalVariables.Instance.GetVariable("llevando");
llevando = (bool)llevando_.GetValue();
if (llevando) {
al_alcance = true;
}
}
}
void OnTriggerExit (Collider other) {
if (other.CompareTag("Christine")) {
animable = false;
texto.SetActive(false);
}
/* if (llevando && other.CompareTag("Christine"))
{
texto.SetActive(false);
}*/
else if (other.CompareTag("Enemy") && llevando){
texto.SetActive(false);
al_alcance = false;
}
}
} |
using System;
using System.IO.Pipelines;
using System.Reactive.Concurrency;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
namespace OmniSharp.Extensions.JsonRpc
{
public class Connection : IDisposable
{
private readonly InputHandler _inputHandler;
public bool IsOpen { get; private set; }
[Obsolete("Use the other constructor that takes a request invoker")]
public Connection(
PipeReader input,
IOutputHandler outputHandler,
IReceiver receiver,
IRequestProcessIdentifier requestProcessIdentifier,
IRequestRouter<IHandlerDescriptor?> requestRouter,
IResponseRouter responseRouter,
ILoggerFactory loggerFactory,
OnUnhandledExceptionHandler onUnhandledException,
TimeSpan requestTimeout,
bool supportContentModified,
int concurrency,
IScheduler scheduler,
CreateResponseExceptionHandler? getException = null
) : this(
input,
outputHandler,
receiver,
requestRouter,
responseRouter,
new DefaultRequestInvoker(
requestRouter,
outputHandler,
requestProcessIdentifier,
new RequestInvokerOptions(
requestTimeout,
supportContentModified,
concurrency),
loggerFactory,
scheduler),
loggerFactory,
onUnhandledException,
getException)
{
}
public Connection(
PipeReader input,
IOutputHandler outputHandler,
IReceiver receiver,
IRequestRouter<IHandlerDescriptor?> requestRouter,
IResponseRouter responseRouter,
RequestInvoker requestInvoker,
ILoggerFactory loggerFactory,
OnUnhandledExceptionHandler onUnhandledException,
CreateResponseExceptionHandler? getException = null
) =>
_inputHandler = new InputHandler(
input,
outputHandler,
receiver,
requestRouter,
responseRouter,
requestInvoker,
loggerFactory,
onUnhandledException,
getException
);
public void Open()
{
// TODO: Throw if called twice?
_inputHandler.Start();
IsOpen = true;
}
public Task StopAsync() => _inputHandler.StopAsync();
public void Dispose()
{
_inputHandler.Dispose();
IsOpen = false;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
using System.Windows.Forms;
namespace Clipboard_And_Snippet_Manager
{
class TreeNodeExImageItem : TreeNode
{
public Image clipboardImage { get; set; }
public TreeNodeExImageItem(Image img, ContextMenuStrip contextMenuStrip , int imageIndex)
{
this.ImageIndex = imageIndex;
this.SelectedImageIndex = imageIndex;
this.ContextMenuStrip = contextMenuStrip;
this.clipboardImage = img;
this.Text = "image";
}
}
}
|
using System;
namespace ArrayOfNumbers.Two_Demensional_array
{
public static class TD_Array
{
/// <summary>
/// Two-demensional array.
/// </summary>
private static int[,] td_array;
/// <summary>
/// A row of the array.
/// </summary>
private static int row;
/// <summary>
/// User's row.
/// </summary>
private static int selectedRow;
/// <summary>
/// User's column.
/// </summary>
private static int selectedColumn;
/// <summary>
/// A column of the array
/// </summary>
private static int column;
/// <summary>
/// The method allows to enter the size of the two-demensional array.
/// </summary>
public static void EnterSizeTDArray()
{
bool isCorrect = true;
bool isCorrect_row = true;
bool isCorrect_column = true;
while (isCorrect)
{
Console.WriteLine("Enter size of array.");
while (isCorrect_row)
{
Console.Write("count of rows - ");
if (isCorrect_row = !Int32.TryParse(Console.ReadLine(), out row))
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Wrong format! Use integer numbers. Try again.\n");
Console.ResetColor();
}
else if (row < 0)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Wrong format! The lengt cannot be negative. Try again.\n");
Console.ResetColor();
isCorrect_row = true;
}
}
while (isCorrect_column)
{
Console.Write("count of columns - ");
if (isCorrect_column = !Int32.TryParse(Console.ReadLine(), out column))
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Wrong format! Use integer numbers. Try again.\n");
Console.ResetColor();
}
else if (column < 0)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Wrong format! The lengt cannot be negative. Try again.\n");
Console.ResetColor();
isCorrect_column = true;
}
}
if (isCorrect)
{
td_array = new int[row, column];
isCorrect = false;
}
}
Console.WriteLine();
}
/// <summary>
/// The method allows to fill the array random numbers in range 0..99.
/// </summary>
public static void RandomNumbersOfTDArray()
{
Random rnd = new Random();
for (int i = 0; i < row; i++)
{
for (int j = 0; j < column; j++)
{
td_array[i, j] = rnd.Next(-100, 100);
}
}
}
/// <summary>
/// The method allows to enter manually values of elements in the array.
/// </summary>
public static void EnterNumbersOfTDArrayManually()
{
bool isCorrect = true; // flag for "while"
while (isCorrect)
{
Console.WriteLine("Enter values of the elemetnts in the array: ");
for (int i = 0; i < row; i++)
{
for (int j = 0; j < column; j++)
{
bool flag = true; //flag for "while"
while (flag)
{
Console.Write($"[{i},{j}] - ");
if (isCorrect = !Int32.TryParse(Console.ReadLine(), out int num))
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Wrong format! Try again.");
Console.ResetColor();
}
else
{
td_array[i, j] = num;
flag = false;
}
}
}
}
Console.WriteLine();
}
}
/// <summary>
/// The method sorts the array's rows by ascending.
/// </summary>
/// <param name="row">User's row</param>
public static void SortAscendingRow()
{
bool flag = true;
while (flag)
{
Console.WriteLine("Choose a row");
bool isCorrect = Int32.TryParse(Console.ReadLine(), out selectedRow);
if (!isCorrect || (selectedRow >= td_array.GetLength(0) || selectedRow < 0))
{
Console.WriteLine("Wrong format. Try again.");
flag = true;
}
else
{
int[] tempArray = new int[td_array.GetLength(0)]; // temporary one-demnsional array
for (int i = 0; i < tempArray.Length; i++)
{
tempArray[i] = td_array[selectedRow, i];
}
for (int i = 0; i < tempArray.Length - 1; i++) //sort by ascending
{
for (int j = i; j < tempArray.Length; j++)
{
if (tempArray[i] > tempArray[j])
{
int temp = tempArray[i];
tempArray[i] = tempArray[j];
tempArray[j] = temp;
}
}
}
for (int i = 0; i < tempArray.Length; i++) //import row in the two-demensional array
{
td_array[selectedRow, i] = tempArray[i];
}
flag = false;
}
}
Console.WriteLine();
}
/// <summary>
/// The method sorts the array's row by descending.
/// </summary>
/// <param name="row">User's row</param>
public static void SortDescendingRow()
{
bool flag = true;
while (flag)
{
Console.WriteLine("Choose a row");
bool isCorrect = Int32.TryParse(Console.ReadLine(), out selectedRow);
if (!isCorrect || (selectedRow >= td_array.GetLength(0) || selectedRow < 0))
{
Console.WriteLine("Wrong format. Try again.");
flag = true;
}
else
{
int[] tempArray = new int[td_array.GetLength(0)]; // temporary one-demnsional array
for (int i = 0; i < tempArray.Length; i++)
{
tempArray[i] = td_array[selectedRow, i];
}
for (int i = 0; i < tempArray.Length - 1; i++) //sort by descending
{
for (int j = i; j < tempArray.Length; j++)
{
if (tempArray[i] < tempArray[j])
{
int temp = tempArray[i];
tempArray[i] = tempArray[j];
tempArray[j] = temp;
}
}
}
for (int i = 0; i < tempArray.Length; i++) //import row in the two-demensional array
{
td_array[selectedRow, i] = tempArray[i];
}
flag = false;
}
}
Console.WriteLine();
}
/// <summary>
/// The method sorts the array's column by ascending.
/// </summary>
/// <param name="column"></param>
public static void SortAscendingColumn()
{
bool flag = true;
while (flag)
{
Console.WriteLine("Choose a column");
bool isCorrect = Int32.TryParse(Console.ReadLine(), out selectedColumn);
if (!isCorrect || (selectedColumn >= td_array.GetLength(1) || selectedColumn < 0))
{
Console.WriteLine("Wrong format. Try again.");
flag = true;
}
else
{
int[] tempArray = new int[td_array.GetLength(1)]; // temporary one-demnsional array
for (int i = 0; i < tempArray.Length; i++)
{
tempArray[i] = td_array[i, selectedColumn];
}
for (int i = 0; i < tempArray.Length - 1; i++) //sort by ascending
{
for (int j = i; j < tempArray.Length; j++)
{
if (tempArray[i] > tempArray[j])
{
int temp = tempArray[i];
tempArray[i] = tempArray[j];
tempArray[j] = temp;
}
}
}
for (int i = 0; i < tempArray.Length; i++) //import row in the two-demensional array
{
td_array[i, selectedColumn] = tempArray[i];
}
flag = false;
}
}
Console.WriteLine();
}
/// <summary>
/// The method sorts the array's column by descending
/// </summary>
/// <param name="column"></param>
public static void SortDescendingColumn()
{
bool flag = true;
while (flag)
{
Console.WriteLine("Choose a column");
bool isCorrect = Int32.TryParse(Console.ReadLine(), out selectedColumn);
if (!isCorrect || (selectedColumn >= td_array.GetLength(1) || selectedColumn < 0))
{
Console.WriteLine("Wrong format. Try again.");
flag = true;
}
else
{
int[] tempArray = new int[td_array.GetLength(1)]; // temporary one-demnsional array
for (int i = 0; i < tempArray.Length; i++)
{
tempArray[i] = td_array[i, selectedColumn];
}
for (int i = 0; i < tempArray.Length - 1; i++) //sort by ascending
{
for (int j = i; j < tempArray.Length; j++)
{
if (tempArray[i] < tempArray[j])
{
int temp = tempArray[i];
tempArray[i] = tempArray[j];
tempArray[j] = temp;
}
}
}
for (int i = 0; i < tempArray.Length; i++) //import row in the two-demensional array
{
td_array[i, selectedColumn] = tempArray[i];
}
flag = false;
}
}
Console.WriteLine();
}
public static void GetNegativeNumbers()
{
int count = 0;
for (int i = 0; i < td_array.GetLength(0); i++)
{
for (int j = 0; j < td_array.GetLength(1)-1; j++)
{
if (td_array[i, j] < 0)
count++;
}
}
Console.WriteLine($"Count of negative numbers: {count}\n");
}
/// <summary>
/// The method shows array
/// </summary>
public static void Show()
{
for (int i = 0; i < row; i++)
{
Console.WriteLine();
for (int j = 0; j < column; j++)
{
Console.Write($"{td_array[i, j]}\t");
}
}
Console.WriteLine();
}
/// <summary>
/// The method shows row of the array sorted by asecending.
/// </summary>
/// <param name="selectedRow">User's row</param>
public static void ShowSortedRow()
{
for (int i = 0; i < row; i++)
{
Console.WriteLine();
for (int j = 0; j < column; j++)
{
if (!(i == selectedRow))
{
Console.Write($"{td_array[i, j]}\t");
}
else
{
Console.ForegroundColor = ConsoleColor.Green;
Console.Write($"{td_array[i, j]}\t");
Console.ResetColor();
}
}
}
Console.WriteLine();
}
/// <summary>
/// The method shows column of the arra sorted by ascending.
/// </summary>
/// <param name="selectedColumn">User's column</param>
public static void ShowSortedColumn()
{
for (int i = 0; i < row; i++)
{
Console.WriteLine();
for (int j = 0; j < column; j++)
{
if (!(j == selectedColumn))
{
Console.Write($"{td_array[i, j]}\t");
}
else
{
Console.ForegroundColor = ConsoleColor.Green;
Console.Write($"{td_array[i, j]}\t");
Console.ResetColor();
}
}
}
Console.WriteLine();
}
}
}
|
using Azure.Storage.Blobs;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace PeliculasAPI.Utilidades
{
public class AlmacenadorAzureStorage : IAlmacenadorArchivos
{
private readonly string connectionString;
public AlmacenadorAzureStorage(IConfiguration configuration)
{
connectionString = configuration.GetConnectionString("AzureStorage");
}
private async Task<BlobContainerClient> GetClient(string container)
{
// Conectando el cliente y creando el contenedor si no existe
var client = new BlobContainerClient(connectionString, container);
await client.CreateIfNotExistsAsync();
client.SetAccessPolicy(Azure.Storage.Blobs.Models.PublicAccessType.Blob);
return client;
}
public async Task<string> GuardarArchivo(string container, IFormFile file)
{
var client = await GetClient(container);
// Creando el nombre del archivo nuevo a guardar
var extension = Path.GetExtension(file.FileName);
var fileName = $"{Guid.NewGuid()}{extension}";
// Subiendo el archivo a Azure Storage
var blob = client.GetBlobClient(fileName);
await blob.UploadAsync(file.OpenReadStream());
// Retornar la URL del archivo subido
return blob.Uri.ToString();
}
public async Task BorrarArchivo(string fileRoute, string container)
{
if (string.IsNullOrEmpty(fileRoute))
{
return;
}
var client = await GetClient(container);
var fileName = Path.GetFileName(fileRoute);
var blob = client.GetBlobClient(fileName);
await blob.DeleteIfExistsAsync();
}
public async Task<string> EditarArchivo(string container, IFormFile file, string fileRoute)
{
await BorrarArchivo(fileRoute, container);
return await GuardarArchivo(container, file);
}
}
}
|
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace CryptobotUi.Models.Cryptodb
{
[Table("market_event", Schema = "public")]
public partial class MarketEvent
{
[NotMapped]
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
[JsonPropertyName("@odata.etag")]
public string ETag
{
get;
set;
}
[Key]
public Int64 id
{
get;
set;
}
[ConcurrencyCheck]
public DateTime event_time
{
get;
set;
}
[ConcurrencyCheck]
public decimal price
{
get;
set;
}
[ConcurrencyCheck]
public Int64 time_frame
{
get;
set;
}
[ConcurrencyCheck]
public decimal? contracts
{
get;
set;
}
[ConcurrencyCheck]
public Int64? exchange
{
get;
set;
}
[ConcurrencyCheck]
public string source
{
get;
set;
}
[ConcurrencyCheck]
public string name
{
get;
set;
}
[ConcurrencyCheck]
public string message
{
get;
set;
}
[ConcurrencyCheck]
public string symbol
{
get;
set;
}
[ConcurrencyCheck]
public string market
{
get;
set;
}
[ConcurrencyCheck]
public string category
{
get;
set;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Prj_PracticeMidterm.BLL;
namespace Prj_PracticeMidterm.GUI
{
public partial class WebFormProjectAssignments : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Student aStudent = new Student();
List<Student> listS = aStudent.GetStudentList();
foreach (Student s in listS)
{
DropDownStudent.Items.Add(s.StudentNum.ToString() + ", " + s.FirstName + ", " + s.LastName);
}
Project aProject = new Project();
List<Project> listP = aProject.GetProjectList();
foreach (Project p in listP)
{
DropDownProject.Items.Add(p.ProjectCode.ToString() + ", " + p.ProjectTitle);
}
}
protected void DropDownStudent_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
} |
using InternDevelopmentProject.BusinessLogic;
using InternDevelopmentProject.DataLogic;
using InternDevelopmentProject.ViewModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace InternDevelopmentProject.Controllers
{
public class BusRegistrationController : Controller
{
/// <summary>
/// The Bus action will register bus if session is valiad by calling the method SetBusDetail()
/// </summary>
/// <param name="bus"></param>
/// <returns></returns>
[HttpPost]
public ActionResult Bus(RegisterBus bus)
{
if ((ModelState.IsValid && Session["EmailID"] != null) || (!ModelState.IsValidField("TotalUpperSeatNum") && Session["EmailID"] != null))
{
var OperatorEmailID = Session["EmailID"].ToString();
var registerBus = new BusRegistrationDetail();
if (registerBus.SetBusDetail(bus, OperatorEmailID))
{
return View("BusRoute");
}
}
return RedirectToAction("MyProfile", "BlueBusServiceOperator");
}
/// <summary>
/// The BusDetail() get action return the list of registered bus based on operator id to the view GetBusList.
/// </summary>
/// <returns></returns>
public ActionResult BusDetail()
{
if (Session["EmailID"] != null)
{
var getOperatorID = new GetEntityID();
var OperatorID = getOperatorID.GetOperatorID(Session["EmailID"].ToString());
var busDetail = new DropDownList();
return View("GetBusList", busDetail.GetBusList(OperatorID).ToList());
}
return RedirectToAction("SignIn", "Operator");
}
/// <summary>
/// The action BusRoute() will return the BusRoute view.
/// </summary>
/// <returns></returns>
///
public ActionResult BusRoute(int? id)
{
if (Session["EmailID"] != null)
{
Session["BusID"] = id;
return View();
}
return RedirectToAction("SignIn", "Operator");
}
/// <summary>
/// The post BusRoute() action will return the intermediate city if the bus route data will get add in bus route table successfully.
/// </summary>
/// <param name="Route"></param>
/// <returns></returns>
[HttpPost]
public ActionResult BusRoute(BusRouteDetail Route)
{
if (Session["EmailID"] != null)
{
if (Session["BusID"] == null)
{
return RedirectToAction("MyProfile", "BlueBusServiceOperator");
}
var BusID = (int)Session["BusID"];
var busRoute = new BusRouteOperation();
if (!busRoute.SetRoute(BusID, Route))
{
ViewBag.Message = "Sorry your form can not be submitted this time.";
return View();
}
return View("IntermediateBusStopCity");
}
return RedirectToAction("SignIn", "Operator");
}
/// <summary>
/// The action IntermediateBusStopCity() will return CityBoardingPoint view if the data inserted in table successfully.
/// </summary>
/// <param name="busStop"></param>
/// <returns></returns>
[HttpPost]
public ActionResult IntermediateBusStopCity(BusStopCity BusStop)
{
if (Session["EmailID"] != null)
{
if (Session["BusID"] == null)
{
return RedirectToAction("MyProfile", "BlueBusServiceOperator");
}
var BusID = (int)Session["BusID"];
var intermediateRoute = new BusRouteOperation();
if (!intermediateRoute.SetIntermediateRoute(BusID, BusStop))
{
ViewBag.ErrorMessage = "Sorry your form can not be submitted this time";
}
return View();
}
return RedirectToAction("SignIn", "Operator");
}
/// <summary>
/// The CityBoardingPoint() action will return the CityBoardingPoint view.
/// </summary>
/// <returns></returns>
public ActionResult CityBoardingPoint()
{
if (Session["EmailID"] != null)
{
return View();
}
return RedirectToAction("SignIn", "Operator");
}
[HttpPost]
public ActionResult CityBoardingPoint(BoardingPoint board)
{
if (Session["EmailID"] != null)
{
return View();
}
return RedirectToAction("SignIn", "Operator");
}
/// <summary>
/// The GetStateList() action will return the list of state in response of json request.
/// </summary>
/// <returns></returns>
public JsonResult GetStateList()
{
if (Request.IsAjaxRequest() && Session["EmailID"] != null)
{
var stateList = new DropDownList();
return Json(stateList.GetStateList(), JsonRequestBehavior.AllowGet);
}
return null;
}
/// <summary>
/// The GetCityList() action will return the list of city based on state id as response of json request.
/// </summary>
/// <param name="StateID"></param>
/// <returns></returns>
public JsonResult GetCityList(int StateID)
{
if (Request.IsAjaxRequest() && Session["EmailID"] != null)
{
var cityList = new DropDownList();
return Json(cityList.GetCityList(StateID), JsonRequestBehavior.AllowGet);
}
return null;
}
}
} |
using System;
using System.Globalization;
using System.Web;
namespace Web.Services
{
public static class TimeDateServices
{
public static double GetUtcOffSet()
{
var iUtcOffSet = -480;
if (HttpContext.Current.Request.Cookies["_timeZoneOffset"] != null)
iUtcOffSet = Convert.ToInt32(HttpContext.Current.Request.Cookies["_timeZoneOffset"].Value);
return iUtcOffSet;
}
private static int DaylightAdjustment()
{
int daylightAdjustment = 0;
var year = DateTime.Now.Year.ToString(CultureInfo.InvariantCulture);
var strStartWinter = year + "-8-10";
var strStartSummer = year + "-4-15";
DateTime startWinter;
DateTime startSummer;
CultureInfo provider = CultureInfo.InvariantCulture;
try
{
startWinter = DateTime.Parse(strStartWinter, provider);
startSummer = DateTime.Parse(strStartSummer, provider);
}
catch
{
//const string e = "DateString is not in the correct format.";
//LogError(ex, e);
return 0;
}
if (DateTime.Now > startSummer && DateTime.Now < startWinter)
daylightAdjustment = -60;
return daylightAdjustment;
}
public static string ConvertSecondsToMinutes(int seconds)
{
int remainder; int result = Math.DivRem(seconds, 60, out remainder);
var sSeconds = remainder.ToString(CultureInfo.InvariantCulture);
switch (sSeconds.Length)
{
case 0:
sSeconds = "00";
break;
case 1:
sSeconds = "0" + sSeconds;
break;
}
string sDuration = result + ":" + sSeconds;
return sDuration;
}
}
} |
using Caliburn.Light;
namespace Demo.HelloSpecialValues
{
public class CharacterViewModel : BindableObject
{
public CharacterViewModel(string name, string image)
{
Name = name;
Image = image;
}
public string Name { get; }
public string Image { get; }
}
}
|
using Microsoft.Extensions.Configuration;
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.Bot.Connector.DirectLine;
using WebSocketSharp;
using Newtonsoft.Json;
using System.Linq;
using System.Diagnostics;
using Activity = Microsoft.Bot.Connector.DirectLine.Activity;
namespace DirectLineSampleClient
{
class Program
{
private static string directLineSecret;
private static string botId;
private static string fromUser;
static Task Main(string[] args)
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
var configuration = builder.Build();
directLineSecret = configuration.GetSection("DirectLineSecret")?.Value;
botId = configuration.GetSection("BotId")?.Value;
fromUser = configuration.GetSection("User")?.Value;
return StartBotConversationAsync();
}
private static async Task StartBotConversationAsync()
{
// Obtain a token using the Direct Line secret
var tokenResponse = await new DirectLineClient(directLineSecret).Tokens.GenerateTokenForNewConversationAsync();
// Use token to create conversation
var directLineClient = new DirectLineClient(tokenResponse.Token);
var conversation = await directLineClient.Conversations.StartConversationAsync();
Console.Write("\nCommand> ");
using (var webSocketClient = new WebSocket(conversation.StreamUrl))
{
webSocketClient.OnMessage += WebSocketClient_OnMessage;
webSocketClient.Connect();
while (true)
{
var input = Console.ReadLine().Trim();
if (input.ToLower() == "exit")
{
break;
}
else
{
if (input.Length > 0)
{
var userMessage = new Activity
{
From = new ChannelAccount(fromUser),
Text = input,
Type = ActivityTypes.Message
};
await directLineClient.Conversations.PostActivityAsync(conversation.ConversationId, userMessage);
}
}
}
}
}
private static void WebSocketClient_OnMessage(object sender, MessageEventArgs e)
{
// Occasionally, the Direct Line service sends an empty message as a liveness ping. Ignore these messages.
if (string.IsNullOrWhiteSpace(e.Data))
{
return;
}
var activitySet = JsonConvert.DeserializeObject<ActivitySet>(e.Data);
var activities = from x in activitySet.Activities
where x.From.Id == botId
select x;
foreach (var activity in activities)
{
Console.WriteLine(activity.Text);
if (activity.Attachments != null)
{
foreach (var attachment in activity.Attachments)
{
switch (attachment.ContentType)
{
case "application/vnd.microsoft.card.hero":
RenderHeroCard(attachment);
break;
case "image/png":
Console.WriteLine($"Opening the requested image '{attachment.ContentUrl}'");
Process.Start(attachment.ContentUrl);
break;
}
}
}
Console.Write("\nCommand> ");
}
}
private static void RenderHeroCard(Attachment attachment)
{
const int Width = 70;
Func<string, string> contentLine = (content) => string.Format($"{{0, -{Width}}}", string.Format("{0," + ((Width + content.Length) / 2).ToString() + "}", content));
var heroCard = JsonConvert.DeserializeObject<HeroCard>(attachment.Content.ToString());
if (heroCard != null)
{
Console.WriteLine("/{0}", new string('*', Width + 1));
Console.WriteLine("*{0}*", contentLine(heroCard.Title));
Console.WriteLine("*{0}*", new string(' ', Width));
Console.WriteLine("*{0}*", contentLine(heroCard.Text));
Console.WriteLine("{0}/", new string('*', Width + 1));
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
public class OrdenMalo : NetworkBehaviour {
public Animator animator;
public bool preview;
public GameObject circulo;
public GameObject objeto;
public GameObject cursor;
bool pos;
Vector3 lugar;
public GameObject Hero;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update ()
{
if(isServer)
{
return;
}
if(objeto == null)
{
objeto = GameObject.Find("Piso");
}
if(Hero == null)
{
Hero = GameObject.Find("Hero");
}
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if(preview)
{
circulo.SetActive(true);
if(objeto.GetComponent<Collider>().Raycast (ray, out hit, Mathf.Infinity))
{
cursor.SetActive(true);
cursor.transform.position = new Vector3(hit.point.x,hit.point.y+1,hit.point.z);//hit.point;
lugar = hit.point;
}
pos = true;
}else
{
circulo.SetActive(false);
cursor.SetActive(false);
pos = false;
}
if(Input.GetMouseButtonDown(1))
{
if(pos)
{
Hero.GetComponent<HeroNetwork>().muneco = gameObject;
Hero.GetComponent<HeroNetwork>().ordenLugar = lugar;
Hero.GetComponent<HeroNetwork>().orden = true;
preview = false;
}else if(Physics.Raycast(ray, out hit))
{
if(hit.collider == gameObject.GetComponent<Collider>())
{
preview = true;
Hero.GetComponent<HeroNetwork>().muneco = null;
Hero.GetComponent<HeroNetwork>().orden = false;
}
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FileManager.DataAccess.Data
{
public class FactoryProvider
{
public static IAbstractFactory getFactory(PersitenseTypes PersistenceTypes)
{
switch (PersistenceTypes)
{
case PersitenseTypes.FILE:
return new FileFactory();
default : return null;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace WebApplication1.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
public JsonResult returnJson(string name,string value)
{
bool isAdmin = false;
//TODO: Check the user if it is admin or normal user, (true-Admin, false- Normal user)
string output = isAdmin ? "Welcome to the Admin User" : "Welcome to the User";
return Json(output, JsonRequestBehavior.AllowGet);
}
}
} |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using WebsiteBanHang.Helpers;
using WebsiteBanHang.Models;
namespace WebsiteBanHang.Controllers
{
[Route("api/[controller]")]
[ApiController]
[Authorize(Roles = "member,admin,employee")]
public class UploadController : ControllerBase
{
private readonly IHostingEnvironment _environment;
public UploadController(IHostingEnvironment environment)
{
_environment = environment;
}
[HttpPost]
public async Task<IActionResult> Post(List<IFormFile> files)
{
var imageList = await Files.UploadAsync(files, _environment.ContentRootPath);
return Ok(new { url = imageList[0] });
}
}
}
|
using System.Collections.Generic;
using Athena.Data.Books;
namespace Athena.Data.Categories {
public class Category {
public CategoryName Name { get; set; }
public ICollection<Book> Books { get; set; }
}
} |
using MVCApplication.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MVCApplication.Data
{
interface IRepository
{
IEnumerable<Project> GetProjects();
IEnumerable<Entry> GetEntries();
void CreateEntries(IEnumerable<Entry> entries);
void CreateProjects(IEnumerable<Project> projects);
void CreateClients(IEnumerable<Client> clients);
void CreateUsers(IEnumerable<User> users);
}
}
|
using System;
using System.Threading.Tasks;
using System.Linq;
using Acr.UserDialogs;
using MvvmCross.Core.ViewModels;
using MvvmCross.Platform;
using MvvmCross.Platform.Platform;
using VictimApplication.Core.Models;
using VictimApplication.Core.Services;
namespace VictimApplication.Core.ViewModels
{
public class RegisterViewModel : MvxViewModel
{
private readonly IApi _api;
private readonly IMvxJsonConverter _jsonConverter;
private readonly IUserDialogs _userDialogs;
public RegisterViewModel(IApi api, IMvxJsonConverter jsonConverter, IUserDialogs userDialogs)
{
_api = api;
_jsonConverter = jsonConverter;
_userDialogs = userDialogs;
}
private string _login = "";
public string Login
{
get => _login;
set { SetProperty(ref _login, value); }
}
private string _password = "";
public string Password
{
get => _password;
set { SetProperty(ref _password, value); }
}
private string _firstname = "";
public string Firstname
{
get => _firstname;
set { SetProperty(ref _firstname, value); }
}
private string _surname = "";
public string Surname
{
get => _surname;
set { SetProperty(ref _surname, value); }
}
private string _email = "";
public string Email
{
get => _email;
set { SetProperty(ref _email, value); }
}
public IMvxCommand RegisterCommand => new MvxAsyncCommand(Register);
public IMvxCommand BackCommand => new MvxCommand(BackToLogin);
private void BackToLogin()
{
ShowViewModel<MenuViewModel>();
}
async Task Register()
{
if (CheckFields())
{
var UserForCreation = new UserForCreationDto
{
UserName = Login,
Password = this.Password,
FirstName = this.Firstname,
SecondName = this.Surname,
Email = this.Email
};
try
{
await _api.CreateUser(UserForCreation);
Close(this);
_userDialogs.Alert("Succesfully Registered! Now you can login to your account.");
}
catch (Exception ex)
{
Close(this);
_userDialogs.Alert("Registration unsuccesfull.", "Error", "OK");
}
}
}
private bool CheckFields()
{
if(Login.Length<4 || Login.Length>17)
{
_userDialogs.Alert("Login has to be between 4 and 16 characters.");
return false;
}
if (Password.Length < 4 || Password.Length > 17)
{
_userDialogs.Alert("Password has to be between 4 and 16 characters.");
return false;
}
if(Firstname.Length<2 || Surname.Length<2 || Firstname.Length>50 || Surname.Length>50)
{
_userDialogs.Alert("Please check your name.");
return false;
}
if(!Email.Contains('@') || Email.Contains(' '))
{
_userDialogs.Alert("Please write correct E-mail");
return false;
}
return true;
}
}
} |
using Google.Apis.Auth.OAuth2;
using Google.Apis.Gmail.v1;
using Google.Apis.Gmail.v1.Data;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Utilities;
using Utilities.Gmail;
namespace GmailQuickstart
{
class Program
{
static void Main(string[] args)
{
ApiAccessObject gmail = new GmailApiAccessObject(new GmailAuthorizer());
gmail.Run();
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Upgrade_Panel : MonoBehaviour
{
public Sprite eye;
public Sprite hand;
public Sprite elbow;
public Sprite gut;
public Sprite bone;
public Sprite heart;
public List<Sprite> upSprites;
public Upgrade_Panel sibling1;
public Upgrade_Panel sibling2;
bool scrolling = false;
public Image icon;
int spriteframe = 0;
public RectTransform DescPanel;
public Text uTitle;
public Text uDesc;
// Start is called before the first frame update
void Start()
{
upSprites = new List<Sprite>();
upSprites.Add(eye);
upSprites.Add(hand);
upSprites.Add(elbow);
upSprites.Add(gut);
upSprites.Add(bone);
upSprites.Add(heart);
}
// Update is called once per frame
void FixedUpdate()
{
if (scrolling && spriteframe % 6 == 0)
{
icon.sprite = upSprites[Random.Range(0,upSprites.Count)];
}
spriteframe++;
spriteframe = spriteframe % 6;
}
public void ScrollUpgrade()
{
scrolling = true;
}
public void ChooseUpgrade(string upgrade)
{
scrolling = false;
if (upgrade == "Third Eye")
{
icon.sprite = eye;
upSprites.Remove(eye);
sibling1.upSprites.Remove(eye);
sibling2.upSprites.Remove(eye);
uTitle.text = "Third Eye";
uDesc.text = "Teleports more";
DescPanel.gameObject.SetActive(true);
}
else if (upgrade == "Free Hand")
{
icon.sprite = hand;
upSprites.Remove(hand);
sibling1.upSprites.Remove(hand);
sibling2.upSprites.Remove(hand);
uTitle.text = "Free Hand";
uDesc.text = "Attacks faster";
DescPanel.gameObject.SetActive(true);
}
else if (upgrade == "Elbow Grease")
{
icon.sprite = elbow;
upSprites.Remove(elbow);
sibling1.upSprites.Remove(elbow);
sibling2.upSprites.Remove(elbow);
uTitle.text = "Elbow Grease";
uDesc.text = "More damage";
DescPanel.gameObject.SetActive(true);
}
else if (upgrade == "Gut Reaction")
{
icon.sprite = gut;
upSprites.Remove(gut);
sibling1.upSprites.Remove(gut);
sibling2.upSprites.Remove(gut);
uTitle.text = "Gut Reaction";
uDesc.text = "Gas trails";
DescPanel.gameObject.SetActive(true);
}
else if (upgrade == "Bare Bones")
{
icon.sprite = bone;
upSprites.Remove(bone);
sibling1.upSprites.Remove(bone);
sibling2.upSprites.Remove(bone);
uTitle.text = "Bare Bones";
uDesc.text = "New attack";
DescPanel.gameObject.SetActive(true);
}
else
{
icon.sprite = heart;
upSprites.Remove(heart);
sibling1.upSprites.Remove(heart);
sibling2.upSprites.Remove(heart);
uTitle.text = "Broken Heart";
uDesc.text = "New attack";
DescPanel.gameObject.SetActive(true);
}
StartCoroutine("HideDesc", 5f);
}
IEnumerator HideDesc(float delay)
{
yield return new WaitForSeconds(delay);
DescPanel.gameObject.SetActive(false);
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Model
{
public class Battery
{
public Battery()
{
this.Data = new Dictionary<string, string>();
}
public Dictionary<string, string> Data { get; set; }
}
}
|
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class ImportExport_ProductMaster : System.Web.UI.Page
{
string obj_Authenticated, obj_emailid;
PlaceHolder maPlaceHolder;
UserControl obj_Tabs;
UserControl obj_LoginCtrl;
UserControl obj_WelcomCtrl;
UserControl obj_Navi;
UserControl obj_Navihome;
string connStr = ConfigurationManager.ConnectionStrings["BizCon"].ConnectionString;
BizConnectLogisticsPlan obj_BizConnectLogisticsPlanClass = new BizConnectLogisticsPlan();
BizConnectClass bizconnect = new BizConnectClass();
protected void Page_Load(object sender, EventArgs e)
{
try
{
obj_emailid = Session["EmailID"].ToString();
}
catch (Exception ex)
{
}
if (IsPostBack == false)
{
ChkAuthentication();
FillProductType();
FillPackingMethods();
}
}
public void ChkAuthentication()
{
obj_LoginCtrl = null;
obj_WelcomCtrl = null;
obj_Navi = null;
obj_Navihome = null;
obj_Authenticated = Session["Authenticated"].ToString();
maPlaceHolder = (PlaceHolder)Master.FindControl("P1");
if (maPlaceHolder != null)
{
obj_Tabs = (UserControl)maPlaceHolder.FindControl("right1");
if (obj_Tabs != null)
{
obj_LoginCtrl = (UserControl)obj_Tabs.FindControl("login1");
obj_WelcomCtrl = (UserControl)obj_Tabs.FindControl("welcome1");
obj_Navi = (UserControl)obj_Tabs.FindControl("Navii");
obj_Navihome = (UserControl)obj_Tabs.FindControl("Navihome1");
if (obj_LoginCtrl != null & obj_WelcomCtrl != null)
{
if (obj_Authenticated == "1")
{
SetVisualON();
}
else
{
SetVisualOFF();
}
}
}
else
{
}
}
else
{
}
}
public void SetVisualON()
{
obj_LoginCtrl.Visible = false;
obj_WelcomCtrl.Visible = true;
//obj_Navi.Visible = true;
// obj_Navihome.Visible = true;
}
public void SetVisualOFF()
{
obj_LoginCtrl.Visible = true;
obj_WelcomCtrl.Visible = false;
//obj_Navi.Visible = true;
// obj_Navihome.Visible = false;
}
//Fill Product Types
public void FillProductType()
{
DataSet ds = new DataSet();
ds = obj_BizConnectLogisticsPlanClass.FillProductType();
if (ds.Tables["ProductType"].Rows.Count > 0)
{
//For Location Type1 DropdownlistBox
DDLproducttype.DataSource = ds.Tables["ProductType"];
DDLproducttype.DataTextField = "ProductType";
DDLproducttype.DataValueField = "ProductTypeID";
DDLproducttype.DataBind();
DDLproducttype.Items.Insert(0, new ListItem("--- Product Type ---", "0"));
}
else
{
lblmsg.Text = "";
lblmsg.Text = "Empty Table";
}
}
//Fill Products depending on the Selected Product Type
public void FillProductCategory()
{
DataSet ds = new DataSet();
ds = obj_BizConnectLogisticsPlanClass.FillProductCategory(Convert.ToInt32(DDLproducttype.SelectedItem.Value));
if (ds.Tables["ProductCategory"].Rows.Count > 0)
{
//For Location Type1 DropdownlistBox
DDLproductcategory.DataSource = ds.Tables["ProductCategory"];
DDLproductcategory.DataTextField = "CategoryName";
DDLproductcategory.DataValueField = "ProductCategoryID";
DDLproductcategory.DataBind();
DDLproductcategory.Items.Insert(0, new ListItem("--- Product Category ---", "0"));
}
else
{
lblmsg.Text = "";
lblmsg.Text = "Empty Table";
}
//drpProductCategory.Items.Add("Other");
DDLproductcategory.Focus();
}
protected void DDLproducttype_SelectedIndexChanged(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(1000);
FillProductCategory();
}
protected void DDLproductcategory_SelectedIndexChanged(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(1000);
FillPackingMethods();
DataSet ds = new DataSet();
//Fill Truck Capacity Unit
if (Convert.ToInt32(DDLproductcategory.SelectedItem.Value) == 1) // For Solid Goods
{
ds.Clear();
ds = obj_BizConnectLogisticsPlanClass.FillUnit(2);
if (ds.Tables["Unit"].Rows.Count > 0)
{
//Fill Units for Quantity Per Truck - Solid type of Goods
DDLQuantityUnit.Items.Clear();
DDLQuantityUnit.DataSource = ds.Tables["Unit"];
DDLQuantityUnit.DataTextField = "Unit";
DDLQuantityUnit.DataValueField = "UnitID";
DDLQuantityUnit.DataBind();
DDLQuantityUnit.Items.Insert(0, new ListItem("- Units -", "0"));
//Fill Units for Weight Per Truck - Solid type of Goods
DDLWeightUnit.Items.Clear();
DDLWeightUnit.DataSource = ds.Tables["Unit"];
DDLWeightUnit.DataTextField = "Unit";
DDLWeightUnit.DataValueField = "UnitID";
DDLWeightUnit.DataBind();
DDLWeightUnit.Items.Insert(0, new ListItem("- Units -", "0"));
//Fill Units for Quantity Unit - Solid type of Goods
ds.Clear();
ds = obj_BizConnectLogisticsPlanClass.FillUnit(4);
DDLQuantityUnit.Items.Clear();
DDLQuantityUnit.DataSource = ds.Tables["Unit"];
DDLQuantityUnit.DataTextField = "Unit";
DDLQuantityUnit.DataValueField = "UnitID";
DDLQuantityUnit.DataBind();
DDLQuantityUnit.Items.Insert(0, new ListItem("- Units -", "0"));
}
else
{
lblmsg.Text = "";
lblmsg.Text = "Empty Table";
}
}
else if (Convert.ToInt32(DDLproductcategory.SelectedItem.Value) == 2) // For Liquid Goods
{
ds.Clear();
ds = obj_BizConnectLogisticsPlanClass.FillUnit(3);
if (ds.Tables["Unit"].Rows.Count > 0)
{
//Fill Units for Quantity Per Truck - Liquid type of Goods
ds.Clear();
ds = obj_BizConnectLogisticsPlanClass.FillUnit(4);
DDLQuantityUnit.Items.Clear();
DDLQuantityUnit.DataSource = ds.Tables["Unit"];
DDLQuantityUnit.DataTextField = "Unit";
DDLQuantityUnit.DataValueField = "UnitID";
DDLQuantityUnit.DataBind();
DDLQuantityUnit.Items.Insert(0, new ListItem("- Units -", "0"));
//Fill Units for Weight Per Truck - Liquid type of Goods
DDLWeightUnit.Items.Clear();
DDLWeightUnit.DataSource = ds.Tables["Unit"];
DDLWeightUnit.DataTextField = "Unit";
DDLWeightUnit.DataValueField = "UnitID";
DDLWeightUnit.DataBind();
DDLWeightUnit.Items.Insert(0, new ListItem("- Units -", "0"));
}
else
{
lblmsg.Text = "";
lblmsg.Text = "Empty Table";
}
}
}
public void FillPackingMethods()
{
//Filling Packing Method Type
DataSet ds = new DataSet();
ds = obj_BizConnectLogisticsPlanClass.FillPackingMethods(Convert.ToInt32(DDLproducttype.SelectedItem.Value));
if (ds.Tables["PackingMethods"].Rows.Count > 0)
{
//For Location Type1 DropdownlistBox
DDLpackingType.Items.Clear();
DDLpackingType.DataSource = ds.Tables["PackingMethods"];
DDLpackingType.DataTextField = "PackingMethod";
DDLpackingType.DataValueField = "PackingMethodID";
DDLpackingType.DataBind();
DDLpackingType.Items.Insert(0, new ListItem("-- Methods --", "0"));
}
else
{
lblmsg.Text = "";
lblmsg.Text = "Empty Table";
}
DDLpackingType.Focus();
//Fill Units for All Dropdown Combo Box
ds.Clear();
ds = obj_BizConnectLogisticsPlanClass.FillUnit(1);
if (ds.Tables["Unit"].Rows.Count > 0)
{
//For Units for Width
DDLwidthunit.Items.Clear();
DDLwidthunit.DataSource = ds.Tables["Unit"];
DDLwidthunit.DataTextField = "Unit";
DDLwidthunit.DataValueField = "UnitID";
DDLwidthunit.DataBind();
DDLwidthunit.Items.Insert(0, new ListItem("- Units -", "0"));
//For Units for Length
DDLLengthUnit.Items.Clear();
DDLLengthUnit.DataSource = ds.Tables["Unit"];
DDLLengthUnit.DataTextField = "Unit";
DDLLengthUnit.DataValueField = "UnitID";
DDLLengthUnit.DataBind();
DDLLengthUnit.Items.Insert(0, new ListItem("- Units -", "0"));
//For Units for Height
DDLHeightUnit.Items.Clear();
DDLHeightUnit.DataSource = ds.Tables["Unit"];
DDLHeightUnit.DataTextField = "Unit";
DDLHeightUnit.DataValueField = "UnitID";
DDLHeightUnit.DataBind();
DDLHeightUnit.Items.Insert(0, new ListItem("- Units -", "0"));
//For Units for weight
DDLWeightUnit.Items.Clear();
DDLWeightUnit.DataSource = ds.Tables["Unit"];
DDLWeightUnit.DataTextField = "Unit";
DDLWeightUnit.DataValueField = "UnitID";
DDLWeightUnit.DataBind();
DDLWeightUnit.Items.Insert(0, new ListItem("- Units -", "0"));
//For Units for Quantity
DDLQuantityUnit.Items.Clear();
DDLQuantityUnit.DataSource = ds.Tables["Unit"];
DDLQuantityUnit.DataTextField = "Unit";
DDLQuantityUnit.DataValueField = "UnitID";
DDLQuantityUnit.DataBind();
DDLQuantityUnit.Items.Insert(0, new ListItem("- Units -", "0"));
}
else
{
lblmsg.Text = "";
lblmsg.Text = "Empty Table";
}
//Fill Units for Volume
ds.Clear();
ds = obj_BizConnectLogisticsPlanClass.FillUnit(3);
if (ds.Tables["Unit"].Rows.Count > 0)
{
//For Units for Volume
DDlvolumeunit.Items.Clear();
DDlvolumeunit.DataSource = ds.Tables["Unit"];
DDlvolumeunit.DataTextField = "Unit";
DDlvolumeunit.DataValueField = "UnitID";
DDlvolumeunit.DataBind();
DDlvolumeunit.Items.Insert(0, new ListItem("- Units -", "0"));
}
else
{
lblmsg.Text = "";
lblmsg.Text = "Empty Table";
}
if (Convert.ToInt32(DDLproducttype.SelectedItem.Value) == 1) // For Solid Goods
{
ds.Clear();
ds = obj_BizConnectLogisticsPlanClass.FillUnit(2);
if (ds.Tables["Unit"].Rows.Count > 0)
{
//Fill Units for Weight Per Truck - Solid type of Goods
DDLWeightUnit.Items.Clear();
DDLWeightUnit.DataSource = ds.Tables["Unit"];
DDLWeightUnit.DataTextField = "Unit";
DDLWeightUnit.DataValueField = "UnitID";
DDLWeightUnit.DataBind();
DDLWeightUnit.Items.Insert(0, new ListItem("- Units -", "0"));
//Fill Units for Quantity Unit - Solid type of Goods
ds.Clear();
ds = obj_BizConnectLogisticsPlanClass.FillUnit(4);
DDLQuantityUnit.Items.Clear();
DDLQuantityUnit.DataSource = ds.Tables["Unit"];
DDLQuantityUnit.DataTextField = "Unit";
DDLQuantityUnit.DataValueField = "UnitID";
DDLQuantityUnit.DataBind();
DDLQuantityUnit.Items.Insert(0, new ListItem("- Units -", "0"));
}
else
{
lblmsg.Text = "";
lblmsg.Text = "Empty Table";
}
}
else if (Convert.ToInt32(DDLproducttype.SelectedItem.Value) == 2) // For Liquid Goods
{
ds.Clear();
ds = obj_BizConnectLogisticsPlanClass.FillUnit(3);
if (ds.Tables["Unit"].Rows.Count > 0)
{
//Fill Units for Weight Per Truck - Liquid type of Goods
DDLWeightUnit.Items.Clear();
DDLWeightUnit.DataSource = ds.Tables["Unit"];
DDLWeightUnit.DataTextField = "Unit";
DDLWeightUnit.DataValueField = "UnitID";
DDLWeightUnit.DataBind();
DDLWeightUnit.Items.Insert(0, new ListItem("- Units -", "0"));
//Fill Units for Quantity Unit - Liquid type of Goods
ds.Clear();
ds = obj_BizConnectLogisticsPlanClass.FillUnit(4);
DDLQuantityUnit.Items.Clear();
DDLQuantityUnit.DataSource = ds.Tables["Unit"];
DDLQuantityUnit.DataTextField = "Unit";
DDLQuantityUnit.DataValueField = "UnitID";
DDLQuantityUnit.DataBind();
DDLQuantityUnit.Items.Insert(0, new ListItem("- Units -", "0"));
}
else
{
lblmsg.Text = "";
lblmsg.Text = "Empty Table";
}
}
}
protected void DDLpackingType_SelectedIndexChanged(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(1000);
if (DDLpackingType.SelectedItem.Text == "Liquid Container")
{
DisableWeightLengthWidthHeight();
Txt_width.Text = "0";
txt_length.Text = "0";
txt_height.Text = "0";
txt_quantity.Text = "0";
txt_weight.Text = "0";
txt_volume.Text = "0";
txt_volume.Focus();
}
else
{
EnableWeightLengthWidthHeight();
Txt_width.Text = "0";
txt_length.Text = "0";
txt_height.Text = "0";
txt_quantity.Text = "0";
txt_weight.Text = "0";
txt_volume.Text = "0";
Txt_width.Focus();
}
}
//Disable Weight Length Width and Height
public void DisableWeightLengthWidthHeight()
{
txt_quantity.Enabled = false;
txt_quantity.Text = "";
DDLQuantityUnit.Enabled = false;
txt_weight.Enabled = false;
txt_weight.Text = "";
DDLWeightUnit.Enabled = false;
txt_length.Enabled = false;
txt_length.Text = "";
DDLLengthUnit.Enabled = false;
Txt_width.Enabled = false;
Txt_width.Text = "";
DDLwidthunit.Enabled = false;
txt_height.Enabled = false;
txt_height.Text = "";
DDLHeightUnit.Enabled = false;
txt_quantity.Enabled = false;
txt_quantity.Text = "0";
DDLQuantityUnit.Enabled = false;
txt_volume.Text = "";
txt_volume.Enabled = true;
DDlvolumeunit.Enabled = true;
}
//Enable Weight Length Width and Height
public void EnableWeightLengthWidthHeight()
{
txt_quantity.Enabled = true;
txt_quantity.Text = "";
DDLQuantityUnit.Enabled = true;
txt_weight.Enabled = true;
txt_weight.Text = "";
DDLWeightUnit.Enabled = true;
txt_length.Enabled = true;
txt_length.Text = "";
DDLLengthUnit.Enabled = true;
Txt_width.Enabled = true;
Txt_width.Text = "";
DDLwidthunit.Enabled = true;
txt_height.Enabled = true;
txt_height.Text = "";
DDLHeightUnit.Enabled = true;
txt_volume.Enabled = false;
txt_volume.Text = "";
DDlvolumeunit.Enabled = false;
}
protected void Btn_submit_Click(object sender, EventArgs e)
{
int res=0;
int clientid = Convert.ToInt32(Session["ClientID"].ToString());
//res = obj_BizConnectLogisticsPlanClass.Insert_Product(clientid, Convert.ToInt32(Txt_sku.Text), Txt_productname.Text, txt_productDescription.Text, Convert.ToInt32(DDLproducttype.SelectedValue), Convert.ToInt32(DDLproductcategory.SelectedValue), Convert.ToInt32(DDLpackingType.SelectedValue), Convert.ToDouble(txt_weight.Text), Convert.ToInt32(DDLWeightUnit.SelectedValue), Convert.ToDouble(txt_length.Text), Convert.ToInt32(DDLLengthUnit.SelectedValue), Convert.ToDouble(Txt_width.Text), Convert.ToInt32(DDLwidthunit.SelectedValue), Convert.ToDouble(txt_height.Text), Convert.ToInt32(DDLHeightUnit.SelectedValue), Convert.ToDouble(txt_volume.Text), Convert.ToInt32(DDlvolumeunit.SelectedValue), Convert.ToDouble(txt_quantity.Text), Convert.ToInt32(DDLQuantityUnit.SelectedValue), Convert.ToInt32(DDLpckngsp.SelectedValue), Convert.ToDouble(txt_transcostperunit.Text), Convert.ToDouble(txt_comm.Text));
if (res == 1)
{
// lblmsg.Visible = true;
//lblmsg.Text = "Data saved successfully";
ClientScript.RegisterStartupScript(this.GetType(), "alert", "<script>alert('Product saved successfully');</script>");
ClearFields();
}
else
{
lblmsg.Visible = true;
lblmsg.Text = "Data not saved";
}
}
public void ClearFields()
{
DDLproducttype.SelectedIndex = -1;
DDLproductcategory.SelectedIndex = -1;
Txt_productname.Text = "";
txt_productDescription.Text = "";
DDLpackingType.SelectedIndex = -1;
DDLHeightUnit.SelectedIndex = -1;
DDLWeightUnit.SelectedIndex = -1;
DDLLengthUnit.SelectedIndex = -1;
DDLwidthunit.SelectedIndex = -1;
DDLQuantityUnit.SelectedIndex = -1;
DDLpckngsp.SelectedIndex = -1;
Txt_sku.Text = "";
txt_transcostperunit.Text = "";
txt_comm.Text = "";
txt_height.Text = "";
txt_length.Text = "";
txt_weight.Text = "";
Txt_width.Text = "";
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using Microsoft.IdentityModel.Claims;
using Microsoft.IdentityModel.Web;
using RecipeWebRole.ActionFilters;
using RecipeWebRole.DataAccess;
using RecipeWebRole.Models;
using RecipeWebRole.Utilities;
namespace RecipeWebRole.Controllers
{
[ActionFilters.Authorize]
public class AccountController : Controller
{
private readonly IUserRepository _userRepo;
public AccountController(IUserRepository userRepo)
{
_userRepo = userRepo;
}
//
// GET: /Account/Login
// Without view -> use WSFederationAuthenticationModule to redirect to Azure ACS
[AllowAnonymous]
public ActionResult Login(string returnUrl)
{
if (!User.Identity.IsAuthenticated)
{
// User is not authenticated.
// WSFederationAuthenticationModule is configured to kick in
// when in EndRequest a request indicates "unauthorized access".
// Therefore, the following call will start the login process,
// and after completion, will come back to this address.
return new HttpUnauthorizedResult();
}
// The user successfully authenticated.
string nameIdentifier = this.GetUserNameIdentifier();
if (!_userRepo.IsExistingUser(nameIdentifier))
{
// New user. Redirect to page for recording user name.
var queryString = new QueryString { { "returnUrl", returnUrl } };
return new RedirectResult("/Account/UserData" + queryString);
}
// user exists.
// Redirect back to the page the user was querying.
return new RedirectResult(returnUrl);
}
//
// GET: /Account/RequiresLogin
[HttpGet]
[AllowAnonymous]
public ActionResult RequiresLogin(string returnUrl)
{
ViewBag.ReturnUrl = returnUrl;
return View();
}
//
// GET: /Account/Register
[HttpGet]
[AllowAnonymous]
public ActionResult Register(string returnUrl)
{
ViewBag.ReturnUrl = returnUrl;
return View();
}
//
// GET: /Account/UserData
[HttpGet]
public ActionResult UserData(string returnUrl)
{
ViewBag.ReturnUrl = returnUrl;
return View();
}
//
// POST: /Account/UserData
[HttpPost]
public ActionResult UserData(string username, string returnUrl)
{
//string username = Request.Form["username"];
string userIdentifier = this.GetUserNameIdentifier();
// TODO: validate that username is valid!
_userRepo.AddUser(new User { Id = userIdentifier, Name = username });
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
// If we got this far, something failed
return RedirectToAction("Index", "Home");
}
//
// GET: /Account/SignOut
public ActionResult SignOut()
{
FederatedAuthentication.WSFederationAuthenticationModule.SignOut(false);
//FederatedAuthentication.SessionAuthenticationModule.DeleteSessionTokenCookie();
return RedirectToAction("Index", "Home");
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using ObjectPooling;
using UnityEngine;
using UnityEngine.PlayerLoop;
public class RoadLayer : MonoBehaviour
{
[SerializeField] private SOPoolableObject _PoolableSO;
[SerializeField] float _StartPoint = 513 + 57;
[SerializeField] private float _TimerLimit = 1.5f;
[SerializeField] private float _XRotation;
private float _Timer;
private PoolableObject _PrefabRef;
private void Awake()
{
_PrefabRef = _PoolableSO.PrefabRef;
}
private void Update()
{
_Timer += Time.deltaTime;
if (_Timer < _TimerLimit) return;
_Timer = 0f;
var nextRoad = PoolManager.GetNext(_PrefabRef, new Vector3(0f, 0f, _StartPoint),
Quaternion.Euler(_XRotation, 0f, 0f), true);
nextRoad.transform.localPosition = new Vector3(0f, 0f, _StartPoint);
nextRoad.transform.localRotation = Quaternion.Euler(_XRotation, 0f, 0f);
}
} |
namespace Plus.Communication.Packets.Outgoing.Inventory.Trading
{
internal class TradingClosedComposer : MessageComposer
{
public int UserId { get; }
public TradingClosedComposer(int userId)
: base(ServerPacketHeader.TradingClosedMessageComposer)
{
UserId = userId;
}
public override void Compose(ServerPacket packet)
{
packet.WriteInteger(UserId);
packet.WriteInteger(0);
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class BarFillScript : MonoBehaviour {
public float mMaxBar = 255;
public float mMinBar = 10;
public float mMaxTime = 2;
public GameObject mPlayer;
private bool isGrounded;
private float mTimer;
private RectTransform mBarRect;
private float mBarSize;
private float mFillSpeed;
private Rigidbody mPlayerRb;
private PlayerScript mPS;
private bool mSpaceDown;
// Use this for initialization
void Start () {
mTimer = 0;
mFillSpeed = (mMaxBar - mMinBar) / mMaxTime;
mSpaceDown = false;
mBarRect = transform as RectTransform;
mBarSize = mBarRect.rect.width;
mPlayerRb = mPlayer.GetComponent<Rigidbody> ();
mPS = mPlayer.GetComponent<PlayerScript> ();
}
// Update is called once per frame
void Update () {
isGrounded = mPS.IsGrounded ();
//Check Space Down/Up
if (Input.GetKeyDown ("space")) {
mSpaceDown = true;
}
if (Input.GetKeyUp ("space")) {
mSpaceDown = false;
JumpPlayer ();
mTimer = 0;
}
//If Bar isnt filled an space is down, increment
if (mSpaceDown == true && mBarSize <= mMaxBar && isGrounded)
mTimer += Time.deltaTime;
UpdateBar ();
}
void UpdateBar(){
//Change Width of bar
mBarSize = mMinBar + (mTimer * mFillSpeed);
if (mBarSize >= mMaxBar)
mBarSize = mMaxBar;
mBarRect.sizeDelta = new Vector2 (mBarSize, mBarRect.sizeDelta.y);
//Change Color of bar
GetComponent<Image>().color = new Color32(255, (byte)(256 - mBarSize), (byte)(256 - mBarSize), 255);
}
void JumpPlayer(){
mPlayerRb.AddForce (mBarSize, mBarSize * 3, 0, 0);
}
}
|
using System;
using UnityEngine;
public static class BezierCurve
{
private static float[] FactorialLookup;
static BezierCurve()
{
CreateFactorialTable();
}
// just check if n is appropriate, then return the result
private static float factorial(int n)
{
if (n < 0) { throw new Exception("n is less than 0"); }
if (n > 32) { throw new Exception("n is greater than 32"); }
return FactorialLookup[n]; /* returns the value n! as a SUMORealing point number */
}
// create lookup table for fast factorial calculation
private static void CreateFactorialTable()
{
// fill untill n=32. The rest is too high to represent
FactorialLookup = new float[33];
FactorialLookup[0] = 1f;
FactorialLookup[1] = 1f;
FactorialLookup[2] = 2f;
FactorialLookup[3] = 6f;
FactorialLookup[4] = 24f;
FactorialLookup[5] = 120f;
FactorialLookup[6] = 720f;
FactorialLookup[7] = 5040f;
FactorialLookup[8] = 40320f;
FactorialLookup[9] = 362880f;
FactorialLookup[10] = 3628800f;
FactorialLookup[11] = 39916800f;
FactorialLookup[12] = 479001600f;
FactorialLookup[13] = 6227020800f;
FactorialLookup[14] = 87178291200f;
FactorialLookup[15] = 1307674368000f;
FactorialLookup[16] = 20922789888000f;
FactorialLookup[17] = 355687428096000f;
FactorialLookup[18] = 6402373705728000f;
FactorialLookup[19] = 121645100408832000f;
FactorialLookup[20] = 2432902008176640000f;
FactorialLookup[21] = 51090942171709440000f;
FactorialLookup[22] = 1124000727777607680000f;
FactorialLookup[23] = 25852016738884976640000f;
FactorialLookup[24] = 620448401733239439360000f;
FactorialLookup[25] = 15511210043330985984000000f;
FactorialLookup[26] = 403291461126605635584000000f;
FactorialLookup[27] = 10888869450418352160768000000f;
FactorialLookup[28] = 304888344611713860501504000000f;
FactorialLookup[29] = 8841761993739701954543616000000f;
FactorialLookup[30] = 265252859812191058636308480000000f;
FactorialLookup[31] = 8222838654177922817725562880000000f;
FactorialLookup[32] = 263130836933693530167218012160000000f;
}
private static float Ni(int n, int i)
{
float ni;
float a1 = factorial(n);
float a2 = factorial(i);
float a3 = factorial(n - i);
ni = a1 / (a2 * a3);
return ni;
}
// Calculate Bernstein basis
private static float Bernstein(int n, int i, float t)
{
float basis;
float ti; /* t^i */
float tni; /* (1 - t)^i */
/* Prevent problems with pow */
if (t == 0f && i == 0)
ti = 1f;
else
ti = Mathf.Pow(t, i);
if (n == i && t == 1f)
tni = 1f;
else
tni = Mathf.Pow((1 - t), (n - i));
//Bernstein basis
basis = Ni(n, i) * ti * tni;
return basis;
}
public static Vector3[] Bezier3D(Vector3[] b)
{
int cpts = (b.Length + 2) / 2;
Vector3[] p = new Vector3[cpts * 2];
return Bezier3D(b, cpts, p);
}
public static Vector3[] Bezier3D(Vector3[] b, int cpts, Vector3[] p)
{
if(p.Length % 2 != 0)
throw new System.ArgumentException();
if(cpts * 2 > p.Length)
throw new System.ArgumentException();
int npts = b.Length / 2;
int icount, jcount;
float step, t;
// Calculate points on curve
icount = 0;
t = 0;
step = 1f / (cpts - 1);
for (int i1 = 0; i1 != cpts; i1++)
{
if ((1f - t) < 5e-6)
t = 1f;
jcount = 0;
p[icount] = Vector3.zero;
p[icount + 1] = Vector3.zero;
for (int i = 0; i != npts; i++)
{
float basis = Bernstein(npts - 1, i, t);
p[icount] += basis * b[jcount];
p[icount + 1] += basis * b[jcount + 1];
jcount = jcount + 2;
}
icount += 2;
t += step;
}
return p;
}
}
|
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="InfoControllerTest.cs" company="CGI">
// Copyright (c) CGI. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using CGI.Reflex.Core.Entities;
using CGI.Reflex.Core.Tests;
using CGI.Reflex.Web.Areas.Applications.Controllers;
using CGI.Reflex.Web.Areas.Applications.Models.Info;
using FluentAssertions;
using NUnit.Framework;
namespace CGI.Reflex.Web.Tests.Areas.Applications.Controllers
{
public class InfoControllerTest : BaseControllerTest<InfoController>
{
[Test]
public void Details_should_return_view()
{
Controller.Details(Rand.Int(int.MaxValue)).Should().BeHttpNotFound();
var application = Factories.Application.Save();
var result = Controller.Details(application.Id);
result.Should().BeDefaultView();
result.Model<InfoEdit>().Id.Should().Be(application.AppInfo.Id);
}
[Test]
public void Edit_should_return_view()
{
Controller.Edit(Rand.Int(int.MaxValue)).Should().BeHttpNotFound();
var application = Factories.Application.Save();
var result = Controller.Edit(application.Id);
result.Should().BeDefaultView();
result.Model<InfoEdit>().Id.Should().Be(application.AppInfo.Id);
}
[Test]
public void Edit_should_update_Info()
{
var application = Factories.Application.Save();
var infoEdit = new InfoEdit
{
Id = application.AppInfo.Id,
Name = Rand.String(),
Code = Rand.String(),
TypeId = Factories.DomainValue.Save(dv => dv.Category = DomainValueCategory.ApplicationType).Id,
StatusId = Factories.DomainValue.Save(dv => dv.Category = DomainValueCategory.ApplicationStatus).Id,
CriticityId = Factories.DomainValue.Save(dv => dv.Category = DomainValueCategory.ApplicationCriticity).Id,
Description = Rand.String(),
UserRange = Factories.DomainValue.Save(dv => dv.Category = DomainValueCategory.ApplicationUserRange).Id,
Category = Factories.DomainValue.Save(dv => dv.Category = DomainValueCategory.ApplicationCategory).Id,
Certification = Factories.DomainValue.Save(dv => dv.Category = DomainValueCategory.ApplicationCertification).Id,
MaintenanceWindow = Rand.String(),
Notes = Rand.String(),
ConcurrencyVersion = application.AppInfo.ConcurrencyVersion
};
StubStandardRequest();
Controller.Edit(Rand.Int(int.MaxValue), infoEdit).Should().BeHttpNotFound();
var result = Controller.Edit(application.Id, infoEdit);
result.Should().BeRedirectToActionName("Details");
application.Name.Should().Be(infoEdit.Name);
application.Code.Should().Be(infoEdit.Code);
application.ApplicationType.Id.Should().Be(infoEdit.TypeId.Value);
application.AppInfo.Status.Id.Should().Be(infoEdit.StatusId.Value);
application.AppInfo.Criticity.Id.Should().Be(infoEdit.CriticityId.Value);
application.AppInfo.Description.Should().Be(infoEdit.Description);
application.AppInfo.UserRange.Id.Should().Be(infoEdit.UserRange.Value);
application.AppInfo.Category.Id.Should().Be(infoEdit.Category.Value);
application.AppInfo.Certification.Id.Should().Be(infoEdit.Certification.Value);
application.AppInfo.MaintenanceWindow.Should().Be(infoEdit.MaintenanceWindow);
application.AppInfo.Notes.Should().Be(infoEdit.Notes);
}
[Test]
public void Edit_should_not_update_Info_when_concurrency_doesnt_match()
{
var application = Factories.Application.Save();
var infoEdit = new InfoEdit
{
Id = application.AppInfo.Id,
StatusId = Factories.DomainValue.Save(dv => dv.Category = DomainValueCategory.ApplicationStatus).Id,
CriticityId = Factories.DomainValue.Save(dv => dv.Category = DomainValueCategory.ApplicationCriticity).Id,
Description = Rand.String(),
UserRange = Factories.DomainValue.Save(dv => dv.Category = DomainValueCategory.ApplicationUserRange).Id,
Category = Factories.DomainValue.Save(dv => dv.Category = DomainValueCategory.ApplicationCategory).Id,
Certification = Factories.DomainValue.Save(dv => dv.Category = DomainValueCategory.ApplicationCertification).Id,
MaintenanceWindow = Rand.String(),
Notes = Rand.String(),
ConcurrencyVersion = application.AppInfo.ConcurrencyVersion - 1
};
StubStandardRequest();
Controller.Edit(application.Id, infoEdit);
application.AppInfo.Status.Id.Should().NotBe(infoEdit.StatusId.Value);
application.AppInfo.Criticity.Id.Should().NotBe(infoEdit.CriticityId.Value);
application.AppInfo.Description.Should().NotBe(infoEdit.Description);
application.AppInfo.UserRange.Id.Should().NotBe(infoEdit.UserRange.Value);
application.AppInfo.Certification.Id.Should().NotBe(infoEdit.Certification.Value);
application.AppInfo.MaintenanceWindow.Should().NotBe(infoEdit.MaintenanceWindow);
application.AppInfo.Notes.Should().NotBe(infoEdit.Notes);
}
}
}
|
using Microsoft.Xna.Framework;
using MonoGame.Extended.Shapes;
namespace MonoGame.Extended.Collisions
{
public class CollisionInfo
{
public ICollidable Other { get; internal set; }
public Vector2 PenetrationVector { get; internal set; }
}
} |
using LuizalabsWishesManager.Domains.Repositories;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
namespace LuizalabsWishesManager.Data.Repositories
{
public class RepositoryBase<TEntity> : IDisposable, IRepositoryBase<TEntity> where TEntity : class
{
protected readonly LuizalabsWishesManagerContext _context;
public RepositoryBase()
{
var options = new DbContextOptionsBuilder<LuizalabsWishesManagerContext>()
.UseInMemoryDatabase(databaseName: "luizalabs")
.Options;
_context = new LuizalabsWishesManagerContext(options);
}
public void Add(TEntity entity)
{
_context.Set<TEntity>().Add(entity);
_context.SaveChanges();
}
public TEntity GetById(int id)
{
return _context.Set<TEntity>().Find(id);
}
public IEnumerable<TEntity> GetAll()
{
return _context.Set<TEntity>().ToList();
}
public IEnumerable<TEntity> GetAll(int page, int pageSize)
{
return _context.Set<TEntity>()
.Skip(pageSize * (page - 1))
.Take(pageSize);
}
public IEnumerable<TEntity> GetAll(Expression<Func<TEntity, bool>> predicate)
{
return _context.Set<TEntity>()
.Where(predicate);
}
public IEnumerable<TEntity> GetAll(Expression<Func<TEntity, bool>> predicate, int page, int pageSize)
{
return _context.Set<TEntity>()
.Where(predicate)
.Skip(pageSize * (page - 1))
.Take(pageSize);
}
public void Update(TEntity entity)
{
_context.Entry(entity).State = EntityState.Modified;
_context.SaveChanges();
}
public void Remove(TEntity entity)
{
_context.Set<TEntity>().Remove(entity);
_context.SaveChanges();
}
public void Dispose()
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Console2.recursion
{
public class CheapestPay
{
/*
* Write a function using Recursion to do the following: You are the manager in a small factory.
* You have 7 workers and 7 jobs to be done. Each worker is assigned one and only one job. Each
* worker demands different pay for each job. (E.g.: Worker Sam demands $10 for welding, $15 for
* carpentry, etc. Worker Joe demands $12 for welding, $5 for carpentry, etc.) Find the job-assignment
* which works out cheapest for you.
*/
public int FindCheapestPay(List<int[]> Salaris)
{
bool[] tracker = new bool[Salaris.Count];
int[] workers = new int[Salaris.Count];
return Worker(workers.Length, 0, workers, tracker, Salaris);
}
/// <summary>
///
/// </summary>
/// <param name="n">total number jobs</param>
/// <param name="k">number of jobs have been assigned</param>
/// <param name="workers">integer array keep tracking which worker has been assigned.</param>
/// <param name="Salaries">salaries input</param>
public int Worker(int n, int k, int[] workers, bool[] tracker, List<int[]> Salaries)
{
if (n == k)
{
int totalSalary = 0;
for (int i = 0; i < workers.Length; i++)
{
totalSalary += Salaries[i][workers[i]];
}
return totalSalary;
}
else
{
int minPay = int.MaxValue;
for (int i = 0; i < workers.Length; i++)
{
if (!tracker[i])
{
tracker[i] = true;
for (int j = 0; j < Salaries[0].Length; j++)
{
workers[i] = j;
int tmp = Worker(n, k + 1, workers, tracker, Salaries);
minPay = tmp < minPay ? tmp : minPay;
}
tracker[i] = false;
}
}
return minPay;
}
}
}
}
|
using System;
using System.Linq.Expressions;
using Azure.CosmosDB.Net.EntityModel;
namespace Azure.CosmosDB.Net.FluentAPI.CRUDOperation.Interface
{
public interface IWhereOperation<T> where T : BaseEntity
{
IOrderBy Orderby(Expression<Func<BaseEntity, bool>> predicate);
IOrderbyDescending OrderbyDescending(Expression<Func<BaseEntity,bool>> predicate);
IOrderbyAscending OrderbyAscending(Expression<Func<BaseEntity, bool>> predicate);
}
} |
using SampleEntityCore.Data;
using SampleEntityCore.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace SampleEntityCore.DAL
{
public class CategoryDAL : ICategory
{
private POSDataContext _context;
public CategoryDAL(POSDataContext context)
{
_context = context;
}
public void Create(Category obj)
{
try
{
_context.Categories.Add(obj);
_context.SaveChanges();
}
catch (Exception ex)
{
throw new NotImplementedException();
}
}
public void Delete(string id)
{
try
{
var result = GetById(id);
if (result!=null)
{
_context.Categories.Remove(result);
_context.SaveChanges();
}
else
{
throw new Exception("Data tidak ditemukan !");
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
public void Edit(string id, Category obj)
{
try
{
var result = GetById(id); //dicari dulu ada tidak yg mau diedit //OOP
if (result != null)
{
result.CategoryName = obj.CategoryName;
_context.SaveChanges();
}
}
catch (Exception ex)
{
throw new Exception("DAta Tidak Ditemukan !");
}
}
public IEnumerable<Category> GetAll()
{
//var results = from c in _context.Categories // typenya IQueryable
// orderby c.CategoryName ascending //lebih mudah dipahami daripada lambda dibawah
// select c;
var results = _context.Categories.OrderBy(c => c.CategoryName);
return results;
}
public Category GetById(string id)
{
var results = (from c in _context.Categories
where c.CategoryID == Convert.ToInt32(id)
select c).SingleOrDefault();
return results;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Firebase;
public class Cenario : MonoBehaviour
{
public GameObject TextoAuxiliador;// Texto Auxiliador Numero ---------------------
void Update()
{
if (PlayerPrefs.GetInt("auxilio") == 1)
{
TextoAuxiliador.gameObject.SetActive(true);
}
else
{
TextoAuxiliador.gameObject.SetActive(false);
}
}
}
|
using UnityEngine;
using System.Collections;
public class e1 : MonoBehaviour {
[HideInInspector]
int _ownerId; // To ensure they have a unique mesh
MeshFilter _mf;
MeshFilter MeshFilter
{ // Tries to find a mesh filter, adds one if it doesn't exist yet
get
{
_mf = _mf ?? GetComponent<MeshFilter>();
_mf = _mf ?? gameObject.AddComponent<MeshFilter>();
return _mf;
}
}
Mesh _mesh;
protected Mesh Mesh
{ // The mesh to edit
get
{
if (_mesh == null)
{
//bool isOwner = _ownerId == gameObject.GetInstanceID();
if (MeshFilter.sharedMesh == null /* || !isOwner*/)
{
MeshFilter.sharedMesh = _mesh = new Mesh();
_ownerId = gameObject.GetInstanceID();
_mesh.name = "Mesh [" + _ownerId + "]";
}
else
{
_mesh = MeshFilter.sharedMesh;
}
}
return _mesh;
}
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
Vector3[] vertices = Mesh.vertices;
Vector3[] normals = Mesh.normals;
int i = 0;
while (i < vertices.Length)
{
vertices[i] += normals[i] * Mathf.Sin(Time.time);
i++;
}
Mesh.vertices = vertices;
}
}
|
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using UnityEngine;
public class Initialization : MonoBehaviour
{
private int max_score_value = 0;
private const int scaler = 20;
public GameObject chicken;
public GameObject dog;
public GameObject fox;
public GameObject pig;
public GameObject lion;
public GameObject cow;
public GameObject penguin;
public GameObject cat;
// Start is called before the first frame update
private void Awake()
{
LoadFile();
if (max_score_value < scaler)
{
Instantiate(chicken, Vector3.zero, Quaternion.identity);
}
else
{
if (max_score_value < 2 * scaler)
{
Instantiate(cat, Vector3.zero, Quaternion.identity);
}
else
{
if (max_score_value < 3 * scaler)
{
Instantiate(dog, Vector3.zero, Quaternion.identity);
}
else
{
if (max_score_value < 4 * scaler)
{
Instantiate(fox, Vector3.zero, Quaternion.identity);
}
else
{
if (max_score_value < 5 * scaler)
{
Instantiate(pig, Vector3.zero, Quaternion.identity);
}
else
{
if (max_score_value < 6 * scaler)
{
Instantiate(lion, Vector3.zero, Quaternion.identity);
}
else
{
if (max_score_value < 7 * scaler)
{
Instantiate(cow, Vector3.zero, Quaternion.identity);
}
else
{
Instantiate(penguin, Vector3.zero, Quaternion.identity);
}
}
}
}
}
}
}
}
public void LoadFile()
{
string destination = Application.persistentDataPath + "/score.dat";
FileStream file;
if (File.Exists(destination)) file = File.OpenRead(destination);
else
{
return;
}
BinaryFormatter bf = new BinaryFormatter();
max_score_value = (int)bf.Deserialize(file);
file.Close();
}
} |
using System.Collections.Generic;
using Asset.DataAccess.Library.AssetModelGetways.AssetEntryGetways;
using Asset.Models.Library.EntityModels.AssetsModels.AssetEntrys;
namespace Asset.BisnessLogic.Library.AssetModelManagers.AssetEntryManagers
{
public class AssetEntryManager : IRepositoryManager<AssetEntry>
{
private readonly AssetEntryGetway _assetEntryGetway;
public AssetEntryManager()
{
_assetEntryGetway = new AssetEntryGetway();
}
public bool IsAssetIdNoExist(string idNo)
{
bool isIdNo = false;
var assetEntry = GetAssetEntryByAssetId(idNo);
if (assetEntry != null)
{
isIdNo = true;
}
return isIdNo;
}
private AssetEntry GetAssetEntryByAssetId(string idNo)
{
return _assetEntryGetway.GetAssetEntryByAssetId(idNo);
}
public bool IsAssetNameExist(string name)
{
bool isName = false;
var assetEntry = GetAssetEntryByName(name);
if (assetEntry != null)
{
isName = true;
}
return isName;
}
private AssetEntry GetAssetEntryByName(string name)
{
return _assetEntryGetway.GetAssetEntryByName(name);
}
public bool IsSerialNoExist(string serialNo)
{
bool isSerialNo = false;
var assetEntry = GetAssetEntryBySerialNo(serialNo);
if (assetEntry != null)
{
isSerialNo = true;
}
return isSerialNo;
}
private AssetEntry GetAssetEntryBySerialNo(string serialNo)
{
return _assetEntryGetway.GetAssetEntryBySerialNo(serialNo);
}
public IEnumerable<AssetEntry> AssetEntriesWithOrganiztionBranchLocationTypeGroupManufactureModel()
{
return _assetEntryGetway.AssetEntriesWithOrganiztionBranchLocationTypeGroupManufactureModel();
}
public IEnumerable<AssetEntry> FindById(int id)
{
return _assetEntryGetway.Find(id);
}
public AssetEntry SingleAssetEntry(int id)
{
return _assetEntryGetway.SingleAssetEntry(id);
}
public AssetEntry Get(int id)
{
return _assetEntryGetway.Get(id);
}
public IEnumerable<AssetEntry> GetAll()
{
return _assetEntryGetway.GetAll();
}
public int Add(AssetEntry entity)
{
return _assetEntryGetway.Add(entity);
}
public int AddRange(IEnumerable<AssetEntry> entities)
{
return _assetEntryGetway.AddRange(entities);
}
public int Update(AssetEntry entity)
{
return _assetEntryGetway.Update(entity);
}
public int Remove(AssetEntry entity)
{
return _assetEntryGetway.Remove(entity);
}
public int RemoveRange(IEnumerable<AssetEntry> entities)
{
return _assetEntryGetway.RemoveRange(entities);
}
}
}
|
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.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Forms;
using MaterialDesignColors.WpfExample.Domain;
using Emgu.CV;
using Emgu.CV.Structure;
using Chpoi.SuitUp.Source;
using Chpoi.SuitUp.Entity;
using Chpoi.SuitUp.Service;
using Chpoi.SuitUp.Util;
namespace chpoi.suitup.ui
{
/// <summary>
/// Interaction logic for SellerAddGoodsInterface.xaml
/// </summary>
public partial class SellerAddGoodsInterface : Window
{
public SellerAddGoodsInterface()
{
InitializeComponent();
SourceManager.sellerNewPicPath = "";
}
private void OrderManageButtonClick(object sender, RoutedEventArgs e)
{
SellerOrderWindow sOW = new SellerOrderWindow();
sOW.Show();
this.Close();
}
private void GoodsManageButtonClick(object sender, RoutedEventArgs e)
{
SellerGoodsWindow sGW = new SellerGoodsWindow();
sGW.Show();
this.Close();
}
private void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
this.DragMove();
}
private void CloseButtonClick(object sender, RoutedEventArgs e)
{
this.Close();
}
private void MinimizeButtonClick(object sender, RoutedEventArgs e)
{
this.WindowState = WindowState.Minimized;
}
private void PersonalInforButtonClick(object sender, RoutedEventArgs e)
{
}
private void BodyParametersClick(object sender, RoutedEventArgs e)
{
BuyerInterfaceBodyParameters bIBP = new BuyerInterfaceBodyParameters();
bIBP.Show();
this.Close();
}
private void LogOutButtonClick(object sender, RoutedEventArgs e)
{
//注销
LoginWindow lW = new LoginWindow();
lW.Show();
this.Close();
}
private void UploadPictureButtonClick(object sender, RoutedEventArgs e)
{
try
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "All Image Files|*.bmp;*.ico;*.gif;*.jpeg;*.jpg;*.png;*.tif;*.tiff|" +
"Windows Bitmap(*.bmp)|*.bmp|" +
"Windows Icon(*.ico)|*.ico|" +
"Graphics Interchange Format (*.gif)|(*.gif)|" +
"JPEG File Interchange Format (*.jpg)|*.jpg;*.jpeg|" +
"Portable Network Graphics (*.png)|*.png|" +
"Tag Image File Format (*.tif)|*.tif;*.tiff";
openFileDialog.Title = "选择图片";
openFileDialog.FilterIndex = 1;
openFileDialog.RestoreDirectory = true;
DialogResult result = openFileDialog.ShowDialog();
if (result == System.Windows.Forms.DialogResult.Cancel)
{
return;
}
string fileName = openFileDialog.FileName;
Picture.Source = new BitmapImage(new Uri(fileName, UriKind.RelativeOrAbsolute));
SourceManager.sellerNewPicPath = fileName;
}
catch
{
System.Windows.MessageBox.Show("上传失败。");
}
}
private void AddButtonClick(object sender, RoutedEventArgs e)
{
//保存修改后的信息
try
{
string NewSuitName = InputSuitName.Text;
if (NewSuitName == "")
{
System.Windows.MessageBox.Show("商品名称不能为空!");
return;
}
double NewPrice;
if (InputPrice.Text == "")
{
System.Windows.MessageBox.Show("价格不能为空!");
return;
}
else
{
try
{
double.Parse(InputPrice.Text);
}
catch
{
System.Windows.MessageBox.Show("价格不合法!");
return;
}
NewPrice = double.Parse(InputPrice.Text);
}
if (SourceManager.sellerNewPicPath == "")
{
System.Windows.MessageBox.Show("无法获取图片!");
return;
}
GoodsService gS = ServiceFactory.GetGoodsService();
if (!gS.CreateGoods(SourceManager.sellerNewPicPath, NewSuitName, NewPrice, SourceManager.seller._id, SourceManager.seller.manufacturer_id))
{
if (SourceManager.ErrorMessage[0] == 'E')
{
System.Windows.MessageBox.Show("系统错误,请稍后再试。");
LoginWindow lW = new LoginWindow();
lW.Show();
this.Close();
return;
}
System.Windows.MessageBox.Show(SourceManager.ErrorMessage);
return;
}
SourceManager.SellerSuits = new List<Suit>();
SourceManager.sellerLastPageCount = 0;
SourceManager.sellerSuitEnd = false;
SourceManager.sellerSuitPageMax = -1;
System.Windows.MessageBox.Show("添加商品成功。");
}
catch
{
System.Windows.MessageBox.Show("添加商品失败!");
return;
}
}
}
}
|
using System.Collections.Generic;
using NUnit.Framework;
using SimpleJSON;
namespace Tests.SimpleJSON {
[TestFixture]
public class DecoderTests {
private Dictionary<string, string> _stringTestCases;
[SetUp]
public void SetUp() {
_stringTestCases = new Dictionary<string, string>
{
{ "\"string\"", "string" },
{ "\"\\\" \\\\ \\b \\f \\n \\r \\t\"", "\" \\ \b \f \n \r \t" },
{ "\"\\u03A0\"", "\u03A0" },
{ "\"\u0000\"", "\0" },
{ "\"\\uD834\\uDD20\"", "\U0001d120" },
{ "\"\"", "" },
{ "\"\\u00E5\"", "å" }
};
}
[Test]
public void String() {
foreach (var pair in _stringTestCases) {
Assert.AreEqual(pair.Value, (string)DecodeJSON(pair.Key));
}
}
[Test]
public void StringWithWhitespace() {
foreach (var pair in _stringTestCases) {
Assert.AreEqual(pair.Value, (string)DecodeJSON(" " + pair.Key + " "));
}
}
[Test]
public void Whitespaces() {
Assert.AreEqual(123, (int)DecodeJSON(" 123"));
Assert.AreEqual(123, (int)DecodeJSON("\t123"));
Assert.AreEqual(123, (int)DecodeJSON("\n123"));
Assert.AreEqual(123, (int)DecodeJSON("\r123"));
}
[Test]
public void NumberZero() {
var obj = DecodeJSON("0");
Assert.AreEqual(JObjectKind.Number, obj.Kind);
Assert.AreEqual(0, (int)obj);
}
[Test]
public void SimpleValidFloatNumbers() {
Assert.AreEqual(0, DecodeJSON("0").FloatValue);
Assert.AreEqual(0.5f, DecodeJSON("0.5").FloatValue);
Assert.AreEqual(0.05f, DecodeJSON("0.05").FloatValue);
Assert.AreEqual(1, DecodeJSON("1.0").FloatValue);
Assert.AreEqual(13, DecodeJSON("13").FloatValue);
Assert.AreEqual(0, DecodeJSON("-0").FloatValue);
Assert.AreEqual(-0.5f, DecodeJSON("-0.5").FloatValue);
Assert.AreEqual(-0.05f, DecodeJSON("-0.05").FloatValue);
Assert.AreEqual(-1, DecodeJSON("-1.0").FloatValue);
Assert.AreEqual(-13, DecodeJSON("-13").FloatValue);
}
[Test]
public void ExponentialFloatValues() {
Assert.AreEqual(0.5f, DecodeJSON("5e-1").FloatValue);
Assert.AreEqual(50, DecodeJSON("5e1").FloatValue);
Assert.AreEqual(5, DecodeJSON("5e+0").FloatValue);
}
[Test]
public void SByteAndLarger() {
var obj = DecodeJSON("123");
var negObj = DecodeJSON("-123");
Assert.IsFalse(obj.IsFractional);
Assert.IsFalse(obj.IsNegative);
Assert.IsFalse(negObj.IsFractional);
Assert.IsTrue(negObj.IsNegative);
Assert.AreEqual(IntegerSize.Int8, obj.MinInteger);
Assert.AreEqual(IntegerSize.Int8, negObj.MinInteger);
Assert.AreEqual(FloatSize.Single, obj.MinFloat);
Assert.AreEqual(FloatSize.Single, negObj.MinFloat);
Assert.AreEqual(123, (sbyte)obj);
Assert.AreEqual(-123, (sbyte)negObj);
Assert.AreEqual(123, (byte)obj);
Assert.AreEqual(123, (short)obj);
Assert.AreEqual(-123, (short)negObj);
Assert.AreEqual(123, (ushort)obj);
Assert.AreEqual(123, (int)obj);
Assert.AreEqual(-123, (int)negObj);
Assert.AreEqual(123, (uint)obj);
Assert.AreEqual(123, (long)obj);
Assert.AreEqual(-123, (long)negObj);
Assert.AreEqual(123, (ulong)obj);
Assert.AreEqual(123, (float)obj);
Assert.AreEqual(-123, (float)negObj);
Assert.AreEqual(123, (double)obj);
Assert.AreEqual(-123, (double)negObj);
}
[Test]
public void IntAndLarger() {
var obj = DecodeJSON("1000000");
var negObj = DecodeJSON("-1000000");
Assert.IsFalse(obj.IsFractional);
Assert.IsFalse(obj.IsNegative);
Assert.IsFalse(negObj.IsFractional);
Assert.IsTrue(negObj.IsNegative);
Assert.AreEqual(IntegerSize.Int32, obj.MinInteger);
Assert.AreEqual(IntegerSize.Int32, negObj.MinInteger);
Assert.AreEqual(1000000, (int)obj);
Assert.AreEqual(-1000000, (int)negObj);
}
[Test]
public void SingleAndLarger() {
var obj = DecodeJSON("150.5");
var negObj = DecodeJSON("-150.5");
Assert.IsTrue(obj.IsFractional);
Assert.IsFalse(obj.IsNegative);
Assert.IsTrue(negObj.IsFractional);
Assert.IsTrue(negObj.IsNegative);
Assert.AreEqual(FloatSize.Single, obj.MinFloat);
Assert.AreEqual(FloatSize.Single, negObj.MinFloat);
Assert.AreEqual(150.5, (float)obj);
Assert.AreEqual(-150.5, (float)negObj);
Assert.AreEqual(150.5, (double)obj);
Assert.AreEqual(-150.5, (double)negObj);
}
[Test]
public void Null() {
Assert.AreEqual(JObjectKind.Null, DecodeJSON("null").Kind);
}
[Test]
public void NullWithWhitespace() {
Assert.AreEqual(JObjectKind.Null, DecodeJSON(" null ").Kind);
}
[Test]
public void Boolean() {
Assert.IsTrue((bool)DecodeJSON("true"));
Assert.IsFalse((bool)DecodeJSON("false"));
}
[Test]
public void BooleanWithWhitespace() {
Assert.IsTrue((bool)DecodeJSON(" true "));
Assert.IsFalse((bool)DecodeJSON(" false "));
}
[Test]
public void Array() {
var obj = DecodeJSON("[1,\"str\",null]");
Assert.AreEqual(JObjectKind.Array, obj.Kind);
Assert.AreEqual(3, obj.Count);
Assert.AreEqual(1, (int)obj[0]);
Assert.AreEqual("str", (string)obj[1]);
Assert.AreEqual(JObjectKind.Null, obj[2].Kind);
}
[Test]
public void ArrayWithWhitespace() {
var obj = DecodeJSON(" [ 1 , \"str\" , null ] ");
Assert.AreEqual(JObjectKind.Array, obj.Kind);
Assert.AreEqual(3, obj.Count);
Assert.AreEqual(1, (int)obj[0]);
Assert.AreEqual("str", (string)obj[1]);
Assert.AreEqual(JObjectKind.Null, obj[2].Kind);
}
[Test]
public void EmptyArray() {
var obj = DecodeJSON("[]");
Assert.AreEqual(JObjectKind.Array, obj.Kind);
Assert.AreEqual(0, obj.Count);
}
[Test]
public void EmptyArrayWithWhitespace() {
var obj = DecodeJSON(" [ ] ");
Assert.AreEqual(JObjectKind.Array, obj.Kind);
Assert.AreEqual(0, obj.Count);
}
[Test]
public void NestedArrays() {
var obj = DecodeJSON("[1,[2,3],4]");
Assert.AreEqual(3, obj.Count);
Assert.AreEqual(2, obj[1].Count);
Assert.AreEqual(1, (int)obj[0]);
Assert.AreEqual(2, (int)obj[1][0]);
Assert.AreEqual(3, (int)obj[1][1]);
Assert.AreEqual(4, (int)obj[2]);
}
[Test]
public void NestedArraysWithWhitespace() {
var obj = DecodeJSON(" [ 1 , [ 2 , 3 ] , 4 ] ");
Assert.AreEqual(3, obj.Count);
Assert.AreEqual(2, obj[1].Count);
Assert.AreEqual(1, (int)obj[0]);
Assert.AreEqual(2, (int)obj[1][0]);
Assert.AreEqual(3, (int)obj[1][1]);
Assert.AreEqual(4, (int)obj[2]);
}
[Test]
public void NestedEmptyArray() {
var obj = DecodeJSON("[[]]");
Assert.AreEqual(1, obj.Count);
Assert.AreEqual(0, obj[0].Count);
}
[Test]
public void NestedEmptyArrayWithWhitespace() {
var obj = DecodeJSON(" [ [ ] ] ");
Assert.AreEqual(1, obj.Count);
Assert.AreEqual(0, obj[0].Count);
}
[Test]
public void EmptyObject() {
var obj = DecodeJSON("{}");
Assert.AreEqual(0, obj.Count);
Assert.AreEqual(JObjectKind.Object, obj.Kind);
}
[Test]
public void EmptyObjectWithWhitespace() {
var obj = DecodeJSON(" { } ");
Assert.AreEqual(0, obj.Count);
Assert.AreEqual(JObjectKind.Object, obj.Kind);
}
[Test]
public void NestedEmptyObject() {
var obj = DecodeJSON("{\"key\":{}}");
Assert.AreEqual(1, obj.Count);
Assert.AreEqual(0, obj["key"].Count);
}
[Test]
public void NestedEmptyObjectWithWhitespace() {
var obj = DecodeJSON(" { \"key\" : { } } ");
Assert.AreEqual(1, obj.Count);
Assert.AreEqual(0, obj["key"].Count);
}
[Test]
public void Object() {
var obj = DecodeJSON("{\"key1\":12,\"key2\":\"value\"}");
Assert.AreEqual(2, obj.Count);
Assert.AreEqual(JObjectKind.Object, obj.Kind);
Assert.AreEqual(12, (int)obj["key1"]);
Assert.AreEqual("value", (string)obj["key2"]);
}
[Test]
public void ObjectWithWhitespace() {
var obj = DecodeJSON(" { \"key1\" : 12 , \"key2\" : \"value\" } ");
Assert.AreEqual(2, obj.Count);
Assert.AreEqual(JObjectKind.Object, obj.Kind);
Assert.AreEqual(12, (int)obj["key1"]);
Assert.AreEqual("value", (string)obj["key2"]);
}
private static JObject DecodeJSON(string json) {
return JSONDecoder.Decode(json);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace bt.Admin
{
public partial class Suadm : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
getData();
}
}
public void getData()
{
int maloai = Convert.ToInt32(Request.QueryString["maloai"]);
banhang2Entities db = new banhang2Entities();
loaisp obj = db.loaisp.FirstOrDefault(x => x.maloai == maloai);
if (obj == null)
{
Response.Redirect("Danhmuc.aspx");
}
else
{
txtTen.Text = obj.tenloai;
}
}
protected void tbnSua_Click(object sender, EventArgs e)
{
int maloai = Convert.ToInt32(Request.QueryString["maloai"]);
banhang2Entities db = new banhang2Entities();
loaisp obj = db.loaisp.FirstOrDefault(x => x.maloai == maloai);
obj.tenloai = txtTen.Text;
db.SaveChanges();
Response.Redirect("Danhmuc.aspx");
}
}
} |
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using VideoServiceBL.DTOs.MoviesDtos;
using VideoServiceBL.Services.Interfaces;
namespace VideoService.Controllers
{
[Route("api/movies")]
[ApiController]
public class MovieController : Controller
{
private readonly IMovieService _movieService;
public MovieController(IMovieService movieService)
{
_movieService = movieService;
}
[AllowAnonymous]
[HttpGet]
public async Task<QueryResultDto<MovieDto>> GetMoviesAsync([FromQuery] MovieDataTableSettings model)
{
return await
_movieService.GetMovieWithGenreForDataTable(model);
}
[HttpGet("{id}")]
[Authorize(Roles = "Admin,User")]
public async Task<MovieDto> GetMovieByIdAsync(long id)
{
return await
_movieService.GetMovieWithGenreWithCoverByIdAsync(id);
}
[HttpPost("add")]
[Authorize(Roles = "Admin")]
public async Task<MovieDataDto> AddMovieAsync(MovieDataDto movieData)
{
return await _movieService.AddMovieAsync(movieData);
}
[HttpPut("{id}")]
[Authorize(Roles = "Admin")]
public async Task UpdateMovieAsync(int id, MovieDataDto movieData)
{
await _movieService.UpdateMovieAsync(id, movieData);
}
[HttpDelete("{id}")]
[Authorize(Roles = "Admin")]
public async Task<IActionResult> RemoveMovieAsync(long id)
{
await _movieService.RemoveAsync(id);
return Ok();
}
}
}
|
using System;
using MonoTouch.CoreLocation;
using System.Net;
using System.Xml;
using System.Xml.Linq;
using System.Linq;
using System.Collections.Generic;
using MonoTouch.Foundation;
using MonoTouch.CoreFoundation;
using MonoTouch.UIKit;
namespace LondonBike
{
public class MapRouting
{
private CLLocationCoordinate2D Source;
private CLLocationCoordinate2D Dest;
public bool HasRoute = false;
public int Time;
public int Distance;
public CLLocationCoordinate2D[] Points;
public List<CLLocation> PointsList;
public MapRouting (CLLocationCoordinate2D source, CLLocationCoordinate2D dest)
{
Source = source;
Dest = dest;
}
public string TimeForDisplay
{
get
{
if (Time == 0) return "Not available";
TimeSpan ts = new TimeSpan(0,0,Time);
return string.Format("{0:0.0} mins", ts.TotalMinutes);
}
}
public string DistanceForDisplay
{
get
{
if (Distance == 0) return "Not available";
float distance = Distance;
using (var defaults = NSUserDefaults.StandardUserDefaults)
{
if (!defaults.BoolForKey("UseKMs"))
{
distance = Util.MetersToMiles(distance);
return string.Format("{0:0.00}mi", distance);
} else
{
if (distance > 1000)
{
distance = distance / 1000;
return string.Format("{0:0.00}km", distance);
}
return string.Format("{0}m", distance);
}
}
}
}
public void FindRoute(NSAction callbackWhenDone)
{
using (var defaults = NSUserDefaults.StandardUserDefaults)
{
string routingType = defaults.StringForKey("routing_type");
if (string.IsNullOrEmpty(routingType)) routingType = "cyclestreets-fastest";
Util.Log("using routing: " + routingType);
switch(routingType)
{ //balanced|fastest|quietest|shortest
case "cyclestreets-fastest":
FindCycleRouteRoute("fastest", callbackWhenDone);
break;
case "cyclestreets-balanced":
FindCycleRouteRoute("balanced", callbackWhenDone);
break;
case "cyclestreets-quietest":
FindCycleRouteRoute("quietest", callbackWhenDone);
break;
case "cloudmade":
FindCloudmadeRoute(callbackWhenDone);
break;
default:
FindCycleRouteRoute("fastest", callbackWhenDone);
break;
}
}
}
// you need to go to cloudmade and get a key!
const string locationUrl = "http://routes.cloudmade.com/KEYS_GO_HERE/api/0.3/{0},{1},{2},{3}/bicycle.gpx?lang=en&unit=km&token={4}";
public void FindCloudmadeRoute(NSAction callbackWhenDone)
{
Util.Log ("YOU NEED TO GET A CLOUDMADE KEY FOR THIS TO WORK");
wc = new WebClient();
string deviceId = UIDevice.CurrentDevice.UniqueIdentifier;
string tokenUrl = string.Format("http://auth.cloudmade.com/token/KEYS_GO_HERE?userid={0}",
deviceId.Substring(5, deviceId.Length - 5));
string token = wc.UploadString(tokenUrl, "");
wc = new WebClient();
string url = string.Format(locationUrl, Source.Latitude, Source.Longitude, Dest.Latitude, Dest.Longitude, token);
Console.WriteLine(url);
StartWatchdogTimer();
wc.DownloadStringCompleted += delegate(object sender, DownloadStringCompletedEventArgs e) {
using (var pool = new NSAutoreleasePool())
{
StopWatchdogTimer();
if (e.Cancelled)
{
HasRoute = false;
callbackWhenDone();
return;
}
try
{
string output = e.Result;
Util.Log(output);
XNamespace gpxNamespace = "http://www.topografix.com/GPX/1/1";
XElement root = XElement.Parse(output);
var extensionElement = root.Element(gpxNamespace + "extensions");
if (!Int32.TryParse(extensionElement.Element(gpxNamespace + "distance").Value, out Distance)) Distance = 0;
if (!Int32.TryParse(extensionElement.Element(gpxNamespace + "time").Value, out Time)) Time = 0;
var gpxitems = from gpxitem in root.Elements(gpxNamespace + "wpt")
select new CLLocationCoordinate2D() {
Latitude = double.Parse(gpxitem.Attribute("lat").Value),
Longitude = double.Parse(gpxitem.Attribute("lon").Value)
};
Points = gpxitems.ToArray();
PointsList = new List<CLLocation>();
foreach(var point in Points)
{
PointsList.Add(new CLLocation(point.Latitude, point.Longitude));
}
HasRoute = true;
} catch (Exception ex)
{
HasRoute = false;
Util.Log(ex.Message);
}
callbackWhenDone();
}
};
wc.DownloadStringAsync(new Uri(url));
}
//Get a key from cyclestreets.net
const string cycleStreetsLocationUrl = @"http://www.cyclestreets.net/api/journey.xml?key=CYCLE_STREETSKEY_HERE&start_longitude={1}&start_latitude={0}&finish_longitude={3}&finish_latitude={2}&plan={4}&segments=0";
WebClient wc = null;
NSTimer watchdogTimer = null;
private void StartWatchdogTimer()
{
watchdogTimer = NSTimer.CreateScheduledTimer(new TimeSpan(0,0,15), delegate {
Console.WriteLine("cancelled");
wc.CancelAsync();
HasRoute = false;
});
}
private void StopWatchdogTimer()
{
if (watchdogTimer != null)
{
watchdogTimer.Invalidate();
watchdogTimer = null;
}
}
public void FindCycleRouteRoute(string type, NSAction callbackWhenDone)
{
wc = new WebClient();
string url = string.Format(cycleStreetsLocationUrl, Source.Latitude, Source.Longitude, Dest.Latitude, Dest.Longitude, type);
Util.Log(url);
StartWatchdogTimer();
wc.DownloadStringCompleted += delegate(object sender, DownloadStringCompletedEventArgs e) {
using (var pool = new NSAutoreleasePool())
{
StopWatchdogTimer();
if (e.Cancelled)
{
HasRoute = false;
callbackWhenDone();
return;
}
try
{
string output = e.Result;
if (output.Contains("type=\"error\""))
{
HasRoute = false;
callbackWhenDone();
return;
}
XElement root = XElement.Parse(output);
var firstElement = root.Element("marker");
if (!Int32.TryParse(firstElement.Attribute("time").Value, out Time)) Time = 0;
if (!Int32.TryParse(firstElement.Attribute("length").Value, out Distance)) Distance = 0;
string elements = firstElement.Attribute("coordinates").Value;
string[] elementitems = elements.Split(' ');
List<CLLocationCoordinate2D> coordlist = new List<CLLocationCoordinate2D>();
foreach(string coord in elementitems)
{
string[] coords = coord.Split(',');
double lat, lon;
bool worked = double.TryParse(coords[0], out lon) && double.TryParse(coords[1], out lat);
if (worked)
{
coordlist.Add(new CLLocationCoordinate2D(lat, lon));
}
}
Points = coordlist.ToArray();
PointsList = new List<CLLocation>();
foreach(var point in Points)
{
PointsList.Add(new CLLocation(point.Latitude, point.Longitude));
}
HasRoute = true;
} catch (Exception ex) {
HasRoute = false;
}
callbackWhenDone();
}
};
wc.DownloadStringAsync(new Uri(url));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cognitive_Metier
{
public class ResultKeyphraseJson
{
public List<DocumentKeyphraseResult> documents { get; set; }
public List<Error> errors { get; set; }
}
}
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Text;
using TableTopCrucible.Domain.Models.Sources;
using TableTopCrucible.Domain.Models.ValueTypes.IDs;
using TableTopCrucible.Domain.Models.ValueTypes;
using System.Text.Json;
using System.IO;
using TableTopCrucible.Data.SaveFile.DataTransferObjects;
namespace TableTopCrucible.Data.SaveFile.Tests.DataTransferObjects
{
[TestClass]
public class DirectorySetupDtoTests
{
private DirectorySetup createTestEntity()
=> new DirectorySetup(new Uri(@"C:\test\test.test"), (DirectorySetupName)"testDir", (Description)"testDesc", DirectorySetupId.New(), DateTime.Now.AddMinutes(-5), DateTime.Now);
void compareEntityToDto(DirectorySetup entity, DirectorySetupDTO dto)
{
Assert.AreEqual((Guid)entity.Id, dto.Id, "faulty id");
Assert.AreEqual(entity.Created, dto.Created, "faulty creation timestamp");
Assert.AreEqual(entity.LastChange, dto.LastChange, "faulty last change timestamp");
Assert.AreEqual(entity.Path, dto.Path, "faulty path");
Assert.AreEqual((string)entity.Name, dto.Name, "faulty name");
Assert.AreEqual((string)entity.Description, dto.Description, "faulty description");
}
void compareEntities(DirectorySetup entityA, DirectorySetup entityB)
{
Assert.AreEqual(entityA.Id, entityB.Id, "faulty id");
Assert.AreEqual(entityA.Created, entityB.Created, "faulty creation timestamp");
Assert.AreEqual(entityA.LastChange, entityB.LastChange, "faulty last change timestamp");
Assert.AreEqual(entityA.Path, entityB.Path, "faulty path");
Assert.AreEqual(entityA.Name, entityB.Name, "faulty name");
Assert.AreEqual(entityA.Description, entityB.Description, "faulty description");
Assert.AreNotEqual(entityA.Identity, entityB.Identity, "it's the same instance");
}
[TestMethod]
public void Entity_to_dto_works()
{
var entity = createTestEntity();
var dto = new DirectorySetupDTO(entity);
compareEntityToDto(entity, dto);
}
[TestMethod]
public void Dto_to_entity_works()
{
var dto = new DirectorySetupDTO(createTestEntity());
var entity = dto.ToEntity();
compareEntityToDto(entity, dto);
}
[TestMethod]
public void serialization_works()
{
var srcEntity = createTestEntity();
var srcDto = new DirectorySetupDTO(srcEntity);
var str = JsonSerializer.Serialize(srcDto);
var dstDto = JsonSerializer.Deserialize<DirectorySetupDTO>(str);
var dstEntity = dstDto.ToEntity();
compareEntities(srcEntity, dstEntity);
}
}
} |
using UnityEngine;
using System.Collections;
public class PlayerMelee : MonoBehaviour {
public float attackTimer;
public float coolDown;
public int damage;
private GameObject target;
private GameObject[] objectList;
private GameObject closest;
private float distance;
private float direction;
private Vector3 position;
private Vector3 dir;
private Transform targetHealthBar;
private Health eh;
void Start() {
attackTimer = 0;
coolDown = 1.0f;
damage = -34;
}
void Update() {
// Find enemy
target = FindClosestEnemy();
if (target != null) {
// Find enemy health
eh = (Health)target.GetComponent ("Health");
if (eh != null) {
// Find enemy health bar (green part)
targetHealthBar = eh.HealthBarGreen.transform;
// Find distance to enemy
distance = Vector3.Distance (target.transform.position, transform.position);
if (attackTimer > 0)
attackTimer -= Time.deltaTime;
if (attackTimer < 0)
attackTimer = 0;
if (distance < 2.5f) {
if (InputManager.GetAttackButton (this.name)) {
if (attackTimer == 0) {
Attack ();
attackTimer = coolDown;
}
}
}
}
}
}
private void Attack() {
dir = (target.transform.position - transform.position).normalized;
direction = Vector3.Dot(dir, transform.forward);
Debug.Log("Distance to Enemy: " + distance);
Debug.Log("Direction to Enemy: " + direction);
if (distance < 2.5f) {
if (direction > 0) {
// Adjust enemy health
eh.AdjustCurrentHealth (damage);
// Adjust enemy health bar
float ratio = damage / eh.maxHealth;
targetHealthBar.transform.localScale -= new Vector3 (0.34f,0,0);
// Knockback (maybe later)
//target.GetComponent<Rigidbody>().AddForce(dir);
if (eh.curHealth == 0) {
target.SetActive (false);
}
}
}
}
private GameObject FindClosestEnemy() {
objectList = GameObject.FindGameObjectsWithTag("Enemy");
closest = null;
distance = Mathf.Infinity;
position = transform.position;
foreach (GameObject gameobject in objectList) {
Vector3 diff = gameobject.transform.position - position;
float curDistance = diff.sqrMagnitude;
if (curDistance < distance) {
closest = gameobject;
distance = curDistance;
}
}
return closest;
}
} |
using apiInovaPP.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace apiInovaPP.AcessoDados
{
public class Parametros
{
public List<Parametro> Params { get; set; }
public Parametros()
{
Params = new List<Parametro>();
}
public void Add(object _Parametro, object _Valor)
{
Params.Add(new Parametro(_Parametro,_Valor));
}
public int Count()
{
return Params.Count;
}
public void Clear()
{
Params.Clear();
}
}
} |
using System;
using System.Globalization;
namespace MicrosoftGraphApplicationAuth
{
public class GraphConfig : IGraphConfig
{
private const string InstanceTemplate = "https://login.microsoftonline.com/{0}";
public string ApiUri => "https://graph.microsoft.com";
public string ApplicationId => "TODO: PUT APPLICATION ID HERE";
public string Tenant => "TODO: PUT TENANT ID HERE";
public string ClientId => "TODO: PUT CLIENT ID HERE";
public string ClientSecret => "TODO: RETURN SECRET FROM HERE";
public Uri Authority => new Uri(string.Format(CultureInfo.InvariantCulture, InstanceTemplate, Tenant));
public string HttpProxyHost => string.Empty;
public int? HttpProxyPort => 0;
}
} |
using LuaInterface;
using SLua;
using System;
using UnityEngine;
public class Lua_UnityEngine_LOD : LuaObject
{
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int constructor(IntPtr l)
{
int result;
try
{
float num;
LuaObject.checkType(l, 2, out num);
Renderer[] array;
LuaObject.checkArray<Renderer>(l, 3, out array);
LOD lOD = new LOD(num, array);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, lOD);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_screenRelativeTransitionHeight(IntPtr l)
{
int result;
try
{
LOD lOD;
LuaObject.checkValueType<LOD>(l, 1, out lOD);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, lOD.screenRelativeTransitionHeight);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_screenRelativeTransitionHeight(IntPtr l)
{
int result;
try
{
LOD lOD;
LuaObject.checkValueType<LOD>(l, 1, out lOD);
float screenRelativeTransitionHeight;
LuaObject.checkType(l, 2, out screenRelativeTransitionHeight);
lOD.screenRelativeTransitionHeight = screenRelativeTransitionHeight;
LuaObject.setBack(l, lOD);
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_fadeTransitionWidth(IntPtr l)
{
int result;
try
{
LOD lOD;
LuaObject.checkValueType<LOD>(l, 1, out lOD);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, lOD.fadeTransitionWidth);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_fadeTransitionWidth(IntPtr l)
{
int result;
try
{
LOD lOD;
LuaObject.checkValueType<LOD>(l, 1, out lOD);
float fadeTransitionWidth;
LuaObject.checkType(l, 2, out fadeTransitionWidth);
lOD.fadeTransitionWidth = fadeTransitionWidth;
LuaObject.setBack(l, lOD);
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_renderers(IntPtr l)
{
int result;
try
{
LOD lOD;
LuaObject.checkValueType<LOD>(l, 1, out lOD);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, lOD.renderers);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_renderers(IntPtr l)
{
int result;
try
{
LOD lOD;
LuaObject.checkValueType<LOD>(l, 1, out lOD);
Renderer[] renderers;
LuaObject.checkArray<Renderer>(l, 2, out renderers);
lOD.renderers = renderers;
LuaObject.setBack(l, lOD);
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, "UnityEngine.LOD");
LuaObject.addMember(l, "screenRelativeTransitionHeight", new LuaCSFunction(Lua_UnityEngine_LOD.get_screenRelativeTransitionHeight), new LuaCSFunction(Lua_UnityEngine_LOD.set_screenRelativeTransitionHeight), true);
LuaObject.addMember(l, "fadeTransitionWidth", new LuaCSFunction(Lua_UnityEngine_LOD.get_fadeTransitionWidth), new LuaCSFunction(Lua_UnityEngine_LOD.set_fadeTransitionWidth), true);
LuaObject.addMember(l, "renderers", new LuaCSFunction(Lua_UnityEngine_LOD.get_renderers), new LuaCSFunction(Lua_UnityEngine_LOD.set_renderers), true);
LuaObject.createTypeMetatable(l, new LuaCSFunction(Lua_UnityEngine_LOD.constructor), typeof(LOD), typeof(ValueType));
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ERP_Palmeiras_RH.Models;
using ERP_Palmeiras_RH.Models.Facade;
namespace ERP_Palmeiras_RH.Controllers
{
[HandleERPException]
public class PermissoesController : BaseController
{
private RecursosHumanos facade = RecursosHumanos.GetInstance();
public ActionResult Index()
{
IEnumerable<Permissao> permissoes = facade.BuscarPermissoes();
ViewBag.permissoes = permissoes;
return View();
}
public ActionResult Criar(String nome)
{
if (nome != null)
{
Permissao perm = new Permissao();
perm.Nome = nome;
facade.InserirPermissao(perm);
return RedirectToAction("Index");
}
return View();
}
public ActionResult Excluir(Int32 pid)
{
facade.ExcluirPermissao(pid);
return RedirectToAction("Index");
}
}
}
|
using System.Net;
using Newtonsoft.Json;
using RestSharp;
using TrafficControl.DAL.RestSharp.Types;
namespace TrafficControl.DAL.RestSharp
{
/// <summary>
/// Denne klasse har ansvar for at API kald der omhandler User
/// </summary>
/// <remarks>nedarvet fra TCDATA<list type="User"></list></remarks>
public class TCDataUser : TCData<User>
{
/// <summary>
/// sætter suburl til det rigtige
/// </summary>
public TCDataUser()
{
LIB = new TCDataConnection {ApiDirectory = "api/Account/"};
}
/// <summary>
/// Håndtere oprettelse af nye Bruger
/// </summary>
/// <param name="email"></param>
/// <param name="password"></param>
/// <param name="confirmedpassword"> skriv password igen </param>
/// <param name="firstname"></param>
/// <param name="lastname"></param>
/// <param name="roles"> 0/1/2 for de forskellige roller </param>
/// <param name="number"> mobil- eller telefonnummer</param>
/// <returns> True på Succes, else False </returns>
public bool Post(string email, string password, string confirmedpassword, string firstname,
string lastname, int roles, string number)
{
var transferOjbectToWebApi = new AccountDTO
{
ConfirmPassword = confirmedpassword,
Email = email,
Password = password,
FirstName = firstname,
LastName = lastname,
Role = roles,
PhoneNumber = number
};
var response = LIB.TCAPIconnection("Register/", Method.POST, transferOjbectToWebApi);
return response.StatusCode == HttpStatusCode.OK;
}
/// <summary>
/// bruges ikke
/// </summary>
/// <param name="obj"></param>
/// <returns>False</returns>
public override bool Post(User obj)
{
return false;
}
/// <summary>
/// Hvis man skal skifte kode
/// </summary>
/// <param name="oPassword"> den gamle kode</param>
/// <param name="nPassword">den nye kode</param>
/// <param name="cPassword">den nye kode</param>
/// <returns> True på Succes, False på Failures </returns>
public bool ChangePassword(string oPassword, string nPassword, string cPassword)
{
var myRequestFormatInJsonThatNeedToBeFeedToWebApi = new ChangePasswordDTO
{
OldPassword = oPassword,
NewPassword = nPassword,
ConfirmPassword = cPassword
};
var response = LIB.TCAPIconnection("ChangePassword/", Method.POST,
myRequestFormatInJsonThatNeedToBeFeedToWebApi);
return response.StatusCode == HttpStatusCode.OK;
}
/// <summary>
/// giver spefik user
/// </summary>
/// <param name="id"> id på given user</param>
/// <returns>User object</returns>
public User Get(string id)
{
var response = LIB.TCAPIconnection("UserInfo/", Method.GET, id);
if (response.StatusCode != HttpStatusCode.OK) return new User();
var retval = JsonConvert.DeserializeObject<User>(response.Content);
return retval;
}
/// <summary>
/// Bruges ikke
/// </summary>
/// <param name="id"></param>
/// <returns>Returner bare en tomt objekt</returns>
public override User Get(long id)
{
return new User();
}
/// <summary>
/// Bruges til opdatering a user
/// </summary>
/// <param name="user">et user objekt</param>
/// <returns>True på Succes, False på Failure</returns>
public override bool Update(User user)
{
var tmp = new UpdateUserInfoDTO
{
EmailNotification = user.EmailNotification,
FirstName = user.FirstName,
LastName = user.LastName,
PhoneNumber = user.Number,
SMSNotification = user.SMSNotification
};
var response = LIB.TCAPIconnection("UserInfo/", Method.PUT, tmp);
return response.StatusCode == HttpStatusCode.OK;
}
/// <summary>
/// At logge ud på user
/// </summary>
/// <returns>True på Succes, False på Failure</returns>
public bool LogOut()
{
TCDataConnection.Token = string.Empty;
var response = LIB.TCAPIconnection("Logout/", Method.POST);
return response.StatusCode == HttpStatusCode.OK;
}
}
} |
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;
using DevExpress.XtraEditors;
using System.Reflection;
namespace Vendo.UcBase
{
public partial class ucBase : XtraUserControl
{
private const string INFORMATIVO = "Informativo";
private const string AVISO = "Aviso";
private const string ERROR = "Error";
public ucBase()
{
InitializeComponent();
}
protected DialogResult MensajeInformativo(string msj)
{
return MessageBox.Show(msj, INFORMATIVO, MessageBoxButtons.OK, MessageBoxIcon.Information);
}
protected DialogResult MensajeAviso(string msj)
{
return MessageBox.Show(msj, AVISO, MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
protected DialogResult MensajePregunta(string msj)
{
return MessageBox.Show(msj, INFORMATIVO, MessageBoxButtons.YesNo, MessageBoxIcon.Information);
}
protected DialogResult MensajePreguntaCanel(string msj)
{
return MessageBox.Show(msj, INFORMATIVO, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Information);
}
protected DialogResult MensajeError(string msj)
{
return MessageBox.Show(msj, ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
private void ucBase_Load(object sender, EventArgs e)
{
Dock = DockStyle.Fill;
}
public XtraUserControl CreateInstance(string objectName)
{
object obj;
try
{
if (objectName.LastIndexOf(".") == -1)
{
objectName = Assembly.GetEntryAssembly().GetName().Name + "." + objectName;
}
var ass = Assembly.GetEntryAssembly().GetName().Name;
obj = Assembly.GetEntryAssembly().CreateInstance(objectName);
}
catch (Exception ex)
{
obj = null;
}
return (XtraUserControl)obj;
}
}
}
|
using System;
using System.Collections.Generic;
namespace SheMediaConverterClean.Infra.Data.Models
{
public partial class VwStatistik
{
public int Id { get; set; }
public string Name { get; set; }
public bool? MultiSelect { get; set; }
}
}
|
using System;
namespace exe_16
{
class Program
{
static void Main(string[] args)
{
Console.Clear();
System.Console.WriteLine("======* Calculador IMC *======");
System.Console.WriteLine();
System.Console.Write("Insira seu peso em KG: ");
double peso = double.Parse(Console.ReadLine());
System.Console.Write("Insira sua altura em metros (ex: 1,70): ");
double alt = double.Parse(Console.ReadLine());
System.Console.WriteLine();
double imc = peso / (alt * alt);
System.Console.WriteLine($"Seu IMC é: {imc}");
if (imc < 20)
{
System.Console.WriteLine("Está abaixo do peso");
} else if (imc >= 21 && imc <= 25)
{
System.Console.WriteLine("Está em um peso de categoria normal");
} else if (imc > 25 && imc <= 30)
{
System.Console.WriteLine("Está acima do peso, excesso de peso");
} else if (imc > 30 && imc <= 35)
{
System.Console.WriteLine("Obesidade");
} else if (imc > 35 )
{
System.Console.WriteLine("Obesidade mórbida");
}
}
}
}
|
/*
* Copyright 2014 Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System.Windows;
using System.Windows.Controls;
using JetBrains.Application.DataContext;
using JetBrains.Application.Settings;
using JetBrains.Application.UI.Options;
using JetBrains.Application.UI.UIAutomation;
using JetBrains.DataFlow;
using JetBrains.ReSharper.Features.Navigation.Resources;
using KaVE.RS.Commons;
using KaVE.VS.FeedbackGenerator.Settings;
using KaVE.VS.FeedbackGenerator.Settings.ExportSettingsSuite;
using KaVE.VS.FeedbackGenerator.Utils;
using KaVEISettingsStore = KaVE.RS.Commons.Settings.ISettingsStore;
namespace KaVE.VS.FeedbackGenerator.UserControls.OptionPage.GeneralOptions
{
[OptionsPage(
PID,
"General Settings",
typeof(FeaturesFindingThemedIcons.SearchOptionsPage),
ParentId = RootOptionPage.PID,
Sequence = 1.0)]
public partial class GeneralOptionsControl : IOptionsPage
{
private const string PID =
"KaVE.VS.FeedbackGenerator.UserControls.OptionPage.GeneralOptions.GeneralOptionsControl";
public const ResetTypes GeneralSettingsResetType = ResetTypes.GeneralSettings;
public const ResetTypes FeedbackResetType = ResetTypes.Feedback;
private readonly Lifetime _lifetime;
private readonly OptionsSettingsSmartContext _ctx;
private readonly IActionExecutor _actionExecutor;
private readonly KaVEISettingsStore _settingsStore;
private readonly DataContexts _dataContexts;
private readonly ExportSettings _exportSettings;
private readonly IMessageBoxCreator _messageBoxCreator;
public GeneralOptionsControl(Lifetime lifetime,
OptionsSettingsSmartContext ctx,
IActionExecutor actionExecutor,
KaVEISettingsStore settingsStore,
DataContexts dataContexts,
IMessageBoxCreator messageBoxCreator)
{
_messageBoxCreator = messageBoxCreator;
_lifetime = lifetime;
_ctx = ctx;
_actionExecutor = actionExecutor;
_settingsStore = settingsStore;
_dataContexts = dataContexts;
InitializeComponent();
_exportSettings = settingsStore.GetSettings<ExportSettings>();
DataContext = new GeneralOptionsViewModel
{
ExportSettings = _exportSettings
};
if (_ctx != null)
{
BindToGeneralChanges();
}
}
private void OnResetSettings(object sender, RoutedEventArgs e)
{
var result = _messageBoxCreator.ShowYesNo(GeneralOptionsMessages.SettingResetDialog);
if (result)
{
var settingResetType = new SettingResetType {ResetType = GeneralSettingsResetType};
_actionExecutor.ExecuteActionGuarded<SettingsCleaner>(
settingResetType.GetDataContextForSettingResultType(_dataContexts, _lifetime));
var window = Window.GetWindow(this);
if (window != null)
{
window.Close();
}
}
}
private void OnResetFeedback(object sender, RoutedEventArgs e)
{
var result = _messageBoxCreator.ShowYesNo(GeneralOptionsMessages.FeedbackResetDialog);
if (result)
{
var settingResetType = new SettingResetType {ResetType = FeedbackResetType};
_actionExecutor.ExecuteActionGuarded<SettingsCleaner>(
settingResetType.GetDataContextForSettingResultType(_dataContexts, _lifetime));
var window = Window.GetWindow(this);
if (window != null)
{
window.Close();
}
}
}
public bool OnOk()
{
// TODO: validation
_settingsStore.SetSettings(_exportSettings);
return true;
}
public bool ValidatePage()
{
return true;
}
public EitherControl Control
{
get { return this; }
}
public string Id
{
get { return PID; }
}
#region jetbrains smart-context bindings
private void BindToGeneralChanges()
{
_ctx.SetBinding(
_lifetime,
(ExportSettings s) => s.UploadUrl,
UploadUrlTextBox,
TextBox.TextProperty);
_ctx.SetBinding(
_lifetime,
(ExportSettings s) => s.WebAccessPrefix,
WebPraefixTextBox,
TextBox.TextProperty);
}
#endregion
}
} |
using Logs.Authentication.Managers;
using Logs.Models;
using Logs.Providers.Contracts;
using Microsoft.AspNet.Identity;
using Microsoft.Owin.Security;
using Moq;
using NUnit.Framework;
namespace Logs.Authentication.Tests.AuthenticationProviderTests
{
[TestFixture]
public class RegisterAndLoginUserTests
{
[TestCase("password", true, true)]
public void TestRegisterAndLoginUser_ShouldCallUserManagerCreate(string password, bool isPersistent, bool rememberBrowser)
{
// Arrange
var mockedDateTimeProvider = new Mock<IDateTimeProvider>();
var mockedUserStore = new Mock<IUserStore<User>>();
var mockedUserManager = new Mock<ApplicationUserManager>(mockedUserStore.Object);
mockedUserManager.Setup(m => m.CreateAsync(It.IsAny<User>(), It.IsAny<string>()))
.ReturnsAsync(new IdentityResult());
var mockedHttpContextProvider = new Mock<IHttpContextProvider>();
mockedHttpContextProvider.Setup(p => p.GetUserManager<ApplicationUserManager>()).Returns(mockedUserManager.Object);
var provider = new AuthenticationProvider(mockedDateTimeProvider.Object, mockedHttpContextProvider.Object);
var user = new User();
// Act
provider.RegisterAndLoginUser(user, password, isPersistent, rememberBrowser);
// Assert
mockedUserManager.Verify(m => m.CreateAsync(user, password), Times.Once);
}
[TestCase("password", true, true)]
public void TestRegisterAndLoginUser_ReturnsSuccess_ShouldCallSignInManagerSignIn(string password, bool isPersistent, bool rememberBrowser)
{
// Arrange
var mockedDateTimeProvider = new Mock<IDateTimeProvider>();
var mockedUserStore = new Mock<IUserStore<User>>();
var mockedUserManager = new Mock<ApplicationUserManager>(mockedUserStore.Object);
mockedUserManager.Setup(m => m.CreateAsync(It.IsAny<User>(), It.IsAny<string>()))
.ReturnsAsync(IdentityResult.Success);
var mockedAuthenticationManager = new Mock<IAuthenticationManager>();
var mockedSignInManager = new Mock<ApplicationSignInManager>(mockedUserManager.Object, mockedAuthenticationManager.Object);
var mockedHttpContextProvider = new Mock<IHttpContextProvider>();
mockedHttpContextProvider.Setup(p => p.GetUserManager<ApplicationUserManager>()).Returns(mockedUserManager.Object);
mockedHttpContextProvider.Setup(p => p.GetUserManager<ApplicationSignInManager>()).Returns(mockedSignInManager.Object);
var provider = new AuthenticationProvider(mockedDateTimeProvider.Object, mockedHttpContextProvider.Object);
var user = new User();
// Act
provider.RegisterAndLoginUser(user, password, isPersistent, rememberBrowser);
// Assert
mockedSignInManager.Verify(s => s.SignInAsync(user, isPersistent, rememberBrowser));
}
[TestCase("password", true, true)]
public void TestRegisterAndLoginUser_ShouldReturnCorrectly(string password, bool isPersistent, bool rememberBrowser)
{
// Arrange
var mockedDateTimeProvider = new Mock<IDateTimeProvider>();
var result = new IdentityResult();
var mockedUserStore = new Mock<IUserStore<User>>();
var mockedUserManager = new Mock<ApplicationUserManager>(mockedUserStore.Object);
mockedUserManager.Setup(m => m.CreateAsync(It.IsAny<User>(), It.IsAny<string>()))
.ReturnsAsync(result);
var mockedHttpContextProvider = new Mock<IHttpContextProvider>();
mockedHttpContextProvider.Setup(p => p.GetUserManager<ApplicationUserManager>()).Returns(mockedUserManager.Object);
var provider = new AuthenticationProvider(mockedDateTimeProvider.Object, mockedHttpContextProvider.Object);
var user = new User();
// Act
var actualResult = provider.RegisterAndLoginUser(user, password, isPersistent, rememberBrowser);
// Assert
Assert.AreSame(result, actualResult);
}
}
}
|
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;
namespace PROJETOBDDEDE
{
public partial class frmAddProf : Form
{
SchoolManagerDataSetTableAdapters.ProfessorTableAdapter ProfTA = new SchoolManagerDataSetTableAdapters.ProfessorTableAdapter();
public frmAddProf()
{
InitializeComponent();
}
private void btnEnviar_Click(object sender, EventArgs e)
{
try
{
ProfTA.Addprof(msk_Cpf.Text, txt_Nome.Text, txt_ClasseResp.Text, msk_txt_Tel.Text, txt_Email.Text, txt_Materia.Text);
MessageBox.Show("Professor Cadastrado!", "", MessageBoxButtons.OK);
}
catch(Exception ex)
{
MessageBox.Show("Não foi possível adicionar o professor! Erro:" + ex.Message, "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void pictureBox1_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class InteractableObjectManager : MonoBehaviour
{
// Enums
public enum InteractType
{
Pick = 0,
Read,
Talk
}
[Header("Interaction type")]
// Tipo de interação
// 0 - Pegar, 1 - Ler, 2 - Falar
[SerializeField]
private InteractType _interactionType = 0;
[Header("Interaction message")]
[SerializeField]
private Dialogue _dialogue;
private void OnTriggerStay2D(Collider2D collision)
{
// If the collision object is the player and he press E
if (collision.tag == "Player" && Input.GetKeyDown(KeyCode.E))
{
// Get player controller
PlayerController playerController = collision.GetComponent<PlayerController>();
// If it don't exists do nothing
if (!playerController)
{
return;
}
// Interact
playerController.Interact(_interactionType, _dialogue);
}
}
}
|
using DB.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace DB.Interfaces
{
public interface IDbRepository<TEntity> where TEntity:BaseEntity
{
/// <summary>
/// Получениие параметризируемых объектов из бд
/// </summary>
/// <returns>IQueryable дженерик объект</returns>
IQueryable<TEntity> Get();
/// <summary>
/// Асинхронный метод добавления дженерик сущности в таблицу
/// </summary>
/// <param name="entity">Объект для добавления в таблицу</param>
/// <returns></returns>
Task AddAsync(TEntity entity);
/// <summary>
/// Асинхронный метод обновления дженерик сущности в таблице
/// </summary>
/// <param name="entity">Объект для обновления в таблице</param>
/// <returns></returns>
Task UpdateAsync(TEntity entity);
/// <summary>
/// Асинхронный метод удаления дженерик сущности из таблицы
/// </summary>
/// <param name="entity">Объект для удаления из таблицы</param>
/// <returns></returns>
Task DeleteAsync(TEntity entity);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PHRApp.Classes
{
public class PlayList
{
[SQLite.PrimaryKey]
public string PlName { get; set; }
public string Theme { get; set; }
public DateTime PlayDateTime { get; set; }
public bool IsPrivate { get; set; }
public string Description { get; set; }
public string TitleName { get; set; }
public List<PlayList> GetPlayLists(Title title)//Gist - how making the 1 to Many
{
List<PlayList> playLists = new List<PlayList>();
using (var db = new SQLite.SQLiteConnection(App.DBPath))
{
var query = db.Table<PlayList>()
.Where(pl => pl.TitleName == title.TitleName)//Gist - how making the 1 to Many
.OrderBy(pl => pl.PlName);
foreach (var playList in query)
{
playLists.Add(playList);
}
}
return playLists;
}
public void UpdatePlayList(PlayList playList)
{
using (var db = new SQLite.SQLiteConnection(App.DBPath))
{
try
{
db.Update(playList);
}
catch (Exception) { }
}
}
public void DeletePlayList(PlayList playList)
{
using (var db = new SQLite.SQLiteConnection(App.DBPath))
{
try
{
db.Delete(playList);
}
catch (Exception) { }
}
}
public void InsertPlayList(PlayList playList)
{
using (var db = new SQLite.SQLiteConnection(App.DBPath))
{
try
{
var existingPlayList = (db.Table<PlayList>()
.Where(pl => pl.PlName == playList.PlName))
.SingleOrDefault();
if (existingPlayList != null)
{
existingPlayList.PlName = playList.PlName;
existingPlayList.Theme = playList.Theme;
existingPlayList.PlayDateTime = playList.PlayDateTime;
existingPlayList.IsPrivate = playList.IsPrivate;
existingPlayList.Description = playList.Description;
this.UpdatePlayList(playList);
}
else
{
db.Insert(playList);
}
}
catch (Exception) { }
}
}
}
}
|
using System.Data;
using PDV.CONTROLER.Funcoes;
namespace PDV.REPORTS.Reports.FechamentoCaixaDiarioTermica
{
public partial class FechamentoCaixaDiario_RecebimentosTermica : DevExpress.XtraReports.UI.XtraReport
{
private decimal IDFLUXOCAIXA;
public FechamentoCaixaDiario_RecebimentosTermica(decimal IDFluxoCaixa)
{
InitializeComponent();
IDFLUXOCAIXA = IDFluxoCaixa;
}
private void FechamentoCaixaDiario_PagamentosTermica_BeforePrint(object sender, System.Drawing.Printing.PrintEventArgs e)
{
DataTable dt = FuncoesContaReceber.GetContasReceberPorFluxoCaixa(IDFLUXOCAIXA);
if (dt.Rows.Count == 0)
{
e.Cancel = true;
return;
}
dt.TableName = "DADOS";
ovDS_Dados.Tables.Clear();
ovDS_Dados.Tables.Add(dt);
}
}
}
|
using HardwareInventoryManager.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace HardwareInventoryManager.Helpers.Messaging
{
public interface IProcessEmail
{
void SendPasswordResetEmail(ApplicationUser recipientUser, string callbackUrl);
void SendEmailConfirmationEmail(ApplicationUser recipientUser, string callbackUrl);
void SendNewAccountSetupEmail(ApplicationUser recipientUser);
void SendEmail(string senderEmailAddress, string[] recipientsEmailAddresses, string subject, string body);
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using PnrAnalysis;
namespace BPiaoBao.Common.CommanPnrAnalyzer
{
public class PnrFormattor
{
public string pnrContext;
public string pnrPat;
public PnrFormattor(string context)
{
var t = context.IndexOf("pat:a", 0, StringComparison.CurrentCultureIgnoreCase);
if (t == -1) t = context.Length;
this.pnrContext = context.Substring(0, t);
this.pnrPat = context.Substring(t, context.Length - t);
}
public Tuple<string[], string> getPnrLines()
{
Dictionary<int, string> lines = new Dictionary<int, string>();
string _pnrType = "1";
Regex regex = new Regex(@"(?<li>\d{1,2})\.\D");
var mc = regex.Match(pnrContext);
int start; int end;
while (mc.Success)
{
start = mc.Index;
var line = mc.Groups["li"].Value.ToInt();
mc = mc.NextMatch();
if (mc.Success)
end = mc.Index;
else
end = pnrContext.Length;
string lineStr = pnrContext.Substring(start, end - start);
lines[line] = lineStr;
}
if (lines.Min(p => p.Key) == 0)
_pnrType = "2";
return Tuple.Create<string[], string>(lines.Select(p => p.Value).ToArray(), _pnrType);
}
public PnrObject Format()
{
var lines = getPnrLines();
var analyzer = new NameAnalyzer();
IAnalyzer[] analyzers = { new SkywayAnalyzer(),new IDCardAnalyzer(),new TelAnalyzer(),new TicketNumAnalyzer(),
new BigCodeAnalyzer(),new OfficeAnalyzer()};
PnrObject obj = new PnrObject();
obj.PnrType = lines.Item2;
foreach (var pnrline in lines.Item1)
{
if (string.IsNullOrEmpty(obj.Pnr))
{
analyzer.Analyze(obj, pnrline);
continue;
}
var oa = analyzers.Where(p => p.CanAnalyze(pnrline)).FirstOrDefault();
if (oa != null)
oa.Analyze(obj, pnrline);
}
PatAnalyzer pat = new PatAnalyzer();
pat.Analyzer(obj, pnrPat);
return obj;
}
}
#region rt解析
public interface INameAnalyzer
{
void Analyze(PnrObject pnrObject, string pnrLine);
}
public interface IAnalyzer : INameAnalyzer
{
bool CanAnalyze(string pnrLine);
}
public class NameAnalyzer : INameAnalyzer //1.蔡佳诚 JYC2ZV or 1.蔡佳诚 or 1.魏嘉琪CHD HS73DL
{
Regex nameAndPnrExp = new Regex(@"(?<id>\d)\.(?<name>.+)(?<pnr>\w{6})");
Regex nameExp = new Regex(@"(?<id>\d)\.(?<name>.+)");
public void Analyze(PnrObject pnrObject, string pnrLine)
{
Match mc;
mc = nameAndPnrExp.Match(pnrLine);
if (mc.Success)
pnrObject.Pnr = mc.Groups["pnr"].Value.Trim();
else
mc = nameExp.Match(pnrLine);
var passengerName = mc.Groups["name"].Value.Trim();
var passenger = new Passenger();
passenger.Id = mc.Groups["id"].Value;
passenger.Name = passengerName;
passenger.PassengerType = EnumPassengerType.ADU;
if (passengerName.EndsWith("CHD"))
{
passenger.Name = passengerName.Substring(0, passengerName.Length - 3);
passenger.PassengerType = EnumPassengerType.CHD;
}
pnrObject.Passengers.Add(passenger);
}
}
public class SkywayAnalyzer : IAnalyzer //2. CA1463 H SA13SEP PEKKWE HK1 1455 1800+1 E T3T2 _
{
Regex skyWay = new Regex(@"\.\s*(?<fn>\w{6})\s*(?<set>\w{1,2})\s*(?<t>\w{7})\s*(?<c>\w{6})\s*(?<state>\w{2,3})\s*(?<ft>\d{4})\s*(?<et>\d{4}(\+\d)?)\s*(?<ty>\w)\s*(?<tm>[\w\-]{4}|[\w\-]{2}|[\s]{4})(?<other>.*?)");
public void Analyze(PnrObject pnrObject, string pnrLine)
{
var mc = skyWay.Match(pnrLine);
if (mc.Success)
{
string Seat = mc.Groups["set"].Value;
string childSeat = string.Empty;
string other = mc.Groups["other"].Value;
if (other.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries).Contains(Seat + "1"))
{
childSeat = Seat + "1";
}
pnrObject.Skyways.Add(new PnrSkyway()
{
FlightNo = mc.Groups["fn"].Value,
FormCode = mc.Groups["c"].Value.Substring(0, 3),
FormTerminal = Units.GetFTerminal(mc.Groups["tm"].Value),
Seat = mc.Groups["set"].Value,
ToCode = mc.Groups["c"].Value.Substring(3, 3),
ToTerminal = Units.GetTTerminal(mc.Groups["tm"].Value),
FormTime = Units.GetDateTime(mc.Groups["t"].Value, mc.Groups["ft"].Value),
ToTime = Units.GetDateTime(mc.Groups["t"].Value, mc.Groups["et"].Value),
SkyState = mc.Groups["state"].Value,
ChildSeat = childSeat
});
}
}
public bool CanAnalyze(string pnrLine)
{
return skyWay.IsMatch(pnrLine);
}
}
public class IDCardAnalyzer : IAnalyzer //7.SSR FOID CA HK1 NI640121198011300811/P1 --
{
Regex cardReg = new Regex(@"\.\s*SSR\s*FOID\s*\w{2}\s*(?<st>\w{2,3})\s*NI(?<no>[^/]*)/P(?<in>\d)");
public void Analyze(PnrObject pnrObject, string pnrLine)
{
var mc = cardReg.Match(pnrLine);
if (mc.Success)
{
var i = mc.Groups["in"].Value;
var passenger = pnrObject.Passengers.FirstOrDefault(p => p.Id == i);
if (passenger != null)
passenger.CardNo = mc.Groups["no"].Value;
}
}
public bool CanAnalyze(string pnrLine)
{
return cardReg.IsMatch(pnrLine);
}
}
public class ChildBornAnlyzer : IAnalyzer // SSR CHLD CZ HK1 02JUL08/P1
{
Regex bornReg = new Regex(@"\.\s*SSR\s*CHLD\s*\w{2}\s*(?<st>\w{2,3})\s*(?<no>[^/]*)/P(?<in>\d)");
public bool CanAnalyze(string pnrLine)
{
return bornReg.IsMatch(pnrLine);
}
public void Analyze(PnrObject pnrObject, string pnrLine)
{
var mc = bornReg.Match(pnrLine);
if (mc.Success)
{
var i = mc.Groups["in"].Value;
var passenger = pnrObject.Passengers.FirstOrDefault(p => p.Id == i);
if (passenger != null)
{
passenger.BornDay = mc.Groups["no"].Value;
passenger.PassengerType = EnumPassengerType.CHD;
}
}
}
}
public class BabyAnlyzer : IAnalyzer // XN/IN/马晓INF(MAY12/P1
{
Regex babyReg = new Regex(@"\s*(?<=XN\/IN\/)(?<YinerName>\w+\s*(INF)?\(?).*?/P(?<Num>\d+)\s*");
public bool CanAnalyze(string pnrLine)
{
return babyReg.IsMatch(pnrLine);
}
public void Analyze(PnrObject pnrObject, string pnrLine)
{
var mc = babyReg.Match(pnrLine);
if (mc.Success)
{
var i = mc.Groups["YinerName"].Value;
pnrObject.Passengers.Add(new Passenger
{
Name = i,
Id = string.Format("P{0}", mc.Groups["Num"].Value),
PassengerType = EnumPassengerType.BABY
});
}
}
}
public class BabyCardNoAnlyzer : IAnalyzer //SSR INFT 3U HK1 CTUXIY 8555 Y31JUL SHANG/LING 23APR12/P1
{
Regex babyCarNoReg = new Regex(@"(?<=SSR\s*INFT)\s*(.*?)\s*\w{1,2}\d{2}\w{3}\s*(?<YinerName>.*?)\s*(?<YinerBirthday>\d{2}[A-Za-z]{3}\d{2})\s*(\/S(?<S>\d+))?\/P(?<Num>\d+)\s*");
public bool CanAnalyze(string pnrLine)
{
return babyCarNoReg.IsMatch(pnrLine);
}
public void Analyze(PnrObject pnrObject, string pnrLine)
{
var mc = babyCarNoReg.Match(pnrLine);
if (mc.Success)
{
var i = string.Format("P{0}", mc.Groups["Num"].Value);
var passenger = pnrObject.Passengers.FirstOrDefault(p => p.PassengerType == EnumPassengerType.BABY && p.Id == i && mc.Groups["YingerName"].Value.Replace("/", "").Equals(PinYingMange.GetSpellByChinese(p.Name)));
if (passenger != null)
passenger.BornDay = mc.Groups["YinerBirthday"].Value;
else
pnrObject.Passengers.Add(new Passenger
{
Id = i,
PassengerType = EnumPassengerType.BABY,
Name = mc.Groups["YinerName"].Value.Trim(),
BornDay = mc.Groups["YinerBirthday"].Value.Trim()
});
}
}
}
public class TelAnalyzer : IAnalyzer //10.OSI CZ CTCM13940582959/P1
{
Regex telReg = new Regex(@"\.\s*OSI\s*\w{2}\s*CTCM(?<tel>\d{11})/P(?<in>\d)");
public void Analyze(PnrObject pnrObject, string pnrLine)
{
var mc = telReg.Match(pnrLine);
if (mc.Success)
{
var i = mc.Groups["in"].Value;
var passenger = pnrObject.Passengers.FirstOrDefault(p => p.Id == i);
if (passenger != null)
passenger.Tel = mc.Groups["tel"].Value;
}
}
public bool CanAnalyze(string pnrLine)
{
return telReg.IsMatch(pnrLine);
}
}
public class TicketNumAnalyzer : IAnalyzer //13.SSR TKNE MU HK1 CTUNKG 2806 M22SEP 7812173436197/1/P1
{
Regex tnReg = new Regex(@"\.\s*SSR\s*TKNE\s*\w{2}\s*\w{2,3}\s*\w{6}\s*\d{4}\s*\w{6}\s*(?<tn>[\d\-]*)/\d/P(?<in>\d)");
public void Analyze(PnrObject pnrObject, string pnrLine)
{
var mc = tnReg.Match(pnrLine);
if (mc.Success)
{
var i = mc.Groups["in"].Value;
var passenger = pnrObject.Passengers.FirstOrDefault(p => p.Id == i);
if (passenger != null)
passenger.TicketNum = mc.Groups["tn"].Value;
}
}
public bool CanAnalyze(string pnrLine)
{
return tnReg.IsMatch(pnrLine);
}
}
public class BigCodeAnalyzer : IAnalyzer //13.RMK CA/MFM3BT -
{
Regex bigCodeReg = new Regex(@"\.(RMK\s*CA/|-CA-)(?<bc>\w{6})");
public void Analyze(PnrObject pnrObject, string pnrLine)
{
var mc = bigCodeReg.Match(pnrLine);
if (mc.Success)
{
pnrObject.BigPnr = mc.Groups["bc"].Value;
}
}
public bool CanAnalyze(string pnrLine)
{
return bigCodeReg.IsMatch(pnrLine);
}
}
public class OfficeAnalyzer : IAnalyzer //14.CTU186
{
Regex officeReg = new Regex(@"\.(?<of>[A-Z]{3}\d{3})");
public void Analyze(PnrObject pnrObject, string pnrLine)
{
var mc = officeReg.Match(pnrLine);
if (mc.Success)
{
pnrObject.Office = mc.Groups["of"].Value;
}
}
public bool CanAnalyze(string pnrLine)
{
return officeReg.IsMatch(pnrLine);
}
}
#endregion
#region pat解析
public class PatAnalyzer
{
//01 L FARE:CNY1050.00 TAX:CNY50.00 YQ:CNY120.00 TOTAL:1220.00
//PAT:A 01 Y FARE:CNY1440.00 TAX:CNY50.00 YQ:CNY110.00 TOTAL:1600.00 SFC:01 SFN:01
//PAT:A*CH>PAT:A*CH01 Y FARE:CNY670.00 TAX:TEXEMPTCN YQ:CNY60.00 TOTAL:730.00>SFC:01
Regex patReg = new Regex(@"FARE:(?<fa>\S*)\s*TAX:(?<t>\S*)\s*YQ:(?<y>\S*)\s*TOTAL:(?<to>\d*).00");
public void Analyzer(PnrObject obj, string patContext)
{
var ms = patReg.Matches(patContext);
foreach (Match m in ms)
{
obj.Pats.Add(new PatObject()
{
FARE = Units.GetPrice(m.Groups["fa"].Value),
TAX = Units.GetPrice(m.Groups["t"].Value),
TOTAL = Units.GetPrice(m.Groups["to"].Value),
YQ = Units.GetPrice(m.Groups["y"].Value)
});
}
}
}
#endregion
public class PnrObject
{
public PnrObject()
{
this.PnrType = "1";
}
public string Pnr { get; set; }
public string BigPnr { get; set; }
public string Office { get; set; }
/// <summary>
/// 编码类型 1普通编码 2团编码
/// </summary>
public string PnrType { get; set; }
private List<Passenger> passengers = new List<Passenger>();
private List<PnrSkyway> skyways = new List<PnrSkyway>();
public List<PnrSkyway> Skyways { get { return skyways; } }
public List<Passenger> Passengers { get { return passengers; } }
private List<PatObject> pats = new List<PatObject>();
public List<PatObject> Pats { get { return pats; } }
}
public class PnrSkyway
{
/// <summary>
/// 出发城市三字码
/// </summary>
public string FormCode { get; set; }
/// <summary>
/// 到达城市三字码
/// </summary>
public string ToCode { get; set; }
/// <summary>
/// 出发航站楼
/// </summary>
public string FormTerminal { get; set; }
/// <summary>
/// 到达航站楼
/// </summary>
public string ToTerminal { get; set; }
/// <summary>
/// 出发时间
/// </summary>
public DateTime FormTime { get; set; }
/// <summary>
/// 到达时间
/// </summary>
public DateTime ToTime { get; set; }
/// <summary>
/// 航班号
/// </summary>
public string FlightNo { get; set; }
/// <summary>
/// 舱位
/// </summary>
public string Seat { get; set; }
/// <summary>
/// 子舱位
/// </summary>
public string ChildSeat { get; set; }
/// <summary>
/// pnr航程状态
/// </summary>
public string SkyState { get; set; }
}
public class Passenger
{
private string name;
internal string Id { get; set; }
public string Name
{
get
{//以CHD结尾儿童
if (name.Contains("CHD"))
return name.Replace("CHD", "");
return name;
}
set { name = value; }
}
/// <summary>
/// 证件号
/// </summary>
public string CardNo { get; set; }
/// <summary>
/// 生日
/// </summary>
public string BornDay { get; set; }
public string Tel { get; set; }
public string TicketNum { get; set; }
private EnumPassengerType _PassengerType = EnumPassengerType.ADU;
public EnumPassengerType PassengerType
{
get
{
if (name.Contains("CHD"))
_PassengerType = EnumPassengerType.CHD;
return _PassengerType;
}
set
{
_PassengerType = value;
}
}
}
public enum EnumPassengerType
{
ADU,
CHD,
BABY
}
public class PatObject
{
public decimal FARE { get; set; }
public decimal TAX { get; set; }
public decimal YQ { get; set; }
public decimal TOTAL { get; set; }
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Casting
{
class Program
{
static void Main(string[] args)
{
// --------------upcasting---------------------
/*
Text text = new Text();
Shape shape = text; // implicitly casting
text.Width = 200;
shape.Width = 100;
Console.WriteLine(text.Width);
// StreamReader reader = new StreamReader(new MemoryStream());
var list = new ArrayList(); // NOT type safe structure
list.Add(1);
list.Add("John");
list.Add(new Text());
var anotherList = new List<int>();
var anotherList2 = new List<Shape>();
*/
// --------------downcasting---------------------
Shape shape = new Text(); // F9 -- F5 -- F10
// Text text = shape; // error: cannot implicitly convert type Casting.Shape to Casting.Text
Text text = (Text)shape;
var fontname = text.FontName;
}
}
}
|
using Pchp.Core;
using System;
using System.Collections.Generic;
using System.Text;
namespace OCP.OCS
{
/**
* Interface IDiscoveryService
*
* Allows you to discover OCS end-points on a remote server
*
* @package OCP\OCS
* @since 12.0.0
*/
public interface IDiscoveryService
{
/**
* Discover OCS end-points
*
* If no valid discovery data is found the defaults are returned
*
* @since 12.0.0
*
* @param string remote
* @param string service the service you want to discover
* @param bool skipCache We won't check if the data is in the cache. This is useful if a background job is updating the status - Added in 14.0.0
* @return array
*/
PhpArray discover(string remote, string service, bool skipCache = false);
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
[CreateAssetMenu(fileName = "Img Scene", menuName = "Img/Scene")]
public class ImgClass : ScriptableObject
{
public int id;
public Sprite img;
public string text, who;
public ImgType type;
public string[] choises;
public int idToLoad;
}
public enum ImgType
{
normal, choise, input
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using Silas.Forecast.Models;
namespace Silas.Forecast.Strategies
{
public class MovingAverageStrategy : IForecastStrategy
{
public ForecastEntry Forecast(IEnumerable<DataEntry> dataEntries, int period, dynamic strategyParameters)
{
if (period - 1 < 0)
return null;
int numberOfPeriods = strategyParameters.PeriodCount;
if (numberOfPeriods > dataEntries.Count())
throw new ArgumentException("The number of periods can not be greater than the number of entries.");
double value;
if (dataEntries.Count() == 1 || period == 1)
value = dataEntries.ElementAt(0).Value;
else if (period < numberOfPeriods)
value = dataEntries.ElementAt(period - 1).Value;
else if (dataEntries.Count() > 1 && period <= dataEntries.Count() + 1)
value =
dataEntries.Take(period - 1).Reverse().Take(numberOfPeriods).Reverse().Sum(entry => (entry.Value))/
numberOfPeriods;
else
value = dataEntries.Reverse().Take(numberOfPeriods).Reverse().Sum(entry => (entry.Value))/
numberOfPeriods;
return new ForecastEntry
{
Period = period,
DataEntry = period > dataEntries.Count() ? dataEntries.Last() : dataEntries.ElementAt(period - 1),
ForecastValue = value,
ConfidenceIntervalLow = value,
ConfidenceIntervalHigh = value,
IsHoldout = period > dataEntries.Count()*0.7 //holdout data is always 70 percent
};
}
}
} |
namespace Adapter
{
class CalculadoraApadatada
{
public double RealizarSumaAdpatada(int[] operandos)
{
double resultado = 0;
foreach (var operando in operandos)
{
resultado += operando;
}
return resultado;
}
}
}
|
using CryptoInvestor.Core.Domain;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace CryptoInvestor.Core.Repositories
{
public interface ITransactionRepository : IRepository
{
Task AddAsync(Transaction transaction);
Task<Transaction> GetAsync(Guid id);
Task<IEnumerable<Transaction>> BrowseAsync(Guid userId);
Task UpdateAsync(Transaction transaction);
Task DeleteAsync(Guid id);
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace RiversideHealthCare.Models
{
[MetadataType(typeof(ProductValidation))]
//name of database table
public partial class Product
{
}
[Bind(Exclude = "ProductId")]
public partial class ProductValidation
{
//[DisplayName("Product ID")]
//public int ProductId { get; set; }
[DisplayName("Product Name")]
[Required(ErrorMessage = "Please enter name of product")]
[StringLength(100, ErrorMessage = "Name cannot be longer than 100 characters.")]
public string Name { get; set; }
[DisplayName("Description")]
[Required(ErrorMessage = "Please enter description")]
[StringLength(500, ErrorMessage = "Description cannot be longer than 500 characters.")]
public string Description { get; set; }
[DisplayName("Price")]
[Required(ErrorMessage = "Please enter unit price")]
[RegularExpression("^[$]?[0-9]*(\\.)?[0-9]?[0-9]?$", ErrorMessage = "Enter valid price value")]
public decimal UnitPrice { get; set; }
//allow for image upload
[DisplayName("Image Upload")]
[Required(ErrorMessage = "Please enter image URL")]
HttpPostedFileBase Image { get; set; }
[DisplayName("Stock")]
[Required(ErrorMessage = "Please enter current stock volume")]
public int Stock { get; set; }
}
} |
using System;
namespace palindrome
{
class Program
{
static void Main(string[] args)
{
Console.Write("write an word: ");
var value = Console.ReadLine();
string first = value.Substring(0, value.Length / 2);
char[] arr = value.ToCharArray();
Array.Reverse(arr);
string temp = new string(arr);
string second = temp.Substring(0, temp.Length / 2);
var msg = first.Equals(second) ? "palindrome: true" : "palindrome: false";
Console.WriteLine(msg);
}
}
}
|
using ServiceDesk.Api.Systems.DirectorySystem.Dtos.License;
namespace ServiceDesk.Api.Systems.DirectorySystem.DtoBuilders.License
{
public class LicenseDtoBuilder : ILicenseDtoBuilder<LicenseDto>
{
public LicenseDto Build(Core.Entities.DirectorySystem.License license)
{
var licenseDto = new LicenseDto()
{
Id = license.Id,
Number = license.Number,
Client = license.Client?.Name,
ClientId = license.ClientId,
CountOfUsers = license.CountOfUsers,
ExpiresDate = license.ExpiresDate,
Software = license.Software.Title,
SoftwareId = license.SoftwareId,
StartDate = license.StartDate
};
return licenseDto;
}
}
}
|
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace HardcoreHistoryBlog.Data
{
public class UserStore : UserStore<ApplicationUser>
{
public UserStore(ApplicationDbContext context) : base(context)
{
}
}
}
|
using HCL.Academy.DAL;
using HCL.Academy.Model;
using HCLAcademy.Util;
using System;
using System.Collections.Generic;
using System.Web.Http;
using Microsoft.ApplicationInsights;
using System.Diagnostics;
namespace HCL.Academy.Service.Controllers
{
/// <summary>
/// This service exposes all the methods related to the Menu
/// </summary>
//[EnableCors(origins: "https://hclacademyhubnew.azurewebsites.net", headers: "*", methods: "*")]
public class MenuController : ApiController
{
/// <summary>
/// This method fetches the menu based on user role and authentication.
/// </summary>
/// <param name="request"></param>
/// <param name="roleid"></param>
/// <returns></returns>
[Authorize]
[HttpPost]
[ActionName("GetMenu")]
public List<SiteMenu> GetMenu(RequestBase request,int roleid)
{
LogHelper.AddLog("MenuController,GetMenu", "In GetMenu method","Starting", "HCL.Academy.Service", request.ClientInfo.emailId);
List<SiteMenu> response = new List<SiteMenu>();
try
{
SqlSvrDAL dal = new SqlSvrDAL(request.ClientInfo);
response = dal.GetMenu(roleid);
}
catch (Exception ex)
{
//LogHelper.AddLog("MenuController,GetMenu", ex.Message, ex.StackTrace, "HCL.Academy.Service",request.ClientInfo.emailId);
TelemetryClient telemetry = new TelemetryClient();
telemetry.TrackException(ex);
}
return response;
}
///// <summary>
///// This method fetches all the banners.
///// </summary>
///// <param name="request"></param>
///// <returns></returns>
//[HttpPost]
//[ActionName("GetBanners")]
//public List<Banners> GetBanners(RequestBase request)
//{
// List<Banners> response = new List<Banners>();
// try
// {
// SharePointDAL dal = new SharePointDAL(request.ClientInfo);
// //IDAL dal = (new DALFactory(request.ClientInfo)).GetInstance();
// response = dal.GetBanners();
// }
// catch (Exception ex)
// {
// LogHelper.AddLog("MenuController,GetBanners", ex.Message, ex.StackTrace, "HCL.Academy.Service", request.ClientInfo.emailId);
// }
// return response;
//}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy_HP : MonoBehaviour
{
public int health = 200;
public void TakeDamage(int amount)
{
health -= amount;
if(health <= 0)
{
Die();
}
}
private void Die()
{
Destroy(this.gameObject);
}
}
|
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 DB_Test.Pages
{
/// <summary>
/// Interaction logic for FlightAttendent.xaml
/// </summary>
public partial class FlightAttendent : Page
{
Windows.Win_OCC win;
public FlightAttendent(Windows.Win_OCC w)
{
InitializeComponent();
win = w;
}
private void Add_Click(object sender, RoutedEventArgs e)
{
AddFlightAttendent a = new AddFlightAttendent(win);
win.frame.Navigate(a);
}
private void Flights_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
FADetail a = new FADetail(win);
win.frame.Navigate(a);
}
}
}
|
using System;
using System.Linq;
namespace InvoiceObjects
{
class Program
{
static void Main(string[] args)
{
/* (Querying an Array of Invoice Objects) Use the class Invoice provided in the ex09_03 folder
with this chapter’s examples to create an array of Invoice objects. Use the sample data shown in
ig. 9.8. Class Invoice includes four properties—a PartNumber (type int), a PartDescription (type
string), a Quantity of the item being purchased (type int) and a Price (type decimal). Perform
the following queries on the array of Invoice objects and display the results:
a) Use LINQ to sort the Invoice objects by PartDescription.
b) Use LINQ to sort the Invoice objects by Price.
c) Use LINQ to select the PartDescription and Quantity and sort the results by
Quantity.
d) Use LINQ to select from each Invoice the PartDescription and the value of the Invoice
(i.e., Quantity * Price). Name the calculated column InvoiceTotal. Order the
results by Invoice value. [Hint: Use let to store the result of Quantity * Price in a new
range variable total.]
e) Using the results of the LINQ query in part (d), select the InvoiceTotals in the range
$200 to $500.*/
//Initiate array of invoices
Invoice[] invoices =
{
new Invoice(83, "Electric Sander", 7, 57.98M),
new Invoice(24, "Power Saw", 18, 99.99M),
new Invoice(7, "Sledge Hammer", 11, 21.5M),
new Invoice(77, "Hammer", 76, 11.99M),
new Invoice(39, "Lawn Mower", 3, 79.5M),
new Invoice(68, "Screwdriver", 106, 6.99M),
new Invoice(56, "Jig Saw", 21, 11M),
new Invoice(3, "Wrench", 34, 7.5M),
};
//a) Use LINQ to sort the Invoice objects by PartDescription.
var sortedByDescription =
from item in invoices
orderby item.PartDescription
select item;
//display invoices, sorted by description
Console.WriteLine("Sorted by description:");
foreach (var item in sortedByDescription)
{
Console.WriteLine(item);
}
//b) Use LINQ to sort the Invoice objects by Price.
var sortedByPrice =
from item in invoices
orderby item.Price
select item;
//display invoices, sorted by Price
Console.WriteLine("Sorted by price:");
foreach (var item in sortedByPrice)
{
Console.WriteLine(item);
}
//c) Use LINQ to select the PartDescription and Quantity and sort the results by Quantity.
var DescriptionAndQuantity =
from item in invoices
orderby item.Quantity
select new { item.PartDescription, item.Quantity };
//display invoices, sorted by quantity
Console.WriteLine("Sorted by quantity:");
foreach (var item in DescriptionAndQuantity)
{
Console.WriteLine(item);
}
/* d) Use LINQ to select from each Invoice the PartDescription and the value of the Invoice
(i.e., Quantity * Price). Name the calculated column InvoiceTotal. Order the
results by Invoice value. [Hint: Use let to store the result of Quantity * Price in a new
range variable total.] */
var descriptionAndTotal =
from item in invoices
let total = item.Quantity * item.Price
orderby total
select new { item.PartDescription, InvoiceTotal = total };
//display description and calculated invoice total
Console.WriteLine("\nSelect description and Invoice Total, Sort by total");
foreach (var item in descriptionAndTotal)
{
Console.WriteLine(item);
}
//e) Using the results of the LINQ query in part (d), select the InvoiceTotals in the range $200 to $500.
var totalbw200and500 =
from item in descriptionAndTotal
where item.InvoiceTotal > 200M && item.InvoiceTotal < 500M
select item;
// display filtererd desccriptions and invoices
Console.WriteLine("\nInvoice totals between {200:C} and {500:C}:");
foreach (var item in totalbw200and500)
{
Console.WriteLine(item);
}
Console.WriteLine("");
Console.ReadLine();
}
}
}
|
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace SkillsGardenDTO
{
/// <summary>
/// The DTO for exercise
/// </summary>
public class ExerciseBody
{
/// <summary>
/// The name of the exercise
/// </summary>
/// <example>Pete</example>
[MinLength(2, ErrorMessage = "Name must be at least 2 characters")]
[MaxLength(30, ErrorMessage = "Name can not be longer than 30 characters")]
[DataType(DataType.Text)]
public string Name { get; set; }
/// <summary>
/// The requirements of the exercise
/// </summary>
/// <example>array</example>
public List<string> Requirements { get; set; }
/// <summary>
/// The setps of the exercise
/// </summary>
/// <example>array</example>
public List<string> Steps { get; set; }
/// <summary>
/// The movement forms of the exercise
/// </summary>
/// <example>array</example>
public List<MovementForm> Forms { get; set; }
/// <summary>
/// The media for the exercise
/// </summary>
/// <example>http://asmplatform.nl/video</example>
public string Media { get; set; }
}
/// <summary>
/// The movement forms
/// </summary>
public enum MovementForm
{
/// <summary>
/// Klimmen
/// </summary>
klimmen,
/// <summary>
/// Balans
/// </summary>
balans,
/// <summary>
/// Mikken
/// </summary>
mikken,
/// <summary>
/// Gooien
/// </summary>
gooien,
/// <summary>
/// Springen
/// </summary>
springen,
/// <summary>
/// Zwaaien
/// </summary>
zwaaien,
/// <summary>
/// Rollen
/// </summary>
rollen,
/// <summary>
/// Hardlopen
/// </summary>
hardlopen,
/// <summary>
/// Overspelen
/// </summary>
overspelen,
/// <summary>
/// Stoeien
/// </summary>
stoeien
}
}
|
using NETCommunity.FsCheck.Cart;
namespace NETCommunity.FsCheck.Discounts.CustomerCharacteristic
{
// 2% discount to customers who are or were members of a military service.
public class TwoPercentMilitaryDiscount : IOrderDiscountRule
{
public decimal Apply(ICart cart)
{
return cart.GrandTotal * 0.98m;
}
}
} |
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ArmadaEngine.TileMaps
{
public class TilemapManager
{
List<TileMap> mapList = new List<TileMap>();
public TileMap ActiveMap;
public void AddMap(TileMap newMap)
{
mapList.Add(newMap);
}
public TileMap findMap(Vector2 pos)
{
foreach (TileMap map in mapList)
{
if (map.mapTilePos.X == pos.X && map.mapTilePos.Y == pos.Y)
{
return map;
}
}
return null;
}
public TileMap findMapByName(String name)
{
foreach (TileMap map in mapList)
{
if (map.name.Equals(name))
{
return map;
}
}
return null;
}
public Tile findTile(Vector2 pos)
{
Vector2 posToTileMapPos = PosToWorldTilePos(pos);
TileMap mapClicked = findMap(PosToWorldTilePos(pos));
if(mapClicked == null)
{
return null;
}
Vector2 localTileMapPos = new Vector2(pos.X - (posToTileMapPos.X * mapClicked.mapWidth), pos.Y - (posToTileMapPos.Y * mapClicked.mapHeight));
if (mapClicked != null)
{
Tile clickedTile = mapClicked.findClickedTile(PosToMapPos(localTileMapPos, mapClicked.tileWidth));
return clickedTile;
}
return null;
}
public List<Tile> FindAdjacentTiles(Vector2 pos, bool allowDiagonal = true)
{
Tile targetTile = findTile(pos);
List<Tile> adjacentTiles = new List<Tile>();
int tileWidth = targetTile.destRect.Width;
//get top center tile
Tile topCenter = findTile(new Vector2(targetTile.tileCenter.X, targetTile.tileCenter.Y - tileWidth));
if (topCenter != null && topCenter.walkable)
{
adjacentTiles.Add(topCenter);
}
Tile LeftTile = findTile(new Vector2(targetTile.tileCenter.X - tileWidth, targetTile.tileCenter.Y));
if (LeftTile != null && LeftTile.walkable)
{
adjacentTiles.Add(LeftTile);
}
Tile rightTIle = findTile(new Vector2(targetTile.tileCenter.X + tileWidth, targetTile.tileCenter.Y));
if (rightTIle != null && rightTIle.walkable)
{
adjacentTiles.Add(rightTIle);
}
Tile bottomCenter = findTile(new Vector2(targetTile.tileCenter.X, targetTile.tileCenter.Y + tileWidth));
if (bottomCenter != null && bottomCenter.walkable)
{
adjacentTiles.Add(bottomCenter);
}
//adjacentTiles.Add(targetTile);
if (allowDiagonal)
{
Tile topleft = findTile(new Vector2(targetTile.tileCenter.X - tileWidth, targetTile.tileCenter.Y - tileWidth));
if (topleft.walkable)
{
adjacentTiles.Add(topleft);
}
Tile topRight = findTile(new Vector2(targetTile.tileCenter.X + tileWidth, targetTile.tileCenter.Y - tileWidth));
if (topRight.walkable)
{
adjacentTiles.Add(topRight);
}
Tile bottomLeft = findTile(new Vector2(targetTile.tileCenter.X - tileWidth, targetTile.tileCenter.Y + tileWidth));
if (bottomLeft.walkable)
{
adjacentTiles.Add(bottomLeft);
}
Tile bottomRight = findTile(new Vector2(targetTile.tileCenter.X + tileWidth, targetTile.tileCenter.Y + tileWidth));
if (bottomRight.walkable)
{
adjacentTiles.Add(bottomRight);
}
}
return adjacentTiles;
}
public List<Tile> AStarTwo(Tile tileOne, Tile tileTwo, bool useDiagonal = false)
{
if (tileOne == tileTwo) return null;
Dictionary<Tile, float> ClosedNodes = new Dictionary<Tile, float>();
Dictionary<Tile, float> OpenNodes = new Dictionary<Tile, float>();
Dictionary<Tile, Tile> Path = new Dictionary<Tile, Tile>();
Dictionary<Tile, float> distanceFromPrevious = new Dictionary<Tile, float>();
distanceFromPrevious.Add(tileOne, 0);
Dictionary<Tile, float> distanceFromStart = new Dictionary<Tile, float>();
float startCost = Vector2.Distance(tileOne.tileCenter, tileTwo.tileCenter);
startCost = calcCost(tileOne, tileTwo);
distanceFromStart.Add(tileOne, startCost);
OpenNodes.Add(tileOne, startCost);
while(OpenNodes.Count > 0)
{
Tile current = OpenNodes.OrderBy(x => x.Value).First().Key;
if(current == tileTwo)
{
//done
return BuildPath(Path, current);
}
OpenNodes.Remove(current);
float closestFScore = Vector2.Distance(current.tileCenter, tileOne.tileCenter);
closestFScore = calcCost(current, tileOne);
ClosedNodes.Add(current, closestFScore);
List<Tile> adjacents = this.FindAdjacentTiles(current.tileCenter, useDiagonal);
foreach(Tile t in adjacents)
{
if(ClosedNodes.ContainsKey(t))
{
continue;
}
float idk = distanceFromPrevious[current] + Vector2.Distance(t.tileCenter, current.tileCenter);
t.myColor = Color.Blue;
if(!OpenNodes.ContainsKey(t))
{
OpenNodes.Add(t, Vector2.Distance(t.tileCenter, tileTwo.tileCenter));
}
else if(idk >= distanceFromPrevious[t])
{
continue;
}
Path[t] = current;
distanceFromPrevious[t] = idk;
//distanceFromStart[t] = distanceFromPrevious[t] + Vector2.Distance(t.tileCenter, tileTwo.tileCenter);
distanceFromStart[t] = distanceFromPrevious[t] + calcCost(t, tileOne);
}
}
return null;
}
public void ResetTileColors()
{
foreach(TileMap t in mapList)
{
t.ResetColors();
}
}
private float calcCost(Tile one, Tile two)
{
float dx = Math.Abs(one.tileCenter.X - two.tileCenter.X);
float dy = Math.Abs(one.tileCenter.Y - two.tileCenter.Y);
float cost = one.destRect.Width;
float diagCost = (cost * cost) + (cost * cost);
return cost * Math.Max(dx, dy) + (diagCost - cost) * Math.Min(dx, dy);
}
public List<Tile> BuildPath(Dictionary<Tile, Tile> Path, Tile current)
{
if (!Path.ContainsKey(current))
{
return new List<Tile> { current };
}
var path = BuildPath(Path, Path[current]);
path.Add(current);
return path;
}
public List<Tile> FindPath(Tile tileOne, Tile TileTwo)
{
List<Tile> pathTiles = new List<Tile>();
while(tileOne != TileTwo)
{
pathTiles.Add(tileOne);
List<Tile> adjacentTiles = this.FindAdjacentTiles(tileOne.tileCenter, false);
Tile closest = FindClosestTile(adjacentTiles, TileTwo);
if(tileOne == closest)
{
return pathTiles;
}
tileOne = closest;
if(tileOne == TileTwo)
{
pathTiles.Add(TileTwo);
}
}
//get tiles adjacent to tileOne
// loop through adjacent tiles to find closest and return it
// add it to pathTIles
// repeat using new tile
return pathTiles;
}
public Tile FindClosestTile(List<Tile> list, Tile target)
{
float distance = 99999999;
Tile closest = list.First();
float newDistance = Vector2.Distance(closest.tileCenter, target.tileCenter);
foreach (Tile tile in list)
{
newDistance = Vector2.Distance(tile.tileCenter, target.tileCenter);
if (newDistance < distance)
{
distance = newDistance;
closest = tile;
}
}
return closest;
}
public List<Tile> getAllTiles(TileMap map)
{
return map.backgroundTiles;
}
public Vector2 PosToWorldTilePos(Vector2 pos)
{
int clickMapX = (int)pos.X / 2048;
int clickMapY = (int)pos.Y / 2048;
return new Vector2(clickMapX, clickMapY);
}
private Vector2 PosToMapPos(Vector2 pos, int TileSize)
{
//need to change this to the coordinates within the tilemap itself...
int clickMapX = (int)pos.X / TileSize;
int clickMapY = (int)pos.Y / TileSize;
return new Vector2(clickMapX, clickMapY);
}
internal Tile findWalkableTile(Vector2 newPos)
{
Tile newTile = findTile(newPos);
if (newTile.walkable)
{
return newTile;
}
return null;
}
public void Draw(SpriteBatch spriteBatch, Rectangle vp)
{
foreach (TileMap map in mapList)
{
map.Draw(spriteBatch, vp);
}
}
public void LoadMap(String mapname, ContentManager Content)
{
TileMap testMap = new TileMap(mapname, Content);
mapList.Add(testMap);
testMap.active = true;
}
}
public class Node
{
public Tile myTile;
public Tile _one;
public Tile _two;
public float toStartCost;
public float toGoalCost;
public Tile closestTile;
public bool open;
public List<Node> neighbors = new List<Node>();
public Node(Tile myTile, Tile two, Tile one)
{
this.myTile = myTile;
toGoalCost = Vector2.Distance(myTile.tileCenter, two.tileCenter);
toStartCost = Vector2.Distance(myTile.tileCenter, one.tileCenter);
}
public void SetNeighbors(List<Tile> n)
{
neighbors.Clear();
foreach(Tile t in n)
{
Node nn = new Node(t, _two, _one);
neighbors.Add(nn);
}
}
}
}
|
using System.ComponentModel.DataAnnotations;
using iCopy.Model.Attributes;
namespace iCopy.Model.Request
{
public class ApplicationUserInsert
{
[Required(AllowEmptyStrings = false, ErrorMessage = "ErrNoEmail")]
[DataType(DataType.EmailAddress, ErrorMessage = "EmailWrongFormat")]
[MaxLength(100, ErrorMessage = "ErrMaxLength")]
[Unique(Type = UniqueAttribute.Email, ErrorMessage = "ErrUniqueEmail")]
public string Email { get; set; }
[Required(AllowEmptyStrings = false, ErrorMessage = "ErrNoUsername")]
[MaxLength(100, ErrorMessage = "ErrMaxLength")]
[Unique(Type = UniqueAttribute.Username, ErrorMessage = "ErrUniqueUsername")]
[UsernamePolicy(ErrorMessage = "ErrUsernamePolicy")]
public string Username { get; set; }
[Required(ErrorMessage = "ErrNoPhoneNumber")]
[DataType(DataType.PhoneNumber, ErrorMessage = "ErrTypePhoneNumber")]
[MaxLength(100, ErrorMessage = "ErrMaxLength")]
[Unique(Type = UniqueAttribute.PhoneNumber, ErrorMessage = "ErrUniquePhoneNumber")]
public string PhoneNumber { get; set; }
[Required(AllowEmptyStrings = false, ErrorMessage = "ErrNoPassword")]
[MaxLength(100, ErrorMessage = "ErrMaxLength")]
[MinLength(8, ErrorMessage = "ErrMinLenghtPassword")]
[PasswordPolicy(ErrorMessage = "ErrPasswordPolicy")]
public string Password { get; set; }
[Required(AllowEmptyStrings = false, ErrorMessage = "ErrNoPasswordConfirm")]
[MaxLength(100, ErrorMessage = "ErrMaxLength")]
[MinLength(8, ErrorMessage = "ErrMinLenghtPasswordConfirm")]
[Compare(nameof(Password), ErrorMessage = "ErrNotSamePasswordConfirm")]
[PasswordPolicy(ErrorMessage = "asdasd")]
public string PasswordConfirm { get; set; }
}
}
|
using TreeStore.Model.Base;
namespace TreeStore.Model
{
public class Tag : FacetingEntityBase, Messaging.ITag
{
public Tag()
: base(string.Empty, new Facet(string.Empty))
{ }
public Tag(string name)
: base(name, new Facet(name))
{ }
public Tag(string name, Facet facet)
: base(name, facet)
{ }
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(SpriteRenderer))]
public class Blink : MonoBehaviour
{
[SerializeField] private Color _targetColor;
[SerializeField] private float _duration;
[SerializeField] private bool _loop;
private SpriteRenderer _sprite;
private float _runningTime;
private Color _originalColor;
void Start()
{
_sprite = GetComponent<SpriteRenderer>();
_originalColor = _sprite.color;
}
void Update()
{
if (_runningTime < _duration)
{
_runningTime += Time.deltaTime;
var normalizeRunningTime = _runningTime / _duration;
_sprite.color = Color.Lerp(_originalColor, _targetColor, normalizeRunningTime);
}
else if (_loop)
{
_sprite.color = _originalColor;
_runningTime = 0;
}
}
}
|
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using test1;
namespace test1.test
{
[TestClass]
public class TaskTest1
{
[TestMethod]
public void TaxShouldBe5PrecentWhen()
{
// Arange
// Act
decimal rezult = Program.Tax(40000);
// Assert
Assert.AreEqual(rezult, 2000);
}
[TestMethod]
public void TaxShouldBe15PrecentWhenSum()
{
// Arange
// Act
decimal rezult = Program.Tax(50000);
// Assert
Assert.AreEqual(rezult, 7500);
}
[TestMethod]
public void TaxShouldBe25PrecentWhenSumIsMore100000()
{
// Arange
// Act
decimal rezult = Program.Tax(1000000);
// Assert
Assert.AreEqual(rezult, 250000);
}
[TestMethod]
public void TaxShouldBe5PrecentWhen0()
{
// Arange
// Act
decimal rezult = Program.Tax(0);
// Assert
Assert.AreEqual(rezult, 0);
}
}
}
|
using System.Collections.Generic;
using System.Threading.Tasks;
using DemoStandardProject.DTOs;
using DemoStandardProject.Models.ServiceResponse;
namespace DemoStandardProject.Services
{
public interface IProductStockLogService
{
Task<ServiceResponse<List<GetProductStockLogDto>>> GetStockLogAll();
Task<ServiceResponse<GetProductStockLogDto>> GetStockLogById(int Id);
Task<ServiceResponse<List<GetProductStockLogDto>>> AddStockLog(AddProductStockLogDto newstockLogDto);
Task<ServiceResponse<List<GetProductStockLogDto>>> DelectStockLog(int Id);
Task<ServiceResponse<GetProductStockLogDto>> UpdateStockLog(UpdateStockProduct updateStock);
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace PF2e_Encounter_Builder.Models
{
public class DisplayMonsterModel
{
[Required]
public string MonsterName;
[Required]
[Range(-1,25)]
public int Level;
public int FamilyId;
public int TerrainId;
public int TypeId;
public string FamilyName;
public string TypeName;
public string TerrainName;
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// Singleton that manages all UI in the level
/// </summary>
public class LevelUIManager : MonoBehaviour {
private static LevelUIManager _instance;
private void Awake()
{
if(_instance != null)
{
Destroy(gameObject);
}
else
{
_instance = this;
}
}
public static LevelUIManager Instance { get { return _instance; } }
[SerializeField] ActionBar actionBar;
[SerializeField] GameObject inventoryPanel;
[SerializeField] GameObject equipmentPanel;
[SerializeField] GameObject abilityPanel;
public ActionBar GetActionBar { get { return actionBar; } }
private void Start()
{
Hide();
}
void Hide()
{
inventoryPanel.SetActive(false);
equipmentPanel.SetActive(false);
abilityPanel.SetActive(false);
}
private void Update()
{
// Toggle Inventory Panel
if(Input.GetKeyDown(KeyCode.I))
{
inventoryPanel.SetActive(!inventoryPanel.activeSelf);
equipmentPanel.SetActive(!equipmentPanel.activeSelf);
}
// Toggle Ability Panel
if (Input.GetKeyDown(KeyCode.L))
{
abilityPanel.SetActive(!abilityPanel.activeSelf);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HackerrankSolutionConsole
{
class pairs : Challenge
{
static int pairsHelper(int[] a, int k)
{
int pairCount = 0;
//works but times out
//foreach (int x in a)
// if (a.Contains(x - k))
// pairCount++;
a = a.OrderByDescending(x => x).ToArray();
for (int i = 0; i < a.Length && a[i] >= k; i++)
{
for (int j = i + 1; (j < a.Length) && (a[j] >= a[i] - k); j++)
{
if (a[j] == a[i] - k)
pairCount++;
}
}
return pairCount;
}
public override void Main(string[] args)
{
int res;
String line = Console.ReadLine();
String[] line_split = line.Split(' ');
int _a_size = Convert.ToInt32(line_split[0]);
int _k = Convert.ToInt32(line_split[1]);
int[] _a = new int[_a_size];
int _a_item;
String move = Console.ReadLine();
String[] move_split = move.Split(' ');
for (int _a_i = 0; _a_i < move_split.Length; _a_i++)
{
_a_item = Convert.ToInt32(move_split[_a_i]);
_a[_a_i] = _a_item;
}
res = pairsHelper(_a, _k);
Console.WriteLine(res);
}
public pairs()
{
Name = "Pairs";
Path = "pairs";
Difficulty = Difficulty.Medium;
Domain = Domain.Algorithms;
Subdomain = Subdomain.Search;
}
}
}
|
using UnityEngine;
public class CameraFlow : MonoBehaviour
{
public Transform target;
public float smoothSpeed = 3f;
private Vector3 currentVelocity;
void LateUpdate()
{
if(target.position.y > transform.position.y)
{
Vector3 newPosition = new Vector3(transform.position.x, transform.position.y, transform.position.z);
transform.position = Vector3.SmoothDamp(transform.position, newPosition, ref currentVelocity, smoothSpeed * Time.deltaTime);
}
}
}
|
using UnityEngine;
using System.Collections;
public class EquipedItem : MonoBehaviour {
public AudioClip activatePearl;
public AudioClip deactivatePearl;
public AudioClip dropBomb;
public LayerMask lightLayer;
private bool moonMode = false;
private bool sunMode = false;
public float pearlUseTime = 0.4f;
float pearlCounter = 0;
private bool haveBoomerang = true;
Movement mov;
MenuNavigation menu;
SecondMenuController menu2;
Shield shield;
Bow bow;
AudioSource myAudio;
Utils.ItemType myItem;
private int id;
protected delegate void TypeCallback();
protected TypeCallback[] typeCallbacks = new TypeCallback[(int) Utils.ItemType.Length];
void setId(int myId) {
id = myId;
}
// Use this for initialization
void Start () {
mov = GetComponent<Movement> ();
menu = transform.Find ("Canvas").GetComponent<MenuNavigation> ();
menu2 = transform.Find ("StuffCanvas").GetComponent<SecondMenuController> ();
shield = transform.Find ("Shield").GetComponent<Shield> ();
bow = transform.Find ("BowItem").GetComponent<Bow> ();
myAudio = GetComponent<AudioSource> ();
InitCallBacks ();
}
// Update is called once per frame
void Update () {
if (GetComponent<PlayerDeadControl> ().getDead ()) {
setMoonMode(false);
setSunMode(false);
return;
}
myItem = (Utils.ItemType) menu.getItemEquipedId ();
TypeCallback callback = typeCallbacks [(int) myItem];
if (callback != null) callback();
}
void InitCallBacks () {
for (int i = 0; i < typeCallbacks.Length; i++)
typeCallbacks[i] = null;
typeCallbacks[(int)Utils.ItemType.None] = new TypeCallback(OnNone);
typeCallbacks[(int)Utils.ItemType.Boomerang] = new TypeCallback(OnBoomerang);
typeCallbacks[(int)Utils.ItemType.Bombs] = new TypeCallback(OnBombs);
typeCallbacks[(int)Utils.ItemType.Bow] = new TypeCallback(OnBow);
typeCallbacks[(int)Utils.ItemType.MirrorShield] = new TypeCallback(OnMirrorShield);
typeCallbacks[(int)Utils.ItemType.MoonPearl] = new TypeCallback(OnMoonPearl);
typeCallbacks[(int)Utils.ItemType.SunPearl] = new TypeCallback(OnSunPearl);
}
protected void OnNone()
{
}
public void activateBoomerang () {
haveBoomerang = true;
}
public bool getBoomerang () {
return haveBoomerang;
}
protected void OnBoomerang()
{
if (Input.GetButtonDown ("360_A"+id) && haveBoomerang) {
Vector2 direction = mov.getWalkDirection();
Vector2 boomerangDirection = Vector2.zero;
Vector3 boomerangPosition = transform.position;
if(direction.magnitude == 0) {
Movement.LookDirection dir = mov.getLooking();
if(dir == Movement.LookDirection.Up) {
boomerangDirection = transform.up;
boomerangPosition += transform.up*0.25f + transform.forward*0.25f;
}
if(dir == Movement.LookDirection.Down) {
boomerangDirection = -transform.up;
boomerangPosition += -transform.up*0.25f - transform.forward*0.25f;
}
if(dir == Movement.LookDirection.Left)
boomerangDirection = -transform.right;
if(dir == Movement.LookDirection.Right)
boomerangDirection = transform.right;
} else {
boomerangDirection = direction.normalized;
}
GameObject item = (GameObject) Instantiate(Items.itemList[(int) myItem].prefab, boomerangPosition, transform.rotation);
item.GetComponent<Boomerang>().InitBoomerang(transform, boomerangDirection);
item.transform.SetParent(transform.parent);
haveBoomerang = false;
}
}
protected void OnBombs()
{
if (Input.GetButtonDown ("360_A"+id)) {
if(GeneralCanvasController.bombs <= 0) return;
--GeneralCanvasController.bombs;
Vector3 offset = transform.TransformPoint(GetComponent<OffsetPositionObject> ().getOffsetPosition ());
Vector3 bombPosition = offset;
GameObject item = (GameObject) Instantiate(Items.itemList[(int) myItem].prefab, bombPosition, transform.rotation);
item.transform.SetParent(transform.parent);
myAudio.Stop();
myAudio.clip = dropBomb;
myAudio.Play();
}
}
public void disableBow() {
bow.setBow (false);
}
protected void OnBow()
{
bow.setBow (true);
if (Input.GetButtonDown ("360_A"+id)) {
if(GeneralCanvasController.arrows <= 0) return;
--GeneralCanvasController.arrows;
Vector2 direction = mov.getWalkDirection();
Vector2 arrowDirection = Vector2.zero;
if(direction.magnitude == 0) {
Movement.LookDirection dir = mov.getLooking();
if(dir == Movement.LookDirection.Up) {
arrowDirection = transform.up;
}
if(dir == Movement.LookDirection.Down) {
arrowDirection = -transform.up;
}
if(dir == Movement.LookDirection.Left)
arrowDirection = -transform.right;
if(dir == Movement.LookDirection.Right)
arrowDirection = transform.right;
} else {
arrowDirection = direction.normalized;
}
GameObject item = (GameObject) Instantiate(Items.itemList[(int) myItem].prefab, bow.transform.position, transform.rotation);
item.GetComponent<Arrow>().InitArrow(transform,arrowDirection);
item.transform.SetParent(transform.parent);
}
}
public void disableShield() {
shield.setShield (false);
}
protected void OnMirrorShield()
{
shield.setShield (true);
}
public bool getMoonMode() {
return moonMode;
}
public void setMoonMode(bool moon) {
if(moonMode == moon) return;
moonMode = moon;
if (menu2.getMagicPoints () <= 0) moonMode = false;
if (moonMode) {
menu2.addMagicPoints(-5);
pearlCounter = pearlUseTime;
GetComponent<LightableObject> ().removeLightableObject ();
GetComponent<Movement>().setSpeed(1.6f);
myAudio.Stop();
myAudio.clip = activatePearl;
myAudio.Play();
} else {
GetComponent<LightableObject> ().addLightableObject ();
GetComponent<Movement>().setSpeed(1);
myAudio.Stop();
myAudio.clip = deactivatePearl;
myAudio.Play();
}
}
protected void OnMoonPearl()
{
if (Input.GetButtonDown ("360_A" + id)) setMoonMode(!moonMode);
if (moonMode) {
pearlCounter -= Time.deltaTime;
if(pearlCounter <= 0) {
menu2.addMagicPoints(-2);
pearlCounter += pearlUseTime;
}
bool onShadow = true;
PolygonCollider2D myMesh = GetComponent<PolygonCollider2D> ();
for (int i = 0; i < myMesh.GetTotalPointCount() && onShadow; i++) {
Vector2 localPoint = myMesh.points [i];
localPoint = localPoint + (localPoint - (Vector2)GetComponent<OffsetPositionObject> ().getOffsetPosition ()).normalized * 0.01f;
Vector2 worldPoint = myMesh.transform.TransformPoint (localPoint);
Vector3 position = new Vector3 (worldPoint.x, worldPoint.y, LightController.lightPosition - 1);
Debug.DrawRay (position, transform.forward * 2);
if (Physics.Raycast (position, transform.forward, 20, lightLayer)) onShadow = false;
}
if(!onShadow) setMoonMode(false);
if (menu2.getMagicPoints () <= 0) setMoonMode(false);
}
}
public bool getSunMode() {
return sunMode;
}
public void setSunMode(bool sun) {
if(sunMode == sun) return;
sunMode = sun;
if (menu2.getMagicPoints () <= 0) sunMode = false;
if (sunMode) {
menu2.addMagicPoints(-5);
pearlCounter = pearlUseTime;
GetComponent<LightableObject> ().removeLightableObject ();
GetComponent<Movement>().setSpeed(1.6f);
myAudio.Stop();
myAudio.clip = activatePearl;
myAudio.Play();
} else {
GetComponent<LightableObject> ().addLightableObject ();
GetComponent<Movement>().setSpeed(1);
myAudio.Stop();
myAudio.clip = deactivatePearl;
myAudio.Play();
}
}
protected void OnSunPearl()
{
if (Input.GetButtonDown ("360_A" + id)) setSunMode(!sunMode);
if (sunMode) {
pearlCounter -= Time.deltaTime;
if(pearlCounter <= 0) {
menu2.addMagicPoints(-2);
pearlCounter += pearlUseTime;
}
bool onLight = false;
PolygonCollider2D myMesh = GetComponent<PolygonCollider2D> ();
for (int i = 0; i < myMesh.GetTotalPointCount() && !onLight; i++) {
Vector2 localPoint = myMesh.points [i];
localPoint = localPoint + (localPoint - (Vector2)GetComponent<OffsetPositionObject> ().getOffsetPosition ()).normalized * 0.01f;
Vector2 worldPoint = myMesh.transform.TransformPoint (localPoint);
Vector3 position = new Vector3 (worldPoint.x, worldPoint.y, LightController.lightPosition - 1);
Debug.DrawRay (position, transform.forward * 2);
if (Physics.Raycast (position, transform.forward, 20, lightLayer)) onLight = true;
}
if(!onLight) setSunMode(false);
if (menu2.getMagicPoints () <= 0) setSunMode(false);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Spine.Unity;
public class Tutorial : MonoBehaviour {
public GameObject dialogos;
public GameObject window;
//ESCRITURA
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
}
void OnTriggerEnter (Collider col)
{
if(col.gameObject.name == "Hero")
{
col.gameObject.GetComponent<Hero>().caminarA = false;
col.gameObject.GetComponent<Hero>().caminarU = false;
col.gameObject.GetComponent<Hero>().caminarD = false;
col.gameObject.GetComponent<Hero>().caminarI = false;
col.gameObject.GetComponent<Hero>().ready = false;
dialogos.SetActive(true);
window.SetActive(true);
Destroy(gameObject);
}
}
}
|
using Microsoft.EntityFrameworkCore;
namespace HandCloud.Backend.Models
{
public class HandCloudContext : DbContext
{
public HandCloudContext(DbContextOptions<HandCloudContext> options) : base(options)
{
}
public DbSet<Car> Car { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Car>()
.Property(f => f.Id)
.ValueGeneratedOnAdd();
}
}
} |
using System;
using System.Collections.Generic;
public class ABZipMD5Infos
{
private List<MD5Info> _md5Infos = new List<MD5Info>();
public string zipName
{
get;
private set;
}
public List<MD5Info> md5Infos
{
get
{
return this._md5Infos;
}
}
public ABZipMD5Infos(string zipName)
{
this.zipName = zipName;
}
public void Add(string filename, string md5, long size)
{
MD5Info mD5Info = default(MD5Info);
mD5Info.fileName = filename;
mD5Info.md5 = md5;
mD5Info.size = size;
this._md5Infos.Add(mD5Info);
}
}
|
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="HttpRequest.cs" company="">
//
// </copyright>
// <summary>
// The http request.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace ConsoleWebServer.Framework.Http
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using ConsoleWebServer.Framework.Actions;
using ConsoleWebServer.Framework.Exceptions;
/// <summary>
/// The http request.
/// </summary>
public class HttpRequest : IHttpRequest
{
/// <summary>
/// Initializes a new instance of the <see cref="HttpRequest"/> class.
/// </summary>
/// <param name="stringRequest">
/// The string request.
/// </param>
/// <exception cref="ParserException">
/// </exception>
public HttpRequest(string stringRequest)
{
var textReader = new StringReader(stringRequest);
var commands = textReader.ReadLine().Split(' ');
if (commands.Length != 3)
{
throw new ParserException(
"Invalid format for the first request line. Expected format: [Method] [Uri] HTTP/[Version]");
}
this.Method = commands[0];
this.Uri = commands[1];
this.ProtocolVersion = Version.Parse(commands[2].ToLower().Replace("HTTP/".ToLower(), string.Empty));
this.Headers = new SortedDictionary<string, ICollection<string>>();
string line;
while ((line = textReader.ReadLine()) != null)
{
this.AddHeader(line);
}
this.Action = new ActionDescriptor(this.Uri);
}
/// <summary>
/// Gets or sets the protocol version.
/// </summary>
public Version ProtocolVersion { get; protected set; }
/// <summary>
/// Gets or sets the headers.
/// </summary>
public IDictionary<string, ICollection<string>> Headers { get; protected set; }
/// <summary>
/// Gets the uri.
/// </summary>
public string Uri { get; }
/// <summary>
/// Gets the method.
/// </summary>
public string Method { get; }
/// <summary>
/// Gets the action.
/// </summary>
public ActionDescriptor Action { get; }
/// <summary>
/// The to string.
/// </summary>
/// <returns>
/// The <see cref="string" />.
/// </returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.AppendLine(string.Format("{0} {1} {2}{3}", this.Method, this.Action, "HTTP/", this.ProtocolVersion));
var headerStringBuilder = new StringBuilder();
foreach (var key in this.Headers.Keys)
{
headerStringBuilder.AppendLine(string.Format("{0}: {1}", key, string.Join("; ", this.Headers[key])));
}
sb.AppendLine(headerStringBuilder.ToString());
return sb.ToString();
}
/// <summary>
/// The add header.
/// </summary>
/// <param name="headerLine">
/// The header line.
/// </param>
private void AddHeader(string headerLine)
{
var splitHeader = headerLine.Split(new[] { ':' }, 2);
var headerName = splitHeader[0].Trim();
var headerValue = splitHeader.Length == 2 ? splitHeader[1].Trim() : string.Empty;
if (!this.Headers.ContainsKey(headerName))
{
this.Headers.Add(headerName, new HashSet<string>(new List<string>()));
}
this.Headers[headerName].Add(headerValue);
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.