text stringlengths 13 6.01M |
|---|
using System;
using System.Collections.Generic;
using com.Sconit.Entity.PRD;
namespace com.Sconit.Service
{
public interface IRoutingMgr
{
IList<RoutingDetail> GetRoutingDetails(string routing, DateTime? effectiveDate);
}
}
|
using Microsoft.AspNetCore.Authorization;
namespace SFA.DAS.ProviderCommitments.Web.Authorization
{
public class ProviderRequirement : IAuthorizationRequirement
{
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using PopulationWars.Components;
using PopulationWars.Components.Governments;
using PopulationWars.Mechanics;
using static PopulationWars.Utilities.Constants;
using static PopulationWars.Utilities.Constants.GameAction;
namespace PopulationWars
{
public partial class PlayerWindow : Form
{
public Player Player { get; set; }
private GameAction m_action;
private List<Player> m_players;
private List<Nation> m_nations;
public PlayerWindow(GameAction action, List<Player> players, List<Nation> nations,
Player player = null)
{
m_action = action; // this needs to be prior to InitializeComponent() due to
// ListBox.SelectedIndexChanged event listener
InitializeComponent();
LoadWindowName(action);
/*var agentDataDir = Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar +
AgentsDataDirName;
Directory.CreateDirectory(agentDataDir);
foreach (var enumerateDirectory in Directory.EnumerateDirectories(agentDataDir))
{
typeListBox.Items.Add(enumerateDirectory.
Substring(enumerateDirectory.LastIndexOf(Path.DirectorySeparatorChar) + 1));
}*/
if (action == EditPlayer)
{
Player = player;
LoadPlayer(player);
}
else
PreselectListBoxes();
m_nations = nations;
m_players = players;
LoadNations(m_nations);
}
private void LoadNations(List<Nation> m_nations) =>
nationListBox.Items.AddRange(m_nations.ToArray());
private void LoadPlayer(Player player)
{
playerNameTextBox.Text = player.Name;
typeListBox.SelectedIndex = player.IsAgent ? 0 : 1;
colorButton.BackColor = player.Color;
nationNameTextBox.Text = player.Nation.Name;
nationListBox.Items.Add(player.Nation);
nationListBox.SelectedIndex = 1;
/*if (!player.IsAgent) return;
var name = Player.Nation.Government.GetType().Name;
foreach (var item in typeListBox.Items)
{
if (name.Equals(item.ToString()))
{
typeListBox.SelectedItem = item;
}
}*/
}
private void LoadWindowName(GameAction action) =>
Text = action == AddPlayer ? "Add Player" : "Edit Player";
private void PreselectListBoxes() =>
typeListBox.SelectedIndex = nationListBox.SelectedIndex =
governmentListBox.SelectedIndex = 0;
private void colorButton_Click(object sender, EventArgs e)
{
var colorDialog = new ColorDialog()
{
Color = colorButton.BackColor
};
if (colorDialog.ShowDialog() == DialogResult.OK)
{
colorButton.BackColor = colorDialog.Color;
}
}
private void saveButton_Click(object sender, EventArgs e)
{
var playerName = playerNameTextBox.Text;
var playerType = typeListBox.SelectedItem.ToString() == Agent ? true : false;
var color = colorButton.BackColor;
var nationName = nationNameTextBox.Text;
/*IGovernment gov;
if (playerType)
{
var className = typeListBox.SelectedItem.ToString();
var agent = (IAgent)System.Reflection.Assembly.GetExecutingAssembly().
CreateInstance(AgentsNamespace + "." + className);
if (agent == null)
{
MessageBox.Show("Agent not found.", "Warning",
MessageBoxButtons.OK, MessageBoxIcon.Warning);
DialogResult = DialogResult.None;
return;
}
var agentDataPath = Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar +
AgentsDataDirName + Path.DirectorySeparatorChar + className;
Directory.CreateDirectory(agentDataPath);
agent.SetDataPath(agentDataPath);
agent.LoadData(); // TODO: Load async if GUI lags
gov = agent;
}
else
{
gov = new RealPlayer();
}*/
var selectedGovernment = governmentListBox.SelectedItem.ToString();
var government = selectedGovernment == GovernmentType.Anarchy.ToString() ?
new Anarchy() : selectedGovernment == GovernmentType.HomeGrownNetwork.ToString() ?
new Components.Governments.HomeGrownNetwork() :
selectedGovernment == GovernmentType.AForgeNetwork.ToString() ?
(IGovernment)new AForgeNetwork() : new AgentBot();
var nation = nationListBox.SelectedIndex == 0 ?
new Nation(nationName, government) :
(m_action == EditPlayer && nationListBox.SelectedIndex == 1) ?
Player.Nation : new Nation(nationName, m_nations.Where(n => n.ToString() ==
nationListBox.SelectedItem.ToString()).First().Government);
var playerNameExists = m_players.Where(p => p.Name == playerName).Any();
var nationNameExists = m_action == AddPlayer ?
m_nations.Where(n => n.Name == nationName).Any() :
m_nations.Where(n => n.Name == nationName && Player.Nation.Name != nationName).
Any();
if (playerName == "")
{
MessageBox.Show("Player name cannot be empty string.", "Warning",
MessageBoxButtons.OK, MessageBoxIcon.Warning);
DialogResult = DialogResult.None;
return;
}
else if (m_action == AddPlayer && playerNameExists || m_action == EditPlayer &&
Player.Name != playerName && playerNameExists)
{
MessageBox.Show("Player name already exists.", "Warning",
MessageBoxButtons.OK, MessageBoxIcon.Warning);
DialogResult = DialogResult.None;
return;
}
else if (nation.Name == "")
{
MessageBox.Show("Nation name cannot be an empty string.", "Warning",
MessageBoxButtons.OK, MessageBoxIcon.Warning);
DialogResult = DialogResult.None;
return;
}
else if (nationNameExists)
{
MessageBox.Show("Nation name already exists.", "Warning",
MessageBoxButtons.OK, MessageBoxIcon.Warning);
DialogResult = DialogResult.None;
return;
}
if (m_action == EditPlayer)
{
Player.Name = playerName;
Player.IsAgent = playerType;
Player.Color = color;
Player.Nation.Name = nationName;
Player.Nation = nation;
if (nationListBox.SelectedIndex != 1)
m_nations.Add(nation);
}
else
{
Player = new Player(playerName, playerType, nation, color);
m_nations.Add(nation);
}
}
/*private void addAgentButton_Click(object sender, EventArgs e)
{
Form newAgentForm = new CreateAgentDialog();
newAgentForm.ShowDialog();
if (newAgentForm.DialogResult == DialogResult.OK)
{
var textBox = newAgentForm.Controls.OfType<TextBox>().FirstOrDefault();
if (textBox != null)
{
var name = textBox.Text;
Boolean exists = false;
foreach (var item in typeListBox.Items)
{
if (name.Equals(item))
{
exists = true;
}
}
if (!exists)
{
typeListBox.Items.Add(name);
typeListBox.SelectedItem = name;
}
else
{
MessageBox.Show("Agent already defined.", "Warning",
MessageBoxButtons.OK, MessageBoxIcon.Warning);
DialogResult = DialogResult.None;
}
}
}
newAgentForm.Dispose();
}*/
private void nationListBox_SelectedIndexChanged(object sender, EventArgs e)
{
if (nationListBox.SelectedIndex == 0)
{
nationNameTextBox.Enabled = true;
governmentListBox.Enabled = true;
}
else /*if (nationListBox.SelectedIndex == 1 && m_action == EditPlayer)*/
{
nationNameTextBox.Enabled = true;
governmentListBox.Enabled = false;
}
/*else
{
nationNameTextBox.Enabled = false;
governmentListBox.Enabled = false;
}*/
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ExemploMVC.BO;
using ExemploMVC.Model;
namespace ExemploMVC
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
grpAutor.Enabled = false;
grpLivro.Enabled = false;
}
private void btnNovoAutor_Click(object sender, EventArgs e)
{
grpAutor.Enabled = true;
}
private void btnNovoLivro_Click(object sender, EventArgs e)
{
grpLivro.Enabled = true;
}
private void btnGravarAutor_Click(object sender, EventArgs e)
{
Autor autor = new Autor();
AutorBO autorBO = new AutorBO();
autor.Nome = txtNome.Text;
autor.Nacionalidade = txtNacionalidade.Text;
autorBO.Gravar(autor);
MessageBox.Show("Autor cadastrado com sucesso");
grpAutor.Enabled = false;
txtNome.Clear();
txtNacionalidade.Clear();
}
}
}
|
using JT808.Protocol.Attributes;
using JT808.Protocol.Formatters;
using JT808.Protocol.MessagePack;
namespace JT808.Protocol.MessageBody
{
/// <summary>
/// 紧急报警时汇报时间间隔,单位为秒(s),>0
/// </summary>
public class JT808_0x8103_0x0028 : JT808_0x8103_BodyBase, IJT808MessagePackFormatter<JT808_0x8103_0x0028>
{
public override uint ParamId { get; set; } = 0x0028;
/// <summary>
/// 数据 长度
/// </summary>
public override byte ParamLength { get; set; } = 4;
/// <summary>
/// 紧急报警时汇报时间间隔,单位为秒(s),>0
/// </summary>
public uint ParamValue { get; set; }
public JT808_0x8103_0x0028 Deserialize(ref JT808MessagePackReader reader, IJT808Config config)
{
JT808_0x8103_0x0028 jT808_0x8103_0x0028 = new JT808_0x8103_0x0028();
jT808_0x8103_0x0028.ParamId = reader.ReadUInt32();
jT808_0x8103_0x0028.ParamLength = reader.ReadByte();
jT808_0x8103_0x0028.ParamValue = reader.ReadUInt32();
return jT808_0x8103_0x0028;
}
public void Serialize(ref JT808MessagePackWriter writer, JT808_0x8103_0x0028 value, IJT808Config config)
{
writer.WriteUInt32(value.ParamId);
writer.WriteByte(value.ParamLength);
writer.WriteUInt32(value.ParamValue);
}
}
}
|
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
using com.Sconit.Utility;
namespace com.Sconit.Web.Models
{
/// <summary>
/// Summary description for AccountModel
/// </summary>
public class ChangePasswordModel : BaseModel
{
public int Id { get; set; }
[Required(AllowEmptyStrings = false, ErrorMessageResourceName = "Errors_Common_FieldRequired", ErrorMessageResourceType = typeof(Resources.SYS.ErrorMessage))]
[StringLength(50, ErrorMessageResourceName = "Errors_Common_FieldLengthNotInRange", ErrorMessageResourceType = typeof(Resources.SYS.ErrorMessage), MinimumLength = 8)]
[DataType(DataType.Password)]
[Display(Name = "User_NewPassword", ResourceType = typeof(Resources.ACC.User))]
public string NewPassword { get; set; }
[Required(AllowEmptyStrings = false, ErrorMessageResourceName = "Errors_Common_FieldRequired", ErrorMessageResourceType = typeof(Resources.SYS.ErrorMessage))]
[DataType(DataType.Password)]
[Display(Name = "User_ConfirmNewPassword", ResourceType = typeof(Resources.ACC.User))]
// [Compare("NewPassword", ErrorMessageResourceName = "Errors_New_Password_And_Confirm_Password_NotEq", ErrorMessageResourceType = typeof(Resources.SYS.ErrorMessage))]
public string ConfirmPassword { get; set; }
}
public class UserChangePasswordModel : BaseModel
{
public int Id { get; set; }
[Required(AllowEmptyStrings = false, ErrorMessageResourceName = "Errors_Common_FieldRequired", ErrorMessageResourceType = typeof(Resources.SYS.ErrorMessage))]
[Display(Name = "User_Code", ResourceType = typeof(Resources.ACC.User))]
public string UserName { get; set; }
[Required(AllowEmptyStrings = false, ErrorMessageResourceName = "Errors_Common_FieldRequired", ErrorMessageResourceType = typeof(Resources.SYS.ErrorMessage))]
[DataType(DataType.Password)]
[Display(Name = "User_OldPassword", ResourceType = typeof(Resources.ACC.User))]
public string OldPassword { get; set; }
[Required(AllowEmptyStrings = false, ErrorMessageResourceName = "Errors_Common_FieldRequired", ErrorMessageResourceType = typeof(Resources.SYS.ErrorMessage))]
[StringLength(50, ErrorMessageResourceName = "Errors_Common_FieldLengthNotInRange", ErrorMessageResourceType = typeof(Resources.SYS.ErrorMessage), MinimumLength = 8)]
[DataType(DataType.Password)]
[Display(Name = "User_NewPassword", ResourceType = typeof(Resources.ACC.User))]
public string NewPassword { get; set; }
[Required(AllowEmptyStrings = false, ErrorMessageResourceName = "Errors_Common_FieldRequired", ErrorMessageResourceType = typeof(Resources.SYS.ErrorMessage))]
[DataType(DataType.Password)]
[Display(Name = "User_ConfirmNewPassword", ResourceType = typeof(Resources.ACC.User))]
// [Compare("NewPassword", ErrorMessageResourceName = "Errors_New_Password_And_Confirm_Password_NotEq", ErrorMessageResourceType = typeof(Resources.SYS.ErrorMessage))]
public string ConfirmPassword { get; set; }
}
public class LogOnModel : BaseModel
{
[Required(AllowEmptyStrings = false, ErrorMessageResourceName = "Errors_Common_FieldRequired", ErrorMessageResourceType = typeof(Resources.SYS.ErrorMessage))]
[Display(Name = "User_Code", ResourceType = typeof(Resources.ACC.User))]
public string UserName { get; set; }
[Required(AllowEmptyStrings = false, ErrorMessageResourceName = "Errors_Common_FieldRequired", ErrorMessageResourceType = typeof(Resources.SYS.ErrorMessage))]
[DataType(DataType.Password)]
[Display(Name = "User_Password", ResourceType = typeof(Resources.ACC.User))]
public string Password { get; set; }
public string HashedPassword { get { return EncryptHelper.Md5(Password); } }
[Display(Name = "User_RememberMe", ResourceType = typeof(Resources.ACC.User))]
public bool RememberMe { get; set; }
}
} |
namespace Forca.Repositorio.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class AdicionandoColunaDicaAPalavra : DbMigration
{
public override void Up()
{
this.AddColumn("dbo.Palavra", "Dica", c => c.String(nullable: false), null);
}
public override void Down()
{
this.DropColumn("dbo.Palavra", "Dica", null);
}
}
}
|
using System.Linq;
using System.Threading.Tasks;
using DFC.ServiceTaxonomy.GraphSync.Interfaces;
using DFC.ServiceTaxonomy.GraphSync.Models;
using FakeItEasy;
using Xunit;
using Xunit.Abstractions;
namespace DFC.ServiceTaxonomy.UnitTests.Neo4j.Services
{
public class GraphReplicaSetTests : GraphReplicaSetTestsBase
{
internal GraphReplicaSet GraphReplicaSet { get; set; }
public GraphReplicaSetTests(ITestOutputHelper testOutputHelper)
: base(testOutputHelper)
{
GraphReplicaSet = new GraphReplicaSet(ReplicaSetName, GraphInstances, Logger);
}
[Fact]
public void Run_Query_EvenCallsAcrossReplicasTest()
{
const int iterationsPerGraphInstance = 5;
const int numberOfIterations = NumberOfGraphInstances * iterationsPerGraphInstance;
Parallel.For(0, numberOfIterations, async (iteration) =>
{
await GraphReplicaSet.Run(Query);
});
int index = 0;
foreach (var graph in GraphInstances)
{
var calls = Fake.GetCalls(graph).ToList();
TestOutputHelper.WriteLine($"Graph #{index}: Run() called x{calls.Count}.");
++index;
}
foreach (var graph in GraphInstances)
{
A.CallTo(() => graph.Run(A<IQuery<int>[]>._))
.MustHaveHappened(iterationsPerGraphInstance, Times.Exactly);
}
}
[Fact]
public async Task Run_Query_LimitedToOneInstance_QueryIsRunOnCorrectInstance()
{
const int limitedToInstance = 2;
GraphReplicaSet = new GraphReplicaSet(ReplicaSetName, GraphInstances, Logger, limitedToInstance);
await GraphReplicaSet.Run(Query);
int index = 0;
foreach (var graph in GraphInstances)
{
var calls = Fake.GetCalls(graph).ToList();
TestOutputHelper.WriteLine($"Graph #{index}: Run() called x{calls.Count}.");
++index;
}
index = 0;
foreach (var graph in GraphInstances)
{
A.CallTo(() => graph.Run(A<IQuery<int>[]>._))
.MustHaveHappened(index == limitedToInstance ? 1 : 0, Times.Exactly);
++index;
}
}
[Fact]
public async Task Run_Command_CallsEveryReplica()
{
await GraphReplicaSet.Run(Command);
foreach (var graph in GraphInstances)
{
A.CallTo(() => graph.Run(A<ICommand[]>._))
.MustHaveHappened(1, Times.Exactly);
}
}
[Fact]
public async Task Run_Command_LimitedToOneInstance_CommandIsRunOnCorrectInstance()
{
const int limitedToInstance = 2;
GraphReplicaSet = new GraphReplicaSet(ReplicaSetName, GraphInstances, Logger, limitedToInstance);
await GraphReplicaSet.Run(Command);
int index = 0;
foreach (var graph in GraphInstances)
{
var calls = Fake.GetCalls(graph).ToList();
TestOutputHelper.WriteLine($"Graph #{index}: Run() called x{calls.Count}.");
++index;
}
index = 0;
foreach (var graph in GraphInstances)
{
A.CallTo(() => graph.Run(A<ICommand>._))
.MustHaveHappened(index == limitedToInstance ? 1 : 0, Times.Exactly);
++index;
}
}
[Fact]
public void InstanceCount_MatchesNumberOfInstances()
{
Assert.Equal(NumberOfGraphInstances, GraphReplicaSet.InstanceCount);
}
[Fact]
public void EnabledInstanceCount_MatchesNumberOfInstances()
{
Assert.Equal(NumberOfGraphInstances, GraphReplicaSet.EnabledInstanceCount());
}
[Fact]
public void IsEnabled_AllGraphInstancesAreEnabled()
{
for (int instance = 0; instance < NumberOfGraphInstances; ++instance)
{
Assert.True(GraphReplicaSet.IsEnabled(instance));
}
}
}
}
|
using Microsoft.Extensions.Caching.Memory;
using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static async Task Main(string[] args)
{
using var memoryCache = new MemoryCache(new MemoryCacheOptions());
var entryOptions = new MemoryCacheEntryOptions().SetAbsoluteExpiration(TimeSpan.FromMilliseconds(10));
using var asyncLock = new SemaphoreSlim(1, 1);
using var mre = new ManualResetEventSlim(true);
var syncLock = new object();
var tasks = new ConcurrentBag<Task>();
var datakey = 0;
var taskKey = 0;
var isAsync = true;
var sw = new Stopwatch();
sw.Start();
Console.WriteLine($"start pool: {ThreadPool.ThreadCount},dt:{DateTime.Now}");
Parallel.For(1, 10_000_000, i =>
{
tasks.Add(Task.Run(async () =>
{
if (memoryCache.TryGetValue(datakey, out int value))
{
// return data from cache
return;
}
if (isAsync)
{
if (memoryCache.TryGetValue(taskKey, out Task task) == false)
{
await asyncLock.WaitAsync();
try
{
if (memoryCache.TryGetValue(taskKey, out task) == false)
{
// http request emulation
task = DoWork(memoryCache, datakey, i, entryOptions);
memoryCache.Set(taskKey, task, entryOptions);
}
}
finally
{
asyncLock.Release();
}
}
await task;
// return data from server
}
else
{
if (memoryCache.TryGetValue(taskKey, out Task task) == false)
{
lock (syncLock)
{
if (memoryCache.TryGetValue(taskKey, out task) == false)
{
// http request emulation
task = DoWork(memoryCache, datakey, i, entryOptions);
memoryCache.Set(taskKey, task, entryOptions);
}
else
{
//Console.WriteLine($"task from cache: {i}");
}
}
}
// wait for http request result
await task;
}
}));
});
await Task.WhenAll(tasks);
sw.Stop();
Console.WriteLine($"time: {sw.ElapsedMilliseconds}");
}
private static async Task DoWork(IMemoryCache memoryCache, int datakey, int i,
MemoryCacheEntryOptions entryOptions)
{
await Task.Delay(1000);
Console.WriteLine($"pool: {ThreadPool.ThreadCount},set cache: {i}, dt:{DateTime.Now}");
memoryCache.Set(datakey, i, entryOptions);
}
}
}
|
using App.Core.Interfaces.Dto;
using App.Core.Interfaces.Dto.Requests;
using App.Core.Interfaces.Dto.Responses;
using App.Core.Interfaces.Managers;
using App.Core.Interfaces.Providers;
using App.Core.Interfaces.Services;
using App.Data.Models;
using AutoMapper;
using Easy.MessageHub;
namespace App.Core.Services
{
public class MessageService : IMessageService
{
protected IChatManager ChatManager { get; }
protected IMessageManager MessageManager { get; }
protected IUserManager UserManager { get; }
protected IEntityProvider<Message> MessageProvider { get; }
protected IEntityProvider<Chat> ChatProvider { get; }
protected IMessageHub MessageHub { get; }
protected IMapper Mapper { get; }
public MessageService(
// Manager.
IChatManager chatManager,
IMessageManager messageManager,
IUserManager userManager,
// Providers.
IEntityProvider<Message> messageProvider,
IEntityProvider<Chat> chatProvider,
// Message hub.
IMessageHub messageHub,
// Mapper.
IMapper mapper)
{
ChatManager = chatManager;
MessageManager = messageManager;
UserManager = userManager;
MessageProvider = messageProvider;
ChatProvider = chatProvider;
MessageHub = messageHub;
Mapper = mapper;
}
public MessageSendResponseDto Send(MessageSendRequestDto request)
{
int chatId;
if (request.ChatId == null)
{
var receiver = UserManager.GetUserById(request.UserId.Value);
chatId = ChatManager.GetOrCreateChatWithUser(request.User, receiver).ChatId;
}
else
{
chatId = request.ChatId.Value;
}
var chat = ChatManager.GetChatById(chatId);
var message = new Message
{
Author = request.User,
Chat = chat,
Text = request.Text
};
MessageProvider.Add(message);
MessageProvider.SaveChanges();
var chatDto = Mapper.Map<Chat, ChatDto>(chat);
var messageDto = Mapper.Map<Message, MessageDto>(message);
var userDto = Mapper.Map<User, UserDto>(request.User);
MessageHub.Publish(new NotificationDto
{
Type = NotificationType.CreateMessage,
TargetChatId = chatId,
TargetUserId = request.UserId
}
.AddEntity(messageDto)
.AddEntity(chatDto)
.AddEntity(userDto)
);
return new MessageSendResponseDto()
.AddEntity(messageDto)
.AddEntity(chatDto);
}
}
} |
using MediatR;
using System.Threading;
using System.Threading.Tasks;
namespace MikeGrayCodes.BuildingBlocks.Application.Behaviors
{
public interface IExistsHandler<TRequest>
where TRequest : IBaseRequest
{
Task<bool> Evaluate(TRequest request, CancellationToken cancellationToken = default);
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace fft
{
struct COMPLEX
{
public double real, imag;
public COMPLEX(double x, double y)
{
real = x;
imag = y;
}
public float Magnitude()
{
return ((float)Math.Sqrt(real * real + imag * imag));
}
public float Phase()
{
return ((float)Math.Atan(imag / real));
}
}
class Program
{
static void read(int pixelSize, double[,] array, BinaryReader br, FileStream fs)
{
for (int j = 0; j < pixelSize; j++)
{
for (int k = 0; k < pixelSize; k++)
{
array[j, k] = (double)br.ReadByte();//8 bit
}
}
br.Close();
fs.Close();
}
static void Main(string[] args)
{
FileStream fs = new FileStream("C:\\Users\\poh12\\OneDrive\\Desktop\\MR_data.raw", FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
//Program nana = new Program();
COMPLEX[,] Fourier = new COMPLEX[256, 512];
// read(256, Fourier, br, fs);
int pixelSize = 256;
for (int j = 0; j < pixelSize; j++)
{
for (int k = 0; k < pixelSize*2; k++)
{
Fourier[j, k].real = (double)br.ReadSingle();//8 bit
Fourier[j, k].imag = (double)br.ReadSingle();
// Fourier[j, k].real = (double)br.ReadByte();//8 bit
// Fourier[j, k].imag = (double)br.ReadByte();
// Console.WriteLine(Fourier[j, k].real + " " + Fourier[j, k].imag);
}
}
br.Close();
fs.Close();
FileStream fs0 = new FileStream("D:/data5.raw", FileMode.CreateNew, FileAccess.Write);
BinaryWriter bw0 = new BinaryWriter(fs0);
for (int j = 0; j < pixelSize; j++)
{
for (int k = 0; k < pixelSize*2; k++)
{
bw0.Write(Fourier[j, k].Magnitude());
// bw0.Write((float)Fourier[j, k].real);
//bw0.Write((float)Fourier[j, k].imag);
// Fourier[j, k].real = (double)br.ReadByte();//8 bit
// Fourier[j, k].imag = 0;
Console.WriteLine(Fourier[j, k].real + " " + Fourier[j, k].imag + " " + Fourier[j, k].Magnitude());
}
}
bw0.Close();
fs0.Close();
}
}
}
|
// <copyright file="Controllers.cs" company="Caspian Pacific Tech">
// Copyright (c) Caspian Pacific Tech. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace SmartLibrary.Site.Pages
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
/// <summary>
/// Controller Name
/// <CreatedBy>Hardik Panchal</CreatedBy>
/// <CreatedDate>14-Aug-2018</CreatedDate>
/// <ModifiedBy></ModifiedBy>
/// <ModifiedDate></ModifiedDate>
/// <ReviewBy>Hardik Panchal</ReviewBy>
/// <ReviewDate>14-Aug-2018</ReviewDate>
/// </summary>
public class Controllers
{
/// <summary>
/// Account Controller
/// </summary>
public static string Account { get { return "Account"; } }
/// <summary>
/// Home Controller
/// </summary>
public static string Home { get { return "Home"; } }
/// <summary>
/// Message Controller
/// </summary>
public static string Message { get { return "Message"; } }
/// <summary>
/// Login Controller
/// </summary>
public static string Login { get { return "Login"; } }
/// <summary>
/// User Controller
/// </summary>
public static string User { get { return "User"; } }
/// <summary>
/// Master Controller
/// </summary>
public static string Master { get { return "Master"; } }
/// <summary>
/// Member Controller
/// </summary>
public static string Member { get { return "Member"; } }
/// <summary>
/// Book Controller
/// </summary>
public static string Book { get { return "Book"; } }
/// <summary>
/// Library Room Bookings(Space Booking)
/// </summary>
public static string LibraryRoomBookings { get { return "Library-Room-Bookings"; } }
/// <summary>
/// Notification Controller
/// </summary>
public static string Notification { get { return "Notification"; } }
/// <summary>
/// Book Controller
/// </summary>
public static string Error { get { return "error"; } }
/// <summary>
/// Active Directory Controller
/// </summary>
public static string ActiveDirectory { get { return "ActiveDirectory"; } }
}
} |
using Core.IRepositories;
using Kafka1.Models;
using MongoDB.Bson;
using MongoDB.Bson.Serialization;
using MongoDB.Driver;
using Shared.Connections;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Repositories.OrderRepository
{
public class OrderRepository : IOrderRepository
{
private static IMongoDatabase _db;
public OrderRepository()
{
_db = MongoDBConnection._client.GetDatabase("testdb1");
}
/// <summary>
/// create order
/// </summary>
/// <param name="orderRequest"></param>
/// <returns></returns>
public async Task<string> createOrder(OrderRequest orderRequest, CancellationToken cancellationToken)
{
try
{
var col = _db.GetCollection<BsonDocument>("testModelCollection");
var doc = orderRequest.getBsonObject();
await col.InsertOneAsync(doc);
return orderRequest.orderId;
}
catch (Exception ex)
{
return null;
}
}
/// <summary>
/// update order
/// </summary>
/// <param name="orderRequest"></param>
/// <returns></returns>
public async Task<string> updateOrder(OrderRequest orderRequest, CancellationToken cancellationToken)
{
try
{
var col = _db.GetCollection<BsonDocument>("testModelCollection");
#region using with replace
//var doc = orderRequest.getBsonObject();
//var filter = Builders<BsonDocument>.Filter.Eq("orderId", orderRequest.orderId);
//await col.ReplaceOneAsync(filter, doc);
#endregion
#region update with update
var filter = Builders<BsonDocument>.Filter.Eq("orderId", orderRequest.orderId);
var update = Builders<BsonDocument>.Update.Set("clientId", orderRequest.clientId)
.Set("updatedBy", orderRequest.updatedBy)
.Set("updatedOn", orderRequest.updatedOn);
await col.UpdateOneAsync(filter, update);
#endregion
return orderRequest.orderId;
}
catch (Exception ex)
{
return null;
}
}
/// <summary>
/// Delete order
/// </summary>
/// <param name="orderId"></param>
/// <returns></returns>
public async Task<string> deleteOrder(string orderId, CancellationToken cancellationToken)
{
try
{
var col = _db.GetCollection<BsonDocument>("testModelCollection");
var filter = Builders<BsonDocument>.Filter.Eq("orderId", orderId);
await col.DeleteOneAsync(filter);
return orderId;
}
catch (Exception ex)
{
return null;
}
}
/// <summary>
/// Get by Id
/// </summary>
/// <param name="orderId"></param>
/// <returns></returns>
public async Task<OrderRequest> getOrderById(string orderId, CancellationToken cancellationToken)
{
try
{
var col = _db.GetCollection<OrderRequest>("testModelCollection");
//var filter = Builders<BsonDocument>.Filter.Eq("orderId", orderId);
var value = await col.FindAsync(s => s.orderId == orderId);
var res = value.FirstOrDefault();
return res;
//return BsonSerializer.Deserialize<OrderRequest>(res);
}
catch (Exception ex)
{
return null;
}
}
public async Task<List<OrderRequest>> getAllOrder(CancellationToken cancellationToken)
{
try
{
var col = _db.GetCollection<OrderRequest>("testModelCollection");
var value = await col.FindAsync(s => !string.IsNullOrEmpty(s.orderId));
var res = value.ToList();
return res;
}
catch (Exception ex)
{
return null;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using HospitalSystem.Models;
namespace HospitalSystem.Business
{
public class Medicine
{
private teamworkContext db = new teamworkContext();
public List<string> SearchMedicine(string medicineName)
{
var medicineSearch = db.medicines.Where(m => m.MedicineName.Contains(medicineName));
return medicineSearch.Select(medicine => medicine.MedicineName).ToList();
}
public medicine GetMedicineByName(string medicineName)
{
return db.medicines.FirstOrDefault(m => m.MedicineName.Equals(medicineName));
}
}
} |
using System.Collections.Generic;
using Slayer.Models;
using Slayer.Services;
namespace Slayer.DesignTimeData
{
public class MockStorageService : IStorageService
{
public void Save(Character character, string saveName)
{
return;
}
public Character Load(string saveName)
{
return new Character() {Name = saveName};
}
public IList<string> GetSavedGames()
{
return new List<string> {"Amero", "Euro", "Cad"};
}
}
} |
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using HTB.Database;
using HTB.v2.intranetx.routeplanter;
using HTB.v2.intranetx.routeplanter.bingmaps;
using HTB.v2.intranetx.util;
using HTBExtras.XML;
using HTBUtilities;
namespace HTB.v2.intranetx.aktenint.tablet
{
public partial class LoginTablet : System.Web.UI.Page
{
private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected void Page_Load(object sender, EventArgs e)
{
string userName = GlobalUtilArea.GetEmptyIfNull(Request.Params[GlobalHtmlParams.USER_NAME]).Replace("'", "''");
string password = GlobalUtilArea.GetEmptyIfNull(Request.Params[GlobalHtmlParams.PASSWORD]).Replace("'", "''");
try
{
var user = (tblUser)HTBUtils.GetSqlSingleRecord("SELECT * FROM tblUser WHERE UserUsername = '" + userName + "' AND UserPasswort = '" + password + "'", typeof(tblUser));
if(user == null)
{
Response.Write("ERROR: Benutzername oder Passwort falsch");
}
else if (user.UserStatus != 1 )
{
Response.Write("ERROR: Benutzer nicht erlaubt");
}
else
{
var rec = new XmlLoginRecord(user);
foreach (RouteFileRecord route in GetSavedRouteRecords(user.UserID))
{
rec.Roads.Add(new XmlRoadRecord {Date = route.RouteDate, Name = route.RouteName, RoadUserID = route.RouteUser.ToString()});
}
Response.Write(rec.ToXmlString());
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
Response.Write(ex.StackTrace);
}
}
private IEnumerable<RouteFileRecord> GetSavedRouteRecords(int userId)
{
Log.Info("RouteFolder: "+RoutePlanerManager.RouteFolder);
string[] fileEntries = Directory.GetFiles(RoutePlanerManager.RouteFolder);
Log.Info("FileEntries: " + fileEntries.Length);
return (from fileName in fileEntries
where fileName.EndsWith(RoutePlanerManager.RouteExtension)
select GetRouteFileRecord(fileName, Directory.GetCreationTime(fileName), userId) into rec
where rec != null
select rec).ToList();
}
private RouteFileRecord GetRouteFileRecord(string fileName, DateTime fileDate, int userId)
{
string[] tokens = fileName.Split('`');
if (tokens.Length == 3)
{
var rec = new RouteFileRecord
{
RouteUser = Convert.ToInt32(tokens[1]),
RouteName = tokens[2].Replace("." + RoutePlanerManager.RouteExtension, ""),
RouteDate = fileDate.ToShortDateString() + " " + fileDate.ToShortTimeString()
};
if (rec.RouteUser == userId)
{
Log.Info("checkign file: " + fileName + " " + fileDate + " " + userId);
try
{
/* read the road to make sure the file is not corrupted */
FileSerializer<RoutePlanerManager>.DeSerialize(RoutePlanerManager.GetRouteFilePath(rec.RouteUser, rec.RouteName));
Log.Info("File OK");
return rec;
}
catch
{
Log.Info("Corrupted file");
}
}
}
return null;
}
}
} |
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class TutorialFirst : MonoBehaviour {
[SerializeField]
private Image myImage;
[SerializeField]
private Sprite[] sprites;
[SerializeField]
private Text tut;
[SerializeField]
private GameObject nextLv;
[SerializeField]
private GameController gc;
[SerializeField]
private string[] tutTexts;
public void ChangeFace(bool happy)
{
CancelInvoke();
if (happy)
myImage.sprite = sprites[Random.Range(1, 3)];
else
myImage.sprite = sprites[Random.Range(3, 5)];
Invoke("BackFace", 1f);
}
void BackFace()
{
myImage.sprite = sprites[0];
}
public void ChangeFinal(Vector3 props)
{
if (props.z > 7 && props.x > 7 && props.y > 7)
{
myImage.sprite = sprites[2];
tut.text = tutTexts[0];
if(gc.GetEtapa().Equals(2))
tut.text = tutTexts[4];
nextLv.SetActive(true);
}
else if (props.z > 6 && props.x > 6 && props.y > 6)
{
myImage.sprite = sprites[1];
tut.text = tutTexts[1];
if (gc.GetEtapa().Equals(2))
tut.text = tutTexts[5];
nextLv.SetActive(true);
}
else if (props.z > 4 && props.x > 4 && props.y > 4)
{
myImage.sprite = sprites[0];
tut.text = tutTexts[2];
nextLv.SetActive(true);
if (gc.GetEtapa().Equals(2))
{
tut.text = tutTexts[6];
nextLv.SetActive(false);
}
}
else
{
myImage.sprite = sprites[3];
tut.text = tutTexts[3];
if (gc.GetEtapa().Equals(2))
tut.text = tutTexts[7];
nextLv.SetActive(false);
}
}
}
|
using System;
using Divar.Core.Commands.Advertisements.Commands;
using Divar.Core.Domain.Advertisements.Data;
using Divar.Core.Domain.Advertisements.ValueObjects;
using Divar.Framework.Domain.ApplicationServices;
using Divar.Framework.Domain.Data;
namespace Divar.Core.ApplicationService.Advertisements.CommandHandlers
{
public class UpdatePriceHandler : ICommandHandler<UpdatePriceCommand>
{
private readonly IAdvertisementRepository _repository;
private readonly IUnitOfWork _unitOfWork;
public UpdatePriceHandler(IAdvertisementRepository repository, IUnitOfWork unitOfWork)
{
_repository = repository;
_unitOfWork = unitOfWork;
}
public void Handle(UpdatePriceCommand command)
{
var advertisement = _repository.Load(command.Id);
if (advertisement == null)
throw new InvalidOperationException($"آگهی با شناسه {command.Id} یافت نشد.");
advertisement.UpdatePrice(Price.FromLong(command.Price));
_unitOfWork.Commit();
}
}
} |
using Microsoft.ApplicationInsights.Extensibility;
// ReSharper disable once CheckNamespace
namespace Microsoft.Extensions.DependencyInjection
{
public static class ApplicationInsightsExtensions
{
public static IServiceCollection AddCallingIdentityTelemetryInitializer(this IServiceCollection services)
{
services.AddSingleton<ITelemetryInitializer, CallingIdentityTelemetryInitializer>();
services.AddSingleton<ITelemetryInitializer, Accept4xxResponseAsSuccessInitializer>();
return services;
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;
namespace Entities.DTOs.UpdateDtos
{
public class CityForUpdateDto
{
[MaxLength(60, ErrorMessage = "Maximum length for the city name is 60 characters.")]
public string Name { get; set; }
}
}
|
using FichaTecnica.Dominio;
using FichaTecnica.Dominio.Repositorio;
using FichaTecnica.Models;
using FichaTecnica.Repositorio.EF;
using FichaTecnica.Seguranca.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace FichaTecnica.Controllers
{
public class DetalhesProjetoController : Controller
{
private IProjetoRepositorio dataBase = new ProjetoRepositorio();
private IMembroRepositorio dataBaseMembro = new MembroRepositorio();
private IUsuarioRepositorio dataBaseUsuario = new UsuarioRepositorio();
private IComentarioRepositorio dataBaseComentario = new ComentarioRepositorio();
[Autorizador]
public ActionResult TelaDetalhes(int Id)
{
Projeto projeto = dataBase.BuscarProjetoPorId(Id);
IList<Membro> membrosDoProjeto = dataBaseMembro.BuscarMembroPorProjeto(projeto);
membrosDoProjeto = dataBaseMembro.BuscarCargoMembros(membrosDoProjeto);
projeto.Membros = membrosDoProjeto;
List<Usuario> usuarios = new List<Usuario>();
foreach(var usuario in projeto.Usuarios)
{
usuarios.Add(dataBaseUsuario.BuscarPorId(usuario.Id));
}
List<MembroDetalheProjetoModel> detalhesMembros = new List<MembroDetalheProjetoModel>();
foreach (var membro in projeto.Membros)
{
MembroDetalheProjetoModel membroDetalheProjetoModel = new MembroDetalheProjetoModel(membro);
List<LinkFork> link = dataBaseMembro.BuscarLinkMembroDoProjeto(projeto.Id,membro.Id);
membroDetalheProjetoModel.LinksGithub = new GraficoAtividadesModel(link);
detalhesMembros.Add(membroDetalheProjetoModel);
List<Comentario>comentarios = dataBaseComentario.BuscarComentariosPorMembro(membroDetalheProjetoModel.Id);
foreach(var comentario in comentarios)
{
if (comentario.Tipo == Tipo.POSITIVO)
{
membroDetalheProjetoModel.TotalComentariosPosivo++;
}
else
membroDetalheProjetoModel.TotalComentarioNegativo++;
}
}
TelaDetalhesModel model = new TelaDetalhesModel();
model.Projeto = projeto;
model.Usuarios = usuarios;
model.MembrosDoProjeto = detalhesMembros;
return View(model);
}
}
} |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml;
//
// BSD 3-Clause License
//
// Copyright (c) 2020, Pharap (@Pharap)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
namespace PlaylistGenerator
{
class Program
{
static void Main(string[] args)
{
if (args.Length == 0)
{
Console.WriteLine("Usage: <path> ...");
return;
}
var files = GetFiles(args);
if(files.Length > 0)
Process(files);
var directories = GetDirectories(args);
if (directories.Length > 0)
Process(directories);
}
static FileInfo[] GetFiles(IEnumerable<string> args)
{
return args.Select(path => new FileInfo(path)).Where(info => info.Exists).ToArray();
}
static void Process(IEnumerable<FileInfo> files)
{
Process(new DirectoryInfo(Environment.CurrentDirectory), files);
}
static DirectoryInfo[] GetDirectories(IEnumerable<string> args)
{
return args.Select(path => new DirectoryInfo(path)).Where(info => info.Exists).ToArray();
}
static void Process(IEnumerable<DirectoryInfo> directories)
{
foreach (var directory in directories)
Process(directory);
}
static void Process(DirectoryInfo directory)
{
Process(directory, EnumerateAllFiles(directory));
}
static IEnumerable<FileInfo> EnumerateAllFiles(DirectoryInfo rootDirectory)
{
var stack = new Queue<DirectoryInfo>();
stack.Enqueue(rootDirectory);
while (stack.Count > 0)
{
var currentDirectory = stack.Dequeue();
var directories = currentDirectory
.EnumerateDirectories()
.OrderBy(info => info.Name);
foreach (var directory in directories)
stack.Enqueue(directory);
var files = currentDirectory
.EnumerateFiles()
.Where(info => mediaExtensions.Contains(Path.GetExtension(info.FullName)))
.OrderBy(info => info.Name);
foreach (var file in files)
yield return file;
}
}
static readonly HashSet<string> videoExtensions = new HashSet<string>
{
".mp4", ".mkv", ".webm"
};
static readonly HashSet<string> audioExtensions = new HashSet<string>
{
".mp3", ".m4a", ".wav"
};
static readonly HashSet<string> mediaExtensions =
new HashSet<string>(Enumerable.Concat(videoExtensions, audioExtensions));
static void Process(DirectoryInfo directory, IEnumerable<FileInfo> files)
{
using (var writer = CreateWriter(directory))
{
writer.WriteStartDocument();
{
writer.WriteStartElement("playlist", "http:" + "//xspf.org/ns/0/");
writer.WriteAttributeString("version", "1");
writer.WriteElementString("title", directory.Name);
{
writer.WriteStartElement("trackList");
{
WriteTrackList(writer, directory, files);
}
writer.WriteEndElement();
}
}
writer.WriteEndDocument();
}
}
static XmlWriter CreateWriter(DirectoryInfo directory)
{
var writerPath = Path.Combine(directory.FullName, directory.Name + ".xspf");
var settings = new XmlWriterSettings()
{
Indent = true,
IndentChars = "\t"
};
return XmlTextWriter.Create(writerPath, settings);
}
static void WriteTrackList(XmlWriter writer, DirectoryInfo root, IEnumerable<FileInfo> files, int trackStart = 1)
{
foreach (var pair in files.Zip(Enumerable.Range(trackStart, int.MaxValue), Tuple.Create))
{
var video = pair.Item1;
var trackNum = pair.Item2;
writer.WriteStartElement("track");
writer.WriteElementString("trackNum", trackNum.ToString());
writer.WriteElementString("title", Path.GetFileNameWithoutExtension(video.Name));
writer.WriteElementString("location", MakeRelativeUri(root, video));
var fileName = Path.GetFileNameWithoutExtension(video.Name);
var relatives = video.Directory
.EnumerateFiles(fileName + ".*")
.ToLookup(info => Path.GetExtension(info.FullName));
foreach (var descriptionFile in relatives[".description"])
writer.WriteElementString("annotation", File.ReadAllText(descriptionFile.FullName));
foreach (var imageExtension in imageExtensions)
foreach (var imageFile in relatives[imageExtension])
writer.WriteElementString("image", MakeRelativeUri(root, imageFile));
writer.WriteEndElement();
}
}
static readonly HashSet<string> imageExtensions = new HashSet<string>
{
".png", ".jpg", ".jpeg"
};
static string MakeRelativeUri(DirectoryInfo rootDirectory, FileInfo file)
{
int start = file.FullName.IndexOf(rootDirectory.FullName);
if (start == -1)
throw new Exception("FileInfo was not contained in DirectoryInfo");
int end = start + rootDirectory.FullName.Length;
string relative = file.FullName.Substring(end);
return Uri.EscapeUriString(relative).Replace("#", "%23");
}
}
}
|
using CommonServiceLocator;
using TopJSRepos.Services;
using TopJSRepos.ViewModels;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace TopJSRepos.Views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class RepositoriesPage : ContentPage
{
public RepositoriesPage()
{
InitializeComponent();
BindingContext = ServiceLocator.Current.GetInstance(typeof(RepositoriesViewModel));
}
}
} |
namespace Game
{
/// <summary>
/// Has all object types
/// </summary>
public enum Objects
{
Wall,
Minion,
Boss,
SmallPowerups,
MediumPowerups,
LargePowerups,
Player,
Victory,
None
}
}
|
using System;
using System.Collections.Generic;
namespace Sitecore.Ship.Core.Domain
{
public class ItemToPublishProperties
{
public Guid ItemId { get; set; }
public bool PublishChildren { get; set; }
public bool PublishRelatedItems { get; set; }
public ItemToPublishProperties()
{
ItemId = new Guid();
PublishChildren = false;
PublishRelatedItems = false;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Task2.Figures
{
class Round : Circle
{
public Round(double radius) : base(radius) { }
public Round(double x, double y, double radius) : base(x, y, radius) { }
public double Area
{
get => Math.Pow(Radius, 2) * Math.PI;
}
public override void Parametres()
{
Console.WriteLine("Figure : {0};\n" +
"Origin point : X = {1:0.#}, Y = {2:0.#};\n" +
"Radius : {3:0.#};\n" +
"Length : {4:0.#};\n" +
"Area : {5:0.#};",
"Round", X, Y, Radius, Length, Area);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataLibrary.Models
{
public class UserModel
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string EmailAddress { get; set; }
public string Username { get; set; }
public UserModel(string firstName, string lastName, string emailAddress, string username)
{
FirstName = firstName;
LastName = lastName;
EmailAddress = emailAddress;
Username = username;
}
public override string ToString()
{
return FirstName + " " + LastName;
}
}
}
|
using EddiDataDefinitions;
using System;
using Utilities;
namespace EddiEvents
{
[PublicAPI]
public class ModuleArrivedEvent : Event
{
public const string NAME = "Module arrived";
public const string DESCRIPTION = "Triggered when your transferred module is arriving at its destination";
public static ModuleArrivedEvent SAMPLE = new ModuleArrivedEvent(DateTime.UtcNow, "Adder", 106, 25, 128662525, Module.FromEDName("$hpt_cloudscanner_size0_class1_name;"), 322, 30, "Lalande 32151", "Lee Gateway");
[PublicAPI("The ship you were in when you requested the transfer")]
public string ship { get; private set; }
[PublicAPI("The ID of the ship you were in when you requested the transfer")]
public int? shipid { get; private set; }
[PublicAPI("The module (object) being transferred")]
public Module module { get; private set; }
[PublicAPI("The cost for the module transfer")]
public long transfercost { get; private set; }
[PublicAPI("The time elapsed during the transfer (in seconds)")]
public long? transfertime { get; private set; }
[PublicAPI("The system at which the module shall arrive")]
public string system { get; private set; }
[PublicAPI("The station at which the module shall arrive")]
public string station { get; private set; }
// Not intended to be user facing
public int storageslot { get; private set; }
public long serverid { get; private set; }
public ModuleArrivedEvent(DateTime timestamp, string ship, int? shipid, int storageslot, long serverid, Module module, long transfercost, long? transfertime, string system, string station) : base(timestamp, NAME)
{
this.ship = ShipDefinitions.FromEDModel(ship).model;
this.shipid = shipid;
this.storageslot = storageslot;
this.serverid = serverid;
this.module = module;
this.transfercost = transfercost;
this.transfertime = transfertime;
this.system = system;
this.station = station;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SSISTeam9.Models;
using SSISTeam9.Services;
using System.Threading.Tasks;
using SSISTeam9.Filters;
namespace SSISTeam9.Controllers
{
[StoreAuthorisationFilter]
public class StockController : Controller
{
public async Task<ActionResult> All(string sessionId)
{
//Contact Python API to get predicted re-order amount and level for item with code 'P021' and 'P030'
//Done via StockService
List<Inventory> items = await StockService.GetAllItemsOrdered();
//Show the quantities which are being ordered by all store staff
items = StockService.GetPendingOrderQuantities(items);
ViewData["items"] = items;
ViewData["sessionId"] = sessionId;
return View();
}
public async Task<ActionResult> EnterQuantities(Inventory inventory, string sessionId)
{
//Contact Python API to get predicted re-order amount and level for item with code 'P021' and 'P030'
List<Inventory> stock = await StockService.GetAllItemsOrdered();
List<Inventory> selectedItems = new List<Inventory>();
try
{
for (int i = 0; i < stock.Count; i++)
{
if (inventory.CheckedItems[i] == true)
{
selectedItems.Add(stock[i]);
}
}
}
catch (NullReferenceException)
{
return RedirectToAction("All", new { sessionid = sessionId });
}
ViewData["selectedItems"] = selectedItems;
ViewData["sessionId"] = sessionId;
return View();
}
public ActionResult CreatePurchaseOrders(Inventory item, FormCollection formCollection, string sessionId)
{
List<int> itemsQuantities = new List<int>();
List<long> itemIds = new List<long>();
string counter = formCollection["counter"];
string empId = EmployeeService.GetUserBySessionId(sessionId).EmpId.ToString();
for (int i = 0; i < int.Parse(counter); i++)
{
itemsQuantities.Add(int.Parse(formCollection["quantity_" + i]));
itemIds.Add(StockService.GetItemId(formCollection["item_" + i]));
}
List<long> itemsFirstSupplierIds = StockService.GetItemsFirstSupplierIds(itemIds);
StockService.CreatePurchaseOrders(empId,itemIds,itemsFirstSupplierIds,itemsQuantities);
return RedirectToAction("All", new {sessionid = sessionId});
}
//The following code used for Stock taking in order to generate Adjustment Voucher
public ActionResult Check(string sessionId)
{
List<Inventory> inventories = CatalogueService.GetAllCatalogue();
ViewData["inventories"] = inventories;
ViewData["sessionId"] = sessionId;
return View();
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Tilemaps;
using MEC;
using Mechanics.Tiles;
using Mechanics.Trail;
namespace Mechanics.Player{
public class SlimeManager : MonoBehaviour{
public GameObject gameGridObject;
public GameObject trailGridObject;
public GameObject baseSlime;
public GameObject canMoveArrowPrefabs;
public float mergeDelay;
public Tilemap gameTM;
List<Slime> slimes;
TrailManager trailMan;
void Awake(){
slimes = new List<Slime>(gameObject.GetComponentsInChildren<Slime>());
gameTM = gameGridObject.GetComponentInChildren<Tilemap>(true);
trailMan = trailGridObject.GetComponent<TrailManager>();
}
void Start(){
foreach(var s in slimes){
s.Spawn(s.location);
}
}
void Update(){}
public bool SubmitSlime(Slime s){
slimes.Remove(s);
s.Despawn(true);
return(slimes.Count == 0);
}
public Slime GetSlimeOnCoord(Vector3Int coord){
foreach(var s in slimes){
if(s.location.x == coord.x && s.location.y == coord.y){
return s;
}
}
return null;
}
public void MergeSlimes(Slime s0, Slime s1){
Debug.Log("Merge begins!");
var newSlimeGO = Instantiate(baseSlime, gameObject.transform);
var newSlime = newSlimeGO.GetComponent<Slime>();
if(canMoveArrowPrefabs != null)
{
var newArrowGO = Instantiate(canMoveArrowPrefabs, newSlimeGO.transform.position + new Vector3(0,0.75f,0), Quaternion.identity, newSlimeGO.transform);
newSlime.canMoveArrow = newArrowGO;
}
slimes.Add(newSlime);
slimes.Remove(s0);
slimes.Remove(s1);
s0.Despawn(false);
s1.Despawn(false);
s0.DisableMove();
s1.DisableMove();
newSlime.componentSlime[0] = s0;
newSlime.componentSlime[1] = s1;
newSlime.SetColor(s0.r || s1.r, s0.g || s1.g, s0.b || s1.b);
newSlime.Spawn(s0.location);
}
public void SplitSlimes(Slime source, Vector3Int dir0, Vector3Int dir1){
var s0 = source.componentSlime[0];
var s1 = source.componentSlime[1];
// If base slime, return.
if(s0 == null || s1 == null) return;
trailMan.DrawTrail(source.location, source.slimeChars, new Vector3Int(0, 0, 0), source.direction);
slimes.Add(s0);
slimes.Add(s1);
slimes.Remove(source);
s0.Spawn(source.location + dir0);
s1.Spawn(source.location + dir1);
source.Despawn(true);
Destroy(source.canMoveArrow);
// Enable all slime to move after all has moved
bool allMoved = true;
foreach(var s in slimes)
allMoved = allMoved && s.moved;
if(allMoved){
foreach(var s in slimes){
s.EnableMove();
allMoved = allMoved && s.moved;
}
}
}
// Respond to click on given target
public bool MoveSlimes(Vector3Int target, TileChar tc, Tilemap tm){
bool someMoved = false;
bool allMoved = true;
// Return value is whether a slime has been moved
foreach(var s in slimes){
var pastLoc = s.location;
bool moved = s.MoveIfValid(target, tc);
if(moved){
trailMan.DrawTrail(pastLoc, s.slimeChars, s.direction, s.prevDir);
someMoved = true;
}
allMoved = allMoved && s.moved;
}
// Merge routine; look for matches; exit loop, and merge
int ic = 0;
while(ic< 50){
Slime s0 = null;
Slime s1 = null;
foreach (var s in slimes){
bool foundMatch = false;
foreach (var os in slimes){
if(os == s) continue;
if(os.location == s.location){
foundMatch = true;
s1 = s;
s0 = os;
break;
}
}
if (foundMatch) break;
}
if(s0 == null && s1 == null) break;
MergeSlimes(s0, s1);
ic++;
}
// Enable all slime to move after all has moved
if(allMoved){
foreach(var s in slimes){
s.EnableMove();
allMoved = allMoved && s.moved;
}
}
return someMoved;
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DestroyAudio : MonoBehaviour {
// Use this for initialization
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Destroy(gameObject);
}
}
}
|
using Citycykler.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace CityCykler
{
public partial class kontaktPage : System.Web.UI.Page
{
DataLinqDB db = new DataLinqDB();
protected void Page_Load(object sender, EventArgs e)
{
var k = db.kontakts.FirstOrDefault(i => i.id == 1);
if (k != null)
{
LiteralKontakt.InnerHtml = k.text;
ImgKontakt.Text = "<img src='img/" + k.img + "' style='width:200px' />";
}
}
protected void ButtonSendMail_Click(object sender, EventArgs e)
{
Regex KontaktPerson = new Regex(@"[a-zA-Z0-9'!#$%& ,.'*+=?^_`-]{1,50}");
Regex Telefon = new Regex(@"[a-zA-Z0-9'!#$%& ,.'*+=?^_`-]{1,50}");
Regex Email = new Regex(@"[a-zA-Z0-9'!#$%& ,.'*+=?^_`-]{1,50}");
Regex Ask = new Regex(@"[a-zA-Z0-9'!#$%& ,.'*+=?^_`-]{1,50}");
string firmaInput = TBFirma.Text;
string KontaktPersonInput = TBKontaktPerson.Text;
string TelefonInput = TBTelefon.Text;
string EmailInput = TBEmail.Text;
string AskInput = TBAsk.Text;
if ((KontaktPerson.IsMatch(KontaktPersonInput)) && (Telefon.IsMatch(TelefonInput)) && (Email.IsMatch(EmailInput)) && (Ask.IsMatch(AskInput)))
{
//sender email til mig
//string titel = "Email fra: " + EmailInput;
//MailDefinition oMailDefinition = new MailDefinition();
//oMailDefinition.BodyFileName = "~/mail.html";
//var k = db.kontakts.FirstOrDefault();
//oMailDefinition.From = k.mail;
//Dictionary<string, string> oReplacements = new Dictionary<string, string>();
//oReplacements.Add("<<navn>>", KontaktPersonInput);
//oReplacements.Add("<<mail>>", EmailInput);
//oReplacements.Add("<<mobil>>", TelefonInput);
//oReplacements.Add("<<indhold>>", AskInput);
//System.Net.Mail.MailMessage oMailMessage = oMailDefinition.CreateMailMessage(KontaktPersonInput, oReplacements, new LiteralControl());
//oMailMessage.Subject = titel;
//oMailMessage.IsBodyHtml = true;
//SmtpClient smtp = new SmtpClient("API HERE!!");
//System.Net.NetworkCredential netcred = new System.Net.NetworkCredential("SMTP NAME", "PASSWORD");
//smtp.UseDefaultCredentials = false;
//smtp.EnableSsl = true;
//smtp.Credentials = netcred;
//smtp.Port = Convert.ToInt32("25");
//smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
//try
//{
// smtp.Send(oMailMessage);
//}
//catch (Exception ex)
//{
// throw ex;
//}
LabelSucces.Text = "Vi kontakter dig så hurtigt som muligt!";
}
else
{
Error.Text = HelperClassText.HelperText.TryAgain();
}
}
}
} |
namespace ApartmentApps.Api.Modules
{
public enum LeaseState
{
Suspended,
Archived,
Active
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class StatusTextController : MonoBehaviour
{
TextMeshProUGUI textRenderer;
void Awake()
{
textRenderer = GetComponent<TextMeshProUGUI>();
}
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
void OnGodSaysGameStateChanged(GameState newState)
{
if(newState == GameState.WAIT_FOR_INPUT)
{
textRenderer.text = "PLAY";
}
else if(newState == GameState.PLAYING)
{
textRenderer.text = "";
}
else if(newState == GameState.WAIT_FOR_RESTART)
{
textRenderer.text = "GAME OVER";
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PanelBuangHandler : MonoBehaviour {
[HideInInspector]
public int slotIndex; //Dimulai dari 0
[HideInInspector]
public GameObject player;
public GameObject itemImage;
public GameObject inputField;
private Player playerScript;
void Awake()
{
playerScript = player.GetComponent<Player>();
}
void OnEnable()
{
inputField.GetComponent<InputField>().text = "1";
itemImage.GetComponent<Image>().sprite = Resources.Load<Sprite>("Items/" + playerScript.inventoryName[slotIndex]);
}
public void BtnUp()
{
var count = int.Parse(inputField.GetComponent<InputField>().text);
count++;
if(count > playerScript.inventoryCount[slotIndex])
{
count = playerScript.inventoryCount[slotIndex];
}
inputField.GetComponent<InputField>().text = count.ToString();
}
public void BtnDown()
{
var count = int.Parse(inputField.GetComponent<InputField>().text);
count--;
if (count < 1)
{
count = 1;
}
inputField.GetComponent<InputField>().text = count.ToString();
}
public void BtnBuang()
{
var count = int.Parse(inputField.GetComponent<InputField>().text);
if(playerScript.inventoryCount[slotIndex] - count == 0)
{
playerScript.inventoryCount.RemoveAt(slotIndex);
playerScript.inventoryName.RemoveAt(slotIndex);
}
else
{
playerScript.inventoryCount[slotIndex] -= count;
}
playerScript.ShowInventory();
playerScript.CountInventory();
playerScript.CheckCraft();
}
public void InputFieldChange()
{
if(int.Parse(inputField.GetComponent<InputField>().text) < 1)
{
inputField.GetComponent<InputField>().text = "1";
}
else if(int.Parse(inputField.GetComponent<InputField>().text) > playerScript.inventoryCount[slotIndex])
{
inputField.GetComponent<InputField>().text = playerScript.inventoryCount[slotIndex].ToString();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using InterfaceService.Models;
using Microsoft.AspNetCore.Http;
using InterfaceService.Services;
using Newtonsoft.Json.Linq;
using System.Text.RegularExpressions;
using System.IO;
namespace InterfaceService.Controllers
{
public class InterfaceController : Controller
{
private TextRecognitionService _textRecognitionService;
private SpacyService _spacyService;
public InterfaceController(TextRecognitionService textRecognitionService, SpacyService spacyService)
{
_textRecognitionService = textRecognitionService;
_spacyService = spacyService;
}
public IActionResult Index()
{
return View();
}
[HttpPost]
public async Task<IActionResult> Process(IFormFile file)
{
//var fileExtention = Path.GetExtension(file.FileName);
//if (!string.Equals(fileExtention, ".jpg", StringComparison.OrdinalIgnoreCase)
// && !string.Equals(fileExtention, ".png", StringComparison.OrdinalIgnoreCase)
// && !string.Equals(fileExtention, ".gif", StringComparison.OrdinalIgnoreCase)
// && !string.Equals(fileExtention, ".jpeg", StringComparison.OrdinalIgnoreCase))
//{
//}
var text = await _textRecognitionService.ConvertPdfToText(file);
var entities_str = await _spacyService.GetEntities(text);
JObject entities_json = JObject.Parse(entities_str);
string rawText = "";
JToken ents_json = null;
List<List<string>> entities = new List<List<string>>();
foreach (var ent in entities_json)
{
if (ent.Key.Equals("text"))
rawText = ent.Value.ToString();
if (ent.Key.Equals("ents"))
ents_json = ent.Value;
}
//rawText = Regex.Replace(rawText, @"\t|\n|\r", "");
TextToken[] ents_json_list = ents_json.ToObject<TextToken[]>();
foreach (var ent in ents_json_list)
{
List<string> entity = new List<string>();
string textData = rawText.Substring(ent.Start, ent.End-ent.Start);
string labelData = ent.Label;
entity.Add(textData);
entity.Add(labelData);
entities.Add(entity);
}
ViewData["entities"] = entities;
return View();
}
}
}
|
using System.Collections.Generic;
using UnityEngine;
public class DrawManager : MonoBehaviour
{
struct udsMinMaxData
{
public float min{ get; set; }
public float max{ get; set; }
public string name { get;set; }
public udsMinMaxData(string v_name, float v_min, float v_max)
{
name = v_name;
min = v_min;
max = v_max;
}
}
const float DRAW_SPHERE_RADIO = 0.05f;
[SerializeField] Camera m_camera;
[SerializeField] DetectCollider m_clsDetectObj_A;
float m_fCenterHight;
Vector3 m_v3CenterPos;
static List<DetectCollider> m_lisData;
void Awake()
{
m_lisData = new List<DetectCollider>();
}
public static void Regist(DetectCollider r_obj)
{
m_lisData.Add(r_obj);
}
void Update()
{
if (m_lisData.Count >= 2)
{
if (CalTrigger() == true)
{
for (int i = 0; i < m_lisData.Count; i++)
m_lisData[i].TriggerEvent(false);
}
else
{
for (int i = 0; i < m_lisData.Count; i++)
m_lisData[i].TriggerEvent(true);
}
}
}
bool CalTrigger()
{
for (int i = 0; i < m_lisData[0].normals.Length; i++)
{
udsMinMaxData sttMinMaxDataA = GetMinMax(m_lisData[0].objName, m_lisData[0].finalPoints2D, m_lisData[0].normals[i]);
udsMinMaxData sttMinMaxDataB = GetMinMax(m_lisData[1].objName, m_lisData[1].finalPoints2D, m_lisData[0].normals[i]);
if (sttMinMaxDataA.min > sttMinMaxDataB.max || sttMinMaxDataB.min > sttMinMaxDataA.max)
return true;
}
for (int i = 0; i < m_lisData[1].normals.Length; i++)
{
udsMinMaxData sttMinMaxDataA = GetMinMax(m_lisData[0].objName, m_lisData[0].finalPoints2D, m_lisData[1].normals[i]);
udsMinMaxData sttMinMaxDataB = GetMinMax(m_lisData[1].objName, m_lisData[1].finalPoints2D, m_lisData[1].normals[i]);
if (sttMinMaxDataA.min > sttMinMaxDataB.max || sttMinMaxDataB.min > sttMinMaxDataA.max)
return true;
}
return false;
}
udsMinMaxData GetMinMax(string v_name, Vector2[] r_verticex, Vector2 v_axis)
{
float fMin_DotPorduct = Common.GetProjectLenghtOnto(r_verticex[0], v_axis);
float fMax_DotPorduct = Common.GetProjectLenghtOnto(r_verticex[0], v_axis);
for (int i = 0; i < r_verticex.Length; i++)
{
float fTmp = Common.GetProjectLenghtOnto(r_verticex[i], v_axis);
if (fTmp < fMin_DotPorduct)
fMin_DotPorduct = fTmp;
if (fTmp > fMax_DotPorduct)
fMax_DotPorduct = fTmp;
}
return new udsMinMaxData(v_name, fMin_DotPorduct, fMax_DotPorduct);
}
void OnDrawGizmosSelected()
{
}
}
|
using System.Runtime.Serialization;
namespace XH.APIs.WebAPI.Models.Projects
{
[DataContract]
public class SearchProjectMapsRequest
{
[DataMember]
public string Keywords { get; set; }
[DataMember]
public string ProvinceId { get; set; }
[DataMember]
public string CityId { get; set; }
[DataMember]
public string AreaId { get; set; }
[DataMember]
public string HazardLevelId { get; set; }
[DataMember]
public string ManagementCategoryId { get; set; }
}
} |
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.IO;
using UnityEngine;
public class QuestsData
{
public List<Quest> QuestList; //Лист со всеми квестами
public int currentQuestID; //id квеста, выбранного активным в данный момент
public QuestsData()
{
//Создание Квестов
QuestList = new List<Quest>();
CreateQuestsList2();
}
void CreateQuestsList()
{
//заполняем список квестов из файла
System.IO.StreamReader file = new System.IO.StreamReader("QuestsData.txt", System.Text.Encoding.GetEncoding(1251));
string line;
while ((line = file.ReadLine()) != null)
{
Quest newQuest = new Quest();
int.TryParse(line, out newQuest.id);//записываем id
line = file.ReadLine();
int st = 0;
int.TryParse(line, out st);
newQuest.status = (Quest.Status)st;//статус
line = file.ReadLine();
newQuest.name = line;//имя
line = file.ReadLine();
newQuest.title = line;//заголовок
line = file.ReadLine();
newQuest.description = line;//описание
line = file.ReadLine();
newQuest.toDo = line;//и что делать
QuestList.Add(newQuest);
}
file.Close();
}
void CreateQuestsList2()
{
//Считывание из xml
//Примеры из интернета:
//https://igroman14.livejournal.com/116218.html
//https://www.studica.com/blog/read-xml-file-in-unity
//http://unitynoobs.blogspot.com/2011/02/xml-loading-data-from-xml-file.html
//Загружаем из ресурсов наш xml файл
TextAsset xmlAsset = Resources.Load("QuestData") as TextAsset;
XmlDocument document = new XmlDocument();
if (xmlAsset) document.LoadXml(xmlAsset.text);
XmlNodeList dataList = document.GetElementsByTagName("quest");
foreach (XmlNode item in dataList)
{
XmlNodeList itemContent = item.ChildNodes;
Quest newQuest = new Quest();
foreach (XmlNode itemItens in itemContent)
{
if (itemItens.Name == "id") newQuest.id = int.Parse(itemItens.InnerText); // TODO to int
else if (itemItens.Name == "status") newQuest.status = (Quest.Status)int.Parse(itemItens.InnerText);
else if (itemItens.Name == "name") newQuest.name = itemItens.InnerText;
else if (itemItens.Name == "title") newQuest.title = itemItens.InnerText;
else if (itemItens.Name == "description") newQuest.description = itemItens.InnerText;
else if (itemItens.Name == "toDo") newQuest.toDo = itemItens.InnerText;
}
QuestList.Add(newQuest);
}
}
//получить объект Quest по его id
public Quest GetQuestData (int id)
{
for (int i = 0; i < QuestList.Count; i++)
{
if (QuestList[i].id == id)
return QuestList[i];
}
return null;
}
public void TakeTheQuest (int id)
{
GetQuestData(id).status = Quest.Status.ACTIVE;
currentQuestID = id;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using KartObjects;
namespace AxisPosCore
{
public interface IMenuView : IView
{
/// <summary>
/// Выход из кассового модуля
/// </summary>
event EventHandler OnExit;
/// <summary>
/// Вход в режим регистрации
/// </summary>
event EventHandler OnRegistrationMode;
/// <summary>
/// Выход из сеанса
/// </summary>
event EventHandler OnLogOff;
/// <summary>
/// Снятие X-отчета
/// </summary>
event EventHandler OnXReport;
/// <summary>
/// Снятие Z-отчета
/// </summary>
event EventHandler OnZReport;
/// <summary>
/// Снятие копии Z-отчета
/// </summary>
event EventHandler OnZReportCopy;
/// <summary>
/// Снятие сменного отчета ФР
/// </summary>
event EventHandler OnFRReport;
/// <summary>
/// Перезапуск
/// </summary>
event EventHandler OnRestart;
/// <summary>
/// Выключение терминала
/// </summary>
event EventHandler OnShutdown;
/// <summary>
/// Внесение наличных
/// </summary>
event EventHandler OnInCash;
/// <summary>
/// Инкассация
/// </summary>
event EventHandler OnOutCash;
event EventHandler OnUpdateData;
string UnsendReceiptsFound
{
get;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace FootballТeamGenerator
{
class Team
{
private string name;
private List<Player> players = new List<Player>();
public Team(string name)
{
this.Name = name;
}
public string Name
{
get => this.name;
private set
{
if (ValidateName(value))
{
this.name = value;
}
}
}
public double GetOverall()
{
double allPlayersOverall = 0;
if (this.players.Count > 0)
{
foreach (var player in this.players)
{
allPlayersOverall += player.Overall;
}
return Math.Round(allPlayersOverall / this.players.Count);
}
else
{
return 0;
}
}
public void RemovePlayer(string player)
{
if (this.players.Exists(x => x.Name == player))
{
this.players.Remove(players.Find(x => x.Name == player));
}
else
{
Console.WriteLine($"Player {player} is not in {this.name} team.");
}
}
public void AddPlayer(Player player)
{
if (this.players.Contains(player))
{
Console.WriteLine($"Player {player.Name} is already in {this.name} team.");
}
else
{
this.players.Add(player);
}
}
private bool ValidateName(string name)
{
if (String.IsNullOrEmpty(name) || String.IsNullOrWhiteSpace(name))
{
throw new ArgumentException($"A name should not be empty.");
}
return true;
}
}
}
|
using FeriaVirtual.App.Desktop.SeedWork.Helpers.Profiles;
using FeriaVirtual.App.Desktop.Services.SignIn;
namespace FeriaVirtual.App.Desktop.SeedWork.Helpers.Utils
{
public static class SessionData
{
public static string FullName { get; set; }
public static string Dni { get; set; }
public static string Email { get; set; }
public static IProfileInfo Profile { get; set; }
public static void AssignUserData(SignInViewModel data)
{
FullName = data.FullName;
Dni = data.Dni;
Email = data.Email;
Profile = ProfileInfo.CreateProfile((ProfileType)data.ProfileId).GetProfile;
}
}
}
|
namespace PatternsCore.Adapter
{
/// <summary>
/// Adapter always implements the interface of the type we are adapting to
/// Adapter Accepts the object that we are adapting
/// Adapter transforms the adapting objects methods to the methods of the objects we are adapting to
/// </summary>
public class TurkeyAdapter : IDuck
{
private readonly ITurkey _someTurkey;
public TurkeyAdapter(ITurkey someTurkey)
{
_someTurkey = someTurkey;
}
public void Quack()
{
if (_someTurkey!=null)
_someTurkey.Gobble();
}
public void Fly()
{
if (_someTurkey != null)
for (int i = 0; i < 5; i++)
_someTurkey.Fly();
}
}
} |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class SpeechController : MonoBehaviour
{
public List<Sprite> backgroundImages = new List<Sprite> ();
List<string> promps = new List<string> {
"prompt 1",
"I’ve gathered you today, here in the very heart of our town to speak frankly in these trying times…",
"This yearly address, a respected tradition and ritual among our people, we must confront the hard realities of the times. Our country can and will flourish once more! It is high time we…",
"For too long have we been subjected to the...",
"And with this in mind, it is time to rise up and claim our place in this world, foreign threats loom and we can no longer sit idle!",
"Our economy has been in tumult this year, yet...",
"Taxes must be immediately adressed as well!",
"prompt 8",
"prompt 9",
"prompt 10"
};
List<string> positiveResponses = new List<string> {
"positiveResponse 1",
"I must congratulate each and every one of you on your dedication to our great country...",
"Gave power back to the people, for it is indeed all of us who",
"Tyranny of the Wealthy elite",
"our flag will rise victorious over all who oppose our glory! No other shall be above Moskistan...",
"due to the great effort of our workers the yearly quotas were surpassed so the ration of chocolate shall be doubled!...",
"As a token of appreciation, and a gesture of my infinite magnanimity, taxes shall be reigned in…",
"positiveResponse 8",
"positiveResponse 9",
"positiveResponse 10"
};
List<string> neutralResponses = new List<string> {
"neutralResponse 1",
"Our contry has sufferend in these recent times, but we persevere...",
"Work harder to restore the glory of our past!",
"Whims of our changing fortunes",
"we have always been at war with Espayesia, in support of our Naguastan allys, we shall proudly continue this effort...",
" your fellow citizens have met the required production goals, and this pleases me…",
"Taxes shall remain at their current levels throughout this year…",
"neutralResponse 8",
"neutralResponse 9",
"neutralResponse 10"
};
List<string> negativeResponses = new List<string> {
"negativeResponse 1",
"I can no longer hide my disgust. Our once proud kingdom has fallen into disarray. You have no one to blame but yourselves...",
"Finally allow our corporations to thrive by ridding ourselves of pointless environmental protectionism.",
"Tyranny of you, the unwashed Masses",
"Surely many of you will die in the coming conflicts, but that is a risk I am willing to take..",
"You lazy and entitled slobs have fallen short of my demands, and as such the gin ration shall be cut…",
"An increase in taxes is inevitable, Your meager contributions will be put to a much better use in our war efforts, and to fund my new mansion...",
"negativeResponse 8",
"negativeResponse 9",
"negativeResponse 10"
};
int speechRound = 0;
public Image backgroundImage;
public Sprite catAssassinBackground;
public Sprite mobBackground;
string positiveText;
string negativeText;
string nutralText;
int bgImageIterator = 1;
public Text promptText;
public Button buttonA;
public Text buttonAText;
public Button buttonB;
public Text buttonBText;
public Button buttonC;
public Text buttonCText;
float publicOpinion = 0f;
void Start ()
{
promptText.text = "";
buttonAText.text = "Hardworking people of this country, you are the ones who make me proud to be a fellow citizen….";
buttonBText.text = "People of Mostkiastan…";
buttonCText.text = "Slaves, Rabble, indebted servants, and assorted filth…";
}
void Update ()
{
if (Input.GetKeyDown (KeyCode.A)) {
SceneManager.LoadScene (SceneManager.GetActiveScene ().name);
}
}
// cycle through the diffrent background images
void AdvanceBackgroundImage ()
{
backgroundImage.sprite = backgroundImages [bgImageIterator];
if (bgImageIterator < backgroundImages.Count - 1) {
bgImageIterator++;
} else {
bgImageIterator = 0;
}
}
//fill the the next rounds text options
void SetUpNextRound ()
{
speechRound++;
if (speechRound >= 7) {
CatAssassinEnding ();
return;
}
if (publicOpinion < -5f) {
MobEnding ();
return;
}
promptText.text = promps [speechRound];
buttonCText.text = negativeResponses [speechRound];
buttonBText.text = neutralResponses [speechRound];
buttonAText.text = positiveResponses [speechRound];
}
void changePublicOpinion (float poChange)
{
publicOpinion += poChange;
// if (publicOpinion > 0) {
// promptText.text = "people Love your this much: " + publicOpinion;
// } else {
// promptText.text = "people Hate your this much: " + publicOpinion;
// }
// if (publicOpinion > 5f) {
// CatAssassinEnding ();
// }
// if (publicOpinion < -5) {
// MobEnding ();
// }
}
// positive option
public void SpeechBoxAPress ()
{
Debug.Log ("Button A has been Pressed");
AdvanceBackgroundImage ();
changePublicOpinion (1f);
SetUpNextRound ();
}
//neutral option
public void SpeechBoxBPress ()
{
Debug.Log ("Button B has been Pressed");
AdvanceBackgroundImage ();
changePublicOpinion (-0f);
SetUpNextRound ();
}
//negative option
public void SpeechBoxCPress ()
{
Debug.Log ("Button C has been Pressed");
AdvanceBackgroundImage ();
changePublicOpinion (-1f);
SetUpNextRound ();
}
void CatAssassinEnding ()
{
backgroundImage.sprite = catAssassinBackground;
buttonA.gameObject.SetActive (false);
buttonB.gameObject.SetActive (false);
buttonC.gameObject.SetActive (false);
promptText.text = "You are too popular. The oligarchy have removed you from the stage.";
Invoke ("CatSceneSwitch", 5.0f);
}
void MobEnding ()
{
backgroundImage.sprite = mobBackground;
buttonA.gameObject.SetActive (false);
buttonB.gameObject.SetActive (false);
buttonC.gameObject.SetActive (false);
promptText.text = "You are torn to peices by the furious mod";
Invoke ("MobSceneSwitch", 5.0f);
}
void CatSceneSwitch()
{
GameManager.instance.SwitchScene ("Assassin");
}
void MobSceneSwitch()
{
GameManager.instance.SwitchScene ("Mob");
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BadBullet_Slow : Bullet
{
public new string type = "bad_bullet_slow";
private void Update()
{
CheckDuration();
}
Coroutine cur;
public override void AffectObject(GameObject target) // AffectingObject의 함수를 오버라이딩 // 대상에 영향을 주는 코드
{
base.AffectObject(target);
target.GetComponent<CharacterState>().AffectSlow(20,3); // 슬로우 효과
target.GetComponent<PlayerControl>().hp -= dmg; // 데미지 주고
target.GetComponent<PlayerControl>().CheckHp(); // 상태확인함
//if(target.tag == "player")
cur = StartCoroutine("SlowPlayer");
target.GetComponent<CharacterState>().isSlowed = true;
}
IEnumerator SlowPlayer() { yield return 0; }
void CheckDuration()
{
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp9
{
public interface IHandler
{
IHandler SetNext(IHandler handler);
object Handle(object request);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;
namespace DataAccess
{
public class EmailSender
{
private readonly string fromEmail = "swpacckhoi@gmail.com";
private readonly string fromPassword = "Swpacc1!";
//port server cua gmail
private readonly int port = 587;
public bool sendEmail(string subject, string body, params string[] receipients)
{
try
{
using (MailMessage mail = new MailMessage())
{
mail.From = new MailAddress(fromEmail);
foreach (string receipient in receipients)
{
mail.To.Add(receipient);
}
mail.Subject = subject;
mail.Body = body;
using (SmtpClient smtp = new SmtpClient("smtp.gmail.com", port))
{
smtp.Credentials = new System.Net.NetworkCredential(fromEmail, fromPassword);
smtp.EnableSsl = true;
smtp.Send(mail);
}
};
return true;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter Mail");
string mail = Console.ReadLine();
Console.WriteLine("Enter subject:");
string subject = Console.ReadLine();
Console.WriteLine("Enter body");
string body = Console.ReadLine();
EmailSender emailSender = new EmailSender();
emailSender.sendEmail(subject, body, mail);
Console.WriteLine("Sent");
}
}
}
|
using System;
using System.Collections.Generic;
namespace dc_demo_api.Models
{
public partial class VariantType
{
public VariantType()
{
AssetVariants = new HashSet<AssetVariant>();
}
public int VariantTypeId { get; set; }
public string Name { get; set; }
public virtual ICollection<AssetVariant> AssetVariants { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using Inventor;
using Autodesk.DesignScript.Geometry;
using Autodesk.DesignScript.Interfaces;
using Autodesk.DesignScript.Runtime;
using Dynamo.Models;
using Dynamo.Utilities;
using InventorLibrary.GeometryConversion;
using InventorServices.Persistence;
using Point = Autodesk.DesignScript.Geometry.Point;
using SimpleInjector;
namespace InventorLibrary.API
{
[IsVisibleInDynamoLibrary(false)]
public class InvWorkPoint
{
#region Private fields
private IObjectBinder _binder;
#endregion
#region Internal properties
internal Inventor.WorkPoint InternalWorkPoint { get; set; }
internal Object InternalApplication
{
get { return WorkPointInstance.Application; }
}
internal InvAttributeSets InternalAttributeSets
{
get { return InvAttributeSets.ByInvAttributeSets(WorkPointInstance.AttributeSets); }
}
internal bool InternalConstruction
{
get { return WorkPointInstance.Construction; }
}
internal bool InternalConsumed
{
get { return WorkPointInstance.Consumed; }
}
//this is temporary, will only work in assemblies
internal InvAssemblyWorkPointDef InternalDefinition
{
get { return InvAssemblyWorkPointDef.ByInvAssemblyWorkPointDef((Inventor.AssemblyWorkPointDef)WorkPointInstance.Definition); }
}
//internal InvWorkPointDefinitionEnum InternalDefinitionType
//{
// get { return WorkPointInstance.DefinitionType.As<InvWorkPointDefinitionEnum>(); }
//}
//internal InvObjectCollection InternalDependents
//{
// get { return InvObjectCollection.ByInvObjectCollection(WorkPointInstance.Dependents); }
//}
//internal InvObjectCollection InternalDrivenBy
//{
// get { return InvObjectCollection.ByInvObjectCollection(WorkPointInstance.DrivenBy); }
//}
internal bool InternalHasReferenceComponent
{
get { return WorkPointInstance.HasReferenceComponent; }
}
//internal InvHealthStatusEnum InternalHealthStatus
//{
// get { return WorkPointInstance.HealthStatus.As<InvHealthStatusEnum>(); }
//}
internal bool InternalIsCoordinateSystemElement
{
get { return WorkPointInstance.IsCoordinateSystemElement; }
}
internal bool InternalIsOwnedByFeature
{
get { return WorkPointInstance.IsOwnedByFeature; }
}
internal bool InternalIsParentSketch
{
get { return WorkPointInstance.IsParentSketch; }
}
internal bool InternalIsPatternElement
{
get { return WorkPointInstance.IsPatternElement; }
}
//internal InvPartFeature InternalOwnedBy
//{
// get { return InvPartFeature.ByInvPartFeature(WorkPointInstance.OwnedBy); }
//}
internal InvComponentDefinition InternalParent
{
get { return InvComponentDefinition.ByInvComponentDefinition(WorkPointInstance.Parent); }
}
//internal InvSketch3D InternalParentSketch
//{
// get { return InvSketch3D.ByInvSketch3D(WorkPointInstance.ParentSketch); }
//}
internal InvPoint InternalPoint
{
get { return InvPoint.ByInvPoint(WorkPointInstance.Point); }
}
//internal InvReferenceComponent InternalReferenceComponent
//{
// get { return InvReferenceComponent.ByInvReferenceComponent(WorkPointInstance.ReferenceComponent); }
//}
internal InvWorkPoint InternalReferencedEntity
{
get { return InvWorkPoint.ByInvWorkPoint(WorkPointInstance.ReferencedEntity); }
}
internal InvObjectTypeEnum InternalType
{
get { return WorkPointInstance.Type.As<InvObjectTypeEnum>(); }
}
internal bool InternalAdaptive { get; set; }
internal bool InternalConsumeInputs { get; set; }
internal bool InternalExported { get; set; }
internal bool InternalGrounded { get; set; }
internal string InternalName { get; set; }
internal bool InternalShared { get; set; }
internal bool InternalVisible { get; set; }
#endregion
#region Private constructors
private InvWorkPoint(InvWorkPoint invWorkPoint)
{
InternalWorkPoint = invWorkPoint.InternalWorkPoint;
}
private InvWorkPoint(Inventor.WorkPoint invWorkPoint)
{
InternalWorkPoint = invWorkPoint;
}
private InvWorkPoint(Point point, IObjectBinder binder)
{
_binder = binder;
Inventor.WorkPoint wp;
if (_binder.GetObjectFromTrace<Inventor.WorkPoint>(out wp))
{
InternalWorkPoint = wp;
AssemblyWorkPointDef wpDef = (AssemblyWorkPointDef)wp.Definition;
wpDef.Point = point.ToPoint();
}
else
{
wp = PersistenceManager.ActiveAssemblyDoc.ComponentDefinition.WorkPoints.AddFixed(point.ToPoint(), false);
InternalWorkPoint = wp;
_binder.SetObjectForTrace<WorkPoint>(this.InternalWorkPoint);
}
}
#endregion
#region Private methods
private void InternalSetWorkPoint(Inventor.WorkPoint wp)
{
InternalWorkPoint = wp;
//this.InternalElementId = InternalReferencePoint.Id;
byte[] refKey = new byte[] { };
if (ReferenceManager.KeyManager == null)
{
ReferenceManager.KeyManager = PersistenceManager.ActiveAssemblyDoc.ReferenceKeyManager;
}
ReferenceManager.KeyContext = PersistenceManager.ActiveAssemblyDoc.ReferenceKeyManager.CreateKeyContext();
wp.GetReferenceKey(ref refKey, (int)ReferenceManager.KeyContext);
//this.InternalRefKey = refKey;
}
private void InternalDelete(bool retainDependents)
{
WorkPointInstance.Delete( retainDependents);
}
private void InternalGetReferenceKey(ref byte[] referenceKey, int keyContext)
{
WorkPointInstance.GetReferenceKey(ref referenceKey, keyContext);
}
private void InternalSetAtCentroid(Object entities)
{
WorkPointInstance.SetAtCentroid( entities);
}
private void InternalSetByCurveAndEntity(Object curve, Object entity, Object proximityPoint)
{
WorkPointInstance.SetByCurveAndEntity( curve, entity, proximityPoint);
}
//private void InternalSetByMidPoint(Edge edge)
//{
// WorkPointInstance.SetByMidPoint( edge);
//}
private void InternalSetByPoint(Object point)
{
WorkPointInstance.SetByPoint( point);
}
//private void InternalSetBySphereCenterPoint(Face face)
//{
// WorkPointInstance.SetBySphereCenterPoint( face);
//}
private void InternalSetByThreePlanes(Object plane1, Object plane2, Object plane3)
{
WorkPointInstance.SetByThreePlanes( plane1, plane2, plane3);
}
//private void InternalSetByTorusCenterPoint(Face face)
//{
// WorkPointInstance.SetByTorusCenterPoint( face);
//}
private void InternalSetByTwoLines(Object line1, Object line2)
{
WorkPointInstance.SetByTwoLines( line1, line2);
}
private void InternalSetEndOfPart(bool before)
{
WorkPointInstance.SetEndOfPart( before);
}
private void InternalSetFixed(Point point)
{
WorkPointInstance.SetFixed( point.ToPoint());
}
#endregion
#region Public properties
public Inventor.WorkPoint WorkPointInstance
{
get { return InternalWorkPoint; }
set { InternalWorkPoint = value; }
}
public Object Application
{
get { return InternalApplication; }
}
public InvAttributeSets AttributeSets
{
get { return InternalAttributeSets; }
}
public bool Construction
{
get { return InternalConstruction; }
}
public bool Consumed
{
get { return InternalConsumed; }
}
public InvAssemblyWorkPointDef Definition
{
get { return InternalDefinition; }
}
//public InvWorkPointDefinitionEnum DefinitionType
//{
// get { return InternalDefinitionType; }
//}
//public InvObjectCollection Dependents
//{
// get { return InternalDependents; }
//}
//public InvObjectCollection DrivenBy
//{
// get { return InternalDrivenBy; }
//}
public bool HasReferenceComponent
{
get { return InternalHasReferenceComponent; }
}
//public InvHealthStatusEnum HealthStatus
//{
// get { return InternalHealthStatus; }
//}
public bool IsCoordinateSystemElement
{
get { return InternalIsCoordinateSystemElement; }
}
public bool IsOwnedByFeature
{
get { return InternalIsOwnedByFeature; }
}
public bool IsParentSketch
{
get { return InternalIsParentSketch; }
}
public bool IsPatternElement
{
get { return InternalIsPatternElement; }
}
//public InvPartFeature OwnedBy
//{
// get { return InternalOwnedBy; }
//}
public InvComponentDefinition Parent
{
get { return InternalParent; }
}
//public InvSketch3D ParentSketch
//{
// get { return InternalParentSketch; }
//}
public InvPoint Point
{
get { return InternalPoint; }
}
//public InvReferenceComponent ReferenceComponent
//{
// get { return InternalReferenceComponent; }
//}
public InvWorkPoint ReferencedEntity
{
get { return InternalReferencedEntity; }
}
public InvObjectTypeEnum Type
{
get { return InternalType; }
}
public bool Adaptive
{
get { return InternalAdaptive; }
set { InternalAdaptive = value; }
}
public bool ConsumeInputs
{
get { return InternalConsumeInputs; }
set { InternalConsumeInputs = value; }
}
public bool Exported
{
get { return InternalExported; }
set { InternalExported = value; }
}
public bool Grounded
{
get { return InternalGrounded; }
set { InternalGrounded = value; }
}
public string Name
{
get { return InternalName; }
set { InternalName = value; }
}
public bool Shared
{
get { return InternalShared; }
set { InternalShared = value; }
}
public bool Visible
{
get { return InternalVisible; }
set { InternalVisible = value; }
}
#endregion
#region Public static constructors
public static InvWorkPoint ByInvWorkPoint(InvWorkPoint invWorkPoint)
{
return new InvWorkPoint(invWorkPoint);
}
public static InvWorkPoint ByInvWorkPoint(Inventor.WorkPoint invWorkPoint)
{
return new InvWorkPoint(invWorkPoint);
}
public static InvWorkPoint ByPoint(Point point)
{
var binder = PersistenceManager.IoC.GetInstance<IObjectBinder>();
return new InvWorkPoint(point, binder);
}
#endregion
#region Public methods
public void Delete(bool retainDependents)
{
InternalDelete( retainDependents);
}
public void GetReferenceKey(ref byte[] referenceKey, int keyContext)
{
InternalGetReferenceKey(ref referenceKey, keyContext);
}
public void SetAtCentroid(Object entities)
{
InternalSetAtCentroid( entities);
}
public void SetByCurveAndEntity(Object curve, Object entity, Object proximityPoint)
{
InternalSetByCurveAndEntity( curve, entity, proximityPoint);
}
//public void SetByMidPoint(Edge edge)
//{
// InternalSetByMidPoint( edge);
//}
//what is going on here is that this, and other methods accepting "Object" point or plane, etc
//is that these methods accept certain varieties of geometries. This is how the api constrains
//what can be done. I can't programattically place work points in a part file unless it is
//on some geometry like a sketch point or vertex. Of course, the workaround is to place
//a sketch line with one endpoint at the location you want, place the work point, then delete the
//sketch without deleting consuming work features.
public void SetByPoint(Object point)
{
InternalSetByPoint( point);
}
//public void SetBySphereCenterPoint(Face face)
//{
// InternalSetBySphereCenterPoint( face);
//}
public void SetByThreePlanes(Object plane1, Object plane2, Object plane3)
{
InternalSetByThreePlanes( plane1, plane2, plane3);
}
//public void SetByTorusCenterPoint(Face face)
//{
// InternalSetByTorusCenterPoint( face);
//}
public void SetByTwoLines(Object line1, Object line2)
{
InternalSetByTwoLines( line1, line2);
}
public void SetEndOfPart(bool before)
{
InternalSetEndOfPart( before);
}
public void SetFixed(Point point)
{
InternalSetFixed( point);
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using LightingBook.Test.Api.Common.Extensions;
using LightingBook.Test.Api.Common.Dto;
using LightingBook.Tests.Api.Dto.Dto.SearchTravel;
using LightingBook.Tests.Api.Helper;
using LightingBook.Tests.Api.SpecDto;
using NUnit.Framework;
using TechTalk.SpecFlow;
using TechTalk.SpecFlow.Assist;
using LightingBook.Tests.Api.Dto.GetItinerary;
using LightingBook.Tests.Api.Product.V10;
using TravelAvailabilityResponse = LightingBook.Test.Api.Client.v10.Models.TravelCTMOBTApiModelsv5TravelTravelAvailabilityResponse;
using FlightSeatMap = LightingBook.Test.Api.Client.v10.Models.TravelCTMOBTApiModelsv3SeatMapFlightSeatMap;
using TravelCTMOBTApiModelsv9Itinerary = LightingBook.Test.Api.Client.v9.Models.TravelCTMOBTApiModelsv9Itinerary;
using LightingBook.Tests.Api.Product.v10;
using System.Threading.Tasks;
using GlobalSettings = LightingBook.Test.Api.Client.v10.Models.TravelCTMOBTApiModelsv10SettingsGlobalSettings;
using LightingBook.Test.Api.Common;
namespace LightingBook.Tests.Api.Steps.v10
{
[Binding]
public class FlightSearch_v10
{
private readonly ScenarioContext _scenarioContext;
private Dictionary<string, string> _appConfigDetails;
public FlightSearch_v10(ScenarioContext scenarioContext)
{
if (scenarioContext == null)
throw new ArgumentNullException("scenarioContext");
this._scenarioContext = scenarioContext;
this._appConfigDetails = ConfigurationBase.AppConfigDetails;
}
[When(@"I enter the search results for flight from between (.*) and (.*) and as mentioned below:")]
public void WhenIEnterTheSearchResultsForFlightForAndAndAsMentionedBelow(int weeksFromTodaysDate, int weeksToTodaysDate, Table table)
{
var tokenResponse = _scenarioContext.Get<TokenResponse>("TokenDetails");
var globalSettings = _scenarioContext.Get<GlobalSettings>("GlobalSettings");
var parameter = table.CreateInstance<CarInputs>();
var dateFrom = DateTime.Now.AddWeeks(weeksFromTodaysDate);
var dateTo = DateTime.Now.AddWeeks(weeksToTodaysDate);
// get itinerary
var tripIdentifier = new Itinerary(tokenResponse, ConfigurationBase.AppConfigDetails)
.GetItineraryFlight(globalSettings, parameter.PickUpCity, parameter.DropOffCity, dateFrom.ToString(), dateTo.ToString());
_scenarioContext.Set(tripIdentifier, "TripIdentifierFlights");
}
[When(@"I enter a flight call from between (.*) and (.*) with the details mentioned below:")]
public void WhenIMakeAFlightCallWithTheDetailsBelow(int weeksFromTodaysDate, int weeksToTodaysDate, Table table)
{
var loginCredentials = _scenarioContext.Get<TokenResponse>("TokenDetails");
var tripIdentifiers = _scenarioContext.Get<TripIdentifiers>("TripIdentifierFlights");
var globalSettings = _scenarioContext.Get<GlobalSettings>("GlobalSettings");
var parameter = table.CreateInstance<CarInputs>();
var dateFrom = DateTime.Now.AddWeeks(weeksFromTodaysDate);
var dateTo = DateTime.Now.AddWeeks(weeksToTodaysDate);
// search flights
var flights =
new TravelSearch(loginCredentials, ConfigurationBase.AppConfigDetails)
.SearchFlights(tripIdentifiers, parameter.PickUpCity, parameter.DropOffCity, dateFrom.ToString(), globalSettings);
_scenarioContext.Set(flights, "SearchFlightsDetails");
}
[Then(@"The flight resuls should match below:")]
public void ThenTheFlightResulsShouldMatchBelow(Table table)
{
var flightsDetails = _scenarioContext.Get<List<TravelAvailabilityResponse>>("SearchFlightsDetails");
var temp = table.CreateSet<Result>();
foreach (var item in temp)
{
if (string.IsNullOrEmpty(item.GdsProviders))
{
continue;
}
var gdsProviders = item.GdsProviders.Split(',').ToList();
if (item.ExpectedResult.Equals(true))
{
foreach (var flightResult in flightsDetails)
{
if (flightResult.Results != null)
{
foreach (var gdsProvider in gdsProviders)
{
var flightResultsByGdsProvider = flightResult.Results.Where(filter => filter.GdsProvider == gdsProvider);
Assert.IsNotNull(flightResultsByGdsProvider);
}
}
else
{
Console.WriteLine("The results did not return a perffered Carrier");
}
}
}
}
}
[Then(@"I should get back all the avalible seats in the seatmap:")]
public void ThenIShouldGetBackAllTheAvalibleSeatsInTheSeatmap(Table table)
{
var flightsDetails = _scenarioContext.Get<List<TravelAvailabilityResponse>>("SearchFlightsDetails");
var LoginCredentials = _scenarioContext.Get<TokenResponse>("TokenDetails");
var parameters = table.CreateInstance<FlightInputs>();
// get seat maps
var seapMapResults =
new SeatMap(LoginCredentials, _appConfigDetails)
.SearchSeatMaps(flightsDetails, parameters.GdsProvider);
_scenarioContext.Set(seapMapResults, "SeatMapResults");
}
[Then(@"select a (.*) seat is avaliable")]
public void ThenSelectASeatIsAvaliable(string FunctionType)
{
var seatMapResults = _scenarioContext.Get<List<FlightSeatMap>>("SeatMapResults");
var functionTypes =
seatMapResults?.SelectMany(x => x.Transport)?.SelectMany(x => x.Decks)?.SelectMany(x => x.Cabins)?.SelectMany(x => x.Rows)?.SelectMany(x => x.Items)?.Where(x => x.RowLocation == FunctionType);
Assert.IsNotNull(functionTypes);
}
[When(@"I search for a flight in (.*) weeks with the following details as a one way trip")]
public void WhenISearchForAFlightInWeeksWithTheFollowingDetailsAsAOneWayTrip(int numberOfWeeks, Table table)
{
//Parameters
var date = DateTime.Now.AddWeeks(numberOfWeeks);
var details = table.CreateInstance<FlightInputs>();
var tokenResponse = _scenarioContext.Get<TokenResponse>("TokenDetails");
var globalSettings = _scenarioContext.Get<GlobalSettings>("GlobalSettings");
//Create Itinerary search
var passengers = new List<Passenger>
{
new Passenger
{
ClientId = globalSettings?.Travellers?.Count > 0 ? globalSettings?.Travellers[0].ClientId : null,
Firstname = "",
Lastname = "",
Identifier = "00000000-0000-0000-0000-000000000000",
PassengerIdentifier = "",
Title = "Traveller User"
}
};
var searchFlights = new List<SearchFlight>
{
new SearchFlight
{
Origin = new SearchFlightLocation
{
Code = details.OriginLocationCode
},
Destination = new SearchFlightLocation
{
Code = details.DestinationLocationCode
},
Date = new DateTimeOffset(date)
}
};
var itineraryContext = new Product.v9.Itinerary(tokenResponse, _appConfigDetails);
var response = itineraryContext.CreateItinerarySearch(passengers, searchFlights, null, null);
_scenarioContext.Set(response, "Itinerary");
var tripIdentifiers = new TripIdentifiers
{
PassengerIdentifier = response?.Passengers?.FirstOrDefault()?.Identifier,
PassengerItinIdentifier = response?.Passengers?.FirstOrDefault()?.ItineraryIdentifier,
PassengerSearchIdentifier = response?.Search?.Flights?.FirstOrDefault()?.Passengers?.FirstOrDefault()?.Identifier,
SearchFlightIdentifer = response?.Search?.Flights?.FirstOrDefault()?.Identifier
};
//Search flights
var travelSearch = new TravelSearch(tokenResponse, _appConfigDetails);
var flights = travelSearch.SearchFlights(tripIdentifiers, details.OriginLocationCode, details.DestinationLocationCode, date.ToString(), globalSettings);
_scenarioContext.Set(flights, "SearchFlightsDetails");
Assert.IsNotNull(response?.Identifier);
}
[Then(@"The flght results I get back should not contain the following carrier (.*)")]
public void ThenTheFlghtResultsIGetBackShouldNotContainTheFollowingCarrier(string excludedCarrier)
{
var itinerary = _scenarioContext.Get<TravelCTMOBTApiModelsv9Itinerary>("Itinerary");
var flightsDetails = _scenarioContext.Get<List<TravelAvailabilityResponse>>("SearchFlightsDetails");
Assert.IsTrue(flightsDetails.FirstOrDefault()?.Results?.Any(x => x.Carrier != excludedCarrier));
}
//---------- PreferredCarrier Steps
[Then(@"when carrier is (.*) then Preferred is set to true")]
public void ThenWhenCarrierIsThenPreferredIsSetToTrue(string PreferredCarrier)
{
var flightsDetails = _scenarioContext.Get<List<TravelAvailabilityResponse>>("SearchFlightsDetails");
var preferredCarrier = flightsDetails?.SelectMany(x => x.Results)?
.Where(x => (x.Preferred == true && x.Carrier == PreferredCarrier));
Assert.IsTrue(preferredCarrier?.Count() > 0);
}
[Then(@"When carrier is not (.*) then Preferred is set to false")]
public void ThenWhenCarrierIsNotThenPreferredIsSetToFalse(string PreferredCarrier)
{
var flightsDetails = _scenarioContext.Get<List<TravelAvailabilityResponse>>("SearchFlightsDetails");
var preferredCarrier = flightsDetails?.SelectMany(x => x.Results)?
.Where(x => (x.Preferred == false && x.Carrier != PreferredCarrier));
Assert.IsTrue(preferredCarrier?.Count() >= 0);
}
}
}
|
using UnityEngine;
using System.Collections;
public class FadeOutAudio : MonoBehaviour {
AudioSource[] soundTracks;
// Use this for initialization
void Start () {
soundTracks = GameObject.Find("GameState").GetComponents<AudioSource>();
StartCoroutine (FadeSoundtrack ());
}
public IEnumerator FadeSoundtrack()
{
while (soundTracks[1].volume > 0.1f)
{
soundTracks[1].volume = Mathf.Lerp(soundTracks[1].volume, 0, Time.fixedDeltaTime * 2f);
yield return new WaitForEndOfFrame ();
}
soundTracks[1].volume = 0f;
soundTracks[1].Stop();
}
}
|
using ApiSGCOlimpiada.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Coravel.Mailer.Mail;
namespace ApiSGCOlimpiada.Services
{
public class DownloadEmail : Mailable<EmailModel>
{
private EmailModel data;
public DownloadEmail(EmailModel data) => this.data = data;
public override void Build()
{
List<string> address = new List<string>();
foreach (var item in data.Responsaveis)
{
address.Add(item.Email);
}
this.To("mauricio.lacerdaml@gmail.com")
.From(new MailRecipient("olimpiada@gmail.com", "Envio da solicitação de compra"))
.Subject($"Realizando teste de envio de email")
.View("~/Views/templateEmail.cshtml", this.data);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyController : MonoBehaviour
{
private Rigidbody2D rbody;
public float speed = -10;
private void Awake()
{
rbody = this.GetComponent<Rigidbody2D>();
}
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
// rbody.velocity = transform.right * speed * Time.deltaTime; // Time.deltaTime giving issues
// rbody.velocity = new Vector2(speed, 0.0f); // can use this also
rbody.velocity = transform.right * speed;
}
}
|
using Fingo.Auth.Domain.Infrastructure.Interfaces;
using Fingo.Auth.Domain.Users.Interfaces;
namespace Fingo.Auth.Domain.Users.Factories.Interfaces
{
public interface IGetUserByLoginFactory : IActionFactory
{
IGetUserByLogin Create();
}
} |
namespace DChild.Gameplay.Player
{
public interface IPlayerSkillGetter
{
T GetSkill<T>() where T : IPlayerSkill;
}
} |
// Copyright (c) 2018 FiiiLab Technology Ltd
// Distributed under the MIT software license, see the accompanying
// file LICENSE or or http://www.opensource.org/licenses/mit-license.php.
using FiiiCoin.DTO;
using FiiiCoin.ServiceAgent;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Threading.Tasks;
namespace FiiiCoin.Wallet.Test.ServiceAgent
{
[TestClass]
public class AddressBookTest
{
[TestMethod]
public async Task AddNewAddressBookItem()
{
AddressBook book = new AddressBook();
await book.AddNewAddressBookItem("fiiitFmH9Cqk5B9gTH3LqZzBtqb8pxgHJ7sVqY", "testnet");
}
[TestMethod]
public async Task GetAddressBook()
{
AddressBook book = new AddressBook();
AddressBookInfoOM[] result = await book.GetAddressBook();
Assert.IsNotNull(result);
}
[TestMethod]
public async Task GetAddressBookItemByAddress()
{
AddressBook book = new AddressBook();
AddressBookInfoOM result = await book.GetAddressBookItemByAddress("fiiitFmH9Cqk5B9gTH3LqZzBtqb8pxgHJ7sVqY");
Assert.IsNotNull(result);
}
[TestMethod]
public async Task GetAddressBookByTag()
{
AddressBook book = new AddressBook();
AddressBookInfoOM[] result = await book.GetAddressBookByTag("John");
Assert.IsNotNull(result);
}
[TestMethod]
public async Task DeleteAddressBookByIds()
{
AddressBook book = new AddressBook();
await book.DeleteAddressBookByIds(new long[] { 5 });
}
}
}
|
using UnityEngine;
using System.Collections;
public class mission2 : MonoBehaviour {
public GameObject crystal_pref;
public GameObject viol_expl;
GameObject ship;
public int step=400;
fleetCommand our_fc;
public NetworkShipGUI nsg;
Rect r;
float carriers_distance;
public int maxDistance=2500;
bool fail=false;
string reasonwhy;
bool game_started=false;
int lastz=0;
public int zlimit=10000;
bool win=false;
Texture back_tx;
int m_count=0;
// Use this for initialization
void StartGame () {
ship=GameObject.Find("menu").GetComponent<SceneResLoader>().localShip;
lastz=(int)ship.transform.position.z+step;
nsg=ship.GetComponent<NetworkShipGUI>();
our_fc=GameObject.Find("fc1").GetComponent<fleetCommand>();
our_fc.ScanOnce();
foreach(GameObject s in our_fc.ships) {
if (s==null) continue;
s.SendMessage("FollowInCurrentFormation",ship,SendMessageOptions.DontRequireReceiver);
}
r= new Rect(Screen.width/2-2*nsg.k,0,4*nsg.k,nsg.k/2);
StartCoroutine(Awaiting());
back_tx=Resources.Load<Texture>("text_back");
}
IEnumerator Awaiting () {
yield return new WaitForSeconds(3);
game_started=true;
}
void SpawnEnemies () {
Vector3 pos=new Vector3(ship.transform.position.x,ship.transform.position.y,lastz+1000);
for (byte j=0;j<9;j++)
{ if (Random.value<=0.5f) continue;
switch (j) {
case 1: pos.y+=5*step;break;
case 2: pos+=new Vector3(-2.5f*step,2.5f*step,step/2);break;
case 3: pos.x-=5*step;break;
case 4: pos+=new Vector3(-2.5f*step,-2.5f*step,step/2);break;
case 5: pos.y-=5*step;break;
case 6: pos+=new Vector3(2.5f*step,-2.5f*step,step/2);break;
case 7: pos.x+=5*step;break;
case 8: pos+=new Vector3(2.5f*step,2.5f*step,step/2);break;
}
for (byte i=0;i<13;i++) {
if (Random.value<=0.5f) continue;
switch (i) {
case 1: pos.y+=2*step; break;
case 2: pos.y+=step;pos.x-=step;break;
case 3: pos.y+=step;break;
case 4: pos.y+=step;pos.x+=step;break;
case 5: pos.x-=2*step;break;
case 6: pos.x-=step;break;
case 7:pos.x+=step;break;
case 8: pos.x+=2*step;break;
case 9: pos.x-=step;pos.y-=step;break;
case 10: pos.y-=step;break;
case 11: pos.y-=step;pos.x+=step;break;
case 12: pos.y-=2*step;break;
}
GameObject c=Instantiate(crystal_pref,pos,Quaternion.Euler(0,180,0)) as GameObject;
c.transform.localScale*=(int)(Random.value*10);
BotControl_crystal bcc=c.GetComponent<BotControl_crystal>();
bcc.maxhp=(int)(2500*c.transform.localScale.x);
bcc.damage=(int)(50*c.transform.localScale.x);
bcc.range=250*c.transform.localScale.x;
bcc.crystal_pref=crystal_pref;
}}
}
void Update() {
if (!game_started) return;
if (!ship) {if (game_started&&!fail) {fail=true;reasonwhy="Вы погибли слишком рано!";}return;}
float d=ship.transform.position.z;d/=zlimit;
int count=0;
for (byte i=0;i<our_fc.ships.Length;i++) {
if (our_fc.ships[i]!=null) {
float d2=Vector3.Distance(ship.transform.position,our_fc.ships[i].transform.position);
if (d>maxDistance&&our_fc.ships[i].name[3]!='h') Destroy(our_fc.ships[i]);
if (our_fc.ships[i].name[5]=='m') {
count++;d+=d2;
}
if (our_fc.ships[i].transform.position.z>=zlimit) {
Instantiate(viol_expl,our_fc.ships[i].transform.position,Quaternion.identity);
our_fc.ships[i].BroadcastMessage("SetLayer",9,SendMessageOptions.DontRequireReceiver);
}
}
}
if (win||fail) return;
m_count=count;
if (count!=0) { carriers_distance=d/count;} else {fail=true;reasonwhy="Мы потеряли всех шахтеров!";return;}
if (ship.transform.position.z>lastz) {lastz+=step;SpawnEnemies();}
if (ship.transform.position.z>=zlimit) {
Instantiate(viol_expl,ship.transform.position,Quaternion.identity);
ship.BroadcastMessage("SetLayer",9,SendMessageOptions.DontRequireReceiver);
win=true;
r=new Rect(Screen.width/2-3*nsg.k,Screen.height/2-nsg.k,6*nsg.k,4*nsg.k);
nsg.enabled=false;
if (PlayerPrefs.HasKey("campaign_mission")) {
if (PlayerPrefs.GetInt("campaign_mission")<3) {PlayerPrefs.SetInt("campaign_mission",3);Global.campaign_mission=3;}}
}
}
void OnGUI () {
if (!fail) {
if (nsg&&nsg.enabled) {
GUI.skin=Global.mySkin;
int fs=GUI.skin.GetStyle("Label").fontSize;
GUI.skin.GetStyle("Label").fontSize=(int)(r.height/2);
float dole=ship.transform.position.z;dole/=zlimit;
if (dole>1) dole=1;
GUI.DrawTexture(new Rect(r.x,r.y,r.width*dole,r.height),nsg.h_green_line,ScaleMode.StretchToFill);
GUI.DrawTexture(r,nsg.h_bar_frame,ScaleMode.StretchToFill);
GUI.Label(r,"Завершено");
dole=carriers_distance/maxDistance;
if (dole>1) dole=1;
Texture t;
if (dole>0.8 ) t=nsg.h_red_line; else t=nsg.h_lblue_line;
GUI.DrawTexture(new Rect(r.x,r.y+nsg.k/2,r.width*dole,r.height),t,ScaleMode.StretchToFill);
GUI.DrawTexture(new Rect(r.x,r.y+nsg.k/2,r.width,r.height),nsg.h_bar_frame,ScaleMode.StretchToFill);
GUI.Label(new Rect(r.x,r.y+nsg.k/2,r.width,r.height),"Удаленность ("+m_count+")");
GUI.skin.GetStyle("Label").fontSize=fs;
}
if (win) {
GUI.skin=Global.stSkin;
GUI.DrawTexture(r,back_tx,ScaleMode.StretchToFill);
GUI.Label(r,"Миссия успешно завершена!");
if (GUI.Button(new Rect(r.x,r.y+nsg.k,3*nsg.k,nsg.k),"Продолжить")) {
nsg.st.nm.onlineScene="mission3";
nsg.st.nm.StopHost();
nsg.st.nm.StartHost();
Destroy(gameObject);}
if (GUI.Button(new Rect(r.x+3*nsg.k,r.y+nsg.k,3*nsg.k,nsg.k),"Выйти в меню")) {
nsg.st.nm.StopHost();
Destroy(gameObject);
}
}
}
else {
GUI.skin=Global.stSkin;
Rect r2=new Rect(Screen.width/2-128,Screen.height/2-32,256,64);
GUI.DrawTexture(r2,back_tx,ScaleMode.StretchToFill);
GUI.Label(r2,"Поражение! "+reasonwhy);r2.width/=2;
if (GUI.Button(new Rect(r2.x,r2.y+64,128,64),"Перезапуск")) GameObject.Find("server_terminal").GetComponent<ServerTerminal>().Restart();
r2.x+=128;
if (GUI.Button(new Rect(r2.x+64,r2.y+64,128,64),"Выход")) GameObject.Find("server_terminal").GetComponent<ServerTerminal>().Exit();
}
}
public void MissionFailed () {
fail=true;
reasonwhy="Вы сбежали с поля боя";
}
}
|
using UnityEngine;
using System.Collections;
public class DeathZoneOperator : MonoBehaviour
{
//This checks if the ball reaches underneath the screen, destroys it and decreases the players health.
public GameObject platform;
void Awake()
{
if (platform == null)
Debug.LogError("A platform needs to be assaigned in the inspector of 'DeathZoneOperator.cs'.");
}
void OnCollisionEnter2D(Collision2D col)
{
BallOperator ballOperator = col.transform.GetComponent<BallOperator>();
if (ballOperator)
{
platform.GetComponent<PlatformOperator>().SpawnBall();
GameOperator.lives--;
Destroy(col.gameObject);
}
}
}
|
using AnyTest.MobileClient.Model;
using AnyTest.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Lib = AnyTest.ResourceLibrary;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using Microsoft.AspNetCore.Components;
namespace AnyTest.MobileClient
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class TestPage : ContentPage
{
private TestViewModel test;
public TestPass Pass { get; set; }
public TestViewModel Test
{
get => test;
set
{
test = value;
Pass = new TestPass { TestId = Test.Id, Answers = new List<AnswerPass>() };
OnPropertyChanged();
}
}
public TestPage(TestViewModel test)
{
InitializeComponent();
Test = test;
}
private async void SubmitButton_Clicked(object sender, EventArgs e)
{
if(Pass.Answers.Count() > Test.TestQuestions.SelectMany(q => q.TestAnswers).Where(a => a.Percent > 0).Count())
{
await DisplayAlert(Lib.Resources.Attention, Lib.Resources.TooManyAnswers, "OK");
}
else if (await DisplayAlert(Lib.Resources.FinishTest, string.Format(Lib.Resources.FinistTestAndSubmitResult, Test?.Name), Lib.Resources.Yes, Lib.Resources.No))
{
AppState.Student.Passes.Add(await AppState.HttpClient.PostJsonAsync<TestPass>($"students/{AppState.Student.Id}/tests", Pass));
await Navigation.PushAsync(new TestResultPage(Pass, Test));
}
}
}
} |
using ClaimDi.DataAccess.Object.API;
using System.ServiceModel;
using System.ServiceModel.Web;
namespace Claimdi.WCF.Consumer
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "ITaskInspection" in both code and config file together.
[ServiceContract]
public interface ITaskInspection
{
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "/add_task_inspection", ResponseFormat = WebMessageFormat.Json)]
BaseResult<APIAddTaskInspectionResponse> AddTaskInspection(APIAddTaskInspectionRequest request);
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "/update_task_inspection", ResponseFormat = WebMessageFormat.Json)]
BaseResult<APIAddTaskInspectionResponse> UpdateTaskInspection(APIUpdateTaskInspectionRequest request);
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "/update_status_wait_approve", ResponseFormat = WebMessageFormat.Json)]
BaseResult<bool?> UpdateStatusWaitApprove(APIUpdateStatusWaitApproveRequest request);
[OperationContract]
[WebInvoke(Method = "GET", UriTemplate = "/task_inspection_detail/{accId}/{taskId}",
ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
BaseResult<APITaskInspectionDetailResponse> GetTaskInspectionDetail(string accId, string taskId);
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "/add_task_inspection_viriyah", ResponseFormat = WebMessageFormat.Json)]
BaseResult<APIAddTaskInspectionResponse> AddTaskInspectionViriyah(APIAddTaskInspectionViriyahRequest request);
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "/update_task_inspection_viriyah", ResponseFormat = WebMessageFormat.Json)]
BaseResult<APIAddTaskInspectionResponse> UpdateTaskInspectionViriyah(APIUpdateTaskInspectionViriyahRequest request);
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "/add_task_inspection_sharepoint", ResponseFormat = WebMessageFormat.Json)]
BaseResult<APIAddTaskInspectionResponse> AddTaskInspectionSharePoint(APIAddTaskInspectionSharePointRequest request);
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "/update_task_inspection_sharepoint", ResponseFormat = WebMessageFormat.Json)]
BaseResult<APIAddTaskInspectionResponse> UpdateTaskInspectionSharePoint(APIUpdateTaskInspectionSharePointRequest request);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _04.RepeatingCounter
{
public class CheckCounter
{
static void Main()
{
int[] numArray = new int[] { 2, 4, 6, 8, 2, 4, 3, 2, 4, 6, 7, 9, 7, 5, 4, 2, 2};
ShowArray(numArray);
PrintRepeatingElements(numArray);
}
public static void ShowArray(int[] numArray)
{
Console.WriteLine("In this array of numbers: ");
foreach (var num in numArray)
{
Console.Write("{0} ", num);
}
Console.WriteLine();
}
public static int CountElements(int[] numArray, int element)
{
int counter = 0;
for (int index = 0; index < numArray.Length; index++)
{
if (numArray[index] == element)
{
counter++;
}
}
return counter;
}
public static void PrintRepeatingElements(int[] numArray)
{
for (int index = 0; index < numArray.Length; index++)
{
Console.WriteLine("Element {0} is repeating {1} times.", numArray[index], CountElements(numArray, numArray[index]));
}
}
}
}
|
using UnityEngine;
using System.Collections;
using MoreMountains.Tools;
namespace MoreMountains.CorgiEngine
{
// Add this to your player prefab and it will have the classic NoClip ability.
public class NoClip : MonoBehaviour
{
[MMInformation("Toogle NoClip with <b>F4</b>",MoreMountains.Tools.MMInformationAttribute.InformationType.Info,false)]
[MMReadOnly] public bool noClip;
public virtual void Update()
{
if (Input.GetKeyDown(KeyCode.F4))
{
noClip = !noClip;
}
if(Input.GetKeyDown(KeyCode.F4) && !noClip)
{
Debug.Log("NOCLIP OFF");
GetComponent<CorgiController>().CollisionsOn();
GetComponent<CorgiController>().GravityActive(true);
GetComponent<Health>().Invulnerable = false;
}
else if (Input.GetKeyDown(KeyCode.F4) && noClip)
{
Debug.Log("NOCLIP ON");
GetComponent<CorgiController>().CollisionsOff();
GetComponent<CorgiController>().GravityActive(false);
GetComponent<Health>().Invulnerable = true;
}
}
}
} |
using System;
using BattleEngine.Actors.Units;
namespace BattleEngine.Actors.Factories
{
public class UnitFactory
{
private BattleObjectFactory _factory;
public UnitFactory(BattleObjectFactory factory, Engine.BattleEngine battleEngine)
{
_factory = factory;
}
public BattleUnit instantiate(Type type)
{
var result = _factory.instantiate(type) as BattleUnit;
return result;
}
public T instantiate<T>() where T : BattleUnitOwner
{
var result = _factory.instantiate(typeof(T)) as T;
return result;
}
}
}
|
using gView.Framework.Geometry;
using System;
using System.Collections;
namespace gView.Plugins.MapTools
{
internal class ZoomStack
{
static System.Collections.Stack stack = new Stack(20);
static public void Push(IEnvelope envelope)
{
if (envelope == null)
{
return;
}
if (stack.Count > 0)
{
IEnvelope last = (IEnvelope)stack.Peek();
//MessageBox.Show(last.minx.ToString() + "==" + envelope.minx.ToString() + "\n" + last.miny.ToString() + "==" + envelope.miny.ToString() + "\n" + last.maxx.ToString() + "==" + envelope.maxx.ToString() + "\n" + last.maxy.ToString() + "==" + envelope.maxy.ToString());
if (Math.Abs(last.minx - envelope.minx) < 1e-10 &&
Math.Abs(last.miny - envelope.miny) < 1e-10 &&
Math.Abs(last.maxx - envelope.maxx) < 1e-10 &&
Math.Abs(last.maxy - envelope.maxy) < 1e-10)
{
return;
}
}
stack.Push(envelope);
//MessageBox.Show(stack.Count.ToString());
}
static public IEnvelope Pop()
{
if (stack.Count == 0)
{
return null;
}
return (IEnvelope)stack.Pop();
}
static public int Count
{
get { return stack.Count; }
}
}
}
|
using System;
using Autofac;
using Autofac.Core;
using System.Collections.Generic;
namespace CC.Infrastructure
{
public class Injector : IDependencyContainer
{
public static IDependencyContainer Container = new Injector();
private ContainerBuilder builder;
private IContainer autFacContainer;
public Injector ()
{
builder = new ContainerBuilder ();
}
public void Register <T1>()
{
builder.RegisterType<T1> ().As<T1> ();
}
public void Register <T1, T2>()
{
builder.RegisterType<T2> ().As<T1> ();
}
public void Register<T1, T2> (List<InitParam> paramsList)
{
builder.RegisterType<T2> ().As<T1> ().WithParameters (paramsList.ToResolvedParam());
}
public void Register<T1, T2> (InitParam param)
{
builder.RegisterType<T2> ().As<T1> ().WithParameter (param.ToResolvedParam ());
}
public void RegisterSingleton <T1, T2>()
{
builder.RegisterType<T2> ().As<T1> ().SingleInstance ();
}
public void RegisterSingleton <T1, T2>(InitParam param)
{
builder.RegisterType<T2> ().As<T1> ().SingleInstance ().WithParameter(param.ToResolvedParam());
}
public void RegisterSingleton <T1, T2, T3>()
{
builder.RegisterType<T3> ()
.As<T1> ().As<T2> ().SingleInstance ();
}
public void RegisterSingleton <T1, T2, T3, T4>()
{
builder.RegisterType<T4> ()
.As<T1> ().As<T2> ().As<T3> ().SingleInstance ();
}
public void RegisterSingleton <T1, T2, T3, T4, T5>()
{
builder.RegisterType<T5> ()
.As<T1> ().As<T2> ().As<T3> ().As<T4> ().SingleInstance();
}
public void RegisterSingleton <T1, T2>(List<InitParam> paramsList)
{
builder.RegisterType<T2> ().As<T1> ().SingleInstance ().WithParameters(paramsList.ToResolvedParam());
}
public void RegisterInstance<T1> (T1 instance) where T1:class{
builder.RegisterInstance (instance).As<T1> ();
}
public T Resolve<T>(List<InitParam> parameters){
return autFacContainer.Resolve<T> (parameters.ToResolvedParam());
}
public T Resolve<T>(params InitParam[] parameters){
return autFacContainer.Resolve<T> (parameters.ToResolvedParam());
}
public T Resolve<T>(){
return autFacContainer.Resolve<T> ();
}
public void Set<T1, T2> (){
var newBuilder = new ContainerBuilder ();
newBuilder.RegisterType<T2> ().As<T1> ();
newBuilder.Update (autFacContainer);
}
public void SetSingleton <T1, T2>()
{
var newBuilder = new ContainerBuilder ();
newBuilder.RegisterType<T2> ().As<T1> ().SingleInstance ();
newBuilder.Update (autFacContainer);
}
public void Init(){
if (builder != null) {
autFacContainer = builder.Build ();
builder = null;
} else {
throw new Exception ("Container is already initialized");
}
}
public void Dispose(){
if (autFacContainer != null) {
autFacContainer.Dispose ();
}
}
public static void Destory(){
if (Container != null) {
(Container as Injector).Dispose ();
Container = null;
}
}
public void RegisterSingleton<T1>()
{
builder.RegisterType<T1>().As<T1>().SingleInstance();
}
}
} |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using ScoreSquid.Web.Models;
namespace ScoreSquid.Web.Tests.Builders
{
public static class ScoreSquidBuilders
{
public static Division BuildDefault(this Division division)
{
return new Division
{
DivisionIdentifier = "E2",
Id = 1,
Name = "Championship"
};
}
public static Team BuildDefault(this Team team, string name = "Brighton")
{
return new Team
{
Division = new Division().BuildDefault(),
DivisionId = 1,
Id = 1,
Name = name
};
}
public static MiniLeague BuildDefault(this MiniLeague miniLeague)
{
var miniLeagueFixture = new MiniLeagueFixture
{
MiniLeague = miniLeague,
Fixtures = new Collection<Fixture>
{
new Fixture
{
HomeTeam = new Team().BuildDefault(),
AwayTeam = new Team().BuildDefault("West Ham")
}
}
};
return new MiniLeague
{
MiniLeagueFixtures = new Collection<MiniLeagueFixture> { miniLeagueFixture },
Name = "Insurecom Mini League"
};
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ChangeColorObject : MonoBehaviour
{
public new ParticleSystem particleSystem;
public ColorType colorType;
private void Start()
{
colorType = (ColorType)Random.Range(0, Technical.EnumCount<ColorType>());
var main = particleSystem.main;
switch (colorType)
{
case ColorType.Green:
main.startColor = Color.green;
break;
case ColorType.Red:
main.startColor = Color.red;
break;
case ColorType.Yellow:
main.startColor = Color.yellow;
break;
}
}
public void OnTriggerEnter(Collider other)
{
if (other.CompareTag(Constants.PlayerTag) && other.TryGetComponent(out BowlingObject bowling))
{
bowling.ChangeColor(colorType);
}
}
} |
using Autofac;
using XH.Core.Context;
using XH.Infrastructure.Bus;
using XH.Infrastructure.Domain;
using XH.Infrastructure.Extensions;
namespace XH.Core.Bus
{
public class MultiTenantInMemoryCommandBus : InMemoryCommandBus
{
private readonly IWorkContext _workContext;
public MultiTenantInMemoryCommandBus(IComponentContext componentContext, IWorkContext workContext) : base(componentContext)
{
_workContext = workContext;
}
public override void Send<TCommand>(TCommand command)
{
var tenancyCommand = command as IMayHaveTenant;
if (tenancyCommand != null && tenancyCommand.TenantId.IsNullOrEmpty())
{
tenancyCommand.TenantId = _workContext.CurrentTenant?.Id;
}
base.Send<TCommand>(command);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MyHotel.Utils;
using System.Web.Services;
using System.Web.UI;
using AjaxControlToolkit;
namespace MyHotel
{
public abstract class BaseWebFormMgmt : System.Web.UI.Page
{
protected override void OnPreInit(EventArgs e)
{
if (HelperCommon.IsMobileDevice(Request.UserAgent))
{
MasterPageFile = "~/MasterPages/MyHotelMobile7InchMgmt.Master";
}
else
{
MasterPageFile = "~/MasterPages/MyHotelMgmt.Master";
}
}
protected void AddScriptManager()
{
if (ScriptManager.GetCurrent(Page) == null)
{
Page.Form.Controls.AddAt(0, new ToolkitScriptManager());
}
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TutoController : MonoBehaviour {
[SerializeField]
private GameObject balloon;
[SerializeField]
private float distance = 3f;
[SerializeField]
private SpawnController spawn;
private List<Color> listColor;
private List<GameObject> listBalloon;
private void Start() {
listColor = new List<Color>();
listColor.Add(Color.blue);
listColor.Add(Color.cyan);
listColor.Add(Color.green);
listColor.Add(Color.red);
listColor.Add(Color.yellow);
listBalloon = new List<GameObject>();
Vector3 position = Vector3.zero;
foreach(Color color in listColor) {
GameObject obj = Instantiate(balloon, transform);
listBalloon.Add(obj);
obj.transform.localPosition = position;
position.x = position.x + distance;
var balloonController = obj.GetComponent<BalloonBehavior>();
balloonController.balloonRenderer.material.color = color;
var balloonRigibody = obj.GetComponent<Rigidbody>();
balloonRigibody.useGravity = false;
balloonRigibody.isKinematic = true;
}
}
private void Update() {
foreach(GameObject obj in listBalloon) {
if(obj == null) {
listBalloon.Remove(obj);
}
}
if (listBalloon.Count == 0) {
spawn.enabled = true;
}
}
}
|
#version 430
layout(local_size_x = 32, local_size_y = 32) in;
uniform float EdgeThreshold = 0.1;
uniform int imageType;
uniform int level;
subroutine void launchSubroutine();
subroutine uniform launchSubroutine sobelSubroutine;
// PLEASE REMEMBER THE DOUBLE LINE PROBLEM https://docs.opencv.org/3.2.0/d5/d0f/tutorial_py_gradients.html
float luminance(vec3 color)
{
//return 0.2126 * float(color.x) / 255.0f + 0.7152 * float(color.y) / 255.0f + 0.0722 * float(color.z) / 255.0f;
return 0.299 * float(color.x) + 0.587 * float(color.y) + 0.114 * float(color.z);
// return float(color.x) + float(color.y) + float(color.z);
}
shared float localData[gl_WorkGroupSize.x + 2][gl_WorkGroupSize.y + 2];
shared float localDataY[gl_WorkGroupSize.x + 2][gl_WorkGroupSize.y + 2];
layout(binding = 0) uniform sampler2D tex_I0;
layout(binding= 0, rgba8) uniform image2D InputImgUI;
layout(binding= 1, rg32f) uniform image2D InputImgF;
layout(binding= 2, rg16i) uniform iimage2D InputImgI;
layout(binding= 7, rg32f) uniform image2D inputGradientXY;
layout(binding= 3, rgba8) uniform image2D OutputImg;
layout(binding= 4, rg32f) uniform image2D outputGradientXY;
layout(binding= 5, rg32f) uniform image2DArray outputGradientArray;
layout(binding= 6, r32f) uniform image2D outputWeight;
//layout(binding= 3, r16i) uniform iimage2D outputGradientY;
subroutine(launchSubroutine)
void applyFilter()
{
uvec2 p = gl_LocalInvocationID.xy + uvec2(1, 1);
float sx = localData[p.x - 1][p.y - 1] + 2 * localData[p.x - 1][p.y] + localData[p.x - 1][p.y + 1] - (localData[p.x + 1][p.y - 1] + 2 * localData[p.x + 1][p.y] + localData[p.x + 1][p.y + 1]);
float sy = localData[p.x - 1][p.y + 1] + 2 * localData[p.x][p.y + 1] + localData[p.x + 1][p.y + 1] - (localData[p.x - 1][p.y - 1] + 2 * localData[p.x][p.y - 1] + localData[p.x + 1][p.y - 1]);
float dist = sx * sx + sy * sy;
if (dist > EdgeThreshold)
imageStore(OutputImg, ivec2(gl_GlobalInvocationID.xy), vec4(1.0));
else
imageStore(OutputImg, ivec2(gl_GlobalInvocationID.xy), vec4(0, 0, 0, 1));
}
subroutine(launchSubroutine)
void getGradients()
{
uvec2 p = gl_LocalInvocationID.xy + uvec2(1, 1);
float lesser = 3.0f;
float upper = 10.0f;
float norm = 1.0f;// / (2 * lesser + 1 * upper); // why does applying the correct norm introduce a lot more noise?
float sx = norm * (- (lesser * localData[p.x - 1][p.y - 1] + upper * localData[p.x - 1][p.y] + lesser * localData[p.x - 1][p.y + 1]) + (lesser * localData[p.x + 1][p.y - 1] + upper * localData[p.x + 1][p.y] + lesser * localData[p.x + 1][p.y + 1]));
float sy = norm * ( (lesser * localData[p.x - 1][p.y + 1] + upper * localData[p.x][p.y + 1] + lesser * localData[p.x + 1][p.y + 1]) - (lesser * localData[p.x - 1][p.y - 1] + upper * localData[p.x][p.y - 1] + lesser * localData[p.x + 1][p.y - 1]));
// float sx = (3.0 * localData[p.x + 1][p.y - 1] + 10.0 * localData[p.x + 1][p.y] + 3.0 * localData[p.x + 1][p.y + 1]) - (3.0 * localData[p.x - 1][p.y - 1] + 10.0 * localData[p.x - 1][p.y] + 3.0 * localData[p.x - 1][p.y + 1]);
// float sy = (3.0 * localData[p.x - 1][p.y + 1] + 10.0 * localData[p.x][p.y + 1] + 3.0 * localData[p.x + 1][p.y + 1]) - (3.0 * localData[p.x - 1][p.y - 1] + 10.0 * localData[p.x][p.y - 1] + 3.0 * localData[p.x + 1][p.y - 1]);
if (imageType == 0 || imageType == 4 || imageType == 5)
{
imageStore(outputGradientXY, ivec2(gl_GlobalInvocationID.xy), vec4((sx), sy, 0, 0));
}
else if (imageType == 1)
{
imageStore(outputGradientXY, ivec2(gl_GlobalInvocationID.xy), vec4(sx, sy , 0, 0));
//imageStore(outputGradientXY, ivec2(gl_GlobalInvocationID.xy), ivec4((sx) * 255.0f, sy * 255.0f, 0, 0));
}
else if (imageType == 2)
{
imageStore(outputGradientArray, ivec3(gl_GlobalInvocationID.xy, 0), vec4(sx, sy, 0, 0));
//float sxY = -(lesser * localDataY[p.x - 1][p.y - 1] + upper * localDataY[p.x - 1][p.y] + lesser * localDataY[p.x - 1][p.y + 1]) + (lesser * localDataY[p.x + 1][p.y - 1] + upper * localDataY[p.x + 1][p.y] + lesser * localDataY[p.x + 1][p.y + 1]);
float syY = norm * ((lesser * localDataY[p.x - 1][p.y + 1] + upper * localDataY[p.x][p.y + 1] + lesser * localDataY[p.x + 1][p.y + 1]) - (lesser * localDataY[p.x - 1][p.y - 1] + upper * localDataY[p.x][p.y - 1] + lesser * localDataY[p.x + 1][p.y - 1]));
//float syY = (lesser * localDataY[p.x - 1][p.y + 1] + upper * localDataY[p.x][p.y + 1] + lesser * localDataY[p.x + 1][p.y + 1]) - (lesser * localDataY[p.x - 1][p.y - 1] + upper * localDataY[p.x][p.y - 1] + lesser * localDataY[p.x + 1][p.y - 1]);
//float syY = (1.0 * localDataY[p.x - 1][p.y + 1] + 2.0 * localDataY[p.x][p.y + 1] + 1.0 * localDataY[p.x + 1][p.y + 1]) - (1.0 * localDataY[p.x - 1][p.y - 1] + 2.0 * localDataY[p.x][p.y - 1] + 1.0 * localDataY[p.x + 1][p.y - 1]);
// we dont need the first chanel output here
imageStore(outputGradientArray, ivec3(gl_GlobalInvocationID.xy, 1), vec4(0, syY, 0, 0));
}
//imageStore(outputGradientY, ivec2(gl_GlobalInvocationID.xy), ivec4(sy * 32766.0f));
}
subroutine(launchSubroutine)
void getSmoothness()
{
// [-0.5, 0.0, 0.5]
// [-0.5
// 0.0
// 0.5]
uvec2 p = gl_LocalInvocationID.xy + uvec2(1, 1);
float ux = (-0.5f * localData[p.x - 1][p.y] + localData[p.x][p.y] + 0.5f * localData[p.x + 1][p.y]); // CHECK ORDER OF ME
float uy = (-0.5f * localData[p.x][p.y - 1] + localData[p.x][p.y] + 0.5f * localData[p.x][p.y + 1]);
float vx = (-0.5f * localDataY[p.x - 1][p.y] + localDataY[p.x][p.y] + 0.5f * localDataY[p.x + 1][p.y]);
float vy = (-0.5f * localDataY[p.x][p.y - 1] + localDataY[p.x][p.y] + 0.5f * localDataY[p.x][p.y + 1]);
float weight = 0.25 / (ux * ux + uy * uy + vx * vx + vy * vy + 0.001f * 0.001f);
imageStore(outputWeight, ivec2(gl_GlobalInvocationID.xy), vec4(weight));
//imageStore(outputGradientArray, ivec3(gl_GlobalInvocationID.xy, 0), ivec4(sx * 32766.0f, sy * 32766.0f, 0, 0));
//imageStore(outputGradientArray, ivec3(gl_GlobalInvocationID.xy, 1), ivec4(sxY * 32766.0f, syY * 32766.0f, 0, 0));
}
void loadImage(ivec2 pos, ivec2 localDataLoc)
{
if (imageType == 0) // rgba8ui
{
// gauss smoothed
localData[localDataLoc.x][localDataLoc.y] = luminance(imageLoad(InputImgUI, pos).xyz);
//localData[localDataLoc.x][localDataLoc.y] = luminance(imageLoad(InputImgUI, ivec2(pos.x - 1, pos.y - 1)).xyz) * 0.077847f + luminance(imageLoad(InputImgUI, ivec2(pos.x, pos.y - 1)).xyz) * 0.123317f + luminance(imageLoad(InputImgUI, ivec2(pos.x + 1, pos.y - 1)).xyz) * 0.077847f +
// luminance(imageLoad(InputImgUI, ivec2(pos.x - 1, pos.y)).xyz) * 0.123317f + luminance(imageLoad(InputImgUI, ivec2(pos.x, pos.y)).xyz) * 0.195346f + luminance(imageLoad(InputImgUI, ivec2(pos.x + 1, pos.y)).xyz) * 0.123317f +
// luminance(imageLoad(InputImgUI, ivec2(pos.x - 1, pos.y + 1)).xyz) * 0.077847f + luminance(imageLoad(InputImgUI, ivec2(pos.x, pos.y + 1)).xyz) * 0.123317f + luminance(imageLoad(InputImgUI, ivec2(pos.x + 1, pos.y + 1)).xyz) * 0.077847f;
}
else if (imageType == 1) // rg float 2
{
vec2 inputVec = imageLoad(InputImgF, pos).xy;
localData[localDataLoc.x][localDataLoc.y] = inputVec.x;
localDataY[localDataLoc.x][localDataLoc.y] = inputVec.y;
}
else if (imageType == 2) // rg float 32
{
//vec2 inputVec = imageLoad(InputImgF, pos).xy;
vec2 inputVec = imageLoad(InputImgUI, ivec2(pos.x - 1, pos.y - 1)).xy * 0.077847f + imageLoad(InputImgUI, ivec2(pos.x, pos.y - 1)).xy * 0.123317f + imageLoad(InputImgUI, ivec2(pos.x + 1, pos.y - 1)).xy * 0.077847f +
imageLoad(InputImgUI, ivec2(pos.x - 1, pos.y)).xy * 0.123317f + imageLoad(InputImgUI, ivec2(pos.x, pos.y)).xy * 0.195346f + imageLoad(InputImgUI, ivec2(pos.x + 1, pos.y)).xy * 0.123317f +
imageLoad(InputImgUI, ivec2(pos.x - 1, pos.y + 1)).xy * 0.077847f + imageLoad(InputImgUI, ivec2(pos.x, pos.y + 1)).xy * 0.123317f + imageLoad(InputImgUI, ivec2(pos.x + 1, pos.y + 1)).xy * 0.077847f;
localData[localDataLoc.x][localDataLoc.y] = inputVec.x;
localDataY[localDataLoc.x][localDataLoc.y] = inputVec.y;
}
else if (imageType == 3) // rg short 16 i
{
ivec2 inputVec = ivec2(imageLoad(InputImgI, pos).xy);
localData[localDataLoc.x][localDataLoc.y] = float(inputVec.x) * 0.00003051757f;
localDataY[localDataLoc.x][localDataLoc.y] = float(inputVec.y) * 0.00003051757f;
}
else if (imageType == 4) // red float 32
{
// gauss smoothed
localData[localDataLoc.x][localDataLoc.y] = texelFetch(tex_I0, pos, level).x;
//localData[localDataLoc.x][localDataLoc.y] = (imageLoad(InputImgF, ivec2(pos.x - 1, pos.y - 1)).x) * 0.077847f + (imageLoad(InputImgUI, ivec2(pos.x, pos.y - 1)).x) * 0.123317f + (imageLoad(InputImgUI, ivec2(pos.x + 1, pos.y - 1)).x) * 0.077847f +
// (imageLoad(InputImgUI, ivec2(pos.x - 1, pos.y)).x) * 0.123317f + (imageLoad(InputImgUI, ivec2(pos.x, pos.y)).x) * 0.195346f + (imageLoad(InputImgUI, ivec2(pos.x + 1, pos.y)).x) * 0.123317f +
// (imageLoad(InputImgUI, ivec2(pos.x - 1, pos.y + 1)).x) * 0.077847f + (imageLoad(InputImgUI, ivec2(pos.x, pos.y + 1)).x) * 0.123317f + (imageLoad(InputImgUI, ivec2(pos.x + 1, pos.y + 1)).x) * 0.077847f;
}
else if (imageType == 5) // rgb8 tex
{
localData[localDataLoc.x][localDataLoc.y] = luminance(texelFetch(tex_I0, pos, level).xyz);
}
}
void main()
{
uvec2 gSize = gl_WorkGroupSize.xy * gl_NumWorkGroups.xy;
// Copy into local memory
loadImage(ivec2(gl_GlobalInvocationID.xy), ivec2(gl_LocalInvocationID.x + 1, gl_LocalInvocationID.y + 1));
// Handle the edges
// Bottom edge
if (gl_LocalInvocationID.y == 0)
{
if (gl_GlobalInvocationID.y > 0)
{
loadImage(ivec2(gl_GlobalInvocationID.xy + ivec2(0, -1)), ivec2(gl_LocalInvocationID.x + 1, 0));
// Lower left corner
if (gl_LocalInvocationID.x == 0)
{
if (gl_GlobalInvocationID.x > 0)
{
loadImage(ivec2(gl_GlobalInvocationID.xy + ivec2(-1, -1)), ivec2(0, 0));
}
else
{
localData[0][0] = 0.0;
localDataY[0][0] = 0.0;
}
}
// Lower right corner
if (gl_LocalInvocationID.x == gl_WorkGroupSize.x - 1)
{
if (gl_GlobalInvocationID.x < gSize.x - 1)
{
loadImage(ivec2(gl_GlobalInvocationID.xy + ivec2(1, -1)), ivec2(gl_WorkGroupSize.x + 1, 0));
}
else
{
localData[gl_WorkGroupSize.x + 1][0] = 0.0;
localDataY[gl_WorkGroupSize.x + 1][0] = 0.0;
}
}
}
else
{
localData[gl_LocalInvocationID.x + 1][0] = 0.0;
localDataY[gl_LocalInvocationID.x + 1][0] = 0.0;
}
}
// Top edge
if (gl_LocalInvocationID.y == gl_WorkGroupSize.y - 1)
{
if (gl_GlobalInvocationID.y < gSize.y - 1)
{
loadImage(ivec2(gl_GlobalInvocationID.xy + ivec2(0, 1)), ivec2(gl_LocalInvocationID.x + 1, gl_WorkGroupSize.y + 1));
// Upper left corner
if (gl_LocalInvocationID.x == 0)
{
if (gl_GlobalInvocationID.x > 0)
{
loadImage(ivec2(gl_GlobalInvocationID.xy) + ivec2(-1, 1), ivec2(0, gl_WorkGroupSize.y + 1));
}
else
{
localData[0][gl_WorkGroupSize.y + 1] = 0.0;
localDataY[0][gl_WorkGroupSize.y + 1] = 0.0;
}
}
// Lower right corner
if (gl_LocalInvocationID.x == gl_WorkGroupSize.x - 1)
{
if (gl_GlobalInvocationID.x < gSize.x - 1)
{
loadImage(ivec2(gl_GlobalInvocationID.xy) + ivec2(1, 1), ivec2(gl_WorkGroupSize.x + 1, gl_WorkGroupSize.y + 1));
}
else
{
localData[gl_WorkGroupSize.x + 1][gl_WorkGroupSize.y + 1] = 0.0;
localDataY[gl_WorkGroupSize.x + 1][gl_WorkGroupSize.y + 1] = 0.0;
}
}
}
else
{
localData[gl_LocalInvocationID.x + 1][gl_WorkGroupSize.y + 1] = 0.0;
localDataY[gl_LocalInvocationID.x + 1][gl_WorkGroupSize.y + 1] = 0.0;
}
}
// Left edge
if (gl_LocalInvocationID.x == 0)
{
if (gl_GlobalInvocationID.x > 0)
{
loadImage(ivec2(gl_GlobalInvocationID.xy) + ivec2(-1, 0), ivec2(0, gl_LocalInvocationID.y + 1));
}
else
{
localData[0][gl_LocalInvocationID.y + 1] = 0.0;
localDataY[0][gl_LocalInvocationID.y + 1] = 0.0;
}
}
// Right edge
if (gl_LocalInvocationID.x == gl_WorkGroupSize.x - 1)
{
if (gl_GlobalInvocationID.x < gSize.x - 1)
{
loadImage(ivec2(gl_GlobalInvocationID.xy) + ivec2(1, 0), ivec2(gl_WorkGroupSize.x + 1, gl_LocalInvocationID.y + 1));
}
else
{
localData[gl_WorkGroupSize.x + 1][gl_LocalInvocationID.y + 1] = 0.0;
localDataY[gl_WorkGroupSize.x + 1][gl_LocalInvocationID.y + 1] = 0.0;
}
}
barrier();
sobelSubroutine();
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Projet2Cpi.DataTypes
{
class PlanningObj
{
}
}
|
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Moq;
using NBatch.Main.Readers.FileReader.Services;
using NBatch.Main.Writers.FileWriter;
using NUnit.Framework;
namespace NBatch.Main.UnitTests.Writers.FileWriter
{
[TestFixture]
class FlatFileItemWriterTests
{
[Test]
public void CallsPropertyValueSerializerToReadAllPropValues()
{
var propSerializer = new Mock<IPropertyValueSerializer>();
var fileService = new Mock<IFileWriterService>();
var fileWriter = new FlatFileItemWriter<string>(propSerializer.Object, fileService.Object);
var values = new[] { "one", "two" };
bool isSaved = fileWriter.Write(values);
Assert.IsFalse(isSaved);
propSerializer.Verify(p => p.Serialize(values));
fileService.Verify(f => f.WriteFile(It.IsAny<IEnumerable<string>>()), Times.Never());
}
[Test]
public void CallsFileServiceToWriterItemsToFile()
{
var values = new[] {"hello"};
var propSerializer = new Mock<IPropertyValueSerializer>();
propSerializer.Setup(p => p.Serialize(It.IsAny<IEnumerable<object>>())).Returns(values);
var fileService = new Mock<IFileWriterService>();
var fileWriter = new FlatFileItemWriter<string>(propSerializer.Object, fileService.Object);
bool isSaved = fileWriter.Write(new[] { "one" });
Assert.IsTrue(isSaved);
fileService.Verify(f => f.WriteFile(values));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace Web3_1.Controllers.Movies
{
[Route("api/movies")]
[ApiController]
public class Movie1Controller : ControllerBase
{
[HttpGet]
public IActionResult GetMovies()
{
return Ok("Pega a visão");
}
}
} |
using UnityEngine;
public interface IEffectManager
{
void PlayEffect(Vector3 position);
}
|
using System;
using System.Linq;
using KartObjects;
using KartObjects.Entities;
using KartObjects.Entities.Documents;
using KartSystem.Entities;
using KartSystem.Interfaces;
namespace KartSystem.Presenters
{
public class ExpDocPresenter : BaseDocEditorPresenter
{
private readonly IExpDocEditView view;
public ExpDocPresenter()
{
}
/// <summary>
/// </summary>
/// <param name="view"></param>
/// <param name="docType"></param>
public ExpDocPresenter(IExpDocEditView view, int docType)
: base(view, docType)
{
this.view = view;
}
public override void refresh()
{
view.ExpGoodRecords = Loader.DbLoad<ExpGoodSpecRecord>("", 0, view.Document.Id,
Convert.ToInt64(view.PriceViewMode), view.SelectedGroupId, Convert.ToInt64(view.ShowNullRest),
view.SelectedSupplierId, IDSession);
//Меняем суммы документа
if ((view.Document is Document) && (view.ExpGoodRecords != null))
{
((Document) view.Document).MarginSumDoc = Convert.ToDecimal(view.ExpGoodRecords.Sum(q => q.MarginSum));
view.Document.SumDoc = Convert.ToDecimal(view.ExpGoodRecords.Sum(q => q.SumPos));
((Document) view.Document).TotalWeight = Convert.ToDecimal(view.ExpGoodRecords.Sum(q => q.Weight*(decimal)q.Quantity));
}
}
public override void saveGoodRecord()
{
Saver.SaveToDb(view.CurrGoodSpecRecord);
var document = view.Document as Document;
if (document != null)
{
document.MarginSumDoc = Convert.ToDecimal(view.ExpGoodRecords.Sum(q => q.MarginSum));
document.SumDoc = Convert.ToDecimal(view.ExpGoodRecords.Sum(q => q.SumPos));
document.TotalWeight = Convert.ToDecimal(view.ExpGoodRecords.Sum(q => q.Weight * (decimal)q.Quantity));
}
Saver.DataContext.CommitRetaining();
}
internal void GetDocPrice(Good good, ExpGoodSpecRecord newExpGoodSpecRecord)
{
var i = Loader.DbLoadSingle<ExpGoodSpecRecord>("idgood=" + good.Id, 0, view.Document.Id, 1, good.IdGoodGroup,
1, null, IDSession);
if (i != null)
{
newExpGoodSpecRecord.Price = i.Price;
newExpGoodSpecRecord.MarginPrice = i.MarginPrice;
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace Polymorphism
{
public class KerjaPerjam : Karyawan
{
private decimal upah;
private decimal jam;
public KerjaPerjam(string namaDepan, string namaBelakang, string nomorKTP, decimal upahPerJam, decimal jamKerja) : base(namaDepan, namaBelakang, nomorKTP)
{
Upah = upahPerJam;
Jam = jamKerja;
}
public decimal Upah
{
get
{
return upah;
}
set
{
if (value < 0)
{
throw new ArgumentOutOfRangeException(nameof(value), value, $"{nameof(Upah)} harus >= 0");
}
upah = value;
}
}
public decimal Jam
{
get
{
return jam;
}
set
{
if (value < 0 || value > 168)
{
throw new ArgumentOutOfRangeException(nameof(value), value, $"{nameof(Jam)} harus >= 0 dan <= 168");
}
jam = value;
}
}
public override decimal Pendapatan()
{
if (Jam <= 40)
{
return Upah * Jam;
}
else
{
return (40 * Upah) + ((Jam - 40) * Upah * 1.5M);
}
}
public override string ToString() =>
$"karyawan per jam: {base.ToString()}\n" +
$"upah per jam: {Upah:C}\njam kerja: {Jam:F2}";
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class QuestButtonListScript : MonoBehaviour {
//private GameObject buttonQuest; //Шаблон для создания кнопок, взятый из Префабов.
private GameObject LineImage; //Линия между активными и уже сделанными квестами
private Text QuestTitle; //Заголовок квеста. Справа наверху
private Text QuestDescription; //Описание квеста.
private Text QuestToDo; //Что надо сделать в квесте
public QuestsData Quests;
public UserData userData; //Список всех квестов.
Transform content;
private GameObject questView;
GameObject currentQuestButton;
private void Awake()
{
//buttonQuest = Resources.Load("Quests/QuestButton") as GameObject;
LineImage = Resources.Load("Quests/QuestSeparator") as GameObject;
}
void OnEnable()
{
userData = GameObject.Find("UserData").GetComponent<UserData>();
Quests = userData.GetComponent<UserData>().ggData.quests;
content = transform.Find("Scroll View/Viewport/Content");
//удаляем старые дочерние объекты для отрисовки актуального списка
foreach (Transform child in content) Destroy(child.gameObject);
//добавляем активные
for (int i = 0; i < Quests.QuestList.Count; i++)
{
if (Quests.QuestList[i].status == Quest.Status.ACTIVE)
{
GenerateButton(i);
}
}
//добавляем разделитель, если есть хоть один активный квест
if (content.childCount >= 1)
{
GameObject sep = Instantiate(LineImage, transform.position, Quaternion.identity) as GameObject;
sep.transform.SetParent(content, false);
}
//добавляем выполненные
for (int i = 0; i < Quests.QuestList.Count; i++)
{
if (Quests.QuestList[i].status == Quest.Status.DONE)
{
GenerateButton(i);
}
}
}
private void GenerateButton (int i)
{
Quest qData = Quests.QuestList[i];
//по списку создаем префабы для каждого объекта
GameObject questView = Instantiate(Resources.Load("Quests/QuestButton"), transform.position, Quaternion.identity) as GameObject;
//делаем их дочерними к полю вывода
questView.transform.SetParent(content, false);
//и отдаем им данные
bool isActiveQuest = qData.id == Quests.currentQuestID;
questView.GetComponent<QuestsButton>().SetQData(isActiveQuest, qData.name, qData.id);
questView.GetComponent<Button>().onClick.AddListener(delegate { UpdateView(questView); });
//если это текущий активный квест, то сохраняем на него ссылку и вызываем отрисовку его описания справа
if (isActiveQuest)
{
currentQuestButton = questView;
UpdateView(questView);
}
//если квест выполнен, делаем текст серым
if (qData.status == Quest.Status.DONE)
{
questView.GetComponent<QuestsButton>().SetTextColorGray();
}
}
public void UpdateView (GameObject questButton)
{
//переписываем поля описания квеста
int id = questButton.GetComponent<QuestsButton>().questID;
Quest qData = Quests.GetQuestData(id);
transform.GetChild(2).GetComponent<UnityEngine.UI.Text>().text = qData.title;
transform.GetChild(3).GetComponent<UnityEngine.UI.Text>().text = qData.description;
transform.GetChild(4).GetComponent<UnityEngine.UI.Text>().text = qData.toDo;
//и меняем флажок активного квеста
if (currentQuestButton) currentQuestButton.GetComponent<QuestsButton>().SetFlag(false);
questButton.GetComponent<QuestsButton>().SetFlag(true);
currentQuestButton = questButton;
Quests.currentQuestID = qData.id;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Baihoc9_QLDangKyHocPhan
{
class SinhVien
{
public string maSV;
public string hoTen;
public string lop;
public SinhVien()
{
}
public SinhVien(string maSV, string hoTen, string lop)
{
this.maSV = maSV;
this.hoTen = hoTen;
this.lop = lop;
}
string CanhLe(string s, int rong)
{
return s.PadRight(rong, ' ');
}
public override string ToString()
{
return string.Format("{0}|{1}|{2}",CanhLe(maSV,10),CanhLe(hoTen, 15),CanhLe(lop,10));
}
}
class SinhVienDH : SinhVien { }
class SinhVienCD : SinhVien { }
}
|
using System;
/// <summary>
/// 283. Move Zeroes
/// </summary>
namespace ConsoleApp4
{
class MoveZeros
{
private static void MoveZeroes(int[] arr)
{
int i = 0,j=1;
while(j<arr.Length)
{
if (arr[i] == 0 && arr[j] == 0)
j++;
else if (arr[i] == 0)
{
int temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
i++;
j++;
}
else
{
i++;
j++;
}
}
}
}
}
|
using System;
namespace Alabo.App.Share.OpenTasks.Base
{
/// <summary>
/// 分润用户,获取收益的用户
/// </summary>
public class ShareUser
{
/// <summary>
/// 是否限制分润用户的用户类型
/// IsLimitShareUserType
/// </summary>
//[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public bool IsLimitShareUserType { get; set; } = false;
/// <summary>
/// 分润用户的用户类型
/// 得到收益的用户类型
/// </summary>
public Guid ShareUserTypeId { get; set; }
/// <summary>
/// 是否限制分润用户的用户类型等级
/// </summary>
public bool IsLimitShareUserGrade { get; set; } = false;
/// <summary>
/// 交易用户、触发用户、下单用户、类型的,等级
/// </summary>
public Guid ShareUserGradeId { get; set; }
}
} |
using Fingo.Auth.Domain.Infrastructure.Interfaces;
using Fingo.Auth.Domain.Users.Interfaces;
namespace Fingo.Auth.Domain.Users.Factories.Interfaces
{
public interface IDeleteByIdUserFactory : IActionFactory
{
IDeleteByIdUser Create();
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace AiBridge
{
public interface ISynapse
{
double Weight { get; set; }
double Value { get; set; }
}
}
|
using UnityEngine;
using System.Collections;
public class RoomTeleport : MonoBehaviour {
ScreenFade sFade;
RoomInfo rInfo;
GameObject destinationRoomObject, destinationDoorObject, playerObject;
int roomX, roomZ;
Room currentRoom;
float currentTime, targetTime, timer = 0, timedAmount = 2;
public float lastInterval, timeNow, myTime;
bool startTimer = false;
// Use this for initialization
void Start () {
//rInfo = GameObject.Find("RoomInfo").GetComponent<RoomInfo>();
sFade = GameObject.Find("Screen Fade").GetComponent<ScreenFade>();
//destinationRoomObject = gameObject;
//destinationDoorObject = gameObject;
currentRoom = transform.parent.parent.parent.GetComponent<Room> ();
roomX = currentRoom.xIndex;
roomZ = currentRoom.zIndex;
}
// Update is called once per frame
void Update () {
timeNow = Time.realtimeSinceStartup;
myTime = timeNow - lastInterval;
if(startTimer){
print(timeNow - currentTime);
if(timer >= (targetTime)){
Teleport();
timer = 0;
startTimer = false;
}
else{
timer = timeNow;
}
}
lastInterval = timeNow;
}
void OnTriggerEnter(Collider c){
if(c.tag == "Player"){
//Debug.Log("[Door Trigger] Attempting to teleport Player.");
playerObject = c.gameObject;
currentTime = timeNow;
targetTime = currentTime + timedAmount;
GetAssociatedDoorway();
sFade.fadeToColor = true;
startTimer = true;
}
}
//void ToggleFade(){
// sFade.ToggleCanFade();
//}
void OnTriggerStay(Collider c){
if(c.tag == "Player"){
}
}
void OnTriggerExit(Collider c){
if(c.tag == "Player"){
}
}
void GetAssociatedDoorway(){
string doorName = transform.parent.name;
switch (doorName) {
case "Door North":
if(GameObject.Find("["+(roomX)+","+(roomZ + 1)+"]")){
destinationRoomObject = GameObject.Find("["+(roomX)+","+(roomZ + 1)+"]");
if(destinationRoomObject.transform.Find("Doors").Find("Door South"))destinationDoorObject = destinationRoomObject.transform.Find("Doors").Find("Door South").Find("RoomInfoTrigger").gameObject;
else Debug.Log("[Door Trigger] Cannot find the associated Door in the next room.");
Debug.Log("[Door Trigger] Teleported North");
}
else Debug.Log("[Door Trigger] Cannot find the next room.");
break;
case "Door South":
if(GameObject.Find("["+(roomX)+","+(roomZ - 1)+"]")){
destinationRoomObject = GameObject.Find("["+(roomX)+","+(roomZ - 1)+"]");
if(destinationRoomObject.transform.Find("Doors").Find("Door North"))destinationDoorObject = destinationRoomObject.transform.Find("Doors").Find("Door North").Find("RoomInfoTrigger").gameObject;
else Debug.Log("[Door Trigger] Cannot find the associated Door in the next room.");
Debug.Log("[Door Trigger] Teleported South");
}
else Debug.Log("[Door Trigger] Cannot find the next room.");
break;
case "Door East" :
if(GameObject.Find("["+(roomX + 1)+","+(roomZ)+"]")){
destinationRoomObject = GameObject.Find("["+(roomX + 1)+","+(roomZ)+"]");
if(destinationRoomObject.transform.Find("Doors").Find("Door West"))destinationDoorObject = destinationRoomObject.transform.Find("Doors").Find("Door West").Find("RoomInfoTrigger").gameObject;
else Debug.Log("[Door Trigger] Cannot find the associated Door in the next room.");
Debug.Log("[Door Trigger] Teleported East");
}
else Debug.Log("[Door Trigger] Cannot find the next room.");
break;
case "Door West" :
if(GameObject.Find("["+(roomX - 1)+","+(roomZ)+"]")){
destinationRoomObject = GameObject.Find("["+(roomX - 1)+","+(roomZ)+"]");
if(destinationRoomObject.transform.Find("Doors").Find("Door East"))destinationDoorObject = destinationRoomObject.transform.Find("Doors").Find("Door East").Find("RoomInfoTrigger").gameObject;
else Debug.Log("[Door Trigger] Cannot find the associated Door in the next room.");
Debug.Log("[Door Trigger] Teleported West");
}
else Debug.Log("[Door Trigger] Cannot find the next room.");
break;
default:
if(GameObject.Find("["+(roomX)+","+(roomZ + 1)+"]")){
destinationRoomObject = GameObject.Find("["+(roomX)+","+(roomZ + 1)+"]");
if(destinationRoomObject.transform.Find("Doors").Find("Door South"))destinationDoorObject = destinationRoomObject.transform.Find("Doors").Find("Door South").Find("RoomInfoTrigger").gameObject;
else Debug.Log("[Door Trigger] Cannot find the associated Door in the next room.");
Debug.Log("[Door Trigger] Teleported North");
}
else Debug.Log("[Door Trigger] Cannot find the next room.");
break;
}
print("Teleporting to " +destinationDoorObject.transform.parent);
}
void Teleport(){
PlayerNavmeshTest nvTest = playerObject.GetComponent<PlayerNavmeshTest> ();
nvTest.StopMoving ();
playerObject.SetActive(false);
//
//
playerObject.transform.position = new Vector3(destinationDoorObject.transform.position.x,
transform.position.y,
destinationDoorObject.transform.position.z);
//
playerObject.SetActive(true);
sFade.fadeToColor = false;
//destinationRoomObject.transform.Find("Doors").Find("Door East").Find("TeleportTrigger").gameObject.SetActive(false);
//playerObject.gameObject.SetActive(false);
//}
}
}
|
#if UNITY_EDITOR
using System;
using System.Collections.Generic;
namespace DChildDebug
{
public class TypeCache<T>
{
private Dictionary<string, Type> m_cache;
public TypeCache()
{
InitializeCache();
}
public Type GetType(string typeName)
{
ValidateCache();
return m_cache[typeName];
}
private void ValidateCache()
{
if (m_cache == null)
{
InitializeCache();
}
}
private void InitializeCache()
{
m_cache = new Dictionary<string, Type>();
var types = Reflection.GetDerivedClasses(typeof(T));
for (int i = 0; i < types.Length; i++)
{
var type = types[i];
m_cache.Add(type.Name, type);
}
}
}
}
#endif |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace ChargeIO
{
public class Charge : Transaction
{
[JsonProperty("gratuity")]
public int? GratuityInCents { get; set; }
[JsonProperty("currency")]
public string Currency { get; set; }
[JsonProperty("capture_reference")]
public string CaptureReference { get; set; }
[JsonProperty("void_reference")]
public string VoidReference { get; set; }
[JsonProperty("avs_result")]
public String AvsResult { get; set; }
[JsonProperty("cvv_result")]
public String CvvResult { get; set; }
[JsonProperty("recurring_charge_id")]
public String RecurringChargeId { get; set; }
[JsonProperty("recurring_charge_occurrence_id")]
public String RecurringChargeOccurrenceId { get; set; }
[JsonProperty("authorization_code")]
public String AuthorizationCode { get; set; }
[JsonProperty("amount_refunded")]
public int? AmountInCentsRefunded { get; set; }
[JsonProperty("refunds")]
public IList<Refund> Refunds { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZY.OA.Model;
using ZY.OA.Model.SearchModel;
namespace ZY.OA.IBLL
{
public partial interface IActionInfoService : IBaseService<ActionInfo>
{
IQueryable<ActionInfo> GetPageEntityBySearch(ActionInfoSearchParms actionInfoSearchParms);
bool SetActionRoleInfo(int actionId, List<int> roleIdlist);
}
}
|
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
namespace Alien2
{
public class OrbitCamera2 : MonoBehaviour
{
public Transform target;
public float maxOffsetDistance = 20f;
public float orbitSpeed = 5f;
public float panSpeed = .1f;
public float zoomSpeed = 1f;
private Vector3 targetOffset = Vector3.zero;
/// Cam position
private Vector3 startPos;
private Vector3 goTo;
private Quaternion startRot;
private Renderer rendd;
private static bool setReset = false;
private bool autoReset = false;
private float turnSpeed;
private Slider mainSlider;
private bool state;
private bool curTabb;
void Start()
{
if (target != null) transform.LookAt(target);
/// Reset Cam position
startPos = Camera.main.transform.position;
startRot = Camera.main.transform.rotation;
mainSlider = GameObject.Find("Canvas").GetComponentInChildren<Slider>();
mainSlider.value = 30f;
}
void Update()
{
MoveCam();
TurnTable();
NewResetCamPos();
}
public void changeState(bool activ)
{
state = activ;
}
public void setAutoRes(bool activ)
{
autoReset = activ;
}
public void turnSpeedf(float speed)
{
turnSpeed = speed;
Debug.Log(turnSpeed);
}
public void TurnTable()
{
if (state)
{
Debug.Log(mainSlider.value);
Vector3 targetPosition = target.position + targetOffset;
transform.RotateAround(targetPosition, Vector3.up, mainSlider.value * Time.deltaTime);
}
}
public void ResetCamPos()
{
GameObject obj = GameObject.Find(GameManager.GetCurrent() + "(Clone)");
string cur1 = obj.name;
if (cur1 == "Alien10(Clone)")
{
transform.position = new Vector3(0.24f, 2.142f, 2.08f);
transform.rotation = Quaternion.Euler(16.9f, 186f, 1f);
}
else
{
targetOffset = Vector3.zero;
Camera.main.transform.position = startPos;
Camera.main.transform.rotation = startRot;
}
}
public static void SetNewResetCamPos(bool asd)
{
setReset = asd;
}
public void SetNewResetCamPos2(bool asd)
{
setReset = asd;
}
public void NewResetCamPos()
{
if (setReset == true)
{
GameObject.Find("Canvas").GetComponentsInChildren<Toggle>()[0].isOn = false;
rendd = GameObject.Find(GameManager.GetCurrent() + "(Clone)").GetComponentInChildren<Renderer>();
Vector3 center = rendd.bounds.center;
float radius = rendd.bounds.extents.magnitude;
goTo = new Vector3(startPos.x, startPos.y, startPos.z + radius - 1.1f);
transform.LookAt(center);
transform.LookAt(center);
transform.position = Vector3.MoveTowards(transform.position, goTo, Time.deltaTime * 1f);
if (transform.position == goTo)
{
setReset = false;
GameObject.Find("Canvas").GetComponentsInChildren<Toggle>()[0].isOn = false;
}
}
}
public void MoveCam()
{
Vector3 targetPosition = target.position + targetOffset;
/// HardReset Cam position Key
if (Input.GetKeyDown(KeyCode.Space))
{
targetOffset = Vector3.zero;
Camera.main.transform.position = startPos;
Camera.main.transform.rotation = startRot;
}
///turntable Key
if (Input.GetKey(KeyCode.T))
{
transform.RotateAround(targetPosition, Vector3.up, 15 * Time.deltaTime);
}
// Left Mouse to Orbit
if (Input.GetMouseButton(0))
{
transform.RotateAround(targetPosition, Vector3.up, Input.GetAxis("Mouse X") * orbitSpeed);
float pitchAngle = Vector3.Angle(Vector3.up, transform.forward);
float pitchDelta = -Input.GetAxis("Mouse Y") * orbitSpeed;
float newAngle = Mathf.Clamp(pitchAngle + pitchDelta, 0f, 180f);
pitchDelta = newAngle - pitchAngle;
transform.RotateAround(targetPosition, transform.right, pitchDelta);
}
// Right Mouse To Truck, Pedestal
if (Input.GetMouseButton(1) || Input.GetMouseButton(2))
{
Vector3 offset = transform.right * -Input.GetAxis("Mouse X") * panSpeed +
transform.up * -Input.GetAxis("Mouse Y") * panSpeed;
Vector3 newTargetOffset = Vector3.ClampMagnitude(targetOffset + offset, maxOffsetDistance);
transform.position += newTargetOffset - targetOffset;
targetOffset = newTargetOffset;
}
// Scroll to Zoom
transform.position += transform.forward * Input.GetAxis("Mouse ScrollWheel") * zoomSpeed;
}
}
} |
using System;
using System.Data;
using System.Text;
using System.Data.SqlClient;
using System.Linq;
using System.Collections.Generic;
using Dapper;
using Model.IntelligenceDiningTable;
namespace DAL.IntelligenceDiningTable
{
/// <summary>
/// 数据访问类:Dish
/// </summary>
public partial class D_Dish
{
#region Method
/// <summary>
/// 是否存在该记录
/// </summary>
public bool Exists(E_Dish model)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("select count(1) from Dish");
strSql.Append(" where id=@id");
using (IDbConnection conn = new SqlConnection(DapperHelper.GetConStr()))
{
int count = conn.Execute(strSql.ToString(), model);
if (count > 0)
{
return true;
}
else
{
return false;
}
}
}
/// <summary>
/// 增加一条数据
/// </summary>
public int Add(E_Dish model)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("insert into Dish(");
strSql.Append("AreaIDS,Name,Characteristic,Back,Picture,FMID,DTID,Method,IsStuffing,cuisine,cookingmethod,taste,crispy,tag)");
strSql.Append(" values (");
strSql.Append("@AreaIDS,@Name,@Characteristic,@Back,@Picture,@FMID,@DTID,@Method,@IsStuffing,@cuisine,@cookingmethod,@taste,@crispy,@tag)");
strSql.Append(";select @@IDENTITY");
using (IDbConnection conn = new SqlConnection(DapperHelper.GetConStr()))
{
object obj = conn.ExecuteScalar(strSql.ToString(), model);
if (obj == null)
{
return 0;
}
else
{
return Convert.ToInt32(obj);
}
}
}
/// <summary>
/// 删除一条数据
/// </summary>
public bool Delete(E_Dish model)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("delete from Dish ");
strSql.Append(" where id=@id");
using (IDbConnection conn = new SqlConnection(DapperHelper.GetConStr()))
{
int count = conn.Execute(strSql.ToString(), model);
if (count > 0)
{
return true;
}
else
{
return false;
}
}
} /// <summary>
/// 批量删除数据
/// </summary>
public bool DeleteList(string idlist)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("delete from Dish ");
strSql.Append(" where id in (" + idlist + ") ");
using (IDbConnection conn = new SqlConnection(DapperHelper.GetConStr()))
{
int count = conn.Execute(strSql.ToString());
if (count > 0)
{
return true;
}
else
{
return false;
}
}
}
/// <summary>
/// 得到一个对象实体
/// </summary>
public E_Dish GetInfoByDevno(int devno,DateTime Date)
{
E_Dish model = null;
StringBuilder strSql = new StringBuilder();
strSql.Append(@"select cast(cast(a.suggest_takeqty as float) as int) as suggest_takeqty,b.* from DishDev a inner join Dish b on a.dishid=b.id
where a.devno=@devno and a.[status]=1 and a.[Date]=@Date");
using (IDbConnection conn = new SqlConnection(DapperHelper.GetConStr()))
{
model = conn.Query<E_Dish>(strSql.ToString(), new { devno= devno, Date= Date })?.FirstOrDefault();
}
return model;
}
/// <summary>
/// 得到一个对象实体
/// </summary>
public E_Dish GetInfo(E_Dish model)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("select * from Dish");
strSql.Append(" where id=@id");
using (IDbConnection conn = new SqlConnection(DapperHelper.GetConStr()))
{
model = conn.Query<E_Dish>(strSql.ToString(), model)?.FirstOrDefault();
}
return model;
}
#endregion Method
}
}
|
using UnityEngine;
[RequireComponent(typeof(BoxCollider2D))]
public class ClickBehaviour : MonoBehaviour
{
private bool isClicking = false;
private SpriteRenderer sr;
private Color originalColor;
public Color clickColor = new Color(0.5f, 0.5f, 0.5f);
public bool hold = false;
public bool alreadyClicked = false;
public int clickCounter = 0;
// Start is called before the first frame update
private void Start()
{
sr = GetComponent<SpriteRenderer>();
originalColor = sr.color;
}
// Update is called once per frame
private void Update()
{
if (isClicking || hold)
{
sr.color = clickColor;
}
else if (hold == false)
{
ResetSprite();
}
}
private void OnMouseDown()
{
isClicking = true;
//GameManager.instance.ClickSound();
}
private void OnMouseUp()
{
isClicking = false;
}
public void ResetSprite()
{
sr.color = originalColor;
hold = false;
}
public void ResetClicks()
{
clickCounter = 0;
}
public void ToggleHold()
{
hold = !hold;
}
} |
using System;
using System.Windows.Input;
using SecurityPlusCore;
namespace SecurityPlusUI.Model
{
public class UserValidationContext : ContextBase
{
private string processPath;
private ProcessOperationType operation;
private ICommand allowCommand;
private ICommand denyCommand;
public UserValidationContext(ProcessOperationType operation, string processPath)
{
if (null == processPath)
{
throw new ArgumentNullException(nameof(processPath));
}
this.processPath = processPath;
this.operation = operation;
this.allowCommand = new CommandBase(o => this.Allow());
this.denyCommand = new CommandBase(o => this.Deny());
}
public ProcessOperationResultType Result { get; private set; } = ProcessOperationResultType.Allow;
public override ICommand AllowCommand
{
get { return this.allowCommand; }
}
public override ICommand DenyCommand
{
get { return this.denyCommand; }
}
public override string Message
{
get
{
return string.Format("Process {0} is executing operation: {1}.", this.processPath, this.operation.ToString().ToUpper());
}
}
private void Allow()
{
this.Result = ProcessOperationResultType.Allow;
}
private void Deny()
{
this.Result = ProcessOperationResultType.Deny;
}
}
}
|
// Copyright (c) Bruno Brant. All rights reserved.
using System;
using System.Windows.Forms;
using RestLittle.UI.Presenters;
namespace RestLittle.UI.Views
{
/// <summary>
/// Displays a configuration form for the user.
/// </summary>
public partial class ConfigurationFormView : Form, IConfigurationFormView
{
/// <summary>
/// Initializes a new instance of the <see cref="ConfigurationFormView"/> class.
/// </summary>
public ConfigurationFormView()
{
InitializeComponent();
// TODO: event leaks here :(
var presenter = new ConfigurationFormPresenter(this, Settings.Default);
components.Add(presenter);
}
/// <inheritdoc/>
public event EventHandler Cancelled
{
add { btnCancel.Click += value; }
remove { btnCancel.Click -= value; }
}
/// <inheritdoc/>
public event EventHandler Accepted
{
add { btnOK.Click += value; }
remove { btnOK.Click -= value; }
}
/// <inheritdoc/>
public TimeSpan TimeToIdle { get => tpTimeToIdle.TimeSpan; set => tpTimeToIdle.TimeSpan = value; }
/// <inheritdoc/>
public TimeSpan MaxBusyTime { get => tpMaxBusyTime.TimeSpan; set => tpMaxBusyTime.TimeSpan = value; }
/// <inheritdoc/>
public TimeSpan RestingTime { get => tpRestingTime.TimeSpan; set => tpRestingTime.TimeSpan = value; }
/// <inheritdoc/>
public TimeSpan WarningInterval { get => tpWarningInterval.TimeSpan; set => tpWarningInterval.TimeSpan = value; }
/// <inheritdoc/>
public void SetError(string name, string errorMessage)
{
var control = GetControlFromName(name);
errorProvider.SetError(control, errorMessage);
}
/// <summary>
/// Returns a control reference accordingly to the name of the control.
/// </summary>
/// <param name="name">The name of the control.</param>
/// <returns>A reference to the user control relating to that name.</returns>
private Control GetControlFromName(string name)
{
// TODO: This is brittle - we are using strings to bind behavior between the presenter and the view.
return name switch
{
nameof(TimeToIdle) => tpTimeToIdle,
nameof(MaxBusyTime) => tpMaxBusyTime,
nameof(RestingTime) => tpRestingTime,
nameof(WarningInterval) => tpWarningInterval,
_ => throw new ArgumentOutOfRangeException(nameof(name), name, "Component doesn't exists."),
};
}
}
}
|
namespace IntervalOfNumbers
{
using System;
public class StartUp
{
public static void Main()
{
int number1 = int.Parse(Console.ReadLine());
int number2 = int.Parse(Console.ReadLine());
if (number1 < number2)
{
for (int i = number1; i <= number2; i++)
{
Console.WriteLine(i);
}
}
else if (number2 < number1)
{
for (int j = number2; j <= number1; j++)
{
Console.WriteLine(j);
}
}
}
}
}
|
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 Cyber_FerCesar_Sistema
{
public partial class Frm_CadFornecedor : Form
{
public Frm_CadFornecedor()
{
InitializeComponent();
}
private void Btn_fechar_Click(object sender, EventArgs e)
{
this.Close();
}
private void Btn_novo_Click(object sender, EventArgs e)
{
Txt_nome.Enabled = true;
Txt_nome.Clear();
Txt_nome.Focus();
Txt_telefone.Enabled = true;
Txt_telefone.Clear();
Txt_nif.Enabled = true;
Txt_nif.Clear();
Btn_salvar.Enabled = true;
Btn_novo.Enabled = false;
}
private void Btn_salvar_Click(object sender, EventArgs e)
{
if (Txt_nome.Text == "" || Txt_telefone.Text =="" || Txt_nif.Text == "")
{
MessageBox.Show("Todos os campos são obrigatórios!");
return;
}
Txt_nome.Enabled = false;
Txt_telefone.Enabled = false;
Txt_nif.Enabled = false;
Btn_salvar.Enabled = false;
Btn_novo.Enabled = true;
string query = String.Format(@"
INSERT INTO
tb_fornecedores(T_NOMEFORNECEDOR,T_TELEFONE,T_NIF)
VALUES('{0}','{1}','{2}')
",Txt_nome.Text,Txt_telefone.Text,Txt_nif.Text);
Banco.dml(query);
MessageBox.Show("Fornecedor Cadastrado!");
}
private void Btn_gestao_Click(object sender, EventArgs e)
{
Frm_GestaoFornecedor frm_GestaoFornecedor = new Frm_GestaoFornecedor();
frm_GestaoFornecedor.Show();
this.Close();
}
}
}
|
using EmberKernel.Services.Statistic;
using EmberKernel.Services.Statistic.Hub;
using Statistic.WpfUI.UI.Model;
using System;
using System.ComponentModel;
using System.Windows;
namespace Statistic.WpfUI.UI.ViewModel
{
public interface IEditorContextViewModel: INotifyPropertyChanged
{
IStatisticHub Formats { get; set; }
IDataSource Variables { get; set; }
InEditHubFormat EditingHubFormat { get; set; }
HubFormat SelectedHubFormat { get; set; }
Visibility CreateVisibility { get; set; }
Visibility SaveVisibility { get; set; }
Visibility DeleteVisibility { get; set; }
EditorMode Mode { get; set; }
event Action<EditorMode> OnEditorModeChanged;
}
}
|
using System;
namespace P01.Stream_Progress
{
public class Program
{
static void Main()
{
var music = new Music("Drake","One Dance", 3, 500);
var file = new File("ILoveNicki.txt", 42, 42);
var film = new Film("TheDictator.mp4", 4242, 16000);
var streamMusic = new StreamProgressInfo(music);
var streamFile = new StreamProgressInfo(file);
var streamFilm = new StreamProgressInfo(film);
Console.WriteLine(streamMusic.CalculateCurrentPercent());
Console.WriteLine(streamFile.CalculateCurrentPercent());
Console.WriteLine(streamFilm.CalculateCurrentPercent());
}
}
}
|
using AspCoreBl.Interfaces;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
namespace AspCoreBl.Repositories
{
public class GenericRepository<T> : IGenericRepository<T> where T : class
{
public PaymentDetailContext _db;
public DbSet<T> _dbSet;
public GenericRepository(PaymentDetailContext db)
{
_db = db;
_dbSet = _db.Set<T>();
}
public IEnumerable<T> GetAll()
{
return _dbSet;
}
public IEnumerable<T> GetAll(Expression<Func<T, bool>> predicate)
{
return _dbSet.Where(predicate);
}
public T GetByID(int id)
{
return _dbSet
.Find(id);
}
public void Add(T t)
{
_dbSet.Add(t);
}
public void Update(T t)
{
EntityEntry dbEntityEntry = _db.Entry<T>(t);
dbEntityEntry.State = EntityState.Modified;
}
public void Delete(T t)
{
_dbSet.Remove(t);
}
public virtual void SaveChanges()
{
_db.SaveChanges();
}
public async Task<T> GetSingleAsync(Expression<Func<T, bool>> predicate, params Expression<Func<T, object>>[] includeProperties)
{
IQueryable<T> query = _db.Set<T>();
foreach (var includeProperty in includeProperties)
{
query = query.Include(includeProperty);
}
return await query.FirstOrDefaultAsync(predicate);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace BudgetHelper.Common
{
public class EnumUtil
{
public static IEnumerable<T> GetValues<T>() =>
Enum.GetValues(typeof(T)).Cast<T>();
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Optimization;
namespace UmbracoMVC
{
public class BundleConfig
{
// For more information on Bundling, visit http://go.microsoft.com/fwlink/?LinkId=254725
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryui").Include(
"~/Scripts/jquery-ui-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.unobtrusive*",
"~/Scripts/jquery.validate*"));
// Use the development version of Modernizr to develop with and learn from. Then, when you're
// ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include("~/Scripts/modernizr-*"));
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/stylesheets/Site.css",
"~/Content/stylesheets/FancyBox/jquery.fancybox.css"));
bundles.Add(new StyleBundle("~/Content/stylesheets/foundicons/css").Include(
"~/Content/stylesheets/generalicons/general_foundicons.css",
"~/Content/stylesheets/generalicons/general_foundicons_ie7.css",
"~/Content/stylesheets/socialicons/social_foundicons.css",
"~/Content/stylesheets/socialicons/social_foundicons_ie7.css"));
bundles.Add(new StyleBundle("~/Content/themes/base/css").Include(
"~/Content/themes/base/jquery.ui.core.css",
"~/Content/themes/base/jquery.ui.resizable.css",
"~/Content/themes/base/jquery.ui.selectable.css",
"~/Content/themes/base/jquery.ui.accordion.css",
"~/Content/themes/base/jquery.ui.autocomplete.css",
"~/Content/themes/base/jquery.ui.button.css",
"~/Content/themes/base/jquery.ui.dialog.css",
"~/Content/themes/base/jquery.ui.slider.css",
"~/Content/themes/base/jquery.ui.tabs.css",
"~/Content/themes/base/jquery.ui.datepicker.css",
"~/Content/themes/base/jquery.ui.progressbar.css",
"~/Content/themes/base/jquery.ui.theme.css"));
#region Foundation Bundles
bundles.Add(new ScriptBundle("~/bundles/foundation").Include(
"~/Scripts/foundation/foundation.js",
"~/Scripts/foundation/foundation.*",
"~/Scripts/foundation/app.js",
"~/Scripts/jquery.cycle2.min.js",
"~/Scripts/jquery.cycle2.center.min.js",
"~/Scripts/jquery.masonry.min.js",
"~/Scripts/FancyBox/jquery.fancybox.js"));
#endregion
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.