text stringlengths 13 6.01M |
|---|
using Amazon.Lambda.APIGatewayEvents;
using Amazon.Lambda.Core;
using Epsagon.Dotnet.Core;
using Newtonsoft.Json;
using OpenTracing;
namespace Epsagon.Dotnet.Instrumentation.Triggers {
public class ProxyAPIGatewayLambda : BaseTrigger<APIGatewayProxyRequest> {
public ProxyAPIGatewayLambda(APIGatewayProxyRequest input) : base(input) {
}
public override void Handle(ILambdaContext context, IScope scope) {
base.Handle(context, scope);
scope.Span.SetTag("event.id", input?.RequestContext?.RequestId);
scope.Span.SetTag("resource.type", "api_gateway");
var hostKey = input?.Headers?.ContainsKey("Host");
scope.Span.SetTag("resource.name", hostKey.HasValue && hostKey.Value ? input?.Headers["Host"] : input?.RequestContext?.ApiId);
scope.Span.SetTag("resource.operation", input?.HttpMethod ?? "Trigger");
scope.Span.SetTag("aws.api_gateway.method", input?.HttpMethod);
scope.Span.SetTag("aws.api_gateway.stage", input?.RequestContext?.Stage);
scope.Span.SetTag("aws.api_gateway.query_string_parameters", JsonConvert.SerializeObject(input?.QueryStringParameters, new JsonSerializerSettings() {
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
}));
scope.Span.SetTag("aws.api_gateway.path", input?.Resource);
scope.Span.SetTag("aws.api_gateway.path_parameters", JsonConvert.SerializeObject(input?.PathParameters, new JsonSerializerSettings() {
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
}));
scope.Span.SetDataIfNeeded("aws.api_gateway.body", input?.Body);
scope.Span.SetDataIfNeeded("aws.api_gateway.headers", input?.Headers);
}
}
}
|
using Cinema.Data.Models;
using Cinema.Data.Models.Contracts;
using System.Collections.Generic;
using System.Linq;
namespace Cinema.Data.Services.Contracts
{
public interface IFilmScreeningService
{
IQueryable<FilmScreening> GetAllScreenings();
IQueryable<FilmScreening> GetAllScreeningsByDate(string date);
IQueryable<FilmScreening> GetScreeningsByMovieTitle(string title);
IQueryable<FilmScreening> GetAllFutureScreenings();
IEnumerable<User> GetUniqueBookersFromScreeningById(string id);
string GetMovieTitleByScreeningId(string id);
IFilmScreening GetById(string id);
int GetAvailableCount(string id);
void UpdateById(string id, FilmScreening updatedFilmScreening);
void Create(string date, string movieId, string price);
}
}
|
// GIMP# - A C# wrapper around the GIMP Library
// Copyright (C) 2004-2009 Maurits Rijk
//
// DrawableList.cs
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace Gimp
{
public abstract class DrawableList<T> where T : Drawable, new()
{
readonly List<T> _list = new List<T>();
protected delegate IntPtr GetDrawablesFunc(Int32 drawable_ID,
out int num_drawables);
protected DrawableList() {}
protected DrawableList(Image image, GetDrawablesFunc getDrawables)
{
int numDrawables;
IntPtr ptr = getDrawables(image.ID, out numDrawables);
FillListFromPtr(ptr, numDrawables);
}
protected void FillListFromPtr(IntPtr ptr, int numDrawables)
{
if (numDrawables > 0)
{
var dest = new int[numDrawables];
Marshal.Copy(ptr, dest, 0, numDrawables);
Array.ForEach(dest, drawableID => Add(new T() {ID = drawableID}));
}
}
public IEnumerator<T> GetEnumerator()
{
return _list.GetEnumerator();
}
protected void Add(T drawable)
{
_list.Add(drawable);
}
public void ForEach(Action<T> action)
{
_list.ForEach(action);
}
public int Count
{
get {return _list.Count;}
}
public T this[int index]
{
get {return _list[index];}
}
public T this[string name]
{
get {return _list.Find(drawable => drawable.Name == name);}
}
public int GetIndex(T key)
{
return _list.FindIndex(drawable => drawable.Name == key.Name);
}
}
}
|
using System;
namespace Lab_20
{
class NoMagicThings
{
enum ECOINS { HALVES = 50, QUARTERS = 25, DIMES = 10, NICKELS = 5, PENNIES = 1 }
public const int MAX = 99;
public const string MSG_HEADER = "I will make change for you.";
public const string MSG_ENTER = "Enter in an amount between 1 and 99: ";
public const string MSG_GBYE = "Goodbye ... ";
public const string MSG_INVALID = "Invalid int value for money!";
public const string MSG_MNY = "For your money {0} cents you get:";
public const string MSG_COIN = "{0} ";
public const string TOO_BIG = "The value you entered is too big, please enter a value between 0 and 99.";
public const string TOO_SMALL = "The value you entered is too small, please enter a value between 0 and 99.";
public static string[] SCOINS = { "Halves", "Quarters", "Dimes", "Nickels", "Pennies" };
public static int[] COINS = { (int)ECOINS.HALVES, (int)ECOINS.QUARTERS, (int)ECOINS.DIMES, (int)ECOINS.NICKELS, (int)ECOINS.PENNIES };
}
}
|
namespace PRGTrainer.Core.TasksStorage
{
using System.Collections.Generic;
using Model.Test;
/// <summary>
/// Интерфейс хранилища вопросов.
/// </summary>
public interface ITasksStorage
{
/// <summary>
/// Получение списка задач для членов комиссии с правом решающего голоса.
/// </summary>
/// <param name="num">Число задач, которые необходимо отдать.</param>
/// <returns>Коллекция задач.</returns>
IEnumerable<TaskInfo> GetTasksForConclusiveMembers(int num);
/// <summary>
/// Получение списка задач для членов комиссии с правом совещательного голоса.
/// </summary>
/// <param name="num">Число задач, которые необходимо отдать.</param>
/// <returns>Коллекция задач.</returns>
IEnumerable<TaskInfo> GetTasksForConsultativeMembers(int num);
/// <summary>
/// Получение списка задач для наблюдателей.
/// </summary>
/// <param name="num">Число задач, которые необходимо отдать.</param>
/// <returns>Коллекция задач.</returns>
IEnumerable<TaskInfo> GetTasksForObservers(int num);
/// <summary>
/// Заполнение хранилища задач.
/// </summary>
void FillStorage();
}
} |
using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
namespace ALM.Reclutamiento.Entidades
{
[Serializable]
public class EReferenciaLaboral
{
public int IdReferencia { get; set; }
public int IdProspecto { get; set; }
[Required(ErrorMessage = "Dato requerido")]
[StringLength(150)]
[DisplayName("Empresa")]
public string Empresa { get; set; }
[Required(ErrorMessage = "Dato requerido")]
[StringLength(150)]
[DisplayName("Domicilio")]
public string Domicilio { get; set; }
[Required(ErrorMessage = "Dato requerido")]
[StringLength(100)]
[DisplayName("Contacto")]
public string Contacto { get; set; }
[Required(ErrorMessage = "Dato requerido")]
[StringLength(64)]
[EmailAddress(ErrorMessage = "Formato incorrecto")]
[DisplayName("Contacto E-mail")]
public string Contacto_Email { get; set; }
[Required(ErrorMessage = "Dato requerido")]
[StringLength(64)]
[DisplayName("Contacto Tel.")]
public string Contacto_Telefono { get; set; }
[Required(ErrorMessage = "Dato requerido")]
[StringLength(150)]
[DisplayName("Motivo Separación")]
public string MotivoSeparacion { get; set; }
[Required(ErrorMessage = "Dato requerido")]
[StringLength(150)]
[DisplayName("Puesto")]
public string Puesto { get; set; }
[Required(ErrorMessage = "Dato requerido")]
[StringLength(64)]
[DisplayName("Tiempo Laborado")]
public string TiempoLaborado { get; set; }
[StringLength(250)]
[DisplayName("Comentario")]
public string Comentario { get; set; }
[DisplayName("Comentario")]
public bool Estatus { get; set; }
public int IdUsuarioCreacion { get; set; }
public DateTime FechaCreacion { get; set; }
public int IdUsuarioModificacion { get; set; }
public DateTime FechaModificacion { get; set; }
public int IdEmpresa { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace RockPaperScissorsWebApp.Models
{
public abstract class Game
{
public abstract void PlayRound();
public abstract void PlayRound(RPSChoice rPSChoice);
public abstract void PlayRound(RPSChoice rPSChoice1, RPSChoice rPSChoice2);
protected RandomRPSChoice randomRPSChoice;
protected User player1;
protected User player2;
protected Scoreboard scoreboard;
protected RPSChoice player1Choice;
protected RPSChoice player2Choice;
protected RPSP1P2Result result;
public int Player1Wins
{
get { return scoreboard.Player1Wins; }
}
internal void ResetScores()
{
scoreboard.Reset();
}
public int Player2Wins
{
get { return scoreboard.Player2Wins; }
}
public int GamesPlayed
{
get { return scoreboard.GamesPlayed; }
}
public int Draws
{
get { return scoreboard.Draws; }
}
public RPSChoice Player1Choice { get => player1Choice; }
public RPSChoice Player2Choice { get => player2Choice; }
public RPSP1P2Result Result { get => result; }
}
} |
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Windows;
using System.Xml;
using System.Xml.Serialization;
namespace Swiddler.Serialization
{
public class UserSettings
{
public Rect MainWindowBounds { get; set; }
public WindowState MainWindowState { get; set; }
public double MainWindowLeftColumn { get; set; }
public double MainWindowBottomRow { get; set; }
public Rect NewConnectionWindowBounds { get; set; }
public double NewConnectionLeftColumn { get; set; }
public double NewConnectionRightColumn { get; set; }
public bool PcapSelectionExport { get; set; } = true;
public List<string> QuickMRU { get; set; }
#region IO
public static string FileName => Path.Combine(App.Current.AppDataPath, nameof(UserSettings) + ".xml");
public static UserSettings Load()
{
if (File.Exists(FileName))
using (var file = File.OpenRead(FileName)) return Deserialize(file);
else
return new UserSettings();
}
public void Save()
{
using (var file = File.Open(FileName, FileMode.OpenOrCreate)) Serialize(file);
}
private static readonly XmlWriterSettings writerSettings = new XmlWriterSettings { OmitXmlDeclaration = true, Indent = true, Encoding = new UTF8Encoding(false) };
private static readonly XmlSerializerNamespaces emptyNamespaces = new XmlSerializerNamespaces(new[] { new XmlQualifiedName("", "") });
private static readonly XmlSerializer serializer = new XmlSerializer(typeof(UserSettings));
void Serialize(Stream stream)
{
stream.SetLength(0);
using (var writer = XmlWriter.Create(stream, writerSettings))
{
serializer.Serialize(writer, this, emptyNamespaces);
}
}
static UserSettings Deserialize(Stream stream)
{
using (var reader = XmlReader.Create(stream))
{
return (UserSettings)serializer.Deserialize(reader);
}
}
#endregion
}
}
|
using PDV.DAO.Atributos;
namespace PDV.DAO.Entidades.Financeiro
{
public class ContaBancaria
{
[CampoTabela("IDCONTABANCARIA")]
public decimal IDContaBancaria { get; set; } = -1;
[CampoTabela("IDBANCO")]
public decimal? IDBanco { get; set; }
[CampoTabela("NOME")]
public string Nome { get; set; }
[CampoTabela("AGENCIA")]
public string Agencia { get; set; }
[CampoTabela("DIGITOAGENCIA")]
public string DigitoAgencia { get; set; }
[CampoTabela("CONTA")]
public string Conta { get; set; }
[CampoTabela("DIGITO")]
public string Digito { get; set; }
[CampoTabela("ATIVO")]
public decimal Ativo { get; set; } = 1;
[CampoTabela("CAIXA")]
public decimal Caixa { get; set; }
[CampoTabela("OPERACAO")]
public string Operacao { get; set; }
public ContaBancaria() { }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
//
using System.Web.UI;
using System.IO;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Text;
using System.Security.Cryptography;
namespace TaskSystem
{
public class tools : Page
{
public bool checkLoginAndPassword(string username, string password)
{
bool flaga = false;
SqlConnection vid = GetConnection();
{
SqlCommand xp = new SqlCommand("SELECT * FROM users WHERE username=@username and password=@password;", vid);
xp.Parameters.AddWithValue("@username", username);
xp.Parameters.AddWithValue("@password", CreateMD5(password));
vid.Open();
DataSet dataSet = new DataSet();
SqlDataAdapter datauser = new SqlDataAdapter(xp);
datauser.Fill(dataSet);
bool flagaSql = dataSet.Tables[0].Rows.Count > 0;
if (flagaSql.Equals(true))
{
Session["User_Id"] = dataSet.Tables[0].Rows[0]["id"].ToString();
Session["User_Username"] = dataSet.Tables[0].Rows[0]["username"].ToString();
Session["User_Fullname"] = dataSet.Tables[0].Rows[0]["fullname"].ToString();
Session["User_Role"] = dataSet.Tables[0].Rows[0]["role"].ToString();
Session["User_Email"] = dataSet.Tables[0].Rows[0]["email"].ToString();
byte[] bytes = (byte[])dataSet.Tables[0].Rows[0]["avatar"];
Session["User_avatar"] = Convert.ToBase64String(bytes, 0, bytes.Length);
flaga = true;
}
vid.Close();
}
return flaga;
}
public static DataTable GetData(string query)
{
DataTable dt = new DataTable();
using (SqlConnection con = GetConnection())
{
using (SqlCommand cmd = new SqlCommand(query))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
}
}
return dt;
}
}
public static SqlConnection GetConnection()
{
//create the connection object
return new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
}
public static Boolean InsertUpdateData(SqlCommand cmd)
{
SqlConnection con = GetConnection();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
cmd.ExecuteNonQuery();
return true;
}
catch (Exception ex)
{
System.Web.HttpContext.Current.Response.Write(ex.Message);
return false;
}
finally
{
con.Close();
con.Dispose();
}
}
public string CreateMD5(string input)
{
MD5 md5 = System.Security.Cryptography.MD5.Create();
byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
byte[] hashBytes = md5.ComputeHash(inputBytes);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hashBytes.Length; i++)
{
sb.Append(hashBytes[i].ToString("X2"));
}
return sb.ToString();
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace Minutes
{
public static class MockDataExtensionMethods
{
public static void LoadMockData(this IEntryStore store)
{
var a = new Entry() { Title = "Sprint Planning Meeting", Content = "1, Scope" };
var b = new Entry() { Title = "Go to Gym", Content = "1, Scope" };
var c = new Entry() { Title = "Go to Eat", Content = "1, Scope" };
store.WriteAsync(a).Wait();
store.WriteAsync(b).Wait();
store.WriteAsync(c).Wait();
}
}
}
|
//
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
using System;
using System.Data;
using DotNetNuke.Data;
using DotNetNuke.Services.Localization;
namespace Dnn.PersonaBar.Servers.Components.DatabaseServer
{
public class DataService
{
private static readonly DataProvider Provider = DataProvider.Instance();
private static string moduleQualifier = "PersonaBar_";
private static string GetFullyQualifiedName(string name)
{
return String.Concat(moduleQualifier, name);
}
public static IDataReader GetDbInfo()
{
return Provider.ExecuteReader(GetFullyQualifiedName("GetDbInfo"));
}
public static IDataReader GetDbFileInfo()
{
return Provider.ExecuteReader(GetFullyQualifiedName("GetDbFileInfo"));
}
public static IDataReader GetDbBackups()
{
return Provider.ExecuteReader(GetFullyQualifiedName("GetDbBackups"));
}
}
}
|
using System;
using Microsoft.AspNetCore.Identity;
namespace LubyClocker.Domain.BoundedContexts.Users
{
public class User : IdentityUser<Guid>
{
}
} |
using Store.Books.Domain;
using System.Threading.Tasks;
namespace Store.Books.Infrastructure.Interfaces
{
public interface IPriceRepository : IGenericRepository<Price> { }
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using SiscomSoft.Models;
using System.Data.Entity;
namespace SiscomSoft_Web.ViewModel
{
public class ImpuestoViewModel : DataModel
{
public static List<Impuesto> Listar()
{
try
{
using (var ctx = new DataModel())
{
return ctx.Impuestos.Where(r => r.bStatus == true).ToList();
}
}
catch (Exception)
{
throw;
}
}
public static Impuesto BuscarporID(int pkImpuesto)
{
try
{
using (var ctx = new DataModel())
{
return ctx.Impuestos.Where(r => r.idImpuesto == pkImpuesto).FirstOrDefault();
}
}
catch (Exception)
{
throw;
}
}
public static void Actualizar(ImpuestosViewModel Datos)
{
//se crean la funcion para buscar el alumno dependiendo de los datos
Impuesto dato = BuscarporID(Datos.txtpkImpuesto);
dato.idImpuesto = Datos.txtpkImpuesto;
dato.sTipoImpuesto = Datos.txtTipoImpuesto;
dato.sImpuesto = Datos.txtImpuesto;
dato.dTasaImpuesto = Datos.txtTasaImpuesto;
try
{
using (var ctx = new DataModel())
{
ctx.Entry(dato).State = EntityState.Modified;
ctx.SaveChanges();
}
}
catch (Exception)
{
throw;
}
}
public static void Borrar(int id)
{
//se crean la funcion para buscar el alumno dependiendo de los datos
Impuesto dato = BuscarporID(id);
dato.bStatus = true;
try
{
using (var ctx = new DataModel())
{
ctx.Entry(dato).State = EntityState.Deleted;
ctx.SaveChanges();
}
}
catch (Exception)
{
throw;
}
}
public static void Guardar(ImpuestosViewModel Datos)
{
Impuesto dato = new Impuesto();
dato.sTipoImpuesto = Datos.txtTipoImpuesto;
dato.sImpuesto = Datos.txtImpuesto;
dato.dTasaImpuesto = Datos.txtTasaImpuesto;
try
{
using (var ctx = new DataModel())
{
ctx.Entry(dato).State = EntityState.Added;
ctx.SaveChanges();
}
}
catch (Exception)
{
throw;
}
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class Mesh_Generator : MonoBehaviour
{
public Material mat;
float width = 0.5f;
float depth = 0.5f;
float length = 1.5f;
// Start is called before the first frame update
void Start()
{
Mesh mesh = new Mesh();
Vector3[] vertices = new Vector3[6];
/*vertices[0] = new Vector3(-width, -depth);
vertices[1] = new Vector3(-width, depth);
vertices[2] = new Vector3(width, depth);
vertices[3] = new Vector3(width, -depth);*/
//gem
vertices[0] = new Vector3(-width, 0, -depth);
vertices[1] = new Vector3(width, 0, -depth);
vertices[2] = new Vector3(width, 0, depth);
vertices[3] = new Vector3(-width, 0, depth);
vertices[4] = new Vector3(0, length, 0);
vertices[5] = new Vector3(0, -length, 0);
mesh.vertices = vertices;
mesh.triangles = new int[] { 0, 1, 4, 1, 2, 4, 2, 3, 4, 3, 0, 4, 0, 1, 5, 1, 2, 5, 2, 3, 5, 3, 0, 5};
GetComponent<MeshFilter>().mesh = mesh;
GetComponent<MeshRenderer>().material = mat;
}
// Update is called once per frame
void Update()
{
}
}
|
using System;
using System.Data;
using Proyecto_Web.Modelos;
namespace Proyecto_Web.Vistas.Private.Supervisor
{
public partial class supervisor : System.Web.UI.Page
{
PERSONA MOD_PERSONA = new PERSONA();
MENU mod_menu = new MENU();
public string foto, Nombre, n1, n2, ape1, ape2, IDn;
DataTable tabla = new DataTable();
SUPERVISOR mod_supervisor = new SUPERVISOR();
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (Session["CORREO_ELECTRONICO"].ToString().Equals(null))
{
Response.Redirect("~/Vistas/Public/Index.aspx");
}
}
catch (Exception)
{
Response.Redirect("~/Vistas/Public/Index.aspx");
}
tabla = mod_supervisor.ConsultarSupervisorAll();
Rep_Supervisor.DataSource = tabla;
Rep_Supervisor.DataBind();
}
}
} |
// Copyright 2017-2019 Elringus (Artyom Sovetnikov). All Rights Reserved.
using System;
using System.Collections.Generic;
using UnityEditor;
namespace Naninovel
{
public class StateSettings : ConfigurationSettings<StateConfiguration>
{
protected override Dictionary<string, Action<SerializedProperty>> OverrideConfigurationDrawers => new Dictionary<string, Action<SerializedProperty>> {
[nameof(StateConfiguration.StateRollbackSteps)] = property => { if (Configuration.StateRollbackMode != StateRollbackMode.Disabled) EditorGUILayout.PropertyField(property); },
[nameof(StateConfiguration.SavedRollbackSteps)] = property => { if (Configuration.StateRollbackMode == StateRollbackMode.Full) EditorGUILayout.PropertyField(property); }
};
}
}
|
namespace Workout.Models.Settings
{
/// <summary>
/// Enumerator that contains all distance units.
/// </summary>
public enum DistanceUnit
{
/// <summary>
/// Kilometer.
/// </summary>
Km,
/// <summary>
/// Mile.
/// </summary>
Mile
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sudoku_Designer
{
class SudokuController
{
protected SudokuLevel sudokuLevel;
protected SudokuDisplay display;
protected SudokuGet get;
protected SudokuSet set;
public void Go(SudokuLevel theSudokuLevel, SudokuDisplay theSudokuDisplay, SudokuGet theSudokuGet, SudokuSet theSudokuSet)
{
sudokuLevel = theSudokuLevel;
display = theSudokuDisplay;
get = theSudokuGet;
set = theSudokuSet;
display.Start();
//Initial State of Sudoku Level
sudokuLevel.SetSize(6);
display.Get(sudokuLevel.Output());
//Testing GetByRow, GetByCol and GetByCell
display.Get(get.GetByCell(sudokuLevel, 1));
display.Get(get.GetByRow(sudokuLevel, 0, 2));
display.Get(get.GetByCol(sudokuLevel, 3, 0));
//Testing SetByRow, SetByCol and SetByCell
set.SetByCell(sudokuLevel, 1, 69);
set.SetByRow(sudokuLevel, 0, 2, 420);
set.SetByCol(sudokuLevel, 3, 0, 78);
//Retesting GetByRow, GetByCol and GetByCell after changing values
display.Get(sudokuLevel.Output());
display.Get(get.GetByCell(sudokuLevel, 1));
display.Get(get.GetByRow(sudokuLevel, 0, 2));
display.Get(get.GetByCol(sudokuLevel, 3, 0));
display.Stop();
}
}
}
|
using CMS_Database.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CMS_Database.Interfaces
{
public interface ICTPhieuXuat:IGenericRepository<CTPhieuXuat>
{
IQueryable<CTPhieuXuat> GetById(int id);
}
}
|
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Threading;
using System.Windows.Input;
using AutoMapper;
using RFI.TimeTracker.ViewModels.Entities;
using RFI.TimeTracker.ViewModels.Interfaces;
using Model = RFI.TimeTracker.Models;
namespace RFI.TimeTracker.ViewModels
{
public class MainViewModel : Model.BaseNotifyObject
{
private readonly ITimesheetService _timesheetService;
private ObservableCollection<Timesheet> _timesheets;
private Timesheet _selectedTimesheet;
private Timer _actualDayWorkTimeTimer;
#region Binded properties
public ObservableCollection<Timesheet> Timesheets
{
get
{
if (_timesheets == null)
{
var timesheetsModel = _timesheetService.LoadAllTimesheets();
var timesheets = Mapper.Map<List<Timesheet>>(timesheetsModel);
_timesheets = new ObservableCollection<Timesheet>(
timesheets
.OrderByDescending(timesheet => timesheet.Year)
.ThenByDescending(timesheet => timesheet.Month));
SelectedTimesheet = _timesheets.FirstOrDefault();
}
return _timesheets;
}
}
public Timesheet SelectedTimesheet
{
get { return _selectedTimesheet; }
set { SetPropertyValue(ref _selectedTimesheet, value); }
}
public string ActualDayWorkTime
{
get
{
const string emptyDayWorkTime = "00:00";
if (ExistActualTimesheetEntry())
{
var workTime = GetActualTimesheetEntry().CalculateWorkTime(GetActualTime());
return workTime.HasValue ? workTime.Value.ToString(@"hh\:mm") : emptyDayWorkTime;
}
else
{
return emptyDayWorkTime;
}
}
}
#endregion
#region Commands
public ICommand StarWorkCommand { get; private set; }
public ICommand EndWorkCommand { get; private set; }
public ICommand StarLunchBreakCommand { get; private set; }
public ICommand EndLunchBreakCommand { get; private set; }
#endregion
public MainViewModel(ITimesheetService timesheetService)
{
_timesheetService = timesheetService;
InitCommands();
}
private void InitCommands()
{
StarWorkCommand = new DelegateCommand(OnStartWork);
EndWorkCommand = new DelegateCommand(OnEndWork);
StarLunchBreakCommand = new DelegateCommand(OnStarLunchBreak);
EndLunchBreakCommand = new DelegateCommand(OnEndLunchBreak);
}
public void OnWindowClosing(object sender, CancelEventArgs e)
{
SaveChanges();
}
private void OnStartWork()
{
var actualTimesheetEntry = GetActualTimesheetEntry();
actualTimesheetEntry.WorkStart = GetActualTime();
SelectActualTimesheet();
SaveChanges();
_actualDayWorkTimeTimer = new Timer(state => OnPropertyChanged("ActualDayWorkTime"), null, TimeSpan.FromSeconds(0), TimeSpan.FromSeconds(30));
}
private void OnEndWork()
{
var actualTimesheetEntry = GetActualTimesheetEntry();
actualTimesheetEntry.WorkEnd = GetActualTime();
SelectActualTimesheet();
SaveChanges();
if (_actualDayWorkTimeTimer != null)
{
_actualDayWorkTimeTimer.Dispose();
}
}
private void OnStarLunchBreak()
{
var actualTimesheetEntry = GetActualTimesheetEntry();
actualTimesheetEntry.LunchBreakStart = GetActualTime();
SelectActualTimesheet();
SaveChanges();
}
private void OnEndLunchBreak()
{
var actualTimesheetEntry = GetActualTimesheetEntry();
actualTimesheetEntry.LunchBreakEnd = GetActualTime();
SelectActualTimesheet();
SaveChanges();
}
private TimesheetEntry GetActualTimesheetEntry()
{
var actualTime = GetActualTime();
var actualTimesheet = GetActualTimesheet();
var actualTimesheetEntry =
actualTimesheet.TimesheetEntries.FirstOrDefault(te =>
(te.WorkStart.HasValue && te.WorkStart.Value.Day == actualTime.Day)
|| (te.WorkEnd.HasValue && te.WorkEnd.Value.Day == actualTime.Day)
|| (te.LunchBreakStart.HasValue && te.LunchBreakStart.Value.Day == actualTime.Day)
|| (te.LunchBreakEnd.HasValue && te.LunchBreakEnd.Value.Day == actualTime.Day));
if (actualTimesheetEntry == null)
{
actualTimesheetEntry = new TimesheetEntry();
actualTimesheet.TimesheetEntries.Add(actualTimesheetEntry);
}
return actualTimesheetEntry;
}
private Timesheet GetActualTimesheet()
{
var actualTime = GetActualTime();
var actualTimesheet =
Timesheets.FirstOrDefault(timesheet => timesheet.Month == actualTime.Month && timesheet.Year == actualTime.Year);
if (actualTimesheet == null)
{
actualTimesheet = new Timesheet
{
Month = actualTime.Month,
Year = actualTime.Year
};
Timesheets.Insert(0, actualTimesheet);
}
return actualTimesheet;
}
private bool ExistActualTimesheetEntry()
{
var actualTime = GetActualTime();
var actualTimesheet = GetActualTimesheet();
return actualTimesheet.TimesheetEntries.Any(te =>
(te.WorkStart.HasValue && te.WorkStart.Value.Day == actualTime.Day)
|| (te.WorkEnd.HasValue && te.WorkEnd.Value.Day == actualTime.Day)
|| (te.LunchBreakStart.HasValue && te.LunchBreakStart.Value.Day == actualTime.Day)
|| (te.LunchBreakEnd.HasValue && te.LunchBreakEnd.Value.Day == actualTime.Day));
}
private DateTime GetActualTime()
{
var actualTime = DateTime.Now;
return new DateTime(actualTime.Year, actualTime.Month, actualTime.Day, actualTime.Hour, actualTime.Minute, 0);
}
private void SelectActualTimesheet()
{
SelectedTimesheet = null;
SelectedTimesheet = _timesheets.First();
}
private void SaveChanges()
{
var timesheetsModel = Mapper.Map<List<Model.Timesheet>>(_timesheets);
_timesheetService.SaveTimesheeets(timesheetsModel);
}
}
}
|
using System.Collections.Generic;
using System;
namespace Binocle.Importers
{
[Serializable]
public class TexturePackerFile
{
public List<TexturePackerRegion> frames;
public TexturePackerMeta meta;
}
}
|
using System.IO;
using Assets._Src.Systems.Scripts;
using UnityEngine;
namespace Assets._Src.Systems.Save_System
{
public struct SaveSettingsObject
{
public float MasterVolume;
public float MusicVolume;
public float SfxVolume;
}
public struct SaveSettingsSystem : ISaveSystem
{
private static readonly string SAVE_FOLDER = Application.persistentDataPath + "/SaveData/";
public void Save()
{
if (!Directory.Exists(SAVE_FOLDER + "/Settings"))
{
Directory.CreateDirectory(SAVE_FOLDER + "/Settings");
}
var saveObject = new SaveSettingsObject()
{
MusicVolume = SettingsMenu.Instance.musicSlider.value,
SfxVolume = SettingsMenu.Instance.sfxSlider.value,
MasterVolume = SettingsMenu.Instance.masterSlider.value
};
var json = JsonUtility.ToJson(saveObject);
File.WriteAllText(SAVE_FOLDER + "/Settings" + "/settings" + ".json", json);
}
public object Load()
{
var dirInfo = new DirectoryInfo(SAVE_FOLDER + "/Settings");
var files = dirInfo.GetFiles("*.json");
FileInfo mostRecent = null;
foreach (var fileInfo in files)
{
if (mostRecent == null)
{
mostRecent = fileInfo;
}
else
{
if (fileInfo.LastWriteTime > mostRecent.LastWriteTime)
mostRecent = fileInfo;
}
}
if (mostRecent == null) return null;
var json = File.ReadAllText(mostRecent.FullName);
var saveObject = JsonUtility.FromJson<SaveSettingsObject>(json);
SettingsMenu.Instance.MasterVolume(saveObject.MasterVolume);
SettingsMenu.Instance.SfxVolume(saveObject.SfxVolume);
SettingsMenu.Instance.MusicVolume(saveObject.MusicVolume);
return saveObject;
}
}
} |
using TMPro;
using UnityEngine;
public class VacuumTube : MonoBehaviour
{
public TextMeshProUGUI text;
public char character;
public void Initialize(char character)
{
this.character = character;
text.SetText(character.ToString());
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Runtime.Serialization;
using System.Xml.Serialization;
namespace ElectricityMonitor.Domain {
public class SensorDataContainer {
private SensorData _sensor;
public SensorData Sensor {
get { return _sensor; }
set { _sensor = value; }
}
}
/// <summary>
/// Sensor data object
/// </summary>
public class SensorData {
private int _nodeId;
public int NodeId {
get { return this._nodeId; }
set { this._nodeId = value; }
}
private DateTime _timeStamp;
public DateTime TimeStamp {
get { return this._timeStamp; }
set { this._timeStamp = value; }
}
private double _powerLevel;
public double PowerLevel {
get { return this._powerLevel; }
set { this._powerLevel = value; }
}
private bool _hasMotion;
public bool HasMotion {
get { return this._hasMotion; }
set { this._hasMotion = value; }
}
public SensorData() { }
public static SensorDataContainer ExportSensorData(SensorData data) {
SensorDataContainer sdc = null;
try {
sdc = new SensorDataContainer() { Sensor = data };
} catch (Exception) {
throw;
}
return(sdc);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace irc_client.session {
public class DialogDictionary {
Dictionary<Contact, DialogData> _dialogDictionary;
public DialogDictionary() {
this._dialogDictionary = new Dictionary<Contact, DialogData>();
}
public DialogData GetDialogByContact(Contact key) {
DialogData returnedData;
this._dialogDictionary.TryGetValue(key, out returnedData);
if (returnedData == null) {
this._dialogDictionary.Add(key, new DialogData(key));
}
return this._dialogDictionary[key];
}
public void AddDialog(Contact key, DialogData newValue) {
this._dialogDictionary.Add(key, newValue);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class GameManager : MonoBehaviour
{
//array that holds all the random places for the book to spawn
public List<GameObject> RandomEmptys = new List<GameObject>();
public GameObject BookPrefab;
public static int Score = 0;
public GameObject WinScreen;
public GameObject thirdButton;
public AudioSource winner;
public AudioSource almostDone;
// Use this for initialization
void Start()
{
//spawns in a key at a random place
int chosenSpawnPoint = Random.Range(0, RandomEmptys.Count);
GameObject instantiatedKey = GameObject.Instantiate(BookPrefab,RandomEmptys[chosenSpawnPoint].transform.position, Quaternion.identity, transform);
}
// Check the score to see what to do next
void Update()
{
if (Score == 2)
{
thirdButton.SetActive(true);
almostDone.Play();
}
if (Score == 3)
{
Debug.Log("You Win");
WinScreen.SetActive(true);
winner.Play();
Score = 0;
}
else
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using Sesi.WebsiteDaSaude.WebApi.Interfaces;
using Sesi.WebsiteDaSaude.WebApi.Models;
using Sesi.WebsiteDaSaude.WebApi.ViewModels;
namespace Sesi.WebsiteDaSaude.WebApi.Repositories
{
public class UsuarioRepository : IUsuarioRepository
{
public Usuarios BuscarPorEmailESenha(LoginViewModel login)
{
using (WebsiteDaSaudeContext ctx = new WebsiteDaSaudeContext())
{
var usuario = ctx.Usuarios.Include(x => x.IdPermissaoNavigation).FirstOrDefault(x => x.Email == login.Email && x.Senha == login.Senha);
if (usuario != null)
{
return usuario;
}
return null;
}
}
public Usuarios BuscarPorId(int id)
{
using (WebsiteDaSaudeContext ctx = new WebsiteDaSaudeContext())
{
var usuario = ctx.Usuarios.Include(x => x.IdPermissaoNavigation).Include(x => x.IdBairroNavigation).FirstOrDefault(x => x.IdUsuario == id);
if (usuario != null)
{
return usuario;
}
return null;
}
}
public void Cadastrar(Usuarios usuario)
{
using (WebsiteDaSaudeContext ctx = new WebsiteDaSaudeContext())
{
if (usuario.Cep.Contains("-"))
{
usuario.Cep = usuario.Cep.Replace("-","");
}
var usuarioExistente = ctx.Usuarios.FirstOrDefault(x => x.Email == usuario.Email);
if (usuarioExistente != null)
{
throw new Exception("Esse email ja está cadastrado no sistema.");
} else
{
ctx.Usuarios.Add(usuario);
ctx.SaveChanges();
}
}
}
public void Editar(Usuarios usuarioPassado)
{
using (WebsiteDaSaudeContext ctx = new WebsiteDaSaudeContext())
{
var usuarioBuscado = ctx.Usuarios.FirstOrDefault(x => x.IdUsuario == usuarioPassado.IdUsuario);
if (usuarioBuscado == null)
{
throw new Exception("Usuário não encontrado no banco de dados");
} else
{
usuarioBuscado.IdPermissao = usuarioPassado.IdPermissao;
usuarioBuscado.NomeUsuario = usuarioPassado.NomeUsuario;
usuarioBuscado.DataNascimento = usuarioPassado.DataNascimento;
usuarioBuscado.Email = usuarioPassado.Email;
usuarioBuscado.Senha = usuarioPassado.Senha;
usuarioBuscado.IdBairro = usuarioPassado.IdBairro;
usuarioBuscado.Cep = usuarioPassado.Cep;
usuarioBuscado.Logradouro = usuarioPassado.Logradouro;
usuarioBuscado.Numero = usuarioPassado.Numero;
if (usuarioBuscado.Cep.Contains("-"))
{
usuarioBuscado.Cep = usuarioBuscado.Cep.Replace("-","");
}
ctx.Update(usuarioBuscado);
ctx.SaveChanges();
}
}
}
public void Excluir(int id)
{
using (WebsiteDaSaudeContext ctx = new WebsiteDaSaudeContext())
{
var usuarioBuscado = ctx.Usuarios.FirstOrDefault(x => x.IdUsuario == id);
ctx.Usuarios.Remove(usuarioBuscado);
ctx.SaveChanges();
}
}
public List<Usuarios> Listar()
{
using (WebsiteDaSaudeContext ctx = new WebsiteDaSaudeContext())
{
var lista = ctx.Usuarios.Include(x => x.IdBairroNavigation).Include(x => x.IdPermissaoNavigation).ToList();
foreach (var item in lista)
{
item.Senha = null;
item.IdPermissaoNavigation.Usuarios = null;
if (item.IdBairro != null)
{
item.IdBairroNavigation.Usuarios = null;
}
}
return lista;
}
}
}
} |
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class ChangeFunc : MonoBehaviour
{
private int merageType = 0;
public Transform notStatic;
public Transform Combined;
public Transform Meraged;
public Text _btnLabel;
private void Start()
{
_changeModel(1);
}
private void _changeModel(int newType)
{
switch (newType)
{
case 1:
notStatic.gameObject.SetActive(false);
Combined.gameObject.SetActive(true);
Meraged.gameObject.SetActive(false);
_btnLabel.text = "Combined";
merageType = 1;
break;
case 2:
notStatic.gameObject.SetActive(false);
Combined.gameObject.SetActive(false);
Meraged.gameObject.SetActive(true);
_btnLabel.text = "Meraged";
merageType = 2;
break;
default:
notStatic.gameObject.SetActive(true);
Combined.gameObject.SetActive(false);
Meraged.gameObject.SetActive(false);
_btnLabel.text = "Not Static";
merageType = 0;
break;
}
}
public void ChangeModel()
{
int n = merageType + 1;
if (n > 2)
{
n = 0;
}
_changeModel(n);
}
}
|
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.Runtime.InteropServices;
using Thrift.Transport;
using Thrift.Collections;
using Thrift.Server;
using Thrift.Protocol;
using Vss;
using VssDisk.DAL;
using VssDisk.BLL;
namespace VssDisk
{
public partial class Login : Form
{
public Login()
{
InitializeComponent();
}
private void Login_Load(object sender, EventArgs e)
{
}
#region 窗体随鼠标移动
[DllImport("user32.dll")]
public static extern bool ReleaseCapture();
[DllImport("user32.dll")]
public static extern bool SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);
private void Login_MouseDown(object sender, MouseEventArgs e)
{
ReleaseCapture();
SendMessage(this.Handle, 0x0112, 0xF012, 0);
}
#endregion
#region 保存密码的文字掩码控制CheckBox
private void lblMask_Click(object sender, EventArgs e)
{
ckbSavePsw.Checked = !ckbSavePsw.Checked;
}
#endregion
#region 主逻辑之登录
private void lblLogin_Click(object sender, EventArgs e)
{
//调用登录验证逻辑!
bool bPass = BLLControl.Login(txtVssId.Text, txtPassword.Text, "VssDisk");
if (bPass)
{
MessageBox.Show("Wrong Username OR Password ! Please Retry !");
return;
}
else
{
Main mainForm = new Main();
mainForm.Show();
this.Hide();
}
}
#endregion
#region 主逻辑之退出
private void lblExit_Click(object sender, EventArgs e)
{
Application.Exit();
}
#endregion
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MechaWheel : GameTimeObject
{
// Configurable Parameters
[SerializeField] Rigidbody wheelBody = null;
[SerializeField] Rigidbody springBody = null;
[SerializeField] float maxWheelRPM = 500.0f;
// State variable
Vector3 savedSpringVelocity;
Vector3 savedSpringAngularVelocity;
Vector3 savedWheelVelocity;
Vector3 savedWheelAngularVelocity;
private void Awake()
{
if(wheelBody)
wheelBody.maxAngularVelocity = (2.0f * Mathf.PI) * (maxWheelRPM / 60.0f);
}
/// <summary>
/// Rotate wheel to generate vehicle acceleration.
/// </summary>
/// <param name="torqueAmount">Amount of torque provided by motor. More torque means more movement power.</param>
public void Accelerate(float torqueAmount)
{
if(!wheelBody || torqueAmount == 0.0f)
return;
Vector3 torqueForce = torqueAmount * wheelBody.transform.right;
wheelBody.AddTorque(torqueForce, ForceMode.Force);
}
/// <summary>
/// Pause game object activity.
/// </summary>
public override void OnPause()
{
if(springBody)
{
savedSpringAngularVelocity = springBody.angularVelocity;
savedSpringVelocity = springBody.velocity;
springBody.isKinematic = true;
}
if(wheelBody)
{
savedWheelAngularVelocity = wheelBody.angularVelocity;
savedWheelVelocity = wheelBody.velocity;
wheelBody.isKinematic = true;
}
}
/// <summary>
/// Un-pause game object activity.
/// </summary>
public override void OnResume()
{
if(springBody)
{
springBody.isKinematic = false;
springBody.velocity = savedSpringVelocity;
springBody.angularVelocity = savedSpringAngularVelocity;
}
if(wheelBody)
{
wheelBody.isKinematic = false;
wheelBody.velocity = savedWheelVelocity;
wheelBody.angularVelocity = savedWheelAngularVelocity;
}
}
/// <summary>
/// Prepare game object for game end.
/// </summary>
public override void OnGameOver()
{
// Nothing special
}
}
|
using MediatR;
namespace Publicon.Infrastructure.Commands.Models.User
{
public class ResetPasswordCommand : IRequest
{
public string SecurityCode { get; set; }
public string NewPassword { get; set; }
}
}
|
using System;
namespace OmniSharp.Extensions.LanguageServer.Protocol.Server.Capabilities
{
/// <summary>
///
/// </summary>
/// <remarks>
/// Is not a record on purpose...
/// get; set; for the moment, to allow for replacement of values.
/// </remarks>
[Obsolete(Constants.Proposal)]
public class ProposedServerCapabilities : ServerCapabilities
{
}
}
|
using System;
namespace XamChat
{
public interface ISetting
{
User User{get;set;}
void Save();
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using NUnit.Framework;
using SelfCheckout.Kiosk.Controller;
using SelfCheckout.Model;
using SelfCheckout.Repository;
namespace SelfCheckout.Kiosk.UnitTests.Controller
{
[TestFixture]
public class PurchaseTester
{
#region Test Data Collections
private IRepository _repository;
private string _repositoryFolderName;
[SetUp]
public void SetUp()
{
_repositoryFolderName = Path.Combine("C:\\ShoppingList\\",
"SelfCheckout.UnitTests");
_repository = new GenericRepository(_repositoryFolderName);
}
[TearDown]
public void TearDown()
{
Directory.Delete(_repositoryFolderName, true);
}
public static IEnumerable<string> ItemNames
{
get
{
yield return "apple";
yield return "banana";
yield return "carrot";
}
}
public static IEnumerable<Item> TestItems
{
get
{
yield return new Item("apple", 0.52m);
yield return new Item("banana", 4.56m);
yield return new Item("carrot", 1.01m);
}
}
public static IEnumerable<Item> TestCart1
{
get
{
List<Item> items = new List<Item>();
items.AddRange(GetTestItem("apple", 2));
items.AddRange(GetTestItem("banana", 2));
items.AddRange(GetTestItem("carrot", 2));
return items;
}
}
public static IEnumerable<Item> TestCart2
{
get
{
List<Item> items = new List<Item>();
items.AddRange(GetTestItem("apple", 2));
items.AddRange(GetTestItem("banana", 3));
items.AddRange(GetTestItem("carrot", 4));
return items;
}
}
public static IEnumerable<Item> TestCart3
{
get
{
List<Item> items = new List<Item>();
items.AddRange(GetTestItem("apple", 5));
items.AddRange(GetTestItem("banana", 6));
items.AddRange(GetTestItem("carrot", 7));
return items;
}
}
public static IEnumerable<IEnumerable<Item>> TestCarts
{
get
{
yield return new List<Item>(TestCart1);
yield return new List<Item>(TestCart2);
yield return new List<Item>(TestCart3);
}
}
#endregion
#region Helpers
private static Item GetTestItem(string name)
{
return TestItems.Single(g => g.Name == name);
}
private static IEnumerable<Item> GetTestItem(string name, int count)
{
for (int i = 0; i < count; i++)
{
yield return new Item(TestItems.Single(x => x.Name == name));
}
}
private static decimal GetRandomDecimal(int min, int max)
{
Random random = new Random();
double next = random.NextDouble();
return new decimal(min + next*(max - min));
}
#endregion
[Test]
public void purchase_items_discount_price_is_same_as_regular_price_by_default()
{
IEnumerable<Item> items = TestItems.ToList();
Purchase purchase = new Purchase(items.Select(x => new Item(x)));
for (int i = 0; i < items.Count(); i++)
{
Assert.AreEqual(items.ElementAt(i).Price, purchase.BuyItems.ElementAt(i).Price);
}
}
[Test]
[TestCaseSource(nameof(TestCarts))]
public void applying_a_sale_sets_price_for_all_items_of_that_type_in_purchase(
IEnumerable<Item> cart)
{
decimal salePrice = new Random().Next(4) + Math.Round(GetRandomDecimal(0, 1), 2);
List<Sale> sales = new List<Sale>();
foreach (string itemName in ItemNames)
{
sales.Add(new Sale(itemName, salePrice));
}
Purchase purchase = new Purchase(cart);
purchase.ApplySales(sales);
foreach (string itemName in ItemNames)
{
IEnumerable<Item> items = purchase.BuyItems.Where(x => x.Name == itemName);
Assert.That(items.All(a => a.Price == salePrice || a.BasePrice < salePrice));
}
}
[Test]
[TestCaseSource(nameof(TestCarts))]
public void group_sale_sets_price_for_a_set_of_required_items(IEnumerable<Item> sampleCart)
{
decimal salePrice = new Random().Next(4) + Math.Round(GetRandomDecimal(0, 1), 2);
int itemsRequired = new Random().Next(1, 5);
List<Sale> sales = new List<Sale>();
foreach (string itemName in ItemNames)
{
sales.Add(new Sale(GetTestItem(itemName).Name, salePrice, itemsRequired));
}
Purchase purchase = new Purchase(sampleCart);
purchase.ApplySales(sales);
foreach (string itemName in ItemNames)
{
int applicableItemsCount = purchase.BuyItems.Count(x => x.Name == itemName);
int discountedItemsCount = purchase.BuyItems.Count(p => (p.Name == itemName) && (p.Price == Math.Round(salePrice/itemsRequired,2) || p.BasePrice < Math.Round(salePrice / itemsRequired, 2)));
Assert.That((discountedItemsCount == 0) || (applicableItemsCount % discountedItemsCount < itemsRequired));
}
}
[Test]
[TestCaseSource(nameof(TestCarts))]
public void additional_product_sale_sets_price_for_the_highest_price_item_of_that_type(
IEnumerable<Item> sampleCart)
{
double salePrice = (double) Math.Round(GetRandomDecimal(0, 1), 2);
int itemsRequired = new Random().Next(1,3);
List<Sale> sales = new List<Sale>();
foreach (string itemName in ItemNames)
{
sales.Add(new Sale(GetTestItem(itemName).Name, itemsRequired, salePrice));
}
Purchase purchase = new Purchase(sampleCart);
purchase.ApplySales(sales);
foreach (string itemName in ItemNames)
{
double applicableItemsCount = purchase.BuyItems.Count(x => x.Name == itemName);
double discountedItemsCount = purchase.BuyItems.Count(p => (p.Name == itemName) && (p.Price == Math.Round(p.BasePrice*(decimal)salePrice,2)));
int expectedDiscountedItemsCount = (int) Math.Floor(applicableItemsCount/(itemsRequired + 1));
Assert.That(expectedDiscountedItemsCount == (int) discountedItemsCount);
}
}
}
}
|
using System.Threading.Tasks;
namespace Caliburn.Light
{
/// <summary>
/// Denotes an instance which may prevent closing.
/// </summary>
public interface ICloseGuard : IClose
{
/// <summary>
/// Called to check whether or not this instance can close.
/// </summary>
/// <returns>A task containing the result of the close check.</returns>
Task<bool> CanCloseAsync();
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.EntityFrameworkCore;
using Npgsql.EntityFrameworkCore.PostgreSQL;
using ApcUpsLogger.Utils;
using ApcUpsLogger.DataAccess;
using ApcUpsLogger.Engine;
namespace ApcUpsLogger
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
var connection = @"User ID=application;Password=1234;Host=localhost;Port=5432;Database=apcups;Pooling=true;";
services.AddDbContext<ApcUpsLoggerDbContext>(options => options.UseNpgsql(connection));
services.AddScoped<ApcDevice, ApcDevice>();
services.AddScoped<ApcDbLogger, ApcDbLogger>();
services.AddTransient<ScopedRunner, ScopedRunner>();
services.AddSingleton<PeriodicLogger, PeriodicLogger>();
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseMvc();
app.ApplicationServices.GetService<PeriodicLogger>().Run();
}
}
}
|
namespace Detectors
{
public abstract class Detector : ISwitchable, ICheckupSettings
{
private static byte CheckupTime = 60; // время обследования
public const byte ON = 1; // работает
public const byte OFF = 0; // не работает (простаивает)
public const byte BROKEN = 2; // неисправен
private byte status; // отображает текущее состояние датчика
private string name = "Датчик"; // название датчика
public string Name
{
get
{
return name; // возвращает имя датчика
}
set
{
name = value; // устаналивает имя датчика
}
}
public static byte CHECKUP_TIME
{
get
{
return CheckupTime; // получить время проведения обследования
}
set
{
CheckupTime = value; // изменить время проведения обследования
}
}
public abstract void switchOn(); // включить датчик
public abstract void switchOff(); // выключить датчик (если не задействован в обследовании)
public abstract void checkUp(); // проверить состояние датчика
public abstract void start(); // начать измерения
public abstract void stop(); // остановить измерения
public abstract int[] transfer(); // передать данные датчика
}
} |
using UnityEngine;
using System.Collections;
public class UfoBeamTrigger : MonoBehaviour {
public bool fire = false;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
}
void OnTriggerEnter(Collider other)
{
if (other.tag == "Player")
{
fire = true;
}
}
void OnTriggerExit(Collider other)
{
if (other.tag == "Player")
{
fire = false;
}
}
}
|
using UnityEngine;
using System.Collections;
public class Slot
{
private int size = 64;
private GUISkin skin;
private Item item;
private Rect bounds;
public Slot(int x, int y, GUISkin skin)
{
bounds = new Rect(x, y, size, size);
this.skin = skin;
}
public void SetItem(Item item)
{
this.item = item;
}
public Item RemoveItem()
{
Item result = item;
item = null;
return result;
}
public Item GetItem()
{
return item;
}
public void GetGUI()
{
GUI.Box(bounds, "", skin.GetStyle("Empty"));
}
public Rect GetBounds()
{
return bounds;
}
} |
using UnityEngine;
using System.Collections;
using AssemblyCSharp;
public class Character : MonoBehaviour, IHover
{
public Vector2 coords;
public BoxCollider2D boxCollider;
public int maxHealth;
public int currentHealth;
public int moveTiles;
public bool moveGridSpawned;
#region IHover implementation
public void OnMouseEnter ()
{
if ( Cursor.instance.coords != this.coords )
{
Cursor.instance.gameObject.transform.position = this.gameObject.transform.position;
Cursor.instance.coords = this.coords;
}
return;
}
public void OnMouseExit ()
{
return;
// throw new System.NotImplementedException ();
}
#endregion
}
|
using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
namespace SwaggerDocs
{
public class Startup
{
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public void Configure(IApplicationBuilder app)
{
app.UseSwaggerUI(c =>
{
var config = Configuration.GetSection("Swagger").Get<SwaggerConfig>();
if (config is null || config.Endpoints is null || config.Endpoints.Length == 0)
{
throw new Exception("Nenhum endpoint swagger foi definido");
}
foreach (var endpoint in config.Endpoints)
{
c.SwaggerEndpoint(endpoint.Url, endpoint.Nome);
}
// Endpoint do swagger vai responder em /
c.RoutePrefix = string.Empty;
});
}
}
}
|
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="CreateConnectionString.cs" company="CGI">
// Copyright (c) CGI. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CGI.Reflex.Core;
using ManyConsole;
using NDesk.Options;
namespace CGI.Reflex.Commands.Commands
{
public class CreateConnectionString : ConsoleCommand
{
public CreateConnectionString()
{
IsCommand("create-connection-string", "Create a connection string");
Options = new OptionSet
{
{ "t|databaseType=", "Type of database", (DatabaseType db) => DatabaseType = db },
{ "f|file=", "File to use", f => FileName = f },
{ "s|server=", "Server name (with named instance if needed)", s => ServerName = s },
{ "d|dbName=", "Name of the database", d => DbName = d },
{ "u|username=", "Username (in case of SQL Auth)", d => Username = d },
{ "p|password=", "Password (in case of SQL Auth)", d => Password = d }
};
}
public DatabaseType DatabaseType { get; set; }
public string FileName { get; set; }
public string ServerName { get; set; }
public string DbName { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public override int Run(string[] remainingArguments)
{
string connectionString;
switch (DatabaseType)
{
case DatabaseType.SqlServer2008:
if (string.IsNullOrEmpty(ServerName))
throw new OptionException("The server argument is mandatory when using SqlServer.", "server");
if (string.IsNullOrEmpty(DbName))
throw new OptionException("The dbName argument is mandatory when using SqlServer.", "dbName");
if (string.IsNullOrEmpty(Username))
{
connectionString = string.Format("Server={0};Database={1};Trusted_Connection=True;", ServerName, DbName);
}
else
{
if (string.IsNullOrEmpty(Password))
throw new OptionException("The password argument is mandatory when using SqlServer and providing a username.", "password");
connectionString = string.Format("Server={0};Database={1};User ID={2};Password={3};", ServerName, DbName, Username, Password);
}
break;
case DatabaseType.SQLite:
if (string.IsNullOrEmpty(FileName))
throw new OptionException("The file argument is mandatory when using SQLite.", "file");
connectionString = string.Format("Data Source={0};Version=3;", FileName);
break;
default:
throw new ArgumentOutOfRangeException();
}
if (!string.IsNullOrEmpty(connectionString))
{
Console.WriteLine(connectionString);
if (Utils.SafeSetClipboard(connectionString))
Console.WriteLine(@"The connection string has been placed on the clipboard.");
}
return 0;
}
}
}
|
using UnityEngine;
using System.Collections;
public class Attack3Collision : MonoBehaviour
{
public playerController player;
public Renderer rend;
public GroundCollision grounded;
public int displayCounter = 0;
public bool attack3Running = false;
public ParticleSystem ParticlesAttack3;
public AudioSource Attack3Sound;
// Use this for initialization
void Start()
{
rend = GetComponent<Renderer>();
rend.enabled = false;
}
// Update is called once per frame
void Update()
{
if ((int)player.attackState == 3)
{
if (player.attack3Pound)
{
displayCounter++;
}
else
{
displayCounter = 0;
}
if (displayCounter == 1)
{
Attack3Sound.PlayOneShot(Attack3Sound.clip);
}
if ((displayCounter > 3) && (displayCounter < 30))
{
rend.enabled = true;
attack3Running = true;
ParticlesAttack3.emissionRate = 10000;
}
else
{
rend.enabled = false;
attack3Running = false;
ParticlesAttack3.emissionRate = 0;
}
}
else
{
rend.enabled = false;
ParticlesAttack3.emissionRate = 0;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
public class BallManager : MonoBehaviour {
// Drop down menu on the inspector panel to select different modes
public enum Mode
{
Flash,
Disappear
};
public Mode mode;
public Stack<GameObject> unassigned;
public List<GameObject> targets;
public List<GameObject> distractors;
public int numTrials = 3; // Number of trials
public int numTotal = 5; // Total number of objects;
public int numTargets = 2; // Number of targets;
public int numRemove = 2; // Number of objects to be removed in Disappear Mode;
public int numFlash = 3; // Number of flashes in Flash Mode;
int numDistractors; // Number of Distractors
public Color distractorColor = Color.white;
public Color targetColor = Color.red;
public Color flashColor = Color.yellow;
public GameObject Prefab; // BouncyBall prefab
public int[] sendInfo; // The information to be send via LSL
public ToLSL LSLManager;
GameObject[] result; // Stores the objects that subject selects as the final result.
// Use this for initialization
void Start () {
// Initialize variables
numDistractors = numTotal - numTargets;
sendInfo = new int[1];
unassigned = new Stack<GameObject>();
targets = new List<GameObject>();
distractors = new List<GameObject>();
InstantiateBalls();
// Check mode
if (mode == Mode.Disappear)
StartCoroutine(Disappear());
else if (mode == Mode.Flash)
StartCoroutine(Flash());
}
// Update is called once per frame
void Update () {
}
/**
* Instantiate all objects in the scene.
*/
private void InstantiateBalls()
{
// Stores all the generated initial positions
List<Vector3> initialPositions = new List<Vector3>();
// Generates initial positions and instantiate a ball at that position
while (unassigned.Count < numTotal)
{
bool overlap = false;
var position = new Vector3(Random.Range(-3, 3), Random.Range(-3, 3), 10);
// Check for overlapping
foreach (Vector3 pos in initialPositions)
{
if (Vector3.Distance(position, pos) <= Prefab.GetComponent<SphereCollider>().radius)
overlap = true;
}
if (!overlap)
{
initialPositions.Add(position);
GameObject newBall = Instantiate(Prefab, position, Quaternion.identity);
// Put the ball as a child under Balls
newBall.transform.parent = gameObject.transform;
unassigned.Push(newBall);
}
}
}
// Coroutine for Disappear mode. Coroutine is only called once.
private IEnumerator Disappear()
{
for (int i = 0; i < numTrials; i++)
{
// Assign targets and distractors and send the starting timestamp
AddTargets(numTargets);
sendInfo[0] = 99;
LSLManager.pushSample();
AddDistractors();
yield return new WaitForSeconds(3f);
// Hide targets and send a timestamp
HideTargets();
sendInfo[0] = numTargets * 10 + numDistractors;
LSLManager.pushSample();
yield return new WaitForSeconds(3f);
// Remove an object each loop and send a timestamp
for (int j = 0; j < numRemove; j++)
{
RemoveObject();
sendInfo[0] = numTargets * 10 + numDistractors;
LSLManager.pushSample();
yield return new WaitForSeconds(3f);
}
// Send a timestamp when trial ends
sendInfo[0] = 100;
LSLManager.pushSample();
// Stop the balls from moving and let the user
// select the remaining targets
FreezeBalls();
UserSelect();
}
sendInfo[0] = 1000;
LSLManager.pushSample();
}
// Coroutine for Flash mode. Coroutine is only called once.
private IEnumerator Flash()
{
for (int j = 0; j < numTrials; j++)
{
// Assign targets and distractors and send the starting timestamp
AddTargets(numTargets);
sendInfo[0] = 99;
LSLManager.pushSample();
AddDistractors();
yield return new WaitForSeconds(3f);
// Hide targets and send a timestamp
HideTargets();
sendInfo[0] = numTargets * 10 + numDistractors;
LSLManager.pushSample();
yield return new WaitForSeconds(2f);
// Make an object flash each loop
for (int i = 0; i < numFlash; i++)
{
int index = FlashObject();
if (index / 10 == 1)
{
Debug.Log("Target FLash");
sendInfo[0] = 1;
LSLManager.pushSample();
yield return new WaitForSeconds(0.2f);
targets[index % 10].GetComponent<Renderer>().material.color = distractorColor;
}
else
{
Debug.Log("Distractor Flash");
sendInfo[0] = 0;
LSLManager.pushSample();
yield return new WaitForSeconds(0.2f);
distractors[index % 10].GetComponent<Renderer>().material.color = distractorColor;
}
yield return new WaitForSeconds(Random.Range(1.9f, 2.1f));
}
// Send a timestamp when trial ends
sendInfo[0] = 100;
LSLManager.pushSample();
// Stop the balls from moving and let the user
// select the remaining targets
FreezeBalls();
UserSelect();
}
sendInfo[0] = 1000;
LSLManager.pushSample();
}
// Assign targets and color them
private void AddTargets(int num)
{
for (int i = 0; i < num; i++)
{
targets.Add(unassigned.Pop());
targets.Last().GetComponent<Renderer>().material.color = targetColor;
targets.Last().tag = "Target";
}
}
// Assign Distractors
private void AddDistractors()
{
while (unassigned.Count != 0)
{
distractors.Add(unassigned.Pop());
distractors.Last().tag = "Distractor";
}
}
// Hide targets
private void HideTargets()
{
foreach(GameObject target in targets)
target.GetComponent<Renderer>().material.color = distractorColor;
}
// Remove a target from scene
private void RemoveTarget()
{
Destroy(targets.Last());
targets.Remove(targets.Last());
numTargets--;
}
// Remove a distractor from scene
private void RemoveDistractor()
{
Destroy(distractors.Last());
distractors.Remove(distractors.Last());
numDistractors--;
}
// Remove an object from scene (either target or distractor)
private void RemoveObject()
{
if (Random.Range(0, 2) == 0)
RemoveDistractor();
else
RemoveTarget();
}
// Make a distractor flash
private int FlashDistractor()
{
int index = Random.Range(0, distractors.Count());
distractors[index].GetComponent<Renderer>().material.color = flashColor;
return index+20;
}
// Make a target flash
private int FlashTarget()
{
int index = Random.Range(0, targets.Count());
targets[index].GetComponent<Renderer>().material.color = flashColor;
return index+10;
}
// Make an object flash (either target or distractor
private int FlashObject()
{
if (Random.value > 0.5f)
return FlashTarget();
else
return FlashDistractor();
}
// Stop balls from moving
private void FreezeBalls()
{
GameObject[] endTargets;
GameObject[] endDistractors;
endTargets = GameObject.FindGameObjectsWithTag("Target");
endDistractors = GameObject.FindGameObjectsWithTag("Distractor");
foreach (GameObject target in endTargets)
{
target.GetComponent<Rigidbody>().constraints = RigidbodyConstraints.FreezeAll;
}
foreach(GameObject distractor in endDistractors)
{
distractor.GetComponent<Rigidbody>().constraints = RigidbodyConstraints.FreezeAll;
}
}
// Check the result from the user
private int CheckResult()
{
int res = 0;
foreach(GameObject gb in result)
{
if (gb.tag == "target")
res += 10;
else
res += 1;
}
return res;
}
// Stores the selected objects and send via LSL
private void UserSelect()
{
if (result != null)
{
int res = CheckResult();
sendInfo[0] = res + 100;
LSLManager.pushSample();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using Emgu.CV;
using Emgu.CV.Cvb;
using Emgu.CV.CvEnum;
using Emgu.CV.Structure;
using Emgu.CV.VideoSurveillance;
using Emgu.CV.BgSegm;
using System.Runtime.InteropServices;
using System.Threading;
using Emgu.CV.UI;
namespace CuentaPersonas
{
public partial class Inicio : Form
{
private static VideoCapture _cameraCapture;
private static BackgroundSubtractor _fgDetector;
private static CvBlobDetector _blobDetector;
private static CvTracks _tracker;
private bool _inProgress;
private Size tam5 = new Size(5, 5);
private int DIR_ABAJO_ARRIBA = 1;
private int DIR_IZQ_DER = 2;
private MCvScalar SCALAR_BLACK = new MCvScalar(0.0, 0.0, 0.0);
private MCvScalar SCALAR_WHITE = new MCvScalar(255.0, 255.0, 255.0);
private MCvScalar SCALAR_BLUE = new MCvScalar(255.0, 0.0, 0.0);
private MCvScalar SCALAR_GREEN = new MCvScalar(0.0, 255.0, 0.0);
private MCvScalar SCALAR_RED = new MCvScalar(0.0, 0.0, 255.0);
private MCvScalar SCALAR_ORANGE = new MCvScalar(0.0, 165.0, 255.0);
private MCvScalar SCALAR_CYAN = new MCvScalar(255.0, 255.0, 0.0);
private MCvScalar SCALAR_AMBER = new MCvScalar(0.0, 191.0, 255.0);
private int _contA;
private int _contB;
private List<uint> _idBlobsA;
private List<uint> _idBlobsB;
private int _direction;
private int _areaMin;
private int _areaMax;
private float _track1;
private uint _track2;
private uint _track3;
private Mat structuringElementErode;
private int cantErode;
private Mat structuringElementDilate;
private int cantDilate;
private Mat imgThresh;
private Mat forgroundMask;
private Point _p0;
private Point _p1;
private Point _p2;
private Point _pt3;
private Point _pt4;
private Point _pt5;
private Point _pt6;
private LineSegment2D l2;
private LineSegment2D l1;
private LineSegment2D line;
private bool parar;
private bool api;
private int _maxAreaEnviada;
private Size _gridImageSize = new Size(80,125);
private bool _mantenerImagenes;
private bool _mantenerTodasImagenes;
private int _seleccionPuntos = 0;
CognitiveService cog;
public Inicio()
{
InitializeComponent();
cboxMantener.SelectedIndex = 0;
ToolTip tt = new ToolTip();
tt.AutomaticDelay = 200;
tt.SetToolTip(this.btPuntos, "Click izquierdo sobre \nla imagen para elegir");
gridA.Columns[0].Width = _gridImageSize.Width;
gridB.Columns[0].Width = _gridImageSize.Width;
gridA.RowTemplate.DefaultCellStyle.Padding = new Padding(0, 4, 0, 4);
gridB.RowTemplate.DefaultCellStyle.Padding = new Padding(0, 4, 0, 4);
_maxAreaEnviada = (int) numMaxAreaScale.Value * 1000;
string[] tipo = new string[] { "Horizontal", "Vertical" };
comboBox1.Items.AddRange(tipo);
string[] shapes = new string[] { "Rectangle", "Ellipse", "Cross" };
comboBoxShapeE.Items.AddRange(shapes);
comboBoxShapeE.Text = "Ellipse";
textBoxErodeSize.Text = "15";
textBoxErodeCant.Text = "3";
comboBoxShapeD.Items.AddRange(shapes);
comboBoxShapeD.Text = "Ellipse";
textBoxDilateSize.Text = "12";
textBoxDilateCant.Text = "3";
textBoxTrackerInac.Text = "5";
textBoxTrackerActive.Text = "5";
textBoxTrackerDist.Text = "0,01";
forgroundMask = new Mat();
imgThresh = new Mat();
_p0 = new Point(-1, -1);
radioButtonDir1.Checked = true;
radioButtonDir2.Checked = false;
textBoxA1min.Text = "6000";
textBoxA1max.Text = "90000";
radioButtonMOG.Checked = true;
textX1.Text = "0,35";
textY1.Text = "0,55";
textX2.Text = "0,65";
textY2.Text = "0,55";
comboBox1.Text = "Vertical";
parar = false;
checkBox1.Checked = true;
richTextBox1.Enabled = checkBox1.Checked;
cog = new CognitiveService();
textBox1.Text = "";
}
// play
private void button1_Click(object sender, EventArgs e)
{
try
{
if (textBox1.Text.ToString().CompareTo("") != 0)
{
_cameraCapture = new VideoCapture(this.textBox1.Text.ToString());
btPuntos.Enabled = true;
gridA.Rows.Clear();
gridB.Rows.Clear();
gridA.ClearSelection();
gridB.ClearSelection();
_blobDetector = new CvBlobDetector();
_tracker = new CvTracks();
_inProgress = true;
_idBlobsA = new List<uint>();
_idBlobsB = new List<uint>();
_contA = 0;
_contB = 0;
_areaMin = int.Parse(textBoxA1min.Text);
_areaMax = int.Parse(textBoxA1max.Text);
_track1 = float.Parse(textBoxTrackerDist.Text);
_track2 = uint.Parse(textBoxTrackerInac.Text);
_track3 = uint.Parse(textBoxTrackerActive.Text);
if (radioButtonDir1.Checked == true)
{
_direction = 1;
}
else if (radioButtonDir2.Checked == true)
{
_direction = 2;
}
if (radioButtonMOG.Checked == true)
{
_fgDetector = new BackgroundSubtractorMOG(int.Parse(textBoxMOGhistory.Text), int.Parse(textBoxMOGnMix.Text), double.Parse(textBoxMOGRatio.Text), double.Parse(textBoxNSigma.Text));
}
else if (radioButtonMOG2.Checked == true)
{
_fgDetector = new BackgroundSubtractorMOG2(int.Parse(textBoxMOG2history.Text), int.Parse(textBoxMOG2thres.Text), checkBoxMOG2Shadow.Checked);
}
else if (radioButtonKNN.Checked == true)
{
_fgDetector = new BackgroundSubtractorKNN(int.Parse(textBoxKNNhistory.Text), double.Parse(textBoxKNNDist2.Text), checkBoxKNNShadow.Checked);
}
else if (radioButtonGMG.Checked == true)
{
_fgDetector = new BackgroundSubtractorGMG(int.Parse(textBoxGMG1.Text), double.Parse(textBoxGMG2.Text));
}
_blobDetector = new CvBlobDetector();
_tracker = new CvTracks();
float x1 = float.Parse(textX1.Text);
float y1 = float.Parse(textY1.Text);
float x2 = float.Parse(textX2.Text);
float y2 = float.Parse(textY2.Text);
_p1 = new Point((int)(_cameraCapture.Width * x1), (int)(_cameraCapture.Height * y1));
_p2 = new Point((int)(_cameraCapture.Width * x2), (int)(_cameraCapture.Height * y2));
ConfigGeometria();
api = checkBox1.Checked;
Application.Idle += ProcessFrame;
}
else
{
System.Windows.Forms.MessageBox.Show("Primero debe ingresar un stream.", "Cuidado.");
}
}
catch (NullReferenceException excpt)
{
MessageBox.Show(excpt.Message);
}
}
private void ConfigGeometria()
{
string shapeErode = comboBoxShapeE.Text;
int sizeErode = int.Parse(textBoxErodeSize.Text);
cantErode = int.Parse(textBoxErodeCant.Text);
if (shapeErode.CompareTo("Rectangle") == 0)
{
structuringElementErode = CvInvoke.GetStructuringElement(ElementShape.Rectangle, new Size(sizeErode, sizeErode),
_p0);
}
else if (shapeErode.CompareTo("Ellipse") == 0)
{
structuringElementErode = CvInvoke.GetStructuringElement(ElementShape.Ellipse, new Size(sizeErode, sizeErode),
_p0);
}
else if (shapeErode.CompareTo("Cross") == 0)
{
structuringElementErode = CvInvoke.GetStructuringElement(ElementShape.Cross, new Size(sizeErode, sizeErode), _p0);
}
string shapeDilate = comboBoxShapeD.Text;
int sizeDilate = int.Parse(textBoxDilateSize.Text);
cantDilate = int.Parse(textBoxDilateCant.Text);
if (shapeDilate.CompareTo("Rectangle") == 0)
{
structuringElementDilate = CvInvoke.GetStructuringElement(ElementShape.Rectangle,
new Size(sizeDilate, sizeDilate), _p0);
}
else if (shapeDilate.CompareTo("Ellipse") == 0)
{
structuringElementDilate = CvInvoke.GetStructuringElement(ElementShape.Ellipse, new Size(sizeDilate, sizeDilate),
_p0);
}
else if (shapeDilate.CompareTo("Cross") == 0)
{
structuringElementDilate = CvInvoke.GetStructuringElement(ElementShape.Cross, new Size(sizeDilate, sizeDilate),
_p0);
}
// ----------------------------
line = new LineSegment2D(_p1, _p2);
double vx = _p2.X - _p1.X;
double vy = _p2.Y - _p1.Y;
double mag = Math.Sqrt(vx * vx + vy * vy);
vx = (int) vx / mag;
vy = vy / mag;
double temp = vx;
vx = vy;
vy = -temp;
int length = 10;
int cx = (int) (_p2.X + vx * length);
int cy = (int) (_p2.Y + vy * length);
int dx = (int) (_p2.X + vx * -length);
int dy = (int) (_p2.Y + vy * -length);
_pt3 = new Point(cx, cy);
_pt4 = new Point(dx, dy);
l1 = new LineSegment2D(_pt3, _pt4);
// ---------
double vx2 = _p2.X - _p1.X;
double vy2 = _p1.Y - _p2.Y;
double mag2 = Math.Sqrt(vx2 * vx2 + vy2 * vy2);
vx2 = (int) vx2 / mag2;
vy2 = vy2 / mag2;
double temp2 = vx2;
vx2 = vy2;
vy2 = -temp2;
int length2 = 10;
int cx2 = (int) (_p1.X + vx2 * length2);
int cy2 = (int) (_p1.Y + vy2 * length2);
int dx2 = (int) (_p1.X + vx2 * -length2);
int dy2 = (int) (_p1.Y + vy2 * -length2);
_pt5 = new Point(cx2, cy2);
_pt6 = new Point(dx2, dy2);
l2 = new LineSegment2D(_pt5, _pt6);
}
// stop
private void button2_Click(object sender, EventArgs e)
{
if (_cameraCapture != null)
{
if (_inProgress)
{
_cameraCapture.Dispose();
_inProgress = false;
imageBox1.Image = null;
imageBox2.Image = null;
//GC.Collect();
}
}
}
private Image<Bgr, byte> Escalar(Mat mat, out double factor)
{
int area = mat.Width * mat.Height;
int maxArea150 = (int)(_maxAreaEnviada / (1.5 * 1.5));
int maxArea200 = _maxAreaEnviada / 4;
factor = 1.0;
var inter = Inter.Linear;
if (area < maxArea200)
{
factor = 2.0;
}
else if (area < maxArea150)
{
factor = 1.5;
inter = Inter.Cubic;;
}
else
{
return mat.ToImage<Bgr, byte>();
}
using (var img = mat.ToImage<Bgr, byte>())
{
return img.Resize(factor, inter);
}
}
private void AgregarFila(Image<Bgr, byte> img, DataGridView grid)
{
//int newWidth = (int)(face.Width / (double)face.Height * 100.0);
using (var copy = img.Resize(_gridImageSize.Width, _gridImageSize.Height, Inter.Linear))
{
this.Invoke(new Action(() =>
{
grid.Rows.Add(copy.ToBitmap(), "");
grid.Rows[0].Selected = false;
}));
}
}
private void ActualizarFila(Image<Bgr, byte> img, DataGridView grid,int idx,string text)
{
using (var copy = img.Resize(_gridImageSize.Width,_gridImageSize.Height, Inter.Linear))
{
this.Invoke(new Action(() =>
{
grid.Rows[idx].Cells[0].Value = copy.ToBitmap();
grid.Rows[idx].Cells[1].Value = text;
}));
}
}
private async void CallAPIAndUpdate(string directory, string date, Image<Bgr, byte> img, double scale, DataGridView grid, int imgIdx)
{
var analisis = await cog.DoWork(date, img.Bitmap, scale);
string res = cog.LogAnalysisResult(analisis);
richTextBox1.Text = richTextBox1.Text + imgIdx + " : " + res + "\n";
cog.DrawFaceResult(img.Bitmap, analisis, scale);
try
{
ActualizarFila(img, grid, imgIdx, res);
if (_mantenerImagenes)
{
if (analisis.Faces.Length > 0 ||_mantenerTodasImagenes)
{
img.Mat.Save(directory + date + ".jpg");
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
void ProcessFrame(object sender, EventArgs e)
{
if (_cameraCapture != null && _cameraCapture.Ptr != IntPtr.Zero)
{
Mat frame = _cameraCapture.QueryFrame();
if (frame != null)
{
Mat clone = frame.Clone();
Mat smoothedFrame = frame.Clone();
CvInvoke.GaussianBlur(smoothedFrame, imgThresh, tam5, 0);
_fgDetector.Apply(imgThresh, forgroundMask);
for (int i = 0; i < cantErode; i++)
{
CvInvoke.Dilate(forgroundMask, forgroundMask, structuringElementErode, _p0, 1, BorderType.Default, SCALAR_BLACK);
}
for (int i = 0; i < cantDilate; i++)
{
CvInvoke.Erode(forgroundMask, forgroundMask, structuringElementDilate, _p0, 1, BorderType.Default, SCALAR_BLACK);
}
CvBlobs blobs = new CvBlobs();
_blobDetector.Detect(forgroundMask.ToImage<Gray, byte>(), blobs);
blobs.FilterByArea(_areaMin, _areaMax);
float scale = (frame.Width + frame.Width) / 2.0f;
_tracker.Update(blobs, _track1 * scale, _track2, _track3);
if (_tracker.Count == 0 && _idBlobsA.Count != 0)
{
_idBlobsA.Clear();
}
if (_tracker.Count == 0 && _idBlobsB.Count != 0)
{
_idBlobsB.Clear();
}
foreach (var pair in _tracker)
{
CvTrack b = pair.Value;
CvInvoke.Rectangle(frame, b.BoundingBox, SCALAR_RED, 2);
//CvInvoke.PutText(frame, b.Id.ToString(), new Point((int)Math.Round(b.Centroid.X), (int)Math.Round(b.Centroid.Y)), FontFace.HersheyPlain, 8.0, new MCvScalar(255.0, 255.0, 255.0),4);
Point p3 = new Point((int)Math.Round(b.Centroid.X), (int)Math.Round(b.Centroid.Y));
CvInvoke.Circle(frame, p3, 3, SCALAR_GREEN, 3);
if (!parar)
{
if (_direction == 1) // Abajo / Arriba
{
// A
if (line.Side(p3) == 1 && !_idBlobsA.Contains(b.Id) && l1.Side(p3) == 1 && l2.Side(p3) == -1)
{
_idBlobsA.Add(b.Id);
}
if (line.Side(p3) == -1 && _idBlobsA.Contains(b.Id) && l1.Side(p3) == 1 && l2.Side(p3) == -1)
{
_idBlobsA.RemoveAll(item => item == b.Id);
_contA++;
labelEntraron.Text = "Entraron " + _contA.ToString();
// imagenes
Mat minimat = new Mat(clone, b.BoundingBox);
AgregarFila(minimat.ToImage<Bgr,byte>(),gridA);
}
// B
if (line.Side(p3) == -1 && !_idBlobsB.Contains(b.Id) && l1.Side(p3) == 1 && l2.Side(p3) == -1)
{
_idBlobsB.Add(b.Id);
}
if (line.Side(p3) == 1 && _idBlobsB.Contains(b.Id) && l1.Side(p3) == 1 && l2.Side(p3) == -1)
{
_idBlobsB.RemoveAll(item => item == b.Id);
_contB++;
labelSalieron.Text = "Salieron " + _contB.ToString();
// imagenes
ProcesarDeteccion(clone,b);
}
}
else if (_direction == 2) // izquierda / derecha
{
// A
if (line.Side(p3) == 1 && !_idBlobsA.Contains(b.Id) && l1.Side(p3) == 1 && l2.Side(p3) == 1)
{
_idBlobsA.Add(b.Id);
}
if (line.Side(p3) == -1 && _idBlobsA.Contains(b.Id) && l1.Side(p3) == 1 && l2.Side(p3) == 1)
{
_idBlobsA.RemoveAll(item => item == b.Id);
_contA++;
labelEntraron.Text = "Entraron " + _contA.ToString();
// imagenes
Mat minimat = new Mat(clone, b.BoundingBox);
AgregarFila(minimat.ToImage<Bgr, byte>(), gridA);
}
// B
if (line.Side(p3) == -1 && !_idBlobsB.Contains(b.Id) && l1.Side(p3) == 1 && l2.Side(p3) == 1)
{
_idBlobsB.Add(b.Id);
}
if (line.Side(p3) == 1 && _idBlobsB.Contains(b.Id) && l1.Side(p3) == 1 && l2.Side(p3) == 1)
{
_idBlobsB.RemoveAll(item => item == b.Id);
_contB++;
labelSalieron.Text = "Salieron " + _contB.ToString();
ProcesarDeteccion(clone, b);
}
}
}
}
CvInvoke.Line(frame, _p1, _p2, SCALAR_BLUE, 2);
CvInvoke.Line(frame, _pt4, _pt3, SCALAR_WHITE, 2);
CvInvoke.Line(frame, _pt5, _pt6, SCALAR_WHITE, 2);
if (_p1_tmp.X != -1)
{
CvInvoke.Circle(frame,_p1_tmp,8,this.SCALAR_CYAN,-1);
}
if (_p2_tmp.X != -1)
{
CvInvoke.Circle(frame, _p2_tmp, 8, this.SCALAR_CYAN, -1);
}
imageBox1.Image = frame;
imageBox2.Image = forgroundMask;
}
}
}
private void ProcesarDeteccion(Mat clone, CvTrack b)
{
// imagenes
Mat minimat = new Mat(clone, b.BoundingBox);
var img = minimat.ToImage<Bgr, byte>();
AgregarFila(img, gridB);
var lastItem = gridB.Rows.Count - 1;
if (api)
{
new Thread(() =>
{
CheckForIllegalCrossThreadCalls = false;
Thread.CurrentThread.IsBackground = true;
string date = DateTime.Now.ToString("dd-MM-yyyy-hh-mm-ss");
// Rectangle r = new Rectangle(b.BoundingBox.X - 50, b.BoundingBox.Y - 50, b.BoundingBox.Width + 100, b.BoundingBox.Height + 50);
using (Mat minimat2 = new Mat(clone, b.BoundingBox))
{
double factor;
using (var resized = Escalar(minimat2, out factor))
{
string directory = AppDomain.CurrentDomain.BaseDirectory;
try
{
resized.Mat.Save(directory + date + ".jpg");
CallAPIAndUpdate(directory, date, img, factor, gridB, lastItem);
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
}
}
}).Start();
}
}
/// <summary>
/// Convert the coordinates for the image's SizeMode. (MAGIA)
/// </summary>
/// https://www.codeproject.com/script/articles/view.aspx?aid=859100
/// http://csharphelper.com/blog/2014/10/select-parts-of-a-scaled-image-picturebox-different-sizemode-values-c/</a>
/// <param name="pic"></param>
/// <param name="X0">out X coordinate</param>
/// <param name="Y0">out Y coordinate</param>
/// <param name="x">actual coordinate</param>
/// <param name="y">actual coordinate</param>
public static void ConvertCoordinates(ImageBox pic,
out int X0, out int Y0, int x, int y)
{
int pic_hgt = pic.ClientSize.Height;
int pic_wid = pic.ClientSize.Width;
int img_hgt = pic.Image.Size.Height;
int img_wid = pic.Image.Size.Width;
X0 = x;
Y0 = y;
switch (pic.SizeMode)
{
case PictureBoxSizeMode.AutoSize:
case PictureBoxSizeMode.Normal:
// These are okay. Leave them alone.
break;
case PictureBoxSizeMode.CenterImage:
X0 = x - (pic_wid - img_wid) / 2;
Y0 = y - (pic_hgt - img_hgt) / 2;
break;
case PictureBoxSizeMode.StretchImage:
X0 = (int)(img_wid * x / (float)pic_wid);
Y0 = (int)(img_hgt * y / (float)pic_hgt);
break;
case PictureBoxSizeMode.Zoom:
float pic_aspect = pic_wid / (float)pic_hgt;
float img_aspect = img_wid / (float)img_wid;
if (pic_aspect > img_aspect)
{
// The PictureBox is wider/shorter than the image.
Y0 = (int)(img_hgt * y / (float)pic_hgt);
// The image fills the height of the PictureBox.
// Get its width.
float scaled_width = img_wid * pic_hgt / img_hgt;
float dx = (pic_wid - scaled_width) / 2;
X0 = (int)((x - dx) * img_hgt / (float)pic_hgt);
}
else
{
// The PictureBox is taller/thinner than the image.
X0 = (int)(img_wid * x / (float)pic_wid);
// The image fills the height of the PictureBox.
// Get its height.
float scaled_height = img_hgt * pic_wid / img_wid;
float dy = (pic_hgt - scaled_height) / 2;
Y0 = (int)((y - dy) * img_wid / pic_wid);
}
break;
}
}
private void radioButtonMOG_CheckedChanged(object sender, EventArgs e)
{
groupBox9.Enabled = false;
groupBox10.Enabled = false;
groupBox7.Enabled = true;
groupBox8.Enabled = false;
textBoxMOGhistory.Text = "200";
textBoxMOGnMix.Text = "5";
textBoxMOGRatio.Text = "0,7";
textBoxNSigma.Text = "0";
}
private void radioButtonMOG2_CheckedChanged(object sender, EventArgs e)
{
groupBox7.Enabled = false;
groupBox8.Enabled = true;
groupBox9.Enabled = false;
groupBox10.Enabled = false;
textBoxMOG2history.Text = "500";
textBoxMOG2thres.Text = "16";
checkBoxMOG2Shadow.Checked = true;
}
private void radioButtonKNN_CheckedChanged(object sender, EventArgs e)
{
groupBox7.Enabled = false;
groupBox8.Enabled = false;
groupBox9.Enabled = true;
groupBox10.Enabled = false;
textBoxKNNhistory.Text = "500";
textBoxKNNDist2.Text = "16";
checkBoxKNNShadow.Checked = false;
}
private void radioButtonGMG_CheckedChanged(object sender, EventArgs e)
{
groupBox7.Enabled = false;
groupBox8.Enabled = false;
groupBox9.Enabled = false;
groupBox10.Enabled = true;
textBoxGMG1.Text = "30";
textBoxGMG2.Text = "0,2";
}
[DllImport("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);
public int MakeLong(short lowPart, short highPart)
{
return (int)(((ushort)lowPart) | (uint)(highPart << 16));
}
public void ListViewItem_SetSpacing(ListView listview, short leftPadding, short topPadding)
{
const int LVM_FIRST = 0x1000;
const int LVM_SETICONSPACING = LVM_FIRST + 53;
SendMessage(listview.Handle, LVM_SETICONSPACING, IntPtr.Zero, (IntPtr)MakeLong(leftPadding, topPadding));
}
private void buttonParar_Click(object sender, EventArgs e)
{
parar = true;
}
private void buttonComenzar_Click(object sender, EventArgs e)
{
labelEntraron.Text = "Entraron 0";
labelSalieron.Text = "Salieron 0";
_contA = 0;
_contB = 0;
_idBlobsB.Clear();
_idBlobsA.Clear();
_tracker.Clear();
gridA.Rows.Clear();
gridB.Rows.Clear();
richTextBox1.Text = "";
parar = false;
}
private void button3_Click(object sender, EventArgs e)
{
if (comboBox1.Text.CompareTo("Horizontal") == 0)
{
radioButtonDir1.Checked = false;
radioButtonDir2.Checked = true;
textBoxA1min.Text = "4500";
textBoxA1max.Text = "90000";
radioButtonMOG.Checked = true;
textX1.Text = "0,37";
textY1.Text = "0,02";
textX2.Text = "0,37";
textY2.Text = "0,98";
}
else if (comboBox1.Text.CompareTo("Vertical") == 0)
{
radioButtonDir1.Checked = true;
radioButtonDir2.Checked = false;
textBoxA1min.Text = "6000";
textBoxA1max.Text = "90000";
radioButtonMOG.Checked = true;
textX1.Text = "0,35";
textY1.Text = "0,55";
textX2.Text = "0,65";
textY2.Text = "0,55";
}
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
if (checkBox1.Checked == true)
{
richTextBox1.Enabled = true;
}else
{
richTextBox1.Enabled = false;
}
}
private void numMaxAreaScale_ValueChanged(object sender, EventArgs e)
{
_maxAreaEnviada = (int)(numMaxAreaScale.Value * 1000);
}
private void checkBox1_CheckedChanged_1(object sender, EventArgs e)
{
api = checkBox1.Checked;
}
private void ckMantenerImg_CheckedChanged(object sender, EventArgs e)
{
_mantenerImagenes = ckMantenerImg.Checked;
cboxMantener.Enabled = ckMantenerImg.Checked;
}
private void cboxMantener_SelectedIndexChanged(object sender, EventArgs e)
{
_mantenerTodasImagenes = cboxMantener.SelectedIndex == 1;
}
private Point _p1_tmp = new Point(-1,-1);
private Point _p2_tmp = new Point(-1,-1);
private void imageBox1_Click(object sender, EventArgs e)
{
// Nota: parece no ser preciso cuando se maximiza la ventana, funciona bien sin maximizar
MouseEventArgs mouse = e as MouseEventArgs;
if (mouse != null && _seleccionPuntos > 0)
{
var mouseLoc = mouse.Location;
int px = 0;
int py = 0;
ConvertCoordinates(imageBox1, out px, out py, mouseLoc.X, mouseLoc.Y);
if (_seleccionPuntos == 1) // estoy eligiendo p1
{
_p1_tmp = new Point(px,py);
_seleccionPuntos = 2;
}
else if (_seleccionPuntos == 2) // ya elegi p1 y estoy eligiendo p2
{
try
{
_p1 = _p1_tmp;
_p2 = new Point(px, py);
_p1_tmp = new Point(-1, -1);
_p2_tmp = new Point(-1, -1);
var tmp = _p1;
if (_direction == DIR_ABAJO_ARRIBA)
{
_p2.Y = _p1.Y;
if (_p1.X > _p2.X)
{
// mantengo p1.X <= p2.X (no se si es importante)
_p1 = _p2;
_p2 = tmp;
}
}
else if (_direction == DIR_IZQ_DER)
{
_p2.X = _p1.X;
if (_p1.Y > _p2.Y)
{
// mantengo p1.Y <= p2.Y (no se si es importante)
_p1 = _p2;
_p2 = tmp;
}
}
// actualizo cuadros de texto para que quede igual si lo detengo
textX1.Text = String.Format("{0:n3}", Math.Round(_p1.X / (double)_cameraCapture.Width, 3));
textX2.Text = String.Format("{0:n3}", Math.Round(_p2.X / (double)_cameraCapture.Width, 3));
textY1.Text = String.Format("{0:n3}", Math.Round(_p1.Y / (double)_cameraCapture.Height, 3));
textY2.Text = String.Format("{0:n3}", Math.Round(_p2.Y / (double)_cameraCapture.Height, 3));
ConfigGeometria();
}
finally
{
// desactivo seleccion de puntos
_seleccionPuntos = 0;
btPuntos.Enabled = true;
}
}
}
}
private void btPuntos_Click(object sender, EventArgs e)
{
_seleccionPuntos = 1;
btPuntos.Enabled = false;
}
private void imageBox1_MouseMove(object sender, MouseEventArgs e)
{
if (_seleccionPuntos == 2)
{
int px = 0;
int py = 0;
var mouseLoc = e.Location;
ConvertCoordinates(imageBox1, out px, out py, mouseLoc.X, mouseLoc.Y);
if (_direction == DIR_ABAJO_ARRIBA)
{
_p2_tmp = new Point(px, _p1_tmp.Y);
}
else if (_direction == DIR_IZQ_DER)
{
_p2_tmp = new Point(_p1_tmp.X, py);
}
}
}
private void btKey_Click(object sender, EventArgs e)
{
if (txtKey.Text.Trim().Length == 32)
{
if (MessageBox.Show(this, "Desea cambiar la clave actual?","Cambiar clave?",MessageBoxButtons.OKCancel,MessageBoxIcon.Warning) == DialogResult.OK)
{
Properties.Settings.Default.MS_Key = txtKey.Text.Trim();
Properties.Settings.Default.Save();
MessageBox.Show(this, "Clave cambiada.\nTendrá efecto (para el usuario actual) al reiniciar el programa.", "Clave cambiada.", MessageBoxButtons.OK, MessageBoxIcon.Information);
txtKey.Clear();
}
}
else
{
MessageBox.Show(this,"La clave debe tener 32 caracteres.","Clave inválida",MessageBoxButtons.OK,MessageBoxIcon.Error);
}
}
}
}
|
using MisMarcadores.Data.Entities;
using System;
using System.Collections.Generic;
using System.Text;
namespace MisMarcadores.Repository
{
public interface IEquiposRepository : IGenericRepository<Equipo>
{
Equipo ObtenerEquipoPorId(Guid id);
Equipo ObtenerEquipoPorNombre(String nombre);
Equipo ObtenerEquipoPorDeporte(String nombreDeporte, String nombreEquipo);
void ModificarEquipo(Equipo equipo);
void BorrarEquipo(Guid id);
List<Equipo> ObtenerEquipos();
List<Equipo> ObtenerEquiposPorDeporte(String deporte);
}
}
|
//using NuGet.Protocol.Core.Types;
//using NuGet.Frameworks;
//using NuGet.Packaging.Core;
//using NuGet.Versioning;
//using System;
//using System.Collections.Generic;
//using System.Linq;
//using System.Text;
//using System.Threading;
//using System.Threading.Tasks;
//using Xunit;
//namespace Client.V2Test
//{
// public class DownloadResource2Tests : TestBase2
// {
// [Fact]
// public async Task DownloadResource_UnzippedUnobtrusive()
// {
// NuGet.UnzippedPackageRepository repo = new NuGet.UnzippedPackageRepository(@"C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET MVC 4\Packages");
// var sourceRepo = GetSourceRepository(repo);
// var resource = sourceRepo.GetResource<DownloadResource>();
// var stream = await resource.GetStream(new PackageIdentity("Microsoft.jQuery.Unobtrusive.Validation", NuGetVersion.Parse("2.0.30506.0")), CancellationToken.None);
// long length = stream.Length;
// Assert.Equal(9578, length);
// }
// [Fact]
// public async Task DownloadResource_Unzipped()
// {
// NuGet.UnzippedPackageRepository repo = new NuGet.UnzippedPackageRepository(@"C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET Web Stack 5\Packages");
// var sourceRepo = GetSourceRepository(repo);
// var resource = sourceRepo.GetResource<DownloadResource>();
// var stream = await resource.GetStream(new PackageIdentity("Microsoft.AspNet.MVC", NuGetVersion.Parse("5.2.2")), CancellationToken.None);
// long length = stream.Length;
// Assert.Equal(298098, length);
// }
// [Fact]
// public async Task DownloadResource_Local()
// {
// NuGet.LocalPackageRepository legacyRepo = new NuGet.LocalPackageRepository(@"C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET Web Stack 5\Packages");
// var sourceRepo = GetSourceRepository(legacyRepo);
// var resource = sourceRepo.GetResource<DownloadResource>();
// var stream = await resource.GetStream(new PackageIdentity("Microsoft.AspNet.MVC", NuGetVersion.Parse("5.2.2")), CancellationToken.None);
// long length = stream.Length;
// Assert.Equal(298098, length);
// }
// }
//}
|
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using lianda.Component;
namespace lianda.LD95
{
/// <summary>
/// LD9540 的摘要说明。
/// </summary>
public class LD9540 : BasePage
{
protected System.Web.UI.WebControls.Button BT_UPD;
protected System.Web.UI.WebControls.Button BT_RESET;
protected System.Web.UI.WebControls.Label useinfo;
protected Infragistics.WebUI.WebDataInput.WebTextEdit oldpass;
protected Infragistics.WebUI.WebDataInput.WebTextEdit newpass1;
protected Infragistics.WebUI.WebDataInput.WebTextEdit newpass2;
private void Page_Load(object sender, System.EventArgs e)
{
// 在此处放置用户代码以初始化页面
//加载用户名信息
this.useinfo.Text="你好:"+this.Session["UserName"].ToString()+". 请修改密码!" ;
}
#region Web 窗体设计器生成的代码
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.BT_UPD.Click += new System.EventHandler(this.BT_UPD_Click);
this.BT_RESET.Click += new System.EventHandler(this.BT_RESET_Click);
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
private void BT_UPD_Click(object sender, System.EventArgs e)
{
if(this.newpass1.Text==null||this.newpass1.Text=="" ||this.newpass1.Text.Trim().Length<1)
{
this.msgbox("新密码必须输入!");
return;
}
if(this.oldpass.Text==null||this.oldpass.Text=="" ||this.oldpass.Text.Trim().Length<1)
{
this.msgbox("旧密码必须输入!");
return;
}
if(this.newpass1.Text.Trim()!=this.newpass2.Text.Trim())
{
this.msgbox("新密码的2次输入不一致!请检查输入!");
return;
}
//LogInfo.LogEventInfo(this.Session["UserID"].ToString(),"LD9530","修改密码"," ");
///检查现在输入密码和数据库是否一致
string strSQL; // SQL语句
// 查询数据
strSQL = "select * from X_XTYH where DM = @DM AND MM=@MM AND ZT='00';";
SqlParameter[] prams = {
new SqlParameter("@DM",SqlDbType.VarChar,10),
new SqlParameter("@MM",SqlDbType.VarChar,15)
};
prams[0].Value= this.Session["UserID"].ToString() ;
prams[1].Value= this.oldpass.Text.Trim();
try
{
SqlDataReader dr = SqlHelper.ExecuteReader(SqlHelper.CONN_STRING,CommandType.Text,strSQL,prams);//
//赋值
if(dr.HasRows)//这里才开始修改密码
{
string strSQLUpd; // SQL语句
strSQLUpd = "UPDATE X_XTYH SET MM=@MM where DM=@DM"; //修改语句
//参数
SqlParameter[] pramsi = {
new SqlParameter("@DM",SqlDbType.VarChar,10),
new SqlParameter("@MM",SqlDbType.VarChar,15)
};
pramsi[0].Value= this.Session["UserID"].ToString() ;
pramsi[1].Value= this.newpass1.Text.Trim();
//执行语句 出错处理
try
{
int count = SqlHelper.ExecuteNonQuery(SqlHelper.CONN_STRING,CommandType.Text,strSQLUpd,pramsi);//
}
catch(Exception ex)
{
this.msgbox(ex.Message+"密码修改失败!!,检查数据 ");
//LogInfo.LogErrorInfo(this.Session["UserID"].ToString(),"LD9530","密码修改失败",ex.Message);
}
Session["UPD_PASS"]=null;
this.msgbox("密码修改成功!");
}
else
{
this.msgbox("原来密码输入错误!!");
dr.Close();
return;
}
dr.Close();
}
catch(Exception exO)
{
this.msgbox(exO.Message+"数据库连接出错!!");
//LogInfo.LogErrorInfo(this.Session["UserID"].ToString(),"LD9530","修改密码",exO.Message);
}
}
private void BT_RESET_Click(object sender, System.EventArgs e)
{
this.oldpass.Text="";
this.newpass1.Text="";
this.newpass2.Text="";
//LogInfo.LogEventInfo(this.Session["UserID"].ToString(),"LD9530","BT_RESET_Click"," ");
}
}
}
|
#region Using declarations
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Xml.Serialization;
using NinjaTrader.Cbi;
using NinjaTrader.Gui;
using NinjaTrader.Gui.Chart;
using NinjaTrader.Gui.SuperDom;
using NinjaTrader.Gui.Tools;
using NinjaTrader.Data;
using NinjaTrader.NinjaScript;
using NinjaTrader.Core.FloatingPoint;
using NinjaTrader.NinjaScript.DrawingTools;
#endregion
//This namespace holds Indicators in this folder and is required. Do not change it.
namespace NinjaTrader.NinjaScript.Indicators.Filt4b
{
public class Filt4bFirz234maOhlc : Indicator
{
private int Q1, Q2, Q3, Q4;
private double Mo;
private double W1, W2, W3, W4;
private Filt4bFirmaOhlc FirstIndicator, SecondIndicator, ThirdIndicator, FourthIndicator;
private int dataValidCount;
private double Firz234maUnBias(double m, int q1, int q2, int q3, int q4)
{
double b0, b01, b02, b03, b04;
double b1, b11, b12, b13, b14;
b01 = q1*(q1+1.0)*(q1+2.0)*(q1+3.0)*(q1+4.0)/((q1-q2)*(q1-q3)*(q1-q4)*(q1+q2+q3+q4+10.0));
b02 = q2*(q2+1.0)*(q2+2.0)*(q2+3.0)*(q2+4.0)/((q2-q1)*(q2-q3)*(q2-q4)*(q1+q2+q3+q4+10.0));
b03 = q3*(q3+1.0)*(q3+2.0)*(q3+3.0)*(q3+4.0)/((q3-q1)*(q3-q2)*(q3-q4)*(q1+q2+q3+q4+10.0));
b04 = q4*(q4+1.0)*(q4+2.0)*(q4+3.0)*(q4+4.0)/((q4-q1)*(q4-q2)*(q4-q3)*(q1+q2+q3+q4+10.0));
b11 = b01 * (2.0*(q1-1.0) + (q1*q2+q2*q3+q3*q4+q1*q3+q2*q4+q1*q4-35.0)/(q1+q2+q3+q4+10.0) - (q2+q3+q4));
b12 = b02 * (2.0*(q2-1.0) + (q1*q2+q2*q3+q3*q4+q1*q3+q2*q4+q1*q4-35.0)/(q1+q2+q3+q4+10.0) - (q1+q3+q4));
b13 = b03 * (2.0*(q3-1.0) + (q1*q2+q2*q3+q3*q4+q1*q3+q2*q4+q1*q4-35.0)/(q1+q2+q3+q4+10.0) - (q1+q2+q4));
b14 = b04 * (2.0*(q4-1.0) + (q1*q2+q2*q3+q3*q4+q1*q3+q2*q4+q1*q4-35.0)/(q1+q2+q3+q4+10.0) - (q1+q2+q3));
b0 = b01 + b02 + b03 + b04;
b1 = (b11 + b12 + b13 + b14)/b0;
return Math.Sqrt(b0*m*m+b1*b1/4.0) - b1/2.0;
}
private Tuple<double, double, double, double> Firz234maWeights(double m, int q1, int q2, int q3, int q4)
{
double a1, a2, a3, a4;
a1 = (m+q2)*(m+q3)*(m+q4)*(q1+1.0)*(q1+2.0)*(q1+3.0)*(q1+4.0)/
((q1-q2)*(q1-q3)*(q1-q4)* (m*m*m*(q1+q2+q3+q4+10)+m*m*(q1*q2+q1*q3+q1*q4+q2*q3+q2*q4+q3*q4-35)+
m*(q1*q2*q3+q1*q2*q4+q1*q3*q4+q2*q3*q4+50)+(q1*q2*q3*q4-24)));
a2 = (m+q1)*(m+q3)*(m+q4)*(q2+1.0)*(q2+2.0)*(q2+3.0)*(q2+4.0)/
((q2-q1)*(q2-q3)*(q2-q4)* (m*m*m*(q1+q2+q3+q4+10)+m*m*(q1*q2+q1*q3+q1*q4+q2*q3+q2*q4+q3*q4-35)+
m*(q1*q2*q3+q1*q2*q4+q1*q3*q4+q2*q3*q4+50)+(q1*q2*q3*q4-24)));
a3 = (m+q1)*(m+q2)*(m+q4)*(q3+1.0)*(q3+2.0)*(q3+3.0)*(q3+4.0)/
((q3-q1)*(q3-q2)*(q3-q4)* (m*m*m*(q1+q2+q3+q4+10)+m*m*(q1*q2+q1*q3+q1*q4+q2*q3+q2*q4+q3*q4-35)+
m*(q1*q2*q3+q1*q2*q4+q1*q3*q4+q2*q3*q4+50)+(q1*q2*q3*q4-24)));
a4 = (m+q1)*(m+q2)*(m+q3)*(q4+1.0)*(q4+2.0)*(q4+3.0)*(q4+4.0)/
((q4-q1)*(q4-q2)*(q4-q3)* (m*m*m*(q1+q2+q3+q4+10)+m*m*(q1*q2+q1*q3+q1*q4+q2*q3+q2*q4+q3*q4-35)+
m*(q1*q2*q3+q1*q2*q4+q1*q3*q4+q2*q3*q4+50)+(q1*q2*q3*q4-24)));
return new Tuple<double, double, double, double>(a1, a2, a3, a4);
}
public int ValidBarsStart
{
get
{
return (int)Math.Ceiling(UnBias ? Firz234maUnBias(M, Q, Q+1, Q+2, Q+3) : M);
}
}
protected override void OnStateChange()
{
if (State == State.SetDefaults)
{
Description = @"Filt4b Firz234maOhlc";
Name = "Filt4bFirz234maOhlc";
Calculate = Calculate.OnBarClose;
IsOverlay = false;
DisplayInDataBox = true;
DrawOnPricePanel = false;
DrawHorizontalGridLines = true;
DrawVerticalGridLines = true;
PaintPriceMarkers = true;
ScaleJustification = NinjaTrader.Gui.Chart.ScaleJustification.Right;
//Disable this property if your indicator requires custom values that cumulate with each new market data event.
//See Help Guide for additional information.
IsSuspendedWhileInactive = false;
MaximumBarsLookBack = MaximumBarsLookBack.Infinite;
// Properties
M = 10;
Q = 2;
UnBias = false;
// Plots
AddPlot(Brushes.DeepPink, "Firz234maOpen");
AddPlot(Brushes.DeepPink, "Firz234maHigh");
AddPlot(Brushes.DeepPink, "Firz234maLow");
AddPlot(Brushes.DeepPink, "Firz234maClose");
}
else if (State == State.Configure)
{
Q1 = Q;
Q2 = Q + 1;
Q3 = Q + 2;
Q4 = Q + 3;
Mo = UnBias ? Firz234maUnBias(M, Q1, Q2, Q3, Q4) : M;
Tuple<double, double, double, double> W = Firz234maWeights(Mo, Q1, Q2, Q3, Q4);
W1 = W.Item1;
W2 = W.Item2;
W3 = W.Item3;
W4 = W.Item4;
dataValidCount = 0;
}
else if (State == State.DataLoaded)
{
BarsRequiredToPlot = ValidBarsStart;
FirstIndicator = Filt4bFirmaOhlc(Mo, Q1, false);
SecondIndicator = Filt4bFirmaOhlc(Mo, Q2, false);
ThirdIndicator = Filt4bFirmaOhlc(Mo, Q3, false);
FourthIndicator = Filt4bFirmaOhlc(Mo, Q4, false);
}
}
protected override void OnBarUpdate()
{
dataValidCount += 1;
if (dataValidCount >= ValidBarsStart)
{
Values[0][0] = W1 * FirstIndicator.Open[0] + W2 * SecondIndicator.Open[0] + W3 * ThirdIndicator.Open[0] + W4 * FourthIndicator.Open[0];
Values[1][0] = W1 * FirstIndicator.High[0] + W2 * SecondIndicator.High[0] + W3 * ThirdIndicator.High[0] + W4 * FourthIndicator.High[0];
Values[2][0] = W1 * FirstIndicator.Low[0] + W2 * SecondIndicator.Low[0] + W3 * ThirdIndicator.Low[0] + W4 * FourthIndicator.Low[0];
Values[3][0] = W1 * FirstIndicator.Close[0] + W2 * SecondIndicator.Close[0] + W3 * ThirdIndicator.Close[0] + W4 * FourthIndicator.Close[0];
}
}
#region Properties
[NinjaScriptProperty]
[Range(1, double.MaxValue)]
[Display(Name="M", Description="Period", Order=1, GroupName="Parameters")]
public double M
{ get; set; }
[NinjaScriptProperty]
[Range(1, int.MaxValue)]
[Display(Name="Q", Description="Mechanism", Order=2, GroupName="Parameters")]
public int Q
{ get; set; }
[NinjaScriptProperty]
[Display(Name="UnBias", Description="RemoveBias", Order=3, GroupName="Parameters")]
public bool UnBias
{ get; set; }
[Browsable(false)]
[XmlIgnore]
public Series<double> Open
{
get { return Values[0]; }
}
[Browsable(false)]
[XmlIgnore]
public Series<double> High
{
get { return Values[1]; }
}
[Browsable(false)]
[XmlIgnore]
public Series<double> Low
{
get { return Values[2]; }
}
[Browsable(false)]
[XmlIgnore]
public Series<double> Close
{
get { return Values[3]; }
}
#endregion
}
}
#region NinjaScript generated code. Neither change nor remove.
namespace NinjaTrader.NinjaScript.Indicators
{
public partial class Indicator : NinjaTrader.Gui.NinjaScript.IndicatorRenderBase
{
private Filt4b.Filt4bFirz234maOhlc[] cacheFilt4bFirz234maOhlc;
public Filt4b.Filt4bFirz234maOhlc Filt4bFirz234maOhlc(double m, int q, bool unBias)
{
return Filt4bFirz234maOhlc(Input, m, q, unBias);
}
public Filt4b.Filt4bFirz234maOhlc Filt4bFirz234maOhlc(ISeries<double> input, double m, int q, bool unBias)
{
if (cacheFilt4bFirz234maOhlc != null)
for (int idx = 0; idx < cacheFilt4bFirz234maOhlc.Length; idx++)
if (cacheFilt4bFirz234maOhlc[idx] != null && cacheFilt4bFirz234maOhlc[idx].M == m && cacheFilt4bFirz234maOhlc[idx].Q == q && cacheFilt4bFirz234maOhlc[idx].UnBias == unBias && cacheFilt4bFirz234maOhlc[idx].EqualsInput(input))
return cacheFilt4bFirz234maOhlc[idx];
return CacheIndicator<Filt4b.Filt4bFirz234maOhlc>(new Filt4b.Filt4bFirz234maOhlc(){ M = m, Q = q, UnBias = unBias }, input, ref cacheFilt4bFirz234maOhlc);
}
}
}
namespace NinjaTrader.NinjaScript.MarketAnalyzerColumns
{
public partial class MarketAnalyzerColumn : MarketAnalyzerColumnBase
{
public Indicators.Filt4b.Filt4bFirz234maOhlc Filt4bFirz234maOhlc(double m, int q, bool unBias)
{
return indicator.Filt4bFirz234maOhlc(Input, m, q, unBias);
}
public Indicators.Filt4b.Filt4bFirz234maOhlc Filt4bFirz234maOhlc(ISeries<double> input , double m, int q, bool unBias)
{
return indicator.Filt4bFirz234maOhlc(input, m, q, unBias);
}
}
}
namespace NinjaTrader.NinjaScript.Strategies
{
public partial class Strategy : NinjaTrader.Gui.NinjaScript.StrategyRenderBase
{
public Indicators.Filt4b.Filt4bFirz234maOhlc Filt4bFirz234maOhlc(double m, int q, bool unBias)
{
return indicator.Filt4bFirz234maOhlc(Input, m, q, unBias);
}
public Indicators.Filt4b.Filt4bFirz234maOhlc Filt4bFirz234maOhlc(ISeries<double> input , double m, int q, bool unBias)
{
return indicator.Filt4bFirz234maOhlc(input, m, q, unBias);
}
}
}
#endregion
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using FileDownloader;
namespace Example
{
class Program
{
static void Main(string[] args)
{
Run(Example1, Console.Out);
Run(Example2, Console.Out);
Console.WriteLine("Hello World!");
}
static void Run(Action action, TextWriter tw)
{
NullCheck(action);
NullCheck(tw);
var sp = new Stopwatch();
sp.Start();
action();
var ts = sp.Elapsed;
var ellapseTime = string.Format("{0:00}:{1:00}:{2:00}:{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10);
tw.WriteLine($"Completed action in : {ellapseTime}");
void NullCheck<T>(T _value)
{
if (_value == null) throw new ArgumentNullException();
}
}
static void Example2()
{
Console.WriteLine("Change all h1 to h2 before saving the contents!");
var files = new List<(Uri, string)> {
(new Uri("https://www.html-5-tutorial.com/table-tag.htm"),"Downloads/table-tag.html"),
(new Uri("https://www.html-5-tutorial.com/html-tag.htm") , "Downloads/html-tag.html"),
(new Uri("https://dotnet.microsoft.com/learn/csharp") , "Downloads/learn-csharp.html")
};
var downloadArgs = new DownloadArgs
{
Files = files,
ProgressTracker = t => Console.WriteLine($"Download complete for {t.sourceFileName}"),
PostFetchContentOverride = contents => contents.Replace("h1", "h2")
};
RemoteFiles.Instance.Download(downloadArgs);
}
static void Example1()
{
var files = new List<(Uri, string)> {
(new Uri("https://www.html-5-tutorial.com/table-tag.htm"),null),
(new Uri("https://www.html-5-tutorial.com/html-tag.htm") , null),
(new Uri("https://dotnet.microsoft.com/learn/csharp") , null)
};
var downloadArgs = new DownloadArgs
{
MaintainSameDirectoryStructure = true,
RootFolderForDownload = "Test",
Files = files,
ProgressTracker = t => Console.WriteLine($"Download complete for {t.sourceFileName}")
};
RemoteFiles.Instance.Download(downloadArgs);
}
}
}
|
using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.Common;
using RealEstate.BusinessObjects;
namespace RealEstate.DataAccess
{
public class AdvertiseDA
{
#region ***** Init Methods *****
public AdvertiseDA()
{
}
#endregion
#region ***** Get Methods *****
/// <summary>
///
/// </summary>
/// <returns></returns>
public Advertise Populate(IDataReader myReader)
{
Advertise obj = new Advertise();
obj.AdvID = (int) myReader["AdvID"];
obj.AdvName = (string) myReader["AdvName"];
obj.Image = (string) myReader["Image"];
obj.Width = (int) myReader["Width"];
obj.Height = (int) myReader["Height"];
obj.Link = (string) myReader["Link"];
obj.Target = (string) myReader["Target"];
obj.Content = (string) myReader["Content"];
obj.Position = (int) myReader["Position"];
obj.PageID = (int) myReader["PageID"];
obj.Click = (int) myReader["Click"];
obj.Ord = (int) myReader["Ord"];
obj.Active = (bool) myReader["Active"];
obj.Lang = (string) myReader["Lang"];
return obj;
}
/// <summary>
/// Get Advertise by advid
/// </summary>
/// <param name="advid">AdvID</param>
/// <returns>Advertise</returns>
public Advertise GetByAdvID(int advid)
{
using (IDataReader reader = SqlHelper.ExecuteReader(Data.ConnectionString, CommandType.StoredProcedure, "sproc_Advertise_GetByAdvID", Data.CreateParameter("AdvID", advid)))
{
if (reader.Read())
{
return Populate(reader);
}
return null;
}
}
/// <summary>
/// Get all of Advertise
/// </summary>
/// <returns>List<<Advertise>></returns>
public List<Advertise> GetList()
{
using (IDataReader reader = SqlHelper.ExecuteReader(Data.ConnectionString, CommandType.StoredProcedure, "sproc_Advertise_Get"))
{
List<Advertise> list = new List<Advertise>();
while (reader.Read())
{
list.Add(Populate(reader));
}
return list;
}
}
/// <summary>
/// Get DataSet of Advertise
/// </summary>
/// <returns>DataSet</returns>
public DataSet GetDataSet()
{
return SqlHelper.ExecuteDataSet(Data.ConnectionString, CommandType.StoredProcedure,"sproc_Advertise_Get");
}
/// <summary>
/// Get all of Advertise paged
/// </summary>
/// <param name="recperpage">record per page</param>
/// <param name="pageindex">page index</param>
/// <returns>List<<Advertise>></returns>
public List<Advertise> GetListPaged(int recperpage, int pageindex)
{
using (IDataReader reader = SqlHelper.ExecuteReader(Data.ConnectionString, CommandType.StoredProcedure, "sproc_Advertise_GetPaged"
,Data.CreateParameter("recperpage", recperpage)
,Data.CreateParameter("pageindex", pageindex)))
{
List<Advertise> list = new List<Advertise>();
while (reader.Read())
{
list.Add(Populate(reader));
}
return list;
}
}
/// <summary>
/// Get DataSet of Advertise paged
/// </summary>
/// <param name="recperpage">record per page</param>
/// <param name="pageindex">page index</param>
/// <returns>DataSet</returns>
public DataSet GetDataSetPaged(int recperpage, int pageindex)
{
return SqlHelper.ExecuteDataSet(Data.ConnectionString, CommandType.StoredProcedure,"sproc_Advertise_GetPaged"
,Data.CreateParameter("recperpage", recperpage)
,Data.CreateParameter("pageindex", pageindex));
}
#endregion
#region ***** Add Update Delete Methods *****
/// <summary>
/// Add a new Advertise within Advertise database table
/// </summary>
/// <param name="obj">Advertise</param>
/// <returns>key of table</returns>
public int Add(Advertise obj)
{
DbParameter parameterItemID = Data.CreateParameter("AdvID", obj.AdvID);
parameterItemID.Direction = ParameterDirection.Output;
SqlHelper.ExecuteNonQuery(Data.ConnectionString, CommandType.StoredProcedure,"sproc_Advertise_Add"
,parameterItemID
,Data.CreateParameter("AdvName", obj.AdvName)
,Data.CreateParameter("Image", obj.Image)
,Data.CreateParameter("Width", obj.Width)
,Data.CreateParameter("Height", obj.Height)
,Data.CreateParameter("Link", obj.Link)
,Data.CreateParameter("Target", obj.Target)
,Data.CreateParameter("Content", obj.Content)
,Data.CreateParameter("Position", obj.Position)
,Data.CreateParameter("PageID", obj.PageID)
,Data.CreateParameter("Click", obj.Click)
,Data.CreateParameter("Ord", obj.Ord)
,Data.CreateParameter("Active", obj.Active)
,Data.CreateParameter("Lang", obj.Lang)
);
return 0;
}
/// <summary>
/// updates the specified Advertise
/// </summary>
/// <param name="obj">Advertise</param>
/// <returns></returns>
public void Update(Advertise obj)
{
SqlHelper.ExecuteNonQuery(Data.ConnectionString, CommandType.StoredProcedure,"sproc_Advertise_Update"
,Data.CreateParameter("AdvID", obj.AdvID)
,Data.CreateParameter("AdvName", obj.AdvName)
,Data.CreateParameter("Image", obj.Image)
,Data.CreateParameter("Width", obj.Width)
,Data.CreateParameter("Height", obj.Height)
,Data.CreateParameter("Link", obj.Link)
,Data.CreateParameter("Target", obj.Target)
,Data.CreateParameter("Content", obj.Content)
,Data.CreateParameter("Position", obj.Position)
,Data.CreateParameter("PageID", obj.PageID)
,Data.CreateParameter("Click", obj.Click)
,Data.CreateParameter("Ord", obj.Ord)
,Data.CreateParameter("Active", obj.Active)
,Data.CreateParameter("Lang", obj.Lang)
);
}
/// <summary>
/// Delete the specified Advertise
/// </summary>
/// <param name="advid">AdvID</param>
/// <returns></returns>
public void Delete(int advid)
{
SqlHelper.ExecuteNonQuery(Data.ConnectionString, CommandType.StoredProcedure,"sproc_Advertise_Delete", Data.CreateParameter("AdvID", advid));
}
#endregion
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//[ExecuteInEditMode]
public class LookAround : MonoBehaviour
{
public bool moving = false;
private Vector3 target;
private Vector3 last_position;
public float stayTime = 0.2f;
public float theDistance;
public Vector3 heading;
public RaycastHit2D[] hitPoint;
public GameObject observedObject;
// Use this for initialization
void Start()
{
target = transform.position;
last_position = new Vector3(0, 0, 0);
}
// Update is called once per frame
void Update()
{
stayTime = stayTime - Time.deltaTime;
if (observedObject == null){
return;
}
if (observedObject.transform.position == last_position)
{
if (stayTime > 0)
{
}
else
{
target = observedObject.transform.position;
target.y = transform.position.y;
if (target.x > transform.position.x)
{
target.x = target.x - 1;
}
else
{
target.x = target.x + 1;
}
observedObject.tag = "Usable_used";
observedObject.layer = 14;
this.SendMessage("Move", target);
}
}
else
{
last_position = observedObject.transform.position;
stayTime = 0.2f;
}
}
/*void OnTriggerEnter2D(Collider2D other)
{
//Debug.Log("I've seen: " + other.gameObject.name);
}*/
private void OnTriggerExit2D(Collider2D other)
{
if (other.gameObject.tag == "Usable_walk"){
observedObject = null;
}
}
void OnTriggerStay2D(Collider2D other){
if (other.gameObject.tag == "Usable_used" && (other.gameObject.transform.position - transform.position).magnitude < 2.0f)
{
if (other.gameObject == observedObject){
observedObject = null;
}
this.GetComponent<AudioSource>().Play();
Destroy(other.gameObject);
}
}
void OnTriggerEnter2D(Collider2D other)
{
//destroy all usables when near
heading = other.gameObject.transform.position - transform.position;
theDistance = heading.magnitude;
Debug.DrawRay(transform.position, heading, Color.red);
hitPoint = Physics2D.RaycastAll(transform.position, heading);
int i = 0;
if (hitPoint.Length > 0)
{
//skip all trigger colliders and the Cat
while ( hitPoint[i].collider.isTrigger || hitPoint[i].collider.gameObject.tag == "Cat") {
if (hitPoint.Length <= i){
break;
}
i++;
}
//raycast test
if (hitPoint[i].collider.gameObject == other.gameObject)
{
//Debug.Log("Visible: " + theDistance + " " + hitPoint[i].collider.gameObject.name);
if (other.gameObject.tag == "Usable_walk" ) // _HACK && Mathf.Abs(other.transform.position.y - transform.position.y) < 1.5f)
{
observedObject = other.gameObject;
/*
if (other.gameObject.transform.position == last_position){
if (stayTime > 0){
}
else {
target = other.gameObject.transform.position;
target.y = transform.position.y;
if (target.x > transform.position.x) {
target.x = target.x - 1;
}
else {
target.x = target.x + 1;
}
other.gameObject.tag = "Usable_used";
other.gameObject.layer = 14;
this.SendMessage("Move",target);
}
}
else {
last_position = other.gameObject.transform.position;
stayTime = 0.2f;
}
*/
}
}
}
}
}
|
using System;
public class Simulate7SidedDie
{
public int rand2()
{
int x = rand5();
if (x == 4||x==5)
return rand2(); // restart
else return x % 2;
}
public int rand7()
{
int x = rand2() * 4 + rand2() * 2 + rand2();
if (x == 7) return rand7(); // restart
else return x;
}
public int rand5()
{
Random rand = new Random();
return rand.Next(1, 6);
}
public void Test()
{
Console.WriteLine(rand7());
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace DiscoTest.cs.Models
{
public class NodeWarDate
{
public int day;
public int month;
public NodeWarDate(int day, int month)
{
this.day = day;
this.month = month;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
namespace Equinox.Domain.Models
{
[System.ComponentModel.DataAnnotations.Schema.Table("AddedTicketsLogger")]
public class AddedTicketsLogger : Core.Models.Entity
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid IdKey { get; set; }
public AddedTicketsLogger() { }
public AddedTicketsLogger( Guid IdKey , DateTime DateTime , string message , string exception , string CLAZZ , string METHOD)
{
this.IdKey = IdKey;
this.DateTime = DateTime;
this.message = message;
this.exception = exception;
this.CLAZZ = CLAZZ;
this.METHOD = METHOD;
}
[System.ComponentModel.DataAnnotations.Schema.ForeignKey("AgentRegisterCasesKey")]
public AgentRegisterCases AgentRegisterCases { get; set; }
[Column("AgentRegisterCasesKey")]
public Guid? AgentRegisterCasesKey { get; set; }
[Column("AgentRegisteredTicketsKey")]
public Guid? AgentRegisteredTicketsKey { get; set; }
[Column("DateTime")]
private DateTime? DateTime { get; set; }
[Column("message")]
private string message { get; set; }
[Column("exception")]
private string exception { get; set; }
[Column("CLAZZ")]
private string CLAZZ { get; set; }
[Column("METHOD")]
private string METHOD { get; set; }
}
}
|
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using VH.Core.Middleware.Logging;
namespace VH.Core.Middleware
{
public static class ConfigureServiceExtensions
{
/// <summary>
/// Add Logging Middleware. This should be the first filter registered.
/// </summary>
/// <param name="serviceCollection"></param>
/// <returns></returns>
public static IServiceCollection AddLoggingMiddlewareFilter(this IServiceCollection serviceCollection)
{
serviceCollection.AddScoped<ILoggingDataExtractor, LoggingDataExtractor>();
serviceCollection.AddMvc(opt => opt.Filters.Add(typeof(LoggingMiddleware))).SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
return serviceCollection;
}
}
}
|
#region Copyright Syncfusion Inc. 2001-2015.
// Copyright Syncfusion Inc. 2001-2015. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using Android.App;
using Android.Content;
using Android.Graphics;
using Android.OS;
using Android.Views;
using Android.Widget;
using Com.Syncfusion.Charts;
using Com.Syncfusion.Charts.Enums;
using System;
using System.Collections.Generic;
namespace SampleBrowser
{
[Activity(Label = "Trackball")]
public class Trackball : SamplePage
{
SfChart chart;
public override View GetSampleContent(Context context)
{
chart = new SfChart(context); ;
chart.SetBackgroundColor(Color.White);
chart.PrimaryAxis = new NumericalAxis ();
chart.SecondaryAxis = new NumericalAxis { };
var series = new LineSeries
{
DataSource = MainPage.GetSeriesData1(),
};
chart.Series.Add(series);
series = new LineSeries
{
DataSource = MainPage.GetSeriesData2(),
};
chart.Series.Add(series);
series = new LineSeries
{
DataSource = MainPage.GetSeriesData3(),
};
chart.Series.Add(series);
chart.Behaviors.Add(new ChartTrackballBehavior());
var label = new TextView(context);;
label.SetPadding(5, 5, 5, 5);
label.Text = "Press and hold to enable trackball.";
var layout = new LinearLayout(context){ Orientation = Android.Widget.Orientation.Vertical };
var layoutLabel = new LinearLayout(context)
{
Orientation = Android.Widget.Orientation.Horizontal,
LayoutParameters =
new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent)
};
layoutLabel.SetHorizontalGravity(GravityFlags.CenterHorizontal);
layoutLabel.AddView(label);
layout.AddView(layoutLabel);
layout.AddView(chart);
return layout;
}
public override View GetPropertyWindowLayout(Android.Content.Context context)
{
/**
* Property Window
* */
int width = (context.Resources.DisplayMetrics.WidthPixels) / 2;
LinearLayout propertylayout = new LinearLayout(context); //= new LinearLayout(context);
propertylayout.Orientation = Android.Widget.Orientation.Vertical;
LinearLayout.LayoutParams layoutParams1 = new LinearLayout.LayoutParams(
width * 2, 5);
layoutParams1.SetMargins(0, 20, 0, 0);
TextView labelDisplayMode = new TextView(context);
labelDisplayMode.TextSize = 20;
labelDisplayMode.Text = "LabelDisplay Mode";
Spinner selectLabelMode = new Spinner(context);
List<String> adapter = new List<String>() { "FloatAllPoints", "NearestPoint", "GroupAllPoints" };
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>
(context, Android.Resource.Layout.SimpleSpinnerItem, adapter);
dataAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleDropDownItem1Line);
selectLabelMode.Adapter = dataAdapter;
selectLabelMode.ItemSelected += (object sender, AdapterView.ItemSelectedEventArgs e) =>
{
String selectedItem = dataAdapter.GetItem(e.Position);
ChartTrackballBehavior trackballBehavior = (chart.Behaviors.Get(0) as ChartTrackballBehavior);
if (selectedItem.Equals("NearestPoint"))
{
trackballBehavior.LabelDisplayMode = TrackballLabelDisplayMode.NearestPoint;
}
else if (selectedItem.Equals("FloatAllPoints"))
{
trackballBehavior.LabelDisplayMode = TrackballLabelDisplayMode.FloatAllPoints;
}
else if (selectedItem.Equals("GroupAllPoints"))
{
trackballBehavior.LabelDisplayMode = TrackballLabelDisplayMode.GroupAllPoints;
}
};
propertylayout.AddView(labelDisplayMode);
SeparatorView separate = new SeparatorView(context, width * 2);
separate.LayoutParameters = new ViewGroup.LayoutParams(width * 2, 5);
propertylayout.AddView(separate, layoutParams1);
propertylayout.AddView(selectLabelMode);
return propertylayout;
}
}
} |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Build.Evaluation;
using Microsoft.Build.Execution;
using Microsoft.Build.Framework;
using Microsoft.Build.Tasks.Hosting;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.MSBuild;
using Roslyn.Utilities;
using MSB = Microsoft.Build;
namespace Microsoft.CodeAnalysis.VisualBasic
{
internal class VisualBasicProjectFileLoader : ProjectFileLoader
{
private readonly HostWorkspaceServices _workspaceServices;
internal HostLanguageServices LanguageServices
{
get { return this._workspaceServices.GetLanguageServices(LanguageNames.VisualBasic); }
}
public override string Language
{
get { return LanguageNames.VisualBasic; }
}
internal VisualBasicProjectFileLoader(HostWorkspaceServices workspaceServices)
{
this._workspaceServices = workspaceServices;
}
protected override ProjectFile CreateProjectFile(MSB.Evaluation.Project loadedProject)
{
return new VisualBasicProjectFile(this, loadedProject, this._workspaceServices.GetService<IMetadataService>(), this._workspaceServices.GetService<IAnalyzerService>());
}
internal class VisualBasicProjectFile : ProjectFile
{
private readonly IMetadataService _metadataService;
private readonly IAnalyzerService _analyzerService;
private readonly IHostBuildDataFactory _hostBuildDataFactory;
private readonly ICommandLineArgumentsFactoryService _commandLineArgumentsFactory;
public VisualBasicProjectFile(VisualBasicProjectFileLoader loader, MSB.Evaluation.Project loadedProject, IMetadataService metadataService, IAnalyzerService analyzerService) : base(loader, loadedProject)
{
this._metadataService = metadataService;
this._analyzerService = analyzerService;
this._hostBuildDataFactory = loader.LanguageServices.GetService<IHostBuildDataFactory>();
this._commandLineArgumentsFactory = loader.LanguageServices.GetService<ICommandLineArgumentsFactoryService>();
}
public override SourceCodeKind GetSourceCodeKind(string documentFileName)
{
SourceCodeKind result;
if (documentFileName.EndsWith(".vbx", StringComparison.OrdinalIgnoreCase))
{
result = SourceCodeKind.Script;
}
else
{
result = SourceCodeKind.Regular;
}
return result;
}
public override string GetDocumentExtension(SourceCodeKind sourceCodeKind)
{
string result;
if (sourceCodeKind != SourceCodeKind.Script)
{
result = ".vb";
}
else
{
result = ".vbx";
}
return result;
}
public override async Task<ProjectFileInfo> GetProjectFileInfoAsync(CancellationToken cancellationToken)
{
var compilerInputs = new VisualBasicCompilerInputs(this);
var executedProject = await BuildAsync("Vbc", compilerInputs, cancellationToken).ConfigureAwait(false);
if (!compilerInputs.Initialized)
{
InitializeFromModel(compilerInputs, executedProject);
}
return CreateProjectFileInfo(compilerInputs, executedProject);
}
private ProjectFileInfo CreateProjectFileInfo(VisualBasicProjectFileLoader.VisualBasicProjectFile.VisualBasicCompilerInputs compilerInputs, ProjectInstance executedProject)
{
IEnumerable<MetadataReference> metadataReferences = null;
IEnumerable<AnalyzerReference> analyzerReferences = null;
this.GetReferences(compilerInputs, executedProject, ref metadataReferences, ref analyzerReferences);
string outputPath = Path.Combine(this.GetOutputDirectory(), compilerInputs.OutputFileName);
string assemblyName = this.GetAssemblyName();
HostBuildData hostBuildData = this._hostBuildDataFactory.Create(compilerInputs.HostBuildOptions);
return new ProjectFileInfo(outputPath, assemblyName, hostBuildData.CompilationOptions, hostBuildData.ParseOptions, compilerInputs.CodePage, this.GetDocuments(compilerInputs.Sources, executedProject), this.GetDocuments(compilerInputs.AdditionalFiles, executedProject), base.GetProjectReferences(executedProject), metadataReferences, analyzerReferences);
}
private void GetReferences(VisualBasicProjectFileLoader.VisualBasicProjectFile.VisualBasicCompilerInputs compilerInputs, ProjectInstance executedProject, ref IEnumerable<MetadataReference> metadataReferences, ref IEnumerable<AnalyzerReference> analyzerReferences)
{
// use command line parser to compute references using common logic
List<string> list = new List<string>();
if (compilerInputs.LibPaths != null && compilerInputs.LibPaths.Count<string>() > 0)
{
list.Add("/libpath:\"" + string.Join(";", compilerInputs.LibPaths) + "\"");
}
// metadata references
foreach (var current in compilerInputs.References)
{
if (!IsProjectReferenceOutputAssembly(current))
{
string documentFilePath = base.GetDocumentFilePath(current);
list.Add("/r:\"" + documentFilePath + "\"");
}
}
// analyzer references
foreach (var current in compilerInputs.AnalyzerReferences)
{
string documentFilePath2 = base.GetDocumentFilePath(current);
list.Add("/a:\"" + documentFilePath2 + "\"");
}
if (compilerInputs.NoStandardLib)
{
list.Add("/nostdlib");
}
if (!string.IsNullOrEmpty(compilerInputs.VbRuntime))
{
if (compilerInputs.VbRuntime == "Default")
{
list.Add("/vbruntime+");
}
else if (compilerInputs.VbRuntime == "Embed")
{
list.Add("/vbruntime*");
}
else if (compilerInputs.VbRuntime == "None")
{
list.Add("/vbruntime-");
}
else
{
list.Add("/vbruntime: " + compilerInputs.VbRuntime);
}
}
if (!string.IsNullOrEmpty(compilerInputs.SdkPath))
{
list.Add("/sdkpath:" + compilerInputs.SdkPath);
}
CommandLineArguments commandLineArguments = this._commandLineArgumentsFactory.CreateCommandLineArguments(list, executedProject.Directory, false, RuntimeEnvironment.GetRuntimeDirectory());
MetadataFileReferenceResolver pathResolver = new MetadataFileReferenceResolver(commandLineArguments.ReferencePaths, commandLineArguments.BaseDirectory);
metadataReferences = commandLineArguments.ResolveMetadataReferences(new AssemblyReferenceResolver(pathResolver, this._metadataService.GetProvider()));
IAnalyzerAssemblyLoader loader = this._analyzerService.GetLoader();
foreach (var path in commandLineArguments.AnalyzerReferences.Select((r) => r.FilePath))
{
loader.AddDependencyLocation(path);
}
analyzerReferences = commandLineArguments.ResolveAnalyzerReferences(loader);
}
private IEnumerable<DocumentFileInfo> GetDocuments(IEnumerable<ITaskItem> sources, ProjectInstance executedProject)
{
IEnumerable<DocumentFileInfo> result;
if (sources == null)
{
result = ImmutableArray<DocumentFileInfo>.Empty;
}
var projectDirectory = executedProject.Directory;
if (!projectDirectory.EndsWith(Path.DirectorySeparatorChar.ToString(), StringComparison.OrdinalIgnoreCase))
{
projectDirectory += Path.DirectorySeparatorChar;
}
return sources
.Where(s => !System.IO.Path.GetFileName(s.ItemSpec).StartsWith("TemporaryGeneratedFile_", StringComparison.Ordinal))
.Select(s => new DocumentFileInfo(GetDocumentFilePath(s), GetDocumentLogicalPath(s, projectDirectory), IsDocumentLinked(s), IsDocumentGenerated(s))).ToImmutableArray();
}
private void InitializeFromModel(VisualBasicProjectFileLoader.VisualBasicProjectFile.VisualBasicCompilerInputs compilerInputs, ProjectInstance executedProject)
{
compilerInputs.BeginInitialization();
compilerInputs.SetBaseAddress(base.ReadPropertyString(executedProject, "OutputType"), base.ReadPropertyString(executedProject, "BaseAddress"));
compilerInputs.SetCodePage(base.ReadPropertyInt(executedProject, "CodePage"));
compilerInputs.SetDebugType(base.ReadPropertyBool(executedProject, "DebugSymbols"), base.ReadPropertyString(executedProject, "DebugType"));
compilerInputs.SetDefineConstants(base.ReadPropertyString(executedProject, "FinalDefineConstants", "DefineConstants"));
compilerInputs.SetDelaySign(base.ReadPropertyBool(executedProject, "DelaySign"));
compilerInputs.SetDisabledWarnings(base.ReadPropertyString(executedProject, "NoWarn"));
compilerInputs.SetDocumentationFile(base.GetItemString(executedProject, "DocFileItem"));
compilerInputs.SetErrorReport(base.ReadPropertyString(executedProject, "ErrorReport"));
compilerInputs.SetFileAlignment(base.ReadPropertyInt(executedProject, "FileAlignment"));
compilerInputs.SetGenerateDocumentation(base.ReadPropertyBool(executedProject, "GenerateDocumentation"));
compilerInputs.SetHighEntropyVA(base.ReadPropertyBool(executedProject, "HighEntropyVA"));
var _imports = this.GetTaskItems(executedProject, "Import");
if (_imports != null)
{
compilerInputs.SetImports(_imports.ToArray());
}
var signAssembly = ReadPropertyBool(executedProject, "SignAssembly");
if (signAssembly)
{
var keyFile = ReadPropertyString(executedProject, "KeyOriginatorFile", "AssemblyOriginatorKeyFile");
if (!string.IsNullOrEmpty(keyFile))
{
compilerInputs.SetKeyFile(keyFile);
}
var keyContainer = ReadPropertyString(executedProject, "KeyContainerName");
if (!string.IsNullOrEmpty(keyContainer))
{
compilerInputs.SetKeyContainer(keyContainer);
}
}
compilerInputs.SetLanguageVersion(base.ReadPropertyString(executedProject, "LangVersion"));
compilerInputs.SetMainEntryPoint(base.ReadPropertyString(executedProject, "StartupObject"));
compilerInputs.SetModuleAssemblyName(base.ReadPropertyString(executedProject, "ModuleEntryPoint"));
compilerInputs.SetNoStandardLib(base.ReadPropertyBool(executedProject, "NoCompilerStandardLib", "NoStdLib"));
compilerInputs.SetNoWarnings(base.ReadPropertyBool(executedProject, "_NoWarnings"));
compilerInputs.SetOptimize(base.ReadPropertyBool(executedProject, "Optimize"));
compilerInputs.SetOptionCompare(base.ReadPropertyString(executedProject, "OptionCompare"));
compilerInputs.SetOptionExplicit(base.ReadPropertyBool(executedProject, "OptionExplicit"));
compilerInputs.SetOptionInfer(base.ReadPropertyBool(executedProject, "OptionInfer"));
compilerInputs.SetOptionStrictType(base.ReadPropertyString(executedProject, "OptionStrict"));
compilerInputs.SetOutputAssembly(base.GetItemString(executedProject, "IntermediateAssembly"));
if (base.ReadPropertyBool(executedProject, "Prefer32Bit"))
{
compilerInputs.SetPlatformWith32BitPreference(base.ReadPropertyString(executedProject, "PlatformTarget"));
}
else
{
compilerInputs.SetPlatform(base.ReadPropertyString(executedProject, "PlatformTarget"));
}
compilerInputs.SetRemoveIntegerChecks(base.ReadPropertyBool(executedProject, "RemoveIntegerChecks"));
compilerInputs.SetRootNamespace(base.ReadPropertyString(executedProject, "RootNamespace"));
compilerInputs.SetSdkPath(base.ReadPropertyString(executedProject, "FrameworkPathOverride"));
compilerInputs.SetSubsystemVersion(base.ReadPropertyString(executedProject, "SubsystemVersion"));
compilerInputs.SetTargetCompactFramework(base.ReadPropertyBool(executedProject, "TargetCompactFramework"));
compilerInputs.SetTargetType(base.ReadPropertyString(executedProject, "OutputType"));
// Decode the warning options from RuleSet file prior to reading explicit settings in the project file, so that project file settings prevail for duplicates.
compilerInputs.SetRuleSet(base.ReadPropertyString(executedProject, "RuleSet"));
compilerInputs.SetTreatWarningsAsErrors(base.ReadPropertyBool(executedProject, "SetTreatWarningsAsErrors"));
compilerInputs.SetVBRuntime(base.ReadPropertyString(executedProject, "VbRuntime"));
compilerInputs.SetWarningsAsErrors(base.ReadPropertyString(executedProject, "WarningsAsErrors"));
compilerInputs.SetWarningsNotAsErrors(base.ReadPropertyString(executedProject, "WarningsNotAsErrors"));
compilerInputs.SetReferences(this.GetMetadataReferencesFromModel(executedProject).ToArray<ITaskItem>());
compilerInputs.SetAnalyzers(this.GetAnalyzerReferencesFromModel(executedProject).ToArray<ITaskItem>());
compilerInputs.SetAdditionalFiles(this.GetAdditionalFilesFromModel(executedProject).ToArray<ITaskItem>());
compilerInputs.SetSources(this.GetDocumentsFromModel(executedProject).ToArray<ITaskItem>());
compilerInputs.EndInitialization();
}
private class VisualBasicCompilerInputs :
MSB.Tasks.Hosting.IVbcHostObject5,
MSB.Tasks.Hosting.IVbcHostObjectFreeThreaded
#if !MSBUILD12
,IAnalyzerHostObject
#endif
{
private readonly VisualBasicProjectFile _projectFile;
private bool _initialized;
private HostBuildOptions _options;
private int _codePage;
private IEnumerable<MSB.Framework.ITaskItem> _sources;
private IEnumerable<MSB.Framework.ITaskItem> _additionalFiles;
private IEnumerable<MSB.Framework.ITaskItem> _references;
private IEnumerable<MSB.Framework.ITaskItem> _analyzerReferences;
private bool _noStandardLib;
private readonly Dictionary<string, ReportDiagnostic> _warnings;
private string _sdkPath;
private bool _targetCompactFramework;
private string _vbRuntime;
private IEnumerable<string> _libPaths;
private string _outputFileName;
public VisualBasicCompilerInputs(VisualBasicProjectFile projectFile)
{
this._projectFile = projectFile;
this._options = new HostBuildOptions();
this._sources = SpecializedCollections.EmptyEnumerable<MSB.Framework.ITaskItem>();
this._references = SpecializedCollections.EmptyEnumerable<MSB.Framework.ITaskItem>();
this._analyzerReferences = SpecializedCollections.EmptyEnumerable<MSB.Framework.ITaskItem>();
this._warnings = new Dictionary<string, ReportDiagnostic>();
this._options.ProjectDirectory = Path.GetDirectoryName(projectFile.FilePath);
this._options.OutputDirectory = projectFile.GetOutputDirectory();
}
public bool Initialized
{
get { return this._initialized; }
}
public HostBuildOptions HostBuildOptions
{
get { return this._options; }
}
public int CodePage
{
get { return this._codePage; }
}
public IEnumerable<MSB.Framework.ITaskItem> References
{
get { return this._references; }
}
public IEnumerable<MSB.Framework.ITaskItem> AnalyzerReferences
{
get { return this._analyzerReferences; }
}
public IEnumerable<MSB.Framework.ITaskItem> Sources
{
get { return this._sources; }
}
public IEnumerable<MSB.Framework.ITaskItem> AdditionalFiles
{
get { return this._additionalFiles; }
}
public bool NoStandardLib
{
get { return this._noStandardLib; }
}
public string VbRuntime
{
get { return this._vbRuntime; }
}
public string SdkPath
{
get { return this._sdkPath; }
}
public bool TargetCompactFramework
{
get { return this._targetCompactFramework; }
}
public IEnumerable<string> LibPaths
{
get { return this._libPaths; }
}
public string OutputFileName
{
get { return this._outputFileName; }
}
public void BeginInitialization()
{
}
public bool Compile()
{
return false;
}
public void EndInitialization()
{
this._initialized = true;
}
public bool IsDesignTime()
{
return true;
}
public bool IsUpToDate()
{
return true;
}
public bool SetAdditionalLibPaths(string[] additionalLibPaths)
{
this._libPaths = additionalLibPaths;
return true;
}
public bool SetAddModules(string[] addModules)
{
return true;
}
public bool SetBaseAddress(string targetType, string baseAddress)
{
// we don't capture emit options
return true;
}
public bool SetCodePage(int codePage)
{
this._codePage = codePage;
return true;
}
public bool SetDebugType(bool emitDebugInformation, string debugType)
{
// ignore, just check for expected values for backwards compat
return string.Equals(debugType, "none", StringComparison.OrdinalIgnoreCase) || string.Equals(debugType, "pdbonly", StringComparison.OrdinalIgnoreCase) || string.Equals(debugType, "full", StringComparison.OrdinalIgnoreCase);
}
public bool SetDefineConstants(string defineConstants)
{
this._options.DefineConstants = defineConstants;
return true;
}
public bool SetDelaySign(bool delaySign)
{
this._options.DelaySign = Tuple.Create(delaySign, false);
return true;
}
public bool SetDisabledWarnings(string disabledWarnings)
{
SetWarnings(disabledWarnings, ReportDiagnostic.Suppress);
return true;
}
public bool SetDocumentationFile(string documentationFile)
{
this._options.DocumentationFile = documentationFile;
return true;
}
public bool SetErrorReport(string errorReport)
{
// ??
return true;
}
public bool SetFileAlignment(int fileAlignment)
{
// we don't capture emit options
return true;
}
public bool SetGenerateDocumentation(bool generateDocumentation)
{
return true;
}
public bool SetImports(Microsoft.Build.Framework.ITaskItem[] importsList)
{
if (importsList != null)
{
_options.GlobalImports.AddRange(importsList.Select(item => item.ItemSpec.Trim()));
}
return true;
}
public bool SetKeyContainer(string keyContainer)
{
this._options.KeyContainer = keyContainer;
return true;
}
public bool SetKeyFile(string keyFile)
{
this._options.KeyFile = keyFile;
return true;
}
public bool SetLinkResources(Microsoft.Build.Framework.ITaskItem[] linkResources)
{
// ??
return true;
}
public bool SetMainEntryPoint(string mainEntryPoint)
{
this._options.MainEntryPoint = mainEntryPoint;
return true;
}
public bool SetNoConfig(bool noConfig)
{
return true;
}
public bool SetNoStandardLib(bool noStandardLib)
{
this._noStandardLib = noStandardLib;
return true;
}
public bool SetNoWarnings(bool noWarnings)
{
this._options.NoWarnings = noWarnings;
return true;
}
public bool SetOptimize(bool optimize)
{
this._options.Optimize = optimize;
return true;
}
public bool SetOptionCompare(string optionCompare)
{
this._options.OptionCompare = optionCompare;
return true;
}
public bool SetOptionExplicit(bool optionExplicit)
{
this._options.OptionExplicit = optionExplicit;
return true;
}
public bool SetOptionStrict(bool _optionStrict)
{
this._options.OptionStrict = _optionStrict ? "On" : "Custom";
return true;
}
public bool SetOptionStrictType(string optionStrictType)
{
if (!string.IsNullOrEmpty(optionStrictType))
{
this._options.OptionStrict = optionStrictType;
}
return true;
}
public bool SetOutputAssembly(string outputAssembly)
{
this._outputFileName = Path.GetFileName(outputAssembly);
return true;
}
public bool SetPlatform(string _platform)
{
this._options.Platform = _platform;
return true;
}
public bool SetPlatformWith32BitPreference(string _platform)
{
this._options.PlatformWith32BitPreference = _platform;
return true;
}
public bool SetReferences(Microsoft.Build.Framework.ITaskItem[] references)
{
this._references = references ?? SpecializedCollections.EmptyEnumerable<MSB.Framework.ITaskItem>();
return true;
}
public bool SetAnalyzers(MSB.Framework.ITaskItem[] analyzerReferences)
{
this._analyzerReferences = analyzerReferences ?? SpecializedCollections.EmptyEnumerable<MSB.Framework.ITaskItem>();
return true;
}
public bool SetAdditionalFiles(MSB.Framework.ITaskItem[] additionalFiles)
{
this._additionalFiles = additionalFiles ?? SpecializedCollections.EmptyEnumerable<MSB.Framework.ITaskItem>();
return true;
}
public bool SetRemoveIntegerChecks(bool removeIntegerChecks)
{
this._options.CheckForOverflowUnderflow = !removeIntegerChecks;
return true;
}
public bool SetResources(Microsoft.Build.Framework.ITaskItem[] resources)
{
return true;
}
public bool SetResponseFiles(Microsoft.Build.Framework.ITaskItem[] responseFiles)
{
return true;
}
public bool SetRootNamespace(string rootNamespace)
{
this._options.RootNamespace = rootNamespace;
return true;
}
public bool SetSdkPath(string sdkPath)
{
this._sdkPath = sdkPath;
return true;
}
public bool SetSources(Microsoft.Build.Framework.ITaskItem[] sources)
{
this._sources = sources ?? SpecializedCollections.EmptyEnumerable<MSB.Framework.ITaskItem>();
return true;
}
public bool SetTargetCompactFramework(bool targetCompactFramework)
{
this._targetCompactFramework = targetCompactFramework;
return true;
}
public bool SetTargetType(string targetType)
{
if (!string.IsNullOrEmpty(targetType))
{
OutputKind outputKind;
if (VisualBasicProjectFile.TryGetOutputKind(targetType, out outputKind))
{
this._options.OutputKind = outputKind;
}
}
return true;
}
public bool SetRuleSet(string ruleSetFile)
{
this._options.RuleSetFile = ruleSetFile;
return true;
}
public bool SetTreatWarningsAsErrors(bool treatWarningsAsErrors)
{
this._options.WarningsAsErrors = treatWarningsAsErrors;
return true;
}
public bool SetWarningsAsErrors(string warningsAsErrors)
{
SetWarnings(warningsAsErrors, ReportDiagnostic.Error);
return true;
}
private static readonly char[] s_warningSeparators = { ';', ',' };
private void SetWarnings(string warnings, ReportDiagnostic reportStyle)
{
if (!string.IsNullOrEmpty(warnings))
{
foreach (var warning in warnings.Split(s_warningSeparators, StringSplitOptions.None))
{
int warningId = 0;
if (Int32.TryParse(warning, out warningId))
{
this._warnings["BC" + warningId.ToString("0000")] = reportStyle;
}
else
{
this._warnings[warning] = reportStyle;
}
}
}
}
public bool SetWarningsNotAsErrors(string warningsNotAsErrors)
{
SetWarnings(warningsNotAsErrors, ReportDiagnostic.Warn);
return true;
}
public bool SetWin32Icon(string win32Icon)
{
return true;
}
public bool SetWin32Resource(string win32Resource)
{
return true;
}
public bool SetModuleAssemblyName(string moduleAssemblyName)
{
return true;
}
public bool SetOptionInfer(bool optionInfer)
{
this._options.OptionInfer = optionInfer;
return true;
}
public bool SetWin32Manifest(string win32Manifest)
{
return true;
}
public bool SetLanguageVersion(string _languageVersion)
{
this._options.LanguageVersion = _languageVersion;
return true;
}
public bool SetVBRuntime(string VBRuntime)
{
this._vbRuntime = VBRuntime;
this._options.VBRuntime = VBRuntime;
return true;
}
public int CompileAsync(out IntPtr buildSucceededEvent, out IntPtr buildFailedEvent)
{
buildSucceededEvent = IntPtr.Zero;
buildFailedEvent = IntPtr.Zero;
return 0;
}
public int EndCompile(bool buildSuccess)
{
return 0;
}
public Microsoft.Build.Tasks.Hosting.IVbcHostObjectFreeThreaded GetFreeThreadedHostObject()
{
return null;
}
public bool SetHighEntropyVA(bool highEntropyVA)
{
// we don't capture emit options
return true;
}
public bool SetSubsystemVersion(string subsystemVersion)
{
// we don't capture emit options
return true;
}
public bool Compile1()
{
return false;
}
bool Microsoft.Build.Tasks.Hosting.IVbcHostObjectFreeThreaded.Compile()
{
return Compile1();
}
}
}
}
}
|
using PlatformRacing3.Common.Customization;
using PlatformRacing3.Common.User;
using PlatformRacing3.Server.API.Game.Commands;
using PlatformRacing3.Server.Game.Client;
namespace PlatformRacing3.Server.Game.Commands.User;
internal sealed class GiveHatCommand : ICommand
{
private readonly ClientManager clientManager;
public GiveHatCommand(ClientManager clientManager)
{
this.clientManager = clientManager;
}
public string Permission => "command.givehat.use";
public void OnCommand(ICommandExecutor executor, string label, ReadOnlySpan<string> args)
{
if (args.Length >= 2 && args.Length <= 3)
{
PlayerUserData playerUserData = UserManager.TryGetUserDataByNameAsync(args[0]).Result;
if (playerUserData != null)
{
Hat hat;
if (uint.TryParse(args[1], out uint hatId))
{
hat = (Hat)hatId;
}
else if (!Enum.TryParse(args[1], ignoreCase: true, out hat))
{
executor.SendMessage($"Unable to find part with name {args[1]}");
return;
}
bool temp = false;
if (args.Length >= 3)
{
bool.TryParse(args[2], out temp);
}
if (this.clientManager.TryGetClientSessionByUserId(playerUserData.Id, out ClientSession session) && session.UserData != null)
{
session.UserData.GiveHat(hat, temp);
}
else if (!temp)
{
UserManager.GiveHat(playerUserData.Id, hat);
}
}
else
{
executor.SendMessage($"Unable to find user named {args[0]}");
}
}
else
{
executor.SendMessage("Usage: /givehat [user] [id/name] [temporaly(false)]");
}
}
} |
namespace GitlabManager.Services.WindowOpener
{
/// <summary>
/// Service that is responsible for opening other windows inside this application
/// </summary>
public interface IWindowOpener
{
/// <summary>
/// Open the connection window
/// </summary>
/// <param name="hostUrl">Gitlab Instance HostURL</param>
/// <param name="authenticationToken">Gitlab Private token</param>
public void OpenConnectionWindow(string hostUrl, string authenticationToken);
/// <summary>
/// Open detail window for a specified project
/// </summary>
/// <param name="projectId">internal project id</param>
public void OpenProjectDetailWindow(int projectId);
}
} |
using Portal.Repo;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Portal
{
public partial class discountCodeAdd : System.Web.UI.Page
{
protected OtherRepo OtherRepos;
public discountCodeAdd()
{
OtherRepos = new OtherRepo();
}
protected void Page_Load(object sender, EventArgs e)
{
if (Session["userType"] != "admin")
{
Response.Redirect("login.aspx");
}
if (!IsPostBack)
{
}
}
protected void add_Click(object sender, EventArgs e)
{
string availableNumber = txt_availableNumber.Value;
string discountCode = txt_discountCode.Value;
string discountFee = txt_discountFee.Value;
string expireDate = txt_expireDate.Value;
if (string.IsNullOrWhiteSpace(availableNumber) || string.IsNullOrWhiteSpace(discountCode) || string.IsNullOrWhiteSpace(discountFee) || string.IsNullOrWhiteSpace(expireDate))
{
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('All fields required.');", true);
return;
}
string result = OtherRepos.addDiscountCode(new tbl_discountCode
{
createdAt = DateTime.Now,
availableNumber = availableNumber.Trim(),
discountCode = discountCode.Trim(),
discountFee = discountFee.Trim(),
expireDate = DateTime.Parse(expireDate)
});
if (result.Equals("true"))
{
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('Added Successfully.');", true);
txt_availableNumber.Value = "";
txt_discountCode.Value = "";
txt_discountFee.Value = "";
txt_expireDate.Value = "";
} else if(result.Equals("already")){
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('This code is already exist.');", true);
}
else
{
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('Something went wrong.');", true);
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CTCT.Components.MyLibrary;
using CTCT.Components;
namespace CTCT.Services
{
/// <summary>
/// Interface for MyLibraryService class
/// </summary>
public interface IMyLibraryService
{
/// <summary>
/// Get MyLibrary usage information
/// </summary>
/// <param name="accessToken">Access token.</param>
/// <param name="apiKey">The API key for the application</param>
/// <returns>Returns a MyLibraryInfo object</returns>
MyLibraryInfo GetLibraryInfo(string accessToken, string apiKey);
/// <summary>
/// Get all existing MyLibrary folders
/// </summary>
/// <param name="accessToken">Access token.</param>
/// <param name="apiKey">The API key for the application</param>
/// <param name="sortBy">Specifies how the list of folders is sorted</param>
/// <param name="limit">Specifies the number of results per page in the output, from 1 - 50, default = 50.</param>
/// <param name="pag">Pagination object.</param>
/// <returns>Returns a collection of MyLibraryFolder objects.</returns>
ResultSet<MyLibraryFolder> GetLibraryFolders(string accessToken, string apiKey, FoldersSortBy? sortBy, int? limit, Pagination pag);
/// <summary>
/// Add new folder to MyLibrary
/// </summary>
/// <param name="accessToken">Access token.</param>
/// <param name="apiKey">The API key for the application</param>
/// <param name="folder">Folder to be added (with name and parent id)</param>
/// <returns>Returns a MyLibraryFolder object.</returns>
MyLibraryFolder AddLibraryFolder(string accessToken, string apiKey, MyLibraryFolder folder);
/// <summary>
/// Get a specific folder by Id
/// </summary>
/// <param name="accessToken">Access token.</param>
/// <param name="apiKey">The API key for the application</param>
/// <param name="folderId">The id of the folder</param>
/// <returns>Returns a MyLibraryFolder object.</returns>
MyLibraryFolder GetLibraryFolder(string accessToken, string apiKey, string folderId);
/// <summary>
/// Update name and parent_id for a specific folder
/// </summary>
/// <param name="accessToken">Access token.</param>
/// <param name="apiKey">The API key for the application</param>
/// <param name="folder">Folder to be updated (with name and parent id)</param>
/// <param name="includePayload">Determines if update's folder JSON payload is returned</param>
/// <returns>Returns a MyLibraryFolder object.</returns>
MyLibraryFolder UpdateLibraryFolder(string accessToken, string apiKey, MyLibraryFolder folder, bool? includePayload);
/// <summary>
/// Delete a specific folder
/// </summary>
/// <param name="accessToken">Access token.</param>
/// <param name="apiKey">The API key for the application</param>
/// <param name="folderId">The id of the folder</param>
/// <returns>Returns true if folder was deleted successfully, false otherwise</returns>
bool DeleteLibraryFolder(string accessToken, string apiKey, string folderId);
/// <summary>
/// Get files from Trash folder
/// </summary>
/// <param name="accessToken">Access token.</param>
/// <param name="apiKey">The API key for the application</param>
/// <param name="type">The type of the files to retrieve</param>
/// <param name="sortBy">Specifies how the list of folders is sorted</param>
/// <param name="limit">Specifies the number of results per page in the output, from 1 - 50, default = 50.</param>
/// <param name="pag">Pagination object.</param>
/// <returns>Returns a collection of MyLibraryFile objects.</returns>
ResultSet<MyLibraryFile> GetLibraryTrashFiles(string accessToken, string apiKey, FileTypes? type, TrashSortBy? sortBy, int? limit, Pagination pag);
/// <summary>
/// Delete files in Trash folder
/// </summary>
/// <param name="accessToken">Access token.</param>
/// <param name="apiKey">The API key for the application</param>
/// <returns>Returns true if files were deleted successfully, false otherwise</returns>
bool DeleteLibraryTrashFiles(string accessToken, string apiKey);
/// <summary>
/// Get files
/// </summary>
/// <param name="accessToken">Access token.</param>
/// <param name="apiKey">The API key for the application</param>
/// <param name="type">The type of the files to retrieve</param>
/// <param name="source">Specifies to retrieve files from a particular source</param>
/// <param name="limit">Specifies the number of results per page in the output, from 1 - 50, default = 50.</param>
/// <param name="pag">Pagination object.</param>
/// <returns>Returns a collection of MyLibraryFile objects.</returns>
ResultSet<MyLibraryFile> GetLibraryFiles(string accessToken, string apiKey, FileTypes? type, FilesSources? source, int? limit, Pagination pag);
/// <summary>
/// Get files from a specific folder
/// </summary>
/// <param name="accessToken">Access token.</param>
/// <param name="apiKey">The API key for the application</param>
/// <param name="folderId">The id of the folder from which to retrieve files</param>
/// <param name="limit">Specifies the number of results per page in the output, from 1 - 50, default = 50.</param>
/// <param name="pag">Pagination object.</param>
/// <returns>Returns a collection of MyLibraryFile objects.</returns>
ResultSet<MyLibraryFile> GetLibraryFilesByFolder(string accessToken, string apiKey, string folderId, int? limit, Pagination pag);
/// <summary>
/// Get file after id
/// </summary>
/// <param name="accessToken">Access token.</param>
/// <param name="apiKey">The API key for the application</param>
/// <param name="fileId">The id of the file</param>
/// <returns>Returns a MyLibraryFile object.</returns>
MyLibraryFile GetLibraryFile(string accessToken, string apiKey, string fileId);
/// <summary>
/// Update a specific file
/// </summary>
/// <param name="accessToken">Access token.</param>
/// <param name="apiKey">The API key for the application</param>
/// <param name="file">File to be updated</param>
/// <param name="includePayload">Determines if update's folder JSON payload is returned</param>
/// <returns>Returns a MyLibraryFile object.</returns>
MyLibraryFile UpdateLibraryFile(string accessToken, string apiKey, MyLibraryFile file, bool? includePayload);
/// <summary>
/// Delete a specific file
/// </summary>
/// <param name="accessToken">Access token.</param>
/// <param name="apiKey">The API key for the application</param>
/// <param name="fileId">The id of the file</param>
/// <returns>Returns true if folder was deleted successfully, false otherwise</returns>
bool DeleteLibraryFile(string accessToken, string apiKey, string fileId);
/// <summary>
/// Get status for an upload file
/// </summary>
/// <param name="accessToken">Access token.</param>
/// <param name="apiKey">The API key for the application</param>
/// <param name="fileId">The id of the file</param>
/// <returns>Returns a list of FileUploadStatus objects</returns>
IList<FileUploadStatus> GetLibraryFileUploadStatus(string accessToken, string apiKey, string fileId);
/// <summary>
/// Move files to a different folder
/// </summary>
/// <param name="accessToken">Access token.</param>
/// <param name="apiKey">The API key for the application</param>
/// <param name="folderId">The id of the folder</param>
/// <param name="fileIds">List of comma separated file ids</param>
/// <returns>Returns a list of FileMoveResult objects.</returns>
IList<FileMoveResult> MoveLibraryFile(string accessToken, string apiKey, string folderId, IList<string> fileIds);
/// <summary>
/// Add files using the multipart content-type
/// </summary>
/// <param name="accessToken">Access token.</param>
/// <param name="apiKey">The API key for the application</param>
/// <param name="fileName">The file name and extension</param>
/// <param name="fileType">The file type</param>
/// <param name="folderId">The id of the folder</param>
/// <param name="description">The description of the file</param>
/// <param name="source">The source of the original file</param>
/// <param name="data">The data contained in the file being uploaded</param>
/// <returns>Returns the file Id associated with the uploaded file</returns>
string AddLibraryFilesMultipart(string accessToken, string apiKey, string fileName, FileType fileType, string folderId, string description, FileSource source, byte[] data);
}
}
|
/*--------------------------------------------------------------------------
Reactor.Web.Sockets
The MIT License (MIT)
Copyright (c) 2015 Haydn Paterson (sinclair) <haydn.developer@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
---------------------------------------------------------------------------*/
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace Reactor.Web.Socket.Protocol
{
internal class Frame : IEnumerable<byte>
{
internal static readonly byte[] EmptyUnmaskPingData;
public Fin Fin { get; private set; }
public Rsv Rsv1 { get; private set; }
public Rsv Rsv2 { get; private set; }
public Rsv Rsv3 { get; private set; }
public Opcode Opcode { get; private set; }
public Mask Mask { get; private set; }
public byte PayloadLen { get; private set; }
public byte[] ExtPayloadLen { get; private set; }
public byte[] MaskingKey { get; private set; }
public Payload Payload { get; private set; }
static Frame()
{
EmptyUnmaskPingData = CreatePingFrame(Mask.Unmask).ToByteArray();
}
private Frame()
{
}
public Frame(Opcode opcode, Payload payload) : this(opcode, Mask.Mask, payload)
{
}
public Frame(Opcode opcode, Mask mask, Payload payload) : this(Fin.Final, opcode, mask, payload)
{
}
public Frame(Fin fin, Opcode opcode, Mask mask, Payload payload) : this(fin, opcode, mask, payload, false)
{
}
public Frame(Fin fin, Opcode opcode, Mask mask, Payload payload, bool compressed)
{
this.Fin = fin;
this.Rsv1 = isData(opcode) && compressed ? Rsv.On : Rsv.Off;
this.Rsv2 = Rsv.Off;
this.Rsv3 = Rsv.Off;
this.Opcode = opcode;
this.Mask = mask;
//---------------------------------
// PayloadLen
//---------------------------------
var dataLen = payload.Length;
var payloadLen = dataLen < 126 ? (byte)dataLen
: dataLen < 0x010000 ? (byte)126 : (byte)127;
this.PayloadLen = payloadLen;
//---------------------------------
// ExtPayloadLen
//---------------------------------
this.ExtPayloadLen = payloadLen < 126
? new byte[] { }
: payloadLen == 126
? Util.ToByteArrayInternally(((ushort)dataLen), ByteOrder.Big)
: Util.ToByteArrayInternally(dataLen, ByteOrder.Big);
//---------------------------------
// MaskingKey
//---------------------------------
var masking = mask == Mask.Mask;
var maskingKey = masking
? CreateMaskingKey()
: new byte[] { };
this.MaskingKey = maskingKey;
//---------------------------------
// PayloadData
//---------------------------------
if (masking)
{
payload.Mask(maskingKey);
}
this.Payload = payload;
}
#region Properties
internal bool IsBinary
{
get
{
return this.Opcode == Opcode.BINARY;
}
}
internal bool IsClose
{
get
{
return this.Opcode == Opcode.CLOSE;
}
}
internal bool IsCompressed
{
get
{
return this.Rsv1 == Rsv.On;
}
}
internal bool IsContinuation
{
get
{
return this.Opcode == Opcode.CONT;
}
}
internal bool IsControl
{
get
{
return this.Opcode == Opcode.CLOSE || this.Opcode == Opcode.PING || this.Opcode == Opcode.PONG;
}
}
internal bool IsData
{
get
{
return this.Opcode == Opcode.BINARY || this.Opcode == Opcode.TEXT;
}
}
internal bool IsFinal
{
get
{
return this.Fin == Fin.Final;
}
}
internal bool IsFragmented
{
get
{
return this.Fin == Fin.More || this.Opcode == Opcode.CONT;
}
}
internal bool IsMasked
{
get
{
return this.Mask == Mask.Mask;
}
}
internal bool IsPerMessageCompressed
{
get
{
return (this.Opcode == Opcode.BINARY || this.Opcode == Opcode.TEXT) && this.Rsv1 == Rsv.On;
}
}
internal bool IsPing
{
get
{
return this.Opcode == Opcode.PING;
}
}
internal bool IsPong
{
get
{
return this.Opcode == Opcode.PONG;
}
}
internal bool IsText
{
get
{
return this.Opcode == Opcode.TEXT;
}
}
internal ulong FrameLength
{
get
{
return 2 + (ulong)(this.ExtPayloadLen.Length + this.MaskingKey.Length) + Payload.Length;
}
}
#endregion
private static byte[] CreateMaskingKey()
{
var key = new byte[4];
var rand = new Random();
rand.NextBytes(key);
return key;
}
private static string Dump(Frame frame)
{
var len = frame.FrameLength;
var count = (long)(len / 4);
var rem = (int)(len % 4);
int countDigit;
string countFmt;
if (count < 10000)
{
countDigit = 4;
countFmt = "{0,4}";
}
else if (count < 0x010000)
{
countDigit = 4;
countFmt = "{0,4:X}";
}
else if (count < 0x0100000000)
{
countDigit = 8;
countFmt = "{0,8:X}";
}
else
{
countDigit = 16;
countFmt = "{0,16:X}";
}
var spFmt = String.Format("{{0,{0}}}", countDigit);
var headerFmt = String.Format(
@"{0} 01234567 89ABCDEF 01234567 89ABCDEF
{0}+--------+--------+--------+--------+\n", spFmt);
var footerFmt = String.Format("{0}+--------+--------+--------+--------+", spFmt);
var buffer = new StringBuilder(64);
Reactor.Func<Reactor.Action<string, string, string, string>> linePrinter = () =>
{
long lineCount = 0;
var lineFmt = String.Format("{0}|{{1,8}} {{2,8}} {{3,8}} {{4,8}}|\n", countFmt);
return (arg1, arg2, arg3, arg4) =>
{
buffer.AppendFormat(lineFmt, ++lineCount, arg1, arg2, arg3, arg4);
};
};
var printLine = linePrinter();
buffer.AppendFormat(headerFmt, String.Empty);
var frameAsBytes = frame.ToByteArray();
int i, j;
for (i = 0; i <= count; i++)
{
j = i * 4;
if (i < count)
{
printLine(
Convert.ToString(frameAsBytes[j], 2).PadLeft(8, '0'),
Convert.ToString(frameAsBytes[j + 1], 2).PadLeft(8, '0'),
Convert.ToString(frameAsBytes[j + 2], 2).PadLeft(8, '0'),
Convert.ToString(frameAsBytes[j + 3], 2).PadLeft(8, '0'));
}
else if (rem > 0)
{
printLine(
Convert.ToString(frameAsBytes[j], 2).PadLeft(8, '0'),
rem >= 2 ? Convert.ToString(frameAsBytes[j + 1], 2).PadLeft(8, '0') : String.Empty,
rem == 3 ? Convert.ToString(frameAsBytes[j + 2], 2).PadLeft(8, '0') : String.Empty,
String.Empty);
}
}
buffer.AppendFormat(footerFmt, String.Empty);
return buffer.ToString();
}
private static Frame Parse(byte[] header, Stream stream, bool unmask)
{
//-----------------------
// Header
//-----------------------
// FIN
var fin = (header[0] & 0x80) == 0x80 ? Fin.Final : Fin.More;
// RSV1
var rsv1 = (header[0] & 0x40) == 0x40 ? Rsv.On : Rsv.Off;
// RSV2
var rsv2 = (header[0] & 0x20) == 0x20 ? Rsv.On : Rsv.Off;
// RSV3
var rsv3 = (header[0] & 0x10) == 0x10 ? Rsv.On : Rsv.Off;
// Opcode
var opcode = (Opcode)(header[0] & 0x0f);
// MASK
var mask = (header[1] & 0x80) == 0x80 ? Mask.Mask : Mask.Unmask;
// Payload len
var payloadLen = (byte)(header[1] & 0x7f);
// Check if correct frame.
var incorrect = isControl(opcode) && fin == Fin.More
? "A control frame is fragmented."
: !isData(opcode) && rsv1 == Rsv.On
? "A non data frame is compressed."
: null;
if (incorrect != null)
{
throw new WebSocketException(CloseStatusCode.IncorrectData, incorrect);
}
// Check if consistent frame.
if (isControl(opcode) && payloadLen > 125)
{
throw new WebSocketException(CloseStatusCode.InconsistentData, "The payload data length of a control frame is greater than 125 bytes.");
}
var frame = new Frame
{
Fin = fin,
Rsv1 = rsv1,
Rsv2 = rsv2,
Rsv3 = rsv3,
Opcode = opcode,
Mask = mask,
PayloadLen = payloadLen
};
//-----------------------
// Extended Payload Length
//-----------------------
var extLen = payloadLen < 126
? 0
: payloadLen == 126
? 2
: 8;
var extPayloadLen = extLen > 0 ? Util.ReadBytes(stream, extLen) : new byte[] { };
if (extLen > 0 && extPayloadLen.Length != extLen)
{
throw new WebSocketException("The 'Extended Payload Length' of a frame cannot be read from the data source.");
}
frame.ExtPayloadLen = extPayloadLen;
//-----------------------------
// Masking Key
//-----------------------------
var masked = mask == Mask.Mask;
var maskingKey = masked ? Util.ReadBytes(stream, 4) : new byte[] { };
if (masked && maskingKey.Length != 4)
{
throw new WebSocketException("The 'Masking Key' of a frame cannot be read from the data source.");
}
frame.MaskingKey = maskingKey;
//-----------------------------
// Payload Data
//-----------------------------
ulong dataLen = payloadLen < 126
? payloadLen
: payloadLen == 126
? Util.ToUInt16(extPayloadLen, ByteOrder.Big)
: Util.ToUInt64(extPayloadLen, ByteOrder.Big);
byte[] data = null;
if (dataLen > 0)
{
// Check if allowable payload data length.
if (payloadLen > 126 && dataLen > Payload.MaxLength)
{
throw new WebSocketException(CloseStatusCode.TooBig, "The 'Payload Data' length is greater than the allowable length.");
}
data = payloadLen > 126
? Util.ReadBytes(stream, (long)dataLen, 1024)
: Util.ReadBytes(stream, (int)dataLen);
if (data.LongLength != (long)dataLen)
{
throw new WebSocketException("The 'Payload Data' of a frame cannot be read from the data source.");
}
}
else
{
data = new byte[] { };
}
var payload = new Payload(data, masked);
if (masked && unmask)
{
payload.Mask(maskingKey);
frame.Mask = Mask.Unmask;
//frame.MaskingKey = new byte[] { }; // why do this?
}
frame.Payload = payload;
return frame;
}
private static string Print(Frame frame)
{
//-------------------------------
// Opcode
//-------------------------------
var opcode = frame.Opcode.ToString();
//-------------------------------
// Payload Len
//-------------------------------
var payloadLen = frame.PayloadLen;
//-------------------------------
// Extended Payload Len
//-------------------------------
var ext = frame.ExtPayloadLen;
var size = ext.Length;
var extLen = size == 2
? Util.ToUInt16(ext, ByteOrder.Big).ToString()
: size == 8
? Util.ToUInt64(ext, ByteOrder.Big).ToString()
: String.Empty;
//-------------------------------
// Masking Key
//-------------------------------
var masked = frame.IsMasked;
var key = masked
? BitConverter.ToString(frame.MaskingKey)
: String.Empty;
//-------------------------------
// Payload Data
//-------------------------------
var data = payloadLen == 0
? String.Empty
: size > 0
? String.Format("A {0} data with {1} bytes.", opcode.ToLower(), extLen)
: masked || frame.IsFragmented || frame.IsBinary || frame.IsClose
? BitConverter.ToString(frame.Payload.ToByteArray())
: Encoding.UTF8.GetString(frame.Payload.ApplicationData);
var format =
@" FIN: {0}
RSV1: {1}
RSV2: {2}
RSV3: {3}
Opcode: {4}
MASK: {5}
Payload Len: {6}
Extended Payload Len: {7}
Masking Key: {8}
Payload Data: {9}";
return String.Format(format, frame.Fin, frame.Rsv1, frame.Rsv2, frame.Rsv3, opcode, frame.Mask, payloadLen, extLen, key, data);
}
#region Statics
public static Frame CreateCloseFrame(Mask mask, Payload payload)
{
return new Frame(Opcode.CLOSE, mask, payload);
}
public static Frame CreatePongFrame(Mask mask, Payload payload)
{
return new Frame(Opcode.PONG, mask, payload);
}
public static Frame CreateCloseFrame(Mask mask, byte[] data)
{
return new Frame(Opcode.CLOSE, mask, new Payload(data));
}
public static Frame CreateCloseFrame(Mask mask, CloseStatusCode code, string reason)
{
return new Frame(Opcode.CLOSE, mask, new Payload(Util.Append((ushort)code, reason)));
}
public static Frame CreateFrame(Fin fin, Opcode opcode, Mask mask, byte[] data, bool compressed)
{
return new Frame(fin, opcode, mask, new Payload(data), compressed);
}
public static Frame CreatePingFrame(Mask mask)
{
return new Frame(Opcode.PING, mask, new Payload());
}
public static Frame CreatePingFrame(Mask mask, byte[] data)
{
return new Frame(Opcode.PING, mask, new Payload(data));
}
public static Frame Parse(byte[] src, bool unmask)
{
using (var stream = new MemoryStream(src))
{
return Parse(stream, unmask);
}
}
public static Frame Parse(Stream stream, bool unmask)
{
var header = Util.ReadBytes(stream, 2);
if (header.Length != 2)
{
throw new WebSocketException("The header part of a frame cannot be read from the data source.");
}
return Parse(header, stream, unmask);
}
#endregion
#region Helpers
public void Print(bool dumped)
{
Console.WriteLine(dumped ? Dump(this) : Print(this));
}
public string PrintToString(bool dumped)
{
return dumped ? Dump(this) : Print(this);
}
public byte[] ToByteArray()
{
using (var buffer = new MemoryStream())
{
int header = (int)Fin;
header = (header << 1) + (int)Rsv1;
header = (header << 1) + (int)Rsv2;
header = (header << 1) + (int)Rsv3;
header = (header << 4) + (int)Opcode;
header = (header << 1) + (int)Mask;
header = (header << 7) + (int)PayloadLen;
buffer.Write(Util.ToByteArrayInternally((ushort)header, ByteOrder.Big), 0, 2);
if (this.PayloadLen > 125)
{
buffer.Write(this.ExtPayloadLen, 0, ExtPayloadLen.Length);
}
if (this.Mask == Mask.Mask)
{
buffer.Write(this.MaskingKey, 0, MaskingKey.Length);
}
if (this.PayloadLen > 0)
{
var data = this.Payload.ToByteArray();
if (this.PayloadLen < 127)
{
buffer.Write(data, 0, data.Length);
}
else
{
Util.WriteBytes(buffer, data);
}
}
buffer.Close();
return buffer.ToArray();
}
}
private static bool isBinary(Opcode opcode)
{
return opcode == Opcode.BINARY;
}
private static bool isClose(Opcode opcode)
{
return opcode == Opcode.CLOSE;
}
private static bool isContinuation(Opcode opcode)
{
return opcode == Opcode.CONT;
}
private static bool isControl(Opcode opcode)
{
return opcode == Opcode.CLOSE || opcode == Opcode.PING || opcode == Opcode.PONG;
}
private static bool isData(Opcode opcode)
{
return opcode == Opcode.TEXT || opcode == Opcode.BINARY;
}
private static bool isFinal(Fin fin)
{
return fin == Fin.Final;
}
private static bool isMasked(Mask mask)
{
return mask == Mask.Mask;
}
private static bool isPing(Opcode opcode)
{
return opcode == Opcode.PING;
}
private static bool isPong(Opcode opcode)
{
return opcode == Opcode.PONG;
}
private static bool isText(Opcode opcode)
{
return opcode == Opcode.TEXT;
}
#endregion
#region IEnumerable<byte>
public IEnumerator<byte> GetEnumerator()
{
foreach (byte b in ToByteArray())
{
yield return b;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
}
} |
using System;
namespace P1
{
class Solution
{
static void Main(string[] args)
{
var j = 1;
string casenumber = Console.ReadLine();
string input = Console.ReadLine();
while (input != "")
{
if (input.Contains("4"))
{
Int64 second = 0;
for (int i = 0; i < input.Length; i++)
{
if (input[i] == '4')
{
second = second + Getdec(input.Length, i);
}
}
var pirmas = Convert.ToInt64(input) - second;
Console.WriteLine($"Case #{j}: {pirmas} {second}");
}
if (j >= Convert.ToInt32(casenumber))
{
return;
}
input = Console.ReadLine();
j++;
}
}
public static Int64 Getdec(int len, int indexer)
{
int zeros = len - indexer - 1;
return (Int64)Math.Pow(10, zeros);
}
}
}
|
#region Copyright Syncfusion Inc. 2001-2015.
// Copyright Syncfusion Inc. 2001-2015. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using System;
using Syncfusion.SfDataGrid;
using UIKit;
namespace SampleBrowser
{
public class Blue : DataGridStyle
{
public Blue ()
{
}
public override UIColor GetHeaderBackgroundColor ()
{
return UIColor.FromRGB (242, 242, 242);
}
public override UIColor GetAlternatingRowBackgroundColor ()
{
return UIColor.FromRGB (230, 239, 237);
}
public override UIColor GetSelectionBackgroundColor ()
{
return UIColor.FromRGB (72, 173, 170);
}
public override UIColor GetSelectionForegroundColor ()
{
return UIColor.FromRGB (255, 255, 255);
}
public override UIColor GetCaptionSummaryRowBackgroundColor ()
{
return UIColor.FromRGB (224, 224, 224);
}
public override UIColor GetCaptionSummaryRowForeGroundColor ()
{
return UIColor.FromRGB (51, 51, 51);
}
public override UIColor GetBordercolor ()
{
return UIColor.FromRGB (180, 180, 180);
}
// public override int GetHeaderSortIndicatorDown ()
// {
// return Resource.Drawable.SortingDown;
// }
//
// public override int GetHeaderSortIndicatorUp ()
// {
// return Resource.Drawable.SortingUp;
// }
}
}
|
using System;
using System.Windows.Forms;
namespace _41016_Ex10
{
class Search{
static public Form1 S;
static internal void Bt_search_Click(object sender, EventArgs e)
{
int sum = 0;
bool found = false;
for (int i = 0; i < S.person.GetLength(0); i++)
{
if (S.Tb_id.Text == S.person[i, 0])
{
found = true;
S.Tb_name.Text = S.person[i, 1];
S.Tb_Chi.Text = S.grade[i, 0].ToString();
S.Tb_Eng.Text = S.grade[i, 1].ToString();
S.Tb_Math.Text = S.grade[i, 2].ToString();
for (int k = 0; k < S.grade.GetLength(1); k++)
{
sum += S.grade[i, k];
}
S.Tb_total.Text = sum.ToString();
}
}
if (!found) MessageBox.Show("不存在" + S.Tb_id.Text);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace affärslager
{
internal class FakturaRepository
{
internal List<Faktura> fakturor = new List<Faktura>();
internal void LäggTillFaktura(int bokningsNummer, string medlemsNummer, DateTime faktisktÅterlämningsDatum, double pris)
{
fakturor.Add(new Faktura(bokningsNummer, medlemsNummer, faktisktÅterlämningsDatum, pris));
}
internal List<Faktura> HämtaFakturor()
{
return fakturor;
}
public double RäknaUtKostnad(double antalDagar)
{
double pris = 0;
if(antalDagar >= 1)
{
pris = antalDagar * 10;
}
else
{
pris = 0;
}
return pris;
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace ApplicationNavigation.Model
{
public class Warrior : PlayerCharacter
{
public Warrior()
{
}
~Warrior()
{
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
// Agregar los namespaces de conexión con SQL Server
using System.Data.SqlClient;
using System.Configuration;
using System.Globalization;
using System.Data;
namespace Clinica_Dental
{
class ListaCita
{
// Variables miembro
private static string connectionString = ConfigurationManager.ConnectionStrings["Clinica_Dental.Properties.Settings.ClinicaDentalConnectionString"].ConnectionString;
private SqlConnection sqlConnection = new SqlConnection(connectionString);
//Propiedades
public int IdCita { get; set; }
public string Identidad { get; set; }
public string Nota { get; set; }
public string Paciente { get; set; }
public TimeSpan Hora { get; set; }
//Constructores
public ListaCita() { }
public ListaCita(int id, string identidad, string nota, string paciente, TimeSpan hora)
{
IdCita = id;
Identidad = identidad;
Nota = nota;
Paciente = paciente;
Hora = hora;
}
//Metodos
public List<ListaCita> MostrarLista(DateTime fecha)
{
//Inicializar una lista vacía de los las citas
List<ListaCita> listas = new List<ListaCita>();
try
{
// Query de selección
string query = @"select a.idCita as ID, a.hora as Hora,a.nota as Nota, c.identidad as Identidad, c.nombres + ' ' + c.apellidos as Paciente
from [Pacientes].[Cita] a inner join [Pacientes].[HistorialClinico] b
on a.idHistorialClinico = b.idHistorialClinico inner join [Pacientes].[Paciente] c
on b.identidadPaciente = c.identidad
where a.fechaCita = @fecha
order by a.hora";
// Establecer la conexión
sqlConnection.Open();
// Crear el comando SQL
SqlCommand sqlCommand = new SqlCommand(query, sqlConnection);
sqlCommand.Parameters.AddWithValue("@fecha", fecha);
// Obtener los datos de la citas
using (SqlDataReader rdr = sqlCommand.ExecuteReader())
{
while (rdr.Read())
{
listas.Add(new ListaCita
{
IdCita = Convert.ToInt32(rdr["ID"]),
Identidad = rdr["Identidad"].ToString(),
Nota = rdr["Nota"].ToString(),
Paciente = rdr["Paciente"].ToString(),
Hora = TimeSpan.Parse((string)rdr["Hora"].ToString())
});
}
}
return listas;
}
catch (Exception e)
{
throw e;
}
finally
{
// Cerrar la conexión
sqlConnection.Close();
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Model.Locale;
using Model.Security.MembershipManagement;
using Model.InvoiceManagement;
using Business.Helper;
using Model.DataEntity;
using Uxnet.Web.Module.Common;
using Utility;
namespace eIVOGo.Module.Inquiry
{
public partial class QueryBonus : System.Web.UI.UserControl, IPostBackEventHandler
{
UserProfileMember _userProfile;
public class dataType
{
public int id;
public string range;
public string TrackCode;
public string No;
public string CompanyName;
public string Addr;
public string CarrierType;
public string Donation;
public string DonateMark;
}
protected void Page_Load(object sender, EventArgs e)
{
_userProfile = WebPageUtility.UserProfile;
if (!Page.IsPostBack)
{
if (_userProfile.CurrentUserRole.RoleID == ((int)Naming.RoleID.ROLE_GUEST))
{
this.rdbType1.Visible = false;
this.rdbType2.Visible = false;
this.lblDevice.Visible = true;
this.ddlDevice.Visible = true;
}
LoadDevice();
LoadRange();
this.PrintingButton21.btnPrint.Text = "資料列印";
this.PrintingButton21.btnPrint.CssClass = "btn";
}
this.PrintingButton21.PrintControls.Add(this.gvEntity);
}
protected override void OnInit(EventArgs e)
{
gvEntity.PreRender += new EventHandler(gvEntity_PreRender);
this.PrintingButton21.BeforeClick += new EventHandler(btnPrint_BeforeClick);
}
void btnPrint_BeforeClick(object sender, EventArgs e)
{
this.gvEntity.AllowPaging = false;
}
#region "Load Page Control Data"
protected void LoadDevice()
{
this.ddlDevice.Items.Clear();
this.ddlDevice.Items.Add(new ListItem("-請選擇-", "0"));
this.ddlDevice.Items.Add(new ListItem("UXB2B條碼卡", "1"));
this.ddlDevice.Items.Add(new ListItem("悠遊卡", "2"));
}
protected void LoadRange()
{
int year = 0;
int month = 0;
this.ddlRange1.Items.Clear();
this.ddlRange2.Items.Clear();
for (int m = 2; m < 26; m += 2)
{
DateTime date = DateTime.Now.AddMonths(-m);
year = date.Year;
month = date.Month;
if (date.Month % 2 == 1)
{
month += 1;
}
this.ddlRange1.Items.Add(new ListItem((year - 1911).ToString().PadLeft(3, '0') + "年 " + (month - 1).ToString("00") + "-" + month.ToString("00") + "月", year.ToString() + (month - 1).ToString("00") + month.ToString("00")));
this.ddlRange2.Items.Add(new ListItem((year - 1911).ToString().PadLeft(3, '0') + "年 " + (month - 1).ToString("00") + "-" + month.ToString("00") + "月", year.ToString() + (month - 1).ToString("00") + month.ToString("00")));
}
}
#endregion
#region "Page Control Event"
protected void rdbType_CheckedChanged(object sender, EventArgs e)
{
if (this.rdbType1.Checked == true)
{
this.ddlDevice.SelectedIndex = 0;
this.ddlDevice.Visible = false;
this.uxb2b.Visible = false;
}
else
{
this.ddlDevice.Visible = true;
}
}
protected void ddlDevice_SelectedIndexChanged(object sender, EventArgs e)
{
if (this.ddlDevice.SelectedValue == "1")
this.uxb2b.Visible = true;
else
this.uxb2b.Visible = false;
}
protected void btnQuery_Click(object sender, EventArgs e)
{
this.divResult.Visible = true;
SearchData();
}
#endregion
#region "Gridview Event"
void gvEntity_PreRender(object sender, EventArgs e)
{
SearchData();
}
#endregion
#region "Search Data"
private void SearchData()
{
using (InvoiceManager im = new InvoiceManager())
{
try
{
var data = from d in im.GetTable<InvoiceWinningNumber>()
select new
{
d.InvoiceID,
d.UniformInvoiceWinningNumber.Year,
MonthFrom = d.UniformInvoiceWinningNumber.Period*2-1,
MonthTo = d.UniformInvoiceWinningNumber.Period*2,
d.InvoiceItem.TrackCode,
d.InvoiceItem.No,
d.InvoiceItem.InvoiceDate,
d.InvoiceItem.Organization.CompanyName,
d.InvoiceItem.Organization.Addr,
d.InvoiceItem.InvoiceByHousehold.InvoiceUserCarrier.InvoiceUserCarrierType.CarrierType,
Donation = im.GetTable<Organization>().Where(og => og.CompanyID == d.InvoiceItem.DonationID).FirstOrDefault().CompanyName,
d.InvoiceItem.DonateMark,
d.InvoiceItem.SellerID,
d.InvoiceItem.InvoiceByHousehold.InvoiceUserCarrier.UID
};
//當登入者為賣方店家時,則只能查到自己的中獎發票資訊,若非店家而是一般使用者,則僅能查詢自己的中獎發票資訊
if (_userProfile.CurrentUserRole.RoleID == (int)Naming.RoleID.ROLE_SELLER || _userProfile.CurrentUserRole.RoleID == (int)Naming.RoleID.ROLE_GOOGLETW)
{
data = data.Where(d => d.SellerID == _userProfile.CurrentUserRole.OrganizationCategory.CompanyID);
}
else
{
data = data.Where(d => d.UID == _userProfile.UID);
}
int Year1 = int.Parse(this.ddlRange1.SelectedValue.Substring(0, 4));
int Year2 = int.Parse(this.ddlRange2.SelectedValue.Substring(0, 4));
DateTime sDate = new DateTime();
DateTime eDate = new DateTime();
if (Year1 > Year2)
{
int Month1 = int.Parse(this.ddlRange2.SelectedValue.Substring(4, 2));
int Month2 = int.Parse(this.ddlRange1.SelectedValue.Substring(6, 2));
sDate = new DateTime(Year2, Month1, 1);
eDate = Month2 == 12 ? new DateTime(Year1 + 1, 1, 1) : new DateTime(Year1, Month2 + 1, 1);
}
else if (Year1 < Year2)
{
int Month1 = int.Parse(this.ddlRange1.SelectedValue.Substring(4, 2));
int Month2 = int.Parse(this.ddlRange2.SelectedValue.Substring(6, 2));
sDate = new DateTime(Year1, Month1, 1);
eDate = Month2 == 12 ? new DateTime(Year2 + 1, 1, 1) : new DateTime(Year2, Month2 + 1, 1);
}
else if (Year1 == Year2)
{
if (int.Parse(this.ddlRange1.SelectedValue.Substring(4, 2)) > int.Parse(this.ddlRange2.SelectedValue.Substring(4, 2)))
{
int Month1 = int.Parse(this.ddlRange2.SelectedValue.Substring(4, 2));
int Month2 = int.Parse(this.ddlRange1.SelectedValue.Substring(6, 2));
sDate = new DateTime(Year1, Month1, 1);
eDate = Month2 == 12 ? new DateTime(Year1 + 1, 1, 1) : new DateTime(Year1, Month2 + 1, 1);
}
else if (int.Parse(this.ddlRange1.SelectedValue.Substring(4, 2)) < int.Parse(this.ddlRange2.SelectedValue.Substring(4, 2)))
{
int Month1 = int.Parse(this.ddlRange1.SelectedValue.Substring(4, 2));
int Month2 = int.Parse(this.ddlRange2.SelectedValue.Substring(6, 2));
sDate = new DateTime(Year1, Month1, 1);
eDate = Month2 == 12 ? new DateTime(Year1 + 1, 1, 1) : new DateTime(Year1, Month2 + 1, 1);
}
else if (int.Parse(this.ddlRange1.SelectedValue.Substring(4, 2)) == int.Parse(this.ddlRange2.SelectedValue.Substring(4, 2)))
{
int Month1 = int.Parse(this.ddlRange1.SelectedValue.Substring(4, 2));
int Month2 = int.Parse(this.ddlRange2.SelectedValue.Substring(6, 2));
sDate = new DateTime(Year1, Month1, 1);
eDate = Month2 == 12 ? new DateTime(Year1 + 1, 1, 1) : new DateTime(Year1, Month2 + 1, 1);
}
}
data = data.Where(d => d.InvoiceDate.Value.Date >= sDate.Date && d.InvoiceDate.Value.Date < eDate.Date);
if (this.rdbDonate.Checked == true)
{
data = data.Where(d => d.DonateMark.Equals("1"));
}
var getData = from da in data.OrderByDescending(d => d.InvoiceDate).ToList()
select new dataType
{
id = da.InvoiceID,
range = (da.Year - 1911) + "年 " + da.MonthFrom + "-" + da.MonthTo + "月",
TrackCode = da.TrackCode,
No = da.No,
CompanyName = da.CompanyName,
Addr = da.Addr,
CarrierType = da.CarrierType,
Donation = da.Donation,
DonateMark=da.DonateMark
};
if (getData.Count() > 0)
{
if (this.gvEntity.AllowPaging)
{
int count = getData.Count();
this.lblError.Visible = false;
this.gvEntity.PageIndex = PagingControl.GetCurrentPageIndex(this.gvEntity, 0);
this.gvEntity.DataSource = getData.ToList();
this.gvEntity.DataBind();
PagingControl paging = (PagingControl)this.gvEntity.BottomPagerRow.Cells[0].FindControl("pagingIndex");
paging.RecordCount = count;
paging.CurrentPageIndex = this.gvEntity.PageIndex;
}
else
{
this.gvEntity.DataSource = getData.ToList();
this.gvEntity.DataBind();
}
this.PrintingButton21.Visible = true;
}
else
{
this.lblError.Text = "查無資料!!";
this.lblError.Visible = true;
this.PrintingButton21.Visible = false;
this.gvEntity.DataSource = null;
this.gvEntity.DataBind();
}
}
catch (Exception ex)
{
Logger.Error(ex);
this.lblError.Text = "系統錯誤:" + ex.Message;
}
}
}
#endregion
public void RaisePostBackEvent(string eventArgument)
{
if (eventArgument.StartsWith("S:"))
{
this.PNewInvalidInvoicePreview1.setDetail = eventArgument.Substring(2).Trim();
this.PNewInvalidInvoicePreview1.Popup.Show();
}
}
}
} |
using System;
using System.ComponentModel.DataAnnotations;
namespace ITQJ.Domain.DTOs
{
public class MileStoneCreateDTO
{
[Required]
public string Description { get; set; }
public string FileName { get; set; }
[Required]
public DateTime UploadDate { get; set; }
[Required]
public Guid ProjectId { get; set; }
[Required]
public Guid UserId { get; set; }
}
public class MileStoneResponseDTO : MileStoneCreateDTO
{
public Guid Id { get; set; }
}
} |
using System.Linq;
using NUnit.Framework;
using SolidabisChallenge;
namespace Tests
{
public class SentenceTests
{
private Sentence _sut;
[Test]
public void WordsAreSplitAndTurnedToLowerCase()
{
_sut = new Sentence("Ywsä xood emääje eföäooä xsyowä vszywåwm öässddodes gföååooä zoåaooäwooeeo.");
Assert.That(_sut.DecipheredWords.Count(), Is.EqualTo(9));
Assert.IsTrue(_sut.DecipheredWords.Contains("ywsä"));
Assert.IsTrue(_sut.DecipheredWords.Contains("xood"));
Assert.IsTrue(_sut.DecipheredWords.Contains("emääje"));
Assert.IsTrue(_sut.DecipheredWords.Contains("eföäooä"));
Assert.IsTrue(_sut.DecipheredWords.Contains("xsyowä"));
Assert.IsTrue(_sut.DecipheredWords.Contains("vszywåwm"));
Assert.IsTrue(_sut.DecipheredWords.Contains("öässddodes"));
Assert.IsTrue(_sut.DecipheredWords.Contains("gföååooä"));
Assert.IsTrue(_sut.DecipheredWords.Contains("zoåaooäwooeeo"));
}
[Test]
public void DecipheringSentencesMovesCharactersOneStepForwardInAlphabet()
{
_sut = new Sentence("Ab cd.");
Assert.IsTrue(_sut.TryCreatingNextDecipheredSentence());
Assert.That(_sut.DecipheredSentence, Is.EqualTo("bc de."));
Assert.That(_sut.DecipheredWords.Count(), Is.EqualTo(2));
Assert.IsTrue(_sut.DecipheredWords.Contains("bc"));
Assert.IsTrue(_sut.DecipheredWords.Contains("de"));
Assert.IsTrue(_sut.TryCreatingNextDecipheredSentence());
Assert.That(_sut.DecipheredSentence, Is.EqualTo("cd ef."));
Assert.That(_sut.DecipheredWords.Count(), Is.EqualTo(2));
Assert.IsTrue(_sut.DecipheredWords.Contains("cd"));
Assert.IsTrue(_sut.DecipheredWords.Contains("ef"));
Assert.IsTrue(_sut.TryCreatingNextDecipheredSentence());
Assert.That(_sut.DecipheredSentence, Is.EqualTo("de fg."));
Assert.That(_sut.DecipheredWords.Count(), Is.EqualTo(2));
Assert.IsTrue(_sut.DecipheredWords.Contains("de"));
Assert.IsTrue(_sut.DecipheredWords.Contains("fg"));
Assert.IsTrue(_sut.TryCreatingNextDecipheredSentence());
Assert.That(_sut.DecipheredSentence, Is.EqualTo("ef gh."));
Assert.That(_sut.DecipheredWords.Count(), Is.EqualTo(2));
Assert.IsTrue(_sut.DecipheredWords.Contains("ef"));
Assert.IsTrue(_sut.DecipheredWords.Contains("gh"));
Assert.IsTrue(_sut.TryCreatingNextDecipheredSentence());
Assert.That(_sut.DecipheredSentence, Is.EqualTo("fg hi."));
Assert.That(_sut.DecipheredWords.Count(), Is.EqualTo(2));
Assert.IsTrue(_sut.DecipheredWords.Contains("fg"));
Assert.IsTrue(_sut.DecipheredWords.Contains("hi"));
Assert.IsTrue(_sut.TryCreatingNextDecipheredSentence());
Assert.That(_sut.DecipheredSentence, Is.EqualTo("gh ij."));
Assert.That(_sut.DecipheredWords.Count(), Is.EqualTo(2));
Assert.IsTrue(_sut.DecipheredWords.Contains("gh"));
Assert.IsTrue(_sut.DecipheredWords.Contains("ij"));
Assert.IsTrue(_sut.TryCreatingNextDecipheredSentence());
Assert.That(_sut.DecipheredSentence, Is.EqualTo("hi jk."));
Assert.That(_sut.DecipheredWords.Count(), Is.EqualTo(2));
Assert.IsTrue(_sut.DecipheredWords.Contains("hi"));
Assert.IsTrue(_sut.DecipheredWords.Contains("jk"));
Assert.IsTrue(_sut.TryCreatingNextDecipheredSentence());
Assert.That(_sut.DecipheredSentence, Is.EqualTo("ij kl."));
Assert.That(_sut.DecipheredWords.Count(), Is.EqualTo(2));
Assert.IsTrue(_sut.DecipheredWords.Contains("ij"));
Assert.IsTrue(_sut.DecipheredWords.Contains("kl"));
Assert.IsTrue(_sut.TryCreatingNextDecipheredSentence());
Assert.That(_sut.DecipheredSentence, Is.EqualTo("jk lm."));
Assert.That(_sut.DecipheredWords.Count(), Is.EqualTo(2));
Assert.IsTrue(_sut.DecipheredWords.Contains("jk"));
Assert.IsTrue(_sut.DecipheredWords.Contains("lm"));
Assert.IsTrue(_sut.TryCreatingNextDecipheredSentence());
Assert.That(_sut.DecipheredSentence, Is.EqualTo("kl mn."));
Assert.That(_sut.DecipheredWords.Count(), Is.EqualTo(2));
Assert.IsTrue(_sut.DecipheredWords.Contains("kl"));
Assert.IsTrue(_sut.DecipheredWords.Contains("mn"));
Assert.IsTrue(_sut.TryCreatingNextDecipheredSentence());
Assert.That(_sut.DecipheredSentence, Is.EqualTo("lm no."));
Assert.That(_sut.DecipheredWords.Count(), Is.EqualTo(2));
Assert.IsTrue(_sut.DecipheredWords.Contains("lm"));
Assert.IsTrue(_sut.DecipheredWords.Contains("no"));
Assert.IsTrue(_sut.TryCreatingNextDecipheredSentence());
Assert.That(_sut.DecipheredSentence, Is.EqualTo("mn op."));
Assert.That(_sut.DecipheredWords.Count(), Is.EqualTo(2));
Assert.IsTrue(_sut.DecipheredWords.Contains("mn"));
Assert.IsTrue(_sut.DecipheredWords.Contains("op"));
Assert.IsTrue(_sut.TryCreatingNextDecipheredSentence());
Assert.That(_sut.DecipheredSentence, Is.EqualTo("no pq."));
Assert.That(_sut.DecipheredWords.Count(), Is.EqualTo(2));
Assert.IsTrue(_sut.DecipheredWords.Contains("no"));
Assert.IsTrue(_sut.DecipheredWords.Contains("pq"));
Assert.IsTrue(_sut.TryCreatingNextDecipheredSentence());
Assert.That(_sut.DecipheredSentence, Is.EqualTo("op qr."));
Assert.That(_sut.DecipheredWords.Count(), Is.EqualTo(2));
Assert.IsTrue(_sut.DecipheredWords.Contains("op"));
Assert.IsTrue(_sut.DecipheredWords.Contains("qr"));
Assert.IsTrue(_sut.TryCreatingNextDecipheredSentence());
Assert.That(_sut.DecipheredSentence, Is.EqualTo("pq rs."));
Assert.That(_sut.DecipheredWords.Count(), Is.EqualTo(2));
Assert.IsTrue(_sut.DecipheredWords.Contains("pq"));
Assert.IsTrue(_sut.DecipheredWords.Contains("rs"));
Assert.IsTrue(_sut.TryCreatingNextDecipheredSentence());
Assert.That(_sut.DecipheredSentence, Is.EqualTo("qr st."));
Assert.That(_sut.DecipheredWords.Count(), Is.EqualTo(2));
Assert.IsTrue(_sut.DecipheredWords.Contains("qr"));
Assert.IsTrue(_sut.DecipheredWords.Contains("st"));
Assert.IsTrue(_sut.TryCreatingNextDecipheredSentence());
Assert.That(_sut.DecipheredSentence, Is.EqualTo("rs tu."));
Assert.That(_sut.DecipheredWords.Count(), Is.EqualTo(2));
Assert.IsTrue(_sut.DecipheredWords.Contains("rs"));
Assert.IsTrue(_sut.DecipheredWords.Contains("tu"));
Assert.IsTrue(_sut.TryCreatingNextDecipheredSentence());
Assert.That(_sut.DecipheredSentence, Is.EqualTo("st uv."));
Assert.That(_sut.DecipheredWords.Count(), Is.EqualTo(2));
Assert.IsTrue(_sut.DecipheredWords.Contains("st"));
Assert.IsTrue(_sut.DecipheredWords.Contains("uv"));
Assert.IsTrue(_sut.TryCreatingNextDecipheredSentence());
Assert.That(_sut.DecipheredSentence, Is.EqualTo("tu vw."));
Assert.That(_sut.DecipheredWords.Count(), Is.EqualTo(2));
Assert.IsTrue(_sut.DecipheredWords.Contains("tu"));
Assert.IsTrue(_sut.DecipheredWords.Contains("vw"));
Assert.IsTrue(_sut.TryCreatingNextDecipheredSentence());
Assert.That(_sut.DecipheredSentence, Is.EqualTo("uv wx."));
Assert.That(_sut.DecipheredWords.Count(), Is.EqualTo(2));
Assert.IsTrue(_sut.DecipheredWords.Contains("uv"));
Assert.IsTrue(_sut.DecipheredWords.Contains("wx"));
Assert.IsTrue(_sut.TryCreatingNextDecipheredSentence());
Assert.That(_sut.DecipheredSentence, Is.EqualTo("vw xy."));
Assert.That(_sut.DecipheredWords.Count(), Is.EqualTo(2));
Assert.IsTrue(_sut.DecipheredWords.Contains("vw"));
Assert.IsTrue(_sut.DecipheredWords.Contains("xy"));
Assert.IsTrue(_sut.TryCreatingNextDecipheredSentence());
Assert.That(_sut.DecipheredSentence, Is.EqualTo("wx yz."));
Assert.That(_sut.DecipheredWords.Count(), Is.EqualTo(2));
Assert.IsTrue(_sut.DecipheredWords.Contains("wx"));
Assert.IsTrue(_sut.DecipheredWords.Contains("yz"));
Assert.IsTrue(_sut.TryCreatingNextDecipheredSentence());
Assert.That(_sut.DecipheredSentence, Is.EqualTo("xy zå."));
Assert.That(_sut.DecipheredWords.Count(), Is.EqualTo(2));
Assert.IsTrue(_sut.DecipheredWords.Contains("xy"));
Assert.IsTrue(_sut.DecipheredWords.Contains("zå"));
Assert.IsTrue(_sut.TryCreatingNextDecipheredSentence());
Assert.That(_sut.DecipheredSentence, Is.EqualTo("yz åä."));
Assert.That(_sut.DecipheredWords.Count(), Is.EqualTo(2));
Assert.IsTrue(_sut.DecipheredWords.Contains("yz"));
Assert.IsTrue(_sut.DecipheredWords.Contains("åä"));
Assert.IsTrue(_sut.TryCreatingNextDecipheredSentence());
Assert.That(_sut.DecipheredSentence, Is.EqualTo("zå äö."));
Assert.That(_sut.DecipheredWords.Count(), Is.EqualTo(2));
Assert.IsTrue(_sut.DecipheredWords.Contains("zå"));
Assert.IsTrue(_sut.DecipheredWords.Contains("äö"));
Assert.IsTrue(_sut.TryCreatingNextDecipheredSentence());
Assert.That(_sut.DecipheredSentence, Is.EqualTo("åä öa."));
Assert.That(_sut.DecipheredWords.Count(), Is.EqualTo(2));
Assert.IsTrue(_sut.DecipheredWords.Contains("åä"));
Assert.IsTrue(_sut.DecipheredWords.Contains("öa"));
Assert.IsTrue(_sut.TryCreatingNextDecipheredSentence());
Assert.That(_sut.DecipheredSentence, Is.EqualTo("äö ab."));
Assert.That(_sut.DecipheredWords.Count(), Is.EqualTo(2));
Assert.IsTrue(_sut.DecipheredWords.Contains("äö"));
Assert.IsTrue(_sut.DecipheredWords.Contains("ab"));
Assert.IsTrue(_sut.TryCreatingNextDecipheredSentence());
Assert.That(_sut.DecipheredSentence, Is.EqualTo("öa bc."));
Assert.That(_sut.DecipheredWords.Count(), Is.EqualTo(2));
Assert.IsTrue(_sut.DecipheredWords.Contains("öa"));
Assert.IsTrue(_sut.DecipheredWords.Contains("bc"));
Assert.IsFalse(_sut.TryCreatingNextDecipheredSentence());
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Assignment5
{
public class Inventory
{
//int slots; //removed it from now, not clear what it will be used for
List<Item> items;
public Inventory(int slots)
{
items = new List<Item>(slots);
}
public void Add(Item item)
{
items.Add(item);
Console.WriteLine("{0} added to inventory.", item.Name);
}
//removes the first instance that matches the item parameters passed
public void Remove(Item item)
{
//code to remove all instances
//List<int> toRemove = new List<int>();
for (int i = 0; i < items.Count; i++)
{
if (items[i].Name.Equals(item.Name) && items[i].Modifier == item.Modifier && items[i].IType == item.IType)
{
//toRemove.Add(i);
Console.WriteLine("{0} removed from inventory.", item.Name);
items.RemoveAt(i);
break;
}
}
//toRemove.Reverse();
//foreach (int i in toRemove)
// items.RemoveAt(i);
}
public void ShowInventory()
{
foreach (Item item in items)
{
Console.WriteLine(item);
}
}
public int GetInventorySize()
{
return items.Count;
}
}
}
|
namespace Triton.Game.Mapping
{
using ns26;
using System;
using Triton.Game.Mono;
[Attribute38("FriendListFriendFrameOffsets")]
public class FriendListFriendFrameOffsets : MonoClass
{
public FriendListFriendFrameOffsets(IntPtr address) : this(address, "FriendListFriendFrameOffsets")
{
}
public FriendListFriendFrameOffsets(IntPtr address, string className) : base(address, className)
{
}
public Vector3 m_PlayerNameText
{
get
{
return base.method_2<Vector3>("m_PlayerNameText");
}
}
public Vector3 m_RecruitUI
{
get
{
return base.method_2<Vector3>("m_RecruitUI");
}
}
public Vector3 m_RightComponent
{
get
{
return base.method_2<Vector3>("m_RightComponent");
}
}
public Vector3 m_StatusText
{
get
{
return base.method_2<Vector3>("m_StatusText");
}
}
}
}
|
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using webapi.Models;
namespace webapi.Credit
{
public interface ICreditCompeny
{
Task<APIResponse> ChargeCredit(TransactionInfo transaction);
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
public class CustomMenuItems
{
#region debug
const string kDebugLuaAssetBundlesMenu = "Custom/Debug Lua";
[MenuItem(kDebugLuaAssetBundlesMenu, false, 1)]
public static void ToggleSimulateAssetBundle()
{
OzLuaManager.isDebug = !OzLuaManager.isDebug;
}
[MenuItem(kDebugLuaAssetBundlesMenu, true, 1)]
public static bool ToggleSimulateAssetBundleValidate()
{
Menu.SetChecked(kDebugLuaAssetBundlesMenu, OzLuaManager.isDebug);
return true;
}
#endregion
#region AssetBundle
const string kSimulationMode = "Custom/AssetBundle/Simulation Mode";
[MenuItem(kSimulationMode, false, 2)]
public static void ToggleSimulationMode()
{
AssetBundleManager.SimulateAssetBundleInEditor = !AssetBundleManager.SimulateAssetBundleInEditor;
}
[MenuItem(kSimulationMode, true)]
public static bool ToggleSimulationModeValidate()
{
Menu.SetChecked(kSimulationMode, AssetBundleManager.SimulateAssetBundleInEditor);
return true;
}
[MenuItem("Custom/AssetBundle/导出AssetBundle", false, 2)]
public static void BuildAssetBundles()
{
ExportAssetBundle.BuildAssetBundles();
}
[MenuItem("Custom/AssetBundle/设置AssetBundle Name", false, 3)]
public static void SetAssetBundlesName()
{
ExportAssetBundle.SetAssetBundlesNameByDirectory();
}
[MenuItem("Assets/AssetBundle/设置AssetBundle Name", false, 201)]
public static void SetAssetBundlesNameByDirectory()
{
ExportAssetBundle.SetAssetBundlesNameByDirectory();
}
[MenuItem("Custom/AssetBundle/更新bundleVersion", false, 4)]
public static void UpdateBundleVersion()
{
BundleVersionChecker.UpdateBundleVersion();
}
#endregion
#region 加密
[MenuItem("Custom/加密/GenerateKey", false, 11)]
static void GenerateDES()
{
ExportAssetBundle.GenerateKey();
}
#endregion
#region lua
[MenuItem("Custom/导出Lua", false, 21)]
public static void ExportLua()
{
ExportAssetBundle.ExportLua();
}
#endregion
#region 发版
[MenuItem("Custom/发版/生成首包版本号", false, 102)]
public static void GenerateVersion()
{
ExportAssetBundle.GenerateVersion();
}
[MenuItem("Custom/发版/生成增量包", false, 101)]
public static void ExportPublic()
{
ExportAssetBundle.BuildAssetBundles();
AssetDatabase.Refresh();
ExportAssetBundle.ExportLua();
AssetDatabase.Refresh();
ExportAssetBundle.GenerateResPublic(CurrentBundleVersion.versionCode.ToString());
}
[MenuItem("Custom/发版/仅生成lua代码增量包", false, 101)]
public static void ExportLuaPublic()
{
ExportAssetBundle.ExportLua();
AssetDatabase.Refresh();
ExportAssetBundle.GenerateDataPublic();
}
[MenuItem("Custom/发版/一键导出所有资源", false, 103)]
public static void ExportAllAssetBundle()
{
string strOutputPath = Path.GetFullPath(Path.Combine(Application.streamingAssetsPath, PathUtil.Platform));
DirectoryInfo dir = new DirectoryInfo(strOutputPath);
if (dir.Exists)
{
dir.Delete(true);
}
ExportAssetBundle.BuildAssetBundles();
ExportAssetBundle.ExportLua();
}
#endregion
#region 服务器
const string kDebugServerDemo = "Custom/服务器/Demo服(47.107.176.241:18001)";
const string kDebugServerLocal = "Custom/服务器/本地环境(127.0.0.1:18001)";
static string[] serverList =
{
"47.107.176.241:18001",
"127.0.0.1:18001"
};
[MenuItem(kDebugServerDemo, false, 50)]
public static void ToggleDemoConnect()
{
if (GameConfig.connectServer == serverList[0])
{
GameConfig.connectServer = "";
}
else
{
GameConfig.connectServer = serverList[0];
}
}
[MenuItem(kDebugServerDemo, true, 50)]
public static bool ToggleDemoConnectValidate()
{
Menu.SetChecked(kDebugServerLocal, GameConfig.connectServer == serverList[0]);
return true;
}
[MenuItem(kDebugServerLocal, false, 50)]
public static void ToggleLocalConnect()
{
if (GameConfig.connectServer == serverList[1])
{
GameConfig.connectServer = "";
}
else
{
GameConfig.connectServer = serverList[1];
}
}
[MenuItem(kDebugServerLocal, true, 50)]
public static bool ToggleLocalConnectValidate()
{
Menu.SetChecked(kDebugServerLocal, GameConfig.connectServer == serverList[1]);
return true;
}
#endregion
#region 其它
[MenuItem("Custom/其它/清除PlayerPrefs", false, 200)]
public static void CleanPlayerPrefs()
{
PlayerPrefs.DeleteAll();
}
[MenuItem("Custom/其它/编辑PlayerPrefs", false, 201)]
public static void EditPlayerPrefs()
{
CustomPrefsEditor.ShowWindow();
}
[MenuItem("Custom/其它/清除本地缓存的文件", false, 202)]
public static void CleanLocalFile()
{
PlayerPrefs.DeleteKey(GameConfig.LocalResVersionKey);
PlayerPrefs.DeleteKey(GameConfig.LocalSubVersionKey);
ExportAssetBundle.CleanLocalFile();
}
[MenuItem("Custom/其它/对lua文件进行UTF8编码", false, 203)]
public static void EncodeLuaFile()
{
ExportAssetBundle.EncodeLuaFile();
}
[MenuItem("Custom/其它/对C#文件进行UTF8编码", false, 203)]
public static void EncodeCSharpFile()
{
ExportAssetBundle.EncodeCSharpFile();
}
[MenuItem("Custom/其它/clear progress bar", false, 204)]
public static void ClearProgressBar()
{
EditorUtility.ClearProgressBar();
}
[MenuItem("Custom/其它/info", false, 205)]
public static void showInfo()
{
Debug.LogFormat("Application.persistentDataPath:{0}", Application.persistentDataPath);
}
[MenuItem("Custom/其它/生成混淆代码", false, 206)]
public static void GenerateCode()
{
GenerateObfuscatedCode.GenerateCodes();
}
[MenuItem("Custom/其它/加密assetbundle", false, 207)]
public static void EncryptAssetBundle()
{
ExportAssetBundle.EncryptAssetBundle();
}
[MenuItem("Custom/其它/解密assetbundle", false, 208)]
public static void DecryptAssetBundle()
{
ExportAssetBundle.EncryptAssetBundle();
}
[MenuItem("Custom/其它/Define/添加DEBUG_PROFILER", false, 209)]
public static void AddProfilerDefine()
{
BetterDefinesUtils.AddProfiler();
}
[MenuItem("Custom/其它/Define/移除DEBUG_PROFILER", false, 210)]
public static void RemoveProfilerDefine()
{
BetterDefinesUtils.RemoveProfiler();
}
//[MenuItem("Custom/其它/修改prefab朝向", false, 212)]
public static void ModifyPrefabForward()
{
EditorUtility.DisplayProgressBar("Modify Prefab", "Please wait...", 0);
string[] ids = AssetDatabase.FindAssets("t:Prefab", new string[] { "Assets/RawResources/Scene/CartoonStyle_Fantasy_Pack/Prefabs" });
for (int i = 0; i < ids.Length; i++)
{
string assetPath = AssetDatabase.GUIDToAssetPath(ids[i]);
GameObject prefab = AssetDatabase.LoadAssetAtPath(assetPath, typeof(GameObject)) as GameObject;
if (prefab.GetComponent<MeshFilter>() != null)
{
GameObject parentObj = new GameObject(prefab.name);
GameObject adjustObj = GameObject.Instantiate<GameObject>(prefab);
adjustObj.name = prefab.name;
adjustObj.transform.SetParent(parentObj.transform);
adjustObj.transform.localPosition = Vector3.zero;
adjustObj.transform.localScale = Vector3.one;
adjustObj.transform.forward = Vector3.up;
PrefabUtility.SaveAsPrefabAssetAndConnect(parentObj, assetPath, InteractionMode.AutomatedAction);
GameObject.DestroyImmediate(parentObj);
}
EditorUtility.DisplayProgressBar("Modify Prefab", assetPath, i / (float)ids.Length);
}
EditorUtility.ClearProgressBar();
/*
if (assetPath.StartsWith("Assets/RawResources/Scene/CartoonStyle_Fantasy_Pack"))
{
if (assetPath.EndsWith(".prefab"))
{
GameObject obj = PrefabUtility.LoadPrefabContents(assetPath);
GameObject newPrefab = PrefabUtility.InstantiatePrefab(obj) as GameObject;
newPrefab.transform.forward = Vector3.up;
PrefabUtility.SaveAsPrefabAssetAndConnect(newPrefab, assetPath, InteractionMode.AutomatedAction);
}
}
*/
}
[MenuItem("Assets/生成子弹", false, 220)]
public static void GenBullet()
{
GenerateBullet.GenBullet();
}
[MenuItem("Assets/生成子弹", true, 220)]
public static bool CheckBullet()
{
return GenerateBullet.CheckObjectType();
}
[MenuItem("Assets/批量生成子弹", false, 221)]
public static void GenBulletBatch()
{
GenerateBullet.GenBulletBatch();
}
[MenuItem("Assets/批量生成子弹", true, 221)]
public static bool CheckGenBulletBatch()
{
return GenerateBullet.CheckCanGenBulletBatch();
}
[MenuItem("Assets/删除子弹", false, 222)]
public static void DeleteBullet()
{
GenerateBullet.DeleteBullet();
}
[MenuItem("Assets/删除子弹", true, 222)]
public static bool CheckDeleteBullet()
{
return GenerateBullet.CheckDelBullet();
}
[MenuItem("Assets/Find References In Project", false, 100)]
public static void FindReference()
{
FindReferencesInProject.Find();
}
[MenuItem("Assets/Find References In Project", true, 100)]
public static bool FindReferenceValidate()
{
return FindReferencesInProject.FindValidate();
}
#endregion
#region 文件及文件夹
[MenuItem("Assets/当前目录下创建Materials等分类目录", false, 101)]
public static void CreateFolder()
{
EditorFolder.CreateFolder();
}
[MenuItem("Assets/当前目录下创建Lua文件", false, 101)]
public static void CreateLuaFile()
{
EditorFolder.CreateLuaFile();
}
[MenuItem("Assets/打开场景/开始场景", false, 102)]
public static void OpenStartScene()
{
EditorSceneManager.OpenScene("Assets/Scene/start.unity");
}
[MenuItem("Assets/打开场景/临时场景", false, 103)]
public static void OpenTempScene()
{
try
{
EditorSceneManager.OpenScene("Assets/Scene/temp.unity");
}
catch (Exception)
{
EditorSceneManager.NewScene(NewSceneSetup.EmptyScene);
GameObject prefab = AssetDatabase.LoadAssetAtPath<GameObject>("Assets/Resources/Scene/Prefab/Canvas.prefab");
GameObject obj = GameObject.Instantiate(prefab);
obj.name = "Canvas";
}
}
#endregion
#region CompileCoreScriptToDLL
//[MenuItem("Custom/CompileCoreScriptToDLL", false, 400)]
public static void CompileCoreScriptToDLL()
{
CompileCoreScript.CompileCoreScriptToDLL();
}
#endregion
}
|
using _01_Review.Data;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace _01_Review
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
NorthwindEntities db = new NorthwindEntities();
#region Tüm Cirom Ne Kadar
//Tüm Ciron ne kadar
//var query = (
// from p in db.Products
// join od in db.Order_Details on p.ProductID equals od.ProductID
// select new
// {
// asd = (double)(p.UnitPrice * od.Quantity) * (1 - od.Discount)
// }).Sum(x => x.asd);
//MessageBox.Show(query.ToString());
//-----------------------------------------------------
//Extendion Method * Lambda Expression
//dgvTest.DataSource = db.Categories.ToList();
//dgvTest.DataSource = db.Categories
// .Where(x => x.CategoryID > 5)
// .ToList();
//-----------------------------------------------------
//MessageBox.Show(db.Categories
// .Where(x => x.CategoryName == "Beverages")
// .Select(x => x.CategoryID)
// .SingleOrDefault() //.FirstOrDefault() Aynı Şey.
// .ToString());
//-----------------------------------------------------
//dgvTest.DataSource = db.Products
// .Where(x => x.UnitPrice > 20 && x.UnitPrice < 50)
// .Select(x => new
// {
// x.ProductID,
// x.UnitPrice,
// x.UnitsInStock,
// x.Category.CategoryName,
// x.Supplier.ContactName
// }).ToList();
//-----------------------------------------------------
// order ID si verilen siparişlerin product isimleri ve adeti
//dgvTest.DataSource = db.Order_Details
// .Where(x=> x.OrderID < 10500)
// .Select(x => new
// {
// x.OrderID,
// x.Product.ProductName,
// x.UnitPrice,
// x.Quantity
// }).ToList();
//-----------------------------------------------------
//Category - Product - OrderDetails
//UnitPrice' ı 100 ve 100 den fazla olan kategori adı urun adı orderID
dgvTest.DataSource = db.Categories
.Join(db.Products,
cat => cat.CategoryID,
pro => pro.CategoryID,
(cat, pro) => new { cat, pro })
.Join(db.Order_Details,
catPro => catPro.pro.ProductID,
ord => ord.ProductID,
(catPro, ord) => new { catPro, ord })
.Where(x => x.catPro.pro.UnitPrice >= 100)
.Select(x => new
{
x.catPro.cat.CategoryName,
x.catPro.pro.ProductName,
x.catPro.pro.UnitPrice,
x.ord.OrderID
}).ToList();
//2.Yazım
dgvTest.DataSource = db.Order_Details
.Where(x => x.Product.UnitPrice >= 100)
.Select(x => new
{
x.Product.Category.CategoryName,
x.Product.ProductName,
x.Product.UnitPrice,
x.OrderID
}).ToList();
// Çalışanla amirini Listelet (Lambda tarzı ile)
#endregion
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ConfigMenu : MonoBehaviour
{
public List<GameObject> Buttons;
public GameObject playSub;
private bool PlayIsActive= false;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
public void OnClickPlay()
{
//PlayIsActive = !PlayIsActive;
//playSub.SetActive(PlayIsActive);
if (PlayIsActive == false)
{
playSub.GetComponent<Animator>().SetTrigger("PlayIsActive");
PlayIsActive = true;
}
//if (PlayIsActive == true)
else
{
playSub.GetComponent<Animator>().SetTrigger("PlayIsInactive");
PlayIsActive = false;
}
}
}
|
// --------------------------------------------------------------------------------------------------------------
// <copyright file="RequestResult.cs" company="Tiny开源团队">
// Copyright (c) 2017-2018 Tiny. All rights reserved.
// </copyright>
// <site>http://www.lxking.cn</site>
// <last-editor>ArcherTrister</last-editor>
// <last-date>2019/3/13 21:55:35</last-date>
// --------------------------------------------------------------------------------------------------------------
namespace Tiny.Data
{
/// <summary>
/// 表示接口请求操作结果
/// </summary>
public class RequestResult
{
/// <summary>
/// 初始化一个<see cref="RequestResult"/>类型的新实例
/// </summary>
public RequestResult()
: this(null)
{ }
/// <summary>
/// 初始化一个<see cref="RequestResult"/>类型的新实例
/// </summary>
public RequestResult(string content, RequestResultType type = RequestResultType.Success, object data = null)
: this(content, data, type)
{ }
/// <summary>
/// 初始化一个<see cref="RequestResult"/>类型的新实例
/// </summary>
public RequestResult(string content, object data, RequestResultType type = RequestResultType.Success)
{
Type = type;
Content = content;
Data = data;
}
/// <summary>
/// 获取或设置 Ajax操作结果类型
/// </summary>
public RequestResultType Type { get; set; }
/// <summary>
/// 获取或设置 消息内容
/// </summary>
public string Content { get; set; }
/// <summary>
/// 获取或设置 返回数据
/// </summary>
public object Data { get; set; }
/// <summary>
/// 是否成功
/// </summary>
public bool Successed()
{
return Type == RequestResultType.Success;
}
/// <summary>
/// 是否错误
/// </summary>
public bool Error()
{
return Type == RequestResultType.Error;
}
/// <summary>
/// 成功的AjaxResult
/// </summary>
public static RequestResult Success(object data = null)
{
return new RequestResult("操作执行成功", RequestResultType.Success, data);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Destruction : MonoBehaviour {
public int damage;
void OnTriggerEnter(Collider other){
other.GetComponent<Health> ().IncrementHealth (damage);
Destroy (gameObject);
}
}
|
using System.Collections;
using System.Collections.Generic;
using System.Threading.Tasks;
using UnityEngine;
public class PlayerDeathLoop : MonoBehaviour
{
public GameObject DetonatorPrefab;
public AudioClip DeathSFX;
private GameObject body;
private GameObject respawnPoint;
private AudioSource audioSource;
// Start is called before the first frame update
void Start()
{
this.body = this.gameObject.GetComponentsInChildren<Animator>()[1].gameObject;
this.respawnPoint = GameObject.FindGameObjectWithTag("RespawnPoint");
this.audioSource = gameObject.AddComponent<AudioSource>();
this.audioSource.clip = this.DeathSFX;
this.audioSource.playOnAwake = false;
this.audioSource.loop = false;
this.audioSource.volume = 0.5f;
}
public void KillPlayer()
{
this.audioSource.Play();
Detonator dTemp = (Detonator)this.DetonatorPrefab.GetComponent("Detonator");
GameObject exp = (GameObject)Instantiate(this.DetonatorPrefab, this.transform.position, Quaternion.identity);
dTemp = (Detonator)exp.GetComponent("Detonator");
dTemp.detail = 1.0f;
Destroy(exp, 2);
this.body.SetActive(false);
}
public void RespawnPlayer()
{
this.transform.position = this.respawnPoint.transform.position;
this.body.SetActive(true);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ByteBank
{
class Program
{
static void Main(string[] args)
{
try
{
ContaCorrente conta = new ContaCorrente(1612, 58479);
ContaCorrente conta2 = new ContaCorrente(1612, 14985);
conta.Depositar(200);
conta.Sacar(100);
conta.Transferir(5000,conta2);
}
catch(ArgumentException ex)
{
Console.WriteLine("Argumento com Problema " + ex.ParamName);
Console.WriteLine("Ocorreu um erro do tipo ArgumentException");
Console.WriteLine(ex.Message);
}
catch (SaldoInsuficienteException ex)
{
/*Neste momento é possivel acessaro estado da aplicação no momento da exceção */
Console.WriteLine(ex.Message);
Console.WriteLine("Exceção do tipo saldo insuficiente");
Console.WriteLine("Valor do saldo: " + ex.Saldo);
Console.WriteLine("Valor do saque: " + ex.ValorSaque);
Console.WriteLine(ex.StackTrace);
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
//onsole.WriteLine(conta.Agencia);
//onsole.WriteLine(conta.Numero);
//onsole.WriteLine(ContaCorrente.TaxaDeOperacao);
Console.ReadLine();
}
}
}
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Yeasca.Commande;
using Yeasca.Metier;
namespace Yeasca.TestsUnitaires.Commande.Profiles
{
[TestClass]
public class TestModifierClientCommande
{
[TestInitialize]
public void initialiser()
{
ConfigurationTest.initialiserLesEntrepotsMongo();
}
[TestMethod]
public void TestModifierClientCommande_modifierUnClientAvecLesBonsParamètresEtAuthentifiéFonctionne()
{
ConfigurationTest.initialiserLaSessionHTTP(TypeUtilisateur.Secrétaire);
Client client = ConfigurationTest.créerUnClient();
IModifierClientMessage message = créerUnMessageValide(client.Id.ToString());
ReponseCommande réponse = BusCommande.exécuter(message);
Assert.IsTrue(réponse.Réussite);
}
[TestMethod]
public void TestModifierClientCommande_modifierUnClientAvecLesBonsParamètresSansEtreAuthentifiéEchoue()
{
ConfigurationTest.initialiserLaSessionHTTP(TypeUtilisateur.Inconnu);
Client client = ConfigurationTest.créerUnClient();
IModifierClientMessage message = créerUnMessageValide(client.Id.ToString());
ReponseCommande réponse = BusCommande.exécuter(message);
Assert.IsFalse(réponse.Réussite);
Assert.AreEqual(Ressource.Commandes.ERREUR_AUTH, réponse.Message);
}
[TestMethod]
public void TestModifierClientCommande_modifierUnClientSansLesBonsParamètresEtAuthentifiéEchoue()
{
ConfigurationTest.initialiserLaSessionHTTP(TypeUtilisateur.Huissier);
Client client = ConfigurationTest.créerUnClient();
IModifierClientMessage message = créerUnMessageValide(client.Id.ToString());
message.NomVoie = null;
ReponseCommande réponse = BusCommande.exécuter(message);
Assert.IsFalse(réponse.Réussite);
Assert.IsTrue(réponse.Message.Contains(Ressource.Validation.NOM_VOIE_REQUIS));
}
private IModifierClientMessage créerUnMessageValide(string idClient)
{
IModifierClientMessage message = new ModifierClientMessageTest();
message.IdClient = idClient;
message.Civilité = 0;
message.Nom = "Johanson";
message.Prénom = "Scarlett";
message.NomVoie = "Pouet";
message.CodePostal = "33520";
message.Ville = "Bruges";
return message;
}
}
public class ModifierClientMessageTest : IModifierClientMessage
{
public string IdClient { get; set; }
public int Civilité { get; set; }
public string Nom { get; set; }
public string Prénom { get; set; }
public string DénominationSociété { get; set; }
public string NuméroVoie { get; set; }
public string RépétitionVoie { get; set; }
public string TypeVoie { get; set; }
public string NomVoie { get; set; }
public string ComplémentVoie { get; set; }
public string CodePostal { get; set; }
public string Ville { get; set; }
}
}
|
using System;
using Indico;
using Indico.Request;
using Indico.Entity;
using Newtonsoft.Json.Linq;
using System.Threading.Tasks;
namespace Examples
{
class GraphQL
{
async static Task Main(string[] args)
{
IndicoConfig config = new IndicoConfig(
host: "app.indico.io"
);
IndicoClient client = new IndicoClient(config);
string query = @"
query GetDatasets {
datasets {
id
name
status
rowCount
numModelGroups
modelGroups {
id
}
}
}
";
GraphQLRequest request = client.GraphQLRequest(query, "GetDatasets");
JObject response = await request.Call();
Console.WriteLine(response);
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Entidades
{
public enum NivelUsuario : int
{
Bajo = 0,
Medio = 1,
Alto = 2
}
public class Usuarios
{
[Key]
public int IdUsuario { get; set; }
public string Nombre { get; set; }
public string Usuario { get; set; }
[Browsable(false)]
public string Clave { get; set; }
public DateTime FechaRegistro { get; set; }
public string NivelUsuario { get; set; }
public Usuarios()
{
IdUsuario = 0;
Nombre = string.Empty;
Usuario = string.Empty;
Clave = string.Empty;
FechaRegistro = DateTime.Now;
this.NivelUsuario = "Bajo";
}
public static string Encriptar(string cadenaEncriptada)
{
string resultado = string.Empty;
byte[] encryted = Encoding.Unicode.GetBytes(cadenaEncriptada);
resultado = Convert.ToBase64String(encryted);
return resultado;
}
public static string DesEncriptar(string cadenaDesencriptada)
{
string resultado = string.Empty;
byte[] decryted = Convert.FromBase64String(cadenaDesencriptada);
resultado = System.Text.Encoding.Unicode.GetString(decryted);
return resultado;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CareerCup150.Chapter3_StacksAndQueues
{
/*
* Describe how you could use a single array to implement three stacks.
*/
public class _03_01_ThreeStacksInOneArray
{
const int stackSize = 300;
int[] array = new int[stackSize * 3];
int[] stackStart = new int[] { 0, 0, 0 };
public void Push(int stackNumber, int value)
{
if (stackStart[stackNumber] >= stackSize) throw new Exception("over flowed.");
array[stackNumber * stackSize + stackStart[stackNumber]] = value;
stackStart[stackNumber]++;
}
public int Pop(int stackNumber)
{
if (stackStart[stackNumber] <= 0) throw new Exception("under flow");
int res = array[stackNumber * stackSize + stackStart[stackNumber] - 1];
stackStart[stackNumber]--;
return res;
}
public int Peek(int stackNumber)
{
if (stackStart[stackNumber] <= 0) throw new Exception("under flow");
int res = array[stackNumber * stackSize + stackStart[stackNumber] - 1];
return res;
}
public bool IsEmpty(int stackNumber)
{
return stackStart[stackNumber] == 0;
}
}
}
|
// Log.cs
// Author:
// Stephen Shaw <sshaw@decriptor.com>
// Copyright (c) 2009 Stephen Shaw
using System;
namespace Agora.Logger
{
/// <summary>
/// Different Levels of logging
/// </summary>
public enum Level
{
DEBUG,
INFO,
WARN,
ERROR,
FATAL
}
public static class Logger
{
public static bool Debug { private get; set; }
public static bool Verbose { private get; set; }
public static bool Silent { private get; set; }
public static void Log (Level lvl, string msg)
{
if (lvl == Level.ERROR || lvl == Level.FATAL) {
msg = string.Format ("[{0}]: {1}", Enum.GetName (typeof(Level), lvl), msg);
Console.WriteLine (msg);
return;
}
if (!Silent) {
if (Debug) {
msg = string.Format ("[{0}]: {1}", Enum.GetName (typeof(Level), lvl), msg);
Console.WriteLine (msg);
}
if (Verbose) {
if (lvl != Level.DEBUG) {
msg = string.Format ("[{0}]: {1}", Enum.GetName (typeof(Level), lvl), msg);
Console.WriteLine (msg);
}
}
}
}
public static void CompilerError (int line, string message)
{
Log (Level.ERROR, String.Format ("Line {0}: {1}", line, message));
}
}
}
|
using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.Common;
using RealEstate.BusinessObjects;
using RealEstate.DataAccess;
namespace RealEstate.BusinessLogic
{
public class CategorysBL
{
#region ***** Init Methods *****
CategorysDA objCategorysDA;
public CategorysBL()
{
objCategorysDA = new CategorysDA();
}
#endregion
#region ***** Get Methods *****
/// <summary>
/// Get Categorys by categoryid
/// </summary>
/// <param name="categoryid">CategoryID</param>
/// <returns>Categorys</returns>
public Categorys GetByCategoryID(int categoryid)
{
return objCategorysDA.GetByCategoryID(categoryid);
}
/// <summary>
/// Get all of Categorys
/// </summary>
/// <returns>List<<Categorys>></returns>
public List<Categorys> GetList()
{
string cacheName = "lstCategorys";
if( ServerCache.Get(cacheName) == null )
{
ServerCache.Insert(cacheName, objCategorysDA.GetList(), "Categorys");
}
return (List<Categorys>) ServerCache.Get(cacheName);
}
/// <summary>
/// Get DataSet of Categorys
/// </summary>
/// <returns>DataSet</returns>
public DataSet GetDataSet()
{
string cacheName = "dsCategorys";
if( ServerCache.Get(cacheName) == null )
{
ServerCache.Insert(cacheName, objCategorysDA.GetDataSet(), "Categorys");
}
return (DataSet) ServerCache.Get(cacheName);
}
/// <summary>
/// Get all of Categorys paged
/// </summary>
/// <param name="recperpage">recperpage</param>
/// <param name="pageindex">pageindex</param>
/// <returns>List<<Categorys>></returns>
public List<Categorys> GetListPaged(int recperpage, int pageindex)
{
return objCategorysDA.GetListPaged(recperpage, pageindex);
}
/// <summary>
/// Get DataSet of Categorys paged
/// </summary>
/// <param name="recperpage">recperpage</param>
/// <param name="pageindex">pageindex</param>
/// <returns>DataSet</returns>
public DataSet GetDataSetPaged(int recperpage, int pageindex)
{
return objCategorysDA.GetDataSetPaged(recperpage, pageindex);
}
#endregion
#region ***** Add Update Delete Methods *****
/// <summary>
/// Add a new Categorys within Categorys database table
/// </summary>
/// <param name="obj_categorys">Categorys</param>
/// <returns>key of table</returns>
public int Add(Categorys obj_categorys)
{
ServerCache.Remove("Categorys", true);
return objCategorysDA.Add(obj_categorys);
}
/// <summary>
/// updates the specified Categorys
/// </summary>
/// <param name="obj_categorys">Categorys</param>
/// <returns></returns>
public void Update(Categorys obj_categorys)
{
ServerCache.Remove("Categorys", true);
objCategorysDA.Update(obj_categorys);
}
/// <summary>
/// Delete the specified Categorys
/// </summary>
/// <param name="categoryid">CategoryID</param>
/// <returns></returns>
public void Delete(int categoryid)
{
ServerCache.Remove("Categorys", true);
objCategorysDA.Delete(categoryid);
}
#endregion
}
}
|
using System;
using UnityEngine;
namespace RO.Test
{
public class TestRoam : MonoBehaviour
{
public float DEFAULT_SCREEN_SIZE_INCH = 4f;
public float touchSenseInch = 0.1f;
public float roamSpeed = 0.1f;
private InputHelper[] helpers
{
get;
set;
}
private StateMachine<InputController> controllerStateMachine
{
get;
set;
}
private RoamInputController roamController
{
get;
set;
}
private void Awake()
{
float num = Screen.get_dpi();
if (num == 0f)
{
Vector2 vector = new Vector2((float)Screen.get_width(), (float)Screen.get_height());
num = vector.get_magnitude() / this.DEFAULT_SCREEN_SIZE_INCH;
}
float touchSenseMin = this.touchSenseInch * num;
this.helpers = new InputHelper[]
{
new InputHelper(0)
};
InputHelper[] helpers = this.helpers;
for (int i = 0; i < helpers.Length; i++)
{
InputHelper inputHelper = helpers[i];
inputHelper.touchSenseMin = touchSenseMin;
}
this.controllerStateMachine = new StateMachine<InputController>();
this.roamController = new RoamInputController(this.helpers);
}
private void Start()
{
this.roamController.speed = this.roamSpeed;
this.roamController.target = base.get_transform();
this.controllerStateMachine.ForceSwitch(this.roamController);
}
private void Update()
{
this.controllerStateMachine.Update();
}
}
}
|
using System.Collections;
using UnityEngine;
using UnityStandardAssets.Characters.FirstPerson;
public class Player : AEntity
{
#region Fields
private FirstPersonController controller;
private Energy energy = new Energy(1500, 1500);
private EPlayerState state = EPlayerState.None;
[SerializeField]
private float RUN_LOST_ENERGY_PER_SECONDS = 5.0f;
private GameObject raycastGameObject;
private Transform myTransform;
#endregion
#region Properties
public EPlayerState State
{
get { return state; }
set { state = value; }
}
public Energy Energy
{
get { return energy; }
set { energy = value; }
}
#endregion
#region Unity Methods
void Awake()
{
this.controller = GetComponent<FirstPersonController>();
this.myTransform = transform;
}
public bool IsBlocking()
{
return this.state == EPlayerState.Defend;
}
void Update()
{
this.UpdateMoveSpeed();
this.UpdateDefend();
}
private void UpdateDefend()
{
if (Input.GetMouseButton(1) || Input.GetButton("Parad")) // clic droit
{
this.state = EPlayerState.Defend;
GetComponent<Animation>().CrossFade("Block_Hold");
this.controller.isBlocking = true;
}
else if (this.state == EPlayerState.Defend)
{
this.state = EPlayerState.None;
this.controller.isBlocking = false;
}
GetComponent<MyController>().canUpdate = this.state != EPlayerState.Defend;
}
#endregion
#region Abstract Methods
protected override void EndureDamage(float damageToEndure)
{
float enduredDamage =
damageToEndure *
(EPlayerState.Defend == state ? 0.5f :
1.0f);
this.energy.RemoveEnergy(enduredDamage);
}
#endregion
#region Behaviour Methods
private void UpdateMoveSpeed()
{
bool isRunning = Input.GetKey(KeyCode.LeftShift) ||Input.GetButton("Run");
this.controller.isRunning = isRunning;
if (isRunning)
this.energy.RemoveEnergy(RUN_LOST_ENERGY_PER_SECONDS * Time.deltaTime);
float moveSpeedBlockingFactor = this.state == EPlayerState.Defend ? 0.0f :
1.0f;
GetComponent<Animation>()["Run"].speed = isRunning ? 2.5f * moveSpeedBlockingFactor:
1.5f * moveSpeedBlockingFactor;
this.controller.m_RunSpeed = isRunning ? this.controller.RUNNING_SPEED * moveSpeedBlockingFactor :
this.controller.WALKING_SPEED * moveSpeedBlockingFactor;
}
#endregion
} |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Alfheim.FuzzyLogic.Variables.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Alfheim.FuzzyLogic.Variables.Model;
using Alfheim.FuzzyLogic.Functions;
namespace Alfheim.FuzzyLogic.Variables.Services.Tests
{
[TestClass()]
public class LinguisticVariableServiceTests
{
[TestMethod()]
public void GetLinguisticVariableTypeTest()
{
LinguisticVariable variable = new LinguisticVariable("var", 1, 10);
LinguisticVariable variable2 = new LinguisticVariable("var2", 1, 10);
LinguisticVariable variable3 = new LinguisticVariable("var3", 1, 10);
Term term = TermsFactory.Instance.CreateTermForVariable("term", variable, new TrapezoidalFunction());
Term term2 = TermsFactory.Instance.CreateTermForVariable("term2", variable, new TrapezoidalFunction());
Term term3 = TermsFactory.Instance.CreateTermForVariable("term3", variable2, new TrapezoidalFunction());
Term term4 = TermsFactory.Instance.CreateTermForVariable("term4", variable3, new TrapezoidalFunction());
LinguisticVariableService.Instance.Add(variable, LinguisticVariableType.Input);
LinguisticVariableService.Instance.Add(variable2, LinguisticVariableType.Input);
LinguisticVariableService.Instance.Add(variable3, LinguisticVariableType.Output);
Assert.AreEqual(LinguisticVariableService.Instance.GetLinguisticVariableType(variable), LinguisticVariableType.Input);
Assert.AreEqual(LinguisticVariableService.Instance.GetLinguisticVariableType(variable2), LinguisticVariableType.Input);
Assert.AreEqual(LinguisticVariableService.Instance.GetLinguisticVariableType(variable3), LinguisticVariableType.Output);
}
}
} |
using System.Collections.Generic;
namespace StochSolver
{
class Contractor
{
public string name = "";
public List<double> probabilities = new List<double>();
public bool selected = false;
public Contractor() { }
public Contractor(string name, List<double> probabilities)
{
this.name = name;
this.probabilities = probabilities;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography;
using System.IO;
using ChartServer.server;
namespace ChartServer.util
{
public class AESCryptos
{
public static int AES_KEY_SIZE = 128;
public static string Decrypt(String value,String key)
{
byte[] keyBytes = Convert.FromBase64String(key);
byte[] valueBytes = Convert.FromBase64String(value);
//Server.log("WMS:" + System.Text.Encoding.Default.GetString(keyBytes), Constant.info, Constant.infoColor);
System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged
{
Key = keyBytes,
Mode = System.Security.Cryptography.CipherMode.ECB,
Padding = System.Security.Cryptography.PaddingMode.PKCS7
};
System.Security.Cryptography.ICryptoTransform cTransform = rm.CreateDecryptor();
Byte[] resultArray = cTransform.TransformFinalBlock(valueBytes, 0, valueBytes.Length);
return Encoding.UTF8.GetString(resultArray);
}
public static String AESEncrypt(String value,String key)
{
Byte[] toEncryptArray = Encoding.UTF8.GetBytes(value);
byte[] keyBytes = Convert.FromBase64String(key);
System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged
{
Key = keyBytes,
Mode = System.Security.Cryptography.CipherMode.ECB,
Padding = System.Security.Cryptography.PaddingMode.PKCS7
};
System.Security.Cryptography.ICryptoTransform cTransform = rm.CreateEncryptor();
Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
return Convert.ToBase64String(resultArray, 0, resultArray.Length);
}
public static String generateKey()
{
System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged
{
KeySize = 128,
Mode = System.Security.Cryptography.CipherMode.ECB,
Padding = System.Security.Cryptography.PaddingMode.PKCS7
};
rm.GenerateKey();
return Convert.ToBase64String(rm.Key);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Web.Http;
using System.Web.Routing;
using EP.CursoMvc.Application.Interfaces;
using EP.CursoMvc.Application.ViewModels;
namespace EP.CursoMvc.Services.ClienteAPI.Controllers
{
public class ClientesController : ApiBase
{
private readonly IClienteAppService _clienteAppService;
public ClientesController(IClienteAppService clienteAppService)
{
_clienteAppService = clienteAppService;
}
// GET: api/Clientes
[HttpGet]
public IEnumerable<ClienteViewModel> ObterTodos()
{
return _clienteAppService.ObterAtivos();
}
// GET: api/Clientes/5
public ClienteViewModel Get(Guid id)
{
return _clienteAppService.ObterPorId(id);
}
// POST: api/Clientes
public IHttpActionResult Post([FromBody] ClienteEnderecoViewModel clienteEnderecoViewModel)
{
clienteEnderecoViewModel = _clienteAppService.Adicionar(clienteEnderecoViewModel);
return Response(clienteEnderecoViewModel);
}
// PUT: api/Clientes/5
public IHttpActionResult Put(Guid id, [FromBody]ClienteViewModel clienteViewModel)
{
clienteViewModel = _clienteAppService.Atualizar(clienteViewModel);
return Response(clienteViewModel);
}
// DELETE: api/Clientes/5
public void Delete(Guid id)
{
_clienteAppService.Remover(id);
}
}
}
|
using UnityEngine;
[SLua.CustomLuaClass]
public class OzGameManager : LuaMonoBehaviourBase
{
public static OzGameManager Instance
{
get
{
return OzSingleton.GetSingleTon<OzGameManager>();
}
}
private static string FuncOnApplicationPause = "OnApplicationPause";
private static string FuncOnApplicationQuit = "OnApplicationQuit";
public void Init() { }
protected override void Awake()
{
m_LuaClassName = "game.LuaGameManager";
base.Awake();
}
protected override void OnDestroy()
{
LocalizationImporter.OnDestroy();
base.OnDestroy();
}
private void OnApplicationPause(bool pauseStatus)
{
CallMethod(FuncOnApplicationPause, pauseStatus);
}
private void OnApplicationQuit()
{
CallMethod(FuncOnApplicationQuit);
}
#if UNITY_EDITOR
[SLua.DoNotToLua]
private void SendApplicationPauseMessage(bool isPause)
{
Transform[] transList = GameObject.FindObjectsOfType<Transform>();
for (int i = 0; i < transList.Length; i++)
{
Transform trans = transList[i];
//Note that messages will not be sent to inactive objects
trans.SendMessage("OnApplicationPause", isPause, SendMessageOptions.DontRequireReceiver);
}
}
[SLua.DoNotToLua]
private void SendApplicationFocusMessage(bool isFocus)
{
Transform[] transList = GameObject.FindObjectsOfType<Transform>();
for (int i = 0; i < transList.Length; i++)
{
Transform trans = transList[i];
//Note that messages will not be sent to inactive objects
trans.SendMessage("OnApplicationFocus", isFocus, SendMessageOptions.DontRequireReceiver);
}
}
[SLua.DoNotToLua]
public void SendEnterBackgroundMessage()
{
SendApplicationPauseMessage(true);
SendApplicationFocusMessage(false);
}
[SLua.DoNotToLua]
public void SendEnterForegroundMessage()
{
SendApplicationFocusMessage(true);
SendApplicationPauseMessage(false);
}
#endif
}
|
using System.Text;
using System;
using System.Collections.Generic;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json;
using System.Net.Http;
using System.Drawing;
using System.Collections.ObjectModel;
using System.Xml;
using System.ComponentModel;
using System.Reflection;
namespace LinnworksAPI
{
public class ConfigRuleCollection
{
public ConfigRule Item;
public List<ConfigRule> Items;
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Countdown : MonoBehaviour {
private int CountdownTime = 3;
private int CurrentTime;
[SerializeField] private UnityEngine.UI.Text CountdownText;
public void StartCountdown(){
//GameMgr.PauseGame();
CurrentTime = CountdownTime;
CountdownText.gameObject.SetActive(true);
InvokeRepeating("CountdownOneSecond", 1f, 1f);
}
private void CountdownOneSecond(){
if(CurrentTime > 0){
CountdownText.text = CurrentTime.ToString();
CurrentTime--;
}
else{
CountdownText.text = "Brawl!";
StartCoroutine(HideCountdownText());
RoundReferee.StartRound();
CancelInvoke("CountdownOneSecond");
}
}
IEnumerator HideCountdownText(){
yield return new WaitForSeconds(1f);
CountdownText.gameObject.SetActive(false);
CountdownText.text = "";
}
}
|
using Dock.Model.ReactiveUI.Controls;
using ReactiveUI;
namespace Notepad.ViewModels.Documents
{
public class FileViewModel : Document
{
private string _path = string.Empty;
private string _text = string.Empty;
private string _encoding = string.Empty;
public string Path
{
get => _path;
set => this.RaiseAndSetIfChanged(ref _path, value);
}
public string Text
{
get => _text;
set => this.RaiseAndSetIfChanged(ref _text, value);
}
public string Encoding
{
get => _encoding;
set => this.RaiseAndSetIfChanged(ref _encoding, value);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.