text
stringlengths
13
6.01M
namespace ChuanGoing.Domain.Modles.Customers.Dtos { public class CustomerDto { public string Name { get; set; } } }
using UnityEngine; public class GameController2 : MonoBehaviour { [SerializeField] private int targetFrameRate = 60; [SerializeField] private float slowMotion = 0.2f; protected virtual void Awake() { Application.targetFrameRate = targetFrameRate; } protected virtual void Update() { if (Input.GetButtonDown("Slow Motion")) { this.ToggleSlowMotion(); } } private void ToggleSlowMotion() { Time.timeScale = Time.timeScale == 1f ? this.slowMotion : 1f; } }
using System; using DataDynamics.ActiveReports; using DataDynamics.ActiveReports.Document; namespace lianda.REP { public class LDRPG2RP : ActiveReport { public LDRPG2RP(string rqfw) { InitializeReport(); this.TextBox_RQFW.Text = rqfw; } #region ActiveReports Designer generated code private PageHeader PageHeader = null; private Label Label18 = null; private TextBox TextBox_RQFW = null; private GroupHeader GroupHeader1 = null; private Label Label22 = null; private Label Label23 = null; private Label Label24 = null; private Label Label26 = null; private Label Label27 = null; private Label Label28 = null; private Label Label29 = null; private Label Label30 = null; private Label Label31 = null; private Label Label32 = null; private Label Label33 = null; private Label Label36 = null; private Label Label37 = null; private Label Label38 = null; private Line Line63 = null; private Line Line64 = null; private Line Line65 = null; private Line Line66 = null; private Line Line67 = null; private Line Line69 = null; private Line Line70 = null; private Line Line71 = null; private Line Line72 = null; private Line Line73 = null; private Line Line74 = null; private Line Line75 = null; private Line Line76 = null; private Line Line77 = null; private Line Line78 = null; private Line Line81 = null; private Line Line82 = null; private TextBox TextBox27 = null; private Detail Detail = null; private TextBox TextBox1 = null; private TextBox TextBox3 = null; private TextBox TextBox4 = null; private TextBox TextBox5 = null; private TextBox TextBox6 = null; private TextBox TextBox7 = null; private TextBox TextBox8 = null; private TextBox TextBox9 = null; private TextBox TextBox10 = null; private TextBox TextBox11 = null; private TextBox TextBox12 = null; private TextBox TextBox15 = null; private TextBox TextBox16 = null; private TextBox TextBox17 = null; private Line Line23 = null; private Line Line24 = null; private Line Line25 = null; private Line Line26 = null; private Line Line29 = null; private Line Line30 = null; private Line Line31 = null; private Line Line32 = null; private Line Line33 = null; private Line Line34 = null; private Line Line35 = null; private Line Line36 = null; private Line Line38 = null; private Line Line40 = null; private Line Line41 = null; private Line Line42 = null; private GroupFooter GroupFooter1 = null; private TextBox TextBox18 = null; private Line Line43 = null; private Line Line44 = null; private TextBox TextBox19 = null; private TextBox TextBox20 = null; private Line Line45 = null; private Line Line46 = null; private Line Line47 = null; private TextBox TextBox21 = null; private Line Line49 = null; private Line Line50 = null; private Line Line51 = null; private Label Label20 = null; private Line Line52 = null; private Line Line53 = null; private Line Line55 = null; private Line Line56 = null; private Line Line57 = null; private TextBox TextBox24 = null; private Line Line60 = null; private Line Line61 = null; private Line Line62 = null; private PageFooter PageFooter = null; private Label Label19 = null; private TextBox TextBox25 = null; private Label Label21 = null; private TextBox TextBox26 = null; public void InitializeReport() { this.LoadLayout(this.GetType(), "lianda.REP.LDRPG2RP.rpx"); this.PageHeader = ((DataDynamics.ActiveReports.PageHeader)(this.Sections["PageHeader"])); this.GroupHeader1 = ((DataDynamics.ActiveReports.GroupHeader)(this.Sections["GroupHeader1"])); this.Detail = ((DataDynamics.ActiveReports.Detail)(this.Sections["Detail"])); this.GroupFooter1 = ((DataDynamics.ActiveReports.GroupFooter)(this.Sections["GroupFooter1"])); this.PageFooter = ((DataDynamics.ActiveReports.PageFooter)(this.Sections["PageFooter"])); this.Label18 = ((DataDynamics.ActiveReports.Label)(this.PageHeader.Controls[0])); this.TextBox_RQFW = ((DataDynamics.ActiveReports.TextBox)(this.PageHeader.Controls[1])); this.Label22 = ((DataDynamics.ActiveReports.Label)(this.GroupHeader1.Controls[0])); this.Label23 = ((DataDynamics.ActiveReports.Label)(this.GroupHeader1.Controls[1])); this.Label24 = ((DataDynamics.ActiveReports.Label)(this.GroupHeader1.Controls[2])); this.Label26 = ((DataDynamics.ActiveReports.Label)(this.GroupHeader1.Controls[3])); this.Label27 = ((DataDynamics.ActiveReports.Label)(this.GroupHeader1.Controls[4])); this.Label28 = ((DataDynamics.ActiveReports.Label)(this.GroupHeader1.Controls[5])); this.Label29 = ((DataDynamics.ActiveReports.Label)(this.GroupHeader1.Controls[6])); this.Label30 = ((DataDynamics.ActiveReports.Label)(this.GroupHeader1.Controls[7])); this.Label31 = ((DataDynamics.ActiveReports.Label)(this.GroupHeader1.Controls[8])); this.Label32 = ((DataDynamics.ActiveReports.Label)(this.GroupHeader1.Controls[9])); this.Label33 = ((DataDynamics.ActiveReports.Label)(this.GroupHeader1.Controls[10])); this.Label36 = ((DataDynamics.ActiveReports.Label)(this.GroupHeader1.Controls[11])); this.Label37 = ((DataDynamics.ActiveReports.Label)(this.GroupHeader1.Controls[12])); this.Label38 = ((DataDynamics.ActiveReports.Label)(this.GroupHeader1.Controls[13])); this.Line63 = ((DataDynamics.ActiveReports.Line)(this.GroupHeader1.Controls[14])); this.Line64 = ((DataDynamics.ActiveReports.Line)(this.GroupHeader1.Controls[15])); this.Line65 = ((DataDynamics.ActiveReports.Line)(this.GroupHeader1.Controls[16])); this.Line66 = ((DataDynamics.ActiveReports.Line)(this.GroupHeader1.Controls[17])); this.Line67 = ((DataDynamics.ActiveReports.Line)(this.GroupHeader1.Controls[18])); this.Line69 = ((DataDynamics.ActiveReports.Line)(this.GroupHeader1.Controls[19])); this.Line70 = ((DataDynamics.ActiveReports.Line)(this.GroupHeader1.Controls[20])); this.Line71 = ((DataDynamics.ActiveReports.Line)(this.GroupHeader1.Controls[21])); this.Line72 = ((DataDynamics.ActiveReports.Line)(this.GroupHeader1.Controls[22])); this.Line73 = ((DataDynamics.ActiveReports.Line)(this.GroupHeader1.Controls[23])); this.Line74 = ((DataDynamics.ActiveReports.Line)(this.GroupHeader1.Controls[24])); this.Line75 = ((DataDynamics.ActiveReports.Line)(this.GroupHeader1.Controls[25])); this.Line76 = ((DataDynamics.ActiveReports.Line)(this.GroupHeader1.Controls[26])); this.Line77 = ((DataDynamics.ActiveReports.Line)(this.GroupHeader1.Controls[27])); this.Line78 = ((DataDynamics.ActiveReports.Line)(this.GroupHeader1.Controls[28])); this.Line81 = ((DataDynamics.ActiveReports.Line)(this.GroupHeader1.Controls[29])); this.Line82 = ((DataDynamics.ActiveReports.Line)(this.GroupHeader1.Controls[30])); this.TextBox27 = ((DataDynamics.ActiveReports.TextBox)(this.GroupHeader1.Controls[31])); this.TextBox1 = ((DataDynamics.ActiveReports.TextBox)(this.Detail.Controls[0])); this.TextBox3 = ((DataDynamics.ActiveReports.TextBox)(this.Detail.Controls[1])); this.TextBox4 = ((DataDynamics.ActiveReports.TextBox)(this.Detail.Controls[2])); this.TextBox5 = ((DataDynamics.ActiveReports.TextBox)(this.Detail.Controls[3])); this.TextBox6 = ((DataDynamics.ActiveReports.TextBox)(this.Detail.Controls[4])); this.TextBox7 = ((DataDynamics.ActiveReports.TextBox)(this.Detail.Controls[5])); this.TextBox8 = ((DataDynamics.ActiveReports.TextBox)(this.Detail.Controls[6])); this.TextBox9 = ((DataDynamics.ActiveReports.TextBox)(this.Detail.Controls[7])); this.TextBox10 = ((DataDynamics.ActiveReports.TextBox)(this.Detail.Controls[8])); this.TextBox11 = ((DataDynamics.ActiveReports.TextBox)(this.Detail.Controls[9])); this.TextBox12 = ((DataDynamics.ActiveReports.TextBox)(this.Detail.Controls[10])); this.TextBox15 = ((DataDynamics.ActiveReports.TextBox)(this.Detail.Controls[11])); this.TextBox16 = ((DataDynamics.ActiveReports.TextBox)(this.Detail.Controls[12])); this.TextBox17 = ((DataDynamics.ActiveReports.TextBox)(this.Detail.Controls[13])); this.Line23 = ((DataDynamics.ActiveReports.Line)(this.Detail.Controls[14])); this.Line24 = ((DataDynamics.ActiveReports.Line)(this.Detail.Controls[15])); this.Line25 = ((DataDynamics.ActiveReports.Line)(this.Detail.Controls[16])); this.Line26 = ((DataDynamics.ActiveReports.Line)(this.Detail.Controls[17])); this.Line29 = ((DataDynamics.ActiveReports.Line)(this.Detail.Controls[18])); this.Line30 = ((DataDynamics.ActiveReports.Line)(this.Detail.Controls[19])); this.Line31 = ((DataDynamics.ActiveReports.Line)(this.Detail.Controls[20])); this.Line32 = ((DataDynamics.ActiveReports.Line)(this.Detail.Controls[21])); this.Line33 = ((DataDynamics.ActiveReports.Line)(this.Detail.Controls[22])); this.Line34 = ((DataDynamics.ActiveReports.Line)(this.Detail.Controls[23])); this.Line35 = ((DataDynamics.ActiveReports.Line)(this.Detail.Controls[24])); this.Line36 = ((DataDynamics.ActiveReports.Line)(this.Detail.Controls[25])); this.Line38 = ((DataDynamics.ActiveReports.Line)(this.Detail.Controls[26])); this.Line40 = ((DataDynamics.ActiveReports.Line)(this.Detail.Controls[27])); this.Line41 = ((DataDynamics.ActiveReports.Line)(this.Detail.Controls[28])); this.Line42 = ((DataDynamics.ActiveReports.Line)(this.Detail.Controls[29])); this.TextBox18 = ((DataDynamics.ActiveReports.TextBox)(this.GroupFooter1.Controls[0])); this.Line43 = ((DataDynamics.ActiveReports.Line)(this.GroupFooter1.Controls[1])); this.Line44 = ((DataDynamics.ActiveReports.Line)(this.GroupFooter1.Controls[2])); this.TextBox19 = ((DataDynamics.ActiveReports.TextBox)(this.GroupFooter1.Controls[3])); this.TextBox20 = ((DataDynamics.ActiveReports.TextBox)(this.GroupFooter1.Controls[4])); this.Line45 = ((DataDynamics.ActiveReports.Line)(this.GroupFooter1.Controls[5])); this.Line46 = ((DataDynamics.ActiveReports.Line)(this.GroupFooter1.Controls[6])); this.Line47 = ((DataDynamics.ActiveReports.Line)(this.GroupFooter1.Controls[7])); this.TextBox21 = ((DataDynamics.ActiveReports.TextBox)(this.GroupFooter1.Controls[8])); this.Line49 = ((DataDynamics.ActiveReports.Line)(this.GroupFooter1.Controls[9])); this.Line50 = ((DataDynamics.ActiveReports.Line)(this.GroupFooter1.Controls[10])); this.Line51 = ((DataDynamics.ActiveReports.Line)(this.GroupFooter1.Controls[11])); this.Label20 = ((DataDynamics.ActiveReports.Label)(this.GroupFooter1.Controls[12])); this.Line52 = ((DataDynamics.ActiveReports.Line)(this.GroupFooter1.Controls[13])); this.Line53 = ((DataDynamics.ActiveReports.Line)(this.GroupFooter1.Controls[14])); this.Line55 = ((DataDynamics.ActiveReports.Line)(this.GroupFooter1.Controls[15])); this.Line56 = ((DataDynamics.ActiveReports.Line)(this.GroupFooter1.Controls[16])); this.Line57 = ((DataDynamics.ActiveReports.Line)(this.GroupFooter1.Controls[17])); this.TextBox24 = ((DataDynamics.ActiveReports.TextBox)(this.GroupFooter1.Controls[18])); this.Line60 = ((DataDynamics.ActiveReports.Line)(this.GroupFooter1.Controls[19])); this.Line61 = ((DataDynamics.ActiveReports.Line)(this.GroupFooter1.Controls[20])); this.Line62 = ((DataDynamics.ActiveReports.Line)(this.GroupFooter1.Controls[21])); this.Label19 = ((DataDynamics.ActiveReports.Label)(this.PageFooter.Controls[0])); this.TextBox25 = ((DataDynamics.ActiveReports.TextBox)(this.PageFooter.Controls[1])); this.Label21 = ((DataDynamics.ActiveReports.Label)(this.PageFooter.Controls[2])); this.TextBox26 = ((DataDynamics.ActiveReports.TextBox)(this.PageFooter.Controls[3])); } #endregion } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Pausa : MonoBehaviour { public GameObject pause; void Update () { if (Input.GetButtonDown ("Cancel")) { Pause (); } } public void Pause(){ if (pause.activeSelf) { pause.SetActive (false); Time.timeScale = 1; } else { pause.SetActive (true); Time.timeScale = 0; } } }
using Moq; using System; using Xunit; namespace TreeStore.Messaging.Test { public class EntityMessagesTest : IDisposable { private readonly TreeStoreMessageBus messageBus = new TreeStoreMessageBus(); private readonly MockRepository mocks = new MockRepository(MockBehavior.Strict); public void Dispose() { this.mocks.VerifyAll(); } [Fact] public void MessageBus_notifies_of_modified_entity() { // ARRANGE var entity = Mock.Of<IEntity>(); var entityObserver = this.mocks.Create<IObserver<ChangedMessage<IEntity>>>(); ChangedMessage<IEntity> entityChangeMessage = null; entityObserver .Setup(o => o.OnNext(It.IsAny<ChangedMessage<IEntity>>())) .Callback<ChangedMessage<IEntity>>(m => entityChangeMessage = m); this.messageBus.Entities.Subscribe(entityObserver.Object); // ACT this.messageBus.Entities.Modified(entity); // ASSERT Assert.Equal(ChangeTypeValues.Modified, entityChangeMessage.ChangeType); Assert.Same(entity, entityChangeMessage.Changed); } [Fact] public void MessageBus_notifies_of_removed_entity() { // ARRANGE var entity = Mock.Of<IEntity>(); var entityObserver = this.mocks.Create<IObserver<ChangedMessage<IEntity>>>(); ChangedMessage<IEntity> entityChangeMessage = null; entityObserver .Setup(o => o.OnNext(It.IsAny<ChangedMessage<IEntity>>())) .Callback<ChangedMessage<IEntity>>(m => entityChangeMessage = m); this.messageBus.Entities.Subscribe(entityObserver.Object); // ACT this.messageBus.Entities.Removed(entity); // ASSERT Assert.Equal(ChangeTypeValues.Removed, entityChangeMessage.ChangeType); Assert.Same(entity, entityChangeMessage.Changed); } } }
using System; using System.Collections.Generic; using System.Text; namespace PnrAnalysis.Model { [Serializable] public class FDModel { public string fromCode = string.Empty; public string toCode = string.Empty; public string strDate = string.Empty; public string fdDate = string.Empty; public string fdMileage = string.Empty; /// <summary> /// 总数据条数 /// </summary> public string TotalCount = "0"; /// <summary> /// 所有FD数据 /// </summary> public List<FdItemData> FdDataList = new List<FdItemData>(); /// <summary> /// Y舱数据 /// </summary> public List<FdItemData> FdYDataList = new List<FdItemData>(); } [Serializable] public class FdItemData { /// <summary> /// 序号 /// </summary> public string num = string.Empty; /// <summary> /// 航空公司二字码 /// </summary> public string Carry = string.Empty; /// <summary> /// 舱位 /// </summary> public string Seat = string.Empty; /// <summary> /// 折扣 保留2位小数 /// </summary> public string DiscountRate = string.Empty; /// <summary> /// 价格 /// </summary> public string Fare1 = string.Empty; /// <summary> /// 两个舱位价格 /// </summary> public string Fare2 = string.Empty; /// <summary> /// 舱位1 /// </summary> public string seat1 = string.Empty; /// <summary> /// 舱位2 /// </summary> public string seat2 = string.Empty; /// <summary> /// 日期 /// </summary> public string date = string.Empty; /// <summary> /// 其他 /// </summary> public string Orther = string.Empty; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Threads.Examples { public static class SecondThreadExample { public static void ShowSecondThread() { //Create new thread ThreadStart threadDelegate = SecondThreadMethod; Thread thread = new Thread(threadDelegate); //Launch function in secondary thread thread.Start(); //Launch function in main thread var threadId = Thread.CurrentThread.ManagedThreadId; Console.WriteLine($"Main thread Id: {threadId}"); for (int i = 0; i < 100; i++) { Thread.Sleep(20); Console.Write(threadId); } Console.WriteLine("\nMain thread is over."); } private static void SecondThreadMethod() { var threadId = Thread.CurrentThread.ManagedThreadId; Console.WriteLine($"Thread Id: {threadId}"); for (int i = 0; i < 1000; i++) { Thread.Sleep(20); Console.Write(threadId); } Console.WriteLine($"\nThread {threadId} is over."); } } }
using AnnealingWPF.Common; using System; using System.Collections.Generic; using System.Text; namespace AnnealingWPF.Solver.ScoreStrategies { public interface IScoreStrategy { public float CalculateScore(SatConfiguration configuration, SimulatedAnnealingSolver solver); } }
namespace Triton.Game.Mapping { using System; public enum FriendChallengeEvent { I_SENT_CHALLENGE, I_RESCINDED_CHALLENGE, OPPONENT_ACCEPTED_CHALLENGE, OPPONENT_DECLINED_CHALLENGE, I_RECEIVED_CHALLENGE, I_ACCEPTED_CHALLENGE, I_DECLINED_CHALLENGE, OPPONENT_RESCINDED_CHALLENGE, SELECTED_DECK, DESELECTED_DECK, OPPONENT_CANCELED_CHALLENGE, OPPONENT_REMOVED_FROM_FRIENDS } }
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 irc_client.connection; using irc_client.connection.requests; namespace irc_client { public partial class Add : Form { public Add() { InitializeComponent(); this.MaximumSize = this.Size; this.MinimumSize = this.Size; } private void addButton_Click(object sender, EventArgs e) { addFriendAndHideForm(); } private void addButton_KeyPress(object sender, KeyPressEventArgs e) { if (Convert.ToInt32(e.KeyChar) == 13) { addFriendAndHideForm(); } } private void addFriendAndHideForm() { string friendLogin = friendLoginBox.Text; RequestRepository.Instance.OutputRequests.Enqueue(new AddRequest(friendLogin)); friendLoginBox.Text = ""; this.Hide(); } } }
using System; using OpenTK; using OpenTK.Graphics.OpenGL; using OpenTK.Input; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using OpenTK.Graphics; using System.Drawing; namespace SnakeGame { public class Game : GameWindow { private GameField _gameField; public GameField gameField { get { return _gameField; } } private bool _gameOver; private int difficulty;//0 for normal mode, 1 for hard public NetworkManager networkManager; public bool hostGame = true; //Game constructor public Game(int aWidth, int aHeight, int difficulty, string ip = "", bool loadTextures = true) : base(32 * aWidth, 32 * aHeight) { this.difficulty = difficulty; _gameField = new GameField(aWidth, aHeight, this, loadTextures); hostGame = ip == "" ? true : false; networkManager = new NetworkManager(this, hostGame, 10, ip); if (hostGame) { networkManager.RegisterPlayer(null, loadTextures); networkManager.RegisterFruit(loadTextures); } _gameOver = false; } //Enable startup stuff when the game loads protected override void OnLoad(EventArgs e) { base.OnLoad(e); GL.ClearColor(0.1f, 0.2f, 0.5f, 0.0f); GL.Enable(EnableCap.DepthTest); GL.Enable(EnableCap.Texture2D); GL.Enable(EnableCap.AlphaTest); GL.AlphaFunc(AlphaFunction.Gequal, 0.5f); } //Window resizing to match user dimensions protected override void OnResize(EventArgs e) { base.OnResize(e); GL.Viewport(ClientRectangle.X, ClientRectangle.Y, ClientRectangle.Width, ClientRectangle.Height); Matrix4 orth = Matrix4.CreateOrthographicOffCenter(0, Width, Height, 0, 1.0f, 64.0f); GL.MatrixMode(MatrixMode.Projection); GL.LoadMatrix(ref orth); } //Graphics stuff protected override void OnRenderFrame(FrameEventArgs e) { base.OnRenderFrame(e); GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit); Matrix4 modelview = Matrix4.LookAt(Vector3.Zero, -Vector3.UnitZ, Vector3.UnitY); GL.MatrixMode(MatrixMode.Modelview); GL.LoadMatrix(ref modelview); //Meat { //Draw the GameField, Snake, and Fruit _gameField.Draw(); foreach (Snake s in _gameField.Snakes) { s.Draw(); } foreach (Fruit f in _gameField.Fruits) { f.Draw(); } } SwapBuffers(); } //Move the Snake each frame update protected override void OnUpdateFrame(FrameEventArgs e) { base.OnUpdateFrame(e); foreach (Snake s in _gameField.Snakes) { s.Tick(e.Time); } networkManager.NetworkTick(); } //Keyboard input, WASD moves Snake up, down, left, and right protected override void OnKeyDown(KeyboardKeyEventArgs e) { base.OnKeyDown(e); Snake turningSnake = null; foreach (Snake s in _gameField.Snakes) { if (s.objectNetID.OwnerID == networkManager.LocalClientID) { turningSnake = s; break; } } if (e.Key == Key.W) { if (turningSnake != null) { turningSnake.SetDirection(Direction.Up); } } if (e.Key == Key.A) { if(turningSnake != null) { turningSnake.SetDirection(Direction.Left); } } if (e.Key == Key.S) { if(turningSnake != null) { turningSnake.SetDirection(Direction.Down); } } if (e.Key == Key.D) { if(turningSnake != null) { turningSnake.SetDirection(Direction.Right); } } if(e.Key == Key.Escape) { using (InGameMenu inGame = new InGameMenu(this)) inGame.Run(120, 60); } } public Fruit RegisterFruit(ObjectNetID objectNetID, bool loadTexture = true) { Fruit f = new Fruit(_gameField.RandomPointInField(), _gameField, loadTexture); _gameField.Fruits.Add(f); return f; } public Snake RegisterSnake(ObjectNetID ID, bool loadTexture = true) { Snake snake = new Snake(_gameField.RandomPointInField(), _gameField, loadTexture) { objectNetID = ID }; Random r = new Random(); snake.SetColor((byte)r.Next(256), (byte)r.Next(256), (byte)r.Next(256)); _gameField.Snakes.Add(snake); return snake; } } }
using System; namespace FinanceBot.Views.Update { public static class SimpleTxtResponse { //help private static string CommandHelp = "Добавить расходы (например): 150 обед\n" + "Статистика за сегодня: /today\n" + "Статистика за месяц: /month\n" + "Последние расходы: /expenses\n" + "Категории расходов: /categories\n"; public static string Help = "Бот для учета финансов\n\n" + "Для начала использования, введите число в диапазоне от 1 " + "до 31 - день начисления зарплаты. Таким образом задается " + "период для расчета статистики за месяц\n\n" + "Добавляйте расходы в формате:\n(сумма) (категория расходов)\n" + "Например: 150 обед\n\n" + "Бот будет вести статистику в разрезе категорий, а также " + "выделять фиксированные (постоянные, ежемесячные) затраты " + "(связь/аренда и т.д.).\n\n" + "Доступные команды:\n" + CommandHelp; //start public static string HelloNewUser = "Бот для учета финансов\n\n" + "Введите день начисления зарплаты\n" + "/help - справка"; public static string HelloUser = "Бот для учета финансов\n\n" + CommandHelp + "\n" + "/help - справка"; //today public static string TodayStatistic = "Расходы за сегодня\n" + "всего - {0} руб." + "фиксированные - {1} руб.\n\n" + "За текущий месяц: /month"; //month public static string MonthStatistic = "Расходы за месяц\n" + "всего - {0} руб." + "фиксированные - {1} руб.\n\n"; //добавление расходов public static string AddExpense = "Добавлены расходы {2}\n\n" + TodayStatistic; //expenses //сумма, категория, описание, команда public static string ExpenseTemplate = "* {0} руб. - {1}\n{2} ({3} для удаления)\n\n"; public static string LastExpenses = "Последние внесенные расходы:\n\n {0}"; //categories //название, описание, ежемесячная, кастомная public static string CategoryTemplate = "* {0} ({1} - {2}, {3})"; public static string Categories = "Категории расходов:\n\n {0}"; //parse commands public static string AddCategory = "Категория \'{0}\' добавлена!"; public static string DelCategory = "Категория \'{0}\' удалена!"; public static string ChangeSalaryDay = "Изменен период для расчета статистики за месяц! " + "Текущий период: {0}.{1} - {2}.{3}"; //exceptions public static string GeneralExceptionInfo = "{0} - команда не поддерживается или не существует!"; public static string UserNotFound = "{0}: пользователь с id{1} не зарегистрирован!"; public static string UserAlredyExist = "Пользователь с id{0} уже существует!"; public static string CategoryNotFound = "Категория \'{0}\' не существует!"; public static string CategoryAlredyExist = "Категория \'{0}\' уже существует!"; public static string BadExpense = "\'{0}\' - невозможно определить категорию или сумму расхода!"; //TODO: команда "дней до зарплаты" } }
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // using Microsoft.Extensions.Logging; using OmniSharp.Extensions.LanguageServer.Protocol.Server; using System; using System.Threading; using System.Threading.Tasks; namespace Microsoft.PowerShell.EditorServices.Services.PowerShellContext { internal class ProtocolPSHostUserInterface : EditorServicesPSHostUserInterface { #region Private Fields private readonly ILanguageServer _languageServer; #endregion #region Constructors /// <summary> /// Creates a new instance of the ConsoleServicePSHostUserInterface /// class with the given IConsoleHost implementation. /// </summary> /// <param name="powerShellContext"></param> public ProtocolPSHostUserInterface( ILanguageServer languageServer, PowerShellContextService powerShellContext, ILogger logger) : base(powerShellContext, new SimplePSHostRawUserInterface(logger), logger) { _languageServer = languageServer; } #endregion /// <summary> /// Writes output of the given type to the user interface with /// the given foreground and background colors. Also includes /// a newline if requested. /// </summary> /// <param name="outputString"> /// The output string to be written. /// </param> /// <param name="includeNewLine"> /// If true, a newline should be appended to the output's contents. /// </param> /// <param name="outputType"> /// Specifies the type of output to be written. /// </param> /// <param name="foregroundColor"> /// Specifies the foreground color of the output to be written. /// </param> /// <param name="backgroundColor"> /// Specifies the background color of the output to be written. /// </param> public override void WriteOutput( string outputString, bool includeNewLine, OutputType outputType, ConsoleColor foregroundColor, ConsoleColor backgroundColor) { // TODO: Invoke the "output" notification! } /// <summary> /// Sends a progress update event to the user. /// </summary> /// <param name="sourceId">The source ID of the progress event.</param> /// <param name="progressDetails">The details of the activity's current progress.</param> protected override void UpdateProgress( long sourceId, ProgressDetails progressDetails) { // TODO: Send a new message. } protected override Task<string> ReadCommandLineAsync(CancellationToken cancellationToken) { // This currently does nothing because the "evaluate" request // will cancel the current prompt and execute the user's // script selection. return new TaskCompletionSource<string>().Task; } protected override InputPromptHandler OnCreateInputPromptHandler() { return new ProtocolInputPromptHandler(_languageServer, this, this, this.Logger); } protected override ChoicePromptHandler OnCreateChoicePromptHandler() { return new ProtocolChoicePromptHandler(_languageServer, this, this, this.Logger); } } }
using System.Diagnostics.CodeAnalysis; using System.Text.Json.Serialization; namespace CoinBot.Clients.Binance { [SuppressMessage(category: "Microsoft.Performance", checkId: "CA1812:AvoidUninstantiatedInternalClasses", Justification = "Used as data packet")] internal sealed class BinanceProduct { [JsonPropertyName(name: @"symbol")] [SuppressMessage(category: "ReSharper", checkId: "RedundantDefaultMemberInitializer", Justification = "TODO: Review")] public string Symbol { get; set; } = default!; [JsonPropertyName(name: @"quoteAssetName")] [SuppressMessage(category: "ReSharper", checkId: "RedundantDefaultMemberInitializer", Justification = "TODO: Review")] public string QuoteAssetName { get; set; } = default!; [JsonPropertyName(name: @"tradedMoney")] public double TradedMoney { get; set; } [JsonPropertyName(name: @"baseAssetUnit")] [SuppressMessage(category: "ReSharper", checkId: "RedundantDefaultMemberInitializer", Justification = "TODO: Review")] public string BaseAssetUnit { get; set; } = default!; [JsonPropertyName(name: @"baseAssetName")] [SuppressMessage(category: "ReSharper", checkId: "RedundantDefaultMemberInitializer", Justification = "TODO: Review")] public string BaseAssetName { get; set; } = default!; [JsonPropertyName(name: @"baseAsset")] [SuppressMessage(category: "ReSharper", checkId: "RedundantDefaultMemberInitializer", Justification = "TODO: Review")] public string BaseAsset { get; set; } = default!; [JsonPropertyName(name: @"tickSize")] [SuppressMessage(category: "ReSharper", checkId: "RedundantDefaultMemberInitializer", Justification = "TODO: Review")] public string TickSize { get; set; } = default!; [JsonPropertyName(name: @"prevClose")] public decimal? PrevClose { get; set; } [JsonPropertyName(name: @"activeBuy")] public decimal ActiveBuy { get; set; } [JsonPropertyName(name: @"high")] [SuppressMessage(category: "ReSharper", checkId: "RedundantDefaultMemberInitializer", Justification = "TODO: Review")] public string High { get; set; } = default!; [JsonPropertyName(name: @"lastAggTradeId")] public long LastAggTradeId { get; set; } [JsonPropertyName(name: @"low")] [SuppressMessage(category: "ReSharper", checkId: "RedundantDefaultMemberInitializer", Justification = "TODO: Review")] public string Low { get; set; } = default!; [JsonPropertyName(name: @"matchingUnitType")] [SuppressMessage(category: "ReSharper", checkId: "RedundantDefaultMemberInitializer", Justification = "TODO: Review")] public string MatchingUnitType { get; set; } = default!; [JsonPropertyName(name: @"close")] [SuppressMessage(category: "ReSharper", checkId: "RedundantDefaultMemberInitializer", Justification = "TODO: Review")] public string Close { get; set; } = default!; [JsonPropertyName(name: @"quoteAsset")] [SuppressMessage(category: "ReSharper", checkId: "RedundantDefaultMemberInitializer", Justification = "TODO: Review")] public string QuoteAsset { get; set; } = default!; [JsonPropertyName(name: @"active")] public bool Active { get; set; } [JsonPropertyName(name: @"minTrade")] [SuppressMessage(category: "ReSharper", checkId: "RedundantDefaultMemberInitializer", Justification = "TODO: Review")] public decimal MinTrade { get; set; } [JsonPropertyName(name: @"activeSell")] public double ActiveSell { get; set; } [JsonPropertyName(name: @"withdrawFee")] [SuppressMessage(category: "ReSharper", checkId: "RedundantDefaultMemberInitializer", Justification = "TODO: Review")] public string WithdrawFee { get; set; } = default!; [JsonPropertyName(name: @"volume")] public decimal Volume { get; set; } [JsonPropertyName(name: @"decimalPlaces")] public long DecimalPlaces { get; set; } [JsonPropertyName(name: @"quoteAssetUnit")] [SuppressMessage(category: "ReSharper", checkId: "RedundantDefaultMemberInitializer", Justification = "TODO: Review")] public string QuoteAssetUnit { get; set; } = default!; [JsonPropertyName(name: @"open")] [SuppressMessage(category: "ReSharper", checkId: "RedundantDefaultMemberInitializer", Justification = "TODO: Review")] public string Open { get; set; } = default!; [JsonPropertyName(name: @"status")] [SuppressMessage(category: "ReSharper", checkId: "RedundantDefaultMemberInitializer", Justification = "TODO: Review")] public string Status { get; set; } = default!; [JsonPropertyName(name: @"minQty")] [SuppressMessage(category: "ReSharper", checkId: "RedundantDefaultMemberInitializer", Justification = "TODO: Review")] public double MinQty { get; set; } = default!; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Ball : MonoBehaviour { public float moveSpeed = 12.0f; public Vector2 ballDirection = Vector2.left; public float topBounds = 9.4f; public float bottomBounds = -9.4f; public float rigthBounds = 15f; public float leftBounds = -15f; private float playerPaddleHeight; private float playerPaddleWidth; private float computerPaddleHeight; private float computerPaddleWidth; private float playerPaddleMaxX; private float playerPaddleMaxY; private float playerPaddleMinX; private float playerPaddleMinY; private float computerPaddleMaxX; private float computerPaddleMaxY; private float computerPaddleMinX; private float computerPaddleMinY; private float ballWidth; private float ballHeight; private GameObject paddlePlayer; private GameObject paddleComputer; private float bounceAngle; private float vx, vy; private float maxAngle = 45.0f; private bool collidedWithPlayer; private bool collidedWithComputer; private bool collidedWithWall; void Start () { if(moveSpeed < 0){ moveSpeed = -1 * moveSpeed; } paddlePlayer = GameObject.Find("player_paddle"); paddleComputer = GameObject.Find("computer_paddle"); playerPaddleHeight = paddlePlayer.transform.GetComponent<SpriteRenderer>().bounds.size.y; playerPaddleWidth = paddlePlayer.transform.GetComponent<SpriteRenderer>().bounds.size.x; computerPaddleHeight = paddleComputer.transform.GetComponent<SpriteRenderer>().bounds.size.y; computerPaddleWidth = paddleComputer.transform.GetComponent<SpriteRenderer>().bounds.size.x; ballHeight = transform.GetComponent<SpriteRenderer>().bounds.size.y; ballWidth = transform.GetComponent<SpriteRenderer>().bounds.size.x; playerPaddleMaxX = paddlePlayer.transform.localPosition.x + playerPaddleWidth / 1.8f; playerPaddleMinX = paddlePlayer.transform.localPosition.x - playerPaddleWidth / 1.8f; computerPaddleMaxX = paddleComputer.transform.localPosition.x - computerPaddleWidth / 1.8f; computerPaddleMinX = paddleComputer.transform.localPosition.x + computerPaddleWidth / 1.8f; bounceAngle = GetRandomBounceAngle(); vx = moveSpeed * Mathf.Cos(bounceAngle); vy = moveSpeed * -Mathf.Sin(bounceAngle); } void Update () { Move(); } bool CheckCollision () { playerPaddleMaxY = paddlePlayer.transform.localPosition.y + playerPaddleHeight / 1.8f; playerPaddleMinY = paddlePlayer.transform.localPosition.y - playerPaddleHeight / 1.8f; computerPaddleMaxY = paddleComputer.transform.localPosition.y + computerPaddleHeight / 1.8f; computerPaddleMinY = paddleComputer.transform.localPosition.y - computerPaddleHeight / 1.8f; if (transform.localPosition.x - ballWidth / 1.8f < playerPaddleMaxX && transform.localPosition.x + ballWidth / 1.8f > playerPaddleMinX){ if(transform.localPosition.y - ballHeight / 1.8f < playerPaddleMaxY && transform.localPosition.y + ballHeight / 1.8f > playerPaddleMinY){ ballDirection = Vector2.right; collidedWithPlayer = true; transform.localPosition = new Vector3(playerPaddleMaxX + ballWidth / 1.8f, transform.localPosition.y, transform.localPosition.z); return true; } } if (transform.localPosition.x + ballWidth / 1.8f > computerPaddleMaxX && transform.localPosition.x - ballWidth / 1.8f < computerPaddleMinX){ if (transform.localPosition.y - ballHeight / 1.8f < computerPaddleMaxY && transform.localPosition.y + ballHeight / 1.8f > computerPaddleMinY){ ballDirection = Vector2.left; collidedWithComputer = true; transform.localPosition = new Vector3(computerPaddleMaxX - ballWidth / 1.8f, transform.localPosition.y, transform.localPosition.z); return true; } } if(transform.localPosition.y > topBounds){ transform.localPosition = new Vector3(transform.localPosition.x, topBounds, transform.localPosition.z); collidedWithWall = true; return true; } if (transform.localPosition.y < bottomBounds){ transform.localPosition = new Vector3(transform.localPosition.x, bottomBounds, transform.localPosition.z); collidedWithWall = true; return true; } return false; } void Move(){ if(!CheckCollision()){ vx = moveSpeed * Mathf.Cos(bounceAngle); if (moveSpeed > 0) vy = moveSpeed * -Mathf.Sin(bounceAngle); else vy = moveSpeed * Mathf.Sin(bounceAngle); transform.localPosition += new Vector3(ballDirection.x * vx * Time.deltaTime, vy * Time.deltaTime, 0); } else { if(moveSpeed < 0) moveSpeed = -1 * moveSpeed; if (collidedWithPlayer){ collidedWithPlayer = false; float relativeIntersectY = paddlePlayer.transform.localPosition.y - transform.localPosition.y; float normalizedRelativeIntersectionY = (relativeIntersectY / (playerPaddleHeight) / 1.8f); bounceAngle = normalizedRelativeIntersectionY * (maxAngle * Mathf.Deg2Rad * 2); } else if(collidedWithComputer){ collidedWithComputer = false; float relativeIntersectY = paddleComputer.transform.localPosition.y - transform.localPosition.y; float normalizedRelativeIntersectionY = (relativeIntersectY / (computerPaddleHeight) / 1.8f); bounceAngle = normalizedRelativeIntersectionY * (maxAngle * Mathf.Deg2Rad * 2); } else if(collidedWithWall){ collidedWithWall = false; bounceAngle = -bounceAngle; } } } float GetRandomBounceAngle(float minDegrees = 160f, float maxDegrees = 260f){ float minRan = minDegrees * Mathf.PI / 180; float maxRad = maxDegrees * Mathf.PI / 180; return Random.Range(minRan, maxRad); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Runtime.Remoting; using System.Runtime.Remoting.Channels; using System.Runtime.Remoting.Channels.Tcp; using System.Diagnostics; using RemoteServices; using System.Timers; using System.Threading; namespace pacman { public static class Server { private static string MSEC_PER_ROUND; private static int NUM_PLAYERS; public static List<IClient> clients; public static GameEngine engine; private static bool gamestarted = false; private static bool gamesettings = false; //game settings is true when the game rate and the num of players is known static object _lock = new Object(); static object _lock1 = new Object(); private static System.Timers.Timer aTimer; public static string executionPath() { return @Environment.CurrentDirectory + "/Server.exe"; } static void Main(string[] args) { if (args.Length == 0) { TcpChannel channel = new TcpChannel(8086); ChannelServices.RegisterChannel(channel, false); System.Console.WriteLine("Desired game rate:"); MSEC_PER_ROUND = Console.ReadLine(); System.Console.WriteLine("Number of players:"); NUM_PLAYERS = Int32.Parse(Console.ReadLine()); } else { string url = args[0]; string[] urlSplit = url.Split(':', '/'); TcpChannel channel = new TcpChannel(Int32.Parse(urlSplit[4])); ChannelServices.RegisterChannel(channel, false); System.Console.WriteLine("Desired game rate:"); MSEC_PER_ROUND = args[1]; System.Console.WriteLine(args[1]); System.Console.WriteLine("Number of players:"); NUM_PLAYERS = Int32.Parse(Console.ReadLine()); System.Console.WriteLine(args[2]); } //Alternative 1 //RemotingConfiguration.RegisterWellKnownServiceType( // typeof(ServerServices), "Server", // WellKnownObjectMode.Singleton); //Alternative 2 ServerServices service = new ServerServices(); RemotingServices.Marshal(service, "Server", typeof(ServerServices)); if (MSEC_PER_ROUND == "") { MSEC_PER_ROUND = "20"; } gamesettings = true; Console.WriteLine("Clients number -> " + clients.Count); while (clients.Count != NUM_PLAYERS) { lock (_lock) { Monitor.Wait(_lock); } } foreach (IClient client in clients.ToList()) { System.Console.WriteLine(client.GetHashCode()); client.startGame(MSEC_PER_ROUND, NUM_PLAYERS.ToString()); } while (service.ready < NUM_PLAYERS) { lock (_lock1) { Monitor.Wait(_lock1); } } gamestarted = true; //indicates that a game as started engine.start(); System.Threading.Thread.Sleep(1000); engine.startTimer(MSEC_PER_ROUND); engine.seePacmans(); System.Console.WriteLine("Press <enter> to terminate game server..."); System.Console.ReadLine(); } delegate void DelSendMoves(string ip, string port, string move); class ServerServices : MarshalByRefObject, IServer { internal int ready = 0; internal ServerServices() { clients = new List<IClient>(); engine = new GameEngine(clients); } public void RegisterClient(string NewClientIP, string NewClientPort) { if(gamestarted == false && gamesettings == true) { Console.WriteLine("New client listening at " + "tcp://" + NewClientIP + ":" + NewClientPort + "/Client"); IClient newClient = (IClient)Activator.GetObject( typeof(IClient), "tcp://" + NewClientIP + ":" + NewClientPort + "/Client"); newClient.setPort(NewClientPort); newClient.setIP(NewClientIP); clients.Add(newClient); engine.setPacmans(NewClientIP, NewClientPort); engine.seePacmans(); lock (_lock) { Monitor.Pulse(_lock); } } else { IClient newClient = (IClient)Activator.GetObject( typeof(IClient), "tcp://" + NewClientIP + ":" + NewClientPort + "/Client"); newClient.fail("Game already started."); } } public List<IClient> getClients() { return clients; } public void sendMove(string ip, string port, string move) { //engine.setMoves(ip, port, move); DelSendMoves delSendMoves = new DelSendMoves(engine.setMoves); delSendMoves(ip, port, move); } public void readyClient() { ready++; if(ready == NUM_PLAYERS) { lock (_lock1) { Monitor.Pulse(_lock1); } } } public void gameOver(string identificador) { engine.removeClient(identificador); } public void getProcessToCrash() { Process.GetCurrentProcess().Kill(); } public void freeze() { engine.setFreeze(); } public void unfreeze() { engine.setUnfreeze(); } public string getStatus() { return "On"; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Infra; namespace CareerCup150.Chapter4_TreeGraph { public class _04_06_LCA { /* * Design an algorithm and write code to find the first common ancestor of two nodes in a binary tree. * Avoid storing additional nodes in a data structure. NOTE: This is not necessarily a binary search tree. */ public TreeNode FindLCA(TreeNode n1, TreeNode n2, TreeNode root) { if (root == null) return null; if (root == n1 || root == n2) return root; TreeNode left = FindLCA(n1, n2, root.LeftChild); TreeNode right = FindLCA(n1, n2, root.RightChild); if (left != null && right != null) { return root; } else if (left == null && right == null) { return null; } return left != null ? left : right; } } }
using Microsoft.EntityFrameworkCore; namespace WebApplication2.Models { public class PostContext : DbContext { public DbSet<Post> Posts { get; set; } public DbSet<User> Users { get; set; } public PostContext(DbContextOptions<PostContext> options) : base(options) => Database.EnsureCreated(); protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { base.OnConfiguring(optionsBuilder); optionsBuilder.UseLazyLoadingProxies(); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.NetworkInformation; using System.Runtime.InteropServices.WindowsRuntime; using System.Runtime.Serialization; using System.Threading.Tasks; using Windows.ApplicationModel.Background; using Windows.Data.Xml.Dom; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.Networking.Connectivity; using Windows.Storage; using Windows.UI; using Windows.UI.Core; using Windows.UI.Notifications; using Windows.UI.Popups; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; // “空白页”项模板在 http://go.microsoft.com/fwlink/?LinkId=391641 上有介绍 namespace WirelessHelper { /// <summary> /// 可用于自身或导航至 Frame 内部的空白页。 /// </summary> public sealed partial class MainPage : Page { public UserManager usermanager=new UserManager(); private ApplicationDataContainer _appSettings; public XmlDocument toastXML = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText01); public bool register = false; public bool flag = false; public BackgroundTaskRegistration task; public MainPage() { this.InitializeComponent(); _appSettings = ApplicationData.Current.LocalSettings; this.NavigationCacheMode = NavigationCacheMode.Required; } /// <summary> /// 在此页将要在 Frame 中显示时进行调用。 /// </summary> /// <param name="e">描述如何访问此页的事件数据。 /// 此参数通常用于配置页。</param> protected override void OnNavigatedTo(NavigationEventArgs e) { writetextbox(); // TODO: 准备此处显示的页面。 // TODO: 如果您的应用程序包含多个页面,请确保 // 通过注册以下事件来处理硬件“后退”按钮: // Windows.Phone.UI.Input.HardwareButtons.BackPressed 事件。 // 如果使用由某些模板提供的 NavigationHelper, // 则系统会为您处理该事件。 foreach (var tasks in BackgroundTaskRegistration.AllTasks) { if(tasks.Value.Name == "ListenForDLUT") { register = true; task = (BackgroundTaskRegistration)tasks.Value; break; } } if(register) { BackgroundSwitch.IsOn = true; NotificationSwitch.IsEnabled = true; } flag = true; } private async void Button_Click(object sender, RoutedEventArgs e) { if(UserNameBox.Text=="") { MessageDialog message = new MessageDialog("请输入用户名"); await message.ShowAsync(); return; } if(PassWordBox.Password=="") { MessageDialog message = new MessageDialog("请输入密码"); await message.ShowAsync(); return; } ConnectionProfile connectionProfile = NetworkInformation.GetInternetConnectionProfile(); if (connectionProfile == null || connectionProfile.ProfileName != "DLUT") { MessageDialog message = new MessageDialog("请连接到DLUT!"); await message.ShowAsync(); await Windows.System.Launcher.LaunchUriAsync(new Uri("ms-settings-wifi:")); return; } usermanager.UserName = UserNameBox.Text; usermanager.UserPassWord = PassWordBox.Password; usermanager.postData(); readtextbox(); } private void readtextbox() { _appSettings.Values["username"] = usermanager.UserName; _appSettings.Values["password"] = usermanager.UserPassWord; _appSettings.Values["save"] = usermanager.PWDSaved; if(NotificationSwitch.IsEnabled) _appSettings.Values["notification"] = NotificationSwitch.IsOn; } private void writetextbox() { if (_appSettings.Values.ContainsKey("username")) { UserNameBox.Text = _appSettings.Values["username"].ToString(); usermanager.UserName = _appSettings.Values["username"].ToString(); } if(_appSettings.Values.ContainsKey("password")) { usermanager.UserPassWord = _appSettings.Values["password"].ToString(); } if (_appSettings.Values.ContainsKey("notification")) { NotificationSwitch.IsOn = (bool)_appSettings.Values["notification"]; } if (_appSettings.Values.ContainsKey("save")) { SavedSwitch.IsOn = (bool)_appSettings.Values["save"]; if ((bool)_appSettings.Values["save"]) usermanager.PWDSaved = true; if ((bool)_appSettings.Values["save"]&&_appSettings.Values.ContainsKey("password")) PassWordBox.Password = _appSettings.Values["password"].ToString(); } } private async void BackgroundSwitch_Toggled(object sender, RoutedEventArgs e) { if (register == false && BackgroundSwitch.IsOn == true) { if(!(_appSettings.Values.ContainsKey("username") )&&!_appSettings.Values.ContainsKey("password") &&(UserNameBox.Text==""||PassWordBox.Password=="" )) { await new MessageDialog("请保存用户信息").ShowAsync(); BackgroundSwitch.IsOn = false; return; } readtextbox(); var builder = new BackgroundTaskBuilder(); builder.Name = "ListenForDLUT"; builder.TaskEntryPoint = "ListenForConnecting.ListenTask"; builder.SetTrigger(new SystemTrigger(SystemTriggerType.NetworkStateChange, false)); builder.AddCondition(new SystemCondition(SystemConditionType.FreeNetworkAvailable)); var access = await BackgroundExecutionManager.RequestAccessAsync(); if (access == BackgroundAccessStatus.AllowedMayUseActiveRealTimeConnectivity) { task = builder.Register(); } else if (access == BackgroundAccessStatus.Denied) { await new MessageDialog("您已禁用后台任务或后台任务数量已达最大!").ShowAsync(); BackgroundSwitch.IsOn = false; return; } NotificationSwitch.IsEnabled = true; register = true; } else { if (register && BackgroundSwitch.IsOn == false) { foreach (var task in BackgroundTaskRegistration.AllTasks) { if (task.Value.Name == "ListenForDLUT") { task.Value.Unregister(true); register = false; NotificationSwitch.IsEnabled = false; return; } } await new MessageDialog("后台未开启!").ShowAsync(); NotificationSwitch.IsEnabled = false; register = false; } } } private void NotificationSwitch_Toggled(object sender, RoutedEventArgs e) { if(flag) readtextbox(); } private void UserNameBox_TextChanged(object sender, TextChangedEventArgs e) { if (UserNameBox.Text != "") { usermanager.UserName = UserNameBox.Text; readtextbox(); } } private void UserNameBox_LostFocus(object sender, RoutedEventArgs e) { if (UserNameBox.Text != "") { usermanager.UserName = UserNameBox.Text; readtextbox(); } } private void PassWordBox_LostFocus(object sender, RoutedEventArgs e) { if(PassWordBox.Password!="") { usermanager.UserPassWord = PassWordBox.Password; readtextbox(); } } private void SavedSwitch_Toggled(object sender, RoutedEventArgs e) { if(flag) { usermanager.PWDSaved = SavedSwitch.IsOn; readtextbox(); } } private async void Button_Click_1(object sender, RoutedEventArgs e) { ConnectionProfile connectionProfile = NetworkInformation.GetInternetConnectionProfile(); if (connectionProfile == null || connectionProfile.ProfileName != "DLUT") { MessageDialog message = new MessageDialog("未连接到DLUT!"); await message.ShowAsync(); return; } usermanager.LoginOut(); } } }
using System; namespace XamFormLogin.Data { public interface ISQLite { } }
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.Extensions.Caching.Memory; using PointOfSalesV2.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace PointOfSalesV2.Api.Security { public class ActionAuthorize : TypeFilterAttribute { public ActionAuthorize(string operation) : base(typeof(ActionRequirementFilter)) { Arguments = new object[] { operation }; } } public class ActionRequirementFilter : IAuthorizationFilter { readonly string _operation; readonly IHttpContextAccessor _httpContextAccessor; readonly IMemoryCache _cache; public ActionRequirementFilter(string operation, IHttpContextAccessor httpContextAccessor, IMemoryCache cache) { _operation = operation; _httpContextAccessor = httpContextAccessor; _cache = cache; } public void OnAuthorization(AuthorizationFilterContext context) { bool isInvalid = false; var currentToken = _httpContextAccessor.HttpContext.Request.Headers.FirstOrDefault(x => x.Key == "Authorization").Value.ToString(); var currentPath = _httpContextAccessor.HttpContext.Request.Path.ToString().Split("/").ToList(); int index = currentPath.IndexOf("api") + 1; string currentController = currentPath[index]; if (string.IsNullOrEmpty(currentToken) || string.IsNullOrEmpty(currentController) || !currentToken.Contains("Bearer")) isInvalid = true; if (!isInvalid) { string token = currentToken.Split(" ").LastOrDefault(); User user = _cache.Get<User>(token); if (user == null) context.Result = new ForbidResult(); else { var operations = user.Permissions.Where(r => r.SectionName.ToLower()==currentController.ToLower() && r.OperationName.ToLower()==_operation.ToLower()); if (user.Permissions.Count() > 0 && operations==null) context.Result = new ForbidResult(); } } else context.Result = new ForbidResult(); } } }
namespace RestaurantManager.Interfaces { using RestaurantManager.Models; public interface IMainCourse : IMeal { MainCourseType Type { get; } } }
using System; namespace CallCenter.Common.DataContracts { public class OperatorChatMessage : IOperatorChatMessage { public int Id { get; set; } public DateTime Date { get; set; } public string Message { get; set; } public ChatMessageType MessageType { get; set; } } }
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 BLL_DAL; namespace QLNHAHANG { public partial class frmLogin : Form { Login_BLL_DAL login = new Login_BLL_DAL(); public frmLogin() { InitializeComponent(); txtPassword.PasswordChar = '\u2022'; CenterToScreen(); btnHidePass.Image = Image.FromFile("../../img/icon/hidden.png"); } private void btnLogIn_Click(object sender, EventArgs e) { if (txtUsername.TextLength <= 0) { MessageBox.Show(grbTenDangNhap.Text + " không được bỏ trống!"); txtUsername.Focus(); } else if (txtPassword.TextLength <= 0) { MessageBox.Show(grbMatKhau.Text + " không được bỏ trống!"); txtPassword.Focus(); } else { string user = txtUsername.Text.Trim(); string pass = txtPassword.Text.Trim(); int kt = login.ktTaiKhoan(user, pass); if (kt == -1) { MessageBox.Show("Tài khoản không tồn tại"); return; } else if (kt == 0) { MessageBox.Show("Mật khẩu không chính xác"); return; } else { DialogResult result; result = MessageBox.Show("Đăng nhập thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1); if (result == DialogResult.OK) { NHANVIEN nd = login.layND(user); this.Visible = false; TrangChu frm = new TrangChu(); frm.WindowState = FormWindowState.Maximized; frm.DangNhapNV(nd); frm.Show(); } } } } private void btnHidePass_Click(object sender, EventArgs e) { txtPassword.PasswordChar = '\u2022'; btnHidePass.Visible = false; btnShowPass.Visible = true; } private void btnShowPass_Click(object sender, EventArgs e) { txtPassword.PasswordChar = (char)0; btnHidePass.Visible = true; btnShowPass.Visible = false; } private void guna2ControlBox1_Click(object sender, EventArgs e) { } private void txtUsername_TextChanged(object sender, EventArgs e) { } private void grbTenDangNhap_Enter(object sender, EventArgs e) { } private void txtPassword_TextChanged(object sender, EventArgs e) { } private void grbMatKhau_Enter(object sender, EventArgs e) { } private void gunaCirclePictureBox1_Click(object sender, EventArgs e) { } } }
namespace Common.Function { using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; public class Md5 { private const string salt = "81fbaa81762885ac3481fd4b416485e6"; public static string GetEncryptionValue(string value) { MD5CryptoServiceProvider m = new MD5CryptoServiceProvider(); byte[] MD5Source = System.Text.Encoding.UTF8.GetBytes(value+salt); byte[] MD5Out = m.ComputeHash(MD5Source); return Convert.ToBase64String(MD5Out); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; using Ornithology.Entity; using Ornithology.Data; using Ornithology.Domain; namespace Ornithology.Services { public class AveServices : IAveServices { private IAveRepository _aveRepository; private IAveDomain _aveDomain; public AveServices(IAveRepository aveRepository, IAveDomain aveDomain) { _aveRepository = aveRepository; _aveDomain = aveDomain; } public async Task<Ave> FindAsync(string codigoAve) { return await _aveRepository.GetFirstAsync(x=>x.Codigo == codigoAve); } public async Task<List<Ave>> ListarAsync() { return await _aveRepository.GetAllAsync(); } public async Task<List<Ave>> ListarAsyncFilteredAsNoTracking(Expression<Func<Ave, bool>> filter, params string[] include) { return await _aveRepository.GetFilteredAsyncAsNoTracking(filter, include); } public async Task<List<Ave>> ListarAsyncAsNoTracking() { return await _aveRepository.GetFilteredAsyncAsNoTracking(); } public async Task<RespuestaApi> CrearAve(Ave ave) { var respuesta = new RespuestaApi(); var mensajes = new List<string>(); bool aveValida = _aveDomain.Validar(ave, ref mensajes); Ave aveExistente = await ValidarAveExistente(ave, mensajes); if (aveValida && mensajes.Count == 0) { if (aveExistente == null) { _aveRepository.Add(ave); } else { foreach (AvePais avepais in ave.AvesPais) { aveExistente.AvesPais.Add(avepais); } _aveRepository.Modify(aveExistente); } int resultado = await _aveRepository.UnitOfWork.CommitAsync(); } else { respuesta = new RespuestaApi { Mensajes = mensajes }; } respuesta.Mensajes = mensajes; return respuesta; } private async Task<Ave> ValidarAveExistente(Ave ave, List<string> mensajes) { var aveExistente = await _aveRepository.GetFirstAsync(item => item.Codigo == ave.Codigo); if (aveExistente != null) { bool aveYaEstaEnPais = aveExistente.AvesPais.Select(x => x.CodigoPais) .Intersect(ave.AvesPais.Select(y => y.CodigoPais)) .Any(); if (aveYaEstaEnPais) { mensajes.Add($"Ya existe una ave con el código {aveExistente.Codigo} en el país seleccionado"); } } return aveExistente; } public async Task<RespuestaApi> ModificarAve(Ave ave) { var respuesta = new RespuestaApi(); var mensajes = new List<string>(); bool aveValida = _aveDomain.Validar(ave, ref mensajes); if (aveValida && mensajes.Count == 0) { //foreach (AvePais avepais in ave.AvesPais) //{ // ave.AvesPais.Add(avepais); //} _aveRepository.Modify(ave); int resultado = await _aveRepository.UnitOfWork.CommitAsync(); } else { respuesta = new RespuestaApi { Mensajes = mensajes }; } respuesta.Mensajes = mensajes; return respuesta; } public async Task<RespuestaApi> EliminarAve(string codigoAve) { var respuesta = new RespuestaApi(); var mensajes = new List<string>(); Ave ave = await _aveRepository .GetFirstAsync(item => item.Codigo == codigoAve); bool aveValida = ave != null; if (aveValida) { _aveRepository.DeleteCascade(ave.Codigo); int resultado = await _aveRepository.UnitOfWork.CommitAsync(); } else { respuesta = new RespuestaApi { Mensajes = mensajes }; } respuesta.Mensajes = mensajes; return respuesta; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Webcorp.unite { public partial class ElectricConductance { /// <summary> /// Implements the operator /. /// </summary> /// <param name="c"> The conductance. </param> /// <param name="l"> The length. </param> /// <returns> The result of the operator. </returns> public static ElectricConductivity operator /(ElectricConductance c, Length l) { return new ElectricConductivity(c.Value / l.Value); } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Microsoft.WindowsAzure; using Microsoft.WindowsAzure.StorageClient; using RecipeWebRole.Models; namespace RecipeWebRole.DataAccess { public class BlobStorageImageRepository : IImageRepository { private const string BlobContainer = "imagecontainer"; // must be lowercase!!! public IList<int> GetImageIds() { CloudBlobContainer container = GetBlobContainer(); // Loop over blobs within the container and output the URI to each of them var ids = new List<string>(); foreach (IListBlobItem blobItem in container.ListBlobs()) { ids.Add(blobItem.Uri.Segments.Last()); } return ids.Select(Int32.Parse).ToList(); } public Image GetImage(int id) { // Retrieve reference to blob. CloudBlobContainer container = GetBlobContainer(); string blobId = id.ToString(CultureInfo.InvariantCulture); CloudBlob blob = container.GetBlobReference(blobId); // get data (if it exists) try { byte[] data = blob.DownloadByteArray(); return new Image() { Id = id, Data = data}; } catch (Exception) { return null; } } public void SetImage(Image image) { if (image.Id <= 0) { image.Id = CreateUniqueId(); } // Retrieve reference to blob. CloudBlobContainer container = GetBlobContainer(); string blobId = image.Id.ToString(CultureInfo.InvariantCulture); CloudBlob blob = container.GetBlobReference(blobId); // Uplaod recipe blob.UploadByteArray(image.Data); } private int CreateUniqueId() { // TODO: do this differently // (see for example http://blog.tatham.oddie.com.au/2011/07/14/released-snowmaker-a-unique-id-generator-for-azure-or-any-other-cloud-hosting-environment/ var random = new Random(); IList<int> recipeIds = GetImageIds(); int maxNumberOfTrials = 100; while (maxNumberOfTrials-- > 0) { int testId = random.Next(0, 100000); if (!recipeIds.Contains(testId)) { return testId; } } throw new InvalidOperationException("Unable to create unique ID."); } private CloudBlobContainer GetBlobContainer() { CloudBlobClient blobClient = GetCloudBlobClient(); CloudBlobContainer container = blobClient.GetContainerReference(BlobContainer); container.CreateIfNotExist(); container.SetPermissions(new BlobContainerPermissions {PublicAccess = BlobContainerPublicAccessType.Blob}); return container; } private CloudBlobClient GetCloudBlobClient() { // Retrieve storage account from connection-string string setting = CloudConfigurationManager.GetSetting("StorageConnectionString"); System.Diagnostics.Debug.WriteLine(setting); //CloudStorageAccount storageAccount = CloudStorageAccount.DevelopmentStorageAccount; CloudStorageAccount storageAccount = CloudStorageAccount.Parse( CloudConfigurationManager.GetSetting("StorageConnectionString")); // Create the blob client CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); return blobClient; } } }
using UnityEngine; using System.Collections; public class Edge { public Hex destination; public Hex source; private int[] cost = new int[3]; // The cost of traversing this edge. Some hexes are slower to move through (Swamps). // Units don't allow enemy units to traverse next to the unit (area of control). public Edge(Hex destination_hex, Hex source_hex, int movementCost) { destination = destination_hex; source = source_hex; cost[0] = movementCost; cost[1] = movementCost; cost[2] = movementCost; } // Units don't allow enemies to traverse next to this unit public int GetCost(Faction faction) { return cost[faction.faction_ID]; } // Unit moved to a hex adjacent to this edge. Increase the cost of this edge for enemy units to traverse public void SetZoneOfControl(Faction faction) { if (faction.faction_ID == 1) cost[2] = 5; else if (faction.faction_ID == 2) cost[1] = 5; } public void ResetCost() { cost[1] = cost[0]; // Cost[0] is the base cost that never changes. The other costs change based on other units around the hex exerting zone of control. cost[2] = cost[0]; } }
using System; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; namespace dailyBurnWP7 { public partial class dailyBurnProgressBar : UserControl { private int maxCalories = 3000; private int caloriesEaten = 0; private int calorieGoalLowerBound = 2000; private int calorieGoalUpperBound = 2500; public dailyBurnProgressBar() { // Required to initialize variables InitializeComponent(); } public int CaloriesEaten { get { return caloriesEaten;} set { if (value >= MaxCalories) { MaxCalories = value; } caloriesEaten = value; setProgressRatio(); } } public int MaxCalories { get { return (maxCalories); } set { if (value < CaloriesEaten) maxCalories = CaloriesEaten; else maxCalories = value; setCalorieBounds(); setProgressRatio(); setTickMarks(); } } private void setTickMarks() { int interval = MaxCalories / 5; txtFirstMark.Text = interval.ToString(); txtSecondMark.Text = (2 * interval).ToString(); txtThirdMark.Text = (3 * interval).ToString(); txtFourthMark.Text = (4 * interval).ToString(); txtFifthMark.Text = MaxCalories.ToString(); } public int CalorieGoalLowerBound { get { return (calorieGoalLowerBound); } set { if (value >= CalorieGoalUpperBound) calorieGoalLowerBound = CalorieGoalUpperBound - 200; else calorieGoalLowerBound = value; setCalorieBounds(); } } public int CalorieGoalUpperBound { get { return (calorieGoalUpperBound); } set { if (value <= CalorieGoalLowerBound) calorieGoalUpperBound = CalorieGoalLowerBound + 200; else calorieGoalUpperBound = value; } } private void setProgressRatio() { double progressRatio = (double)CaloriesEaten / MaxCalories; progressGrid.ColumnDefinitions[0].Width = new GridLength(progressRatio, GridUnitType.Star); progressGrid.ColumnDefinitions[1].Width = new GridLength(1 - progressRatio, GridUnitType.Star); } private void setCalorieBounds() { double upBoundRatio = (double)(CalorieGoalUpperBound - CalorieGoalLowerBound) / MaxCalories; double lowBoundRatio = (double)CalorieGoalLowerBound / MaxCalories; targetGrid.ColumnDefinitions[0].Width = new GridLength(lowBoundRatio, GridUnitType.Star); targetGrid.ColumnDefinitions[1].Width = new GridLength(upBoundRatio, GridUnitType.Star); //targetGrid.ColumnDefinitions[2].Width = new GridLength(1 - (lowBoundRatio + upBoundRatio), GridUnitType.Star); } } }
using System; namespace NetBattle.Field.Events { public class CounterAcknowledgeEvent : FieldEvent { // TODO add event data public CounterAcknowledgeEvent(string targetOwner) : base(targetOwner) { } public CounterAcknowledgeEvent(Guid target) : base(target) { } public CounterAcknowledgeEvent(string targetOwner, Guid source) : base(targetOwner, source) { } public CounterAcknowledgeEvent(Guid target, Guid source) : base(target, source) { } } }
using Cotizaciones_Edwin_Marte.Registros; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; namespace Cotizaciones_Edwin_Marte.Entidades { public class Cotizaciones { [Key] public int CotizacionesId { get; set; } public string Fecha { get; set; } public string Comentario { get; set; } public decimal Total { get; set; } public virtual List<CotizacionDetalle> CotDetalle { get; set; } public Cotizaciones() { CotizacionesId = 0; Fecha = " "; Comentario = " "; Total = 0; CotDetalle = new List<CotizacionDetalle>(); } public Cotizaciones(int CotizacionesId, string Fecha, string Comentario, decimal Total, List<CotizacionDetalle> CotDetalle) { this.CotizacionesId = CotizacionesId; this.Fecha = Fecha; this.Comentario = Comentario; this.Total = Total; this.CotDetalle = CotDetalle; } } }
namespace ns9 { using System; internal class Exception1 : ApplicationException { public Exception1() : base("Invalid Parameter") { } } }
using System; using System.Reflection; using Nabbix.Items; namespace Nabbix { public class Item { public const string NotSupported = "ZBX_NOTSUPPORTED"; private readonly PropertyInfo _property; private readonly NabbixItemAttribute _attribute; private readonly object _instance; public Item(PropertyInfo property, NabbixItemAttribute attribute, object instance) { if (property == null) throw new ArgumentNullException(nameof(property)); if (attribute == null) throw new ArgumentNullException(nameof(attribute)); if (instance == null) throw new ArgumentNullException(nameof(instance)); _property = property; _attribute = attribute; _instance = instance; } public string GetValue(string key) { return _attribute.GetValue(key, _instance, _property); } } }
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace RastreioFacil.Web.Models { public class VeiculoModels { public string IMEI { get; set; } public int? id_cliente { get; set; } public int? id_marca { get; set; } public int? id_rastreador { get; set; } public int? id_status { get; set; } public string ds_placa { get; set; } public string ds_modelo { get; set; } public int? nm_ano { get; set; } public int? nm_modelo { get; set; } public string nm_telefonico { get; set; } [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] public List<DadosVeiculoModels> DadosVeiculo { get; set; } //public DateTime? dt_pagamento { get; set; } //public DateTime? dt_vencimento { get; set; } public bool? avisoBloqueio { get; set; } public bool? comandoBloqueo { get; set; } public bool? bloqueado { get; set; } //public bool? comandoTempo { get; set; } //public string tempoIgnicaoON { get; set; } //public string tempoIgnicaoOFF { get; set; } //public int? cd_user_cadm { get; set; } //public DateTime? ts_user_cadm { get; set; } //public int? cd_user_manu { get; set; } //public DateTime? ts_user_manu { get; set; } } }
using System; using System.Collections.Generic; namespace Domain.Entities { public class Home : EntityBase { public string Name { get; set; } public string Address { get; set; } public string City { get; set; } public string Country { get; set; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace transGraph { public partial class addWay : Form { dbFacade db = new dbFacade(); public addWay() { InitializeComponent(); DataTable data = db.FetchAllSql("SELECT title FROM regs"); foreach (DataRow rr in data.Rows) { comboBox1.Items.Add(rr[0]); } } private void button2_Click(object sender, EventArgs e) { this.Close(); } private void button1_Click(object sender, EventArgs e) { string reg = ""; try { DataTable data = db.FetchAllSql("SELECT id FROM `regs` WHERE title = '" + this.comboBox1.SelectedItem.ToString() + "'"); reg = data.Rows[0][0].ToString(); } catch (Exception) { } try { db.FetchAllSql("INSERT INTO `ways` (`title`,`reg`) VALUES ('" + Convert.ToString(this.textBox1.Text) + "','" + reg + "')"); this.Close(); } catch (Exception) { MessageBox.Show("Ошибка при записи БД! Неверные значения!"); } } } }
using Microsoft.AspNetCore.Http; using System.Threading.Tasks; namespace AspNetCore.Api.TenantResolver { public class RequestPathBasedTenantResolutionStrategy : ITenantResolutionStrategy { private readonly IHttpContextAccessor _httpContextAccessor; public RequestPathBasedTenantResolutionStrategy(IHttpContextAccessor httpContextAccessor) { _httpContextAccessor = httpContextAccessor; } public Task<string> GetTenantIdentifierAsync() { //TODO:_httpContextAccessor.HttpContext.Request.Path.Value return Task.FromResult(string.Empty); } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="IFileImporter.cs" company="CGI"> // Copyright (c) CGI. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using NHibernate; namespace CGI.Reflex.Core.Importers { internal interface IFileImporter { string TechnicalName { get; } string DisplayName { get; } int Priority { get; } FileImporterResult GetTemplate(ISession session); FileImporterResult Export(ISession session); IEnumerable<ImportOperationLineResult> Import(ISession session, Stream inputStream); } }
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; using System.Web; namespace Services.Interface { public interface IClientNewshoreService { /// <summary> /// Metodo encargado de grabar los archivos /// que contienen las listas de letras com las listar de /// clientes /// </summary> /// <param name="request">rquest http</param> /// <param name="fileNameContent">nombre del archivo a esperar para contenido</param> /// <param name="fileNameRegister">nombre del archivo a esperar para los registros</param> /// <param name="pathBase">ruta local donde se almacenaran los recursos</param> /// <returns>retorna si fue capaz de grabar los archivos necesarios o no </returns> bool UploadClientsWeb(HttpRequest request, string fileNameContent, string fileNameRegister,string pathBase); /// <summary> /// Metodo encargado de obtener el archivo de resultados /// </summary> /// <param name="request"></param> /// <returns></returns> HttpResponseMessage GetFileResult(string fileNameContent, string fileNameRegister, string pathResult, string pathBase); } }
using System; using UnityEngine; namespace LeoESCTest.UnityComponents { public class GameStateComponent : MonoBehaviour { private GameState _currentState; public event Action<GameState> StateChangedEvent; public GameState CurrentState { get => _currentState; set { _currentState = value; StateChangedEvent?.Invoke(_currentState); } } public float StartTime; private void Start() { StartTime = Time.time; } } }
/******************************************************************** * FulcrumWeb RAD Framework - Fulcrum of your business * * Copyright (c) 2002-2010 FulcrumWeb, ALL RIGHTS RESERVED * * * * THE SOURCE CODE CONTAINED WITHIN THIS FILE AND ALL RELATED * * FILES OR ANY PORTION OF ITS CONTENTS SHALL AT NO TIME BE * * COPIED, TRANSFERRED, SOLD, DISTRIBUTED, OR OTHERWISE MADE * * AVAILABLE TO OTHER INDIVIDUALS WITHOUT EXPRESS WRITTEN CONSENT * * AND PERMISSION FROM FULCRUMWEB. CONSULT THE END USER LICENSE * * AGREEMENT FOR INFORMATION ON ADDITIONAL RESTRICTIONS. * ********************************************************************/ using System.Collections; using System.Collections.Generic; using System.Xml; using Framework.Utils; namespace Framework.Metadata { /// <summary> /// Child collection of tabs for portal page. /// </summary> public class CxTabsCollection { //------------------------------------------------------------------------- protected CxPageMetadata m_Page = null; protected List<CxTabMetadata> m_TabList = new List<CxTabMetadata>(); protected Hashtable m_TabMap = new Hashtable(); //------------------------------------------------------------------------- //------------------------------------------------------------------------- /// <summary> /// Constructor /// </summary> /// <param name="page">parent portal page</param> public CxTabsCollection(CxPageMetadata page) { m_Page = page; } //------------------------------------------------------------------------- /// <summary> /// Constructor /// </summary> /// <param name="page">parent portal page</param> /// <param name="element">XML element to load tabs from</param> public CxTabsCollection(CxPageMetadata page, XmlElement element) : this(page) { AddFrom(element); } //------------------------------------------------------------------------- /// <summary> /// Adds tab to tabs collection. /// </summary> /// <param name="tab">tab object to add</param> public void Add(CxTabMetadata tab) { m_TabList.Add(tab); m_TabMap.Add(tab.Id, tab); } //------------------------------------------------------------------------- /// <summary> /// Appends tab collection with items loaded from the given XML element. /// </summary> /// <param name="element">XML element to load tabs from</param> public void AddFrom(XmlElement element) { foreach (XmlElement tabElement in element.SelectNodes("tab")) { CxTabMetadata tab = new CxTabMetadata(Page.Holder, tabElement, Page); Add(tab); } } //------------------------------------------------------------------------- /// <summary> /// Returns tab with the specified ID. /// </summary> /// <param name="id">ID of the tab</param> /// <returns>found tab or null</returns> public CxTabMetadata Find(string id) { return CxUtils.NotEmpty(id) ? (CxTabMetadata) m_TabMap[id.ToUpper()] : null; } //------------------------------------------------------------------------- //------------------------------------------------------------------------- /// <summary> /// Returns tab object by its index. /// </summary> public CxTabMetadata this[int index] { get { return m_TabList[index]; } } //------------------------------------------------------------------------- /// <summary> /// Returns count of tabs in the collection. /// </summary> public int Count { get { return m_TabList.Count; } } //------------------------------------------------------------------------- /// <summary> /// Returns parent tab page. /// </summary> public CxPageMetadata Page { get {return m_Page;} } //------------------------------------------------------------------------- /// <summary> /// Retruns list of tabs. /// </summary> public IList<CxTabMetadata> Items { get { return m_TabList; } } //------------------------------------------------------------------------- } }
namespace OmniSharp.Extensions.LanguageServer.Protocol.Models { public interface ITextDocumentIdentifierParams { TextDocumentIdentifier TextDocument { get; } } }
using Microsoft.EntityFrameworkCore; using Publicon.Core.DAL; using Publicon.Core.Entities.Abstract; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Publicon.Core.Repositories.Concrete { internal class GenericDeleteAbleRepository<T> : GenericRepository<T> where T : DeleteAble { public GenericDeleteAbleRepository(PubliconContext context) : base(context) { } public override async Task<bool> ExistAsync(Guid id) { if (id == Guid.Empty) throw new ArgumentNullException(nameof(id)); return await _dbSet.AnyAsync(e => e.Id == id && !e.DeletedAt.HasValue); } public override async Task<T> GetByIdAsync(Guid id) { if (id == Guid.Empty) throw new ArgumentNullException(nameof(id)); var entity = await _dbSet.FindAsync(id); return (entity == null || entity.DeletedAt.HasValue) ? null : entity; } public override async Task<IEnumerable<T>> GetEntitiesAsync() => await _dbSet.Where(e => !e.DeletedAt.HasValue).ToListAsync(); public override async Task<IEnumerable<T>> GetEntitiesAsync(IEnumerable<Guid> entityIds) { if (entityIds == null) throw new ArgumentNullException(nameof(entityIds)); var entities = await _dbSet .Where(e => entityIds.Contains(e.Id) && !e.DeletedAt.HasValue) .ToListAsync(); return entities; } } }
using Microsoft.EntityFrameworkCore.Migrations; namespace dotNetRogueLootAPI.Persistence.Migrations { public partial class newMigrations : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "Effects", columns: table => new { EffectName = table.Column<string>(type: "nvarchar(450)", nullable: false), WeaponNameFix = table.Column<string>(type: "nvarchar(450)", nullable: true), BonusDamage = table.Column<int>(type: "int", nullable: false), BonusHealing = table.Column<int>(type: "int", nullable: false), ExtraHits = table.Column<int>(type: "int", nullable: false) }, constraints: table => { table.PrimaryKey("PK_Effects", x => x.EffectName); }); migrationBuilder.CreateTable( name: "WeaponRarities", columns: table => new { RarityName = table.Column<string>(type: "nvarchar(450)", nullable: false), AppearChance = table.Column<int>(type: "int", nullable: false), StatModMul = table.Column<double>(type: "float", nullable: false), AmountOfEffects = table.Column<int>(type: "int", nullable: false) }, constraints: table => { table.PrimaryKey("PK_WeaponRarities", x => x.RarityName); }); migrationBuilder.CreateTable( name: "WeaponTypes", columns: table => new { Name = table.Column<string>(type: "nvarchar(450)", nullable: false), Damage = table.Column<int>(type: "int", nullable: false), DodgeChance = table.Column<int>(type: "int", nullable: false) }, constraints: table => { table.PrimaryKey("PK_WeaponTypes", x => x.Name); }); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "Effects"); migrationBuilder.DropTable( name: "WeaponRarities"); migrationBuilder.DropTable( name: "WeaponTypes"); } } }
using PDV.DAO.Custom; using PDV.DAO.DB.Controller; using PDV.DAO.Entidades; using PDV.DAO.Enum; using System; using System.Collections.Generic; using System.Data; namespace PDV.CONTROLER.Funcoes { public class FuncoesUF { public static bool Existe(decimal IDUnidadeFederativa) { using (SQLQuery oSQL = new SQLQuery()) { oSQL.SQL = "SELECT 1 FROM UNIDADEFEDERATIVA WHERE IDUNIDADEFEDERATIVA = @IDUNIDADEFEDERATIVA"; oSQL.ParamByName["IDUNIDADEFEDERATIVA"] = IDUnidadeFederativa; oSQL.Open(); return !oSQL.IsEmpty; } } public static UnidadeFederativa GetUnidadeFederativa(decimal IDUnidadeFederativa) { using (SQLQuery oSQL = new SQLQuery()) { oSQL.SQL = @"SELECT UNIDADEFEDERATIVA.* FROM UNIDADEFEDERATIVA INNER JOIN PAIS ON(UNIDADEFEDERATIVA.IDPAIS = PAIS.IDPAIS) WHERE UNIDADEFEDERATIVA.IDUNIDADEFEDERATIVA = @IDUNIDADEFEDERATIVA"; oSQL.ParamByName["IDUNIDADEFEDERATIVA"] = IDUnidadeFederativa; oSQL.Open(); if (oSQL.IsEmpty) return null; return EntityUtil<UnidadeFederativa>.ParseDataRow(oSQL.dtDados.Rows[0]); } } public static UnidadeFederativa GetUnidadeFederativa(string sigla) { using (SQLQuery oSQL = new SQLQuery()) { oSQL.SQL = @"SELECT UNIDADEFEDERATIVA.* FROM UNIDADEFEDERATIVA INNER JOIN PAIS ON(UNIDADEFEDERATIVA.IDPAIS = PAIS.IDPAIS) WHERE UNIDADEFEDERATIVA.SIGLA = @SIGLA"; oSQL.ParamByName["SIGLA"] = sigla; oSQL.Open(); if (oSQL.IsEmpty) return null; return EntityUtil<UnidadeFederativa>.ParseDataRow(oSQL.dtDados.Rows[0]); } } public static UnidadeFederativa GetUnidadeFederativaPorSigla(string Sigla) { using (SQLQuery oSQL = new SQLQuery()) { oSQL.SQL = @"SELECT UNIDADEFEDERATIVA.* FROM UNIDADEFEDERATIVA INNER JOIN PAIS ON(UNIDADEFEDERATIVA.IDPAIS = PAIS.IDPAIS) WHERE UPPER(UNIDADEFEDERATIVA.SIGLA) = @SIGLA"; oSQL.ParamByName["SIGLA"] = Sigla.ToUpper(); oSQL.Open(); if (oSQL.IsEmpty) return null; return EntityUtil<UnidadeFederativa>.ParseDataRow(oSQL.dtDados.Rows[0]); } } public static List<UnidadeFederativa> GetUnidadeFederativaPorCodigoPais(string CodigoPais) { using (SQLQuery oSQL = new SQLQuery()) { oSQL.SQL = @"SELECT UNIDADEFEDERATIVA.IDUNIDADEFEDERATIVA, UNIDADEFEDERATIVA.DESCRICAO, UNIDADEFEDERATIVA.SIGLA, PAIS.IDPAIS, PAIS.DESCRICAO AS PAIS FROM UNIDADEFEDERATIVA INNER JOIN PAIS ON(UNIDADEFEDERATIVA.IDPAIS = PAIS.IDPAIS) WHERE PAIS.CODIGO = @CODIGO"; oSQL.ParamByName["CODIGO"] = CodigoPais; oSQL.Open(); if (oSQL.IsEmpty) return null; return new DataTableParser<UnidadeFederativa>().ParseDataTable(oSQL.dtDados); } } public static DataTable GetUnidadesFederativa(string Sigla, string Descricao) { using (SQLQuery oSQL = new SQLQuery()) { List<string> Filtros = new List<string>(); if (!string.IsNullOrEmpty(Sigla)) Filtros.Add(string.Format("(UPPER(UNIDADEFEDERATIVA.SIGLA) LIKE UPPER('%{0}%'))", Sigla)); if (!string.IsNullOrEmpty(Descricao)) Filtros.Add(string.Format("(UPPER(UNIDADEFEDERATIVA.DESCRICAO) LIKE UPPER('%{0}%'))", Descricao)); oSQL.SQL = string.Format( @"SELECT UNIDADEFEDERATIVA.IDUNIDADEFEDERATIVA, UNIDADEFEDERATIVA.DESCRICAO AS UNIDADEFEDERATIVA, UNIDADEFEDERATIVA.SIGLA, PAIS.IDPAIS, PAIS.DESCRICAO AS PAIS FROM UNIDADEFEDERATIVA INNER JOIN PAIS ON (UNIDADEFEDERATIVA.IDPAIS = PAIS.IDPAIS) {0} ORDER BY UNIDADEFEDERATIVA.DESCRICAO, PAIS.DESCRICAO", Filtros.Count > 0 ? "WHERE " + string.Join(" AND ", Filtros.ToArray()) : string.Empty); oSQL.Open(); return oSQL.dtDados; } } public static bool Remover(decimal IDUnidadeFederativa) { using (SQLQuery oSQL = new SQLQuery()) { oSQL.SQL = "SELECT 1 FROM MUNICIPIO WHERE IDUNIDADEFEDERATIVA = @IDUNIDADEFEDERATIVA"; oSQL.ParamByName["IDUNIDADEFEDERATIVA"] = IDUnidadeFederativa; oSQL.Open(); if (!oSQL.IsEmpty) throw new Exception("A Unidade Federativa tem vinculo com município e não pode ser removida."); oSQL.ClearAll(); oSQL.SQL = @"SELECT 1 FROM ENDERECO WHERE IDUNIDADEFEDERATIVA = @IDUNIDADEFEDERATIVA"; oSQL.ParamByName["IDUNIDADEFEDERATIVA"] = IDUnidadeFederativa; oSQL.Open(); if (!oSQL.IsEmpty) throw new Exception("A Unidade Federativa tem vinculo com Endereço e não pode ser remvido."); oSQL.ClearAll(); oSQL.SQL = @"DELETE FROM UNIDADEFEDERATIVA WHERE IDUNIDADEFEDERATIVA = @IDUNIDADEFEDERATIVA"; oSQL.ParamByName["IDUNIDADEFEDERATIVA"] = IDUnidadeFederativa; return oSQL.ExecSQL() == 1; } } public static bool Salvar(UnidadeFederativa UF, TipoOperacao Op) { using (SQLQuery oSQL = new SQLQuery()) { switch (Op) { case TipoOperacao.INSERT: oSQL.SQL = @"INSERT INTO UNIDADEFEDERATIVA (IDUNIDADEFEDERATIVA, SIGLA, DESCRICAO, IDPAIS, ALIQUOTAINTER, ALIQUOTAINTRA, FCP) VALUES (@IDUNIDADEFEDERATIVA, @SIGLA, @DESCRICAO, @IDPAIS, @ALIQUOTAINTER, @ALIQUOTAINTRA, @FCP)"; break; case TipoOperacao.UPDATE: oSQL.SQL = @"UPDATE UNIDADEFEDERATIVA SET SIGLA = @SIGLA, DESCRICAO = @DESCRICAO, IDPAIS = @IDPAIS, ALIQUOTAINTER = @ALIQUOTAINTER, ALIQUOTAINTRA = @ALIQUOTAINTRA, FCP = @FCP WHERE IDUNIDADEFEDERATIVA = @IDUNIDADEFEDERATIVA"; break; } oSQL.ParamByName["IDUNIDADEFEDERATIVA"] = UF.IDUnidadeFederativa; oSQL.ParamByName["IDPAIS"] = UF.IDPais; oSQL.ParamByName["DESCRICAO"] = UF.Descricao; oSQL.ParamByName["SIGLA"] = UF.Sigla; oSQL.ParamByName["ALIQUOTAINTER"] = UF.AliquotaInter; oSQL.ParamByName["ALIQUOTAINTRA"] = UF.AliquotaIntra; oSQL.ParamByName["FCP"] = UF.FCP; return oSQL.ExecSQL() == 1; } } public static List<UnidadeFederativa> GetUnidadesFederativa(decimal IDPais) { using (SQLQuery oSQL = new SQLQuery()) { oSQL.SQL = @"SELECT IDUNIDADEFEDERATIVA, IDPAIS, SIGLA, DESCRICAO FROM UNIDADEFEDERATIVA WHERE IDPAIS = @IDPAIS"; oSQL.ParamByName["IDPAIS"] = IDPais; oSQL.Open(); return new DataTableParser<UnidadeFederativa>().ParseDataTable(oSQL.dtDados); } } public static List<UnidadeFederativa> GetUnidadesFederativa() { using (SQLQuery oSQL = new SQLQuery()) { oSQL.SQL = @"SELECT UNIDADEFEDERATIVA.IDUNIDADEFEDERATIVA, UNIDADEFEDERATIVA.IDPAIS, UNIDADEFEDERATIVA.SIGLA, UNIDADEFEDERATIVA.DESCRICAO FROM UNIDADEFEDERATIVA INNER JOIN PAIS ON (UNIDADEFEDERATIVA.IDPAIS = PAIS.IDPAIS) ORDER BY UNIDADEFEDERATIVA.SIGLA"; oSQL.Open(); return new DataTableParser<UnidadeFederativa>().ParseDataTable(oSQL.dtDados); } } public static List<UnidadeFederativa> GetUnidadesFederativaNFe() { using (SQLQuery oSQL = new SQLQuery()) { oSQL.SQL = @"SELECT UNIDADEFEDERATIVA.IDUNIDADEFEDERATIVA, UNIDADEFEDERATIVA.SIGLA FROM UNIDADEFEDERATIVA INNER JOIN PAIS ON (UNIDADEFEDERATIVA.IDPAIS = PAIS.IDPAIS) ORDER BY UNIDADEFEDERATIVA.SIGLA"; oSQL.Open(); return new DataTableParser<UnidadeFederativa>().ParseDataTable(oSQL.dtDados); } } public static DataTable GetUnidadesFederativaComAliquotasICMS() { using (SQLQuery oSQL = new SQLQuery()) { oSQL.SQL = @"SELECT IDUNIDADEFEDERATIVA, IDPAIS, SIGLA, COALESCE(ALIQUOTAINTER, 0) AS ALIQUOTAINTER, COALESCE(ALIQUOTAINTRA, 0) AS ALIQUOTAINTRA, COALESCE(FCP, 0) AS FCP FROM UNIDADEFEDERATIVA"; oSQL.Open(); return oSQL.dtDados; } } public static UnidadeFederativa GetUnidadesFederativaComAliquotasICMS(decimal IDEmitente) { using (SQLQuery oSQL = new SQLQuery()) { oSQL.SQL = @"SELECT UNIDADEFEDERATIVA.IDUNIDADEFEDERATIVA, UNIDADEFEDERATIVA.IDPAIS, UNIDADEFEDERATIVA.SIGLA, COALESCE(ALIQUOTAINTER, 0) AS ALIQUOTAINTER, COALESCE(ALIQUOTAINTRA, 0) AS ALIQUOTAINTRA, COALESCE(FCP, 0) AS FCP FROM UNIDADEFEDERATIVA INNER JOIN ENDERECO ON (UNIDADEFEDERATIVA.IDUNIDADEFEDERATIVA = ENDERECO.IDUNIDADEFEDERATIVA) INNER JOIN EMITENTE ON (EMITENTE.IDENDERECO = ENDERECO.IDENDERECO) WHERE EMITENTE.IDEMITENTE = @IDEMITENTE"; oSQL.ParamByName["IDEMITENTE"] = IDEmitente; oSQL.Open(); return EntityUtil<UnidadeFederativa>.ParseDataRow(oSQL.dtDados.Rows[0]); } } public static UnidadeFederativa GetUnidadesFederativaComAliquotasICMS_PorUF(decimal IDUnidadeFederativa) { using (SQLQuery oSQL = new SQLQuery()) { oSQL.SQL = @"SELECT UNIDADEFEDERATIVA.IDUNIDADEFEDERATIVA, UNIDADEFEDERATIVA.IDPAIS, UNIDADEFEDERATIVA.SIGLA, COALESCE(ALIQUOTAINTER, 0) AS ALIQUOTAINTER, COALESCE(ALIQUOTAINTRA, 0) AS ALIQUOTAINTRA, COALESCE(FCP, 0) AS FCP FROM UNIDADEFEDERATIVA INNER JOIN ENDERECO ON (UNIDADEFEDERATIVA.IDUNIDADEFEDERATIVA = ENDERECO.IDUNIDADEFEDERATIVA) WHERE UNIDADEFEDERATIVA.IDUNIDADEFEDERATIVA = @IDUNIDADEFEDERATIVA"; oSQL.ParamByName["IDUNIDADEFEDERATIVA"] = IDUnidadeFederativa; oSQL.Open(); return EntityUtil<UnidadeFederativa>.ParseDataRow(oSQL.dtDados.Rows[0]); } } } }
namespace Goop.Xml.Serialization { using System.IO; using System.Xml.Serialization; public static class XmlSerializerEx { public static T Deserialize<T>(this XmlSerializer x, string path) { using var stream = File.OpenRead(path); return (T)x.Deserialize(stream)!; } } }
using Alarmy.Common; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Alarmy.Tests.Utils { internal abstract class FakeMainView : IMainView { public event EventHandler OnNewRequest; public event EventHandler OnImportRequest; public event EventHandler<AlarmEventArgs> OnCancelRequest; public event EventHandler<AlarmEventArgs> OnChangeRequest; public event EventHandler<AlarmEventArgs> OnCompleteRequest; public event EventHandler<AlarmEventArgs> OnHushRequest; public event EventHandler<AlarmEventArgs> OnUnhushRequest; public event EventHandler OnEnableSoundRequest; public event EventHandler OnDisableSoundRequest; public event EventHandler OnPopupOnAlarmOn; public event EventHandler OnPopupOnAlarmOff; public event EventHandler OnSmartAlarmOn; public event EventHandler OnSmartAlarmOff; public event EventHandler OnHideRequest; public event EventHandler OnShowRequest; public event EventHandler OnExitRequest; public event EventHandler OnLoad; public event EventHandler OnClosing; public bool Visible { get; set; } public bool IsMute { get; set; } public bool SoundEnabled { get; set; } public bool PopupOnAlarm { get; set; } public bool SmartAlarm { get; set; } public void SetSound(bool value) { this.SoundEnabled = value; if (this.SoundEnabled) this.OnEnableSoundRequest.Invoke(); else this.OnDisableSoundRequest.Invoke(); } public void SetPopupOnAlarm(bool value) { this.PopupOnAlarm = value; if (this.PopupOnAlarm) this.OnPopupOnAlarmOn.Invoke(); else this.OnPopupOnAlarmOff.Invoke(); } public void SetSmartAlarm(bool value) { this.SmartAlarm = value; if (this.SmartAlarm) this.OnSmartAlarmOn.Invoke(); else this.OnSmartAlarmOff.Invoke(); } public abstract void Show(); public abstract void Hide(); public abstract string AskCancelReason(IAlarm alarm); public abstract ImportContext AskImport(); public abstract AlarmMetadata AskAlarmMetadata(IAlarm alarm = null); public abstract void PlayAlarm(); public abstract void StopAlarm(); public abstract void AddAlarm(IAlarm alarm); public abstract void RemoveAlarm(IAlarm alarm); public abstract void UpdateAlarm(IAlarm alarm); public abstract void ShowReminder(string caption, string message); } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Services; using ERP_Palmeiras_LA.Models.Facade; using ERP_Palmeiras_LA.Models; namespace ERP_Palmeiras_LA.WebServices { /// <summary> /// Summary description for EquipamentosWS /// </summary> [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.ComponentModel.ToolboxItem(false)] // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. // [System.Web.Script.Services.ScriptService] public class EquipamentosWS : System.Web.Services.WebService { LogisticaAbastecimento facade = LogisticaAbastecimento.GetInstance(); [WebMethod] public bool ReportarEquipamentoDefeituoso(int equipamentoId) { EquipamentoClinica ec = facade.BuscarEquipamentoClinica(equipamentoId); if(ec.Status == StatusEquipamento.FUNCIONANDO) { ec.Status = StatusEquipamento.QUEBRADO; try { facade.AlterarEquipamentoClinica(ec); return true; } catch (Exception) { return false; } } return true; } [WebMethod] public List<EquipamentoClinicaDTO> BuscarEquipamentos() { IEnumerable<EquipamentoClinica> eqs = facade.BuscarEquipamentosClinica(); List<EquipamentoClinicaDTO> list = new List<EquipamentoClinicaDTO>(); foreach (EquipamentoClinica ec in eqs) { list.Add(new EquipamentoClinicaDTO(ec.Equipamento.Nome, ec.Status == StatusEquipamento.FUNCIONANDO? "Funcionando" : "Quebrado", ec.Id, ec.Equipamento.Fabricante.Nome, ec.Equipamento.NumeroSerie)); } return list; } } }
using OpenQA.Selenium; namespace PokuponTestAutomation.Driver { public static class ExtensionMethods { public static IWebElement FindElementSafe(this IWebDriver driver, By by) { try { return driver.FindElement(by); } catch (NoSuchElementException) { return null; } } public static bool Exists(this IWebElement element) { return (element == null) ? false : true; } } }
using Iri.IoC; using Iri.Plugin.Tests.Types.MapGen; namespace Iri.Plugin.Tests.Types { internal class StupidMapGenPlugin : IMapGenPlugin { public string Name => "Stupid Mapgen"; public void BeforeActivation(CookieJar container) { container.Register<IMapModifier>(new AlternatingModifier()); container.Register<IMapModifier>(new FirstFiveModifier()); } } }
using System.Web.Optimization; namespace ModuleZeroSampleProject.Web { public static class BundleConfig { public static void RegisterBundles(BundleCollection bundles) { bundles.IgnoreList.Clear(); #region Bundles for Angular application (private pages, entered after login) //VENDOR RESOURCES //~/Bundles/App/vendor/css bundles.Add( new StyleBundle("~/Bundles/App/vendor/css") .Include( "~/Content/themes/base/all.css", "~/Content/bootstrap.min.css", "~/bower_components/bootstrap-material-design/dist/css/ripples.min.css", "~/bower_components/bootstrap-material-design/dist/css/material-wfont.min.css", "~/bower_components/angular-material/angular-material.min.css", "~/bower_components/angular-material/themes/blue-theme.css", "~/Content/toastr.min.css", "~/Content/flags/famfamfam-flags.css", "~/Content/font-awesome.min.css" ) ); //~/Bundles/App/vendor/js bundles.Add( new ScriptBundle("~/Bundles/App/vendor/js") .Include( "~/Abp/Framework/scripts/utils/ie10fix.js", "~/Scripts/json2.min.js", "~/Scripts/modernizr-2.8.3.js", "~/Scripts/jquery-2.1.3.min.js", "~/Scripts/jquery-ui-1.11.4.min.js", "~/Scripts/bootstrap.min.js", "~/bower_components/bootstrap-material-design/dist/css/ripples.min.js", "~/bower_components/bootstrap-material-design/dist/css/material.min.js", "~/Scripts/moment-with-locales.min.js", "~/Scripts/jquery.blockUI.js", "~/Scripts/toastr.min.js", "~/bower_components/spin.js/spin.js", "~/bower_components/spin.js/jquery.spin.js", "~/bower_components/angular/angular.min.js", "~/bower_components/angular-animate/angular-animate.min.js", "~/bower_components/angular-sanitize/angular-sanitize.min.js", "~/bower_components/angular-aria/angular-aria.min.js", "~/bower_components/angular-ui-router/release/angular-ui-router.min.js", "~/bower_components/hammerjs/hammer.min.js", "~/bower_components/angular-material/angular-material.min.js", "~/Scripts/angular-ui/ui-bootstrap.min.js", "~/Scripts/angular-ui/ui-bootstrap-tpls.min.js", "~/Scripts/angular-ui/ui-utils.min.js", "~/Abp/Framework/scripts/abp.js", "~/Abp/Framework/scripts/libs/abp.jquery.js", "~/Abp/Framework/scripts/libs/abp.toastr.js", "~/Abp/Framework/scripts/libs/abp.blockUI.js", "~/Abp/Framework/scripts/libs/abp.spin.js", "~/Abp/Framework/scripts/libs/angularjs/abp.ng.js" ) ); //APPLICATION RESOURCES //~/Bundles/App/Main/css bundles.Add( new StyleBundle("~/Bundles/App/Main/css") .IncludeDirectory("~/App/Main", "*.css", true) ); //~/Bundles/App/Main/js bundles.Add( new ScriptBundle("~/Bundles/App/Main/js") .IncludeDirectory("~/App/Main", "*.js", true) ); #endregion #region Bundles for MVC application (public pages, can be seen without login) //VENDOR RESOURCES //~/Bundles/vendor/css bundles.Add( new StyleBundle("~/Bundles/vendor/css") .Include( "~/Content/themes/base/all.css", "~/Content/bootstrap.min.css", "~/bower_components/bootstrap-material-design/dist/css/ripples.min.css", "~/bower_components/bootstrap-material-design/dist/css/material-wfont.min.css", "~/Content/toastr.min.css", "~/Content/flags/famfamfam-flags.css", "~/Content/font-awesome.min.css" ) ); //~/Bundles/vendor/js/top (These scripts should be included in the head of the page) bundles.Add( new ScriptBundle("~/Bundles/vendor/js/top") .Include( "~/Abp/Framework/scripts/utils/ie10fix.js", "~/Scripts/modernizr-2.8.3.js" ) ); //~/Bundles/vendor/bottom (Included in the bottom for fast page load) bundles.Add( new ScriptBundle("~/Bundles/vendor/js/bottom") .Include( "~/Scripts/json2.min.js", "~/Scripts/jquery-2.1.3.min.js", "~/Scripts/jquery-ui-1.11.4.min.js", "~/Scripts/bootstrap.min.js", "~/bower_components/bootstrap-material-design/dist/css/ripples.min.js", "~/bower_components/bootstrap-material-design/dist/css/material.min.js", "~/Scripts/moment-with-locales.min.js", "~/Scripts/jquery.validate.min.js", "~/Scripts/jquery.blockUI.js", "~/Scripts/toastr.min.js", "~/bower_components/spin.js/spin.js", "~/bower_components/spin.js/jquery.spin.js", "~/Abp/Framework/scripts/abp.js", "~/Abp/Framework/scripts/libs/abp.jquery.js", "~/Abp/Framework/scripts/libs/abp.toastr.js", "~/Abp/Framework/scripts/libs/abp.blockUI.js", "~/Abp/Framework/scripts/libs/abp.spin.js" ) ); //APPLICATION RESOURCES //~/Bundles/css bundles.Add( new StyleBundle("~/Bundles/css") .Include("~/css/main.css") ); //~/Bundles/js bundles.Add( new ScriptBundle("~/Bundles/js") .Include("~/js/main.js") ); bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include( "~/Scripts/jquery.validate*")); // 使用要用于开发和学习的 Modernizr 的开发版本。然后,当你做好 // 生产准备时,请使用 http://modernizr.com 上的生成工具来仅选择所需的测试。 bundles.Add(new ScriptBundle("~/bundles/modernizr").Include( "~/Scripts/modernizr-*")); bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include( "~/Scripts/bootstrap.js", "~/Scripts/respond.js")); bundles.Add(new StyleBundle("~/Content/css").Include( "~/Content/bootstrap.css", "~/Content/site.css")); bundles.Add(new ScriptBundle("~/bundles/jquery").Include( "~/Scripts/jquery-{version}.js")); bundles.Add(new ScriptBundle("~/adminLTE/js"). Include( "~/Scripts/bootstrap.js", "~/Scripts/jquery-{version}.js", "~/App/Main/AdminLTE/plugins/iCheck/icheck.min.js")); bundles.Add(new ScriptBundle("~/adminLTE/js"). Include("~/Scripts/bootstrap.js", "~/Scripts/jquery-{version}.js", "~/App/Main/AdminLTE/plugins/iCheck/icheck.min.js")); bundles.Add(new ScriptBundle("~/login/js"). Include("~/Abp/Framework/scripts/libs/abp.jquery.js", "~/abp/framework/scripts/abp.js", "~/js/Account/login.js")); bundles.Add( new StyleBundle("~/adminLTE/css") .Include("~/Content/bootstrap.min.css", "~/App/Main/AdminLTE/dist/css/AdminLTE.min.css", "~/App/Main/AdminLTE/plugins/iCheck/square/blue.css") ); bundles.Add( new StyleBundle("~/adminLTE/main/css") .Include("~/Content/bootstrap.min.css", "~/App/Main/AdminLTE/dist/css/AdminLTE.min.css", "~/App/Main/AdminLTE/plugins/iCheck/square/blue.css", "~/App/Main/AdminLTE/dist/css/skins/_all-skins.min.css", "~/App/Main/AdminLTE/iconfont/css/ionicons.min.css", "~/App/Main/AdminLTE/plugins/morris/morris.css", "~/App/Main/AdminLTE/plugins/jvectormap/jquery-jvectormap-1.2.2.css", "~/App/Main/AdminLTE/plugins/datepicker/datepicker3.css", "~/App/Main/AdminLTE/plugins/daterangepicker/daterangepicker-bs3.css", "~/App/Main/AdminLTE/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.min.css" ) ); bundles.Add( new ScriptBundle("~/adminLTE/main/js") .Include( "~/App/Main/AdminLTE/plugins/jQuery/jQuery-2.1.4.min.js", "~/App/Main/AdminLTE/plugins/jQuery/jquery-ui.min.js", "~/bower_components/angular/angular.min.js", "~/Scripts/bootstrap.min.js", "~/App/Main/AdminLTE/plugins/morris/morris.min.js", "~/App/Main/AdminLTE/plugins/sparkline/jquery.sparkline.min.js", "~/App/Main/AdminLTE/plugins/jvectormap/jquery-jvectormap-1.2.2.min.js", "~/App/Main/AdminLTE/plugins/jvectormap/jquery-jvectormap-world-mill-en.js", "~/App/Main/AdminLTE/plugins/knob/jquery.knob.js", "~/App/Main/AdminLTE/plugins/daterangepicker/daterangepicker.js", "~/App/Main/AdminLTE/plugins/datepicker/bootstrap-datepicker.js", "~/App/Main/AdminLTE/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.min.js", "~/App/Main/AdminLTE/plugins/slimScroll/jquery.slimscroll.min.js", "~/App/Main/AdminLTE/plugins/fastclick/fastclick.min.js", "~/App/Main/AdminLTE/dist/js/app.min.js", "~/App/Main/AdminLTE/dist/js/pages/dashboard.js", "~/App/Main/AdminLTE/dist/js/demo.js", "~/Abp/Framework/scripts/libs/abp.jquery.js", "~/abp/framework/scripts/abp.js", "~/js/Account/login.js" ) ); #endregion } } }
using System; using System.Linq; using System.Collections.Generic; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace GeoNavigator { /// <summary> /// Okno nastaveni /// </summary> public partial class Settings : Form { // Obecne nastaveni a nastaveni zobrazeni private string[] settings; private bool[] settingsShow; /// <summary> /// Vytvori okno s nastavenim programu /// </summary> public Settings(string[] appSettings, bool[] appSettingsShow) { InitializeComponent(); settings = appSettings; settingsShow = appSettingsShow; // Layout ArrayList list1 = new ArrayList(); list1.Add("Meter"); list1.Add("Miles"); list1.Add("Nautical miles"); comboBox1.DataSource = list1; ArrayList list2 = new ArrayList(); list2.Add("Deg°"); list2.Add("Deg°Min'"); list2.Add("Deg°Min'Sec\""); comboBox2.DataSource = list2; // Aktualni hodnota switch(settings[2]) { case "mile": comboBox1.SelectedIndex = 1; break; case "nautical": comboBox1.SelectedIndex = 2; break; default: comboBox1.SelectedIndex = 0; break; } switch (settings[3]) { case "degmin": comboBox2.SelectedIndex = 1; break; case "degminsec": comboBox2.SelectedIndex = 2; break; default: comboBox2.SelectedIndex = 0; break; } if (settingsShow[0]) checkBox1.Checked = true; if (settingsShow[1]) checkBox2.Checked = true; if (settingsShow[2]) checkBox3.Checked = true; if (settingsShow[3]) checkBox4.Checked = true; if (settingsShow[4]) checkBox5.Checked = true; if (settingsShow[5]) checkBox6.Checked = true; } /// <summary> /// Stisknuti tlacitka OK /// </summary> private void menuItem1_Click(object sender, EventArgs e) { // Ulozeni nastaveni switch (comboBox1.SelectedIndex) { case 0: settings[2] = "meter"; break; case 1: settings[2] = "mile"; break; case 2: settings[2] = "nautical"; break; } switch (comboBox2.SelectedIndex) { case 0: settings[3] = "deg"; break; case 1: settings[3] = "degmin"; break; case 2: settings[3] = "degminsec"; break; } settingsShow[0] = checkBox1.Checked; settingsShow[1] = checkBox2.Checked; settingsShow[2] = checkBox3.Checked; settingsShow[3] = checkBox4.Checked; settingsShow[4] = checkBox5.Checked; settingsShow[5] = checkBox6.Checked; // Uzavreni okna this.DialogResult = DialogResult.OK; this.Close(); } /// <summary> /// Stisknuti tlacitka Cancel /// </summary> private void menuItem2_Click(object sender, EventArgs e) { this.DialogResult = DialogResult.Cancel; this.Close(); } } }
 using System; using UrTLibrary.Server.Queries.Game; namespace UrTLibrary.Server.Logging.Events.ChatCommands { [ChatCommandKey("reload")] public class ReloadCommand : ChatCommand { public override void Execute(GameServer server) { log.DebugFormat("--> Executing ReloadCommand"); try { server.Init(); server.QueryManager.RCon("reload"); } catch (CommandException ex) { server.QueryManager.TellError(Slot, ex.Message); } } } }
using UnityEngine; using System.Collections; public class TestSphere : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update () { Vector3 newScale = new Vector3( AudioInput.smoothedVolume, AudioInput.smoothedVolume, AudioInput.smoothedVolume ); newScale *= 3; transform.localScale = newScale; } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; using Football.DAL.Context; using Football.DAL.Entities; using Microsoft.EntityFrameworkCore; namespace Football.DAL.Repository { public class Repository<TEntity> : IRepository<TEntity> where TEntity : class, IEntityBase { protected readonly FootballContext Context; protected DbSet<TEntity> Entities; public Repository(FootballContext context) { Context = context; Entities = context.Set<TEntity>(); } public virtual IQueryable<TEntity> GetAll() { return Entities.AsQueryable(); } public virtual async Task<TEntity> FindByIdAsync(params object[] keys) { return await Entities.FindAsync(keys); } public virtual async Task<TEntity> FindByCondition(Expression<Func<TEntity, bool>> predicate) { return await Entities.FirstOrDefaultAsync(predicate); } public virtual void Add(TEntity entity) { Entities.Add(entity); } public virtual void AddRange(IEnumerable<TEntity> entity) { Entities.AddRange(entity); } public virtual void Remove(TEntity entity) { Entities.Remove(entity); } public virtual void RemoveRange(IEnumerable<TEntity> entity) { Entities.RemoveRange(entity); } public virtual void Update(TEntity entity) { Entities.Update(entity); } } }
namespace ns9 { using ns10; using ns11; using System; using System.IO; using System.Runtime.InteropServices; internal class Class54 : Interface2, Interface3, Interface4 { private bool bool_0; private bool bool_1; private bool bool_2; private bool bool_3; private static readonly byte[] byte_0 = new byte[0x800]; private readonly byte[] byte_1 = new byte[5]; private byte byte_2; private readonly Class56 class56_0 = new Class56(); private readonly Class56 class56_1 = new Class56(); private readonly Class57 class57_0 = new Class57(); private readonly Class58[] class58_0 = new Class58[0x1000]; private readonly Class61 class61_0 = new Class61(); private Enum6 enum6_0 = Enum6.const_1; private const int int_0 = 0x16; private const int int_1 = 5; private int int_2 = 3; private int int_3; private int int_4 = 2; private Interface7 interface7_0; private long long_0; private Stream stream_0; private static readonly string[] string_0 = new string[] { "BT2", "BT4" }; private readonly Struct11[] struct11_0 = new Struct11[0xc0]; private readonly Struct11[] struct11_1 = new Struct11[12]; private readonly Struct11[] struct11_2 = new Struct11[0xc0]; private readonly Struct11[] struct11_3 = new Struct11[12]; private readonly Struct11[] struct11_4 = new Struct11[12]; private readonly Struct11[] struct11_5 = new Struct11[12]; private readonly Struct11[] struct11_6 = new Struct11[0x72]; private readonly Struct13[] struct13_0 = new Struct13[4]; private Struct13 struct13_1 = new Struct13(4); private Class50.Struct8 struct8_0; private const uint uint_0 = 0xfffffff; private const uint uint_1 = 0x20; private readonly uint[] uint_10 = new uint[4]; private readonly uint[] uint_11 = new uint[0x80]; private uint uint_12; private uint uint_13; private uint uint_14 = 0x400000; private uint uint_15 = uint.MaxValue; private uint uint_16 = 0x2c; private uint uint_17; private uint uint_18; private uint uint_19; private const uint uint_2 = 0x10; private uint uint_20 = 0x20; private uint uint_21 = uint.MaxValue; private uint uint_22; private uint uint_23; private uint uint_24 = 3; private const uint uint_3 = 0x1000; private readonly uint[] uint_4 = new uint[0x10]; private readonly uint[] uint_5 = new uint[0x200]; private readonly uint[] uint_6 = new uint[0x224]; private readonly uint[] uint_7 = new uint[0x100]; private readonly uint[] uint_8 = new uint[4]; private readonly uint[] uint_9 = new uint[4]; static Class54() { int index = 2; byte_0[0] = 0; byte_0[1] = 1; for (byte i = 2; i < 0x16; i = (byte) (i + 1)) { uint num3 = ((uint) 1) << ((i >> 1) - 1); uint num4 = 0; while (num4 < num3) { byte_0[index] = i; num4++; index++; } } } public Class54() { for (int i = 0; i < 0x1000L; i++) { this.class58_0[i] = new Class58(); } for (int j = 0; j < 4L; j++) { this.struct13_0[j] = new Struct13(6); } } public void imethod_0(Stream stream_1, Stream stream_2, long long_1, long long_2, Interface1 interface1_0) { this.bool_2 = false; try { long num; long num2; bool flag; this.method_20(stream_1, stream_2, long_1, long_2); goto Label_0021; Label_0014: if (interface1_0 != null) { interface1_0.imethod_0(num, num2); } Label_0021: this.method_15(out num, out num2, out flag); if (!flag) { goto Label_0014; } } finally { this.method_19(); } } public void imethod_1(Enum5[] enum5_0, object[] object_0) { for (uint i = 0; i < object_0.Length; i++) { int num4; int num5; object obj2 = object_0[i]; switch (enum5_0[i]) { case Enum5.const_1: if (!(obj2 is int)) { throw new Exception1(); } num4 = (int) obj2; if ((num4 < 1L) || (num4 > 0x40000000L)) { throw new Exception1(); } this.uint_14 = (uint) num4; num5 = 0; goto Label_00A9; case Enum5.const_5: { if (!(obj2 is int)) { throw new Exception1(); } int num6 = (int) obj2; if ((num6 < 0) || (num6 > 4L)) { throw new Exception1(); } this.int_4 = num6; this.uint_24 = (uint) ((((int) 1) << this.int_4) - 1); continue; } case Enum5.const_6: { if (!(obj2 is int)) { throw new Exception1(); } int num8 = (int) obj2; if ((num8 < 0) || (num8 > 8L)) { throw new Exception1(); } this.int_2 = num8; continue; } case Enum5.const_7: { if (!(obj2 is int)) { throw new Exception1(); } int num7 = (int) obj2; if ((num7 < 0) || (num7 > 4L)) { throw new Exception1(); } this.int_3 = num7; continue; } case Enum5.const_8: { if (!(obj2 is int)) { throw new Exception1(); } int num2 = (int) obj2; if ((num2 < 5) || (num2 > 0x111L)) { throw new Exception1(); } this.uint_20 = (uint) num2; continue; } case Enum5.const_9: { if (!(obj2 is string)) { throw new Exception1(); } Enum6 enum3 = this.enum6_0; int num3 = smethod_2(((string) obj2).ToUpper()); if (num3 < 0) { throw new Exception1(); } this.enum6_0 = (Enum6) num3; if ((this.interface7_0 != null) && (enum3 != this.enum6_0)) { this.uint_15 = uint.MaxValue; this.interface7_0 = null; } continue; } case Enum5.const_12: { continue; } case Enum5.const_14: { if (!(obj2 is bool)) { throw new Exception1(); } this.method_2((bool) obj2); continue; } default: throw new Exception1(); } Label_0096: if (num4 <= (((uint) 1) << num5)) { goto Label_00B7; } num5++; Label_00A9: if (num5 < 30L) { goto Label_0096; } Label_00B7: this.uint_16 = (uint) (num5 * 2); } } public void imethod_2(Stream stream_1) { this.byte_1[0] = (byte) ((((this.int_4 * 5) + this.int_3) * 9) + this.int_2); for (int i = 0; i < 4; i++) { this.byte_1[1 + i] = (byte) (this.uint_14 >> (8 * i)); } stream_1.Write(this.byte_1, 0, 5); } private void method_0() { this.struct8_0.method_0(); this.byte_2 = 0; for (uint i = 0; i < 4; i++) { this.uint_8[i] = 0; } } private void method_1() { if (this.interface7_0 == null) { Class49 class2 = new Class49(); int num = 4; if (this.enum6_0 == Enum6.const_0) { num = 2; } class2.method_11(num); this.interface7_0 = class2; } this.class57_0.method_0(this.int_3, this.int_2); if ((this.uint_14 != this.uint_15) || (this.uint_21 != this.uint_20)) { this.interface7_0.imethod_6(this.uint_14, 0x1000, this.uint_20, 0x112); this.uint_15 = this.uint_14; this.uint_21 = this.uint_20; } } private uint method_10(out uint uint_25, uint uint_26) { this.uint_23 = uint_26; uint index = this.class58_0[uint_26].uint_6; uint num2 = this.class58_0[uint_26].uint_0; while (true) { if (this.class58_0[uint_26].bool_0) { this.class58_0[index].method_0(); this.class58_0[index].uint_6 = index - 1; if (this.class58_0[uint_26].bool_1) { this.class58_0[((int) index) - 1].bool_0 = false; this.class58_0[((int) index) - 1].uint_6 = this.class58_0[uint_26].uint_7; this.class58_0[((int) index) - 1].uint_0 = this.class58_0[uint_26].uint_1; } } uint num3 = index; uint num4 = num2; num2 = this.class58_0[num3].uint_0; index = this.class58_0[num3].uint_6; this.class58_0[num3].uint_0 = num4; this.class58_0[num3].uint_6 = uint_26; uint_26 = num3; if (uint_26 <= 0) { uint_25 = this.class58_0[0].uint_0; this.uint_22 = this.class58_0[0].uint_6; return this.uint_22; } } } private uint method_11(uint uint_25, out uint uint_26) { uint num; uint num2; uint num5; if (this.uint_23 != this.uint_22) { uint_26 = this.class58_0[this.uint_22].uint_0; this.uint_22 = this.class58_0[this.uint_22].uint_6; return (this.class58_0[this.uint_22].uint_6 - this.uint_22); } this.uint_23 = 0; this.uint_22 = 0; if (!this.bool_1) { this.method_4(out num, out num2); } else { num = this.uint_17; num2 = this.uint_19; this.bool_1 = false; } uint num3 = this.interface7_0.imethod_5() + 1; if (num3 < 2) { uint_26 = uint.MaxValue; return 1; } if (num3 > 0x111) { num3 = 0x111; } uint index = 0; for (num5 = 0; num5 < 4; num5++) { this.uint_10[num5] = this.uint_8[num5]; this.uint_9[num5] = this.interface7_0.imethod_4(-1, this.uint_10[num5], 0x111); if (this.uint_9[num5] > this.uint_9[index]) { index = num5; } } if (this.uint_9[index] >= this.uint_20) { uint_26 = index; uint num6 = this.uint_9[index]; this.method_5(num6 - 1); return num6; } if (num >= this.uint_20) { uint_26 = this.uint_6[((int) num2) - 1] + 4; this.method_5(num - 1); return num; } byte num7 = this.interface7_0.imethod_3(-1); byte num8 = this.interface7_0.imethod_3(((0 - ((int) this.uint_8[0])) - 1) - 1); if (((num < 2) && (num7 != num8)) && (this.uint_9[index] < 2)) { uint_26 = uint.MaxValue; return 1; } this.class58_0[0].struct8_0 = this.struct8_0; uint num9 = uint_25 & this.uint_24; this.class58_0[1].uint_8 = this.struct11_0[(this.struct8_0.uint_0 << 4) + num9].method_4() + this.class57_0.method_2(uint_25, this.byte_2).method_4(!this.struct8_0.method_5(), num8, num7); this.class58_0[1].method_0(); uint num10 = this.struct11_0[(this.struct8_0.uint_0 << 4) + num9].method_5(); uint num11 = num10 + this.struct11_1[this.struct8_0.uint_0].method_5(); if (num8 == num7) { uint num12 = num11 + this.method_6(this.struct8_0, num9); if (num12 < this.class58_0[1].uint_8) { this.class58_0[1].uint_8 = num12; this.class58_0[1].method_1(); } } uint num13 = (num >= this.uint_9[index]) ? num : this.uint_9[index]; if (num13 < 2) { uint_26 = this.class58_0[1].uint_0; return 1; } this.class58_0[1].uint_6 = 0; this.class58_0[0].uint_2 = this.uint_10[0]; this.class58_0[0].uint_3 = this.uint_10[1]; this.class58_0[0].uint_4 = this.uint_10[2]; this.class58_0[0].uint_5 = this.uint_10[3]; uint num14 = num13; do { this.class58_0[num14--].uint_8 = 0xfffffff; } while (num14 >= 2); for (num5 = 0; num5 < 4; num5++) { uint num17; Class58 class2; uint num15 = this.uint_9[num5]; if (num15 < 2) { continue; } uint num16 = num11 + this.method_7(num5, this.struct8_0, num9); goto Label_03B9; Label_0389: if (--num15 >= 2) { goto Label_03B9; } continue; Label_0395: class2.uint_8 = num17; class2.uint_6 = 0; class2.uint_0 = num5; class2.bool_0 = false; goto Label_0389; Label_03B9: num17 = num16 + this.class56_1.method_4(num15 - 2, num9); class2 = this.class58_0[num15]; if (num17 >= class2.uint_8) { goto Label_0389; } goto Label_0395; } uint num18 = num10 + this.struct11_1[this.struct8_0.uint_0].method_4(); num14 = (this.uint_9[0] >= 2) ? (this.uint_9[0] + 1) : 2; if (num14 <= num) { uint num19 = 0; while (num14 > this.uint_6[num19]) { num19 += 2; } while (true) { uint num20 = this.uint_6[((int) num19) + 1]; uint num21 = num18 + this.method_9(num20, num14, num9); Class58 class3 = this.class58_0[num14]; if (num21 < class3.uint_8) { class3.uint_8 = num21; class3.uint_6 = 0; class3.uint_0 = num20 + 4; class3.bool_0 = false; } if (num14 == this.uint_6[num19]) { num19 += 2; if (num19 == num2) { break; } } num14++; } } uint num22 = 0; Label_0FD3: num22++; if (num22 != num13) { uint num23; Class50.Struct8 struct3; uint num46; this.method_4(out num23, out num2); if (num23 >= this.uint_20) { this.uint_19 = num2; this.uint_17 = num23; this.bool_1 = true; return this.method_10(out uint_26, num22); } uint_25++; uint num24 = this.class58_0[num22].uint_6; if (this.class58_0[num22].bool_0) { num24--; if (this.class58_0[num22].bool_1) { struct3 = this.class58_0[this.class58_0[num22].uint_7].struct8_0; if (this.class58_0[num22].uint_1 < 4) { struct3.method_3(); } else { struct3.method_2(); } } else { struct3 = this.class58_0[num24].struct8_0; } struct3.method_1(); } else { struct3 = this.class58_0[num24].struct8_0; } if (num24 == (num22 - 1)) { if (this.class58_0[num22].method_2()) { struct3.method_4(); } else { struct3.method_1(); } } else { uint num25; if (this.class58_0[num22].bool_0 && this.class58_0[num22].bool_1) { num24 = this.class58_0[num22].uint_7; num25 = this.class58_0[num22].uint_1; struct3.method_3(); } else { num25 = this.class58_0[num22].uint_0; if (num25 < 4) { struct3.method_3(); } else { struct3.method_2(); } } Class58 class4 = this.class58_0[num24]; if (num25 < 4) { if (num25 == 0) { this.uint_10[0] = class4.uint_2; this.uint_10[1] = class4.uint_3; this.uint_10[2] = class4.uint_4; this.uint_10[3] = class4.uint_5; } else if (num25 == 1) { this.uint_10[0] = class4.uint_3; this.uint_10[1] = class4.uint_2; this.uint_10[2] = class4.uint_4; this.uint_10[3] = class4.uint_5; } else if (num25 == 2) { this.uint_10[0] = class4.uint_4; this.uint_10[1] = class4.uint_2; this.uint_10[2] = class4.uint_3; this.uint_10[3] = class4.uint_5; } else { this.uint_10[0] = class4.uint_5; this.uint_10[1] = class4.uint_2; this.uint_10[2] = class4.uint_3; this.uint_10[3] = class4.uint_4; } } else { this.uint_10[0] = num25 - 4; this.uint_10[1] = class4.uint_2; this.uint_10[2] = class4.uint_3; this.uint_10[3] = class4.uint_4; } } this.class58_0[num22].struct8_0 = struct3; this.class58_0[num22].uint_2 = this.uint_10[0]; this.class58_0[num22].uint_3 = this.uint_10[1]; this.class58_0[num22].uint_4 = this.uint_10[2]; this.class58_0[num22].uint_5 = this.uint_10[3]; num7 = this.interface7_0.imethod_3(-1); num8 = this.interface7_0.imethod_3(((0 - ((int) this.uint_10[0])) - 1) - 1); num9 = uint_25 & this.uint_24; uint num26 = (this.class58_0[num22].uint_8 + this.struct11_0[(struct3.uint_0 << 4) + num9].method_4()) + this.class57_0.method_2(uint_25, this.interface7_0.imethod_3(-2)).method_4(!struct3.method_5(), num8, num7); Class58 class5 = this.class58_0[((int) num22) + 1]; bool flag = false; if (num26 < class5.uint_8) { class5.uint_8 = num26; class5.uint_6 = num22; class5.method_0(); flag = true; } num10 = this.class58_0[num22].uint_8 + this.struct11_0[(struct3.uint_0 << 4) + num9].method_5(); num11 = num10 + this.struct11_1[struct3.uint_0].method_5(); if ((num8 == num7) && ((class5.uint_6 >= num22) || (class5.uint_0 != 0))) { uint num27 = num11 + this.method_6(struct3, num9); if (num27 <= class5.uint_8) { class5.uint_8 = num27; class5.uint_6 = num22; class5.method_1(); flag = true; } } uint num28 = this.interface7_0.imethod_5() + 1; num28 = Math.Min(0xfff - num22, num28); num3 = num28; if (num3 < 2) { goto Label_0FD3; } if (num3 > this.uint_20) { num3 = this.uint_20; } if (!flag && (num8 != num7)) { uint num29 = Math.Min(num28 - 1, this.uint_20); uint num30 = this.interface7_0.imethod_4(0, this.uint_10[0], num29); if (num30 >= 2) { Class50.Struct8 struct4 = struct3; struct4.method_1(); uint num31 = (uint_25 + 1) & this.uint_24; uint num32 = (num26 + this.struct11_0[(struct4.uint_0 << 4) + num31].method_5()) + this.struct11_1[struct4.uint_0].method_5(); uint num33 = (num22 + 1) + num30; while (num13 < num33) { this.class58_0[++num13].uint_8 = 0xfffffff; } uint num34 = num32 + this.method_8(0, num30, struct4, num31); Class58 class6 = this.class58_0[num33]; if (num34 < class6.uint_8) { class6.uint_8 = num34; class6.uint_6 = num22 + 1; class6.uint_0 = 0; class6.bool_0 = true; class6.bool_1 = false; } } } uint num35 = 2; for (uint i = 0; i < 4; i++) { uint num37 = this.interface7_0.imethod_4(-1, this.uint_10[i], num3); if (num37 < 2) { continue; } uint num38 = num37; while (num13 < (num22 + num37)) { uint num39; this.class58_0[++num13].uint_8 = 0xfffffff; continue; Label_0AD4: num39 = num11 + this.method_8(i, num37, struct3, num9); Class58 class7 = this.class58_0[num22 + num37]; if (num39 < class7.uint_8) { class7.uint_8 = num39; class7.uint_6 = num22; class7.uint_0 = i; class7.bool_0 = false; } if (--num37 < 2) { goto Label_0B38; } } goto Label_0AD4; Label_0B38: num37 = num38; if (i == 0) { num35 = num37 + 1; } if (num37 < num28) { uint num40 = Math.Min((num28 - 1) - num37, this.uint_20); uint num41 = this.interface7_0.imethod_4((int) num37, this.uint_10[i], num40); if (num41 >= 2) { Class50.Struct8 struct5 = struct3; struct5.method_3(); uint num42 = (uint_25 + num37) & this.uint_24; struct5.method_1(); num42 = ((uint_25 + num37) + 1) & this.uint_24; uint num43 = ((((num11 + this.method_8(i, num37, struct3, num9)) + this.struct11_0[(struct5.uint_0 << 4) + num42].method_4()) + this.class57_0.method_2(uint_25 + num37, this.interface7_0.imethod_3((((int) num37) - 1) - 1)).method_4(true, this.interface7_0.imethod_3((int) ((num37 - 1) - (this.uint_10[i] + 1))), this.interface7_0.imethod_3(((int) num37) - 1))) + this.struct11_0[(struct5.uint_0 << 4) + num42].method_5()) + this.struct11_1[struct5.uint_0].method_5(); uint num44 = (num37 + 1) + num41; while (num13 < (num22 + num44)) { this.class58_0[++num13].uint_8 = 0xfffffff; } uint num45 = num43 + this.method_8(0, num41, struct5, num42); Class58 class8 = this.class58_0[num22 + num44]; if (num45 < class8.uint_8) { class8.uint_8 = num45; class8.uint_6 = (num22 + num37) + 1; class8.uint_0 = 0; class8.bool_0 = true; class8.bool_1 = true; class8.uint_7 = num22; class8.uint_1 = i; } } } } if (num23 > num3) { num23 = num3; num2 = 0; while (num23 > this.uint_6[num2]) { num2 += 2; } this.uint_6[num2] = num23; num2 += 2; } if (num23 < num35) { goto Label_0FD3; } num18 = num10 + this.struct11_1[struct3.uint_0].method_4(); while (num13 < (num22 + num23)) { this.class58_0[++num13].uint_8 = 0xfffffff; } for (num46 = 0; num35 > this.uint_6[num46]; num46 += 2) { } uint num47 = num35; while (true) { uint num48 = this.uint_6[((int) num46) + 1]; uint num49 = num18 + this.method_9(num48, num47, num9); Class58 class9 = this.class58_0[num22 + num47]; if (num49 < class9.uint_8) { class9.uint_8 = num49; class9.uint_6 = num22; class9.uint_0 = num48 + 4; class9.bool_0 = false; } if (num47 == this.uint_6[num46]) { if (num47 < num28) { uint num50 = Math.Min((num28 - 1) - num47, this.uint_20); uint num51 = this.interface7_0.imethod_4((int) num47, num48, num50); if (num51 >= 2) { Class50.Struct8 struct6 = struct3; struct6.method_2(); uint num52 = (uint_25 + num47) & this.uint_24; struct6.method_1(); num52 = ((uint_25 + num47) + 1) & this.uint_24; uint num53 = (((num49 + this.struct11_0[(struct6.uint_0 << 4) + num52].method_4()) + this.class57_0.method_2(uint_25 + num47, this.interface7_0.imethod_3((((int) num47) - 1) - 1)).method_4(true, this.interface7_0.imethod_3(((int) (num47 - (num48 + 1))) - 1), this.interface7_0.imethod_3(((int) num47) - 1))) + this.struct11_0[(struct6.uint_0 << 4) + num52].method_5()) + this.struct11_1[struct6.uint_0].method_5(); uint num54 = (num47 + 1) + num51; while (num13 < (num22 + num54)) { this.class58_0[++num13].uint_8 = 0xfffffff; } num49 = num53 + this.method_8(0, num51, struct6, num52); class9 = this.class58_0[num22 + num54]; if (num49 < class9.uint_8) { class9.uint_8 = num49; class9.uint_6 = (num22 + num47) + 1; class9.uint_0 = 0; class9.bool_0 = true; class9.bool_1 = true; class9.uint_7 = num22; class9.uint_1 = num48 + 4; } } } num46 += 2; if (num46 == num2) { goto Label_0FD3; } } num47++; } } return this.method_10(out uint_26, num22); } private bool method_12(uint uint_25, uint uint_26) { return ((uint_25 < 0x2000000) && (uint_26 >= (uint_25 << 7))); } private void method_13(uint uint_25) { if (this.bool_3) { this.struct11_0[(this.struct8_0.uint_0 << 4) + uint_25].method_2(this.class61_0, 1); this.struct11_1[this.struct8_0.uint_0].method_2(this.class61_0, 0); this.struct8_0.method_2(); this.class56_0.method_7(this.class61_0, 0, uint_25); uint index = Class50.smethod_0(2); this.struct13_0[index].method_1(this.class61_0, 0x3f); this.class61_0.method_8(0x3ffffff, 0x1a); this.struct13_1.method_2(this.class61_0, 15); } } private void method_14(uint uint_25) { this.method_16(); this.method_13(uint_25 & this.uint_24); this.class61_0.method_3(); this.class61_0.method_4(); } public void method_15(out long long_1, out long long_2, out bool bool_4) { long num; uint num6; uint num7; long_1 = 0L; long_2 = 0L; bool_4 = true; if (this.stream_0 != null) { this.interface7_0.imethod_0(this.stream_0); this.interface7_0.imethod_1(); this.bool_2 = true; this.stream_0 = null; } if (!this.bool_0) { this.bool_0 = true; num = this.long_0; if (this.long_0 == 0) { uint num2; uint num3; if (this.interface7_0.imethod_5() == 0) { this.method_14((uint) this.long_0); return; } this.method_4(out num2, out num3); uint num4 = ((uint) this.long_0) & this.uint_24; this.struct11_0[(this.struct8_0.uint_0 << 4) + num4].method_2(this.class61_0, 0); this.struct8_0.method_1(); byte num5 = this.interface7_0.imethod_3(0 - ((int) this.uint_12)); this.class57_0.method_2((uint) this.long_0, this.byte_2).method_2(this.class61_0, num5); this.byte_2 = num5; this.uint_12--; this.long_0 += 1L; } if (this.interface7_0.imethod_5() != 0) { goto Label_05A3; } this.method_14((uint) this.long_0); } return; Label_05A3: num7 = this.method_11((uint) this.long_0, out num6); uint num8 = ((uint) this.long_0) & this.uint_24; uint index = (this.struct8_0.uint_0 << 4) + num8; if ((num7 != 1) || (num6 != uint.MaxValue)) { this.struct11_0[index].method_2(this.class61_0, 1); if (num6 < 4) { this.struct11_1[this.struct8_0.uint_0].method_2(this.class61_0, 1); if (num6 == 0) { this.struct11_3[this.struct8_0.uint_0].method_2(this.class61_0, 0); if (num7 == 1) { this.struct11_2[index].method_2(this.class61_0, 0); } else { this.struct11_2[index].method_2(this.class61_0, 1); } } else { this.struct11_3[this.struct8_0.uint_0].method_2(this.class61_0, 1); if (num6 == 1) { this.struct11_4[this.struct8_0.uint_0].method_2(this.class61_0, 0); } else { this.struct11_4[this.struct8_0.uint_0].method_2(this.class61_0, 1); this.struct11_5[this.struct8_0.uint_0].method_2(this.class61_0, num6 - 2); } } if (num7 == 1) { this.struct8_0.method_4(); } else { this.class56_1.method_7(this.class61_0, num7 - 2, num8); this.struct8_0.method_3(); } uint num12 = this.uint_8[num6]; if (num6 != 0) { for (uint i = num6; i >= 1; i--) { this.uint_8[i] = this.uint_8[((int) i) - 1]; } this.uint_8[0] = num12; } } else { this.struct11_1[this.struct8_0.uint_0].method_2(this.class61_0, 0); this.struct8_0.method_2(); this.class56_0.method_7(this.class61_0, num7 - 2, num8); num6 -= 4; uint num14 = smethod_0(num6); uint num15 = Class50.smethod_0(num7); this.struct13_0[num15].method_1(this.class61_0, num14); if (num14 >= 4) { int num17 = ((int) (num14 >> 1)) - 1; uint num18 = (uint) ((2 | (num14 & 1)) << (num17 & 0x1f)); uint num19 = num6 - num18; if (num14 < 14) { Struct13.smethod_1(this.struct11_6, (num18 - num14) - 1, this.class61_0, num17, num19); } else { this.class61_0.method_8(num19 >> 4, num17 - 4); this.struct13_1.method_2(this.class61_0, num19 & 15); this.uint_13++; } } uint num16 = num6; for (uint j = 3; j >= 1; j--) { this.uint_8[j] = this.uint_8[((int) j) - 1]; } this.uint_8[0] = num16; this.uint_18++; } this.byte_2 = this.interface7_0.imethod_3((int) ((num7 - 1) - this.uint_12)); } else { this.struct11_0[index].method_2(this.class61_0, 0); byte num10 = this.interface7_0.imethod_3(0 - ((int) this.uint_12)); Class57.Struct10 struct3 = this.class57_0.method_2((uint) this.long_0, this.byte_2); if (!this.struct8_0.method_5()) { byte num11 = this.interface7_0.imethod_3((int) (((0 - this.uint_8[0]) - 1) - this.uint_12)); struct3.method_3(this.class61_0, num11, num10); } else { struct3.method_2(this.class61_0, num10); } this.byte_2 = num10; this.struct8_0.method_1(); } this.uint_12 -= num7; this.long_0 += num7; if (this.uint_12 == 0) { if (this.uint_18 >= 0x80) { this.method_21(); } if (this.uint_13 >= 0x10) { this.method_22(); } long_1 = this.long_0; long_2 = this.class61_0.method_10(); if (this.interface7_0.imethod_5() == 0) { this.method_14((uint) this.long_0); return; } if ((this.long_0 - num) >= 0x1000L) { this.bool_0 = false; bool_4 = false; return; } } goto Label_05A3; } private void method_16() { if ((this.interface7_0 != null) && this.bool_2) { this.interface7_0.imethod_2(); this.bool_2 = false; } } private void method_17(Stream stream_1) { this.class61_0.method_0(stream_1); } private void method_18() { this.class61_0.method_1(); } private void method_19() { this.method_16(); this.method_18(); } private void method_2(bool bool_4) { this.bool_3 = bool_4; } private void method_20(Stream stream_1, Stream stream_2, long long_1, long long_2) { this.stream_0 = stream_1; this.bool_0 = false; this.method_1(); this.method_17(stream_2); this.method_3(); this.method_21(); this.method_22(); this.class56_0.method_3((this.uint_20 + 1) - 2); this.class56_0.method_6(((uint) 1) << this.int_4); this.class56_1.method_3((this.uint_20 + 1) - 2); this.class56_1.method_6(((uint) 1) << this.int_4); this.long_0 = 0L; } private void method_21() { for (uint i = 4; i < 0x80; i++) { uint num2 = smethod_0(i); int num3 = ((int) (num2 >> 1)) - 1; uint num4 = (uint) ((2 | (num2 & 1)) << (num3 & 0x1f)); this.uint_11[i] = Struct13.smethod_0(this.struct11_6, (num4 - num2) - 1, num3, i - num4); } for (uint j = 0; j < 4; j++) { Struct13 struct2 = this.struct13_0[j]; uint num7 = j << 6; uint num6 = 0; while (num6 < this.uint_16) { this.uint_7[num7 + num6] = struct2.method_3(num6); num6++; } for (num6 = 14; num6 < this.uint_16; num6++) { this.uint_7[num7 + num6] += (uint) ((((num6 >> 1) - 1) - 4) << 6); } uint num8 = j * 0x80; uint num9 = 0; while (num9 < 4) { this.uint_5[num8 + num9] = this.uint_7[num7 + num9]; num9++; } while (num9 < 0x80) { this.uint_5[num8 + num9] = this.uint_7[num7 + smethod_0(num9)] + this.uint_11[num9]; num9++; } } this.uint_18 = 0; } private void method_22() { for (uint i = 0; i < 0x10; i++) { this.uint_4[i] = this.struct13_1.method_4(i); } this.uint_13 = 0; } private void method_3() { uint num; this.method_0(); this.class61_0.method_2(); for (num = 0; num < 12; num++) { for (uint i = 0; i <= this.uint_24; i++) { uint index = (num << 4) + i; this.struct11_0[index].method_0(); this.struct11_2[index].method_0(); } this.struct11_1[num].method_0(); this.struct11_3[num].method_0(); this.struct11_4[num].method_0(); this.struct11_5[num].method_0(); } this.class57_0.method_1(); for (num = 0; num < 4; num++) { this.struct13_0[num].method_0(); } for (num = 0; num < 0x72; num++) { this.struct11_6[num].method_0(); } this.class56_0.method_0(((uint) 1) << this.int_4); this.class56_1.method_0(((uint) 1) << this.int_4); this.struct13_1.method_0(); this.bool_1 = false; this.uint_23 = 0; this.uint_22 = 0; this.uint_12 = 0; } private void method_4(out uint uint_25, out uint uint_26) { uint_25 = 0; uint_26 = this.interface7_0.imethod_7(this.uint_6); if (uint_26 > 0) { uint_25 = this.uint_6[uint_26 - 2]; if (uint_25 == this.uint_20) { uint_25 += this.interface7_0.imethod_4(((int) uint_25) - 1, this.uint_6[uint_26 - 1], 0x111 - uint_25); } } this.uint_12++; } private void method_5(uint uint_25) { if (uint_25 > 0) { this.interface7_0.imethod_8(uint_25); this.uint_12 += uint_25; } } private uint method_6(Class50.Struct8 struct8_1, uint uint_25) { return (this.struct11_3[struct8_1.uint_0].method_4() + this.struct11_2[(struct8_1.uint_0 << 4) + uint_25].method_4()); } private uint method_7(uint uint_25, Class50.Struct8 struct8_1, uint uint_26) { if (uint_25 == 0) { return (this.struct11_3[struct8_1.uint_0].method_4() + this.struct11_2[(struct8_1.uint_0 << 4) + uint_26].method_5()); } uint num = this.struct11_3[struct8_1.uint_0].method_5(); if (uint_25 == 1) { return (num + this.struct11_4[struct8_1.uint_0].method_4()); } num += this.struct11_4[struct8_1.uint_0].method_5(); return (num + this.struct11_5[struct8_1.uint_0].method_3(uint_25 - 2)); } private uint method_8(uint uint_25, uint uint_26, Class50.Struct8 struct8_1, uint uint_27) { return (this.class56_1.method_4(uint_26 - 2, uint_27) + this.method_7(uint_25, struct8_1, uint_27)); } private uint method_9(uint uint_25, uint uint_26, uint uint_27) { uint num; uint num2 = Class50.smethod_0(uint_26); if (uint_25 < 0x80) { num = this.uint_5[(num2 * 0x80) + uint_25]; } else { num = this.uint_7[(num2 << 6) + smethod_1(uint_25)] + this.uint_4[((int) uint_25) & 15]; } return (num + this.class56_0.method_4(uint_26 - 2, uint_27)); } private static uint smethod_0(uint uint_25) { if (uint_25 < 0x800) { return byte_0[uint_25]; } if (uint_25 < 0x200000) { return (uint) (byte_0[uint_25 >> 10] + 20); } return (uint) (byte_0[uint_25 >> 20] + 40); } private static uint smethod_1(uint uint_25) { if (uint_25 < 0x20000) { return (uint) (byte_0[uint_25 >> 6] + 12); } if (uint_25 < 0x8000000) { return (uint) (byte_0[uint_25 >> 0x10] + 0x20); } return (uint) (byte_0[uint_25 >> 0x1a] + 0x34); } private static int smethod_2(string string_1) { for (int i = 0; i < string_0.Length; i++) { if (string_1 == string_0[i]) { return i; } } return -1; } internal class Class55 { private Struct11 struct11_0; private Struct11 struct11_1; private readonly Struct13[] struct13_0 = new Struct13[0x10]; private readonly Struct13[] struct13_1 = new Struct13[0x10]; private Struct13 struct13_2 = new Struct13(8); public Class55() { for (uint i = 0; i < 0x10; i++) { this.struct13_0[i] = new Struct13(3); this.struct13_1[i] = new Struct13(3); } } public void method_0(uint uint_0) { this.struct11_0.method_0(); this.struct11_1.method_0(); for (uint i = 0; i < uint_0; i++) { this.struct13_0[i].method_0(); this.struct13_1[i].method_0(); } this.struct13_2.method_0(); } public void method_1(Class61 class61_0, uint uint_0, uint uint_1) { if (uint_0 < 8) { this.struct11_0.method_2(class61_0, 0); this.struct13_0[uint_1].method_1(class61_0, uint_0); } else { uint_0 -= 8; this.struct11_0.method_2(class61_0, 1); if (uint_0 < 8) { this.struct11_1.method_2(class61_0, 0); this.struct13_1[uint_1].method_1(class61_0, uint_0); } else { this.struct11_1.method_2(class61_0, 1); this.struct13_2.method_1(class61_0, uint_0 - 8); } } } public void method_2(uint uint_0, uint uint_1, uint[] uint_2, uint uint_3) { uint num = this.struct11_0.method_4(); uint num1 = this.struct11_0.method_5(); uint num2 = num1 + this.struct11_1.method_4(); uint num3 = num1 + this.struct11_1.method_5(); uint num4 = 0; num4 = 0; while (num4 < 8) { if (num4 >= uint_1) { return; } uint_2[uint_3 + num4] = num + this.struct13_0[uint_0].method_3(num4); num4++; } while (num4 < 0x10) { if (num4 >= uint_1) { return; } uint_2[uint_3 + num4] = num2 + this.struct13_1[uint_0].method_3(num4 - 8); num4++; } while (num4 < uint_1) { uint_2[uint_3 + num4] = num3 + this.struct13_2.method_3((num4 - 8) - 8); num4++; } } } internal class Class56 : Class54.Class55 { private readonly uint[] uint_0 = new uint[0x10]; private readonly uint[] uint_1 = new uint[0x1100]; private uint uint_2; public void method_3(uint uint_3) { this.uint_2 = uint_3; } public uint method_4(uint uint_3, uint uint_4) { return this.uint_1[(uint_4 * 0x110) + uint_3]; } private void method_5(uint uint_3) { base.method_2(uint_3, this.uint_2, this.uint_1, uint_3 * 0x110); this.uint_0[uint_3] = this.uint_2; } public void method_6(uint uint_3) { for (uint i = 0; i < uint_3; i++) { this.method_5(i); } } public void method_7(Class61 class61_0, uint uint_3, uint uint_4) { base.method_1(class61_0, uint_3, uint_4); uint num = this.uint_0[uint_4] - 1; this.uint_0[uint_4] = num; if (num == 0) { this.method_5(uint_4); } } } internal class Class57 { private int int_0; private int int_1; private Struct10[] struct10_0; private uint uint_0; public void method_0(int int_2, int int_3) { if (((this.struct10_0 == null) || (this.int_1 != int_3)) || (this.int_0 != int_2)) { this.int_0 = int_2; this.uint_0 = (uint) ((((int) 1) << int_2) - 1); this.int_1 = int_3; uint num = ((uint) 1) << (this.int_1 + this.int_0); this.struct10_0 = new Struct10[num]; for (uint i = 0; i < num; i++) { this.struct10_0[i].method_0(); } } } public void method_1() { uint num = ((uint) 1) << (this.int_1 + this.int_0); for (uint i = 0; i < num; i++) { this.struct10_0[i].method_1(); } } public Struct10 method_2(uint uint_1, byte byte_0) { return this.struct10_0[((int) ((uint_1 & this.uint_0) << this.int_1)) + (byte_0 >> (8 - this.int_1))]; } [StructLayout(LayoutKind.Sequential)] public struct Struct10 { private Struct11[] struct11_0; public void method_0() { this.struct11_0 = new Struct11[0x300]; } public void method_1() { for (int i = 0; i < 0x300; i++) { this.struct11_0[i].method_0(); } } public void method_2(Class61 class61_0, byte byte_0) { uint index = 1; for (int i = 7; i >= 0; i--) { uint num3 = (uint) ((byte_0 >> i) & 1); this.struct11_0[index].method_2(class61_0, num3); index = (index << 1) | num3; } } public void method_3(Class61 class61_0, byte byte_0, byte byte_1) { uint num = 1; bool flag = true; for (int i = 7; i >= 0; i--) { uint num3 = (uint) ((byte_1 >> i) & 1); uint index = num; if (flag) { uint num5 = (uint) ((byte_0 >> i) & 1); index += (uint) ((1 + num5) << 8); flag = num5 == num3; } this.struct11_0[index].method_2(class61_0, num3); num = (num << 1) | num3; } } public uint method_4(bool bool_0, byte byte_0, byte byte_1) { uint num = 0; uint index = 1; int num3 = 7; if (bool_0) { while (num3 >= 0) { uint num4 = (uint) ((byte_0 >> num3) & 1); uint num5 = (uint) ((byte_1 >> num3) & 1); num += this.struct11_0[(int) (((1 + num4) << 8) + index)].method_3(num5); index = (index << 1) | num5; if (num4 != num5) { num3--; break; } num3--; } } while (num3 >= 0) { uint num6 = (uint) ((byte_1 >> num3) & 1); num += this.struct11_0[index].method_3(num6); index = (index << 1) | num6; num3--; } return num; } } } internal class Class58 { public bool bool_0; public bool bool_1; public Class50.Struct8 struct8_0; public uint uint_0; public uint uint_1; public uint uint_2; public uint uint_3; public uint uint_4; public uint uint_5; public uint uint_6; public uint uint_7; public uint uint_8; public void method_0() { this.uint_0 = uint.MaxValue; this.bool_0 = false; } public void method_1() { this.uint_0 = 0; this.bool_0 = false; } public bool method_2() { return (this.uint_0 == 0); } } private enum Enum6 { const_0, const_1 } } }
using System.Collections.Generic; using MySql.Data.MySqlClient; namespace at02.Models { public class UsuarioRepository : Repository { public void Cadastra (Usuario u) { conexao.Open(); string sql = "INSERT INTO usuarios (nome, nascimento, login, senha, tipo) VALUES (@nome, @nascimento, @login, @senha, @tipo)"; MySqlCommand comando = new MySqlCommand(sql,conexao); comando.Parameters.AddWithValue("@nome", u.nome); comando.Parameters.AddWithValue("@nascimento", u.nascimento); comando.Parameters.AddWithValue("@login", u.login); comando.Parameters.AddWithValue("@senha", u.senha); comando.Parameters.AddWithValue("@tipo", u.tipo); comando.ExecuteNonQuery(); conexao.Close(); } public void Atualiza (Usuario u) { conexao.Open(); string sql = "UPDATE usuarios SET nome = @nome , nascimento = @nascimento, login = @login, senha = @senha, tipo = @tipo WHERE id = @id"; MySqlCommand comando = new MySqlCommand(sql,conexao); comando.Parameters.AddWithValue("@nome", u.nome); comando.Parameters.AddWithValue("@nascimento", u.nascimento); comando.Parameters.AddWithValue("@login", u.login); comando.Parameters.AddWithValue("@senha", u.senha); comando.Parameters.AddWithValue("@tipo", u.tipo); comando.Parameters.AddWithValue("@id", u.id); comando.ExecuteNonQuery(); conexao.Close(); } public List<Usuario> Lista() { conexao.Open(); string sql = "SELECT * FROM usuarios ORDER BY nome"; MySqlCommand comando = new MySqlCommand(sql,conexao); MySqlDataReader reader = comando.ExecuteReader(); List<Usuario> lista = new List<Usuario>(); while(reader.Read()) { Usuario usuario = new Usuario(); usuario.id = reader.GetInt32("id"); if (!reader.IsDBNull(reader.GetOrdinal("nome"))) usuario.nome = reader.GetString("nome"); if (!reader.IsDBNull(reader.GetOrdinal("nascimento"))) usuario.nascimento = reader.GetDateTime("nascimento"); if (!reader.IsDBNull(reader.GetOrdinal("login"))) usuario.login = reader.GetString("login"); if (!reader.IsDBNull(reader.GetOrdinal("senha"))) usuario.senha = reader.GetString("senha"); if (!reader.IsDBNull(reader.GetOrdinal("tipo"))) usuario.tipo = reader.GetBoolean("tipo"); lista.Add(usuario); } conexao.Close(); return lista; } public Usuario Lista(int id) { conexao.Open(); string sql = "SELECT * FROM usuarios WHERE id = " + id; MySqlCommand comando = new MySqlCommand(sql,conexao); MySqlDataReader reader = comando.ExecuteReader(); reader.Read(); Usuario usuario = new Usuario(); usuario.id = reader.GetInt32("id"); if (!reader.IsDBNull(reader.GetOrdinal("nome"))) usuario.nome = reader.GetString("nome"); if (!reader.IsDBNull(reader.GetOrdinal("nascimento"))) usuario.nascimento = reader.GetDateTime("nascimento"); if (!reader.IsDBNull(reader.GetOrdinal("login"))) usuario.login = reader.GetString("login"); if (!reader.IsDBNull(reader.GetOrdinal("senha"))) usuario.senha = reader.GetString("senha"); if (!reader.IsDBNull(reader.GetOrdinal("tipo"))) usuario.tipo = reader.GetBoolean("tipo"); conexao.Close(); return usuario; } public void Apaga(int id) { conexao.Open(); string sql = "DELETE FROM usuarios WHERE id = " + id; MySqlCommand comando = new MySqlCommand(sql,conexao); comando.ExecuteNonQuery(); conexao.Close(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AcademyPopcorn { //Task 12 class GiftBlock : Block { public GiftBlock(MatrixCoords topLeft) : base(topLeft) { this.body = new char[,] { { 'G' } }; } public override void RespondToCollision(CollisionData collisionData) { this.IsDestroyed = true; ProduceObjects(); } public override IEnumerable<GameObject> ProduceObjects() { List<GameObject> list = new List<GameObject>(); if (IsDestroyed) { MovingObject gift01 = new Gift(new MatrixCoords(this.topLeft.Row + 1, this.topLeft.Col)); list.Add(gift01); } return list; } } }
// Copyright 2021 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using NtApiDotNet; using NtApiDotNet.Win32; using NtObjectManager.Utils; using System.Linq; using System.Management.Automation; namespace NtObjectManager.Cmdlets.Win32 { /// <summary> /// <para type="synopsis">Change the configuration of a service.</para> /// <para type="description">This cmdlet changes the configuration of a service either locally /// or remotely.</para> /// </summary> /// <example> /// <code>Set-Win32ServiceConfig -Name "DEMO" -Path "c:\target\path.exe"</code> /// <para>Set the binary path for the service DEMO.</para> /// </example> [Cmdlet(VerbsCommon.Set, "Win32ServiceConfig")] public sealed class SetWin32ServiceConfigCmdlet : PSCmdlet { /// <summary> /// <para type="description">Specify the name of the service.</para> /// </summary> [Parameter(Mandatory = true, Position = 0)] public string Name { get; set; } /// <summary> /// <para type="description">Specify the name of target computer.</para> /// </summary> [Parameter] public string MachineName { get; set; } /// <summary> /// <para type="description">Specify the display name of the service.</para> /// </summary> [Parameter(ParameterSetName = "ChangeConfig")] public string DisplayName { get; set; } /// <summary> /// <para type="description">Specify the type of the service.</para> /// </summary> [Parameter(ParameterSetName = "ChangeConfig")] public ServiceType? Type { get; set; } /// <summary> /// <para type="description">Specify the start type of the service.</para> /// </summary> [Parameter(ParameterSetName = "ChangeConfig")] public ServiceStartType? Start { get; set; } /// <summary> /// <para type="description">Specify error control of the service.</para> /// </summary> [Parameter(ParameterSetName = "ChangeConfig")] public ServiceErrorControl? ErrorControl { get; set; } /// <summary> /// <para type="description">Specify the binary path to the service.</para> /// </summary> [Parameter(ParameterSetName = "ChangeConfig")] public string Path { get; set; } /// <summary> /// <para type="description">Specify the load order tag id.</para> /// </summary> [Parameter(ParameterSetName = "ChangeConfig")] public int? TagId { get; set; } /// <summary> /// <para type="description">Specify the load order group.</para> /// </summary> [Parameter(ParameterSetName = "ChangeConfig")] public string LoadOrderGroup { get; set; } /// <summary> /// <para type="description">Specify list of dependencies.</para> /// </summary> [Parameter(ParameterSetName = "ChangeConfig")] public string[] Dependencies { get; set; } /// <summary> /// <para type="description">Specify the user name for the service.</para> /// </summary> [Parameter(ParameterSetName = "ChangeConfig")] public string UserName { get; set; } /// <summary> /// <para type="description">Specify password for the service user.</para> /// </summary> [Parameter(ParameterSetName = "ChangeConfig")] public PasswordHolder Password { get; set; } /// <summary> /// <para type="description">Specify the service protected type.</para> /// </summary> [Parameter(Mandatory = true, ParameterSetName = "ChangeProtected")] public ServiceLaunchProtectedType LaunchProtected { get; set; } /// <summary> /// <para type="description">Specify the service restricted SID type.</para> /// </summary> [Parameter(Mandatory = true, ParameterSetName = "ChangeSid")] public ServiceSidType SidType { get; set; } /// <summary> /// <para type="description">Specify the service required privilege.</para> /// </summary> [Parameter(Mandatory = true, ParameterSetName = "ChangeRequiredPrivilege")] [AllowEmptyCollection] public TokenPrivilegeValue[] RequiredPrivilege { get; set; } /// <summary> /// Process record. /// </summary> protected override void ProcessRecord() { switch (ParameterSetName) { case "ChangeConfig": ServiceUtils.ChangeServiceConfig(MachineName, Name, DisplayName, Type, Start, ErrorControl, Path, TagId, LoadOrderGroup, Dependencies, UserName, Password?.Password); break; case "ChangeProtected": ServiceUtils.SetServiceLaunchProtected(MachineName, Name, LaunchProtected); break; case "ChangeSid": ServiceUtils.SetServiceSidType(MachineName, Name, SidType); break; case "ChangeRequiredPrivilege": ServiceUtils.SetServiceRequiredPrivileges(MachineName, Name, RequiredPrivilege.Select(p => p.ToString()).ToArray()); break; } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class BossDoor : MonoBehaviour { #region OldCode //[SerializeField] public RoomHandle MyRoom; //[SerializeField] public Transform MyExit; //[SerializeField] BossDoor Target; //RoomManagement Manager; //private void Start() //{ // MyRoom = GetComponentInParent<RoomHandle>(); // Manager = FindObjectOfType<RoomManagement>(); // if (Target != null) // { // Target.SetTarget(this); // } //} //private void OnTriggerEnter2D(Collider2D collision) //{ // if (collision.tag == "Player") // { // Manager.UpdateRoom(Target); // } //} //public void SetTarget(BossDoor Partner) //{ // Target = Partner; //} [SerializeField] int BossScene = 0; //LoadingSceneManager loadingManager = null; private void OnTriggerEnter2D(Collider2D collision) { if (collision.CompareTag("Player")) { LoadingSceneManager.LoadScene(BossScene); } } #endregion }
using System; using Xamarin.Forms; using Xamarin.Forms.Xaml; using Industrial.Services; using Industrial.Views; using Industrial.Services.SupplyService; namespace Industrial { public partial class App : Application { public static SupplyManager supplyManager { get; private set; } public App() { InitializeComponent(); supplyManager = new SupplyManager(new SupplyRest()); DependencyService.Register<MockDataStore>(); MainPage = new AppShell(); } protected override void OnStart() { } protected override void OnSleep() { } protected override void OnResume() { } } }
using NUnit.Framework; using System; namespace TestsPayroll.Taxing.HappyTests { [TestFixture()] public class TaxAdvancePaymentHappyTest { [Test()] public void AdvanceTax_Payment_For_2_000_CZK_Base_Is_X_CZK() { } [Test()] public void AdvanceTax_Payment_For_10_000_CZK_Base_Is_X_CZK() { } [Test()] public void AdvanceTax_Payment_For_Negative_Base_Is_ZERO_CZK() { } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class LocationUpdateManager : MonoBehaviour { public Camera mainCamera; public Text xLocation; public Text yLocation; public Text zLocation; // Use this for initialization void Start () { } // Update is called once per frame void Update () { if (mainCamera != null){ xLocation.text = Camera.main.transform.position.x.ToString(); yLocation.text = Camera.main.transform.position.y.ToString(); zLocation.text = Camera.main.transform.position.z.ToString(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; //Task 13 namespace Binary_to_Decimal_Number_System { class Program { static void Main(string[] args) { Console.Write("Enter number: "); int n = int.Parse(Console.ReadLine()); double resultNum = 0; int count = 0; while (n > 0) { resultNum += (n % 10) * (Math.Pow(2, count)); n /= 10; count++; } Console.WriteLine(resultNum); } } }
using System; using System.Collections.Generic; using System.Collections.Concurrent; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Media; namespace Gensokyo.Xaml.Converters { static class ColorConverters { internal static readonly ConcurrentDictionary<Color , Brush> BrushCache = new ConcurrentDictionary<Color, Brush>(); internal static readonly ConcurrentDictionary<Brush , Color> StringCache = new ConcurrentDictionary<Brush, Color>(); } }
 using PyFarmaceutica.acceso_a_datos.implementaciones; using PyFarmaceutica.acceso_a_datos.interfaces; using PyFarmaceutica.Reportes; using PyFarmaceutica.Reportes.entidades; using PyFarmaceutica.servicios.interfaces; using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PyFarmaceutica.servicios.implementaciones { public class ServiceReporte : IServiceReporte { private IReporteDao reporteDao; public ServiceReporte() { reporteDao = new ReporteDao(); } public List<Año> GetAños() { List<Año> Lista_obj_año = new List<Año>(); foreach (DataRow item in reporteDao.AñosFacturados().Rows) { Año obj_año = new Año() { Anio = Convert.ToInt32(item.ItemArray[0]) }; Lista_obj_año.Add(obj_año); } return Lista_obj_año; } public List<ReporteCantidadVentas_Suministro> GetCantidadVentas_Suministros() { List<ReporteCantidadVentas_Suministro> Lista_obj_cantidad_ventas_suministro = new List<ReporteCantidadVentas_Suministro>(); foreach (DataRow item in reporteDao.ReporteCantidadVentas_Suministro().Rows) { ReporteCantidadVentas_Suministro obj_cantidad_ventas_suministro = new ReporteCantidadVentas_Suministro() { IdSuministro = Convert.ToInt32(item.ItemArray[0]), Suministro= item.ItemArray[1].ToString(), Cantidad= Convert.ToInt32(item.ItemArray[2]), Monto = Convert.ToInt32(item.ItemArray[3]) }; Lista_obj_cantidad_ventas_suministro.Add(obj_cantidad_ventas_suministro); } return Lista_obj_cantidad_ventas_suministro; } public List<ReporteFacturacionTotal_Mes> GetReporteFacturacionTotal_Mes(Año anio) { List<ReporteFacturacionTotal_Mes> Lista_obj_facturacion_mes = new List<ReporteFacturacionTotal_Mes>(); foreach (DataRow item in reporteDao.ReporteFacturacion_Mes(anio).Rows) { ReporteFacturacionTotal_Mes obj_facturacion_mes = new ReporteFacturacionTotal_Mes() { Mes = item.ItemArray[0].ToString(), NroFactura = Convert.ToInt32(item.ItemArray[1]), Fecha= Convert.ToDateTime(item.ItemArray[2].ToString()), Total=Convert.ToDouble(item.ItemArray[3]) }; Lista_obj_facturacion_mes.Add(obj_facturacion_mes); } return Lista_obj_facturacion_mes; } } }
using System.Collections.Generic; namespace FileUploadNetCore.Models { public class FileUploadViewModel { public List<FileOnFileSystemModel> FilesOnFileSystem { get; set; } public List<FileOnDatabaseModel> FilesOnDatabase { get; set; } } }
using System; using System.ComponentModel; using System.IO; using System.Runtime.CompilerServices; using AnyfinCalculator.Annotations; using Hearthstone_Deck_Tracker; namespace AnyfinCalculator { [Serializable] public class AnyfinConfig : INotifyPropertyChanged { [NonSerialized] public static readonly string ConfigLocation = Path.Combine(Config.Instance.DataDir, "anyfin.xml"); private double _iconX; private double _iconY; public AnyfinConfig() { IconX = 83.5; IconY = 69.5; } [DefaultValue(false)] public bool ClassicMode { get; set; } public double IconX { get { return _iconX; } set { if (value == _iconX) return; _iconX = value; OnPropertyChanged(); } } public double IconY { get { return _iconY; } set { if (value == _iconY) return; _iconY = value; OnPropertyChanged(); } } public event PropertyChangedEventHandler PropertyChanged; [NotifyPropertyChangedInvocator] protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } }
using FluentValidation; namespace Application.Product.Commands.CreateProductCommands { public class CreateProductCommandValidator : AbstractValidator<CreateProductCommand> { public CreateProductCommandValidator () { RuleFor (v => v.Product.CategoryName) .NotEmpty ().WithMessage ("Category Is Required") .NotNull ().WithMessage ("Category Is Required"); RuleFor (v => v.Product.Cost) .NotNull ().WithMessage ("Cost Is Required"); RuleFor (v => v.Product.IsAvailable) .NotNull ().WithMessage ("IsAvailable is Required"); RuleFor (v => v.Product.ProductName) .NotEmpty ().WithMessage ("ProductName Is Required") .NotNull ().WithMessage ("ProductName Is Required"); RuleFor (v => v.Product.Stock) .NotNull ().WithMessage ("Stock Is Required"); RuleFor (v => v.Product.VariantName) .NotEmpty ().WithMessage ("VariantName Is Required") .NotNull ().WithMessage ("VariantName Is Required"); RuleFor (v => v.Product.Description) .NotEmpty ().WithMessage ("Description Is Required") .NotNull ().WithMessage ("Description Is Required"); RuleFor (v => v.Image) .NotEmpty ().WithMessage ("Image is required"); } } }
namespace PrimeNumbersSieveOfEratosthenes { using System; using System.Collections; using System.Collections.Generic; public class PrimeNumbersSieveOfEratosthenes { /// <summary> /// Write a program that finds all prime numbers in the range [1...10 000 000]. Use the sieve of Eratosthenes algorithm. /// </summary> public static void Main(string[] args) { uint maxNumber = 10000000; List<int> primeNumbers = GetPrimeNumbersSieveOfEratosthenes(maxNumber); foreach (int primeNumber in primeNumbers) { Console.Write(primeNumber + " "); } Console.WriteLine("Prime Numbers Count = " + primeNumbers.Count); } public static List<int> GetPrimeNumbersSieveOfEratosthenes(uint maxNumber) { BitArray primeNumbers = new BitArray((int)maxNumber, true); int currentNumber = 1; int currentNumberSquare = 1; while (currentNumberSquare <= maxNumber) { currentNumber++; while (!primeNumbers[currentNumber]) { currentNumber++; } currentNumberSquare = currentNumber * currentNumber; for (int i = currentNumberSquare; i < maxNumber; i += currentNumber) { if (i > 0) { primeNumbers[i] = false; } } } List<int> primeNumbersList = new List<int>(); for (int i = 2; i < maxNumber; i++) { if (primeNumbers[i]) { primeNumbersList.Add(i); } } return primeNumbersList; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; namespace Framework.Remote.Mobile { [DataContract(Name = "CxClientImageMetadata", Namespace = "http://schemas.datacontract.org/2004/07/FulcrumWeb")] public partial class CxClientImageMetadata { [DataMember] public readonly string Id; [DataMember] public readonly string ProviderClassId; [DataMember] public readonly int ImageIndex; public readonly string FileName; public readonly string Folder; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class FinishScript : MonoBehaviour { public CrosserSpawn crosserSpawn; void OnTriggerEnter(Collider col) { if (col.tag == "Crosser") { crosserSpawn.ReturnedCrosser(); } } }
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 BLL_DAL; using System.IO; namespace QLNHAHANG { public partial class frmSanPham : Form { SanPham_BLL_DAL sp_bll = new SanPham_BLL_DAL(); List<NGUYENLIEU> lstNL = new List<NGUYENLIEU>(); List<NGUYENLIEU> lstNLHienTai; bool checkThem = false; bool checkSua = false; bool checkXoa = false; public frmSanPham() { InitializeComponent(); loadCBLoai(); lstNL = sp_bll.LayTatCaNguyenLieu(); thietlapcontrol(); gvNguyenLieu.MultiSelect = false; gvNguyenLieu.MultiSelect = false; gvSanPham.MultiSelect = false; } public void thietlapcontrol() { //foreach (Control item in pnControlSP.Controls) //{ // if (item.Name == groupMaLoai.Name) // continue; // item.Enabled = false; //} btnXoa.Enabled = false; btnLuu.Enabled = false; btnThemNL.Enabled = false; btnXoaNL.Enabled = false; btnThem.Enabled = true; gvSanPham.Enabled = true; btnSua.Enabled = true; } public void loadCBLoai() { cbMaLoai.DataSource = sp_bll.loadAllLoai(); cbMaLoai.ValueMember = "MALSP"; cbMaLoai.DisplayMember = "TENLSP"; } public void loadGridViewSP(List<SANPHAM> sp) { gvSanPham.DataSource = sp; //gvSPDataBinding(); } public void loadTatCaSP(string maloai) { List<SANPHAM> lstSP = sp_bll.getALLSanPhamByLoai(maloai).ToList(); loadGridViewSP(lstSP); } //List nguyên liệu có trong sanpham public List<NGUYENLIEU> lstNLCuaSP() { List<NGUYENLIEU> lst = new List<NGUYENLIEU>(); gvNL_SP.AllowUserToAddRows = false; if (gvNL_SP.Rows.Count == 0) { gvNL_SP.AllowUserToAddRows = true; return lst; } foreach (DataGridViewRow item in gvNL_SP.Rows) { NGUYENLIEU nl = lstNL.Single(t => t.MANL == item.Cells["MANL"].Value.ToString()); lst.Add(nl); } return lst; } // List Nhung nguyen lieu trong thuoc san pham do public List<NGUYENLIEU> lstNL_KoThuocSP() { List<NGUYENLIEU> lstcuasp = lstNLCuaSP(); List<NGUYENLIEU> lstkocuasp = new List<NGUYENLIEU>(); foreach (NGUYENLIEU item in lstNL) { if (!lstcuasp.Contains(item)) { lstkocuasp.Add(item); } } return lstkocuasp; } public void LoadGVSP_NL(string maSP) { gvNL_SP.DataSource = sp_bll.laySP_NL(maSP); gvNguyenLieu.DataSource = lstNL_KoThuocSP(); } private void gvSanPham_SelectionChanged(object sender, EventArgs e) { btnXoa.Enabled = true; try { string hinh = gvSanPham.CurrentRow.Cells["HINHANH"].Value.ToString(); //pcSp.Image = Image.FromFile("../../img/img_sanpham/" + hinh); pcSp.LoadAsync(hinh); //pcSp.Image.Save("../../img/img_sanpham/" + hinh, System.Drawing.Imaging.ImageFormat.Jpeg); string masp = gvSanPham.CurrentRow.Cells[0].Value.ToString(); LoadGVSP_NL(masp); } catch (Exception) { pcSp.Image = null; return; throw; } } private void frmSanPham_Resize(object sender, EventArgs e) { btnspace.Width = gvSanPham.Width; } private void frmSanPham_Load(object sender, EventArgs e) { gvSanPham.DataSource = sp_bll.getALLSPGV(); cbMaLoai.DataSource = sp_bll.loadAllLoai(); bindingSP(0); setHeaderSP(); setHeaderNL_SP(); setHeaderNL(); btnXoa.Enabled = false; btnSua.Enabled = false; btnLamMoi.Enabled = true; btnChonHinh.Enabled = false; txtMa.Enabled = false; txtTen.Enabled = false; cbMaLoai.Enabled = false; cbTinhTrang.Enabled = false; txtGia.Enabled = false; } private void cbMaLoai_SelectedIndexChanged(object sender, EventArgs e) { } private void txtGia_KeyPress(object sender, KeyPressEventArgs e) { if (!Char.IsDigit(e.KeyChar) && !Char.IsControl(e.KeyChar)) { e.Handled = true; } } private void gvNL_SP_CellContentClick(object sender, DataGridViewCellEventArgs e) { } private bool kiemtraControl() { if (txtGia.Text == string.Empty || txtMa.Text == string.Empty || txtGia.Text == string.Empty) { return false; } return true; } public void bindingSP(int rowindex) { txtMa.Text = gvSanPham.Rows[rowindex].Cells[0].FormattedValue.ToString(); txtTen.Text = gvSanPham.Rows[rowindex].Cells[1].FormattedValue.ToString(); txtGia.Text = gvSanPham.Rows[rowindex].Cells[3].FormattedValue.ToString(); var a = gvSanPham.Rows[rowindex].Cells["MALSP"].FormattedValue.ToString(); cbMaLoai.SelectedValue = gvSanPham.Rows[rowindex].Cells["MALSP"].FormattedValue.ToString(); cbTinhTrang.SelectedIndex = gvSanPham.Rows[rowindex].Cells["TRANGTHAI"].FormattedValue.ToString() == "Bán" ? 0 : 1; //string pathImage = Application.StartupPath + "\\img\\img_sanpham\\"+ gvSanPham.CurrentRow.Cells["HINHANH"].Value.ToString()+".jpg"; //pcSp.Image = new Bitmap(pathImage); //gvNL_SP.DataSource = sp_bll.laySP_NL(txtMa.Text); LoadGVSP_NL(txtMa.Text); foreach (DataGridViewRow item in gvSanPham.SelectedRows) { try { pcSp.Image = Image.FromFile("../../img/img_sanpham/" + gvSanPham.CurrentRow.Cells["HINHANH"].Value.ToString()); pcSp.Tag = "../../img/img_sanpham/" + gvSanPham.CurrentRow.Cells["HINHANH"].Value.ToString(); } catch (Exception) { return; throw; } } } private void gvSanPham_CellClick(object sender, DataGridViewCellEventArgs e) { btnSua.Enabled = true; try { if (gvSanPham.Rows[e.RowIndex].Cells[e.ColumnIndex].Value != null) { gvSanPham.CurrentRow.Selected = true; bindingSP(e.RowIndex); } } catch { return; } } private void btnThem_Click(object sender, EventArgs e) { txtMa.Enabled = false; cbMaLoai.Enabled = true; cbTinhTrang.SelectedValue = "Bán"; txtGia.Enabled = true; btnChonHinh.Enabled = true; txtTen.Enabled = true; cbTinhTrang.Enabled = true; checkThem = true; checkSua = false; checkXoa = false; foreach (Control item in pnControlSP.Controls) { // khong cho nha maSP if (item.Name == "gbMSP") { continue; } else item.Enabled = true; } resetControlKhiThem(); } private string taoMaSPMoi() { return "SP000" + gvSanPham.Rows.Count.ToString(); } private List<CT_SANPHAM_NGUYENLIEU> loadNL_SP() { List<CT_SANPHAM_NGUYENLIEU> lst_nlsp = new List<CT_SANPHAM_NGUYENLIEU>(); foreach (NGUYENLIEU item in lstNLHienTai) { CT_SANPHAM_NGUYENLIEU nlsp = new CT_SANPHAM_NGUYENLIEU(); nlsp.MANL = item.MANL; nlsp.MASP = txtMa.Text; nlsp.SOLUONG = 1; lst_nlsp.Add(nlsp); } return lst_nlsp; } private void resetControlKhiThem() { txtMa.Text = taoMaSPMoi(); txtGia.Text = ""; txtTen.Text = ""; btnThemNL.Enabled = true; btnXoaNL.Enabled = true; btnLuu.Enabled = true; gvSanPham.Enabled = false; btnSua.Enabled = false; btnXoa.Enabled = false; lstNLHienTai = new List<NGUYENLIEU>(); gvNL_SP.DataSource = loadNL_SP(); gvNguyenLieu.DataSource = lstNL; pcSp.Image = null; } private void btnXoa_Click(object sender, EventArgs e) { checkXoa = true; checkThem = false; checkSua = false; btnThem.Enabled = false; btnSua.Enabled = false; if (gvSanPham.SelectedRows.Count == 0) { MessageBox.Show("Chưa chọn sản phẩm để sửa"); return; } DialogResult rs = MessageBox.Show("Bạn có chắc muốn xóa sản phẩm (" + txtTen.Text + ")", "Xác nhận", MessageBoxButtons.YesNo); if (rs == DialogResult.Yes) { bool check = sp_bll.xoaSP(txtMa.Text); if (check) { MessageBox.Show("Xóa thành công"); } else { MessageBox.Show("Xóa thất bại"); } gvSanPham.DataSource = sp_bll.getALLSP(); thietlapcontrol(); } frmSanPham_Load(sender, e); } private void btnSua_Click(object sender, EventArgs e) { txtTen.Enabled = true; cbTinhTrang.Enabled = true; txtGia.Enabled = true; cbMaLoai.Enabled = true; btnChonHinh.Enabled = true; if (gvSanPham.SelectedRows.Count == 0) { MessageBox.Show("Chưa chọn sản phẩm để sửa"); return; } gvSanPham.Enabled = false; checkSua = true; checkThem = false; checkXoa = true; foreach (Control item in pnControlSP.Controls) { // khong cho nha maSP if (item.Name == "gbMSP") { continue; } else item.Enabled = true; } lstNLHienTai = lstNLCuaSP(); btnXoa.Enabled = false; btnThem.Enabled = false; btnThemNL.Enabled = true; btnXoaNL.Enabled = true; btnLuu.Enabled = true; } private void btnThemNL_Click(object sender, EventArgs e) { if (gvNguyenLieu.SelectedRows == null) { MessageBox.Show("Chưa chọn nguyện liệu"); } foreach (DataGridViewRow item in gvNguyenLieu.SelectedRows) { NGUYENLIEU nl = lstNL.Single(t => t.MANL == item.Cells["MANL"].Value.ToString()); lstNLHienTai.Add(nl); gvNL_SP.DataSource = loadNL_SP(); gvNguyenLieu.DataSource = lstNL_KoThuocSP(); } } private void btnXoaNL_Click(object sender, EventArgs e) { lstNLHienTai.Remove(lstNLHienTai.SingleOrDefault(t => t.MANL == gvNL_SP.CurrentRow.Cells["MANL"].Value.ToString())); gvNL_SP.DataSource = loadNL_SP(); gvNguyenLieu.DataSource = lstNL_KoThuocSP(); } private void btnLuu_Click(object sender, EventArgs e) { if (kiemtraControl() == false) { MessageBox.Show("Nhập chưa đầy đủ"); return; } SANPHAM sp = new SANPHAM(); sp.MASP = txtMa.Text; sp.TENSP = txtTen.Text; sp.TRANGTHAI = cbTinhTrang.Text; sp.MALSP = cbMaLoai.SelectedValue.ToString(); sp.GIABAN = Convert.ToInt64(txtGia.Text); try { sp.HINHANH = pcSp.Tag.ToString(); } catch (Exception) { sp.HINHANH = "no-image.jpg"; } List<CT_SANPHAM_NGUYENLIEU> lstNLSP = loadNL_SP(); if (checkThem == true) { bool check = sp_bll.themSanPham(sp, lstNLSP); if (check) { MessageBox.Show("Thêm thành công"); } else { MessageBox.Show("Thêm thất bại"); } gvSanPham.Enabled = true; checkThem = false; } else if (checkSua == true) { bool check = sp_bll.suaSanPham(sp, lstNLSP); if (check) { MessageBox.Show("Sửa thành công"); } else { MessageBox.Show("Sửa thất bại"); } gvSanPham.Enabled = true; checkSua = false; } else { checkXoa = false; } sp_bll.submitChange(); btnLuu.Enabled = false; thietlapcontrol(); frmSanPham_Load(sender, e); } private void btnLamMoi_Click(object sender, EventArgs e) { thietlapcontrol(); frmSanPham_Load(sender, e); } public void setHeaderSP() { //gvSanPham.Columns["MASP"].HeaderText = "Mã sản phẩm"; //gvSanPham.Columns["TENSP"].HeaderText = "Tên sản phẩm"; //gvSanPham.Columns["GIABAN"].HeaderText = "Giá"; //gvSanPham.Columns["TRANGTHAI"].HeaderText = "Tình trạng"; gvSanPham.Columns["MALSP"].HeaderText = "Loại"; gvSanPham.Columns["MALSP"].Visible = true; gvSanPham.Columns["TENLSP"].Visible = false; gvSanPham.Columns["LOAISP"].Visible = false; gvSanPham.Columns["HINHANH"].Visible = false; } public void setHeaderNL_SP() { // gvNL_SP.Columns["MASP"].HeaderText = "Mã sản phẩm"; // gvNL_SP.Columns["MALSP"].Visible = true; // gvSanPham.Columns["TENLSP"].Visible = false; gvNL_SP.Columns["NGUYENLIEU"].Visible = false; gvNL_SP.Columns["SANPHAM"].Visible = false; } public void setHeaderNL() { gvNguyenLieu.Columns["MANL"].HeaderText = "Mã nguyên liệu"; gvNguyenLieu.Columns["TENNL"].HeaderText = "Tên nguyên liệu"; //gvNguyenLieu.Columns["SOLUONG"].HeaderText = "Số lượng"; gvNguyenLieu.Columns["MALNL"].Visible = false; gvNguyenLieu.Columns["MANL"].Visible = false; gvNguyenLieu.Columns["LOAINL"].Visible = false; gvNguyenLieu.Columns["HSD"].Visible = false; } private void gvSanPham_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e) { string RowNumber = (e.RowIndex + 1).ToString(); SizeF size = e.Graphics.MeasureString(RowNumber, this.Font); if (gvSanPham.RowHeadersWidth < (int)(size.Width + 20)) gvSanPham.RowHeadersWidth = (int)(size.Width + 20); Brush b = SystemBrushes.ControlText; e.Graphics.DrawString(RowNumber, this.Font, b, e.RowBounds.Location.X + 15, e.RowBounds.Location.Y + ((e.RowBounds.Height - size.Height) / 2)); } private void guna2TextBox1_TextChanged(object sender, EventArgs e) { if (guna2TextBox1.Text.Length == 0) { gvSanPham.DataSource = sp_bll.getALLSPGV(); } else { gvSanPham.DataSource = sp_bll.loadGridViewTimKiemSanPham(guna2TextBox1.Text); } } private void txtTimNL_TextChanged(object sender, EventArgs e) { if (txtTimNL.Text.Length == 0) { gvNguyenLieu.DataSource = lstNL_KoThuocSP(); } else { gvNguyenLieu.DataSource = sp_bll.loadGridViewTimKiemNguyenLieu(txtTimNL.Text); } } private void gvNL_SP_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e) { string RowNumber = (e.RowIndex + 1).ToString(); SizeF size = e.Graphics.MeasureString(RowNumber, this.Font); if (gvSanPham.RowHeadersWidth < (int)(size.Width + 20)) gvSanPham.RowHeadersWidth = (int)(size.Width + 20); Brush b = SystemBrushes.ControlText; e.Graphics.DrawString(RowNumber, this.Font, b, e.RowBounds.Location.X + 15, e.RowBounds.Location.Y + ((e.RowBounds.Height - size.Height) / 2)); } private void gvNguyenLieu_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e) { string RowNumber = (e.RowIndex + 1).ToString(); SizeF size = e.Graphics.MeasureString(RowNumber, this.Font); if (gvSanPham.RowHeadersWidth < (int)(size.Width + 20)) gvSanPham.RowHeadersWidth = (int)(size.Width + 20); Brush b = SystemBrushes.ControlText; e.Graphics.DrawString(RowNumber, this.Font, b, e.RowBounds.Location.X + 15, e.RowBounds.Location.Y + ((e.RowBounds.Height - size.Height) / 2)); } private void btnChonHinh_Click(object sender, EventArgs e) { pickAsync(); } private async void pickAsync() { string path = String.Empty; string imageURL = String.Empty; OpenFileDialog open = new OpenFileDialog(); // image filters open.Filter = "Image Files(*.jpg; *.jpeg; *.gif; *.bmp)|*.jpg; *.jpeg; *.gif; *.bmp"; if (open.ShowDialog() == DialogResult.OK) { path = open.FileName; // display image in picture box pcSp.Image = new Bitmap(open.FileName); // image file path if (!string.IsNullOrEmpty(path)) { imageURL = await Utils.addProductImage(path); pcSp.Load(imageURL); pcSp.Tag = imageURL; } } } private void btnReport_Click(object sender, EventArgs e) { frm_rpSanPham rp = new frm_rpSanPham(); rp.Show(); } } }
// Copyright (c) 2007 - Dave Kerr // http://www.dopecode.co.uk // // // This file is part of SharpGL. // // SharpGL is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 3 of the License, or // (at your option) any later version. // // SharpGL is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // // If you are using this code for commerical purposes then you MUST // purchase a license. See http://www.dopecode.co.uk for details. using System; using System.Windows.Forms; using System.Collections; using SharpGL.SceneGraph; namespace SharpGL.SceneGraph.Interaction { public class Click { public Click(OpenGL gl, MouseEventArgs args) { this.args = args; GDIx = OpenGLx = args.X; GDIy = OpenGLy = args.Y; gl.GDItoOpenGL(ref OpenGLx, ref OpenGLy); } public int GDIx = 0; public int GDIy = 0; public int OpenGLx = 0; public int OpenGLy = 0; public Vertex vertex = null; public MouseEventArgs args; } public class ClickCollection : CollectionBase { public ClickCollection(){} public virtual void Add(Click value) { List.Add(value); } public virtual void AddRange(IList list) { foreach(Click click in list) List.Add(click); } public virtual Click this[int index] { get {return (Click)List[index];} set {List[index] = value;} } public virtual void Remove(Click value) { List.Remove(value); } } public class BuildingGrid { public BuildingGrid() { } public virtual void Clamp(Vertex v) { float diff = v.X % size; if(diff > size/2) diff -=size; v.X -= diff; diff = v.Y % size; if(diff > size/2) diff -=size; v.Y -= diff; diff = v.Z % size; if(diff > size/2) diff -=size; v.Z -= diff; } protected float size = 0.2f; } /// <summary> /// A Builder is an object that is used to build a SceneObject /// specifically using the mouse. /// </summary> public abstract class Builder { public Builder() { } /// <summary> /// This function is called when the user clicks /// in the window. /// </summary> /// <param name="e"></param> /// <param name="gl"></param> /// <returns>An object if the object is finished building.</returns> public virtual SceneObject OnMouseDown(OpenGL gl, MouseEventArgs e) { clicks.Add(new Click(gl, e)); return null; } public virtual SceneObject OnMouseUp(OpenGL gl, MouseEventArgs e) { return null; } /// <summary> /// Update the mouse movement. /// </summary> /// <param name="gl"></param> /// <param name="e"></param> /// <returns>True if a redraw is needed.</returns> public virtual bool OnMouseMove(OpenGL gl, MouseEventArgs e) { return false; } public virtual void Draw(OpenGL gl) { if(buildingObject != null) buildingObject.Draw(gl); } /// <summary> /// This is a utility function that will turn a click /// on the control to a point on a specified plane. /// </summary> /// <param name="gl">OpenGL.</param> /// <param name="plane">The plane to project onto.</param> /// <param name="x">The X part of the point.</param> /// <param name="y">The Y part of the point.</param> /// <returns>A three-tuple representing the point on the floor.</returns> protected Vertex PointToVertexOnPlane(OpenGL gl, Plane plane, int x, int y) { // The first thing we do is turn the click into a vector that // is from the camera to the cursor. double[] point1 = gl.UnProject((double)x, (double)y, 0); double[] point2 = gl.UnProject((double)x, (double)y, 1); double[] direction = {point2[0] - point1[0], point2[1] - point1[1], point2[2] - point1[2]}; // Now we find out the position when the line intersects the // ground level. if(direction[1] == 0) return null; double dist = 0; switch(plane) { case Plane.xy: dist = -1.0 * point1[2] / direction[2]; break; case Plane.xz: dist = -1.0 * point1[1] / direction[1]; break; case Plane.yz: dist = -1.0 * point1[0] / direction[0]; break; } double px = point1[0] + dist*direction[0]; double py = point1[1] + dist*direction[1]; double pz = point1[2] + dist*direction[2]; return new Vertex((float)px, (float)py, (float)pz); } public enum Plane { xy, xz, yz, } #region Member Data /// <summary> /// This is the object that the builder is currently /// building. /// </summary> protected SceneObject buildingObject = null; /// <summary> /// This collection maintains data about where the user /// has clicked. /// </summary> protected ClickCollection clicks = new ClickCollection(); #endregion } public class SphereBuilder : Builder { public SphereBuilder() { } public override SceneObject OnMouseDown(OpenGL gl, MouseEventArgs e) { base.OnMouseDown(gl, e); // When the user presses the mouse down, we create the centre of the // sphere. buildingObject = new Quadrics.Sphere(); Vertex v = PointToVertexOnPlane(gl, Plane.xz, clicks[0].OpenGLx, clicks[0].OpenGLy); BuildingGrid grid = new BuildingGrid(); grid.Clamp(v); if(v != null) { clicks[0].vertex = v; buildingObject.Translate = v; } return null; } public override bool OnMouseMove(OpenGL gl, MouseEventArgs e) { // We only update the radius if the left button is // down, and the buildingObject isn't null. Click click = new Click(gl, e); if(e.Button == MouseButtons.Left) { // If we have clicked once, then we are setting the radius. Vertex v = PointToVertexOnPlane(gl, Plane.xz, click.OpenGLx, click.OpenGLy); if(v != null) { Vertex v2 = clicks[0].vertex; BuildingGrid grid = new BuildingGrid(); grid.Clamp(v); grid.Clamp(v2); Vertex between = v - v2; ((Quadrics.Sphere)buildingObject).Radius = between.Magnitude(); } buildingObject.Modified = true; return true; } return base.OnMouseMove (gl, e); } public override SceneObject OnMouseUp(OpenGL gl, MouseEventArgs e) { base.OnMouseUp(gl, e); OnMouseMove(gl, e); return buildingObject; } } public class PlaneBuilder : Builder { public PlaneBuilder() { Polygon plane = new Polygon(); plane.Vertices.Add(new Vertex()); plane.Vertices.Add(new Vertex()); plane.Vertices.Add(new Vertex()); plane.Vertices.Add(new Vertex()); plane.UVs.Add(new UV(0, 0)); plane.UVs.Add(new UV(0, 1)); plane.UVs.Add(new UV(1, 1)); plane.UVs.Add(new UV(1, 0)); Face face = new Face(); face.Indices.Add(new Index(2, 0)); face.Indices.Add(new Index(3, 1)); face.Indices.Add(new Index(1, 2)); face.Indices.Add(new Index(0, 3)); plane.Faces.Add(face); buildingObject = plane; } public override SceneObject OnMouseDown(OpenGL gl, MouseEventArgs e) { base.OnMouseDown(gl, e); Polygon plane = (Polygon)buildingObject; // When the user presses the mouse down, we create the corner // of the plane. Vertex v = PointToVertexOnPlane(gl, Plane.xz, clicks[0].OpenGLx, clicks[0].OpenGLy); BuildingGrid grid = new BuildingGrid(); grid.Clamp(v); if(v != null) { plane.Vertices[0] = v; } return null; } public override bool OnMouseMove(OpenGL gl, MouseEventArgs e) { // We only update the radius if the left button is // down, and the buildingObject isn't null. Polygon plane = (Polygon)buildingObject; Click click = new Click(gl, e); if(e.Button == MouseButtons.Left) { // If we have clicked once, then we are setting the other corner. Vertex v = PointToVertexOnPlane(gl, Plane.xz, click.OpenGLx, click.OpenGLy); if(v != null) { BuildingGrid grid = new BuildingGrid(); grid.Clamp(v); Vertex v0 = plane.Vertices[0]; Vertex v3 = plane.Vertices[3] = v; plane.Vertices[1].Set(v3.X, 0, v0.Z); plane.Vertices[2].Set(v0.X, 0, v3.Z); } buildingObject.Modified = true; return true; } return base.OnMouseMove (gl, e); } public override SceneObject OnMouseUp(OpenGL gl, MouseEventArgs e) { base.OnMouseUp(gl, e); OnMouseMove(gl, e); return buildingObject; } } public class PolygonBuilder : Builder { public override SceneObject OnMouseDown(OpenGL gl, MouseEventArgs e) { base.OnMouseDown(gl, e); // Every time the left mouse button is cliced, a new point // is added. The first time the right button is clicked // completes the polygon, the second time sweeps it. if(e.Button == MouseButtons.Left) { // Add this click as a point. Click click = clicks[clicks.Count-1]; click.vertex = PointToVertexOnPlane(gl, Plane.xz, click.OpenGLx, click.OpenGLy); } return null; } public override bool OnMouseMove(OpenGL gl, MouseEventArgs e) { Click click = new Click(gl, e); return base.OnMouseMove (gl, e); } public override void Draw(OpenGL gl) { // Draw each point and the lines between them. base.Draw (gl); } } }
using System.Collections; using System.Collections.Generic; using static AudioManager; using UnityEngine; public class PlayerMove : MonoBehaviour { public int playerNum; private GameObject crosshairHolder; // The object on the center of the player that controls crosshair placement [SerializeField] private AudioClip knifeThrow, knifeDeflect; /* // If needed, a sprite that shows them dead [SerializeField] private Sprite player_dead; */ public bool canDash; private Rigidbody2D myRigidBody; private BoxCollider2D[] myCollider; private Animator anim; public float movementSpeed; private bool isDead; private string hor, vert, rotx, roty, a, b, x, y, shoot, dash; /// <summary>If the inversion is on, change this to -1</summary> public int inversion = 1; [SerializeField] private GameObject knife; public float resetCD = 0.5f; private float fireCooldown; private bool canFire; public bool multiShot, pierceShot; // Use this for initialization void Start() { myRigidBody = GetComponent<Rigidbody2D>(); myCollider = GetComponents<BoxCollider2D>(); crosshairHolder = transform.GetChild(0).gameObject; Debug.Assert(crosshairHolder != null); // Checks to ensure it's not null SetPlayerControls(); movementSpeed = 5f; canFire = true; canDash = false; anim = GetComponent<Animator>(); } // Update is called once per frame void Update() { } /// <summary> /// Initializes the player controls /// </summary> private void SetPlayerControls() { //Use format p1_horizontal, p2_horizontal, so player number is used to set controls hor = SetInputString("Horizontal"); vert = SetInputString("Vertical"); rotx = SetInputString("RotateX"); roty = SetInputString("RotateY"); shoot = SetInputString("Fire"); dash = SetInputString("Dash"); } /// <summary>Cleaner function for setting the string, it just sets it as "inputtype" + playernum</summary> /// <param name="inputStart">Input Type String first part</param> /// <returns>Input String in its entirety</returns> private string SetInputString(string inputStart) { return inputStart + playerNum.ToString(); } void FixedUpdate() { Dash(); if (Input.GetAxis(shoot) > 0) { Shoot(); } if (fireCooldown > 0) { fireCooldown -= Time.deltaTime; if (fireCooldown <= 0) { canFire = true; } } // If they are dead, freeze them (movement speed set to 0 if we want to switch to dead sprite) if (isDead == true) { movementSpeed = 0; myRigidBody.velocity = Vector2.zero; } if (isDead == false) { Turn(); float horizontal = Mathf.Round(Input.GetAxis(hor) * inversion); float vertical = Mathf.Round(Input.GetAxis(vert) * inversion); myRigidBody.velocity = new Vector2(horizontal * movementSpeed, myRigidBody.velocity.y); myRigidBody.velocity = new Vector2(myRigidBody.velocity.x, vertical * movementSpeed); //Flip sprite if(horizontal > 0) { transform.rotation = Quaternion.Euler(new Vector3(0, 180, 0)); } else { transform.rotation = Quaternion.identity; } anim.SetFloat("Hor", horizontal); anim.SetFloat("Vert", vertical); } } /// <summary> /// Handles turning /// </summary> private void Turn() { float x = Input.GetAxis(rotx) * inversion; float y = Input.GetAxis(roty) * inversion; if (x != 0.0 || y != 0.0) { float angle = Mathf.Atan2(x, y) * Mathf.Rad2Deg; crosshairHolder.transform.rotation = Quaternion.AngleAxis(90 - angle, Vector3.forward); } } private void Dash() { bool cooldown, dashing; cooldown = dashing = false; float cooldownTime = 2.0f; // time between available dashes float dashDuration = 0.2f; // how long the move speed will stay modified before reverting float temp = movementSpeed; // backs-up normal move speed if (Input.GetAxis(dash) > 0) { if (canDash) { if (!cooldown && !dashing) // if not on cooldown, and not currently dashing { dashing = true; // then begin dashing movementSpeed = 25; } else if (dashing) // if already dashing { dashDuration -= Time.deltaTime; // decrement from dash duration if (dashDuration <= 0) // if dash duration hits 0 { movementSpeed = temp; // reset movement speed dashing = false; // player is no longer dashing dashDuration = 0.2f; // reset the duration timer } } else if (cooldown) // if player is on cooldown, or currently dashing... { cooldownTime -= Time.deltaTime; // derement cooldown timer if (cooldownTime < 0) // if ccooldown has counted down all the way { cooldown = false; // dash is no longer on cooldown } } }// End if } movementSpeed = temp; } private void Shoot() { if (canFire) { print(playerNum + " is firing"); //AudioManager.instance.PlaySound(AudioManager.SoundClip.KnifeThrow); instance.soundPlayer.PlayOneShot(knifeThrow); canFire = false; fireCooldown = resetCD; if (!multiShot) { GameObject clone = Instantiate(knife, crosshairHolder.transform.position, crosshairHolder.transform.rotation); if (pierceShot) clone.GetComponent<Knife>().pierce = true; //Physics2D.IgnoreCollision(clone.GetComponent<BoxCollider2D>(), myCollider[0]); } else { for (int i = -1; i < 2; i++) { GameObject clone = Instantiate(knife, crosshairHolder.transform.position, crosshairHolder.transform.rotation * Quaternion.Euler(0, 0, crosshairHolder.transform.rotation.z + 15 * i)); if (pierceShot) clone.GetComponent<Knife>().pierce = true; //Physics2D.IgnoreCollision(clone.GetComponent<BoxCollider2D>(), myCollider[0]); //GameObject newClone = Instantiate(knife, crosshairHolder.transform.position, Quaternion.Euler(new Vector3(0, 0, crosshairHolder.transform.rotation.z + 10))); } } } } }
using System.Windows.Forms; namespace Grimoire.Tools { public class Hotkey { public string Text { get; set; } public Keys Key { get; set; } public int ActionIndex { get; set; } } }
using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using OpenGovAlerts.Models; using System; using System.Collections.Generic; using System.Text; namespace OpenGovAlertsTests { public class Environment { private IServiceProvider provider = null; private DbContextOptions<AlertsDbContext> options; public Environment() { var services = new ServiceCollection(); options = GetDbContextOptions(); services.AddTransient<AlertsDbContext, AlertsDbContext>(sp => new AlertsDbContext(options)); // use Transient instances so we can test our database actions on a new instance of the context (but with the same underlying in-memory database) provider = services.BuildServiceProvider(); } public AlertsDbContext Db { get { return provider.GetService<AlertsDbContext>(); } } private static DbContextOptions<AlertsDbContext> GetDbContextOptions() { var services = new ServiceCollection(); services.AddEntityFrameworkInMemoryDatabase(); var provider = services.BuildServiceProvider(); // Create a new options instance telling the context to use an // InMemory database and the new service provider. var builder = new DbContextOptionsBuilder<AlertsDbContext>(); builder.UseInMemoryDatabase("alertsdb") .UseInternalServiceProvider(provider); return builder.Options; } } }
using System; namespace RO { [CustomLuaClass] public class CompatibilityVersion { public static int version = 11; } }
using System; using System.Collections.Generic; using System.Text; namespace HackerRank_HomeCode { public class CamelCase { public void NoofWords() { string s = Console.ReadLine(); int wordCount = 0; if (s.Length > 0) { wordCount = 1; for (int i = 1; i < s.Length; i++) { if (char.IsUpper(s[i])) { wordCount++; } } } Console.WriteLine(wordCount); } } }
namespace Triton.Game.Mapping { using ns26; using System; [Attribute38("BRM01_GrimGuzzler")] public class BRM01_GrimGuzzler : BRM_MissionEntity { public BRM01_GrimGuzzler(IntPtr address) : this(address, "BRM01_GrimGuzzler") { } public BRM01_GrimGuzzler(IntPtr address, string className) : base(address, className) { } public void InitEmoteResponses() { base.method_8("InitEmoteResponses", Array.Empty<object>()); } public void PreloadAssets() { base.method_8("PreloadAssets", Array.Empty<object>()); } public bool m_cardLinePlayed { get { return base.method_2<bool>("m_cardLinePlayed"); } } public bool m_disableSpecialCardVO { get { return base.method_2<bool>("m_disableSpecialCardVO"); } } public bool m_eTCLinePlayed { get { return base.method_2<bool>("m_eTCLinePlayed"); } } public bool m_heroPowerLinePlayed { get { return base.method_2<bool>("m_heroPowerLinePlayed"); } } public bool m_succubusLinePlayed { get { return base.method_2<bool>("m_succubusLinePlayed"); } } public bool m_warGolemLinePlayed { get { return base.method_2<bool>("m_warGolemLinePlayed"); } } } }
namespace BigONotationPartial { enum DataStructureType { List, HashSet } }
 using System; using Abp.Application.Services.Dto; using System.ComponentModel.DataAnnotations; namespace eForm.EFlight.Dtos { public class CreateOrEditFlightDto : EntityDto<int?> { public string Detail { get; set; } public string Name { get; set; } public string NRIC { get; set; } public string StaffID { get; set; } public string Position { get; set; } public string Email { get; set; } public string PhoneNo { get; set; } public string MembershipNo { get; set; } public string ValidationName { get; set; } public string ValidationPhoneNo { get; set; } public string ValidationPosition { get; set; } public DateTime ValidationDate { get; set; } public bool Validation { get; set; } public string ApprovalName { get; set; } public string ApprovalPosition { get; set; } public DateTime ApprovalDate { get; set; } public bool Approval { get; set; } public int? TravelAgentId { get; set; } public int? PurposeId { get; set; } public int? JobTitleId { get; set; } } }
using Course.Commands; using Course.Context; using Course.Model; using Course.View; using NLog; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Data.Entity; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows; namespace Course.ViewModel { public class MainWindowViewModel : INotifyPropertyChanged { Logger logger = LogManager.GetCurrentClassLogger(); ApplicationContext db; private Material selectedMaterial; private Employee selectedEmployee; RelayCommand addMaterialCommand; RelayCommand deleteMaterialCommand; RelayCommand editMaterialCommand; RelayCommand addEmployeeCommand; RelayCommand deleteEmployeeCommand; RelayCommand editEmployeeCommand; RelayCommand lookVictimCommand; RelayCommand addVictimCommand; RelayCommand lookAllMaterialCommand; RelayCommand rewriteMaterialCommand; RelayCommand getInfoAboutApp; RelayCommand lookTermOnTodayCommand; public RelayCommand ExitCommand { get; set; } private ObservableCollection<Material> materials; private ObservableCollection<Employee> employees; public ObservableCollection<Material> Materials { get { return materials; } set { materials = value; } } public ObservableCollection<Employee> Employees { get { return employees; } set { employees = value; OnPropertyChanged("Employees"); } } public Material SelectedMaterial { get { return selectedMaterial; } set { selectedMaterial = value; OnPropertyChanged("SelectedMaterial"); } } public Employee SelectedEmployee { get { return selectedEmployee; } set { selectedEmployee = value; OnPropertyChanged("SelectedEmployee"); materials.Clear(); if (selectedEmployee != null) { try { db.Materials.Where(x => x.DateOfTerm < DateTime.Today).ToList().ForEach(x => x.ExecutedOrNotExecuted = true); db.SaveChanges(); db.Employees.FirstOrDefault(x => x.EmployeeId == selectedEmployee.EmployeeId).Materials.Where(x => x.ExecutedOrNotExecuted != true).ToList().ForEach(x => materials.Add(x)); } catch (Exception ex) { logger.Error(ex, "Ошибка загрузки БД свойстве SelectedEmployee"); } } } } public MainWindowViewModel(ApplicationContext db) { //db = new ApplicationContext(); this.db = db; this.Materials = new ObservableCollection<Material>(); try { this.db.Employees.Load(); this.Employees = new ObservableCollection<Employee>(this.db.Employees.Local.ToBindingList()); } catch (Exception ex) { logger.Error(ex, "Ошибка загрузки БД в конструкторе "); } } public RelayCommand AddMaterialCommand { get { return addMaterialCommand ?? (addMaterialCommand = new RelayCommand((o) => { MaterialWindow materialWindow = new MaterialWindow(null, selectedEmployee, db); materialWindow.ShowDialog(); materials.Clear(); try { db.Employees.FirstOrDefault(x => x.EmployeeId == selectedEmployee.EmployeeId).Materials.Where(x => x.ExecutedOrNotExecuted != true).ToList().ForEach(x => materials.Add(x)); } catch (Exception ex) { logger.Error(ex, "Ошибка загрузки БД после добавления материала"); } }, (o => SelectedEmployee != null) )); } } public RelayCommand EditMaterialCommand { get { return editMaterialCommand ?? (editMaterialCommand = new RelayCommand((o) => { var result = MessageBox.Show("Изменить информацию о материале?", "", MessageBoxButton.YesNo, MessageBoxImage.Information); if (result == MessageBoxResult.Yes) { var material = o as Material; MaterialWindow materialWindow = new MaterialWindow(material, selectedEmployee, db); materialWindow.ShowDialog(); materials.Clear(); try { db.Employees.FirstOrDefault(x => x.EmployeeId == selectedEmployee.EmployeeId).Materials.Where(x => x.ExecutedOrNotExecuted != true).ToList().ForEach(x => materials.Add(x)); } catch (Exception ex) { logger.Error(ex, "Ошибка загрузки БД после изменения материала"); } } }, (o => SelectedMaterial != null) )); } } public RelayCommand DeleteMaterialCommand { get { return deleteMaterialCommand ?? (deleteMaterialCommand = new RelayCommand((o) => { var result = MessageBox.Show("Удалить материал?", "", MessageBoxButton.YesNo, MessageBoxImage.Information); if (result == MessageBoxResult.Yes) { var material = o as Material; if (material != null) { try { db.Materials.Remove(db.Materials.Where(x => x.MaterialId == material.MaterialId).First()); db.SaveChanges(); logger.Info("Материал ЕК№" + material.NumberEK + " удален из БД"); } catch (Exception ex) { logger.Error(ex, "Ошибка загрузки БД после удаления материала"); } materials.Remove(material); } } }, (o => SelectedMaterial != null)) ); } } public RelayCommand AddEmployeeCommand { get { return addEmployeeCommand ?? (addEmployeeCommand = new RelayCommand((o) => { EmployeeWindow employeeWindow = new EmployeeWindow(null, db); employeeWindow.ShowDialog(); try { var newEmployee = db.Employees.ToList().Except(employees.ToList()).FirstOrDefault(); if (newEmployee != null) employees.Add(newEmployee); } catch (Exception ex) { logger.Error(ex, "Ошибка загрузки БД после добавления сотрудника"); } //MessageBox.Show("Сотрудник добавлен"); })); } } public RelayCommand EditEmployeeCommand { get { return editEmployeeCommand ?? (editEmployeeCommand = new RelayCommand((o) => { var result = MessageBox.Show("Изменить информацию о сотруднике?", "", MessageBoxButton.YesNo, MessageBoxImage.Information); if (result == MessageBoxResult.Yes) { var employee = o as Employee; EmployeeWindow employeeWindow = new EmployeeWindow(employee, db); employeeWindow.ShowDialog(); } }, (o => SelectedEmployee != null) )); } } public RelayCommand DeleteEmployeeCommand { get { return deleteEmployeeCommand ?? (deleteEmployeeCommand = new RelayCommand((o) => { var result = MessageBox.Show("Удалить сотрудника?", "", MessageBoxButton.YesNo, MessageBoxImage.Information); if (result == MessageBoxResult.Yes) { var employee = o as Employee; if (employee != null) { try { db.Employees.Remove(db.Employees.Where(x => x.EmployeeId == employee.EmployeeId).First()); db.SaveChanges(); logger.Info("Сотрудник " + employee.FirstName + employee.LastName + " удален из БД"); } catch (Exception ex) { logger.Error(ex, "Ошибка загрузки БД после удаления сотрудника"); } Employees.Remove(employee); } } }, (o => SelectedEmployee != null)) ); } } public RelayCommand LookVictimCommand { get { return lookVictimCommand ?? (lookVictimCommand = new RelayCommand((o) => { var victim = o as Victim; LookVictimWindow victimWindow = new LookVictimWindow(null, db, victim); victimWindow.ShowDialog(); }, (o => SelectedMaterial != null) )); } } public RelayCommand AddVictimCommand { get { return addVictimCommand ?? (addVictimCommand = new RelayCommand((o) => { VictimWindow victimWindow = new VictimWindow(SelectedMaterial, db, null); victimWindow.ShowDialog(); }, (o => SelectedMaterial != null) )); } } public RelayCommand LookAllMaterialCommand { get { return lookAllMaterialCommand ?? (lookAllMaterialCommand = new RelayCommand((o) => { AllMaterialWindow allMaterialWindow = new AllMaterialWindow(db); allMaterialWindow.ShowDialog(); } )); } } public RelayCommand RewriteMaterialCommand { get { return rewriteMaterialCommand ?? (rewriteMaterialCommand = new RelayCommand((o) => { RewriteMaterialWindow rewriteMaterialWindow = new RewriteMaterialWindow(db, SelectedMaterial, SelectedEmployee); rewriteMaterialWindow.ShowDialog(); Materials.Clear(); try { db.Employees.FirstOrDefault(x => x.EmployeeId == selectedEmployee.EmployeeId).Materials.Where(x => x.ExecutedOrNotExecuted != true).ToList().ForEach(x => materials.Add(x)); } catch (Exception ex) { logger.Error(ex, "Ошибка загрузки БД после того как материал был переписан на другого сотрудника"); } }, (o => SelectedMaterial != null) )); } } public RelayCommand GetInfoAboutApp { get { return getInfoAboutApp ?? (getInfoAboutApp = new RelayCommand((o) => { MessageBox.Show("Developed by Andrew Shpakovskiy"); } )); } } public RelayCommand LookTermOnTodayCommand { get { return lookTermOnTodayCommand ?? (lookTermOnTodayCommand = new RelayCommand((o) => { NotificationWindow notificationWindow = new NotificationWindow(db, false); notificationWindow.ShowDialog(); } )); } } public event PropertyChangedEventHandler PropertyChanged; public void OnPropertyChanged(string prop = "") { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(prop)); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Movement : MonoBehaviour { // Update is called once per frame void Update () { /* // 1 private SteamVR_TrackedObject trackedObj; //2 private SteamVR_Controller.Device Controller */ } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace PKKGui { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { BinaryWriter myStreamWriter; BinaryReader myStreamReader; public MainWindow() { InitializeComponent(); TcpClient myClient = new TcpClient(); myClient.Connect("127.0.0.1", 8080); var tcpStream = myClient.GetStream(); myStreamWriter = new BinaryWriter(tcpStream); myStreamReader = new BinaryReader(tcpStream); ThreadPool.QueueUserWorkItem(HandleReading, myStreamReader); } private void HandleReading(object state) { var myStreamReader = state as BinaryReader; do { try { // read the string sent to the server var theReply = myStreamReader.ReadString(); Dispatcher.BeginInvoke(new Action(() => { ChatBox.Text += theReply; })); } catch (Exception) { break; } } while (true); } private void button_Click(object sender, RoutedEventArgs e) { try { myStreamWriter.Write(MessageTextbox.Text); } catch (Exception ex) { throw ex; } } } }
using async_inn.Models.DTOs; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace async_inn.Models.Interfaces { public interface IRoom { /// <summary> /// Creates a room /// </summary> /// <param name="room"> room object</param> /// <returns> task completion </returns> Task<RoomDTO> Create(RoomDTO roomdto); /// <summary> /// Gets all the rooms /// </summary> /// <returns> List of all rooms</returns> Task<List<RoomDTO>> GetRooms(); /// <summary> /// Gets a single room /// </summary> /// <param name="id"> room identifier</param> /// <returns> The room with all its amenities</returns> Task<RoomDTO> GetRoom(int id); /// <summary> /// Updates room /// </summary> /// <param name="room"> room object</param> /// <returns>the updated room object</returns> Task<RoomDTO> Update(RoomDTO roomdto); /// <summary> /// Deletes selected room /// </summary> /// <param name="id">room identifier</param> /// <returns> task completion </returns> Task Delete(int id); /// <summary> /// Adds an amenity to a room /// </summary> /// <param name="roomId"> identifier for room</param> /// <param name="amenityId"> identifier for amenity</param> /// <returns> Task of completion </returns> Task AddAmenityToRoom(int roomId, int amenityId); /// <summary> /// Removes an amenity to a room /// </summary> /// <param name="roomId"> identifier for room</param> /// <param name="amenityId"> identifier for amenity</param> /// <returns> Task of completion </returns> Task RemoveAmenityFromRoom(int roomId, int amenityId); } }
using NUnit.Framework; using TestNinja.Fundamentals; namespace TestNinja.UnitTests { [TestFixture] public class HtmlFormatterTests { [Test] public void FormatAsBold_WhenCalled_ShouldEncloseTheStringWithStrongElement() { var formatter = new HtmlFormatter(); var result = formatter.FormatAsBold("abc"); // Specific assertion. Better for strings like HTML that need to be exact. Assert.That(result, Is.EqualTo("<strong>abc</strong>").IgnoreCase); // More general assertions. Better for error messages etc. Assert.That(result, Does.StartWith("<strong>").IgnoreCase); Assert.That(result, Does.EndWith("</strong>").IgnoreCase); Assert.That(result, Does.Contain("abc").IgnoreCase); } } }
namespace System.Linq { using System.Collections.Generic; public static partial class FastLinq { /// <remarks> /// BCL does not set initial size /// </remarks> /// TODO: Should have array pooling but probably doesn't belong in this library /// TODO: Could have a lazy dictionary that memoizes as necessary but can optimize /// for enumeration and the return types of Dictionary versus IDictionary public static Dictionary<TKey, TSource> ToDictionary<TSource, TKey>( this IReadOnlyCollection<TSource> source, Func<TSource, TKey> keySelector) { if (source == null) { throw new ArgumentNullException(nameof(source)); } if (keySelector == null) { throw new ArgumentNullException(nameof(keySelector)); } var dictionary = new Dictionary<TKey, TSource>(source.Count); foreach (var item in source) { TKey key = keySelector(item); dictionary.Add(key, item); } return dictionary; } public static Dictionary<TKey, TSource> ToDictionary<TSource, TKey>( this IReadOnlyCollection<TSource> source, Func<TSource, TKey> keySelector, IEqualityComparer<TKey> keyComparer) { if (source == null) { throw new ArgumentNullException(nameof(source)); } if (keySelector == null) { throw new ArgumentNullException(nameof(keySelector)); } var dictionary = new Dictionary<TKey, TSource>(source.Count, keyComparer); foreach (var item in source) { TKey key = keySelector(item); dictionary.Add(key, item); } return dictionary; } public static Dictionary<TKey, TElement> ToDictionary<TSource, TKey, TElement>( this IReadOnlyCollection<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> itemSelector, IEqualityComparer<TKey> keyComparer) { if (source == null) { throw new ArgumentNullException(nameof(source)); } if (keySelector == null) { throw new ArgumentNullException(nameof(keySelector)); } if (itemSelector == null) { throw new ArgumentNullException(nameof(itemSelector)); } var dictionary = new Dictionary<TKey, TElement>(source.Count, keyComparer); foreach (var item in source) { TKey key = keySelector(item); var value = itemSelector(item); dictionary.Add(key, value); } return dictionary; } public static Dictionary<TKey, TElement> ToDictionary<TSource, TKey, TElement>( this IReadOnlyCollection<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> itemSelector) { if (source == null) { throw new ArgumentNullException(nameof(source)); } if (keySelector == null) { throw new ArgumentNullException(nameof(keySelector)); } if (itemSelector == null) { throw new ArgumentNullException(nameof(itemSelector)); } var dictionary = new Dictionary<TKey, TElement>(source.Count); foreach (var item in source) { TKey key = keySelector(item); var value = itemSelector(item); dictionary.Add(key, value); } return dictionary; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Xml.Linq; namespace PhonesStore.ViewModels { public static class DataPersister { public static IEnumerable<PhonesStoreViewModel> GetAllStores(string documentPath) { var allPhones = GetPhones(documentPath); var storesDocumentRoot = XDocument.Load(documentPath + "stores.xml").Root; var stores = from storeElement in storesDocumentRoot.Elements("store") select new PhonesStoreViewModel() { Name = storeElement.Element("name").Value, Phones = from phoneElement in storeElement.Element("phones").Elements("phoneId") select allPhones.FirstOrDefault(p => p.Id == phoneElement.Value) }; return stores; } public static IEnumerable<PhoneViewModel> GetPhones(string documentPath) { var location = Assembly.GetExecutingAssembly().Location; var path = Path.GetDirectoryName(location); var phonesDocumentRoot = XDocument.Load(documentPath + "phones.xml").Root; var oses = GetAllOSes(documentPath); var phonesVM = from phoneElement in phonesDocumentRoot.Elements("phone") select new PhoneViewModel() { Id = phoneElement.Element("id").Value, Vendor = phoneElement.Element("vendor").Value, Model = phoneElement.Element("model").Value, Year = int.Parse(phoneElement.Element("year").Value), ImagePath = Path.Combine(path, phoneElement.Element("image").Value), OS = oses.FirstOrDefault(os => os.Id == phoneElement.Element("os").Value) }; return phonesVM; } internal static IEnumerable<OperatingSystemViewModel> GetAllOSes(string phonesDocumentPath) { var osRoot = XDocument.Load(phonesDocumentPath + "os.xml").Root; var osVms = from osElement in osRoot.Elements("os") select new OperatingSystemViewModel() { Name = osElement.Element("name").Value, Manufacturer = osElement.Element("manufacturer").Value, Version = osElement.Element("version").Value, Id = osElement.Element("id").Value }; return osVms; } internal static void AddPhone(string documenPath, PhoneViewModel phone, string storeName) { var root = XDocument.Load(documenPath + "phones.xml").Root; var newPhoneId = Guid.NewGuid(); root.Add( new XElement("phone", new XElement("id", newPhoneId), new XElement("vendor", phone.Vendor), new XElement("model", phone.Model), new XElement("year", phone.Year), new XElement("image", phone.ImagePath), new XElement("os", new XElement("id", phone.OS.Id) //new XElement("name", phone.OS.Name), //new XElement("version", phone.OS.Name), //new XElement("manufacturer", phone.OS.Manufacturer))) ) ) ); root.Document.Save(documenPath + "phones.xml"); } public static void SavePhoneToStore(string documenPath, string storeName, string newPhoneId) { var storesRoot = XDocument.Load(documenPath + "stores.xml").Root; var store = storesRoot.Elements("store").FirstOrDefault(e => e.Element("name").Value == storeName); store.Element("phones").Add(new XElement("phoneId", newPhoneId)); storesRoot.Save(documenPath + "stores.xml"); } public static IEnumerable<PhoneViewModel> GetPhonesByStoreName(string documentPath, string storeName) { var allStores = GetAllStores(documentPath); var store = allStores.FirstOrDefault(s => s.Name == storeName); return store.Phones; } internal static void AddNewStore(PhonesStoreViewModel phonesStoreViewModel, string path) { var storesPath = path + "stores.xml"; var stores = XDocument.Load(storesPath).Root; stores.Add( new XElement("store", new XElement("name", phonesStoreViewModel.Name), new XElement("phones"))); stores.Save(storesPath); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Data.SqlClient; namespace Idenz.Core.Windows { public partial class frmListBaseForm : frmSimpleBaseForm { Core.Corelib.DB _db = new Core.Corelib.DB(); public List<SqlParameter> parameters = new List<SqlParameter>(); public string ListSpName; public string EditorFormName; public frmListBaseForm() { InitializeComponent(); } /// <summary> /// base.LoadData çalismadan önce parametreleri ekleyin. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public virtual void LoadData(object sender, EventArgs e) { this.gcMain.DataSource = _db.LoadData(ListSpName, parameters); } public virtual void Edit(object sender, EventArgs e) { System.Reflection.Assembly asm = System.Reflection.Assembly.LoadFile(@System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase); //Type t = asm.GetType(((BizLayer.Models.Assembly)moduleList.Single(m => m.Assemblies.Where(a => a.Name == assemblyName))).Namespace); Type t = asm.GetType(this.EditorFormName); Form f = ((Form)Activator.CreateInstance(t)); f.Show(); } public virtual void ValidateFilters() { } } }
// **************************************************************** // Copyright 2007, Charlie Poole // This is free software licensed under the NUnit license. You may // obtain a copy of the license at http://nunit.org // **************************************************************** // **************************************************************** // Copyright 2012, Lei Qun // 2013.1.7修改: // 1.NUnit.Util.SettingsService改为NUnit.Util.ArxNet.SettingsServiceArxNet类 // 2.从NUnit.Util.ArxNet.SettingsGroupArxNet类继承 // 3.NUnit.Util.LegacySettingsConverter改为NUnit.Util.ArxNet.LegacySettingsConverterArxNet类 // 4.从NUnit.Util.ArxNet.SettingsGroupArxNet类继承 // **************************************************************** using System; using System.IO; using Microsoft.Win32; using NUnit.Core; namespace NUnit.Util.ArxNet { /// <summary> /// Summary description for UserSettingsService. /// </summary> public class SettingsServiceArxNet : SettingsGroupArxNet, NUnit.Core.IService { static readonly string settingsFileName = "NUnitSettings.xml"; private bool writeable; public SettingsServiceArxNet() : this(true) { } public SettingsServiceArxNet(bool writeable) { this.writeable = writeable; #if CLR_2_0 || CLR_4_0 string settingsFile = System.Configuration.ConfigurationManager.AppSettings["settingsFile"]; #else string settingsFile = System.Configuration.ConfigurationSettings.AppSettings["settingsFile"]; #endif if ( settingsFile == null ) settingsFile = Path.Combine( NUnitConfiguration.ApplicationDirectory, settingsFileName ); this.storage = new XmlSettingsStorage( settingsFile, writeable ); if ( File.Exists( settingsFile ) ) storage.LoadSettings(); else if (writeable) ConvertLegacySettings(); } #region IService Implementation public void InitializeService() { } public void UnloadService() { if ( writeable ) storage.SaveSettings(); this.Dispose(); } #endregion #region ConvertLegacySettings void ConvertLegacySettings() { RegistryKey key = Registry.CurrentUser.OpenSubKey( NUnitRegistry.KEY ); if ( key == null ) key = Registry.CurrentUser.OpenSubKey( NUnitRegistry.LEGACY_KEY ); if ( key != null ) { using( ISettingsStorage legacyStorage = new RegistrySettingsStorage( key ) ) { new LegacySettingsConverterArxNet( legacyStorage, storage ).Convert(); } storage.SaveSettings(); } } private class LegacySettingsConverterArxNet : SettingsGroupArxNet { private ISettingsStorage legacy; public LegacySettingsConverterArxNet( ISettingsStorage legacy, ISettingsStorage current ) : base( current ) { this.legacy = legacy; } public void Convert() { Convert( "Form.x-location", "Gui.MainForm.Left" ); Convert( "Form.x-location", "Gui.MiniForm.Left" ); Convert( "Form.y-location", "Gui.MainForm.Top" ); Convert( "Form.y-location", "Gui.MiniForm.Top" ); Convert( "Form.width", "Gui.MainForm.Width" ); Convert( "Form.width", "Gui.MiniForm.Width" ); Convert( "Form.height", "Gui.MainForm.Height" ); Convert( "Form.height", "Gui.MiniForm.Height" ); Convert( "Form.maximized", "Gui.MainForm.Maximized", "False", "True" ); Convert( "Form.maximized", "Gui.MiniForm.Maximized", "False", "True" ); Convert( "Form.font", "Gui.MainForm.Font" ); Convert( "Form.font", "Gui.MiniForm.Font" ); Convert( "Form.tree-splitter-position", "Gui.MainForm.SplitPosition"); Convert( "Form.tab-splitter-position", "Gui.ResultTabs.ErrorsTabSplitterPosition"); Convert( "Options.TestLabels", "Gui.ResultTabs.DisplayTestLabels", "False", "True" ); Convert( "Options.FailureToolTips", "Gui.ResultTabs.ErrorTab.ToolTipsEnabled", "False", "True" ); Convert( "Options.EnableWordWrapForFailures", "Gui.ResultTabs.ErrorTab.WordWrapEnabled", "False", "True" ); Convert( "Options.InitialTreeDisplay", "Gui.TestTree.InitialTreeDisplay", "Auto", "Expand", "Collapse", "HideTests" ); Convert( "Options.ShowCheckBoxes", "Gui.TestTree.ShowCheckBoxes", "False", "True" ); Convert( "Options.LoadLastProject", "Options.LoadLastProject", "False", "True" ); Convert( "Options.ClearResults", "Options.TestLoader.ClearResultsOnReload", "False", "True" ); Convert( "Options.ReloadOnChange", "Options.TestLoader.ReloadOnChange", "False", "True" ); Convert( "Options.RerunOnChange", "Options.TestLoader.RerunOnChange", "False", "True" ); Convert( "Options.ReloadOnRun", "Options.TestLoader.ReloadOnRun", "False", "True" ); Convert( "Options.MergeAssemblies", "Options.TestLoader.MergeAssemblies", "False", "True" ); //Convert( "Options.MultiDomain", "Options.TestLoader.MultiDomain", "False", "True" ); Convert( "Options.AutoNamespaceSuites", "Options.TestLoader.AutoNamespaceSuites", "False", "True" ); Convert( "Options.VisualStudioSupport", "Options.TestLoader.VisualStudioSupport", "False", "True" ); Convert( "Recent-Projects.MaxFiles", "RecentProjects.MaxFiles" ); object val = legacy.GetSetting("Options.MultiDomain"); if (val != null && (bool)val) this.SaveSetting("Options.TestLoader.DomainUsage", NUnit.Core.DomainUsage.Multiple); int maxFiles = this.GetSetting( "RecentProjects.MaxFiles", 5 ); for( int i = 1; i <= maxFiles; i++ ) { string fileKey = string.Format( "File{0}", i ); object fileEntry = legacy.GetSetting( "Recent-Projects." + fileKey ); if ( fileEntry != null ) this.SaveSetting( "RecentProjects." + fileKey, fileEntry ); } } private void Convert( string legacyName, string currentName, params string[]values ) { object val = legacy.GetSetting( legacyName ); if ( val != null ) { if ( val is int && values != null ) { int ival = (int)val; if ( ival >= 0 && ival < values.Length ) val = values[(int)val]; } this.SaveSetting( currentName, val ); } } } #endregion } }
using FluentValidation; namespace Application.Users.Commands.CreateUserCommands { public class CreateUserCommandValidator : AbstractValidator<CreateUserCommand> { public CreateUserCommandValidator () { RuleFor (e => e.User.Address) .NotEmpty ().WithMessage ("User Address is Required") .NotNull ().WithMessage ("User Address is Required"); RuleFor (e => e.User.Email) .NotEmpty ().WithMessage ("User Email is Required") .NotNull ().WithMessage ("User Email is Required"); RuleFor (e => e.User.Gender) .NotNull ().WithMessage ("User Gender is Required"); RuleFor (e => e.User.Name) .NotEmpty ().WithMessage ("User Name is Required") .NotNull ().WithMessage ("User Name is Required"); RuleFor (e => e.User.Password) .NotEmpty ().WithMessage ("User Password is Required") .NotNull ().WithMessage ("User Password is Required"); RuleFor (e => e.User.Phone) .NotEmpty ().WithMessage ("User Phone is Required") .NotNull ().WithMessage ("User Phone is Required"); RuleFor (e => e.User.ZipCode) .NotEmpty ().WithMessage ("User ZipCode is Required") .NotNull ().WithMessage ("User ZipCode is Required"); RuleFor (e => e.Image) .NotEmpty ().WithMessage ("User Profile is Required") .NotNull ().WithMessage ("User Profile is Required"); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace GeorgePairs { public partial class MainWindow : Window { public MainWindow() { WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen; InitializeComponent(); } protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e) { base.OnMouseLeftButtonDown(e); this.DragMove(); } private void btnRegister_Click(object sender, RoutedEventArgs e) { Register inreg = new Register(); App.Current.MainWindow = inreg; this.Close(); inreg.Show(); } private void btnLogin_Click(object sender, RoutedEventArgs e) { Login log = new Login(); App.Current.MainWindow = log; this.Close(); log.Show(); } private void btnExit_Click(object sender, RoutedEventArgs e) { Close(); } private void MinimizeButton_Click(object sender, RoutedEventArgs e) { this.WindowState = WindowState.Minimized; } private void MaximizeButton_Click(object sender, RoutedEventArgs e) { AdjustWindowSize(); } private void AdjustWindowSize() { if (this.WindowState == WindowState.Maximized) { this.WindowState = WindowState.Normal; } else { this.WindowState = WindowState.Maximized; } } } }
using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Text; using VoterSystem.Models; namespace VoterSystem.Data { public class ApplicantDbContext : DbContext { public ApplicantDbContext(DbContextOptions<ApplicantDbContext> options) : base(options) { } public DbSet<VoterSystem.Models.Applicant> Applicant { get; set; } public DbSet<VoterSystem.Models.ApplicantVotes> ApplicantVotes { get; set; } public DbSet<VoterSystem.Models.Election> Election { get; set; } public DbSet<VoterSystem.Models.Elector> Elector { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace Shop { public partial class Admin : Window { public Admin() { InitializeComponent(); } string connStr = @"Data Source=.\SQLEXPRESS;Initial Catalog=StoreDB;Integrated Security=True"; private void button2_Click(object sender, RoutedEventArgs e) { try { DB db = new DB(); db.openConnection(connStr); db.getAllProducts(); prodGrid.ItemsSource = ProductsList.prodList; MessageBox.Show("Выполнено !!!"); db.closeConnection(); } catch { MessageBox.Show("Ошибка запроса"); } } private void button_Click(object sender, RoutedEventArgs e) { TripleDes ecription = new TripleDes(); try { string name = textBox.Text; string surname = textBox1.Text; string post = comboBox.Text; string log = textBox2.Text; string pass = ecription.Encrypt(passwordBox.Password, "300"); double salary = Convert.ToDouble(textBox3.Text); if (salary == 0 || salary < 0 || name.Length == 0 || surname.Length == 0 || post.Length == 0 || log.Length == 0 || pass.Length == 0) { MessageBox.Show("Проверьте данные сотрудника"); } else { DB db = new DB(); db.openConnection(connStr); db.addEmploye(name, surname, post, log, pass, salary); MessageBox.Show("Выполнено !!!"); db.closeConnection(); } } catch { MessageBox.Show("Ошибка запроса"); } } private void button1_Click(object sender, RoutedEventArgs e) { prodGrid.ItemsSource = null; prodGrid.ItemsSource = ProductsList.prodList; } private void button4_Click(object sender, RoutedEventArgs e) { try { DB db = new DB(); db.openConnection(connStr); db.getAllEmployee(); emplGrid.ItemsSource = EmployeeList.emplList; MessageBox.Show("Выполнено !!!"); db.closeConnection(); } catch { MessageBox.Show("Ошибка запроса"); } } private void button3_Click(object sender, RoutedEventArgs e) { emplGrid.ItemsSource = null; emplGrid.ItemsSource = EmployeeList.emplList; } private void button5_Click(object sender, RoutedEventArgs e) { try { int id = Convert.ToInt32(textBox4.Text); DB db = new DB(); db.openConnection(connStr); db.deleteEmplId(id); emplGrid.ItemsSource = null; emplGrid.ItemsSource = EmployeeList.emplList; MessageBox.Show("Выполнено !!!"); db.closeConnection(); } catch { MessageBox.Show("Ошибка запроса"); } } private void button6_Click(object sender, RoutedEventArgs e) { try { EmployeeList path = emplGrid.SelectedItem as EmployeeList; DB db = new DB(); db.openConnection(connStr); db.updateEmployee(path.id, path.name, path.surname, path.post, path.login, path.password, path.salary); MessageBox.Show("Выполнено !!!"); db.closeConnection(); } catch { MessageBox.Show("Ошибка запроса"); } } private void button7_Click(object sender, RoutedEventArgs e) { try { DB db = new DB(); db.openConnection(connStr); db.deleteAllEmpl(); EmployeeList.emplList.Clear(); emplGrid.ItemsSource = null; emplGrid.ItemsSource = EmployeeList.emplList; MessageBox.Show("Выполнено !!!"); db.closeConnection(); } catch { MessageBox.Show("Ошибка запроса"); } } private void button8_Click(object sender, RoutedEventArgs e) { try { DB db = new DB(); db.openConnection(connStr); ProductsList path = prodGrid.SelectedItem as ProductsList; db.updatePriceProduct(path.id, path.price); MessageBox.Show("Выполнено !!!"); db.closeConnection(); } catch { MessageBox.Show("Ошибка запроса"); } } private void button9_Click(object sender, RoutedEventArgs e) { try { DB db = new DB(); db.openConnection(connStr); db.getAllCategories(); catGrid.ItemsSource = null; catGrid.ItemsSource = Categories.categoriesList; MessageBox.Show("Выполнено !!!"); db.closeConnection(); } catch { MessageBox.Show("Ошибка запроса"); } } private void button10_Click(object sender, RoutedEventArgs e) { catGrid.ItemsSource = null; catGrid.ItemsSource = Categories.categoriesList; } private void button11_Click(object sender, RoutedEventArgs e) { try { DB db = new DB(); db.openConnection(connStr); Categories path = catGrid.SelectedItem as Categories; db.updateCategory(path.id, path.name_category); MessageBox.Show("Выполнено"); db.closeConnection(); } catch { MessageBox.Show("Ошибка запроса"); } } private void button12_Click(object sender, RoutedEventArgs e) { try { DB db = new DB(); db.openConnection(connStr); Categories path = catGrid.SelectedItem as Categories; int disc = Convert.ToInt32(textBox5.Text); if (disc == 0 || disc < 0) { MessageBox.Show("Проверьте скидку"); } else { db.setDiscountCategory(path.id, disc); MessageBox.Show("Выполнено"); } db.closeConnection(); } catch { MessageBox.Show("Ошибка запроса"); } } private void button13_Click(object sender, RoutedEventArgs e) { try { DB db = new DB(); db.openConnection(connStr); db.addNewProduct(textBox6.Text, Convert.ToDouble(textBox7.Text), Convert.ToInt32(textBox8.Text), Convert.ToInt32(textBox9.Text), textBox10.Text, Convert.ToInt32(textBox11.Text)); MessageBox.Show("Выполнено !!!"); db.closeConnection(); } catch { MessageBox.Show("Ошибка запроса"); } } private void button14_Click(object sender, RoutedEventArgs e) { try { DB db = new DB(); db.openConnection(connStr); db.getAllProducers(); pcGrid.ItemsSource = null; pcGrid.ItemsSource = Producers.producerList; MessageBox.Show("Выполнено !!!"); db.closeConnection(); } catch { MessageBox.Show("Ошибка запроса"); } } private void button17_Click(object sender, RoutedEventArgs e) { pcGrid.ItemsSource = null; pcGrid.ItemsSource = Producers.producerList; } private void button18_Click(object sender, RoutedEventArgs e) { try { DB db = new DB(); db.openConnection(connStr); db.deleteProductId(Convert.ToInt32(textBox12.Text)); MessageBox.Show("Выполнено !!!"); db.closeConnection(); } catch { MessageBox.Show("Ошибка запроса"); } } private void button15_Click(object sender, RoutedEventArgs e) { try { DB db = new DB(); db.openConnection(connStr); db.getAllSales(); sGrid.ItemsSource = null; sGrid.ItemsSource = Sales.sList; MessageBox.Show("Выполнено !!!"); db.closeConnection(); } catch { MessageBox.Show("Ошибка запроса"); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using WebApiPais.Models; namespace WebApiPais.Controllers { [Produces("application/json")] //se agrega a la regla de ruteo el pais y luego la provincia para obtener la informacion por //pais y luego las provincias de ese pais [Route("api/Pais/{PaisId}/Provincia")] public class ProvinciaController : Controller { private readonly AplicationDbContext context; public ProvinciaController(AplicationDbContext context) { this.context = context; } //http://localhost:63146/api/pais/2/provincia [HttpGet] public IEnumerable<Provincia> Get(int? PaisId) { return context.Provincias.Where(c => c.PaisId == PaisId).ToList(); } [HttpGet("{id}", Name = "ProvinciaCreada")] public IActionResult GetById(int id) { var pais = context.Provincias.FirstOrDefault(c => c.Id == id); if (pais == null) return NotFound(); return Ok(pais); } [HttpPost] public IActionResult Post([FromBody] Provincia provincia) { if (ModelState.IsValid) { context.Provincias.Add(provincia); context.SaveChanges(); //redirecciona a la acion GetById con el verbo PaisCreado, pasando como parametro el id del nuevo pais creado. return new CreatedAtRouteResult("ProvinciaCreada", new { id = provincia.Id }, provincia); } //permite llevar los mensajes de validacion definidos en el modelo //hasta la aplicacion cliente cuando trata de guardar un nombre que //pasa de los 30 caracteres para el pais return BadRequest(ModelState); } [HttpPut("{id}")] public IActionResult Post([FromBody] Provincia provincia, int id) { if (provincia.Id != id) { return BadRequest(); } context.Entry(provincia).State = EntityState.Modified; context.SaveChanges(); return Ok(); } [HttpPut("{id}")] public IActionResult Delete(int id) { var provincia = context.Provincias.FirstOrDefault(c => c.Id == id); if (provincia == null) { return NotFound(); } context.Provincias.Remove(provincia); context.SaveChanges(); context.Provincias.Remove(provincia); return Ok(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace CoreComponents.Threading { public sealed class AcquisitionThread : IReset, IDisposable { public const int NoThread = -1; int myId = NoThread; readonly SpinLock mySpinLock; public AcquisitionThread() { } public AcquisitionThread(bool acquired) { if(acquired) myId = Thread.CurrentThread.ManagedThreadId; } public int Id { get { bool lockTaken = false; try { mySpinLock.Enter(ref lockTaken); return myId; } finally { if(lockTaken) mySpinLock.Exit(); } } } public bool CanAcquire { get { return Id != NoThread; } } public bool TryAquire() { bool lockTaken = false; try { mySpinLock.Enter(ref lockTaken); if(myId != NoThread) { myId = Thread.CurrentThread.ManagedThreadId; return true; } return false; } finally { if(lockTaken) mySpinLock.Exit(); } } public bool TryAquire(Action action) { if(TryAquire()) { using(this) action(); return true; } return false; } public bool TryAquire<TResult>(Func<TResult> func, out TResult result) { if(TryAquire()) { using(this) result = func(); return true; } result = default(TResult); return false; } public void Reset() { bool lockTaken = false; try { mySpinLock.Enter(ref lockTaken); myId = NoThread; } finally { if(lockTaken) mySpinLock.Exit(); } } public void Dispose() { Reset(); } } }
using UnityEngine; using System.Collections; public class Timer { private float time; private float elapsedTime = 0; public Timer() { Set(0); } public Timer(float time) { Set(time); } public void Reset() { elapsedTime = 0; } public void Run() { elapsedTime = elapsedTime + Time.deltaTime; } public bool IsOver() { return (elapsedTime >= time); } public void Set(float time) { this.time = time; } public float GetElapsedTime() { return elapsedTime; } }
using System; using System.Collections.Generic; using System.Text; using System.Threading; using OpenQA.Selenium; using OpenQA.Selenium.Appium; using OpenQA.Selenium.Appium.Android; using OpenQA.Selenium.Appium.iOS; using OpenQA.Selenium.Support.UI; namespace Ios_Android_Project.PageObjectModel { public class BasePageFindElement { //public IOSDriver<IOSElement> driverios; AppiumDriver<AppiumWebElement> basemobiledriver; public BasePageFindElement(AppiumDriver<AppiumWebElement> Driver) { basemobiledriver = Driver; } public string contextSwitching() { List<string> AllContexts = new List<string>(); foreach (var context in (basemobiledriver.Contexts)) { AllContexts.Add(context); } basemobiledriver.Context = (AllContexts[1]); // Switch to NATIVE_APP // driver.Context = ("NATIVE_APP"); Thread.Sleep(1000); var PS = basemobiledriver.PageSource; return PS; } public IWebElement ElementByCss(String KeyName) { Console.WriteLine("Element Found " + KeyName); WaitForElement(KeyName, "CssSelector"); return basemobiledriver.FindElement(By.CssSelector(KeyName)); } private void WaitForElement(String Element, string Locator) { var wait = new DefaultWait<AppiumDriver<AppiumWebElement>>(basemobiledriver) { Timeout = TimeSpan.FromSeconds(120), PollingInterval = TimeSpan.FromMilliseconds(9000) }; wait.IgnoreExceptionTypes(typeof(NoSuchElementException)); if (Locator == "CssSelector") wait.Until(d => d.FindElement(MobileBy.CssSelector(Element))); else wait.Until(d => d.FindElement(MobileBy.XPath(Element))); } public IWebElement ElementByXpath(String KeyName) { Console.WriteLine("Element Found " + KeyName); WaitForElement(KeyName, "Xpath"); return basemobiledriver.FindElement(By.XPath(KeyName)); } } }